From 02acad47eef27d06fef99da8df58da6fa2ad8368 Mon Sep 17 00:00:00 2001 From: kirpichov Date: Thu, 21 Jan 2016 14:21:32 -0800 Subject: [PATCH 001/751] Fixes a bug in custom unbounded readers Custom unbounded readers are read in bundles of at most 10k elements or 10 seconds. A recent change accidentally removed the 10k element limit. This change reintroduces it and adds a test. The previous test also was passing vacuously because the iteration limit was incorrect (it would always have only one iteration). ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112723469 --- .../sdk/runners/dataflow/CustomSources.java | 19 +++++++++++-------- .../runners/dataflow/CustomSourcesTest.java | 13 ++++++++++++- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java index 5dbeaa05dd..f159f66a85 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java @@ -546,14 +546,16 @@ public double getRemainingParallelism() { } } + // Commit at least once every 10 seconds or 10k records. This keeps the watermark advancing + // smoothly, and ensures that not too much work will have to be reprocessed in the event of + // a crash. + @VisibleForTesting + static final int MAX_UNBOUNDED_BUNDLE_SIZE = 10000; + @VisibleForTesting + static final Duration MAX_UNBOUNDED_BUNDLE_READ_TIME = Duration.standardSeconds(10); + private static class UnboundedReaderIterator extends NativeReader.NativeReaderIterator>> { - // Commit at least once every 10 seconds or 10k records. This keeps the watermark advancing - // smoothly, and ensures that not too much work will have to be reprocessed in the event of - // a crash. - private static final int MAX_BUNDLE_SIZE = 10000; - private static final Duration MAX_BUNDLE_READ_TIME = Duration.standardSeconds(10); - private final UnboundedSource.UnboundedReader reader; private final boolean started; private final Instant endTime; @@ -561,7 +563,7 @@ private static class UnboundedReaderIterator private UnboundedReaderIterator(UnboundedSource.UnboundedReader reader, boolean started) { this.reader = reader; - this.endTime = Instant.now().plus(MAX_BUNDLE_READ_TIME); + this.endTime = Instant.now().plus(MAX_UNBOUNDED_BUNDLE_READ_TIME); this.elemsRead = 0; this.started = started; } @@ -588,7 +590,7 @@ public boolean start() throws IOException { @Override public boolean advance() throws IOException { - if (elemsRead >= MAX_BUNDLE_SIZE + if (elemsRead >= MAX_UNBOUNDED_BUNDLE_SIZE || Instant.now().isAfter(endTime)) { return false; } @@ -598,6 +600,7 @@ public boolean advance() throws IOException { while (true) { try { if (reader.advance()) { + elemsRead++; return true; } } catch (Exception e) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index 15256df634..b4fbb3b24d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -32,6 +32,7 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -632,7 +633,8 @@ public void testReadUnboundedReader() throws Exception { options.setNumWorkers(5); ByteString state = ByteString.EMPTY; - for (int i = 0; i < 100; /* Incremented in inner loop */) { + for (int i = 0; i < 10 * CustomSources.MAX_UNBOUNDED_BUNDLE_SIZE; + /* Incremented in inner loop */) { WindowedValue>> value; // Initialize streaming context with state from previous iteration. @@ -664,6 +666,8 @@ public void testReadUnboundedReader() throws Exception { iterator = reader.iterator(); // Verify data. + Instant beforeReading = Instant.now(); + int numReadOnThisIteration = 0; for (boolean more = iterator.start(); more; more = iterator.advance()) { value = iterator.getCurrent(); assertEquals(KV.of(0, i), value.getValue().getValue()); @@ -673,7 +677,14 @@ public void testReadUnboundedReader() throws Exception { assertThat(value.getWindows(), contains((BoundedWindow) GlobalWindow.INSTANCE)); assertEquals(i, value.getTimestamp().getMillis()); i++; + numReadOnThisIteration++; } + Instant afterReading = Instant.now(); + assertThat( + new Duration(beforeReading, afterReading).getStandardSeconds(), + lessThanOrEqualTo(CustomSources.MAX_UNBOUNDED_BUNDLE_READ_TIME.getStandardSeconds() + 1)); + assertThat( + numReadOnThisIteration, lessThanOrEqualTo(CustomSources.MAX_UNBOUNDED_BUNDLE_SIZE)); // Extract and verify state modifications. context.flushState(); From 4114f629ef939dc265f93a55cb3edc5e05018462 Mon Sep 17 00:00:00 2001 From: Magnus Runesson Date: Sun, 24 Jan 2016 16:33:40 +0100 Subject: [PATCH 002/751] Adapt to be able to upload to maven-central --- contrib/join-library/README.md | 7 +++ contrib/join-library/pom.xml | 54 ++++++++++++++++--- .../dataflow/contrib/joinlibrary/Join.java | 3 +- .../contrib/joinlibrary/InnerJoinTest.java | 6 ++- 4 files changed, 60 insertions(+), 10 deletions(-) diff --git a/contrib/join-library/README.md b/contrib/join-library/README.md index a6e0b73d6c..8cf55108d0 100644 --- a/contrib/join-library/README.md +++ b/contrib/join-library/README.md @@ -22,4 +22,11 @@ Example how to use join-library: PCollection>> joinedPcollection = Join.innerJoin(leftPcollection, rightPcollection); +Join-library can be found on maven-central: + + org.linuxalert.dataflow + google-cloud-dataflow-java-contrib-joinlibrary + 0.0.3 + + Questions or comments: `M.Runesson [at] gmail [dot] com` diff --git a/contrib/join-library/pom.xml b/contrib/join-library/pom.xml index 5e843a20c9..352f198ff8 100644 --- a/contrib/join-library/pom.xml +++ b/contrib/join-library/pom.xml @@ -5,11 +5,19 @@ 4.0.0 - com.google.cloud.dataflow + org.linuxalert.dataflow google-cloud-dataflow-java-contrib-joinlibrary - Join library + Dataflow Join Library Library with generic join functions for Dataflow. - 0.0.2-SNAPSHOT + https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/contrib/join-library + + + Magnus Runesson + M (dot) Runesson (at) gmail (dot) com + https://github.com/mrunesson + + + 0.0.3 jar @@ -20,9 +28,15 @@ + + scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git + scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git + https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/contrib/join-library + + UTF-8 - 0.3.150227 + 1.3.0 @@ -40,7 +54,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.12 + 2.17 ../../checkstyle.xml true @@ -56,6 +70,34 @@ + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + + attach-sources + + jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + + jar + + + + @@ -69,7 +111,7 @@ com.google.guava guava - 18.0 + 19.0 diff --git a/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java b/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java index ad409c7090..81d8a7f9af 100644 --- a/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java +++ b/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java @@ -44,8 +44,7 @@ public class Join { * KV where Key is of type V1 and Value is type V2. */ public static PCollection>> innerJoin( - final PCollection> leftCollection, final PCollection> rightCollection) - { + final PCollection> leftCollection, final PCollection> rightCollection) { Preconditions.checkNotNull(leftCollection); Preconditions.checkNotNull(rightCollection); diff --git a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java b/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java index c077ea5603..839c451950 100644 --- a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java +++ b/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java @@ -53,11 +53,13 @@ public void setup() { public void testJoinOneToOneMapping() { leftListOfKv.add(KV.of("Key1", 5L)); leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p.apply(Create.of(leftListOfKv)); + PCollection> leftCollection = + p.apply("CreateLeft", Create.of(leftListOfKv)); listRightOfKv.add(KV.of("Key1", "foo")); listRightOfKv.add(KV.of("Key2", "bar")); - PCollection> rightCollection = p.apply(Create.of(listRightOfKv)); + PCollection> rightCollection = + p.apply("CreateRight", Create.of(listRightOfKv)); PCollection>> output = Join.innerJoin( leftCollection, rightCollection); From 1c224b6f6eb020daecb47b37b0ca3e49c485c6ae Mon Sep 17 00:00:00 2001 From: Magnus Runesson Date: Mon, 25 Jan 2016 20:31:46 +0100 Subject: [PATCH 003/751] Aditional info to simplify release. --- contrib/join-library/pom.xml | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/contrib/join-library/pom.xml b/contrib/join-library/pom.xml index 352f198ff8..eb12bd00fa 100644 --- a/contrib/join-library/pom.xml +++ b/contrib/join-library/pom.xml @@ -10,6 +10,20 @@ Dataflow Join Library Library with generic join functions for Dataflow. https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/contrib/join-library + + + magru + Magnus Runesson + M (dot) Runesson (at) gmail (dot) com + Linuxalert + http://www.linuxalert.org/ + + Project-Administrator + Developer + + +1 + + Magnus Runesson @@ -98,9 +112,47 @@ + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.3 + true + + ossrh + https://oss.sonatype.org/ + true + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + com.google.cloud.dataflow From 7fbb20600d9dfbc3b493879fe4207ec0107b30eb Mon Sep 17 00:00:00 2001 From: Kris Hildrum Date: Wed, 27 Jan 2016 09:37:56 -0800 Subject: [PATCH 004/751] fix typo --- .../com/google/cloud/dataflow/sdk/util/state/ValueState.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java index 4bed0f88fd..d72c67e22c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java @@ -19,7 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; /** - * sTate holding a single value. + * State holding a single value. * * @param The type of values being stored. */ From 575b7334bbcd32adf7fcda7aeafb5149a9f8512d Mon Sep 17 00:00:00 2001 From: Magnus Runesson Date: Sat, 30 Jan 2016 16:01:20 +0100 Subject: [PATCH 005/751] Fix review comments. --- contrib/join-library/README.md | 1 + contrib/join-library/pom.xml | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/contrib/join-library/README.md b/contrib/join-library/README.md index 8cf55108d0..8e2a011c34 100644 --- a/contrib/join-library/README.md +++ b/contrib/join-library/README.md @@ -23,6 +23,7 @@ Example how to use join-library: Join.innerJoin(leftPcollection, rightPcollection); Join-library can be found on maven-central: + org.linuxalert.dataflow google-cloud-dataflow-java-contrib-joinlibrary diff --git a/contrib/join-library/pom.xml b/contrib/join-library/pom.xml index eb12bd00fa..df39545dac 100644 --- a/contrib/join-library/pom.xml +++ b/contrib/join-library/pom.xml @@ -7,18 +7,18 @@ org.linuxalert.dataflow google-cloud-dataflow-java-contrib-joinlibrary - Dataflow Join Library + Google Cloud Dataflow Join Library Library with generic join functions for Dataflow. https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/contrib/join-library - magru + Google Inc. + http://www.google.com + + Magnus Runesson M (dot) Runesson (at) gmail (dot) com - Linuxalert - http://www.linuxalert.org/ - Project-Administrator Developer +1 @@ -31,7 +31,7 @@ https://github.com/mrunesson - 0.0.3 + 0.0.4 jar @@ -50,7 +50,7 @@ UTF-8 - 1.3.0 + [1.0.0, 2.0.0) From acb83b71f3a6c062a780c5cfba9fd5415468d540 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 25 Jan 2016 22:10:00 -0800 Subject: [PATCH 006/751] Version management Updating version numbers from 1.4.0-SNAPSHOT to 1.5.0-SNAPSHOT ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113022038 --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 60ada167fe..2b8c3d83b8 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.4.0-SNAPSHOT + 1.5.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 42a553aa02..6cb1852562 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.4.0-SNAPSHOT + 1.5.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index fee9e33947..b5b32514dc 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.4.0-SNAPSHOT + 1.5.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index 74bbd56785..3c49657d91 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.4.0-SNAPSHOT + 1.5.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index 3a083ade1e..e182ccabe6 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.4.0-SNAPSHOT + 1.5.0-SNAPSHOT com.google.cloud.dataflow From 96ec971835a0eb8773fbed3f3cfc18a6fe1dcc10 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Tue, 19 Jan 2016 11:41:15 -0800 Subject: [PATCH 007/751] BigQueryTableRowIterator: elide columns with null values As in 6a11a72f, this makes BigQueryIO.Read work in the DirectPipelineRunner as it does in the DataflowPipelineRunner. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112496161 --- .../cloud/dataflow/sdk/util/BigQueryTableRowIterator.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index e0fac614ea..0fc21b93a7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -290,6 +290,14 @@ private TableRow getTypedTableRow(List fields, Map Date: Tue, 19 Jan 2016 14:33:17 -0800 Subject: [PATCH 008/751] Rollback "BigQueryTableRowIterator: elide columns with null values" ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112515243 --- .../cloud/dataflow/sdk/util/BigQueryTableRowIterator.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 0fc21b93a7..e0fac614ea 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -290,14 +290,6 @@ private TableRow getTypedTableRow(List fields, Map Date: Tue, 19 Jan 2016 16:45:57 -0800 Subject: [PATCH 009/751] Deterministically choose freshest aggregations in pipeline results ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112529131 --- .../sdk/runners/dataflow/DataflowMetricUpdateExtractor.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java index 00412e82ff..13016dd493 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java @@ -34,6 +34,7 @@ */ public final class DataflowMetricUpdateExtractor { private static final String STEP_NAME_CONTEXT_KEY = "step"; + private static final String IS_TENTATIVE_KEY = "tentative"; private DataflowMetricUpdateExtractor() { // Do not instantiate. @@ -63,7 +64,10 @@ public static Map fromMetricUpdates(Aggregator Date: Tue, 19 Jan 2016 17:56:20 -0800 Subject: [PATCH 010/751] Split streaming status pages into servlets Also updates /heapz so that it downloads the heapdump rather than just telling you where on the worker it is. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112535088 --- .../worker/StreamingDataflowWorker.java | 221 +++++++----------- .../runners/worker/WindmillStateCache.java | 31 +-- .../worker/status/BaseStatusServlet.java | 60 +++++ .../runners/worker/status/HealthzServlet.java | 40 ++++ .../runners/worker/status/HeapzServlet.java | 97 ++++++++ .../runners/worker/status/ThreadzServlet.java | 55 +++++ .../worker/status/WorkerStatusPages.java | 119 ++++++++++ .../runners/worker/status/package-info.java | 23 ++ .../dataflow/sdk/util/MemoryMonitor.java | 18 +- 9 files changed, 505 insertions(+), 159 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java index 9fa20848f4..94a59691b4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java @@ -25,6 +25,8 @@ import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingInitializer; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; +import com.google.cloud.dataflow.sdk.runners.worker.status.BaseStatusServlet; +import com.google.cloud.dataflow.sdk.runners.worker.status.WorkerStatusPages; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServerStub; import com.google.cloud.dataflow.sdk.util.BoundedQueueExecutor; @@ -44,9 +46,6 @@ import com.google.common.base.Preconditions; import com.google.protobuf.ByteString; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,7 +77,6 @@ import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -95,7 +93,6 @@ public class StreamingDataflowWorker { // prioritization / utilization. static final int MAX_WORK_UNITS_QUEUED = 100; static final long MAX_COMMIT_BYTES = 32 << 20; - static final int DEFAULT_STATUS_PORT = 8081; static final String DEFAULT_WINDMILL_SERVER_CLASS_NAME = "com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServer"; static final int MAX_COMMIT_QUEUE_BYTES = 500 << 20; // 500MB @@ -108,8 +105,6 @@ public class StreamingDataflowWorker { */ private static final long MAX_GET_WORK_ITEMS = 100; - private static final MemoryMonitor memoryMonitor = new MemoryMonitor(); - /** * Indicates that the key token was invalid when data was attempted to be fetched. */ @@ -169,12 +164,6 @@ public static void main(String[] args) throws Exception { if (hostport == null) { throw new Exception("-Dwindmill.hostport must be set to the location of the windmill server"); } - - int statusPort = DEFAULT_STATUS_PORT; - if (System.getProperties().containsKey("status_port")) { - statusPort = Integer.parseInt(System.getProperty("status_port")); - } - String windmillServerClassName = DEFAULT_WINDMILL_SERVER_CLASS_NAME; if (System.getProperties().containsKey("windmill.serverclassname")) { windmillServerClassName = System.getProperty("windmill.serverclassname"); @@ -191,9 +180,9 @@ public static void main(String[] args) throws Exception { StreamingDataflowWorker worker = new StreamingDataflowWorker(mapTasks, windmillServer, options); - worker.start(); - worker.runStatusServer(statusPort); + worker.start(); + worker.startStatusPages(); } /** @@ -309,14 +298,17 @@ public Integer apply(Windmill.WorkItemCommitRequest input) { private StateFetcher stateFetcher; private DataflowWorkerHarnessOptions options; private long clientId; - private Server statusServer; - private final AtomicReference lastException; private final MetricTrackingWindmillServerStub metricTrackingWindmillServer; private Timer globalCountersUpdatesTimer; + private static final MemoryMonitor memoryMonitor = new MemoryMonitor(); + private final AtomicReference lastException = new AtomicReference<>(); + private final UserCodeTimeTracker userCodeTimeTracker = new UserCodeTimeTracker(); private final AtomicInteger nextStateSamplerId = new AtomicInteger(); + private final WorkerStatusPages statusPages = WorkerStatusPages.create(); + public StreamingDataflowWorker( List mapTasks, WindmillServerStub server, DataflowWorkerHarnessOptions options) { this.options = options; @@ -361,7 +353,6 @@ public Thread newThread(Runnable r) { this.running = new AtomicBoolean(); this.stateFetcher = new StateFetcher(metricTrackingWindmillServer); this.clientId = new Random().nextLong(); - this.lastException = new AtomicReference<>(); for (MapTask mapTask : mapTasks) { addComputation(mapTask); @@ -404,14 +395,18 @@ public void run() { reportHarnessStartup(); } + public void startStatusPages() { + statusPages.addPage(new StreamingStatuszServlet()); + statusPages.addPage(stateCache.statusServlet()); + statusPages.start(); + } + public void stop() { try { if (globalCountersUpdatesTimer != null) { globalCountersUpdatesTimer.cancel(); } - if (statusServer != null) { - statusServer.stop(); - } + statusPages.stop(); running.set(false); dispatchThread.join(); workUnitExecutor.shutdown(); @@ -433,18 +428,6 @@ public void stop() { } } - public void runStatusServer(int statusPort) { - statusServer = new Server(statusPort); - statusServer.setHandler(new StatusHandler()); - try { - statusServer.start(); - LOG.info("Status server started on port {}", statusPort); - statusServer.join(); - } catch (Exception e) { - LOG.warn("Status server failed to start: ", e); - } - } - private void addComputation(MapTask mapTask) { String computationId = systemNameToComputationIdMap.containsKey(mapTask.getSystemName()) @@ -997,128 +980,96 @@ public StreamingModeExecutionContext getContext() { } } - private class StatusHandler extends AbstractHandler { + private class StreamingStatuszServlet extends BaseStatusServlet { + + private StreamingStatuszServlet() { + super("statusz"); + } + @Override - public void handle( - String target, Request baseRequest, - HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); - baseRequest.setHandled(true); - PrintWriter responseWriter = response.getWriter(); + PrintWriter writer = response.getWriter(); + writer.println(""); + printHeader(writer); + printResources(writer); + printMetrics(writer); + printLastException(writer); + printSpecs(writer); - responseWriter.println(""); - - if (target.equals("/healthz")) { - responseWriter.println("ok"); - } else if (target.equals("/threadz")) { - printThreads(responseWriter); - } else if (target.equals("/heapz")) { - dumpHeap(responseWriter); - } else if (target.equals("/cachez")) { - stateCache.printDetailedHtml(responseWriter); - } else { - printHeader(responseWriter); - printResources(responseWriter); - printMetrics(responseWriter); - printLastException(responseWriter); - printSpecs(responseWriter); - } - - responseWriter.println(""); + stateCache.printSummaryHtml(writer); + writer.println(""); } - } - private void printHeader(PrintWriter response) { - response.println("

Streaming Worker Harness

"); - response.println("Running: " + running.get() + "
"); - response.println("ID: " + clientId + "
"); - } - - private void printMetrics(PrintWriter response) { - response.println("

Metrics

"); - response.println("Worker Threads: " + workUnitExecutor.getPoolSize() - + "/" + workUnitExecutor.getMaximumPoolSize() + "
"); - response.println("Active Threads: " + workUnitExecutor.getActiveCount() + "
"); - response.println("Work Queue Size: " + workUnitExecutor.getQueue().size() - + "/" + MAX_WORK_UNITS_QUEUED + "
"); - response.print("Commit Queues: ("); - response.print(commitQueue.weight() >> 20); - response.println("MB)
    "); - for (String computation : commitQueue.keySet()) { - response.print("
  • "); - response.print(computation); - response.print(": "); - response.print(commitQueue.queueSize(computation)); - response.println("
  • "); + private void printHeader(PrintWriter response) { + response.println("

    Streaming Worker Harness

    "); + response.println("Running: " + running.get() + "
    "); + response.println("ID: " + clientId + "
    "); } - response.println("
"); - - stateCache.printSummaryHtml(response); - metricTrackingWindmillServer.printHtml(response); + private void printMetrics(PrintWriter response) { + response.println("

Metrics

"); + response.println("Worker Threads: " + workUnitExecutor.getPoolSize() + + "/" + workUnitExecutor.getMaximumPoolSize() + "
"); + response.println("Active Threads: " + workUnitExecutor.getActiveCount() + "
"); + response.println("Work Queue Size: " + workUnitExecutor.getQueue().size() + + "/" + MAX_WORK_UNITS_QUEUED + "
"); + response.print("Commit Queues: ("); + response.print(commitQueue.weight() >> 20); + response.println("MB)
    "); + for (String computation : commitQueue.keySet()) { + response.print("
  • "); + response.print(computation); + response.print(": "); + response.print(commitQueue.queueSize(computation)); + response.println("
  • "); + } + response.println("
"); - response.println("Active Keys:
    "); - for (Map.Entry computationEntry - : activeWorkMap.entrySet()) { - response.print("
  • "); - response.print(computationEntry.getKey()); - response.print(":"); - computationEntry.getValue().printActiveWork(response); - response.println("
  • "); - } - response.println("
"); - } + stateCache.printSummaryHtml(response); - private void printResources(PrintWriter response) { - response.append("

Resources

\n"); - response.append("Memory is " + memoryMonitor.describeMemory() + "
\n"); - } + metricTrackingWindmillServer.printHtml(response); - private void printSpecs(PrintWriter response) { - response.append("

Specs

\n"); - for (Map.Entry entry : instructionMap.entrySet()) { - response.println("

" + entry.getKey() + "

"); - response.print(""); + response.println("Active Keys:
    "); + for (Map.Entry computationEntry + : activeWorkMap.entrySet()) { + response.print("
  • "); + response.print(computationEntry.getKey()); + response.print(":"); + computationEntry.getValue().printActiveWork(response); + response.println("
  • "); + } + response.println("
"); } - } - private void printLastException(PrintWriter response) { - Throwable t = lastException.get(); - if (t != null) { - response.println("

Last Exception

"); - StringWriter writer = new StringWriter(); - t.printStackTrace(new PrintWriter(writer)); - response.println(writer.toString().replace("\t", "  ").replace("\n", "
")); + + private void printResources(PrintWriter response) { + response.append("

Resources

\n"); + response.append("Memory is " + memoryMonitor.describeMemory() + "
\n"); } - } - private void printThreads(PrintWriter response) { - Map stacks = Thread.getAllStackTraces(); - for (Map.Entry entry : stacks.entrySet()) { - Thread thread = entry.getKey(); - response.println("Thread: " + thread + " State: " + thread.getState() + "
"); - for (StackTraceElement element : entry.getValue()) { - response.println("  " + element + "
"); + private void printSpecs(PrintWriter response) { + response.append("

Specs

\n"); + for (Map.Entry entry : instructionMap.entrySet()) { + response.println("

" + entry.getKey() + "

"); + response.print(""); } - response.println("
"); } - } - private void dumpHeap(PrintWriter response) { - try { - String dumpFile = MemoryMonitor.dumpHeap(); - response.println("Dumped heap to " + dumpFile); - } catch (Exception e) { - response.println("Failed to dump heap:
"); - StringWriter writer = new StringWriter(); - e.printStackTrace(new PrintWriter(writer)); - response.println(writer.toString().replace("\t", "  ").replace("\n", "
")); + private void printLastException(PrintWriter response) { + Throwable t = lastException.get(); + if (t != null) { + response.println("

Last Exception

"); + StringWriter writer = new StringWriter(); + t.printStackTrace(new PrintWriter(writer)); + response.println(writer.toString().replace("\t", "  ").replace("\n", "
")); + } } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java index 5eaefa2445..8eb37c3139 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java @@ -15,6 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.worker; +import com.google.cloud.dataflow.sdk.runners.worker.status.BaseStatusServlet; import com.google.cloud.dataflow.sdk.util.Weighted; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; @@ -27,11 +28,16 @@ import com.google.common.cache.Weigher; import com.google.protobuf.ByteString; +import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + /** * Process-wide cache of per-key state. */ @@ -40,13 +46,6 @@ public class WindmillStateCache { private Cache stateCache; private int weight = 0; - private static class CacheWeigher implements Weigher { - @Override - public int weigh(Weighted key, Weighted value) { - return (int) Math.max(key.getWeight() + value.getWeight(), Integer.MAX_VALUE); - } - } - public WindmillStateCache() { final Weigher weigher = Weighers.weightedKeysAndValues(); @@ -282,11 +281,17 @@ public void printSummaryHtml(PrintWriter response) { response.println("
"); } - /** - * Print detailed information about the cache to the given {@link PrintWriter}. - */ - public void printDetailedHtml(PrintWriter response) { - response.println("

Cache Information

"); - printSummaryHtml(response); + + public BaseStatusServlet statusServlet() { + return new BaseStatusServlet("/cachez") { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + + PrintWriter writer = response.getWriter(); + writer.println("

Cache Information

"); + printSummaryHtml(writer); + } + }; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java new file mode 100644 index 0000000000..23245bbab2 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import com.google.common.base.Strings; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Base class for status servlets. + */ +public abstract class BaseStatusServlet extends HttpServlet { + + private final String path; + + protected BaseStatusServlet(String path) { + this.path = path.startsWith("/") ? path : "/" + path; + } + + /** + * Return the path that this servlet should listen on. + */ + public String getPath() { + return path; + } + + /** + * Return the servlet that this path is on, modified to include the specified query + * {@code parameters} if any. + */ + protected String getPath(String parameters) { + if (Strings.isNullOrEmpty(parameters)) { + return path; + } else { + return path + "?" + parameters; + } + } + + @Override + protected abstract void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException; +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java new file mode 100644 index 0000000000..1f7c83c83f --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Respond to /healthz with "ok". + */ +public class HealthzServlet extends BaseStatusServlet { + + public HealthzServlet() { + super("healthz"); + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { + response.setContentType("text/html;charset=utf-8"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().println("ok"); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java new file mode 100644 index 0000000000..363d26fb57 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import com.google.cloud.dataflow.sdk.util.MemoryMonitor; +import com.google.common.io.Files; + +import java.io.File; +import java.io.IOException; + +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ReflectionException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Respond to /heapz with a page allowing downloading of the heap dumps. + * + *

Respond to /heapz?action=download with a download of the actual heap dump. + */ +public class HeapzServlet extends BaseStatusServlet { + + public HeapzServlet() { + super("heapz"); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String action = req.getParameter("action"); + if (action == null || action.isEmpty()) { + resp.setContentType("text/html;charset=utf-8"); + resp.setStatus(HttpServletResponse.SC_OK); + + ServletOutputStream writer = resp.getOutputStream(); + writer.println(""); + writer.println(String.format( + "Click here to download heap dump", getPath("action=download"))); + writer.println(""); + return; + } else if ("download".equals(action)) { + doDownload(resp); + } + } + + private void doDownload(HttpServletResponse resp) throws IOException { + File file; + + try { + file = MemoryMonitor.dumpHeap(); + } catch (MalformedObjectNameException + | InstanceNotFoundException | ReflectionException | MBeanException e) { + resp.setContentType("text/html;charset=utf-8"); + resp.setStatus(HttpServletResponse.SC_OK); + + ServletOutputStream writer = resp.getOutputStream(); + writer.println("\nFailed to dump heap:
\n

");
+      writer.println(e.toString());
+      writer.println("
\n"); + return; + } + + resp.setContentType("application/octet-stream"); + resp.setContentLength((int) file.length()); + resp.setHeader( + "Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); + + try { + Files.copy(file, resp.getOutputStream()); + resp.setStatus(HttpServletResponse.SC_OK); + } catch (IOException e) { + resp.reset(); + resp.setContentType("text/html;charset=utf-8"); + ServletOutputStream writer = resp.getOutputStream(); + writer.println("\nFailed to dump heap:
\n
\n");
+      writer.println(e.toString());
+      writer.println("
\n"); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java new file mode 100644 index 0000000000..0c8dc6a8aa --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Respond to /threadz with the stack traces of all running threads. + */ +class ThreadzServlet extends BaseStatusServlet { + + public ThreadzServlet() { + super("threadz"); + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { + response.setContentType("text/html;charset=utf-8"); + response.setStatus(HttpServletResponse.SC_OK); + + PrintWriter writer = response.getWriter(); + writer.println(""); + + Map stacks = Thread.getAllStackTraces(); + for (Map.Entry entry : stacks.entrySet()) { + Thread thread = entry.getKey(); + writer.println("Thread: " + thread + " State: " + thread.getState() + "
"); + for (StackTraceElement element : entry.getValue()) { + writer.println("  " + element + "
"); + } + writer.println("
"); + } + writer.println(""); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java new file mode 100644 index 0000000000..db04ddbe57 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Manages the server providing the worker status pages. + */ +public class WorkerStatusPages { + + private static final Logger LOG = LoggerFactory.getLogger(WorkerStatusPages.class); + + private static final int DEFAULT_STATUS_PORT = 8081; + + private final Server statusServer; + private final ServletHandler servletHandler = new ServletHandler(); + + private WorkerStatusPages(int statusPort) { + this.statusServer = new Server(statusPort); + this.statusServer.setHandler(servletHandler); + + // Install the default servlets (threadz, healthz, heapz) + addPage(new ThreadzServlet()); + addPage(new HealthzServlet()); + addPage(new HeapzServlet()); + } + + public static WorkerStatusPages create() { + int statusPort = DEFAULT_STATUS_PORT; + if (System.getProperties().containsKey("status_port")) { + statusPort = Integer.parseInt(System.getProperty("status_port")); + } + return new WorkerStatusPages(statusPort); + } + + /** Start the server. */ + public void start() { + if (statusServer.isStarted()) { + LOG.warn("Status server already started on port {}", statusServer.getURI().getPort()); + return; + } + + try { + addPage(new RedirectToStatusz404Handler()); + statusServer.start(); + + LOG.info("Status server started on port {}", statusServer.getURI().getPort()); + statusServer.join(); + } catch (Exception e) { + LOG.warn("Status server failed to start: ", e); + } + } + + /** Stop the server. */ + public void stop() { + try { + statusServer.stop(); + } catch (Exception e) { + LOG.warn("Status server failed to stop: ", e); + } + } + + /** + * Add a status servlet. + */ + public void addPage(BaseStatusServlet servlet) { + ServletHolder holder = new ServletHolder(); + holder.setServlet(servlet); + servletHandler.addServletWithMapping(holder, servlet.getPath()); + } + + /** + * Redirect missing pages to /statusz. + */ + private static class RedirectToStatusz404Handler extends BaseStatusServlet { + + protected RedirectToStatusz404Handler() { + super("/*"); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.setContentType("text/html;charset=utf-8"); + resp.setStatus(HttpServletResponse.SC_NOT_FOUND); + + PrintWriter writer = resp.getWriter(); + writer.println(""); + writer.println("404 Not Found. Try /statusz"); + writer.println(""); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java new file mode 100644 index 0000000000..9138c155a6 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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. + */ + +/** + * Server and tools for the Worker Status pages. + */ +@ParametersAreNonnullByDefault +package com.google.cloud.dataflow.sdk.runners.worker.status; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java index 7a7c7d974a..2704223a78 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java @@ -286,7 +286,7 @@ private void updateData(long now, long lastTimeWokeUp) { * * @return The name of the file the heap was dumped to. */ - private String tryToDumpHeap() { + private File tryToDumpHeap() { // clearing this list should "release" some memory // that will be needed to dump the heap reservedForDumpingHeap = null; @@ -340,7 +340,7 @@ public void run() { if (shutDownAfterNumGCThrashing > 0 && (currentThrashingCount >= shutDownAfterNumGCThrashing)) { - String heapDumpFile = tryToDumpHeap(); + File heapDumpFile = tryToDumpHeap(); LOG.error( "Shutting down JVM after {} consecutive periods of measured GC thrashing. " + "Memory is {}. Heap dump written to {}", @@ -401,16 +401,12 @@ private static String getLoggingDir() { /** * Dump the current heap profile to a file and return its name. - * - * @throws MalformedObjectNameException - * @throws MBeanException - * @throws ReflectionException - * @throws InstanceNotFoundException */ - public static String dumpHeap() throws MalformedObjectNameException, InstanceNotFoundException, - ReflectionException, MBeanException { + public static File dumpHeap() throws + MalformedObjectNameException, InstanceNotFoundException, ReflectionException, MBeanException { boolean liveObjectsOnly = true; - String fileName = String.format("%s/heap_dump_%d", getLoggingDir(), System.currentTimeMillis()); + String fileName = String.format( + "%s/heap_dump_%d.hprof", getLoggingDir(), System.currentTimeMillis()); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName oname = new ObjectName("com.sun.management:type=HotSpotDiagnostic"); @@ -418,6 +414,6 @@ public static String dumpHeap() throws MalformedObjectNameException, InstanceNot String[] signatures = {"java.lang.String", boolean.class.getName()}; mbs.invoke(oname, "dumpHeap", parameters, signatures); - return fileName; + return new File(fileName); } } From 6db9723e77066c34f85b623b8dbe398ffa2883c3 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 19 Jan 2016 21:32:37 -0800 Subject: [PATCH 011/751] Expose dependent realtime watermark via Windmill protos ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112546981 --- sdk/src/main/proto/windmill.proto | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/src/main/proto/windmill.proto b/sdk/src/main/proto/windmill.proto index cc24ab322d..8120ec8571 100644 --- a/sdk/src/main/proto/windmill.proto +++ b/sdk/src/main/proto/windmill.proto @@ -150,6 +150,8 @@ message ComputationWorkItems { required string computation_id = 1; repeated WorkItem work = 2; optional int64 input_data_watermark = 3 [default=-0x8000000000000000]; + optional int64 dependent_realtime_input_watermark = 4 + [default = -0x8000000000000000]; } //////////////////////////////////////////////////////////////////////////////// From 219d22a3ab9c1928c8334573c650390c4a785452 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 20 Jan 2016 09:10:56 -0800 Subject: [PATCH 012/751] Add ByteStringCoder, a coder for ByteStrings This is a deterministic coder for ByteString. In the wholeStream context, it simply writes the string. Otherwise, it writes the string delimited with its length (encoded as a VarInt). ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112586805 --- .../dataflow/sdk/coders/ByteStringCoder.java | 106 +++++++++++++++ .../dataflow/sdk/coders/CoderRegistry.java | 2 + .../sdk/coders/ByteStringCoderTest.java | 121 ++++++++++++++++++ 3 files changed, 229 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java new file mode 100644 index 0000000000..b7c1a3cd0a --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders; + +import com.google.cloud.dataflow.sdk.util.VarInt; +import com.google.common.io.ByteStreams; +import com.google.protobuf.ByteString; + +import com.fasterxml.jackson.annotation.JsonCreator; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * A {@link Coder} for {@link ByteString} objects based on their encoded Protocol Buffer form. + * + *

When this code is used in a nested {@link Coder.Context}, the serialized {@link ByteString} + * objects are first delimited by their size. + */ +public class ByteStringCoder extends AtomicCoder { + + @JsonCreator + public static ByteStringCoder of() { + return INSTANCE; + } + + /***************************/ + + private static final ByteStringCoder INSTANCE = new ByteStringCoder(); + + private ByteStringCoder() {} + + @Override + public void encode(ByteString value, OutputStream outStream, Context context) + throws IOException, CoderException { + if (value == null) { + throw new CoderException("cannot encode a null ByteString"); + } + + if (!context.isWholeStream) { + // ByteString is not delimited, so write its size before its contents. + VarInt.encode(value.size(), outStream); + } + value.writeTo(outStream); + } + + @Override + public ByteString decode(InputStream inStream, Context context) throws IOException { + if (context.isWholeStream) { + return ByteString.readFrom(inStream); + } + + int size = VarInt.decodeInt(inStream); + // ByteString reads to the end of the input stream, so give it a limited stream of exactly + // the right length. Also set its chunk size so that the ByteString will contain exactly + // one chunk. + return ByteString.readFrom(ByteStreams.limit(inStream, size), size); + } + + @Override + protected long getEncodedElementByteSize(ByteString value, Context context) throws Exception { + int size = value.size(); + + if (context.isWholeStream) { + return size; + } + return VarInt.getLength(size) + size; + } + + /** + * {@inheritDoc} + * + *

Returns true; the encoded output of two invocations of {@link ByteStringCoder} in the same + * {@link Coder.Context} will be identical if and only if the original {@link ByteString} objects + * are equal according to {@link Object#equals}. + */ + @Override + public boolean consistentWithEquals() { + return true; + } + + /** + * {@inheritDoc} + * + *

Returns true. {@link ByteString#size} returns the size of an array and a {@link VarInt}. + */ + @Override + public boolean isRegisterByteSizeObserverCheap(ByteString value, Context context) { + return true; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java index a5f77b9429..1ef09712d4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java @@ -27,6 +27,7 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; +import com.google.protobuf.ByteString; import org.joda.time.Instant; import org.slf4j.Logger; @@ -89,6 +90,7 @@ public CoderRegistry() { */ public void registerStandardCoders() { registerCoder(Byte.class, ByteCoder.class); + registerCoder(ByteString.class, ByteStringCoder.class); registerCoder(Double.class, DoubleCoder.class); registerCoder(Instant.class, InstantCoder.class); registerCoder(Integer.class, VarIntCoder.class); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java new file mode 100644 index 0000000000..debae71fdd --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.coders.Coder.Context; +import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Arrays; +import java.util.List; + +/** + * Test case for {@link ByteStringCoder}. + */ +@RunWith(JUnit4.class) +public class ByteStringCoderTest { + + private static final ByteStringCoder TEST_CODER = ByteStringCoder.of(); + + private static final List TEST_STRING_VALUES = Arrays.asList( + "", "a", "13", "hello", + "a longer string with spaces and all that", + "a string with a \n newline", + "???????????????"); + private static final ImmutableList TEST_VALUES; + static { + ImmutableList.Builder builder = ImmutableList.builder(); + for (String s : TEST_STRING_VALUES) { + builder.add(ByteString.copyFrom(s.getBytes())); + } + TEST_VALUES = builder.build(); + } + + /** + * Generated data to check that the wire format has not changed. To regenerate, see + * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. + */ + private static final List TEST_ENCODINGS = Arrays.asList( + "", + "YQ", + "MTM", + "aGVsbG8", + "YSBsb25nZXIgc3RyaW5nIHdpdGggc3BhY2VzIGFuZCBhbGwgdGhhdA", + "YSBzdHJpbmcgd2l0aCBhIAogbmV3bGluZQ", + "Pz8_Pz8_Pz8_Pz8_Pz8_"); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testDecodeEncodeEqualInAllContexts() throws Exception { + for (ByteString value : TEST_VALUES) { + CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); + } + } + + @Test + public void testWireFormatEncode() throws Exception { + CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); + } + + @Test + public void testCoderDeterministic() throws Throwable { + TEST_CODER.verifyDeterministic(); + } + + @Test + public void testConsistentWithEquals() { + assertTrue(TEST_CODER.consistentWithEquals()); + } + + @Test + public void testEncodeNullThrowsCoderException() throws Exception { + thrown.expect(CoderException.class); + thrown.expectMessage("cannot encode a null ByteString"); + + CoderUtils.encodeToBase64(TEST_CODER, null); + } + + @Test + public void testNestedCoding() throws Throwable { + Coder> listCoder = ListCoder.of(TEST_CODER); + CoderProperties.coderDecodeEncodeContentsEqual(listCoder, TEST_VALUES); + CoderProperties.coderDecodeEncodeContentsInSameOrder(listCoder, TEST_VALUES); + } + + @Test + public void testEncodedElementByteSizeInAllContexts() throws Throwable { + for (Context context : CoderProperties.ALL_CONTEXTS) { + for (ByteString value : TEST_VALUES) { + byte[] encoded = CoderUtils.encodeToByteArray(TEST_CODER, value, context); + assertEquals(encoded.length, TEST_CODER.getEncodedElementByteSize(value, context)); + } + } + } +} From 1e5524a7f5d0d774488cb0206ea6433085461775 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 20 Jan 2016 09:13:48 -0800 Subject: [PATCH 013/751] CustomSources: remove dead code ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112587034 --- .../sdk/runners/dataflow/CustomSources.java | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java index f159f66a85..44fbc55fce 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java @@ -483,17 +483,12 @@ public void close() throws IOException { @Override public NativeReader.Progress getProgress() { - if (reader instanceof BoundedSource.BoundedReader) { - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - Double fractionConsumed = reader.getFractionConsumed(); - if (fractionConsumed != null) { - progress.setFractionConsumed(fractionConsumed); - } - return SourceTranslationUtils.cloudProgressToReaderProgress(progress); - } else { - // Progress estimation for unbounded sources not yet supported. - return null; + ApproximateReportedProgress progress = new ApproximateReportedProgress(); + Double fractionConsumed = reader.getFractionConsumed(); + if (fractionConsumed != null) { + progress.setFractionConsumed(fractionConsumed); } + return SourceTranslationUtils.cloudProgressToReaderProgress(progress); } @Override From 7509f8737a37a84128a74f22b61797141ee782fe Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 20 Jan 2016 10:58:41 -0800 Subject: [PATCH 014/751] Ignore Eclipse project files in root .gitignore Users who check out and edit the SDK in Eclipse should use m2e's Eclipse import wizard, and should not want to commit their actual project configurations. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112597945 --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 52aee3fa88..0ba351f6d6 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,11 @@ target/ *.ipr *.iws +# Ignore Eclipse files. +.classpath +.project +.settings/ + # The build process generates the dependency-reduced POM, but it shouldn't be # committed. dependency-reduced-pom.xml From c14418013e13fa0bf952109ad835a365881d4816 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 20 Jan 2016 11:00:36 -0800 Subject: [PATCH 015/751] BigQueryTableRowIterator: elide columns with null values As in 6a11a72f, this makes BigQueryIO.Read work in the DirectPipelineRunner as it does in the DataflowPipelineRunner. This reverts "Rollback "BigQueryTableRowIterator: elide columns with null values"" ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112598156 --- .../cloud/dataflow/sdk/util/BigQueryTableRowIterator.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index e0fac614ea..0fc21b93a7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -290,6 +290,14 @@ private TableRow getTypedTableRow(List fields, Map Date: Wed, 20 Jan 2016 11:17:05 -0800 Subject: [PATCH 016/751] Split out StatusDataProviders ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112600047 --- .../worker/StreamingDataflowWorker.java | 140 +++++++----------- .../runners/worker/WindmillStateCache.java | 10 +- .../status/LastExceptionDataProvider.java | 46 ++++++ .../worker/status/StatusDataProvider.java | 25 ++++ .../runners/worker/status/StatuszServlet.java | 68 +++++++++ .../worker/status/WorkerStatusPages.java | 42 +++--- .../dataflow/sdk/util/MemoryMonitor.java | 39 +++-- 7 files changed, 246 insertions(+), 124 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java index 94a59691b4..c9f3485b15 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java @@ -25,7 +25,8 @@ import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingInitializer; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; -import com.google.cloud.dataflow.sdk.runners.worker.status.BaseStatusServlet; +import com.google.cloud.dataflow.sdk.runners.worker.status.LastExceptionDataProvider; +import com.google.cloud.dataflow.sdk.runners.worker.status.StatusDataProvider; import com.google.cloud.dataflow.sdk.runners.worker.status.WorkerStatusPages; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServerStub; @@ -52,7 +53,6 @@ import java.io.IOException; import java.io.PrintWriter; -import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; @@ -74,11 +74,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; /** * Implements a Streaming Dataflow worker. @@ -302,7 +299,6 @@ public Integer apply(Windmill.WorkItemCommitRequest input) { private Timer globalCountersUpdatesTimer; private static final MemoryMonitor memoryMonitor = new MemoryMonitor(); - private final AtomicReference lastException = new AtomicReference<>(); private final UserCodeTimeTracker userCodeTimeTracker = new UserCodeTimeTracker(); private final AtomicInteger nextStateSamplerId = new AtomicInteger(); @@ -396,8 +392,16 @@ public void run() { } public void startStatusPages() { - statusPages.addPage(new StreamingStatuszServlet()); - statusPages.addPage(stateCache.statusServlet()); + statusPages.addServlet(stateCache.statusServlet()); + + statusPages.addStatusDataProvider("harness", "Harness", new HarnessDataProvider()); + statusPages.addStatusDataProvider("resources", "Resources", memoryMonitor); + statusPages.addStatusDataProvider("metrics", "Metrics", new MetricsDataProvider()); + statusPages.addStatusDataProvider( + "exception", "Last Exception", new LastExceptionDataProvider()); + statusPages.addStatusDataProvider("specs", "Specs", new SpecsDataProvider()); + statusPages.addStatusDataProvider("cache", "State Cache", stateCache); + statusPages.start(); } @@ -674,7 +678,7 @@ public void run() { computation, work.getKey().toStringUtf8()); LOG.error("\nError: ", t); - lastException.set(t); + LastExceptionDataProvider.reportException(t); LOG.debug("Failed work: {}", work); if (reportFailure(computation, work, t)) { // Try again, after some delay and at the end of the queue to avoid a tight loop. @@ -980,96 +984,58 @@ public StreamingModeExecutionContext getContext() { } } - private class StreamingStatuszServlet extends BaseStatusServlet { - - private StreamingStatuszServlet() { - super("statusz"); - } - + private class HarnessDataProvider implements StatusDataProvider { @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws IOException { - - response.setContentType("text/html;charset=utf-8"); - response.setStatus(HttpServletResponse.SC_OK); - - PrintWriter writer = response.getWriter(); - writer.println(""); - printHeader(writer); - printResources(writer); - printMetrics(writer); - printLastException(writer); - printSpecs(writer); - - stateCache.printSummaryHtml(writer); - writer.println(""); + public void appendSummaryHtml(PrintWriter writer) { + writer.println("Running: " + running.get() + "
"); + writer.println("ID: " + clientId + "
"); } + } - private void printHeader(PrintWriter response) { - response.println("

Streaming Worker Harness

"); - response.println("Running: " + running.get() + "
"); - response.println("ID: " + clientId + "
"); + private class SpecsDataProvider implements StatusDataProvider { + @Override + public void appendSummaryHtml(PrintWriter writer) { + for (Map.Entry entry : instructionMap.entrySet()) { + writer.println("

" + entry.getKey() + "

"); + writer.print(""); + } } + } - private void printMetrics(PrintWriter response) { - response.println("

Metrics

"); - response.println("Worker Threads: " + workUnitExecutor.getPoolSize() - + "/" + workUnitExecutor.getMaximumPoolSize() + "
"); - response.println("Active Threads: " + workUnitExecutor.getActiveCount() + "
"); - response.println("Work Queue Size: " + workUnitExecutor.getQueue().size() + private class MetricsDataProvider implements StatusDataProvider { + @Override + public void appendSummaryHtml(PrintWriter writer) { + writer.println("Worker Threads: " + workUnitExecutor.getPoolSize() + + "/" + workUnitExecutor.getMaximumPoolSize() + "
"); + writer.println("Active Threads: " + workUnitExecutor.getActiveCount() + "
"); + writer.println("Work Queue Size: " + workUnitExecutor.getQueue().size() + "/" + MAX_WORK_UNITS_QUEUED + "
"); - response.print("Commit Queues: ("); - response.print(commitQueue.weight() >> 20); - response.println("MB)
    "); + writer.print("Commit Queues: ("); + writer.print(commitQueue.weight() >> 20); + writer.println("MB)
      "); for (String computation : commitQueue.keySet()) { - response.print("
    • "); - response.print(computation); - response.print(": "); - response.print(commitQueue.queueSize(computation)); - response.println("
    • "); + writer.print("
    • "); + writer.print(computation); + writer.print(": "); + writer.print(commitQueue.queueSize(computation)); + writer.println("
    • "); } - response.println("
    "); - - stateCache.printSummaryHtml(response); - - metricTrackingWindmillServer.printHtml(response); + writer.println("
"); - response.println("Active Keys:
    "); + writer.println("Active Keys:
      "); for (Map.Entry computationEntry - : activeWorkMap.entrySet()) { - response.print("
    • "); - response.print(computationEntry.getKey()); - response.print(":"); - computationEntry.getValue().printActiveWork(response); - response.println("
    • "); - } - response.println("
    "); - } - - - private void printResources(PrintWriter response) { - response.append("

    Resources

    \n"); - response.append("Memory is " + memoryMonitor.describeMemory() + "
    \n"); - } - - private void printSpecs(PrintWriter response) { - response.append("

    Specs

    \n"); - for (Map.Entry entry : instructionMap.entrySet()) { - response.println("

    " + entry.getKey() + "

    "); - response.print(""); + : activeWorkMap.entrySet()) { + writer.print("
  • "); + writer.print(computationEntry.getKey()); + writer.print(":"); + computationEntry.getValue().printActiveWork(writer); + writer.println("
  • "); } - } + writer.println("
"); - private void printLastException(PrintWriter response) { - Throwable t = lastException.get(); - if (t != null) { - response.println("

Last Exception

"); - StringWriter writer = new StringWriter(); - t.printStackTrace(new PrintWriter(writer)); - response.println(writer.toString().replace("\t", "  ").replace("\n", "
")); - } + metricTrackingWindmillServer.printHtml(writer); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java index 8eb37c3139..b50be91226 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.worker; import com.google.cloud.dataflow.sdk.runners.worker.status.BaseStatusServlet; +import com.google.cloud.dataflow.sdk.runners.worker.status.StatusDataProvider; import com.google.cloud.dataflow.sdk.util.Weighted; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; @@ -41,7 +42,7 @@ /** * Process-wide cache of per-key state. */ -public class WindmillStateCache { +public class WindmillStateCache implements StatusDataProvider { private Cache stateCache; private int weight = 0; @@ -270,7 +271,8 @@ private static class WeightedValue { /** * Print summary statistics of the cache to the given {@link PrintWriter}. */ - public void printSummaryHtml(PrintWriter response) { + @Override + public void appendSummaryHtml(PrintWriter response) { response.println("Cache Stats:
"); response.println( ""); @@ -290,8 +292,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) PrintWriter writer = response.getWriter(); writer.println("

Cache Information

"); - printSummaryHtml(writer); + appendSummaryHtml(writer); } }; } + + } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java new file mode 100644 index 0000000000..00df485ae2 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import java.io.PrintWriter; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Capture the last exception thrown during processing, and display that on the statusz page. + */ +public class LastExceptionDataProvider implements StatusDataProvider { + + private static final AtomicReference lastException = new AtomicReference<>(); + + /** + * Report an exception to the exception data provider. + */ + public static void reportException(Throwable t) { + lastException.set(t); + } + + @Override + public void appendSummaryHtml(PrintWriter writer) { + Throwable t = lastException.get(); + if (t == null) { + writer.println("None
"); + } else { + writer.println("
");
+      t.printStackTrace(writer);
+      writer.println("
"); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java new file mode 100644 index 0000000000..91e962d331 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import java.io.PrintWriter; + +/** + * Interface for providing information to the /statusz page. + */ +public interface StatusDataProvider { + void appendSummaryHtml(PrintWriter writer); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java new file mode 100644 index 0000000000..78bf91ae27 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.LinkedHashMap; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * General servlet for providing a bunch of information on the statusz page. + */ +public class StatuszServlet extends BaseStatusServlet { + + private static class DataProviderInfo { + private final String longName; + private final StatusDataProvider dataProvider; + + public DataProviderInfo(String longName, StatusDataProvider dataProvider) { + this.longName = longName; + this.dataProvider = dataProvider; + } + } + + private LinkedHashMap dataProviders = new LinkedHashMap<>(); + + public StatuszServlet() { + super("statusz"); + } + + public void addDataProvider(String shortName, String longName, StatusDataProvider provider) { + dataProviders.put(shortName, new DataProviderInfo(longName, provider)); + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + PrintWriter writer = response.getWriter(); + writer.println(""); + + writer.println("

Worker Harness

"); + + for (DataProviderInfo info : dataProviders.values()) { + writer.print("

"); + writer.print(info.longName); + writer.println("

"); + + info.dataProvider.appendSummaryHtml(writer); + } + writer.println(""); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java index db04ddbe57..f383b8e2e1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java @@ -23,7 +23,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; -import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -39,16 +38,18 @@ public class WorkerStatusPages { private static final int DEFAULT_STATUS_PORT = 8081; private final Server statusServer; + private final StatuszServlet statuszServlet = new StatuszServlet(); private final ServletHandler servletHandler = new ServletHandler(); private WorkerStatusPages(int statusPort) { this.statusServer = new Server(statusPort); this.statusServer.setHandler(servletHandler); - // Install the default servlets (threadz, healthz, heapz) - addPage(new ThreadzServlet()); - addPage(new HealthzServlet()); - addPage(new HeapzServlet()); + // Install the default servlets (threadz, healthz, heapz, statusz) + addServlet(new ThreadzServlet()); + addServlet(new HealthzServlet()); + addServlet(new HeapzServlet()); + addServlet(statuszServlet); } public static WorkerStatusPages create() { @@ -67,7 +68,7 @@ public void start() { } try { - addPage(new RedirectToStatusz404Handler()); + addServlet(new RedirectToStatusz404Handler()); statusServer.start(); LOG.info("Status server started on port {}", statusServer.getURI().getPort()); @@ -89,31 +90,34 @@ public void stop() { /** * Add a status servlet. */ - public void addPage(BaseStatusServlet servlet) { + public void addServlet(BaseStatusServlet servlet) { ServletHolder holder = new ServletHolder(); holder.setServlet(servlet); servletHandler.addServletWithMapping(holder, servlet.getPath()); } /** - * Redirect missing pages to /statusz. + * Add data to the main statusz servlet. + */ + public void addStatusDataProvider( + String shortName, String longName, StatusDataProvider dataProvider) { + statuszServlet.addDataProvider(shortName, longName, dataProvider); + } + + /** + * Redirect all invalid pages to /statusz. */ private static class RedirectToStatusz404Handler extends BaseStatusServlet { - protected RedirectToStatusz404Handler() { - super("/*"); + public RedirectToStatusz404Handler() { + super("*"); } @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - resp.setContentType("text/html;charset=utf-8"); - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - - PrintWriter writer = resp.getWriter(); - writer.println(""); - writer.println("404 Not Found. Try /statusz"); - writer.println(""); + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + response.sendRedirect("/statusz"); } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java index 2704223a78..78df47ad5d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkState; +import com.google.cloud.dataflow.sdk.runners.worker.status.StatusDataProvider; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.AtomicDouble; @@ -25,6 +26,7 @@ import org.slf4j.LoggerFactory; import java.io.File; +import java.io.PrintWriter; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.ArrayDeque; @@ -60,7 +62,7 @@ * thrashing count is met. A heap dump is made before shutdown. * */ -public class MemoryMonitor implements Runnable { +public class MemoryMonitor implements Runnable, StatusDataProvider { private static final Logger LOG = LoggerFactory.getLogger(MemoryMonitor.class); /** Directory to hold heap dumps if not overridden. */ @@ -298,20 +300,6 @@ private File tryToDumpHeap() { } } - /** - * Return a string describing the current memory state of the server. - */ - public String describeMemory() { - Runtime runtime = Runtime.getRuntime(); - long maxMemory = runtime.maxMemory(); - long totalMemory = runtime.totalMemory(); - long usedMemory = totalMemory - runtime.freeMemory(); - return String.format( - "used/total/max = %d/%d/%d MB, GC last/max = %.2f/%.2f %%, #pushbacks=%d, gc thrashing=%s", - usedMemory >> 20, totalMemory >> 20, maxMemory >> 20, lastMeasuredGCPercentage.get(), - maxGCPercentage.get(), numPushbacks.get(), isThrashing.get()); - } - /** * Runs this thread. */ @@ -416,4 +404,25 @@ public static File dumpHeap() throws return new File(fileName); } + + /** + * Return a string describing the current memory state of the server. + */ + private String describeMemory() { + Runtime runtime = Runtime.getRuntime(); + long maxMemory = runtime.maxMemory(); + long totalMemory = runtime.totalMemory(); + long usedMemory = totalMemory - runtime.freeMemory(); + return String.format( + "used/total/max = %d/%d/%d MB, GC last/max = %.2f/%.2f %%, #pushbacks=%d, gc thrashing=%s", + usedMemory >> 20, totalMemory >> 20, maxMemory >> 20, lastMeasuredGCPercentage.get(), + maxGCPercentage.get(), numPushbacks.get(), isThrashing.get()); + } + + @Override + public void appendSummaryHtml(PrintWriter writer) { + writer.print("Memory: "); + writer.print(describeMemory()); + writer.println("
"); + } } From 7248ecfa70b9cdaa6b3dedd9a15231bf60b64b0f Mon Sep 17 00:00:00 2001 From: millsd Date: Wed, 20 Jan 2016 13:14:11 -0800 Subject: [PATCH 017/751] Proto changes for multi-worker support. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112612082 --- sdk/src/main/proto/windmill.proto | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sdk/src/main/proto/windmill.proto b/sdk/src/main/proto/windmill.proto index 8120ec8571..d9d9706cd0 100644 --- a/sdk/src/main/proto/windmill.proto +++ b/sdk/src/main/proto/windmill.proto @@ -161,8 +161,11 @@ message ComputationWorkItems { message GetWorkRequest { required fixed64 client_id = 1; + optional string worker_id = 4; + optional string job_id = 5; optional int64 max_items = 2 [default = 0xffffffff]; optional int64 max_bytes = 3 [default = 0x7fffffffffffffff]; + // reserved field number = 6 } message GetWorkResponse { @@ -185,6 +188,7 @@ message ComputationGetDataRequest { } message GetDataRequest { + optional string job_id = 4; repeated ComputationGetDataRequest requests = 1; repeated GlobalDataRequest global_data_fetch_requests = 3; @@ -270,6 +274,7 @@ message ComputationCommitWorkRequest { } message CommitWorkRequest { + optional string job_id = 2; repeated ComputationCommitWorkRequest requests = 1; } @@ -278,6 +283,7 @@ message CommitWorkResponse {} // Configuration message GetConfigRequest { + optional string job_id = 2; repeated string computations = 1; } @@ -308,6 +314,7 @@ message Exception { } message ReportStatsRequest { + optional string job_id = 6; optional string computation_id = 1; optional bytes key = 2; optional fixed64 work_token = 3; From cb110627cd155e29ab3b32ab044604f4eb14d686 Mon Sep 17 00:00:00 2001 From: bchambers Date: Wed, 20 Jan 2016 13:30:10 -0800 Subject: [PATCH 018/751] Use the standard set of status pages for Batch This includes all the status information that was previously available and adds /heapz to download a heap dump. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112613644 --- .../sdk/runners/worker/DataflowWorker.java | 65 ++-------------- .../runners/worker/DataflowWorkerHarness.java | 6 +- .../worker/StreamingDataflowWorker.java | 4 +- .../worker/status/WorkerStatusPages.java | 20 ++--- .../runners/worker/DataflowWorkerTest.java | 44 ----------- .../worker/status/WorkerStatusPagesTest.java | 76 +++++++++++++++++++ 6 files changed, 96 insertions(+), 119 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java index 9848c4c35f..ffef4a053d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java @@ -34,6 +34,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingHandler; +import com.google.cloud.dataflow.sdk.runners.worker.status.WorkerStatusPages; import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; import com.google.cloud.dataflow.sdk.util.CloudCounterUtils; import com.google.cloud.dataflow.sdk.util.CloudMetricUtils; @@ -51,14 +52,10 @@ import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -67,9 +64,6 @@ import java.util.Map; import javax.annotation.Nullable; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; /** * This is a semi-abstract harness for executing WorkItem tasks in @@ -99,10 +93,12 @@ public class DataflowWorker { */ private final Cache, WeightedValue> sideInputCache; + private static final int DEFAULT_STATUS_PORT = 18081; + /** * Status server returning health of worker. */ - private Server statusServer; + private WorkerStatusPages statusServer = WorkerStatusPages.create(DEFAULT_STATUS_PORT); /** * Tracker for user code time. @@ -117,7 +113,6 @@ public class DataflowWorker { private static final long MEGABYTES = 1024 * 1024; - public static final int DEFAULT_STATUS_PORT = 18081; public DataflowWorker(WorkUnitClient workUnitClient, DataflowWorkerHarnessOptions options) { this.workUnitClient = workUnitClient; @@ -462,55 +457,7 @@ protected SideInputReader getSideInputReaderForViews( /** * Runs the status server to report worker health on the specified port. */ - public void runStatusServer(int statusPort) { - LOG.info("Status server started on port {}", statusPort); - runStatusServer(new Server(statusPort)); - } - - // @VisibleForTesting - void runStatusServer(Server server) { - statusServer = server; - statusServer.setHandler(new StatusHandler()); - try { - // Run status server in separate thread. - statusServer.start(); - } catch (Exception e) { - LOG.warn("Status server failed to start: ", e); - } - } - - private class StatusHandler extends AbstractHandler { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { - response.setContentType("text/html;charset=utf-8"); - baseRequest.setHandled(true); - - PrintWriter responseWriter = response.getWriter(); - - if (target.equals("/healthz")) { - response.setStatus(HttpServletResponse.SC_OK); - // Right now, we always return "ok". - responseWriter.println("ok"); - } else if (target.equals("/threadz")) { - response.setStatus(HttpServletResponse.SC_OK); - printThreads(responseWriter); - } else { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - responseWriter.println("not found"); - } - } - - private void printThreads(PrintWriter response) { - Map stacks = Thread.getAllStackTraces(); - for (Map.Entry entry : stacks.entrySet()) { - Thread thread = entry.getKey(); - response.println("--- Thread: " + thread + " State: " - + thread.getState() + " stack: ---"); - for (StackTraceElement element : entry.getValue()) { - response.println(" " + element); - } - } - } + public void runStatusServer() { + statusServer.start(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java index 5f8d5db70b..9de057fcd4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java @@ -133,11 +133,7 @@ public static void main(String[] args) throws Exception { final Sleeper sleeper = Sleeper.DEFAULT; final DataflowWorker worker = create(pipelineOptions); - int statusPort = DataflowWorker.DEFAULT_STATUS_PORT; - if (System.getProperties().containsKey("status_port")) { - statusPort = Integer.parseInt(System.getProperty("status_port")); - } - worker.runStatusServer(statusPort); + worker.runStatusServer(); processWork(pipelineOptions, worker, sleeper); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java index c9f3485b15..fc7259ea8f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java @@ -94,6 +94,8 @@ public class StreamingDataflowWorker { "com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServer"; static final int MAX_COMMIT_QUEUE_BYTES = 500 << 20; // 500MB + private static final int DEFAULT_STATUS_PORT = 8081; + // Maximum size of the result of a GetWork request. private static final long MAX_GET_WORK_FETCH_BYTES = 64L << 20; // 64m @@ -303,7 +305,7 @@ public Integer apply(Windmill.WorkItemCommitRequest input) { private final UserCodeTimeTracker userCodeTimeTracker = new UserCodeTimeTracker(); private final AtomicInteger nextStateSamplerId = new AtomicInteger(); - private final WorkerStatusPages statusPages = WorkerStatusPages.create(); + private final WorkerStatusPages statusPages = WorkerStatusPages.create(DEFAULT_STATUS_PORT); public StreamingDataflowWorker( List mapTasks, WindmillServerStub server, DataflowWorkerHarnessOptions options) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java index f383b8e2e1..ad16654e27 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.runners.worker.status; +import com.google.common.annotations.VisibleForTesting; + import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; @@ -35,14 +37,12 @@ public class WorkerStatusPages { private static final Logger LOG = LoggerFactory.getLogger(WorkerStatusPages.class); - private static final int DEFAULT_STATUS_PORT = 8081; - private final Server statusServer; private final StatuszServlet statuszServlet = new StatuszServlet(); private final ServletHandler servletHandler = new ServletHandler(); - private WorkerStatusPages(int statusPort) { - this.statusServer = new Server(statusPort); + @VisibleForTesting WorkerStatusPages(Server server) { + this.statusServer = server; this.statusServer.setHandler(servletHandler); // Install the default servlets (threadz, healthz, heapz, statusz) @@ -50,20 +50,21 @@ private WorkerStatusPages(int statusPort) { addServlet(new HealthzServlet()); addServlet(new HeapzServlet()); addServlet(statuszServlet); + } - public static WorkerStatusPages create() { - int statusPort = DEFAULT_STATUS_PORT; + public static WorkerStatusPages create(int defaultStatusPort) { + int statusPort = defaultStatusPort; if (System.getProperties().containsKey("status_port")) { statusPort = Integer.parseInt(System.getProperty("status_port")); } - return new WorkerStatusPages(statusPort); + return new WorkerStatusPages(new Server(statusPort)); } /** Start the server. */ public void start() { if (statusServer.isStarted()) { - LOG.warn("Status server already started on port {}", statusServer.getURI().getPort()); + LOG.warn("Status server already started on {}", statusServer.getURI()); return; } @@ -71,8 +72,7 @@ public void start() { addServlet(new RedirectToStatusz404Handler()); statusServer.start(); - LOG.info("Status server started on port {}", statusServer.getURI().getPort()); - statusServer.join(); + LOG.info("Status server started on {}", statusServer.getURI()); } catch (Exception e) { LOG.warn("Status server failed to start: ", e); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java index d575d6f429..afafa1c285 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java @@ -14,7 +14,6 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; @@ -36,8 +35,6 @@ import com.google.cloud.dataflow.sdk.util.common.worker.WorkExecutor; import com.google.common.collect.ImmutableList; -import org.eclipse.jetty.server.LocalConnector; -import org.eclipse.jetty.server.Server; import org.hamcrest.CoreMatchers; import org.hamcrest.Description; import org.hamcrest.Matcher; @@ -118,31 +115,6 @@ public void testStopProgressReportInCaseOfFailure() throws Exception { verify(mockProgressUpdater, times(1)).stopReportingProgress(); } - @Test - public void testHealthzHandler() throws Exception { - String response = testStatusServer( - "GET /healthz HTTP/1.1\nhost: localhost\n\n"); - assertThat(response, containsString("HTTP/1.1 200 OK")); - assertThat(response, containsString("ok")); - } - - @Test - public void testThreadzHandler() throws Exception { - String response = testStatusServer( - "GET /threadz HTTP/1.1\nhost: localhost\n\n"); - assertThat(response, containsString("HTTP/1.1 200 OK")); - assertThat(response, containsString("--- Thread: ")); - // testThreadzHandler should be somewhere in the stack trace of one of the threads. - assertThat(response, containsString("testThreadzHandler")); - } - - @Test - public void testUnknownHandler() throws Exception { - String response = testStatusServer( - "GET /missinghandlerz HTTP/1.1\nhost: localhost\n\n"); - assertThat(response, containsString("HTTP/1.1 404 Not Found")); - } - @Test public void testIsSplitResponseTooLarge() { SourceSplitResponse splitResponse = new SourceSplitResponse(); @@ -170,22 +142,6 @@ public void testWorkItemStatusWithStateSamplerInfo() throws Exception { assertEquals(101L, metric.get("num-transitions")); } - private String testStatusServer(String request) throws Exception { - Server server = new Server(); - LocalConnector connector = new LocalConnector(server); - try { - DataflowWorker worker = new DataflowWorker(mockWorkUnitClient, options); - worker.runStatusServer(server); - connector.start(); - return connector.getResponses(request); - } finally { - connector.stop(); - connector.join(); - server.stop(); - server.join(); - } - } - private Matcher cloudWorkHasErrors(final long expectedReportIndex) { return new TypeSafeMatcher() { @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java new file mode 100644 index 0000000000..8730a61497 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertThat; + +import org.eclipse.jetty.server.LocalConnector; +import org.eclipse.jetty.server.Server; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link WorkerStatusPages}. + */ +@RunWith(JUnit4.class) +public class WorkerStatusPagesTest { + + private final Server server = new Server(); + private final LocalConnector connector = new LocalConnector(server); + private final WorkerStatusPages wsp = new WorkerStatusPages(server); + + @Before + public void setUp() throws Exception { + server.addConnector(connector); + wsp.start(); + } + + @After + public void tearDown() throws Exception { + wsp.stop(); + } + + @Test + public void testThreadz() throws Exception { + String response = getPage("/threadz"); + assertThat(response, containsString("HTTP/1.1 200 OK")); + assertThat("Test method should appear in stack trace", + response, containsString("WorkerStatusPagesTest.testThreadz")); + } + + @Test + public void testHealthz() throws Exception { + String response = getPage("/threadz"); + assertThat(response, containsString("HTTP/1.1 200 OK")); + assertThat(response, containsString("ok")); + } + + @Test + public void testUnknownHandler() throws Exception { + String response = getPage("/missinghandlerz"); + assertThat(response, containsString("HTTP/1.1 302 Found")); + assertThat(response, containsString("Location: http://localhost/statusz")); + } + + private String getPage(String requestURL) throws Exception { + String request = String.format("GET %s HTTP/1.1\nhost: localhost\n\n", requestURL); + return connector.getResponses(request); + } +} From 46a1ece9a3912bf9c95d4a5cab9c960a7795bb23 Mon Sep 17 00:00:00 2001 From: klk Date: Wed, 20 Jan 2016 15:02:22 -0800 Subject: [PATCH 019/751] Add FinishedTriggers abstraction with BitSet and Set implementations Previously, we directly interacted with a BitSet using indices stored on each ExecutableTrigger to track which triggers are finished for a window. This change introduces a very small interface for this interaction, and two implementations: 1. Via a BitSet for efficient storage and transmittal. 2. Via a Set for simple in-memory execution and debugging. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112623430 --- .../dataflow/sdk/util/FinishedTriggers.java | 42 +++++++ .../sdk/util/FinishedTriggersBitSet.java | 68 +++++++++++ .../sdk/util/FinishedTriggersSet.java | 74 ++++++++++++ .../sdk/util/TriggerContextFactory.java | 61 +++++----- .../dataflow/sdk/util/TriggerRunner.java | 30 +++-- .../sdk/util/FinishedTriggersBitSetTest.java | 54 +++++++++ .../sdk/util/FinishedTriggersProperties.java | 109 ++++++++++++++++++ .../sdk/util/FinishedTriggersSetTest.java | 60 ++++++++++ .../dataflow/sdk/util/TriggerTester.java | 19 +-- 9 files changed, 467 insertions(+), 50 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java new file mode 100644 index 0000000000..e75be23eee --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +/** + * A mutable set which tracks whether any particular {@link ExecutableTrigger} is + * finished. + */ +public interface FinishedTriggers { + /** + * Returns {@code true} if the trigger is finished. + */ + public boolean isFinished(ExecutableTrigger trigger); + + /** + * Sets the fact that the trigger is finished. + */ + public void setFinished(ExecutableTrigger trigger, boolean value); + + /** + * Sets the trigger and all of its subtriggers to unfinished. + */ + public void clearRecursively(ExecutableTrigger trigger); + + /** + * Create an independent copy of this mutable {@link FinishedTriggers}. + */ + public FinishedTriggers copy(); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java new file mode 100644 index 0000000000..09f7af7a95 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import java.util.BitSet; + +/** + * A {@link FinishedTriggers} implementation based on an underlying {@link BitSet}. + */ +public class FinishedTriggersBitSet implements FinishedTriggers { + + private final BitSet bitSet; + + private FinishedTriggersBitSet(BitSet bitSet) { + this.bitSet = bitSet; + } + + public static FinishedTriggersBitSet emptyWithCapacity(int capacity) { + return new FinishedTriggersBitSet(new BitSet(capacity)); + } + + public static FinishedTriggersBitSet fromBitSet(BitSet bitSet) { + return new FinishedTriggersBitSet(bitSet); + } + + /** + * Returns the underlying {@link BitSet} for this {@link FinishedTriggersBitSet}. + */ + public BitSet getBitSet() { + return bitSet; + } + + @Override + public boolean isFinished(ExecutableTrigger trigger) { + return bitSet.get(trigger.getTriggerIndex()); + } + + @Override + public void setFinished(ExecutableTrigger trigger, boolean value) { + bitSet.set(trigger.getTriggerIndex(), value); + } + + @Override + public void clearRecursively(ExecutableTrigger trigger) { + bitSet.clear(trigger.getTriggerIndex(), trigger.getFirstIndexAfterSubtree()); + } + + @Override + public FinishedTriggersBitSet copy() { + return new FinishedTriggersBitSet((BitSet) bitSet.clone()); + } +} + + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java new file mode 100644 index 0000000000..6da673d28c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.common.collect.Sets; + +import java.util.Set; + +/** + * An implementation of {@link FinishedTriggers} atop a user-provided mutable {@link Set}. + */ +public class FinishedTriggersSet implements FinishedTriggers { + + private final Set> finishedTriggers; + + private FinishedTriggersSet(Set> finishedTriggers) { + this.finishedTriggers = finishedTriggers; + } + + public static FinishedTriggersSet fromSet(Set> finishedTriggers) { + return new FinishedTriggersSet(finishedTriggers); + } + + /** + * Returns a mutable {@link Set} of the underlying triggers that are finished. + */ + public Set> getFinishedTriggers() { + return finishedTriggers; + } + + @Override + public boolean isFinished(ExecutableTrigger trigger) { + return finishedTriggers.contains(trigger); + } + + @Override + public void setFinished(ExecutableTrigger trigger, boolean value) { + if (value) { + finishedTriggers.add(trigger); + } else { + finishedTriggers.remove(trigger); + } + } + + @Override + public void clearRecursively(ExecutableTrigger trigger) { + finishedTriggers.remove(trigger); + for (ExecutableTrigger subTrigger : trigger.subTriggers()) { + clearRecursively(subTrigger); + } + } + + @Override + public FinishedTriggersSet copy() { + return fromSet(Sets.newHashSet(finishedTriggers)); + } + +} + + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index e7193b3dce..8c438cea14 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -30,7 +30,6 @@ import org.joda.time.Instant; -import java.util.BitSet; import java.util.Collection; import java.util.Map; @@ -53,14 +52,14 @@ public TriggerContextFactory(WindowingStrategy windowingStrategy, this.activeWindows = activeWindows; } - public Trigger.TriggerContext base( - W window, ReduceFn.Timers timers, ExecutableTrigger rootTrigger, BitSet finishedSet) { + public Trigger.TriggerContext base(W window, ReduceFn.Timers timers, + ExecutableTrigger rootTrigger, FinishedTriggers finishedSet) { return new TriggerContextImpl(window, timers, rootTrigger, finishedSet); } public Trigger.OnElementContext createOnElementContext( W window, ReduceFn.Timers timers, Instant elementTimestamp, - ExecutableTrigger rootTrigger, BitSet finishedSet) { + ExecutableTrigger rootTrigger, FinishedTriggers finishedSet) { return new OnElementContextImpl( window, timers, rootTrigger, finishedSet, elementTimestamp); @@ -68,7 +67,7 @@ public Trigger.OnElementContext createOnElementContext( public Trigger.OnTimerContext createOnTimerContext( W window, ReduceFn.Timers timers, - ExecutableTrigger rootTrigger, BitSet finishedSet, + ExecutableTrigger rootTrigger, FinishedTriggers finishedSet, Instant timestamp, TimeDomain domain) { return new OnTimerContextImpl( window, timers, rootTrigger, finishedSet, timestamp, domain); @@ -76,8 +75,8 @@ public Trigger.OnTimerContext createOnTimerContext( public Trigger.OnMergeContext createOnMergeContext( W window, ReduceFn.Timers timers, Collection mergingWindows, - ExecutableTrigger rootTrigger, BitSet finishedSet, - Map finishedSets) { + ExecutableTrigger rootTrigger, FinishedTriggers finishedSet, + Map finishedSets) { return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, mergingWindows, finishedSets); } @@ -85,11 +84,11 @@ public Trigger.OnMergeContext createOnMergeContext( private class TriggerInfoImpl implements Trigger.TriggerInfo { protected final ExecutableTrigger trigger; - protected final BitSet finishedSet; + protected final FinishedTriggers finishedSet; private final Trigger.TriggerContext context; - public TriggerInfoImpl( - ExecutableTrigger trigger, BitSet finishedSet, Trigger.TriggerContext context) { + public TriggerInfoImpl(ExecutableTrigger trigger, FinishedTriggers finishedSet, + Trigger.TriggerContext context) { this.trigger = trigger; this.finishedSet = finishedSet; this.context = context; @@ -112,12 +111,12 @@ public ExecutableTrigger subTrigger(int subtriggerIndex) { @Override public boolean isFinished() { - return finishedSet.get(trigger.getTriggerIndex()); + return finishedSet.isFinished(trigger); } @Override public boolean isFinished(int subtriggerIndex) { - return finishedSet.get(subTrigger(subtriggerIndex).getTriggerIndex()); + return finishedSet.isFinished(subTrigger(subtriggerIndex)); } @Override @@ -131,8 +130,8 @@ public Iterable> unfinishedSubTriggers() { .from(trigger.subTriggers()) .filter(new Predicate>() { @Override - public boolean apply(ExecutableTrigger input) { - return !finishedSet.get(input.getTriggerIndex()); + public boolean apply(ExecutableTrigger trigger) { + return !finishedSet.isFinished(trigger); } }); } @@ -140,7 +139,7 @@ public boolean apply(ExecutableTrigger input) { @Override public ExecutableTrigger firstUnfinishedSubTrigger() { for (ExecutableTrigger subTrigger : trigger.subTriggers()) { - if (!finishedSet.get(subTrigger.getTriggerIndex())) { + if (!finishedSet.isFinished(subTrigger)) { return subTrigger; } } @@ -149,18 +148,18 @@ public ExecutableTrigger firstUnfinishedSubTrigger() { @Override public void resetTree() throws Exception { - finishedSet.clear(trigger.getTriggerIndex(), trigger.getFirstIndexAfterSubtree()); + finishedSet.clearRecursively(trigger); trigger.invokeClear(context); } @Override public void setFinished(boolean finished) { - finishedSet.set(trigger.getTriggerIndex(), finished); + finishedSet.setFinished(trigger, finished); } @Override public void setFinished(boolean finished, int subTriggerIndex) { - finishedSet.set(subTrigger(subTriggerIndex).getTriggerIndex(), finished); + finishedSet.setFinished(subTrigger(subTriggerIndex), finished); } } @@ -199,21 +198,21 @@ public Instant currentProcessingTime() { private class MergingTriggerInfoImpl extends TriggerInfoImpl implements Trigger.MergingTriggerInfo { - private final Map finishedSets; + private final Map finishedSets; public MergingTriggerInfoImpl( ExecutableTrigger trigger, - BitSet finishedSet, + FinishedTriggers finishedSet, Trigger.TriggerContext context, - Map finishedSets) { + Map finishedSets) { super(trigger, finishedSet, context); this.finishedSets = finishedSets; } @Override public boolean finishedInAnyMergingWindow() { - for (BitSet bitSet : finishedSets.values()) { - if (bitSet.get(trigger.getTriggerIndex())) { + for (FinishedTriggers finishedSet : finishedSets.values()) { + if (finishedSet.isFinished(trigger)) { return true; } } @@ -222,10 +221,10 @@ public boolean finishedInAnyMergingWindow() { @Override public Iterable getFinishedMergingWindows() { - return Maps.filterValues(finishedSets, new Predicate() { + return Maps.filterValues(finishedSets, new Predicate() { @Override - public boolean apply(BitSet input) { - return input.get(trigger.getTriggerIndex()); + public boolean apply(FinishedTriggers finishedSet) { + return finishedSet.isFinished(trigger); } }).keySet(); } @@ -270,7 +269,7 @@ private TriggerContextImpl( W window, ReduceFn.Timers timers, ExecutableTrigger trigger, - BitSet finishedSet) { + FinishedTriggers finishedSet) { trigger.getSpec().super(); this.state = triggerState(window, trigger); this.timers = new TriggerTimers(window, timers); @@ -320,7 +319,7 @@ private OnElementContextImpl( W window, ReduceFn.Timers timers, ExecutableTrigger trigger, - BitSet finishedSet, + FinishedTriggers finishedSet, Instant eventTimestamp) { trigger.getSpec().super(); this.state = triggerState(window, trigger); @@ -385,7 +384,7 @@ private OnTimerContextImpl( W window, ReduceFn.Timers timers, ExecutableTrigger trigger, - BitSet finishedSet, + FinishedTriggers finishedSet, Instant timestamp, TimeDomain domain) { trigger.getSpec().super(); @@ -448,9 +447,9 @@ private OnMergeContextImpl( W window, ReduceFn.Timers timers, ExecutableTrigger trigger, - BitSet finishedSet, + FinishedTriggers finishedSet, Collection mergingWindows, - Map finishedSets) { + Map finishedSets) { trigger.getSpec().super(); this.state = new ReduceFnContextFactory.MergingStateContextImpl<>( triggerState(window, trigger), mergingWindows); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index 6efd5b7b45..1fd077f0a4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -58,21 +58,23 @@ public TriggerRunner(ExecutableTrigger rootTrigger, TriggerContextFactory this.contextFactory = contextFactory; } - private BitSet readFinishedBits(ValueState state) { + private FinishedTriggersBitSet readFinishedBits(ValueState state) { if (!isFinishedSetNeeded()) { // If no trigger in the tree will ever have finished bits, then we don't need to read them. // So that the code can be agnostic to that fact, we create a BitSet that is all 0 (not // finished) for each trigger in the tree. - return new BitSet(rootTrigger.getFirstIndexAfterSubtree()); + return FinishedTriggersBitSet.emptyWithCapacity(rootTrigger.getFirstIndexAfterSubtree()); } BitSet bitSet = state.get().read(); - return bitSet == null ? new BitSet(rootTrigger.getFirstIndexAfterSubtree()) : bitSet; + return bitSet == null + ? FinishedTriggersBitSet.emptyWithCapacity(rootTrigger.getFirstIndexAfterSubtree()) + : FinishedTriggersBitSet.fromBitSet(bitSet); } /** Return true if the trigger is closed in the window corresponding to the specified state. */ public boolean isClosed(ReduceFn.StateContext state) { - return readFinishedBits(state.access(FINISHED_BITS_TAG)).get(0); + return readFinishedBits(state.access(FINISHED_BITS_TAG)).isFinished(rootTrigger); } public void prefetchForValue(ReduceFn.StateContext state) { @@ -87,7 +89,8 @@ public void prefetchForValue(ReduceFn.StateContext state) { */ public TriggerResult processValue(ReduceFn.ProcessValueContext c) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. - BitSet finishedSet = (BitSet) readFinishedBits(c.state().access(FINISHED_BITS_TAG)).clone(); + FinishedTriggersBitSet finishedSet = + readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); Trigger.OnElementContext triggerContext = contextFactory.createOnElementContext( c.window(), c.timers(), c.timestamp(), rootTrigger, finishedSet); TriggerResult result = rootTrigger.invokeElement(triggerContext); @@ -110,10 +113,11 @@ public void prefetchForMerge(ReduceFn.MergingStateContext state) { */ public TriggerResult onMerge(ReduceFn.OnMergeContext c) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. - BitSet finishedSet = (BitSet) readFinishedBits(c.state().access(FINISHED_BITS_TAG)).clone(); + FinishedTriggersBitSet finishedSet = + readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); // And read the finished bits in each merging window. - ImmutableMap.Builder mergingFinishedSets = ImmutableMap.builder(); + ImmutableMap.Builder mergingFinishedSets = ImmutableMap.builder(); Map> mergingFinishedSetState = c.state().mergingAccessInEachMergingWindow(FINISHED_BITS_TAG); for (W window : c.mergingWindows()) { @@ -147,7 +151,8 @@ public void prefetchForTimer(ReduceFn.StateContext state) { */ public TriggerResult onTimer(ReduceFn.Context c, TimerData timer) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. - BitSet finishedSet = (BitSet) readFinishedBits(c.state().access(FINISHED_BITS_TAG)).clone(); + FinishedTriggersBitSet finishedSet = + readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); Trigger.OnTimerContext triggerContext = contextFactory.createOnTimerContext( c.window(), c.timers(), rootTrigger, finishedSet, timer.getTimestamp(), timer.getDomain()); @@ -156,17 +161,18 @@ public TriggerResult onTimer(ReduceFn.Context c, TimerData timer) th return result; } - private void persistFinishedSet(ReduceFn.StateContext state, BitSet modifiedFinishedSet) { + private void persistFinishedSet( + ReduceFn.StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { if (!isFinishedSetNeeded()) { return; } ValueState finishedSet = state.access(FINISHED_BITS_TAG); if (!finishedSet.get().equals(modifiedFinishedSet)) { - if (modifiedFinishedSet.isEmpty()) { + if (modifiedFinishedSet.getBitSet().isEmpty()) { finishedSet.clear(); } else { - finishedSet.set(modifiedFinishedSet); + finishedSet.set(modifiedFinishedSet.getBitSet()); } } } @@ -177,7 +183,7 @@ private void persistFinishedSet(ReduceFn.StateContext state, BitSet modifiedFini */ public void clearState(ReduceFn.Context c) throws Exception { // Don't need to clone, because we'll be clearing the finished bits anyways. - BitSet finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)); + FinishedTriggers finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)); rootTrigger.invokeClear(contextFactory.base( c.window(), c.timers(), rootTrigger, finishedSet)); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java new file mode 100644 index 0000000000..7e66683e26 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.theInstance; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link FinishedTriggersBitSet}. + */ +@RunWith(JUnit4.class) +public class FinishedTriggersBitSetTest { + /** + * Tests that after a trigger is set to finished, it reads back as finished. + */ + @Test + public void testSetGet() { + FinishedTriggersProperties.verifyGetAfterSet(FinishedTriggersBitSet.emptyWithCapacity(1)); + } + + /** + * Tests that clearing a trigger recursively clears all of that triggers subTriggers, but no + * others. + */ + @Test + public void testClearRecursively() { + FinishedTriggersProperties.verifyClearRecursively(FinishedTriggersBitSet.emptyWithCapacity(1)); + } + + @Test + public void testCopy() throws Exception { + FinishedTriggersBitSet finishedSet = FinishedTriggersBitSet.emptyWithCapacity(10); + assertThat(finishedSet.copy().getBitSet(), not(theInstance(finishedSet.getBitSet()))); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java new file mode 100644 index 0000000000..7b3ac689af --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterAll; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterFirst; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; + +/** + * Generalized tests for {@link FinishedTriggers} implementations. + */ +public class FinishedTriggersProperties { + /** + * Tests that for the provided trigger and {@link FinishedTriggers}, when the trigger is set + * finished, it is correctly reported as finished. + */ + public static void verifyGetAfterSet(FinishedTriggers finishedSet, ExecutableTrigger trigger) { + assertFalse(finishedSet.isFinished(trigger)); + finishedSet.setFinished(trigger, true); + assertTrue(finishedSet.isFinished(trigger)); + } + + /** + * For a few arbitrary triggers, tests that when the trigger is set finished it is correctly + * reported as finished. + */ + public static void verifyGetAfterSet(FinishedTriggers finishedSet) { + ExecutableTrigger trigger = ExecutableTrigger.create(AfterAll.of( + AfterFirst.of(AfterPane.elementCountAtLeast(3), AfterWatermark.pastEndOfWindow()), + AfterAll.of( + AfterPane.elementCountAtLeast(10), AfterProcessingTime.pastFirstElementInPane()))); + + verifyGetAfterSet(finishedSet, trigger); + verifyGetAfterSet(finishedSet, trigger.subTriggers().get(0).subTriggers().get(1)); + verifyGetAfterSet(finishedSet, trigger.subTriggers().get(0)); + verifyGetAfterSet(finishedSet, trigger.subTriggers().get(1)); + verifyGetAfterSet(finishedSet, trigger.subTriggers().get(1).subTriggers().get(1)); + verifyGetAfterSet(finishedSet, trigger.subTriggers().get(1).subTriggers().get(0)); + } + + /** + * Tests that clearing a trigger recursively clears all of that triggers subTriggers, but no + * others. + */ + public static void verifyClearRecursively(FinishedTriggers finishedSet) { + ExecutableTrigger trigger = ExecutableTrigger.create(AfterAll.of( + AfterFirst.of(AfterPane.elementCountAtLeast(3), AfterWatermark.pastEndOfWindow()), + AfterAll.of( + AfterPane.elementCountAtLeast(10), AfterProcessingTime.pastFirstElementInPane()))); + + // Set them all finished. This method is not on a trigger as it makes no sense outside tests. + setFinishedRecursively(finishedSet, trigger); + assertTrue(finishedSet.isFinished(trigger)); + assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0))); + assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0).subTriggers().get(0))); + assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0).subTriggers().get(1))); + + // Clear just the second AfterAll + finishedSet.clearRecursively(trigger.subTriggers().get(1)); + + // Check that the first and all that are still finished + assertTrue(finishedSet.isFinished(trigger)); + verifyFinishedRecursively(finishedSet, trigger.subTriggers().get(0)); + verifyUnfinishedRecursively(finishedSet, trigger.subTriggers().get(1)); + } + + private static void setFinishedRecursively( + FinishedTriggers finishedSet, ExecutableTrigger trigger) { + finishedSet.setFinished(trigger, true); + for (ExecutableTrigger subTrigger : trigger.subTriggers()) { + setFinishedRecursively(finishedSet, subTrigger); + } + } + + private static void verifyFinishedRecursively( + FinishedTriggers finishedSet, ExecutableTrigger trigger) { + assertTrue(finishedSet.isFinished(trigger)); + for (ExecutableTrigger subTrigger : trigger.subTriggers()) { + verifyFinishedRecursively(finishedSet, subTrigger); + } + } + + private static void verifyUnfinishedRecursively( + FinishedTriggers finishedSet, ExecutableTrigger trigger) { + assertFalse(finishedSet.isFinished(trigger)); + for (ExecutableTrigger subTrigger : trigger.subTriggers()) { + verifyUnfinishedRecursively(finishedSet, subTrigger); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java new file mode 100644 index 0000000000..60384deebd --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.theInstance; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.HashSet; + +/** + * Tests for {@link FinishedTriggersSet}. + */ +@RunWith(JUnit4.class) +public class FinishedTriggersSetTest { + /** + * Tests that after a trigger is set to finished, it reads back as finished. + */ + @Test + public void testSetGet() { + FinishedTriggersProperties.verifyGetAfterSet( + FinishedTriggersSet.fromSet(new HashSet>())); + } + + /** + * Tests that clearing a trigger recursively clears all of that triggers subTriggers, but no + * others. + */ + @Test + public void testClearRecursively() { + FinishedTriggersProperties.verifyClearRecursively( + FinishedTriggersSet.fromSet(new HashSet>())); + } + + @Test + public void testCopy() throws Exception { + FinishedTriggersSet finishedSet = + FinishedTriggersSet.fromSet(new HashSet>()); + assertThat(finishedSet.copy().getFinishedTriggers(), + not(theInstance(finishedSet.getFinishedTriggers()))); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index dc5836b3a3..7b3a6593e0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -46,12 +46,12 @@ import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import org.joda.time.Instant; import java.util.ArrayList; import java.util.Arrays; -import java.util.BitSet; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -111,7 +111,7 @@ public void injectElements(int... values) throws Exception { /** * A map from a window and trigger to whether that trigger is finished for the window. */ - private final Map finishedSets; + private final Map finishedSets; public static SimpleTriggerTester forTrigger( TriggerBuilder trigger, WindowFn windowFn) throws Exception { @@ -234,12 +234,12 @@ public void assertCleared(W window) { * Returns {@code true} if the {@link Trigger} under test is finished for the given window. */ public boolean isMarkedFinished(W window) { - BitSet finishedSet = finishedSets.get(window); + FinishedTriggers finishedSet = finishedSets.get(window); if (finishedSet == null) { return false; } - return finishedSet.get(executableTrigger.getTriggerIndex()); + return finishedSet.isFinished(executableTrigger); } private StateNamespace windowNamespace(W window) { @@ -339,16 +339,21 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W for (Map.Entry> merged : windowToComponents.entrySet()) { W window = merged.getKey(); Collection oldWindows = merged.getValue(); + Map mergingFinishedSets = + Maps.newHashMapWithExpectedSize(oldWindows.size()); + for (W oldWindow : oldWindows) { + mergingFinishedSets.put(oldWindow, getFinishedSet(oldWindow)); + } latestMergeResult = executableTrigger.invokeMerge( contextFactory.createOnMergeContext(window, new TestTimers(windowNamespace(window)), oldWindows, executableTrigger, getFinishedSet(window), finishedSets)); } } - private BitSet getFinishedSet(W window) { - BitSet finishedSet = finishedSets.get(window); + private FinishedTriggers getFinishedSet(W window) { + FinishedTriggers finishedSet = finishedSets.get(window); if (finishedSet == null) { - finishedSet = new BitSet(); + finishedSet = FinishedTriggersSet.fromSet(new HashSet>()); finishedSets.put(window, finishedSet); } return finishedSet; From a46d3bde653b5b073c7d684e16d4adbaf79f779a Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 20 Jan 2016 16:53:37 -0800 Subject: [PATCH 020/751] CustomSources: add logs and normalize log levels - Log when dynamic work rebalancing fails. - Downgrade expected logs from warn to info. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112634778 --- .../cloud/dataflow/sdk/runners/dataflow/CustomSources.java | 4 ++++ .../cloud/dataflow/sdk/util/common/worker/ReadOperation.java | 5 ++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java index 44fbc55fce..0039281c4a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java @@ -499,11 +499,15 @@ public NativeReader.DynamicSplitResult requestDynamicSplit( Double fractionConsumed = stopPosition.getFractionConsumed(); if (fractionConsumed == null) { // Only truncating at a fraction is currently supported. + LOG.info( + "Rejecting split request because custom sources only support splits at fraction: {}", + stopPosition); return null; } BoundedSource original = reader.getCurrentSource(); BoundedSource residual = reader.splitAtFraction(fractionConsumed); if (residual == null) { + LOG.info("Rejecting split request because custom reader returned null residual source."); return null; } // Try to catch some potential subclass implementation errors early. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java index 4cf434de10..c46e2a3669 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java @@ -272,12 +272,11 @@ public NativeReader.DynamicSplitResult requestDynamicSplit( NativeReader.DynamicSplitRequest splitRequest) { synchronized (initializationStateLock) { if (isFinished()) { - LOG.warn("Iterator is in the Finished state, returning null stop position."); + LOG.info("Iterator is in the Finished state, returning null stop position."); return null; } if (readerIterator == null) { - LOG.warn("Iterator has not been initialized, refusing to split at {}", - splitRequest); + LOG.info("Iterator has not been initialized, refusing to split at {}", splitRequest); return null; } NativeReader.DynamicSplitResult result = readerIterator.requestDynamicSplit(splitRequest); From a923d7712e7415289b4ecb7c27e89a85cdd2797c Mon Sep 17 00:00:00 2001 From: sgmc Date: Thu, 21 Jan 2016 09:17:24 -0800 Subject: [PATCH 021/751] SingletonAssert: add a notEqualTo matcher ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112692113 --- .../dataflow/sdk/testing/DataflowAssert.java | 40 +++++++++++++++++++ .../sdk/testing/DataflowAssertTest.java | 12 ++++++ 2 files changed, 52 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java index 596c43fa00..6c9643cc3c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java @@ -18,6 +18,7 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.Pipeline; @@ -471,6 +472,16 @@ public SingletonAssert isEqualTo(T expectedValue) { return satisfies(new AssertIsEqualToRelation(), expectedValue); } + /** + * Checks that the value of this {@code SingletonAssert}'s view is not equal + * to the expected value. + * + *

Returns this {@code SingletonAssert}. + */ + public SingletonAssert notEqualTo(T expectedValue) { + return satisfies(new AssertNotEqualToRelation(), expectedValue); + } + /** * Checks that the value of this {@code SingletonAssert}'s view is equal to * the expected value. @@ -719,6 +730,24 @@ public Void apply(T actual) { } } + /** + * A {@link SerializableFunction} that verifies that an actual value is not equal to an + * expected value. + */ + private static class AssertNotEqualTo implements SerializableFunction { + private T expected; + + public AssertNotEqualTo(T expected) { + this.expected = expected; + } + + @Override + public Void apply(T actual) { + assertThat(actual, not(equalTo(expected))); + return null; + } + } + /** * A {@link SerializableFunction} that verifies that an {@code Iterable} contains * expected items in any order. @@ -771,6 +800,17 @@ public SerializableFunction assertFor(T expected) { } } + /** + * An {@link AssertRelation} implementing the binary predicate that two objects are not equal. + */ + private static class AssertNotEqualToRelation + implements AssertRelation { + @Override + public SerializableFunction assertFor(T expected) { + return new AssertNotEqualTo(expected); + } + } + /** * An {@code AssertRelation} implementing the binary predicate that two collections are equal * modulo reordering. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java index 44e64491a5..2cd3014b11 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java @@ -249,6 +249,18 @@ public void testIsEqualTo() throws Exception { pipeline.run(); } + /** + * Basic test for {@code notEqualTo}. + */ + @Test + @Category(RunnableOnService.class) + public void testNotEqualTo() throws Exception { + Pipeline pipeline = TestPipeline.create(); + PCollection pcollection = pipeline.apply(Create.of(43)); + DataflowAssert.thatSingleton(pcollection).notEqualTo(42); + pipeline.run(); + } + /** * Tests that {@code containsInAnyOrder} is actually order-independent. */ From 6e5d74394fccd91bf1a26adc802224a2dca5ccef Mon Sep 17 00:00:00 2001 From: tgroh Date: Thu, 21 Jan 2016 14:21:09 -0800 Subject: [PATCH 022/751] Implement Counter#merge Merge is referenced in isCompatibleWith but is not implemented via the Counter interface. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112723417 --- .../dataflow/sdk/util/common/Counter.java | 81 ++++++++++++++- .../dataflow/sdk/util/common/CounterTest.java | 98 +++++++++++++++++++ 2 files changed, 178 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java index 32acfef28d..2c1985c053 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java @@ -19,6 +19,7 @@ import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.AND; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.OR; +import static com.google.common.base.Preconditions.checkArgument; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.util.concurrent.AtomicDouble; @@ -328,6 +329,13 @@ public boolean isCompatibleWith(Counter that) { && this.getClass().equals(that.getClass()); } + /** + * Merges this counter with the provided counter, returning this counter with the combined value + * of both counters. This may reset the delta of this counter. + * + * @throws IllegalArgumentException if the provided Counter is not compatible with this Counter + */ + public abstract Counter merge(Counter that); ////////////////////////////////////////////////////////////////////////////// @@ -494,6 +502,25 @@ public CounterMean getMean() { return mean.get(); } + @Override + public Counter merge(Counter that) { + checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + switch (kind) { + case SUM: + case MIN: + case MAX: + return addValue(that.getAggregate()); + case MEAN: + CounterMean thisCounterMean = this.getMean(); + CounterMean thatCounterMean = that.getMean(); + return resetMeanToValue( + thisCounterMean.getCount() + thatCounterMean.getCount(), + thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); + default: + throw illegalArgumentException(); + } + } + private static class LongCounterMean implements CounterMean { private final long aggregate; private final long count; @@ -670,6 +697,25 @@ public CounterMean getMean() { return mean.get(); } + @Override + public Counter merge(Counter that) { + checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + switch (kind) { + case SUM: + case MIN: + case MAX: + return addValue(that.getAggregate()); + case MEAN: + CounterMean thisCounterMean = this.getMean(); + CounterMean thatCounterMean = that.getMean(); + return resetMeanToValue( + thisCounterMean.getCount() + thatCounterMean.getCount(), + thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); + default: + throw illegalArgumentException(); + } + } + private static class DoubleCounterMean implements CounterMean { private final double aggregate; private final long count; @@ -763,13 +809,18 @@ public Boolean getAggregate() { public CounterMean getMean() { throw illegalArgumentException(); } + + @Override + public Counter merge(Counter that) { + checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + return addValue(that.getAggregate()); + } } /** * Implements a {@link Counter} for {@link String} values. */ private static class StringCounter extends Counter { - /** Initializes a new {@link Counter} for {@link String} values. */ private StringCounter(String name, AggregationKind kind) { super(name, kind); @@ -833,6 +884,15 @@ public CounterMean getMean() { throw illegalArgumentException(); } } + + @Override + public Counter merge(Counter that) { + checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + switch (kind) { + default: + throw illegalArgumentException(); + } + } } /** @@ -985,6 +1045,25 @@ public CounterMean getMean() { return mean.get(); } + @Override + public Counter merge(Counter that) { + checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + switch (kind) { + case SUM: + case MIN: + case MAX: + return addValue(that.getAggregate()); + case MEAN: + CounterMean thisCounterMean = this.getMean(); + CounterMean thatCounterMean = that.getMean(); + return resetMeanToValue( + thisCounterMean.getCount() + thatCounterMean.getCount(), + thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); + default: + throw illegalArgumentException(); + } + } + private static class IntegerCounterMean implements CounterMean { private final int aggregate; private final long count; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java index ddae986ef1..33d5d3e647 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java @@ -33,12 +33,15 @@ import com.google.cloud.dataflow.sdk.util.CloudCounterUtils; import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Set; /** @@ -47,6 +50,9 @@ @RunWith(JUnit4.class) public class CounterTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + private static MetricUpdate flush(Counter c) { // TODO: Move this out into a separate Counter test. return CounterTestUtils.extractCounterUpdate(c, true); @@ -211,6 +217,13 @@ public void testSumLong() { c.resetToValue(100L).addValue(17L).addValue(49L); expectedTotal = expectedDelta = 166; assertOK(expectedTotal, expectedDelta, c); + + Counter other = Counter.longs("sum-long", SUM); + other.addValue(12L); + expectedDelta = 12L; + expectedTotal += 12L; + c.merge(other); + assertOK(expectedTotal, expectedDelta, c); } @Test @@ -241,6 +254,13 @@ public void testSumDouble() { c.resetToValue(Math.sqrt(17)).addValue(17.0).addValue(49.0); expectedTotal = expectedDelta = Math.sqrt(17.0) + 17.0 + 49.0; assertOK(expectedTotal, expectedDelta, c); + + Counter other = Counter.doubles("sum-double", SUM); + other.addValue(12 * Math.PI); + expectedDelta = 12 * Math.PI; + expectedTotal += 12 * Math.PI; + c.merge(other); + assertOK(expectedTotal, expectedDelta, c); } @@ -272,6 +292,12 @@ public void testMaxLong() { c.resetToValue(100L).addValue(171L).addValue(49L); expectedTotal = expectedDelta = 171; assertOK(expectedTotal, expectedDelta, c); + + Counter other = Counter.longs("max-long", MAX); + other.addValue(12L); + expectedDelta = 12L; + c.merge(other); + assertOK(expectedTotal, expectedDelta, c); } @Test @@ -300,6 +326,12 @@ public void testMaxDouble() { c.resetToValue(Math.sqrt(17)).addValue(171.0).addValue(49.0); expectedTotal = expectedDelta = 171.0; assertOK(expectedTotal, expectedDelta, c); + + Counter other = Counter.doubles("max-double", MAX); + other.addValue(12 * Math.PI); + expectedDelta = 12 * Math.PI; + c.merge(other); + assertOK(expectedTotal, expectedDelta, c); } @@ -331,6 +363,12 @@ public void testMinLong() { c.resetToValue(100L).addValue(171L).addValue(49L); expectedTotal = expectedDelta = 49; assertOK(expectedTotal, expectedDelta, c); + + Counter other = Counter.longs("min-long", MIN); + other.addValue(42L); + expectedTotal = expectedDelta = 42L; + c.merge(other); + assertOK(expectedTotal, expectedDelta, c); } @Test @@ -359,6 +397,12 @@ public void testMinDouble() { c.resetToValue(Math.sqrt(17)).addValue(171.0).addValue(0.0); expectedTotal = expectedDelta = 0.0; assertOK(expectedTotal, expectedDelta, c); + + Counter other = Counter.doubles("min-double", MIN); + other.addValue(42 * Math.E); + expectedDelta = 42 * Math.E; + c.merge(other); + assertOK(expectedTotal, expectedDelta, c); } @@ -419,6 +463,15 @@ public void testMeanLong() { expTotal = expDelta = 166; expCountTotal = expCountDelta = 5; assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); + + Counter other = Counter.longs("mean-long", MEAN); + other.addValue(12L).addValue(44L).addValue(-5L); + expTotal += 12L + 44L - 5L; + expDelta += 12L + 44L - 5L; + expCountTotal += 3; + expCountDelta += 3; + c.merge(other); + assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); } @Test @@ -458,6 +511,15 @@ public void testMeanDouble() { expTotal = expDelta = Math.sqrt(17.0) + 17.0 + 49.0; expCountTotal = expCountDelta = 5; assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); + + Counter other = Counter.doubles("mean-double", MEAN); + other.addValue(3 * Math.PI).addValue(12 * Math.E); + expTotal += 3 * Math.PI + 12 * Math.E; + expDelta += 3 * Math.PI + 12 * Math.E; + expCountTotal += 2; + expCountDelta += 2; + c.merge(other); + assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); } @@ -590,4 +652,40 @@ public void testExtraction() { assertEquals(cloudCountersFromSet, cloudCountersFromArray); assertEquals(2, cloudCountersFromSet.size()); } + + @Test + public void testMergeIncompatibleCounters() { + Counter longSums = Counter.longs("longsums", SUM); + Counter longMean = Counter.longs("longmean", MEAN); + Counter longMin = Counter.longs("longmin", MIN); + + Counter otherLongSums = Counter.longs("othersums", SUM); + Counter otherLongMean = Counter.longs("otherlongmean", MEAN); + + Counter doubleSums = Counter.doubles("doublesums", SUM); + Counter doubleMean = Counter.doubles("doublemean", MEAN); + + Counter boolAnd = Counter.booleans("and", AND); + Counter boolOr = Counter.booleans("or", OR); + + List> longCounters = + Arrays.asList(longSums, longMean, longMin, otherLongSums, otherLongMean); + for (Counter left : longCounters) { + for (Counter right : longCounters) { + if (left != right) { + assertIncompatibleMerge(left, right); + } + } + } + + assertIncompatibleMerge(doubleSums, doubleMean); + assertIncompatibleMerge(boolAnd, boolOr); + } + + private void assertIncompatibleMerge(Counter left, Counter right) { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Counters"); + thrown.expectMessage("are incompatible"); + left.merge(right); + } } From 054f1e6e3b5aa79aa4f61726ec802f4b3124c623 Mon Sep 17 00:00:00 2001 From: peihe Date: Thu, 21 Jan 2016 14:25:03 -0800 Subject: [PATCH 023/751] Optimize mergeAccumulators by reusing an existing accumulator Also, added units tests for Sum, Min, Max, Mean. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112723885 --- .../dataflow/sdk/transforms/Combine.java | 48 ++++++++++++------- .../dataflow/sdk/transforms/MaxTest.java | 27 +++++++++++ .../dataflow/sdk/transforms/MeanTest.java | 10 ++++ .../dataflow/sdk/transforms/MinTest.java | 27 +++++++++++ .../dataflow/sdk/transforms/SumTest.java | 28 ++++++++++- 5 files changed, 121 insertions(+), 19 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java index 3e3d9f4063..0e3ae9be48 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java @@ -534,17 +534,23 @@ public Holder addInput(Holder accumulator, V input) { @Override public Holder mergeAccumulators(Iterable> accumulators) { - Holder running = new Holder<>(); - for (Holder accumulator : accumulators) { - if (accumulator.present) { - if (running.present) { - running.set(apply(running.value, accumulator.value)); - } else { - running.set(accumulator.value); + Iterator> iter = accumulators.iterator(); + if (!iter.hasNext()) { + return createAccumulator(); + } else { + Holder running = iter.next(); + while (iter.hasNext()) { + Holder accum = iter.next(); + if (accum.present) { + if (running.present) { + running.set(apply(running.value, accum.value)); + } else { + running.set(accum.value); + } } } + return running; } - return running; } @Override @@ -632,7 +638,9 @@ public void verifyDeterministic() throws NonDeterministicException { /** * An abstract subclass of {@link CombineFn} for implementing combiners that are more - * easily and efficiently expressed as binary operations on ints. + * easily and efficiently expressed as binary operations on ints + * + *

It uses {@code int[0]} as the mutable accumulator. */ public abstract static class BinaryCombineIntegerFn extends CombineFn { @@ -664,11 +672,11 @@ public int[] mergeAccumulators(Iterable accumulators) { if (!iter.hasNext()) { return createAccumulator(); } else { - int running = iter.next()[0]; + int[] running = iter.next(); while (iter.hasNext()) { - running = apply(running, iter.next()[0]); + running[0] = apply(running[0], iter.next()[0]); } - return wrap(running); + return running; } } @@ -713,6 +721,8 @@ public Counter getCounter(String name) { /** * An abstract subclass of {@link CombineFn} for implementing combiners that are more * easily and efficiently expressed as binary operations on longs. + * + *

It uses {@code long[0]} as the mutable accumulator. */ public abstract static class BinaryCombineLongFn extends CombineFn { /** @@ -743,11 +753,11 @@ public long[] mergeAccumulators(Iterable accumulators) { if (!iter.hasNext()) { return createAccumulator(); } else { - long running = iter.next()[0]; + long[] running = iter.next(); while (iter.hasNext()) { - running = apply(running, iter.next()[0]); + running[0] = apply(running[0], iter.next()[0]); } - return wrap(running); + return running; } } @@ -791,6 +801,8 @@ public Counter getCounter(String name) { /** * An abstract subclass of {@link CombineFn} for implementing combiners that are more * easily and efficiently expressed as binary operations on doubles. + * + *

It uses {@code double[0]} as the mutable accumulator. */ public abstract static class BinaryCombineDoubleFn extends CombineFn { @@ -822,11 +834,11 @@ public double[] mergeAccumulators(Iterable accumulators) { if (!iter.hasNext()) { return createAccumulator(); } else { - double running = iter.next()[0]; + double[] running = iter.next(); while (iter.hasNext()) { - running = apply(running, iter.next()[0]); + running[0] = apply(running[0], iter.next()[0]); } - return wrap(running); + return running; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java index cd61c2302d..e1ea33bcf2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; import static org.junit.Assert.assertEquals; +import com.google.common.collect.Lists; + import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -36,4 +39,28 @@ public void testMeanGetNames() { assertEquals("Max.PerKey", Max.doublesPerKey().getName()); assertEquals("Max.PerKey", Max.longsPerKey().getName()); } + + @Test + public void testMaxIntegerFn() { + checkCombineFn( + new Max.MaxIntegerFn(), + Lists.newArrayList(1, 2, 3, 4), + 4); + } + + @Test + public void testMaxLongFn() { + checkCombineFn( + new Max.MaxLongFn(), + Lists.newArrayList(1L, 2L, 3L, 4L), + 4L); + } + + @Test + public void testMaxDoubleFn() { + checkCombineFn( + new Max.MaxDoubleFn(), + Lists.newArrayList(1.0, 2.0, 3.0, 4.0), + 4.0); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java index bb2729f659..64a2f9de94 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java @@ -16,12 +16,14 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; import static org.junit.Assert.assertEquals; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.testing.CoderProperties; import com.google.cloud.dataflow.sdk.transforms.Mean.CountSum; import com.google.cloud.dataflow.sdk.transforms.Mean.CountSumCoder; +import com.google.common.collect.Lists; import org.junit.Test; import org.junit.runner.RunWith; @@ -59,4 +61,12 @@ public void testCountSumCoderEncodeDecode() throws Exception { public void testCountSumCoderSerializable() throws Exception { CoderProperties.coderSerializable(TEST_CODER); } + + @Test + public void testMeanFn() throws Exception { + checkCombineFn( + new Mean.MeanFn(), + Lists.newArrayList(1, 2, 3, 4), + 2.5); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java index 3c5b78d80e..a291537adf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; import static org.junit.Assert.assertEquals; +import com.google.common.collect.Lists; + import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -36,4 +39,28 @@ public void testMeanGetNames() { assertEquals("Min.PerKey", Min.doublesPerKey().getName()); assertEquals("Min.PerKey", Min.longsPerKey().getName()); } + + @Test + public void testMinIntegerFn() { + checkCombineFn( + new Min.MinIntegerFn(), + Lists.newArrayList(1, 2, 3, 4), + 1); + } + + @Test + public void testMinLongFn() { + checkCombineFn( + new Min.MinLongFn(), + Lists.newArrayList(1L, 2L, 3L, 4L), + 1L); + } + + @Test + public void testMinDoubleFn() { + checkCombineFn( + new Min.MinDoubleFn(), + Lists.newArrayList(1.0, 2.0, 3.0, 4.0), + 1.0); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java index 634f4ef9c0..b5ad51ce13 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java @@ -13,11 +13,13 @@ * License for the specific language governing permissions and limitations under * the License. */ - package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; import static org.junit.Assert.assertEquals; +import com.google.common.collect.Lists; + import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -37,4 +39,28 @@ public void testSumGetNames() { assertEquals("Sum.PerKey", Sum.doublesPerKey().getName()); assertEquals("Sum.PerKey", Sum.longsPerKey().getName()); } + + @Test + public void testSumIntegerFn() { + checkCombineFn( + new Sum.SumIntegerFn(), + Lists.newArrayList(1, 2, 3, 4), + 10); + } + + @Test + public void testSumLongFn() { + checkCombineFn( + new Sum.SumLongFn(), + Lists.newArrayList(1L, 2L, 3L, 4L), + 10L); + } + + @Test + public void testSumDoubleFn() { + checkCombineFn( + new Sum.SumDoubleFn(), + Lists.newArrayList(1.0, 2.0, 3.0, 4.0), + 10.0); + } } From baa8e2f271b211a9ed153274c87c33fb6dc14476 Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 21 Jan 2016 14:37:32 -0800 Subject: [PATCH 024/751] Handle when Dataflow service tells us that values are sorted in GBK ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112725244 --- .../runners/worker/GroupingShuffleReader.java | 41 +++- .../worker/GroupingShuffleReaderFactory.java | 8 +- ...uffleReaderWithFaultyBytesReadCounter.java | 5 +- .../sdk/runners/worker/ShuffleSink.java | 20 +- .../dataflow/sdk/util/PropertyNames.java | 1 + .../worker/GroupingShuffleReaderTest.java | 182 +++++++++++------- .../sdk/runners/worker/ShuffleSinkTest.java | 7 +- .../sdk/runners/worker/TestShuffleReader.java | 69 +++++-- .../runners/worker/TestShuffleReaderTest.java | 84 ++++---- 9 files changed, 263 insertions(+), 154 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java index 46e4b85e4e..ee5b600b45 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java @@ -21,10 +21,12 @@ import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; +import static com.google.common.base.Preconditions.checkState; import com.google.api.services.dataflow.model.ApproximateReportedProgress; import com.google.api.services.dataflow.model.ApproximateSplitRequest; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.IterableCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; @@ -54,6 +56,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; @@ -80,7 +83,8 @@ public class GroupingShuffleReader extends NativeReader perOperationPerDatasetBytesCounter; Coder keyCoder; - Coder valueCoder; + Coder valueCoder; + @Nullable Coder secondaryKeyCoder; public GroupingShuffleReader( PipelineOptions options, @@ -90,7 +94,8 @@ public GroupingShuffleReader( Coder>>> coder, BatchModeExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, - String operationName) + String operationName, + boolean valuesAreSorted) throws Exception { this.shuffleReaderConfig = shuffleReaderConfig; this.startShufflePosition = startShufflePosition; @@ -98,7 +103,7 @@ public GroupingShuffleReader( this.executionContext = executionContext; this.addCounterMutator = addCounterMutator; this.operationName = operationName; - initCoder(coder); + initCoder(coder, valuesAreSorted); // We cannot initialize perOperationPerDatasetBytesCounter here, as it // depends on shuffleReaderConfig, which isn't populated yet. } @@ -131,7 +136,8 @@ public GroupingShuffleReaderIterator iterator() throws IOException { new ChunkingShuffleBatchReader(asr))); } - private void initCoder(Coder>>> coder) throws Exception { + private void initCoder(Coder>>> coder, + boolean valuesAreSorted) throws Exception { if (!(coder instanceof WindowedValueCoder)) { throw new Exception("unexpected kind of coder for WindowedValue: " + coder); } @@ -151,7 +157,17 @@ private void initCoder(Coder>>> coder) throws Ex + "a key-grouping shuffle"); } IterableCoder iterCoder = (IterableCoder) kvValueCoder; - this.valueCoder = iterCoder.getElemCoder(); + if (valuesAreSorted) { + checkState(iterCoder.getElemCoder() instanceof KvCoder, + "unexpected kind of coder for elements read from a " + + "key-grouping value sorting shuffle: %s", iterCoder.getElemCoder()); + @SuppressWarnings("rawtypes") + KvCoder valueKvCoder = (KvCoder) iterCoder.getElemCoder(); + this.secondaryKeyCoder = valueKvCoder.getKeyCoder(); + this.valueCoder = valueKvCoder.getValueCoder(); + } else { + this.valueCoder = iterCoder.getElemCoder(); + } } final GroupingShuffleReaderIterator iterator(ShuffleEntryReader reader) { @@ -390,7 +406,20 @@ public V next() { // notify the bytes that have been read so far. notifyValueReturned(currentGroupSize.getAndSet(0L)); try { - return CoderUtils.decodeFromByteArray(parentReader.valueCoder, entry.getValue()); + if (parentReader.secondaryKeyCoder != null) { + ByteArrayInputStream bais = new ByteArrayInputStream(entry.getSecondaryKey()); + @SuppressWarnings("unchecked") + V value = (V) KV.of( + // We ignore decoding the timestamp. + parentReader.secondaryKeyCoder.decode(bais, Context.NESTED), + CoderUtils.decodeFromByteArray(parentReader.valueCoder, entry.getValue())); + return value; + } else { + @SuppressWarnings("unchecked") + V value = (V) CoderUtils.decodeFromByteArray(parentReader.valueCoder, + entry.getValue()); + return value; + } } catch (IOException exn) { throw new RuntimeException(exn); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java index 602e27b24c..a0f1c9d73a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.runners.worker; import static com.google.api.client.util.Base64.decodeBase64; +import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; import static com.google.cloud.dataflow.sdk.util.Structs.getString; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -39,7 +40,6 @@ * Creates a GroupingShuffleReader from a CloudObject spec. */ public class GroupingShuffleReaderFactory implements ReaderFactory { - @Override public NativeReader create( CloudObject spec, @@ -69,7 +69,8 @@ public GroupingShuffleReader createTyped( decodeBase64(getString(spec, PropertyNames.SHUFFLE_READER_CONFIG)), getString(spec, PropertyNames.START_SHUFFLE_POSITION, null), getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), coder, - (BatchModeExecutionContext) executionContext, addCounterMutator, operationName); + (BatchModeExecutionContext) executionContext, addCounterMutator, operationName, + getBoolean(spec, PropertyNames.SORT_VALUES, false)); } return new GroupingShuffleReader(options, @@ -78,7 +79,8 @@ public GroupingShuffleReader createTyped( getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), coder, (BatchModeExecutionContext) executionContext, - addCounterMutator, operationName); + addCounterMutator, operationName, + getBoolean(spec, PropertyNames.SORT_VALUES, false)); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java index df10ece465..d4a4170f72 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java @@ -47,10 +47,11 @@ public GroupingShuffleReaderWithFaultyBytesReadCounter( Coder>>> coder, BatchModeExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, - String operationName) + String operationName, + boolean sortValues) throws Exception { super(options, shuffleReaderConfig, startShufflePosition, stopShufflePosition, coder, - executionContext, addCounterMutator, operationName); + executionContext, addCounterMutator, operationName, sortValues); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java index 86cb099b88..793ed61bde 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.InstantCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; @@ -36,6 +37,7 @@ import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.base.Preconditions; +import java.io.ByteArrayOutputStream; import java.io.IOException; /** @@ -220,14 +222,18 @@ public long add(WindowedValue windowedElem) throws IOException { Object sortKey = kvValue.getKey(); Object sortValue = kvValue.getValue(); - // TODO: Need to coordinate with the - // GroupingShuffleReader, to make sure it knows how to - // reconstruct the value from the sortKeyBytes and - // sortValueBytes. Right now, it doesn't know between - // sorting and non-sorting GBKs. - secondaryKeyBytes = CoderUtils.encodeToByteArray(sortKeyCoder, sortKey); + // Sort values by key and then timestamp so that any GroupAlsoByWindows + // can run more efficiently. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + sortKeyCoder.encode(sortKey, baos, Context.NESTED); + if (!windowedElem.getTimestamp().equals(BoundedWindow.TIMESTAMP_MIN_VALUE)) { + // Empty timestamp suffixes sort before all other sort value keys with + // the same prefix. So We can omit this suffix for this common value here + // for efficiency and only encode when its not the minimum timestamp. + InstantCoder.of().encode(windowedElem.getTimestamp(), baos, Context.OUTER); + } + secondaryKeyBytes = baos.toByteArray(); valueBytes = CoderUtils.encodeToByteArray(sortValueCoder, sortValue); - } else if (groupValues) { // Sort values by timestamp so that GroupAlsoByWindows can run efficiently. if (windowedElem.getTimestamp().equals(BoundedWindow.TIMESTAMP_MIN_VALUE)) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java index 6fbb6bdefa..5a7ff3d881 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java @@ -84,6 +84,7 @@ public class PropertyNames { public static final String SHUFFLE_KIND = "shuffle_kind"; public static final String SHUFFLE_READER_CONFIG = "shuffle_reader_config"; public static final String SHUFFLE_WRITER_CONFIG = "shuffle_writer_config"; + public static final String SORT_VALUES = "sort_values"; public static final String START_INDEX = "start_index"; public static final String START_OFFSET = "start_offset"; public static final String START_SHUFFLE_POSITION = "start_shuffle_position"; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java index 798a08b016..5fa96599af 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java @@ -37,10 +37,10 @@ import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.IterableCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.worker.GroupingShuffleReader.GroupingShuffleReaderIterator; +import com.google.cloud.dataflow.sdk.runners.worker.ShuffleSink.ShuffleKind; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; @@ -79,18 +79,24 @@ */ @RunWith(JUnit4.class) public class GroupingShuffleReaderTest { - private static final List>> NO_KVS = Collections.emptyList(); + private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; + private static final List>>> NO_KVS = + Collections.emptyList(); private static final Instant timestamp = new Instant(123000); private static final IntervalWindow window = new IntervalWindow(timestamp, timestamp.plus(1000)); - // As Shuffle records, {@code KVS} is encoded as 10 records. Each records uses an integer as key - // (4 bytes), and a length-prefixed string as value (4 bytes + length of utf8-encoded string). - // Overall {@code KVS} has a byte size of 17 + 17 + 17 + 17 + 16 + 17 + 17 + 17 + 17 + 16 = 168. - private static final List>> KVS = Arrays.asList( - KV.of(1, Arrays.asList("in 1a", "in 1b")), KV.of(2, Arrays.asList("in 2a", "in 2b")), - KV.of(3, Arrays.asList("in 3")), KV.of(4, Arrays.asList("in 4a", "in 4b", "in 4c", "in 4d")), - KV.of(5, Arrays.asList("in 5"))); + // As Shuffle records, {@code KV} is encoded as 10 records. Each records uses an integer as key + // (4 bytes), and a {@code KV} of an integer key and value (each 4 bytes). + // Overall {@code KV}s have a byte size of 25 * 4 = 100. Note that we also encode the + // timestamp into the secondary key adding another 100 bytes. + private static final List>>> KVS = Arrays.asList( + KV.of(1, Arrays.asList(KV.of(1, 11), KV.of(2, 12))), + KV.of(2, Arrays.asList(KV.of(1, 21), KV.of(2, 22))), + KV.of(3, Arrays.asList(KV.of(1, 31))), + KV.of(4, Arrays.asList(KV.of(1, 41), KV.of(2, 42), + KV.of(3, 43), KV.of(4, 44))), + KV.of(5, Arrays.asList(KV.of(1, 51)))); /** How many of the values with each key are to be read. * Note that the order matters as the conversion to ordinal is used below. @@ -108,25 +114,31 @@ private enum ValuesToRead { READ_ALL_VALUES_TWICE } - private List writeShuffleEntries(List>> input) + private List writeShuffleEntries( + List>>> input, boolean sortValues) throws Exception { - Coder>> sinkElemCoder = WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of()), IntervalWindow.getCoder()); + Coder>>> sinkElemCoder = + WindowedValue.getFullCoder( + KvCoder.of(BigEndianIntegerCoder.of(), + KvCoder.of(BigEndianIntegerCoder.of(), + BigEndianIntegerCoder.of())), + IntervalWindow.getCoder()); CounterSet.AddCounterMutator addCounterMutator = new CounterSet().getAddCounterMutator(); // Write to shuffle with GROUP_KEYS ShuffleSink. - ShuffleSink> shuffleSink = - new ShuffleSink<>(PipelineOptionsFactory.create(), null, ShuffleSink.ShuffleKind.GROUP_KEYS, + ShuffleSink>> shuffleSink = + new ShuffleSink<>(PipelineOptionsFactory.create(), null, + sortValues ? ShuffleKind.GROUP_KEYS_AND_SORT_VALUES : ShuffleKind.GROUP_KEYS, sinkElemCoder, addCounterMutator); TestShuffleWriter shuffleWriter = new TestShuffleWriter(); int kvCount = 0; List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter>> shuffleSinkWriter = + try (Sink.SinkWriter>>> shuffleSinkWriter = shuffleSink.writer(shuffleWriter, "dataset")) { - for (KV> kvs : input) { + for (KV>> kvs : input) { Integer key = kvs.getKey(); - for (String value : kvs.getValue()) { + for (KV value : kvs.getValue()) { ++kvCount; actualSizes.add(shuffleSinkWriter.add(WindowedValue.of( KV.of(key, value), timestamp, Lists.newArrayList(window), PaneInfo.NO_FIRING))); @@ -139,24 +151,25 @@ private List writeShuffleEntries(List>> i return records; } - private List>> runIterationOverGroupingShuffleReader( + private List>>> runIterationOverGroupingShuffleReader( BatchModeExecutionContext context, TestShuffleReader shuffleReader, - GroupingShuffleReader groupingShuffleReader, - Coder>>> coder, ValuesToRead valuesToRead) - throws Exception { + GroupingShuffleReader> groupingShuffleReader, + Coder>>>> coder, + ValuesToRead valuesToRead) throws Exception { Counter elementByteSizeCounter = Counter.longs("element-byte-size-counter", SUM); ElementByteSizeObserver elementObserver = new ElementByteSizeObserver(elementByteSizeCounter); - List>> actual = new ArrayList<>(); - try (GroupingShuffleReaderIterator iter = - groupingShuffleReader.iterator(shuffleReader)) { - Iterable prevValuesIterable = null; - Iterator prevValuesIterator = null; + List>>> actual = new ArrayList<>(); + try (GroupingShuffleReaderIterator> iter = + groupingShuffleReader.iterator(shuffleReader)) { + Iterable> prevValuesIterable = null; + Iterator> prevValuesIterator = null; while (iter.hasNext()) { assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); @SuppressWarnings({"rawtypes", "unchecked"}) // safe co-variant cast. - WindowedValue>> windowedValue = (WindowedValue) iter.next(); + WindowedValue>>> windowedValue = + (WindowedValue) iter.next(); // Verify that the byte size observer is lazy for every value the GroupingShuffleReader // produces. coder.registerByteSizeObserver(windowedValue, elementObserver, Context.OUTER); @@ -166,9 +179,9 @@ private List>> runIterationOverGroupingShuffleReader( assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, windowedValue.getTimestamp()); assertEquals(0, windowedValue.getWindows().size()); - KV> elem = windowedValue.getValue(); + KV>> elem = windowedValue.getValue(); Integer key = elem.getKey(); - List values = new ArrayList<>(); + List> values = new ArrayList<>(); if (valuesToRead.ordinal() > ValuesToRead.SKIP_VALUES.ordinal()) { if (prevValuesIterable != null) { prevValuesIterable.iterator(); // Verifies that this does not throw. @@ -177,8 +190,8 @@ private List>> runIterationOverGroupingShuffleReader( prevValuesIterator.hasNext(); // Verifies that this does not throw. } - Iterable valuesIterable = elem.getValue(); - Iterator valuesIterator = valuesIterable.iterator(); + Iterable> valuesIterable = elem.getValue(); + Iterator> valuesIterator = valuesIterable.iterator(); if (valuesToRead.ordinal() >= ValuesToRead.READ_ONE_VALUE.ordinal()) { while (valuesIterator.hasNext()) { @@ -242,19 +255,23 @@ private List>> runIterationOverGroupingShuffleReader( } private void runTestReadFromShuffle( - List>> input, ValuesToRead valuesToRead) throws Exception { - Coder>>> sourceElemCoder = + List>>> input, boolean sortValues, + ValuesToRead valuesToRead) throws Exception { + Coder>>>> sourceElemCoder = WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(StringUtf8Coder.of())), + KvCoder.of(BigEndianIntegerCoder.of(), + IterableCoder.of(KvCoder.of(BigEndianIntegerCoder.of(), + BigEndianIntegerCoder.of()))), IntervalWindow.getCoder()); - List records = writeShuffleEntries(input); + List records = writeShuffleEntries(input, sortValues); PipelineOptions options = PipelineOptionsFactory.create(); // Read from shuffle with GroupingShuffleReader. BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - GroupingShuffleReader groupingShuffleReader = new GroupingShuffleReader<>( - options, null, null, null, sourceElemCoder, context, null, null); + GroupingShuffleReader> groupingShuffleReader = + new GroupingShuffleReader<>( + options, null, null, null, sourceElemCoder, context, null, null, sortValues); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(groupingShuffleReader); @@ -265,15 +282,15 @@ private void runTestReadFromShuffle( shuffleReader.addEntry(record); } - List>> actual = runIterationOverGroupingShuffleReader( + List>>> actual = runIterationOverGroupingShuffleReader( context, shuffleReader, groupingShuffleReader, sourceElemCoder, valuesToRead); - List>> expected = new ArrayList<>(); - for (KV> kvs : input) { + List>>> expected = new ArrayList<>(); + for (KV>> kvs : input) { Integer key = kvs.getKey(); - List values = new ArrayList<>(); + List> values = new ArrayList<>(); if (valuesToRead.ordinal() >= ValuesToRead.READ_ONE_VALUE.ordinal()) { - for (String value : kvs.getValue()) { + for (KV value : kvs.getValue()) { values.add(value); if (valuesToRead == ValuesToRead.READ_ONE_VALUE) { break; @@ -288,60 +305,70 @@ private void runTestReadFromShuffle( @Test public void testReadEmptyShuffleData() throws Exception { - runTestReadFromShuffle(NO_KVS, ValuesToRead.READ_ALL_VALUES); + runTestReadFromShuffle(NO_KVS, false /* do not sort values */, ValuesToRead.READ_ALL_VALUES); + runTestReadFromShuffle(NO_KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES); } @Test public void testReadEmptyShuffleDataSkippingValues() throws Exception { - runTestReadFromShuffle(NO_KVS, ValuesToRead.SKIP_VALUES); + runTestReadFromShuffle(NO_KVS, false /* do not sort values */, ValuesToRead.SKIP_VALUES); + runTestReadFromShuffle(NO_KVS, true /* sort values */, ValuesToRead.SKIP_VALUES); } @Test public void testReadNonEmptyShuffleData() throws Exception { - runTestReadFromShuffle(KVS, ValuesToRead.READ_ALL_VALUES); + runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_ALL_VALUES); + runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES); } @Test public void testReadNonEmptyShuffleDataTwice() throws Exception { - runTestReadFromShuffle(KVS, ValuesToRead.READ_ALL_VALUES_TWICE); + runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_ALL_VALUES_TWICE); + runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES_TWICE); } @Test public void testReadNonEmptyShuffleDataReadingOneValue() throws Exception { - runTestReadFromShuffle(KVS, ValuesToRead.READ_ONE_VALUE); + runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_ONE_VALUE); + runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_ONE_VALUE); } @Test public void testReadNonEmptyShuffleDataReadingNoValues() throws Exception { - runTestReadFromShuffle(KVS, ValuesToRead.READ_NO_VALUES); + runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_NO_VALUES); + runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_NO_VALUES); } @Test public void testReadNonEmptyShuffleDataSkippingValues() throws Exception { - runTestReadFromShuffle(KVS, ValuesToRead.SKIP_VALUES); + runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.SKIP_VALUES); + runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.SKIP_VALUES); } private void runTestBytesReadCounter( - List>> input, ValuesToRead valuesToRead, - long expectedReadBytes) throws Exception { + List>>> input, boolean useSecondaryKey, + ValuesToRead valuesToRead, long expectedReadBytes) throws Exception { // Create a shuffle reader with the shuffle values provided as input. - List records = writeShuffleEntries(input); + List records = writeShuffleEntries(input, useSecondaryKey); TestShuffleReader shuffleReader = new TestShuffleReader(); for (ShuffleEntry record : records) { shuffleReader.addEntry(record); } - Coder>>> sourceElemCoder = + Coder>>>> sourceElemCoder = WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(StringUtf8Coder.of())), + KvCoder.of(BigEndianIntegerCoder.of(), + IterableCoder.of(KvCoder.of(BigEndianIntegerCoder.of(), + BigEndianIntegerCoder.of()))), IntervalWindow.getCoder()); PipelineOptions options = PipelineOptionsFactory.create(); CounterSet.AddCounterMutator addCounterMutator = new CounterSet().getAddCounterMutator(); // Read from shuffle with GroupingShuffleReader. BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - GroupingShuffleReader groupingShuffleReader = new GroupingShuffleReader<>( - options, null, null, null, sourceElemCoder, context, null, null); + GroupingShuffleReader> groupingShuffleReader = + new GroupingShuffleReader<>( + options, null, null, null, sourceElemCoder, context, null, null, useSecondaryKey); groupingShuffleReader.perOperationPerDatasetBytesCounter = addCounterMutator.addCounter(Counter.longs("dax-shuffle-test-wf-read-bytes", SUM)); @@ -354,27 +381,35 @@ private void runTestBytesReadCounter( @Test public void testBytesReadNonEmptyShuffleData() throws Exception { - runTestBytesReadCounter(KVS, ValuesToRead.READ_ALL_VALUES, 168L); + runTestBytesReadCounter(KVS, false /* do not sort values */, + ValuesToRead.READ_ALL_VALUES, 200L); + runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES, 200L); } @Test public void testBytesReadNonEmptyShuffleDataTwice() throws Exception { - runTestBytesReadCounter(KVS, ValuesToRead.READ_ALL_VALUES_TWICE, 168L); + runTestBytesReadCounter(KVS, false /* do not sort values */, + ValuesToRead.READ_ALL_VALUES_TWICE, 200L); + runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES_TWICE, 200L); } @Test public void testBytesReadNonEmptyShuffleDataReadingOneValue() throws Exception { - runTestBytesReadCounter(KVS, ValuesToRead.READ_ONE_VALUE, 168L); + runTestBytesReadCounter(KVS, false /* do not sort values */, ValuesToRead.READ_ONE_VALUE, 200L); + runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.READ_ONE_VALUE, 200L); } @Test public void testBytesReadNonEmptyShuffleDataSkippingValues() throws Exception { - runTestBytesReadCounter(KVS, ValuesToRead.SKIP_VALUES, 168L); + runTestBytesReadCounter(KVS, false /* do not sort values */, ValuesToRead.SKIP_VALUES, 200L); + runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.SKIP_VALUES, 200L); } @Test public void testBytesReadEmptyShuffleData() throws Exception { - runTestBytesReadCounter(NO_KVS, ValuesToRead.READ_ALL_VALUES, 0L); + runTestBytesReadCounter(NO_KVS, false /* do not sort values */, + ValuesToRead.READ_ALL_VALUES, 0L); + runTestBytesReadCounter(NO_KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES, 0L); } static byte[] fabricatePosition(int shard) throws Exception { @@ -405,7 +440,8 @@ public void testReadFromShuffleDataAndFailToSplit() throws Exception { final int kNumRecords = 2; for (int i = 0; i < kNumRecords; ++i) { byte[] key = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - shuffleReader.addEntry(new ShuffleEntry(fabricatePosition(kFirstShard, key), key, null, key)); + shuffleReader.addEntry( + new ShuffleEntry(fabricatePosition(kFirstShard, key), key, EMPTY_BYTE_ARRAY, key)); } // Note that TestShuffleReader start/end positions are in the @@ -417,7 +453,7 @@ public void testReadFromShuffleDataAndFailToSplit() throws Exception { WindowedValue.getFullCoder( KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(BigEndianIntegerCoder.of())), IntervalWindow.getCoder()), - context, null, null); + context, null, null, false /* do not sort values */); try (GroupingShuffleReaderIterator iter = groupingShuffleReader.iterator(shuffleReader)) { @@ -464,7 +500,8 @@ public void testRemainingParallelism() throws Exception { final int kNumRecords = 5; for (int i = 0; i < kNumRecords; ++i) { byte[] key = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - ShuffleEntry entry = new ShuffleEntry(fabricatePosition(kFirstShard, i), key, null, key); + ShuffleEntry entry = new ShuffleEntry( + fabricatePosition(kFirstShard, i), key, EMPTY_BYTE_ARRAY, key); shuffleReader.addEntry(entry); } @@ -480,7 +517,8 @@ public void testRemainingParallelism() throws Exception { IntervalWindow.getCoder()), context, null, - null); + null, + false /* do not sort values */); try (GroupingShuffleReaderIterator iter = groupingShuffleReader.iterator(shuffleReader)) { @@ -535,7 +573,7 @@ public void testReadFromShuffleAndDynamicSplit() throws Exception { WindowedValue.getFullCoder( KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(BigEndianIntegerCoder.of())), IntervalWindow.getCoder()), - context, null, null); + context, null, null, false /* do not sort values */); groupingShuffleReader.perOperationPerDatasetBytesCounter = addCounterMutator.addCounter(Counter.longs("dax-shuffle-test-wf-read-bytes", SUM)); @@ -549,16 +587,16 @@ public void testReadFromShuffleAndDynamicSplit() throws Exception { // therefore each record comes with a unique position constructed. for (int i = 0; i < kNumRecords; ++i) { byte[] keyByte = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - ShuffleEntry entry = - new ShuffleEntry(fabricatePosition(kFirstShard, keyByte), keyByte, null, keyByte); + ShuffleEntry entry = new ShuffleEntry( + fabricatePosition(kFirstShard, keyByte), keyByte, EMPTY_BYTE_ARRAY, keyByte); shuffleReader.addEntry(entry); } for (int i = kNumRecords; i < 2 * kNumRecords; ++i) { byte[] keyByte = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - ShuffleEntry entry = - new ShuffleEntry(fabricatePosition(kSecondShard, keyByte), keyByte, null, keyByte); + ShuffleEntry entry = new ShuffleEntry( + fabricatePosition(kSecondShard, keyByte), keyByte, EMPTY_BYTE_ARRAY, keyByte); shuffleReader.addEntry(entry); } @@ -626,7 +664,7 @@ public void testGetApproximateProgress() throws Exception { WindowedValue.getFullCoder( KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(BigEndianIntegerCoder.of())), IntervalWindow.getCoder()), - context, null, null); + context, null, null, false /* do not sort values */); TestShuffleReader shuffleReader = new TestShuffleReader(); final int kNumRecords = 10; @@ -635,7 +673,7 @@ public void testGetApproximateProgress() throws Exception { byte[] position = fabricatePosition(i); byte[] keyByte = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); positionsList.add(position); - ShuffleEntry entry = new ShuffleEntry(position, keyByte, null, keyByte); + ShuffleEntry entry = new ShuffleEntry(position, keyByte, EMPTY_BYTE_ARRAY, keyByte); shuffleReader.addEntry(entry); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java index 9a4eaa8965..c4f2ea03b5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.TestUtils; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.InstantCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; @@ -42,6 +43,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -206,9 +208,8 @@ void runTestWriteGroupingSortingShuffleSink( Integer key = CoderUtils.decodeFromByteArray(BigEndianIntegerCoder.of(), keyBytes); - String sortKey = - CoderUtils.decodeFromByteArray(StringUtf8Coder.of(), - sortKeyBytes); + ByteArrayInputStream bais = new ByteArrayInputStream(sortKeyBytes); + String sortKey = StringUtf8Coder.of().decode(bais, Context.NESTED); Integer sortValue = CoderUtils.decodeFromByteArray(BigEndianIntegerCoder.of(), valueBytes); actual.add(KV.of(key, KV.of(sortKey, sortValue))); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java index 4aba127e04..34bbead2bf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java @@ -20,7 +20,6 @@ import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntryReader; import com.google.cloud.dataflow.sdk.util.common.worker.ShufflePosition; -// TODO: Decide how we want to handle this Guava dependency. import com.google.common.primitives.UnsignedBytes; import org.junit.Assert; @@ -40,31 +39,44 @@ * A fake implementation of a ShuffleEntryReader, for testing. */ public class TestShuffleReader implements ShuffleEntryReader { - static final Comparator SHUFFLE_KEY_COMPARATOR = - UnsignedBytes.lexicographicalComparator(); - final NavigableMap> records; + // Sorts by secondary key where an empty secondary key sorts before all other secondary keys. + static final Comparator SHUFFLE_KEY_COMPARATOR = new Comparator() { - public TestShuffleReader(NavigableMap> records) { - this.records = records; - } + @Override + public int compare(byte[] o1, byte[] o2) { + if (o1 == o2) { + return 0; + } + if (o1 == null) { + return -1; + } + if (o2 == null) { + return 1; + } + return UnsignedBytes.lexicographicalComparator().compare(o1, o2); + } + }; - public TestShuffleReader() { - this(new TreeMap>(SHUFFLE_KEY_COMPARATOR)); - } + final NavigableMap>> records; - public void addEntry(String key, String value) { - addEntry(key.getBytes(), value.getBytes()); + public TestShuffleReader() { + this.records = new TreeMap<>(SHUFFLE_KEY_COMPARATOR); } - public void addEntry(byte[] key, byte[] value) { - addEntry(new ShuffleEntry(key, null, value)); + public void addEntry(String key, String secondaryKey, String value) { + addEntry(new ShuffleEntry(key.getBytes(), secondaryKey.getBytes(), value.getBytes())); } public void addEntry(ShuffleEntry entry) { - List values = records.get(entry.getKey()); + NavigableMap> valuesBySecondaryKey = records.get(entry.getKey()); + if (valuesBySecondaryKey == null) { + valuesBySecondaryKey = new TreeMap<>(SHUFFLE_KEY_COMPARATOR); + records.put(entry.getKey(), valuesBySecondaryKey); + } + List values = valuesBySecondaryKey.get(entry.getSecondaryKey()); if (values == null) { values = new ArrayList<>(); - records.put(entry.getKey(), values); + valuesBySecondaryKey.put(entry.getSecondaryKey(), values); } values.add(entry); } @@ -90,11 +102,12 @@ public Reiterator read(String startKey, String endKey) { } class ShuffleReaderIterator implements Reiterator { - final Iterator>> recordsIter; + final Iterator>>> recordsIter; final byte[] startKey; final byte[] endKey; byte[] currentKey; - Map.Entry> currentRecord; + byte[] currentSecondaryKey; + Map.Entry>> currentRecord; ListIterator currentValuesIter; public ShuffleReaderIterator(byte[] startKey, byte[] endKey) { @@ -116,8 +129,9 @@ private ShuffleReaderIterator(ShuffleReaderIterator it) { this.currentKey = it.currentKey; this.currentRecord = it.currentRecord; if (it.currentValuesIter != null) { + this.currentSecondaryKey = it.currentSecondaryKey; this.currentValuesIter = - it.currentRecord.getValue().listIterator( + it.currentRecord.getValue().get(currentSecondaryKey).listIterator( it.currentValuesIter.nextIndex()); } else { this.currentValuesIter = null; @@ -137,7 +151,7 @@ public ShuffleEntry next() { ShuffleEntry resultValue = currentValuesIter.next(); Assert.assertTrue(Arrays.equals(currentKey, resultValue.getKey())); if (!currentValuesIter.hasNext()) { - advanceKey(); + advanceSecondaryKey(); } return resultValue; } @@ -152,6 +166,17 @@ public Reiterator copy() { return new ShuffleReaderIterator(this); } + private void advanceSecondaryKey() { + NavigableMap> tailMap = + currentRecord.getValue().tailMap(currentSecondaryKey, false /* do not include key */); + if (tailMap.isEmpty()) { + advanceKey(); + } else { + currentSecondaryKey = tailMap.firstKey(); + currentValuesIter = tailMap.get(currentSecondaryKey).listIterator(); + } + } + private void advanceKey() { while (recordsIter.hasNext()) { currentRecord = recordsIter.next(); @@ -167,10 +192,12 @@ private void advanceKey() { break; } // In range. - currentValuesIter = currentRecord.getValue().listIterator(); + currentSecondaryKey = currentRecord.getValue().firstKey(); + currentValuesIter = currentRecord.getValue().get(currentSecondaryKey).listIterator(); return; } currentKey = null; + currentSecondaryKey = null; currentValuesIter = null; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java index 7c349108ce..f4b87bc01b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java @@ -16,20 +16,21 @@ package com.google.cloud.dataflow.sdk.runners.worker; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; +import com.google.cloud.dataflow.sdk.values.KV; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.NoSuchElementException; /** @@ -40,71 +41,74 @@ public class TestShuffleReaderTest { static final String START_KEY = "ddd"; static final String END_KEY = "mmm"; - static final List> NO_ENTRIES = + static final List>> NO_ENTRIES = Collections.emptyList(); - static final List> IN_RANGE_ENTRIES = - Arrays.>asList( - new SimpleEntry<>("ddd", "in 1"), - new SimpleEntry<>("ddd", "in 1"), - new SimpleEntry<>("ddd", "in 1"), - new SimpleEntry<>("dddd", "in 2"), - new SimpleEntry<>("dddd", "in 2"), - new SimpleEntry<>("de", "in 3"), - new SimpleEntry<>("ee", "in 4"), - new SimpleEntry<>("ee", "in 4"), - new SimpleEntry<>("ee", "in 4"), - new SimpleEntry<>("ee", "in 4"), - new SimpleEntry<>("mm", "in 5")); - static final List> BEFORE_RANGE_ENTRIES = - Arrays.>asList( - new SimpleEntry<>("", "out 1"), - new SimpleEntry<>("dd", "out 2")); - static final List> AFTER_RANGE_ENTRIES = - Arrays.>asList( - new SimpleEntry<>("mmm", "out 3"), - new SimpleEntry<>("mmm", "out 3"), - new SimpleEntry<>("mmmm", "out 4"), - new SimpleEntry<>("mn", "out 5"), - new SimpleEntry<>("zzz", "out 6")); - static final List> OUT_OF_RANGE_ENTRIES = + static final List>> IN_RANGE_ENTRIES = + Arrays.>>asList( + KV.of("ddd", KV.of("1", "in 1")), + KV.of("ddd", KV.of("2", "in 1")), + KV.of("ddd", KV.of("3", "in 1")), + KV.of("dddd", KV.of("1", "in 2")), + KV.of("dddd", KV.of("2", "in 2")), + KV.of("de", KV.of("1", "in 3")), + KV.of("ee", KV.of("1", "in 4")), + KV.of("ee", KV.of("2", "in 4")), + KV.of("ee", KV.of("3", "in 4")), + KV.of("ee", KV.of("4", "in 4")), + KV.of("mm", KV.of("1", "in 5"))); + static final List>> BEFORE_RANGE_ENTRIES = + Arrays.>>asList( + KV.of("", KV.of("1", "out 1")), + KV.of("dd", KV.of("1", "out 2"))); + static final List>> AFTER_RANGE_ENTRIES = + Arrays.>>asList( + KV.of("mmm", KV.of("1", "out 3")), + KV.of("mmm", KV.of("2", "out 3")), + KV.of("mmmm", KV.of("1", "out 4")), + KV.of("mn", KV.of("1", "out 5")), + KV.of("zzz", KV.of("1", "out 6"))); + static final List>> OUT_OF_RANGE_ENTRIES = new ArrayList<>(); static { OUT_OF_RANGE_ENTRIES.addAll(BEFORE_RANGE_ENTRIES); OUT_OF_RANGE_ENTRIES.addAll(AFTER_RANGE_ENTRIES); } - static final List> ALL_ENTRIES = new ArrayList<>(); + static final List>> ALL_ENTRIES = new ArrayList<>(); static { ALL_ENTRIES.addAll(BEFORE_RANGE_ENTRIES); ALL_ENTRIES.addAll(IN_RANGE_ENTRIES); ALL_ENTRIES.addAll(AFTER_RANGE_ENTRIES); } - void runTest(List> expected, - List> outOfRange, + void runTest(List>> expected, + List>> outOfRange, String startKey, String endKey) { TestShuffleReader shuffleReader = new TestShuffleReader(); - List> expectedCopy = new ArrayList<>(expected); + List>> expectedCopy = new ArrayList<>(expected); expectedCopy.addAll(outOfRange); Collections.shuffle(expectedCopy); - for (Map.Entry entry : expectedCopy) { - shuffleReader.addEntry(entry.getKey(), entry.getValue()); + for (KV> entry : expectedCopy) { + shuffleReader.addEntry(entry.getKey(), + entry.getValue().getKey() /* secondary key */, + entry.getValue().getValue()); } Iterator iter = shuffleReader.read(startKey, endKey); - List> actual = new ArrayList<>(); + List>> actual = new ArrayList<>(); while (iter.hasNext()) { ShuffleEntry entry = iter.next(); - actual.add(new SimpleEntry<>(new String(entry.getKey()), - new String(entry.getValue()))); + actual.add(KV.of(new String(entry.getKey()), + KV.of(new String(entry.getSecondaryKey()), + new String(entry.getValue())))); } try { iter.next(); - Assert.fail("should have failed"); + fail("should have failed"); } catch (NoSuchElementException exn) { // Success. } - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } @Test From c41d15418d1664b28a3e6c8d43c5ae0fd71c762d Mon Sep 17 00:00:00 2001 From: kirpichov Date: Thu, 21 Jan 2016 15:13:17 -0800 Subject: [PATCH 025/751] Continues unifying ReaderIterator and Source.Reader * Flattens the ReaderIterator hierarchy a bit: removes Abstract{Bounded,}ReaderIterator, instead merges them all into LegacyReaderIterator directly. * Converts InMemoryReaderIterator, PubsubReaderIterator, UngroupedWindmillReaderIterator, ConcatIterator, and a couple of anonymous classes to the new interface. File-based and shuffle readers remain. * Extracts a common base class from Pubsub and UngroupedWindmill readers. * Converts most call sites that could use Source.Reader instead of ReaderIterator to use either Source.Reader, or the concrete class of the reader, to ease future conversion. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112728940 --- .../sdk/runners/worker/AvroByteReader.java | 5 +- .../sdk/runners/worker/AvroReader.java | 5 +- .../sdk/runners/worker/BigQueryReader.java | 4 +- .../sdk/runners/worker/ConcatReader.java | 55 ++++-- .../runners/worker/GroupingShuffleReader.java | 3 +- .../sdk/runners/worker/InMemoryReader.java | 80 ++++++--- .../runners/worker/InMemoryReaderFactory.java | 7 +- .../sdk/runners/worker/IsmReader.java | 11 +- .../worker/LazyMultiReaderIterator.java | 3 +- .../worker/PartitioningShuffleReader.java | 4 +- .../sdk/runners/worker/PubsubReader.java | 25 +-- .../sdk/runners/worker/TextReader.java | 3 +- .../worker/UngroupedShuffleReader.java | 3 +- .../worker/UngroupedWindmillReader.java | 25 +-- .../worker/WindmillReaderIteratorBase.java | 71 ++++++++ .../worker/WindowingWindmillReader.java | 29 ++- .../cloud/dataflow/sdk/util/Structs.java | 14 +- .../worker/AbstractBoundedReaderIterator.java | 57 ------ .../sdk/util/common/worker/NativeReader.java | 90 +++++----- .../runners/dataflow/CustomSourcesTest.java | 10 +- .../runners/worker/AvroByteReaderTest.java | 3 +- .../sdk/runners/worker/AvroReaderTest.java | 2 +- .../sdk/runners/worker/ConcatReaderTest.java | 60 ++++--- .../runners/worker/InMemoryReaderTest.java | 169 +++++++++++++----- .../sdk/runners/worker/ReaderFactoryTest.java | 33 ++-- .../sdk/runners/worker/TextReaderTest.java | 4 +- .../WindmillReaderIteratorBaseTest.java | 97 ++++++++++ .../cloud/dataflow/sdk/util/StructsTest.java | 11 ++ .../util/common/worker/ExecutorTestUtils.java | 37 ++-- .../util/common/worker/ReadOperationTest.java | 82 ++++++--- 30 files changed, 641 insertions(+), 361 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/AbstractBoundedReaderIterator.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java index 5c6b4c036b..4f73a0503a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import org.apache.avro.Schema; @@ -51,11 +50,11 @@ public AvroByteReader(String filename, @Nullable Long startPosition, @Nullable L } @Override - public NativeReaderIterator iterator() throws IOException { + public AvroByteFileIterator iterator() throws IOException { return new AvroByteFileIterator(); } - class AvroByteFileIterator extends AbstractBoundedReaderIterator { + class AvroByteFileIterator extends LegacyReaderIterator { private final LegacyReaderIterator> avroFileIterator; public AvroByteFileIterator() throws IOException { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java index af46561cae..725ebec9ef 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java @@ -26,7 +26,6 @@ import com.google.cloud.dataflow.sdk.io.OffsetBasedSource; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import org.apache.avro.generic.GenericRecord; @@ -78,7 +77,7 @@ public AvroReader(String filename, @Nullable Long startPosition, @Nullable Long } @Override - public LegacyReaderIterator> iterator() throws IOException { + public AvroFileIterator iterator() throws IOException { Long endPosition = this.endPosition; Long startPosition = this.startPosition; if (endPosition == null) { @@ -99,7 +98,7 @@ public LegacyReaderIterator> iterator() throws IOException { return new AvroFileIterator((AvroSource.AvroReader) reader); } - class AvroFileIterator extends AbstractBoundedReaderIterator> { + class AvroFileIterator extends LegacyReaderIterator> { final AvroSource.AvroReader reader; boolean hasStarted = false; long blockOffset = -1; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java index dc3771c0ae..e03966059f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.common.annotations.VisibleForTesting; @@ -113,8 +112,7 @@ public BigQueryReaderIterator iterator() throws IOException { * A ReaderIterator that yields TableRow objects for each row of a BigQuery table. */ @VisibleForTesting - static class BigQueryReaderIterator - extends AbstractBoundedReaderIterator> { + static class BigQueryReaderIterator extends LegacyReaderIterator> { private BigQueryTableRowIterator rowIterator; public BigQueryReaderIterator(TableReference tableRef, Bigquery bigQueryClient) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java index 9323b4edd2..3ef0a9a9a2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java @@ -30,8 +30,8 @@ import com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.DataflowReaderProgress; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.slf4j.Logger; @@ -42,6 +42,8 @@ import java.util.List; import java.util.NoSuchElementException; +import javax.annotation.Nullable; + /** * A {@link NativeReader} that reads elements from a given set of encoded {@link Source}s. Creates * {@link NativeReader}s for sources lazily, i.e. only when elements from the particular @@ -96,7 +98,7 @@ public Iterator getSources() { } @Override - public LegacyReaderIterator iterator() throws IOException { + public ConcatIterator iterator() throws IOException { return new ConcatIterator( registry, options, @@ -106,16 +108,16 @@ public LegacyReaderIterator iterator() throws IOException { sources); } - private static class ConcatIterator extends AbstractBoundedReaderIterator { + @VisibleForTesting + static class ConcatIterator extends NativeReaderIterator { private int currentIteratorIndex = -1; - private LegacyReaderIterator currentIterator = null; + @Nullable private NativeReaderIterator currentIterator = null; private final List sources; private final PipelineOptions options; private final ExecutionContext executionContext; private final CounterSet.AddCounterMutator addCounterMutator; private final String operationName; private final OffsetRangeTracker rangeTracker; - private boolean isAtFirstRecordInCurrentSource = true; private final ReaderFactory.Registry registry; public ConcatIterator( @@ -135,16 +137,29 @@ public ConcatIterator( } @Override - protected boolean hasNextImpl() throws IOException { - for (;;) { - if (currentIterator != null && currentIterator.hasNext()) { - break; - } + public boolean start() throws IOException { + return advance(); + } + @Override + public boolean advance() throws IOException { + while (true) { + // Invariant: we call currentIterator.start() immediately when opening an iterator + // (below). So if currentIterator != null, then start() has already been called on it. + if (currentIterator != null && currentIterator.advance()) { + // Happy case: current iterator has a next record. + return true; + } + // Now current iterator is either non-existent or exhausted. + // Close it, and try opening a new one. if (currentIterator != null) { currentIterator.close(); + currentIterator = null; } + if (!rangeTracker.tryReturnRecordAt(true, currentIteratorIndex + 1)) { + return false; + } currentIteratorIndex++; if (currentIteratorIndex == sources.size()) { // All sources were read. @@ -158,20 +173,26 @@ protected boolean hasNextImpl() throws IOException { (NativeReader) registry.create( currentSource, options, executionContext, addCounterMutator, operationName); - currentIterator = (LegacyReaderIterator) currentReader.iterator(); - isAtFirstRecordInCurrentSource = true; + currentIterator = currentReader.iterator(); } catch (Exception e) { throw new IOException("Failed to create a reader for source: " + currentSource, e); } + if (!currentIterator.start()) { + currentIterator.close(); + currentIterator = null; + continue; + } + // Happy case: newly opened iterator has a first record. + return true; } - - return rangeTracker.tryReturnRecordAt(isAtFirstRecordInCurrentSource, currentIteratorIndex); } @Override - protected T nextImpl() throws IOException, NoSuchElementException { - isAtFirstRecordInCurrentSource = false; - return currentIterator.next(); + public T getCurrent() throws NoSuchElementException { + if (currentIterator == null) { + throw new NoSuchElementException(); + } + return currentIterator.getCurrent(); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java index ee5b600b45..19ab083a3b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java @@ -40,7 +40,6 @@ import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservableIterator; import com.google.cloud.dataflow.sdk.util.common.Reiterable; import com.google.cloud.dataflow.sdk.util.common.Reiterator; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; import com.google.cloud.dataflow.sdk.util.common.worker.GroupingShuffleEntryIterator; import com.google.cloud.dataflow.sdk.util.common.worker.KeyGroupedShuffleEntries; @@ -193,7 +192,7 @@ final GroupingShuffleReaderIterator iterator(ShuffleEntryReader reader) { */ @VisibleForTesting static final class GroupingShuffleReaderIterator - extends AbstractBoundedReaderIterator>>> { + extends LegacyReaderIterator>>> { // The enclosing GroupingShuffleReader. private final GroupingShuffleReader parentReader; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java index 56b999eced..ffcfa0ca4f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java @@ -20,22 +20,25 @@ import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; -import static java.lang.Math.min; +import static com.google.common.base.MoreObjects.firstNonNull; +import static com.google.common.base.Preconditions.checkArgument; import com.google.api.services.dataflow.model.ApproximateReportedProgress; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; +import java.util.NoSuchElementException; import javax.annotation.Nullable; @@ -52,26 +55,20 @@ public class InMemoryReader extends NativeReader { final int endIndex; final Coder coder; - public InMemoryReader(List encodedElements, @Nullable Long startIndex, - @Nullable Long endIndex, Coder coder) { + public InMemoryReader( + List encodedElements, + @Nullable Integer startIndex, + @Nullable Integer endIndex, + Coder coder) { + checkNotNull(encodedElements); this.encodedElements = encodedElements; int maxIndex = encodedElements.size(); - if (startIndex == null) { - this.startIndex = 0; - } else { - if (startIndex < 0) { - throw new IllegalArgumentException("start index should be >= 0"); - } - this.startIndex = (int) min(startIndex, maxIndex); - } - if (endIndex == null) { - this.endIndex = maxIndex; - } else { - if (endIndex < this.startIndex) { - throw new IllegalArgumentException("end index should be >= start index"); - } - this.endIndex = (int) min(endIndex, maxIndex); - } + this.startIndex = Math.min(maxIndex, firstNonNull(startIndex, 0)); + this.endIndex = Math.min(maxIndex, firstNonNull(endIndex, maxIndex)); + checkArgument(this.startIndex >= 0, "negative start index: " + startIndex); + checkArgument( + this.endIndex >= this.startIndex, + "end index before start: [" + this.startIndex + ", " + this.endIndex + ")"); this.coder = coder; } @@ -88,24 +85,45 @@ public double getTotalParallelism() { /** * A ReaderIterator that yields an in-memory list of elements. */ - class InMemoryReaderIterator extends AbstractBoundedReaderIterator { + class InMemoryReaderIterator extends NativeReaderIterator { @VisibleForTesting OffsetRangeTracker tracker; - private int nextIndex; + @Nullable private Integer lastReturnedIndex; + private T current; public InMemoryReaderIterator() { this.tracker = new OffsetRangeTracker(startIndex, endIndex); - this.nextIndex = startIndex; + this.lastReturnedIndex = null; } @Override - protected boolean hasNextImpl() { - return tracker.tryReturnRecordAt(true, nextIndex); + public boolean start() throws IOException { + Preconditions.checkState(lastReturnedIndex == null, "Already started"); + if (!tracker.tryReturnRecordAt(true, startIndex)) { + return false; + } + current = decode(encodedElements.get(startIndex)); + lastReturnedIndex = startIndex; + return true; } @Override - protected T nextImpl() throws IOException { - String encodedElementString = encodedElements.get(nextIndex++); + public boolean advance() throws IOException { + Preconditions.checkNotNull(lastReturnedIndex, "Not started"); + if (!tracker.tryReturnRecordAt(true, (long) lastReturnedIndex + 1)) { + return false; + } + ++lastReturnedIndex; + current = decode(encodedElements.get(lastReturnedIndex)); + return true; + } + + @Override + public T getCurrent() throws NoSuchElementException { + return current; + } + + private T decode(String encodedElementString) throws CoderException { // TODO: Replace with the real encoding used by the // front end, when we know what it is. byte[] encodedElement = StringUtils.jsonStringToByteArray(encodedElementString); @@ -115,12 +133,15 @@ protected T nextImpl() throws IOException { @Override public Progress getProgress() { + if (lastReturnedIndex == null) { + return null; + } // Currently we assume that only a record index position is reported as // current progress. An implementer can override this method to update // other metrics, e.g. completion percentage or remaining time. com.google.api.services.dataflow.model.Position currentPosition = new com.google.api.services.dataflow.model.Position(); - currentPosition.setRecordIndex((long) nextIndex); + currentPosition.setRecordIndex((long) lastReturnedIndex); ApproximateReportedProgress progress = new ApproximateReportedProgress(); progress.setPosition(currentPosition); @@ -130,7 +151,8 @@ public Progress getProgress() { @Override public double getRemainingParallelism() { - return tracker.getStopPosition() - nextIndex; + // Use the starting index if no elements have yet been returned. + return tracker.getStopPosition() - firstNonNull(lastReturnedIndex, startIndex); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java index 5a37a872ad..3a8f748348 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java @@ -16,7 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import static com.google.cloud.dataflow.sdk.util.Structs.getLong; +import static com.google.cloud.dataflow.sdk.util.Structs.getInt; import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -51,7 +51,8 @@ public NativeReader create( InMemoryReader create(CloudObject spec, Coder coder) throws Exception { return new InMemoryReader<>( getStrings(spec, PropertyNames.ELEMENTS, Collections.emptyList()), - getLong(spec, PropertyNames.START_INDEX, null), - getLong(spec, PropertyNames.END_INDEX, null), coder); + getInt(spec, PropertyNames.START_INDEX, null), + getInt(spec, PropertyNames.END_INDEX, null), + coder); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java index a006a1890f..2d0458437a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java @@ -161,12 +161,12 @@ private class LazyIsmReaderIterator extends LegacyReaderIterator> { private SeekableByteChannel inChannel; @Override - public boolean hasNext() throws IOException { + public boolean hasNextImpl() throws IOException { return getDelegate().hasNext(); } @Override - public KV next() throws IOException, NoSuchElementException { + public KV nextImpl() throws IOException, NoSuchElementException { long startPosition = getChannel().position(); KV rval = getDelegate().next(); notifyElementRead(getChannel().position() - startPosition); @@ -240,7 +240,7 @@ public IsmReaderIterator(SeekableByteChannel unownedChannel, } @Override - public boolean hasNext() throws IOException { + public boolean hasNextImpl() throws IOException { if (inChannel.position() > readLimit) { throw new IllegalStateException("Read past end of stream"); } @@ -248,10 +248,7 @@ public boolean hasNext() throws IOException { } @Override - public KV next() throws IOException, NoSuchElementException { - if (!hasNext()) { - throw new NoSuchElementException(); - } + public KV nextImpl() throws IOException, NoSuchElementException { KeyPrefix keyPrefix = KeyPrefixCoder.of().decode(inStream, Context.NESTED); int totalKeyLength = keyPrefix.getSharedKeySize() + keyPrefix.getUnsharedKeySize(); // currentKey = prevKey[0 : sharedKeySize] + read(unsharedKeySize) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java index 4d3085120d..96432eda54 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import java.io.IOException; @@ -33,7 +32,7 @@ * to be produced lazily, as an open source iterator may consume process * resources such as file descriptors. */ -abstract class LazyMultiReaderIterator extends AbstractBoundedReaderIterator { +abstract class LazyMultiReaderIterator extends NativeReader.LegacyReaderIterator { private final Iterator inputs; NativeReader.LegacyReaderIterator current; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java index b2fc62f09e..dda76f117c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java @@ -22,7 +22,6 @@ import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; @@ -92,8 +91,7 @@ PartitioningShuffleReaderIterator iterator(ShuffleEntryReader reader) { * extracts K and {@code WindowedValue}, and returns a constructed * {@code WindowedValue}. */ - class PartitioningShuffleReaderIterator - extends AbstractBoundedReaderIterator>> { + class PartitioningShuffleReaderIterator extends LegacyReaderIterator>> { Iterator iterator; PartitioningShuffleReaderIterator(ShuffleEntryReader reader) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java index a25af9752c..b341c0553a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java @@ -66,31 +66,16 @@ public NativeReader create( @Override public NativeReaderIterator> iterator() throws IOException { - return new PubsubReaderIterator(); + return new PubsubReaderIterator(context.getWork()); } - class PubsubReaderIterator extends LegacyReaderIterator> { - private int bundleIndex = 0; - private int messageIndex = 0; - - @Override - public boolean hasNext() throws IOException { - Windmill.WorkItem work = context.getWork(); - return bundleIndex < work.getMessageBundlesCount() && - messageIndex < work.getMessageBundles(bundleIndex).getMessagesCount(); + class PubsubReaderIterator extends WindmillReaderIteratorBase { + protected PubsubReaderIterator(Windmill.WorkItem work) { + super(work); } @Override - public WindowedValue next() throws IOException { - Windmill.Message message = - context.getWork().getMessageBundles(bundleIndex).getMessages(messageIndex); - if (messageIndex >= - context.getWork().getMessageBundles(bundleIndex).getMessagesCount() - 1) { - messageIndex = 0; - bundleIndex++; - } else { - messageIndex++; - } + protected WindowedValue decodeMessage(Windmill.Message message) throws IOException { long timestampMillis = TimeUnit.MICROSECONDS.toMillis(message.getTimestamp()); InputStream data = message.getData().newInput(); notifyElementRead(data.available()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java index 5558be8816..fe681aaa75 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java @@ -29,7 +29,6 @@ import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.ProgressTracker; import com.google.cloud.dataflow.sdk.util.common.worker.ProgressTrackerGroup; @@ -270,7 +269,7 @@ protected LegacyReaderIterator open(String input) throws IOException { } } - class TextFileIterator extends AbstractBoundedReaderIterator { + class TextFileIterator extends LegacyReaderIterator { private final CopyableSeekableByteChannel seeker; private final PushbackInputStream stream; private final OffsetRangeTracker rangeTracker; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java index 033cdb1678..18a217dafc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java @@ -19,7 +19,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.AbstractBoundedReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; @@ -67,7 +66,7 @@ UngroupedShuffleReaderIterator iterator(ShuffleEntryReader reader) { * A ReaderIterator that reads from a ShuffleEntryReader and extracts * just the values. */ - class UngroupedShuffleReaderIterator extends AbstractBoundedReaderIterator { + class UngroupedShuffleReaderIterator extends LegacyReaderIterator { Iterator iterator; UngroupedShuffleReaderIterator(ShuffleEntryReader reader) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java index 1467baffc7..abcb9c5fe9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java @@ -74,31 +74,16 @@ public NativeReader create( @Override public NativeReaderIterator> iterator() throws IOException { - return new UngroupedWindmillReaderIterator(); + return new UngroupedWindmillReaderIterator(context.getWork()); } - class UngroupedWindmillReaderIterator extends LegacyReaderIterator> { - private int bundleIndex = 0; - private int messageIndex = 0; - - @Override - public boolean hasNext() throws IOException { - Windmill.WorkItem work = context.getWork(); - return bundleIndex < work.getMessageBundlesCount() && - messageIndex < work.getMessageBundles(bundleIndex).getMessagesCount(); + class UngroupedWindmillReaderIterator extends WindmillReaderIteratorBase { + UngroupedWindmillReaderIterator(Windmill.WorkItem work) { + super(work); } @Override - public WindowedValue next() throws IOException { - Windmill.Message message = - context.getWork().getMessageBundles(bundleIndex).getMessages(messageIndex); - if (messageIndex >= - context.getWork().getMessageBundles(bundleIndex).getMessagesCount() - 1) { - messageIndex = 0; - bundleIndex++; - } else { - messageIndex++; - } + protected WindowedValue decodeMessage(Windmill.Message message) throws IOException { Instant timestampMillis = new Instant(TimeUnit.MICROSECONDS.toMillis(message.getTimestamp())); InputStream data = message.getData().newInput(); InputStream metadata = message.getMetadata().newInput(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java new file mode 100644 index 0000000000..9a57621803 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; + +import java.io.IOException; +import java.util.NoSuchElementException; + +/** + * Base class for iterators that decode messages from bundles inside a {@link Windmill.WorkItem}. + */ +public abstract class WindmillReaderIteratorBase + extends NativeReader.NativeReaderIterator> { + private Windmill.WorkItem work; + private int bundleIndex = 0; + private int messageIndex = -1; + private WindowedValue current; + + protected WindmillReaderIteratorBase(Windmill.WorkItem work) { + this.work = work; + } + + @Override + public boolean start() throws IOException { + return advance(); + } + + @Override + public boolean advance() throws IOException { + if (bundleIndex == work.getMessageBundlesCount() + || messageIndex == work.getMessageBundles(bundleIndex).getMessagesCount()) { + return false; + } + ++messageIndex; + for (; bundleIndex < work.getMessageBundlesCount(); ++bundleIndex, messageIndex = 0) { + Windmill.InputMessageBundle bundle = work.getMessageBundles(bundleIndex); + if (messageIndex < bundle.getMessagesCount()) { + current = decodeMessage(bundle.getMessages(messageIndex)); + return true; + } + } + current = null; + return false; + } + + protected abstract WindowedValue decodeMessage(Windmill.Message message) throws IOException; + + @Override + public WindowedValue getCurrent() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + return current; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java index 1daa31f138..38d9b28603 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java @@ -96,21 +96,32 @@ public NativeReaderIterator>> iterator() throws I final Object key = kvCoder.getKeyCoder().decode( context.getSerializedKey().newInput(), Coder.Context.OUTER); final WorkItem workItem = context.getWork(); + final WindowedValue> value = + WindowedValue.valueInEmptyWindows( + KeyedWorkItem.workItem( + key, workItem, windowCoder, windowsCoder, kvCoder.getValueCoder())); - return new LegacyReaderIterator>>() { - boolean consumed = false; + return new NativeReaderIterator>>() { + private WindowedValue> current; @Override - public boolean hasNext() throws IOException { - return !consumed; + public boolean start() throws IOException { + current = value; + return true; } @Override - public WindowedValue> next() throws IOException, NoSuchElementException { - consumed = true; - return WindowedValue.valueInEmptyWindows( - KeyedWorkItem.workItem( - key, workItem, windowCoder, windowsCoder, kvCoder.getValueCoder())); + public boolean advance() throws IOException { + current = null; + return false; + } + + @Override + public WindowedValue> getCurrent() { + if (current == null) { + throw new NoSuchElementException(); + } + return value; } }; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java index c9d223c654..c621c5564e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java @@ -76,13 +76,23 @@ public static Boolean getBoolean( } public static Long getLong(Map map, String name) throws Exception { - return getValue(map, name, Long.class, "an int"); + return getValue(map, name, Long.class, "a long"); } @Nullable public static Long getLong(Map map, String name, @Nullable Long defaultValue) throws Exception { - return getValue(map, name, Long.class, "an int", defaultValue); + return getValue(map, name, Long.class, "a long", defaultValue); + } + + public static Integer getInt(Map map, String name) throws Exception { + return getValue(map, name, Integer.class, "an int"); + } + + @Nullable + public static Integer getInt(Map map, String name, @Nullable Integer defaultValue) + throws Exception { + return getValue(map, name, Integer.class, "an int", defaultValue); } @Nullable diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/AbstractBoundedReaderIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/AbstractBoundedReaderIterator.java deleted file mode 100644 index 37ebabc7b4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/AbstractBoundedReaderIterator.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import java.io.IOException; -import java.util.NoSuchElementException; - -/** - * An abstract base class for implementations of ReaderIterator classes for bounded sources, - * where hasNext() returns the same value if called multiple times. - * - *

Provides basic treatment of hasNext()/next() to simplify implementations (e.g. ensuring - * hasNext() is called only once and verifying hasNext() in next()) and default no-op - * implementations of other operations. - * - *

This class is intended for internal usage. Users of Dataflow must not subclass it. - * - * @param Type of records returned by the reader. - */ -public abstract class AbstractBoundedReaderIterator - extends NativeReader.LegacyReaderIterator { - private Boolean cachedHasNext; - - @Override - public final boolean hasNext() throws IOException { - if (cachedHasNext == null) { - cachedHasNext = hasNextImpl(); - } - return cachedHasNext; - } - - protected abstract boolean hasNextImpl() throws IOException; - - @Override - public final T next() throws IOException, NoSuchElementException { - if (!hasNext()) { - throw new NoSuchElementException(); - } - cachedHasNext = null; - return nextImpl(); - } - - protected abstract T nextImpl() throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java index be97c08c64..20f399ffa4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java @@ -21,6 +21,8 @@ import java.util.NoSuchElementException; import java.util.Observable; +import javax.annotation.Nullable; + /** * Abstract base class for native readers in the Dataflow runner. * @@ -84,11 +86,15 @@ public abstract static class NativeReaderIterator implements AutoCloseable { /** * Returns a representation of how far this iterator is through the source. - * @return the progress, or {@code null} if no progress measure - * can be provided (implementors are discouraged from throwing - * {@code UnsupportedOperationException} in this case). + * + * @return the progress, or {@code null} if no progress measure can be provided + * (implementors are discouraged from throwing {@code UnsupportedOperationException} + * in this case). By default, returns {@code null}. */ - public abstract Progress getProgress(); + @Nullable + public Progress getProgress() { + return null; + } /** * Attempts to split the input in two parts: the "primary" part and the "residual" part. @@ -119,9 +125,12 @@ public abstract static class NativeReaderIterator implements AutoCloseable { * @return {@code null} if the {@link NativeReader.DynamicSplitRequest} cannot be honored * (in that case the input represented by this {@link NativeReaderIterator} stays the same), * or a {@link NativeReader.DynamicSplitResult} describing how the input was split into - * a primary and residual part. + * a primary and residual part. By default, returns {@code null}. */ - public abstract DynamicSplitResult requestDynamicSplit(DynamicSplitRequest request); + @Nullable + public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest request) { + return null; + } /** * Returns an estimate of the degree of parallelism that could be achieved by @@ -141,8 +150,12 @@ public abstract static class NativeReaderIterator implements AutoCloseable { * {@link NativeReader#getTotalParallelism} using the current progress fraction. * Infinity may also be returned (indicating no known bound on parallelism), * as may fractional estimates (in which case the sum over all shards is taken). + * + *

By default, returns {@link #REMAINING_PARALLELISM_FROM_PROGRESS_FRACTION}. */ - public abstract double getRemainingParallelism(); + public double getRemainingParallelism() { + return REMAINING_PARALLELISM_FROM_PROGRESS_FRACTION; + } /** * Initializes the reader and advances the reader to the first record. @@ -181,30 +194,8 @@ public abstract static class NativeReaderIterator implements AutoCloseable { * @inheritDoc */ @Override - public abstract void close() throws IOException; - } - - /** An abstract base class for ReaderIterator implementations. */ - public abstract static class AbstractReaderIterator extends NativeReaderIterator { - - @Override public void close() throws IOException { - // By default, nothing is needed for close. - } - - @Override - public Progress getProgress() { - return null; - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - return null; - } - - @Override - public double getRemainingParallelism() { - return REMAINING_PARALLELISM_FROM_PROGRESS_FRACTION; + // By default, do nothing. } } @@ -215,25 +206,36 @@ public double getRemainingParallelism() { * * This class is temporary and the intention is to get rid of its subclasses one by one, * converting them to use the new-style interface directly, and then remove this class. + * + *

Provides basic treatment of hasNext()/next() to simplify implementations (e.g. ensuring + * hasNext() is called only once and verifying hasNext() in next()) and default no-op + * implementations of other operations. + * + *

This class is intended for internal usage. Users of Dataflow must not subclass it. */ - public abstract static class LegacyReaderIterator extends AbstractReaderIterator { + public abstract static class LegacyReaderIterator extends NativeReaderIterator { + private Boolean cachedHasNext; private T current; private boolean hasCurrent; - /** - * Returns whether the source has any more elements. Some sources, - * such as GroupingShuffleReader, invalidate the return value of - * the previous next() call during the call to hasNext(). - */ - public abstract boolean hasNext() throws IOException; + public final boolean hasNext() throws IOException { + if (cachedHasNext == null) { + cachedHasNext = hasNextImpl(); + } + return cachedHasNext; + } - /** - * Returns the next element. - * - * @throws IOException if attempting to access an element involves IO that fails - * @throws NoSuchElementException if there are no more elements - */ - public abstract T next() throws IOException, NoSuchElementException; + protected abstract boolean hasNextImpl() throws IOException; + + public final T next() throws IOException, NoSuchElementException { + if (!hasNext()) { + throw new NoSuchElementException(); + } + cachedHasNext = null; + return nextImpl(); + } + + protected abstract T nextImpl() throws IOException; @Override public boolean start() throws IOException { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index b4fbb3b24d..57f6185b42 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -76,6 +76,7 @@ import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.ReaderUtils; import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; @@ -635,8 +636,6 @@ public void testReadUnboundedReader() throws Exception { ByteString state = ByteString.EMPTY; for (int i = 0; i < 10 * CustomSources.MAX_UNBOUNDED_BUNDLE_SIZE; /* Incremented in inner loop */) { - WindowedValue>> value; - // Initialize streaming context with state from previous iteration. context.start( Windmill.WorkItem.newBuilder() @@ -662,14 +661,11 @@ public void testReadUnboundedReader() throws Exception { options, context); - NativeReader.NativeReaderIterator>>> - iterator = reader.iterator(); - // Verify data. Instant beforeReading = Instant.now(); int numReadOnThisIteration = 0; - for (boolean more = iterator.start(); more; more = iterator.advance()) { - value = iterator.getCurrent(); + for (WindowedValue>> value : + ReaderUtils.readElemsFromReader(reader)) { assertEquals(KV.of(0, i), value.getValue().getValue()); assertArrayEquals( encodeToByteArray(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()), KV.of(0, i)), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java index cbc9a4cac3..eab3a68ba0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java @@ -28,7 +28,6 @@ import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.DynamicSplitResult; import org.apache.avro.Schema; @@ -229,7 +228,7 @@ private void testRequestDynamicSplitInternal( List primaryElements; List residualElements = new ArrayList<>(); - try (NativeReader.NativeReaderIterator iterator = reader.iterator()) { + try (AvroByteReader.AvroByteFileIterator iterator = reader.iterator()) { // Read n elements from the reader primaryElements = readNItemsFromUnstartedReader(iterator, readBeforeSplit); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java index ff0278179b..5ba037b3e8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java @@ -204,7 +204,7 @@ private void testRequestDynamicSplitInternal( Long endOffset = reader.endPosition; List primaryElements; List residualElements = new ArrayList<>(); - try (NativeReader.NativeReaderIterator> iterator = reader.iterator()) { + try (AvroReader.AvroFileIterator iterator = reader.iterator()) { // Read n elements from the reader primaryElements = windowedValuesToValues(readNItemsFromUnstartedReader(iterator, readBeforeSplit)); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java index 16db911e93..5f7323d159 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java @@ -99,8 +99,7 @@ public TestReader(List encodedElements, Coder coder, long recordToFai boolean failWhenClosing) { this.recordToFailAt = recordToFailAt; this.failWhenClosing = failWhenClosing; - readerDelegator = - new InMemoryReader<>(encodedElements, 0L, (long) encodedElements.size(), coder); + readerDelegator = new InMemoryReader<>(encodedElements, 0, encodedElements.size(), coder); recordedReaders.add(this); } @@ -114,32 +113,41 @@ public boolean isClosedOrUnopened() { } @Override - public LegacyReaderIterator iterator() throws IOException { - lastIterator = new TestIterator((LegacyReaderIterator) readerDelegator.iterator()); + public NativeReaderIterator iterator() throws IOException { + lastIterator = new TestIterator(readerDelegator.iterator()); return lastIterator; } - private class TestIterator extends LegacyReaderIterator { - private final LegacyReaderIterator iteratorImpl; - private long currentRecord; + private class TestIterator extends NativeReaderIterator { + private final NativeReaderIterator iteratorImpl; + private long currentIndex = -1; private boolean isClosed = false; - private TestIterator(LegacyReaderIterator iteratorImpl) { + private TestIterator(NativeReaderIterator iteratorImpl) { this.iteratorImpl = iteratorImpl; } @Override - public boolean hasNext() throws IOException { - return iteratorImpl.hasNext(); + public boolean start() throws IOException { + currentIndex++; + if (currentIndex == recordToFailAt) { + throw new IOException("Failing at record " + currentIndex); + } + return iteratorImpl.start(); } @Override - public T next() throws IOException, NoSuchElementException { - if (currentRecord == recordToFailAt) { - throw new IOException("Failing at record " + currentRecord); + public boolean advance() throws IOException { + currentIndex++; + if (currentIndex == recordToFailAt) { + throw new IOException("Failing at record " + currentIndex); } - currentRecord++; - return iteratorImpl.next(); + return iteratorImpl.advance(); + } + + @Override + public T getCurrent() throws NoSuchElementException { + return iteratorImpl.getCurrent(); } @Override @@ -263,12 +271,12 @@ public void testReadEmptyList() throws Exception { null /* addCounterMutator */, null /* operationName */, new ArrayList()); - NativeReader.LegacyReaderIterator iterator = concat.iterator(); + ConcatReader.ConcatIterator iterator = concat.iterator(); assertNotNull(iterator); - assertFalse(concat.iterator().hasNext()); + assertFalse(concat.iterator().start()); expectedException.expect(NoSuchElementException.class); - iterator.next(); + iterator.getCurrent(); } @Test @@ -359,10 +367,14 @@ public void testReaderFailsAtRead() throws Exception { private void runProgressTest(int... sizes) throws Exception { ConcatReader concatReader = createConcatReadersOfSizes(new ArrayList(), sizes); - try (NativeReader.LegacyReaderIterator iterator = concatReader.iterator()) { + try (ConcatReader.ConcatIterator iterator = concatReader.iterator()) { for (int readerIndex = 0; readerIndex < sizes.length; readerIndex++) { for (int recordIndex = 0; recordIndex < sizes[readerIndex]; recordIndex++) { - iterator.next(); + if (readerIndex == 0 && recordIndex == 0) { + iterator.start(); + } else { + iterator.advance(); + } ApproximateReportedProgress progress = readerProgressToCloudProgress(iterator.getProgress()); assertEquals( @@ -410,9 +422,13 @@ public void runUpdateStopPositionTest(int... readerSizes) throws Exception { recordsToRead++; - NativeReader.LegacyReaderIterator iterator = concatReader.iterator(); + NativeReader.NativeReaderIterator iterator = concatReader.iterator(); for (int i = 0; i < recordsToRead; i++) { - iterator.next(); + if (i == 0) { + iterator.start(); + } else { + iterator.advance(); + } } DynamicSplitResult splitResult = diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java index 76a002a675..19a022d0e7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java @@ -18,6 +18,7 @@ import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.approximateProgressAtIndex; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionAtIndex; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromProgress; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtIndex; import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; @@ -35,7 +36,9 @@ import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -43,11 +46,15 @@ import java.util.Arrays; import java.util.List; +import javax.annotation.Nullable; + /** * Tests for InMemoryReader. */ @RunWith(JUnit4.class) public class InMemoryReaderTest { + @Rule public ExpectedException expectedException = ExpectedException.none(); + static List encodedElements(List elements, Coder coder) throws Exception { List encodedElements = new ArrayList<>(); for (T element : elements) { @@ -58,18 +65,26 @@ static List encodedElements(List elements, Coder coder) throws return encodedElements; } - void runTestReadInMemory(List elements, Long startIndex, Long endIndex, - List expectedElements, List expectedSizes, Coder coder) throws Exception { + void runTestReadInMemory( + List elements, + @Nullable Integer startIndex, + @Nullable Integer endIndex, + List expectedElements, + List expectedSizes, + Coder coder) + throws Exception { InMemoryReader inMemoryReader = new InMemoryReader<>(encodedElements(elements, coder), startIndex, endIndex, coder); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(inMemoryReader); List actualElements = new ArrayList<>(); try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - for (long i = inMemoryReader.startIndex; iterator.hasNext(); i++) { + for (long i = inMemoryReader.startIndex; + (i == inMemoryReader.startIndex) ? iterator.start() : iterator.advance(); + i++) { assertEquals( approximateProgressAtIndex(i), readerProgressToCloudProgress(iterator.getProgress())); - actualElements.add(iterator.next()); + actualElements.add(iterator.getCurrent()); } } assertEquals(expectedElements, actualElements); @@ -85,39 +100,68 @@ public void testReadAllElements() throws Exception { @Test public void testReadElementsFromStart() throws Exception { - runTestReadInMemory(Arrays.asList(33, 44, 55, 66, 77, 88), 2L, null, - Arrays.asList(55, 66, 77, 88), Arrays.asList(4, 4, 4, 4), BigEndianIntegerCoder.of()); + runTestReadInMemory( + Arrays.asList(33, 44, 55, 66, 77, 88), + 2, + null, + Arrays.asList(55, 66, 77, 88), + Arrays.asList(4, 4, 4, 4), + BigEndianIntegerCoder.of()); } @Test public void testReadElementsToEnd() throws Exception { - runTestReadInMemory(Arrays.asList(33, 44, 55, 66, 77, 88), null, 3L, Arrays.asList(33, 44, 55), - Arrays.asList(4, 4, 4), BigEndianIntegerCoder.of()); + runTestReadInMemory( + Arrays.asList(33, 44, 55, 66, 77, 88), + null, + 3, + Arrays.asList(33, 44, 55), + Arrays.asList(4, 4, 4), + BigEndianIntegerCoder.of()); } @Test public void testReadElementsFromStartToEnd() throws Exception { - runTestReadInMemory(Arrays.asList(33, 44, 55, 66, 77, 88), 2L, 5L, Arrays.asList(55, 66, 77), - Arrays.asList(4, 4, 4), BigEndianIntegerCoder.of()); + runTestReadInMemory( + Arrays.asList(33, 44, 55, 66, 77, 88), + 2, + 5, + Arrays.asList(55, 66, 77), + Arrays.asList(4, 4, 4), + BigEndianIntegerCoder.of()); } @Test public void testReadElementsOffEnd() throws Exception { - runTestReadInMemory(Arrays.asList(33, 44, 55, 66, 77, 88), null, 30L, - Arrays.asList(33, 44, 55, 66, 77, 88), Arrays.asList(4, 4, 4, 4, 4, 4), + runTestReadInMemory( + Arrays.asList(33, 44, 55, 66, 77, 88), + null, + 30, + Arrays.asList(33, 44, 55, 66, 77, 88), + Arrays.asList(4, 4, 4, 4, 4, 4), BigEndianIntegerCoder.of()); } @Test public void testReadElementsFromStartPastEnd() throws Exception { - runTestReadInMemory(Arrays.asList(33, 44, 55, 66, 77, 88), 20L, null, Arrays.asList(), - Arrays.asList(), BigEndianIntegerCoder.of()); + runTestReadInMemory( + Arrays.asList(33, 44, 55, 66, 77, 88), + 20, + null, + Arrays.asList(), + Arrays.asList(), + BigEndianIntegerCoder.of()); } @Test public void testReadElementsFromStartToEndEmptyRange() throws Exception { - runTestReadInMemory(Arrays.asList(33, 44, 55, 66, 77, 88), 2L, 2L, Arrays.asList(), - Arrays.asList(), BigEndianIntegerCoder.of()); + runTestReadInMemory( + Arrays.asList(33, 44, 55, 66, 77, 88), + 2, + 2, + Arrays.asList(), + Arrays.asList(), + BigEndianIntegerCoder.of()); } @Test @@ -128,8 +172,41 @@ public void testReadNoElements() throws Exception { @Test public void testReadNoElementsFromStartToEndEmptyRange() throws Exception { - runTestReadInMemory(Arrays.asList(), 0L, 0L, Arrays.asList(), - Arrays.asList(), BigEndianIntegerCoder.of()); + runTestReadInMemory( + Arrays.asList(), + 0, + 0, + Arrays.asList(), + Arrays.asList(), + BigEndianIntegerCoder.of()); + } + + @Test + public void testProgressReporting() throws Exception { + List elements = Arrays.asList(33, 44, 55, 66, 77, 88); + // Should initially read elements at indices: 44@1, 55@2, 66@3, 77@4 + + Coder coder = BigEndianIntegerCoder.of(); + InMemoryReader inMemoryReader = + new InMemoryReader<>(encodedElements(elements, coder), 1, 4, coder); + try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { + assertNull(iterator.getProgress()); + assertEquals(3, iterator.getRemainingParallelism(), 0.0); + + assertTrue(iterator.start()); + assertEquals(positionAtIndex(1L), positionFromProgress(iterator.getProgress())); + assertEquals(3, iterator.getRemainingParallelism(), 0.0); + + assertTrue(iterator.advance()); + assertEquals(positionAtIndex(2L), positionFromProgress(iterator.getProgress())); + assertEquals(2, iterator.getRemainingParallelism(), 0.0); + + assertTrue(iterator.advance()); + assertEquals(positionAtIndex(3L), positionFromProgress(iterator.getProgress())); + assertEquals(1, iterator.getRemainingParallelism(), 0.0); + + assertFalse(iterator.advance()); + } } @Test @@ -139,50 +216,56 @@ public void testDynamicSplit() throws Exception { Coder coder = BigEndianIntegerCoder.of(); InMemoryReader inMemoryReader = - new InMemoryReader<>(encodedElements(elements, coder), 1L, 4L, coder); + new InMemoryReader<>(encodedElements(elements, coder), 1, 4, coder); + + // Unstarted iterator. + try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { + assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(3L))); + } // Illegal proposed split position. try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { + assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(3L))); // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.hasNext()); + assertTrue(iterator.start()); assertNull(iterator.requestDynamicSplit(toDynamicSplitRequest( new ApproximateSplitRequest()))); assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(null))); } // Successful update. - try (InMemoryReader.InMemoryReaderIterator iterator = - (InMemoryReader.InMemoryReaderIterator) inMemoryReader.iterator()) { + try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.hasNext()); + assertTrue(iterator.start()); NativeReader.DynamicSplitResult dynamicSplitResult = iterator.requestDynamicSplit(splitRequestAtIndex(3L)); assertEquals(positionAtIndex(3L), positionFromSplitResult(dynamicSplitResult)); assertEquals(3, iterator.tracker.getStopPosition().longValue()); - assertEquals(44, iterator.next().intValue()); - assertEquals(55, iterator.next().intValue()); - assertFalse(iterator.hasNext()); + assertEquals(44, iterator.getCurrent().intValue()); + assertTrue(iterator.advance()); + assertEquals(55, iterator.getCurrent().intValue()); + assertFalse(iterator.advance()); } // Proposed split position is before the current position, no update. - try (InMemoryReader.InMemoryReaderIterator iterator = - (InMemoryReader.InMemoryReaderIterator) inMemoryReader.iterator()) { + try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.hasNext()); - assertEquals(44, iterator.next().intValue()); - assertEquals(55, iterator.next().intValue()); - assertTrue(iterator.hasNext()); // Returns true => we promised to return 66. + assertTrue(iterator.start()); + assertEquals(44, iterator.getCurrent().intValue()); + assertTrue(iterator.advance()); + assertEquals(55, iterator.getCurrent().intValue()); + assertTrue(iterator.advance()); // Returns true => we promised to return 66. // Now we have to refuse the split. assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(3L))); assertEquals(4, iterator.tracker.getStopPosition().longValue()); - assertTrue(iterator.hasNext()); + assertEquals(66, iterator.getCurrent().intValue()); + assertFalse(iterator.advance()); } // Proposed split position is after the current stop (end) position, no update. - try (InMemoryReader.InMemoryReaderIterator iterator = - (InMemoryReader.InMemoryReaderIterator) inMemoryReader.iterator()) { + try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.hasNext()); + assertTrue(iterator.start()); assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(5L))); assertEquals(4, iterator.tracker.getStopPosition().longValue()); } @@ -194,14 +277,14 @@ public void testParallelism() throws Exception { Coder coder = BigEndianIntegerCoder.of(); InMemoryReader inMemoryReader = - new InMemoryReader<>(encodedElements(elements, coder), 1L, 4L, coder); + new InMemoryReader<>(encodedElements(elements, coder), 1, 4, coder); int count = 0; - for (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator(); - iterator.hasNext(); - iterator.next()) { - assertTrue(iterator.getRemainingParallelism() >= 1); - assertEquals(3 - count, iterator.getRemainingParallelism(), 0 /*tolerance*/); - count++; + try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { + for (boolean more = iterator.start(); more; more = iterator.advance()) { + assertTrue(iterator.getRemainingParallelism() >= 1); + assertEquals(3 - count, iterator.getRemainingParallelism(), 0 /*tolerance*/); + count++; + } } assertEquals(count, inMemoryReader.getTotalParallelism(), 0 /*tolerance*/); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java index 89bb4da6de..b2e0a19fca 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java @@ -37,6 +37,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.IOException; import java.util.NoSuchElementException; import javax.annotation.Nullable; @@ -67,19 +68,21 @@ public NativeReaderIterator iterator() { } /** A source iterator that produces no values, for testing. */ - class TestReaderIterator extends LegacyReaderIterator { + class TestReaderIterator extends NativeReaderIterator { @Override - public boolean hasNext() { + public boolean start() { return false; } @Override - public Integer next() { - throw new NoSuchElementException(); + public boolean advance() { + return false; } @Override - public void close() {} + public Integer getCurrent() { + throw new NoSuchElementException(); + } } } @@ -103,25 +106,21 @@ public SingletonTestReaderIterator iterator() { } /** A source iterator that produces no values, for testing. */ - class SingletonTestReaderIterator extends LegacyReaderIterator> { - private boolean seen = false; + class SingletonTestReaderIterator extends NativeReaderIterator> { @Override - public boolean hasNext() { - return !seen; + public boolean start() { + return true; } @Override - public WindowedValue next() { - if (seen) { - throw new NoSuchElementException(); - } else { - seen = true; - return WindowedValue.valueInGlobalWindow("something"); - } + public boolean advance() throws IOException { + return false; } @Override - public void close() {} + public WindowedValue getCurrent() { + return WindowedValue.valueInGlobalWindow("something"); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java index a1a009a233..ef559e3d30 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java @@ -44,8 +44,8 @@ import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.LegacyReaderIterator; +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.NativeReaderIterator; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.junit.Rule; @@ -130,7 +130,7 @@ private File initTestFile() throws IOException { public void testReadEmptyFile() throws Exception { TextReader textReader = new TextReader<>(tmpFolder.newFile().getPath(), true, null, null, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - try (NativeReader.NativeReaderIterator iterator = textReader.iterator()) { + try (NativeReaderIterator iterator = textReader.iterator()) { assertFalse(iterator.start()); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java new file mode 100644 index 0000000000..0de53ef679 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.protobuf.ByteString; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Tests for {@link WindmillReaderIteratorBase}. + */ +@RunWith(JUnit4.class) +public class WindmillReaderIteratorBaseTest { + private static class TestWindmillReaderIterator extends WindmillReaderIteratorBase { + protected TestWindmillReaderIterator(Windmill.WorkItem work) { + super(work); + } + + @Override + protected WindowedValue decodeMessage(Windmill.Message message) { + return WindowedValue.valueInGlobalWindow(message.getTimestamp()); + } + } + + @Test + public void testBasic() throws IOException { + testForMessageBundleCounts(); + testForMessageBundleCounts(0); + testForMessageBundleCounts(0, 0); + testForMessageBundleCounts(1); + testForMessageBundleCounts(2); + testForMessageBundleCounts(1, 1); + testForMessageBundleCounts(0, 1); + testForMessageBundleCounts(1, 0); + testForMessageBundleCounts(0, 0, 1, 3, 0, 1, 0, 0, 0, 1); + testForMessageBundleCounts(0, 0, 1, 3, 0, 1, 0, 0, 0, 0); + } + + private void testForMessageBundleCounts(int... messageBundleCounts) throws IOException { + List bundles = new ArrayList<>(); + long numTotalMessages = 0; + for (int count : messageBundleCounts) { + Windmill.InputMessageBundle.Builder bundle = + Windmill.InputMessageBundle.newBuilder().setSourceComputationId("foo"); + for (int i = 0; i < count; ++i) { + bundle.addMessages( + Windmill.Message.newBuilder() + .setTimestamp(numTotalMessages++) + .setData(ByteString.EMPTY) + .build()); + } + bundles.add(bundle.build()); + } + Windmill.WorkItem workItem = + Windmill.WorkItem.newBuilder() + .setKey(ByteString.EMPTY) + .setWorkToken(0L) + .addAllMessageBundles(bundles) + .build(); + try (TestWindmillReaderIterator iter = new TestWindmillReaderIterator(workItem)) { + List actual = + ReaderTestUtils.windowedValuesToValues( + ReaderTestUtils.readRemainingFromReader(iter, false)); + assertFalse(iter.advance()); + List expected = new ArrayList<>(); + for (int i = 0; i < numTotalMessages; ++i) { + expected.add((long) i); + } + assertEquals(Arrays.toString(messageBundleCounts), expected, actual); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java index b50d9d2bdc..bc0bdd82ec 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java @@ -26,6 +26,7 @@ import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; +import static com.google.cloud.dataflow.sdk.util.Structs.getInt; import static com.google.cloud.dataflow.sdk.util.Structs.getListOfMaps; import static com.google.cloud.dataflow.sdk.util.Structs.getLong; import static com.google.cloud.dataflow.sdk.util.Structs.getObject; @@ -161,6 +162,9 @@ public void testGetLongParameter() throws Exception { Assert.assertEquals( (Long) 42L, getLong(o, "singletonLongKey", 666L)); + Assert.assertEquals( + (Integer) 42, + getInt(o, "singletonLongKey", 666)); Assert.assertEquals( (Long) 666L, getLong(o, "missingKey", 666L)); @@ -168,6 +172,13 @@ public void testGetLongParameter() throws Exception { try { getLong(o, "emptyKey", 666L); Assert.fail("should have thrown an exception"); + } catch (Exception exn) { + Assert.assertThat(exn.toString(), + Matchers.containsString("not a long")); + } + try { + getInt(o, "emptyKey", 666); + Assert.fail("should have thrown an exception"); } catch (Exception exn) { Assert.assertThat(exn.toString(), Matchers.containsString("not an int")); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java index 4942eadfeb..18b703564a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java @@ -19,13 +19,15 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.ElementByteSizeObservableCoder; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.common.collect.ImmutableList; import org.junit.Assert; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; import java.util.Observable; import java.util.Observer; @@ -84,24 +86,37 @@ public NativeReaderIterator iterator() { return new TestReaderIterator(inputs); } - class TestReaderIterator extends LegacyReaderIterator { - Iterator iter; - boolean closed = false; + class TestReaderIterator extends NativeReaderIterator { + private final List inputs; + private int currentIndex; + private boolean closed = false; public TestReaderIterator(List inputs) { - iter = inputs.iterator(); + this.inputs = ImmutableList.copyOf(inputs); } @Override - public boolean hasNext() { - return iter.hasNext(); + public boolean start() { + if (inputs.isEmpty()) { + return false; + } + notifyElementRead(getCurrent().length()); + return true; } @Override - public String next() { - String next = iter.next(); - notifyElementRead(next.length()); - return next; + public boolean advance() throws IOException { + if (currentIndex >= inputs.size() - 1) { + return false; + } + ++currentIndex; + notifyElementRead(getCurrent().length()); + return true; + } + + @Override + public String getCurrent() throws NoSuchElementException { + return inputs.get(currentIndex); } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java index 0eae253e4d..7385199d5d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java @@ -52,6 +52,7 @@ import java.io.IOException; import java.util.NoSuchElementException; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Exchanger; /** @@ -152,10 +153,10 @@ public void testDynamicSplit() throws Exception { readOperation.requestDynamicSplit(splitRequestAtIndex(8L))); Thread thread = runReadLoopInThread(readOperation); - iterator.offerNext(0); // Await first next() and return 0 from it. + iterator.offerNext(0); // Await start() and return 0 from getCurrent(). receiver.unblockProcess(); + // Await advance() and return 1 from getCurrent(). iterator.offerNext(1); - // Read loop is now blocked in process() (not next()). NativeReader.DynamicSplitResultWithPosition split = (NativeReader.DynamicSplitResultWithPosition) readOperation.requestDynamicSplit(splitRequestAtIndex(8L)); @@ -165,7 +166,7 @@ public void testDynamicSplit() throws Exception { // Check that the progress has been recomputed. ApproximateReportedProgress progress = readerProgressToCloudProgress( readOperation.getProgress()); - assertEquals(2, progress.getPosition().getRecordIndex().longValue()); + assertEquals(1, progress.getPosition().getRecordIndex().longValue()); assertEquals(2.0f / 8.0, progress.getFractionConsumed(), 0.001); receiver.unblockProcess(); @@ -239,35 +240,47 @@ public void testRaceBetweenCloseAndDynamicSplit() throws Exception { counterSet.getAddCounterMutator(), new StateSampler("test-", counterSet.getAddCounterMutator())); - final Exchanger startCompleted = new Exchanger<>(); - final Exchanger requestDynamicSplitCompleted = new Exchanger<>(); - Thread thread = new Thread() { - @Override - public void run() { - try { - readOperation.start(); - startCompleted.exchange(null); - requestDynamicSplitCompleted.exchange(null); - readOperation.finish(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; + // We simulate the following sequence: + // "Reader thread" calls ReadOperation.start() and returns from it + // "Main thread" calls requestDynamicSplit() + // "Reader thread" calls ReadOperation.finish() + // We use CountDownLatch as synchronization barriers to establish this sequence. + final CountDownLatch startCompleted = new CountDownLatch(1); + final CountDownLatch requestDynamicSplitCompleted = new CountDownLatch(1); + Thread thread = + new Thread() { + @Override + public void run() { + try { + readOperation.start(); + // Synchronize with main test thread to notify it that .start() has finished, + // meaning the ReadOperation has finished reading. + startCompleted.countDown(); + // Synchronize with main test thread to wait until requestDynamicSplit() + // has completed. + requestDynamicSplitCompleted.await(); + // Now finish the ReadOperation. + readOperation.finish(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }; thread.start(); for (int i = 0; i < 10; ++i) { iterator.offerNext(i); receiver.unblockProcess(); } - // Wait for ReadOperation.start() to finish - startCompleted.exchange(null); + // Synchronize with reader thread to wait until ReadOperation.start() finishes. + startCompleted.await(); // Check that requestDynamicSplit is safe (no-op) if the operation is done with start() // but not yet done with finish() readOperation.requestDynamicSplit(splitRequestAtIndex(5L)); - // Allow thread to finish() and join. - requestDynamicSplitCompleted.exchange(null); + // Synchronize with reader thread to notify it that we're done calling requestDynamicSplit(). + requestDynamicSplitCompleted.countDown(); + // Let the reader thread complete (it just calls finish()). thread.join(); // Check once more that requestDynamicSplit on a finished operation is also safe (no-op). @@ -290,7 +303,7 @@ public void run() { return thread; } - private static class MockReaderIterator extends AbstractBoundedReaderIterator { + private static class MockReaderIterator extends NativeReader.NativeReaderIterator { private final OffsetRangeTracker tracker; private Exchanger exchanger = new Exchanger<>(); private int current; @@ -298,24 +311,37 @@ private static class MockReaderIterator extends AbstractBoundedReaderIterator Date: Thu, 21 Jan 2016 16:32:18 -0800 Subject: [PATCH 026/751] Fix Coder.Context equality and hashCode This only worked if you depended on the instances directly and didn't construct your own. Also add Coder.Context#toString() ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112736780 --- .../cloud/dataflow/sdk/coders/Coder.java | 22 +++++- .../cloud/dataflow/sdk/coders/CoderTest.java | 78 +++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java index 89b35164d4..f3a8bec4a6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java @@ -21,6 +21,8 @@ import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; import com.google.common.base.Joiner; +import com.google.common.base.MoreObjects; +import com.google.common.base.Objects; import com.google.common.base.Preconditions; import java.io.IOException; @@ -30,7 +32,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.Objects; import javax.annotation.Nullable; @@ -92,6 +93,25 @@ public Context(boolean isWholeStream) { public Context nested() { return NESTED; } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Context)) { + return false; + } + return Objects.equal(isWholeStream, ((Context) obj).isWholeStream); + } + + @Override + public int hashCode() { + return Objects.hashCode(isWholeStream); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(Context.class) + .addValue(isWholeStream ? "OUTER" : "NESTED").toString(); + } } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java new file mode 100644 index 0000000000..c5d275cf63 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.coders.Coder.Context; +import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Collections; + +/** Tests for constructs defined within {@link Coder}. */ +@RunWith(JUnit4.class) +public class CoderTest { + @Rule public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void testContextEqualsAndHashCode() { + assertEquals(Context.NESTED, new Context(false)); + assertEquals(Context.OUTER, new Context(true)); + assertNotEquals(Context.NESTED, Context.OUTER); + + assertEquals(Context.NESTED.hashCode(), new Context(false).hashCode()); + assertEquals(Context.OUTER.hashCode(), new Context(true).hashCode()); + // Even though this isn't strictly required by the hashCode contract, + // we still want this to be true. + assertNotEquals(Context.NESTED.hashCode(), Context.OUTER.hashCode()); + } + + @Test + public void testContextToString() { + assertEquals("Context{NESTED}", Context.NESTED.toString()); + assertEquals("Context{OUTER}", Context.OUTER.toString()); + } + + @Test + public void testNonDeterministicExcpetionRequiresReason() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Reasons must not be empty"); + new NonDeterministicException(VoidCoder.of(), Collections.emptyList()); + } + + @Test + public void testNonDeterministicException() { + NonDeterministicException rootCause = + new NonDeterministicException(VoidCoder.of(), "Root Cause"); + NonDeterministicException exception = + new NonDeterministicException(StringUtf8Coder.of(), "Problem", rootCause); + assertEquals(rootCause, exception.getCause()); + assertThat(exception.getReasons(), contains("Problem")); + assertThat(exception.toString(), containsString("Problem")); + assertThat(exception.toString(), containsString("is not deterministic")); + } +} + From 1c47353fe5c46e21421c3d5161cb69a7295d4043 Mon Sep 17 00:00:00 2001 From: klk Date: Fri, 22 Jan 2016 09:43:24 -0800 Subject: [PATCH 027/751] Update prebuilt proto libraries for Dataflow to 2016-01-20 version ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112792425 --- sdk/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index e182ccabe6..5378ffa1f3 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -430,7 +430,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-proto-library-all - 0.4.151117 + 0.4.160120 From b5b8d95ccee226c57ed4a42b073583bc6d40d77f Mon Sep 17 00:00:00 2001 From: lcwik Date: Fri, 22 Jan 2016 11:08:37 -0800 Subject: [PATCH 028/751] Upgrade Jackson dependency from 2.4.5 to 2.7.0 https://github.com/FasterXML/jackson-databind/issues/543 was fixed and we have deprecated KvCoderBase and MapCoderBase which were used as work arounds for the issue. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112801278 --- examples/pom.xml | 4 ++-- javadoc/jackson-databind-docs/package-list | 18 ++++++++++++++++++ pom.xml | 2 +- sdk/pom.xml | 4 ++-- .../cloud/dataflow/sdk/coders/KvCoderBase.java | 2 ++ .../dataflow/sdk/coders/MapCoderBase.java | 2 ++ 6 files changed, 27 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 2b8c3d83b8..0e7db3d59b 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -276,11 +276,11 @@ ${basedir}/../javadoc/guava-docs - http://fasterxml.github.io/jackson-annotations/javadoc/2.4/ + http://fasterxml.github.io/jackson-annotations/javadoc/2.7/ ${basedir}/../javadoc/jackson-annotations-docs - http://fasterxml.github.io/jackson-databind/javadoc/2.4/ + http://fasterxml.github.io/jackson-databind/javadoc/2.7/ ${basedir}/../javadoc/jackson-databind-docs diff --git a/javadoc/jackson-databind-docs/package-list b/javadoc/jackson-databind-docs/package-list index 8a7d4399ff..8a2cd8be56 100644 --- a/javadoc/jackson-databind-docs/package-list +++ b/javadoc/jackson-databind-docs/package-list @@ -1,2 +1,20 @@ com.fasterxml.jackson.databind com.fasterxml.jackson.databind.annotation +com.fasterxml.jackson.databind.cfg +com.fasterxml.jackson.databind.deser +com.fasterxml.jackson.databind.deser.impl +com.fasterxml.jackson.databind.deser.std +com.fasterxml.jackson.databind.exc +com.fasterxml.jackson.databind.ext +com.fasterxml.jackson.databind.introspect +com.fasterxml.jackson.databind.jsonFormatVisitors +com.fasterxml.jackson.databind.jsonschema +com.fasterxml.jackson.databind.jsontype +com.fasterxml.jackson.databind.jsontype.impl +com.fasterxml.jackson.databind.module +com.fasterxml.jackson.databind.node +com.fasterxml.jackson.databind.ser +com.fasterxml.jackson.databind.ser.impl +com.fasterxml.jackson.databind.ser.std +com.fasterxml.jackson.databind.type +com.fasterxml.jackson.databind.util diff --git a/pom.xml b/pom.xml index 3c49657d91..7bdee33965 100644 --- a/pom.xml +++ b/pom.xml @@ -74,7 +74,7 @@ 1.21.0 19.0 1.3 - 2.4.2 + 2.7.0 2.4 4.11 2.5.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index 5378ffa1f3..891bb220d9 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -253,11 +253,11 @@ ${basedir}/../javadoc/hamcrest-docs - http://fasterxml.github.io/jackson-annotations/javadoc/2.4/ + http://fasterxml.github.io/jackson-annotations/javadoc/2.7/ ${basedir}/../javadoc/jackson-annotations-docs - http://fasterxml.github.io/jackson-databind/javadoc/2.4/ + http://fasterxml.github.io/jackson-databind/javadoc/2.7/ ${basedir}/../javadoc/jackson-databind-docs diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java index d33da00d5c..4a12ee0d96 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java @@ -31,6 +31,7 @@ * * @param the type of values being transcoded */ +@Deprecated public abstract class KvCoderBase extends StandardCoder { /** * A constructor used only for decoding from JSON. @@ -38,6 +39,7 @@ public abstract class KvCoderBase extends StandardCoder { * @param typeId present in the JSON encoding, but unused * @param isPairLike present in the JSON encoding, but unused */ + @Deprecated @JsonCreator public static KvCoderBase of( // N.B. typeId is a required parameter here, since a field named "@type" diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java index 7a6a99790e..d32406c50d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java @@ -30,7 +30,9 @@ * parameters). This should be removed in favor of a better workaround. * @param the type of values being transcoded */ +@Deprecated public abstract class MapCoderBase extends StandardCoder { + @Deprecated @JsonCreator public static MapCoderBase of( // N.B. typeId is a required parameter here, since a field named "@type" From 61a2e27acd21bd1028162be22a6df3ccb5cb38b7 Mon Sep 17 00:00:00 2001 From: klk Date: Fri, 22 Jan 2016 11:28:16 -0800 Subject: [PATCH 029/751] Expose event time and synchronized upstream processing time Event time track the input event time watermark for a step. Synchronized processing time tracks the processing time which all upstream workers have reached and processed timers for. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112803163 --- .../worker/StreamingDataflowWorker.java | 15 +++-- .../worker/StreamingModeExecutionContext.java | 26 +++++--- .../sdk/transforms/windowing/Trigger.java | 8 +++ .../sdk/util/BatchTimerInternals.java | 12 ++++ .../cloud/dataflow/sdk/util/ReduceFn.java | 10 +++ .../sdk/util/ReduceFnContextFactory.java | 14 +++++ .../dataflow/sdk/util/TimerInternals.java | 7 +++ .../sdk/util/TriggerContextFactory.java | 63 ++++++++++++++++++- .../runners/dataflow/CustomSourcesTest.java | 1 + .../StreamingModeExecutionContextTest.java | 2 + .../dataflow/sdk/util/ReduceFnTester.java | 32 ++++++++++ .../dataflow/sdk/util/TriggerTester.java | 38 +++++++++++ 12 files changed, 216 insertions(+), 12 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java index fc7259ea8f..6f507e9f80 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java @@ -492,6 +492,10 @@ private void dispatchLoop() { final Instant inputDataWatermark = WindmillTimeUtils.windmillToHarnessInputWatermark( computationWork.getInputDataWatermark()); + @Nullable + final Instant synchronizedProcessingTime = + WindmillTimeUtils.windmillToHarnessInputWatermark( + computationWork.getDependentRealtimeInputWatermark()); ActiveWorkForComputation activeWork = activeWorkMap.get(computation); for (final Windmill.WorkItem workItem : computationWork.getWorkList()) { // May be null if output watermark not yet known. @@ -504,7 +508,8 @@ private void dispatchLoop() { Work work = new Work(workItem.getWorkToken()) { @Override public void run() { - process(computation, mapTask, inputDataWatermark, outputDataWatermark, workItem); + process(computation, mapTask, inputDataWatermark, outputDataWatermark, + synchronizedProcessingTime, workItem); } }; if (activeWork.activateWork(workItem.getKey(), work)) { @@ -528,6 +533,7 @@ public long getWorkToken() { private void process(final String computation, final MapTask mapTask, @Nullable final Instant inputDataWatermark, @Nullable final Instant outputDataWatermark, + @Nullable final Instant synchronizedProcessingTime, final Windmill.WorkItem work) { LOG.debug("Starting processing for {}:\n{}", computation, work); @@ -587,8 +593,8 @@ private void process(final String computation, final MapTask mapTask, WindmillStateReader stateReader = new WindmillStateReader( metricTrackingWindmillServer, computation, work.getKey(), work.getWorkToken()); StateFetcher localStateFetcher = stateFetcher.byteTrackingView(); - context.start(work, inputDataWatermark, outputDataWatermark, stateReader, localStateFetcher, - outputBuilder); + context.start(work, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime, + stateReader, localStateFetcher, outputBuilder); for (Long callbackId : context.getReadyCommitCallbackIds()) { final Runnable callback = commitCallbacks.remove(callbackId); @@ -688,7 +694,8 @@ public void run() { workUnitExecutor.forceExecute(new Runnable() { @Override public void run() { - process(computation, mapTask, inputDataWatermark, outputDataWatermark, work); + process(computation, mapTask, inputDataWatermark, outputDataWatermark, + synchronizedProcessingTime, work); } }); } else { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java index a8bdceb186..b4bbdcc61b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java @@ -70,6 +70,7 @@ public class StreamingModeExecutionContext private Windmill.WorkItem work; @Nullable private Instant inputDataWatermark; @Nullable private Instant outputDataWatermark; + @Nullable private Instant synchronizedProcessingTime; private WindmillStateReader stateReader; private StateFetcher stateFetcher; private Windmill.WorkItemCommitRequest.Builder outputBuilder; @@ -89,19 +90,22 @@ public void start( Windmill.WorkItem work, @Nullable Instant inputDataWatermark, @Nullable Instant outputDataWatermark, + @Nullable Instant synchronizedProcessingTime, WindmillStateReader stateReader, StateFetcher stateFetcher, Windmill.WorkItemCommitRequest.Builder outputBuilder) { this.work = work; this.inputDataWatermark = inputDataWatermark; this.outputDataWatermark = outputDataWatermark; + this.synchronizedProcessingTime = synchronizedProcessingTime; this.stateReader = stateReader; this.stateFetcher = stateFetcher; this.outputBuilder = outputBuilder; this.sideInputCache.clear(); for (ExecutionContext.StepContext stepContext : getAllStepContexts()) { - ((StepContext) stepContext).start(stateReader, inputDataWatermark, outputDataWatermark); + ((StepContext) stepContext) + .start(stateReader, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime); } } @@ -109,7 +113,7 @@ public void start( public StepContext createStepContext( String stepName, String transformName, StateSampler stateSampler) { StepContext context = new StepContext(stepName, transformName, stateSampler); - context.start(stateReader, inputDataWatermark, outputDataWatermark); + context.start(stateReader, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime); return context; } @@ -297,11 +301,11 @@ private static class WindmillTimerInternals implements TimerInternals { private Map timers = new HashMap<>(); @Nullable private Instant inputDataWatermark; @Nullable private Instant outputDataWatermark; + @Nullable private Instant synchronizedProcessingTime; private String stateFamily; - public WindmillTimerInternals( - String stateFamily, @Nullable Instant inputDataWatermark, - @Nullable Instant outputDataWatermark) { + public WindmillTimerInternals(String stateFamily, @Nullable Instant inputDataWatermark, + @Nullable Instant outputDataWatermark, @Nullable Instant synchronizedProcessingTime) { this.inputDataWatermark = inputDataWatermark; this.outputDataWatermark = outputDataWatermark; this.stateFamily = stateFamily; @@ -322,6 +326,12 @@ public Instant currentProcessingTime() { return Instant.now(); } + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return synchronizedProcessingTime; + } + /** * {@inheritDoc} * @@ -417,12 +427,14 @@ public StateSampler.ScopedState get() { */ public void start( WindmillStateReader stateReader, @Nullable Instant inputDataWatermark, - @Nullable Instant outputDataWatermark) { + @Nullable Instant outputDataWatermark, + @Nullable Instant synchronizedProcessingTime) { this.stateInternals = new WindmillStateInternals(stateFamily, stateReader, stateCache.forKey(getSerializedKey(), stateFamily, getWork().getCacheToken()), scopedReadStateSupplier); this.timerInternals = - new WindmillTimerInternals(stateFamily, inputDataWatermark, outputDataWatermark); +new WindmillTimerInternals( + stateFamily, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime); } public void flushState() { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java index 880f9e05fb..8b5038a81c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java @@ -264,6 +264,14 @@ public abstract class TriggerContext { /** The current processing time. */ public abstract Instant currentProcessingTime(); + + /** The current synchronized upstream processing time or {@code null} if unknown. */ + @Nullable + public abstract Instant currentSynchronizedProcessingTime(); + + /** The current event time for the input or {@code null} if unknown. */ + @Nullable + public abstract Instant currentEventTime(); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java index 29492c3892..8df5406417 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java @@ -69,6 +69,18 @@ public Instant currentProcessingTime() { return processingTime; } + /** + * {@inheritDoc} + * + * @return {@link BoundedWindow#TIMESTAMP_MAX_VALUE}: in batch mode, upstream processing + * is already complete. + */ + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return BoundedWindow.TIMESTAMP_MAX_VALUE; + } + @Override public Instant currentInputWatermarkTime() { return inputWatermarkTime; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java index e76868aa42..3ac2126fdd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java @@ -29,6 +29,8 @@ import java.util.Collection; import java.util.Map; +import javax.annotation.Nullable; + /** * Specification for processing to happen after elements have been grouped by key. * @@ -103,6 +105,14 @@ public interface Timers { /** Returns the current processing time. */ public abstract Instant currentProcessingTime(); + + /** Returns the current synchronized processing time or {@code null} if unknown. */ + @Nullable + public abstract Instant currentSynchronizedProcessingTime(); + + /** Returns the current event time or {@code null} if unknown. */ + @Nullable + public abstract Instant currentEventTime(); } /** Information accessible to all the processing methods in this {@code ReduceFn}. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index 643919035f..e0d7c2e22c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -40,6 +40,8 @@ import java.util.List; import java.util.Map; +import javax.annotation.Nullable; + /** * Factory for creating instances of the various {@link ReduceFn} contexts. */ @@ -117,6 +119,18 @@ public void deleteTimer(Instant timestamp, TimeDomain timeDomain) { public Instant currentProcessingTime() { return timerInternals.currentProcessingTime(); } + + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return timerInternals.currentSynchronizedProcessingTime(); + } + + @Override + @Nullable + public Instant currentEventTime() { + return timerInternals.currentInputWatermarkTime(); + } } static class StateContextImpl diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java index aa44c50058..bedff3e8d6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java @@ -54,6 +54,13 @@ public interface TimerInternals { */ Instant currentProcessingTime(); + /** + * Returns the current timestamp in the {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} time + * domain or {@code null} if unknown. + */ + @Nullable + Instant currentSynchronizedProcessingTime(); + /** * Return the current, local input watermark timestamp for this computation * in the {@link TimeDomain#EVENT_TIME} time domain. Return {@code null} if unknown. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 8c438cea14..86e17eb1cc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -33,6 +33,8 @@ import java.util.Collection; import java.util.Map; +import javax.annotation.Nullable; + /** * Factory for creating instances of the various {@link Trigger} contexts. * @@ -193,6 +195,18 @@ public void deleteTimer(Instant timestamp, TimeDomain timeDomain) { public Instant currentProcessingTime() { return timers.currentProcessingTime(); } + + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return timers.currentSynchronizedProcessingTime(); + } + + @Override + @Nullable + public Instant currentEventTime() { + return timers.currentEventTime(); + } } private class MergingTriggerInfoImpl @@ -305,8 +319,19 @@ public void deleteTimer(Instant timestamp, TimeDomain domain) { public Instant currentProcessingTime() { return timers.currentProcessingTime(); } - } + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return timers.currentSynchronizedProcessingTime(); + } + + @Override + @Nullable + public Instant currentEventTime() { + return timers.currentEventTime(); + } + } private class OnElementContextImpl extends Trigger.OnElementContext { @@ -370,6 +395,18 @@ public void deleteTimer(Instant timestamp, TimeDomain domain) { public Instant currentProcessingTime() { return timers.currentProcessingTime(); } + + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return timers.currentSynchronizedProcessingTime(); + } + + @Override + @Nullable + public Instant currentEventTime() { + return timers.currentEventTime(); + } } private class OnTimerContextImpl extends Trigger.OnTimerContext { @@ -435,6 +472,18 @@ public void deleteTimer(Instant timestamp, TimeDomain domain) { public Instant currentProcessingTime() { return timers.currentProcessingTime(); } + + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return timers.currentSynchronizedProcessingTime(); + } + + @Override + @Nullable + public Instant currentEventTime() { + return timers.currentEventTime(); + } } private class OnMergeContextImpl extends Trigger.OnMergeContext { @@ -499,5 +548,17 @@ public void deleteTimer(Instant timestamp, TimeDomain domain) { public Instant currentProcessingTime() { return timers.currentProcessingTime(); } + + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return timers.currentSynchronizedProcessingTime(); + } + + @Override + @Nullable + public Instant currentEventTime() { + return timers.currentEventTime(); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index 57f6185b42..54bdf60adb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -646,6 +646,7 @@ public void testReadUnboundedReader() throws Exception { .build(), new Instant(0), // input watermark null, // output watermark + null, // synchronized processing time null, // StateReader null, // StateFetcher Windmill.WorkItemCommitRequest.newBuilder()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java index 9c4f272e17..826ce11eef 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java @@ -86,6 +86,7 @@ public void testTimerInternalsSetTimer() { Windmill.WorkItem.newBuilder().setKey(ByteString.EMPTY).setWorkToken(17L).build(), new Instant(1000), // input watermark null, // output watermark + null, // synchronized processing time stateReader, stateFetcher, outputBuilder); ExecutionContext.StepContext step = executionContext.getOrCreateStepContext("step", "transform", null); @@ -148,6 +149,7 @@ private void startContext( .build(), new Instant(0), // input watermark null, // output watermark + null, // synchronized processing time null, // StateReader null, // StateFetcher Windmill.WorkItemCommitRequest.newBuilder()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index 8327359277..bb889d8283 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -309,6 +309,16 @@ public void advanceProcessingTime(Instant newProcessingTime) throws Exception { runner.persist(); } + /** + * Advance the synchronized processing time to the specified time, + * firing any timers that should fire. + */ + public void advanceSynchronizedProcessingTime(Instant newProcessingTime) throws Exception { + ReduceFnRunner runner = createRunner(); + timerInternals.advanceSynchronizedProcessingTime(runner, newProcessingTime); + runner.persist(); + } + /** * Inject all the timestamped values (after passing through the window function) as if they * arrived in a single chunk of a bundle (or work-unit). @@ -511,6 +521,10 @@ private class TestTimerInternals implements TimerInternals { /** Current processing time. */ private Instant processingTime = BoundedWindow.TIMESTAMP_MIN_VALUE; + /** Current synchronized processing time. */ + @Nullable + private Instant synchronizedProcessingTime = null; + private PriorityQueue queue(TimeDomain domain) { return TimeDomain.EVENT_TIME.equals(domain) ? watermarkTimers : processingTimers; } @@ -535,6 +549,12 @@ public Instant currentProcessingTime() { return processingTime; } + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return synchronizedProcessingTime; + } + @Override @Nullable public Instant currentInputWatermarkTime() { @@ -607,6 +627,18 @@ public void advanceProcessingTime( advanceAndFire(runner, newProcessingTime, TimeDomain.PROCESSING_TIME); } + public void advanceSynchronizedProcessingTime( + ReduceFnRunner runner, Instant newSynchronizedProcessingTime) { + Preconditions.checkState(!newSynchronizedProcessingTime.isBefore(synchronizedProcessingTime), + "Cannot move processing time backwards from %s to %s", processingTime, + newSynchronizedProcessingTime); + WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", + synchronizedProcessingTime, newSynchronizedProcessingTime); + synchronizedProcessingTime = newSynchronizedProcessingTime; + advanceAndFire( + runner, newSynchronizedProcessingTime, TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + } + private void advanceAndFire( ReduceFnRunner runner, Instant currentTime, TimeDomain domain) { PriorityQueue queue = queue(domain); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index 7b3a6593e0..6de9382041 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -259,6 +259,12 @@ public void advanceProcessingTime(Instant newProcessingTime) throws Exception { timerInternals.advanceProcessingTime(newProcessingTime); } + /** Advance the processing time to the specified time, firing any timers that should fire. */ + public void advanceSynchronizedProcessingTime(Instant newSynchronizedProcessingTime) + throws Exception { + timerInternals.advanceSynchronizedProcessingTime(newSynchronizedProcessingTime); + } + /** * Inject all the timestamped values (after passing through the window function) as if they * arrived in a single chunk of a bundle (or work-unit). @@ -460,6 +466,9 @@ private class TestTimerInternals implements TimerInternals { /** Current processing time. */ private Instant processingTime = BoundedWindow.TIMESTAMP_MIN_VALUE; + /** Current processing time. */ + private Instant synchronizedProcessingTime = null; + private PriorityQueue queue(TimeDomain domain) { return TimeDomain.EVENT_TIME.equals(domain) ? watermarkTimers : processingTimers; } @@ -484,6 +493,12 @@ public Instant currentProcessingTime() { return processingTime; } + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return synchronizedProcessingTime; + } + @Override @Nullable public Instant currentInputWatermarkTime() { @@ -552,6 +567,17 @@ public void advanceProcessingTime(Instant newProcessingTime) throws Exception { advanceAndFire(newProcessingTime, TimeDomain.PROCESSING_TIME); } + public void advanceSynchronizedProcessingTime(Instant newSynchronizedProcessingTime) + throws Exception { + checkState(!newSynchronizedProcessingTime.isBefore(synchronizedProcessingTime), + "Cannot move processing time backwards from %s to %s", synchronizedProcessingTime, + newSynchronizedProcessingTime); + WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", + synchronizedProcessingTime, newSynchronizedProcessingTime); + synchronizedProcessingTime = newSynchronizedProcessingTime; + advanceAndFire(newSynchronizedProcessingTime, TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + } + private void advanceAndFire(Instant currentTime, TimeDomain domain) throws Exception { PriorityQueue queue = queue(domain); @@ -599,5 +625,17 @@ public void deleteTimer(Instant timestamp, TimeDomain timeDomain) { public Instant currentProcessingTime() { return timerInternals.currentProcessingTime(); } + + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return timerInternals.currentSynchronizedProcessingTime(); + } + + @Override + @Nullable + public Instant currentEventTime() { + return timerInternals.currentInputWatermarkTime(); + } } } From cfda3ff87ef04ed8603f77eca5b5fe72f900a562 Mon Sep 17 00:00:00 2001 From: klk Date: Fri, 22 Jan 2016 12:36:05 -0800 Subject: [PATCH 030/751] Update Triggers to new shouldFire() based semantics User-facing trigger expressions are unchanged in syntax or semantics. The high-level change to the internal-facing API is as follows: - onElement no longer returns a TriggerResult, now void - onMerge no longer returns a MergeResult, now void - onTimer no longer exists in Trigger (it exists in the runner only) - shouldFire says whether to fire; the runner controls when to ask - onFire transitions/resets a trigger for sequential firings This also addresses a particular semantic issue where OrFinally did not fire as soon as expected. ----Release Notes---- - The "finally" branch of OrFinally now fires as soon as it is satisfied; before it would often take much longer due to seeing only the prefix of each work unit that satisfied the "main" branch. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112809409 --- .../sdk/transforms/windowing/AfterAll.java | 77 ++- .../windowing/AfterDelayFromFirstElement.java | 127 ++++ .../sdk/transforms/windowing/AfterEach.java | 123 ++-- .../sdk/transforms/windowing/AfterFirst.java | 67 ++- .../sdk/transforms/windowing/AfterPane.java | 52 +- .../windowing/AfterProcessingTime.java | 90 +-- .../AfterSynchronizedProcessingTime.java | 100 +--- .../transforms/windowing/AfterWatermark.java | 452 +++++---------- .../transforms/windowing/DefaultTrigger.java | 40 +- .../windowing/OrFinallyTrigger.java | 65 ++- .../sdk/transforms/windowing/Repeatedly.java | 47 +- .../sdk/transforms/windowing/Trigger.java | 164 ++---- .../dataflow/sdk/util/ExecutableTrigger.java | 75 +-- .../sdk/util/ReduceFnContextFactory.java | 4 +- .../dataflow/sdk/util/ReduceFnRunner.java | 187 +++--- .../dataflow/sdk/util/ReshuffleTrigger.java | 22 +- .../sdk/util/TriggerContextFactory.java | 95 +-- .../dataflow/sdk/util/TriggerRunner.java | 54 +- .../util/state/InMemoryStateInternals.java | 4 + .../transforms/windowing/AfterAllTest.java | 249 +++----- .../transforms/windowing/AfterEachTest.java | 233 ++------ .../transforms/windowing/AfterFirstTest.java | 240 +++----- .../transforms/windowing/AfterPaneTest.java | 67 ++- .../windowing/AfterProcessingTimeTest.java | 88 ++- .../AfterSynchronizedProcessingTimeTest.java | 95 +-- .../windowing/AfterWatermarkTest.java | 545 ++++++++---------- .../windowing/DefaultTriggerTest.java | 167 ++++-- .../windowing/OrFinallyTriggerTest.java | 300 ++++------ .../transforms/windowing/RepeatedlyTest.java | 155 ++--- .../transforms/windowing/TimeTriggerTest.java | 20 +- .../sdk/transforms/windowing/TriggerTest.java | 42 +- .../sdk/util/BatchTimerInternalsTest.java | 6 +- .../sdk/util/ExecutableTriggerTest.java | 25 +- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 512 ++++++++-------- .../sdk/util/ReshuffleTriggerTest.java | 29 +- .../dataflow/sdk/util/TriggerTester.java | 169 ++---- 36 files changed, 1945 insertions(+), 2842 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java index a40454631a..bb43010ae5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java @@ -49,59 +49,25 @@ public static OnceTrigger of( return new AfterAll(Arrays.>asList(triggers)); } - private TriggerResult result(TriggerContext c) { - // If all children have finished, then they must have each fired at least once. - if (c.trigger().areAllSubtriggersFinished()) { - return TriggerResult.FIRE_AND_FINISH; - } - - return TriggerResult.CONTINUE; - } - @Override - public TriggerResult onElement(OnElementContext c) throws Exception { + public void onElement(OnElementContext c) throws Exception { for (ExecutableTrigger subTrigger : c.trigger().unfinishedSubTriggers()) { // Since subTriggers are all OnceTriggers, they must either CONTINUE or FIRE_AND_FINISH. // invokeElement will automatically mark the finish bit if they return FIRE_AND_FINISH. - subTrigger.invokeElement(c); + subTrigger.invokeOnElement(c); } - - return result(c); } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // CONTINUE if merging returns CONTINUE for at least one sub-trigger - // ALREADY_FINISHED if merging returns ALREADY_FINISHED for all sub-triggers and this - // trigger itself was already finished in some window. - // FIRE_AND_FINISH otherwise: It means this trigger is ready to fire (because all subtriggers - // are satisfied) but has never fired as a whole. - boolean anyContinue = false; - boolean alreadyFinished = true; + public void onMerge(OnMergeContext c) throws Exception { for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - MergeResult result = subTrigger.invokeMerge(c); - anyContinue |= !result.isFire() && !result.isFinish(); - alreadyFinished &= !result.isFire() && result.isFinish(); + subTrigger.invokeOnMerge(c); } - - if (anyContinue) { - return MergeResult.CONTINUE; - } else if (alreadyFinished && c.trigger().finishedInAnyMergingWindow()) { - return MergeResult.ALREADY_FINISHED; - } else { - return MergeResult.FIRE_AND_FINISH; + boolean allFinished = true; + for (ExecutableTrigger subTrigger1 : c.trigger().subTriggers()) { + allFinished &= c.forTrigger(subTrigger1).trigger().isFinished(); } - } - - @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - for (ExecutableTrigger subTrigger : c.trigger().unfinishedSubTriggers()) { - // Since subTriggers are all OnceTriggers, they must either CONTINUE or FIRE_AND_FINISH. - // invokeTimer will automatically mark the finish bit if they return FIRE_AND_FINISH. - subTrigger.invokeTimer(c); - } - - return result(c); + c.trigger().setFinished(allFinished); } @Override @@ -121,4 +87,31 @@ public Instant getWatermarkThatGuaranteesFiring(W window) { public OnceTrigger getContinuationTrigger(List> continuationTriggers) { return new AfterAll(continuationTriggers); } + + /** + * {@inheritDoc} + * + * @return {@code true} if all subtriggers return {@code true}. + */ + @Override + public boolean shouldFire(TriggerContext context) throws Exception { + for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { + if (!context.forTrigger(subtrigger).trigger().isFinished() + && !subtrigger.invokeShouldFire(context)) { + return false; + } + } + return true; + } + + /** + * Invokes {@link #onFire} for all subtriggers, eliding redundant calls to {@link #shouldFire} + * because they all must be ready to fire. + */ + @Override + public void onOnlyFiring(TriggerContext context) throws Exception { + for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { + subtrigger.invokeOnFire(context); + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java new file mode 100644 index 0000000000..0272629399 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; + +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; + +import org.joda.time.Instant; + +import java.util.List; + +import javax.annotation.Nullable; + +/** + * A base class for triggers that happen after a processing time delay from the arrival + * of the first element in a pane. + */ +abstract class AfterDelayFromFirstElement extends TimeTrigger { + + /** + * To complete an implementation, return the desired time from the TriggerContext. + */ + @Nullable + public abstract Instant getCurrentTime(Trigger.TriggerContext context); + + private final TimeDomain timeDomain; + + public AfterDelayFromFirstElement( + TimeDomain timeDomain, List> timestampMappers) { + super(timestampMappers); + this.timeDomain = timeDomain; + } + + private Instant getTargetTimestamp(OnElementContext c) { + return computeTargetTimestamp(c.currentProcessingTime()); + } + + @Override + public void prefetchOnElement(StateContext state) { + state.access(DELAYED_UNTIL_TAG).get(); + } + + @Override + public void onElement(OnElementContext c) throws Exception { + CombiningValueState delayUntilState = c.state().access(DELAYED_UNTIL_TAG); + Instant oldDelayUntil = delayUntilState.get().read(); + + // Since processing time can only advance, resulting in target wake-up times we would + // ignore anyhow, we don't bother with it if it is already set. + if (oldDelayUntil != null) { + return; + } + + Instant targetTimestamp = getTargetTimestamp(c); + delayUntilState.add(targetTimestamp); + c.setTimer(targetTimestamp, timeDomain); + } + + @Override + public void prefetchOnMerge(MergingStateContext state) { + state.mergingAccess(DELAYED_UNTIL_TAG).get(); + } + + @Override + public void onMerge(OnMergeContext c) throws Exception { + // If the trigger is already finished, there is no way it will become re-activated + if (c.trigger().isFinished()) { + return; + } + + // Determine the earliest point across all the windows, and delay to that. + CombiningValueState mergingDelays = + c.state().mergingAccess(DELAYED_UNTIL_TAG); + + Instant earliestTargetTime = mergingDelays.get().read(); + if (earliestTargetTime != null) { + mergingDelays.clear(); + mergingDelays.add(earliestTargetTime); + c.setTimer(earliestTargetTime, timeDomain); + } + } + + @Override + public void prefetchShouldFire(StateContext state) { + state.access(DELAYED_UNTIL_TAG).get(); + } + + @Override + public void clear(TriggerContext c) throws Exception { + c.state().access(DELAYED_UNTIL_TAG).clear(); + } + + @Override + public Instant getWatermarkThatGuaranteesFiring(W window) { + return BoundedWindow.TIMESTAMP_MAX_VALUE; + } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + Instant delayedUntil = context.state().access(DELAYED_UNTIL_TAG).get().read(); + return delayedUntil != null + && getCurrentTime(context) != null + && getCurrentTime(context).isAfter(delayedUntil); + } + + @Override + protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { + clear(context); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java index bf16365bd8..4b052faeb8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java @@ -16,14 +16,14 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; +import static com.google.common.base.Preconditions.checkArgument; + import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.common.base.Preconditions; import org.joda.time.Instant; import java.util.Arrays; -import java.util.Iterator; import java.util.List; /** @@ -50,7 +50,7 @@ public class AfterEach extends Trigger { private AfterEach(List> subTriggers) { super(subTriggers); - Preconditions.checkArgument(subTriggers.size() > 1); + checkArgument(subTriggers.size() > 1); } /** @@ -61,94 +61,75 @@ public static Trigger inOrder(Trigger... trigger return new AfterEach(Arrays.>asList(triggers)); } - private TriggerResult result(TriggerContext c, TriggerResult subResult) - throws Exception { - if (subResult.isFire()) { - return c.trigger().areAllSubtriggersFinished() - ? TriggerResult.FIRE_AND_FINISH : TriggerResult.FIRE; + @Override + public void onElement(OnElementContext c) throws Exception { + if (!c.trigger().isMerging()) { + // If merges are not possible, we need only run the first unfinished subtrigger + c.trigger().firstUnfinishedSubTrigger().invokeOnElement(c); } else { - return TriggerResult.CONTINUE; + // If merges are possible, we need to run all subtriggers in parallel + for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { + // Even if the subTrigger is done, it may be revived via merging and must have + // adequate state. + subTrigger.invokeOnElement(c); + } } } @Override - public TriggerResult onElement(OnElementContext c) throws Exception { - Iterator> iterator = c.trigger().unfinishedSubTriggers().iterator(); - - // If all the sub-triggers have finished, we should have already finished, so we know there is - // at least one unfinished trigger. - TriggerResult firstResult = iterator.next().invokeElement(c); - - // If onMerge might be called, we need to make sure we have proper state for future triggers. - if (c.trigger().isMerging()) { - if (firstResult.isFire()) { - // If we're firing, clear out all of the later subtriggers, since we don't want to pollute - // their state. - resetRemaining(c, iterator); + public void onMerge(OnMergeContext context) throws Exception { + // If merging makes a subtrigger no-longer-finished, it will automatically + // begin participating in shouldFire and onFire appropriately. + + // All the following triggers are retroactively "not started" but that is + // also automatic because they are cleared whenever this trigger + // fires. + boolean priorTriggersAllFinished = true; + for (ExecutableTrigger subTrigger : context.trigger().subTriggers()) { + if (priorTriggersAllFinished) { + subTrigger.invokeOnMerge(context); + priorTriggersAllFinished &= context.forTrigger(subTrigger).trigger().isFinished(); } else { - // Otherwise, iterate over all of them to build up some state. - while (iterator.hasNext()) { - iterator.next().invokeElement(c); - } + subTrigger.invokeClear(context); } } - - return result(c, firstResult); + updateFinishedState(context); } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // Iterate over the sub-triggers to identify the "current" sub-trigger. - Iterator> iterator = c.trigger().subTriggers().iterator(); - while (iterator.hasNext()) { - ExecutableTrigger subTrigger = iterator.next(); - - MergeResult mergeResult = subTrigger.invokeMerge(c); - - if (MergeResult.CONTINUE.equals(mergeResult)) { - resetRemaining(c, iterator); - return MergeResult.CONTINUE; - } else if (MergeResult.FIRE.equals(mergeResult)) { - resetRemaining(c, iterator); - return MergeResult.FIRE; - } else if (MergeResult.FIRE_AND_FINISH.equals(mergeResult)) { - resetRemaining(c, iterator); - return c.trigger().areAllSubtriggersFinished() - ? MergeResult.FIRE_AND_FINISH : MergeResult.FIRE; - } - } - - // If we get here, all the merges indicated they were finished, which means there was at least - // one merged window in which the triggers had all already finished. Given that, this AfterEach - // would have already finished in that window as well. Since the window was still in the window - // set for merging, we can return FINISHED (because we were finished in that window) and we also - // know that there must be another trigger (parent or sibling) which hasn't finished yet, which - // will FIRE, CONTINUE, or FIRE_AND_FINISH. - return MergeResult.ALREADY_FINISHED; + public Instant getWatermarkThatGuaranteesFiring(W window) { + // This trigger will fire at least once when the first trigger in the sequence + // fires at least once. + return subTriggers.get(0).getWatermarkThatGuaranteesFiring(window); } - private void resetRemaining( - TriggerContext c, Iterator> triggers) throws Exception { - while (triggers.hasNext()) { - c.forTrigger(triggers.next()).trigger().resetTree(); - } + @Override + public Trigger getContinuationTrigger(List> continuationTriggers) { + return Repeatedly.forever(new AfterFirst(continuationTriggers)); } @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - // Only deliver to the currently active subtrigger - return result(c, c.trigger().firstUnfinishedSubTrigger().invokeTimer(c)); + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + ExecutableTrigger firstUnfinished = context.trigger().firstUnfinishedSubTrigger(); + return firstUnfinished.invokeShouldFire(context); } @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - // This trigger will fire at least once when the first trigger in the sequence - // fires at least once. - return subTriggers.get(0).getWatermarkThatGuaranteesFiring(window); + public void onFire(Trigger.TriggerContext context) throws Exception { + context.trigger().firstUnfinishedSubTrigger().invokeOnFire(context); + + // Reset all subtriggers if in a merging context; any may be revived by merging so they are + // all run in parallel for each pending pane. + if (context.trigger().isMerging()) { + for (ExecutableTrigger subTrigger : context.trigger().subTriggers()) { + subTrigger.invokeClear(context); + } + } + + updateFinishedState(context); } - @Override - public Trigger getContinuationTrigger(List> continuationTriggers) { - return Repeatedly.forever(new AfterFirst(continuationTriggers)); + private void updateFinishedState(TriggerContext context) { + context.trigger().setFinished(context.trigger().firstUnfinishedSubTrigger() == null); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java index 534649b587..29b19bf9b9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java @@ -51,41 +51,18 @@ public static OnceTrigger of( } @Override - public TriggerResult onElement(OnElementContext c) throws Exception { + public void onElement(OnElementContext c) throws Exception { for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - if (subTrigger.invokeElement(c).isFire()) { - return TriggerResult.FIRE_AND_FINISH; - } - } - - return TriggerResult.CONTINUE; - } - - @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // FINISH if merging returns FINISH for any sub-trigger. - // FIRE_AND_FINISH if merging returns FIRE or FIRE_AND_FINISH for at least one sub-trigger. - // CONTINUE otherwise - boolean fired = false; - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - MergeResult mergeResult = subTrigger.invokeMerge(c); - if (MergeResult.ALREADY_FINISHED.equals(mergeResult)) { - return MergeResult.ALREADY_FINISHED; - } else if (mergeResult.isFire()) { - fired = true; - } + subTrigger.invokeOnElement(c); } - return fired ? MergeResult.FIRE_AND_FINISH : MergeResult.CONTINUE; } @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { + public void onMerge(OnMergeContext c) throws Exception { for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - if (subTrigger.invokeTimer(c).isFire()) { - return TriggerResult.FIRE_AND_FINISH; - } + subTrigger.invokeOnMerge(c); } - return TriggerResult.CONTINUE; + updateFinishedStatus(c); } @Override @@ -105,4 +82,38 @@ public Instant getWatermarkThatGuaranteesFiring(W window) { public OnceTrigger getContinuationTrigger(List> continuationTriggers) { return new AfterFirst(continuationTriggers); } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { + if (context.forTrigger(subtrigger).trigger().isFinished() + || subtrigger.invokeShouldFire(context)) { + return true; + } + } + return false; + } + + @Override + protected void onOnlyFiring(TriggerContext context) throws Exception { + for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { + TriggerContext subContext = context.forTrigger(subtrigger); + if (subtrigger.invokeShouldFire(subContext)) { + // If the trigger is ready to fire, then do whatever it needs to do. + subtrigger.invokeOnFire(subContext); + } else { + // If the trigger is not ready to fire, it is nonetheless true that whatever + // pending pane it was tracking is now gone. + subtrigger.invokeClear(subContext); + } + } + } + + private void updateFinishedStatus(TriggerContext c) { + boolean anyFinished = false; + for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { + anyFinished |= c.forTrigger(subTrigger).trigger().isFinished(); + } + c.trigger().setFinished(anyFinished); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java index bdc04c2c17..642efd1875 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java @@ -23,7 +23,6 @@ import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; -import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -60,20 +59,8 @@ public static AfterPane elementCountAtLeast(int cou } @Override - public void prefetchOnElement(StateContext state) { - state.access(ELEMENTS_IN_PANE_TAG).get(); - } - - @Override - public TriggerResult onElement(OnElementContext c) throws Exception { - CombiningValueState elementsInPane = c.state().access(ELEMENTS_IN_PANE_TAG); - StateContents countContents = elementsInPane.get(); - elementsInPane.add(1L); - - // TODO: Consider waiting to read the value until the end of a bundle, since we don't need to - // fire immediately when the count exceeds countElems. - long count = countContents.read(); - return count >= countElems ? TriggerResult.FIRE_AND_FINISH : TriggerResult.CONTINUE; + public void onElement(OnElementContext c) throws Exception { + c.state().access(ELEMENTS_IN_PANE_TAG).add(1L); } @Override @@ -82,31 +69,27 @@ public void prefetchOnMerge(MergingStateContext state) { } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // If we've already received enough elements and finished in some window, then this trigger - // is just finished. - if (c.trigger().finishedInAnyMergingWindow()) { - return MergeResult.ALREADY_FINISHED; + public void onMerge(OnMergeContext context) throws Exception { + if (context.trigger().finishedInAnyMergingWindow()) { + context.trigger().setFinished(true); + return; } - // Otherwise, compute the sum of elements in all the active panes - CombiningValueState elementsInPane = c.state().mergingAccess(ELEMENTS_IN_PANE_TAG); - // Both InMemoryStateInternals and WindmillStateInternals implement merging access using - // MergeCombiningValue. The implementation of StateContents.read returned by get will - // eagerly compact state on read. Thus after the following we are guaranteed all state from - // merged windows will have been compacted away. - // TODO: Make this more explicit and less fragile with a 'compact' API? - long count = elementsInPane.get().read(); - return count >= countElems ? MergeResult.FIRE_AND_FINISH : MergeResult.CONTINUE; + // Eagerly merge + long count = context.state().mergingAccess(ELEMENTS_IN_PANE_TAG).get().read(); + context.state().mergingAccess(ELEMENTS_IN_PANE_TAG).clear(); + context.state().access(ELEMENTS_IN_PANE_TAG).add(count); } @Override - public TriggerResult onTimer(OnTimerContext c) { - return TriggerResult.CONTINUE; + public void prefetchShouldFire(StateContext state) { + state.access(ELEMENTS_IN_PANE_TAG).get(); } @Override - public void prefetchOnTimer(StateContext state) { + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + long count = context.state().access(ELEMENTS_IN_PANE_TAG).get().read(); + return count >= countElems; } @Override @@ -150,4 +133,9 @@ public boolean equals(Object obj) { public int hashCode() { return Objects.hash(countElems); } + + @Override + protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { + clear(context); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java index 4c269c28e6..7e89902741 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java @@ -18,16 +18,15 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import org.joda.time.Instant; import java.util.List; import java.util.Objects; +import javax.annotation.Nullable; + /** * {@code AfterProcessingTime} triggers fire based on the current processing time. They operate in * the real-time domain. @@ -38,10 +37,16 @@ * @param {@link BoundedWindow} subclass used to represent the windows used */ @Experimental(Experimental.Kind.TRIGGER) -public class AfterProcessingTime extends TimeTrigger { +public class AfterProcessingTime extends AfterDelayFromFirstElement { + + @Override + @Nullable + public Instant getCurrentTime(Trigger.TriggerContext context) { + return context.currentProcessingTime(); + } private AfterProcessingTime(List> transforms) { - super(transforms); + super(TimeDomain.PROCESSING_TIME, transforms); } /** @@ -58,81 +63,6 @@ protected AfterProcessingTime newWith( return new AfterProcessingTime(transforms); } - @Override - public void prefetchOnElement(StateContext state) { - state.access(DELAYED_UNTIL_TAG).get(); - } - - @Override - public TriggerResult onElement(OnElementContext c) - throws Exception { - CombiningValueState delayUntilState = c.state().access(DELAYED_UNTIL_TAG); - Instant delayUntil = delayUntilState.get().read(); - if (delayUntil == null) { - delayUntil = computeTargetTimestamp(c.currentProcessingTime()); - c.setTimer(delayUntil, TimeDomain.PROCESSING_TIME); - delayUntilState.add(delayUntil); - } - - return TriggerResult.CONTINUE; - } - - @Override - public void prefetchOnMerge(MergingStateContext state) { - state.mergingAccess(DELAYED_UNTIL_TAG).get(); - } - - @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // If the processing time timer has fired in any of the windows being merged, it would have - // fired at the same point if it had been added to the merged window. So, we just report it as - // finished. - if (c.trigger().finishedInAnyMergingWindow()) { - return MergeResult.ALREADY_FINISHED; - } - - // Determine the earliest point across all the windows, and delay to that. - CombiningValueState mergingDelays = - c.state().mergingAccess(DELAYED_UNTIL_TAG); - Instant earliestTimer = mergingDelays.get().read(); - if (earliestTimer != null) { - mergingDelays.clear(); - mergingDelays.add(earliestTimer); - c.setTimer(earliestTimer, TimeDomain.PROCESSING_TIME); - } - - return MergeResult.CONTINUE; - } - - @Override - public void prefetchOnTimer(StateContext state) { - state.access(DELAYED_UNTIL_TAG).get(); - } - - @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - if (c.timeDomain() != TimeDomain.PROCESSING_TIME) { - return TriggerResult.CONTINUE; - } - - Instant delayedUntil = c.state().access(DELAYED_UNTIL_TAG).get().read(); - if (delayedUntil == null || delayedUntil.isAfter(c.timestamp())) { - return TriggerResult.CONTINUE; - } - - return TriggerResult.FIRE_AND_FINISH; - } - - @Override - public void clear(TriggerContext c) throws Exception { - CombiningValueState delayed = c.state().access(DELAYED_UNTIL_TAG); - Instant timestamp = delayed.get().read(); - delayed.clear(); - if (timestamp != null) { - c.deleteTimer(timestamp, TimeDomain.PROCESSING_TIME); - } - } - @Override public Instant getWatermarkThatGuaranteesFiring(W window) { return BoundedWindow.TIMESTAMP_MAX_VALUE; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java index e15f4a96c3..a811a9b273 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java @@ -15,98 +15,30 @@ */ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static com.google.cloud.dataflow.sdk.transforms.windowing.TimeTrigger.DELAYED_UNTIL_TAG; - -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import com.google.common.base.Objects; import org.joda.time.Instant; +import java.util.Collections; import java.util.List; -class AfterSynchronizedProcessingTime extends OnceTrigger { - - public AfterSynchronizedProcessingTime() { - super(null); - } - - @Override - public void prefetchOnElement(StateContext state) { - state.access(DELAYED_UNTIL_TAG).get(); - } - - @Override - public TriggerResult onElement(OnElementContext c) - throws Exception { - CombiningValueState delayUntilState = c.state().access(DELAYED_UNTIL_TAG); - Instant delayUntil = delayUntilState.get().read(); - if (delayUntil == null) { - delayUntil = c.currentProcessingTime(); - c.setTimer(delayUntil, TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - delayUntilState.add(delayUntil); - } - - return TriggerResult.CONTINUE; - } - - @Override - public void prefetchOnMerge(MergingStateContext state) { - state.mergingAccess(DELAYED_UNTIL_TAG).get(); - } - - @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // If the processing time timer has fired in any of the windows being merged, it would have - // fired at the same point if it had been added to the merged window. So, we just report it as - // finished. - if (c.trigger().finishedInAnyMergingWindow()) { - return MergeResult.ALREADY_FINISHED; - } - - // Otherwise, determine the earliest delay for all of the windows, and delay to that point. - CombiningValueState mergingDelays = - c.state().mergingAccess(DELAYED_UNTIL_TAG); - Instant earliestTimer = mergingDelays.get().read(); - if (earliestTimer != null) { - mergingDelays.clear(); - mergingDelays.add(earliestTimer); - c.setTimer(earliestTimer, TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - } - - return MergeResult.CONTINUE; - } +import javax.annotation.Nullable; - @Override - public void prefetchOnTimer(StateContext state) { - state.access(DELAYED_UNTIL_TAG).get(); - } +class AfterSynchronizedProcessingTime + extends AfterDelayFromFirstElement { @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - if (c.timeDomain() != TimeDomain.SYNCHRONIZED_PROCESSING_TIME) { - return TriggerResult.CONTINUE; - } - - Instant delayedUntil = c.state().access(DELAYED_UNTIL_TAG).get().read(); - if (delayedUntil == null || delayedUntil.isAfter(c.timestamp())) { - return TriggerResult.CONTINUE; - } - - return TriggerResult.FIRE_AND_FINISH; + @Nullable + public Instant getCurrentTime(Trigger.TriggerContext context) { + // TODO: plumb synchronized processing time + return context.currentProcessingTime(); } - @Override - public void clear(TriggerContext c) throws Exception { - CombiningValueState delayed = c.state().access(DELAYED_UNTIL_TAG); - Instant timestamp = delayed.get().read(); - delayed.clear(); - if (timestamp != null) { - c.deleteTimer(timestamp, TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - } + public AfterSynchronizedProcessingTime() { + super(TimeDomain.SYNCHRONIZED_PROCESSING_TIME, + Collections.>emptyList()); } @Override @@ -133,4 +65,12 @@ public boolean equals(Object obj) { public int hashCode() { return Objects.hashCode(AfterSynchronizedProcessingTime.class); } + + @Override + protected AfterSynchronizedProcessingTime + newWith(List> transforms) { + // ignore transforms + return this; + } + } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index 3b8302f9cc..694a538f6c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -16,14 +16,12 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; @@ -69,14 +67,6 @@ public class AfterWatermark { // Static factory class. private AfterWatermark() {} - /** - * Creates a trigger that fires when the watermark passes timestamp of the first element added to - * the pane. - */ - static TimeTrigger pastFirstElementInPane() { - return new FromFirstElementInPane(TimeTrigger.IDENTITY); - } - /** * Creates a trigger that fires when the watermark passes the end of the window. */ @@ -84,132 +74,6 @@ public static FromEndOfWindow pastEndOfWindow() { return new FromEndOfWindow(); } - /** - * A watermark trigger targeted relative to the event time of the first element in the pane. - */ - private static class FromFirstElementInPane extends TimeTrigger { - - private FromFirstElementInPane( - List> delayFunction) { - super(delayFunction); - } - - @Override - public void prefetchOnElement(StateContext state) { - state.access(DELAYED_UNTIL_TAG).get(); - } - - @Override - public TriggerResult onElement(OnElementContext c) throws Exception { - CombiningValueState delayUntilState = c.state().access(DELAYED_UNTIL_TAG); - Instant delayUntil = delayUntilState.get().read(); - if (delayUntil == null) { - delayUntil = computeTargetTimestamp(c.eventTimestamp()); - c.setTimer(delayUntil, TimeDomain.EVENT_TIME); - delayUntilState.add(delayUntil); - } - - return TriggerResult.CONTINUE; - } - - @Override - public void prefetchOnMerge(MergingStateContext state) { - state.mergingAccess(DELAYED_UNTIL_TAG).get(); - } - - @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // If the watermark time timer has fired in any of the windows being merged, it would have - // fired at the same point if it had been added to the merged window. So, we just record it as - // finished. - if (c.trigger().finishedInAnyMergingWindow()) { - return MergeResult.ALREADY_FINISHED; - } - - // To have gotten here, we must not have fired in any of the oldWindows. Determine the event - // timestamp from the minimum (we could also just pick one, or try to record the arrival times - // of this first element in each pane). - // Determine the earliest point across all the windows, and delay to that. - CombiningValueState mergingDelays = - c.state().mergingAccess(DELAYED_UNTIL_TAG); - Instant earliestTimer = mergingDelays.get().read(); - if (earliestTimer != null) { - mergingDelays.clear(); - mergingDelays.add(earliestTimer); - c.setTimer(earliestTimer, TimeDomain.EVENT_TIME); - } - - return MergeResult.CONTINUE; - } - - @Override - public void prefetchOnTimer(StateContext state) { - state.access(DELAYED_UNTIL_TAG).get(); - } - - @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - if (c.timeDomain() != TimeDomain.EVENT_TIME) { - return TriggerResult.CONTINUE; - } - - Instant delayedUntil = c.state().access(DELAYED_UNTIL_TAG).get().read(); - if (delayedUntil == null || delayedUntil.isAfter(c.timestamp())) { - return TriggerResult.CONTINUE; - } - - return TriggerResult.FIRE_AND_FINISH; - } - - @Override - public void clear(TriggerContext c) throws Exception { - CombiningValueState delayed = c.state().access(DELAYED_UNTIL_TAG); - Instant timestamp = delayed.get().read(); - delayed.clear(); - if (timestamp != null) { - c.deleteTimer(timestamp, TimeDomain.EVENT_TIME); - } - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return computeTargetTimestamp(window.maxTimestamp()); - } - - @Override - protected FromFirstElementInPane newWith( - List> transforms) { - return new FromFirstElementInPane(transforms); - } - - @Override - public OnceTrigger getContinuationTrigger(List> continuationTriggers) { - return this; - } - - @Override - public String toString() { - return "AfterWatermark.pastFirstElementInPane(" + timestampMappers + ")"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof FromFirstElementInPane)) { - return false; - } - FromFirstElementInPane that = (FromFirstElementInPane) obj; - return Objects.equals(this.timestampMappers, that.timestampMappers); - } - - @Override - public int hashCode() { - return Objects.hashCode(timestampMappers); - } - } - /** * Interface for building an AfterWatermarkTrigger with early firings already filled in. */ @@ -243,21 +107,10 @@ protected NeverTrigger() { } @Override - public TriggerResult onElement(OnElementContext c) throws Exception { - return TriggerResult.CONTINUE; - } + public void onElement(OnElementContext c) throws Exception { } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - return c.trigger().finishedInAnyMergingWindow() - ? MergeResult.ALREADY_FINISHED - : MergeResult.CONTINUE; - } - - @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - return TriggerResult.CONTINUE; - } + public void onMerge(OnMergeContext c) throws Exception { } @Override protected Trigger getContinuationTrigger(List> continuationTriggers) { @@ -268,6 +121,17 @@ protected Trigger getContinuationTrigger(List> continuationTrigger public Instant getWatermarkThatGuaranteesFiring(W window) { return BoundedWindow.TIMESTAMP_MAX_VALUE; } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return false; + } + + @Override + protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { + throw new UnsupportedOperationException( + String.format("%s should never fire", getClass().getSimpleName())); + } } private static class AfterWatermarkEarlyAndLate @@ -285,8 +149,7 @@ private AfterWatermarkEarlyAndLate(OnceTrigger earlyTrigger, OnceTrigger l super(lateTrigger == null ? ImmutableList.>of(earlyTrigger) : ImmutableList.>of(earlyTrigger, lateTrigger)); - this.earlyTrigger = - Preconditions.checkNotNull(earlyTrigger, "earlyTrigger should not be null"); + this.earlyTrigger = checkNotNull(earlyTrigger, "earlyTrigger should not be null"); this.lateTrigger = lateTrigger; } @@ -301,147 +164,42 @@ public TriggerBuilder withLateFirings(OnceTrigger lateTrigger) { } @Override - public TriggerResult onElement(OnElementContext c) throws Exception { - // We always have an early trigger, even if it is the one that never fires. It will be marked - // as finished once the watermark has passed the end of the window. - - if (!c.trigger().isFinished(EARLY_INDEX)) { - // We're running the early trigger. If the window function is merging, we need to also - // pass the events to the late trigger, so that merging data is available. - ExecutableTrigger current = c.trigger().subTrigger(EARLY_INDEX); - TriggerResult result = current.invokeElement(c); - if (result.isFire()) { - // the subtriggers are OnceTriggers that are implicitly repeated. Rather than having - // wrapped them explicitly, we implement that logic here. This allows us to take advantage - // of the fact that they're being repeated to improve the implementation of this trigger. - current.invokeClear(c); - c.trigger().setFinished(false, EARLY_INDEX); - - if (lateTrigger != null && c.trigger().isMerging()) { - c.trigger().subTrigger(LATE_INDEX).invokeClear(c); - } - - return TriggerResult.FIRE; - } else { - - if (lateTrigger != null && c.trigger().isMerging()) { - if (c.trigger().subTrigger(LATE_INDEX).invokeElement(c).isFinish()) { - // If late trigegr finishes, clear it out and keep going. - c.trigger().subTrigger(LATE_INDEX).invokeClear(c); - c.trigger().setFinished(false, LATE_INDEX); - } - } - - return TriggerResult.CONTINUE; - } - } else if (lateTrigger != null) { - // We're running the late trigger -- otherwise the root would have finished when the early - // finished. - ExecutableTrigger current = c.trigger().subTrigger(LATE_INDEX); - TriggerResult result = current.invokeElement(c); - if (result.isFire()) { - // the subtriggers are OnceTriggers that need an implicit repeat around them. So, reset - // the trigger after it fires. - current.invokeClear(c); - c.trigger().setFinished(false, LATE_INDEX); - return TriggerResult.FIRE; - } else { - return TriggerResult.CONTINUE; - } + public void onElement(OnElementContext c) throws Exception { + if (!c.trigger().isMerging()) { + // If merges can never happen, we just run the unfinished subtrigger + c.trigger().firstUnfinishedSubTrigger().invokeOnElement(c); } else { - throw new IllegalStateException( - "Shouldn't receive elements after the watermark with no late trigger"); + // If merges can happen, we run for all subtriggers because they might be + // de-activated or re-activated + for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { + subTrigger.invokeOnElement(c); + } } } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - boolean pastEndOfWindow = false; - - // If the watermark was past the end of a window that is past the end of the new window, - // then the watermark must also be past the end of this window. What's more, we've already - // fired some elements for that trigger firing, so we report FINISHED (without firing). - OnMergeContext earlySubContext = c.forTrigger(c.trigger().subTrigger(EARLY_INDEX)); - for (W finishedWindow : earlySubContext.trigger().getFinishedMergingWindows()) { - if (!finishedWindow.maxTimestamp().isBefore(c.window().maxTimestamp())) { - pastEndOfWindow = true; - break; - } - } - - c.trigger().setFinished(pastEndOfWindow, EARLY_INDEX); + public void onMerge(OnMergeContext c) throws Exception { + ExecutableTrigger earlySubtrigger = c.trigger().subTrigger(EARLY_INDEX); + // We check the early trigger to determine if we are still processing it or + // if the end of window has transitioned us to the late trigger + OnMergeContext earlyContext = c.forTrigger(earlySubtrigger); - if (pastEndOfWindow) { - // If we've already fired the AtWatermark for a watermark that is >= the end of this window, - // then we should merge the late trigger (if any) + // If the early trigger is still active in any merging window then it is still active in + // the new merged window, because even if the merged window is "done" some pending elements + // haven't had a chance to fire. + if (!earlyContext.trigger().finishedInAllMergingWindows() || !endOfWindowReached(c)) { + earlyContext.trigger().setFinished(false); if (lateTrigger != null) { - ExecutableTrigger lateTrigger = c.trigger().subTrigger(LATE_INDEX); - MergeResult result = lateTrigger.invokeMerge(c); - // clear merge state if it got marked finished - if (result.isFire()) { - c.trigger().setFinished(false, 1); - lateTrigger.invokeClear(c); - return MergeResult.FIRE; - } else { - return MergeResult.CONTINUE; - } - } else { - throw new IllegalStateException( - "Shouldn't merge with windows that have already finished"); - } - } else { - // We haven't reached the watermark yet, so merge the early trigger. - ExecutableTrigger earlyTrigger = c.trigger().subTrigger(EARLY_INDEX); - MergeResult result = earlyTrigger.invokeMerge(c); - - // clear merge state if it got marked finished - if (result.isFire()) { - c.trigger().setFinished(false, EARLY_INDEX); - earlyTrigger.invokeClear(c); - return MergeResult.FIRE; - } else { - return MergeResult.CONTINUE; - } - } - } - - @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - boolean isOnTime = c.timeDomain() == TimeDomain.EVENT_TIME - && c.timestamp().isEqual(c.window().maxTimestamp()); - - if (!isOnTime) { - // If this timer isn't the ON_TIME firing, send it to the current subtree. - ExecutableTrigger current = c.trigger().firstUnfinishedSubTrigger(); - if (current == null) { - return TriggerResult.CONTINUE; - } - TriggerResult result = current.invokeTimer(c); - if (result.isFire()) { - // the subtriggers are OnceTriggers that need an implicit repeat around them. So, reset - // the trigger after it fires. - c.trigger().setFinished(false, LATE_INDEX); - current.invokeClear(c); - return TriggerResult.FIRE; - } else { - return TriggerResult.CONTINUE; + ExecutableTrigger lateSubtrigger = c.trigger().subTrigger(LATE_INDEX); + OnMergeContext lateContext = c.forTrigger(lateSubtrigger); + lateContext.trigger().setFinished(false); + lateSubtrigger.invokeClear(lateContext); } } else { - // Mark the early trigger finished. - c.trigger().setFinished(true, EARLY_INDEX); - + // Otherwise the early trigger and end-of-window bit is done for good. + earlyContext.trigger().setFinished(true); if (lateTrigger != null) { - // In case we ran the late trigger in parallel, clear out its state. - - if (c.trigger().isMerging()) { - // If we were pre-running the late trigger, clear out any state since we're firing. - c.trigger().setFinished(false, LATE_INDEX); - c.trigger().subTrigger(LATE_INDEX).invokeClear(c); - } - - return TriggerResult.FIRE; - } else { - return TriggerResult.FIRE_AND_FINISH; + c.trigger().subTrigger(LATE_INDEX).invokeOnMerge(c); } } } @@ -464,6 +222,79 @@ public Instant getWatermarkThatGuaranteesFiring(W window) { // Even without an early or late trigger, we'll still produce a firing at the watermark. return window.maxTimestamp(); } + + private boolean endOfWindowReached(Trigger.TriggerContext context) { + return context.currentEventTime() != null + && context.currentEventTime().isAfter(context.window().maxTimestamp()); + } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + if (!context.trigger().isFinished(EARLY_INDEX)) { + // We have not yet transitioned to late firings. + // We should fire if either the trigger is ready or we reach the end of the window. + return context.trigger().subTrigger(EARLY_INDEX).invokeShouldFire(context) + || endOfWindowReached(context); + } else if (lateTrigger == null) { + return false; + } else { + // We are running the late trigger + return context.trigger().subTrigger(LATE_INDEX).invokeShouldFire(context); + } + } + + @Override + public void onFire(Trigger.TriggerContext context) throws Exception { + if (!context.forTrigger(context.trigger().subTrigger(EARLY_INDEX)).trigger().isFinished()) { + onNonLateFiring(context); + } else if (lateTrigger != null) { + onLateFiring(context); + } else { + // all done + context.trigger().setFinished(true); + } + } + + private void onNonLateFiring(Trigger.TriggerContext context) throws Exception { + // We have not yet transitioned to late firings. + ExecutableTrigger earlySubtrigger = context.trigger().subTrigger(EARLY_INDEX); + Trigger.TriggerContext earlyContext = context.forTrigger(earlySubtrigger); + + if (!endOfWindowReached(context)) { + // This is an early firing, since we have not arrived at the end of the window + // Implicitly repeats + earlySubtrigger.invokeOnFire(context); + earlySubtrigger.invokeClear(context); + earlyContext.trigger().setFinished(false); + } else { + // We have arrived at the end of the window; terminate the early trigger + // and clear out the late trigger's state + if (earlySubtrigger.invokeShouldFire(context)) { + earlySubtrigger.invokeOnFire(context); + } + earlyContext.trigger().setFinished(true); + earlySubtrigger.invokeClear(context); + + if (lateTrigger == null) { + // Done if there is no late trigger. + context.trigger().setFinished(true); + } else { + // If there is a late trigger, we transition to it, and need to clear its state + // because it was run in parallel. + context.trigger().subTrigger(LATE_INDEX).invokeClear(context); + } + } + + } + + private void onLateFiring(Trigger.TriggerContext context) throws Exception { + // We are firing the late trigger, with implicit repeat + ExecutableTrigger lateSubtrigger = context.trigger().subTrigger(LATE_INDEX); + lateSubtrigger.invokeOnFire(context); + // It is a OnceTrigger, so it must have finished; unfinished it and clear it + lateSubtrigger.invokeClear(context); + context.forTrigger(lateSubtrigger).trigger().setFinished(false); + } } /** @@ -496,42 +327,26 @@ public AfterWatermarkLate withLateFirings(OnceTrigger lateFirings) { } @Override - public TriggerResult onElement(OnElementContext c) throws Exception { + public void onElement(OnElementContext c) throws Exception { c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - return TriggerResult.CONTINUE; } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - // If the watermark was past the end of a window that is past the end of the new window, - // then the watermark must also be past the end of this window. What's more, we've already - // fired some elements for that trigger firing, so we report FINISHED (without firing). - for (W finishedWindow : c.trigger().getFinishedMergingWindows()) { - if (!finishedWindow.maxTimestamp().isBefore(c.window().maxTimestamp())) { - return MergeResult.ALREADY_FINISHED; - } - } - - // Otherwise, set a timer for this window, and return. - c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - return MergeResult.CONTINUE; - } - - @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - if (c.timeDomain() != TimeDomain.EVENT_TIME - || c.timestamp().isBefore(c.window().maxTimestamp())) { - return TriggerResult.CONTINUE; + public void onMerge(OnMergeContext c) throws Exception { + if (!c.trigger().finishedInAllMergingWindows()) { + // If the trigger is still active in any merging window then it is still active in the new + // merged window, because even if the merged window is "done" some pending elements haven't + // had a chance to fire + c.trigger().setFinished(false); + } else if (!endOfWindowReached(c)) { + // If the end of the new window has not been reached, then the trigger is active again. + c.trigger().setFinished(false); } else { - return TriggerResult.FIRE_AND_FINISH; + // Otherwise it is done for good + c.trigger().setFinished(true); } } - @Override - public void clear(TriggerContext c) throws Exception { - c.deleteTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - } - @Override public Instant getWatermarkThatGuaranteesFiring(W window) { return window.maxTimestamp(); @@ -556,5 +371,18 @@ public boolean equals(Object obj) { public int hashCode() { return Objects.hash(getClass()); } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return endOfWindowReached(context); + } + + private boolean endOfWindowReached(Trigger.TriggerContext context) { + return context.currentEventTime() != null + && context.currentEventTime().isAfter(context.window().maxTimestamp()); + } + + @Override + protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java index ddcbe1ce71..9ac4abd894 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java @@ -44,26 +44,25 @@ public static DefaultTrigger of() { } @Override - public TriggerResult onElement(OnElementContext c) throws Exception { - c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - return TriggerResult.CONTINUE; + public void onElement(OnElementContext c) throws Exception { + // If the end of the window has already been reached, then we are already ready to fire + // and do not need to set a wake-up timer. + if (!endOfWindowReached(c)) { + c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); + } } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - return MergeResult.CONTINUE; + public void onMerge(OnMergeContext c) throws Exception { + // If the end of the window has already been reached, then we are already ready to fire + // and do not need to set a wake-up timer. + if (!endOfWindowReached(c)) { + c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); + } } @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - return TriggerResult.FIRE; - } - - @Override - public void clear(TriggerContext c) throws Exception { - c.deleteTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - } + public void clear(TriggerContext c) throws Exception { } @Override public Instant getWatermarkThatGuaranteesFiring(W window) { @@ -80,4 +79,17 @@ public boolean isCompatible(Trigger other) { public Trigger getContinuationTrigger(List> continuationTriggers) { return this; } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return endOfWindowReached(context); + } + + private boolean endOfWindowReached(Trigger.TriggerContext context) { + return context.currentEventTime() != null + && context.currentEventTime().isAfter(context.window().maxTimestamp()); + } + + @Override + public void onFire(Trigger.TriggerContext context) throws Exception { } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java index a2717d2189..652092ad6e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java @@ -15,6 +15,7 @@ */ package com.google.cloud.dataflow.sdk.transforms.windowing; +import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; import com.google.common.annotations.VisibleForTesting; import org.joda.time.Instant; @@ -35,36 +36,17 @@ class OrFinallyTrigger extends Trigger { } @Override - public Trigger.TriggerResult onElement(OnElementContext c) throws Exception { - Trigger.TriggerResult untilResult = c.trigger().subTrigger(UNTIL).invokeElement(c); - if (untilResult != TriggerResult.CONTINUE) { - return TriggerResult.FIRE_AND_FINISH; - } - - return c.trigger().subTrigger(ACTUAL).invokeElement(c); - } - - @Override - public Trigger.MergeResult onMerge(OnMergeContext c) throws Exception { - Trigger.MergeResult untilResult = c.trigger().subTrigger(UNTIL).invokeMerge(c); - if (untilResult == MergeResult.ALREADY_FINISHED) { - return MergeResult.ALREADY_FINISHED; - } else if (untilResult.isFire()) { - return MergeResult.FIRE_AND_FINISH; - } else { - // was CONTINUE -- so merge the underlying trigger - return c.trigger().subTrigger(ACTUAL).invokeMerge(c); - } + public void onElement(OnElementContext c) throws Exception { + c.trigger().subTrigger(ACTUAL).invokeOnElement(c); + c.trigger().subTrigger(UNTIL).invokeOnElement(c); } @Override - public Trigger.TriggerResult onTimer(OnTimerContext c) throws Exception { - Trigger.TriggerResult untilResult = c.trigger().subTrigger(UNTIL).invokeTimer(c); - if (untilResult != TriggerResult.CONTINUE) { - return TriggerResult.FIRE_AND_FINISH; + public void onMerge(OnMergeContext c) throws Exception { + for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { + subTrigger.invokeOnMerge(c); } - - return c.trigger().subTrigger(ACTUAL).invokeTimer(c); + updateFinishedState(c); } @Override @@ -84,4 +66,35 @@ public Trigger getContinuationTrigger(List> continuationTriggers) continuationTriggers.get(ACTUAL), (Trigger.OnceTrigger) continuationTriggers.get(UNTIL))); } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return context.trigger().subTrigger(ACTUAL).invokeShouldFire(context) + || context.trigger().subTrigger(UNTIL).invokeShouldFire(context); + } + + @Override + public void onFire(Trigger.TriggerContext context) throws Exception { + ExecutableTrigger actualSubtrigger = context.trigger().subTrigger(ACTUAL); + ExecutableTrigger untilSubtrigger = context.trigger().subTrigger(UNTIL); + + if (untilSubtrigger.invokeShouldFire(context)) { + untilSubtrigger.invokeOnFire(context); + actualSubtrigger.invokeClear(context); + } else { + // If until didn't fire, then the actual must have (or it is forbidden to call + // onFire) so we are done only if actual is done. + actualSubtrigger.invokeOnFire(context); + // Do not clear the until trigger, because it tracks data cross firings. + } + updateFinishedState(context); + } + + private void updateFinishedState(TriggerContext c) throws Exception { + boolean anyStillFinished = false; + for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { + anyStillFinished |= c.forTrigger(subTrigger).trigger().isFinished(); + } + c.trigger().setFinished(anyStillFinished); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java index 79006867a3..e77e2a1203 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; +import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; + import org.joda.time.Instant; import java.util.Arrays; @@ -57,31 +59,13 @@ private Repeatedly(Trigger repeated) { @Override - public TriggerResult onElement(OnElementContext c) - throws Exception { - TriggerResult result = c.trigger().subTrigger(REPEATED).invokeElement(c); - if (result.isFinish()) { - c.forTrigger(c.trigger().subTrigger(REPEATED)).trigger().resetTree(); - } - return result.isFire() ? TriggerResult.FIRE : TriggerResult.CONTINUE; + public void onElement(OnElementContext c) throws Exception { + getRepeated(c).invokeOnElement(c); } @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - MergeResult mergeResult = c.trigger().subTrigger(REPEATED).invokeMerge(c); - if (mergeResult.isFinish()) { - c.forTrigger(c.trigger().subTrigger(REPEATED)).trigger().resetTree(); - } - return mergeResult.isFire() ? MergeResult.FIRE : MergeResult.CONTINUE; - } - - @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - TriggerResult result = c.trigger().subTrigger(REPEATED).invokeTimer(c); - if (result.isFinish()) { - c.forTrigger(c.trigger().subTrigger(REPEATED)).trigger().resetTree(); - } - return result.isFire() ? TriggerResult.FIRE : TriggerResult.CONTINUE; + public void onMerge(OnMergeContext c) throws Exception { + getRepeated(c).invokeOnMerge(c); } @Override @@ -94,4 +78,23 @@ public Instant getWatermarkThatGuaranteesFiring(W window) { public Trigger getContinuationTrigger(List> continuationTriggers) { return new Repeatedly(continuationTriggers.get(REPEATED)); } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return getRepeated(context).invokeShouldFire(context); + } + + @Override + public void onFire(TriggerContext context) throws Exception { + getRepeated(context).invokeOnFire(context); + + if (context.trigger().isFinished(REPEATED)) { + context.trigger().setFinished(false, REPEATED); + getRepeated(context).invokeClear(context); + } + } + + private ExecutableTrigger getRepeated(TriggerContext context) { + return context.trigger().subTrigger(REPEATED); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java index 8b5038a81c..1cb88ebd0e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java @@ -95,71 +95,6 @@ @Experimental(Experimental.Kind.TRIGGER) public abstract class Trigger implements Serializable, TriggerBuilder { - /** - * {@code TriggerResult} enumerates the possible result a trigger can have when it is executed. - */ - public enum TriggerResult { - FIRE(true, false), - CONTINUE(false, false), - FIRE_AND_FINISH(true, true); - - private boolean finish; - private boolean fire; - - private TriggerResult(boolean fire, boolean finish) { - this.fire = fire; - this.finish = finish; - } - - public boolean isFire() { - return fire; - } - - public boolean isFinish() { - return finish; - } - } - - /** - * {@code TriggerResult} enumerates the possible result a trigger can have when it is merged. - */ - public enum MergeResult { - FIRE(true, false, TriggerResult.FIRE), - CONTINUE(false, false, TriggerResult.CONTINUE), - FIRE_AND_FINISH(true, true, TriggerResult.FIRE_AND_FINISH), - - /** - * A trigger can only return {@code ALREADY_FINISHED} from {@code onMerge}, and it should only - * be returned if the trigger was previously finished in at least one window. - * - *

Returning this indicates that the sub-trigger should be treated as finished in the output - * window. - */ - ALREADY_FINISHED(false, true, null); - - private boolean finish; - private boolean fire; - private TriggerResult triggerResult; - - private MergeResult(boolean fire, boolean finish, TriggerResult triggerResult) { - this.fire = fire; - this.finish = finish; - this.triggerResult = triggerResult; - } - - public boolean isFire() { - return fire; - } - - public boolean isFinish() { - return finish; - } - - public TriggerResult getTriggerResult() { - return triggerResult; - } - } - /** * Interface for accessing information about the trigger being executed and other triggers in the * same tree. @@ -235,12 +170,18 @@ public interface MergingTriggerInfo extends TriggerInfo /** Return true if the trigger is finished in any window being merged. */ public abstract boolean finishedInAnyMergingWindow(); + /** Return true if the trigger is finished in all windows being merged. */ + public abstract boolean finishedInAllMergingWindows(); + /** Return the merging windows in which the trigger is finished. */ public abstract Iterable getFinishedMergingWindows(); } /** - * Information accessible to all of the callbacks that are executed on a {@link Trigger}. + * Information accessible to all operational hooks in this {@code Trigger}. + * + *

Used directly in {@link Trigger#shouldFire} and {@link Trigger#clear}, and + * extended with additional information in other methods. */ public abstract class TriggerContext { @@ -275,7 +216,8 @@ public abstract class TriggerContext { } /** - * Details about an invocation of {@link Trigger#onElement}. + * Extended {@link Context} containing information accessible to the {@link #onElement} + * operational hook. */ public abstract class OnElementContext extends TriggerContext { /** The event timestamp of the element currently being processed. */ @@ -301,7 +243,8 @@ public abstract class OnElementContext extends TriggerContext { } /** - * Details about an invocation of {@link Trigger#onMerge}. + * Extended {@link Context} containing information accessible to the {@link #onMerge} + * operational hook. */ public abstract class OnMergeContext extends TriggerContext { /** The old windows that were merged. */ @@ -332,24 +275,6 @@ public abstract class OnMergeContext extends TriggerContext { public abstract MergingTriggerInfo trigger(); } - /** - * Details about an invocation of {@link Trigger#onTimer}. - */ - public abstract class OnTimerContext extends TriggerContext { - - /** Returns the time that the timer was set for. */ - public abstract Instant timestamp(); - - /** Returns the time domain that thet timer was set for. */ - public abstract TimeDomain timeDomain(); - - /** - * Create an {@code OnTimerContext} for executing the given trigger. - */ - @Override - public abstract OnTimerContext forTrigger(ExecutableTrigger trigger); - } - @Nullable protected final List> subTriggers; @@ -361,28 +286,38 @@ protected Trigger(@Nullable List> subTriggers) { /** * Called immediately after an element is first incorporated into a window. */ - public abstract TriggerResult onElement(OnElementContext c) throws Exception; + public abstract void onElement(OnElementContext c) throws Exception; /** * Called immediately after windows have been merged. * - *

Leaf triggers should determine their result by inspecting their status and any state - * in the merging windows. Composite triggers should determine their result by calling + *

Leaf triggers should update their state by inspecting their status and any state + * in the merging windows. Composite triggers should update their state by calling * {@link ExecutableTrigger#invokeMerge} on their sub-triggers, and applying appropriate logic. * - *

A trigger can only return {@link MergeResult#ALREADY_FINISHED} if it is marked as finished - * in at least one of the windows being merged. + *

A trigger such as {@link AfterWatermark#pastEndOfWindow} may no longer be finished; + * it is the responsibility of the trigger itself to record this fact. It is forbidden for + * a trigger to become finished due to {@link onMerge}, as it has not yet fired the pending + * elements that led to it being ready to fire. * *

The implementation does not need to clear out any state associated with the old windows. */ - public abstract MergeResult onMerge(OnMergeContext c) throws Exception; + public abstract void onMerge(OnMergeContext c) throws Exception; /** - * Called when a timer has fired for the current window. Composite triggers should pass the event - * to all sub-triggers. Triggers that set timers should verify the timer matches what they set - * before processing the firing. + * Returns {@code true} if the current state of the trigger indicates that its condition + * is satisfied and it is ready to fire. */ - public abstract TriggerResult onTimer(OnTimerContext c) throws Exception; + public abstract boolean shouldFire(TriggerContext context) throws Exception; + + /** + * Adjusts the state of the trigger to be ready for the next pane. For example, a + * {@link Repeatedly} trigger will reset its inner trigger, since it has fired. + * + *

If the trigger is finished, it is the responsibility of the trigger itself to + * record that fact via the {@code context}. + */ + public abstract void onFire(TriggerContext context) throws Exception; /** * Called to allow the trigger to prefetch any state it will likely need to read from during @@ -414,14 +349,28 @@ public void prefetchOnMerge(ReduceFn.MergingStateContext state) { /** * Called to allow the trigger to prefetch any state it will likely need to read from during - * an {@link #onTimer} call. + * an {@link #shouldFire} call. + * + * @param state {@link ReduceFn.StateContext} to prefetch from. + */ + public void prefetchShouldFire(ReduceFn.StateContext state) { + if (subTriggers != null) { + for (Trigger trigger : subTriggers) { + trigger.prefetchShouldFire(state); + } + } + } + + /** + * Called to allow the trigger to prefetch any state it will likely need to read from during + * an {@link #onFire} call. * - * @param state {@lijnk ReduceFn.StateContext} to prefetch from. + * @param state {@link ReduceFn.StateContext} to prefetch from. */ - public void prefetchOnTimer(ReduceFn.StateContext state) { + public void prefetchOnFire(ReduceFn.StateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { - trigger.prefetchOnTimer(state); + trigger.prefetchOnFire(state); } } } @@ -588,5 +537,20 @@ public final OnceTrigger getContinuationTrigger() { } return (OnceTrigger) continuation; } + + /** + * {@inheritDoc} + */ + @Override + public final void onFire(TriggerContext context) throws Exception { + onOnlyFiring(context); + context.trigger().setFinished(true); + } + + /** + * Called exactly once by {@link #onFire} when the trigger is fired. By default, + * invokes {@link #onFire} on all subtriggers for which {@link #shouldFire} is {@code true}. + */ + protected abstract void onOnlyFiring(TriggerContext context) throws Exception; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java index 326b1c3876..22a3762dfc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java @@ -18,9 +18,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; import com.google.common.base.Preconditions; import java.io.Serializable; @@ -120,47 +118,25 @@ public ExecutableTrigger getSubTriggerContaining(int index) { * Invoke the {@link Trigger#onElement} method for this trigger, ensuring that the bits are * properly updated if the trigger finishes. */ - public TriggerResult invokeElement(Trigger.OnElementContext c) throws Exception { - Trigger.OnElementContext subContext = c.forTrigger(this); - if (subContext.trigger().isFinished()) { - throw new IllegalStateException("Shouldn't invokeElement on finished triggers."); - } - - Trigger.TriggerResult result = trigger.onElement(subContext); - - if (result.isFinish()) { - subContext.trigger().setFinished(true); - } - - return result; - } - - /** - * Invoke the {@link Trigger#onTimer} method for this trigger, ensuring that the bits are properly - * updated if the trigger finishes. - */ - public TriggerResult invokeTimer(Trigger.OnTimerContext c) throws Exception { - Trigger.OnTimerContext subContext = c.forTrigger(this); - if (subContext.trigger().isFinished()) { - throw new IllegalStateException("Shouldn't invokeTimer on finished triggers."); - } - - Trigger.TriggerResult result = trigger.onTimer(subContext); - if (result.isFinish()) { - subContext.trigger().setFinished(true); - } - return result; + public void invokeOnElement(Trigger.OnElementContext c) throws Exception { + trigger.onElement(c.forTrigger(this)); } /** * Invoke the {@link Trigger#onMerge} method for this trigger, ensuring that the bits are properly * updated. */ - public MergeResult invokeMerge(Trigger.OnMergeContext c) throws Exception { + public void invokeOnMerge(Trigger.OnMergeContext c) throws Exception { Trigger.OnMergeContext subContext = c.forTrigger(this); - Trigger.MergeResult result = trigger.onMerge(subContext); - subContext.trigger().setFinished(result.isFinish()); - return result; + trigger.onMerge(subContext); + } + + public boolean invokeShouldFire(Trigger.TriggerContext c) throws Exception { + return trigger.shouldFire(c.forTrigger(this)); + } + + public void invokeOnFire(Trigger.TriggerContext c) throws Exception { + trigger.onFire(c.forTrigger(this)); } /** @@ -179,32 +155,5 @@ private static class ExecutableOnceTrigger extends Exec public ExecutableOnceTrigger(OnceTrigger trigger, int nextUnusedIndex) { super(trigger, nextUnusedIndex); } - - @Override - public TriggerResult invokeElement(Trigger.OnElementContext c) throws Exception { - TriggerResult result = super.invokeElement(c); - if (TriggerResult.FIRE.equals(result)) { - throw new IllegalStateException("TriggerResult.FIRE returned from once trigger"); - } - return result; - } - - @Override - public TriggerResult invokeTimer(Trigger.OnTimerContext c) throws Exception { - TriggerResult result = super.invokeTimer(c); - if (TriggerResult.FIRE.equals(result)) { - throw new IllegalStateException("TriggerResult.FIRE returned from once trigger"); - } - return result; - } - - @Override - public MergeResult invokeMerge(Trigger.OnMergeContext c) throws Exception { - MergeResult result = super.invokeMerge(c); - if (MergeResult.FIRE.equals(result)) { - throw new IllegalStateException("MergeResult.FIRE returned from once trigger"); - } - return result; - } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index e0d7c2e22c..baa48cc7a7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.sdk.util; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; @@ -150,7 +152,7 @@ public StateContextImpl( this.activeWindows = activeWindows; this.windowCoder = windowCoder; this.stateInternals = stateInternals; - this.window = window; + this.window = checkNotNull(window); this.windowNamespace = namespaceFor(window); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index d1276800f5..a5cd11b442 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.ActiveWindowSet.MergeCallback; @@ -35,7 +34,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.joda.time.Duration; @@ -44,8 +42,8 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Set; /** @@ -239,26 +237,23 @@ boolean isFinished(W window) { * holds, and invoking {@link ReduceFn#onTrigger}. * */ - public void processElements(Iterable> values) { - // Map from element window to the result of running its trigger. - final Map results = Maps.newHashMap(); - - if (!windowingStrategy.getWindowFn().isNonMerging()) { - // If an incoming element introduces a new window, attempt to merge it into an existing - // window eagerly. Otherwise track which state address windows are used to store the state - // for each merged, active window. - collectAndMergeWindows(values, results); - } + public void processElements(Iterable> values) throws Exception { + // If an incoming element introduces a new window, attempt to merge it into an existing + // window eagerly. The outcome is stored in the ActiveWindowSet. + collectAndMergeWindows(values); + + Set windowsToConsider = new HashSet<>(); // Process each element, using the updated activeWindows determined by collectAndMergeWindows. for (WindowedValue value : values) { - processElement(results, value); + windowsToConsider.addAll(processElement(value)); } - // Trigger output from any window that was triggered by merging or processing elements. - for (Map.Entry result : results.entrySet()) { - handleTriggerResult( - contextFactory.base(result.getKey()), false/*isEndOfWindow*/, result.getValue()); + // Trigger output from any window for which the trigger is ready + for (W mergedWindow : windowsToConsider) { + ReduceFn.Context context = contextFactory.base(mergedWindow); + triggerRunner.prefetchShouldFire(context.state()); + emitIfAppropriate(context, false /* isEndOfWindow */); } // We're all done with merging and emitting elements so can compress the activeWindow state. @@ -278,13 +273,13 @@ private boolean canDropDueToExpiredWindow(W window) { /** * Extract the windows associated with the values, and invoke merge. - * - * @param results an output parameter that accumulates all of the windows that have had the - * trigger return FIRE or FIRE_AND_FINISH. Once present in this map, it is no longer - * necessary to evaluate triggers for the given window. */ - private void collectAndMergeWindows( - Iterable> values, final Map results) { + private void collectAndMergeWindows(Iterable> values) { + // No-op if no merging can take place + if (windowingStrategy.getWindowFn().isNonMerging()) { + return; + } + Set currentlyActiveWindows = Sets.newHashSet(activeWindows.getActiveWindows()); // Collect the windows from all elements (except those which are too late) and @@ -312,7 +307,7 @@ private void collectAndMergeWindows( } // Merge all of the active windows and retain a mapping from source windows to result windows. - mergeActiveWindows(results); + mergeActiveWindows(); // Make sure we've scheduled timers for any ACTIVE windows we just introduced. // (Timers for ACTIVE windows which are now MERGED will have been discarded above.) @@ -321,14 +316,7 @@ private void collectAndMergeWindows( } } - /** - * Merge the active windows. - * - * @param results an output parameter that accumulates all of the windows that have had the - * trigger return FIRE or FIRE_AND_FINISH. Once present in this map, it is no longer - * necessary to evaluate triggers for the given window. - */ - private void mergeActiveWindows(final Map results) { + private void mergeActiveWindows() { try { activeWindows.merge(new MergeCallback() { @Override @@ -352,19 +340,14 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W // Otherwise, leave all the merging window watermark holds where they are. watermarkHold.onMerge(mergeResultContext); - // Have the trigger merge state as needed, and handle the result. - TriggerResult result; + // Have the trigger merge state as needed try { - result = triggerRunner.onMerge(mergeResultContext); + triggerRunner.onMerge(mergeResultContext); } catch (Exception e) { Throwables.propagateIfPossible(e); throw new RuntimeException("Failed to merge the triggers", e); } - if (result.isFire()) { - results.put(mergeResult, result); - } - for (W active : activeToBeMerged) { if (active.equals(mergeResult)) { // Not merged away. @@ -393,16 +376,15 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W } /** - * @param results a record of all of the windows that have had the trigger return FIRE or - * FIRE_AND_FINISH. Once present in this map, it is no longer necessary to evaluate triggers - * for the given result. + * Process an element. * @param value the value being processed + * + * @return the set of windows in which the element was actually processed */ - private void processElement(Map results, WindowedValue value) { + private Collection processElement(WindowedValue value) { // Redirect element windows to the ACTIVE windows they have been merged into. // It is possible two of the element's windows have been merged into the same window. // In that case we'll process the same element for the same window twice. - @SuppressWarnings("unchecked") Collection windows = new ArrayList<>(); for (BoundedWindow untypedWindow : value.getWindows()) { @SuppressWarnings("unchecked") @@ -424,11 +406,9 @@ private void processElement(Map results, WindowedValue // Prefetch in each of the windows if we're going to need to process triggers for (W window : windows) { - if (!results.containsKey(window)) { - ReduceFn.ProcessValueContext context = - contextFactory.forValue(window, value.getValue(), value.getTimestamp()); - triggerRunner.prefetchForValue(context.state()); - } + ReduceFn.ProcessValueContext context = + contextFactory.forValue(window, value.getValue(), value.getTimestamp()); + triggerRunner.prefetchForValue(context.state()); } // Process the element for each (representative) window it belongs to. @@ -437,13 +417,13 @@ private void processElement(Map results, WindowedValue contextFactory.forValue(window, value.getValue(), value.getTimestamp()); // Check to see if the triggerRunner thinks the window is closed. If so, drop that window. - if (!results.containsKey(window) && triggerRunner.isClosed(context.state())) { + if (triggerRunner.isClosed(context.state())) { droppedDueToClosedWindow.addValue(1L); WindowTracing.debug( "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", - value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); + + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", + value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); continue; } @@ -468,19 +448,16 @@ private void processElement(Map results, WindowedValue throw wrapMaybeUserException(e); } - // Run the trigger and handle the result as appropriate - if (!results.containsKey(window)) { - try { - TriggerResult result = triggerRunner.processValue(context); - if (result.isFire()) { - results.put(window, result); - } - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Failed to run trigger", e); - } + // Run the trigger to update its state + try { + triggerRunner.processValue(context); + } catch (Exception e) { + Throwables.propagateIfPossible(e); + throw new RuntimeException("Failed to run trigger", e); } } + + return windows; } /** @@ -523,12 +500,11 @@ public void onTimer(TimerData timer) { if (activeWindows.isActive(window) && !triggerRunner.isClosed(context.state())) { // We need to call onTrigger to emit the final pane if required. - // The final pane *may* be ON_TIME if: - // - AllowedLateness = 0 (ie the timer is at end-of-window), and; - // - The trigger fires on the end-of-window timer. - boolean isWatermarkTrigger = - isEndOfWindowTimer && runTriggersForTimer(context, timer).isFire(); - onTrigger(context, isWatermarkTrigger, true/*isFinish*/, false/*willStillBeActive*/); + // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, + // and the watermark has passed the end of the window. + boolean isWatermarkTrigger = isEndOfWindowTimer; + onTrigger(context, isWatermarkTrigger, + true /* isFinished */, false /* willStillBeActive */); } // Clear all the state for this window since we'll never see elements for it again. @@ -546,8 +522,12 @@ public void onTimer(TimerData timer) { key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); if (activeWindows.isActive(window) && !triggerRunner.isClosed(context.state())) { - TriggerResult result = runTriggersForTimer(context, timer); - handleTriggerResult(context, isEndOfWindowTimer, result); + try { + emitIfAppropriate(context, isEndOfWindowTimer); + } catch (Exception e) { + Throwables.propagateIfPossible(e); + throw Throwables.propagate(e); + } } if (isEndOfWindowTimer) { @@ -569,18 +549,6 @@ public void onTimer(TimerData timer) { } } - private TriggerResult runTriggersForTimer( - ReduceFn.Context context, TimerData timer) { - triggerRunner.prefetchForTimer(context.state()); - - try { - return triggerRunner.onTimer(context, timer); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Exception in onTimer for trigger", e); - } - } - /** * Clear all the state associated with {@code context}'s window. * Should only be invoked if we know all future elements for this window will be considered @@ -609,8 +577,8 @@ private void clearAllState(ReduceFn.Context context) thro } /** Should the reduce function state be cleared? */ - private boolean shouldDiscardAfterFiring(TriggerResult result) { - if (result.isFinish()) { + private boolean shouldDiscardAfterFiring(boolean isFinished) { + if (isFinished) { // This is the last firing for trigger. return true; } @@ -622,25 +590,26 @@ private boolean shouldDiscardAfterFiring(TriggerResult result) { } /** - * Possibly emit a pane if a trigger fired or timers require it, and cleanup state. + * Possibly emit a pane if a trigger is ready to fire or timers require it, and cleanup state. */ - private void handleTriggerResult(ReduceFn.Context context, - boolean isEndOfWindow, TriggerResult result) { - if (!result.isFire()) { - // Ignore unless trigger fired. + private void emitIfAppropriate(ReduceFn.Context context, + boolean isEndOfWindow) throws Exception { + if (!triggerRunner.shouldFire(context)) { + // Ignore unless trigger is ready to fire return; } - // If the trigger fired due to an end-of-window timer, treat it as an AfterWatermark trigger. - boolean isWatermarkTrigger = isEndOfWindow; + // Inform the trigger of the transition to see if it is finished + triggerRunner.onFire(context); + boolean isFinished = triggerRunner.isClosed(context.state()); // Will be able to clear all element state after triggering? - boolean shouldDiscard = shouldDiscardAfterFiring(result); + boolean shouldDiscard = shouldDiscardAfterFiring(isFinished); // Run onTrigger to produce the actual pane contents. // As a side effect it will clear all element holds, but not necessarily any // end-of-window or garbage collection holds. - onTrigger(context, isWatermarkTrigger, result.isFinish(), !shouldDiscard); + onTrigger(context, isEndOfWindow, isFinished, !shouldDiscard); // Now that we've triggered, the pane is empty. nonEmptyPanes.clearPane(context); @@ -660,16 +629,16 @@ private void handleTriggerResult(ReduceFn.Context context WindowTracing.debug("ReduceFnRunner.handleTriggerResult: removing {}", context.window()); activeWindows.remove(context.window()); - if (!result.isFinish()) { + if (!triggerRunner.isClosed(context.state())) { // We still need to consider this window active since we may have had to add an // end-of-window or garbage collection hold above. activeWindows.addActive(context.window()); } } - if (result.isFinish()) { - // If we're finishing, eagerly clear state to reduce pressure on the backend. - // Leave behind a tombstone in the trigger runner so we know the trigger is finished. + if (triggerRunner.isClosed(context.state())) { + // If we're finishing, clear up the trigger tree as well. + // However, we'll leave behind a tombstone so we know the trigger is finished. try { triggerRunner.clearState(context); paneInfoTracker.clear(context.state()); @@ -686,7 +655,7 @@ private void handleTriggerResult(ReduceFn.Context context * Do we need to emit a pane? */ private boolean needToEmit( - boolean isEmpty, boolean isWatermarkTrigger, boolean isFinish, PaneInfo.Timing timing) { + boolean isEmpty, boolean isWatermarkTrigger, boolean isFinished, PaneInfo.Timing timing) { if (!isEmpty) { // The pane has elements. return true; @@ -695,7 +664,8 @@ private boolean needToEmit( // This is the unique ON_TIME pane, triggered by an AfterWatermark. return true; } - if (isFinish && windowingStrategy.getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS) { + if (isFinished + && windowingStrategy.getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS) { // This is known to be the final pane, and the user has requested it even when empty. return true; } @@ -710,15 +680,16 @@ private boolean needToEmit( * @param isFinish true if this will be the last triggering processed */ private void onTrigger(final ReduceFn.Context context, - boolean isWatermarkTrigger, boolean isFinish, boolean willStillBeActive) { + boolean isWatermarkTrigger, boolean isFinished, boolean willStillBeActive) { // Collect state. - StateContents outputTimestampFuture = - watermarkHold.extractAndRelease(context, isFinish, willStillBeActive); - StateContents paneFuture = - paneInfoTracker.getNextPaneInfo(context, isWatermarkTrigger, isFinish); + StateContents outputTimestampFuture = watermarkHold.extractAndRelease( + context, isFinished, willStillBeActive); + StateContents paneFuture = paneInfoTracker.getNextPaneInfo( + context, isWatermarkTrigger, isFinished); StateContents isEmptyFuture = nonEmptyPanes.isEmpty(context); reduceFn.prefetchOnTrigger(context.state()); + triggerRunner.prefetchOnFire(context.state()); // Calculate the pane info. final PaneInfo pane = paneFuture.read(); @@ -726,7 +697,7 @@ private void onTrigger(final ReduceFn.Context context, final Instant outputTimestamp = outputTimestampFuture.read(); // Only emit a pane if it has data or empty panes are observable. - if (needToEmit(isEmptyFuture.read(), isWatermarkTrigger, isFinish, pane.getTiming())) { + if (needToEmit(isEmptyFuture.read(), isWatermarkTrigger, isFinished, pane.getTiming())) { // Run reduceFn.onTrigger method. final List windows = Collections.singletonList(context.window()); ReduceFn.OnTriggerContext triggerContext = contextFactory.forTrigger( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java index f27ff380e0..248f00589d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java @@ -35,20 +35,10 @@ public class ReshuffleTrigger extends Trigger { } @Override - public TriggerResult onElement(Trigger.OnElementContext c) { - return TriggerResult.FIRE; - } + public void onElement(Trigger.OnElementContext c) { } @Override - public MergeResult onMerge(Trigger.OnMergeContext c) { - // We fire on every element, so merging will never produce a pane containing new elements. - return MergeResult.CONTINUE; - } - - @Override - public TriggerResult onTimer(Trigger.OnTimerContext c) { - return TriggerResult.CONTINUE; - } + public void onMerge(Trigger.OnMergeContext c) { } @Override protected Trigger getContinuationTrigger(List> continuationTriggers) { @@ -60,4 +50,12 @@ public Instant getWatermarkThatGuaranteesFiring(W window) { throw new UnsupportedOperationException( "ReshuffleTrigger should not be used outside of Reshuffle"); } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return true; + } + + @Override + public void onFire(Trigger.TriggerContext context) throws Exception { } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 86e17eb1cc..83ea415d4d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -67,14 +67,6 @@ public Trigger.OnElementContext createOnElementContext( elementTimestamp); } - public Trigger.OnTimerContext createOnTimerContext( - W window, ReduceFn.Timers timers, - ExecutableTrigger rootTrigger, FinishedTriggers finishedSet, - Instant timestamp, TimeDomain domain) { - return new OnTimerContextImpl( - window, timers, rootTrigger, finishedSet, timestamp, domain); - } - public Trigger.OnMergeContext createOnMergeContext( W window, ReduceFn.Timers timers, Collection mergingWindows, ExecutableTrigger rootTrigger, FinishedTriggers finishedSet, @@ -233,6 +225,16 @@ public boolean finishedInAnyMergingWindow() { return false; } + @Override + public boolean finishedInAllMergingWindows() { + for (FinishedTriggers finishedSet : finishedSets.values()) { + if (!finishedSet.isFinished(trigger)) { + return false; + } + } + return true; + } + @Override public Iterable getFinishedMergingWindows() { return Maps.filterValues(finishedSets, new Predicate() { @@ -409,83 +411,6 @@ public Instant currentEventTime() { } } - private class OnTimerContextImpl extends Trigger.OnTimerContext { - - private final ReduceFnContextFactory.StateContextImpl state; - private final ReduceFn.Timers timers; - private final TriggerInfoImpl triggerInfo; - private final Instant timestamp; - private final TimeDomain domain; - - private OnTimerContextImpl( - W window, - ReduceFn.Timers timers, - ExecutableTrigger trigger, - FinishedTriggers finishedSet, - Instant timestamp, - TimeDomain domain) { - trigger.getSpec().super(); - this.state = triggerState(window, trigger); - this.timers = new TriggerTimers(window, timers); - this.triggerInfo = new TriggerInfoImpl(trigger, finishedSet, this); - this.timestamp = timestamp; - this.domain = domain; - } - - @Override - public Trigger.OnTimerContext forTrigger(ExecutableTrigger trigger) { - return new OnTimerContextImpl( - state.window(), timers, trigger, triggerInfo.finishedSet, timestamp, domain); - } - - @Override - public TriggerInfo trigger() { - return triggerInfo; - } - - @Override - public ReduceFn.StateContext state() { - return state; - } - - @Override - public W window() { - return state.window(); - } - - @Override - public Instant timestamp() { - return timestamp; - } - - @Override - public TimeDomain timeDomain() { - return domain; - } - - @Override - public void deleteTimer(Instant timestamp, TimeDomain domain) { - timers.deleteTimer(timestamp, domain); - } - - @Override - public Instant currentProcessingTime() { - return timers.currentProcessingTime(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return timers.currentSynchronizedProcessingTime(); - } - - @Override - @Nullable - public Instant currentEventTime() { - return timers.currentEventTime(); - } - } - private class OnMergeContextImpl extends Trigger.OnMergeContext { private final ReduceFnContextFactory.MergingStateContextImpl state; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index 1fd077f0a4..c846dac860 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -18,9 +18,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.cloud.dataflow.sdk.util.state.ValueState; @@ -84,18 +81,31 @@ public void prefetchForValue(ReduceFn.StateContext state) { rootTrigger.getSpec().prefetchOnElement(state); } + public void prefetchOnFire(ReduceFn.StateContext state) { + if (isFinishedSetNeeded()) { + state.access(FINISHED_BITS_TAG).get(); + } + rootTrigger.getSpec().prefetchOnFire(state); + } + + public void prefetchShouldFire(ReduceFn.StateContext state) { + if (isFinishedSetNeeded()) { + state.access(FINISHED_BITS_TAG).get(); + } + rootTrigger.getSpec().prefetchShouldFire(state); + } + /** * Run the trigger logic to deal with a new value. */ - public TriggerResult processValue(ReduceFn.ProcessValueContext c) throws Exception { + public void processValue(ReduceFn.ProcessValueContext c) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. FinishedTriggersBitSet finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); Trigger.OnElementContext triggerContext = contextFactory.createOnElementContext( c.window(), c.timers(), c.timestamp(), rootTrigger, finishedSet); - TriggerResult result = rootTrigger.invokeElement(triggerContext); + rootTrigger.invokeOnElement(triggerContext); persistFinishedSet(c.state(), finishedSet); - return result; } public void prefetchForMerge(ReduceFn.MergingStateContext state) { @@ -111,7 +121,7 @@ public void prefetchForMerge(ReduceFn.MergingStateContext state) { /** * Run the trigger merging logic as part of executing the specified merge. */ - public TriggerResult onMerge(ReduceFn.OnMergeContext c) throws Exception { + public void onMerge(ReduceFn.OnMergeContext c) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. FinishedTriggersBitSet finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); @@ -130,35 +140,25 @@ public TriggerResult onMerge(ReduceFn.OnMergeContext c) throws Excep finishedSet, mergingFinishedSets.build()); // Run the merge from the trigger - MergeResult result = rootTrigger.invokeMerge(mergeContext); - if (MergeResult.ALREADY_FINISHED.equals(result)) { - throw new IllegalStateException("Root trigger returned MergeResult.ALREADY_FINISHED."); - } + rootTrigger.invokeOnMerge(mergeContext); persistFinishedSet(c.state(), finishedSet); - return result.getTriggerResult(); } - public void prefetchForTimer(ReduceFn.StateContext state) { - if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).get(); - } - rootTrigger.getSpec().prefetchOnElement(state); + public boolean shouldFire(ReduceFn.Context c) throws Exception { + FinishedTriggers finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); + Trigger.TriggerContext context = contextFactory.base(c.window(), c.timers(), + rootTrigger, finishedSet); + return rootTrigger.invokeShouldFire(context); } - /** - * Run the trigger logic appropriate for receiving a timer with the specified destination ID. - */ - public TriggerResult onTimer(ReduceFn.Context c, TimerData timer) throws Exception { - // Clone so that we can detect changes and so that changes here don't pollute merging. + public void onFire(ReduceFn.Context c) throws Exception { FinishedTriggersBitSet finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); - Trigger.OnTimerContext triggerContext = contextFactory.createOnTimerContext( - c.window(), c.timers(), rootTrigger, finishedSet, - timer.getTimestamp(), timer.getDomain()); - TriggerResult result = rootTrigger.invokeTimer(triggerContext); + Trigger.TriggerContext context = contextFactory.base(c.window(), c.timers(), + rootTrigger, finishedSet); + rootTrigger.invokeOnFire(context); persistFinishedSet(c.state(), finishedSet); - return result; } private void persistFinishedSet( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 9a28d040c4..64341b9180 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -30,6 +30,8 @@ import java.util.List; import java.util.Objects; +import javax.annotation.Nullable; + /** * In-memory implementation of {@link StateInternals}. Used in {@code BatchModeExecutionContext} * and for running tests that need state. @@ -127,6 +129,8 @@ private final class WatermarkStateInternalImplementation implements WatermarkStateInternal, InMemoryState { private final OutputTimeFn outputTimeFn; + + @Nullable private Instant combinedHold = null; public WatermarkStateInternalImplementation(OutputTimeFn outputTimeFn) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java index dde39c21b4..06f0c3f759 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java @@ -16,18 +16,11 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.everyItem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -36,222 +29,115 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; /** * Tests for {@link AfterAll}. */ @RunWith(JUnit4.class) public class AfterAllTest { - @Mock private OnceTrigger mockTrigger1; - @Mock private OnceTrigger mockTrigger2; private SimpleTriggerTester tester; - private IntervalWindow firstWindow; - - public void setUp(WindowFn windowFn) throws Exception { - MockitoAnnotations.initMocks(this); - tester = TriggerTester.forTrigger( - AfterAll.of(mockTrigger1, mockTrigger2), - windowFn); - firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); - } - - private void injectElement(int element, TriggerResult result1, TriggerResult result2) - throws Exception { - if (result1 != null) { - when(mockTrigger1.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result1); - } - if (result2 != null) { - when(mockTrigger2.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result2); - } - tester.injectElements(element); - } - - @Test - public void testOnElementT1FiresFirst() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - injectElement(2, TriggerResult.FIRE_AND_FINISH, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - injectElement(3, null, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(firstWindow)); - } @Test - public void testOnElementT2FiresFirst() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); + public void testT1FiresFirst() throws Exception { + tester = TriggerTester.forTrigger( + AfterAll.of( + AfterPane.elementCountAtLeast(1), + AfterPane.elementCountAtLeast(2)), + FixedWindows.of(Duration.millis(100))); - injectElement(1, TriggerResult.CONTINUE, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - injectElement(2, TriggerResult.FIRE_AND_FINISH, null); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); - assertTrue(tester.isMarkedFinished(firstWindow)); + tester.injectElements(2); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); } - @SuppressWarnings("unchecked") @Test - public void testOnTimerFire() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); + public void testT2FiresFirst() throws Exception { + tester = TriggerTester.forTrigger( + AfterAll.of( + AfterPane.elementCountAtLeast(2), + AfterPane.elementCountAtLeast(1)), + FixedWindows.of(Duration.millis(100))); - injectElement(1, TriggerResult.CONTINUE, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - when(mockTrigger1.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - tester.advanceInputWatermark(new Instant(12)); + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(firstWindow)); + tester.injectElements(2); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); } + /** + * Tests that the AfterAll properly unsets finished bits when a merge causing it to become + * unfinished. + */ @Test - public void testOnTimerFireAndFinish() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - when(mockTrigger1.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - tester.fireTimer(firstWindow, new Instant(11), TimeDomain.EVENT_TIME); - - tester.advanceInputWatermark(new Instant(12)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - assertFalse(tester.isMarkedFinished(firstWindow)); + public void testOnMergeRewinds() throws Exception { + tester = TriggerTester.forTrigger( + AfterEach.inOrder( + AfterAll.of( + AfterWatermark.pastEndOfWindow(), + AfterPane.elementCountAtLeast(1)), + Repeatedly.forever(AfterPane.elementCountAtLeast(1))), + Sessions.withGapDuration(Duration.millis(10))); - injectElement(2, TriggerResult.FIRE_AND_FINISH, null); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(firstWindow)); - } + tester.injectElements(1); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - @Test - public void testOnMergeFires() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); + tester.injectElements(5); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - when(mockTrigger1.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(1, 5); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); + // Finish the AfterAll in the first window + tester.advanceInputWatermark(new Instant(11)); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); - when(mockTrigger1.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.ALREADY_FINISHED); - when(mockTrigger2.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.FIRE_AND_FINISH); + // Merge them; the AfterAll should not be finished tester.mergeWindows(); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + assertFalse(tester.isMarkedFinished(mergedWindow)); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(15)))); - } - - @Test - public void testOnMergeFiresNotAlreadyFinished() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); + // Confirm that we are back on the first trigger by probing that it is not ready to fire + // after an element (with merging) + tester.injectElements(3); + tester.mergeWindows(); + assertFalse(tester.shouldFire(mergedWindow)); - when(mockTrigger1.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(1, 12); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); + // Fire the AfterAll in the merged window + tester.advanceInputWatermark(new Instant(15)); + assertTrue(tester.shouldFire(mergedWindow)); + tester.fireIfShouldFire(mergedWindow); - when(mockTrigger1.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.ALREADY_FINISHED); - when(mockTrigger2.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.ALREADY_FINISHED); - tester.injectElements(5); + // Confirm that we are on the second trigger by probing + tester.injectElements(2); tester.mergeWindows(); - - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(22)))); + assertTrue(tester.shouldFire(mergedWindow)); + tester.fireIfShouldFire(mergedWindow); + tester.injectElements(2); + tester.mergeWindows(); + assertTrue(tester.shouldFire(mergedWindow)); + tester.fireIfShouldFire(mergedWindow); } @Test public void testFireDeadline() throws Exception { BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - assertEquals(new Instant(19), - AfterAll.of(AfterWatermark.pastEndOfWindow(), - AfterWatermark.pastFirstElementInPane().plusDelayOf(Duration.millis(10))) - .getWatermarkThatGuaranteesFiring(window)); assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, AfterAll.of(AfterWatermark.pastEndOfWindow(), AfterPane.elementCountAtLeast(1)) .getWatermarkThatGuaranteesFiring(window)); } - @Test - public void testAfterAllRealTriggersFixedWindow() throws Exception { - tester = TriggerTester.forTrigger(Repeatedly.forever( - AfterAll.of( - AfterPane.elementCountAtLeast(5), - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)))), - FixedWindows.of(Duration.millis(50))); - - tester.advanceProcessingTime(new Instant(0)); - // 6 elements -> after pane fires - tester.injectElements(0, 0, 1, 1, 1, 2); - - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - tester.advanceProcessingTime(new Instant(6)); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - // 4 elements, advance processing time, then deliver the last elem - tester.clearResultSequence(); - tester.advanceProcessingTime(new Instant(15)); - tester.injectElements(2, 3, 4, 5); - tester.advanceProcessingTime(new Instant(21)); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - tester.injectElements(6); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(50)))); - } - - @Test - public void testAfterAllMergingWindowSomeFinished() throws Exception { - Duration windowDuration = Duration.millis(10); - tester = TriggerTester.forTrigger( - AfterAll.of( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - AfterPane.elementCountAtLeast(5)), - Sessions.withGapDuration(windowDuration)); - - tester.advanceProcessingTime(new Instant(10)); - tester.injectElements(1); // in [1, 11), timer for 15 - tester.advanceProcessingTime(new Instant(16)); - tester.injectElements( - 1, // in [1, 11) count = 1 - 2); // in [2, 12), timer for 16 - - // Enough data comes in for 2 that combined, we should fire - tester.injectElements(2, 2); - tester.mergeWindows(); - - // This fires, because the earliest element in [1, 12) arrived at time 10 - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - } - @Test public void testContinuation() throws Exception { OnceTrigger trigger1 = AfterProcessingTime.pastFirstElementInPane(); @@ -261,4 +147,5 @@ public void testContinuation() throws Exception { AfterAll.of(trigger1.getContinuationTrigger(), trigger2.getContinuationTrigger()), afterAll.getContinuationTrigger()); } + } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java index 0dc7345b92..5d6632d1c4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java @@ -16,29 +16,20 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnTimerContext; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; import org.joda.time.Duration; import org.joda.time.Instant; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.MockitoAnnotations; /** @@ -47,123 +38,61 @@ @RunWith(JUnit4.class) public class AfterEachTest { - @Mock private Trigger mockTrigger1; - @Mock private Trigger mockTrigger2; - private SimpleTriggerTester tester; - private IntervalWindow firstWindow; - public void setUp(WindowFn windowFn) throws Exception { + @Before + public void initMocks() { MockitoAnnotations.initMocks(this); - tester = TriggerTester.forTrigger( - AfterEach.inOrder(mockTrigger1, mockTrigger2), windowFn); - firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); - } - - private void injectElement(int element, TriggerResult result1, TriggerResult result2) - throws Exception { - if (result1 != null) { - when(mockTrigger1.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result1); - } - if (result2 != null) { - when(mockTrigger2.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result2); - } - - tester.injectElements(element); } /** * Tests that the {@link AfterEach} trigger fires and finishes the first trigger then the second. */ @Test - public void testOnElementT1Fires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - injectElement(2, TriggerResult.FIRE, null); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - tester.clearResultSequence(); - - injectElement(3, TriggerResult.FIRE_AND_FINISH, null); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - tester.clearResultSequence(); - - injectElement(4, null, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - } - - @Test - public void testOnElementT2Fires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.FIRE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - assertFalse(tester.isMarkedFinished(firstWindow)); - } - - @SuppressWarnings("unchecked") - @Test - public void testOnTimerFire() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - when(mockTrigger1.onTimer(Mockito.isA(OnTimerContext.class))) - .thenReturn(TriggerResult.FIRE); - tester.fireTimer(firstWindow, new Instant(11), TimeDomain.EVENT_TIME); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - assertFalse("Should still be waiting for the second trigger.", - tester.isMarkedFinished(firstWindow)); - } - - @Test - public void testOnMergeFinishes() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); - - when(mockTrigger1.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(1, 5); - - when(mockTrigger1.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.ALREADY_FINISHED); - when(mockTrigger2.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.FIRE_AND_FINISH); + public void testAfterEachInSequence() throws Exception { + tester = TriggerTester.forTrigger( + AfterEach.inOrder( + Repeatedly.forever(AfterPane.elementCountAtLeast(2)) + .orFinally(AfterPane.elementCountAtLeast(3)), + Repeatedly.forever(AfterPane.elementCountAtLeast(5)) + .orFinally(AfterWatermark.pastEndOfWindow())), + FixedWindows.of(Duration.millis(10))); + + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); + + // AfterCount(2) not ready + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + + // AfterCount(2) ready, not finished + tester.injectElements(2); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); + + // orFinally(AfterCount(3)) ready and will finish the first + tester.injectElements(1, 2, 3); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); + + // Now running as the second trigger + assertFalse(tester.shouldFire(window)); + // This quantity of elements would fire and finish if it were erroneously still the first + tester.injectElements(1, 2, 3, 4); + assertFalse(tester.shouldFire(window)); + + // Now fire once tester.injectElements(5); - - tester.mergeWindows(); - - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(15)))); - } - - @Test - public void testOnMergeFires() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); - - when(mockTrigger1.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(1, 5); - - when(mockTrigger1.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.ALREADY_FINISHED); - when(mockTrigger2.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.FIRE); - - tester.mergeWindows(); - - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE)); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); + + // This time advance the watermark to finish the whole mess. + tester.advanceInputWatermark(new Instant(10)); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); } @Test @@ -172,80 +101,14 @@ public void testFireDeadline() throws Exception { assertEquals(new Instant(9), AfterEach.inOrder(AfterWatermark.pastEndOfWindow(), - AfterWatermark.pastFirstElementInPane().plusDelayOf(Duration.millis(10))) + AfterPane.elementCountAtLeast(4)) .getWatermarkThatGuaranteesFiring(window)); + assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, AfterEach.inOrder(AfterPane.elementCountAtLeast(2), AfterWatermark.pastEndOfWindow()) .getWatermarkThatGuaranteesFiring(window)); } - @Test - public void testSequenceRealTriggersFixedWindow() throws Exception { - tester = TriggerTester.forTrigger(AfterEach.inOrder( - AfterPane.elementCountAtLeast(5), - AfterPane.elementCountAtLeast(5), - Repeatedly.forever(AfterEach.inOrder( - AfterPane.elementCountAtLeast(2), - AfterPane.elementCountAtLeast(2))) - .orFinally(AfterPane.elementCountAtLeast(7))), - FixedWindows.of(Duration.millis(50))); - - // Inject a bunch of elements all in the same window - for (int i = 0; i < 20; i++) { - tester.injectElements(i); - } - assertThat(tester.getResultSequence(), contains( - TriggerResult.CONTINUE, - TriggerResult.CONTINUE, - TriggerResult.CONTINUE, - TriggerResult.CONTINUE, - TriggerResult.FIRE, // 5 elements - TriggerResult.CONTINUE, - TriggerResult.CONTINUE, - TriggerResult.CONTINUE, - TriggerResult.CONTINUE, - TriggerResult.FIRE, // 5 elements - TriggerResult.CONTINUE, - TriggerResult.FIRE, // 2 elements (OrFinally at 2) - TriggerResult.CONTINUE, - TriggerResult.FIRE, // 2 elements (OrFinally at 4) - TriggerResult.CONTINUE, - TriggerResult.FIRE, // 2 elements (OrFinally at 6) - TriggerResult.FIRE_AND_FINISH)); // 1 elements (OrFinally at 7) - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(50)))); - } - - @Test - public void testAfterEachMergingWindowSomeFinished() throws Exception { - Duration windowDuration = Duration.millis(10); - tester = TriggerTester.forTrigger( - AfterEach.inOrder( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - AfterPane.elementCountAtLeast(5)), - Sessions.withGapDuration(windowDuration)); - - tester.advanceProcessingTime(new Instant(10)); - tester.injectElements(1); // in [1, 11), timer for 15 - tester.advanceProcessingTime(new Instant(16)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - tester.injectElements( - 1, // in [1, 11) count = 1 - 2); // in [2, 12), timer for 16 - - // [2, 12) tries to fire, but gets merged; count = 2 - tester.advanceProcessingTime(new Instant(30)); - - tester.injectElements(1, 2, 1); // count = 5, but need to call merge fire - - tester.mergeWindows(); - - // This fires, because the earliest element in [1, 12) arrived at time 10 - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - } - @Test public void testContinuation() throws Exception { OnceTrigger trigger1 = AfterProcessingTime.pastFirstElementInPane(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java index 9b43782eec..135638c363 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java @@ -16,23 +16,18 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; import org.joda.time.Duration; import org.joda.time.Instant; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -48,127 +43,112 @@ public class AfterFirstTest { @Mock private OnceTrigger mockTrigger1; @Mock private OnceTrigger mockTrigger2; - private SimpleTriggerTester tester; - private IntervalWindow firstWindow; - - public void setUp(WindowFn windowFn) throws Exception { - MockitoAnnotations.initMocks(this); - tester = TriggerTester.forTrigger( - AfterFirst.of(mockTrigger1, mockTrigger2), windowFn); - firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); + private static Trigger.TriggerContext anyTriggerContext() { + return Mockito..TriggerContext>any(); } - private void injectElement(int element, TriggerResult result1, TriggerResult result2) - throws Exception { - if (result1 != null) { - when(mockTrigger1.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result1); - } - if (result2 != null) { - when(mockTrigger2.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result2); - } - - tester.injectElements(element); - } - - @Test - public void testOnElementT1Fires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - injectElement(2, TriggerResult.FIRE_AND_FINISH, TriggerResult.CONTINUE); - assertThat(tester.getResultSequence(), - contains(TriggerResult.CONTINUE, TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(firstWindow)); + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); } @Test - public void testOnElementT2Fires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); + public void testNeitherShouldFireFixedWindows() throws Exception { + tester = TriggerTester.forTrigger( + AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + tester.injectElements(1); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - injectElement(2, TriggerResult.CONTINUE, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); + when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(false); + when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(false); - assertTrue(tester.isMarkedFinished(firstWindow)); + assertFalse(tester.shouldFire(window)); // should not fire + assertFalse(tester.isMarkedFinished(window)); // not finished } - @SuppressWarnings("unchecked") @Test - public void testOnTimerT1Fires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); + public void testOnlyT1ShouldFireFixedWindows() throws Exception { + tester = TriggerTester.forTrigger( + AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); + tester.injectElements(1); + IntervalWindow window = new IntervalWindow(new Instant(1), new Instant(11)); - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(true); + when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(false); - when(mockTrigger1.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - tester.fireTimer(firstWindow, new Instant(11), TimeDomain.EVENT_TIME); + assertTrue(tester.shouldFire(window)); // should fire - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(firstWindow)); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); } - @SuppressWarnings("unchecked") @Test - public void testOnTimerT2Fires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - when(mockTrigger1.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - tester.fireTimer(firstWindow, new Instant(11), TimeDomain.EVENT_TIME); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); + public void testOnlyT2ShouldFireFixedWindows() throws Exception { + tester = TriggerTester.forTrigger( + AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); + tester.injectElements(1); + IntervalWindow window = new IntervalWindow(new Instant(1), new Instant(11)); - assertTrue(tester.isMarkedFinished(firstWindow)); - } + when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(false); + when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(true); + assertTrue(tester.shouldFire(window)); // should fire - @SuppressWarnings("unchecked") - @Test - public void testOnTimerContinue() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - when(mockTrigger1.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.fireTimer(firstWindow, new Instant(11), TimeDomain.EVENT_TIME); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + tester.fireIfShouldFire(window); // now finished + assertTrue(tester.isMarkedFinished(window)); } @Test - public void testOnMergeFires() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); + public void testBothShouldFireFixedWindows() throws Exception { + tester = TriggerTester.forTrigger( + AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); + tester.injectElements(1); + IntervalWindow window = new IntervalWindow(new Instant(1), new Instant(11)); - when(mockTrigger1.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockTrigger2.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(1, 8); + when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(true); + when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(true); + assertTrue(tester.shouldFire(window)); // should fire - when(mockTrigger1.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.CONTINUE); - when(mockTrigger2.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.FIRE_AND_FINISH); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); + } + /** + * Tests that if the first trigger rewinds to be non-finished in the merged window, + * then it becomes the currently active trigger again, with real triggers. + */ + @Test + public void testShouldFireAfterMerge() throws Exception { + tester = TriggerTester.forTrigger( + AfterEach.inOrder( + AfterFirst.of(AfterPane.elementCountAtLeast(5), + AfterWatermark.pastEndOfWindow()), + Repeatedly.forever(AfterPane.elementCountAtLeast(1))), + Sessions.withGapDuration(Duration.millis(10))); + + // Finished the AfterFirst in the first window + tester.injectElements(1); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + assertFalse(tester.shouldFire(firstWindow)); + tester.advanceInputWatermark(new Instant(11)); + assertTrue(tester.shouldFire(firstWindow)); + tester.fireIfShouldFire(firstWindow); + + // Set up second window where it is not done + tester.injectElements(5); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); + assertFalse(tester.shouldFire(secondWindow)); + + // Merge them, if the merged window were on the second trigger, it would be ready tester.mergeWindows(); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + assertFalse(tester.shouldFire(mergedWindow)); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(18)))); + // Now adding 3 more makes the AfterFirst ready to fire + tester.injectElements(1, 2, 3, 4, 5); + tester.mergeWindows(); + assertTrue(tester.shouldFire(mergedWindow)); } @Test @@ -176,73 +156,13 @@ public void testFireDeadline() throws Exception { BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); assertEquals(new Instant(9), - AfterFirst.of(AfterWatermark.pastEndOfWindow(), - AfterWatermark.pastFirstElementInPane().plusDelayOf(Duration.millis(10))) + AfterFirst.of(AfterWatermark.pastEndOfWindow(), AfterPane.elementCountAtLeast(4)) .getWatermarkThatGuaranteesFiring(window)); assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, AfterFirst.of(AfterPane.elementCountAtLeast(2), AfterPane.elementCountAtLeast(1)) .getWatermarkThatGuaranteesFiring(window)); } - @Test - public void testAfterFirstRealTriggersFixedWindow() throws Exception { - tester = TriggerTester.forTrigger(Repeatedly.forever( - AfterFirst.of( - AfterPane.elementCountAtLeast(5), - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)))), - FixedWindows.of(Duration.millis(50))); - - tester.advanceProcessingTime(new Instant(0)); - // 5 elements -> after pane fires - tester.injectElements(0, 0, 1, 1, 1); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - // 4 elements, advance processing time to 5 (shouldn't fire yet), then advance it to 6 - tester.advanceProcessingTime(new Instant(1)); - tester.injectElements(2, 3, 4, 5); - tester.advanceProcessingTime(new Instant(5)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - // Fires now - tester.advanceProcessingTime(new Instant(7)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - // Now, send in 5 more elements, and make sure they come out as a group. State should not - // be carried over. - tester.injectElements(6, 7, 8, 9, 10); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(50)))); - } - - @Test - public void testAfterFirstMergingWindowSomeFinished() throws Exception { - Duration windowDuration = Duration.millis(10); - tester = TriggerTester.forTrigger( - AfterFirst.of( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - AfterPane.elementCountAtLeast(5)), - Sessions.withGapDuration(windowDuration)); - - tester.advanceProcessingTime(new Instant(10)); - tester.injectElements( - 1, // in [1, 11), timer for 15 - 1, // in [1, 11) count = 1 - 2); // in [2, 12), timer for 16 - - // Enough data comes in for 2 that combined, we should fire - tester.injectElements(2, 2); - - tester.mergeWindows(); - - // This fires, because the earliest element in [1, 12) arrived at time 10 - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - } - @Test public void testContinuation() throws Exception { OnceTrigger trigger1 = AfterProcessingTime.pastFirstElementInPane(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java index 8c6b165f74..9139bc5884 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java @@ -16,14 +16,10 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -38,29 +34,30 @@ */ @RunWith(JUnit4.class) public class AfterPaneTest { + + SimpleTriggerTester tester; + /** + * Tests that the trigger does fire when enough elements are in a window, and that it only + * fires that window (no leakage). + */ @Test - public void testAfterPaneWithGlobalWindowsAndCombining() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testAfterPaneElementCountFixedWindows() throws Exception { + tester = TriggerTester.forTrigger( AfterPane.elementCountAtLeast(2), - FixedWindows.of(windowDuration)); + FixedWindows.of(Duration.millis(10))); - tester.injectElements(1, 9); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); - } + tester.injectElements(1); // [0, 10) + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); + assertFalse(tester.shouldFire(window)); - @Test - public void testAfterPaneWithFixedWindow() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterPane.elementCountAtLeast(2), - FixedWindows.of(windowDuration)); + tester.injectElements(2); // [0, 10) + tester.injectElements(11); // [10, 20) - tester.injectElements(1, 9); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); + assertTrue(tester.shouldFire(window)); // ready to fire + tester.fireIfShouldFire(window); // and finished + assertTrue(tester.isMarkedFinished(window)); + + // But don't finish the other window assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); } @@ -77,29 +74,37 @@ public void testClear() throws Exception { } @Test - public void testAfterPaneWithMerging() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testAfterPaneElementCountSessions() throws Exception { + tester = TriggerTester.forTrigger( AfterPane.elementCountAtLeast(2), - Sessions.withGapDuration(windowDuration)); + Sessions.withGapDuration(Duration.millis(10))); tester.injectElements( 1, // in [1, 11) 2); // in [2, 12) + + assertFalse(tester.shouldFire(new IntervalWindow(new Instant(1), new Instant(11)))); + assertFalse(tester.shouldFire(new IntervalWindow(new Instant(2), new Instant(12)))); + tester.mergeWindows(); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - tester.clearLatestMergeResult(); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(12)); + assertTrue(tester.shouldFire(mergedWindow)); + tester.fireIfShouldFire(mergedWindow); + assertTrue(tester.isMarkedFinished(mergedWindow)); // Because we closed the previous window, we don't have it around to merge with. So there // will be a new FIRE_AND_FINISH result. tester.injectElements( 7, // in [7, 17) - 9); // in [8, 18) + 9); // in [9, 19) - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); + tester.mergeWindows(); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); + IntervalWindow newMergedWindow = new IntervalWindow(new Instant(7), new Instant(19)); + assertTrue(tester.shouldFire(newMergedWindow)); + tester.fireIfShouldFire(newMergedWindow); + assertTrue(tester.isMarkedFinished(newMergedWindow)); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java index 0da184a8c9..013c5395bb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java @@ -16,15 +16,10 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.everyItem; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -39,24 +34,13 @@ */ @RunWith(JUnit4.class) public class AfterProcessingTimeTest { - @Test - public void testAfterProcessingTimeIgnoresTimer() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterProcessingTime - .pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - FixedWindows.of(windowDuration)); - - tester.fireTimer(new IntervalWindow(new Instant(0), new Instant(10)), - new Instant(15), TimeDomain.PROCESSING_TIME); - tester.injectElements(1); - tester.fireTimer(new IntervalWindow(new Instant(0), new Instant(10)), - new Instant(5), TimeDomain.PROCESSING_TIME); - } + /** + * Tests the basic property that the trigger does wait for processing time to be + * far enough advanced. + */ @Test - public void testAfterProcessingTimeWithFixedWindow() throws Exception { + public void testAfterProcessingTimeFixedWindows() throws Exception { Duration windowDuration = Duration.millis(10); SimpleTriggerTester tester = TriggerTester.forTrigger( AfterProcessingTime @@ -68,42 +52,41 @@ public void testAfterProcessingTimeWithFixedWindow() throws Exception { // Timer at 15 tester.injectElements(1); + IntervalWindow firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); tester.advanceProcessingTime(new Instant(12)); + assertFalse(tester.shouldFire(firstWindow)); // Load up elements in the next window, timer at 17 for them tester.injectElements(11, 12, 13); + IntervalWindow secondWindow = new IntervalWindow(new Instant(10), new Instant(20)); + assertFalse(tester.shouldFire(secondWindow)); + // Not quite time to fire tester.advanceProcessingTime(new Instant(14)); + assertFalse(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); - // Timer at 19 for these; it should be ignored since the 15 will fire first + // Timer at 19 for these in the first window; it should be ignored since the 15 will fire first tester.injectElements(2, 3); - // We should not have fired yet - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - // Advance past the first timer and fire, finishing the first window tester.advanceProcessingTime(new Instant(16)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + assertTrue(tester.isMarkedFinished(firstWindow)); - // This element belongs in the window that has already fired; it should not - // be passed to onElement, so there should be no resultSequence to observe - // (thus necessarily no timer) - tester.clearResultSequence(); - tester.injectElements(2); - assertThat(tester.getResultSequence(), emptyIterable()); - - // The next window fires and finishes + // The next window fires and finishes now tester.advanceProcessingTime(new Instant(18)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); - - // The timer for the finished window, from later elements, should also not do anything - tester.clearResultSequence(); - tester.advanceProcessingTime(new Instant(20)); - assertThat(tester.getResultSequence(), emptyIterable()); + assertTrue(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(secondWindow); + assertTrue(tester.isMarkedFinished(secondWindow)); } + /** + * Tests that when windows merge, if the trigger is waiting for "N millis after the first + * element" that it is relative to the earlier of the two merged windows. + */ @Test public void testClear() throws Exception { SimpleTriggerTester tester = TriggerTester.forTrigger( @@ -120,22 +103,27 @@ public void testClear() throws Exception { @Test public void testAfterProcessingTimeWithMergingWindow() throws Exception { - Duration windowDuration = Duration.millis(10); SimpleTriggerTester tester = TriggerTester.forTrigger( AfterProcessingTime .pastFirstElementInPane() .plusDelayOf(Duration.millis(5)), - Sessions.withGapDuration(windowDuration)); + Sessions.withGapDuration(Duration.millis(10))); tester.advanceProcessingTime(new Instant(10)); tester.injectElements(1); // in [1, 11), timer for 15 - tester.advanceProcessingTime(new Instant(11)); - tester.injectElements(2); // in [2, 12), timer for 16 + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + assertFalse(tester.shouldFire(firstWindow)); + + tester.advanceProcessingTime(new Instant(12)); + tester.injectElements(3); // in [3, 13), timer for 17 + IntervalWindow secondWindow = new IntervalWindow(new Instant(3), new Instant(13)); + assertFalse(tester.shouldFire(secondWindow)); + + tester.mergeWindows(); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(13)); tester.advanceProcessingTime(new Instant(16)); - // This fires, because the earliest element in [1, 12) arrived at time 10 - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(11)))); + assertTrue(tester.shouldFire(mergedWindow)); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java index 23f46f24ff..b37bba42e9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java @@ -15,15 +15,10 @@ */ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.everyItem; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -43,61 +38,73 @@ public class AfterSynchronizedProcessingTimeTest { new AfterSynchronizedProcessingTime(); @Test - public void testAfterProcessingTimeWithFixedWindow() throws Exception { + public void testAfterProcessingTimeWithFixedWindows() throws Exception { Duration windowDuration = Duration.millis(10); SimpleTriggerTester tester = TriggerTester.forTrigger( - underTest, FixedWindows.of(windowDuration)); + AfterProcessingTime + .pastFirstElementInPane() + .plusDelayOf(Duration.millis(5)), + FixedWindows.of(windowDuration)); tester.advanceProcessingTime(new Instant(10)); - // synchronized timers for 10 - tester.injectElements(1, 9, 8); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - - tester.advanceProcessingTime(new Instant(11)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); - - // This element belongs in the window that has already fired. It should not be - // processed. - tester.clearResultSequence(); - tester.injectElements(2); - assertThat(tester.getResultSequence(), emptyIterable()); + // Timer at 15 + tester.injectElements(1); + IntervalWindow firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); + tester.advanceProcessingTime(new Instant(12)); + assertFalse(tester.shouldFire(firstWindow)); + + // Load up elements in the next window, timer at 17 for them + tester.injectElements(11, 12, 13); + IntervalWindow secondWindow = new IntervalWindow(new Instant(10), new Instant(20)); + assertFalse(tester.shouldFire(secondWindow)); + + // Not quite time to fire + tester.advanceProcessingTime(new Instant(14)); + assertFalse(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + + // Timer at 19 for these in the first window; it should be ignored since the 15 will fire first + tester.injectElements(2, 3); + + // Advance past the first timer and fire, finishing the first window + tester.advanceProcessingTime(new Instant(16)); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + assertTrue(tester.isMarkedFinished(firstWindow)); + + // The next window fires and finishes now + tester.advanceProcessingTime(new Instant(18)); + assertTrue(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(secondWindow); + assertTrue(tester.isMarkedFinished(secondWindow)); } @Test public void testAfterProcessingTimeWithMergingWindow() throws Exception { Duration windowDuration = Duration.millis(10); SimpleTriggerTester tester = TriggerTester.forTrigger( - underTest, + AfterProcessingTime + .pastFirstElementInPane() + .plusDelayOf(Duration.millis(5)), Sessions.withGapDuration(windowDuration)); tester.advanceProcessingTime(new Instant(10)); - tester.injectElements( - 1, // in [1, 11), synchronized timer for 10 - 2); // in [2, 12), synchronized timer for 10 - tester.mergeWindows(); - tester.clearResultSequence(); + tester.injectElements(1); // in [1, 11), timer for 15 + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + assertFalse(tester.shouldFire(firstWindow)); - // The timers for the pre-merged windows should be ignored. - tester.advanceProcessingTime(new Instant(11)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - } + tester.advanceProcessingTime(new Instant(12)); + tester.injectElements(3); // in [3, 13), timer for 17 + IntervalWindow secondWindow = new IntervalWindow(new Instant(3), new Instant(13)); + assertFalse(tester.shouldFire(secondWindow)); - @Test - public void testAfterSynchronizedProcessingTimeIgnoresTimer() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - new AfterSynchronizedProcessingTime(), - FixedWindows.of(windowDuration)); + tester.mergeWindows(); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(13)); - tester.fireTimer(new IntervalWindow(new Instant(0), new Instant(10)), - new Instant(15), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - tester.advanceProcessingTime(new Instant(5)); - tester.injectElements(1); - tester.fireTimer(new IntervalWindow(new Instant(0), new Instant(10)), - new Instant(0), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + tester.advanceProcessingTime(new Instant(16)); + assertTrue(tester.shouldFire(mergedWindow)); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java index 517bf20920..fb610aadd1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java @@ -16,17 +16,12 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.everyItem; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -46,364 +41,298 @@ @RunWith(JUnit4.class) public class AfterWatermarkTest { - @Mock - private OnceTrigger mockEarly; - @Mock - private OnceTrigger mockLate; + @Mock private OnceTrigger mockEarly; + @Mock private OnceTrigger mockLate; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); + private SimpleTriggerTester tester; + private static Trigger.TriggerContext anyTriggerContext() { + return Mockito..TriggerContext>any(); } - - @Test - public void testFirstInPaneWithFixedWindow() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastFirstElementInPane().plusDelayOf(Duration.millis(5)), - FixedWindows.of(windowDuration)); - - tester.injectElements(1); // first in window [0, 10), timer set for 6 - tester.advanceInputWatermark(new Instant(5)); - tester.injectElements(9, 8); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - - tester.advanceInputWatermark(new Instant(7)); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); + private static Trigger.OnElementContext anyElementContext() { + return Mockito..OnElementContext>any(); } - @Test - public void testAlignAndDelay() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastFirstElementInPane() - .alignedTo(Duration.standardMinutes(1)) - .plusDelayOf(Duration.standardMinutes(5)), - FixedWindows.of(Duration.standardMinutes(1))); - - Instant zero = new Instant(0); - - // first in window [0, 1m), timer set for 6m - tester.injectElements(1000, 5000, 55000); - - // Advance to 6m. No output should be produced. - tester.advanceInputWatermark(zero.plus(Duration.standardMinutes(6))); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - - // Advance to 6m+1ms and see our output - tester.advanceInputWatermark(zero.plus(Duration.standardMinutes(6).plus(1))); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - } - - @Test - public void testAfterFirstInPaneClear() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastFirstElementInPane().plusDelayOf(Duration.millis(5)), - FixedWindows.of(Duration.millis(10))); - - tester.injectElements(1, 2, 3); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - tester.clearState(window); - tester.assertCleared(window); - } - - @Test - public void testFirstInPaneWithMerging() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastFirstElementInPane().plusDelayOf(Duration.millis(5)), - Sessions.withGapDuration(windowDuration)); - - tester.advanceInputWatermark(new Instant(1)); - - tester.injectElements( - 1, // in [1, 11), timer for 6 - 2); // in [2, 12), timer for 7 - tester.mergeWindows(); - tester.advanceInputWatermark(new Instant(7)); - - // We merged, and updated the timer to the earliest timer, which was still 6. - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); + private void injectElements(int... elements) throws Exception { + for (int element : elements) { + doNothing().when(mockEarly).onElement(anyElementContext()); + doNothing().when(mockLate).onElement(anyElementContext()); + tester.injectElements(element); + } } - @Test - public void testEndOfWindowFixedWindow() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow(), - FixedWindows.of(windowDuration)); - - tester.injectElements(1); // first in window [0, 10), timer set for 9 - tester.advanceInputWatermark(new Instant(8)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - tester.injectElements(9, 8); - tester.advanceInputWatermark(new Instant(10)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(10)))); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); } - @Test - public void testEndOfWindowWithMerging() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow(), - Sessions.withGapDuration(windowDuration)); - - tester.advanceInputWatermark(new Instant(1)); - - tester.injectElements( - 1, // in [1, 11], timer for 11 - 2); // in [2, 12], timer for 12 - tester.mergeWindows(); - tester.advanceInputWatermark(new Instant(10)); - - // We merged, and updated the watermark timer to the end of the new window. - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - tester.injectElements(1); // in [1, 11], timer for 11 - tester.mergeWindows(); - tester.advanceInputWatermark(new Instant(12)); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - } + public void testRunningAsTrigger(OnceTrigger mockTrigger, IntervalWindow window) + throws Exception { - @Test - public void testFireDeadline() throws Exception { - BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - assertEquals(new Instant(9), AfterWatermark.pastEndOfWindow() - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(GlobalWindow.INSTANCE.maxTimestamp(), - AfterWatermark.pastEndOfWindow().getWatermarkThatGuaranteesFiring(GlobalWindow.INSTANCE)); - assertEquals(new Instant(19), - AfterWatermark - .pastFirstElementInPane() - .plusDelayOf(Duration.millis(10)).getWatermarkThatGuaranteesFiring(window)); - } + // Don't fire due to mock saying no + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); + assertFalse(tester.shouldFire(window)); // not ready - @Test - public void testContinuation() throws Exception { - Trigger endOfWindow = AfterWatermark.pastEndOfWindow(); - assertEquals(endOfWindow, endOfWindow.getContinuationTrigger()); - assertEquals( - endOfWindow, - endOfWindow.getContinuationTrigger().getContinuationTrigger()); - - Trigger firstElementAligned = - AfterWatermark.pastFirstElementInPane().alignedTo(Duration.standardDays(1)); - assertEquals( - firstElementAligned, - firstElementAligned.getContinuationTrigger()); - assertEquals( - firstElementAligned, - firstElementAligned.getContinuationTrigger().getContinuationTrigger()); + // Fire due to mock trigger; early trigger is required to be a OnceTrigger + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + assertTrue(tester.shouldFire(window)); // ready + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); } @Test - public void testEarlyAndAtWatermarkProcessElement() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testEarlyAndAtWatermark() throws Exception { + tester = TriggerTester.forTrigger( AfterWatermark.pastEndOfWindow() .withEarlyFirings(mockEarly), FixedWindows.of(Duration.millis(100))); - // Fire the early trigger - when(mockEarly.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.FIRE_AND_FINISH) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(5, 10); // Fires due to early trigger - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - // Fire the watermark trigger - tester.injectElements(15); - tester.advanceInputWatermark(new Instant(100L)); // Fires due to AtWatermark - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(100)))); + injectElements(1); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); + + testRunningAsTrigger(mockEarly, window); + + // Fire due to watermark + when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(false); + tester.advanceInputWatermark(new Instant(100)); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); } @Test - public void testLateAndAtWatermarkProcessElement() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testAtWatermarkAndLate() throws Exception { + tester = TriggerTester.forTrigger( AfterWatermark.pastEndOfWindow() .withLateFirings(mockLate), FixedWindows.of(Duration.millis(100))); - tester.injectElements(5, 10, 15); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - - tester.advanceInputWatermark(new Instant(100L)); // Fires due to AtWatermark - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); + injectElements(1); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - when(mockLate.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.FIRE_AND_FINISH) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - - tester.injectElements(20, 25, 30); // Fires due to late trigger - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); + // No early firing, just double checking + when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(true); + assertFalse(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); - tester.injectElements(35, 40); // Fires due to late trigger - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); + // Fire due to watermark + when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(false); + tester.advanceInputWatermark(new Instant(100)); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(100)))); + testRunningAsTrigger(mockLate, window); } @Test - public void testEarlyLateAndAtWatermarkProcessElement() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testEarlyAndAtWatermarkAndLate() throws Exception { + tester = TriggerTester.forTrigger( AfterWatermark.pastEndOfWindow() .withEarlyFirings(mockEarly) .withLateFirings(mockLate), FixedWindows.of(Duration.millis(100))); - when(mockEarly.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.FIRE_AND_FINISH) - .thenReturn(TriggerResult.CONTINUE); - - // These should set a timer for 100 - tester.injectElements(5, 10); // Fires due to early trigger - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - tester.injectElements(15); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - tester.advanceInputWatermark(new Instant(99L)); // Checking for off-by-one - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - tester.advanceInputWatermark(new Instant(100L)); // Fires due to AtWatermark - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - when(mockLate.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.FIRE_AND_FINISH) - .thenReturn(TriggerResult.CONTINUE) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - - // Get the late trigger to fire once - tester.clearResultSequence(); - tester.injectElements(20, 25); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - tester.injectElements(30); // Fires due to late trigger - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - // Get the late trigger to fire again - tester.clearResultSequence(); - tester.injectElements(35); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - tester.injectElements(40); // Fires due to late again - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(0), new Instant(100)))); - } - - @Test - public void testEarlyAndAtWatermarkSessions() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterPane.elementCountAtLeast(2)), - Sessions.withGapDuration(Duration.millis(20))); + injectElements(1); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - tester.injectElements(5, 20); - tester.mergeWindows(); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(5), new Instant(40)))); + testRunningAsTrigger(mockEarly, window); - tester.injectElements(6); - tester.mergeWindows(); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.CONTINUE)); + // Fire due to watermark + when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(false); + tester.advanceInputWatermark(new Instant(100)); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); - tester.advanceInputWatermark(new Instant(100L)); // Fires due to AtWatermark - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(5), new Instant(40)))); + testRunningAsTrigger(mockLate, window); } + /** + * Tests that if the EOW is finished in both as well as the merged window, then + * it is finished in the merged result. + * + *

Because windows are discarded when a trigger finishes, we need to embed this + * in a sequence in order to check that it is re-activated. So this test is potentially + * sensitive to other triggers' correctness. + */ @Test - public void testLateAndAtWatermarkSessionsProcessingTime() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow() - .withLateFirings(AfterProcessingTime - .pastFirstElementInPane().plusDelayOf(Duration.millis(10))), - Sessions.withGapDuration(Duration.millis(20))); - - tester.advanceProcessingTime(new Instant(0L)); - tester.injectElements(5, 20); - tester.advanceProcessingTime(new Instant(50L)); // Check that we don't trigger wrongly - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); + public void testOnMergeAlreadyFinished() throws Exception { + tester = TriggerTester.forTrigger( + AfterEach.inOrder( + AfterWatermark.pastEndOfWindow(), + Repeatedly.forever(AfterPane.elementCountAtLeast(1))), + Sessions.withGapDuration(Duration.millis(10))); + + tester.injectElements(1); + tester.injectElements(5); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + + // Finish the AfterWatermark.pastEndOfWindow() trigger in both windows + tester.advanceInputWatermark(new Instant(15)); + assertTrue(tester.shouldFire(firstWindow)); + assertTrue(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + tester.fireIfShouldFire(secondWindow); + + // Confirm that we are on the second trigger by probing + assertFalse(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + tester.injectElements(1); + tester.injectElements(5); + assertTrue(tester.shouldFire(firstWindow)); + assertTrue(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + tester.fireIfShouldFire(secondWindow); + + // Merging should leave it finished + tester.mergeWindows(); - tester.advanceInputWatermark(new Instant(70L)); // Fires due to AtWatermark - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); + // Confirm that we are on the second trigger by probing + assertFalse(tester.shouldFire(mergedWindow)); + tester.injectElements(1); + assertTrue(tester.shouldFire(mergedWindow)); + } - tester.injectElements(6); - tester.mergeWindows(); // merge must be manually triggered to learn we are on late trigger - tester.advanceProcessingTime(new Instant(100L)); // Fires the late trigger - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); + /** + * Tests that the trigger rewinds to be non-finished in the merged window. + * + *

Because windows are discarded when a trigger finishes, we need to embed this + * in a sequence in order to check that it is re-activated. So this test is potentially + * sensitive to other triggers' correctness. + */ + @Test + public void testOnMergeRewinds() throws Exception { + tester = TriggerTester.forTrigger( + AfterEach.inOrder( + AfterWatermark.pastEndOfWindow(), + Repeatedly.forever(AfterPane.elementCountAtLeast(1))), + Sessions.withGapDuration(Duration.millis(10))); + + tester.injectElements(1); + tester.injectElements(5); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + + // Finish the AfterWatermark.pastEndOfWindow() trigger in only the first window + tester.advanceInputWatermark(new Instant(11)); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + + // Confirm that we are on the second trigger by probing + assertFalse(tester.shouldFire(firstWindow)); + tester.injectElements(1); + assertTrue(tester.shouldFire(firstWindow)); + tester.fireIfShouldFire(firstWindow); + + // Merging should re-activate the watermark trigger in the merged window + tester.mergeWindows(); - tester.injectElements(9); - tester.mergeWindows(); // merge must be manually triggered to learn we are on late trigger - tester.advanceProcessingTime(new Instant(150L)); // Fires the late trigger again + // Confirm that we are not on the second trigger by probing + assertFalse(tester.shouldFire(mergedWindow)); + tester.injectElements(1); + assertFalse(tester.shouldFire(mergedWindow)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(5), new Instant(40)))); + // And confirm that advancing the watermark fires again + tester.advanceInputWatermark(new Instant(15)); + assertTrue(tester.shouldFire(mergedWindow)); } + /** + * Tests that if the EOW is finished in both as well as the merged window, then + * it is finished in the merged result. + * + *

Because windows are discarded when a trigger finishes, we need to embed this + * in a sequence in order to check that it is re-activated. So this test is potentially + * sensitive to other triggers' correctness. + */ @Test - public void testLateAndAtWatermarkSessions() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testEarlyAndLateOnMergeAlreadyFinished() throws Exception { + tester = TriggerTester.forTrigger( AfterWatermark.pastEndOfWindow() - .withLateFirings(AfterPane.elementCountAtLeast(2)), - Sessions.withGapDuration(Duration.millis(20))); - - tester.injectElements(5, 20); - - tester.advanceInputWatermark(new Instant(70L)); // Fires due to AtWatermark - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - IntervalWindow window = new IntervalWindow(new Instant(5), new Instant(40)); - assertFalse(tester.isMarkedFinished(window)); - - tester.injectElements(7, 8, 9); // Fires because we have at least 5 items + .withEarlyFirings(AfterPane.elementCountAtLeast(100)) + .withLateFirings(AfterPane.elementCountAtLeast(1)), + Sessions.withGapDuration(Duration.millis(10))); + + tester.injectElements(1); + tester.injectElements(5); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + + // Finish the AfterWatermark.pastEndOfWindow() bit of the trigger in both windows + tester.advanceInputWatermark(new Instant(15)); + assertTrue(tester.shouldFire(firstWindow)); + assertTrue(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + tester.fireIfShouldFire(secondWindow); + + // Confirm that we are on the late trigger by probing + assertFalse(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + tester.injectElements(1); + tester.injectElements(5); + assertTrue(tester.shouldFire(firstWindow)); + assertTrue(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + tester.fireIfShouldFire(secondWindow); + + // Merging should leave it on the late trigger tester.mergeWindows(); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE)); - assertFalse(tester.isMarkedFinished(window)); + // Confirm that we are on the late trigger by probing + assertFalse(tester.shouldFire(mergedWindow)); + tester.injectElements(1); + assertTrue(tester.shouldFire(mergedWindow)); } + /** + * Tests that the trigger rewinds to be non-finished in the merged window. + * + *

Because windows are discarded when a trigger finishes, we need to embed this + * in a sequence in order to check that it is re-activated. So this test is potentially + * sensitive to other triggers' correctness. + */ @Test - public void testEarlyLateAndAtWatermarkSessions() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testEarlyAndLateOnMergeRewinds() throws Exception { + tester = TriggerTester.forTrigger( AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(50))) - .withLateFirings(AfterPane.elementCountAtLeast(2)), - Sessions.withGapDuration(Duration.millis(20))); - - tester.advanceProcessingTime(new Instant(0)); - tester.injectElements(5, 20); - - tester.advanceProcessingTime(new Instant(56)); // Fires due to early trigger - tester.advanceInputWatermark(new Instant(70L)); // Fires due to AtWatermark - - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(5), new Instant(40)))); - - tester.injectElements( - 6, - 7, // Should fire due to late trigger - 8); + .withEarlyFirings(AfterPane.elementCountAtLeast(100)) + .withLateFirings(AfterPane.elementCountAtLeast(1)), + Sessions.withGapDuration(Duration.millis(10))); + + tester.injectElements(1); + tester.injectElements(5); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + + // Finish the AfterWatermark.pastEndOfWindow() bit of the trigger in only the first window + tester.advanceInputWatermark(new Instant(11)); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + tester.fireIfShouldFire(firstWindow); + + // Confirm that we are on the late trigger by probing + assertFalse(tester.shouldFire(firstWindow)); + tester.injectElements(1); + assertTrue(tester.shouldFire(firstWindow)); + tester.fireIfShouldFire(firstWindow); + + // Merging should re-activate the early trigger in the merged window tester.mergeWindows(); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(5), new Instant(40)))); + // Confirm that we are not on the second trigger by probing + assertFalse(tester.shouldFire(mergedWindow)); + tester.injectElements(1); + assertFalse(tester.shouldFire(mergedWindow)); + + // And confirm that advancing the watermark fires again + tester.advanceInputWatermark(new Instant(15)); + assertTrue(tester.shouldFire(mergedWindow)); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java index 3e660dfd56..bdc31e27fd 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java @@ -16,13 +16,10 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.everyItem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -33,87 +30,135 @@ import org.junit.runners.JUnit4; /** - * Tests the {@link DefaultTrigger} in a variety of windowing modes. + * Tests the {@link DefaultTrigger}, which should be equivalent to + * {@code Repeatedly.forever(AfterWatermark.pastEndOfWindow())}. */ @RunWith(JUnit4.class) public class DefaultTriggerTest { + SimpleTriggerTester tester; + @Test - public void testDefaultTriggerWithFixedWindow() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testDefaultTriggerFixedWindows() throws Exception { + tester = TriggerTester.forTrigger( DefaultTrigger.of(), - FixedWindows.of(Duration.millis(10))); + FixedWindows.of(Duration.millis(100))); - tester.injectElements(1, 9, 15, 19, 30); + tester.injectElements( + 1, // [0, 100) + 101); // [100, 200) - // Advance the watermark almost to the end of the first window. - tester.advanceProcessingTime(new Instant(500)); - tester.advanceInputWatermark(new Instant(8)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + IntervalWindow firstWindow = new IntervalWindow(new Instant(0), new Instant(100)); + IntervalWindow secondWindow = new IntervalWindow(new Instant(100), new Instant(200)); - // Advance watermark to 10 (past end of the window), which causes the first fixed window to - // be emitted - tester.advanceInputWatermark(new Instant(10)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); + // Advance the watermark almost to the end of the first window. + tester.advanceInputWatermark(new Instant(99)); + assertFalse(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); - // Advance watermark to 100, which causes the remaining two windows to be emitted. - // Since their timers were at different timestamps, they should fire in order. + // Advance watermark past end of the first window, which is then ready tester.advanceInputWatermark(new Instant(100)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(30), new Instant(40)))); - } - - @Test - public void testDefaultTriggerWithSessionWindow() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - DefaultTrigger.of(), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements(1, 9); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); - // no output, because we merged into the [9-19) session - tester.advanceInputWatermark(new Instant(10)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + // Fire, but the first window is still allowed to fire + tester.fireIfShouldFire(firstWindow); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); - tester.injectElements(15, 30); + // Advance watermark to 200, then both are ready + tester.advanceInputWatermark(new Instant(200)); + assertTrue(tester.shouldFire(firstWindow)); + assertTrue(tester.shouldFire(secondWindow)); - tester.advanceInputWatermark(new Instant(100)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(25)))); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(30), new Instant(40)))); + assertFalse(tester.isMarkedFinished(firstWindow)); + assertFalse(tester.isMarkedFinished(secondWindow)); } @Test - public void testDefaultTriggerWithSlidingWindow() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testDefaultTriggerSlidingWindows() throws Exception { + tester = TriggerTester.forTrigger( DefaultTrigger.of(), - SlidingWindows.of(Duration.millis(10)).every(Duration.millis(5))); - - tester.injectElements(1, 4, 9); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - tester.clearResultSequence(); - - tester.advanceInputWatermark(new Instant(5)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - tester.advanceInputWatermark(new Instant(10)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - tester.advanceInputWatermark(new Instant(15)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(10)))); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(5), new Instant(15)))); + SlidingWindows.of(Duration.millis(100)).every(Duration.millis(50))); + + tester.injectElements( + 1, // [-50, 50), [0, 100) + 50); // [0, 100), [50, 150) + + IntervalWindow firstWindow = new IntervalWindow(new Instant(-50), new Instant(50)); + IntervalWindow secondWindow = new IntervalWindow(new Instant(0), new Instant(100)); + IntervalWindow thirdWindow = new IntervalWindow(new Instant(50), new Instant(150)); + + assertFalse(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + assertFalse(tester.shouldFire(thirdWindow)); + + // At 50, the first becomes ready; it stays ready after firing + tester.advanceInputWatermark(new Instant(50)); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + assertFalse(tester.shouldFire(thirdWindow)); + tester.fireIfShouldFire(firstWindow); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + assertFalse(tester.shouldFire(thirdWindow)); + + // At 99, the first is still the only one ready + tester.advanceInputWatermark(new Instant(99)); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + assertFalse(tester.shouldFire(thirdWindow)); + + // At 100, the first and second are ready + tester.advanceInputWatermark(new Instant(100)); + assertTrue(tester.shouldFire(firstWindow)); + assertTrue(tester.shouldFire(secondWindow)); + assertFalse(tester.shouldFire(thirdWindow)); + tester.fireIfShouldFire(firstWindow); + + assertFalse(tester.isMarkedFinished(firstWindow)); + assertFalse(tester.isMarkedFinished(secondWindow)); + assertFalse(tester.isMarkedFinished(thirdWindow)); } @Test - public void testDefaultTriggerWithContainedSessionWindow() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( + public void testDefaultTriggerSessions() throws Exception { + tester = TriggerTester.forTrigger( DefaultTrigger.of(), - Sessions.withGapDuration(Duration.millis(10))); + Sessions.withGapDuration(Duration.millis(100))); + + tester.injectElements( + 1, // [1, 101) + 50); // [50, 150) + tester.mergeWindows(); - tester.injectElements(1, 9, 7); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(101)); + IntervalWindow secondWindow = new IntervalWindow(new Instant(50), new Instant(150)); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(150)); - tester.advanceInputWatermark(new Instant(20)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); + // Not ready in any window yet + tester.advanceInputWatermark(new Instant(100)); + assertFalse(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + assertFalse(tester.shouldFire(mergedWindow)); + + // The first window is "ready": the caller owns knowledge of which windows are merged away + tester.advanceInputWatermark(new Instant(149)); + assertTrue(tester.shouldFire(firstWindow)); + assertFalse(tester.shouldFire(secondWindow)); + assertFalse(tester.shouldFire(mergedWindow)); + + // Now ready on all windows + tester.advanceInputWatermark(new Instant(150)); + assertTrue(tester.shouldFire(firstWindow)); + assertTrue(tester.shouldFire(secondWindow)); + assertTrue(tester.shouldFire(mergedWindow)); + + // Ensure it repeats + tester.fireIfShouldFire(mergedWindow); + assertTrue(tester.shouldFire(mergedWindow)); + + assertFalse(tester.isMarkedFinished(mergedWindow)); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java index 2660074a47..a416e60425 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java @@ -16,18 +16,11 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.everyItem; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -36,159 +29,142 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; /** * Tests for {@link OrFinallyTrigger}. */ @RunWith(JUnit4.class) public class OrFinallyTriggerTest { - @Mock private Trigger mockActual; - @Mock private OnceTrigger mockUntil; private SimpleTriggerTester tester; - private IntervalWindow firstWindow; - - public void setUp(WindowFn windowFn) throws Exception { - MockitoAnnotations.initMocks(this); - - Trigger underTest = - new OrFinallyTrigger(mockActual, mockUntil); - - tester = TriggerTester.forTrigger( - underTest, windowFn); - firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); - } - - private void injectElement(int element, TriggerResult result1, TriggerResult result2) - throws Exception { - if (result1 != null) { - when(mockActual.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result1); - } - if (result2 != null) { - when(mockUntil.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result2); - } - tester.injectElements(element); - } - - @Test - public void testOnElementActualFires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.FIRE, TriggerResult.CONTINUE); - injectElement(2, TriggerResult.FIRE_AND_FINISH, TriggerResult.CONTINUE); - assertThat(tester.getResultSequence(), - contains(TriggerResult.FIRE, TriggerResult.FIRE_AND_FINISH)); - - // This should do nothing (we've already fired and finished) - injectElement(3, TriggerResult.FIRE, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getResultSequence(), - contains(TriggerResult.FIRE, TriggerResult.FIRE_AND_FINISH)); - - assertTrue(tester.isMarkedFinished(firstWindow)); - } - - @Test - public void testOnElementUntilFires() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - injectElement(2, TriggerResult.CONTINUE, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - - assertTrue(tester.isMarkedFinished(firstWindow)); - } + /** + * Tests that for {@code OrFinally(actual, ...)} when {@code actual} + * fires and finishes, the {@code OrFinally} also fires and finishes. + */ @Test - public void testOnElementUntilFiresAndFinishes() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); + public void testActualFiresAndFinishes() throws Exception { + tester = TriggerTester.forTrigger( + new OrFinallyTrigger<>( + AfterPane.elementCountAtLeast(2), + AfterPane.elementCountAtLeast(100)), + FixedWindows.of(Duration.millis(100))); - injectElement(2, TriggerResult.CONTINUE, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - assertTrue(tester.isMarkedFinished(firstWindow)); + // Not yet firing + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + assertFalse(tester.isMarkedFinished(window)); + + // The actual fires and finishes + tester.injectElements(2); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); } + /** + * Tests that for {@code OrFinally(actual, ...)} when {@code actual} + * fires but does not finish, the {@code OrFinally} also fires and also does not + * finish. + */ @Test - public void testOnTimerFinishesUntil() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE, TriggerResult.CONTINUE); - - // Timer fires for until, which says continue - when(mockUntil.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockActual.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.fireTimer(firstWindow, new Instant(11), TimeDomain.EVENT_TIME); - - injectElement(2, TriggerResult.FIRE, TriggerResult.CONTINUE); - - injectElement(3, TriggerResult.CONTINUE, TriggerResult.CONTINUE); + public void testActualFiresOnly() throws Exception { + tester = TriggerTester.forTrigger( + new OrFinallyTrigger<>( + Repeatedly.forever(AfterPane.elementCountAtLeast(2)), + AfterPane.elementCountAtLeast(100)), + FixedWindows.of(Duration.millis(100))); - // Timer fires for until, which says FIRE, so we fire and finish - when(mockUntil.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - tester.fireTimer(firstWindow, new Instant(12), TimeDomain.EVENT_TIME); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE_AND_FINISH)); - assertTrue(tester.isMarkedFinished(firstWindow)); + // Not yet firing + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + assertFalse(tester.isMarkedFinished(window)); + + // The actual fires but does not finish + tester.injectElements(2); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); + + // And again + tester.injectElements(3, 4); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); } + /** + * Tests that if the first trigger rewinds to be non-finished in the merged window, + * then it becomes the currently active trigger again, with real triggers. + */ @Test - public void testMergeActualFires() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); - - when(mockActual.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockUntil.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - - tester.injectElements(1, 12); + public void testShouldFireAfterMerge() throws Exception { + tester = TriggerTester.forTrigger( + AfterEach.inOrder( + AfterPane.elementCountAtLeast(5) + .orFinally(AfterWatermark.pastEndOfWindow()), + Repeatedly.forever(AfterPane.elementCountAtLeast(1))), + Sessions.withGapDuration(Duration.millis(10))); - when(mockActual.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.FIRE); - when(mockUntil.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.CONTINUE); + // Finished the orFinally in the first window + tester.injectElements(1); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + assertFalse(tester.shouldFire(firstWindow)); + tester.advanceInputWatermark(new Instant(11)); + assertTrue(tester.shouldFire(firstWindow)); + tester.fireIfShouldFire(firstWindow); + // Set up second window where it is not done tester.injectElements(5); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); + assertFalse(tester.shouldFire(secondWindow)); + + // Merge them, if the merged window were on the second trigger, it would be ready tester.mergeWindows(); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + assertFalse(tester.shouldFire(mergedWindow)); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE)); + // Now adding 3 more makes the main trigger ready to fire + tester.injectElements(1, 2, 3, 4, 5); + tester.mergeWindows(); + assertTrue(tester.shouldFire(mergedWindow)); } + /** + * Tests that for {@code OrFinally(actual, until)} when {@code actual} + * fires but does not finish, then {@code until} fires and finishes, the + * whole thing fires and finished. + */ @Test - public void testMergeUntilFires() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); - - when(mockActual.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - when(mockUntil.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(1, 12); + public void testActualFiresButUntilFinishes() throws Exception { + tester = TriggerTester.forTrigger( + new OrFinallyTrigger( + Repeatedly.forever(AfterPane.elementCountAtLeast(2)), + AfterPane.elementCountAtLeast(3)), + FixedWindows.of(Duration.millis(10))); - when(mockActual.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.CONTINUE); - when(mockUntil.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.FIRE_AND_FINISH); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - tester.injectElements(5); - tester.mergeWindows(); - - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - // the until fired during the merge - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(22)))); + // Before any firing + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + assertFalse(tester.isMarkedFinished(window)); + + // The actual fires but doesn't finish + tester.injectElements(2); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.isMarkedFinished(window)); + + // The until fires and finishes; the trigger is finished + tester.injectElements(3); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertTrue(tester.isMarkedFinished(window)); } @Test @@ -215,68 +191,6 @@ public void testFireDeadline() throws Exception { .getWatermarkThatGuaranteesFiring(window)); } - @Test - public void testOrFinallyRealTriggersFixedWindow() throws Exception { - // Test an orFinally with a composite trigger, and make sure it properly resets state, etc. - tester = TriggerTester.forTrigger(Repeatedly.forever( - // This element count should never fire because the orFinally fires sooner, every time - AfterPane.elementCountAtLeast(12) - .orFinally(AfterAll.of( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - AfterPane.elementCountAtLeast(5)))), - FixedWindows.of(Duration.millis(50))); - - // First, fire processing time then the 5 element - - tester.advanceProcessingTime(new Instant(0)); - tester.injectElements(0, 0, 1, 1); - tester.advanceProcessingTime(new Instant(6)); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - - tester.injectElements(1); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - // Then fire 6 new elements, then processing time - tester.clearResultSequence(); - tester.injectElements(2, 3, 4, 5, 2, 3); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - tester.clearResultSequence(); - tester.advanceProcessingTime(new Instant(15)); - - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - // Finally, fire 3 more elements and verify the base of the orFinally doesn't fire. - tester.clearResultSequence(); - tester.injectElements(1, 1, 1); - assertThat(tester.getResultSequence(), everyItem(equalTo(TriggerResult.CONTINUE))); - } - - @Test - public void testOrFinallyMergingWindowSomeFinished() throws Exception { - Duration windowDuration = Duration.millis(10); - tester = TriggerTester.forTrigger( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)) - .orFinally(AfterPane.elementCountAtLeast(5)), - Sessions.withGapDuration(windowDuration)); - - tester.advanceProcessingTime(new Instant(10)); - tester.injectElements( - 1, // in [1, 11), timer for 15 - 1, // in [1, 11) count = 1 - 2); // in [2, 12), timer for 16 - - // Enough data comes in for 2 that combined, we should fire - tester.injectElements(2, 2); - tester.mergeWindows(); - - // This fires, because the earliest element in [1, 12) arrived at time 10 - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE_AND_FINISH)); - - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - } - @Test public void testContinuation() throws Exception { OnceTrigger triggerA = AfterProcessingTime.pastFirstElementInPane(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java index 2888f134b5..f445b52565 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java @@ -20,11 +20,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -42,121 +41,58 @@ */ @RunWith(JUnit4.class) public class RepeatedlyTest { - @Mock private Trigger mockRepeated; + @Mock private Trigger mockTrigger; private SimpleTriggerTester tester; - private IntervalWindow firstWindow; - - public void setUp(WindowFn windowFn) throws Exception { - MockitoAnnotations.initMocks(this); - Trigger underTest = Repeatedly.forever(mockRepeated); - tester = TriggerTester.forTrigger( - underTest, windowFn); - firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); + private static Trigger.TriggerContext anyTriggerContext() { + return Mockito..TriggerContext>any(); } - private void injectElement(int element, TriggerResult result1) - throws Exception { - if (result1 != null) { - when(mockRepeated.onElement( - Mockito..OnElementContext>any())) - .thenReturn(result1); - } - - tester.injectElements(element); + public void setUp(WindowFn windowFn) throws Exception { + MockitoAnnotations.initMocks(this); + tester = TriggerTester.forTrigger(Repeatedly.forever(mockTrigger), windowFn); } + /** + * Tests that onElement correctly passes the data on to the subtrigger. + */ @Test public void testOnElement() throws Exception { setUp(FixedWindows.of(Duration.millis(10))); - - injectElement(1, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - injectElement(2, TriggerResult.FIRE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - injectElement(3, TriggerResult.FIRE_AND_FINISH); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - injectElement(4, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - assertFalse(tester.isMarkedFinished(firstWindow)); + tester.injectElements(37); + verify(mockTrigger).onElement(Mockito..OnElementContext>any()); } + /** + * Tests that the repeatedly is ready to fire whenever the subtrigger is ready. + */ @Test - public void testOnElementTimerFires() throws Exception { + public void testShouldFire() throws Exception { setUp(FixedWindows.of(Duration.millis(10))); - injectElement(1, TriggerResult.CONTINUE); - - when(mockRepeated.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE); - tester.fireTimer(firstWindow, new Instant(11), TimeDomain.EVENT_TIME); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - injectElement(2, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - when(mockRepeated.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE_AND_FINISH); - tester.fireTimer(firstWindow, new Instant(12), TimeDomain.EVENT_TIME); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - - injectElement(3, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - when(mockRepeated.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.fireTimer(firstWindow, new Instant(13), TimeDomain.EVENT_TIME); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - injectElement(4, TriggerResult.CONTINUE); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.CONTINUE)); - - when(mockRepeated.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE); - tester.fireTimer(firstWindow, new Instant(14), TimeDomain.EVENT_TIME); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + assertTrue(tester.shouldFire(new IntervalWindow(new Instant(0), new Instant(10)))); - assertThat(tester.getLatestResult(), equalTo(TriggerResult.FIRE)); - assertFalse(tester.isMarkedFinished(firstWindow)); + when(mockTrigger.shouldFire(Mockito..TriggerContext>any())) + .thenReturn(false); + assertFalse(tester.shouldFire(new IntervalWindow(new Instant(0), new Instant(10)))); } + /** + * Tests that the watermark that guarantees firing is that of the subtrigger. + */ @Test - public void testMerge() throws Exception { - setUp(Sessions.withGapDuration(Duration.millis(10))); - - when(mockRepeated.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.injectElements(1, 5); - - when(mockRepeated.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.FIRE_AND_FINISH); - - tester.mergeWindows(); + public void testFireDeadline() throws Exception { + setUp(FixedWindows.of(Duration.millis(10))); + IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); + Instant arbitraryInstant = new Instant(34957849); - assertThat(tester.getLatestMergeResult(), equalTo(MergeResult.FIRE)); - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(16)))); - } + when(mockTrigger.getWatermarkThatGuaranteesFiring(Mockito.any())) + .thenReturn(arbitraryInstant); - @Test - public void testFireDeadline() throws Exception { - BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - assertEquals(new Instant(9), - Repeatedly.forever(AfterWatermark.pastEndOfWindow()) - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(new Instant(9), Repeatedly.forever(AfterWatermark.pastEndOfWindow()) - .orFinally(AfterPane.elementCountAtLeast(1)) - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(new Instant(9), Repeatedly.forever(AfterPane.elementCountAtLeast(1)) - .orFinally(AfterWatermark.pastEndOfWindow()) - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - Repeatedly.forever(AfterPane.elementCountAtLeast(1)) - .orFinally(AfterPane.elementCountAtLeast(10)) - .getWatermarkThatGuaranteesFiring(window)); + assertThat( + Repeatedly.forever(mockTrigger).getWatermarkThatGuaranteesFiring(window), + equalTo(arbitraryInstant)); } @Test @@ -164,10 +100,29 @@ public void testContinuation() throws Exception { Trigger trigger = AfterProcessingTime.pastFirstElementInPane(); Trigger repeatedly = Repeatedly.forever(trigger); assertEquals( - Repeatedly.forever(trigger.getContinuationTrigger()), - repeatedly.getContinuationTrigger()); + Repeatedly.forever(trigger.getContinuationTrigger()), repeatedly.getContinuationTrigger()); assertEquals( Repeatedly.forever(trigger.getContinuationTrigger().getContinuationTrigger()), repeatedly.getContinuationTrigger().getContinuationTrigger()); } + + @Test + public void testShouldFireAfterMerge() throws Exception { + tester = TriggerTester.forTrigger( + Repeatedly.forever(AfterPane.elementCountAtLeast(2)), + Sessions.withGapDuration(Duration.millis(10))); + + tester.injectElements(1); + IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); + assertFalse(tester.shouldFire(firstWindow)); + + tester.injectElements(5); + IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); + assertFalse(tester.shouldFire(secondWindow)); + + // Merge them, if the merged window were on the second trigger, it would be ready + tester.mergeWindows(); + IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); + assertTrue(tester.shouldFire(mergedWindow)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java index 4d4b4dc204..b15a6037d7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java @@ -67,19 +67,10 @@ protected TestTimeTrigger newWith(List> t } @Override - public TriggerResult onElement(OnElementContext c) throws Exception { - return null; - } - - @Override - public MergeResult onMerge(OnMergeContext c) throws Exception { - return null; - } + public void onElement(OnElementContext c) throws Exception { } @Override - public TriggerResult onTimer(OnTimerContext c) throws Exception { - return null; - } + public void onMerge(OnMergeContext c) throws Exception { } @Override protected Trigger getContinuationTrigger( @@ -92,5 +83,12 @@ public Instant getWatermarkThatGuaranteesFiring(IntervalWindow window) { return null; } + @Override + public boolean shouldFire(TriggerContext context) throws Exception { + return false; + } + + @Override + public void onOnlyFiring(TriggerContext context) throws Exception { } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java index 84ecce58aa..ddff33fbda 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java @@ -58,19 +58,10 @@ private Trigger1(List> subTriggers) { } @Override - public Trigger.TriggerResult onElement(Trigger.OnElementContext c) { - return null; - } + public void onElement(Trigger.OnElementContext c) { } @Override - public Trigger.MergeResult onMerge(Trigger.OnMergeContext c) { - return null; - } - - @Override - public Trigger.TriggerResult onTimer(Trigger.OnTimerContext c) { - return null; - } + public void onMerge(Trigger.OnMergeContext c) { } @Override protected Trigger getContinuationTrigger( @@ -82,6 +73,14 @@ protected Trigger getContinuationTrigger( public Instant getWatermarkThatGuaranteesFiring(IntervalWindow window) { return null; } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return false; + } + + @Override + public void onFire(Trigger.TriggerContext context) throws Exception { } } private static class Trigger2 extends Trigger { @@ -91,19 +90,10 @@ private Trigger2(List> subTriggers) { } @Override - public Trigger.TriggerResult onElement(Trigger.OnElementContext c) { - return null; - } + public void onElement(Trigger.OnElementContext c) { } @Override - public Trigger.MergeResult onMerge(Trigger.OnMergeContext c) { - return null; - } - - @Override - public Trigger.TriggerResult onTimer(Trigger.OnTimerContext c) { - return null; - } + public void onMerge(Trigger.OnMergeContext c) { } @Override protected Trigger getContinuationTrigger( @@ -115,5 +105,13 @@ protected Trigger getContinuationTrigger( public Instant getWatermarkThatGuaranteesFiring(IntervalWindow window) { return null; } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) throws Exception { + return false; + } + + @Override + public void onFire(Trigger.TriggerContext context) throws Exception { } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java index 1accd76248..25d07d62d7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java @@ -45,7 +45,7 @@ public void setUp() { } @Test - public void testFiringTimers() { + public void testFiringTimers() throws Exception { BatchTimerInternals underTest = new BatchTimerInternals(new Instant(0)); TimerData processingTime1 = TimerData.of(NS1, new Instant(19), TimeDomain.PROCESSING_TIME); TimerData processingTime2 = TimerData.of(NS1, new Instant(29), TimeDomain.PROCESSING_TIME); @@ -74,7 +74,7 @@ public void testFiringTimers() { } @Test - public void testTimerOrdering() { + public void testTimerOrdering() throws Exception { BatchTimerInternals underTest = new BatchTimerInternals(new Instant(0)); TimerData watermarkTime1 = TimerData.of(NS1, new Instant(19), TimeDomain.EVENT_TIME); TimerData processingTime1 = TimerData.of(NS1, new Instant(19), TimeDomain.PROCESSING_TIME); @@ -98,7 +98,7 @@ public void testTimerOrdering() { } @Test - public void testDeduplicate() { + public void testDeduplicate() throws Exception { BatchTimerInternals underTest = new BatchTimerInternals(new Instant(0)); TimerData watermarkTime = TimerData.of(NS1, new Instant(19), TimeDomain.EVENT_TIME); TimerData processingTime = TimerData.of(NS1, new Instant(19), TimeDomain.PROCESSING_TIME); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java index cafd14a303..7b8466a5fa 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java @@ -94,23 +94,10 @@ protected StubTrigger(Trigger... subTriggers) { } @Override - public TriggerResult onElement( - OnElementContext c) throws Exception { - return TriggerResult.CONTINUE; - } - - @Override - public MergeResult onMerge(OnMergeContext c) - throws Exception { - return MergeResult.CONTINUE; - } + public void onElement(OnElementContext c) throws Exception { } @Override - public TriggerResult onTimer( - OnTimerContext c) - throws Exception { - return TriggerResult.CONTINUE; - } + public void onMerge(OnMergeContext c) throws Exception { } @Override public void clear(TriggerContext c) throws Exception { @@ -131,5 +118,13 @@ public Trigger getContinuationTrigger( List> continuationTriggers) { return this; } + + @Override + public boolean shouldFire(TriggerContext c) { + return false; + } + + @Override + public void onFire(TriggerContext c) { } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index 854a89ae00..c68d67670c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -19,14 +19,14 @@ import static com.google.cloud.dataflow.sdk.WindowMatchers.isSingleWindowedValue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.WindowMatchers; @@ -45,13 +45,10 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import org.hamcrest.Matchers; import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Before; @@ -78,6 +75,13 @@ public class ReduceFnRunnerTest { private Trigger mockTrigger; private IntervalWindow firstWindow; + private static Trigger.TriggerContext anyTriggerContext() { + return Mockito..TriggerContext>any(); + } + private static Trigger.OnElementContext anyElementContext() { + return Mockito..OnElementContext>any(); + } + @Before public void setUp() { MockitoAnnotations.initMocks(this); @@ -85,13 +89,26 @@ public void setUp() { firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); } - private void injectElement(ReduceFnTester tester, int element, - TriggerResult result) throws Exception { - when(mockTrigger.onElement(Mockito..OnElementContext>any())) - .thenReturn(result); + private void injectElement(ReduceFnTester tester, int element) + throws Exception { + doNothing().when(mockTrigger).onElement(anyElementContext()); tester.injectElements(TimestampedValue.of(element, new Instant(element))); } + private void triggerShouldFinish(Trigger mockTrigger) throws Exception { + doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocation) throws Exception { + @SuppressWarnings("unchecked") + Trigger.TriggerContext context = + (Trigger.TriggerContext) invocation.getArguments()[0]; + context.trigger().setFinished(true); + return null; + } + }) + .when(mockTrigger).onFire(anyTriggerContext()); + } + @Test public void testOnElementBufferingDiscarding() throws Exception { // Test basic execution of a trigger using a non-combining window set and discarding mode. @@ -99,22 +116,25 @@ public void testOnElementBufferingDiscarding() throws Exception { ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); - injectElement(tester, 1, TriggerResult.CONTINUE); - injectElement(tester, 2, TriggerResult.FIRE); - - injectElement(tester, 3, TriggerResult.FIRE_AND_FINISH); - - // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 4, null); - - assertThat( - tester.extractOutput(), - Matchers.contains( - isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2), 1, 0, 10), - isSingleWindowedValue(Matchers.containsInAnyOrder(3), 3, 0, 10))); + // Pane of {1, 2} + injectElement(tester, 1); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 2); + assertThat(tester.extractOutput(), + contains(isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10))); + + // Pane of just 3, and finish + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 3); + assertThat(tester.extractOutput(), + contains(isSingleWindowedValue(containsInAnyOrder(3), 3, 0, 10))); assertTrue(tester.isMarkedFinished(firstWindow)); tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); + // This element shouldn't be seen, because the trigger has finished + injectElement(tester, 4); + assertEquals(1, tester.getElementsDroppedDueToClosedWindow()); assertEquals(0, tester.getElementsDroppedDueToLateness()); } @@ -126,18 +146,25 @@ public void testOnElementBufferingAccumulating() throws Exception { ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100)); - injectElement(tester, 1, TriggerResult.CONTINUE); - injectElement(tester, 2, TriggerResult.FIRE); - injectElement(tester, 3, TriggerResult.FIRE_AND_FINISH); + injectElement(tester, 1); + + // Fires {1, 2} + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 2); + + // Fires {1, 2, 3} because we are in accumulating mode + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 3); // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 4, null); + injectElement(tester, 4); assertThat( tester.extractOutput(), - Matchers.contains( - isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2), 1, 0, 10), - isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2, 3), 3, 0, 10))); + contains( + isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10), + isSingleWindowedValue(containsInAnyOrder(1, 2, 3), 3, 0, 10))); assertTrue(tester.isMarkedFinished(firstWindow)); tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); } @@ -149,18 +176,23 @@ public void testOnElementCombiningDiscarding() throws Exception { FixedWindows.of(Duration.millis(10)), mockTrigger, AccumulationMode.DISCARDING_FIRED_PANES, new Sum.SumIntegerFn().asKeyedFn(), VarIntCoder.of(), Duration.millis(100)); - injectElement(tester, 2, TriggerResult.CONTINUE); - injectElement(tester, 3, TriggerResult.FIRE); - injectElement(tester, 4, TriggerResult.FIRE_AND_FINISH); + injectElement(tester, 2); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 3); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 4); // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 6, null); + injectElement(tester, 6); assertThat( tester.extractOutput(), - Matchers.contains( - isSingleWindowedValue(Matchers.equalTo(5), 2, 0, 10), - isSingleWindowedValue(Matchers.equalTo(4), 4, 0, 10))); + contains( + isSingleWindowedValue(equalTo(5), 2, 0, 10), + isSingleWindowedValue(equalTo(4), 4, 0, 10))); assertTrue(tester.isMarkedFinished(firstWindow)); tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); } @@ -173,18 +205,23 @@ public void testOnElementCombiningAccumulating() throws Exception { AccumulationMode.ACCUMULATING_FIRED_PANES, new Sum.SumIntegerFn().asKeyedFn(), VarIntCoder.of(), Duration.millis(100)); - injectElement(tester, 1, TriggerResult.CONTINUE); - injectElement(tester, 2, TriggerResult.FIRE); - injectElement(tester, 3, TriggerResult.FIRE_AND_FINISH); + injectElement(tester, 1); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 2); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 3); // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 4, null); + injectElement(tester, 4); assertThat( tester.extractOutput(), - Matchers.contains( - isSingleWindowedValue(Matchers.equalTo(3), 1, 0, 10), - isSingleWindowedValue(Matchers.equalTo(6), 3, 0, 10))); + contains( + isSingleWindowedValue(equalTo(3), 1, 0, 10), + isSingleWindowedValue(equalTo(6), 3, 0, 10))); assertTrue(tester.isMarkedFinished(firstWindow)); tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); } @@ -201,11 +238,19 @@ public void testWatermarkHoldAndLateData() throws Exception { assertEquals(null, tester.getOutputWatermark()); // All on time data, verify watermark hold. - injectElement(tester, 1, TriggerResult.CONTINUE); - injectElement(tester, 3, TriggerResult.CONTINUE); + injectElement(tester, 1); + injectElement(tester, 3); assertEquals(new Instant(1), tester.getWatermarkHold()); - injectElement(tester, 2, TriggerResult.FIRE); - assertEquals(1, tester.getOutputSize()); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 2); + List>> output = tester.extractOutput(); + assertThat(output, contains( + isSingleWindowedValue(containsInAnyOrder(1, 2, 3), + 1, // timestamp + 0, // window start + 10))); // window end + assertThat(output.get(0).getPane(), + equalTo(PaneInfo.createPane(true, false, Timing.EARLY, 0, -1))); // Holding for the end-of-window transition. assertEquals(new Instant(9), tester.getWatermarkHold()); @@ -213,51 +258,90 @@ public void testWatermarkHoldAndLateData() throws Exception { assertEquals(0, tester.getElementsDroppedDueToLateness()); assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - // Input watermark -> 4 + // Input watermark -> 4, output watermark should advance that far as well tester.advanceInputWatermark(new Instant(4)); assertEquals(new Instant(4), tester.getOutputWatermark()); // Some late, some on time. Verify that we only hold to the minimum of on-time. - injectElement(tester, 2, TriggerResult.CONTINUE); - injectElement(tester, 3, TriggerResult.CONTINUE); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); + tester.advanceInputWatermark(new Instant(4)); + injectElement(tester, 2); + injectElement(tester, 3); assertEquals(new Instant(9), tester.getWatermarkHold()); - injectElement(tester, 5, TriggerResult.CONTINUE); + injectElement(tester, 5); assertEquals(new Instant(5), tester.getWatermarkHold()); - injectElement(tester, 4, TriggerResult.FIRE); - assertEquals(2, tester.getOutputSize()); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 4); + output = tester.extractOutput(); + assertThat(output, + contains( + isSingleWindowedValue(containsInAnyOrder( + 1, 2, 3, // earlier firing + 2, 3, 4, 5), // new elements + 4, // timestamp + 0, // window start + 10))); // window end + assertThat(output.get(0).getPane(), + equalTo(PaneInfo.createPane(false, false, Timing.EARLY, 1, -1))); // All late -- output at end of window timestamp. - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - // Input watermark -> 8 + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); tester.advanceInputWatermark(new Instant(8)); - assertEquals(new Instant(8), tester.getOutputWatermark()); - injectElement(tester, 6, TriggerResult.CONTINUE); - injectElement(tester, 5, TriggerResult.CONTINUE); + injectElement(tester, 6); + injectElement(tester, 5); assertEquals(new Instant(9), tester.getWatermarkHold()); - injectElement(tester, 4, TriggerResult.CONTINUE); + injectElement(tester, 4); - // This is behind both the input and output watermarks, but will still make it - // into an ON_TIME pane. - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE); - // Input watermark -> 10 + // Fire the ON_TIME pane + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); tester.advanceInputWatermark(new Instant(10)); - assertEquals(3, tester.getOutputSize()); - assertEquals(new Instant(10), tester.getOutputWatermark()); - injectElement(tester, 8, TriggerResult.CONTINUE); + // Output time is end of the window, because all the new data was late, but the pane + // is the ON_TIME pane. + output = tester.extractOutput(); + assertThat(output, + contains(isSingleWindowedValue( + containsInAnyOrder(1, 2, 3, // earlier firing + 2, 3, 4, 5, // earlier firing + 4, 5, 6), // new elements + 9, // timestamp + 0, // window start + 10))); // window end + assertThat(output.get(0).getPane(), + equalTo(PaneInfo.createPane(false, false, Timing.ON_TIME, 2, 0))); + + // This is "pending" at the time the watermark makes it way-late. + // Because we're about to expire the window, we output it. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); + injectElement(tester, 8); assertEquals(0, tester.getElementsDroppedDueToLateness()); assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - // All very late -- gets dropped. - // Input watermark -> 50 + // Exceed the GC limit, triggering the last pane to be fired tester.advanceInputWatermark(new Instant(50)); + output = tester.extractOutput(); + // Output time is still end of the window, because the new data (8) was behind + // the output watermark. + assertThat(output, + contains(isSingleWindowedValue( + containsInAnyOrder(1, 2, 3, // earlier firing + 2, 3, 4, 5, // earlier firing + 4, 5, 6, // earlier firing + 8), // new element prior to window becoming expired + 9, // timestamp + 0, // window start + 10))); // window end + assertThat( + output.get(0).getPane(), + equalTo(PaneInfo.createPane(false, true, Timing.LATE, 3, 1))); + + // All very late -- gets dropped, because the window is expired + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); assertEquals(new Instant(50), tester.getOutputWatermark()); assertEquals(null, tester.getWatermarkHold()); - injectElement(tester, 22, TriggerResult.FIRE); - assertEquals(4, tester.getOutputSize()); + injectElement(tester, 2); assertEquals(null, tester.getWatermarkHold()); + assertThat(tester.extractOutput(), emptyIterable()); assertEquals(1, tester.getElementsDroppedDueToLateness()); assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); @@ -266,36 +350,6 @@ public void testWatermarkHoldAndLateData() throws Exception { tester.fireTimer(new IntervalWindow(new Instant(0), new Instant(10)), new Instant(12), TimeDomain.EVENT_TIME); - List>> output = tester.extractOutput(); - assertThat( - output, Matchers.contains( - isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2, 3), 1, 0, 10), - isSingleWindowedValue( - Matchers.containsInAnyOrder(1, 2, 3, 2, 3, 4, 5), 4, 0, 10), - // Output time is end of the window, because all the new data was late - isSingleWindowedValue( - Matchers.containsInAnyOrder(1, 2, 3, 2, 3, 4, 5, 4, 5, 6), 9, 0, 10), - // Output time is still end of the window, because the new data (8) was behind - // the output watermark. - isSingleWindowedValue( - Matchers.containsInAnyOrder(1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 8), 9, 0, 10))); - - assertThat( - output.get(0).getPane(), - Matchers.equalTo(PaneInfo.createPane(true, false, Timing.EARLY, 0, -1))); - - assertThat( - output.get(1).getPane(), - Matchers.equalTo(PaneInfo.createPane(false, false, Timing.EARLY, 1, -1))); - - assertThat( - output.get(2).getPane(), - Matchers.equalTo(PaneInfo.createPane(false, false, Timing.ON_TIME, 2, 0))); - - assertThat( - output.get(3).getPane(), - Matchers.equalTo(PaneInfo.createPane(false, true, Timing.LATE, 3, 1))); - // And because we're past the end of window + allowed lateness, everything should be cleaned up. assertFalse(tester.isMarkedFinished(firstWindow)); tester.assertHasOnlyGlobalAndFinishedSetsFor(); @@ -307,40 +361,35 @@ public void testPaneInfoAllStates() throws Exception { ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); - tester.advanceInputWatermark(new Instant(0)); - injectElement(tester, 1, TriggerResult.FIRE); - assertThat( - tester.extractOutput(), - Matchers.contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, false, Timing.EARLY)))); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 1); + assertThat(tester.extractOutput(), contains( + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, false, Timing.EARLY)))); - injectElement(tester, 2, TriggerResult.FIRE); - assertThat( - tester.extractOutput(), - Matchers.contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, false, Timing.EARLY, 1, -1)))); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 2); + assertThat(tester.extractOutput(), contains( + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.EARLY, 1, -1)))); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); tester.advanceInputWatermark(new Instant(15)); - injectElement(tester, 3, TriggerResult.FIRE); - assertThat( - tester.extractOutput(), - Matchers.contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, false, Timing.EARLY, 2, -1)))); - - injectElement(tester, 4, TriggerResult.FIRE); - assertThat( - tester.extractOutput(), - Matchers.contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, false, Timing.EARLY, 3, -1)))); - - injectElement(tester, 5, TriggerResult.FIRE_AND_FINISH); - assertThat( - tester.extractOutput(), - Matchers.contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, true, Timing.EARLY, 4, -1)))); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 3); + assertThat(tester.extractOutput(), contains( + // This is late, because the trigger wasn't waiting for AfterWatermark + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.EARLY, 2, -1)))); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 4); + assertThat(tester.extractOutput(), contains( + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.EARLY, 3, -1)))); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 5); + assertThat(tester.extractOutput(), contains( + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.EARLY, 4, -1)))); } @Test @@ -361,12 +410,12 @@ public void testPaneInfoAllStatesAfterWatermark() throws Exception { List>> output = tester.extractOutput(); assertThat( output, - Matchers.contains(WindowMatchers.valueWithPaneInfo( + contains(WindowMatchers.valueWithPaneInfo( PaneInfo.createPane(true, false, Timing.EARLY, 0, -1)))); assertThat( output, - Matchers.contains( - WindowMatchers.isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2), 1, 0, 10))); + contains( + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10))); tester.advanceInputWatermark(new Instant(50)); @@ -375,24 +424,24 @@ public void testPaneInfoAllStatesAfterWatermark() throws Exception { output = tester.extractOutput(); assertThat( output, - Matchers.contains(WindowMatchers.valueWithPaneInfo( + contains(WindowMatchers.valueWithPaneInfo( PaneInfo.createPane(false, false, Timing.ON_TIME, 1, 0)))); assertThat( output, - Matchers.contains( - WindowMatchers.isSingleWindowedValue(Matchers.emptyIterable(), 9, 0, 10))); + contains( + WindowMatchers.isSingleWindowedValue(emptyIterable(), 9, 0, 10))); // We should get the final pane even though it is empty. tester.advanceInputWatermark(new Instant(150)); output = tester.extractOutput(); assertThat( output, - Matchers.contains( + contains( WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 2, 1)))); assertThat( output, - Matchers.contains( - WindowMatchers.isSingleWindowedValue(Matchers.emptyIterable(), 9, 0, 10))); + contains( + WindowMatchers.isSingleWindowedValue(emptyIterable(), 9, 0, 10))); } @Test @@ -413,12 +462,12 @@ public void testPaneInfoAllStatesAfterWatermarkAccumulating() throws Exception { List>> output = tester.extractOutput(); assertThat( output, - Matchers.contains(WindowMatchers.valueWithPaneInfo( + contains(WindowMatchers.valueWithPaneInfo( PaneInfo.createPane(true, false, Timing.EARLY, 0, -1)))); assertThat( output, - Matchers.contains( - WindowMatchers.isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2), 1, 0, 10))); + contains( + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10))); tester.advanceInputWatermark(new Instant(50)); @@ -427,24 +476,24 @@ public void testPaneInfoAllStatesAfterWatermarkAccumulating() throws Exception { output = tester.extractOutput(); assertThat( output, - Matchers.contains(WindowMatchers.valueWithPaneInfo( + contains(WindowMatchers.valueWithPaneInfo( PaneInfo.createPane(false, false, Timing.ON_TIME, 1, 0)))); assertThat( output, - Matchers.contains( - WindowMatchers.isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2), 9, 0, 10))); + contains( + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); // We should get the final pane even though it is empty. tester.advanceInputWatermark(new Instant(150)); output = tester.extractOutput(); assertThat( output, - Matchers.contains( + contains( WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 2, 1)))); assertThat( output, - Matchers.contains( - WindowMatchers.isSingleWindowedValue(Matchers.containsInAnyOrder(1, 2), 9, 0, 10))); + contains( + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); } @Test @@ -459,16 +508,18 @@ public void testPaneInfoFinalAndOnTime() throws Exception { .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); tester.advanceInputWatermark(new Instant(0)); + + // Should trigger due to element count tester.injectElements( TimestampedValue.of(1, new Instant(1)), TimestampedValue.of(2, new Instant(2))); assertThat( tester.extractOutput(), - Matchers.contains(WindowMatchers.valueWithPaneInfo( + contains(WindowMatchers.valueWithPaneInfo( PaneInfo.createPane(true, false, Timing.EARLY, 0, -1)))); tester.advanceInputWatermark(new Instant(150)); - assertThat(tester.extractOutput(), Matchers.contains( + assertThat(tester.extractOutput(), contains( WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.ON_TIME, 1, 0)))); } @@ -479,11 +530,11 @@ public void testPaneInfoSkipToFinish() throws Exception { AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); tester.advanceInputWatermark(new Instant(0)); - injectElement(tester, 1, TriggerResult.FIRE_AND_FINISH); - assertThat( - tester.extractOutput(), - Matchers.contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, true, Timing.EARLY)))); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 1); + assertThat(tester.extractOutput(), contains( + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, true, Timing.EARLY)))); } @Test @@ -493,11 +544,11 @@ public void testPaneInfoSkipToNonSpeculativeAndFinish() throws Exception { AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); tester.advanceInputWatermark(new Instant(15)); - injectElement(tester, 1, TriggerResult.FIRE_AND_FINISH); - assertThat( - tester.extractOutput(), - Matchers.contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, true, Timing.LATE)))); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 1); + assertThat(tester.extractOutput(), contains( + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, true, Timing.LATE)))); } @Test @@ -509,24 +560,24 @@ public void testMergeBeforeFinalizing() throws Exception { AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(0)); // All on time data, verify watermark hold. - when(mockTrigger.onMerge(Mockito..OnMergeContext>any())) - .thenReturn(MergeResult.CONTINUE); - when(mockTrigger.onElement(Mockito..OnElementContext>any())) - .thenReturn(TriggerResult.CONTINUE, TriggerResult.CONTINUE); + // These two windows should pre-merge immediately to [1, 20) tester.injectElements( - TimestampedValue.of(1, new Instant(1)), TimestampedValue.of(10, new Instant(10))); - - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); + TimestampedValue.of(1, new Instant(1)), // in [1, 11) + TimestampedValue.of(10, new Instant(10))); // in [10, 20) + // And this should fire the end-of-window timer tester.advanceInputWatermark(new Instant(100)); List>> output = tester.extractOutput(); - assertThat(output.size(), Matchers.equalTo(1)); - assertThat(output.get(0), isSingleWindowedValue(Matchers.containsInAnyOrder(1, 10), 1, 1, 20)); + assertThat(output.size(), equalTo(1)); + assertThat(output.get(0), + isSingleWindowedValue(containsInAnyOrder(1, 10), + 1, // timestamp + 1, // window start + 20)); // window end assertThat( output.get(0).getPane(), - Matchers.equalTo(PaneInfo.createPane(true, true, Timing.EARLY, 0, 0))); + equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); } /** @@ -605,7 +656,7 @@ public void testDropDataMultipleWindowsFinishedTrigger() throws Exception { } @Test - public void testIdempotentEmptyPanes() throws Exception { + public void testIdempotentEmptyPanesDiscarding() throws Exception { // Test uninteresting (empty) panes don't increment the index or otherwise // modify PaneInfo. ReduceFnTester, IntervalWindow> tester = @@ -613,23 +664,22 @@ public void testIdempotentEmptyPanes() throws Exception { AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); // Inject a couple of on-time elements and fire at the window end. - injectElement(tester, 1, TriggerResult.CONTINUE); - injectElement(tester, 2, TriggerResult.CONTINUE); - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); + injectElement(tester, 1); + injectElement(tester, 2); tester.advanceInputWatermark(new Instant(12)); - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE); + // Fire the on-time pane + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); - // Fire another timer (with no data, so it's an uninteresting pane). - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE); + // Fire another timer (with no data, so it's an uninteresting pane that should not be output). + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); // Finish it off with another datum. - injectElement(tester, 3, TriggerResult.FIRE_AND_FINISH); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 3); // The intermediate trigger firing shouldn't result in any output. List>> output = tester.extractOutput(); @@ -659,37 +709,36 @@ public void testIdempotentEmptyPanesAccumulating() throws Exception { AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100)); // Inject a couple of on-time elements and fire at the window end. - injectElement(tester, 1, TriggerResult.CONTINUE); - injectElement(tester, 2, TriggerResult.CONTINUE); - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.CONTINUE); + injectElement(tester, 1); + injectElement(tester, 2); tester.advanceInputWatermark(new Instant(12)); - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE); + // Trigger the on-time pane + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); + List>> output = tester.extractOutput(); + assertThat(output.size(), equalTo(1)); + assertThat(output.get(0), isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10)); + assertThat(output.get(0).getPane(), + equalTo(PaneInfo.createPane(true, false, Timing.ON_TIME, 0, 0))); - // Fire another timer (with no data, so it's an uninteresting pane). - when(mockTrigger.onTimer(Mockito..OnTimerContext>any())) - .thenReturn(TriggerResult.FIRE); + // Fire another timer with no data; the empty pane should not be output even though the + // trigger is ready to fire + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); + assertThat(tester.extractOutput().size(), equalTo(0)); - // Finish it off with another datum. - injectElement(tester, 3, TriggerResult.FIRE_AND_FINISH); - - // The intermediate trigger firing shouldn't result in any output. - List>> output = tester.extractOutput(); - assertThat(output.size(), equalTo(2)); - - // The on-time pane is as expected. - assertThat(output.get(0), isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10)); - assertThat( - output.get(0).getPane(), equalTo(PaneInfo.createPane(true, false, Timing.ON_TIME, 0, 0))); + // Finish it off with another datum, which is late + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 3); + output = tester.extractOutput(); + assertThat(output.size(), equalTo(1)); // The late pane has the correct indices. - assertThat(output.get(1).getValue(), containsInAnyOrder(1, 2, 3)); - assertThat( - output.get(1).getPane(), equalTo(PaneInfo.createPane(false, true, Timing.LATE, 1, 1))); + assertThat(output.get(0).getValue(), containsInAnyOrder(1, 2, 3)); + assertThat(output.get(0).getPane(), + equalTo(PaneInfo.createPane(false, true, Timing.LATE, 1, 1))); assertTrue(tester.isMarkedFinished(firstWindow)); tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); @@ -698,21 +747,6 @@ public void testIdempotentEmptyPanesAccumulating() throws Exception { assertEquals(0, tester.getElementsDroppedDueToLateness()); } - private class ResultCaptor implements Answer { - private T result = null; - - public T get() { - return result; - } - - @Override - @SuppressWarnings("unchecked") - public T answer(InvocationOnMock invocationOnMock) throws Throwable { - result = (T) invocationOnMock.callRealMethod(); - return result; - } - } - /** * Test that we receive an empty on-time pane when an or-finally waiting for the watermark fires. * Specifically, verify the proper triggerings and pane-info of a typical speculative/on-time/late @@ -737,12 +771,17 @@ public void testEmptyOnTimeFromOrFinally() throws Exception { tester.advanceInputWatermark(new Instant(0)); tester.advanceProcessingTime(new Instant(0)); - tester.injectElements(TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(1, new Instant(3)), TimestampedValue.of(1, new Instant(7)), + // Processing time timer for 5 + tester.injectElements( + TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(1, new Instant(3)), + TimestampedValue.of(1, new Instant(7)), TimestampedValue.of(1, new Instant(5))); + // Should fire early pane tester.advanceProcessingTime(new Instant(6)); + // Should fire empty on time pane tester.advanceInputWatermark(new Instant(11)); List> output = tester.extractOutput(); assertEquals(2, output.size()); @@ -838,29 +877,4 @@ public void testProcessingTime() throws Exception { output.get(3), WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 3, 2))); } - - @Test - public void testMultipleTimerTypes() throws Exception { - Trigger trigger = spy(Repeatedly.forever(AfterFirst.of( - AfterProcessingTime.pastFirstElementInPane().plusDelayOf( - Duration.millis(10)), - AfterWatermark.pastEndOfWindow()))); - - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), trigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.standardDays(1)); - - tester.injectElements(TimestampedValue.of(1, new Instant(1))); - - ResultCaptor result = new ResultCaptor<>(); - doAnswer(result) - .when(trigger) - .onTimer(Mockito..OnTimerContext>any()); - tester.advanceInputWatermark(new Instant(1000)); - assertEquals(TriggerResult.FIRE, result.get()); - - tester.advanceProcessingTime(Instant.now().plus(Duration.millis(10))); - // Verify that the only onTimer call was the one from advancing the watermark. - verify(trigger).onTimer(Mockito..OnTimerContext>any()); - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java index 4ff5f620f8..4b3a77ce61 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java @@ -15,12 +15,15 @@ */ package com.google.cloud.dataflow.sdk.util; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import org.joda.time.Duration; +import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -37,17 +40,19 @@ public static ReshuffleTrigger forTest() { } @Test - public void testOnElement() { - assertEquals(TriggerResult.FIRE, forTest().onElement(null)); + public void testShouldFire() throws Exception { + TriggerTester tester = TriggerTester.forTrigger( + new ReshuffleTrigger(), FixedWindows.of(Duration.millis(100))); + IntervalWindow arbitraryWindow = new IntervalWindow(new Instant(300), new Instant(400)); + assertTrue(tester.shouldFire(arbitraryWindow)); } @Test - public void testOnMerge() { - assertEquals(MergeResult.CONTINUE, forTest().onMerge(null)); - } - - @Test - public void testOnTimer() { - assertEquals(TriggerResult.CONTINUE, forTest().onTimer(null)); + public void testOnTimer() throws Exception { + TriggerTester tester = TriggerTester.forTrigger( + new ReshuffleTrigger(), FixedWindows.of(Duration.millis(100))); + IntervalWindow arbitraryWindow = new IntervalWindow(new Instant(100), new Instant(200)); + tester.fireIfShouldFire(arbitraryWindow); + assertFalse(tester.isMarkedFinished(arbitraryWindow)); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index 6de9382041..0c362e6438 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -25,8 +25,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergeResult; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerResult; import com.google.cloud.dataflow.sdk.transforms.windowing.TriggerBuilder; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.ActiveWindowSet.MergeCallback; @@ -44,13 +42,12 @@ import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.base.MoreObjects; import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import org.joda.time.Duration; import org.joda.time.Instant; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; @@ -78,8 +75,8 @@ public class TriggerTester { public static class SimpleTriggerTester extends TriggerTester { - private SimpleTriggerTester(WindowingStrategy wildcardStrategy) throws Exception { - super(wildcardStrategy); + private SimpleTriggerTester(WindowingStrategy windowingStrategy) throws Exception { + super(windowingStrategy); } public void injectElements(int... values) throws Exception { @@ -90,17 +87,20 @@ public void injectElements(int... values) throws Exception { } injectElements(timestampedValues); } + + public SimpleTriggerTester withAllowedLateness(Duration allowedLateness) throws Exception { + return new SimpleTriggerTester<>( + windowingStrategy.withAllowedLateness(allowedLateness)); + } } + protected final WindowingStrategy windowingStrategy; + private final TestInMemoryStateInternals stateInternals = new TestInMemoryStateInternals(); private final TestTimerInternals timerInternals = new TestTimerInternals(); private final TriggerContextFactory contextFactory; - private final WindowFn windowFn; private final ActiveWindowSet activeWindows; - private final List resultSequence; - private Trigger.TriggerResult latestResult; - private Trigger.MergeResult latestMergeResult; /** * An {@link ExecutableTrigger} built from the {@link Trigger} or {@link TriggerBuilder} @@ -114,8 +114,9 @@ public void injectElements(int... values) throws Exception { private final Map finishedSets; public static SimpleTriggerTester forTrigger( - TriggerBuilder trigger, WindowFn windowFn) throws Exception { - WindowingStrategy strategy = + TriggerBuilder trigger, WindowFn windowFn) + throws Exception { + WindowingStrategy windowingStrategy = WindowingStrategy.of(windowFn).withTrigger(trigger.buildTrigger()) // Merging requires accumulation mode or early firings can break up a session. // Not currently an issue with the tester (because we never GC) but we don't want @@ -124,12 +125,12 @@ public static SimpleTriggerTester forTrigger( ? AccumulationMode.DISCARDING_FIRED_PANES : AccumulationMode.ACCUMULATING_FIRED_PANES); - return new SimpleTriggerTester<>(strategy); + return new SimpleTriggerTester<>(windowingStrategy); } - public static TriggerTester forAdvancedTrigger( - TriggerBuilder trigger, WindowFn windowFn) throws Exception { - WindowingStrategy strategy = + public static TriggerTester forAdvancedTrigger( + TriggerBuilder trigger, WindowFn windowFn) throws Exception { + WindowingStrategy strategy = WindowingStrategy.of(windowFn).withTrigger(trigger.buildTrigger()) // Merging requires accumulation mode or early firings can break up a session. // Not currently an issue with the tester (because we never GC) but we don't want @@ -141,13 +142,10 @@ public static TriggerTester forAdv return new TriggerTester<>(strategy); } - protected TriggerTester(WindowingStrategy wildcardStrategy) throws Exception { - @SuppressWarnings("unchecked") - WindowingStrategy objectStrategy = (WindowingStrategy) wildcardStrategy; - - this.windowFn = objectStrategy.getWindowFn(); - this.executableTrigger = wildcardStrategy.getTrigger(); - this.resultSequence = new ArrayList<>(); + protected TriggerTester(WindowingStrategy windowingStrategy) throws Exception { + this.windowingStrategy = windowingStrategy; + this.windowFn = windowingStrategy.getWindowFn(); + this.executableTrigger = windowingStrategy.getTrigger(); this.finishedSets = new HashMap<>(); this.activeWindows = @@ -156,52 +154,7 @@ protected TriggerTester(WindowingStrategy wildcardStrategy) throws Excepti : new MergingActiveWindowSet(windowFn, stateInternals); this.contextFactory = - new TriggerContextFactory<>(objectStrategy, stateInternals, activeWindows); - } - - /** - * Returns the most recent {@link TriggerResult} from any invocation of the - * {@link Trigger#onElement} or {@link Trigger#onTimer} methods - * of the trigger under test. - * - *

Note that this is not window-aware, but will return the most recent - * for any window. Tests should mostly be able to check - * the latest result at an opportune moment. - */ - public TriggerResult getLatestResult() { - return latestResult; - } - - /** - * Returns the most recent {@link MergeResult} from any invocation of the - * {@link Trigger#onMerge} of the trigger under test. - * - *

Note that this is not window-aware, but will return the most recent - * of any merge result, not for any particular result window. Tests should generally - * be able to check the latest merge result at an opportune moment. - */ - public MergeResult getLatestMergeResult() { - return latestMergeResult; - } - - public void clearLatestMergeResult() { - latestResult = null; - } - - /** - * Returns the full sequence of returned {@link TriggerResult TriggerResults} from - * invocations of {@link Trigger#onElement} or {@link Trigger#onTimer} methods - * of the trigger under test. - */ - public List getResultSequence() { - return ImmutableList.copyOf(resultSequence); - } - - /** - * Clears the result sequence returned by {@link #getResultSequence}. - */ - public void clearResultSequence() { - resultSequence.clear(); + new TriggerContextFactory<>(windowingStrategy, stateInternals, activeWindows); } /** @@ -314,16 +267,42 @@ public final void injectElements(Collection> values) th executableTrigger, getFinishedSet(window)); if (!context.trigger().isFinished()) { - latestResult = executableTrigger.invokeElement(context); - resultSequence.add(latestResult); - if (latestResult.isFinish()) { - context.trigger().setFinished(true); - } + executableTrigger.invokeOnElement(context); } } } } + public boolean shouldFire(W window) throws Exception { + Trigger.TriggerContext context = contextFactory.base( + window, + new TestTimers(windowNamespace(window)), + executableTrigger, getFinishedSet(window)); + executableTrigger.getSpec().prefetchShouldFire(context.state()); + return executableTrigger.invokeShouldFire(context); + } + + public void fireIfShouldFire(W window) throws Exception { + Trigger.TriggerContext context = contextFactory.base( + window, + new TestTimers(windowNamespace(window)), + executableTrigger, getFinishedSet(window)); + + executableTrigger.getSpec().prefetchShouldFire(context.state()); + if (executableTrigger.invokeShouldFire(context)) { + executableTrigger.getSpec().prefetchOnFire(context.state()); + executableTrigger.invokeOnFire(context); + if (context.trigger().isFinished()) { + activeWindows.remove(context.window()); + executableTrigger.invokeClear(context); + } + } + } + + public void setSubTriggerFinishedForWindow(int subTriggerIndex, W window, boolean value) { + getFinishedSet(window).setFinished(executableTrigger.subTriggers().get(subTriggerIndex), value); + } + /** * Invokes merge from the {@link WindowFn} a single time and passes the resulting merge * events on to the trigger under test. Does not persist the fact that merging happened, @@ -350,9 +329,9 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W for (W oldWindow : oldWindows) { mergingFinishedSets.put(oldWindow, getFinishedSet(oldWindow)); } - latestMergeResult = executableTrigger.invokeMerge( + executableTrigger.invokeOnMerge( contextFactory.createOnMergeContext(window, new TestTimers(windowNamespace(window)), - oldWindows, executableTrigger, getFinishedSet(window), finishedSets)); + oldWindows, executableTrigger, getFinishedSet(window), mergingFinishedSets)); } } @@ -365,17 +344,6 @@ private FinishedTriggers getFinishedSet(W window) { return finishedSet; } - public void fireTimer(W window, Instant timestamp, TimeDomain domain) throws Exception { - Trigger.OnTimerContext context = - contextFactory.createOnTimerContext(window, new TestTimers(windowNamespace(window)), - executableTrigger, getFinishedSet(window), timestamp, domain); - latestResult = executableTrigger.invokeTimer(context); - resultSequence.add(latestResult); - if (latestResult.isFinish()) { - context.trigger().setFinished(true); - } - } - /** * Simulate state. */ @@ -530,7 +498,6 @@ public void advanceInputWatermark(Instant newInputWatermark) throws Exception { WindowTracing.trace("TestTimerInternals.advanceInputWatermark: from {} to {}", inputWatermarkTime, newInputWatermark); inputWatermarkTime = newInputWatermark; - advanceAndFire(newInputWatermark, TimeDomain.EVENT_TIME); Instant hold = stateInternals.earliestWatermarkHold(); if (hold == null) { @@ -564,7 +531,6 @@ public void advanceProcessingTime(Instant newProcessingTime) throws Exception { WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", processingTime, newProcessingTime); processingTime = newProcessingTime; - advanceAndFire(newProcessingTime, TimeDomain.PROCESSING_TIME); } public void advanceSynchronizedProcessingTime(Instant newSynchronizedProcessingTime) @@ -575,31 +541,6 @@ public void advanceSynchronizedProcessingTime(Instant newSynchronizedProcessingT WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", synchronizedProcessingTime, newSynchronizedProcessingTime); synchronizedProcessingTime = newSynchronizedProcessingTime; - advanceAndFire(newSynchronizedProcessingTime, TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - } - - private void advanceAndFire(Instant currentTime, TimeDomain domain) throws Exception { - PriorityQueue queue = queue(domain); - - TimerData nextTimer = queue.peek(); - while (nextTimer != null && currentTime.isAfter(nextTimer.getTimestamp())) { - // Timers fire when the current time progresses past the timer time. - WindowTracing.trace( - "TestTimerInternals.advanceAndFire: firing {} at {}", nextTimer, currentTime); - // Remove before firing, so that if the trigger adds another identical - // timer we don't remove it. - queue.remove(); - - @SuppressWarnings("unchecked") - WindowNamespace windowNamespace = (WindowNamespace) nextTimer.getNamespace(); - W window = windowNamespace.getWindow(); - - if (activeWindows.isActive(window)) { - fireTimer(window, nextTimer.getTimestamp(), nextTimer.getDomain()); - } - - nextTimer = queue.peek(); - } } } From 4fa7bd3ab96975ff1618a01f0b2920d15fb46efb Mon Sep 17 00:00:00 2001 From: dhalperi Date: Fri, 22 Jan 2016 14:20:43 -0800 Subject: [PATCH 031/751] StreamingWriteFn: check if table exists before creating In StreamingWriteFn, every worker tries to create the table without checking beforehand whether the table exists. This behavior can lead to temporarily violating the BigQuery API quota limits on table.insert: { "code" : 403, "errors" : [ { "domain" : "global", "location" : "table.write", "locationType" : "other", "message" : "Exceeded rate limits: Your table exceeded quota for table.insert or table.update per table. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors";, "reason" : "rateLimitExceeded" } ], "message" : "Exceeded rate limits: Your table exceeded quota for table.insert or table.update per table. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors"; } Note that although this error appears severe, it should not cause jobs to fail. This change primarily aims to reduce the occurrence of this alarming log. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112818882 --- .../java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 5da265e6d7..b591982379 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -31,6 +31,8 @@ import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; @@ -1086,7 +1088,8 @@ public TableReference getOrCreateTable(BigQueryOptions options, String tableSpec TableSchema tableSchema = JSON_FACTORY.fromString(jsonTableSchema, TableSchema.class); Bigquery client = Transport.newBigQueryClient(options).build(); BigQueryTableInserter inserter = new BigQueryTableInserter(client); - inserter.tryCreateTable(tableReference, tableSchema); + inserter.getOrCreateTable(tableReference, WriteDisposition.WRITE_APPEND, + CreateDisposition.CREATE_IF_NEEDED, tableSchema); createdTables.add(tableSpec); } } From 25b4e8737aa57b01cf6bdf4cdcdfda574ce34832 Mon Sep 17 00:00:00 2001 From: mwegiel Date: Fri, 22 Jan 2016 16:11:37 -0800 Subject: [PATCH 032/751] Let shuffle reader and writer update counters. To this end, provide a reference to CounterSet.AddCounterMutator to ApplianceShuffleWriter and ApplianceShuffleReader. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112828809 --- .../runners/worker/ApplianceShuffleReader.java | 13 ++++++++++++- .../runners/worker/ApplianceShuffleWriter.java | 15 +++++++++++++-- .../runners/worker/GroupingShuffleReader.java | 3 ++- .../worker/PartitioningShuffleReader.java | 11 +++++++++-- .../PartitioningShuffleReaderFactory.java | 8 +++++--- .../sdk/runners/worker/ShuffleSink.java | 2 +- .../runners/worker/UngroupedShuffleReader.java | 11 +++++++++-- .../worker/UngroupedShuffleReaderFactory.java | 18 +++++++++++++----- .../worker/PartitioningShuffleReaderTest.java | 3 ++- .../worker/UngroupedShuffleReaderTest.java | 2 +- 10 files changed, 67 insertions(+), 19 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java index 5bea5a41d6..8ebcd52e0b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.runners.worker; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; + import java.io.IOException; import javax.annotation.concurrent.ThreadSafe; @@ -37,12 +39,21 @@ public final class ApplianceShuffleReader implements ShuffleReader { */ private long nativePointer; + /** + * Mutator that can be used to update counters. + */ + private CounterSet.AddCounterMutator addCounterMutator; + /** * @param shuffleReaderConfig opaque configuration for creating a * shuffle reader + * @param addCounterMutator mutator that can be used to update counters */ - public ApplianceShuffleReader(byte[] shuffleReaderConfig) { + public ApplianceShuffleReader( + byte[] shuffleReaderConfig, + CounterSet.AddCounterMutator addCounterMutator) { this.nativePointer = createFromConfig(shuffleReaderConfig); + this.addCounterMutator = addCounterMutator; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java index 2e4601c844..ca633f00ea 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.runners.worker; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; + import java.io.IOException; import javax.annotation.concurrent.ThreadSafe; @@ -35,14 +37,23 @@ public final class ApplianceShuffleWriter implements ShuffleWriter { */ private long nativePointer; + /** + * Mutator that can be used to update counters. + */ + private final CounterSet.AddCounterMutator addCounterMutator; + /** * @param shuffleWriterConfig opaque configuration for creating a * shuffle writer * @param bufferSize the writer buffer size + * @param addCounterMutator mutator that can be used to update counters */ - public ApplianceShuffleWriter(byte[] shuffleWriterConfig, - long bufferSize) { + public ApplianceShuffleWriter( + byte[] shuffleWriterConfig, + long bufferSize, + CounterSet.AddCounterMutator addCounterMutator) { this.nativePointer = createFromConfig(shuffleWriterConfig, bufferSize); + this.addCounterMutator = addCounterMutator; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java index 19ab083a3b..ce9a626b60 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java @@ -127,7 +127,8 @@ protected StateKind getStateSamplerStateKind() { @Override public GroupingShuffleReaderIterator iterator() throws IOException { Preconditions.checkArgument(shuffleReaderConfig != null); - ApplianceShuffleReader asr = new ApplianceShuffleReader(shuffleReaderConfig); + ApplianceShuffleReader asr = + new ApplianceShuffleReader(shuffleReaderConfig, addCounterMutator); String datasetId = asr.getDatasetId(); initCounter(datasetId); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java index dda76f117c..72abe59a81 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; @@ -43,15 +44,18 @@ public class PartitioningShuffleReader extends NativeReader keyCoder; WindowedValueCoder windowedValueCoder; public PartitioningShuffleReader(PipelineOptions options, byte[] shuffleReaderConfig, - String startShufflePosition, String stopShufflePosition, Coder>> coder) + String startShufflePosition, String stopShufflePosition, Coder>> coder, + CounterSet.AddCounterMutator addCounterMutator) throws Exception { this.shuffleReaderConfig = shuffleReaderConfig; this.startShufflePosition = startShufflePosition; this.stopShufflePosition = stopShufflePosition; + this.addCounterMutator = addCounterMutator; initCoder(coder); } @@ -79,7 +83,10 @@ private void initCoder(Coder>> coder) throws Exception { public NativeReaderIterator>> iterator() throws IOException { Preconditions.checkArgument(shuffleReaderConfig != null); return iterator(new BatchingShuffleEntryReader( - new ChunkingShuffleBatchReader(new ApplianceShuffleReader(shuffleReaderConfig)))); + new ChunkingShuffleBatchReader( + new ApplianceShuffleReader( + shuffleReaderConfig, + addCounterMutator)))); } PartitioningShuffleReaderIterator iterator(ShuffleEntryReader reader) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java index 2e36c0513d..cb68eefa3f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java @@ -50,19 +50,21 @@ public NativeReader create( @SuppressWarnings({"unchecked", "rawtypes"}) Coder>> typedCoder = (Coder>>) coder; - return createTyped(spec, options, typedCoder); + return createTyped(spec, options, typedCoder, addCounterMutator); } public PartitioningShuffleReader createTyped( CloudObject spec, PipelineOptions options, - Coder>> coder) + Coder>> coder, + CounterSet.AddCounterMutator addCounterMutator) throws Exception { return new PartitioningShuffleReader( options, decodeBase64(getString(spec, PropertyNames.SHUFFLE_READER_CONFIG)), getString(spec, PropertyNames.START_SHUFFLE_POSITION, null), getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), - coder); + coder, + addCounterMutator); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java index 793ed61bde..ea538db1a4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java @@ -283,7 +283,7 @@ public void close() throws IOException { public SinkWriter> writer() throws IOException { Preconditions.checkArgument(shuffleWriterConfig != null); ApplianceShuffleWriter applianceWriter = new ApplianceShuffleWriter( - shuffleWriterConfig, SHUFFLE_WRITER_BUFFER_SIZE); + shuffleWriterConfig, SHUFFLE_WRITER_BUFFER_SIZE, addCounterMutator); String datasetId = applianceWriter.getDatasetId(); return writer(new ChunkingShuffleEntryWriter(applianceWriter), datasetId); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java index 18a217dafc..391f169bf6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; @@ -41,21 +42,27 @@ public class UngroupedShuffleReader extends NativeReader { final String startShufflePosition; final String stopShufflePosition; final Coder coder; + final CounterSet.AddCounterMutator addCounterMutator; public UngroupedShuffleReader( @SuppressWarnings("unused") PipelineOptions options, byte[] shuffleReaderConfig, - @Nullable String startShufflePosition, @Nullable String stopShufflePosition, Coder coder) { + @Nullable String startShufflePosition, @Nullable String stopShufflePosition, Coder coder, + @Nullable CounterSet.AddCounterMutator addCounterMutator) { this.shuffleReaderConfig = shuffleReaderConfig; this.startShufflePosition = startShufflePosition; this.stopShufflePosition = stopShufflePosition; this.coder = coder; + this.addCounterMutator = addCounterMutator; } @Override public NativeReaderIterator iterator() throws IOException { Preconditions.checkArgument(shuffleReaderConfig != null); return iterator(new BatchingShuffleEntryReader( - new ChunkingShuffleBatchReader(new ApplianceShuffleReader(shuffleReaderConfig)))); + new ChunkingShuffleBatchReader( + new ApplianceShuffleReader( + shuffleReaderConfig, + addCounterMutator)))); } UngroupedShuffleReaderIterator iterator(ShuffleEntryReader reader) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java index 68dbacc058..dbf0bed403 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java @@ -43,19 +43,27 @@ public NativeReader create( @Nullable CounterSet.AddCounterMutator addCounterMutator, @Nullable String operationName) throws Exception { - return create(spec, coder, options); + return create(spec, coder, options, addCounterMutator); } public UngroupedShuffleReader create( - CloudObject spec, Coder coder, PipelineOptions options) throws Exception { - return create(options, spec, coder); + CloudObject spec, + Coder coder, + PipelineOptions options, + CounterSet.AddCounterMutator addCounterMutator) throws Exception { + return create(options, spec, coder, addCounterMutator); } UngroupedShuffleReader create( - PipelineOptions options, CloudObject spec, Coder coder) throws Exception { + PipelineOptions options, + CloudObject spec, + Coder coder, + CounterSet.AddCounterMutator addCounterMutator) throws Exception { return new UngroupedShuffleReader<>(options, decodeBase64(getString(spec, PropertyNames.SHUFFLE_READER_CONFIG)), getString(spec, PropertyNames.START_SHUFFLE_POSITION, null), - getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), coder); + getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), + coder, + addCounterMutator); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java index 4891dc5bbc..cd3d8e52b6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java @@ -94,7 +94,8 @@ private void runTestReadFromShuffle(List>> exp // Read from shuffle with PartitioningShuffleReader. PartitioningShuffleReader partitioningShuffleReader = new PartitioningShuffleReader<>( - PipelineOptionsFactory.create(), null, null, null, elemCoder); + PipelineOptionsFactory.create(), null, null, null, elemCoder, + addCounterMutator); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(partitioningShuffleReader); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java index 831bfc5851..657ed050d5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java @@ -79,7 +79,7 @@ void runTestReadFromShuffle(List expected) throws Exception { new UngroupedShuffleReader<>( PipelineOptionsFactory.create(), null, null, null, - elemCoder); + elemCoder, addCounterMutator); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(ungroupedShuffleReader); From 8929f3e428a50ea0217a020c4cb4fcc954815a9a Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 22 Jan 2016 16:46:10 -0800 Subject: [PATCH 033/751] Provide a reasonable default to Window.Bound#apply Window.into can be implemented by use of the AssignWindowsDoFn and a call to PCollection#setWindowingStrategyInternal. Providing this as the default behavior of Window#into allows runner implementors who do not need to be aware of window applications to not implement an override and instead just implement windowing on top of ParDo. Add DataflowWindow to the DataflowPipelineRunner to maintain current graph structure and behavior. Remove DirectPipelineRunner TransformEvaluator for Window. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112831751 --- .../sdk/runners/DataflowPipelineRunner.java | 24 +++- .../sdk/runners/dataflow/AssignWindows.java | 88 +++++++++++++++ .../sdk/transforms/windowing/Window.java | 104 +++++------------- 3 files changed, 137 insertions(+), 79 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 4636c1f86f..846c81dc3c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -45,6 +45,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.JobSpecification; +import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; import com.google.cloud.dataflow.sdk.transforms.Aggregator; @@ -262,10 +263,12 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { .put(BigQueryIO.Read.Bound.class, UnsupportedIO.class) .put(TextIO.Read.Bound.class, UnsupportedIO.class) .put(TextIO.Write.Bound.class, UnsupportedIO.class) + .put(Window.Bound.class, AssignWindows.class) .build(); } else { overrides = ImmutableMap., Class>builder() .put(Read.Unbounded.class, UnsupportedIO.class) + .put(Window.Bound.class, AssignWindows.class) .build(); } } @@ -294,7 +297,16 @@ public OutputT apply( : pc.getWindowingStrategy(), pc.isBounded()); return outputT; - + } else if (Window.Bound.class.equals(transform.getClass())) { + /* + * TODO: make this the generic way overrides are applied (using super.apply() rather than + * Pipeline.applyTransform(); this allows the apply method to be replaced without inserting + * additional nodes into the graph. + */ + // casting to wildcard + @SuppressWarnings("unchecked") + OutputT windowed = (OutputT) applyWindow((Window.Bound) transform, (PCollection) input); + return windowed; } else if (overrides.containsKey(transform.getClass())) { // It is the responsibility of whoever constructs overrides to ensure this is type safe. @SuppressWarnings("unchecked") @@ -316,6 +328,16 @@ public OutputT apply( } } + private PCollection applyWindow( + Window.Bound intitialTransform, PCollection initialInput) { + // types are matched at compile time + @SuppressWarnings("unchecked") + Window.Bound transform = (Window.Bound) intitialTransform; + @SuppressWarnings("unchecked") + PCollection input = (PCollection) initialInput; + return super.apply(new AssignWindows<>(transform), input); + } + @Override public DataflowPipelineJob run(Pipeline pipeline) { LOG.info("Executing pipeline on the Dataflow Service, which will have billing implications " diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java new file mode 100644 index 0000000000..093783de85 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.PCollection; + +/** + * A primitive {@link PTransform} that implements the {@link Window#into(WindowFn)} + * {@link PTransform}. + * + * For an application of {@link Window#into(WindowFn)} that changes the {@link WindowFn}, applies + * a primitive {@link PTransform} in the Dataflow service. + * + * For an application of {@link Window#into(WindowFn)} that does not change the {@link WindowFn}, + * applies an identity {@link ParDo} and sets the windowing strategy of the output + * {@link PCollection}. + * + * For internal use only. + * + * @param the type of input element + */ +public class AssignWindows extends PTransform, PCollection> { + private final Window.Bound transform; + + /** + * Builds an instance of this class from the overriden transform. + */ + @SuppressWarnings("unused") // Used via reflection + public AssignWindows(Window.Bound transform) { + this.transform = transform; + } + + @Override + public PCollection apply(PCollection input) { + WindowingStrategy outputStrategy = + transform.getOutputStrategyInternal(input.getWindowingStrategy()); + if (transform.getWindowFn() != null) { + // If the windowFn changed, we create a primitive, and run the AssignWindows operation here. + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), outputStrategy, input.isBounded()); + } else { + // If the windowFn didn't change, we just run a pass-through transform and then set the + // new windowing strategy. + return input.apply(ParDo.named("Identity").of(new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) throws Exception { + c.output(c.element()); + } + })).setWindowingStrategyInternal(outputStrategy); + } + } + + @Override + public void validate(PCollection input) { + transform.validate(input); + } + + @Override + protected Coder getDefaultOutputCoder(PCollection input) { + return input.getCoder(); + } + + @Override + protected String getKindString() { + return "Window.Into()"; + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java index dfdc25903d..6793e7648f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java @@ -20,24 +20,17 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.util.AssignWindowsDoFn; -import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TupleTag; import org.joda.time.Duration; -import java.util.ArrayList; - import javax.annotation.Nullable; /** @@ -527,9 +520,14 @@ public Bound withAllowedLateness(Duration allowedLateness, ClosingBehavior be return new Bound(name, windowFn, trigger, mode, allowedLateness, behavior, outputTimeFn); } + /** + * Get the output strategy of this {@link Window.Bound Window PTransform}. For internal use + * only. + */ // Rawtype cast of OutputTimeFn cannot be eliminated with intermediate variable, as it is // casting between wildcards - private WindowingStrategy getOutputStrategy(WindowingStrategy inputStrategy) { + public WindowingStrategy getOutputStrategyInternal( + WindowingStrategy inputStrategy) { WindowingStrategy result = inputStrategy; if (windowFn != null) { result = result.withWindowFn(windowFn); @@ -552,18 +550,24 @@ public Bound withAllowedLateness(Duration allowedLateness, ClosingBehavior be return result; } + /** + * Get the {@link WindowFn} of this {@link Window.Bound Window PTransform}. + */ + public WindowFn getWindowFn() { + return windowFn; + } + @Override public void validate(PCollection input) { - WindowingStrategy outputStrategy = getOutputStrategy(input.getWindowingStrategy()); + WindowingStrategy outputStrategy = + getOutputStrategyInternal(input.getWindowingStrategy()); // Make sure that the windowing strategy is complete & valid. if (outputStrategy.isTriggerSpecified() && !(outputStrategy.getTrigger().getSpec() instanceof DefaultTrigger)) { - if (!(outputStrategy.getWindowFn() instanceof GlobalWindows) && !outputStrategy.isAllowedLatenessSpecified()) { - throw new IllegalArgumentException( - "Except when using GlobalWindows," + throw new IllegalArgumentException("Except when using GlobalWindows," + " calling .triggering() to specify a trigger requires that the allowed lateness be" + " specified using .withAllowedLateness() to set the upper bound on how late data" + " can arrive before being dropped. See Javadoc for more details."); @@ -580,17 +584,23 @@ public void validate(PCollection input) { @Override public PCollection apply(PCollection input) { - WindowingStrategy outputStrategy = getOutputStrategy(input.getWindowingStrategy()); + WindowingStrategy outputStrategy = + getOutputStrategyInternal(input.getWindowingStrategy()); + PCollection output; if (windowFn != null) { // If the windowFn changed, we create a primitive, and run the AssignWindows operation here. - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), outputStrategy, input.isBounded()); + output = assignWindows(input, windowFn); } else { // If the windowFn didn't change, we just run a pass-through transform and then set the // new windowing strategy. - return input.apply(Window.identity()).setWindowingStrategyInternal(outputStrategy); + output = input.apply(Window.identity()); } + return output.setWindowingStrategyInternal(outputStrategy); + } + private PCollection assignWindows( + PCollection input, WindowFn windowFn) { + return input.apply("AssignWindows", ParDo.of(new AssignWindowsDoFn(windowFn))); } @Override @@ -608,7 +618,6 @@ protected String getKindString() { private static PTransform, PCollection> identity() { return ParDo.named("Identity").of(new DoFn() { - @Override public void processElement(ProcessContext c) { c.output(c.element()); } @@ -650,65 +659,4 @@ private WindowingStrategy getOutputWindowing( } } } - - ///////////////////////////////////////////////////////////////////////////// - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, - new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, - DirectPipelineRunner.EvaluationContext context) { - evaluateHelper(transform, context); - } - }); - } - - private static void evaluateHelper( - Bound transform, - DirectPipelineRunner.EvaluationContext context) { - - // If this use of Window didn't change the WindowFn, there is nothing to do. - if (transform.windowFn == null) { - throw new IllegalStateException("Shouldn't reach evaluateHelper with no windowFn"); - } - - PCollection input = context.getInput(transform); - - DirectModeExecutionContext executionContext = DirectModeExecutionContext.create(); - - TupleTag outputTag = new TupleTag<>(); - WindowFn windowFn = (WindowFn) transform.windowFn; - String name = context.getStepName(transform); - @SuppressWarnings("unchecked") - DoFn addWindowsDoFn = new AssignWindowsDoFn(windowFn); - DoFnRunner addWindowsRunner = - DoFnRunner.create( - context.getPipelineOptions(), - addWindowsDoFn, - NullSideInputReader.empty(), - new DoFnRunner.ListOutputManager(), - outputTag, - new ArrayList>(), - executionContext.getOrCreateStepContext(name, name, null), - context.getAddCounterMutator(), - context.getOutput(transform).getWindowingStrategy()); - - addWindowsRunner.startBundle(); - - // Process input elements. - for (DirectPipelineRunner.ValueWithMetadata inputElem - : context.getPCollectionValuesWithMetadata(input)) { - executionContext.setKey(inputElem.getKey()); - addWindowsRunner.processElement(inputElem.getWindowedValue()); - } - - addWindowsRunner.finishBundle(); - - context.setPCollectionValuesWithMetadata( - context.getOutput(transform), - executionContext.getOutput(outputTag)); - } } From 4ed7f131ee2fde89911433f3bc74283c973fd522 Mon Sep 17 00:00:00 2001 From: gardnerj Date: Sun, 24 Jan 2016 20:52:23 -0800 Subject: [PATCH 034/751] Allow 'game' examples to append to existing BigQuery tables. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112915940 --- .../examples/complete/game/utils/WriteToBigQuery.java | 4 +++- .../examples/complete/game/utils/WriteWindowedToBigQuery.java | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java index 401251489d..2cf719a7ef 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -117,7 +118,8 @@ public PDone apply(PCollection teamAndScore) { .to(getTable(teamAndScore.getPipeline(), tableName)) .withSchema(getSchema()) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)); + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) + .withWriteDisposition(WriteDisposition.WRITE_APPEND)); } /** Utility to construct an output table reference. */ diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java index 538af018f7..8433021f2e 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java @@ -19,6 +19,7 @@ import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; import com.google.cloud.dataflow.sdk.transforms.ParDo; @@ -68,7 +69,8 @@ public PDone apply(PCollection teamAndScore) { .to(getTable(teamAndScore.getPipeline(), tableName)) .withSchema(getSchema()) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)); + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) + .withWriteDisposition(WriteDisposition.WRITE_APPEND)); } } From ec5dfe82f77442a559d5d6ac43a9b9bf17184dbc Mon Sep 17 00:00:00 2001 From: peihe Date: Mon, 25 Jan 2016 13:45:48 -0800 Subject: [PATCH 035/751] Create StreamingGroupAlsoByWindowsDoFnRunner Move the input elements lateness check to DoFnRunner. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112982861 --- .../worker/GroupAlsoByWindowsParDoFn.java | 15 +- .../sdk/runners/worker/KeyedWorkItem.java | 221 +------ .../sdk/runners/worker/KeyedWorkItems.java | 313 ++++++++++ .../worker/LateDataDroppingDoFnRunner.java | 135 +++++ .../sdk/runners/worker/ParDoFnBase.java | 24 +- .../StreamingGroupAlsoByWindowsDoFn.java | 25 +- ...eamingGroupAlsoByWindowsReshuffleDoFn.java | 4 +- .../worker/StreamingSideInputDoFnRunner.java | 14 +- .../worker/WindowingWindmillReader.java | 41 +- .../dataflow/sdk/transforms/DoFnTester.java | 8 +- .../cloud/dataflow/sdk/transforms/ParDo.java | 14 +- .../cloud/dataflow/sdk/util/DoFnRunner.java | 571 +----------------- .../dataflow/sdk/util/DoFnRunnerBase.java | 559 +++++++++++++++++ .../cloud/dataflow/sdk/util/DoFnRunners.java | 106 ++++ .../sdk/util/GroupAlsoByWindowsDoFn.java | 9 + ...GroupAlsoByWindowsViaOutputBufferDoFn.java | 9 +- .../dataflow/sdk/util/ReduceFnRunner.java | 36 +- .../dataflow/sdk/util/SimpleDoFnRunner.java | 58 ++ .../dataflow/sdk/util/TimerOrElement.java | 4 +- .../sdk/runners/worker/KeyedWorkItemTest.java | 8 +- .../worker/StreamingDataflowWorkerTest.java | 4 +- .../StreamingGroupAlsoByWindowsDoFnTest.java | 152 +++-- ...ngGroupAlsoByWindowsReshuffleDoFnTest.java | 28 +- .../StreamingSideInputDoFnRunnerTest.java | 33 +- .../util/GroupAlsoByWindowsProperties.java | 6 +- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 52 -- .../dataflow/sdk/util/ReduceFnTester.java | 10 +- 27 files changed, 1459 insertions(+), 1000 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LateDataDroppingDoFnRunner.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java index ec7dd8ee5a..e8b93062b3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java @@ -65,14 +65,15 @@ class GroupAlsoByWindowsParDoFn extends ParDoFnBase { static GroupAlsoByWindowsParDoFn of( PipelineOptions options, DoFn groupAlsoByWindowsDoFn, + WindowingStrategy windowingStrategy, String stepName, String transformName, - DataflowExecutionContext executionContext, + DataflowExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception { - return new GroupAlsoByWindowsParDoFn(options, groupAlsoByWindowsDoFn, stepName, transformName, - executionContext, addCounterMutator, stateSampler); + return new GroupAlsoByWindowsParDoFn(options, groupAlsoByWindowsDoFn, windowingStrategy, + stepName, transformName, executionContext, addCounterMutator, stateSampler); } /** @@ -160,6 +161,7 @@ public ParDoFn create( return GroupAlsoByWindowsParDoFn.of( options, groupAlsoByWindowsDoFn, + windowingStrategy, stepName, transformName, executionContext, @@ -170,7 +172,7 @@ public ParDoFn create( @Override protected DoFnInfo getDoFnInfo() { - return new DoFnInfo<>(groupAlsoByWindowsDoFn, null); + return new DoFnInfo<>(groupAlsoByWindowsDoFn, windowingStrategy); } @SuppressWarnings({"unchecked", "rawtypes"}) @@ -262,13 +264,15 @@ public Coder> getAccumulatorCoder(CoderRegistry registry, Coder } private final DoFn groupAlsoByWindowsDoFn; + private final WindowingStrategy windowingStrategy; private GroupAlsoByWindowsParDoFn( PipelineOptions options, DoFn groupAlsoByWindowsDoFn, + WindowingStrategy windowingStrategy, String stepName, String transformName, - DataflowExecutionContext executionContext, + DataflowExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) { super( @@ -281,5 +285,6 @@ private GroupAlsoByWindowsParDoFn( addCounterMutator, stateSampler); this.groupAlsoByWindowsDoFn = groupAlsoByWindowsDoFn; + this.windowingStrategy = windowingStrategy; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItem.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItem.java index 1a05a5bec4..d6a87e17fa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItem.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItem.java @@ -13,228 +13,33 @@ * License for the specific language governing permissions and limitations under * the License. */ - package com.google.cloud.dataflow.sdk.runners.worker; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.InputMessageBundle; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Message; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Timer; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.base.Throwables; -import com.google.common.collect.FluentIterable; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; /** - * Wrapper around a {@link Windmill.WorkItem} which contains all the timers and elements associated - * with a specific work item. + * Interface that contains all the timers and elements associated with a specific work item. * *

Used as the input type of {@link StreamingGroupAlsoByWindowsDoFn}. * + * @param the key type * @param the element type */ -public class KeyedWorkItem { - - private static final Predicate IS_WATERMARK = new Predicate() { - @Override - public boolean apply(Timer input) { - return input.getType() == Timer.Type.WATERMARK; - } - }; - - public static KeyedWorkItem workItem( - Object key, - Windmill.WorkItem workItem, - Coder windowCoder, - Coder> windowsCoder, - Coder valueCoder) { - return new KeyedWorkItem<>(key, workItem, windowCoder, windowsCoder, valueCoder); - } - - public Object key() { - return key; - } - - public Iterable timersIterable() { - FluentIterable allTimers = FluentIterable.from(workItem.getTimers().getTimersList()); - FluentIterable eventTimers = allTimers.filter(IS_WATERMARK); - FluentIterable nonEventTimers = allTimers.filter(Predicates.not(IS_WATERMARK)); - return eventTimers.append(nonEventTimers).transform(new Function() { - private TimeDomain getTimeDomain(Windmill.Timer.Type type) { - switch (type) { - case REALTIME: - return TimeDomain.PROCESSING_TIME; - case DEPENDENT_REALTIME: - return TimeDomain.SYNCHRONIZED_PROCESSING_TIME; - case WATERMARK: - return TimeDomain.EVENT_TIME; - default: - throw new IllegalArgumentException("Unsupported timer type " + type); - } - } - - @Override - public TimerData apply(Timer timer) { - String tag = timer.getTag().toStringUtf8(); - String namespaceString = tag.substring(0, tag.indexOf('+')); - StateNamespace namespace = StateNamespaces.fromString(namespaceString, windowCoder); - - Instant timestamp = new Instant(TimeUnit.MICROSECONDS.toMillis(timer.getTimestamp())); - return TimerData.of(namespace, timestamp, getTimeDomain(timer.getType())); - } - }); - } - - public Iterable> elementsIterable() { - return FluentIterable.from(workItem.getMessageBundlesList()) - .transformAndConcat(new Function>() { - @Override - public Iterable apply(InputMessageBundle input) { - return input.getMessagesList(); - } - }) - .transform(new Function>() { - @Override - public WindowedValue apply(Message message) { - try { - Instant timestamp = new Instant( - TimeUnit.MICROSECONDS.toMillis(message.getTimestamp())); - Collection windows = - WindmillSink.decodeMetadataWindows(windowsCoder, message.getMetadata()); - PaneInfo pane = WindmillSink.decodeMetadataPane(message.getMetadata()); - - InputStream inputStream = message.getData().newInput(); - ElemT value = valueCoder.decode(inputStream, Coder.Context.OUTER); - return WindowedValue.of(value, timestamp, windows, pane); - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - }); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof KeyedWorkItem)) { - return false; - } - - KeyedWorkItem that = (KeyedWorkItem) other; - return Objects.equals(this.key, that.key) - && Objects.equals(this.workItem, that.workItem); - } - - @Override - public int hashCode() { - return Objects.hash(key, workItem); - } +public interface KeyedWorkItem { /** - * Coder that forwards {@code ByteSizeObserver} calls to an underlying element coder. - * {@code TimerOrElement} objects never need to be encoded, so this class does not - * support the {@code encode} and {@code decode} methods. + * Returns the key. */ - public static class KeyedWorkItemCoder extends StandardCoder> { - final Coder elemCoder; - - /** - * Creates a new {@code TimerOrElement.Coder} that wraps the given {@link Coder}. - */ - public static KeyedWorkItemCoder of(Coder elemCoder) { - return new KeyedWorkItemCoder<>(elemCoder); - } + public K key(); - @JsonCreator - public static KeyedWorkItemCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List components) { - return of((Coder) components.get(0)); - } - - @Override - public void encode(KeyedWorkItem value, OutputStream outStream, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public KeyedWorkItem decode(InputStream inStream, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isRegisterByteSizeObserverCheap(KeyedWorkItem value, Context context) { - return true; - } - - @Override - public void registerByteSizeObserver( - KeyedWorkItem value, ElementByteSizeObserver observer, Context context) - throws Exception { - observer.update((long) value.workItem.getSerializedSize()); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException {} - - @Override - public List> getCoderArguments() { - return Arrays.asList(elemCoder); - } - - public Coder getElementCoder() { - return elemCoder; - } - - protected KeyedWorkItemCoder(Coder elemCoder) { - this.elemCoder = elemCoder; - } - } - - ////////////////////////////////////////////////////////////////////////////// - - private final Windmill.WorkItem workItem; - private final Object key; - - private final transient Coder windowCoder; - private final transient Coder> windowsCoder; - private final transient Coder valueCoder; + /** + * Returns the timers iterable. + */ + public Iterable timersIterable(); - KeyedWorkItem( - Object key, - Windmill.WorkItem workItem, - Coder windowCoder, - Coder> windowsCoder, - Coder valueCoder) { - this.key = key; - this.workItem = workItem; - this.windowCoder = windowCoder; - this.windowsCoder = windowsCoder; - this.valueCoder = valueCoder; - } + /** + * Returns the elements iterable. + */ + public Iterable> elementsIterable(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java new file mode 100644 index 0000000000..8311fdcfde --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java @@ -0,0 +1,313 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; +import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.InputMessageBundle; +import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Message; +import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Timer; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; +import com.google.cloud.dataflow.sdk.util.state.StateNamespace; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.base.Throwables; +import com.google.common.collect.FluentIterable; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.joda.time.Instant; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * Static utility methods that provide {@link KeyedWorkItem} implementations. + */ +public class KeyedWorkItems { + /** + * Return an implementation of {@link KeyedWorkItem} that wraps around + * a {@code Windmill.WorkItem}. + * + * @param the key type + * @param the element type + */ + public static KeyedWorkItem windmillWorkItem( + K key, + Windmill.WorkItem workItem, + Coder windowCoder, + Coder> windowsCoder, + Coder valueCoder) { + return new WindmillKeyedWorkItem<>(key, workItem, windowCoder, windowsCoder, valueCoder); + } + + /** + * Returns an implementation of {@link KeyedWorkItem} that wraps around an elements iterable. + * + * @param the key type + * @param the element type + */ + public static KeyedWorkItem elementsWorkItem( + K key, Iterable> elementsIterable) { + return new ComposedKeyedWorkItem<>(key, Collections.emptyList(), elementsIterable); + } + + /** + * Returns an implementation of {@link KeyedWorkItem} that wraps around an timers iterable. + * + * @param the key type + * @param the element type + */ + public static KeyedWorkItem timersWorkItem( + K key, Iterable timersIterable) { + return new ComposedKeyedWorkItem<>( + key, timersIterable, Collections.>emptyList()); + } + + /** + * Returns an implementation of {@link KeyedWorkItem} that wraps around + * an timers iterable and an elements iterable. + * + * @param the key type + * @param the element type + */ + public static KeyedWorkItem workItem( + K key, Iterable timersIterable, Iterable> elementsIterable) { + return new ComposedKeyedWorkItem<>( + key, timersIterable, elementsIterable); + } + + private static class WindmillKeyedWorkItem implements KeyedWorkItem { + private static final Predicate IS_WATERMARK = new Predicate() { + @Override + public boolean apply(Timer input) { + return input.getType() == Timer.Type.WATERMARK; + } + }; + + private final Windmill.WorkItem workItem; + private final K key; + + private final transient Coder windowCoder; + private final transient Coder> windowsCoder; + private final transient Coder valueCoder; + + WindmillKeyedWorkItem( + K key, + Windmill.WorkItem workItem, + Coder windowCoder, + Coder> windowsCoder, + Coder valueCoder) { + this.key = key; + this.workItem = workItem; + this.windowCoder = windowCoder; + this.windowsCoder = windowsCoder; + this.valueCoder = valueCoder; + } + + @Override + public K key() { + return key; + } + + @Override + public Iterable timersIterable() { + FluentIterable allTimers = FluentIterable.from(workItem.getTimers().getTimersList()); + FluentIterable eventTimers = allTimers.filter(IS_WATERMARK); + FluentIterable nonEventTimers = allTimers.filter(Predicates.not(IS_WATERMARK)); + return eventTimers.append(nonEventTimers).transform(new Function() { + private TimeDomain getTimeDomain(Windmill.Timer.Type type) { + switch (type) { + case REALTIME: + return TimeDomain.PROCESSING_TIME; + case DEPENDENT_REALTIME: + return TimeDomain.SYNCHRONIZED_PROCESSING_TIME; + case WATERMARK: + return TimeDomain.EVENT_TIME; + default: + throw new IllegalArgumentException("Unsupported timer type " + type); + } + } + + @Override + public TimerData apply(Timer timer) { + String tag = timer.getTag().toStringUtf8(); + String namespaceString = tag.substring(0, tag.indexOf('+')); + StateNamespace namespace = StateNamespaces.fromString(namespaceString, windowCoder); + + Instant timestamp = new Instant(TimeUnit.MICROSECONDS.toMillis(timer.getTimestamp())); + return TimerData.of(namespace, timestamp, getTimeDomain(timer.getType())); + } + }); + } + + @Override + public Iterable> elementsIterable() { + return FluentIterable.from(workItem.getMessageBundlesList()) + .transformAndConcat(new Function>() { + @Override + public Iterable apply(InputMessageBundle input) { + return input.getMessagesList(); + } + }) + .transform(new Function>() { + @Override + public WindowedValue apply(Message message) { + try { + Instant timestamp = new Instant( + TimeUnit.MICROSECONDS.toMillis(message.getTimestamp())); + Collection windows = + WindmillSink.decodeMetadataWindows(windowsCoder, message.getMetadata()); + PaneInfo pane = WindmillSink.decodeMetadataPane(message.getMetadata()); + + InputStream inputStream = message.getData().newInput(); + ElemT value = valueCoder.decode(inputStream, Coder.Context.OUTER); + return WindowedValue.of(value, timestamp, windows, pane); + } catch (IOException e) { + throw Throwables.propagate(e); + } + } + }); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof WindmillKeyedWorkItem)) { + return false; + } + + WindmillKeyedWorkItem that = (WindmillKeyedWorkItem) other; + return Objects.equals(this.key, that.key) + && Objects.equals(this.workItem, that.workItem); + } + + @Override + public int hashCode() { + return Objects.hash(key, workItem); + } + } + + private static class ComposedKeyedWorkItem implements KeyedWorkItem { + private final K key; + private final Iterable timersIterable; + private final Iterable> elementsIterable; + + ComposedKeyedWorkItem(K key, Iterable timersIterable, + Iterable> elementsIterable) { + this.key = key; + this.timersIterable = timersIterable; + this.elementsIterable = elementsIterable; + } + @Override + public K key() { + return key; + } + + @Override + public Iterable timersIterable() { + return timersIterable; + } + + @Override + public Iterable> elementsIterable() { + return elementsIterable; + } + } + + /** + * Coder that forwards {@code ByteSizeObserver} calls to an underlying element coder. + * {@code TimerOrElement} objects never need to be encoded, so this class does not + * support the {@code encode} and {@code decode} methods. + */ + public static class FakeKeyedWorkItemCoder extends StandardCoder> { + final Coder elemCoder; + + /** + * Creates a new {@code TimerOrElement.Coder} that wraps the given {@link Coder}. + */ + public static FakeKeyedWorkItemCoder of(Coder elemCoder) { + return new FakeKeyedWorkItemCoder<>(elemCoder); + } + + @JsonCreator + public static FakeKeyedWorkItemCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) + List components) { + return of((Coder) components.get(0)); + } + + @Override + public void encode(KeyedWorkItem value, OutputStream outStream, Context context) { + throw new UnsupportedOperationException(); + } + + @Override + public KeyedWorkItem decode(InputStream inStream, Context context) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isRegisterByteSizeObserverCheap(KeyedWorkItem value, Context context) { + return true; + } + + @Override + public void registerByteSizeObserver( + KeyedWorkItem value, ElementByteSizeObserver observer, Context context) + throws Exception { + if (value instanceof WindmillKeyedWorkItem) { + long serializedSize = ((WindmillKeyedWorkItem) value).workItem.getSerializedSize(); + observer.update(serializedSize); + } else { + throw new UnsupportedOperationException(); + } + } + + @Override + public void verifyDeterministic() throws NonDeterministicException {} + + @Override + public List> getCoderArguments() { + return Arrays.asList(elemCoder); + } + + public Coder getElementCoder() { + return elemCoder; + } + + protected FakeKeyedWorkItemCoder(Coder elemCoder) { + this.elemCoder = elemCoder; + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LateDataDroppingDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LateDataDroppingDoFnRunner.java new file mode 100644 index 0000000000..dc40276272 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LateDataDroppingDoFnRunner.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; +import com.google.cloud.dataflow.sdk.util.SideInputReader; +import com.google.cloud.dataflow.sdk.util.TimerInternals; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowTracing; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +import org.joda.time.Instant; + +import java.util.List; + +/** + * A customized {@link DoFnRunner} that handles late data dropping. + * + *

It expands windows before checking data lateness. + * + * @param key type + * @param input value element type + * @param output value element type + * @param window type + */ +public class LateDataDroppingDoFnRunner + extends DoFnRunnerBase, KV> { + private final WindowingStrategy windowingStrategy; + private final TimerInternals timerInternals; + private final Aggregator droppedDueToLateness; + + public LateDataDroppingDoFnRunner( + PipelineOptions options, + StreamingGroupAlsoByWindowsDoFn doFn, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag> mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator, + WindowingStrategy windowingStrategy) { + super(options, doFn, sideInputReader, outputManager, + mainOutputTag, sideOutputTags, stepContext, + addCounterMutator, windowingStrategy); + this.windowingStrategy = windowingStrategy; + this.timerInternals = stepContext.timerInternals(); + + droppedDueToLateness = doFn.droppedDueToLateness; + } + + @Override + public void invokeProcessElement(WindowedValue> elem) { + final K key = elem.getValue().key(); + Iterable>> elements = Iterables.transform( + elem.getValue().elementsIterable(), + new Function, Iterable>>() { + @Override + public Iterable> apply(final WindowedValue input) { + return Iterables.transform( + input.getWindows(), + new Function>() { + @Override + public WindowedValue apply(BoundedWindow window) { + return WindowedValue.of( + input.getValue(), input.getTimestamp(), window, input.getPane()); + } + }); + }}); + + Iterable> nonLateElements = Iterables.filter( + Iterables.concat(elements), + new Predicate>() { + @Override + public boolean apply(WindowedValue input) { + BoundedWindow window = Iterables.getOnlyElement(input.getWindows()); + if (canDropDueToExpiredWindow(window)) { + // The element is too late for this window. + droppedDueToLateness.addValue(1L); + WindowTracing.debug( + "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " + + "since too far behind inputWatermark:{}; outputWatermark:{}", + input.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + return false; + } else { + return true; + } + } + }); + KeyedWorkItem keyedWorkItem = KeyedWorkItems.workItem( + elem.getValue().key(), elem.getValue().timersIterable(), nonLateElements); + // This can contain user code. Wrap it in case it throws an exception. + try { + fn.processElement(createProcessContext(elem.withValue(keyedWorkItem))); + } catch (Throwable t) { + // Exception in user code. + Throwables.propagateIfInstanceOf(t, UserCodeException.class); + throw new UserCodeException(t); + } + } + + /** Is {@code window} expired w.r.t. the garbage collection watermark? */ + private boolean canDropDueToExpiredWindow(BoundedWindow window) { + Instant inputWM = timerInternals.currentInputWatermarkTime(); + return inputWM != null + && window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()).isBefore(inputWM); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java index fea0544344..585cd06ebd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java @@ -19,10 +19,11 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.DoFnInfo; import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunner.OutputManager; +import com.google.cloud.dataflow.sdk.util.DoFnRunner.RequiresLateDataDropping; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; import com.google.cloud.dataflow.sdk.util.SideInputReader; @@ -178,8 +179,21 @@ public void output(TupleTag tag, WindowedValue output) { } }; - if (hasStreamingSideInput) { - fnRunner = new StreamingSideInputDoFnRunner( + if (doFnInfo.getDoFn() instanceof StreamingGroupAlsoByWindowsDoFn + && doFnInfo.getDoFn() instanceof RequiresLateDataDropping) { + @SuppressWarnings({"unchecked", "rawtypes"}) + DoFnRunner objectFnRunner = DoFnRunners.lateDataDroppingRunner( + options, + (DoFnInfo) doFnInfo, + sideInputReader, + outputManager, + (TupleTag) mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator); + fnRunner = objectFnRunner; + } else if (hasStreamingSideInput) { + fnRunner = DoFnRunners.streamingSideInputRunner( options, doFnInfo, sideInputReader, @@ -189,7 +203,7 @@ public void output(TupleTag tag, WindowedValue output) { stepContext, addCounterMutator); } else { - fnRunner = DoFnRunner.create( + fnRunner = DoFnRunners.simpleRunner( options, doFnInfo.getDoFn(), sideInputReader, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java index cfc98e5c96..78977d51b3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java @@ -22,6 +22,8 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; +import com.google.cloud.dataflow.sdk.util.DoFnRunner.RequiresLateDataDropping; +import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsDoFn; import com.google.cloud.dataflow.sdk.util.ReduceFnRunner; import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; import com.google.cloud.dataflow.sdk.util.SystemReduceFn; @@ -41,7 +43,11 @@ */ @SystemDoFnInternal public abstract class StreamingGroupAlsoByWindowsDoFn - extends DoFn, KV> { + extends DoFn, KV> { + protected final Aggregator droppedDueToClosedWindow = createAggregator( + GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); + protected final Aggregator droppedDueToLateness = createAggregator( + GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); public static StreamingGroupAlsoByWindowsDoFn create( @@ -54,7 +60,7 @@ StreamingGroupAlsoByWindowsDoFn create( } public static - DoFn, KV>> createForIterable( + DoFn, KV>> createForIterable( final WindowingStrategy windowingStrategy, final Coder inputCoder) { // If the windowing strategy indicates we're doing a reshuffle, use the special-path. @@ -67,13 +73,8 @@ DoFn, KV>> createForIterable( } private static class StreamingGABWViaWindowSetDoFn - extends StreamingGroupAlsoByWindowsDoFn { - - private final Aggregator droppedDueToClosedWindow = - createAggregator(ReduceFnRunner.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); - private final Aggregator droppedDueToLateness = - createAggregator(ReduceFnRunner.DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); - + extends StreamingGroupAlsoByWindowsDoFn + implements RequiresLateDataDropping { private final WindowingStrategy windowingStrategy; private SystemReduceFn.Factory reduceFnFactory; @@ -87,14 +88,14 @@ public StreamingGABWViaWindowSetDoFn(WindowingStrategy windowingStrategy, @Override public void processElement(ProcessContext c) throws Exception { - KeyedWorkItem element = c.element(); + KeyedWorkItem element = c.element(); @SuppressWarnings("unchecked") - K key = (K) c.element().key(); + K key = c.element().key(); TimerInternals timerInternals = c.windowingInternals().timerInternals(); ReduceFnRunner runner = new ReduceFnRunner<>( key, windowingStrategy, timerInternals, c.windowingInternals(), - droppedDueToClosedWindow, droppedDueToLateness, reduceFnFactory.create(key)); + droppedDueToClosedWindow, reduceFnFactory.create(key)); for (TimerData timer : element.timersIterable()) { runner.onTimer(timer); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java index 39c521a895..5bb5d64712 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java @@ -33,7 +33,7 @@ */ @SystemDoFnInternal public class StreamingGroupAlsoByWindowsReshuffleDoFn - extends DoFn, KV>> { + extends DoFn, KV>> { public static boolean isReshuffle(WindowingStrategy strategy) { return strategy.getTrigger().getSpec() instanceof ReshuffleTrigger; @@ -42,7 +42,7 @@ public static boolean isReshuffle(WindowingStrategy strategy) { @Override public void processElement(ProcessContext c) throws Exception { @SuppressWarnings("unchecked") - K key = (K) c.element().key(); + K key = c.element().key(); for (WindowedValue item : c.element().elementsIterable()) { c.windowingInternals().outputWindowedValue( KV.of(key, (Iterable) Collections.singletonList(item.getValue())), diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java index dcbdc2546a..b61a48d3ea 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java @@ -27,7 +27,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.UserCodeException; @@ -62,7 +63,7 @@ * @param the type of the windows of the main input */ public class StreamingSideInputDoFnRunner - extends DoFnRunner { + extends DoFnRunnerBase { private StreamingModeExecutionContext.StepContext stepContext; private Map> sideInputViews; @@ -82,17 +83,14 @@ public StreamingSideInputDoFnRunner( TupleTag mainOutputTag, List> sideOutputTags, StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator) throws Exception { + CounterSet.AddCounterMutator addCounterMutator, + WindowingStrategy windowingStrategy) { super(options, doFnInfo.getDoFn(), sideInputReader, outputManager, mainOutputTag, sideOutputTags, stepContext, addCounterMutator, doFnInfo.getWindowingStrategy()); this.stepContext = (StreamingModeExecutionContext.StepContext) stepContext; - WindowFn wildcardWindowFn = - doFnInfo.getWindowingStrategy().getWindowFn(); - @SuppressWarnings("unchecked") - WindowFn typedWindowFn = (WindowFn) wildcardWindowFn; - this.windowFn = typedWindowFn; + this.windowFn = windowingStrategy.getWindowFn(); this.sideInputViews = new HashMap<>(); for (PCollectionView view : doFnInfo.getSideInputViews()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java index 38d9b28603..36f7a03ece 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java @@ -19,7 +19,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItem.KeyedWorkItemCoder; +import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItems.FakeKeyedWorkItemCoder; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItem; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.CloudObject; @@ -39,26 +39,27 @@ * A Reader that receives input data from a Windmill server, and returns a singleton iterable * containing the work item. */ -class WindowingWindmillReader extends NativeReader>> { +class WindowingWindmillReader extends NativeReader>> { - private final KvCoder kvCoder; + private final KvCoder kvCoder; private final Coder windowCoder; private final Coder> windowsCoder; private StreamingModeExecutionContext context; - WindowingWindmillReader(Coder>> coder, + WindowingWindmillReader(Coder>> coder, StreamingModeExecutionContext context) { - FullWindowedValueCoder> inputCoder = - (FullWindowedValueCoder>) coder; + FullWindowedValueCoder> inputCoder = + (FullWindowedValueCoder>) coder; this.windowsCoder = inputCoder.getWindowsCoder(); this.windowCoder = inputCoder.getWindowCoder(); - Coder elementCoder = ((KeyedWorkItemCoder) inputCoder.getValueCoder()).getElementCoder(); + Coder elementCoder = + ((FakeKeyedWorkItemCoder) inputCoder.getValueCoder()).getElementCoder(); if (!(elementCoder instanceof KvCoder)) { throw new IllegalArgumentException( "WindowingWindmillReader only works with KvCoders."); } @SuppressWarnings("unchecked") - KvCoder kvCoder = (KvCoder) + KvCoder kvCoder = (KvCoder) elementCoder; this.kvCoder = kvCoder; this.context = context; @@ -75,8 +76,8 @@ public NativeReader create( @Nullable String operationName) throws Exception { @SuppressWarnings({"rawtypes", "unchecked"}) - Coder>> typedCoder = - (Coder>>) coder; + Coder>> typedCoder = + (Coder>>) coder; return WindowingWindmillReader.create(typedCoder, (StreamingModeExecutionContext) context); } } @@ -85,24 +86,24 @@ public NativeReader create( * Creates a {@link WindowingWindmillReader} from the provided {@link Coder} * and {@link StreamingModeExecutionContext}. */ - public static WindowingWindmillReader create( - Coder>> coder, + public static WindowingWindmillReader create( + Coder>> coder, StreamingModeExecutionContext context) { - return new WindowingWindmillReader(coder, context); + return new WindowingWindmillReader(coder, context); } @Override - public NativeReaderIterator>> iterator() throws IOException { - final Object key = kvCoder.getKeyCoder().decode( + public NativeReaderIterator>> iterator() throws IOException { + final K key = kvCoder.getKeyCoder().decode( context.getSerializedKey().newInput(), Coder.Context.OUTER); final WorkItem workItem = context.getWork(); - final WindowedValue> value = + final WindowedValue> value = WindowedValue.valueInEmptyWindows( - KeyedWorkItem.workItem( + KeyedWorkItems.windmillWorkItem( key, workItem, windowCoder, windowsCoder, kvCoder.getValueCoder())); - return new NativeReaderIterator>>() { - private WindowedValue> current; + return new NativeReaderIterator>>() { + private WindowedValue> current; @Override public boolean start() throws IOException { @@ -117,7 +118,7 @@ public boolean advance() throws IOException { } @Override - public WindowedValue> getCurrent() { + public WindowedValue> getCurrent() { if (current == null) { throw new NoSuchElementException(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java index 2903c48cf2..02980713b3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java @@ -22,6 +22,8 @@ import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.PTuple; import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -442,7 +444,7 @@ enum State { DoFn fn; /** The ListOutputManager to examine the outputs. */ - DoFnRunner.ListOutputManager outputManager; + DoFnRunnerBase.ListOutputManager outputManager; /** The DoFnRunner if processing is in progress. */ DoFnRunner fnRunner; @@ -478,8 +480,8 @@ void initializeState() { : sideInputs.entrySet()) { runnerSideInputs = runnerSideInputs.and(entry.getKey().getTagInternal(), entry.getValue()); } - outputManager = new DoFnRunner.ListOutputManager(); - fnRunner = DoFnRunner.create( + outputManager = new DoFnRunnerBase.ListOutputManager(); + fnRunner = DoFnRunners.simpleRunner( options, fn, DirectSideInputReader.of(runnerSideInputs), diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java index 43644d4e73..15dd0abd52 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java @@ -24,6 +24,8 @@ import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.IllegalMutationException; import com.google.cloud.dataflow.sdk.util.MutationDetector; import com.google.cloud.dataflow.sdk.util.MutationDetectors; @@ -1138,11 +1140,11 @@ private static void evaluateHelpe ImmutabilityCheckingOutputManager outputManager = new ImmutabilityCheckingOutputManager<>( fn.getClass().getSimpleName(), - new DoFnRunner.ListOutputManager(), + new DoFnRunnerBase.ListOutputManager(), outputs); DoFnRunner fnRunner = - DoFnRunner.create( + DoFnRunners.simpleRunner( context.getPipelineOptions(), fn, sideInputReader, @@ -1210,23 +1212,23 @@ private static SideInputReader makeSideInputReader( } /** - * A {@link DoFnRunner.OutputManager} that provides facilities for checking output values for + * A {@code DoFnRunner.OutputManager} that provides facilities for checking output values for * illegal mutations. * *

When used via the try-with-resources pattern, it is guaranteed that every value passed * to {@link #output} will have been checked for illegal mutation. */ private static class ImmutabilityCheckingOutputManager - implements DoFnRunner.OutputManager, AutoCloseable { + implements DoFnRunners.OutputManager, AutoCloseable { - private final DoFnRunner.OutputManager underlyingOutputManager; + private final DoFnRunners.OutputManager underlyingOutputManager; private final ConcurrentMap, MutationDetector> mutationDetectorForTag; private final PCollectionTuple outputs; private String doFnName; public ImmutabilityCheckingOutputManager( String doFnName, - DoFnRunner.OutputManager underlyingOutputManager, + DoFnRunners.OutputManager underlyingOutputManager, PCollectionTuple outputs) { this.doFnName = doFnName; this.underlyingOutputManager = underlyingOutputManager; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java index b501e90208..3cc78f0999 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Google Inc. + * Copyright (C) 2016 Google Inc. * * Licensed 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 @@ -13,578 +13,33 @@ * License for the specific language governing permissions and limitations under * the License. */ - package com.google.cloud.dataflow.sdk.util; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import org.joda.time.Instant; -import org.joda.time.format.PeriodFormat; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import com.google.cloud.dataflow.sdk.transforms.DoFn.ProcessContext; /** - * Runs a DoFn by constructing the appropriate contexts and passing them in. - * - * @param the type of the DoFn's (main) input elements - * @param the type of the DoFn's (main) output elements + * An wrapper interface that represents the execution of a {@link DoFn}. */ -public class DoFnRunner { - - /** Information about how to create output receivers and output to them. */ - public interface OutputManager { - - /** Outputs a single element to the receiver indicated by the given {@link TupleTag}. */ - public void output(TupleTag tag, WindowedValue output); - } - - /** The DoFn being run. */ - public final DoFn fn; - - /** The context used for running the DoFn. */ - public final DoFnContext context; - - protected DoFnRunner( - PipelineOptions options, - DoFn fn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - this.fn = fn; - this.context = new DoFnContext<>( - options, - fn, - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - windowingStrategy == null ? null : windowingStrategy.getWindowFn()); - } - - public static DoFnRunner create( - PipelineOptions options, - DoFn fn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - return new DoFnRunner<>( - options, fn, sideInputReader, outputManager, - mainOutputTag, sideOutputTags, stepContext, addCounterMutator, windowingStrategy); - } - +public interface DoFnRunner { /** - * An implementation of {@link OutputManager} using simple lists, for testing and in-memory - * contexts such as the {@link com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner}. + * Prepares and calls {@link DoFn#startBundle}. */ - public static class ListOutputManager implements OutputManager { - - private Map, List>> outputLists = Maps.newHashMap(); - - @Override - public void output(TupleTag tag, WindowedValue output) { - @SuppressWarnings({"rawtypes", "unchecked"}) - List> outputList = (List) outputLists.get(tag); - - if (outputList == null) { - outputList = Lists.newArrayList(); - @SuppressWarnings({"rawtypes", "unchecked"}) - List> untypedList = (List) outputList; - outputLists.put(tag, untypedList); - } - - outputList.add(output); - } - - public List> getOutput(TupleTag tag) { - // Safe cast by design, inexpressible in Java without rawtypes - @SuppressWarnings({"rawtypes", "unchecked"}) - List> outputList = (List) outputLists.get(tag); - return (outputList != null) ? outputList : Collections.>emptyList(); - } - } - - /** Calls {@link DoFn#startBundle}. */ - public void startBundle() { - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.startBundle(context); - } catch (Throwable t) { - // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); - } - } + public void startBundle(); /** - * Calls {@link DoFn#processElement} with a ProcessContext containing - * the current element. + * Calls {@link DoFn#processElement} with a {@link ProcessContext} containing the current element. */ - public void processElement(WindowedValue elem) { - // Setup new thread local logging before running user code, and restore it after. - // Needs to happen here (per-element) since fusion may be running this as part of a call to - // output in an earlier step. - String previousStepName = DataflowWorkerLoggingMDC.getStepName(); - DataflowWorkerLoggingMDC.setStepName(context.stepContext.getStepName()); - try { - if (elem.getWindows().size() <= 1 - || (!RequiresWindowAccess.class.isAssignableFrom(fn.getClass()) - && context.sideInputReader.isEmpty())) { - invokeProcessElement(elem); - } else { - // We could modify the windowed value (and the processContext) to - // avoid repeated allocations, but this is more straightforward. - for (BoundedWindow window : elem.getWindows()) { - invokeProcessElement(WindowedValue.of( - elem.getValue(), elem.getTimestamp(), window, elem.getPane())); - } - } - } finally { - DataflowWorkerLoggingMDC.setStepName(previousStepName); - } - } - - protected void invokeProcessElement(WindowedValue elem) { - DoFn.ProcessContext processContext = createProcessContext(elem); - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.processElement(processContext); - } catch (Throwable t) { - // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); - } - } - - /** Calls {@link DoFn#finishBundle}. */ - public void finishBundle() { - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.finishBundle(context); - } catch (Throwable t) { - // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); - } - } + public void processElement(WindowedValue elem); /** - * A concrete implementation of {@link DoFn.Context} used for running - * a {@link DoFn}. - * - * @param the type of the DoFn's (main) input elements - * @param the type of the DoFn's (main) output elements + * Calls {@link DoFn#finishBundle} and performs additional tasks, such as + * flushing in-memory states. */ - private static class DoFnContext - extends DoFn.Context { - private static final int MAX_SIDE_OUTPUTS = 1000; - - final PipelineOptions options; - final DoFn fn; - final SideInputReader sideInputReader; - final OutputManager outputManager; - final TupleTag mainOutputTag; - final StepContext stepContext; - final CounterSet.AddCounterMutator addCounterMutator; - final WindowFn windowFn; - - /** - * The set of known output tags, some of which may be undeclared, so we can throw an - * exception when it exceeds {@link #MAX_SIDE_OUTPUTS}. - */ - private Set> outputTags; - - public DoFnContext(PipelineOptions options, - DoFn fn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowFn windowFn) { - fn.super(); - this.options = options; - this.fn = fn; - this.sideInputReader = sideInputReader; - this.outputManager = outputManager; - this.mainOutputTag = mainOutputTag; - this.outputTags = Sets.newHashSet(); - - outputTags.add(mainOutputTag); - for (TupleTag sideOutputTag : sideOutputTags) { - outputTags.add(sideOutputTag); - } - - this.stepContext = stepContext; - this.addCounterMutator = addCounterMutator; - this.windowFn = windowFn; - super.setupDelegateAggregators(); - } - - ////////////////////////////////////////////////////////////////////////////// - - @Override - public PipelineOptions getPipelineOptions() { - return options; - } - - WindowedValue makeWindowedValue( - T output, Instant timestamp, Collection windows, PaneInfo pane) { - final Instant inputTimestamp = timestamp; - - if (timestamp == null) { - timestamp = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - if (windows == null) { - try { - // The windowFn can never succeed at accessing the element, so its type does not - // matter here - @SuppressWarnings("unchecked") - WindowFn objectWindowFn = (WindowFn) windowFn; - windows = objectWindowFn.assignWindows(objectWindowFn.new AssignContext() { - @Override - public Object element() { - throw new UnsupportedOperationException( - "WindowFn attempted to access input element when none was available"); - } - - @Override - public Instant timestamp() { - if (inputTimestamp == null) { - throw new UnsupportedOperationException( - "WindowFn attempted to access input timestamp when none was available"); - } - return inputTimestamp; - } - - @Override - public Collection windows() { - throw new UnsupportedOperationException( - "WindowFn attempted to access input windows when none were available"); - } - }); - } catch (Exception e) { - Throwables.propagateIfInstanceOf(e, UserCodeException.class); - throw new UserCodeException(e); - } - } - - return WindowedValue.of(output, timestamp, windows, pane); - } - - public T sideInput(PCollectionView view, BoundedWindow mainInputWindow) { - if (!sideInputReader.contains(view)) { - throw new IllegalArgumentException("calling sideInput() with unknown view"); - } - BoundedWindow sideInputWindow = - view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(mainInputWindow); - return sideInputReader.get(view, sideInputWindow); - } - - void outputWindowedValue( - OutputT output, - Instant timestamp, - Collection windows, - PaneInfo pane) { - outputWindowedValue(makeWindowedValue(output, timestamp, windows, pane)); - } - - void outputWindowedValue(WindowedValue windowedElem) { - outputManager.output(mainOutputTag, windowedElem); - if (stepContext != null) { - stepContext.noteOutput(windowedElem); - } - } - - protected void sideOutputWindowedValue(TupleTag tag, - T output, - Instant timestamp, - Collection windows, - PaneInfo pane) { - sideOutputWindowedValue(tag, makeWindowedValue(output, timestamp, windows, pane)); - } - - protected void sideOutputWindowedValue(TupleTag tag, WindowedValue windowedElem) { - if (!outputTags.contains(tag)) { - // This tag wasn't declared nor was it seen before during this execution. - // Thus, this must be a new, undeclared and unconsumed output. - // To prevent likely user errors, enforce the limit on the number of side - // outputs. - if (outputTags.size() >= MAX_SIDE_OUTPUTS) { - throw new IllegalArgumentException( - "the number of side outputs has exceeded a limit of " + MAX_SIDE_OUTPUTS); - } - outputTags.add(tag); - } - - outputManager.output(tag, windowedElem); - if (stepContext != null) { - stepContext.noteSideOutput(tag, windowedElem); - } - } - - // Following implementations of output, outputWithTimestamp, and sideOutput - // are only accessible in DoFn.startBundle and DoFn.finishBundle, and will be shadowed by - // ProcessContext's versions in DoFn.processElement. - @Override - public void output(OutputT output) { - outputWindowedValue(output, null, null, PaneInfo.NO_FIRING); - } - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - outputWindowedValue(output, timestamp, null, PaneInfo.NO_FIRING); - } - - @Override - public void sideOutput(TupleTag tag, T output) { - Preconditions.checkNotNull(tag, "TupleTag passed to sideOutput cannot be null"); - sideOutputWindowedValue(tag, output, null, null, PaneInfo.NO_FIRING); - } - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - Preconditions.checkNotNull(tag, "TupleTag passed to sideOutputWithTimestamp cannot be null"); - sideOutputWindowedValue(tag, output, timestamp, null, PaneInfo.NO_FIRING); - } - - private String generateInternalAggregatorName(String userName) { - boolean system = fn.getClass().isAnnotationPresent(SystemDoFnInternal.class); - return (system ? "" : "user-") + stepContext.getStepName() + "-" + userName; - } - - @Override - protected Aggregator createAggregatorInternal( - String name, CombineFn combiner) { - Preconditions.checkNotNull(combiner, - "Combiner passed to createAggregator cannot be null"); - return new CounterAggregator<>(generateInternalAggregatorName(name), - combiner, addCounterMutator); - } - } - - /** - * Returns a new {@link DoFn.ProcessContext} for the given element. - */ - protected DoFn.ProcessContext createProcessContext(WindowedValue elem) { - return new DoFnProcessContext(fn, context, elem); - } + public void finishBundle(); /** - * A concrete implementation of {@link DoFn.ProcessContext} used for - * running a {@link DoFn} over a single element. - * - * @param the type of the DoFn's (main) input elements - * @param the type of the DoFn's (main) output elements + * An internal interface for signaling that a {@link DoFn} requires late data dropping. */ - static class DoFnProcessContext - extends DoFn.ProcessContext { - - - final DoFn fn; - final DoFnContext context; - final WindowedValue windowedValue; - - public DoFnProcessContext(DoFn fn, - DoFnContext context, - WindowedValue windowedValue) { - fn.super(); - this.fn = fn; - this.context = context; - this.windowedValue = windowedValue; - } - - @Override - public PipelineOptions getPipelineOptions() { - return context.getPipelineOptions(); - } - - @Override - public InputT element() { - return windowedValue.getValue(); - } - - @Override - public T sideInput(PCollectionView view) { - Preconditions.checkNotNull(view, "View passed to sideInput cannot be null"); - Iterator windowIter = windows().iterator(); - BoundedWindow window; - if (!windowIter.hasNext()) { - if (context.windowFn instanceof GlobalWindows) { - // TODO: Remove this once GroupByKeyOnly no longer outputs elements - // without windows - window = GlobalWindow.INSTANCE; - } else { - throw new IllegalStateException( - "sideInput called when main input element is not in any windows"); - } - } else { - window = windowIter.next(); - if (windowIter.hasNext()) { - throw new IllegalStateException( - "sideInput called when main input element is in multiple windows"); - } - } - return context.sideInput(view, window); - } - - @Override - public BoundedWindow window() { - if (!(fn instanceof RequiresWindowAccess)) { - throw new UnsupportedOperationException( - "window() is only available in the context of a DoFn marked as RequiresWindow."); - } - return Iterables.getOnlyElement(windows()); - } - - @Override - public PaneInfo pane() { - return windowedValue.getPane(); - } - - @Override - public void output(OutputT output) { - context.outputWindowedValue(windowedValue.withValue(output)); - } - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - checkTimestamp(timestamp); - context.outputWindowedValue(output, timestamp, - windowedValue.getWindows(), windowedValue.getPane()); - } - - void outputWindowedValue( - OutputT output, - Instant timestamp, - Collection windows, - PaneInfo pane) { - context.outputWindowedValue(output, timestamp, windows, pane); - } - - @Override - public void sideOutput(TupleTag tag, T output) { - Preconditions.checkNotNull(tag, "Tag passed to sideOutput cannot be null"); - context.sideOutputWindowedValue(tag, windowedValue.withValue(output)); - } - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - Preconditions.checkNotNull(tag, "Tag passed to sideOutputWithTimestamp cannot be null"); - checkTimestamp(timestamp); - context.sideOutputWindowedValue( - tag, output, timestamp, windowedValue.getWindows(), windowedValue.getPane()); - } - - @Override - public Instant timestamp() { - return windowedValue.getTimestamp(); - } - - public Collection windows() { - return windowedValue.getWindows(); - } - - private void checkTimestamp(Instant timestamp) { - if (timestamp.isBefore(windowedValue.getTimestamp().minus(fn.getAllowedTimestampSkew()))) { - throw new IllegalArgumentException(String.format( - "Cannot output with timestamp %s. Output timestamps must be no earlier than the " - + "timestamp of the current input (%s) minus the allowed skew (%s). See the " - + "DoFn#getAllowedTimestampSkew() Javadoc for details on changing the allowed skew.", - timestamp, windowedValue.getTimestamp(), - PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod()))); - } - } - - @Override - public WindowingInternals windowingInternals() { - return new WindowingInternals() { - @Override - public void outputWindowedValue(OutputT output, Instant timestamp, - Collection windows, PaneInfo pane) { - context.outputWindowedValue(output, timestamp, windows, pane); - } - - @Override - public Collection windows() { - return windowedValue.getWindows(); - } - - @Override - public PaneInfo pane() { - return windowedValue.getPane(); - } - - @Override - public TimerInternals timerInternals() { - return context.stepContext.timerInternals(); - } - - @Override - public void writePCollectionViewData( - TupleTag tag, - Iterable> data, - Coder elemCoder) throws IOException { - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) context.windowFn.windowCoder(); - - context.stepContext.writePCollectionViewData( - tag, data, IterableCoder.of(WindowedValue.getFullCoder(elemCoder, windowCoder)), - window(), windowCoder); - } - - @Override - public StateInternals stateInternals() { - return context.stepContext.stateInternals(); - } - }; - } - - @Override - protected Aggregator - createAggregatorInternal( - String name, CombineFn combiner) { - return context.createAggregatorInternal(name, combiner); - } - } + public interface RequiresLateDataDropping {} } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java new file mode 100644 index 0000000000..d4954e298a --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -0,0 +1,559 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.IterableCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.StateInternals; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.base.Preconditions; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import org.joda.time.Instant; +import org.joda.time.format.PeriodFormat; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A base implementation of {@link DoFnRunner}. + * + *

Sub-classes should override {@link #invokeProcessElement}. + */ +public abstract class DoFnRunnerBase implements DoFnRunner { + + /** The DoFn being run. */ + public final DoFn fn; + + /** The context used for running the DoFn. */ + public final DoFnContext context; + + protected DoFnRunnerBase( + PipelineOptions options, + DoFn fn, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator, + WindowingStrategy windowingStrategy) { + this.fn = fn; + this.context = new DoFnContext<>( + options, + fn, + sideInputReader, + outputManager, + mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator, + windowingStrategy == null ? null : windowingStrategy.getWindowFn()); + } + + /** + * An implementation of {@code OutputManager} using simple lists, for testing and in-memory + * contexts such as the {@link DirectPipelineRunner}. + */ + public static class ListOutputManager implements OutputManager { + + private Map, List>> outputLists = Maps.newHashMap(); + + @Override + public void output(TupleTag tag, WindowedValue output) { + @SuppressWarnings({"rawtypes", "unchecked"}) + List> outputList = (List) outputLists.get(tag); + + if (outputList == null) { + outputList = Lists.newArrayList(); + @SuppressWarnings({"rawtypes", "unchecked"}) + List> untypedList = (List) outputList; + outputLists.put(tag, untypedList); + } + + outputList.add(output); + } + + public List> getOutput(TupleTag tag) { + // Safe cast by design, inexpressible in Java without rawtypes + @SuppressWarnings({"rawtypes", "unchecked"}) + List> outputList = (List) outputLists.get(tag); + return (outputList != null) ? outputList : Collections.>emptyList(); + } + } + + @Override + public void startBundle() { + // This can contain user code. Wrap it in case it throws an exception. + try { + fn.startBundle(context); + } catch (Throwable t) { + // Exception in user code. + Throwables.propagateIfInstanceOf(t, UserCodeException.class); + throw new UserCodeException(t); + } + } + + @Override + public void processElement(WindowedValue elem) { + // Setup new thread local logging before running user code, and restore it after. + // Needs to happen here (per-element) since fusion may be running this as part of a call to + // output in an earlier step. + String previousStepName = DataflowWorkerLoggingMDC.getStepName(); + DataflowWorkerLoggingMDC.setStepName(context.stepContext.getStepName()); + try { + if (elem.getWindows().size() <= 1 + || (!RequiresWindowAccess.class.isAssignableFrom(fn.getClass()) + && context.sideInputReader.isEmpty())) { + invokeProcessElement(elem); + } else { + // We could modify the windowed value (and the processContext) to + // avoid repeated allocations, but this is more straightforward. + for (BoundedWindow window : elem.getWindows()) { + invokeProcessElement(WindowedValue.of( + elem.getValue(), elem.getTimestamp(), window, elem.getPane())); + } + } + } finally { + DataflowWorkerLoggingMDC.setStepName(previousStepName); + } + } + + /** + * Invokes {@link DoFn#processElement} after certain pre-processings has been done in + * {@link DoFnRunnerBase#processElement}. + */ + protected abstract void invokeProcessElement(WindowedValue elem); + + @Override + public void finishBundle() { + // This can contain user code. Wrap it in case it throws an exception. + try { + fn.finishBundle(context); + } catch (Throwable t) { + // Exception in user code. + Throwables.propagateIfInstanceOf(t, UserCodeException.class); + throw new UserCodeException(t); + } + } + + /** + * A concrete implementation of {@code DoFn.Context} used for running a {@link DoFn}. + * + * @param the type of the DoFn's (main) input elements + * @param the type of the DoFn's (main) output elements + */ + private static class DoFnContext + extends DoFn.Context { + private static final int MAX_SIDE_OUTPUTS = 1000; + + final PipelineOptions options; + final DoFn fn; + final SideInputReader sideInputReader; + final OutputManager outputManager; + final TupleTag mainOutputTag; + final StepContext stepContext; + final CounterSet.AddCounterMutator addCounterMutator; + final WindowFn windowFn; + + /** + * The set of known output tags, some of which may be undeclared, so we can throw an + * exception when it exceeds {@link #MAX_SIDE_OUTPUTS}. + */ + private Set> outputTags; + + public DoFnContext(PipelineOptions options, + DoFn fn, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator, + WindowFn windowFn) { + fn.super(); + this.options = options; + this.fn = fn; + this.sideInputReader = sideInputReader; + this.outputManager = outputManager; + this.mainOutputTag = mainOutputTag; + this.outputTags = Sets.newHashSet(); + + outputTags.add(mainOutputTag); + for (TupleTag sideOutputTag : sideOutputTags) { + outputTags.add(sideOutputTag); + } + + this.stepContext = stepContext; + this.addCounterMutator = addCounterMutator; + this.windowFn = windowFn; + super.setupDelegateAggregators(); + } + + ////////////////////////////////////////////////////////////////////////////// + + @Override + public PipelineOptions getPipelineOptions() { + return options; + } + + WindowedValue makeWindowedValue( + T output, Instant timestamp, Collection windows, PaneInfo pane) { + final Instant inputTimestamp = timestamp; + + if (timestamp == null) { + timestamp = BoundedWindow.TIMESTAMP_MIN_VALUE; + } + + if (windows == null) { + try { + // The windowFn can never succeed at accessing the element, so its type does not + // matter here + @SuppressWarnings("unchecked") + WindowFn objectWindowFn = (WindowFn) windowFn; + windows = objectWindowFn.assignWindows(objectWindowFn.new AssignContext() { + @Override + public Object element() { + throw new UnsupportedOperationException( + "WindowFn attempted to access input element when none was available"); + } + + @Override + public Instant timestamp() { + if (inputTimestamp == null) { + throw new UnsupportedOperationException( + "WindowFn attempted to access input timestamp when none was available"); + } + return inputTimestamp; + } + + @Override + public Collection windows() { + throw new UnsupportedOperationException( + "WindowFn attempted to access input windows when none were available"); + } + }); + } catch (Exception e) { + Throwables.propagateIfInstanceOf(e, UserCodeException.class); + throw new UserCodeException(e); + } + } + + return WindowedValue.of(output, timestamp, windows, pane); + } + + public T sideInput(PCollectionView view, BoundedWindow mainInputWindow) { + if (!sideInputReader.contains(view)) { + throw new IllegalArgumentException("calling sideInput() with unknown view"); + } + BoundedWindow sideInputWindow = + view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(mainInputWindow); + return sideInputReader.get(view, sideInputWindow); + } + + void outputWindowedValue( + OutputT output, + Instant timestamp, + Collection windows, + PaneInfo pane) { + outputWindowedValue(makeWindowedValue(output, timestamp, windows, pane)); + } + + void outputWindowedValue(WindowedValue windowedElem) { + outputManager.output(mainOutputTag, windowedElem); + if (stepContext != null) { + stepContext.noteOutput(windowedElem); + } + } + + protected void sideOutputWindowedValue(TupleTag tag, + T output, + Instant timestamp, + Collection windows, + PaneInfo pane) { + sideOutputWindowedValue(tag, makeWindowedValue(output, timestamp, windows, pane)); + } + + protected void sideOutputWindowedValue(TupleTag tag, WindowedValue windowedElem) { + if (!outputTags.contains(tag)) { + // This tag wasn't declared nor was it seen before during this execution. + // Thus, this must be a new, undeclared and unconsumed output. + // To prevent likely user errors, enforce the limit on the number of side + // outputs. + if (outputTags.size() >= MAX_SIDE_OUTPUTS) { + throw new IllegalArgumentException( + "the number of side outputs has exceeded a limit of " + MAX_SIDE_OUTPUTS); + } + outputTags.add(tag); + } + + outputManager.output(tag, windowedElem); + if (stepContext != null) { + stepContext.noteSideOutput(tag, windowedElem); + } + } + + // Following implementations of output, outputWithTimestamp, and sideOutput + // are only accessible in DoFn.startBundle and DoFn.finishBundle, and will be shadowed by + // ProcessContext's versions in DoFn.processElement. + @Override + public void output(OutputT output) { + outputWindowedValue(output, null, null, PaneInfo.NO_FIRING); + } + + @Override + public void outputWithTimestamp(OutputT output, Instant timestamp) { + outputWindowedValue(output, timestamp, null, PaneInfo.NO_FIRING); + } + + @Override + public void sideOutput(TupleTag tag, T output) { + Preconditions.checkNotNull(tag, "TupleTag passed to sideOutput cannot be null"); + sideOutputWindowedValue(tag, output, null, null, PaneInfo.NO_FIRING); + } + + @Override + public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { + Preconditions.checkNotNull(tag, "TupleTag passed to sideOutputWithTimestamp cannot be null"); + sideOutputWindowedValue(tag, output, timestamp, null, PaneInfo.NO_FIRING); + } + + private String generateInternalAggregatorName(String userName) { + boolean system = fn.getClass().isAnnotationPresent(SystemDoFnInternal.class); + return (system ? "" : "user-") + stepContext.getStepName() + "-" + userName; + } + + @Override + protected Aggregator createAggregatorInternal( + String name, CombineFn combiner) { + Preconditions.checkNotNull(combiner, + "Combiner passed to createAggregator cannot be null"); + return new CounterAggregator<>(generateInternalAggregatorName(name), + combiner, addCounterMutator); + } + } + + /** + * Returns a new {@code DoFn.ProcessContext} for the given element. + */ + protected DoFn.ProcessContext createProcessContext(WindowedValue elem) { + return new DoFnProcessContext(fn, context, elem); + } + + /** + * A concrete implementation of {@code DoFn.ProcessContext} used for + * running a {@link DoFn} over a single element. + * + * @param the type of the DoFn's (main) input elements + * @param the type of the DoFn's (main) output elements + */ + static class DoFnProcessContext + extends DoFn.ProcessContext { + + + final DoFn fn; + final DoFnContext context; + final WindowedValue windowedValue; + + public DoFnProcessContext(DoFn fn, + DoFnContext context, + WindowedValue windowedValue) { + fn.super(); + this.fn = fn; + this.context = context; + this.windowedValue = windowedValue; + } + + @Override + public PipelineOptions getPipelineOptions() { + return context.getPipelineOptions(); + } + + @Override + public InputT element() { + return windowedValue.getValue(); + } + + @Override + public T sideInput(PCollectionView view) { + Preconditions.checkNotNull(view, "View passed to sideInput cannot be null"); + Iterator windowIter = windows().iterator(); + BoundedWindow window; + if (!windowIter.hasNext()) { + if (context.windowFn instanceof GlobalWindows) { + // TODO: Remove this once GroupByKeyOnly no longer outputs elements + // without windows + window = GlobalWindow.INSTANCE; + } else { + throw new IllegalStateException( + "sideInput called when main input element is not in any windows"); + } + } else { + window = windowIter.next(); + if (windowIter.hasNext()) { + throw new IllegalStateException( + "sideInput called when main input element is in multiple windows"); + } + } + return context.sideInput(view, window); + } + + @Override + public BoundedWindow window() { + if (!(fn instanceof RequiresWindowAccess)) { + throw new UnsupportedOperationException( + "window() is only available in the context of a DoFn marked as RequiresWindow."); + } + return Iterables.getOnlyElement(windows()); + } + + @Override + public PaneInfo pane() { + return windowedValue.getPane(); + } + + @Override + public void output(OutputT output) { + context.outputWindowedValue(windowedValue.withValue(output)); + } + + @Override + public void outputWithTimestamp(OutputT output, Instant timestamp) { + checkTimestamp(timestamp); + context.outputWindowedValue(output, timestamp, + windowedValue.getWindows(), windowedValue.getPane()); + } + + void outputWindowedValue( + OutputT output, + Instant timestamp, + Collection windows, + PaneInfo pane) { + context.outputWindowedValue(output, timestamp, windows, pane); + } + + @Override + public void sideOutput(TupleTag tag, T output) { + Preconditions.checkNotNull(tag, "Tag passed to sideOutput cannot be null"); + context.sideOutputWindowedValue(tag, windowedValue.withValue(output)); + } + + @Override + public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { + Preconditions.checkNotNull(tag, "Tag passed to sideOutputWithTimestamp cannot be null"); + checkTimestamp(timestamp); + context.sideOutputWindowedValue( + tag, output, timestamp, windowedValue.getWindows(), windowedValue.getPane()); + } + + @Override + public Instant timestamp() { + return windowedValue.getTimestamp(); + } + + public Collection windows() { + return windowedValue.getWindows(); + } + + private void checkTimestamp(Instant timestamp) { + if (timestamp.isBefore(windowedValue.getTimestamp().minus(fn.getAllowedTimestampSkew()))) { + throw new IllegalArgumentException(String.format( + "Cannot output with timestamp %s. Output timestamps must be no earlier than the " + + "timestamp of the current input (%s) minus the allowed skew (%s). See the " + + "DoFn#getAllowedTimestampSkew() Javadoc for details on changing the allowed skew.", + timestamp, windowedValue.getTimestamp(), + PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod()))); + } + } + + @Override + public WindowingInternals windowingInternals() { + return new WindowingInternals() { + @Override + public void outputWindowedValue(OutputT output, Instant timestamp, + Collection windows, PaneInfo pane) { + context.outputWindowedValue(output, timestamp, windows, pane); + } + + @Override + public Collection windows() { + return windowedValue.getWindows(); + } + + @Override + public PaneInfo pane() { + return windowedValue.getPane(); + } + + @Override + public TimerInternals timerInternals() { + return context.stepContext.timerInternals(); + } + + @Override + public void writePCollectionViewData( + TupleTag tag, + Iterable> data, + Coder elemCoder) throws IOException { + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) context.windowFn.windowCoder(); + + context.stepContext.writePCollectionViewData( + tag, data, IterableCoder.of(WindowedValue.getFullCoder(elemCoder, windowCoder)), + window(), windowCoder); + } + + @Override + public StateInternals stateInternals() { + return context.stepContext.stateInternals(); + } + }; + } + + @Override + protected Aggregator + createAggregatorInternal( + String name, CombineFn combiner) { + return context.createAggregatorInternal(name, combiner); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java new file mode 100644 index 0000000000..a65192a23d --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItem; +import com.google.cloud.dataflow.sdk.runners.worker.LateDataDroppingDoFnRunner; +import com.google.cloud.dataflow.sdk.runners.worker.StreamingGroupAlsoByWindowsDoFn; +import com.google.cloud.dataflow.sdk.runners.worker.StreamingSideInputDoFnRunner; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.TupleTag; + +import java.util.List; + +/** + * Static utility methods that provide {@link DoFnRunner} implementations. + */ +public class DoFnRunners { + /** + * Information about how to create output receivers and output to them. + */ + public interface OutputManager { + /** + * Outputs a single element to the receiver indicated by the given {@link TupleTag}. + */ + public void output(TupleTag tag, WindowedValue output); + } + + /** + * Returns a basic implementation of {@link DoFnRunner} that works for most {@link DoFn DoFns}. + * + *

It invokes {@link DoFn#processElement} for each input. + */ + public static DoFnRunner simpleRunner( + PipelineOptions options, + DoFn fn, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator, + WindowingStrategy windowingStrategy) { + return new SimpleDoFnRunner<>( + options, fn, sideInputReader, outputManager, mainOutputTag, sideOutputTags, + stepContext, addCounterMutator, windowingStrategy); + } + + /** + * Returns an implementation of {@link DoFnRunner} that handles streaming side inputs. + * + *

It blocks and caches input elements if their side inputs are not ready. + */ + public static DoFnRunner streamingSideInputRunner( + PipelineOptions options, + DoFnInfo doFnInfo, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator) { + return new StreamingSideInputDoFnRunner<>( + options, doFnInfo, sideInputReader, outputManager, mainOutputTag, sideOutputTags, + stepContext, addCounterMutator, doFnInfo.getWindowingStrategy()); + } + + /** + * Returns an implementation of {@link DoFnRunner} that handles late data dropping. + * + *

It drops elements from expired windows before they reach the underlying {@link DoFn}. + */ + public static DoFnRunner, KV> + lateDataDroppingRunner( + PipelineOptions options, + DoFnInfo, KV> doFnInfo, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag> mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator) { + @SuppressWarnings({"unchecked"}) + StreamingGroupAlsoByWindowsDoFn streamingGabwDoFn = + (StreamingGroupAlsoByWindowsDoFn) doFnInfo.getDoFn(); + return new LateDataDroppingDoFnRunner<>( + options, streamingGabwDoFn, sideInputReader, outputManager, mainOutputTag, sideOutputTags, + stepContext, addCounterMutator, doFnInfo.getWindowingStrategy()); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java index 7c7d1e1ee7..f15a0c5e2a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java @@ -19,8 +19,10 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.values.KV; @@ -36,6 +38,13 @@ @SystemDoFnInternal public abstract class GroupAlsoByWindowsDoFn extends DoFn>>, KV> { + public static final String DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER = "DroppedDueToClosedWindow"; + public static final String DROPPED_DUE_TO_LATENESS_COUNTER = "DroppedDueToLateness"; + + protected final Aggregator droppedDueToClosedWindow = + createAggregator(DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); + protected final Aggregator droppedDueToLateness = + createAggregator(DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); /** * Create a {@link GroupAlsoByWindowsDoFn} without a combine function. Depending on the diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java index 9da4b4deb3..bb3b2194b6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java @@ -16,9 +16,7 @@ package com.google.cloud.dataflow.sdk.util; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.collect.Iterables; @@ -35,11 +33,6 @@ class GroupAlsoByWindowsViaOutputBufferDoFn extends GroupAlsoByWindowsDoFn { - private final Aggregator droppedDueToClosedWindow = - createAggregator(ReduceFnRunner.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); - private final Aggregator droppedDueToLateness = - createAggregator(ReduceFnRunner.DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); - private final WindowingStrategy strategy; private SystemReduceFn.Factory reduceFnFactory; @@ -63,7 +56,7 @@ public void processElement( ReduceFnRunner runner = new ReduceFnRunner<>( key, strategy, timerInternals, c.windowingInternals(), - droppedDueToClosedWindow, droppedDueToLateness, reduceFnFactory.create(key)); + droppedDueToClosedWindow, reduceFnFactory.create(key)); Iterable>> chunks = Iterables.partition(c.element().getValue(), 1000); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index a5cd11b442..54906b1e5c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -71,15 +71,11 @@ * @param The type of windows this operates on. */ public class ReduceFnRunner { - public static final String DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER = "DroppedDueToClosedWindow"; - public static final String DROPPED_DUE_TO_LATENESS_COUNTER = "DroppedDueToLateness"; - private final WindowingStrategy windowingStrategy; private final WindowingInternals> windowingInternals; private final Aggregator droppedDueToClosedWindow; - private final Aggregator droppedDueToLateness; private final K key; @@ -174,14 +170,13 @@ public class ReduceFnRunner { public ReduceFnRunner(K key, WindowingStrategy windowingStrategy, TimerInternals timerInternals, WindowingInternals> windowingInternals, - Aggregator droppedDueToClosedWindow, Aggregator droppedDueToLateness, + Aggregator droppedDueToClosedWindow, ReduceFn reduceFn) { this.key = key; this.timerInternals = timerInternals; this.paneInfoTracker = new PaneInfoTracker(timerInternals); this.windowingInternals = windowingInternals; this.droppedDueToClosedWindow = droppedDueToClosedWindow; - this.droppedDueToLateness = droppedDueToLateness; this.reduceFn = reduceFn; @SuppressWarnings("unchecked") @@ -264,13 +259,6 @@ public void persist() { activeWindows.persist(); } - /** Is {@code window} expired w.r.t. the garbage collection watermark? */ - private boolean canDropDueToExpiredWindow(W window) { - Instant inputWM = timerInternals.currentInputWatermarkTime(); - return inputWM != null - && window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()).isBefore(inputWM); - } - /** * Extract the windows associated with the values, and invoke merge. */ @@ -289,12 +277,6 @@ private void collectAndMergeWindows(Iterable> values) { @SuppressWarnings("unchecked") W window = (W) untypedWindow; - if (canDropDueToExpiredWindow(window)) { - // This element is too late to contribute to this window. - // We will update the counter for this in the corresponding processElement call. - continue; - } - ReduceFn.Context context = contextFactory.base(window); if (triggerRunner.isClosed(context.state())) { // This window has already been closed. @@ -389,19 +371,9 @@ private Collection processElement(WindowedValue value) { for (BoundedWindow untypedWindow : value.getWindows()) { @SuppressWarnings("unchecked") W window = (W) untypedWindow; - if (canDropDueToExpiredWindow(window)) { - // The element is too late for this window. - droppedDueToLateness.addValue(1L); - WindowTracing.debug( - "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since too far behind inputWatermark:{}; outputWatermark:{}", - value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - } else { - W active = activeWindows.representative(window); - Preconditions.checkState(active != null, "Window %s should have been added", window); - windows.add(active); - } + W active = activeWindows.representative(window); + Preconditions.checkState(active != null, "Window %s should have been added", window); + windows.add(active); } // Prefetch in each of the windows if we're going to need to process triggers diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java new file mode 100644 index 0000000000..66824e39f2 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; +import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.base.Throwables; + +import java.util.List; + +/** + * Runs a {@link DoFn} by constructing the appropriate contexts and passing them in. + * + * @param the type of the DoFn's (main) input elements + * @param the type of the DoFn's (main) output elements + */ +public class SimpleDoFnRunner extends DoFnRunnerBase{ + + protected SimpleDoFnRunner(PipelineOptions options, DoFn fn, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag mainOutputTag, List> sideOutputTags, StepContext stepContext, + AddCounterMutator addCounterMutator, WindowingStrategy windowingStrategy) { + super(options, fn, sideInputReader, outputManager, mainOutputTag, sideOutputTags, stepContext, + addCounterMutator, windowingStrategy); + } + + @Override + protected void invokeProcessElement(WindowedValue elem) { + DoFn.ProcessContext processContext = createProcessContext(elem); + // This can contain user code. Wrap it in case it throws an exception. + try { + fn.processElement(processContext); + } catch (Throwable t) { + // Exception in user code. + Throwables.propagateIfInstanceOf(t, UserCodeException.class); + throw new UserCodeException(t); + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java index 8b9b7e0a4a..7cd5f82340 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java @@ -16,7 +16,7 @@ package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItem.KeyedWorkItemCoder; +import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItems.FakeKeyedWorkItemCoder; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -38,7 +38,7 @@ private TimerOrElement() {} * {@code com.google.cloud.dataflow.sdk.util.TimerOrElement$TimerOrElementCoder} and we'd like to * be able to rename/move that without breaking things. */ - public static class TimerOrElementCoder extends KeyedWorkItemCoder { + public static class TimerOrElementCoder extends FakeKeyedWorkItemCoder { private TimerOrElementCoder(Coder elemCoder) { super(elemCoder); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemTest.java index 60a151c1dd..8f436df0ba 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemTest.java @@ -88,8 +88,8 @@ public void testElementIteration() throws Exception { chunk2.setSourceComputationId("computation"); addElement(chunk2, 6, "earth", WINDOW_1, paneInfo(1)); - KeyedWorkItem keyedWorkItem = - KeyedWorkItem.workItem(KEY, workItem.build(), WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); + KeyedWorkItem keyedWorkItem = KeyedWorkItems.windmillWorkItem( + KEY, workItem.build(), WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); assertThat(keyedWorkItem.elementsIterable(), Matchers.contains( WindowedValue.of("hello", new Instant(5), WINDOW_1, paneInfo(0)), @@ -126,8 +126,8 @@ public void testTimerOrdering() throws Exception { .build()) .build(); - KeyedWorkItem keyedWorkItem = - KeyedWorkItem.workItem(KEY, workItem, WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); + KeyedWorkItem keyedWorkItem = + KeyedWorkItems.windmillWorkItem(KEY, workItem, WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); assertThat(keyedWorkItem.timersIterable(), Matchers.contains( makeTimer(STATE_NAMESPACE_1, 1, TimeDomain.EVENT_TIME), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java index 0c56886d07..b0714e7b80 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java @@ -50,7 +50,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.dataflow.CountingSource; import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; -import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItem.KeyedWorkItemCoder; +import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItems.FakeKeyedWorkItemCoder; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItemCommitRequest; @@ -161,7 +161,7 @@ private String dataStringForIndex(long index) { private ParallelInstruction makeWindowingSourceInstruction(Coder coder) { CloudObject encodedCoder = FullWindowedValueCoder.of( - KeyedWorkItemCoder.of(coder), IntervalWindow.getCoder()).asCloudObject(); + FakeKeyedWorkItemCoder.of(coder), IntervalWindow.getCoder()).asCloudObject(); return new ParallelInstruction() .setSystemName(DEFAULT_SOURCE_SYSTEM_NAME) .setRead(new ReadInstruction().setSource( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java index 1c6edd4a74..ae185f4b13 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java @@ -19,6 +19,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -43,7 +44,10 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; +import com.google.cloud.dataflow.sdk.util.DoFnInfo; import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.NullSideInputReader; import com.google.cloud.dataflow.sdk.util.ReshuffleTriggerTest; @@ -121,8 +125,8 @@ public StepContext createStepContext( @Test public void testEmpty() throws Exception { TupleTag>> outputTag = new TupleTag<>(); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); - DoFnRunner, KV>> runner = + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + DoFnRunner, KV>> runner = makeRunner( outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); @@ -163,18 +167,18 @@ private void addElement( .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(timestamp)); } - private WindowedValue> createValue( + private WindowedValue> createValue( WorkItem.Builder workItem, Coder valueCoder) { @SuppressWarnings({"unchecked", "rawtypes"}) Coder> wildcardWindowsCoder = (Coder) windowsCoder; - return WindowedValue.valueInEmptyWindows(KeyedWorkItem.workItem( + return WindowedValue.valueInEmptyWindows(KeyedWorkItems.windmillWorkItem( KEY, workItem.build(), windowCoder, wildcardWindowsCoder, valueCoder)); } @Test public void testFixedWindows() throws Exception { TupleTag>> outputTag = new TupleTag<>(); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); - DoFnRunner, KV>> runner = + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + DoFnRunner, KV>> runner = makeRunner( outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); @@ -226,14 +230,16 @@ private WindowedValue> createValue( @Test public void testSlidingWindows() throws Exception { TupleTag>> outputTag = new TupleTag<>(); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); - DoFnRunner, KV>> runner = + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + DoFnRunner, KV>> runner = makeRunner( outputTag, outputManager, WindowingStrategy.of( SlidingWindows.of(Duration.millis(20)).every(Duration.millis(10)))); + when(mockTimerInternals.currentInputWatermarkTime()).thenReturn(new Instant(5)); + runner.startBundle(); WorkItem.Builder workItem1 = WorkItem.newBuilder(); @@ -291,10 +297,87 @@ private WindowedValue> createValue( assertThat(item2.getWindows(), Matchers.contains(window(10, 30))); } + @Test public void testSlidingWindowsAndLateData() throws Exception { + TupleTag>> outputTag = new TupleTag<>(); + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + WindowingStrategy windowingStrategy = WindowingStrategy.of( + SlidingWindows.of(Duration.millis(20)).every(Duration.millis(10))); + DoFn, KV>> fn = + StreamingGroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, StringUtf8Coder.of()); + DoFnRunner, KV>> runner = + makeRunner( + outputTag, + outputManager, + windowingStrategy, + fn); + + when(mockTimerInternals.currentInputWatermarkTime()).thenReturn(new Instant(15)); + + runner.startBundle(); + + WorkItem.Builder workItem1 = WorkItem.newBuilder(); + workItem1.setKey(ByteString.copyFromUtf8(KEY)); + workItem1.setWorkToken(WORK_TOKEN); + InputMessageBundle.Builder messageBundle = workItem1.addMessageBundlesBuilder(); + messageBundle.setSourceComputationId(SOURCE_COMPUTATION_ID); + + Coder valueCoder = StringUtf8Coder.of(); + addElement(messageBundle, + Arrays.asList(window(-10, 10), window(0, 20)), new Instant(5), valueCoder, "v1"); + addElement(messageBundle, + Arrays.asList(window(-10, 10), window(0, 20)), new Instant(2), valueCoder, "v0"); + addElement(messageBundle, + Arrays.asList(window(0, 20), window(10, 30)), new Instant(15), valueCoder, "v2"); + + runner.processElement(createValue(workItem1, valueCoder)); + + runner.finishBundle(); + runner.startBundle(); + + WorkItem.Builder workItem2 = WorkItem.newBuilder(); + workItem2.setKey(ByteString.copyFromUtf8(KEY)); + workItem2.setWorkToken(WORK_TOKEN); + addTimer(workItem2, window(-10, 10), new Instant(9), Timer.Type.WATERMARK); + addTimer(workItem2, window(0, 20), new Instant(19), Timer.Type.WATERMARK); + addTimer(workItem2, window(10, 30), new Instant(29), Timer.Type.WATERMARK); + + runner.processElement(createValue(workItem2, valueCoder)); + + runner.finishBundle(); + + List>>> result = outputManager.getOutput(outputTag); + + assertEquals(3, result.size()); + + WindowedValue>> item0 = result.get(0); + assertEquals(KEY, item0.getValue().getKey()); + assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder()); + assertEquals(new Instant(9), item0.getTimestamp()); + assertThat(item0.getWindows(), Matchers.contains(window(-10, 10))); + + WindowedValue>> item1 = result.get(1); + assertEquals(KEY, item1.getValue().getKey()); + assertThat(item1.getValue().getValue(), Matchers.containsInAnyOrder("v0", "v1", "v2")); + // For this sliding window, the minimum output timestmap was 10, since we didn't want to overlap + // with the previous window that was [-10, 10). + assertEquals(new Instant(10), item1.getTimestamp()); + assertThat(item1.getWindows(), Matchers.contains(window(0, 20))); + + WindowedValue>> item2 = result.get(2); + assertEquals(KEY, item2.getValue().getKey()); + assertThat(item2.getValue().getValue(), Matchers.containsInAnyOrder("v2")); + assertEquals(new Instant(20), item2.getTimestamp()); + assertThat(item2.getWindows(), Matchers.contains(window(10, 30))); + + assertEquals( + counters.getExistingCounter("user-merge-DroppedDueToLateness").getAggregate(), + new Long(2)); + } + @Test public void testSessions() throws Exception { TupleTag>> outputTag = new TupleTag<>(); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); - DoFnRunner, KV>> runner = makeRunner( + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + DoFnRunner, KV>> runner = makeRunner( outputTag, outputManager, WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10)))); @@ -386,8 +469,8 @@ public Long extractOutput(Long accumulator) { AppliedCombineFn appliedCombineFn = AppliedCombineFn.withInputCoder( combineFn.asKeyedFn(), registry, KvCoder.of(StringUtf8Coder.of(), BigEndianLongCoder.of())); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); - DoFnRunner, KV> runner = makeRunner( + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + DoFnRunner, KV> runner = makeRunner( outputTag, outputManager, WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))), @@ -441,46 +524,47 @@ public Long extractOutput(Long accumulator) { assertThat(item1.getWindows(), Matchers.contains(window(15, 25))); } - private DoFnRunner, KV>> makeRunner( + private DoFnRunner, KV>> makeRunner( TupleTag>> outputTag, - DoFnRunner.OutputManager outputManager, - WindowingStrategy windowingStrategy) { + DoFnRunners.OutputManager outputManager, + WindowingStrategy windowingStrategy) throws Exception { - DoFn, KV>> fn = + DoFn, KV>> fn = StreamingGroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, StringUtf8Coder.of()); return makeRunner(outputTag, outputManager, windowingStrategy, fn); } - private DoFnRunner, KV> makeRunner( + private DoFnRunner, KV> makeRunner( TupleTag> outputTag, - DoFnRunner.OutputManager outputManager, + DoFnRunners.OutputManager outputManager, WindowingStrategy windowingStrategy, - AppliedCombineFn combineFn) { + AppliedCombineFn combineFn) throws Exception { - DoFn, KV> fn = + DoFn, KV> fn = StreamingGroupAlsoByWindowsDoFn.create(windowingStrategy, combineFn, StringUtf8Coder.of()); return makeRunner(outputTag, outputManager, windowingStrategy, fn); } private - DoFnRunner, KV> makeRunner( + DoFnRunner, KV> makeRunner( TupleTag> outputTag, - DoFnRunner.OutputManager outputManager, + DoFnRunners.OutputManager outputManager, WindowingStrategy windowingStrategy, - DoFn, KV> fn) { - return - DoFnRunner.create( - PipelineOptionsFactory.create(), - fn, - NullSideInputReader.empty(), - outputManager, - outputTag, - new ArrayList>(), - execContext.getOrCreateStepContext("merge", "merge", null), - counters.getAddCounterMutator(), - windowingStrategy); + DoFn, KV> fn) throws Exception { + DoFnInfo, KV> doFnInfo = + new DoFnInfo<>(fn, windowingStrategy); + + return DoFnRunners.lateDataDroppingRunner( + PipelineOptionsFactory.create(), + doFnInfo, + NullSideInputReader.empty(), + outputManager, + outputTag, + new ArrayList>(), + execContext.getOrCreateStepContext("merge", "merge", null), + counters.getAddCounterMutator()); } private IntervalWindow window(long start, long end) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java index 6bb9e5b83d..0c7cfce3cf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java @@ -33,6 +33,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.NullSideInputReader; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -89,8 +91,8 @@ public StepContext createStepContext( @Test public void testEmpty() throws Exception { TupleTag>> outputTag = new TupleTag<>(); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); - DoFnRunner, KV>> runner = + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + DoFnRunner, KV>> runner = makeRunner( outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); @@ -118,18 +120,18 @@ private void addElement( .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(timestamp)); } - private WindowedValue> createValue( + private WindowedValue> createValue( WorkItem.Builder workItem, Coder valueCoder) { @SuppressWarnings({"unchecked", "rawtypes"}) Coder> wildcardWindowsCoder = (Coder) windowsCoder; - return WindowedValue.valueInEmptyWindows(KeyedWorkItem.workItem( + return WindowedValue.valueInEmptyWindows(KeyedWorkItems.windmillWorkItem( KEY, workItem.build(), windowCoder, wildcardWindowsCoder, valueCoder)); } @Test public void testFixedWindows() throws Exception { TupleTag>> outputTag = new TupleTag<>(); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); - DoFnRunner, KV>> runner = + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); + DoFnRunner, KV>> runner = makeRunner( outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); @@ -180,25 +182,25 @@ private WindowedValue> createValue( assertThat(item3.getWindows(), Matchers.contains(window(10, 20))); } - private DoFnRunner, KV>> makeRunner( + private DoFnRunner, KV>> makeRunner( TupleTag>> outputTag, - DoFnRunner.OutputManager outputManager, + DoFnRunners.OutputManager outputManager, WindowingStrategy windowingStrategy) { - DoFn, KV>> fn = + DoFn, KV>> fn = new StreamingGroupAlsoByWindowsReshuffleDoFn<>(); return makeRunner(outputTag, outputManager, windowingStrategy, fn); } private - DoFnRunner, KV> makeRunner( + DoFnRunner, KV> makeRunner( TupleTag> outputTag, - DoFnRunner.OutputManager outputManager, + DoFnRunners.OutputManager outputManager, WindowingStrategy windowingStrategy, - DoFn, KV> fn) { + DoFn, KV> fn) { return - DoFnRunner.create( + DoFnRunners.simpleRunner( PipelineOptionsFactory.create(), fn, NullSideInputReader.empty(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java index 2f470140a8..90e5bd2693 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java @@ -40,7 +40,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; @@ -103,7 +104,7 @@ public void testSideInputReady() throws Exception { when(mockSideInputReader.contains(eq(view))).thenReturn(true); when(mockSideInputReader.get(eq(view), any(BoundedWindow.class))).thenReturn("data"); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); StreamingSideInputDoFnRunner runner = createRunner(outputManager, Arrays.asList(view)); @@ -124,7 +125,7 @@ public void testSideInputNotReady() throws Exception { eq(view), any(BoundedWindow.class), eq(SideInputState.UNKNOWN))) .thenReturn(false); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); StreamingSideInputDoFnRunner runner = createRunner(outputManager, Arrays.asList(view)); @@ -178,7 +179,7 @@ public void testSideInputNotification() throws Exception { StreamingSideInputDoFnRunner.blockedMapAddr(WINDOW_FN)); blockedMapState.set(blockedMap); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); StreamingSideInputDoFnRunner runner = createRunner(outputManager, Arrays.asList(view)); runner.watermarkHold(createWindow(0)).add(new Instant(0)); @@ -239,7 +240,7 @@ public void testMultipleSideInputs() throws Exception { when(mockSideInputReader.get(eq(view1), any(BoundedWindow.class))).thenReturn("data1"); when(mockSideInputReader.get(eq(view2), any(BoundedWindow.class))).thenReturn("data2"); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); StreamingSideInputDoFnRunner runner = createRunner(outputManager, Arrays.asList(view1, view2)); runner.watermarkHold(createWindow(0)).add(new Instant(0)); @@ -257,8 +258,9 @@ public void testMultipleSideInputs() throws Exception { assertThat(runner.elementBag(createWindow(0)).get().read(), Matchers.emptyIterable()); } + @SuppressWarnings("unchecked") private StreamingSideInputDoFnRunner - createRunner(DoFnRunner.OutputManager outputManager, List> views) + createRunner(DoFnRunners.OutputManager outputManager, List> views) throws Exception { @SuppressWarnings({"unchecked", "rawtypes"}) Iterable> typedViews = (Iterable) views; @@ -267,15 +269,16 @@ public void testMultipleSideInputs() throws Exception { new SideInputFn(views), WindowingStrategy.of(WINDOW_FN), typedViews, StringUtf8Coder.of()); - return new StreamingSideInputDoFnRunner( - PipelineOptionsFactory.create(), - doFnInfo, - mockSideInputReader, - outputManager, - mainOutputTag, - Arrays.>asList(), - stepContext, - null); + return (StreamingSideInputDoFnRunner) + DoFnRunners.streamingSideInputRunner( + PipelineOptionsFactory.create(), + doFnInfo, + mockSideInputReader, + outputManager, + mainOutputTag, + Arrays.>asList(), + stepContext, + null); } private static class SideInputFn extends DoFn { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java index 34edb2489e..ce06299d61 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java @@ -660,7 +660,7 @@ List>> runGABW( Collection> values) { TupleTag> outputTag = new TupleTag<>(); - DoFnRunner.ListOutputManager outputManager = new DoFnRunner.ListOutputManager(); + DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); DoFnRunner>>, KV> runner = makeRunner( @@ -694,12 +694,12 @@ List>> runGABW( GroupAlsoByWindowsDoFn fn, WindowingStrategy windowingStrategy, TupleTag> outputTag, - DoFnRunner.OutputManager outputManager) { + DoFnRunners.OutputManager outputManager) { ExecutionContext executionContext = DirectModeExecutionContext.create(); CounterSet counters = new CounterSet(); - return DoFnRunner.create( + return DoFnRunners.simpleRunner( PipelineOptionsFactory.create(), fn, NullSideInputReader.empty(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index c68d67670c..ced9de5413 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -136,7 +136,6 @@ public void testOnElementBufferingDiscarding() throws Exception { injectElement(tester, 4); assertEquals(1, tester.getElementsDroppedDueToClosedWindow()); - assertEquals(0, tester.getElementsDroppedDueToLateness()); } @Test @@ -255,7 +254,6 @@ public void testWatermarkHoldAndLateData() throws Exception { // Holding for the end-of-window transition. assertEquals(new Instant(9), tester.getWatermarkHold()); // Nothing dropped. - assertEquals(0, tester.getElementsDroppedDueToLateness()); assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); // Input watermark -> 4, output watermark should advance that far as well @@ -314,7 +312,6 @@ public void testWatermarkHoldAndLateData() throws Exception { // Because we're about to expire the window, we output it. when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); injectElement(tester, 8); - assertEquals(0, tester.getElementsDroppedDueToLateness()); assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); // Exceed the GC limit, triggering the last pane to be fired @@ -334,17 +331,8 @@ public void testWatermarkHoldAndLateData() throws Exception { assertThat( output.get(0).getPane(), equalTo(PaneInfo.createPane(false, true, Timing.LATE, 3, 1))); - - // All very late -- gets dropped, because the window is expired - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); assertEquals(new Instant(50), tester.getOutputWatermark()); assertEquals(null, tester.getWatermarkHold()); - injectElement(tester, 2); - assertEquals(null, tester.getWatermarkHold()); - assertThat(tester.extractOutput(), emptyIterable()); - - assertEquals(1, tester.getElementsDroppedDueToLateness()); - assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); // Late timers are ignored tester.fireTimer(new IntervalWindow(new Instant(0), new Instant(10)), new Instant(12), @@ -580,44 +568,6 @@ public void testMergeBeforeFinalizing() throws Exception { equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); } - /** - * Tests that when data is assigned to multiple windows but some of those windows have expired, - * then the data is dropped and counted accurately. - */ - @Test - public void testDropDataMultipleWindowsExpiredWindow() throws Exception { - ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( - WindowingStrategy.of( - SlidingWindows.of(Duration.millis(100)).every(Duration.millis(30))) - .withAllowedLateness(Duration.millis(10))); - - tester.injectElements( - // assigned to [-60, 40), [-30, 70), [0, 100) - TimestampedValue.of(10, new Instant(23)), - // assigned to [-30, 70), [0, 100), [30, 130) - TimestampedValue.of(12, new Instant(40))); - - assertEquals(0, tester.getElementsDroppedDueToLateness()); - - tester.advanceInputWatermark(new Instant(70)); - - - tester.injectElements( - // assigned to [-30, 70), [0, 100), [30, 130) - // but [-30, 70) has past but is not is expired - TimestampedValue.of(14, new Instant(50))); - - assertEquals(0, tester.getElementsDroppedDueToLateness()); - - tester.advanceInputWatermark(new Instant(110)); - - // assigned to [-30, 70), [0, 100), [30, 130) - // but the first two are expired - tester.injectElements(TimestampedValue.of(16, new Instant(40))); - - assertEquals(2, tester.getElementsDroppedDueToLateness()); - } - /** * Tests that when data is assigned to multiple windows but some of those windows have * had their triggers finish, then the data is dropped and counted accurately. @@ -697,7 +647,6 @@ public void testIdempotentEmptyPanesDiscarding() throws Exception { tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - assertEquals(0, tester.getElementsDroppedDueToLateness()); } @Test @@ -744,7 +693,6 @@ public void testIdempotentEmptyPanesAccumulating() throws Exception { tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - assertEquals(0, tester.getElementsDroppedDueToLateness()); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index bb889d8283..c2220051d0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -99,9 +99,7 @@ public class ReduceFnTester { private ExecutableTrigger executableTrigger; private final InMemoryLongSumAggregator droppedDueToClosedWindow = - new InMemoryLongSumAggregator(ReduceFnRunner.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER); - private final InMemoryLongSumAggregator droppedDueToLateness = - new InMemoryLongSumAggregator(ReduceFnRunner.DROPPED_DUE_TO_LATENESS_COUNTER); + new InMemoryLongSumAggregator(GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER); public static ReduceFnTester, W> nonCombining(WindowingStrategy windowingStrategy) throws Exception { @@ -167,7 +165,7 @@ private ReduceFnTester(WindowingStrategy wildcardStrategy, ReduceFnRunner createRunner() { return new ReduceFnRunner<>(KEY, objectStrategy, timerInternals, windowingInternals, - droppedDueToClosedWindow, droppedDueToLateness, reduceFn); + droppedDueToClosedWindow, reduceFn); } public ExecutableTrigger getTrigger() { @@ -264,10 +262,6 @@ public long getElementsDroppedDueToClosedWindow() { return droppedDueToClosedWindow.getSum(); } - public long getElementsDroppedDueToLateness() { - return droppedDueToLateness.getSum(); - } - /** * How many panes do we have in the output? */ From e468caddd803b0dd5aaa10a0dfa92f15bad4962e Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 25 Jan 2016 16:07:59 -0800 Subject: [PATCH 036/751] DatastoreIO: do not split when QuerySplitter fails As opposed to throwing an exception. Fixes #101. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=112999725 --- .../cloud/dataflow/sdk/io/DatastoreIO.java | 10 +++++- .../dataflow/sdk/io/DatastoreIOTest.java | 35 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java index 9b784d0bcd..f618bc9d63 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java @@ -326,8 +326,16 @@ public List splitIntoBundles(long desiredBundleSizeBytes, PipelineOption return ImmutableList.of(this); } + List datastoreSplits; + try { + datastoreSplits = getSplitQueries(Ints.checkedCast(numSplits), options); + } catch (IllegalArgumentException | DatastoreException e) { + LOG.warn("Unable to parallelize the given query: {}", query, e); + return ImmutableList.of(this); + } + ImmutableList.Builder splits = ImmutableList.builder(); - for (Query splitQuery : getSplitQueries(Ints.checkedCast(numSplits), options)) { + for (Query splitQuery : datastoreSplits) { splits.add(new Source(host, datasetId, splitQuery, namespace)); } return splits.build(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java index 96e29b0ae6..4cc3ace1b5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java @@ -29,6 +29,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -52,6 +53,7 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.common.collect.Lists; @@ -97,6 +99,8 @@ public class DatastoreIOTest { @Rule public final ExpectedException thrown = ExpectedException.none(); + @Rule public final ExpectedLogs logged = ExpectedLogs.none(DatastoreIO.Source.class); + @Before public void setUp() { MockitoAnnotations.initMocks(this); @@ -330,6 +334,37 @@ public void testQueryDoesNotSplitWithLimitSet() throws Exception { verifyNoMoreInteractions(splitter); } + /** + * Tests that when {@link QuerySplitter} cannot split a query, {@link DatastoreIO} falls back to + * a single split. + */ + @Test + public void testQuerySplitterThrows() throws Exception { + // Mock query splitter that throws IllegalArgumentException + IllegalArgumentException exception = + new IllegalArgumentException("query not supported by splitter"); + QuerySplitter splitter = mock(QuerySplitter.class); + when( + splitter.getSplits( + any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class))) + .thenThrow(exception); + + Query query = Query.newBuilder().addKind(KindExpression.newBuilder().setName("myKind")).build(); + List bundles = + initialSource + .withQuery(query) + .withMockSplitter(splitter) + .withMockEstimateSizeBytes(10240L) + .splitIntoBundles(1024, testPipelineOptions(null)); + + assertEquals(1, bundles.size()); + assertEquals(query, bundles.get(0).getQuery()); + verify(splitter, times(1)) + .getSplits( + any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class)); + logged.verifyWarn("Unable to parallelize the given query", exception); + } + @Test public void testQuerySplitSizeUnavailable() throws Exception { KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); From 50f98a77634f10e6b2eb5468363133e3a0a71eff Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 25 Jan 2016 17:59:43 -0800 Subject: [PATCH 037/751] BigQueryTableInserter: retry rateLimitExceeded API calls When using BigQueryIO with a custom table per window, we may temporarily exceed BigQuery's quota. In these cases, retry for a short period of time before failing. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113010175 --- .../sdk/util/BigQueryTableInserter.java | 67 ++++- .../sdk/util/BigQueryTableInserterTest.java | 239 ++++++++++++++++++ 2 files changed, 294 insertions(+), 12 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java index 0ed22947c2..bcd972034a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java @@ -16,6 +16,10 @@ package com.google.cloud.dataflow.sdk.util; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.BackOffUtils; +import com.google.api.client.util.ExponentialBackOff; +import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableDataInsertAllRequest; @@ -28,6 +32,7 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.hadoop.util.ApiErrorExtractor; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.util.concurrent.MoreExecutors; @@ -350,6 +355,13 @@ public boolean isEmpty(TableReference ref) throws IOException { return dataList.getRows() == null || dataList.getRows().isEmpty(); } + /** + * Retry table creation up to 5 minutes (with exponential backoff) when this user is near the + * quota for table creation. This relatively innocuous behavior can happen when BigQueryIO is + * configured with a table spec function to use different tables for each window. + */ + private static final int RETRY_CREATE_TABLE_DURATION_MILLIS = (int) TimeUnit.MINUTES.toMillis(5); + /** * Tries to create the BigQuery table. * If a table with the same name already exists in the dataset, the table @@ -365,21 +377,52 @@ public boolean isEmpty(TableReference ref) throws IOException { @Nullable public Table tryCreateTable(TableReference ref, TableSchema schema) throws IOException { LOG.info("Trying to create BigQuery table: {}", BigQueryIO.toTableSpec(ref)); + BackOff backoff = + new ExponentialBackOff.Builder() + .setMaxElapsedTimeMillis(RETRY_CREATE_TABLE_DURATION_MILLIS) + .build(); - Table content = new Table(); - content.setTableReference(ref); - content.setSchema(schema); + Table table = new Table().setTableReference(ref).setSchema(schema); + return tryCreateTable(table, ref.getProjectId(), ref.getDatasetId(), backoff, Sleeper.DEFAULT); + } - try { - return client.tables() - .insert(ref.getProjectId(), ref.getDatasetId(), content) - .execute(); - } catch (IOException e) { - if (new ApiErrorExtractor().itemAlreadyExists(e)) { - LOG.info("The BigQuery table already exists."); - return null; + @VisibleForTesting + @Nullable + Table tryCreateTable( + Table table, String projectId, String datasetId, BackOff backoff, Sleeper sleeper) + throws IOException { + boolean retry = false; + while (true) { + try { + return client.tables().insert(projectId, datasetId, table).execute(); + } catch (IOException e) { + ApiErrorExtractor extractor = new ApiErrorExtractor(); + if (extractor.itemAlreadyExists(e)) { + // The table already exists, nothing to return. + return null; + } else if (extractor.rateLimited(e)) { + // The request failed because we hit a temporary quota. Back off and try again. + try { + if (BackOffUtils.next(sleeper, backoff)) { + if (!retry) { + LOG.info( + "Quota limit reached when creating table {}:{}.{}, retrying up to {} minutes", + projectId, + datasetId, + table.getTableReference().getTableId(), + TimeUnit.MILLISECONDS.toSeconds(RETRY_CREATE_TABLE_DURATION_MILLIS) / 60.0); + retry = true; + } + continue; + } + } catch (InterruptedException e1) { + // Restore interrupted state and throw the last failure. + Thread.currentThread().interrupt(); + throw e; + } + } + throw e; } - throw e; } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java new file mode 100644 index 0000000000..d53315ba66 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java @@ -0,0 +1,239 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Verify.verifyNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; +import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.json.GenericJson; +import com.google.api.client.json.Json; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.Sleeper; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.hadoop.util.RetryBoundedBackOff; +import com.google.common.collect.ImmutableList; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Tests of {@link BigQueryTableInserter}. + */ +@RunWith(JUnit4.class) +public class BigQueryTableInserterTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(BigQueryTableInserter.class); + @Mock private LowLevelHttpResponse response; + private Bigquery bigquery; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + // A mock transport that lets us mock the API responses. + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpRequest( + new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + return response; + } + }) + .build(); + + // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer. + bigquery = + new Bigquery.Builder( + transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()) + .build(); + } + + @After + public void tearDown() throws IOException { + // These three interactions happen for every request in the normal response parsing. + verify(response, atLeastOnce()).getContentEncoding(); + verify(response, atLeastOnce()).getHeaderCount(); + verify(response, atLeastOnce()).getReasonPhrase(); + verifyNoMoreInteractions(response); + } + + /** A helper to wrap a {@link GenericJson} object in a content stream. */ + private static InputStream toStream(GenericJson content) throws IOException { + return new ByteArrayInputStream(JacksonFactory.getDefaultInstance().toByteArray(content)); + } + + /** A helper that generates the error JSON payload that Google APIs produce. */ + private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, int status) { + ErrorInfo info = new ErrorInfo(); + info.setReason(reason); + info.setDomain("global"); + // GoogleJsonError contains one or more ErrorInfo objects; our utiities read the first one. + GoogleJsonError error = new GoogleJsonError(); + error.setErrors(ImmutableList.of(info)); + error.setCode(status); + // The actual JSON response is an error container. + GoogleJsonErrorContainer container = new GoogleJsonErrorContainer(); + container.setError(error); + return container; + } + + /** + * Tests that {@link BigQueryTableInserter} succeeds on the first try. + */ + @Test + public void testCreateTableSucceeds() throws IOException { + Table testTable = new Table().setDescription("a table"); + + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(200); + when(response.getContent()).thenReturn(toStream(testTable)); + + BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); + Table ret = + inserter.tryCreateTable( + new Table(), + "project", + "dataset", + new RetryBoundedBackOff(0, BackOff.ZERO_BACKOFF), + Sleeper.DEFAULT); + assertEquals(testTable, ret); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + /** + * Tests that {@link BigQueryTableInserter} succeeds when the table already exists. + */ + @Test + public void testCreateTableSucceedsAlreadyExists() throws IOException { + when(response.getStatusCode()).thenReturn(409); // 409 means already exists + + BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); + Table ret = + inserter.tryCreateTable( + new Table(), + "project", + "dataset", + new RetryBoundedBackOff(0, BackOff.ZERO_BACKOFF), + Sleeper.DEFAULT); + + assertNull(ret); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + /** + * Tests that {@link BigQueryTableInserter} retries quota rate limited attempts. + */ + @Test + public void testCreateTableRetry() throws IOException { + TableReference ref = + new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); + Table testTable = new Table().setTableReference(ref); + + // First response is 403 rate limited, second response has valid payload. + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(403).thenReturn(200); + when(response.getContent()) + .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403))) + .thenReturn(toStream(testTable)); + + BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); + Table ret = + inserter.tryCreateTable( + testTable, + "project", + "dataset", + new RetryBoundedBackOff(3, BackOff.ZERO_BACKOFF), + Sleeper.DEFAULT); + assertEquals(testTable, ret); + verify(response, times(2)).getStatusCode(); + verify(response, times(2)).getContent(); + verify(response, times(2)).getContentType(); + verifyNotNull(ret.getTableReference()); + expectedLogs.verifyInfo( + "Quota limit reached when creating table project:dataset.table, " + + "retrying up to 5.0 minutes"); + } + + /** + * Tests that {@link BigQueryTableInserter} does not retry non-rate-limited attempts. + */ + @Test + public void testCreateTableDoesNotRetry() throws IOException { + Table testTable = new Table().setDescription("a table"); + + // First response is 403 not-rate-limited, second response has valid payload but should not + // be invoked. + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(403).thenReturn(200); + when(response.getContent()) + .thenReturn(toStream(errorWithReasonAndStatus("actually forbidden", 403))) + .thenReturn(toStream(testTable)); + + thrown.expect(GoogleJsonResponseException.class); + thrown.expectMessage("actually forbidden"); + + BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); + try { + inserter.tryCreateTable( + new Table(), + "project", + "dataset", + new RetryBoundedBackOff(3, BackOff.ZERO_BACKOFF), + Sleeper.DEFAULT); + fail(); + } catch (IOException e) { + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + throw e; + } + } +} From ab733b4557f82589d661d5093a6e0c6d7905bae4 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 25 Jan 2016 20:49:12 -0800 Subject: [PATCH 038/751] AvroCoder: more efficient use of Avro APIs - Make the Encoder/Decoder factories static -- they are thread-safe and immutable. - Reuse the DirectBinaryEncoder/DirectBinaryDecoder objects across invocations to encode/decode. Though reuse is only "when possible", it's always applicable in our invocations. This change reduces the allocations of these objects from 1/element to 1/coder instance. - Remove the call to flush from encoder(), because the DirectBinaryEncoder does not need to be flushed. - Cache the objects in ThreadLocal variables for thread safety. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113018546 --- .../cloud/dataflow/sdk/coders/AvroCoder.java | 68 +++++++++++++------ 1 file changed, 48 insertions(+), 20 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java index 0afbe98fd2..91efb43f35 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java @@ -171,19 +171,42 @@ public Coder getCoder(TypeDescriptor typeDescriptor) { private final List nonDeterministicReasons; - private final DatumWriter writer; - private final DatumReader reader; - private final EncoderFactory encoderFactory = new EncoderFactory(); - private final DecoderFactory decoderFactory = new DecoderFactory(); + // Factories allocated by .get() are thread-safe and immutable. + private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); + private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); + // Cache the old encoder/decoder and let the factories reuse them when possible. To be threadsafe, + // these are ThreadLocal. This code does not need to be re-entrant as AvroCoder does not use + // an inner coder. + private final ThreadLocal decoder; + private final ThreadLocal encoder; + private final ThreadLocal> writer; + private final ThreadLocal> reader; protected AvroCoder(Class type, Schema schema) { this.type = type; this.schema = schema; - nonDeterministicReasons = new AvroDeterminismChecker() - .check(TypeDescriptor.of(type), schema); - this.reader = createDatumReader(); - this.writer = createDatumWriter(); + nonDeterministicReasons = new AvroDeterminismChecker().check(TypeDescriptor.of(type), schema); + + // Decoder and Encoder start off null for each thread. They are allocated and potentially + // reused inside encode/decode. + this.decoder = new ThreadLocal<>(); + this.encoder = new ThreadLocal<>(); + + // Reader and writer are allocated once per thread and are "final" for thread-local Coder + // instance. + this.reader = new ThreadLocal>() { + @Override + public DatumReader initialValue() { + return createDatumReader(); + } + }; + this.writer = new ThreadLocal>() { + @Override + public DatumWriter initialValue() { + return createDatumWriter(); + } + }; } /** @@ -233,17 +256,22 @@ private Object writeReplace() { } @Override - public void encode(T value, OutputStream outStream, Context context) - throws IOException { - BinaryEncoder encoder = encoderFactory.directBinaryEncoder(outStream, null); - writer.write(value, encoder); - encoder.flush(); + public void encode(T value, OutputStream outStream, Context context) throws IOException { + // Get a BinaryEncoder instance from the ThreadLocal cache and attempt to reuse it. + BinaryEncoder encoderInstance = ENCODER_FACTORY.directBinaryEncoder(outStream, encoder.get()); + // Save the potentially-new instance for reuse later. + encoder.set(encoderInstance); + writer.get().write(value, encoderInstance); + // Direct binary encoder does not buffer any data and need not be flushed. } @Override public T decode(InputStream inStream, Context context) throws IOException { - BinaryDecoder decoder = decoderFactory.directBinaryDecoder(inStream, null); - return reader.read(null, decoder); + // Get a BinaryDecoder instance from the ThreadLocal cache and attempt to reuse it. + BinaryDecoder decoderInstance = DECODER_FACTORY.directBinaryDecoder(inStream, decoder.get()); + // Save the potentially-new instance for later. + decoder.set(decoderInstance); + return reader.get().read(null, decoderInstance); } @Override @@ -272,12 +300,12 @@ public void verifyDeterministic() throws NonDeterministicException { } /** - * Returns a new DatumReader that can be used to read from - * an Avro file directly. Assumes the schema used to read is - * the same as the schema that was used when writing. + * Returns a new {@link DatumReader} that can be used to read from an Avro file directly. Assumes + * the schema used to read is the same as the schema that was used when writing. * * @deprecated For {@code AvroCoder} internal use only. */ + // TODO: once we can remove this deprecated function, inline in constructor. @Deprecated public DatumReader createDatumReader() { if (type.equals(GenericRecord.class)) { @@ -288,11 +316,11 @@ public DatumReader createDatumReader() { } /** - * Returns a new DatumWriter that can be used to write to - * an Avro file directly. + * Returns a new {@link DatumWriter} that can be used to write to an Avro file directly. * * @deprecated For {@code AvroCoder} internal use only. */ + // TODO: once we can remove this deprecated function, inline in constructor. @Deprecated public DatumWriter createDatumWriter() { if (type.equals(GenericRecord.class)) { From 46a80827cdc86c5958ade908452d084ffbeb5a50 Mon Sep 17 00:00:00 2001 From: amyu Date: Tue, 26 Jan 2016 07:12:51 -0800 Subject: [PATCH 039/751] Modify GameStats window definitions for blog post ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113051755 --- .../cloud/dataflow/examples/complete/game/GameStats.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java index d826995ac6..175af748bb 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java @@ -318,8 +318,7 @@ public void processElement(ProcessContext c) { .>into( Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap()))) .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow()) - .withAllowedLateness(Duration.ZERO) - .discardingFiredPanes()) + .withAllowedLateness(Duration.ZERO)) .apply("UserSessionSum", Sum.integersPerKey()) // Get the duration per session. .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn())) @@ -329,8 +328,7 @@ public void processElement(ProcessContext c) { .apply(Window.named("WindowToExtractSessionMean") .into( FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration()))) - .withAllowedLateness(Duration.standardMinutes(options.getAllowedLateness())) - .accumulatingFiredPanes()) + .withAllowedLateness(Duration.ZERO)) // Find the mean session duration in each window. .apply(Mean.globally().withoutDefaults()) // Write this info to a BigQuery table. From 186a7ff20f058e91ef6a6eeeb2daa3df1d8903a8 Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 26 Jan 2016 09:37:02 -0800 Subject: [PATCH 040/751] Add new property names This is towards indexed side inputs. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113064801 --- .../java/com/google/cloud/dataflow/sdk/util/PropertyNames.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java index 5a7ff3d881..59fa0e9b5c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java @@ -67,6 +67,8 @@ public class PropertyNames { public static final String IS_WRAPPER = "is_wrapper"; public static final String DISALLOW_COMBINER_LIFTING = "disallow_combiner_lifting"; public static final String NON_PARALLEL_INPUTS = "non_parallel_inputs"; + public static final String NUM_SHARD_CODERS = "num_shard_coders"; + public static final String NUM_METADATA_SHARD_CODERS = "num_metadata_shard_coders"; public static final String NUM_SHARDS = "num_shards"; public static final String OBJECT_TYPE_NAME = "@type"; public static final String OUTPUT = "output"; @@ -90,6 +92,7 @@ public class PropertyNames { public static final String START_SHUFFLE_POSITION = "start_shuffle_position"; public static final String STRIP_TRAILING_NEWLINES = "strip_trailing_newlines"; public static final String TUPLE_TAGS = "tuple_tags"; + public static final String USE_INDEXED_FORMAT = "use_indexed_format"; public static final String USER_FN = "user_fn"; public static final String USER_NAME = "user_name"; public static final String USES_KEYED_STATE = "uses_keyed_state"; From ede56efb56f53bea548691c1efa15416cfb4cfe0 Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 26 Jan 2016 21:03:25 -0800 Subject: [PATCH 041/751] Add increment support with positive infinity Add support for compare from offset and common prefix length to comparator. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113125854 --- .../dataflow/sdk/util/RandomAccessData.java | 102 ++++++++++++++++-- .../sdk/util/RandomAccessDataTest.java | 53 ++++++++- 2 files changed, 144 insertions(+), 11 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java index 4d86866ff2..6c96c8e703 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.util; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; @@ -23,6 +24,7 @@ import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.common.base.MoreObjects; import com.google.common.io.ByteStreams; +import com.google.common.primitives.UnsignedBytes; import com.fasterxml.jackson.annotation.JsonCreator; @@ -50,7 +52,9 @@ public class RandomAccessData { /** * A {@link Coder} which encodes the valid parts of this stream. * This follows the same encoding scheme as {@link ByteArrayCoder}. - * This coder is deterministic and the consistent with equals. + * This coder is deterministic and consistent with equals. + * + * This coder does not support encoding positive infinity. */ public static class RandomAccessDataCoder extends AtomicCoder { private static final RandomAccessDataCoder INSTANCE = new RandomAccessDataCoder(); @@ -63,6 +67,9 @@ public static RandomAccessDataCoder of() { @Override public void encode(RandomAccessData value, OutputStream outStream, Coder.Context context) throws CoderException, IOException { + if (value == POSITIVE_INFINITY) { + throw new CoderException("Positive infinity can not be encoded."); + } if (!context.isWholeStream) { VarInt.encode(value.size, outStream); } @@ -107,18 +114,45 @@ protected long getEncodedElementByteSize(RandomAccessData value, Coder.Context c } } + public static final UnsignedLexicographicalComparator UNSIGNED_LEXICOGRAPHICAL_COMPARATOR = + new UnsignedLexicographicalComparator(); + /** * A {@link Comparator} that compares two byte arrays lexicographically. It compares * values as a list of unsigned bytes. The first pair of values that follow any common prefix, * or when one array is a prefix of the other, treats the shorter array as the lesser. - * For example, [] < [0x01] < [0x01, 0x7F] < [0x01, 0x80] < [0x02]. + * For example, [] < [0x01] < [0x01, 0x7F] < [0x01, 0x80] < [0x02] < POSITIVE INFINITY. + * + *

Note that a token type of positive infinity is supported and is greater than + * all other {@link RandomAccessData}. */ - public static final Comparator UNSIGNED_LEXICOGRAPHICAL_COMPARATOR = - new Comparator() { + public static final class UnsignedLexicographicalComparator + implements Comparator { + // Do not instantiate + private UnsignedLexicographicalComparator() { + } + @Override public int compare(RandomAccessData o1, RandomAccessData o2) { + return compare(o1, o2, 0 /* start from the beginning */); + } + + /** + * Compare the two sets of bytes starting at the given offset. + */ + public int compare(RandomAccessData o1, RandomAccessData o2, int startOffset) { + if (o1 == o2) { + return 0; + } + if (o1 == POSITIVE_INFINITY) { + return 1; + } + if (o2 == POSITIVE_INFINITY) { + return -1; + } + int minBytesLen = Math.min(o1.size, o2.size); - for (int i = 0; i < minBytesLen; i++) { + for (int i = startOffset; i < minBytesLen; i++) { // unsigned comparison int b1 = o1.buffer[i] & 0xFF; int b2 = o2.buffer[i] & 0xFF; @@ -132,7 +166,45 @@ public int compare(RandomAccessData o1, RandomAccessData o2) { // If both lengths are equal, then both streams are equal. return o1.size - o2.size; } - }; + + /** + * Compute the length of the common prefix of the two provided sets of bytes. + */ + public int commonPrefixLength(RandomAccessData o1, RandomAccessData o2) { + int minBytesLen = Math.min(o1.size, o2.size); + for (int i = 0; i < minBytesLen; i++) { + // unsigned comparison + int b1 = o1.buffer[i] & 0xFF; + int b2 = o2.buffer[i] & 0xFF; + if (b1 != b2) { + return i; + } + } + return minBytesLen; + } + } + + /** A token type representing positive infinity. */ + static final RandomAccessData POSITIVE_INFINITY = new RandomAccessData(0); + + /** + * Returns a RandomAccessData that is the smallest value of same length which + * is strictly greater than this. Note that if this is empty or is all 0xFF then + * a token value of positive infinity is returned. + * + * The {@link UnsignedLexicographicalComparator} supports comparing {@link RandomAccessData} + * with support for positive infinitiy. + */ + public RandomAccessData increment() throws IOException { + RandomAccessData copy = copy(); + for (int i = copy.size - 1; i >= 0; --i) { + if (copy.buffer[i] != UnsignedBytes.MAX_VALUE) { + copy.buffer[i] = UnsignedBytes.checkedCast(UnsignedBytes.toInt(copy.buffer[i]) + 1); + return copy; + } + } + return POSITIVE_INFINITY; + } private static final int DEFAULT_INITIAL_BUFFER_SIZE = 128; @@ -141,10 +213,17 @@ public RandomAccessData() { this(DEFAULT_INITIAL_BUFFER_SIZE); } + /** Constructs a RandomAccessData with the initial buffer. */ + public RandomAccessData(byte[] initialBuffer) { + checkNotNull(initialBuffer); + this.buffer = initialBuffer; + this.size = initialBuffer.length; + } + /** Constructs a RandomAccessData with the given buffer size. */ public RandomAccessData(int initialBufferSize) { checkArgument(initialBufferSize >= 0, "Expected initial buffer size to be greater than zero."); - buffer = new byte[initialBufferSize]; + this.buffer = new byte[initialBufferSize]; } private byte[] buffer; @@ -220,6 +299,13 @@ public void readFrom(InputStream inStream, int offset, int length) throws IOExce size = offset + length; } + /** Returns a copy of this RandomAccessData. */ + public RandomAccessData copy() throws IOException { + RandomAccessData copy = new RandomAccessData(size); + writeTo(copy.asOutputStream(), 0, size); + return copy; + } + @Override public boolean equals(Object other) { if (other == this) { @@ -244,7 +330,7 @@ public int hashCode() { @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("buffer", buffer) + .add("buffer", Arrays.copyOf(buffer, size)) .add("size", size) .toString(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java index a9e5223702..6d88305068 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java @@ -18,13 +18,18 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.coders.Coder.Context; +import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.testing.CoderProperties; import com.google.cloud.dataflow.sdk.util.RandomAccessData.RandomAccessDataCoder; +import com.google.common.primitives.UnsignedBytes; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -40,6 +45,9 @@ public class RandomAccessDataTest { private static final byte[] TEST_DATA_A = new byte[]{ 0x01, 0x02, 0x03 }; private static final byte[] TEST_DATA_B = new byte[]{ 0x06, 0x05, 0x04, 0x03 }; + private static final byte[] TEST_DATA_C = new byte[]{ 0x06, 0x05, 0x03, 0x03 }; + + @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testCoder() throws Exception { @@ -59,15 +67,41 @@ public void testCoder() throws Exception { assertEquals(3, RandomAccessDataCoder.of().getEncodedElementByteSize(streamA, Context.OUTER)); } + @Test + public void testCoderWithPositiveInfinityIsError() throws Exception { + expectedException.expect(CoderException.class); + expectedException.expectMessage("Positive infinity can not be encoded"); + RandomAccessDataCoder.of().encode( + RandomAccessData.POSITIVE_INFINITY, new ByteArrayOutputStream(), Context.OUTER); + } + @Test public void testLexicographicalComparator() throws Exception { RandomAccessData streamA = new RandomAccessData(); streamA.asOutputStream().write(TEST_DATA_A); RandomAccessData streamB = new RandomAccessData(); streamB.asOutputStream().write(TEST_DATA_B); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare(streamA, streamB) < 0); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare(streamB, streamA) > 0); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare(streamB, streamB) == 0); + RandomAccessData streamC = new RandomAccessData(); + streamC.asOutputStream().write(TEST_DATA_C); + assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + streamA, streamB) < 0); + assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + streamB, streamA) > 0); + assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + streamB, streamB) == 0); + // Check common prefix length. + assertEquals(2, RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.commonPrefixLength( + streamB, streamC)); + // Check that we honor the start offset. + assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + streamB, streamC, 3) == 0); + // Test positive infinity comparisons. + assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + streamA, RandomAccessData.POSITIVE_INFINITY) < 0); + assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + RandomAccessData.POSITIVE_INFINITY, RandomAccessData.POSITIVE_INFINITY) == 0); + assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + RandomAccessData.POSITIVE_INFINITY, streamA) > 0); } @Test @@ -154,5 +188,18 @@ public void testThatRandomAccessDataGrowsWhenReading() throws Exception { Arrays.copyOf(stream.array(), TEST_DATA_A.length)); } + @Test + public void testIncrement() throws Exception { + assertEquals(new RandomAccessData(new byte[]{ 0x00, 0x01 }), + new RandomAccessData(new byte[]{ 0x00, 0x00 }).increment()); + assertEquals(new RandomAccessData(new byte[]{ 0x01, UnsignedBytes.MAX_VALUE }), + new RandomAccessData(new byte[]{ 0x00, UnsignedBytes.MAX_VALUE }).increment()); + + // Test for positive infinity + assertSame(RandomAccessData.POSITIVE_INFINITY, new RandomAccessData(new byte[0]).increment()); + assertSame(RandomAccessData.POSITIVE_INFINITY, + new RandomAccessData(new byte[]{ UnsignedBytes.MAX_VALUE }).increment()); + assertSame(RandomAccessData.POSITIVE_INFINITY, RandomAccessData.POSITIVE_INFINITY.increment()); + } } From ec6a695f71dda84b79773f6dabef383093e62940 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 27 Jan 2016 14:09:24 -0800 Subject: [PATCH 042/751] BigQueryTableRowIterator: handle query failures In the DirectPipelineRunner, when BigQuery fails to execute a query, make sure that the query failure is reported and make sure only the right resources are cleaned up. Before, the query would silently fail and there would be an error reading the query results instead. The temporary dataset would be left around until garbage-collected. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113198888 --- .../sdk/util/BigQueryTableRowIterator.java | 25 +- .../util/BigQueryTableRowIteratorTest.java | 254 ++++++++++++++++++ 2 files changed, 276 insertions(+), 3 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 0fc21b93a7..924552016c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -30,10 +30,12 @@ import com.google.api.services.bigquery.Bigquery.Jobs.Insert; import com.google.api.services.bigquery.model.Dataset; import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ErrorProto; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfiguration; import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableCell; import com.google.api.services.bigquery.model.TableDataList; @@ -352,6 +354,12 @@ private void deleteDataset(String datasetId) throws IOException, InterruptedExce + projectId + ". Manual deletion may be required. Error message : {}"); } + /** + * Executes the specified query and returns a reference to the temporary BigQuery table created + * to hold the results. + * + * @throws IOException if the query fails. + */ private TableReference executeQueryAndWaitForCompletion() throws IOException, InterruptedException { // Create a temporary dataset to store results. @@ -384,8 +392,17 @@ private TableReference executeQueryAndWaitForCompletion() Job pollJob = executeWithBackOff( client.jobs().get(projectId, jobId.getJobId()), "Error when trying to get status of the job for query " + query + " :{}"); - if (pollJob.getStatus().getState().equals("DONE")) { - return pollJob.getConfiguration().getQuery().getDestinationTable(); + JobStatus status = pollJob.getStatus(); + if (status.getState().equals("DONE")) { + // Job is DONE, but did not necessarily succeed. + ErrorProto error = status.getErrorResult(); + if (error == null) { + return pollJob.getConfiguration().getQuery().getDestinationTable(); + } else { + // There will be no temporary table to delete, so null out the reference. + temporaryTableId = null; + throw new IOException("Executing query " + query + " failed: " + error.getMessage()); + } } try { Thread.sleep(QUERY_COMPLETION_POLL_TIME.getMillis()); @@ -460,7 +477,9 @@ public void close() throws IOException { try { // Deleting temporary table and dataset that gets generated when executing a query. if (temporaryDatasetId != null) { - deleteTable(temporaryDatasetId, temporaryTableId); + if (temporaryTableId != null) { + deleteTable(temporaryDatasetId, temporaryTableId); + } deleteDataset(temporaryDatasetId); } } catch (InterruptedException e) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java new file mode 100644 index 0000000000..cab74579a0 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -0,0 +1,254 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.ErrorProto; +import com.google.api.services.bigquery.model.Job; +import com.google.api.services.bigquery.model.JobConfiguration; +import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatus; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableCell; +import com.google.api.services.bigquery.model.TableDataList; +import com.google.api.services.bigquery.model.TableFieldSchema; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableRow; +import com.google.api.services.bigquery.model.TableSchema; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.IOException; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Tests for {@link BigQueryTableRowIterator}. + */ +@RunWith(JUnit4.class) +public class BigQueryTableRowIteratorTest { + + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Mock private Bigquery mockClient; + @Mock private Bigquery.Datasets mockDatasets; + @Mock private Bigquery.Datasets.Delete mockDatasetsDelete; + @Mock private Bigquery.Datasets.Insert mockDatasetsInsert; + @Mock private Bigquery.Jobs mockJobs; + @Mock private Bigquery.Jobs.Get mockJobsGet; + @Mock private Bigquery.Jobs.Insert mockJobsInsert; + @Mock private Bigquery.Tables mockTables; + @Mock private Bigquery.Tables.Get mockTablesGet; + @Mock private Bigquery.Tables.Delete mockTablesDelete; + @Mock private Bigquery.Tabledata mockTabledata; + @Mock private Bigquery.Tabledata.List mockTabledataList; + + @Before + public void setUp() throws IOException { + MockitoAnnotations.initMocks(this); + when(mockClient.tabledata()).thenReturn(mockTabledata); + when(mockTabledata.list(anyString(), anyString(), anyString())).thenReturn(mockTabledataList); + + when(mockClient.tables()).thenReturn(mockTables); + when(mockTables.delete(anyString(), anyString(), anyString())).thenReturn(mockTablesDelete); + when(mockTables.get(anyString(), anyString(), anyString())).thenReturn(mockTablesGet); + + when(mockClient.datasets()).thenReturn(mockDatasets); + when(mockDatasets.delete(anyString(), anyString())).thenReturn(mockDatasetsDelete); + when(mockDatasets.insert(anyString(), any(Dataset.class))).thenReturn(mockDatasetsInsert); + + when(mockClient.jobs()).thenReturn(mockJobs); + when(mockJobs.insert(anyString(), any(Job.class))).thenReturn(mockJobsInsert); + when(mockJobs.get(anyString(), anyString())).thenReturn(mockJobsGet); + } + + @After + public void tearDown() { + verifyNoMoreInteractions(mockClient); + verifyNoMoreInteractions(mockDatasets); + verifyNoMoreInteractions(mockDatasetsDelete); + verifyNoMoreInteractions(mockDatasetsInsert); + verifyNoMoreInteractions(mockJobs); + verifyNoMoreInteractions(mockJobsGet); + verifyNoMoreInteractions(mockJobsInsert); + verifyNoMoreInteractions(mockTables); + verifyNoMoreInteractions(mockTablesDelete); + verifyNoMoreInteractions(mockTablesGet); + verifyNoMoreInteractions(mockTabledata); + verifyNoMoreInteractions(mockTabledataList); + } + + private static Table tableWithBasicSchema() { + return new Table() + .setSchema( + new TableSchema() + .setFields( + Arrays.asList( + new TableFieldSchema().setName("name").setType("STRING"), + new TableFieldSchema().setName("answer").setType("INTEGER")))); + } + + private TableRow rawRow(Object... args) { + List cells = new LinkedList<>(); + for (Object a : args) { + cells.add(new TableCell().setV(a)); + } + return new TableRow().setF(cells); + } + + private TableDataList rawDataList(TableRow... rows) { + return new TableDataList().setRows(Arrays.asList(rows)); + } + + /** + * Verifies that when the query runs, the correct data is returned and the temporary dataset and + * table are both cleaned up. + */ + @Test + public void testReadFromQuery() throws IOException { + // Mock job inserting. + Job insertedJob = new Job().setJobReference(new JobReference()); + when(mockJobsInsert.execute()).thenReturn(insertedJob); + + // Mock job polling. + JobStatus status = new JobStatus().setState("DONE"); + TableReference tableRef = + new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); + JobConfigurationQuery queryConfig = new JobConfigurationQuery().setDestinationTable(tableRef); + Job getJob = + new Job() + .setJobReference(new JobReference()) + .setStatus(status) + .setConfiguration(new JobConfiguration().setQuery(queryConfig)); + when(mockJobsGet.execute()).thenReturn(getJob); + + // Mock table schema fetch. + when(mockTablesGet.execute()).thenReturn(tableWithBasicSchema()); + + // Mock table data fetch. + when(mockTabledataList.execute()).thenReturn(rawDataList(rawRow("Arthur", 42))); + + // Run query and verify + String query = "SELECT name, count from table"; + try (BigQueryTableRowIterator iterator = + BigQueryTableRowIterator.fromQuery(query, "project", mockClient)) { + assertTrue(iterator.hasNext()); + TableRow row = iterator.next(); + + assertTrue(row.containsKey("name")); + assertTrue(row.containsKey("answer")); + assertEquals("Arthur", row.get("name")); + assertEquals(42, row.get("answer")); + + assertFalse(iterator.hasNext()); + } + + // Temp dataset created and later deleted. + verify(mockClient, times(2)).datasets(); + verify(mockDatasets).insert(anyString(), any(Dataset.class)); + verify(mockDatasetsInsert).execute(); + verify(mockDatasets).delete(anyString(), anyString()); + verify(mockDatasetsDelete).execute(); + // Job inserted to run the query, polled once. + verify(mockClient, times(2)).jobs(); + verify(mockJobs).insert(anyString(), any(Job.class)); + verify(mockJobsInsert).execute(); + verify(mockJobs).get(anyString(), anyString()); + verify(mockJobsGet).execute(); + // Temp table get after query finish, deleted after reading. + verify(mockClient, times(2)).tables(); + verify(mockTables).get("project", "dataset", "table"); + verify(mockTablesGet).execute(); + verify(mockTables).delete(anyString(), anyString(), anyString()); + verify(mockTablesDelete).execute(); + // Table data read. + verify(mockClient).tabledata(); + verify(mockTabledata).list("project", "dataset", "table"); + verify(mockTabledataList).execute(); + } + + /** + * Verifies that when the query fails, the user gets a useful exception and the temporary dataset + * is cleaned up. Also verifies that the temporary table (which is never created) is not + * erroneously attempted to be deleted. + */ + @Test + public void testQueryFailed() throws IOException { + // Job can be created. + JobReference ref = new JobReference(); + Job insertedJob = new Job().setJobReference(ref); + when(mockJobsInsert.execute()).thenReturn(insertedJob); + + // Job state polled with an error. + String errorReason = "bad query"; + JobStatus status = + new JobStatus().setState("DONE").setErrorResult(new ErrorProto().setMessage(errorReason)); + Job getJob = new Job().setJobReference(ref).setStatus(status); + when(mockJobsGet.execute()).thenReturn(getJob); + + String query = "NOT A QUERY"; + try (BigQueryTableRowIterator iterator = + BigQueryTableRowIterator.fromQuery(query, "project", mockClient)) { + try { + iterator.hasNext(); + fail(); + } catch (Exception expected) { + // Verify message explains cause and reports the query. + assertThat(expected.getMessage(), containsString("failed")); + assertThat(expected.getMessage(), containsString(errorReason)); + assertThat(expected.getMessage(), containsString(query)); + } + } + + // Temp dataset created and then later deleted. + verify(mockClient, times(2)).datasets(); + verify(mockDatasets).insert(anyString(), any(Dataset.class)); + verify(mockDatasetsInsert).execute(); + verify(mockDatasets).delete(anyString(), anyString()); + verify(mockDatasetsDelete).execute(); + // Job inserted to run the query, then polled once. + verify(mockClient, times(2)).jobs(); + verify(mockJobs).insert(anyString(), any(Job.class)); + verify(mockJobsInsert).execute(); + verify(mockJobs).get(anyString(), anyString()); + verify(mockJobsGet).execute(); + } +} From e00629256a68060a98fc67f4f9a79dd960e4ece7 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 27 Jan 2016 19:40:44 -0800 Subject: [PATCH 043/751] Add CounterSet#merge(CounterSet) This method merges the contents of the two counter sets into the called CounterSet, using the underlying Counter#merge method. All counters that are present only in one of the CounterSets are added to the called set. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113225321 --- .../dataflow/sdk/util/common/CounterSet.java | 25 +++++++ .../sdk/util/common/CounterSetTest.java | 65 +++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java index 62904a5662..873add4c85 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.util.common; +import static com.google.common.base.Preconditions.checkArgument; + import java.util.AbstractSet; import java.util.HashMap; import java.util.Iterator; @@ -129,6 +131,29 @@ public synchronized boolean add(Counter e) { return true; } + public synchronized void merge(CounterSet that) { + for (Counter theirCounter : that) { + Counter myCounter = counters.get(theirCounter.getName()); + if (myCounter != null) { + mergeCounters(myCounter, theirCounter); + } else { + addCounter(theirCounter); + } + } + } + + private void mergeCounters(Counter mine, Counter theirCounter) { + checkArgument( + mine.isCompatibleWith(theirCounter), + "Can't merge CounterSets containing incompatible counters with the same name: " + + "%s (existing) and %s (merged)", + mine, + theirCounter); + @SuppressWarnings("unchecked") + Counter theirs = (Counter) theirCounter; + mine.merge(theirs); + } + /** * A nested class that supports adding additional counters into the * enclosing CounterSet. This is useful as a mutator, hiding other diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java index d3f7a23cf3..55ed714ad7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java @@ -19,6 +19,7 @@ import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; @@ -109,6 +110,70 @@ public void testAddOrReuseWithIncompatibleTypesThrowsException() { set.addOrReuseCounter(c1Incompatible); } + @Test + public void testMergeWithDifferentNamesAddsAll() { + Counter c1 = Counter.longs("c1", SUM); + Counter c2 = Counter.ints("c2", MAX); + + set.add(c1); + set.add(c2); + + CounterSet newSet = new CounterSet(); + newSet.merge(set); + + assertThat(newSet, containsInAnyOrder(c1, c2)); + } + + @SuppressWarnings("unchecked") + @Test + public void testMergeWithSameNamesMerges() { + Counter c1 = Counter.longs("c1", SUM); + Counter c2 = Counter.ints("c2", MAX); + + set.add(c1); + set.add(c2); + + c1.addValue(3L); + c2.addValue(22); + + CounterSet newSet = new CounterSet(); + Counter c1Prime = Counter.longs("c1", SUM); + Counter c2Prime = Counter.ints("c2", MAX); + + c1Prime.addValue(7L); + c2Prime.addValue(14); + + newSet.add(c1Prime); + newSet.add(c2Prime); + + newSet.merge(set); + + assertThat((Counter) newSet.getExistingCounter("c1"), equalTo(c1Prime)); + assertThat((Long) newSet.getExistingCounter("c1").getAggregate(), equalTo(10L)); + + assertThat((Counter) newSet.getExistingCounter("c2"), equalTo(c2Prime)); + assertThat((Integer) newSet.getExistingCounter("c2").getAggregate(), equalTo(22)); + } + + @SuppressWarnings("unchecked") + @Test + public void testMergeWithIncompatibleTypesThrowsException() { + Counter c1 = Counter.longs("c1", SUM); + + set.add(c1); + + CounterSet newSet = new CounterSet(); + Counter c1Prime = Counter.longs("c1", MAX); + + newSet.add(c1Prime); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("c1"); + thrown.expectMessage("incompatible counters with the same name"); + + newSet.merge(set); + } + @Test public void testAddCounterMutatorAddCounterAddsCounter() { Counter c1 = Counter.longs("c1", SUM); From b08ec20935afea90a89e4ba08e7aaf5daaf2a583 Mon Sep 17 00:00:00 2001 From: sgmc Date: Thu, 28 Jan 2016 09:45:02 -0800 Subject: [PATCH 044/751] Allow unflattened results from a BigQuery query-based export ----Release Notes---- Add an option to not flatten results from a BigQuery query-based export [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113271738 --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 48 ++++++++++++++++--- .../dataflow/BigQueryIOTranslator.java | 1 + .../sdk/runners/worker/BigQueryReader.java | 23 +++++---- .../runners/worker/BigQueryReaderFactory.java | 4 +- .../sdk/util/BigQueryTableRowIterator.java | 14 ++++-- .../dataflow/sdk/util/PropertyNames.java | 1 + .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 25 ++++++++-- .../util/BigQueryTableRowIteratorTest.java | 4 +- 8 files changed, 93 insertions(+), 27 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index b591982379..87258fe42c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -57,6 +57,7 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.hadoop.util.ApiErrorExtractor; +import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.fasterxml.jackson.annotation.JsonCreator; @@ -80,6 +81,7 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.annotation.Nullable; /** * {@link PTransform}s for reading and writing @@ -339,20 +341,24 @@ public static class Bound extends PTransform> { TableReference table; final String query; final boolean validate; + @Nullable + Boolean flattenResults; private static final String QUERY_VALIDATION_FAILURE_ERROR = "Validation of query \"%1$s\" failed. If the query depends on an earlier stage of the" + " pipeline, This validation can be disabled using #withoutValidation."; private Bound() { - this(null, null, null, true); + this(null, null, null, true, null); } - private Bound(String name, String query, TableReference reference, boolean validate) { + private Bound(String name, String query, TableReference reference, boolean validate, + Boolean flattenResults) { super(name); this.table = reference; this.query = query; this.validate = validate; + this.flattenResults = flattenResults; } /** @@ -361,7 +367,7 @@ private Bound(String name, String query, TableReference reference, boolean valid *

Does not modify this object. */ public Bound named(String name) { - return new Bound(name, query, table, validate); + return new Bound(name, query, table, validate, flattenResults); } /** @@ -380,23 +386,40 @@ public Bound from(String tableSpec) { *

Does not modify this object. */ public Bound from(TableReference table) { - return new Bound(name, query, table, validate); + return new Bound(name, query, table, validate, flattenResults); } /** * Returns a copy of this transform that reads the results of the specified query. * *

Does not modify this object. + * + *

By default, the query results will be flattened -- see + * "flattenResults" in the + * Jobs documentation for more information. To disable flattening, use + * {@link BigQueryIO.Read.Bound#withoutResultFlattening}. */ public Bound fromQuery(String query) { - return new Bound(name, query, table, validate); + return new Bound(name, query, table, validate, + MoreObjects.firstNonNull(flattenResults, Boolean.TRUE)); } /** * Disable table validation. */ public Bound withoutValidation() { - return new Bound(name, query, table, false); + return new Bound(name, query, table, false, flattenResults); + } + + /** + * Disable + * flattening of query results. + * + *

Only valid when a query is used ({@link #fromQuery}). Setting this option when reading + * from a table will cause an error during validation. + */ + public Bound withoutResultFlattening() { + return new Bound(name, query, table, validate, false); } /** @@ -410,6 +433,12 @@ public void validate(PInput input) { } else if (table != null && query != null) { throw new IllegalStateException("Invalid BigQuery read operation. Specifies both a" + " query and a table, only one of these should be provided"); + } else if (table != null && flattenResults != null) { + throw new IllegalStateException("Invalid BigQuery read operation. Specifies a" + + " table with a result flattening preference, which is not configurable"); + } else if (query != null && flattenResults == null) { + throw new IllegalStateException("Invalid BigQuery read operation. Specifies a" + + " query without a result flattening preference"); } BigQueryOptions bqOptions = input.getPipeline().getOptions().as(BigQueryOptions.class); @@ -500,6 +529,13 @@ public String getQuery() { public boolean getValidate() { return validate; } + + /** + * Returns true/false if result flattening is enabled/disabled, or null if not applicable. + */ + public Boolean getFlattenResults() { + return flattenResults; + } } /** Disallow construction of utility class. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java index 2aa6c9f0d3..d6856633dd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java @@ -52,6 +52,7 @@ public void translate( if (transform.getQuery() != null) { context.addInput(PropertyNames.BIGQUERY_QUERY, transform.getQuery()); + context.addInput(PropertyNames.BIGQUERY_FLATTEN_RESULTS, transform.getFlattenResults()); } else { TableReference table = transform.getTable(); if (table.getProjectId() == null) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java index e03966059f..617e5dc2f5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java @@ -44,13 +44,15 @@ public class BigQueryReader extends NativeReader> { @Nullable private final TableReference tableRef; @Nullable private final String query; @Nullable private final String projectId; + @Nullable private final Boolean flattenResults; private final Bigquery bigQueryClient; private BigQueryReader(TableReference tableRef, String query, String projectId, - Bigquery bigQueryClient) { + Bigquery bigQueryClient, Boolean flattenResults) { this.tableRef = tableRef; this.query = query; this.projectId = projectId; + this.flattenResults = flattenResults; this.bigQueryClient = checkNotNull(bigQueryClient, "bigQueryClient"); } @@ -59,7 +61,7 @@ private BigQueryReader(TableReference tableRef, String query, String projectId, * table. */ public static BigQueryReader fromTable(TableReference tableRef, Bigquery bigQueryClient) { - return new BigQueryReader(tableRef, null, null, bigQueryClient); + return new BigQueryReader(tableRef, null, null, bigQueryClient, null); } /** @@ -69,7 +71,7 @@ public static BigQueryReader fromTable(TableReference tableRef, Bigquery bigQuer public static BigQueryReader fromTableWithOptions( TableReference tableRef, BigQueryOptions bigQueryOptions) { Bigquery client = Transport.newBigQueryClient(bigQueryOptions).build(); - return new BigQueryReader(tableRef, null, null, client); + return new BigQueryReader(tableRef, null, null, client, null); } /** @@ -77,7 +79,7 @@ public static BigQueryReader fromTableWithOptions( * executing the specified query in the specified project. */ public static BigQueryReader fromQuery(String query, String projectId, Bigquery bigQueryClient) { - return new BigQueryReader(null, query, projectId, bigQueryClient); + return new BigQueryReader(null, query, projectId, bigQueryClient, true); } /** @@ -86,9 +88,10 @@ public static BigQueryReader fromQuery(String query, String projectId, Bigquery * specified options. */ public static BigQueryReader fromQueryWithOptions( - String query, String projectId, BigQueryOptions bigQueryOptions) { + String query, String projectId, BigQueryOptions bigQueryOptions, + @Nullable Boolean flattenResults) { Bigquery client = Transport.newBigQueryClient(bigQueryOptions).build(); - return new BigQueryReader(null, query, projectId, client); + return new BigQueryReader(null, query, projectId, client, flattenResults); } public TableReference getTableRef() { @@ -104,7 +107,7 @@ public BigQueryReaderIterator iterator() throws IOException { if (tableRef != null) { return new BigQueryReaderIterator(tableRef, bigQueryClient); } else { - return new BigQueryReaderIterator(query, projectId, bigQueryClient); + return new BigQueryReaderIterator(query, projectId, bigQueryClient, flattenResults); } } @@ -119,8 +122,10 @@ public BigQueryReaderIterator(TableReference tableRef, Bigquery bigQueryClient) rowIterator = BigQueryTableRowIterator.fromTable(tableRef, bigQueryClient); } - public BigQueryReaderIterator(String query, String projectId, Bigquery bigQueryClient) { - rowIterator = BigQueryTableRowIterator.fromQuery(query, projectId, bigQueryClient); + public BigQueryReaderIterator(String query, String projectId, Bigquery bigQueryClient, + @Nullable Boolean flattenResults) { + rowIterator = BigQueryTableRowIterator.fromQuery(query, projectId, bigQueryClient, + flattenResults); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java index e3d529f90f..a389aef3af 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.worker; +import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; import static com.google.cloud.dataflow.sdk.util.Structs.getString; import com.google.api.services.bigquery.model.TableReference; @@ -54,10 +55,11 @@ public BigQueryReader createTyped( PipelineOptions options, ExecutionContext executionContext) throws Exception { String query = getString(spec, PropertyNames.BIGQUERY_QUERY, null); + Boolean flatten = getBoolean(spec, PropertyNames.BIGQUERY_FLATTEN_RESULTS, true); if (query != null) { GcpOptions gcpOptions = options.as(GcpOptions.class); return BigQueryReader.fromQueryWithOptions( - query, gcpOptions.getProject(), options.as(BigQueryOptions.class)); + query, gcpOptions.getProject(), options.as(BigQueryOptions.class), flatten); } String tableId = getString(spec, PropertyNames.BIGQUERY_TABLE, null); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 924552016c..b867c27434 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -43,6 +43,7 @@ import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; +import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import org.joda.time.Duration; @@ -89,6 +90,8 @@ public class BigQueryTableRowIterator implements Iterator, Closeable { private static final Duration QUERY_COMPLETION_POLL_TIME = Duration.standardSeconds(1); private final String query; + // Whether to flatten query results. + private final boolean flattenResults; // Temporary dataset used to store query results. private String temporaryDatasetId = null; // Temporary table used to store query results. @@ -96,11 +99,12 @@ public class BigQueryTableRowIterator implements Iterator, Closeable { private BigQueryTableRowIterator( @Nullable TableReference ref, @Nullable String query, @Nullable String projectId, - Bigquery client) { + Bigquery client, boolean flattenResults) { this.ref = ref; this.query = query; this.projectId = projectId; this.client = checkNotNull(client, "client"); + this.flattenResults = flattenResults; } /** @@ -109,7 +113,7 @@ private BigQueryTableRowIterator( public static BigQueryTableRowIterator fromTable(TableReference ref, Bigquery client) { checkNotNull(ref, "ref"); checkNotNull(client, "client"); - return new BigQueryTableRowIterator(ref, null, ref.getProjectId(), client); + return new BigQueryTableRowIterator(ref, null, ref.getProjectId(), client, true); } /** @@ -117,11 +121,12 @@ public static BigQueryTableRowIterator fromTable(TableReference ref, Bigquery cl * specified query in the specified project. */ public static BigQueryTableRowIterator fromQuery( - String query, String projectId, Bigquery client) { + String query, String projectId, Bigquery client, @Nullable Boolean flattenResults) { checkNotNull(query, "query"); checkNotNull(projectId, "projectId"); checkNotNull(client, "client"); - return new BigQueryTableRowIterator(null, query, projectId, client); + return new BigQueryTableRowIterator(null, query, projectId, client, + MoreObjects.firstNonNull(flattenResults, Boolean.TRUE)); } @Override @@ -376,6 +381,7 @@ private TableReference executeQueryAndWaitForCompletion() job.setConfiguration(config); queryConfig.setQuery(query); queryConfig.setAllowLargeResults(true); + queryConfig.setFlattenResults(flattenResults); TableReference destinationTable = new TableReference(); destinationTable.setProjectId(projectId); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java index 59fa0e9b5c..2f105ec224 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java @@ -28,6 +28,7 @@ public class PropertyNames { public static final String BIGQUERY_SCHEMA = "schema"; public static final String BIGQUERY_TABLE = "table"; public static final String BIGQUERY_QUERY = "bigquery_query"; + public static final String BIGQUERY_FLATTEN_RESULTS = "bigquery_flatten_results"; public static final String BIGQUERY_WRITE_DISPOSITION = "write_disposition"; public static final String CO_GBK_RESULT_SCHEMA = "co_gbk_result_schema"; public static final String COMBINE_FN = "combine_fn"; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index a3dc18f462..a081de095c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -185,8 +185,8 @@ public void testValidateReadSetsDefaultProject() { public void testBuildSourceWithoutTableOrQuery() { Pipeline p = TestPipeline.create(); thrown.expect(IllegalStateException.class); - thrown.expectMessage(Matchers.containsString( - "Invalid BigQuery read operation, either table reference or query has to be set")); + thrown.expectMessage( + "Invalid BigQuery read operation, either table reference or query has to be set"); p.apply(BigQueryIO.Read.named("ReadMyTable")); p.run(); } @@ -196,9 +196,9 @@ public void testBuildSourceWithoutTableOrQuery() { public void testBuildSourceWithTableAndQuery() { Pipeline p = TestPipeline.create(); thrown.expect(IllegalStateException.class); - thrown.expectMessage(Matchers.containsString( + thrown.expectMessage( "Invalid BigQuery read operation. Specifies both a query and a table, only one of these" - + " should be provided")); + + " should be provided"); p.apply( BigQueryIO.Read.named("ReadMyTable") .from("foo.com:project:somedataset.sometable") @@ -206,6 +206,21 @@ public void testBuildSourceWithTableAndQuery() { p.run(); } + @Test + @Category(RunnableOnService.class) + public void testBuildSourceWithTableAndFlatten() { + Pipeline p = TestPipeline.create(); + thrown.expect(IllegalStateException.class); + thrown.expectMessage( + "Invalid BigQuery read operation. Specifies a" + + " table with a result flattening preference, which is not configurable"); + p.apply( + BigQueryIO.Read.named("ReadMyTable") + .from("foo.com:project:somedataset.sometable") + .withoutResultFlattening()); + p.run(); + } + @Test public void testBuildSink() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") @@ -253,7 +268,7 @@ public void testBuildSinkWithTableReference() { public void testBuildSinkWithoutTable() { Pipeline p = TestPipeline.create(); thrown.expect(IllegalStateException.class); - thrown.expectMessage(Matchers.containsString("must set the table reference")); + thrown.expectMessage("must set the table reference"); p.apply(Create.of().withCoder(TableRowJsonCoder.of())) .apply(BigQueryIO.Write.named("WriteMyTable")); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java index cab74579a0..b7903ca26c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -169,7 +169,7 @@ public void testReadFromQuery() throws IOException { // Run query and verify String query = "SELECT name, count from table"; try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromQuery(query, "project", mockClient)) { + BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null)) { assertTrue(iterator.hasNext()); TableRow row = iterator.next(); @@ -226,7 +226,7 @@ public void testQueryFailed() throws IOException { String query = "NOT A QUERY"; try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromQuery(query, "project", mockClient)) { + BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null)) { try { iterator.hasNext(); fail(); From 97cf4f24f7ee1f62873946a7d8d74f02a949fcb5 Mon Sep 17 00:00:00 2001 From: amyu Date: Thu, 28 Jan 2016 11:41:57 -0800 Subject: [PATCH 045/751] Clean up GameStats session branch for blog post ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113285110 --- .../examples/complete/game/GameStats.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java index 175af748bb..39d7a760c0 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java @@ -27,6 +27,7 @@ import com.google.cloud.dataflow.sdk.options.Validation; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; import com.google.cloud.dataflow.sdk.transforms.MapElements; @@ -309,17 +310,18 @@ public void processElement(ProcessContext c) { // [START DocInclude_SessionCalc] - // Calculate the total score for the users per session-- that is, a burst of activity - // separated by a gap from further activity. Find and record the mean session lengths. + // Detect user sessions-- that is, a burst of activity separated by a gap from further + // activity. Find and record the mean session lengths. // This information could help the game designers track the changing user engagement // as their set of games changes. userEvents .apply(Window.named("WindowIntoSessions") .>into( Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap()))) - .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow()) - .withAllowedLateness(Duration.ZERO)) - .apply("UserSessionSum", Sum.integersPerKey()) + .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow())) + // For this use, we care only about the existence of the session, not any particular + // information aggregated over it, so the following is an efficient way to do that. + .apply(Combine.perKey(x -> 0)) // Get the duration per session. .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn())) // [END DocInclude_SessionCalc] @@ -327,8 +329,7 @@ public void processElement(ProcessContext c) { // Re-window to process groups of session sums according to when the sessions complete. .apply(Window.named("WindowToExtractSessionMean") .into( - FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration()))) - .withAllowedLateness(Duration.ZERO)) + FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration())))) // Find the mean session duration in each window. .apply(Mean.globally().withoutDefaults()) // Write this info to a BigQuery table. From 76b86897ddeea484d6f38f1cddf2c45ab2c532e8 Mon Sep 17 00:00:00 2001 From: millsd Date: Thu, 28 Jan 2016 13:12:36 -0800 Subject: [PATCH 046/751] Account for per-window overhead in WindmillStateCache ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113294041 --- .../runners/worker/WindmillStateCache.java | 27 +++++++++++++------ .../worker/WindmillStateCacheTest.java | 14 +++++----- .../worker/WindmillStateInternalsTest.java | 18 ++++++------- 3 files changed, 35 insertions(+), 24 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java index b50be91226..9849ed8695 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java @@ -43,9 +43,18 @@ * Process-wide cache of per-key state. */ public class WindmillStateCache implements StatusDataProvider { + // Estimate of overhead per StateId. + private static final int PER_STATE_ID_OVERHEAD = 20; + // Initial size of hash tables per entry. + private static final int INITIAL_HASH_MAP_CAPACITY = 4; + // Overhead of each hash map entry. + private static final int HASH_MAP_ENTRY_OVERHEAD = 16; + // Overhead of each cache entry. Two longs, plus a hash table. + private static final int PER_CACHE_ENTRY_OVERHEAD = + 16 + HASH_MAP_ENTRY_OVERHEAD * INITIAL_HASH_MAP_CAPACITY; private Cache stateCache; - private int weight = 0; + private int displayedWeight = 0; // Only used for status pages and unit tests. public WindmillStateCache() { final Weigher weigher = Weighers.weightedKeysAndValues(); @@ -59,7 +68,7 @@ public WindmillStateCache() { @Override public void onRemoval(RemovalNotification removal) { if (removal.getCause() != RemovalCause.REPLACED) { - weight -= weigher.weigh(removal.getKey(), removal.getValue()); + displayedWeight -= weigher.weigh(removal.getKey(), removal.getValue()); } } }) @@ -67,7 +76,7 @@ public void onRemoval(RemovalNotification removal) { } public long getWeight() { - return weight; + return displayedWeight; } /** @@ -143,9 +152,10 @@ private void put(String computation, ByteString processingKey, StateCacheEntry entry = stateCache.getIfPresent(id); if (entry == null || entry.getToken() != token) { entry = new StateCacheEntry(token); - this.weight += id.getWeight(); + this.displayedWeight += id.getWeight(); + this.displayedWeight += entry.getWeight(); } - this.weight += entry.put(namespace, address, value, weight); + this.displayedWeight += entry.put(namespace, address, value, weight); // Always add back to the cache to update the weight. stateCache.put(id, entry); } @@ -186,7 +196,7 @@ public int hashCode() { @Override public long getWeight() { - return processingKey.size(); + return processingKey.size() + PER_STATE_ID_OVERHEAD; } } @@ -200,7 +210,7 @@ private static class StateCacheEntry implements Weighted { private long weight; public StateCacheEntry(long token) { - this.values = new HashMap<>(); + this.values = new HashMap<>(INITIAL_HASH_MAP_CAPACITY); this.token = token; this.weight = 0; } @@ -219,6 +229,7 @@ public long put( long weightDelta = 0; if (weightedValue == null) { weightedValue = new WeightedValue(); + weightDelta += HASH_MAP_ENTRY_OVERHEAD; } else { weightDelta -= weightedValue.weight; } @@ -232,7 +243,7 @@ public long put( @Override public long getWeight() { - return weight; + return weight + PER_CACHE_ENTRY_OVERHEAD; } public long getToken() { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java index 5906638199..6d2e8b5675 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java @@ -141,13 +141,13 @@ public void testBasic() throws Exception { assertNull(keyCache.get(triggerNamespace(0, 0), new TestStateTag("tag2"))); keyCache.put(StateNamespaces.global(), new TestStateTag("tag1"), new TestState("g1"), 2); - assertEquals(5, cache.getWeight()); + assertEquals(121, cache.getWeight()); keyCache.put(windowNamespace(0), new TestStateTag("tag2"), new TestState("w2"), 2); - assertEquals(10, cache.getWeight()); + assertEquals(242, cache.getWeight()); keyCache.put(triggerNamespace(0, 0), new TestStateTag("tag3"), new TestState("t3"), 2); - assertEquals(12, cache.getWeight()); + assertEquals(260, cache.getWeight()); keyCache.put(triggerNamespace(0, 0), new TestStateTag("tag2"), new TestState("t2"), 2); - assertEquals(14, cache.getWeight()); + assertEquals(278, cache.getWeight()); assertEquals( new TestState("g1"), keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); @@ -165,12 +165,12 @@ public void testBasic() throws Exception { public void testInvalidation() throws Exception { assertNull(keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); keyCache.put(StateNamespaces.global(), new TestStateTag("tag1"), new TestState("g1"), 2); - assertEquals(5, cache.getWeight()); + assertEquals(121, cache.getWeight()); assertEquals( new TestState("g1"), keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); keyCache = cache.forComputation(COMPUTATION).forKey(KEY, STATE_FAMILY, 1L); - assertEquals(5, cache.getWeight()); + assertEquals(121, cache.getWeight()); assertNull(keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); assertEquals(0, cache.getWeight()); } @@ -181,7 +181,7 @@ public void testInvalidation() throws Exception { @Test public void testEviction() throws Exception { keyCache.put(windowNamespace(0), new TestStateTag("tag2"), new TestState("w2"), 2); - assertEquals(5, cache.getWeight()); + assertEquals(121, cache.getWeight()); keyCache.put(triggerNamespace(0, 0), new TestStateTag("tag3"), new TestState("t3"), 2000000000); assertEquals(0, cache.getWeight()); // Eviction is atomic across the whole window. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java index 355ffe14fb..a279b80acf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java @@ -787,14 +787,14 @@ public void testCachedValue() throws Exception { value.set("Hi"); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(2, cache.getWeight()); + assertEquals(118, cache.getWeight()); value = underTest.state(NAMESPACE, addr); assertEquals("Hi", value.get().read()); value.clear(); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(0, cache.getWeight()); + assertEquals(116, cache.getWeight()); value = underTest.state(NAMESPACE, addr); assertEquals(null, value.get().read()); @@ -823,7 +823,7 @@ public void testCachedBag() throws Exception { underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(10, cache.getWeight()); + assertEquals(126, cache.getWeight()); bag = underTest.state(NAMESPACE, addr); bag.add("goodbye"); @@ -833,7 +833,7 @@ public void testCachedBag() throws Exception { underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(3, cache.getWeight()); + assertEquals(119, cache.getWeight()); bag = underTest.state(NAMESPACE, addr); bag.add("new2"); @@ -843,7 +843,7 @@ public void testCachedBag() throws Exception { underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(4, cache.getWeight()); + assertEquals(120, cache.getWeight()); bag = underTest.state(NAMESPACE, addr); assertThat(bag.get().read(), Matchers.containsInAnyOrder("new3")); @@ -872,7 +872,7 @@ public void testCachedWatermarkHold() throws Exception { underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(8, cache.getWeight()); + assertEquals(124, cache.getWeight()); bag = underTest.state(NAMESPACE, addr); assertThat(bag.get().read(), Matchers.equalTo(new Instant(2000))); @@ -880,7 +880,7 @@ public void testCachedWatermarkHold() throws Exception { underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(8, cache.getWeight()); + assertEquals(124, cache.getWeight()); bag = underTest.state(NAMESPACE, addr); assertEquals(null, bag.get().read()); @@ -907,7 +907,7 @@ public void testCachedCombining() throws Exception { underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(1, cache.getWeight()); + assertEquals(117, cache.getWeight()); value = underTest.state(NAMESPACE, COMBINING_ADDR); assertThat(value.get().read(), Matchers.equalTo(3)); @@ -917,7 +917,7 @@ public void testCachedCombining() throws Exception { underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - assertEquals(0, cache.getWeight()); + assertEquals(116, cache.getWeight()); value = underTest.state(NAMESPACE, COMBINING_ADDR); assertThat(value.get().read(), Matchers.equalTo(0)); From e64446cc10c663a22c57e02d9badeada7e92b837 Mon Sep 17 00:00:00 2001 From: tudorm Date: Thu, 28 Jan 2016 15:14:28 -0800 Subject: [PATCH 047/751] Add support to configure the shuffle client library with a property. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113307012 --- .../cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java index 6694e99924..999809b2f8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java @@ -32,9 +32,13 @@ class ShuffleLibrary { */ static void load() { try { + final String shuffleClientLibraryPropertyKey = "batch.shuffle_client_library"; + String shuffleClientLibrary = "libshuffle_client_jni.so.stripped"; + if (System.getProperties().containsKey(shuffleClientLibraryPropertyKey)) { + shuffleClientLibrary = System.getProperty(shuffleClientLibraryPropertyKey); + } File tempfile = File.createTempFile("libshuffle_client_jni", ".so"); - InputStream input = ClassLoader.getSystemResourceAsStream( - "libshuffle_client_jni.so.stripped"); + InputStream input = ClassLoader.getSystemResourceAsStream(shuffleClientLibrary); Files.copy(input, tempfile.toPath(), StandardCopyOption.REPLACE_EXISTING); System.load(tempfile.getAbsolutePath()); } catch (IOException e) { From 9b0b39587e8db9d80053647b8186c8c69d5d655e Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 28 Jan 2016 16:56:35 -0800 Subject: [PATCH 048/751] Create worker maven module ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113317733 --- pom.xml | 1 + worker/pom.xml | 243 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 244 insertions(+) create mode 100644 worker/pom.xml diff --git a/pom.xml b/pom.xml index 7bdee33965..7d31ee07fb 100644 --- a/pom.xml +++ b/pom.xml @@ -86,6 +86,7 @@ pom sdk + worker examples maven-archetypes/starter maven-archetypes/examples diff --git a/worker/pom.xml b/worker/pom.xml new file mode 100644 index 0000000000..46def118c2 --- /dev/null +++ b/worker/pom.xml @@ -0,0 +1,243 @@ + + + + 4.0.0 + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-parent + 1.5.0-SNAPSHOT + + + com.google.cloud.dataflow + google-cloud-dataflow-java-worker-all + Google Cloud Dataflow Java Worker - All + Google Cloud Dataflow Java SDK provides a simple, Java-based + interface for processing virtually any size data using Google cloud + resources. This artifact includes entire Dataflow Java Worker. + http://cloud.google.com/dataflow + + jar + + + ${maven.build.timestamp} + yyyy-MM-dd HH:mm + none + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.12 + + + com.puppycrawl.tools + checkstyle + 6.6 + + + + ../checkstyle.xml + true + true + false + true + ${project.build.directory}/generated-test-sources/** + + + + + check + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + default-jar + + jar + + + + default-test-jar + + test-jar + + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + + attach-sources + compile + + jar + + + + attach-test-sources + test-compile + + test-jar + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + + + bundle-and-repackage + package + + shade + + + true + + + com.google.guava:guava + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + com.google.common + com.google.cloud.dataflow.sdk.repackaged.com.google.common + + + com.google.thirdparty + com.google.cloud.dataflow.sdk.repackaged.com.google.thirdparty + + + + + + + + bundle-rest-without-repackaging + package + + shade + + + true + ${project.artifactId}-bundled-${project.version} + + + com.google.guava:guava + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + + org.jacoco + jacoco-maven-plugin + + + + + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-all + ${project.version} + + + + + org.hamcrest + hamcrest-all + ${hamcrest.version} + provided + + + + junit + junit + ${junit.version} + provided + + + + org.slf4j + slf4j-jdk14 + ${slf4j.version} + test + + + + org.mockito + mockito-all + 1.9.5 + test + + + From ce8c03f930055f51125a1b0f0e4648121a801ca6 Mon Sep 17 00:00:00 2001 From: lcwik Date: Fri, 29 Jan 2016 10:41:02 -0800 Subject: [PATCH 049/751] Add explicit record type for Ism files This change adds the record coder, and shard coder for a 2nd level index, and hashing for shard generation. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113376303 --- .../sdk/runners/worker/IsmFormat.java | 681 +++++++++++++++++- .../sdk/runners/worker/IsmFormatTest.java | 214 ++++++ 2 files changed, 880 insertions(+), 15 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java index 517b0e1a11..118f31692e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java @@ -15,50 +15,702 @@ */ package com.google.cloud.dataflow.sdk.runners.worker; +import static com.google.cloud.dataflow.sdk.util.Structs.addLong; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.ListCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.RandomAccessData; import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter; import com.google.cloud.dataflow.sdk.util.VarInt; +import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; +import com.google.common.base.MoreObjects.ToStringHelper; +import com.google.common.base.Objects; import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import com.google.common.hash.HashFunction; +import com.google.common.hash.Hashing; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.Objects; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** - * An Ism file is a prefix encoded key value file with a bloom filter and an index to - * enable lookups. + * An Ism file is a prefix encoded composite key value file broken into shards. Each composite + * key is composed of a fixed number of component keys. A fixed number of those sub keys represent + * the shard key portion; see {@link IsmRecord} and {@link IsmRecordCoder} for further details + * around the data format. In addition to the data, there is a bloom filter, + * and multiple indices to allow for efficient retrieval. * *

An Ism file is composed of these high level sections (in order): *

    - *
  • data block
  • + *
  • shard block
  • *
  • bloom filter (See {@link ScalableBloomFilter} for details on encoding format)
  • - *
  • index
  • + *
  • shard index
  • *
  • footer (See {@link Footer} for details on encoding format)
  • *
* + *

The shard block is composed of multiple copies of the following: + *

    + *
  • data block
  • + *
  • data index
  • + *
+ * *

The data block is composed of multiple copies of the following: *

    *
  • key prefix (See {@link KeyPrefix} for details on encoding format)
  • *
  • unshared key bytes
  • *
  • value bytes
  • + *
  • optional 0x00 0x00 bytes followed by metadata bytes + * (if the following 0x00 0x00 bytes are not present, then there are no metadata bytes)
  • *
+ * Each key written into the data block must be in unsigned lexicographically increasing order + * and also its shard portion of the key must hash to the same shard id as all other keys + * within the same data block. The hashing function used is the + * + * 32-bit murmur3 algorithm, x86 variant (little-endian variant), + * using {@code 1225801234} as the seed value. * - *

The index is composed of {@code N} copies of the following: + *

The data index is composed of {@code N} copies of the following: *

    *
  • key prefix (See {@link KeyPrefix} for details on encoding format)
  • *
  • unshared key bytes
  • *
  • byte offset to key prefix in data block (variable length long coding)
  • *
+ * + *

The shard index is composed of a variable length integer encoding representing + * the number of shard index records followed by that many shard index records. + * See {@link IsmShardCoder} for further details as to its encoding scheme. */ -class IsmFormat { +public class IsmFormat { + private static final int HASH_SEED = 1225801234; + private static final HashFunction HASH_FUNCTION = Hashing.murmur3_32(HASH_SEED); + static final int SHARD_BITS = 0x7F; // [0-127] shards + [128-255] metadata shards + + /** + * A record containing a composite key and either a value or metadata. The composite key + * must not contain the metadata key component place holder if producing a value record, and must + * contain the metadata component key place holder if producing a metadata record. + * + *

The composite key is a fixed number of component keys where the first {@code N} component + * keys are used to create a shard id via hashing. See {@link IsmRecordCoder#hash(List)} for + * further details. + */ + public static class IsmRecord { + /** Returns an IsmRecord with the specified key components and value. */ + public static IsmRecord of(List keyComponents, V value) { + checkNotNull(keyComponents); + checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); + checkArgument(!isMetadataKey(keyComponents), + "Expected key components to not contain metadata key."); + return new IsmRecord<>(keyComponents, value, null); + } + + public static IsmRecord meta(List keyComponents, byte[] metadata) { + checkNotNull(keyComponents); + checkNotNull(metadata); + checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); + checkArgument(isMetadataKey(keyComponents), + "Expected key components to contain metadata key."); + return new IsmRecord(keyComponents, null, metadata); + } + + private final List keyComponents; + private final V value; + private final byte[] metadata; + private IsmRecord(List keyComponents, V value, byte[] metadata) { + this.keyComponents = keyComponents; + this.value = value; + this.metadata = metadata; + } + + /** Returns the list of key components. */ + public List getKeyComponents() { + return keyComponents; + } + + /** Returns the key component at the specified index. */ + public Object getKeyComponent(int index) { + return keyComponents.get(index); + } + + /** + * Returns the value. Throws {@link IllegalStateException} if this is not a + * value record. + */ + public V getValue() { + checkState(!isMetadataKey(keyComponents), + "This is a metadata record and not a value record."); + return value; + } + + /** + * Returns the metadata. Throws {@link IllegalStateException} if this is not a + * metadata record. + */ + public byte[] getMetadata() { + checkState(isMetadataKey(keyComponents), + "This is a value record and not a metadata record."); + return metadata; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof IsmRecord)) { + return false; + } + IsmRecord other = (IsmRecord) obj; + return Objects.equal(keyComponents, other.keyComponents) + && Objects.equal(value, other.value) + && Arrays.equals(metadata, other.metadata); + } + + @Override + public int hashCode() { + return Objects.hashCode(keyComponents, value, Arrays.hashCode(metadata)); + } + + @Override + public String toString() { + ToStringHelper builder = MoreObjects.toStringHelper(IsmRecord.class) + .add("keyComponents", keyComponents); + if (isMetadataKey(keyComponents)) { + builder.add("metadata", metadata); + } else { + builder.add("value", value); + } + return builder.toString(); + } + } + + /** A {@link Coder} for {@link IsmRecord}s. + * + *

Note that this coder standalone will not produce an Ism file. This coder can be used + * to materialize a {@link PCollection} of {@link IsmRecord}s. Only when this coder + * is combined with an {@link IsmSink} will one produce an Ism file. + * + *

The {@link IsmRecord} encoded format is: + *

    + *
  • encoded key component 1 using key component coder 1
  • + *
  • ...
  • + *
  • encoded key component N using key component coder N
  • + *
  • encoded value using value coder
  • + *
+ */ + public static class IsmRecordCoder + extends StandardCoder> { + /** Returns an IsmRecordCoder with the specified key component coders, value coder. */ + public static IsmRecordCoder of( + int numberOfShardKeyCoders, + int numberOfMetadataShardKeyCoders, + List> keyComponentCoders, + Coder valueCoder) { + checkNotNull(keyComponentCoders); + checkArgument(keyComponentCoders.size() > 0); + checkArgument(numberOfShardKeyCoders > 0); + checkArgument(numberOfShardKeyCoders <= keyComponentCoders.size()); + checkArgument(numberOfMetadataShardKeyCoders <= keyComponentCoders.size()); + return new IsmRecordCoder<>( + numberOfShardKeyCoders, + numberOfMetadataShardKeyCoders, + keyComponentCoders, + valueCoder); + } + + /** + * Returns an IsmRecordCoder with the specified coders. Note that this method is not meant + * to be called by users but used by Jackson when decoding this coder. + */ + @JsonCreator + public static IsmRecordCoder of( + @JsonProperty(PropertyNames.NUM_SHARD_CODERS) int numberOfShardCoders, + @JsonProperty(PropertyNames.NUM_METADATA_SHARD_CODERS) int numberOfMetadataShardCoders, + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { + Preconditions.checkArgument(components.size() >= 2, + "Expecting at least 2 components, got " + components.size()); + return of( + numberOfShardCoders, + numberOfMetadataShardCoders, + components.subList(0, components.size() - 1), + components.get(components.size() - 1)); + } + + private final int numberOfShardKeyCoders; + private final int numberOfMetadataShardKeyCoders; + private final List> keyComponentCoders; + private final Coder valueCoder; + + private IsmRecordCoder( + int numberOfShardKeyCoders, + int numberOfMetadataShardKeyCoders, + List> keyComponentCoders, Coder valueCoder) { + this.numberOfShardKeyCoders = numberOfShardKeyCoders; + this.numberOfMetadataShardKeyCoders = numberOfMetadataShardKeyCoders; + this.keyComponentCoders = keyComponentCoders; + this.valueCoder = valueCoder; + } + + /** Returns the list of key component coders. */ + public List> getKeyComponentCoders() { + return keyComponentCoders; + } + + /** Returns the key coder at the specified index. */ + public Coder getKeyComponentCoder(int index) { + return keyComponentCoders.get(index); + } + + /** Returns the value coder. */ + public Coder getValueCoder() { + return valueCoder; + } + + @Override + public void encode(IsmRecord value, OutputStream outStream, + Coder.Context context) throws CoderException, IOException { + if (value.getKeyComponents().size() != keyComponentCoders.size()) { + throw new CoderException(String.format( + "Expected %s key component(s) but received key component(s) %s.", + keyComponentCoders.size(), value.getKeyComponents())); + } + for (int i = 0; i < keyComponentCoders.size(); ++i) { + getKeyComponentCoder(i).encode(value.getKeyComponent(i), outStream, context.nested()); + } + if (isMetadataKey(value.getKeyComponents())) { + ByteArrayCoder.of().encode(value.getMetadata(), outStream, context.nested()); + } else { + valueCoder.encode(value.getValue(), outStream, context.nested()); + } + } + + @Override + public IsmRecord decode(InputStream inStream, Coder.Context context) + throws CoderException, IOException { + List keyComponents = new ArrayList<>(keyComponentCoders.size()); + for (Coder keyCoder : keyComponentCoders) { + keyComponents.add(keyCoder.decode(inStream, context.nested())); + } + if (isMetadataKey(keyComponents)) { + return IsmRecord.meta( + keyComponents, ByteArrayCoder.of().decode(inStream, context.nested())); + } else { + return IsmRecord.of(keyComponents, valueCoder.decode(inStream, context.nested())); + } + } + + int getNumberOfShardKeyCoders(List keyComponents) { + if (isMetadataKey(keyComponents)) { + return numberOfMetadataShardKeyCoders; + } else { + return numberOfShardKeyCoders; + } + } + + /** + * Computes the shard id for the given key component(s). + * + * The shard keys are encoded into their byte representations and hashed using the + * + * 32-bit murmur3 algorithm, x86 variant (little-endian variant), + * using {@code 1225801234} as the seed value. We ensure that shard ids for + * metadata keys and normal keys do not overlap. + */ + public int hash(List keyComponents) { + return encodeAndHash(keyComponents, new RandomAccessData(), new ArrayList()); + } + + /** + * Computes the shard id for the given key component(s). + * + * Mutates {@code keyBytes} such that when returned, contains the encoded + * version of the key components. + */ + int encodeAndHash(List keyComponents, RandomAccessData keyBytesToMutate) { + return encodeAndHash(keyComponents, keyBytesToMutate, new ArrayList()); + } + + /** + * Computes the shard id for the given key component(s). + * + * Mutates {@code keyBytes} such that when returned, contains the encoded + * version of the key components. Also, mutates {@code keyComponentByteOffsetsToMutate} to + * store the location where each key component's encoded byte representation ends within + * {@code keyBytes}. + */ + int encodeAndHash( + List keyComponents, + RandomAccessData keyBytesToMutate, + List keyComponentByteOffsetsToMutate) { + checkNotNull(keyComponents); + checkArgument(keyComponents.size() <= keyComponentCoders.size(), + "Expected at most %s key component(s) but received %s.", + keyComponentCoders.size(), keyComponents); + + final int numberOfKeyCodersToUse; + final int shardOffset; + if (isMetadataKey(keyComponents)) { + numberOfKeyCodersToUse = numberOfMetadataShardKeyCoders; + shardOffset = SHARD_BITS + 1; + } else { + numberOfKeyCodersToUse = numberOfShardKeyCoders; + shardOffset = 0; + } + + checkArgument(numberOfKeyCodersToUse <= keyComponents.size(), + "Expected at least %s key component(s) but received %s.", + numberOfShardKeyCoders, keyComponents); + + try { + // Encode the shard portion + for (int i = 0; i < numberOfKeyCodersToUse; ++i) { + getKeyComponentCoder(i).encode( + keyComponents.get(i), keyBytesToMutate.asOutputStream(), Context.NESTED); + keyComponentByteOffsetsToMutate.add(keyBytesToMutate.size()); + } + int rval = HASH_FUNCTION.hashBytes( + keyBytesToMutate.array(), 0, keyBytesToMutate.size()).asInt() & SHARD_BITS; + rval += shardOffset; + + // Encode the remainder + for (int i = numberOfKeyCodersToUse; i < keyComponents.size(); ++i) { + getKeyComponentCoder(i).encode( + keyComponents.get(i), keyBytesToMutate.asOutputStream(), Context.NESTED); + keyComponentByteOffsetsToMutate.add(keyBytesToMutate.size()); + } + return rval; + } catch (IOException e) { + throw new IllegalStateException( + String.format("Failed to hash %s with coder %s", keyComponents, this), e); + } + } + + @Override + public List> getCoderArguments() { + return ImmutableList.>builder() + .addAll(keyComponentCoders) + .add(valueCoder) + .build(); + } + + @Override + public CloudObject asCloudObject() { + CloudObject cloudObject = super.asCloudObject(); + addLong(cloudObject, PropertyNames.NUM_SHARD_CODERS, numberOfShardKeyCoders); + addLong(cloudObject, PropertyNames.NUM_METADATA_SHARD_CODERS, numberOfMetadataShardKeyCoders); + return cloudObject; + } + + @Override + public void verifyDeterministic() throws Coder.NonDeterministicException { + verifyDeterministic("Key component coders expected to be deterministic.", keyComponentCoders); + verifyDeterministic("Value coder expected to be deterministic.", valueCoder); + } + + @Override + public boolean consistentWithEquals() { + for (Coder keyComponentCoder : keyComponentCoders) { + if (!keyComponentCoder.consistentWithEquals()) { + return false; + } + } + return valueCoder.consistentWithEquals(); + } + + @Override + public Object structuralValue(IsmRecord record) throws Exception { + checkState(record.getKeyComponents().size() == keyComponentCoders.size(), + "Expected the number of key component coders %s " + + "to match the number of key components %s.", + keyComponentCoders.size(), record.getKeyComponents()); + + if (record != null && consistentWithEquals()) { + ArrayList keyComponentStructuralValues = new ArrayList<>(); + for (int i = 0; i < keyComponentCoders.size(); ++i) { + keyComponentStructuralValues.add( + getKeyComponentCoder(i).structuralValue(record.getKeyComponent(i))); + } + if (isMetadataKey(record.getKeyComponents())) { + return IsmRecord.meta(keyComponentStructuralValues, record.getMetadata()); + } else { + return IsmRecord.of(keyComponentStructuralValues, + valueCoder.structuralValue(record.getValue())); + } + } + return super.structuralValue(record); + } + } + + /** Returns true if and only if any of the passed in key components represent a metadata key. */ + public static boolean isMetadataKey(List keyComponents) { + for (Object keyComponent : keyComponents) { + if (keyComponent == METADATA_KEY) { + return true; + } + } + return false; + } + + /** A marker object representing the wildcard metadata key component. */ + private static final Object METADATA_KEY = new Object() { + @Override + public String toString() { + return "META"; + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return -1248902349; + } + }; + + /** + * An object representing a wild card for a key component. + * Encoded using {@link MetadataKeyCoder}. + */ + public static Object getMetadataKey() { + return METADATA_KEY; + } + + /** + * A coder for metadata key component. Can be used to wrap key component coder allowing for + * the metadata key component to be used as a place holder instead of an actual key. + */ + public static class MetadataKeyCoder extends StandardCoder { + public static MetadataKeyCoder of(Coder keyCoder) { + checkNotNull(keyCoder); + return new MetadataKeyCoder<>(keyCoder); + } + + /** + * Returns an IsmRecordCoder with the specified coders. Note that this method is not meant + * to be called by users but used by Jackson when decoding this coder. + */ + @JsonCreator + public static MetadataKeyCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { + Preconditions.checkArgument(components.size() == 1, + "Expecting one component, got " + components.size()); + return of(components.get(0)); + } + + private final Coder keyCoder; + + private MetadataKeyCoder(Coder keyCoder) { + this.keyCoder = keyCoder; + } + + public Coder getKeyCoder() { + return keyCoder; + } + + @Override + public void encode(K value, OutputStream outStream, Coder.Context context) + throws CoderException, IOException { + if (value == METADATA_KEY) { + outStream.write(0); + } else { + outStream.write(1); + keyCoder.encode(value, outStream, context.nested()); + } + } + + @Override + public K decode(InputStream inStream, Coder.Context context) + throws CoderException, IOException { + int marker = inStream.read(); + if (marker == 0) { + return (K) getMetadataKey(); + } else if (marker == 1) { + return keyCoder.decode(inStream, context.nested()); + } else { + throw new CoderException(String.format("Expected marker but got %s.", marker)); + } + } + + @Override + public List> getCoderArguments() { + return ImmutableList.>of(keyCoder); + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + verifyDeterministic("Expected key coder to be deterministic", keyCoder); + } + } + + /** + * A shard descriptor containing shard id, the data block offset, and the index offset for the + * given shard. + */ + public static class IsmShard { + private final int id; + private final long blockOffset; + private final long indexOffset; + + /** Returns an IsmShard with the given id, block offset and no index offset. */ + public static IsmShard of(int id, long blockOffset) { + IsmShard ismShard = new IsmShard(id, blockOffset, -1); + checkState(id >= 0, + "%s attempting to be written with negative shard id.", + ismShard); + checkState(blockOffset >= 0, + "%s attempting to be written with negative block offset.", + ismShard); + return ismShard; + } + + /** Returns an IsmShard with the given id, block offset, and index offset. */ + public static IsmShard of(int id, long blockOffset, long indexOffset) { + IsmShard ismShard = new IsmShard(id, blockOffset, indexOffset); + checkState(id >= 0, + "%s attempting to be written with negative shard id.", + ismShard); + checkState(blockOffset >= 0, + "%s attempting to be written with negative block offset.", + ismShard); + checkState(indexOffset >= 0, + "%s attempting to be written with negative index offset.", + ismShard); + return ismShard; + } + + private IsmShard(int id, long blockOffset, long indexOffset) { + this.id = id; + this.blockOffset = blockOffset; + this.indexOffset = indexOffset; + } + + /** Return the shard id. */ + public int getId() { + return id; + } + + /** Return the absolute position within the Ism file where the data block begins. */ + public long getBlockOffset() { + return blockOffset; + } + + /** + * Return the absolute position within the Ism file where the index block begins. + * Throws {@link IllegalStateException} if the index offset was never specified. + */ + public long getIndexOffset() { + checkState(indexOffset >= 0, + "Unable to fetch index offset because it was never specified."); + return indexOffset; + } + + /** Returns a new IsmShard like this one with the specified index offset. */ + public IsmShard withIndexOffset(long indexOffset) { + return of(id, blockOffset, indexOffset); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(IsmShard.class) + .add("id", id) + .add("blockOffset", blockOffset) + .add("indexOffset", indexOffset) + .toString(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof IsmShard)) { + return false; + } + IsmShard other = (IsmShard) obj; + return Objects.equal(id, other.id) + && Objects.equal(blockOffset, other.blockOffset) + && Objects.equal(indexOffset, other.indexOffset); + } + + @Override + public int hashCode() { + return Objects.hashCode(id, blockOffset, indexOffset); + } + } + + /** + * A {@link ListCoder} wrapping a {@link IsmShardCoder} used to encode the shard index. + * See {@link ListCoder} for its encoding specification and {@link IsmShardCoder} for its + * encoding specification. + */ + public static final Coder> ISM_SHARD_INDEX_CODER = + ListCoder.of(IsmShardCoder.of()); + + /** + * A coder for {@link IsmShard}s. + * + * The shard descriptor is encoded as: + *
    + *
  • id (variable length integer encoding)
  • + *
  • blockOffset (variable length long encoding)
  • + *
  • indexOffset (variable length long encoding)
  • + *
+ */ + public static class IsmShardCoder extends AtomicCoder { + private static final IsmShardCoder INSTANCE = new IsmShardCoder(); + + /** Returns an IsmShardCoder. */ + @JsonCreator + public static IsmShardCoder of() { + return INSTANCE; + } + + private IsmShardCoder() { + } + + @Override + public void encode(IsmShard value, OutputStream outStream, Coder.Context context) + throws CoderException, IOException { + checkState(value.getIndexOffset() >= 0, + "%s attempting to be written without index offset.", + value); + VarIntCoder.of().encode(value.getId(), outStream, context.nested()); + VarLongCoder.of().encode(value.getBlockOffset(), outStream, context.nested()); + VarLongCoder.of().encode(value.getIndexOffset(), outStream, context.nested()); + } + + @Override + public IsmShard decode( + InputStream inStream, Coder.Context context) throws CoderException, IOException { + return IsmShard.of( + VarIntCoder.of().decode(inStream, context), + VarLongCoder.of().decode(inStream, context), + VarLongCoder.of().decode(inStream, context)); + } + + @Override + public boolean consistentWithEquals() { + return true; + } + } + /** * The prefix used before each key which contains the number of shared and unshared * bytes from the previous key that was read. The key prefix along with the previous key @@ -90,7 +742,7 @@ public int getUnsharedKeySize() { @Override public int hashCode() { - return Objects.hash(sharedKeySize, unsharedKeySize); + return Objects.hashCode(sharedKeySize, unsharedKeySize); } @Override @@ -162,15 +814,15 @@ protected long getEncodedElementByteSize(KeyPrefix value, Coder.Context context) *

The footer is encoded as the value containing: *

    *
  • start of bloom filter offset (big endian long coding)
  • - *
  • start of index position offset (big endian long coding)
  • + *
  • start of shard index position offset (big endian long coding)
  • *
  • number of keys in file (big endian long coding)
  • *
  • 0x01 (version key as a single byte)
  • *
*/ static class Footer { static final int LONG_BYTES = 8; - static final long FIXED_LENGTH = 3 * LONG_BYTES + 1; - static final byte VERSION = 1; + static final int FIXED_LENGTH = 3 * LONG_BYTES + 1; + static final byte VERSION = 2; private final long indexPosition; private final long bloomFilterPosition; @@ -210,13 +862,13 @@ public boolean equals(Object other) { @Override public int hashCode() { - return Objects.hash(indexPosition, bloomFilterPosition, numberOfKeys); + return Objects.hashCode(indexPosition, bloomFilterPosition, numberOfKeys); } @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("version", 1) + .add("version", Footer.VERSION) .add("indexPosition", indexPosition) .add("bloomFilterPosition", bloomFilterPosition) .add("numberOfKeys", numberOfKeys) @@ -251,7 +903,7 @@ public Footer decode(InputStream inStream, Coder.Context context) int version = dataIn.read(); if (version != Footer.VERSION) { throw new IOException("Unknown version " + version + ". " - + "Only version 0x01 is currently supported."); + + "Only version 2 is currently supported."); } return footer; } @@ -273,4 +925,3 @@ protected long getEncodedElementByteSize(Footer value, Coder.Context context) } } } - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java index 3a540b6192..f03a2e9887 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java @@ -15,15 +15,29 @@ */ package com.google.cloud.dataflow.sdk.runners.worker; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.Coder.Context; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.Footer; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.FooterCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShard; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShardCoder; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefix; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefixCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.common.collect.ImmutableList; import org.junit.Rule; import org.junit.Test; @@ -32,6 +46,7 @@ import org.junit.runners.JUnit4; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; /** @@ -72,6 +87,205 @@ public void testFooterCoder() throws Exception { assertEquals(25, FooterCoder.of().getEncodedElementByteSize(footerA, Context.OUTER)); } + @Test + public void testNormalIsmRecordWithMetadataKeyIsError() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Expected key components to not contain metadata key"); + IsmRecord.of(ImmutableList.of(IsmFormat.getMetadataKey()), "test"); + } + + @Test + public void testMetadataIsmRecordWithoutMetadataKeyIsError() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Expected key components to contain metadata key"); + IsmRecord.meta(ImmutableList.of("non-metadata key"), "test".getBytes()); + } + + @Test + public void testIsmRecordCoder() throws Exception { + IsmRecord ismRecordA = IsmRecord.of(ImmutableList.of("0"), "1"); + IsmRecord ismRecordB = IsmRecord.of(ImmutableList.of("0"), "1"); + IsmRecord ismMetaRecordA = + IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey()), "2".getBytes()); + IsmRecord ismMetaRecordB = + IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey()), "2".getBytes()); + IsmRecordCoder coder = + IsmRecordCoder.of( + 1, + 0, + ImmutableList.>of(StringUtf8Coder.of()), + StringUtf8Coder.of()); + IsmRecordCoder coderWithMetadata = + IsmRecordCoder.of( + 1, + 1, + ImmutableList.>of(MetadataKeyCoder.of(StringUtf8Coder.of())), + StringUtf8Coder.of()); + + // Non-metadata records against coder without metadata key support + CoderProperties.coderDecodeEncodeEqual(coder, ismRecordA); + CoderProperties.coderDeterministic(coder, ismRecordA, ismRecordB); + CoderProperties.coderConsistentWithEquals(coder, ismRecordA, ismRecordB); + CoderProperties.coderSerializable(coder); + CoderProperties.structuralValueConsistentWithEquals(coder, ismRecordA, ismRecordB); + + // Non-metadata records against coder with metadata key support + CoderProperties.coderDecodeEncodeEqual(coderWithMetadata, ismRecordA); + CoderProperties.coderDeterministic(coderWithMetadata, ismRecordA, ismRecordB); + CoderProperties.coderConsistentWithEquals(coderWithMetadata, ismRecordA, ismRecordB); + CoderProperties.coderSerializable(coderWithMetadata); + CoderProperties.structuralValueConsistentWithEquals(coderWithMetadata, ismRecordA, ismRecordB); + + // Metadata records + CoderProperties.coderDecodeEncodeEqual(coderWithMetadata, ismMetaRecordA); + CoderProperties.coderDeterministic(coderWithMetadata, ismMetaRecordA, ismMetaRecordB); + CoderProperties.coderConsistentWithEquals( + coderWithMetadata, ismMetaRecordA, ismMetaRecordB); + CoderProperties.coderSerializable(coderWithMetadata); + CoderProperties.structuralValueConsistentWithEquals( + coderWithMetadata, ismMetaRecordA, ismMetaRecordB); + } + + @Test + public void testIsmRecordCoderHashWithinExpectedRanges() throws Exception { + IsmRecordCoder coder = + IsmRecordCoder.of( + 2, + 0, + ImmutableList.>of(StringUtf8Coder.of(), StringUtf8Coder.of()), + StringUtf8Coder.of()); + IsmRecordCoder coderWithMetadata = + IsmRecordCoder.of( + 2, + 2, + ImmutableList.>of( + MetadataKeyCoder.of(StringUtf8Coder.of()), StringUtf8Coder.of()), + StringUtf8Coder.of()); + + assertTrue(coder.hash(ImmutableList.of("A", "B")) < IsmFormat.SHARD_BITS + 1); + int hash = coderWithMetadata.hash(ImmutableList.of(IsmFormat.getMetadataKey(), "B")); + assertTrue(hash > IsmFormat.SHARD_BITS && hash < (IsmFormat.SHARD_BITS + 1) * 2); + } + + @Test + public void testIsmRecordCoderWithTooManyKeysIsError() throws Exception { + IsmRecordCoder coder = + IsmRecordCoder.of( + 2, + 0, + ImmutableList.>of(StringUtf8Coder.of(), StringUtf8Coder.of()), + StringUtf8Coder.of()); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Expected at most"); + coder.hash(ImmutableList.of("A", "B", "C")); + } + + @Test + public void testIsmRecordCoderHashWithoutEnoughKeysIsError() throws Exception { + IsmRecordCoder coder = + IsmRecordCoder.of( + 2, + 0, + ImmutableList.>of(StringUtf8Coder.of(), StringUtf8Coder.of()), + StringUtf8Coder.of()); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Expected at least"); + coder.hash(ImmutableList.of("A")); + } + + @Test + public void testIsmRecordCoderMetadataHashWithoutEnoughKeysIsError() throws Exception { + IsmRecordCoder coderWithMetadata = + IsmRecordCoder.of( + 2, + 2, + ImmutableList.>of( + MetadataKeyCoder.of(StringUtf8Coder.of()), StringUtf8Coder.of()), + StringUtf8Coder.of()); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Expected at least"); + coderWithMetadata.hash(ImmutableList.of(IsmFormat.getMetadataKey())); + } + + + @Test + public void testIsmRecordCoderKeyCoderCountMismatch() throws Exception { + IsmRecord ismRecord = IsmRecord.of(ImmutableList.of("0", "too many"), "1"); + IsmRecordCoder coder = + IsmRecordCoder.of( + 1, + 0, + ImmutableList.>of(StringUtf8Coder.of()), + StringUtf8Coder.of()); + + expectedException.expect(CoderException.class); + expectedException.expectMessage("Expected 1 key component(s) but received key"); + coder.encode(ismRecord, new ByteArrayOutputStream(), Context.NESTED); + } + + @Test + public void testIsmRecordToStringEqualsAndHashCode() { + IsmRecord ismRecordA = IsmRecord.of(ImmutableList.of("0"), "1"); + IsmRecord ismRecordB = IsmRecord.of(ImmutableList.of("0"), "1"); + IsmRecord ismRecordC = IsmRecord.of(ImmutableList.of("3"), "4"); + IsmRecord ismRecordAWithMeta = + IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey(), "0"), "2".getBytes()); + IsmRecord ismRecordBWithMeta = + IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey(), "0"), "2".getBytes()); + IsmRecord ismRecordCWithMeta = + IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey(), "0"), "5".getBytes()); + + assertEquals(ismRecordA, ismRecordB); + assertEquals(ismRecordAWithMeta, ismRecordBWithMeta); + assertNotEquals(ismRecordA, ismRecordAWithMeta); + assertNotEquals(ismRecordA, ismRecordC); + assertNotEquals(ismRecordAWithMeta, ismRecordCWithMeta); + + assertEquals(ismRecordA.hashCode(), ismRecordB.hashCode()); + assertEquals(ismRecordAWithMeta.hashCode(), ismRecordBWithMeta.hashCode()); + assertNotEquals(ismRecordA.hashCode(), ismRecordAWithMeta.hashCode()); + assertNotEquals(ismRecordA.hashCode(), ismRecordC.hashCode()); + assertNotEquals(ismRecordAWithMeta.hashCode(), ismRecordCWithMeta.hashCode()); + + assertThat(ismRecordA.toString(), allOf( + containsString("keyComponents=[0]"), + containsString("value=1"), + not(containsString("metadata")))); + assertThat(ismRecordAWithMeta.toString(), allOf( + containsString("keyComponents=[META, 0]"), + containsString("metadata="), + not(containsString("value")))); + } + + @Test + public void testIsmShardCoder() throws Exception { + IsmShard shardA = IsmShard.of(1, 2, 3); + IsmShard shardB = IsmShard.of(1, 2, 3); + CoderProperties.coderDecodeEncodeEqual(IsmShardCoder.of(), shardA); + CoderProperties.coderDeterministic(IsmShardCoder.of(), shardA, shardB); + CoderProperties.coderConsistentWithEquals(IsmShardCoder.of(), shardA, shardB); + CoderProperties.coderSerializable(IsmShardCoder.of()); + CoderProperties.structuralValueConsistentWithEquals(IsmShardCoder.of(), shardA, shardB); + } + + @Test + public void testIsmShardToStringEqualsAndHashCode() { + IsmShard shardA = IsmShard.of(1, 2, 3); + IsmShard shardB = IsmShard.of(1, 2, 3); + IsmShard shardC = IsmShard.of(4, 5, 6); + assertEquals(shardA, shardB); + assertNotEquals(shardA, shardC); + assertEquals(shardA.hashCode(), shardB.hashCode()); + assertNotEquals(shardA.hashCode(), shardC.hashCode()); + assertThat(shardA.toString(), allOf( + containsString("id=1"), + containsString("blockOffset=2"), + containsString("indexOffset=3"))); + } + @Test public void testUnknownVersion() throws Exception { byte[] data = new byte[25]; From 8b4c34e4bed59a775e601381d130e449a4b257f0 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Fri, 29 Jan 2016 11:28:49 -0800 Subject: [PATCH 050/751] Upgrade protobuf runtime to version 3.0.0-beta-1 ----Release Notes---- Dataflow now uses Protocol Buffers version 3.0.0-beta-1, in order to support Google Cloud Platform products such as Cloud Datastore and Cloud Bigtable. This change does not impact older versions of the SDK, which will continue to work as long as they are supported. Users whose pipelines do not use additional proto dependencies should not notice any change. Users that use existing protos, in proto2 or proto3 syntax, are supported but these users must recompile with a version of the Protocol Buffer compiler protoc matching the Dataflow runtime version, 3.0.0-beta-1. User pipeline code does not need to change. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113381485 --- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 7d31ee07fb..78b82b6d65 100644 --- a/pom.xml +++ b/pom.xml @@ -70,14 +70,14 @@ 1.7.7 v2-rev248-1.21.0 v1b3-rev14-1.21.0 - v1beta2-rev1-3.0.2 + v1beta2-rev1-4.0.0 1.21.0 19.0 1.3 2.7.0 2.4 4.11 - 2.5.0 + 3.0.0-beta-1 v1-rev7-1.21.0 1.7.7 v1-rev53-1.21.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index 891bb220d9..89cd29ee88 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -430,7 +430,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-proto-library-all - 0.4.160120 + 0.5.160127 From 61853d1e58f1d888b0bcec3989997c4ee158d9c1 Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 29 Jan 2016 15:40:06 -0800 Subject: [PATCH 051/751] Refactor LateDataDroppingDoFnRunner This moves the LateDataDroppingDoFnRunner into util, removes references to worker code from util, and genericizes the general GroupAlsoByWindowsDoFn. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113405451 --- .../sdk/runners/worker/KeyedWorkItems.java | 36 +----- .../sdk/runners/worker/ParDoFnBase.java | 20 +--- .../runners/worker/StreamingDoFnRunners.java | 65 +++++++++++ .../StreamingGroupAlsoByWindowsDoFn.java | 63 ++--------- ...eamingGroupAlsoByWindowsReshuffleDoFn.java | 1 + .../worker/WindowingWindmillReader.java | 3 +- .../dataflow/sdk/transforms/DoFnTester.java | 2 +- .../cloud/dataflow/sdk/transforms/ParDo.java | 2 +- .../sdk/util/ComposedKeyedWorkItem.java | 56 ++++++++++ .../cloud/dataflow/sdk/util/DoFnRunner.java | 17 ++- .../dataflow/sdk/util/DoFnRunnerBase.java | 2 + .../cloud/dataflow/sdk/util/DoFnRunners.java | 104 +++++++++++------- .../GroupAlsoByWindowViaWindowSetDoFn.java | 96 ++++++++++++++++ .../worker => util}/KeyedWorkItem.java | 16 +-- .../LateDataDroppingDoFnRunner.java | 31 +++--- ...kItemTest.java => KeyedWorkItemsTest.java} | 5 +- .../worker/StreamingDataflowWorkerTest.java | 21 ++-- .../StreamingGroupAlsoByWindowsDoFnTest.java | 15 ++- ...ngGroupAlsoByWindowsReshuffleDoFnTest.java | 3 +- .../StreamingSideInputDoFnRunnerTest.java | 2 +- 20 files changed, 373 insertions(+), 187 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java rename sdk/src/main/java/com/google/cloud/dataflow/sdk/{runners/worker => util}/KeyedWorkItem.java (70%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/{runners/worker => util}/LateDataDroppingDoFnRunner.java (83%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/{KeyedWorkItemTest.java => KeyedWorkItemsTest.java} (98%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java index 8311fdcfde..7a9ece1eda 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java @@ -23,6 +23,8 @@ import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Timer; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.ComposedKeyedWorkItem; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; @@ -79,7 +81,7 @@ public static KeyedWorkItem windmillWorkItem( */ public static KeyedWorkItem elementsWorkItem( K key, Iterable> elementsIterable) { - return new ComposedKeyedWorkItem<>(key, Collections.emptyList(), elementsIterable); + return ComposedKeyedWorkItem.create(key, Collections.emptyList(), elementsIterable); } /** @@ -90,7 +92,7 @@ public static KeyedWorkItem elementsWorkItem( */ public static KeyedWorkItem timersWorkItem( K key, Iterable timersIterable) { - return new ComposedKeyedWorkItem<>( + return ComposedKeyedWorkItem.create( key, timersIterable, Collections.>emptyList()); } @@ -103,8 +105,7 @@ public static KeyedWorkItem timersWorkItem( */ public static KeyedWorkItem workItem( K key, Iterable timersIterable, Iterable> elementsIterable) { - return new ComposedKeyedWorkItem<>( - key, timersIterable, elementsIterable); + return ComposedKeyedWorkItem.create(key, timersIterable, elementsIterable); } private static class WindmillKeyedWorkItem implements KeyedWorkItem { @@ -217,33 +218,6 @@ public int hashCode() { } } - private static class ComposedKeyedWorkItem implements KeyedWorkItem { - private final K key; - private final Iterable timersIterable; - private final Iterable> elementsIterable; - - ComposedKeyedWorkItem(K key, Iterable timersIterable, - Iterable> elementsIterable) { - this.key = key; - this.timersIterable = timersIterable; - this.elementsIterable = elementsIterable; - } - @Override - public K key() { - return key; - } - - @Override - public Iterable timersIterable() { - return timersIterable; - } - - @Override - public Iterable> elementsIterable() { - return elementsIterable; - } - } - /** * Coder that forwards {@code ByteSizeObserver} calls to an underlying element coder. * {@code TimerOrElement} objects never need to be encoded, so this class does not diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java index 585cd06ebd..a1a1181498 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.util.DoFnInfo; import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunner.RequiresLateDataDropping; import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; import com.google.cloud.dataflow.sdk.util.ExecutionContext; @@ -179,21 +178,8 @@ public void output(TupleTag tag, WindowedValue output) { } }; - if (doFnInfo.getDoFn() instanceof StreamingGroupAlsoByWindowsDoFn - && doFnInfo.getDoFn() instanceof RequiresLateDataDropping) { - @SuppressWarnings({"unchecked", "rawtypes"}) - DoFnRunner objectFnRunner = DoFnRunners.lateDataDroppingRunner( - options, - (DoFnInfo) doFnInfo, - sideInputReader, - outputManager, - (TupleTag) mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator); - fnRunner = objectFnRunner; - } else if (hasStreamingSideInput) { - fnRunner = DoFnRunners.streamingSideInputRunner( + if (hasStreamingSideInput) { + fnRunner = StreamingDoFnRunners.streamingSideInputRunner( options, doFnInfo, sideInputReader, @@ -203,7 +189,7 @@ public void output(TupleTag tag, WindowedValue output) { stepContext, addCounterMutator); } else { - fnRunner = DoFnRunners.simpleRunner( + fnRunner = DoFnRunners.createDefault( options, doFnInfo.getDoFn(), sideInputReader, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java new file mode 100644 index 0000000000..f3c2a859e3 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.util.DoFnInfo; +import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; +import com.google.cloud.dataflow.sdk.util.SideInputReader; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.TupleTag; + +import java.util.List; + +/** + * Utility methods for creating {@link DoFnRunner} instances used by streaming Dataflow. + */ +public final class StreamingDoFnRunners { + private StreamingDoFnRunners() { + // Do not instantiate + } + + /** + * Returns an implementation of {@link DoFnRunner} that handles streaming side inputs. + * + *

It blocks and caches input elements if their side inputs are not ready. + */ + public static DoFnRunner streamingSideInputRunner( + PipelineOptions options, + DoFnInfo doFnInfo, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator) { + return new StreamingSideInputDoFnRunner<>( + options, + doFnInfo, + sideInputReader, + outputManager, + mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator, + doFnInfo.getWindowingStrategy()); + } + + +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java index 78977d51b3..c589ec3762 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java @@ -17,18 +17,13 @@ package com.google.cloud.dataflow.sdk.runners.worker; import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.DoFnRunner.RequiresLateDataDropping; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsDoFn; -import com.google.cloud.dataflow.sdk.util.ReduceFnRunner; +import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowViaWindowSetDoFn; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; import com.google.cloud.dataflow.sdk.util.SystemReduceFn; -import com.google.cloud.dataflow.sdk.util.TimerInternals; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.base.Preconditions; @@ -44,64 +39,28 @@ @SystemDoFnInternal public abstract class StreamingGroupAlsoByWindowsDoFn extends DoFn, KV> { - protected final Aggregator droppedDueToClosedWindow = createAggregator( - GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); - protected final Aggregator droppedDueToLateness = createAggregator( - GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); - public static - StreamingGroupAlsoByWindowsDoFn create( + DoFn, KV> create( final WindowingStrategy windowingStrategy, final AppliedCombineFn combineFn, final Coder keyCoder) { Preconditions.checkNotNull(combineFn); - return new StreamingGABWViaWindowSetDoFn<>(windowingStrategy, - SystemReduceFn.combining(keyCoder, combineFn)); + DoFn, KV> fn = + GroupAlsoByWindowViaWindowSetDoFn.create( + windowingStrategy, + SystemReduceFn.combining(keyCoder, combineFn)); + return fn; } public static - DoFn, KV>> createForIterable( - final WindowingStrategy windowingStrategy, - final Coder inputCoder) { + DoFn, KV>> createForIterable( + final WindowingStrategy windowingStrategy, final Coder inputCoder) { // If the windowing strategy indicates we're doing a reshuffle, use the special-path. if (StreamingGroupAlsoByWindowsReshuffleDoFn.isReshuffle(windowingStrategy)) { return new StreamingGroupAlsoByWindowsReshuffleDoFn<>(); } else { - return new StreamingGABWViaWindowSetDoFn<>( + return GroupAlsoByWindowViaWindowSetDoFn.create( windowingStrategy, SystemReduceFn.buffering(inputCoder)); } } - - private static class StreamingGABWViaWindowSetDoFn - extends StreamingGroupAlsoByWindowsDoFn - implements RequiresLateDataDropping { - private final WindowingStrategy windowingStrategy; - private SystemReduceFn.Factory reduceFnFactory; - - public StreamingGABWViaWindowSetDoFn(WindowingStrategy windowingStrategy, - SystemReduceFn.Factory reduceFnFactory) { - @SuppressWarnings("unchecked") - WindowingStrategy noWildcard = (WindowingStrategy) windowingStrategy; - this.windowingStrategy = noWildcard; - this.reduceFnFactory = reduceFnFactory; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - KeyedWorkItem element = c.element(); - - @SuppressWarnings("unchecked") - K key = c.element().key(); - TimerInternals timerInternals = c.windowingInternals().timerInternals(); - ReduceFnRunner runner = new ReduceFnRunner<>( - key, windowingStrategy, timerInternals, c.windowingInternals(), - droppedDueToClosedWindow, reduceFnFactory.create(key)); - - for (TimerData timer : element.timersIterable()) { - runner.onTimer(timer); - } - runner.processElements(element.elementsIterable()); - runner.persist(); - } - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java index 5bb5d64712..ddd9b00bd1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.worker; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.ReshuffleTrigger; import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; import com.google.cloud.dataflow.sdk.util.WindowedValue; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java index 36f7a03ece..5cff492296 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; import com.google.cloud.dataflow.sdk.util.common.CounterSet; @@ -99,7 +100,7 @@ public NativeReaderIterator>> iterator() throw final WorkItem workItem = context.getWork(); final WindowedValue> value = WindowedValue.valueInEmptyWindows( - KeyedWorkItems.windmillWorkItem( + KeyedWorkItems.windmillWorkItem( key, workItem, windowCoder, windowsCoder, kvCoder.getValueCoder())); return new NativeReaderIterator>>() { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java index 02980713b3..544766433c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java @@ -481,7 +481,7 @@ void initializeState() { runnerSideInputs = runnerSideInputs.and(entry.getKey().getTagInternal(), entry.getValue()); } outputManager = new DoFnRunnerBase.ListOutputManager(); - fnRunner = DoFnRunners.simpleRunner( + fnRunner = DoFnRunners.createDefault( options, fn, DirectSideInputReader.of(runnerSideInputs), diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java index 15dd0abd52..f0ed484258 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java @@ -1144,7 +1144,7 @@ private static void evaluateHelpe outputs); DoFnRunner fnRunner = - DoFnRunners.simpleRunner( + DoFnRunners.createDefault( context.getPipelineOptions(), fn, sideInputReader, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java new file mode 100644 index 0000000000..25dd6a7dd0 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; + +/** + * A {@link KeyedWorkItem} composed of an underlying key, {@link TimerData} iterable, and element + * iterable. + */ +public class ComposedKeyedWorkItem implements KeyedWorkItem { + + private final K key; + private final Iterable timers; + private final Iterable> elements; + + public static ComposedKeyedWorkItem create( + K key, Iterable timers, Iterable> elements) { + return new ComposedKeyedWorkItem(key, timers, elements); + } + + private ComposedKeyedWorkItem( + K key, Iterable timers, Iterable> elements) { + this.key = key; + this.timers = timers; + this.elements = elements; + } + + @Override + public K key() { + return key; + } + + @Override + public Iterable timersIterable() { + return timers; + } + + @Override + public Iterable> elementsIterable() { + return elements; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java index 3cc78f0999..51c3f39584 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java @@ -15,8 +15,10 @@ */ package com.google.cloud.dataflow.sdk.util; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.DoFn.ProcessContext; +import com.google.cloud.dataflow.sdk.values.KV; /** * An wrapper interface that represents the execution of a {@link DoFn}. @@ -41,5 +43,18 @@ public interface DoFnRunner { /** * An internal interface for signaling that a {@link DoFn} requires late data dropping. */ - public interface RequiresLateDataDropping {} + public interface ReduceFnExecutor { + /** + * Gets this object as a {@link DoFn}. + * + * Most implementors of this interface are expected to be {@link DoFn} instances, and will + * return themselves. + */ + DoFn, KV> asDoFn(); + + /** + * Returns an aggregator that tracks elements that are dropped due to being late. + */ + Aggregator getDroppedDueToLatenessAggregator(); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index d4954e298a..de2844c7ff 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -135,6 +135,8 @@ public void startBundle() { @Override public void processElement(WindowedValue elem) { + // TODO: Move the DataflowWorkerLoggingMDC into wrapper used on the Dataflow worker in + // invokeProcessElement // Setup new thread local logging before running user code, and restore it after. // Needs to happen here (per-element) since fusion may be running this as part of a call to // output in an earlier step. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java index a65192a23d..d78b45a09a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java @@ -16,13 +16,12 @@ package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.runners.worker.LateDataDroppingDoFnRunner; -import com.google.cloud.dataflow.sdk.runners.worker.StreamingGroupAlsoByWindowsDoFn; -import com.google.cloud.dataflow.sdk.runners.worker.StreamingSideInputDoFnRunner; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.DoFnRunner.ReduceFnExecutor; import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.TupleTag; @@ -47,7 +46,7 @@ public interface OutputManager { * *

It invokes {@link DoFn#processElement} for each input. */ - public static DoFnRunner simpleRunner( + static DoFnRunner simpleRunner( PipelineOptions options, DoFn fn, SideInputReader sideInputReader, @@ -58,27 +57,15 @@ public static DoFnRunner simpleRunner( CounterSet.AddCounterMutator addCounterMutator, WindowingStrategy windowingStrategy) { return new SimpleDoFnRunner<>( - options, fn, sideInputReader, outputManager, mainOutputTag, sideOutputTags, - stepContext, addCounterMutator, windowingStrategy); - } - - /** - * Returns an implementation of {@link DoFnRunner} that handles streaming side inputs. - * - *

It blocks and caches input elements if their side inputs are not ready. - */ - public static DoFnRunner streamingSideInputRunner( - PipelineOptions options, - DoFnInfo doFnInfo, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator) { - return new StreamingSideInputDoFnRunner<>( - options, doFnInfo, sideInputReader, outputManager, mainOutputTag, sideOutputTags, - stepContext, addCounterMutator, doFnInfo.getWindowingStrategy()); + options, + fn, + sideInputReader, + outputManager, + mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator, + windowingStrategy); } /** @@ -86,21 +73,64 @@ public static DoFnRunner streamingSideInputRu * *

It drops elements from expired windows before they reach the underlying {@link DoFn}. */ - public static DoFnRunner, KV> - lateDataDroppingRunner( + static + DoFnRunner, KV> lateDataDroppingRunner( + PipelineOptions options, + ReduceFnExecutor reduceFnExecutor, + SideInputReader sideInputReader, + OutputManager outputManager, + TupleTag> mainOutputTag, + List> sideOutputTags, + StepContext stepContext, + CounterSet.AddCounterMutator addCounterMutator, + WindowingStrategy windowingStrategy) { + LateDataDroppingDoFnRunner runner = + new LateDataDroppingDoFnRunner<>( + options, + reduceFnExecutor, + sideInputReader, + outputManager, + mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator, + windowingStrategy); + return runner; + } + + public static DoFnRunner createDefault( PipelineOptions options, - DoFnInfo, KV> doFnInfo, + DoFn doFn, SideInputReader sideInputReader, OutputManager outputManager, - TupleTag> mainOutputTag, + TupleTag mainOutputTag, List> sideOutputTags, StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator) { - @SuppressWarnings({"unchecked"}) - StreamingGroupAlsoByWindowsDoFn streamingGabwDoFn = - (StreamingGroupAlsoByWindowsDoFn) doFnInfo.getDoFn(); - return new LateDataDroppingDoFnRunner<>( - options, streamingGabwDoFn, sideInputReader, outputManager, mainOutputTag, sideOutputTags, - stepContext, addCounterMutator, doFnInfo.getWindowingStrategy()); + AddCounterMutator addCounterMutator, + WindowingStrategy windowingStrategy) { + if (doFn instanceof ReduceFnExecutor) { + @SuppressWarnings("rawtypes") + ReduceFnExecutor fn = (ReduceFnExecutor) doFn; + return lateDataDroppingRunner( + options, + fn, + sideInputReader, + outputManager, + (TupleTag) mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator, + (WindowingStrategy) windowingStrategy); + } + return simpleRunner( + options, + doFn, + sideInputReader, + outputManager, + mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator, + windowingStrategy); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java new file mode 100644 index 0000000000..e9f23fb327 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.DoFnRunner.ReduceFnExecutor; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.values.KV; + +/** + * A general {@link GroupAlsoByWindowsDoFn}. This delegates all of the logic to the + * {@link ReduceFnRunner}. + */ +@SystemDoFnInternal +public class GroupAlsoByWindowViaWindowSetDoFn< + K, InputT, OutputT, W extends BoundedWindow, RinT extends KeyedWorkItem> + extends DoFn> implements ReduceFnExecutor { + + public static > + DoFn> create( + WindowingStrategy strategy, SystemReduceFn.Factory factory) { + return new GroupAlsoByWindowViaWindowSetDoFn<>(strategy, factory); + } + + protected final Aggregator droppedDueToClosedWindow = + createAggregator( + GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); + protected final Aggregator droppedDueToLateness = + createAggregator(GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); + + private final WindowingStrategy windowingStrategy; + private SystemReduceFn.Factory reduceFnFactory; + + private GroupAlsoByWindowViaWindowSetDoFn( + WindowingStrategy windowingStrategy, + SystemReduceFn.Factory reduceFnFactory) { + @SuppressWarnings("unchecked") + WindowingStrategy noWildcard = (WindowingStrategy) windowingStrategy; + this.windowingStrategy = noWildcard; + this.reduceFnFactory = reduceFnFactory; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + KeyedWorkItem element = c.element(); + + K key = c.element().key(); + TimerInternals timerInternals = c.windowingInternals().timerInternals(); + ReduceFnRunner runner = + new ReduceFnRunner<>( + key, + windowingStrategy, + timerInternals, + c.windowingInternals(), + droppedDueToClosedWindow, + reduceFnFactory.create(key)); + + for (TimerData timer : element.timersIterable()) { + runner.onTimer(timer); + } + runner.processElements(element.elementsIterable()); + runner.persist(); + } + + @Override + public DoFn, KV> asDoFn() { + // Safe contravariant cast + @SuppressWarnings("unchecked") + DoFn, KV> asFn = + (DoFn, KV>) this; + return asFn; + } + + @Override + public Aggregator getDroppedDueToLatenessAggregator() { + return droppedDueToLateness; + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItem.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItem.java similarity index 70% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItem.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItem.java index d6a87e17fa..355f0bbc47 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItem.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItem.java @@ -13,33 +13,29 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.worker; +package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; /** * Interface that contains all the timers and elements associated with a specific work item. * - *

Used as the input type of {@link StreamingGroupAlsoByWindowsDoFn}. - * * @param the key type * @param the element type */ public interface KeyedWorkItem { - /** * Returns the key. */ - public K key(); + K key(); /** - * Returns the timers iterable. + * Returns an iterable containing the timers. */ - public Iterable timersIterable(); + Iterable timersIterable(); /** - * Returns the elements iterable. + * Returns an iterable containing the elements. */ - public Iterable> elementsIterable(); + Iterable> elementsIterable(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LateDataDroppingDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java similarity index 83% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LateDataDroppingDoFnRunner.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java index dc40276272..749438a99a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LateDataDroppingDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java @@ -13,21 +13,13 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.worker; +package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.TimerInternals; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowTracing; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.TupleTag; @@ -58,7 +50,7 @@ public class LateDataDroppingDoFnRunner doFn, + ReduceFnExecutor reduceFnExecutor, SideInputReader sideInputReader, OutputManager outputManager, TupleTag> mainOutputTag, @@ -66,13 +58,20 @@ public LateDataDroppingDoFnRunner( StepContext stepContext, CounterSet.AddCounterMutator addCounterMutator, WindowingStrategy windowingStrategy) { - super(options, doFn, sideInputReader, outputManager, - mainOutputTag, sideOutputTags, stepContext, - addCounterMutator, windowingStrategy); + super( + options, + reduceFnExecutor.asDoFn(), + sideInputReader, + outputManager, + mainOutputTag, + sideOutputTags, + stepContext, + addCounterMutator, + windowingStrategy); this.windowingStrategy = windowingStrategy; this.timerInternals = stepContext.timerInternals(); - droppedDueToLateness = doFn.droppedDueToLateness; + droppedDueToLateness = reduceFnExecutor.getDroppedDueToLatenessAggregator(); } @Override @@ -114,11 +113,11 @@ public boolean apply(WindowedValue input) { } } }); - KeyedWorkItem keyedWorkItem = KeyedWorkItems.workItem( + KeyedWorkItem inputs = ComposedKeyedWorkItem.create( elem.getValue().key(), elem.getValue().timersIterable(), nonLateElements); // This can contain user code. Wrap it in case it throws an exception. try { - fn.processElement(createProcessContext(elem.withValue(keyedWorkItem))); + fn.processElement(createProcessContext(elem.withValue(inputs))); } catch (Throwable t) { // Exception in user code. Throwables.propagateIfInstanceOf(t, UserCodeException.class); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemsTest.java similarity index 98% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemsTest.java index 8f436df0ba..8db559c14d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemsTest.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -45,9 +46,9 @@ import java.util.Collection; import java.util.Collections; -/** Tests for {@link KeyedWorkItem}. */ +/** Tests for {@link KeyedWorkItems}. */ @RunWith(JUnit4.class) -public class KeyedWorkItemTest { +public class KeyedWorkItemsTest { private static final String STATE_FAMILY = "state"; private static final String KEY = "key"; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java index b0714e7b80..1e2f433e60 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java @@ -160,18 +160,19 @@ private String dataStringForIndex(long index) { } private ParallelInstruction makeWindowingSourceInstruction(Coder coder) { - CloudObject encodedCoder = FullWindowedValueCoder.of( - FakeKeyedWorkItemCoder.of(coder), IntervalWindow.getCoder()).asCloudObject(); + CloudObject encodedCoder = + FullWindowedValueCoder.of(FakeKeyedWorkItemCoder.of(coder), IntervalWindow.getCoder()) + .asCloudObject(); return new ParallelInstruction() .setSystemName(DEFAULT_SOURCE_SYSTEM_NAME) - .setRead(new ReadInstruction().setSource( - new Source() - .setSpec(CloudObject.forClass(WindowingWindmillReader.class)) - .setCodec(encodedCoder))) - .setOutputs(Arrays.asList( - new InstructionOutput() - .setName("read_output") - .setCodec(encodedCoder))); + .setRead( + new ReadInstruction() + .setSource( + new Source() + .setSpec(CloudObject.forClass(WindowingWindmillReader.class)) + .setCodec(encodedCoder))) + .setOutputs( + Arrays.asList(new InstructionOutput().setName("read_output").setCodec(encodedCoder))); } private ParallelInstruction makeSourceInstruction(Coder coder) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java index ae185f4b13..5f5f712b32 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java @@ -49,6 +49,7 @@ import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.NullSideInputReader; import com.google.cloud.dataflow.sdk.util.ReshuffleTriggerTest; import com.google.cloud.dataflow.sdk.util.TimeDomain; @@ -171,8 +172,9 @@ private WindowedValue> createValue( WorkItem.Builder workItem, Coder valueCoder) { @SuppressWarnings({"unchecked", "rawtypes"}) Coder> wildcardWindowsCoder = (Coder) windowsCoder; - return WindowedValue.valueInEmptyWindows(KeyedWorkItems.windmillWorkItem( - KEY, workItem.build(), windowCoder, wildcardWindowsCoder, valueCoder)); + return WindowedValue.valueInEmptyWindows( + KeyedWorkItems.windmillWorkItem( + KEY, workItem.build(), windowCoder, wildcardWindowsCoder, valueCoder)); } @Test public void testFixedWindows() throws Exception { @@ -370,7 +372,7 @@ private WindowedValue> createValue( assertThat(item2.getWindows(), Matchers.contains(window(10, 30))); assertEquals( - counters.getExistingCounter("user-merge-DroppedDueToLateness").getAggregate(), + counters.getExistingCounter("merge-DroppedDueToLateness").getAggregate(), new Long(2)); } @@ -556,15 +558,16 @@ DoFnRunner, KV> makeRunner( DoFnInfo, KV> doFnInfo = new DoFnInfo<>(fn, windowingStrategy); - return DoFnRunners.lateDataDroppingRunner( + return DoFnRunners.createDefault( PipelineOptionsFactory.create(), - doFnInfo, + doFnInfo.getDoFn(), NullSideInputReader.empty(), outputManager, outputTag, new ArrayList>(), execContext.getOrCreateStepContext("merge", "merge", null), - counters.getAddCounterMutator()); + counters.getAddCounterMutator(), + doFnInfo.getWindowingStrategy()); } private IntervalWindow window(long start, long end) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java index 0c7cfce3cf..e2f6ef28b6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java @@ -36,6 +36,7 @@ import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.NullSideInputReader; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; @@ -200,7 +201,7 @@ DoFnRunner, KV> makeRunner( WindowingStrategy windowingStrategy, DoFn, KV> fn) { return - DoFnRunners.simpleRunner( + DoFnRunners.createDefault( PipelineOptionsFactory.create(), fn, NullSideInputReader.empty(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java index 90e5bd2693..0c16555604 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java @@ -270,7 +270,7 @@ public void testMultipleSideInputs() throws Exception { typedViews, StringUtf8Coder.of()); return (StreamingSideInputDoFnRunner) - DoFnRunners.streamingSideInputRunner( + StreamingDoFnRunners.streamingSideInputRunner( PipelineOptionsFactory.create(), doFnInfo, mockSideInputReader, From f7feb7191d4d88dd955fbbd7c2d15275d7d0bf21 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Sun, 31 Jan 2016 10:28:43 -0800 Subject: [PATCH 052/751] BigQueryIO: remove DirectRunner dependence on Dataflow native reader The Dataflow-service-specific BigQueryReader should not need to be referenced in BigQueryIO itself. Simplify the code by using the actual element iterator. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113477479 --- .../google/cloud/dataflow/sdk/io/BigQueryIO.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 87258fe42c..fbebd52dc2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -37,7 +37,6 @@ import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.BigQueryReader; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; @@ -46,7 +45,6 @@ import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.ReaderUtils; import com.google.cloud.dataflow.sdk.util.Reshuffle; import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -59,6 +57,7 @@ import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -81,6 +80,7 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Matcher; import java.util.regex.Pattern; + import javax.annotation.Nullable; /** @@ -1411,18 +1411,20 @@ private static void evaluateReadHelper( transform.table.setProjectId(options.getProject()); } - BigQueryReader reader = null; + BigQueryTableRowIterator iterator; if (transform.query != null) { LOG.info("Reading from BigQuery query {}", transform.query); - reader = BigQueryReader.fromQuery(transform.query, options.getProject(), client); + iterator = + BigQueryTableRowIterator.fromQuery( + transform.query, options.getProject(), client, transform.getFlattenResults()); } else { - reader = BigQueryReader.fromTable(transform.table, client); LOG.info("Reading from BigQuery table {}", toTableSpec(transform.table)); + iterator = BigQueryTableRowIterator.fromTable(transform.table, client); } - List> elems = ReaderUtils.readElemsFromReader(reader); + List elems = ImmutableList.copyOf(iterator); LOG.info("Number of records read from BigQuery: {}", elems.size()); - context.setPCollectionWindowedValue(context.getOutput(transform), elems); + context.setPCollection(context.getOutput(transform), elems); } private static List getOrCreateMapListValue(Map> map, K key) { From 0adaa91510e2a0c7301c456a663f0952ab8e531e Mon Sep 17 00:00:00 2001 From: dhalperi Date: Sun, 31 Jan 2016 22:10:31 -0800 Subject: [PATCH 053/751] runners.CountingSource: rename to TestCountingSource To de-dupe names. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113496863 --- .../BoundedReadFromUnboundedSourceTest.java | 7 +++-- .../runners/DataflowPipelineRunnerTest.java | 4 +-- .../runners/dataflow/CustomSourcesTest.java | 7 +++-- ...ingSource.java => TestCountingSource.java} | 27 ++++++++++--------- .../worker/StreamingDataflowWorkerTest.java | 6 ++--- .../StreamingModeExecutionContextTest.java | 6 ++--- 6 files changed, 28 insertions(+), 29 deletions(-) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/{CountingSource.java => TestCountingSource.java} (86%) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java index f0105b676b..d01c036344 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java @@ -23,7 +23,7 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.dataflow.CountingSource; +import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -32,7 +32,6 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import org.joda.time.Duration; - import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; @@ -108,9 +107,9 @@ private void test(boolean dedup, boolean timeBound) throws Exception { if (p.getOptions().getRunner() == DirectPipelineRunner.class) { finalizeTracker = new ArrayList<>(); - CountingSource.setFinalizeTracker(finalizeTracker); + TestCountingSource.setFinalizeTracker(finalizeTracker); } - CountingSource source = new CountingSource(Integer.MAX_VALUE); + TestCountingSource source = new TestCountingSource(Integer.MAX_VALUE); if (dedup) { source = source.withDedup(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index cccdccff28..deabbc0a2f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -48,7 +48,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.dataflow.CountingSource; +import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; @@ -870,7 +870,7 @@ public void testReadBoundedSourceUnsupportedInStreaming() throws Exception { @Test public void testReadUnboundedUnsupportedInBatch() throws Exception { - testUnsupportedSource(Read.from(new CountingSource(1)), "Read.Unbounded", false); + testUnsupportedSource(Read.from(new TestCountingSource(1)), "Read.Unbounded", false); } private void testUnsupportedSink( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index 54bdf60adb..c31a7f066f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -611,15 +611,14 @@ public void testUnboundedSplits() throws Exception { DataflowPipelineOptions options = PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); com.google.api.services.dataflow.model.Source source = - CustomSources.serializeToCloudSource( - new CountingSource(Integer.MAX_VALUE), options); + CustomSources.serializeToCloudSource(new TestCountingSource(Integer.MAX_VALUE), options); List serializedSplits = getStrings(source.getSpec(), CustomSources.SERIALIZED_SOURCE_SPLITS, null); assertEquals(20, serializedSplits.size()); for (String serializedSplit : serializedSplits) { assertTrue( deserializeFromByteArray(decodeBase64(serializedSplit), "source") - instanceof CountingSource); + instanceof TestCountingSource); } } @@ -657,7 +656,7 @@ public void testReadUnboundedReader() throws Exception { CustomSources.create( (CloudObject) CustomSources.serializeToCloudSource( - new CountingSource(Integer.MAX_VALUE), options) + new TestCountingSource(Integer.MAX_VALUE), options) .getSpec(), options, context); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CountingSource.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java similarity index 86% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CountingSource.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java index 933f62fa82..181ddcae5b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CountingSource.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java @@ -44,30 +44,30 @@ * from {@code advance}, in order to simulate a source where not all the data is * available immediately. */ -public class CountingSource - extends UnboundedSource, CountingSource.CounterMark> { +public class TestCountingSource + extends UnboundedSource, TestCountingSource.CounterMark> { private static List finalizeTracker; private final int numMessagesPerShard; private final int shardNumber; private final boolean dedup; public static void setFinalizeTracker(List finalizeTracker) { - CountingSource.finalizeTracker = finalizeTracker; + TestCountingSource.finalizeTracker = finalizeTracker; } - public CountingSource(int numMessagesPerShard) { + public TestCountingSource(int numMessagesPerShard) { this(numMessagesPerShard, 0, false); } - public CountingSource withDedup() { - return new CountingSource(numMessagesPerShard, shardNumber, true); + public TestCountingSource withDedup() { + return new TestCountingSource(numMessagesPerShard, shardNumber, true); } - private CountingSource withShardNumber(int shardNumber) { - return new CountingSource(numMessagesPerShard, shardNumber, dedup); + private TestCountingSource withShardNumber(int shardNumber) { + return new TestCountingSource(numMessagesPerShard, shardNumber, dedup); } - private CountingSource(int numMessagesPerShard, int shardNumber, boolean dedup) { + private TestCountingSource(int numMessagesPerShard, int shardNumber, boolean dedup) { this.numMessagesPerShard = numMessagesPerShard; this.shardNumber = shardNumber; this.dedup = dedup; @@ -78,8 +78,9 @@ public int getShardNumber() { } @Override - public List generateInitialSplits(int desiredNumSplits, PipelineOptions options) { - List splits = new ArrayList<>(); + public List generateInitialSplits( + int desiredNumSplits, PipelineOptions options) { + List splits = new ArrayList<>(); for (int i = 0; i < desiredNumSplits; i++) { splits.add(withShardNumber(i)); } @@ -173,8 +174,8 @@ public byte[] getCurrentRecordId() { public void close() {} @Override - public CountingSource getCurrentSource() { - return CountingSource.this; + public TestCountingSource getCurrentSource() { + return TestCountingSource.this; } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java index 1e2f433e60..d7e6fe706a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java @@ -48,8 +48,8 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.dataflow.CountingSource; import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; +import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItems.FakeKeyedWorkItemCoder; import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; @@ -989,7 +989,7 @@ public void testUnboundedSources() throws Exception { new ReadInstruction() .setSource( CustomSources.serializeToCloudSource( - new CountingSource(1), options))) + new TestCountingSource(1), options))) .setOutputs( Arrays.asList( new InstructionOutput() @@ -1004,7 +1004,7 @@ public void testUnboundedSources() throws Exception { new PrintFn(), 0, StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE), makeSinkInstruction(StringUtf8Coder.of(), 1, GlobalWindow.Coder.INSTANCE)); - CountingSource.setFinalizeTracker(finalizeTracker); + TestCountingSource.setFinalizeTracker(finalizeTracker); FakeWindmillServer server = new FakeWindmillServer(); StreamingDataflowWorker worker = new StreamingDataflowWorker( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java index 826ce11eef..e8f07830b5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java @@ -24,7 +24,7 @@ import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.dataflow.CountingSource; +import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; import com.google.cloud.dataflow.sdk.runners.worker.StreamingDataflowWorker.ReaderCacheEntry; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.testing.PCollectionViewTesting; @@ -168,9 +168,9 @@ public void testReaderCache() throws Exception { /*stateCache=*/null); UnboundedSource.UnboundedReader reader1 = - new CountingSource(Integer.MAX_VALUE).createReader(options, null); + new TestCountingSource(Integer.MAX_VALUE).createReader(options, null); UnboundedSource.UnboundedReader reader2 = - new CountingSource(Integer.MAX_VALUE).createReader(options, null); + new TestCountingSource(Integer.MAX_VALUE).createReader(options, null); readerCache.put(ByteString.copyFromUtf8("0000000000000001"), new ReaderCacheEntry(reader1, 1L)); readerCache.put(ByteString.copyFromUtf8("0000000000000002"), new ReaderCacheEntry(reader2, 2L)); From ef71d473817d514b0982bc90a59383a9766fb130 Mon Sep 17 00:00:00 2001 From: swegner Date: Mon, 1 Feb 2016 11:04:03 -0800 Subject: [PATCH 054/751] Validate DoFn.createAggregate is not called during pipeline processing ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113546770 --- .../cloud/dataflow/sdk/transforms/DoFn.java | 20 ++++- .../sdk/transforms/DoFnReflector.java | 7 +- .../sdk/transforms/DoFnWithContext.java | 26 ++++++- .../dataflow/sdk/transforms/DoFnTest.java | 77 ++++++++++++++++++- .../sdk/transforms/DoFnWithContextTest.java | 77 ++++++++++++++++++- 5 files changed, 197 insertions(+), 10 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java index f299954b11..85bd433071 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; @@ -207,6 +208,8 @@ protected final void setupDelegateAggregators() { for (DelegatingAggregator aggregator : aggregators.values()) { setupDelegateAggregator(aggregator); } + + aggregatorsAreFinal = true; } private final void setupDelegateAggregator( @@ -316,6 +319,11 @@ public DoFn() { private final Map> aggregators; + /** + * Protects aggregators from being created after initialization. + */ + private boolean aggregatorsAreFinal; + /** * Prepares this {@code DoFn} instance for processing a batch of elements. * @@ -382,7 +390,8 @@ protected TypeDescriptor getOutputTypeDescriptor() { /** * Returns an {@link Aggregator} with aggregation logic specified by the * {@link CombineFn} argument. The name provided must be unique across - * {@link Aggregator}s created within the DoFn. + * {@link Aggregator}s created within the DoFn. Aggregators can only be created + * during pipeline construction. * * @param name the name of the aggregator * @param combiner the {@link CombineFn} to use in the aggregator @@ -391,6 +400,7 @@ protected TypeDescriptor getOutputTypeDescriptor() { * @throws NullPointerException if the name or combiner is null * @throws IllegalArgumentException if the given name collides with another * aggregator in this scope + * @throws IllegalStateException if called during pipeline processing. */ protected final Aggregator createAggregator(String name, CombineFn combiner) { @@ -400,6 +410,10 @@ protected TypeDescriptor getOutputTypeDescriptor() { "Cannot create aggregator with name %s." + " An Aggregator with that name already exists within this scope.", name); + + checkState(!aggregatorsAreFinal, "Cannot create an aggregator during DoFn processing." + + " Aggregators should be registered during pipeline construction."); + DelegatingAggregator aggregator = new DelegatingAggregator<>(name, combiner); aggregators.put(name, aggregator); @@ -409,7 +423,8 @@ protected TypeDescriptor getOutputTypeDescriptor() { /** * Returns an {@link Aggregator} with the aggregation logic specified by the * {@link SerializableFunction} argument. The name provided must be unique - * across {@link Aggregator}s created within the DoFn. + * across {@link Aggregator}s created within the DoFn. Aggregators can only be + * created during pipeline construction. * * @param name the name of the aggregator * @param combiner the {@link SerializableFunction} to use in the aggregator @@ -418,6 +433,7 @@ protected TypeDescriptor getOutputTypeDescriptor() { * @throws NullPointerException if the name or combiner is null * @throws IllegalArgumentException if the given name collides with another * aggregator in this scope + * @throws IllegalStateException if called during pipeline processing. */ protected final Aggregator createAggregator(String name, SerializableFunction, AggInputT> combiner) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java index af20054280..c75c013b2c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java @@ -133,10 +133,12 @@ abstract void invokeProcessElement( * @param c the {@link com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.Context} * to pass to {@link StartBundle}. */ - abstract void invokeStartBundle( + void invokeStartBundle( DoFnWithContext fn, DoFnWithContext.Context c, - ExtraContextFactory extra); + ExtraContextFactory extra) { + fn.prepareForProcessing(); + } /** * Invoke the reflected {@link FinishBundle} method on the given instance. @@ -438,6 +440,7 @@ void invokeStartBundle( DoFnWithContext fn, DoFnWithContext.Context c, ExtraContextFactory extra) { + super.invokeStartBundle(fn, c, extra); if (startBundle != null) { invoke(startBundle, fn, c, extra, startBundleArgs); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java index f2f5ba7743..10bf0eb16a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.options.PipelineOptions; @@ -248,6 +249,11 @@ public Duration getAllowedTimestampSkew() { Map> aggregators = new HashMap<>(); + /** + * Protects aggregators from being created after initialization. + */ + private boolean aggregatorsAreFinal; + /** * Returns a {@link TypeDescriptor} capturing what is known statically * about the input type of this {@code DoFnWithContext} instance's most-derived @@ -349,7 +355,8 @@ public interface ExtraContextFactory { /** * Returns an {@link Aggregator} with aggregation logic specified by the * {@link CombineFn} argument. The name provided must be unique across - * {@link Aggregator}s created within the DoFn. + * {@link Aggregator}s created within the DoFn. Aggregators can only be created + * during pipeline construction. * * @param name the name of the aggregator * @param combiner the {@link CombineFn} to use in the aggregator @@ -358,6 +365,7 @@ public interface ExtraContextFactory { * @throws NullPointerException if the name or combiner is null * @throws IllegalArgumentException if the given name collides with another * aggregator in this scope + * @throws IllegalStateException if called during pipeline execution. */ public final Aggregator createAggregator(String name, Combine.CombineFn combiner) { @@ -367,6 +375,10 @@ public interface ExtraContextFactory { "Cannot create aggregator with name %s." + " An Aggregator with that name already exists within this scope.", name); + checkState(!aggregatorsAreFinal, + "Cannot create an aggregator during pipeline execution." + + " Aggregators should be registered during pipeline construction."); + DelegatingAggregator aggregator = new DelegatingAggregator<>(name, combiner); aggregators.put(name, aggregator); @@ -376,7 +388,8 @@ public interface ExtraContextFactory { /** * Returns an {@link Aggregator} with the aggregation logic specified by the * {@link SerializableFunction} argument. The name provided must be unique - * across {@link Aggregator}s created within the DoFn. + * across {@link Aggregator}s created within the DoFn. Aggregators can only be + * created during pipeline construction. * * @param name the name of the aggregator * @param combiner the {@link SerializableFunction} to use in the aggregator @@ -385,10 +398,19 @@ public interface ExtraContextFactory { * @throws NullPointerException if the name or combiner is null * @throws IllegalArgumentException if the given name collides with another * aggregator in this scope + * @throws IllegalStateException if called during pipeline execution. */ public final Aggregator createAggregator( String name, SerializableFunction, AggInputT> combiner) { checkNotNull(combiner, "combiner cannot be null."); return createAggregator(name, Combine.IterableCombineFn.of(combiner)); } + + /** + * Finalize the @{link DoFnWithContext} construction to prepare for processing. + * This method should be called by runners before any processing methods. + */ + void prepareForProcessing() { + aggregatorsAreFinal = true; + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java index b275cd2252..f6df14a72b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java @@ -16,25 +16,33 @@ package com.google.cloud.dataflow.sdk.transforms; +import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; +import com.google.cloud.dataflow.sdk.testing.RunnableOnService; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; import org.junit.Rule; import org.junit.Test; +import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.Serializable; + /** * Tests for DoFn. */ @RunWith(JUnit4.class) -public class DoFnTest { +public class DoFnTest implements Serializable { @Rule - public ExpectedException thrown = ExpectedException.none(); + public transient ExpectedException thrown = ExpectedException.none(); @Test public void testCreateAggregatorWithCombinerSucceeds() { @@ -115,4 +123,69 @@ public void testCreateAggregatorsWithDifferentNamesSucceeds() { assertNotEquals(aggregatorOne, aggregatorTwo); } + + @Test + @Category(RunnableOnService.class) + public void testCreateAggregatorInStartBundleThrows() { + TestPipeline p = createTestPipeline(new DoFn() { + @Override + public void startBundle(DoFn.Context c) throws Exception { + createAggregator("anyAggregate", new MaxIntegerFn()); + } + + @Override + public void processElement(DoFn.ProcessContext c) throws Exception {} + }); + + thrown.expect(PipelineExecutionException.class); + thrown.expectCause(isA(IllegalStateException.class)); + + p.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testCreateAggregatorInProcessElementThrows() { + TestPipeline p = createTestPipeline(new DoFn() { + @Override + public void processElement(ProcessContext c) throws Exception { + createAggregator("anyAggregate", new MaxIntegerFn()); + } + }); + + thrown.expect(PipelineExecutionException.class); + thrown.expectCause(isA(IllegalStateException.class)); + + p.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testCreateAggregatorInFinishBundleThrows() { + TestPipeline p = createTestPipeline(new DoFn() { + @Override + public void finishBundle(DoFn.Context c) throws Exception { + createAggregator("anyAggregate", new MaxIntegerFn()); + } + + @Override + public void processElement(DoFn.ProcessContext c) throws Exception {} + }); + + thrown.expect(PipelineExecutionException.class); + thrown.expectCause(isA(IllegalStateException.class)); + + p.run(); + } + + /** + * Initialize a test pipeline with the specified @{link DoFn}. + */ + private TestPipeline createTestPipeline(DoFn fn) { + TestPipeline pipeline = TestPipeline.create(); + pipeline.apply(Create.of((InputT) null)) + .apply(ParDo.of(fn)); + + return pipeline; + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java index b580139fd7..228b961421 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.transforms; +import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.mock; @@ -23,19 +24,26 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; +import com.google.cloud.dataflow.sdk.testing.RunnableOnService; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; import org.junit.Rule; import org.junit.Test; +import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.Serializable; + /** Tests for {@link DoFnWithContext}. */ @RunWith(JUnit4.class) -public class DoFnWithContextTest { +public class DoFnWithContextTest implements Serializable { @Rule - public ExpectedException thrown = ExpectedException.none(); + public transient ExpectedException thrown = ExpectedException.none(); private class NoOpDoFnWithContext extends DoFnWithContext { @@ -149,4 +157,69 @@ public void testDoFnWithContextUsingAggregators() { verify(agg).addValue(1L); } + + @Test + @Category(RunnableOnService.class) + public void testCreateAggregatorInStartBundleThrows() { + TestPipeline p = createTestPipeline(new DoFnWithContext() { + @StartBundle + public void startBundle(Context c) { + createAggregator("anyAggregate", new MaxIntegerFn()); + } + + @ProcessElement + public void processElement(ProcessContext c) {} + }); + + thrown.expect(PipelineExecutionException.class); + thrown.expectCause(isA(IllegalStateException.class)); + + p.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testCreateAggregatorInProcessElementThrows() { + TestPipeline p = createTestPipeline(new DoFnWithContext() { + @ProcessElement + public void processElement(ProcessContext c) { + createAggregator("anyAggregate", new MaxIntegerFn()); + } + }); + + thrown.expect(PipelineExecutionException.class); + thrown.expectCause(isA(IllegalStateException.class)); + + p.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testCreateAggregatorInFinishBundleThrows() { + TestPipeline p = createTestPipeline(new DoFnWithContext() { + @FinishBundle + public void finishBundle(Context c) { + createAggregator("anyAggregate", new MaxIntegerFn()); + } + + @ProcessElement + public void processElement(ProcessContext c) {} + }); + + thrown.expect(PipelineExecutionException.class); + thrown.expectCause(isA(IllegalStateException.class)); + + p.run(); + } + + /** + * Initialize a test pipeline with the specified @{link DoFn}. + */ + private TestPipeline createTestPipeline(DoFnWithContext fn) { + TestPipeline pipeline = TestPipeline.create(); + pipeline.apply(Create.of((InputT) null)) + .apply(ParDo.of(fn)); + + return pipeline; + } } From 12be5db69759db5c76ce38e43f037eb28bf0e4fc Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 1 Feb 2016 12:38:27 -0800 Subject: [PATCH 055/751] DataflowPipelineRunner: retry source splitting when too many bundles The Cloud Dataflow API has a limited number of bytes it will accept in a request or response payload -- today, 20 MB. One common place this limit can be reached is when a custom source split into many bundles. A common cause of this behavior is when the initial size estimation is wildly inaccurate, so that the Dataflow service requests bundles with a small amount of work. Today, messages hitting this API limit during initial splitting will cause a job to fail. This change adds a one-time step that increases the desired bundle size and retries splitting the source, to let jobs affected by inaccurate size estimation succeed in some cases. Also clean up related code, generalizing and extracting some utility functions to common utility classes and reducing the memory usage in pathological cases, preventing out-of-memory errors. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113557076 --- .../sdk/runners/dataflow/CustomSources.java | 136 +++++++++--------- .../sdk/runners/worker/DataflowApiUtils.java | 60 ++++++++ .../sdk/runners/worker/DataflowWorker.java | 17 ++- .../worker/SourceOperationExecutor.java | 44 +++--- .../runners/dataflow/CustomSourcesTest.java | 62 ++++++-- .../runners/worker/DataflowWorkerTest.java | 10 +- 6 files changed, 211 insertions(+), 118 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java index 0039281c4a..81d607e469 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java @@ -25,6 +25,7 @@ import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; import static com.google.cloud.dataflow.sdk.util.Structs.getString; import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; +import static com.google.common.base.Preconditions.checkArgument; import com.google.api.client.util.BackOff; import com.google.api.client.util.Base64; @@ -33,7 +34,6 @@ import com.google.api.services.dataflow.model.DerivedSource; import com.google.api.services.dataflow.model.DynamicSourceSplit; import com.google.api.services.dataflow.model.SourceMetadata; -import com.google.api.services.dataflow.model.SourceOperationRequest; import com.google.api.services.dataflow.model.SourceOperationResponse; import com.google.api.services.dataflow.model.SourceSplitOptions; import com.google.api.services.dataflow.model.SourceSplitRequest; @@ -47,6 +47,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.worker.DataflowApiUtils; import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; import com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils; import com.google.cloud.dataflow.sdk.runners.worker.StreamingModeExecutionContext; @@ -61,7 +62,6 @@ import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; import com.google.protobuf.ByteString; import org.joda.time.Duration; @@ -87,15 +87,11 @@ public class CustomSources { private static final String SERIALIZED_SOURCE = "serialized_source"; @VisibleForTesting static final String SERIALIZED_SOURCE_SPLITS = "serialized_source_splits"; private static final long DEFAULT_DESIRED_BUNDLE_SIZE_BYTES = 64 * (1 << 20); - - public static final String TOO_MANY_SOURCE_SPLITS_ERROR = - "Total number of Source objects generated by splitIntoBundles() operation, %d, is" - + " larger than the allowable limit, %d. For more information, please check the corresponding" - + " FAQ entry at:\n" - + "https://cloud.google.com/dataflow/faq"; - - // Maximum number of custom source splits currently supported by Dataflow. - private static final int MAX_NUMBER_OF_SPLITS = 16000; + /** + * The current limit on the size of a ReportWorkItemStatus RPC to Google Cloud Dataflow, which + * includes the initial splits, is 20 MB. + */ + public static final long DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES = 20 * (1 << 20); private static final Logger LOG = LoggerFactory.getLogger(CustomSources.class); @@ -144,17 +140,47 @@ public static DynamicSourceSplit toSourceSplit( * Executes a protocol-level split {@code SourceOperationRequest} for bounded sources * by deserializing its source to a {@code BoundedSource}, splitting it, and * serializing results back. + * + *

When the splits produced by this function are too large to be serialized to the Dataflow + * API, splitting is retried once with an increase in the desired bundle size. This change aims + * to work around API limitations on split size. */ - public static SourceOperationResponse performSourceOperation( - SourceOperationRequest request, PipelineOptions options) throws Exception { - SourceOperationResponse response = new SourceOperationResponse(); - if (request.getSplit() != null) { - response.setSplit(performSplit(request.getSplit(), options)); - } else { - throw new UnsupportedOperationException( - "Unsupported source operation request: " + request); - } - return response; + public static SourceOperationResponse performSplit( + SourceSplitRequest request, PipelineOptions options) throws Exception { + Source anySource = deserializeFromCloudSource(request.getSource().getSpec()); + checkArgument( + anySource instanceof BoundedSource, "Cannot split a non-Bounded source: %s", anySource); + BoundedSource source = (BoundedSource) anySource; + + // Compute the desired bundle size given by the service, or default if none was provided. + long desiredBundleSizeBytes = DEFAULT_DESIRED_BUNDLE_SIZE_BYTES; + SourceSplitOptions splitOptions = request.getOptions(); + if (splitOptions != null && splitOptions.getDesiredBundleSizeBytes() != null) { + desiredBundleSizeBytes = splitOptions.getDesiredBundleSizeBytes(); + } + + // Try generating initial splits normally. + SourceSplitResponse splits = performSplit(source, options, desiredBundleSizeBytes); + long serializedSize = DataflowApiUtils.computeSerializedSizeBytes(splits); + + // If split response is too large, scale desired size for expected DATAFLOW_API_SIZE_BYTES/2. + if (serializedSize > DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES) { + double expansion = 2 * (double) serializedSize / DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; + long expandedBundleSizeBytes = (long) (desiredBundleSizeBytes * expansion); + LOG.warn( + "Splitting source {} into bundles of estimated size {} bytes produced {} bundles, which" + + " have total serialized size {} bytes. As this is too large for the Google Cloud" + + " Dataflow API, retrying splitting once with increased desiredBundleSizeBytes {}" + + " to reduce the number of splits.", + source, + desiredBundleSizeBytes, + splits.getBundles().size(), + serializedSize, + expandedBundleSizeBytes); + splits = performSplit(source, options, expandedBundleSizeBytes); + } + + return new SourceOperationResponse().setSplit(splits); } /** @@ -270,9 +296,8 @@ private UnboundedSource parseSource(int index } catch (Exception e) { throw new RuntimeException("Parsing serialized source splits failed: ", e); } - Preconditions.checkArgument( - serializedSplits != null, "UnboundedSource object did not contain splits"); - Preconditions.checkArgument( + checkArgument(serializedSplits != null, "UnboundedSource object did not contain splits"); + checkArgument( index < serializedSplits.size(), "UnboundedSource splits contained too few splits. Requested index was %s, size was %s", index, @@ -287,66 +312,48 @@ private UnboundedSource parseSource(int index } private static SourceSplitResponse performSplit( - SourceSplitRequest request, PipelineOptions options) + BoundedSource source, PipelineOptions options, long desiredBundleSizeBytes) throws Exception { - Source anySource = deserializeFromCloudSource(request.getSource().getSpec()); - if (!(anySource instanceof BoundedSource)) { - throw new UnsupportedOperationException("Cannot split a non-Bounded source: " + anySource); - } - BoundedSource source = (BoundedSource) anySource; - LOG.debug("Splitting source: {}", source); + LOG.debug("Splitting source {} into bundles of size {}", source, desiredBundleSizeBytes); - // Produce simple independent, unsplittable bundles with no metadata attached. - SourceSplitResponse response = new SourceSplitResponse(); - response.setBundles(new ArrayList()); - SourceSplitOptions splitOptions = request.getOptions(); - Long desiredBundleSizeBytes = - (splitOptions == null) ? null : splitOptions.getDesiredBundleSizeBytes(); - if (desiredBundleSizeBytes == null) { - desiredBundleSizeBytes = DEFAULT_DESIRED_BUNDLE_SIZE_BYTES; - } List> bundles = - source.splitIntoBundles(desiredBundleSizeBytes, options); - - if (bundles.size() > MAX_NUMBER_OF_SPLITS) { - throw new IOException( - String.format(TOO_MANY_SOURCE_SPLITS_ERROR, bundles.size(), MAX_NUMBER_OF_SPLITS)); - } + ((BoundedSource) source).splitIntoBundles(desiredBundleSizeBytes, options); + List splits = new ArrayList<>(bundles.size()); + // Produce simple independent, unsplittable bundles with no metadata attached. LOG.debug("Splitting produced {} bundles", bundles.size()); for (BoundedSource split : bundles) { try { split.validate(); } catch (Exception e) { throw new IllegalArgumentException( - "Splitting a valid source produced an invalid bundle. " - + "\nOriginal source: " - + source - + "\nInvalid bundle: " - + split, + String.format( + "Splitting a valid source produced an invalid source." + + "\nOriginal source: %s\nInvalid source: %s", + source, + split), e); } - DerivedSource bundle = new DerivedSource(); - com.google.api.services.dataflow.model.Source cloudSource = - serializeToCloudSource(split, options); - cloudSource.setDoesNotNeedSplitting(true); - - bundle.setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT"); - bundle.setSource(cloudSource); - response.getBundles().add(bundle); + splits.add( + new DerivedSource() + .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") + .setSource(serializeToCloudSource(split, options).setDoesNotNeedSplitting(true))); } - response.setOutcome("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED"); - return response; + + // Return all the splits in the SourceSplitResponse. + return new SourceSplitResponse() + .setBundles(splits) + .setOutcome("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED"); } - public static Source deserializeFromCloudSource(Map spec) throws Exception { + private static Source deserializeFromCloudSource(Map spec) throws Exception { Source source = (Source) deserializeFromByteArray( Base64.decodeBase64(getString(spec, SERIALIZED_SOURCE)), "Source"); try { source.validate(); } catch (Exception e) { - LOG.error("Invalid source: " + source, e); + LOG.error("Invalid source: {}", source, e); throw e; } return source; @@ -396,8 +403,7 @@ public static com.google.api.services.dataflow.model.Source serializeToCloudSour unboundedSource.generateInitialSplits(desiredNumSplits, options)) { encodedSplits.add(encodeBase64String(serializeToByteArray(split))); } - Preconditions.checkArgument( - !encodedSplits.isEmpty(), "UnboundedSources must have at least one split"); + checkArgument(!encodedSplits.isEmpty(), "UnboundedSources must have at least one split"); addStringList(cloudSource.getSpec(), SERIALIZED_SOURCE_SPLITS, encodedSplits); } else { throw new IllegalArgumentException("Unexpected source kind: " + source.getClass()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java new file mode 100644 index 0000000000..5c0d7d7da0 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.api.client.json.GenericJson; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.JsonGenerator; +import com.google.cloud.dataflow.sdk.util.Transport; +import com.google.common.io.ByteStreams; +import com.google.common.io.CountingOutputStream; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * A utility class for generic interactions with the Google Cloud Dataflow API. + */ +public final class DataflowApiUtils { + /** + * Determines the serialized size (in bytes) of the {@link GenericJson} object that will be + * serialized and sent to the Google Cloud Dataflow service API. + * + *

Uses only constant memory. + */ + public static long computeSerializedSizeBytes(GenericJson object) throws IOException { + JsonFactory factory = object.getFactory(); + if (factory == null) { + factory = Transport.getJsonFactory(); + } + + CountingOutputStream stream = new CountingOutputStream(ByteStreams.nullOutputStream()); + JsonGenerator generator = null; + try { + generator = factory.createJsonGenerator(stream, StandardCharsets.UTF_8); + generator.serialize(object); + generator.close(); // also closes the stream. + } finally { + if (generator != null) { + generator.close(); + } + } + return stream.getCount(); + } + + // Prevent construction of utility class. + private DataflowApiUtils() {} +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java index ffef4a053d..322845b127 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java @@ -41,6 +41,7 @@ import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.Weighted; import com.google.cloud.dataflow.sdk.util.WeightedValue; import com.google.cloud.dataflow.sdk.util.common.Counter; import com.google.cloud.dataflow.sdk.util.common.CounterSet; @@ -106,7 +107,7 @@ public class DataflowWorker { private final UserCodeTimeTracker userCodeTimeTracker = new UserCodeTimeTracker(); /** - * A weight in "bytes" for the overhead of a {@link Sized} wrapper in the cache. It is just an + * A weight in "bytes" for the overhead of a {@link Weighted} wrapper in the cache. It is just an * approximation so it is OK for it to be fairly arbitrary as long as it is nonzero. */ private static final int OVERHEAD_WEIGHT = 8; @@ -154,7 +155,7 @@ private boolean doWork(WorkItem workItem) throws IOException { // Populate PipelineOptions with data from work unit. options.setProject(workItem.getProjectId()); - DataflowExecutionContext executionContext = + DataflowExecutionContext executionContext = new DataflowWorkerExecutionContext(sideInputCache, options); CounterSet counters = new CounterSet(); @@ -268,9 +269,15 @@ private void handleWorkError(WorkItem workItem, WorkExecutor worker, long nextRe // TODO: Attach the stack trace as exception details, not to the message. error.setMessage(DataflowWorkerLoggingHandler.formatException(t)); - reportStatus(options, "Failure", workItem, worker == null ? null : worker.getOutputCounters(), - worker == null ? null : worker.getOutputMetrics(), null/*sourceOperationResponse*/, - error == null ? null : Collections.singletonList(error), nextReportIndex); + reportStatus( + options, + "Failure", + workItem, + worker == null ? null : worker.getOutputCounters(), + worker == null ? null : worker.getOutputMetrics(), + null /*sourceOperationResponse*/, + Collections.singletonList(error), + nextReportIndex); } private void reportStatus(DataflowWorkerHarnessOptions options, String status, WorkItem workItem, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java index f66476ab8e..cdace38d2d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java @@ -16,13 +16,11 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import com.google.api.client.json.JsonFactory; import com.google.api.services.dataflow.model.SourceOperationRequest; import com.google.api.services.dataflow.model.SourceOperationResponse; -import com.google.api.services.dataflow.model.SourceSplitResponse; +import com.google.api.services.dataflow.model.SourceSplitRequest; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; -import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.WorkExecutor; @@ -34,17 +32,12 @@ /** * An executor for a source operation, defined by a {@code SourceOperationRequest}. */ -@SuppressWarnings("resource") public class SourceOperationExecutor extends WorkExecutor { private static final Logger LOG = LoggerFactory.getLogger(SourceOperationExecutor.class); public static final String SPLIT_RESPONSE_TOO_LARGE_ERROR = "Total size of the BoundedSource objects generated by splitIntoBundles() operation is larger" - + " than the allowable limit. For more information, please check the corresponding FAQ" - + " entry at :\n" - + "https://cloud.google.com/dataflow/faq"; - // This limit is only used to produce an error message. Actual current limit offered by the - // service may be different. - private static final int SOURCE_OPERATION_RESPONSE_SIZE_LIMIT_MB = 20; + + " than the allowable limit. For more information, please check the corresponding FAQ" + + " entry at https://cloud.google.com/dataflow/pipelines/troubleshooting-your-pipeline"; private final PipelineOptions options; private final SourceOperationRequest request; @@ -61,7 +54,12 @@ public SourceOperationExecutor(PipelineOptions options, @Override public void execute() throws Exception { LOG.debug("Executing source operation"); - this.response = CustomSources.performSourceOperation(request, options); + SourceSplitRequest split = request.getSplit(); + if (split != null) { + this.response = CustomSources.performSplit(split, options); + } else { + throw new UnsupportedOperationException("Unsupported source operation request: " + request); + } LOG.debug("Source operation execution complete"); } @@ -69,25 +67,15 @@ public SourceOperationResponse getResponse() { return response; } - static int determineSplitResponseSize(SourceOperationResponse operationResponse) { + static boolean isSplitResponseTooLarge(SourceOperationResponse operationResponse) { try { - SourceSplitResponse splitResponse = operationResponse.getSplit(); - JsonFactory factory = splitResponse.getFactory(); - if (factory == null) { - factory = Transport.getJsonFactory(); - } - return factory.toByteArray(operationResponse).length; - } catch (OutOfMemoryError e) { - LOG.error("Got exception when trying to serialize split response: " + e.getMessage()); - // We will go out of memory if split response is extremely large. - return Integer.MAX_VALUE; + long splitResponseSize = + DataflowApiUtils.computeSerializedSizeBytes(operationResponse.getSplit()); + return splitResponseSize > CustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; } catch (IOException e) { - throw new RuntimeException(e); + /* Assume that the size is not too large, so that the actual API error is exposed. */ + LOG.warn("Error determining the size of the split response.", e); + return false; } } - - static boolean isSplitResponseTooLarge(SourceOperationResponse operationResponse) { - return determineSplitResponseSize(operationResponse) - >= SOURCE_OPERATION_RESPONSE_SIZE_LIMIT_MB * 1024 * 1024; - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index c31a7f066f..10a432bb3c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -32,6 +32,7 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -45,8 +46,8 @@ import com.google.api.services.dataflow.model.DataflowPackage; import com.google.api.services.dataflow.model.DerivedSource; import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.SourceOperationRequest; import com.google.api.services.dataflow.model.SourceOperationResponse; +import com.google.api.services.dataflow.model.SourceSplitOptions; import com.google.api.services.dataflow.model.SourceSplitRequest; import com.google.api.services.dataflow.model.SourceSplitResponse; import com.google.api.services.dataflow.model.Step; @@ -56,16 +57,19 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; +import com.google.cloud.dataflow.sdk.runners.worker.DataflowApiUtils; import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; import com.google.cloud.dataflow.sdk.runners.worker.StreamingDataflowWorker.ReaderCacheEntry; import com.google.cloud.dataflow.sdk.runners.worker.StreamingModeExecutionContext; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Sample; import com.google.cloud.dataflow.sdk.transforms.Sum; @@ -102,13 +106,15 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; + /** * Tests for {@code BasicSerializableSourceFormat}. */ @RunWith(JUnit4.class) public class CustomSourcesTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule public ExpectedException expectedException = ExpectedException.none(); + @Rule public ExpectedLogs logged = ExpectedLogs.none(CustomSources.class); static class TestIO { public static Read fromRange(int from, int to) { @@ -263,7 +269,7 @@ public void testSplitAndReadBundlesBack() throws Exception { for (int i = 0; i < 10; ++i) { assertEquals(valueInGlobalWindow(10 + i), elems.get(i)); } - SourceSplitResponse response = performSplit(source, options); + SourceSplitResponse response = performSplit(source, options, null /*desiredBundleSizeBytes*/); assertEquals("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED", response.getOutcome()); List bundles = response.getBundles(); assertEquals(5, bundles.size()); @@ -480,12 +486,13 @@ public void testSplittingProducedInvalidSource() throws Exception { translateIOToCloudSource(new SourceProducingInvalidSplits("original", null), options); expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(allOf( - containsString("Splitting a valid source produced an invalid bundle"), - containsString("original"), - containsString("badBundle"))); + expectedException.expectMessage( + allOf( + containsString("Splitting a valid source produced an invalid source"), + containsString("original"), + containsString("badBundle"))); expectedException.expectCause(hasMessage(containsString("intentionally invalid"))); - performSplit(cloudSource, options); + performSplit(cloudSource, options, null /*desiredBundleSizeBytes*/); } private static class FailingReader extends BoundedSource.BoundedReader { @@ -596,13 +603,17 @@ private static com.google.api.services.dataflow.model.Source stepToCloudSource(S } private static SourceSplitResponse performSplit( - com.google.api.services.dataflow.model.Source source, PipelineOptions options) - throws Exception { + com.google.api.services.dataflow.model.Source source, + PipelineOptions options, + @Nullable Long desiredBundleSizeBytes) + throws Exception { SourceSplitRequest splitRequest = new SourceSplitRequest(); splitRequest.setSource(source); - SourceOperationRequest request = new SourceOperationRequest(); - request.setSplit(splitRequest); - SourceOperationResponse response = CustomSources.performSourceOperation(request, options); + if (desiredBundleSizeBytes != null) { + splitRequest.setOptions( + new SourceSplitOptions().setDesiredBundleSizeBytes(desiredBundleSizeBytes)); + } + SourceOperationResponse response = CustomSources.performSplit(splitRequest, options); return response.getSplit(); } @@ -714,4 +725,27 @@ private Windmill.Counter getCounter(StreamingModeExecutionContext context, Strin } return null; } + + @Test + public void testLargeSerializedSizeResplits() throws Exception { + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + // Figure out how many splits of CountingSource are needed to exceed the API limits, using an + // extra factor of 2 to ensure that we go over the limits. + BoundedSource justForSizing = CountingSource.upTo(1000000L); + long size = + DataflowApiUtils.computeSerializedSizeBytes( + translateIOToCloudSource(justForSizing, options)); + long numberToSplitToExceedLimit = + 2 * CustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES / size; + + // Generate a CountingSource and split it into the desired number of splits + // (desired size = 8 bytes, 1 long), triggering the re-split with a larger bundle size. + com.google.api.services.dataflow.model.Source source = + translateIOToCloudSource(CountingSource.upTo(numberToSplitToExceedLimit), options); + SourceSplitResponse split = performSplit(source, options, 8L); + logged.verifyWarn("too large for the Google Cloud Dataflow API"); + logged.verifyWarn(String.format("%d bundles", numberToSplitToExceedLimit)); + assertThat((long) split.getBundles().size(), lessThan(numberToSplitToExceedLimit)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java index afafa1c285..6b11af91b6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java @@ -14,17 +14,16 @@ package com.google.cloud.dataflow.sdk.runners.worker; +import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.google.api.services.dataflow.model.SourceOperationResponse; import com.google.api.services.dataflow.model.SourceSplitResponse; import com.google.api.services.dataflow.model.SourceSplitShard; import com.google.api.services.dataflow.model.WorkItem; @@ -47,6 +46,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.io.IOException; import java.util.Map; /** Unit tests for {@link DataflowWorker}. */ @@ -116,13 +116,11 @@ public void testStopProgressReportInCaseOfFailure() throws Exception { } @Test - public void testIsSplitResponseTooLarge() { + public void testIsSplitResponseTooLarge() throws IOException { SourceSplitResponse splitResponse = new SourceSplitResponse(); splitResponse.setShards( ImmutableList.of(new SourceSplitShard(), new SourceSplitShard())); - assertTrue( - SourceOperationExecutor.determineSplitResponseSize( - new SourceOperationResponse().setSplit(splitResponse)) > 0); + assertThat(DataflowApiUtils.computeSerializedSizeBytes(splitResponse), greaterThan(0L)); } @Test From da4f771142f46c5e6d34b2a0dfeea425a8244f26 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 1 Feb 2016 15:18:38 -0800 Subject: [PATCH 056/751] DataflowWorker: elide some for loops for unused log levels ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113573783 --- .../sdk/runners/worker/DataflowWorker.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java index 322845b127..2b5ee083c9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java @@ -192,15 +192,19 @@ private boolean doWork(WorkItem workItem) throws IOException { } } - // Log all counter values for debugging purposes. - for (Counter counter : counters) { - LOG.trace("COUNTER {}.", counter); + // Log counters for debugging purposes, if TRACE logging is on. + if (LOG.isTraceEnabled()) { + for (Counter counter : counters) { + LOG.trace("COUNTER {}.", counter); + } } - // Log all metrics for debugging purposes. + // Log metrics for debugging purposes, if TRACE logging is on. Collection> metrics = worker.getOutputMetrics(); - for (Metric metric : metrics) { - LOG.trace("METRIC {}: {}", metric.getName(), metric.getValue()); + if (LOG.isTraceEnabled()) { + for (Metric metric : metrics) { + LOG.trace("METRIC {}: {}", metric.getName(), metric.getValue()); + } } // Report job success. From 4638244cc797617fbbc286e61929008ba45859e3 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 1 Feb 2016 15:42:27 -0800 Subject: [PATCH 057/751] BigQueryReader: simplify and remove some redundant code ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113576126 --- .../sdk/runners/worker/BigQueryReader.java | 31 ++------------ .../runners/worker/BigQueryReaderFactory.java | 40 +++++++++---------- .../runners/worker/BigQueryReaderTest.java | 2 +- 3 files changed, 23 insertions(+), 50 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java index 617e5dc2f5..de726712a2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java @@ -21,9 +21,7 @@ import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; -import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.common.annotations.VisibleForTesting; @@ -60,38 +58,17 @@ private BigQueryReader(TableReference tableRef, String query, String projectId, * Returns a {@code BigQueryReader} that uses the specified client to read from the specified * table. */ - public static BigQueryReader fromTable(TableReference tableRef, Bigquery bigQueryClient) { + static BigQueryReader fromTable(TableReference tableRef, Bigquery bigQueryClient) { return new BigQueryReader(tableRef, null, null, bigQueryClient, null); } - /** - * Returns a {@code BigQueryReader} that reads from the specified table. The {@link Bigquery} - * client is constructed at runtime from the specified options. - */ - public static BigQueryReader fromTableWithOptions( - TableReference tableRef, BigQueryOptions bigQueryOptions) { - Bigquery client = Transport.newBigQueryClient(bigQueryOptions).build(); - return new BigQueryReader(tableRef, null, null, client, null); - } - /** * Returns a {@code BigQueryReader} that uses the specified client to read the results from * executing the specified query in the specified project. */ - public static BigQueryReader fromQuery(String query, String projectId, Bigquery bigQueryClient) { - return new BigQueryReader(null, query, projectId, bigQueryClient, true); - } - - /** - * Returns a {@code BigQueryReader} that reads the results from executing the specified query in - * the specified project. The {@link Bigquery} client is constructed at runtime from the - * specified options. - */ - public static BigQueryReader fromQueryWithOptions( - String query, String projectId, BigQueryOptions bigQueryOptions, - @Nullable Boolean flattenResults) { - Bigquery client = Transport.newBigQueryClient(bigQueryOptions).build(); - return new BigQueryReader(null, query, projectId, client, flattenResults); + static BigQueryReader fromQuery( + String query, String projectId, Bigquery bigQueryClient, boolean flatten) { + return new BigQueryReader(null, query, projectId, bigQueryClient, flatten); } public TableReference getTableRef() { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java index a389aef3af..06486e9a17 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java @@ -18,7 +18,9 @@ import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; import static com.google.cloud.dataflow.sdk.util.Structs.getString; +import static com.google.common.base.Preconditions.checkArgument; +import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.TableReference; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; @@ -27,6 +29,7 @@ import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; @@ -46,32 +49,25 @@ public NativeReader create( @Nullable CounterSet.AddCounterMutator addCounterMutator, @Nullable String operationName) throws Exception { - return createTyped(spec, coder, options, executionContext); + return createTyped(spec, options); } - public BigQueryReader createTyped( - CloudObject spec, - Coder coder, - PipelineOptions options, - ExecutionContext executionContext) throws Exception { + private BigQueryReader createTyped(CloudObject spec, PipelineOptions options) throws Exception { + Bigquery client = Transport.newBigQueryClient(options.as(BigQueryOptions.class)).build(); + String query = getString(spec, PropertyNames.BIGQUERY_QUERY, null); - Boolean flatten = getBoolean(spec, PropertyNames.BIGQUERY_FLATTEN_RESULTS, true); if (query != null) { - GcpOptions gcpOptions = options.as(GcpOptions.class); - return BigQueryReader.fromQueryWithOptions( - query, gcpOptions.getProject(), options.as(BigQueryOptions.class), flatten); + String project = options.as(GcpOptions.class).getProject(); + Boolean flatten = getBoolean(spec, PropertyNames.BIGQUERY_FLATTEN_RESULTS, true); + return BigQueryReader.fromQuery(query, project, client, flatten); + } else { + String tableId = getString(spec, PropertyNames.BIGQUERY_TABLE, null); + checkArgument(tableId != null, "Either a table or a query has to be specified"); + String project = getString(spec, PropertyNames.BIGQUERY_PROJECT); + String dataset = getString(spec, PropertyNames.BIGQUERY_DATASET); + return BigQueryReader.fromTable( + new TableReference().setProjectId(project).setDatasetId(dataset).setTableId(tableId), + client); } - - String tableId = getString(spec, PropertyNames.BIGQUERY_TABLE, null); - if (tableId != null) { - return BigQueryReader.fromTableWithOptions( - new TableReference() - .setProjectId(getString(spec, PropertyNames.BIGQUERY_PROJECT)) - .setDatasetId(getString(spec, PropertyNames.BIGQUERY_DATASET)) - .setTableId(tableId), - options.as(BigQueryOptions.class)); - } - - throw new IllegalArgumentException("Either a table or a query has to be specified"); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java index 55acaf834f..e30413c5a3 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java @@ -562,7 +562,7 @@ public void testReadQuery() throws Exception { setUpMockQuery(); Bigquery bigQueryClient = new Bigquery(mockTransport, Transport.getJsonFactory(), null); - BigQueryReader reader = BigQueryReader.fromQuery(QUERY, PROJECT_ID, bigQueryClient); + BigQueryReader reader = BigQueryReader.fromQuery(QUERY, PROJECT_ID, bigQueryClient, true); BigQueryReader.BigQueryReaderIterator iterator = reader.iterator(); assertTrue(iterator.hasNext()); From ea0e7bb62c6911b5ef71bbb79b6a3a05c8812895 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 1 Feb 2016 19:07:19 -0800 Subject: [PATCH 058/751] Create internal-only classifier for Dataflow SDK This creates a valid module which the worker package can depend on so it can share Guava objects between itself and the SDK module until the worker package is fully separated. Users should not depend on this classifier as it will be removed. This is towards ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113593122 --- sdk/pom.xml | 21 +++++++++++++++++++-- worker/pom.xml | 1 + 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index 89cd29ee88..4e6cb6c777 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -289,7 +289,24 @@ maven-shade-plugin 2.3 - + + + internal-only + package + + shade + + + true + internal-only + + + + bundle-and-repackage package @@ -329,7 +346,7 @@ - bundle-rest-without-repackaging diff --git a/worker/pom.xml b/worker/pom.xml index 46def118c2..476d3fbb2f 100644 --- a/worker/pom.xml +++ b/worker/pom.xml @@ -209,6 +209,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all ${project.version} + internal-only From fc98f52f8587755b2cceb73bbcb702a59276388b Mon Sep 17 00:00:00 2001 From: Rafal Wojdyla Date: Thu, 4 Feb 2016 17:14:41 -0500 Subject: [PATCH 059/751] Change BQ mode to append instead of truncate It appears that truncate mode is not supported for unbounded PCollection. Error message: [ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.1:java (default-cli) on project google-cloud-dataflow-java-examples-all: An exception occured while executing th e Java class. null: InvocationTargetException: WriteDisposition.WRITE_TRUNCATE is not supported for unbounded PCollections or when using tablespec functions. -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException --- .../com/google/cloud/dataflow/examples/WindowedWordCount.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java index dddab3a692..2adac55627 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java @@ -251,7 +251,7 @@ public static void main(String[] args) throws IOException { .to(getTableReference(options)) .withSchema(getSchema()) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); + .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)); PipelineResult result = pipeline.run(); From 47178ec5c26993141a8f5149e47e3a703365711b Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 9 Feb 2016 21:48:11 -0800 Subject: [PATCH 060/751] Disable surefire forking in Travis-CI Attempt to fix build issues. See: https://github.com/travis-ci/travis-ci/issues/3396 --- .travis.yml | 35 ++++++++++++----------------------- 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/.travis.yml b/.travis.yml index b12caf64d4..52e1d3a5cb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,29 +9,18 @@ notifications: on_success: change on_failure: always -os: - - linux - - osx - -env: - matrix: - - CUSTOM_JDK="default" - - CUSTOM_JDK="oraclejdk8" - - CUSTOM_JDK="oraclejdk7" - - CUSTOM_JDK="openjdk7" - matrix: - exclude: - # On OSX, run with default JDK only. - - os: osx - env: CUSTOM_JDK="oraclejdk8" - - os: osx - env: CUSTOM_JDK="oraclejdk7" - - os: osx - env: CUSTOM_JDK="openjdk7" - # On Linux, run with specific JDKs only. - - os: linux - env: CUSTOM_JDK="default" + include: + # On OSX, run with default JDK only. + - os: osx + env: MAVEN_OVERRIDE="" + # On Linux, run with specific JDKs only. + - os: linux + env: CUSTOM_JDK="oraclejdk8" MAVEN_OVERRIDE="-DforkCount=0" + - os: linux + env: CUSTOM_JDK="oraclejdk7" MAVEN_OVERRIDE="-DforkCount=0" + - os: linux + env: CUSTOM_JDK="openjdk7" MAVEN_OVERRIDE="-DforkCount=0" before_install: - if [ "$TRAVIS_OS_NAME" == "osx" ]; then export JAVA_HOME=$(/usr/libexec/java_home); fi @@ -42,5 +31,5 @@ install: script: - travis_retry mvn versions:set -DnewVersion=manual_build - - travis_retry mvn install -U + - travis_retry mvn $MAVEN_OVERRIDE install -U - travis_retry travis/test_wordcount.sh From 0166accb000f0ffa8748e47918194cb1929295ec Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 1 Feb 2016 20:10:06 -0800 Subject: [PATCH 061/751] Move Dataflow worker mains to worker maven module This is towards ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113595976 --- .../sdk/options/PipelineOptionsFactory.java | 11 +- .../worker/DataflowWorkProgressUpdater.java | 128 -- .../sdk/runners/worker/DataflowWorker.java | 474 ------- .../runners/worker/DataflowWorkerHarness.java | 375 ------ .../worker/KeyTokenInvalidException.java | 38 + .../sdk/runners/worker/ReaderCacheEntry.java | 32 + .../worker/StreamingDataflowWorker.java | 1050 --------------- .../worker/StreamingModeExecutionContext.java | 2 +- .../runners/worker/WindmillStateReader.java | 4 +- .../runners/dataflow/CustomSourcesTest.java | 2 +- .../DataflowWorkProgressUpdaterTest.java | 479 ------- .../worker/DataflowWorkerHarnessTest.java | 301 ----- .../runners/worker/DataflowWorkerTest.java | 162 --- .../worker/KeyTokenInvalidExceptionTest.java | 37 + .../worker/StreamingDataflowWorkerTest.java | 1182 ----------------- .../StreamingModeExecutionContextTest.java | 1 - .../worker/WindmillStateReaderTest.java | 4 +- worker/pom.xml | 18 +- 18 files changed, 134 insertions(+), 4166 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdater.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdaterTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarnessTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java index bbdc8d5406..e77b89f9a4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java @@ -19,7 +19,6 @@ import com.google.cloud.dataflow.sdk.options.Validation.Required; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; -import com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness; import com.google.cloud.dataflow.sdk.util.StringUtils; import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; import com.google.common.base.Function; @@ -819,14 +818,14 @@ static List getPropertyDescriptors( } /** - * Creates a set of {@link DataflowWorkerHarnessOptions} based of a set of known system - * properties. This is meant to only be used from the {@link DataflowWorkerHarness} as a method to + * Creates a set of Dataflow worker harness options based of a set of known system + * properties. This is meant to only be used from the Dataflow worker harness as a method to * bootstrap the worker harness. * *

For internal use only. * * @return A {@link DataflowWorkerHarnessOptions} object configured for the - * {@link DataflowWorkerHarness}. + * Dataflow worker harness. */ public static DataflowWorkerHarnessOptions createFromSystemPropertiesInternal() throws IOException { @@ -835,11 +834,11 @@ public static DataflowWorkerHarnessOptions createFromSystemPropertiesInternal() /** * Creates a set of {@link DataflowWorkerHarnessOptions} based of a set of known system - * properties. This is meant to only be used from the {@link DataflowWorkerHarness} as a method to + * properties. This is meant to only be used from the Dataflow worker harness as a method to * bootstrap the worker harness. * * @return A {@link DataflowWorkerHarnessOptions} object configured for the - * {@link DataflowWorkerHarness}. + * Dataflow worker harness. * @deprecated for internal use only */ @Deprecated diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdater.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdater.java deleted file mode 100644 index c1e99bd671..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdater.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.buildStatus; -import static com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.uniqueId; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.toDynamicSplitRequest; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudDuration; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudTime; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudDuration; - -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.WorkItem; -import com.google.api.services.dataflow.model.WorkItemServiceState; -import com.google.api.services.dataflow.model.WorkItemStatus; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.util.common.worker.WorkExecutor; -import com.google.cloud.dataflow.sdk.util.common.worker.WorkProgressUpdater; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.concurrent.NotThreadSafe; - -/** - * DataflowWorkProgressUpdater implements the WorkProgressUpdater - * interface for the Cloud Dataflow system. - */ -@NotThreadSafe -public class DataflowWorkProgressUpdater extends WorkProgressUpdater { - private static final Logger LOG = LoggerFactory.getLogger(DataflowWorkProgressUpdater.class); - - /** The Dataflow Worker WorkItem client. */ - private final DataflowWorker.WorkUnitClient workUnitClient; - - /** The WorkItem for which work progress updates are sent. */ - private final WorkItem workItem; - - /** Options specifying information about the pipeline run by the worker.*/ - private final DataflowWorkerHarnessOptions options; - - /** The index to use for the next report sent for the updater's work item. */ - private long nextReportIndex; - - public DataflowWorkProgressUpdater(WorkItem workItem, WorkExecutor worker, - DataflowWorker.WorkUnitClient workUnitClient, DataflowWorkerHarnessOptions options) { - super(worker); - this.workItem = workItem; - this.workUnitClient = workUnitClient; - this.options = options; - this.nextReportIndex = workItem.getInitialReportIndex(); - } - - @Override - protected String workString() { - return uniqueId(workItem); - } - - @Override - protected long getWorkUnitLeaseExpirationTimestamp() { - return getLeaseExpirationTimestamp(workItem); - } - - @Override - protected long getWorkUnitSuggestedReportingInterval(){ - return fromCloudDuration(workItem.getReportStatusInterval()).getMillis(); - } - - @Override - protected void reportProgressHelper() throws Exception { - WorkItemStatus status = buildStatus(workItem, false/*completed*/, worker.getOutputCounters(), - worker.getOutputMetrics(), options, worker.getWorkerProgress(), dynamicSplitResultToReport, - null/*sourceOperationResponse*/, null/*errors*/, - getNextReportIndex(), worker.getWorkerStateSamplerInfo()); - status.setRequestedLeaseDuration(toCloudDuration(Duration.millis(requestedLeaseDurationMs))); - - WorkItemServiceState result = workUnitClient.reportWorkItemStatus(status); - if (result != null) { - // Resets state after a successful progress report. - dynamicSplitResultToReport = null; - nextReportIndex = result.getNextReportIndex(); - - progressReportIntervalMs = nextProgressReportInterval( - fromCloudDuration(result.getReportStatusInterval()).getMillis(), - leaseRemainingTime(getLeaseExpirationTimestamp(result))); - - ApproximateSplitRequest suggestedStopPoint = result.getSplitRequest(); - if (suggestedStopPoint != null) { - LOG.info("Proposing dynamic split of work unit {} at {}", workString(), suggestedStopPoint); - dynamicSplitResultToReport = worker.requestDynamicSplit( - toDynamicSplitRequest(suggestedStopPoint)); - } - } - } - - /** Returns the given work unit's lease expiration timestamp. */ - private long getLeaseExpirationTimestamp(WorkItem workItem) { - return fromCloudTime(workItem.getLeaseExpireTime()).getMillis(); - } - - /** Returns the given work unit service state lease expiration timestamp. */ - private long getLeaseExpirationTimestamp(WorkItemServiceState workItemServiceState) { - return fromCloudTime(workItemServiceState.getLeaseExpireTime()).getMillis(); - } - - /** - * Returns the index to use for the next work item report for the work - * progress updater's work item. - */ - long getNextReportIndex() { - return nextReportIndex; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java deleted file mode 100644 index 2b5ee083c9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorker.java +++ /dev/null @@ -1,474 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.SourceOperationExecutor.SPLIT_RESPONSE_TOO_LARGE_ERROR; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceOperationExecutor.isSplitResponseTooLarge; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.toCloudPosition; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.services.dataflow.model.MetricStructuredName; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.api.services.dataflow.model.SourceOperationResponse; -import com.google.api.services.dataflow.model.Status; -import com.google.api.services.dataflow.model.WorkItem; -import com.google.api.services.dataflow.model.WorkItemServiceState; -import com.google.api.services.dataflow.model.WorkItemStatus; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingHandler; -import com.google.cloud.dataflow.sdk.runners.worker.status.WorkerStatusPages; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudCounterUtils; -import com.google.cloud.dataflow.sdk.util.CloudMetricUtils; -import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.Weighted; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.Metric; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.common.worker.WorkExecutor; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * This is a semi-abstract harness for executing WorkItem tasks in - * Java workers. Concrete implementations need to implement a - * WorkUnitClient. - * - *

DataflowWorker presents one public interface, - * getAndPerformWork(), which uses the WorkUnitClient to get work, - * execute it, and update the work. - */ -public class DataflowWorker { - private static final Logger LOG = LoggerFactory.getLogger(DataflowWorker.class); - - /** - * A client to get and update work items. - */ - private final WorkUnitClient workUnitClient; - - /** - * Pipeline options, initially provided via the constructor and - * partially provided via each work work unit. - */ - private final DataflowWorkerHarnessOptions options; - - /** - * A side input cache shared between all execution contexts. - */ - private final Cache, WeightedValue> sideInputCache; - - private static final int DEFAULT_STATUS_PORT = 18081; - - /** - * Status server returning health of worker. - */ - private WorkerStatusPages statusServer = WorkerStatusPages.create(DEFAULT_STATUS_PORT); - - /** - * Tracker for user code time. - */ - private final UserCodeTimeTracker userCodeTimeTracker = new UserCodeTimeTracker(); - - /** - * A weight in "bytes" for the overhead of a {@link Weighted} wrapper in the cache. It is just an - * approximation so it is OK for it to be fairly arbitrary as long as it is nonzero. - */ - private static final int OVERHEAD_WEIGHT = 8; - - private static final long MEGABYTES = 1024 * 1024; - - - public DataflowWorker(WorkUnitClient workUnitClient, DataflowWorkerHarnessOptions options) { - this.workUnitClient = workUnitClient; - this.options = options; - this.sideInputCache = CacheBuilder.newBuilder() - .maximumWeight(options.getWorkerCacheMb() * MEGABYTES) // weights are in bytes - .weigher(Weighers.fixedWeightKeys(OVERHEAD_WEIGHT)) - .softValues() - .build(); - } - - /** - * Gets WorkItem and performs it; returns true if work was - * successfully completed. - * - *

getAndPerformWork may throw if there is a failure of the - * WorkUnitClient. - */ - public boolean getAndPerformWork() throws IOException { - WorkItem work = workUnitClient.getWorkItem(); - if (work == null) { - return false; - } - return doWork(work); - } - - /** - * Performs the given work; returns true if successful. - * - * @throws IOException Only if the WorkUnitClient fails. - */ - private boolean doWork(WorkItem workItem) throws IOException { - LOG.debug("Executing: {}", workItem); - - WorkExecutor worker = null; - SourceOperationResponse operationResponse = null; - long nextReportIndex = workItem.getInitialReportIndex(); - try { - // Populate PipelineOptions with data from work unit. - options.setProject(workItem.getProjectId()); - - DataflowExecutionContext executionContext = - new DataflowWorkerExecutionContext(sideInputCache, options); - - CounterSet counters = new CounterSet(); - StateSampler sampler = null; - - if (workItem.getMapTask() != null) { - sampler = new StateSampler( - workItem.getMapTask().getStageName() + "-", counters.getAddCounterMutator()); - worker = MapTaskExecutorFactory.create( - options, workItem.getMapTask(), executionContext, counters, sampler); - } else if (workItem.getSourceOperationTask() != null) { - sampler = new StateSampler( - "source-operation-", counters.getAddCounterMutator()); - worker = SourceOperationExecutorFactory.create(options, workItem.getSourceOperationTask()); - } else { - throw new RuntimeException("Unknown kind of work item: " + workItem.toString()); - } - - sampler.addSamplingCallback( - new UserCodeTimeTracker.StateSamplerCallback( - userCodeTimeTracker, workItem.getId())); - - DataflowWorkProgressUpdater progressUpdater = - new DataflowWorkProgressUpdater(workItem, worker, workUnitClient, options); - try (AutoCloseable scope = userCodeTimeTracker.scopedWork( - sampler.getPrefix(), workItem.getId(), counters.getAddCounterMutator())) { - // Nested try/finally is used to make sure worker.close() happen before scope.close(). - try { - executeWork(worker, progressUpdater); - } finally { - worker.close(); - // Grab nextReportIndex so we can use it in handleWorkError if there is an exception. - nextReportIndex = progressUpdater.getNextReportIndex(); - } - } - - // Log counters for debugging purposes, if TRACE logging is on. - if (LOG.isTraceEnabled()) { - for (Counter counter : counters) { - LOG.trace("COUNTER {}.", counter); - } - } - - // Log metrics for debugging purposes, if TRACE logging is on. - Collection> metrics = worker.getOutputMetrics(); - if (LOG.isTraceEnabled()) { - for (Metric metric : metrics) { - LOG.trace("METRIC {}: {}", metric.getName(), metric.getValue()); - } - } - - // Report job success. - // TODO: Find out a generic way for the WorkExecutor to report work-specific results - // into the work update. - operationResponse = - (worker instanceof SourceOperationExecutor) - ? ((SourceOperationExecutor) worker).getResponse() - : null; - - try { - reportStatus( - options, "Success", workItem, counters, metrics, operationResponse, null/*errors*/, - nextReportIndex); - } catch (GoogleJsonResponseException e) { - if ((operationResponse != null) && (worker instanceof SourceOperationExecutor)) { - if (isSplitResponseTooLarge(operationResponse)) { - throw new RuntimeException(SPLIT_RESPONSE_TOO_LARGE_ERROR, e); - } - } - throw e; - } - - return true; - - } catch (Throwable e) { - handleWorkError(workItem, worker, nextReportIndex, e); - return false; - - } finally { - if (worker != null) { - try { - worker.close(); - } catch (Exception exn) { - LOG.warn("Uncaught exception occurred during work unit shutdown:", exn); - } - } - } - } - - /** Executes the work and report progress. For testing only. */ - void executeWork(WorkExecutor worker, DataflowWorkProgressUpdater progressUpdater) - throws Exception { - progressUpdater.startReportingProgress(); - // Blocks while executing the work. - try { - worker.execute(); - } finally { - // stopReportingProgress can throw an exception if the final progress - // update fails. For correctness, the task must then be marked as failed. - progressUpdater.stopReportingProgress(); - } - } - - - /** Handles the exception thrown when reading and executing the work. */ - private void handleWorkError(WorkItem workItem, WorkExecutor worker, long nextReportIndex, - Throwable e) throws IOException { - LOG.warn("Uncaught exception occurred during work unit execution:", e); - - // TODO: Look into moving the stack trace thinning - // into the client. - Throwable t = e instanceof UserCodeException ? e.getCause() : e; - Status error = new Status(); - error.setCode(2); // Code.UNKNOWN. TODO: Replace with a generated definition. - // TODO: Attach the stack trace as exception details, not to the message. - error.setMessage(DataflowWorkerLoggingHandler.formatException(t)); - - reportStatus( - options, - "Failure", - workItem, - worker == null ? null : worker.getOutputCounters(), - worker == null ? null : worker.getOutputMetrics(), - null /*sourceOperationResponse*/, - Collections.singletonList(error), - nextReportIndex); - } - - private void reportStatus(DataflowWorkerHarnessOptions options, String status, WorkItem workItem, - @Nullable CounterSet counters, @Nullable Collection> metrics, - @Nullable SourceOperationResponse operationResponse, @Nullable List errors, - long reportIndex) - throws IOException { - String message = "{} processing work item {}"; - if (null != errors && errors.size() > 0) { - LOG.warn(message, status, uniqueId(workItem)); - } else { - LOG.debug(message, status, uniqueId(workItem)); - } - WorkItemStatus workItemStatus = buildStatus(workItem, true/*completed*/, counters, metrics, - options, null, null, operationResponse, errors, reportIndex); - workUnitClient.reportWorkItemStatus(workItemStatus); - } - - static WorkItemStatus buildStatus( - WorkItem workItem, - boolean completed, - @Nullable CounterSet counters, - @Nullable Collection> metrics, - DataflowWorkerHarnessOptions options, - @Nullable NativeReader.Progress progress, - @Nullable NativeReader.DynamicSplitResult dynamicSplitResult, - @Nullable SourceOperationResponse operationResponse, - @Nullable List errors, - long reportIndex) { - - return buildStatus(workItem, completed, counters, metrics, options, progress, - dynamicSplitResult, operationResponse, errors, reportIndex, null); - } - - static WorkItemStatus buildStatus( - WorkItem workItem, - boolean completed, - @Nullable CounterSet counters, - @Nullable Collection> metrics, - DataflowWorkerHarnessOptions options, - @Nullable NativeReader.Progress progress, - @Nullable NativeReader.DynamicSplitResult dynamicSplitResult, - @Nullable SourceOperationResponse operationResponse, - @Nullable List errors, - long reportIndex, - @Nullable StateSampler.StateSamplerInfo stateSamplerInfo) { - WorkItemStatus status = new WorkItemStatus(); - status.setWorkItemId(Long.toString(workItem.getId())); - status.setCompleted(completed); - status.setReportIndex(reportIndex); - - List counterUpdates = null; - List metricUpdates = null; - - if (counters != null) { - // Currently we lack a reliable exactly-once delivery mechanism for - // work updates, i.e. they can be retried or reordered, so sending - // delta updates could lead to double-counted or missed contributions. - // However, delta updates may be beneficial for performance. - // TODO: Implement exactly-once delivery and use deltas, - // if it ever becomes clear that deltas are necessary for performance. - boolean delta = false; - counterUpdates = CloudCounterUtils.extractCounters(counters, delta); - } - if (metrics != null) { - metricUpdates = CloudMetricUtils.extractCloudMetrics(metrics, options.getWorkerId()); - } - List updates = new ArrayList<>(); - if (counterUpdates != null) { - updates.addAll(counterUpdates); - } - if (metricUpdates != null) { - updates.addAll(metricUpdates); - } - if (stateSamplerInfo != null) { - MetricUpdate update = new MetricUpdate(); - update.setKind("internal"); - MetricStructuredName name = new MetricStructuredName(); - name.setName("state-sampler"); - update.setName(name); - Map metric = new HashMap(); - if (stateSamplerInfo.state != null) { - metric.put("last-state-name", stateSamplerInfo.state); - } - if (stateSamplerInfo.transitionCount != null) { - metric.put("num-transitions", stateSamplerInfo.transitionCount); - } - if (stateSamplerInfo.stateDurationMillis != null) { - metric.put("last-state-duration-ms", - stateSamplerInfo.stateDurationMillis); - } - update.setInternal(metric); - updates.add(update); - } - status.setMetricUpdates(updates); - - // TODO: Provide more structure representation of error, - // e.g., the serialized exception object. - if (errors != null) { - status.setErrors(errors); - } - - if (progress != null) { - status.setReportedProgress(readerProgressToCloudProgress(progress)); - } - if (dynamicSplitResult instanceof NativeReader.DynamicSplitResultWithPosition) { - NativeReader.DynamicSplitResultWithPosition asPosition = - (NativeReader.DynamicSplitResultWithPosition) dynamicSplitResult; - status.setStopPosition(toCloudPosition(asPosition.getAcceptedPosition())); - } else if (dynamicSplitResult instanceof CustomSources.BoundedSourceSplit) { - status.setDynamicSourceSplit( - CustomSources.toSourceSplit( - (CustomSources.BoundedSourceSplit) dynamicSplitResult, options)); - } else if (dynamicSplitResult != null) { - throw new IllegalArgumentException( - "Unexpected type of dynamic split result: " + dynamicSplitResult); - } - - if (workItem.getSourceOperationTask() != null) { - status.setSourceOperationResponse(operationResponse); - } - - return status; - } - - static String uniqueId(WorkItem work) { - return work.getProjectId() + ";" + work.getJobId() + ";" + work.getId(); - } - - /** - * Abstract base class describing a client for WorkItem work units. - */ - public abstract static class WorkUnitClient { - /** - * Returns a new WorkItem unit for this Worker to work on or null - * if no work item is available. - */ - public abstract WorkItem getWorkItem() throws IOException; - - /** - * Reports a {@link WorkItemStatus} for an assigned {@link WorkItem}. - * - * @param workItemStatus the status to report - * @return a {@link WorkItemServiceState} (e.g. a new stop position) - */ - public abstract WorkItemServiceState reportWorkItemStatus(WorkItemStatus workItemStatus) - throws IOException; - } - - /** - * A {@link DataflowExecutionContext} that provides a caching side input reader using - * the worker's shared cache. - */ - private static class DataflowWorkerExecutionContext extends BatchModeExecutionContext { - - private final Cache, WeightedValue> cache; - private final PipelineOptions options; - - public DataflowWorkerExecutionContext( - Cache, WeightedValue> cache, PipelineOptions options) { - super(options); - this.cache = cache; - this.options = options; - } - - @Override - protected SideInputReader getSideInputReader(Iterable sideInputInfos) - throws Exception { - return CachingSideInputReader.of( - DataflowSideInputReader.of(sideInputInfos, options, this), - cache); - } - - @Override - protected SideInputReader getSideInputReaderForViews( - Iterable> sideInputViews) { - throw new UnsupportedOperationException( - "Cannot call getSideInputReaderForViews for batch DataflowWorker: " - + "the MapTask specification should have had SideInputInfo descriptors " - + "for each side input, and a SideInputReader provided via getSideInputReader"); - } - } - - /** - * Runs the status server to report worker health on the specified port. - */ - public void runStatusServer() { - statusServer.start(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java deleted file mode 100644 index 9de057fcd4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarness.java +++ /dev/null @@ -1,375 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudDuration; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudTime; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.Sleeper; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.LeaseWorkItemRequest; -import com.google.api.services.dataflow.model.LeaseWorkItemResponse; -import com.google.api.services.dataflow.model.ReportWorkItemStatusRequest; -import com.google.api.services.dataflow.model.ReportWorkItemStatusResponse; -import com.google.api.services.dataflow.model.WorkItem; -import com.google.api.services.dataflow.model.WorkItemServiceState; -import com.google.api.services.dataflow.model.WorkItemStatus; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingInitializer; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; -import com.google.cloud.dataflow.sdk.util.GcsIOChannelFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.IntervalBoundedExponentialBackOff; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.common.worker.WorkProgressUpdater; -import com.google.common.collect.ImmutableList; - -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.joda.time.Interval; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.PrintStream; -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; - -import javax.annotation.concurrent.ThreadSafe; - -/** - * This is a harness for executing WorkItem tasks in Java workers. - * - *

The worker fetches WorkItem units from the Dataflow Service. - * When the work is complete, the program sends results via the worker service API. - * - *

Returns status code 0 on successful completion, 1 on any uncaught failures. - * - *

TODO: add support for VM initialization via config. - * During initialization, we should take a configuration that specifies - * an initialization function, allowing user code to run on VM startup. - */ -public class DataflowWorkerHarness { - private static final Logger LOG = LoggerFactory.getLogger(DataflowWorkerHarness.class); - - private static final String APPLICATION_NAME = "DataflowWorkerHarness"; - - // ExponentialBackOff parameters for the task retry strategy. Visible for testing. - static final int BACKOFF_INITIAL_INTERVAL_MILLIS = 5000; // 5 second - static final int BACKOFF_MAX_INTERVAL_MILLIS = 5 * 60 * 1000; // 5 min. - - /** - * This uncaught exception handler logs the {@link Throwable} to the logger, {@link System#err} - * and exits the application with status code 1. - */ - static class WorkerUncaughtExceptionHandler implements UncaughtExceptionHandler { - static final WorkerUncaughtExceptionHandler INSTANCE = new WorkerUncaughtExceptionHandler(); - - // Cache the original System.err, because the logging infrastructure modifies it and redirects - // it to a logger. - private static final PrintStream originalStandardError = System.err; - - @Override - public void uncaughtException(Thread thread, Throwable e) { - try { - LOG.error("Uncaught exception in main thread. Exiting with status code 1.", e); - System.err.println("Uncaught exception in main thread. Exiting with status code 1."); - e.printStackTrace(); - } catch (Throwable t) { - originalStandardError.println( - "Uncaught exception in main thread. Exiting with status code 1."); - e.printStackTrace(originalStandardError); - - originalStandardError.println( - "UncaughtExceptionHandler caused another exception to be thrown, as follows:"); - t.printStackTrace(originalStandardError); - } finally { - System.exit(1); - } - } - } - - /** - * Helper for initializing the BackOff used for retries. - */ - private static BackOff createBackOff() { - return new IntervalBoundedExponentialBackOff( - BACKOFF_MAX_INTERVAL_MILLIS, BACKOFF_INITIAL_INTERVAL_MILLIS); - } - - /** - * Fetches and processes work units from the Dataflow service. - */ - public static void main(String[] args) throws Exception { - Thread.setDefaultUncaughtExceptionHandler(WorkerUncaughtExceptionHandler.INSTANCE); - DataflowWorkerLoggingInitializer.initialize(); - - DataflowWorkerHarnessOptions pipelineOptions = - PipelineOptionsFactory.createFromSystemPropertiesInternal(); - DataflowWorkerLoggingInitializer.configure(pipelineOptions); - - final Sleeper sleeper = Sleeper.DEFAULT; - final DataflowWorker worker = create(pipelineOptions); - - worker.runStatusServer(); - - processWork(pipelineOptions, worker, sleeper); - } - - /** - * A thread that repeatedly fetches and processes work units from the Dataflow service. - */ - private static class WorkerThread implements Callable { - // sleeper is used to sleep the appropriate amount of time - WorkerThread(final DataflowWorker worker, final Sleeper sleeper) { - this.worker = worker; - this.sleeper = sleeper; - this.backOff = createBackOff(); - } - - @Override - public Boolean call() { - boolean success = true; - try { - do { // We loop getting and processing work. - success = doWork(); - if (success) { - backOff.reset(); - } - // Sleeping a while if there is a problem with the work, then go on with the next work. - } while (success || BackOffUtils.next(sleeper, backOff)); - } catch (IOException e) { // Failure of BackOff. - LOG.error("Already tried several attempts at working on tasks. Aborting.", e); - } catch (InterruptedException e) { - LOG.error("Interrupted during thread execution or sleep.", e); - } catch (Throwable t) { - LOG.error("Thread {} died.", Thread.currentThread().getId(), t); - } - return false; - } - - private boolean doWork() { - try { - LOG.debug("Thread starting getAndPerformWork."); - boolean success = worker.getAndPerformWork(); - LOG.debug("{} processing one WorkItem.", success ? "Finished" : "Failed"); - return success; - } catch (IOException e) { // If there is a problem getting work. - LOG.debug("There was a problem getting work.", e); - return false; - } catch (Exception e) { // These exceptions are caused by bugs within the SDK - LOG.error("There was an unhandled error caused by the Dataflow SDK.", e); - return false; - } - } - - private final DataflowWorker worker; - private final Sleeper sleeper; - private final BackOff backOff; - } - - // Visible for testing. - static void processWork(DataflowWorkerHarnessOptions pipelineOptions, - final DataflowWorker worker, Sleeper sleeper) throws InterruptedException { - int numThreads = chooseNumberOfThreads(pipelineOptions); - ExecutorService executor = pipelineOptions.getExecutorService(); - final List> tasks = new LinkedList<>(); - - LOG.debug("Starting {} worker threads", numThreads); - // We start the appropriate number of threads. - for (int i = 0; i < numThreads; ++i) { - tasks.add(new WorkerThread(worker, sleeper)); - } - - LOG.debug("Waiting for {} worker threads", numThreads); - // We wait forever unless there is a big problem. - executor.invokeAll(tasks); - LOG.error("All threads died."); - } - - static DataflowWorker create(DataflowWorkerHarnessOptions options) { - DataflowWorkerLoggingMDC.setJobId(options.getJobId()); - DataflowWorkerLoggingMDC.setWorkerId(options.getWorkerId()); - options.setAppName(APPLICATION_NAME); - - // Configure standard IO factories. - IOChannelUtils.setIOFactory("gs", new GcsIOChannelFactory(options)); - - DataflowWorkUnitClient client = DataflowWorkUnitClient.fromOptions(options); - return new DataflowWorker(client, options); - } - - private static int chooseNumberOfThreads(DataflowWorkerHarnessOptions pipelineOptions) { - if (pipelineOptions.getNumberOfWorkerHarnessThreads() != 0) { - return pipelineOptions.getNumberOfWorkerHarnessThreads(); - } - return Math.max(Runtime.getRuntime().availableProcessors(), 1); - } - - /** - * A Dataflow WorkUnit client that fetches WorkItems from the Dataflow service. - */ - @ThreadSafe - static class DataflowWorkUnitClient extends DataflowWorker.WorkUnitClient { - /** - * Work items are reported as complete using this class's reportWorkItemStatus() method - * on the same thread that requested the item using getWorkItem(). - * This thread local variable is used to tag the current thread with the stage start time - * during getWorkItem() so that the elapsed execution time can be easily determined in - * reportWorkItemStatus(). A similar thread-local mechanism is used in DataflowWorkerLoggingMDC - * to track other metadata about the current operation being executed. - */ - private static final ThreadLocal stageStartTime = new ThreadLocal<>(); - - private final Dataflow dataflow; - private final DataflowWorkerHarnessOptions options; - - /** - * Creates a client that fetches WorkItems from the Dataflow service. - * - * @param options The pipeline options. - * @return A WorkItemClient that fetches WorkItems from the Dataflow service. - */ - static DataflowWorkUnitClient fromOptions(DataflowWorkerHarnessOptions options) { - return new DataflowWorkUnitClient( - Transport.newDataflowClient(options).build(), - options); - } - - /** - * Package private constructor for testing. - */ - DataflowWorkUnitClient(Dataflow dataflow, DataflowWorkerHarnessOptions options) { - this.dataflow = dataflow; - this.options = options; - } - - /** - * Gets a {@link WorkItem} from the Dataflow service, or returns null if no work was found. - * - *

If work is returned, the calling thread should call reportWorkItemStatus after completing - * it and before requesting another work item. - */ - @Override - public WorkItem getWorkItem() throws IOException { - LeaseWorkItemRequest request = new LeaseWorkItemRequest(); - request.setFactory(Transport.getJsonFactory()); - request.setWorkItemTypes(ImmutableList.of( - "map_task", "seq_map_task", "remote_source_task")); - // All remote sources require the "remote_source" capability. Dataflow's - // custom sources are further tagged with the format "custom_source". - request.setWorkerCapabilities(ImmutableList.of( - options.getWorkerId(), "remote_source", PropertyNames.CUSTOM_SOURCE_FORMAT)); - request.setWorkerId(options.getWorkerId()); - request.setCurrentWorkerTime(toCloudTime(DateTime.now())); - - // This shouldn't be necessary, but a valid cloud duration string is - // required by the Google API parsing framework. TODO: Fix the framework - // so that an empty or not-present string can be used as a default value. - request.setRequestedLeaseDuration( - toCloudDuration(Duration.millis(WorkProgressUpdater.DEFAULT_LEASE_DURATION_MILLIS))); - - LOG.debug("Leasing work: {}", request); - - LeaseWorkItemResponse response = dataflow.projects().jobs().workItems().lease( - options.getProject(), options.getJobId(), request).execute(); - LOG.debug("Lease work response: {}", response); - - List workItems = response.getWorkItems(); - if (workItems == null || workItems.isEmpty()) { - // We didn't lease any work. - return null; - } else if (workItems.size() > 1) { - throw new IOException( - "This version of the SDK expects no more than one work item from the service: " - + response); - } - - WorkItem work = response.getWorkItems().get(0); - if (work == null || work.getId() == null) { - return null; - } - - // Capture the work item's stage name. - if (work.getMapTask() != null) { - String stage = work.getMapTask().getStageName(); - DataflowWorkerLoggingMDC.setStageName(stage); - LOG.info("Starting MapTask stage {}", stage); - } else if (work.getSeqMapTask() != null) { - String stage = work.getSeqMapTask().getStageName(); - DataflowWorkerLoggingMDC.setStageName(stage); - LOG.info("Starting SeqMapTask stage {}", stage); - } else { - // Only MapTask and SeqMapTask currently have a stage name. - DataflowWorkerLoggingMDC.setStageName(null); - } - - stageStartTime.set(DateTime.now()); - DataflowWorkerLoggingMDC.setWorkId(Long.toString(work.getId())); - // Looks like the work's a'ight. - return work; - } - - /** - * Reports the status of the most recently requested work item. - */ - @Override - public WorkItemServiceState reportWorkItemStatus(WorkItemStatus workItemStatus) - throws IOException { - DateTime endTime = DateTime.now(); - workItemStatus.setFactory(Transport.getJsonFactory()); - LOG.debug("Reporting work status: {}", workItemStatus); - // Log the stage execution time of finished stages that have a stage name. - if (workItemStatus.getCompleted() && DataflowWorkerLoggingMDC.getStageName() != null) { - DateTime startTime = stageStartTime.get(); - if (startTime != null) { - // This thread should have been tagged with the stage start time during getWorkItem(), - Interval elapsed = new Interval(startTime, endTime); - int numErrors = workItemStatus.getErrors() == null - ? 0 : workItemStatus.getErrors().size(); - LOG.info("Finished processing stage {} with {} errors in {} seconds ", - DataflowWorkerLoggingMDC.getStageName(), numErrors, - (double) elapsed.toDurationMillis() / 1000); - } - } - ReportWorkItemStatusResponse result = - dataflow.projects().jobs().workItems().reportStatus( - options.getProject(), options.getJobId(), - new ReportWorkItemStatusRequest() - .setWorkerId(options.getWorkerId()) - .setWorkItemStatuses(Collections.singletonList(workItemStatus)) - .setCurrentWorkerTime(toCloudTime(endTime))) - .execute(); - if (result == null || result.getWorkItemServiceStates() == null - || result.getWorkItemServiceStates().size() != 1) { - throw new IOException( - "This version of the SDK expects exactly one work item service state from the service"); - } - WorkItemServiceState state = result.getWorkItemServiceStates().get(0); - LOG.debug("ReportWorkItemStatus result: {}", state); - return state; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java new file mode 100644 index 0000000000..096a50d356 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +/** + * Indicates that the key token was invalid when data was attempted to be fetched. + */ +public class KeyTokenInvalidException extends RuntimeException { + public KeyTokenInvalidException(String key) { + super("Unable to fetch data due to token mismatch for key " + key); + } + + /** + * Returns whether an exception was caused by a {@link KeyTokenInvalidException}. + */ + public static boolean isKeyTokenInvalidException(Throwable t) { + while (t != null) { + if (t instanceof KeyTokenInvalidException) { + return true; + } + t = t.getCause(); + } + return false; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java new file mode 100644 index 0000000000..0fe0800810 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.io.UnboundedSource; + +/** + * Entry in a per-key UnboundedSource#UnboundedReader cache. + */ +public class ReaderCacheEntry { + UnboundedSource.UnboundedReader reader; + long token; + + public ReaderCacheEntry(UnboundedSource.UnboundedReader reader, long token) { + this.reader = reader; + this.token = token; + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java deleted file mode 100644 index 6f507e9f80..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java +++ /dev/null @@ -1,1050 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.MapTask; -import com.google.api.services.dataflow.model.ParallelInstruction; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingInitializer; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; -import com.google.cloud.dataflow.sdk.runners.worker.status.LastExceptionDataProvider; -import com.google.cloud.dataflow.sdk.runners.worker.status.StatusDataProvider; -import com.google.cloud.dataflow.sdk.runners.worker.status.WorkerStatusPages; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServerStub; -import com.google.cloud.dataflow.sdk.util.BoundedQueueExecutor; -import com.google.cloud.dataflow.sdk.util.MemoryMonitor; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; -import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor; -import com.google.cloud.dataflow.sdk.util.common.worker.OutputObjectAndByteCounter; -import com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.protobuf.ByteString; - -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Random; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Nullable; - -/** - * Implements a Streaming Dataflow worker. - */ -public class StreamingDataflowWorker { - private static final Logger LOG = LoggerFactory.getLogger(StreamingDataflowWorker.class); - // Maximum number of threads for processing. Currently each thread processes one key at a time. - static final int MAX_PROCESSING_THREADS = 300; - static final long THREAD_EXPIRATION_TIME_SEC = 60; - // Maximum work units retrieved from Windmill and queued before processing. Limiting this delays - // retrieving extra work from Windmill without working on it, leading to better - // prioritization / utilization. - static final int MAX_WORK_UNITS_QUEUED = 100; - static final long MAX_COMMIT_BYTES = 32 << 20; - static final String DEFAULT_WINDMILL_SERVER_CLASS_NAME = - "com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServer"; - static final int MAX_COMMIT_QUEUE_BYTES = 500 << 20; // 500MB - - private static final int DEFAULT_STATUS_PORT = 8081; - - // Maximum size of the result of a GetWork request. - private static final long MAX_GET_WORK_FETCH_BYTES = 64L << 20; // 64m - - /** - * Maximum number of items to return in a GetWork request. - */ - private static final long MAX_GET_WORK_ITEMS = 100; - - /** - * Indicates that the key token was invalid when data was attempted to be fetched. - */ - public static class KeyTokenInvalidException extends RuntimeException { - public KeyTokenInvalidException(String key) { - super("Unable to fetch data due to token mismatch for key " + key); - } - } - - /** - * Returns whether an exception was caused by a {@link KeyTokenInvalidException}. - */ - public static boolean isKeyTokenInvalidException(Throwable t) { - while (t != null) { - if (t instanceof KeyTokenInvalidException) { - return true; - } - t = t.getCause(); - } - return false; - } - - /** - * Returns whether an exception was caused by a {@link OutOfMemoryError}. - */ - private static boolean isOutOfMemoryError(Throwable t) { - while (t != null) { - if (t instanceof OutOfMemoryError) { - return true; - } - t = t.getCause(); - } - return false; - } - - static MapTask parseMapTask(String input) throws IOException { - return Transport.getJsonFactory() - .fromString(input, MapTask.class); - } - - public static void main(String[] args) throws Exception { - Thread.setDefaultUncaughtExceptionHandler( - DataflowWorkerHarness.WorkerUncaughtExceptionHandler.INSTANCE); - - new Thread(memoryMonitor).start(); - - DataflowWorkerLoggingInitializer.initialize(); - DataflowWorkerHarnessOptions options = - PipelineOptionsFactory.createFromSystemPropertiesInternal(); - // TODO: Remove setting these options once we have migrated to passing - // through the pipeline options. - options.setAppName("StreamingWorkerHarness"); - options.setStreaming(true); - - DataflowWorkerLoggingInitializer.configure(options); - String hostport = System.getProperty("windmill.hostport"); - if (hostport == null) { - throw new Exception("-Dwindmill.hostport must be set to the location of the windmill server"); - } - String windmillServerClassName = DEFAULT_WINDMILL_SERVER_CLASS_NAME; - if (System.getProperties().containsKey("windmill.serverclassname")) { - windmillServerClassName = System.getProperty("windmill.serverclassname"); - } - - ArrayList mapTasks = new ArrayList<>(); - for (String arg : args) { - mapTasks.add(parseMapTask(arg)); - } - - WindmillServerStub windmillServer = - (WindmillServerStub) Class.forName(windmillServerClassName) - .getDeclaredConstructor(String.class).newInstance(hostport); - - StreamingDataflowWorker worker = - new StreamingDataflowWorker(mapTasks, windmillServer, options); - - worker.start(); - worker.startStatusPages(); - } - - /** - * Entry in a per-key UnboundedSource#UnboundedReader cache. - */ - public static class ReaderCacheEntry { - UnboundedSource.UnboundedReader reader; - long token; - - public ReaderCacheEntry(UnboundedSource.UnboundedReader reader, long token) { - this.reader = reader; - this.token = token; - } - } - - /** - * Bounded set of queues, with a maximum total weight. - */ - private static class KeyedWeightBoundedQueue { - private final ConcurrentMap> queueMap = new ConcurrentHashMap<>(); - private final int maxWeight; - private final Semaphore limit; - private final Function weigher; - - public KeyedWeightBoundedQueue(int maxWeight, Function weigher) { - this.maxWeight = maxWeight; - this.limit = new Semaphore(maxWeight, true); - this.weigher = weigher; - } - - /** - * Adds a new sub-queue for the given key. - */ - public void addQueue(K key) { - queueMap.put(key, new ConcurrentLinkedQueue()); - } - - /** - * Adds the value to the queue for the key, blocking if this would cause the overall weight to - * exceed the limit. - */ - public void put(K key, V value) { - limit.acquireUninterruptibly(Math.max(maxWeight, weigher.apply(value))); - Preconditions.checkNotNull(queueMap.get(key), - "Must create a queue by calling addQueue() before put. Missing key %s", key).add(value); - } - - /** - * Return the set of keys for which there are sub-queues. - */ - public Set keySet() { - return queueMap.keySet(); - } - - /** - * Returns and removes the next value from the given sub-queue, or null if there is no such - * value. - */ - @Nullable - public V poll(K key) { - V result = queueMap.get(key).poll(); - if (result != null) { - limit.release(Math.max(maxWeight, weigher.apply(result))); - } - return result; - } - - /** - * Returns the size of the given sub-queue. - */ - public int queueSize(K key) { - return queueMap.get(key).size(); - } - - /** - * Returns the current weight of all queues. - */ - public int weight() { - return maxWeight - limit.availablePermits(); - } - } - - // Maps from computation ids to per-computation state. - private final ConcurrentMap instructionMap; - private final ConcurrentMap> mapTaskExecutors; - private final ConcurrentMap activeWorkMap; - // Per computation cache of active readers, keyed by split ID. - private final ConcurrentMap> readerCache; - private final KeyedWeightBoundedQueue commitQueue = - new KeyedWeightBoundedQueue<>( - MAX_COMMIT_QUEUE_BYTES, new Function() { - @Override - public Integer apply(Windmill.WorkItemCommitRequest input) { - return input.getSerializedSize(); - } - }); - - // Map of tokens to commit callbacks. - private ConcurrentMap commitCallbacks; - - // Map of user state names to system state names. - private ConcurrentMap stateNameMap; - private ConcurrentMap systemNameToComputationIdMap; - - private WindmillStateCache stateCache = new WindmillStateCache(); - - private ThreadFactory threadFactory; - private BoundedQueueExecutor workUnitExecutor; - private ExecutorService commitExecutor; - private WindmillServerStub windmillServer; - private Thread dispatchThread; - private AtomicBoolean running; - private StateFetcher stateFetcher; - private DataflowWorkerHarnessOptions options; - private long clientId; - private final MetricTrackingWindmillServerStub metricTrackingWindmillServer; - private Timer globalCountersUpdatesTimer; - - private static final MemoryMonitor memoryMonitor = new MemoryMonitor(); - - private final UserCodeTimeTracker userCodeTimeTracker = new UserCodeTimeTracker(); - private final AtomicInteger nextStateSamplerId = new AtomicInteger(); - - private final WorkerStatusPages statusPages = WorkerStatusPages.create(DEFAULT_STATUS_PORT); - - public StreamingDataflowWorker( - List mapTasks, WindmillServerStub server, DataflowWorkerHarnessOptions options) { - this.options = options; - this.instructionMap = new ConcurrentHashMap<>(); - this.mapTaskExecutors = new ConcurrentHashMap<>(); - this.activeWorkMap = new ConcurrentHashMap<>(); - this.readerCache = new ConcurrentHashMap<>(); - this.commitCallbacks = new ConcurrentHashMap<>(); - this.stateNameMap = new ConcurrentHashMap<>(); - this.systemNameToComputationIdMap = new ConcurrentHashMap<>(); - this.threadFactory = new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }; - this.workUnitExecutor = new BoundedQueueExecutor( - chooseMaximumNumberOfThreads(options), THREAD_EXPIRATION_TIME_SEC, TimeUnit.SECONDS, - MAX_WORK_UNITS_QUEUED, threadFactory); - this.commitExecutor = - new ThreadPoolExecutor( - 1, - 1, - Long.MAX_VALUE, - TimeUnit.SECONDS, - new LinkedBlockingQueue(2), - new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - t.setPriority(Thread.MAX_PRIORITY); - t.setName("CommitThread"); - return t; - } - }, - new ThreadPoolExecutor.DiscardPolicy()); - this.windmillServer = server; - this.metricTrackingWindmillServer = new MetricTrackingWindmillServerStub(server, memoryMonitor); - this.running = new AtomicBoolean(); - this.stateFetcher = new StateFetcher(metricTrackingWindmillServer); - this.clientId = new Random().nextLong(); - - for (MapTask mapTask : mapTasks) { - addComputation(mapTask); - } - - DataflowWorkerLoggingMDC.setJobId(options.getJobId()); - DataflowWorkerLoggingMDC.setWorkerId(options.getWorkerId()); - } - - private static int chooseMaximumNumberOfThreads(DataflowWorkerHarnessOptions pipelineOptions) { - if (pipelineOptions.getNumberOfWorkerHarnessThreads() != 0) { - return pipelineOptions.getNumberOfWorkerHarnessThreads(); - } - return MAX_PROCESSING_THREADS; - } - - void addStateNameMappings(Map nameMap) { - stateNameMap.putAll(nameMap); - } - - public void start() { - running.set(true); - dispatchThread = threadFactory.newThread(new Runnable() { - @Override - public void run() { - dispatchLoop(); - } - }); - dispatchThread.setPriority(Thread.MIN_PRIORITY); - dispatchThread.setName("DispatchThread"); - dispatchThread.start(); - globalCountersUpdatesTimer = new Timer("GlobalCountersUpdates"); - // Report counters update every second. - globalCountersUpdatesTimer.schedule(new TimerTask() { - @Override - public void run() { - reportPeriodicStats(); - } - }, 1000, 1000); - reportHarnessStartup(); - } - - public void startStatusPages() { - statusPages.addServlet(stateCache.statusServlet()); - - statusPages.addStatusDataProvider("harness", "Harness", new HarnessDataProvider()); - statusPages.addStatusDataProvider("resources", "Resources", memoryMonitor); - statusPages.addStatusDataProvider("metrics", "Metrics", new MetricsDataProvider()); - statusPages.addStatusDataProvider( - "exception", "Last Exception", new LastExceptionDataProvider()); - statusPages.addStatusDataProvider("specs", "Specs", new SpecsDataProvider()); - statusPages.addStatusDataProvider("cache", "State Cache", stateCache); - - statusPages.start(); - } - - public void stop() { - try { - if (globalCountersUpdatesTimer != null) { - globalCountersUpdatesTimer.cancel(); - } - statusPages.stop(); - running.set(false); - dispatchThread.join(); - workUnitExecutor.shutdown(); - if (!workUnitExecutor.awaitTermination(5, TimeUnit.MINUTES)) { - throw new RuntimeException("Work executor did not terminate within 5 minutes"); - } - for (ConcurrentLinkedQueue queue : mapTaskExecutors.values()) { - WorkerAndContext workerAndContext; - while ((workerAndContext = queue.poll()) != null) { - workerAndContext.getWorker().close(); - } - } - commitExecutor.shutdown(); - if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES)) { - throw new RuntimeException("Commit executor did not terminate within 5 minutes"); - } - } catch (Exception e) { - LOG.warn("Exception while shutting down: ", e); - } - } - - private void addComputation(MapTask mapTask) { - String computationId = - systemNameToComputationIdMap.containsKey(mapTask.getSystemName()) - ? systemNameToComputationIdMap.get(mapTask.getSystemName()) - : mapTask.getSystemName(); - if (!instructionMap.containsKey(computationId)) { - LOG.info("Adding config for {}: {}", computationId, mapTask); - commitQueue.addQueue(computationId); - instructionMap.put(computationId, mapTask); - mapTaskExecutors.put(computationId, new ConcurrentLinkedQueue()); - activeWorkMap.put(computationId, new ActiveWorkForComputation(workUnitExecutor)); - readerCache.put( - computationId, new ConcurrentHashMap()); - } - } - - private static void sleep(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - // NOLINT - } - } - - private void dispatchLoop() { - LOG.info("Dispatch starting"); - while (running.get()) { - memoryMonitor.waitForResources("GetWork"); - - int backoff = 1; - Windmill.GetWorkResponse workResponse; - do { - workResponse = getWork(); - if (workResponse.getWorkCount() > 0) { - break; - } - sleep(backoff); - backoff = Math.min(1000, backoff * 2); - } while (running.get()); - for (final Windmill.ComputationWorkItems computationWork : workResponse.getWorkList()) { - final String computation = computationWork.getComputationId(); - if (!instructionMap.containsKey(computation)) { - getConfig(computation); - } - final MapTask mapTask = instructionMap.get(computation); - if (mapTask == null) { - LOG.warn( - "Received work for unknown computation: {}. Known computations are {}", - computation, instructionMap.keySet()); - continue; - } - - // May be null if input watermark not yet known. - // TODO: Can assert this is non-null once Windmill waits for known input watermark. - @Nullable - final Instant inputDataWatermark = - WindmillTimeUtils.windmillToHarnessInputWatermark( - computationWork.getInputDataWatermark()); - @Nullable - final Instant synchronizedProcessingTime = - WindmillTimeUtils.windmillToHarnessInputWatermark( - computationWork.getDependentRealtimeInputWatermark()); - ActiveWorkForComputation activeWork = activeWorkMap.get(computation); - for (final Windmill.WorkItem workItem : computationWork.getWorkList()) { - // May be null if output watermark not yet known. - @Nullable - final Instant outputDataWatermark = - WindmillTimeUtils.windmillToHarnessOutputWatermark( - workItem.getOutputDataWatermark()); - Preconditions.checkState(inputDataWatermark == null || outputDataWatermark == null - || !outputDataWatermark.isAfter(inputDataWatermark)); - Work work = new Work(workItem.getWorkToken()) { - @Override - public void run() { - process(computation, mapTask, inputDataWatermark, outputDataWatermark, - synchronizedProcessingTime, workItem); - } - }; - if (activeWork.activateWork(workItem.getKey(), work)) { - workUnitExecutor.execute(work); - } - } - } - } - LOG.info("Dispatch done"); - } - - abstract static class Work implements Runnable { - private final long workToken; - public Work(long workToken) { - this.workToken = workToken; - } - public long getWorkToken() { - return workToken; - } - } - - private void process(final String computation, final MapTask mapTask, - @Nullable final Instant inputDataWatermark, @Nullable final Instant outputDataWatermark, - @Nullable final Instant synchronizedProcessingTime, - final Windmill.WorkItem work) { - LOG.debug("Starting processing for {}:\n{}", computation, work); - - Windmill.WorkItemCommitRequest.Builder outputBuilder = - Windmill.WorkItemCommitRequest.newBuilder() - .setKey(work.getKey()) - .setWorkToken(work.getWorkToken()); - - StreamingModeExecutionContext context = null; - MapTaskExecutor worker = null; - - try { - DataflowWorkerLoggingMDC.setWorkId( - work.getKey().toStringUtf8() + "-" + Long.toString(work.getWorkToken())); - DataflowWorkerLoggingMDC.setStageName(computation); - WorkerAndContext workerAndContext = mapTaskExecutors.get(computation).poll(); - if (workerAndContext == null) { - CounterSet counters = new CounterSet(); - context = new StreamingModeExecutionContext(mapTask.getSystemName(), - readerCache.get(computation), stateNameMap, stateCache.forComputation(computation)); - StateSampler sampler = - new StateSampler(mapTask.getStageName() + "-", counters.getAddCounterMutator()); - // In streaming mode, state samplers are long lived. So here a unique id is generated as - // the item_id for the userCodeTimeTracker. - int stateSamplerId = nextStateSamplerId.incrementAndGet(); - sampler.addSamplingCallback( - new UserCodeTimeTracker.StateSamplerCallback( - userCodeTimeTracker, stateSamplerId)); - // "work" will never finish here. - userCodeTimeTracker.workStarted( - sampler.getPrefix(), stateSamplerId, counters.getAddCounterMutator()); - worker = MapTaskExecutorFactory.create(options, mapTask, context, counters, sampler); - ReadOperation readOperation = worker.getReadOperation(); - // Disable progress updates since its results are unused for streaming - // and involves starting a thread. - readOperation.setProgressUpdatePeriodMs(ReadOperation.DONT_UPDATE_PERIODICALLY); - Preconditions.checkState( - worker.supportsRestart(), "Streaming runner requires all operations support restart."); - - // If using a custom source, count bytes read for autoscaling. - ParallelInstruction read = mapTask.getInstructions().get(0); - if (CustomSources.class.getName().equals( - read.getRead().getSource().getSpec().get("@type"))) { - Coder coder = Serializer.deserialize(read.getOutputs().get(0).getCodec(), Coder.class); - readOperation.receivers[0].addOutputCounter( - new OutputObjectAndByteCounter( - new MapTaskExecutorFactory.ElementByteSizeObservableCoder<>(coder), - worker.getOutputCounters().getAddCounterMutator()) - .setSamplingPeriod(100) - .countBytes("dataflow_input_size-" + mapTask.getSystemName())); - } - } else { - worker = workerAndContext.getWorker(); - context = workerAndContext.getContext(); - } - - WindmillStateReader stateReader = new WindmillStateReader( - metricTrackingWindmillServer, computation, work.getKey(), work.getWorkToken()); - StateFetcher localStateFetcher = stateFetcher.byteTrackingView(); - context.start(work, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime, - stateReader, localStateFetcher, outputBuilder); - - for (Long callbackId : context.getReadyCommitCallbackIds()) { - final Runnable callback = commitCallbacks.remove(callbackId); - if (callback != null) { - workUnitExecutor.forceExecute(new Runnable() { - @Override - public void run() { - try { - callback.run(); - } catch (Throwable t) { - // TODO: Count interesting failures. - LOG.error("Source checkpoint finalization failed:", t); - } - } - }); - } - } - - // Blocks while executing work. - worker.execute(); - - commitCallbacks.putAll(context.flushState()); - - // Compute shuffle and state byte statistics after the work is completely done, but before - // counters are added to the outputBuilder. - long shuffleBytesRead = 0; - for (Windmill.InputMessageBundle bundle : work.getMessageBundlesList()) { - for (Windmill.Message message : bundle.getMessagesList()) { - shuffleBytesRead += message.getSerializedSize(); - } - } - long stateBytesRead = stateReader.getBytesRead() + localStateFetcher.getBytesRead(); - long stateBytesWritten = Windmill.WorkItemCommitRequest.newBuilder(outputBuilder.build()) - .clearOutputMessages() - .build() - .getSerializedSize(); - CounterSet counters = worker.getOutputCounters(); - counters - .getAddCounterMutator() - .addCounter(Counter.longs("WindmillShuffleBytesRead", Counter.AggregationKind.SUM)) - .addValue(shuffleBytesRead); - counters - .getAddCounterMutator() - .addCounter(Counter.longs("WindmillStateBytesRead", Counter.AggregationKind.SUM)) - .addValue(stateBytesRead); - counters - .getAddCounterMutator() - .addCounter(Counter.longs("WindmillStateBytesWritten", Counter.AggregationKind.SUM)) - .addValue(stateBytesWritten); - - buildCounters(counters, outputBuilder); - - mapTaskExecutors.get(computation).offer(new WorkerAndContext(worker, context)); - worker = null; - context = null; - - commitQueue.put(computation, outputBuilder.build()); - scheduleCommit(); - - LOG.debug("Processing done for work token: {}", work.getWorkToken()); - } catch (Throwable t) { - if (worker != null) { - try { - worker.close(); - } catch (Exception e) { - LOG.warn("Failed to close worker: ", e); - } finally { - // Release references to potentially large objects early. - worker = null; - context = null; - } - } - - t = t instanceof UserCodeException ? t.getCause() : t; - - if (isOutOfMemoryError(t)) { - reportFailure(computation, work, t); - LOG.error("Received OutOfMemoryError, crashing. Error was ", t); - System.exit(1); - } else if (isKeyTokenInvalidException(t)) { - LOG.debug( - "Execution of work for {} for key {} failed due to token expiration, " - + "will not retry locally.", - computation, work.getKey().toStringUtf8()); - activeWorkMap.get(computation).completeWork(work.getKey()); - } else { - LOG.error( - "Execution of work for {} for key {} failed, retrying.", - computation, - work.getKey().toStringUtf8()); - LOG.error("\nError: ", t); - LastExceptionDataProvider.reportException(t); - LOG.debug("Failed work: {}", work); - if (reportFailure(computation, work, t)) { - // Try again, after some delay and at the end of the queue to avoid a tight loop. - sleep(10000); - workUnitExecutor.forceExecute(new Runnable() { - @Override - public void run() { - process(computation, mapTask, inputDataWatermark, outputDataWatermark, - synchronizedProcessingTime, work); - } - }); - } else { - // If we failed to report the error, the item is invalid and should - // not be retried internally. It will be retried at the higher level. - LOG.debug("Aborting processing due to exception reporting failure"); - activeWorkMap.get(computation).completeWork(work.getKey()); - } - } - } finally { - DataflowWorkerLoggingMDC.setWorkId(null); - DataflowWorkerLoggingMDC.setStageName(null); - } - } - - private void scheduleCommit() { - commitExecutor.execute(new Commit()); - } - - private class Commit implements Runnable { - @Override - public void run() { - while (true) { - Windmill.CommitWorkRequest.Builder commitRequestBuilder = - Windmill.CommitWorkRequest.newBuilder(); - long remainingCommitBytes = MAX_COMMIT_BYTES; - for (String computation : commitQueue.keySet()) { - Windmill.ComputationCommitWorkRequest.Builder computationRequestBuilder = - Windmill.ComputationCommitWorkRequest.newBuilder(); - while (remainingCommitBytes > 0) { - Windmill.WorkItemCommitRequest request = commitQueue.poll(computation); - if (request == null) { - break; - } - remainingCommitBytes -= request.getSerializedSize(); - computationRequestBuilder.addRequests(request); - } - if (computationRequestBuilder.getRequestsCount() > 0) { - computationRequestBuilder.setComputationId(computation); - commitRequestBuilder.addRequests(computationRequestBuilder); - } - } - if (commitRequestBuilder.getRequestsCount() > 0) { - Windmill.CommitWorkRequest commitRequest = commitRequestBuilder.build(); - LOG.trace("Commit: {}", commitRequest); - commitWork(commitRequest); - for (Windmill.ComputationCommitWorkRequest computationRequest : - commitRequest.getRequestsList()) { - ActiveWorkForComputation activeWork = - activeWorkMap.get(computationRequest.getComputationId()); - for (Windmill.WorkItemCommitRequest workRequest : - computationRequest.getRequestsList()) { - activeWork.completeWork(workRequest.getKey()); - } - } - } else { - break; - } - } - } - } - - private Windmill.GetWorkResponse getWork() { - return windmillServer.getWork( - Windmill.GetWorkRequest.newBuilder() - .setClientId(clientId) - .setMaxItems(MAX_GET_WORK_ITEMS) - .setMaxBytes(MAX_GET_WORK_FETCH_BYTES) - .build()); - } - - private void commitWork(Windmill.CommitWorkRequest request) { - windmillServer.commitWork(request); - } - - private void getConfig(String computation) { - Windmill.GetConfigRequest request = - Windmill.GetConfigRequest.newBuilder().addComputations(computation).build(); - - Windmill.GetConfigResponse response = windmillServer.getConfig(request); - for (Windmill.GetConfigResponse.SystemNameToComputationIdMapEntry entry : - response.getSystemNameToComputationIdMapList()) { - systemNameToComputationIdMap.put(entry.getSystemName(), entry.getComputationId()); - } - for (String serializedMapTask : response.getCloudWorksList()) { - try { - addComputation(parseMapTask(serializedMapTask)); - } catch (IOException e) { - LOG.warn("Parsing MapTask failed: {}", serializedMapTask); - LOG.warn("Error: ", e); - } - } - for (Windmill.GetConfigResponse.NameMapEntry entry : response.getNameMapList()) { - stateNameMap.put(entry.getUserName(), entry.getSystemName()); - } - } - - private void buildCounters(CounterSet counterSet, - Windmill.WorkItemCommitRequest.Builder builder) { - for (Counter counter : counterSet) { - Windmill.Counter.Builder counterBuilder = Windmill.Counter.newBuilder(); - Windmill.Counter.Kind kind; - Object aggregateObj = null; - switch (counter.getKind()) { - case SUM: kind = Windmill.Counter.Kind.SUM; break; - case MAX: kind = Windmill.Counter.Kind.MAX; break; - case MIN: kind = Windmill.Counter.Kind.MIN; break; - case MEAN: - kind = Windmill.Counter.Kind.MEAN; - CounterMean mean = counter.getAndResetMeanDelta(); - long count = mean.getCount(); - aggregateObj = mean.getAggregate(); - if (count <= 0) { - continue; - } - counterBuilder.setMeanCount(count); - break; - default: - LOG.debug("Unhandled counter type: {}", counter.getKind()); - continue; - } - if (counter.getKind() != AggregationKind.MEAN) { - aggregateObj = counter.getAndResetDelta(); - } - if (addKnownTypeToCounterBuilder(aggregateObj, counterBuilder)) { - counterBuilder.setName(counter.getName()).setKind(kind); - builder.addCounterUpdates(counterBuilder); - } - } - } - - private boolean addKnownTypeToCounterBuilder(Object aggregateObj, - Windmill.Counter.Builder counterBuilder) { - if (aggregateObj instanceof Double) { - double aggregate = (Double) aggregateObj; - if (aggregate != 0) { - counterBuilder.setDoubleScalar(aggregate); - } - } else if (aggregateObj instanceof Long) { - long aggregate = (Long) aggregateObj; - if (aggregate != 0) { - counterBuilder.setIntScalar(aggregate); - } - } else if (aggregateObj instanceof Integer) { - long aggregate = ((Integer) aggregateObj).longValue(); - if (aggregate != 0) { - counterBuilder.setIntScalar(aggregate); - } - } else { - LOG.debug("Unhandled aggregate class: {}", aggregateObj.getClass()); - return false; - } - return true; - } - - private Windmill.Exception buildExceptionReport(Throwable t) { - Windmill.Exception.Builder builder = Windmill.Exception.newBuilder(); - - builder.addStackFrames(t.toString()); - for (StackTraceElement frame : t.getStackTrace()) { - builder.addStackFrames(frame.toString()); - } - if (t.getCause() != null) { - builder.setCause(buildExceptionReport(t.getCause())); - } - - return builder.build(); - } - - // Returns true if reporting the exception is successful and the work should be retried. - private boolean reportFailure(String computation, Windmill.WorkItem work, Throwable t) { - Windmill.ReportStatsResponse response = - windmillServer.reportStats(Windmill.ReportStatsRequest.newBuilder() - .setComputationId(computation) - .setKey(work.getKey()) - .setWorkToken(work.getWorkToken()) - .addExceptions(buildExceptionReport(t)) - .build()); - return !response.getFailed(); - } - - private void reportHarnessStartup() { - Windmill.Counter.Builder counterBuilder = Windmill.Counter.newBuilder(); - counterBuilder = - counterBuilder.setName("dataflow_java_harness_restarts") - .setKind(Windmill.Counter.Kind.SUM) - .setIntScalar(1); - Windmill.ReportStatsResponse response = windmillServer.reportStats( - Windmill.ReportStatsRequest.newBuilder().addCounterUpdates(counterBuilder).build()); - if (response.getFailed()) { - LOG.warn("Failed to notify windmill on harness startup. dataflow_java_harness_restarts will " - + " not be incremented."); - } - } - - private void reportPeriodicStats() { - Runtime rt = Runtime.getRuntime(); - long usedMemory = rt.totalMemory() - rt.freeMemory(); - long maxMemory = rt.maxMemory(); - Windmill.Counter.Builder counterBuilder = Windmill.Counter.newBuilder(); - counterBuilder = - counterBuilder.setName("dataflow_java_harness_memory_utilization") - .setKind(Windmill.Counter.Kind.MEAN) - .setCumulative(true) - .setIntScalar(usedMemory) - .setMeanCount(maxMemory); - Windmill.ReportStatsResponse response = windmillServer.reportStats( - Windmill.ReportStatsRequest.newBuilder() - .addCounterUpdates(counterBuilder) - .build()); - if (response.getFailed()) { - LOG.warn("Failed to send periodic counters to windmill."); - } - } - - /** - * Class representing the state of active work for a computation. - * - *

This class is synchronized, but only used from the dispatch and commit threads, so should - * not be heavily contended. Still, blocking work should not be done by it. - */ - static class ActiveWorkForComputation { - private Map> activeWork = new HashMap<>(); - private BoundedQueueExecutor executor; - - ActiveWorkForComputation(BoundedQueueExecutor executor) { - this.executor = executor; - } - - /** - * Mark the given key and work as active. Returns whether the work is ready to be run - * immediately. - */ - public synchronized boolean activateWork(ByteString key, Work work) { - Queue queue = activeWork.get(key); - if (queue == null) { - queue = new LinkedList<>(); - activeWork.put(key, queue); - queue.add(work); - return true; - } - if (queue.peek().getWorkToken() != work.getWorkToken()) { - queue.add(work); - } - return false; - } - - /** - * Marks the work for a the given key as complete. Schedules queued work for the key if any. - */ - public synchronized void completeWork(ByteString key) { - Queue queue = activeWork.get(key); - queue.poll(); - if (queue.peek() != null) { - executor.forceExecute(queue.peek()); - } else { - activeWork.remove(key); - } - } - - public synchronized void printActiveWork(PrintWriter writer) { - writer.println("

    "); - for (Map.Entry> entry : activeWork.entrySet()) { - Queue queue = entry.getValue(); - writer.print("
  • Key: "); - writer.print(entry.getKey().toStringUtf8()); - writer.print(" Token: "); - writer.print(queue.peek().getWorkToken()); - if (queue.size() > 1) { - writer.print("("); - writer.print(queue.size() - 1); - writer.print(" queued)"); - } - writer.println("
  • "); - } - writer.println("
"); - } - } - - private static class WorkerAndContext { - public MapTaskExecutor worker; - public StreamingModeExecutionContext context; - - public WorkerAndContext(MapTaskExecutor worker, StreamingModeExecutionContext context) { - this.worker = worker; - this.context = context; - } - - public MapTaskExecutor getWorker() { - return worker; - } - - public StreamingModeExecutionContext getContext() { - return context; - } - } - - private class HarnessDataProvider implements StatusDataProvider { - @Override - public void appendSummaryHtml(PrintWriter writer) { - writer.println("Running: " + running.get() + "
"); - writer.println("ID: " + clientId + "
"); - } - } - - private class SpecsDataProvider implements StatusDataProvider { - @Override - public void appendSummaryHtml(PrintWriter writer) { - for (Map.Entry entry : instructionMap.entrySet()) { - writer.println("

" + entry.getKey() + "

"); - writer.print(""); - } - } - } - - private class MetricsDataProvider implements StatusDataProvider { - @Override - public void appendSummaryHtml(PrintWriter writer) { - writer.println("Worker Threads: " + workUnitExecutor.getPoolSize() - + "/" + workUnitExecutor.getMaximumPoolSize() + "
"); - writer.println("Active Threads: " + workUnitExecutor.getActiveCount() + "
"); - writer.println("Work Queue Size: " + workUnitExecutor.getQueue().size() - + "/" + MAX_WORK_UNITS_QUEUED + "
"); - writer.print("Commit Queues: ("); - writer.print(commitQueue.weight() >> 20); - writer.println("MB)
    "); - for (String computation : commitQueue.keySet()) { - writer.print("
  • "); - writer.print(computation); - writer.print(": "); - writer.print(commitQueue.queueSize(computation)); - writer.println("
  • "); - } - writer.println("
"); - - writer.println("Active Keys:
    "); - for (Map.Entry computationEntry - : activeWorkMap.entrySet()) { - writer.print("
  • "); - writer.print(computationEntry.getKey()); - writer.print(":"); - computationEntry.getValue().printActiveWork(writer); - writer.println("
  • "); - } - writer.println("
"); - - metricTrackingWindmillServer.printHtml(writer); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java index b4bbdcc61b..3b8dd591e2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.runners.worker.StateFetcher.SideInputState; -import com.google.cloud.dataflow.sdk.runners.worker.StreamingDataflowWorker.ReaderCacheEntry; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; @@ -59,6 +58,7 @@ */ public class StreamingModeExecutionContext extends DataflowExecutionContext { + private final String stageName; private final Map, Map> sideInputCache; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java index af7a64e478..53e9104074 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java @@ -428,8 +428,8 @@ private void consumeResponse(Windmill.GetDataRequest request, if (response.getFailed()) { // Set up all the futures for this key to throw an exception: - StreamingDataflowWorker.KeyTokenInvalidException keyTokenInvalidException = - new StreamingDataflowWorker.KeyTokenInvalidException(key.toStringUtf8()); + KeyTokenInvalidException keyTokenInvalidException = + new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index 10a432bb3c..1387224dde 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -64,8 +64,8 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; import com.google.cloud.dataflow.sdk.runners.worker.DataflowApiUtils; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderCacheEntry; import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; -import com.google.cloud.dataflow.sdk.runners.worker.StreamingDataflowWorker.ReaderCacheEntry; import com.google.cloud.dataflow.sdk.runners.worker.StreamingModeExecutionContext; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdaterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdaterTest.java deleted file mode 100644 index e98c014c41..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkProgressUpdaterTest.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.approximateProgressAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.approximateSplitRequestAtPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; -import static com.google.cloud.dataflow.sdk.util.CloudCounterUtils.extractCounter; -import static com.google.cloud.dataflow.sdk.util.CloudMetricUtils.extractCloudMetric; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudDuration; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudTime; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MIN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.api.services.dataflow.model.Position; -import com.google.api.services.dataflow.model.WorkItem; -import com.google.api.services.dataflow.model.WorkItemServiceState; -import com.google.api.services.dataflow.model.WorkItemStatus; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.CounterTestUtils; -import com.google.cloud.dataflow.sdk.util.common.Metric; -import com.google.cloud.dataflow.sdk.util.common.Metric.DoubleMetric; -import com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.Operation; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; - -import org.hamcrest.Description; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentMatcher; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.annotation.Nullable; - -/** Unit tests for {@link DataflowWorkProgressUpdater}. */ -@RunWith(JUnit4.class) -public class DataflowWorkProgressUpdaterTest { - static class TestMapTaskExecutor extends MapTaskExecutor { - ApproximateReportedProgress progress = null; - List> metrics = new ArrayList<>(); - CounterSet counters; - - public TestMapTaskExecutor(CounterSet counters) { - super(new ArrayList(), counters, - new StateSampler("test", counters.getAddCounterMutator())); - this.counters = counters; - } - - @Override - public synchronized NativeReader.Progress getWorkerProgress() { - return cloudProgressToReaderProgress(progress); - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest splitRequest) { - @Nullable - ApproximateSplitRequest split = splitRequestToApproximateSplitRequest(splitRequest); - if (split == null) { - return null; - } - return new NativeReader.DynamicSplitResultWithPosition( - cloudPositionToReaderPosition(split.getPosition())); - } - - public synchronized void setWorkerProgress(ApproximateReportedProgress progress) { - this.progress = progress; - } - - @Override - public synchronized Collection> getOutputMetrics() { - return metrics; - } - - public synchronized void setUpMetrics(int n) { - metrics = new ArrayList<>(); - for (int i = 0; i < n; i++) { - metrics.add(makeMetric(i)); - } - } - - public synchronized void setUpCounters(int n) { - counters.clear(); - for (int i = 0; i < n; i++) { - counters.add(makeCounter(i)); - } - } - } - - private static final String PROJECT_ID = "TEST_PROJECT_ID"; - private static final String JOB_ID = "TEST_JOB_ID"; - private static final String WORKER_ID = "TEST_WORKER_ID"; - private static final Long WORK_ID = 1234567890L; - private static final String COUNTER_NAME = "test-counter-"; - private static final AggregationKind[] COUNTER_KINDS = {SUM, MAX, MIN}; - private static final Long COUNTER_VALUE1 = 12345L; - private static final Double COUNTER_VALUE2 = Math.PI; - private static final Long COUNTER_VALUE3 = -389L; - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - - @Mock - private DataflowWorker.WorkUnitClient workUnitClient; - private TestMapTaskExecutor worker; - private WorkItem workItem; - private DataflowWorkerHarnessOptions options; - private DataflowWorkProgressUpdater progressUpdater; - - @Before - public void initMocksAndWorkflowServiceAndWorkerAndWork() { - MockitoAnnotations.initMocks(this); - - options = PipelineOptionsFactory.as(DataflowWorkerHarnessOptions.class); - options.setProject(PROJECT_ID); - options.setJobId(JOB_ID); - options.setWorkerId(WORKER_ID); - - worker = new TestMapTaskExecutor(new CounterSet()); - - workItem = new WorkItem(); - workItem.setProjectId(PROJECT_ID); - workItem.setJobId(JOB_ID); - workItem.setId(WORK_ID); - workItem.setLeaseExpireTime(toCloudTime(new Instant(System.currentTimeMillis() + 1000))); - workItem.setReportStatusInterval(toCloudDuration(Duration.millis(300))); - workItem.setInitialReportIndex(1L); - - progressUpdater = new DataflowWorkProgressUpdater(workItem, worker, workUnitClient, options) { - // Shorten reporting interval boundaries for faster testing. - @Override - protected long getMinReportingInterval() { - return 100; - } - - @Override - protected long getLeaseRenewalLatencyMargin() { - return 100; - } - }; - } - - // TODO: Remove sleeps from this test by using a mock sleeper. This - // requires a redesign of the WorkProgressUpdater to use a Sleeper and - // not use a ScheduledThreadExecutor that relies on real time passing. - @Test(timeout = 1000) - public void workProgressUpdaterUpdates() throws Exception { - when(workUnitClient.reportWorkItemStatus(any(WorkItemStatus.class))) - .thenReturn(generateServiceState(System.currentTimeMillis() + 2000, 1000, null, 2L)); - worker.setUpCounters(2); - worker.setUpMetrics(3); - worker.setWorkerProgress(approximateProgressAtIndex(1L)); - progressUpdater.startReportingProgress(); - // The initial update should be sent after 300. - verify(workUnitClient, timeout(400)) - .reportWorkItemStatus(argThat( - new ExpectedDataflowWorkItemStatus().withCounters(2).withMetrics(3).withProgress( - approximateProgressAtIndex(1L)))); - progressUpdater.stopReportingProgress(); - } - - // Verifies that ReportWorkItemStatusRequest contains correct progress report - // and actual dynamic split result. - @Test(timeout = 10000) - public void workProgressUpdaterAdaptsProgressInterval() throws Exception { - worker.setUpCounters(3); - worker.setUpMetrics(2); - worker.setWorkerProgress(approximateProgressAtIndex(1L)); - - // In tests below, we allow 500ms leeway. - - when(workUnitClient.reportWorkItemStatus(any(WorkItemStatus.class))) - // leaseExpirationTimestamp, progressReportInterval, suggestedStopPosition, nextReportIndex - .thenReturn(generateServiceState( - System.currentTimeMillis() + 2000, 1000, positionAtIndex(3L), 2L)); - - // Start progress updates. - progressUpdater.startReportingProgress(); - - // The initial update should be sent at nowMillis+300 (+500ms leeway). - verify(workUnitClient, timeout(800)).reportWorkItemStatus(argThat( - new ExpectedDataflowWorkItemStatus().withCounters(3).withMetrics(2).withProgress( - approximateProgressAtIndex(1L)).withReportIndex(1L))); - - worker.setUpCounters(5); - worker.setUpMetrics(6); - worker.setWorkerProgress(approximateProgressAtIndex(2L)); - when(workUnitClient.reportWorkItemStatus(any(WorkItemStatus.class))) - .thenReturn(generateServiceState(System.currentTimeMillis() + 3000, 2000, null, 3L)); - // The second update should be sent after ~1000ms (previous requested report interval). - verify(workUnitClient, timeout(1500)).reportWorkItemStatus(argThat( - new ExpectedDataflowWorkItemStatus() - .withCounters(5) - .withMetrics(6) - .withProgress(approximateProgressAtIndex(2L)) - .withDynamicSplitAtPosition(positionAtIndex(3L)) - .withReportIndex(2L))); - - // After the request is sent, reset cached dynamic split result to null. - assertNull(progressUpdater.getDynamicSplitResultToReport()); - - worker.setWorkerProgress(approximateProgressAtIndex(3L)); - - when(workUnitClient.reportWorkItemStatus(any(WorkItemStatus.class))) - .thenReturn(generateServiceState(System.currentTimeMillis() + 1000, 3000, null, 4L)); - // The third update should be sent after ~2000ms (previous requested report interval). - verify(workUnitClient, timeout(2500)).reportWorkItemStatus(argThat( - new ExpectedDataflowWorkItemStatus().withProgress(approximateProgressAtIndex(3L)) - .withReportIndex(3L))); - - worker.setWorkerProgress(approximateProgressAtIndex(4L)); - - when(workUnitClient.reportWorkItemStatus(any(WorkItemStatus.class))) - .thenReturn(generateServiceState(System.currentTimeMillis() + 4000, 3000, null, 5L)); - // The fourth update should not respect the suggested report interval (3000ms) - // because the lease expires in 1000ms. The update should be sent before the lease expires. - verify(workUnitClient, timeout(900)).reportWorkItemStatus(argThat( - new ExpectedDataflowWorkItemStatus().withProgress(approximateProgressAtIndex(4L)) - .withReportIndex(4L))); - - progressUpdater.stopReportingProgress(); - - assertEquals(5L, progressUpdater.getNextReportIndex()); - } - - // Verifies that a last update is sent when there is an unacknowledged split request. - @Test(timeout = 2000) - public void workProgressUpdaterSendsLastPendingUpdateWhenStopped() throws Exception { - // The setup process sends one update after 300ms. Enqueue another that should be scheduled - // 1000ms after that. - when(workUnitClient.reportWorkItemStatus(any(WorkItemStatus.class))) - .thenReturn(generateServiceState( - System.currentTimeMillis() + 2000, 1000, positionAtIndex(2L), 2L)); - - worker.setWorkerProgress(approximateProgressAtIndex(1L)); - progressUpdater.startReportingProgress(); - - // The initial update should be sent after 300 msec. - sleepMillis(50); - verifyZeroInteractions(workUnitClient); - - verify(workUnitClient, timeout(350)) - .reportWorkItemStatus(argThat( - new ExpectedDataflowWorkItemStatus().withProgress(approximateProgressAtIndex(1L)))); - - // The second update should be scheduled to happen after one second. - - // not immediately - verifyNoMoreInteractions(workUnitClient); - - // still not yet after 50ms - sleepMillis(50); - verifyNoMoreInteractions(workUnitClient); - - // Stop the progressUpdater now, and expect the last update immediately - progressUpdater.stopReportingProgress(); - - // Verify that the last update is sent immediately and contained the latest split result. - verify(workUnitClient) - .reportWorkItemStatus(argThat( - new ExpectedDataflowWorkItemStatus().withDynamicSplitAtPosition(positionAtIndex(2L)))); - - // And nothing happened after that. - verifyNoMoreInteractions(workUnitClient); - } - - private static Counter makeCounter(int i) { - if (i % 3 == 0) { - return Counter.longs(COUNTER_NAME + i, COUNTER_KINDS[0]) - .addValue(COUNTER_VALUE1 + i) - .addValue(COUNTER_VALUE1 + i * 2); - } else if (i % 3 == 1) { - return Counter.doubles(COUNTER_NAME + i, COUNTER_KINDS[1]) - .addValue(COUNTER_VALUE2 + i) - .addValue(COUNTER_VALUE2 + i * 3); - } else { - return Counter.longs(COUNTER_NAME + i, COUNTER_KINDS[2]) - .addValue(COUNTER_VALUE3 + i) - .addValue(COUNTER_VALUE3 + i * 5); - } - } - - private static Metric makeMetric(int i) { - return new DoubleMetric(String.valueOf(i), i); - } - - private WorkItemServiceState generateServiceState(long leaseExpirationTimestamp, - int progressReportIntervalMs, Position suggestedStopPosition, - long nextReportIndex) { - WorkItemServiceState responseState = new WorkItemServiceState(); - responseState.setFactory(Transport.getJsonFactory()); - responseState.setLeaseExpireTime(toCloudTime(new Instant(leaseExpirationTimestamp))); - responseState.setReportStatusInterval( - toCloudDuration(Duration.millis(progressReportIntervalMs))); - responseState.setNextReportIndex(nextReportIndex); - - if (suggestedStopPosition != null) { - responseState.setSplitRequest(approximateSplitRequestAtPosition(suggestedStopPosition)); - } - - return responseState; - } - - private static final class ExpectedDataflowWorkItemStatus - extends ArgumentMatcher { - @Nullable - Integer counterCount; - - @Nullable - Integer metricCount; - - @Nullable - ApproximateReportedProgress expectedProgress; - - @Nullable - Position expectedSplitPosition; - - @Nullable - Long expectedReportIndex; - - public ExpectedDataflowWorkItemStatus withCounters(Integer counterCount) { - this.counterCount = counterCount; - return this; - } - - public ExpectedDataflowWorkItemStatus withMetrics(Integer metricCount) { - this.metricCount = metricCount; - return this; - } - - public ExpectedDataflowWorkItemStatus withProgress( - ApproximateReportedProgress expectedProgress) { - this.expectedProgress = expectedProgress; - return this; - } - - public ExpectedDataflowWorkItemStatus withDynamicSplitAtPosition( - Position expectedSplitPosition) { - this.expectedSplitPosition = expectedSplitPosition; - return this; - } - - public ExpectedDataflowWorkItemStatus withReportIndex(Long reportIndex) { - this.expectedReportIndex = reportIndex; - return this; - } - - @Override - public void describeTo(Description description) { - List values = new ArrayList<>(); - if (this.counterCount != null) { - for (int i = 0; i < counterCount; i++) { - values.add(extractCounter(makeCounter(i), false).toString()); - } - } - if (this.metricCount != null) { - for (int i = 0; i < metricCount; i++) { - values.add(extractCloudMetric(makeMetric(i), WORKER_ID).toString()); - } - } - if (this.expectedProgress != null) { - values.add("progress " + this.expectedProgress); - } - if (this.expectedSplitPosition != null) { - values.add("split position " + this.expectedSplitPosition); - } else { - values.add("no split position present"); - } - if (this.expectedReportIndex != null) { - values.add("reportIndex " + this.expectedReportIndex); - } - description.appendValueList("Dataflow WorkItemStatus with ", ", ", ".", values); - } - - @Override - public boolean matches(Object status) { - WorkItemStatus st = (WorkItemStatus) status; - return matchCountersAndMetrics(st) && matchProgress(st) && matchStopPosition(st) - && matchReportIndex(st); - } - - private boolean matchCountersAndMetrics(WorkItemStatus status) { - if (counterCount == null && metricCount == null) { - return true; - } - - List sentUpdates = status.getMetricUpdates(); - - if (counterCount + metricCount != sentUpdates.size()) { - return false; - } - - for (int i = 0; i < counterCount; i++) { - if (!sentUpdates.contains(CounterTestUtils.extractCounterUpdate(makeCounter(i), false))) { - return false; - } - } - - for (int i = 0; i < metricCount; i++) { - if (!sentUpdates.contains(extractCloudMetric(makeMetric(i), WORKER_ID))) { - return false; - } - } - - return true; - } - - private boolean matchProgress(WorkItemStatus status) { - if (expectedProgress == null) { - return true; - } - ApproximateReportedProgress progress = status.getReportedProgress(); - return expectedProgress.equals(progress); - } - - private boolean matchStopPosition(WorkItemStatus status) { - Position actualStopPosition = status.getStopPosition(); - if (expectedSplitPosition == null) { - return actualStopPosition == null; - } - return expectedSplitPosition.equals(actualStopPosition); - } - - private boolean matchReportIndex(WorkItemStatus status) { - if (expectedReportIndex == null) { - return true; - } - return expectedReportIndex.equals(status.getReportIndex()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarnessTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarnessTest.java deleted file mode 100644 index 66710fd229..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerHarnessTest.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doCallRealMethod; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.client.http.LowLevelHttpResponse; -import com.google.api.client.json.Json; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.testing.http.MockLowLevelHttpResponse; -import com.google.api.client.util.Sleeper; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.LeaseWorkItemRequest; -import com.google.api.services.dataflow.model.LeaseWorkItemResponse; -import com.google.api.services.dataflow.model.MapTask; -import com.google.api.services.dataflow.model.SeqMapTask; -import com.google.api.services.dataflow.model.WorkItem; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; -import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; -import com.google.cloud.dataflow.sdk.testing.RestoreDataflowLoggingMDC; -import com.google.cloud.dataflow.sdk.testing.RestoreSystemProperties; -import com.google.cloud.dataflow.sdk.util.IntervalBoundedExponentialBackOff; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; - -/** Unit tests for {@link DataflowWorkerHarness}. */ -@RunWith(JUnit4.class) -public class DataflowWorkerHarnessTest { - - @Rule public TestRule restoreSystemProperties = new RestoreSystemProperties(); - @Rule public TestRule restoreLogging = new RestoreDataflowLoggingMDC(); - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Rule public FastNanoClockAndSleeper fastNanoClockAndSleeper = new FastNanoClockAndSleeper(); - @Mock private MockHttpTransport transport; - @Mock private MockLowLevelHttpRequest request; - @Mock private DataflowWorker mockDataflowWorker; - private DataflowWorkerHarnessOptions pipelineOptions; - - private Dataflow service; - - private static final String PROJECT_ID = "TEST_PROJECT_ID"; - private static final String JOB_ID = "TEST_JOB_ID"; - private static final String WORKER_ID = "TEST_WORKER_ID"; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - when(transport.buildRequest(anyString(), anyString())).thenReturn(request); - doCallRealMethod().when(request).getContentAsString(); - - service = new Dataflow(transport, Transport.getJsonFactory(), null); - pipelineOptions = PipelineOptionsFactory.as(DataflowWorkerHarnessOptions.class); - pipelineOptions.setProject(PROJECT_ID); - pipelineOptions.setJobId(JOB_ID); - pipelineOptions.setWorkerId(WORKER_ID); - pipelineOptions.setGcpCredential(new TestCredential()); - } - - public void runTestThatWeRetryIfTaskExecutionFailsAgainAndAgain() throws Exception { - final int numWorkers = Math.max(Runtime.getRuntime().availableProcessors(), 1); - final AtomicInteger sleepCount = new AtomicInteger(0); - final AtomicInteger illegalIntervalCount = new AtomicInteger(0); - DataflowWorkerHarness.processWork( - pipelineOptions, - mockDataflowWorker, - new Sleeper() { - @Override - public void sleep(long millis) throws InterruptedException { - if ((millis - > DataflowWorkerHarness.BACKOFF_MAX_INTERVAL_MILLIS - * (1 + IntervalBoundedExponentialBackOff.DEFAULT_RANDOMIZATION_FACTOR))) { - // We count the times the sleep interval is greater than the backoff max interval with - // randomization to make sure it does not happen. - illegalIntervalCount.incrementAndGet(); - } - if (sleepCount.incrementAndGet() > 1000) { - throw new InterruptedException("Stopping the retry loop."); - } - } - }); - // Test that the backoff mechanism will allow at least 1000 failures. - verify(mockDataflowWorker, times(numWorkers + 1000)).getAndPerformWork(); - verifyNoMoreInteractions(mockDataflowWorker); - assertEquals(0, illegalIntervalCount.get()); - } - - @Test - public void testThatWeRetryIfTaskExecutionFailAgainAndAgain() throws Exception { - when(mockDataflowWorker.getAndPerformWork()).thenReturn(false); - runTestThatWeRetryIfTaskExecutionFailsAgainAndAgain(); - } - - @Test - public void testThatWeRetryIfTaskExecutionFailAgainAndAgainByIOException() throws Exception { - when(mockDataflowWorker.getAndPerformWork()).thenThrow(new IOException()); - runTestThatWeRetryIfTaskExecutionFailsAgainAndAgain(); - } - - @Test - public void testThatWeRetryIfTaskExecutionFailAgainAndAgainByUnknownException() throws Exception { - when(mockDataflowWorker.getAndPerformWork()).thenThrow(new RuntimeException()); - runTestThatWeRetryIfTaskExecutionFailsAgainAndAgain(); - } - - @Test - public void testNumberOfWorkerHarnessThreadsIsHonored() throws Exception { - final int expectedNumberOfThreads = 5; - pipelineOptions.setNumberOfWorkerHarnessThreads(expectedNumberOfThreads); - - when(mockDataflowWorker.getAndPerformWork()).thenReturn(false); - DataflowWorkerHarness.processWork( - pipelineOptions, - mockDataflowWorker, - new Sleeper() { - @Override - public void sleep(long millis) throws InterruptedException { - throw new InterruptedException("Stopping the retry loop."); - } - }); - // Verify that the number of requested worker harness threads is honored. - verify(mockDataflowWorker, times(expectedNumberOfThreads)).getAndPerformWork(); - verifyNoMoreInteractions(mockDataflowWorker); - } - - @Test - public void testCreationOfWorkerHarness() throws Exception { - assertNotNull(DataflowWorkerHarness.create(pipelineOptions)); - assertEquals(JOB_ID, DataflowWorkerLoggingMDC.getJobId()); - assertEquals(WORKER_ID, DataflowWorkerLoggingMDC.getWorkerId()); - } - - @Test - public void testCloudServiceCall() throws Exception { - WorkItem workItem = createWorkItem(PROJECT_ID, JOB_ID); - - when(request.execute()).thenReturn(generateMockResponse(workItem)); - - DataflowWorker.WorkUnitClient client = - new DataflowWorkerHarness.DataflowWorkUnitClient(service, pipelineOptions); - - assertEquals(workItem, client.getWorkItem()); - - LeaseWorkItemRequest actualRequest = Transport.getJsonFactory().fromString( - request.getContentAsString(), LeaseWorkItemRequest.class); - assertEquals(WORKER_ID, actualRequest.getWorkerId()); - assertEquals(ImmutableList.of(WORKER_ID, "remote_source", "custom_source"), - actualRequest.getWorkerCapabilities()); - assertEquals(ImmutableList.of("map_task", "seq_map_task", "remote_source_task"), - actualRequest.getWorkItemTypes()); - assertEquals("1234", DataflowWorkerLoggingMDC.getWorkId()); - } - - @Test - public void testCloudServiceCallMapTaskStagePropagation() throws Exception { - DataflowWorker.WorkUnitClient client = - new DataflowWorkerHarness.DataflowWorkUnitClient(service, pipelineOptions); - - // Publish and acquire a map task work item, and verify we're now processing that stage. - final String stageName = "test_stage_name"; - MapTask mapTask = new MapTask(); - mapTask.setStageName(stageName); - WorkItem workItem = createWorkItem(PROJECT_ID, JOB_ID); - workItem.setMapTask(mapTask); - when(request.execute()).thenReturn(generateMockResponse(workItem)); - assertEquals(workItem, client.getWorkItem()); - assertEquals(stageName, DataflowWorkerLoggingMDC.getStageName()); - } - - @Test - public void testCloudServiceCallSeqMapTaskStagePropagation() throws Exception { - DataflowWorker.WorkUnitClient client = - new DataflowWorkerHarness.DataflowWorkUnitClient(service, pipelineOptions); - - // Publish and acquire a seq map task work item, and verify we're now processing that stage. - final String stageName = "test_stage_name"; - SeqMapTask seqMapTask = new SeqMapTask(); - seqMapTask.setStageName(stageName); - WorkItem workItem = createWorkItem(PROJECT_ID, JOB_ID); - workItem.setSeqMapTask(seqMapTask); - when(request.execute()).thenReturn(generateMockResponse(workItem)); - assertEquals(workItem, client.getWorkItem()); - assertEquals(stageName, DataflowWorkerLoggingMDC.getStageName()); - } - - @Test - public void testCloudServiceCallNoWorkId() throws Exception { - // If there's no work the service should return an empty work item. - WorkItem workItem = new WorkItem(); - - when(request.execute()).thenReturn(generateMockResponse(workItem)); - - DataflowWorker.WorkUnitClient client = - new DataflowWorkerHarness.DataflowWorkUnitClient(service, pipelineOptions); - - assertNull(client.getWorkItem()); - - LeaseWorkItemRequest actualRequest = Transport.getJsonFactory().fromString( - request.getContentAsString(), LeaseWorkItemRequest.class); - assertEquals(WORKER_ID, actualRequest.getWorkerId()); - assertEquals(ImmutableList.of(WORKER_ID, "remote_source", "custom_source"), - actualRequest.getWorkerCapabilities()); - assertEquals(ImmutableList.of("map_task", "seq_map_task", "remote_source_task"), - actualRequest.getWorkItemTypes()); - } - - @Test - public void testCloudServiceCallNoWorkItem() throws Exception { - when(request.execute()).thenReturn(generateMockResponse()); - - DataflowWorker.WorkUnitClient client = - new DataflowWorkerHarness.DataflowWorkUnitClient(service, pipelineOptions); - - assertNull(client.getWorkItem()); - - LeaseWorkItemRequest actualRequest = Transport.getJsonFactory().fromString( - request.getContentAsString(), LeaseWorkItemRequest.class); - assertEquals(WORKER_ID, actualRequest.getWorkerId()); - assertEquals(ImmutableList.of(WORKER_ID, "remote_source", "custom_source"), - actualRequest.getWorkerCapabilities()); - assertEquals(ImmutableList.of("map_task", "seq_map_task", "remote_source_task"), - actualRequest.getWorkItemTypes()); - } - - @Test - public void testCloudServiceCallMultipleWorkItems() throws Exception { - expectedException.expect(IOException.class); - expectedException.expectMessage( - "This version of the SDK expects no more than one work item from the service"); - - WorkItem workItem1 = createWorkItem(PROJECT_ID, JOB_ID); - WorkItem workItem2 = createWorkItem(PROJECT_ID, JOB_ID); - - when(request.execute()).thenReturn(generateMockResponse(workItem1, workItem2)); - - DataflowWorker.WorkUnitClient client = - new DataflowWorkerHarness.DataflowWorkUnitClient(service, pipelineOptions); - - client.getWorkItem(); - } - - private LowLevelHttpResponse generateMockResponse(WorkItem ... workItems) throws Exception { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setContentType(Json.MEDIA_TYPE); - LeaseWorkItemResponse lease = new LeaseWorkItemResponse(); - lease.setWorkItems(Lists.newArrayList(workItems)); - // N.B. Setting the factory is necessary in order to get valid JSON. - lease.setFactory(Transport.getJsonFactory()); - response.setContent(lease.toPrettyString()); - return response; - } - - private WorkItem createWorkItem(String projectId, String jobId) { - WorkItem workItem = new WorkItem(); - workItem.setFactory(Transport.getJsonFactory()); - workItem.setProjectId(projectId); - workItem.setJobId(jobId); - - // We need to set a work id because otherwise the client will treat the response as - // indicating no work is available. - workItem.setId(1234L); - return workItem; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java deleted file mode 100644 index 6b11af91b6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowWorkerTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.api.services.dataflow.model.SourceSplitResponse; -import com.google.api.services.dataflow.model.SourceSplitShard; -import com.google.api.services.dataflow.model.WorkItem; -import com.google.api.services.dataflow.model.WorkItemStatus; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.common.worker.WorkExecutor; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.CoreMatchers; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.util.Map; - -/** Unit tests for {@link DataflowWorker}. */ -@RunWith(JUnit4.class) -public class DataflowWorkerTest { - - private class WorkerException extends Exception { } - - @Rule - public FastNanoClockAndSleeper clockAndSleeper = new FastNanoClockAndSleeper(); - - @Mock - DataflowWorker.WorkUnitClient mockWorkUnitClient; - - @Mock - DataflowWorkerHarnessOptions options; - - @Mock - DataflowWorkProgressUpdater mockProgressUpdater; - - @Mock - WorkExecutor mockWorkExecutor; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testWhenNoWorkThatWeReturnFalse() throws Exception { - DataflowWorker worker = new DataflowWorker(mockWorkUnitClient, options); - when(mockWorkUnitClient.getWorkItem()).thenReturn(null); - - assertFalse(worker.getAndPerformWork()); - } - - @Test - public void testWhenProcessingWorkUnitFailsWeReportStatus() throws Exception { - DataflowWorker worker = new DataflowWorker(mockWorkUnitClient, options); - // In practice this value is always 1, but for the sake of testing send a different value. - long initialReportIndex = 4L; - WorkItem workItem = new WorkItem() - .setId(1L).setJobId("Expected to fail the job").setInitialReportIndex(initialReportIndex); - when(mockWorkUnitClient.getWorkItem()).thenReturn(workItem).thenReturn(null); - - assertFalse(worker.getAndPerformWork()); - verify(mockWorkUnitClient) - .reportWorkItemStatus(argThat(cloudWorkHasErrors(initialReportIndex))); - } - - @Test - public void testStartAndStopProgressReport() throws Exception { - DataflowWorker worker = new DataflowWorker(mockWorkUnitClient, options); - worker.executeWork(mockWorkExecutor, mockProgressUpdater); - verify(mockProgressUpdater, times(1)).startReportingProgress(); - verify(mockProgressUpdater, times(1)).stopReportingProgress(); - } - - @Test - public void testStopProgressReportInCaseOfFailure() throws Exception { - doThrow(new WorkerException()).when(mockWorkExecutor).execute(); - DataflowWorker worker = new DataflowWorker(mockWorkUnitClient, options); - try { - worker.executeWork(mockWorkExecutor, mockProgressUpdater); - } catch (WorkerException e) { /* Expected - ignore. */ } - verify(mockProgressUpdater, times(1)).stopReportingProgress(); - } - - @Test - public void testIsSplitResponseTooLarge() throws IOException { - SourceSplitResponse splitResponse = new SourceSplitResponse(); - splitResponse.setShards( - ImmutableList.of(new SourceSplitShard(), new SourceSplitShard())); - assertThat(DataflowApiUtils.computeSerializedSizeBytes(splitResponse), greaterThan(0L)); - } - - @Test - public void testWorkItemStatusWithStateSamplerInfo() throws Exception { - WorkItem workItem = new WorkItem() - .setId(1L).setJobId("jobid").setInitialReportIndex(4L); - WorkItemStatus status = DataflowWorker.buildStatus(workItem, false, - null, null, options, null, null, null, null, 0, - new StateSampler.StateSamplerInfo("state", 101L, null)); - assertEquals(1, status.getMetricUpdates().size()); - assertEquals("internal", status.getMetricUpdates().get(0).getKind()); - assertEquals("state-sampler", status.getMetricUpdates().get(0).getName().getName()); - @SuppressWarnings("unchecked") - Map metric = - (Map) status.getMetricUpdates().get(0).getInternal(); - assertEquals("state", metric.get("last-state-name")); - assertEquals(101L, metric.get("num-transitions")); - } - - private Matcher cloudWorkHasErrors(final long expectedReportIndex) { - return new TypeSafeMatcher() { - @Override - public void describeTo(Description description) { - description.appendText("WorkItemStatus expected to have errors"); - } - - @Override - protected boolean matchesSafely(WorkItemStatus status) { - assertEquals(expectedReportIndex, (long) status.getReportIndex()); - boolean returnValue = status.getCompleted() && !status.getErrors().isEmpty(); - if (returnValue) { - assertThat(status.getErrors().get(0).getMessage(), - CoreMatchers.containsString("java.lang.RuntimeException: Unknown kind of work")); - } - return returnValue; - } - }; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java new file mode 100644 index 0000000000..8507fb90d9 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link KeyTokenInvalidException}. */ +@RunWith(JUnit4.class) +public final class KeyTokenInvalidExceptionTest { + @Test + public void testIsKeyTokenInvalidException() throws Exception { + KeyTokenInvalidException exception = new KeyTokenInvalidException("test"); + RuntimeException keyTokenCauseException = new RuntimeException("key token cause", exception); + assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(exception)); + assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(keyTokenCauseException)); + assertFalse(KeyTokenInvalidException.isKeyTokenInvalidException( + new RuntimeException("non key token"))); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java deleted file mode 100644 index d7e6fe706a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorkerTest.java +++ /dev/null @@ -1,1182 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.addObject; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.api.services.dataflow.model.InstructionInput; -import com.google.api.services.dataflow.model.InstructionOutput; -import com.google.api.services.dataflow.model.MapTask; -import com.google.api.services.dataflow.model.ParDoInstruction; -import com.google.api.services.dataflow.model.ParallelInstruction; -import com.google.api.services.dataflow.model.ReadInstruction; -import com.google.api.services.dataflow.model.Sink; -import com.google.api.services.dataflow.model.Source; -import com.google.api.services.dataflow.model.WriteInstruction; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CollectionCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; -import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; -import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItems.FakeKeyedWorkItemCoder; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItemCommitRequest; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.BoundedQueueExecutor; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.Lists; -import com.google.common.primitives.UnsignedLong; -import com.google.protobuf.ByteString; -import com.google.protobuf.ByteString.Output; -import com.google.protobuf.TextFormat; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.junit.runners.model.Statement; -import org.mockito.Mockito; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -/** Unit tests for {@link StreamingDataflowWorker}. */ -@RunWith(JUnit4.class) -public class StreamingDataflowWorkerTest { - private static final IntervalWindow DEFAULT_WINDOW = - new IntervalWindow(new Instant(1234), new Duration(1000)); - - private static final IntervalWindow WINDOW_AT_ZERO = - new IntervalWindow(new Instant(0), new Instant(1000)); - - private static final IntervalWindow WINDOW_AT_ONE_SECOND = - new IntervalWindow(new Instant(1000), new Instant(2000)); - - private static final Coder DEFAULT_WINDOW_CODER = IntervalWindow.getCoder(); - private static final Coder> DEFAULT_WINDOW_COLLECTION_CODER = - CollectionCoder.of(DEFAULT_WINDOW_CODER); - - private static final byte[] defaultWindowsBytes() throws Exception { - return CoderUtils.encodeToByteArray( - DEFAULT_WINDOW_COLLECTION_CODER, Arrays.asList(DEFAULT_WINDOW)); - } - - private static final byte[] windowAtZeroBytes() throws Exception { - return CoderUtils.encodeToByteArray( - DEFAULT_WINDOW_COLLECTION_CODER, Arrays.asList(WINDOW_AT_ZERO)); - } - - private static final byte[] windowAtOneSecondBytes() throws Exception { - return CoderUtils.encodeToByteArray( - DEFAULT_WINDOW_COLLECTION_CODER, Arrays.asList(WINDOW_AT_ONE_SECOND)); - } - - // Default values that are unimportant for correctness, but must be consistent - // between pieces of this test suite - private static final String DEFAULT_COMPUTATION_ID = "computation"; - private static final String DEFAULT_MAP_STAGE_NAME = "computation"; - private static final String DEFAULT_MAP_SYSTEM_NAME = "computation"; - private static final String DEFAULT_PARDO_SYSTEM_NAME = "parDo"; - private static final String DEFAULT_PARDO_USER_NAME = "parDoUserName"; - private static final String DEFAULT_SOURCE_SYSTEM_NAME = "source"; - private static final String DEFAULT_SINK_SYSTEM_NAME = "sink"; - private static final String DEFAULT_SOURCE_COMPUTATION_ID = "upstream"; - private static final String DEFAULT_KEY_STRING = "key"; - private static final String DEFAULT_DATA_STRING = "data"; - private static final String DEFAULT_DESTINATION_STREAM_ID = "out"; - - @Rule public BlockingFn blockingFn = new BlockingFn(); - - private String keyStringForIndex(int index) { - return DEFAULT_KEY_STRING + index; - } - - private String dataStringForIndex(long index) { - return DEFAULT_DATA_STRING + index; - } - - private ParallelInstruction makeWindowingSourceInstruction(Coder coder) { - CloudObject encodedCoder = - FullWindowedValueCoder.of(FakeKeyedWorkItemCoder.of(coder), IntervalWindow.getCoder()) - .asCloudObject(); - return new ParallelInstruction() - .setSystemName(DEFAULT_SOURCE_SYSTEM_NAME) - .setRead( - new ReadInstruction() - .setSource( - new Source() - .setSpec(CloudObject.forClass(WindowingWindmillReader.class)) - .setCodec(encodedCoder))) - .setOutputs( - Arrays.asList(new InstructionOutput().setName("read_output").setCodec(encodedCoder))); - } - - private ParallelInstruction makeSourceInstruction(Coder coder) { - return new ParallelInstruction() - .setSystemName(DEFAULT_SOURCE_SYSTEM_NAME) - .setRead(new ReadInstruction().setSource( - new Source() - .setSpec(CloudObject.forClass(UngroupedWindmillReader.class)) - .setCodec(WindowedValue.getFullCoder(coder, IntervalWindow.getCoder()) - .asCloudObject()))) - .setOutputs(Arrays.asList( - new InstructionOutput() - .setName("read_output") - .setCodec(WindowedValue.getFullCoder(coder, IntervalWindow.getCoder()) - .asCloudObject()))); - } - - private ParallelInstruction makeDoFnInstruction( - DoFn doFn, - int producerIndex, - Coder outputCoder, - Coder windowCoder) { - CloudObject spec = CloudObject.forClassName("DoFn"); - addString(spec, PropertyNames.SERIALIZED_FN, - StringUtils.byteArrayToJsonString( - SerializableUtils.serializeToByteArray(new DoFnInfo<>(doFn, null)))); - return new ParallelInstruction() - .setSystemName(DEFAULT_PARDO_SYSTEM_NAME) - .setName(DEFAULT_PARDO_USER_NAME) - .setParDo(new ParDoInstruction() - .setInput( - new InstructionInput().setProducerInstructionIndex(producerIndex).setOutputNum(0)) - .setNumOutputs(1) - .setUserFn(spec)) - .setOutputs(Arrays.asList( - new InstructionOutput() - .setName("par_do_output") - .setCodec(WindowedValue.getFullCoder(outputCoder, windowCoder) - .asCloudObject()))); - } - - private ParallelInstruction makeDoFnInstruction( - DoFn doFn, int producerIndex, Coder outputCoder) { - return makeDoFnInstruction(doFn, producerIndex, outputCoder, IntervalWindow.getCoder()); - } - - private ParallelInstruction makeSinkInstruction( - Coder coder, int producerIndex, Coder windowCoder) { - CloudObject spec = CloudObject.forClass(WindmillSink.class); - addString(spec, "stream_id", DEFAULT_DESTINATION_STREAM_ID); - return new ParallelInstruction() - .setSystemName(DEFAULT_SINK_SYSTEM_NAME) - .setWrite(new WriteInstruction() - .setInput( - new InstructionInput().setProducerInstructionIndex(producerIndex).setOutputNum(0)) - .setSink(new Sink() - .setSpec(spec) - .setCodec(WindowedValue.getFullCoder(coder, windowCoder) - .asCloudObject()))); - } - - private ParallelInstruction makeSinkInstruction(Coder coder, int producerIndex) { - return makeSinkInstruction(coder, producerIndex, IntervalWindow.getCoder()); - } - - /** - * Returns a {@link MapTask} with the provided {@code instructions} and default values - * everywhere else. - */ - private MapTask defaultMapTask(List instructions) { - return new MapTask() - .setStageName(DEFAULT_MAP_STAGE_NAME) - .setSystemName(DEFAULT_MAP_SYSTEM_NAME) - .setInstructions(instructions); - } - - private Windmill.GetWorkResponse buildInput(String input, byte[] metadata) throws Exception { - Windmill.GetWorkResponse.Builder builder = Windmill.GetWorkResponse.newBuilder(); - TextFormat.merge(input, builder); - if (metadata != null) { - Windmill.InputMessageBundle.Builder messageBundleBuilder = - builder.getWorkBuilder(0).getWorkBuilder(0).getMessageBundlesBuilder(0); - for (Windmill.Message.Builder messageBuilder : - messageBundleBuilder.getMessagesBuilderList()) { - messageBuilder.setMetadata(addPaneTag(PaneInfo.NO_FIRING, metadata)); - } - } - return builder.build(); - } - - private Windmill.GetWorkResponse makeInput(int index, long timestamp) throws Exception { - return makeInput(index, timestamp, keyStringForIndex(index)); - } - - private Windmill.GetWorkResponse makeInput(int index, long timestamp, String key) - throws Exception { - return buildInput( - "work {" + - " computation_id: \"" + DEFAULT_COMPUTATION_ID + "\"" + - " work {" + - " key: \"" + key + "\"" + - " work_token: " + index + - " message_bundles {" + - " source_computation_id: \"" + DEFAULT_SOURCE_COMPUTATION_ID + "\"" + - " messages {" + - " timestamp: " + timestamp + - " data: \"data" + index + "\"" + - " }" + - " }" + - " }" + - "}", - CoderUtils.encodeToByteArray( - CollectionCoder.of(IntervalWindow.getCoder()), Arrays.asList(DEFAULT_WINDOW))); - } - - /** - * Returns a - * {@link com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItemCommitRequest} - * builder parsed from the provided text format proto. - */ - private WorkItemCommitRequest.Builder parseCommitRequest(String output) throws Exception { - WorkItemCommitRequest.Builder builder = Windmill.WorkItemCommitRequest.newBuilder(); - TextFormat.merge(output, builder); - return builder; - } - - /** - * Sets the metadata of the first contained message in this WorkItemCommitRequest - * (it should only have one message). - */ - private WorkItemCommitRequest.Builder setMessagesMetadata( - PaneInfo pane, byte[] windowBytes, WorkItemCommitRequest.Builder builder) throws Exception { - if (windowBytes != null) { - builder.getOutputMessagesBuilder(0) - .getBundlesBuilder(0) - .getMessagesBuilder(0) - .setMetadata(addPaneTag(pane, windowBytes)); - } - return builder; - } - - private WorkItemCommitRequest.Builder makeExpectedOutput(int index, long timestamp) - throws Exception { - return makeExpectedOutput(index, timestamp, keyStringForIndex(index), keyStringForIndex(index)); - } - - private WorkItemCommitRequest.Builder makeExpectedOutput( - int index, long timestamp, String key, String outKey) throws Exception { - return setMessagesMetadata(PaneInfo.NO_FIRING, defaultWindowsBytes(), - parseCommitRequest( - "key: \"" + key + "\" " + - "work_token: " + index + " " + - "output_messages {" + - " destination_stream_id: \"" + DEFAULT_DESTINATION_STREAM_ID + "\"" + - " bundles {" + - " key: \"" + outKey + "\"" + - " messages {" + - " timestamp: " + timestamp + - " data: \"" + dataStringForIndex(index) + "\"" + - " metadata: \"\"" + - " }" + - " messages_ids: \"\"" + - " }" + - "}")); - } - - private ByteString addPaneTag(PaneInfo pane, byte[] windowBytes) - throws CoderException, IOException { - Output output = ByteString.newOutput(); - PaneInfo.PaneInfoCoder.INSTANCE.encode(pane, output, Context.OUTER); - output.write(windowBytes); - return output.toByteString(); - } - - private DataflowWorkerHarnessOptions createTestingPipelineOptions() { - DataflowWorkerHarnessOptions options = - PipelineOptionsFactory.as(DataflowWorkerHarnessOptions.class); - options.setAppName("StreamingWorkerHarnessTest"); - options.setStreaming(true); - return options; - } - - private Windmill.WorkItemCommitRequest stripCounters(Windmill.WorkItemCommitRequest request) { - return Windmill.WorkItemCommitRequest.newBuilder(request).clearCounterUpdates().build(); - } - - @Test - public void testBasicHarness() throws Exception { - List instructions = Arrays.asList( - makeSourceInstruction(StringUtf8Coder.of()), - makeSinkInstruction(StringUtf8Coder.of(), 0)); - - FakeWindmillServer server = new FakeWindmillServer(); - DataflowWorkerHarnessOptions options = createTestingPipelineOptions(); - StreamingDataflowWorker worker = - new StreamingDataflowWorker(Arrays.asList(defaultMapTask(instructions)), server, options); - worker.start(); - - // Thread locals for the job and worker should have been updated for logging. - assertEquals(options.getJobId(), DataflowWorkerLoggingMDC.getJobId()); - assertEquals(options.getWorkerId(), DataflowWorkerLoggingMDC.getWorkerId()); - - final int numIters = 2000; - for (int i = 0; i < numIters; ++i) { - server.addWorkToOffer(makeInput(i, TimeUnit.MILLISECONDS.toMicros(i))); - } - - Map result = server.waitForAndGetCommits(numIters); - worker.stop(); - - for (int i = 0; i < numIters; ++i) { - assertTrue(result.containsKey((long) i)); - assertEquals(makeExpectedOutput(i, TimeUnit.MILLISECONDS.toMicros(i)).build(), - stripCounters(result.get((long) i))); - } - } - - static class BlockingFn extends DoFn implements TestRule { - public static CountDownLatch blocker = new CountDownLatch(1); - public static Semaphore counter = new Semaphore(0); - public static AtomicInteger callCounter = new AtomicInteger(0); - - @Override - public void processElement(ProcessContext c) throws InterruptedException { - callCounter.incrementAndGet(); - counter.release(); - blocker.await(); - c.output(c.element()); - } - - @Override - public Statement apply(final Statement base, final Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - blocker = new CountDownLatch(1); - counter = new Semaphore(0); - callCounter = new AtomicInteger(); - base.evaluate(); - } - }; - } - } - - @Test - public void testIgnoreRetriedKeys() throws Exception { - final int numIters = 4; - List instructions = Arrays.asList( - makeSourceInstruction(StringUtf8Coder.of()), - makeDoFnInstruction(blockingFn, 0, StringUtf8Coder.of()), - makeSinkInstruction(StringUtf8Coder.of(), 0)); - - FakeWindmillServer server = new FakeWindmillServer(); - DataflowWorkerHarnessOptions options = createTestingPipelineOptions(); - StreamingDataflowWorker worker = - new StreamingDataflowWorker(Arrays.asList(defaultMapTask(instructions)), server, options); - worker.start(); - - // Thread locals for the job and worker should have been updated for logging. - assertEquals(options.getJobId(), DataflowWorkerLoggingMDC.getJobId()); - assertEquals(options.getWorkerId(), DataflowWorkerLoggingMDC.getWorkerId()); - - for (int i = 0; i < numIters; ++i) { - server.addWorkToOffer(makeInput(i, TimeUnit.MILLISECONDS.toMicros(i))); - } - - // Wait for keys to schedule. They will be blocked. - BlockingFn.counter.acquire(numIters); - - // Re-add the work, it should be ignored due to the keys being active. - for (int i = 0; i < numIters; ++i) { - // Same work token. - server.addWorkToOffer(makeInput(i, TimeUnit.MILLISECONDS.toMicros(i))); - } - - // Give all added calls a chance to run. - server.waitForEmptyWorkQueue(); - - for (int i = 0; i < numIters; ++i) { - // Different work token same keys. - server.addWorkToOffer( - makeInput(i + numIters, TimeUnit.MILLISECONDS.toMicros(i), keyStringForIndex(i))); - } - - // Give all added calls a chance to run. - server.waitForEmptyWorkQueue(); - - // Release the blocked calls. - BlockingFn.blocker.countDown(); - - // Verify the output - Map result = server.waitForAndGetCommits(numIters * 2); - for (int i = 0; i < numIters; ++i) { - assertTrue(result.containsKey((long) i)); - assertEquals(makeExpectedOutput(i, TimeUnit.MILLISECONDS.toMicros(i)).build(), - stripCounters(result.get((long) i))); - assertTrue(result.containsKey((long) i + numIters)); - assertEquals(makeExpectedOutput(i + numIters, TimeUnit.MILLISECONDS.toMicros(i), - keyStringForIndex(i), keyStringForIndex(i)).build(), - stripCounters(result.get((long) i + numIters))); - } - - // Re-add the work, it should process due to the keys no longer being active. - for (int i = 0; i < numIters; ++i) { - server.addWorkToOffer(makeInput(i + numIters * 2, TimeUnit.MILLISECONDS.toMicros(i), - keyStringForIndex(i))); - } - result = server.waitForAndGetCommits(numIters); - worker.stop(); - for (int i = 0; i < numIters; ++i) { - assertTrue(result.containsKey((long) i + numIters * 2)); - assertEquals(makeExpectedOutput(i + numIters * 2, TimeUnit.MILLISECONDS.toMicros(i), - keyStringForIndex(i), keyStringForIndex(i)).build(), - stripCounters(result.get((long) i + numIters * 2))); - } - } - - @Test(timeout = 10000) - public void testNumberOfWorkerHarnessThreadsIsHonored() throws Exception { - int expectedNumberOfThreads = 5; - List instructions = Arrays.asList( - makeSourceInstruction(StringUtf8Coder.of()), - makeDoFnInstruction(blockingFn, 0, StringUtf8Coder.of()), - makeSinkInstruction(StringUtf8Coder.of(), 0)); - - FakeWindmillServer server = new FakeWindmillServer(); - DataflowWorkerHarnessOptions options = createTestingPipelineOptions(); - options.setNumberOfWorkerHarnessThreads(expectedNumberOfThreads); - - StreamingDataflowWorker worker = - new StreamingDataflowWorker(Arrays.asList(defaultMapTask(instructions)), server, options); - worker.start(); - - for (int i = 0; i < expectedNumberOfThreads * 2; ++i) { - server.addWorkToOffer(makeInput(i, TimeUnit.MILLISECONDS.toMicros(i))); - } - - // This will fail to complete if the number of threads is less than the amount of work. - // Forcing this test to timeout. - BlockingFn.counter.acquire(expectedNumberOfThreads); - - // Attempt to acquire an additional permit, if we were able to then that means - // too many items were being processed concurrently. - if (BlockingFn.counter.tryAcquire(500, TimeUnit.MILLISECONDS)) { - fail("Expected number of threads " + expectedNumberOfThreads + " does not match actual " - + "number of work items processed concurrently " + BlockingFn.callCounter.get() + "."); - } - - BlockingFn.blocker.countDown(); - } - - static class KeyTokenInvalidFn extends DoFn, KV> { - static boolean thrown = false; - - @Override - public void processElement(ProcessContext c) { - if (!thrown) { - thrown = true; - throw new StreamingDataflowWorker.KeyTokenInvalidException("key"); - } else { - c.output(c.element()); - } - } - } - - @Test - public void testKeyTokenInvalidException() throws Exception { - KvCoder kvCoder = KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()); - - List instructions = Arrays.asList( - makeSourceInstruction(kvCoder), - makeDoFnInstruction(new KeyTokenInvalidFn(), 0, kvCoder), - makeSinkInstruction(kvCoder, 1)); - - FakeWindmillServer server = new FakeWindmillServer(); - server.addWorkToOffer(makeInput(0, 0, "key")); - - StreamingDataflowWorker worker = new StreamingDataflowWorker( - Arrays.asList(defaultMapTask(instructions)), server, createTestingPipelineOptions()); - worker.start(); - - server.waitForEmptyWorkQueue(); - - server.addWorkToOffer(makeInput(1, 0, "key")); - - Map result = server.waitForAndGetCommits(1); - - assertEquals(makeExpectedOutput(1, 0, "key", "key").build(), stripCounters(result.get(1L))); - assertEquals(1, result.size()); - } - - static class ChangeKeysFn extends DoFn, KV> { - @Override - public void processElement(ProcessContext c) { - KV elem = c.element(); - c.output(KV.of(elem.getKey() + "_" + elem.getValue(), elem.getValue())); - } - } - - @Test - public void testKeyChange() throws Exception { - KvCoder kvCoder = KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()); - - List instructions = Arrays.asList( - makeSourceInstruction(kvCoder), - makeDoFnInstruction(new ChangeKeysFn(), 0, kvCoder), - makeSinkInstruction(kvCoder, 1)); - - FakeWindmillServer server = new FakeWindmillServer(); - server.addWorkToOffer(makeInput(0, 0)); - server.addWorkToOffer(makeInput(1, TimeUnit.MILLISECONDS.toMicros(1))); - - StreamingDataflowWorker worker = new StreamingDataflowWorker( - Arrays.asList(defaultMapTask(instructions)), server, createTestingPipelineOptions()); - worker.start(); - - Map result = server.waitForAndGetCommits(2); - - for (int i = 0; i < 2; i++) { - assertEquals(makeExpectedOutput(i, TimeUnit.MILLISECONDS.toMicros(i), - keyStringForIndex(i), keyStringForIndex(i) + "_data" + i).build(), - stripCounters(result.get((long) i))); - } - } - - static class TestExceptionFn extends DoFn { - @Override - public void processElement(ProcessContext c) throws Exception { - try { - throw new Exception("Exception!"); - } catch (Exception e) { - throw new Exception("Another exception!", e); - } - } - } - - @Test - public void testExceptions() throws Exception { - List instructions = Arrays.asList( - makeSourceInstruction(StringUtf8Coder.of()), - makeDoFnInstruction(new TestExceptionFn(), 0, StringUtf8Coder.of()), - makeSinkInstruction(StringUtf8Coder.of(), 1)); - - FakeWindmillServer server = new FakeWindmillServer(); - server.setExpectedExceptionCount(1); - server.addWorkToOffer(buildInput( - "work {" + - " computation_id: \"" + DEFAULT_COMPUTATION_ID + "\"" + - " work {" + - " key: \"" + keyStringForIndex(0) + "\"" + - " work_token: 0" + - " message_bundles {" + - " source_computation_id: \"" + DEFAULT_SOURCE_COMPUTATION_ID + "\"" + - " messages {" + - " timestamp: 0" + - " data: \"0\"" + - " }" + - " }" + - " }" + - "}", - CoderUtils.encodeToByteArray(CollectionCoder.of(IntervalWindow.getCoder()), - Arrays.asList(DEFAULT_WINDOW)))); - - StreamingDataflowWorker worker = new StreamingDataflowWorker( - Arrays.asList(defaultMapTask(instructions)), server, createTestingPipelineOptions()); - worker.start(); - - Windmill.Exception exception = server.getException(); - - assertThat(exception.getStackFrames(0), - containsString("Another exception!")); - assertThat(exception.getStackFrames(1), - containsString("processElement")); - assertTrue(exception.hasCause()); - - assertThat(exception.getCause().getStackFrames(0), - containsString("Exception!")); - assertThat(exception.getCause().getStackFrames(1), - containsString("processElement")); - assertFalse(exception.getCause().hasCause()); - - // The server should retry the work since reporting the exception succeeded. - // Make next retry should fail because we only expected 1 exception. - exception = server.getException(); - } - - @Test - public void testAssignWindows() throws Exception { - Duration gapDuration = Duration.standardSeconds(1); - CloudObject spec = CloudObject.forClassName("AssignWindowsDoFn"); - addString(spec, PropertyNames.SERIALIZED_FN, - StringUtils.byteArrayToJsonString( - SerializableUtils.serializeToByteArray( - WindowingStrategy.of(FixedWindows.of(gapDuration))))); - - ParallelInstruction addWindowsInstruction = - new ParallelInstruction() - .setSystemName("AssignWindows") - .setName("AssignWindows") - .setParDo(new ParDoInstruction() - .setInput(new InstructionInput().setProducerInstructionIndex(0).setOutputNum(0)) - .setNumOutputs(1) - .setUserFn(spec)) - .setOutputs(Arrays.asList(new InstructionOutput() - .setName("output") - .setCodec(WindowedValue.getFullCoder(StringUtf8Coder.of(), - IntervalWindow.getCoder()).asCloudObject()))); - - List instructions = Arrays.asList( - makeSourceInstruction(StringUtf8Coder.of()), - addWindowsInstruction, - makeSinkInstruction(StringUtf8Coder.of(), 1)); - - FakeWindmillServer server = new FakeWindmillServer(); - - int timestamp1 = 0; - int timestamp2 = 1000000; - - server.addWorkToOffer(makeInput(timestamp1, timestamp1)); - server.addWorkToOffer(makeInput(timestamp2, timestamp2)); - - StreamingDataflowWorker worker = new StreamingDataflowWorker( - Arrays.asList(defaultMapTask(instructions)), server, createTestingPipelineOptions()); - worker.start(); - - Map result = server.waitForAndGetCommits(2); - - assertThat( - stripCounters(result.get((long) timestamp1)), - equalTo(setMessagesMetadata(PaneInfo.NO_FIRING, windowAtZeroBytes(), - makeExpectedOutput(timestamp1, timestamp1)) - .build())); - - assertThat(stripCounters(result.get((long) timestamp2)), - equalTo(setMessagesMetadata(PaneInfo.NO_FIRING, windowAtOneSecondBytes(), - makeExpectedOutput(timestamp2, timestamp2)) - .build())); - } - - @Test - public void testMergeWindows() throws Exception { - Coder> kvCoder = KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()); - Coder>> windowedKvCoder = - FullWindowedValueCoder.of(kvCoder, IntervalWindow.getCoder()); - KvCoder> groupedCoder = - KvCoder.of(StringUtf8Coder.of(), ListCoder.of(StringUtf8Coder.of())); - Coder>>> windowedGroupedCoder = - FullWindowedValueCoder.of(groupedCoder, IntervalWindow.getCoder()); - - CloudObject spec = CloudObject.forClassName("MergeWindowsDoFn"); - addString(spec, PropertyNames.SERIALIZED_FN, - StringUtils.byteArrayToJsonString( - SerializableUtils.serializeToByteArray( - WindowingStrategy.of(FixedWindows.of(Duration.standardSeconds(1)))))); - addObject(spec, PropertyNames.INPUT_CODER, windowedKvCoder.asCloudObject()); - - ParallelInstruction mergeWindowsInstruction = - new ParallelInstruction() - .setSystemName("MergeWindows-System") - .setName("MergeWindowsStep") - .setParDo(new ParDoInstruction() - .setInput(new InstructionInput().setProducerInstructionIndex(0).setOutputNum(0)) - .setNumOutputs(1) - .setUserFn(spec)) - .setOutputs(Arrays.asList(new InstructionOutput() - .setName("output") - .setCodec(windowedGroupedCoder.asCloudObject()))); - - List instructions = Arrays.asList( - makeWindowingSourceInstruction(kvCoder), - mergeWindowsInstruction, - makeSinkInstruction(groupedCoder, 1)); - - FakeWindmillServer server = new FakeWindmillServer(); - - StreamingDataflowWorker worker = new StreamingDataflowWorker( - Arrays.asList(defaultMapTask(instructions)), server, createTestingPipelineOptions()); - Map nameMap = new HashMap<>(); - nameMap.put("MergeWindowsStep", "MergeWindows"); - worker.addStateNameMappings(nameMap); - worker.start(); - - server.addWorkToOffer(buildInput( - "work {" + - " computation_id: \"" + DEFAULT_COMPUTATION_ID + "\"" + - " input_data_watermark: 0" + - " work {" + - " key: \"" + DEFAULT_KEY_STRING + "\"" + - " work_token: 0" + - " message_bundles {" + - " source_computation_id: \"" + DEFAULT_SOURCE_COMPUTATION_ID + "\"" + - " messages {" + - " timestamp: 0" + - " data: \"" + dataStringForIndex(0) + "\"" + - " }" + - " }" + - " }" + - "}", - windowAtZeroBytes())); - - Map result = server.waitForAndGetCommits(1); - - // These tags and data are opaque strings and this is a change detector test. - String window = "/gAAAAAAAA-joBw/"; - ByteString timerTag = ByteString.copyFromUtf8(window + "+0:999"); // GC timer just has window - ByteString bufferTag = ByteString.copyFromUtf8(window + "+sbuf"); - ByteString paneInfoTag = ByteString.copyFromUtf8(window + "+spane"); - ByteString watermarkDataHoldTag = - ByteString.copyFromUtf8(window + "+shold"); - ByteString watermarkExtraHoldTag = - ByteString.copyFromUtf8(window + "+sextra"); - String stateFamily = "MergeWindows"; - ByteString bufferData = ByteString.copyFromUtf8("\000data0"); - // Encoded form for Iterable: -1, true, 'data0', false - ByteString outputData = ByteString.copyFrom( - new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, - 0x01, 0x05, 0x64, 0x61, 0x74, 0x61, 0x30, 0x00 }); - - // These values are not essential to the change detector test - long timerTimestamp = 999000L; - - WorkItemCommitRequest actualOutput = result.get(0L); - - // Set timer - assertThat(actualOutput.getOutputTimersList(), Matchers.contains( - Matchers.equalTo(Windmill.Timer.newBuilder() - .setTag(timerTag) - .setStateFamily(stateFamily) - .setTimestamp(timerTimestamp) - .setType(Windmill.Timer.Type.WATERMARK).build()))); - - assertThat(actualOutput.getListUpdatesList(), Matchers.contains( - Matchers.equalTo(Windmill.TagList.newBuilder() - .setTag(bufferTag) - .setStateFamily(stateFamily) - .addValues(Windmill.Value.newBuilder() - .setTimestamp(Long.MAX_VALUE) - .setData(bufferData) - .build()) - .build()))); - - assertThat( - actualOutput.getWatermarkHoldsList(), - Matchers.containsInAnyOrder( - Windmill.WatermarkHold.newBuilder() - .setTag(watermarkDataHoldTag) - .setStateFamily(stateFamily) - .addTimestamps(0) - .build())); - - List counters = actualOutput.getCounterUpdatesList(); - // No state reads - assertEquals(0L, getCounter(counters, "WindmillStateBytesRead").getIntScalar()); - // Timer + buffer + watermark hold - assertEquals( - Windmill.WorkItemCommitRequest.newBuilder(actualOutput) - .clearCounterUpdates() - .clearOutputMessages() - .build() - .getSerializedSize(), - getCounter(counters, "WindmillStateBytesWritten").getIntScalar()); - // Input messages - assertEquals(VarInt.getLength(0L) + dataStringForIndex(0).length() - + addPaneTag(PaneInfo.NO_FIRING, windowAtZeroBytes()).size() + 5L /* proto overhead */, - getCounter(counters, "WindmillShuffleBytesRead").getIntScalar()); - - Windmill.GetWorkResponse.Builder getWorkResponse = Windmill.GetWorkResponse.newBuilder(); - getWorkResponse.addWorkBuilder() - .setComputationId(DEFAULT_COMPUTATION_ID) - .setInputDataWatermark(timerTimestamp) - .addWorkBuilder() - .setKey(ByteString.copyFromUtf8(DEFAULT_KEY_STRING)) - .setWorkToken(1) - .getTimersBuilder().addTimersBuilder() - .setTag(timerTag) - .setStateFamily(stateFamily) - .setTimestamp(timerTimestamp); - server.addWorkToOffer(getWorkResponse.build()); - - long expectedBytesRead = 0L; - - Windmill.GetDataResponse.Builder dataResponse = Windmill.GetDataResponse.newBuilder(); - Windmill.KeyedGetDataResponse.Builder dataBuilder = dataResponse.addDataBuilder() - .setComputationId(DEFAULT_COMPUTATION_ID) - .addDataBuilder() - .setKey(ByteString.copyFromUtf8(DEFAULT_KEY_STRING)); - dataBuilder.addListsBuilder() - .setTag(bufferTag) - .setStateFamily(stateFamily) - .addValuesBuilder() - .setTimestamp(0) // is ignored - .setData(bufferData); - dataBuilder.addWatermarkHoldsBuilder() - .setTag(watermarkDataHoldTag) - .setStateFamily(stateFamily) - .addTimestamps(0); - dataBuilder.addWatermarkHoldsBuilder() - .setTag(watermarkExtraHoldTag) - .setStateFamily(stateFamily) - .addTimestamps(0); - dataBuilder.addValuesBuilder() - .setTag(paneInfoTag) - .setStateFamily(stateFamily) - .getValueBuilder() - .setTimestamp(0) - .setData(ByteString.EMPTY); - server.addDataToOffer(dataResponse.build()); - - expectedBytesRead += dataBuilder.build().getSerializedSize(); - - result = server.waitForAndGetCommits(1); - - actualOutput = result.get(1L); - - assertEquals(1, actualOutput.getOutputMessagesCount()); - assertEquals(DEFAULT_DESTINATION_STREAM_ID, - actualOutput.getOutputMessages(0).getDestinationStreamId()); - assertEquals(DEFAULT_KEY_STRING, - actualOutput.getOutputMessages(0).getBundles(0).getKey().toStringUtf8()); - assertEquals(0, - actualOutput.getOutputMessages(0).getBundles(0).getMessages(0).getTimestamp()); - assertEquals(outputData, - actualOutput.getOutputMessages(0).getBundles(0).getMessages(0).getData()); - - ByteString metadata = - actualOutput.getOutputMessages(0).getBundles(0).getMessages(0).getMetadata(); - assertEquals(PaneInfo.createPane(true, true, Timing.ON_TIME), - PaneInfo.decodePane(metadata.byteAt(0))); - Assert.assertArrayEquals(windowAtZeroBytes(), metadata.substring(1).toByteArray()); - - // Data was deleted - assertThat("" + actualOutput.getValueUpdatesList(), - actualOutput.getValueUpdatesList(), Matchers.contains( - Matchers.equalTo(Windmill.TagValue.newBuilder() - .setTag(paneInfoTag) - .setStateFamily(stateFamily) - .setValue(Windmill.Value.newBuilder() - .setTimestamp(Long.MAX_VALUE).setData(ByteString.EMPTY)) - .build()))); - - assertThat("" + actualOutput.getListUpdatesList(), - actualOutput.getListUpdatesList(), Matchers.contains( - Matchers.equalTo(Windmill.TagList.newBuilder() - .setTag(bufferTag) - .setStateFamily(stateFamily) - .setEndTimestamp(Long.MAX_VALUE) - .build()))); - - assertThat( - actualOutput.getWatermarkHoldsList(), - Matchers.containsInAnyOrder( - Windmill.WatermarkHold.newBuilder() - .setTag(watermarkDataHoldTag) - .setStateFamily(stateFamily) - .setReset(true) - .build(), - Windmill.WatermarkHold.newBuilder() - .setTag(watermarkExtraHoldTag) - .setStateFamily(stateFamily) - .setReset(true) - .build())); - - counters = actualOutput.getCounterUpdatesList(); - - Windmill.Counter actualReadCounter = - getCounter(counters, "computation-MergeWindows-System-windmill-read-msecs"); - assertNotNull(actualReadCounter); - assertThat(actualReadCounter.getIntScalar(), Matchers.greaterThan(0L)); - - // State reads for windowing - assertEquals(expectedBytesRead, getCounter(counters, "WindmillStateBytesRead").getIntScalar()); - // State updates to clear state - assertEquals( - Windmill.WorkItemCommitRequest.newBuilder(actualOutput) - .clearCounterUpdates() - .clearOutputMessages() - .build() - .getSerializedSize(), - getCounter(counters, "WindmillStateBytesWritten").getIntScalar()); - // No input messages - assertEquals(0L, getCounter(counters, "WindmillShuffleBytesRead").getIntScalar()); - } - - private static Windmill.Counter getCounter(List counters, String name) { - for (Windmill.Counter counter : counters) { - if (counter.getName().equals(name)) { - return counter; - } - } - return null; - } - - static class PrintFn extends DoFn>, String> { - @Override - public void processElement(ProcessContext c) { - KV elem = c.element().getValue(); - c.output(elem.getKey() + ":" + elem.getValue()); - } - } - - @Test - public void testUnboundedSources() throws Exception { - List finalizeTracker = Lists.newArrayList(); - - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setNumWorkers(1); - - List instructions = - Arrays.asList( - new ParallelInstruction() - .setSystemName("Read") - .setRead( - new ReadInstruction() - .setSource( - CustomSources.serializeToCloudSource( - new TestCountingSource(1), options))) - .setOutputs( - Arrays.asList( - new InstructionOutput() - .setName("read_output") - .setCodec( - WindowedValue.getFullCoder( - ValueWithRecordId.ValueWithRecordIdCoder.of( - KvCoder.of(VarIntCoder.of(), VarIntCoder.of())), - GlobalWindow.Coder.INSTANCE) - .asCloudObject()))), - makeDoFnInstruction( - new PrintFn(), 0, StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE), - makeSinkInstruction(StringUtf8Coder.of(), 1, GlobalWindow.Coder.INSTANCE)); - - TestCountingSource.setFinalizeTracker(finalizeTracker); - - FakeWindmillServer server = new FakeWindmillServer(); - StreamingDataflowWorker worker = new StreamingDataflowWorker( - Arrays.asList(defaultMapTask(instructions)), server, createTestingPipelineOptions()); - worker.start(); - - // Test new key. - server.addWorkToOffer(buildInput( - "work {" + - " computation_id: \"computation\"" + - " input_data_watermark: 0" + - " work {" + - " key: \"0000000000000001\"" + - " work_token: 1" + - " }" + - "}", null)); - - Map result = server.waitForAndGetCommits(1); - - Windmill.WorkItemCommitRequest commit = stripCounters(result.get(1L)); - UnsignedLong finalizeId = - UnsignedLong.fromLongBits(commit.getSourceStateUpdates().getFinalizeIds(0)); - - assertThat(commit, - equalTo(setMessagesMetadata(PaneInfo.NO_FIRING, - CoderUtils.encodeToByteArray( - CollectionCoder.of(GlobalWindow.Coder.INSTANCE), - Arrays.asList(GlobalWindow.INSTANCE)), - parseCommitRequest( - "key: \"0000000000000001\" " + - "work_token: 1 " + - "output_messages {" + - " destination_stream_id: \"out\"" + - " bundles {" + - " key: \"0000000000000001\"" + - " messages {" + - " timestamp: 0" + - " data: \"0:0\"" + - " }" + - " messages_ids: \"\"" + - " }" + - "} " + - "source_state_updates {" + - " state: \"\000\"" + - " finalize_ids: " + finalizeId + - "} " + - "source_watermark: 1000")).build())); - - assertEquals( - 16L, - getCounter(result.get(1L).getCounterUpdatesList(), "dataflow_input_size-computation") - .getIntScalar()); - - // Test same key continuing. - server.addWorkToOffer(buildInput( - "work {" + - " computation_id: \"computation\"" + - " input_data_watermark: 0" + - " work {" + - " key: \"0000000000000001\"" + - " work_token: 2" + - " source_state {" + - " state: \"\000\"" + - " finalize_ids: " + finalizeId + - " } " + - " }" + - "}", null)); - - result = server.waitForAndGetCommits(1); - - commit = stripCounters(result.get(2L)); - finalizeId = UnsignedLong.fromLongBits(commit.getSourceStateUpdates().getFinalizeIds(0)); - - assertThat(commit, - equalTo(parseCommitRequest( - "key: \"0000000000000001\" " + - "work_token: 2 " + - "source_state_updates {" + - " state: \"\000\"" + - " finalize_ids: " + finalizeId + - "} " + - "source_watermark: 1000").build())); - - assertThat(finalizeTracker, contains(0)); - - assertEquals( - 0L, - getCounter(result.get(2L).getCounterUpdatesList(), "dataflow_input_size-computation") - .getIntScalar()); - - // Test recovery. - server.addWorkToOffer(buildInput( - "work {" + - " computation_id: \"computation\"" + - " input_data_watermark: 0" + - " work {" + - " key: \"0000000000000002\"" + - " work_token: 3" + - " source_state {" + - " state: \"\005\"" + - " } " + - " }" + - "}", null)); - - result = server.waitForAndGetCommits(1); - - commit = stripCounters(result.get(3L)); - finalizeId = UnsignedLong.fromLongBits(commit.getSourceStateUpdates().getFinalizeIds(0)); - - assertThat(commit, - equalTo(setMessagesMetadata(PaneInfo.NO_FIRING, - CoderUtils.encodeToByteArray( - CollectionCoder.of(GlobalWindow.Coder.INSTANCE), - Arrays.asList(GlobalWindow.INSTANCE)), - parseCommitRequest( - "key: \"0000000000000002\" " + - "work_token: 3 " + - "output_messages {" + - " destination_stream_id: \"out\"" + - " bundles {" + - " key: \"0000000000000002\"" + - " messages {" + - " timestamp: 5000" + - " data: \"1:5\"" + - " }" + - " messages_ids: \"\"" + - " }" + - "} " + - "source_state_updates {" + - " state: \"\005\"" + - " finalize_ids: " + finalizeId + - "} " + - "source_watermark: 6000")).build())); - - assertEquals( - 16L, - getCounter(result.get(3L).getCounterUpdatesList(), "dataflow_input_size-computation") - .getIntScalar()); - } - - private static class MockWork extends StreamingDataflowWorker.Work { - public MockWork(long workToken) { - super(workToken); - } - @Override - public void run() {} - } - - @Test - public void testActiveWork() throws Exception { - BoundedQueueExecutor mockExecutor = Mockito.mock(BoundedQueueExecutor.class); - StreamingDataflowWorker.ActiveWorkForComputation activeWork = - new StreamingDataflowWorker.ActiveWorkForComputation(mockExecutor); - - ByteString key1 = ByteString.copyFromUtf8("key1"); - ByteString key2 = ByteString.copyFromUtf8("key2"); - - assertEquals(true, activeWork.activateWork(key1, new MockWork(1))); - activeWork.completeWork(key1); - - assertEquals(true, activeWork.activateWork(key1, new MockWork(2))); - assertEquals(false, activeWork.activateWork(key1, new MockWork(2))); - assertEquals(false, activeWork.activateWork(key1, new MockWork(3))); - assertEquals(true, activeWork.activateWork(key2, new MockWork(4))); - activeWork.completeWork(key2); - Mockito.verifyNoMoreInteractions(mockExecutor); - - activeWork.completeWork(key1); - Mockito.verify(mockExecutor).forceExecute(Mockito.any()); - activeWork.completeWork(key1); - - assertEquals(true, activeWork.activateWork(key1, new MockWork(1))); - activeWork.completeWork(key1); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java index e8f07830b5..b781546b1b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; -import com.google.cloud.dataflow.sdk.runners.worker.StreamingDataflowWorker.ReaderCacheEntry; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.testing.PCollectionViewTesting; import com.google.cloud.dataflow.sdk.testing.PCollectionViewTesting.ConstantViewFn; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java index 961c33025c..9a411f9354 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java @@ -383,14 +383,14 @@ public void testKeyTokenInvalid() throws Exception { watermarkFuture.get(); fail("Expected KeyTokenInvalidException"); } catch (Throwable e) { - assertTrue(StreamingDataflowWorker.isKeyTokenInvalidException(e)); + assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(e)); } try { listFuture.get(); fail("Expected KeyTokenInvalidException"); } catch (Throwable e) { - assertTrue(StreamingDataflowWorker.isKeyTokenInvalidException(e)); + assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(e)); } } diff --git a/worker/pom.xml b/worker/pom.xml index 476d3fbb2f..111301fda7 100644 --- a/worker/pom.xml +++ b/worker/pom.xml @@ -212,19 +212,33 @@ internal-only + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-all + ${project.version} + test-jar + test + + + + com.google.guava + guava + ${guava.version} + + org.hamcrest hamcrest-all ${hamcrest.version} - provided + test junit junit ${junit.version} - provided + test From e852da2511ef78c755ffc7afcf9835a502d1bd2d Mon Sep 17 00:00:00 2001 From: kirpichov Date: Mon, 1 Feb 2016 23:54:25 -0800 Subject: [PATCH 062/751] Removes dependency on LegacyReaderIterator from more readers This time, file-based readers, ISM and BigQuery reader. Only shuffle readers remain. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113606351 --- .../google/cloud/dataflow/sdk/io/AvroIO.java | 16 +- .../cloud/dataflow/sdk/io/BigQueryIO.java | 15 +- .../dataflow/sdk/io/CompressedSource.java | 1 - .../google/cloud/dataflow/sdk/io/TextIO.java | 10 +- .../sdk/runners/worker/AvroByteReader.java | 36 ++- .../sdk/runners/worker/AvroReader.java | 40 ++- .../sdk/runners/worker/BigQueryReader.java | 33 ++- .../sdk/runners/worker/IsmReader.java | 114 ++++---- .../worker/LazyMultiReaderIterator.java | 52 ++-- .../sdk/runners/worker/ReaderUtils.java | 74 ++++++ .../sdk/runners/worker/TextReader.java | 65 +++-- .../sdk/util/BigQueryTableRowIterator.java | 146 +++++------ .../dataflow/sdk/util/CloudSourceUtils.java | 3 +- .../cloud/dataflow/sdk/util/ReaderUtils.java | 42 --- .../runners/dataflow/CustomSourcesTest.java | 4 +- .../runners/worker/AvroByteReaderTest.java | 10 +- .../sdk/runners/worker/AvroByteSinkTest.java | 2 +- .../sdk/runners/worker/AvroReaderTest.java | 18 +- .../sdk/runners/worker/AvroSinkTest.java | 2 +- .../runners/worker/BigQueryReaderTest.java | 27 +- .../worker/ConcatReaderFactoryTest.java | 2 +- .../sdk/runners/worker/ConcatReaderTest.java | 2 +- .../sdk/runners/worker/IsmReaderTest.java | 18 +- .../sdk/runners/worker/ReaderTestUtils.java | 43 --- .../sdk/runners/worker/TextReaderTest.java | 246 ++++++++---------- .../WindmillReaderIteratorBaseTest.java | 2 +- .../util/BigQueryTableRowIteratorTest.java | 11 +- .../dataflow/sdk/util/BigQueryUtilTest.java | 49 ++-- .../dataflow/sdk/util/IOFactoryTest.java | 21 +- 29 files changed, 573 insertions(+), 531 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReaderUtils.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java index 7997d96f45..b18e7266e5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java @@ -24,8 +24,8 @@ import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.runners.worker.AvroReader; import com.google.cloud.dataflow.sdk.runners.worker.AvroSink; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.ReaderUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; @@ -785,12 +785,16 @@ private static void evaluateReadHelper( Read.Bound transform, DirectPipelineRunner.EvaluationContext context) { AvroReader reader = new AvroReader<>(transform.filepattern, null, null, (AvroCoder) transform.getDefaultOutputCoder(), context.getPipelineOptions()); - List> elems = ReaderUtils.readElemsFromReader(reader); - List> output = new ArrayList<>(); - for (WindowedValue elem : elems) { - output.add(ValueWithMetadata.of(elem)); + try { + List> elems = ReaderUtils.readAllFromReader(reader); + List> output = new ArrayList<>(); + for (WindowedValue elem : elems) { + output.add(ValueWithMetadata.of(elem)); + } + context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); + } catch (IOException e) { + throw new RuntimeException(e); } - context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); } private static void evaluateWriteHelper( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index fbebd52dc2..6a56a81a98 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -57,7 +57,6 @@ import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -1422,9 +1421,17 @@ private static void evaluateReadHelper( iterator = BigQueryTableRowIterator.fromTable(transform.table, client); } - List elems = ImmutableList.copyOf(iterator); - LOG.info("Number of records read from BigQuery: {}", elems.size()); - context.setPCollection(context.getOutput(transform), elems); + try (BigQueryTableRowIterator ignored = iterator) { + List elems = new ArrayList<>(); + iterator.open(); + while (iterator.advance()) { + elems.add(iterator.getCurrent()); + } + LOG.info("Number of records read from BigQuery: {}", elems.size()); + context.setPCollection(context.getOutput(transform), elems); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } } private static List getOrCreateMapListValue(Map> map, K key) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index 5f98732608..687fa04ab6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -18,7 +18,6 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.common.base.Preconditions; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 4f2f1b8acd..2e95b968a2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -21,10 +21,10 @@ import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.runners.worker.TextReader; import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.ReaderUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; @@ -782,8 +782,12 @@ private static void evaluateReadHelper( TextReader reader = new TextReader<>(transform.filepattern, true, null, null, transform.coder, transform.getCompressionType()); - List elems = ReaderUtils.readElemsFromReader(reader); - context.setPCollection(context.getOutput(transform), elems); + try { + List elems = ReaderUtils.readAllFromReader(reader); + context.setPCollection(context.getOutput(transform), elems); + } catch (IOException e) { + throw new RuntimeException(e); + } } private static void evaluateWriteHelper( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java index 4f73a0503a..418dd05d9c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java @@ -27,6 +27,7 @@ import java.io.IOException; import java.nio.ByteBuffer; +import java.util.NoSuchElementException; import javax.annotation.Nullable; @@ -54,27 +55,48 @@ public AvroByteFileIterator iterator() throws IOException { return new AvroByteFileIterator(); } - class AvroByteFileIterator extends LegacyReaderIterator { - private final LegacyReaderIterator> avroFileIterator; + class AvroByteFileIterator extends NativeReaderIterator { + private final NativeReaderIterator> avroFileIterator; + private T current; public AvroByteFileIterator() throws IOException { avroFileIterator = avroReader.iterator(); } @Override - protected boolean hasNextImpl() throws IOException { - return avroFileIterator.hasNext(); + public boolean start() throws IOException { + if (!avroFileIterator.start()) { + return false; + } + updateCurrent(); + return true; } @Override - protected T nextImpl() throws IOException { - ByteBuffer inBuffer = avroFileIterator.next().getValue(); + public boolean advance() throws IOException { + if (!avroFileIterator.advance()) { + return false; + } + updateCurrent(); + return true; + } + + @Override + public T getCurrent() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + return current; + } + + private void updateCurrent() throws IOException { + ByteBuffer inBuffer = avroFileIterator.getCurrent().getValue(); byte[] encodedElem = new byte[inBuffer.remaining()]; inBuffer.get(encodedElem); assert inBuffer.remaining() == 0; inBuffer.clear(); notifyElementRead(encodedElem.length); - return CoderUtils.decodeFromByteArray(coder, encodedElem); + current = CoderUtils.decodeFromByteArray(coder, encodedElem); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java index 725ebec9ef..90452c1f04 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java @@ -33,6 +33,7 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.NoSuchElementException; import javax.annotation.Nullable; @@ -98,18 +99,34 @@ public AvroFileIterator iterator() throws IOException { return new AvroFileIterator((AvroSource.AvroReader) reader); } - class AvroFileIterator extends LegacyReaderIterator> { - final AvroSource.AvroReader reader; - boolean hasStarted = false; - long blockOffset = -1; + class AvroFileIterator extends NativeReaderIterator> { + private final AvroSource.AvroReader reader; + private long blockOffset = -1; + private WindowedValue current; public AvroFileIterator(AvroSource.AvroReader reader) { this.reader = reader; } @Override - protected WindowedValue nextImpl() throws IOException { - T next = reader.getCurrent(); + public boolean start() throws IOException { + if (!reader.start()) { + return false; + } + updateBlockOffsetAndCurrent(); + return true; + } + + @Override + public boolean advance() throws IOException { + if (!reader.advance()) { + return false; + } + updateBlockOffsetAndCurrent(); + return true; + } + + private void updateBlockOffsetAndCurrent() { // Coarse-grained reporting of input bytes consumed. // After completing reading a block, the block offset changes. long currentOffset = reader.getCurrentBlockOffset(); @@ -117,16 +134,15 @@ protected WindowedValue nextImpl() throws IOException { notifyElementRead(reader.getCurrentBlockSize()); blockOffset = currentOffset; } - return WindowedValue.valueInGlobalWindow(next); + current = WindowedValue.valueInGlobalWindow(reader.getCurrent()); } @Override - protected boolean hasNextImpl() throws IOException { - if (!hasStarted) { - hasStarted = true; - return reader.start(); + public WindowedValue getCurrent() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); } - return reader.advance(); + return current; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java index de726712a2..975bf38218 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java @@ -27,6 +27,7 @@ import com.google.common.annotations.VisibleForTesting; import java.io.IOException; +import java.util.NoSuchElementException; import javax.annotation.Nullable; @@ -92,8 +93,9 @@ public BigQueryReaderIterator iterator() throws IOException { * A ReaderIterator that yields TableRow objects for each row of a BigQuery table. */ @VisibleForTesting - static class BigQueryReaderIterator extends LegacyReaderIterator> { + static class BigQueryReaderIterator extends NativeReaderIterator> { private BigQueryTableRowIterator rowIterator; + private WindowedValue current; public BigQueryReaderIterator(TableReference tableRef, Bigquery bigQueryClient) { rowIterator = BigQueryTableRowIterator.fromTable(tableRef, bigQueryClient); @@ -106,13 +108,34 @@ public BigQueryReaderIterator(String query, String projectId, Bigquery bigQueryC } @Override - protected boolean hasNextImpl() { - return rowIterator.hasNext(); + public boolean start() throws IOException { + try { + rowIterator.open(); + } catch (InterruptedException e) { + throw new IOException(e); + } + return advance(); } @Override - protected WindowedValue nextImpl() throws IOException { - return WindowedValue.valueInGlobalWindow(rowIterator.next()); + public boolean advance() throws IOException { + try { + if (!rowIterator.advance()) { + return false; + } + } catch (InterruptedException e) { + throw new IOException(e); + } + current = WindowedValue.valueInGlobalWindow(rowIterator.getCurrent()); + return true; + } + + @Override + public WindowedValue getCurrent() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + return current; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java index 2d0458437a..88c4f54f7a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java @@ -34,7 +34,6 @@ import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSortedMap; import java.io.IOException; @@ -113,9 +112,9 @@ public KV get(K k) throws IOException { RandomAccessDataCoder.of(), valueCoder, footer.getBloomFilterPosition())) { - while (iterator.hasNext()) { - long startPosition = inChannel.position(); - KV next = iterator.next(); + long startPosition = inChannel.position(); + for (boolean more = iterator.start(); more; more = iterator.advance()) { + KV next = iterator.getCurrent(); int comparison = RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( next.getKey(), keyBytes); // If the current key is greater then the requested key, this Ism file does not contain @@ -126,6 +125,7 @@ public KV get(K k) throws IOException { notifyElementRead(inChannel.position() - startPosition); return KV.of(k, next.getValue()); } + startPosition = inChannel.position(); } } // We hit the end of the file, therefore this Ism file does not contain the key. @@ -156,49 +156,50 @@ private synchronized void initializeFooter(SeekableByteChannel in) throws IOExce * A {@link NativeReaderIterator * Reader.ReaderIterator} which initializes its input stream lazily. */ - private class LazyIsmReaderIterator extends LegacyReaderIterator> { + private class LazyIsmReaderIterator extends NativeReaderIterator> { private IsmReaderIterator delegate; private SeekableByteChannel inChannel; @Override - public boolean hasNextImpl() throws IOException { - return getDelegate().hasNext(); + public boolean start() throws IOException { + inChannel = openConnection(filename); + initializeFooter(inChannel); + delegate = + new IsmReaderIterator<>( + inChannel, + new RandomAccessData(), + keyCoder, + valueCoder, + footer.getBloomFilterPosition()); + + long startPosition = inChannel.position(); + boolean rval = delegate.start(); + notifyElementRead(inChannel.position() - startPosition); + return rval; } @Override - public KV nextImpl() throws IOException, NoSuchElementException { - long startPosition = getChannel().position(); - KV rval = getDelegate().next(); - notifyElementRead(getChannel().position() - startPosition); + public boolean advance() throws IOException { + checkState(delegate != null, "unstarted"); + long startPosition = inChannel.position(); + boolean rval = delegate.advance(); + notifyElementRead(inChannel.position() - startPosition); return rval; } @Override - public void close() throws IOException { - inChannel.close(); - } - - /** - * Return a reader, caching the creation on the first call. - */ - private IsmReaderIterator getDelegate() throws IOException { + public KV getCurrent() { + // By the time getCurrent() is called, delegate should already be created by + // a start() call. if (delegate == null) { - inChannel = getChannel(); - initializeFooter(inChannel); - delegate = new IsmReaderIterator<>(inChannel, new RandomAccessData(), - keyCoder, valueCoder, footer.getBloomFilterPosition()); + throw new NoSuchElementException(); } - return delegate; + return delegate.getCurrent(); } - /** - * Return a connection, caching the creation on the first call. - */ - private SeekableByteChannel getChannel() throws IOException { - if (inChannel == null) { - inChannel = openConnection(filename); - } - return inChannel; + @Override + public void close() throws IOException { + inChannel.close(); } } @@ -207,21 +208,26 @@ private SeekableByteChannel getChannel() throws IOException { * Reader.ReaderIterator} for Ism formatted files which returns a sequence of * {@code KV}'s read from a {@link SeekableByteChannel}. */ - private static class IsmReaderIterator extends LegacyReaderIterator> { + private static class IsmReaderIterator extends NativeReaderIterator> { private final SeekableByteChannel inChannel; private final InputStream inStream; private final RandomAccessData currentKeyBytes; private final Coder keyCoder; private final Coder valueCoder; private final long readLimit; + private KV current; /** * Start an initialized reader that will start from the given key. This reader iterator does * not own the channel and the caller must ensure that it is closed. */ - public IsmReaderIterator(SeekableByteChannel unownedChannel, - RandomAccessData currentKeyBytes, Coder keyCoder, Coder valueCoder, long readLimit) - throws IOException { + public IsmReaderIterator( + SeekableByteChannel unownedChannel, + RandomAccessData currentKeyBytes, + Coder keyCoder, + Coder valueCoder, + long readLimit) + throws IOException { checkNotNull(unownedChannel); checkNotNull(currentKeyBytes); checkNotNull(keyCoder); @@ -240,15 +246,16 @@ public IsmReaderIterator(SeekableByteChannel unownedChannel, } @Override - public boolean hasNextImpl() throws IOException { - if (inChannel.position() > readLimit) { - throw new IllegalStateException("Read past end of stream"); - } - return inChannel.position() < readLimit; + public boolean start() throws IOException { + return advance(); } @Override - public KV nextImpl() throws IOException, NoSuchElementException { + public boolean advance() throws IOException { + if (inChannel.position() >= readLimit) { + current = null; + return false; + } KeyPrefix keyPrefix = KeyPrefixCoder.of().decode(inStream, Context.NESTED); int totalKeyLength = keyPrefix.getSharedKeySize() + keyPrefix.getUnsharedKeySize(); // currentKey = prevKey[0 : sharedKeySize] + read(unsharedKeySize) @@ -258,7 +265,16 @@ public KV nextImpl() throws IOException, NoSuchElementException { keyPrefix.getUnsharedKeySize() /* read unsharedKeySize bytes from the stream */); K key = keyCoder.decode(currentKeyBytes.asInputStream(0, totalKeyLength), Context.OUTER); V value = valueCoder.decode(inStream, Context.NESTED); - return KV.of(key, value); + current = KV.of(key, value); + return true; + } + + @Override + public KV getCurrent() { + if (current == null) { + throw new NoSuchElementException(); + } + return current; } } @@ -286,7 +302,7 @@ private SeekableByteChannel initializeForKeyedRead() throws IOException { // The index follows the bloom filter directly, so we do not need to do a seek here. // This is an optimization. @SuppressWarnings("resource") - LegacyReaderIterator> iterator = + NativeReaderIterator> iterator = new IsmReaderIterator( inChannel, new RandomAccessData(), @@ -297,8 +313,8 @@ private SeekableByteChannel initializeForKeyedRead() throws IOException { ImmutableSortedMap.orderedBy(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR); // Read the index into memory. - while (iterator.hasNext()) { - KV next = iterator.next(); + for (boolean more = iterator.start(); more; more = iterator.advance()) { + KV next = iterator.getCurrent(); builder.put(next.getKey(), next.getValue()); } index = builder.build(); @@ -310,9 +326,11 @@ private SeekableByteChannel initializeForKeyedRead() throws IOException { */ private static SeekableByteChannel openConnection(String filename) throws IOException { ReadableByteChannel channel = IOChannelUtils.getFactory(filename).open(filename); - Preconditions.checkArgument(channel instanceof SeekableByteChannel, + checkArgument( + channel instanceof SeekableByteChannel, "IsmReader requires a SeekableByteChannel for path %s but received %s.", - filename, channel); + filename, + channel); return (SeekableByteChannel) channel; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java index 96432eda54..4a35fa6f70 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.Iterator; +import java.util.NoSuchElementException; /** * Implements a ReaderIterator over a collection of inputs. @@ -32,50 +33,55 @@ * to be produced lazily, as an open source iterator may consume process * resources such as file descriptors. */ -abstract class LazyMultiReaderIterator extends NativeReader.LegacyReaderIterator { +abstract class LazyMultiReaderIterator extends NativeReader.NativeReaderIterator { private final Iterator inputs; - NativeReader.LegacyReaderIterator current; + private NativeReader.NativeReaderIterator current; public LazyMultiReaderIterator(Iterator inputs) { this.inputs = inputs; } @Override - protected boolean hasNextImpl() throws IOException { - while (selectReader()) { - if (!current.hasNext()) { + public boolean start() throws IOException { + return advance(); + } + + @Override + public boolean advance() throws IOException { + boolean currentStarted = true; + while (true) { + // Try moving through the current reader + if (current != null) { + if (currentStarted ? current.advance() : current.start()) { + return true; + } current.close(); current = null; - } else { - return true; } + // Current reader is done - move on to the next one. + if (!inputs.hasNext()) { + return false; + } + current = open(inputs.next()); + currentStarted = false; } - return false; } @Override - protected T nextImpl() throws IOException { - return current.next(); + public T getCurrent() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + return current.getCurrent(); } @Override public void close() throws IOException { - while (selectReader()) { + if (current != null) { current.close(); current = null; } } - protected abstract NativeReader.LegacyReaderIterator open(String input) throws IOException; - - boolean selectReader() throws IOException { - if (current != null) { - return true; - } - if (inputs.hasNext()) { - current = open(inputs.next()); - return true; - } - return false; - } + protected abstract NativeReader.NativeReaderIterator open(String input) throws IOException; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java new file mode 100644 index 0000000000..3e065f40dd --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Utilities for working with {@link NativeReader} objects. + */ +public class ReaderUtils { + /** + * Creates a {@link NativeReader.NativeReaderIterator} from the given {@link NativeReader} and + * reads it to the end. + * + * @param reader {@link NativeReader} to read from + */ + public static List readAllFromReader(NativeReader reader) throws IOException { + try (NativeReader.NativeReaderIterator iterator = reader.iterator()) { + return readRemainingFromIterator(iterator, false); + } + } + + /** + * Read elements from a {@link NativeReader.NativeReaderIterator} until either the reader is + * exhausted, or {@code n} elements are read. Specifying {@code n == Integer.MAX_VALUE} means + * read all remaining elements. + */ + public static List readNItemsFromIterator( + NativeReader.NativeReaderIterator reader, int n, boolean started) throws IOException { + List res = new ArrayList<>(); + for (long i = 0; n == Integer.MAX_VALUE || i < n; i++) { + if (!((i == 0 && !started) ? reader.start() : reader.advance())) { + break; + } + res.add(reader.getCurrent()); + } + return res; + } + + /** + * Read elements from a {@link NativeReader.NativeReaderIterator} until either the reader is + * exhausted, or n elements are read. Specifying {@code n == Integer.MAX_VALUE} means + * read all remaining elements. + */ + public static List readNItemsFromUnstartedIterator( + NativeReader.NativeReaderIterator reader, int n) throws IOException { + return readNItemsFromIterator(reader, n, false); + } + + /** + * Read elements from a {@link NativeReader.NativeReaderIterator} until the reader is exhausted. + */ + public static List readRemainingFromIterator( + NativeReader.NativeReaderIterator reader, boolean started) throws IOException { + return readNItemsFromIterator(reader, Integer.MAX_VALUE, started); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java index fe681aaa75..cda7fedbf1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java @@ -48,6 +48,7 @@ import java.nio.channels.SeekableByteChannel; import java.util.Collection; import java.util.Iterator; +import java.util.NoSuchElementException; import javax.annotation.Nullable; @@ -117,24 +118,14 @@ private double getTotalParallelismUnsplittable() throws IOException { return expandedFilepattern().size(); } - private LegacyReaderIterator newReaderIteratorForRangeInFile( + private NativeReaderIterator newReaderIteratorForRangeInFile( IOChannelFactory factory, String oneFile, long startPosition, @Nullable Long endPosition) - throws IOException { - // Position before the first record, so we can find the record beginning. - final long start = startPosition > 0 ? startPosition - 1 : 0; - - TextFileIterator iterator = newReaderIteratorForRangeWithStrictStart( - factory, oneFile, stripTrailingNewlines, start, endPosition); - - // Skip the initial record if start position was set. - if (startPosition > 0) { - iterator.hasNextImpl(); - } - - return iterator; + throws IOException { + return newReaderIteratorForRangeWithStrictStart( + factory, oneFile, stripTrailingNewlines, startPosition, endPosition); } - private LegacyReaderIterator newReaderIteratorForFiles( + private NativeReaderIterator newReaderIteratorForFiles( IOChannelFactory factory, Collection files) throws IOException { if (files.size() == 1) { return newReaderIteratorForFile(factory, files.iterator().next(), stripTrailingNewlines); @@ -178,7 +169,7 @@ private Collection expandedFilepattern() throws IOException { } @Override - public LegacyReaderIterator iterator() throws IOException { + public NativeReaderIterator iterator() throws IOException { IOChannelFactory factory = IOChannelUtils.getFactory(filepattern); Collection inputs = expandedFilepattern(); if (inputs.isEmpty()) { @@ -264,32 +255,34 @@ public TextFileMultiIterator( } @Override - protected LegacyReaderIterator open(String input) throws IOException { + protected NativeReaderIterator open(String input) throws IOException { return newReaderIteratorForFile(factory, input, stripTrailingNewlines); } } - class TextFileIterator extends LegacyReaderIterator { + class TextFileIterator extends NativeReaderIterator { private final CopyableSeekableByteChannel seeker; private final PushbackInputStream stream; private final OffsetRangeTracker rangeTracker; private final ProgressTracker progressTracker; + private final long startOffset; private long offset; - private ByteArrayOutputStream nextElement; + private T current; private ScanState state; TextFileIterator(CopyableSeekableByteChannel seeker, boolean stripTrailingNewlines, long startOffset, @Nullable Long endOffset, DecompressingStreamFactory compressionStreamFactory) throws IOException { + this.offset = Math.max(0, startOffset - 1); this.seeker = checkNotNull(seeker); - this.seeker.position(startOffset); + this.seeker.position(offset); InputStream inputStream = compressionStreamFactory.createInputStream(Channels.newInputStream(seeker)); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); this.stream = new PushbackInputStream(bufferedStream, BUF_SIZE); long stopOffset = (endOffset == null) ? OffsetRangeTracker.OFFSET_INFINITY : endOffset; + this.startOffset = startOffset; this.rangeTracker = new OffsetRangeTracker(startOffset, stopOffset); - this.offset = startOffset; this.progressTracker = checkNotNull(new ProgressTrackerGroup() { @Override protected void report(Integer lineLength) { @@ -312,6 +305,7 @@ protected void report(Integer lineLength) { * been reached. * @throws IOException if an I/O error occurs */ + @Nullable protected ByteArrayOutputStream readElement() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(BUF_SIZE); @@ -345,21 +339,38 @@ protected ByteArrayOutputStream readElement() throws IOException { } @Override - protected boolean hasNextImpl() throws IOException { + public boolean start() throws IOException { + if (this.startOffset > 0) { + long savedOffset = offset; + // Skip initial partial line. + if (readElement() == null) { + return false; + } else { + progressTracker.saw((int) (offset - savedOffset)); + } + } + return advance(); + } + + @Override + public boolean advance() throws IOException { long startOffset = offset; ByteArrayOutputStream element = readElement(); // As a side effect, updates "offset" if (element != null && rangeTracker.tryReturnRecordAt(true, startOffset)) { - nextElement = element; + current = CoderUtils.decodeFromByteArray(coder, element.toByteArray()); progressTracker.saw((int) (offset - startOffset)); } else { - nextElement = null; + current = null; } - return nextElement != null; + return current != null; } @Override - protected T nextImpl() throws IOException { - return CoderUtils.decodeFromByteArray(coder, nextElement.toByteArray()); + public T getCurrent() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + return current; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index b867c27434..1a9f7869c1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -52,7 +52,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Collections; @@ -68,7 +67,7 @@ /** * Iterates over all rows in a table. */ -public class BigQueryTableRowIterator implements Iterator, Closeable { +public class BigQueryTableRowIterator implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(BigQueryTableRowIterator.class); @Nullable private TableReference ref; @@ -76,7 +75,8 @@ public class BigQueryTableRowIterator implements Iterator, Closeable { @Nullable private TableSchema schema; private final Bigquery client; private String pageToken; - private Iterator rowIterator; + private Iterator iteratorOverCurrentBatch; + private TableRow current; // Set true when the final page is seen from the service. private boolean lastPage = false; @@ -129,17 +129,71 @@ public static BigQueryTableRowIterator fromQuery( MoreObjects.firstNonNull(flattenResults, Boolean.TRUE)); } - @Override - public boolean hasNext() { - try { - if (rowIterator == null || (!rowIterator.hasNext() && !lastPage)) { - readNext(); + /** + * Opens the table for read. + * @throws IOException on failure + */ + public void open() throws IOException, InterruptedException { + if (query != null) { + ref = executeQueryAndWaitForCompletion(); + } + // Get table schema. + Bigquery.Tables.Get get = + client.tables().get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); + + Table table = + executeWithBackOff( + get, + "Error opening BigQuery table %s of dataset %s : {}", + ref.getTableId(), + ref.getDatasetId()); + schema = table.getSchema(); + } + + public boolean advance() throws IOException, InterruptedException { + while (true) { + if (iteratorOverCurrentBatch != null && iteratorOverCurrentBatch.hasNext()) { + // Embed schema information into the raw row, so that values have an + // associated key. This matches how rows are read when using the + // DataflowPipelineRunner. + current = getTypedTableRow(schema.getFields(), iteratorOverCurrentBatch.next()); + return true; + } + if (lastPage) { + return false; + } + + Bigquery.Tabledata.List list = + client.tabledata().list(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); + if (pageToken != null) { + list.setPageToken(pageToken); + } + + TableDataList result = + executeWithBackOff( + list, + "Error reading from BigQuery table %s of dataset %s : {}", + ref.getTableId(), + ref.getDatasetId()); + + pageToken = result.getPageToken(); + iteratorOverCurrentBatch = + result.getRows() != null + ? result.getRows().iterator() + : Collections.emptyIterator(); + + // The server may return a page token indefinitely on a zero-length table. + if (pageToken == null || result.getTotalRows() != null && result.getTotalRows() == 0) { + lastPage = true; } - } catch (IOException | InterruptedException e) { - throw new RuntimeException(e); } + } - return rowIterator.hasNext(); + public TableRow getCurrent() { + if (current == null) { + throw new NoSuchElementException(); + } + return current; } /** @@ -310,23 +364,6 @@ private TableRow getTypedTableRow(List fields, Map T executeWithBackOff(AbstractGoogleClientRequest client, St return result; } - private void readNext() throws IOException, InterruptedException { - if (query != null && ref == null) { - ref = executeQueryAndWaitForCompletion(); - } - if (!isOpen()) { - open(); - } - - Bigquery.Tabledata.List list = - client.tabledata().list(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - if (pageToken != null) { - list.setPageToken(pageToken); - } - - TableDataList result = - executeWithBackOff(list, "Error reading from BigQuery table %s of dataset %s : {}", - ref.getTableId(), ref.getDatasetId()); - - pageToken = result.getPageToken(); - rowIterator = - result.getRows() != null - ? result.getRows().iterator() : Collections.emptyIterator(); - - // The server may return a page token indefinitely on a zero-length table. - if (pageToken == null || result.getTotalRows() != null && result.getTotalRows() == 0) { - lastPage = true; - } - } - @Override - public void close() throws IOException { + public void close() { // Prevent any further requests. lastPage = true; @@ -488,27 +496,9 @@ public void close() throws IOException { } deleteDataset(temporaryDatasetId); } - } catch (InterruptedException e) { - throw new IOException(e); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); } } - - private boolean isOpen() { - return schema != null; - } - - /** - * Opens the table for read. - * @throws IOException on failure - */ - private void open() throws IOException, InterruptedException { - // Get table schema. - Bigquery.Tables.Get get = - client.tables().get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - - Table table = executeWithBackOff(get, "Error opening BigQuery table %s of dataset %s : {}", - ref.getTableId(), ref.getDatasetId()); - schema = table.getSchema(); - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java index 326af02af8..4d48010647 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java @@ -19,6 +19,7 @@ import com.google.api.services.dataflow.model.Source; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import java.util.HashMap; @@ -63,7 +64,7 @@ public static List readElemsFromSource(PipelineOptions options, Source so NativeReader reader = (NativeReader) ReaderFactory.Registry.defaultRegistry().create(source, options, null, null, null); - return ReaderUtils.readElemsFromReader(reader); + return ReaderUtils.readAllFromReader(reader); } catch (Exception e) { throw new RuntimeException("Failed to read from source: " + source.toString(), e); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReaderUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReaderUtils.java deleted file mode 100644 index 290d9ddfef..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReaderUtils.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Utilities for working with {@link NativeReader} objects. - */ -public class ReaderUtils { - /** - * Reads all elements from the given {@link NativeReader}. - */ - public static List readElemsFromReader(NativeReader reader) { - List elems = new ArrayList<>(); - try (NativeReader.NativeReaderIterator it = reader.iterator()) { - for (boolean more = it.start(); more; more = it.advance()) { - elems.add(it.getCurrent()); - } - } catch (IOException e) { - throw new RuntimeException("Failed to read from reader: " + reader, e); - } - return elems; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index 1387224dde..a0f19012d3 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -66,6 +66,7 @@ import com.google.cloud.dataflow.sdk.runners.worker.DataflowApiUtils; import com.google.cloud.dataflow.sdk.runners.worker.ReaderCacheEntry; import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.runners.worker.StreamingModeExecutionContext; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; @@ -80,7 +81,6 @@ import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.ReaderUtils; import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; @@ -676,7 +676,7 @@ public void testReadUnboundedReader() throws Exception { Instant beforeReading = Instant.now(); int numReadOnThisIteration = 0; for (WindowedValue>> value : - ReaderUtils.readElemsFromReader(reader)) { + ReaderUtils.readAllFromReader(reader)) { assertEquals(KV.of(0, i), value.getValue().getValue()); assertArrayEquals( encodeToByteArray(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()), KV.of(0, i)), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java index eab3a68ba0..babd10a7fd 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java @@ -16,9 +16,9 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readAllFromReader; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readNItemsFromUnstartedReader; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readRemainingFromReader; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readNItemsFromUnstartedIterator; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readRemainingFromIterator; import com.google.cloud.dataflow.sdk.TestUtils; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; @@ -230,7 +230,7 @@ private void testRequestDynamicSplitInternal( List residualElements = new ArrayList<>(); try (AvroByteReader.AvroByteFileIterator iterator = reader.iterator()) { // Read n elements from the reader - primaryElements = readNItemsFromUnstartedReader(iterator, readBeforeSplit); + primaryElements = readNItemsFromUnstartedIterator(iterator, readBeforeSplit); // Request a split at the specified position DynamicSplitResult splitResult = @@ -247,7 +247,7 @@ private void testRequestDynamicSplitInternal( } // Finish reading from the original reader. - primaryElements.addAll(readRemainingFromReader(iterator, readBeforeSplit > 0)); + primaryElements.addAll(readRemainingFromIterator(iterator, readBeforeSplit > 0)); if (splitResult != null) { Long splitPosition = ReaderTestUtils.positionFromSplitResult(splitResult).getByteOffset(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java index 10474e711a..9f1a4eacc5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java @@ -16,7 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readAllFromReader; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; import com.google.cloud.dataflow.sdk.TestUtils; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java index 5ba037b3e8..bc56cf56cf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java @@ -17,11 +17,11 @@ package com.google.cloud.dataflow.sdk.runners.worker; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readAllFromReader; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readNItemsFromUnstartedReader; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readRemainingFromReader; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtFraction; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.windowedValuesToValues; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readNItemsFromUnstartedIterator; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readRemainingFromIterator; import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.isA; @@ -31,9 +31,7 @@ import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.DynamicSplitResult; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.Progress; @@ -171,9 +169,9 @@ private List readElems(String filename, @Nullable Long startOffset, double progressReported = 0; List actualElems = new ArrayList<>(); - try (NativeReader.LegacyReaderIterator> iterator = avroReader.iterator()) { - while (iterator.hasNext()) { - actualElems.add(iterator.next().getValue()); + try (AvroReader.AvroFileIterator iterator = avroReader.iterator()) { + for (boolean more = iterator.start(); more; more = iterator.advance()) { + actualElems.add(iterator.getCurrent().getValue()); double progress = 0.0; Progress readerProgress = iterator.getProgress(); if (readerProgress != null) { @@ -207,7 +205,7 @@ private void testRequestDynamicSplitInternal( try (AvroReader.AvroFileIterator iterator = reader.iterator()) { // Read n elements from the reader primaryElements = - windowedValuesToValues(readNItemsFromUnstartedReader(iterator, readBeforeSplit)); + windowedValuesToValues(readNItemsFromUnstartedIterator(iterator, readBeforeSplit)); // Request a split at the specified position DynamicSplitResult splitResult = @@ -225,7 +223,7 @@ private void testRequestDynamicSplitInternal( // Finish reading from the original reader. primaryElements.addAll( - windowedValuesToValues(readRemainingFromReader(iterator, readBeforeSplit > 0))); + windowedValuesToValues(readRemainingFromIterator(iterator, readBeforeSplit > 0))); if (splitResult != null) { Long splitPosition = positionFromSplitResult(splitResult).getByteOffset(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java index 9f005df0a0..e881913ed8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java @@ -16,8 +16,8 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readAllFromReader; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.windowedValuesToValues; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; import com.google.cloud.dataflow.sdk.TestUtils; import com.google.cloud.dataflow.sdk.coders.AvroCoder; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java index e30413c5a3..579bb6b1fb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java @@ -565,14 +565,15 @@ public void testReadQuery() throws Exception { BigQueryReader reader = BigQueryReader.fromQuery(QUERY, PROJECT_ID, bigQueryClient, true); BigQueryReader.BigQueryReaderIterator iterator = reader.iterator(); - assertTrue(iterator.hasNext()); - TableRow row = iterator.next().getValue(); + assertTrue(iterator.start()); + TableRow row = iterator.getCurrent().getValue(); assertEquals("Arthur", row.get("name")); assertEquals("42", row.get("integer")); assertNull(row.getF()); - row = iterator.next().getValue(); + assertTrue(iterator.advance()); + row = iterator.getCurrent().getValue(); assertEquals("Allison", row.get("name")); assertEquals("79", row.get("integer")); assertNull(row.getF()); @@ -764,9 +765,9 @@ public void testReadTable() throws Exception { bigQueryClient); BigQueryReader.BigQueryReaderIterator iterator = reader.iterator(); - assertTrue(iterator.hasNext()); + assertTrue(iterator.start()); - TableRow row = iterator.next().getValue(); + TableRow row = iterator.getCurrent().getValue(); assertEquals("Arthur", row.get("name")); assertEquals("42", row.get("integer")); @@ -782,7 +783,8 @@ public void testReadTable() throws Exception { assertTrue(((List) row.get("repeatedFloat")).isEmpty()); assertTrue(((List) row.get("repeatedRecord")).isEmpty()); - row = iterator.next().getValue(); + assertTrue(iterator.advance()); + row = iterator.getCurrent().getValue(); assertEquals("Allison", row.get("name")); assertEquals("79", row.get("integer")); @@ -807,7 +809,7 @@ public void testReadTable() throws Exception { assertEquals(false, nestedRecords.get(1).get("bool")); assertNull(nestedRecords.get(1).getF()); - assertFalse(iterator.hasNext()); + assertFalse(iterator.advance()); verifyTableGet(); verifyTabledataList(); @@ -898,12 +900,11 @@ public void testReadTableWithFieldF() throws Exception { .setProjectId(PROJECT_ID).setDatasetId(DATASET).setTableId(TABLE_WITH_FIELD_F); BigQueryReader reader = BigQueryReader.fromTable(tableRef, bigQueryClient); - BigQueryReader.BigQueryReaderIterator iterator = reader.iterator(); - assertTrue(iterator.hasNext()); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("BigQueryIO does not support records with columns named f"); + try (BigQueryReader.BigQueryReaderIterator iterator = reader.iterator()) { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("BigQueryIO does not support records with columns named f"); - iterator.next().getValue(); + iterator.start(); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java index ede98df746..59cfcfe0d8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java @@ -16,7 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readAllFromReader; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; import static com.google.cloud.dataflow.sdk.util.Structs.addList; import static com.google.cloud.dataflow.sdk.util.Structs.addLong; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java index 5f7323d159..5eebb84823 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java @@ -17,8 +17,8 @@ package com.google.cloud.dataflow.sdk.runners.worker; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.readAllFromReader; import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtConcatPosition; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java index a99cb98015..7ee710ac40 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java @@ -133,9 +133,11 @@ static void runTestRead(Iterable> expectedData, File tmpFile) reader.addObserver(observer); Iterator> expectedIterator = expectedData.iterator(); - try (NativeReader.LegacyReaderIterator> iterator = reader.iterator()) { - while (iterator.hasNext() && expectedIterator.hasNext()) { - KV actual = iterator.next(); + try (NativeReader.NativeReaderIterator> iterator = reader.iterator()) { + for (boolean more = iterator.start(); + more && expectedIterator.hasNext(); + more = iterator.advance()) { + KV actual = iterator.getCurrent(); KV expectedNext = expectedIterator.next(); assertArrayEquals(actual.getKey(), expectedNext.getKey()); assertArrayEquals(actual.getValue(), expectedNext.getValue()); @@ -144,15 +146,15 @@ static void runTestRead(Iterable> expectedData, File tmpFile) assertTrue(actual.getValue().length <= observer.getActualSizes().get(observer.getActualSizes().size() - 1)); } - if (iterator.hasNext()) { - fail("Read more elements then expected, did not expect: " + iterator.next()); + if (iterator.advance()) { + fail("Read more elements then expected, did not expect: " + iterator.getCurrent()); } else if (expectedIterator.hasNext()) { fail("Read less elements then expected, expected: " + expectedIterator.next()); } // Verify that we see a {@link NoSuchElementException} if we attempt to go further. try { - iterator.next(); + iterator.getCurrent(); fail("Expected a NoSuchElementException to have been thrown."); } catch (NoSuchElementException expected) { } @@ -188,8 +190,8 @@ static void runTestReadRandomOrder(Iterable> elements, File t assertArrayEquals(actual.getValue(), expectedNext.getValue()); // Verify that the observer saw at least as many bytes as the size of the value. - assertTrue(actual.getValue().length - <= observer.getActualSizes().get(observer.getActualSizes().size() - 1)); + List actualSizes = observer.getActualSizes(); + assertTrue(actual.getValue().length <= actualSizes.get(actualSizes.size() - 1)); } Iterator> missingIterator = evenValues.iterator(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java index 7b4ce9be51..11a1faddff 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java @@ -27,7 +27,6 @@ import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.NativeReaderIterator; -import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -147,46 +146,4 @@ public static List windowedValuesToValues(Collection> wi return res; } - /** - * Creates a {@link NativeReaderIterator} from the given {@link NativeReader} and reads it - * to the end. - * - * @param reader {@link NativeReader} to read from - * @throws IOException - */ - public static List readAllFromReader(NativeReader reader) throws IOException { - try (NativeReaderIterator iterator = reader.iterator()) { - return readRemainingFromReader(iterator, false); - } - } - - /** - * Read elements from a {@link NativeReader.NativeReaderIterator} until either the reader is - * exhausted, or n elements are read. - */ - public static List readNItemsFromReader( - NativeReader.NativeReaderIterator reader, int n, boolean started) throws IOException { - List res = new ArrayList<>(); - for (int i = 0; i < n; i++) { - if (!((i == 0 && !started) ? reader.start() : reader.advance())) { - break; - } - res.add(reader.getCurrent()); - } - return res; - } - - /** - * Read elements from a {@link NativeReader.NativeReaderIterator} until either the reader is - * exhausted, or n elements are read. - */ - public static List readNItemsFromUnstartedReader( - NativeReader.NativeReaderIterator reader, int n) throws IOException { - return readNItemsFromReader(reader, n, false); - } - - public static List readRemainingFromReader( - NativeReader.NativeReaderIterator reader, boolean started) throws IOException { - return readNItemsFromReader(reader, Integer.MAX_VALUE, started); - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java index ef559e3d30..59f494241d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java @@ -23,7 +23,6 @@ import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -44,8 +43,8 @@ import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.LegacyReaderIterator; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.NativeReaderIterator; +import com.google.common.base.Joiner; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.junit.Rule; @@ -180,21 +179,19 @@ public void testUnstrippedNewlinesAtEndOfReadBuffer() throws Exception { @Test public void testStartPosition() throws Exception { File tmpFile = initTestFile(); + assertEquals(40, tmpFile.length()); { TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 13L, null, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); - - try (LegacyReaderIterator iterator = textReader.iterator()) { - assertEquals("\r\n", iterator.next()); - assertEquals("", iterator.next()); - assertFalse(iterator.hasNext()); - // The first '1' in the array represents the reading of '\n' between first and - // second line, to confirm that we are reading from the beginning of a record. - assertEquals(Arrays.asList(1, 15, 12), observer.getActualSizes()); - } + assertEquals( + Arrays.asList("\r\n", ""), + ReaderUtils.readAllFromReader(textReader)); + // The first '1' in the array represents the reading of '\n' between first and + // second line, to confirm that we are reading from the beginning of a record. + assertEquals(Arrays.asList(1, 15, 12), observer.getActualSizes()); } { @@ -202,28 +199,57 @@ public void testStartPosition() throws Exception { new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); + assertEquals(Arrays.asList(""), ReaderUtils.readAllFromReader(textReader)); + // The first '5' in the array represents the reading of a portion of the second + // line, which had to be read to find the beginning of the third line. + assertEquals(Arrays.asList(5, 12), observer.getActualSizes()); + } - try (LegacyReaderIterator iterator = textReader.iterator()) { - assertEquals("", iterator.next()); - assertFalse(iterator.hasNext()); - // The first '5' in the array represents the reading of a portion of the second - // line, which had to be read to find the beginning of the third line. - assertEquals(Arrays.asList(5, 12), observer.getActualSizes()); - } + { + TextReader textReader = + new TextReader<>( + tmpFile.getPath(), + false, + 32L, + null, + new WholeLineVerifyingCoder(), + TextIO.CompressionType.UNCOMPRESSED); + ExecutorTestUtils.TestReaderObserver observer = + new ExecutorTestUtils.TestReaderObserver(textReader); + assertEquals(Arrays.asList(), ReaderUtils.readAllFromReader(textReader)); + assertEquals(Arrays.asList(9), observer.getActualSizes()); } { - TextReader textReader = new TextReader<>(tmpFile.getPath(), true, 0L, 22L, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); + TextReader textReader = + new TextReader<>( + tmpFile.getPath(), + false, + 41L, + null, + new WholeLineVerifyingCoder(), + TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); + assertEquals(Arrays.asList(), ReaderUtils.readAllFromReader(textReader)); + assertEquals(Arrays.asList(), observer.getActualSizes()); + } - try (LegacyReaderIterator iterator = textReader.iterator()) { - assertEquals("", iterator.next()); - assertEquals("", iterator.next()); - assertFalse(iterator.hasNext()); - assertEquals(Arrays.asList(13, 15), observer.getActualSizes()); - } + { + TextReader textReader = + new TextReader<>( + tmpFile.getPath(), + true, + 0L, + 22L, + new WholeLineVerifyingCoder(), + TextIO.CompressionType.UNCOMPRESSED); + ExecutorTestUtils.TestReaderObserver observer = + new ExecutorTestUtils.TestReaderObserver(textReader); + assertEquals( + Arrays.asList("", ""), + ReaderUtils.readAllFromReader(textReader)); + assertEquals(Arrays.asList(13, 15), observer.getActualSizes()); } { @@ -231,14 +257,10 @@ public void testStartPosition() throws Exception { new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); - - try (LegacyReaderIterator iterator = textReader.iterator()) { - assertEquals("", iterator.next()); - assertFalse(iterator.hasNext()); - // The first '13' in the array represents the reading of the entire first - // line, which had to be read to find the beginning of the second line. - assertEquals(Arrays.asList(13, 15), observer.getActualSizes()); - } + assertEquals(Arrays.asList(""), ReaderUtils.readAllFromReader(textReader)); + // The first '13' in the array represents the reading of the entire first + // line, which had to be read to find the beginning of the second line. + assertEquals(Arrays.asList(13, 15), observer.getActualSizes()); } } @@ -260,12 +282,8 @@ public void testUtf8Handling() throws Exception { StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); - - try (LegacyReaderIterator iterator = textReader.iterator()) { - assertArrayEquals("€".getBytes("UTF-8"), iterator.next().getBytes("UTF-8")); - assertFalse(iterator.hasNext()); - assertEquals(Arrays.asList(4), observer.getActualSizes()); - } + assertEquals(Arrays.asList("€"), ReaderUtils.readAllFromReader(textReader)); + assertEquals(Arrays.asList(4), observer.getActualSizes()); } { @@ -275,14 +293,10 @@ public void testUtf8Handling() throws Exception { StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); - - try (LegacyReaderIterator iterator = textReader.iterator()) { - assertArrayEquals("¢".getBytes("UTF-8"), iterator.next().getBytes("UTF-8")); - assertFalse(iterator.hasNext()); - // The first '3' in the array represents the reading of a portion of the first - // line, which had to be read to find the beginning of the second line. - assertEquals(Arrays.asList(3, 3), observer.getActualSizes()); - } + assertEquals(Arrays.asList("¢"), ReaderUtils.readAllFromReader(textReader)); + // The first '3' in the array represents the reading of a portion of the first + // line, which had to be read to find the beginning of the second line. + assertEquals(Arrays.asList(3, 3), observer.getActualSizes()); } } @@ -302,14 +316,7 @@ private void testNewlineHandling(String separator, boolean stripNewlines) throws StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); - - List actual = new ArrayList<>(); - try (LegacyReaderIterator iterator = textReader.iterator()) { - while (iterator.hasNext()) { - actual.add(iterator.next()); - } - } - + List actual = ReaderUtils.readAllFromReader(textReader); if (stripNewlines) { assertEquals(expected, actual); } else { @@ -337,13 +344,7 @@ private void testStringPayload(String[] lines, String separator, boolean stripNe TextReader textReader = new TextReader<>(tmpFile.getPath(), stripNewlines, null, null, StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); - List actual = new ArrayList<>(); - try (LegacyReaderIterator iterator = textReader.iterator()) { - while (iterator.hasNext()) { - actual.add(iterator.next()); - } - } - assertEquals(expected, actual); + assertEquals(expected, ReaderUtils.readAllFromReader(textReader)); } @Test @@ -364,15 +365,7 @@ public void testNonStringCoders() throws Exception { TextualIntegerCoder.of(), TextIO.CompressionType.UNCOMPRESSED); ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader); - - List actual = new ArrayList<>(); - try (LegacyReaderIterator iterator = textReader.iterator()) { - while (iterator.hasNext()) { - actual.add(iterator.next()); - } - } - - assertEquals(expected, actual); + assertEquals(expected, ReaderUtils.readAllFromReader(textReader)); assertEquals(expectedSizes, observer.getActualSizes()); } @@ -382,22 +375,22 @@ public void testGetProgressNoEndOffset() throws Exception { TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 0L, null, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - try (LegacyReaderIterator iterator = textReader.iterator()) { + try (NativeReaderIterator iterator = textReader.iterator()) { ApproximateReportedProgress progress = readerProgressToCloudProgress(iterator.getProgress()); assertEquals(0L, progress.getPosition().getByteOffset().longValue()); - iterator.next(); + assertTrue(iterator.start()); progress = readerProgressToCloudProgress(iterator.getProgress()); assertEquals(13L, progress.getPosition().getByteOffset().longValue()); - iterator.next(); + assertTrue(iterator.advance()); progress = readerProgressToCloudProgress(iterator.getProgress()); assertEquals(28L, progress.getPosition().getByteOffset().longValue()); // Since end position is not specified, percentComplete should be null. assertNull(progress.getFractionConsumed()); - iterator.next(); + assertTrue(iterator.advance()); progress = readerProgressToCloudProgress(iterator.getProgress()); assertEquals(40L, progress.getPosition().getByteOffset().longValue()); - assertFalse(iterator.hasNext()); + assertFalse(iterator.advance()); } } @@ -407,17 +400,17 @@ public void testGetProgressWithEndOffset() throws Exception { TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 0L, 40L, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - try (LegacyReaderIterator iterator = textReader.iterator()) { - iterator.next(); + try (NativeReaderIterator iterator = textReader.iterator()) { + assertTrue(iterator.start()); ApproximateReportedProgress progress = readerProgressToCloudProgress(iterator.getProgress()); // Returned a record that starts at position 0 of 40 - 1/40 fraction consumed. assertEquals(1.0 / 40, progress.getFractionConsumed(), 1e-6); - iterator.next(); - iterator.next(); + assertTrue(iterator.advance()); + assertTrue(iterator.advance()); progress = readerProgressToCloudProgress(iterator.getProgress()); // Returned a record that starts at position 28 - 29/40 consumed. assertEquals(1.0 * 29 / 40, progress.getFractionConsumed(), 1e-6); - assertFalse(iterator.hasNext()); + assertFalse(iterator.advance()); } } @@ -434,10 +427,9 @@ public void testUpdateStopPosition() throws Exception { tmpFile.getPath(), false, 0L, fileSize, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { + try (NativeReaderIterator iterator = textReader.iterator()) { // Poke the iterator so we can test dynamic splitting. - assertTrue(iterator.hasNext()); + assertTrue(iterator.start()); assertNull(iterator.requestDynamicSplit(splitRequestAtPosition(new Position()))); } @@ -454,7 +446,7 @@ public void testUpdateStopPosition() throws Exception { try (TextReader.TextFileIterator iterator = (TextReader.TextFileIterator) textReader.iterator()) { // Poke the iterator so we can test dynamic splitting. - assertTrue(iterator.hasNext()); + assertTrue(iterator.start()); assertEquals(fileSize, iterator.getEndOffset()); assertEquals( @@ -462,9 +454,10 @@ public void testUpdateStopPosition() throws Exception { positionFromSplitResult(iterator.requestDynamicSplit(splitRequestAtByteOffset(stop))) .getByteOffset()); assertEquals(stop, iterator.getEndOffset()); - assertEquals(fileContent[0], iterator.next()); - assertEquals(fileContent[1], iterator.next()); - assertFalse(iterator.hasNext()); + assertEquals(fileContent[0], iterator.getCurrent()); + assertTrue(iterator.advance()); + assertEquals(fileContent[1], iterator.getCurrent()); + assertFalse(iterator.advance()); assertEquals( Arrays.asList(fileContent[0].length(), fileContent[1].length()), observer.getActualSizes()); @@ -481,7 +474,7 @@ public void testUpdateStopPosition() throws Exception { try (TextReader.TextFileIterator iterator = (TextReader.TextFileIterator) textReader.iterator()) { // Poke the iterator so we can test dynamic splitting. - assertTrue(iterator.hasNext()); + assertTrue(iterator.start()); // Trying to split at 0 or 1 will fail. assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0))); @@ -498,9 +491,10 @@ public void testUpdateStopPosition() throws Exception { positionFromSplitResult(iterator.requestDynamicSplit(splitRequestAtFraction(splitPos))) .getByteOffset()); assertEquals(stopPosition, iterator.getEndOffset()); - assertEquals(fileContent[0], iterator.next()); - assertEquals(fileContent[1], iterator.next()); - assertFalse(iterator.hasNext()); + assertEquals(fileContent[0], iterator.getCurrent()); + assertTrue(iterator.advance()); + assertEquals(fileContent[1], iterator.getCurrent()); + assertFalse(iterator.advance()); assertEquals( Arrays.asList(fileContent[0].length(), fileContent[1].length()), observer.getActualSizes()); @@ -517,21 +511,23 @@ public void testUpdateStopPosition() throws Exception { try (TextReader.TextFileIterator iterator = (TextReader.TextFileIterator) textReader.iterator()) { - assertEquals(fileContent[0], iterator.next()); - assertEquals(fileContent[1], iterator.next()); + assertTrue(iterator.start()); + assertEquals(fileContent[0], iterator.getCurrent()); + assertTrue(iterator.advance()); + assertEquals(fileContent[1], iterator.getCurrent()); assertThat( readerProgressToCloudProgress(iterator.getProgress()).getPosition().getByteOffset(), greaterThan(stop)); - assertTrue(iterator.hasNext()); + assertTrue(iterator.advance()); // The iterator just promised to return the next record, which is beyond "stop". assertNull(iterator.requestDynamicSplit(splitRequestAtByteOffset(stop))); assertEquals(fileSize, iterator.getEndOffset()); - assertTrue(iterator.hasNext()); - assertEquals(fileContent[2], iterator.next()); + assertEquals(fileContent[2], iterator.getCurrent()); assertEquals( Arrays.asList( fileContent[0].length(), fileContent[1].length(), fileContent[2].length()), observer.getActualSizes()); + assertFalse(iterator.advance()); } } @@ -544,11 +540,11 @@ public void testUpdateStopPosition() throws Exception { try (TextReader.TextFileIterator iterator = (TextReader.TextFileIterator) textReader.iterator()) { - assertTrue(iterator.hasNext()); - assertEquals(fileContent[0], iterator.next()); + assertTrue(iterator.start()); + assertEquals(fileContent[0], iterator.getCurrent()); assertNull(iterator.requestDynamicSplit(splitRequestAtByteOffset(stop))); assertEquals(end, iterator.getEndOffset()); - assertFalse(iterator.hasNext()); + assertFalse(iterator.advance()); assertEquals(Arrays.asList(fileContent[0].length()), observer.getActualSizes()); } } @@ -579,45 +575,21 @@ private void stopPositionTestInternal( Long startOffset, Long endOffset, Long stopOffset, File tmpFile) throws Exception { String readWithoutSplit; String readWithSplit1, readWithSplit2; - StringBuilder accumulatedRead = new StringBuilder(); // Read from source without split attempts. TextReader textReader = new TextReader<>(tmpFile.getPath(), false, startOffset, endOffset, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { - while (iterator.hasNext()) { - accumulatedRead.append(iterator.next()); - } - readWithoutSplit = accumulatedRead.toString(); - } + readWithoutSplit = Joiner.on("").join(ReaderUtils.readAllFromReader(textReader)); // Read the first half of the split. textReader = new TextReader<>(tmpFile.getPath(), false, startOffset, stopOffset, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - accumulatedRead = new StringBuilder(); - - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { - while (iterator.hasNext()) { - accumulatedRead.append(iterator.next()); - } - readWithSplit1 = accumulatedRead.toString(); - } + readWithSplit1 = Joiner.on("").join(ReaderUtils.readAllFromReader(textReader)); // Read the second half of the split. textReader = new TextReader<>(tmpFile.getPath(), false, stopOffset, endOffset, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - accumulatedRead = new StringBuilder(); - - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { - while (iterator.hasNext()) { - accumulatedRead.append(iterator.next()); - } - readWithSplit2 = accumulatedRead.toString(); - } + readWithSplit2 = Joiner.on("").join(ReaderUtils.readAllFromReader(textReader)); assertEquals(readWithoutSplit, readWithSplit1 + readWithSplit2); } @@ -664,14 +636,7 @@ private void testCompressionTypeHelper(String[] lines, String filename, TextReader textReader = new TextReader<>( tmpFile.getPath(), true, null, null, new WholeLineVerifyingCoder(), inputCompressionType); - - List actual = new ArrayList<>(); - try (LegacyReaderIterator iterator = textReader.iterator()) { - while (iterator.hasNext()) { - actual.add(iterator.next()); - } - } - assertEquals(expected, actual); + assertEquals(expected, ReaderUtils.readAllFromReader(textReader)); tmpFile.delete(); } @@ -716,14 +681,7 @@ public void testCompressionTypeFileGlob() throws IOException { TextReader textReader = new TextReader<>(path, true, null, null, new WholeLineVerifyingCoder(), CompressionType.AUTO); - - List actual = new ArrayList<>(); - try (LegacyReaderIterator iterator = textReader.iterator()) { - while (iterator.hasNext()) { - actual.add(iterator.next()); - } - } - assertThat(actual, containsInAnyOrder(expected.toArray())); + assertThat(ReaderUtils.readAllFromReader(textReader), containsInAnyOrder(expected.toArray())); for (File file : files) { file.delete(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java index 0de53ef679..7c09fcc51d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java @@ -85,7 +85,7 @@ private void testForMessageBundleCounts(int... messageBundleCounts) throws IOExc try (TestWindmillReaderIterator iter = new TestWindmillReaderIterator(workItem)) { List actual = ReaderTestUtils.windowedValuesToValues( - ReaderTestUtils.readRemainingFromReader(iter, false)); + ReaderUtils.readRemainingFromIterator(iter, false)); assertFalse(iter.advance()); List expected = new ArrayList<>(); for (int i = 0; i < numTotalMessages; ++i) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java index b7903ca26c..b82e62595c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -143,7 +143,7 @@ private TableDataList rawDataList(TableRow... rows) { * table are both cleaned up. */ @Test - public void testReadFromQuery() throws IOException { + public void testReadFromQuery() throws IOException, InterruptedException { // Mock job inserting. Job insertedJob = new Job().setJobReference(new JobReference()); when(mockJobsInsert.execute()).thenReturn(insertedJob); @@ -170,15 +170,16 @@ public void testReadFromQuery() throws IOException { String query = "SELECT name, count from table"; try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null)) { - assertTrue(iterator.hasNext()); - TableRow row = iterator.next(); + iterator.open(); + assertTrue(iterator.advance()); + TableRow row = iterator.getCurrent(); assertTrue(row.containsKey("name")); assertTrue(row.containsKey("answer")); assertEquals("Arthur", row.get("name")); assertEquals(42, row.get("answer")); - assertFalse(iterator.hasNext()); + assertFalse(iterator.advance()); } // Temp dataset created and later deleted. @@ -228,7 +229,7 @@ public void testQueryFailed() throws IOException { try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null)) { try { - iterator.hasNext(); + iterator.open(); fail(); } catch (Exception expected) { // Verify message explains cause and reports the query. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java index 3589123315..99dad0f541 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java @@ -40,9 +40,7 @@ import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterators; import org.hamcrest.Matchers; import org.junit.After; @@ -188,7 +186,7 @@ private Table basicTableSchemaWithTime() { } @Test - public void testReadWithTime() throws IOException { + public void testReadWithTime() throws IOException, InterruptedException { // The BigQuery JSON API returns timestamps in the following format: floating-point seconds // since epoch (UTC) with microsecond precision. Test that we faithfully preserve a set of // known values. @@ -218,8 +216,15 @@ public void testReadWithTime() throws IOException { "2016-01-06 06:38:11.123456 UTC"); // Download the rows, verify the interactions. - List rows = ImmutableList.copyOf(BigQueryTableRowIterator.fromTable( - BigQueryIO.parseTableSpec("project:dataset.table"), mockClient)); + List rows = new ArrayList<>(); + try (BigQueryTableRowIterator iterator = + BigQueryTableRowIterator.fromTable( + BigQueryIO.parseTableSpec("project:dataset.table"), mockClient)) { + iterator.open(); + while (iterator.advance()) { + rows.add(iterator.getCurrent()); + } + } verifyTableGet(); verifyTabledataList(); @@ -246,7 +251,7 @@ private TableDataList rawDataList(TableRow...rows) { } @Test - public void testRead() throws IOException { + public void testRead() throws IOException, InterruptedException { onTableGet(basicTableSchema()); TableDataList dataList = rawDataList(rawRow("Arthur", 42)); @@ -255,16 +260,16 @@ public void testRead() throws IOException { try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromTable( BigQueryIO.parseTableSpec("project:dataset.table"), mockClient)) { - - Assert.assertTrue(iterator.hasNext()); - TableRow row = iterator.next(); + iterator.open(); + Assert.assertTrue(iterator.advance()); + TableRow row = iterator.getCurrent(); Assert.assertTrue(row.containsKey("name")); Assert.assertTrue(row.containsKey("answer")); Assert.assertEquals("Arthur", row.get("name")); Assert.assertEquals(42, row.get("answer")); - Assert.assertFalse(iterator.hasNext()); + Assert.assertFalse(iterator.advance()); verifyTableGet(); verifyTabledataList(); @@ -272,7 +277,7 @@ public void testRead() throws IOException { } @Test - public void testReadEmpty() throws IOException { + public void testReadEmpty() throws IOException, InterruptedException { onTableGet(basicTableSchema()); // BigQuery may respond with a page token for an empty table, ensure we @@ -285,8 +290,9 @@ public void testReadEmpty() throws IOException { try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromTable( BigQueryIO.parseTableSpec("project:dataset.table"), mockClient)) { + iterator.open(); - Assert.assertFalse(iterator.hasNext()); + Assert.assertFalse(iterator.advance()); verifyTableGet(); verifyTabledataList(); @@ -294,7 +300,7 @@ public void testReadEmpty() throws IOException { } @Test - public void testReadMultiPage() throws IOException { + public void testReadMultiPage() throws IOException, InterruptedException { onTableGet(basicTableSchema()); TableDataList page1 = rawDataList(rawRow("Row1", 1)) @@ -313,15 +319,12 @@ public void testReadMultiPage() throws IOException { try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromTable( BigQueryIO.parseTableSpec("project:dataset.table"), mockClient)) { + iterator.open(); List names = new LinkedList<>(); - Iterators.addAll(names, - Iterators.transform(iterator, new Function(){ - @Override - public String apply(TableRow input) { - return (String) input.get("name"); - } - })); + while (iterator.advance()) { + names.add((String) iterator.getCurrent().get("name")); + } Assert.assertThat(names, Matchers.hasItems("Row1", "Row2")); @@ -333,8 +336,8 @@ public String apply(TableRow input) { } @Test - public void testReadOpenFailure() throws IOException { - thrown.expect(RuntimeException.class); + public void testReadOpenFailure() throws IOException, InterruptedException { + thrown.expect(IOException.class); when(mockClient.tables()) .thenReturn(mockTables); @@ -347,7 +350,7 @@ public void testReadOpenFailure() throws IOException { BigQueryIO.parseTableSpec("project:dataset.table"), mockClient)) { try { - Assert.assertFalse(iterator.hasNext()); // throws. + iterator.open(); // throws. } finally { verifyTableGet(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java index 2bbdf6b61c..0b8c48b3cf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java @@ -16,10 +16,13 @@ package com.google.cloud.dataflow.sdk.util; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; + import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.runners.worker.TextReader; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import org.junit.Assert; import org.junit.Rule; @@ -31,8 +34,6 @@ import java.io.File; import java.io.FileOutputStream; import java.util.Collection; -import java.util.Set; -import java.util.TreeSet; /** * Tests for IOFactory. @@ -81,18 +82,6 @@ public void testMultiFileRead() throws Exception { tmpFolder.getRoot() + "/file*", true /* strip newlines */, null, null, StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); - Set records = new TreeSet<>(); - try (NativeReader.LegacyReaderIterator iterator = reader.iterator()) { - while (iterator.hasNext()) { - records.add(iterator.next()); - } - } - - Assert.assertEquals(records.toString(), 5, records.size()); - Assert.assertTrue(records.contains("1")); - Assert.assertTrue(records.contains("2")); - Assert.assertTrue(records.contains("3")); - Assert.assertTrue(records.contains("4")); - Assert.assertTrue(records.contains("5")); + assertThat(ReaderUtils.readAllFromReader(reader), containsInAnyOrder("1", "2", "3", "4", "5")); } } From 579c8f3e7a79008f312b43712ff7d05f9951a108 Mon Sep 17 00:00:00 2001 From: sgmc Date: Tue, 2 Feb 2016 08:07:49 -0800 Subject: [PATCH 063/751] Add support to export BigQuery files in Avro format ----Release Notes---- When activated, greatly increases the efficiency of the BigQuery source by using Avro instead of JSON as an export format. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113637797 --- .../runners/worker/BigQueryAvroReader.java | 160 ++++++++++++++ .../worker/BigQueryAvroReaderFactory.java | 68 ++++++ .../sdk/runners/worker/ReaderFactory.java | 1 + .../cloud/dataflow/sdk/util/AvroUtils.java | 200 ++++++++++++++++++ .../sdk/util/BigQueryTableRowIterator.java | 37 +--- .../dataflow/sdk/util/PropertyNames.java | 2 + .../dataflow/sdk/util/AvroUtilsTest.java | 129 +++++++---- 7 files changed, 520 insertions(+), 77 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java new file mode 100644 index 0000000000..a7ad24b3da --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; +import static com.google.common.base.MoreObjects.firstNonNull; + +import com.google.api.services.bigquery.model.TableRow; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.api.services.dataflow.model.ApproximateReportedProgress; +import com.google.api.services.dataflow.model.ApproximateSplitRequest; +import com.google.cloud.dataflow.sdk.io.AvroSource; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.OffsetBasedSource; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.util.AvroUtils; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; + +import org.apache.avro.Schema; +import org.apache.avro.Schema.Parser; +import org.apache.avro.generic.GenericRecord; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +import javax.annotation.Nullable; + +/** + * A reader for Avro files exported by BigQuery, which converts them to {@link TableRow} records. + */ +public class BigQueryAvroReader extends NativeReader> { + private static final Logger LOG = LoggerFactory.getLogger(BigQueryAvroReader.class); + + @Nullable + final Long startPosition; + @Nullable + final Long endPosition; + final String filename; + final AvroSource avroSource; + final TableSchema tableSchema; + final PipelineOptions options; + + public BigQueryAvroReader( + String filename, + @Nullable Long startPosition, + @Nullable Long endPosition, + TableSchema schema, + @Nullable PipelineOptions options) + throws IOException { + this.filename = filename; + this.startPosition = startPosition; + this.endPosition = endPosition; + Schema recordSchema = + new Parser().parse(AvroUtils.readMetadataFromFile(filename).getSchemaString()); + this.tableSchema = schema; + this.options = options; + this.avroSource = AvroSource.from(filename).withSchema(recordSchema); + } + + @Override + public BigQueryAvroFileIterator iterator() throws IOException { + Long endPosition = firstNonNull(this.endPosition, Long.MAX_VALUE); + Long startPosition = firstNonNull(this.startPosition, 0L); + BoundedSource.BoundedReader reader; + if (startPosition == 0 && endPosition == Long.MAX_VALUE) { + // Read entire file (or collection of files). + reader = avroSource.createReader(options); + } else { + // Read a subrange of file. + reader = avroSource.createForSubrangeOfFile(filename, startPosition, endPosition) + .createReader(options); + } + return new BigQueryAvroFileIterator((AvroSource.AvroReader) reader); + } + + class BigQueryAvroFileIterator extends LegacyReaderIterator> { + final AvroSource.AvroReader reader; + boolean hasStarted = false; + long blockOffset = -1; + + public BigQueryAvroFileIterator(AvroSource.AvroReader reader) { + this.reader = reader; + } + + @Override + protected WindowedValue nextImpl() throws IOException { + GenericRecord next = reader.getCurrent(); + // Coarse-grained reporting of input bytes consumed. + // After completing reading a block, the block offset changes. + long currentOffset = reader.getCurrentBlockOffset(); + if (currentOffset != blockOffset) { + notifyElementRead(reader.getCurrentBlockSize()); + blockOffset = currentOffset; + } + return WindowedValue.valueInGlobalWindow( + AvroUtils.convertGenericRecordToTableRow(next, tableSchema)); + } + + @Override + protected boolean hasNextImpl() throws IOException { + if (!hasStarted) { + hasStarted = true; + return reader.start(); + } + return reader.advance(); + } + + @Override + public Progress getProgress() { + Double readerProgress = reader.getFractionConsumed(); + if (readerProgress == null) { + return null; + } + ApproximateReportedProgress progress = new ApproximateReportedProgress(); + progress.setFractionConsumed(readerProgress); + return cloudProgressToReaderProgress(progress); + } + + @Override + public void close() throws IOException { + reader.close(); + } + + @Override + public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { + ApproximateSplitRequest splitProgress = + SourceTranslationUtils.splitRequestToApproximateSplitRequest(splitRequest); + double splitAtFraction = splitProgress.getFractionConsumed(); + LOG.info("Received request for dynamic split at {}", splitAtFraction); + OffsetBasedSource residual = reader.splitAtFraction(splitAtFraction); + if (residual == null) { + LOG.info("Rejected split request for split at {}", splitAtFraction); + return null; + } + com.google.api.services.dataflow.model.Position acceptedPosition = + new com.google.api.services.dataflow.model.Position(); + acceptedPosition.setByteOffset(residual.getStartOffset()); + LOG.info("Accepted split for position {} which resulted in a new source with byte offset {}", + splitAtFraction, residual.getStartOffset()); + return new DynamicSplitResultWithPosition( + SourceTranslationUtils.cloudPositionToReaderPosition(acceptedPosition)); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java new file mode 100644 index 0000000000..9ab6534049 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import static com.google.cloud.dataflow.sdk.util.Structs.getLong; +import static com.google.cloud.dataflow.sdk.util.Structs.getString; +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; + +import java.io.IOException; + +import javax.annotation.Nullable; + +/** + * Creates an AvroReader specifically for the output of a BigQuery export job. + */ +public class BigQueryAvroReaderFactory implements ReaderFactory { + + public BigQueryAvroReaderFactory() {} + + @Override + public NativeReader create( + CloudObject spec, + @Nullable Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator, + @Nullable String operationName) + throws Exception { + return createTyped(spec, options); + } + + private static TableSchema parseTableSchema(String schemaStr) throws IOException { + checkArgument(!schemaStr.isEmpty(), "Provided BigQuery schema is empty"); + return JacksonFactory.getDefaultInstance().fromString(schemaStr, TableSchema.class); + } + + NativeReader createTyped(CloudObject spec, PipelineOptions options) throws Exception { + String filename = getString(spec, PropertyNames.FILENAME); + Long startOffset = getLong(spec, PropertyNames.START_OFFSET, null); + Long endOffset = getLong(spec, PropertyNames.END_OFFSET, null); + TableSchema bqSchema = parseTableSchema(getString(spec, PropertyNames.BIGQUERY_EXPORT_SCHEMA)); + return new BigQueryAvroReader(filename, startOffset, endOffset, bqSchema, options); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java index d55258b681..5ea2490475 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java @@ -68,6 +68,7 @@ public static Registry defaultRegistry() { factories.put("TextSource", TextReaderFactory.getInstance()); factories.put("AvroSource", new AvroReaderFactory()); + factories.put("BigQueryAvroSource", new BigQueryAvroReaderFactory()); factories.put("UngroupedShuffleSource", new UngroupedShuffleReaderFactory()); factories.put("PartitioningShuffleSource", new PartitioningShuffleReaderFactory()); factories.put("GroupingShuffleSource", new GroupingShuffleReaderFactory()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java index b50fe8a780..335e529873 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java @@ -16,15 +16,33 @@ package com.google.cloud.dataflow.sdk.util; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Verify.verify; + +import com.google.api.services.bigquery.model.TableFieldSchema; +import com.google.api.services.bigquery.model.TableRow; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +import org.apache.avro.Schema; +import org.apache.avro.Schema.Field; +import org.apache.avro.Schema.Type; import org.apache.avro.file.DataFileConstants; +import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.BinaryDecoder; import org.apache.avro.io.DecoderFactory; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.util.Arrays; +import java.util.List; + +import javax.annotation.Nullable; /** * A set of utilities for working with Avro files. @@ -134,4 +152,186 @@ public static AvroMetadata readMetadataFromFile(String fileName) throws IOExcept } return new AvroMetadata(syncMarker, codec, schemaString); } + + /** + * Formats BigQuery seconds-since-epoch into String matching JSON export. Thread-safe and + * immutable. + */ + private static final DateTimeFormatter DATE_AND_SECONDS_FORMATTER = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC(); + // Package private for BigQueryTableRowIterator to use. + static String formatTimestamp(String timestamp) { + // timestamp is in "seconds since epoch" format, with scientific notation. + // e.g., "1.45206229112345E9" to mean "2016-01-06 06:38:11.123456 UTC". + // Separate into seconds and microseconds. + double timestampDoubleMicros = Double.parseDouble(timestamp) * 1000000; + long timestampMicros = (long) timestampDoubleMicros; + long seconds = timestampMicros / 1000000; + int micros = (int) (timestampMicros % 1000000); + String dayAndTime = DATE_AND_SECONDS_FORMATTER.print(seconds * 1000); + + // No sub-second component. + if (micros == 0) { + return String.format("%s UTC", dayAndTime); + } + + // Sub-second component. + int digits = 6; + int subsecond = micros; + while (subsecond % 10 == 0) { + digits--; + subsecond /= 10; + } + String formatString = String.format("%%0%dd", digits); + String fractionalSeconds = String.format(formatString, subsecond); + return String.format("%s.%s UTC", dayAndTime, fractionalSeconds); + } + + /** + * Utility function to convert from an Avro {@link GenericRecord} to a BigQuery {@link TableRow}. + * + * See + * "Avro format" for more information. + */ + public static TableRow convertGenericRecordToTableRow(GenericRecord record, TableSchema schema) { + return convertGenericRecordToTableRow(record, schema.getFields()); + } + + private static TableRow convertGenericRecordToTableRow( + GenericRecord record, List fields) { + TableRow row = new TableRow(); + for (TableFieldSchema subSchema : fields) { + Field field = record.getSchema().getField(subSchema.getName()); + Object convertedValue = + getTypedCellValue(field.schema(), subSchema, record.get(field.name())); + if (convertedValue != null) { + // To match the JSON files exported by BigQuery, do not include null values in the output. + row.set(field.name(), convertedValue); + } + } + return row; + } + + @Nullable + private static Object getTypedCellValue(Schema schema, TableFieldSchema fieldSchema, Object v) { + switch (fieldSchema.getMode()) { + case "REQUIRED": + return convertRequiredField(schema.getType(), fieldSchema, v); + case "REPEATED": + return convertRepeatedField(schema, fieldSchema, v); + case "NULLABLE": + return convertNullableField(schema, fieldSchema, v); + default: + throw new UnsupportedOperationException( + "Parsing a field with BigQuery field schema mode " + fieldSchema.getMode()); + } + } + + private static List convertRepeatedField( + Schema schema, TableFieldSchema fieldSchema, Object v) { + Type arrayType = schema.getType(); + verify( + arrayType == Type.ARRAY, + "BigQuery REPEATED field %s should be Avro ARRAY, not %s", + fieldSchema.getName(), + arrayType); + // REPEATED fields are represented as Avro arrays. + if (v == null) { + // Handle the case of an empty repeated field. + return ImmutableList.of(); + } + @SuppressWarnings("unchecked") + List elements = (List) v; + ImmutableList.Builder values = ImmutableList.builder(); + Type elementType = schema.getElementType().getType(); + for (Object element : elements) { + values.add(convertRequiredField(elementType, fieldSchema, element)); + } + return values.build(); + } + + private static Object convertRequiredField( + Type avroType, TableFieldSchema fieldSchema, Object v) { + // REQUIRED fields are represented as the corresponding Avro types. For example, a BigQuery + // INTEGER type maps to an Avro LONG type. + checkNotNull(v, "REQUIRED field %s should not be null", fieldSchema.getName()); + ImmutableMap fieldMap = + ImmutableMap.builder() + .put("STRING", Type.STRING) + .put("INTEGER", Type.LONG) + .put("FLOAT", Type.DOUBLE) + .put("BOOLEAN", Type.BOOLEAN) + .put("TIMESTAMP", Type.LONG) + .put("RECORD", Type.RECORD) + .build(); + String bqType = fieldSchema.getType(); + Type expectedAvroType = fieldMap.get(bqType); + verify( + avroType == expectedAvroType, + "Expected Avro schema type %s, not %s, for BigQuery %s field %s", + expectedAvroType, + avroType, + bqType, + fieldSchema.getName()); + switch (fieldSchema.getType()) { + case "STRING": + // Avro will use a CharSequence to represent String objects, but it may not always use + // java.lang.String; for example, it may prefer org.apache.avro.util.Utf8. + verify(v instanceof CharSequence, "Expected CharSequence (String), got %s", v.getClass()); + return v.toString(); + case "INTEGER": + verify(v instanceof Long, "Expected Long, got %s", v.getClass()); + return ((Long) v).toString(); + case "FLOAT": + verify(v instanceof Double, "Expected Double, got %s", v.getClass()); + return v; + case "BOOLEAN": + verify(v instanceof Boolean, "Expected Boolean, got %s", v.getClass()); + return v; + case "TIMESTAMP": + // TIMESTAMP data types are represented as Avro LONG types. They are converted back to + // Strings with variable-precision (up to six digits) to match the JSON files export + // by BigQuery. + verify(v instanceof Long, "Expected Long, got %s", v.getClass()); + Double doubleValue = ((Long) v) / 1000000.0; + return formatTimestamp(doubleValue.toString()); + case "RECORD": + verify(v instanceof GenericRecord, "Expected GenericRecord, got %s", v.getClass()); + return convertGenericRecordToTableRow((GenericRecord) v, fieldSchema.getFields()); + default: + throw new UnsupportedOperationException( + String.format( + "Unexpected BigQuery field schema type %s for field named %s", + fieldSchema.getType(), + fieldSchema.getName())); + } + } + + @Nullable + private static Object convertNullableField( + Schema avroSchema, TableFieldSchema fieldSchema, Object v) { + // NULLABLE fields are represented as an Avro Union of the corresponding type and "null". + verify( + avroSchema.getType() == Type.UNION, + "Expected Avro schema type UNION, not %s, for BigQuery NULLABLE field %s", + avroSchema.getType(), + fieldSchema.getName()); + List unionTypes = avroSchema.getTypes(); + verify( + unionTypes.size() == 2, + "BigQuery NULLABLE field %s should be an Avro UNION of NULL and another type, not %s", + fieldSchema.getName(), + unionTypes); + + if (v == null) { + return null; + } + + Type firstType = unionTypes.get(0).getType(); + if (!firstType.equals(Type.NULL)) { + return convertRequiredField(firstType, fieldSchema, v); + } + return convertRequiredField(unionTypes.get(1).getType(), fieldSchema, v); + } } + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 1a9f7869c1..c2c80f79c3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -47,8 +47,6 @@ import com.google.common.collect.ImmutableList; import org.joda.time.Duration; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -196,39 +194,6 @@ public TableRow getCurrent() { return current; } - /** - * Formats BigQuery seconds-since-epoch into String matching JSON export. Thread-safe and - * immutable. - */ - private static final DateTimeFormatter DATE_AND_SECONDS_FORMATER = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC(); - private static String formatTimestamp(String timestamp) { - // timestamp is in "seconds since epoch" format, with scientific notation. - // e.g., "1.45206229112345E9" to mean "2016-01-06 06:38:11.123456 UTC". - // Separate into seconds and microseconds. - double timestampDoubleMicros = Double.parseDouble(timestamp) * 1000000; - long timestampMicros = (long) timestampDoubleMicros; - long seconds = timestampMicros / 1000000; - int micros = (int) (timestampMicros % 1000000); - String dayAndTime = DATE_AND_SECONDS_FORMATER.print(seconds * 1000); - - // No sub-second component. - if (micros == 0) { - return String.format("%s UTC", dayAndTime); - } - - // Sub-second component. - int digits = 6; - int subsecond = micros; - while (subsecond % 10 == 0) { - digits--; - subsecond /= 10; - } - String formatString = String.format("%%0%dd", digits); - String fractionalSeconds = String.format(formatString, subsecond); - return String.format("%s.%s UTC", dayAndTime, fractionalSeconds); - } - /** * Adjusts a field returned from the BigQuery API to match what we will receive when running * BigQuery's export-to-GCS and parallel read, which is the efficient parallel implementation @@ -284,7 +249,7 @@ private static String formatTimestamp(String timestamp) { } if (fieldSchema.getType().equals("TIMESTAMP")) { - return formatTimestamp((String) v); + return AvroUtils.formatTimestamp((String) v); } return v; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java index 2f105ec224..5611fabe28 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java @@ -30,6 +30,8 @@ public class PropertyNames { public static final String BIGQUERY_QUERY = "bigquery_query"; public static final String BIGQUERY_FLATTEN_RESULTS = "bigquery_flatten_results"; public static final String BIGQUERY_WRITE_DISPOSITION = "write_disposition"; + public static final String BIGQUERY_EXPORT_FORMAT = "bigquery_export_format"; + public static final String BIGQUERY_EXPORT_SCHEMA = "bigquery_export_schema"; public static final String CO_GBK_RESULT_SCHEMA = "co_gbk_result_schema"; public static final String COMBINE_FN = "combine_fn"; public static final String COMPONENT_ENCODINGS = "component_encodings"; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java index 68570bfd7a..28bd98adc7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java @@ -18,16 +18,22 @@ import static org.junit.Assert.assertEquals; +import com.google.api.services.bigquery.model.TableFieldSchema; +import com.google.api.services.bigquery.model.TableRow; +import com.google.api.services.bigquery.model.TableSchema; import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.DefaultCoder; import com.google.cloud.dataflow.sdk.util.AvroUtils.AvroMetadata; -import com.google.common.base.MoreObjects; +import com.google.common.collect.Lists; import org.apache.avro.Schema; import org.apache.avro.file.CodecFactory; import org.apache.avro.file.DataFileConstants; import org.apache.avro.file.DataFileWriter; +import org.apache.avro.generic.GenericData; +import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumWriter; +import org.apache.avro.reflect.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -39,7 +45,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Random; /** @@ -99,51 +104,95 @@ public void testReadSchemaString() throws Exception { AvroMetadata metadata = AvroUtils.readMetadataFromFile(filename); // By default, parse validates the schema, which is what we want. Schema schema = new Schema.Parser().parse(metadata.getSchemaString()); - assertEquals(4, schema.getFields().size()); + assertEquals(8, schema.getFields().size()); + } + + @Test + public void testConvertGenericRecordToTableRow() throws Exception { + TableSchema tableSchema = new TableSchema(); + List subFields = Lists.newArrayList( + new TableFieldSchema().setName("species").setType("STRING").setMode("NULLABLE")); + List fields = + Lists.newArrayList( + new TableFieldSchema().setName("number").setType("INTEGER").setMode("REQUIRED"), + new TableFieldSchema().setName("species").setType("STRING").setMode("NULLABLE"), + new TableFieldSchema().setName("quality").setType("FLOAT").setMode("NULLABLE"), + new TableFieldSchema().setName("quantity").setType("INTEGER").setMode("NULLABLE"), + new TableFieldSchema().setName("birthday").setType("TIMESTAMP").setMode("NULLABLE"), + new TableFieldSchema().setName("flighted").setType("BOOLEAN").setMode("NULLABLE"), + new TableFieldSchema().setName("scion").setType("RECORD").setMode("NULLABLE") + .setFields(subFields), + new TableFieldSchema().setName("associates").setType("RECORD").setMode("REPEATED") + .setFields(subFields)); + tableSchema.setFields(fields); + Schema avroSchema = AvroCoder.of(Bird.class).getSchema(); + + { + // Test nullable fields. + GenericRecord record = new GenericData.Record(avroSchema); + record.put("number", 5L); + TableRow convertedRow = AvroUtils.convertGenericRecordToTableRow(record, tableSchema); + TableRow row = new TableRow() + .set("number", "5") + .set("associates", new ArrayList()); + assertEquals(row, convertedRow); + } + { + // Test type conversion for TIMESTAMP, INTEGER, BOOLEAN, and FLOAT. + GenericRecord record = new GenericData.Record(avroSchema); + record.put("number", 5L); + record.put("quality", 5.0); + record.put("birthday", 5L); + record.put("flighted", Boolean.TRUE); + TableRow convertedRow = AvroUtils.convertGenericRecordToTableRow(record, tableSchema); + TableRow row = new TableRow() + .set("number", "5") + .set("birthday", "1970-01-01 00:00:00.000005 UTC") + .set("quality", 5.0) + .set("associates", new ArrayList()) + .set("flighted", Boolean.TRUE); + assertEquals(row, convertedRow); + } + { + // Test repeated fields. + Schema subBirdSchema = AvroCoder.of(Bird.SubBird.class).getSchema(); + GenericRecord nestedRecord = new GenericData.Record(subBirdSchema); + nestedRecord.put("species", "other"); + GenericRecord record = new GenericData.Record(avroSchema); + record.put("number", 5L); + record.put("associates", Lists.newArrayList(nestedRecord)); + TableRow convertedRow = AvroUtils.convertGenericRecordToTableRow(record, tableSchema); + TableRow row = new TableRow() + .set("associates", Lists.newArrayList( + new TableRow().set("species", "other"))) + .set("number", "5"); + assertEquals(row, convertedRow); + } } /** - * Class used as the record type in tests. + * Pojo class used as the record type in tests. */ @DefaultCoder(AvroCoder.class) static class Bird { long number; - String species; - String quality; - long quantity; - - public Bird() {} - - public Bird(long number, String species, String quality, long quantity) { - this.number = number; - this.species = species; - this.quality = quality; - this.quantity = quantity; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(Bird.class) - .addValue(number) - .addValue(species) - .addValue(quantity) - .addValue(quality) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Bird) { - Bird other = (Bird) obj; - return Objects.equals(species, other.species) && Objects.equals(quality, other.quality) - && quantity == other.quantity && number == other.number; - } - return false; + @Nullable String species; + @Nullable Double quality; + @Nullable Long quantity; + @Nullable Long birthday; // Exercises TIMESTAMP. + @Nullable Boolean flighted; + @Nullable SubBird scion; + SubBird[] associates; + + static class SubBird { + @Nullable String species; + + public SubBird() {} } - @Override - public int hashCode() { - return Objects.hash(number, species, quality, quantity); + public Bird() { + associates = new SubBird[1]; + associates[0] = new SubBird(); } } @@ -151,15 +200,13 @@ public int hashCode() { * Create a list of n random records. */ private static List createRandomRecords(long n) { - String[] qualities = { - "miserable", "forelorn", "fidgity", "squirrelly", "fanciful", "chipper", "lazy"}; String[] species = {"pigeons", "owls", "gulls", "hawks", "robins", "jays"}; Random random = new Random(0); List records = new ArrayList<>(); for (long i = 0; i < n; i++) { Bird bird = new Bird(); - bird.quality = qualities[random.nextInt(qualities.length)]; + bird.quality = random.nextDouble(); bird.species = species[random.nextInt(species.length)]; bird.number = i; bird.quantity = random.nextLong(); From ed87d95abd39a12c742092b2a4795bf6b4da5069 Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 2 Feb 2016 09:51:46 -0800 Subject: [PATCH 064/751] Move some status pages to worker module This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113646973 --- .../status/LastExceptionDataProvider.java | 46 ------- .../runners/worker/status/StatuszServlet.java | 68 ---------- .../worker/status/WorkerStatusPages.java | 123 ------------------ .../worker/status/WorkerStatusPagesTest.java | 76 ----------- 4 files changed, 313 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java deleted file mode 100644 index 00df485ae2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/LastExceptionDataProvider.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import java.io.PrintWriter; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Capture the last exception thrown during processing, and display that on the statusz page. - */ -public class LastExceptionDataProvider implements StatusDataProvider { - - private static final AtomicReference lastException = new AtomicReference<>(); - - /** - * Report an exception to the exception data provider. - */ - public static void reportException(Throwable t) { - lastException.set(t); - } - - @Override - public void appendSummaryHtml(PrintWriter writer) { - Throwable t = lastException.get(); - if (t == null) { - writer.println("None
"); - } else { - writer.println("
");
-      t.printStackTrace(writer);
-      writer.println("
"); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java deleted file mode 100644 index 78bf91ae27..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatuszServlet.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.LinkedHashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * General servlet for providing a bunch of information on the statusz page. - */ -public class StatuszServlet extends BaseStatusServlet { - - private static class DataProviderInfo { - private final String longName; - private final StatusDataProvider dataProvider; - - public DataProviderInfo(String longName, StatusDataProvider dataProvider) { - this.longName = longName; - this.dataProvider = dataProvider; - } - } - - private LinkedHashMap dataProviders = new LinkedHashMap<>(); - - public StatuszServlet() { - super("statusz"); - } - - public void addDataProvider(String shortName, String longName, StatusDataProvider provider) { - dataProviders.put(shortName, new DataProviderInfo(longName, provider)); - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - PrintWriter writer = response.getWriter(); - writer.println(""); - - writer.println("

Worker Harness

"); - - for (DataProviderInfo info : dataProviders.values()) { - writer.print("

"); - writer.print(info.longName); - writer.println("

"); - - info.dataProvider.appendSummaryHtml(writer); - } - writer.println(""); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java deleted file mode 100644 index ad16654e27..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPages.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import com.google.common.annotations.VisibleForTesting; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Manages the server providing the worker status pages. - */ -public class WorkerStatusPages { - - private static final Logger LOG = LoggerFactory.getLogger(WorkerStatusPages.class); - - private final Server statusServer; - private final StatuszServlet statuszServlet = new StatuszServlet(); - private final ServletHandler servletHandler = new ServletHandler(); - - @VisibleForTesting WorkerStatusPages(Server server) { - this.statusServer = server; - this.statusServer.setHandler(servletHandler); - - // Install the default servlets (threadz, healthz, heapz, statusz) - addServlet(new ThreadzServlet()); - addServlet(new HealthzServlet()); - addServlet(new HeapzServlet()); - addServlet(statuszServlet); - - } - - public static WorkerStatusPages create(int defaultStatusPort) { - int statusPort = defaultStatusPort; - if (System.getProperties().containsKey("status_port")) { - statusPort = Integer.parseInt(System.getProperty("status_port")); - } - return new WorkerStatusPages(new Server(statusPort)); - } - - /** Start the server. */ - public void start() { - if (statusServer.isStarted()) { - LOG.warn("Status server already started on {}", statusServer.getURI()); - return; - } - - try { - addServlet(new RedirectToStatusz404Handler()); - statusServer.start(); - - LOG.info("Status server started on {}", statusServer.getURI()); - } catch (Exception e) { - LOG.warn("Status server failed to start: ", e); - } - } - - /** Stop the server. */ - public void stop() { - try { - statusServer.stop(); - } catch (Exception e) { - LOG.warn("Status server failed to stop: ", e); - } - } - - /** - * Add a status servlet. - */ - public void addServlet(BaseStatusServlet servlet) { - ServletHolder holder = new ServletHolder(); - holder.setServlet(servlet); - servletHandler.addServletWithMapping(holder, servlet.getPath()); - } - - /** - * Add data to the main statusz servlet. - */ - public void addStatusDataProvider( - String shortName, String longName, StatusDataProvider dataProvider) { - statuszServlet.addDataProvider(shortName, longName, dataProvider); - } - - /** - * Redirect all invalid pages to /statusz. - */ - private static class RedirectToStatusz404Handler extends BaseStatusServlet { - - public RedirectToStatusz404Handler() { - super("*"); - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - response.sendRedirect("/statusz"); - } - - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java deleted file mode 100644 index 8730a61497..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/status/WorkerStatusPagesTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; - -import org.eclipse.jetty.server.LocalConnector; -import org.eclipse.jetty.server.Server; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link WorkerStatusPages}. - */ -@RunWith(JUnit4.class) -public class WorkerStatusPagesTest { - - private final Server server = new Server(); - private final LocalConnector connector = new LocalConnector(server); - private final WorkerStatusPages wsp = new WorkerStatusPages(server); - - @Before - public void setUp() throws Exception { - server.addConnector(connector); - wsp.start(); - } - - @After - public void tearDown() throws Exception { - wsp.stop(); - } - - @Test - public void testThreadz() throws Exception { - String response = getPage("/threadz"); - assertThat(response, containsString("HTTP/1.1 200 OK")); - assertThat("Test method should appear in stack trace", - response, containsString("WorkerStatusPagesTest.testThreadz")); - } - - @Test - public void testHealthz() throws Exception { - String response = getPage("/threadz"); - assertThat(response, containsString("HTTP/1.1 200 OK")); - assertThat(response, containsString("ok")); - } - - @Test - public void testUnknownHandler() throws Exception { - String response = getPage("/missinghandlerz"); - assertThat(response, containsString("HTTP/1.1 302 Found")); - assertThat(response, containsString("Location: http://localhost/statusz")); - } - - private String getPage(String requestURL) throws Exception { - String request = String.format("GET %s HTTP/1.1\nhost: localhost\n\n", requestURL); - return connector.getResponses(request); - } -} From 748ada7762f4033665b8daaa726fdc5b65952a2a Mon Sep 17 00:00:00 2001 From: peihe Date: Tue, 2 Feb 2016 13:57:40 -0800 Subject: [PATCH 065/751] CombineWithContext support in batch PartialGroupByKeyOperation ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113674191 --- .../worker/MapTaskExecutorFactory.java | 118 +++++++++++++----- .../sdk/util/PerKeyCombineFnRunner.java | 70 +++++++++-- .../sdk/util/PerKeyCombineFnRunners.java | 75 +++++++++++ .../worker/PartialGroupByKeyOperation.java | 10 +- .../worker/MapTaskExecutorFactoryTest.java | 51 ++++++++ .../PartialGroupByKeyOperationTest.java | 8 +- 6 files changed, 284 insertions(+), 48 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java index efab417e21..b38d9c852d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java @@ -17,7 +17,6 @@ package com.google.cloud.dataflow.sdk.runners.worker; import static com.google.cloud.dataflow.sdk.util.Structs.getBytes; -import static com.google.common.base.Preconditions.checkArgument; import com.google.api.services.dataflow.model.FlattenInstruction; import com.google.api.services.dataflow.model.InstructionInput; @@ -31,17 +30,18 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunner; +import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunners; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.Serializer; +import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; import com.google.cloud.dataflow.sdk.util.common.CounterSet; @@ -63,6 +63,10 @@ import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; import com.google.cloud.dataflow.sdk.util.common.worker.WriteOperation; import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.base.Function; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import org.joda.time.Instant; @@ -280,9 +284,9 @@ static ParDoOperation createParDoOperation( } static PartialGroupByKeyOperation createPartialGroupByKeyOperation( - @SuppressWarnings("unused") PipelineOptions options, + PipelineOptions options, ParallelInstruction instruction, - @SuppressWarnings("unused") ExecutionContext executionContext, + DataflowExecutionContext executionContext, List priorOperations, String counterPrefix, CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception { PartialGroupByKeyInstruction pgbk = instruction.getPartialGroupByKey(); @@ -304,71 +308,81 @@ static PartialGroupByKeyOperation createPartialGroupByKeyOperation( OutputReceiver[] receivers = createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1); - PartialGroupByKeyOperation.Combiner valueCombiner = createValueCombiner(pgbk); + PartialGroupByKeyOperation.Combiner valueCombiner = null; + PartialGroupByKeyOperation.PairInfo pairInfo = PairInfo.create(); + if (pgbk.getValueCombiningFn() != null) { + Object deserializedFn = SerializableUtils.deserializeFromByteArray( + getBytes(CloudObject.fromSpec(pgbk.getValueCombiningFn()), PropertyNames.SERIALIZED_FN), + "serialized combine fn"); + AppliedCombineFn combineFn = ((AppliedCombineFn) deserializedFn); + + SideInputReader sideInputReader = + executionContext.getSideInputReader(pgbk.getSideInputs(), combineFn.getSideInputViews()); + valueCombiner = new ValueCombiner<>( + PerKeyCombineFnRunners.create(combineFn.getFn()), sideInputReader, options); + if (combineFn.getFn() instanceof RequiresContextInternal) { + pairInfo = WindowsExpandingPairInfo.create(); + } + } PartialGroupByKeyOperation operation = new PartialGroupByKeyOperation( instruction.getSystemName(), new WindowingCoderGroupingKeyCreator<>(keyCoder), new CoderSizeEstimator<>(WindowedValue.getValueOnlyCoder(keyCoder)), new CoderSizeEstimator<>(valueCoder), 0.001 /*sizeEstimatorSampleRate*/, valueCombiner, - PairInfo.create(), receivers, counterPrefix, addCounterMutator, stateSampler); + pairInfo, receivers, counterPrefix, addCounterMutator, stateSampler); attachInput(operation, pgbk.getInput(), priorOperations); return operation; } - static ValueCombiner createValueCombiner(PartialGroupByKeyInstruction pgbk) - throws Exception { - if (pgbk.getValueCombiningFn() == null) { - return null; - } - - Object deserializedFn = SerializableUtils.deserializeFromByteArray( - getBytes(CloudObject.fromSpec(pgbk.getValueCombiningFn()), PropertyNames.SERIALIZED_FN), - "serialized combine fn"); - AppliedCombineFn appliedCombineFn = (AppliedCombineFn) deserializedFn; - checkArgument( - !(appliedCombineFn.getFn() instanceof RequiresContextInternal), - "Combiner lifting is not supported for combine functions with contexts: %s", - appliedCombineFn.getFn().getClass().getName()); - return new ValueCombiner<>(((KeyedCombineFn) appliedCombineFn.getFn())); - } - /** * Implements PGBKOp.Combiner via Combine.KeyedCombineFn. */ public static class ValueCombiner implements PartialGroupByKeyOperation.Combiner, InputT, AccumT, OutputT> { - private final Combine.KeyedCombineFn combineFn; - - private ValueCombiner(Combine.KeyedCombineFn combineFn) { + private final PerKeyCombineFnRunner combineFn; + private final SideInputReader sideInputReader; + private final PipelineOptions options; + + private ValueCombiner( + PerKeyCombineFnRunner combineFn, + SideInputReader sideInputReader, + PipelineOptions options) { this.combineFn = combineFn; + this.sideInputReader = sideInputReader; + this.options = options; } @Override public AccumT createAccumulator(WindowedValue windowedKey) { - return this.combineFn.createAccumulator(windowedKey.getValue()); + return this.combineFn.createAccumulator(windowedKey.getValue(), + options, sideInputReader, windowedKey.getWindows()); } @Override public AccumT add(WindowedValue windowedKey, AccumT accumulator, InputT value) { - return this.combineFn.addInput(windowedKey.getValue(), accumulator, value); + return this.combineFn.addInput(windowedKey.getValue(), accumulator, value, + options, sideInputReader, windowedKey.getWindows()); } @Override public AccumT merge(WindowedValue windowedKey, Iterable accumulators) { - return this.combineFn.mergeAccumulators(windowedKey.getValue(), accumulators); + return this.combineFn.mergeAccumulators(windowedKey.getValue(), accumulators, + options, sideInputReader, windowedKey.getWindows()); } @Override public AccumT compact(WindowedValue windowedKey, AccumT accumulator) { - return this.combineFn.compact(windowedKey.getValue(), accumulator); + return this.combineFn.compact(windowedKey.getValue(), accumulator, + options, sideInputReader, windowedKey.getWindows()); } @Override public OutputT extract(WindowedValue windowedKey, AccumT accumulator) { - return this.combineFn.extractOutput(windowedKey.getValue(), accumulator); + return this.combineFn.extractOutput(windowedKey.getValue(), accumulator, + options, sideInputReader, windowedKey.getWindows()); } } @@ -382,10 +396,46 @@ public static PairInfo create() { } private PairInfo() {} @Override - public Object getKeyFromInputPair(Object pair) { + public Iterable getKeysFromInputPair(Object pair) { + @SuppressWarnings("unchecked") + WindowedValue> windowedKv = (WindowedValue>) pair; + return ImmutableList.of(windowedKv.withValue(windowedKv.getValue().getKey())); + } + @Override + public Object getValueFromInputPair(Object pair) { @SuppressWarnings("unchecked") WindowedValue> windowedKv = (WindowedValue>) pair; - return windowedKv.withValue(windowedKv.getValue().getKey()); + return windowedKv.getValue().getValue(); + } + @Override + public Object makeOutputPair(Object key, Object values) { + WindowedValue windowedKey = (WindowedValue) key; + return windowedKey.withValue(KV.of(windowedKey.getValue(), values)); + } + } + + /** + * Implements windows expanding PGBKOp.PairInfo via KVs. + */ + public static class WindowsExpandingPairInfo implements PartialGroupByKeyOperation.PairInfo { + private static WindowsExpandingPairInfo theInstance = new WindowsExpandingPairInfo(); + public static WindowsExpandingPairInfo create() { + return theInstance; + } + private WindowsExpandingPairInfo() {} + @Override + public Iterable getKeysFromInputPair(Object pair) { + @SuppressWarnings("unchecked") + final WindowedValue> windowedKv = (WindowedValue>) pair; + Preconditions.checkArgument(!windowedKv.getWindows().isEmpty()); + return Iterables.transform(windowedKv.getWindows(), + new Function() { + @Override + public Object apply(BoundedWindow window) { + return WindowedValue.of(windowedKv.getValue().getKey(), + windowedKv.getTimestamp(), window, windowedKv.getPane()); + } + }); } @Override public Object getValueFromInputPair(Object pair) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java index 295d20ef22..516525a795 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java @@ -15,10 +15,14 @@ */ package com.google.cloud.dataflow.sdk.util; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation; import java.io.Serializable; +import java.util.Collection; /** * An interface that runs a {@link PerKeyCombineFn} with unified APIs. @@ -38,7 +42,7 @@ public interface PerKeyCombineFnRunner extends Seria ///////////////////////////////////////////////////////////////////////////// /** - * Forwards the call to a keyed combine function to create accumulator in a {@link DoFn}. + * Forwards the call to a {@link PerKeyCombineFn} to create the accumulator in a {@link DoFn}. * *

It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} * if it is required. @@ -46,7 +50,7 @@ public interface PerKeyCombineFnRunner extends Seria public AccumT createAccumulator(K key, DoFn.ProcessContext c); /** - * Forwards the call to a keyed combine function to add input in a {@link DoFn}. + * Forwards the call to a {@link PerKeyCombineFn} to add the input in a {@link DoFn}. * *

It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} * if it is required. @@ -54,7 +58,7 @@ public interface PerKeyCombineFnRunner extends Seria public AccumT addInput(K key, AccumT accumulator, InputT input, DoFn.ProcessContext c); /** - * Forwards the call to a keyed combine function to merge accumulators in a {@link DoFn}. + * Forwards the call to a {@link PerKeyCombineFn} to merge accumulators in a {@link DoFn}. * *

It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} * if it is required. @@ -63,7 +67,7 @@ public AccumT mergeAccumulators( K key, Iterable accumulators, DoFn.ProcessContext c); /** - * Forwards the call to a keyed combine function to extract output in a {@link DoFn}. + * Forwards the call to a {@link PerKeyCombineFn} to extract the output in a {@link DoFn}. * *

It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} * if it is required. @@ -71,7 +75,7 @@ public AccumT mergeAccumulators( public OutputT extractOutput(K key, AccumT accumulator, DoFn.ProcessContext c); /** - * Forwards the call to a keyed combine function to compact the accumulator in a {@link DoFn}. + * Forwards the call to a {@link PerKeyCombineFn} to compact the accumulator in a {@link DoFn}. * *

It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} * if it is required. @@ -79,7 +83,7 @@ public AccumT mergeAccumulators( public AccumT compact(K key, AccumT accumulator, DoFn.ProcessContext c); /** - * Forwards the call to a keyed combine function to combine the inputs and extract output + * Forwards the call to a {@link PerKeyCombineFn} to combine the inputs and extract output * in a {@link DoFn}. * *

It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} @@ -88,10 +92,62 @@ public AccumT mergeAccumulators( public OutputT apply(K key, Iterable inputs, DoFn.ProcessContext c); /** - * Forwards the call to a keyed combine function to add all inputs in a {@link DoFn}. + * Forwards the call to a {@link PerKeyCombineFn} to add all inputs in a {@link DoFn}. * *

It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} * if it is required. */ public AccumT addInputs(K key, Iterable inputs, DoFn.ProcessContext c); + + ///////////////////////////////////////////////////////////////////////////// + + /** + * Forwards the call to a {@link PerKeyCombineFn} to create the accumulator + * in a {@link PartialGroupByKeyOperation}. + * + *

It constructs a {@code CombineWithContext.Context} from + * {@link PipelineOptions} and {@link SideInputReader} if it is required. + */ + public AccumT createAccumulator(K key, PipelineOptions options, + SideInputReader sideInputReader, Collection windows); + + /** + * Forwards the call to a {@link PerKeyCombineFn} to add the input + * in a {@link PartialGroupByKeyOperation}. + * + *

It constructs a {@code CombineWithContext.Context} from + * {@link PipelineOptions} and {@link SideInputReader} if it is required. + */ + public AccumT addInput(K key, AccumT accumulator, InputT value, PipelineOptions options, + SideInputReader sideInputReader, Collection windows); + + /** + * Forwards the call to a {@link PerKeyCombineFn} to merge accumulators + * in a {@link PartialGroupByKeyOperation}. + * + *

It constructs a {@code CombineWithContext.Context} from + * {@link PipelineOptions} and {@link SideInputReader} if it is required. + */ + public AccumT mergeAccumulators(K key, Iterable accumulators, PipelineOptions options, + SideInputReader sideInputReader, Collection windows); + + /** + * Forwards the call to a {@link PerKeyCombineFn} to extract the output + * in a {@link PartialGroupByKeyOperation}. + * + *

It constructs a {@code CombineWithContext.Context} from + * {@link PipelineOptions} and {@link SideInputReader} if it is required. + */ + public OutputT extractOutput(K key, AccumT accumulator, PipelineOptions options, + SideInputReader sideInputReader, Collection windows); + + /** + * Forwards the call to a {@link PerKeyCombineFn} to compact the accumulator + * in a {@link PartialGroupByKeyOperation}. + * + *

It constructs a {@code CombineWithContext.Context} from + * {@link PipelineOptions} and {@link SideInputReader} if it is required. + */ + public AccumT compact(K key, AccumT accumulator, PipelineOptions options, + SideInputReader sideInputReader, Collection windows); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java index b574632633..6606c5451f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java @@ -15,12 +15,17 @@ */ package com.google.cloud.dataflow.sdk.util; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.common.collect.Iterables; + +import java.util.Collection; /** * Static utility methods that provide {@link PerKeyCombineFnRunner} implementations @@ -105,6 +110,36 @@ public AccumT addInputs(K key, Iterable inputs, DoFn.ProcessContex public String toString() { return keyedCombineFn.toString(); } + + @Override + public AccumT createAccumulator(K key, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFn.createAccumulator(key); + } + + @Override + public AccumT addInput(K key, AccumT accumulator, InputT input, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFn.addInput(key, accumulator, input); + } + + @Override + public AccumT mergeAccumulators(K key, Iterable accumulators, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFn.mergeAccumulators(key, accumulators); + } + + @Override + public OutputT extractOutput(K key, AccumT accumulator, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFn.extractOutput(key, accumulator); + } + + @Override + public AccumT compact(K key, AccumT accumulator, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFn.compact(key, accumulator); + } } /** @@ -178,5 +213,45 @@ public AccumT addInputs(K key, Iterable inputs, DoFn.ProcessContex public String toString() { return keyedCombineFnWithContext.toString(); } + + @Override + public AccumT createAccumulator(K key, PipelineOptions options, SideInputReader sideInputReader, + Collection windows) { + return keyedCombineFnWithContext.createAccumulator(key, + CombineContextFactory.createFromComponents( + options, sideInputReader, Iterables.getOnlyElement(windows))); + } + + @Override + public AccumT addInput(K key, AccumT accumulator, InputT input, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFnWithContext.addInput(key, accumulator, input, + CombineContextFactory.createFromComponents( + options, sideInputReader, Iterables.getOnlyElement(windows))); + } + + @Override + public AccumT mergeAccumulators(K key, Iterable accumulators, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFnWithContext.mergeAccumulators(key, accumulators, + CombineContextFactory.createFromComponents( + options, sideInputReader, Iterables.getOnlyElement(windows))); + } + + @Override + public OutputT extractOutput(K key, AccumT accumulator, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFnWithContext.extractOutput(key, accumulator, + CombineContextFactory.createFromComponents( + options, sideInputReader, Iterables.getOnlyElement(windows))); + } + + @Override + public AccumT compact(K key, AccumT accumulator, PipelineOptions options, + SideInputReader sideInputReader, Collection windows) { + return keyedCombineFnWithContext.compact(key, accumulator, + CombineContextFactory.createFromComponents( + options, sideInputReader, Iterables.getOnlyElement(windows))); + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java index 5f8f9d32fe..cbd4f56799 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java @@ -51,7 +51,7 @@ public static interface SizeEstimator { * that are key/value or key/values pairs. */ public interface PairInfo { - public Object getKeyFromInputPair(Object pair); + public Iterable getKeysFromInputPair(Object pair); public Object getValueFromInputPair(Object pair); public Object makeOutputPair(Object key, Object value); } @@ -310,9 +310,11 @@ interface GroupingTableEntry { */ @SuppressWarnings("unchecked") public void put(Object pair, Receiver receiver) throws Exception { - put((K) pairInfo.getKeyFromInputPair(pair), - (InputT) pairInfo.getValueFromInputPair(pair), - receiver); + for (Object key : pairInfo.getKeysFromInputPair(pair)) { + put((K) key, + (InputT) pairInfo.getValueFromInputPair(pair), + receiver); + } } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java index f8799bd9af..4dad6be28b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java @@ -20,6 +20,8 @@ import static com.google.cloud.dataflow.sdk.runners.worker.DataflowOutputCounter.getMeanByteCounterName; import static com.google.cloud.dataflow.sdk.runners.worker.DataflowOutputCounter.getObjectCounterName; import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; +import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; +import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; import static com.google.cloud.dataflow.sdk.util.Structs.addString; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; @@ -40,6 +42,9 @@ import com.google.api.services.dataflow.model.ReadInstruction; import com.google.api.services.dataflow.model.Source; import com.google.api.services.dataflow.model.WriteInstruction; +import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.CoderRegistry; +import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; @@ -49,7 +54,9 @@ import com.google.cloud.dataflow.sdk.runners.worker.SinkFactoryTest.TestSink; import com.google.cloud.dataflow.sdk.runners.worker.SinkFactoryTest.TestSinkFactory; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.DoFnInfo; @@ -512,6 +519,50 @@ public void testCreatePartialGroupByKeyOperation() throws Exception { priorOperations.get(producerIndex).receivers[producerOutputNum].getOnlyReceiver()); } + @Test + public void testCreatePartialGroupByKeyOperationWithCombine() throws Exception { + List priorOperations = Arrays.asList( + new Operation[] {new TestOperation(3), new TestOperation(5), new TestOperation(1)}); + + int producerIndex = 1; + int producerOutputNum = 2; + + ParallelInstruction instruction = + createPartialGroupByKeyInstruction(producerIndex, producerOutputNum); + + AppliedCombineFn combineFn = AppliedCombineFn.withInputCoder( + new Sum.SumIntegerFn().asKeyedFn(), new CoderRegistry(), + KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of())); + CloudObject cloudCombineFn = CloudObject.forClassName("CombineFn"); + addString(cloudCombineFn, PropertyNames.SERIALIZED_FN, + byteArrayToJsonString(serializeToByteArray(combineFn))); + instruction.getPartialGroupByKey().setValueCombiningFn(cloudCombineFn); + + CounterSet counterSet = new CounterSet(); + String counterPrefix = "test-"; + String systemStageName = "stageName"; + StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); + Operation operation = MapTaskExecutorFactory.createOperation( + options, + instruction, + readerFactoryRegistry, + BatchModeExecutionContext.fromOptions(options), + priorOperations, + counterPrefix, + systemStageName, + counterSet.getAddCounterMutator(), + stateSampler); + assertThat(operation, instanceOf(PartialGroupByKeyOperation.class)); + PartialGroupByKeyOperation pgbkOperation = (PartialGroupByKeyOperation) operation; + + assertEquals(pgbkOperation.receivers.length, 1); + assertEquals(pgbkOperation.receivers[0].getReceiverCount(), 0); + assertEquals(pgbkOperation.initializationState, Operation.InitializationState.UNSTARTED); + assertSame( + pgbkOperation, + priorOperations.get(producerIndex).receivers[producerOutputNum].getOnlyReceiver()); + } + static ParallelInstruction createFlattenInstruction(int producerIndex1, int producerOutputNum1, int producerIndex2, int producerOutputNum2, String systemName) { List cloudInputs = new ArrayList<>(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java index 496632ba9a..bf5bf9b541 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java @@ -37,6 +37,7 @@ import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.ElementByteSizeObservableCoder; import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.PairInfo; import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.WindowingCoderGroupingKeyCreator; +import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.WindowsExpandingPairInfo; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.Counter; import com.google.cloud.dataflow.sdk.util.common.CounterSet; @@ -47,6 +48,7 @@ import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.SamplingSizeEstimator; import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.SizeEstimator; import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.collect.ImmutableList; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; @@ -181,7 +183,7 @@ public Integer extract(WindowedValue key, Integer accumulator) { new CoderSizeEstimator(WindowedValue.getValueOnlyCoder(keyCoder)), new CoderSizeEstimator(valueCoder), combineFn, - PairInfo.create(), + WindowsExpandingPairInfo.create(), receiver, counterPrefix, counterSet.getAddCounterMutator(), @@ -262,8 +264,8 @@ public long estimateSize(String element) { private static class KvPairInfo implements PartialGroupByKeyOperation.PairInfo { @Override - public Object getKeyFromInputPair(Object pair) { - return ((KV) pair).getKey(); + public Iterable getKeysFromInputPair(Object pair) { + return ImmutableList.of(((KV) pair).getKey()); } @Override public Object getValueFromInputPair(Object pair) { From e5952815302de10e1979fcdd398ab71b73a15249 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 2 Feb 2016 15:19:19 -0800 Subject: [PATCH 066/751] Fix TimeTrigger#isCompatible Previously, TimeTrigger#isCompatible was true only when the time transformation functions were the same object, not merely equal transformations. Now when they are created via the primary builder methods, equality is decidable and compatibility is more useful. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113683351 --- .../sdk/transforms/windowing/TimeTrigger.java | 103 ++++++++++++++---- .../windowing/AfterProcessingTimeTest.java | 12 ++ 2 files changed, 93 insertions(+), 22 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java index 72f00b7ed8..0263c85900 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java @@ -30,6 +30,7 @@ import org.joda.time.Instant; import java.util.List; +import java.util.Objects; /** * Support for manipulating the time at which time-based {@link Trigger}s fire. @@ -76,16 +77,7 @@ protected Instant computeTargetTimestamp(Instant time) { * @return An updated time trigger that will wait the additional time before firing. */ public TimeTrigger plusDelayOf(final Duration delay) { - return newWith(delayFn(delay)); - } - - private static SerializableFunction delayFn(final Duration delay) { - return new SerializableFunction() { - @Override - public Instant apply(Instant input) { - return input.plus(delay); - } - }; + return newWith(new DelayFn(delay)); } /** @@ -96,18 +88,7 @@ public Instant apply(Instant input) { * CalendarWindows. */ public TimeTrigger alignedTo(final Duration size, final Instant offset) { - return newWith(alignFn(size, offset)); - } - - private static SerializableFunction alignFn( - final Duration size, final Instant offset) { - return new SerializableFunction() { - @Override - public Instant apply(Instant point) { - long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis(); - return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart); - } - }; + return newWith(new AlignFn(size, offset)); } /** @@ -161,4 +142,82 @@ private TimeTrigger newWith(SerializableFunction timestampM * @return a new {@code TimeTrigger}. */ protected abstract TimeTrigger newWith(List> transform); + + /** + * A {@link SerializableFunction} to delay the timestamp at which this triggers fires. + */ + private static final class DelayFn implements SerializableFunction { + private final Duration delay; + + public DelayFn(Duration delay) { + this.delay = delay; + } + + @Override + public Instant apply(Instant input) { + return input.plus(delay); + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + + if (!(object instanceof DelayFn)) { + return false; + } + + return this.delay.equals(((DelayFn) object).delay); + } + + @Override + public int hashCode() { + return Objects.hash(delay); + } + } + + /** + * A {@link SerializableFunction} to align an instant to the nearest interval boundary. + */ + private static final class AlignFn implements SerializableFunction { + private final Duration size; + private final Instant offset; + + + /** + * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater + * than the timestamp. + */ + public AlignFn(Duration size, Instant offset) { + this.size = size; + this.offset = offset; + } + + @Override + public Instant apply(Instant point) { + long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis(); + return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart); + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + + if (!(object instanceof AlignFn)) { + return false; + } + + AlignFn other = (AlignFn) object; + return other.size.equals(this.size) + && other.offset.equals(this.offset); + } + + @Override + public int hashCode() { + return Objects.hash(size, offset); + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java index 013c5395bb..0e35fe221f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java @@ -141,4 +141,16 @@ public void testContinuation() throws Exception { new AfterSynchronizedProcessingTime<>(), firstElementPlus1.getContinuationTrigger()); } + + /** + * Basic test of compatibility check between identical triggers. + */ + @Test + public void testCompatibilityIdentical() throws Exception { + Trigger t1 = AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(1L)); + Trigger t2 = AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(1L)); + assertTrue(t1.isCompatible(t2)); + } } From 4942eeff68edbc64f2b431f44ad6174659df63f6 Mon Sep 17 00:00:00 2001 From: peihe Date: Tue, 2 Feb 2016 15:59:43 -0800 Subject: [PATCH 067/751] Move StructuralByteArray to the coder package ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113687235 --- .../dataflow/sdk/coders/ByteArrayCoder.java | 1 - .../dataflow/sdk/coders/StandardCoder.java | 1 - .../sdk/coders/StructuralByteArray.java | 56 +++++++++++++++++++ .../worker/PartialGroupByKeyOperation.java | 39 ------------- .../sdk/coders/StructuralByteArrayTest.java | 39 +++++++++++++ 5 files changed, 95 insertions(+), 41 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java index 18182688d7..1e555c67bf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java @@ -19,7 +19,6 @@ import com.google.cloud.dataflow.sdk.util.ExposedByteArrayOutputStream; import com.google.cloud.dataflow.sdk.util.StreamUtils; import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.StructuralByteArray; import com.google.common.io.ByteStreams; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java index ad5551224a..faa98619ec 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java @@ -24,7 +24,6 @@ import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.StructuralByteArray; import com.google.common.collect.Lists; import com.google.common.io.ByteStreams; import com.google.common.io.CountingOutputStream; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java new file mode 100644 index 0000000000..ea18eb971a --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders; + +import static com.google.api.client.util.Base64.encodeBase64String; + +import java.util.Arrays; + +/** + * A wrapper around a byte[] that uses structural, value-based + * equality rather than byte[]'s normal object identity. + */ +public class StructuralByteArray { + byte[] value; + + public StructuralByteArray(byte[] value) { + this.value = value; + } + + public byte[] getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (o instanceof StructuralByteArray) { + StructuralByteArray that = (StructuralByteArray) o; + return Arrays.equals(this.value, that.value); + } else { + return false; + } + } + + @Override + public int hashCode() { + return Arrays.hashCode(value); + } + + @Override + public String toString() { + return "base64:" + encodeBase64String(value); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java index cbd4f56799..7004eac287 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java @@ -16,12 +16,9 @@ package com.google.cloud.dataflow.sdk.util.common.worker; -import static com.google.api.client.util.Base64.encodeBase64String; - import com.google.cloud.dataflow.sdk.util.common.CounterSet; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -67,42 +64,6 @@ public interface Combiner { public OutputT extract(K key, AccumT accumulator); } - /** - * A wrapper around a byte[] that uses structural, value-based - * equality rather than byte[]'s normal object identity. - */ - public static class StructuralByteArray { - byte[] value; - - public StructuralByteArray(byte[] value) { - this.value = value; - } - - public byte[] getValue() { - return value; - } - - @Override - public boolean equals(Object o) { - if (o instanceof StructuralByteArray) { - StructuralByteArray that = (StructuralByteArray) o; - return Arrays.equals(this.value, that.value); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Arrays.hashCode(value); - } - - @Override - public String toString() { - return "base64:" + encodeBase64String(value); - } - } - // By default, how many bytes we allow the grouping table to consume before // it has to be flushed. static final long DEFAULT_MAX_GROUPING_TABLE_BYTES = 100_000_000L; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java new file mode 100644 index 0000000000..8f8cd8cb08 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link StructuralByteArray}. + */ +@RunWith(JUnit4.class) +public final class StructuralByteArrayTest { + + @Test + public void testStructuralByteArray() throws Exception { + assertEquals( + new StructuralByteArray("test string".getBytes()), + new StructuralByteArray("test string".getBytes())); + assertFalse(new StructuralByteArray("test string".getBytes()).equals( + new StructuralByteArray("diff string".getBytes()))); + } +} From 5f06ee585d5c7b8d3db75f33707ccd0fc7aad58e Mon Sep 17 00:00:00 2001 From: dhalperi Date: Tue, 2 Feb 2016 16:04:19 -0800 Subject: [PATCH 068/751] AvroUtils: default missing field schema mode to NULLABLE, and test Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113687733 --- .../google/cloud/dataflow/sdk/util/AvroUtils.java | 10 +++++++++- .../cloud/dataflow/sdk/util/AvroUtilsTest.java | 12 ++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java index 335e529873..c3a486102e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.util; +import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; @@ -201,6 +202,8 @@ private static TableRow convertGenericRecordToTableRow( GenericRecord record, List fields) { TableRow row = new TableRow(); for (TableFieldSchema subSchema : fields) { + // Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the name field + // is required, so it may not be null. Field field = record.getSchema().getField(subSchema.getName()); Object convertedValue = getTypedCellValue(field.schema(), subSchema, record.get(field.name())); @@ -214,7 +217,10 @@ private static TableRow convertGenericRecordToTableRow( @Nullable private static Object getTypedCellValue(Schema schema, TableFieldSchema fieldSchema, Object v) { - switch (fieldSchema.getMode()) { + // Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the mode field + // is optional (and so it may be null), but defaults to "NULLABLE". + String mode = firstNonNull(fieldSchema.getMode(), "NULLABLE"); + switch (mode) { case "REQUIRED": return convertRequiredField(schema.getType(), fieldSchema, v); case "REPEATED": @@ -264,6 +270,8 @@ private static Object convertRequiredField( .put("TIMESTAMP", Type.LONG) .put("RECORD", Type.RECORD) .build(); + // Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the type field + // is required, so it may not be null. String bqType = fieldSchema.getType(); Type expectedAvroType = fieldMap.get(bqType); verify( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java index 28bd98adc7..d03ac89eab 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java @@ -112,12 +112,20 @@ public void testConvertGenericRecordToTableRow() throws Exception { TableSchema tableSchema = new TableSchema(); List subFields = Lists.newArrayList( new TableFieldSchema().setName("species").setType("STRING").setMode("NULLABLE")); + /* + * Note that the quality and quantity fields do not have their mode set, so they should default + * to NULLABLE. This is an important test of BigQuery semantics. + * + * All the other fields we set in this function are required on the Schema response. + * + * See https://cloud.google.com/bigquery/docs/reference/v2/tables#schema + */ List fields = Lists.newArrayList( new TableFieldSchema().setName("number").setType("INTEGER").setMode("REQUIRED"), new TableFieldSchema().setName("species").setType("STRING").setMode("NULLABLE"), - new TableFieldSchema().setName("quality").setType("FLOAT").setMode("NULLABLE"), - new TableFieldSchema().setName("quantity").setType("INTEGER").setMode("NULLABLE"), + new TableFieldSchema().setName("quality").setType("FLOAT") /* default to NULLABLE */, + new TableFieldSchema().setName("quantity").setType("INTEGER") /* default to NULLABLE */, new TableFieldSchema().setName("birthday").setType("TIMESTAMP").setMode("NULLABLE"), new TableFieldSchema().setName("flighted").setType("BOOLEAN").setMode("NULLABLE"), new TableFieldSchema().setName("scion").setType("RECORD").setMode("NULLABLE") From d476d5b76109bf3c20e05dfe3155d7520d335e4a Mon Sep 17 00:00:00 2001 From: hdeist Date: Tue, 2 Feb 2016 16:14:43 -0800 Subject: [PATCH 069/751] Add ByteCount for BigQueryIO streaming write Currently a system Counter called ByteCount is generated when writing to BigQuery in non-streaming mode, but not in streaming mode. This change uses an Aggregator in BigQueryTableInserter to track bytes streamed to BigQuery and expose it as the ByteCount Counter. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113688829 --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 10 ++++- .../sdk/util/BigQueryTableInserter.java | 16 +++++--- .../dataflow/sdk/util/BigQueryUtilTest.java | 38 ++++++++++++++++++- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 6a56a81a98..ab7df6f081 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -37,15 +37,18 @@ import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.Reshuffle; +import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; @@ -1053,6 +1056,7 @@ private static void verifyTablePresence(BigQueryOptions options, TableReference /** * Implementation of DoFn to perform streaming BigQuery write. */ + @SystemDoFnInternal private static class StreamingWriteFn extends DoFn, TableRowInfo>, Void> { /** TableSchema in JSON. Use String to make the class Serializable. */ @@ -1069,6 +1073,10 @@ private static class StreamingWriteFn private static Set createdTables = Collections.newSetFromMap(new ConcurrentHashMap()); + /** Tracks bytes written, exposed as "ByteCount" Counter. */ + private Aggregator byteCountAggregator = + createAggregator("ByteCount", new Sum.SumLongFn()); + /** Constructor. */ StreamingWriteFn(TableSchema schema) { try { @@ -1138,7 +1146,7 @@ private void flushRows(Bigquery client, TableReference tableReference, if (!tableRows.isEmpty()) { try { BigQueryTableInserter inserter = new BigQueryTableInserter(client); - inserter.insertAll(tableReference, tableRows, uniqueIds); + inserter.insertAll(tableReference, tableRows, uniqueIds, byteCountAggregator); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java index bcd972034a..cd51062756 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java @@ -31,6 +31,7 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; @@ -136,7 +137,7 @@ public BigQueryTableInserter(Bigquery client, TableReference defaultRef, int max */ @Deprecated public void insertAll(List rowList) throws IOException { - insertAll(defaultRef, rowList, null); + insertAll(defaultRef, rowList, null, null); } /** @@ -147,21 +148,23 @@ public void insertAll(List rowList) throws IOException { @Deprecated public void insertAll(List rowList, @Nullable List insertIdList) throws IOException { - insertAll(defaultRef, rowList, insertIdList); + insertAll(defaultRef, rowList, insertIdList, null); } /** * Insert all rows from the given list. */ public void insertAll(TableReference ref, List rowList) throws IOException { - insertAll(ref, rowList, null); + insertAll(ref, rowList, null, null); } /** - * Insert all rows from the given list using specified insertIds if not null. + * Insert all rows from the given list using specified insertIds if not null. Track count of + * bytes written with the Aggregator. */ public void insertAll(TableReference ref, List rowList, - @Nullable List insertIdList) throws IOException { + @Nullable List insertIdList, Aggregator byteCountAggregator) + throws IOException { Preconditions.checkNotNull(ref, "ref"); if (insertIdList != null && rowList.size() != insertIdList.size()) { throw new AssertionError("If insertIdList is not null it needs to have at least " @@ -217,6 +220,9 @@ public List call() throws IOException { })); strideIndices.add(strideIndex); + if (byteCountAggregator != null) { + byteCountAggregator.addValue(Long.valueOf(dataSize)); + } dataSize = 0; strideIndex = i + 1; rows = new LinkedList<>(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java index 99dad0f541..fab4aecb47 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java @@ -40,6 +40,9 @@ import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; import com.google.cloud.dataflow.sdk.io.BigQueryIO; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.common.collect.ImmutableList; import org.hamcrest.Matchers; @@ -432,14 +435,45 @@ public void testInsertAll() throws Exception, IOException { List rows = new ArrayList<>(); List ids = new ArrayList<>(); for (int i = 0; i < 25; ++i) { - rows.add(new TableRow()); + rows.add(rawRow("foo", 1234)); ids.add(new String()); } + InMemoryLongSumAggregator byteCountAggregator = new InMemoryLongSumAggregator("ByteCount"); try { - inserter.insertAll(ref, rows, ids); + inserter.insertAll(ref, rows, ids, byteCountAggregator); } finally { verifyInsertAll(5); + // Each of the 25 rows is 23 bytes: "{f=[{v=foo}, {v=1234}]}" + assertEquals("Incorrect byte count", 25L * 23L, byteCountAggregator.getSum()); + } + } + + private static class InMemoryLongSumAggregator implements Aggregator { + private final String name; + private long sum = 0; + + public InMemoryLongSumAggregator(String name) { + this.name = name; + } + + @Override + public void addValue(Long value) { + sum += value; + } + + @Override + public String getName() { + return name; + } + + @Override + public CombineFn getCombineFn() { + return new Sum.SumLongFn(); + } + + public long getSum() { + return sum; } } } From 4dce3c25d4c4920cb8c369ee31fb22ec0b5cd045 Mon Sep 17 00:00:00 2001 From: sgmc Date: Tue, 2 Feb 2016 20:24:06 -0800 Subject: [PATCH 070/751] Default to exporting BigQuery files in Avro format ----Release Notes---- Greatly increases the efficiency of the BigQuery source by using Avro instead of JSON as an export format. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113705731 --- .../dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java index d6856633dd..538901c722 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java @@ -49,6 +49,7 @@ public void translate( // Actual translation. context.addStep(transform, "ParallelRead"); context.addInput(PropertyNames.FORMAT, "bigquery"); + context.addInput(PropertyNames.BIGQUERY_EXPORT_FORMAT, "FORMAT_AVRO"); if (transform.getQuery() != null) { context.addInput(PropertyNames.BIGQUERY_QUERY, transform.getQuery()); From ad6060958127914e48b8670e8328b0217d3c886f Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 3 Feb 2016 17:00:02 -0800 Subject: [PATCH 071/751] Add InProcessPipelineRunner, Evaluation Interfaces These interfaces are the requirements for a Streamier DirectPipelineRunner. Implement transform primitives Implement InProcessCreate as a PTransform that uses a Bounded Source. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113798889 --- sdk/pom.xml | 5 +- .../inprocess/InProcessPipelineOptions.java | 24 ++ .../inprocess/InProcessPipelineRunner.java | 241 ++++++++++++++++++ .../inprocess/InProcessTransformResult.java | 51 ++++ .../runners/inprocess/TransformEvaluator.java | 45 ++++ .../inprocess/TransformEvaluatorFactory.java | 41 +++ .../BoundedReadEvaluatorFactory.java | 114 +++++++++ .../inprocess/evaluator/EvaluatorKey.java | 56 ++++ .../evaluator/FlattenEvaluatorFactory.java | 79 ++++++ .../evaluator/GroupByKeyEvaluatorFactory.java | 164 ++++++++++++ .../inprocess/evaluator/InProcessCreate.java | 169 ++++++++++++ .../evaluator/ParDoInProcessEvaluator.java | 84 ++++++ .../evaluator/ParDoMultiEvaluatorFactory.java | 104 ++++++++ .../ParDoSingleEvaluatorFactory.java | 99 +++++++ .../UnboundedReadEvaluatorFactory.java | 124 +++++++++ .../evaluator/ViewEvaluatorFactory.java | 73 ++++++ .../ImmutableInProcessTransformResult.java | 112 ++++++++ .../inprocess/util/InProcessBundle.java | 98 +++++++ .../cloud/dataflow/sdk/transforms/ParDo.java | 4 + .../BoundedReadEvaluatorFactoryTest.java | 106 ++++++++ .../FlattenEvaluatorFactoryTest.java | 109 ++++++++ .../GroupByKeyEvaluatorFactoryTest.java | 155 +++++++++++ .../evaluator/InProcessCreateTest.java | 73 ++++++ .../ParDoMultiEvaluatorFactoryTest.java | 138 ++++++++++ .../ParDoSingleEvaluatorFactoryTest.java | 95 +++++++ .../UnboundedReadEvaluatorFactoryTest.java | 127 +++++++++ .../evaluator/ViewEvaluatorFactoryTest.java | 79 ++++++ .../inprocess/util/InProcessBundleTest.java | 102 ++++++++ 28 files changed, 2668 insertions(+), 3 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/EvaluatorKey.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreate.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreateTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java diff --git a/sdk/pom.xml b/sdk/pom.xml index 4e6cb6c777..2c8b52b638 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -214,15 +214,14 @@ - org.apache.maven.plugins - maven-javadoc-plugin + org.apache.maven.plugins maven-javadoc-plugin Google Cloud Dataflow SDK ${project.version} API Google Cloud Dataflow SDK for Java, version ${project.version} ../javadoc/overview.html com.google.cloud.dataflow.sdk - -exclude com.google.cloud.dataflow.sdk.runners.worker:com.google.cloud.dataflow.sdk.runners.dataflow:com.google.cloud.dataflow.sdk.util ${dataflow.javadoc_opts} + -exclude com.google.cloud.dataflow.sdk.runners.worker:com.google.cloud.dataflow.sdk.runners.dataflow:com.google.cloud.dataflow.sdk.util:com.google.cloud.dataflow.sdk.runners.inprocess ${dataflow.javadoc_opts} false true ]]> diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java new file mode 100644 index 0000000000..d659d962f0 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; + +/** + * Options that can be used to configure the {@link InProcessPipelineRunner}. + */ +public interface InProcessPipelineOptions extends PipelineOptions {} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java new file mode 100644 index 0000000000..399d1c85a2 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -0,0 +1,241 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.SideInputReader; +import com.google.cloud.dataflow.sdk.util.TimerInternals; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; +import com.google.cloud.dataflow.sdk.util.state.StateInternals; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.annotation.Nullable; + +/** + * An In-Memory implementation of the Dataflow Programming Model. Supports Unbounded + * {@link PCollection PCollections}. + */ +@Experimental +public class InProcessPipelineRunner { + private static Map, TransformEvaluatorFactory> defaultEvaluatorFactories = + new ConcurrentHashMap<>(); + + /** + * Register a default transform evaluator. + */ + public static > void registerTransformEvaluatorFactory( + Class clazz, TransformEvaluatorFactory evaluator) { + checkArgument(defaultEvaluatorFactories.put(clazz, evaluator) == null, + "Defining a default factory %s to evaluate Transforms of type %s multiple times", evaluator, + clazz); + } + + /** + * Part of a {@link PCollection}. Elements are output to a bundle, which will cause them to be + * executed by {@link PTransform PTransforms} that consume the {@link PCollection} this bundle is + * a part of at a later point. + * @param + */ + public static interface Bundle { + /** + * Outputs an element to this bundle. + * + * @param element the element to add to this bundle + * @return this bundle + */ + Bundle add(WindowedValue element); + + /** + * @return the PCollection that the elements of this bundle belong to + */ + PCollection getPCollection(); + + /** + * Returns weather this bundle is keyed. A bundle that is part of a {@link PCollection} that + * occurs after a {@link GroupByKey} is keyed by the result of the last {@link GroupByKey}. + */ + boolean isKeyed(); + + /** + * Returns the (possibly null) key that was output in the most recent {@link GroupByKey} in the + * execution of this bundle. + */ + @Nullable Object getKey(); + + /** + * @return an {@link Iterable} containing all of the elements that have been added to this + * {@link Bundle} + */ + Iterable> getElements(); + } + + /** + * A {@link PCollectionViewWriter} is responsible for writing contents of a {@link PCollection} to + * a storage mechanism that can be read from while constructing a {@link PCollectionView}. + * @param the type of elements the input {@link PCollection} contains. + * @param the type of the PCollectionView this writer writes to. + */ + public static interface PCollectionViewWriter { + void add(Iterable> values); + } + + /** + * Execution Context for the InMemoryPipelineRunner. + * + * This implementation is not thread safe. A new InMemoryExecutionContext must be created for each + * thread that requires it. + */ + public static class InProcessExecutionContext + extends com.google.cloud.dataflow.sdk.util.BaseExecutionContext { + @Override + protected InMemoryStepContext createStepContext( + String stepName, String transformName, StateSampler stateSampler) { + return new InMemoryStepContext(this, stepName, transformName); + } + + /** + * Step Context for the InMemoryPipelineRunner. + */ + public class InMemoryStepContext + extends com.google.cloud.dataflow.sdk.util.BaseExecutionContext.StepContext { + public InMemoryStepContext( + InProcessExecutionContext executionContext, String stepName, String transformName) { + super(executionContext, stepName, transformName); + } + + @Override + public StateInternals stateInternals() { + // TODO get or create state for current key. + throw new UnsupportedOperationException("StateInternals not yet meaningfully supported"); + } + + @Override + public TimerInternals timerInternals() { + // TODO: Have the executionContext/evaluationContext pass this in + throw new UnsupportedOperationException("TimerInternals not yet meaningfully supported"); + } + } + + } + + + /** + * The evaluation context for the {@link InProcessPipelineRunner}. Contains state shared within + * the current evaluation. + */ + public static interface InProcessEvaluationContext { + /** + * Create a bundle for use by a source. + */ + Bundle createRootBundle(PCollection output); + + /** + * Create a {@link Bundle} whose elements belong to the specified {@link PCollection}. + */ + Bundle createBundle(Bundle input, PCollection output); + + /** + * Create a {@link Bundle} with the specified keys at the specified step. For use by + * {@link GroupByKeyOnly} {@link PTransform PTransforms}. + */ + Bundle createKeyedBundle(Bundle input, Object key, PCollection output); + + /** + * Create a bundle whose elements will be used in a PCollectionView. + */ + PCollectionViewWriter createPCollectionViewWriter( + PCollection input, PCollectionView output); + + /** + * Get the options used by this {@link Pipeline}. + */ + InProcessPipelineOptions getPipelineOptions(); + + /** + * Get an {@link ExecutionContext} for the provided application. + */ + InProcessExecutionContext getExecutionContext(AppliedPTransform application); + + /** + * Get the Step Name for the provided application. + */ + String getStepName(AppliedPTransform application); + + /** + * @param sideInputs the {@link PCollectionView PCollectionViews} the result should be able to + * read + * @return a {@link SideInputReader} that can read all of the provided + * {@link PCollectionView PCollectionViews} + */ + SideInputReader createSideInputReader(List> sideInputs); + + /** + * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent + * of all other {@link CounterSet CounterSets} created by this call. + * + * The {@link InProcessEvaluationContext} is responsible for unifying the counters present in + * all created {@link CounterSet CounterSets} when the transforms that call this method + * complete. + */ + CounterSet createCounterSet(); + + /** + * Returns all of the counters that have been merged into this context via calls to + * {@link CounterSet#merge(CounterSet)}. + */ + CounterSet getCounters(); + } + + /** + * An executor that schedules and executes {@link AppliedPTransform AppliedPTransforms} for both + * source and intermediate {@link PTransform PTransforms}. + */ + public static interface InProcessExecutor { + /** + * @param root the root {@link AppliedPTransform} to schedule + */ + void scheduleRoot(AppliedPTransform root); + + /** + * @param consumer the {@link AppliedPTransform} to schedule + * @param bundle the input bundle to the consumer + */ + void scheduleConsumption(AppliedPTransform consumer, Bundle bundle); + + /** + * Blocks until the job being executed enters a terminal state. A job is completed after all + * root {@link AppliedPTransform AppliedPTransforms} have completed, and all + * {@link Bundle Bundles} have been consumed. Jobs may also terminate abnormally. + */ + void awaitCompletion(); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java new file mode 100644 index 0000000000..aad0c7613f --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; + +import org.joda.time.Instant; + +import javax.annotation.Nullable; + +/** + * The result of evaluating an {@link AppliedPTransform} with a {@link TransformEvaluator}. + */ +public interface InProcessTransformResult { + /** + * @return the {@link AppliedPTransform} that produced this result + */ + AppliedPTransform getTransform(); + + /** + * @return the {@link Bundle Bundles} produced by this transform + */ + Iterable> getBundles(); + + /** + * @return the {@link CounterSet} used by this {@link PTransform}, or null if this transform did + * not use a {@link CounterSet} + */ + @Nullable CounterSet getCounters(); + + /** + * @return the Watermark Hold for the transform at the time this result was produced + */ + Instant getWatermarkHold(); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java new file mode 100644 index 0000000000..c8bccb3596 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.util.WindowedValue; + +/** + * An evaluator of a specific application of a transform. Will be used for at least one + * {@link Bundle}. + * + * @param the type of elements that will be passed to {@link #processElement} + */ +public interface TransformEvaluator { + /** + * Process an element in the input {@link Bundle}. + * + * @param element the element to process + */ + void processElement(WindowedValue element) throws Exception; + + /** + * Finish processing the bundle of this {@link TransformEvaluator}. + * + * After {@link #finishBundle()} is called, the {@link TransformEvaluator} will not be reused, + * and no more elements will be processed. + * + * @return an {@link InProcessTransformResult} containing the results of this bundle evaluation. + */ + InProcessTransformResult finishBundle() throws Exception; +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java new file mode 100644 index 0000000000..25cb6cc30c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.PTransform; + +import javax.annotation.Nullable; + +/** + * A factory for creating instances of {@link TransformEvaluator} for the application of a + * {@link PTransform}. + */ +public interface TransformEvaluatorFactory { + /** + * Create a new {@link TransformEvaluator} for the application of the {@link PTransform}. + * + * Any work that must be done before input elements are processed (such as calling + * {@link DoFn#startBundle(DoFn.Context)}) must be done before the {@link TransformEvaluator} is + * made available to the caller. + */ + TransformEvaluator forApplication( + AppliedPTransform application, @Nullable Bundle inputBundle, + InProcessEvaluationContext evaluationContext); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java new file mode 100644 index 0000000000..bffaeea974 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.io.Read.Bounded; +import com.google.cloud.dataflow.sdk.io.Source.Reader; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.annotation.Nullable; + +/** + * A {@link TransformEvaluatorFactory} that produces {@link TransformEvaluator TransformEvaluators} + * for the {@link Bounded Read.Bounded} primitive {@link PTransform}. + */ +public class BoundedReadEvaluatorFactory implements TransformEvaluatorFactory { + /* + * An evaluator for a Source is stateful, to ensure data is not read multiple times. + * Evaluators are cached here to ensure that the reader is not restarted if the evaluator is + * retriggered. + */ + private final Map> sourceEvaluators = + new ConcurrentHashMap<>(); + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + @Nullable Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + return getTransformEvaluator((AppliedPTransform) application, evaluationContext); + } + + private TransformEvaluator getTransformEvaluator( + final AppliedPTransform, Bounded> transform, + final InProcessEvaluationContext evaluationContext) { + EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); + @SuppressWarnings("unchecked") + BoundedReadEvaluator result = + (BoundedReadEvaluator) sourceEvaluators.get(key); + if (result == null) { + try { + result = new BoundedReadEvaluator(transform, evaluationContext); + } catch (IOException e) { + throw new RuntimeException(e); + } + sourceEvaluators.put(key, result); + } + return result; + } + + private static class BoundedReadEvaluator implements TransformEvaluator { + private final AppliedPTransform, Bounded> transform; + private final InProcessEvaluationContext evaluationContext; + private final Reader reader; + private boolean contentsRemaining; + + public BoundedReadEvaluator( + AppliedPTransform, Bounded> transform, + InProcessEvaluationContext evaluationContext) + throws IOException { + this.transform = transform; + this.evaluationContext = evaluationContext; + reader = + transform.getTransform().getSource().createReader(evaluationContext.getPipelineOptions()); + contentsRemaining = reader.start(); + } + + @Override + public void processElement(WindowedValue element) {} + + @Override + public InProcessTransformResult finishBundle() throws IOException { + Bundle output = evaluationContext.createRootBundle(transform.getOutput()); + while (contentsRemaining) { + output.add( + WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp())); + contentsRemaining = reader.advance(); + } + return ImmutableInProcessTransformResult + .withHold(transform, BoundedWindow.TIMESTAMP_MAX_VALUE) + .addOutput(output) + .build(); + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/EvaluatorKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/EvaluatorKey.java new file mode 100644 index 0000000000..5f7ff6a6a3 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/EvaluatorKey.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; + +import java.util.Objects; + +/** + * A (Transform, Pipeline Execution) key for stateful evaluators. + * + * Source evaluators are stateful to ensure data is not read multiple times. Evaluators are cached + * to ensure that the reader is not restarted if the evaluator is retriggered. An + * {@link EvaluatorKey} is used to ensure that multiple Pipelines can be executed without sharing + * the same evaluators. + */ +final class EvaluatorKey { + private final AppliedPTransform transform; + private final InProcessEvaluationContext context; + + public EvaluatorKey(AppliedPTransform transform, InProcessEvaluationContext context) { + this.transform = transform; + this.context = context; + } + + @Override + public int hashCode() { + return Objects.hash(transform, context); + } + + @Override + public boolean equals(Object other) { + if (other == null || !(other instanceof EvaluatorKey)) { + return false; + } + EvaluatorKey that = (EvaluatorKey) other; + return Objects.equals(this.transform, that.transform) + && Objects.equals(this.context, that.context); + } +} + + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java new file mode 100644 index 0000000000..61ccc5e152 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; + +/** + * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the {@link Flatten} + * {@link PTransform}. + */ +public class FlattenEvaluatorFactory implements TransformEvaluatorFactory { + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + return createInMemoryEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); + } + + private TransformEvaluator createInMemoryEvaluator( + final AppliedPTransform< + PCollectionList, PCollection, FlattenPCollectionList> + application, + final Bundle inputBundle, + final InProcessEvaluationContext evaluationContext) { + final Bundle outputBundle = + evaluationContext.createBundle(inputBundle, application.getOutput()); + final InProcessTransformResult result = + ImmutableInProcessTransformResult.withoutHold(application).addOutput(outputBundle).build(); + return new FlattenEvaluator<>(outputBundle, result); + } + + private static class FlattenEvaluator implements TransformEvaluator { + private final Bundle outputBundle; + private final InProcessTransformResult result; + + public FlattenEvaluator(Bundle outputBundle, InProcessTransformResult result) { + this.outputBundle = outputBundle; + this.result = result; + } + + @Override + public void processElement(WindowedValue element) { + outputBundle.add(element); + } + + @Override + public InProcessTransformResult finishBundle() { + return result; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java new file mode 100644 index 0000000000..f5cf86186f --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult.Builder; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the {@link GroupByKey} + * {@link PTransform}. + */ +public class GroupByKeyEvaluatorFactory implements TransformEvaluatorFactory { + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public TransformEvaluator forApplication( + AppliedPTransform application, + Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + return createEvaluator( + (AppliedPTransform) application, (Bundle) inputBundle, evaluationContext); + } + + private TransformEvaluator> createEvaluator( + final AppliedPTransform< + PCollection>, PCollection>>, GroupByKeyOnly> + application, + final Bundle> inputBundle, + final InProcessEvaluationContext evaluationContext) { + return new GroupByKeyEvaluator(evaluationContext, inputBundle, application); + } + + private static class GroupByKeyEvaluator implements TransformEvaluator> { + private final InProcessEvaluationContext evaluationContext; + + private final Bundle> inputBundle; + private final AppliedPTransform< + PCollection>, PCollection>>, GroupByKeyOnly> + application; + private final Coder keyCoder; + private Map, List> groupingMap; + + public GroupByKeyEvaluator( + InProcessEvaluationContext evaluationContext, + Bundle> inputBundle, + AppliedPTransform< + PCollection>, PCollection>>, GroupByKeyOnly> + application) { + this.evaluationContext = evaluationContext; + this.inputBundle = inputBundle; + this.application = application; + + PCollection> input = application.getInput(); + keyCoder = getKeyCoder(input.getCoder()); + groupingMap = new HashMap<>(); + } + + private Coder getKeyCoder(Coder> coder) { + if (!(coder instanceof KvCoder)) { + throw new IllegalStateException(); + } + @SuppressWarnings("unchecked") + Coder keyCoder = ((KvCoder) coder).getKeyCoder(); + return keyCoder; + } + + @Override + public void processElement(WindowedValue> element) { + KV kv = element.getValue(); + K key = kv.getKey(); + byte[] encodedKey; + try { + encodedKey = encodeToByteArray(keyCoder, key); + } catch (CoderException exn) { + // TODO: Put in better element printing: + // truncate if too long. + throw new IllegalArgumentException( + String.format("unable to encode key %s of input to %s using %s", key, this, keyCoder), + exn); + } + GroupingKey groupingKey = new GroupingKey<>(key, encodedKey); + if (!groupingMap.containsKey(groupingKey)) { + groupingMap.put(groupingKey, new ArrayList()); + } + List values = groupingMap.get(groupingKey); + values.add(kv.getValue()); + } + + @Override + public InProcessTransformResult finishBundle() { + Builder resultBuilder = ImmutableInProcessTransformResult.withoutHold(application); + for (Map.Entry, List> groupedEntry : groupingMap.entrySet()) { + K key = groupedEntry.getKey().key; + KV> groupedKv = KV.>of(key, groupedEntry.getValue()); + Bundle>> bundle = + evaluationContext.createKeyedBundle(inputBundle, key, application.getOutput()); + bundle.add(WindowedValue.valueInEmptyWindows(groupedKv)); + resultBuilder.addOutput(bundle); + } + return resultBuilder.build(); + } + + private static class GroupingKey { + private K key; + private byte[] encodedKey; + + public GroupingKey(K key, byte[] encodedKey) { + this.key = key; + this.encodedKey = encodedKey; + } + + @Override + public boolean equals(Object o) { + if (o instanceof GroupingKey) { + GroupingKey that = (GroupingKey) o; + return Arrays.equals(this.encodedKey, that.encodedKey); + } else { + return false; + } + } + + @Override + public int hashCode() { + return Arrays.hashCode(encodedKey); + } + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreate.java new file mode 100644 index 0000000000..cdd1b01d82 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreate.java @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.Create.Values; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.collect.Iterators; +import com.google.common.collect.PeekingIterator; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; + +/** + * An in memory implementation of the {@link Values Create.Values} {@link PTransform}, implemented' + * using a {@link BoundedSource}. + * + * The coder is inferred via the {@link Values#getDefaultOutputCoder(PInput)} method on the original + * transform. + */ +public class InProcessCreate extends PTransform> { + private final Create.Values original; + private final InMemorySource source; + + public static InProcessCreate from(Create.Values original) { + return new InProcessCreate<>(original); + } + + private InProcessCreate(Values original) { + this.original = original; + this.source = new InMemorySource<>(original.getElements()); + } + + @Override + public PCollection apply(PInput input) { + input.getPipeline().getCoderRegistry(); + PCollection result = input.getPipeline().apply(Read.from(source)); + try { + result.setCoder(original.getDefaultOutputCoder(input)); + } catch (CannotProvideCoderException e) { + throw new IllegalArgumentException("Unable to infer a coder and no Coder was specified. " + + "Please set a coder by invoking Create.withCoder() explicitly.", e); + } + return result; + } + + private static class InMemorySource extends BoundedSource { + private final Iterable elements; + + public InMemorySource(Iterable elements) { + this.elements = elements; + } + + @Override + public List> splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + return Collections.singletonList(this); + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + return 0L; + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return false; + } + + @Override + public BoundedSource.BoundedReader createReader(PipelineOptions options) throws IOException { + return new IterableReader(); + } + + @Override + public void validate() {} + + @Override + public Coder getDefaultOutputCoder() { + // Return a coder that exclusively throws exceptions. The coder is set properly in apply, or + // an illegal argument exception is thrown. + return new StandardCoder() { + @Override + public void encode(T value, OutputStream outStream, + com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + throw new CoderException("Default Create Coder cannot be used"); + } + + @Override + public T decode( + InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + throw new CoderException("Default Create Coder cannot be used"); + } + + @Override + public List> getCoderArguments() { + return Collections.emptyList(); + } + + @Override + public void verifyDeterministic() + throws com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException { + throw new NonDeterministicException( + this, Collections.singletonList("Default Create Coder cannot be used")); + } + }; + } + + private class IterableReader extends BoundedReader { + private final PeekingIterator iter; + + public IterableReader() { + this.iter = Iterators.peekingIterator(elements.iterator()); + } + + @Override + public BoundedSource getCurrentSource() { + return InMemorySource.this; + } + + @Override + public boolean start() throws IOException { + return iter.hasNext(); + } + + @Override + public boolean advance() throws IOException { + iter.next(); + return iter.hasNext(); + } + + @Override + public T getCurrent() throws NoSuchElementException { + return iter.peek(); + } + + @Override + public void close() throws IOException {} + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java new file mode 100644 index 0000000000..86cc89ce4c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TupleTag; + +import org.joda.time.Instant; + +import java.util.Collection; +import java.util.Map; + +class ParDoInProcessEvaluator { + private final DoFnRunner fnRunner; + private final AppliedPTransform, ?, ?> transform; + private final CounterSet counters; + private final Collection> outputBundles; + + public ParDoInProcessEvaluator(DoFnRunner fnRunner, + AppliedPTransform, ?, ?> transform, CounterSet counters, + Collection> outputBundles) { + this.fnRunner = fnRunner; + this.transform = transform; + this.counters = counters; + this.outputBundles = outputBundles; + } + + public void processElement(WindowedValue element) { + fnRunner.processElement(element); + } + + public InProcessTransformResult finishBundle() { + fnRunner.finishBundle(); + // TODO Use a real value + Instant hold = BoundedWindow.TIMESTAMP_MAX_VALUE; + return ImmutableInProcessTransformResult.withHold(transform, hold) + .addOutput(outputBundles) + .withCounters(counters) + .build(); + } + + static class BundleOutputManager implements OutputManager { + private final Map, Bundle> bundles; + + public static BundleOutputManager create(Map, Bundle> outputBundles) { + return new BundleOutputManager(outputBundles); + } + + public BundleOutputManager(Map, Bundle> bundles) { + this.bundles = bundles; + } + + @SuppressWarnings("unchecked") + @Override + public void output(TupleTag tag, WindowedValue output) { + @SuppressWarnings("rawtypes") + Bundle bundle = bundles.get(tag); + bundle.add(output); + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java new file mode 100644 index 0000000000..3b2309e1c4 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InMemoryStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.evaluator.ParDoInProcessEvaluator.BundleOutputManager; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti; +import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionTuple; +import com.google.cloud.dataflow.sdk.values.TupleTag; + +import java.util.HashMap; +import java.util.Map; + +/** + * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the + * {@link BoundMulti} primitive {@link PTransform}. + */ +public class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory { + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + @SuppressWarnings({"unchecked", "rawtypes"}) + final ParDoInProcessEvaluator multiEvaluator = + createMultiEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); + return new TransformEvaluator() { + @Override + public void processElement(WindowedValue value) { + multiEvaluator.processElement(value); + } + + @Override + public InProcessTransformResult finishBundle() { + return multiEvaluator.finishBundle(); + } + }; + } + + private static ParDoInProcessEvaluator createMultiEvaluator( + AppliedPTransform, PCollectionTuple, BoundMulti> application, + Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + PCollectionTuple output = application.getOutput(); + Map, PCollection> outputs = output.getAll(); + Map, Bundle> outputBundles = new HashMap<>(); + for (Map.Entry, PCollection> outputEntry : outputs.entrySet()) { + outputBundles.put( + outputEntry.getKey(), + evaluationContext.createBundle(inputBundle, outputEntry.getValue())); + } + InProcessExecutionContext executionContext = evaluationContext.getExecutionContext(application); + String stepName = evaluationContext.getStepName(application); + InMemoryStepContext stepContext = + executionContext.getOrCreateStepContext(stepName, stepName, null); + + CounterSet counters = evaluationContext.createCounterSet(); + + DoFn fn = application.getTransform().getFn(); + DoFnRunner runner = + DoFnRunners.createDefault( + evaluationContext.getPipelineOptions(), + fn, + evaluationContext.createSideInputReader(application.getTransform().getSideInputs()), + BundleOutputManager.create(outputBundles), + application.getTransform().getMainOutputTag(), + application.getTransform().getSideOutputTags().getAll(), + stepContext, + counters.getAddCounterMutator(), + application.getInput().getWindowingStrategy()); + + runner.startBundle(); + + return new ParDoInProcessEvaluator<>(runner, application, counters, outputBundles.values()); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java new file mode 100644 index 0000000000..33144e7b67 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InMemoryStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.evaluator.ParDoInProcessEvaluator.BundleOutputManager; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; +import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TupleTag; + +import java.util.Collections; + +/** + * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the + * {@link Bound ParDo.Bound} primitive {@link PTransform}. + */ +public class ParDoSingleEvaluatorFactory implements TransformEvaluatorFactory { + @Override + public TransformEvaluator forApplication( + final AppliedPTransform application, + Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + @SuppressWarnings({"unchecked", "rawtypes"}) + final ParDoInProcessEvaluator evaluator = + createSingleEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); + TransformEvaluator singleEvaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue value) { + evaluator.processElement(value); + } + + @Override + public InProcessTransformResult finishBundle() { + return evaluator.finishBundle(); + } + }; + return singleEvaluator; + } + + private static ParDoInProcessEvaluator createSingleEvaluator( + @SuppressWarnings("rawtypes") + AppliedPTransform, PCollection, Bound> application, + Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + TupleTag mainOutputTag = new TupleTag<>("out"); + Bundle outputBundle = evaluationContext.createBundle(inputBundle, application.getOutput()); + + InProcessExecutionContext executionContext = evaluationContext.getExecutionContext(application); + String stepName = evaluationContext.getStepName(application); + InMemoryStepContext stepContext = + executionContext.getOrCreateStepContext(stepName, stepName, null); + + CounterSet counters = evaluationContext.createCounterSet(); + + DoFnRunner runner = + DoFnRunners.createDefault( + evaluationContext.getPipelineOptions(), + application.getTransform().getFn(), + evaluationContext.createSideInputReader(application.getTransform().getSideInputs()), + BundleOutputManager.create( + Collections., Bundle>singletonMap(mainOutputTag, outputBundle)), + mainOutputTag, + Collections.>emptyList(), + stepContext, + counters.getAddCounterMutator(), + application.getInput().getWindowingStrategy()); + + runner.startBundle(); + return new ParDoInProcessEvaluator( + runner, application, counters, Collections.>singleton(outputBundle)); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java new file mode 100644 index 0000000000..9a5e3aa694 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.io.Read.Unbounded; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; +import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.Nullable; + +/** + * A {@link TransformEvaluatorFactory} that produces {@link TransformEvaluator TransformEvaluators} + * for the {@link Unbounded Read.Unbounded} primitive {@link PTransform}. + */ +public class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { + /* + * An evaluator for a Source is stateful, to ensure the CheckpointMark is properly persisted. + * Evaluators are cached here to ensure that the checkpoint mark is appropriately reused + * and any splits are honored. + */ + private final Map> sourceEvaluators = new HashMap<>(); + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + @Nullable Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + return getTransformEvaluator((AppliedPTransform) application, evaluationContext); + } + + private TransformEvaluator getTransformEvaluator( + final AppliedPTransform, Unbounded> transform, + final InProcessEvaluationContext evaluationContext) { + EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); + @SuppressWarnings("unchecked") + UnboundedReadEvaluator result = + (UnboundedReadEvaluator) sourceEvaluators.get(key); + if (result == null) { + result = new UnboundedReadEvaluator(transform, evaluationContext); + sourceEvaluators.put(key, result); + } + return result; + } + + private static class UnboundedReadEvaluator implements TransformEvaluator { + private static final int ARBITRARY_MAX_ELEMENTS = 10; + private final AppliedPTransform, Unbounded> transform; + private final InProcessEvaluationContext evaluationContext; + private CheckpointMark checkpointMark; + + public UnboundedReadEvaluator( + AppliedPTransform, Unbounded> transform, + InProcessEvaluationContext evaluationContext) { + this.transform = transform; + this.evaluationContext = evaluationContext; + this.checkpointMark = null; + } + + @Override + public void processElement(WindowedValue element) {} + + @Override + public InProcessTransformResult finishBundle() throws IOException { + Bundle output = evaluationContext.createRootBundle(transform.getOutput()); + UnboundedReader reader = + createReader( + transform.getTransform().getSource(), evaluationContext.getPipelineOptions()); + int numElements = 0; + if (reader.start()) { + do { + output.add( + WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp())); + numElements++; + } while (numElements < ARBITRARY_MAX_ELEMENTS && reader.advance()); + } + checkpointMark = reader.getCheckpointMark(); + checkpointMark.finalizeCheckpoint(); + // TODO: When exercising create initial splits, make this the minimum across all existing + // readers + return ImmutableInProcessTransformResult.withHold(transform, reader.getWatermark()) + .addOutput(output) + .build(); + } + + private UnboundedReader createReader( + UnboundedSource source, PipelineOptions options) { + @SuppressWarnings("unchecked") + CheckpointMarkT mark = (CheckpointMarkT) checkpointMark; + return source.createReader(options, mark); + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java new file mode 100644 index 0000000000..c9f26db929 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; + +import java.util.ArrayList; +import java.util.List; + +/** + * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the + * {@link CreatePCollectionView} primitive {@link PTransform}. + */ +public class ViewEvaluatorFactory implements TransformEvaluatorFactory { + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + InProcessPipelineRunner.Bundle inputBundle, + InProcessEvaluationContext evaluationContext) { + return createEvaluator( + (AppliedPTransform) application, evaluationContext); + } + + private TransformEvaluator createEvaluator( + final AppliedPTransform, PCollectionView, + CreatePCollectionView> application, + InProcessEvaluationContext context) { + PCollection input = application.getInput(); + final PCollectionViewWriter writer = + context.createPCollectionViewWriter(input, application.getOutput()); + return new TransformEvaluator() { + private final List> elements = new ArrayList<>(); + + @Override + public void processElement(WindowedValue element) { + elements.add(element); + } + + @Override + public InProcessTransformResult finishBundle() { + writer.add(elements); + return ImmutableInProcessTransformResult.withoutHold(application).build(); + } + }; + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java new file mode 100644 index 0000000000..0373ef5e11 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.common.collect.ImmutableList; + +import org.joda.time.Instant; + +import java.util.Collection; + +/** + * An immutable {@link InProcessTransformResult}. + */ +public class ImmutableInProcessTransformResult implements InProcessTransformResult { + private final AppliedPTransform transform; + private final Iterable> bundles; + private final CounterSet counters; + private final Instant watermarkHold; + + private ImmutableInProcessTransformResult(AppliedPTransform transform, + Iterable> outputBundles, CounterSet counters, Instant watermarkHold) { + this.transform = transform; + this.bundles = outputBundles; + this.counters = counters; + this.watermarkHold = watermarkHold; + } + + @Override + public Iterable> getBundles() { + return bundles; + } + + @Override + public CounterSet getCounters() { + return counters; + } + + @Override + public AppliedPTransform getTransform() { + return transform; + } + + @Override + public Instant getWatermarkHold() { + return watermarkHold; + } + + public static Builder withHold(AppliedPTransform transform, + Instant watermarkHold) { + return new Builder(transform, watermarkHold); + } + + public static Builder withoutHold(AppliedPTransform transform) { + return new Builder(transform, BoundedWindow.TIMESTAMP_MAX_VALUE); + } + + /** + * A builder for creating instances of {@link ImmutableInProcessTransformResult}. + */ + public static class Builder { + private final AppliedPTransform transform; + private final ImmutableList.Builder> bundlesBuilder; + private CounterSet counters; + private final Instant watermarkHold; + + public Builder(AppliedPTransform transform, + Instant watermarkHold) { + this.transform = transform; + this.watermarkHold = watermarkHold; + this.bundlesBuilder = ImmutableList.builder(); + } + + public ImmutableInProcessTransformResult build() { + return new ImmutableInProcessTransformResult( + transform, bundlesBuilder.build(), counters, watermarkHold); + } + + public Builder withCounters(CounterSet counters) { + this.counters = counters; + return this; + } + + public Builder addOutput(Bundle outputBundle, Bundle... outputBundles) { + bundlesBuilder.add(outputBundle); + bundlesBuilder.add(outputBundles); + return this; + } + + public Builder addOutput(Collection> outputBundles) { + bundlesBuilder.addAll(outputBundles); + return this; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java new file mode 100644 index 0000000000..1a01a3db12 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.base.MoreObjects; +import com.google.common.base.MoreObjects.ToStringHelper; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.annotation.Nullable; + +/** + * A {@link Bundle} that buffers elements in memory. + */ +public final class InProcessBundle implements Bundle { + private final PCollection pcollection; + private final boolean keyed; + private final Object key; + private Collection> elements; + + /** + * Create a new {@link InProcessBundle} for the specified {@link PCollection} without a key. + */ + public static InProcessBundle unkeyed(PCollection pcollection) { + return new InProcessBundle(pcollection, false, null); + } + + /** + * Create a new {@link InProcessBundle} for the specified {@link PCollection} with the specified + * key. + * + * See {@link #getKey()} and {@link #isKeyed()} for more information. + */ + public static InProcessBundle keyed(PCollection pcollection, Object key) { + return new InProcessBundle(pcollection, true, key); + } + + private InProcessBundle(PCollection pcollection, boolean keyed, Object key) { + this.pcollection = pcollection; + this.keyed = keyed; + this.key = key; + this.elements = new ArrayList<>(); + } + + @Override + public InProcessBundle add(WindowedValue element) { + elements.add(element); + return this; + } + + @Override + @Nullable + public Object getKey() { + return key; + } + + @Override + public boolean isKeyed() { + return keyed; + } + + @Override + public Iterable> getElements() { + return elements; + } + + @Override + public PCollection getPCollection() { + return pcollection; + } + + @Override + public String toString() { + ToStringHelper toStringHelper = + MoreObjects.toStringHelper(this).add("pcollection", pcollection); + if (keyed) { + toStringHelper = toStringHelper.add("key", keyed); + } + return toStringHelper.add("elements", elements).toString(); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java index f0ed484258..e971ab9355 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java @@ -1017,6 +1017,10 @@ public TupleTag getMainOutputTag() { return mainOutputTag; } + public TupleTagList getSideOutputTags() { + return sideOutputTags; + } + public List> getSideInputs() { return sideInputs; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java new file mode 100644 index 0000000000..e202876181 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.CountingSource; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link BoundedReadEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class BoundedReadEvaluatorFactoryTest { + @Test + public void boundedSourceInMemoryTransformEvaluatorProducesElements() throws Exception { + BoundedSource source = CountingSource.upTo(10L); + TestPipeline p = TestPipeline.create(); + PCollection longs = p.apply(Read.from(source)); + + TransformEvaluatorFactory factory = new BoundedReadEvaluatorFactory(); + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + Bundle output = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(longs)).thenReturn(output); + + TransformEvaluator evaluator = + factory.forApplication(longs.getProducingTransformInternal(), null, context); + InProcessTransformResult result = evaluator.finishBundle(); + assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + assertThat( + output.getElements(), + containsInAnyOrder( + gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); + } + + @Test + public void boundedSourceInMemoryTransformEvaluatorMultipleCalls() throws Exception { + BoundedSource source = CountingSource.upTo(10L); + TestPipeline p = TestPipeline.create(); + PCollection longs = p.apply(Read.from(source)); + + TransformEvaluatorFactory factory = new BoundedReadEvaluatorFactory(); + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + Bundle output = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(longs)).thenReturn(output); + + TransformEvaluator evaluator = + factory.forApplication(longs.getProducingTransformInternal(), null, context); + InProcessTransformResult result = evaluator.finishBundle(); + assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + assertThat( + output.getElements(), + containsInAnyOrder( + gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); + + Bundle secondOutput = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(longs)).thenReturn(secondOutput); + TransformEvaluator secondEvaluator = + factory.forApplication(longs.getProducingTransformInternal(), null, context); + InProcessTransformResult secondResult = secondEvaluator.finishBundle(); + assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + assertThat(secondOutput.getElements(), emptyIterable()); + assertThat( + output.getElements(), + containsInAnyOrder( + gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); + } + + private static WindowedValue gw(Long elem) { + return WindowedValue.valueInGlobalWindow(elem); + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java new file mode 100644 index 0000000000..ad4f927f75 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link FlattenEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class FlattenEvaluatorFactoryTest { + @Test + public void testFlattenInMemoryEvaluator() throws Exception { + TestPipeline p = TestPipeline.create(); + PCollection left = p.apply("left", Create.of(1, 2, 4)); + PCollection right = p.apply("right", Create.of(-1, 2, -4)); + PCollectionList list = PCollectionList.of(left).and(right); + + PCollection flattened = list.apply(Flatten.pCollections()); + + Bundle leftBundle = InProcessBundle.unkeyed(left); + Bundle rightBundle = InProcessBundle.unkeyed(right); + + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + + Bundle flattenedLeftBundle = InProcessBundle.unkeyed(flattened); + Bundle flattenedRightBundle = InProcessBundle.unkeyed(flattened); + + when(context.createBundle(leftBundle, flattened)).thenReturn(flattenedLeftBundle); + when(context.createBundle(rightBundle, flattened)).thenReturn(flattenedRightBundle); + + FlattenEvaluatorFactory factory = new FlattenEvaluatorFactory(); + TransformEvaluator leftSideEvaluator = factory.forApplication( + flattened.getProducingTransformInternal(), leftBundle, context); + TransformEvaluator rightSideEvaluator = + factory.forApplication(flattened.getProducingTransformInternal(), rightBundle, context); + + leftSideEvaluator.processElement(WindowedValue.valueInGlobalWindow(1)); + rightSideEvaluator.processElement(WindowedValue.valueInGlobalWindow(-1)); + leftSideEvaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1024))); + leftSideEvaluator.processElement(WindowedValue.valueInEmptyWindows(4, PaneInfo.NO_FIRING)); + rightSideEvaluator.processElement( + WindowedValue.valueInEmptyWindows(2, PaneInfo.ON_TIME_AND_ONLY_FIRING)); + rightSideEvaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow(-4, new Instant(-4096))); + + InProcessTransformResult rightSideResult = rightSideEvaluator.finishBundle(); + InProcessTransformResult leftSideResult = leftSideEvaluator.finishBundle(); + + assertThat(rightSideResult.getBundles(), Matchers.>contains(flattenedRightBundle)); + assertThat( + rightSideResult.getTransform(), + Matchers.>equalTo(flattened.getProducingTransformInternal())); + assertThat(leftSideResult.getBundles(), Matchers.>contains(flattenedLeftBundle)); + assertThat( + leftSideResult.getTransform(), + Matchers.>equalTo(flattened.getProducingTransformInternal())); + + assertThat( + flattenedLeftBundle.getElements(), + containsInAnyOrder( + WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1024)), + WindowedValue.valueInEmptyWindows(4, PaneInfo.NO_FIRING), + WindowedValue.valueInGlobalWindow(1))); + assertThat( + flattenedRightBundle.getElements(), + containsInAnyOrder( + WindowedValue.valueInEmptyWindows(2, PaneInfo.ON_TIME_AND_ONLY_FIRING), + WindowedValue.timestampedValueInGlobalWindow(-4, new Instant(-4096)), + WindowedValue.valueInGlobalWindow(-1))); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java new file mode 100644 index 0000000000..456a52fa70 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.emptyIterable; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.HashMultiset; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Multiset; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link GroupByKeyEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class GroupByKeyEvaluatorFactoryTest { + @Test + public void testInMemoryEvaluator() throws Exception { + TestPipeline p = TestPipeline.create(); + KV firstFoo = KV.of("foo", -1); + KV secondFoo = KV.of("foo", 1); + KV thirdFoo = KV.of("foo", 3); + KV firstBar = KV.of("bar", 22); + KV secondBar = KV.of("bar", 12); + KV firstBaz = KV.of("baz", Integer.MAX_VALUE); + PCollection> kvs = p.apply(Create.of(firstFoo, firstBar, + secondFoo, firstBaz, secondBar, thirdFoo)); + PCollection>> groupedKvs = + kvs.apply(new GroupByKeyOnly()); + + Bundle> inputBundle = InProcessBundle.unkeyed(kvs); + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + + Bundle>> fooBundle = InProcessBundle.keyed(groupedKvs, "foo"); + Bundle>> barBundle = InProcessBundle.keyed(groupedKvs, "bar"); + Bundle>> bazBundle = InProcessBundle.keyed(groupedKvs, "baz"); + + when(evaluationContext.createKeyedBundle(inputBundle, "foo", groupedKvs)).thenReturn(fooBundle); + when(evaluationContext.createKeyedBundle(inputBundle, "bar", groupedKvs)).thenReturn(barBundle); + when(evaluationContext.createKeyedBundle(inputBundle, "baz", groupedKvs)).thenReturn(bazBundle); + + // The input to a GroupByKey is assumed to be a KvCoder + @SuppressWarnings("unchecked") + Coder keyCoder = ((KvCoder) kvs.getCoder()).getKeyCoder(); + TransformEvaluator> evaluator = + new GroupByKeyEvaluatorFactory().forApplication( + groupedKvs.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow(firstFoo)); + evaluator.processElement(WindowedValue.valueInGlobalWindow(secondFoo)); + evaluator.processElement(WindowedValue.valueInGlobalWindow(thirdFoo)); + evaluator.processElement(WindowedValue.valueInGlobalWindow(firstBar)); + evaluator.processElement(WindowedValue.valueInGlobalWindow(secondBar)); + evaluator.processElement(WindowedValue.valueInGlobalWindow(firstBaz)); + + assertThat(fooBundle.getElements(), emptyIterable()); + assertThat(barBundle.getElements(), emptyIterable()); + assertThat(bazBundle.getElements(), emptyIterable()); + + evaluator.finishBundle(); + assertThat( + fooBundle.getElements(), + contains(new KIterVMatcher( + KV.>of("foo", ImmutableSet.of(-1, 1, 3)), keyCoder))); + assertThat( + barBundle.getElements(), + contains(new KIterVMatcher( + KV.>of("bar", ImmutableSet.of(12, 22)), keyCoder))); + assertThat( + bazBundle.getElements(), + contains( + new KIterVMatcher( + KV.>of("baz", ImmutableSet.of(Integer.MAX_VALUE)), + keyCoder))); + } + + private static class KIterVMatcher extends BaseMatcher>>> { + private final KV> myKv; + private final Coder keyCoder; + + public KIterVMatcher(KV> myKv, Coder keyCoder) { + this.myKv = myKv; + this.keyCoder = keyCoder; + } + + @Override + public boolean matches(Object item) { + if (item == null || !(item instanceof WindowedValue)) { + return false; + } + @SuppressWarnings("unchecked") + WindowedValue>> that = (WindowedValue>>) item; + Multiset myValues = HashMultiset.create(); + Multiset thatValues = HashMultiset.create(); + for (V value : myKv.getValue()) { + myValues.add(value); + } + for (V value : that.getValue().getValue()) { + thatValues.add(value); + } + try { + return myValues.equals(thatValues) + && keyCoder + .structuralValue(myKv.getKey()) + .equals(keyCoder.structuralValue(that.getValue().getKey())); + } catch (Exception e) { + return false; + } + } + + @Override + public void describeTo(Description description) { + description + .appendText("KV> containing key ") + .appendValue(myKv.getKey()) + .appendText(" and values ") + .appendValueList("[", ", ", "]", myKv.getValue()); + } + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreateTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreateTest.java new file mode 100644 index 0000000000..2b685dce05 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreateTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.junit.Assert.fail; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.hamcrest.Matchers; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; + +/** + * Tests for {@link InProcessCreate}. + */ +@RunWith(JUnit4.class) +public class InProcessCreateTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testConvertsCreate() { + TestPipeline p = TestPipeline.create(); + Create.Values og = Create.of(1, 2, 3); + + InProcessCreate converted = InProcessCreate.from(og); + + DataflowAssert.that(p.apply(converted)).containsInAnyOrder(2, 1, 3); + } + + static class Record implements Serializable {} + + static class Record2 extends Record {} + + @Test + public void testThrowsIllegalArgumentWhenCannotInferCoder() { + Create.Values og = Create.of(new Record(), new Record2()); + InProcessCreate converted = InProcessCreate.from(og); + + Pipeline p = TestPipeline.create(); + + // Create won't infer a default coder in this case. + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(Matchers.containsString("Unable to infer a coder")); + + PCollection c = p.apply(converted); + p.run(); + + fail("Unexpectedly Inferred Coder " + c.getCoder()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java new file mode 100644 index 0000000000..b5b3823a04 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionTuple; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.cloud.dataflow.sdk.values.TupleTagList; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; + +/** + * Tests for {@link ParDoMultiEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class ParDoMultiEvaluatorFactoryTest implements Serializable { + @Test + public void testParDoMultiInMemoryTransformEvaluator() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + + TupleTag> mainOutputTag = new TupleTag>() {}; + final TupleTag elementTag = new TupleTag<>(); + final TupleTag lengthTag = new TupleTag<>(); + + BoundMulti> pardo = + ParDo.of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output(KV.of(c.element(), c.element().length())); + c.sideOutput(elementTag, c.element()); + c.sideOutput(lengthTag, c.element().length()); + } + }).withOutputTags(mainOutputTag, TupleTagList.of(elementTag).and(lengthTag)); + PCollectionTuple outputTuple = input.apply(pardo); + + Bundle inputBundle = InProcessBundle.unkeyed(input); + + PCollection> mainOutput = outputTuple.get(mainOutputTag); + PCollection elementOutput = outputTuple.get(elementTag); + PCollection lengthOutput = outputTuple.get(lengthTag); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + Bundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + Bundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + Bundle lengthOutputBundle = InProcessBundle.unkeyed(lengthOutput); + + when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); + when(evaluationContext.createBundle(inputBundle, elementOutput)) + .thenReturn(elementOutputBundle); + when(evaluationContext.createBundle(inputBundle, lengthOutput)).thenReturn(lengthOutputBundle); + + InProcessExecutionContext executionContext = new InProcessExecutionContext(); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal())) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = + new ParDoMultiEvaluatorFactory().forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); + evaluator.processElement( + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getBundles(), + Matchers.>containsInAnyOrder( + lengthOutputBundle, mainOutputBundle, elementOutputBundle)); + assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + assertThat(result.getCounters(), equalTo(counters)); + + assertThat( + mainOutputBundle.getElements(), + Matchers.>>containsInAnyOrder( + WindowedValue.valueInGlobalWindow(KV.of("foo", 3)), + WindowedValue.timestampedValueInGlobalWindow(KV.of("bara", 4), new Instant(1000)), + WindowedValue.valueInGlobalWindow( + KV.of("bazam", 5), PaneInfo.ON_TIME_AND_ONLY_FIRING))); + assertThat( + elementOutputBundle.getElements(), + Matchers.>containsInAnyOrder( + WindowedValue.valueInGlobalWindow("foo"), + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000)), + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING))); + assertThat( + lengthOutputBundle.getElements(), + Matchers.>containsInAnyOrder( + WindowedValue.valueInGlobalWindow(3), + WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), + WindowedValue.valueInGlobalWindow(5, PaneInfo.ON_TIME_AND_ONLY_FIRING))); + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java new file mode 100644 index 0000000000..07d08d1fad --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; + +/** + * Tests for {@link ParDoSingleEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class ParDoSingleEvaluatorFactoryTest implements Serializable { + @Test + public void testParDoInMemoryTransformEvaluator() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + PCollection collection = input.apply(ParDo.of(new DoFn() { + @Override public void processElement(ProcessContext c) { + c.output(c.element().length()); + } + })); + Bundle inputBundle = InProcessBundle.unkeyed(input); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + Bundle outputBundle = InProcessBundle.unkeyed(collection); + when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); + InProcessExecutionContext executionContext = new InProcessExecutionContext(); + when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal())) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = + new ParDoSingleEvaluatorFactory().forApplication( + collection.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); + evaluator.processElement( + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat(result.getBundles(), Matchers.>contains(outputBundle)); + assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + assertThat(result.getCounters(), equalTo(counters)); + + assertThat( + outputBundle.getElements(), + Matchers.>containsInAnyOrder( + WindowedValue.valueInGlobalWindow(3), + WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), + WindowedValue.valueInGlobalWindow(5, PaneInfo.ON_TIME_AND_ONLY_FIRING))); + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java new file mode 100644 index 0000000000..bc3bd76daf --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.io.CountingSource; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.hamcrest.Matchers; +import org.joda.time.DateTime; +import org.joda.time.Instant; +import org.joda.time.ReadableInstant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +/** + * Tests for {@link UnboundedReadEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class UnboundedReadEvaluatorFactoryTest { + @Test + public void unboundedSourceInMemoryTransformEvaluatorProducesElements() throws Exception { + UnboundedSource source = + CountingSource.unboundedWithTimestampFn(new LongToInstantFn()); + TestPipeline p = TestPipeline.create(); + PCollection longs = p.apply(Read.from(source)); + + TransformEvaluatorFactory factory = new UnboundedReadEvaluatorFactory(); + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + Bundle output = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(longs)).thenReturn(output); + + TransformEvaluator evaluator = + factory.forApplication(longs.getProducingTransformInternal(), null, context); + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); + assertThat( + output.getElements(), + containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), + tgw(3L), tgw(0L))); + } + + @Test + public void unboundedSourceInMemoryTransformEvaluatorMultipleCalls() throws Exception { + UnboundedSource source = + CountingSource.unboundedWithTimestampFn(new LongToInstantFn()); + TestPipeline p = TestPipeline.create(); + PCollection longs = p.apply(Read.from(source)); + + TransformEvaluatorFactory factory = new UnboundedReadEvaluatorFactory(); + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + Bundle output = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(longs)).thenReturn(output); + + TransformEvaluator evaluator = + factory.forApplication(longs.getProducingTransformInternal(), null, context); + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); + assertThat( + output.getElements(), + containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), + tgw(3L), tgw(0L))); + + Bundle secondOutput = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(longs)).thenReturn(secondOutput); + TransformEvaluator secondEvaluator = + factory.forApplication(longs.getProducingTransformInternal(), null, context); + InProcessTransformResult secondResult = secondEvaluator.finishBundle(); + assertThat( + secondResult.getWatermarkHold(), + Matchers.lessThan(DateTime.now().toInstant())); + assertThat( + secondOutput.getElements(), + containsInAnyOrder(tgw(11L), tgw(12L), tgw(14L), tgw(18L), tgw(19L), tgw(17L), tgw(16L), + tgw(15L), tgw(13L), tgw(10L))); + assertThat( + output.getElements(), + containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), + tgw(3L), tgw(0L))); + } + + /** + * A terse alias for producing timestamped longs in the {@link GlobalWindow}, where + * the timestamp is the epoch offset by the value of the element. + */ + private static WindowedValue tgw(Long elem) { + return WindowedValue.timestampedValueInGlobalWindow(elem, new Instant(elem)); + } + + private static class LongToInstantFn implements SerializableFunction { + @Override + public Instant apply(Long input) { + return new Instant(input); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java new file mode 100644 index 0000000000..50af094086 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; +import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link ViewEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class ViewEvaluatorFactoryTest { + @Test + public void testInMemoryEvaluator() throws Exception { + TestPipeline p = TestPipeline.create(); + PCollection input = p.apply(Create.of("foo", "bar")); + PCollectionView> view = input.apply(View.asIterable()); + + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + TestViewWriter> viewWriter = new TestViewWriter<>(); + when(context.createPCollectionViewWriter(input, view)).thenReturn(viewWriter); + + Bundle inputBundle = InProcessBundle.unkeyed(input); + TransformEvaluator evaluator = new ViewEvaluatorFactory().forApplication( + view.getProducingTransformInternal(), inputBundle, context); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement(WindowedValue.valueInGlobalWindow("bar")); + assertThat(viewWriter.latest, nullValue()); + + evaluator.finishBundle(); + assertThat( + viewWriter.latest, + containsInAnyOrder( + WindowedValue.valueInGlobalWindow("foo"), WindowedValue.valueInGlobalWindow("bar"))); + } + + private static class TestViewWriter implements PCollectionViewWriter { + private Iterable> latest; + + @Override + public void add(Iterable> values) { + latest = values; + } + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java new file mode 100644 index 0000000000..3378e3bded --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +/** + * Tests for {@link InProcessBundle}. + */ +@RunWith(JUnit4.class) +public class InProcessBundleTest { + @Test + public void unkeyedShouldCreateWithNullKey() { + PCollection pcollection = TestPipeline.create().apply(Create.of(1)); + + InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); + + assertThat(bundle.isKeyed(), is(false)); + assertThat(bundle.getKey(), nullValue()); + } + + private void keyedCreateBundle(Object key) { + PCollection pcollection = TestPipeline.create().apply(Create.of(1)); + + InProcessBundle bundle = InProcessBundle.keyed(pcollection, key); + + assertThat(bundle.isKeyed(), is(true)); + assertThat(bundle.getKey(), equalTo(key)); + } + + @Test + public void keyedWithNullKeyShouldCreateKeyedBundle() { + keyedCreateBundle(null); + } + + @Test + public void keyedWithKeyShouldCreateKeyedBundle() { + keyedCreateBundle(new Object()); + } + + private void getElementsShouldHaveAddedElements(Iterable> elems) { + PCollection pcollection = TestPipeline.create().apply(Create.of()); + + InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); + Collection>> expectations = new ArrayList<>(); + for (WindowedValue elem : elems) { + bundle.add(elem); + expectations.add(equalTo(elem)); + } + Matcher>> containsMatcher = + Matchers.>containsInAnyOrder(expectations); + assertThat(bundle.getElements(), containsMatcher); + } + + @Test + public void getElementsBeforeAddShouldReturnEmptyIterable() { + getElementsShouldHaveAddedElements(Collections.>emptyList()); + } + + @Test + public void getElementsAfterAddShouldReturnAddedElements() { + WindowedValue firstValue = WindowedValue.valueInGlobalWindow(1); + WindowedValue secondValue = + WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1000L)); + + getElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); + } +} + From d0e28bc982f2e23e4b6dcd0ba0e320f1b3f7dafb Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 3 Feb 2016 17:52:13 -0800 Subject: [PATCH 072/751] Upgrade maven shade plugin to avoid infinite loop Maven shade plugin issue fixed: https://issues.apache.org/jira/browse/MSHADE-148 This is for ASF beam ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113803227 --- examples/pom.xml | 2 +- sdk/pom.xml | 2 +- worker/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 0e7db3d59b..8e708ced69 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -306,7 +306,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.3 + 2.4.1 package diff --git a/sdk/pom.xml b/sdk/pom.xml index 2c8b52b638..24fc45cc40 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -286,7 +286,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.3 + 2.4.1 From 460dc2004057ca7b0d362c404055798f5cd79a22 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 3 Feb 2016 20:25:47 -0800 Subject: [PATCH 073/751] Add InMemoryWatermarkManager This is responsible for tracking and updating watermarks of PCollections. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113811735 --- .../util/InMemoryWatermarkManager.java | 568 ++++++++++++++++++ .../util/InMemoryWatermarkManagerTest.java | 500 +++++++++++++++ 2 files changed, 1068 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java new file mode 100644 index 0000000000..8673956d69 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java @@ -0,0 +1,568 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Ordering; +import com.google.common.collect.SortedMultiset; +import com.google.common.collect.TreeMultiset; + +import org.joda.time.Instant; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import javax.annotation.Nullable; + +/** + * Manages watermarks of {@link PCollection PCollections} and input and output watermarks of + * {@link AppliedPTransform AppliedPTransforms} to provide event-time and completion tracking for + * in-memory execution. {@link InMemoryWatermarkManager} is designed to update and return a + * consistent view of watermarks in the presence of concurrent updates. + * + *

An {@link InMemoryWatermarkManager} is provided with the collection of root + * {@link AppliedPTransform AppliedPTransforms} and a map of {@link PCollection PCollections} to + * all the {@link AppliedPTransform AppliedPTransforms} that consume them at construction time. + * + *

Whenever a root {@link AppliedPTransform transform} produces elements, the + * {@link InMemoryWatermarkManager} is provided with the produced elements and the output watermark + * of the producing {@link AppliedPTransform transform}. The + * {@link InMemoryWatermarkManager watermark manager} is responsible for computing the watermarks + * of all {@link AppliedPTransform transforms} that consume one or more + * {@link PCollection PCollections}. + * + *

Whenever a non-root {@link AppliedPTransform} finishes processing one or more in-flight + * elements (referred to as the input {@link Bundle bundle}), the following occurs atomically: + *

    + *
  • All of the in-flight elements are removed from the collection of pending elements for the + * {@link AppliedPTransform}.
  • + *
  • All of the elements produced by the {@link AppliedPTransform} are added to the collection + * of pending elements for each {@link AppliedPTransform} that consumes them.
  • + *
  • The input watermark for the {@link AppliedPTransform} becomes the maximum value of + *
      + *
    • the previous input watermark
    • + *
    • the minimum of + *
        + *
      • the timestamps of all currently pending elements
      • + *
      • all input {@link PCollection} watermarks
      • + *
      + *
    • + *
    + *
  • + *
  • The output watermark for the {@link AppliedPTransform} becomes the maximum of + *
      + *
    • the previous output watermark
    • + *
    • the minimum of + *
        + *
      • the current input watermark
      • + *
      • the current watermark holds
      • + *
      + *
    • + *
    + *
  • + *
  • The watermark of the output {@link PCollection} can be advanced to the output watermark of + * the {@link AppliedPTransform}
  • + *
  • The watermark of all downstream {@link AppliedPTransform AppliedPTransforms} can be + * advanced.
  • + *
+ * + *

The watermark of a {@link PCollection} is equal to the output watermark of the + * {@link AppliedPTransform} that produces it. + * + *

The watermarks for a {@link PTransform} are updated as follows when output is committed:

+ * Watermark_In'  = MAX(Watermark_In, MIN(U(TS_Pending), U(Watermark_InputPCollection)))
+ * Watermark_Out' = MAX(Watermark_Out, MIN(Watermark_In', U(StateHold)))
+ * Watermark_PCollection = Watermark_Out_ProducingPTransform
+ * 
+ */ +public class InMemoryWatermarkManager { + /** + * The watermark of some {@link Pipeline} element, usually a {@link PTransform} or a + * {@link PCollection}. + * + *

A watermark is a monotonically increasing value, which represents the point up to which the + * system believes it has received all of the data. Data that arrives with a timestamp that is + * before the watermark is considered late. {@link BoundedWindow#TIMESTAMP_MAX_VALUE} is a special + * timestamp which indicates we have received all of the data and there will be no more on-time or + * late data. This value is represented by {@link InMemoryWatermarkManager#THE_END_OF_TIME}. + */ + private static interface Watermark { + /** + * Returns the current value of this watermark. + */ + Instant get(); + + /** + * Refreshes the value of this watermark from its input watermarks and watermark holds. + * + * @return true if the value of the watermark has changed (and thus dependent watermark must + * also be updated + */ + WatermarkUpdate refresh(); + + } + + /** + * The result of computing a {@link Watermark}. + */ + private static enum WatermarkUpdate { + /** The watermark is later than the value at the previous time it was computed. */ + ADVANCED(true), + /** The watermark is equal to the value at the previous time it was computed. */ + NO_CHANGE(false); + + private final boolean advanced; + + private WatermarkUpdate(boolean advanced) { + this.advanced = advanced; + } + + public boolean isAdvanced() { + return advanced; + } + + /** + * Returns the {@link WatermarkUpdate} based on the former and current + * {@link Instant timestamps}. + */ + public static WatermarkUpdate fromTimestamps(Instant oldTime, Instant currentTime) { + if (currentTime.isAfter(oldTime)) { + return ADVANCED; + } + return NO_CHANGE; + } + } + + /** + * The input {@link Watermark} of an {@link AppliedPTransform}. + * + *

At any point, the value of an {@link AppliedPTransformInputWatermark} is equal to the + * minimum watermark across all of its input {@link Watermark Watermarks}, and the minimum + * timestamp of all of the pending elements, restricted to be monotonically increasing. + * + *

See {@link #refresh()} for more information. + */ + private static class AppliedPTransformInputWatermark implements Watermark { + private final Collection inputWatermarks; + private final SortedMultiset> pendingElements; + private AtomicReference currentWatermark; + + public AppliedPTransformInputWatermark(Collection inputWatermarks) { + this.inputWatermarks = inputWatermarks; + this.pendingElements = TreeMultiset.create(PENDING_ELEMENT_COMPARATOR); + currentWatermark = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); + } + + @Override + public Instant get() { + return currentWatermark.get(); + } + + /** + * {@inheritDoc}. + * + *

When refresh is called, the value of the {@link AppliedPTransformInputWatermark} becomes + * equal to the maximum value of + *

    + *
  • the previous input watermark
  • + *
  • the minimum of + *
      + *
    • the timestamps of all currently pending elements
    • + *
    • all input {@link PCollection} watermarks
    • + *
    + *
  • + *
+ */ + @Override + public synchronized WatermarkUpdate refresh() { + Instant oldWatermark = currentWatermark.get(); + Instant minInputWatermark = BoundedWindow.TIMESTAMP_MAX_VALUE; + for (Watermark inputWatermark : inputWatermarks) { + minInputWatermark = INSTANT_ORDERING.min(minInputWatermark, inputWatermark.get()); + } + if (!pendingElements.isEmpty()) { + minInputWatermark = INSTANT_ORDERING.min( + minInputWatermark, pendingElements.firstEntry().getElement().getTimestamp()); + } + Instant newWatermark = INSTANT_ORDERING.max(oldWatermark, minInputWatermark); + currentWatermark.set(newWatermark); + return WatermarkUpdate.fromTimestamps(oldWatermark, newWatermark); + } + + public synchronized void addPending(Iterable> newPending) { + for (WindowedValue pendingElement : newPending) { + pendingElements.add(pendingElement); + } + } + + public synchronized void removePending(Iterable> finishedElements) { + for (WindowedValue finishedElement : finishedElements) { + pendingElements.remove(finishedElement); + } + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(AppliedPTransformInputWatermark.class) + .add("pendingElements", pendingElements) + .add("currentWatermark", currentWatermark) + .toString(); + } + } + + /** + * The output {@link Watermark} of an {@link AppliedPTransform}. + * + *

The value of an {@link AppliedPTransformOutputWatermark} is equal to the minimum of the + * current watermark hold and the {@link AppliedPTransformInputWatermark} for the same + * {@link AppliedPTransform}, restricted to be monotonically increasing. See + * {@link #refresh()} for more information. + */ + private static class AppliedPTransformOutputWatermark implements Watermark { + private final Watermark inputWatermark; + private Instant currentHold; + private AtomicReference currentWatermark; + + public AppliedPTransformOutputWatermark(AppliedPTransformInputWatermark inputWatermark) { + this.inputWatermark = inputWatermark; + currentHold = BoundedWindow.TIMESTAMP_MAX_VALUE; + currentWatermark = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); + } + + public synchronized void setHold(Instant newHold) { + currentHold = newHold; + } + + @Override + public Instant get() { + return currentWatermark.get(); + } + + /** + * {@inheritDoc}. + * + *

When refresh is called, the value of the {@link AppliedPTransformOutputWatermark} becomes + * equal to the maximum value of: + *

    + *
  • the previous output watermark
  • + *
  • the minimum of + *
      + *
    • the current input watermark
    • + *
    • the current watermark holds
    • + *
    + *
  • + *
+ */ + @Override + public synchronized WatermarkUpdate refresh() { + Instant oldWatermark = currentWatermark.get(); + Instant newWatermark; + if (currentHold == null) { + newWatermark = inputWatermark.get(); + } else { + newWatermark = INSTANT_ORDERING.min(inputWatermark.get(), currentHold); + } + newWatermark = INSTANT_ORDERING.max(oldWatermark, newWatermark); + currentWatermark.set(newWatermark); + return WatermarkUpdate.fromTimestamps(oldWatermark, newWatermark); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(AppliedPTransformOutputWatermark.class) + .add("currentHold", currentHold) + .add("currentWatermark", currentWatermark) + .toString(); + } + } + + /** + * A {@code Watermark} that is after the latest time it is possible to represent in the global + * window. This is a distinguished value representing a complete {@link PTransform}. + */ + private static final Watermark THE_END_OF_TIME = new Watermark() { + @Override + public WatermarkUpdate refresh() { + // THE_END_OF_TIME is a distinguished value that cannot be advanced. + return WatermarkUpdate.NO_CHANGE; + } + + @Override + public Instant get() { + return BoundedWindow.TIMESTAMP_MAX_VALUE; + } + }; + + private static final Ordering INSTANT_ORDERING = Ordering.natural(); + + /** + * An ordering that compares windowed values by timestamp, then arbitrarily. This ensures that + * {@link WindowedValue WindowedValues} will be sorted by timestamp, while two different + * {@link WindowedValue WindowedValues} with the same timestamp are not considered equal. + */ + private static final Ordering> PENDING_ELEMENT_COMPARATOR = + (new WindowedValueByTimestampComparator()).compound(Ordering.arbitrary()); + + /** + * A map from each {@link PCollection} to all {@link AppliedPTransform PTransform applications} + * that consume that {@link PCollection}. + */ + private final Map, Collection>> consumers; + + /** + * The input and output watermark of each {@link AppliedPTransform}. + */ + private final Map, TransformWatermarks> transformToWatermarks; + + /** + * Creates a new {@link InMemoryWatermarkManager}. All watermarks within the newly created + * {@link InMemoryWatermarkManager} start at {@link BoundedWindow#TIMESTAMP_MIN_VALUE}, the + * minimum watermark, with no watermark holds or pending elements. + * + * @param rootTransforms the root-level transforms of the {@link Pipeline} + * @param consumers a mapping between each {@link PCollection} in the {@link Pipeline} to the + * transforms that consume it as a part of their input + */ + public static InMemoryWatermarkManager create( + Collection> rootTransforms, + Map, Collection>> consumers) { + return new InMemoryWatermarkManager(rootTransforms, consumers); + } + + private InMemoryWatermarkManager( + Collection> rootTransforms, + Map, Collection>> consumers) { + this.consumers = consumers; + + transformToWatermarks = new HashMap<>(); + + for (AppliedPTransform rootTransform : rootTransforms) { + getTransformWatermark(rootTransform); + } + for (Collection> intermediateTransforms : consumers.values()) { + for (AppliedPTransform transform : intermediateTransforms) { + getTransformWatermark(transform); + } + } + } + + private TransformWatermarks getTransformWatermark(AppliedPTransform transform) { + TransformWatermarks wms = transformToWatermarks.get(transform); + if (wms == null) { + List inputCollectionWatermarks = getInputWatermarks(transform); + AppliedPTransformInputWatermark inputWatermark = + new AppliedPTransformInputWatermark(inputCollectionWatermarks); + AppliedPTransformOutputWatermark outputWatermark = + new AppliedPTransformOutputWatermark(inputWatermark); + wms = new TransformWatermarks(inputWatermark, outputWatermark); + transformToWatermarks.put(transform, wms); + } + return wms; + } + + private List getInputWatermarks(AppliedPTransform transform) { + ImmutableList.Builder inputWatermarksBuilder = ImmutableList.builder(); + Collection inputs = transform.getInput().expand(); + if (inputs.isEmpty()) { + inputWatermarksBuilder.add(THE_END_OF_TIME); + } + for (PValue pvalue : inputs) { + Watermark producerOutputWatermark = + getTransformWatermark(pvalue.getProducingTransformInternal()).outputWatermark(); + inputWatermarksBuilder.add(producerOutputWatermark); + } + List inputCollectionWatermarks = inputWatermarksBuilder.build(); + return inputCollectionWatermarks; + } + + /** + * Gets the input and output watermarks for an {@link AppliedPTransform}. If the + * {@link AppliedPTransform PTransform} has not processed any elements, return a watermark of + * {@link BoundedWindow#TIMESTAMP_MIN_VALUE}. + * + * @return a snapshot of the input watermark and output watermark for the provided transform + */ + public synchronized TransformWatermarks getWatermarks(AppliedPTransform transform) { + return transformToWatermarks.get(transform); + } + + /** + * Updates the output watermark of a transform that takes no input. + * + *

The output watermark of a transform that takes no input is determined by that transform, as + * there are no input {@link PCollection PCollections}. + * + * @param watermark the output watermark of the transform. If the transform has buffered input + * elements, the watermark should be the minimum of all buffered elements. + * @return both watermarks of the source transform + */ + public TransformWatermarks updateOutputWatermark( + AppliedPTransform transform, Iterable> outputs, Instant watermark) { + TransformWatermarks watermarks = getWatermarks(transform); + watermarks.outputWatermark().setHold(watermark); + + for (Bundle output : outputs) { + PCollection pCollection = output.getPCollection(); + for (AppliedPTransform consumer : consumers.get(pCollection)) { + addPending(consumer, output.getElements()); + } + } + refreshWatermarks(transform); + return watermarks; + } + + /** + * Updates the watermarks of a transform with one or more inputs. + * + *

Each transform has two monotonically increasing watermarks: the input watermark, which can, + * at any time, be updated to equal: + *

+   * MAX(CurrentInputWatermark, MIN(PendingElements, InputPCollectionWatermarks))
+   * 
+ * and the output watermark, which can, at any time, be updated to equal: + *
+   * MAX(CurrentOutputWatermark, MIN(InputWatermark, WatermarkHolds))
+   * 
. + * + * @param completed the input that has completed + * @param transform the transform that has completed processing the input + * @param outputs the bundles the transform has output + * @param earliestHold the earliest watermark hold in the transform's state. {@code null} if there + * is no hold + * @return the updated watermark of the transform + */ + public TransformWatermarks updateWatermarks(Bundle completed, + AppliedPTransform transform, Collection> outputs, + @Nullable Instant earliestHold) { + updatePending(completed, transform, outputs); + TransformWatermarks transformWms = transformToWatermarks.get(transform); + transformWms.outputWatermark().setHold(earliestHold); + refreshWatermarks(transform); + return transformWms; + } + + private void refreshWatermarks(AppliedPTransform transform) { + TransformWatermarks myWatermarks = transformToWatermarks.get(transform); + WatermarkUpdate updateResult = myWatermarks.refresh(); + if (updateResult.isAdvanced()) { + for (PValue outputPValue : transform.getOutput().expand()) { + Collection> downstreamTransforms = consumers.get(outputPValue); + if (downstreamTransforms != null) { + for (AppliedPTransform downstreamTransform : downstreamTransforms) { + refreshWatermarks(downstreamTransform); + } + } + } + } + } + + /** + * Removes all elements consumed by the input bundle from the {@link PTransform PTransforms} + * collection of pending elements, and adds all elements produced by the {@link PTransform} to the + * pending queue of each consumer. + */ + private void updatePending( + Bundle input, AppliedPTransform transform, Collection> outputs) { + AppliedPTransformInputWatermark inputWatermark = + transformToWatermarks.get(transform).inputWatermark(); + inputWatermark.removePending(input.getElements()); + + for (Bundle bundle : outputs) { + for (AppliedPTransform consumer : consumers.get(bundle.getPCollection())) { + addPending(consumer, bundle.getElements()); + } + } + } + + /** + * Adds all of the provided {@link WindowedValue WindowedValues} to the collection of pending + * elements for the provided {@link AppliedPTransform}. + */ + private void addPending( + AppliedPTransform transform, Iterable> pending) { + TransformWatermarks watermarks = transformToWatermarks.get(transform); + watermarks.inputWatermark().addPending(pending); + } + + /** + * A reference to the input and output watermarks of an {@link AppliedPTransform}. + */ + public class TransformWatermarks { + private final AppliedPTransformInputWatermark inputWatermark; + private final AppliedPTransformOutputWatermark outputWatermark; + + private TransformWatermarks( + AppliedPTransformInputWatermark inputWatermark, + AppliedPTransformOutputWatermark outputWatermark) { + this.inputWatermark = inputWatermark; + this.outputWatermark = outputWatermark; + } + + /** + * Returns the input watermark of the {@link AppliedPTransform}. + */ + public Instant getInputWatermark() { + return inputWatermark.get(); + } + + /** + * Returns the output watermark of the {@link AppliedPTransform}. + */ + public Instant getOutputWatermark() { + return outputWatermark.get(); + } + + AppliedPTransformInputWatermark inputWatermark() { + return inputWatermark; + } + + AppliedPTransformOutputWatermark outputWatermark() { + return outputWatermark; + } + + private WatermarkUpdate refresh() { + inputWatermark.refresh(); + return outputWatermark.refresh(); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(TransformWatermarks.class) + .add("inputWatermark", inputWatermark) + .add("outputWatermark", outputWatermark) + .toString(); + } + } + + private static class WindowedValueByTimestampComparator extends Ordering> { + @Override + public int compare(WindowedValue o1, WindowedValue o2) { + return o1.getTimestamp().compareTo(o2.getTimestamp()); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java new file mode 100644 index 0000000000..aeb276c9ad --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java @@ -0,0 +1,500 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TransformWatermarks; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.Filter; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.joda.time.Instant; +import org.joda.time.ReadableInstant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Tests for {@link InMemoryWatermarkManager}. + */ +@RunWith(JUnit4.class) +public class InMemoryWatermarkManagerTest implements Serializable { + private PCollection createdInts; + + private PCollection filtered; + private PCollection> keyed; + + private PCollection intsToFlatten; + private PCollection flattened; + + private InMemoryWatermarkManager manager; + + @Before + public void setup() { + TestPipeline p = TestPipeline.create(); + + createdInts = p.apply("createdInts", Create.of(1, 2, 3)); + + filtered = createdInts.apply("filtered", Filter.greaterThan(1)); + keyed = createdInts.apply("keyed", WithKeys.of("MyKey")); + + intsToFlatten = p.apply("intsToFlatten", Create.of(-1, 256, 65535)); + PCollectionList preFlatten = PCollectionList.of(createdInts).and(intsToFlatten); + flattened = preFlatten.apply("flattened", Flatten.pCollections()); + + Collection> rootTransforms = + ImmutableList.>of( + createdInts.getProducingTransformInternal(), + intsToFlatten.getProducingTransformInternal()); + + Map, Collection>> consumers = new HashMap<>(); + consumers.put( + createdInts, + ImmutableList.>of(filtered.getProducingTransformInternal(), + keyed.getProducingTransformInternal(), flattened.getProducingTransformInternal())); + consumers.put(filtered, Collections.>emptyList()); + consumers.put(keyed, Collections.>emptyList()); + + consumers.put( + intsToFlatten, + Collections.>singleton( + flattened.getProducingTransformInternal())); + consumers.put(flattened, Collections.>emptyList()); + + manager = InMemoryWatermarkManager.create(rootTransforms, consumers); + } + + + /** + * Demonstrates that getWatermark, when called on an {@link AppliedPTransform} that has not + * processed any elements, returns the {@link BoundedWindow#TIMESTAMP_MIN_VALUE}. + */ + @Test + public void getWatermarkForUntouchedTransform() { + TransformWatermarks watermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); + + assertThat(watermarks.getInputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + assertThat(watermarks.getOutputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + } + + /** + * Demonstrates that getWatermark for a transform that consumes no input uses the Watermark + * Hold value provided to it as the output watermark. + */ + @Test + public void getWatermarkForUpdatedSourceTransform() { + Bundle output = globallyWindowedBundle(createdInts, 1); + + TransformWatermarks updatedSourceWatermark = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(output), new Instant(8000L)); + + assertThat(updatedSourceWatermark.getOutputWatermark(), equalTo(new Instant(8000L))); + } + + /** + * Demonstrates that getWatermark for a transform that takes multiple inputs is held to the + * minimum watermark across all of its inputs. + */ + @Test + public void getWatermarkForMultiInputTransform() { + Bundle secondPcollectionBundle = globallyWindowedBundle(intsToFlatten, -1); + + manager.updateOutputWatermark(intsToFlatten.getProducingTransformInternal(), + Collections.>singleton(secondPcollectionBundle), new Instant(Long.MAX_VALUE)); + + // We didn't do anything for the first source, so we shouldn't have progressed the watermark + TransformWatermarks firstSourceWatermark = + manager.getWatermarks(createdInts.getProducingTransformInternal()); + assertThat( + firstSourceWatermark.getOutputWatermark(), + not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + + // the Second Source output all of the elements so it should be done (with a watermark at the + // end of time). + TransformWatermarks secondSourceWatermark = + manager.getWatermarks(intsToFlatten.getProducingTransformInternal()); + assertThat( + secondSourceWatermark.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + + // We haven't consumed anything yet, so our watermark should be at the beginning of time + TransformWatermarks transformWatermark = + manager.getWatermarks(flattened.getProducingTransformInternal()); + assertThat( + transformWatermark.getInputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + assertThat( + transformWatermark.getOutputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + + Bundle flattenedBundleSecondCreate = globallyWindowedBundle(flattened, -1); + // We have finished processing the bundle from the second PCollection, but we haven't consumed + // anything from the first PCollection yet; so our watermark shouldn't advance + TransformWatermarks transformAfterProcessing = + manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), + Collections.>singleton(flattenedBundleSecondCreate), null); + assertThat( + transformAfterProcessing.getInputWatermark(), + not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + assertThat( + transformAfterProcessing.getOutputWatermark(), + not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + + Instant firstCollectionTimestamp = new Instant(10000); + Bundle firstPcollectionBundle = timestampedBundle( + createdInts, TimestampedValue.of(5, firstCollectionTimestamp)); + // the source is done, but elements are still buffered. The source output watermark should be + // past the end of the global window + TransformWatermarks firstSourceWatermarks = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(firstPcollectionBundle), new Instant(Long.MAX_VALUE)); + assertThat(firstSourceWatermarks.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + + // We still haven't consumed any of the first source's input, so the watermark should still not + // progress + TransformWatermarks flattenAfterSourcesProduced = + manager.getWatermarks(flattened.getProducingTransformInternal()); + assertThat( + flattenAfterSourcesProduced.getInputWatermark(), + not(laterThan(firstCollectionTimestamp))); + assertThat( + flattenAfterSourcesProduced.getOutputWatermark(), + not(laterThan(firstCollectionTimestamp))); + + // We have buffered inputs, but since the PCollection has all of the elements (has a WM past the + // end of the global window), we should have a watermark equal to the min among buffered + // elements + TransformWatermarks withBufferedElements = + manager.getWatermarks(flattened.getProducingTransformInternal()); + assertThat(withBufferedElements.getInputWatermark(), equalTo(firstCollectionTimestamp)); + assertThat(withBufferedElements.getOutputWatermark(), equalTo(firstCollectionTimestamp)); + + Bundle completedFlattenBundle = InProcessBundle.unkeyed(flattened); + TransformWatermarks afterConsumingAllInput = + manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), + Collections.>singleton(completedFlattenBundle), null); + assertThat( + afterConsumingAllInput.getInputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat( + afterConsumingAllInput.getOutputWatermark(), + not(laterThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + } + + /** + * Demonstrates that pending elements are independent among + * {@link AppliedPTransform AppliedPTransforms} that consume the same input {@link PCollection}. + */ + @Test + public void getWatermarkForMultiConsumedCollection() { + Bundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + TransformWatermarks createdAfterProducing = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + assertThat(createdAfterProducing.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + + Bundle> keyBundle = + timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), + TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + TransformWatermarks keyedWatermarks = manager.updateWatermarks(createdBundle, + keyed.getProducingTransformInternal(), Collections.>singleton(keyBundle), null); + assertThat( + keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat( + keyedWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + + TransformWatermarks filteredWatermarks = + manager.getWatermarks(filtered.getProducingTransformInternal()); + assertThat(filteredWatermarks.getInputWatermark(), not(laterThan(new Instant(-1000L)))); + assertThat( + filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); + + Bundle filteredBundle = timestampedBundle( + filtered, TimestampedValue.of(2, new Instant(1234L))); + TransformWatermarks filteredProcessedWatermarks = + manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), + Collections.>singleton(filteredBundle), null); + assertThat( + filteredProcessedWatermarks.getInputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat( + filteredProcessedWatermarks.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + } + + /** + * Demonstrates that the watermark of an {@link AppliedPTransform} is held to the provided + * watermark hold. + */ + @Test + public void updateWatermarkWithWatermarkHolds() { + Bundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), + TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + + Bundle> keyBundle = timestampedBundle( + keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), + TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + TransformWatermarks keyedWatermarks = manager.updateWatermarks(createdBundle, + keyed.getProducingTransformInternal(), Collections.>singleton(keyBundle), + new Instant(500L)); + assertThat( + keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); + } + + /** + * Demonstrates that updated output watermarks are monotonic in the presence of late data, when + * called on an {@link AppliedPTransform} that consumes no input. + */ + @Test + public void updateOutputWatermarkShouldBeMonotonic() { + Bundle firstInput = InProcessBundle.unkeyed(createdInts); + TransformWatermarks firstWatermarks = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(firstInput), new Instant(0L)); + assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); + + Bundle secondInput = InProcessBundle.unkeyed(createdInts); + TransformWatermarks secondWatermarks = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(secondInput), new Instant(-250L)); + assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); + } + + /** + * Demonstrates that updated output watermarks are monotonic in the presence of watermark holds + * that become earlier than a previous watermark hold. + */ + @Test + public void updateWatermarkWithHoldsShouldBeMonotonic() { + Bundle createdBundle = timestampedBundle( + createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), + TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle), + new Instant(Long.MAX_VALUE)); + + Bundle> keyBundle = timestampedBundle( + keyed, + TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), + TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + TransformWatermarks keyedWatermarks = + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), new Instant(500L)); + assertThat( + keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); + Instant oldOutputWatermark = keyedWatermarks.getOutputWatermark(); + + TransformWatermarks updatedWatermarks = + manager.getWatermarks(keyed.getProducingTransformInternal()); + assertThat( + updatedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + // We added a hold prior to the old watermark; we shouldn't progress (due to the earlier hold) + // but the watermark is monotonic and should not backslide to the new, earlier hold + assertThat( + updatedWatermarks.getOutputWatermark(), equalTo(oldOutputWatermark)); + } + + /** + * Demonstrates that updateWatermarks in the presence of late data is monotonic. + */ + @Test + public void updateWatermarkWithLateData() { + Instant sourceWatermark = new Instant(1_000_000L); + Bundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, sourceWatermark), TimestampedValue.of(2, new Instant(1234L))); + + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle), sourceWatermark); + + Bundle> keyBundle = timestampedBundle( + keyed, + TimestampedValue.of(KV.of("MyKey", 1), sourceWatermark), + TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); + + // Finish processing the on-time data. The watermarks should progress to be equal to the source + TransformWatermarks onTimeWatermarks = + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), null); + assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); + assertThat(onTimeWatermarks.getOutputWatermark(), equalTo(sourceWatermark)); + + Bundle lateDataBundle = timestampedBundle( + createdInts, TimestampedValue.of(3, new Instant(-1000L))); + + // the late data arrives in a downstream PCollection after its watermark has advanced past it; + // we don't advance the watermark past the current watermark until we've consumed the late data + TransformWatermarks bufferedLateWm = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(lateDataBundle), + new Instant(2_000_000L)); + assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); + + // The input watermark should be held to its previous value (not advanced due to late data; not + // moved backwards in the presence of watermarks due to monotonicity). + TransformWatermarks lateDataBufferedWatermark = + manager.getWatermarks(keyed.getProducingTransformInternal()); + assertThat(lateDataBufferedWatermark.getInputWatermark(), not(earlierThan(sourceWatermark))); + assertThat(lateDataBufferedWatermark.getOutputWatermark(), not(earlierThan(sourceWatermark))); + + Bundle> lateKeyedBundle = timestampedBundle( + keyed, TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + manager.updateWatermarks(lateDataBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(lateKeyedBundle), null); + } + + /** + * Demonstrates that after watermarks of an upstream transform are updated, but no output has been + * produced, the watermarks of a downstream process are advanced. + */ + @Test + public void getWatermarksAfterOnlyEmptyOutput() { + Bundle emptyCreateOutput = globallyWindowedBundle(createdInts); + TransformWatermarks updatedSourceWatermarks = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + + assertThat(updatedSourceWatermarks.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + + TransformWatermarks finishedFilterWatermarks = + manager.getWatermarks(filtered.getProducingTransformInternal()); + assertThat(finishedFilterWatermarks.getInputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat(finishedFilterWatermarks.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + } + + /** + * Demonstrates that after watermarks of an upstream transform are updated, but no output has been + * produced, and the downstream transform has a watermark hold, the watermark is held to the hold. + */ + @Test + public void getWatermarksAfterHoldAndEmptyOutput() { + Bundle firstCreateOutput = globallyWindowedBundle(createdInts, 1, 2); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(firstCreateOutput), new Instant(12_000L)); + + Bundle firstFilterOutput = globallyWindowedBundle(filtered); + TransformWatermarks firstFilterWatermarks = + manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), + Collections.>singleton(firstFilterOutput), new Instant(10_000L)); + assertThat(firstFilterWatermarks.getInputWatermark(), not(earlierThan(new Instant(12_000L)))); + assertThat(firstFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); + + Bundle emptyCreateOutput = globallyWindowedBundle(createdInts); + TransformWatermarks updatedSourceWatermarks = + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + + assertThat(updatedSourceWatermarks.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + + TransformWatermarks finishedFilterWatermarks = + manager.getWatermarks(filtered.getProducingTransformInternal()); + assertThat(finishedFilterWatermarks.getInputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat(finishedFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); + } + + private static Matcher earlierThan(final Instant laterInstant) { + return new BaseMatcher() { + @Override + public boolean matches(Object item) { + ReadableInstant instant = (ReadableInstant) item; + return instant.isBefore(laterInstant); + } + + @Override + public void describeTo(Description description) { + description.appendText("earlier than ").appendValue(laterInstant); + } + }; + } + + private static Matcher laterThan(final Instant shouldBeEarlier) { + return new BaseMatcher() { + @Override + public boolean matches(Object item) { + ReadableInstant instant = (ReadableInstant) item; + return instant.isAfter(shouldBeEarlier); + } + + @Override + public void describeTo(Description description) { + description.appendText("later than ").appendValue(shouldBeEarlier); + }}; + } + + @SafeVarargs + private final Bundle timestampedBundle( + PCollection pc, TimestampedValue... values) { + Bundle bundle = InProcessBundle.unkeyed(pc); + for (TimestampedValue value : values) { + bundle.add( + WindowedValue.timestampedValueInGlobalWindow(value.getValue(), value.getTimestamp())); + } + return bundle; + } + + @SafeVarargs + private final Bundle globallyWindowedBundle(PCollection pc, T... values) { + Bundle bundle = InProcessBundle.unkeyed(pc); + for (T value : values) { + bundle.add(WindowedValue.valueInGlobalWindow(value)); + } + return bundle; + } +} From b88c2c449e0677cf8985d8e37ea3e15711b6667c Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 4 Feb 2016 09:37:39 -0800 Subject: [PATCH 074/751] Have worker maven module depend on unshaded/unrelocated test jar Worker maven module when compiling/running tests, executes before shading, so must depend on targets before relocation/repackaging. This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113858878 --- sdk/pom.xml | 21 ++------------------ worker/pom.xml | 53 +++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 50 insertions(+), 24 deletions(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index 24fc45cc40..2526c10b65 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -288,24 +288,7 @@ maven-shade-plugin 2.4.1 - - - internal-only - package - - shade - - - true - internal-only - - - - + bundle-and-repackage package @@ -345,7 +328,7 @@ - bundle-rest-without-repackaging diff --git a/worker/pom.xml b/worker/pom.xml index 1bab41bc61..aff36240b5 100644 --- a/worker/pom.xml +++ b/worker/pom.xml @@ -42,14 +42,53 @@ + + ${project.build.directory}/generated/src/main/java + ${project.build.directory}/generated/src/test/java + + + + com.google.code.maven-replacer-plugin + replacer + 1.5.3 + + + process-sources + + replace + + + + + ${project.basedir} + ${project.build.directory} + generated + + src/**/*.java + + + + import com.google.common. + import com.google.cloud.dataflow.sdk.repackaged.com.google.common. + + + import com.google.thirdparty. + import com.google.cloud.dataflow.sdk.repackaged.com.google.thirdparty. + + + + + org.apache.maven.plugins maven-compiler-plugin - + org.apache.maven.plugins maven-checkstyle-plugin @@ -68,6 +107,10 @@ false true ${project.build.directory}/generated-test-sources/** + + ${project.build.directory}/src/main/java + ${project.build.directory}/src/test/java @@ -155,11 +198,11 @@ the second relocation. --> com.google.common - com.google.cloud.dataflow.sdk.repackaged.com.google.common + com.google.cloud.dataflow.worker.repackaged.com.google.common com.google.thirdparty - com.google.cloud.dataflow.sdk.repackaged.com.google.thirdparty + com.google.cloud.dataflow.worker.repackaged.com.google.thirdparty @@ -209,7 +252,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all ${project.version} - internal-only + provided From 396e0cc1a0a29aa977023c4f5e017e6176883b83 Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 4 Feb 2016 09:49:46 -0800 Subject: [PATCH 075/751] Separate CustomSources into worker and non-worker pieces ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113860002 --- .../sdk/runners/dataflow/CustomSources.java | 484 ----------- .../sdk/runners/worker/ReaderFactory.java | 6 +- .../worker/SourceOperationExecutor.java | 5 +- .../runners/worker/WorkerCustomSources.java | 572 +++++++++++++ .../runners/dataflow/CustomSourcesTest.java | 333 +------- .../worker/WorkerCustomSourcesTest.java | 749 ++++++++++++++++++ 6 files changed, 1340 insertions(+), 809 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java index 81d607e469..238ec4b0f3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java @@ -16,29 +16,14 @@ package com.google.cloud.dataflow.sdk.runners.dataflow; -import static com.google.api.client.util.Base64.decodeBase64; import static com.google.api.client.util.Base64.encodeBase64String; import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudSourceToDictionary; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.deserializeFromByteArray; import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; import static com.google.cloud.dataflow.sdk.util.Structs.addString; import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; import static com.google.common.base.Preconditions.checkArgument; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.Base64; -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.DerivedSource; -import com.google.api.services.dataflow.model.DynamicSourceSplit; import com.google.api.services.dataflow.model.SourceMetadata; -import com.google.api.services.dataflow.model.SourceOperationResponse; -import com.google.api.services.dataflow.model.SourceSplitOptions; -import com.google.api.services.dataflow.model.SourceSplitRequest; -import com.google.api.services.dataflow.model.SourceSplitResponse; -import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Source; @@ -47,35 +32,21 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.DataflowApiUtils; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; -import com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils; -import com.google.cloud.dataflow.sdk.runners.worker.StreamingModeExecutionContext; import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; import org.joda.time.Duration; -import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import javax.annotation.Nullable; /** * A helper class for supporting sources defined as {@code Source}. @@ -86,7 +57,6 @@ public class CustomSources { private static final String SERIALIZED_SOURCE = "serialized_source"; @VisibleForTesting static final String SERIALIZED_SOURCE_SPLITS = "serialized_source_splits"; - private static final long DEFAULT_DESIRED_BUNDLE_SIZE_BYTES = 64 * (1 << 20); /** * The current limit on the size of a ReportWorkItemStatus RPC to Google Cloud Dataflow, which * includes the initial splits, is 20 MB. @@ -95,270 +65,12 @@ public class CustomSources { private static final Logger LOG = LoggerFactory.getLogger(CustomSources.class); - /** - * A {@code DynamicSplitResult} specified explicitly by a pair of {@code BoundedSource} - * objects describing the primary and residual sources. - */ - public static final class BoundedSourceSplit implements NativeReader.DynamicSplitResult { - public final BoundedSource primary; - public final BoundedSource residual; - - public BoundedSourceSplit(BoundedSource primary, BoundedSource residual) { - this.primary = primary; - this.residual = residual; - } - - @Override - public String toString() { - return String.format("", primary, residual); - } - } - - public static DynamicSourceSplit toSourceSplit( - BoundedSourceSplit sourceSplitResult, PipelineOptions options) { - DynamicSourceSplit sourceSplit = new DynamicSourceSplit(); - com.google.api.services.dataflow.model.Source primarySource; - com.google.api.services.dataflow.model.Source residualSource; - try { - primarySource = serializeToCloudSource(sourceSplitResult.primary, options); - residualSource = serializeToCloudSource(sourceSplitResult.residual, options); - } catch (Exception e) { - throw new RuntimeException("Failed to serialize one of the parts of the source split", e); - } - sourceSplit.setPrimary( - new DerivedSource() - .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") - .setSource(primarySource)); - sourceSplit.setResidual( - new DerivedSource() - .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") - .setSource(residualSource)); - return sourceSplit; - } - - /** - * Executes a protocol-level split {@code SourceOperationRequest} for bounded sources - * by deserializing its source to a {@code BoundedSource}, splitting it, and - * serializing results back. - * - *

When the splits produced by this function are too large to be serialized to the Dataflow - * API, splitting is retried once with an increase in the desired bundle size. This change aims - * to work around API limitations on split size. - */ - public static SourceOperationResponse performSplit( - SourceSplitRequest request, PipelineOptions options) throws Exception { - Source anySource = deserializeFromCloudSource(request.getSource().getSpec()); - checkArgument( - anySource instanceof BoundedSource, "Cannot split a non-Bounded source: %s", anySource); - BoundedSource source = (BoundedSource) anySource; - - // Compute the desired bundle size given by the service, or default if none was provided. - long desiredBundleSizeBytes = DEFAULT_DESIRED_BUNDLE_SIZE_BYTES; - SourceSplitOptions splitOptions = request.getOptions(); - if (splitOptions != null && splitOptions.getDesiredBundleSizeBytes() != null) { - desiredBundleSizeBytes = splitOptions.getDesiredBundleSizeBytes(); - } - - // Try generating initial splits normally. - SourceSplitResponse splits = performSplit(source, options, desiredBundleSizeBytes); - long serializedSize = DataflowApiUtils.computeSerializedSizeBytes(splits); - - // If split response is too large, scale desired size for expected DATAFLOW_API_SIZE_BYTES/2. - if (serializedSize > DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES) { - double expansion = 2 * (double) serializedSize / DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; - long expandedBundleSizeBytes = (long) (desiredBundleSizeBytes * expansion); - LOG.warn( - "Splitting source {} into bundles of estimated size {} bytes produced {} bundles, which" - + " have total serialized size {} bytes. As this is too large for the Google Cloud" - + " Dataflow API, retrying splitting once with increased desiredBundleSizeBytes {}" - + " to reduce the number of splits.", - source, - desiredBundleSizeBytes, - splits.getBundles().size(), - serializedSize, - expandedBundleSizeBytes); - splits = performSplit(source, options, expandedBundleSizeBytes); - } - - return new SourceOperationResponse().setSplit(splits); - } - - /** - * Factory to create a {@link CustomSources} from a Dataflow API - * source specification. - */ - public static class Factory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - // The parameter "coder" is deliberately never used. It is an artifact of ReaderFactory: - // some readers need a coder, some don't (i.e. for some it doesn't even make sense), - // but ReaderFactory passes it to all readers anyway. - return CustomSources.create(spec, options, executionContext); - } - } - - public static NativeReader> create( - final CloudObject spec, final PipelineOptions options, ExecutionContext executionContext) - throws Exception { - - @SuppressWarnings("unchecked") - final Source source = (Source) deserializeFromCloudSource(spec); - - if (source instanceof BoundedSource) { - @SuppressWarnings({"unchecked", "rawtypes"}) - NativeReader> reader = - (NativeReader) - new NativeReader>() { - @Override - public NativeReaderIterator> iterator() throws IOException { - return new BoundedReaderIterator<>( - ((BoundedSource) source).createReader(options)); - } - }; - return reader; - } else if (source instanceof UnboundedSource) { - @SuppressWarnings({"unchecked", "rawtypes"}) - NativeReader> reader = - (NativeReader) - new UnboundedReader( - options, spec, (StreamingModeExecutionContext) executionContext); - return reader; - } else { - throw new IllegalArgumentException("Unexpected source kind: " + source.getClass()); - } - } - private static final ByteString firstSplitKey = ByteString.copyFromUtf8("0000000000000001"); public static boolean isFirstUnboundedSourceSplit(ByteString splitKey) { return splitKey.equals(firstSplitKey); } - /** - * {@link NativeReader} for reading from {@link UnboundedSource UnboundedSources}. - */ - private static class UnboundedReader - extends NativeReader>> { - private final PipelineOptions options; - private final CloudObject spec; - private final StreamingModeExecutionContext context; - - UnboundedReader( - PipelineOptions options, CloudObject spec, StreamingModeExecutionContext context) { - this.options = options; - this.spec = spec; - this.context = context; - } - - @Override - @SuppressWarnings("unchecked") - public NativeReaderIterator>> iterator() { - UnboundedSource.UnboundedReader reader = - (UnboundedSource.UnboundedReader) context.getCachedReader(); - final boolean started = reader != null; - if (reader == null) { - String key = context.getSerializedKey().toStringUtf8(); - // Key is expected to be a zero-padded integer representing the split index. - int splitIndex = Integer.parseInt(key.substring(0, 16), 16) - 1; - - UnboundedSource splitSource = parseSource(splitIndex); - - UnboundedSource.CheckpointMark checkpoint = null; - if (splitSource.getCheckpointMarkCoder() != null) { - checkpoint = context.getReaderCheckpoint(splitSource.getCheckpointMarkCoder()); - } - - reader = splitSource.createReader(options, checkpoint); - } - - context.setActiveReader(reader); - - return new UnboundedReaderIterator<>(reader, started); - } - - @Override - public boolean supportsRestart() { - return true; - } - - @SuppressWarnings("unchecked") - private UnboundedSource parseSource(int index) { - List serializedSplits = null; - try { - serializedSplits = getStrings(spec, SERIALIZED_SOURCE_SPLITS, null); - } catch (Exception e) { - throw new RuntimeException("Parsing serialized source splits failed: ", e); - } - checkArgument(serializedSplits != null, "UnboundedSource object did not contain splits"); - checkArgument( - index < serializedSplits.size(), - "UnboundedSource splits contained too few splits. Requested index was %s, size was %s", - index, - serializedSplits.size()); - Object rawSource = deserializeFromByteArray( - decodeBase64(serializedSplits.get(index)), "UnboundedSource split"); - if (!(rawSource instanceof UnboundedSource)) { - throw new IllegalArgumentException("Expected UnboundedSource, got " + rawSource.getClass()); - } - return (UnboundedSource) rawSource; - } - } - - private static SourceSplitResponse performSplit( - BoundedSource source, PipelineOptions options, long desiredBundleSizeBytes) - throws Exception { - LOG.debug("Splitting source {} into bundles of size {}", source, desiredBundleSizeBytes); - - List> bundles = - ((BoundedSource) source).splitIntoBundles(desiredBundleSizeBytes, options); - List splits = new ArrayList<>(bundles.size()); - - // Produce simple independent, unsplittable bundles with no metadata attached. - LOG.debug("Splitting produced {} bundles", bundles.size()); - for (BoundedSource split : bundles) { - try { - split.validate(); - } catch (Exception e) { - throw new IllegalArgumentException( - String.format( - "Splitting a valid source produced an invalid source." - + "\nOriginal source: %s\nInvalid source: %s", - source, - split), - e); - } - - splits.add( - new DerivedSource() - .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") - .setSource(serializeToCloudSource(split, options).setDoesNotNeedSplitting(true))); - } - - // Return all the splits in the SourceSplitResponse. - return new SourceSplitResponse() - .setBundles(splits) - .setOutcome("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED"); - } - - private static Source deserializeFromCloudSource(Map spec) throws Exception { - Source source = (Source) deserializeFromByteArray( - Base64.decodeBase64(getString(spec, SERIALIZED_SOURCE)), "Source"); - try { - source.validate(); - } catch (Exception e) { - LOG.error("Invalid source: {}", source, e); - throw e; - } - return source; - } - private static int getDesiredNumUnboundedSourceSplits(DataflowPipelineOptions options) { if (options.getMaxNumWorkers() > 0) { return options.getMaxNumWorkers(); @@ -448,109 +160,6 @@ public static void translateReadHelper(Source source, } } - private static class BoundedReaderIterator - extends NativeReader.NativeReaderIterator> { - private BoundedSource.BoundedReader reader; - - private BoundedReaderIterator(BoundedSource.BoundedReader reader) { - this.reader = reader; - } - - @Override - public boolean start() throws IOException { - try { - return reader.start(); - } catch (Exception e) { - throw new IOException( - "Failed to start reading from source: " + reader.getCurrentSource(), e); - } - } - - @Override - public boolean advance() throws IOException { - try { - return reader.advance(); - } catch (Exception e) { - throw new IOException( - "Failed to advance reader of source: " + reader.getCurrentSource(), e); - } - } - - @Override - public WindowedValue getCurrent() throws NoSuchElementException { - return WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp()); - } - - @Override - public void close() throws IOException { - reader.close(); - } - - @Override - public NativeReader.Progress getProgress() { - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - Double fractionConsumed = reader.getFractionConsumed(); - if (fractionConsumed != null) { - progress.setFractionConsumed(fractionConsumed); - } - return SourceTranslationUtils.cloudProgressToReaderProgress(progress); - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest request) { - ApproximateSplitRequest stopPosition = - SourceTranslationUtils.splitRequestToApproximateSplitRequest(request); - Double fractionConsumed = stopPosition.getFractionConsumed(); - if (fractionConsumed == null) { - // Only truncating at a fraction is currently supported. - LOG.info( - "Rejecting split request because custom sources only support splits at fraction: {}", - stopPosition); - return null; - } - BoundedSource original = reader.getCurrentSource(); - BoundedSource residual = reader.splitAtFraction(fractionConsumed); - if (residual == null) { - LOG.info("Rejecting split request because custom reader returned null residual source."); - return null; - } - // Try to catch some potential subclass implementation errors early. - BoundedSource primary = reader.getCurrentSource(); - if (original == primary) { - throw new IllegalStateException( - "Successful split did not change the current source: primary is identical to original" - + " (Source objects MUST be immutable): " + primary); - } - if (original == residual) { - throw new IllegalStateException( - "Successful split did not change the current source: residual is identical to original" - + " (Source objects MUST be immutable): " + residual); - } - try { - primary.validate(); - } catch (Exception e) { - throw new IllegalStateException( - "Successful split produced an illegal primary source. " - + "\nOriginal: " + original + "\nPrimary: " + primary + "\nResidual: " + residual); - } - try { - residual.validate(); - } catch (Exception e) { - throw new IllegalStateException( - "Successful split produced an illegal residual source. " - + "\nOriginal: " + original + "\nPrimary: " + primary + "\nResidual: " + residual); - } - return new BoundedSourceSplit(primary, residual); - } - - @Override - public double getRemainingParallelism() { - return Double.NaN; - } - } - // Commit at least once every 10 seconds or 10k records. This keeps the watermark advancing // smoothly, and ensures that not too much work will have to be reprocessed in the event of // a crash. @@ -558,97 +167,4 @@ public double getRemainingParallelism() { static final int MAX_UNBOUNDED_BUNDLE_SIZE = 10000; @VisibleForTesting static final Duration MAX_UNBOUNDED_BUNDLE_READ_TIME = Duration.standardSeconds(10); - - private static class UnboundedReaderIterator - extends NativeReader.NativeReaderIterator>> { - private final UnboundedSource.UnboundedReader reader; - private final boolean started; - private final Instant endTime; - private int elemsRead; - - private UnboundedReaderIterator(UnboundedSource.UnboundedReader reader, boolean started) { - this.reader = reader; - this.endTime = Instant.now().plus(MAX_UNBOUNDED_BUNDLE_READ_TIME); - this.elemsRead = 0; - this.started = started; - } - - @Override - public boolean start() throws IOException { - if (started) { - // This is a reader that has been restored from the unbounded reader cache. - // It has already been started, so this call to start() should delegate - // to advance() instead. - return advance(); - } - try { - if (!reader.start()) { - return false; - } - } catch (Exception e) { - throw new IOException( - "Failed to start reading from source: " + reader.getCurrentSource(), e); - } - elemsRead++; - return true; - } - - @Override - public boolean advance() throws IOException { - if (elemsRead >= MAX_UNBOUNDED_BUNDLE_SIZE - || Instant.now().isAfter(endTime)) { - return false; - } - - // Backoff starting at 100ms, for approximately 1s total. 100+150+225+337.5~=1000. - BackOff backoff = new AttemptBoundedExponentialBackOff(5, 100); - while (true) { - try { - if (reader.advance()) { - elemsRead++; - return true; - } - } catch (Exception e) { - throw new IOException("Failed to advance source: " + reader.getCurrentSource(), e); - } - long nextBackoff = backoff.nextBackOffMillis(); - if (nextBackoff == BackOff.STOP) { - return false; - } - try { - Thread.sleep(nextBackoff); - } catch (InterruptedException e) { - // ignore. - } - } - } - - @Override - public WindowedValue> getCurrent() throws NoSuchElementException { - WindowedValue result = - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp()); - return result.withValue( - new ValueWithRecordId<>(result.getValue(), reader.getCurrentRecordId())); - } - - @Override - public void close() {} - - @Override - public NativeReader.Progress getProgress() { - return null; - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest request) { - return null; - } - - @Override - public double getRemainingParallelism() { - return Double.NaN; - } - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java index 5ea2490475..e5a810d755 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java @@ -19,7 +19,6 @@ import com.google.api.services.dataflow.model.Source; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; import com.google.cloud.dataflow.sdk.util.ExecutionContext; @@ -97,7 +96,10 @@ public static Registry defaultRegistry() { // Custom sources factories.put( "com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources", - new CustomSources.Factory()); + new WorkerCustomSources.Factory()); + factories.put( + "com.google.cloud.dataflow.sdk.runners.dataflow.WorkerCustomSources", + new WorkerCustomSources.Factory()); return new Registry(factories); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java index cdace38d2d..ad13e3a69a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java @@ -20,7 +20,6 @@ import com.google.api.services.dataflow.model.SourceOperationResponse; import com.google.api.services.dataflow.model.SourceSplitRequest; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.WorkExecutor; @@ -56,7 +55,7 @@ public void execute() throws Exception { LOG.debug("Executing source operation"); SourceSplitRequest split = request.getSplit(); if (split != null) { - this.response = CustomSources.performSplit(split, options); + this.response = WorkerCustomSources.performSplit(split, options); } else { throw new UnsupportedOperationException("Unsupported source operation request: " + request); } @@ -71,7 +70,7 @@ static boolean isSplitResponseTooLarge(SourceOperationResponse operationResponse try { long splitResponseSize = DataflowApiUtils.computeSerializedSizeBytes(operationResponse.getSplit()); - return splitResponseSize > CustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; + return splitResponseSize > WorkerCustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; } catch (IOException e) { /* Assume that the size is not too large, so that the actual API error is exposed. */ LOG.warn("Error determining the size of the split response.", e); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java new file mode 100644 index 0000000000..59da1f0805 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java @@ -0,0 +1,572 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import static com.google.api.client.util.Base64.decodeBase64; +import static com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources.serializeToCloudSource; +import static com.google.cloud.dataflow.sdk.util.SerializableUtils.deserializeFromByteArray; +import static com.google.cloud.dataflow.sdk.util.Structs.getString; +import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.api.client.util.BackOff; +import com.google.api.client.util.Base64; +import com.google.api.services.dataflow.model.ApproximateReportedProgress; +import com.google.api.services.dataflow.model.ApproximateSplitRequest; +import com.google.api.services.dataflow.model.DerivedSource; +import com.google.api.services.dataflow.model.DynamicSourceSplit; +import com.google.api.services.dataflow.model.SourceOperationResponse; +import com.google.api.services.dataflow.model.SourceSplitOptions; +import com.google.api.services.dataflow.model.SourceSplitRequest; +import com.google.api.services.dataflow.model.SourceSplitResponse; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.Source; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; +import com.google.common.annotations.VisibleForTesting; +import com.google.protobuf.ByteString; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import javax.annotation.Nullable; + + +/** + * A helper class for supporting sources defined as {@code Source}. + * + *

Provides a bridge between the high-level {@code Source} API and the + * low-level {@code CloudSource} class. + */ +public class WorkerCustomSources { + private static final String SERIALIZED_SOURCE = "serialized_source"; + @VisibleForTesting static final String SERIALIZED_SOURCE_SPLITS = "serialized_source_splits"; + private static final long DEFAULT_DESIRED_BUNDLE_SIZE_BYTES = 64 * (1 << 20); + /** + * The current limit on the size of a ReportWorkItemStatus RPC to Google Cloud Dataflow, which + * includes the initial splits, is 20 MB. + */ + public static final long DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES = 20 * (1 << 20); + + private static final Logger LOG = LoggerFactory.getLogger(WorkerCustomSources.class); + + /** + * A {@code DynamicSplitResult} specified explicitly by a pair of {@code BoundedSource} + * objects describing the primary and residual sources. + */ + public static final class BoundedSourceSplit implements NativeReader.DynamicSplitResult { + public final BoundedSource primary; + public final BoundedSource residual; + + public BoundedSourceSplit(BoundedSource primary, BoundedSource residual) { + this.primary = primary; + this.residual = residual; + } + + @Override + public String toString() { + return String.format("", primary, residual); + } + } + + public static DynamicSourceSplit toSourceSplit( + BoundedSourceSplit sourceSplitResult, PipelineOptions options) { + DynamicSourceSplit sourceSplit = new DynamicSourceSplit(); + com.google.api.services.dataflow.model.Source primarySource; + com.google.api.services.dataflow.model.Source residualSource; + try { + primarySource = serializeToCloudSource(sourceSplitResult.primary, options); + residualSource = serializeToCloudSource(sourceSplitResult.residual, options); + } catch (Exception e) { + throw new RuntimeException("Failed to serialize one of the parts of the source split", e); + } + sourceSplit.setPrimary( + new DerivedSource() + .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") + .setSource(primarySource)); + sourceSplit.setResidual( + new DerivedSource() + .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") + .setSource(residualSource)); + return sourceSplit; + } + + /** + * Executes a protocol-level split {@code SourceOperationRequest} for bounded sources + * by deserializing its source to a {@code BoundedSource}, splitting it, and + * serializing results back. + * + *

When the splits produced by this function are too large to be serialized to the Dataflow + * API, splitting is retried once with an increase in the desired bundle size. This change aims + * to work around API limitations on split size. + */ + public static SourceOperationResponse performSplit( + SourceSplitRequest request, PipelineOptions options) throws Exception { + Source anySource = deserializeFromCloudSource(request.getSource().getSpec()); + checkArgument( + anySource instanceof BoundedSource, "Cannot split a non-Bounded source: %s", anySource); + BoundedSource source = (BoundedSource) anySource; + + // Compute the desired bundle size given by the service, or default if none was provided. + long desiredBundleSizeBytes = DEFAULT_DESIRED_BUNDLE_SIZE_BYTES; + SourceSplitOptions splitOptions = request.getOptions(); + if (splitOptions != null && splitOptions.getDesiredBundleSizeBytes() != null) { + desiredBundleSizeBytes = splitOptions.getDesiredBundleSizeBytes(); + } + + // Try generating initial splits normally. + SourceSplitResponse splits = performSplit(source, options, desiredBundleSizeBytes); + long serializedSize = DataflowApiUtils.computeSerializedSizeBytes(splits); + + // If split response is too large, scale desired size for expected DATAFLOW_API_SIZE_BYTES/2. + if (serializedSize > DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES) { + double expansion = 2 * (double) serializedSize / DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; + long expandedBundleSizeBytes = (long) (desiredBundleSizeBytes * expansion); + LOG.warn( + "Splitting source {} into bundles of estimated size {} bytes produced {} bundles, which" + + " have total serialized size {} bytes. As this is too large for the Google Cloud" + + " Dataflow API, retrying splitting once with increased desiredBundleSizeBytes {}" + + " to reduce the number of splits.", + source, + desiredBundleSizeBytes, + splits.getBundles().size(), + serializedSize, + expandedBundleSizeBytes); + splits = performSplit(source, options, expandedBundleSizeBytes); + } + + return new SourceOperationResponse().setSplit(splits); + } + + /** + * Factory to create a {@link WorkerCustomSources} from a Dataflow API + * source specification. + */ + public static class Factory implements ReaderFactory { + @Override + public NativeReader create( + CloudObject spec, + @Nullable Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator, + @Nullable String operationName) + throws Exception { + // The parameter "coder" is deliberately never used. It is an artifact of ReaderFactory: + // some readers need a coder, some don't (i.e. for some it doesn't even make sense), + // but ReaderFactory passes it to all readers anyway. + return WorkerCustomSources.create(spec, options, executionContext); + } + } + + public static NativeReader> create( + final CloudObject spec, final PipelineOptions options, ExecutionContext executionContext) + throws Exception { + + @SuppressWarnings("unchecked") + final Source source = (Source) deserializeFromCloudSource(spec); + + if (source instanceof BoundedSource) { + @SuppressWarnings({"unchecked", "rawtypes"}) + NativeReader> reader = + (NativeReader) + new NativeReader>() { + @Override + public NativeReaderIterator> iterator() throws IOException { + return new BoundedReaderIterator<>( + ((BoundedSource) source).createReader(options)); + } + }; + return reader; + } else if (source instanceof UnboundedSource) { + @SuppressWarnings({"unchecked", "rawtypes"}) + NativeReader> reader = + (NativeReader) + new UnboundedReader( + options, spec, (StreamingModeExecutionContext) executionContext); + return reader; + } else { + throw new IllegalArgumentException("Unexpected source kind: " + source.getClass()); + } + } + + private static final ByteString firstSplitKey = ByteString.copyFromUtf8("0000000000000001"); + + public static boolean isFirstUnboundedSourceSplit(ByteString splitKey) { + return splitKey.equals(firstSplitKey); + } + + /** + * {@link NativeReader} for reading from {@link UnboundedSource UnboundedSources}. + */ + private static class UnboundedReader + extends NativeReader>> { + private final PipelineOptions options; + private final CloudObject spec; + private final StreamingModeExecutionContext context; + + UnboundedReader( + PipelineOptions options, CloudObject spec, StreamingModeExecutionContext context) { + this.options = options; + this.spec = spec; + this.context = context; + } + + @Override + @SuppressWarnings("unchecked") + public NativeReaderIterator>> iterator() { + UnboundedSource.UnboundedReader reader = + (UnboundedSource.UnboundedReader) context.getCachedReader(); + final boolean started = reader != null; + if (reader == null) { + String key = context.getSerializedKey().toStringUtf8(); + // Key is expected to be a zero-padded integer representing the split index. + int splitIndex = Integer.parseInt(key.substring(0, 16), 16) - 1; + + UnboundedSource splitSource = parseSource(splitIndex); + + UnboundedSource.CheckpointMark checkpoint = null; + if (splitSource.getCheckpointMarkCoder() != null) { + checkpoint = context.getReaderCheckpoint(splitSource.getCheckpointMarkCoder()); + } + + reader = splitSource.createReader(options, checkpoint); + } + + context.setActiveReader(reader); + + return new UnboundedReaderIterator<>(reader, started); + } + + @Override + public boolean supportsRestart() { + return true; + } + + @SuppressWarnings("unchecked") + private UnboundedSource parseSource(int index) { + List serializedSplits = null; + try { + serializedSplits = getStrings(spec, SERIALIZED_SOURCE_SPLITS, null); + } catch (Exception e) { + throw new RuntimeException("Parsing serialized source splits failed: ", e); + } + checkArgument(serializedSplits != null, "UnboundedSource object did not contain splits"); + checkArgument( + index < serializedSplits.size(), + "UnboundedSource splits contained too few splits. Requested index was %s, size was %s", + index, + serializedSplits.size()); + Object rawSource = deserializeFromByteArray( + decodeBase64(serializedSplits.get(index)), "UnboundedSource split"); + if (!(rawSource instanceof UnboundedSource)) { + throw new IllegalArgumentException("Expected UnboundedSource, got " + rawSource.getClass()); + } + return (UnboundedSource) rawSource; + } + } + + private static SourceSplitResponse performSplit( + BoundedSource source, PipelineOptions options, long desiredBundleSizeBytes) + throws Exception { + LOG.debug("Splitting source {} into bundles of size {}", source, desiredBundleSizeBytes); + + List> bundles = + ((BoundedSource) source).splitIntoBundles(desiredBundleSizeBytes, options); + List splits = new ArrayList<>(bundles.size()); + + // Produce simple independent, unsplittable bundles with no metadata attached. + LOG.debug("Splitting produced {} bundles", bundles.size()); + for (BoundedSource split : bundles) { + try { + split.validate(); + } catch (Exception e) { + throw new IllegalArgumentException( + String.format( + "Splitting a valid source produced an invalid source." + + "\nOriginal source: %s\nInvalid source: %s", + source, + split), + e); + } + + splits.add( + new DerivedSource() + .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") + .setSource(serializeToCloudSource(split, options).setDoesNotNeedSplitting(true))); + } + + // Return all the splits in the SourceSplitResponse. + return new SourceSplitResponse() + .setBundles(splits) + .setOutcome("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED"); + } + + private static Source deserializeFromCloudSource(Map spec) throws Exception { + Source source = (Source) deserializeFromByteArray( + Base64.decodeBase64(getString(spec, SERIALIZED_SOURCE)), "Source"); + try { + source.validate(); + } catch (Exception e) { + LOG.error("Invalid source: {}", source, e); + throw e; + } + return source; + } + + public static void evaluateReadHelper( + Read.Bounded transform, DirectPipelineRunner.EvaluationContext context) { + try { + List> output = new ArrayList<>(); + BoundedSource source = transform.getSource(); + try (BoundedSource.BoundedReader reader = + source.createReader(context.getPipelineOptions())) { + for (boolean available = reader.start(); available; available = reader.advance()) { + output.add( + DirectPipelineRunner.ValueWithMetadata.of( + WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp()))); + } + } + context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static class BoundedReaderIterator + extends NativeReader.NativeReaderIterator> { + private BoundedSource.BoundedReader reader; + + private BoundedReaderIterator(BoundedSource.BoundedReader reader) { + this.reader = reader; + } + + @Override + public boolean start() throws IOException { + try { + return reader.start(); + } catch (Exception e) { + throw new IOException( + "Failed to start reading from source: " + reader.getCurrentSource(), e); + } + } + + @Override + public boolean advance() throws IOException { + try { + return reader.advance(); + } catch (Exception e) { + throw new IOException( + "Failed to advance reader of source: " + reader.getCurrentSource(), e); + } + } + + @Override + public WindowedValue getCurrent() throws NoSuchElementException { + return WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp()); + } + + @Override + public void close() throws IOException { + reader.close(); + } + + @Override + public NativeReader.Progress getProgress() { + ApproximateReportedProgress progress = new ApproximateReportedProgress(); + Double fractionConsumed = reader.getFractionConsumed(); + if (fractionConsumed != null) { + progress.setFractionConsumed(fractionConsumed); + } + return SourceTranslationUtils.cloudProgressToReaderProgress(progress); + } + + @Override + public NativeReader.DynamicSplitResult requestDynamicSplit( + NativeReader.DynamicSplitRequest request) { + ApproximateSplitRequest stopPosition = + SourceTranslationUtils.splitRequestToApproximateSplitRequest(request); + Double fractionConsumed = stopPosition.getFractionConsumed(); + if (fractionConsumed == null) { + // Only truncating at a fraction is currently supported. + LOG.info( + "Rejecting split request because custom sources only support splits at fraction: {}", + stopPosition); + return null; + } + BoundedSource original = reader.getCurrentSource(); + BoundedSource residual = reader.splitAtFraction(fractionConsumed); + if (residual == null) { + LOG.info("Rejecting split request because custom reader returned null residual source."); + return null; + } + // Try to catch some potential subclass implementation errors early. + BoundedSource primary = reader.getCurrentSource(); + if (original == primary) { + throw new IllegalStateException( + "Successful split did not change the current source: primary is identical to original" + + " (Source objects MUST be immutable): " + primary); + } + if (original == residual) { + throw new IllegalStateException( + "Successful split did not change the current source: residual is identical to original" + + " (Source objects MUST be immutable): " + residual); + } + try { + primary.validate(); + } catch (Exception e) { + throw new IllegalStateException( + "Successful split produced an illegal primary source. " + + "\nOriginal: " + original + "\nPrimary: " + primary + "\nResidual: " + residual); + } + try { + residual.validate(); + } catch (Exception e) { + throw new IllegalStateException( + "Successful split produced an illegal residual source. " + + "\nOriginal: " + original + "\nPrimary: " + primary + "\nResidual: " + residual); + } + return new BoundedSourceSplit(primary, residual); + } + + @Override + public double getRemainingParallelism() { + return Double.NaN; + } + } + + // Commit at least once every 10 seconds or 10k records. This keeps the watermark advancing + // smoothly, and ensures that not too much work will have to be reprocessed in the event of + // a crash. + @VisibleForTesting + static final int MAX_UNBOUNDED_BUNDLE_SIZE = 10000; + @VisibleForTesting + static final Duration MAX_UNBOUNDED_BUNDLE_READ_TIME = Duration.standardSeconds(10); + + private static class UnboundedReaderIterator + extends NativeReader.NativeReaderIterator>> { + private final UnboundedSource.UnboundedReader reader; + private final boolean started; + private final Instant endTime; + private int elemsRead; + + private UnboundedReaderIterator(UnboundedSource.UnboundedReader reader, boolean started) { + this.reader = reader; + this.endTime = Instant.now().plus(MAX_UNBOUNDED_BUNDLE_READ_TIME); + this.elemsRead = 0; + this.started = started; + } + + @Override + public boolean start() throws IOException { + if (started) { + // This is a reader that has been restored from the unbounded reader cache. + // It has already been started, so this call to start() should delegate + // to advance() instead. + return advance(); + } + try { + if (!reader.start()) { + return false; + } + } catch (Exception e) { + throw new IOException( + "Failed to start reading from source: " + reader.getCurrentSource(), e); + } + elemsRead++; + return true; + } + + @Override + public boolean advance() throws IOException { + if (elemsRead >= MAX_UNBOUNDED_BUNDLE_SIZE + || Instant.now().isAfter(endTime)) { + return false; + } + + // Backoff starting at 100ms, for approximately 1s total. 100+150+225+337.5~=1000. + BackOff backoff = new AttemptBoundedExponentialBackOff(5, 100); + while (true) { + try { + if (reader.advance()) { + elemsRead++; + return true; + } + } catch (Exception e) { + throw new IOException("Failed to advance source: " + reader.getCurrentSource(), e); + } + long nextBackoff = backoff.nextBackOffMillis(); + if (nextBackoff == BackOff.STOP) { + return false; + } + try { + Thread.sleep(nextBackoff); + } catch (InterruptedException e) { + // ignore. + } + } + } + + @Override + public WindowedValue> getCurrent() throws NoSuchElementException { + WindowedValue result = + WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp()); + return result.withValue( + new ValueWithRecordId<>(result.getValue(), reader.getCurrentRecordId())); + } + + @Override + public void close() {} + + @Override + public NativeReader.Progress getProgress() { + return null; + } + + @Override + public NativeReader.DynamicSplitResult requestDynamicSplit( + NativeReader.DynamicSplitRequest request) { + return null; + } + + @Override + public double getRemainingParallelism() { + return Double.NaN; + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index a0f19012d3..569c4523f6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -15,60 +15,34 @@ */ package com.google.cloud.dataflow.sdk.runners.dataflow; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtFraction; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.dictionaryToCloudSource; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.deserializeFromByteArray; import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; import static com.google.cloud.dataflow.sdk.util.Structs.getObject; -import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; -import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; import static com.google.common.base.Throwables.getStackTraceAsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.api.services.dataflow.model.DerivedSource; import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.SourceOperationResponse; -import com.google.api.services.dataflow.model.SourceSplitOptions; -import com.google.api.services.dataflow.model.SourceSplitRequest; -import com.google.api.services.dataflow.model.SourceSplitResponse; +import com.google.api.services.dataflow.model.Source; import com.google.api.services.dataflow.model.Step; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; -import com.google.cloud.dataflow.sdk.runners.worker.DataflowApiUtils; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderCacheEntry; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; -import com.google.cloud.dataflow.sdk.runners.worker.StreamingModeExecutionContext; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -76,18 +50,12 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.Preconditions; -import com.google.protobuf.ByteString; import org.joda.time.Duration; import org.joda.time.Instant; @@ -103,13 +71,9 @@ import java.util.List; import java.util.Map; import java.util.NoSuchElementException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; /** - * Tests for {@code BasicSerializableSourceFormat}. + * Tests for {@link CustomSources}. */ @RunWith(JUnit4.class) public class CustomSourcesTest { @@ -257,33 +221,6 @@ public Double getFractionConsumed() { } } - @Test - public void testSplitAndReadBundlesBack() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setNumWorkers(5); - com.google.api.services.dataflow.model.Source source = - translateIOToCloudSource(TestIO.fromRange(10, 20), options); - List> elems = CloudSourceUtils.readElemsFromSource(options, source); - assertEquals(10, elems.size()); - for (int i = 0; i < 10; ++i) { - assertEquals(valueInGlobalWindow(10 + i), elems.get(i)); - } - SourceSplitResponse response = performSplit(source, options, null /*desiredBundleSizeBytes*/); - assertEquals("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED", response.getOutcome()); - List bundles = response.getBundles(); - assertEquals(5, bundles.size()); - for (int i = 0; i < 5; ++i) { - DerivedSource bundle = bundles.get(i); - assertEquals("SOURCE_DERIVATION_MODE_INDEPENDENT", bundle.getDerivationMode()); - com.google.api.services.dataflow.model.Source bundleSource = bundle.getSource(); - assertTrue(bundleSource.getDoesNotNeedSplitting()); - bundleSource.setCodec(source.getCodec()); - List> xs = CloudSourceUtils.readElemsFromSource(options, bundleSource); - assertThat(xs, contains(valueInGlobalWindow(10 + 2 * i), valueInGlobalWindow(11 + 2 * i))); - } - } - @Test public void testDirectPipelineWithoutTimestamps() throws Exception { Pipeline p = TestPipeline.create(); @@ -351,65 +288,6 @@ public void testRangeProgressAndSplitAtFraction() throws Exception { } } - @Test - @SuppressWarnings("unchecked") - public void testProgressAndSourceSplitTranslation() throws Exception { - // Same as previous test, but now using BasicSerializableSourceFormat wrappers. - // We know that the underlying reader behaves correctly (because of the previous test), - // now check that we are wrapping it correctly. - DataflowPipelineOptions options = PipelineOptionsFactory.create() - .as(DataflowPipelineOptions.class); - NativeReader> reader = - (NativeReader>) - ReaderFactory.Registry.defaultRegistry() - .create( - translateIOToCloudSource(TestIO.fromRange(10, 20), options), - options, - null, // executionContext - null, // addCounterMutator - null); // operationName - try (NativeReader.NativeReaderIterator> iterator = reader.iterator()) { - assertTrue(iterator.start()); - assertEquals( - 0.1, - readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), - 1e-6); - assertEquals(valueInGlobalWindow(10), iterator.getCurrent()); - assertEquals( - 0.1, - readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), - 1e-6); - assertTrue(iterator.advance()); - assertEquals(valueInGlobalWindow(11), iterator.getCurrent()); - assertEquals( - 0.2, - readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), - 1e-6); - assertTrue(iterator.advance()); - assertEquals(valueInGlobalWindow(12), iterator.getCurrent()); - - assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0))); - assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0.1f))); - CustomSources.BoundedSourceSplit sourceSplit = - (CustomSources.BoundedSourceSplit) - iterator.requestDynamicSplit(splitRequestAtFraction(0.5f)); - assertNotNull(sourceSplit); - assertThat(readFromSource(sourceSplit.primary, options), contains(10, 11, 12, 13, 14)); - assertThat(readFromSource(sourceSplit.residual, options), contains(15, 16, 17, 18, 19)); - - sourceSplit = - (CustomSources.BoundedSourceSplit) - iterator.requestDynamicSplit(splitRequestAtFraction(0.8f)); - assertNotNull(sourceSplit); - assertThat(readFromSource(sourceSplit.primary, options), contains(10, 11, 12, 13)); - assertThat(readFromSource(sourceSplit.residual, options), contains(14)); - - assertTrue(iterator.advance()); - assertEquals(valueInGlobalWindow(13), iterator.getCurrent()); - assertFalse(iterator.advance()); - } - } - /** * A source that cannot do anything. Intended to be overridden for testing of individual methods. */ @@ -449,52 +327,6 @@ public Coder getDefaultOutputCoder() { } } - private static class SourceProducingInvalidSplits extends MockSource { - private String description; - private String errorMessage; - - private SourceProducingInvalidSplits(String description, String errorMessage) { - this.description = description; - this.errorMessage = errorMessage; - } - - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - Preconditions.checkState(errorMessage == null, "Unexpected invalid source"); - return Arrays.asList( - new SourceProducingInvalidSplits("goodBundle", null), - new SourceProducingInvalidSplits("badBundle", "intentionally invalid")); - } - - @Override - public void validate() { - Preconditions.checkState(errorMessage == null, errorMessage); - } - - @Override - public String toString() { - return description; - } - } - - @Test - public void testSplittingProducedInvalidSource() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - com.google.api.services.dataflow.model.Source cloudSource = - translateIOToCloudSource(new SourceProducingInvalidSplits("original", null), options); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - allOf( - containsString("Splitting a valid source produced an invalid source"), - containsString("original"), - containsString("badBundle"))); - expectedException.expectCause(hasMessage(containsString("intentionally invalid"))); - performSplit(cloudSource, options, null /*desiredBundleSizeBytes*/); - } - private static class FailingReader extends BoundedSource.BoundedReader { private BoundedSource source; @@ -557,8 +389,7 @@ public String toString() { public void testFailureToStartReadingIncludesSourceDetails() throws Exception { DataflowPipelineOptions options = PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - com.google.api.services.dataflow.model.Source source = - translateIOToCloudSource(new SourceProducingFailingReader(), options); + Source source = translateIOToCloudSource(new SourceProducingFailingReader(), options); // Unfortunately Hamcrest doesn't have a matcher that can match on the exception's // printStackTrace(), however we just want to verify that the error and source description // would be contained in the exception *somewhere*, not necessarily in the top-level @@ -573,7 +404,7 @@ public void testFailureToStartReadingIncludesSourceDetails() throws Exception { } } - private static com.google.api.services.dataflow.model.Source translateIOToCloudSource( + private static Source translateIOToCloudSource( BoundedSource io, DataflowPipelineOptions options) throws Exception { DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); Pipeline p = Pipeline.create(options); @@ -585,9 +416,9 @@ private static com.google.api.services.dataflow.model.Source translateIOToCloudS return stepToCloudSource(step); } - private static com.google.api.services.dataflow.model.Source stepToCloudSource(Step step) + private static Source stepToCloudSource(Step step) throws Exception { - com.google.api.services.dataflow.model.Source res = dictionaryToCloudSource( + Source res = dictionaryToCloudSource( getDictionary(step.getProperties(), PropertyNames.SOURCE_STEP_INPUT)); // Encoding is specified in the step, not in the source itself. This is // normal: incoming Dataflow API Source objects in map tasks will have the @@ -602,150 +433,12 @@ private static com.google.api.services.dataflow.model.Source stepToCloudSource(S return res; } - private static SourceSplitResponse performSplit( - com.google.api.services.dataflow.model.Source source, - PipelineOptions options, - @Nullable Long desiredBundleSizeBytes) - throws Exception { - SourceSplitRequest splitRequest = new SourceSplitRequest(); - splitRequest.setSource(source); - if (desiredBundleSizeBytes != null) { - splitRequest.setOptions( - new SourceSplitOptions().setDesiredBundleSizeBytes(desiredBundleSizeBytes)); - } - SourceOperationResponse response = CustomSources.performSplit(splitRequest, options); - return response.getSplit(); - } - - @Test - public void testUnboundedSplits() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - com.google.api.services.dataflow.model.Source source = - CustomSources.serializeToCloudSource(new TestCountingSource(Integer.MAX_VALUE), options); - List serializedSplits = - getStrings(source.getSpec(), CustomSources.SERIALIZED_SOURCE_SPLITS, null); - assertEquals(20, serializedSplits.size()); - for (String serializedSplit : serializedSplits) { - assertTrue( - deserializeFromByteArray(decodeBase64(serializedSplit), "source") - instanceof TestCountingSource); - } - } - - @Test - public void testReadUnboundedReader() throws Exception { - StreamingModeExecutionContext context = new StreamingModeExecutionContext("stageName", - new ConcurrentHashMap(), /*stateNameMap=*/null, - /*stateCache=*/null); - - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setNumWorkers(5); - - ByteString state = ByteString.EMPTY; - for (int i = 0; i < 10 * CustomSources.MAX_UNBOUNDED_BUNDLE_SIZE; - /* Incremented in inner loop */) { - // Initialize streaming context with state from previous iteration. - context.start( - Windmill.WorkItem.newBuilder() - .setKey(ByteString.copyFromUtf8("0000000000000001")) // key is zero-padded index. - .setWorkToken(0) // Required proto field, unused. - .setSourceState( - Windmill.SourceState.newBuilder().setState(state).build()) // Source state. - .build(), - new Instant(0), // input watermark - null, // output watermark - null, // synchronized processing time - null, // StateReader - null, // StateFetcher - Windmill.WorkItemCommitRequest.newBuilder()); - - @SuppressWarnings({"unchecked", "rawtypes"}) - NativeReader>>> reader = - (NativeReader) - CustomSources.create( - (CloudObject) - CustomSources.serializeToCloudSource( - new TestCountingSource(Integer.MAX_VALUE), options) - .getSpec(), - options, - context); - - // Verify data. - Instant beforeReading = Instant.now(); - int numReadOnThisIteration = 0; - for (WindowedValue>> value : - ReaderUtils.readAllFromReader(reader)) { - assertEquals(KV.of(0, i), value.getValue().getValue()); - assertArrayEquals( - encodeToByteArray(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()), KV.of(0, i)), - value.getValue().getId()); - assertThat(value.getWindows(), contains((BoundedWindow) GlobalWindow.INSTANCE)); - assertEquals(i, value.getTimestamp().getMillis()); - i++; - numReadOnThisIteration++; - } - Instant afterReading = Instant.now(); - assertThat( - new Duration(beforeReading, afterReading).getStandardSeconds(), - lessThanOrEqualTo(CustomSources.MAX_UNBOUNDED_BUNDLE_READ_TIME.getStandardSeconds() + 1)); - assertThat( - numReadOnThisIteration, lessThanOrEqualTo(CustomSources.MAX_UNBOUNDED_BUNDLE_SIZE)); - - // Extract and verify state modifications. - context.flushState(); - state = context.getOutputBuilder().getSourceStateUpdates().getState(); - // CountingSource's watermark is the last record + 1. i is now one past the last record, - // so the expected watermark is i millis. - assertEquals( - TimeUnit.MILLISECONDS.toMicros(i), context.getOutputBuilder().getSourceWatermark()); - assertEquals( - 1, - context - .getOutputBuilder() - .getSourceStateUpdates() - .getFinalizeIdsList() - .size()); - - assertNotNull(context.getCachedReader()); - - Windmill.Counter backlog = getCounter(context, "dataflow_backlog_size-stageName"); - assertEquals(7L, backlog.getIntScalar()); - assertTrue(backlog.getCumulative()); - assertEquals(Windmill.Counter.Kind.SUM, backlog.getKind()); - } - } - - private Windmill.Counter getCounter(StreamingModeExecutionContext context, String name) { - for (Windmill.Counter counter : context.getOutputBuilder().getCounterUpdatesList()) { - if (counter.getName().equals(name)) { - return counter; - } - } - return null; - } - - @Test - public void testLargeSerializedSizeResplits() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - // Figure out how many splits of CountingSource are needed to exceed the API limits, using an - // extra factor of 2 to ensure that we go over the limits. - BoundedSource justForSizing = CountingSource.upTo(1000000L); - long size = - DataflowApiUtils.computeSerializedSizeBytes( - translateIOToCloudSource(justForSizing, options)); - long numberToSplitToExceedLimit = - 2 * CustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES / size; - - // Generate a CountingSource and split it into the desired number of splits - // (desired size = 8 bytes, 1 long), triggering the re-split with a larger bundle size. - com.google.api.services.dataflow.model.Source source = - translateIOToCloudSource(CountingSource.upTo(numberToSplitToExceedLimit), options); - SourceSplitResponse split = performSplit(source, options, 8L); - logged.verifyWarn("too large for the Google Cloud Dataflow API"); - logged.verifyWarn(String.format("%d bundles", numberToSplitToExceedLimit)); - assertThat((long) split.getBundles().size(), lessThan(numberToSplitToExceedLimit)); + // Duplicated from runners.worker.SourceTranslationUtils to break dependency on worker + private static Source dictionaryToCloudSource(Map params) throws Exception { + Source res = new Source(); + res.setSpec(getDictionary(params, PropertyNames.SOURCE_SPEC)); + // SOURCE_METADATA and SOURCE_DOES_NOT_NEED_SPLITTING do not have to be + // translated, because they only make sense in cloud Source objects produced by the user. + return res; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java new file mode 100644 index 0000000000..26841294c8 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java @@ -0,0 +1,749 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import static com.google.api.client.util.Base64.decodeBase64; +import static com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources.serializeToCloudSource; +import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtFraction; +import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.dictionaryToCloudSource; +import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; +import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; +import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; +import static com.google.cloud.dataflow.sdk.util.SerializableUtils.deserializeFromByteArray; +import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; +import static com.google.cloud.dataflow.sdk.util.Structs.getObject; +import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; +import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; +import static com.google.common.base.Throwables.getStackTraceAsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; + +import com.google.api.services.dataflow.model.DataflowPackage; +import com.google.api.services.dataflow.model.DerivedSource; +import com.google.api.services.dataflow.model.Job; +import com.google.api.services.dataflow.model.SourceOperationResponse; +import com.google.api.services.dataflow.model.SourceSplitOptions; +import com.google.api.services.dataflow.model.SourceSplitRequest; +import com.google.api.services.dataflow.model.SourceSplitResponse; +import com.google.api.services.dataflow.model.Step; +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.CountingSource; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; +import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; +import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Sample; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.base.Preconditions; +import com.google.protobuf.ByteString; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +import javax.annotation.Nullable; + +/** + * Tests for {@link WorkerCustomSources}. + */ +@RunWith(JUnit4.class) +public class WorkerCustomSourcesTest { + @Rule public ExpectedException expectedException = ExpectedException.none(); + @Rule public ExpectedLogs logged = ExpectedLogs.none(WorkerCustomSources.class); + + static class TestIO { + public static Read fromRange(int from, int to) { + return new Read(from, to, false); + } + + static class Read extends BoundedSource { + final int from; + final int to; + final boolean produceTimestamps; + + Read(int from, int to, boolean produceTimestamps) { + this.from = from; + this.to = to; + this.produceTimestamps = produceTimestamps; + } + + public Read withTimestampsMillis() { + return new Read(from, to, true); + } + + @Override + public List splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) + throws Exception { + List res = new ArrayList<>(); + DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); + float step = 1.0f * (to - from) / dataflowOptions.getNumWorkers(); + for (int i = 0; i < dataflowOptions.getNumWorkers(); ++i) { + res.add(new Read( + Math.round(from + i * step), Math.round(from + (i + 1) * step), + produceTimestamps)); + } + return res; + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + return 8 * (to - from); + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return true; + } + + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + return new RangeReader(this); + } + + @Override + public void validate() {} + + @Override + public String toString() { + return "[" + from + ", " + to + ")"; + } + + @Override + public Coder getDefaultOutputCoder() { + return BigEndianIntegerCoder.of(); + } + + private static class RangeReader extends BoundedReader { + // To verify that BasicSerializableSourceFormat calls our methods according to protocol. + enum State { + UNSTARTED, + STARTED, + FINISHED + } + private Read source; + private int current = -1; + private State state = State.UNSTARTED; + + public RangeReader(Read source) { + this.source = source; + } + + @Override + public boolean start() throws IOException { + Preconditions.checkState(state == State.UNSTARTED); + state = State.STARTED; + current = source.from; + return (current < source.to); + } + + @Override + public boolean advance() throws IOException { + Preconditions.checkState(state == State.STARTED); + if (current == source.to - 1) { + state = State.FINISHED; + return false; + } + current++; + return true; + } + + @Override + public Integer getCurrent() { + Preconditions.checkState(state == State.STARTED); + return current; + } + + @Override + public Instant getCurrentTimestamp() { + return source.produceTimestamps + ? new Instant(current /* as millis */) : BoundedWindow.TIMESTAMP_MIN_VALUE; + } + + @Override + public void close() throws IOException { + Preconditions.checkState(state == State.STARTED || state == State.FINISHED); + state = State.FINISHED; + } + + @Override + public Read getCurrentSource() { + return source; + } + + @Override + public Read splitAtFraction(double fraction) { + int proposedIndex = (int) (source.from + fraction * (source.to - source.from)); + if (proposedIndex <= current) { + return null; + } + Read primary = new Read(source.from, proposedIndex, source.produceTimestamps); + Read residual = new Read(proposedIndex, source.to, source.produceTimestamps); + this.source = primary; + return residual; + } + + @Override + public Double getFractionConsumed() { + return (current == -1) + ? 0.0 + : (1.0 * (1 + current - source.from) / (source.to - source.from)); + } + } + } + } + + @Test + public void testSplitAndReadBundlesBack() throws Exception { + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + options.setNumWorkers(5); + com.google.api.services.dataflow.model.Source source = + translateIOToCloudSource(TestIO.fromRange(10, 20), options); + List> elems = CloudSourceUtils.readElemsFromSource(options, source); + assertEquals(10, elems.size()); + for (int i = 0; i < 10; ++i) { + assertEquals(valueInGlobalWindow(10 + i), elems.get(i)); + } + SourceSplitResponse response = performSplit(source, options, null /*desiredBundleSizeBytes*/); + assertEquals("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED", response.getOutcome()); + List bundles = response.getBundles(); + assertEquals(5, bundles.size()); + for (int i = 0; i < 5; ++i) { + DerivedSource bundle = bundles.get(i); + assertEquals("SOURCE_DERIVATION_MODE_INDEPENDENT", bundle.getDerivationMode()); + com.google.api.services.dataflow.model.Source bundleSource = bundle.getSource(); + assertTrue(bundleSource.getDoesNotNeedSplitting()); + bundleSource.setCodec(source.getCodec()); + List> xs = CloudSourceUtils.readElemsFromSource(options, bundleSource); + assertThat(xs, contains(valueInGlobalWindow(10 + 2 * i), valueInGlobalWindow(11 + 2 * i))); + } + } + + @Test + public void testDirectPipelineWithoutTimestamps() throws Exception { + Pipeline p = TestPipeline.create(); + PCollection sum = p + .apply(Read.from(TestIO.fromRange(10, 20))) + .apply(Sum.integersGlobally()) + .apply(Sample.any(1)); + + DataflowAssert.thatSingleton(sum).isEqualTo(145); + p.run(); + } + + @Test + public void testDirectPipelineWithTimestamps() throws Exception { + Pipeline p = TestPipeline.create(); + PCollection sums = + p.apply(Read.from(TestIO.fromRange(10, 20).withTimestampsMillis())) + .apply(Window.into(FixedWindows.of(Duration.millis(3)))) + .apply(Sum.integersGlobally().withoutDefaults()); + // Should group into [10 11] [12 13 14] [15 16 17] [18 19]. + DataflowAssert.that(sums).containsInAnyOrder(21, 37, 39, 48); + p.run(); + } + + @Test + public void testRangeProgressAndSplitAtFraction() throws Exception { + // Show basic usage of getFractionConsumed and splitAtFraction. + // This test only tests TestIO itself, not BasicSerializableSourceFormat. + + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + TestIO.Read source = TestIO.fromRange(10, 20); + try (BoundedSource.BoundedReader reader = source.createReader(options)) { + assertEquals(0, reader.getFractionConsumed().intValue()); + assertTrue(reader.start()); + assertEquals(0.1, reader.getFractionConsumed(), 1e-6); + assertTrue(reader.advance()); + assertEquals(0.2, reader.getFractionConsumed(), 1e-6); + // Already past 0.0 and 0.1. + assertNull(reader.splitAtFraction(0.0)); + assertNull(reader.splitAtFraction(0.1)); + + { + TestIO.Read residual = (TestIO.Read) reader.splitAtFraction(0.5); + assertNotNull(residual); + TestIO.Read primary = (TestIO.Read) reader.getCurrentSource(); + assertThat(readFromSource(primary, options), contains(10, 11, 12, 13, 14)); + assertThat(readFromSource(residual, options), contains(15, 16, 17, 18, 19)); + } + + // Range is now [10, 15) and we are at 12. + { + TestIO.Read residual = (TestIO.Read) reader.splitAtFraction(0.8); // give up 14. + assertNotNull(residual); + TestIO.Read primary = (TestIO.Read) reader.getCurrentSource(); + assertThat(readFromSource(primary, options), contains(10, 11, 12, 13)); + assertThat(readFromSource(residual, options), contains(14)); + } + + assertTrue(reader.advance()); + assertEquals(12, reader.getCurrent().intValue()); + assertTrue(reader.advance()); + assertEquals(13, reader.getCurrent().intValue()); + assertFalse(reader.advance()); + } + } + + @Test + @SuppressWarnings("unchecked") + public void testProgressAndSourceSplitTranslation() throws Exception { + // Same as previous test, but now using BasicSerializableSourceFormat wrappers. + // We know that the underlying reader behaves correctly (because of the previous test), + // now check that we are wrapping it correctly. + DataflowPipelineOptions options = PipelineOptionsFactory.create() + .as(DataflowPipelineOptions.class); + NativeReader> reader = + (NativeReader>) + ReaderFactory.Registry.defaultRegistry() + .create( + translateIOToCloudSource(TestIO.fromRange(10, 20), options), + options, + null, // executionContext + null, // addCounterMutator + null); // operationName + try (NativeReader.NativeReaderIterator> iterator = reader.iterator()) { + assertTrue(iterator.start()); + assertEquals( + 0.1, + readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), + 1e-6); + assertEquals(valueInGlobalWindow(10), iterator.getCurrent()); + assertEquals( + 0.1, + readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), + 1e-6); + assertTrue(iterator.advance()); + assertEquals(valueInGlobalWindow(11), iterator.getCurrent()); + assertEquals( + 0.2, + readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), + 1e-6); + assertTrue(iterator.advance()); + assertEquals(valueInGlobalWindow(12), iterator.getCurrent()); + + assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0))); + assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0.1f))); + WorkerCustomSources.BoundedSourceSplit sourceSplit = + (WorkerCustomSources.BoundedSourceSplit) + iterator.requestDynamicSplit(splitRequestAtFraction(0.5f)); + assertNotNull(sourceSplit); + assertThat(readFromSource(sourceSplit.primary, options), contains(10, 11, 12, 13, 14)); + assertThat(readFromSource(sourceSplit.residual, options), contains(15, 16, 17, 18, 19)); + + sourceSplit = + (WorkerCustomSources.BoundedSourceSplit) + iterator.requestDynamicSplit(splitRequestAtFraction(0.8f)); + assertNotNull(sourceSplit); + assertThat(readFromSource(sourceSplit.primary, options), contains(10, 11, 12, 13)); + assertThat(readFromSource(sourceSplit.residual, options), contains(14)); + + assertTrue(iterator.advance()); + assertEquals(valueInGlobalWindow(13), iterator.getCurrent()); + assertFalse(iterator.advance()); + } + } + + /** + * A source that cannot do anything. Intended to be overridden for testing of individual methods. + */ + private static class MockSource extends BoundedSource { + @Override + public List> splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + return Arrays.asList(this); + } + + @Override + public void validate() { } + + @Override + public boolean producesSortedKeys(PipelineOptions options) { + return false; + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) { + throw new UnsupportedOperationException(); + } + + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() { + return ""; + } + + @Override + public Coder getDefaultOutputCoder() { + return BigEndianIntegerCoder.of(); + } + } + + private static class SourceProducingInvalidSplits extends MockSource { + private String description; + private String errorMessage; + + private SourceProducingInvalidSplits(String description, String errorMessage) { + this.description = description; + this.errorMessage = errorMessage; + } + + @Override + public List> splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + Preconditions.checkState(errorMessage == null, "Unexpected invalid source"); + return Arrays.asList( + new SourceProducingInvalidSplits("goodBundle", null), + new SourceProducingInvalidSplits("badBundle", "intentionally invalid")); + } + + @Override + public void validate() { + Preconditions.checkState(errorMessage == null, errorMessage); + } + + @Override + public String toString() { + return description; + } + } + + @Test + public void testSplittingProducedInvalidSource() throws Exception { + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + com.google.api.services.dataflow.model.Source cloudSource = + translateIOToCloudSource(new SourceProducingInvalidSplits("original", null), options); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage( + allOf( + containsString("Splitting a valid source produced an invalid source"), + containsString("original"), + containsString("badBundle"))); + expectedException.expectCause(hasMessage(containsString("intentionally invalid"))); + performSplit(cloudSource, options, null /*desiredBundleSizeBytes*/); + } + + private static class FailingReader extends BoundedSource.BoundedReader { + private BoundedSource source; + + private FailingReader(BoundedSource source) { + this.source = source; + } + + @Override + public BoundedSource getCurrentSource() { + return source; + } + + @Override + public boolean start() throws IOException { + throw new IOException("Intentional error"); + } + + @Override + public boolean advance() throws IOException { + throw new IllegalStateException("Should have failed in start()"); + } + + @Override + public Integer getCurrent() throws NoSuchElementException { + throw new IllegalStateException("Should have failed in start()"); + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + throw new IllegalStateException("Should have failed in start()"); + } + + @Override + public void close() throws IOException {} + + @Override + public Double getFractionConsumed() { + return null; + } + + @Override + public BoundedSource splitAtFraction(double fraction) { + return null; + } + } + + private static class SourceProducingFailingReader extends MockSource { + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + return new FailingReader(this); + } + + @Override + public String toString() { + return "Some description"; + } + } + + @Test + public void testFailureToStartReadingIncludesSourceDetails() throws Exception { + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + com.google.api.services.dataflow.model.Source source = + translateIOToCloudSource(new SourceProducingFailingReader(), options); + // Unfortunately Hamcrest doesn't have a matcher that can match on the exception's + // printStackTrace(), however we just want to verify that the error and source description + // would be contained in the exception *somewhere*, not necessarily in the top-level + // Exception object. So instead we use Throwables.getStackTraceAsString and match on that. + try { + CloudSourceUtils.readElemsFromSource(options, source); + fail("Expected to fail"); + } catch (Exception e) { + assertThat( + getStackTraceAsString(e), + allOf(containsString("Intentional error"), containsString("Some description"))); + } + } + + private static com.google.api.services.dataflow.model.Source translateIOToCloudSource( + BoundedSource io, DataflowPipelineOptions options) throws Exception { + DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); + Pipeline p = Pipeline.create(options); + p.begin().apply(Read.from(io)); + + Job workflow = translator.translate(p, new ArrayList()).getJob(); + Step step = workflow.getSteps().get(0); + + return stepToCloudSource(step); + } + + private static com.google.api.services.dataflow.model.Source stepToCloudSource(Step step) + throws Exception { + com.google.api.services.dataflow.model.Source res = dictionaryToCloudSource( + getDictionary(step.getProperties(), PropertyNames.SOURCE_STEP_INPUT)); + // Encoding is specified in the step, not in the source itself. This is + // normal: incoming Dataflow API Source objects in map tasks will have the + // encoding filled in from the step's output encoding. + @SuppressWarnings("unchecked") + List> outputInfo = + (List>) step.getProperties().get(PropertyNames.OUTPUT_INFO); + + CloudObject encoding = CloudObject.fromSpec(getObject(outputInfo.get(0), + PropertyNames.ENCODING)); + res.setCodec(encoding); + return res; + } + + private static SourceSplitResponse performSplit( + com.google.api.services.dataflow.model.Source source, + PipelineOptions options, + @Nullable Long desiredBundleSizeBytes) + throws Exception { + SourceSplitRequest splitRequest = new SourceSplitRequest(); + splitRequest.setSource(source); + if (desiredBundleSizeBytes != null) { + splitRequest.setOptions( + new SourceSplitOptions().setDesiredBundleSizeBytes(desiredBundleSizeBytes)); + } + SourceOperationResponse response = WorkerCustomSources.performSplit(splitRequest, options); + return response.getSplit(); + } + + @Test + public void testUnboundedSplits() throws Exception { + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + com.google.api.services.dataflow.model.Source source = + serializeToCloudSource(new TestCountingSource(Integer.MAX_VALUE), options); + List serializedSplits = + getStrings(source.getSpec(), WorkerCustomSources.SERIALIZED_SOURCE_SPLITS, null); + assertEquals(20, serializedSplits.size()); + for (String serializedSplit : serializedSplits) { + assertTrue( + deserializeFromByteArray(decodeBase64(serializedSplit), "source") + instanceof TestCountingSource); + } + } + + @Test + public void testReadUnboundedReader() throws Exception { + StreamingModeExecutionContext context = new StreamingModeExecutionContext("stageName", + new ConcurrentHashMap(), /*stateNameMap=*/null, + /*stateCache=*/null); + + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + options.setNumWorkers(5); + + ByteString state = ByteString.EMPTY; + for (int i = 0; i < 10 * WorkerCustomSources.MAX_UNBOUNDED_BUNDLE_SIZE; + /* Incremented in inner loop */) { + // Initialize streaming context with state from previous iteration. + context.start( + Windmill.WorkItem.newBuilder() + .setKey(ByteString.copyFromUtf8("0000000000000001")) // key is zero-padded index. + .setWorkToken(0) // Required proto field, unused. + .setSourceState( + Windmill.SourceState.newBuilder().setState(state).build()) // Source state. + .build(), + new Instant(0), // input watermark + null, // output watermark + null, // synchronized processing time + null, // StateReader + null, // StateFetcher + Windmill.WorkItemCommitRequest.newBuilder()); + + @SuppressWarnings({"unchecked", "rawtypes"}) + NativeReader>>> reader = + (NativeReader) + WorkerCustomSources.create( + (CloudObject) + serializeToCloudSource( + new TestCountingSource(Integer.MAX_VALUE), options) + .getSpec(), + options, + context); + + // Verify data. + Instant beforeReading = Instant.now(); + int numReadOnThisIteration = 0; + for (WindowedValue>> value : + ReaderUtils.readAllFromReader(reader)) { + assertEquals(KV.of(0, i), value.getValue().getValue()); + assertArrayEquals( + encodeToByteArray(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()), KV.of(0, i)), + value.getValue().getId()); + assertThat(value.getWindows(), contains((BoundedWindow) GlobalWindow.INSTANCE)); + assertEquals(i, value.getTimestamp().getMillis()); + i++; + numReadOnThisIteration++; + } + Instant afterReading = Instant.now(); + assertThat( + new Duration(beforeReading, afterReading).getStandardSeconds(), + lessThanOrEqualTo(WorkerCustomSources.MAX_UNBOUNDED_BUNDLE_READ_TIME.getStandardSeconds() + + 1)); + assertThat( + numReadOnThisIteration, lessThanOrEqualTo(WorkerCustomSources.MAX_UNBOUNDED_BUNDLE_SIZE)); + + // Extract and verify state modifications. + context.flushState(); + state = context.getOutputBuilder().getSourceStateUpdates().getState(); + // CountingSource's watermark is the last record + 1. i is now one past the last record, + // so the expected watermark is i millis. + assertEquals( + TimeUnit.MILLISECONDS.toMicros(i), context.getOutputBuilder().getSourceWatermark()); + assertEquals( + 1, + context + .getOutputBuilder() + .getSourceStateUpdates() + .getFinalizeIdsList() + .size()); + + assertNotNull(context.getCachedReader()); + + Windmill.Counter backlog = getCounter(context, "dataflow_backlog_size-stageName"); + assertEquals(7L, backlog.getIntScalar()); + assertTrue(backlog.getCumulative()); + assertEquals(Windmill.Counter.Kind.SUM, backlog.getKind()); + } + } + + private Windmill.Counter getCounter(StreamingModeExecutionContext context, String name) { + for (Windmill.Counter counter : context.getOutputBuilder().getCounterUpdatesList()) { + if (counter.getName().equals(name)) { + return counter; + } + } + return null; + } + + @Test + public void testLargeSerializedSizeResplits() throws Exception { + DataflowPipelineOptions options = + PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); + // Figure out how many splits of CountingSource are needed to exceed the API limits, using an + // extra factor of 2 to ensure that we go over the limits. + BoundedSource justForSizing = CountingSource.upTo(1000000L); + long size = + DataflowApiUtils.computeSerializedSizeBytes( + translateIOToCloudSource(justForSizing, options)); + long numberToSplitToExceedLimit = + 2 * WorkerCustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES / size; + + // Generate a CountingSource and split it into the desired number of splits + // (desired size = 8 bytes, 1 long), triggering the re-split with a larger bundle size. + com.google.api.services.dataflow.model.Source source = + translateIOToCloudSource(CountingSource.upTo(numberToSplitToExceedLimit), options); + SourceSplitResponse split = performSplit(source, options, 8L); + logged.verifyWarn("too large for the Google Cloud Dataflow API"); + logged.verifyWarn(String.format("%d bundles", numberToSplitToExceedLimit)); + assertThat((long) split.getBundles().size(), lessThan(numberToSplitToExceedLimit)); + } +} From cb11e9da5b563a170233f58c44322241b59d99f5 Mon Sep 17 00:00:00 2001 From: kak Date: Thu, 4 Feb 2016 10:37:25 -0800 Subject: [PATCH 076/751] Most methods in com.google.common will soon have @CheckReturnValue applied to them. Adding the annotation makes it a compile time error to ignore the return value from the method. This CL fixes the soon-to-be compile error by either deleting the no op statement or otherwise handling the return value. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113865372 --- .../sdk/runners/worker/WindmillStateReaderTest.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java index 9a411f9354..bef0877f44 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.KeyedGetDataRequest; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.common.collect.Iterables; import com.google.protobuf.ByteString; import com.google.protobuf.ByteString.Output; @@ -121,7 +120,9 @@ public void testReadList() throws Exception { Iterable results = future.get(); Mockito.verify(mockWindmill).getStateData(expectedRequest.build()); - Iterables.size(results); + for (Integer unused : results) { + // Iterate over the results to force loading all the pages. + } Mockito.verifyNoMoreInteractions(mockWindmill); assertThat(results, Matchers.contains(5, 6)); @@ -190,7 +191,9 @@ public void testReadListWithContinuations() throws Exception { Iterable results = future.get(); Mockito.verify(mockWindmill).getStateData(expectedRequest1.build()); - Iterables.size(results); + for (Integer unused : results) { + // Iterate over the results to force loading all the pages. + } Mockito.verify(mockWindmill).getStateData(expectedRequest2.build()); Mockito.verifyNoMoreInteractions(mockWindmill); From 7d7a49a2154bd09b134979d60d26f26b3d97fa23 Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 4 Feb 2016 10:44:10 -0800 Subject: [PATCH 077/751] Move ReaderFactory.Registry to ReaderRegistry This breaks the circular dependency between ReaderFactory and all of its known implementations. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113866133 --- .../sdk/runners/worker/ConcatReader.java | 8 +- .../runners/worker/ConcatReaderFactory.java | 12 +- .../worker/MapTaskExecutorFactory.java | 18 +- .../sdk/runners/worker/ReaderFactory.java | 135 --------------- .../sdk/runners/worker/ReaderRegistry.java | 161 ++++++++++++++++++ .../sdk/runners/worker/SideInputUtils.java | 2 +- .../dataflow/sdk/util/CloudSourceUtils.java | 4 +- .../runners/worker/AvroReaderFactoryTest.java | 2 +- .../worker/BigQueryReaderFactoryTest.java | 4 +- .../worker/ConcatReaderFactoryTest.java | 4 +- .../sdk/runners/worker/ConcatReaderTest.java | 4 +- .../worker/InMemoryReaderFactoryTest.java | 2 +- .../worker/MapTaskExecutorFactoryTest.java | 4 +- .../sdk/runners/worker/ReaderFactoryTest.java | 6 +- .../worker/ShuffleReaderFactoryTest.java | 2 +- .../runners/worker/TextReaderFactoryTest.java | 2 +- .../worker/WorkerCustomSourcesTest.java | 2 +- 17 files changed, 199 insertions(+), 173 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java index 3ef0a9a9a2..f3057c5ce0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java @@ -72,13 +72,13 @@ public class ConcatReader extends NativeReader { private final ExecutionContext executionContext; private final CounterSet.AddCounterMutator addCounterMutator; private final String operationName; - private final ReaderFactory.Registry registry; + private final ReaderRegistry registry; /** * Create a {@link ConcatReader} using a given list of encoded {@link Source}s. */ public ConcatReader( - ReaderFactory.Registry registry, + ReaderRegistry registry, PipelineOptions options, ExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, @@ -118,10 +118,10 @@ static class ConcatIterator extends NativeReaderIterator { private final CounterSet.AddCounterMutator addCounterMutator; private final String operationName; private final OffsetRangeTracker rangeTracker; - private final ReaderFactory.Registry registry; + private final ReaderRegistry registry; public ConcatIterator( - ReaderFactory.Registry registry, + ReaderRegistry registry, PipelineOptions options, ExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java index 6fb8ef6473..05ae2b9b17 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java @@ -42,25 +42,25 @@ */ public class ConcatReaderFactory implements ReaderFactory { - private final ReaderFactory.Registry registry; + private final ReaderRegistry registry; - private ConcatReaderFactory(ReaderFactory.Registry registry) { + private ConcatReaderFactory(ReaderRegistry registry) { this.registry = registry; } /** * Returns a new {@link ConcatReaderFactory} that will use the default - * {@link ReaderFactory.Registry} to create sub-{@link NativeReader} instances. + * {@link ReaderRegistry} to create sub-{@link NativeReader} instances. */ public static ConcatReaderFactory withDefaultRegistry() { - return withRegistry(ReaderFactory.Registry.defaultRegistry()); + return withRegistry(ReaderRegistry.defaultRegistry()); } /** * Returns a new {@link ConcatReaderFactory} that will use the provided - * {@link ReaderFactory.Registry} to create sub-{@link NativeReader} instances. + * {@link ReaderRegistry} to create sub-{@link NativeReader} instances. */ - public static ConcatReaderFactory withRegistry(ReaderFactory.Registry registry) { + public static ConcatReaderFactory withRegistry(ReaderRegistry registry) { return new ConcatReaderFactory(registry); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java index b38d9c852d..420be59de7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java @@ -82,7 +82,7 @@ public class MapTaskExecutorFactory { /** * Creates a new MapTaskExecutor from the given MapTask definition using the default - * {@link ReaderFactory.Registry}. + * {@link ReaderRegistry}. */ public static MapTaskExecutor create( PipelineOptions options, @@ -93,7 +93,7 @@ public static MapTaskExecutor create( return create( options, mapTask, - ReaderFactory.Registry.defaultRegistry(), + ReaderRegistry.defaultRegistry(), context, counters, stateSampler); @@ -101,12 +101,12 @@ public static MapTaskExecutor create( /** * Creates a new MapTaskExecutor from the given MapTask definition using the provided - * {@link ReaderFactory.Registry}. + * {@link ReaderRegistry}. */ public static MapTaskExecutor create( PipelineOptions options, MapTask mapTask, - ReaderFactory.Registry registry, + ReaderRegistry registry, DataflowExecutionContext context, CounterSet counters, StateSampler stateSampler) @@ -135,7 +135,7 @@ public static MapTaskExecutor create( /** * Creates an Operation from the given ParallelInstruction definition using the provided - * {@link ReaderFactory.Registry}. + * {@link ReaderRegistry}. */ static Operation createOperation( PipelineOptions options, @@ -150,7 +150,7 @@ static Operation createOperation( return createOperation( options, instruction, - ReaderFactory.Registry.defaultRegistry(), + ReaderRegistry.defaultRegistry(), executionContext, priorOperations, counterPrefix, @@ -161,12 +161,12 @@ static Operation createOperation( /** * Creates an Operation from the given ParallelInstruction definition using the provided - * {@link ReaderFactory.Registry}. + * {@link ReaderRegistry}. */ static Operation createOperation( PipelineOptions options, ParallelInstruction instruction, - ReaderFactory.Registry registry, + ReaderRegistry registry, DataflowExecutionContext executionContext, List priorOperations, String counterPrefix, @@ -205,7 +205,7 @@ static Operation createOperation( static ReadOperation createReadOperation( PipelineOptions options, ParallelInstruction instruction, - ReaderFactory.Registry registry, + ReaderRegistry registry, DataflowExecutionContext executionContext, @SuppressWarnings("unused") List priorOperations, String counterPrefix, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java index e5a810d755..f65858a2b5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java @@ -16,18 +16,12 @@ package com.google.cloud.dataflow.sdk.runners.worker; -import com.google.api.services.dataflow.model.Source; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.Serializer; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.collect.Maps; - -import java.util.Map; import javax.annotation.Nullable; @@ -51,133 +45,4 @@ NativeReader create( @Nullable CounterSet.AddCounterMutator addCounterMutator, @Nullable String operationName) throws Exception; - - /** - * An immutable registry from {@link String} identifiers (provided to the worker by the Dataflow - * service) to appropriate {@link ReaderFactory} instances. - */ - public class Registry implements ReaderFactory { - - /** - * A {@link Registry} with each {@link ReaderFactory} known to the Dataflow worker already - * registered. - */ - public static Registry defaultRegistry() { - Map factories = Maps.newHashMap(); - - factories.put("TextSource", TextReaderFactory.getInstance()); - factories.put("AvroSource", new AvroReaderFactory()); - factories.put("BigQueryAvroSource", new BigQueryAvroReaderFactory()); - factories.put("UngroupedShuffleSource", new UngroupedShuffleReaderFactory()); - factories.put("PartitioningShuffleSource", new PartitioningShuffleReaderFactory()); - factories.put("GroupingShuffleSource", new GroupingShuffleReaderFactory()); - factories.put("InMemorySource", new InMemoryReaderFactory()); - factories.put("BigQuerySource", new BigQueryReaderFactory()); - - // Aliases for WindowingWindmillreader - factories.put("WindowingWindmillReader", new WindowingWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.WindowingWindmillReader", - new WindowingWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.BucketingWindmillSource", - new WindowingWindmillReader.Factory()); - - // Aliases for UngroupedWindmillReader - factories.put("UngroupedWindmillReader", new UngroupedWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.UngroupedWindmillSource", - new UngroupedWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.UngroupedWindmillReader", - new UngroupedWindmillReader.Factory()); - - // Aliases for PubsubReader - factories.put("PubsubReader", new PubsubReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.PubsubSource", - new PubsubReader.Factory()); - - // Custom sources - factories.put( - "com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources", - new WorkerCustomSources.Factory()); - factories.put( - "com.google.cloud.dataflow.sdk.runners.dataflow.WorkerCustomSources", - new WorkerCustomSources.Factory()); - - return new Registry(factories); - } - - /** - * Builds a new {@link Registry} with the provided mutable map of initial mappings. - * - *

Owns and mutates the provided map, which must be mutable. This constructor should only be - * called by methods in this class that are aware of this requirement and abstract from this - * behavior. - */ - private Registry(Map factories) { - // ConcatReader requires special treatment: Recursive access to the registry since it calls - // back to create its sub-readers lazily. - this.factories = factories; - this.factories.put(ConcatReader.SOURCE_NAME, ConcatReaderFactory.withRegistry(this)); - } - - /** - * A map from the short names of predefined sources to the associated {@link ReaderFactory}. - */ - private final Map factories; - - /** - * Returns a new {@link Registry} with the provided identifier associated with the provided - * {@link ReaderFactory}, overriding any existing binding for that identifier. - */ - public Registry register(String readerSpecType, ReaderFactory factory) { - Map newFactories = Maps.newHashMap(); - newFactories.putAll(factories); - newFactories.put(readerSpecType, factory); - return new Registry(newFactories); - } - - /** - * Creates a {@link NativeReader} according to the provided {@code sourceSpec}, - * by dispatching on the type of {@link CloudObject} to instantiate. - */ - @Override - public NativeReader create( - CloudObject sourceSpec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - - String objClassName = sourceSpec.getClassName(); - ReaderFactory readerFactory = factories.get(objClassName); - if (readerFactory == null) { - throw new IllegalArgumentException(String.format( - "Unable to create a Reader: Unknown Reader type in Source specification: %s", - objClassName)); - } - return readerFactory.create( - sourceSpec, coder, options, executionContext, addCounterMutator, operationName); - } - - /** - * Creates a {@link NativeReader} from a Dataflow API {@link Source} specification, using the - * {@link Coder} contained in the {@link Source} specification. - */ - public NativeReader create( - Source cloudSource, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - - cloudSource = CloudSourceUtils.flattenBaseSpecs(cloudSource); - CloudObject sourceSpec = CloudObject.fromSpec(cloudSource.getSpec()); - Coder coder = null; - if (cloudSource.getCodec() != null) { - coder = Serializer.deserialize(cloudSource.getCodec(), Coder.class); - } - return create(sourceSpec, coder, options, executionContext, addCounterMutator, operationName); - } - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java new file mode 100644 index 0000000000..a74db55fb5 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.api.services.dataflow.model.Source; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.Serializer; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; +import com.google.common.collect.Maps; + +import java.util.Map; + +import javax.annotation.Nullable; + +/** + * An immutable registry from {@link String} identifiers (provided to the worker by the Dataflow + * service) to appropriate {@link ReaderFactory} instances. + */ +public class ReaderRegistry implements ReaderFactory { + + /** + * A {@link ReaderRegistry} with each {@link ReaderFactory} known to the Dataflow worker already + * registered. + */ + public static ReaderRegistry defaultRegistry() { + Map factories = Maps.newHashMap(); + + factories.put("TextSource", TextReaderFactory.getInstance()); + factories.put("AvroSource", new AvroReaderFactory()); + factories.put("BigQueryAvroSource", new BigQueryAvroReaderFactory()); + factories.put("UngroupedShuffleSource", new UngroupedShuffleReaderFactory()); + factories.put("PartitioningShuffleSource", new PartitioningShuffleReaderFactory()); + factories.put("GroupingShuffleSource", new GroupingShuffleReaderFactory()); + factories.put("InMemorySource", new InMemoryReaderFactory()); + factories.put("BigQuerySource", new BigQueryReaderFactory()); + + // Aliases for WindowingWindmillreader + factories.put("WindowingWindmillReader", new WindowingWindmillReader.Factory()); + factories.put("com.google.cloud.dataflow.sdk.runners.worker.WindowingWindmillReader", + new WindowingWindmillReader.Factory()); + factories.put("com.google.cloud.dataflow.sdk.runners.worker.BucketingWindmillSource", + new WindowingWindmillReader.Factory()); + + // Aliases for UngroupedWindmillReader + factories.put("UngroupedWindmillReader", new UngroupedWindmillReader.Factory()); + factories.put("com.google.cloud.dataflow.sdk.runners.worker.UngroupedWindmillSource", + new UngroupedWindmillReader.Factory()); + factories.put("com.google.cloud.dataflow.sdk.runners.worker.UngroupedWindmillReader", + new UngroupedWindmillReader.Factory()); + + // Aliases for PubsubReader + factories.put("PubsubReader", new PubsubReader.Factory()); + factories.put("com.google.cloud.dataflow.sdk.runners.worker.PubsubSource", + new PubsubReader.Factory()); + + // Custom sources + factories.put( + "com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources", + new WorkerCustomSources.Factory()); + factories.put( + "com.google.cloud.dataflow.sdk.runners.dataflow.WorkerCustomSources", + new WorkerCustomSources.Factory()); + + return new ReaderRegistry(factories); + } + + /** + * Builds a new {@link ReaderRegistry} with the provided mutable map of initial mappings. + * + *

Owns and mutates the provided map, which must be mutable. This constructor should only be + * called by methods in this class that are aware of this requirement and abstract from this + * behavior. + */ + private ReaderRegistry(Map factories) { + // ConcatReader requires special treatment: Recursive access to the registry since it calls + // back to create its sub-readers lazily. + this.factories = factories; + this.factories.put(ConcatReader.SOURCE_NAME, ConcatReaderFactory.withRegistry(this)); + } + + /** + * A map from the short names of predefined sources to the associated {@link ReaderFactory}. + */ + private final Map factories; + + /** + * Returns a new {@link ReaderRegistry} with the provided identifier associated with the + * provided {@link ReaderFactory}, overriding any existing binding for that identifier. + */ + public ReaderRegistry register(String readerSpecType, ReaderFactory factory) { + Map newFactories = Maps.newHashMap(); + newFactories.putAll(factories); + newFactories.put(readerSpecType, factory); + return new ReaderRegistry(newFactories); + } + + /** + * Creates a {@link NativeReader} according to the provided {@code sourceSpec}, + * by dispatching on the type of {@link CloudObject} to instantiate. + */ + @Override + public NativeReader create( + CloudObject sourceSpec, + @Nullable Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator, + @Nullable String operationName) + throws Exception { + + String objClassName = sourceSpec.getClassName(); + ReaderFactory readerFactory = factories.get(objClassName); + if (readerFactory == null) { + throw new IllegalArgumentException(String.format( + "Unable to create a Reader: Unknown Reader type in Source specification: %s", + objClassName)); + } + return readerFactory.create( + sourceSpec, coder, options, executionContext, addCounterMutator, operationName); + } + + /** + * Creates a {@link NativeReader} from a Dataflow API {@link Source} specification, using the + * {@link Coder} contained in the {@link Source} specification. + */ + public NativeReader create( + Source cloudSource, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator, + @Nullable String operationName) + throws Exception { + + cloudSource = CloudSourceUtils.flattenBaseSpecs(cloudSource); + CloudObject sourceSpec = CloudObject.fromSpec(cloudSource.getSpec()); + Coder coder = null; + if (cloudSource.getCodec() != null) { + coder = Serializer.deserialize(cloudSource.getCodec(), Coder.class); + } + return create(sourceSpec, coder, options, executionContext, addCounterMutator, operationName); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java index ce01a9bfdb..4603eccc82 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java @@ -101,7 +101,7 @@ private static Iterable readSideInputSource( @SuppressWarnings("unchecked") NativeReader reader = (NativeReader) - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create(sideInputSource, options, executionContext, null, null); if (observer != null) { reader.addObserver(observer); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java index 4d48010647..616fbe1b39 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java @@ -18,7 +18,7 @@ import com.google.api.services.dataflow.model.Source; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderRegistry; import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; @@ -63,7 +63,7 @@ public static List readElemsFromSource(PipelineOptions options, Source so @SuppressWarnings("unchecked") NativeReader reader = (NativeReader) - ReaderFactory.Registry.defaultRegistry().create(source, options, null, null, null); + ReaderRegistry.defaultRegistry().create(source, options, null, null, null); return ReaderUtils.readAllFromReader(reader); } catch (Exception e) { throw new RuntimeException("Failed to read from source: " + source.toString(), e); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java index 86d4085561..2a7b7e18bb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java @@ -63,7 +63,7 @@ NativeReader runTestCreateAvroReader( cloudSource.setCodec(encoding); NativeReader reader = - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create( cloudSource, PipelineOptionsFactory.create(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java index 7d52658644..d2d69085a3 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java @@ -55,7 +55,7 @@ void runTestCreateBigQueryReaderFromTable( options.setGcpCredential(new TestCredential()); NativeReader reader = - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create(cloudSource, options, DirectModeExecutionContext.create(), null, null); assertThat(reader, new IsInstanceOf(BigQueryReader.class)); BigQueryReader bigQueryReader = (BigQueryReader) reader; @@ -77,7 +77,7 @@ void runTestCreateBigQueryReaderFromQuery(String query, CloudObject encoding) th options.setGcpCredential(new TestCredential()); NativeReader reader = - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create(cloudSource, options, DirectModeExecutionContext.create(), null, null); assertThat(reader, new IsInstanceOf(BigQueryReader.class)); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java index 59cfcfe0d8..dce6e9f15f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java @@ -92,7 +92,7 @@ public void testCreateConcatReaderWithOneSubSource() throws Exception { @SuppressWarnings("unchecked") NativeReader reader = (NativeReader) - ReaderFactory.Registry.defaultRegistry().create(source, null, null, null, null); + ReaderRegistry.defaultRegistry().create(source, null, null, null, null); assertNotNull(reader); List expected = new ArrayList<>(); @@ -111,7 +111,7 @@ public void testCreateConcatReaderWithManySubSources() throws Exception { @SuppressWarnings("unchecked") NativeReader reader = (NativeReader) - ReaderFactory.Registry.defaultRegistry().create(source, null, null, null, null); + ReaderRegistry.defaultRegistry().create(source, null, null, null, null); assertNotNull(reader); List expected = new ArrayList<>(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java index 5eebb84823..c38611ba4b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java @@ -66,12 +66,12 @@ public class ConcatReaderTest { private List> recordedReaders = new ArrayList<>(); - private ReaderFactory.Registry registry; + private ReaderRegistry registry; @Before public void setUp() { recordedReaders.clear(); - registry = ReaderFactory.Registry.defaultRegistry() + registry = ReaderRegistry.defaultRegistry() .register(TestReader.class.getName(), new TestReaderFactory()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java index eb7d54cd7f..67647a53dc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java @@ -70,7 +70,7 @@ void runTestCreateInMemoryReader(List elements, Long start, Long end, int Source cloudSource = createInMemoryCloudSource(elements, start, end, coder); NativeReader reader = - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create( cloudSource, PipelineOptionsFactory.create(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java index 4dad6be28b..777b3545c2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java @@ -99,12 +99,12 @@ public class MapTaskExecutorFactoryTest { WindowedValue.getValueOnlyCoder(StringUtf8Coder.of()).asCloudObject(); private PipelineOptions options; - private ReaderFactory.Registry readerFactoryRegistry; + private ReaderRegistry readerFactoryRegistry; @Before public void setUp() { options = PipelineOptionsFactory.create(); - readerFactoryRegistry = ReaderFactory.Registry.defaultRegistry() + readerFactoryRegistry = ReaderRegistry.defaultRegistry() .register( TestReaderFactory.class.getName(), new TestReaderFactory()) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java index b2e0a19fca..f5cc6159b4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java @@ -135,7 +135,7 @@ public void testCreatePredefinedReader() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); NativeReader reader = - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create( cloudSource, options, BatchModeExecutionContext.fromOptions(options), null, null); Assert.assertThat(reader, new IsInstanceOf(TextReader.class)); @@ -150,7 +150,7 @@ public void testCreateUserDefinedReader() throws Exception { cloudSource.setCodec(makeCloudEncoding("BigEndianIntegerCoder")); PipelineOptions options = PipelineOptionsFactory.create(); - ReaderFactory.Registry registry = ReaderFactory.Registry.defaultRegistry() + ReaderRegistry registry = ReaderRegistry.defaultRegistry() .register(TestReaderFactory.class.getName(), new TestReaderFactory()); NativeReader reader = registry.create( @@ -170,7 +170,7 @@ public void testCreateUnknownReader() throws Exception { cloudSource.setCodec(makeCloudEncoding("StringUtf8Coder")); try { PipelineOptions options = PipelineOptionsFactory.create(); - ReaderFactory.Registry.defaultRegistry().create( + ReaderRegistry.defaultRegistry().create( cloudSource, options, BatchModeExecutionContext.fromOptions(options), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java index 394abcca99..3868931e6e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java @@ -71,7 +71,7 @@ T runTestCreateShuffleReader( cloudSource.setCodec(encoding); NativeReader reader = - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create(cloudSource, PipelineOptionsFactory.create(), context, null, null); Assert.assertThat(reader, new IsInstanceOf(shuffleReaderClass)); T shuffleSource = (T) reader; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java index 0d4ea0599d..f05d20344a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java @@ -68,7 +68,7 @@ void runTestCreateTextReader(String filename, @Nullable Boolean stripTrailingNew PipelineOptions options = PipelineOptionsFactory.create(); NativeReader reader = - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create( cloudSource, options, BatchModeExecutionContext.fromOptions(options), null, null); Assert.assertThat(reader, new IsInstanceOf(TextReader.class)); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java index 26841294c8..92d8a86b80 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java @@ -358,7 +358,7 @@ public void testProgressAndSourceSplitTranslation() throws Exception { .as(DataflowPipelineOptions.class); NativeReader> reader = (NativeReader>) - ReaderFactory.Registry.defaultRegistry() + ReaderRegistry.defaultRegistry() .create( translateIOToCloudSource(TestIO.fromRange(10, 20), options), options, From 1ddc6fd382e438b747a8a90186d971bbf1be4e51 Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 4 Feb 2016 11:25:39 -0800 Subject: [PATCH 078/751] Add Ism file format version 2 Version 2 allows for Ism files to have keys with metadata associated with them. Also, the IsmReader exposes methods to allow for iteration over a subset of keys and to find the last key with a given prefix. Finally expose the IsmSink via the sink factory. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113870973 --- .../sdk/runners/worker/IsmFormat.java | 22 +- .../sdk/runners/worker/IsmReader.java | 1035 +++++++++++++---- .../dataflow/sdk/runners/worker/IsmSink.java | 198 +++- .../sdk/runners/worker/IsmSinkFactory.java | 69 ++ .../sdk/runners/worker/SinkFactory.java | 3 + .../sdk/runners/worker/IsmFormatTest.java | 28 + .../sdk/runners/worker/IsmReaderTest.java | 585 +++++++--- .../sdk/runners/worker/IsmSinkTest.java | 111 +- .../sdk/testing/CoderPropertiesTest.java | 2 +- 9 files changed, 1625 insertions(+), 428 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java index 118f31692e..182d3f2464 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java @@ -23,6 +23,7 @@ import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.ListCoder; import com.google.cloud.dataflow.sdk.coders.StandardCoder; @@ -54,6 +55,8 @@ import java.util.Arrays; import java.util.List; +import javax.annotation.Nullable; + /** * An Ism file is a prefix encoded composite key value file broken into shards. Each composite * key is composed of a fixed number of component keys. A fixed number of those sub keys represent @@ -97,7 +100,7 @@ *
  • byte offset to key prefix in data block (variable length long coding)
  • * * - *

    The shard index is composed of a variable length integer encoding representing + *

    The shard index is composed of a {@link VarInt variable length integer} encoding representing * the number of shard index records followed by that many shard index records. * See {@link IsmShardCoder} for further details as to its encoding scheme. */ @@ -135,7 +138,9 @@ public static IsmRecord meta(List keyComponents, byte[] metadata) { } private final List keyComponents; + @Nullable private final V value; + @Nullable private final byte[] metadata; private IsmRecord(List keyComponents, V value, byte[] metadata) { this.keyComponents = keyComponents; @@ -459,6 +464,21 @@ public Object structuralValue(IsmRecord record) throws Exception { } } + /** + * Validates that the key portion of the given coder is deterministic. + */ + static void validateCoderIsCompatible(IsmRecordCoder coder) { + for (Coder keyComponentCoder : coder.getKeyComponentCoders()) { + try { + keyComponentCoder.verifyDeterministic(); + } catch (NonDeterministicException e) { + throw new IllegalArgumentException( + String.format("Key component coder %s is expected to be deterministic.", + keyComponentCoder), e); + } + } + } + /** Returns true if and only if any of the passed in key components represent a metadata key. */ public static boolean isMetadataKey(List keyComponents) { for (Object keyComponent : keyComponents) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java index 88c4f54f7a..3b85f1e1c9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java @@ -15,122 +15,200 @@ */ package com.google.cloud.dataflow.sdk.runners.worker; +import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.Footer; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.FooterCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShard; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefix; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefixCoder; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.RandomAccessData; -import com.google.cloud.dataflow.sdk.util.RandomAccessData.RandomAccessDataCoder; import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter; import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter.ScalableBloomFilterCoder; +import com.google.cloud.dataflow.sdk.util.VarInt; +import com.google.cloud.dataflow.sdk.util.WeightedValue; +import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.MoreObjects; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.base.Throwables; +import com.google.common.cache.Cache; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedMap; +import com.google.common.collect.Ordering; +import com.google.common.io.ByteStreams; +import com.google.common.primitives.Longs; import java.io.IOException; import java.io.InputStream; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SeekableByteChannel; -import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.NavigableMap; import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.SortedMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; /** - * A {@link NativeReader} that reads Ism files. The coder provided is used to encode each key value - * record. See {@link IsmFormat} for encoded format details. + * A {@link NativeReader} that reads Ism files. * - * @param the type of the keys written to the sink - * @param the type of the values written to the sink + * @param the type of the value written to the sink */ -public class IsmReader extends NativeReader> { +public class IsmReader extends NativeReader>> { + /** + * This constant represents the distance we would rather read and drop bytes for + * versus doing an actual repositioning of the underlying stream. Tuned for operation + * within GCS. + */ + private static final int SEEK_VS_READ = 6 * 1024 * 1024; + private static final int MAX_SHARD_INDEX_AND_FOOTER_SIZE = 1024 * 1024; + private final String filename; - private final Coder keyCoder; - private final Coder valueCoder; + private final IsmRecordCoder coder; /** Lazily initialized on first read. */ private long length; private Footer footer; - /** Lazily initialized on first keyed read. */ - private ImmutableSortedMap index; + /** A map indexed by shard id, storing the Ism shard descriptors. */ + private NavigableMap shardIdToShardMap; + + /** + * A map sorted and indexed by the block offset for a given shard. The sorting is important so + * the {@link LazyIsmPrefixReaderIterator} can read through the file in increasing order. + */ + private NavigableMap shardOffsetToShardMap; + + /** Values lazily initialized per shard on first keyed read of each shard. */ + private Map> indexPerShard; ScalableBloomFilter bloomFilter; - IsmReader(final String filename, Coder keyCoder, Coder valueCoder) { + /** + * A cache instance which if set on this reader is used to cache blocks of data that are read. + * Each value represents the decoded form of a block. + */ + private final Cache>>>> cache; + + /** + * Produces a reader for the specified {@code filename} and {@code coder}. + * See {@link IsmFormat} for encoded format details. + */ + IsmReader( + final String filename, + IsmRecordCoder coder, + Cache>>>> cache) { + checkNotNull(cache); + IsmFormat.validateCoderIsCompatible(coder); this.filename = filename; - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; + this.coder = coder; + this.cache = cache; } @Override - public LazyIsmReaderIterator iterator() throws IOException { - return new LazyIsmReaderIterator(); + public IsmPrefixReaderIterator iterator() throws IOException { + return new LazyIsmPrefixReaderIterator(); } /** - * Returns a {@code KV} pair for the given {@code K} or null if {@code K} is not - * present within this Ism file. + * Returns a reader over a set of key components. The key components are encoded to their + * byte representations and used as a key prefix. + * + *

    If the file is empty or their is no key with the same prefix, then we return + * an empty reader iterator. + * + *

    If less than the required number of shard key components is passed in, then a reader + * iterator over all the keys is returned. + * + *

    Otherwise we return a reader iterator which only iterates over keys which have the + * same key prefix. */ - public KV get(K k) throws IOException { - try (SeekableByteChannel inChannel = initializeForKeyedRead()) { - RandomAccessData keyBytes = new RandomAccessData(); + public IsmPrefixReaderIterator overKeyComponents(List keyComponents) throws IOException { + checkNotNull(keyComponents); + checkArgument(keyComponents.size() <= coder.getKeyComponentCoders().size(), + "Expected at most %s key component(s) but received %s.", + coder.getKeyComponentCoders().size(), keyComponents); + + Optional inChannel = + initializeFooterAndShardIndex(Optional.absent()); + + // If this file is empty, we can return an empty iterator. + if (footer.getNumberOfKeys() == 0) { + return new EmptyIsmPrefixReaderIterator(keyComponents); + } - // Encode the requested key - keyCoder.encode(k, keyBytes.asOutputStream(), Context.OUTER); + // If not enough key components to figure out which shard was requested, we return a reader + // iterator over all the keys. + if (keyComponents.size() < coder.getNumberOfShardKeyCoders(keyComponents)) { + return new ShardAwareIsmPrefixReaderIterator(keyComponents, openIfNeeded(inChannel)); + } - // If the Bloom filter says we don't have the key, we have nothing further to do. - if (!bloomFilterMightContain(keyBytes)) { - return null; - } + RandomAccessData keyBytes = new RandomAccessData(); + int shardId = coder.encodeAndHash(keyComponents, keyBytes); - // Find the index record which is less than or equal to the passed in key. - Entry entry = index.floorEntry(keyBytes); + // If this file does not contain the shard or Bloom filter does not contain the key prefix, + // we know that we can return an empty reader iterator. + if (!shardIdToShardMap.containsKey(shardId)) { + return new EmptyIsmPrefixReaderIterator(keyComponents); + } + inChannel = initializeForKeyedRead(shardId, inChannel); + closeIfPresent(inChannel); + if (!bloomFilterMightContain(keyBytes)) { + return new EmptyIsmPrefixReaderIterator(keyComponents); + } - // If no indexed entry is less than or equal to the passed in key then we start - // at the beginning of the file. - if (entry == null) { - entry = new AbstractMap.SimpleEntry<>(new RandomAccessData(), 0L); - } + // Otherwise we may actually contain the key so construct a reader iterator + // which will fetch the data blocks containing the requested key prefix. - // Reposition the stream to the data block that should contain the key. - inChannel.position(entry.getValue()); - - // Seek through the data block till we find a key that matches or a greater key. - try (IsmReaderIterator iterator = - new IsmReaderIterator<>( - inChannel, - entry.getKey(), - RandomAccessDataCoder.of(), - valueCoder, - footer.getBloomFilterPosition())) { - long startPosition = inChannel.position(); - for (boolean more = iterator.start(); more; more = iterator.advance()) { - KV next = iterator.getCurrent(); - int comparison = RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - next.getKey(), keyBytes); - // If the current key is greater then the requested key, this Ism file does not contain - // the record. - if (comparison > 0) { - return null; - } else if (comparison == 0) { - notifyElementRead(inChannel.position() - startPosition); - return KV.of(k, next.getValue()); - } - startPosition = inChannel.position(); - } - } - // We hit the end of the file, therefore this Ism file does not contain the key. - return null; - } + // We find the first key in the index which may contain our prefix + RandomAccessData floorKey = indexPerShard.get(shardId).floorKey(keyBytes); + + // We compute an upper bound on the key prefix by incrementing the prefix + RandomAccessData keyBytesUpperBound = keyBytes.increment(); + // Compute the sub-range of the index map that we want to iterate over since + // any of these blocks may contain the key prefix. + Iterator blockEntries = + indexPerShard.get(shardId).subMap(floorKey, keyBytesUpperBound).values().iterator(); + + return new WithinShardIsmPrefixReaderIterator( + keyComponents, + keyBytes, + keyBytesUpperBound, + blockEntries); + } + + /** Returns the coder associated with this IsmReader. */ + public IsmRecordCoder getCoder() { + return coder; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(IsmReader.class) + .add("filename", filename) + .add("coder", coder) + .toString(); } // Overridable by tests to get around the bloom filter not containing any values. @@ -140,198 +218,745 @@ boolean bloomFilterMightContain(RandomAccessData keyBytes) { } /** - * Initialize this Ism reader by reading the footer. + * Initialize this Ism reader by reading the footer and shard index. Returns a channel for re-use + * if this method was required to open one. */ - private synchronized void initializeFooter(SeekableByteChannel in) throws IOException { + private synchronized Optional + initializeFooterAndShardIndex(Optional inChannel) throws IOException { if (footer != null) { - return; + checkState(shardIdToShardMap != null, + "Expected shard id to shard map to have been initialized."); + checkState(shardOffsetToShardMap != null, + "Expected shard offset to shard map to have been initialized."); + return inChannel; + } + checkState(shardIdToShardMap == null, + "Expected shard id to shard map to not have been initialized."); + checkState(shardOffsetToShardMap == null, + "Expected shard offset to shard map to not have been initialized."); + + SeekableByteChannel rawChannel = openIfNeeded(inChannel); + this.length = rawChannel.size(); + + // We read the last chunk of data, for small files we will capture the entire file. + // We may capture the Bloom filter, shard index, and footer for slightly larger files. + // Otherwise we are guaranteed to capture the footer and the shard index. + long startPosition = Math.max(length - MAX_SHARD_INDEX_AND_FOOTER_SIZE, 0); + position(rawChannel, startPosition); + RandomAccessData data = + new RandomAccessData(ByteStreams.toByteArray(Channels.newInputStream(rawChannel))); + + // Read the fixed length footer. + this.footer = FooterCoder.of().decode( + data.asInputStream(data.size() - Footer.FIXED_LENGTH, Footer.FIXED_LENGTH), Context.OUTER); + + checkState(startPosition < footer.getIndexPosition(), + "Malformed file, expected to have been able to read entire shard index."); + int offsetWithinReadData = (int) (footer.getIndexPosition() - startPosition); + + // Decode the list of Ism shard descriptors + List ismShards = IsmFormat.ISM_SHARD_INDEX_CODER.decode( + data.asInputStream(offsetWithinReadData, data.size() - offsetWithinReadData), + Context.NESTED); + + // Build the shard id to shard descriptor map + ImmutableSortedMap.Builder shardIdToShardMapBuilder = + ImmutableSortedMap.orderedBy(Ordering.natural()); + for (IsmShard ismShard : ismShards) { + shardIdToShardMapBuilder.put(ismShard.getId(), ismShard); + } + shardIdToShardMap = shardIdToShardMapBuilder.build(); + + // Build the shard block offset to shard descriptor map + ImmutableSortedMap.Builder shardOffsetToShardMapBuilder = + ImmutableSortedMap.orderedBy(Ordering.natural()); + for (IsmShard ismShard : ismShards) { + shardOffsetToShardMapBuilder.put(ismShard.getBlockOffset(), ismShard); + } + shardOffsetToShardMap = shardOffsetToShardMapBuilder.build(); + + // We may have gotten the Bloom filter, if so lets store it. + if (startPosition < footer.getBloomFilterPosition()) { + offsetWithinReadData = (int) (footer.getBloomFilterPosition() - startPosition); + bloomFilter = ScalableBloomFilterCoder.of().decode( + data.asInputStream(offsetWithinReadData, data.size() - offsetWithinReadData), + Context.NESTED); } - this.length = in.size(); - in.position(length - Footer.FIXED_LENGTH); - this.footer = FooterCoder.of().decode(Channels.newInputStream(in), Context.OUTER); - in.position(0L); + + // TODO: We may have gotten the entire file so we should populate our cache to + // prevent a re-read of the same data. + + return Optional.of(rawChannel); } /** - * A {@link NativeReaderIterator - * Reader.ReaderIterator} which initializes its input stream lazily. + * Initializes the Bloom filter and index per shard. We prepopulate empty indices + * for shards where the index offset matches the following shard block offset. + * Re-uses the provided channel, returning it or a new one if this method + * was required to open one. */ - private class LazyIsmReaderIterator extends NativeReaderIterator> { - private IsmReaderIterator delegate; - private SeekableByteChannel inChannel; + private synchronized Optional initializeBloomFilterAndIndexPerShard( + Optional inChannel) throws IOException { + if (indexPerShard != null) { + checkState(bloomFilter != null, "Expected Bloom filter to have been initialized."); + return inChannel; + } - @Override - public boolean start() throws IOException { - inChannel = openConnection(filename); - initializeFooter(inChannel); - delegate = - new IsmReaderIterator<>( - inChannel, - new RandomAccessData(), - keyCoder, - valueCoder, - footer.getBloomFilterPosition()); - - long startPosition = inChannel.position(); - boolean rval = delegate.start(); - notifyElementRead(inChannel.position() - startPosition); - return rval; + SeekableByteChannel rawChannel = openIfNeeded(inChannel); + + // initializeFooterAndShardIndex may have initialized the Bloom filter + // if the file is small enough. + if (bloomFilter == null) { + // Set the position to where the bloom filter is and read it in. + position(rawChannel, footer.getBloomFilterPosition()); + bloomFilter = ScalableBloomFilterCoder.of().decode( + Channels.newInputStream(rawChannel), Context.NESTED); + } + + indexPerShard = new HashMap<>(); + // If a shard is small, it may not contain an index and we can detect this and + // prepopulate the shard index map with an empty entry if the start of the index + // and start of the next block are equal + Iterator shardIterator = shardOffsetToShardMap.values().iterator(); + + // If file is empty we just return here. + if (!shardIterator.hasNext()) { + return Optional.of(rawChannel); + } + + // If the current shard's index position is equal to the next shards block offset + // then we know that the index contains no data and we can pre-populate it with + // the empty map. + IsmShard currentShard = shardIterator.next(); + while (shardIterator.hasNext()) { + IsmShard nextShard = shardIterator.next(); + if (currentShard.getIndexOffset() == nextShard.getBlockOffset()) { + indexPerShard.put(currentShard.getId(), + ImmutableSortedMap.orderedBy( + RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR) + .put( + new RandomAccessData(0), + new IsmShardKey( + IsmReader.this.filename, + new RandomAccessData(0), + currentShard.getBlockOffset(), + currentShard.getIndexOffset())).build()); + } + currentShard = nextShard; + } + + // Add an entry for the last shard if its index offset is equivalent to the + // start of the Bloom filter, then we know that the index is empty. + if (currentShard.getIndexOffset() == footer.getBloomFilterPosition()) { + indexPerShard.put(currentShard.getId(), + ImmutableSortedMap.orderedBy( + RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR) + .put( + new RandomAccessData(0), + new IsmShardKey( + IsmReader.this.filename, + new RandomAccessData(0), + currentShard.getBlockOffset(), + currentShard.getIndexOffset())).build()); + } + + return Optional.of(rawChannel); + } + + /** A unique key used to fully describe an Ism shard. */ + static class IsmShardKey { + private final String filename; + private final RandomAccessData firstKey; + private final long startOffset; + private final long endOffset; + + private IsmShardKey( + String filename, RandomAccessData firstKey, long startOffset, long endOffset) { + this.filename = filename; + this.firstKey = firstKey; + this.startOffset = startOffset; + this.endOffset = endOffset; } @Override - public boolean advance() throws IOException { - checkState(delegate != null, "unstarted"); - long startPosition = inChannel.position(); - boolean rval = delegate.advance(); - notifyElementRead(inChannel.position() - startPosition); - return rval; + public String toString() { + return MoreObjects.toStringHelper(IsmShardKey.class) + .add("filename", filename) + .add("firstKey", firstKey) + .add("startOffset", startOffset) + .add("endOffset", endOffset) + .toString(); } @Override - public KV getCurrent() { - // By the time getCurrent() is called, delegate should already be created by - // a start() call. - if (delegate == null) { - throw new NoSuchElementException(); + public boolean equals(Object obj) { + if (!(obj instanceof IsmShardKey)) { + return false; } - return delegate.getCurrent(); + IsmShardKey cacheEntry = (IsmShardKey) obj; + return startOffset == cacheEntry.startOffset + && endOffset == cacheEntry.endOffset + && Objects.equals(filename, cacheEntry.filename) + && Objects.equals(firstKey, cacheEntry.firstKey); } @Override - public void close() throws IOException { - inChannel.close(); + public int hashCode() { + return Longs.hashCode(startOffset) + Longs.hashCode(endOffset); } } /** - * A {@link NativeReaderIterator - * Reader.ReaderIterator} for Ism formatted files which returns a sequence of - * {@code KV}'s read from a {@link SeekableByteChannel}. + * Initializes the footer, shard index, Bloom filter and index for the requested shard id if + * they have not been initialized yet. Re-uses the provided channel, returning it or a + * new one if this method was required to open one. */ - private static class IsmReaderIterator extends NativeReaderIterator> { - private final SeekableByteChannel inChannel; - private final InputStream inStream; - private final RandomAccessData currentKeyBytes; - private final Coder keyCoder; - private final Coder valueCoder; - private final long readLimit; - private KV current; + private Optional initializeForKeyedRead( + int shardId, Optional inChannel) throws IOException { + inChannel = initializeFooterAndShardIndex(inChannel); + + IsmShard shardWithIndex = shardIdToShardMap.get(shardId); + + // If this shard id is not within this file, we can return immediately. + if (shardWithIndex == null) { + return inChannel; + } + + inChannel = initializeBloomFilterAndIndexPerShard(inChannel); + + // If the index has been populated and contains the shard id, we can return. + if (indexPerShard != null && indexPerShard.containsKey(shardId)) { + checkState(bloomFilter != null, "Bloom filter expected to have been initialized."); + return inChannel; + } + + checkState(indexPerShard.get(shardId) == null, + "Expected to not have initialized index for shard %s", shardId); + + Long startOfNextBlock = shardOffsetToShardMap.higherKey(shardWithIndex.getBlockOffset()); + // If this is the last block, then we need to grab the position of the Bloom filter + // as the upper bound. + if (startOfNextBlock == null) { + startOfNextBlock = footer.getBloomFilterPosition(); + } + + // Open the channel if needed and seek to the start of the index. + SeekableByteChannel rawChannel = openIfNeeded(inChannel); + rawChannel.position(shardWithIndex.getIndexOffset()); + InputStream inStream = Channels.newInputStream(rawChannel); + + ImmutableSortedMap.Builder builder = + ImmutableSortedMap.orderedBy(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR); + + // Read the first key + RandomAccessData currentKeyBytes = new RandomAccessData(); + readKey(inStream, currentKeyBytes); + long currentOffset = VarInt.decodeLong(inStream); + + // Insert the entry that happens at the beginning limiting the shard block by the + // first keys block offset. + builder.put( + new RandomAccessData(0), + new IsmShardKey( + IsmReader.this.filename, + new RandomAccessData(0), + shardWithIndex.getBlockOffset(), + currentOffset)); + + // While another index entry exists, insert an index entry with the key, and offsets + // that limit the range of the shard block. + while (rawChannel.position() < startOfNextBlock) { + RandomAccessData nextKeyBytes = currentKeyBytes.copy(); + readKey(inStream, nextKeyBytes); + long nextOffset = VarInt.decodeLong(inStream); + + builder.put(currentKeyBytes, + new IsmShardKey( + IsmReader.this.filename, currentKeyBytes, currentOffset, nextOffset)); + + currentKeyBytes = nextKeyBytes; + currentOffset = nextOffset; + } + + // Upper bound the last entry with the index offset. + builder.put(currentKeyBytes, + new IsmShardKey( + IsmReader.this.filename, + currentKeyBytes, + currentOffset, + shardWithIndex.getIndexOffset())); + indexPerShard.put(shardId, builder.build()); + + return Optional.of(rawChannel); + } + + /** A function which takes an IsmShardKey fully describing a data block to read and return. */ + private class IsmCacheLoader + implements Callable>>>> { + + private final IsmShardKey key; + private IsmCacheLoader(IsmShardKey key) { + this.key = key; + } + + @Override + public WeightedValue>>> call() + throws IOException { + // Open a channel and build a sorted map from key to value for each key value + // pair found within the data block. + try (SeekableByteChannel rawChannel = open()) { + try (WithinShardIsmReaderIterator readerIterator = new WithinShardIsmReaderIterator( + rawChannel, key.firstKey, key.startOffset, key.endOffset)) { + + ImmutableSortedMap.Builder>> mapBuilder = + ImmutableSortedMap.orderedBy(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR); + while (readerIterator.hasNext()) { + RandomAccessData nextKey = readerIterator.peekKey().copy(); + WindowedValue> next = readerIterator.next(); + mapBuilder.put(nextKey, next); + } + // We return the size of the data block as the weight of this data block. + return WeightedValue.of( + (NavigableMap>>) mapBuilder.build(), + key.endOffset - key.startOffset); + } + } + } + } + + /** + * Fetches the data block requested. + * + * If the cache is available, we will load and cache the requested block. Otherwise, we will + * load and return the block. + */ + private NavigableMap>> + fetch(IsmShardKey key) throws IOException { + try { + if (cache == null) { + return new IsmCacheLoader(key).call().getValue(); + } else { + return cache.get(key, new IsmCacheLoader(key)).getValue(); + } + } catch (ExecutionException e) { + // Try and re-throw the root cause if its an IOException + Throwables.propagateIfPossible(e.getCause(), IOException.class); + throw new IOException(e.getCause()); + } + } + + /** The base class of Ism reader iterators which operate over a given key prefix. */ + abstract class IsmPrefixReaderIterator + extends LegacyReaderIterator>> { + private final List keyComponents; + private IsmPrefixReaderIterator(List keyComponents) { + this.keyComponents = keyComponents; + } /** - * Start an initialized reader that will start from the given key. This reader iterator does - * not own the channel and the caller must ensure that it is closed. + * Returns the list of key components representing this iterators key prefix. */ - public IsmReaderIterator( - SeekableByteChannel unownedChannel, - RandomAccessData currentKeyBytes, - Coder keyCoder, - Coder valueCoder, - long readLimit) + protected List getKeyComponents() { + return keyComponents; + } + + /** + * Concatenates this reader iterators key components with the additionally supplied + * key components and encodes them into their byte representations producing a key. + * Returns the exact record represented by the key generated above. + * + * Null is returned if no key has all the key components as a prefix within this file. + */ + public final WindowedValue> get(List additionalKeyComponents) throws IOException { - checkNotNull(unownedChannel); - checkNotNull(currentKeyBytes); - checkNotNull(keyCoder); - checkNotNull(valueCoder); - checkArgument(readLimit >= 0L); - this.inChannel = unownedChannel; - this.inStream = Channels.newInputStream(unownedChannel); + RandomAccessData keyBytes = new RandomAccessData(); + int shardId = coder.encodeAndHash( + ImmutableList.builder().addAll(keyComponents).addAll(additionalKeyComponents).build(), + keyBytes); + return getBlock(keyBytes, shardId).get(keyBytes); + } + + /** + * Returns the record for the last key having this iterators key prefix. + * Last is defined as the largest key with the same key prefix when comparing key's + * byte representations using an unsigned lexicographical byte order. + * + * Null is returned if the prefix is not present within this file. + */ + public WindowedValue> getLast() throws IOException { + RandomAccessData keyBytes = new RandomAccessData(); + int shardId = coder.encodeAndHash(keyComponents, keyBytes); + + Optional inChannel = + initializeFooterAndShardIndex(Optional.absent()); + + // Key is not stored here + if (!shardIdToShardMap.containsKey(shardId) + || !bloomFilterMightContain(keyBytes)) { + return null; + } + + inChannel = initializeForKeyedRead(shardId, inChannel); + closeIfPresent(inChannel); + + final NavigableMap indexInShard = indexPerShard.get(shardId); + RandomAccessData end = keyBytes.increment(); + final IsmShardKey cacheEntry = indexInShard.floorEntry(end).getValue(); + + NavigableMap>> block = fetch(cacheEntry); + + RandomAccessData lastKey = block.lastKey(); + + // If the requested key is greater then the last key within the block, then it + // does not exist. + if (RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare(keyBytes, lastKey) > 0) { + return null; + } + + Entry>> rval = block.floorEntry(end); + + // If the prefix matches completely then we can return + if (RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.commonPrefixLength( + keyBytes, rval.getKey()) == keyBytes.size()) { + return rval.getValue(); + } + return null; + } + } + + /** An empty reader iterator. */ + class EmptyIsmPrefixReaderIterator extends IsmPrefixReaderIterator { + private EmptyIsmPrefixReaderIterator(List keyComponents) { + super(keyComponents); + } + + @Override + public boolean hasNextImpl() throws IOException { + return false; + } - // Copy the key since the IsmReaderIterator mutates the key. - this.currentKeyBytes = new RandomAccessData(currentKeyBytes.size()); - currentKeyBytes.writeTo(this.currentKeyBytes.asOutputStream(), 0, currentKeyBytes.size()); + @Override + public WindowedValue> nextImpl() throws IOException, NoSuchElementException { + throw new NoSuchElementException(); + } + } + + /** A reader iterator which initializes its input stream lazily. */ + class LazyIsmPrefixReaderIterator extends IsmPrefixReaderIterator { + private IsmPrefixReaderIterator delegate; - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; - this.readLimit = readLimit; + public LazyIsmPrefixReaderIterator() { + super(ImmutableList.of()); } @Override - public boolean start() throws IOException { - return advance(); + public boolean hasNextImpl() throws IOException { + return getDelegate().hasNext(); } @Override - public boolean advance() throws IOException { - if (inChannel.position() >= readLimit) { - current = null; - return false; + public WindowedValue> nextImpl() + throws IOException, NoSuchElementException { + WindowedValue> rval = getDelegate().next(); + return rval; + } + + @Override + public void close() throws IOException { + if (delegate != null) { + delegate.close(); + } + } + + /** Return a reader, caching the creation on the first call. */ + private IsmPrefixReaderIterator getDelegate() throws IOException { + if (delegate == null) { + delegate = overKeyComponents(getKeyComponents()); + } + return delegate; + } + } + + /** + * Returns a map from key to value, where the keys are in increasing lexicographical order. + * If the requested key is not contained within this file, an empty map is returned. + */ + private NavigableMap>> + getBlock(RandomAccessData keyBytes, int shardId) throws IOException { + Optional inChannel = + initializeFooterAndShardIndex(Optional.absent()); + + // Key is not stored here so return an empty map. + if (!shardIdToShardMap.containsKey(shardId) + || !bloomFilterMightContain(keyBytes)) { + return ImmutableSortedMap.>>orderedBy( + RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR).build(); + } + + inChannel = initializeForKeyedRead(shardId, inChannel); + closeIfPresent(inChannel); + + final NavigableMap indexInShard = indexPerShard.get(shardId); + final IsmShardKey cacheEntry = indexInShard.floorEntry(keyBytes).getValue(); + return fetch(cacheEntry); + } + + /** + * A reader iterator that returns all elements from prefix (inclusive) to + * prefixUpperBound (exclusive) within the set of block entries provided. + */ + private class WithinShardIsmPrefixReaderIterator extends IsmPrefixReaderIterator { + private final Iterator blockEntriesIterator; + Iterator>> iterator; + private final RandomAccessData prefix; + private final RandomAccessData prefixUpperBound; + + private WithinShardIsmPrefixReaderIterator( + List keyComponents, + RandomAccessData prefix, + RandomAccessData prefixUpperBound, + Iterator blockEntriesIterator) { + super(keyComponents); + checkNotNull(blockEntriesIterator); + this.prefix = prefix; + this.prefixUpperBound = prefixUpperBound; + this.blockEntriesIterator = blockEntriesIterator; + } + + @Override + public boolean hasNextImpl() throws IOException { + // This is in a while loop because the blocks that we are asked to look into may + // not contain the key prefix. + while (iterator == null || !iterator.hasNext()) { + // If there are no blocks to iterate over we can return false + if (!blockEntriesIterator.hasNext()) { + return false; + } + + IsmShardKey nextBlock = blockEntriesIterator.next(); + NavigableMap>> map = + fetch(nextBlock); + SortedMap>> submap = + map.subMap(prefix, prefixUpperBound); + Collection>> values = submap.values(); + iterator = values.iterator(); } - KeyPrefix keyPrefix = KeyPrefixCoder.of().decode(inStream, Context.NESTED); - int totalKeyLength = keyPrefix.getSharedKeySize() + keyPrefix.getUnsharedKeySize(); - // currentKey = prevKey[0 : sharedKeySize] + read(unsharedKeySize) - currentKeyBytes.readFrom( - inStream, - keyPrefix.getSharedKeySize() /* start to overwrite the previous key at sharedKeySize */, - keyPrefix.getUnsharedKeySize() /* read unsharedKeySize bytes from the stream */); - K key = keyCoder.decode(currentKeyBytes.asInputStream(0, totalKeyLength), Context.OUTER); - V value = valueCoder.decode(inStream, Context.NESTED); - current = KV.of(key, value); - return true; + return iterator.hasNext(); } @Override - public KV getCurrent() { - if (current == null) { - throw new NoSuchElementException(); + public WindowedValue> nextImpl() + throws IOException, NoSuchElementException { + return iterator.next(); + } + } + + /** A reader iterator that returns all records across all shards contained within this file. */ + private class ShardAwareIsmPrefixReaderIterator extends IsmPrefixReaderIterator { + private final SeekableByteChannel rawChannel; + private WithinShardIsmReaderIterator delegate; + private Iterator shardEntries; + + private ShardAwareIsmPrefixReaderIterator( + List keyComponents, SeekableByteChannel rawChannel) throws IOException { + super(keyComponents); + checkState(shardOffsetToShardMap.size() > 0, + "Expected that shard offset to shard map has been initialized and is not empty."); + + this.rawChannel = rawChannel; + this.shardEntries = shardOffsetToShardMap.values().iterator(); + IsmShard firstShard = shardEntries.next(); + delegate = new WithinShardIsmReaderIterator( + rawChannel, + new RandomAccessData(), + firstShard.getBlockOffset(), + firstShard.getIndexOffset()); + } + + @Override + public boolean hasNextImpl() throws IOException { + // If the current shard has a value, or we have another shard index to + // look into then we know that there is another value. + return delegate.hasNext() || shardEntries.hasNext(); + } + + @Override + public WindowedValue> nextImpl() + throws IOException, NoSuchElementException { + // If our current shard index is empty, we need to move to the next one. + if (!delegate.hasNext()) { + moveToNextShard(); } - return current; + WindowedValue> rval = delegate.next(); + return rval; + } + + @Override + public void close() throws IOException { + rawChannel.close(); + } + + @Override + public WindowedValue> getLast() throws IOException { + // Since this is an iterator over all of the file, we return the last record within the file. + int lastShardId = shardOffsetToShardMap.lastEntry().getValue().getId(); + initializeForKeyedRead(lastShardId, Optional.absent()); + NavigableMap>> lastBlock = + getBlock(indexPerShard.get(lastShardId).lastKey(), lastShardId); + return lastBlock.lastEntry().getValue(); + } + + private void moveToNextShard() throws IOException { + IsmShard nextIsmShard = shardEntries.next(); + checkState(nextIsmShard.getBlockOffset() >= rawChannel.position(), + "Expected channel read order to be sequential."); + + delegate = new WithinShardIsmReaderIterator( + rawChannel, new RandomAccessData(), + nextIsmShard.getBlockOffset(), nextIsmShard.getIndexOffset()); + + checkState(delegate.hasNext(), "Expected each shard to contain at least one entry."); } } /** - * Initializes the footer, Bloom filter and index if they have not yet been initialized. - * Returns a {@link SeekableByteChannel} at an arbitrary position within the stream. - * Callers should re-position the channel to their desired location. + * A reader iterator for Ism formatted files which returns a sequence of Ism records + * from the underlying channel from where it is currently positioned till + * the supplied limit. + * + * This reader iterator will use the supplied bytes as the bytes for the previous key + * which is required to do the KeyPrefix based key decoding. */ - private SeekableByteChannel initializeForKeyedRead() throws IOException { - SeekableByteChannel inChannel = openConnection(filename); - if (index != null) { - checkState(footer != null, "Footer expected to have been initialized."); - checkState(bloomFilter != null, "Bloom filter expected to have been initialized."); - return inChannel; + private class WithinShardIsmReaderIterator + extends LegacyReaderIterator>> { + private final SeekableByteChannel rawChannel; + private final InputStream inStream; + private long readLimit; + private RandomAccessData keyBytes; + private boolean keyIsPeeked; + private long position; + + private WithinShardIsmReaderIterator( + SeekableByteChannel rawChannel, + RandomAccessData currentKeyBytes, + long newPosition, + long newLimit) throws IOException { + checkNotNull(rawChannel); + checkNotNull(currentKeyBytes); + checkArgument(newLimit >= 0L); + checkArgument(newPosition <= newLimit); + this.rawChannel = rawChannel; + this.inStream = Channels.newInputStream(rawChannel); + this.keyBytes = currentKeyBytes.copy(); + this.position = newPosition; + this.readLimit = newLimit; + this.keyIsPeeked = false; + IsmReader.position(rawChannel, newPosition); } - checkState(bloomFilter == null, "Bloom filter not expected to have been initialized."); - - initializeFooter(inChannel); - - // Set the position to where the bloom filter is and read it in. - inChannel.position(footer.getBloomFilterPosition()); - bloomFilter = ScalableBloomFilterCoder.of().decode( - Channels.newInputStream(inChannel), Context.NESTED); - - // The index follows the bloom filter directly, so we do not need to do a seek here. - // This is an optimization. - @SuppressWarnings("resource") - NativeReaderIterator> iterator = - new IsmReaderIterator( - inChannel, - new RandomAccessData(), - RandomAccessDataCoder.of(), - VarLongCoder.of(), - length - Footer.FIXED_LENGTH); - ImmutableSortedMap.Builder builder = - ImmutableSortedMap.orderedBy(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR); - // Read the index into memory. - for (boolean more = iterator.start(); more; more = iterator.advance()) { - KV next = iterator.getCurrent(); - builder.put(next.getKey(), next.getValue()); + @Override + public boolean hasNextImpl() throws IOException { + if (position > readLimit) { + throw new IllegalStateException("Read past end of stream"); + } + return position < readLimit; + } + + @Override + public WindowedValue> nextImpl() throws IOException, NoSuchElementException { + RandomAccessData peekedKey = peekKey(); + keyIsPeeked = false; + + InputStream keyInputStream = peekedKey.asInputStream(0, peekedKey.size()); + List keyComponents = new ArrayList<>(coder.getKeyComponentCoders().size()); + for (int i = 0; i < coder.getKeyComponentCoders().size(); ++i) { + keyComponents.add(coder.getKeyComponentCoder(i).decode( + keyInputStream, + Context.NESTED)); + } + + final IsmRecord ismRecord; + if (IsmFormat.isMetadataKey(keyComponents)) { + byte[] metadata = ByteArrayCoder.of().decode(inStream, Context.NESTED); + ismRecord = IsmRecord.meta(keyComponents, metadata); + } else { + V value = coder.getValueCoder().decode(inStream, Context.NESTED); + ismRecord = IsmRecord.of(keyComponents, value); + } + + long newPosition = rawChannel.position(); + notifyElementRead(newPosition - position); + position = newPosition; + return valueInEmptyWindows(ismRecord); + } + + public RandomAccessData peekKey() throws IOException, NoSuchElementException { + if (keyIsPeeked) { + return keyBytes; + } + readKey(inStream, keyBytes); + keyIsPeeked = true; + + return keyBytes; } - index = builder.build(); - return inChannel; } /** - * Returns a {@link SeekableByteChannel} for the given {@code filename}. + * Decodes a KeyPrefix from the stream and then reads unshared key bytes from the stream + * placing them into the supplied keyBytes at position + * keyBytes[shared key bytes : shared key bytes + unshared key bytes]. */ - private static SeekableByteChannel openConnection(String filename) throws IOException { + private static void readKey(InputStream inStream, RandomAccessData keyBytes) + throws IOException { + KeyPrefix keyPrefix = KeyPrefixCoder.of().decode(inStream, Context.NESTED); + // currentKey = prevKey[0 : sharedKeySize] + read(unsharedKeySize) + keyBytes.readFrom( + inStream, + keyPrefix.getSharedKeySize() /* start to overwrite the previous key at sharedKeySize */, + keyPrefix.getUnsharedKeySize() /* read unsharedKeySize bytes from the stream */); + // Reset the length incase the next key was shorter. + keyBytes.resetTo(keyPrefix.getSharedKeySize() + keyPrefix.getUnsharedKeySize()); + } + + /** Closes the underlying channel if present. */ + private void closeIfPresent(Optional inChannel) throws IOException { + if (inChannel.isPresent()) { + inChannel.get().close(); + } + } + + /** Returns a channel, opening a new one if required. */ + private SeekableByteChannel openIfNeeded(Optional inChannel) + throws IOException { + if (inChannel.isPresent()) { + return inChannel.get(); + } + return open(); + } + + /** Opens a new channel. */ + private SeekableByteChannel open() + throws IOException { ReadableByteChannel channel = IOChannelUtils.getFactory(filename).open(filename); - checkArgument( - channel instanceof SeekableByteChannel, + Preconditions.checkArgument(channel instanceof SeekableByteChannel, "IsmReader requires a SeekableByteChannel for path %s but received %s.", - filename, - channel); + filename, channel); return (SeekableByteChannel) channel; } -} + /** + * Seeks into the channel intelligently by either resetting the position or reading and + * discarding bytes. + */ + private static void position(SeekableByteChannel inChannel, long newPosition) throws IOException { + long currentPosition = inChannel.position(); + // If just doing a read is cheaper discarding the bytes lets just do the read + if (currentPosition < newPosition && newPosition - currentPosition <= SEEK_VS_READ) { + ByteStreams.skipFully(Channels.newInputStream(inChannel), newPosition - currentPosition); + } else { + // Otherwise we will perform a seek + inChannel.position(newPosition); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java index 9f077802e1..cdb565fff0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java @@ -15,12 +15,18 @@ */ package com.google.cloud.dataflow.sdk.runners.worker; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.Footer; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.FooterCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShard; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefix; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefixCoder; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; @@ -31,46 +37,59 @@ import com.google.cloud.dataflow.sdk.util.VarInt; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Optional; import com.google.common.io.CountingOutputStream; import java.io.IOException; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; +import java.util.ArrayList; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; /** - * A {@link Sink} that writes Ism files. The coder provided is used to encode each key value - * record. See {@link IsmFormat} for encoded format details. + * A {@link Sink} that writes Ism files. * - * @param the type of the keys written to the sink - * @param the type of the values written to the sink + * @param the type of the value written to the sink */ -public class IsmSink extends Sink>> { +public class IsmSink extends Sink>> { + private static final int BLOCK_SIZE_BYTES = 1024 * 1024; private final String filename; - private final Coder keyCoder; - private final Coder valueCoder; + private final IsmRecordCoder coder; - IsmSink(String filename, Coder keyCoder, Coder valueCoder) { + /** + * Produces a sink for the specified {@code filename} and {@code coder}. + * See {@link IsmFormat} for encoded format details. + */ + IsmSink(String filename, IsmRecordCoder coder) { + IsmFormat.validateCoderIsCompatible(coder); this.filename = filename; - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; + this.coder = coder; } @Override - public SinkWriter>> writer() throws IOException { + public SinkWriter>> writer() throws IOException { return new IsmSinkWriter(IOChannelUtils.create(filename, MimeTypes.BINARY)); } - private class IsmSinkWriter implements SinkWriter>> { - private static final long MAX_BLOCK_SIZE = 1024 * 1024; + // Can be overridden by tests to generate files with smaller block sizes for testing. + @VisibleForTesting + long getBlockSize() { + return BLOCK_SIZE_BYTES; + } + private class IsmSinkWriter implements SinkWriter>> { private final CountingOutputStream out; private final RandomAccessData indexOut; - private RandomAccessData lastKeyBytes; + private RandomAccessData previousKeyBytes; + private Optional previousShard; private RandomAccessData currentKeyBytes; private RandomAccessData lastIndexKeyBytes; private long lastIndexedPosition; private long numberOfKeysWritten; + private SortedMap shardKeyToShardMap; private final ScalableBloomFilter.Builder bloomFilterBuilder; /** @@ -80,34 +99,70 @@ private IsmSinkWriter(WritableByteChannel channel) { checkNotNull(channel); out = new CountingOutputStream(Channels.newOutputStream(channel)); indexOut = new RandomAccessData(); - lastKeyBytes = new RandomAccessData(); + previousShard = Optional.absent(); + previousKeyBytes = new RandomAccessData(); currentKeyBytes = new RandomAccessData(); lastIndexKeyBytes = new RandomAccessData(); bloomFilterBuilder = ScalableBloomFilter.builder(); + shardKeyToShardMap = new TreeMap<>(); } @Override - public long add(WindowedValue> windowedValue) throws IOException { + public long add(WindowedValue> windowedRecord) throws IOException { // The windowed portion of the value is ignored. - KV value = windowedValue.getValue(); + IsmRecord record = windowedRecord.getValue(); + + checkArgument(coder.getKeyComponentCoders().size() == record.getKeyComponents().size()); + + List keyOffsetPositions = new ArrayList<>(); + final int currentShard = + coder.encodeAndHash(record.getKeyComponents(), currentKeyBytes, keyOffsetPositions); + // Put each component of the key into the Bloom filter so that we can use the Bloom + // filter for key prefix checks. + for (Integer offsetPosition : keyOffsetPositions) { + bloomFilterBuilder.put(currentKeyBytes.array(), 0, offsetPosition); + } + + // If we are moving to another shard, finish outputting the last shard. + if (previousShard.isPresent() && currentShard != previousShard.get()) { + // We reset last shard to be empty. + finishShard(); + } long currentPosition = out.getCount(); - // Marshal the key, compute the common prefix length - keyCoder.encode(value.getKey(), currentKeyBytes.asOutputStream(), Context.OUTER); - int keySize = currentKeyBytes.size(); - int sharedKeySize = commonPrefixLength(lastKeyBytes, currentKeyBytes); + + // If we are doing a reset because the shard number is changing we + // assume 0 bytes are saved from the previous key. + int sharedKeySize; + if (!previousShard.isPresent()) { + sharedKeySize = 0; + // Create a new shard record for the current value being output validating + // that we have never seen this shard before. + IsmShard ismShard = IsmShard.of(currentShard, currentPosition); + checkState(shardKeyToShardMap.put(currentShard, ismShard) == null, + "Unexpected insertion of keys %s for shard which already exists %s. " + + "Ism files expect that all shards are written contiguously.", + record.getKeyComponents(), ismShard); + } else { + sharedKeySize = commonPrefixLengthWithOrderCheck(previousKeyBytes, currentKeyBytes); + } // Put key-value mapping record into block buffer - int unsharedKeySize = keySize - sharedKeySize; + int unsharedKeySize = currentKeyBytes.size() - sharedKeySize; KeyPrefix keyPrefix = new KeyPrefix(sharedKeySize, unsharedKeySize); KeyPrefixCoder.of().encode(keyPrefix, out, Context.NESTED); currentKeyBytes.writeTo(out, sharedKeySize, unsharedKeySize); - valueCoder.encode(value.getValue(), out, Context.NESTED); + if (IsmFormat.isMetadataKey(record.getKeyComponents())) { + ByteArrayCoder.of().encode(record.getMetadata(), out, Context.NESTED); + } else { + coder.getValueCoder().encode(record.getValue(), out, Context.NESTED); + } - // If we have emitted enough bytes to add another entry into the index. - if (lastIndexedPosition + MAX_BLOCK_SIZE < out.getCount()) { - int sharedIndexKeySize = commonPrefixLength(lastIndexKeyBytes, currentKeyBytes); - int unsharedIndexKeySize = keySize - sharedIndexKeySize; + // If we have emitted enough bytes to add another entry into the index + if (out.getCount() > lastIndexedPosition + getBlockSize()) { + int sharedIndexKeySize = + commonPrefixLengthWithOrderCheck(lastIndexKeyBytes, currentKeyBytes); + int unsharedIndexKeySize = currentKeyBytes.size() - sharedIndexKeySize; KeyPrefix indexKeyPrefix = new KeyPrefix(sharedIndexKeySize, unsharedIndexKeySize); KeyPrefixCoder.of().encode(indexKeyPrefix, indexOut.asOutputStream(), Context.NESTED); currentKeyBytes.writeTo( @@ -115,14 +170,15 @@ public long add(WindowedValue> windowedValue) throws IOException { VarInt.encode(currentPosition, indexOut.asOutputStream()); lastIndexKeyBytes.resetTo(0); currentKeyBytes.writeTo(lastIndexKeyBytes.asOutputStream(), 0, currentKeyBytes.size()); + lastIndexedPosition = out.getCount(); } - // Update the bloom filter - bloomFilterBuilder.put(currentKeyBytes.array(), 0, currentKeyBytes.size()); + // Remember the shard for the current key. + previousShard = Optional.of(currentShard); // Swap the current key and the previous key, resetting the previous key to be re-used. - RandomAccessData temp = lastKeyBytes; - lastKeyBytes = currentKeyBytes; + RandomAccessData temp = previousKeyBytes; + previousKeyBytes = currentKeyBytes; currentKeyBytes = temp; currentKeyBytes.resetTo(0); @@ -135,45 +191,79 @@ public long add(WindowedValue> windowedValue) throws IOException { * and perform a key order check. We check that the currently being inserted key * is strictly greater than the previous key. */ - private int commonPrefixLength( + private int commonPrefixLengthWithOrderCheck( RandomAccessData prevKeyBytes, RandomAccessData currentKeyBytes) { - byte[] prevKey = prevKeyBytes.array(); - byte[] currentKey = currentKeyBytes.array(); - int minBytesLen = Math.min(prevKeyBytes.size(), currentKeyBytes.size()); - for (int i = 0; i < minBytesLen; i++) { - // unsigned comparison - int b1 = prevKey[i] & 0xFF; - int b2 = currentKey[i] & 0xFF; - if (b1 > b2) { - throw new IllegalArgumentException(IsmSinkWriter.class.getSimpleName() - + " expects keys to be written in strictly increasing order but was given " - + prevKeyBytes + " as the previous key and " + currentKeyBytes - + " as the current key. Expected " + b1 + " <= " + b2 + " at position " + i + "."); - } - if (b1 != b2) { - return i; - } - } - if (prevKeyBytes.size() >= currentKeyBytes.size()) { + int offset = RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR + .commonPrefixLength(prevKeyBytes, currentKeyBytes); + int compare = RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR + .compare(prevKeyBytes, currentKeyBytes, offset); + if (compare < 0) { + return offset; + } else if (compare == 0) { + throw new IllegalArgumentException(IsmSinkWriter.class.getSimpleName() + + " expects keys to be written in strictly increasing order but was given " + + prevKeyBytes + " as the previous key and " + currentKeyBytes + + " as the current key. Expected " + prevKeyBytes.array()[offset + 1] + " <= " + + currentKeyBytes.array()[offset + 1] + " at position " + (offset + 1) + "."); + } else { throw new IllegalArgumentException(IsmSinkWriter.class.getSimpleName() + " expects keys to be written in strictly increasing order but was given " + prevKeyBytes + " as the previous key and " + currentKeyBytes + " as the current key. Expected length of previous key " + prevKeyBytes.size() + " <= " + currentKeyBytes.size() + " to current key."); } - return minBytesLen; } /** - * Completes the construction of the Ism file. + * Outputs the end of a shard. This is done by: + *
      + *
    • updating the shard index for the current shard with the index offset
    • + *
    • writing out the index for the shard
    • + *
    • resetting the last indexed position
    • + *
    • forgetting the last shard
    • + *
    + */ + private void finishShard() throws IOException { + // Update the last shard record as to the position of the index. + IsmShard ismShard = shardKeyToShardMap.get(previousShard.get()); + shardKeyToShardMap.put( + previousShard.get(), ismShard.withIndexOffset(out.getCount())); + + indexOut.writeTo(out, 0, indexOut.size()); + indexOut.resetTo(0); + + // Reset the last indexed position to here. + lastIndexedPosition = out.getCount(); + lastIndexKeyBytes = new RandomAccessData(); + + // Clear the last shard. + previousShard = Optional.absent(); + } + + /** + * Completes the construction of the Ism file. This is done by: + *
      + *
    • finishing the last shard if present
    • + *
    • writing out the Bloom filter
    • + *
    • writing out the shard index
    • + *
    • writing out the footer
    • + *
    * * @throws IOException if an underlying write fails */ private void finish() throws IOException { + // Update the last shard if at least one element was written. + if (previousShard.isPresent()) { + finishShard(); + } + long startOfBloomFilter = out.getCount(); ScalableBloomFilterCoder.of().encode(bloomFilterBuilder.build(), out, Context.NESTED); + long startOfIndex = out.getCount(); - indexOut.writeTo(out, 0, indexOut.size()); + IsmFormat.ISM_SHARD_INDEX_CODER.encode( + new ArrayList<>(shardKeyToShardMap.values()), out, Context.NESTED); + FooterCoder.of().encode(new Footer(startOfIndex, startOfBloomFilter, numberOfKeysWritten), out, Coder.Context.OUTER); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java new file mode 100644 index 0000000000..b1386067d1 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import static com.google.cloud.dataflow.sdk.util.Structs.getString; +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.worker.Sink; + +/** + * Creates an {@link IsmSink} from a {@link CloudObject} spec. Note that it is invalid to use a + * non {@link IsmRecordCoder} with this sink factory. + */ +public class IsmSinkFactory { + // Do not instantiate. + private IsmSinkFactory() {} + + @SuppressWarnings("unused") + public static Sink>> create( + PipelineOptions options, + CloudObject spec, + Coder>> coder, + ExecutionContext executionContext, + CounterSet.AddCounterMutator addCounterMutator) throws Exception { + return create(spec, coder); + } + + static Sink>> create( + CloudObject spec, Coder>> coder) throws Exception { + String filename = getString(spec, PropertyNames.FILENAME); + + checkArgument(coder instanceof WindowedValueCoder, + "%s only supports using %s but got %s.", IsmSink.class, WindowedValueCoder.class, coder); + WindowedValueCoder> windowedCoder = + (WindowedValueCoder>) coder; + + checkArgument(windowedCoder.getValueCoder() instanceof IsmRecordCoder, + "%s only supports using %s but got %s.", + IsmSink.class, IsmRecordCoder.class, windowedCoder.getValueCoder()); + @SuppressWarnings("unchecked") + IsmRecordCoder ismCoder = + (IsmRecordCoder) windowedCoder.getValueCoder(); + + return new IsmSink<>(filename, ismCoder); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java index 63a22288f0..da228ac635 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java @@ -55,6 +55,8 @@ private SinkFactory() {} TextSinkFactory.class.getName()); predefinedSinkFactories.put("AvroSink", AvroSinkFactory.class.getName()); + predefinedSinkFactories.put("IsmSink", + IsmSinkFactory.class.getName()); predefinedSinkFactories.put("ShuffleSink", ShuffleSinkFactory.class.getName()); predefinedSinkFactories.put("PubsubSink", @@ -75,6 +77,7 @@ public static Sink create( ExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator) throws Exception { + @SuppressWarnings("unchecked") Coder coder = Serializer.deserialize(cloudSink.getCodec(), Coder.class); CloudObject object = CloudObject.fromSpec(cloudSink.getSpec()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java index f03a2e9887..36875040be 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java @@ -23,6 +23,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.CoderException; @@ -37,11 +38,13 @@ import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefixCoder; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.cloud.dataflow.sdk.testing.CoderPropertiesTest.NonDeterministicCoder; import com.google.common.collect.ImmutableList; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -54,7 +57,32 @@ */ @RunWith(JUnit4.class) public class IsmFormatTest { + private static final Coder NON_DETERMINISTIC_CODER = new NonDeterministicCoder(); @Rule public ExpectedException expectedException = ExpectedException.none(); + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); + + @Test + public void testUsingNonDeterministicShardKeyCoder() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("is expected to be deterministic"); + IsmFormat.validateCoderIsCompatible(IsmRecordCoder.of( + 1, // number or shard key coders for value records + 0, // number of shard key coders for metadata records + ImmutableList.>of(NON_DETERMINISTIC_CODER, ByteArrayCoder.of()), + ByteArrayCoder.of())); + } + + @Test + public void testUsingNonDeterministicNonShardKeyCoder() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("is expected to be deterministic"); + IsmFormat.validateCoderIsCompatible(IsmRecordCoder.of( + 1, // number or shard key coders for value records + 0, // number of shard key coders for metadata records + ImmutableList.>of(ByteArrayCoder.of(), NON_DETERMINISTIC_CODER), + ByteArrayCoder.of())); + } + @Test public void testKeyPrefixCoder() throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java index 7ee710ac40..3ae91641e1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java @@ -15,25 +15,44 @@ */ package com.google.cloud.dataflow.sdk.runners.worker; +import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; +import static com.google.common.base.Preconditions.checkState; import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmReader.IsmShardKey; +import com.google.cloud.dataflow.sdk.testing.CoderPropertiesTest.NonDeterministicCoder; +import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.RandomAccessData; +import com.google.cloud.dataflow.sdk.util.WeightedValue; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils.TestReaderObserver; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.util.common.worker.Sink.SinkWriter; -import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; +import com.google.common.primitives.UnsignedBytes; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -42,55 +61,163 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Random; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; -/** - * Tests for {@link IsmReader}. - */ +/** Tests for {@link IsmReader}. */ @RunWith(JUnit4.class) public class IsmReaderTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); + private static final int TEST_BLOCK_SIZE = 1024; + private static final IsmRecordCoder CODER = + IsmRecordCoder.of( + 1, // number or shard key coders for value records + 1, // number of shard key coders for metadata records + ImmutableList.>of(MetadataKeyCoder.of(ByteArrayCoder.of()), ByteArrayCoder.of()), + ByteArrayCoder.of()); + + private static final Coder NON_DETERMINISTIC_CODER = new NonDeterministicCoder(); + private static final byte[] EMPTY = new byte[0]; + + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); + @Rule public ExpectedException expectedException = ExpectedException.none(); + + private Cache>>>> cache; + + @Before + public void setUp() { + cache = CacheBuilder + .newBuilder() + .weigher(Weighers.fixedWeightKeys(1)) + .maximumWeight(10_000) + .build(); + } @Test public void testReadEmpty() throws Exception { - runTestRead(Collections.>emptyList(), tmpFolder.newFile()); + writeElementsToFileAndReadInOrder(Collections.>emptyList()); + } + + @Test + public void testUsingNonDeterministicShardKeyCoder() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("is expected to be deterministic"); + new IsmReader<>( + tmpFolder.newFile().getPath(), + IsmRecordCoder.of( + 1, // number or shard key coders for value records + 0, // number of shard key coders for metadata records + ImmutableList.>of(NON_DETERMINISTIC_CODER, ByteArrayCoder.of()), + ByteArrayCoder.of()), + cache); + } + + @Test + public void testUsingNonDeterministicNonShardKeyCoder() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("is expected to be deterministic"); + new IsmReader<>( + tmpFolder.newFile().getPath(), + IsmRecordCoder.of( + 1, // number or shard key coders for value records + 0, // number of shard key coders for metadata records + ImmutableList.>of(ByteArrayCoder.of(), NON_DETERMINISTIC_CODER), + ByteArrayCoder.of()), + cache); } @Test public void testRead() throws Exception { Random random = new Random(23498321490L); - for (int i : Arrays.asList(4, 8, 12)) { + for (int i : Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) { int minElements = (int) Math.pow(2, i); + int valueSize = 128; // Generates between 2^i and 2^(i + 1) elements. - runTestRead(dataGenerator(minElements + random.nextInt(minElements), - 8 /* approximate key size */, 8 /* max value size */), tmpFolder.newFile()); + writeElementsToFileAndReadInOrder(dataGenerator(8 /* number of primary keys */, + minElements + random.nextInt(minElements) /* number of secondary keys */, + 8 /* max key size */, valueSize)); } } + @Test + public void testReadThatProducesIndexEntries() throws Exception { + Random random = new Random(23498323891L); + int minElements = (int) Math.pow(2, 6); + int valueSize = 128; + // Since we are generating more then 2 blocks worth of data, we are guaranteed that + // at least one index entry is generated per shard. + checkState(minElements * valueSize > 2 * TEST_BLOCK_SIZE); + writeElementsToFileAndReadInOrder(dataGenerator(8 /* number of primary keys */, + minElements + random.nextInt(minElements) /* number of secondary keys */, + 8 /* max key size */, valueSize /* max value size */)); + } + @Test public void testReadRandomOrder() throws Exception { Random random = new Random(2348238943L); - for (int i : Arrays.asList(4, 8, 12)) { + for (int i : Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)) { int minElements = (int) Math.pow(2, i); + int valueSize = 128; // Generates between 2^i and 2^(i + 1) elements. - runTestReadRandomOrder( - dataGenerator(minElements + random.nextInt(minElements), - 8 /* approximate key size */, 4096 /* max value size */), tmpFolder.newFile()); + writeElementsToFileAndReadInRandomOrder(dataGenerator(7 /* number of primary keys */, + minElements + random.nextInt(minElements) /* number of secondary keys */, + 8 /* max key size */, valueSize /* max value size */)); } } + @Test + public void testGetLastWithPrefix() throws Exception { + Random random = new Random(2348238943L); + for (int i : Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) { + int minElements = (int) Math.pow(2, i); + int valueSize = 128; + // Generates between 2^i and 2^(i + 1) elements. + writeElementsToFileAndFindLastElementPerPrimaryKey( + dataGenerator(7, minElements + random.nextInt(minElements), + 8 /* max key size */, valueSize /* max value size */)); + } + } + + @Test + public void testReadMissingKeys() throws Exception { + File tmpFile = tmpFolder.newFile(); + List> data = new ArrayList<>(); + data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x04 }), EMPTY)); + data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x08 }), EMPTY)); + writeElementsToFile(data, tmpFile); + + IsmReader reader = new IsmReader(tmpFile.getAbsolutePath(), CODER, cache); + + // Check that we got false with a key before all keys contained in the file. + assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x02 })).hasNext()); + // Check that we got false with a key between two other keys contained in the file. + assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x06 })).hasNext()); + // Check that we got false with a key that is after all keys contained in the file. + assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x10 })).hasNext()); + } + @Test public void testReadMissingKeysBypassingBloomFilter() throws Exception { - List> data = new ArrayList<>(); - data.add(KV.of(new byte[]{ 0x04 }, new byte[] { 0x00 })); - data.add(KV.of(new byte[]{ 0x08 }, new byte[] { 0x01 })); - String path = initInputFile(data, tmpFolder.newFile()); - IsmReader reader = - new IsmReader(path, ByteArrayCoder.of(), ByteArrayCoder.of()) { + File tmpFile = tmpFolder.newFile(); + List> data = new ArrayList<>(); + data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x04 }), EMPTY)); + data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x08 }), EMPTY)); + writeElementsToFile(data, tmpFile); + + IsmReader reader = + new IsmReader(tmpFile.getAbsolutePath(), CODER, cache) { // We use this override to get around the Bloom filter saying that the key doesn't exist. @Override boolean bloomFilterMightContain(RandomAccessData keyBytes) { @@ -98,58 +225,94 @@ boolean bloomFilterMightContain(RandomAccessData keyBytes) { } }; - // Check that we got null with a key before all keys contained in the file. - assertNull(reader.get(new byte[]{ 0x02 })); - // Check that we got null with a key between two other keys contained in the file. - assertNull(reader.get(new byte[]{ 0x06 })); - // Check that we got null with a key that is after all keys contained in the file. - assertNull(reader.get(new byte[]{ 0x10 })); + // Check that we got false with a key before all keys contained in the file. + assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x02 })).hasNext()); + // Check that we got false with a key between two other keys contained in the file. + assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x06 })).hasNext()); + // Check that we got false with a key that is after all keys contained in the file. + assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x10 })).hasNext()); } - /** Write input elements to a file and return the file name. */ - static String initInputFile(Iterable> elements, File tmpFile) - throws Exception { - Sink>> sink = - new IsmSink(tmpFile.getPath(), ByteArrayCoder.of(), ByteArrayCoder.of()); + @Test + public void testReadKeyThatEncodesToEmptyByteArray() throws Exception { + File tmpFile = tmpFolder.newFile(); + IsmRecordCoder coder = IsmRecordCoder.of( + 1, 0, ImmutableList.>of(VoidCoder.of()), VoidCoder.of()); + IsmSink sink = new IsmSink<>( + tmpFile.getPath(), coder); + IsmRecord element = IsmRecord.of(Arrays.asList((Void) null), (Void) null); + try (SinkWriter>> writer = + sink.writer()) { + writer.add(valueInEmptyWindows(element)); + } + + Cache>>>> cache = + CacheBuilder + .newBuilder() + .weigher(Weighers.fixedWeightKeys(1)) + .maximumWeight(10_000) + .build(); + IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), coder, cache); + assertEquals(coder.structuralValue(element), + coder.structuralValue(reader.iterator().next().getValue())); + } - try (SinkWriter>> writer = sink.writer()) { - for (KV element : elements) { - writer.add(WindowedValue.valueInGlobalWindow(element)); + /** Write input elements to the specified file. */ + static void writeElementsToFile( + Iterable> elements, File tmpFile) throws Exception { + IsmSink sink = + new IsmSink(tmpFile.getPath(), CODER) { + @Override + long getBlockSize() { + return TEST_BLOCK_SIZE; + } + }; + + try (SinkWriter>> writer = + sink.writer()) { + for (IsmRecord element : elements) { + writer.add(valueInEmptyWindows(element)); } } - return tmpFile.getPath(); } /** - * Reads from a file generated from a collection of elements and verifies that the elements read - * are the same as the elements written. + * Writes elements to an Ism file using an IsmSink. Then reads them back with an IsmReader, + * verifying the values read match those that were written. */ - static void runTestRead(Iterable> expectedData, File tmpFile) + private void writeElementsToFileAndReadInOrder(Iterable> elements) throws Exception { - String filename = initInputFile(expectedData, tmpFile); - IsmReader reader = - new IsmReader<>(filename, ByteArrayCoder.of(), ByteArrayCoder.of()); + File tmpFile = tmpFolder.newFile(); + writeElementsToFile(elements, tmpFile); + IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), CODER, cache); TestReaderObserver observer = new TestReaderObserver(reader); reader.addObserver(observer); - Iterator> expectedIterator = expectedData.iterator(); - try (NativeReader.NativeReaderIterator> iterator = reader.iterator()) { - for (boolean more = iterator.start(); - more && expectedIterator.hasNext(); - more = iterator.advance()) { - KV actual = iterator.getCurrent(); - KV expectedNext = expectedIterator.next(); - assertArrayEquals(actual.getKey(), expectedNext.getKey()); - assertArrayEquals(actual.getValue(), expectedNext.getValue()); + Iterator> elementsIterator = elements.iterator(); + try (NativeReader.LegacyReaderIterator>> iterator = + reader.iterator()) { + + while (iterator.hasNext() && elementsIterator.hasNext()) { + IsmRecord expected = elementsIterator.next(); + IsmRecord actual = iterator.next().getValue(); + assertIsmEquals(actual, expected); + final int expectedLength; + if (IsmFormat.isMetadataKey(expected.getKeyComponents())) { + expectedLength = expected.getMetadata().length; + } else { + expectedLength = expected.getValue().length; + } // Verify that the observer saw at least as many bytes as the size of the value. - assertTrue(actual.getValue().length + assertTrue(expectedLength <= observer.getActualSizes().get(observer.getActualSizes().size() - 1)); + } if (iterator.advance()) { fail("Read more elements then expected, did not expect: " + iterator.getCurrent()); - } else if (expectedIterator.hasNext()) { - fail("Read less elements then expected, expected: " + expectedIterator.next()); + } else if (elementsIterator.hasNext()) { + fail("Read less elements then expected, expected: " + elementsIterator.next()); } // Verify that we see a {@link NoSuchElementException} if we attempt to go further. @@ -161,108 +324,260 @@ static void runTestRead(Iterable> expectedData, File tmpFile) } } - static class EvenFilter implements Predicate> { + private static void assertIsmEquals( + IsmRecord actual, + IsmRecord expected) { + assertEquals(expected.getKeyComponents().size(), actual.getKeyComponents().size()); + for (int i = 0; i < expected.getKeyComponents().size(); ++i) { + if (actual.getKeyComponent(i) != expected.getKeyComponent(i)) { + assertArrayEquals((byte[]) actual.getKeyComponent(i), (byte[]) expected.getKeyComponent(i)); + } + } + + if (IsmFormat.isMetadataKey(expected.getKeyComponents())) { + assertArrayEquals(actual.getMetadata(), expected.getMetadata()); + } else { + assertArrayEquals(actual.getValue(), expected.getValue()); + } + } + + /** + * A predicate which filters elements on whether the second key's last byte is odd or even. + * Allows for a stable partitioning of generated data. + */ + private static class EvenFilter implements Predicate> { private static final EvenFilter INSTANCE = new EvenFilter(); @Override - public boolean apply(KV input) { - return input.getValue()[input.getValue().length - 1] % 2 == 0; + public boolean apply(IsmRecord input) { + byte[] secondKey = (byte[]) input.getKeyComponent(1); + return secondKey[secondKey.length - 1] % 2 == 0; } } - static void runTestReadRandomOrder(Iterable> elements, File tmpFile) + /** + * Writes elements to an Ism file using an IsmSink. Then reads them back with an IsmReader + * using a random order. + */ + private void writeElementsToFileAndReadInRandomOrder(Iterable> elements) throws Exception { - Iterable> oddValues = + File tmpFile = tmpFolder.newFile(); + List> oddSecondaryKeys = new ArrayList<>( + ImmutableList.copyOf(Iterables.filter(elements, Predicates.not(EvenFilter.INSTANCE)))); + List> evenSecondaryKeys = new ArrayList<>( + ImmutableList.copyOf(Iterables.filter(elements, EvenFilter.INSTANCE))); + + writeElementsToFile(oddSecondaryKeys, tmpFile); + IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), CODER, cache); + + // Test using next() for a within shard Ism prefix reader iterator + Collections.shuffle(oddSecondaryKeys); + for (IsmRecord expectedNext : oddSecondaryKeys) { + assertIsmEquals(reader.overKeyComponents( + expectedNext.getKeyComponents()).next().getValue(), expectedNext); + } + + Collections.shuffle(oddSecondaryKeys); + // Test using get() for a shard aware Ism prefix reader + IsmReader.IsmPrefixReaderIterator readerIterator = + reader.overKeyComponents(ImmutableList.of()); + for (IsmRecord expectedNext : oddSecondaryKeys) { + assertIsmEquals(readerIterator.get(expectedNext.getKeyComponents()).getValue(), expectedNext); + } + + // Test using next() for a within shard Ism prefix reader iterator + Collections.shuffle(evenSecondaryKeys); + for (IsmRecord missingNext : evenSecondaryKeys) { + assertFalse(reader.overKeyComponents(missingNext.getKeyComponents()).hasNext()); + } + + Collections.shuffle(evenSecondaryKeys); + // Test using get() for a shard aware Ism prefix reader + readerIterator = reader.overKeyComponents(ImmutableList.of()); + for (IsmRecord missingNext : evenSecondaryKeys) { + assertNull(readerIterator.get(missingNext.getKeyComponents())); + } + } + + private void writeElementsToFileAndFindLastElementPerPrimaryKey( + Iterable> elements) throws Exception { + File tmpFile = tmpFolder.newFile(); + Iterable> oddValues = Iterables.filter(elements, Predicates.not(EvenFilter.INSTANCE)); - Iterable> evenValues = + Iterable> evenValues = Iterables.filter(elements, EvenFilter.INSTANCE); + writeElementsToFile(oddValues, tmpFile); + IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), CODER, cache); - String filename = initInputFile(oddValues, tmpFile); - IsmReader reader = - new IsmReader<>(filename, ByteArrayCoder.of(), ByteArrayCoder.of()); - TestReaderObserver observer = new TestReaderObserver(reader); - reader.addObserver(observer); + SortedMap>> sortedBySecondKey = + new TreeMap<>(UnsignedBytes.lexicographicalComparator()); + for (IsmRecord element : oddValues) { + byte[] encodedPrimaryKey = + CoderUtils.encodeToByteArray(CODER.getKeyComponentCoder(0), element.getKeyComponent(0)); + if (!sortedBySecondKey.containsKey(encodedPrimaryKey)) { + sortedBySecondKey.put( + encodedPrimaryKey, new TreeSet<>(new IsmRecordKeyComparator<>(CODER))); + } + sortedBySecondKey.get(encodedPrimaryKey).add(element); + } - Iterator> expectedIterator = oddValues.iterator(); - while (expectedIterator.hasNext()) { - KV expectedNext = expectedIterator.next(); - KV actual = reader.get(expectedNext.getKey()); - assertArrayEquals(actual.getValue(), expectedNext.getValue()); + // The returned value should have the element as a prefix of itself. + for (IsmRecord element : oddValues) { + byte[] encodedPrimaryKey = + CoderUtils.encodeToByteArray(CODER.getKeyComponentCoder(0), element.getKeyComponent(0)); + assertIsmEquals( + reader.overKeyComponents( + ImmutableList.of(element.getKeyComponent(0))).getLast().getValue(), + sortedBySecondKey.get(encodedPrimaryKey).last()); + } + + // The returned value should always have the element as a prefix of itself or not exist. + for (IsmRecord element : evenValues) { + byte[] encodedPrimaryKey = + CoderUtils.encodeToByteArray(CODER.getKeyComponentCoder(0), element.getKeyComponent(0)); + IsmReader.IsmPrefixReaderIterator readerIterator = + reader.overKeyComponents(ImmutableList.of(element.getKeyComponent(0))); + WindowedValue> lastWindowedValue = readerIterator.getLast(); + if (lastWindowedValue != null) { + assertIsmEquals( + lastWindowedValue.getValue(), + sortedBySecondKey.get(encodedPrimaryKey).last()); + } + } + } - // Verify that the observer saw at least as many bytes as the size of the value. - List actualSizes = observer.getActualSizes(); - assertTrue(actual.getValue().length <= actualSizes.get(actualSizes.size() - 1)); + static class IsmRecordKeyComparator implements Comparator> { + private final IsmRecordCoder coder; + IsmRecordKeyComparator(IsmRecordCoder coder) { + this.coder = coder; } - Iterator> missingIterator = evenValues.iterator(); - while (missingIterator.hasNext()) { - KV missingNext = missingIterator.next(); - assertNull(reader.get(missingNext.getKey())); + @Override + public int compare(IsmRecord first, IsmRecord second) { + RandomAccessData firstKeyBytes = new RandomAccessData(); + coder.encodeAndHash(first.getKeyComponents(), firstKeyBytes); + RandomAccessData secondKeyBytes = new RandomAccessData(); + coder.encodeAndHash(second.getKeyComponents(), secondKeyBytes); + return RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( + firstKeyBytes, secondKeyBytes); } } - // Creates an iterable with key bytes in ascending order. - static Iterable> dataGenerator( - final int numberOfKeys, final int approximateKeySize, final int maxValueSize) { - final int minimumNumberOfKeyBytes = 4; - return new Iterable>() { - @Override - public Iterator> iterator() { - final Random random = new Random(numberOfKeys); - return new Iterator>() { - int current; - byte[] previousKey = new byte[random.nextInt(approximateKeySize) - + minimumNumberOfKeyBytes]; - { - // Generate a random key with enough space at the front for 2^32 values. - random.nextBytes(previousKey); - previousKey[0] = 0; - previousKey[1] = 0; - previousKey[2] = 0; - previousKey[3] = 0; - } + /** + * Specifies the minimum key size so that we can produce a random byte array + * with enough of a prefix to be able to create successively larger secondary keys. + */ + private static final int MIN_KEY_SIZE = 4; - @Override - public boolean hasNext() { - return current < numberOfKeys; - } + /** Specifies the percentage of keys that are metadata records when using the data generator. */ + private static final double PERCENT_METADATA_RECORDS = 0.01; - @Override - public KV next() { - current += 1; - byte[] currentKey = new byte[random.nextInt(approximateKeySize) - + minimumNumberOfKeyBytes]; - int matchingPrefix = Math.min(currentKey.length, - random.nextInt(approximateKeySize) + minimumNumberOfKeyBytes); - byte[] randomSuffix = new byte[currentKey.length - matchingPrefix]; - random.nextBytes(randomSuffix); - - System.arraycopy(previousKey, 0, - currentKey, 0, Math.min(currentKey.length, previousKey.length)); - System.arraycopy(randomSuffix, 0, currentKey, matchingPrefix, randomSuffix.length); - - matchingPrefix -= 1; - // Find the first byte which is less than 255 at the end of the matching portion. - while ((currentKey[matchingPrefix] & 0xFF) == 0xFF) { - currentKey[matchingPrefix] = 0; - matchingPrefix -= 1; - } - // Increment the last byte of the matching prefix to make sure this key is - // larger than the previous key. - currentKey[matchingPrefix] = (byte) ((currentKey[matchingPrefix] & 0xFF) + 1); - - byte[] value = new byte[random.nextInt(maxValueSize) + 1]; - random.nextBytes(value); - previousKey = currentKey; - return KV.of(currentKey, value); - } + /** + * Creates a map from Ism shard to a sorted set of IsmRecords. + */ + private Map>> dataGeneratorPerShard( + final int numberOfPrimaryKeys, + final int minNumberOfSecondaryKeys, + final int maxKeySize, + final int maxValueSize) { + checkState(maxKeySize >= MIN_KEY_SIZE); - @Override - public void remove() { - throw new UnsupportedOperationException(); + final Random random = new Random(minNumberOfSecondaryKeys); + + Map>> shardToRecordMap = new HashMap<>(); + while (shardToRecordMap.keySet().size() < numberOfPrimaryKeys) { + // Generate the next primary key + byte[] primaryKey = new byte[random.nextInt(maxKeySize - MIN_KEY_SIZE) + MIN_KEY_SIZE]; + random.nextBytes(primaryKey); + int shardId = CODER.hash(ImmutableList.of(primaryKey)); + // Add a sorted set for the shard id if this shard id has never been generated before. + if (!shardToRecordMap.containsKey(shardId)) { + shardToRecordMap.put(shardId, + new TreeSet>(new IsmRecordKeyComparator(CODER))); + } + + // Generate the requested number of secondary keys using the newly generated primary key. + byte[] secondaryKey = new byte[maxKeySize]; + for (int j = 0; j < minNumberOfSecondaryKeys; ++j) { + secondaryKey = generateNextSecondaryKey(random, maxKeySize, secondaryKey); + + // Generate the value bytes. + byte[] value = new byte[random.nextInt(maxValueSize)]; + random.nextBytes(value); + + // 1% of keys are metadata records + if (random.nextFloat() < PERCENT_METADATA_RECORDS) { + IsmRecord ismRecord = IsmRecord.meta( + ImmutableList.of(IsmFormat.getMetadataKey(), secondaryKey), value); + int metadataShardId = CODER.hash(ismRecord.getKeyComponents()); + // Add a sorted set for the shard id if this shard id has never been generated before. + if (!shardToRecordMap.containsKey(metadataShardId)) { + shardToRecordMap.put(metadataShardId, + new TreeSet>( + new IsmRecordKeyComparator(CODER))); } - }; + shardToRecordMap.get(metadataShardId).add(ismRecord); + } else { + IsmRecord ismRecord = IsmRecord.of( + ImmutableList.of(primaryKey, secondaryKey), + value); + shardToRecordMap.get(shardId).add(ismRecord); + } } - }; + } + return shardToRecordMap; + } + + private byte[] generateNextSecondaryKey( + Random random, int maxKeySize, byte[] previousSecondaryKey) { + byte[] currentSecondaryKey = + new byte[random.nextInt(maxKeySize - MIN_KEY_SIZE) + MIN_KEY_SIZE]; + int matchingPrefix = Math.min(currentSecondaryKey.length, + random.nextInt(maxKeySize - MIN_KEY_SIZE) + MIN_KEY_SIZE); + byte[] randomSuffix = new byte[currentSecondaryKey.length - matchingPrefix]; + random.nextBytes(randomSuffix); + + System.arraycopy(previousSecondaryKey, 0, + currentSecondaryKey, 0, + Math.min(currentSecondaryKey.length, previousSecondaryKey.length)); + System.arraycopy(randomSuffix, 0, + currentSecondaryKey, matchingPrefix, randomSuffix.length); + + matchingPrefix -= 1; + // Find the first byte which is less than 255 at the end of the matching portion. + while ((currentSecondaryKey[matchingPrefix] & 0xFF) == 0xFF) { + currentSecondaryKey[matchingPrefix] = 0; + matchingPrefix -= 1; + } + // Increment the last byte of the matching prefix to make sure this key is + // larger than the previous key. + currentSecondaryKey[matchingPrefix] = + (byte) ((currentSecondaryKey[matchingPrefix] & 0xFF) + 1); + return currentSecondaryKey; + } + + /** + * Creates an iterable of IsmRecords grouped by shard id, and in ascending order per shard. + */ + private Iterable> dataGenerator( + final int numberOfPrimaryKeys, + final int numberOfSecondaryKeys, + final int approximateKeySize, + final int maxValueSize) { + + FluentIterable> records = FluentIterable + .from(dataGeneratorPerShard( + numberOfPrimaryKeys, numberOfSecondaryKeys, + approximateKeySize, maxValueSize).entrySet()) + .transformAndConcat( + new Function>>, + Iterable>>() { + @Override + public Iterable> apply( + Entry>> input) { + return input.getValue(); + } + }); + return records; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java index 621305912b..d8e3502a74 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java @@ -15,10 +15,17 @@ */ package com.google.cloud.dataflow.sdk.runners.worker; +import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; + import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; +import com.google.cloud.dataflow.sdk.testing.CoderPropertiesTest.NonDeterministicCoder; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.worker.Sink.SinkWriter; -import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.collect.ImmutableList; import org.junit.Rule; import org.junit.Test; @@ -27,64 +34,104 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.Arrays; -import java.util.Random; - /** * Tests for {@link IsmSink}. - * Note that {@link IsmReaderTest} covers reading/writing tests. This tests + * + *

    Note that {@link IsmReaderTest} covers reading/writing tests. This tests * error cases for the {@link IsmSink}. */ @RunWith(JUnit4.class) public class IsmSinkTest { + private static final IsmRecordCoder CODER = + IsmRecordCoder.of( + 1, // number or shard key coders for value records + 1, // number of shard key coders for metadata records + ImmutableList.>of(MetadataKeyCoder.of(ByteArrayCoder.of()), ByteArrayCoder.of()), + ByteArrayCoder.of()); + private static final byte[] EMPTY = new byte[0]; + private static final Coder NON_DETERMINISTIC_CODER = new NonDeterministicCoder(); + + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Test - public void testWriteOutOfOrderKeysIsError() throws Exception { - IsmSink sink = - new IsmSink<>(tmpFolder.newFile().getPath(), ByteArrayCoder.of(), ByteArrayCoder.of()); - SinkWriter>> sinkWriter = sink.writer(); - sinkWriter.add(WindowedValue.valueInGlobalWindow(KV.of(new byte[]{ 0x01 }, new byte[0]))); + public void testWriteOutOfOrderKeysWithSameShardKeyIsError() throws Throwable { + IsmSink sink = + new IsmSink<>(tmpFolder.newFile().getPath(), CODER); + SinkWriter>> sinkWriter = sink.writer(); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x01 }), EMPTY))); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("expects keys to be written in strictly increasing order"); - sinkWriter.add(WindowedValue.valueInGlobalWindow(KV.of(new byte[]{ 0x00 }, new byte[0]))); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x00 }), EMPTY))); + } + + @Test + public void testWriteNonContiguousShardsIsError() throws Throwable { + IsmSink sink = + new IsmSink<>(tmpFolder.newFile().getPath(), CODER); + SinkWriter>> sinkWriter = sink.writer(); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(new byte[]{ 0x00 }, EMPTY), EMPTY))); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(new byte[]{ 0x01 }, EMPTY), EMPTY))); + + expectedException.expect(IllegalStateException.class); + expectedException.expectMessage("for shard which already exists"); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(new byte[]{ 0x00 }, EMPTY), EMPTY))); } @Test - public void testWriteEqualsKeysIsError() throws Exception { - IsmSink sink = - new IsmSink<>(tmpFolder.newFile().getPath(), ByteArrayCoder.of(), ByteArrayCoder.of()); - SinkWriter>> sinkWriter = sink.writer(); - sinkWriter.add(WindowedValue.valueInGlobalWindow(KV.of(new byte[]{ 0x00 }, new byte[0]))); + public void testWriteEqualKeysIsError() throws Throwable { + IsmSink sink = + new IsmSink<>(tmpFolder.newFile().getPath(), CODER); + SinkWriter>> sinkWriter = sink.writer(); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x01 }), EMPTY))); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("expects keys to be written in strictly increasing order"); - sinkWriter.add(WindowedValue.valueInGlobalWindow(KV.of(new byte[]{ 0x00 }, new byte[0]))); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x01 }), EMPTY))); } @Test - public void testWriteKeyWhichIsProperPrefixOfPreviousKeyIsError() throws Exception { - IsmSink sink = - new IsmSink<>(tmpFolder.newFile().getPath(), ByteArrayCoder.of(), ByteArrayCoder.of()); - SinkWriter>> sinkWriter = sink.writer(); - sinkWriter.add(WindowedValue.valueInGlobalWindow(KV.of(new byte[]{ 0x00, 0x00 }, new byte[0]))); + public void testWriteKeyWhichIsProperPrefixOfPreviousSecondaryKeyIsError() throws Throwable { + IsmSink sink = + new IsmSink<>(tmpFolder.newFile().getPath(), CODER); + SinkWriter>> sinkWriter = sink.writer(); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x00, 0x00 }), EMPTY))); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("expects keys to be written in strictly increasing order"); - sinkWriter.add(WindowedValue.valueInGlobalWindow(KV.of(new byte[]{ 0x00 }, new byte[0]))); + sinkWriter.add(valueInEmptyWindows( + IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x00 }), EMPTY))); } @Test - public void testWrite() throws Exception { - Random random = new Random(23498321490L); - for (int i : Arrays.asList(4, 8, 12)) { - int minElements = (int) Math.pow(2, i); - // Generates between 2^i and 2^(i + 1) elements. - IsmReaderTest.runTestRead( - IsmReaderTest.dataGenerator(minElements + random.nextInt(minElements), - 8 /* approximate key size */, 8 /* max value size */), tmpFolder.newFile()); - } + public void testUsingNonDeterministicShardKeyCoder() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("is expected to be deterministic"); + new IsmSink<>(tmpFolder.newFile().getPath(), IsmRecordCoder.of( + 1, + 0, + ImmutableList.>of(NON_DETERMINISTIC_CODER, ByteArrayCoder.of()), + ByteArrayCoder.of())); + } + + @Test + public void testUsingNonDeterministicNonShardKeyCoder() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("is expected to be deterministic"); + new IsmSink<>(tmpFolder.newFile().getPath(), IsmRecordCoder.of( + 1, + 0, + ImmutableList.>of(ByteArrayCoder.of(), NON_DETERMINISTIC_CODER), + ByteArrayCoder.of())); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java index f0fe688459..4564d95fc3 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java @@ -47,7 +47,7 @@ public void testGoodCoderIsDeterministic() throws Exception { } /** A coder that says it is not deterministic but actually is. */ - private static class NonDeterministicCoder extends CustomCoder { + public static class NonDeterministicCoder extends CustomCoder { @Override public void encode(String value, OutputStream outStream, Context context) throws CoderException, IOException { From bee2bb381cebf2da24c30741152559d8158adf10 Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 4 Feb 2016 12:31:04 -0800 Subject: [PATCH 079/751] Always explicitly pass ReaderRegistry to MapTaskExecutorFactory This breaks the dependency between MapTaskExecutorFactory and the default registry (and thence to all implementations of ReaderFactory). While the convenience method removed is reasonable, it is used so infrequently it does not seem important, and the dependency removal is a bigger win. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113877516 --- .../worker/MapTaskExecutorFactory.java | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java index 420be59de7..f95d7f7807 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java @@ -80,25 +80,6 @@ */ public class MapTaskExecutorFactory { - /** - * Creates a new MapTaskExecutor from the given MapTask definition using the default - * {@link ReaderRegistry}. - */ - public static MapTaskExecutor create( - PipelineOptions options, - MapTask mapTask, - DataflowExecutionContext context, - CounterSet counters, - StateSampler stateSampler) throws Exception { - return create( - options, - mapTask, - ReaderRegistry.defaultRegistry(), - context, - counters, - stateSampler); - } - /** * Creates a new MapTaskExecutor from the given MapTask definition using the provided * {@link ReaderRegistry}. From 97b9ed31a2383f51a63ef04d68254b58bfefd43a Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 4 Feb 2016 12:32:38 -0800 Subject: [PATCH 080/751] Move worker tests to worker maven module This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113877653 --- .../runners/worker/AvroByteReaderTest.java | 306 ------ .../sdk/runners/worker/AvroByteSinkTest.java | 88 -- .../runners/worker/AvroReaderFactoryTest.java | 120 --- .../sdk/runners/worker/AvroReaderTest.java | 343 ------- .../runners/worker/AvroSinkFactoryTest.java | 86 -- .../sdk/runners/worker/AvroSinkTest.java | 88 -- .../worker/BigQueryReaderFactoryTest.java | 106 -- .../runners/worker/BigQueryReaderTest.java | 910 ----------------- .../worker/CachingSideInputReaderTest.java | 199 ---- .../runners/worker/CombineValuesFnTest.java | 350 ------- .../worker/ConcatReaderFactoryTest.java | 124 --- .../sdk/runners/worker/ConcatReaderTest.java | 471 --------- .../CopyableSeekableByteChannelTest.java | 153 --- .../worker/DataflowSideInputReaderTest.java | 229 ----- .../runners/worker/DatastoreReaderTest.java | 200 ---- .../worker/DefaultParDoFnFactoryTest.java | 172 ---- .../runners/worker/FakeWindmillServer.java | 152 --- .../GroupingShuffleRangeTrackerTest.java | 177 ---- .../worker/GroupingShuffleReaderTest.java | 709 ------------- .../worker/InMemoryReaderFactoryTest.java | 99 -- .../runners/worker/InMemoryReaderTest.java | 291 ------ .../sdk/runners/worker/IsmFormatTest.java | 328 ------ .../sdk/runners/worker/IsmReaderTest.java | 583 ----------- .../sdk/runners/worker/IsmSinkTest.java | 137 --- .../worker/KeyTokenInvalidExceptionTest.java | 37 - .../runners/worker/KeyedWorkItemsTest.java | 155 --- .../worker/MapTaskExecutorFactoryTest.java | 636 ------------ .../sdk/runners/worker/NormalParDoFnTest.java | 371 ------- .../sdk/runners/worker/OrderedCodeTest.java | 504 --------- .../worker/PartitioningShuffleReaderTest.java | 138 --- .../sdk/runners/worker/ReaderFactoryTest.java | 184 ---- .../sdk/runners/worker/ReaderTestUtils.java | 149 --- .../worker/ShuffleReaderFactoryTest.java | 202 ---- .../worker/ShuffleSinkFactoryTest.java | 195 ---- .../sdk/runners/worker/ShuffleSinkTest.java | 251 ----- .../runners/worker/SideInputUtilsTest.java | 125 --- .../sdk/runners/worker/SinkFactoryTest.java | 138 --- .../sdk/runners/worker/StateFetcherTest.java | 227 ----- .../StreamingGroupAlsoByWindowsDoFnTest.java | 576 ----------- ...ngGroupAlsoByWindowsReshuffleDoFnTest.java | 219 ---- .../StreamingModeExecutionContextTest.java | 189 ---- .../StreamingSideInputDoFnRunnerTest.java | 321 ------ .../sdk/runners/worker/TestShuffleReader.java | 204 ---- .../runners/worker/TestShuffleReaderTest.java | 143 --- .../sdk/runners/worker/TestShuffleWriter.java | 68 -- .../runners/worker/TextReaderFactoryTest.java | 98 -- .../sdk/runners/worker/TextReaderTest.java | 804 --------------- .../runners/worker/TextSinkFactoryTest.java | 105 -- .../sdk/runners/worker/TextSinkTest.java | 215 ---- .../worker/UngroupedShuffleReaderTest.java | 127 --- .../worker/UserCodeTimeTrackerTest.java | 120 --- .../worker/WeightedDirectSideInputReader.java | 76 -- .../WindmillReaderIteratorBaseTest.java | 97 -- .../worker/WindmillStateCacheTest.java | 210 ---- .../worker/WindmillStateInternalsTest.java | 963 ------------------ .../worker/WindmillStateReaderTest.java | 411 -------- .../worker/WorkerCustomSourcesTest.java | 749 -------------- .../BatchingShuffleEntryReaderTest.java | 138 --- .../worker/CachingShuffleBatchReaderTest.java | 95 -- .../util/common/worker/ExecutorTestUtils.java | 180 ---- .../common/worker/FlattenOperationTest.java | 80 -- .../common/worker/MapTaskExecutorTest.java | 264 ----- .../OutputObjectAndByteCounterTest.java | 128 --- .../common/worker/OutputReceiverTest.java | 73 -- .../common/worker/ParDoOperationTest.java | 117 --- .../PartialGroupByKeyOperationTest.java | 515 ---------- .../util/common/worker/ReadOperationTest.java | 414 -------- .../util/common/worker/ShuffleEntryTest.java | 145 --- .../util/common/worker/StateSamplerTest.java | 197 ---- .../common/worker/TestOutputReceiver.java | 117 --- .../util/common/worker/WorkExecutorTest.java | 57 -- .../common/worker/WriteOperationTest.java | 74 -- 72 files changed, 18022 deletions(-) delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannelTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DatastoreReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/FakeWindmillServer.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTrackerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCodeTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcherTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleWriter.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTrackerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WeightedDirectSideInputReader.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperationTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounterTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiverTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperationTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSamplerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/TestOutputReceiver.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperationTest.java diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java deleted file mode 100644 index babd10a7fd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReaderTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readNItemsFromUnstartedIterator; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readRemainingFromIterator; - -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.DynamicSplitResult; - -import org.apache.avro.Schema; -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.generic.GenericDatumWriter; -import org.apache.avro.io.DatumWriter; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import javax.annotation.Nullable; - -/** - * Tests for AvroByteReader. - */ -@RunWith(JUnit4.class) -public class AvroByteReaderTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - /** Class representing information about an Avro file generated from a list of elements. */ - private static class AvroFileInfo { - String filename; - List elementSizes = new ArrayList<>(); - List syncPoints = new ArrayList<>(); - long totalElementEncodedSize = 0; - } - - /** Write input elements to a file and return information about the Avro-encoded file. */ - private AvroFileInfo initInputFile(List> elemsList, Coder coder) - throws Exception { - File tmpFile = tmpFolder.newFile("file.avro"); - AvroFileInfo fileInfo = new AvroFileInfo<>(); - fileInfo.filename = tmpFile.getPath(); - - // Write the data. - OutputStream outStream = - Channels.newOutputStream(IOChannelUtils.create(fileInfo.filename, MimeTypes.BINARY)); - Schema schema = Schema.create(Schema.Type.BYTES); - DatumWriter datumWriter = new GenericDatumWriter<>(schema); - try (DataFileWriter fileWriter = new DataFileWriter<>(datumWriter)) { - fileWriter.create(schema, outStream); - boolean first = true; - for (List elems : elemsList) { - if (first) { - first = false; - } else { - // Ensure a block boundary here. - long syncPoint = fileWriter.sync(); - fileInfo.syncPoints.add(syncPoint); - } - for (T elem : elems) { - byte[] encodedElement = CoderUtils.encodeToByteArray(coder, elem); - fileWriter.append(ByteBuffer.wrap(encodedElement)); - fileInfo.elementSizes.add(encodedElement.length); - fileInfo.totalElementEncodedSize += encodedElement.length; - } - } - } - - return fileInfo; - } - - - /** - * Reads from a file generated from a collection of elements and verifies that the elements read - * are the same as the elements written. - * - * @param elemsList a list of blocks of elements, each of which is as a list of elements. - * @param coder the coder used to encode the elements - * @param requireExactMatch if true, each block must match exactly - * @throws Exception - */ - private void runTestRead(List> elemsList, Coder coder, boolean requireExactMatch) - throws Exception { - AvroFileInfo fileInfo = initInputFile(elemsList, coder); - - // Test reading the data back. - List> actualElemsList = new ArrayList<>(); - List actualSizes = new ArrayList<>(); - Long startOffset = null; - Long endOffset; - long prevSyncPoint = 0; - for (long syncPoint : fileInfo.syncPoints) { - endOffset = (prevSyncPoint + syncPoint) / 2; - actualElemsList.add(readElems(fileInfo.filename, startOffset, endOffset, coder, actualSizes)); - startOffset = endOffset; - prevSyncPoint = syncPoint; - } - actualElemsList.add(readElems(fileInfo.filename, startOffset, null, coder, actualSizes)); - - // Compare the expected and the actual elements. - if (requireExactMatch) { - // Require the blocks to match exactly. (This works only for - // small block sizes. Large block sizes, bigger than Avro's - // internal sizes, lead to different splits.) - Assert.assertEquals(elemsList, actualElemsList); - } else { - // Just require the overall elements to be the same. (This - // works for any block size.) - List expected = new ArrayList<>(); - for (List elems : elemsList) { - expected.addAll(elems); - } - List actual = new ArrayList<>(); - for (List actualElems : actualElemsList) { - actual.addAll(actualElems); - } - Assert.assertEquals(expected, actual); - } - - long actualTotalSize = 0; - for (int elemSize : actualSizes) { - actualTotalSize += elemSize; - } - Assert.assertEquals(fileInfo.totalElementEncodedSize, actualTotalSize); - } - - private List readElems(String filename, @Nullable Long startOffset, - @Nullable Long endOffset, Coder coder, List actualSizes) throws Exception { - AvroByteReader avroReader = - new AvroByteReader<>(filename, startOffset, endOffset, coder, null); - new ExecutorTestUtils.TestReaderObserver(avroReader, actualSizes); - return readAllFromReader(avroReader); - } - - @Test - public void testRead() throws Exception { - runTestRead(Collections.singletonList(TestUtils.INTS), BigEndianIntegerCoder.of(), - true/* require exact match */); - } - - @Test - public void testReadEmpty() throws Exception { - runTestRead(Collections.singletonList(TestUtils.NO_INTS), BigEndianIntegerCoder.of(), - true/* require exact match */); - } - - private List> generateInputBlocks( - int numBlocks, int blockSizeBytes, int averageLineSizeBytes) { - Random random = new Random(0); - List> blocks = new ArrayList<>(numBlocks); - for (int blockNum = 0; blockNum < numBlocks; blockNum++) { - int numLines = blockSizeBytes / averageLineSizeBytes; - List lines = new ArrayList<>(numLines); - for (int lineNum = 0; lineNum < numLines; lineNum++) { - int numChars = random.nextInt(averageLineSizeBytes * 2); - StringBuilder sb = new StringBuilder(); - for (int charNum = 0; charNum < numChars; charNum++) { - sb.appendCodePoint(random.nextInt('z' - 'a' + 1) + 'a'); - } - lines.add(sb.toString()); - } - blocks.add(lines); - } - return blocks; - } - - @Test - public void testReadSmallRanges() throws Exception { - runTestRead(generateInputBlocks(3, 50, 5), StringUtf8Coder.of(), true/* require exact match */); - } - - @Test - public void testReadBigRanges() throws Exception { - runTestRead(generateInputBlocks(10, 128 * 1024, 100), StringUtf8Coder.of(), - false/* don't require exact match */); - } - - // Verification behavior for split requests. Used for testRequestDynamicSplitInternal. - private static enum SplitVerificationBehavior { - VERIFY_SUCCESS, // Split request must succeed. - VERIFY_FAILURE, // Split request must fail. - DO_NOT_VERIFY; // Perform no verification. - } - - private void testRequestDynamicSplitInternal( - AvroByteReader reader, - float splitAtFraction, - int readBeforeSplit, - SplitVerificationBehavior splitVerificationBehavior) - throws Exception { - // Read all elements from the reader - Long endOffset = reader.avroReader.endPosition; - List expectedElements = readAllFromReader(reader); - - List primaryElements; - List residualElements = new ArrayList<>(); - try (AvroByteReader.AvroByteFileIterator iterator = reader.iterator()) { - // Read n elements from the reader - primaryElements = readNItemsFromUnstartedIterator(iterator, readBeforeSplit); - - // Request a split at the specified position - DynamicSplitResult splitResult = - iterator.requestDynamicSplit(ReaderTestUtils.splitRequestAtFraction(splitAtFraction)); - - switch (splitVerificationBehavior) { - case VERIFY_SUCCESS: - Assert.assertNotNull(splitResult); - break; - case VERIFY_FAILURE: - Assert.assertNull(splitResult); - break; - case DO_NOT_VERIFY: - } - - // Finish reading from the original reader. - primaryElements.addAll(readRemainingFromIterator(iterator, readBeforeSplit > 0)); - - if (splitResult != null) { - Long splitPosition = ReaderTestUtils.positionFromSplitResult(splitResult).getByteOffset(); - AvroByteReader residualReader = - new AvroByteReader(reader.avroReader.avroSource.getFileOrPatternSpec(), - splitPosition, endOffset, reader.coder, reader.avroReader.options); - // Read from the residual until it is complete. - residualElements = readAllFromReader(residualReader); - } - } - - primaryElements.addAll(residualElements); - Assert.assertEquals(expectedElements, primaryElements); - if (splitVerificationBehavior == SplitVerificationBehavior.VERIFY_SUCCESS) { - Assert.assertNotEquals(0, residualElements.size()); - } - } - - @Test - public void testRequestDynamicSplit() throws Exception { - // Note that exhaustive tests for AvroSource's split behavior exist in {@link AvroSourceTest}. - List> elements = generateInputBlocks(10, 100 * 100, 100); - Coder coder = StringUtf8Coder.of(); - AvroFileInfo fileInfo = initInputFile(elements, coder); - AvroByteReader reader = - new AvroByteReader(fileInfo.filename, null, null, coder, null); - // Read most of the records before the proposed split point. - testRequestDynamicSplitInternal(reader, 0.5F, 490, SplitVerificationBehavior.VERIFY_SUCCESS); - // Read a single record. - testRequestDynamicSplitInternal(reader, 0.5F, 1, SplitVerificationBehavior.VERIFY_SUCCESS); - // Read zero records. - testRequestDynamicSplitInternal(reader, 0.5F, 0, SplitVerificationBehavior.VERIFY_FAILURE); - // Read almost the entire input. - testRequestDynamicSplitInternal(reader, 0.5F, 900, SplitVerificationBehavior.VERIFY_FAILURE); - // Read the entire input. - testRequestDynamicSplitInternal(reader, 0.5F, 2000, SplitVerificationBehavior.VERIFY_FAILURE); - } - - @Test - public void testRequestDynamicSplitExhaustive() throws Exception { - List> elements = generateInputBlocks(5, 10 * 10, 10); - Coder coder = StringUtf8Coder.of(); - AvroFileInfo fileInfo = initInputFile(elements, coder); - AvroByteReader reader = - new AvroByteReader(fileInfo.filename, null, null, coder, null); - for (float splitFraction = 0.0F; splitFraction < 1.0F; splitFraction += 0.02F) { - for (int recordsToRead = 0; recordsToRead <= 500; recordsToRead += 5) { - testRequestDynamicSplitInternal( - reader, splitFraction, recordsToRead, SplitVerificationBehavior.DO_NOT_VERIFY); - } - } - } - - // TODO: sharded filenames - // TODO: reading from GCS -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java deleted file mode 100644 index 9f1a4eacc5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSinkTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; - -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for AvroByteSink. - */ -@RunWith(JUnit4.class) -public class AvroByteSinkTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - void runTestWriteFile(List elems, Coder coder) throws Exception { - File tmpFile = tmpFolder.newFile("file.avro"); - String filename = tmpFile.getPath(); - - // Write the file. - - AvroByteSink avroSink = new AvroByteSink<>(filename, coder); - List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter writer = avroSink.writer()) { - for (T elem : elems) { - actualSizes.add(writer.add(elem)); - } - } - - // Read back the file. - AvroByteReader reader = new AvroByteReader<>(filename, null, null, coder, null); - - - List actual = readAllFromReader(reader); - List expectedSizes = new ArrayList<>(); - - for (T value : actual) { - expectedSizes.add((long) CoderUtils.encodeToByteArray(coder, value).length); - } - - // Compare the expected and the actual elements. - Assert.assertEquals(elems, actual); - Assert.assertEquals(expectedSizes, actualSizes); - } - - @Test - public void testWriteFile() throws Exception { - runTestWriteFile(TestUtils.INTS, BigEndianIntegerCoder.of()); - } - - @Test - public void testWriteEmptyFile() throws Exception { - runTestWriteFile(TestUtils.NO_INTS, BigEndianIntegerCoder.of()); - } - - // TODO: sharded filenames - // TODO: writing to GCS -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java deleted file mode 100644 index 2a7b7e18bb..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactoryTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import javax.annotation.Nullable; - -/** - * Tests for AvroReaderFactory. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("rawtypes") -public class AvroReaderFactoryTest { - private final String pathToAvroFile = "/path/to/file.avro"; - - NativeReader runTestCreateAvroReader( - String filename, @Nullable Long start, @Nullable Long end, CloudObject encoding) - throws Exception { - CloudObject spec = CloudObject.forClassName("AvroSource"); - addString(spec, "filename", filename); - if (start != null) { - addLong(spec, "start_offset", start); - } - if (end != null) { - addLong(spec, "end_offset", end); - } - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(encoding); - - NativeReader reader = - ReaderRegistry.defaultRegistry() - .create( - cloudSource, - PipelineOptionsFactory.create(), - DirectModeExecutionContext.create(), - null, - null); - return reader; - } - - @Test - public void testCreatePlainAvroByteReader() throws Exception { - Coder coder = WindowedValue.getFullCoder( - BigEndianIntegerCoder.of(), GlobalWindow.Coder.INSTANCE); - NativeReader reader = - runTestCreateAvroReader(pathToAvroFile, null, null, coder.asCloudObject()); - - Assert.assertThat(reader, new IsInstanceOf(AvroByteReader.class)); - AvroByteReader avroReader = (AvroByteReader) reader; - Assert.assertEquals(pathToAvroFile, avroReader.avroReader.avroSource.getFileOrPatternSpec()); - Assert.assertEquals(null, avroReader.avroReader.startPosition); - Assert.assertEquals(null, avroReader.avroReader.endPosition); - Assert.assertEquals(coder, avroReader.coder); - } - - @Test - public void testCreateRichAvroByteReader() throws Exception { - Coder coder = WindowedValue.getFullCoder( - BigEndianIntegerCoder.of(), GlobalWindow.Coder.INSTANCE); - NativeReader reader = - runTestCreateAvroReader(pathToAvroFile, 200L, 500L, coder.asCloudObject()); - - Assert.assertThat(reader, new IsInstanceOf(AvroByteReader.class)); - AvroByteReader avroReader = (AvroByteReader) reader; - Assert.assertEquals(pathToAvroFile, avroReader.avroReader.avroSource.getFileOrPatternSpec()); - Assert.assertEquals(200L, (long) avroReader.avroReader.startPosition); - Assert.assertEquals(500L, (long) avroReader.avroReader.endPosition); - Assert.assertEquals(coder, avroReader.coder); - } - - @Test - public void testCreateRichAvroReader() throws Exception { - WindowedValue.WindowedValueCoder coder = - WindowedValue.getValueOnlyCoder(AvroCoder.of(Integer.class)); - NativeReader reader = - runTestCreateAvroReader(pathToAvroFile, 200L, 500L, coder.asCloudObject()); - - Assert.assertThat(reader, new IsInstanceOf(AvroReader.class)); - AvroReader avroReader = (AvroReader) reader; - Assert.assertEquals(pathToAvroFile, avroReader.avroSource.getFileOrPatternSpec()); - Assert.assertEquals(200L, (long) avroReader.startPosition); - Assert.assertEquals(500L, (long) avroReader.endPosition); - Assert.assertEquals(coder.getValueCoder(), avroReader.avroCoder); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java deleted file mode 100644 index bc56cf56cf..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderTest.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtFraction; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.windowedValuesToValues; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readNItemsFromUnstartedIterator; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readRemainingFromIterator; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.isA; - -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.DynamicSplitResult; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.Progress; - -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.io.DatumWriter; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.OutputStream; -import java.nio.channels.Channels; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import javax.annotation.Nullable; - -/** - * Tests for AvroReader. - */ -@RunWith(JUnit4.class) -public class AvroReaderTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - /** Class representing information about an Avro file generated from a list of elements. */ - private static class AvroFileInfo { - String filename; - List elementSizes = new ArrayList<>(); - List syncPoints = new ArrayList<>(); - long totalElementEncodedSize = 0; - } - - /** Write input elements to a file and return information about the Avro-encoded file. */ - private AvroFileInfo initInputFile(List> elemsList, AvroCoder coder) - throws Exception { - File tmpFile = tmpFolder.newFile("file.avro"); - AvroFileInfo fileInfo = new AvroFileInfo<>(); - fileInfo.filename = tmpFile.getPath(); - - // Write the data. - OutputStream outStream = - Channels.newOutputStream(IOChannelUtils.create(fileInfo.filename, MimeTypes.BINARY)); - DatumWriter datumWriter = coder.createDatumWriter(); - try (DataFileWriter fileWriter = new DataFileWriter<>(datumWriter)) { - fileWriter.create(coder.getSchema(), outStream); - boolean first = true; - for (List elems : elemsList) { - if (first) { - first = false; - } else { - // Ensure a block boundary here. - long syncPoint = fileWriter.sync(); - fileInfo.syncPoints.add(syncPoint); - } - for (T elem : elems) { - fileWriter.append(elem); - fileInfo.elementSizes.add(CoderUtils.encodeToByteArray(coder, elem).length); - fileInfo.totalElementEncodedSize += CoderUtils.encodeToByteArray(coder, elem).length; - } - } - } - - return fileInfo; - } - - /** - * Reads from a file generated from a collection of elements and verifies that the elements read - * are the same as the elements written. - * - * @param elemsList a list of blocks of elements, each of which is as a list of elements. - * @param coder the coder used to encode the elements - * @param requireExactMatch if true, each block must match exactly - * @throws Exception - */ - private void runTestRead( - List> elemsList, AvroCoder coder, boolean requireExactMatch) throws Exception { - // Initialize the input file. - AvroFileInfo fileInfo = initInputFile(elemsList, coder); - - // Test reading the data back. - List> actualElemsList = new ArrayList<>(); - List actualSizes = new ArrayList<>(); - Long startOffset = null; - Long endOffset; - long prevSyncPoint = 0; - for (long syncPoint : fileInfo.syncPoints) { - endOffset = (prevSyncPoint + syncPoint) / 2; - actualElemsList.add(readElems(fileInfo.filename, startOffset, endOffset, coder, actualSizes)); - startOffset = endOffset; - prevSyncPoint = syncPoint; - } - actualElemsList.add(readElems(fileInfo.filename, startOffset, null, coder, actualSizes)); - - // Compare the expected and the actual elements. - if (requireExactMatch) { - // Require the blocks to match exactly. (This works only for - // small block sizes. Large block sizes, bigger than Avro's - // internal sizes, lead to different splits.) - Assert.assertEquals(elemsList, actualElemsList); - } else { - // Just require the overall elements to be the same. (This - // works for any block size.) - List expected = new ArrayList<>(); - for (List elems : elemsList) { - expected.addAll(elems); - } - List actual = new ArrayList<>(); - for (List actualElems : actualElemsList) { - actual.addAll(actualElems); - } - Assert.assertEquals(expected, actual); - } - - long actualTotalSize = 0; - for (int elemSize : actualSizes) { - actualTotalSize += elemSize; - } - Assert.assertEquals(fileInfo.totalElementEncodedSize, actualTotalSize); - } - - private List readElems(String filename, @Nullable Long startOffset, - @Nullable Long endOffset, AvroCoder coder, List actualSizes) throws Exception { - AvroReader avroReader = new AvroReader<>(filename, startOffset, endOffset, coder, null); - new ExecutorTestUtils.TestReaderObserver(avroReader, actualSizes); - - double progressReported = 0; - List actualElems = new ArrayList<>(); - try (AvroReader.AvroFileIterator iterator = avroReader.iterator()) { - for (boolean more = iterator.start(); more; more = iterator.advance()) { - actualElems.add(iterator.getCurrent().getValue()); - double progress = 0.0; - Progress readerProgress = iterator.getProgress(); - if (readerProgress != null) { - progress = readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed(); - } - // Make sure that the reported progress is monotonous. - Assert.assertThat(progress, greaterThanOrEqualTo(progressReported)); - progressReported = progress; - } - } - return actualElems; - } - - // Verification behavior for split requests. Used for testRequestDynamicSplitInternal. - private static enum SplitVerificationBehavior { - VERIFY_SUCCESS, // Split request must succeed. - VERIFY_FAILURE, // Split request must fail. - DO_NOT_VERIFY; // Perform no verification. - } - - private void testRequestDynamicSplitInternal( - AvroReader reader, - float splitAtFraction, - int readBeforeSplit, - SplitVerificationBehavior splitVerificationBehavior) - throws Exception { - // Read all elements from the reader - Long endOffset = reader.endPosition; - List primaryElements; - List residualElements = new ArrayList<>(); - try (AvroReader.AvroFileIterator iterator = reader.iterator()) { - // Read n elements from the reader - primaryElements = - windowedValuesToValues(readNItemsFromUnstartedIterator(iterator, readBeforeSplit)); - - // Request a split at the specified position - DynamicSplitResult splitResult = - iterator.requestDynamicSplit(splitRequestAtFraction(splitAtFraction)); - - switch (splitVerificationBehavior) { - case VERIFY_SUCCESS: - Assert.assertNotNull(splitResult); - break; - case VERIFY_FAILURE: - Assert.assertNull(splitResult); - break; - case DO_NOT_VERIFY: - } - - // Finish reading from the original reader. - primaryElements.addAll( - windowedValuesToValues(readRemainingFromIterator(iterator, readBeforeSplit > 0))); - - if (splitResult != null) { - Long splitPosition = positionFromSplitResult(splitResult).getByteOffset(); - AvroReader residualReader = new AvroReader(reader.avroSource.getFileOrPatternSpec(), - splitPosition, endOffset, reader.avroCoder, reader.options); - // Read from the residual until it is complete. - residualElements = windowedValuesToValues(readAllFromReader(residualReader)); - } - } - - primaryElements.addAll(residualElements); - List expectedElements = windowedValuesToValues(readAllFromReader(reader)); - Assert.assertEquals(expectedElements, primaryElements); - if (splitVerificationBehavior == SplitVerificationBehavior.VERIFY_SUCCESS) { - Assert.assertNotEquals(0, residualElements.size()); - } - } - - @Test - public void testRequestDynamicSplit() throws Exception { - // Note that exhaustive tests for AvroSource's split behavior exist in {@link AvroSourceTest}. - List> elements = generateInputBlocks(10, 100 * 100, 100); - AvroCoder coder = AvroCoder.of(String.class); - AvroFileInfo fileInfo = initInputFile(elements, coder); - AvroReader reader = new AvroReader(fileInfo.filename, null, null, coder, null); - // Read most of the records before the proposed split point. - testRequestDynamicSplitInternal(reader, 0.5F, 490, SplitVerificationBehavior.VERIFY_SUCCESS); - // Read a single record. - testRequestDynamicSplitInternal(reader, 0.5F, 1, SplitVerificationBehavior.VERIFY_SUCCESS); - // Read zero records. - testRequestDynamicSplitInternal(reader, 0.5F, 0, SplitVerificationBehavior.VERIFY_FAILURE); - // Read almost the entire input. - testRequestDynamicSplitInternal(reader, 0.5F, 900, SplitVerificationBehavior.VERIFY_FAILURE); - // Read the entire input. - testRequestDynamicSplitInternal(reader, 0.5F, 2000, SplitVerificationBehavior.VERIFY_FAILURE); - } - - @Test - public void testRequestDynamicSplitExhaustive() throws Exception { - List> elements = generateInputBlocks(5, 10 * 10, 10); - AvroCoder coder = AvroCoder.of(String.class); - AvroFileInfo fileInfo = initInputFile(elements, coder); - AvroReader reader = new AvroReader(fileInfo.filename, null, null, coder, null); - for (float splitFraction = 0.0F; splitFraction < 1.0F; splitFraction += 0.02F) { - for (int recordsToRead = 0; recordsToRead <= 500; recordsToRead += 5) { - testRequestDynamicSplitInternal( - reader, splitFraction, recordsToRead, SplitVerificationBehavior.DO_NOT_VERIFY); - } - } - } - - @Test - public void testRead() throws Exception { - runTestRead(Collections.singletonList(TestUtils.INTS), AvroCoder.of(Integer.class), - true/* require exact match */); - } - - @Test - public void testReadEmpty() throws Exception { - runTestRead(Collections.singletonList(TestUtils.NO_INTS), AvroCoder.of(Integer.class), - true/* require exact match */); - } - - private List> generateInputBlocks( - int numBlocks, int blockSizeBytes, int averageLineSizeBytes) { - Random random = new Random(0); - List> blocks = new ArrayList<>(numBlocks); - for (int blockNum = 0; blockNum < numBlocks; blockNum++) { - int numLines = blockSizeBytes / averageLineSizeBytes; - List lines = new ArrayList<>(numLines); - for (int lineNum = 0; lineNum < numLines; lineNum++) { - int numChars = random.nextInt(averageLineSizeBytes * 2); - StringBuilder sb = new StringBuilder(); - for (int charNum = 0; charNum < numChars; charNum++) { - sb.appendCodePoint(random.nextInt('z' - 'a' + 1) + 'a'); - } - lines.add(sb.toString()); - } - blocks.add(lines); - } - return blocks; - } - - @Test - public void testReadSmallRanges() throws Exception { - runTestRead(generateInputBlocks(3, 50, 5), AvroCoder.of(String.class), - true/* require exact match */); - } - - @Test - public void testReadBigRanges() throws Exception { - runTestRead(generateInputBlocks(10, 128 * 1024, 100), AvroCoder.of(String.class), - false/* don't require exact match */); - } - - @Test - public void testErrorOnFileNotFound() throws Exception { - expectedException.expectCause(isA(FileNotFoundException.class)); - readElems("file-not-found", 0L, 100L, AvroCoder.of(String.class), new ArrayList()); - } - - @Test - public void testErrorOnMultipleFiles() throws Exception { - File file1 = tmpFolder.newFile("foo1.avro"); - File file2 = tmpFolder.newFile("foo2.avro"); - Channels.newOutputStream(IOChannelUtils.create(file1.getPath(), MimeTypes.BINARY)).close(); - Channels.newOutputStream(IOChannelUtils.create(file2.getPath(), MimeTypes.BINARY)).close(); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("More than 1 file matched"); - readElems(new File(tmpFolder.getRoot(), "*").getPath(), 0L, 100L, - AvroCoder.of(String.class), new ArrayList()); - } - - // TODO: sharded filenames - // TODO: reading from GCS -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactoryTest.java deleted file mode 100644 index 3b42dc30c8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactoryTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for AvroSinkFactory. - */ -@RunWith(JUnit4.class) -public class AvroSinkFactoryTest { - private final String pathToAvroFile = "/path/to/file.avro"; - - Sink runTestCreateAvroSink(String filename, - CloudObject encoding) - throws Exception { - CloudObject spec = CloudObject.forClassName("AvroSink"); - addString(spec, "filename", filename); - - com.google.api.services.dataflow.model.Sink cloudSink = - new com.google.api.services.dataflow.model.Sink(); - cloudSink.setSpec(spec); - cloudSink.setCodec(encoding); - - PipelineOptions options = PipelineOptionsFactory.create(); - Sink sink = SinkFactory.create(options, cloudSink, - BatchModeExecutionContext.fromOptions(options), null); - return sink; - } - - @Test - public void testCreateAvroByteSink() throws Exception { - Coder coder = - WindowedValue.getFullCoder(BigEndianIntegerCoder.of(), GlobalWindow.Coder.INSTANCE); - Sink sink = runTestCreateAvroSink( - pathToAvroFile, coder.asCloudObject()); - - Assert.assertThat(sink, new IsInstanceOf(AvroByteSink.class)); - AvroByteSink avroSink = (AvroByteSink) sink; - Assert.assertEquals(pathToAvroFile, avroSink.avroSink.filenamePrefix); - Assert.assertEquals(coder, avroSink.coder); - } - - @Test - public void testCreateAvroSink() throws Exception { - WindowedValue.WindowedValueCoder coder = - WindowedValue.getValueOnlyCoder(AvroCoder.of(Integer.class)); - Sink sink = runTestCreateAvroSink(pathToAvroFile, coder.asCloudObject()); - - Assert.assertThat(sink, new IsInstanceOf(AvroSink.class)); - AvroSink avroSink = (AvroSink) sink; - Assert.assertEquals(pathToAvroFile, avroSink.filenamePrefix); - Assert.assertEquals(coder.getValueCoder(), avroSink.avroCoder); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java deleted file mode 100644 index e881913ed8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.windowedValuesToValues; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; - -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for AvroSink. - */ -@RunWith(JUnit4.class) -public class AvroSinkTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - void runTestWriteFile(List elems, AvroCoder coder) throws Exception { - File tmpFile = tmpFolder.newFile("file.avro"); - String filename = tmpFile.getPath(); - - // Write the file. - - AvroSink avroSink = new AvroSink<>(filename, WindowedValue.getValueOnlyCoder(coder)); - List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter> writer = avroSink.writer()) { - for (T elem : elems) { - actualSizes.add(writer.add(WindowedValue.valueInGlobalWindow(elem))); - } - } - - // Read back the file. - AvroReader reader = new AvroReader<>(filename, null, null, coder, null); - - List actual = windowedValuesToValues(readAllFromReader(reader)); - - List expectedSizes = new ArrayList<>(); - for (T value : actual) { - expectedSizes.add((long) CoderUtils.encodeToByteArray(coder, value).length); - } - - // Compare the expected and the actual elements. - Assert.assertEquals(elems, actual); - Assert.assertEquals(expectedSizes, actualSizes); - } - - @Test - public void testWriteFile() throws Exception { - runTestWriteFile(TestUtils.INTS, AvroCoder.of(Integer.class)); - } - - @Test - public void testWriteEmptyFile() throws Exception { - runTestWriteFile(TestUtils.NO_INTS, AvroCoder.of(Integer.class)); - } - - // TODO: sharded filenames - // TODO: writing to GCS -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java deleted file mode 100644 index d2d69085a3..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactoryTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for BigQueryReaderFactory. - */ -@RunWith(JUnit4.class) -public class BigQueryReaderFactoryTest { - void runTestCreateBigQueryReaderFromTable( - String project, String dataset, String table, CloudObject encoding) throws Exception { - CloudObject spec = CloudObject.forClassName("BigQuerySource"); - addString(spec, "project", project); - addString(spec, "dataset", dataset); - addString(spec, "table", table); - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(encoding); - - GcpOptions options = PipelineOptionsFactory.create().as(GcpOptions.class); - options.setGcpCredential(new TestCredential()); - - NativeReader reader = - ReaderRegistry.defaultRegistry() - .create(cloudSource, options, DirectModeExecutionContext.create(), null, null); - assertThat(reader, new IsInstanceOf(BigQueryReader.class)); - BigQueryReader bigQueryReader = (BigQueryReader) reader; - TableReference tableRef = bigQueryReader.getTableRef(); - assertEquals(project, tableRef.getProjectId()); - assertEquals(dataset, tableRef.getDatasetId()); - assertEquals(table, tableRef.getTableId()); - } - - void runTestCreateBigQueryReaderFromQuery(String query, CloudObject encoding) throws Exception { - CloudObject spec = CloudObject.forClassName("BigQuerySource"); - addString(spec, "bigquery_query", query); - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(encoding); - - GcpOptions options = PipelineOptionsFactory.create().as(GcpOptions.class); - options.setGcpCredential(new TestCredential()); - - NativeReader reader = - ReaderRegistry.defaultRegistry() - .create(cloudSource, options, DirectModeExecutionContext.create(), null, null); - - assertThat(reader, new IsInstanceOf(BigQueryReader.class)); - BigQueryReader bigQueryReader = (BigQueryReader) reader; - assertEquals(query, bigQueryReader.getQuery()); - } - - @Test - public void testCreateBigQueryReaderFromQuery() throws Exception { - runTestCreateBigQueryReaderFromQuery("somequery", makeCloudEncoding("TableRowJsonCoder")); - } - - @Test - public void testCreateBigQueryReaderFromTable() throws Exception { - runTestCreateBigQueryReaderFromTable( - "someproject", "somedataset", "sometable", makeCloudEncoding("TableRowJsonCoder")); - } - - @Test - public void testCreateBigQueryReaderCoderIgnored() throws Exception { - // BigQuery sources do not need a coder because the TableRow objects are read directly from - // the table using the BigQuery API. - runTestCreateBigQueryReaderFromTable( - "someproject", "somedataset", "sometable", makeCloudEncoding("BigEndianIntegerCoder")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java deleted file mode 100644 index 579bb6b1fb..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderTest.java +++ /dev/null @@ -1,910 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.contains; -import static org.mockito.Matchers.endsWith; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.client.http.LowLevelHttpRequest; -import com.google.api.client.json.Json; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.testing.http.MockLowLevelHttpResponse; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.common.collect.Lists; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.IOException; -import java.util.List; - -/** - * Tests for BigQueryReader. - * - *

    The tests make sure a simple scenario (reading two rows) work for the various kinds of fields - * and modes. - */ -@RunWith(JUnit4.class) -public class BigQueryReaderTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - - private static final String PROJECT_ID = "project"; - private static final String DATASET = "dataset"; - private static final String TABLE = "table"; - private static final String QUERY_JOB_ID = "query_job_id"; - private static final String QUERY_JOB_RESPONSE_DATASET = "query_job_response_dataset"; - private static final String QUERY_JOB_RESPONSE_TEMP_TABLE = "query_job_response_temp_table"; - - private static final String GET_TABLE_REQUEST_PATH = - String.format("projects/%s/datasets/%s/tables/%s", PROJECT_ID, DATASET, TABLE); - - // This is a real response (with some unused fields removed) for the table created from this - // schema: - // [ - // {"name":"name","type":"STRING"}, - // {"name":"integer", "type":"INTEGER"}, - // {"name":"float", "type":"FLOAT"}, - // {"name":"bool", "type":"BOOLEAN"}, - // {"name":"record", "type":"RECORD", "fields":[ - // {"name": "nestedInt","type":"INTEGER"}, - // {"name": "nestedFloat","type":"FLOAT"} - // ]}, - // {"name":"repeatedInt", "type":"INTEGER", "mode":"REPEATED"}, - // {"name":"repeatedFloat", "type":"FLOAT", "mode":"REPEATED"}, - // - // {"name":"repeatedRecord", "type":"RECORD", "mode":"REPEATED", "fields":[ - // {"name": "bool", "type": "BOOLEAN"}, - // {"name": "string", "type": "STRING"} - // ]} - // ] - private static final String GET_TABLE_RESPONSE_JSON = - "{\n" - + " \"schema\": {\n" - + " \"fields\": [\n" - + " {\n" - + " \"name\": \"name\",\n" - + " \"type\": \"STRING\"\n" - + " },\n" - + " {\n" - + " \"name\": \"integer\",\n" - + " \"type\": \"INTEGER\"\n" - + " },\n" - + " {\n" - + " \"name\": \"float\",\n" - + " \"type\": \"FLOAT\"\n" - + " },\n" - + " {\n" - + " \"name\": \"bool\",\n" - + " \"type\": \"BOOLEAN\"\n" - + " },\n" - + " {\n" - + " \"name\": \"record\",\n" - + " \"type\": \"RECORD\",\n" - + " \"fields\": [\n" - + " {\n" - + " \"name\": \"nestedInt\",\n" - + " \"type\": \"INTEGER\"\n" - + " },\n" - + " {\n" - + " \"name\": \"nestedFloat\",\n" - + " \"type\": \"FLOAT\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"name\": \"repeatedInt\",\n" - + " \"type\": \"INTEGER\",\n" - + " \"mode\": \"REPEATED\"\n" - + " },\n" - + " {\n" - + " \"name\": \"repeatedFloat\",\n" - + " \"type\": \"FLOAT\",\n" - + " \"mode\": \"REPEATED\"\n" - + " },\n" - + " {\n" - + " \"name\": \"repeatedRecord\",\n" - + " \"type\": \"RECORD\",\n" - + " \"mode\": \"REPEATED\",\n" - + " \"fields\": [\n" - + " {\n" - + " \"name\": \"bool\",\n" - + " \"type\": \"BOOLEAN\"\n" - + " },\n" - + " {\n" - + " \"name\": \"string\",\n" - + " \"type\": \"STRING\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " ]\n" - + " },\n" - + " \"numRows\": \"2\",\n" - + " \"type\": \"TABLE\"\n" - + "}"; - - private static final String LIST_TABLE_DATA_REQUEST_PATH = - String.format("projects/%s/datasets/%s/tables/%s/data", PROJECT_ID, DATASET, TABLE); - - // This is a real response (with some unused fields removed) for the table listed above, populated - // with the following data: - // {"name": "Arthur", "integer": 42, "float": 3.14159, "bool": "false", - // "record": {"nestedInt": 43, "nestedFloat": "4.14159"}, - // "repeatedInt":[42, 43, 79]}, - // - // {"name": "Allison", "integer": 79, "float": 2.71828, "bool": "true", - // "record": {"nestedInt": 80, "nestedFloat": "3.71828"}, - // "repeatedFloat":[3.14159, 2.71828], - // "repeatedRecord":[{"bool":"true","string":"hello"}, - // {"bool":"false","string":"world"}]} - private static final String LIST_TABLEDATA_RESPONSE_JSON = - "{\n" - + " \"totalRows\": \"2\",\n" - + " \"rows\": [\n" - + " {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"Arthur\"\n" - + " },\n" - + " {\n" - + " \"v\": \"42\"\n" - + " },\n" - + " {\n" - + " \"v\": \"3.14159\"\n" - + " },\n" - + " {\n" - + " \"v\": \"false\"\n" - + " },\n" - + " {\n" - + " \"v\": {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"43\"\n" - + " },\n" - + " {\n" - + " \"v\": \"4.14159\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " },\n" - + " {\n" - + " \"v\": [\n" - + " {\n" - + " \"v\": \"42\"\n" - + " },\n" - + " {\n" - + " \"v\": \"43\"\n" - + " },\n" - + " {\n" - + " \"v\": \"79\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"v\": [\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"v\": [\n" - + " ]\n" - + " }\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"Allison\"\n" - + " },\n" - + " {\n" - + " \"v\": \"79\"\n" - + " },\n" - + " {\n" - + " \"v\": \"2.71828\"\n" - + " },\n" - + " {\n" - + " \"v\": \"true\"\n" - + " },\n" - + " {\n" - + " \"v\": {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"80\"\n" - + " },\n" - + " {\n" - + " \"v\": \"3.71828\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " },\n" - + " {\n" - + " \"v\": [\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"v\": [\n" - + " {\n" - + " \"v\": \"3.14159\"\n" - + " },\n" - + " {\n" - + " \"v\": \"2.71828\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"v\": [\n" - + " {\n" - + " \"v\": {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"true\"\n" - + " },\n" - + " {\n" - + " \"v\": \"hello\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " },\n" - + " {\n" - + " \"v\": {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"false\"\n" - + " },\n" - + " {\n" - + " \"v\": \"world\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " }\n" - + " ]\n" - + " }\n" - + " ]\n" - + " }\n" - + " ]\n" - + "}"; - - private static final String INSERT_QUERY_JOB_PATH = - String.format("https://www.googleapis.com/bigquery/v2/projects/%s/jobs", PROJECT_ID); - - // This is the actual response received for following requests (parameterized identifiers were - // updated). - // POST https://www.googleapis.com/bigquery/v2/projects/project/jobs - // - // { - // "configuration": { - // "query": { - // "query": "SELECT name, integer from dataset.table" - // } - // } - // } - private static final String INSERT_QUERY_JOB_RESPONSE = String.format( - "{\n" - + "\n" - + " \"kind\": \"bigquery#job\",\n" - + " \"etag\": \"\\\"Gn3Hpo5WaKnpFuT457VBDNMgZBw/GF2DiLTiF0s2MwsdQlV4UB-xaew\\\"\",\n" - + " \"id\": \"%1$s:%2$s\",\n" - + " \"selfLink\": \"https://www.googleapis.com/bigquery/v2/projects/%1$s/jobs/%2$s\",\n" - + " \"jobReference\": {\n" - + " \"projectId\": \"%1$s\",\n" - + " \"jobId\": \"%2$s\"\n" - + " },\n" - + " \"configuration\": {\n" - + " \"query\": {\n" - + " \"query\": \"SELECT name, integer from %4$s.%5$s\",\n" - + " \"destinationTable\": {\n" - + " \"projectId\": \"%1$s\",\n" - + " \"datasetId\": \"%4$s\",\n" - + " \"tableId\": \"%3$s\"\n" - + " },\n" - + " \"createDisposition\": \"CREATE_IF_NEEDED\",\n" - + " \"writeDisposition\": \"WRITE_TRUNCATE\"\n" - + " }\n" - + " },\n" - + " \"status\": {\n" - + " \"state\": \"RUNNING\"\n" - + " },\n" - + " \"statistics\": {\n" - + " \"creationTime\": \"1433378500260\",\n" - + " \"startTime\": \"1433378500833\"\n" - + " },\n" - + " \"user_email\": \"user@gmail.com\"\n" - + "}", - PROJECT_ID, QUERY_JOB_ID, QUERY_JOB_RESPONSE_TEMP_TABLE, QUERY_JOB_RESPONSE_DATASET, TABLE); - - - private static final String GET_QUERY_JOB_STATUS_REQUEST_PATH = String.format( - "https://www.googleapis.com/bigquery/v2/projects/%s/jobs/%s", PROJECT_ID, QUERY_JOB_ID); - - - // This is the actual response received for following requests (parameterized identifiers were - // updated). - // GET - // https://www.googleapis.com/bigquery/v2/projects/project/jobs/query_job_id - private static final String GET_QUERY_JOB_STATUS_RESPONSE_JSON = String.format( - "{\n" - + "\n" - + " \"kind\": \"bigquery#job\",\n" - + " \"etag\": \"\\\"Gn3Hpo5WaKnpFuT457VBDNMgZBw/ZVEFinsDS6AZ04jebPWC9_isCpY\\\"\",\n" - + " \"id\": \"%1$s:%4$s\",\n" - + " \"selfLink\": \"https://www.googleapis.com/bigquery/v2/projects/%1$s/jobs/%4$s\",\n" - + " \"jobReference\": {\n" - + " \"projectId\": \"%1$s\",\n" - + " \"jobId\": \"%4$s\"\n" - + " },\n" - + " \"configuration\": {\n" - + " \"query\": {\n" - + " \"query\": \"SELECT name, integer from test_chamikara.bigquery_reader_test\",\n" - + " \"destinationTable\": {\n" - + " \"projectId\": \"%1$s\",\n" - + " \"datasetId\": \"%2$s\",\n" - + " \"tableId\": \"%3$s\"\n" - + " },\n" - + " \"createDisposition\": \"CREATE_IF_NEEDED\",\n" - + " \"writeDisposition\": \"WRITE_TRUNCATE\",\n" - + " \"priority\": \"INTERACTIVE\",\n" - + " \"useQueryCache\": true\n" - + " }\n" - + " },\n" - + " \"status\": {\n" - + " \"state\": \"DONE\"\n" - + " },\n" - + " \"statistics\": {\n" - + " \"creationTime\": \"1433374960768\",\n" - + " \"startTime\": \"1433374961242\",\n" - + " \"endTime\": \"1433374961532\",\n" - + " \"totalBytesProcessed\": \"33\",\n" - + " \"query\": {\n" - + " \"totalBytesProcessed\": \"33\",\n" - + " \"cacheHit\": false\n" - + " }\n" - + " },\n" - + " \"user_email\": \"user@gmail.com\"\n" - + "}", - PROJECT_ID, QUERY_JOB_RESPONSE_DATASET, QUERY_JOB_RESPONSE_TEMP_TABLE, QUERY_JOB_ID); - - private static final String LIST_QUERY_TABLE_DATA_REQUEST_PATH = - String.format("https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s/data", - PROJECT_ID, QUERY_JOB_RESPONSE_DATASET, QUERY_JOB_RESPONSE_TEMP_TABLE); - - // This is the actual response received for following requests (parameterized identifiers were - // updated). - // GET - // https://www.googleapis.com/bigquery/v2/projects/project/datasets/query_job_response_dataset/ - // tables/query_job_response_temp_table/data - private static final String LIST_QUERY_TABLE_DATA_RESPONSE = - "{\n" - + " \"kind\": \"bigquery#tableDataList\",\n" - + " \"etag\": \"\\\"Gn3Hpo5WaKnpFuT457VBDNMgZBw/6Y6hxVy6yTmtI2EEgHfqg3w49yU\\\"\",\n" - + " \"totalRows\": \"2\",\n" - + " \"rows\": [\n" - + " {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"Arthur\"\n" - + " },\n" - + " {\n" - + " \"v\": \"42\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"Allison\"\n" - + " },\n" - + " {\n" - + " \"v\": \"79\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " ]\n" - + "}"; - - private static final String QUERY_TABLE_GET_REQUEST_PATH = - String.format("https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s", - PROJECT_ID, QUERY_JOB_RESPONSE_DATASET, QUERY_JOB_RESPONSE_TEMP_TABLE); - - // This is the actual response received for following requests (parameterized identifiers were - // updated). - // GET - // https://www.googleapis.com/bigquery/v2/projects/project/datasets/query_job_response_dataset/ - // tables/query_job_response_temp_table - private static final String QUERY_TABLE_GET_RESPONSE = String.format( - "{\n" - + "\n" - + " \"kind\": \"bigquery#table\",\n" - + " \"etag\": \"\\\"Gn3Hpo5WaKnpFuT457VBDNMgZBw/MTQzMzM3ODUwMDg4NA\\\"\",\n" - + " \"id\": \"%1$s:%2$s.%3$s\",\n" - + " \"selfLink\": \"https://www.googleapis.com/bigquery/v2/projects/%1$s/datasets/%2$s/" - + "tables/%3$s\",\n" - + " \"tableReference\": {\n" - + " \"projectId\": \"%1$s\",\n" - + " \"datasetId\": \"%2$s\",\n" - + " \"tableId\": \"%3$s\"\n" - + " },\n" - + " \"schema\": {\n" - + " \"fields\": [\n" - + " {\n" - + " \"name\": \"name\",\n" - + " \"type\": \"STRING\",\n" - + " \"mode\": \"NULLABLE\"\n" - + " },\n" - + " {\n" - + " \"name\": \"integer\",\n" - + " \"type\": \"INTEGER\",\n" - + " \"mode\": \"NULLABLE\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " \"numBytes\": \"33\",\n" - + " \"numRows\": \"2\",\n" - + " \"creationTime\": \"1433374961476\",\n" - + " \"expirationTime\": \"1433464900889\",\n" - + " \"lastModifiedTime\": \"1433378500884\",\n" - + " \"type\": \"TABLE\"\n" - + "}", - PROJECT_ID, QUERY_JOB_RESPONSE_DATASET, QUERY_JOB_RESPONSE_TEMP_TABLE); - - private static final String QUERY_DATASET_INSERT_PATH = - String.format("https://www.googleapis.com/bigquery/v2/projects/%s/datasets", PROJECT_ID); - - private static final String QUERY_DATASET_INSERT_RESPONSE = String.format( - "{\n" - + "\n" - + " \"kind\": \"bigquery#dataset\",\n" - + " \"etag\": \"\\\"Gn3Hpo5WaKnpFuT457VBDNMgZBw/67ZQLsO6a6iDLJ71ReSC-LWBBw4\\\"\",\n" - + " \"id\": \"%1$s:%2$s\",\n" - + " \"selfLink\": \"https://www.googleapis.com/bigquery/v2/projects/%1$s/datasets/%2$s\",\n" - + " \"datasetReference\": {\n" - + " \"datasetId\": \"%2$s\",\n" - + " \"projectId\": \"%1$s\"\n" - + " },\n" - + " \"access\": [\n" - + " {\n" - + " \"role\": \"OWNER\",\n" - + " \"specialGroup\": \"projectOwners\"\n" - + " },\n" - + " {\n" - + " \"role\": \"WRITER\",\n" - + " \"specialGroup\": \"projectWriters\"\n" - + " },\n" - + " {\n" - + " \"role\": \"READER\",\n" - + " \"specialGroup\": \"projectReaders\"\n" - + " }\n" - + " ],\n" - + " \"creationTime\": \"1436219427054\",\n" - + " \"lastModifiedTime\": \"1436219427054\"\n" - + "}", - PROJECT_ID, QUERY_JOB_RESPONSE_DATASET); - - private static final String QUERY_TABLE_DELETE_PATH = - String.format("https://www.googleapis.com/bigquery/v2/projects/%s/", PROJECT_ID); - - private static final String QUERY_TABLE_DELETE_RESPONSE = ""; // Empty body - - private static final String QUERY_DATASET_DELETE_PATH = - String.format("https://www.googleapis.com/bigquery/v2/projects/%s/", PROJECT_ID); - - private static final String QUERY_DATASET_DELETE_RESPONSE = ""; // Empty body - - private static final String QUERY = "SELECT name, integer from dataset.table"; - - @Mock - private MockHttpTransport mockTransport; - - private void verifyDatasetInsert() throws IOException { - verify(mockTransport, times(1)).buildRequest(eq("POST"), endsWith(QUERY_DATASET_INSERT_PATH)); - } - - private void verifyInsertQueryJob() throws IOException { - verify(mockTransport, times(1)).buildRequest(eq("POST"), endsWith(INSERT_QUERY_JOB_PATH)); - } - - private void verifyQueryJobStatus() throws IOException { - verify(mockTransport, times(1)) - .buildRequest(eq("GET"), endsWith(GET_QUERY_JOB_STATUS_REQUEST_PATH)); - } - - private void verifyQueryTableData() throws IOException { - verify(mockTransport, times(1)) - .buildRequest(eq("GET"), endsWith(LIST_QUERY_TABLE_DATA_REQUEST_PATH)); - } - - private void verifyQueryTableGet() throws IOException { - verify(mockTransport, times(1)).buildRequest(eq("GET"), endsWith(QUERY_TABLE_GET_REQUEST_PATH)); - } - - private void verifyTableDelete() throws IOException { - verify(mockTransport, times(2)).buildRequest(eq("DELETE"), contains(QUERY_TABLE_DELETE_PATH)); - } - - private void verifyDatasetDelete() throws IOException { - verify(mockTransport, times(2)).buildRequest(eq("DELETE"), contains(QUERY_DATASET_DELETE_PATH)); - } - - @Test - public void testReadQuery() throws Exception { - setUpMockQuery(); - - Bigquery bigQueryClient = new Bigquery(mockTransport, Transport.getJsonFactory(), null); - BigQueryReader reader = BigQueryReader.fromQuery(QUERY, PROJECT_ID, bigQueryClient, true); - BigQueryReader.BigQueryReaderIterator iterator = reader.iterator(); - - assertTrue(iterator.start()); - TableRow row = iterator.getCurrent().getValue(); - - assertEquals("Arthur", row.get("name")); - assertEquals("42", row.get("integer")); - assertNull(row.getF()); - - assertTrue(iterator.advance()); - row = iterator.getCurrent().getValue(); - assertEquals("Allison", row.get("name")); - assertEquals("79", row.get("integer")); - assertNull(row.getF()); - - iterator.close(); - - verify(mockTransport, atLeastOnce()).supportsMethod("GET"); - verify(mockTransport, atLeastOnce()).supportsMethod("DELETE"); - - verifyDatasetInsert(); - verifyInsertQueryJob(); - verifyQueryJobStatus(); - verifyQueryTableData(); - verifyQueryTableGet(); - verifyTableDelete(); - verifyDatasetDelete(); - - verifyNoMoreInteractions(mockTransport); - } - - void setUpMockQuery() throws IOException { - MockitoAnnotations.initMocks(this); - - when(mockTransport.buildRequest(eq("POST"), endsWith(QUERY_DATASET_INSERT_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(QUERY_DATASET_INSERT_RESPONSE); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - - when(mockTransport.buildRequest(eq("POST"), endsWith(INSERT_QUERY_JOB_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(INSERT_QUERY_JOB_RESPONSE); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - - when(mockTransport.buildRequest(eq("GET"), endsWith(GET_QUERY_JOB_STATUS_REQUEST_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(GET_QUERY_JOB_STATUS_RESPONSE_JSON); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - - when(mockTransport.buildRequest(eq("GET"), endsWith(LIST_QUERY_TABLE_DATA_REQUEST_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(LIST_QUERY_TABLE_DATA_RESPONSE); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - - when(mockTransport.buildRequest(eq("GET"), endsWith(QUERY_TABLE_GET_REQUEST_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(QUERY_TABLE_GET_RESPONSE); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - - when(mockTransport.buildRequest(eq("DELETE"), contains(QUERY_TABLE_DELETE_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(QUERY_TABLE_DELETE_RESPONSE); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - - when(mockTransport.buildRequest(eq("DELETE"), contains(QUERY_DATASET_DELETE_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(QUERY_DATASET_DELETE_RESPONSE); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - - when(mockTransport.supportsMethod("GET")).thenReturn(true); - when(mockTransport.supportsMethod("DELETE")).thenReturn(true); - } - - void setUpMockTable() throws Exception { - MockitoAnnotations.initMocks(this); - when(mockTransport.buildRequest(eq("GET"), endsWith(GET_TABLE_REQUEST_PATH))) - .thenThrow(new IOException()) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(GET_TABLE_RESPONSE_JSON); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - when(mockTransport.buildRequest(eq("GET"), endsWith(LIST_TABLE_DATA_REQUEST_PATH))) - .thenThrow(new IOException()) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(LIST_TABLEDATA_RESPONSE_JSON); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - when(mockTransport.buildRequest(eq("GET"), endsWith(GET_TABLE_WITH_F_REQUEST_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(GET_TABLE_WITH_F_RESPONSE_JSON); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - when(mockTransport.buildRequest(eq("GET"), endsWith(LIST_TABLE_WITH_F_DATA_REQUEST_PATH))) - .thenAnswer(new Answer() { - @Override - public LowLevelHttpRequest answer(InvocationOnMock invocation) throws Throwable { - MockLowLevelHttpResponse response = - new MockLowLevelHttpResponse() - .setContentType(Json.MEDIA_TYPE) - .setContent(LIST_TABLE_WITH_F_DATA_RESPONSE_JSON); - return new MockLowLevelHttpRequest((String) invocation.getArguments()[1]) - .setResponse(response); - } - }); - when(mockTransport.supportsMethod("GET")).thenReturn(true); - } - - private void verifyTableGet() throws IOException { - verify(mockTransport, times(2)).buildRequest(eq("GET"), endsWith(GET_TABLE_REQUEST_PATH)); - } - - private void verifyTabledataList() throws IOException { - verify(mockTransport, times(2)).buildRequest(eq("GET"), endsWith(LIST_TABLE_DATA_REQUEST_PATH)); - } - - @Test - public void testReadTable() throws Exception { - setUpMockTable(); - - Bigquery bigQueryClient = new Bigquery(mockTransport, Transport.getJsonFactory(), null); - BigQueryReader reader = BigQueryReader.fromTable( - new TableReference().setProjectId(PROJECT_ID).setDatasetId(DATASET).setTableId(TABLE), - bigQueryClient); - - BigQueryReader.BigQueryReaderIterator iterator = reader.iterator(); - assertTrue(iterator.start()); - - TableRow row = iterator.getCurrent().getValue(); - - assertEquals("Arthur", row.get("name")); - assertEquals("42", row.get("integer")); - assertEquals(3.14159, row.get("float")); - assertEquals(false, row.get("bool")); - - TableRow nested = (TableRow) row.get("record"); - assertEquals("43", nested.get("nestedInt")); - assertEquals(4.14159, nested.get("nestedFloat")); - assertNull(nested.getF()); - - assertEquals(Lists.newArrayList("42", "43", "79"), row.get("repeatedInt")); - assertTrue(((List) row.get("repeatedFloat")).isEmpty()); - assertTrue(((List) row.get("repeatedRecord")).isEmpty()); - - assertTrue(iterator.advance()); - row = iterator.getCurrent().getValue(); - - assertEquals("Allison", row.get("name")); - assertEquals("79", row.get("integer")); - assertEquals(2.71828, row.get("float")); - assertEquals(true, row.get("bool")); - - nested = (TableRow) row.get("record"); - assertEquals("80", nested.get("nestedInt")); - assertEquals(3.71828, nested.get("nestedFloat")); - assertNull(nested.getF()); - - assertTrue(((List) row.get("repeatedInt")).isEmpty()); - assertEquals(Lists.newArrayList(3.14159, 2.71828), row.get("repeatedFloat")); - - @SuppressWarnings("unchecked") - List nestedRecords = (List) row.get("repeatedRecord"); - assertEquals(2, nestedRecords.size()); - assertEquals("hello", nestedRecords.get(0).get("string")); - assertEquals(true, nestedRecords.get(0).get("bool")); - assertNull(nestedRecords.get(0).getF()); - assertEquals("world", nestedRecords.get(1).get("string")); - assertEquals(false, nestedRecords.get(1).get("bool")); - assertNull(nestedRecords.get(1).getF()); - - assertFalse(iterator.advance()); - - verifyTableGet(); - verifyTabledataList(); - - verify(mockTransport, atLeastOnce()).supportsMethod("GET"); - verifyNoMoreInteractions(mockTransport); - } - - //////////////////////////////////////////////////////////////////////////// - // Constants and tests for surviving a field named "f" in the table schema. - //////////////////////////////////////////////////////////////////////////// - - // Modified from GET_TABLE_RESPONSE_JSON for a table with a field name "f" - // [ - // {"name":"int","type":"INTEGER"}, - // {"name":"f","type":"STRING"} - // ] - private static final String GET_TABLE_WITH_F_RESPONSE_JSON = - "{\n" - + " \"schema\": {\n" - + " \"fields\": [\n" - + " {\n" - + " \"name\": \"int\",\n" - + " \"type\": \"INTEGER\"\n" - + " },\n" - + " {\n" - + " \"name\": \"f\",\n" - + " \"type\": \"STRING\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " \"numRows\": \"2\",\n" - + " \"type\": \"TABLE\"\n" - + "}"; - - private static final String TABLE_WITH_FIELD_F = "table_f"; - private static final String GET_TABLE_WITH_F_REQUEST_PATH = - String.format("projects/%s/datasets/%s/tables/%s", PROJECT_ID, DATASET, TABLE_WITH_FIELD_F); - private static final String LIST_TABLE_WITH_F_DATA_REQUEST_PATH = - String.format("%s/data", GET_TABLE_WITH_F_REQUEST_PATH); - - // Modified from LIST_TABLEDATA_RESPONSE_JSON for a table with a field named "f" - // with the following data: - // {"int": "5", "f": "Arthur"}, - // - // {"int": "42", "f": "Allison"} - private static final String LIST_TABLE_WITH_F_DATA_RESPONSE_JSON = - "{\n" - + " \"totalRows\": \"2\",\n" - + " \"rows\": [\n" - + " {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"5\"\n" - + " },\n" - + " {\n" - + " \"v\": \"Arthur\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"f\": [\n" - + " {\n" - + " \"v\": \"42\"\n" - + " },\n" - + " {\n" - + " \"v\": \"Allison\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " ]\n" - + "}"; - - /** - * This tests two different things: - * - *

      - *
    1. {@link BigQueryReader} can handle a field named "f" without crashing. - *
    2. The value of field named "f" can be retrieved positionally from {@link TableRow#getF()} - *
    - */ - @Test - public void testReadTableWithFieldF() throws Exception { - setUpMockTable(); - - Bigquery bigQueryClient = new Bigquery(mockTransport, Transport.getJsonFactory(), null); - TableReference tableRef = new TableReference() - .setProjectId(PROJECT_ID).setDatasetId(DATASET).setTableId(TABLE_WITH_FIELD_F); - BigQueryReader reader = BigQueryReader.fromTable(tableRef, bigQueryClient); - - try (BigQueryReader.BigQueryReaderIterator iterator = reader.iterator()) { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("BigQueryIO does not support records with columns named f"); - - iterator.start(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReaderTest.java deleted file mode 100644 index 791d762dc6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReaderTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.PCollectionViewTesting; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; -import com.google.cloud.dataflow.sdk.util.WeightedSideInputReader; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.collect.ImmutableMap; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link CachingSideInputReader}. - */ -@RunWith(JUnit4.class) -public class CachingSideInputReaderTest { - - private static boolean isCached( - Cache, WeightedValue> cache, - PCollectionView view, BoundedWindow window) { - return null != cache.getIfPresent(PCollectionViewWindow.of(view, window)); - } - - /** An arbitrary {@link TupleTag} used for tests. */ - private static final TupleTag>> ITERABLE_TAG = new TupleTag<>(); - - /** A {@link TupleTag} that agrees with {@link #ITERABLE_TAG} but is not {@code ==} to it. */ - private static final TupleTag UNTYPED_ITERABLE_TAG = new TupleTag<>(ITERABLE_TAG.getId()); - - /** - * A {@link PCollectionView} using {@link #ITERABLE_TAG} that maps the contents of a - * {@link PCollection} to the number of elements it contains. - */ - private static final PCollectionView LENGTH_VIEW_FOR_ITERABLE_TAG = - PCollectionViewTesting.testingView( - ITERABLE_TAG, - new PCollectionViewTesting.LengthViewFn(), StringUtf8Coder.of()); - - private static final int MAXIMUM_CACHE_SIZE = 1000; - - /** A {@link Cache} that is set up before each test. */ - private Cache, WeightedValue> defaultCache; - - @Before - public void setupCache() { - defaultCache = CacheBuilder.newBuilder() - .maximumWeight(MAXIMUM_CACHE_SIZE) - .weigher(Weighers.fixedWeightKeys(1)) - .build(); - } - - @Test - public void testCachingSideInputReaderAgreesWithUnderlyingReaderForSmallItem() throws Exception { - // A SideInputReader that vends fixed contents for LENGTH_VIEW_FOR_DEFAULT_TAG - // with a chosen size that fits in the maximum size of the cache. - WeightedSideInputReader reader = WeightedDirectSideInputReader.withContents( - ImmutableMap.of( - UNTYPED_ITERABLE_TAG, - WeightedValue.of( - PCollectionViewTesting.contentsInDefaultWindow("some", "small", "collection"), - MAXIMUM_CACHE_SIZE - 100))); - - // The CachingSideInputReader under test - CachingSideInputReader cachingReader = - CachingSideInputReader.of(reader, defaultCache); - - assertThat( - cachingReader.get( - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW), - equalTo( - reader.get( - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW))); - } - - @Test - public void testCachingSideInputReaderAgreesWithUnderlyingReaderForLargeItem() throws Exception { - // A SideInputReader that vends fixed contents for LENGTH_VIEW_FOR_DEFAULT_TAG - // with a chosen size that exceeds the maximum size of the cache. - WeightedSideInputReader reader = WeightedDirectSideInputReader.withContents( - ImmutableMap.of( - UNTYPED_ITERABLE_TAG, - WeightedValue.of( - PCollectionViewTesting.contentsInDefaultWindow("some", "large", "collection"), - MAXIMUM_CACHE_SIZE + 100))); - - // The CachingSideInputReader under test - CachingSideInputReader cachingReader = - CachingSideInputReader.of(reader, defaultCache); - - assertThat( - cachingReader.get( - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW), - equalTo( - reader.get( - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW))); - } - - - @Test - public void testCachingSideInputReaderCachesSmallItem() throws Exception { - // A SideInputReader that vends fixed contents for LENGTH_VIEW_FOR_DEFAULT_TAG - // with a chosen size that fits in the maximum size of the cache. - WeightedSideInputReader reader = WeightedDirectSideInputReader.withContents( - ImmutableMap.of( - UNTYPED_ITERABLE_TAG, - WeightedValue.of( - PCollectionViewTesting.contentsInDefaultWindow("hello", "goodbye"), - MAXIMUM_CACHE_SIZE - 1000))); - - // The CachingSideInputReader under test - CachingSideInputReader cachingReader = - CachingSideInputReader.of(reader, defaultCache); - - cachingReader.get( - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW); - - assertTrue( - isCached( - defaultCache, - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW)); - } - - @Test - public void testCachingSideInputReaderDoesNotCacheLargeItem() throws Exception { - // A SideInputReader that vends fixed contents for LENGTH_VIEW_FOR_DEFAULT_TAG - // with a chosen size that exceeds in the maximum size of the cache. - WeightedSideInputReader reader = WeightedDirectSideInputReader.withContents( - ImmutableMap.of( - UNTYPED_ITERABLE_TAG, - WeightedValue.of( - PCollectionViewTesting.contentsInDefaultWindow("hello", "goodbye"), - MAXIMUM_CACHE_SIZE + 100))); - - // The CachingSideInputReader under test - CachingSideInputReader cachingReader = - CachingSideInputReader.of(reader, defaultCache); - - cachingReader.get( - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW); - - assertFalse( - isCached( - defaultCache, - LENGTH_VIEW_FOR_ITERABLE_TAG, - PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW)); - } - - @Test - public void testCachingSideInputReaderEmpty() throws Exception { - TupleTag>> tag = new TupleTag<>(); - PCollectionView view = PCollectionViewTesting.testingView( - tag, new PCollectionViewTesting.LengthViewFn(), StringUtf8Coder.of()); - - CachingSideInputReader sideInputReader = - CachingSideInputReader.of(WeightedDirectSideInputReader.withContents( - ImmutableMap., WeightedValue>of()), - defaultCache); - - assertFalse(sideInputReader.contains(view)); - assertTrue(sideInputReader.isEmpty()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFnTest.java deleted file mode 100644 index 973c355567..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFnTest.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; -import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.DeterministicStandardCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.Receiver; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.MoreObjects; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -/** - * Tests for CombineValuesFn. - */ -@RunWith(JUnit4.class) -public class CombineValuesFnTest { - /** Example AccumulatingCombineFn. */ - public static class MeanInts extends - Combine.AccumulatingCombineFn { - - class CountSum implements - Combine.AccumulatingCombineFn.Accumulator { - - long count; - double sum; - - @Override - public void addInput(Integer element) { - count++; - sum += element.doubleValue(); - } - - @Override - public void mergeAccumulator(CountSum accumulator) { - count += accumulator.count; - sum += accumulator.sum; - } - - @Override - public String extractOutput() { - return String.format("%.1f", count == 0 ? 0.0 : sum / count); - } - - public CountSum(long count, double sum) { - this.count = count; - this.sum = sum; - } - - @Override - public int hashCode() { - return Objects.hash(count, sum); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof CountSum)) { - return false; - } - CountSum other = (CountSum) obj; - return (this.count == other.count) - && (Math.abs(this.sum - other.sum) < 0.1); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("count", count) - .add("sum", sum) - .toString(); - } - } - - @Override - public CountSum createAccumulator() { - return new CountSum(0, 0.0); - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder inputCoder) { - return new CountSumCoder(); - } - } - - /** - * An example "cheap" accumulator coder. - */ - public static class CountSumCoder extends DeterministicStandardCoder { - public CountSumCoder() { } - - @Override - public void encode( - MeanInts.CountSum value, OutputStream outStream, Context context) - throws CoderException, IOException { - DataOutputStream dataStream = new DataOutputStream(outStream); - dataStream.writeLong(value.count); - dataStream.writeDouble(value.sum); - } - - @Override - public MeanInts.CountSum decode(InputStream inStream, Context context) - throws CoderException, IOException { - DataInputStream dataStream = new DataInputStream(inStream); - long count = dataStream.readLong(); - double sum = dataStream.readDouble(); - return (new MeanInts ()).new CountSum(count, sum); - } - - @Override - public CloudObject asCloudObject() { - return makeCloudEncoding(this.getClass().getName()); - } - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public boolean isRegisterByteSizeObserverCheap( - MeanInts.CountSum value, Context context) { - return true; - } - - @Override - public void registerByteSizeObserver( - MeanInts.CountSum value, ElementByteSizeObserver observer, Context ctx) - throws Exception { - observer.update((long) 16); - } - } - - static class TestReceiver implements Receiver { - List receivedElems = new ArrayList<>(); - - @Override - public void process(Object outputElem) { - receivedElems.add(outputElem); - } - } - - private static final ParDoFnFactory parDoFnFactory = new CombineValuesFn.Factory(); - - @SuppressWarnings("rawtypes") - private static ParDoFn createCombineValuesFn( - String phase, Combine.KeyedCombineFn combineFn, Coder accumCoder) throws Exception { - // This partially mirrors the work that - // com.google.cloud.dataflow.sdk.transforms.Combine.translateHelper - // does, at least for the KeyedCombineFn. The phase is generated - // by the back-end. - CloudObject spec = CloudObject.forClassName("CombineValuesFn"); - @SuppressWarnings("unchecked") - AppliedCombineFn appliedCombineFn = - AppliedCombineFn.withAccumulatorCoder(combineFn, accumCoder); - addString(spec, PropertyNames.SERIALIZED_FN, - byteArrayToJsonString(serializeToByteArray(appliedCombineFn))); - addString(spec, PropertyNames.PHASE, phase); - - return parDoFnFactory.create( - PipelineOptionsFactory.create(), - spec, - "name", - "transformName", - null, // no side inputs - null, // no side outputs - 1, // single main output - BatchModeExecutionContext.fromOptions(PipelineOptionsFactory.create()), - (new CounterSet()).getAddCounterMutator(), - null); - } - - @Test - public void testCombineValuesFnAll() throws Exception { - TestReceiver receiver = new TestReceiver(); - - Combine.KeyedCombineFn combiner = - (new MeanInts()).asKeyedFn(); - - ParDoFn combineParDoFn = createCombineValuesFn( - CombineValuesFn.CombinePhase.ALL, combiner, new CountSumCoder()); - - combineParDoFn.startBundle(receiver); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("a", Arrays.asList(5, 6, 7)))); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("b", Arrays.asList(1, 3, 7)))); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("c", Arrays.asList(3, 6, 8, 9)))); - combineParDoFn.finishBundle(); - - Object[] expectedReceivedElems = { - WindowedValue.valueInGlobalWindow(KV.of("a", String.format("%.1f", 6.0))), - WindowedValue.valueInGlobalWindow(KV.of("b", String.format("%.1f", 3.7))), - WindowedValue.valueInGlobalWindow(KV.of("c", String.format("%.1f", 6.5))), - }; - assertArrayEquals(expectedReceivedElems, receiver.receivedElems.toArray()); - } - - @Test - public void testCombineValuesFnAdd() throws Exception { - TestReceiver receiver = new TestReceiver(); - MeanInts mean = new MeanInts(); - - Combine.KeyedCombineFn combiner = mean.asKeyedFn(); - - ParDoFn combineParDoFn = createCombineValuesFn( - CombineValuesFn.CombinePhase.ADD, combiner, new CountSumCoder()); - - combineParDoFn.startBundle(receiver); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("a", Arrays.asList(5, 6, 7)))); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("b", Arrays.asList(1, 3, 7)))); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("c", Arrays.asList(3, 6, 8, 9)))); - combineParDoFn.finishBundle(); - - Object[] expectedReceivedElems = { - WindowedValue.valueInGlobalWindow(KV.of("a", mean.new CountSum(3, 18))), - WindowedValue.valueInGlobalWindow(KV.of("b", mean.new CountSum(3, 11))), - WindowedValue.valueInGlobalWindow(KV.of("c", mean.new CountSum(4, 26))) - }; - assertArrayEquals(expectedReceivedElems, receiver.receivedElems.toArray()); - } - - @Test - public void testCombineValuesFnMerge() throws Exception { - TestReceiver receiver = new TestReceiver(); - MeanInts mean = new MeanInts(); - - Combine.KeyedCombineFn combiner = mean.asKeyedFn(); - - ParDoFn combineParDoFn = createCombineValuesFn( - CombineValuesFn.CombinePhase.MERGE, combiner, new CountSumCoder()); - - combineParDoFn.startBundle(receiver); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("a", - Arrays.asList( - mean.new CountSum(3, 6), - mean.new CountSum(2, 9), - mean.new CountSum(1, 12))))); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("b", - Arrays.asList( - mean.new CountSum(2, 20), - mean.new CountSum(1, 1))))); - combineParDoFn.finishBundle(); - - Object[] expectedReceivedElems = { - WindowedValue.valueInGlobalWindow(KV.of("a", mean.new CountSum(6, 27))), - WindowedValue.valueInGlobalWindow(KV.of("b", mean.new CountSum(3, 21))), - }; - assertArrayEquals(expectedReceivedElems, receiver.receivedElems.toArray()); - } - - @Test - public void testCombineValuesFnExtract() throws Exception { - TestReceiver receiver = new TestReceiver(); - MeanInts mean = new MeanInts(); - - Combine.KeyedCombineFn combiner = mean.asKeyedFn(); - - ParDoFn combineParDoFn = createCombineValuesFn( - CombineValuesFn.CombinePhase.EXTRACT, combiner, new CountSumCoder()); - - combineParDoFn.startBundle(receiver); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("a", mean.new CountSum(6, 27)))); - combineParDoFn.processElement(WindowedValue.valueInGlobalWindow( - KV.of("b", mean.new CountSum(3, 21)))); - combineParDoFn.finishBundle(); - - assertArrayEquals( - new Object[]{ WindowedValue.valueInGlobalWindow(KV.of("a", String.format("%.1f", 4.5))), - WindowedValue.valueInGlobalWindow(KV.of("b", String.format("%.1f", 7.0))) }, - receiver.receivedElems.toArray()); - } - - @Test - public void testCombineValuesFnCoders() throws Exception { - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - - MeanInts meanInts = new MeanInts(); - MeanInts.CountSum countSum = meanInts.new CountSum(6, 27); - - Coder coder = meanInts.getAccumulatorCoder( - registry, registry.getDefaultCoder(TypeDescriptor.of(Integer.class))); - - assertEquals( - countSum, - CoderUtils.decodeFromByteArray(coder, - CoderUtils.encodeToByteArray(coder, countSum))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java deleted file mode 100644 index dce6e9f15f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactoryTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addList; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Test for {@code ConcatReaderFactory}. - */ -@RunWith(JUnit4.class) -public class ConcatReaderFactoryTest { - - Source createSourcesWithInMemorySources(List> allData) { - List> sourcesList = new ArrayList<>(); - Source source = new Source(); - - for (List data : allData) { - CloudObject inMemorySourceSpec = CloudObject.forClassName("InMemorySource"); - - Map inMemorySourceDictionary = new HashMap<>(); - addStringList(inMemorySourceSpec, PropertyNames.ELEMENTS, data); - addLong(inMemorySourceSpec, PropertyNames.START_INDEX, 0L); - addLong(inMemorySourceSpec, PropertyNames.END_INDEX, data.size()); - - inMemorySourceDictionary.put(PropertyNames.SOURCE_SPEC, inMemorySourceSpec); - - CloudObject textSourceEncoding = makeCloudEncoding("StringUtf8Coder"); - inMemorySourceDictionary.put(PropertyNames.ENCODING, textSourceEncoding); - - sourcesList.add(inMemorySourceDictionary); - } - CloudObject spec = CloudObject.forClassName("ConcatSource"); - addList(spec, PropertyNames.CONCAT_SOURCE_SOURCES, sourcesList); - - source.setSpec(spec); - return source; - } - - private List> createInMemorySourceData(int numSources, int dataPerSource) { - List> allData = new ArrayList<>(); - for (int i = 0; i < numSources; i++) { - List data = new ArrayList<>(); - for (int j = 0; j < dataPerSource; j++) { - data.add("data j of source i"); - } - allData.add(data); - } - return allData; - } - - @Test - public void testCreateConcatReaderWithOneSubSource() throws Exception { - List> allData = createInMemorySourceData(1, 10); - - Source source = createSourcesWithInMemorySources(allData); - - @SuppressWarnings("unchecked") - NativeReader reader = - (NativeReader) - ReaderRegistry.defaultRegistry().create(source, null, null, null, null); - assertNotNull(reader); - - List expected = new ArrayList<>(); - for (List data : allData) { - expected.addAll(data); - } - assertThat(readAllFromReader(reader), containsInAnyOrder(expected.toArray())); - } - - @Test - public void testCreateConcatReaderWithManySubSources() throws Exception { - List> allData = createInMemorySourceData(15, 10); - - Source source = createSourcesWithInMemorySources(allData); - - @SuppressWarnings("unchecked") - NativeReader reader = - (NativeReader) - ReaderRegistry.defaultRegistry().create(source, null, null, null, null); - assertNotNull(reader); - - List expected = new ArrayList<>(); - for (List data : allData) { - expected.addAll(data); - } - - assertThat(readAllFromReader(reader), containsInAnyOrder(expected.toArray())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java deleted file mode 100644 index c38611ba4b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderTest.java +++ /dev/null @@ -1,471 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtConcatPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils.readAllFromReader; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.DynamicSplitResult; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * Tests for {@code ConcatReader}. - */ -@RunWith(JUnit4.class) -public class ConcatReaderTest { - private static final String READER_OBJECT = "reader_object"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - private List> recordedReaders = new ArrayList<>(); - - private ReaderRegistry registry; - - @Before - public void setUp() { - recordedReaders.clear(); - registry = ReaderRegistry.defaultRegistry() - .register(TestReader.class.getName(), new TestReaderFactory()); - } - - /** - * A {@link NativeReader} used for testing purposes. Delegates functionality to an underlying - * {@link InMemoryReader}. - */ - public class TestReader extends NativeReader { - private final long recordToFailAt; - private final boolean failWhenClosing; - private TestIterator lastIterator = null; - private final NativeReader readerDelegator; - - /** - * Create a TestReader. - * - * @param encodedElements list of elements read by the {@code Reader} - * @param coder {@code Coder} to by used by the underlying {@code Reader} - * @param recordToFailAt if non-negative, a {@code TestIterator} will fail throwing an {@code - * IOException} when trying to read the element at this index - * @param failWhenClosing if {@code true}, a {@code TestIterator} will fail throwing an {@code - * IOException} when {@link TestIterator#close()} is invoked - */ - public TestReader(List encodedElements, Coder coder, long recordToFailAt, - boolean failWhenClosing) { - this.recordToFailAt = recordToFailAt; - this.failWhenClosing = failWhenClosing; - readerDelegator = new InMemoryReader<>(encodedElements, 0, encodedElements.size(), coder); - recordedReaders.add(this); - } - - public boolean isClosedOrUnopened() { - if (lastIterator != null) { - return lastIterator.isClosed; - } - - // A reader was not created - return true; - } - - @Override - public NativeReaderIterator iterator() throws IOException { - lastIterator = new TestIterator(readerDelegator.iterator()); - return lastIterator; - } - - private class TestIterator extends NativeReaderIterator { - private final NativeReaderIterator iteratorImpl; - private long currentIndex = -1; - private boolean isClosed = false; - - private TestIterator(NativeReaderIterator iteratorImpl) { - this.iteratorImpl = iteratorImpl; - } - - @Override - public boolean start() throws IOException { - currentIndex++; - if (currentIndex == recordToFailAt) { - throw new IOException("Failing at record " + currentIndex); - } - return iteratorImpl.start(); - } - - @Override - public boolean advance() throws IOException { - currentIndex++; - if (currentIndex == recordToFailAt) { - throw new IOException("Failing at record " + currentIndex); - } - return iteratorImpl.advance(); - } - - @Override - public T getCurrent() throws NoSuchElementException { - return iteratorImpl.getCurrent(); - } - - @Override - public void close() throws IOException { - isClosed = true; - if (failWhenClosing) { - throw new IOException("Failing when closing"); - } - iteratorImpl.close(); - } - - @Override - public Progress getProgress() { - return iteratorImpl.getProgress(); - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest request) { - throw new UnsupportedOperationException(); - } - - @Override - public double getRemainingParallelism() { - return Double.NaN; - } - } - } - - private static class TestReaderFactory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - NativeReader reader = (NativeReader) spec.get(READER_OBJECT); - return reader; - } - } - - private TestReader createTestReader(long recordsPerReader, long recordToFailAt, - boolean failWhenClosing, List expectedData) throws Exception { - List records = new ArrayList<>(); - for (int i = 0; i < recordsPerReader; i++) { - String record = "Record" + i; - records.add(record); - if (recordToFailAt < 0 || i < recordToFailAt) { - expectedData.add(record); - } - } - - return new TestReader(records, StringUtf8Coder.of(), recordToFailAt, failWhenClosing); - } - - private static void assertAllOpenReadersClosed(List> readers) { - for (TestReader reader : readers) { - if (!reader.isClosedOrUnopened()) { - throw new AssertionError("At least one reader was not closed"); - } - } - } - - private Source createSourceForTestReader(TestReader testReader) { - Source source = new Source(); - CloudObject specObj = CloudObject.forClass(TestReader.class); - specObj.put(READER_OBJECT, testReader); - source.setSpec(specObj); - return source; - } - - private ConcatReader createConcatReadersOfSizes( - List expected, int... recordsPerReader) throws Exception { - List sourceList = new ArrayList<>(); - - for (int items : recordsPerReader) { - sourceList.add(createSourceForTestReader(createTestReader( - items /* recordsPerReader */, - -1 /* recordToFailAt */, - false /* failWhenClosing */, - expected))); - } - return new ConcatReader<>( - registry, - null /* options */, - null /* executionContext */, - null /* addCounterMutator */, - null /* operationName */, - sourceList); - } - - private void testReadersOfSizes(int... recordsPerReader) throws Exception { - List expected = new ArrayList<>(); - ConcatReader concatReader = createConcatReadersOfSizes(expected, recordsPerReader); - assertThat(readAllFromReader(concatReader), containsInAnyOrder(expected.toArray())); - assertEquals(recordedReaders.size(), recordsPerReader.length); - assertAllOpenReadersClosed(recordedReaders); - } - - @Test - public void testCreateFromNull() throws Exception { - expectedException.expect(NullPointerException.class); - new ConcatReader( - registry, - null /* options */, - null /* executionContext */, - null /* addCounterMutator */, - null /* operationName */, - null /* sources */); - } - - @Test - public void testReadEmptyList() throws Exception { - ConcatReader concat = - new ConcatReader<>( - registry, - null /* options */, - null /* executionContext */, - null /* addCounterMutator */, - null /* operationName */, - new ArrayList()); - ConcatReader.ConcatIterator iterator = concat.iterator(); - assertNotNull(iterator); - assertFalse(concat.iterator().start()); - - expectedException.expect(NoSuchElementException.class); - iterator.getCurrent(); - } - - @Test - public void testReadOne() throws Exception { - testReadersOfSizes(100); - } - - @Test - public void testReadMulti() throws Exception { - testReadersOfSizes(10, 5, 20, 40); - } - - @Test - public void testReadFirstReaderEmpty() throws Exception { - testReadersOfSizes(0, 5, 20, 40); - } - - @Test - public void testReadLastReaderEmpty() throws Exception { - testReadersOfSizes(10, 5, 20, 0); - } - - @Test - public void testEmptyReaderBeforeNonEmptyReader() throws Exception { - testReadersOfSizes(10, 0, 20, 30); - } - - @Test - public void testMultipleReadersAreEmpty() throws Exception { - testReadersOfSizes(10, 0, 20, 0, 30, 0, 40); - } - - @Test - public void testAReaderFailsAtClose() throws Exception { - List expected = new ArrayList<>(); - List sources = Arrays.asList( - createSourceForTestReader(createTestReader(10 /* recordsPerReader */, - -1 /* recordToFailAt */, false /* failWhenClosing */, expected)), - createSourceForTestReader(createTestReader(10 /* recordsPerReader */, - -1 /* recordToFailAt */, true /* failWhenClosing */, expected)), - createSourceForTestReader(createTestReader(10/* recordsPerReader */, -1/* recordToFailAt */, - false/* failWhenClosing */, new ArrayList()))); - - ConcatReader concatReader = new ConcatReader<>( - registry, - null /* options */, - null /* executionContext */, - null /* addCounterMutator */, - null /* operationName */, - sources); - try { - readAllFromReader(concatReader); - fail(); - } catch (IOException e) { - assertEquals(3, recordedReaders.size()); - assertAllOpenReadersClosed(recordedReaders); - } - } - - @Test - public void testReaderFailsAtRead() throws Exception { - List expected = new ArrayList<>(); - List sources = Arrays.asList( - createSourceForTestReader(createTestReader(10 /* recordsPerReader */, - -1 /* recordToFailAt */, false /* failWhenClosing */, expected)), - createSourceForTestReader(createTestReader(10 /* recordsPerReader */, - 6 /* recordToFailAt */, false /* failWhenClosing */, expected)), - createSourceForTestReader(createTestReader(10 /* recordsPerReader */, - -1 /* recordToFailAt */, false /* failWhenClosing */, expected))); - expected = expected.subList(0, 16); - assertEquals(16, expected.size()); - - ConcatReader concatReader = new ConcatReader<>( - registry, - null /* options */, - null /* executionContext */, - null /* addCounterMutator */, - null /* operationName */, - sources); - try { - readAllFromReader(concatReader); - fail(); - } catch (IOException e) { - assertEquals(3, recordedReaders.size()); - assertAllOpenReadersClosed(recordedReaders); - } - } - - private void runProgressTest(int... sizes) throws Exception { - ConcatReader concatReader = createConcatReadersOfSizes(new ArrayList(), sizes); - try (ConcatReader.ConcatIterator iterator = concatReader.iterator()) { - for (int readerIndex = 0; readerIndex < sizes.length; readerIndex++) { - for (int recordIndex = 0; recordIndex < sizes[readerIndex]; recordIndex++) { - if (readerIndex == 0 && recordIndex == 0) { - iterator.start(); - } else { - iterator.advance(); - } - ApproximateReportedProgress progress = - readerProgressToCloudProgress(iterator.getProgress()); - assertEquals( - readerIndex, progress.getPosition().getConcatPosition().getIndex().intValue()); - } - } - } - } - - @Test - public void testGetProgressSingle() throws Exception { - runProgressTest(10); - } - - @Test - public void testGetProgressSameSize() throws Exception { - runProgressTest(10, 10, 10); - } - - @Test - public void testGetProgressDifferentSizes() throws Exception { - runProgressTest(10, 30, 20, 15, 7); - } - - // This is an exhaustive test for method ConcatIterator#splitAtPosition. - // Given an array of reader sizes of length 's' this method exhaustively create ConcatReaders that - // have read up to every possible position. For each position 'p', this method creates a set of - // ConcatReaders of size 's+1' that have read up to position 'p' and tests splitting those - // ConcatReaders for index positions in the range [0, s]. - public void runUpdateStopPositionTest(int... readerSizes) throws Exception { - ConcatReader concatReader = - createConcatReadersOfSizes(new ArrayList(), readerSizes); - - // This includes indexToSplit == sizes.length case to test out of range split requests. - for (int indexToSplit = 0; indexToSplit <= readerSizes.length; indexToSplit++) { - int recordsToRead = -1; // Number of records to read from the ConcatReader before splitting. - for (int readerIndex = 0; readerIndex < readerSizes.length; readerIndex++) { - for (int recordIndex = 0; recordIndex <= readerSizes[readerIndex]; recordIndex++) { - if (readerIndex > 0 && recordIndex == 0) { - // This is an invalid state as far as ConcatReader is concerned. - // When we have not read any records from the reader at 'readerIndex', current reader - // should be the reader at 'readerIndex - 1'. - continue; - } - - recordsToRead++; - - NativeReader.NativeReaderIterator iterator = concatReader.iterator(); - for (int i = 0; i < recordsToRead; i++) { - if (i == 0) { - iterator.start(); - } else { - iterator.advance(); - } - } - - DynamicSplitResult splitResult = - iterator.requestDynamicSplit(splitRequestAtConcatPosition(indexToSplit, null)); - - // We will not be able to successfully perform the request to dynamically split (and hence - // splitResult will be null) in following cases. - // * recordsToRead == 0 - ConcatReader has not started reading - // * readerIndex >= indexToSplit - ConcatReader has already read at least one record from - // reader proposed in the split request. - // * indexToSplit < 0 || indexToSplit >= sizes.length - split position is out of range - - if ((recordsToRead == 0) || (readerIndex >= indexToSplit) - || (indexToSplit < 0 || indexToSplit >= readerSizes.length)) { - assertNull(splitResult); - } else { - assertEquals( - indexToSplit, - positionFromSplitResult(splitResult).getConcatPosition().getIndex().intValue()); - } - } - } - } - } - - @Test - public void testUpdateStopPositionSingle() throws Exception { - runUpdateStopPositionTest(10); - } - - @Test - public void testUpdateStopPositionSameSize() throws Exception { - runUpdateStopPositionTest(10, 10, 10); - } - - @Test - public void testUpdateStopPositionDifferentSizes() throws Exception { - runUpdateStopPositionTest(10, 30, 20, 15, 7); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannelTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannelTest.java deleted file mode 100644 index 0091d7710d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannelTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Preconditions.checkArgument; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SeekableByteChannel; - -/** Unit tests for {@link CopyableSeekableByteChannel}. */ -@RunWith(JUnit4.class) -public final class CopyableSeekableByteChannelTest { - @Test - public void copiedChannelShouldMaintainIndependentPosition() - throws IOException { - ByteBuffer dst = ByteBuffer.allocate(6); - SeekableByteChannel base = - new FakeSeekableByteChannel("Hello, world! :-)".getBytes()); - base.position(1); - - try (CopyableSeekableByteChannel chan = new CopyableSeekableByteChannel(base)) { - assertThat(chan.position(), equalTo((long) 1)); - - CopyableSeekableByteChannel copy = chan.copy(); - assertThat(copy.position(), equalTo((long) 1)); - - assertThat(chan.read(dst), equalTo(6)); - assertThat(chan.position(), equalTo((long) 7)); - assertThat(new String(dst.array()), equalTo("ello, ")); - dst.rewind(); - - assertThat(copy.position(), equalTo((long) 1)); - copy.position(3); - assertThat(copy.read(dst), equalTo(6)); - assertThat(copy.position(), equalTo((long) 9)); - assertThat(new String(dst.array()), equalTo("lo, wo")); - dst.rewind(); - - assertThat(chan.read(dst), equalTo(6)); - assertThat(chan.position(), equalTo((long) 13)); - assertThat(new String(dst.array()), equalTo("world!")); - dst.rewind(); - - assertThat(chan.read(dst), equalTo(4)); - assertThat(chan.position(), equalTo((long) 17)); - assertThat(new String(dst.array()), equalTo(" :-)d!")); - dst.rewind(); - - assertThat(copy.position(), equalTo((long) 9)); - assertThat(copy.read(dst), equalTo(6)); - assertThat(new String(dst.array()), equalTo("rld! :")); - } - } - - private static final class FakeSeekableByteChannel - implements SeekableByteChannel { - private boolean closed = false; - private ByteBuffer data; - - public FakeSeekableByteChannel(byte[] data) { - this.data = ByteBuffer.wrap(data); - } - - @Override - public long position() throws IOException { - checkClosed(); - return data.position(); - } - - @Override - public SeekableByteChannel position(long newPosition) throws IOException { - checkArgument(newPosition >= 0); - checkClosed(); - data.position((int) newPosition); - return this; - } - - @Override - public int read(ByteBuffer dst) throws IOException { - checkClosed(); - if (!data.hasRemaining()) { - return -1; - } - int count = Math.min(data.remaining(), dst.remaining()); - ByteBuffer src = data.slice(); - src.limit(count); - dst.put(src); - data.position(data.position() + count); - return count; - } - - @Override - public long size() throws IOException { - checkClosed(); - return data.limit(); - } - - @Override - public SeekableByteChannel truncate(long size) throws IOException { - checkClosed(); - data.limit((int) size); - return this; - } - - @Override - public int write(ByteBuffer src) throws IOException { - checkClosed(); - int count = Math.min(data.remaining(), src.remaining()); - ByteBuffer copySrc = src.slice(); - copySrc.limit(count); - data.put(copySrc); - return count; - } - - @Override - public boolean isOpen() { - return !closed; - } - - @Override - public void close() { - closed = true; - } - - private void checkClosed() throws ClosedChannelException { - if (closed) { - throw new ClosedChannelException(); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReaderTest.java deleted file mode 100644 index 90c55273a5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReaderTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.PCollectionViewTesting; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests for {@link DataflowSideInputReader}. - */ -@RunWith(JUnit4.class) -public class DataflowSideInputReaderTest { - - private static final Coder LONG_CODER = BigEndianLongCoder.of(); - private static final TupleTag>> DEFAULT_TAG = new TupleTag<>(); - private static final PCollectionView DEFAULT_LENGTH_VIEW = - PCollectionViewTesting.testingView( - DEFAULT_TAG, new PCollectionViewTesting.LengthViewFn(), LONG_CODER); - - private static final List DEFAULT_SOURCE_CONTENTS = - ImmutableList.of(1L, -43255L, 0L, 13L, 1975858L); - - private static final long DEFAULT_SOURCE_LENGTH = DEFAULT_SOURCE_CONTENTS.size(); - private static final IntervalWindow OTHER_WINDOW = - new IntervalWindow(new Instant(50000L), new Instant(60000L)); - private PipelineOptions options = PipelineOptionsFactory.create(); - private static ExecutionContext executionContext; - private SideInputInfo defaultSideInputInfo; - private DataflowSideInputReader defaultSideInputReader; - - /** - * Creates a {@link Source} descriptor for reading the provided contents as a side input. - * - *

    If the {@code PCollectionView} has an incompatible {@code Coder} or - * {@code WindowingStrategy}, then results are unpredictable. - */ - private final Source sourceInMultipleWindows(PCollectionView view, Iterable values) - throws Exception { - List> windowedValues = ImmutableList.>builder() - .addAll(PCollectionViewTesting.contentsInDefaultWindow(values)) - // We add the values twice within the other window so there are a different number - // then in the default window. - .addAll(contentsInWindow(values, OTHER_WINDOW)) - .addAll(contentsInWindow(values, OTHER_WINDOW)) - .build(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - List> componentCoders = (List) view.getCoderInternal().getCoderArguments(); - if (componentCoders == null || componentCoders.size() != 1) { - throw new Exception("Could not extract element Coder from " + view.getCoderInternal()); - } - @SuppressWarnings("unchecked") - Coder> elemCoder = (Coder>) componentCoders.get(0); - - return InMemoryReaderFactoryTest.createInMemoryCloudSource( - windowedValues, null, null, elemCoder); - } - - /** - * The size, in bytes, of a {@code long} placed in - * {@link PCollectionViewTesting#DEFAULT_NONEMPTY_WINDOW}. This is the size of each of the - * elements of each {@code PCollection} created in the following tests. - * - *

    This value is arbitrary from the point of view of these tests. - * The correctness of {@link DataflowSideInputReader} does not depend on this value, - * but depends on the fact that the reported sizes are this value times the number - * of elements in a collection. - */ - private long windowedLongBytes() throws Exception { - long arbitraryLong = 42L; - return CoderUtils.encodeToByteArray( - PCollectionViewTesting.defaultWindowedValueCoder(LONG_CODER), - PCollectionViewTesting.valueInDefaultWindow(arbitraryLong)).length; - } - - /** - * Prepares {@code values} for reading as the contents of a {@link PCollectionView} side input. - */ - private static Iterable> contentsInWindow(Iterable values, - BoundedWindow window) throws Exception { - List> windowedValues = Lists.newArrayList(); - for (T value : values) { - windowedValues.add( - WindowedValue.of(value, window.maxTimestamp().minus(1), window, PaneInfo.NO_FIRING)); - } - return windowedValues; - } - - @Before - public void setUp() throws Exception { - options = PipelineOptionsFactory.create(); - executionContext = BatchModeExecutionContext.fromOptions(options); - - defaultSideInputInfo = SideInputUtils.createCollectionSideInputInfo( - sourceInMultipleWindows(DEFAULT_LENGTH_VIEW, DEFAULT_SOURCE_CONTENTS)); - defaultSideInputInfo.setTag(DEFAULT_LENGTH_VIEW.getTagInternal().getId()); - - defaultSideInputReader = DataflowSideInputReader.of( - Collections.singletonList(defaultSideInputInfo), options, executionContext); - } - - /** - * Tests that when a {@link PCollectionView} is actually available in a - * {@link DataflowSideInputReader}, it does not claim to be empty. - */ - @Test - public void testDataflowSideInputReaderNotEmpty() throws Exception { - assertFalse(defaultSideInputReader.isEmpty()); - } - - /** - * Tests that when a {@link PCollectionView} is actually available in a - * {@link DataflowSideInputReader}, the read succeeds and has the right size. - */ - @Test - public void testDataflowSideInputReaderFilteredRead() throws Exception { - assertTrue(defaultSideInputReader.contains(DEFAULT_LENGTH_VIEW)); - WeightedValue sizedValue = defaultSideInputReader.getWeighted( - DEFAULT_LENGTH_VIEW, PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW); - assertThat(sizedValue.getValue(), equalTo(DEFAULT_SOURCE_LENGTH)); - assertThat(sizedValue.getWeight(), equalTo(DEFAULT_SOURCE_LENGTH * windowedLongBytes())); - } - - /** - * Tests that when a {@link PCollectionView} is actually available in a - * {@link DataflowSideInputReader}, repeated reads yield the same value with the same size. - */ - @Test - public void testDataflowSideInputReaderRepeatedRead() throws Exception { - DataflowSideInputReader sideInputReader = DataflowSideInputReader.of( - Collections.singletonList(defaultSideInputInfo), options, executionContext); - - WeightedValue firstRead = sideInputReader.getWeighted( - DEFAULT_LENGTH_VIEW, PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW); - - // A repeated read should yield the same size. - WeightedValue repeatedRead = sideInputReader.getWeighted( - DEFAULT_LENGTH_VIEW, PCollectionViewTesting.DEFAULT_NONEMPTY_WINDOW); - - assertThat(repeatedRead.getValue(), equalTo(firstRead.getValue())); - assertThat(repeatedRead.getWeight(), equalTo(firstRead.getWeight())); - - } - - @Test - public void testDataflowSideInputReaderMiss() throws Exception { - DataflowSideInputReader sideInputReader = DataflowSideInputReader.of( - Collections.singletonList(defaultSideInputInfo), options, executionContext); - - // Reading an empty window yields the size of 0 elements. - WeightedValue emptyWindowValue = sideInputReader.getWeighted( - DEFAULT_LENGTH_VIEW, PCollectionViewTesting.DEFAULT_EMPTY_WINDOW); - assertThat(emptyWindowValue.getValue(), equalTo(0L)); - assertThat(emptyWindowValue.getWeight(), equalTo(0L)); - } - - /** - * Tests that when a {@link PCollectionView} is not available in a - * {@link DataflowSideInputReader}, it is reflected properly. - */ - @Test - public void testDataflowSideInputReaderBadRead() throws Exception { - SideInputInfo sideInputInfo = SideInputUtils.createCollectionSideInputInfo( - sourceInMultipleWindows(DEFAULT_LENGTH_VIEW, DEFAULT_SOURCE_CONTENTS)); - sideInputInfo.setTag("not the same tag at all"); - - DataflowSideInputReader sideInputReader = DataflowSideInputReader.of( - Arrays.asList(sideInputInfo), options, executionContext); - - assertFalse(sideInputReader.contains(DEFAULT_LENGTH_VIEW)); - } - - /** - * Tests that when a {@link PCollectionView} is not available in a - * {@link DataflowSideInputReader}, it is reflected properly. - */ - @Test - public void testDataflowSideInputEmpty() throws Exception { - DataflowSideInputReader sideInputReader = DataflowSideInputReader.of( - Collections.emptyList(), options, executionContext); - assertTrue(sideInputReader.isEmpty()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DatastoreReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DatastoreReaderTest.java deleted file mode 100644 index c4d031b64e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DatastoreReaderTest.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.services.datastore.client.DatastoreHelper.makeProperty; -import static com.google.api.services.datastore.client.DatastoreHelper.makeValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.api.services.datastore.DatastoreV1.Entity; -import com.google.api.services.datastore.DatastoreV1.EntityResult; -import com.google.api.services.datastore.DatastoreV1.EntityResult.ResultType; -import com.google.api.services.datastore.DatastoreV1.Query; -import com.google.api.services.datastore.DatastoreV1.QueryResultBatch; -import com.google.api.services.datastore.DatastoreV1.QueryResultBatch.MoreResultsType; -import com.google.api.services.datastore.DatastoreV1.RunQueryRequest; -import com.google.api.services.datastore.DatastoreV1.RunQueryResponse; -import com.google.api.services.datastore.client.Datastore; -import com.google.api.services.datastore.client.DatastoreException; -import com.google.cloud.dataflow.sdk.io.DatastoreIO; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentMatcher; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * Unit tests for {@code DatastoreSource}. - */ -@RunWith(JUnit4.class) -public class DatastoreReaderTest { - private static final String TEST_KIND = "mykind"; - private static final String TEST_PROPERTY = "myproperty"; - private static final String TEST_NAMESPACE = "mynamespace"; - - private static class IsValidRequestWithNamespace extends ArgumentMatcher { - private final String namespace; - - public IsValidRequestWithNamespace(String namespace) { - this.namespace = namespace; - } - @Override - public boolean matches(Object o) { - RunQueryRequest request = (RunQueryRequest) o; - return request.hasQuery() - && Objects.equals(request.getPartitionId().getNamespace(), namespace); - } - } - - private EntityResult createEntityResult(String val) { - Entity entity = - Entity.newBuilder().addProperty(makeProperty(TEST_PROPERTY, makeValue(val))).build(); - return EntityResult.newBuilder().setEntity(entity).build(); - } - - private Datastore buildMockDatastore() throws DatastoreException { - Datastore datastore = mock(Datastore.class); - RunQueryResponse.Builder firstResponseBuilder = RunQueryResponse.newBuilder(); - RunQueryResponse.Builder secondResponseBuilder = RunQueryResponse.newBuilder(); - RunQueryResponse.Builder thirdResponseBuilder = RunQueryResponse.newBuilder(); - RunQueryResponse.Builder firstNamespaceResponseBuilder = RunQueryResponse.newBuilder(); - { - QueryResultBatch.Builder resultsBatch = QueryResultBatch.newBuilder(); - resultsBatch.addEntityResult(0, createEntityResult("val0")); - resultsBatch.addEntityResult(1, createEntityResult("val1")); - resultsBatch.addEntityResult(2, createEntityResult("val2")); - resultsBatch.addEntityResult(3, createEntityResult("val3")); - resultsBatch.addEntityResult(4, createEntityResult("val4")); - resultsBatch.setEntityResultType(ResultType.FULL); - - resultsBatch.setMoreResults(MoreResultsType.NOT_FINISHED); - - firstResponseBuilder.setBatch(resultsBatch.build()); - } - { - QueryResultBatch.Builder resultsBatch = QueryResultBatch.newBuilder(); - resultsBatch.addEntityResult(0, createEntityResult("val5")); - resultsBatch.addEntityResult(1, createEntityResult("val6")); - resultsBatch.addEntityResult(2, createEntityResult("val7")); - resultsBatch.addEntityResult(3, createEntityResult("val8")); - resultsBatch.addEntityResult(4, createEntityResult("val9")); - resultsBatch.setEntityResultType(ResultType.FULL); - - resultsBatch.setMoreResults(MoreResultsType.NOT_FINISHED); - - secondResponseBuilder.setBatch(resultsBatch.build()); - } - { - QueryResultBatch.Builder resultsBatch = QueryResultBatch.newBuilder(); - resultsBatch.setEntityResultType(ResultType.FULL); - - resultsBatch.setMoreResults(MoreResultsType.NO_MORE_RESULTS); - - thirdResponseBuilder.setBatch(resultsBatch.build()); - } - { - QueryResultBatch.Builder resultsBatch = QueryResultBatch.newBuilder(); - resultsBatch.addEntityResult(0, createEntityResult("nsval0")); - resultsBatch.addEntityResult(1, createEntityResult("nsval1")); - resultsBatch.addEntityResult(2, createEntityResult("nsval2")); - resultsBatch.addEntityResult(3, createEntityResult("nsval3")); - resultsBatch.addEntityResult(4, createEntityResult("nsval4")); - resultsBatch.setEntityResultType(ResultType.FULL); - - resultsBatch.setMoreResults(MoreResultsType.NO_MORE_RESULTS); - - firstNamespaceResponseBuilder.setBatch(resultsBatch.build()); - } - // Without namespace - when(datastore.runQuery(argThat(new IsValidRequestWithNamespace("")))) - .thenReturn(firstResponseBuilder.build()) - .thenReturn(secondResponseBuilder.build()) - .thenReturn(thirdResponseBuilder.build()); - - // With namespace - doReturn(firstNamespaceResponseBuilder.build()).when(datastore) - .runQuery(argThat(new IsValidRequestWithNamespace(TEST_NAMESPACE))); - - return datastore; - } - - - @Test - public void testRead() throws Exception { - Datastore datastore = buildMockDatastore(); - - Query.Builder q = Query.newBuilder(); - q.addKindBuilder().setName(TEST_KIND); - Query query = q.build(); - - List entityResults = new ArrayList(); - - try (DatastoreIO.DatastoreReader iterator = - new DatastoreIO.DatastoreReader(DatastoreIO.source().withQuery(query), datastore)) { - while (iterator.advance()) { - entityResults.add(iterator.getCurrent()); - } - } - - assertEquals(10, entityResults.size()); - for (int i = 0; i < 10; i++) { - assertNotNull(entityResults.get(i).getPropertyList()); - assertEquals(entityResults.get(i).getPropertyList().size(), 1); - assertTrue(entityResults.get(i).getPropertyList().get(0).hasValue()); - assertTrue(entityResults.get(i).getPropertyList().get(0).getValue().hasStringValue()); - assertEquals( - entityResults.get(i).getPropertyList().get(0).getValue().getStringValue(), "val" + i); - } - } - - @Test - public void testReadWithNamespace() throws Exception { - Datastore datastore = buildMockDatastore(); - - Query.Builder q = Query.newBuilder(); - q.addKindBuilder().setName(TEST_KIND); - Query query = q.build(); - - List entityResults = new ArrayList(); - - try (DatastoreIO.DatastoreReader iterator = new DatastoreIO.DatastoreReader( - DatastoreIO.source().withQuery(query).withNamespace(TEST_NAMESPACE), datastore)) { - while (iterator.advance()) { - entityResults.add(iterator.getCurrent()); - } - } - - assertEquals(5, entityResults.size()); - for (int i = 0; i < 5; i++) { - assertNotNull(entityResults.get(i).getPropertyList()); - assertEquals(entityResults.get(i).getPropertyList().size(), 1); - assertTrue(entityResults.get(i).getPropertyList().get(0).hasValue()); - assertTrue(entityResults.get(i).getPropertyList().get(0).getValue().hasStringValue()); - assertEquals( - entityResults.get(i).getPropertyList().get(0).getValue().getStringValue(), "nsval" + i); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactoryTest.java deleted file mode 100644 index 8be86f71f3..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactoryTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; - -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collections; -import java.util.List; - -/** - * Tests for {@link DefaultParDoFnFactory}. - */ -@RunWith(JUnit4.class) -public class DefaultParDoFnFactoryTest { - - private static class TestDoFn extends DoFn { - final String stringField; - final long longField; - - TestDoFn(String stringValue, long longValue) { - this.stringField = stringValue; - this.longField = longValue; - } - - @Override - public void processElement(ProcessContext c) { - throw new RuntimeException("not expecting to call this"); - } - } - - // Miscellaneous default values required by the ParDoFnFactory interface - private static final ParDoFnFactory DEFAULT_FACTORY = new DefaultParDoFnFactory(); - private static final PipelineOptions DEFAULT_OPTIONS = PipelineOptionsFactory.create(); - private static final DataflowExecutionContext DEFAULT_EXECUTION_CONTEXT = - BatchModeExecutionContext.fromOptions(DEFAULT_OPTIONS); - private static final CounterSet EMPTY_COUNTER_SET = new CounterSet(); - private static final StateSampler EMPTY_STATE_SAMPLER = - new StateSampler("test", EMPTY_COUNTER_SET.getAddCounterMutator()); - - private List dummySingleOutputInfo; - - @Before - public void setUp() throws Exception { - String tag = "output"; - MultiOutputInfo multiOutputInfo = new MultiOutputInfo(); - multiOutputInfo.setTag(tag); - dummySingleOutputInfo = Collections.singletonList(multiOutputInfo); - } - - /** - * Tests that a "normal" {@link DoFn} is correctly dispatched to {@link NormalParDoFn} and - * instantiated correctly. - */ - @Test - public void testCreateNormalParDoFn() throws Exception { - // A serialized DoFn - String stringFieldValue = "some state"; - long longFieldValue = 42L; - TestDoFn fn = new TestDoFn(stringFieldValue, longFieldValue); - String serializedFn = - StringUtils.byteArrayToJsonString( - SerializableUtils.serializeToByteArray( - new DoFnInfo<>(fn, WindowingStrategy.globalDefault()))); - CloudObject cloudUserFn = CloudObject.forClassName("DoFn"); - addString(cloudUserFn, "serialized_fn", serializedFn); - - // Create the ParDoFn from the serialized DoFn - ParDoFn parDoFn = DEFAULT_FACTORY.create( - DEFAULT_OPTIONS, - cloudUserFn, - "name", - "transformName", - null, - dummySingleOutputInfo, - 1, - DEFAULT_EXECUTION_CONTEXT, - EMPTY_COUNTER_SET.getAddCounterMutator(), - EMPTY_STATE_SAMPLER); - - // Test that the factory created the correct class - assertThat(parDoFn, instanceOf(NormalParDoFn.class)); - - // TODO: move the asserts below into new tests in NormalParDoFnTest, and this test should - // simply assert that DefaultParDoFnFactory.create() matches NormalParDoFn.Factory.create() - - // Test that the DoFnInfo reflects the one passed in - NormalParDoFn normalParDoFn = (NormalParDoFn) parDoFn; - @SuppressWarnings("rawtypes") - DoFnInfo doFnInfo = normalParDoFn.getDoFnInfo(); - @SuppressWarnings("rawtypes") - DoFn actualDoFn = doFnInfo.getDoFn(); - assertThat(actualDoFn, instanceOf(TestDoFn.class)); - assertThat( - doFnInfo.getWindowingStrategy().getWindowFn(), - instanceOf(GlobalWindows.class)); - assertThat( - doFnInfo.getWindowingStrategy().getTrigger().getSpec(), - instanceOf(DefaultTrigger.class)); - - // Test that the deserialized user DoFn is as expected - TestDoFn actualTestDoFn = (TestDoFn) actualDoFn; - assertEquals(stringFieldValue, actualTestDoFn.stringField); - assertEquals(longFieldValue, actualTestDoFn.longField); - assertEquals(DEFAULT_EXECUTION_CONTEXT, normalParDoFn.getExecutionContext()); - } - - @Test - public void testCreateUnknownParDoFn() throws Exception { - // A bogus serialized DoFn - CloudObject cloudUserFn = CloudObject.forClassName("UnknownKindOfDoFn"); - try { - DEFAULT_FACTORY.create( - DEFAULT_OPTIONS, - cloudUserFn, - "name", - "transformName", - null, - null, - 1, - DEFAULT_EXECUTION_CONTEXT, - EMPTY_COUNTER_SET.getAddCounterMutator(), - EMPTY_STATE_SAMPLER); - fail("should have thrown an exception"); - } catch (Exception exn) { - assertThat( - exn.toString(), - Matchers.containsString("No known ParDoFnFactory")); - } - } - - // TODO: Test side inputs. -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/FakeWindmillServer.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/FakeWindmillServer.java deleted file mode 100644 index 1b609f044e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/FakeWindmillServer.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; -import static org.junit.Assert.assertFalse; - -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.CommitWorkResponse; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.ComputationCommitWorkRequest; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.GetDataResponse; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.GetWorkResponse; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItemCommitRequest; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServerStub; - -import java.util.Map; -import java.util.Queue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * An in-memory Windmill server that offers provided work and data. - */ -class FakeWindmillServer extends WindmillServerStub { - private Queue workToOffer; - private Queue dataToOffer; - private Map commitsReceived; - private LinkedBlockingQueue exceptions; - private int commitsRequested = 0; - private AtomicInteger expectedExceptionCount; - public FakeWindmillServer() { - workToOffer = new ConcurrentLinkedQueue(); - dataToOffer = new ConcurrentLinkedQueue(); - commitsReceived = new ConcurrentHashMap(); - exceptions = new LinkedBlockingQueue<>(); - expectedExceptionCount = new AtomicInteger(); - } - - public void addWorkToOffer(Windmill.GetWorkResponse work) { - workToOffer.add(work); - } - - public void addDataToOffer(Windmill.GetDataResponse data) { - dataToOffer.add(data); - } - - @Override - public Windmill.GetWorkResponse getWork(Windmill.GetWorkRequest request) { - Windmill.GetWorkResponse response = workToOffer.poll(); - if (response == null) { - return Windmill.GetWorkResponse.newBuilder().build(); - } - return response; - } - - @Override - public Windmill.GetDataResponse getData(Windmill.GetDataRequest request) { - Windmill.GetDataResponse response = dataToOffer.poll(); - if (response == null) { - response = Windmill.GetDataResponse.newBuilder().build(); - } else { - try { - // Sleep for a little bit to ensure that *-windmill-read state-sampled counters show up. - sleepMillis(500); - } catch (InterruptedException e) {} - } - return response; - } - - @Override - public CommitWorkResponse commitWork(Windmill.CommitWorkRequest request) { - for (ComputationCommitWorkRequest computationRequest : request.getRequestsList()) { - for (WorkItemCommitRequest commit : computationRequest.getRequestsList()) { - commitsReceived.put(commit.getWorkToken(), commit); - } - } - return CommitWorkResponse.newBuilder().build(); - } - - @Override - public Windmill.GetConfigResponse getConfig(Windmill.GetConfigRequest request) { - return Windmill.GetConfigResponse.newBuilder().build(); - } - - @Override - public Windmill.ReportStatsResponse reportStats(Windmill.ReportStatsRequest request) { - for (Windmill.Exception exception : request.getExceptionsList()) { - try { - exceptions.put(exception); - } catch (InterruptedException expected) { - } - } - - if (request.getExceptionsList().isEmpty() || expectedExceptionCount.getAndDecrement() > 0) { - return Windmill.ReportStatsResponse.newBuilder().build(); - } else { - return Windmill.ReportStatsResponse.newBuilder().setFailed(true).build(); - } - } - - - public void waitForEmptyWorkQueue() { - while (!workToOffer.isEmpty()) { - try { - Thread.sleep(1000); - } catch (InterruptedException expected) { - } - } - } - - public Map waitForAndGetCommits(int numCommits) { - int maxTries = 10; - while (maxTries-- > 0 && commitsReceived.size() < commitsRequested + numCommits) { - try { - Thread.sleep(1000); - } catch (InterruptedException expected) { - } - } - - assertFalse( - "Should have received " + numCommits + " more commits beyond " + commitsRequested - + " commits already seen, but after 10s have only seen " + commitsReceived, - commitsReceived.size() < commitsRequested + numCommits); - commitsRequested += numCommits; - - return commitsReceived; - } - - public void setExpectedExceptionCount(int i) { - expectedExceptionCount.getAndAdd(i); - } - - public Windmill.Exception getException() throws InterruptedException { - return exceptions.take(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTrackerTest.java deleted file mode 100644 index ed525330a3..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTrackerTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * icensed under the Apache icense, Version 2.0 (the "icense"); you may not - * use this file except in compliance with the icense. You may obtain a copy of - * the icense at - * - * http://www.apache.org/licenses/ICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the icense is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * icense for the specific language governing permissions and limitations under - * the icense. - ******************************************************************************/ - -package com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link GroupingShuffleRangeTracker}. - */ -@RunWith(JUnit4.class) -public class GroupingShuffleRangeTrackerTest { - @Rule - public final ExpectedException expected = ExpectedException.none(); - - private static ByteArrayShufflePosition ofBytes(int... bytes) { - byte[] b = new byte[bytes.length]; - for (int i = 0; i < bytes.length; ++i) { - b[i] = (byte) bytes[i]; - } - return ByteArrayShufflePosition.of(b); - } - - @Test - public void testTryReturnRecordInfiniteRange() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker(null, null); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 5))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(3, 6, 8, 10))); - } - - @Test - public void testTryReturnRecordFiniteRange() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(1, 0, 0), ofBytes(5, 0, 0)); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 5))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(3, 6, 8, 10))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(4, 255, 255, 255, 255))); - // Should fail on lexicographically larger positions. - assertFalse(tracker.copy().tryReturnRecordAt(true, ofBytes(5, 0, 0))); - assertFalse(tracker.copy().tryReturnRecordAt(true, ofBytes(5, 0, 1))); - assertFalse(tracker.copy().tryReturnRecordAt(true, ofBytes(6, 0, 0))); - } - - @Test - public void testTryReturnRecordWithNonSplitPoints() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(1, 0, 0), ofBytes(5, 0, 0)); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3))); - assertTrue(tracker.tryReturnRecordAt(false, ofBytes(1, 2, 3))); - assertTrue(tracker.tryReturnRecordAt(false, ofBytes(1, 2, 3))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 5))); - assertTrue(tracker.tryReturnRecordAt(false, ofBytes(1, 2, 5))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(3, 6, 8, 10))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(4, 255, 255, 255, 255))); - } - - @Test - public void testFirstRecordNonSplitPoint() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(3, 0, 0), ofBytes(5, 0, 0)); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(false, ofBytes(3, 4, 5)); - } - - @Test - public void testNonSplitPointRecordWithDifferentPosition() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(3, 0, 0), ofBytes(5, 0, 0)); - tracker.tryReturnRecordAt(true, ofBytes(3, 4, 5)); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(false, ofBytes(3, 4, 6)); - } - - @Test - public void testTryReturnRecordBeforeStart() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(3, 0, 0), ofBytes(5, 0, 0)); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3)); - } - - @Test - public void testTryReturnNonMonotonic() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(3, 0, 0), ofBytes(5, 0, 0)); - tracker.tryReturnRecordAt(true, ofBytes(3, 4, 5)); - tracker.tryReturnRecordAt(true, ofBytes(3, 4, 6)); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(true, ofBytes(3, 2, 1)); - } - - @Test - public void testTryReturnIdenticalPositions() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(3, 0, 0), ofBytes(5, 0, 0)); - tracker.tryReturnRecordAt(true, ofBytes(3, 4, 5)); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(true, ofBytes(3, 4, 5)); - } - - @Test - public void testTrySplitAtPositionInfiniteRange() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker(null, null); - // Should fail before first record is returned. - assertFalse(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6))); - - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3))); - - // Should now succeed. - assertTrue(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6))); - // Should not split at same or larger position. - assertFalse(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6))); - assertFalse(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6, 7))); - assertFalse(tracker.trySplitAtPosition(ofBytes(4, 5, 6, 7))); - - // Should split at smaller position. - assertTrue(tracker.trySplitAtPosition(ofBytes(3, 2, 1))); - - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(2, 3, 4))); - - // Should not split at a position we're already past. - assertFalse(tracker.trySplitAtPosition(ofBytes(2, 3, 4))); - assertFalse(tracker.trySplitAtPosition(ofBytes(2, 3, 3))); - - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(3, 2, 0))); - assertFalse(tracker.tryReturnRecordAt(true, ofBytes(3, 2, 1))); - } - - @Test - public void testTrySplitAtPositionFiniteRange() throws Exception { - GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker( - ofBytes(0, 0, 0), ofBytes(10, 20, 30)); - // Should fail before first record is returned. - assertFalse(tracker.trySplitAtPosition(ofBytes(0, 0, 0))); - assertFalse(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6))); - - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3))); - - // Should now succeed. - assertTrue(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6))); - // Should not split at same or larger position. - assertFalse(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6))); - assertFalse(tracker.trySplitAtPosition(ofBytes(3, 4, 5, 6, 7))); - assertFalse(tracker.trySplitAtPosition(ofBytes(4, 5, 6, 7))); - - // Should split at smaller position. - assertTrue(tracker.trySplitAtPosition(ofBytes(3, 2, 1))); - // But not at a position at or before last returned record. - assertFalse(tracker.trySplitAtPosition(ofBytes(1, 2, 3))); - - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(2, 3, 4))); - assertTrue(tracker.tryReturnRecordAt(true, ofBytes(3, 2, 0))); - assertFalse(tracker.tryReturnRecordAt(true, ofBytes(3, 2, 1))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java deleted file mode 100644 index 5fa96599af..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderTest.java +++ /dev/null @@ -1,709 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.encodeBase64URLSafeString; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.approximateSplitRequestAtPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.toDynamicSplitRequest; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.Position; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.GroupingShuffleReader.GroupingShuffleReaderIterator; -import com.google.cloud.dataflow.sdk.runners.worker.ShuffleSink.ShuffleKind; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.util.common.Reiterable; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * Tests for GroupingShuffleReader. - */ -@RunWith(JUnit4.class) -public class GroupingShuffleReaderTest { - private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; - private static final List>>> NO_KVS = - Collections.emptyList(); - - private static final Instant timestamp = new Instant(123000); - private static final IntervalWindow window = new IntervalWindow(timestamp, timestamp.plus(1000)); - - // As Shuffle records, {@code KV} is encoded as 10 records. Each records uses an integer as key - // (4 bytes), and a {@code KV} of an integer key and value (each 4 bytes). - // Overall {@code KV}s have a byte size of 25 * 4 = 100. Note that we also encode the - // timestamp into the secondary key adding another 100 bytes. - private static final List>>> KVS = Arrays.asList( - KV.of(1, Arrays.asList(KV.of(1, 11), KV.of(2, 12))), - KV.of(2, Arrays.asList(KV.of(1, 21), KV.of(2, 22))), - KV.of(3, Arrays.asList(KV.of(1, 31))), - KV.of(4, Arrays.asList(KV.of(1, 41), KV.of(2, 42), - KV.of(3, 43), KV.of(4, 44))), - KV.of(5, Arrays.asList(KV.of(1, 51)))); - - /** How many of the values with each key are to be read. - * Note that the order matters as the conversion to ordinal is used below. - */ - private enum ValuesToRead { - /** Don't even ask for the values iterator. */ - SKIP_VALUES, - /** Get the iterator, but don't read any values. */ - READ_NO_VALUES, - /** Read just the first value. */ - READ_ONE_VALUE, - /** Read all the values. */ - READ_ALL_VALUES, - /** Read all the values twice. */ - READ_ALL_VALUES_TWICE - } - - private List writeShuffleEntries( - List>>> input, boolean sortValues) - throws Exception { - Coder>>> sinkElemCoder = - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), - KvCoder.of(BigEndianIntegerCoder.of(), - BigEndianIntegerCoder.of())), - IntervalWindow.getCoder()); - CounterSet.AddCounterMutator addCounterMutator = new CounterSet().getAddCounterMutator(); - // Write to shuffle with GROUP_KEYS ShuffleSink. - ShuffleSink>> shuffleSink = - new ShuffleSink<>(PipelineOptionsFactory.create(), null, - sortValues ? ShuffleKind.GROUP_KEYS_AND_SORT_VALUES : ShuffleKind.GROUP_KEYS, - sinkElemCoder, addCounterMutator); - - TestShuffleWriter shuffleWriter = new TestShuffleWriter(); - - int kvCount = 0; - List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter>>> shuffleSinkWriter = - shuffleSink.writer(shuffleWriter, "dataset")) { - for (KV>> kvs : input) { - Integer key = kvs.getKey(); - for (KV value : kvs.getValue()) { - ++kvCount; - actualSizes.add(shuffleSinkWriter.add(WindowedValue.of( - KV.of(key, value), timestamp, Lists.newArrayList(window), PaneInfo.NO_FIRING))); - } - } - } - List records = shuffleWriter.getRecords(); - assertEquals(kvCount, records.size()); - assertEquals(shuffleWriter.getSizes(), actualSizes); - return records; - } - - private List>>> runIterationOverGroupingShuffleReader( - BatchModeExecutionContext context, TestShuffleReader shuffleReader, - GroupingShuffleReader> groupingShuffleReader, - Coder>>>> coder, - ValuesToRead valuesToRead) throws Exception { - Counter elementByteSizeCounter = Counter.longs("element-byte-size-counter", SUM); - ElementByteSizeObserver elementObserver = new ElementByteSizeObserver(elementByteSizeCounter); - List>>> actual = new ArrayList<>(); - try (GroupingShuffleReaderIterator> iter = - groupingShuffleReader.iterator(shuffleReader)) { - Iterable> prevValuesIterable = null; - Iterator> prevValuesIterator = null; - while (iter.hasNext()) { - assertTrue(iter.hasNext()); - assertTrue(iter.hasNext()); - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe co-variant cast. - WindowedValue>>> windowedValue = - (WindowedValue) iter.next(); - // Verify that the byte size observer is lazy for every value the GroupingShuffleReader - // produces. - coder.registerByteSizeObserver(windowedValue, elementObserver, Context.OUTER); - assertTrue(elementObserver.getIsLazy()); - - // Verify value is in an empty windows. - assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, windowedValue.getTimestamp()); - assertEquals(0, windowedValue.getWindows().size()); - - KV>> elem = windowedValue.getValue(); - Integer key = elem.getKey(); - List> values = new ArrayList<>(); - if (valuesToRead.ordinal() > ValuesToRead.SKIP_VALUES.ordinal()) { - if (prevValuesIterable != null) { - prevValuesIterable.iterator(); // Verifies that this does not throw. - } - if (prevValuesIterator != null) { - prevValuesIterator.hasNext(); // Verifies that this does not throw. - } - - Iterable> valuesIterable = elem.getValue(); - Iterator> valuesIterator = valuesIterable.iterator(); - - if (valuesToRead.ordinal() >= ValuesToRead.READ_ONE_VALUE.ordinal()) { - while (valuesIterator.hasNext()) { - assertTrue(valuesIterator.hasNext()); - assertTrue(valuesIterator.hasNext()); - assertEquals("BatchModeExecutionContext key", key, context.getKey()); - values.add(valuesIterator.next()); - if (valuesToRead == ValuesToRead.READ_ONE_VALUE) { - break; - } - } - if (valuesToRead.ordinal() >= ValuesToRead.READ_ALL_VALUES.ordinal()) { - assertFalse(valuesIterator.hasNext()); - assertFalse(valuesIterator.hasNext()); - - try { - valuesIterator.next(); - fail("Expected NoSuchElementException"); - } catch (NoSuchElementException exn) { - // As expected. - } - valuesIterable.iterator(); // Verifies that this does not throw. - } - } - if (valuesToRead == ValuesToRead.READ_ALL_VALUES_TWICE) { - // Create new iterator; - valuesIterator = valuesIterable.iterator(); - - while (valuesIterator.hasNext()) { - assertTrue(valuesIterator.hasNext()); - assertTrue(valuesIterator.hasNext()); - assertEquals("BatchModeExecutionContext key", key, context.getKey()); - valuesIterator.next(); - } - assertFalse(valuesIterator.hasNext()); - assertFalse(valuesIterator.hasNext()); - try { - valuesIterator.next(); - fail("Expected NoSuchElementException"); - } catch (NoSuchElementException exn) { - // As expected. - } - } - - prevValuesIterable = valuesIterable; - prevValuesIterator = valuesIterator; - } - - actual.add(KV.of(key, values)); - } - assertFalse(iter.hasNext()); - assertFalse(iter.hasNext()); - try { - iter.next(); - fail("Expected NoSuchElementException"); - } catch (NoSuchElementException exn) { - // As expected. - } - } - return actual; - } - - private void runTestReadFromShuffle( - List>>> input, boolean sortValues, - ValuesToRead valuesToRead) throws Exception { - Coder>>>> sourceElemCoder = - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), - IterableCoder.of(KvCoder.of(BigEndianIntegerCoder.of(), - BigEndianIntegerCoder.of()))), - IntervalWindow.getCoder()); - - List records = writeShuffleEntries(input, sortValues); - - PipelineOptions options = PipelineOptionsFactory.create(); - // Read from shuffle with GroupingShuffleReader. - BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - GroupingShuffleReader> groupingShuffleReader = - new GroupingShuffleReader<>( - options, null, null, null, sourceElemCoder, context, null, null, sortValues); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(groupingShuffleReader); - - TestShuffleReader shuffleReader = new TestShuffleReader(); - List expectedSizes = new ArrayList<>(); - for (ShuffleEntry record : records) { - expectedSizes.add(record.length()); - shuffleReader.addEntry(record); - } - - List>>> actual = runIterationOverGroupingShuffleReader( - context, shuffleReader, groupingShuffleReader, sourceElemCoder, valuesToRead); - - List>>> expected = new ArrayList<>(); - for (KV>> kvs : input) { - Integer key = kvs.getKey(); - List> values = new ArrayList<>(); - if (valuesToRead.ordinal() >= ValuesToRead.READ_ONE_VALUE.ordinal()) { - for (KV value : kvs.getValue()) { - values.add(value); - if (valuesToRead == ValuesToRead.READ_ONE_VALUE) { - break; - } - } - } - expected.add(KV.of(key, values)); - } - assertEquals(expected, actual); - assertEquals(expectedSizes, observer.getActualSizes()); - } - - @Test - public void testReadEmptyShuffleData() throws Exception { - runTestReadFromShuffle(NO_KVS, false /* do not sort values */, ValuesToRead.READ_ALL_VALUES); - runTestReadFromShuffle(NO_KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES); - } - - @Test - public void testReadEmptyShuffleDataSkippingValues() throws Exception { - runTestReadFromShuffle(NO_KVS, false /* do not sort values */, ValuesToRead.SKIP_VALUES); - runTestReadFromShuffle(NO_KVS, true /* sort values */, ValuesToRead.SKIP_VALUES); - } - - @Test - public void testReadNonEmptyShuffleData() throws Exception { - runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_ALL_VALUES); - runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES); - } - - @Test - public void testReadNonEmptyShuffleDataTwice() throws Exception { - runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_ALL_VALUES_TWICE); - runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES_TWICE); - } - - @Test - public void testReadNonEmptyShuffleDataReadingOneValue() throws Exception { - runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_ONE_VALUE); - runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_ONE_VALUE); - } - - @Test - public void testReadNonEmptyShuffleDataReadingNoValues() throws Exception { - runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.READ_NO_VALUES); - runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.READ_NO_VALUES); - } - - @Test - public void testReadNonEmptyShuffleDataSkippingValues() throws Exception { - runTestReadFromShuffle(KVS, false /* do not sort values */, ValuesToRead.SKIP_VALUES); - runTestReadFromShuffle(KVS, true /* sort values */, ValuesToRead.SKIP_VALUES); - } - - private void runTestBytesReadCounter( - List>>> input, boolean useSecondaryKey, - ValuesToRead valuesToRead, long expectedReadBytes) throws Exception { - // Create a shuffle reader with the shuffle values provided as input. - List records = writeShuffleEntries(input, useSecondaryKey); - TestShuffleReader shuffleReader = new TestShuffleReader(); - for (ShuffleEntry record : records) { - shuffleReader.addEntry(record); - } - - Coder>>>> sourceElemCoder = - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), - IterableCoder.of(KvCoder.of(BigEndianIntegerCoder.of(), - BigEndianIntegerCoder.of()))), - IntervalWindow.getCoder()); - PipelineOptions options = PipelineOptionsFactory.create(); - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - // Read from shuffle with GroupingShuffleReader. - BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - GroupingShuffleReader> groupingShuffleReader = - new GroupingShuffleReader<>( - options, null, null, null, sourceElemCoder, context, null, null, useSecondaryKey); - groupingShuffleReader.perOperationPerDatasetBytesCounter = - addCounterMutator.addCounter(Counter.longs("dax-shuffle-test-wf-read-bytes", SUM)); - - runIterationOverGroupingShuffleReader( - context, shuffleReader, groupingShuffleReader, sourceElemCoder, valuesToRead); - - assertEquals(expectedReadBytes, - (long) groupingShuffleReader.perOperationPerDatasetBytesCounter.getAggregate()); - } - - @Test - public void testBytesReadNonEmptyShuffleData() throws Exception { - runTestBytesReadCounter(KVS, false /* do not sort values */, - ValuesToRead.READ_ALL_VALUES, 200L); - runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES, 200L); - } - - @Test - public void testBytesReadNonEmptyShuffleDataTwice() throws Exception { - runTestBytesReadCounter(KVS, false /* do not sort values */, - ValuesToRead.READ_ALL_VALUES_TWICE, 200L); - runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES_TWICE, 200L); - } - - @Test - public void testBytesReadNonEmptyShuffleDataReadingOneValue() throws Exception { - runTestBytesReadCounter(KVS, false /* do not sort values */, ValuesToRead.READ_ONE_VALUE, 200L); - runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.READ_ONE_VALUE, 200L); - } - - @Test - public void testBytesReadNonEmptyShuffleDataSkippingValues() throws Exception { - runTestBytesReadCounter(KVS, false /* do not sort values */, ValuesToRead.SKIP_VALUES, 200L); - runTestBytesReadCounter(KVS, true /* sort values */, ValuesToRead.SKIP_VALUES, 200L); - } - - @Test - public void testBytesReadEmptyShuffleData() throws Exception { - runTestBytesReadCounter(NO_KVS, false /* do not sort values */, - ValuesToRead.READ_ALL_VALUES, 0L); - runTestBytesReadCounter(NO_KVS, true /* sort values */, ValuesToRead.READ_ALL_VALUES, 0L); - } - - static byte[] fabricatePosition(int shard) throws Exception { - return fabricatePosition(shard, (Integer) null); - } - - static byte[] fabricatePosition(int shard, @Nullable byte[] key) throws Exception { - return fabricatePosition(shard, key == null ? null : Arrays.hashCode(key)); - } - - static byte[] fabricatePosition(int shard, @Nullable Integer keyHash) throws Exception { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(os); - dos.writeInt(shard); - if (keyHash != null) { - dos.writeInt(keyHash); - } - return os.toByteArray(); - } - - @Test - public void testReadFromShuffleDataAndFailToSplit() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - final int kFirstShard = 0; - - TestShuffleReader shuffleReader = new TestShuffleReader(); - final int kNumRecords = 2; - for (int i = 0; i < kNumRecords; ++i) { - byte[] key = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - shuffleReader.addEntry( - new ShuffleEntry(fabricatePosition(kFirstShard, key), key, EMPTY_BYTE_ARRAY, key)); - } - - // Note that TestShuffleReader start/end positions are in the - // space of keys not the positions (TODO: should probably always - // use positions instead). - String stop = encodeBase64URLSafeString(fabricatePosition(kNumRecords)); - GroupingShuffleReader groupingShuffleReader = new GroupingShuffleReader<>( - options, null, null, stop, - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(BigEndianIntegerCoder.of())), - IntervalWindow.getCoder()), - context, null, null, false /* do not sort values */); - - try (GroupingShuffleReaderIterator iter = - groupingShuffleReader.iterator(shuffleReader)) { - // Poke the iterator so we can test dynamic splitting. - assertTrue(iter.hasNext()); - - // Cannot split since the value provided is past the current stop position. - assertNull(iter.requestDynamicSplit(splitRequestAtPosition( - makeShufflePosition(kNumRecords + 1, null)))); - - int i = 0; - for (; iter.hasNext(); ++i) { - iter.next().getValue(); // ignored - if (i == 0) { - // First record - byte[] key = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - // Cannot split since the split position is identical with the position of the record - // that was just returned. - assertNull( - iter.requestDynamicSplit(splitRequestAtPosition( - makeShufflePosition(kFirstShard, key)))); - - // Cannot split since the requested split position comes before current position - assertNull( - iter.requestDynamicSplit(splitRequestAtPosition( - makeShufflePosition(kFirstShard, null)))); - } - } - assertEquals(kNumRecords, i); - - // Cannot split since all input was consumed. - assertNull( - iter.requestDynamicSplit(splitRequestAtPosition(makeShufflePosition(kFirstShard, null)))); - } - } - - @Test - public void testRemainingParallelism() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - final int kFirstShard = 0; - - TestShuffleReader shuffleReader = new TestShuffleReader(); - final int kNumRecords = 5; - for (int i = 0; i < kNumRecords; ++i) { - byte[] key = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - ShuffleEntry entry = new ShuffleEntry( - fabricatePosition(kFirstShard, i), key, EMPTY_BYTE_ARRAY, key); - shuffleReader.addEntry(entry); - } - - GroupingShuffleReader groupingShuffleReader = - new GroupingShuffleReader<>( - options, - null, - null, - null, - WindowedValue.getFullCoder( - KvCoder.of( - BigEndianIntegerCoder.of(), IterableCoder.of(BigEndianIntegerCoder.of())), - IntervalWindow.getCoder()), - context, - null, - null, - false /* do not sort values */); - - try (GroupingShuffleReaderIterator iter = - groupingShuffleReader.iterator(shuffleReader)) { - - assertEquals(Double.POSITIVE_INFINITY, iter.getRemainingParallelism(), 0); - - // The only way to set a stop *position* in tests is via a split. To do that, - // we must call hasNext() first. - assertTrue(iter.hasNext()); - assertNotNull( - iter.requestDynamicSplit( - splitRequestAtPosition( - makeShufflePosition( - ByteArrayShufflePosition.of(fabricatePosition(kFirstShard, 2)) - .immediateSuccessor() - .getPosition())))); - assertTrue(iter.hasNext()); - - assertEquals(Double.POSITIVE_INFINITY, iter.getRemainingParallelism(), 0); - iter.next(); - assertEquals(Double.POSITIVE_INFINITY, iter.getRemainingParallelism(), 0); - assertTrue(iter.hasNext()); - assertEquals(Double.POSITIVE_INFINITY, iter.getRemainingParallelism(), 0); - iter.next(); - assertEquals(Double.POSITIVE_INFINITY, iter.getRemainingParallelism(), 0); - assertTrue(iter.hasNext()); - assertEquals(1, iter.getRemainingParallelism(), 0); - iter.next(); - assertEquals(1, iter.getRemainingParallelism(), 0); - assertFalse(iter.hasNext()); - assertEquals(1, iter.getRemainingParallelism(), 0); - } - } - - private Position makeShufflePosition(int shard, byte[] key) throws Exception { - return new Position().setShufflePosition( - encodeBase64URLSafeString(fabricatePosition(shard, key))); - } - - private Position makeShufflePosition(byte[] position) throws Exception { - return new Position().setShufflePosition(encodeBase64URLSafeString(position)); - } - - @Test - public void testReadFromShuffleAndDynamicSplit() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - GroupingShuffleReader groupingShuffleReader = new GroupingShuffleReader<>( - options, null, null, null, - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(BigEndianIntegerCoder.of())), - IntervalWindow.getCoder()), - context, null, null, false /* do not sort values */); - groupingShuffleReader.perOperationPerDatasetBytesCounter = - addCounterMutator.addCounter(Counter.longs("dax-shuffle-test-wf-read-bytes", SUM)); - - TestShuffleReader shuffleReader = new TestShuffleReader(); - final int kNumRecords = 10; - final int kFirstShard = 0; - final int kSecondShard = 1; - - // Setting up two shards with kNumRecords each; keys are unique - // (hence groups of values for the same key are singletons) - // therefore each record comes with a unique position constructed. - for (int i = 0; i < kNumRecords; ++i) { - byte[] keyByte = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - ShuffleEntry entry = new ShuffleEntry( - fabricatePosition(kFirstShard, keyByte), keyByte, EMPTY_BYTE_ARRAY, keyByte); - shuffleReader.addEntry(entry); - } - - for (int i = kNumRecords; i < 2 * kNumRecords; ++i) { - byte[] keyByte = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - - ShuffleEntry entry = new ShuffleEntry( - fabricatePosition(kSecondShard, keyByte), keyByte, EMPTY_BYTE_ARRAY, keyByte); - shuffleReader.addEntry(entry); - } - - int i = 0; - try (GroupingShuffleReaderIterator iter = - groupingShuffleReader.iterator(shuffleReader)) { - // Poke the iterator so we can test dynamic splitting. - assertTrue(iter.hasNext()); - - assertNull(iter.requestDynamicSplit(splitRequestAtPosition(new Position()))); - - // Split at the shard boundary - NativeReader.DynamicSplitResult dynamicSplitResult = - iter.requestDynamicSplit(splitRequestAtPosition(makeShufflePosition(kSecondShard, null))); - assertNotNull(dynamicSplitResult); - assertEquals( - encodeBase64URLSafeString(fabricatePosition(kSecondShard)), - positionFromSplitResult(dynamicSplitResult).getShufflePosition()); - - while (iter.hasNext()) { - // iter.hasNext() is supposed to be side-effect-free and give the same result if called - // repeatedly. Test that this is indeed the case. - assertTrue(iter.hasNext()); - assertTrue(iter.hasNext()); - - KV> elem = iter.next().getValue(); - int key = elem.getKey(); - assertEquals(key, i); - - Iterable valuesIterable = elem.getValue(); - Iterator valuesIterator = valuesIterable.iterator(); - - int j = 0; - while (valuesIterator.hasNext()) { - assertTrue(valuesIterator.hasNext()); - assertTrue(valuesIterator.hasNext()); - - int value = valuesIterator.next(); - assertEquals(value, i); - ++j; - } - assertFalse(valuesIterator.hasNext()); - assertFalse(valuesIterator.hasNext()); - assertEquals(j, 1); - ++i; - } - assertFalse(iter.hasNext()); - } - assertEquals(i, kNumRecords); - // There are 10 Shuffle records that each encode an integer key (4 bytes) and integer value (4 - // bytes). We therefore expect to read 80 bytes. - assertEquals( - 80L, (long) groupingShuffleReader.perOperationPerDatasetBytesCounter.getAggregate()); - } - - @Test - public void testGetApproximateProgress() throws Exception { - // Store the positions of all KVs returned. - List positionsList = new ArrayList(); - - PipelineOptions options = PipelineOptionsFactory.create(); - BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - GroupingShuffleReader groupingShuffleReader = new GroupingShuffleReader<>( - options, null, null, null, - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), IterableCoder.of(BigEndianIntegerCoder.of())), - IntervalWindow.getCoder()), - context, null, null, false /* do not sort values */); - - TestShuffleReader shuffleReader = new TestShuffleReader(); - final int kNumRecords = 10; - - for (int i = 0; i < kNumRecords; ++i) { - byte[] position = fabricatePosition(i); - byte[] keyByte = CoderUtils.encodeToByteArray(BigEndianIntegerCoder.of(), i); - positionsList.add(position); - ShuffleEntry entry = new ShuffleEntry(position, keyByte, EMPTY_BYTE_ARRAY, keyByte); - shuffleReader.addEntry(entry); - } - - try (GroupingShuffleReaderIterator readerIterator = - groupingShuffleReader.iterator(shuffleReader)) { - Integer i = 0; - while (readerIterator.hasNext()) { - assertTrue(readerIterator.hasNext()); - ApproximateReportedProgress progress = readerProgressToCloudProgress( - readerIterator.getProgress()); - assertNotNull(progress.getPosition().getShufflePosition()); - - // Compare returned position with the expected position. - assertEquals( - ByteArrayShufflePosition.of(positionsList.get(i)).encodeBase64(), - progress.getPosition().getShufflePosition()); - - WindowedValue>> elem = readerIterator.next(); - assertEquals(i, elem.getValue().getKey()); - i++; - } - assertFalse(readerIterator.hasNext()); - - // Cannot split since all input was consumed. - Position proposedSplitPosition = new Position(); - String stop = encodeBase64URLSafeString(fabricatePosition(0)); - proposedSplitPosition.setShufflePosition(stop); - assertNull( - readerIterator.requestDynamicSplit( - toDynamicSplitRequest(approximateSplitRequestAtPosition(proposedSplitPosition)))); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java deleted file mode 100644 index 67647a53dc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactoryTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.InMemoryReaderTest.encodedElements; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for InMemoryReaderFactory. - */ -@RunWith(JUnit4.class) -public class InMemoryReaderFactoryTest { - static Source createInMemoryCloudSource( - List elements, Long start, Long end, Coder coder) throws Exception { - List encodedElements = encodedElements(elements, coder); - - CloudObject spec = CloudObject.forClassName("InMemorySource"); - addStringList(spec, PropertyNames.ELEMENTS, encodedElements); - - if (start != null) { - addLong(spec, PropertyNames.START_INDEX, start); - } - if (end != null) { - addLong(spec, PropertyNames.END_INDEX, end); - } - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(coder.asCloudObject()); - - return cloudSource; - } - - void runTestCreateInMemoryReader(List elements, Long start, Long end, int expectedStart, - int expectedEnd, Coder coder) throws Exception { - Source cloudSource = createInMemoryCloudSource(elements, start, end, coder); - - NativeReader reader = - ReaderRegistry.defaultRegistry() - .create( - cloudSource, - PipelineOptionsFactory.create(), - BatchModeExecutionContext.fromOptions(PipelineOptionsFactory.create()), - null, - null); - Assert.assertThat(reader, new IsInstanceOf(InMemoryReader.class)); - InMemoryReader inMemoryReader = (InMemoryReader) reader; - Assert.assertEquals(encodedElements(elements, coder), inMemoryReader.encodedElements); - Assert.assertEquals(expectedStart, inMemoryReader.startIndex); - Assert.assertEquals(expectedEnd, inMemoryReader.endIndex); - Assert.assertEquals(coder, inMemoryReader.coder); - } - - @Test - public void testCreatePlainInMemoryReader() throws Exception { - runTestCreateInMemoryReader( - Arrays.asList("hi", "there", "bob"), null, null, 0, 3, StringUtf8Coder.of()); - } - - @Test - public void testCreateRichInMemoryReader() throws Exception { - runTestCreateInMemoryReader( - Arrays.asList(33, 44, 55, 66, 77, 88), 1L, 3L, 1, 3, BigEndianIntegerCoder.of()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java deleted file mode 100644 index 19a022d0e7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderTest.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.approximateProgressAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.toDynamicSplitRequest; -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; -import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Tests for InMemoryReader. - */ -@RunWith(JUnit4.class) -public class InMemoryReaderTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - static List encodedElements(List elements, Coder coder) throws Exception { - List encodedElements = new ArrayList<>(); - for (T element : elements) { - byte[] encodedElement = encodeToByteArray(coder, element); - String encodedElementString = byteArrayToJsonString(encodedElement); - encodedElements.add(encodedElementString); - } - return encodedElements; - } - - void runTestReadInMemory( - List elements, - @Nullable Integer startIndex, - @Nullable Integer endIndex, - List expectedElements, - List expectedSizes, - Coder coder) - throws Exception { - InMemoryReader inMemoryReader = - new InMemoryReader<>(encodedElements(elements, coder), startIndex, endIndex, coder); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(inMemoryReader); - List actualElements = new ArrayList<>(); - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - for (long i = inMemoryReader.startIndex; - (i == inMemoryReader.startIndex) ? iterator.start() : iterator.advance(); - i++) { - assertEquals( - approximateProgressAtIndex(i), readerProgressToCloudProgress(iterator.getProgress())); - actualElements.add(iterator.getCurrent()); - } - } - assertEquals(expectedElements, actualElements); - assertEquals(expectedSizes, observer.getActualSizes()); - } - - @Test - public void testReadAllElements() throws Exception { - runTestReadInMemory(Arrays.asList(33, 44, 55, 66, 77, 88), null, null, - Arrays.asList(33, 44, 55, 66, 77, 88), Arrays.asList(4, 4, 4, 4, 4, 4), - BigEndianIntegerCoder.of()); - } - - @Test - public void testReadElementsFromStart() throws Exception { - runTestReadInMemory( - Arrays.asList(33, 44, 55, 66, 77, 88), - 2, - null, - Arrays.asList(55, 66, 77, 88), - Arrays.asList(4, 4, 4, 4), - BigEndianIntegerCoder.of()); - } - - @Test - public void testReadElementsToEnd() throws Exception { - runTestReadInMemory( - Arrays.asList(33, 44, 55, 66, 77, 88), - null, - 3, - Arrays.asList(33, 44, 55), - Arrays.asList(4, 4, 4), - BigEndianIntegerCoder.of()); - } - - @Test - public void testReadElementsFromStartToEnd() throws Exception { - runTestReadInMemory( - Arrays.asList(33, 44, 55, 66, 77, 88), - 2, - 5, - Arrays.asList(55, 66, 77), - Arrays.asList(4, 4, 4), - BigEndianIntegerCoder.of()); - } - - @Test - public void testReadElementsOffEnd() throws Exception { - runTestReadInMemory( - Arrays.asList(33, 44, 55, 66, 77, 88), - null, - 30, - Arrays.asList(33, 44, 55, 66, 77, 88), - Arrays.asList(4, 4, 4, 4, 4, 4), - BigEndianIntegerCoder.of()); - } - - @Test - public void testReadElementsFromStartPastEnd() throws Exception { - runTestReadInMemory( - Arrays.asList(33, 44, 55, 66, 77, 88), - 20, - null, - Arrays.asList(), - Arrays.asList(), - BigEndianIntegerCoder.of()); - } - - @Test - public void testReadElementsFromStartToEndEmptyRange() throws Exception { - runTestReadInMemory( - Arrays.asList(33, 44, 55, 66, 77, 88), - 2, - 2, - Arrays.asList(), - Arrays.asList(), - BigEndianIntegerCoder.of()); - } - - @Test - public void testReadNoElements() throws Exception { - runTestReadInMemory(Arrays.asList(), null, null, Arrays.asList(), - Arrays.asList(), BigEndianIntegerCoder.of()); - } - - @Test - public void testReadNoElementsFromStartToEndEmptyRange() throws Exception { - runTestReadInMemory( - Arrays.asList(), - 0, - 0, - Arrays.asList(), - Arrays.asList(), - BigEndianIntegerCoder.of()); - } - - @Test - public void testProgressReporting() throws Exception { - List elements = Arrays.asList(33, 44, 55, 66, 77, 88); - // Should initially read elements at indices: 44@1, 55@2, 66@3, 77@4 - - Coder coder = BigEndianIntegerCoder.of(); - InMemoryReader inMemoryReader = - new InMemoryReader<>(encodedElements(elements, coder), 1, 4, coder); - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - assertNull(iterator.getProgress()); - assertEquals(3, iterator.getRemainingParallelism(), 0.0); - - assertTrue(iterator.start()); - assertEquals(positionAtIndex(1L), positionFromProgress(iterator.getProgress())); - assertEquals(3, iterator.getRemainingParallelism(), 0.0); - - assertTrue(iterator.advance()); - assertEquals(positionAtIndex(2L), positionFromProgress(iterator.getProgress())); - assertEquals(2, iterator.getRemainingParallelism(), 0.0); - - assertTrue(iterator.advance()); - assertEquals(positionAtIndex(3L), positionFromProgress(iterator.getProgress())); - assertEquals(1, iterator.getRemainingParallelism(), 0.0); - - assertFalse(iterator.advance()); - } - } - - @Test - public void testDynamicSplit() throws Exception { - List elements = Arrays.asList(33, 44, 55, 66, 77, 88); - // Should initially read elements at indices: 44@1, 55@2, 66@3, 77@4 - - Coder coder = BigEndianIntegerCoder.of(); - InMemoryReader inMemoryReader = - new InMemoryReader<>(encodedElements(elements, coder), 1, 4, coder); - - // Unstarted iterator. - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(3L))); - } - - // Illegal proposed split position. - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(3L))); - // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.start()); - assertNull(iterator.requestDynamicSplit(toDynamicSplitRequest( - new ApproximateSplitRequest()))); - assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(null))); - } - - // Successful update. - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.start()); - NativeReader.DynamicSplitResult dynamicSplitResult = - iterator.requestDynamicSplit(splitRequestAtIndex(3L)); - assertEquals(positionAtIndex(3L), positionFromSplitResult(dynamicSplitResult)); - assertEquals(3, iterator.tracker.getStopPosition().longValue()); - assertEquals(44, iterator.getCurrent().intValue()); - assertTrue(iterator.advance()); - assertEquals(55, iterator.getCurrent().intValue()); - assertFalse(iterator.advance()); - } - - // Proposed split position is before the current position, no update. - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.start()); - assertEquals(44, iterator.getCurrent().intValue()); - assertTrue(iterator.advance()); - assertEquals(55, iterator.getCurrent().intValue()); - assertTrue(iterator.advance()); // Returns true => we promised to return 66. - // Now we have to refuse the split. - assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(3L))); - assertEquals(4, iterator.tracker.getStopPosition().longValue()); - assertEquals(66, iterator.getCurrent().intValue()); - assertFalse(iterator.advance()); - } - - // Proposed split position is after the current stop (end) position, no update. - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - // Poke the iterator so that we can test dynamic splitting. - assertTrue(iterator.start()); - assertNull(iterator.requestDynamicSplit(splitRequestAtIndex(5L))); - assertEquals(4, iterator.tracker.getStopPosition().longValue()); - } - } - - @Test - public void testParallelism() throws Exception { - List elements = Arrays.asList(33, 44, 55, 66, 77, 88); - - Coder coder = BigEndianIntegerCoder.of(); - InMemoryReader inMemoryReader = - new InMemoryReader<>(encodedElements(elements, coder), 1, 4, coder); - int count = 0; - try (InMemoryReader.InMemoryReaderIterator iterator = inMemoryReader.iterator()) { - for (boolean more = iterator.start(); more; more = iterator.advance()) { - assertTrue(iterator.getRemainingParallelism() >= 1); - assertEquals(3 - count, iterator.getRemainingParallelism(), 0 /*tolerance*/); - count++; - } - } - assertEquals(count, inMemoryReader.getTotalParallelism(), 0 /*tolerance*/); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java deleted file mode 100644 index 36875040be..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormatTest.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.Footer; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.FooterCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShard; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShardCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefix; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefixCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.testing.CoderPropertiesTest.NonDeterministicCoder; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * Tests for {@link IsmFormat}. - */ -@RunWith(JUnit4.class) -public class IsmFormatTest { - private static final Coder NON_DETERMINISTIC_CODER = new NonDeterministicCoder(); - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Test - public void testUsingNonDeterministicShardKeyCoder() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("is expected to be deterministic"); - IsmFormat.validateCoderIsCompatible(IsmRecordCoder.of( - 1, // number or shard key coders for value records - 0, // number of shard key coders for metadata records - ImmutableList.>of(NON_DETERMINISTIC_CODER, ByteArrayCoder.of()), - ByteArrayCoder.of())); - } - - @Test - public void testUsingNonDeterministicNonShardKeyCoder() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("is expected to be deterministic"); - IsmFormat.validateCoderIsCompatible(IsmRecordCoder.of( - 1, // number or shard key coders for value records - 0, // number of shard key coders for metadata records - ImmutableList.>of(ByteArrayCoder.of(), NON_DETERMINISTIC_CODER), - ByteArrayCoder.of())); - } - - - @Test - public void testKeyPrefixCoder() throws Exception { - KeyPrefix keyPrefixA = new KeyPrefix(5, 7); - KeyPrefix keyPrefixB = new KeyPrefix(5, 7); - CoderProperties.coderDecodeEncodeEqual(KeyPrefixCoder.of(), keyPrefixA); - CoderProperties.coderDeterministic(KeyPrefixCoder.of(), keyPrefixA, keyPrefixB); - CoderProperties.coderConsistentWithEquals(KeyPrefixCoder.of(), keyPrefixA, keyPrefixB); - CoderProperties.coderSerializable(KeyPrefixCoder.of()); - CoderProperties.structuralValueConsistentWithEquals( - KeyPrefixCoder.of(), keyPrefixA, keyPrefixB); - assertTrue(KeyPrefixCoder.of().isRegisterByteSizeObserverCheap(keyPrefixA, Context.NESTED)); - assertTrue(KeyPrefixCoder.of().isRegisterByteSizeObserverCheap(keyPrefixA, Context.OUTER)); - assertEquals(2, KeyPrefixCoder.of().getEncodedElementByteSize(keyPrefixA, Context.NESTED)); - assertEquals(2, KeyPrefixCoder.of().getEncodedElementByteSize(keyPrefixA, Context.OUTER)); - } - - @Test - public void testFooterCoder() throws Exception { - Footer footerA = new Footer(1, 2, 3); - Footer footerB = new Footer(1, 2, 3); - CoderProperties.coderDecodeEncodeEqual(FooterCoder.of(), footerA); - CoderProperties.coderDeterministic(FooterCoder.of(), footerA, footerB); - CoderProperties.coderConsistentWithEquals(FooterCoder.of(), footerA, footerB); - CoderProperties.coderSerializable(FooterCoder.of()); - CoderProperties.structuralValueConsistentWithEquals(FooterCoder.of(), footerA, footerB); - assertTrue(FooterCoder.of().isRegisterByteSizeObserverCheap(footerA, Context.NESTED)); - assertTrue(FooterCoder.of().isRegisterByteSizeObserverCheap(footerA, Context.OUTER)); - assertEquals(25, FooterCoder.of().getEncodedElementByteSize(footerA, Context.NESTED)); - assertEquals(25, FooterCoder.of().getEncodedElementByteSize(footerA, Context.OUTER)); - } - - @Test - public void testNormalIsmRecordWithMetadataKeyIsError() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Expected key components to not contain metadata key"); - IsmRecord.of(ImmutableList.of(IsmFormat.getMetadataKey()), "test"); - } - - @Test - public void testMetadataIsmRecordWithoutMetadataKeyIsError() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Expected key components to contain metadata key"); - IsmRecord.meta(ImmutableList.of("non-metadata key"), "test".getBytes()); - } - - @Test - public void testIsmRecordCoder() throws Exception { - IsmRecord ismRecordA = IsmRecord.of(ImmutableList.of("0"), "1"); - IsmRecord ismRecordB = IsmRecord.of(ImmutableList.of("0"), "1"); - IsmRecord ismMetaRecordA = - IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey()), "2".getBytes()); - IsmRecord ismMetaRecordB = - IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey()), "2".getBytes()); - IsmRecordCoder coder = - IsmRecordCoder.of( - 1, - 0, - ImmutableList.>of(StringUtf8Coder.of()), - StringUtf8Coder.of()); - IsmRecordCoder coderWithMetadata = - IsmRecordCoder.of( - 1, - 1, - ImmutableList.>of(MetadataKeyCoder.of(StringUtf8Coder.of())), - StringUtf8Coder.of()); - - // Non-metadata records against coder without metadata key support - CoderProperties.coderDecodeEncodeEqual(coder, ismRecordA); - CoderProperties.coderDeterministic(coder, ismRecordA, ismRecordB); - CoderProperties.coderConsistentWithEquals(coder, ismRecordA, ismRecordB); - CoderProperties.coderSerializable(coder); - CoderProperties.structuralValueConsistentWithEquals(coder, ismRecordA, ismRecordB); - - // Non-metadata records against coder with metadata key support - CoderProperties.coderDecodeEncodeEqual(coderWithMetadata, ismRecordA); - CoderProperties.coderDeterministic(coderWithMetadata, ismRecordA, ismRecordB); - CoderProperties.coderConsistentWithEquals(coderWithMetadata, ismRecordA, ismRecordB); - CoderProperties.coderSerializable(coderWithMetadata); - CoderProperties.structuralValueConsistentWithEquals(coderWithMetadata, ismRecordA, ismRecordB); - - // Metadata records - CoderProperties.coderDecodeEncodeEqual(coderWithMetadata, ismMetaRecordA); - CoderProperties.coderDeterministic(coderWithMetadata, ismMetaRecordA, ismMetaRecordB); - CoderProperties.coderConsistentWithEquals( - coderWithMetadata, ismMetaRecordA, ismMetaRecordB); - CoderProperties.coderSerializable(coderWithMetadata); - CoderProperties.structuralValueConsistentWithEquals( - coderWithMetadata, ismMetaRecordA, ismMetaRecordB); - } - - @Test - public void testIsmRecordCoderHashWithinExpectedRanges() throws Exception { - IsmRecordCoder coder = - IsmRecordCoder.of( - 2, - 0, - ImmutableList.>of(StringUtf8Coder.of(), StringUtf8Coder.of()), - StringUtf8Coder.of()); - IsmRecordCoder coderWithMetadata = - IsmRecordCoder.of( - 2, - 2, - ImmutableList.>of( - MetadataKeyCoder.of(StringUtf8Coder.of()), StringUtf8Coder.of()), - StringUtf8Coder.of()); - - assertTrue(coder.hash(ImmutableList.of("A", "B")) < IsmFormat.SHARD_BITS + 1); - int hash = coderWithMetadata.hash(ImmutableList.of(IsmFormat.getMetadataKey(), "B")); - assertTrue(hash > IsmFormat.SHARD_BITS && hash < (IsmFormat.SHARD_BITS + 1) * 2); - } - - @Test - public void testIsmRecordCoderWithTooManyKeysIsError() throws Exception { - IsmRecordCoder coder = - IsmRecordCoder.of( - 2, - 0, - ImmutableList.>of(StringUtf8Coder.of(), StringUtf8Coder.of()), - StringUtf8Coder.of()); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Expected at most"); - coder.hash(ImmutableList.of("A", "B", "C")); - } - - @Test - public void testIsmRecordCoderHashWithoutEnoughKeysIsError() throws Exception { - IsmRecordCoder coder = - IsmRecordCoder.of( - 2, - 0, - ImmutableList.>of(StringUtf8Coder.of(), StringUtf8Coder.of()), - StringUtf8Coder.of()); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Expected at least"); - coder.hash(ImmutableList.of("A")); - } - - @Test - public void testIsmRecordCoderMetadataHashWithoutEnoughKeysIsError() throws Exception { - IsmRecordCoder coderWithMetadata = - IsmRecordCoder.of( - 2, - 2, - ImmutableList.>of( - MetadataKeyCoder.of(StringUtf8Coder.of()), StringUtf8Coder.of()), - StringUtf8Coder.of()); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Expected at least"); - coderWithMetadata.hash(ImmutableList.of(IsmFormat.getMetadataKey())); - } - - - @Test - public void testIsmRecordCoderKeyCoderCountMismatch() throws Exception { - IsmRecord ismRecord = IsmRecord.of(ImmutableList.of("0", "too many"), "1"); - IsmRecordCoder coder = - IsmRecordCoder.of( - 1, - 0, - ImmutableList.>of(StringUtf8Coder.of()), - StringUtf8Coder.of()); - - expectedException.expect(CoderException.class); - expectedException.expectMessage("Expected 1 key component(s) but received key"); - coder.encode(ismRecord, new ByteArrayOutputStream(), Context.NESTED); - } - - @Test - public void testIsmRecordToStringEqualsAndHashCode() { - IsmRecord ismRecordA = IsmRecord.of(ImmutableList.of("0"), "1"); - IsmRecord ismRecordB = IsmRecord.of(ImmutableList.of("0"), "1"); - IsmRecord ismRecordC = IsmRecord.of(ImmutableList.of("3"), "4"); - IsmRecord ismRecordAWithMeta = - IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey(), "0"), "2".getBytes()); - IsmRecord ismRecordBWithMeta = - IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey(), "0"), "2".getBytes()); - IsmRecord ismRecordCWithMeta = - IsmRecord.meta(ImmutableList.of(IsmFormat.getMetadataKey(), "0"), "5".getBytes()); - - assertEquals(ismRecordA, ismRecordB); - assertEquals(ismRecordAWithMeta, ismRecordBWithMeta); - assertNotEquals(ismRecordA, ismRecordAWithMeta); - assertNotEquals(ismRecordA, ismRecordC); - assertNotEquals(ismRecordAWithMeta, ismRecordCWithMeta); - - assertEquals(ismRecordA.hashCode(), ismRecordB.hashCode()); - assertEquals(ismRecordAWithMeta.hashCode(), ismRecordBWithMeta.hashCode()); - assertNotEquals(ismRecordA.hashCode(), ismRecordAWithMeta.hashCode()); - assertNotEquals(ismRecordA.hashCode(), ismRecordC.hashCode()); - assertNotEquals(ismRecordAWithMeta.hashCode(), ismRecordCWithMeta.hashCode()); - - assertThat(ismRecordA.toString(), allOf( - containsString("keyComponents=[0]"), - containsString("value=1"), - not(containsString("metadata")))); - assertThat(ismRecordAWithMeta.toString(), allOf( - containsString("keyComponents=[META, 0]"), - containsString("metadata="), - not(containsString("value")))); - } - - @Test - public void testIsmShardCoder() throws Exception { - IsmShard shardA = IsmShard.of(1, 2, 3); - IsmShard shardB = IsmShard.of(1, 2, 3); - CoderProperties.coderDecodeEncodeEqual(IsmShardCoder.of(), shardA); - CoderProperties.coderDeterministic(IsmShardCoder.of(), shardA, shardB); - CoderProperties.coderConsistentWithEquals(IsmShardCoder.of(), shardA, shardB); - CoderProperties.coderSerializable(IsmShardCoder.of()); - CoderProperties.structuralValueConsistentWithEquals(IsmShardCoder.of(), shardA, shardB); - } - - @Test - public void testIsmShardToStringEqualsAndHashCode() { - IsmShard shardA = IsmShard.of(1, 2, 3); - IsmShard shardB = IsmShard.of(1, 2, 3); - IsmShard shardC = IsmShard.of(4, 5, 6); - assertEquals(shardA, shardB); - assertNotEquals(shardA, shardC); - assertEquals(shardA.hashCode(), shardB.hashCode()); - assertNotEquals(shardA.hashCode(), shardC.hashCode()); - assertThat(shardA.toString(), allOf( - containsString("id=1"), - containsString("blockOffset=2"), - containsString("indexOffset=3"))); - } - - @Test - public void testUnknownVersion() throws Exception { - byte[] data = new byte[25]; - data[24] = 5; // unknown version - ByteArrayInputStream bais = new ByteArrayInputStream(data); - - expectedException.expect(IOException.class); - expectedException.expectMessage("Unknown version 5"); - FooterCoder.of().decode(bais, Context.OUTER); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java deleted file mode 100644 index 3ae91641e1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReaderTest.java +++ /dev/null @@ -1,583 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; -import static com.google.common.base.Preconditions.checkState; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmReader.IsmShardKey; -import com.google.cloud.dataflow.sdk.testing.CoderPropertiesTest.NonDeterministicCoder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.RandomAccessData; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils.TestReaderObserver; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink.SinkWriter; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.primitives.UnsignedBytes; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.NavigableSet; -import java.util.NoSuchElementException; -import java.util.Random; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -/** Tests for {@link IsmReader}. */ -@RunWith(JUnit4.class) -public class IsmReaderTest { - private static final int TEST_BLOCK_SIZE = 1024; - private static final IsmRecordCoder CODER = - IsmRecordCoder.of( - 1, // number or shard key coders for value records - 1, // number of shard key coders for metadata records - ImmutableList.>of(MetadataKeyCoder.of(ByteArrayCoder.of()), ByteArrayCoder.of()), - ByteArrayCoder.of()); - - private static final Coder NON_DETERMINISTIC_CODER = new NonDeterministicCoder(); - private static final byte[] EMPTY = new byte[0]; - - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - @Rule public ExpectedException expectedException = ExpectedException.none(); - - private Cache>>>> cache; - - @Before - public void setUp() { - cache = CacheBuilder - .newBuilder() - .weigher(Weighers.fixedWeightKeys(1)) - .maximumWeight(10_000) - .build(); - } - - @Test - public void testReadEmpty() throws Exception { - writeElementsToFileAndReadInOrder(Collections.>emptyList()); - } - - @Test - public void testUsingNonDeterministicShardKeyCoder() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("is expected to be deterministic"); - new IsmReader<>( - tmpFolder.newFile().getPath(), - IsmRecordCoder.of( - 1, // number or shard key coders for value records - 0, // number of shard key coders for metadata records - ImmutableList.>of(NON_DETERMINISTIC_CODER, ByteArrayCoder.of()), - ByteArrayCoder.of()), - cache); - } - - @Test - public void testUsingNonDeterministicNonShardKeyCoder() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("is expected to be deterministic"); - new IsmReader<>( - tmpFolder.newFile().getPath(), - IsmRecordCoder.of( - 1, // number or shard key coders for value records - 0, // number of shard key coders for metadata records - ImmutableList.>of(ByteArrayCoder.of(), NON_DETERMINISTIC_CODER), - ByteArrayCoder.of()), - cache); - } - - @Test - public void testRead() throws Exception { - Random random = new Random(23498321490L); - for (int i : Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) { - int minElements = (int) Math.pow(2, i); - int valueSize = 128; - // Generates between 2^i and 2^(i + 1) elements. - writeElementsToFileAndReadInOrder(dataGenerator(8 /* number of primary keys */, - minElements + random.nextInt(minElements) /* number of secondary keys */, - 8 /* max key size */, valueSize)); - } - } - - @Test - public void testReadThatProducesIndexEntries() throws Exception { - Random random = new Random(23498323891L); - int minElements = (int) Math.pow(2, 6); - int valueSize = 128; - // Since we are generating more then 2 blocks worth of data, we are guaranteed that - // at least one index entry is generated per shard. - checkState(minElements * valueSize > 2 * TEST_BLOCK_SIZE); - writeElementsToFileAndReadInOrder(dataGenerator(8 /* number of primary keys */, - minElements + random.nextInt(minElements) /* number of secondary keys */, - 8 /* max key size */, valueSize /* max value size */)); - } - - @Test - public void testReadRandomOrder() throws Exception { - Random random = new Random(2348238943L); - for (int i : Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)) { - int minElements = (int) Math.pow(2, i); - int valueSize = 128; - // Generates between 2^i and 2^(i + 1) elements. - writeElementsToFileAndReadInRandomOrder(dataGenerator(7 /* number of primary keys */, - minElements + random.nextInt(minElements) /* number of secondary keys */, - 8 /* max key size */, valueSize /* max value size */)); - } - } - - @Test - public void testGetLastWithPrefix() throws Exception { - Random random = new Random(2348238943L); - for (int i : Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) { - int minElements = (int) Math.pow(2, i); - int valueSize = 128; - // Generates between 2^i and 2^(i + 1) elements. - writeElementsToFileAndFindLastElementPerPrimaryKey( - dataGenerator(7, minElements + random.nextInt(minElements), - 8 /* max key size */, valueSize /* max value size */)); - } - } - - @Test - public void testReadMissingKeys() throws Exception { - File tmpFile = tmpFolder.newFile(); - List> data = new ArrayList<>(); - data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x04 }), EMPTY)); - data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x08 }), EMPTY)); - writeElementsToFile(data, tmpFile); - - IsmReader reader = new IsmReader(tmpFile.getAbsolutePath(), CODER, cache); - - // Check that we got false with a key before all keys contained in the file. - assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x02 })).hasNext()); - // Check that we got false with a key between two other keys contained in the file. - assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x06 })).hasNext()); - // Check that we got false with a key that is after all keys contained in the file. - assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x10 })).hasNext()); - } - - @Test - public void testReadMissingKeysBypassingBloomFilter() throws Exception { - File tmpFile = tmpFolder.newFile(); - List> data = new ArrayList<>(); - data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x04 }), EMPTY)); - data.add(IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x08 }), EMPTY)); - writeElementsToFile(data, tmpFile); - - IsmReader reader = - new IsmReader(tmpFile.getAbsolutePath(), CODER, cache) { - // We use this override to get around the Bloom filter saying that the key doesn't exist. - @Override - boolean bloomFilterMightContain(RandomAccessData keyBytes) { - return true; - } - }; - - // Check that we got false with a key before all keys contained in the file. - assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x02 })).hasNext()); - // Check that we got false with a key between two other keys contained in the file. - assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x06 })).hasNext()); - // Check that we got false with a key that is after all keys contained in the file. - assertFalse(reader.overKeyComponents(ImmutableList.of(EMPTY, new byte[]{ 0x10 })).hasNext()); - } - - @Test - public void testReadKeyThatEncodesToEmptyByteArray() throws Exception { - File tmpFile = tmpFolder.newFile(); - IsmRecordCoder coder = IsmRecordCoder.of( - 1, 0, ImmutableList.>of(VoidCoder.of()), VoidCoder.of()); - IsmSink sink = new IsmSink<>( - tmpFile.getPath(), coder); - IsmRecord element = IsmRecord.of(Arrays.asList((Void) null), (Void) null); - try (SinkWriter>> writer = - sink.writer()) { - writer.add(valueInEmptyWindows(element)); - } - - Cache>>>> cache = - CacheBuilder - .newBuilder() - .weigher(Weighers.fixedWeightKeys(1)) - .maximumWeight(10_000) - .build(); - IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), coder, cache); - assertEquals(coder.structuralValue(element), - coder.structuralValue(reader.iterator().next().getValue())); - } - - /** Write input elements to the specified file. */ - static void writeElementsToFile( - Iterable> elements, File tmpFile) throws Exception { - IsmSink sink = - new IsmSink(tmpFile.getPath(), CODER) { - @Override - long getBlockSize() { - return TEST_BLOCK_SIZE; - } - }; - - try (SinkWriter>> writer = - sink.writer()) { - for (IsmRecord element : elements) { - writer.add(valueInEmptyWindows(element)); - } - } - } - - /** - * Writes elements to an Ism file using an IsmSink. Then reads them back with an IsmReader, - * verifying the values read match those that were written. - */ - private void writeElementsToFileAndReadInOrder(Iterable> elements) - throws Exception { - File tmpFile = tmpFolder.newFile(); - writeElementsToFile(elements, tmpFile); - IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), CODER, cache); - TestReaderObserver observer = new TestReaderObserver(reader); - reader.addObserver(observer); - - Iterator> elementsIterator = elements.iterator(); - try (NativeReader.LegacyReaderIterator>> iterator = - reader.iterator()) { - - while (iterator.hasNext() && elementsIterator.hasNext()) { - IsmRecord expected = elementsIterator.next(); - IsmRecord actual = iterator.next().getValue(); - assertIsmEquals(actual, expected); - - final int expectedLength; - if (IsmFormat.isMetadataKey(expected.getKeyComponents())) { - expectedLength = expected.getMetadata().length; - } else { - expectedLength = expected.getValue().length; - } - // Verify that the observer saw at least as many bytes as the size of the value. - assertTrue(expectedLength - <= observer.getActualSizes().get(observer.getActualSizes().size() - 1)); - - } - if (iterator.advance()) { - fail("Read more elements then expected, did not expect: " + iterator.getCurrent()); - } else if (elementsIterator.hasNext()) { - fail("Read less elements then expected, expected: " + elementsIterator.next()); - } - - // Verify that we see a {@link NoSuchElementException} if we attempt to go further. - try { - iterator.getCurrent(); - fail("Expected a NoSuchElementException to have been thrown."); - } catch (NoSuchElementException expected) { - } - } - } - - private static void assertIsmEquals( - IsmRecord actual, - IsmRecord expected) { - assertEquals(expected.getKeyComponents().size(), actual.getKeyComponents().size()); - for (int i = 0; i < expected.getKeyComponents().size(); ++i) { - if (actual.getKeyComponent(i) != expected.getKeyComponent(i)) { - assertArrayEquals((byte[]) actual.getKeyComponent(i), (byte[]) expected.getKeyComponent(i)); - } - } - - if (IsmFormat.isMetadataKey(expected.getKeyComponents())) { - assertArrayEquals(actual.getMetadata(), expected.getMetadata()); - } else { - assertArrayEquals(actual.getValue(), expected.getValue()); - } - } - - /** - * A predicate which filters elements on whether the second key's last byte is odd or even. - * Allows for a stable partitioning of generated data. - */ - private static class EvenFilter implements Predicate> { - private static final EvenFilter INSTANCE = new EvenFilter(); - - @Override - public boolean apply(IsmRecord input) { - byte[] secondKey = (byte[]) input.getKeyComponent(1); - return secondKey[secondKey.length - 1] % 2 == 0; - } - } - - /** - * Writes elements to an Ism file using an IsmSink. Then reads them back with an IsmReader - * using a random order. - */ - private void writeElementsToFileAndReadInRandomOrder(Iterable> elements) - throws Exception { - File tmpFile = tmpFolder.newFile(); - List> oddSecondaryKeys = new ArrayList<>( - ImmutableList.copyOf(Iterables.filter(elements, Predicates.not(EvenFilter.INSTANCE)))); - List> evenSecondaryKeys = new ArrayList<>( - ImmutableList.copyOf(Iterables.filter(elements, EvenFilter.INSTANCE))); - - writeElementsToFile(oddSecondaryKeys, tmpFile); - IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), CODER, cache); - - // Test using next() for a within shard Ism prefix reader iterator - Collections.shuffle(oddSecondaryKeys); - for (IsmRecord expectedNext : oddSecondaryKeys) { - assertIsmEquals(reader.overKeyComponents( - expectedNext.getKeyComponents()).next().getValue(), expectedNext); - } - - Collections.shuffle(oddSecondaryKeys); - // Test using get() for a shard aware Ism prefix reader - IsmReader.IsmPrefixReaderIterator readerIterator = - reader.overKeyComponents(ImmutableList.of()); - for (IsmRecord expectedNext : oddSecondaryKeys) { - assertIsmEquals(readerIterator.get(expectedNext.getKeyComponents()).getValue(), expectedNext); - } - - // Test using next() for a within shard Ism prefix reader iterator - Collections.shuffle(evenSecondaryKeys); - for (IsmRecord missingNext : evenSecondaryKeys) { - assertFalse(reader.overKeyComponents(missingNext.getKeyComponents()).hasNext()); - } - - Collections.shuffle(evenSecondaryKeys); - // Test using get() for a shard aware Ism prefix reader - readerIterator = reader.overKeyComponents(ImmutableList.of()); - for (IsmRecord missingNext : evenSecondaryKeys) { - assertNull(readerIterator.get(missingNext.getKeyComponents())); - } - } - - private void writeElementsToFileAndFindLastElementPerPrimaryKey( - Iterable> elements) throws Exception { - File tmpFile = tmpFolder.newFile(); - Iterable> oddValues = - Iterables.filter(elements, Predicates.not(EvenFilter.INSTANCE)); - Iterable> evenValues = - Iterables.filter(elements, EvenFilter.INSTANCE); - writeElementsToFile(oddValues, tmpFile); - IsmReader reader = new IsmReader<>(tmpFile.getAbsolutePath(), CODER, cache); - - SortedMap>> sortedBySecondKey = - new TreeMap<>(UnsignedBytes.lexicographicalComparator()); - for (IsmRecord element : oddValues) { - byte[] encodedPrimaryKey = - CoderUtils.encodeToByteArray(CODER.getKeyComponentCoder(0), element.getKeyComponent(0)); - if (!sortedBySecondKey.containsKey(encodedPrimaryKey)) { - sortedBySecondKey.put( - encodedPrimaryKey, new TreeSet<>(new IsmRecordKeyComparator<>(CODER))); - } - sortedBySecondKey.get(encodedPrimaryKey).add(element); - } - - // The returned value should have the element as a prefix of itself. - for (IsmRecord element : oddValues) { - byte[] encodedPrimaryKey = - CoderUtils.encodeToByteArray(CODER.getKeyComponentCoder(0), element.getKeyComponent(0)); - assertIsmEquals( - reader.overKeyComponents( - ImmutableList.of(element.getKeyComponent(0))).getLast().getValue(), - sortedBySecondKey.get(encodedPrimaryKey).last()); - } - - // The returned value should always have the element as a prefix of itself or not exist. - for (IsmRecord element : evenValues) { - byte[] encodedPrimaryKey = - CoderUtils.encodeToByteArray(CODER.getKeyComponentCoder(0), element.getKeyComponent(0)); - IsmReader.IsmPrefixReaderIterator readerIterator = - reader.overKeyComponents(ImmutableList.of(element.getKeyComponent(0))); - WindowedValue> lastWindowedValue = readerIterator.getLast(); - if (lastWindowedValue != null) { - assertIsmEquals( - lastWindowedValue.getValue(), - sortedBySecondKey.get(encodedPrimaryKey).last()); - } - } - } - - static class IsmRecordKeyComparator implements Comparator> { - private final IsmRecordCoder coder; - IsmRecordKeyComparator(IsmRecordCoder coder) { - this.coder = coder; - } - - @Override - public int compare(IsmRecord first, IsmRecord second) { - RandomAccessData firstKeyBytes = new RandomAccessData(); - coder.encodeAndHash(first.getKeyComponents(), firstKeyBytes); - RandomAccessData secondKeyBytes = new RandomAccessData(); - coder.encodeAndHash(second.getKeyComponents(), secondKeyBytes); - return RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - firstKeyBytes, secondKeyBytes); - } - } - - /** - * Specifies the minimum key size so that we can produce a random byte array - * with enough of a prefix to be able to create successively larger secondary keys. - */ - private static final int MIN_KEY_SIZE = 4; - - /** Specifies the percentage of keys that are metadata records when using the data generator. */ - private static final double PERCENT_METADATA_RECORDS = 0.01; - - /** - * Creates a map from Ism shard to a sorted set of IsmRecords. - */ - private Map>> dataGeneratorPerShard( - final int numberOfPrimaryKeys, - final int minNumberOfSecondaryKeys, - final int maxKeySize, - final int maxValueSize) { - checkState(maxKeySize >= MIN_KEY_SIZE); - - final Random random = new Random(minNumberOfSecondaryKeys); - - Map>> shardToRecordMap = new HashMap<>(); - while (shardToRecordMap.keySet().size() < numberOfPrimaryKeys) { - // Generate the next primary key - byte[] primaryKey = new byte[random.nextInt(maxKeySize - MIN_KEY_SIZE) + MIN_KEY_SIZE]; - random.nextBytes(primaryKey); - int shardId = CODER.hash(ImmutableList.of(primaryKey)); - // Add a sorted set for the shard id if this shard id has never been generated before. - if (!shardToRecordMap.containsKey(shardId)) { - shardToRecordMap.put(shardId, - new TreeSet>(new IsmRecordKeyComparator(CODER))); - } - - // Generate the requested number of secondary keys using the newly generated primary key. - byte[] secondaryKey = new byte[maxKeySize]; - for (int j = 0; j < minNumberOfSecondaryKeys; ++j) { - secondaryKey = generateNextSecondaryKey(random, maxKeySize, secondaryKey); - - // Generate the value bytes. - byte[] value = new byte[random.nextInt(maxValueSize)]; - random.nextBytes(value); - - // 1% of keys are metadata records - if (random.nextFloat() < PERCENT_METADATA_RECORDS) { - IsmRecord ismRecord = IsmRecord.meta( - ImmutableList.of(IsmFormat.getMetadataKey(), secondaryKey), value); - int metadataShardId = CODER.hash(ismRecord.getKeyComponents()); - // Add a sorted set for the shard id if this shard id has never been generated before. - if (!shardToRecordMap.containsKey(metadataShardId)) { - shardToRecordMap.put(metadataShardId, - new TreeSet>( - new IsmRecordKeyComparator(CODER))); - } - shardToRecordMap.get(metadataShardId).add(ismRecord); - } else { - IsmRecord ismRecord = IsmRecord.of( - ImmutableList.of(primaryKey, secondaryKey), - value); - shardToRecordMap.get(shardId).add(ismRecord); - } - } - } - return shardToRecordMap; - } - - private byte[] generateNextSecondaryKey( - Random random, int maxKeySize, byte[] previousSecondaryKey) { - byte[] currentSecondaryKey = - new byte[random.nextInt(maxKeySize - MIN_KEY_SIZE) + MIN_KEY_SIZE]; - int matchingPrefix = Math.min(currentSecondaryKey.length, - random.nextInt(maxKeySize - MIN_KEY_SIZE) + MIN_KEY_SIZE); - byte[] randomSuffix = new byte[currentSecondaryKey.length - matchingPrefix]; - random.nextBytes(randomSuffix); - - System.arraycopy(previousSecondaryKey, 0, - currentSecondaryKey, 0, - Math.min(currentSecondaryKey.length, previousSecondaryKey.length)); - System.arraycopy(randomSuffix, 0, - currentSecondaryKey, matchingPrefix, randomSuffix.length); - - matchingPrefix -= 1; - // Find the first byte which is less than 255 at the end of the matching portion. - while ((currentSecondaryKey[matchingPrefix] & 0xFF) == 0xFF) { - currentSecondaryKey[matchingPrefix] = 0; - matchingPrefix -= 1; - } - // Increment the last byte of the matching prefix to make sure this key is - // larger than the previous key. - currentSecondaryKey[matchingPrefix] = - (byte) ((currentSecondaryKey[matchingPrefix] & 0xFF) + 1); - return currentSecondaryKey; - } - - /** - * Creates an iterable of IsmRecords grouped by shard id, and in ascending order per shard. - */ - private Iterable> dataGenerator( - final int numberOfPrimaryKeys, - final int numberOfSecondaryKeys, - final int approximateKeySize, - final int maxValueSize) { - - FluentIterable> records = FluentIterable - .from(dataGeneratorPerShard( - numberOfPrimaryKeys, numberOfSecondaryKeys, - approximateKeySize, maxValueSize).entrySet()) - .transformAndConcat( - new Function>>, - Iterable>>() { - @Override - public Iterable> apply( - Entry>> input) { - return input.getValue(); - } - }); - return records; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java deleted file mode 100644 index d8e3502a74..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; -import com.google.cloud.dataflow.sdk.testing.CoderPropertiesTest.NonDeterministicCoder; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink.SinkWriter; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link IsmSink}. - * - *

    Note that {@link IsmReaderTest} covers reading/writing tests. This tests - * error cases for the {@link IsmSink}. - */ -@RunWith(JUnit4.class) -public class IsmSinkTest { - private static final IsmRecordCoder CODER = - IsmRecordCoder.of( - 1, // number or shard key coders for value records - 1, // number of shard key coders for metadata records - ImmutableList.>of(MetadataKeyCoder.of(ByteArrayCoder.of()), ByteArrayCoder.of()), - ByteArrayCoder.of()); - private static final byte[] EMPTY = new byte[0]; - private static final Coder NON_DETERMINISTIC_CODER = new NonDeterministicCoder(); - - - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testWriteOutOfOrderKeysWithSameShardKeyIsError() throws Throwable { - IsmSink sink = - new IsmSink<>(tmpFolder.newFile().getPath(), CODER); - SinkWriter>> sinkWriter = sink.writer(); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x01 }), EMPTY))); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("expects keys to be written in strictly increasing order"); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x00 }), EMPTY))); - } - - @Test - public void testWriteNonContiguousShardsIsError() throws Throwable { - IsmSink sink = - new IsmSink<>(tmpFolder.newFile().getPath(), CODER); - SinkWriter>> sinkWriter = sink.writer(); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(new byte[]{ 0x00 }, EMPTY), EMPTY))); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(new byte[]{ 0x01 }, EMPTY), EMPTY))); - - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("for shard which already exists"); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(new byte[]{ 0x00 }, EMPTY), EMPTY))); - } - - @Test - public void testWriteEqualKeysIsError() throws Throwable { - IsmSink sink = - new IsmSink<>(tmpFolder.newFile().getPath(), CODER); - SinkWriter>> sinkWriter = sink.writer(); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x01 }), EMPTY))); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("expects keys to be written in strictly increasing order"); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x01 }), EMPTY))); - } - - @Test - public void testWriteKeyWhichIsProperPrefixOfPreviousSecondaryKeyIsError() throws Throwable { - IsmSink sink = - new IsmSink<>(tmpFolder.newFile().getPath(), CODER); - SinkWriter>> sinkWriter = sink.writer(); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x00, 0x00 }), EMPTY))); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("expects keys to be written in strictly increasing order"); - sinkWriter.add(valueInEmptyWindows( - IsmRecord.of(ImmutableList.of(EMPTY, new byte[]{ 0x00 }), EMPTY))); - } - - @Test - public void testUsingNonDeterministicShardKeyCoder() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("is expected to be deterministic"); - new IsmSink<>(tmpFolder.newFile().getPath(), IsmRecordCoder.of( - 1, - 0, - ImmutableList.>of(NON_DETERMINISTIC_CODER, ByteArrayCoder.of()), - ByteArrayCoder.of())); - } - - @Test - public void testUsingNonDeterministicNonShardKeyCoder() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("is expected to be deterministic"); - new IsmSink<>(tmpFolder.newFile().getPath(), IsmRecordCoder.of( - 1, - 0, - ImmutableList.>of(ByteArrayCoder.of(), NON_DETERMINISTIC_CODER), - ByteArrayCoder.of())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java deleted file mode 100644 index 8507fb90d9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidExceptionTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link KeyTokenInvalidException}. */ -@RunWith(JUnit4.class) -public final class KeyTokenInvalidExceptionTest { - @Test - public void testIsKeyTokenInvalidException() throws Exception { - KeyTokenInvalidException exception = new KeyTokenInvalidException("test"); - RuntimeException keyTokenCauseException = new RuntimeException("key token cause", exception); - assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(exception)); - assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(keyTokenCauseException)); - assertFalse(KeyTokenInvalidException.isKeyTokenInvalidException( - new RuntimeException("non key token"))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemsTest.java deleted file mode 100644 index 8db559c14d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItemsTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CollectionCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.protobuf.ByteString; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; - -/** Tests for {@link KeyedWorkItems}. */ -@RunWith(JUnit4.class) -public class KeyedWorkItemsTest { - - private static final String STATE_FAMILY = "state"; - private static final String KEY = "key"; - private static final ByteString SERIALIZED_KEY = ByteString.copyFromUtf8(KEY); - - private static final Coder WINDOW_CODER = IntervalWindow.getCoder(); - @SuppressWarnings({"unchecked", "rawtypes"}) - private static final Coder> WINDOWS_CODER = - (Coder) CollectionCoder.of(WINDOW_CODER); - private static final Coder VALUE_CODER = StringUtf8Coder.of(); - private static final IntervalWindow WINDOW_1 = - new IntervalWindow(new Instant(0), new Instant(10)); - private static final StateNamespace STATE_NAMESPACE_1 = - StateNamespaces.window(WINDOW_CODER, WINDOW_1); - private static final IntervalWindow WINDOW_2 = - new IntervalWindow(new Instant(10), new Instant(20)); - private static final StateNamespace STATE_NAMESPACE_2 = - StateNamespaces.window(WINDOW_CODER, WINDOW_2); - - @Mock - private StreamingModeExecutionContext mockContext; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testElementIteration() throws Exception { - Windmill.WorkItem.Builder workItem = Windmill.WorkItem.newBuilder() - .setKey(SERIALIZED_KEY) - .setWorkToken(17); - Windmill.InputMessageBundle.Builder chunk1 = workItem.addMessageBundlesBuilder(); - chunk1.setSourceComputationId("computation"); - addElement(chunk1, 5, "hello", WINDOW_1, paneInfo(0)); - addElement(chunk1, 7, "world", WINDOW_2, paneInfo(2)); - Windmill.InputMessageBundle.Builder chunk2 = workItem.addMessageBundlesBuilder(); - chunk2.setSourceComputationId("computation"); - addElement(chunk2, 6, "earth", WINDOW_1, paneInfo(1)); - - KeyedWorkItem keyedWorkItem = KeyedWorkItems.windmillWorkItem( - KEY, workItem.build(), WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); - - assertThat(keyedWorkItem.elementsIterable(), Matchers.contains( - WindowedValue.of("hello", new Instant(5), WINDOW_1, paneInfo(0)), - WindowedValue.of("world", new Instant(7), WINDOW_2, paneInfo(2)), - WindowedValue.of("earth", new Instant(6), WINDOW_1, paneInfo(1)))); - } - - private void addElement( - Windmill.InputMessageBundle.Builder chunk, long timestamp, String value, - IntervalWindow window, PaneInfo pane) throws IOException { - ByteString encodedMetadata = - WindmillSink.encodeMetadata(WINDOWS_CODER, Collections.singletonList(window), pane); - chunk.addMessagesBuilder() - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(new Instant(timestamp))) - .setData(ByteString.copyFromUtf8(value)) - .setMetadata(encodedMetadata); - } - - private PaneInfo paneInfo(int index) { - return PaneInfo.createPane(false, false, Timing.EARLY, index, -1); - } - - /** Make sure that event time timers are processed before other timers. */ - @Test - public void testTimerOrdering() throws Exception { - Windmill.WorkItem workItem = Windmill.WorkItem.newBuilder() - .setKey(SERIALIZED_KEY) - .setWorkToken(17) - .setTimers(Windmill.TimerBundle.newBuilder() - .addTimers(makeSerializedTimer(STATE_NAMESPACE_1, 0, Windmill.Timer.Type.REALTIME)) - .addTimers(makeSerializedTimer(STATE_NAMESPACE_1, 1, Windmill.Timer.Type.WATERMARK)) - .addTimers(makeSerializedTimer(STATE_NAMESPACE_1, 2, Windmill.Timer.Type.REALTIME)) - .addTimers(makeSerializedTimer(STATE_NAMESPACE_2, 3, Windmill.Timer.Type.WATERMARK)) - .build()) - .build(); - - KeyedWorkItem keyedWorkItem = - KeyedWorkItems.windmillWorkItem(KEY, workItem, WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); - - assertThat(keyedWorkItem.timersIterable(), Matchers.contains( - makeTimer(STATE_NAMESPACE_1, 1, TimeDomain.EVENT_TIME), - makeTimer(STATE_NAMESPACE_2, 3, TimeDomain.EVENT_TIME), - makeTimer(STATE_NAMESPACE_1, 0, TimeDomain.PROCESSING_TIME), - makeTimer(STATE_NAMESPACE_1, 2, TimeDomain.PROCESSING_TIME))); - } - - private static Windmill.Timer makeSerializedTimer( - StateNamespace ns, long timestamp, Windmill.Timer.Type type) { - return Windmill.Timer.newBuilder() - .setTag(ByteString.copyFromUtf8( - ns.stringKey() + "+" + type + "-" + timestamp)) - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(new Instant(timestamp))) - .setType(type) - .setStateFamily(STATE_FAMILY) - .build(); - } - - private static TimerData makeTimer(StateNamespace ns, long timestamp, TimeDomain domain) { - return TimerData.of(ns, new Instant(timestamp), domain); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java deleted file mode 100644 index 777b3545c2..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactoryTest.java +++ /dev/null @@ -1,636 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.DataflowOutputCounter.getElementCounterName; -import static com.google.cloud.dataflow.sdk.runners.worker.DataflowOutputCounter.getMeanByteCounterName; -import static com.google.cloud.dataflow.sdk.runners.worker.DataflowOutputCounter.getObjectCounterName; -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; -import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; - -import com.google.api.services.dataflow.model.FlattenInstruction; -import com.google.api.services.dataflow.model.InstructionInput; -import com.google.api.services.dataflow.model.InstructionOutput; -import com.google.api.services.dataflow.model.MapTask; -import com.google.api.services.dataflow.model.ParDoInstruction; -import com.google.api.services.dataflow.model.ParallelInstruction; -import com.google.api.services.dataflow.model.PartialGroupByKeyInstruction; -import com.google.api.services.dataflow.model.ReadInstruction; -import com.google.api.services.dataflow.model.Source; -import com.google.api.services.dataflow.model.WriteInstruction; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactoryTest.SingletonTestReaderFactory; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactoryTest.TestReader; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactoryTest.TestReaderFactory; -import com.google.cloud.dataflow.sdk.runners.worker.SinkFactoryTest.TestSink; -import com.google.cloud.dataflow.sdk.runners.worker.SinkFactoryTest.TestSinkFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils.TestOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.FlattenOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor; -import com.google.cloud.dataflow.sdk.util.common.worker.Operation; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.common.worker.WriteOperation; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests for MapTaskExecutorFactory. - */ -@RunWith(JUnit4.class) -public class MapTaskExecutorFactoryTest { - - private static final CloudObject windowedStringCoder = - WindowedValue.getValueOnlyCoder(StringUtf8Coder.of()).asCloudObject(); - - private PipelineOptions options; - private ReaderRegistry readerFactoryRegistry; - - @Before - public void setUp() { - options = PipelineOptionsFactory.create(); - readerFactoryRegistry = ReaderRegistry.defaultRegistry() - .register( - TestReaderFactory.class.getName(), - new TestReaderFactory()) - .register( - SingletonTestReaderFactory.class.getName(), - new SingletonTestReaderFactory()); - } - - @Test - public void testCreateMapTaskExecutor() throws Exception { - List instructions = Arrays.asList( - createReadInstruction("Read"), - createParDoInstruction(0, 0, "DoFn1"), - createParDoInstruction(0, 0, "DoFnWithContext"), - createFlattenInstruction(1, 0, 2, 0, "Flatten"), - createWriteInstruction(3, 0, "Write")); - - MapTask mapTask = new MapTask(); - mapTask.setStageName("test"); - mapTask.setSystemName("stageName"); - mapTask.setInstructions(instructions); - - CounterSet counterSet = new CounterSet(); - StateSampler sampler = - new StateSampler(mapTask.getStageName() + "-", counterSet.getAddCounterMutator()); - try ( - MapTaskExecutor executor = MapTaskExecutorFactory.create( - options, - mapTask, - readerFactoryRegistry, - BatchModeExecutionContext.fromOptions(options), - counterSet, - sampler)) { - // Safe covariant cast not expressible without rawtypes. - @SuppressWarnings({"rawtypes", "unchecked"}) - List operations = (List) executor.operations; - assertThat( - operations, - hasItems( - instanceOf(ReadOperation.class), - instanceOf(ParDoOperation.class), - instanceOf(ParDoOperation.class), - instanceOf(FlattenOperation.class), - instanceOf(WriteOperation.class))); - counterSet = executor.getOutputCounters(); - } - - @SuppressWarnings("unchecked") - Counter otherMsecCounter = - (Counter) counterSet.getExistingCounter("test-other-msecs"); - - // "other" state only got created upon MapTaskExecutor.execute(). - assertNull(otherMsecCounter); - - assertEquals( - new CounterSet( - Counter.longs(getElementCounterName("read_output_name"), SUM).resetToValue(0L), - Counter.longs(getObjectCounterName("read_output_name"), SUM).resetToValue(0L), - Counter.longs(getMeanByteCounterName("read_output_name"), MEAN).resetMeanToValue(0, 0L), - Counter.longs("Read-ByteCount", SUM).resetToValue(0L), - Counter.doubles("dataflow_total_parallelism-stageName", SUM) - .resetToValue(ReadOperation.LARGE_PARALLELISM_BOUND), - Counter.doubles("dataflow_remaining_parallelism-stageName", SUM).resetToValue(0.0), - Counter.longs("test-Read-start-msecs", SUM).resetToValue(0L), - Counter.longs("test-Read-process-msecs", SUM).resetToValue(0L), - Counter.longs("test-Read-finish-msecs", SUM).resetToValue(0L), - Counter.longs(getElementCounterName("DoFn1_output"), SUM).resetToValue(0L), - Counter.longs(getObjectCounterName("DoFn1_output"), SUM).resetToValue(0L), - Counter.longs(getMeanByteCounterName("DoFn1_output"), MEAN).resetMeanToValue(0, 0L), - Counter.longs("test-DoFn1-start-msecs", SUM).resetToValue(0L), - Counter.longs("test-DoFn1-process-msecs", SUM).resetToValue(0L), - Counter.longs("test-DoFn1-finish-msecs", SUM).resetToValue(0L), - Counter.longs(getElementCounterName("DoFnWithContext_output"), SUM).resetToValue(0L), - Counter.longs(getObjectCounterName("DoFnWithContext_output"), SUM).resetToValue(0L), - Counter.longs(getMeanByteCounterName("DoFnWithContext_output"), MEAN) - .resetMeanToValue(0, 0L), - Counter.longs("test-DoFnWithContext-start-msecs", SUM).resetToValue(0L), - Counter.longs("test-DoFnWithContext-process-msecs", SUM).resetToValue(0L), - Counter.longs("test-DoFnWithContext-finish-msecs", SUM).resetToValue(0L), - Counter.longs(getElementCounterName("flatten_output_name"), SUM).resetToValue(0L), - Counter.longs(getObjectCounterName("flatten_output_name"), SUM).resetToValue(0L), - Counter.longs(getMeanByteCounterName("flatten_output_name"), MEAN) - .resetMeanToValue(0, 0L), - Counter.longs("test-Flatten-start-msecs", SUM).resetToValue(0L), - Counter.longs("test-Flatten-process-msecs", SUM).resetToValue(0L), - Counter.longs("test-Flatten-finish-msecs", SUM).resetToValue(0L), - Counter.longs("Write-ByteCount", SUM).resetToValue(0L), - Counter.longs("test-Write-start-msecs", SUM).resetToValue(0L), - Counter.longs("test-Write-process-msecs", SUM).resetToValue(0L), - Counter.longs("test-Write-finish-msecs", SUM).resetToValue(0L)), - counterSet); - } - - @Test - public void testExecutionContextPlumbing() throws Exception { - List instructions = Arrays.asList( - createReadInstruction("Read", SingletonTestReaderFactory.class), - createParDoInstruction(0, 0, "DoFn1", "DoFnUserName"), - createParDoInstruction(1, 0, "DoFnWithContext", "DoFnWithContextUserName")); - - MapTask mapTask = new MapTask(); - mapTask.setStageName("test"); - mapTask.setInstructions(instructions); - - BatchModeExecutionContext context = BatchModeExecutionContext.fromOptions(options); - - CounterSet counters = new CounterSet(); - try (MapTaskExecutor executor = - MapTaskExecutorFactory.create( - options, - mapTask, - readerFactoryRegistry, - context, - counters, - new StateSampler(mapTask.getStageName() + "-", counters.getAddCounterMutator()))) { - executor.execute(); - } - - List stepNames = new ArrayList<>(); - for (ExecutionContext.StepContext stepContext : context.getAllStepContexts()) { - stepNames.add(stepContext.getStepName()); - } - assertThat(stepNames, hasItems("DoFn1", "DoFnWithContext")); - } - - static ParallelInstruction createReadInstruction(String name) { - return createReadInstruction(name, TestReaderFactory.class); - } - - static ParallelInstruction createReadInstruction( - String name, Class readerFactoryClass) { - CloudObject spec = CloudObject.forClass(readerFactoryClass); - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(windowedStringCoder); - - ReadInstruction readInstruction = new ReadInstruction(); - readInstruction.setSource(cloudSource); - - InstructionOutput output = new InstructionOutput(); - output.setName("read_output_name"); - output.setCodec(windowedStringCoder); - - ParallelInstruction instruction = new ParallelInstruction(); - instruction.setSystemName(name); - instruction.setRead(readInstruction); - instruction.setOutputs(Arrays.asList(output)); - - return instruction; - } - - @Test - public void testCreateReadOperation() throws Exception { - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - String systemStageName = "stageName"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - Operation operation = MapTaskExecutorFactory.createOperation( - PipelineOptionsFactory.create(), - createReadInstruction("Read"), - readerFactoryRegistry, - BatchModeExecutionContext.fromOptions(options), - Collections.emptyList(), - counterPrefix, - systemStageName, - counterSet.getAddCounterMutator(), - stateSampler); - assertThat(operation, instanceOf(ReadOperation.class)); - ReadOperation readOperation = (ReadOperation) operation; - - assertEquals(readOperation.receivers.length, 1); - assertEquals(readOperation.receivers[0].getReceiverCount(), 0); - assertEquals(readOperation.initializationState, Operation.InitializationState.UNSTARTED); - assertThat(readOperation.reader, instanceOf(TestReader.class)); - - assertEquals( - new CounterSet( - Counter.longs("test-Read-start-msecs", SUM).resetToValue(0L), - Counter.longs("Read-ByteCount", SUM).resetToValue(0L), - Counter.doubles("dataflow_total_parallelism-stageName", SUM) - .resetToValue(ReadOperation.LARGE_PARALLELISM_BOUND), - Counter.doubles("dataflow_remaining_parallelism-stageName", SUM).resetToValue(0.0), - Counter.longs("test-Read-finish-msecs", SUM).resetToValue(0L), - Counter.longs("test-Read-process-msecs", SUM), - Counter.longs(getMeanByteCounterName("read_output_name"), MEAN).resetMeanToValue(0, 0L), - Counter.longs(getElementCounterName("read_output_name"), SUM).resetToValue(0L), - Counter.longs(getObjectCounterName("read_output_name"), SUM).resetToValue(0L)), - counterSet); - } - - static ParallelInstruction createWriteInstruction( - int producerIndex, int producerOutputNum, String systemName) { - InstructionInput cloudInput = new InstructionInput(); - cloudInput.setProducerInstructionIndex(producerIndex); - cloudInput.setOutputNum(producerOutputNum); - - CloudObject spec = CloudObject.forClass(TestSinkFactory.class); - - com.google.api.services.dataflow.model.Sink cloudSink = - new com.google.api.services.dataflow.model.Sink(); - cloudSink.setSpec(spec); - cloudSink.setCodec(windowedStringCoder); - - WriteInstruction writeInstruction = new WriteInstruction(); - writeInstruction.setInput(cloudInput); - writeInstruction.setSink(cloudSink); - - ParallelInstruction instruction = new ParallelInstruction(); - instruction.setWrite(writeInstruction); - instruction.setSystemName(systemName); - - return instruction; - } - - @SuppressWarnings("unchecked") - @Test - public void testCreateWriteOperation() throws Exception { - List priorOperations = Arrays.asList( - new Operation[] {new TestOperation(3), new TestOperation(5), new TestOperation(1)}); - - int producerIndex = 1; - int producerOutputNum = 2; - - ParallelInstruction instruction = - createWriteInstruction(producerIndex, producerOutputNum, "WriteOperation"); - - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - String systemStageName = "stageName"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - Operation operation = MapTaskExecutorFactory.createOperation(options, - instruction, BatchModeExecutionContext.fromOptions(options), priorOperations, counterPrefix, - systemStageName, counterSet.getAddCounterMutator(), stateSampler); - assertThat(operation, instanceOf(WriteOperation.class)); - WriteOperation writeOperation = (WriteOperation) operation; - - assertEquals(writeOperation.receivers.length, 0); - assertEquals(writeOperation.initializationState, Operation.InitializationState.UNSTARTED); - assertThat(writeOperation.sink, instanceOf(TestSink.class)); - - assertSame( - writeOperation, - priorOperations.get(producerIndex).receivers[producerOutputNum].getOnlyReceiver()); - - assertEquals( - new CounterSet(Counter.longs("WriteOperation-ByteCount", SUM).resetToValue(0L), - Counter.longs("test-WriteOperation-start-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-WriteOperation-start-msecs")).getAggregate()), - Counter.longs("test-WriteOperation-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-WriteOperation-process-msecs")).getAggregate()), - Counter.longs("test-WriteOperation-finish-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-WriteOperation-finish-msecs")).getAggregate())), - counterSet); - } - - static class TestDoFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element()); - } - } - - static ParallelInstruction createParDoInstruction( - int producerIndex, int producerOutputNum, String systemName) { - return createParDoInstruction(producerIndex, producerOutputNum, systemName, ""); - } - - static ParallelInstruction createParDoInstruction( - int producerIndex, int producerOutputNum, String systemName, String userName) { - InstructionInput cloudInput = new InstructionInput(); - cloudInput.setProducerInstructionIndex(producerIndex); - cloudInput.setOutputNum(producerOutputNum); - - TestDoFn fn = new TestDoFn(); - - String serializedFn = - StringUtils.byteArrayToJsonString( - SerializableUtils.serializeToByteArray( - new DoFnInfo<>(fn, WindowingStrategy.globalDefault()))); - - CloudObject cloudUserFn = CloudObject.forClassName("DoFn"); - addString(cloudUserFn, PropertyNames.SERIALIZED_FN, serializedFn); - - ParDoInstruction parDoInstruction = new ParDoInstruction(); - parDoInstruction.setInput(cloudInput); - parDoInstruction.setNumOutputs(1); - parDoInstruction.setUserFn(cloudUserFn); - - InstructionOutput output = new InstructionOutput(); - output.setName(systemName + "_output"); - output.setCodec(windowedStringCoder); - - ParallelInstruction instruction = new ParallelInstruction(); - instruction.setParDo(parDoInstruction); - instruction.setOutputs(Arrays.asList(output)); - instruction.setSystemName(systemName); - instruction.setName(userName); - return instruction; - } - - @Test - public void testCreateParDoOperation() throws Exception { - List priorOperations = Arrays.asList( - new Operation[] {new TestOperation(3), new TestOperation(5), new TestOperation(1)}); - - int producerIndex = 1; - int producerOutputNum = 2; - - ParallelInstruction instruction = - createParDoInstruction(producerIndex, producerOutputNum, "DoFn"); - - BatchModeExecutionContext context = - BatchModeExecutionContext.fromOptions(options); - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - String systemStageName = "stageName"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - Operation operation = MapTaskExecutorFactory.createOperation( - options, - instruction, - readerFactoryRegistry, - context, - priorOperations, - counterPrefix, - systemStageName, - counterSet.getAddCounterMutator(), - stateSampler); - assertThat(operation, instanceOf(ParDoOperation.class)); - ParDoOperation parDoOperation = (ParDoOperation) operation; - - assertEquals(parDoOperation.receivers.length, 1); - assertEquals(parDoOperation.receivers[0].getReceiverCount(), 0); - assertEquals(parDoOperation.initializationState, Operation.InitializationState.UNSTARTED); - assertThat(parDoOperation.getFn(), instanceOf(NormalParDoFn.class)); - NormalParDoFn normalParDoFn = (NormalParDoFn) parDoOperation.getFn(); - - assertThat( - normalParDoFn.getDoFnInfo().getDoFn(), - instanceOf(TestDoFn.class)); - - assertSame( - parDoOperation, - priorOperations.get(producerIndex).receivers[producerOutputNum].getOnlyReceiver()); - - assertEquals(context, normalParDoFn.getExecutionContext()); - } - - static ParallelInstruction createPartialGroupByKeyInstruction( - int producerIndex, int producerOutputNum) { - InstructionInput cloudInput = new InstructionInput(); - cloudInput.setProducerInstructionIndex(producerIndex); - cloudInput.setOutputNum(producerOutputNum); - - PartialGroupByKeyInstruction pgbkInstruction = new PartialGroupByKeyInstruction(); - pgbkInstruction.setInput(cloudInput); - pgbkInstruction.setInputElementCodec(makeCloudEncoding( - FullWindowedValueCoder.class.getName(), - makeCloudEncoding("KvCoder", makeCloudEncoding("StringUtf8Coder"), - makeCloudEncoding("BigEndianIntegerCoder")), - IntervalWindow.getCoder().asCloudObject())); - - InstructionOutput output = new InstructionOutput(); - output.setName("pgbk_output_name"); - output.setCodec(makeCloudEncoding("KvCoder", makeCloudEncoding("StringUtf8Coder"), - makeCloudEncoding("IterableCoder", makeCloudEncoding("BigEndianIntegerCoder")))); - - ParallelInstruction instruction = new ParallelInstruction(); - instruction.setPartialGroupByKey(pgbkInstruction); - instruction.setOutputs(Arrays.asList(output)); - - return instruction; - } - - @Test - public void testCreatePartialGroupByKeyOperation() throws Exception { - List priorOperations = Arrays.asList( - new Operation[] {new TestOperation(3), new TestOperation(5), new TestOperation(1)}); - - int producerIndex = 1; - int producerOutputNum = 2; - - ParallelInstruction instruction = - createPartialGroupByKeyInstruction(producerIndex, producerOutputNum); - - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - String systemStageName = "stageName"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - Operation operation = MapTaskExecutorFactory.createOperation( - options, - instruction, - readerFactoryRegistry, - BatchModeExecutionContext.fromOptions(options), - priorOperations, - counterPrefix, - systemStageName, - counterSet.getAddCounterMutator(), - stateSampler); - assertThat(operation, instanceOf(PartialGroupByKeyOperation.class)); - PartialGroupByKeyOperation pgbkOperation = (PartialGroupByKeyOperation) operation; - - assertEquals(pgbkOperation.receivers.length, 1); - assertEquals(pgbkOperation.receivers[0].getReceiverCount(), 0); - assertEquals(pgbkOperation.initializationState, Operation.InitializationState.UNSTARTED); - - assertSame( - pgbkOperation, - priorOperations.get(producerIndex).receivers[producerOutputNum].getOnlyReceiver()); - } - - @Test - public void testCreatePartialGroupByKeyOperationWithCombine() throws Exception { - List priorOperations = Arrays.asList( - new Operation[] {new TestOperation(3), new TestOperation(5), new TestOperation(1)}); - - int producerIndex = 1; - int producerOutputNum = 2; - - ParallelInstruction instruction = - createPartialGroupByKeyInstruction(producerIndex, producerOutputNum); - - AppliedCombineFn combineFn = AppliedCombineFn.withInputCoder( - new Sum.SumIntegerFn().asKeyedFn(), new CoderRegistry(), - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of())); - CloudObject cloudCombineFn = CloudObject.forClassName("CombineFn"); - addString(cloudCombineFn, PropertyNames.SERIALIZED_FN, - byteArrayToJsonString(serializeToByteArray(combineFn))); - instruction.getPartialGroupByKey().setValueCombiningFn(cloudCombineFn); - - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - String systemStageName = "stageName"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - Operation operation = MapTaskExecutorFactory.createOperation( - options, - instruction, - readerFactoryRegistry, - BatchModeExecutionContext.fromOptions(options), - priorOperations, - counterPrefix, - systemStageName, - counterSet.getAddCounterMutator(), - stateSampler); - assertThat(operation, instanceOf(PartialGroupByKeyOperation.class)); - PartialGroupByKeyOperation pgbkOperation = (PartialGroupByKeyOperation) operation; - - assertEquals(pgbkOperation.receivers.length, 1); - assertEquals(pgbkOperation.receivers[0].getReceiverCount(), 0); - assertEquals(pgbkOperation.initializationState, Operation.InitializationState.UNSTARTED); - assertSame( - pgbkOperation, - priorOperations.get(producerIndex).receivers[producerOutputNum].getOnlyReceiver()); - } - - static ParallelInstruction createFlattenInstruction(int producerIndex1, int producerOutputNum1, - int producerIndex2, int producerOutputNum2, String systemName) { - List cloudInputs = new ArrayList<>(); - - InstructionInput cloudInput1 = new InstructionInput(); - cloudInput1.setProducerInstructionIndex(producerIndex1); - cloudInput1.setOutputNum(producerOutputNum1); - cloudInputs.add(cloudInput1); - - InstructionInput cloudInput2 = new InstructionInput(); - cloudInput2.setProducerInstructionIndex(producerIndex2); - cloudInput2.setOutputNum(producerOutputNum2); - cloudInputs.add(cloudInput2); - - FlattenInstruction flattenInstruction = new FlattenInstruction(); - flattenInstruction.setInputs(cloudInputs); - - InstructionOutput output = new InstructionOutput(); - output.setName("flatten_output_name"); - output.setCodec(makeCloudEncoding(StringUtf8Coder.class.getName())); - - ParallelInstruction instruction = new ParallelInstruction(); - instruction.setFlatten(flattenInstruction); - instruction.setOutputs(Arrays.asList(output)); - instruction.setSystemName(systemName); - - return instruction; - } - - @Test - public void testCreateFlattenOperation() throws Exception { - List priorOperations = Arrays.asList( - new Operation[] {new TestOperation(3), new TestOperation(5), new TestOperation(1)}); - - int producerIndex1 = 1; - int producerOutputNum1 = 2; - int producerIndex2 = 0; - int producerOutputNum2 = 1; - - ParallelInstruction instruction = createFlattenInstruction( - producerIndex1, producerOutputNum1, producerIndex2, producerOutputNum2, "Flatten"); - - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - String systemStageName = "stageName"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - Operation operation = MapTaskExecutorFactory.createOperation( - options, - instruction, - readerFactoryRegistry, - BatchModeExecutionContext.fromOptions(options), - priorOperations, - counterPrefix, - systemStageName, - counterSet.getAddCounterMutator(), - stateSampler); - assertThat(operation, instanceOf(FlattenOperation.class)); - FlattenOperation flattenOperation = (FlattenOperation) operation; - - assertEquals(flattenOperation.receivers.length, 1); - assertEquals(flattenOperation.receivers[0].getReceiverCount(), 0); - assertEquals(flattenOperation.initializationState, Operation.InitializationState.UNSTARTED); - - assertSame( - flattenOperation, - priorOperations.get(producerIndex1).receivers[producerOutputNum1].getOnlyReceiver()); - assertSame( - flattenOperation, - priorOperations.get(producerIndex2).receivers[producerOutputNum2].getOnlyReceiver()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFnTest.java deleted file mode 100644 index e87d42a90b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFnTest.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.DataflowOutputCounter.getElementCounterName; -import static com.google.cloud.dataflow.sdk.runners.worker.DataflowOutputCounter.getObjectCounterName; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.hamcrest.core.AnyOf.anyOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; -import com.google.cloud.dataflow.sdk.util.PTuple; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Receiver; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests for NormalParDoFn. - */ -@RunWith(JUnit4.class) -public class NormalParDoFnTest { - static class TestDoFn extends DoFn { - enum State { UNSTARTED, STARTED, PROCESSING, FINISHED } - State state = State.UNSTARTED; - - List> sideOutputTupleTags; - - public TestDoFn(List sideOutputTags) { - sideOutputTupleTags = new ArrayList<>(); - for (String sideOutputTag : sideOutputTags) { - sideOutputTupleTags.add(new TupleTag(sideOutputTag)); - } - } - - @Override - public void startBundle(Context c) { - assertEquals(State.UNSTARTED, state); - state = State.STARTED; - outputToAll(c, "started"); - } - - @Override - public void processElement(ProcessContext c) { - assertThat(state, anyOf(equalTo(State.STARTED), - equalTo(State.PROCESSING))); - state = State.PROCESSING; - outputToAll(c, "processing: " + c.element()); - } - - @Override - public void finishBundle(Context c) { - assertThat(state, anyOf(equalTo(State.STARTED), - equalTo(State.PROCESSING))); - state = State.FINISHED; - outputToAll(c, "finished"); - } - - private void outputToAll(Context c, String value) { - c.output(value); - for (TupleTag sideOutputTupleTag : sideOutputTupleTags) { - c.sideOutput(sideOutputTupleTag, - sideOutputTupleTag.getId() + ": " + value); - } - } - } - - static class TestErrorDoFn extends DoFn { - - // Used to test nested stack traces. - private void nestedFunctionBeta(String s) { - throw new RuntimeException(s); - } - - private void nestedFunctionAlpha(String s) { - nestedFunctionBeta(s); - } - - @Override - public void startBundle(Context c) { - nestedFunctionAlpha("test error in initialize"); - } - - @Override - public void processElement(ProcessContext c) { - nestedFunctionBeta("test error in process"); - } - - @Override - public void finishBundle(Context c) { - throw new RuntimeException("test error in finalize"); - } - } - - static class TestReceiver implements Receiver { - List receivedElems = new ArrayList<>(); - - @Override - public void process(Object outputElem) { - receivedElems.add(outputElem); - } - } - - private PipelineOptions options; - - @Before - public void setupDefaultOptions() { - options = PipelineOptionsFactory.create(); - } - - @Test - public void testNormalParDoFn() throws Exception { - List sideOutputTags = Arrays.asList("tag1", "tag2", "tag3"); - - TestDoFn fn = new TestDoFn(sideOutputTags); - DoFnInfo fnInfo = new DoFnInfo<>(fn, WindowingStrategy.globalDefault()); - TestReceiver receiver = new TestReceiver(); - TestReceiver receiver1 = new TestReceiver(); - TestReceiver receiver2 = new TestReceiver(); - TestReceiver receiver3 = new TestReceiver(); - - PTuple sideInputValues = PTuple.empty(); - - List outputTags = new ArrayList<>(); - outputTags.add("output"); - outputTags.addAll(sideOutputTags); - NormalParDoFn normalParDoFn = NormalParDoFn.of( - options, - fnInfo, - DirectSideInputReader.of(sideInputValues), - outputTags, - "doFn", - "doFn", - BatchModeExecutionContext.fromOptions(options), - (new CounterSet()).getAddCounterMutator(), - null); - - normalParDoFn.startBundle(receiver, receiver1, receiver2, receiver3); - - normalParDoFn.processElement(WindowedValue.valueInGlobalWindow(3)); - normalParDoFn.processElement(WindowedValue.valueInGlobalWindow(42)); - normalParDoFn.processElement(WindowedValue.valueInGlobalWindow(666)); - - normalParDoFn.finishBundle(); - - Object[] expectedReceivedElems = { - WindowedValue.valueInGlobalWindow("started"), - WindowedValue.valueInGlobalWindow("processing: 3"), - WindowedValue.valueInGlobalWindow("processing: 42"), - WindowedValue.valueInGlobalWindow("processing: 666"), - WindowedValue.valueInGlobalWindow("finished"), - }; - assertArrayEquals(expectedReceivedElems, receiver.receivedElems.toArray()); - - Object[] expectedReceivedElems1 = { - WindowedValue.valueInGlobalWindow("tag1: started"), - WindowedValue.valueInGlobalWindow("tag1: processing: 3"), - WindowedValue.valueInGlobalWindow("tag1: processing: 42"), - WindowedValue.valueInGlobalWindow("tag1: processing: 666"), - WindowedValue.valueInGlobalWindow("tag1: finished"), - }; - assertArrayEquals(expectedReceivedElems1, receiver1.receivedElems.toArray()); - - Object[] expectedReceivedElems2 = { - WindowedValue.valueInGlobalWindow("tag2: started"), - WindowedValue.valueInGlobalWindow("tag2: processing: 3"), - WindowedValue.valueInGlobalWindow("tag2: processing: 42"), - WindowedValue.valueInGlobalWindow("tag2: processing: 666"), - WindowedValue.valueInGlobalWindow("tag2: finished"), - }; - assertArrayEquals(expectedReceivedElems2, receiver2.receivedElems.toArray()); - - Object[] expectedReceivedElems3 = { - WindowedValue.valueInGlobalWindow("tag3: started"), - WindowedValue.valueInGlobalWindow("tag3: processing: 3"), - WindowedValue.valueInGlobalWindow("tag3: processing: 42"), - WindowedValue.valueInGlobalWindow("tag3: processing: 666"), - WindowedValue.valueInGlobalWindow("tag3: finished"), - }; - assertArrayEquals(expectedReceivedElems3, receiver3.receivedElems.toArray()); - } - - @Test - public void testUnexpectedNumberOfReceivers() throws Exception { - TestDoFn fn = new TestDoFn(Collections.emptyList()); - DoFnInfo fnInfo = new DoFnInfo<>(fn, WindowingStrategy.globalDefault()); - TestReceiver receiver = new TestReceiver(); - - PTuple sideInputValues = PTuple.empty(); - List outputTags = Arrays.asList("output"); - NormalParDoFn normalParDoFn = NormalParDoFn.of( - options, - fnInfo, - DirectSideInputReader.of(sideInputValues), - outputTags, - "doFn", - "doFn", - BatchModeExecutionContext.fromOptions(options), - (new CounterSet()).getAddCounterMutator(), - null); - - try { - normalParDoFn.startBundle(); - fail("should have failed"); - } catch (Throwable exn) { - assertThat(exn.toString(), - containsString("unexpected number of receivers")); - } - try { - normalParDoFn.startBundle(receiver, receiver); - fail("should have failed"); - } catch (Throwable exn) { - assertThat(exn.toString(), - containsString("unexpected number of receivers")); - } - } - - private List stackTraceFrameStrings(Throwable t) { - List stack = new ArrayList<>(); - for (StackTraceElement frame : t.getStackTrace()) { - // Make sure that the frame has the expected name. - stack.add(frame.toString()); - } - return stack; - } - - @Test - public void testErrorPropagation() throws Exception { - TestErrorDoFn fn = new TestErrorDoFn(); - DoFnInfo fnInfo = new DoFnInfo<>(fn, WindowingStrategy.globalDefault()); - TestReceiver receiver = new TestReceiver(); - - PTuple sideInputValues = PTuple.empty(); - List outputTags = Arrays.asList("output"); - NormalParDoFn normalParDoFn = NormalParDoFn.of( - options, - fnInfo, - DirectSideInputReader.of(sideInputValues), - outputTags, - "doFn", - "doFn", - BatchModeExecutionContext.fromOptions(options), - (new CounterSet()).getAddCounterMutator(), - null); - - try { - normalParDoFn.startBundle(receiver); - normalParDoFn.processElement(null); - fail("should have failed"); - } catch (Exception exn) { - // Because we're calling this from inside the SDK and not from a - // user's program (e.g. through Pipeline.run), the error should - // be thrown as a UserCodeException. The cause of the - // UserCodeError shouldn't contain any of the stack from within - // the SDK, since we don't want to overwhelm users with stack - // frames outside of their control. - assertThat(exn, instanceOf(UserCodeException.class)); - // Stack trace of the cause should contain three frames: - // TestErrorDoFn.nestedFunctionBeta - // TestErrorDoFn.nestedFunctionAlpha - // TestErrorDoFn.startBundle - assertThat(stackTraceFrameStrings(exn.getCause()), contains( - containsString("TestErrorDoFn.nestedFunctionBeta"), - containsString("TestErrorDoFn.nestedFunctionAlpha"), - containsString("TestErrorDoFn.startBundle"))); - assertThat(exn.toString(), - containsString("test error in initialize")); - } - - try { - normalParDoFn.processElement(WindowedValue.valueInGlobalWindow(3)); - fail("should have failed"); - } catch (Exception exn) { - // Exception should be a UserCodeException since we're calling - // from inside the SDK. - assertThat(exn, instanceOf(UserCodeException.class)); - // Stack trace of the cause should contain two frames: - // TestErrorDoFn.nestedFunctionBeta - // TestErrorDoFn.processElement - assertThat(stackTraceFrameStrings(exn.getCause()), contains( - containsString("TestErrorDoFn.nestedFunctionBeta"), - containsString("TestErrorDoFn.processElement"))); - assertThat(exn.toString(), containsString("test error in process")); - } - - try { - normalParDoFn.finishBundle(); - fail("should have failed"); - } catch (Exception exn) { - // Exception should be a UserCodeException since we're calling - // from inside the SDK. - assertThat(exn, instanceOf(UserCodeException.class)); - // Stack trace should only contain a single frame: - // TestErrorDoFn.finishBundle - assertThat(stackTraceFrameStrings(exn.getCause()), contains( - containsString("TestErrorDoFn.finishBundle"))); - assertThat(exn.toString(), containsString("test error in finalize")); - } - } - - @Test - public void testUndeclaredSideOutputs() throws Exception { - TestDoFn fn = new TestDoFn(Arrays.asList("declared", "undecl1", "undecl2", "undecl3")); - DoFnInfo fnInfo = new DoFnInfo<>(fn, WindowingStrategy.globalDefault()); - CounterSet counters = new CounterSet(); - NormalParDoFn normalParDoFn = NormalParDoFn.of( - options, - fnInfo, - NullSideInputReader.empty(), - Arrays.asList("output", "declared"), - "doFn", - "doFn", - BatchModeExecutionContext.fromOptions(options), - counters.getAddCounterMutator(), - null); - - normalParDoFn.startBundle(new TestReceiver(), new TestReceiver()); - normalParDoFn.processElement(WindowedValue.valueInGlobalWindow(5)); - normalParDoFn.finishBundle(); - - assertEquals( - new CounterSet( - Counter.longs(getElementCounterName("implicit-undecl1"), SUM).resetToValue(3L), - Counter.longs(getObjectCounterName("implicit-undecl1"), SUM).resetToValue(3L), - Counter.longs(getElementCounterName("implicit-undecl2"), SUM).resetToValue(3L), - Counter.longs(getObjectCounterName("implicit-undecl2"), SUM).resetToValue(3L), - Counter.longs(getElementCounterName("implicit-undecl3"), SUM).resetToValue(3L), - Counter.longs(getObjectCounterName("implicit-undecl3"), SUM).resetToValue(3L)), - counters); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCodeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCodeTest.java deleted file mode 100644 index 5acef2e080..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCodeTest.java +++ /dev/null @@ -1,504 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.common.io.BaseEncoding; -import com.google.common.primitives.Bytes; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for OrderedCode. - */ -@RunWith(JUnit4.class) -public class OrderedCodeTest { - @Test - public void testWriteInfinity() { - OrderedCode orderedCode = new OrderedCode(); - try { - orderedCode.readInfinity(); - fail("Expected IllegalArgumentException."); - } catch (IllegalArgumentException e) { - // expected - } - orderedCode.writeInfinity(); - assertTrue(orderedCode.readInfinity()); - try { - orderedCode.readInfinity(); - fail("Expected IllegalArgumentException."); - } catch (IllegalArgumentException e) { - // expected - } - } - - @Test - public void testWriteBytes() { - byte[] first = { 'a', 'b', 'c'}; - byte[] second = { 'd', 'e', 'f'}; - byte[] last = { 'x', 'y', 'z'}; - OrderedCode orderedCode = new OrderedCode(); - orderedCode.writeBytes(first); - byte[] firstEncoded = orderedCode.getEncodedBytes(); - assertArrayEquals(orderedCode.readBytes(), first); - - orderedCode.writeBytes(first); - orderedCode.writeBytes(second); - orderedCode.writeBytes(last); - byte[] allEncoded = orderedCode.getEncodedBytes(); - assertArrayEquals(orderedCode.readBytes(), first); - assertArrayEquals(orderedCode.readBytes(), second); - assertArrayEquals(orderedCode.readBytes(), last); - - orderedCode = new OrderedCode(firstEncoded); - orderedCode.writeBytes(second); - orderedCode.writeBytes(last); - assertArrayEquals(orderedCode.getEncodedBytes(), allEncoded); - assertArrayEquals(orderedCode.readBytes(), first); - assertArrayEquals(orderedCode.readBytes(), second); - assertArrayEquals(orderedCode.readBytes(), last); - - orderedCode = new OrderedCode(allEncoded); - assertArrayEquals(orderedCode.readBytes(), first); - assertArrayEquals(orderedCode.readBytes(), second); - assertArrayEquals(orderedCode.readBytes(), last); - } - - @Test - public void testWriteNumIncreasing() { - OrderedCode orderedCode = new OrderedCode(); - orderedCode.writeNumIncreasing(0); - orderedCode.writeNumIncreasing(1); - orderedCode.writeNumIncreasing(Long.MIN_VALUE); - orderedCode.writeNumIncreasing(Long.MAX_VALUE); - assertEquals(orderedCode.readNumIncreasing(), 0); - assertEquals(orderedCode.readNumIncreasing(), 1); - assertEquals(orderedCode.readNumIncreasing(), Long.MIN_VALUE); - assertEquals(orderedCode.readNumIncreasing(), Long.MAX_VALUE); - } - - /** - * Assert that encoding the specified long via - * {@link OrderedCode#writeSignedNumIncreasing(long)} results in the bytes - * represented by the specified string of hex digits. - * E.g. assertSignedNumIncreasingEncodingEquals("3fbf", -65) asserts that - * -65 is encoded as { (byte) 0x3f, (byte) 0xbf }. - */ - private static void assertSignedNumIncreasingEncodingEquals( - String expectedHexEncoding, long num) { - OrderedCode orderedCode = new OrderedCode(); - orderedCode.writeSignedNumIncreasing(num); - assertEquals( - "Unexpected encoding for " + num, - expectedHexEncoding, - BaseEncoding.base16().lowerCase().encode(orderedCode.getEncodedBytes())); - } - - /** - * Assert that encoding various long values via - * {@link OrderedCode#writeSignedNumIncreasing(long)} produces the expected - * bytes. Expected byte sequences were generated via the c++ (authoritative) - * implementation of OrderedCode::WriteSignedNumIncreasing. - */ - @Test - public void testSignedNumIncreasing_write() { - assertSignedNumIncreasingEncodingEquals( - "003f8000000000000000", Long.MIN_VALUE); - assertSignedNumIncreasingEncodingEquals( - "003f8000000000000001", Long.MIN_VALUE + 1); - assertSignedNumIncreasingEncodingEquals( - "077fffffff", Integer.MIN_VALUE - 1L); - assertSignedNumIncreasingEncodingEquals("0780000000", Integer.MIN_VALUE); - assertSignedNumIncreasingEncodingEquals( - "0780000001", Integer.MIN_VALUE + 1); - assertSignedNumIncreasingEncodingEquals("3fbf", -65); - assertSignedNumIncreasingEncodingEquals("40", -64); - assertSignedNumIncreasingEncodingEquals("41", -63); - assertSignedNumIncreasingEncodingEquals("7d", -3); - assertSignedNumIncreasingEncodingEquals("7e", -2); - assertSignedNumIncreasingEncodingEquals("7f", -1); - assertSignedNumIncreasingEncodingEquals("80", 0); - assertSignedNumIncreasingEncodingEquals("81", 1); - assertSignedNumIncreasingEncodingEquals("82", 2); - assertSignedNumIncreasingEncodingEquals("83", 3); - assertSignedNumIncreasingEncodingEquals("bf", 63); - assertSignedNumIncreasingEncodingEquals("c040", 64); - assertSignedNumIncreasingEncodingEquals("c041", 65); - assertSignedNumIncreasingEncodingEquals( - "f87ffffffe", Integer.MAX_VALUE - 1); - assertSignedNumIncreasingEncodingEquals("f87fffffff", Integer.MAX_VALUE); - assertSignedNumIncreasingEncodingEquals( - "f880000000", Integer.MAX_VALUE + 1L); - assertSignedNumIncreasingEncodingEquals( - "ffc07ffffffffffffffe", Long.MAX_VALUE - 1); - assertSignedNumIncreasingEncodingEquals( - "ffc07fffffffffffffff", Long.MAX_VALUE); - } - - /** - * Convert a string of hex digits (e.g. "3fbf") to a byte[] - * (e.g. { (byte) 0x3f, (byte) 0xbf }). - */ - private static byte[] bytesFromHexString(String hexDigits) { - return BaseEncoding.base16().lowerCase().decode(hexDigits); - } - - /** - * Assert that decoding (via {@link OrderedCode#readSignedNumIncreasing()}) - * the bytes represented by the specified string of hex digits results in the - * expected long value. - * E.g. assertDecodedSignedNumIncreasingEquals(-65, "3fbf") asserts that the - * byte array { (byte) 0x3f, (byte) 0xbf } is decoded as -65. - */ - private static void assertDecodedSignedNumIncreasingEquals( - long expectedNum, String encodedHexString) { - OrderedCode orderedCode = - new OrderedCode(bytesFromHexString(encodedHexString)); - assertEquals( - "Unexpected value when decoding 0x" + encodedHexString, - expectedNum, - orderedCode.readSignedNumIncreasing()); - assertFalse( - "Unexpected encoded bytes remain after decoding 0x" + encodedHexString, - orderedCode.hasRemainingEncodedBytes()); - } - - /** - * Assert that decoding various sequences of bytes via - * {@link OrderedCode#readSignedNumIncreasing()} produces the expected long - * value. - * Input byte sequences were generated via the c++ (authoritative) - * implementation of OrderedCode::WriteSignedNumIncreasing. - */ - @Test - public void testSignedNumIncreasing_read() { - assertDecodedSignedNumIncreasingEquals( - Long.MIN_VALUE, "003f8000000000000000"); - assertDecodedSignedNumIncreasingEquals( - Long.MIN_VALUE + 1, "003f8000000000000001"); - assertDecodedSignedNumIncreasingEquals( - Integer.MIN_VALUE - 1L, "077fffffff"); - assertDecodedSignedNumIncreasingEquals(Integer.MIN_VALUE, "0780000000"); - assertDecodedSignedNumIncreasingEquals(Integer.MIN_VALUE + 1, "0780000001"); - assertDecodedSignedNumIncreasingEquals(-65, "3fbf"); - assertDecodedSignedNumIncreasingEquals(-64, "40"); - assertDecodedSignedNumIncreasingEquals(-63, "41"); - assertDecodedSignedNumIncreasingEquals(-3, "7d"); - assertDecodedSignedNumIncreasingEquals(-2, "7e"); - assertDecodedSignedNumIncreasingEquals(-1, "7f"); - assertDecodedSignedNumIncreasingEquals(0, "80"); - assertDecodedSignedNumIncreasingEquals(1, "81"); - assertDecodedSignedNumIncreasingEquals(2, "82"); - assertDecodedSignedNumIncreasingEquals(3, "83"); - assertDecodedSignedNumIncreasingEquals(63, "bf"); - assertDecodedSignedNumIncreasingEquals(64, "c040"); - assertDecodedSignedNumIncreasingEquals(65, "c041"); - assertDecodedSignedNumIncreasingEquals(Integer.MAX_VALUE - 1, "f87ffffffe"); - assertDecodedSignedNumIncreasingEquals(Integer.MAX_VALUE, "f87fffffff"); - assertDecodedSignedNumIncreasingEquals( - Integer.MAX_VALUE + 1L, "f880000000"); - assertDecodedSignedNumIncreasingEquals( - Long.MAX_VALUE - 1, "ffc07ffffffffffffffe"); - assertDecodedSignedNumIncreasingEquals( - Long.MAX_VALUE, "ffc07fffffffffffffff"); - } - - /** - * Assert that encoding (via - * {@link OrderedCode#writeSignedNumIncreasing(long)}) the specified long - * value and then decoding (via {@link OrderedCode#readSignedNumIncreasing()}) - * results in the original value. - */ - private static void assertSignedNumIncreasingWriteAndReadIsLossless( - long num) { - OrderedCode orderedCode = new OrderedCode(); - orderedCode.writeSignedNumIncreasing(num); - assertEquals( - "Unexpected result when decoding writeSignedNumIncreasing(" + num + ")", - num, - orderedCode.readSignedNumIncreasing()); - assertFalse("Unexpected remaining encoded bytes after decoding " + num, - orderedCode.hasRemainingEncodedBytes()); - } - - /** - * Assert that for various long values, encoding (via - * {@link OrderedCode#writeSignedNumIncreasing(long)}) and then decoding (via - * {@link OrderedCode#readSignedNumIncreasing()}) results in the original - * value. - */ - @Test - public void testSignedNumIncreasing_writeAndRead() { - assertSignedNumIncreasingWriteAndReadIsLossless(Long.MIN_VALUE); - assertSignedNumIncreasingWriteAndReadIsLossless(Long.MIN_VALUE + 1); - assertSignedNumIncreasingWriteAndReadIsLossless(Integer.MIN_VALUE - 1L); - assertSignedNumIncreasingWriteAndReadIsLossless(Integer.MIN_VALUE); - assertSignedNumIncreasingWriteAndReadIsLossless(Integer.MIN_VALUE + 1); - assertSignedNumIncreasingWriteAndReadIsLossless(-65); - assertSignedNumIncreasingWriteAndReadIsLossless(-64); - assertSignedNumIncreasingWriteAndReadIsLossless(-63); - assertSignedNumIncreasingWriteAndReadIsLossless(-3); - assertSignedNumIncreasingWriteAndReadIsLossless(-2); - assertSignedNumIncreasingWriteAndReadIsLossless(-1); - assertSignedNumIncreasingWriteAndReadIsLossless(0); - assertSignedNumIncreasingWriteAndReadIsLossless(1); - assertSignedNumIncreasingWriteAndReadIsLossless(2); - assertSignedNumIncreasingWriteAndReadIsLossless(3); - assertSignedNumIncreasingWriteAndReadIsLossless(63); - assertSignedNumIncreasingWriteAndReadIsLossless(64); - assertSignedNumIncreasingWriteAndReadIsLossless(65); - assertSignedNumIncreasingWriteAndReadIsLossless(Integer.MAX_VALUE - 1); - assertSignedNumIncreasingWriteAndReadIsLossless(Integer.MAX_VALUE); - assertSignedNumIncreasingWriteAndReadIsLossless(Integer.MAX_VALUE + 1L); - assertSignedNumIncreasingWriteAndReadIsLossless(Long.MAX_VALUE - 1); - assertSignedNumIncreasingWriteAndReadIsLossless(Long.MAX_VALUE); - } - - @Test - public void testLog2Floor_Positive() { - OrderedCode orderedCode = new OrderedCode(); - assertEquals(0, orderedCode.log2Floor(1)); - assertEquals(1, orderedCode.log2Floor(2)); - assertEquals(1, orderedCode.log2Floor(3)); - assertEquals(2, orderedCode.log2Floor(4)); - assertEquals(5, orderedCode.log2Floor(63)); - assertEquals(6, orderedCode.log2Floor(64)); - assertEquals(62, orderedCode.log2Floor(Long.MAX_VALUE)); - } - - /** - * OrderedCode.log2Floor(long) is defined to return -1 given an input of zero. - */ - @Test - public void testLog2Floor_zero() { - OrderedCode orderedCode = new OrderedCode(); - assertEquals(-1, orderedCode.log2Floor(0)); - } - - @Test - public void testLog2Floor_negative() { - OrderedCode orderedCode = new OrderedCode(); - try { - orderedCode.log2Floor(-1); - fail("Expected an IllegalArgumentException."); - } catch (IllegalArgumentException expected) { - // Expected! - } - } - - @Test - public void testGetSignedEncodingLength() { - OrderedCode orderedCode = new OrderedCode(); - assertEquals(10, orderedCode.getSignedEncodingLength(Long.MIN_VALUE)); - assertEquals(10, orderedCode.getSignedEncodingLength(~(1L << 62))); - assertEquals(9, orderedCode.getSignedEncodingLength(~(1L << 62) + 1)); - assertEquals(3, orderedCode.getSignedEncodingLength(-8193)); - assertEquals(2, orderedCode.getSignedEncodingLength(-8192)); - assertEquals(2, orderedCode.getSignedEncodingLength(-65)); - assertEquals(1, orderedCode.getSignedEncodingLength(-64)); - assertEquals(1, orderedCode.getSignedEncodingLength(-2)); - assertEquals(1, orderedCode.getSignedEncodingLength(-1)); - assertEquals(1, orderedCode.getSignedEncodingLength(0)); - assertEquals(1, orderedCode.getSignedEncodingLength(1)); - assertEquals(1, orderedCode.getSignedEncodingLength(63)); - assertEquals(2, orderedCode.getSignedEncodingLength(64)); - assertEquals(2, orderedCode.getSignedEncodingLength(8191)); - assertEquals(3, orderedCode.getSignedEncodingLength(8192)); - assertEquals(9, orderedCode.getSignedEncodingLength((1L << 62)) - 1); - assertEquals(10, orderedCode.getSignedEncodingLength(1L << 62)); - assertEquals(10, orderedCode.getSignedEncodingLength(Long.MAX_VALUE)); - } - - @Test - public void testWriteTrailingBytes() { - byte[] escapeChars = new byte[] { OrderedCode.ESCAPE1, - OrderedCode.NULL_CHARACTER, OrderedCode.SEPARATOR, OrderedCode.ESCAPE2, - OrderedCode.INFINITY, OrderedCode.FF_CHARACTER}; - byte[] anotherArray = new byte[] { 'a', 'b', 'c', 'd', 'e' }; - - OrderedCode orderedCode = new OrderedCode(); - orderedCode.writeTrailingBytes(escapeChars); - assertArrayEquals(orderedCode.getEncodedBytes(), escapeChars); - assertArrayEquals(orderedCode.readTrailingBytes(), escapeChars); - try { - orderedCode.readInfinity(); - fail("Expected IllegalArgumentException."); - } catch (IllegalArgumentException e) { - // expected - } - - orderedCode = new OrderedCode(); - orderedCode.writeTrailingBytes(anotherArray); - assertArrayEquals(orderedCode.getEncodedBytes(), anotherArray); - assertArrayEquals(orderedCode.readTrailingBytes(), anotherArray); - } - - @Test - public void testMixedWrite() { - byte[] first = { 'a', 'b', 'c'}; - byte[] second = { 'd', 'e', 'f'}; - byte[] last = { 'x', 'y', 'z'}; - byte[] escapeChars = new byte[] { OrderedCode.ESCAPE1, - OrderedCode.NULL_CHARACTER, OrderedCode.SEPARATOR, OrderedCode.ESCAPE2, - OrderedCode.INFINITY, OrderedCode.FF_CHARACTER}; - - OrderedCode orderedCode = new OrderedCode(); - orderedCode.writeBytes(first); - orderedCode.writeBytes(second); - orderedCode.writeBytes(last); - orderedCode.writeInfinity(); - orderedCode.writeNumIncreasing(0); - orderedCode.writeNumIncreasing(1); - orderedCode.writeNumIncreasing(Long.MIN_VALUE); - orderedCode.writeNumIncreasing(Long.MAX_VALUE); - orderedCode.writeSignedNumIncreasing(0); - orderedCode.writeSignedNumIncreasing(1); - orderedCode.writeSignedNumIncreasing(Long.MIN_VALUE); - orderedCode.writeSignedNumIncreasing(Long.MAX_VALUE); - orderedCode.writeTrailingBytes(escapeChars); - byte[] allEncoded = orderedCode.getEncodedBytes(); - assertArrayEquals(orderedCode.readBytes(), first); - assertArrayEquals(orderedCode.readBytes(), second); - assertFalse(orderedCode.readInfinity()); - assertArrayEquals(orderedCode.readBytes(), last); - assertTrue(orderedCode.readInfinity()); - assertEquals(orderedCode.readNumIncreasing(), 0); - assertEquals(orderedCode.readNumIncreasing(), 1); - assertFalse(orderedCode.readInfinity()); - assertEquals(orderedCode.readNumIncreasing(), Long.MIN_VALUE); - assertEquals(orderedCode.readNumIncreasing(), Long.MAX_VALUE); - assertEquals(orderedCode.readSignedNumIncreasing(), 0); - assertEquals(orderedCode.readSignedNumIncreasing(), 1); - assertFalse(orderedCode.readInfinity()); - assertEquals(orderedCode.readSignedNumIncreasing(), Long.MIN_VALUE); - assertEquals(orderedCode.readSignedNumIncreasing(), Long.MAX_VALUE); - assertArrayEquals(orderedCode.getEncodedBytes(), escapeChars); - assertArrayEquals(orderedCode.readTrailingBytes(), escapeChars); - - orderedCode = new OrderedCode(allEncoded); - assertArrayEquals(orderedCode.readBytes(), first); - assertArrayEquals(orderedCode.readBytes(), second); - assertFalse(orderedCode.readInfinity()); - assertArrayEquals(orderedCode.readBytes(), last); - assertTrue(orderedCode.readInfinity()); - assertEquals(orderedCode.readNumIncreasing(), 0); - assertEquals(orderedCode.readNumIncreasing(), 1); - assertFalse(orderedCode.readInfinity()); - assertEquals(orderedCode.readNumIncreasing(), Long.MIN_VALUE); - assertEquals(orderedCode.readNumIncreasing(), Long.MAX_VALUE); - assertEquals(orderedCode.readSignedNumIncreasing(), 0); - assertEquals(orderedCode.readSignedNumIncreasing(), 1); - assertFalse(orderedCode.readInfinity()); - assertEquals(orderedCode.readSignedNumIncreasing(), Long.MIN_VALUE); - assertEquals(orderedCode.readSignedNumIncreasing(), Long.MAX_VALUE); - assertArrayEquals(orderedCode.getEncodedBytes(), escapeChars); - assertArrayEquals(orderedCode.readTrailingBytes(), escapeChars); - } - - @Test - public void testEdgeCases() { - byte[] ffChar = {OrderedCode.FF_CHARACTER}; - byte[] nullChar = {OrderedCode.NULL_CHARACTER}; - - byte[] separatorEncoded = {OrderedCode.ESCAPE1, OrderedCode.SEPARATOR}; - byte[] ffCharEncoded = {OrderedCode.ESCAPE1, OrderedCode.NULL_CHARACTER}; - byte[] nullCharEncoded = {OrderedCode.ESCAPE2, OrderedCode.FF_CHARACTER}; - byte[] infinityEncoded = {OrderedCode.ESCAPE2, OrderedCode.INFINITY}; - - OrderedCode orderedCode = new OrderedCode(); - orderedCode.writeBytes(ffChar); - orderedCode.writeBytes(nullChar); - orderedCode.writeInfinity(); - assertArrayEquals(orderedCode.getEncodedBytes(), - Bytes.concat(ffCharEncoded, separatorEncoded, - nullCharEncoded, separatorEncoded, - infinityEncoded)); - assertArrayEquals(orderedCode.readBytes(), ffChar); - assertArrayEquals(orderedCode.readBytes(), nullChar); - assertTrue(orderedCode.readInfinity()); - - orderedCode = new OrderedCode( - Bytes.concat(ffCharEncoded, separatorEncoded)); - assertArrayEquals(orderedCode.readBytes(), ffChar); - - orderedCode = new OrderedCode( - Bytes.concat(nullCharEncoded, separatorEncoded)); - assertArrayEquals(orderedCode.readBytes(), nullChar); - - byte[] invalidEncodingForRead = {OrderedCode.ESCAPE2, OrderedCode.ESCAPE2, - OrderedCode.ESCAPE1, OrderedCode.SEPARATOR}; - orderedCode = new OrderedCode(invalidEncodingForRead); - try { - orderedCode.readBytes(); - fail("Should have failed."); - } catch (Exception e) { - // Expected - } - assertTrue(orderedCode.hasRemainingEncodedBytes()); - } - - @Test - public void testHasRemainingEncodedBytes() { - byte[] bytes = { 'a', 'b', 'c'}; - long number = 12345; - - // Empty - OrderedCode orderedCode = new OrderedCode(); - assertFalse(orderedCode.hasRemainingEncodedBytes()); - - // First and only field of each type. - orderedCode.writeBytes(bytes); - assertTrue(orderedCode.hasRemainingEncodedBytes()); - assertArrayEquals(orderedCode.readBytes(), bytes); - assertFalse(orderedCode.hasRemainingEncodedBytes()); - - orderedCode.writeNumIncreasing(number); - assertTrue(orderedCode.hasRemainingEncodedBytes()); - assertEquals(orderedCode.readNumIncreasing(), number); - assertFalse(orderedCode.hasRemainingEncodedBytes()); - - orderedCode.writeSignedNumIncreasing(number); - assertTrue(orderedCode.hasRemainingEncodedBytes()); - assertEquals(orderedCode.readSignedNumIncreasing(), number); - assertFalse(orderedCode.hasRemainingEncodedBytes()); - - orderedCode.writeInfinity(); - assertTrue(orderedCode.hasRemainingEncodedBytes()); - assertTrue(orderedCode.readInfinity()); - assertFalse(orderedCode.hasRemainingEncodedBytes()); - - orderedCode.writeTrailingBytes(bytes); - assertTrue(orderedCode.hasRemainingEncodedBytes()); - assertArrayEquals(orderedCode.readTrailingBytes(), bytes); - assertFalse(orderedCode.hasRemainingEncodedBytes()); - - // Two fields of same type. - orderedCode.writeBytes(bytes); - orderedCode.writeBytes(bytes); - assertTrue(orderedCode.hasRemainingEncodedBytes()); - assertArrayEquals(orderedCode.readBytes(), bytes); - assertArrayEquals(orderedCode.readBytes(), bytes); - assertFalse(orderedCode.hasRemainingEncodedBytes()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java deleted file mode 100644 index cd3d8e52b6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.NO_FIRING; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Tests for PartitioningShuffleReader. - */ -@RunWith(JUnit4.class) -public class PartitioningShuffleReaderTest { - private static final List>> NO_KVS = Collections.emptyList(); - - private static final Instant timestamp = new Instant(123000); - private static final IntervalWindow window = new IntervalWindow(timestamp, timestamp.plus(1000)); - - private static final List>> KVS = Arrays.asList( - WindowedValue.of(KV.of(1, "in 1a"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(1, "in 1b"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(2, "in 2a"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(2, "in 2b"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(3, "in 3"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(4, "in 4a"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(4, "in 4b"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(4, "in 4c"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(4, "in 4d"), timestamp, Lists.newArrayList(window), NO_FIRING), - WindowedValue.of(KV.of(5, "in 5"), timestamp, Lists.newArrayList(window), NO_FIRING)); - - private void runTestReadFromShuffle(List>> expected) - throws Exception { - Coder>> elemCoder = WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of()), IntervalWindow.getCoder()); - - // Write to shuffle with PARTITION_KEYS ShuffleSink. - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - ShuffleSink> shuffleSink = new ShuffleSink<>( - PipelineOptionsFactory.create(), null, ShuffleSink.ShuffleKind.PARTITION_KEYS, - elemCoder, addCounterMutator); - - TestShuffleWriter shuffleWriter = new TestShuffleWriter(); - - List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter>> shuffleSinkWriter = - shuffleSink.writer(shuffleWriter, "dataset")) { - for (WindowedValue> value : expected) { - actualSizes.add(shuffleSinkWriter.add(value)); - } - } - List records = shuffleWriter.getRecords(); - Assert.assertEquals(expected.size(), records.size()); - Assert.assertEquals(shuffleWriter.getSizes(), actualSizes); - - // Read from shuffle with PartitioningShuffleReader. - PartitioningShuffleReader partitioningShuffleReader = - new PartitioningShuffleReader<>( - PipelineOptionsFactory.create(), null, null, null, elemCoder, - addCounterMutator); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(partitioningShuffleReader); - - TestShuffleReader shuffleReader = new TestShuffleReader(); - List expectedSizes = new ArrayList<>(); - for (ShuffleEntry record : records) { - expectedSizes.add(record.length()); - shuffleReader.addEntry(record); - } - - List>> actual = new ArrayList<>(); - try (PartitioningShuffleReader.PartitioningShuffleReaderIterator iter = - partitioningShuffleReader.iterator(shuffleReader)) { - while (iter.hasNext()) { - Assert.assertTrue(iter.hasNext()); - actual.add(iter.next()); - } - Assert.assertFalse(iter.hasNext()); - try { - iter.next(); - Assert.fail("should have failed"); - } catch (NoSuchElementException exn) { - // As expected. - } - } - - Assert.assertEquals(expected, actual); - Assert.assertEquals(expectedSizes, observer.getActualSizes()); - } - - @Test - public void testReadEmptyShuffleData() throws Exception { - runTestReadFromShuffle(NO_KVS); - } - - @Test - public void testReadNonEmptyShuffleData() throws Exception { - runTestReadFromShuffle(KVS); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java deleted file mode 100644 index f5cc6159b4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactoryTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.hamcrest.CoreMatchers; -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * Tests for ReaderFactory. - */ -@RunWith(JUnit4.class) -public class ReaderFactoryTest { - - static class TestReaderFactory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) { - return new TestReader(); - } - } - - static class TestReader extends NativeReader { - @Override - public NativeReaderIterator iterator() { - return new TestReaderIterator(); - } - - /** A source iterator that produces no values, for testing. */ - class TestReaderIterator extends NativeReaderIterator { - @Override - public boolean start() { - return false; - } - - @Override - public boolean advance() { - return false; - } - - @Override - public Integer getCurrent() { - throw new NoSuchElementException(); - } - } - } - - static class SingletonTestReaderFactory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) { - return new SingletonTestReader(); - } - } - - static class SingletonTestReader extends NativeReader> { - @Override - public SingletonTestReaderIterator iterator() { - return new SingletonTestReaderIterator(); - } - - /** A source iterator that produces no values, for testing. */ - class SingletonTestReaderIterator extends NativeReaderIterator> { - @Override - public boolean start() { - return true; - } - - @Override - public boolean advance() throws IOException { - return false; - } - - @Override - public WindowedValue getCurrent() { - return WindowedValue.valueInGlobalWindow("something"); - } - } - } - - @Test - public void testCreatePredefinedReader() throws Exception { - CloudObject spec = CloudObject.forClassName("TextSource"); - addString(spec, "filename", "/path/to/file.txt"); - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(makeCloudEncoding("StringUtf8Coder")); - - PipelineOptions options = PipelineOptionsFactory.create(); - NativeReader reader = - ReaderRegistry.defaultRegistry() - .create( - cloudSource, options, BatchModeExecutionContext.fromOptions(options), null, null); - Assert.assertThat(reader, new IsInstanceOf(TextReader.class)); - } - - @Test - public void testCreateUserDefinedReader() throws Exception { - CloudObject spec = CloudObject.forClass(TestReaderFactory.class); - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(makeCloudEncoding("BigEndianIntegerCoder")); - - PipelineOptions options = PipelineOptionsFactory.create(); - ReaderRegistry registry = ReaderRegistry.defaultRegistry() - .register(TestReaderFactory.class.getName(), new TestReaderFactory()); - NativeReader reader = - registry.create( - cloudSource, - PipelineOptionsFactory.create(), - BatchModeExecutionContext.fromOptions(options), - null, - null); - Assert.assertThat(reader, new IsInstanceOf(TestReader.class)); - } - - @Test - public void testCreateUnknownReader() throws Exception { - CloudObject spec = CloudObject.forClassName("UnknownSource"); - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(makeCloudEncoding("StringUtf8Coder")); - try { - PipelineOptions options = PipelineOptionsFactory.create(); - ReaderRegistry.defaultRegistry().create( - cloudSource, - options, - BatchModeExecutionContext.fromOptions(options), - null, - null); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), CoreMatchers.containsString("Unable to create a Reader")); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java deleted file mode 100644 index 11a1faddff..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderTestUtils.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.toCloudPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.toDynamicSplitRequest; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.ConcatPosition; -import com.google.api.services.dataflow.model.Position; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.NativeReaderIterator; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Helpers for testing {@link NativeReader} and related classes, especially - * {@link NativeReaderIterator#getProgress} and {@link NativeReaderIterator#requestDynamicSplit}. - */ -public class ReaderTestUtils { - public static Position positionAtIndex(@Nullable Long index) { - return new Position().setRecordIndex(index); - } - - public static Position positionAtByteOffset(@Nullable Long byteOffset) { - return new Position().setByteOffset(byteOffset); - } - - public static Position positionAtConcatPosition( - @Nullable Integer index, @Nullable Position innerPosition) { - return new Position().setConcatPosition( - new ConcatPosition().setIndex(index).setPosition(innerPosition)); - } - - public static ApproximateReportedProgress approximateProgressAtPosition( - @Nullable Position position) { - return new ApproximateReportedProgress().setPosition(position); - } - - public static ApproximateSplitRequest approximateSplitRequestAtPosition( - @Nullable Position position) { - return new ApproximateSplitRequest().setPosition(position); - } - - public static ApproximateReportedProgress approximateProgressAtIndex( - @Nullable Long index) { - return approximateProgressAtPosition(positionAtIndex(index)); - } - - public static ApproximateSplitRequest approximateSplitRequestAtIndex( - @Nullable Long index) { - return approximateSplitRequestAtPosition(positionAtIndex(index)); - } - - public static ApproximateReportedProgress approximateProgressAtByteOffset( - @Nullable Long byteOffset) { - return approximateProgressAtPosition(positionAtByteOffset(byteOffset)); - } - - public static ApproximateSplitRequest approximateSplitRequestAtByteOffset( - @Nullable Long byteOffset) { - return approximateSplitRequestAtPosition(positionAtByteOffset(byteOffset)); - } - - public static ApproximateReportedProgress approximateProgressAtConcatPosition( - @Nullable Integer index, @Nullable Position innerPosition) { - return approximateProgressAtPosition(positionAtConcatPosition(index, innerPosition)); - } - - public static ApproximateSplitRequest approximateSplitRequestAtConcatPosition( - @Nullable Integer index, @Nullable Position innerPosition) { - return approximateSplitRequestAtPosition(positionAtConcatPosition(index, innerPosition)); - } - - public static ApproximateReportedProgress approximateProgressAtFraction( - @Nullable Double fraction) { - return new ApproximateReportedProgress().setFractionConsumed(fraction); - } - - public static ApproximateSplitRequest approximateSplitRequestAtFraction( - @Nullable Double fraction) { - return new ApproximateSplitRequest().setFractionConsumed(fraction); - } - - public static NativeReader.DynamicSplitRequest splitRequestAtPosition( - @Nullable Position position) { - return toDynamicSplitRequest(approximateSplitRequestAtPosition(position)); - } - - public static NativeReader.DynamicSplitRequest splitRequestAtIndex(@Nullable Long index) { - return toDynamicSplitRequest(approximateSplitRequestAtIndex(index)); - } - - public static NativeReader.DynamicSplitRequest splitRequestAtByteOffset( - @Nullable Long byteOffset) { - return toDynamicSplitRequest(approximateSplitRequestAtByteOffset(byteOffset)); - } - - public static NativeReader.DynamicSplitRequest splitRequestAtConcatPosition( - @Nullable Integer index, @Nullable Position innerPosition) { - return toDynamicSplitRequest(approximateSplitRequestAtConcatPosition(index, innerPosition)); - } - - public static Position positionFromSplitResult( - NativeReader.DynamicSplitResult dynamicSplitResult) { - return toCloudPosition( - ((NativeReader.DynamicSplitResultWithPosition) dynamicSplitResult).getAcceptedPosition()); - } - - public static Position positionFromProgress(NativeReader.Progress progress) { - return readerProgressToCloudProgress(progress).getPosition(); - } - - public static NativeReader.DynamicSplitRequest splitRequestAtFraction(double fraction) { - return toDynamicSplitRequest(approximateSplitRequestAtFraction(fraction)); - } - - /** - * Appends all values from a collection of {@code WindowedValue} values to a collection of values. - */ - public static List windowedValuesToValues(Collection> windowedValues) { - List res = new ArrayList<>(); - for (WindowedValue windowedValue : windowedValues) { - res.add(windowedValue.getValue()); - } - return res; - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java deleted file mode 100644 index 3868931e6e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReaderFactoryTest.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.encodeBase64String; -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import javax.annotation.Nullable; - -/** - * Tests for UngroupedShuffleReaderFactory, GroupingShuffleReaderFactory, - * and PartitioningShuffleReaderFactory. - */ -@RunWith(JUnit4.class) -@SuppressWarnings({"rawtypes", "unchecked"}) -public class ShuffleReaderFactoryTest { - T runTestCreateShuffleReader( - byte[] shuffleReaderConfig, - @Nullable String start, - @Nullable String end, - CloudObject encoding, - BatchModeExecutionContext context, - Class shuffleReaderClass, - String shuffleSourceAlias) - throws Exception { - CloudObject spec = CloudObject.forClassName(shuffleSourceAlias); - addString(spec, "shuffle_reader_config", encodeBase64String(shuffleReaderConfig)); - if (start != null) { - addString(spec, "start_shuffle_position", start); - } - if (end != null) { - addString(spec, "end_shuffle_position", end); - } - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(encoding); - - NativeReader reader = - ReaderRegistry.defaultRegistry() - .create(cloudSource, PipelineOptionsFactory.create(), context, null, null); - Assert.assertThat(reader, new IsInstanceOf(shuffleReaderClass)); - T shuffleSource = (T) reader; - return shuffleSource; - } - - void runTestCreateUngroupedShuffleReader(byte[] shuffleReaderConfig, @Nullable String start, - @Nullable String end, CloudObject encoding, Coder coder) throws Exception { - UngroupedShuffleReader ungroupedShuffleReader = runTestCreateShuffleReader( - shuffleReaderConfig, - start, - end, - encoding, - BatchModeExecutionContext.fromOptions(PipelineOptionsFactory.create()), - UngroupedShuffleReader.class, - "UngroupedShuffleSource"); - Assert.assertArrayEquals(shuffleReaderConfig, ungroupedShuffleReader.shuffleReaderConfig); - Assert.assertEquals(start, ungroupedShuffleReader.startShufflePosition); - Assert.assertEquals(end, ungroupedShuffleReader.stopShufflePosition); - - Assert.assertEquals(coder, ungroupedShuffleReader.coder); - } - - void runTestCreateGroupingShuffleReader(byte[] shuffleReaderConfig, @Nullable String start, - @Nullable String end, CloudObject encoding, Coder keyCoder, Coder valueCoder) - throws Exception { - BatchModeExecutionContext context = - BatchModeExecutionContext.fromOptions(PipelineOptionsFactory.create()); - GroupingShuffleReader groupingShuffleReader = runTestCreateShuffleReader( - shuffleReaderConfig, start, end, encoding, context, GroupingShuffleReader.class, - "GroupingShuffleSource"); - Assert.assertArrayEquals(shuffleReaderConfig, groupingShuffleReader.shuffleReaderConfig); - Assert.assertEquals(start, groupingShuffleReader.startShufflePosition); - Assert.assertEquals(end, groupingShuffleReader.stopShufflePosition); - - Assert.assertEquals(keyCoder, groupingShuffleReader.keyCoder); - Assert.assertEquals(valueCoder, groupingShuffleReader.valueCoder); - Assert.assertEquals(context, groupingShuffleReader.executionContext); - } - - void runTestCreatePartitioningShuffleReader(byte[] shuffleReaderConfig, @Nullable String start, - @Nullable String end, CloudObject encoding, Coder keyCoder, Coder windowedValueCoder) - throws Exception { - PartitioningShuffleReader partitioningShuffleReader = runTestCreateShuffleReader( - shuffleReaderConfig, - start, - end, - encoding, - BatchModeExecutionContext.fromOptions(PipelineOptionsFactory.create()), - PartitioningShuffleReader.class, - "PartitioningShuffleSource"); - Assert.assertArrayEquals(shuffleReaderConfig, partitioningShuffleReader.shuffleReaderConfig); - Assert.assertEquals(start, partitioningShuffleReader.startShufflePosition); - Assert.assertEquals(end, partitioningShuffleReader.stopShufflePosition); - - Assert.assertEquals(keyCoder, partitioningShuffleReader.keyCoder); - Assert.assertEquals(windowedValueCoder, partitioningShuffleReader.windowedValueCoder); - } - - @Test - public void testCreatePlainUngroupedShuffleReader() throws Exception { - runTestCreateUngroupedShuffleReader(new byte[] {(byte) 0xE1}, null, null, - makeCloudEncoding("StringUtf8Coder"), StringUtf8Coder.of()); - } - - @Test - public void testCreateRichUngroupedShuffleReader() throws Exception { - runTestCreateUngroupedShuffleReader(new byte[] {(byte) 0xE2}, "aaa", "zzz", - makeCloudEncoding("BigEndianIntegerCoder"), BigEndianIntegerCoder.of()); - } - - @Test - public void testCreatePlainGroupingShuffleReader() throws Exception { - runTestCreateGroupingShuffleReader( - new byte[] {(byte) 0xE1}, null, null, - makeCloudEncoding( - FullWindowedValueCoder.class.getName(), - makeCloudEncoding("KvCoder", makeCloudEncoding("BigEndianIntegerCoder"), - makeCloudEncoding("IterableCoder", makeCloudEncoding("StringUtf8Coder"))), - IntervalWindow.getCoder().asCloudObject()), - BigEndianIntegerCoder.of(), StringUtf8Coder.of()); - } - - @Test - public void testCreateRichGroupingShuffleReader() throws Exception { - runTestCreateGroupingShuffleReader( - new byte[] {(byte) 0xE2}, "aaa", "zzz", - makeCloudEncoding( - FullWindowedValueCoder.class.getName(), - makeCloudEncoding( - "KvCoder", makeCloudEncoding("BigEndianIntegerCoder"), - makeCloudEncoding( - "IterableCoder", - makeCloudEncoding("KvCoder", makeCloudEncoding("StringUtf8Coder"), - makeCloudEncoding("VoidCoder")))), - IntervalWindow.getCoder().asCloudObject()), - BigEndianIntegerCoder.of(), KvCoder.of(StringUtf8Coder.of(), VoidCoder.of())); - } - - @Test - public void testCreatePlainPartitioningShuffleReader() throws Exception { - runTestCreatePartitioningShuffleReader( - new byte[] {(byte) 0xE1}, null, null, - makeCloudEncoding( - FullWindowedValueCoder.class.getName(), - makeCloudEncoding("KvCoder", makeCloudEncoding("BigEndianIntegerCoder"), - makeCloudEncoding("StringUtf8Coder")), - IntervalWindow.getCoder().asCloudObject()), - BigEndianIntegerCoder.of(), - FullWindowedValueCoder.of(StringUtf8Coder.of(), IntervalWindow.getCoder())); - } - - @Test - public void testCreateRichPartitioningShuffleReader() throws Exception { - runTestCreatePartitioningShuffleReader( - new byte[] {(byte) 0xE2}, "aaa", "zzz", - makeCloudEncoding( - FullWindowedValueCoder.class.getName(), - makeCloudEncoding( - "KvCoder", makeCloudEncoding("BigEndianIntegerCoder"), - makeCloudEncoding("KvCoder", makeCloudEncoding("StringUtf8Coder"), - makeCloudEncoding("VoidCoder"))), - IntervalWindow.getCoder().asCloudObject()), - BigEndianIntegerCoder.of(), - FullWindowedValueCoder.of( - KvCoder.of(StringUtf8Coder.of(), VoidCoder.of()), IntervalWindow.getCoder())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactoryTest.java deleted file mode 100644 index cad5dadebc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactoryTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.encodeBase64String; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for ShuffleSinkFactory. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("rawtypes") -public class ShuffleSinkFactoryTest { - ShuffleSink runTestCreateShuffleSinkHelper(byte[] shuffleWriterConfig, - String shuffleKind, - CloudObject encoding, - FullWindowedValueCoder coder) - throws Exception { - CloudObject spec = CloudObject.forClassName("ShuffleSink"); - addString(spec, "shuffle_writer_config", encodeBase64String(shuffleWriterConfig)); - addString(spec, "shuffle_kind", shuffleKind); - - com.google.api.services.dataflow.model.Sink cloudSink = - new com.google.api.services.dataflow.model.Sink(); - cloudSink.setSpec(spec); - cloudSink.setCodec(encoding); - - PipelineOptions options = PipelineOptionsFactory.create(); - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - Sink sink = SinkFactory.create( - options, - cloudSink, - BatchModeExecutionContext.fromOptions(options), - addCounterMutator); - Assert.assertThat(sink, new IsInstanceOf(ShuffleSink.class)); - ShuffleSink shuffleSink = (ShuffleSink) sink; - Assert.assertArrayEquals(shuffleWriterConfig, - shuffleSink.shuffleWriterConfig); - Assert.assertEquals(coder, shuffleSink.windowedElemCoder); - return shuffleSink; - } - - void runTestCreateUngroupingShuffleSink(byte[] shuffleWriterConfig, - CloudObject encoding, - FullWindowedValueCoder coder) - throws Exception { - ShuffleSink shuffleSink = runTestCreateShuffleSinkHelper( - shuffleWriterConfig, "ungrouped", encoding, coder); - Assert.assertEquals(ShuffleSink.ShuffleKind.UNGROUPED, - shuffleSink.shuffleKind); - Assert.assertFalse(shuffleSink.shardByKey); - Assert.assertFalse(shuffleSink.groupValues); - Assert.assertFalse(shuffleSink.sortValues); - Assert.assertNull(shuffleSink.keyCoder); - Assert.assertNull(shuffleSink.valueCoder); - Assert.assertNull(shuffleSink.sortKeyCoder); - Assert.assertNull(shuffleSink.sortValueCoder); - } - - void runTestCreatePartitioningShuffleSink(byte[] shuffleWriterConfig, - Coder keyCoder, - Coder valueCoder) - throws Exception { - FullWindowedValueCoder coder = WindowedValue.getFullCoder( - KvCoder.of(keyCoder, valueCoder), IntervalWindow.getCoder()); - ShuffleSink shuffleSink = runTestCreateShuffleSinkHelper( - shuffleWriterConfig, "partition_keys", coder.asCloudObject(), coder); - Assert.assertEquals(ShuffleSink.ShuffleKind.PARTITION_KEYS, - shuffleSink.shuffleKind); - Assert.assertTrue(shuffleSink.shardByKey); - Assert.assertFalse(shuffleSink.groupValues); - Assert.assertFalse(shuffleSink.sortValues); - Assert.assertEquals(keyCoder, shuffleSink.keyCoder); - Assert.assertEquals(valueCoder, shuffleSink.valueCoder); - Assert.assertEquals(FullWindowedValueCoder.of(valueCoder, - IntervalWindow.getCoder()), - shuffleSink.windowedValueCoder); - Assert.assertNull(shuffleSink.sortKeyCoder); - Assert.assertNull(shuffleSink.sortValueCoder); - } - - void runTestCreateGroupingShuffleSink(byte[] shuffleWriterConfig, - Coder keyCoder, - Coder valueCoder) - throws Exception { - FullWindowedValueCoder coder = WindowedValue.getFullCoder( - KvCoder.of(keyCoder, valueCoder), IntervalWindow.getCoder()); - ShuffleSink shuffleSink = runTestCreateShuffleSinkHelper( - shuffleWriterConfig, "group_keys", coder.asCloudObject(), coder); - Assert.assertEquals(ShuffleSink.ShuffleKind.GROUP_KEYS, - shuffleSink.shuffleKind); - Assert.assertTrue(shuffleSink.shardByKey); - Assert.assertTrue(shuffleSink.groupValues); - Assert.assertFalse(shuffleSink.sortValues); - Assert.assertEquals(keyCoder, shuffleSink.keyCoder); - Assert.assertEquals(valueCoder, shuffleSink.valueCoder); - Assert.assertNull(shuffleSink.windowedValueCoder); - Assert.assertNull(shuffleSink.sortKeyCoder); - Assert.assertNull(shuffleSink.sortValueCoder); - } - - void runTestCreateGroupingSortingShuffleSink(byte[] shuffleWriterConfig, - Coder keyCoder, - Coder sortKeyCoder, - Coder sortValueCoder) - throws Exception { - FullWindowedValueCoder coder = WindowedValue.getFullCoder( - KvCoder.of(keyCoder, KvCoder.of(sortKeyCoder, sortValueCoder)), - IntervalWindow.getCoder()); - ShuffleSink shuffleSink = runTestCreateShuffleSinkHelper( - shuffleWriterConfig, "group_keys_and_sort_values", coder.asCloudObject(), coder); - Assert.assertEquals(ShuffleSink.ShuffleKind.GROUP_KEYS_AND_SORT_VALUES, - shuffleSink.shuffleKind); - Assert.assertTrue(shuffleSink.shardByKey); - Assert.assertTrue(shuffleSink.groupValues); - Assert.assertTrue(shuffleSink.sortValues); - Assert.assertEquals(keyCoder, shuffleSink.keyCoder); - Assert.assertEquals(KvCoder.of(sortKeyCoder, sortValueCoder), - shuffleSink.valueCoder); - Assert.assertEquals(sortKeyCoder, shuffleSink.sortKeyCoder); - Assert.assertEquals(sortValueCoder, shuffleSink.sortValueCoder); - Assert.assertNull(shuffleSink.windowedValueCoder); - } - - @Test - public void testCreateUngroupingShuffleSink() throws Exception { - FullWindowedValueCoder coder = WindowedValue.getFullCoder( - StringUtf8Coder.of(), IntervalWindow.getCoder()); - runTestCreateUngroupingShuffleSink( - new byte[]{(byte) 0xE1}, - coder.asCloudObject(), - coder); - } - - @Test - public void testCreatePartitionShuffleSink() throws Exception { - runTestCreatePartitioningShuffleSink( - new byte[]{(byte) 0xE2}, - BigEndianIntegerCoder.of(), - StringUtf8Coder.of()); - } - - @Test - public void testCreateGroupingShuffleSink() throws Exception { - runTestCreateGroupingShuffleSink( - new byte[]{(byte) 0xE2}, - BigEndianIntegerCoder.of(), - WindowedValue.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder())); - } - - @Test - public void testCreateGroupingSortingShuffleSink() throws Exception { - runTestCreateGroupingSortingShuffleSink( - new byte[]{(byte) 0xE3}, - BigEndianIntegerCoder.of(), - StringUtf8Coder.of(), - VoidCoder.of()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java deleted file mode 100644 index c4f2ea03b5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkTest.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink.SinkWriter; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests for {@link ShuffleSink}. - */ -@RunWith(JUnit4.class) -public class ShuffleSinkTest { - private static final List> NO_KVS = Collections.emptyList(); - - private static final List> KVS = Arrays.asList( - KV.of(1, "in 1a"), - KV.of(1, "in 1b"), - KV.of(2, "in 2a"), - KV.of(2, "in 2b"), - KV.of(3, "in 3"), - KV.of(4, "in 4a"), - KV.of(4, "in 4b"), - KV.of(4, "in 4c"), - KV.of(4, "in 4d"), - KV.of(5, "in 5")); - - private static final List>> NO_SORTING_KVS = - Collections.emptyList(); - - private static final List>> SORTING_KVS = - Arrays.asList( - KV.of(1, KV.of("in 1a", 3)), - KV.of(1, KV.of("in 1b", 9)), - KV.of(2, KV.of("in 2a", 2)), - KV.of(2, KV.of("in 2b", 77)), - KV.of(3, KV.of("in 3", 33)), - KV.of(4, KV.of("in 4a", -123)), - KV.of(4, KV.of("in 4b", 0)), - KV.of(4, KV.of("in 4c", -1)), - KV.of(4, KV.of("in 4d", 1)), - KV.of(5, KV.of("in 5", 666))); - - private static final Instant timestamp = new Instant(123000); - private static final IntervalWindow window = new IntervalWindow(timestamp, timestamp.plus(1000)); - - private void runTestWriteUngroupingShuffleSink(List expected) - throws Exception { - Coder> windowedValueCoder = - WindowedValue.getFullCoder(BigEndianIntegerCoder.of(), new GlobalWindows().windowCoder()); - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - ShuffleSink shuffleSink = new ShuffleSink<>( - PipelineOptionsFactory.create(), - null, ShuffleSink.ShuffleKind.UNGROUPED, - windowedValueCoder, - addCounterMutator); - - TestShuffleWriter shuffleWriter = new TestShuffleWriter(); - List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter> shuffleSinkWriter = - shuffleSink.writer(shuffleWriter, "dataset")) { - for (Integer value : expected) { - actualSizes.add(shuffleSinkWriter.add(WindowedValue.valueInGlobalWindow(value))); - } - } - - List records = shuffleWriter.getRecords(); - - List actual = new ArrayList<>(); - for (ShuffleEntry record : records) { - // Ignore the key. - byte[] valueBytes = record.getValue(); - WindowedValue value = CoderUtils.decodeFromByteArray(windowedValueCoder, valueBytes); - Assert.assertEquals(Lists.newArrayList(GlobalWindow.INSTANCE), - value.getWindows()); - actual.add(value.getValue()); - } - - Assert.assertEquals(expected, actual); - Assert.assertEquals(shuffleWriter.getSizes(), actualSizes); - } - - void runTestWriteGroupingShuffleSink( - List> expected) - throws Exception { - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - ShuffleSink> shuffleSink = new ShuffleSink<>( - PipelineOptionsFactory.create(), - null, ShuffleSink.ShuffleKind.GROUP_KEYS, - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of()), - IntervalWindow.getCoder()), - addCounterMutator); - - TestShuffleWriter shuffleWriter = new TestShuffleWriter(); - List actualSizes = new ArrayList<>(); - try (SinkWriter>> shuffleSinkWriter = - shuffleSink.writer(shuffleWriter, "dataset")) { - for (KV kv : expected) { - actualSizes.add(shuffleSinkWriter.add( - WindowedValue.of(KV.of(kv.getKey(), kv.getValue()), - timestamp, - Lists.newArrayList(window), - PaneInfo.NO_FIRING))); - } - } - - List records = shuffleWriter.getRecords(); - - List> actual = new ArrayList<>(); - for (ShuffleEntry record : records) { - byte[] keyBytes = record.getKey(); - byte[] valueBytes = record.getValue(); - Assert.assertEquals(timestamp, - CoderUtils.decodeFromByteArray(InstantCoder.of(), record.getSecondaryKey())); - - Integer key = - CoderUtils.decodeFromByteArray(BigEndianIntegerCoder.of(), - keyBytes); - String valueElem = CoderUtils.decodeFromByteArray(StringUtf8Coder.of(), valueBytes); - - actual.add(KV.of(key, valueElem)); - } - - Assert.assertEquals(expected, actual); - Assert.assertEquals(shuffleWriter.getSizes(), actualSizes); - } - - void runTestWriteGroupingSortingShuffleSink( - List>> expected) - throws Exception { - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - ShuffleSink>> shuffleSink = - new ShuffleSink<>( - PipelineOptionsFactory.create(), - null, - ShuffleSink.ShuffleKind.GROUP_KEYS_AND_SORT_VALUES, - WindowedValue.getFullCoder( - KvCoder.of(BigEndianIntegerCoder.of(), - KvCoder.of(StringUtf8Coder.of(), - BigEndianIntegerCoder.of())), - new GlobalWindows().windowCoder()), - addCounterMutator); - - TestShuffleWriter shuffleWriter = new TestShuffleWriter(); - List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter>>> shuffleSinkWriter = - shuffleSink.writer(shuffleWriter, "dataset")) { - for (KV> kv : expected) { - actualSizes.add(shuffleSinkWriter.add(WindowedValue.valueInGlobalWindow(kv))); - } - } - - List records = shuffleWriter.getRecords(); - - List>> actual = new ArrayList<>(); - for (ShuffleEntry record : records) { - byte[] keyBytes = record.getKey(); - byte[] valueBytes = record.getValue(); - byte[] sortKeyBytes = record.getSecondaryKey(); - - Integer key = - CoderUtils.decodeFromByteArray(BigEndianIntegerCoder.of(), - keyBytes); - ByteArrayInputStream bais = new ByteArrayInputStream(sortKeyBytes); - String sortKey = StringUtf8Coder.of().decode(bais, Context.NESTED); - Integer sortValue = CoderUtils.decodeFromByteArray(BigEndianIntegerCoder.of(), valueBytes); - - actual.add(KV.of(key, KV.of(sortKey, sortValue))); - } - - Assert.assertEquals(expected, actual); - Assert.assertEquals(shuffleWriter.getSizes(), actualSizes); - } - - @Test - public void testWriteEmptyUngroupingShuffleSink() throws Exception { - runTestWriteUngroupingShuffleSink(TestUtils.NO_INTS); - } - - @Test - public void testWriteNonEmptyUngroupingShuffleSink() throws Exception { - runTestWriteUngroupingShuffleSink(TestUtils.INTS); - } - - @Test - public void testWriteEmptyGroupingShuffleSink() throws Exception { - runTestWriteGroupingShuffleSink(NO_KVS); - } - - @Test - public void testWriteNonEmptyGroupingShuffleSink() throws Exception { - runTestWriteGroupingShuffleSink(KVS); - } - - @Test - public void testWriteEmptyGroupingSortingShuffleSink() throws Exception { - runTestWriteGroupingSortingShuffleSink(NO_SORTING_KVS); - } - - @Test - public void testWriteNonEmptyGroupingSortingShuffleSink() throws Exception { - runTestWriteGroupingSortingShuffleSink(SORTING_KVS); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtilsTest.java deleted file mode 100644 index be80235e54..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtilsTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.SideInputUtils.createCollectionSideInputInfo; -import static com.google.cloud.dataflow.sdk.runners.worker.SideInputUtils.createSingletonSideInputInfo; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for SideInputUtils. - */ -@RunWith(JUnit4.class) -public class SideInputUtilsTest { - Source createSideInputSource(Integer... ints) throws Exception { - return InMemoryReaderFactoryTest.createInMemoryCloudSource( - Arrays.asList(ints), null, null, BigEndianIntegerCoder.of()); - } - - void assertThatContains(Object actual, Object... expected) { - assertThat(actual, instanceOf(Iterable.class)); - Iterable iter = (Iterable) actual; - if (expected.length == 0) { - assertThat(iter, is(emptyIterable())); - } else { - assertThat(iter, contains(expected)); - } - } - - @Test - public void testReadSingletonSideInput() throws Exception { - SideInputInfo sideInputInfo = createSingletonSideInputInfo(createSideInputSource(42)); - - PipelineOptions options = PipelineOptionsFactory.create(); - assertEquals( - 42, - SideInputUtils.readSideInput( - options, sideInputInfo, - BatchModeExecutionContext.fromOptions(options))); - } - - @Test - public void testReadEmptyCollectionSideInput() throws Exception { - SideInputInfo sideInputInfo = createCollectionSideInputInfo(createSideInputSource()); - - PipelineOptions options = PipelineOptionsFactory.create(); - assertThatContains(SideInputUtils.readSideInput( - options, sideInputInfo, - BatchModeExecutionContext.fromOptions(options))); - } - - @Test - public void testReadCollectionSideInput() throws Exception { - SideInputInfo sideInputInfo = createCollectionSideInputInfo(createSideInputSource(3, 4, 5, 6)); - - PipelineOptions options = PipelineOptionsFactory.create(); - assertThatContains( - SideInputUtils.readSideInput( - options, sideInputInfo, - BatchModeExecutionContext.fromOptions(options)), - 3, 4, 5, 6); - } - - @Test - public void testReadCollectionShardedSideInput() throws Exception { - SideInputInfo sideInputInfo = - createCollectionSideInputInfo(createSideInputSource(3), createSideInputSource(), - createSideInputSource(4, 5), createSideInputSource(6), createSideInputSource()); - - PipelineOptions options = PipelineOptionsFactory.create(); - assertThatContains( - SideInputUtils.readSideInput( - options, sideInputInfo, - BatchModeExecutionContext.fromOptions(options)), - 3, 4, 5, 6); - } - - @Test - public void testReadSingletonSideInputValue() throws Exception { - CloudObject sideInputKind = CloudObject.forClassName("singleton"); - Object elem = "hi"; - List elems = Arrays.asList(elem); - assertEquals(elem, SideInputUtils.readSideInputValue(sideInputKind, elems)); - } - - @Test - public void testReadCollectionSideInputValue() throws Exception { - CloudObject sideInputKind = CloudObject.forClassName("collection"); - List elems = Arrays.asList("hi", "there", "bob"); - assertEquals(elems, SideInputUtils.readSideInputValue(sideInputKind, elems)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactoryTest.java deleted file mode 100644 index 96189e7f3e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactoryTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.hamcrest.CoreMatchers; -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for SinkFactory. - */ -@RunWith(JUnit4.class) -public class SinkFactoryTest { - static class TestSinkFactory { - public static TestSink create(PipelineOptions options, - CloudObject o, - Coder coder, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator) { - return new TestSink(); - } - } - - static class TestSink extends Sink { - @Override - public SinkWriter writer() { - return new TestSinkWriter(); - } - - /** A sink writer that drops its input values, for testing. */ - class TestSinkWriter implements SinkWriter { - @Override - public long add(Integer outputElem) { - return 4; - } - - @Override - public void close() { - } - } - } - - private PipelineOptions options; - - @Before - public void setUp() { - options = PipelineOptionsFactory.create(); - } - - @Test - public void testCreatePredefinedSink() throws Exception { - CloudObject spec = CloudObject.forClassName("TextSink"); - addString(spec, "filename", "/path/to/file.txt"); - - com.google.api.services.dataflow.model.Sink cloudSink = - new com.google.api.services.dataflow.model.Sink(); - cloudSink.setSpec(spec); - cloudSink.setCodec(makeCloudEncoding("StringUtf8Coder")); - - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - Sink sink = SinkFactory.create(options, - cloudSink, - BatchModeExecutionContext.fromOptions(options), - addCounterMutator); - Assert.assertThat(sink, new IsInstanceOf(TextSink.class)); - } - - @Test - public void testCreateUserDefinedSink() throws Exception { - CloudObject spec = CloudObject.forClass(TestSinkFactory.class); - - com.google.api.services.dataflow.model.Sink cloudSink = - new com.google.api.services.dataflow.model.Sink(); - cloudSink.setSpec(spec); - cloudSink.setCodec(makeCloudEncoding("BigEndianIntegerCoder")); - - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - Sink sink = SinkFactory.create(options, - cloudSink, - BatchModeExecutionContext.fromOptions(options), - addCounterMutator); - Assert.assertThat(sink, new IsInstanceOf(TestSink.class)); - } - - @Test - public void testCreateUnknownSink() throws Exception { - CloudObject spec = CloudObject.forClassName("UnknownSink"); - com.google.api.services.dataflow.model.Sink cloudSink = - new com.google.api.services.dataflow.model.Sink(); - cloudSink.setSpec(spec); - cloudSink.setCodec(makeCloudEncoding("StringUtf8Coder")); - try { - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - SinkFactory.create(options, - cloudSink, - BatchModeExecutionContext.fromOptions(options), - addCounterMutator); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - CoreMatchers.containsString( - "unable to create a sink")); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcherTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcherTest.java deleted file mode 100644 index 8fe7bc2cd4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcherTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.runners.worker.StateFetcher.SideInputState; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.base.Supplier; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.protobuf.ByteString; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** Unit tests for {@link StateFetcher}. */ -@RunWith(JUnit4.class) -public class StateFetcherTest { - private static final String STATE_FAMILY = "state"; - - @Mock - MetricTrackingWindmillServerStub server; - - @Mock - Supplier readStateSupplier; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testFetchGlobalDataBasic() throws Exception { - StateFetcher fetcher = new StateFetcher(server); - - ByteString.Output stream = ByteString.newOutput(); - ListCoder.of(WindowedValue.getFullCoder(StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE)) - .encode(Arrays.asList(WindowedValue.valueInGlobalWindow("data")), - stream, Coder.Context.OUTER); - ByteString encodedIterable = stream.toByteString(); - - PCollectionView view = - TestPipeline.create().apply(Create.of() - .withCoder(StringUtf8Coder.of())).apply(View.asSingleton()); - - String tag = view.getTagInternal().getId(); - - // Test three calls in a row. First, data is not ready, then data is ready, - // then the data is already cached. - when(server.getSideInputData(any(Windmill.GetDataRequest.class))).thenReturn( - buildGlobalDataResponse(tag, ByteString.EMPTY, false, null), - buildGlobalDataResponse(tag, ByteString.EMPTY, true, encodedIterable)); - - assertEquals(null, fetcher.fetchSideInput(view, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.UNKNOWN, readStateSupplier)); - assertEquals(null, fetcher.fetchSideInput(view, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.UNKNOWN, readStateSupplier)); - assertEquals("data", fetcher.fetchSideInput(view, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.KNOWN_READY, readStateSupplier)); - assertEquals("data", fetcher.fetchSideInput(view, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.KNOWN_READY, readStateSupplier)); - - verify(server, times(2)).getSideInputData(buildGlobalDataRequest(tag, ByteString.EMPTY)); - verifyNoMoreInteractions(server); - } - - @Test - public void testFetchGlobalDataCacheOverflow() throws Exception { - Coder>> coder = - ListCoder.of(WindowedValue.getFullCoder(StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE)); - - ByteString.Output stream = ByteString.newOutput(); - coder.encode(Arrays.asList(WindowedValue.valueInGlobalWindow("data1")), - stream, Coder.Context.OUTER); - ByteString encodedIterable1 = stream.toByteString(); - stream = ByteString.newOutput(); - coder.encode(Arrays.asList(WindowedValue.valueInGlobalWindow("data2")), - stream, Coder.Context.OUTER); - ByteString encodedIterable2 = stream.toByteString(); - - Cache cache = - CacheBuilder.newBuilder().build(); - - StateFetcher fetcher = new StateFetcher(server, cache); - - PCollectionView view1 = - TestPipeline.create().apply(Create.of() - .withCoder(StringUtf8Coder.of())).apply(View.asSingleton()); - - PCollectionView view2 = - TestPipeline.create().apply(Create.of() - .withCoder(StringUtf8Coder.of())).apply(View.asSingleton()); - - String tag1 = view1.getTagInternal().getId(); - String tag2 = view2.getTagInternal().getId(); - - // Test four calls in a row. First, fetch view1, then view2 (which evicts view1 from the cache), - // then view 1 again twice. - when(server.getSideInputData(any(Windmill.GetDataRequest.class))).thenReturn( - buildGlobalDataResponse(tag1, ByteString.EMPTY, true, encodedIterable1), - buildGlobalDataResponse(tag2, ByteString.EMPTY, true, encodedIterable2), - buildGlobalDataResponse(tag1, ByteString.EMPTY, true, encodedIterable1)); - - assertEquals("data1", fetcher.fetchSideInput(view1, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.UNKNOWN, readStateSupplier)); - assertEquals("data2", fetcher.fetchSideInput(view2, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.UNKNOWN, readStateSupplier)); - cache.invalidateAll(); - assertEquals("data1", fetcher.fetchSideInput(view1, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.UNKNOWN, readStateSupplier)); - assertEquals("data1", fetcher.fetchSideInput(view1, GlobalWindow.INSTANCE, STATE_FAMILY, - SideInputState.UNKNOWN, readStateSupplier)); - - ArgumentCaptor captor = - ArgumentCaptor.forClass(Windmill.GetDataRequest.class); - - verify(server, times(3)).getSideInputData(captor.capture()); - verifyNoMoreInteractions(server); - - assertThat(captor.getAllValues(), contains( - buildGlobalDataRequest(tag1, ByteString.EMPTY), - buildGlobalDataRequest(tag2, ByteString.EMPTY), - buildGlobalDataRequest(tag1, ByteString.EMPTY))); - } - - @Test - public void testEmptyFetchGlobalData() throws Exception { - StateFetcher fetcher = new StateFetcher(server); - - ByteString encodedIterable = ByteString.EMPTY; - - PCollectionView view = - TestPipeline.create().apply(Create.of() - .withCoder(VarLongCoder.of())).apply(Sum.longsGlobally().asSingletonView()); - - String tag = view.getTagInternal().getId(); - - // Test three calls in a row. First, data is not ready, then data is ready, - // then the data is already cached. - when(server.getSideInputData(any(Windmill.GetDataRequest.class))).thenReturn( - buildGlobalDataResponse(tag, ByteString.EMPTY, true, encodedIterable)); - - assertEquals(0L, (long) fetcher.fetchSideInput( - view, GlobalWindow.INSTANCE, STATE_FAMILY, SideInputState.UNKNOWN, readStateSupplier)); - - verify(server).getSideInputData(buildGlobalDataRequest(tag, ByteString.EMPTY)); - verifyNoMoreInteractions(server); - } - - private Windmill.GetDataResponse buildGlobalDataResponse( - String tag, ByteString version, boolean isReady, ByteString data) { - Windmill.GlobalData.Builder builder = Windmill.GlobalData.newBuilder() - .setDataId(Windmill.GlobalDataId.newBuilder() - .setTag(tag) - .setVersion(version) - .build()); - - if (isReady) { - builder.setIsReady(true).setData(data); - } else { - builder.setIsReady(false); - } - return Windmill.GetDataResponse.newBuilder() - .addGlobalData(builder.build()).build(); - } - - private Windmill.GetDataRequest buildGlobalDataRequest( - String tag, ByteString version) { - Windmill.GlobalDataId id = - Windmill.GlobalDataId.newBuilder().setTag(tag).setVersion(version).build(); - - return Windmill.GetDataRequest.newBuilder() - .addGlobalDataFetchRequests( - Windmill.GlobalDataRequest.newBuilder() - .setDataId(id) - .setStateFamily(STATE_FAMILY) - .setExistenceWatermarkDeadline( - TimeUnit.MILLISECONDS.toMicros( - GlobalWindow.INSTANCE.maxTimestamp().getMillis())) - .build()) - .addGlobalDataToFetch(id) - .build(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java deleted file mode 100644 index 5f5f712b32..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFnTest.java +++ /dev/null @@ -1,576 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.CollectionCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.InputMessageBundle; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Timer; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItem; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; -import com.google.cloud.dataflow.sdk.util.ReshuffleTriggerTest; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.protobuf.ByteString; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** Unit tests for {@link StreamingGroupAlsoByWindowsDoFn}. */ -@RunWith(JUnit4.class) -public class StreamingGroupAlsoByWindowsDoFnTest { - private static final String KEY = "k"; - private static final String STATE_FAMILY = "stateFamily"; - private static final long WORK_TOKEN = 1000L; - private static final String SOURCE_COMPUTATION_ID = "sourceComputationId"; - private ExecutionContext execContext; - private CounterSet counters; - - @Mock - private TimerInternals mockTimerInternals; - - private Coder windowCoder = IntervalWindow.getCoder(); - private Coder> windowsCoder = CollectionCoder.of(windowCoder); - - @Before public void setUp() { - MockitoAnnotations.initMocks(this); - execContext = new DirectModeExecutionContext() { - // Normally timerInternals doesn't come from the execution context, but - // StreamingGroupAlsoByWindows expects it to. So, hook that up. - - @Override - public StepContext createStepContext( - String stepName, String transformName, StateSampler stateSampler) { - StepContext context = - Mockito.spy(super.createStepContext(stepName, transformName, stateSampler)); - Mockito.doReturn(mockTimerInternals).when(context).timerInternals(); - return context; - } - }; - counters = new CounterSet(); - } - - @Test public void testReshufle() throws Exception { - DoFn fn = StreamingGroupAlsoByWindowsDoFn.createForIterable( - WindowingStrategy.of(FixedWindows.of(Duration.standardSeconds(30))) - .withTrigger(ReshuffleTriggerTest.forTest()), - VarIntCoder.of()); - assertTrue(fn instanceof StreamingGroupAlsoByWindowsReshuffleDoFn); - } - - @Test public void testEmpty() throws Exception { - TupleTag>> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - DoFnRunner, KV>> runner = - makeRunner( - outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); - - runner.startBundle(); - - runner.finishBundle(); - - List result = outputManager.getOutput(outputTag); - - assertEquals(0, result.size()); - } - - private void addTimer(WorkItem.Builder workItem, - IntervalWindow window, Instant timestamp, Windmill.Timer.Type type) { - StateNamespace namespace = StateNamespaces.window(windowCoder, window); - workItem.getTimersBuilder().addTimersBuilder() - .setTag(StreamingModeExecutionContext.timerTag(TimerData.of( - namespace, timestamp, - type == Windmill.Timer.Type.WATERMARK - ? TimeDomain.EVENT_TIME : TimeDomain.PROCESSING_TIME))) - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(timestamp)) - .setType(type) - .setStateFamily(STATE_FAMILY); - } - - private void addElement( - InputMessageBundle.Builder messageBundle, Collection windows, - Instant timestamp, Coder valueCoder, V value) throws IOException { - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder> windowsCoder = - (Coder) CollectionCoder.of(windowCoder); - - ByteString.Output dataOutput = ByteString.newOutput(); - valueCoder.encode(value, dataOutput, Context.OUTER); - messageBundle.addMessagesBuilder() - .setMetadata(WindmillSink.encodeMetadata(windowsCoder, windows, PaneInfo.NO_FIRING)) - .setData(dataOutput.toByteString()) - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(timestamp)); - } - - private WindowedValue> createValue( - WorkItem.Builder workItem, Coder valueCoder) { - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder> wildcardWindowsCoder = (Coder) windowsCoder; - return WindowedValue.valueInEmptyWindows( - KeyedWorkItems.windmillWorkItem( - KEY, workItem.build(), windowCoder, wildcardWindowsCoder, valueCoder)); - } - - @Test public void testFixedWindows() throws Exception { - TupleTag>> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - DoFnRunner, KV>> runner = - makeRunner( - outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); - - runner.startBundle(); - - WorkItem.Builder workItem1 = WorkItem.newBuilder(); - workItem1.setKey(ByteString.copyFromUtf8(KEY)); - workItem1.setWorkToken(WORK_TOKEN); - InputMessageBundle.Builder messageBundle = workItem1.addMessageBundlesBuilder(); - messageBundle.setSourceComputationId(SOURCE_COMPUTATION_ID); - - Coder valueCoder = StringUtf8Coder.of(); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(1), valueCoder, "v1"); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(2), valueCoder, "v2"); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(0), valueCoder, "v0"); - addElement(messageBundle, Arrays.asList(window(10, 20)), new Instant(13), valueCoder, "v3"); - - runner.processElement(createValue(workItem1, valueCoder)); - - runner.finishBundle(); - runner.startBundle(); - - WorkItem.Builder workItem2 = WorkItem.newBuilder(); - workItem2.setKey(ByteString.copyFromUtf8(KEY)); - workItem2.setWorkToken(WORK_TOKEN); - addTimer(workItem2, window(0, 10), new Instant(9), Timer.Type.WATERMARK); - addTimer(workItem2, window(10, 20), new Instant(19), Timer.Type.WATERMARK); - - runner.processElement(createValue(workItem2, valueCoder)); - - runner.finishBundle(); - - List>>> result = outputManager.getOutput(outputTag); - - assertEquals(2, result.size()); - - WindowedValue>> item0 = result.get(0); - assertEquals(KEY, item0.getValue().getKey()); - assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder("v0", "v1", "v2")); - assertEquals(new Instant(0), item0.getTimestamp()); - assertThat(item0.getWindows(), Matchers.contains(window(0, 10))); - - WindowedValue>> item1 = result.get(1); - assertEquals(KEY, item1.getValue().getKey()); - assertThat(item1.getValue().getValue(), Matchers.containsInAnyOrder("v3")); - assertEquals(new Instant(13), item1.getTimestamp()); - assertThat(item1.getWindows(), Matchers.contains(window(10, 20))); - } - - @Test public void testSlidingWindows() throws Exception { - TupleTag>> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - DoFnRunner, KV>> runner = - makeRunner( - outputTag, - outputManager, - WindowingStrategy.of( - SlidingWindows.of(Duration.millis(20)).every(Duration.millis(10)))); - - when(mockTimerInternals.currentInputWatermarkTime()).thenReturn(new Instant(5)); - - runner.startBundle(); - - WorkItem.Builder workItem1 = WorkItem.newBuilder(); - workItem1.setKey(ByteString.copyFromUtf8(KEY)); - workItem1.setWorkToken(WORK_TOKEN); - InputMessageBundle.Builder messageBundle = workItem1.addMessageBundlesBuilder(); - messageBundle.setSourceComputationId(SOURCE_COMPUTATION_ID); - - Coder valueCoder = StringUtf8Coder.of(); - addElement(messageBundle, - Arrays.asList(window(-10, 10), window(0, 20)), new Instant(5), valueCoder, "v1"); - addElement(messageBundle, - Arrays.asList(window(-10, 10), window(0, 20)), new Instant(2), valueCoder, "v0"); - addElement(messageBundle, - Arrays.asList(window(0, 20), window(10, 30)), new Instant(15), valueCoder, "v2"); - - runner.processElement(createValue(workItem1, valueCoder)); - - runner.finishBundle(); - runner.startBundle(); - - WorkItem.Builder workItem2 = WorkItem.newBuilder(); - workItem2.setKey(ByteString.copyFromUtf8(KEY)); - workItem2.setWorkToken(WORK_TOKEN); - addTimer(workItem2, window(-10, 10), new Instant(9), Timer.Type.WATERMARK); - addTimer(workItem2, window(0, 20), new Instant(19), Timer.Type.WATERMARK); - addTimer(workItem2, window(10, 30), new Instant(29), Timer.Type.WATERMARK); - - runner.processElement(createValue(workItem2, valueCoder)); - - runner.finishBundle(); - - List>>> result = outputManager.getOutput(outputTag); - - assertEquals(3, result.size()); - - WindowedValue>> item0 = result.get(0); - assertEquals(KEY, item0.getValue().getKey()); - assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder("v0", "v1")); - assertEquals(new Instant(2), item0.getTimestamp()); - assertThat(item0.getWindows(), Matchers.contains(window(-10, 10))); - - WindowedValue>> item1 = result.get(1); - assertEquals(KEY, item1.getValue().getKey()); - assertThat(item1.getValue().getValue(), Matchers.containsInAnyOrder("v0", "v1", "v2")); - // For this sliding window, the minimum output timestmap was 10, since we didn't want to overlap - // with the previous window that was [-10, 10). - assertEquals(new Instant(10), item1.getTimestamp()); - assertThat(item1.getWindows(), Matchers.contains(window(0, 20))); - - WindowedValue>> item2 = result.get(2); - assertEquals(KEY, item2.getValue().getKey()); - assertThat(item2.getValue().getValue(), Matchers.containsInAnyOrder("v2")); - assertEquals(new Instant(20), item2.getTimestamp()); - assertThat(item2.getWindows(), Matchers.contains(window(10, 30))); - } - - @Test public void testSlidingWindowsAndLateData() throws Exception { - TupleTag>> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - WindowingStrategy windowingStrategy = WindowingStrategy.of( - SlidingWindows.of(Duration.millis(20)).every(Duration.millis(10))); - DoFn, KV>> fn = - StreamingGroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, StringUtf8Coder.of()); - DoFnRunner, KV>> runner = - makeRunner( - outputTag, - outputManager, - windowingStrategy, - fn); - - when(mockTimerInternals.currentInputWatermarkTime()).thenReturn(new Instant(15)); - - runner.startBundle(); - - WorkItem.Builder workItem1 = WorkItem.newBuilder(); - workItem1.setKey(ByteString.copyFromUtf8(KEY)); - workItem1.setWorkToken(WORK_TOKEN); - InputMessageBundle.Builder messageBundle = workItem1.addMessageBundlesBuilder(); - messageBundle.setSourceComputationId(SOURCE_COMPUTATION_ID); - - Coder valueCoder = StringUtf8Coder.of(); - addElement(messageBundle, - Arrays.asList(window(-10, 10), window(0, 20)), new Instant(5), valueCoder, "v1"); - addElement(messageBundle, - Arrays.asList(window(-10, 10), window(0, 20)), new Instant(2), valueCoder, "v0"); - addElement(messageBundle, - Arrays.asList(window(0, 20), window(10, 30)), new Instant(15), valueCoder, "v2"); - - runner.processElement(createValue(workItem1, valueCoder)); - - runner.finishBundle(); - runner.startBundle(); - - WorkItem.Builder workItem2 = WorkItem.newBuilder(); - workItem2.setKey(ByteString.copyFromUtf8(KEY)); - workItem2.setWorkToken(WORK_TOKEN); - addTimer(workItem2, window(-10, 10), new Instant(9), Timer.Type.WATERMARK); - addTimer(workItem2, window(0, 20), new Instant(19), Timer.Type.WATERMARK); - addTimer(workItem2, window(10, 30), new Instant(29), Timer.Type.WATERMARK); - - runner.processElement(createValue(workItem2, valueCoder)); - - runner.finishBundle(); - - List>>> result = outputManager.getOutput(outputTag); - - assertEquals(3, result.size()); - - WindowedValue>> item0 = result.get(0); - assertEquals(KEY, item0.getValue().getKey()); - assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder()); - assertEquals(new Instant(9), item0.getTimestamp()); - assertThat(item0.getWindows(), Matchers.contains(window(-10, 10))); - - WindowedValue>> item1 = result.get(1); - assertEquals(KEY, item1.getValue().getKey()); - assertThat(item1.getValue().getValue(), Matchers.containsInAnyOrder("v0", "v1", "v2")); - // For this sliding window, the minimum output timestmap was 10, since we didn't want to overlap - // with the previous window that was [-10, 10). - assertEquals(new Instant(10), item1.getTimestamp()); - assertThat(item1.getWindows(), Matchers.contains(window(0, 20))); - - WindowedValue>> item2 = result.get(2); - assertEquals(KEY, item2.getValue().getKey()); - assertThat(item2.getValue().getValue(), Matchers.containsInAnyOrder("v2")); - assertEquals(new Instant(20), item2.getTimestamp()); - assertThat(item2.getWindows(), Matchers.contains(window(10, 30))); - - assertEquals( - counters.getExistingCounter("merge-DroppedDueToLateness").getAggregate(), - new Long(2)); - } - - @Test public void testSessions() throws Exception { - TupleTag>> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - DoFnRunner, KV>> runner = makeRunner( - outputTag, - outputManager, - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10)))); - - runner.startBundle(); - - WorkItem.Builder workItem1 = WorkItem.newBuilder(); - workItem1.setKey(ByteString.copyFromUtf8(KEY)); - workItem1.setWorkToken(WORK_TOKEN); - InputMessageBundle.Builder messageBundle = workItem1.addMessageBundlesBuilder(); - messageBundle.setSourceComputationId(SOURCE_COMPUTATION_ID); - - Coder valueCoder = StringUtf8Coder.of(); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(0), valueCoder, "v1"); - addElement(messageBundle, Arrays.asList(window(5, 15)), new Instant(5), valueCoder, "v2"); - addElement(messageBundle, Arrays.asList(window(15, 25)), new Instant(15), valueCoder, "v3"); - addElement(messageBundle, Arrays.asList(window(3, 13)), new Instant(3), valueCoder, "v0"); - - runner.processElement(createValue(workItem1, valueCoder)); - - runner.finishBundle(); - runner.startBundle(); - - WorkItem.Builder workItem2 = WorkItem.newBuilder(); - workItem2.setKey(ByteString.copyFromUtf8(KEY)); - workItem2.setWorkToken(WORK_TOKEN); - // Note that the WATERMARK timer for Instant(9) will have been deleted by - // ReduceFnRunner when window(0, 10) was merged away. - addTimer(workItem2, window(0, 15), new Instant(14), Timer.Type.WATERMARK); - addTimer(workItem2, window(15, 25), new Instant(24), Timer.Type.WATERMARK); - - runner.processElement(createValue(workItem2, valueCoder)); - - runner.finishBundle(); - - List>>> result = outputManager.getOutput(outputTag); - - assertEquals(2, result.size()); - - WindowedValue>> item0 = result.get(0); - assertEquals(KEY, item0.getValue().getKey()); - assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder("v0", "v1", "v2")); - assertEquals(new Instant(0), item0.getTimestamp()); - assertThat(item0.getWindows(), Matchers.contains(window(0, 15))); - - WindowedValue>> item1 = result.get(1); - assertEquals(KEY, item1.getValue().getKey()); - assertThat(item1.getValue().getValue(), Matchers.containsInAnyOrder("v3")); - assertEquals(new Instant(15), item1.getTimestamp()); - assertThat(item1.getWindows(), Matchers.contains(window(15, 25))); - } - - /** - * A custom combine fn that doesn't take any performace shortcuts - * to ensure that we are using the CombineFn API properly. - */ - private static class SumLongs extends CombineFn { - @Override - public Long createAccumulator() { - return 0L; - } - - @Override - public Long addInput(Long accumulator, Long input) { - return accumulator + input; - } - - @Override - public Long mergeAccumulators(Iterable accumulators) { - Long sum = 0L; - for (Long value : accumulators) { - sum += value; - } - return sum; - } - - @Override - public Long extractOutput(Long accumulator) { - return new Long(accumulator); - } - } - - @Test public void testSessionsCombine() throws Exception { - TupleTag> outputTag = new TupleTag<>(); - CombineFn combineFn = new SumLongs(); - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - - AppliedCombineFn appliedCombineFn = AppliedCombineFn.withInputCoder( - combineFn.asKeyedFn(), registry, KvCoder.of(StringUtf8Coder.of(), BigEndianLongCoder.of())); - - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - DoFnRunner, KV> runner = makeRunner( - outputTag, - outputManager, - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))), - appliedCombineFn); - - runner.startBundle(); - - WorkItem.Builder workItem1 = WorkItem.newBuilder(); - workItem1.setKey(ByteString.copyFromUtf8(KEY)); - workItem1.setWorkToken(WORK_TOKEN); - InputMessageBundle.Builder messageBundle = workItem1.addMessageBundlesBuilder(); - messageBundle.setSourceComputationId(SOURCE_COMPUTATION_ID); - - Coder valueCoder = BigEndianLongCoder.of(); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(0), valueCoder, 1L); - addElement(messageBundle, Arrays.asList(window(5, 15)), new Instant(5), valueCoder, 2L); - addElement(messageBundle, Arrays.asList(window(15, 25)), new Instant(15), valueCoder, 3L); - addElement(messageBundle, Arrays.asList(window(3, 13)), new Instant(3), valueCoder, 4L); - - runner.processElement(createValue(workItem1, valueCoder)); - - runner.finishBundle(); - runner.startBundle(); - - WorkItem.Builder workItem2 = WorkItem.newBuilder(); - workItem2.setKey(ByteString.copyFromUtf8(KEY)); - workItem2.setWorkToken(WORK_TOKEN); - // Note that the WATERMARK timer for Instant(9) will have been deleted by - // ReduceFnRunner when window(0, 10) was merged away. - addTimer(workItem2, window(0, 15), new Instant(14), Timer.Type.WATERMARK); - addTimer(workItem2, window(15, 25), new Instant(24), Timer.Type.WATERMARK); - - runner.processElement(createValue(workItem2, valueCoder)); - - runner.finishBundle(); - - List>> result = outputManager.getOutput(outputTag); - - assertEquals(2, result.size()); - - WindowedValue> item0 = result.get(0); - assertEquals(KEY, item0.getValue().getKey()); - assertEquals((Long) 7L, item0.getValue().getValue()); - assertEquals(new Instant(0), item0.getTimestamp()); - assertThat(item0.getWindows(), Matchers.contains(window(0, 15))); - - WindowedValue> item1 = result.get(1); - assertEquals(KEY, item1.getValue().getKey()); - assertEquals((Long) 3L, item1.getValue().getValue()); - assertEquals(new Instant(15), item1.getTimestamp()); - assertThat(item1.getWindows(), Matchers.contains(window(15, 25))); - } - - private DoFnRunner, KV>> makeRunner( - TupleTag>> outputTag, - DoFnRunners.OutputManager outputManager, - WindowingStrategy windowingStrategy) throws Exception { - - DoFn, KV>> fn = - StreamingGroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, StringUtf8Coder.of()); - - return makeRunner(outputTag, outputManager, windowingStrategy, fn); - } - - private DoFnRunner, KV> makeRunner( - TupleTag> outputTag, - DoFnRunners.OutputManager outputManager, - WindowingStrategy windowingStrategy, - AppliedCombineFn combineFn) throws Exception { - - DoFn, KV> fn = - StreamingGroupAlsoByWindowsDoFn.create(windowingStrategy, combineFn, StringUtf8Coder.of()); - - return makeRunner(outputTag, outputManager, windowingStrategy, fn); - } - - private - DoFnRunner, KV> makeRunner( - TupleTag> outputTag, - DoFnRunners.OutputManager outputManager, - WindowingStrategy windowingStrategy, - DoFn, KV> fn) throws Exception { - DoFnInfo, KV> doFnInfo = - new DoFnInfo<>(fn, windowingStrategy); - - return DoFnRunners.createDefault( - PipelineOptionsFactory.create(), - doFnInfo.getDoFn(), - NullSideInputReader.empty(), - outputManager, - outputTag, - new ArrayList>(), - execContext.getOrCreateStepContext("merge", "merge", null), - counters.getAddCounterMutator(), - doFnInfo.getWindowingStrategy()); - } - - private IntervalWindow window(long start, long end) { - return new IntervalWindow(new Instant(start), new Instant(end)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java deleted file mode 100644 index e2f6ef28b6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFnTest.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CollectionCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.InputMessageBundle; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItem; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.protobuf.ByteString; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** Unit tests for {@link StreamingGroupAlsoByWindowsReshuffleDoFn}. */ -@RunWith(JUnit4.class) -public class StreamingGroupAlsoByWindowsReshuffleDoFnTest { - private static final String KEY = "k"; - private static final long WORK_TOKEN = 1000L; - private static final String SOURCE_COMPUTATION_ID = "sourceComputationId"; - private ExecutionContext execContext; - private CounterSet counters; - - private Coder windowCoder = IntervalWindow.getCoder(); - private Coder> windowsCoder = CollectionCoder.of(windowCoder); - - @Before public void setUp() { - execContext = new DirectModeExecutionContext() { - // Normally timerInternals doesn't come from the execution context, but - // StreamingGroupAlsoByWindows expects it to. So, hook that up. - - @Override - public StepContext createStepContext( - String stepName, String transformName, StateSampler stateSampler) { - StepContext context = - Mockito.spy(super.createStepContext(stepName, transformName, stateSampler)); - Mockito.doReturn(null).when(context).timerInternals(); - return context; - } - }; - counters = new CounterSet(); - } - - @Test public void testEmpty() throws Exception { - TupleTag>> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - DoFnRunner, KV>> runner = - makeRunner( - outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); - - runner.startBundle(); - - runner.finishBundle(); - - List result = outputManager.getOutput(outputTag); - - assertEquals(0, result.size()); - } - - private void addElement( - InputMessageBundle.Builder messageBundle, Collection windows, - Instant timestamp, Coder valueCoder, V value) throws IOException { - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder> windowsCoder = - (Coder) CollectionCoder.of(windowCoder); - - ByteString.Output dataOutput = ByteString.newOutput(); - valueCoder.encode(value, dataOutput, Context.OUTER); - messageBundle.addMessagesBuilder() - .setMetadata(WindmillSink.encodeMetadata(windowsCoder, windows, PaneInfo.NO_FIRING)) - .setData(dataOutput.toByteString()) - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(timestamp)); - } - - private WindowedValue> createValue( - WorkItem.Builder workItem, Coder valueCoder) { - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder> wildcardWindowsCoder = (Coder) windowsCoder; - return WindowedValue.valueInEmptyWindows(KeyedWorkItems.windmillWorkItem( - KEY, workItem.build(), windowCoder, wildcardWindowsCoder, valueCoder)); - } - - @Test public void testFixedWindows() throws Exception { - TupleTag>> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - DoFnRunner, KV>> runner = - makeRunner( - outputTag, outputManager, WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))); - - runner.startBundle(); - - WorkItem.Builder workItem = WorkItem.newBuilder(); - workItem.setKey(ByteString.copyFromUtf8(KEY)); - workItem.setWorkToken(WORK_TOKEN); - InputMessageBundle.Builder messageBundle = workItem.addMessageBundlesBuilder(); - messageBundle.setSourceComputationId(SOURCE_COMPUTATION_ID); - - Coder valueCoder = StringUtf8Coder.of(); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(1), valueCoder, "v1"); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(2), valueCoder, "v2"); - addElement(messageBundle, Arrays.asList(window(0, 10)), new Instant(0), valueCoder, "v0"); - addElement(messageBundle, Arrays.asList(window(10, 20)), new Instant(13), valueCoder, "v3"); - - runner.processElement(createValue(workItem, valueCoder)); - - runner.finishBundle(); - - List>>> result = outputManager.getOutput(outputTag); - - assertEquals(4, result.size()); - - WindowedValue>> item0 = result.get(0); - assertEquals(KEY, item0.getValue().getKey()); - assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder("v1")); - assertEquals(new Instant(1), item0.getTimestamp()); - assertThat(item0.getWindows(), Matchers.contains(window(0, 10))); - - WindowedValue>> item1 = result.get(1); - assertEquals(KEY, item1.getValue().getKey()); - assertThat(item1.getValue().getValue(), Matchers.containsInAnyOrder("v2")); - assertEquals(new Instant(2), item1.getTimestamp()); - assertThat(item1.getWindows(), Matchers.contains(window(0, 10))); - - WindowedValue>> item2 = result.get(2); - assertEquals(KEY, item2.getValue().getKey()); - assertThat(item2.getValue().getValue(), Matchers.containsInAnyOrder("v0")); - assertEquals(new Instant(0), item2.getTimestamp()); - assertThat(item2.getWindows(), Matchers.contains(window(0, 10))); - - WindowedValue>> item3 = result.get(3); - assertEquals(KEY, item3.getValue().getKey()); - assertThat(item3.getValue().getValue(), Matchers.containsInAnyOrder("v3")); - assertEquals(new Instant(13), item3.getTimestamp()); - assertThat(item3.getWindows(), Matchers.contains(window(10, 20))); - } - - private DoFnRunner, KV>> makeRunner( - TupleTag>> outputTag, - DoFnRunners.OutputManager outputManager, - WindowingStrategy windowingStrategy) { - - DoFn, KV>> fn = - new StreamingGroupAlsoByWindowsReshuffleDoFn<>(); - - return makeRunner(outputTag, outputManager, windowingStrategy, fn); - } - - private - DoFnRunner, KV> makeRunner( - TupleTag> outputTag, - DoFnRunners.OutputManager outputManager, - WindowingStrategy windowingStrategy, - DoFn, KV> fn) { - return - DoFnRunners.createDefault( - PipelineOptionsFactory.create(), - fn, - NullSideInputReader.empty(), - outputManager, - outputTag, - new ArrayList>(), - execContext.getOrCreateStepContext("merge", "merge", null), - counters.getAddCounterMutator(), - windowingStrategy); - } - - private IntervalWindow window(long start, long end) { - return new IntervalWindow(new Instant(start), new Instant(end)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java deleted file mode 100644 index b781546b1b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContextTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.testing.PCollectionViewTesting; -import com.google.cloud.dataflow.sdk.testing.PCollectionViewTesting.ConstantViewFn; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaceForTest; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.protobuf.ByteString; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.Arrays; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link StreamingModeExecutionContext}. - */ -@RunWith(JUnit4.class) -public class StreamingModeExecutionContextTest { - - @Mock - private StateFetcher stateFetcher; - @Mock - private WindmillStateReader stateReader; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - // Helper to aid type inference - private static TupleTag>> newStringTag() { - return new TupleTag<>(); - } - - @Test - public void testTimerInternalsSetTimer() { - StreamingModeExecutionContext executionContext = new StreamingModeExecutionContext("stageName", - null, new ConcurrentHashMap(), - new WindmillStateCache().forComputation("comp")); - - Windmill.WorkItemCommitRequest.Builder outputBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - executionContext.start( - Windmill.WorkItem.newBuilder().setKey(ByteString.EMPTY).setWorkToken(17L).build(), - new Instant(1000), // input watermark - null, // output watermark - null, // synchronized processing time - stateReader, stateFetcher, outputBuilder); - ExecutionContext.StepContext step = - executionContext.getOrCreateStepContext("step", "transform", null); - - TimerInternals timerInternals = step.timerInternals(); - - timerInternals.setTimer( - TimerData.of(new StateNamespaceForTest("key"), new Instant(5000), TimeDomain.EVENT_TIME)); - executionContext.flushState(); - - Windmill.Timer timer = outputBuilder.buildPartial().getOutputTimers(0); - assertEquals("key+0:5000", timer.getTag().toStringUtf8()); - assertEquals(TimeUnit.MILLISECONDS.toMicros(5000), timer.getTimestamp()); - assertEquals(Windmill.Timer.Type.WATERMARK, timer.getType()); - } - - /** - * Tests that the {@link SideInputReader} returned by the {@link StreamingModeExecutionContext} - * contains the expected views when they are deserialized, as occurs on the - * service. - */ - @Test - public void testSideInputReaderReconstituted() { - StreamingModeExecutionContext executionContext = - new StreamingModeExecutionContext("stageName", null, null, null); - - PCollectionView preview1 = PCollectionViewTesting.testingView( - newStringTag(), new ConstantViewFn("view1"), StringUtf8Coder.of()); - PCollectionView preview2 = PCollectionViewTesting.testingView( - newStringTag(), new ConstantViewFn("view2"), StringUtf8Coder.of()); - PCollectionView preview3 = PCollectionViewTesting.testingView( - newStringTag(), new ConstantViewFn("view3"), StringUtf8Coder.of()); - - SideInputReader sideInputReader = executionContext.getSideInputReaderForViews( - Arrays.asList(preview1, preview2)); - - assertTrue(sideInputReader.contains(preview1)); - assertTrue(sideInputReader.contains(preview2)); - assertFalse(sideInputReader.contains(preview3)); - - PCollectionView view1 = SerializableUtils.ensureSerializable(preview1); - PCollectionView view2 = SerializableUtils.ensureSerializable(preview2); - PCollectionView view3 = SerializableUtils.ensureSerializable(preview3); - - assertTrue(sideInputReader.contains(view1)); - assertTrue(sideInputReader.contains(view2)); - assertFalse(sideInputReader.contains(view3)); - } - - private void startContext( - StreamingModeExecutionContext context, String key, long cacheToken) { - context.start( - Windmill.WorkItem.newBuilder() - .setKey(ByteString.copyFromUtf8(key)) // key is zero-padded index. - .setWorkToken(0) // Required proto field, unused. - .setCacheToken(cacheToken) - .setSourceState(Windmill.SourceState.newBuilder() - .setState(ByteString.EMPTY) - .build()) // Source state. - .build(), - new Instant(0), // input watermark - null, // output watermark - null, // synchronized processing time - null, // StateReader - null, // StateFetcher - Windmill.WorkItemCommitRequest.newBuilder()); - } - - @Test - public void testReaderCache() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setNumWorkers(5); - - ConcurrentHashMap readerCache = - new ConcurrentHashMap(); - StreamingModeExecutionContext context = - new StreamingModeExecutionContext("stageName", readerCache, /*stateNameMap=*/null, - /*stateCache=*/null); - - UnboundedSource.UnboundedReader reader1 = - new TestCountingSource(Integer.MAX_VALUE).createReader(options, null); - UnboundedSource.UnboundedReader reader2 = - new TestCountingSource(Integer.MAX_VALUE).createReader(options, null); - - readerCache.put(ByteString.copyFromUtf8("0000000000000001"), new ReaderCacheEntry(reader1, 1L)); - readerCache.put(ByteString.copyFromUtf8("0000000000000002"), new ReaderCacheEntry(reader2, 2L)); - - startContext(context, "0000000000000001", 1L); - assertEquals(reader1, context.getCachedReader()); - - startContext(context, "0000000000000001", 1L); - assertEquals(reader1, context.getCachedReader()); - - startContext(context, "0000000000000002", 1L); - assertEquals(null, context.getCachedReader()); - - startContext(context, "0000000000000003", 3L); - assertEquals(null, context.getCachedReader()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java deleted file mode 100644 index 0c16555604..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunnerTest.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.StateFetcher.SideInputState; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.GlobalDataRequest; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.ValueState; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.protobuf.ByteString; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** Unit tests for {@link StreamingSideInputDoFnRunner}. */ -@RunWith(JUnit4.class) -public class StreamingSideInputDoFnRunnerTest { - - private static final FixedWindows WINDOW_FN = FixedWindows.of(Duration.millis(10)); - - static TupleTag mainOutputTag = new TupleTag(); - @Mock StreamingModeExecutionContext execContext; - @Mock StreamingModeExecutionContext.StepContext stepContext; - @Mock SideInputReader mockSideInputReader; - - private final InMemoryStateInternals state = new InMemoryStateInternals(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - when(stepContext.stateInternals()).thenReturn(state); - } - - @Test - public void testSideInputReady() throws Exception { - PCollectionView view = createView(); - - when(stepContext.getSideInputNotifications()) - .thenReturn(Arrays.asList()); - when(stepContext.issueSideInputFetch( - eq(view), any(BoundedWindow.class), eq(SideInputState.UNKNOWN))) - .thenReturn(true); - when(execContext.getSideInputReaderForViews( - Mockito.>>any())).thenReturn(mockSideInputReader); - when(mockSideInputReader.contains(eq(view))).thenReturn(true); - when(mockSideInputReader.get(eq(view), any(BoundedWindow.class))).thenReturn("data"); - - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - StreamingSideInputDoFnRunner runner = - createRunner(outputManager, Arrays.asList(view)); - - runner.startBundle(); - runner.processElement(createDatum("e", 0)); - runner.finishBundle(); - - assertThat(outputManager.getOutput(mainOutputTag), contains(createDatum("e:data", 0))); - } - - @Test - public void testSideInputNotReady() throws Exception { - PCollectionView view = createView(); - - when(stepContext.getSideInputNotifications()) - .thenReturn(Arrays.asList()); - when(stepContext.issueSideInputFetch( - eq(view), any(BoundedWindow.class), eq(SideInputState.UNKNOWN))) - .thenReturn(false); - - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - StreamingSideInputDoFnRunner runner = - createRunner(outputManager, Arrays.asList(view)); - - runner.startBundle(); - runner.processElement(createDatum("e", 0)); - runner.finishBundle(); - - assertTrue(outputManager.getOutput(mainOutputTag).isEmpty()); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - // Verify that we added the element to an appropriate tag list, and that we buffered the element - ValueState>> blockedMapState = - state.state(StateNamespaces.global(), - StreamingSideInputDoFnRunner.blockedMapAddr(WINDOW_FN)); - assertEquals( - blockedMapState.get().read(), - Collections.singletonMap( - window, - Collections.singleton(Windmill.GlobalDataRequest.newBuilder() - .setDataId(Windmill.GlobalDataId.newBuilder() - .setTag(view.getTagInternal().getId()) - .setVersion(ByteString.copyFrom(CoderUtils.encodeToByteArray( - IntervalWindow.getCoder(), window))) - .build()) - .setExistenceWatermarkDeadline(9000) - .build()))); - assertThat(runner.elementBag(createWindow(0)).get().read(), - Matchers.contains(createDatum("e", 0))); - assertEquals(runner.watermarkHold(createWindow(0)).get().read(), new Instant(0)); - } - - @Test - public void testSideInputNotification() throws Exception { - PCollectionView view = createView(); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - Windmill.GlobalDataId id = Windmill.GlobalDataId.newBuilder() - .setTag(view.getTagInternal().getId()) - .setVersion(ByteString.copyFrom(CoderUtils.encodeToByteArray( - IntervalWindow.getCoder(), window))) - .build(); - - Set requestSet = new HashSet<>(); - requestSet.add(Windmill.GlobalDataRequest.newBuilder().setDataId(id).build()); - Map> blockedMap = new HashMap<>(); - blockedMap.put(window, requestSet); - - ValueState>> blockedMapState = - state.state(StateNamespaces.global(), - StreamingSideInputDoFnRunner.blockedMapAddr(WINDOW_FN)); - blockedMapState.set(blockedMap); - - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - StreamingSideInputDoFnRunner runner = - createRunner(outputManager, Arrays.asList(view)); - runner.watermarkHold(createWindow(0)).add(new Instant(0)); - runner.elementBag(createWindow(0)).add(createDatum("e", 0)); - - when(stepContext.getSideInputNotifications()).thenReturn(Arrays.asList(id)); - when(stepContext.issueSideInputFetch( - eq(view), any(BoundedWindow.class), eq(SideInputState.UNKNOWN))) - .thenReturn(false); - when(stepContext.issueSideInputFetch( - eq(view), any(BoundedWindow.class), eq(SideInputState.KNOWN_READY))) - .thenReturn(true); - when(execContext.getSideInputReaderForViews( - Mockito.>>any())).thenReturn(mockSideInputReader); - when(mockSideInputReader.contains(eq(view))).thenReturn(true); - when(mockSideInputReader.get(eq(view), any(BoundedWindow.class))).thenReturn("data"); - - runner.startBundle(); - runner.finishBundle(); - - assertThat(outputManager.getOutput(mainOutputTag), contains(createDatum("e:data", 0))); - - assertThat(blockedMapState.get().read().keySet(), Matchers.empty()); - assertThat(runner.watermarkHold(createWindow(0)).get().read(), Matchers.nullValue()); - assertThat(runner.elementBag(createWindow(0)).get().read(), Matchers.emptyIterable()); - } - - @Test - public void testMultipleSideInputs() throws Exception { - PCollectionView view1 = createView(); - PCollectionView view2 = createView(); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - Windmill.GlobalDataId id = Windmill.GlobalDataId.newBuilder() - .setTag(view1.getTagInternal().getId()) - .setVersion(ByteString.copyFrom(CoderUtils.encodeToByteArray( - IntervalWindow.getCoder(), window))) - .build(); - - Set requestSet = new HashSet<>(); - requestSet.add(Windmill.GlobalDataRequest.newBuilder().setDataId(id).build()); - Map> blockedMap = new HashMap<>(); - blockedMap.put(window, requestSet); - - ValueState>> blockedMapState = - state.state(StateNamespaces.global(), - StreamingSideInputDoFnRunner.blockedMapAddr(WINDOW_FN)); - blockedMapState.set(blockedMap); - - when(stepContext.getSideInputNotifications()).thenReturn(Arrays.asList(id)); - when(stepContext.issueSideInputFetch( - any(PCollectionView.class), any(BoundedWindow.class), any(SideInputState.class))) - .thenReturn(true); - when(execContext.getSideInputReaderForViews( - Mockito.>>any())).thenReturn(mockSideInputReader); - when(mockSideInputReader.contains(eq(view1))).thenReturn(true); - when(mockSideInputReader.contains(eq(view2))).thenReturn(true); - when(mockSideInputReader.get(eq(view1), any(BoundedWindow.class))).thenReturn("data1"); - when(mockSideInputReader.get(eq(view2), any(BoundedWindow.class))).thenReturn("data2"); - - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - StreamingSideInputDoFnRunner runner = - createRunner(outputManager, Arrays.asList(view1, view2)); - runner.watermarkHold(createWindow(0)).add(new Instant(0)); - runner.elementBag(createWindow(0)).add(createDatum("e1", 0)); - - runner.startBundle(); - runner.processElement(createDatum("e2", 2)); - runner.finishBundle(); - - assertThat(outputManager.getOutput(mainOutputTag), - contains(createDatum("e1:data1:data2", 0), createDatum("e2:data1:data2", 2))); - - assertThat(blockedMapState.get().read().keySet(), Matchers.empty()); - assertThat(runner.watermarkHold(createWindow(0)).get().read(), Matchers.nullValue()); - assertThat(runner.elementBag(createWindow(0)).get().read(), Matchers.emptyIterable()); - } - - @SuppressWarnings("unchecked") - private StreamingSideInputDoFnRunner - createRunner(DoFnRunners.OutputManager outputManager, List> views) - throws Exception { - @SuppressWarnings({"unchecked", "rawtypes"}) - Iterable> typedViews = (Iterable) views; - - DoFnInfo doFnInfo = new DoFnInfo( - new SideInputFn(views), WindowingStrategy.of(WINDOW_FN), - typedViews, StringUtf8Coder.of()); - - return (StreamingSideInputDoFnRunner) - StreamingDoFnRunners.streamingSideInputRunner( - PipelineOptionsFactory.create(), - doFnInfo, - mockSideInputReader, - outputManager, - mainOutputTag, - Arrays.>asList(), - stepContext, - null); - } - - private static class SideInputFn extends DoFn { - private List> views; - - public SideInputFn(List> views) { - this.views = views; - } - - @Override - public void processElement(ProcessContext c) { - String output = c.element(); - for (PCollectionView view : views) { - output += ":" + c.sideInput(view); - } - c.output(output); - } - } - - private PCollectionView createView() { - return TestPipeline.create() - .apply(Create.of().withCoder(StringUtf8Coder.of())) - .apply(Window.into(WINDOW_FN)) - .apply(View.asSingleton()); - } - - private WindowedValue createDatum(String element, long timestamp) { - return WindowedValue.of( - element, - new Instant(timestamp), - Arrays.asList(createWindow(timestamp)), - PaneInfo.NO_FIRING); - } - - private IntervalWindow createWindow(long timestamp) { - return new IntervalWindow( - new Instant(timestamp - timestamp % 10), - new Instant(timestamp - timestamp % 10 + 10)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java deleted file mode 100644 index 34bbead2bf..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReader.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.Reiterator; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntryReader; -import com.google.cloud.dataflow.sdk.util.common.worker.ShufflePosition; -import com.google.common.primitives.UnsignedBytes; - -import org.junit.Assert; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.NavigableMap; -import java.util.NoSuchElementException; -import java.util.TreeMap; - -/** - * A fake implementation of a ShuffleEntryReader, for testing. - */ -public class TestShuffleReader implements ShuffleEntryReader { - // Sorts by secondary key where an empty secondary key sorts before all other secondary keys. - static final Comparator SHUFFLE_KEY_COMPARATOR = new Comparator() { - - @Override - public int compare(byte[] o1, byte[] o2) { - if (o1 == o2) { - return 0; - } - if (o1 == null) { - return -1; - } - if (o2 == null) { - return 1; - } - return UnsignedBytes.lexicographicalComparator().compare(o1, o2); - } - }; - - final NavigableMap>> records; - - public TestShuffleReader() { - this.records = new TreeMap<>(SHUFFLE_KEY_COMPARATOR); - } - - public void addEntry(String key, String secondaryKey, String value) { - addEntry(new ShuffleEntry(key.getBytes(), secondaryKey.getBytes(), value.getBytes())); - } - - public void addEntry(ShuffleEntry entry) { - NavigableMap> valuesBySecondaryKey = records.get(entry.getKey()); - if (valuesBySecondaryKey == null) { - valuesBySecondaryKey = new TreeMap<>(SHUFFLE_KEY_COMPARATOR); - records.put(entry.getKey(), valuesBySecondaryKey); - } - List values = valuesBySecondaryKey.get(entry.getSecondaryKey()); - if (values == null) { - values = new ArrayList<>(); - valuesBySecondaryKey.put(entry.getSecondaryKey(), values); - } - values.add(entry); - } - - public Iterator read() { - return read((byte[]) null, (byte[]) null); - } - - @Override - public Reiterator read(ShufflePosition startPosition, - ShufflePosition endPosition) { - return read(ByteArrayShufflePosition.getPosition(startPosition), - ByteArrayShufflePosition.getPosition(endPosition)); - } - - public Reiterator read(String startKey, String endKey) { - return read(startKey == null ? null : startKey.getBytes(), - endKey == null ? null : endKey.getBytes()); - } - - public Reiteratorread(byte[] startKey, byte[] endKey) { - return new ShuffleReaderIterator(startKey, endKey); - } - - class ShuffleReaderIterator implements Reiterator { - final Iterator>>> recordsIter; - final byte[] startKey; - final byte[] endKey; - byte[] currentKey; - byte[] currentSecondaryKey; - Map.Entry>> currentRecord; - ListIterator currentValuesIter; - - public ShuffleReaderIterator(byte[] startKey, byte[] endKey) { - this.recordsIter = records.entrySet().iterator(); - this.startKey = startKey; - this.endKey = endKey; - advanceKey(); - } - - private ShuffleReaderIterator(ShuffleReaderIterator it) { - if (it.currentKey != null) { - this.recordsIter = - records.tailMap(it.currentKey, false).entrySet().iterator(); - } else { - this.recordsIter = null; - } - this.startKey = it.startKey; - this.endKey = it.endKey; - this.currentKey = it.currentKey; - this.currentRecord = it.currentRecord; - if (it.currentValuesIter != null) { - this.currentSecondaryKey = it.currentSecondaryKey; - this.currentValuesIter = - it.currentRecord.getValue().get(currentSecondaryKey).listIterator( - it.currentValuesIter.nextIndex()); - } else { - this.currentValuesIter = null; - } - } - - @Override - public boolean hasNext() { - return currentKey != null; - } - - @Override - public ShuffleEntry next() { - if (currentKey == null) { - throw new NoSuchElementException(); - } - ShuffleEntry resultValue = currentValuesIter.next(); - Assert.assertTrue(Arrays.equals(currentKey, resultValue.getKey())); - if (!currentValuesIter.hasNext()) { - advanceSecondaryKey(); - } - return resultValue; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public Reiterator copy() { - return new ShuffleReaderIterator(this); - } - - private void advanceSecondaryKey() { - NavigableMap> tailMap = - currentRecord.getValue().tailMap(currentSecondaryKey, false /* do not include key */); - if (tailMap.isEmpty()) { - advanceKey(); - } else { - currentSecondaryKey = tailMap.firstKey(); - currentValuesIter = tailMap.get(currentSecondaryKey).listIterator(); - } - } - - private void advanceKey() { - while (recordsIter.hasNext()) { - currentRecord = recordsIter.next(); - currentKey = currentRecord.getKey(); - if (startKey != null && - SHUFFLE_KEY_COMPARATOR.compare(currentKey, startKey) < 0) { - // This key is before the start of the range. Keep looking. - continue; - } - if (endKey != null && - SHUFFLE_KEY_COMPARATOR.compare(currentKey, endKey) >= 0) { - // This key is at or after the end of the range. Stop looking. - break; - } - // In range. - currentSecondaryKey = currentRecord.getValue().firstKey(); - currentValuesIter = currentRecord.getValue().get(currentSecondaryKey).listIterator(); - return; - } - currentKey = null; - currentSecondaryKey = null; - currentValuesIter = null; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java deleted file mode 100644 index f4b87bc01b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleReaderTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Tests of TestShuffleReader. - */ -@RunWith(JUnit4.class) -public class TestShuffleReaderTest { - static final String START_KEY = "ddd"; - static final String END_KEY = "mmm"; - - static final List>> NO_ENTRIES = - Collections.emptyList(); - - static final List>> IN_RANGE_ENTRIES = - Arrays.>>asList( - KV.of("ddd", KV.of("1", "in 1")), - KV.of("ddd", KV.of("2", "in 1")), - KV.of("ddd", KV.of("3", "in 1")), - KV.of("dddd", KV.of("1", "in 2")), - KV.of("dddd", KV.of("2", "in 2")), - KV.of("de", KV.of("1", "in 3")), - KV.of("ee", KV.of("1", "in 4")), - KV.of("ee", KV.of("2", "in 4")), - KV.of("ee", KV.of("3", "in 4")), - KV.of("ee", KV.of("4", "in 4")), - KV.of("mm", KV.of("1", "in 5"))); - static final List>> BEFORE_RANGE_ENTRIES = - Arrays.>>asList( - KV.of("", KV.of("1", "out 1")), - KV.of("dd", KV.of("1", "out 2"))); - static final List>> AFTER_RANGE_ENTRIES = - Arrays.>>asList( - KV.of("mmm", KV.of("1", "out 3")), - KV.of("mmm", KV.of("2", "out 3")), - KV.of("mmmm", KV.of("1", "out 4")), - KV.of("mn", KV.of("1", "out 5")), - KV.of("zzz", KV.of("1", "out 6"))); - static final List>> OUT_OF_RANGE_ENTRIES = - new ArrayList<>(); - static { - OUT_OF_RANGE_ENTRIES.addAll(BEFORE_RANGE_ENTRIES); - OUT_OF_RANGE_ENTRIES.addAll(AFTER_RANGE_ENTRIES); - } - static final List>> ALL_ENTRIES = new ArrayList<>(); - static { - ALL_ENTRIES.addAll(BEFORE_RANGE_ENTRIES); - ALL_ENTRIES.addAll(IN_RANGE_ENTRIES); - ALL_ENTRIES.addAll(AFTER_RANGE_ENTRIES); - } - - void runTest(List>> expected, - List>> outOfRange, - String startKey, - String endKey) { - TestShuffleReader shuffleReader = new TestShuffleReader(); - List>> expectedCopy = new ArrayList<>(expected); - expectedCopy.addAll(outOfRange); - Collections.shuffle(expectedCopy); - for (KV> entry : expectedCopy) { - shuffleReader.addEntry(entry.getKey(), - entry.getValue().getKey() /* secondary key */, - entry.getValue().getValue()); - } - Iterator iter = shuffleReader.read(startKey, endKey); - List>> actual = new ArrayList<>(); - while (iter.hasNext()) { - ShuffleEntry entry = iter.next(); - actual.add(KV.of(new String(entry.getKey()), - KV.of(new String(entry.getSecondaryKey()), - new String(entry.getValue())))); - } - try { - iter.next(); - fail("should have failed"); - } catch (NoSuchElementException exn) { - // Success. - } - assertEquals(expected, actual); - } - - @Test - public void testEmpty() { - runTest(NO_ENTRIES, NO_ENTRIES, null, null); - } - - @Test - public void testEmptyWithRange() { - runTest(NO_ENTRIES, NO_ENTRIES, START_KEY, END_KEY); - } - - @Test - public void testNonEmpty() { - runTest(ALL_ENTRIES, NO_ENTRIES, null, null); - } - - @Test - public void testNonEmptyWithAllInRange() { - runTest(IN_RANGE_ENTRIES, NO_ENTRIES, START_KEY, END_KEY); - } - - @Test - public void testNonEmptyWithSomeOutOfRange() { - runTest(IN_RANGE_ENTRIES, OUT_OF_RANGE_ENTRIES, START_KEY, END_KEY); - } - - @Test - public void testNonEmptyWithAllOutOfRange() { - runTest(NO_ENTRIES, OUT_OF_RANGE_ENTRIES, START_KEY, END_KEY); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleWriter.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleWriter.java deleted file mode 100644 index c7a2dfc677..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TestShuffleWriter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; - -import java.util.ArrayList; -import java.util.List; - -/** - * A fake implementation of a ShuffleEntryWriter, for testing. - */ -public class TestShuffleWriter implements ShuffleEntryWriter { - final List records = new ArrayList<>(); - final List sizes = new ArrayList<>(); - boolean closed = false; - - public TestShuffleWriter() { } - - @Override - public void put(ShuffleEntry entry) { - if (closed) { - throw new AssertionError("shuffle writer already closed"); - } - records.add(entry); - - long size = entry.length(); - sizes.add(size); - } - - @Override - public void close() { - if (closed) { - throw new AssertionError("shuffle writer already closed"); - } - closed = true; - } - - /** Returns the key/value records that were written to this ShuffleWriter. */ - public List getRecords() { - if (!closed) { - throw new AssertionError("shuffle writer not closed"); - } - return records; - } - - /** Returns the sizes in bytes of the records that were written to this ShuffleWriter. */ - public List getSizes() { - if (!closed) { - throw new AssertionError("shuffle writer not closed"); - } - return sizes; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java deleted file mode 100644 index f05d20344a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactoryTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; -import com.google.cloud.dataflow.sdk.io.TextIO.CompressionType; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import javax.annotation.Nullable; - -/** - * Tests for TextReaderFactory. - */ -@RunWith(JUnit4.class) -public class TextReaderFactoryTest { - void runTestCreateTextReader(String filename, @Nullable Boolean stripTrailingNewlines, - @Nullable Long start, @Nullable Long end, CloudObject encoding, Coder coder, - CompressionType compressionType) - throws Exception { - CloudObject spec = CloudObject.forClassName("TextSource"); - addString(spec, "filename", filename); - if (stripTrailingNewlines != null) { - addBoolean(spec, "strip_trailing_newlines", stripTrailingNewlines); - } - if (start != null) { - addLong(spec, "start_offset", start); - } - if (end != null) { - addLong(spec, "end_offset", end); - } - addString(spec, "compression_type", compressionType.toString()); - - Source cloudSource = new Source(); - cloudSource.setSpec(spec); - cloudSource.setCodec(encoding); - - PipelineOptions options = PipelineOptionsFactory.create(); - NativeReader reader = - ReaderRegistry.defaultRegistry() - .create( - cloudSource, options, BatchModeExecutionContext.fromOptions(options), null, null); - Assert.assertThat(reader, new IsInstanceOf(TextReader.class)); - TextReader textReader = (TextReader) reader; - Assert.assertEquals(filename, textReader.filepattern); - Assert.assertEquals( - stripTrailingNewlines == null ? true : stripTrailingNewlines, - textReader.stripTrailingNewlines); - Assert.assertEquals(start, textReader.startPosition); - Assert.assertEquals(end, textReader.endPosition); - Assert.assertEquals(coder, textReader.coder); - Assert.assertEquals(compressionType, textReader.compressionType); - } - - @Test - public void testCreatePlainTextReader() throws Exception { - runTestCreateTextReader("/path/to/file.txt", null, null, null, - makeCloudEncoding("StringUtf8Coder"), StringUtf8Coder.of(), CompressionType.UNCOMPRESSED); - } - - @Test - public void testCreateRichTextReader() throws Exception { - runTestCreateTextReader("gs://bucket/path/to/file2.txt", false, 200L, 500L, - makeCloudEncoding("TextualIntegerCoder"), TextualIntegerCoder.of(), - CompressionType.UNCOMPRESSED); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java deleted file mode 100644 index 59f494241d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderTest.java +++ /dev/null @@ -1,804 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtByteOffset; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtFraction; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.Position; -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.TextIO.CompressionType; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader.NativeReaderIterator; -import com.google.common.base.Joiner; - -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.nio.channels.Channels; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.zip.GZIPOutputStream; - -/** - * Tests for TextReader. - */ -@RunWith(JUnit4.class) -public class TextReaderTest { - private static final String[] fileContent = { - "\n", "\r\n", "" - }; - private static final long TOTAL_BYTES_COUNT; - - static { - long sumLen = 0L; - - for (String s : fileContent) { - sumLen += s.length(); - } - TOTAL_BYTES_COUNT = sumLen; - } - - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - /** - * A coder that verifies that all lines are of the form {@code <...>}, - * to give further assurance that TextReader is never returning or even - * trying to decode partial lines, in the tests where this coder is used. - */ - private static class WholeLineVerifyingCoder extends AtomicCoder { - @Override - public void encode(String value, OutputStream outStream, Context context) - throws CoderException, IOException { - StringUtf8Coder.of().encode(value, outStream, context); - } - - @Override - public String decode(InputStream inStream, Context context) throws CoderException, IOException { - String res = StringUtf8Coder.of().decode(inStream, context); - if (!res.trim().startsWith("<") || !res.trim().endsWith(">")) { - throw new CoderException("A partial line was passed to the coder by TextReader: " + res); - } - return res; - } - } - - private File initTestFile() throws IOException { - File tmpFile = tmpFolder.newFile(); - try (FileOutputStream output = new FileOutputStream(tmpFile)) { - for (String s : fileContent) { - output.write(s.getBytes()); - } - } - - return tmpFile; - } - - @Test - public void testReadEmptyFile() throws Exception { - TextReader textReader = new TextReader<>(tmpFolder.newFile().getPath(), true, null, - null, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - try (NativeReaderIterator iterator = textReader.iterator()) { - assertFalse(iterator.start()); - } - } - - @Test - public void testStrippedNewlines() throws Exception { - testNewlineHandling("\r", true); - testNewlineHandling("\r\n", true); - testNewlineHandling("\n", true); - } - - @Test - public void testStrippedNewlinesAtEndOfReadBuffer() throws Exception { - boolean stripNewLines = true; - StringBuilder payload = new StringBuilder(); - payload.append('<'); - for (int i = 0; i < TextReader.BUF_SIZE - 4; ++i) { - payload.append('a'); - } - payload.append('>'); - String[] lines = {payload.toString(), payload.toString()}; - testStringPayload(lines, "\r", stripNewLines); - testStringPayload(lines, "\r\n", stripNewLines); - testStringPayload(lines, "\n", stripNewLines); - } - - @Test - public void testUnstrippedNewlines() throws Exception { - testNewlineHandling("\r", false); - testNewlineHandling("\r\n", false); - testNewlineHandling("\n", false); - } - - @Test - public void testUnstrippedNewlinesAtEndOfReadBuffer() throws Exception { - boolean stripNewLines = false; - StringBuilder payload = new StringBuilder(); - for (int i = 0; i < TextReader.BUF_SIZE - 2; ++i) { - payload.append('a'); - } - String[] lines = {payload.toString(), payload.toString()}; - testStringPayload(lines, "\r", stripNewLines); - testStringPayload(lines, "\r\n", stripNewLines); - testStringPayload(lines, "\n", stripNewLines); - } - - @Test - public void testStartPosition() throws Exception { - File tmpFile = initTestFile(); - assertEquals(40, tmpFile.length()); - - { - TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 13L, null, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals( - Arrays.asList("\r\n", ""), - ReaderUtils.readAllFromReader(textReader)); - // The first '1' in the array represents the reading of '\n' between first and - // second line, to confirm that we are reading from the beginning of a record. - assertEquals(Arrays.asList(1, 15, 12), observer.getActualSizes()); - } - - { - TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 24L, null, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals(Arrays.asList(""), ReaderUtils.readAllFromReader(textReader)); - // The first '5' in the array represents the reading of a portion of the second - // line, which had to be read to find the beginning of the third line. - assertEquals(Arrays.asList(5, 12), observer.getActualSizes()); - } - - { - TextReader textReader = - new TextReader<>( - tmpFile.getPath(), - false, - 32L, - null, - new WholeLineVerifyingCoder(), - TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals(Arrays.asList(), ReaderUtils.readAllFromReader(textReader)); - assertEquals(Arrays.asList(9), observer.getActualSizes()); - } - - { - TextReader textReader = - new TextReader<>( - tmpFile.getPath(), - false, - 41L, - null, - new WholeLineVerifyingCoder(), - TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals(Arrays.asList(), ReaderUtils.readAllFromReader(textReader)); - assertEquals(Arrays.asList(), observer.getActualSizes()); - } - - { - TextReader textReader = - new TextReader<>( - tmpFile.getPath(), - true, - 0L, - 22L, - new WholeLineVerifyingCoder(), - TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals( - Arrays.asList("", ""), - ReaderUtils.readAllFromReader(textReader)); - assertEquals(Arrays.asList(13, 15), observer.getActualSizes()); - } - - { - TextReader textReader = new TextReader<>(tmpFile.getPath(), true, 1L, 20L, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals(Arrays.asList(""), ReaderUtils.readAllFromReader(textReader)); - // The first '13' in the array represents the reading of the entire first - // line, which had to be read to find the beginning of the second line. - assertEquals(Arrays.asList(13, 15), observer.getActualSizes()); - } - } - - @Test - public void testUtf8Handling() throws Exception { - File tmpFile = tmpFolder.newFile(); - try (FileOutputStream output = new FileOutputStream(tmpFile)) { - // first line: €\n - // second line: ¢\n - output.write( - new byte[] {(byte) 0xE2, (byte) 0x82, (byte) 0xAC, '\n', (byte) 0xC2, (byte) 0xA2, '\n'}); - } - - { - // 3L is after the first line if counting codepoints, but within - // the first line if counting chars. So correct behavior is to return - // just one line, since offsets are in chars, not codepoints. - TextReader textReader = new TextReader<>(tmpFile.getPath(), true, 0L, 3L, - StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals(Arrays.asList("€"), ReaderUtils.readAllFromReader(textReader)); - assertEquals(Arrays.asList(4), observer.getActualSizes()); - } - - { - // Starting location is mid-way into a codepoint. - // Ensures we don't fail when skipping over an incomplete codepoint. - TextReader textReader = new TextReader<>(tmpFile.getPath(), true, 2L, null, - StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals(Arrays.asList("¢"), ReaderUtils.readAllFromReader(textReader)); - // The first '3' in the array represents the reading of a portion of the first - // line, which had to be read to find the beginning of the second line. - assertEquals(Arrays.asList(3, 3), observer.getActualSizes()); - } - } - - private void testNewlineHandling(String separator, boolean stripNewlines) throws Exception { - File tmpFile = tmpFolder.newFile(); - List expected = Arrays.asList("", " hi there ", "bob", "", " ", "--zowie!--", ""); - List expectedSizes = new ArrayList<>(); - try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) { - for (String line : expected) { - writer.print(line); - writer.print(separator); - expectedSizes.add(line.length() + separator.length()); - } - } - - TextReader textReader = new TextReader<>(tmpFile.getPath(), stripNewlines, null, null, - StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - List actual = ReaderUtils.readAllFromReader(textReader); - if (stripNewlines) { - assertEquals(expected, actual); - } else { - List unstripped = new LinkedList<>(); - for (String s : expected) { - unstripped.add(s + separator); - } - assertEquals(unstripped, actual); - } - - assertEquals(expectedSizes, observer.getActualSizes()); - } - - private void testStringPayload(String[] lines, String separator, boolean stripNewlines) - throws Exception { - File tmpFile = tmpFolder.newFile(); - List expected = new ArrayList<>(); - try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) { - for (String line : lines) { - writer.print(line); - writer.print(separator); - expected.add(stripNewlines ? line : line + separator); - } - } - - TextReader textReader = new TextReader<>(tmpFile.getPath(), stripNewlines, null, null, - StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); - assertEquals(expected, ReaderUtils.readAllFromReader(textReader)); - } - - @Test - public void testNonStringCoders() throws Exception { - File tmpFile = tmpFolder.newFile(); - List expected = TestUtils.INTS; - List expectedSizes = new ArrayList<>(); - try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) { - for (Integer elem : expected) { - byte[] encodedElem = CoderUtils.encodeToByteArray(TextualIntegerCoder.of(), elem); - writer.print(elem); - writer.print("\n"); - expectedSizes.add(1 + encodedElem.length); - } - } - - TextReader textReader = new TextReader<>(tmpFile.getPath(), true, null, null, - TextualIntegerCoder.of(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - assertEquals(expected, ReaderUtils.readAllFromReader(textReader)); - assertEquals(expectedSizes, observer.getActualSizes()); - } - - @Test - public void testGetProgressNoEndOffset() throws Exception { - File tmpFile = initTestFile(); - TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 0L, null, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - - try (NativeReaderIterator iterator = textReader.iterator()) { - ApproximateReportedProgress progress = readerProgressToCloudProgress(iterator.getProgress()); - assertEquals(0L, progress.getPosition().getByteOffset().longValue()); - assertTrue(iterator.start()); - progress = readerProgressToCloudProgress(iterator.getProgress()); - assertEquals(13L, progress.getPosition().getByteOffset().longValue()); - assertTrue(iterator.advance()); - progress = readerProgressToCloudProgress(iterator.getProgress()); - assertEquals(28L, progress.getPosition().getByteOffset().longValue()); - // Since end position is not specified, percentComplete should be null. - assertNull(progress.getFractionConsumed()); - - assertTrue(iterator.advance()); - progress = readerProgressToCloudProgress(iterator.getProgress()); - assertEquals(40L, progress.getPosition().getByteOffset().longValue()); - assertFalse(iterator.advance()); - } - } - - @Test - public void testGetProgressWithEndOffset() throws Exception { - File tmpFile = initTestFile(); - TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 0L, 40L, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - - try (NativeReaderIterator iterator = textReader.iterator()) { - assertTrue(iterator.start()); - ApproximateReportedProgress progress = readerProgressToCloudProgress(iterator.getProgress()); - // Returned a record that starts at position 0 of 40 - 1/40 fraction consumed. - assertEquals(1.0 / 40, progress.getFractionConsumed(), 1e-6); - assertTrue(iterator.advance()); - assertTrue(iterator.advance()); - progress = readerProgressToCloudProgress(iterator.getProgress()); - // Returned a record that starts at position 28 - 29/40 consumed. - assertEquals(1.0 * 29 / 40, progress.getFractionConsumed(), 1e-6); - assertFalse(iterator.advance()); - } - } - - @Test - public void testUpdateStopPosition() throws Exception { - final long end = 10L; // in the first line - final long stop = 14L; // in the middle of the second line - File tmpFile = initTestFile(); - long fileSize = tmpFile.length(); - - // Illegal proposed stop position, no update. - { - TextReader textReader = new TextReader<>( - tmpFile.getPath(), false, 0L, fileSize, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - - try (NativeReaderIterator iterator = textReader.iterator()) { - // Poke the iterator so we can test dynamic splitting. - assertTrue(iterator.start()); - - assertNull(iterator.requestDynamicSplit(splitRequestAtPosition(new Position()))); - } - } - - // Successful update. - { - TextReader textReader = new TextReader<>( - tmpFile.getPath(), false, 0L, fileSize, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { - // Poke the iterator so we can test dynamic splitting. - assertTrue(iterator.start()); - - assertEquals(fileSize, iterator.getEndOffset()); - assertEquals( - Long.valueOf(stop), - positionFromSplitResult(iterator.requestDynamicSplit(splitRequestAtByteOffset(stop))) - .getByteOffset()); - assertEquals(stop, iterator.getEndOffset()); - assertEquals(fileContent[0], iterator.getCurrent()); - assertTrue(iterator.advance()); - assertEquals(fileContent[1], iterator.getCurrent()); - assertFalse(iterator.advance()); - assertEquals( - Arrays.asList(fileContent[0].length(), fileContent[1].length()), - observer.getActualSizes()); - } - } - - // Update based on fraction. - { - TextReader textReader = new TextReader<>(tmpFile.getPath(), false, 0L, fileSize, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { - // Poke the iterator so we can test dynamic splitting. - assertTrue(iterator.start()); - - // Trying to split at 0 or 1 will fail. - assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0))); - assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(1))); - - // must be less than or equal to (size of first two lines / size of file) for this test to - // pass. - float splitPos = 0.61f; - - long stopPosition = (long) Math.ceil(fileSize * splitPos); - assertEquals(fileSize, iterator.getEndOffset()); - assertEquals( - Long.valueOf(stopPosition), - positionFromSplitResult(iterator.requestDynamicSplit(splitRequestAtFraction(splitPos))) - .getByteOffset()); - assertEquals(stopPosition, iterator.getEndOffset()); - assertEquals(fileContent[0], iterator.getCurrent()); - assertTrue(iterator.advance()); - assertEquals(fileContent[1], iterator.getCurrent()); - assertFalse(iterator.advance()); - assertEquals( - Arrays.asList(fileContent[0].length(), fileContent[1].length()), - observer.getActualSizes()); - } - } - - // Proposed stop position is before the current position, no update. - { - TextReader textReader = new TextReader<>( - tmpFile.getPath(), false, 0L, fileSize, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { - assertTrue(iterator.start()); - assertEquals(fileContent[0], iterator.getCurrent()); - assertTrue(iterator.advance()); - assertEquals(fileContent[1], iterator.getCurrent()); - assertThat( - readerProgressToCloudProgress(iterator.getProgress()).getPosition().getByteOffset(), - greaterThan(stop)); - assertTrue(iterator.advance()); - // The iterator just promised to return the next record, which is beyond "stop". - assertNull(iterator.requestDynamicSplit(splitRequestAtByteOffset(stop))); - assertEquals(fileSize, iterator.getEndOffset()); - assertEquals(fileContent[2], iterator.getCurrent()); - assertEquals( - Arrays.asList( - fileContent[0].length(), fileContent[1].length(), fileContent[2].length()), - observer.getActualSizes()); - assertFalse(iterator.advance()); - } - } - - // Proposed stop position is after the current stop (end) position, no update. - { - TextReader textReader = new TextReader<>(tmpFile.getPath(), false, null, end, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(textReader); - - try (TextReader.TextFileIterator iterator = - (TextReader.TextFileIterator) textReader.iterator()) { - assertTrue(iterator.start()); - assertEquals(fileContent[0], iterator.getCurrent()); - assertNull(iterator.requestDynamicSplit(splitRequestAtByteOffset(stop))); - assertEquals(end, iterator.getEndOffset()); - assertFalse(iterator.advance()); - assertEquals(Arrays.asList(fileContent[0].length()), observer.getActualSizes()); - } - } - } - - @Test - public void testUpdateStopPositionExhaustive() throws Exception { - File tmpFile = initTestFile(); - - // Checks for every possible position in the file, that either we fail to - // "updateStop" at it, or we succeed and then reading both halves together - // yields the original file with no missed records or duplicates. - for (long start = 0; start < TOTAL_BYTES_COUNT - 1; start++) { - for (long end = start + 1; end < TOTAL_BYTES_COUNT; end++) { - for (long stop = start; stop <= end; stop++) { - stopPositionTestInternal(start, end, stop, tmpFile); - } - } - } - - // Test with null start/end positions. - for (long stop = 0L; stop < TOTAL_BYTES_COUNT; stop++) { - stopPositionTestInternal(null, null, stop, tmpFile); - } - } - - private void stopPositionTestInternal( - Long startOffset, Long endOffset, Long stopOffset, File tmpFile) throws Exception { - String readWithoutSplit; - String readWithSplit1, readWithSplit2; - - // Read from source without split attempts. - TextReader textReader = new TextReader<>(tmpFile.getPath(), false, startOffset, - endOffset, new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - readWithoutSplit = Joiner.on("").join(ReaderUtils.readAllFromReader(textReader)); - - // Read the first half of the split. - textReader = new TextReader<>(tmpFile.getPath(), false, startOffset, stopOffset, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - readWithSplit1 = Joiner.on("").join(ReaderUtils.readAllFromReader(textReader)); - - // Read the second half of the split. - textReader = new TextReader<>(tmpFile.getPath(), false, stopOffset, endOffset, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - readWithSplit2 = Joiner.on("").join(ReaderUtils.readAllFromReader(textReader)); - - assertEquals(readWithoutSplit, readWithSplit1 + readWithSplit2); - } - - private OutputStream getOutputStreamForCompressionType( - OutputStream stream, CompressionType compressionType) throws IOException { - switch (compressionType) { - case GZIP: - return new GZIPOutputStream(stream); - case BZIP2: - return new BZip2CompressorOutputStream(stream); - case UNCOMPRESSED: - case AUTO: - return stream; - default: - fail("Unrecognized stream type"); - } - return stream; - } - - private File createFileWithCompressionType( - String[] lines, String filename, CompressionType compressionType) throws IOException { - File tmpFile = tmpFolder.newFile(filename); - try (PrintStream writer = - new PrintStream( - getOutputStreamForCompressionType( - new FileOutputStream(tmpFile), compressionType))) { - for (String line : lines) { - writer.println(line); - } - } - return tmpFile; - } - - private void testCompressionTypeHelper(String[] lines, String filename, - CompressionType outputCompressionType, CompressionType inputCompressionType) - throws IOException { - File tmpFile = createFileWithCompressionType(lines, filename, outputCompressionType); - - List expected = new ArrayList<>(); - for (String line : lines) { - expected.add(line); - } - - TextReader textReader = new TextReader<>( - tmpFile.getPath(), true, null, null, new WholeLineVerifyingCoder(), inputCompressionType); - assertEquals(expected, ReaderUtils.readAllFromReader(textReader)); - tmpFile.delete(); - } - - @Test - public void testCompressionTypeOneFile() throws IOException { - String[] contents = {"", "", ""}; - // test AUTO compression type with different extensions - testCompressionTypeHelper(contents, "test.gz", CompressionType.GZIP, CompressionType.AUTO); - testCompressionTypeHelper(contents, "test.bz2", CompressionType.BZIP2, CompressionType.AUTO); - testCompressionTypeHelper( - contents, "test.txt", CompressionType.UNCOMPRESSED, CompressionType.AUTO); - testCompressionTypeHelper(contents, "test", CompressionType.UNCOMPRESSED, CompressionType.AUTO); - // test GZIP, BZIP2, and UNCOMPRESSED - testCompressionTypeHelper(contents, "test.txt", CompressionType.GZIP, CompressionType.GZIP); - testCompressionTypeHelper(contents, "test.txt", CompressionType.BZIP2, CompressionType.BZIP2); - testCompressionTypeHelper( - contents, "test.gz", CompressionType.UNCOMPRESSED, CompressionType.UNCOMPRESSED); - } - - @Test - public void testCompressionTypeFileGlob() throws IOException { - String[][] contents = { - {"", "", ""}, - {"", ""}, - {"", ""}, - }; - File[] files = { - createFileWithCompressionType(contents[0], "test.gz", CompressionType.GZIP), - createFileWithCompressionType(contents[1], "test.bz2", CompressionType.BZIP2), - createFileWithCompressionType(contents[2], "test.txt", CompressionType.UNCOMPRESSED), - }; - - List expected = new ArrayList<>(); - for (String[] fileContents : contents) { - for (String line : fileContents) { - expected.add(line); - } - } - - String path = tmpFolder.getRoot().getPath() + System.getProperty("file.separator") + "*"; - - TextReader textReader = - new TextReader<>(path, true, null, null, new WholeLineVerifyingCoder(), - CompressionType.AUTO); - assertThat(ReaderUtils.readAllFromReader(textReader), containsInAnyOrder(expected.toArray())); - for (File file : files) { - file.delete(); - } - } - - @Test - public void testParallelismEstimatesDeclaredNotCompressed() throws IOException { - File file = - createFileWithCompressionType(fileContent, "test.gz", CompressionType.UNCOMPRESSED); - TextReader textReader = - new TextReader<>( - file.getPath(), - true /*stripTrailingNewlines*/, - null /*startPos*/, - null /*endPos*/, - new WholeLineVerifyingCoder(), - CompressionType.UNCOMPRESSED); - assertEquals(Double.POSITIVE_INFINITY, textReader.getTotalParallelism(), 0 /*tolerance*/); - file.delete(); - } - - @Test - public void testParallelismEstimatesDeclaredCompressed() throws IOException { - File file = createFileWithCompressionType(fileContent, "test.txt", CompressionType.GZIP); - TextReader textReader = - new TextReader<>( - file.getPath(), true, null, null, new WholeLineVerifyingCoder(), CompressionType.GZIP); - assertEquals(1, textReader.getTotalParallelism(), 0 /*tolerance*/); - file.delete(); - } - - @Test - public void testParallelismEstimatesAutoNotCompressed() throws IOException { - File file = - createFileWithCompressionType(fileContent, "test.txt", CompressionType.UNCOMPRESSED); - TextReader textReader = - new TextReader<>( - file.getPath(), true, null, null, new WholeLineVerifyingCoder(), CompressionType.AUTO); - assertEquals(Double.POSITIVE_INFINITY, textReader.getTotalParallelism(), 0 /*tolerance*/); - file.delete(); - } - - @Test - public void testParallelismEstimatesAutoCompressed() throws IOException { - File file = createFileWithCompressionType(fileContent, "test.gz", CompressionType.GZIP); - TextReader textReader = - new TextReader<>( - file.getPath(), true, null, null, new WholeLineVerifyingCoder(), CompressionType.AUTO); - assertEquals(1, textReader.getTotalParallelism(), 0 /*tolerance*/); - file.delete(); - } - - @Test - public void testParallelismEstimatesPartialRead() throws IOException { - File file = - createFileWithCompressionType(fileContent, "test.txt", CompressionType.UNCOMPRESSED); - TextReader textReader = - new TextReader<>( - file.getPath(), - true /*stripTrailingNewlines*/, - 10L /*startPos*/, - 17L /*endPos*/, - new WholeLineVerifyingCoder(), - CompressionType.AUTO); - assertEquals(7, textReader.getTotalParallelism(), 0 /*tolerance*/); - file.delete(); - } - - @Test - public void testParallelismEstimatesCompressedGlob() throws IOException { - File gzip = createFileWithCompressionType(fileContent, "test.gz", CompressionType.GZIP); - File bzip = createFileWithCompressionType(fileContent, "test.bz2", CompressionType.BZIP2); - String pattern = new File(tmpFolder.getRoot(), "*").getPath(); - TextReader textReader = - new TextReader<>( - pattern, true, null, null, new WholeLineVerifyingCoder(), CompressionType.AUTO); - assertEquals(2, textReader.getTotalParallelism(), 0 /*tolerance*/); - gzip.delete(); - bzip.delete(); - } - - @Test - public void testParallelismEstimatesMixedGlob() throws IOException { - File gzip = createFileWithCompressionType(fileContent, "test.gz", CompressionType.GZIP); - File txt = createFileWithCompressionType(fileContent, "test.txt", CompressionType.UNCOMPRESSED); - String pattern = new File(tmpFolder.getRoot(), "*").getPath(); - TextReader textReader = - new TextReader<>( - pattern, true, null, null, new WholeLineVerifyingCoder(), CompressionType.AUTO); - assertEquals(Double.POSITIVE_INFINITY, textReader.getTotalParallelism(), 0 /*tolerance*/); - gzip.delete(); - txt.delete(); - } - - @Test - public void testErrorOnFileNotFound() throws Exception { - expectedException.expect(FileNotFoundException.class); - TextReader textReader = new TextReader<>( - "file-not-found", true, 0L, 100L, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - textReader.iterator().close(); - } - - @Test - public void testErrorOnMultipleFiles() throws Exception { - File file1 = tmpFolder.newFile("foo1.avro"); - File file2 = tmpFolder.newFile("foo2.avro"); - Channels.newOutputStream(IOChannelUtils.create(file1.getPath(), MimeTypes.BINARY)).close(); - Channels.newOutputStream(IOChannelUtils.create(file2.getPath(), MimeTypes.BINARY)).close(); - TextReader textReader = new TextReader<>( - new File(tmpFolder.getRoot(), "*").getPath(), true, 0L, 100L, - new WholeLineVerifyingCoder(), TextIO.CompressionType.UNCOMPRESSED); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("more than 1 file matched"); - textReader.iterator().close(); - } - - // TODO: sharded filenames - // TODO: reading from GCS -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactoryTest.java deleted file mode 100644 index 5ed168adc8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactoryTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import javax.annotation.Nullable; - -/** - * Tests for TextSinkFactory. - */ -@RunWith(JUnit4.class) -public class TextSinkFactoryTest { - void runTestCreateTextSink(String filename, - @Nullable Boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - CloudObject encoding, - Coder coder) - throws Exception { - CloudObject spec = CloudObject.forClassName("TextSink"); - addString(spec, PropertyNames.FILENAME, filename); - if (appendTrailingNewlines != null) { - addBoolean(spec, PropertyNames.APPEND_TRAILING_NEWLINES, appendTrailingNewlines); - } - if (header != null) { - addString(spec, PropertyNames.HEADER, header); - } - if (footer != null) { - addString(spec, PropertyNames.FOOTER, footer); - } - - com.google.api.services.dataflow.model.Sink cloudSink = - new com.google.api.services.dataflow.model.Sink(); - cloudSink.setSpec(spec); - cloudSink.setCodec(encoding); - - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - PipelineOptions options = PipelineOptionsFactory.create(); - Sink sink = SinkFactory.create( - options, - cloudSink, - BatchModeExecutionContext.fromOptions(options), - addCounterMutator); - Assert.assertThat(sink, new IsInstanceOf(TextSink.class)); - TextSink textSink = (TextSink) sink; - Assert.assertEquals(filename, textSink.namePrefix); - Assert.assertEquals( - appendTrailingNewlines == null ? true : appendTrailingNewlines, - textSink.appendTrailingNewlines); - Assert.assertEquals(header, textSink.header); - Assert.assertEquals(footer, textSink.footer); - Assert.assertEquals(coder, textSink.coder); - } - - @Test - public void testCreatePlainTextSink() throws Exception { - runTestCreateTextSink( - "/path/to/file.txt", null, null, null, - makeCloudEncoding("StringUtf8Coder"), - StringUtf8Coder.of()); - } - - @Test - public void testCreateRichTextSink() throws Exception { - runTestCreateTextSink( - "gs://bucket/path/to/file2.txt", false, "$$$", "***", - makeCloudEncoding("TextualIntegerCoder"), - TextualIntegerCoder.of()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkTest.java deleted file mode 100644 index 51228f678e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkTest.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.ShardingWritableByteChannel; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Tests for TextSink. - */ -@RunWith(JUnit4.class) -public class TextSinkTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - void runTestWriteFile(List elems, - @Nullable String header, - @Nullable String footer, - Coder coder) throws Exception { - File tmpFile = tmpFolder.newFile("file.txt"); - TextSink> textSink = TextSink.createForTest( - tmpFile.getPath(), true, header, footer, coder); - List expected = new ArrayList<>(); - List actualSizes = new ArrayList<>(); - if (header != null) { - expected.add(header); - } - try (Sink.SinkWriter> writer = textSink.writer()) { - for (T elem : elems) { - actualSizes.add((int) writer.add(WindowedValue.valueInGlobalWindow(elem))); - byte[] encodedElem = CoderUtils.encodeToByteArray(coder, elem); - String line = new String(encodedElem); - expected.add(line); - } - } - if (footer != null) { - expected.add(footer); - } - - List actual = new ArrayList<>(); - List expectedSizes = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader(new FileReader(tmpFile))) { - for (;;) { - String line = reader.readLine(); - if (line == null) { - break; - } - actual.add(line); - expectedSizes.add(line.length() + TextSink.NEWLINE.length); - } - } - if (header != null) { - expectedSizes.remove(0); - } - if (footer != null) { - expectedSizes.remove(expectedSizes.size() - 1); - } - - Assert.assertEquals(expected, actual); - Assert.assertEquals(expectedSizes, actualSizes); - } - - @Test - public void testWriteEmptyFile() throws Exception { - runTestWriteFile(Collections.emptyList(), null, null, - StringUtf8Coder.of()); - } - - @Test - public void testWriteEmptyFileWithHeaderAndFooter() throws Exception { - runTestWriteFile(Collections.emptyList(), "the head", "the foot", - StringUtf8Coder.of()); - } - - @Test - public void testWriteNonEmptyFile() throws Exception { - List lines = Arrays.asList( - "", - " hi there ", - "bob", - "", - " ", - "--zowie!--", - ""); - runTestWriteFile(lines, null, null, StringUtf8Coder.of()); - } - - @Test - public void testWriteNonEmptyFileWithHeaderAndFooter() throws Exception { - List lines = Arrays.asList( - "", - " hi there ", - "bob", - "", - " ", - "--zowie!--", - ""); - runTestWriteFile(lines, "the head", "the foot", StringUtf8Coder.of()); - } - - @Test - public void testWriteNonEmptyNonStringFile() throws Exception { - runTestWriteFile(TestUtils.INTS, null, null, TextualIntegerCoder.of()); - } - - - private static class ThrowingWritableByteChannel extends ShardingWritableByteChannel { - IOException exception = null; - boolean open = true; - @Override - public boolean isOpen() { - return open; - } - - @Override - public void close() throws IOException { - open = false; - } - - @Override - public int write(ByteBuffer src) throws IOException { - if (exception != null) { - throw exception; - } - return src.remaining(); - } - - @Override - public int writeToShard(int shardNum, ByteBuffer src) throws IOException { - if (exception != null) { - throw exception; - } - return src.remaining(); - } - } - - @Test - public void testWriteFileWithFooterThatThrowsException() throws Exception { - ThrowingWritableByteChannel channel = new ThrowingWritableByteChannel(); - TextSink> sink = - TextSink.createForTest("test-location", false, null, "test-footer", StringUtf8Coder.of()); - TextSink>.TextFileWriter writer = sink.new TextFileWriter(channel); - channel.exception = new IOException("Test throwing exception during close"); - try { - writer.close(); - fail(); - } catch (IOException e) { - assertSame(e, channel.exception); - assertFalse(channel.isOpen()); - } - } - - @Test - public void testWriteShardedFileWithFooterThatThrowsException() throws Exception { - ThrowingWritableByteChannel channel = new ThrowingWritableByteChannel(); - TextSink> sink = - TextSink.createForTest("test-location", false, null, "test-footer", StringUtf8Coder.of()); - TextSink>.ShardingTextFileWriter writer = - sink.new ShardingTextFileWriter(channel); - channel.exception = new IOException("Test throwing exception during close"); - try { - writer.close(); - fail(); - } catch (IOException e) { - assertSame(e, channel.exception); - assertFalse(channel.isOpen()); - } - } - - // TODO: sharded filenames - // TODO: not appending newlines -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java deleted file mode 100644 index 657ed050d5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Tests for UngroupedShuffleReader. - */ -@RunWith(JUnit4.class) -public class UngroupedShuffleReaderTest { - private static final Instant timestamp = new Instant(123000); - private static final IntervalWindow window = new IntervalWindow(timestamp, timestamp.plus(1000)); - - void runTestReadFromShuffle(List expected) throws Exception { - Coder> elemCoder = - WindowedValue.getFullCoder(BigEndianIntegerCoder.of(), IntervalWindow.getCoder()); - - CounterSet.AddCounterMutator addCounterMutator = - new CounterSet().getAddCounterMutator(); - // Write to shuffle with UNGROUPED ShuffleSink. - ShuffleSink shuffleSink = new ShuffleSink<>( - PipelineOptionsFactory.create(), - null, ShuffleSink.ShuffleKind.UNGROUPED, - elemCoder, - addCounterMutator); - - TestShuffleWriter shuffleWriter = new TestShuffleWriter(); - - List actualSizes = new ArrayList<>(); - try (Sink.SinkWriter> shuffleSinkWriter = - shuffleSink.writer(shuffleWriter, "dataset")) { - for (Integer value : expected) { - actualSizes.add(shuffleSinkWriter.add( - WindowedValue.of(value, timestamp, Lists.newArrayList(window), PaneInfo.NO_FIRING))); - } - } - List records = shuffleWriter.getRecords(); - Assert.assertEquals(expected.size(), records.size()); - Assert.assertEquals(shuffleWriter.getSizes(), actualSizes); - - // Read from shuffle with UngroupedShuffleReader. - UngroupedShuffleReader> ungroupedShuffleReader = - new UngroupedShuffleReader<>( - PipelineOptionsFactory.create(), - null, null, null, - elemCoder, addCounterMutator); - ExecutorTestUtils.TestReaderObserver observer = - new ExecutorTestUtils.TestReaderObserver(ungroupedShuffleReader); - - TestShuffleReader shuffleReader = new TestShuffleReader(); - List expectedSizes = new ArrayList<>(); - for (ShuffleEntry record : records) { - expectedSizes.add(record.length()); - shuffleReader.addEntry(record); - } - - List actual = new ArrayList<>(); - try (UngroupedShuffleReader>.UngroupedShuffleReaderIterator iter = - ungroupedShuffleReader.iterator(shuffleReader)) { - while (iter.hasNext()) { - Assert.assertTrue(iter.hasNext()); - Assert.assertTrue(iter.hasNext()); - WindowedValue elem = iter.next(); - Assert.assertEquals(timestamp, elem.getTimestamp()); - Assert.assertEquals(Lists.newArrayList(window), elem.getWindows()); - actual.add(elem.getValue()); - } - Assert.assertFalse(iter.hasNext()); - Assert.assertFalse(iter.hasNext()); - try { - iter.next(); - Assert.fail("should have failed"); - } catch (NoSuchElementException exn) { - // As expected. - } - } - - Assert.assertEquals(expected, actual); - Assert.assertEquals(expectedSizes, observer.getActualSizes()); - } - - @Test - public void testReadEmptyShuffleData() throws Exception { - runTestReadFromShuffle(TestUtils.NO_INTS); - } - - @Test - public void testReadNonEmptyShuffleData() throws Exception { - runTestReadFromShuffle(TestUtils.INTS); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTrackerTest.java deleted file mode 100644 index fa34e9a275..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTrackerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Test for {@link UserCodeTimeTracker}. - */ -@RunWith(JUnit4.class) -public class UserCodeTimeTrackerTest { - UserCodeTimeTracker getTracker(final int numProcessors) { - return new UserCodeTimeTracker() { - @Override - protected int getNumProcessors() { - return numProcessors; - } - }; - } - @Test - public void testUserFrameworkTimeDiscrimination() { - CounterSet counters = new CounterSet(); - UserCodeTimeTracker tracker = getTracker(1); - CounterSet.AddCounterMutator mutator = counters.getAddCounterMutator(); - tracker.workStarted("stage1-", 1, mutator); - tracker.workObservedInState(1, StateKind.USER, 100); - tracker.workObservedInState(1, StateKind.FRAMEWORK, 50); - tracker.workFinished(1); - - assertEquals(100L, counters.getExistingCounter("stage1-user-code-msecs").getAggregate()); - } - - @Test - public void testSaturated() { - CounterSet counters = new CounterSet(); - UserCodeTimeTracker tracker = getTracker(2); - CounterSet.AddCounterMutator mutator = counters.getAddCounterMutator(); - tracker.workStarted("stage1-", 1, mutator); - tracker.workStarted("stage2-", 2, mutator); - tracker.workObservedInState(1, StateKind.USER, 100); - tracker.workObservedInState(2, StateKind.USER, 50); - tracker.workFinished(1); - tracker.workFinished(2); - - assertEquals(100L, counters.getExistingCounter("stage1-user-code-msecs").getAggregate()); - assertEquals(50L, counters.getExistingCounter("stage2-user-code-msecs").getAggregate()); - } - - @Test - public void testOversubscribed() { - CounterSet counters = new CounterSet(); - UserCodeTimeTracker tracker = getTracker(1); - CounterSet.AddCounterMutator mutator = counters.getAddCounterMutator(); - tracker.workStarted("stage1-", 1, mutator); - tracker.workStarted("stage2-", 2, mutator); - // 1 user state work item. - tracker.workObservedInState(1, StateKind.USER, 10); - // 2 user state work items. - tracker.workObservedInState(2, StateKind.USER, 20); - // 2 user state work items. - tracker.workObservedInState(1, StateKind.USER, 30); - // 2 user state work items. - tracker.workObservedInState(2, StateKind.USER, 40); - // 1 user state work item. - tracker.workObservedInState(1, StateKind.FRAMEWORK, 99); - // 1 user state work items. - tracker.workObservedInState(2, StateKind.USER, 50); - // 2 user state work items. - tracker.workFinished(1); - // 1 user state work item. - tracker.workObservedInState(2, StateKind.USER, 60); - tracker.workFinished(2); - // 0 user state work item. - - // 10 + 30 / 2 = 25 - assertEquals(25L, counters.getExistingCounter("stage1-user-code-msecs").getAggregate()); - // 20 / 2 + 40 / 2 + 50 + 60 = 140 - assertEquals(140L, counters.getExistingCounter("stage2-user-code-msecs").getAggregate()); - } - - @Test - public void testScopedWork() throws Exception { - CounterSet counters = new CounterSet(); - UserCodeTimeTracker tracker = getTracker(1); - try (AutoCloseable scope1 = tracker.scopedWork("stage1-", 1, counters.getAddCounterMutator())) { - tracker.workObservedInState(1, StateKind.USER, 10); - try (AutoCloseable scope2 = tracker.scopedWork( - "stage2-", 2, counters.getAddCounterMutator())) { - tracker.workObservedInState(2, StateKind.USER, 30); - tracker.workObservedInState(1, StateKind.USER, 100); - } - } - - // 10 + 100 / 2 = 60 - assertEquals(60L, counters.getExistingCounter("stage1-user-code-msecs").getAggregate()); - // 30 / 2 = 15 - assertEquals(15L, counters.getExistingCounter("stage2-user-code-msecs").getAggregate()); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WeightedDirectSideInputReader.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WeightedDirectSideInputReader.java deleted file mode 100644 index 9667df2edd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WeightedDirectSideInputReader.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; -import com.google.cloud.dataflow.sdk.util.PTuple; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WeightedSideInputReader; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.util.HashMap; -import java.util.Map; - -/** - * A {@link WeightedSideInputReader} with explicitly provided sizes for all values. - */ -class WeightedDirectSideInputReader extends WeightedSideInputReader.Defaults { - - private final SideInputReader subReader; - private final Map, Long> weights; - - /** - * Returns a {@link WeightedDirectSideInputReader} containing the contents in the provided - * {@code Map}. A {@link DirectSideInputReader} will be used for the actual retrieval logic; this - * class merely does the size bookkeeping. - */ - public static WeightedDirectSideInputReader withContents( - Map, WeightedValue> sizedContents) { - return new WeightedDirectSideInputReader(sizedContents); - } - - private WeightedDirectSideInputReader( - Map, WeightedValue> sizedContents) { - weights = new HashMap<>(); - PTuple values = PTuple.empty(); - for (Map.Entry, WeightedValue> entry : sizedContents.entrySet()) { - values = values.and(entry.getKey(), entry.getValue().getValue()); - weights.put(entry.getKey(), entry.getValue().getWeight()); - } - subReader = DirectSideInputReader.of(values); - } - - @Override - public boolean isEmpty() { - return subReader.isEmpty(); - } - - @Override - public boolean contains(PCollectionView view) { - return subReader.contains(view); - } - - @Override - public WeightedValue getWeighted(PCollectionView view, BoundedWindow window) { - return WeightedValue.of( - subReader.get(view, window), - weights.get(view.getTagInternal())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java deleted file mode 100644 index 7c09fcc51d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBaseTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.protobuf.ByteString; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Tests for {@link WindmillReaderIteratorBase}. - */ -@RunWith(JUnit4.class) -public class WindmillReaderIteratorBaseTest { - private static class TestWindmillReaderIterator extends WindmillReaderIteratorBase { - protected TestWindmillReaderIterator(Windmill.WorkItem work) { - super(work); - } - - @Override - protected WindowedValue decodeMessage(Windmill.Message message) { - return WindowedValue.valueInGlobalWindow(message.getTimestamp()); - } - } - - @Test - public void testBasic() throws IOException { - testForMessageBundleCounts(); - testForMessageBundleCounts(0); - testForMessageBundleCounts(0, 0); - testForMessageBundleCounts(1); - testForMessageBundleCounts(2); - testForMessageBundleCounts(1, 1); - testForMessageBundleCounts(0, 1); - testForMessageBundleCounts(1, 0); - testForMessageBundleCounts(0, 0, 1, 3, 0, 1, 0, 0, 0, 1); - testForMessageBundleCounts(0, 0, 1, 3, 0, 1, 0, 0, 0, 0); - } - - private void testForMessageBundleCounts(int... messageBundleCounts) throws IOException { - List bundles = new ArrayList<>(); - long numTotalMessages = 0; - for (int count : messageBundleCounts) { - Windmill.InputMessageBundle.Builder bundle = - Windmill.InputMessageBundle.newBuilder().setSourceComputationId("foo"); - for (int i = 0; i < count; ++i) { - bundle.addMessages( - Windmill.Message.newBuilder() - .setTimestamp(numTotalMessages++) - .setData(ByteString.EMPTY) - .build()); - } - bundles.add(bundle.build()); - } - Windmill.WorkItem workItem = - Windmill.WorkItem.newBuilder() - .setKey(ByteString.EMPTY) - .setWorkToken(0L) - .addAllMessageBundles(bundles) - .build(); - try (TestWindmillReaderIterator iter = new TestWindmillReaderIterator(workItem)) { - List actual = - ReaderTestUtils.windowedValuesToValues( - ReaderUtils.readRemainingFromIterator(iter, false)); - assertFalse(iter.advance()); - List expected = new ArrayList<>(); - for (int i = 0; i < numTotalMessages; ++i) { - expected.add((long) i); - } - assertEquals(Arrays.toString(messageBundleCounts), expected, actual); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java deleted file mode 100644 index 6d2e8b5675..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCacheTest.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.protobuf.ByteString; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.Objects; - -/** - * Tests for {@link WindmillStateCache}. - */ -@RunWith(JUnit4.class) -public class WindmillStateCacheTest { - private static final String COMPUTATION = "computation"; - private static final ByteString KEY = ByteString.copyFromUtf8("key"); - private static final String STATE_FAMILY = "family"; - - private static class TestStateTag implements StateTag { - final String id; - - TestStateTag(String id) { - this.id = id; - } - - @Override - public void appendTo(Appendable appendable) throws IOException { - appendable.append(id); - } - - @Override - public String getId() { - return id; - } - - @Override - public TestState bind(StateBinder binder) { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() { - return "Tag(" + id + ")"; - } - - @Override - public boolean equals(Object other) { - return (other instanceof TestStateTag) && Objects.equals(((TestStateTag) other).id, id); - } - - @Override - public int hashCode() { - return Objects.hash(id); - } - } - - private static class TestState implements State { - String value = null; - - TestState(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public void clear() { - this.value = null; - } - - @Override - public boolean equals(Object other) { - return (other instanceof TestState) && Objects.equals(((TestState) other).value, value); - } - - @Override - public int hashCode() { - return Objects.hash(value); - } - - @Override - public String toString() { - return "State(" + value + ")"; - } - } - - private static StateNamespace windowNamespace(long start) { - return StateNamespaces.window( - IntervalWindow.getCoder(), new IntervalWindow(new Instant(start), new Instant(start + 1))); - } - - private static StateNamespace triggerNamespace(long start, int triggerIdx) { - return StateNamespaces.windowAndTrigger(IntervalWindow.getCoder(), - new IntervalWindow(new Instant(start), new Instant(start + 1)), triggerIdx); - } - - WindmillStateCache cache; - WindmillStateCache.ForKey keyCache; - - @Before - public void setUp() { - cache = new WindmillStateCache(); - keyCache = cache.forComputation(COMPUTATION).forKey(KEY, STATE_FAMILY, 0L); - assertEquals(0, cache.getWeight()); - } - - @Test - public void testBasic() throws Exception { - assertNull(keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); - assertNull(keyCache.get(windowNamespace(0), new TestStateTag("tag2"))); - assertNull(keyCache.get(triggerNamespace(0, 0), new TestStateTag("tag3"))); - assertNull(keyCache.get(triggerNamespace(0, 0), new TestStateTag("tag2"))); - - keyCache.put(StateNamespaces.global(), new TestStateTag("tag1"), new TestState("g1"), 2); - assertEquals(121, cache.getWeight()); - keyCache.put(windowNamespace(0), new TestStateTag("tag2"), new TestState("w2"), 2); - assertEquals(242, cache.getWeight()); - keyCache.put(triggerNamespace(0, 0), new TestStateTag("tag3"), new TestState("t3"), 2); - assertEquals(260, cache.getWeight()); - keyCache.put(triggerNamespace(0, 0), new TestStateTag("tag2"), new TestState("t2"), 2); - assertEquals(278, cache.getWeight()); - - assertEquals( - new TestState("g1"), keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); - assertEquals(new TestState("w2"), keyCache.get(windowNamespace(0), new TestStateTag("tag2"))); - assertEquals( - new TestState("t3"), keyCache.get(triggerNamespace(0, 0), new TestStateTag("tag3"))); - assertEquals( - new TestState("t2"), keyCache.get(triggerNamespace(0, 0), new TestStateTag("tag2"))); - } - - /** - * Verifies that values are cached in the appropriate namespaces. - */ - @Test - public void testInvalidation() throws Exception { - assertNull(keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); - keyCache.put(StateNamespaces.global(), new TestStateTag("tag1"), new TestState("g1"), 2); - assertEquals(121, cache.getWeight()); - assertEquals( - new TestState("g1"), keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); - - keyCache = cache.forComputation(COMPUTATION).forKey(KEY, STATE_FAMILY, 1L); - assertEquals(121, cache.getWeight()); - assertNull(keyCache.get(StateNamespaces.global(), new TestStateTag("tag1"))); - assertEquals(0, cache.getWeight()); - } - - /** - * Verifies that the cache is invalidated when the cache token changes. - */ - @Test - public void testEviction() throws Exception { - keyCache.put(windowNamespace(0), new TestStateTag("tag2"), new TestState("w2"), 2); - assertEquals(121, cache.getWeight()); - keyCache.put(triggerNamespace(0, 0), new TestStateTag("tag3"), new TestState("t3"), 2000000000); - assertEquals(0, cache.getWeight()); - // Eviction is atomic across the whole window. - assertNull(keyCache.get(windowNamespace(0), new TestStateTag("tag2"))); - assertNull(keyCache.get(triggerNamespace(0, 0), new TestStateTag("tag3"))); - } - - /** - * Verifies that caches are kept independently per-key. - */ - @Test - public void testMultipleKeys() throws Exception { - WindmillStateCache.ForKey keyCache1 = cache.forComputation("comp1").forKey( - ByteString.copyFromUtf8("key1"), STATE_FAMILY, 0L); - WindmillStateCache.ForKey keyCache2 = cache.forComputation("comp1").forKey( - ByteString.copyFromUtf8("key2"), STATE_FAMILY, 0L); - WindmillStateCache.ForKey keyCache3 = cache.forComputation("comp2").forKey( - ByteString.copyFromUtf8("key1"), STATE_FAMILY, 0L); - - keyCache1.put(StateNamespaces.global(), new TestStateTag("tag1"), new TestState("g1"), 2); - assertEquals( - new TestState("g1"), keyCache1.get(StateNamespaces.global(), new TestStateTag("tag1"))); - assertNull(keyCache2.get(StateNamespaces.global(), new TestStateTag("tag1"))); - assertNull(keyCache3.get(StateNamespaces.global(), new TestStateTag("tag1"))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java deleted file mode 100644 index a279b80acf..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternalsTest.java +++ /dev/null @@ -1,963 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.DataflowMatchers.ByteStringMatcher.byteStringEq; -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.TagList; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.TagValue; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; -import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaceForTest; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.ValueState; -import com.google.cloud.dataflow.sdk.util.state.WatermarkStateInternal; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.SettableFuture; -import com.google.protobuf.ByteString; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link WindmillStateInternals}. - */ -@RunWith(JUnit4.class) -public class WindmillStateInternalsTest { - private static final StateNamespace NAMESPACE = new StateNamespaceForTest("ns"); - private static final String STATE_FAMILY = "family"; - - private static final StateTag> COMBINING_ADDR = - StateTags.combiningValueFromInputInternal( - "combining", VarIntCoder.of(), new Sum.SumIntegerFn()); - private static final ByteString COMBINING_KEY = key(NAMESPACE, "combining"); - private final Coder accumCoder = - new Sum.SumIntegerFn().getAccumulatorCoder(null, VarIntCoder.of()); - - @Mock - private WindmillStateReader mockReader; - - private WindmillStateInternals underTest; - private WindmillStateCache cache; - - @Mock - private Supplier readStateSupplier; - - private static ByteString key(StateNamespace namespace, String addrId) { - return ByteString.copyFromUtf8(namespace.stringKey() + "+u" + addrId); - } - - private static ByteString systemKey(StateNamespace namespace, String addrId) { - return ByteString.copyFromUtf8(namespace.stringKey() + "+s" + addrId); - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - cache = new WindmillStateCache(); - underTest = new WindmillStateInternals(STATE_FAMILY, mockReader, - cache.forComputation("comp").forKey(ByteString.EMPTY, STATE_FAMILY, 17L), - readStateSupplier); - } - - private void waitAndSet(final SettableFuture future, final T value, final long millis) { - new Thread(new Runnable() { - @Override - public void run() { - try { - sleepMillis(millis); - } catch (InterruptedException e) { - throw new RuntimeException("Interrupted before setting", e); - } - future.set(value); - } - }).run(); - } - - private WindmillStateReader.WeightedList weightedList(String... elems) { - WindmillStateReader.WeightedList result = - new WindmillStateReader.WeightedList(new ArrayList(elems.length)); - for (String elem : elems) { - result.addWeighted(elem, elem.length()); - } - return result; - } - - @Test - public void testBagAddBeforeRead() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) - .thenReturn(future); - - StateContents> result = bag.get(); - - bag.add("hello"); - waitAndSet(future, Arrays.asList("world"), 200); - assertThat(result.read(), Matchers.containsInAnyOrder("hello", "world")); - - bag.add("goodbye"); - assertThat(result.read(), Matchers.containsInAnyOrder("hello", "world", "goodbye")); - } - - @Test - public void testBagClearBeforeRead() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - bag.clear(); - bag.add("hello"); - assertThat(bag.get().read(), Matchers.containsInAnyOrder("hello")); - - // Shouldn't need to read from windmill for this. - Mockito.verifyZeroInteractions(mockReader); - } - - @Test - public void testBagIsEmptyFalse() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) - .thenReturn(future); - StateContents result = bag.isEmpty(); - Mockito.verify(mockReader) - .listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); - - waitAndSet(future, Arrays.asList("world"), 200); - assertThat(result.read(), Matchers.is(false)); - } - - @Test - public void testBagIsEmptyTrue() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) - .thenReturn(future); - StateContents result = bag.isEmpty(); - Mockito.verify(mockReader) - .listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); - - waitAndSet(future, Arrays.asList(), 200); - assertThat(result.read(), Matchers.is(true)); - } - - @Test - public void testBagIsEmptyAfterClear() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - bag.clear(); - StateContents result = bag.isEmpty(); - Mockito.verify(mockReader, never()) - .listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); - assertThat(result.read(), Matchers.is(true)); - - bag.add("hello"); - assertThat(result.read(), Matchers.is(false)); - } - - @Test - public void testBagAddPersist() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - bag.add("hello"); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getListUpdatesCount()); - - TagList listUpdates = commitBuilder.getListUpdates(0); - assertEquals(key(NAMESPACE, "bag"), listUpdates.getTag()); - assertEquals(1, listUpdates.getValuesCount()); - assertEquals("hello", listUpdates.getValues(0).getData().substring(1).toStringUtf8()); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testBagClearPersist() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - bag.add("hello"); - bag.clear(); - bag.add("world"); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(2, commitBuilder.getListUpdatesCount()); - - TagList listClear = commitBuilder.getListUpdates(0); - assertEquals(key(NAMESPACE, "bag"), listClear.getTag()); - assertEquals(Long.MAX_VALUE, listClear.getEndTimestamp()); - assertEquals(0, listClear.getValuesCount()); - - TagList listUpdates = commitBuilder.getListUpdates(1); - assertEquals(key(NAMESPACE, "bag"), listUpdates.getTag()); - assertEquals(1, listUpdates.getValuesCount()); - assertEquals("world", listUpdates.getValues(0).getData().substring(1).toStringUtf8()); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testBagPersistEmpty() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - bag.clear(); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - // 1 list update = the clear - assertEquals(1, commitBuilder.getListUpdatesCount()); - } - - @Test - public void testCombiningAddBeforeRead() throws Exception { - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(COMBINING_KEY, STATE_FAMILY, accumCoder)) - .thenReturn(future); - - StateContents result = value.get(); - - value.add(5); - value.add(6); - waitAndSet(future, Arrays.asList(new int[] {8}, new int[] {10}), 200); - assertThat(result.read(), Matchers.equalTo(29)); - - // That get "compressed" the combiner. So, the underlying future should change: - future.set(Arrays.asList(new int[] {29})); - - value.add(2); - assertThat(result.read(), Matchers.equalTo(31)); - } - - @Test - public void testCombiningClearBeforeRead() throws Exception { - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - value.clear(); - - StateContents result = value.get(); - value.add(5); - value.add(6); - assertThat(result.read(), Matchers.equalTo(11)); - - value.add(2); - assertThat(result.read(), Matchers.equalTo(13)); - - // Shouldn't need to read from windmill for this because we immediately cleared.. - Mockito.verifyZeroInteractions(mockReader); - } - - @Test - public void testCombiningIsEmpty() throws Exception { - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(COMBINING_KEY, STATE_FAMILY, accumCoder)) - .thenReturn(future); - StateContents result = value.isEmpty(); - ArgumentCaptor byteString = ArgumentCaptor.forClass(ByteString.class); - Mockito.verify(mockReader).listFuture(byteString.capture(), eq(STATE_FAMILY), eq(accumCoder)); - assertThat(byteString.getValue(), byteStringEq(COMBINING_KEY)); - - waitAndSet(future, Arrays.asList(new int[] {29}), 200); - assertThat(result.read(), Matchers.is(false)); - } - - @Test - public void testCombiningIsEmptyAfterClear() throws Exception { - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - value.clear(); - StateContents result = value.isEmpty(); - Mockito.verify(mockReader, never()) - .listFuture(COMBINING_KEY, STATE_FAMILY, accumCoder); - assertThat(result.read(), Matchers.is(true)); - - value.add(87); - assertThat(result.read(), Matchers.is(false)); - } - - @Test - public void testCombiningAddPersist() throws Exception { - disableCompactOnWrite(); - - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - value.add(5); - value.add(6); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getListUpdatesCount()); - - TagList listUpdates = commitBuilder.getListUpdates(0); - assertEquals(COMBINING_KEY, listUpdates.getTag()); - assertEquals(1, listUpdates.getValuesCount()); - assertEquals( - 11, - CoderUtils.decodeFromByteArray( - accumCoder, listUpdates.getValues(0).getData().substring(1).toByteArray())[0]); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testCombiningAddPersistWithCompact() throws Exception { - forceCompactOnWrite(); - - Mockito.stub( - mockReader.listFuture( - org.mockito.Matchers.any(), - org.mockito.Matchers.any(), - org.mockito.Matchers.>any())) - .toReturn( - Futures.>immediateFuture( - ImmutableList.of(new int[] {40}, new int[] {60}))); - - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - value.add(5); - value.add(6); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(2, commitBuilder.getListUpdatesCount()); - assertEquals(0, commitBuilder.getListUpdates(0).getValuesCount()); - - TagList listUpdates = commitBuilder.getListUpdates(1); - assertEquals(COMBINING_KEY, listUpdates.getTag()); - assertEquals(1, listUpdates.getValuesCount()); - assertEquals( - 111, - CoderUtils.decodeFromByteArray( - accumCoder, listUpdates.getValues(0).getData().substring(1).toByteArray())[ - 0]); - } - - @Test - public void testCombiningClearPersist() throws Exception { - disableCompactOnWrite(); - - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - value.clear(); - value.add(5); - value.add(6); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(2, commitBuilder.getListUpdatesCount()); - - TagList listClear = commitBuilder.getListUpdates(0); - assertEquals(COMBINING_KEY, listClear.getTag()); - assertEquals(Long.MAX_VALUE, listClear.getEndTimestamp()); - assertEquals(0, listClear.getValuesCount()); - - TagList listUpdates = commitBuilder.getListUpdates(1); - assertEquals(COMBINING_KEY, listUpdates.getTag()); - assertEquals(1, listUpdates.getValuesCount()); - assertEquals( - 11, - CoderUtils.decodeFromByteArray( - accumCoder, listUpdates.getValues(0).getData().substring(1).toByteArray())[0]); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkAddBeforeReadEarliest() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - SettableFuture future = SettableFuture.create(); - when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); - - StateContents result = bag.get(); - - bag.add(new Instant(3000)); - waitAndSet(future, new Instant(2000), 200); - assertThat(result.read(), Matchers.equalTo(new Instant(2000))); - - Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockReader); - - // Adding another value doesn't create another future, but does update the result. - bag.add(new Instant(1000)); - assertThat(result.read(), Matchers.equalTo(new Instant(1000))); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkAddBeforeReadLatest() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtLatestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - SettableFuture future = SettableFuture.create(); - when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); - - StateContents result = bag.get(); - - bag.add(new Instant(3000)); - waitAndSet(future, new Instant(2000), 200); - assertThat(result.read(), Matchers.equalTo(new Instant(3000))); - - Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockReader); - - // Adding another value doesn't create another future, but does update the result. - bag.add(new Instant(3000)); - assertThat(result.read(), Matchers.equalTo(new Instant(3000))); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkAddBeforeReadEndOfWindow() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEndOfWindow()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - SettableFuture future = SettableFuture.create(); - when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); - - StateContents result = bag.get(); - - bag.add(new Instant(3000)); - waitAndSet(future, new Instant(3000), 200); - assertThat(result.read(), Matchers.equalTo(new Instant(3000))); - - Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockReader); - - // Adding another value doesn't create another future, but does update the result. - bag.add(new Instant(3000)); - assertThat(result.read(), Matchers.equalTo(new Instant(3000))); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkClearBeforeRead() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.clear(); - assertThat(bag.get().read(), Matchers.nullValue()); - - bag.add(new Instant(300)); - assertThat(bag.get().read(), Matchers.equalTo(new Instant(300))); - - // Shouldn't need to read from windmill because the value is already available. - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkPersistEarliest() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.add(new Instant(1000)); - bag.add(new Instant(2000)); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getWatermarkHoldsCount()); - - Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); - assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); - assertEquals(TimeUnit.MILLISECONDS.toMicros(1000), watermarkHold.getTimestamps(0)); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkPersistLatestEmpty() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtLatestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.add(new Instant(1000)); - bag.add(new Instant(2000)); - - when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)) - .thenReturn(Futures.immediateFuture(null)); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getWatermarkHoldsCount()); - - Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); - assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); - assertEquals(TimeUnit.MILLISECONDS.toMicros(2000), watermarkHold.getTimestamps(0)); - - Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkPersistLatestWindmillWins() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtLatestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.add(new Instant(1000)); - bag.add(new Instant(2000)); - - when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)) - .thenReturn(Futures.immediateFuture(new Instant(4000))); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getWatermarkHoldsCount()); - - Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); - assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); - assertEquals(TimeUnit.MILLISECONDS.toMicros(4000), watermarkHold.getTimestamps(0)); - - Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkPersistLatestLocalAdditionsWin() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtLatestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.add(new Instant(1000)); - bag.add(new Instant(2000)); - - when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)) - .thenReturn(Futures.immediateFuture(new Instant(500))); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getWatermarkHoldsCount()); - - Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); - assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); - assertEquals(TimeUnit.MILLISECONDS.toMicros(2000), watermarkHold.getTimestamps(0)); - - Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkPersistEndOfWindow() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEndOfWindow()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.add(new Instant(2000)); - bag.add(new Instant(2000)); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getWatermarkHoldsCount()); - - Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); - assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); - assertEquals(TimeUnit.MILLISECONDS.toMicros(2000), watermarkHold.getTimestamps(0)); - - // Blind adds should not need to read the future. - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkClearPersist() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.add(new Instant(500)); - bag.clear(); - bag.add(new Instant(1000)); - bag.add(new Instant(2000)); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getWatermarkHoldsCount()); - - Windmill.WatermarkHold clearAndUpdate = commitBuilder.getWatermarkHolds(0); - assertEquals(key(NAMESPACE, "watermark"), clearAndUpdate.getTag()); - assertEquals(1, clearAndUpdate.getTimestampsCount()); - assertEquals(TimeUnit.MILLISECONDS.toMicros(1000), clearAndUpdate.getTimestamps(0)); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testWatermarkPersistEmpty() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - bag.add(new Instant(500)); - bag.clear(); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - // 1 list update corresponds to deletion. There shouldn't be a list update adding items. - assertEquals(1, commitBuilder.getWatermarkHoldsCount()); - } - - @Test - public void testValueSetBeforeRead() throws Exception { - StateTag> addr = StateTags.value("value", StringUtf8Coder.of()); - ValueState value = underTest.state(NAMESPACE, addr); - - value.set("Hello"); - - assertEquals("Hello", value.get().read()); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testValueClearBeforeRead() throws Exception { - StateTag> addr = StateTags.value("value", StringUtf8Coder.of()); - ValueState value = underTest.state(NAMESPACE, addr); - - value.clear(); - - assertEquals(null, value.get().read()); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testValueRead() throws Exception { - StateTag> addr = StateTags.value("value", StringUtf8Coder.of()); - ValueState value = underTest.state(NAMESPACE, addr); - - SettableFuture future = SettableFuture.create(); - when(mockReader.valueFuture(key(NAMESPACE, "value"), STATE_FAMILY, StringUtf8Coder.of())) - .thenReturn(future); - waitAndSet(future, "World", 200); - - assertEquals("World", value.get().read()); - } - - @Test - public void testValueSetPersist() throws Exception { - StateTag> addr = StateTags.value("value", StringUtf8Coder.of()); - ValueState value = underTest.state(NAMESPACE, addr); - - value.set("Hi"); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getValueUpdatesCount()); - TagValue valueUpdate = commitBuilder.getValueUpdates(0); - assertEquals(key(NAMESPACE, "value"), valueUpdate.getTag()); - assertEquals("Hi", valueUpdate.getValue().getData().toStringUtf8()); - assertTrue(valueUpdate.isInitialized()); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testValueClearPersist() throws Exception { - StateTag> addr = StateTags.value("value", StringUtf8Coder.of()); - ValueState value = underTest.state(NAMESPACE, addr); - - value.set("Hi"); - value.clear(); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(1, commitBuilder.getValueUpdatesCount()); - TagValue valueUpdate = commitBuilder.getValueUpdates(0); - assertEquals(key(NAMESPACE, "value"), valueUpdate.getTag()); - assertEquals(0, valueUpdate.getValue().getData().size()); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testValueNoChangePersist() throws Exception { - StateTag> addr = StateTags.value("value", StringUtf8Coder.of()); - underTest.state(NAMESPACE, addr); - - Windmill.WorkItemCommitRequest.Builder commitBuilder = - Windmill.WorkItemCommitRequest.newBuilder(); - underTest.persist(commitBuilder); - - assertEquals(0, commitBuilder.getValueUpdatesCount()); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testCachedValue() throws Exception { - StateTag> addr = StateTags.value("value", StringUtf8Coder.of()); - ValueState value = underTest.state(NAMESPACE, addr); - - assertEquals(0, cache.getWeight()); - - value.set("Hi"); - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(118, cache.getWeight()); - - value = underTest.state(NAMESPACE, addr); - assertEquals("Hi", value.get().read()); - value.clear(); - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(116, cache.getWeight()); - - value = underTest.state(NAMESPACE, addr); - assertEquals(null, value.get().read()); - - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testCachedBag() throws Exception { - StateTag> addr = StateTags.bag("bag", StringUtf8Coder.of()); - BagState bag = underTest.state(NAMESPACE, addr); - - assertEquals(0, cache.getWeight()); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) - .thenReturn(future); - - StateContents> result = bag.get(); - - assertEquals(0, cache.getWeight()); - - bag.add("hello"); - waitAndSet(future, weightedList("world"), 200); - assertThat(result.read(), Matchers.containsInAnyOrder("hello", "world")); - - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(126, cache.getWeight()); - - bag = underTest.state(NAMESPACE, addr); - bag.add("goodbye"); - assertThat(bag.get().read(), Matchers.containsInAnyOrder("hello", "world", "goodbye")); - bag.clear(); - bag.add("new"); - - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(119, cache.getWeight()); - - bag = underTest.state(NAMESPACE, addr); - bag.add("new2"); - assertThat(bag.get().read(), Matchers.containsInAnyOrder("new", "new2")); - bag.clear(); - bag.add("new3"); - - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(120, cache.getWeight()); - - bag = underTest.state(NAMESPACE, addr); - assertThat(bag.get().read(), Matchers.containsInAnyOrder("new3")); - - Mockito.verify(mockReader) - .listFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testCachedWatermarkHold() throws Exception { - StateTag addr = StateTags.watermarkStateInternal( - "watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal bag = underTest.state(NAMESPACE, addr); - - SettableFuture future = SettableFuture.create(); - when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); - - assertEquals(0, cache.getWeight()); - - StateContents result = bag.get(); - - bag.add(new Instant(3000)); - waitAndSet(future, new Instant(2000), 200); - assertThat(result.read(), Matchers.equalTo(new Instant(2000))); - - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(124, cache.getWeight()); - - bag = underTest.state(NAMESPACE, addr); - assertThat(bag.get().read(), Matchers.equalTo(new Instant(2000))); - bag.clear(); - - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(124, cache.getWeight()); - - bag = underTest.state(NAMESPACE, addr); - assertEquals(null, bag.get().read()); - - Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testCachedCombining() throws Exception { - CombiningValueState value = underTest.state(NAMESPACE, COMBINING_ADDR); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(key(NAMESPACE, "combining"), STATE_FAMILY, accumCoder)) - .thenReturn(future); - - assertEquals(0, cache.getWeight()); - - StateContents result = value.get(); - - value.add(1); - waitAndSet(future, Arrays.asList(new int[]{2}), 200); - assertThat(result.read(), Matchers.equalTo(3)); - - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(117, cache.getWeight()); - - value = underTest.state(NAMESPACE, COMBINING_ADDR); - assertThat(value.get().read(), Matchers.equalTo(3)); - value.add(3); - assertThat(value.get().read(), Matchers.equalTo(6)); - value.clear(); - - underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); - - assertEquals(116, cache.getWeight()); - - value = underTest.state(NAMESPACE, COMBINING_ADDR); - assertThat(value.get().read(), Matchers.equalTo(0)); - - Mockito.verify(mockReader) - .listFuture(key(NAMESPACE, "combining"), STATE_FAMILY, accumCoder); - Mockito.verifyNoMoreInteractions(mockReader); - } - - @Test - public void testSystemTags() throws Exception { - CombiningValueState value = - underTest.state(NAMESPACE, StateTags.makeSystemTagInternal(COMBINING_ADDR)); - - SettableFuture> future = SettableFuture.create(); - when(mockReader.listFuture(systemKey(NAMESPACE, "combining"), STATE_FAMILY, accumCoder)) - .thenReturn(future); - value.isEmpty(); // Ignore result, we just want to generate the future. - ArgumentCaptor byteString = ArgumentCaptor.forClass(ByteString.class); - Mockito.verify(mockReader).listFuture(byteString.capture(), eq(STATE_FAMILY), eq(accumCoder)); - assertThat(byteString.getValue(), byteStringEq(systemKey(NAMESPACE, "combining"))); - } - - private void disableCompactOnWrite() { - WindmillStateInternals.COMPACT_NOW.set( - new Supplier() { - @Override - public Boolean get() { - return false; - } - }); - } - - private void forceCompactOnWrite() { - WindmillStateInternals.COMPACT_NOW.set( - new Supplier() { - @Override - public Boolean get() { - return true; - } - }); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java deleted file mode 100644 index bef0877f44..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReaderTest.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.KeyedGetDataRequest; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.protobuf.ByteString; -import com.google.protobuf.ByteString.Output; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.util.concurrent.Future; - -/** - * Tests for {@link WindmillStateReader}. - */ -@RunWith(JUnit4.class) -public class WindmillStateReaderTest { - private static final VarIntCoder INT_CODER = VarIntCoder.of(); - - private static final String COMPUTATION = "computation"; - private static final ByteString DATA_KEY = ByteString.copyFromUtf8("DATA_KEY"); - private static final long WORK_TOKEN = 5043L; - private static final ByteString CONT_TOKEN = ByteString.copyFromUtf8("CONT_TOKEN"); - - private static final ByteString STATE_KEY_1 = ByteString.copyFromUtf8("key1"); - private static final ByteString STATE_KEY_2 = ByteString.copyFromUtf8("key2"); - private static final String STATE_FAMILY = "family"; - - @Mock - private MetricTrackingWindmillServerStub mockWindmill; - - private WindmillStateReader underTest; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - underTest = new WindmillStateReader(mockWindmill, COMPUTATION, DATA_KEY, WORK_TOKEN); - } - - private Windmill.Value intValue(int value, boolean padded) throws IOException { - Output output = ByteString.newOutput(); - - if (padded) { - byte[] zero = {0x0}; - output.write(zero); - } - INT_CODER.encode(value, output, Coder.Context.OUTER); - - return Windmill.Value.newBuilder() - .setData(output.toByteString()) - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp( - BoundedWindow.TIMESTAMP_MAX_VALUE)) - .build(); - } - - @Test - public void testReadList() throws Exception { - Future> future = underTest.listFuture(STATE_KEY_1, STATE_FAMILY, INT_CODER); - Mockito.verifyNoMoreInteractions(mockWindmill); - - Windmill.GetDataRequest.Builder expectedRequest = Windmill.GetDataRequest.newBuilder(); - expectedRequest.addRequestsBuilder() - .setComputationId(COMPUTATION) - .addRequestsBuilder() - .setKey(DATA_KEY) - .setWorkToken(WORK_TOKEN) - .addListsToFetch( - Windmill.TagList.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .setEndTimestamp(Long.MAX_VALUE) - .setFetchMaxBytes(WindmillStateReader.MAX_LIST_BYTES)); - - Windmill.GetDataResponse.Builder response = Windmill.GetDataResponse.newBuilder(); - response.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .addLists( - Windmill.TagList.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .addValues(intValue(5, true)) - .addValues(intValue(6, true))); - - Mockito.when(mockWindmill.getStateData(expectedRequest.build())).thenReturn(response.build()); - - Iterable results = future.get(); - Mockito.verify(mockWindmill).getStateData(expectedRequest.build()); - for (Integer unused : results) { - // Iterate over the results to force loading all the pages. - } - Mockito.verifyNoMoreInteractions(mockWindmill); - - assertThat(results, Matchers.contains(5, 6)); - } - - @Test - public void testReadListWithContinuations() throws Exception { - Future> future = underTest.listFuture(STATE_KEY_1, STATE_FAMILY, INT_CODER); - Mockito.verifyNoMoreInteractions(mockWindmill); - - Windmill.GetDataRequest.Builder expectedRequest1 = Windmill.GetDataRequest.newBuilder(); - expectedRequest1.addRequestsBuilder() - .setComputationId(COMPUTATION) - .addRequestsBuilder() - .setKey(DATA_KEY) - .setWorkToken(WORK_TOKEN) - .addListsToFetch( - Windmill.TagList.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .setEndTimestamp(Long.MAX_VALUE) - .setFetchMaxBytes(WindmillStateReader.MAX_LIST_BYTES)); - - Windmill.GetDataResponse.Builder response1 = Windmill.GetDataResponse.newBuilder(); - response1.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .addLists( - Windmill.TagList.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .setContinuationToken(CONT_TOKEN) - .addValues(intValue(5, true)) - .addValues(intValue(6, true))); - - Windmill.GetDataRequest.Builder expectedRequest2 = Windmill.GetDataRequest.newBuilder(); - expectedRequest2.addRequestsBuilder() - .setComputationId(COMPUTATION) - .addRequestsBuilder() - .setKey(DATA_KEY) - .setWorkToken(WORK_TOKEN) - .addListsToFetch( - Windmill.TagList.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .setEndTimestamp(Long.MAX_VALUE) - .setFetchMaxBytes(WindmillStateReader.MAX_LIST_BYTES) - .setRequestToken(CONT_TOKEN)); - - Windmill.GetDataResponse.Builder response2 = Windmill.GetDataResponse.newBuilder(); - response2.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .addLists( - Windmill.TagList.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .setRequestToken(CONT_TOKEN) - .addValues(intValue(7, true)) - .addValues(intValue(8, true))); - - Mockito.when(mockWindmill.getStateData(expectedRequest1.build())).thenReturn(response1.build()); - Mockito.when(mockWindmill.getStateData(expectedRequest2.build())).thenReturn(response2.build()); - - Iterable results = future.get(); - Mockito.verify(mockWindmill).getStateData(expectedRequest1.build()); - for (Integer unused : results) { - // Iterate over the results to force loading all the pages. - } - Mockito.verify(mockWindmill).getStateData(expectedRequest2.build()); - Mockito.verifyNoMoreInteractions(mockWindmill); - - assertThat(results, Matchers.contains(5, 6, 7, 8)); - } - - @Test - public void testReadValue() throws Exception { - Future future = underTest.valueFuture(STATE_KEY_1, STATE_FAMILY, INT_CODER); - Mockito.verifyNoMoreInteractions(mockWindmill); - - Windmill.GetDataRequest.Builder expectedRequest = Windmill.GetDataRequest.newBuilder(); - expectedRequest.addRequestsBuilder() - .setComputationId(COMPUTATION) - .addRequestsBuilder() - .setKey(DATA_KEY) - .setWorkToken(WORK_TOKEN) - .addValuesToFetch( - Windmill.TagValue.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .build()); - Windmill.GetDataResponse.Builder response = Windmill.GetDataResponse.newBuilder(); - response.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .addValues( - Windmill.TagValue.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .setValue(intValue(8, false))); - - Mockito.when(mockWindmill.getStateData(expectedRequest.build())).thenReturn(response.build()); - - Integer result = future.get(); - Mockito.verify(mockWindmill).getStateData(expectedRequest.build()); - Mockito.verifyNoMoreInteractions(mockWindmill); - - assertThat(result, Matchers.equalTo(8)); - } - - @Test - public void testReadWatermark() throws Exception { - Future future = underTest.watermarkFuture(STATE_KEY_1, STATE_FAMILY); - Mockito.verifyNoMoreInteractions(mockWindmill); - - Windmill.GetDataRequest.Builder expectedRequest = Windmill.GetDataRequest.newBuilder(); - expectedRequest.addRequestsBuilder() - .setComputationId(COMPUTATION) - .addRequestsBuilder() - .setKey(DATA_KEY) - .setWorkToken(WORK_TOKEN) - .addWatermarkHoldsToFetch( - Windmill.WatermarkHold.newBuilder().setTag(STATE_KEY_1).setStateFamily(STATE_FAMILY)); - - Windmill.GetDataResponse.Builder response = Windmill.GetDataResponse.newBuilder(); - response.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .addWatermarkHolds( - Windmill.WatermarkHold.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .addTimestamps(5000000) - .addTimestamps(6000000)); - - Mockito.when(mockWindmill.getStateData(expectedRequest.build())).thenReturn(response.build()); - - Instant result = future.get(); - Mockito.verify(mockWindmill).getStateData(expectedRequest.build()); - - assertThat(result, Matchers.equalTo(new Instant(5000))); - } - - @Test - public void testBatching() throws Exception { - // Reads two lists and verifies that we batch them up correctly. - Future watermarkFuture = underTest.watermarkFuture(STATE_KEY_2, STATE_FAMILY); - Future> listFuture = - underTest.listFuture(STATE_KEY_1, STATE_FAMILY, INT_CODER); - - Mockito.verifyNoMoreInteractions(mockWindmill); - - ArgumentCaptor request = - ArgumentCaptor.forClass(Windmill.GetDataRequest.class); - - Windmill.GetDataResponse.Builder response = Windmill.GetDataResponse.newBuilder(); - response.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .addWatermarkHolds( - Windmill.WatermarkHold.newBuilder() - .setTag(STATE_KEY_2) - .setStateFamily(STATE_FAMILY) - .addTimestamps(5000000) - .addTimestamps(6000000)) - .addLists( - Windmill.TagList.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily(STATE_FAMILY) - .addValues(intValue(5, true)) - .addValues(intValue(100, true))); - - Mockito.when(mockWindmill.getStateData(Mockito.isA(Windmill.GetDataRequest.class))) - .thenReturn(response.build()); - Instant result = watermarkFuture.get(); - Mockito.verify(mockWindmill).getStateData(request.capture()); - - // Verify the request looks right. - assertThat(request.getValue().getRequestsCount(), Matchers.equalTo(1)); - assertThat(request.getValue().getRequests(0).getComputationId(), Matchers.equalTo(COMPUTATION)); - assertThat(request.getValue().getRequests(0).getRequestsCount(), Matchers.equalTo(1)); - KeyedGetDataRequest keyedRequest = request.getValue().getRequests(0).getRequests(0); - assertThat(keyedRequest.getKey(), Matchers.equalTo(DATA_KEY)); - assertThat(keyedRequest.getWorkToken(), Matchers.equalTo(WORK_TOKEN)); - assertThat(keyedRequest.getListsToFetchCount(), Matchers.equalTo(1)); - assertThat(keyedRequest.getListsToFetch(0).getEndTimestamp(), Matchers.equalTo(Long.MAX_VALUE)); - assertThat(keyedRequest.getListsToFetch(0).getTag(), Matchers.equalTo(STATE_KEY_1)); - assertThat(keyedRequest.getWatermarkHoldsToFetchCount(), Matchers.equalTo(1)); - assertThat(keyedRequest.getWatermarkHoldsToFetch(0).getTag(), Matchers.equalTo(STATE_KEY_2)); - - // Verify the values returned to the user. - assertThat(result, Matchers.equalTo(new Instant(5000))); - Mockito.verifyNoMoreInteractions(mockWindmill); - - assertThat(listFuture.get(), Matchers.contains(5, 100)); - Mockito.verifyNoMoreInteractions(mockWindmill); - - // And verify that getting a future again returns the already completed future. - Future watermarkFuture2 = underTest.watermarkFuture(STATE_KEY_2, STATE_FAMILY); - assertTrue(watermarkFuture2.isDone()); - } - - @Test - public void testNoStateFamily() throws Exception { - Future future = underTest.valueFuture(STATE_KEY_1, "", INT_CODER); - Mockito.verifyNoMoreInteractions(mockWindmill); - - Windmill.GetDataRequest.Builder expectedRequest = Windmill.GetDataRequest.newBuilder(); - expectedRequest.addRequestsBuilder() - .setComputationId(COMPUTATION) - .addRequestsBuilder() - .setKey(DATA_KEY) - .setWorkToken(WORK_TOKEN) - .addValuesToFetch( - Windmill.TagValue.newBuilder().setTag(STATE_KEY_1).setStateFamily("").build()); - Windmill.GetDataResponse.Builder response = Windmill.GetDataResponse.newBuilder(); - response.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .addValues( - Windmill.TagValue.newBuilder() - .setTag(STATE_KEY_1) - .setStateFamily("") - .setValue(intValue(8, false))); - - Mockito.when(mockWindmill.getStateData(expectedRequest.build())).thenReturn(response.build()); - - Integer result = future.get(); - Mockito.verify(mockWindmill).getStateData(expectedRequest.build()); - Mockito.verifyNoMoreInteractions(mockWindmill); - - assertThat(result, Matchers.equalTo(8)); - } - - @Test - public void testKeyTokenInvalid() throws Exception { - // Reads two lists and verifies that we batch them up correctly. - Future watermarkFuture = underTest.watermarkFuture(STATE_KEY_2, STATE_FAMILY); - Future> listFuture = - underTest.listFuture(STATE_KEY_1, STATE_FAMILY, INT_CODER); - - Mockito.verifyNoMoreInteractions(mockWindmill); - - Windmill.GetDataResponse.Builder response = Windmill.GetDataResponse.newBuilder(); - response.addDataBuilder() - .setComputationId(COMPUTATION) - .addDataBuilder() - .setKey(DATA_KEY) - .setFailed(true); - - Mockito.when(mockWindmill.getStateData(Mockito.isA(Windmill.GetDataRequest.class))) - .thenReturn(response.build()); - - try { - watermarkFuture.get(); - fail("Expected KeyTokenInvalidException"); - } catch (Throwable e) { - assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(e)); - } - - try { - listFuture.get(); - fail("Expected KeyTokenInvalidException"); - } catch (Throwable e) { - assertTrue(KeyTokenInvalidException.isKeyTokenInvalidException(e)); - } - } - - /** - * Tests that multiple reads for the same tag in the same batch are cached. We can't compare - * the futures since we've wrapped the delegate aronud them, so we just verify there is only - * one queued lookup. - */ - @Test - public void testCachingWithinBatch() throws Exception { - underTest.watermarkFuture(STATE_KEY_1, STATE_FAMILY); - underTest.watermarkFuture(STATE_KEY_1, STATE_FAMILY); - assertEquals(1, underTest.pendingLookups.size()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java deleted file mode 100644 index 92d8a86b80..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSourcesTest.java +++ /dev/null @@ -1,749 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources.serializeToCloudSource; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtFraction; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.dictionaryToCloudSource; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.deserializeFromByteArray; -import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; -import static com.google.cloud.dataflow.sdk.util.Structs.getObject; -import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; -import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; -import static com.google.common.base.Throwables.getStackTraceAsString; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; - -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.api.services.dataflow.model.DerivedSource; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.SourceOperationResponse; -import com.google.api.services.dataflow.model.SourceSplitOptions; -import com.google.api.services.dataflow.model.SourceSplitRequest; -import com.google.api.services.dataflow.model.SourceSplitResponse; -import com.google.api.services.dataflow.model.Step; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.CountingSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; -import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Sample; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Preconditions; -import com.google.protobuf.ByteString; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * Tests for {@link WorkerCustomSources}. - */ -@RunWith(JUnit4.class) -public class WorkerCustomSourcesTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Rule public ExpectedLogs logged = ExpectedLogs.none(WorkerCustomSources.class); - - static class TestIO { - public static Read fromRange(int from, int to) { - return new Read(from, to, false); - } - - static class Read extends BoundedSource { - final int from; - final int to; - final boolean produceTimestamps; - - Read(int from, int to, boolean produceTimestamps) { - this.from = from; - this.to = to; - this.produceTimestamps = produceTimestamps; - } - - public Read withTimestampsMillis() { - return new Read(from, to, true); - } - - @Override - public List splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) - throws Exception { - List res = new ArrayList<>(); - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - float step = 1.0f * (to - from) / dataflowOptions.getNumWorkers(); - for (int i = 0; i < dataflowOptions.getNumWorkers(); ++i) { - res.add(new Read( - Math.round(from + i * step), Math.round(from + (i + 1) * step), - produceTimestamps)); - } - return res; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return 8 * (to - from); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return true; - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return new RangeReader(this); - } - - @Override - public void validate() {} - - @Override - public String toString() { - return "[" + from + ", " + to + ")"; - } - - @Override - public Coder getDefaultOutputCoder() { - return BigEndianIntegerCoder.of(); - } - - private static class RangeReader extends BoundedReader { - // To verify that BasicSerializableSourceFormat calls our methods according to protocol. - enum State { - UNSTARTED, - STARTED, - FINISHED - } - private Read source; - private int current = -1; - private State state = State.UNSTARTED; - - public RangeReader(Read source) { - this.source = source; - } - - @Override - public boolean start() throws IOException { - Preconditions.checkState(state == State.UNSTARTED); - state = State.STARTED; - current = source.from; - return (current < source.to); - } - - @Override - public boolean advance() throws IOException { - Preconditions.checkState(state == State.STARTED); - if (current == source.to - 1) { - state = State.FINISHED; - return false; - } - current++; - return true; - } - - @Override - public Integer getCurrent() { - Preconditions.checkState(state == State.STARTED); - return current; - } - - @Override - public Instant getCurrentTimestamp() { - return source.produceTimestamps - ? new Instant(current /* as millis */) : BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - @Override - public void close() throws IOException { - Preconditions.checkState(state == State.STARTED || state == State.FINISHED); - state = State.FINISHED; - } - - @Override - public Read getCurrentSource() { - return source; - } - - @Override - public Read splitAtFraction(double fraction) { - int proposedIndex = (int) (source.from + fraction * (source.to - source.from)); - if (proposedIndex <= current) { - return null; - } - Read primary = new Read(source.from, proposedIndex, source.produceTimestamps); - Read residual = new Read(proposedIndex, source.to, source.produceTimestamps); - this.source = primary; - return residual; - } - - @Override - public Double getFractionConsumed() { - return (current == -1) - ? 0.0 - : (1.0 * (1 + current - source.from) / (source.to - source.from)); - } - } - } - } - - @Test - public void testSplitAndReadBundlesBack() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setNumWorkers(5); - com.google.api.services.dataflow.model.Source source = - translateIOToCloudSource(TestIO.fromRange(10, 20), options); - List> elems = CloudSourceUtils.readElemsFromSource(options, source); - assertEquals(10, elems.size()); - for (int i = 0; i < 10; ++i) { - assertEquals(valueInGlobalWindow(10 + i), elems.get(i)); - } - SourceSplitResponse response = performSplit(source, options, null /*desiredBundleSizeBytes*/); - assertEquals("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED", response.getOutcome()); - List bundles = response.getBundles(); - assertEquals(5, bundles.size()); - for (int i = 0; i < 5; ++i) { - DerivedSource bundle = bundles.get(i); - assertEquals("SOURCE_DERIVATION_MODE_INDEPENDENT", bundle.getDerivationMode()); - com.google.api.services.dataflow.model.Source bundleSource = bundle.getSource(); - assertTrue(bundleSource.getDoesNotNeedSplitting()); - bundleSource.setCodec(source.getCodec()); - List> xs = CloudSourceUtils.readElemsFromSource(options, bundleSource); - assertThat(xs, contains(valueInGlobalWindow(10 + 2 * i), valueInGlobalWindow(11 + 2 * i))); - } - } - - @Test - public void testDirectPipelineWithoutTimestamps() throws Exception { - Pipeline p = TestPipeline.create(); - PCollection sum = p - .apply(Read.from(TestIO.fromRange(10, 20))) - .apply(Sum.integersGlobally()) - .apply(Sample.any(1)); - - DataflowAssert.thatSingleton(sum).isEqualTo(145); - p.run(); - } - - @Test - public void testDirectPipelineWithTimestamps() throws Exception { - Pipeline p = TestPipeline.create(); - PCollection sums = - p.apply(Read.from(TestIO.fromRange(10, 20).withTimestampsMillis())) - .apply(Window.into(FixedWindows.of(Duration.millis(3)))) - .apply(Sum.integersGlobally().withoutDefaults()); - // Should group into [10 11] [12 13 14] [15 16 17] [18 19]. - DataflowAssert.that(sums).containsInAnyOrder(21, 37, 39, 48); - p.run(); - } - - @Test - public void testRangeProgressAndSplitAtFraction() throws Exception { - // Show basic usage of getFractionConsumed and splitAtFraction. - // This test only tests TestIO itself, not BasicSerializableSourceFormat. - - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - TestIO.Read source = TestIO.fromRange(10, 20); - try (BoundedSource.BoundedReader reader = source.createReader(options)) { - assertEquals(0, reader.getFractionConsumed().intValue()); - assertTrue(reader.start()); - assertEquals(0.1, reader.getFractionConsumed(), 1e-6); - assertTrue(reader.advance()); - assertEquals(0.2, reader.getFractionConsumed(), 1e-6); - // Already past 0.0 and 0.1. - assertNull(reader.splitAtFraction(0.0)); - assertNull(reader.splitAtFraction(0.1)); - - { - TestIO.Read residual = (TestIO.Read) reader.splitAtFraction(0.5); - assertNotNull(residual); - TestIO.Read primary = (TestIO.Read) reader.getCurrentSource(); - assertThat(readFromSource(primary, options), contains(10, 11, 12, 13, 14)); - assertThat(readFromSource(residual, options), contains(15, 16, 17, 18, 19)); - } - - // Range is now [10, 15) and we are at 12. - { - TestIO.Read residual = (TestIO.Read) reader.splitAtFraction(0.8); // give up 14. - assertNotNull(residual); - TestIO.Read primary = (TestIO.Read) reader.getCurrentSource(); - assertThat(readFromSource(primary, options), contains(10, 11, 12, 13)); - assertThat(readFromSource(residual, options), contains(14)); - } - - assertTrue(reader.advance()); - assertEquals(12, reader.getCurrent().intValue()); - assertTrue(reader.advance()); - assertEquals(13, reader.getCurrent().intValue()); - assertFalse(reader.advance()); - } - } - - @Test - @SuppressWarnings("unchecked") - public void testProgressAndSourceSplitTranslation() throws Exception { - // Same as previous test, but now using BasicSerializableSourceFormat wrappers. - // We know that the underlying reader behaves correctly (because of the previous test), - // now check that we are wrapping it correctly. - DataflowPipelineOptions options = PipelineOptionsFactory.create() - .as(DataflowPipelineOptions.class); - NativeReader> reader = - (NativeReader>) - ReaderRegistry.defaultRegistry() - .create( - translateIOToCloudSource(TestIO.fromRange(10, 20), options), - options, - null, // executionContext - null, // addCounterMutator - null); // operationName - try (NativeReader.NativeReaderIterator> iterator = reader.iterator()) { - assertTrue(iterator.start()); - assertEquals( - 0.1, - readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), - 1e-6); - assertEquals(valueInGlobalWindow(10), iterator.getCurrent()); - assertEquals( - 0.1, - readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), - 1e-6); - assertTrue(iterator.advance()); - assertEquals(valueInGlobalWindow(11), iterator.getCurrent()); - assertEquals( - 0.2, - readerProgressToCloudProgress(iterator.getProgress()).getFractionConsumed().doubleValue(), - 1e-6); - assertTrue(iterator.advance()); - assertEquals(valueInGlobalWindow(12), iterator.getCurrent()); - - assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0))); - assertNull(iterator.requestDynamicSplit(splitRequestAtFraction(0.1f))); - WorkerCustomSources.BoundedSourceSplit sourceSplit = - (WorkerCustomSources.BoundedSourceSplit) - iterator.requestDynamicSplit(splitRequestAtFraction(0.5f)); - assertNotNull(sourceSplit); - assertThat(readFromSource(sourceSplit.primary, options), contains(10, 11, 12, 13, 14)); - assertThat(readFromSource(sourceSplit.residual, options), contains(15, 16, 17, 18, 19)); - - sourceSplit = - (WorkerCustomSources.BoundedSourceSplit) - iterator.requestDynamicSplit(splitRequestAtFraction(0.8f)); - assertNotNull(sourceSplit); - assertThat(readFromSource(sourceSplit.primary, options), contains(10, 11, 12, 13)); - assertThat(readFromSource(sourceSplit.residual, options), contains(14)); - - assertTrue(iterator.advance()); - assertEquals(valueInGlobalWindow(13), iterator.getCurrent()); - assertFalse(iterator.advance()); - } - } - - /** - * A source that cannot do anything. Intended to be overridden for testing of individual methods. - */ - private static class MockSource extends BoundedSource { - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - return Arrays.asList(this); - } - - @Override - public void validate() { } - - @Override - public boolean producesSortedKeys(PipelineOptions options) { - return false; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) { - throw new UnsupportedOperationException(); - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() { - return ""; - } - - @Override - public Coder getDefaultOutputCoder() { - return BigEndianIntegerCoder.of(); - } - } - - private static class SourceProducingInvalidSplits extends MockSource { - private String description; - private String errorMessage; - - private SourceProducingInvalidSplits(String description, String errorMessage) { - this.description = description; - this.errorMessage = errorMessage; - } - - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - Preconditions.checkState(errorMessage == null, "Unexpected invalid source"); - return Arrays.asList( - new SourceProducingInvalidSplits("goodBundle", null), - new SourceProducingInvalidSplits("badBundle", "intentionally invalid")); - } - - @Override - public void validate() { - Preconditions.checkState(errorMessage == null, errorMessage); - } - - @Override - public String toString() { - return description; - } - } - - @Test - public void testSplittingProducedInvalidSource() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - com.google.api.services.dataflow.model.Source cloudSource = - translateIOToCloudSource(new SourceProducingInvalidSplits("original", null), options); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - allOf( - containsString("Splitting a valid source produced an invalid source"), - containsString("original"), - containsString("badBundle"))); - expectedException.expectCause(hasMessage(containsString("intentionally invalid"))); - performSplit(cloudSource, options, null /*desiredBundleSizeBytes*/); - } - - private static class FailingReader extends BoundedSource.BoundedReader { - private BoundedSource source; - - private FailingReader(BoundedSource source) { - this.source = source; - } - - @Override - public BoundedSource getCurrentSource() { - return source; - } - - @Override - public boolean start() throws IOException { - throw new IOException("Intentional error"); - } - - @Override - public boolean advance() throws IOException { - throw new IllegalStateException("Should have failed in start()"); - } - - @Override - public Integer getCurrent() throws NoSuchElementException { - throw new IllegalStateException("Should have failed in start()"); - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - throw new IllegalStateException("Should have failed in start()"); - } - - @Override - public void close() throws IOException {} - - @Override - public Double getFractionConsumed() { - return null; - } - - @Override - public BoundedSource splitAtFraction(double fraction) { - return null; - } - } - - private static class SourceProducingFailingReader extends MockSource { - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return new FailingReader(this); - } - - @Override - public String toString() { - return "Some description"; - } - } - - @Test - public void testFailureToStartReadingIncludesSourceDetails() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - com.google.api.services.dataflow.model.Source source = - translateIOToCloudSource(new SourceProducingFailingReader(), options); - // Unfortunately Hamcrest doesn't have a matcher that can match on the exception's - // printStackTrace(), however we just want to verify that the error and source description - // would be contained in the exception *somewhere*, not necessarily in the top-level - // Exception object. So instead we use Throwables.getStackTraceAsString and match on that. - try { - CloudSourceUtils.readElemsFromSource(options, source); - fail("Expected to fail"); - } catch (Exception e) { - assertThat( - getStackTraceAsString(e), - allOf(containsString("Intentional error"), containsString("Some description"))); - } - } - - private static com.google.api.services.dataflow.model.Source translateIOToCloudSource( - BoundedSource io, DataflowPipelineOptions options) throws Exception { - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - Pipeline p = Pipeline.create(options); - p.begin().apply(Read.from(io)); - - Job workflow = translator.translate(p, new ArrayList()).getJob(); - Step step = workflow.getSteps().get(0); - - return stepToCloudSource(step); - } - - private static com.google.api.services.dataflow.model.Source stepToCloudSource(Step step) - throws Exception { - com.google.api.services.dataflow.model.Source res = dictionaryToCloudSource( - getDictionary(step.getProperties(), PropertyNames.SOURCE_STEP_INPUT)); - // Encoding is specified in the step, not in the source itself. This is - // normal: incoming Dataflow API Source objects in map tasks will have the - // encoding filled in from the step's output encoding. - @SuppressWarnings("unchecked") - List> outputInfo = - (List>) step.getProperties().get(PropertyNames.OUTPUT_INFO); - - CloudObject encoding = CloudObject.fromSpec(getObject(outputInfo.get(0), - PropertyNames.ENCODING)); - res.setCodec(encoding); - return res; - } - - private static SourceSplitResponse performSplit( - com.google.api.services.dataflow.model.Source source, - PipelineOptions options, - @Nullable Long desiredBundleSizeBytes) - throws Exception { - SourceSplitRequest splitRequest = new SourceSplitRequest(); - splitRequest.setSource(source); - if (desiredBundleSizeBytes != null) { - splitRequest.setOptions( - new SourceSplitOptions().setDesiredBundleSizeBytes(desiredBundleSizeBytes)); - } - SourceOperationResponse response = WorkerCustomSources.performSplit(splitRequest, options); - return response.getSplit(); - } - - @Test - public void testUnboundedSplits() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - com.google.api.services.dataflow.model.Source source = - serializeToCloudSource(new TestCountingSource(Integer.MAX_VALUE), options); - List serializedSplits = - getStrings(source.getSpec(), WorkerCustomSources.SERIALIZED_SOURCE_SPLITS, null); - assertEquals(20, serializedSplits.size()); - for (String serializedSplit : serializedSplits) { - assertTrue( - deserializeFromByteArray(decodeBase64(serializedSplit), "source") - instanceof TestCountingSource); - } - } - - @Test - public void testReadUnboundedReader() throws Exception { - StreamingModeExecutionContext context = new StreamingModeExecutionContext("stageName", - new ConcurrentHashMap(), /*stateNameMap=*/null, - /*stateCache=*/null); - - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setNumWorkers(5); - - ByteString state = ByteString.EMPTY; - for (int i = 0; i < 10 * WorkerCustomSources.MAX_UNBOUNDED_BUNDLE_SIZE; - /* Incremented in inner loop */) { - // Initialize streaming context with state from previous iteration. - context.start( - Windmill.WorkItem.newBuilder() - .setKey(ByteString.copyFromUtf8("0000000000000001")) // key is zero-padded index. - .setWorkToken(0) // Required proto field, unused. - .setSourceState( - Windmill.SourceState.newBuilder().setState(state).build()) // Source state. - .build(), - new Instant(0), // input watermark - null, // output watermark - null, // synchronized processing time - null, // StateReader - null, // StateFetcher - Windmill.WorkItemCommitRequest.newBuilder()); - - @SuppressWarnings({"unchecked", "rawtypes"}) - NativeReader>>> reader = - (NativeReader) - WorkerCustomSources.create( - (CloudObject) - serializeToCloudSource( - new TestCountingSource(Integer.MAX_VALUE), options) - .getSpec(), - options, - context); - - // Verify data. - Instant beforeReading = Instant.now(); - int numReadOnThisIteration = 0; - for (WindowedValue>> value : - ReaderUtils.readAllFromReader(reader)) { - assertEquals(KV.of(0, i), value.getValue().getValue()); - assertArrayEquals( - encodeToByteArray(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()), KV.of(0, i)), - value.getValue().getId()); - assertThat(value.getWindows(), contains((BoundedWindow) GlobalWindow.INSTANCE)); - assertEquals(i, value.getTimestamp().getMillis()); - i++; - numReadOnThisIteration++; - } - Instant afterReading = Instant.now(); - assertThat( - new Duration(beforeReading, afterReading).getStandardSeconds(), - lessThanOrEqualTo(WorkerCustomSources.MAX_UNBOUNDED_BUNDLE_READ_TIME.getStandardSeconds() - + 1)); - assertThat( - numReadOnThisIteration, lessThanOrEqualTo(WorkerCustomSources.MAX_UNBOUNDED_BUNDLE_SIZE)); - - // Extract and verify state modifications. - context.flushState(); - state = context.getOutputBuilder().getSourceStateUpdates().getState(); - // CountingSource's watermark is the last record + 1. i is now one past the last record, - // so the expected watermark is i millis. - assertEquals( - TimeUnit.MILLISECONDS.toMicros(i), context.getOutputBuilder().getSourceWatermark()); - assertEquals( - 1, - context - .getOutputBuilder() - .getSourceStateUpdates() - .getFinalizeIdsList() - .size()); - - assertNotNull(context.getCachedReader()); - - Windmill.Counter backlog = getCounter(context, "dataflow_backlog_size-stageName"); - assertEquals(7L, backlog.getIntScalar()); - assertTrue(backlog.getCumulative()); - assertEquals(Windmill.Counter.Kind.SUM, backlog.getKind()); - } - } - - private Windmill.Counter getCounter(StreamingModeExecutionContext context, String name) { - for (Windmill.Counter counter : context.getOutputBuilder().getCounterUpdatesList()) { - if (counter.getName().equals(name)) { - return counter; - } - } - return null; - } - - @Test - public void testLargeSerializedSizeResplits() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - // Figure out how many splits of CountingSource are needed to exceed the API limits, using an - // extra factor of 2 to ensure that we go over the limits. - BoundedSource justForSizing = CountingSource.upTo(1000000L); - long size = - DataflowApiUtils.computeSerializedSizeBytes( - translateIOToCloudSource(justForSizing, options)); - long numberToSplitToExceedLimit = - 2 * WorkerCustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES / size; - - // Generate a CountingSource and split it into the desired number of splits - // (desired size = 8 bytes, 1 long), triggering the re-split with a larger bundle size. - com.google.api.services.dataflow.model.Source source = - translateIOToCloudSource(CountingSource.upTo(numberToSplitToExceedLimit), options); - SourceSplitResponse split = performSplit(source, options, 8L); - logged.verifyWarn("too large for the Google Cloud Dataflow API"); - logged.verifyWarn(String.format("%d bundles", numberToSplitToExceedLimit)); - assertThat((long) split.getBundles().size(), lessThan(numberToSplitToExceedLimit)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReaderTest.java deleted file mode 100644 index 93c16e92b5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReaderTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.api.client.util.Lists.newArrayList; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.runners.worker.ByteArrayShufflePosition; -import com.google.cloud.dataflow.sdk.util.common.Reiterator; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** Unit tests for {@link BatchingShuffleEntryReader}. */ -@RunWith(JUnit4.class) -public final class BatchingShuffleEntryReaderTest { - private static final byte[] KEY = {0xA}; - private static final byte[] SKEY = {0xB}; - private static final byte[] VALUE = {0xC}; - private static final ShufflePosition START_POSITION = - ByteArrayShufflePosition.of("aaa".getBytes()); - private static final ShufflePosition END_POSITION = - ByteArrayShufflePosition.of("zzz".getBytes()); - private static final ShufflePosition NEXT_START_POSITION = - ByteArrayShufflePosition.of("next".getBytes()); - private static final ShufflePosition SECOND_NEXT_START_POSITION = - ByteArrayShufflePosition.of("next-second".getBytes()); - - @Mock private ShuffleBatchReader batchReader; - private ShuffleEntryReader reader; - - @Before - public void initMocksAndReader() { - MockitoAnnotations.initMocks(this); - reader = new BatchingShuffleEntryReader(batchReader); - } - - @Test - public void readerCanRead() throws Exception { - ShuffleEntry e1 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry e2 = new ShuffleEntry(KEY, SKEY, VALUE); - ArrayList entries = new ArrayList<>(); - entries.add(e1); - entries.add(e2); - when(batchReader.read(START_POSITION, END_POSITION)) - .thenReturn(new ShuffleBatchReader.Batch(entries, null)); - List results = newArrayList(reader.read(START_POSITION, END_POSITION)); - assertThat(results, contains(e1, e2)); - } - - @Test - public void readerIteratorCanBeCopied() throws Exception { - ShuffleEntry e1 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry e2 = new ShuffleEntry(KEY, SKEY, VALUE); - ArrayList entries = new ArrayList<>(); - entries.add(e1); - entries.add(e2); - when(batchReader.read(START_POSITION, END_POSITION)) - .thenReturn(new ShuffleBatchReader.Batch(entries, null)); - Reiterator it = reader.read(START_POSITION, END_POSITION); - assertThat(it.hasNext(), equalTo(Boolean.TRUE)); - assertThat(it.next(), equalTo(e1)); - Reiterator copy = it.copy(); - assertThat(it.hasNext(), equalTo(Boolean.TRUE)); - assertThat(it.next(), equalTo(e2)); - assertThat(it.hasNext(), equalTo(Boolean.FALSE)); - assertThat(copy.hasNext(), equalTo(Boolean.TRUE)); - assertThat(copy.next(), equalTo(e2)); - assertThat(copy.hasNext(), equalTo(Boolean.FALSE)); - } - - @Test - public void readerShouldMergeMultipleBatchResults() throws Exception { - ShuffleEntry e1 = new ShuffleEntry(KEY, SKEY, VALUE); - List e1s = Collections.singletonList(e1); - ShuffleEntry e2 = new ShuffleEntry(KEY, SKEY, VALUE); - List e2s = Collections.singletonList(e2); - when(batchReader.read(START_POSITION, END_POSITION)) - .thenReturn(new ShuffleBatchReader.Batch(e1s, NEXT_START_POSITION)); - when(batchReader.read(NEXT_START_POSITION, END_POSITION)) - .thenReturn(new ShuffleBatchReader.Batch(e2s, null)); - List results = newArrayList(reader.read(START_POSITION, END_POSITION)); - assertThat(results, contains(e1, e2)); - - verify(batchReader).read(START_POSITION, END_POSITION); - verify(batchReader).read(NEXT_START_POSITION, END_POSITION); - verifyNoMoreInteractions(batchReader); - } - - @Test - public void readerShouldMergeMultipleBatchResultsIncludingEmptyShards() - throws Exception { - List e1s = new ArrayList<>(); - List e2s = new ArrayList<>(); - ShuffleEntry e3 = new ShuffleEntry(KEY, SKEY, VALUE); - List e3s = Collections.singletonList(e3); - when(batchReader.read(START_POSITION, END_POSITION)) - .thenReturn(new ShuffleBatchReader.Batch(e1s, NEXT_START_POSITION)); - when(batchReader.read(NEXT_START_POSITION, END_POSITION)) - .thenReturn(new ShuffleBatchReader.Batch(e2s, SECOND_NEXT_START_POSITION)); - when(batchReader.read(SECOND_NEXT_START_POSITION, END_POSITION)) - .thenReturn(new ShuffleBatchReader.Batch(e3s, null)); - List results = newArrayList(reader.read(START_POSITION, END_POSITION)); - assertThat(results, contains(e3)); - - verify(batchReader).read(START_POSITION, END_POSITION); - verify(batchReader).read(NEXT_START_POSITION, END_POSITION); - verify(batchReader).read(SECOND_NEXT_START_POSITION, END_POSITION); - verifyNoMoreInteractions(batchReader); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReaderTest.java deleted file mode 100644 index afc8e38580..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReaderTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; - -/** Unit tests for {@link CachingShuffleBatchReader}. */ -@RunWith(JUnit4.class) -public final class CachingShuffleBatchReaderTest { - - private final ShuffleBatchReader.Batch testBatch = - new ShuffleBatchReader.Batch(new ArrayList(), null); - - @Test - public void readerShouldCacheReads() throws IOException { - ShuffleBatchReader base = mock(ShuffleBatchReader.class); - CachingShuffleBatchReader reader = new CachingShuffleBatchReader(base); - when(base.read(null, null)).thenReturn(testBatch); - // N.B. We need to capture the result of reader.read() in order to ensure - // that there's a strong reference to it, preventing it from being - // collected. Not that this should be an issue in tests, but it's good to - // be solid. - ShuffleBatchReader.Batch read = reader.read(null, null); - assertThat(read, equalTo(testBatch)); - assertThat(reader.read(null, null), equalTo(testBatch)); - assertThat(reader.read(null, null), equalTo(testBatch)); - assertThat(reader.read(null, null), equalTo(testBatch)); - assertThat(reader.read(null, null), equalTo(testBatch)); - verify(base, times(1)).read(null, null); - } - - @Test - public void readerShouldNotCacheExceptions() throws IOException { - ShuffleBatchReader base = mock(ShuffleBatchReader.class); - CachingShuffleBatchReader reader = new CachingShuffleBatchReader(base); - when(base.read(null, null)) - .thenThrow(new IOException("test")) - .thenReturn(testBatch); - try { - reader.read(null, null); - fail("expected an IOException"); - } catch (IOException e) { - // Nothing to do -- exception is expected. - } - assertThat(reader.read(null, null), equalTo(testBatch)); - verify(base, times(2)).read(null, null); - } - - @Test - public void readerShouldRereadClearedBatches() throws IOException { - ShuffleBatchReader base = mock(ShuffleBatchReader.class); - CachingShuffleBatchReader reader = new CachingShuffleBatchReader(base); - when(base.read(null, null)).thenReturn(testBatch); - ShuffleBatchReader.Batch read = reader.read(null, null); - assertThat(read, equalTo(testBatch)); - verify(base, times(1)).read(null, null); - CachingShuffleBatchReader.BatchRange range = - new CachingShuffleBatchReader.BatchRange(null, null); - CachingShuffleBatchReader.RangeReadReference ref = - reader.cache.get(range); - assertThat(ref, notNullValue()); - ref.clear(); - read = reader.read(null, null); - assertThat(read, equalTo(testBatch)); - verify(base, times(2)).read(null, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java deleted file mode 100644 index 18b703564a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ExecutorTestUtils.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.ElementByteSizeObservableCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.common.collect.ImmutableList; - -import org.junit.Assert; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Observable; -import java.util.Observer; - -/** - * Utilities for tests. - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class ExecutorTestUtils { - // Do not instantiate. - private ExecutorTestUtils() {} - - /** An Operation with a specified number of outputs. */ - public static class TestOperation extends Operation { - public TestOperation(int numOutputs) { - this(numOutputs, new CounterSet()); - } - - TestOperation(int numOutputs, CounterSet counters) { - this(numOutputs, counters, "test-"); - } - - TestOperation(int numOutputs, CounterSet counters, String counterPrefix) { - this(numOutputs, counterPrefix, counters.getAddCounterMutator(), - new StateSampler(counterPrefix, counters.getAddCounterMutator())); - } - - TestOperation(int numOutputs, String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) { - super("TestOperation", - createOutputReceivers(numOutputs, counterPrefix, addCounterMutator), - counterPrefix, addCounterMutator, stateSampler); - } - - private static OutputReceiver[] createOutputReceivers(int numOutputs, String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator) { - OutputReceiver[] receivers = new OutputReceiver[numOutputs]; - for (int i = 0; i < numOutputs; i++) { - receivers[i] = new TestOutputReceiver("out_" + i, - new ElementByteSizeObservableCoder(StringUtf8Coder.of()), addCounterMutator); - } - return receivers; - } - } - - - /** A {@code Reader} that yields a specified set of values. */ - public static class TestReader extends NativeReader { - private final List inputs; - - public TestReader(String... inputs) { - this.inputs = Arrays.asList(inputs); - } - - @Override - public NativeReaderIterator iterator() { - return new TestReaderIterator(inputs); - } - - class TestReaderIterator extends NativeReaderIterator { - private final List inputs; - private int currentIndex; - private boolean closed = false; - - public TestReaderIterator(List inputs) { - this.inputs = ImmutableList.copyOf(inputs); - } - - @Override - public boolean start() { - if (inputs.isEmpty()) { - return false; - } - notifyElementRead(getCurrent().length()); - return true; - } - - @Override - public boolean advance() throws IOException { - if (currentIndex >= inputs.size() - 1) { - return false; - } - ++currentIndex; - notifyElementRead(getCurrent().length()); - return true; - } - - @Override - public String getCurrent() throws NoSuchElementException { - return inputs.get(currentIndex); - } - - @Override - public void close() { - Assert.assertFalse(closed); - closed = true; - } - } - } - - /** - * An Observer that stores all sizes into an ArrayList, to compare - * against the gold standard during testing. - */ - public static class TestReaderObserver implements Observer { - private final List sizes; - - public TestReaderObserver(NativeReader reader) { - this(reader, new ArrayList()); - } - - public TestReaderObserver(NativeReader reader, List sizes) { - this.sizes = sizes; - reader.addObserver(this); - } - - @Override - public void update(Observable obs, Object obj) { - sizes.add((int) (long) obj); - } - - public List getActualSizes() { - return sizes; - } - } - - /** A {@code Sink} that allows the output elements to be retrieved. */ - public static class TestSink extends Sink { - List outputElems = new ArrayList<>(); - boolean closed = false; - - @Override - public SinkWriter writer() { - return new TestSinkWriter(); - } - - class TestSinkWriter implements SinkWriter { - @Override - public long add(String outputElem) { - outputElems.add(outputElem); - return outputElem.length(); - } - - @Override - public void close() { - Assert.assertFalse(closed); - closed = true; - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperationTest.java deleted file mode 100644 index 7586239d4f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getMeanByteCounterName; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getObjectCounterName; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for FlattenOperation. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("unchecked") -public class FlattenOperationTest { - @Test - public void testRunFlattenOperation() throws Exception { - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler( - counterPrefix, counterSet.getAddCounterMutator()); - TestOutputReceiver receiver = new TestOutputReceiver(counterSet); - - FlattenOperation flattenOperation = - new FlattenOperation(receiver, - counterPrefix, counterSet.getAddCounterMutator(), - stateSampler); - - flattenOperation.start(); - - flattenOperation.process("hi"); - flattenOperation.process("there"); - flattenOperation.process(""); - flattenOperation.process("bob"); - - flattenOperation.finish(); - - Assert.assertThat(receiver.outputElems, - CoreMatchers.hasItems("hi", "there", "", "bob")); - - Assert.assertEquals( - new CounterSet( - Counter.longs("test-FlattenOperation-start-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-FlattenOperation-start-msecs")).getAggregate()), - Counter.longs("test-FlattenOperation-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-FlattenOperation-process-msecs")).getAggregate()), - Counter.longs("test-FlattenOperation-finish-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-FlattenOperation-finish-msecs")).getAggregate()), - Counter.longs(getObjectCounterName("test_receiver_out"), SUM).resetToValue(4L), - Counter.longs(getMeanByteCounterName("test_receiver_out"), MEAN) - .resetMeanToValue(4, 10L)), - counterSet); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutorTest.java deleted file mode 100644 index 6a60e96a26..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutorTest.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.approximateProgressAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionFromSplitResult; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils.TestReader; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Tests for MapTaskExecutor. - */ -@RunWith(JUnit4.class) -public class MapTaskExecutorTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - static class TestOperation extends Operation { - String label; - List log; - - private static CounterSet counterSet = new CounterSet(); - private static String counterPrefix = "test-"; - private static StateSampler testStateSampler = - new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - - TestOperation(String label, List log) { - super(label, new OutputReceiver[] {}, counterPrefix, counterSet.getAddCounterMutator(), - testStateSampler); - this.label = label; - this.log = log; - } - - TestOperation(String outputName, String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler, - long outputCount) { - super(outputName, new OutputReceiver[] {}, counterPrefix, addCounterMutator, stateSampler); - addCounterMutator.addCounter( - Counter.longs(outputName + "-ElementCount", SUM).resetToValue(outputCount)); - } - - @Override - public void start() throws Exception { - super.start(); - log.add(label + " started"); - } - - @Override - public void finish() throws Exception { - log.add(label + " finished"); - super.finish(); - } - } - - // A mock ReadOperation fed to a MapTaskExecutor in test. - static class TestReadOperation extends ReadOperation { - private ApproximateReportedProgress progress = null; - - TestReadOperation(OutputReceiver outputReceiver, String counterPrefix, - AddCounterMutator addCounterMutator, StateSampler stateSampler) { - super("ReadOperation", new TestReader(), new OutputReceiver[]{outputReceiver}, - counterPrefix, "systemStageName", addCounterMutator, stateSampler); - } - - @Override - public NativeReader.Progress getProgress() { - return cloudProgressToReaderProgress(progress); - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest splitRequest) { - // Fakes the return with the same position as proposed. - return new NativeReader.DynamicSplitResultWithPosition( - cloudPositionToReaderPosition( - splitRequestToApproximateSplitRequest(splitRequest).getPosition())); - } - - public void setProgress(ApproximateReportedProgress progress) { - this.progress = progress; - } - } - - @Test - public void testExecuteMapTaskExecutor() throws Exception { - List log = new ArrayList<>(); - - List operations = Arrays.asList(new Operation[] { - new TestOperation("o1", log), new TestOperation("o2", log), new TestOperation("o3", log)}); - - CounterSet counters = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler(counterPrefix, counters.getAddCounterMutator()); - MapTaskExecutor executor = new MapTaskExecutor(operations, counters, stateSampler); - - executor.execute(); - - Assert.assertThat( - log, - CoreMatchers.hasItems( - "o3 started", "o2 started", "o1 started", "o1 finished", "o2 finished", "o3 finished")); - - executor.close(); - } - - @Test - @SuppressWarnings("unchecked") - public void testGetOutputCounters() throws Exception { - CounterSet counters = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler(counterPrefix, counters.getAddCounterMutator()); - List operations = Arrays.asList(new Operation[] { - new TestOperation("o1", counterPrefix, counters.getAddCounterMutator(), stateSampler, 1), - new TestOperation("o2", counterPrefix, counters.getAddCounterMutator(), stateSampler, 2), - new TestOperation("o3", counterPrefix, counters.getAddCounterMutator(), stateSampler, 3)}); - - MapTaskExecutor executor = new MapTaskExecutor(operations, counters, stateSampler); - - CounterSet counterSet = executor.getOutputCounters(); - Assert.assertEquals( - new CounterSet(Counter.longs("o1-ElementCount", SUM).resetToValue(1L), - Counter.longs("test-o1-start-msecs", SUM) - .resetToValue( - ((Counter) - counterSet.getExistingCounter("test-o1-start-msecs")).getAggregate()), - Counter.longs("test-o1-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-o1-process-msecs")).getAggregate()), - Counter.longs("test-o1-finish-msecs", SUM) - .resetToValue( - ((Counter) - counterSet.getExistingCounter("test-o1-finish-msecs")).getAggregate()), - Counter.longs("o2-ElementCount", SUM).resetToValue(2L), - Counter.longs("test-o2-start-msecs", SUM) - .resetToValue( - ((Counter) - counterSet.getExistingCounter("test-o2-start-msecs")).getAggregate()), - Counter.longs("test-o2-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-o2-process-msecs")).getAggregate()), - Counter.longs("test-o2-finish-msecs", SUM) - .resetToValue( - ((Counter) - counterSet.getExistingCounter("test-o2-finish-msecs")).getAggregate()), - Counter.longs("o3-ElementCount", SUM).resetToValue(3L), - Counter.longs("test-o3-start-msecs", SUM) - .resetToValue( - ((Counter) - counterSet.getExistingCounter("test-o3-start-msecs")).getAggregate()), - Counter.longs("test-o3-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-o3-process-msecs")).getAggregate()), - Counter.longs("test-o3-finish-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-o3-finish-msecs")).getAggregate())), - counterSet); - - executor.close(); - } - - @Test - public void testNoOperation() throws Exception { - // Test MapTaskExecutor without a single operation. - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - try (MapTaskExecutor executor = - new MapTaskExecutor(new ArrayList(), counterSet, stateSampler)) { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("has no operation"); - executor.getReadOperation(); - } - } - - @Test - public void testNoReadOperation() throws Exception { - // Test MapTaskExecutor without ReadOperation. - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - List operations = Arrays.asList( - new TestOperation("o1", counterPrefix, counterSet.getAddCounterMutator(), stateSampler, 1), - new TestOperation( - "o2", counterPrefix, counterSet.getAddCounterMutator(), stateSampler, 2)); - - try (MapTaskExecutor executor = new MapTaskExecutor(operations, counterSet, stateSampler)) { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("is not a ReadOperation"); - executor.getReadOperation(); - } - } - - @Test - public void testValidOperations() throws Exception { - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - TestOutputReceiver receiver = new TestOutputReceiver(counterSet); - List operations = Arrays.asList( - new TestReadOperation(receiver, counterPrefix, - counterSet.getAddCounterMutator(), stateSampler)); - try (MapTaskExecutor executor = new MapTaskExecutor(operations, counterSet, stateSampler)) { - Assert.assertEquals(operations.get(0), executor.getReadOperation()); - } - } - - @Test - public void testGetProgressAndRequestSplit() throws Exception { - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - TestOutputReceiver receiver = new TestOutputReceiver(counterSet); - TestReadOperation operation = new TestReadOperation( - receiver, counterPrefix, counterSet.getAddCounterMutator(), stateSampler); - MapTaskExecutor executor = - new MapTaskExecutor(Arrays.asList(new Operation[] {operation}), counterSet, stateSampler); - - operation.setProgress(approximateProgressAtIndex(1L)); - Assert.assertEquals(positionAtIndex(1L), positionFromProgress(executor.getWorkerProgress())); - Assert.assertEquals( - positionAtIndex(1L), - positionFromSplitResult(executor.requestDynamicSplit(splitRequestAtIndex(1L)))); - - executor.close(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounterTest.java deleted file mode 100644 index cd6b6e5084..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounterTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getMeanByteCounterName; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getObjectCounterName; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.ElementByteSizeObservableCoder; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; -import java.util.Random; - -/** - * Tests for {@link OutputObjectAndByteCounter}. - */ -@RunWith(JUnit4.class) -public class OutputObjectAndByteCounterTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - - @Test - public void testUpdate() throws Exception { - TestOutputCounter outputCounter = new TestOutputCounter(); - outputCounter.update("hi"); - outputCounter.finishLazyUpdate("hi"); - outputCounter.update("bob"); - outputCounter.finishLazyUpdate("bob"); - - CounterMean meanByteCount = outputCounter.getMeanByteCount().getMean(); - assertEquals(5, (long) meanByteCount.getAggregate()); - assertEquals(2, meanByteCount.getCount()); - } - - @Test - public void testIncorrectType() throws Exception { - TestOutputCounter outputCounter = new TestOutputCounter(); - thrown.expect(ClassCastException.class); - outputCounter.update(5); - } - - @Test - public void testNullArgument() throws Exception { - TestOutputCounter outputCounter = new TestOutputCounter(); - thrown.expect(CoderException.class); - outputCounter.update(null); - } - - @Test - public void testAddingCountersIntoCounterSet() throws Exception { - CounterSet counters = new CounterSet(); - new TestOutputCounter(counters); - - assertEquals( - new CounterSet( - Counter.longs(getMeanByteCounterName("output_name"), MEAN).resetMeanToValue(0, 0L), - Counter.longs(getObjectCounterName("output_name"), SUM).resetToValue(0L)), - counters); - } - - private OutputObjectAndByteCounter makeCounter(int samplingPeriod, int seed) { - return new OutputObjectAndByteCounter( - new ElementByteSizeObservableCoder<>(StringUtf8Coder.of()), - new CounterSet().getAddCounterMutator()) - .setSamplingPeriod(samplingPeriod) - .setRandom(new Random(seed)) - .countBytes("byte_count"); - } - - @Test - public void testSimpleByteCount() throws Exception { - OutputObjectAndByteCounter counter = makeCounter(1, 0); - for (int i = 0; i < 10000; i++) { - counter.update("foo"); - } - assertEquals(30000L, (long) counter.getByteCount().getAggregate()); - } - - @Test - public void testSamplingByteCountFewElements() throws Exception { - OutputObjectAndByteCounter counter = makeCounter(100, 0); - for (int i = 0; i < 10; i++) { - counter.update("foo"); - } - assertEquals(30L, (long) counter.getByteCount().getAggregate()); - } - - @Test - public void testSamplingByteCount() throws Exception { - List expected = Arrays.asList(3007230L, 2984989L, 3010540L); - for (int n = 0; n < 3; n++) { - OutputObjectAndByteCounter counter = makeCounter(100, n); - for (int i = 0; i < 1000000; i++) { - counter.update("foo"); - } - assertEquals(expected.get(n), counter.getByteCount().getAggregate()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiverTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiverTest.java deleted file mode 100644 index 77fe094606..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiverTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for OutputReceiver. - */ -@RunWith(JUnit4.class) -public class OutputReceiverTest { - - @Test - public void testEmptyOutputReceiver() throws Exception { - OutputReceiver fanOut = new OutputReceiver(); - TestOutputCounter outputCounter = new TestOutputCounter(); - fanOut.addOutputCounter(outputCounter); - fanOut.process("hi"); - fanOut.process("bob"); - - CounterMean meanByteCount = outputCounter.getMeanByteCount().getMean(); - Assert.assertEquals(5, (long) meanByteCount.getAggregate()); - Assert.assertEquals(2, meanByteCount.getCount()); - } - - @Test - public void testMultipleOutputReceiver() throws Exception { - OutputReceiver fanOut = new OutputReceiver(); - TestOutputCounter outputCounter = new TestOutputCounter(); - fanOut.addOutputCounter(outputCounter); - - CounterSet counters = new CounterSet(); - - TestOutputReceiver receiver1 = new TestOutputReceiver(counters); - fanOut.addOutput(receiver1); - - TestOutputReceiver receiver2 = new TestOutputReceiver(counters); - fanOut.addOutput(receiver2); - - fanOut.process("hi"); - fanOut.process("bob"); - - CounterMean meanByteCount = outputCounter.getMeanByteCount().getMean(); - Assert.assertEquals(5, meanByteCount.getAggregate().longValue()); - Assert.assertEquals(2, meanByteCount.getCount()); - Assert.assertThat(receiver1.outputElems, - CoreMatchers.hasItems("hi", "bob")); - Assert.assertThat(receiver2.outputElems, - CoreMatchers.hasItems("hi", "bob")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperationTest.java deleted file mode 100644 index 0bcf6c2b9d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperationTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getMeanByteCounterName; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getObjectCounterName; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for ParDoOperation. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("unchecked") -public class ParDoOperationTest { - private static class TestParDoFn implements ParDoFn { - final OutputReceiver outputReceiver; - - public TestParDoFn(OutputReceiver outputReceiver) { - this.outputReceiver = outputReceiver; - } - - @Override - public void startBundle(final Receiver... receivers) throws Exception { - if (receivers.length != 1) { - throw new AssertionError( - "unexpected number of receivers for DoFn"); - } - - outputReceiver.process("x-start"); - } - - @Override - public void processElement(Object elem) throws Exception { - outputReceiver.process("y-" + elem); - } - - @Override - public void finishBundle() throws Exception { - outputReceiver.process("z-finish"); - } - } - - @Test - public void testRunParDoOperation() throws Exception { - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler( - counterPrefix, counterSet.getAddCounterMutator()); - TestOutputReceiver receiver = new TestOutputReceiver(counterSet); - - ParDoOperation parDoOperation = - new ParDoOperation( - "ParDoOperation", - new TestParDoFn(receiver), - new OutputReceiver[]{ receiver }, - counterPrefix, - counterSet.getAddCounterMutator(), - stateSampler); - - parDoOperation.start(); - - parDoOperation.process("hi"); - parDoOperation.process("there"); - parDoOperation.process(""); - parDoOperation.process("bob"); - - parDoOperation.finish(); - - Assert.assertThat( - receiver.outputElems, - CoreMatchers.hasItems( - "x-start", "y-hi", "y-there", "y-", "y-bob", "z-finish")); - - Assert.assertEquals( - new CounterSet( - Counter.longs("test-ParDoOperation-start-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-ParDoOperation-start-msecs")).getAggregate()), - Counter.longs("test-ParDoOperation-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-ParDoOperation-process-msecs")).getAggregate()), - Counter.longs("test-ParDoOperation-finish-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-ParDoOperation-finish-msecs")).getAggregate()), - Counter.longs(getObjectCounterName("test_receiver_out"), SUM).resetToValue(6L), - Counter.longs(getMeanByteCounterName("test_receiver_out"), MEAN) - .resetMeanToValue(6, 33L)), - counterSet); - } - - // TODO: Test side inputs. - // TODO: Test side outputs. -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java deleted file mode 100644 index bf5bf9b541..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperationTest.java +++ /dev/null @@ -1,515 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getMeanByteCounterName; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getObjectCounterName; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.isIn; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.CoderSizeEstimator; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.ElementByteSizeObservableCoder; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.PairInfo; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.WindowingCoderGroupingKeyCreator; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.WindowsExpandingPairInfo; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.BufferingGroupingTable; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.Combiner; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.CombiningGroupingTable; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.GroupingKeyCreator; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.SamplingSizeEstimator; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.SizeEstimator; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Description; -import org.hamcrest.TypeSafeDiagnosingMatcher; -import org.hamcrest.collection.IsIterableContainingInAnyOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; -import java.util.Random; - -/** - * Tests for PartialGroupByKeyOperation. - */ -@RunWith(JUnit4.class) -@SuppressWarnings({"rawtypes", "unchecked"}) -public class PartialGroupByKeyOperationTest { - @Test - public void testRunPartialGroupByKeyOperation() throws Exception { - Coder keyCoder = StringUtf8Coder.of(); - Coder valueCoder = BigEndianIntegerCoder.of(); - - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler( - counterPrefix, counterSet.getAddCounterMutator()); - TestOutputReceiver receiver = - new TestOutputReceiver( - new ElementByteSizeObservableCoder( - WindowedValue.getValueOnlyCoder( - KvCoder.of(keyCoder, IterableCoder.of(valueCoder)))), - counterSet); - - PartialGroupByKeyOperation pgbkOperation = - new PartialGroupByKeyOperation( - new WindowingCoderGroupingKeyCreator(keyCoder), - new CoderSizeEstimator(WindowedValue.getValueOnlyCoder(keyCoder)), - new CoderSizeEstimator(valueCoder), - PairInfo.create(), - receiver, - counterPrefix, - counterSet.getAddCounterMutator(), - stateSampler); - - pgbkOperation.start(); - - pgbkOperation.process(WindowedValue.valueInEmptyWindows(KV.of("hi", 4))); - pgbkOperation.process(WindowedValue.valueInEmptyWindows(KV.of("there", 5))); - pgbkOperation.process(WindowedValue.valueInEmptyWindows(KV.of("hi", 6))); - pgbkOperation.process(WindowedValue.valueInEmptyWindows(KV.of("joe", 7))); - pgbkOperation.process(WindowedValue.valueInEmptyWindows(KV.of("there", 8))); - pgbkOperation.process(WindowedValue.valueInEmptyWindows(KV.of("hi", 9))); - - pgbkOperation.finish(); - - assertThat(receiver.outputElems, - IsIterableContainingInAnyOrder.containsInAnyOrder( - WindowedValue.valueInEmptyWindows(KV.of("hi", Arrays.asList(4, 6, 9))), - WindowedValue.valueInEmptyWindows(KV.of("there", Arrays.asList(5, 8))), - WindowedValue.valueInEmptyWindows(KV.of("joe", Arrays.asList(7))))); - - // Exact counter values depend on size of encoded data. If encoding - // changes, then these expected counters should change to match. - assertEquals( - new CounterSet( - Counter.longs("test-PartialGroupByKeyOperation-start-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-PartialGroupByKeyOperation-start-msecs")).getAggregate()), - Counter.longs("test-PartialGroupByKeyOperation-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-PartialGroupByKeyOperation-process-msecs")).getAggregate()), - Counter.longs("test-PartialGroupByKeyOperation-finish-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-PartialGroupByKeyOperation-finish-msecs")).getAggregate()), - Counter.longs(getObjectCounterName("test_receiver_out"), SUM).resetToValue(3L), - Counter.longs(getMeanByteCounterName("test_receiver_out"), MEAN) - .resetMeanToValue(3, 49L)), - counterSet); - } - - @Test - public void testRunPartialGroupByKeyOperationWithCombiner() throws Exception { - Coder keyCoder = StringUtf8Coder.of(); - Coder valueCoder = BigEndianIntegerCoder.of(); - - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler( - counterPrefix, counterSet.getAddCounterMutator()); - TestOutputReceiver receiver = new TestOutputReceiver( - new ElementByteSizeObservableCoder( - WindowedValue.getValueOnlyCoder(KvCoder.of(keyCoder, valueCoder))), - counterSet); - - Combiner, Integer, Integer, Integer> combineFn = - new Combiner, Integer, Integer, Integer>() { - - @Override - public Integer createAccumulator(WindowedValue key) { - return 0; - } - - @Override - public Integer add(WindowedValue key, Integer accumulator, Integer value) { - return accumulator + value; - } - - @Override - public Integer merge(WindowedValue key, Iterable accumulators) { - Integer sum = 0; - for (Integer part : accumulators) { - sum += part; - } - return sum; - } - - @Override - public Integer compact(WindowedValue key, Integer accumulator) { - return accumulator; - } - - @Override - public Integer extract(WindowedValue key, Integer accumulator) { - return accumulator; - } - }; - - PartialGroupByKeyOperation pgbkOperation = - new PartialGroupByKeyOperation( - new WindowingCoderGroupingKeyCreator(keyCoder), - new CoderSizeEstimator(WindowedValue.getValueOnlyCoder(keyCoder)), - new CoderSizeEstimator(valueCoder), - combineFn, - WindowsExpandingPairInfo.create(), - receiver, - counterPrefix, - counterSet.getAddCounterMutator(), - stateSampler); - - pgbkOperation.start(); - - pgbkOperation.process(WindowedValue.valueInGlobalWindow(KV.of("hi", 4))); - pgbkOperation.process(WindowedValue.valueInGlobalWindow(KV.of("there", 5))); - pgbkOperation.process(WindowedValue.valueInGlobalWindow(KV.of("hi", 6))); - pgbkOperation.process(WindowedValue.valueInGlobalWindow(KV.of("joe", 7))); - pgbkOperation.process(WindowedValue.valueInGlobalWindow(KV.of("there", 8))); - pgbkOperation.process(WindowedValue.valueInGlobalWindow(KV.of("hi", 9))); - - pgbkOperation.finish(); - - assertThat(receiver.outputElems, - IsIterableContainingInAnyOrder.containsInAnyOrder( - WindowedValue.valueInGlobalWindow(KV.of("hi", 19)), - WindowedValue.valueInGlobalWindow(KV.of("there", 13)), - WindowedValue.valueInGlobalWindow(KV.of("joe", 7)))); - - // Exact counter values depend on size of encoded data. If encoding - // changes, then these expected counters should change to match. - assertEquals( - new CounterSet( - Counter.longs("test-PartialGroupByKeyOperation-start-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-PartialGroupByKeyOperation-start-msecs")).getAggregate()), - Counter.longs("test-PartialGroupByKeyOperation-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-PartialGroupByKeyOperation-process-msecs")).getAggregate()), - Counter.longs("test-PartialGroupByKeyOperation-finish-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-PartialGroupByKeyOperation-finish-msecs")).getAggregate()), - Counter.longs(getObjectCounterName("test_receiver_out"), SUM).resetToValue(3L), - Counter.longs(getMeanByteCounterName("test_receiver_out"), MEAN) - .resetMeanToValue(3, 25L)), - counterSet); - } - - // TODO: Add tests about early flushing when the table fills. - - //////////////////////////////////////////////////////////////////////////// - // Tests for PartialGroupByKey internals. - - /** - * Return the key as its grouping key. - */ - public static class IdentityGroupingKeyCreator implements GroupingKeyCreator { - @Override - public Object createGroupingKey(Object key) { - return key; - } - } - - /** - * "Estimate" the size of longs by looking at their value. - */ - private static class IdentitySizeEstimator implements SizeEstimator { - public int calls = 0; - @Override - public long estimateSize(Long element) { - calls++; - return element; - } - } - - /** - * "Estimate" the size of strings by taking the tenth power of their length. - */ - private static class StringPowerSizeEstimator implements SizeEstimator { - @Override - public long estimateSize(String element) { - return (long) Math.pow(10, element.length()); - } - } - - private static class KvPairInfo implements PartialGroupByKeyOperation.PairInfo { - @Override - public Iterable getKeysFromInputPair(Object pair) { - return ImmutableList.of(((KV) pair).getKey()); - } - @Override - public Object getValueFromInputPair(Object pair) { - return ((KV) pair).getValue(); - } - @Override - public Object makeOutputPair(Object key, Object value) { - return KV.of(key, value); - } - } - - @Test - public void testBufferingGroupingTable() throws Exception { - BufferingGroupingTable table = - new BufferingGroupingTable<>( - 1000, new IdentityGroupingKeyCreator(), new KvPairInfo(), - new StringPowerSizeEstimator(), new StringPowerSizeEstimator()); - TestOutputReceiver receiver = new TestOutputReceiver( - KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of()))); - - table.put("A", "a", receiver); - table.put("B", "b1", receiver); - table.put("B", "b2", receiver); - table.put("C", "c", receiver); - assertThat(receiver.outputElems, empty()); - - table.put("C", "cccc", receiver); - assertThat(receiver.outputElems, - hasItem((Object) KV.of("C", Arrays.asList("c", "cccc")))); - - table.put("DDDD", "d", receiver); - assertThat(receiver.outputElems, - hasItem((Object) KV.of("DDDD", Arrays.asList("d")))); - - table.flush(receiver); - assertThat(receiver.outputElems, - IsIterableContainingInAnyOrder.containsInAnyOrder( - KV.of("A", Arrays.asList("a")), - KV.of("B", Arrays.asList("b1", "b2")), - KV.of("C", Arrays.asList("c", "cccc")), - KV.of("DDDD", Arrays.asList("d")))); - } - - @Test - public void testCombiningGroupingTable() throws Exception { - Combiner summingCombineFn = - new Combiner() { - - @Override - public Long createAccumulator(Object key) { - return 0L; - } - - @Override - public Long add(Object key, Long accumulator, Integer value) { - return accumulator + value; - } - - @Override - public Long merge(Object key, Iterable accumulators) { - long sum = 0; - for (Long part : accumulators) { - sum += part; - } - return sum; - } - - @Override - public Long compact(Object key, Long accumulator) { - return accumulator; - } - - @Override - public Long extract(Object key, Long accumulator) { - return accumulator; - } - }; - - CombiningGroupingTable table = - new CombiningGroupingTable( - 1000, new IdentityGroupingKeyCreator(), new KvPairInfo(), - summingCombineFn, - new StringPowerSizeEstimator(), new IdentitySizeEstimator()); - - TestOutputReceiver receiver = new TestOutputReceiver( - KvCoder.of(StringUtf8Coder.of(), BigEndianLongCoder.of())); - - table.put("A", 1, receiver); - table.put("B", 2, receiver); - table.put("B", 3, receiver); - table.put("C", 4, receiver); - assertThat(receiver.outputElems, empty()); - - table.put("C", 5000, receiver); - assertThat(receiver.outputElems, hasItem((Object) KV.of("C", 5004L))); - - table.put("DDDD", 6, receiver); - assertThat(receiver.outputElems, hasItem((Object) KV.of("DDDD", 6L))); - - table.flush(receiver); - assertThat(receiver.outputElems, - IsIterableContainingInAnyOrder.containsInAnyOrder( - KV.of("A", 1L), - KV.of("B", 2L + 3), - KV.of("C", 5000L + 4), - KV.of("DDDD", 6L))); - } - - - //////////////////////////////////////////////////////////////////////////// - // Tests for the sampling size estimator. - - @Test - public void testSampleFlatSizes() throws Exception { - IdentitySizeEstimator underlying = new IdentitySizeEstimator(); - SizeEstimator estimator = - new SamplingSizeEstimator(underlying, 0.05, 1.0, 10, new Random(1)); - // First 10 elements are always sampled. - for (int k = 0; k < 10; k++) { - assertEquals(100, estimator.estimateSize(100L)); - assertEquals(k + 1, underlying.calls); - } - // Next 10 are sometimes sampled. - for (int k = 10; k < 20; k++) { - assertEquals(100, estimator.estimateSize(100L)); - } - assertThat(underlying.calls, between(11, 19)); - int initialCalls = underlying.calls; - // Next 1000 are sampled at about 5%. - for (int k = 20; k < 1020; k++) { - assertEquals(100, estimator.estimateSize(100L)); - } - assertThat(underlying.calls - initialCalls, between(40, 60)); - } - - @Test - public void testSampleBoringSizes() throws Exception { - IdentitySizeEstimator underlying = new IdentitySizeEstimator(); - SizeEstimator estimator = - new SamplingSizeEstimator(underlying, 0.05, 1.0, 10, new Random(1)); - // First 10 elements are always sampled. - for (int k = 0; k < 10; k += 2) { - assertEquals(100, estimator.estimateSize(100L)); - assertEquals(102, estimator.estimateSize(102L)); - assertEquals(k + 2, underlying.calls); - } - // Next 10 are sometimes sampled. - for (int k = 10; k < 20; k += 2) { - assertThat(estimator.estimateSize(100L), between(100L, 102L)); - assertThat(estimator.estimateSize(102L), between(100L, 102L)); - } - assertThat(underlying.calls, between(11, 19)); - int initialCalls = underlying.calls; - // Next 1000 are sampled at about 5%. - for (int k = 20; k < 1020; k += 2) { - assertThat(estimator.estimateSize(100L), between(100L, 102L)); - assertThat(estimator.estimateSize(102L), between(100L, 102L)); - } - assertThat(underlying.calls - initialCalls, between(40, 60)); - } - - @Test - public void testSampleHighVarianceSizes() throws Exception { - // The largest element is much larger than the average. - List sizes = Arrays.asList(1L, 10L, 100L, 1000L); - IdentitySizeEstimator underlying = new IdentitySizeEstimator(); - SizeEstimator estimator = - new SamplingSizeEstimator(underlying, 0.1, 0.2, 10, new Random(1)); - // First 10 elements are always sampled. - for (int k = 0; k < 10; k++) { - long size = sizes.get(k % sizes.size()); - assertEquals(size, estimator.estimateSize(size)); - assertEquals(k + 1, underlying.calls); - } - // We're still not out of the woods; sample every element. - for (int k = 10; k < 20; k++) { - long size = sizes.get(k % sizes.size()); - assertEquals(size, estimator.estimateSize(size)); - assertEquals(k + 1, underlying.calls); - } - // Sample some more to let things settle down. - for (int k = 20; k < 500; k++) { - estimator.estimateSize(sizes.get(k % sizes.size())); - } - // Next 1000 are sampled at about 20% (maxSampleRate). - int initialCalls = underlying.calls; - for (int k = 500; k < 1500; k++) { - long size = sizes.get(k % sizes.size()); - assertThat(estimator.estimateSize(size), - anyOf(isIn(sizes), between(250L, 350L))); - } - assertThat(underlying.calls - initialCalls, between(180, 220)); - // Sample some more to let things settle down. - for (int k = 1500; k < 3000; k++) { - estimator.estimateSize(sizes.get(k % sizes.size())); - } - // Next 1000 are sampled at about 10% (minSampleRate). - initialCalls = underlying.calls; - for (int k = 3000; k < 4000; k++) { - long size = sizes.get(k % sizes.size()); - assertThat(estimator.estimateSize(size), - anyOf(isIn(sizes), between(250L, 350L))); - } - assertThat(underlying.calls - initialCalls, between(90, 110)); - } - - @Test - public void testSampleChangingSizes() throws Exception { - IdentitySizeEstimator underlying = new IdentitySizeEstimator(); - SizeEstimator estimator = - new SamplingSizeEstimator(underlying, 0.05, 1.0, 10, new Random(1)); - // First 10 elements are always sampled. - for (int k = 0; k < 10; k++) { - assertEquals(100, estimator.estimateSize(100L)); - assertEquals(k + 1, underlying.calls); - } - // Next 10 are sometimes sampled. - for (int k = 10; k < 20; k++) { - assertEquals(100, estimator.estimateSize(100L)); - } - assertThat(underlying.calls, between(11, 19)); - int initialCalls = underlying.calls; - // Next 1000 are sampled at about 5%. - for (int k = 20; k < 1020; k++) { - assertEquals(100, estimator.estimateSize(100L)); - } - assertThat(underlying.calls - initialCalls, between(40, 60)); - // Inject a big element until it is sampled. - while (estimator.estimateSize(1000000L) == 100) { } - // Check that we have started sampling more regularly again. - assertEquals(99, estimator.estimateSize(99L)); - } - - private static > TypeSafeDiagnosingMatcher - between(final T min, final T max) { - return new TypeSafeDiagnosingMatcher() { - @Override - public void describeTo(Description description) { - description.appendText("is between " + min + " and " + max); - } - @Override - protected boolean matchesSafely(T item, Description mismatchDescription) { - return min.compareTo(item) <= 0 && item.compareTo(max) <= 0; - } - }; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java deleted file mode 100644 index 7385199d5d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperationTest.java +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.positionAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.ReaderTestUtils.splitRequestAtIndex; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.readerProgressToCloudProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.toCloudPosition; -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getMeanByteCounterName; -import static com.google.cloud.dataflow.sdk.util.common.worker.TestOutputReceiver.TestOutputCounter.getObjectCounterName; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.Position; -import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ExecutorTestUtils.TestReader; -import com.google.common.base.Preconditions; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.NoSuchElementException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Exchanger; - -/** - * Tests for ReadOperation. - */ -@RunWith(JUnit4.class) -public class ReadOperationTest { - - private void assertCounterKindAndContents( - CounterSet counterSet, String name, AggregationKind kind, T contents) { - @SuppressWarnings("unchecked") - Counter counter = (Counter) counterSet.getExistingCounter(name); - assertThat(counter.getKind(), equalTo(kind)); - assertThat(counter.getAggregate(), equalTo(contents)); - } - - private void assertCounterMean( - CounterSet counterSet, String name, long count, T aggregate) { - @SuppressWarnings("unchecked") - Counter counter = (Counter) counterSet.getExistingCounter(name); - assertThat(counter.getKind(), equalTo(MEAN)); - assertThat(counter.getMean().getCount(), equalTo(count)); - assertThat(counter.getMean().getAggregate(), equalTo(aggregate)); - } - - private void assertCounterKind( - CounterSet counterSet, String name, AggregationKind kind) { - assertThat(counterSet.getExistingCounter(name).getKind(), equalTo(kind)); - } - - /** - * Tests that a {@link ReadOperation} has expected counters, and that their - * values are reasonable. - */ - @Test - @SuppressWarnings("unchecked") - public void testRunReadOperation() throws Exception { - TestReader reader = new TestReader("hi", "there", "", "bob"); - - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler(counterPrefix, counterSet.getAddCounterMutator()); - TestOutputReceiver receiver = new TestOutputReceiver(counterSet); - - ReadOperation readOperation = ReadOperation.forTest( - reader, receiver, counterPrefix, counterSet.getAddCounterMutator(), stateSampler); - - readOperation.start(); - readOperation.finish(); - - assertThat(receiver.outputElems, containsInAnyOrder((Object) "hi", "there", "", "bob")); - - assertCounterKindAndContents(counterSet, "ReadOperation-ByteCount", SUM, 2L + 5 + 0 + 3); - assertCounterKindAndContents(counterSet, getObjectCounterName("test_receiver_out"), SUM, 4L); - assertCounterMean(counterSet, getMeanByteCounterName("test_receiver_out"), 4, 10L); - assertCounterKind(counterSet, "test-ReadOperation-start-msecs", SUM); - assertCounterKind(counterSet, "test-ReadOperation-process-msecs", SUM); - assertCounterKind(counterSet, "test-ReadOperation-finish-msecs", SUM); - } - - @Test - public void testGetProgress() throws Exception { - MockReaderIterator iterator = new MockReaderIterator(0, 5); - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - final ReadOperation readOperation = ReadOperation.forTest(new MockReader(iterator), - new TestOutputReceiver("out", null, counterSet), counterPrefix, - counterSet.getAddCounterMutator(), - new StateSampler(counterPrefix, counterSet.getAddCounterMutator())); - // Update progress not continuously, but so that it's never more than 1 record stale. - readOperation.setProgressUpdatePeriodMs(150); - - Thread thread = runReadLoopInThread(readOperation); - for (int i = 0; i < 5; ++i) { - sleepMillis(500); // Wait for the operation to start and block. - // Ensure that getProgress() doesn't block while the next() method is blocked. - ApproximateReportedProgress progress = readerProgressToCloudProgress( - readOperation.getProgress()); - long observedIndex = progress.getPosition().getRecordIndex().longValue(); - assertTrue("Actual: " + observedIndex, i == observedIndex || i == observedIndex + 1); - iterator.offerNext(i); - } - thread.join(); - } - - @Test - public void testDynamicSplit() throws Exception { - MockReaderIterator iterator = new MockReaderIterator(0, 10); - CounterSet counterSet = new CounterSet(); - MockOutputReceiver receiver = new MockOutputReceiver(); - ReadOperation readOperation = ReadOperation.forTest(new MockReader(iterator), receiver, "test-", - counterSet.getAddCounterMutator(), - new StateSampler("test-", counterSet.getAddCounterMutator())); - readOperation.setProgressUpdatePeriodMs(ReadOperation.UPDATE_ON_EACH_ITERATION); - - // An unstarted ReadOperation refuses split requests. - assertNull( - readOperation.requestDynamicSplit(splitRequestAtIndex(8L))); - - Thread thread = runReadLoopInThread(readOperation); - iterator.offerNext(0); // Await start() and return 0 from getCurrent(). - receiver.unblockProcess(); - // Await advance() and return 1 from getCurrent(). - iterator.offerNext(1); - NativeReader.DynamicSplitResultWithPosition split = - (NativeReader.DynamicSplitResultWithPosition) - readOperation.requestDynamicSplit(splitRequestAtIndex(8L)); - assertNotNull(split); - assertEquals(positionAtIndex(8L), toCloudPosition(split.getAcceptedPosition())); - - // Check that the progress has been recomputed. - ApproximateReportedProgress progress = readerProgressToCloudProgress( - readOperation.getProgress()); - assertEquals(1, progress.getPosition().getRecordIndex().longValue()); - assertEquals(2.0f / 8.0, progress.getFractionConsumed(), 0.001); - - receiver.unblockProcess(); - iterator.offerNext(2); - receiver.unblockProcess(); - iterator.offerNext(3); - - // Should accept a split at an earlier position than previously requested. - // Should reject a split at a later position than previously requested. - // Note that here we're testing our own MockReaderIterator class, so it's kind of pointless, - // but we're also testing that ReadOperation correctly relays the request to the iterator. - split = - (NativeReader.DynamicSplitResultWithPosition) - readOperation.requestDynamicSplit(splitRequestAtIndex(6L)); - assertNotNull(split); - assertEquals(positionAtIndex(6L), toCloudPosition(split.getAcceptedPosition())); - split = - (NativeReader.DynamicSplitResultWithPosition) - readOperation.requestDynamicSplit(splitRequestAtIndex(6L)); - assertNull(split); - receiver.unblockProcess(); - - iterator.offerNext(4); - receiver.unblockProcess(); - iterator.offerNext(5); - receiver.unblockProcess(); - - // Should return false from hasNext() and exit read loop now. - - thread.join(); - - // Operation is now finished. Check that it refuses a split request. - assertNull(readOperation.requestDynamicSplit(splitRequestAtIndex(5L))); - } - - @Test - public void testDynamicSplitDoesNotBlock() throws Exception { - MockReaderIterator iterator = new MockReaderIterator(0, 10); - CounterSet counterSet = new CounterSet(); - MockOutputReceiver receiver = new MockOutputReceiver(); - ReadOperation readOperation = ReadOperation.forTest(new MockReader(iterator), receiver, "test-", - counterSet.getAddCounterMutator(), - new StateSampler("test-", counterSet.getAddCounterMutator())); - - Thread thread = runReadLoopInThread(readOperation); - iterator.offerNext(0); - receiver.unblockProcess(); - // Read loop is blocked in next(). Do not offer another next item, - // but check that we can still split while the read loop is blocked. - NativeReader.DynamicSplitResultWithPosition split = - (NativeReader.DynamicSplitResultWithPosition) - readOperation.requestDynamicSplit(splitRequestAtIndex(5L)); - assertNotNull(split); - assertEquals(positionAtIndex(5L), toCloudPosition(split.getAcceptedPosition())); - - for (int i = 1; i < 5; ++i) { - iterator.offerNext(i); - receiver.unblockProcess(); - } - - thread.join(); - } - - @Test - public void testRaceBetweenCloseAndDynamicSplit() throws Exception { - MockReaderIterator iterator = new MockReaderIterator(0, 10); - CounterSet counterSet = new CounterSet(); - MockOutputReceiver receiver = new MockOutputReceiver(); - final ReadOperation readOperation = ReadOperation.forTest( - new MockReader(iterator), receiver, "test-", - counterSet.getAddCounterMutator(), - new StateSampler("test-", counterSet.getAddCounterMutator())); - - // We simulate the following sequence: - // "Reader thread" calls ReadOperation.start() and returns from it - // "Main thread" calls requestDynamicSplit() - // "Reader thread" calls ReadOperation.finish() - // We use CountDownLatch as synchronization barriers to establish this sequence. - final CountDownLatch startCompleted = new CountDownLatch(1); - final CountDownLatch requestDynamicSplitCompleted = new CountDownLatch(1); - Thread thread = - new Thread() { - @Override - public void run() { - try { - readOperation.start(); - // Synchronize with main test thread to notify it that .start() has finished, - // meaning the ReadOperation has finished reading. - startCompleted.countDown(); - // Synchronize with main test thread to wait until requestDynamicSplit() - // has completed. - requestDynamicSplitCompleted.await(); - // Now finish the ReadOperation. - readOperation.finish(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - thread.start(); - - for (int i = 0; i < 10; ++i) { - iterator.offerNext(i); - receiver.unblockProcess(); - } - // Synchronize with reader thread to wait until ReadOperation.start() finishes. - startCompleted.await(); - // Check that requestDynamicSplit is safe (no-op) if the operation is done with start() - // but not yet done with finish() - readOperation.requestDynamicSplit(splitRequestAtIndex(5L)); - // Synchronize with reader thread to notify it that we're done calling requestDynamicSplit(). - requestDynamicSplitCompleted.countDown(); - - // Let the reader thread complete (it just calls finish()). - thread.join(); - - // Check once more that requestDynamicSplit on a finished operation is also safe (no-op). - readOperation.requestDynamicSplit(splitRequestAtIndex(5L)); - } - - private Thread runReadLoopInThread(final ReadOperation readOperation) { - Thread thread = new Thread() { - @Override - public void run() { - try { - readOperation.start(); - readOperation.finish(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - thread.start(); - return thread; - } - - private static class MockReaderIterator extends NativeReader.NativeReaderIterator { - private final OffsetRangeTracker tracker; - private Exchanger exchanger = new Exchanger<>(); - private int current; - private volatile boolean isClosed; - - public MockReaderIterator(int from, int to) { - this.tracker = new OffsetRangeTracker(from, to); - this.current = from - 1; - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - if (!tracker.tryReturnRecordAt(true, current + 1)) { - return false; - } - ++current; - exchangeCurrent(); - return true; - } - - private void exchangeCurrent() { - try { - current = exchanger.exchange(current); - } catch (InterruptedException e) { - throw new NoSuchElementException("interrupted"); - } - } - - @Override - public Integer getCurrent() { - return current; - } - - @Override - public NativeReader.Progress getProgress() { - Preconditions.checkState(!isClosed); - return cloudProgressToReaderProgress( - new ApproximateReportedProgress() - .setPosition(new Position().setRecordIndex((long) current)) - .setFractionConsumed(tracker.getFractionConsumed())); - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest splitRequest) { - Preconditions.checkState(!isClosed); - ApproximateSplitRequest approximateSplitRequest = splitRequestToApproximateSplitRequest( - splitRequest); - int index = approximateSplitRequest.getPosition().getRecordIndex().intValue(); - if (!tracker.trySplitAtPosition(index)) { - return null; - } - return new NativeReader.DynamicSplitResultWithPosition( - cloudPositionToReaderPosition(approximateSplitRequest.getPosition())); - } - - public int offerNext(int next) { - try { - return exchanger.exchange(next); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - - @Override - public void close() throws IOException { - isClosed = true; - } - } - - private static class MockReader extends NativeReader { - private NativeReaderIterator iterator; - - private MockReader(NativeReaderIterator iterator) { - this.iterator = iterator; - } - - @Override - public NativeReaderIterator iterator() throws IOException { - return iterator; - } - } - - /** - * A mock {@link OutputReceiver} that blocks the read loop in {@link ReadOperation}. - */ - private static class MockOutputReceiver extends OutputReceiver { - private Exchanger exchanger = new Exchanger<>(); - - @Override - public void process(Object elem) throws Exception { - exchanger.exchange(null); - } - - public void unblockProcess() { - try { - exchanger.exchange(null); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryTest.java deleted file mode 100644 index 6b7e0e9d1f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link ShuffleEntry}. */ -@RunWith(JUnit4.class) -public class ShuffleEntryTest { - private static final byte[] KEY = {0xA}; - private static final byte[] SKEY = {0xB}; - private static final byte[] VALUE = {0xC}; - - @Test - public void accessors() { - ShuffleEntry entry = new ShuffleEntry(KEY, SKEY, VALUE); - assertThat(entry.getKey(), equalTo(KEY)); - assertThat(entry.getSecondaryKey(), equalTo(SKEY)); - assertThat(entry.getValue(), equalTo(VALUE)); - } - - @Test - public void equalsToItself() { - ShuffleEntry entry = new ShuffleEntry(KEY, SKEY, VALUE); - assertTrue(entry.equals(entry)); - } - - @Test - public void equalsForEqualEntries() { - ShuffleEntry entry0 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry entry1 = new ShuffleEntry( - KEY.clone(), SKEY.clone(), VALUE.clone()); - - assertTrue(entry0.equals(entry1)); - assertTrue(entry1.equals(entry0)); - assertEquals(entry0.hashCode(), entry1.hashCode()); - } - - @Test - public void equalsForEqualNullEntries() { - ShuffleEntry entry0 = new ShuffleEntry(null, null, null); - ShuffleEntry entry1 = new ShuffleEntry(null, null, null); - - assertTrue(entry0.equals(entry1)); - assertTrue(entry1.equals(entry0)); - assertEquals(entry0.hashCode(), entry1.hashCode()); - } - - @Test - public void notEqualsWhenKeysDiffer() { - final byte[] otherKey = {0x1}; - ShuffleEntry entry0 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry entry1 = new ShuffleEntry(otherKey, SKEY, VALUE); - - assertFalse(entry0.equals(entry1)); - assertFalse(entry1.equals(entry0)); - assertThat(entry0.hashCode(), not(equalTo(entry1.hashCode()))); - } - - @Test - public void notEqualsWhenKeysDifferOneNull() { - ShuffleEntry entry0 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry entry1 = new ShuffleEntry(null, SKEY, VALUE); - - assertFalse(entry0.equals(entry1)); - assertFalse(entry1.equals(entry0)); - assertThat(entry0.hashCode(), not(equalTo(entry1.hashCode()))); - } - - @Test - public void notEqualsWhenSecondaryKeysDiffer() { - final byte[] otherSKey = {0x2}; - ShuffleEntry entry0 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry entry1 = new ShuffleEntry(KEY, otherSKey, VALUE); - - assertFalse(entry0.equals(entry1)); - assertFalse(entry1.equals(entry0)); - assertThat(entry0.hashCode(), not(equalTo(entry1.hashCode()))); - } - - @Test - public void notEqualsWhenSecondaryKeysDifferOneNull() { - ShuffleEntry entry0 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry entry1 = new ShuffleEntry(KEY, null, VALUE); - - assertFalse(entry0.equals(entry1)); - assertFalse(entry1.equals(entry0)); - assertThat(entry0.hashCode(), not(equalTo(entry1.hashCode()))); - } - - @Test - public void notEqualsWhenValuesDiffer() { - final byte[] otherValue = {0x2}; - ShuffleEntry entry0 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry entry1 = new ShuffleEntry(KEY, SKEY, otherValue); - - assertFalse(entry0.equals(entry1)); - assertFalse(entry1.equals(entry0)); - assertThat(entry0.hashCode(), not(equalTo(entry1.hashCode()))); - } - - @Test - public void notEqualsWhenValuesDifferOneNull() { - ShuffleEntry entry0 = new ShuffleEntry(KEY, SKEY, VALUE); - ShuffleEntry entry1 = new ShuffleEntry(KEY, SKEY, null); - - assertFalse(entry0.equals(entry1)); - assertFalse(entry1.equals(entry0)); - assertThat(entry0.hashCode(), not(equalTo(entry1.hashCode()))); - } - - @Test - public void emptyNotTheSameAsNull() { - final byte[] empty = {}; - ShuffleEntry entry0 = new ShuffleEntry(null, null, null); - ShuffleEntry entry1 = new ShuffleEntry(empty, empty, empty); - - assertFalse(entry0.equals(entry1)); - assertFalse(entry1.equals(entry0)); - assertThat(entry0.hashCode(), not(equalTo(entry1.hashCode()))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSamplerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSamplerTest.java deleted file mode 100644 index f4f6752b6c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSamplerTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.SamplingCallback; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.ScopedState; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; - -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Unit tests for the {@link Counter} API. - */ -@RunWith(JUnit4.class) -public class StateSamplerTest { - - public static long getCounterLongValue(CounterSet counters, String name) { - @SuppressWarnings("unchecked") - Counter counter = (Counter) counters.getExistingCounter(name); - return counter.getAggregate(); - } - - @Test - public void basicTest() throws InterruptedException { - CounterSet counters = new CounterSet(); - long periodMs = 50; - try (StateSampler stateSampler = - new StateSampler("test-", counters.getAddCounterMutator(), periodMs)) { - - int state1 = stateSampler.stateForName("1", StateSampler.StateKind.USER); - int state2 = stateSampler.stateForName("2", StateSampler.StateKind.USER); - - try (StateSampler.ScopedState s1 = - stateSampler.scopedState(state1)) { - assert s1 != null; - sleepMillis(2 * periodMs); - } - - try (StateSampler.ScopedState s2 = - stateSampler.scopedState(state2)) { - assert s2 != null; - sleepMillis(3 * periodMs); - } - - long s1 = getCounterLongValue(counters, "test-1-msecs"); - long s2 = getCounterLongValue(counters, "test-2-msecs"); - - long toleranceMs = periodMs; - assertTrue(s1 + s2 >= 1 * periodMs - toleranceMs); - assertTrue(s1 + s2 <= 10 * periodMs + toleranceMs); - } - } - - @Test - public void nestingTest() throws InterruptedException { - CounterSet counters = new CounterSet(); - long periodMs = 50; - try (StateSampler stateSampler = - new StateSampler("test-", counters.getAddCounterMutator(), periodMs)) { - - int state1 = stateSampler.stateForName("1", StateSampler.StateKind.USER); - int state2 = stateSampler.stateForName("2", StateSampler.StateKind.USER); - int state3 = stateSampler.stateForName("3", StateSampler.StateKind.USER); - - try (StateSampler.ScopedState s1 = - stateSampler.scopedState(state1)) { - assert s1 != null; - sleepMillis(2 * periodMs); - - try (StateSampler.ScopedState s2 = - stateSampler.scopedState(state2)) { - assert s2 != null; - sleepMillis(2 * periodMs); - - try (StateSampler.ScopedState s3 = - stateSampler.scopedState(state3)) { - assert s3 != null; - sleepMillis(2 * periodMs); - } - sleepMillis(periodMs); - } - sleepMillis(periodMs); - } - - long s1 = getCounterLongValue(counters, "test-1-msecs"); - long s2 = getCounterLongValue(counters, "test-2-msecs"); - long s3 = getCounterLongValue(counters, "test-3-msecs"); - - long toleranceMs = periodMs; - assertTrue(s1 + s2 + s3 >= 4 * periodMs - toleranceMs); - assertTrue(s1 + s2 + s3 <= 18 * periodMs + toleranceMs); - } - } - - @Test - public void nonScopedTest() throws InterruptedException { - CounterSet counters = new CounterSet(); - long periodMs = 50; - try (StateSampler stateSampler = new StateSampler("test-", - counters.getAddCounterMutator(), periodMs)) { - - int state1 = stateSampler.stateForName("1", StateSampler.StateKind.USER); - int previousState = stateSampler.setState(state1); - sleepMillis(2 * periodMs); - stateSampler.setState(previousState); - long tolerance = periodMs; - long s = getCounterLongValue(counters, "test-1-msecs"); - - assertTrue(s >= periodMs - tolerance); - assertTrue(s <= 5 * periodMs + tolerance); - } - } - - private void noSamplingAfterCloseTestOnce() throws Exception { - CounterSet counters = new CounterSet(); - long periodMs = 200; - - final AtomicLong lastSampledTimeStamp = new AtomicLong(); - final Semaphore sampleHappened = new Semaphore(0); - try (StateSampler stateSampler = new StateSampler("test-", - counters.getAddCounterMutator(), periodMs)) { - stateSampler.setState("test", StateKind.USER); - stateSampler.addSamplingCallback(new SamplingCallback(){ - @Override - public void run(int state, StateKind kind, long elapsedMs) { - lastSampledTimeStamp.set(System.nanoTime()); - sampleHappened.release(); - } - }); - sampleHappened.acquire(); - } - long samplerStoppedTimeStamp = System.nanoTime(); - assertThat(lastSampledTimeStamp.get(), Matchers.lessThanOrEqualTo(samplerStoppedTimeStamp)); - } - - @Test - public void noSamplingAfterCloseTest() throws Exception { - // Run it multiple times to detect flakyness. - for (int i = 0; i < 10; ++i) { - noSamplingAfterCloseTestOnce(); - } - } - - @Test - public void reuseStateByNameTest() throws Exception { - StateSampler stateSampler = new StateSampler("test-", - new CounterSet().getAddCounterMutator(), 200); - int state1 = stateSampler.stateForName("test_state", StateKind.USER); - int state2 = stateSampler.stateForName("test_state", StateKind.USER); - assertEquals(state1, state2); - stateSampler.close(); - } - - @Test - public void reuseManyStatesByName() throws Exception { - // Issue big number of stateForName() and setState calls to StateSampler. - CounterSet counters = new CounterSet(); - StateSampler stateSampler = new StateSampler("test-", - counters.getAddCounterMutator(), 200); - for (int i = 0; i < 10000; i++) { - for (int j = 0; j < 10000; j++) { - int state = stateSampler.stateForName("state" + j, StateKind.USER); - try (ScopedState scope = stateSampler.scopedState(state)) {} - } - } - // All counters got reused. - assertEquals(10000, counters.size()); - stateSampler.close(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/TestOutputReceiver.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/TestOutputReceiver.java deleted file mode 100644 index d5ff1573ce..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/TestOutputReceiver.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.worker.MapTaskExecutorFactory.ElementByteSizeObservableCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservable; -import com.google.common.annotations.VisibleForTesting; - -import java.util.ArrayList; -import java.util.List; - -/** - * An OutputReceiver that allows the output elements to be retrieved. - */ -public class TestOutputReceiver extends OutputReceiver { - private static final String OBJECT_COUNTER_NAME = "-ObjectCount"; - private static final String MEAN_BYTE_COUNTER_NAME = "-MeanByteCount"; - - @VisibleForTesting - final List outputElems = new ArrayList<>(); - - public TestOutputReceiver(CounterSet counterSet) { - this("test_receiver_out", counterSet); - } - - public TestOutputReceiver(Coder coder) { - this(coder, new CounterSet()); - } - - public TestOutputReceiver(Coder coder, CounterSet counterSet) { - this("test_receiver_out", new ElementByteSizeObservableCoder<>(coder), counterSet); - } - - public TestOutputReceiver(String outputName, CounterSet counterSet) { - this(outputName, new ElementByteSizeObservableCoder<>(StringUtf8Coder.of()), counterSet); - } - - public TestOutputReceiver( - ElementByteSizeObservable elementByteSizeObservable, CounterSet counterSet) { - this("test_receiver_out", elementByteSizeObservable, counterSet); - } - - public TestOutputReceiver(String outputName, - ElementByteSizeObservable elementByteSizeObservable, - CounterSet counterSet) { - this(outputName, elementByteSizeObservable, counterSet.getAddCounterMutator()); - } - - public TestOutputReceiver(String string, ElementByteSizeObservable elementByteSizeObservable, - AddCounterMutator addCounterMutator) { - ElementCounter outputCounter = - new TestOutputCounter(string, elementByteSizeObservable, addCounterMutator); - addOutputCounter(outputCounter); - } - - @Override - public void process(Object elem) throws Exception { - super.process(elem); - outputElems.add(elem); - } - - /** - * TestOutputCounter that samples every element. - */ - public static class TestOutputCounter extends OutputObjectAndByteCounter { - public TestOutputCounter() { - this(new CounterSet()); - } - - @SuppressWarnings("rawtypes") - public TestOutputCounter(CounterSet counters) { - this("output_name", new ElementByteSizeObservableCoder<>(StringUtf8Coder.of()), - counters.getAddCounterMutator()); - } - - public TestOutputCounter(String outputName, - ElementByteSizeObservable elementByteSizeObservable, - CounterSet.AddCounterMutator addCounterMutator) { - super(elementByteSizeObservable, addCounterMutator); - this.countObject(outputName + OBJECT_COUNTER_NAME); - this.countMeanByte(outputName + MEAN_BYTE_COUNTER_NAME); - } - - @Override - protected boolean sampleElement() { - return true; - } - - @VisibleForTesting - static String getObjectCounterName(String prefix) { - return prefix + OBJECT_COUNTER_NAME; - } - - @VisibleForTesting - static String getMeanByteCounterName(String prefix) { - return prefix + MEAN_BYTE_COUNTER_NAME; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutorTest.java deleted file mode 100644 index 918ac4ad78..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutorTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; - -import com.google.cloud.dataflow.sdk.util.common.Metric; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Unit tests for {@link WorkExecutor}. - */ -@RunWith(JUnit4.class) -public class WorkExecutorTest { - private WorkExecutor mapWorker; - - @Before - public void setUp() { - mapWorker = new MapTaskExecutor(null, null, null); - } - - @Test - public void testMapTaskGetOutputMetrics() { - Collection> metrics = mapWorker.getOutputMetrics(); - verifyOutputMetrics(metrics); - } - - private void verifyOutputMetrics(Collection> metrics) { - Collection metricNames = new ArrayList<>(); - for (Metric metric : metrics) { - metricNames.add(metric.getName()); - } - Assert.assertThat(metricNames, containsInAnyOrder("CPU")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperationTest.java deleted file mode 100644 index bb013afa15..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for WriteOperation. - */ -@RunWith(JUnit4.class) -public class WriteOperationTest { - @Test - @SuppressWarnings("unchecked") - public void testRunWriteOperation() throws Exception { - ExecutorTestUtils.TestSink sink = new ExecutorTestUtils.TestSink(); - CounterSet counterSet = new CounterSet(); - String counterPrefix = "test-"; - StateSampler stateSampler = new StateSampler( - counterPrefix, counterSet.getAddCounterMutator()); - - WriteOperation writeOperation = new WriteOperation( - sink, counterPrefix, counterSet.getAddCounterMutator(), stateSampler); - - writeOperation.start(); - - writeOperation.process("hi"); - writeOperation.process("there"); - writeOperation.process(""); - writeOperation.process("bob"); - - writeOperation.finish(); - - Assert.assertThat(sink.outputElems, - CoreMatchers.hasItems("hi", "there", "", "bob")); - - Assert.assertEquals( - new CounterSet( - Counter.longs("WriteOperation-ByteCount", SUM) - .resetToValue(2L + 5 + 0 + 3), - Counter.longs("test-WriteOperation-start-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-WriteOperation-start-msecs")).getAggregate()), - Counter.longs("test-WriteOperation-process-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-WriteOperation-process-msecs")).getAggregate()), - Counter.longs("test-WriteOperation-finish-msecs", SUM) - .resetToValue(((Counter) counterSet.getExistingCounter( - "test-WriteOperation-finish-msecs")).getAggregate())), - counterSet); - } -} From 2db0f78a53996f1f20bd0cffdeb7b6b23081fcd3 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Thu, 4 Feb 2016 13:07:37 -0800 Subject: [PATCH 081/751] CustomSourcesTest: use a smaller byte limit to reduce test runtime ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113880884 --- .../sdk/runners/worker/WorkerCustomSources.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java index 59da1f0805..192b9ee456 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java @@ -63,7 +63,6 @@ import javax.annotation.Nullable; - /** * A helper class for supporting sources defined as {@code Source}. * @@ -134,6 +133,15 @@ public static DynamicSourceSplit toSourceSplit( */ public static SourceOperationResponse performSplit( SourceSplitRequest request, PipelineOptions options) throws Exception { + return performSplitWithApiLimit(request, options, DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES); + } + + /** + * A helper method like {@link #performSplit(SourceSplitRequest, PipelineOptions)} but that + * allows overriding the API size limit for testing. + */ + static SourceOperationResponse performSplitWithApiLimit( + SourceSplitRequest request, PipelineOptions options, long apiByteLimit) throws Exception { Source anySource = deserializeFromCloudSource(request.getSource().getSpec()); checkArgument( anySource instanceof BoundedSource, "Cannot split a non-Bounded source: %s", anySource); @@ -151,8 +159,8 @@ public static SourceOperationResponse performSplit( long serializedSize = DataflowApiUtils.computeSerializedSizeBytes(splits); // If split response is too large, scale desired size for expected DATAFLOW_API_SIZE_BYTES/2. - if (serializedSize > DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES) { - double expansion = 2 * (double) serializedSize / DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; + if (serializedSize > apiByteLimit) { + double expansion = 2 * (double) serializedSize / apiByteLimit; long expandedBundleSizeBytes = (long) (desiredBundleSizeBytes * expansion); LOG.warn( "Splitting source {} into bundles of estimated size {} bytes produced {} bundles, which" From 5addd1b58a1b0c2d0a80823ad59a6664b6ee4bb7 Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 4 Feb 2016 13:33:10 -0800 Subject: [PATCH 082/751] Explicitly pass ReaderFactory from worker classes to SideInputUtils This removes the dependency of SideInputUtils on having the default registry, hence the various ReaderFactory implementations. Furthermore, it was probably wrong that a DataflowSideInputReader created by the workers did not use a registry controlled at the worker level but instead created its own. (in practice it is never customized) ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113883350 --- .../worker/DataflowSideInputReader.java | 6 +- .../worker/MapTaskExecutorFactory.java | 58 +++++++------------ .../sdk/runners/worker/SideInputUtils.java | 30 +++++++--- .../sdk/util/BatchModeExecutionContext.java | 17 ++++-- 4 files changed, 58 insertions(+), 53 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java index ed1d702791..109fc58da8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java @@ -59,6 +59,7 @@ public class DataflowSideInputReader private DataflowSideInputReader( Iterable sideInputInfos, + ReaderFactory readerFactory, PipelineOptions options, ExecutionContext executionContext) throws Exception { // Initializing the values may or may not actually read through the @@ -72,7 +73,7 @@ private DataflowSideInputReader( TupleTag tag = new TupleTag<>(sideInputInfo.getTag()); ByteSizeObserver observer = new ByteSizeObserver(); Object sideInputValue = SideInputUtils.readSideInput( - options, sideInputInfo, observer, executionContext); + options, sideInputInfo, readerFactory, observer, executionContext); overheads.put(tag, observer.getBytes()); observer.reset(); observers.put(tag, observer); @@ -87,10 +88,11 @@ private DataflowSideInputReader( */ public static DataflowSideInputReader of( Iterable sideInputInfos, + ReaderFactory readerFactory, PipelineOptions options, ExecutionContext context) throws Exception { - return new DataflowSideInputReader(sideInputInfos, options, context); + return new DataflowSideInputReader(sideInputInfos, readerFactory, options, context); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java index f95d7f7807..094a50247b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java @@ -26,6 +26,7 @@ import com.google.api.services.dataflow.model.ParallelInstruction; import com.google.api.services.dataflow.model.PartialGroupByKeyInstruction; import com.google.api.services.dataflow.model.ReadInstruction; +import com.google.api.services.dataflow.model.Source; import com.google.api.services.dataflow.model.WriteInstruction; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.KvCoder; @@ -34,6 +35,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunner; @@ -76,18 +78,18 @@ import javax.annotation.Nullable; /** - * Creates a MapTaskExecutor from a MapTask definition. + * Creates a {@link MapTaskExecutor} from a {@link MapTask} definition. */ public class MapTaskExecutorFactory { /** - * Creates a new MapTaskExecutor from the given MapTask definition using the provided - * {@link ReaderRegistry}. + * Creates a new {@link MapTaskExecutor} from the given {@link MapTask} definition using the + * provided {@link ReaderFactory}. */ public static MapTaskExecutor create( PipelineOptions options, MapTask mapTask, - ReaderRegistry registry, + ReaderFactory readerFactory, DataflowExecutionContext context, CounterSet counters, StateSampler stateSampler) @@ -101,7 +103,7 @@ public static MapTaskExecutor create( operations.add(createOperation( options, instruction, - registry, + readerFactory, context, operations, counterPrefix, @@ -115,39 +117,13 @@ public static MapTaskExecutor create( } /** - * Creates an Operation from the given ParallelInstruction definition using the provided - * {@link ReaderRegistry}. + * Creates an {@link Operation} from the given {@link ParallelInstruction} definition using the + * provided {@link ReaderFactory}. */ static Operation createOperation( PipelineOptions options, ParallelInstruction instruction, - DataflowExecutionContext executionContext, - List priorOperations, - String counterPrefix, - String systemStageName, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - return createOperation( - options, - instruction, - ReaderRegistry.defaultRegistry(), - executionContext, - priorOperations, - counterPrefix, - systemStageName, - addCounterMutator, - stateSampler); - } - - /** - * Creates an Operation from the given ParallelInstruction definition using the provided - * {@link ReaderRegistry}. - */ - static Operation createOperation( - PipelineOptions options, - ParallelInstruction instruction, - ReaderRegistry registry, + ReaderFactory readerFactory, DataflowExecutionContext executionContext, List priorOperations, String counterPrefix, @@ -159,7 +135,7 @@ static Operation createOperation( return createReadOperation( options, instruction, - registry, + readerFactory, executionContext, priorOperations, counterPrefix, @@ -186,7 +162,7 @@ static Operation createOperation( static ReadOperation createReadOperation( PipelineOptions options, ParallelInstruction instruction, - ReaderRegistry registry, + ReaderFactory readerFactory, DataflowExecutionContext executionContext, @SuppressWarnings("unused") List priorOperations, String counterPrefix, @@ -197,9 +173,15 @@ static ReadOperation createReadOperation( ReadInstruction read = instruction.getRead(); String operationName = instruction.getSystemName(); + Source cloudSource = CloudSourceUtils.flattenBaseSpecs(read.getSource()); + CloudObject sourceSpec = CloudObject.fromSpec(cloudSource.getSpec()); + Coder coder = null; + if (cloudSource.getCodec() != null) { + coder = Serializer.deserialize(cloudSource.getCodec(), Coder.class); + } NativeReader reader = - registry.create( - read.getSource(), options, executionContext, addCounterMutator, operationName); + readerFactory.create( + sourceSpec, coder, options, executionContext, addCounterMutator, operationName); OutputReceiver[] receivers = createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java index 4603eccc82..8254bceba0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java @@ -20,10 +20,12 @@ import com.google.api.services.dataflow.model.SideInputInfo; import com.google.api.services.dataflow.model.Source; +import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.Serializer; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.common.collect.Iterables; @@ -53,27 +55,31 @@ public class SideInputUtils { public static Object readSideInput( PipelineOptions options, SideInputInfo sideInputInfo, + ReaderFactory readerFactory, Observer observer, ExecutionContext executionContext) throws Exception { Iterable elements = - readSideInputSources(options, sideInputInfo.getSources(), observer, executionContext); + readSideInputSources(options, sideInputInfo.getSources(), readerFactory, observer, + executionContext); return readSideInputValue(sideInputInfo.getKind(), elements); } public static Object readSideInput( PipelineOptions options, SideInputInfo sideInputInfo, + ReaderFactory readerFactory, ExecutionContext executionContext) throws Exception { - Iterable elements = - readSideInputSources(options, sideInputInfo.getSources(), null, executionContext); + Iterable elements = readSideInputSources( + options, sideInputInfo.getSources(), readerFactory, null, executionContext); return readSideInputValue(sideInputInfo.getKind(), elements); } private static Iterable readSideInputSources( PipelineOptions options, List sideInputSources, + ReaderFactory readerFactory, Observer observer, ExecutionContext executionContext) throws Exception { @@ -81,11 +87,13 @@ private static Iterable readSideInputSources( if (numSideInputSources == 0) { throw new Exception("expecting at least one side input Source"); } else if (numSideInputSources == 1) { - return readSideInputSource(options, sideInputSources.get(0), observer, executionContext); + return readSideInputSource( + options, sideInputSources.get(0), readerFactory, observer, executionContext); } else { List> shards = new ArrayList<>(); for (Source sideInputSource : sideInputSources) { - shards.add(readSideInputSource(options, sideInputSource, observer, executionContext)); + shards.add(readSideInputSource( + options, sideInputSource, readerFactory, observer, executionContext)); } return Iterables.concat(shards); } @@ -94,15 +102,19 @@ private static Iterable readSideInputSources( private static Iterable readSideInputSource( PipelineOptions options, Source sideInputSource, + ReaderFactory readerFactory, Observer observer, ExecutionContext executionContext) throws Exception { + Coder coder = null; + if (sideInputSource.getCodec() != null) { + coder = Serializer.deserialize(sideInputSource.getCodec(), Coder.class); + } // We don't do shuffle sanity check on side inputs, as they don't have to be read completely. @SuppressWarnings("unchecked") NativeReader reader = - (NativeReader) - ReaderRegistry.defaultRegistry() - .create(sideInputSource, options, executionContext, null, null); + (NativeReader) readerFactory.create(CloudObject.fromSpec(sideInputSource.getSpec()), + coder, options, executionContext, null, null); if (observer != null) { reader.addObserver(observer); } @@ -170,6 +182,7 @@ private NativeReaderToIteratorAdapter(NativeReader.NativeReaderIterator reade this.state = NextState.UNKNOWN_BEFORE_START; } + @Override public boolean hasNext() { try { switch (state) { @@ -201,6 +214,7 @@ public boolean hasNext() { } } + @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java index 98065952aa..29980bd015 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java @@ -21,6 +21,8 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.worker.DataflowExecutionContext; import com.google.cloud.dataflow.sdk.runners.worker.DataflowSideInputReader; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderRegistry; import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; import com.google.cloud.dataflow.sdk.util.state.StateInternals; @@ -35,10 +37,12 @@ public class BatchModeExecutionContext extends DataflowExecutionContext { private Object key; - private PipelineOptions options; + private final PipelineOptions options; + private final ReaderFactory readerFactory; - protected BatchModeExecutionContext(PipelineOptions options) { + protected BatchModeExecutionContext(PipelineOptions options, ReaderFactory readerFactory) { this.options = options; + this.readerFactory = readerFactory; } /** @@ -46,14 +50,16 @@ protected BatchModeExecutionContext(PipelineOptions options) { * pipeline options. */ public static BatchModeExecutionContext withDefaultOptions() { - return new BatchModeExecutionContext(PipelineOptionsFactory.create()); + return new BatchModeExecutionContext( + PipelineOptionsFactory.create(), + ReaderRegistry.defaultRegistry()); } /** * Returns a {@link BatchModeExecutionContext} configured according to the provided options. */ public static BatchModeExecutionContext fromOptions(PipelineOptions options) { - return new BatchModeExecutionContext(options); + return new BatchModeExecutionContext(options, ReaderRegistry.defaultRegistry()); } /** @@ -104,7 +110,8 @@ public Object getKey() { @Override protected SideInputReader getSideInputReader( Iterable sideInputInfos) throws Exception { - return DataflowSideInputReader.of(sideInputInfos, options, this); + return DataflowSideInputReader.of( + sideInputInfos, readerFactory, options, this); } @Override From be3326c13723f23fdf30f6ffd039962eb46135f6 Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 4 Feb 2016 17:11:00 -0800 Subject: [PATCH 083/751] Move MapTaskExecutorFactory and system DoFns and their factories This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113904737 --- .../runners/worker/AssignWindowsParDoFn.java | 136 ----- .../sdk/runners/worker/CombineValuesFn.java | 289 --------- .../runners/worker/DefaultParDoFnFactory.java | 82 --- .../worker/GroupAlsoByWindowsParDoFn.java | 290 --------- .../worker/MapTaskExecutorFactory.java | 555 ------------------ .../sdk/runners/worker/NormalParDoFn.java | 168 ------ .../sdk/runners/worker/ParDoFnBase.java | 223 ------- .../ReifyTimestampAndWindowsParDoFn.java | 115 ---- 8 files changed, 1858 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AssignWindowsParDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReifyTimestampAndWindowsParDoFn.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AssignWindowsParDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AssignWindowsParDoFn.java deleted file mode 100644 index 153fcf5f30..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AssignWindowsParDoFn.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBytes; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.AssignWindowsDoFn; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.common.base.Preconditions; - -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A wrapper around an AssignWindowsDoFn. This class is the same as - * NormalParDoFn, except that it gets deserialized differently. - */ -class AssignWindowsParDoFn extends ParDoFnBase { - - static AssignWindowsParDoFn of( - PipelineOptions options, - AssignWindowsDoFn fn, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - return new AssignWindowsParDoFn( - options, fn, stepName, transformName, executionContext, addCounterMutator, stateSampler); - } - - /** - * A {@link ParDoFnFactory} to create instances of {@link AssignWindowsParDoFn} according to - * specifications from the Dataflow service. - */ - static final class Factory implements ParDoFnFactory { - @Override - public ParDoFn create( - PipelineOptions options, - final CloudObject cloudUserFn, - String stepName, - String transformName, - @Nullable List sideInputInfos, - @Nullable List multiOutputInfos, - int numOutputs, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - - final Object deserializedWindowingStrategy = - SerializableUtils.deserializeFromByteArray( - getBytes(cloudUserFn, PropertyNames.SERIALIZED_FN), - "serialized windowing strategy"); - - Preconditions.checkArgument( - deserializedWindowingStrategy instanceof WindowingStrategy, - "unexpected kind of WindowingStrategy: " - + deserializedWindowingStrategy.getClass().getName()); - - // We just checked the raw type, and the other types are simply required to be enforced - // outside of this class - @SuppressWarnings("unchecked") - final WindowingStrategy windowingStrategy = - (WindowingStrategy) deserializedWindowingStrategy; - - final AssignWindowsDoFn assignFn = - new AssignWindowsDoFn<>(windowingStrategy.getWindowFn()); - - return AssignWindowsParDoFn.of( - options, - assignFn, - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - } - } - - @Override - protected DoFnInfo getDoFnInfo() { - return new DoFnInfo<>(fn, null); - } - - private final AssignWindowsDoFn fn; - - private AssignWindowsParDoFn( - PipelineOptions options, - AssignWindowsDoFn fn, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super( - options, - NullSideInputReader.empty(), - Arrays.asList("output"), - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - this.fn = fn; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFn.java deleted file mode 100644 index 2b381f15b5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CombineValuesFn.java +++ /dev/null @@ -1,289 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBytes; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunner; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunners; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.base.Preconditions; - -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A {@link ParDoFn} wrapping a decoded user {@link CombineFn}. - */ -class CombineValuesFn extends ParDoFnBase { - /** - * The optimizer may split run the user combiner in 3 separate - * phases (ADD, MERGE, and EXTRACT), on separate VMs, as it sees - * fit. The CombinerPhase dictates which DoFn is actually running in - * the worker. - */ - // TODO: These strings are part of the service definition, and - // should be added into the definition of the ParDoInstruction, - // but the protiary definitions don't allow for enums yet. - public static class CombinePhase { - public static final String ALL = "all"; - public static final String ADD = "add"; - public static final String MERGE = "merge"; - public static final String EXTRACT = "extract"; - } - - static CombineValuesFn of( - PipelineOptions options, - AppliedCombineFn combineFn, - String phase, - SideInputReader sideInputReader, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - return new CombineValuesFn(options, combineFn, phase, sideInputReader, stepName, transformName, - executionContext, addCounterMutator, stateSampler); - } - - /** - * A {@link ParDoFnFactory} to create instances of {@link CombineValuesFn} according to - * specifications from the Dataflow service. - */ - static final class Factory implements ParDoFnFactory { - @Override - public ParDoFn create( - PipelineOptions options, - final CloudObject cloudUserFn, - String stepName, - String transformName, - @Nullable List sideInputInfos, - @Nullable List multiOutputInfos, - int numOutputs, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - - Preconditions.checkArgument( - numOutputs == 1, "expected exactly one output for CombineValuesFn"); - - Object deserializedFn = - SerializableUtils.deserializeFromByteArray( - getBytes(cloudUserFn, PropertyNames.SERIALIZED_FN), - "serialized user fn"); - Preconditions.checkArgument(deserializedFn instanceof AppliedCombineFn); - AppliedCombineFn combineFn = (AppliedCombineFn) deserializedFn; - Iterable> sideInputViews = combineFn.getSideInputViews(); - final SideInputReader sideInputReader = - executionContext.getSideInputReader(sideInputInfos, sideInputViews); - - // Get the combine phase, default to ALL. (The implementation - // doesn't have to split the combiner). - String phase = getString(cloudUserFn, PropertyNames.PHASE, CombinePhase.ALL); - - return CombineValuesFn.of( - options, - combineFn, - phase, - sideInputReader, - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - } - } - - @Override - protected DoFnInfo getDoFnInfo() { - PerKeyCombineFnRunner combineFnRunner = - PerKeyCombineFnRunners.create(combineFn.getFn()); - DoFn doFn = null; - switch (phase) { - case CombinePhase.ALL: - doFn = new CombineValuesDoFn<>(combineFnRunner); - break; - case CombinePhase.ADD: - doFn = new AddInputsDoFn<>(combineFnRunner); - break; - case CombinePhase.MERGE: - doFn = new MergeAccumulatorsDoFn<>(combineFnRunner); - break; - case CombinePhase.EXTRACT: - doFn = new ExtractOutputDoFn<>(combineFnRunner); - break; - default: - throw new IllegalArgumentException( - "phase must be one of 'all', 'add', 'merge', 'extract'"); - } - - Coder inputCoder = null; - if (combineFn.getKvCoder() != null) { - switch (phase) { - case CombinePhase.ALL: - inputCoder = KvCoder.of( - combineFn.getKvCoder().getKeyCoder(), - IterableCoder.of(combineFn.getKvCoder().getValueCoder())); - break; - case CombinePhase.ADD: - inputCoder = combineFn.getKvCoder(); - break; - case CombinePhase.MERGE: - inputCoder = KvCoder.of( - combineFn.getKvCoder().getKeyCoder(), - IterableCoder.of(combineFn.getAccumulatorCoder())); - break; - case CombinePhase.EXTRACT: - inputCoder = - KvCoder.of(combineFn.getKvCoder().getKeyCoder(), combineFn.getAccumulatorCoder()); - break; - } - } - return new DoFnInfo<>( - doFn, combineFn.getWindowingStrategy(), combineFn.getSideInputViews(), inputCoder); - } - - private final String phase; - private final AppliedCombineFn combineFn; - - private CombineValuesFn( - PipelineOptions options, - AppliedCombineFn combineFn, - String phase, - SideInputReader sideInputReader, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super( - options, - sideInputReader, - Arrays.asList("output"), - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - this.phase = phase; - this.combineFn = combineFn; - } - - /** - * The ALL phase is the unsplit combiner, in case combiner lifting - * is disabled or the optimizer chose not to lift this combiner. - */ - private static class CombineValuesDoFn - extends DoFn>, KV>{ - private final PerKeyCombineFnRunner combinefnRunner; - - private CombineValuesDoFn(PerKeyCombineFnRunner combinefnRunner) { - this.combinefnRunner = combinefnRunner; - } - - @Override - public void processElement(ProcessContext c) { - KV> kv = c.element(); - K key = kv.getKey(); - - c.output(KV.of(key, this.combinefnRunner.apply(key, kv.getValue(), c))); - } - } - - /* - * ADD phase: KV> -> KV. - */ - private static class AddInputsDoFn - extends DoFn>, KV>{ - private final PerKeyCombineFnRunner combinefnRunner; - - private AddInputsDoFn(PerKeyCombineFnRunner combinefnRunner) { - this.combinefnRunner = combinefnRunner; - } - - @Override - public void processElement(ProcessContext c) { - KV> kv = c.element(); - K key = kv.getKey(); - AccumT accum = combinefnRunner.addInputs(key, kv.getValue(), c); - c.output(KV.of(key, accum)); - } - } - - /* - * MERGE phase: KV> -> KV. - */ - private static class MergeAccumulatorsDoFn - extends DoFn>, KV>{ - private final PerKeyCombineFnRunner combinefnRunner; - - private MergeAccumulatorsDoFn(PerKeyCombineFnRunner combinefnRunner) { - this.combinefnRunner = combinefnRunner; - } - - @Override - public void processElement(ProcessContext c) { - KV> kv = c.element(); - K key = kv.getKey(); - AccumT accum = this.combinefnRunner.mergeAccumulators(key, kv.getValue(), c); - c.output(KV.of(key, accum)); - } - } - - /* - * EXTRACT phase: KV -> KV. - */ - private static class ExtractOutputDoFn - extends DoFn, KV>{ - private final PerKeyCombineFnRunner combinefnRunner; - - private ExtractOutputDoFn(PerKeyCombineFnRunner combinefnRunner) { - this.combinefnRunner = combinefnRunner; - } - - @Override - public void processElement(ProcessContext c) { - KV kv = c.element(); - K key = kv.getKey(); - OutputT output = this.combinefnRunner.extractOutput(key, kv.getValue(), c); - c.output(KV.of(key, output)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactory.java deleted file mode 100644 index b11d8327a5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DefaultParDoFnFactory.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.common.collect.ImmutableMap; - -import java.util.List; - -/** - * A factory that dispatches to all known factories in the Dataflow SDK based on the value of - * {@link CloudObject#getClassName()} for the specified {@code DoFn}. - */ -public class DefaultParDoFnFactory implements ParDoFnFactory { - private final ImmutableMap defaultFactories; - - public DefaultParDoFnFactory() { - defaultFactories = ImmutableMap.builder() - .put("DoFn", new NormalParDoFn.Factory()) - .put("CombineValuesFn", new CombineValuesFn.Factory()) - .put("MergeBucketsDoFn", new GroupAlsoByWindowsParDoFn.Factory()) - .put("AssignBucketsDoFn", new AssignWindowsParDoFn.Factory()) - .put("MergeWindowsDoFn", new GroupAlsoByWindowsParDoFn.Factory()) - .put("AssignWindowsDoFn", new AssignWindowsParDoFn.Factory()) - .put("ReifyTimestampAndWindowsDoFn", new ReifyTimestampAndWindowsParDoFn.Factory()) - .build(); - } - - @Override - public ParDoFn create( - PipelineOptions options, - CloudObject cloudUserFn, - String stepName, - String transformName, - List sideInputInfos, - List multiOutputInfos, - int numOutputs, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - - String className = cloudUserFn.getClassName(); - ParDoFnFactory factory = defaultFactories.get(className); - - if (factory == null) { - throw new Exception("No known ParDoFnFactory for " + className); - } - - return factory.create( - options, - cloudUserFn, - stepName, - transformName, - sideInputInfos, - multiOutputInfos, - numOutputs, - executionContext, - addCounterMutator, - stateSampler); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java deleted file mode 100644 index e8b93062b3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupAlsoByWindowsParDoFn.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBytes; -import static com.google.cloud.dataflow.sdk.util.Structs.getObject; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.StreamingOptions; -import com.google.cloud.dataflow.sdk.runners.worker.CombineValuesFn.CombinePhase; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsDoFn; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * A wrapper around a GroupAlsoByWindowsDoFn. This class is the same as - * NormalParDoFn, except that it gets deserialized differently. - */ -class GroupAlsoByWindowsParDoFn extends ParDoFnBase { - - static GroupAlsoByWindowsParDoFn of( - PipelineOptions options, - DoFn groupAlsoByWindowsDoFn, - WindowingStrategy windowingStrategy, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - return new GroupAlsoByWindowsParDoFn(options, groupAlsoByWindowsDoFn, windowingStrategy, - stepName, transformName, executionContext, addCounterMutator, stateSampler); - } - - /** - * A {@link ParDoFnFactory} to create {@link GroupAlsoByWindowsParDoFn} instances according to - * specifications from the Dataflow service. - */ - static final class Factory implements ParDoFnFactory { - @Override - public ParDoFn create( - PipelineOptions options, - CloudObject cloudUserFn, - String stepName, - String transformName, - @Nullable List sideInputInfos, - @Nullable List multiOutputInfos, - int numOutputs, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - Object windowingStrategyObj; - byte[] encodedWindowingStrategy = getBytes(cloudUserFn, PropertyNames.SERIALIZED_FN); - if (encodedWindowingStrategy.length == 0) { - windowingStrategyObj = WindowingStrategy.globalDefault(); - } else { - windowingStrategyObj = - SerializableUtils.deserializeFromByteArray( - encodedWindowingStrategy, "serialized windowing strategy"); - Preconditions.checkArgument( - windowingStrategyObj instanceof WindowingStrategy, - "unexpected kind of WindowingStrategy: " + windowingStrategyObj.getClass().getName()); - } - @SuppressWarnings({"rawtypes", "unchecked"}) - WindowingStrategy windowingStrategy = (WindowingStrategy) windowingStrategyObj; - - byte[] serializedCombineFn = getBytes(cloudUserFn, PropertyNames.COMBINE_FN, null); - AppliedCombineFn combineFn = null; - if (serializedCombineFn != null) { - Object combineFnObj = SerializableUtils.deserializeFromByteArray( - serializedCombineFn, "serialized combine fn"); - Preconditions.checkArgument( - combineFnObj instanceof AppliedCombineFn, - "unexpected kind of AppliedCombineFn: " + combineFnObj.getClass().getName()); - combineFn = (AppliedCombineFn) combineFnObj; - } - - Map inputCoderObject = getObject(cloudUserFn, PropertyNames.INPUT_CODER); - - Coder inputCoder = Serializer.deserialize(inputCoderObject, Coder.class); - Preconditions.checkArgument( - inputCoder instanceof WindowedValueCoder, - "Expected WindowedValueCoder for inputCoder, got: " + inputCoder.getClass().getName()); - @SuppressWarnings("unchecked") - WindowedValueCoder windowedValueCoder = (WindowedValueCoder) inputCoder; - - Coder elemCoder = windowedValueCoder.getValueCoder(); - Preconditions.checkArgument( - elemCoder instanceof KvCoder, - "Expected KvCoder for inputCoder, got: " + elemCoder.getClass().getName()); - @SuppressWarnings("unchecked") - KvCoder kvCoder = (KvCoder) elemCoder; - - boolean isStreamingPipeline = options.as(StreamingOptions.class).isStreaming(); - - @Nullable AppliedCombineFn maybeMergingCombineFn = null; - if (combineFn != null) { - Preconditions.checkState( - !(combineFn.getFn() instanceof RequiresContextInternal), - "Combiner lifting is not supported for combine functions with contexts: %s", - combineFn.getFn().getClass().getName()); - String phase = getString(cloudUserFn, PropertyNames.PHASE, CombinePhase.ALL); - Preconditions.checkArgument( - phase.equals(CombinePhase.ALL) || phase.equals(CombinePhase.MERGE), - "Unexpected phase: " + phase); - if (phase.equals(CombinePhase.MERGE)) { - maybeMergingCombineFn = makeAppliedMergingFunction(combineFn); - } else { - maybeMergingCombineFn = combineFn; - } - } - - DoFn groupAlsoByWindowsDoFn = getGroupAlsoByWindowsDoFn( - isStreamingPipeline, windowingStrategy, kvCoder, maybeMergingCombineFn); - - return GroupAlsoByWindowsParDoFn.of( - options, - groupAlsoByWindowsDoFn, - windowingStrategy, - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - } - } - - @Override - protected DoFnInfo getDoFnInfo() { - return new DoFnInfo<>(groupAlsoByWindowsDoFn, windowingStrategy); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static DoFn getGroupAlsoByWindowsDoFn( - boolean isStreamingPipeline, - WindowingStrategy windowingStrategy, - KvCoder kvCoder, - @Nullable AppliedCombineFn maybeMergingCombineFn) { - if (isStreamingPipeline) { - if (maybeMergingCombineFn == null) { - return StreamingGroupAlsoByWindowsDoFn.createForIterable( - windowingStrategy, kvCoder.getValueCoder()); - } else { - return StreamingGroupAlsoByWindowsDoFn.create( - windowingStrategy, maybeMergingCombineFn, kvCoder.getKeyCoder()); - } - } else { - if (maybeMergingCombineFn == null) { - return GroupAlsoByWindowsDoFn.createForIterable( - windowingStrategy, kvCoder.getValueCoder()); - } else { - return GroupAlsoByWindowsDoFn.create( - windowingStrategy, maybeMergingCombineFn, kvCoder.getKeyCoder()); - } - } - } - - private static AppliedCombineFn, AccumT> - makeAppliedMergingFunction(AppliedCombineFn appliedFn) { - Preconditions.checkArgument( - !(appliedFn.getFn() instanceof RequiresContextInternal), - "Combiner lifting is not supported for combine functions with contexts: %s", - appliedFn.getFn().getClass().getName()); - KeyedCombineFn keyedCombineFn = - ((KeyedCombineFn) appliedFn.getFn()); - MergingKeyedCombineFn mergingCombineFn = - new MergingKeyedCombineFn<>(keyedCombineFn , appliedFn.getAccumulatorCoder()); - return AppliedCombineFn., AccumT>withAccumulatorCoder( - mergingCombineFn, ListCoder.of(appliedFn.getAccumulatorCoder())); - } - - static class MergingKeyedCombineFn - extends KeyedCombineFn, AccumT> { - - private final KeyedCombineFn keyedCombineFn; - private final Coder accumCoder; - - MergingKeyedCombineFn( - KeyedCombineFn keyedCombineFn, Coder accumCoder) { - this.keyedCombineFn = keyedCombineFn; - this.accumCoder = accumCoder; - } - @Override - public List createAccumulator(K key) { - return new ArrayList<>(); - } - @Override - public List addInput(K key, List accumulator, AccumT input) { - accumulator.add(input); - return accumulator; - } - @Override - public List mergeAccumulators(K key, Iterable> accumulators) { - return mergeToSingleton(key, Iterables.concat(accumulators)); - } - @Override - public List compact(K key, List accumulator) { - return mergeToSingleton(key, accumulator); - } - @Override - public AccumT extractOutput(K key, List accumulator) { - if (accumulator.size() == 0) { - return keyedCombineFn.createAccumulator(key); - } else { - return keyedCombineFn.mergeAccumulators(key, accumulator); - } - } - private List mergeToSingleton(K key, Iterable accumulators) { - List singleton = new ArrayList<>(); - singleton.add(keyedCombineFn.mergeAccumulators(key, accumulators)); - return singleton; - } - - @Override - public Coder> getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return ListCoder.of(accumCoder); - } - } - - private final DoFn groupAlsoByWindowsDoFn; - private final WindowingStrategy windowingStrategy; - - private GroupAlsoByWindowsParDoFn( - PipelineOptions options, - DoFn groupAlsoByWindowsDoFn, - WindowingStrategy windowingStrategy, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super( - options, - NullSideInputReader.empty(), - Arrays.asList("output"), - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - this.groupAlsoByWindowsDoFn = groupAlsoByWindowsDoFn; - this.windowingStrategy = windowingStrategy; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java deleted file mode 100644 index 094a50247b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MapTaskExecutorFactory.java +++ /dev/null @@ -1,555 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBytes; - -import com.google.api.services.dataflow.model.FlattenInstruction; -import com.google.api.services.dataflow.model.InstructionInput; -import com.google.api.services.dataflow.model.InstructionOutput; -import com.google.api.services.dataflow.model.MapTask; -import com.google.api.services.dataflow.model.ParDoInstruction; -import com.google.api.services.dataflow.model.ParallelInstruction; -import com.google.api.services.dataflow.model.PartialGroupByKeyInstruction; -import com.google.api.services.dataflow.model.ReadInstruction; -import com.google.api.services.dataflow.model.Source; -import com.google.api.services.dataflow.model.WriteInstruction; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunner; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunners; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservable; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.util.common.worker.ElementCounter; -import com.google.cloud.dataflow.sdk.util.common.worker.FlattenOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.Operation; -import com.google.cloud.dataflow.sdk.util.common.worker.OutputReceiver; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation.GroupingKeyCreator; -import com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.ReceivingOperation; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.common.worker.WriteOperation; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Creates a {@link MapTaskExecutor} from a {@link MapTask} definition. - */ -public class MapTaskExecutorFactory { - - /** - * Creates a new {@link MapTaskExecutor} from the given {@link MapTask} definition using the - * provided {@link ReaderFactory}. - */ - public static MapTaskExecutor create( - PipelineOptions options, - MapTask mapTask, - ReaderFactory readerFactory, - DataflowExecutionContext context, - CounterSet counters, - StateSampler stateSampler) - throws Exception { - - List operations = new ArrayList<>(); - String counterPrefix = stateSampler.getPrefix(); - - // Instantiate operations for each instruction in the graph. - for (ParallelInstruction instruction : mapTask.getInstructions()) { - operations.add(createOperation( - options, - instruction, - readerFactory, - context, - operations, - counterPrefix, - mapTask.getSystemName(), - counters.getAddCounterMutator(), - stateSampler)); - } - - return new MapTaskExecutor(operations, counters, stateSampler); - - } - - /** - * Creates an {@link Operation} from the given {@link ParallelInstruction} definition using the - * provided {@link ReaderFactory}. - */ - static Operation createOperation( - PipelineOptions options, - ParallelInstruction instruction, - ReaderFactory readerFactory, - DataflowExecutionContext executionContext, - List priorOperations, - String counterPrefix, - String systemStageName, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - if (instruction.getRead() != null) { - return createReadOperation( - options, - instruction, - readerFactory, - executionContext, - priorOperations, - counterPrefix, - systemStageName, - addCounterMutator, - stateSampler); - } else if (instruction.getWrite() != null) { - return createWriteOperation(options, instruction, executionContext, priorOperations, - counterPrefix, addCounterMutator, stateSampler); - } else if (instruction.getParDo() != null) { - return createParDoOperation(options, instruction, executionContext, priorOperations, - counterPrefix, addCounterMutator, stateSampler); - } else if (instruction.getPartialGroupByKey() != null) { - return createPartialGroupByKeyOperation(options, instruction, executionContext, - priorOperations, counterPrefix, addCounterMutator, stateSampler); - } else if (instruction.getFlatten() != null) { - return createFlattenOperation(options, instruction, executionContext, priorOperations, - counterPrefix, addCounterMutator, stateSampler); - } else { - throw new Exception("Unexpected instruction: " + instruction); - } - } - - static ReadOperation createReadOperation( - PipelineOptions options, - ParallelInstruction instruction, - ReaderFactory readerFactory, - DataflowExecutionContext executionContext, - @SuppressWarnings("unused") List priorOperations, - String counterPrefix, - String systemStageName, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - ReadInstruction read = instruction.getRead(); - - String operationName = instruction.getSystemName(); - Source cloudSource = CloudSourceUtils.flattenBaseSpecs(read.getSource()); - CloudObject sourceSpec = CloudObject.fromSpec(cloudSource.getSpec()); - Coder coder = null; - if (cloudSource.getCodec() != null) { - coder = Serializer.deserialize(cloudSource.getCodec(), Coder.class); - } - NativeReader reader = - readerFactory.create( - sourceSpec, coder, options, executionContext, addCounterMutator, operationName); - - OutputReceiver[] receivers = - createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1); - - return new ReadOperation(operationName, reader, receivers, counterPrefix, systemStageName, - addCounterMutator, stateSampler); - } - - static WriteOperation createWriteOperation(PipelineOptions options, - ParallelInstruction instruction, ExecutionContext executionContext, - List priorOperations, String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception { - WriteInstruction write = instruction.getWrite(); - - Sink sink = - SinkFactory.create(options, write.getSink(), executionContext, addCounterMutator); - - OutputReceiver[] receivers = - createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 0); - - WriteOperation operation = new WriteOperation(instruction.getSystemName(), sink, receivers, - counterPrefix, addCounterMutator, stateSampler); - - attachInput(operation, write.getInput(), priorOperations); - - return operation; - } - - private static ParDoFnFactory parDoFnFactory = new DefaultParDoFnFactory(); - - static ParDoOperation createParDoOperation( - PipelineOptions options, - ParallelInstruction instruction, - DataflowExecutionContext executionContext, - List priorOperations, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - ParDoInstruction parDo = instruction.getParDo(); - - ParDoFn fn = parDoFnFactory.create( - options, - CloudObject.fromSpec(parDo.getUserFn()), - instruction.getSystemName(), - instruction.getName(), - parDo.getSideInputs(), - parDo.getMultiOutputInfos(), - parDo.getNumOutputs(), - executionContext, - addCounterMutator, - stateSampler); - - OutputReceiver[] receivers = createOutputReceivers( - instruction, counterPrefix, addCounterMutator, stateSampler, parDo.getNumOutputs()); - - ParDoOperation operation = new ParDoOperation( - instruction.getSystemName(), fn, receivers, counterPrefix, addCounterMutator, stateSampler); - - attachInput(operation, parDo.getInput(), priorOperations); - - return operation; - } - - static PartialGroupByKeyOperation createPartialGroupByKeyOperation( - PipelineOptions options, - ParallelInstruction instruction, - DataflowExecutionContext executionContext, - List priorOperations, String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception { - PartialGroupByKeyInstruction pgbk = instruction.getPartialGroupByKey(); - - Coder windowedCoder = Serializer.deserialize(pgbk.getInputElementCodec(), Coder.class); - if (!(windowedCoder instanceof WindowedValueCoder)) { - throw new Exception( - "unexpected kind of input coder for PartialGroupByKeyOperation: " + windowedCoder); - } - Coder elemCoder = ((WindowedValueCoder) windowedCoder).getValueCoder(); - if (!(elemCoder instanceof KvCoder)) { - throw new Exception( - "unexpected kind of input element coder for PartialGroupByKeyOperation: " + elemCoder); - } - KvCoder kvCoder = (KvCoder) elemCoder; - Coder keyCoder = kvCoder.getKeyCoder(); - Coder valueCoder = kvCoder.getValueCoder(); - - OutputReceiver[] receivers = - createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1); - - PartialGroupByKeyOperation.Combiner valueCombiner = null; - PartialGroupByKeyOperation.PairInfo pairInfo = PairInfo.create(); - if (pgbk.getValueCombiningFn() != null) { - Object deserializedFn = SerializableUtils.deserializeFromByteArray( - getBytes(CloudObject.fromSpec(pgbk.getValueCombiningFn()), PropertyNames.SERIALIZED_FN), - "serialized combine fn"); - AppliedCombineFn combineFn = ((AppliedCombineFn) deserializedFn); - - SideInputReader sideInputReader = - executionContext.getSideInputReader(pgbk.getSideInputs(), combineFn.getSideInputViews()); - valueCombiner = new ValueCombiner<>( - PerKeyCombineFnRunners.create(combineFn.getFn()), sideInputReader, options); - if (combineFn.getFn() instanceof RequiresContextInternal) { - pairInfo = WindowsExpandingPairInfo.create(); - } - } - - PartialGroupByKeyOperation operation = new PartialGroupByKeyOperation( - instruction.getSystemName(), - new WindowingCoderGroupingKeyCreator<>(keyCoder), - new CoderSizeEstimator<>(WindowedValue.getValueOnlyCoder(keyCoder)), - new CoderSizeEstimator<>(valueCoder), 0.001 /*sizeEstimatorSampleRate*/, valueCombiner, - pairInfo, receivers, counterPrefix, addCounterMutator, stateSampler); - - attachInput(operation, pgbk.getInput(), priorOperations); - - return operation; - } - - /** - * Implements PGBKOp.Combiner via Combine.KeyedCombineFn. - */ - public static class ValueCombiner - implements PartialGroupByKeyOperation.Combiner, InputT, AccumT, OutputT> { - private final PerKeyCombineFnRunner combineFn; - private final SideInputReader sideInputReader; - private final PipelineOptions options; - - private ValueCombiner( - PerKeyCombineFnRunner combineFn, - SideInputReader sideInputReader, - PipelineOptions options) { - this.combineFn = combineFn; - this.sideInputReader = sideInputReader; - this.options = options; - } - - @Override - public AccumT createAccumulator(WindowedValue windowedKey) { - return this.combineFn.createAccumulator(windowedKey.getValue(), - options, sideInputReader, windowedKey.getWindows()); - } - - @Override - public AccumT add(WindowedValue windowedKey, AccumT accumulator, InputT value) { - return this.combineFn.addInput(windowedKey.getValue(), accumulator, value, - options, sideInputReader, windowedKey.getWindows()); - } - - @Override - public AccumT merge(WindowedValue windowedKey, Iterable accumulators) { - return this.combineFn.mergeAccumulators(windowedKey.getValue(), accumulators, - options, sideInputReader, windowedKey.getWindows()); - } - - @Override - public AccumT compact(WindowedValue windowedKey, AccumT accumulator) { - return this.combineFn.compact(windowedKey.getValue(), accumulator, - options, sideInputReader, windowedKey.getWindows()); - } - - @Override - public OutputT extract(WindowedValue windowedKey, AccumT accumulator) { - return this.combineFn.extractOutput(windowedKey.getValue(), accumulator, - options, sideInputReader, windowedKey.getWindows()); - } - } - - /** - * Implements PGBKOp.PairInfo via KVs. - */ - public static class PairInfo implements PartialGroupByKeyOperation.PairInfo { - private static PairInfo theInstance = new PairInfo(); - public static PairInfo create() { - return theInstance; - } - private PairInfo() {} - @Override - public Iterable getKeysFromInputPair(Object pair) { - @SuppressWarnings("unchecked") - WindowedValue> windowedKv = (WindowedValue>) pair; - return ImmutableList.of(windowedKv.withValue(windowedKv.getValue().getKey())); - } - @Override - public Object getValueFromInputPair(Object pair) { - @SuppressWarnings("unchecked") - WindowedValue> windowedKv = (WindowedValue>) pair; - return windowedKv.getValue().getValue(); - } - @Override - public Object makeOutputPair(Object key, Object values) { - WindowedValue windowedKey = (WindowedValue) key; - return windowedKey.withValue(KV.of(windowedKey.getValue(), values)); - } - } - - /** - * Implements windows expanding PGBKOp.PairInfo via KVs. - */ - public static class WindowsExpandingPairInfo implements PartialGroupByKeyOperation.PairInfo { - private static WindowsExpandingPairInfo theInstance = new WindowsExpandingPairInfo(); - public static WindowsExpandingPairInfo create() { - return theInstance; - } - private WindowsExpandingPairInfo() {} - @Override - public Iterable getKeysFromInputPair(Object pair) { - @SuppressWarnings("unchecked") - final WindowedValue> windowedKv = (WindowedValue>) pair; - Preconditions.checkArgument(!windowedKv.getWindows().isEmpty()); - return Iterables.transform(windowedKv.getWindows(), - new Function() { - @Override - public Object apply(BoundedWindow window) { - return WindowedValue.of(windowedKv.getValue().getKey(), - windowedKv.getTimestamp(), window, windowedKv.getPane()); - } - }); - } - @Override - public Object getValueFromInputPair(Object pair) { - @SuppressWarnings("unchecked") - WindowedValue> windowedKv = (WindowedValue>) pair; - return windowedKv.getValue().getValue(); - } - @Override - public Object makeOutputPair(Object key, Object values) { - WindowedValue windowedKey = (WindowedValue) key; - return windowedKey.withValue(KV.of(windowedKey.getValue(), values)); - } - } - - /** - * Implements PGBKOp.GroupingKeyCreator via Coder. - */ - // TODO: Actually support window merging in the combiner table. - public static class WindowingCoderGroupingKeyCreator - implements GroupingKeyCreator> { - - private static final Instant ignored = BoundedWindow.TIMESTAMP_MIN_VALUE; - - private final Coder coder; - - public WindowingCoderGroupingKeyCreator(Coder coder) { - this.coder = coder; - } - - @Override - public Object createGroupingKey(WindowedValue key) throws Exception { - // Ignore timestamp for grouping purposes. - // The PGBK output will inherit the timestamp of one of its inputs. - return WindowedValue.of( - coder.structuralValue(key.getValue()), - ignored, - key.getWindows(), - key.getPane()); - } - } - - /** - * Implements PGBKOp.SizeEstimator via Coder. - */ - public static class CoderSizeEstimatorimplements PartialGroupByKeyOperation.SizeEstimator { - final Coder coder; - - public CoderSizeEstimator(Coder coder) { - this.coder = coder; - } - - @Override - public long estimateSize(T value) throws Exception { - return CoderUtils.encodeToByteArray(coder, value).length; - } - } - - static FlattenOperation createFlattenOperation( - @SuppressWarnings("unused") PipelineOptions options, - ParallelInstruction instruction, - @SuppressWarnings("unused") ExecutionContext executionContext, - List priorOperations, String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) throws Exception { - FlattenInstruction flatten = instruction.getFlatten(); - - OutputReceiver[] receivers = - createOutputReceivers(instruction, counterPrefix, addCounterMutator, stateSampler, 1); - - FlattenOperation operation = new FlattenOperation( - instruction.getSystemName(), receivers, counterPrefix, addCounterMutator, stateSampler); - - for (InstructionInput input : flatten.getInputs()) { - attachInput(operation, input, priorOperations); - } - - return operation; - } - - /** - * Returns an array of OutputReceivers for the given - * ParallelInstruction definition. - */ - static OutputReceiver[] createOutputReceivers(ParallelInstruction instruction, - @SuppressWarnings("unused") String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - @SuppressWarnings("unused") StateSampler stateSampler, - int expectedNumOutputs) throws Exception { - int numOutputs = 0; - if (instruction.getOutputs() != null) { - numOutputs = instruction.getOutputs().size(); - } - if (numOutputs != expectedNumOutputs) { - throw new AssertionError("ParallelInstruction.Outputs has an unexpected length"); - } - OutputReceiver[] receivers = new OutputReceiver[numOutputs]; - for (int i = 0; i < numOutputs; i++) { - InstructionOutput cloudOutput = instruction.getOutputs().get(i); - receivers[i] = new OutputReceiver(); - - @SuppressWarnings("unchecked") - ElementCounter outputCounter = new DataflowOutputCounter( - cloudOutput.getName(), - new ElementByteSizeObservableCoder<>( - Serializer.deserialize(cloudOutput.getCodec(), Coder.class)), - addCounterMutator); - receivers[i].addOutputCounter(outputCounter); - } - return receivers; - } - - /** - * Adapts a Coder to the ElementByteSizeObservable interface. - */ - public static class ElementByteSizeObservableCoder implements ElementByteSizeObservable { - final Coder coder; - - public ElementByteSizeObservableCoder(Coder coder) { - this.coder = coder; - } - - @Override - public boolean isRegisterByteSizeObserverCheap(T value) { - return coder.isRegisterByteSizeObserverCheap(value, Coder.Context.OUTER); - } - - @Override - public void registerByteSizeObserver(T value, ElementByteSizeObserver observer) - throws Exception { - coder.registerByteSizeObserver(value, observer, Coder.Context.OUTER); - } - } - - /** - * Adds an input to the given Operation, coming from the given - * producer instruction output. - */ - static void attachInput(ReceivingOperation operation, @Nullable InstructionInput input, - List priorOperations) { - Integer producerInstructionIndex = 0; - Integer outputNum = 0; - if (input != null) { - if (input.getProducerInstructionIndex() != null) { - producerInstructionIndex = input.getProducerInstructionIndex(); - } - if (input.getOutputNum() != null) { - outputNum = input.getOutputNum(); - } - } - // Input id must refer to an operation that has already been seen. - Operation source = priorOperations.get(producerInstructionIndex); - operation.attachInput(source, outputNum); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFn.java deleted file mode 100644 index 86d159f281..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/NormalParDoFn.java +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBytes; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A wrapper around a decoded user {@link DoFn}. - */ -class NormalParDoFn extends ParDoFnBase { - - /** - * Create a {@link NormalParDoFn}. - */ - static NormalParDoFn of( - PipelineOptions options, - DoFnInfo doFnInfo, - SideInputReader sideInputReader, - List outputTags, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - return new NormalParDoFn( - options, - doFnInfo, - sideInputReader, - outputTags, - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - } - - /** - * A {@link ParDoFnFactory} to create instances of {@link NormalParDoFn} according to - * specifications from the Dataflow service. - */ - static final class Factory implements ParDoFnFactory { - @Override - public ParDoFn create( - PipelineOptions options, - final CloudObject cloudUserFn, - String stepName, - String transformName, - @Nullable List sideInputInfos, - @Nullable List multiOutputInfos, - int numOutputs, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - Object deserializedFnInfo = - SerializableUtils.deserializeFromByteArray( - getBytes(cloudUserFn, PropertyNames.SERIALIZED_FN), - "serialized fn info"); - if (!(deserializedFnInfo instanceof DoFnInfo)) { - throw new Exception( - "unexpected kind of DoFnInfo: " + deserializedFnInfo.getClass().getName()); - } - DoFnInfo doFnInfo = (DoFnInfo) deserializedFnInfo; - - Iterable> sideInputViews = doFnInfo.getSideInputViews(); - SideInputReader sideInputReader = - executionContext.getSideInputReader(sideInputInfos, sideInputViews); - - List outputTags = new ArrayList<>(); - if (multiOutputInfos != null) { - for (MultiOutputInfo multiOutputInfo : multiOutputInfos) { - outputTags.add(multiOutputInfo.getTag()); - } - } - if (outputTags.isEmpty()) { - // Legacy support: assume there's a single output tag named "output". - // (The output tag name will be ignored, for the main output.) - outputTags.add("output"); - } - if (numOutputs != outputTags.size()) { - throw new AssertionError( - "unexpected number of outputTags for DoFn"); - } - - return NormalParDoFn.of( - options, - doFnInfo, - sideInputReader, - outputTags, - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - } - } - - private final byte[] serializedDoFn; - private final DoFnInfo doFnInfo; - - private NormalParDoFn( - PipelineOptions options, - DoFnInfo doFnInfo, - SideInputReader sideInputReader, - List outputTags, - String stepName, - String transformName, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super(options, sideInputReader, outputTags, stepName, transformName, executionContext, - addCounterMutator, stateSampler); - // The userDoFn is serialized because a fresh copy is provided each time it is accessed. - this.serializedDoFn = SerializableUtils.serializeToByteArray(doFnInfo.getDoFn()); - this.doFnInfo = doFnInfo; - } - - /** - * Produces a fresh {@link DoFnInfo} containing the user's {@link DoFn}. - */ - @Override - protected DoFnInfo getDoFnInfo() { - // This class write the serialized data in its own constructor, as a way of doing - // a deep copy. - @SuppressWarnings("unchecked") - DoFn userDoFn = (DoFn) SerializableUtils.deserializeFromByteArray( - serializedDoFn, "serialized user fun"); - return new DoFnInfo( - userDoFn, - doFnInfo.getWindowingStrategy(), - doFnInfo.getSideInputViews(), - doFnInfo.getInputCoder()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java deleted file mode 100644 index a1a1181498..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnBase.java +++ /dev/null @@ -1,223 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.StreamingOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ElementCounter; -import com.google.cloud.dataflow.sdk.util.common.worker.OutputReceiver; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.Receiver; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * A base class providing simple set up, processing, and tear down for a wrapped - * {@link DoFn}. - * - *

    Subclasses override just a method to provide a {@link DoFnInfo} for the - * wrapped {@link DoFn}. - */ -public abstract class ParDoFnBase implements ParDoFn { - - private final PipelineOptions options; - private final SideInputReader sideInputReader; - private final TupleTag mainOutputTag; - private final List> sideOutputTags; - private final String stepName; - private final String transformName; - private final ExecutionContext executionContext; - private final CounterSet.AddCounterMutator addCounterMutator; - private final StateSampler stateSampler; - private final boolean hasStreamingSideInput; - - /** The DoFnRunner executing a batch. Null between batches. */ - private DoFnRunner fnRunner; - private Receiver[] receivers; - - public ExecutionContext getExecutionContext() { - return executionContext; - } - - /** - * Creates a {@link ParDoFnBase} using basic information about the step being executed. - */ - protected ParDoFnBase( - PipelineOptions options, - SideInputReader sideInputReader, - List outputTags, - String stepName, - String transformName, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - this.options = options; - - // We vend a freshly deserialized version for each run - this.sideInputReader = sideInputReader; - Preconditions.checkArgument( - outputTags.size() > 0, - "expected at least one output"); - this.mainOutputTag = new TupleTag<>(outputTags.get(0)); - this.sideOutputTags = new ArrayList<>(); - if (outputTags.size() > 1) { - for (String tag : outputTags.subList(1, outputTags.size())) { - this.sideOutputTags.add(new TupleTag(tag)); - } - } - this.stepName = stepName; - this.transformName = transformName; - this.executionContext = executionContext; - this.addCounterMutator = addCounterMutator; - this.stateSampler = stateSampler; - this.hasStreamingSideInput = - options.as(StreamingOptions.class).isStreaming() && !sideInputReader.isEmpty(); - } - - /** - * Creates a fresh {@link DoFnInfo}. This will be called for each bundle. - */ - protected abstract DoFnInfo getDoFnInfo(); - - @Override - public void startBundle(Receiver... receivers) throws Exception { - if (receivers.length != sideOutputTags.size() + 1) { - throw new AssertionError( - "unexpected number of receivers for DoFn"); - } - - this.receivers = receivers; - if (hasStreamingSideInput) { - // There is non-trivial setup that needs to be performed for watermark propagation - // even on empty bundles. - reallyStartBundle(); - } - } - - private void reallyStartBundle() throws Exception { - Preconditions.checkState(fnRunner == null, "bundle already started (or not properly finished)"); - StepContext stepContext = null; - if (executionContext != null) { - stepContext = executionContext.getOrCreateStepContext(stepName, transformName, stateSampler); - } - - @SuppressWarnings("unchecked") - DoFnInfo doFnInfo = (DoFnInfo) getDoFnInfo(); - - OutputManager outputManager = new OutputManager() { - final Map, OutputReceiver> undeclaredOutputs = new HashMap<>(); - - @Nullable - private Receiver getReceiverOrNull(TupleTag tag) { - if (tag.equals(mainOutputTag)) { - return receivers[0]; - } else if (sideOutputTags.contains(tag)) { - return receivers[sideOutputTags.indexOf(tag) + 1]; - } else { - return undeclaredOutputs.get(tag); - } - } - - @Override - public void output(TupleTag tag, WindowedValue output) { - Receiver receiver = getReceiverOrNull(tag); - if (receiver == null) { - // A new undeclared output. - // TODO: plumb through the operationName, so that we can - // name implicit outputs after it. - String outputName = "implicit-" + tag.getId(); - // TODO: plumb through the counter prefix, so we can - // make it available to the OutputReceiver class in case - // it wants to use it in naming output counters. (It - // doesn't today.) - OutputReceiver undeclaredReceiver = new OutputReceiver(); - ElementCounter outputCounter = new DataflowOutputCounter(outputName, addCounterMutator); - undeclaredReceiver.addOutputCounter(outputCounter); - undeclaredOutputs.put(tag, undeclaredReceiver); - receiver = undeclaredReceiver; - } - - try { - receiver.process(output); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - if (hasStreamingSideInput) { - fnRunner = StreamingDoFnRunners.streamingSideInputRunner( - options, - doFnInfo, - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator); - } else { - fnRunner = DoFnRunners.createDefault( - options, - doFnInfo.getDoFn(), - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - doFnInfo.getWindowingStrategy()); - } - - fnRunner.startBundle(); - } - - @Override - @SuppressWarnings("unchecked") - public void processElement(Object elem) throws Exception { - if (fnRunner == null) { - reallyStartBundle(); - } - fnRunner.processElement((WindowedValue) elem); - } - - @Override - public void finishBundle() throws Exception { - if (fnRunner != null) { - fnRunner.finishBundle(); - fnRunner = null; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReifyTimestampAndWindowsParDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReifyTimestampAndWindowsParDoFn.java deleted file mode 100644 index 3e9e1a6e54..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReifyTimestampAndWindowsParDoFn.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; -import com.google.cloud.dataflow.sdk.util.ReifyTimestampAndWindowsDoFn; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; - -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A {@link ParDoFn} wrapping a {@link ReifyTimestampAndWindowsDoFn}. - */ -class ReifyTimestampAndWindowsParDoFn extends ParDoFnBase { - - static ReifyTimestampAndWindowsParDoFn of( - PipelineOptions options, - ReifyTimestampAndWindowsDoFn fn, - String stepName, - String transformName, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - - return new ReifyTimestampAndWindowsParDoFn( - options, fn, stepName, transformName, executionContext, addCounterMutator, stateSampler); - } - - /** - * A {@link ParDoFnFactory} to create instances of {@link ReifyTimestampAndWindowsParDoFn} - * according to specifications from the Dataflow service. - */ - static final class Factory implements ParDoFnFactory { - @Override - public ParDoFn create( - PipelineOptions options, - final CloudObject cloudUserFn, - String stepName, - String transformName, - @Nullable List sideInputInfos, - @Nullable List multiOutputInfos, - int numOutputs, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception { - - final ReifyTimestampAndWindowsDoFn fn = - new ReifyTimestampAndWindowsDoFn(); - - return ReifyTimestampAndWindowsParDoFn.of( - options, - fn, - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - } - } - - @Override - protected DoFnInfo getDoFnInfo() { - return new DoFnInfo<>(fn, null); - } - - private final ReifyTimestampAndWindowsDoFn fn; - - private ReifyTimestampAndWindowsParDoFn( - PipelineOptions options, - ReifyTimestampAndWindowsDoFn fn, - String stepName, - String transformName, - ExecutionContext executionContext, - AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super( - options, - NullSideInputReader.empty(), - Arrays.asList("output"), - stepName, - transformName, - executionContext, - addCounterMutator, - stateSampler); - this.fn = fn; - } -} From 7794247e509ce8c45b0b7eec0db34d46881f07bb Mon Sep 17 00:00:00 2001 From: lcwik Date: Fri, 5 Feb 2016 11:17:59 -0800 Subject: [PATCH 084/751] Move several operations and dependencies to worker module This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113967733 --- .../runners/worker/DataflowOutputCounter.java | 92 --- .../sdk/runners/worker/ParDoFnFactory.java | 51 -- .../worker/SourceOperationExecutor.java | 80 --- .../SourceOperationExecutorFactory.java | 32 - .../sdk/util/PerKeyCombineFnRunner.java | 16 +- .../util/common/worker/FlattenOperation.java | 59 -- .../util/common/worker/MapTaskExecutor.java | 129 ---- .../worker/OutputObjectAndByteCounter.java | 171 ------ .../sdk/util/common/worker/ParDoFn.java | 31 - .../util/common/worker/ParDoOperation.java | 76 --- .../worker/PartialGroupByKeyOperation.java | 576 ------------------ .../common/worker/ReceivingOperation.java | 55 -- .../sdk/util/common/worker/WorkExecutor.java | 109 ---- .../common/worker/WorkProgressUpdater.java | 257 -------- .../util/common/worker/WriteOperation.java | 113 ---- 15 files changed, 5 insertions(+), 1842 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowOutputCounter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperation.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperation.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReceivingOperation.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkProgressUpdater.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperation.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowOutputCounter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowOutputCounter.java deleted file mode 100644 index cd0323d08b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowOutputCounter.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservable; -import com.google.cloud.dataflow.sdk.util.common.worker.ElementCounter; -import com.google.cloud.dataflow.sdk.util.common.worker.OutputObjectAndByteCounter; -import com.google.common.annotations.VisibleForTesting; - -/** - * A Dataflow-specific version of {@link ElementCounter}, which specifies - * the object counter name differently as PhysicalElementCount. - * Additionally, it counts element windows as ElementCount. - */ -public class DataflowOutputCounter implements ElementCounter { - /** Number of physical element and multiple-window assignments that were serialized/processed. */ - private static final String OBJECT_COUNTER_NAME = "-PhysicalElementCount"; - /** Number of logical element and single window pairs that were processed. */ - private static final String ELEMENT_COUNTER_NAME = "-ElementCount"; - private static final String MEAN_BYTE_COUNTER_NAME = "-MeanByteCount"; - - private OutputObjectAndByteCounter objectAndByteCounter; - private Counter elementCount; - - public DataflowOutputCounter(String outputName, CounterSet.AddCounterMutator addCounterMutator) { - this(outputName, null, addCounterMutator); - } - - public DataflowOutputCounter( - String outputName, ElementByteSizeObservable elementByteSizeObservable, - CounterSet.AddCounterMutator addCounterMutator) { - objectAndByteCounter = - new OutputObjectAndByteCounter(elementByteSizeObservable, addCounterMutator); - objectAndByteCounter.countObject(outputName + OBJECT_COUNTER_NAME); - objectAndByteCounter.countMeanByte(outputName + MEAN_BYTE_COUNTER_NAME); - elementCount = - addCounterMutator.addCounter(Counter.longs(outputName + ELEMENT_COUNTER_NAME, SUM)); - } - - @Override - public void update(Object elem) throws Exception { - objectAndByteCounter.update(elem); - long windowsSize = ((WindowedValue) elem).getWindows().size(); - if (windowsSize == 0) { - // GroupingShuffleReader produces ValueInEmptyWindows. - // For now, we count the element at least once to keep the current counter - // behavior. - elementCount.addValue(1L); - } else { - elementCount.addValue(windowsSize); - } - } - - @Override - public void finishLazyUpdate(Object elem) { - objectAndByteCounter.finishLazyUpdate(elem); - } - - @VisibleForTesting - static String getElementCounterName(String prefix) { - return prefix + ELEMENT_COUNTER_NAME; - } - - @VisibleForTesting - static String getObjectCounterName(String prefix) { - return prefix + OBJECT_COUNTER_NAME; - } - - @VisibleForTesting - static String getMeanByteCounterName(String prefix) { - return prefix + MEAN_BYTE_COUNTER_NAME; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnFactory.java deleted file mode 100644 index cfb96645c7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ParDoFnFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.MultiOutputInfo; -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ParDoFn; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; - -import java.util.List; - -/** - * The interface of factories that create a worker-side {@link ParDoFn} from a {@link CloudObject} - * specification provided by the Dataflow service. - */ -public interface ParDoFnFactory { - - /** - * Creates a {@link ParDoFn} from standard parameters, corresponding to the specification - * provided to the worker by the Dataflow service. - */ - ParDoFn create( - PipelineOptions options, - CloudObject cloudUserFn, - String stepName, - String transformName, - List sideInputInfos, - List multiOutputInfos, - int numOutputs, - DataflowExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) - throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java deleted file mode 100644 index ad13e3a69a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutor.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.SourceOperationRequest; -import com.google.api.services.dataflow.model.SourceOperationResponse; -import com.google.api.services.dataflow.model.SourceSplitRequest; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.WorkExecutor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -/** - * An executor for a source operation, defined by a {@code SourceOperationRequest}. - */ -public class SourceOperationExecutor extends WorkExecutor { - private static final Logger LOG = LoggerFactory.getLogger(SourceOperationExecutor.class); - public static final String SPLIT_RESPONSE_TOO_LARGE_ERROR = - "Total size of the BoundedSource objects generated by splitIntoBundles() operation is larger" - + " than the allowable limit. For more information, please check the corresponding FAQ" - + " entry at https://cloud.google.com/dataflow/pipelines/troubleshooting-your-pipeline"; - - private final PipelineOptions options; - private final SourceOperationRequest request; - private SourceOperationResponse response; - - public SourceOperationExecutor(PipelineOptions options, - SourceOperationRequest request, - CounterSet counters) { - super(counters); - this.options = options; - this.request = request; - } - - @Override - public void execute() throws Exception { - LOG.debug("Executing source operation"); - SourceSplitRequest split = request.getSplit(); - if (split != null) { - this.response = WorkerCustomSources.performSplit(split, options); - } else { - throw new UnsupportedOperationException("Unsupported source operation request: " + request); - } - LOG.debug("Source operation execution complete"); - } - - public SourceOperationResponse getResponse() { - return response; - } - - static boolean isSplitResponseTooLarge(SourceOperationResponse operationResponse) { - try { - long splitResponseSize = - DataflowApiUtils.computeSerializedSizeBytes(operationResponse.getSplit()); - return splitResponseSize > WorkerCustomSources.DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES; - } catch (IOException e) { - /* Assume that the size is not too large, so that the actual API error is exposed. */ - LOG.warn("Error determining the size of the split response.", e); - return false; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutorFactory.java deleted file mode 100644 index 6c897004d4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceOperationExecutorFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.SourceOperationRequest; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -/** - * Creates a SourceOperationExecutor from a SourceOperation. - */ -public class SourceOperationExecutorFactory { - public static SourceOperationExecutor create( - PipelineOptions options, SourceOperationRequest request) throws Exception { - CounterSet counters = new CounterSet(); - return new SourceOperationExecutor(options, request, counters); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java index 516525a795..b5f328f014 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java @@ -19,7 +19,6 @@ import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.common.worker.PartialGroupByKeyOperation; import java.io.Serializable; import java.util.Collection; @@ -102,8 +101,7 @@ public AccumT mergeAccumulators( ///////////////////////////////////////////////////////////////////////////// /** - * Forwards the call to a {@link PerKeyCombineFn} to create the accumulator - * in a {@link PartialGroupByKeyOperation}. + * Forwards the call to a {@link PerKeyCombineFn} to create the accumulator. * *

    It constructs a {@code CombineWithContext.Context} from * {@link PipelineOptions} and {@link SideInputReader} if it is required. @@ -112,8 +110,7 @@ public AccumT createAccumulator(K key, PipelineOptions options, SideInputReader sideInputReader, Collection windows); /** - * Forwards the call to a {@link PerKeyCombineFn} to add the input - * in a {@link PartialGroupByKeyOperation}. + * Forwards the call to a {@link PerKeyCombineFn} to add the input. * *

    It constructs a {@code CombineWithContext.Context} from * {@link PipelineOptions} and {@link SideInputReader} if it is required. @@ -122,8 +119,7 @@ public AccumT addInput(K key, AccumT accumulator, InputT value, PipelineOptions SideInputReader sideInputReader, Collection windows); /** - * Forwards the call to a {@link PerKeyCombineFn} to merge accumulators - * in a {@link PartialGroupByKeyOperation}. + * Forwards the call to a {@link PerKeyCombineFn} to merge accumulators. * *

    It constructs a {@code CombineWithContext.Context} from * {@link PipelineOptions} and {@link SideInputReader} if it is required. @@ -132,8 +128,7 @@ public AccumT mergeAccumulators(K key, Iterable accumulators, PipelineOp SideInputReader sideInputReader, Collection windows); /** - * Forwards the call to a {@link PerKeyCombineFn} to extract the output - * in a {@link PartialGroupByKeyOperation}. + * Forwards the call to a {@link PerKeyCombineFn} to extract the output. * *

    It constructs a {@code CombineWithContext.Context} from * {@link PipelineOptions} and {@link SideInputReader} if it is required. @@ -142,8 +137,7 @@ public OutputT extractOutput(K key, AccumT accumulator, PipelineOptions options, SideInputReader sideInputReader, Collection windows); /** - * Forwards the call to a {@link PerKeyCombineFn} to compact the accumulator - * in a {@link PartialGroupByKeyOperation}. + * Forwards the call to a {@link PerKeyCombineFn} to compact the accumulator. * *

    It constructs a {@code CombineWithContext.Context} from * {@link PipelineOptions} and {@link SideInputReader} if it is required. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperation.java deleted file mode 100644 index fb6a48f35a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/FlattenOperation.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -/** - * A flatten operation. - */ -public class FlattenOperation extends ReceivingOperation { - public FlattenOperation(String operationName, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super(operationName, receivers, - counterPrefix, addCounterMutator, stateSampler); - } - - /** Invoked by tests. */ - public FlattenOperation(OutputReceiver outputReceiver, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - this("FlattenOperation", new OutputReceiver[]{ outputReceiver }, - counterPrefix, addCounterMutator, stateSampler); - } - - @Override - public void process(Object elem) throws Exception { - try (StateSampler.ScopedState process = - stateSampler.scopedState(processState)) { - checkStarted(); - Receiver receiver = receivers[0]; - if (receiver != null) { - receiver.process(elem); - } - } - } - - @Override - public boolean supportsRestart() { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutor.java deleted file mode 100644 index abe2e2063e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/MapTaskExecutor.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.ListIterator; - -/** - * An executor for a map task, defined by a list of Operations. - */ -public class MapTaskExecutor extends WorkExecutor { - private static final Logger LOG = LoggerFactory.getLogger(MapTaskExecutor.class); - - /** The operations in the map task, in execution order. */ - public final List operations; - - /** The StateSampler for tracking where time is being spent, or null. */ - protected final StateSampler stateSampler; - - /** - * Creates a new MapTaskExecutor. - * - * @param operations the operations of the map task, in order of execution - * @param counters a set of system counters associated with - * operations, which may get extended during execution - * @param stateSampler a state sampler for tracking where time is being spent - */ - public MapTaskExecutor( - List operations, CounterSet counters, StateSampler stateSampler) { - super(counters); - this.operations = operations; - this.stateSampler = stateSampler; - } - - @Override - public void execute() throws Exception { - LOG.debug("Executing map task"); - - try (StateSampler.ScopedState state - = stateSampler.scopedState( - stateSampler.stateForName("other", StateSampler.StateKind.FRAMEWORK))) { - // Start operations, in reverse-execution-order, so that a - // consumer is started before a producer might output to it. - // Starting a root operation such as a ReadOperation does the work - // of processing the input dataset. - LOG.debug("Starting operations"); - ListIterator iterator = operations.listIterator(operations.size()); - while (iterator.hasPrevious()) { - Operation op = iterator.previous(); - op.start(); - } - - // Finish operations, in forward-execution-order, so that a - // producer finishes outputting to its consumers before those - // consumers are themselves finished. - LOG.debug("Finishing operations"); - for (Operation op : operations) { - op.finish(); - } - } - - LOG.debug("Map task execution complete"); - - // TODO: support for success / failure ports? - } - - @Override - public NativeReader.Progress getWorkerProgress() throws Exception { - return getReadOperation().getProgress(); - } - - @Override - public StateSampler.StateSamplerInfo getWorkerStateSamplerInfo() throws Exception { - return stateSampler == null ? null : stateSampler.getInfo(); - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest splitRequest) throws Exception { - return getReadOperation().requestDynamicSplit(splitRequest); - } - - public ReadOperation getReadOperation() throws Exception { - if (operations == null || operations.isEmpty()) { - throw new IllegalStateException("Map task has no operation."); - } - - Operation readOperation = operations.get(0); - if (!(readOperation instanceof ReadOperation)) { - throw new IllegalStateException("First operation in the map task is not a ReadOperation."); - } - - return (ReadOperation) readOperation; - } - - @Override - public void close() throws Exception { - stateSampler.close(); - super.close(); - } - - public boolean supportsRestart() { - for (Operation op : operations) { - if (!op.supportsRestart()) { - return false; - } - } - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounter.java deleted file mode 100644 index 0cd7a0832b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputObjectAndByteCounter.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservable; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; - -import java.util.Random; - -/** - * An {@link ElementCounter} that counts output objects, bytes, and mean bytes. - */ -public class OutputObjectAndByteCounter implements ElementCounter { - // Might be null, e.g., undeclared outputs will not have an - // elementByteSizeObservable. - private final ElementByteSizeObservable elementByteSizeObservable; - private final CounterSet.AddCounterMutator addCounterMutator; - - private Random randomGenerator = new Random(); - - // Lowest sampling probability: 0.001%. - private static final int SAMPLING_TOKEN_UPPER_BOUND = 1000000; - private static final int SAMPLING_CUTOFF = 10; - private int samplingToken = 0; - - private Counter objectCount = null; - private Counter byteCount = null; - private Counter meanByteCount = null; - private ElementByteSizeObserver byteCountObserver = null; - private ElementByteSizeObserver meanByteCountObserver = null; - private int samplingTokenUpperBound = SAMPLING_TOKEN_UPPER_BOUND; - - @SuppressWarnings("unchecked") - public OutputObjectAndByteCounter( - ElementByteSizeObservable elementByteSizeObservable, - CounterSet.AddCounterMutator addCounterMutator) { - this.elementByteSizeObservable = (ElementByteSizeObservable) elementByteSizeObservable; - this.addCounterMutator = addCounterMutator; - } - - /** - * Count output objects. - */ - public OutputObjectAndByteCounter countObject(String objectCounterName) { - objectCount = addCounterMutator.addCounter(Counter.longs(objectCounterName, SUM)); - return this; - } - - /** - * Count output bytes. - */ - public OutputObjectAndByteCounter countBytes(String bytesCounterName) { - if (elementByteSizeObservable != null) { - byteCount = addCounterMutator.addCounter(Counter.longs(bytesCounterName, SUM)); - byteCountObserver = new ElementByteSizeObserver(byteCount); - } - return this; - } - - /** - * Count output mean byte. - */ - public OutputObjectAndByteCounter countMeanByte(String meanByteCounterName) { - if (elementByteSizeObservable != null) { - meanByteCount = addCounterMutator.addCounter(Counter.longs(meanByteCounterName, MEAN)); - meanByteCountObserver = new ElementByteSizeObserver(meanByteCount); - } - return this; - } - - /** - * Sets the minimum sampling rate to the inverse of the given value. - */ - public OutputObjectAndByteCounter setSamplingPeriod(int period) { - this.samplingTokenUpperBound = period * SAMPLING_CUTOFF; - return this; - } - - public Counter getObjectCount() { - return objectCount; - } - - public Counter getByteCount() { - return byteCount; - } - - public Counter getMeanByteCount() { - return meanByteCount; - } - - @Override - public void update(Object elem) throws Exception { - // Increment object counter. - if (objectCount != null) { - objectCount.addValue(1L); - } - - // Increment byte counter. - if ((byteCountObserver != null || meanByteCountObserver != null) - && (sampleElement() || elementByteSizeObservable.isRegisterByteSizeObserverCheap(elem))) { - if (byteCountObserver != null) { - byteCountObserver.setScalingFactor( - Math.max(samplingToken, SAMPLING_CUTOFF) / (double) SAMPLING_CUTOFF); - elementByteSizeObservable.registerByteSizeObserver(elem, byteCountObserver); - } - if (meanByteCountObserver != null) { - elementByteSizeObservable.registerByteSizeObserver(elem, meanByteCountObserver); - } - - if (byteCountObserver != null && !byteCountObserver.getIsLazy()) { - byteCountObserver.advance(); - } - if (meanByteCountObserver != null && !meanByteCountObserver.getIsLazy()) { - meanByteCountObserver.advance(); - } - } - } - - @Override - public void finishLazyUpdate(Object elem) { - // Advance lazy ElementByteSizeObservers, if any. - // Note that user's code is allowed to store the element of one - // DoFn.processElement() call and access it later on. We are still - // calling next() here, causing an update to byteCount. If user's - // code really accesses more element's pieces later on, their byte - // count would accrue against a future element. This is not ideal, - // but still approximately correct. - if (byteCountObserver != null && byteCountObserver.getIsLazy()) { - byteCountObserver.advance(); - } - if (meanByteCountObserver != null && meanByteCountObserver.getIsLazy()) { - meanByteCountObserver.advance(); - } - } - - protected boolean sampleElement() { - // Sampling probability decreases as the element count is increasing. - // We unconditionally sample the first samplingCutoff elements. For the - // next samplingCutoff elements, the sampling probability drops from 100% - // to 50%. The probability of sampling the Nth element is: - // min(1, samplingCutoff / N), with an additional lower bound of - // samplingCutoff / samplingTokenUpperBound. This algorithm may be refined - // later. - samplingToken = Math.min(samplingToken + 1, samplingTokenUpperBound); - return randomGenerator.nextInt(samplingToken) < SAMPLING_CUTOFF; - } - - public OutputObjectAndByteCounter setRandom(Random random) { - this.randomGenerator = random; - return this; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoFn.java deleted file mode 100644 index 828bc9e971..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoFn.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -/** - * Interface for functions invocable by {@link ParDoOperation} instances. - * - *

    To easily create a {@link ParDoFn} implementation with default setup, processing, - * and teardown, extend {@code ParDoFnBase}. - */ -public interface ParDoFn { - public void startBundle(Receiver... receivers) throws Exception; - - public void processElement(Object elem) throws Exception; - - public void finishBundle() throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperation.java deleted file mode 100644 index 2f3fa6521d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ParDoOperation.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.common.annotations.VisibleForTesting; - -/** - * A ParDo mapping function. - */ -public class ParDoOperation extends ReceivingOperation { - private final ParDoFn fn; - - public ParDoOperation(String operationName, - ParDoFn fn, - OutputReceiver[] outputReceivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super(operationName, outputReceivers, - counterPrefix, addCounterMutator, stateSampler); - this.fn = fn; - } - - @Override - public void start() throws Exception { - try (StateSampler.ScopedState start = - stateSampler.scopedState(startState)) { - super.start(); - fn.startBundle(receivers); - } - } - - @Override - public void process(Object elem) throws Exception { - try (StateSampler.ScopedState process = - stateSampler.scopedState(processState)) { - checkStarted(); - fn.processElement(elem); - } - } - - @Override - public void finish() throws Exception { - try (StateSampler.ScopedState finish = - stateSampler.scopedState(finishState)) { - checkStarted(); - fn.finishBundle(); - super.finish(); - } - } - - @Override - public boolean supportsRestart() { - return true; - } - - @VisibleForTesting - public ParDoFn getFn() throws Exception { - return fn; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java deleted file mode 100644 index 7004eac287..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/PartialGroupByKeyOperation.java +++ /dev/null @@ -1,576 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; - -/** - * A partial group-by-key operation. - */ -public class PartialGroupByKeyOperation extends ReceivingOperation { - /** - * Provides client-specific operations for grouping keys. - */ - public static interface GroupingKeyCreator { - public Object createGroupingKey(K key) throws Exception; - } - - /** - * Provides client-specific operations for size estimates. - */ - public static interface SizeEstimator { - public long estimateSize(T element) throws Exception; - } - - /** - * Provides client-specific operations for working with elements - * that are key/value or key/values pairs. - */ - public interface PairInfo { - public Iterable getKeysFromInputPair(Object pair); - public Object getValueFromInputPair(Object pair); - public Object makeOutputPair(Object key, Object value); - } - - /** - * Provides client-specific operations for combining values. - */ - public interface Combiner { - public AccumT createAccumulator(K key); - public AccumT add(K key, AccumT accumulator, InputT value); - public AccumT merge(K key, Iterable accumulators); - public AccumT compact(K key, AccumT accumulator); - public OutputT extract(K key, AccumT accumulator); - } - - // By default, how many bytes we allow the grouping table to consume before - // it has to be flushed. - static final long DEFAULT_MAX_GROUPING_TABLE_BYTES = 100_000_000L; - - // How many bytes a word in the JVM has. - static final int BYTES_PER_JVM_WORD = getBytesPerJvmWord(); - - /** - * The number of bytes of overhead to store an entry in the - * grouping table (a {@code HashMap}), - * ignoring the actual number of bytes in the keys and values: - *
      - *
    • an array element (1 word), - *
    • a HashMap.Entry (4 words), - *
    • a StructuralByteArray (1 words), - *
    • a backing array (guessed at 1 word for the length), - *
    • a KeyAndValues (2 words), - *
    • an ArrayList (2 words), - *
    • a backing array (1 word), - *
    • per-object overhead (JVM-specific, guessed at 2 words * 6 objects). - *
    - */ - static final int PER_KEY_OVERHEAD = 24 * BYTES_PER_JVM_WORD; - - final GroupingTable groupingTable; - - @SuppressWarnings("unchecked") - public PartialGroupByKeyOperation( - String operationName, - GroupingKeyCreator groupingKeyCreator, - SizeEstimator keySizeEstimator, SizeEstimator valueSizeEstimator, - PairInfo pairInfo, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - this(operationName, groupingKeyCreator, keySizeEstimator, valueSizeEstimator, null, pairInfo, - receivers, counterPrefix, addCounterMutator, stateSampler); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public PartialGroupByKeyOperation( - String operationName, - GroupingKeyCreator groupingKeyCreator, - SizeEstimator keySizeEstimator, SizeEstimator valueSizeEstimator, - Combiner combineFn, - PairInfo pairInfo, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super(operationName, receivers, counterPrefix, addCounterMutator, stateSampler); - if (combineFn == null) { - groupingTable = new BufferingGroupingTable(DEFAULT_MAX_GROUPING_TABLE_BYTES, - groupingKeyCreator, pairInfo, keySizeEstimator, valueSizeEstimator); - } else { - groupingTable = new CombiningGroupingTable(DEFAULT_MAX_GROUPING_TABLE_BYTES, - groupingKeyCreator, pairInfo, combineFn, keySizeEstimator, valueSizeEstimator); - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public PartialGroupByKeyOperation( - String operationName, - GroupingKeyCreator groupingKeyCreator, - SizeEstimator keySizeEstimator, SizeEstimator valueSizeEstimator, - double sizeEstimatorSampleRate, - Combiner combineFn, - PairInfo pairInfo, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - this(operationName, groupingKeyCreator, - new SamplingSizeEstimator(keySizeEstimator, sizeEstimatorSampleRate, 1.0), - new SamplingSizeEstimator(valueSizeEstimator, sizeEstimatorSampleRate, 1.0), combineFn, - pairInfo, receivers, counterPrefix, addCounterMutator, stateSampler); - } - - /** Invoked by tests. */ - public PartialGroupByKeyOperation(GroupingKeyCreator groupingKeyCreator, - SizeEstimator keySizeEstimator, SizeEstimator valueSizeEstimator, PairInfo pairInfo, - OutputReceiver outputReceiver, String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) { - this(groupingKeyCreator, - keySizeEstimator, valueSizeEstimator, null, pairInfo, - outputReceiver, - counterPrefix, - addCounterMutator, - stateSampler); - } - - /** Invoked by tests. */ - @SuppressWarnings({"rawtypes"}) - public PartialGroupByKeyOperation( - GroupingKeyCreator groupingKeyCreator, - SizeEstimator keySizeEstimator, SizeEstimator valueSizeEstimator, - Combiner combineFn, - PairInfo pairInfo, - OutputReceiver outputReceiver, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - this("PartialGroupByKeyOperation", groupingKeyCreator, - keySizeEstimator, valueSizeEstimator, combineFn, pairInfo, - new OutputReceiver[]{ outputReceiver }, - counterPrefix, - addCounterMutator, - stateSampler); - } - - @Override - public void process(Object elem) throws Exception { - try (StateSampler.ScopedState process = - stateSampler.scopedState(processState)) { - if (receivers[0] != null) { - groupingTable.put(elem, receivers[0]); - } - } - } - - @Override - public void finish() throws Exception { - try (StateSampler.ScopedState finish = - stateSampler.scopedState(finishState)) { - checkStarted(); - if (receivers[0] != null) { - groupingTable.flush(receivers[0]); - } - super.finish(); - } - } - - @Override - public boolean supportsRestart() { - // SizeEstimators are safe to be reused. - return true; - } - - /** - * Sets the maximum amount of memory the grouping table is allowed to - * consume before it has to be flushed. - */ - // @VisibleForTesting - public void setMaxGroupingTableBytes(long maxSize) { - groupingTable.maxSize = maxSize; - } - - /** - * Returns the amount of memory the grouping table currently consumes. - */ - // @VisibleForTesting - public long getGroupingTableBytes() { - return groupingTable.size; - } - - /** - * Returns the number of bytes in a JVM word. In case we failed to - * find the answer, returns 8. - */ - static int getBytesPerJvmWord() { - String wordSizeInBits = System.getProperty("sun.arch.data.model"); - try { - return Integer.parseInt(wordSizeInBits) / 8; - } catch (NumberFormatException e) { - // The JVM word size is unknown. Assume 64-bit. - return 8; - } - } - - private abstract static class GroupingTable { - - // Keep the table relatively full to increase the chance of collisions. - private static final double TARGET_LOAD = 0.9; - - private long maxSize; - private final GroupingKeyCreator groupingKeyCreator; - private final PairInfo pairInfo; - - private long size = 0; - private Map> table; - - public GroupingTable(long maxSize, - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo) { - this.maxSize = maxSize; - this.groupingKeyCreator = groupingKeyCreator; - this.pairInfo = pairInfo; - this.table = new HashMap<>(); - } - - interface GroupingTableEntry { - public K getKey(); - public AccumT getValue(); - public void add(InputT value) throws Exception; - public long getSize(); - public void compact() throws Exception; - } - - public abstract GroupingTableEntry createTableEntry(K key) throws Exception; - - /** - * Adds a pair to this table, possibly flushing some entries to output - * if the table is full. - */ - @SuppressWarnings("unchecked") - public void put(Object pair, Receiver receiver) throws Exception { - for (Object key : pairInfo.getKeysFromInputPair(pair)) { - put((K) key, - (InputT) pairInfo.getValueFromInputPair(pair), - receiver); - } - } - - /** - * Adds the key and value to this table, possibly flushing some entries - * to output if the table is full. - */ - public void put(K key, InputT value, Receiver receiver) throws Exception { - Object groupingKey = groupingKeyCreator.createGroupingKey(key); - GroupingTableEntry entry = table.get(groupingKey); - if (entry == null) { - entry = createTableEntry(key); - table.put(groupingKey, entry); - size += PER_KEY_OVERHEAD; - } else { - size -= entry.getSize(); - } - entry.add(value); - size += entry.getSize(); - - if (size >= maxSize) { - long targetSize = (long) (TARGET_LOAD * maxSize); - Iterator> entries = - table.values().iterator(); - while (size >= targetSize) { - if (!entries.hasNext()) { - // Should never happen, but sizes may be estimates... - size = 0; - break; - } - GroupingTableEntry toFlush = entries.next(); - entries.remove(); - size -= toFlush.getSize() + PER_KEY_OVERHEAD; - output(toFlush, receiver); - } - } - } - - /** - * Output the given entry. Does not actually remove it from the table or - * update this table's size. - */ - private void output(GroupingTableEntry entry, Receiver receiver) - throws Exception { - entry.compact(); - receiver.process(pairInfo.makeOutputPair(entry.getKey(), entry.getValue())); - } - - /** - * Flushes all entries in this table to output. - */ - public void flush(Receiver output) throws Exception { - for (GroupingTableEntry entry : table.values()) { - output(entry, output); - } - table.clear(); - size = 0; - } - - } - - /** - * A grouping table that simply buffers all inserted values in a list. - */ - public static class BufferingGroupingTable extends GroupingTable> { - - public final SizeEstimator keySizer; - public final SizeEstimator valueSizer; - - public BufferingGroupingTable(long maxSize, - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - SizeEstimator keySizer, - SizeEstimator valueSizer) { - super(maxSize, groupingKeyCreator, pairInfo); - this.keySizer = keySizer; - this.valueSizer = valueSizer; - } - - @Override - public GroupingTableEntry> createTableEntry(final K key) throws Exception { - return new GroupingTableEntry>() { - long size = keySizer.estimateSize(key); - final List values = new ArrayList<>(); - - @Override - public K getKey() { - return key; - } - - @Override - public List getValue() { - return values; - } - - @Override - public long getSize() { - return size; - } - - @Override - public void compact() { } - - @Override - public void add(V value) throws Exception { - values.add(value); - size += BYTES_PER_JVM_WORD + valueSizer.estimateSize(value); - } - }; - } - } - - /** - * A grouping table that uses the given combiner to combine values in place. - */ - public static class CombiningGroupingTable - extends GroupingTable { - - private final Combiner combiner; - private final SizeEstimator keySizer; - private final SizeEstimator accumulatorSizer; - - public CombiningGroupingTable(long maxSize, - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - Combiner combineFn, - SizeEstimator keySizer, - SizeEstimator accumulatorSizer) { - super(maxSize, groupingKeyCreator, pairInfo); - this.combiner = combineFn; - this.keySizer = keySizer; - this.accumulatorSizer = accumulatorSizer; - } - - @Override - public GroupingTableEntry createTableEntry(final K key) throws Exception { - return new GroupingTableEntry() { - final long keySize = keySizer.estimateSize(key); - AccumT accumulator = combiner.createAccumulator(key); - long accumulatorSize = 0; // never used before a value is added... - - @Override - public K getKey() { - return key; - } - - @Override - public AccumT getValue() { - return accumulator; - } - - @Override - public long getSize() { - return keySize + accumulatorSize; - } - - @Override - public void compact() throws Exception { - AccumT newAccumulator = combiner.compact(key, accumulator); - if (newAccumulator != accumulator) { - accumulator = newAccumulator; - accumulatorSize = accumulatorSizer.estimateSize(newAccumulator); - } - } - - @Override - public void add(InputT value) throws Exception { - accumulator = combiner.add(key, accumulator, value); - accumulatorSize = accumulatorSizer.estimateSize(accumulator); - } - }; - } - } - - - //////////////////////////////////////////////////////////////////////////// - // Size sampling. - - /** - * Implements size estimation by adaptively delegating to an underlying - * (potentially more expensive) estimator for some elements and returning - * the average value for others. - */ - public static class SamplingSizeEstimator implements SizeEstimator { - - /** - * The degree of confidence required in our expected value predictions - * before we allow under-sampling. - * - *

    The value of 3.0 is a confidence interval of about 99.7% for a - * a high-degree-of-freedom t-distribution. - */ - public static final double CONFIDENCE_INTERVAL_SIGMA = 3; - - /** - * The desired size of our confidence interval (relative to the measured - * expected value). - * - *

    The value of 0.25 is plus or minus 25%. - */ - public static final double CONFIDENCE_INTERVAL_SIZE = 0.25; - - /** - * Default number of elements that must be measured before elements are skipped. - */ - public static final long DEFAULT_MIN_SAMPLED = 20; - - private final SizeEstimator underlying; - private final double minSampleRate; - private final double maxSampleRate; - private final long minSampled; - private final Random random; - - private long totalElements = 0; - private long sampledElements = 0; - private long sampledSum = 0; - private double sampledSumSquares = 0; - private long estimate; - - private long nextSample = 0; - - public SamplingSizeEstimator( - SizeEstimator underlying, - double minSampleRate, - double maxSampleRate) { - this(underlying, minSampleRate, maxSampleRate, DEFAULT_MIN_SAMPLED, new Random()); - } - - public SamplingSizeEstimator(SizeEstimator underlying, - double minSampleRate, - double maxSampleRate, - long minSampled, - Random random) { - this.underlying = underlying; - this.minSampleRate = minSampleRate; - this.maxSampleRate = maxSampleRate; - this.minSampled = minSampled; - this.random = random; - } - - @Override - public long estimateSize(T element) throws Exception { - if (sampleNow()) { - return recordSample(underlying.estimateSize(element)); - } else { - return estimate; - } - } - - private boolean sampleNow() { - totalElements++; - return --nextSample < 0; - } - - private long recordSample(long value) { - sampledElements += 1; - sampledSum += value; - sampledSumSquares += value * value; - estimate = (long) Math.ceil(sampledSum / sampledElements); - long target = desiredSampleSize(); - if (sampledElements < minSampled || sampledElements < target) { - // Sample immediately. - nextSample = 0; - } else { - double rate = cap( - minSampleRate, - maxSampleRate, - Math.max(1.0 / (totalElements - minSampled + 1), // slowly ramp down - target / (double) totalElements)); // "future" target - // Uses the geometric distribution to return the likely distance between - // successive independent trials of a fixed probability p. This gives the - // same uniform distribution of branching on Math.random() < p, but with - // one random number generation per success rather than one - // per test, which can be a significant savings if p is small. - nextSample = rate == 1.0 - ? 0 - : (long) Math.floor(Math.log(random.nextDouble()) / Math.log(1 - rate)); - } - return value; - } - - private static final double cap(double min, double max, double value) { - return Math.min(max, Math.max(min, value)); - } - - private long desiredSampleSize() { - // We have no a-priori information on the actual distribution of data - // sizes, so compute our desired sample as if it were normal. - // Yes this formula is unstable for small stddev, but we only care about large stddev. - double mean = sampledSum / (double) sampledElements; - double sumSquareDiff = - (sampledSumSquares - (2 * mean * sampledSum) + (sampledElements * mean * mean)); - double stddev = Math.sqrt(sumSquareDiff / (sampledElements - 1)); - double sqrtDesiredSamples = - (CONFIDENCE_INTERVAL_SIGMA * stddev) / (CONFIDENCE_INTERVAL_SIZE * mean); - return (long) Math.ceil(sqrtDesiredSamples * sqrtDesiredSamples); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReceivingOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReceivingOperation.java deleted file mode 100644 index eb8f26cfd1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReceivingOperation.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -/** - * The abstract base class for Operations that have inputs and - * implement process(). - */ -public abstract class ReceivingOperation extends Operation implements Receiver { - - public ReceivingOperation(String operationName, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler, - StateSampler.StateKind stateKind) { - super(operationName, receivers, - counterPrefix, addCounterMutator, stateSampler, stateKind); - } - - public ReceivingOperation(String operationName, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super(operationName, receivers, - counterPrefix, addCounterMutator, stateSampler); - } - - /** - * Adds an input to this Operation, coming from the given - * output of the given source Operation. - */ - public void attachInput(Operation source, int outputNum) { - checkUnstarted(); - OutputReceiver fanOut = source.receivers[outputNum]; - fanOut.addOutput(this); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutor.java deleted file mode 100644 index 2d8dfa6971..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkExecutor.java +++ /dev/null @@ -1,109 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.Metric; -import com.google.cloud.dataflow.sdk.util.common.Metric.DoubleMetric; - -import com.sun.management.OperatingSystemMXBean; - -import java.lang.management.ManagementFactory; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Abstract executor for WorkItem tasks. - */ -@SuppressWarnings("resource") -public abstract class WorkExecutor implements AutoCloseable { - /** The output counters for this task. */ - private final CounterSet outputCounters; - - /** - * OperatingSystemMXBean for reporting CPU usage. - * - *

    Uses com.sun.management.OperatingSystemMXBean instead of - * java.lang.management.OperatingSystemMXBean because the former supports - * getProcessCpuLoad(). - */ - private final OperatingSystemMXBean os; - - /** - * Constructs a new WorkExecutor task. - */ - public WorkExecutor(CounterSet outputCounters) { - this.outputCounters = outputCounters; - this.os = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); - } - - /** - * Returns the set of output counters for this task. - */ - public CounterSet getOutputCounters() { - return outputCounters; - } - - /** - * Returns a collection of output metrics for this task. - */ - public Collection> getOutputMetrics() { - List> outputMetrics = new ArrayList<>(); - outputMetrics.add(new DoubleMetric("CPU", os.getProcessCpuLoad())); - // More metrics as needed. - return outputMetrics; - } - - /** - * Executes the task. - */ - public abstract void execute() throws Exception; - - /** - * Returns the worker's current progress. - */ - public NativeReader.Progress getWorkerProgress() throws Exception { - // By default, return null indicating worker progress not available. - return null; - } - - /** - * See {@link NativeReader.NativeReaderIterator#requestDynamicSplit}. - * Makes sense only for tasks that read input. - */ - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest splitRequest) throws Exception { - // By default, dynamic splitting is unsupported. - return null; - } - - /** - * Returns the worker's current state sampler info, or null if the - * state sampling is not enabled. - */ - @Nullable public StateSampler.StateSamplerInfo getWorkerStateSamplerInfo() throws Exception { - return null; - } - - @Override - public void close() throws Exception { - // By default, nothing to close or shut down. - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkProgressUpdater.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkProgressUpdater.java deleted file mode 100644 index 285f03f7b8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WorkProgressUpdater.java +++ /dev/null @@ -1,257 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import javax.annotation.concurrent.NotThreadSafe; - -/** - * WorkProgressUpdater allows a work executor to send work progress - * updates to the worker service. The life-cycle of the - * WorkProgressUpdater is controlled externally through its - * {@link #startReportingProgress()} and - * {@link #stopReportingProgress()} methods. The updater queries the - * worker for progress updates and sends the updates to the worker - * service. The interval between two consecutive updates is - * controlled by the worker service through reporting interval hints - * sent back in the update response messages. To avoid update storms - * and monitoring staleness, the interval between two consecutive - * updates is also bound by {@link #getMinReportingInterval} and - * {@link #getMaxReportingInterval}. - */ -@NotThreadSafe -public abstract class WorkProgressUpdater { - private static final Logger LOG = LoggerFactory.getLogger(WorkProgressUpdater.class); - - /** The default lease duration to request from the external worker service (3 minutes). */ - public static final long DEFAULT_LEASE_DURATION_MILLIS = 3 * 60 * 1000; - - /** The lease renewal RPC latency margin (5 seconds). */ - private static final long DEFAULT_LEASE_RENEWAL_LATENCY_MARGIN = 5000; - - /** - * The minimum period between two consecutive progress updates. Ensures the - * {@link WorkProgressUpdater} does not generate update storms (5 seconds). - */ - private static final long DEFAULT_MIN_REPORTING_INTERVAL_MILLIS = 5000; - - /** - * The maximum period between two consecutive progress updates. Ensures the - * {@link WorkProgressUpdater} does not cause monitoring staleness (10 minutes). - */ - private static final long DEFAULT_MAX_REPORTING_INTERVAL_MILLIS = 10 * 60 * 1000; - - /** Worker providing the work progress updates. */ - protected final WorkExecutor worker; - - /** Executor used to schedule work progress updates. */ - private final ScheduledExecutorService executor; - - /** The lease duration to request from the external worker service. */ - protected long requestedLeaseDurationMs; - - /** The time period until the next work progress update. */ - protected long progressReportIntervalMs; - - /** - * The {@link NativeReader.DynamicSplitResult} to report to the service in the next - * progress update, or {@code null} if there is nothing to report (if no dynamic split happened - * since the last progress update). - */ - protected NativeReader.DynamicSplitResult dynamicSplitResultToReport; - - public WorkProgressUpdater(WorkExecutor worker) { - this.worker = worker; - this.executor = Executors.newSingleThreadScheduledExecutor( - new ThreadFactoryBuilder().setDaemon(true).setNameFormat("WorkProgressUpdater-%d").build()); - } - - /** - * Starts sending work progress updates to the worker service. - */ - public void startReportingProgress() { - // The initial work progress report is sent according to hints from the service if any. - // Otherwise the default is half-way through the lease. - long leaseRemainingTime = leaseRemainingTime(getWorkUnitLeaseExpirationTimestamp()); - progressReportIntervalMs = - nextProgressReportInterval( - getWorkUnitSuggestedReportingInterval(), leaseRemainingTime); - requestedLeaseDurationMs = DEFAULT_LEASE_DURATION_MILLIS; - - LOG.debug("Started reporting progress for work item: {}", workString()); - scheduleNextUpdate(); - } - - /** - * Stops sending work progress updates to the worker service. - * It may throw an exception if the final progress report fails to be sent for some reason. - */ - public void stopReportingProgress() throws Exception { - // TODO: Redesign to get rid of the executor and use a dedicated - // thread with a sleeper. Also unify with success/failure reporting. - - // Wait until there are no more progress updates in progress, then - // shut down. - synchronized (executor) { - executor.shutdownNow(); - } - - // We send a final progress report in case there was an unreported dynamic split. - if (dynamicSplitResultToReport != null) { - LOG.debug("Sending final progress update with unreported split: {} " - + "for work item: {}", dynamicSplitResultToReport, workString()); - reportProgressHelper(); // This call can fail with an exception - } - - LOG.debug("Stopped reporting progress for work item: {}", workString()); - } - - /** - * Computes the time before sending the next work progress update making sure - * that it falls between the [{@link #getMinReportingInterval}, - * {@link #getMaxReportingInterval}] interval. Makes an attempt to bound - * the result by the remaining lease time, with an RPC latency margin of - * {@link #getLeaseRenewalLatencyMargin}. - * - * @param suggestedInterval the suggested progress report interval - * @param leaseRemainingTime milliseconds left before the work lease expires - * @return the time in milliseconds before sending the next progress update - */ - protected final long nextProgressReportInterval( - long suggestedInterval, long leaseRemainingTime) { - // Try to send the next progress update before the next lease expiration - // allowing some RPC latency margin. - suggestedInterval = - Math.min(suggestedInterval, leaseRemainingTime - getLeaseRenewalLatencyMargin()); - - // Bound reporting interval to avoid staleness and progress update storms. - return Math.min( - Math.max(getMinReportingInterval(), suggestedInterval), getMaxReportingInterval()); - } - - /** - * Schedules the next work progress update. - */ - private void scheduleNextUpdate() { - if (executor.isShutdown()) { - return; - } - executor.schedule(new Runnable() { - @Override - public void run() { - // Don't shut down while reporting progress. - synchronized (executor) { - if (executor.isShutdown()) { - return; - } - reportProgress(); - } - } - }, - progressReportIntervalMs, TimeUnit.MILLISECONDS); - LOG.debug("Next work progress update for work item {} scheduled to occur in {} ms.", - workString(), progressReportIntervalMs); - } - - /** - * Reports the current work progress to the worker service. - */ - private void reportProgress() { - LOG.debug("Updating progress on work item {}", workString()); - try { - reportProgressHelper(); - } catch (Throwable e) { - LOG.warn("Error reporting workitem progress update to Dataflow service: ", e); - } finally { - scheduleNextUpdate(); - } - } - - /** - * Computes the amount of time left, in milliseconds, before a lease - * with the specified expiration timestamp expires. Returns zero if - * the lease has already expired. - */ - protected long leaseRemainingTime(long leaseExpirationTimestamp) { - long now = System.currentTimeMillis(); - if (leaseExpirationTimestamp < now) { - LOG.debug("Lease remaining time for {} is 0 ms.", workString()); - return 0; - } - LOG.debug( - "Lease remaining time for {} is {} ms.", workString(), leaseExpirationTimestamp - now); - return leaseExpirationTimestamp - now; - } - - // Visible for testing. - public NativeReader.DynamicSplitResult getDynamicSplitResultToReport() { - return dynamicSplitResultToReport; - } - - /** - * Reports the current work progress to the worker service. - */ - protected abstract void reportProgressHelper() throws Exception; - - /** - * Returns the current work item's lease expiration timestamp. - */ - protected abstract long getWorkUnitLeaseExpirationTimestamp(); - - /** - * Returns the current work item's suggested progress reporting interval. - */ - protected long getWorkUnitSuggestedReportingInterval() { - return leaseRemainingTime(getWorkUnitLeaseExpirationTimestamp()) / 2; - } - - /** - * Returns the minimum allowed time between two periodic progress updates. - */ - protected long getMinReportingInterval() { - return DEFAULT_MIN_REPORTING_INTERVAL_MILLIS; - } - - /** - * Returns the maximum allowed time between two periodic progress updates. - */ - protected long getMaxReportingInterval() { - return DEFAULT_MAX_REPORTING_INTERVAL_MILLIS; - } - - /** - * Returns the maximum allowed time between a periodic progress update and the moment - * the current lease expires. - */ - protected long getLeaseRenewalLatencyMargin() { - return DEFAULT_LEASE_RENEWAL_LATENCY_MARGIN; - } - - /** - * Returns a string representation of the work item whose progress - * is being updated, for use in logging messages. - */ - protected abstract String workString(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperation.java deleted file mode 100644 index 31ed07d5fc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/WriteOperation.java +++ /dev/null @@ -1,113 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -/** - * A write operation. - */ -public class WriteOperation extends ReceivingOperation { - /** - * The Sink this operation writes to. - */ - public final Sink sink; - - /** - * The total byte counter for all data written by this operation. - */ - final Counter byteCount; - - /** - * The Sink's writer this operation writes to, created by start(). - */ - Sink.SinkWriter writer; - - public WriteOperation(String operationName, - Sink sink, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super(operationName, receivers, - counterPrefix, addCounterMutator, stateSampler, sink.getStateSamplerStateKind()); - this.sink = sink; - this.byteCount = addCounterMutator.addCounter( - Counter.longs(bytesCounterName(counterPrefix, operationName), SUM)); - } - - /** Invoked by tests. */ - public WriteOperation(Sink sink, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - this("WriteOperation", sink, new OutputReceiver[]{ }, - counterPrefix, addCounterMutator, stateSampler); - } - - protected String bytesCounterName(String counterPrefix, - String operationName) { - return operationName + "-ByteCount"; - } - - public Sink getSink() { - return sink; - } - - @Override - public void start() throws Exception { - try (StateSampler.ScopedState start = - stateSampler.scopedState(startState)) { - assert start != null; - super.start(); - writer = (Sink.SinkWriter) sink.writer(); - } - } - - @Override - public void process(Object outputElem) throws Exception { - try (StateSampler.ScopedState process = - stateSampler.scopedState(processState)) { - assert process != null; - checkStarted(); - byteCount.addValue(writer.add(outputElem)); - } - } - - @Override - public void finish() throws Exception { - try (StateSampler.ScopedState finish = - stateSampler.scopedState(finishState)) { - assert finish != null; - checkStarted(); - writer.close(); - super.finish(); - } - } - - @Override - public boolean supportsRestart() { - return sink.supportsRestart(); - } - - public Counter getByteCount() { - return byteCount; - } -} From 085469d0fbadada98afe0d04c25f3e09d6fa409c Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 5 Feb 2016 11:22:34 -0800 Subject: [PATCH 085/751] Split InMemoryBundle into Read/Write only interfaces This allows transform evaluators to write to a bundle but provide a single immutable object representing that bundle after processing completes, as well as deferring setting bundle attributes until the bundle has been completed, rather than when it starts. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113968310 --- .../inprocess/InProcessPipelineRunner.java | 74 +++++-- .../inprocess/InProcessTransformResult.java | 7 +- .../runners/inprocess/TransformEvaluator.java | 6 +- .../inprocess/TransformEvaluatorFactory.java | 4 +- .../BoundedReadEvaluatorFactory.java | 7 +- .../evaluator/FlattenEvaluatorFactory.java | 14 +- .../evaluator/GroupByKeyEvaluatorFactory.java | 15 +- .../evaluator/ParDoInProcessEvaluator.java | 14 +- .../evaluator/ParDoMultiEvaluatorFactory.java | 13 +- .../ParDoSingleEvaluatorFactory.java | 32 +-- .../UnboundedReadEvaluatorFactory.java | 7 +- .../evaluator/ViewEvaluatorFactory.java | 2 +- .../ImmutableInProcessTransformResult.java | 20 +- .../util/InMemoryWatermarkManager.java | 21 +- .../inprocess/util/InProcessBundle.java | 83 ++++--- .../util/InProcessBundleOutputManager.java | 51 +++++ .../cloud/dataflow/sdk/util/TimeDomain.java | 2 +- .../BoundedReadEvaluatorFactoryTest.java | 20 +- .../FlattenEvaluatorFactoryTest.java | 32 +-- .../GroupByKeyEvaluatorFactoryTest.java | 48 ++--- .../ParDoMultiEvaluatorFactoryTest.java | 26 ++- .../ParDoSingleEvaluatorFactoryTest.java | 14 +- .../UnboundedReadEvaluatorFactoryTest.java | 18 +- .../evaluator/ViewEvaluatorFactoryTest.java | 5 +- .../util/InMemoryWatermarkManagerTest.java | 204 +++++++++--------- .../inprocess/util/InProcessBundleTest.java | 53 ++++- 26 files changed, 487 insertions(+), 305 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleOutputManager.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 399d1c85a2..10ac123143 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -23,9 +23,11 @@ import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.TimerInternals; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; @@ -33,6 +35,8 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; +import org.joda.time.Instant; + import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -61,17 +65,37 @@ public class InProcessPipelineRunner { /** * Part of a {@link PCollection}. Elements are output to a bundle, which will cause them to be * executed by {@link PTransform PTransforms} that consume the {@link PCollection} this bundle is - * a part of at a later point. - * @param + * a part of at a later point. This is an uncommitted bundle and can have elements added to it. + * + * @param the type of elements that can be added to this bundle */ - public static interface Bundle { + public static interface UncommittedBundle { /** * Outputs an element to this bundle. * * @param element the element to add to this bundle * @return this bundle */ - Bundle add(WindowedValue element); + UncommittedBundle add(WindowedValue element); + + /** + * Commits this {@link UncommittedBundle}, returning an immutable {@link CommittedBundle} + * containing all of the elements that were added to it. The {@link #add(WindowedValue)} method + * will throw an {@link IllegalStateException} if called after a call to commit. + * @param synchronizedProcessingTime the synchronized processing time at which this bundle was + * committed + */ + CommittedBundle commit(Instant synchronizedProcessingTime); + } + + /** + * Part of a {@link PCollection}. Elements are output to an {@link UncommittedBundle}, which will + * eventually committed. Committed elements are executed by the {@link PTransform PTransforms} + * that consume the {@link PCollection} this bundle is + * a part of at a later point. + * @param the type of elements contained within this bundle + */ + public static interface CommittedBundle { /** * @return the PCollection that the elements of this bundle belong to @@ -92,9 +116,20 @@ public static interface Bundle { /** * @return an {@link Iterable} containing all of the elements that have been added to this - * {@link Bundle} + * {@link CommittedBundle} */ Iterable> getElements(); + + /** + * Returns the processing time output watermark at the time the producing {@link PTransform} + * committed this bundle. Downstream synchronized processing time watermarks cannot progress + * past this point before consuming this bundle. + * + *

    This value is no greater than the earliest incomplete processing time or synchronized + * processing time {@link TimerData timer} at the time this bundle was committed, including any + * timers that fired to produce this bundle. + */ + Instant getSynchronizedProcessingOutputWatermark(); } /** @@ -114,20 +149,19 @@ public static interface PCollectionViewWriter { * thread that requires it. */ public static class InProcessExecutionContext - extends com.google.cloud.dataflow.sdk.util.BaseExecutionContext { + extends BaseExecutionContext { @Override - protected InMemoryStepContext createStepContext( + protected InProcessStepContext createStepContext( String stepName, String transformName, StateSampler stateSampler) { - return new InMemoryStepContext(this, stepName, transformName); + return new InProcessStepContext(this, stepName, transformName); } /** * Step Context for the InMemoryPipelineRunner. */ - public class InMemoryStepContext + public class InProcessStepContext extends com.google.cloud.dataflow.sdk.util.BaseExecutionContext.StepContext { - public InMemoryStepContext( + public InProcessStepContext( InProcessExecutionContext executionContext, String stepName, String transformName) { super(executionContext, stepName, transformName); } @@ -154,20 +188,22 @@ public TimerInternals timerInternals() { */ public static interface InProcessEvaluationContext { /** - * Create a bundle for use by a source. + * Create a {@link UncommittedBundle} for use by a source. */ - Bundle createRootBundle(PCollection output); + UncommittedBundle createRootBundle(PCollection output); /** - * Create a {@link Bundle} whose elements belong to the specified {@link PCollection}. + * Create a {@link UncommittedBundle} whose elements belong to the specified {@link + * PCollection}. */ - Bundle createBundle(Bundle input, PCollection output); + UncommittedBundle createBundle(CommittedBundle input, PCollection output); /** - * Create a {@link Bundle} with the specified keys at the specified step. For use by + * Create a {@link UncommittedBundle} with the specified keys at the specified step. For use by * {@link GroupByKeyOnly} {@link PTransform PTransforms}. */ - Bundle createKeyedBundle(Bundle input, Object key, PCollection output); + UncommittedBundle createKeyedBundle( + CommittedBundle input, Object key, PCollection output); /** * Create a bundle whose elements will be used in a PCollectionView. @@ -229,12 +265,12 @@ public static interface InProcessExecutor { * @param consumer the {@link AppliedPTransform} to schedule * @param bundle the input bundle to the consumer */ - void scheduleConsumption(AppliedPTransform consumer, Bundle bundle); + void scheduleConsumption(AppliedPTransform consumer, CommittedBundle bundle); /** * Blocks until the job being executed enters a terminal state. A job is completed after all * root {@link AppliedPTransform AppliedPTransforms} have completed, and all - * {@link Bundle Bundles} have been consumed. Jobs may also terminate abnormally. + * {@link CommittedBundle Bundles} have been consumed. Jobs may also terminate abnormally. */ void awaitCompletion(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java index aad0c7613f..c44f77c863 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -15,7 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.common.CounterSet; @@ -34,9 +34,10 @@ public interface InProcessTransformResult { AppliedPTransform getTransform(); /** - * @return the {@link Bundle Bundles} produced by this transform + * Returns the {@link UncommittedBundle (uncommitted) Bundles} output by this transform. These + * will be committed by the evaluation context as part of completing this result. */ - Iterable> getBundles(); + Iterable> getOutputBundles(); /** * @return the {@link CounterSet} used by this {@link PTransform}, or null if this transform did diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java index c8bccb3596..270557d55c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java @@ -15,18 +15,18 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.util.WindowedValue; /** * An evaluator of a specific application of a transform. Will be used for at least one - * {@link Bundle}. + * {@link CommittedBundle}. * * @param the type of elements that will be passed to {@link #processElement} */ public interface TransformEvaluator { /** - * Process an element in the input {@link Bundle}. + * Process an element in the input {@link CommittedBundle}. * * @param element the element to process */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java index 25cb6cc30c..7941c1651b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java @@ -15,7 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -36,6 +36,6 @@ public interface TransformEvaluatorFactory { * made available to the caller. */ TransformEvaluator forApplication( - AppliedPTransform application, @Nullable Bundle inputBundle, + AppliedPTransform application, @Nullable CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java index bffaeea974..7679fa78ac 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java @@ -17,8 +17,9 @@ import com.google.cloud.dataflow.sdk.io.Read.Bounded; import com.google.cloud.dataflow.sdk.io.Source.Reader; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -52,7 +53,7 @@ public class BoundedReadEvaluatorFactory implements TransformEvaluatorFactory { @Override public TransformEvaluator forApplication( AppliedPTransform application, - @Nullable Bundle inputBundle, + @Nullable CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { return getTransformEvaluator((AppliedPTransform) application, evaluationContext); } @@ -97,7 +98,7 @@ public void processElement(WindowedValue element) {} @Override public InProcessTransformResult finishBundle() throws IOException { - Bundle output = evaluationContext.createRootBundle(transform.getOutput()); + UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); while (contentsRemaining) { output.add( WindowedValue.timestampedValueInGlobalWindow( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java index 61ccc5e152..29910b29b3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java @@ -16,8 +16,9 @@ package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -39,7 +40,7 @@ public class FlattenEvaluatorFactory implements TransformEvaluatorFactory { @Override public TransformEvaluator forApplication( AppliedPTransform application, - Bundle inputBundle, + CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { return createInMemoryEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); } @@ -48,9 +49,9 @@ private TransformEvaluator createInMemoryEvaluator( final AppliedPTransform< PCollectionList, PCollection, FlattenPCollectionList> application, - final Bundle inputBundle, + final CommittedBundle inputBundle, final InProcessEvaluationContext evaluationContext) { - final Bundle outputBundle = + final UncommittedBundle outputBundle = evaluationContext.createBundle(inputBundle, application.getOutput()); final InProcessTransformResult result = ImmutableInProcessTransformResult.withoutHold(application).addOutput(outputBundle).build(); @@ -58,10 +59,11 @@ private TransformEvaluator createInMemoryEvaluator( } private static class FlattenEvaluator implements TransformEvaluator { - private final Bundle outputBundle; + private final UncommittedBundle outputBundle; private final InProcessTransformResult result; - public FlattenEvaluator(Bundle outputBundle, InProcessTransformResult result) { + public FlattenEvaluator( + UncommittedBundle outputBundle, InProcessTransformResult result) { this.outputBundle = outputBundle; this.result = result; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java index f5cf86186f..7598b1e495 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java @@ -21,8 +21,9 @@ import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -51,17 +52,17 @@ public class GroupByKeyEvaluatorFactory implements TransformEvaluatorFactory { @SuppressWarnings({"unchecked", "rawtypes"}) public TransformEvaluator forApplication( AppliedPTransform application, - Bundle inputBundle, + CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { return createEvaluator( - (AppliedPTransform) application, (Bundle) inputBundle, evaluationContext); + (AppliedPTransform) application, (CommittedBundle) inputBundle, evaluationContext); } private TransformEvaluator> createEvaluator( final AppliedPTransform< PCollection>, PCollection>>, GroupByKeyOnly> application, - final Bundle> inputBundle, + final CommittedBundle> inputBundle, final InProcessEvaluationContext evaluationContext) { return new GroupByKeyEvaluator(evaluationContext, inputBundle, application); } @@ -69,7 +70,7 @@ private TransformEvaluator> createEvaluator( private static class GroupByKeyEvaluator implements TransformEvaluator> { private final InProcessEvaluationContext evaluationContext; - private final Bundle> inputBundle; + private final CommittedBundle> inputBundle; private final AppliedPTransform< PCollection>, PCollection>>, GroupByKeyOnly> application; @@ -78,7 +79,7 @@ private static class GroupByKeyEvaluator implements TransformEvaluator> inputBundle, + CommittedBundle> inputBundle, AppliedPTransform< PCollection>, PCollection>>, GroupByKeyOnly> application) { @@ -128,7 +129,7 @@ public InProcessTransformResult finishBundle() { for (Map.Entry, List> groupedEntry : groupingMap.entrySet()) { K key = groupedEntry.getKey().key; KV> groupedKv = KV.>of(key, groupedEntry.getValue()); - Bundle>> bundle = + UncommittedBundle>> bundle = evaluationContext.createKeyedBundle(inputBundle, key, application.getOutput()); bundle.add(WindowedValue.valueInEmptyWindows(groupedKv)); resultBuilder.addOutput(bundle); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java index 86cc89ce4c..797a175f4d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java @@ -15,7 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -36,11 +36,11 @@ class ParDoInProcessEvaluator { private final DoFnRunner fnRunner; private final AppliedPTransform, ?, ?> transform; private final CounterSet counters; - private final Collection> outputBundles; + private final Collection> outputBundles; public ParDoInProcessEvaluator(DoFnRunner fnRunner, AppliedPTransform, ?, ?> transform, CounterSet counters, - Collection> outputBundles) { + Collection> outputBundles) { this.fnRunner = fnRunner; this.transform = transform; this.counters = counters; @@ -62,13 +62,13 @@ public InProcessTransformResult finishBundle() { } static class BundleOutputManager implements OutputManager { - private final Map, Bundle> bundles; + private final Map, UncommittedBundle> bundles; - public static BundleOutputManager create(Map, Bundle> outputBundles) { + public static BundleOutputManager create(Map, UncommittedBundle> outputBundles) { return new BundleOutputManager(outputBundles); } - public BundleOutputManager(Map, Bundle> bundles) { + private BundleOutputManager(Map, UncommittedBundle> bundles) { this.bundles = bundles; } @@ -76,7 +76,7 @@ public BundleOutputManager(Map, Bundle> bundles) { @Override public void output(TupleTag tag, WindowedValue output) { @SuppressWarnings("rawtypes") - Bundle bundle = bundles.get(tag); + UncommittedBundle bundle = bundles.get(tag); bundle.add(output); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java index 3b2309e1c4..c6ee134581 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java @@ -16,10 +16,11 @@ package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InMemoryStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InProcessStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -47,7 +48,7 @@ public class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory { @Override public TransformEvaluator forApplication( AppliedPTransform application, - Bundle inputBundle, + CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { @SuppressWarnings({"unchecked", "rawtypes"}) final ParDoInProcessEvaluator multiEvaluator = @@ -67,11 +68,11 @@ public InProcessTransformResult finishBundle() { private static ParDoInProcessEvaluator createMultiEvaluator( AppliedPTransform, PCollectionTuple, BoundMulti> application, - Bundle inputBundle, + CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { PCollectionTuple output = application.getOutput(); Map, PCollection> outputs = output.getAll(); - Map, Bundle> outputBundles = new HashMap<>(); + Map, UncommittedBundle> outputBundles = new HashMap<>(); for (Map.Entry, PCollection> outputEntry : outputs.entrySet()) { outputBundles.put( outputEntry.getKey(), @@ -79,7 +80,7 @@ private static ParDoInProcessEvaluator createMultiEvaluator( } InProcessExecutionContext executionContext = evaluationContext.getExecutionContext(application); String stepName = evaluationContext.getStepName(application); - InMemoryStepContext stepContext = + InProcessStepContext stepContext = executionContext.getOrCreateStepContext(stepName, stepName, null); CounterSet counters = evaluationContext.createCounterSet(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java index 33144e7b67..c6e3f8accc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java @@ -16,10 +16,11 @@ package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InMemoryStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InProcessStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -44,7 +45,7 @@ public class ParDoSingleEvaluatorFactory implements TransformEvaluatorFactory { @Override public TransformEvaluator forApplication( final AppliedPTransform application, - Bundle inputBundle, + CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { @SuppressWarnings({"unchecked", "rawtypes"}) final ParDoInProcessEvaluator evaluator = @@ -64,28 +65,29 @@ public InProcessTransformResult finishBundle() { return singleEvaluator; } - private static ParDoInProcessEvaluator createSingleEvaluator( - @SuppressWarnings("rawtypes") - AppliedPTransform, PCollection, Bound> application, - Bundle inputBundle, - InProcessEvaluationContext evaluationContext) { - TupleTag mainOutputTag = new TupleTag<>("out"); - Bundle outputBundle = evaluationContext.createBundle(inputBundle, application.getOutput()); + private static ParDoInProcessEvaluator createSingleEvaluator( + @SuppressWarnings("rawtypes") AppliedPTransform, PCollection, + Bound> application, + CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { + TupleTag mainOutputTag = new TupleTag<>("out"); + UncommittedBundle outputBundle = + evaluationContext.createBundle(inputBundle, application.getOutput()); InProcessExecutionContext executionContext = evaluationContext.getExecutionContext(application); String stepName = evaluationContext.getStepName(application); - InMemoryStepContext stepContext = + InProcessStepContext stepContext = executionContext.getOrCreateStepContext(stepName, stepName, null); CounterSet counters = evaluationContext.createCounterSet(); - DoFnRunner runner = + DoFnRunner runner = DoFnRunners.createDefault( evaluationContext.getPipelineOptions(), application.getTransform().getFn(), evaluationContext.createSideInputReader(application.getTransform().getSideInputs()), BundleOutputManager.create( - Collections., Bundle>singletonMap(mainOutputTag, outputBundle)), + Collections., UncommittedBundle>singletonMap( + mainOutputTag, outputBundle)), mainOutputTag, Collections.>emptyList(), stepContext, @@ -93,7 +95,7 @@ private static ParDoInProcessEvaluator createSingleEvaluator( application.getInput().getWindowingStrategy()); runner.startBundle(); - return new ParDoInProcessEvaluator( - runner, application, counters, Collections.>singleton(outputBundle)); + return new ParDoInProcessEvaluator( + runner, application, counters, Collections.>singleton(outputBundle)); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java index 9a5e3aa694..e40941edde 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java @@ -20,8 +20,9 @@ import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -53,7 +54,7 @@ public class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory @Override public TransformEvaluator forApplication( AppliedPTransform application, - @Nullable Bundle inputBundle, + @Nullable CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { return getTransformEvaluator((AppliedPTransform) application, evaluationContext); } @@ -91,7 +92,7 @@ public void processElement(WindowedValue element) {} @Override public InProcessTransformResult finishBundle() throws IOException { - Bundle output = evaluationContext.createRootBundle(transform.getOutput()); + UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); UnboundedReader reader = createReader( transform.getTransform().getSource(), evaluationContext.getPipelineOptions()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java index c9f26db929..d651871099 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java @@ -41,7 +41,7 @@ public class ViewEvaluatorFactory implements TransformEvaluatorFactory { @Override public TransformEvaluator forApplication( AppliedPTransform application, - InProcessPipelineRunner.Bundle inputBundle, + InProcessPipelineRunner.CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { return createEvaluator( (AppliedPTransform) application, evaluationContext); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java index 0373ef5e11..c55887f784 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java @@ -15,7 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess.util; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; @@ -31,12 +31,15 @@ */ public class ImmutableInProcessTransformResult implements InProcessTransformResult { private final AppliedPTransform transform; - private final Iterable> bundles; + private final Iterable> bundles; private final CounterSet counters; private final Instant watermarkHold; - private ImmutableInProcessTransformResult(AppliedPTransform transform, - Iterable> outputBundles, CounterSet counters, Instant watermarkHold) { + private ImmutableInProcessTransformResult( + AppliedPTransform transform, + Iterable> outputBundles, + CounterSet counters, + Instant watermarkHold) { this.transform = transform; this.bundles = outputBundles; this.counters = counters; @@ -44,7 +47,7 @@ private ImmutableInProcessTransformResult(AppliedPTransform transform, } @Override - public Iterable> getBundles() { + public Iterable> getOutputBundles() { return bundles; } @@ -77,7 +80,7 @@ public static Builder withoutHold(AppliedPTransform transform) { */ public static class Builder { private final AppliedPTransform transform; - private final ImmutableList.Builder> bundlesBuilder; + private final ImmutableList.Builder> bundlesBuilder; private CounterSet counters; private final Instant watermarkHold; @@ -98,13 +101,14 @@ public Builder withCounters(CounterSet counters) { return this; } - public Builder addOutput(Bundle outputBundle, Bundle... outputBundles) { + public Builder addOutput( + UncommittedBundle outputBundle, UncommittedBundle... outputBundles) { bundlesBuilder.add(outputBundle); bundlesBuilder.add(outputBundles); return this; } - public Builder addOutput(Collection> outputBundles) { + public Builder addOutput(Collection> outputBundles) { bundlesBuilder.addAll(outputBundles); return this; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java index 8673956d69..417b33b3c5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java @@ -16,7 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.inprocess.util; import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; @@ -57,7 +57,8 @@ * {@link PCollection PCollections}. * *

    Whenever a non-root {@link AppliedPTransform} finishes processing one or more in-flight - * elements (referred to as the input {@link Bundle bundle}), the following occurs atomically: + * elements (referred to as the input {@link CommittedBundle bundle}), the following occurs + * atomically: *

      *
    • All of the in-flight elements are removed from the collection of pending elements for the * {@link AppliedPTransform}.
    • @@ -421,12 +422,12 @@ public synchronized TransformWatermarks getWatermarks(AppliedPTransform * elements, the watermark should be the minimum of all buffered elements. * @return both watermarks of the source transform */ - public TransformWatermarks updateOutputWatermark( - AppliedPTransform transform, Iterable> outputs, Instant watermark) { + public TransformWatermarks updateOutputWatermark(AppliedPTransform transform, + Iterable> outputs, Instant watermark) { TransformWatermarks watermarks = getWatermarks(transform); watermarks.outputWatermark().setHold(watermark); - for (Bundle output : outputs) { + for (CommittedBundle output : outputs) { PCollection pCollection = output.getPCollection(); for (AppliedPTransform consumer : consumers.get(pCollection)) { addPending(consumer, output.getElements()); @@ -456,8 +457,8 @@ public TransformWatermarks updateOutputWatermark( * is no hold * @return the updated watermark of the transform */ - public TransformWatermarks updateWatermarks(Bundle completed, - AppliedPTransform transform, Collection> outputs, + public TransformWatermarks updateWatermarks(CommittedBundle completed, + AppliedPTransform transform, Collection> outputs, @Nullable Instant earliestHold) { updatePending(completed, transform, outputs); TransformWatermarks transformWms = transformToWatermarks.get(transform); @@ -486,13 +487,13 @@ private void refreshWatermarks(AppliedPTransform transform) { * collection of pending elements, and adds all elements produced by the {@link PTransform} to the * pending queue of each consumer. */ - private void updatePending( - Bundle input, AppliedPTransform transform, Collection> outputs) { + private void updatePending(CommittedBundle input, AppliedPTransform transform, + Collection> outputs) { AppliedPTransformInputWatermark inputWatermark = transformToWatermarks.get(transform).inputWatermark(); inputWatermark.removePending(input.getElements()); - for (Bundle bundle : outputs) { + for (CommittedBundle bundle : outputs) { for (AppliedPTransform consumer : consumers.get(bundle.getPCollection())) { addPending(consumer, bundle.getElements()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java index 1a01a3db12..18f863dbbf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundle.java @@ -15,25 +15,29 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess.util; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects.ToStringHelper; +import com.google.common.collect.ImmutableList; -import java.util.ArrayList; -import java.util.Collection; +import org.joda.time.Instant; import javax.annotation.Nullable; /** - * A {@link Bundle} that buffers elements in memory. + * A {@link UncommittedBundle} that buffers elements in memory. */ -public final class InProcessBundle implements Bundle { +public final class InProcessBundle implements UncommittedBundle { private final PCollection pcollection; private final boolean keyed; private final Object key; - private Collection> elements; + private boolean committed = false; + private ImmutableList.Builder> elements; /** * Create a new {@link InProcessBundle} for the specified {@link PCollection} without a key. @@ -46,7 +50,8 @@ public static InProcessBundle unkeyed(PCollection pcollection) { * Create a new {@link InProcessBundle} for the specified {@link PCollection} with the specified * key. * - * See {@link #getKey()} and {@link #isKeyed()} for more information. + * See {@link CommittedBundle#getKey()} and {@link CommittedBundle#isKeyed()} for more + * information. */ public static InProcessBundle keyed(PCollection pcollection, Object key) { return new InProcessBundle(pcollection, true, key); @@ -56,43 +61,57 @@ private InProcessBundle(PCollection pcollection, boolean keyed, Object key) { this.pcollection = pcollection; this.keyed = keyed; this.key = key; - this.elements = new ArrayList<>(); + this.elements = ImmutableList.builder(); } @Override public InProcessBundle add(WindowedValue element) { + checkState(!committed, "Can't add element %s to committed bundle %s", element, this); elements.add(element); return this; } @Override - @Nullable - public Object getKey() { - return key; - } + public CommittedBundle commit(final Instant synchronizedCompletionTime) { + checkState(!committed, "Can't commit already committed bundle %s", this); + committed = true; + final Iterable> committedElements = elements.build(); + return new CommittedBundle() { + @Override + @Nullable + public Object getKey() { + return key; + } - @Override - public boolean isKeyed() { - return keyed; - } + @Override + public boolean isKeyed() { + return keyed; + } - @Override - public Iterable> getElements() { - return elements; - } + @Override + public Iterable> getElements() { + return committedElements; + } - @Override - public PCollection getPCollection() { - return pcollection; - } + @Override + public PCollection getPCollection() { + return pcollection; + } - @Override - public String toString() { - ToStringHelper toStringHelper = - MoreObjects.toStringHelper(this).add("pcollection", pcollection); - if (keyed) { - toStringHelper = toStringHelper.add("key", keyed); - } - return toStringHelper.add("elements", elements).toString(); + @Override + public Instant getSynchronizedProcessingOutputWatermark() { + return synchronizedCompletionTime; + } + + @Override + public String toString() { + ToStringHelper toStringHelper = + MoreObjects.toStringHelper(this).add("pcollection", pcollection); + if (keyed) { + toStringHelper = toStringHelper.add("key", key); + } + return toStringHelper.add("elements", elements).toString(); + } + }; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleOutputManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleOutputManager.java new file mode 100644 index 0000000000..00462dc379 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleOutputManager.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.TupleTag; + +import java.util.Map; + +/** + * An {@link OutputManager} that outputs to {@link CommittedBundle Bundles} used by the + * {@link InProcessPipelineRunner}. + */ +public class InProcessBundleOutputManager implements OutputManager { + private final Map, UncommittedBundle> bundles; + + public static InProcessBundleOutputManager create( + Map, UncommittedBundle> outputBundles) { + return new InProcessBundleOutputManager(outputBundles); + } + + public InProcessBundleOutputManager(Map, UncommittedBundle> bundles) { + this.bundles = bundles; + } + + @SuppressWarnings("unchecked") + @Override + public void output(TupleTag tag, WindowedValue output) { + @SuppressWarnings("rawtypes") + UncommittedBundle bundle = bundles.get(tag); + bundle.add(output); + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java index 75e086350a..4ff36f722a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java @@ -21,7 +21,7 @@ */ public enum TimeDomain { /** - * The {@code EVENT_TIME} domain corresponds to the timestamps on the elemnts. Time advances + * The {@code EVENT_TIME} domain corresponds to the timestamps on the elements. Time advances * on the system watermark advances. */ EVENT_TIME, diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java index e202876181..81095b0a0d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java @@ -25,8 +25,8 @@ import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -53,7 +53,7 @@ public void boundedSourceInMemoryTransformEvaluatorProducesElements() throws Exc TransformEvaluatorFactory factory = new BoundedReadEvaluatorFactory(); InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - Bundle output = InProcessBundle.unkeyed(longs); + UncommittedBundle output = InProcessBundle.unkeyed(longs); when(context.createRootBundle(longs)).thenReturn(output); TransformEvaluator evaluator = @@ -61,7 +61,7 @@ public void boundedSourceInMemoryTransformEvaluatorProducesElements() throws Exc InProcessTransformResult result = evaluator.finishBundle(); assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); assertThat( - output.getElements(), + output.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(), containsInAnyOrder( gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); } @@ -74,27 +74,31 @@ public void boundedSourceInMemoryTransformEvaluatorMultipleCalls() throws Except TransformEvaluatorFactory factory = new BoundedReadEvaluatorFactory(); InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - Bundle output = InProcessBundle.unkeyed(longs); + UncommittedBundle output = + InProcessBundle.unkeyed(longs); when(context.createRootBundle(longs)).thenReturn(output); TransformEvaluator evaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); InProcessTransformResult result = evaluator.finishBundle(); assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + Iterable> outputElements = + output.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(); assertThat( - output.getElements(), + outputElements, containsInAnyOrder( gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); - Bundle secondOutput = InProcessBundle.unkeyed(longs); + UncommittedBundle secondOutput = InProcessBundle.unkeyed(longs); when(context.createRootBundle(longs)).thenReturn(secondOutput); TransformEvaluator secondEvaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); InProcessTransformResult secondResult = secondEvaluator.finishBundle(); assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - assertThat(secondOutput.getElements(), emptyIterable()); assertThat( - output.getElements(), + secondOutput.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(), emptyIterable()); + assertThat( + outputElements, containsInAnyOrder( gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java index ad4f927f75..8fa411464e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java @@ -20,8 +20,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; @@ -54,22 +55,25 @@ public void testFlattenInMemoryEvaluator() throws Exception { PCollection flattened = list.apply(Flatten.pCollections()); - Bundle leftBundle = InProcessBundle.unkeyed(left); - Bundle rightBundle = InProcessBundle.unkeyed(right); + CommittedBundle leftBundle = InProcessBundle.unkeyed(left).commit(Instant.now()); + CommittedBundle rightBundle = InProcessBundle.unkeyed(right).commit(Instant.now()); InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - Bundle flattenedLeftBundle = InProcessBundle.unkeyed(flattened); - Bundle flattenedRightBundle = InProcessBundle.unkeyed(flattened); + UncommittedBundle flattenedLeftBundle = InProcessBundle.unkeyed(flattened); + UncommittedBundle flattenedRightBundle = InProcessBundle.unkeyed(flattened); when(context.createBundle(leftBundle, flattened)).thenReturn(flattenedLeftBundle); when(context.createBundle(rightBundle, flattened)).thenReturn(flattenedRightBundle); FlattenEvaluatorFactory factory = new FlattenEvaluatorFactory(); - TransformEvaluator leftSideEvaluator = factory.forApplication( - flattened.getProducingTransformInternal(), leftBundle, context); + TransformEvaluator leftSideEvaluator = + factory.forApplication(flattened.getProducingTransformInternal(), leftBundle, context); TransformEvaluator rightSideEvaluator = - factory.forApplication(flattened.getProducingTransformInternal(), rightBundle, context); + factory.forApplication( + flattened.getProducingTransformInternal(), + rightBundle, + context); leftSideEvaluator.processElement(WindowedValue.valueInGlobalWindow(1)); rightSideEvaluator.processElement(WindowedValue.valueInGlobalWindow(-1)); @@ -84,23 +88,27 @@ public void testFlattenInMemoryEvaluator() throws Exception { InProcessTransformResult rightSideResult = rightSideEvaluator.finishBundle(); InProcessTransformResult leftSideResult = leftSideEvaluator.finishBundle(); - assertThat(rightSideResult.getBundles(), Matchers.>contains(flattenedRightBundle)); + assertThat( + rightSideResult.getOutputBundles(), + Matchers.>contains(flattenedRightBundle)); assertThat( rightSideResult.getTransform(), Matchers.>equalTo(flattened.getProducingTransformInternal())); - assertThat(leftSideResult.getBundles(), Matchers.>contains(flattenedLeftBundle)); + assertThat( + leftSideResult.getOutputBundles(), + Matchers.>contains(flattenedLeftBundle)); assertThat( leftSideResult.getTransform(), Matchers.>equalTo(flattened.getProducingTransformInternal())); assertThat( - flattenedLeftBundle.getElements(), + flattenedLeftBundle.commit(Instant.now()).getElements(), containsInAnyOrder( WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1024)), WindowedValue.valueInEmptyWindows(4, PaneInfo.NO_FIRING), WindowedValue.valueInGlobalWindow(1))); assertThat( - flattenedRightBundle.getElements(), + flattenedRightBundle.commit(Instant.now()).getElements(), containsInAnyOrder( WindowedValue.valueInEmptyWindows(2, PaneInfo.ON_TIME_AND_ONLY_FIRING), WindowedValue.timestampedValueInGlobalWindow(-4, new Instant(-4096)), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java index 456a52fa70..1d7031dee7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java @@ -16,20 +16,21 @@ package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.emptyIterable; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -39,6 +40,7 @@ import org.hamcrest.BaseMatcher; import org.hamcrest.Description; +import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -57,17 +59,21 @@ public void testInMemoryEvaluator() throws Exception { KV firstBar = KV.of("bar", 22); KV secondBar = KV.of("bar", 12); KV firstBaz = KV.of("baz", Integer.MAX_VALUE); - PCollection> kvs = p.apply(Create.of(firstFoo, firstBar, - secondFoo, firstBaz, secondBar, thirdFoo)); + PCollection> kvs = + p.apply(Create.of(firstFoo, firstBar, secondFoo, firstBaz, secondBar, thirdFoo)); PCollection>> groupedKvs = kvs.apply(new GroupByKeyOnly()); - Bundle> inputBundle = InProcessBundle.unkeyed(kvs); + CommittedBundle> inputBundle = + InProcessBundle.unkeyed(kvs).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - Bundle>> fooBundle = InProcessBundle.keyed(groupedKvs, "foo"); - Bundle>> barBundle = InProcessBundle.keyed(groupedKvs, "bar"); - Bundle>> bazBundle = InProcessBundle.keyed(groupedKvs, "baz"); + UncommittedBundle>> fooBundle = + InProcessBundle.keyed(groupedKvs, "foo"); + UncommittedBundle>> barBundle = + InProcessBundle.keyed(groupedKvs, "bar"); + UncommittedBundle>> bazBundle = + InProcessBundle.keyed(groupedKvs, "baz"); when(evaluationContext.createKeyedBundle(inputBundle, "foo", groupedKvs)).thenReturn(fooBundle); when(evaluationContext.createKeyedBundle(inputBundle, "bar", groupedKvs)).thenReturn(barBundle); @@ -87,25 +93,21 @@ public void testInMemoryEvaluator() throws Exception { evaluator.processElement(WindowedValue.valueInGlobalWindow(secondBar)); evaluator.processElement(WindowedValue.valueInGlobalWindow(firstBaz)); - assertThat(fooBundle.getElements(), emptyIterable()); - assertThat(barBundle.getElements(), emptyIterable()); - assertThat(bazBundle.getElements(), emptyIterable()); - evaluator.finishBundle(); + assertThat( - fooBundle.getElements(), + fooBundle.commit(Instant.now()).getElements(), contains(new KIterVMatcher( KV.>of("foo", ImmutableSet.of(-1, 1, 3)), keyCoder))); assertThat( - barBundle.getElements(), + barBundle.commit(Instant.now()).getElements(), contains(new KIterVMatcher( KV.>of("bar", ImmutableSet.of(12, 22)), keyCoder))); assertThat( - bazBundle.getElements(), - contains( - new KIterVMatcher( - KV.>of("baz", ImmutableSet.of(Integer.MAX_VALUE)), - keyCoder))); + bazBundle.commit(Instant.now()).getElements(), + contains(new KIterVMatcher( + KV.>of("baz", ImmutableSet.of(Integer.MAX_VALUE)), + keyCoder))); } private static class KIterVMatcher extends BaseMatcher>>> { @@ -134,9 +136,8 @@ public boolean matches(Object item) { } try { return myValues.equals(thatValues) - && keyCoder - .structuralValue(myKv.getKey()) - .equals(keyCoder.structuralValue(that.getValue().getKey())); + && keyCoder.structuralValue(myKv.getKey()) + .equals(keyCoder.structuralValue(that.getValue().getKey())); } catch (Exception e) { return false; } @@ -144,8 +145,7 @@ public boolean matches(Object item) { @Override public void describeTo(Description description) { - description - .appendText("KV> containing key ") + description.appendText("KV> containing key ") .appendValue(myKv.getKey()) .appendText(" and values ") .appendValueList("[", ", ", "]", myKv.getValue()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java index b5b3823a04..939121be41 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java @@ -15,14 +15,15 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; -import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -74,16 +75,19 @@ public void processElement(ProcessContext c) { }).withOutputTags(mainOutputTag, TupleTagList.of(elementTag).and(lengthTag)); PCollectionTuple outputTuple = input.apply(pardo); - Bundle inputBundle = InProcessBundle.unkeyed(input); + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); PCollection> mainOutput = outputTuple.get(mainOutputTag); PCollection elementOutput = outputTuple.get(elementTag); PCollection lengthOutput = outputTuple.get(lengthTag); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - Bundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); - Bundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); - Bundle lengthOutputBundle = InProcessBundle.unkeyed(lengthOutput); + UncommittedBundle> mainOutputBundle = + InProcessBundle.unkeyed(mainOutput); + UncommittedBundle elementOutputBundle = + InProcessBundle.unkeyed(elementOutput); + UncommittedBundle lengthOutputBundle = + InProcessBundle.unkeyed(lengthOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); when(evaluationContext.createBundle(inputBundle, elementOutput)) @@ -108,27 +112,27 @@ public void processElement(ProcessContext c) { InProcessTransformResult result = evaluator.finishBundle(); assertThat( - result.getBundles(), - Matchers.>containsInAnyOrder( + result.getOutputBundles(), + Matchers.>containsInAnyOrder( lengthOutputBundle, mainOutputBundle, elementOutputBundle)); assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); assertThat(result.getCounters(), equalTo(counters)); assertThat( - mainOutputBundle.getElements(), + mainOutputBundle.commit(Instant.now()).getElements(), Matchers.>>containsInAnyOrder( WindowedValue.valueInGlobalWindow(KV.of("foo", 3)), WindowedValue.timestampedValueInGlobalWindow(KV.of("bara", 4), new Instant(1000)), WindowedValue.valueInGlobalWindow( KV.of("bazam", 5), PaneInfo.ON_TIME_AND_ONLY_FIRING))); assertThat( - elementOutputBundle.getElements(), + elementOutputBundle.commit(Instant.now()).getElements(), Matchers.>containsInAnyOrder( WindowedValue.valueInGlobalWindow("foo"), WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000)), WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING))); assertThat( - lengthOutputBundle.getElements(), + lengthOutputBundle.commit(Instant.now()).getElements(), Matchers.>containsInAnyOrder( WindowedValue.valueInGlobalWindow(3), WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java index 07d08d1fad..b0e30034ee 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java @@ -15,14 +15,15 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; -import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -58,10 +59,11 @@ public void testParDoInMemoryTransformEvaluator() throws Exception { c.output(c.element().length()); } })); - Bundle inputBundle = InProcessBundle.unkeyed(input); + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - Bundle outputBundle = InProcessBundle.unkeyed(collection); + UncommittedBundle outputBundle = + InProcessBundle.unkeyed(collection); when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); InProcessExecutionContext executionContext = new InProcessExecutionContext(); when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal())) @@ -80,12 +82,12 @@ public void testParDoInMemoryTransformEvaluator() throws Exception { WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); InProcessTransformResult result = evaluator.finishBundle(); - assertThat(result.getBundles(), Matchers.>contains(outputBundle)); + assertThat(result.getOutputBundles(), Matchers.>contains(outputBundle)); assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); assertThat(result.getCounters(), equalTo(counters)); assertThat( - outputBundle.getElements(), + outputBundle.commit(Instant.now()).getElements(), Matchers.>containsInAnyOrder( WindowedValue.valueInGlobalWindow(3), WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java index bc3bd76daf..c8500f30cb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java @@ -23,8 +23,8 @@ import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; @@ -56,7 +56,7 @@ public void unboundedSourceInMemoryTransformEvaluatorProducesElements() throws E TransformEvaluatorFactory factory = new UnboundedReadEvaluatorFactory(); InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - Bundle output = InProcessBundle.unkeyed(longs); + UncommittedBundle output = InProcessBundle.unkeyed(longs); when(context.createRootBundle(longs)).thenReturn(output); TransformEvaluator evaluator = @@ -65,7 +65,7 @@ public void unboundedSourceInMemoryTransformEvaluatorProducesElements() throws E assertThat( result.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); assertThat( - output.getElements(), + output.commit(Instant.now()).getElements(), containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), tgw(3L), tgw(0L))); } @@ -79,7 +79,7 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleCalls() throws Exce TransformEvaluatorFactory factory = new UnboundedReadEvaluatorFactory(); InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - Bundle output = InProcessBundle.unkeyed(longs); + UncommittedBundle output = InProcessBundle.unkeyed(longs); when(context.createRootBundle(longs)).thenReturn(output); TransformEvaluator evaluator = @@ -88,11 +88,11 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleCalls() throws Exce assertThat( result.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); assertThat( - output.getElements(), + output.commit(Instant.now()).getElements(), containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), tgw(3L), tgw(0L))); - Bundle secondOutput = InProcessBundle.unkeyed(longs); + UncommittedBundle secondOutput = InProcessBundle.unkeyed(longs); when(context.createRootBundle(longs)).thenReturn(secondOutput); TransformEvaluator secondEvaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); @@ -101,13 +101,9 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleCalls() throws Exce secondResult.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); assertThat( - secondOutput.getElements(), + secondOutput.commit(Instant.now()).getElements(), containsInAnyOrder(tgw(11L), tgw(12L), tgw(14L), tgw(18L), tgw(19L), tgw(17L), tgw(16L), tgw(15L), tgw(13L), tgw(10L))); - assertThat( - output.getElements(), - containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), - tgw(3L), tgw(0L))); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java index 50af094086..34a9344d28 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java @@ -21,7 +21,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; @@ -33,6 +33,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; +import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -52,7 +53,7 @@ public void testInMemoryEvaluator() throws Exception { TestViewWriter> viewWriter = new TestViewWriter<>(); when(context.createPCollectionViewWriter(input, view)).thenReturn(viewWriter); - Bundle inputBundle = InProcessBundle.unkeyed(input); + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); TransformEvaluator evaluator = new ViewEvaluatorFactory().forApplication( view.getProducingTransformInternal(), inputBundle, context); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java index aeb276c9ad..d32fa6b869 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java @@ -19,7 +19,8 @@ import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.Bundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TransformWatermarks; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -121,11 +122,11 @@ public void getWatermarkForUntouchedTransform() { */ @Test public void getWatermarkForUpdatedSourceTransform() { - Bundle output = globallyWindowedBundle(createdInts, 1); + CommittedBundle output = globallyWindowedBundle(createdInts, 1); TransformWatermarks updatedSourceWatermark = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(output), new Instant(8000L)); + Collections.>singleton(output), new Instant(8000L)); assertThat(updatedSourceWatermark.getOutputWatermark(), equalTo(new Instant(8000L))); } @@ -136,10 +137,12 @@ public void getWatermarkForUpdatedSourceTransform() { */ @Test public void getWatermarkForMultiInputTransform() { - Bundle secondPcollectionBundle = globallyWindowedBundle(intsToFlatten, -1); + CommittedBundle secondPcollectionBundle = globallyWindowedBundle(intsToFlatten, -1); - manager.updateOutputWatermark(intsToFlatten.getProducingTransformInternal(), - Collections.>singleton(secondPcollectionBundle), new Instant(Long.MAX_VALUE)); + manager.updateOutputWatermark( + intsToFlatten.getProducingTransformInternal(), + Collections.>singleton(secondPcollectionBundle), + new Instant(Long.MAX_VALUE)); // We didn't do anything for the first source, so we shouldn't have progressed the watermark TransformWatermarks firstSourceWatermark = @@ -164,12 +167,12 @@ public void getWatermarkForMultiInputTransform() { assertThat( transformWatermark.getOutputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - Bundle flattenedBundleSecondCreate = globallyWindowedBundle(flattened, -1); + CommittedBundle flattenedBundleSecondCreate = globallyWindowedBundle(flattened, -1); // We have finished processing the bundle from the second PCollection, but we haven't consumed // anything from the first PCollection yet; so our watermark shouldn't advance TransformWatermarks transformAfterProcessing = manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(flattenedBundleSecondCreate), null); + Collections.>singleton(flattenedBundleSecondCreate), null); assertThat( transformAfterProcessing.getInputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); @@ -178,14 +181,16 @@ public void getWatermarkForMultiInputTransform() { not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); Instant firstCollectionTimestamp = new Instant(10000); - Bundle firstPcollectionBundle = timestampedBundle( - createdInts, TimestampedValue.of(5, firstCollectionTimestamp)); + CommittedBundle firstPcollectionBundle = + timestampedBundle(createdInts, TimestampedValue.of(5, firstCollectionTimestamp)); // the source is done, but elements are still buffered. The source output watermark should be // past the end of the global window - TransformWatermarks firstSourceWatermarks = - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(firstPcollectionBundle), new Instant(Long.MAX_VALUE)); - assertThat(firstSourceWatermarks.getOutputWatermark(), + TransformWatermarks firstSourceWatermarks = manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + Collections.>singleton(firstPcollectionBundle), + new Instant(Long.MAX_VALUE)); + assertThat( + firstSourceWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); // We still haven't consumed any of the first source's input, so the watermark should still not @@ -193,11 +198,9 @@ public void getWatermarkForMultiInputTransform() { TransformWatermarks flattenAfterSourcesProduced = manager.getWatermarks(flattened.getProducingTransformInternal()); assertThat( - flattenAfterSourcesProduced.getInputWatermark(), - not(laterThan(firstCollectionTimestamp))); + flattenAfterSourcesProduced.getInputWatermark(), not(laterThan(firstCollectionTimestamp))); assertThat( - flattenAfterSourcesProduced.getOutputWatermark(), - not(laterThan(firstCollectionTimestamp))); + flattenAfterSourcesProduced.getOutputWatermark(), not(laterThan(firstCollectionTimestamp))); // We have buffered inputs, but since the PCollection has all of the elements (has a WM past the // end of the global window), we should have a watermark equal to the min among buffered @@ -207,10 +210,11 @@ public void getWatermarkForMultiInputTransform() { assertThat(withBufferedElements.getInputWatermark(), equalTo(firstCollectionTimestamp)); assertThat(withBufferedElements.getOutputWatermark(), equalTo(firstCollectionTimestamp)); - Bundle completedFlattenBundle = InProcessBundle.unkeyed(flattened); + CommittedBundle completedFlattenBundle = + InProcessBundle.unkeyed(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks afterConsumingAllInput = manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(completedFlattenBundle), null); + Collections.>singleton(completedFlattenBundle), null); assertThat( afterConsumingAllInput.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); @@ -225,21 +229,23 @@ public void getWatermarkForMultiInputTransform() { */ @Test public void getWatermarkForMultiConsumedCollection() { - Bundle createdBundle = timestampedBundle(createdInts, + CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), TimestampedValue.of(3, new Instant(-1000L))); TransformWatermarks createdAfterProducing = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); - assertThat(createdAfterProducing.getOutputWatermark(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + assertThat( + createdAfterProducing.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - Bundle> keyBundle = + CommittedBundle> keyBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - TransformWatermarks keyedWatermarks = manager.updateWatermarks(createdBundle, - keyed.getProducingTransformInternal(), Collections.>singleton(keyBundle), null); + TransformWatermarks keyedWatermarks = + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), null); assertThat( keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat( @@ -248,14 +254,13 @@ public void getWatermarkForMultiConsumedCollection() { TransformWatermarks filteredWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat(filteredWatermarks.getInputWatermark(), not(laterThan(new Instant(-1000L)))); - assertThat( - filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); + assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); - Bundle filteredBundle = timestampedBundle( - filtered, TimestampedValue.of(2, new Instant(1234L))); + CommittedBundle filteredBundle = + timestampedBundle(filtered, TimestampedValue.of(2, new Instant(1234L))); TransformWatermarks filteredProcessedWatermarks = manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), - Collections.>singleton(filteredBundle), null); + Collections.>singleton(filteredBundle), null); assertThat( filteredProcessedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); @@ -270,20 +275,19 @@ public void getWatermarkForMultiConsumedCollection() { */ @Test public void updateWatermarkWithWatermarkHolds() { - Bundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), + CommittedBundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), TimestampedValue.of(3, new Instant(-1000L))); manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); - - Bundle> keyBundle = timestampedBundle( - keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), - TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), - TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - TransformWatermarks keyedWatermarks = manager.updateWatermarks(createdBundle, - keyed.getProducingTransformInternal(), Collections.>singleton(keyBundle), - new Instant(500L)); + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + + CommittedBundle> keyBundle = + timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), + TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + TransformWatermarks keyedWatermarks = + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), new Instant(500L)); assertThat( keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); @@ -295,16 +299,18 @@ public void updateWatermarkWithWatermarkHolds() { */ @Test public void updateOutputWatermarkShouldBeMonotonic() { - Bundle firstInput = InProcessBundle.unkeyed(createdInts); + CommittedBundle firstInput = + InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks firstWatermarks = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(firstInput), new Instant(0L)); + Collections.>singleton(firstInput), new Instant(0L)); assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); - Bundle secondInput = InProcessBundle.unkeyed(createdInts); + CommittedBundle secondInput = + InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks secondWatermarks = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(secondInput), new Instant(-250L)); + Collections.>singleton(secondInput), new Instant(-250L)); assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); } @@ -314,24 +320,19 @@ public void updateOutputWatermarkShouldBeMonotonic() { */ @Test public void updateWatermarkWithHoldsShouldBeMonotonic() { - Bundle createdBundle = timestampedBundle( - createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), + CommittedBundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), TimestampedValue.of(3, new Instant(-1000L))); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), - new Instant(Long.MAX_VALUE)); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); - Bundle> keyBundle = timestampedBundle( - keyed, - TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + CommittedBundle> keyBundle = + timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); TransformWatermarks keyedWatermarks = manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), new Instant(500L)); + Collections.>singleton(keyBundle), new Instant(500L)); assertThat( keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); @@ -343,8 +344,7 @@ public void updateWatermarkWithHoldsShouldBeMonotonic() { updatedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); // We added a hold prior to the old watermark; we shouldn't progress (due to the earlier hold) // but the watermark is monotonic and should not backslide to the new, earlier hold - assertThat( - updatedWatermarks.getOutputWatermark(), equalTo(oldOutputWatermark)); + assertThat(updatedWatermarks.getOutputWatermark(), equalTo(oldOutputWatermark)); } /** @@ -353,33 +353,31 @@ public void updateWatermarkWithHoldsShouldBeMonotonic() { @Test public void updateWatermarkWithLateData() { Instant sourceWatermark = new Instant(1_000_000L); - Bundle createdBundle = timestampedBundle(createdInts, + CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, sourceWatermark), TimestampedValue.of(2, new Instant(1234L))); manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), sourceWatermark); + Collections.>singleton(createdBundle), sourceWatermark); - Bundle> keyBundle = timestampedBundle( - keyed, - TimestampedValue.of(KV.of("MyKey", 1), sourceWatermark), - TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); + CommittedBundle> keyBundle = + timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), sourceWatermark), + TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); // Finish processing the on-time data. The watermarks should progress to be equal to the source TransformWatermarks onTimeWatermarks = manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), null); + Collections.>singleton(keyBundle), null); assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); assertThat(onTimeWatermarks.getOutputWatermark(), equalTo(sourceWatermark)); - Bundle lateDataBundle = timestampedBundle( - createdInts, TimestampedValue.of(3, new Instant(-1000L))); + CommittedBundle lateDataBundle = + timestampedBundle(createdInts, TimestampedValue.of(3, new Instant(-1000L))); // the late data arrives in a downstream PCollection after its watermark has advanced past it; // we don't advance the watermark past the current watermark until we've consumed the late data TransformWatermarks bufferedLateWm = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(lateDataBundle), - new Instant(2_000_000L)); + Collections.>singleton(lateDataBundle), new Instant(2_000_000L)); assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); // The input watermark should be held to its previous value (not advanced due to late data; not @@ -389,10 +387,10 @@ public void updateWatermarkWithLateData() { assertThat(lateDataBufferedWatermark.getInputWatermark(), not(earlierThan(sourceWatermark))); assertThat(lateDataBufferedWatermark.getOutputWatermark(), not(earlierThan(sourceWatermark))); - Bundle> lateKeyedBundle = timestampedBundle( - keyed, TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + CommittedBundle> lateKeyedBundle = + timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); manager.updateWatermarks(lateDataBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(lateKeyedBundle), null); + Collections.>singleton(lateKeyedBundle), null); } /** @@ -401,19 +399,23 @@ public void updateWatermarkWithLateData() { */ @Test public void getWatermarksAfterOnlyEmptyOutput() { - Bundle emptyCreateOutput = globallyWindowedBundle(createdInts); - TransformWatermarks updatedSourceWatermarks = - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); + TransformWatermarks updatedSourceWatermarks = manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + Collections.>singleton(emptyCreateOutput), + BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(updatedSourceWatermarks.getOutputWatermark(), + assertThat( + updatedSourceWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); TransformWatermarks finishedFilterWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat(finishedFilterWatermarks.getInputWatermark(), + assertThat( + finishedFilterWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat(finishedFilterWatermarks.getOutputWatermark(), + assertThat( + finishedFilterWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); } @@ -423,28 +425,31 @@ public void getWatermarksAfterOnlyEmptyOutput() { */ @Test public void getWatermarksAfterHoldAndEmptyOutput() { - Bundle firstCreateOutput = globallyWindowedBundle(createdInts, 1, 2); + CommittedBundle firstCreateOutput = globallyWindowedBundle(createdInts, 1, 2); manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(firstCreateOutput), new Instant(12_000L)); + Collections.>singleton(firstCreateOutput), new Instant(12_000L)); - Bundle firstFilterOutput = globallyWindowedBundle(filtered); + CommittedBundle firstFilterOutput = globallyWindowedBundle(filtered); TransformWatermarks firstFilterWatermarks = manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), - Collections.>singleton(firstFilterOutput), new Instant(10_000L)); + Collections.>singleton(firstFilterOutput), new Instant(10_000L)); assertThat(firstFilterWatermarks.getInputWatermark(), not(earlierThan(new Instant(12_000L)))); assertThat(firstFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); - Bundle emptyCreateOutput = globallyWindowedBundle(createdInts); - TransformWatermarks updatedSourceWatermarks = - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); + TransformWatermarks updatedSourceWatermarks = manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + Collections.>singleton(emptyCreateOutput), + BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(updatedSourceWatermarks.getOutputWatermark(), + assertThat( + updatedSourceWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); TransformWatermarks finishedFilterWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat(finishedFilterWatermarks.getInputWatermark(), + assertThat( + finishedFilterWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat(finishedFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); } @@ -475,26 +480,27 @@ public boolean matches(Object item) { @Override public void describeTo(Description description) { description.appendText("later than ").appendValue(shouldBeEarlier); - }}; + } + }; } @SafeVarargs - private final Bundle timestampedBundle( + private final CommittedBundle timestampedBundle( PCollection pc, TimestampedValue... values) { - Bundle bundle = InProcessBundle.unkeyed(pc); + UncommittedBundle bundle = InProcessBundle.unkeyed(pc); for (TimestampedValue value : values) { bundle.add( WindowedValue.timestampedValueInGlobalWindow(value.getValue(), value.getTimestamp())); } - return bundle; + return bundle.commit(BoundedWindow.TIMESTAMP_MAX_VALUE); } @SafeVarargs - private final Bundle globallyWindowedBundle(PCollection pc, T... values) { - Bundle bundle = InProcessBundle.unkeyed(pc); + private final CommittedBundle globallyWindowedBundle(PCollection pc, T... values) { + UncommittedBundle bundle = InProcessBundle.unkeyed(pc); for (T value : values) { bundle.add(WindowedValue.valueInGlobalWindow(value)); } - return bundle; + return bundle.commit(BoundedWindow.TIMESTAMP_MAX_VALUE); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java index 3378e3bded..57d8c908e0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessBundleTest.java @@ -15,11 +15,13 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess.util; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -29,7 +31,9 @@ import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.joda.time.Instant; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -42,11 +46,16 @@ */ @RunWith(JUnit4.class) public class InProcessBundleTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Test public void unkeyedShouldCreateWithNullKey() { PCollection pcollection = TestPipeline.create().apply(Create.of(1)); - InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); + InProcessBundle inFlightBundle = InProcessBundle.unkeyed(pcollection); + + CommittedBundle bundle = inFlightBundle.commit(Instant.now()); assertThat(bundle.isKeyed(), is(false)); assertThat(bundle.getKey(), nullValue()); @@ -55,8 +64,9 @@ public void unkeyedShouldCreateWithNullKey() { private void keyedCreateBundle(Object key) { PCollection pcollection = TestPipeline.create().apply(Create.of(1)); - InProcessBundle bundle = InProcessBundle.keyed(pcollection, key); + InProcessBundle inFlightBundle = InProcessBundle.keyed(pcollection, key); + CommittedBundle bundle = inFlightBundle.commit(Instant.now()); assertThat(bundle.isKeyed(), is(true)); assertThat(bundle.getKey(), equalTo(key)); } @@ -71,7 +81,7 @@ public void keyedWithKeyShouldCreateKeyedBundle() { keyedCreateBundle(new Object()); } - private void getElementsShouldHaveAddedElements(Iterable> elems) { + private void afterCommitGetElementsShouldHaveAddedElements(Iterable> elems) { PCollection pcollection = TestPipeline.create().apply(Create.of()); InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); @@ -82,12 +92,12 @@ private void getElementsShouldHaveAddedElements(Iterable> e } Matcher>> containsMatcher = Matchers.>containsInAnyOrder(expectations); - assertThat(bundle.getElements(), containsMatcher); + assertThat(bundle.commit(Instant.now()).getElements(), containsMatcher); } @Test public void getElementsBeforeAddShouldReturnEmptyIterable() { - getElementsShouldHaveAddedElements(Collections.>emptyList()); + afterCommitGetElementsShouldHaveAddedElements(Collections.>emptyList()); } @Test @@ -96,7 +106,38 @@ public void getElementsAfterAddShouldReturnAddedElements() { WindowedValue secondValue = WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1000L)); - getElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); + afterCommitGetElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); + } + + @Test + public void addAfterCommitShouldThrowException() { + PCollection pcollection = TestPipeline.create().apply(Create.of()); + + InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); + bundle.add(WindowedValue.valueInGlobalWindow(1)); + CommittedBundle firstCommit = bundle.commit(Instant.now()); + assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage("3"); + thrown.expectMessage("committed"); + + bundle.add(WindowedValue.valueInGlobalWindow(3)); + } + + @Test + public void commitAfterCommitShouldThrowException() { + PCollection pcollection = TestPipeline.create().apply(Create.of()); + + InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); + bundle.add(WindowedValue.valueInGlobalWindow(1)); + CommittedBundle firstCommit = bundle.commit(Instant.now()); + assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage("committed"); + + bundle.commit(Instant.now()); } } From 4c1e9112a92e1600c6bbdd63723220f06ba50132 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Fri, 5 Feb 2016 12:16:32 -0800 Subject: [PATCH 086/751] ApiSurfaceTest: whitelist com.google.auth package This is a new package that contains user credentials for GCP, and will ultimately need to be exposed as part of our API surface, ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113973842 --- .../main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java index 2456c0e094..20ba6698f1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java @@ -550,6 +550,7 @@ public static ApiSurface getSdkApiSurface() throws IOException { .pruningPrefix("com.google.cloud.dataflow.integration") .pruningPrefix("java") .pruningPrefix("com.google.api") + .pruningPrefix("com.google.auth") .pruningPrefix("com.google.protobuf") .pruningPrefix("org.joda.time") .pruningPrefix("org.apache.avro") From f41716aa4cab2c5641c06105665476e934ea1089 Mon Sep 17 00:00:00 2001 From: klk Date: Fri, 5 Feb 2016 12:28:42 -0800 Subject: [PATCH 087/751] Make SinkFactory a real class; remove some reflection This refactor has no observable change, given that the reflection was not actually part of our public programming model. Previously, SinkFactory was actually a global registry mapping service-side class names to SDK-side classes. These classes were to "implement" a particular interface via their static methods. This change makes SinkFactory express that interface, and now SinkRegistry encapsulates the default behavior of maintaining a lightweight registry, previously in a global variable. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113974786 --- .../sdk/runners/worker/AvroSinkFactory.java | 31 ++--- .../sdk/runners/worker/IsmSinkFactory.java | 40 +++--- .../sdk/runners/worker/PubsubSink.java | 34 +++-- .../runners/worker/ShuffleSinkFactory.java | 37 +++--- .../sdk/runners/worker/SinkFactory.java | 82 ++---------- .../sdk/runners/worker/SinkRegistry.java | 118 ++++++++++++++++++ .../sdk/runners/worker/TextSinkFactory.java | 44 +++---- .../sdk/runners/worker/WindmillSink.java | 25 ++-- 8 files changed, 239 insertions(+), 172 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java index fadd31a38f..bb881da9ec 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java @@ -28,28 +28,21 @@ import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; +import javax.annotation.Nullable; + /** - * Creates an AvroSink from a CloudObject spec. + * Creates an {@link AvroSink} from a {@link CloudObject} spec. */ -@SuppressWarnings("rawtypes") -public final class AvroSinkFactory { - // Do not instantiate. - private AvroSinkFactory() {} - - @SuppressWarnings("unused") - public static Sink create(PipelineOptions options, - CloudObject spec, - Coder coder, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - return create(spec, coder); - } +public final class AvroSinkFactory implements SinkFactory { - static Sink create(CloudObject spec, Coder coder) + @Override + public Sink create( + CloudObject spec, + Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator) throws Exception { - String filename = getString(spec, PropertyNames.FILENAME); - // Avro sinks are used both for outputting user data at the end of a pipeline and for // materializing PCollections as intermediate results. It is important to distinguish these // two cases because one requires only the values (outputting with AvroSink) and one requires @@ -83,6 +76,8 @@ static Sink create(CloudObject spec, Coder coder) // include the window and timestamp. // // See AvroReaderFactory#create for the accompanying reader logic. + String filename = getString(spec, PropertyNames.FILENAME); + if (coder instanceof ValueOnlyWindowedValueCoder && ((ValueOnlyWindowedValueCoder) coder).getValueCoder() instanceof AvroCoder) { return new AvroSink(filename, (ValueOnlyWindowedValueCoder) coder); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java index b1386067d1..03ce0327c8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java @@ -30,39 +30,41 @@ import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; +import javax.annotation.Nullable; + /** * Creates an {@link IsmSink} from a {@link CloudObject} spec. Note that it is invalid to use a * non {@link IsmRecordCoder} with this sink factory. */ -public class IsmSinkFactory { - // Do not instantiate. - private IsmSinkFactory() {} +public class IsmSinkFactory implements SinkFactory { - @SuppressWarnings("unused") - public static Sink>> create( - PipelineOptions options, + @Override + public Sink create( CloudObject spec, - Coder>> coder, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator) throws Exception { - return create(spec, coder); - } + @Nullable Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator) throws Exception { + + // The validity of this coder is checked in detail by the typed create, below + @SuppressWarnings("unchecked") + Coder>> typedCoder = + (Coder>>) coder; - static Sink>> create( - CloudObject spec, Coder>> coder) throws Exception { String filename = getString(spec, PropertyNames.FILENAME); - checkArgument(coder instanceof WindowedValueCoder, - "%s only supports using %s but got %s.", IsmSink.class, WindowedValueCoder.class, coder); - WindowedValueCoder> windowedCoder = - (WindowedValueCoder>) coder; + checkArgument(typedCoder instanceof WindowedValueCoder, + "%s only supports using %s but got %s.", IsmSink.class, WindowedValueCoder.class, + typedCoder); + WindowedValueCoder> windowedCoder = + (WindowedValueCoder>) typedCoder; checkArgument(windowedCoder.getValueCoder() instanceof IsmRecordCoder, "%s only supports using %s but got %s.", IsmSink.class, IsmRecordCoder.class, windowedCoder.getValueCoder()); @SuppressWarnings("unchecked") - IsmRecordCoder ismCoder = - (IsmRecordCoder) windowedCoder.getValueCoder(); + IsmRecordCoder ismCoder = + (IsmRecordCoder) windowedCoder.getValueCoder(); return new IsmSink<>(filename, ismCoder); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java index 2c7c142fbe..4fe7c27243 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java @@ -30,6 +30,8 @@ import java.io.IOException; +import javax.annotation.Nullable; + /** * A sink that writes to Pubsub, via a Windmill server. * @@ -55,18 +57,26 @@ class PubsubSink extends Sink> { this.context = context; } - @SuppressWarnings("unused") - public static PubsubSink create(PipelineOptions options, - CloudObject spec, - Coder> coder, - ExecutionContext context, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - String topic = getString(spec, "pubsub_topic"); - String timestampLabel = getString(spec, "pubsub_timestamp_label", ""); - String idLabel = getString(spec, "pubsub_id_label", ""); - return new PubsubSink<>( - topic, timestampLabel, idLabel, coder, (StreamingModeExecutionContext) context); + public static class Factory implements SinkFactory { + @Override + public PubsubSink create( + CloudObject spec, + Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext context, + @Nullable CounterSet.AddCounterMutator addCounterMutator) + throws Exception { + String topic = getString(spec, "pubsub_topic"); + String timestampLabel = getString(spec, "pubsub_timestamp_label", ""); + String idLabel = getString(spec, "pubsub_id_label", ""); + + @SuppressWarnings("unchecked") + Coder> typedCoder = + (Coder>) coder; + + return new PubsubSink<>( + topic, timestampLabel, idLabel, typedCoder, (StreamingModeExecutionContext) context); + } } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java index 8f3897541f..360a20bad8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java @@ -28,32 +28,31 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import javax.annotation.Nullable; + /** - * Creates a ShuffleSink from a CloudObject spec. + * Creates a {@link ShuffleSink} from a {@link CloudObject} spec. */ -public class ShuffleSinkFactory { - // Do not instantiate. - private ShuffleSinkFactory() {} - - public static ShuffleSink create(PipelineOptions options, - CloudObject spec, - Coder> coder, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - return create(options, spec, coder, addCounterMutator); - } +public class ShuffleSinkFactory implements SinkFactory { + + @Override + public ShuffleSink create( + CloudObject spec, + Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator) + throws Exception { + + @SuppressWarnings("unchecked") + Coder> typedCoder = + (Coder>) coder; - static ShuffleSink create(PipelineOptions options, - CloudObject spec, - Coder> coder, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { return new ShuffleSink<>( options, decodeBase64(getString(spec, PropertyNames.SHUFFLE_WRITER_CONFIG, null)), parseShuffleKind(getString(spec, PropertyNames.SHUFFLE_KIND)), - coder, + typedCoder, addCounterMutator); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java index da228ac635..6abef2c3b6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java @@ -20,86 +20,24 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; -import com.google.cloud.dataflow.sdk.util.Serializer; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import java.util.HashMap; -import java.util.Map; +import javax.annotation.Nullable; /** - * Constructs a Sink from a Dataflow service protocol Sink definition. - * - *

      A SinkFactory concrete "subclass" should define a method with the - * following signature: - *

       {@code
      - * static SomeSinkSubclass create(PipelineOptions, CloudObject,
      - *                                   Coder, ExecutionContext,
      - *                                   CounterSet.AddCounterMutator);
      - * } 
      + * Constructs a {@link Sink} from a Dataflow service {@link CloudObject} specification. */ -public final class SinkFactory { - // Do not instantiate. - private SinkFactory() {} - - /** - * A map from the short names of predefined sinks to their full - * factory class names. - */ - static Map predefinedSinkFactories = new HashMap<>(); - - static { - predefinedSinkFactories.put("TextSink", - TextSinkFactory.class.getName()); - predefinedSinkFactories.put("AvroSink", - AvroSinkFactory.class.getName()); - predefinedSinkFactories.put("IsmSink", - IsmSinkFactory.class.getName()); - predefinedSinkFactories.put("ShuffleSink", - ShuffleSinkFactory.class.getName()); - predefinedSinkFactories.put("PubsubSink", - PubsubSink.class.getName()); - predefinedSinkFactories.put("WindmillSink", - WindmillSink.class.getName()); - } +public interface SinkFactory { /** * Creates a {@link Sink} from a Dataflow API Sink definition. - * - * @throws Exception if the sink could not be decoded and - * constructed */ - public static Sink create( - PipelineOptions options, - com.google.api.services.dataflow.model.Sink cloudSink, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - @SuppressWarnings("unchecked") - Coder coder = Serializer.deserialize(cloudSink.getCodec(), Coder.class); - CloudObject object = CloudObject.fromSpec(cloudSink.getSpec()); - - String className = predefinedSinkFactories.get(object.getClassName()); - if (className == null) { - className = object.getClassName(); - } - - try { - return InstanceBuilder.ofType(new TypeDescriptor>() {}) - .fromClassName(className) - .fromFactoryMethod("create") - .withArg(PipelineOptions.class, options) - .withArg(CloudObject.class, object) - .withArg(Coder.class, coder) - .withArg(ExecutionContext.class, executionContext) - .withArg(CounterSet.AddCounterMutator.class, addCounterMutator) - .build(); - - } catch (ClassNotFoundException exn) { - throw new Exception( - "unable to create a sink from " + cloudSink, exn); - } - } + Sink create( + CloudObject sinkSpec, + Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator) + throws Exception; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java new file mode 100644 index 0000000000..d73c88035b --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.worker.Sink; + +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.Nullable; + +/** + * An immutable registry from {@link String} identifiers (provided to the worker by the Dataflow + * service) to appropriate {@link SinkFactory} instances. + */ +public final class SinkRegistry implements SinkFactory { + + public static SinkRegistry defaultRegistry() { + Map predefinedSinkFactories = new HashMap<>(); + predefinedSinkFactories.put("TextSink", new TextSinkFactory()); + predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.TextSink", + new TextSinkFactory()); + + predefinedSinkFactories.put("AvroSink", new AvroSinkFactory()); + predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.AvroSink", + new AvroSinkFactory()); + + predefinedSinkFactories.put("IsmSink", new IsmSinkFactory()); + predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.IsmSink", + new IsmSinkFactory()); + + predefinedSinkFactories.put("ShuffleSink", new ShuffleSinkFactory()); + predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.ShuffleSink", + new ShuffleSinkFactory()); + + predefinedSinkFactories.put("PubsubSink", new PubsubSink.Factory()); + predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.PubsubSink", + new PubsubSink.Factory()); + + predefinedSinkFactories.put("WindmillSink", new WindmillSink.Factory()); + predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.WindmillSink", + new WindmillSink.Factory()); + + return new SinkRegistry(predefinedSinkFactories); + } + + /** + * Builds a new {@link SinkRegistry} with the provided mutable map of initial mappings. + * + *

      Owns and mutates the provided map, which must be mutable. This constructor should only be + * called by methods in this class that are aware of this requirement and abstract from this + * behavior. + */ + private SinkRegistry(Map factories) { + this.factories = factories; + } + + /** + * A map from the short names of predefined sinks to the associated {@link SinkFactory}. + */ + private final Map factories; + + /** + * Returns a new {@link SinkRegistry} with the provided identifier associated with the + * provided {@link SinkFactory}, overriding any existing binding for that identifier. + */ + public SinkRegistry register(String readerSpecType, SinkFactory factory) { + Map newFactories = new HashMap<>(); + newFactories.putAll(factories); + newFactories.put(readerSpecType, factory); + return new SinkRegistry(newFactories); + } + + /** + * Creates a {@link Sink} from a Dataflow API Sink definition. + * + * @throws Exception if the sink could not be decoded and + * constructed + */ + @Override + public Sink create( + CloudObject sinkSpec, + Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator) + throws Exception { + + String objClassName = sinkSpec.getClassName(); + + SinkFactory factory = factories.get(objClassName); + if (factory == null) { + throw new IllegalArgumentException(String.format( + "Unable to create a Sink: Unknown Sink type in specification: %s", + objClassName)); + } + return factory.create(sinkSpec, coder, options, executionContext, addCounterMutator); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java index d0b2b9b24b..30b91b2cef 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java @@ -26,32 +26,28 @@ import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import javax.annotation.Nullable; + /** - * Creates a TextSink from a CloudObject spec. + * Creates a {@link TextSink} from a {@link CloudObject} spec. */ -public final class TextSinkFactory { - // Do not instantiate. - private TextSinkFactory() {} - - public static TextSink create(PipelineOptions options, - CloudObject spec, - Coder coder, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - return create(spec, coder); - } - - static TextSink create(CloudObject spec, Coder coder) - throws Exception { +public final class TextSinkFactory implements SinkFactory { + @Override + public TextSink create( + CloudObject spec, + Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext executionContext, + @Nullable CounterSet.AddCounterMutator addCounterMutator) + throws Exception { return TextSink.create( - getString(spec, PropertyNames.FILENAME), - "", // No shard template - "", // No suffix - 1, // Exactly one output file - getBoolean(spec, PropertyNames.APPEND_TRAILING_NEWLINES, true), - getString(spec, PropertyNames.HEADER, null), - getString(spec, PropertyNames.FOOTER, null), - coder); + getString(spec, PropertyNames.FILENAME), + "", // No shard template + "", // No suffix + 1, // Exactly one output file + getBoolean(spec, PropertyNames.APPEND_TRAILING_NEWLINES, true), + getString(spec, PropertyNames.HEADER, null), + getString(spec, PropertyNames.FOOTER, null), + coder); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java index 9fc6cf75ef..7c92d3e892 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java @@ -42,6 +42,8 @@ import java.util.HashMap; import java.util.Map; +import javax.annotation.Nullable; + class WindmillSink extends Sink> { private WindmillStreamWriter writer; private final Coder valueCoder; @@ -81,14 +83,21 @@ public static Collection decodeMetadataWindows( return windowsCoder.decode(inStream, Coder.Context.OUTER); } - public static WindmillSink create(PipelineOptions options, - CloudObject spec, - Coder> coder, - ExecutionContext context, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - return new WindmillSink<>(getString(spec, "stream_id"), coder, - (StreamingModeExecutionContext) context); + public static class Factory implements SinkFactory { + @Override + public WindmillSink create( + CloudObject spec, + Coder coder, + @Nullable PipelineOptions options, + @Nullable ExecutionContext context, + @Nullable CounterSet.AddCounterMutator addCounterMutator) + throws Exception { + + @SuppressWarnings("unchecked") + Coder> typedCoder = (Coder>) coder; + return new WindmillSink<>( + getString(spec, "stream_id"), typedCoder, (StreamingModeExecutionContext) context); + } } @Override From 91a418f5f6426a782a9bd27653d497f8e7c0f69b Mon Sep 17 00:00:00 2001 From: robertwb Date: Fri, 5 Feb 2016 13:34:14 -0800 Subject: [PATCH 088/751] Marks getAllowedTimestampSkew as deprecated. This API is dangerous as it does not influence watermark computations. A better API will be released in a future version of Dataflow. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113980532 --- .../com/google/cloud/dataflow/sdk/transforms/DoFn.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java index 85bd433071..af06cc8796 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java @@ -295,7 +295,15 @@ public abstract class ProcessContext extends Context { *

      The default value is {@code Duration.ZERO}, in which case * timestamps can only be shifted forward to future. For infinite * skew, return {@code Duration.millis(Long.MAX_VALUE)}. + * + *

      Note that producing an element whose timestamp is less than the + * current timestamp may result in late data, i.e. returning a non-zero + * value here does not impact watermark calculations used for firing + * windows. + * + * @deprecated does not interact well with the watermark. */ + @Deprecated public Duration getAllowedTimestampSkew() { return Duration.ZERO; } From 6100a17e5da914c0b4931aea9d78c94e90f1d09d Mon Sep 17 00:00:00 2001 From: lcwik Date: Fri, 5 Feb 2016 13:35:23 -0800 Subject: [PATCH 089/751] Add the transforms required to create an Ism side input ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113980662 --- .../sdk/runners/DataflowPipelineRunner.java | 1518 ++++++++++++++++- .../runners/DataflowPipelineTranslator.java | 44 +- .../runners/DataflowPipelineRunnerTest.java | 468 ++++- .../DataflowPipelineTranslatorTest.java | 150 +- .../runners/dataflow/CustomSourcesTest.java | 13 +- .../dataflow/sdk/transforms/ViewTest.java | 1215 +++++++++---- 6 files changed, 2985 insertions(+), 423 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 846c81dc3c..c3efb791ee 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -18,6 +18,9 @@ import static com.google.cloud.dataflow.sdk.util.StringUtils.approximatePTransformName; import static com.google.cloud.dataflow.sdk.util.StringUtils.approximateSimpleName; +import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.dataflow.Dataflow; @@ -25,13 +28,23 @@ import com.google.api.services.dataflow.model.Job; import com.google.api.services.dataflow.model.ListJobsResponse; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; import com.google.cloud.dataflow.sdk.PipelineResult.State; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.CoderRegistry; +import com.google.cloud.dataflow.sdk.coders.IterableCoder; +import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.ListCoder; +import com.google.cloud.dataflow.sdk.coders.MapCoder; +import com.google.cloud.dataflow.sdk.coders.SerializableCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; @@ -48,18 +61,27 @@ import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; +import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.CoderUtils; @@ -71,23 +93,41 @@ import com.google.cloud.dataflow.sdk.util.PathValidator; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.Reshuffle; +import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; +import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.cloud.dataflow.sdk.values.PCollectionTuple; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; +import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.cloud.dataflow.sdk.values.TupleTagList; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; import com.google.common.base.Joiner; +import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.base.Utf8; +import com.google.common.collect.ForwardingMap; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; @@ -99,17 +139,26 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.io.PrintWriter; +import java.io.Serializable; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; /** * A {@link PipelineRunner} that executes the operations in the @@ -150,6 +199,8 @@ public class DataflowPipelineRunner extends PipelineRunner // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; + private final Set> pcollectionsRequiringIndexedFormat; + /** * Project IDs must contain lowercase letters, digits, or dashes. * IDs must start with a letter and may not end with a dash. @@ -165,7 +216,6 @@ public class DataflowPipelineRunner extends PipelineRunner * @return The newly created runner. */ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { - // (Re-)register standard IO factories. Clobbers any prior credentials. IOChannelUtils.registerStandardIOFactories(options); @@ -244,6 +294,8 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { this.options = options; this.dataflowClient = options.getDataflowClient(); this.translator = DataflowPipelineTranslator.fromOptions(options); + this.pcollectionsRequiringIndexedFormat = new HashSet<>(); + this.ptransformViewsWithNonDeterministicKeyCoders = new HashSet<>(); if (options.isStreaming()) { overrides = ImmutableMap., Class>builder() @@ -266,10 +318,18 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { .put(Window.Bound.class, AssignWindows.class) .build(); } else { - overrides = ImmutableMap., Class>builder() - .put(Read.Unbounded.class, UnsupportedIO.class) - .put(Window.Bound.class, AssignWindows.class) - .build(); + ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); + builder.put(Read.Unbounded.class, UnsupportedIO.class); + builder.put(Window.Bound.class, AssignWindows.class); + if (options.getExperiments() != null + && options.getExperiments().contains("enable_ism_side_input")) { + builder.put(View.AsMap.class, BatchViewAsMap.class); + builder.put(View.AsMultimap.class, BatchViewAsMultimap.class); + builder.put(View.AsSingleton.class, BatchViewAsSingleton.class); + builder.put(View.AsList.class, BatchViewAsList.class); + builder.put(View.AsIterable.class, BatchViewAsIterable.class); + } + overrides = builder.build(); } } @@ -319,6 +379,7 @@ public OutputT apply( PTransform customTransform = InstanceBuilder.ofType(customTransformClass) + .withArg(DataflowPipelineRunner.class, this) .withArg(transformClass, transform) .build(); @@ -340,11 +401,14 @@ private PCollection applyWindow( @Override public DataflowPipelineJob run(Pipeline pipeline) { + logWarningIfPCollectionViewHasNonDeterministicKeyCoder(pipeline); + LOG.info("Executing pipeline on the Dataflow Service, which will have billing implications " + "related to Google Compute Engine usage and other Google Cloud Services."); List packages = options.getStager().stageFiles(); - JobSpecification jobSpecification = translator.translate(pipeline, packages); + JobSpecification jobSpecification = + translator.translate(pipeline, this, packages); Job newJob = jobSpecification.getJob(); // Set a unique client_request_id in the CreateJob request. @@ -496,15 +560,1355 @@ public void setHooks(DataflowPipelineRunnerHooks hooks) { ///////////////////////////////////////////////////////////////////////////// + /** Outputs a warning about PCollection views without deterministic key coders. */ + private void logWarningIfPCollectionViewHasNonDeterministicKeyCoder(Pipeline pipeline) { + // We need to wait till this point to determine the names of the transforms since only + // at this time do we know the hierarchy of the transforms otherwise we could + // have just recorded the full names during apply time. + if (!ptransformViewsWithNonDeterministicKeyCoders.isEmpty()) { + final SortedSet ptransformViewNamesWithNonDeterministicKeyCoders = new TreeSet<>(); + pipeline.traverseTopologically(new PipelineVisitor() { + @Override + public void visitValue(PValue value, TransformTreeNode producer) { + } + + @Override + public void visitTransform(TransformTreeNode node) { + if (ptransformViewsWithNonDeterministicKeyCoders.contains(node.getTransform())) { + ptransformViewNamesWithNonDeterministicKeyCoders.add(node.getFullName()); + } + } + + @Override + public void enterCompositeTransform(TransformTreeNode node) { + if (ptransformViewsWithNonDeterministicKeyCoders.contains(node.getTransform())) { + ptransformViewNamesWithNonDeterministicKeyCoders.add(node.getFullName()); + } + } + + @Override + public void leaveCompositeTransform(TransformTreeNode node) { + } + }); + + LOG.warn("Unable to use indexed implementation for View.AsMap and View.AsMultimap for {} " + + "because the key coder is not deterministic. Falling back to singleton implementation " + + "which may cause memory and/or performance problems. Future major versions of " + + "Dataflow will require deterministic key coders.", + ptransformViewNamesWithNonDeterministicKeyCoders); + } + } + + /** + * Returns true if the passed in {@link PCollection} needs to be materialiazed using + * an indexed format. + */ + boolean doesPCollectionRequireIndexedFormat(PCollection pcol) { + return pcollectionsRequiringIndexedFormat.contains(pcol); + } + + /** + * Marks the passed in {@link PCollection} as requiring to be materialized using + * an indexed format. + */ + private void addPCollectionRequiringIndexedFormat(PCollection pcol) { + pcollectionsRequiringIndexedFormat.add(pcol); + } + + /** A set of {@link View}s with non-deterministic key coders. */ + Set> ptransformViewsWithNonDeterministicKeyCoders; + + /** + * Records that the {@link PTransform} requires a deterministic key coder. + */ + private void recordViewUsesNonDeterministicKeyCoder(PTransform ptransform) { + ptransformViewsWithNonDeterministicKeyCoders.add(ptransform); + } + + /** + * A {@link GroupByKey} transform for the {@link DataflowPipelineRunner} which sorts + * values using the secondary key {@code K2}. + * + *

      The {@link PCollection} created created by this {@link PTransform} will have values in + * the empty window. Care must be taken *afterwards* to either re-window + * (using {@link Window#into}) or only use {@link PTransform}s that do not depend on the + * values being within a window. + */ + static class GroupByKeyAndSortValuesOnly + extends PTransform>>, PCollection>>>> { + private GroupByKeyAndSortValuesOnly() { + } + + @Override + public PCollection>>> apply(PCollection>> input) { + PCollection>>> rval = + PCollection.>>>createPrimitiveOutputInternal( + input.getPipeline(), + WindowingStrategy.globalDefault(), + IsBounded.BOUNDED); + + @SuppressWarnings({"unchecked", "rawtypes"}) + KvCoder> inputCoder = (KvCoder) input.getCoder(); + rval.setCoder( + KvCoder.of(inputCoder.getKeyCoder(), + IterableCoder.of(inputCoder.getValueCoder()))); + return rval; + } + } + /** - * Specialized (non-)implementation for {@link Write.Bound} for the Dataflow runner in streaming - * mode. + * A {@link PTransform} that groups the values by a hash of the window's byte representation + * and sorts the values using the windows byte representation. + */ + private static class GroupByWindowHashAsKeyAndWindowAsSortKey extends + PTransform, PCollection>>>>> { + + /** + * A {@link DoFn} that for each element outputs a {@code KV} structure suitable for + * grouping by the hash of the window's byte representation and sorting the grouped values + * using the window's byte representation. + */ + @SystemDoFnInternal + private static class UseWindowHashAsKeyAndWindowAsSortKeyDoFn + extends DoFn>>> implements DoFn.RequiresWindowAccess { + + private final IsmRecordCoder ismCoderForHash; + private UseWindowHashAsKeyAndWindowAsSortKeyDoFn(IsmRecordCoder ismCoderForHash) { + this.ismCoderForHash = ismCoderForHash; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + @SuppressWarnings("unchecked") + W window = (W) c.window(); + c.output( + KV.of(ismCoderForHash.hash(ImmutableList.of(window)), + KV.of(window, + WindowedValue.of( + c.element(), + c.timestamp(), + c.window(), + c.pane())))); + } + } + + private final IsmRecordCoder ismCoderForHash; + private GroupByWindowHashAsKeyAndWindowAsSortKey(IsmRecordCoder ismCoderForHash) { + this.ismCoderForHash = ismCoderForHash; + } + + @Override + public PCollection>>>> apply(PCollection input) { + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + PCollection>>> rval = + input.apply(ParDo.of( + new UseWindowHashAsKeyAndWindowAsSortKeyDoFn(ismCoderForHash))); + rval.setCoder( + KvCoder.of( + VarIntCoder.of(), + KvCoder.of(windowCoder, + FullWindowedValueCoder.of(input.getCoder(), windowCoder)))); + return rval.apply(new GroupByKeyAndSortValuesOnly>()); + } + } + + /** + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} for the + * Dataflow runner in batch mode. + * + *

      Creates a set of files in the {@link IsmFormat} sharded by the hash of the windows + * byte representation and with records having: + *

        + *
      • Key 1: Window
      • + *
      • Value: Windowed value
      • + *
      + */ + static class BatchViewAsSingleton + extends PTransform, PCollectionView> { + + /** + * A {@link DoFn} that outputs {@link IsmRecord}s. These records are structured as follows: + *
        + *
      • Key 1: Window + *
      • Value: Windowed value + *
      + */ + static class IsmRecordForSingularValuePerWindowDoFn + extends DoFn>>>, + IsmRecord>> { + + @Override + public void processElement(ProcessContext c) throws Exception { + Iterator>> iterator = c.element().getValue().iterator(); + while (iterator.hasNext()) { + KV> next = iterator.next(); + c.output( + IsmRecord.of( + ImmutableList.of(next.getKey()), next.getValue())); + } + } + } + + private final DataflowPipelineRunner runner; + private final View.AsSingleton transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchViewAsSingleton(DataflowPipelineRunner runner, View.AsSingleton transform) { + this.runner = runner; + this.transform = transform; + } + + @Override + public PCollectionView apply(PCollection input) { + return BatchViewAsSingleton.applyForSingleton( + runner, + input, + new IsmRecordForSingularValuePerWindowDoFn(), + transform.hasDefaultValue(), + transform.defaultValue(), + input.getCoder()); + } + + static PCollectionView + applyForSingleton( + DataflowPipelineRunner runner, + PCollection input, + DoFn>>>, + IsmRecord>> doFn, + boolean hasDefault, + FinalT defaultValue, + Coder defaultValueCoder) { + + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + + @SuppressWarnings({"rawtypes", "unchecked"}) + PCollectionView view = PCollectionViews.singletonView( + input.getPipeline(), + (WindowingStrategy) input.getWindowingStrategy(), + hasDefault, + defaultValue, + defaultValueCoder); + + IsmRecordCoder> ismCoder = + coderForSingleton(windowCoder, defaultValueCoder); + + PCollection>> reifiedPerWindowAndSorted = input + .apply(new GroupByWindowHashAsKeyAndWindowAsSortKey(ismCoder)) + .apply(ParDo.of(doFn)); + reifiedPerWindowAndSorted.setCoder(ismCoder); + + runner.addPCollectionRequiringIndexedFormat(reifiedPerWindowAndSorted); + return reifiedPerWindowAndSorted.apply( + CreatePCollectionView.>, ViewT>of(view)); + } + + @Override + protected String getKindString() { + return "BatchViewAsSingleton"; + } + + static IsmRecordCoder> coderForSingleton( + Coder windowCoder, Coder valueCoder) { + return IsmRecordCoder.of( + 1, // We hash using only the window + 0, // There are no metadata records + ImmutableList.>of(windowCoder), + FullWindowedValueCoder.of(valueCoder, windowCoder)); + } + } + + /** + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsIterable View.AsIterable} for the + * Dataflow runner in batch mode. + * + *

      Creates a set of {@code Ism} files sharded by the hash of the windows byte representation + * and with records having: + *

        + *
      • Key 1: Window
      • + *
      • Key 2: Index offset within window
      • + *
      • Value: Windowed value
      • + *
      + */ + static class BatchViewAsIterable + extends PTransform, PCollectionView>> { + + private final DataflowPipelineRunner runner; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchViewAsIterable(DataflowPipelineRunner runner, View.AsIterable transform) { + this.runner = runner; + } + + @Override + public PCollectionView> apply(PCollection input) { + PCollectionView> view = PCollectionViews.iterableView( + input.getPipeline(), input.getWindowingStrategy(), input.getCoder()); + return BatchViewAsList.applyForIterableLike(runner, input, view); + } + } + + /** + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsList View.AsList} for the + * Dataflow runner in batch mode. + * + *

      Creates a set of {@code Ism} files sharded by the hash of the window's byte representation + * and with records having: + *

        + *
      • Key 1: Window
      • + *
      • Key 2: Index offset within window
      • + *
      • Value: Windowed value
      • + *
      + */ + static class BatchViewAsList + extends PTransform, PCollectionView>> { + /** + * A {@link DoFn} which creates {@link IsmRecord}s assuming that each element is within the + * global window. Each {@link IsmRecord} has + *
        + *
      • Key 1: Global window
      • + *
      • Key 2: Index offset within window
      • + *
      • Value: Windowed value
      • + *
      + */ + @SystemDoFnInternal + static class ToIsmRecordForGlobalWindowDoFn + extends DoFn>> { + + long indexInBundle; + @Override + public void startBundle(Context c) throws Exception { + indexInBundle = 0; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + c.output(IsmRecord.of( + ImmutableList.of(GlobalWindow.INSTANCE, indexInBundle), + WindowedValue.of( + c.element(), + c.timestamp(), + GlobalWindow.INSTANCE, + c.pane()))); + indexInBundle += 1; + } + } + + /** + * A {@link DoFn} which creates {@link IsmRecord}s comparing successive elements windows + * to locate the window boundaries. The {@link IsmRecord} has: + *
        + *
      • Key 1: Window
      • + *
      • Key 2: Index offset within window
      • + *
      • Value: Windowed value
      • + *
      + */ + @SystemDoFnInternal + static class ToIsmRecordForNonGlobalWindowDoFn + extends DoFn>>>, + IsmRecord>> { + + private final Coder windowCoder; + ToIsmRecordForNonGlobalWindowDoFn(Coder windowCoder) { + this.windowCoder = windowCoder; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + long elementsInWindow = 0; + Optional previousWindowStructuralValue = Optional.absent(); + for (KV> value : c.element().getValue()) { + Object currentWindowStructuralValue = windowCoder.structuralValue(value.getKey()); + // Compare to see if this is a new window so we can reset the index counter i + if (previousWindowStructuralValue.isPresent() + && !previousWindowStructuralValue.get().equals(currentWindowStructuralValue)) { + // Reset i since we have a new window. + elementsInWindow = 0; + } + c.output(IsmRecord.of( + ImmutableList.of(value.getKey(), elementsInWindow), + value.getValue())); + previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); + elementsInWindow += 1; + } + } + } + + private final DataflowPipelineRunner runner; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchViewAsList(DataflowPipelineRunner runner, View.AsList transform) { + this.runner = runner; + } + + @Override + public PCollectionView> apply(PCollection input) { + PCollectionView> view = PCollectionViews.listView( + input.getPipeline(), input.getWindowingStrategy(), input.getCoder()); + return applyForIterableLike(runner, input, view); + } + + static PCollectionView applyForIterableLike( + DataflowPipelineRunner runner, + PCollection input, + PCollectionView view) { + + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + + IsmRecordCoder> ismCoder = coderForListLike(windowCoder, input.getCoder()); + + // If we are working in the global window, we do not need to do a GBK using the window + // as the key since all the elements of the input PCollection are already such. + // We just reify the windowed value while converting them to IsmRecords and generating + // an index based upon where we are within the bundle. Each bundle + // maps to one file exactly. + if (input.getWindowingStrategy().getWindowFn() instanceof GlobalWindows) { + PCollection>> reifiedPerWindowAndSorted = + input.apply(ParDo.of(new ToIsmRecordForGlobalWindowDoFn())); + reifiedPerWindowAndSorted.setCoder(ismCoder); + + runner.addPCollectionRequiringIndexedFormat(reifiedPerWindowAndSorted); + return reifiedPerWindowAndSorted.apply( + CreatePCollectionView.>, ViewT>of(view)); + } + + PCollection>> reifiedPerWindowAndSorted = input + .apply(new GroupByWindowHashAsKeyAndWindowAsSortKey(ismCoder)) + .apply(ParDo.of(new ToIsmRecordForNonGlobalWindowDoFn(windowCoder))); + reifiedPerWindowAndSorted.setCoder(ismCoder); + + runner.addPCollectionRequiringIndexedFormat(reifiedPerWindowAndSorted); + return reifiedPerWindowAndSorted.apply( + CreatePCollectionView.>, ViewT>of(view)); + } + + @Override + protected String getKindString() { + return "BatchViewAsList"; + } + + static IsmRecordCoder> coderForListLike( + Coder windowCoder, Coder valueCoder) { + // TODO: swap to use a variable length long coder which has values which compare + // the same as their byte representation compare lexicographically within the key coder + return IsmRecordCoder.of( + 1, // We hash using only the window + 0, // There are no metadata records + ImmutableList.of(windowCoder, BigEndianLongCoder.of()), + FullWindowedValueCoder.of(valueCoder, windowCoder)); + } + } + + /** + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsMap View.AsMap} for the + * Dataflow runner in batch mode. + * + *

      Creates a set of {@code Ism} files sharded by the hash of the key's byte + * representation. Each record is structured as follows: + *

        + *
      • Key 1: User key K
      • + *
      • Key 2: Window
      • + *
      • Key 3: 0L (constant)
      • + *
      • Value: Windowed value
      • + *
      + * + *

      Alongside the data records, there are the following metadata records: + *

        + *
      • Key 1: Metadata Key
      • + *
      • Key 2: Window
      • + *
      • Key 3: Index [0, size of map]
      • + *
      • Value: variable length long byte representation of size of map if index is 0, + * otherwise the byte representation of a key
      • + *
      + * The {@code [META, Window, 0]} record stores the number of unique keys per window, while + * {@code [META, Window, i]} for {@code i} in {@code [1, size of map]} stores a the users key. + * This allows for one to access the size of the map by looking at {@code [META, Window, 0]} + * and iterate over all the keys by accessing {@code [META, Window, i]} for {@code i} in + * {@code [1, size of map]}. + * + *

      Note that in the case of a non-deterministic key coder, we fallback to using + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} printing + * a warning to users to specify a deterministic key coder. + */ + static class BatchViewAsMap + extends PTransform>, PCollectionView>> { + + /** + * A {@link DoFn} which groups elements by window boundaries. For each group, + * the group of elements is transformed into a {@link TransformedMap}. + * The transformed {@code Map} is backed by a {@code Map>} + * and contains a function {@code WindowedValue -> V}. + * + *

      Outputs {@link IsmRecord}s having: + *

        + *
      • Key 1: Window
      • + *
      • Value: Transformed map containing a transform that removes the encapsulation + * of the window around each value, + * {@code Map> -> Map}.
      • + *
      + */ + static class ToMapDoFn + extends DoFn>>>>, + IsmRecord, + V>>>> { + + private final Coder windowCoder; + ToMapDoFn(Coder windowCoder) { + this.windowCoder = windowCoder; + } + + @Override + public void processElement(ProcessContext c) + throws Exception { + Optional previousWindowStructuralValue = Optional.absent(); + Optional previousWindow = Optional.absent(); + Map> map = new HashMap<>(); + for (KV>> kv : c.element().getValue()) { + Object currentWindowStructuralValue = windowCoder.structuralValue(kv.getKey()); + if (previousWindowStructuralValue.isPresent() + && !previousWindowStructuralValue.get().equals(currentWindowStructuralValue)) { + // Construct the transformed map containing all the elements since we + // are at a window boundary. + c.output(IsmRecord.of( + ImmutableList.of(previousWindow.get()), + valueInEmptyWindows(new TransformedMap<>(WindowedValueToValue.of(), map)))); + map = new HashMap<>(); + } + + // Verify that the user isn't trying to insert the same key multiple times. + checkState(!map.containsKey(kv.getValue().getValue().getKey()), + "Multiple values [%s, %s] found for single key [%s] within window [%s].", + map.get(kv.getValue().getValue().getKey()), + kv.getValue().getValue().getValue(), + kv.getKey()); + map.put(kv.getValue().getValue().getKey(), + kv.getValue().withValue(kv.getValue().getValue().getValue())); + previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); + previousWindow = Optional.of(kv.getKey()); + } + + // The last value for this hash is guaranteed to be at a window boundary + // so we output a transformed map containing all the elements since the last + // window boundary. + c.output(IsmRecord.of( + ImmutableList.of(previousWindow.get()), + valueInEmptyWindows(new TransformedMap<>(WindowedValueToValue.of(), map)))); + } + } + + private final DataflowPipelineRunner runner; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchViewAsMap(DataflowPipelineRunner runner, View.AsMap transform) { + this.runner = runner; + } + + @Override + public PCollectionView> apply(PCollection> input) { + return this.applyInternal(input); + } + + private PCollectionView> + applyInternal(PCollection> input) { + + @SuppressWarnings({"rawtypes", "unchecked"}) + KvCoder inputCoder = (KvCoder) input.getCoder(); + try { + PCollectionView> view = PCollectionViews.mapView( + input.getPipeline(), input.getWindowingStrategy(), inputCoder); + return BatchViewAsMultimap.applyForMapLike(runner, input, view, true /* unique keys */); + } catch (NonDeterministicException e) { + runner.recordViewUsesNonDeterministicKeyCoder(this); + + // Since the key coder is not deterministic, we convert the map into a singleton + // and return a singleton view equivalent. + return applyForSingletonFallback(input); + } + } + + @Override + protected String getKindString() { + return "BatchViewAsMap"; + } + + /** Transforms the input {@link PCollection} into a singleton {@link Map} per window. */ + private PCollectionView> + applyForSingletonFallback(PCollection> input) { + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + + @SuppressWarnings({"rawtypes", "unchecked"}) + KvCoder inputCoder = (KvCoder) input.getCoder(); + + @SuppressWarnings({"unchecked", "rawtypes"}) + Coder, V>> transformCoder = + (Coder) SerializableCoder.of(WindowedValueToValue.class); + + Coder, V>> finalValueCoder = + TransformedMapCoder.of( + transformCoder, + MapCoder.of( + inputCoder.getKeyCoder(), + FullWindowedValueCoder.of(inputCoder.getValueCoder(), windowCoder))); + + TransformedMap, V> defaultValue = new TransformedMap<>( + WindowedValueToValue.of(), + ImmutableMap.>of()); + + return BatchViewAsSingleton., + TransformedMap, V>, + Map, + W> applyForSingleton( + runner, + input, + new ToMapDoFn(windowCoder), + true, + defaultValue, + finalValueCoder); + } + } + + /** + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsMultimap View.AsMultimap} for the + * Dataflow runner in batch mode. + * + *

      Creates a set of {@code Ism} files sharded by the hash of the key's byte + * representation. Each record is structured as follows: + *

        + *
      • Key 1: User key K
      • + *
      • Key 2: Window
      • + *
      • Key 3: Index offset for a given key and window.
      • + *
      • Value: Windowed value
      • + *
      + * + *

      Alongside the data records, there are the following metadata records: + *

        + *
      • Key 1: Metadata Key
      • + *
      • Key 2: Window
      • + *
      • Key 3: Index [0, size of map]
      • + *
      • Value: variable length long byte representation of size of map if index is 0, + * otherwise the byte representation of a key
      • + *
      + * The {@code [META, Window, 0]} record stores the number of unique keys per window, while + * {@code [META, Window, i]} for {@code i} in {@code [1, size of map]} stores a the users key. + * This allows for one to access the size of the map by looking at {@code [META, Window, 0]} + * and iterate over all the keys by accessing {@code [META, Window, i]} for {@code i} in + * {@code [1, size of map]}. + * + *

      Note that in the case of a non-deterministic key coder, we fallback to using + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} printing + * a warning to users to specify a deterministic key coder. + */ + static class BatchViewAsMultimap + extends PTransform>, PCollectionView>>> { + /** + * A {@link PTransform} that groups elements by the hash of window's byte representation + * if the input {@link PCollection} is not within the global window. Otherwise by the hash + * of the window and key's byte representation. This {@link PTransform} also sorts + * the values by the combination of the window and key's byte representations. + */ + private static class GroupByKeyHashAndSortByKeyAndWindow + extends PTransform>, + PCollection, WindowedValue>>>>> { + + @SystemDoFnInternal + private static class GroupByKeyHashAndSortByKeyAndWindowDoFn + extends DoFn, KV, WindowedValue>>> + implements DoFn.RequiresWindowAccess { + + private final IsmRecordCoder coder; + private GroupByKeyHashAndSortByKeyAndWindowDoFn(IsmRecordCoder coder) { + this.coder = coder; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + @SuppressWarnings("unchecked") + W window = (W) c.window(); + + c.output( + KV.of(coder.hash(ImmutableList.of(c.element().getKey())), + KV.of(KV.of(c.element().getKey(), window), + WindowedValue.of( + c.element().getValue(), + c.timestamp(), + (BoundedWindow) window, + c.pane())))); + } + } + + private final IsmRecordCoder coder; + public GroupByKeyHashAndSortByKeyAndWindow(IsmRecordCoder coder) { + this.coder = coder; + } + + @Override + public PCollection, WindowedValue>>>> + apply(PCollection> input) { + + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + @SuppressWarnings("unchecked") + KvCoder inputCoder = (KvCoder) input.getCoder(); + + PCollection, WindowedValue>>> keyedByHash; + keyedByHash = input.apply( + ParDo.of(new GroupByKeyHashAndSortByKeyAndWindowDoFn(coder))); + keyedByHash.setCoder( + KvCoder.of( + VarIntCoder.of(), + KvCoder.of(KvCoder.of(inputCoder.getKeyCoder(), windowCoder), + FullWindowedValueCoder.of(inputCoder.getValueCoder(), windowCoder)))); + + return keyedByHash.apply( + new GroupByKeyAndSortValuesOnly, WindowedValue>()); + } + } + + /** + * A {@link DoFn} which creates {@link IsmRecord}s comparing successive elements windows + * and keys to locate window and key boundaries. The main output {@link IsmRecord}s have: + *

        + *
      • Key 1: Window
      • + *
      • Key 2: User key K
      • + *
      • Key 3: Index offset for a given key and window.
      • + *
      • Value: Windowed value
      • + *
      + * + *

      Additionally, we output all the unique keys per window seen to {@code outputForEntrySet} + * and the unique key count per window to {@code outputForSize}. + * + *

      Finally, if this DoFn has been requested to perform unique key checking, it will + * throw an {@link IllegalStateException} if more than one key per window is found. + */ + static class ToIsmRecordForMapLikeDoFn + extends DoFn, WindowedValue>>>, + IsmRecord>> { + + private final TupleTag>> outputForSize; + private final TupleTag>> outputForEntrySet; + private final Coder windowCoder; + private final Coder keyCoder; + private final IsmRecordCoder> ismCoder; + private final boolean uniqueKeysExpected; + ToIsmRecordForMapLikeDoFn( + TupleTag>> outputForSize, + TupleTag>> outputForEntrySet, + Coder windowCoder, + Coder keyCoder, + IsmRecordCoder> ismCoder, + boolean uniqueKeysExpected) { + this.outputForSize = outputForSize; + this.outputForEntrySet = outputForEntrySet; + this.windowCoder = windowCoder; + this.keyCoder = keyCoder; + this.ismCoder = ismCoder; + this.uniqueKeysExpected = uniqueKeysExpected; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + long currentKeyIndex = 0; + // We use one based indexing while counting + long currentUniqueKeyCounter = 1; + Iterator, WindowedValue>> iterator = c.element().getValue().iterator(); + + KV, WindowedValue> currentValue = iterator.next(); + Object currentKeyStructuralValue = + keyCoder.structuralValue(currentValue.getKey().getKey()); + Object currentWindowStructuralValue = + windowCoder.structuralValue(currentValue.getKey().getValue()); + + while (iterator.hasNext()) { + KV, WindowedValue> nextValue = iterator.next(); + Object nextKeyStructuralValue = + keyCoder.structuralValue(nextValue.getKey().getKey()); + Object nextWindowStructuralValue = + windowCoder.structuralValue(nextValue.getKey().getValue()); + + outputDataRecord(c, currentValue, currentKeyIndex); + + final long nextKeyIndex; + final long nextUniqueKeyCounter; + + // Check to see if its a new window + if (!currentWindowStructuralValue.equals(nextWindowStructuralValue)) { + // The next value is a new window, so we output for size the number of unique keys + // seen and the last key of the window. We also reset the next key index the unique + // key counter. + outputMetadataRecordForSize(c, currentValue, currentUniqueKeyCounter); + outputMetadataRecordForEntrySet(c, currentValue); + + nextKeyIndex = 0; + nextUniqueKeyCounter = 1; + } else if (!currentKeyStructuralValue.equals(nextKeyStructuralValue)){ + // It is a new key within the same window so output the key for the entry set, + // reset the key index and increase the count of unique keys seen within this window. + outputMetadataRecordForEntrySet(c, currentValue); + + nextKeyIndex = 0; + nextUniqueKeyCounter = currentUniqueKeyCounter + 1; + } else if (!uniqueKeysExpected) { + // It is not a new key so we don't have to output the number of elements in this + // window or increase the unique key counter. All we do is increase the key index. + + nextKeyIndex = currentKeyIndex + 1; + nextUniqueKeyCounter = currentUniqueKeyCounter; + } else { + throw new IllegalStateException(String.format( + "Unique keys are expected but found key %s with values %s and %s in window %s.", + currentValue.getKey().getKey(), + currentValue.getValue().getValue(), + nextValue.getValue().getValue(), + currentValue.getKey().getValue())); + } + + currentValue = nextValue; + currentWindowStructuralValue = nextWindowStructuralValue; + currentKeyStructuralValue = nextKeyStructuralValue; + currentKeyIndex = nextKeyIndex; + currentUniqueKeyCounter = nextUniqueKeyCounter; + } + + outputDataRecord(c, currentValue, currentKeyIndex); + outputMetadataRecordForSize(c, currentValue, currentUniqueKeyCounter); + // The last value for this hash is guaranteed to be at a window boundary + // so we output a record with the number of unique keys seen. + outputMetadataRecordForEntrySet(c, currentValue); + } + + /** This outputs the data record. */ + private void outputDataRecord( + ProcessContext c, KV, WindowedValue> value, long keyIndex) { + IsmRecord> ismRecord = IsmRecord.of( + ImmutableList.of( + value.getKey().getKey(), + value.getKey().getValue(), + keyIndex), + value.getValue()); + c.output(ismRecord); + } + + /** + * This outputs records which will be used to compute the number of keys for a given window. + */ + private void outputMetadataRecordForSize( + ProcessContext c, KV, WindowedValue> value, long uniqueKeyCount) { + c.sideOutput(outputForSize, + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), + value.getKey().getValue())), + KV.of(value.getKey().getValue(), uniqueKeyCount))); + } + + /** This outputs records which will be used to construct the entry set. */ + private void outputMetadataRecordForEntrySet( + ProcessContext c, KV, WindowedValue> value) { + c.sideOutput(outputForEntrySet, + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), + value.getKey().getValue())), + KV.of(value.getKey().getValue(), value.getKey().getKey()))); + } + } + + /** + * A {@link DoFn} which outputs a metadata {@link IsmRecord} per window of: + *

        + *
      • Key 1: META key
      • + *
      • Key 2: window
      • + *
      • Key 3: 0L (constant)
      • + *
      • Value: sum of values for window
      • + *
      + * + *

      This {@link DoFn} is meant to be used to compute the number of unique keys + * per window for map and multimap side inputs. + */ + static class ToIsmMetadataRecordForSizeDoFn + extends DoFn>>, IsmRecord>> { + private final Coder windowCoder; + ToIsmMetadataRecordForSizeDoFn(Coder windowCoder) { + this.windowCoder = windowCoder; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + Iterator> iterator = c.element().getValue().iterator(); + KV currentValue = iterator.next(); + Object currentWindowStructuralValue = windowCoder.structuralValue(currentValue.getKey()); + long size = 0; + while (iterator.hasNext()) { + KV nextValue = iterator.next(); + Object nextWindowStructuralValue = windowCoder.structuralValue(nextValue.getKey()); + + size += currentValue.getValue(); + if (!currentWindowStructuralValue.equals(nextWindowStructuralValue)) { + c.output(IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), 0L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), size))); + size = 0; + } + + currentValue = nextValue; + currentWindowStructuralValue = nextWindowStructuralValue; + } + + size += currentValue.getValue(); + // Output the final value since it is guaranteed to be on a window boundary. + c.output(IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), 0L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), size))); + } + } + + /** + * A {@link DoFn} which outputs a metadata {@link IsmRecord} per window and key pair of: + *

        + *
      • Key 1: META key
      • + *
      • Key 2: window
      • + *
      • Key 3: index offset (1-based index)
      • + *
      • Value: key
      • + *
      + * + *

      This {@link DoFn} is meant to be used to output index to key records + * per window for map and multimap side inputs. + */ + static class ToIsmMetadataRecordForKeyDoFn + extends DoFn>>, IsmRecord>> { + + private final Coder keyCoder; + private final Coder windowCoder; + ToIsmMetadataRecordForKeyDoFn(Coder keyCoder, Coder windowCoder) { + this.keyCoder = keyCoder; + this.windowCoder = windowCoder; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + Iterator> iterator = c.element().getValue().iterator(); + KV currentValue = iterator.next(); + Object currentWindowStructuralValue = windowCoder.structuralValue(currentValue.getKey()); + long elementsInWindow = 1; + while (iterator.hasNext()) { + KV nextValue = iterator.next(); + Object nextWindowStructuralValue = windowCoder.structuralValue(nextValue.getKey()); + + c.output(IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), elementsInWindow), + CoderUtils.encodeToByteArray(keyCoder, currentValue.getValue()))); + elementsInWindow += 1; + + if (!currentWindowStructuralValue.equals(nextWindowStructuralValue)) { + elementsInWindow = 1; + } + + currentValue = nextValue; + currentWindowStructuralValue = nextWindowStructuralValue; + } + + // Output the final value since it is guaranteed to be on a window boundary. + c.output(IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), elementsInWindow), + CoderUtils.encodeToByteArray(keyCoder, currentValue.getValue()))); + } + } + + /** + * A {@link DoFn} which partitions sets of elements by window boundaries. Within each + * partition, the set of elements is transformed into a {@link TransformedMap}. + * The transformed {@code Map>} is backed by a + * {@code Map>>} and contains a function + * {@code Iterable> -> Iterable}. + * + *

      Outputs {@link IsmRecord}s having: + *

        + *
      • Key 1: Window
      • + *
      • Value: Transformed map containing a transform that removes the encapsulation + * of the window around each value, + * {@code Map>> -> Map>}.
      • + *
      + */ + static class ToMultimapDoFn + extends DoFn>>>>, + IsmRecord>, + Iterable>>>> { + + private final Coder windowCoder; + ToMultimapDoFn(Coder windowCoder) { + this.windowCoder = windowCoder; + } + + @Override + public void processElement(ProcessContext c) + throws Exception { + Optional previousWindowStructuralValue = Optional.absent(); + Optional previousWindow = Optional.absent(); + Multimap> multimap = HashMultimap.create(); + for (KV>> kv : c.element().getValue()) { + Object currentWindowStructuralValue = windowCoder.structuralValue(kv.getKey()); + if (previousWindowStructuralValue.isPresent() + && !previousWindowStructuralValue.get().equals(currentWindowStructuralValue)) { + // Construct the transformed map containing all the elements since we + // are at a window boundary. + @SuppressWarnings({"unchecked", "rawtypes"}) + Map>> resultMap = (Map) multimap.asMap(); + c.output(IsmRecord.>, + Iterable>>>of( + ImmutableList.of(previousWindow.get()), + valueInEmptyWindows( + new TransformedMap<>( + IterableWithWindowedValuesToIterable.of(), resultMap)))); + multimap = HashMultimap.create(); + } + + multimap.put(kv.getValue().getValue().getKey(), + kv.getValue().withValue(kv.getValue().getValue().getValue())); + previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); + previousWindow = Optional.of(kv.getKey()); + } + + // The last value for this hash is guaranteed to be at a window boundary + // so we output a transformed map containing all the elements since the last + // window boundary. + @SuppressWarnings({"unchecked", "rawtypes"}) + Map>> resultMap = (Map) multimap.asMap(); + c.output(IsmRecord.>, + Iterable>>>of( + ImmutableList.of(previousWindow.get()), + valueInEmptyWindows( + new TransformedMap<>(IterableWithWindowedValuesToIterable.of(), resultMap)))); + } + } + + private final DataflowPipelineRunner runner; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchViewAsMultimap(DataflowPipelineRunner runner, View.AsMultimap transform) { + this.runner = runner; + } + + @Override + public PCollectionView>> apply(PCollection> input) { + return this.applyInternal(input); + } + + private PCollectionView>> + applyInternal(PCollection> input) { + @SuppressWarnings({"rawtypes", "unchecked"}) + KvCoder inputCoder = (KvCoder) input.getCoder(); + try { + PCollectionView>> view = PCollectionViews.multimapView( + input.getPipeline(), input.getWindowingStrategy(), inputCoder); + + return applyForMapLike(runner, input, view, false /* unique keys not expected */); + } catch (NonDeterministicException e) { + runner.recordViewUsesNonDeterministicKeyCoder(this); + + // Since the key coder is not deterministic, we convert the map into a singleton + // and return a singleton view equivalent. + return applyForSingletonFallback(input); + } + } + + /** Transforms the input {@link PCollection} into a singleton {@link Map} per window. */ + private PCollectionView>> + applyForSingletonFallback(PCollection> input) { + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + + @SuppressWarnings({"rawtypes", "unchecked"}) + KvCoder inputCoder = (KvCoder) input.getCoder(); + + @SuppressWarnings({"unchecked", "rawtypes"}) + Coder>, Iterable>> transformCoder = + (Coder) SerializableCoder.of(IterableWithWindowedValuesToIterable.class); + + Coder>, Iterable>> finalValueCoder = + TransformedMapCoder.of( + transformCoder, + MapCoder.of( + inputCoder.getKeyCoder(), + IterableCoder.of( + FullWindowedValueCoder.of(inputCoder.getValueCoder(), windowCoder)))); + + TransformedMap>, Iterable> defaultValue = + new TransformedMap<>( + IterableWithWindowedValuesToIterable.of(), + ImmutableMap.>>of()); + + return BatchViewAsSingleton., + TransformedMap>, Iterable>, + Map>, + W> applyForSingleton( + runner, + input, + new ToMultimapDoFn(windowCoder), + true, + defaultValue, + finalValueCoder); + } + + + + private static PCollectionView applyForMapLike( + DataflowPipelineRunner runner, + PCollection> input, + PCollectionView view, + boolean uniqueKeysExpected) throws NonDeterministicException { + + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + + @SuppressWarnings({"rawtypes", "unchecked"}) + KvCoder inputCoder = (KvCoder) input.getCoder(); + + // If our key coder is deterministic, we can use the key portion of each KV + // part of a composite key containing the window , key and index. + inputCoder.getKeyCoder().verifyDeterministic(); + + IsmRecordCoder> ismCoder = + coderForMapLike(windowCoder, inputCoder.getKeyCoder(), inputCoder.getValueCoder()); + + // Create the various output tags representing the main output containing the data stream + // and the side outputs containing the metadata about the size and entry set. + TupleTag>> mainOutputTag = new TupleTag<>(); + TupleTag>> outputForSizeTag = new TupleTag<>(); + TupleTag>> outputForEntrySetTag = new TupleTag<>(); + + // Process all the elements grouped by key hash, and sorted by key and then window + // outputting to all the outputs defined above. + PCollectionTuple outputTuple = input + .apply("GBKaSVForData", new GroupByKeyHashAndSortByKeyAndWindow(ismCoder)) + .apply(ParDo.of(new ToIsmRecordForMapLikeDoFn( + outputForSizeTag, outputForEntrySetTag, + windowCoder, inputCoder.getKeyCoder(), ismCoder, uniqueKeysExpected)) + .withOutputTags(mainOutputTag, + TupleTagList.of( + ImmutableList.>of(outputForSizeTag, + outputForEntrySetTag)))); + + // Set the coder on the main data output. + PCollection>> perHashWithReifiedWindows = + outputTuple.get(mainOutputTag); + perHashWithReifiedWindows.setCoder(ismCoder); + + // Set the coder on the metadata output for size and process the entries + // producing a [META, Window, 0L] record per window storing the number of unique keys + // for each window. + PCollection>> outputForSize = outputTuple.get(outputForSizeTag); + outputForSize.setCoder( + KvCoder.of(VarIntCoder.of(), + KvCoder.of(windowCoder, VarLongCoder.of()))); + PCollection>> windowMapSizeMetadata = outputForSize + .apply("GBKaSVForSize", new GroupByKeyAndSortValuesOnly()) + .apply(ParDo.of(new ToIsmMetadataRecordForSizeDoFn(windowCoder))); + windowMapSizeMetadata.setCoder(ismCoder); + + // Set the coder on the metadata output destined to build the entry set and process the + // entries producing a [META, Window, Index] record per window key pair storing the key. + PCollection>> outputForEntrySet = + outputTuple.get(outputForEntrySetTag); + outputForEntrySet.setCoder( + KvCoder.of(VarIntCoder.of(), + KvCoder.of(windowCoder, inputCoder.getKeyCoder()))); + PCollection>> windowMapKeysMetadata = outputForEntrySet + .apply("GBKaSVForKeys", new GroupByKeyAndSortValuesOnly()) + .apply(ParDo.of( + new ToIsmMetadataRecordForKeyDoFn(inputCoder.getKeyCoder(), windowCoder))); + windowMapKeysMetadata.setCoder(ismCoder); + + // Set that all these outputs should be materialized using an indexed format. + runner.addPCollectionRequiringIndexedFormat(perHashWithReifiedWindows); + runner.addPCollectionRequiringIndexedFormat(windowMapSizeMetadata); + runner.addPCollectionRequiringIndexedFormat(windowMapKeysMetadata); + + PCollectionList>> outputs = + PCollectionList.of(ImmutableList.of( + perHashWithReifiedWindows, windowMapSizeMetadata, windowMapKeysMetadata)); + + return Pipeline.applyTransform(outputs, + Flatten.>>pCollections()) + .apply(CreatePCollectionView.>, + ViewT>of(view)); + } + + @Override + protected String getKindString() { + return "BatchViewAsMultimap"; + } + + static IsmRecordCoder> coderForMapLike( + Coder windowCoder, Coder keyCoder, Coder valueCoder) { + // TODO: swap to use a variable length long coder which has values which compare + // the same as their byte representation compare lexicographically within the key coder + return IsmRecordCoder.of( + 1, // We use only the key for hashing when producing value records + 2, // Since the key is not present, we add the window to the hash when + // producing metadata records + ImmutableList.of( + MetadataKeyCoder.of(keyCoder), + windowCoder, + BigEndianLongCoder.of()), + FullWindowedValueCoder.of(valueCoder, windowCoder)); + } + } + + /** + * A {@code Map} backed by a {@code Map} and a function that transforms + * {@code V1 -> V2}. + */ + static class TransformedMap + extends ForwardingMap { + private final Function transform; + private final Map originalMap; + private final Map transformedMap; + + private TransformedMap(Function transform, Map originalMap) { + this.transform = transform; + this.originalMap = Collections.unmodifiableMap(originalMap); + this.transformedMap = Maps.transformValues(originalMap, transform); + } + + @Override + protected Map delegate() { + return transformedMap; + } + } + + /** + * A {@link Coder} for {@link TransformedMap}s. + */ + static class TransformedMapCoder + extends StandardCoder> { + private final Coder> transformCoder; + private final Coder> originalMapCoder; + + private TransformedMapCoder( + Coder> transformCoder, Coder> originalMapCoder) { + this.transformCoder = transformCoder; + this.originalMapCoder = originalMapCoder; + } + + public static TransformedMapCoder of( + Coder> transformCoder, Coder> originalMapCoder) { + return new TransformedMapCoder<>(transformCoder, originalMapCoder); + } + + @JsonCreator + public static TransformedMapCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) + List> components) { + checkArgument(components.size() == 2, + "Expecting 2 components, got " + components.size()); + @SuppressWarnings("unchecked") + Coder> transformCoder = (Coder>) components.get(0); + @SuppressWarnings("unchecked") + Coder> originalMapCoder = (Coder>) components.get(1); + return of(transformCoder, originalMapCoder); + } + + @Override + public void encode(TransformedMap value, OutputStream outStream, + Coder.Context context) throws CoderException, IOException { + transformCoder.encode(value.transform, outStream, context.nested()); + originalMapCoder.encode(value.originalMap, outStream, context.nested()); + } + + @Override + public TransformedMap decode( + InputStream inStream, Coder.Context context) throws CoderException, IOException { + return new TransformedMap<>( + transformCoder.decode(inStream, context.nested()), + originalMapCoder.decode(inStream, context.nested())); + } + + @Override + public List> getCoderArguments() { + return Arrays.asList(transformCoder, originalMapCoder); + } + + @Override + public void verifyDeterministic() + throws com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException { + verifyDeterministic("Expected transform coder to be deterministic.", transformCoder); + verifyDeterministic("Expected map coder to be deterministic.", originalMapCoder); + } + } + + /** + * A {@link Function} which converts {@code WindowedValue} to {@code V}. + */ + private static class WindowedValueToValue implements + Function, V>, Serializable { + private static final WindowedValueToValue INSTANCE = new WindowedValueToValue<>(); + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static WindowedValueToValue of() { + return (WindowedValueToValue) INSTANCE; + } + + @Override + public V apply(WindowedValue input) { + return input.getValue(); + } + } + + /** + * A {@link Function} which converts {@code Iterable>} to {@code Iterable}. + */ + private static class IterableWithWindowedValuesToIterable implements + Function>, Iterable>, Serializable { + private static final IterableWithWindowedValuesToIterable INSTANCE = + new IterableWithWindowedValuesToIterable<>(); + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static IterableWithWindowedValuesToIterable of() { + return (IterableWithWindowedValuesToIterable) INSTANCE; + } + + @Override + public Iterable apply(Iterable> input) { + return Iterables.transform(input, WindowedValueToValue.of()); + } + } + + /** + * Specialized (non-)implementation for + * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} + * for the Dataflow runner in streaming mode. */ private static class StreamingWrite extends PTransform, PDone> { /** * Builds an instance of this class from the overridden transform. */ - public StreamingWrite(Write.Bound transform) { } + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public StreamingWrite(DataflowPipelineRunner runner, Write.Bound transform) { } @Override public PDone apply(PCollection input) { @@ -519,13 +1923,13 @@ protected String getKindString() { } /** - * Specialized implementation for {@link PubsubIO.Write} for the Dataflow runner in streaming - * mode. + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.io.PubsubIO.Write PubsubIO.Write} for the + * Dataflow runner in streaming mode. * *

      For internal use only. Subject to change at any time. * - *

      Public so the {@link com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator} - * can access. + *

      Public so the {@link PubsubIOTranslator} can access. */ public static class StreamingPubsubIOWrite extends PTransform, PDone> { private final PubsubIO.Write.Bound transform; @@ -533,7 +1937,8 @@ public static class StreamingPubsubIOWrite extends PTransform, /** * Builds an instance of this class from the overridden transform. */ - public StreamingPubsubIOWrite(PubsubIO.Write.Bound transform) { + public StreamingPubsubIOWrite( + DataflowPipelineRunner runner, PubsubIO.Write.Bound transform) { this.transform = transform; } @@ -553,8 +1958,9 @@ protected String getKindString() { } /** - * Specialized implementation for {@link Read.Unbounded} for the Dataflow runner in streaming - * mode. + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.io.Read.Unbounded Read.Unbounded} for the + * Dataflow runner in streaming mode. * *

      In particular, if an UnboundedSource requires deduplication, then features of WindmillSink * are leveraged to do the deduplication. @@ -566,7 +1972,7 @@ private static class StreamingUnboundedRead extends PTransform transform) { + public StreamingUnboundedRead(DataflowPipelineRunner runner, Read.Unbounded transform) { this.source = transform.getSource(); } @@ -669,7 +2075,9 @@ public void processElement(ProcessContext c) { } /** - * Specialized implementation for {@link Create.Values} for the Dataflow runner in streaming mode. + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.Create.Values Create.Values} for the + * Dataflow runner in streaming mode. */ private static class StreamingCreate extends PTransform> { private final Create.Values transform; @@ -678,7 +2086,7 @@ private static class StreamingCreate extends PTransform transform) { + public StreamingCreate(DataflowPipelineRunner runner, Create.Values transform) { this.transform = transform; } @@ -785,12 +2193,18 @@ public void processElement(ProcessContext c) throws Exception { } /** - * Specialized implementation for {@link View.AsMap} for the Dataflow runner in streaming mode. + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsMap View.AsMap} + * for the Dataflow runner in streaming mode. */ private static class StreamingViewAsMap extends PTransform>, PCollectionView>> { + private final DataflowPipelineRunner runner; + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsMap(View.AsMap transform) { } + public StreamingViewAsMap(DataflowPipelineRunner runner, View.AsMap transform) { + this.runner = runner; + } @Override public PCollectionView> apply(PCollection> input) { @@ -800,6 +2214,14 @@ public PCollectionView> apply(PCollection> input) { input.getWindowingStrategy(), input.getCoder()); + @SuppressWarnings({"rawtypes", "unchecked"}) + KvCoder inputCoder = (KvCoder) input.getCoder(); + try { + inputCoder.getKeyCoder().verifyDeterministic(); + } catch (NonDeterministicException e) { + runner.recordViewUsesNonDeterministicKeyCoder(this); + } + return input .apply(Combine.globally(new Concatenate>()).withoutDefaults()) .apply(ParDo.of(StreamingPCollectionViewWriterFn.create(view, input.getCoder()))) @@ -813,15 +2235,21 @@ protected String getKindString() { } /** - * Specialized expansion for {@link View.AsMultimap} for the Dataflow runner in streaming mode. + * Specialized expansion for {@link + * com.google.cloud.dataflow.sdk.transforms.View.AsMultimap View.AsMultimap} for the + * Dataflow runner in streaming mode. */ private static class StreamingViewAsMultimap - extends PTransform>, PCollectionView>>> { + extends PTransform>, PCollectionView>>> { + private final DataflowPipelineRunner runner; + /** * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsMultimap(View.AsMultimap transform) { } + public StreamingViewAsMultimap(DataflowPipelineRunner runner, View.AsMultimap transform) { + this.runner = runner; + } @Override public PCollectionView>> apply(PCollection> input) { @@ -831,6 +2259,14 @@ public PCollectionView>> apply(PCollection> input) { input.getWindowingStrategy(), input.getCoder()); + @SuppressWarnings({"rawtypes", "unchecked"}) + KvCoder inputCoder = (KvCoder) input.getCoder(); + try { + inputCoder.getKeyCoder().verifyDeterministic(); + } catch (NonDeterministicException e) { + runner.recordViewUsesNonDeterministicKeyCoder(this); + } + return input .apply(Combine.globally(new Concatenate>()).withoutDefaults()) .apply(ParDo.of(StreamingPCollectionViewWriterFn.create(view, input.getCoder()))) @@ -844,7 +2280,9 @@ protected String getKindString() { } /** - * Specialized implementation for {@link View.AsList} for the Dataflow runner in streaming mode. + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsList View.AsList} for the + * Dataflow runner in streaming mode. */ private static class StreamingViewAsList extends PTransform, PCollectionView>> { @@ -852,7 +2290,7 @@ private static class StreamingViewAsList * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsList(View.AsList transform) {} + public StreamingViewAsList(DataflowPipelineRunner runner, View.AsList transform) {} @Override public PCollectionView> apply(PCollection input) { @@ -874,8 +2312,9 @@ protected String getKindString() { } /** - * Specialized implementation for {@link View.AsIterable} for the Dataflow runner in streaming - * mode. + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsIterable View.AsIterable} for the + * Dataflow runner in streaming mode. */ private static class StreamingViewAsIterable extends PTransform, PCollectionView>> { @@ -883,7 +2322,7 @@ private static class StreamingViewAsIterable * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsIterable(View.AsIterable transform) { } + public StreamingViewAsIterable(DataflowPipelineRunner runner, View.AsIterable transform) { } @Override public PCollectionView> apply(PCollection input) { @@ -912,7 +2351,9 @@ public void processElement(ProcessContext c) { } /** - * Specialized expansion for {@link View.AsSingleton} for the Dataflow runner in streaming mode. + * Specialized expansion for + * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} for the + * Dataflow runner in streaming mode. */ private static class StreamingViewAsSingleton extends PTransform, PCollectionView> { @@ -922,7 +2363,7 @@ private static class StreamingViewAsSingleton * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsSingleton(View.AsSingleton transform) { + public StreamingViewAsSingleton(DataflowPipelineRunner runner, View.AsSingleton transform) { this.transform = transform; } @@ -979,6 +2420,7 @@ private static class StreamingCombineGloballyAsSingletonView */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() public StreamingCombineGloballyAsSingletonView( + DataflowPipelineRunner runner, Combine.GloballyAsSingletonView transform) { this.transform = transform; } @@ -1067,7 +2509,7 @@ private static class UnsupportedIO transform) { + public UnsupportedIO(DataflowPipelineRunner runner, AvroIO.Read.Bound transform) { this.transform = transform; } @@ -1075,7 +2517,7 @@ public UnsupportedIO(AvroIO.Read.Bound transform) { * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(BigQueryIO.Read.Bound transform) { + public UnsupportedIO(DataflowPipelineRunner runner, BigQueryIO.Read.Bound transform) { this.transform = transform; } @@ -1083,7 +2525,7 @@ public UnsupportedIO(BigQueryIO.Read.Bound transform) { * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(TextIO.Read.Bound transform) { + public UnsupportedIO(DataflowPipelineRunner runner, TextIO.Read.Bound transform) { this.transform = transform; } @@ -1091,7 +2533,7 @@ public UnsupportedIO(TextIO.Read.Bound transform) { * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(Read.Bounded transform) { + public UnsupportedIO(DataflowPipelineRunner runner, Read.Bounded transform) { this.transform = transform; } @@ -1099,7 +2541,7 @@ public UnsupportedIO(Read.Bounded transform) { * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(Read.Unbounded transform) { + public UnsupportedIO(DataflowPipelineRunner runner, Read.Unbounded transform) { this.transform = transform; } @@ -1107,7 +2549,7 @@ public UnsupportedIO(Read.Unbounded transform) { * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(AvroIO.Write.Bound transform) { + public UnsupportedIO(DataflowPipelineRunner runner, AvroIO.Write.Bound transform) { this.transform = transform; } @@ -1115,7 +2557,7 @@ public UnsupportedIO(AvroIO.Write.Bound transform) { * Builds an instance of this class from the overridden transform. */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(TextIO.Write.Bound transform) { + public UnsupportedIO(DataflowPipelineRunner runner, TextIO.Write.Bound transform) { this.transform = transform; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index bcbd3e7eb5..cef03a8598 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -48,6 +48,7 @@ import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; import com.google.cloud.dataflow.sdk.runners.dataflow.AvroIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; @@ -141,8 +142,12 @@ private DataflowPipelineTranslator(DataflowPipelineOptions options) { /** * Translates a {@link Pipeline} into a {@code JobSpecification}. */ - public JobSpecification translate(Pipeline pipeline, List packages) { - Translator translator = new Translator(pipeline); + public JobSpecification translate( + Pipeline pipeline, + DataflowPipelineRunner runner, + List packages) { + + Translator translator = new Translator(pipeline, runner); Job result = translator.translate(packages); return new JobSpecification(result, Collections.unmodifiableMap(translator.stepNames)); } @@ -349,6 +354,9 @@ class Translator implements PipelineVisitor, TranslationContext { /** The Pipeline to translate. */ private final Pipeline pipeline; + /** The runner which will execute the pipeline. */ + private final DataflowPipelineRunner runner; + /** The Cloud Dataflow Job representation. */ private final Job job = new Job(); @@ -382,8 +390,9 @@ class Translator implements PipelineVisitor, TranslationContext { * Constructs a Translator that will translate the specified * Pipeline into Dataflow objects. */ - public Translator(Pipeline pipeline) { + public Translator(Pipeline pipeline, DataflowPipelineRunner runner) { this.pipeline = pipeline; + this.runner = runner; } /** @@ -702,7 +711,10 @@ private void addOutput(String name, PValue value, Coder valueCoder) { Map outputInfo = new HashMap<>(); addString(outputInfo, PropertyNames.OUTPUT_NAME, name); addString(outputInfo, PropertyNames.USER_NAME, value.getName()); - + if (value instanceof PCollection + && runner.doesPCollectionRequireIndexedFormat((PCollection) value)) { + addBoolean(outputInfo, PropertyNames.USE_INDEXED_FORMAT, true); + } if (valueCoder != null) { // Verify that encoding can be decoded, in order to catch serialization // failures as early as possible. @@ -886,6 +898,30 @@ private void flattenHelper( } }); + registerTransformTranslator( + GroupByKeyAndSortValuesOnly.class, + new TransformTranslator() { + @Override + public void translate( + GroupByKeyAndSortValuesOnly transform, + TranslationContext context) { + groupByKeyAndSortValuesHelper(transform, context); + } + + private void groupByKeyAndSortValuesHelper( + GroupByKeyAndSortValuesOnly transform, + TranslationContext context) { + context.addStep(transform, "GroupByKey"); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + context.addOutput(PropertyNames.OUTPUT, context.getOutput(transform)); + context.addInput(PropertyNames.SORT_VALUES, true); + + // TODO: Add support for combiner lifting once the need arises. + context.addInput( + PropertyNames.DISALLOW_COMBINER_LIFTING, true); + } + }); + registerTransformTranslator( GroupByKey.class, new TransformTranslator() { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index deabbc0a2f..6d9f90f39e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.runners; +import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.startsWith; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -37,7 +40,9 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.AvroSource; import com.google.cloud.dataflow.sdk.io.BigQueryIO; @@ -48,21 +53,41 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsList; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMap; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMultimap; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.TransformedMap; import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; +import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; import com.google.cloud.dataflow.sdk.util.GcsUtil; import com.google.cloud.dataflow.sdk.util.NoopPathValidator; import com.google.cloud.dataflow.sdk.util.TestCredential; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.PValue; import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.cloud.dataflow.sdk.values.TupleTagList; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import org.hamcrest.Description; import org.hamcrest.Matchers; @@ -89,6 +114,7 @@ import java.util.Collections; import java.util.LinkedList; import java.util.List; +import java.util.Map; /** * Tests for DataflowPipelineRunner. @@ -713,7 +739,7 @@ public void testTransformTranslatorMissing() throws IOException { ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); - Pipeline p = DataflowPipeline.create(options); + DataflowPipeline p = DataflowPipeline.create(options); p.apply(Create.of(Arrays.asList(1, 2, 3))) .apply(new TestTransform()); @@ -721,7 +747,7 @@ public void testTransformTranslatorMissing() throws IOException { thrown.expect(IllegalStateException.class); thrown.expectMessage(Matchers.containsString("no translator registered")); DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()); + .translate(p, p.getRunner(), Collections.emptyList()); assertValidJob(jobCaptor.getValue()); } @@ -755,7 +781,8 @@ public void translate( } }); - translator.translate(p, Collections.emptyList()); + translator.translate( + p, p.getRunner(), Collections.emptyList()); assertTrue(transform.translated); } @@ -894,4 +921,439 @@ public void testAvroIOSinkUnsupportedInStreaming() throws Exception { public void testTextIOSinkUnsupportedInStreaming() throws Exception { testUnsupportedSink(TextIO.Write.to("foo"), "TextIO.Write", true); } + + @Test + public void testBatchViewAsListToIsmRecordForGlobalWindow() throws Exception { + DoFnTester>> doFnTester = + DoFnTester.of(new BatchViewAsList.ToIsmRecordForGlobalWindowDoFn()); + + // The order of the output elements is important relative to processing order + assertThat(doFnTester.processBatch(ImmutableList.of("a", "b", "c")), contains( + IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE, 0L), valueInGlobalWindow("a")), + IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE, 1L), valueInGlobalWindow("b")), + IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE, 2L), valueInGlobalWindow("c")))); + } + + @Test + public void testBatchViewAsListToIsmRecordForNonGlobalWindow() throws Exception { + DoFnTester>>>, + IsmRecord>> doFnTester = + DoFnTester.of( + new BatchViewAsList.ToIsmRecordForNonGlobalWindowDoFn( + IntervalWindow.getCoder())); + + IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); + IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); + IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); + + Iterable>>>> inputElements = + ImmutableList.of( + KV.of(1, (Iterable>>) ImmutableList.of( + KV.of( + windowA, WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), + KV.of( + windowA, WindowedValue.of(111L, new Instant(3), windowA, PaneInfo.NO_FIRING)), + KV.of( + windowA, WindowedValue.of(112L, new Instant(4), windowA, PaneInfo.NO_FIRING)), + KV.of( + windowB, WindowedValue.of(120L, new Instant(12), windowB, PaneInfo.NO_FIRING)), + KV.of( + windowB, WindowedValue.of(121L, new Instant(14), windowB, PaneInfo.NO_FIRING)) + )), + KV.of(2, (Iterable>>) ImmutableList.of( + KV.of( + windowC, WindowedValue.of(210L, new Instant(25), windowC, PaneInfo.NO_FIRING)) + ))); + + // The order of the output elements is important relative to processing order + assertThat(doFnTester.processBatch(inputElements), contains( + IsmRecord.of(ImmutableList.of(windowA, 0L), + WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), + IsmRecord.of(ImmutableList.of(windowA, 1L), + WindowedValue.of(111L, new Instant(3), windowA, PaneInfo.NO_FIRING)), + IsmRecord.of(ImmutableList.of(windowA, 2L), + WindowedValue.of(112L, new Instant(4), windowA, PaneInfo.NO_FIRING)), + IsmRecord.of(ImmutableList.of(windowB, 0L), + WindowedValue.of(120L, new Instant(12), windowB, PaneInfo.NO_FIRING)), + IsmRecord.of(ImmutableList.of(windowB, 1L), + WindowedValue.of(121L, new Instant(14), windowB, PaneInfo.NO_FIRING)), + IsmRecord.of(ImmutableList.of(windowC, 0L), + WindowedValue.of(210L, new Instant(25), windowC, PaneInfo.NO_FIRING)))); + } + + @Test + public void testToIsmRecordForMapLikeDoFn() throws Exception { + TupleTag>> outputForSizeTag = new TupleTag<>(); + TupleTag>> outputForEntrySetTag = new TupleTag<>(); + + Coder keyCoder = VarLongCoder.of(); + Coder windowCoder = IntervalWindow.getCoder(); + + IsmRecordCoder> ismCoder = IsmRecordCoder.of( + 1, + 2, + ImmutableList.>of( + MetadataKeyCoder.of(keyCoder), + IntervalWindow.getCoder(), + BigEndianLongCoder.of()), + FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); + + DoFnTester, WindowedValue>>>, + IsmRecord>> doFnTester = + DoFnTester.of(new BatchViewAsMultimap.ToIsmRecordForMapLikeDoFn( + outputForSizeTag, + outputForEntrySetTag, + windowCoder, + keyCoder, + ismCoder, + false /* unique keys */)); + doFnTester.setSideOutputTags(TupleTagList.of( + ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); + + IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); + IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); + IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); + + Iterable, WindowedValue>>>> inputElements = + ImmutableList.of( + KV.of(1, (Iterable, WindowedValue>>) ImmutableList.of( + KV.of(KV.of(1L, windowA), + WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), + // same window same key as to previous + KV.of(KV.of(1L, windowA), + WindowedValue.of(111L, new Instant(2), windowA, PaneInfo.NO_FIRING)), + // same window different key as to previous + KV.of(KV.of(2L, windowA), + WindowedValue.of(120L, new Instant(3), windowA, PaneInfo.NO_FIRING)), + // different window same key as to previous + KV.of(KV.of(2L, windowB), + WindowedValue.of(210L, new Instant(11), windowB, PaneInfo.NO_FIRING)), + // different window and different key as to previous + KV.of(KV.of(3L, windowB), + WindowedValue.of(220L, new Instant(12), windowB, PaneInfo.NO_FIRING)))), + KV.of(2, (Iterable, WindowedValue>>) ImmutableList.of( + // different shard + KV.of(KV.of(4L, windowC), + WindowedValue.of(330L, new Instant(21), windowC, PaneInfo.NO_FIRING))))); + + // The order of the output elements is important relative to processing order + assertThat(doFnTester.processBatch(inputElements), contains( + IsmRecord.of( + ImmutableList.of(1L, windowA, 0L), + WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), + IsmRecord.of( + ImmutableList.of(1L, windowA, 1L), + WindowedValue.of(111L, new Instant(2), windowA, PaneInfo.NO_FIRING)), + IsmRecord.of( + ImmutableList.of(2L, windowA, 0L), + WindowedValue.of(120L, new Instant(3), windowA, PaneInfo.NO_FIRING)), + IsmRecord.of( + ImmutableList.of(2L, windowB, 0L), + WindowedValue.of(210L, new Instant(11), windowB, PaneInfo.NO_FIRING)), + IsmRecord.of( + ImmutableList.of(3L, windowB, 0L), + WindowedValue.of(220L, new Instant(12), windowB, PaneInfo.NO_FIRING)), + IsmRecord.of( + ImmutableList.of(4L, windowC, 0L), + WindowedValue.of(330L, new Instant(21), windowC, PaneInfo.NO_FIRING)))); + + // Verify the number of unique keys per window. + assertThat(doFnTester.takeSideOutputElements(outputForSizeTag), contains( + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowA)), + KV.of(windowA, 2L)), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), + KV.of(windowB, 2L)), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowC)), + KV.of(windowC, 1L)) + )); + + // Verify the output for the unique keys. + assertThat(doFnTester.takeSideOutputElements(outputForEntrySetTag), contains( + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowA)), + KV.of(windowA, 1L)), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowA)), + KV.of(windowA, 2L)), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), + KV.of(windowB, 2L)), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), + KV.of(windowB, 3L)), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowC)), + KV.of(windowC, 4L)) + )); + } + + @Test + public void testToIsmRecordForMapLikeDoFnWithoutUniqueKeysThrowsException() throws Exception { + TupleTag>> outputForSizeTag = new TupleTag<>(); + TupleTag>> outputForEntrySetTag = new TupleTag<>(); + + Coder keyCoder = VarLongCoder.of(); + Coder windowCoder = IntervalWindow.getCoder(); + + IsmRecordCoder> ismCoder = IsmRecordCoder.of( + 1, + 2, + ImmutableList.>of( + MetadataKeyCoder.of(keyCoder), + IntervalWindow.getCoder(), + BigEndianLongCoder.of()), + FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); + + DoFnTester, WindowedValue>>>, + IsmRecord>> doFnTester = + DoFnTester.of(new BatchViewAsMultimap.ToIsmRecordForMapLikeDoFn( + outputForSizeTag, + outputForEntrySetTag, + windowCoder, + keyCoder, + ismCoder, + true /* unique keys */)); + doFnTester.setSideOutputTags(TupleTagList.of( + ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); + + IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); + + Iterable, WindowedValue>>>> inputElements = + ImmutableList.of( + KV.of(1, (Iterable, WindowedValue>>) ImmutableList.of( + KV.of(KV.of(1L, windowA), + WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), + // same window same key as to previous + KV.of(KV.of(1L, windowA), + WindowedValue.of(111L, new Instant(2), windowA, PaneInfo.NO_FIRING))))); + + try { + doFnTester.processBatch(inputElements); + } catch (UserCodeException e) { + assertTrue(e.getCause() instanceof IllegalStateException); + IllegalStateException rootCause = (IllegalStateException) e.getCause(); + assertThat(rootCause.getMessage(), containsString("Unique keys are expected but found key")); + } + } + + @Test + public void testToIsmMetadataRecordForSizeDoFn() throws Exception { + TupleTag>> outputForSizeTag = new TupleTag<>(); + TupleTag>> outputForEntrySetTag = new TupleTag<>(); + + Coder keyCoder = VarLongCoder.of(); + Coder windowCoder = IntervalWindow.getCoder(); + + IsmRecordCoder> ismCoder = IsmRecordCoder.of( + 1, + 2, + ImmutableList.>of( + MetadataKeyCoder.of(keyCoder), + IntervalWindow.getCoder(), + BigEndianLongCoder.of()), + FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); + + DoFnTester>>, + IsmRecord>> doFnTester = DoFnTester.of( + new BatchViewAsMultimap.ToIsmMetadataRecordForSizeDoFn( + windowCoder)); + doFnTester.setSideOutputTags(TupleTagList.of( + ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); + + IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); + IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); + IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); + + Iterable>>> inputElements = + ImmutableList.of( + KV.of(1, + (Iterable>) ImmutableList.of( + KV.of(windowA, 2L), + KV.of(windowA, 3L), + KV.of(windowB, 7L))), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), + (Iterable>) ImmutableList.of( + KV.of(windowC, 9L)))); + + // The order of the output elements is important relative to processing order + assertThat(doFnTester.processBatch(inputElements), contains( + IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), windowA, 0L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), 5L)), + IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), windowB, 0L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), 7L)), + IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), windowC, 0L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), 9L)) + )); + } + + @Test + public void testToIsmMetadataRecordForKeyDoFn() throws Exception { + TupleTag>> outputForSizeTag = new TupleTag<>(); + TupleTag>> outputForEntrySetTag = new TupleTag<>(); + + Coder keyCoder = VarLongCoder.of(); + Coder windowCoder = IntervalWindow.getCoder(); + + IsmRecordCoder> ismCoder = IsmRecordCoder.of( + 1, + 2, + ImmutableList.>of( + MetadataKeyCoder.of(keyCoder), + IntervalWindow.getCoder(), + BigEndianLongCoder.of()), + FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); + + DoFnTester>>, + IsmRecord>> doFnTester = DoFnTester.of( + new BatchViewAsMultimap.ToIsmMetadataRecordForKeyDoFn( + keyCoder, windowCoder)); + doFnTester.setSideOutputTags(TupleTagList.of( + ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); + + IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); + IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); + IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); + + Iterable>>> inputElements = + ImmutableList.of( + KV.of(1, + (Iterable>) ImmutableList.of( + KV.of(windowA, 2L), + // same window as previous + KV.of(windowA, 3L), + // different window as previous + KV.of(windowB, 3L))), + KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), + (Iterable>) ImmutableList.of( + KV.of(windowC, 3L)))); + + // The order of the output elements is important relative to processing order + assertThat(doFnTester.processBatch(inputElements), contains( + IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), windowA, 1L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), 2L)), + IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), windowA, 2L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), 3L)), + IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), windowB, 1L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), 3L)), + IsmRecord.>meta( + ImmutableList.of(IsmFormat.getMetadataKey(), windowC, 1L), + CoderUtils.encodeToByteArray(VarLongCoder.of(), 3L)) + )); + } + + @Test + public void testToMapDoFn() throws Exception { + Coder windowCoder = IntervalWindow.getCoder(); + + DoFnTester>>>>, + IsmRecord, + Long>>>> doFnTester = + DoFnTester.of(new BatchViewAsMap.ToMapDoFn(windowCoder)); + + + IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); + IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); + IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); + + Iterable>>>>> inputElements = + ImmutableList.of( + KV.of(1, + (Iterable>>>) ImmutableList.of( + KV.of(windowA, WindowedValue.of( + KV.of(1L, 11L), new Instant(3), windowA, PaneInfo.NO_FIRING)), + KV.of(windowA, WindowedValue.of( + KV.of(2L, 21L), new Instant(7), windowA, PaneInfo.NO_FIRING)), + KV.of(windowB, WindowedValue.of( + KV.of(2L, 21L), new Instant(13), windowB, PaneInfo.NO_FIRING)), + KV.of(windowB, WindowedValue.of( + KV.of(3L, 31L), new Instant(15), windowB, PaneInfo.NO_FIRING)))), + KV.of(2, + (Iterable>>>) ImmutableList.of( + KV.of(windowC, WindowedValue.of( + KV.of(4L, 41L), new Instant(25), windowC, PaneInfo.NO_FIRING))))); + + // The order of the output elements is important relative to processing order + List, + Long>>>> output = + doFnTester.processBatch(inputElements); + assertEquals(3, output.size()); + Map outputMap; + + outputMap = output.get(0).getValue().getValue(); + assertEquals(2, outputMap.size()); + assertEquals(ImmutableMap.of(1L, 11L, 2L, 21L), outputMap); + + outputMap = output.get(1).getValue().getValue(); + assertEquals(2, outputMap.size()); + assertEquals(ImmutableMap.of(2L, 21L, 3L, 31L), outputMap); + + outputMap = output.get(2).getValue().getValue(); + assertEquals(1, outputMap.size()); + assertEquals(ImmutableMap.of(4L, 41L), outputMap); + } + + @Test + public void testToMultimapDoFn() throws Exception { + Coder windowCoder = IntervalWindow.getCoder(); + + DoFnTester>>>>, + IsmRecord>, + Iterable>>>> doFnTester = + DoFnTester.of( + new BatchViewAsMultimap.ToMultimapDoFn(windowCoder)); + + + IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); + IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); + IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); + + Iterable>>>>> inputElements = + ImmutableList.of( + KV.of(1, + (Iterable>>>) ImmutableList.of( + KV.of(windowA, WindowedValue.of( + KV.of(1L, 11L), new Instant(3), windowA, PaneInfo.NO_FIRING)), + KV.of(windowA, WindowedValue.of( + KV.of(1L, 12L), new Instant(5), windowA, PaneInfo.NO_FIRING)), + KV.of(windowA, WindowedValue.of( + KV.of(2L, 21L), new Instant(7), windowA, PaneInfo.NO_FIRING)), + KV.of(windowB, WindowedValue.of( + KV.of(2L, 21L), new Instant(13), windowB, PaneInfo.NO_FIRING)), + KV.of(windowB, WindowedValue.of( + KV.of(3L, 31L), new Instant(15), windowB, PaneInfo.NO_FIRING)))), + KV.of(2, + (Iterable>>>) ImmutableList.of( + KV.of(windowC, WindowedValue.of( + KV.of(4L, 41L), new Instant(25), windowC, PaneInfo.NO_FIRING))))); + + // The order of the output elements is important relative to processing order + List>, + Iterable>>>> output = + doFnTester.processBatch(inputElements); + assertEquals(3, output.size()); + Map> outputMap; + + outputMap = output.get(0).getValue().getValue(); + assertEquals(2, outputMap.size()); + assertThat(outputMap.get(1L), containsInAnyOrder(11L, 12L)); + assertThat(outputMap.get(2L), containsInAnyOrder(21L)); + + outputMap = output.get(1).getValue().getValue(); + assertEquals(2, outputMap.size()); + assertThat(outputMap.get(2L), containsInAnyOrder(21L)); + assertThat(outputMap.get(3L), containsInAnyOrder(31L)); + + outputMap = output.get(2).getValue().getValue(); + assertEquals(1, outputMap.size()); + assertThat(outputMap.get(4L), containsInAnyOrder(41L)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 272329f950..c55d215da8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -21,6 +21,7 @@ import static com.google.cloud.dataflow.sdk.util.Structs.getString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; @@ -53,6 +54,7 @@ import com.google.cloud.dataflow.sdk.util.GcsUtil; import com.google.cloud.dataflow.sdk.util.OutputReference; import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.Structs; import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; @@ -60,6 +62,7 @@ import com.google.cloud.dataflow.sdk.values.PCollectionTuple; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; @@ -73,6 +76,7 @@ import java.io.IOException; import java.util.Collections; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -153,29 +157,30 @@ public void testSettingOfSdkPipelineOptions() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setRunner(DataflowPipelineRunner.class); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); // Note that the contents of this materialized map may be changed by the act of reading an // option, which will cause the default to get materialized whereas it would otherwise be // left absent. It is permissible to simply alter this test to reflect current behavior. - assertEquals(ImmutableMap.of("options", - ImmutableMap.builder() - .put("appName", "DataflowPipelineTranslatorTest") - .put("project", "some-project") - .put("pathValidatorClass", "com.google.cloud.dataflow.sdk.util.DataflowPathValidator") - .put("runner", "com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner") - .put("jobName", "some-job-name") - .put("tempLocation", "gs://somebucket/some/path") - .put("stagingLocation", "gs://somebucket/some/path/staging") - .put("stableUniqueNames", "WARNING") - .put("streaming", false) - .put("numberOfWorkerHarnessThreads", 0) - .build()), + Map settings = new HashMap<>(); + settings.put("appName", "DataflowPipelineTranslatorTest"); + settings.put("project", "some-project"); + settings.put("pathValidatorClass", "com.google.cloud.dataflow.sdk.util.DataflowPathValidator"); + settings.put("runner", "com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner"); + settings.put("jobName", "some-job-name"); + settings.put("tempLocation", "gs://somebucket/some/path"); + settings.put("stagingLocation", "gs://somebucket/some/path/staging"); + settings.put("stableUniqueNames", "WARNING"); + settings.put("streaming", false); + settings.put("numberOfWorkerHarnessThreads", 0); + settings.put("experiments", null); + + assertEquals(ImmutableMap.of("options", settings), job.getEnvironment().getSdkPipelineOptions()); } @@ -186,11 +191,11 @@ public void testNetworkConfig() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setNetwork(testNetwork); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -202,11 +207,11 @@ public void testNetworkConfig() throws IOException { public void testNetworkConfigMissing() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -217,11 +222,11 @@ public void testNetworkConfigMissing() throws IOException { public void testScalingAlgorithmMissing() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -252,11 +257,11 @@ public void testScalingAlgorithmNone() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setAutoscalingAlgorithm(noScaling); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -286,11 +291,11 @@ public void testMaxNumWorkersIsPassedWhenNoAlgorithmIsSet() throws IOException { options.setMaxNumWorkers(42); options.setAutoscalingAlgorithm(noScaling); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -319,11 +324,11 @@ public void testZoneConfig() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setZone(testZone); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -338,11 +343,11 @@ public void testWorkerMachineTypeConfig() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setWorkerMachineType(testMachineType); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -358,11 +363,11 @@ public void testDiskSizeGbConfig() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setDiskSizeGb(diskSizeGb); - Pipeline p = buildPipeline(options); + DataflowPipeline p = buildPipeline(options); p.traverseTopologically(new RecordingPipelineVisitor()); Job job = DataflowPipelineTranslator.fromOptions(options) - .translate(p, Collections.emptyList()) + .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); assertEquals(1, job.getEnvironment().getWorkerPools().size()); @@ -387,7 +392,8 @@ public void testPredefinedAddStep() throws Exception { .apply(ParDo.of(new NoOpFn())) .apply(new EmbeddedTransform(predefinedStep.clone())) .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/out")); - Job job = translator.translate(pipeline, Collections.emptyList()).getJob(); + Job job = translator.translate( + pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); List steps = job.getSteps(); assertEquals(4, steps.size()); @@ -435,7 +441,8 @@ private static Step createPredefinedStep() throws Exception { pipeline.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/in")) .apply(ParDo.of(new NoOpFn()).named(stepName)) .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/out")); - Job job = translator.translate(pipeline, Collections.emptyList()).getJob(); + Job job = translator.translate( + pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); assertEquals(3, job.getSteps().size()); Step step = job.getSteps().get(1); @@ -555,7 +562,7 @@ public PCollectionTuple apply(PCollection input) { @Test public void testMultiGraphPipelineSerialization() throws IOException { - Pipeline p = DataflowPipeline.create(buildPipelineOptions()); + DataflowPipeline p = DataflowPipeline.create(buildPipelineOptions()); PCollection input = p.begin() .apply(Create.of(1, 2, 3)); @@ -567,7 +574,7 @@ public void testMultiGraphPipelineSerialization() throws IOException { PipelineOptionsFactory.as(DataflowPipelineOptions.class)); // Check that translation doesn't fail. - t.translate(p, Collections.emptyList()); + t.translate(p, p.getRunner(), Collections.emptyList()); } @Test @@ -589,7 +596,7 @@ public void testPartiallyBoundFailure() throws IOException { @Test public void testGoodWildcards() throws Exception { DataflowPipelineOptions options = buildPipelineOptions(); - Pipeline pipeline = DataflowPipeline.create(options); + DataflowPipeline pipeline = DataflowPipeline.create(options); DataflowPipelineTranslator t = DataflowPipelineTranslator.fromOptions(options); applyRead(pipeline, "gs://bucket/foo"); @@ -608,7 +615,7 @@ public void testGoodWildcards() throws Exception { applyRead(pipeline, "gs://bucket/foo[0-9]/baz"); // Check that translation doesn't fail. - t.translate(pipeline, Collections.emptyList()); + t.translate(pipeline, pipeline.getRunner(), Collections.emptyList()); } private void applyRead(Pipeline pipeline, String path) { @@ -622,7 +629,7 @@ private void applyRead(Pipeline pipeline, String path) { @Test public void testBadWildcardRecursive() throws Exception { DataflowPipelineOptions options = buildPipelineOptions(); - Pipeline pipeline = DataflowPipeline.create(options); + DataflowPipeline pipeline = DataflowPipeline.create(options); DataflowPipelineTranslator t = DataflowPipelineTranslator.fromOptions(options); pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); @@ -630,7 +637,7 @@ public void testBadWildcardRecursive() throws Exception { // Check that translation does fail. thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Unsupported wildcard usage"); - t.translate(pipeline, Collections.emptyList()); + t.translate(pipeline, pipeline.getRunner(), Collections.emptyList()); } @Test @@ -645,7 +652,8 @@ public void testToSingletonTranslation() throws Exception { DataflowPipeline pipeline = DataflowPipeline.create(options); pipeline.apply(Create.of(1)) .apply(View.asSingleton()); - Job job = translator.translate(pipeline, Collections.emptyList()).getJob(); + Job job = translator.translate( + pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); List steps = job.getSteps(); assertEquals(2, steps.size()); @@ -670,7 +678,8 @@ public void testToIterableTranslation() throws Exception { DataflowPipeline pipeline = DataflowPipeline.create(options); pipeline.apply(Create.of(1, 2, 3)) .apply(View.asIterable()); - Job job = translator.translate(pipeline, Collections.emptyList()).getJob(); + Job job = translator.translate( + pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); List steps = job.getSteps(); assertEquals(2, steps.size()); @@ -681,4 +690,63 @@ public void testToIterableTranslation() throws Exception { Step collectionToSingletonStep = steps.get(1); assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); } + + @Test + public void testToSingletonTranslationWithIsmSideInput() throws Exception { + // A "change detector" test that makes sure the translation + // of getting a PCollectionView does not change + // in bad ways during refactor + + DataflowPipelineOptions options = buildPipelineOptions(); + options.setExperiments(ImmutableList.of("enable_ism_side_input")); + DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); + + DataflowPipeline pipeline = DataflowPipeline.create(options); + pipeline.apply(Create.of(1)) + .apply(View.asSingleton()); + Job job = translator.translate( + pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); + + List steps = job.getSteps(); + assertEquals(5, steps.size()); + + @SuppressWarnings("unchecked") + List> toIsmRecordOutputs = + (List>) steps.get(3).getProperties().get(PropertyNames.OUTPUT_INFO); + assertTrue( + Structs.getBoolean(Iterables.getOnlyElement(toIsmRecordOutputs), "use_indexed_format")); + + Step collectionToSingletonStep = steps.get(4); + assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); + } + + @Test + public void testToIterableTranslationWithIsmSideInput() throws Exception { + // A "change detector" test that makes sure the translation + // of getting a PCollectionView> does not change + // in bad ways during refactor + + DataflowPipelineOptions options = buildPipelineOptions(); + options.setExperiments(ImmutableList.of("enable_ism_side_input")); + DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); + + DataflowPipeline pipeline = DataflowPipeline.create(options); + pipeline.apply(Create.of(1, 2, 3)) + .apply(View.asIterable()); + Job job = translator.translate( + pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); + + List steps = job.getSteps(); + assertEquals(3, steps.size()); + + @SuppressWarnings("unchecked") + List> toIsmRecordOutputs = + (List>) steps.get(1).getProperties().get(PropertyNames.OUTPUT_INFO); + assertTrue( + Structs.getBoolean(Iterables.getOnlyElement(toIsmRecordOutputs), "use_indexed_format")); + + + Step collectionToSingletonStep = steps.get(2); + assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index 569c4523f6..fe350aad60 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -42,6 +42,7 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.DataflowPipeline; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; @@ -53,7 +54,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; +import com.google.cloud.dataflow.sdk.util.NoopPathValidator; import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.Preconditions; @@ -406,11 +409,17 @@ public void testFailureToStartReadingIncludesSourceDetails() throws Exception { private static Source translateIOToCloudSource( BoundedSource io, DataflowPipelineOptions options) throws Exception { + options.setProject("test-project"); + options.setTempLocation("gs://test-tmp"); + options.setPathValidatorClass(NoopPathValidator.class); + options.setGcpCredential(new TestCredential()); + DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - Pipeline p = Pipeline.create(options); + DataflowPipeline p = DataflowPipeline.create(options); p.begin().apply(Read.from(io)); - Job workflow = translator.translate(p, new ArrayList()).getJob(); + Job workflow = translator.translate( + p, p.getRunner(), new ArrayList()).getJob(); Step step = workflow.getSteps().get(0); return stepToCloudSource(step); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java index 555eb8b6e7..aa45050e50 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java @@ -24,6 +24,9 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.CustomCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.NullableCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; @@ -62,12 +65,16 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.NoSuchElementException; /** @@ -88,44 +95,69 @@ public class ViewTest implements Serializable { public void testSingletonSideInput() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView view = pipeline - .apply("Create47", Create.of(47)) - .apply(View.asSingleton()); + final PCollectionView view = + pipeline.apply("Create47", Create.of(47)).apply(View.asSingleton()); - PCollection output = pipeline - .apply("Create123", Create.of(1, 2, 3)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection output = + pipeline.apply("Create123", Create.of(1, 2, 3)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { c.output(c.sideInput(view)); } })); - DataflowAssert.that(output) - .containsInAnyOrder(47, 47, 47); + DataflowAssert.that(output).containsInAnyOrder(47, 47, 47); pipeline.run(); } @Test - public void testEmptySingletonSideInput() throws Exception { + @Category(RunnableOnService.class) + public void testWindowedSingletonSideInput() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView view = pipeline - .apply("CreateEmptyIntegers", Create.of().withCoder(VarIntCoder.of())) - .apply(View.asSingleton()); - - pipeline - .apply("Create123", Create.of(1, 2, 3)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + final PCollectionView view = + pipeline.apply("Create47", Create.timestamped( + TimestampedValue.of(47, new Instant(1)), + TimestampedValue.of(48, new Instant(11)))) + .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asSingleton()); + + PCollection output = + pipeline.apply("Create123", Create.timestamped( + TimestampedValue.of(1, new Instant(4)), + TimestampedValue.of(2, new Instant(8)), + TimestampedValue.of(3, new Instant(12)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { c.output(c.sideInput(view)); } })); + DataflowAssert.that(output).containsInAnyOrder(47, 47, 48); + + pipeline.run(); + } + + @Test + public void testEmptySingletonSideInput() throws Exception { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView view = + pipeline.apply("CreateEmptyIntegers", Create.of().withCoder(VarIntCoder.of())) + .apply(View.asSingleton()); + + pipeline.apply("Create123", Create.of(1, 2, 3)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.output(c.sideInput(view)); + } + })); + thrown.expect(PipelineExecutionException.class); thrown.expectCause(isA(NoSuchElementException.class)); thrown.expectMessage("Empty"); @@ -140,17 +172,15 @@ public void testNonSingletonSideInput() throws Exception { Pipeline pipeline = TestPipeline.create(); PCollection oneTwoThree = pipeline.apply(Create.of(1, 2, 3)); - final PCollectionView view = oneTwoThree - .apply(View.asSingleton()); + final PCollectionView view = oneTwoThree.apply(View.asSingleton()); - oneTwoThree - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.sideInput(view)); - } - })); + oneTwoThree.apply( + "OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.output(c.sideInput(view)); + } + })); thrown.expect(PipelineExecutionException.class); thrown.expectCause(isA(IllegalArgumentException.class)); @@ -166,14 +196,12 @@ public void processElement(ProcessContext c) { public void testListSideInput() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(11, 13, 17, 23)) - .apply(View.asList()); + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(11, 13, 17, 23)).apply(View.asList()); - PCollection output = pipeline - .apply("CreateMainInput", Create.of(29, 31)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection output = + pipeline.apply("CreateMainInput", Create.of(29, 31)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { Preconditions.checkArgument(c.sideInput(view).size() == 4); @@ -184,9 +212,46 @@ public void processElement(ProcessContext c) { } })); - DataflowAssert.that(output).containsInAnyOrder( - 11, 13, 17, 23, - 11, 13, 17, 23); + DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 11, 13, 17, 23); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testWindowedListSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.timestamped( + TimestampedValue.of(11, new Instant(1)), + TimestampedValue.of(13, new Instant(1)), + TimestampedValue.of(17, new Instant(1)), + TimestampedValue.of(23, new Instant(1)), + TimestampedValue.of(31, new Instant(11)), + TimestampedValue.of(33, new Instant(11)), + TimestampedValue.of(37, new Instant(11)), + TimestampedValue.of(43, new Instant(11)))) + .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asList()); + + PCollection output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of(29, new Instant(1)), + TimestampedValue.of(35, new Instant(11)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { + @Override + public void processElement(ProcessContext c) { + Preconditions.checkArgument(c.sideInput(view).size() == 4); + Preconditions.checkArgument(c.sideInput(view).get(0) == c.sideInput(view).get(0)); + for (Integer i : c.sideInput(view)) { + c.output(i); + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 31, 33, 37, 43); pipeline.run(); } @@ -196,17 +261,17 @@ public void processElement(ProcessContext c) { public void testEmptyListSideInput() throws Exception { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateEmptyView", Create.of().withCoder(VarIntCoder.of())) - .apply(View.asList()); + final PCollectionView> view = + pipeline.apply("CreateEmptyView", Create.of().withCoder(VarIntCoder.of())) + .apply(View.asList()); - PCollection results = pipeline - .apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection results = + pipeline.apply("Create1", Create.of(1)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { assertTrue(c.sideInput(view).isEmpty()); + assertFalse(c.sideInput(view).iterator().hasNext()); c.output(1); } })); @@ -222,14 +287,12 @@ public void processElement(ProcessContext c) { public void testListSideInputIsImmutable() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(11)) - .apply(View.asList()); + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(11)).apply(View.asList()); - PCollection output = pipeline - .apply("CreateMainInput", Create.of(29)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection output = + pipeline.apply("CreateMainInput", Create.of(29)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { try { @@ -269,14 +332,13 @@ public void processElement(ProcessContext c) { public void testIterableSideInput() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(11, 13, 17, 23)) - .apply(View.asIterable()); + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(11, 13, 17, 23)) + .apply(View.asIterable()); - PCollection output = pipeline - .apply("CreateMainInput", Create.of(29, 31)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection output = + pipeline.apply("CreateMainInput", Create.of(29, 31)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { for (Integer i : c.sideInput(view)) { @@ -285,9 +347,44 @@ public void processElement(ProcessContext c) { } })); - DataflowAssert.that(output).containsInAnyOrder( - 11, 13, 17, 23, - 11, 13, 17, 23); + DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 11, 13, 17, 23); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testWindowedIterableSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.timestamped( + TimestampedValue.of(11, new Instant(1)), + TimestampedValue.of(13, new Instant(1)), + TimestampedValue.of(17, new Instant(1)), + TimestampedValue.of(23, new Instant(1)), + TimestampedValue.of(31, new Instant(11)), + TimestampedValue.of(33, new Instant(11)), + TimestampedValue.of(37, new Instant(11)), + TimestampedValue.of(43, new Instant(11)))) + .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asIterable()); + + PCollection output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of(29, new Instant(1)), + TimestampedValue.of(35, new Instant(11)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { + @Override + public void processElement(ProcessContext c) { + for (Integer i : c.sideInput(view)) { + c.output(i); + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 31, 33, 37, 43); pipeline.run(); } @@ -297,14 +394,13 @@ public void processElement(ProcessContext c) { public void testEmptyIterableSideInput() throws Exception { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateEmptyView", Create.of().withCoder(VarIntCoder.of())) - .apply(View.asIterable()); + final PCollectionView> view = + pipeline.apply("CreateEmptyView", Create.of().withCoder(VarIntCoder.of())) + .apply(View.asIterable()); - PCollection results = pipeline - .apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection results = + pipeline.apply("Create1", Create.of(1)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { assertFalse(c.sideInput(view).iterator().hasNext()); @@ -323,14 +419,12 @@ public void processElement(ProcessContext c) { public void testIterableSideInputIsImmutable() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(11)) - .apply(View.asIterable()); + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(11)).apply(View.asIterable()); - PCollection output = pipeline - .apply("CreateMainInput", Create.of(29)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection output = + pipeline.apply("CreateMainInput", Create.of(29)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { Iterator iterator = c.sideInput(view).iterator(); @@ -356,25 +450,229 @@ public void processElement(ProcessContext c) { public void testMultimapSideInput() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView>> view = pipeline - .apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 2), KV.of("b", 3))) - .apply(View.asMultimap()); + final PCollectionView>> view = + pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 2), KV.of("b", 3))) + .apply(View.asMultimap()); - PCollection> output = pipeline - .apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { - c.output(KV.of(c.element(), v)); - } - } - })); + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { + c.output(KV.of(c.element(), v)); + } + } + })); - DataflowAssert.that(output) - .containsInAnyOrder(KV.of("apple", 1), KV.of("apple", 2), - KV.of("banana", 3), KV.of("blackberry", 3)); + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testMultimapAsEntrySetSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView>> view = + pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 2), KV.of("b", 3))) + .apply(View.asMultimap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.of(2 /* size */)) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + assertEquals((int) c.element(), c.sideInput(view).size()); + assertEquals((int) c.element(), c.sideInput(view).entrySet().size()); + for (Entry> entry : c.sideInput(view).entrySet()) { + for (Integer value : entry.getValue()) { + c.output(KV.of(entry.getKey(), value)); + } + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("a", 1), KV.of("a", 2), KV.of("b", 3)); + + pipeline.run(); + } + + private static class NonDeterministicStringCoder extends CustomCoder { + @Override + public void encode(String value, OutputStream outStream, Coder.Context context) + throws CoderException, IOException { + StringUtf8Coder.of().encode(value, outStream, context); + } + + @Override + public String decode(InputStream inStream, Coder.Context context) + throws CoderException, IOException { + return StringUtf8Coder.of().decode(inStream, context); + } + + @Override + public void verifyDeterministic() + throws com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException { + throw new NonDeterministicException(this, "Test coder is not deterministic on purpose."); + } + } + + @Test + @Category(RunnableOnService.class) + public void testMultimapSideInputWithNonDeterministicKeyCoder() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView>> view = + pipeline.apply("CreateSideInput", + Create.of(KV.of("a", 1), KV.of("a", 2), KV.of("b", 3)) + .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) + .apply(View.asMultimap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { + c.output(KV.of(c.element(), v)); + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testWindowedMultimapSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView>> view = + pipeline.apply("CreateSideInput", Create.timestamped( + TimestampedValue.of(KV.of("a", 1), new Instant(1)), + TimestampedValue.of(KV.of("a", 2), new Instant(7)), + TimestampedValue.of(KV.of("b", 3), new Instant(14)))) + .apply( + "SideWindowInto", + Window.>into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asMultimap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of("apple", new Instant(5)), + TimestampedValue.of("banana", new Instant(13)), + TimestampedValue.of("blackberry", new Instant(16)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + for (Integer v : + c.sideInput(view) + .get(c.element().substring(0, 1))) { + c.output(KV.of(c.element(), v)); + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testWindowedMultimapAsEntrySetSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView>> view = + pipeline.apply("CreateSideInput", Create.timestamped( + TimestampedValue.of(KV.of("a", 1), new Instant(1)), + TimestampedValue.of(KV.of("a", 2), new Instant(7)), + TimestampedValue.of(KV.of("b", 3), new Instant(14)))) + .apply( + "SideWindowInto", + Window.>into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asMultimap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of(1 /* size */, new Instant(5)), + TimestampedValue.of(1 /* size */, new Instant(16)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + assertEquals((int) c.element(), + c.sideInput(view).size()); + assertEquals((int) c.element(), + c.sideInput(view).entrySet().size()); + for (Entry> entry + : c.sideInput(view).entrySet()) { + for (Integer value : entry.getValue()) { + c.output(KV.of(entry.getKey(), value)); + } + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("a", 1), KV.of("a", 2), KV.of("b", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testWindowedMultimapSideInputWithNonDeterministicKeyCoder() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView>> view = + pipeline.apply("CreateSideInput", + Create.timestamped( + TimestampedValue.of(KV.of("a", 1), new Instant(1)), + TimestampedValue.of(KV.of("a", 2), new Instant(7)), + TimestampedValue.of(KV.of("b", 3), new Instant(14))) + .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) + .apply("SideWindowInto", + Window.>into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asMultimap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of("apple", new Instant(5)), + TimestampedValue.of("banana", new Instant(13)), + TimestampedValue.of("blackberry", new Instant(16)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + for (Integer v : + c.sideInput(view) + .get(c.element().substring(0, 1))) { + c.output(KV.of(c.element(), v)); + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); pipeline.run(); } @@ -384,18 +682,19 @@ public void processElement(ProcessContext c) { public void testEmptyMultimapSideInput() throws Exception { Pipeline pipeline = TestPipeline.create(); - final PCollectionView>> view = pipeline - .apply("CreateEmptyView", Create.>of() - .withCoder(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()))) - .apply(View.asMultimap()); + final PCollectionView>> view = + pipeline.apply("CreateEmptyView", Create.>of().withCoder( + KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) + .apply(View.asMultimap()); - PCollection results = pipeline - .apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection results = + pipeline.apply("Create1", Create.of(1)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { assertTrue(c.sideInput(view).isEmpty()); + assertTrue(c.sideInput(view).entrySet().isEmpty()); + assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); c.output(c.element()); } })); @@ -408,45 +707,75 @@ public void processElement(ProcessContext c) { @Test @Category(RunnableOnService.class) - public void testMultimapSideInputIsImmutable() { + public void testEmptyMultimapSideInputWithNonDeterministicKeyCoder() throws Exception { Pipeline pipeline = TestPipeline.create(); - final PCollectionView>> view = pipeline - .apply("CreateSideInput", Create.of(KV.of("a", 1))) - .apply(View.asMultimap()); + final PCollectionView>> view = + pipeline.apply("CreateEmptyView", + Create.>of().withCoder( + KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) + .apply(View.asMultimap()); - PCollection> output = pipeline - .apply("CreateMainInput", Create.of("apple")) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { + PCollection results = + pipeline.apply("Create1", Create.of(1)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { - try { - c.sideInput(view).clear(); - fail("Expected UnsupportedOperationException on clear()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).put("c", ImmutableList.of(3)); - fail("Expected UnsupportedOperationException on put()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).remove("c"); - fail("Expected UnsupportedOperationException on remove()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).putAll(new HashMap>()); - fail("Expected UnsupportedOperationException on putAll()"); - } catch (UnsupportedOperationException expected) { - } - for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { - c.output(KV.of(c.element(), v)); - } + assertTrue(c.sideInput(view).isEmpty()); + assertTrue(c.sideInput(view).entrySet().isEmpty()); + assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); + c.output(c.element()); } })); + // Pass at least one value through to guarantee that DoFn executes. + DataflowAssert.that(results).containsInAnyOrder(1); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testMultimapSideInputIsImmutable() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView>> view = + pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1))) + .apply(View.asMultimap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple")) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + try { + c.sideInput(view).clear(); + fail("Expected UnsupportedOperationException on clear()"); + } catch (UnsupportedOperationException expected) { + } + try { + c.sideInput(view).put("c", ImmutableList.of(3)); + fail("Expected UnsupportedOperationException on put()"); + } catch (UnsupportedOperationException expected) { + } + try { + c.sideInput(view).remove("c"); + fail("Expected UnsupportedOperationException on remove()"); + } catch (UnsupportedOperationException expected) { + } + try { + c.sideInput(view).putAll(new HashMap>()); + fail("Expected UnsupportedOperationException on putAll()"); + } catch (UnsupportedOperationException expected) { + } + for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { + c.output(KV.of(c.element(), v)); + } + } + })); + // Pass at least one value through to guarantee that DoFn executes. DataflowAssert.that(output).containsInAnyOrder(KV.of("apple", 1)); @@ -458,23 +787,204 @@ public void processElement(ProcessContext c) { public void testMapSideInput() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3))) - .apply(View.asMap()); + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3))) + .apply(View.asMap()); - PCollection> output = pipeline - .apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); - } - })); + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output( + KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); + } + })); - DataflowAssert.that(output) - .containsInAnyOrder(KV.of("apple", 1), - KV.of("banana", 3), KV.of("blackberry", 3)); + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("banana", 3), KV.of("blackberry", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testMapAsEntrySetSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3))) + .apply(View.asMap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.of(2 /* size */)) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + assertEquals((int) c.element(), c.sideInput(view).size()); + assertEquals((int) c.element(), c.sideInput(view).entrySet().size()); + for (Entry entry : c.sideInput(view).entrySet()) { + System.out.println("LCWIKL: " + entry); + c.output(KV.of(entry.getKey(), entry.getValue())); + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("a", 1), KV.of("b", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testMapSideInputWithNonDeterministicKeyCoder() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline.apply("CreateSideInput", + Create.of(KV.of("a", 1), KV.of("b", 3)) + .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) + .apply(View.asMap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output( + KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("banana", 3), KV.of("blackberry", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testWindowedMapSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.timestamped( + TimestampedValue.of(KV.of("a", 1), new Instant(1)), + TimestampedValue.of(KV.of("b", 2), new Instant(4)), + TimestampedValue.of(KV.of("b", 3), new Instant(18)))) + .apply( + "SideWindowInto", + Window.>into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asMap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of("apple", new Instant(5)), + TimestampedValue.of("banana", new Instant(4)), + TimestampedValue.of("blackberry", new Instant(16)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output(KV.of( + c.element(), + c.sideInput(view).get( + c.element().substring(0, 1)))); + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("banana", 2), KV.of("blackberry", 3)); + + pipeline.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testWindowedMapAsEntrySetSideInput() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.timestamped( + TimestampedValue.of(KV.of("a", 1), new Instant(1)), + TimestampedValue.of(KV.of("b", 2), new Instant(4)), + TimestampedValue.of(KV.of("b", 3), new Instant(18)))) + .apply( + "SideWindowInto", + Window.>into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asMap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of(2 /* size */, new Instant(5)), + TimestampedValue.of(1 /* size */, new Instant(16)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + assertEquals((int) c.element(), + c.sideInput(view).size()); + assertEquals((int) c.element(), + c.sideInput(view).entrySet().size()); + for (Entry entry + : c.sideInput(view).entrySet()) { + c.output(KV.of(entry.getKey(), entry.getValue())); + } + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("a", 1), KV.of("b", 2), KV.of("b", 3)); + + pipeline.run(); + } + + + @Test + @Category(RunnableOnService.class) + public void testWindowedMapSideInputWithNonDeterministicKeyCoder() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline.apply("CreateSideInput", + Create.timestamped( + TimestampedValue.of(KV.of("a", 1), new Instant(1)), + TimestampedValue.of(KV.of("b", 2), new Instant(4)), + TimestampedValue.of(KV.of("b", 3), new Instant(18))) + .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) + .apply( + "SideWindowInto", + Window.>into(FixedWindows.of(Duration.millis(10)))) + .apply(View.asMap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of("apple", new Instant(5)), + TimestampedValue.of("banana", new Instant(4)), + TimestampedValue.of("blackberry", new Instant(16)))) + .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output(KV.of( + c.element(), + c.sideInput(view).get( + c.element().substring(0, 1)))); + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("banana", 2), KV.of("blackberry", 3)); pipeline.run(); } @@ -484,18 +994,19 @@ public void processElement(ProcessContext c) { public void testEmptyMapSideInput() throws Exception { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateEmptyView", Create.>of() - .withCoder(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()))) - .apply(View.asMap()); + final PCollectionView> view = + pipeline.apply("CreateEmptyView", Create.>of().withCoder( + KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) + .apply(View.asMap()); - PCollection results = pipeline - .apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + PCollection results = + pipeline.apply("Create1", Create.of(1)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { assertTrue(c.sideInput(view).isEmpty()); + assertTrue(c.sideInput(view).entrySet().isEmpty()); + assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); c.output(c.element()); } })); @@ -507,32 +1018,65 @@ public void processElement(ProcessContext c) { } @Test - public void testMapSideInputWithNullValuesCatchesDuplicates() { + @Category(RunnableOnService.class) + public void testEmptyMapSideInputWithNonDeterministicKeyCoder() throws Exception { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(KV.of("a", (Integer) null), KV.of("a", (Integer) null)) - .withCoder(KvCoder.of(StringUtf8Coder.of(), NullableCoder.of(VarIntCoder.of())))) - .apply(View.asMap()); + final PCollectionView> view = + pipeline.apply("CreateEmptyView", Create.>of().withCoder( + KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) + .apply(View.asMap()); - PCollection> output = pipeline - .apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { + PCollection results = + pipeline.apply("Create1", Create.of(1)) + .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { @Override public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); + assertTrue(c.sideInput(view).isEmpty()); + assertTrue(c.sideInput(view).entrySet().isEmpty()); + assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); + c.output(c.element()); } })); - DataflowAssert.that(output) - .containsInAnyOrder(KV.of("apple", 1), - KV.of("banana", 3), KV.of("blackberry", 3)); + // Pass at least one value through to guarantee that DoFn executes. + DataflowAssert.that(results).containsInAnyOrder(1); + + pipeline.run(); + } + + @Test + public void testMapSideInputWithNullValuesCatchesDuplicates() { + Pipeline pipeline = TestPipeline.create(); + + final PCollectionView> view = + pipeline + .apply( + "CreateSideInput", + Create.of(KV.of("a", (Integer) null), KV.of("a", (Integer) null)) + .withCoder( + KvCoder.of(StringUtf8Coder.of(), NullableCoder.of(VarIntCoder.of())))) + .apply(View.asMap()); + + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output( + KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); + } + })); + + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 1), KV.of("banana", 3), KV.of("blackberry", 3)); // PipelineExecutionException is thrown with cause having a message stating that a // duplicate is not allowed. - thrown.expectCause(ThrowableMessageMatcher.hasMessage( - Matchers.containsString("Duplicate values for a"))); + thrown.expectCause( + ThrowableMessageMatcher.hasMessage(Matchers.containsString("Duplicate values for a"))); pipeline.run(); } @@ -541,39 +1085,41 @@ public void processElement(ProcessContext c) { public void testMapSideInputIsImmutable() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(KV.of("a", 1))) - .apply(View.asMap()); + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1))) + .apply(View.asMap()); - PCollection> output = pipeline - .apply("CreateMainInput", Create.of("apple")) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - try { - c.sideInput(view).clear(); - fail("Expected UnsupportedOperationException on clear()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).put("c", 3); - fail("Expected UnsupportedOperationException on put()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).remove("c"); - fail("Expected UnsupportedOperationException on remove()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).putAll(new HashMap()); - fail("Expected UnsupportedOperationException on putAll()"); - } catch (UnsupportedOperationException expected) { - } - c.output(KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); - } - })); + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple")) + .apply( + "OutputSideInputs", + ParDo.withSideInputs(view).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + try { + c.sideInput(view).clear(); + fail("Expected UnsupportedOperationException on clear()"); + } catch (UnsupportedOperationException expected) { + } + try { + c.sideInput(view).put("c", 3); + fail("Expected UnsupportedOperationException on put()"); + } catch (UnsupportedOperationException expected) { + } + try { + c.sideInput(view).remove("c"); + fail("Expected UnsupportedOperationException on remove()"); + } catch (UnsupportedOperationException expected) { + } + try { + c.sideInput(view).putAll(new HashMap()); + fail("Expected UnsupportedOperationException on putAll()"); + } catch (UnsupportedOperationException expected) { + } + c.output( + KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); + } + })); // Pass at least one value through to guarantee that DoFn executes. DataflowAssert.that(output).containsInAnyOrder(KV.of("apple", 1)); @@ -586,25 +1132,22 @@ public void processElement(ProcessContext c) { public void testCombinedMapSideInput() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view = pipeline - .apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 20), KV.of("b", 3))) - .apply("SumIntegers", - Combine.perKey(new Sum.SumIntegerFn().asKeyedFn())) - .apply(View.asMap()); + final PCollectionView> view = + pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 20), KV.of("b", 3))) + .apply("SumIntegers", Combine.perKey(new Sum.SumIntegerFn().asKeyedFn())) + .apply(View.asMap()); - PCollection> output = pipeline - .apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply("Output", ParDo.withSideInputs(view).of( - new DoFn>() { + PCollection> output = + pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) + .apply("Output", ParDo.withSideInputs(view).of(new DoFn>() { @Override public void processElement(ProcessContext c) { c.output(KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); } })); - DataflowAssert.that(output) - .containsInAnyOrder(KV.of("apple", 21), - KV.of("banana", 3), KV.of("blackberry", 3)); + DataflowAssert.that(output).containsInAnyOrder( + KV.of("apple", 21), KV.of("banana", 3), KV.of("blackberry", 3)); pipeline.run(); } @@ -614,28 +1157,28 @@ public void processElement(ProcessContext c) { public void testWindowedSideInputFixedToFixed() { Pipeline p = TestPipeline.create(); - final PCollectionView view = p - .apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(11)), - TimestampedValue.of(3, new Instant(13)))) - .apply("WindowSideInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply(Sum.integersGlobally().withoutDefaults()) - .apply(View.asSingleton()); - - PCollection output = p - .apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("A", new Instant(4)), - TimestampedValue.of("B", new Instant(15)), - TimestampedValue.of("C", new Instant(7)))) - .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); - } - })); + final PCollectionView view = + p.apply( + "CreateSideInput", + Create.timestamped(TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(2, new Instant(11)), TimestampedValue.of(3, new Instant(13)))) + .apply("WindowSideInput", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply(Sum.integersGlobally().withoutDefaults()) + .apply(View.asSingleton()); + + PCollection output = + p.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of("A", new Instant(4)), + TimestampedValue.of("B", new Instant(15)), + TimestampedValue.of("C", new Instant(7)))) + .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( + new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.output(c.element() + c.sideInput(view)); + } + })); DataflowAssert.that(output).containsInAnyOrder("A1", "B5", "C1"); @@ -647,28 +1190,28 @@ public void processElement(ProcessContext c) { public void testWindowedSideInputFixedToGlobal() { Pipeline p = TestPipeline.create(); - final PCollectionView view = p - .apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(11)), - TimestampedValue.of(3, new Instant(13)))) - .apply("WindowSideInput", Window.into(new GlobalWindows())) - .apply(Sum.integersGlobally()) - .apply(View.asSingleton()); - - PCollection output = p - .apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("A", new Instant(4)), - TimestampedValue.of("B", new Instant(15)), - TimestampedValue.of("C", new Instant(7)))) - .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); - } - })); + final PCollectionView view = + p.apply( + "CreateSideInput", + Create.timestamped(TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(2, new Instant(11)), TimestampedValue.of(3, new Instant(13)))) + .apply("WindowSideInput", Window.into(new GlobalWindows())) + .apply(Sum.integersGlobally()) + .apply(View.asSingleton()); + + PCollection output = + p.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of("A", new Instant(4)), + TimestampedValue.of("B", new Instant(15)), + TimestampedValue.of("C", new Instant(7)))) + .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( + new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.output(c.element() + c.sideInput(view)); + } + })); DataflowAssert.that(output).containsInAnyOrder("A6", "B6", "C6"); @@ -680,26 +1223,26 @@ public void processElement(ProcessContext c) { public void testWindowedSideInputFixedToFixedWithDefault() { Pipeline p = TestPipeline.create(); - final PCollectionView view = p - .apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(2, new Instant(11)), - TimestampedValue.of(3, new Instant(13)))) - .apply("WindowSideInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply(Sum.integersGlobally().asSingletonView()); - - PCollection output = p - .apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("A", new Instant(4)), - TimestampedValue.of("B", new Instant(15)), - TimestampedValue.of("C", new Instant(7)))) - .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); - } - })); + final PCollectionView view = + p.apply("CreateSideInput", Create.timestamped( + TimestampedValue.of(2, new Instant(11)), + TimestampedValue.of(3, new Instant(13)))) + .apply("WindowSideInput", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply(Sum.integersGlobally().asSingletonView()); + + PCollection output = + p.apply("CreateMainInput", Create.timestamped( + TimestampedValue.of("A", new Instant(4)), + TimestampedValue.of("B", new Instant(15)), + TimestampedValue.of("C", new Instant(7)))) + .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) + .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( + new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.output(c.element() + c.sideInput(view)); + } + })); DataflowAssert.that(output).containsInAnyOrder("A0", "B5", "C0"); @@ -711,24 +1254,25 @@ public void processElement(ProcessContext c) { public void testSideInputWithNullDefault() { Pipeline p = TestPipeline.create(); - final PCollectionView view = p - .apply("CreateSideInput", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply(Combine.globally(new SerializableFunction, Void>() { - @Override - public Void apply(Iterable input) { - return null; - } - }).asSingletonView()); - - PCollection output = p - .apply("CreateMainInput", Create.of("")) - .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { + final PCollectionView view = + p.apply("CreateSideInput", Create.of((Void) null).withCoder(VoidCoder.of())) + .apply(Combine.globally(new SerializableFunction, Void>() { @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); + public Void apply(Iterable input) { + return null; } - })); + }).asSingletonView()); + + PCollection output = + p.apply("CreateMainInput", Create.of("")) + .apply( + "OutputMainAndSideInputs", + ParDo.withSideInputs(view).of(new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.output(c.element() + c.sideInput(view)); + } + })); DataflowAssert.that(output).containsInAnyOrder("null"); @@ -739,39 +1283,41 @@ public void processElement(ProcessContext c) { @Category(RunnableOnService.class) public void testSideInputWithNestedIterables() { Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view1 = pipeline - .apply("CreateVoid1", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply("OutputOneInteger", ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(17); - } - })) - .apply("View1", View.asIterable()); - - final PCollectionView>> view2 = pipeline - .apply("CreateVoid2", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply("OutputSideInput", - ParDo.withSideInputs(view1).of(new DoFn>(){ + final PCollectionView> view1 = + pipeline.apply("CreateVoid1", Create.of((Void) null).withCoder(VoidCoder.of())) + .apply("OutputOneInteger", ParDo.of(new DoFn() { @Override public void processElement(ProcessContext c) { - c.output(c.sideInput(view1)); + c.output(17); } })) - .apply("View2", View.>asIterable()); + .apply("View1", View.asIterable()); - PCollection output = pipeline - .apply("CreateVoid3", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply("ReadIterableSideInput", ParDo.withSideInputs(view2).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - for (Iterable input : c.sideInput(view2)) { - for (Integer i : input) { - c.output(i); - } - } - } - })); + final PCollectionView>> view2 = + pipeline.apply("CreateVoid2", Create.of((Void) null).withCoder(VoidCoder.of())) + .apply( + "OutputSideInput", + ParDo.withSideInputs(view1).of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output(c.sideInput(view1)); + } + })) + .apply("View2", View.>asIterable()); + + PCollection output = + pipeline.apply("CreateVoid3", Create.of((Void) null).withCoder(VoidCoder.of())) + .apply( + "ReadIterableSideInput", ParDo.withSideInputs(view2).of(new DoFn() { + @Override + public void processElement(ProcessContext c) { + for (Iterable input : c.sideInput(view2)) { + for (Integer i : input) { + c.output(i); + } + } + } + })); DataflowAssert.that(output).containsInAnyOrder(17); @@ -813,31 +1359,30 @@ private Pipeline createTestDirectRunner() { return Pipeline.create(options); } - private void testViewUnbounded(Pipeline pipeline, + private void testViewUnbounded( + Pipeline pipeline, PTransform>, ? extends PCollectionView> view) { thrown.expect(IllegalStateException.class); thrown.expectMessage("Unable to create a side-input view from input"); thrown.expectCause( ThrowableMessageMatcher.hasMessage(Matchers.containsString("non-bounded PCollection"))); - pipeline - .apply(new PTransform>>() { - @Override - public PCollection> apply(PBegin input) { - return PCollection.createPrimitiveOutputInternal(input.getPipeline(), - WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED); - } - }) - .apply(view); + pipeline.apply(new PTransform>>() { + @Override + public PCollection> apply(PBegin input) { + return PCollection.createPrimitiveOutputInternal(input.getPipeline(), + WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED); + } + }).apply(view); } - private void testViewNonmerging(Pipeline pipeline, + private void testViewNonmerging( + Pipeline pipeline, PTransform>, ? extends PCollectionView> view) { thrown.expect(IllegalStateException.class); thrown.expectMessage("Unable to create a side-input view from input"); thrown.expectCause( ThrowableMessageMatcher.hasMessage(Matchers.containsString("Consumed by GroupByKey"))); - pipeline - .apply(Create.>of(KV.of("hello", 5))) + pipeline.apply(Create.>of(KV.of("hello", 5))) .apply(Window.>into(new InvalidWindows<>( "Consumed by GroupByKey", FixedWindows.of(Duration.standardHours(1))))) .apply(view); From 867afdd6edbabfaec866d5e0787a5df2b6b2ca89 Mon Sep 17 00:00:00 2001 From: swegner Date: Fri, 5 Feb 2016 15:20:42 -0800 Subject: [PATCH 090/751] Don't wrap system DoFn exceptions. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=113990785 --- .../worker/StreamingSideInputDoFnRunner.java | 40 ++-- .../sdk/testing/SerializableMatchers.java | 2 +- .../sdk/transforms/DoFnReflector.java | 3 +- .../cloud/dataflow/sdk/transforms/ParDo.java | 7 +- .../dataflow/sdk/util/DoFnRunnerBase.java | 18 +- .../sdk/util/LateDataDroppingDoFnRunner.java | 7 +- .../dataflow/sdk/util/ReduceFnRunner.java | 8 +- .../dataflow/sdk/util/SimpleDoFnRunner.java | 9 +- .../dataflow/sdk/util/UserCodeException.java | 138 +++++--------- .../cloud/dataflow/sdk/PipelineTest.java | 2 +- .../sdk/util/SimpleDoFnRunnerTest.java | 86 +++++++++ .../sdk/util/UserCodeExceptionTest.java | 176 ++++++++++++++++++ 12 files changed, 359 insertions(+), 137 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java index b61a48d3ea..be916adf76 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java @@ -31,7 +31,6 @@ import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.CounterSet; @@ -191,14 +190,12 @@ public void startBundle() { BagState> elementsBag = elementBag(window); Iterable> elements = elementsBag.get().read(); - try { - for (WindowedValue elem : elements) { + for (WindowedValue elem : elements) { + try { fn.processElement(createProcessContext(elem)); + } catch (Exception ex) { + throw wrapUserCodeException(ex); } - } catch (Throwable t) { - // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); } elementsBag.clear(); @@ -239,21 +236,26 @@ public void invokeProcessElement(WindowedValue elem) { @SuppressWarnings("unchecked") W window = (W) Iterables.getOnlyElement(elem.getWindows()); - // This can contain user code. Wrap it in case it throws an exception. + Set blocked; try { - Set blocked = computeBlockedSideInputs(window); - if (blocked == null) { - fn.processElement(createProcessContext(elem)); - } else { - elementBag(window).add(elem); - watermarkHold(window).add(elem.getTimestamp()); + blocked = computeBlockedSideInputs(window); + } catch (IOException ex) { + // Can't leak IOException here + throw Throwables.propagate(ex); + } - stepContext.addBlockingSideInputs(blocked); + if (blocked == null) { + // This can contain user code. Wrap it in case it throws an exception. + try { + fn.processElement(createProcessContext(elem)); + } catch (Exception ex) { + throw wrapUserCodeException(ex); } - } catch (Throwable t) { - // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); + } else { + elementBag(window).add(elem); + watermarkHold(window).add(elem.getTimestamp()); + + stepContext.addBlockingSideInputs(blocked); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java index 252bd2fdec..da5171e21f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java @@ -1159,7 +1159,7 @@ public SerializableArrayViaCoder(Coder elementCoder, T[] value) { try { this.encodedValue = CoderUtils.encodeToByteArray(coder, Arrays.asList(value)); } catch (CoderException exc) { - throw new UserCodeException(exc); + throw UserCodeException.wrap(exc); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java index c75c013b2c..1bb05fb340 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java @@ -473,8 +473,7 @@ private void invoke(Method m, m.invoke(on, args); } catch (InvocationTargetException e) { // Exception in user code. - Throwables.propagateIfInstanceOf(e.getCause(), UserCodeException.class); - throw new UserCodeException(e.getCause()); + throw UserCodeException.wrap(e.getCause()); } catch (IllegalAccessException | IllegalArgumentException e) { // Exception in our code. throw Throwables.propagate(e); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java index e971ab9355..0922767adc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java @@ -16,11 +16,13 @@ package com.google.cloud.dataflow.sdk.transforms; +import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; import com.google.cloud.dataflow.sdk.util.DoFnRunner; @@ -45,6 +47,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; +import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -1184,7 +1187,7 @@ private static void evaluateHelpe fnRunner.processElement(windowedElem); inputMutationDetector.verifyUnmodified(); } catch (CoderException e) { - throw new UserCodeException(e); + throw UserCodeException.wrap(e); } catch (IllegalMutationException exn) { throw new IllegalMutationException( String.format("DoFn %s mutated input value %s of class %s (new value was %s)." @@ -1252,7 +1255,7 @@ public void output(TupleTag tag, WindowedValue output) { MutationDetector priorDetector = mutationDetectorForTag.put(tag, newDetector); verifyOutputUnmodified(priorDetector); } catch (CoderException e) { - throw new UserCodeException(e); + throw UserCodeException.wrap(e); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index de2844c7ff..f4dfeb20b6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -37,7 +37,6 @@ import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -128,8 +127,7 @@ public void startBundle() { fn.startBundle(context); } catch (Throwable t) { // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); + throw wrapUserCodeException(t); } } @@ -173,8 +171,7 @@ public void finishBundle() { fn.finishBundle(context); } catch (Throwable t) { // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); + throw wrapUserCodeException(t); } } @@ -275,8 +272,7 @@ public Collection windows() { } }); } catch (Exception e) { - Throwables.propagateIfInstanceOf(e, UserCodeException.class); - throw new UserCodeException(e); + throw UserCodeException.wrap(e); } } @@ -381,6 +377,14 @@ protected DoFn.ProcessContext createProcessContext(WindowedValu return new DoFnProcessContext(fn, context, elem); } + protected RuntimeException wrapUserCodeException(Throwable t) { + throw UserCodeException.wrapIf(!isSystemDoFn(), t); + } + + private boolean isSystemDoFn() { + return fn.getClass().isAnnotationPresent(SystemDoFnInternal.class); + } + /** * A concrete implementation of {@code DoFn.ProcessContext} used for * running a {@link DoFn} over a single element. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java index 749438a99a..e1f13d539d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.common.base.Function; import com.google.common.base.Predicate; -import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import org.joda.time.Instant; @@ -118,10 +117,8 @@ public boolean apply(WindowedValue input) { // This can contain user code. Wrap it in case it throws an exception. try { fn.processElement(createProcessContext(elem.withValue(inputs))); - } catch (Throwable t) { - // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); + } catch (Exception ex) { + throw wrapUserCodeException(ex); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 54906b1e5c..5fc2bc22ba 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -729,11 +729,7 @@ private void cancelEndOfWindowAndGarbageCollectionTimers(ReduceFn.Co ////////////////////////////////////////////////////////////////////////////////////////////////// private RuntimeException wrapMaybeUserException(Throwable t) { - if (reduceFn instanceof SystemReduceFn) { - throw Throwables.propagate(t); - } else { - // Any exceptions that happen inside a non-system ReduceFn are considered user code. - throw new UserCodeException(t); - } + // Any exceptions that happen inside a non-system ReduceFn are considered user code. + throw UserCodeException.wrapIf(!(reduceFn instanceof SystemReduceFn), t); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java index 66824e39f2..15a5e51834 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Throwables; import java.util.List; @@ -44,14 +43,12 @@ protected SimpleDoFnRunner(PipelineOptions options, DoFn fn, @Override protected void invokeProcessElement(WindowedValue elem) { - DoFn.ProcessContext processContext = createProcessContext(elem); + final DoFn.ProcessContext processContext = createProcessContext(elem); // This can contain user code. Wrap it in case it throws an exception. try { fn.processElement(processContext); - } catch (Throwable t) { - // Exception in user code. - Throwables.propagateIfInstanceOf(t, UserCodeException.class); - throw new UserCodeException(t); + } catch (Exception ex) { + throw wrapUserCodeException(ex); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java index b0f21f5dfb..9b9c7a5919 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java @@ -16,9 +16,6 @@ package com.google.cloud.dataflow.sdk.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Arrays; import java.util.Objects; @@ -29,104 +26,69 @@ * reached. */ public class UserCodeException extends RuntimeException { - private static final Logger LOG = LoggerFactory.getLogger(UserCodeException.class); - - public UserCodeException(Throwable t) { - super(t); - StackTraceElement[] currentFrames = - Thread.currentThread().getStackTrace(); - - // We're interested in getting the third stack frame here, since - // the exception stack trace includes the getStackTrace frame from - // Thread and the frame from where the UserCodeException is - // actually thrown. If there aren't more than two frames, - // something is odd about where the exception was thrown, so leave - // the stack trace alone and allow it to propagate. - // - // For example, if an exception in user code has a stack trace like this: - // - // java.lang.NullPointerException - // at com.google.cloud.dataflow.sdk.examples. - // SimpleWordCount$ExtractWordsFn.dieHere(SimpleWordCount.java:23) - // at com.google.cloud.dataflow.sdk.examples. - // SimpleWordCount$ExtractWordsFn. - // processElement(SimpleWordCount.java:27) - // at com.google.cloud.dataflow.sdk. - // DoFnRunner.processElement(DoFnRunner.java:95) <-- caught here - // at com.google.cloud.dataflow.sdk. - // worker.NormalParDoFn.processElement(NormalParDoFn.java:119) - // at com.google.cloud.dataflow.sdk. - // worker.executor.ParDoOperation.process(ParDoOperation.java:65) - // at com.google.cloud.dataflow.sdk. - // worker.executor.ReadOperation.start(ReadOperation.java:65) - // at com.google.cloud.dataflow.sdk. - // worker.executor.MapTaskExecutor.execute(MapTaskExecutor.java:79) - // at com.google.cloud.dataflow.sdk. - // worker.DataflowWorkerHarness.main(DataflowWorkerHarness.java:95) - // - // It would be truncated to: - // - // java.lang.NullPointerException - // at com.google.cloud.dataflow.sdk.examples. - // SimpleWordCount$ExtractWordsFn.dieHere(SimpleWordCount.java:23) - // at com.google.cloud.dataflow.sdk.examples. - // SimpleWordCount$ExtractWordsFn. - // processElement(SimpleWordCount.java:27) - // - // However, we need to get the third stack frame from the - // getStackTrace, since after catching the error in DoFnRunner, - // the trace is two frames deeper by the time we get it: - // - // [0] java.lang.Thread.getStackTrace(Thread.java:1568) - // [1] com.google.cloud.dataflow.sdk. - // UserCodeException.(UserCodeException.java:16) - // [2] com.google.cloud.dataflow.sdk. - // DoFnRunner.processElement(DoFnRunner.java:95) <-- common frame - // - // We then proceed to truncate the original exception at the - // common frame, setting the UserCodeException's cause to the - // truncated stack trace. - - // Check to make sure the stack is > 2 deep. - if (currentFrames.length <= 2) { - LOG.error("Expecting stack trace to be > 2 frames long."); - return; + public static UserCodeException wrap(Throwable t) { + if (t instanceof UserCodeException) { + return (UserCodeException) t; } - // Perform some checks to make sure javac doesn't change from below us. - if (!Objects.equals(currentFrames[1].getClassName(), getClass().getName())) { - LOG.error("Expected second frame coming from Thread.currentThread.getStackTrace() " - + "to be {}, was: {}", getClass().getName(), currentFrames[1].getClassName()); - return; + return new UserCodeException(t); + } + + public static RuntimeException wrapIf(boolean condition, Throwable t) { + if (condition) { + return wrap(t); } - if (Objects.equals(currentFrames[2].getClassName(), currentFrames[1].getClassName())) { - LOG.error("Javac's Thread.CurrentThread.getStackTrace() changed unexpectedly."); - return; + + if (t instanceof RuntimeException) { + return (RuntimeException) t; } - // Now that all checks have passed, select the common frame. - StackTraceElement callingFrame = currentFrames[2]; - // Truncate the user-level stack trace below where the - // UserCodeException was thrown. - truncateStackTrace(callingFrame, t); + return new RuntimeException(t); + } + + private UserCodeException(Throwable t) { + super(t); + truncateStackTrace(t); } /** - * Truncates this Throwable's stack frame at the given frame, + * Truncates the @{Throwable}'s stack trace to contain only user code, * removing all frames below. + * + *

      This is to remove infrastructure noise below user code entry point. We do this + * by finding common stack frames between the throwable's captured stack and that + * of the current thread. */ - private void truncateStackTrace( - StackTraceElement currentFrame, Throwable t) { - int index = 0; - StackTraceElement[] stackTrace = t.getStackTrace(); - for (StackTraceElement element : stackTrace) { - if (Objects.equals(element.getClassName(), currentFrame.getClassName()) && - Objects.equals(element.getMethodName(), currentFrame.getMethodName())) { - t.setStackTrace(Arrays.copyOfRange(stackTrace, 0, index)); + private void truncateStackTrace(Throwable t) { + + StackTraceElement[] currentStack = Thread.currentThread().getStackTrace(); + StackTraceElement[] throwableStack = t.getStackTrace(); + + int currentStackSize = currentStack.length; + int throwableStackSize = throwableStack.length; + + int commonFrames = 0; + while (framesEqual(currentStack[currentStackSize - commonFrames - 1], + throwableStack[throwableStackSize - commonFrames - 1])) { + commonFrames++; + if (commonFrames >= Math.min(currentStackSize, throwableStackSize)) { break; } - index++; } + + StackTraceElement[] truncatedStack = Arrays.copyOfRange(throwableStack, 0, + throwableStackSize - commonFrames); + t.setStackTrace(truncatedStack); + } + + /** + * Check if two frames are equal; Frames are considered equal if they point to the same method. + */ + private boolean framesEqual(StackTraceElement frame1, StackTraceElement frame2) { + boolean areEqual = Objects.equals(frame1.getClassName(), frame2.getClassName()); + areEqual &= Objects.equals(frame1.getMethodName(), frame2.getMethodName()); + + return areEqual; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java index 351af9307a..e311252021 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java @@ -77,7 +77,7 @@ static class TestPipelineRunnerThrowingUserException @Override public PipelineResult run(Pipeline pipeline) { Throwable t = new IllegalStateException("user code exception"); - throw new UserCodeException(t); + throw UserCodeException.wrap(t); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java new file mode 100644 index 0000000000..4af60dbe91 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.mock; + +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.util.BaseExecutionContext.StepContext; +import com.google.cloud.dataflow.sdk.values.TupleTag; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Arrays; +import java.util.List; + +/** + * Tests for base @{link DoFnRunnerBase} functionality. + */ +@RunWith(JUnit4.class) +public class SimpleDoFnRunnerTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testExceptionsWrappedAsUserCodeException() { + ThrowingDoFn fn = new ThrowingDoFn(); + DoFnRunner runner = createRunner(fn); + + thrown.expect(UserCodeException.class); + thrown.expectCause(is(fn.exceptionToThrow)); + + runner.processElement(WindowedValue.valueInGlobalWindow("anyValue")); + } + + @Test + public void testSystemDoFnInternalExceptionsNotWrapped() { + ThrowingSystemDoFn fn = new ThrowingSystemDoFn(); + DoFnRunner runner = createRunner(fn); + + thrown.expect(is(fn.exceptionToThrow)); + + runner.processElement(WindowedValue.valueInGlobalWindow("anyValue")); + } + + private DoFnRunner createRunner(DoFn fn) { + // Pass in only necessary parameters for the test + List> sideOutputTags = Arrays.asList(); + StepContext context = mock(StepContext.class); + return DoFnRunners.simpleRunner( + null, fn, null, null, null, sideOutputTags, context, null, null); + } + + static class ThrowingDoFn extends DoFn { + final Exception exceptionToThrow = + new UnsupportedOperationException("Expected exception"); + + @Override + public void processElement(ProcessContext c) throws Exception { + throw exceptionToThrow; + } + } + + @SystemDoFnInternal + static class ThrowingSystemDoFn extends ThrowingDoFn { + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java new file mode 100644 index 0000000000..5cf385cf31 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.hamcrest.Description; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; + +/** + * Tests for @{link UserCodeException} functionality. + */ +@RunWith(JUnit4.class) +public class UserCodeExceptionTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void existingUserCodeExceptionsNotWrapped() { + UserCodeException existing = UserCodeException.wrap(new IOException()); + UserCodeException wrapped = UserCodeException.wrap(existing); + + assertEquals(existing, wrapped); + } + + @Test + public void testCauseIsSet() { + thrown.expectCause(isA(IOException.class)); + throwUserCodeException(); + } + + @Test + public void testStackTraceIsTruncatedToUserCode() { + thrown.expectCause(hasBottomStackFrame(method("userCode"))); + throwUserCodeException(); + } + + @Test + public void testStackTraceIsTruncatedProperlyFromHelperMethod() { + thrown.expectCause(hasBottomStackFrame(method("userCode"))); + throwUserCodeExceptionFromHelper(); + } + + @Test + public void testWrapIfOnlyWrapsWhenTrue() { + IOException cause = new IOException(); + RuntimeException wrapped = UserCodeException.wrapIf(true, cause); + + assertThat(wrapped, is(instanceOf(UserCodeException.class))); + } + + @Test + public void testWrapIfReturnsRuntimeExceptionWhenFalse() { + IOException cause = new IOException(); + RuntimeException wrapped = UserCodeException.wrapIf(false, cause); + + assertThat(wrapped, is(not(instanceOf(UserCodeException.class)))); + assertEquals(cause, wrapped.getCause()); + } + + @Test + public void testWrapIfReturnsSourceRuntimeExceptionWhenFalse() { + RuntimeException runtimeException = new RuntimeException("oh noes!"); + RuntimeException wrapped = UserCodeException.wrapIf(false, runtimeException); + + assertEquals(runtimeException, wrapped); + } + + + private void throwUserCodeException() { + try { + userCode(); + } catch (Exception ex) { + throw UserCodeException.wrap(ex); + } + } + + private void throwUserCodeExceptionFromHelper() { + try { + userCode(); + } catch (Exception ex) { + throw wrap(ex); + } + } + + private UserCodeException wrap(Throwable t) { + throw UserCodeException.wrap(t); + } + + private void userCode() throws IOException { + userCode2(); + } + + private void userCode2() throws IOException { + userCode3(); + } + + private void userCode3() throws IOException { + IOException ex = new IOException("User processing error!"); + throw ex; + } + + private static ThrowableBottomStackFrameMethodMatcher hasBottomStackFrame( + Matcher frameMatcher) { + return new ThrowableBottomStackFrameMethodMatcher(frameMatcher); + } + + private static StackFrameMethodMatcher method(String methodName) { + return new StackFrameMethodMatcher(is(methodName)); + } + + static class ThrowableBottomStackFrameMethodMatcher + extends FeatureMatcher { + + public ThrowableBottomStackFrameMethodMatcher(Matcher subMatcher) { + super(subMatcher, "Throwable with bottom stack frame:", "stack frame"); + } + + @Override + protected StackTraceElement featureValueOf(Throwable actual) { + StackTraceElement[] stackTrace = actual.getStackTrace(); + return stackTrace[stackTrace.length - 1]; + } + } + + static class StackFrameMethodMatcher extends TypeSafeMatcher { + + private Matcher methodNameMatcher; + + public StackFrameMethodMatcher(Matcher methodNameMatcher) { + this.methodNameMatcher = methodNameMatcher; + } + + @Override + public void describeTo(Description description) { + description.appendText("stack frame where method name "); + methodNameMatcher.describeTo(description); + } + + @Override + protected boolean matchesSafely(StackTraceElement item) { + return methodNameMatcher.matches(item.getMethodName()); + } + } +} + From abcbdf4ab63cf21bbeae0cff9a2d21f7657ef793 Mon Sep 17 00:00:00 2001 From: klk Date: Fri, 5 Feb 2016 19:25:09 -0800 Subject: [PATCH 091/751] Move BatchModeExecutionContext and dependents to worker module ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114006425 --- .../sdk/runners/worker/ConcatReader.java | 27 +- .../runners/worker/ConcatReaderFactory.java | 163 ------- .../runners/worker/GroupingShuffleReader.java | 440 ------------------ .../worker/GroupingShuffleReaderFactory.java | 95 ---- ...uffleReaderWithFaultyBytesReadCounter.java | 67 --- .../sdk/runners/worker/ReaderRegistry.java | 161 ------- .../sdk/util/BatchModeExecutionContext.java | 146 ------ .../dataflow/sdk/util/CloudSourceUtils.java | 21 - .../runners/dataflow/CustomSourcesTest.java | 180 ------- 9 files changed, 18 insertions(+), 1282 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java index f3057c5ce0..d7c0429d42 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java @@ -25,10 +25,13 @@ import com.google.api.services.dataflow.model.ApproximateSplitRequest; import com.google.api.services.dataflow.model.ConcatPosition; import com.google.api.services.dataflow.model.Source; +import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.DataflowReaderProgress; +import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.Serializer; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import com.google.common.annotations.VisibleForTesting; @@ -72,20 +75,20 @@ public class ConcatReader extends NativeReader { private final ExecutionContext executionContext; private final CounterSet.AddCounterMutator addCounterMutator; private final String operationName; - private final ReaderRegistry registry; + private final ReaderFactory readerFactory; /** * Create a {@link ConcatReader} using a given list of encoded {@link Source}s. */ public ConcatReader( - ReaderRegistry registry, + ReaderFactory readerFactory, PipelineOptions options, ExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, String operationName, List sources) { Preconditions.checkNotNull(sources); - this.registry = registry; + this.readerFactory = readerFactory; this.sources = sources; this.options = options; this.executionContext = executionContext; @@ -100,7 +103,7 @@ public Iterator getSources() { @Override public ConcatIterator iterator() throws IOException { return new ConcatIterator( - registry, + readerFactory, options, executionContext, addCounterMutator, @@ -118,16 +121,16 @@ static class ConcatIterator extends NativeReaderIterator { private final CounterSet.AddCounterMutator addCounterMutator; private final String operationName; private final OffsetRangeTracker rangeTracker; - private final ReaderRegistry registry; + private final ReaderFactory readerFactory; public ConcatIterator( - ReaderRegistry registry, + ReaderFactory readerFactory, PipelineOptions options, ExecutionContext executionContext, CounterSet.AddCounterMutator addCounterMutator, String operationName, List sources) { - this.registry = registry; + this.readerFactory = readerFactory; this.sources = sources; this.options = options; this.executionContext = executionContext; @@ -168,11 +171,17 @@ public boolean advance() throws IOException { Source currentSource = sources.get(currentIteratorIndex); try { + Coder coder = null; + if (currentSource.getCodec() != null) { + coder = Serializer.deserialize(currentSource.getCodec(), Coder.class); + } @SuppressWarnings("unchecked") NativeReader currentReader = (NativeReader) - registry.create( - currentSource, options, executionContext, addCounterMutator, operationName); + readerFactory.create( + CloudObject.fromSpec(currentSource.getSpec()), coder, options, + executionContext, addCounterMutator, + operationName); currentIterator = currentReader.iterator(); } catch (Exception e) { throw new IOException("Failed to create a reader for source: " + currentSource, e); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java deleted file mode 100644 index 05ae2b9b17..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReaderFactory.java +++ /dev/null @@ -1,163 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.getListOfMaps; -import static com.google.cloud.dataflow.sdk.util.Structs.getLong; -import static com.google.cloud.dataflow.sdk.util.Structs.getObject; - -import com.google.api.services.dataflow.model.Source; -import com.google.api.services.dataflow.model.SourceMetadata; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * Creates an {@link ConcatReader} from a {@link CloudObject} spec. - */ -public class ConcatReaderFactory implements ReaderFactory { - - private final ReaderRegistry registry; - - private ConcatReaderFactory(ReaderRegistry registry) { - this.registry = registry; - } - - /** - * Returns a new {@link ConcatReaderFactory} that will use the default - * {@link ReaderRegistry} to create sub-{@link NativeReader} instances. - */ - public static ConcatReaderFactory withDefaultRegistry() { - return withRegistry(ReaderRegistry.defaultRegistry()); - } - - /** - * Returns a new {@link ConcatReaderFactory} that will use the provided - * {@link ReaderRegistry} to create sub-{@link NativeReader} instances. - */ - public static ConcatReaderFactory withRegistry(ReaderRegistry registry) { - return new ConcatReaderFactory(registry); - } - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - @SuppressWarnings("unchecked") - Coder typedCoder = (Coder) coder; - return createTyped( - spec, typedCoder, options, executionContext, addCounterMutator, operationName); - } - - public NativeReader createTyped( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - List sources = getSubSources(spec); - return new ConcatReader( - registry, options, executionContext, addCounterMutator, operationName, sources); - } - - private static List getSubSources(CloudObject spec) throws Exception { - List subSources = new ArrayList<>(); - - // Get the list of sub-sources. - List> subSourceDictionaries = - getListOfMaps(spec, PropertyNames.CONCAT_SOURCE_SOURCES, null); - if (subSourceDictionaries == null) { - return subSources; - } - - for (Map subSourceDictionary : subSourceDictionaries) { - // Each sub-source is encoded as a dictionary that contains several properties. - subSources.add(createSourceFromDictionary(subSourceDictionary)); - } - - return subSources; - } - - public static Source createSourceFromDictionary(Map dictionary) throws Exception { - Source source = new Source(); - - // Set spec - CloudObject subSourceSpec = - CloudObject.fromSpec(getObject(dictionary, PropertyNames.SOURCE_SPEC)); - source.setSpec(subSourceSpec); - - // Set encoding - CloudObject subSourceEncoding = - CloudObject.fromSpec(getObject(dictionary, PropertyNames.ENCODING, null)); - if (subSourceEncoding != null) { - source.setCodec(subSourceEncoding); - } - - // Set base specs - List> subSourceBaseSpecs = - getListOfMaps(dictionary, PropertyNames.CONCAT_SOURCE_BASE_SPECS, null); - if (subSourceBaseSpecs != null) { - source.setBaseSpecs(subSourceBaseSpecs); - } - - // Set metadata - SourceMetadata metadata = new SourceMetadata(); - Boolean producesSortedKeys = - getBoolean(dictionary, PropertyNames.SOURCE_PRODUCES_SORTED_KEYS, null); - if (producesSortedKeys != null) { - metadata.setProducesSortedKeys(producesSortedKeys); - } - Boolean infinite = getBoolean(dictionary, PropertyNames.SOURCE_IS_INFINITE, null); - if (infinite != null) { - metadata.setInfinite(infinite); - } - Long estimatedSizeBytes = getLong(dictionary, PropertyNames.SOURCE_ESTIMATED_SIZE_BYTES, null); - if (estimatedSizeBytes != null) { - metadata.setEstimatedSizeBytes(estimatedSizeBytes); - } - if (producesSortedKeys != null || estimatedSizeBytes != null || infinite != null) { - source.setMetadata(metadata); - } - - // Set doesNotNeedSplitting - Boolean doesNotNeedSplitting = - getBoolean(dictionary, PropertyNames.SOURCE_DOES_NOT_NEED_SPLITTING, null); - if (doesNotNeedSplitting != null) { - source.setDoesNotNeedSplitting(doesNotNeedSplitting); - } - - return source; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java deleted file mode 100644 index ce9a626b60..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReader.java +++ /dev/null @@ -1,440 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Preconditions.checkNotNull; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservableIterable; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservableIterator; -import com.google.cloud.dataflow.sdk.util.common.Reiterable; -import com.google.cloud.dataflow.sdk.util.common.Reiterator; -import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; -import com.google.cloud.dataflow.sdk.util.common.worker.GroupingShuffleEntryIterator; -import com.google.cloud.dataflow.sdk.util.common.worker.KeyGroupedShuffleEntries; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntryReader; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.concurrent.atomic.AtomicLong; - -import javax.annotation.Nullable; - -/** - * A source that reads from a shuffled dataset and yields key-grouped data. - * - * @param the type of the keys read from the shuffle - * @param the type of the values read from the shuffle - */ -public class GroupingShuffleReader extends NativeReader>>> { - private static final Logger LOG = LoggerFactory.getLogger(GroupingShuffleReader.class); - public static final String SOURCE_NAME = "GroupingShuffleSource"; - - final byte[] shuffleReaderConfig; - @Nullable final String startShufflePosition; - @Nullable final String stopShufflePosition; - final BatchModeExecutionContext executionContext; - @Nullable final CounterSet.AddCounterMutator addCounterMutator; - @Nullable final String operationName; - - // Counts how many bytes were from by a given operation from a given shuffle session. - @Nullable Counter perOperationPerDatasetBytesCounter; - Coder keyCoder; - Coder valueCoder; - @Nullable Coder secondaryKeyCoder; - - public GroupingShuffleReader( - PipelineOptions options, - byte[] shuffleReaderConfig, - @Nullable String startShufflePosition, - @Nullable String stopShufflePosition, - Coder>>> coder, - BatchModeExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - String operationName, - boolean valuesAreSorted) - throws Exception { - this.shuffleReaderConfig = shuffleReaderConfig; - this.startShufflePosition = startShufflePosition; - this.stopShufflePosition = stopShufflePosition; - this.executionContext = executionContext; - this.addCounterMutator = addCounterMutator; - this.operationName = operationName; - initCoder(coder, valuesAreSorted); - // We cannot initialize perOperationPerDatasetBytesCounter here, as it - // depends on shuffleReaderConfig, which isn't populated yet. - } - - private synchronized void initCounter(String datasetId) { - if (perOperationPerDatasetBytesCounter == null - && addCounterMutator != null - && operationName != null) { - perOperationPerDatasetBytesCounter = - addCounterMutator.addCounter( - Counter.longs( - "dax-shuffle-" + datasetId + "-wf-" + operationName + "-read-bytes", - SUM)); - } - } - - @Override - protected StateKind getStateSamplerStateKind() { - return StateKind.FRAMEWORK; - } - - @Override - public GroupingShuffleReaderIterator iterator() throws IOException { - Preconditions.checkArgument(shuffleReaderConfig != null); - ApplianceShuffleReader asr = - new ApplianceShuffleReader(shuffleReaderConfig, addCounterMutator); - String datasetId = asr.getDatasetId(); - initCounter(datasetId); - - return iterator(new BatchingShuffleEntryReader( - new ChunkingShuffleBatchReader(asr))); - } - - private void initCoder(Coder>>> coder, - boolean valuesAreSorted) throws Exception { - if (!(coder instanceof WindowedValueCoder)) { - throw new Exception("unexpected kind of coder for WindowedValue: " + coder); - } - Coder>> elemCoder = - ((WindowedValueCoder>>) coder).getValueCoder(); - if (!(elemCoder instanceof KvCoder)) { - throw new Exception("unexpected kind of coder for elements read from " - + "a key-grouping shuffle: " + elemCoder); - } - - @SuppressWarnings("unchecked") - KvCoder> kvCoder = (KvCoder>) elemCoder; - this.keyCoder = kvCoder.getKeyCoder(); - Coder> kvValueCoder = kvCoder.getValueCoder(); - if (!(kvValueCoder instanceof IterableCoder)) { - throw new Exception("unexpected kind of coder for values of KVs read from " - + "a key-grouping shuffle"); - } - IterableCoder iterCoder = (IterableCoder) kvValueCoder; - if (valuesAreSorted) { - checkState(iterCoder.getElemCoder() instanceof KvCoder, - "unexpected kind of coder for elements read from a " - + "key-grouping value sorting shuffle: %s", iterCoder.getElemCoder()); - @SuppressWarnings("rawtypes") - KvCoder valueKvCoder = (KvCoder) iterCoder.getElemCoder(); - this.secondaryKeyCoder = valueKvCoder.getKeyCoder(); - this.valueCoder = valueKvCoder.getValueCoder(); - } else { - this.valueCoder = iterCoder.getElemCoder(); - } - } - - final GroupingShuffleReaderIterator iterator(ShuffleEntryReader reader) { - return new GroupingShuffleReaderIterator(this, reader); - } - - /** - * A ReaderIterator that reads from a ShuffleEntryReader and groups - * all the values with the same key. - * - *

      A key limitation of this implementation is that all iterator accesses - * must by externally synchronized (the iterator objects are not individually - * thread-safe, and the iterators derived from a single original iterator - * access shared state that is not thread-safe). - * - *

      To access the current position, the iterator must advance - * on-demand and cache the next batch of key grouped shuffle - * entries. The iterator does not advance a second time in @next() - * to avoid asking the underlying iterator to advance to the next - * key before the caller/user iterates over the values corresponding - * to the current key, which would introduce a performance - * penalty. - */ - @VisibleForTesting - static final class GroupingShuffleReaderIterator - extends LegacyReaderIterator>>> { - // The enclosing GroupingShuffleReader. - private final GroupingShuffleReader parentReader; - - /** The iterator over shuffle entries, grouped by common key. */ - private final Iterator groups; - - private final GroupingShuffleRangeTracker rangeTracker; - private ByteArrayShufflePosition lastGroupStart; - - /** The next group to be consumed, if available. */ - private KeyGroupedShuffleEntries currentGroup = null; - private final AtomicLong currentGroupSize = new AtomicLong(0L); - - protected StateSampler stateSampler = null; - protected int readState; - - public GroupingShuffleReaderIterator( - final GroupingShuffleReader parentReader, ShuffleEntryReader entryReader) { - this.parentReader = parentReader; - if (parentReader.stateSampler == null) { - // This code path is only used in tests. - CounterSet counterSet = new CounterSet(); - this.stateSampler = new StateSampler("local", counterSet.getAddCounterMutator()); - this.readState = stateSampler.stateForName("shuffle", StateSampler.StateKind.FRAMEWORK); - } else { - checkNotNull(parentReader.stateSamplerOperationName); - this.stateSampler = parentReader.stateSampler; - this.readState = stateSampler.stateForName( - parentReader.stateSamplerOperationName + "-process", - StateSampler.StateKind.FRAMEWORK); - } - - this.rangeTracker = - new GroupingShuffleRangeTracker( - ByteArrayShufflePosition.fromBase64(parentReader.startShufflePosition), - ByteArrayShufflePosition.fromBase64(parentReader.stopShufflePosition)); - try (StateSampler.ScopedState read = stateSampler.scopedState(readState)) { - this.groups = - new GroupingShuffleEntryIterator( - entryReader.read(rangeTracker.getStartPosition(), rangeTracker.getStopPosition()), - parentReader.perOperationPerDatasetBytesCounter) { - @Override - protected void notifyElementRead(long byteSize) { - // We accumulate the sum of bytes read in a local variable. This sum will be counted - // when the values are actually read by the consumer of the shuffle reader. - currentGroupSize.addAndGet(byteSize); - parentReader.notifyElementRead(byteSize); - } - }; - } - } - - @Override - protected boolean hasNextImpl() throws IOException { - try (StateSampler.ScopedState read = stateSampler.scopedState(readState)) { - if (!groups.hasNext()) { - return false; - } - currentGroup = groups.next(); - } - ByteArrayShufflePosition groupStart = ByteArrayShufflePosition.of(currentGroup.position); - boolean isAtSplitPoint = (lastGroupStart == null) || (!groupStart.equals(lastGroupStart)); - lastGroupStart = groupStart; - return rangeTracker.tryReturnRecordAt(isAtSplitPoint, groupStart); - } - - @Override - protected WindowedValue>> nextImpl() throws IOException { - K key = CoderUtils.decodeFromByteArray(parentReader.keyCoder, currentGroup.key); - if (parentReader.executionContext != null) { - parentReader.executionContext.setKey(key); - } - - KeyGroupedShuffleEntries group = currentGroup; - currentGroup = null; - return WindowedValue.valueInEmptyWindows( - KV.>of(key, new ValuesIterable(group.values))); - } - - @Override - public double getRemainingParallelism() { - // Return 1 iff the stop position <= the lexicographic successor to the current position. - ByteArrayShufflePosition stopPosition = rangeTracker.getStopPosition(); - if (stopPosition != null - && lastGroupStart != null - && stopPosition.compareTo(lastGroupStart.immediateSuccessor()) <= 0) { - return 1; - } else { - return Double.POSITIVE_INFINITY; - } - } - - /** - * Returns the position before the next {@code KV>} to be returned by the - * {@link GroupingShuffleReaderIterator}. Returns null if the - * {@link GroupingShuffleReaderIterator} is finished. - */ - @Override - public Progress getProgress() { - com.google.api.services.dataflow.model.Position position = - new com.google.api.services.dataflow.model.Position(); - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - ByteArrayShufflePosition groupStart = rangeTracker.getLastGroupStart(); - if (groupStart != null) { - position.setShufflePosition(groupStart.encodeBase64()); - progress.setPosition(position); - } - return cloudProgressToReaderProgress(progress); - } - - /** - * Updates the stop position of the shuffle source to the position proposed. Ignores the - * proposed stop position if it is smaller than or equal to the position before the next - * {@code KV>} to be returned by the {@link GroupingShuffleReaderIterator}. - */ - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - checkNotNull(splitRequest); - ApproximateSplitRequest splitProgress = splitRequestToApproximateSplitRequest( - splitRequest); - com.google.api.services.dataflow.model.Position splitPosition = splitProgress.getPosition(); - if (splitPosition == null) { - LOG.warn("GroupingShuffleReader only supports split at a Position. Requested: {}", - splitRequest); - return null; - } - String splitShufflePosition = splitPosition.getShufflePosition(); - if (splitShufflePosition == null) { - LOG.warn("GroupingShuffleReader only supports split at a shuffle position. Requested: {}", - splitPosition); - return null; - } - ByteArrayShufflePosition newStopPosition = - ByteArrayShufflePosition.fromBase64(splitShufflePosition); - if (rangeTracker.trySplitAtPosition(newStopPosition)) { - LOG.info( - "Split GroupingShuffleReader at {}, now {}", - newStopPosition.encodeBase64(), - rangeTracker); - return new DynamicSplitResultWithPosition(cloudPositionToReaderPosition(splitPosition)); - } else { - LOG.info( - "Refused to split GroupingShuffleReader {} at {}", - rangeTracker, - newStopPosition.encodeBase64()); - return null; - } - } - - /** - * Provides the {@link Reiterable} used to iterate through the values part - * of a {@code KV>} entry produced by a - * {@link GroupingShuffleReader}. - */ - private final class ValuesIterable extends ElementByteSizeObservableIterable - implements Reiterable { - // N.B. This class is *not* static; it uses the valueCoder from - // its enclosing GroupingShuffleReader. - - private final Reiterable base; - - public ValuesIterable(Reiterable base) { - this.base = checkNotNull(base); - } - - @Override - public ValuesIterator iterator() { - return new ValuesIterator(base.iterator()); - } - - @Override - protected ValuesIterator createIterator() { - return iterator(); - } - } - - /** - * Provides the {@link Reiterator} used to iterate through the values part - * of a {@code KV>} entry produced by a - * {@link GroupingShuffleReader}. - */ - private final class ValuesIterator extends ElementByteSizeObservableIterator - implements Reiterator { - // N.B. This class is *not* static; it uses the valueCoder from - // its enclosing GroupingShuffleReader. - - private final Reiterator base; - - public ValuesIterator(Reiterator base) { - this.base = checkNotNull(base); - } - - @Override - public boolean hasNext() { - try (StateSampler.ScopedState read = - GroupingShuffleReaderIterator.this.stateSampler.scopedState( - GroupingShuffleReaderIterator.this.readState)) { - return base.hasNext(); - } - } - - @Override - public V next() { - try (StateSampler.ScopedState read = - GroupingShuffleReaderIterator.this.stateSampler.scopedState( - GroupingShuffleReaderIterator.this.readState)) { - ShuffleEntry entry = base.next(); - - // The shuffle entries are handed over to the consumer of this iterator. Therefore, we can - // notify the bytes that have been read so far. - notifyValueReturned(currentGroupSize.getAndSet(0L)); - try { - if (parentReader.secondaryKeyCoder != null) { - ByteArrayInputStream bais = new ByteArrayInputStream(entry.getSecondaryKey()); - @SuppressWarnings("unchecked") - V value = (V) KV.of( - // We ignore decoding the timestamp. - parentReader.secondaryKeyCoder.decode(bais, Context.NESTED), - CoderUtils.decodeFromByteArray(parentReader.valueCoder, entry.getValue())); - return value; - } else { - @SuppressWarnings("unchecked") - V value = (V) CoderUtils.decodeFromByteArray(parentReader.valueCoder, - entry.getValue()); - return value; - } - } catch (IOException exn) { - throw new RuntimeException(exn); - } - } - } - - @Override - public void remove() { - base.remove(); - } - - @Override - public ValuesIterator copy() { - return new ValuesIterator(base.copy()); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java deleted file mode 100644 index a0f1c9d73a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.values.KV; - -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Creates a GroupingShuffleReader from a CloudObject spec. - */ -public class GroupingShuffleReaderFactory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - - @SuppressWarnings({"rawtypes", "unchecked"}) - Coder>>> typedCoder = (Coder) coder; - return createTyped( - spec, typedCoder, options, executionContext, addCounterMutator, operationName); - } - - public GroupingShuffleReader createTyped( - CloudObject spec, - @Nullable Coder>>> coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - if (shouldUseGroupingShuffleReaderWithFaultyBytesReadCounter(options)) { - return new GroupingShuffleReaderWithFaultyBytesReadCounter(options, - decodeBase64(getString(spec, PropertyNames.SHUFFLE_READER_CONFIG)), - getString(spec, PropertyNames.START_SHUFFLE_POSITION, null), - getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), coder, - (BatchModeExecutionContext) executionContext, addCounterMutator, operationName, - getBoolean(spec, PropertyNames.SORT_VALUES, false)); - } - - return new GroupingShuffleReader(options, - decodeBase64(getString(spec, PropertyNames.SHUFFLE_READER_CONFIG)), - getString(spec, PropertyNames.START_SHUFFLE_POSITION, null), - getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), - coder, - (BatchModeExecutionContext) executionContext, - addCounterMutator, operationName, - getBoolean(spec, PropertyNames.SORT_VALUES, false)); - } - - /** - * Returns true if we should inject errors in the shuffle read bytes - * counter for testing. - */ - private static boolean shouldUseGroupingShuffleReaderWithFaultyBytesReadCounter( - PipelineOptions options) { - List experiments = options.as(DataflowPipelineDebugOptions.class).getExperiments(); - return (experiments != null) && experiments.contains("inject_shuffle_read_count_error"); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java deleted file mode 100644 index d4a4170f72..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleReaderWithFaultyBytesReadCounter.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.BatchModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.annotations.VisibleForTesting; - -import java.io.IOException; - -import javax.annotation.Nullable; - -/** - * A source that reads from a shuffled dataset and yields key-grouped - * data. Like {@link GroupingShuffleReader}, except that it injects - * an error in the counter tracking how many bytes are read. This - * class is solely used to test the shuffle sanity check mechanism. - * - * @param the type of the keys read from the shuffle - * @param the type of the values read from the shuffle - */ -@VisibleForTesting -class GroupingShuffleReaderWithFaultyBytesReadCounter extends GroupingShuffleReader { - public GroupingShuffleReaderWithFaultyBytesReadCounter( - PipelineOptions options, - byte[] shuffleReaderConfig, - @Nullable String startShufflePosition, - @Nullable String stopShufflePosition, - Coder>>> coder, - BatchModeExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - String operationName, - boolean sortValues) - throws Exception { - super(options, shuffleReaderConfig, startShufflePosition, stopShufflePosition, coder, - executionContext, addCounterMutator, operationName, sortValues); - } - - @Override - public GroupingShuffleReaderIterator iterator() throws IOException { - // This causes perOperationPerDatasetBytesCounter to be initialized. - GroupingShuffleReaderIterator it = super.iterator(); - - // Inject an error in the counter tracking how many bytes are read - // from this reader's data source. - perOperationPerDatasetBytesCounter.addValue(1L); - return it; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java deleted file mode 100644 index a74db55fb5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderRegistry.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.collect.Maps; - -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * An immutable registry from {@link String} identifiers (provided to the worker by the Dataflow - * service) to appropriate {@link ReaderFactory} instances. - */ -public class ReaderRegistry implements ReaderFactory { - - /** - * A {@link ReaderRegistry} with each {@link ReaderFactory} known to the Dataflow worker already - * registered. - */ - public static ReaderRegistry defaultRegistry() { - Map factories = Maps.newHashMap(); - - factories.put("TextSource", TextReaderFactory.getInstance()); - factories.put("AvroSource", new AvroReaderFactory()); - factories.put("BigQueryAvroSource", new BigQueryAvroReaderFactory()); - factories.put("UngroupedShuffleSource", new UngroupedShuffleReaderFactory()); - factories.put("PartitioningShuffleSource", new PartitioningShuffleReaderFactory()); - factories.put("GroupingShuffleSource", new GroupingShuffleReaderFactory()); - factories.put("InMemorySource", new InMemoryReaderFactory()); - factories.put("BigQuerySource", new BigQueryReaderFactory()); - - // Aliases for WindowingWindmillreader - factories.put("WindowingWindmillReader", new WindowingWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.WindowingWindmillReader", - new WindowingWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.BucketingWindmillSource", - new WindowingWindmillReader.Factory()); - - // Aliases for UngroupedWindmillReader - factories.put("UngroupedWindmillReader", new UngroupedWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.UngroupedWindmillSource", - new UngroupedWindmillReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.UngroupedWindmillReader", - new UngroupedWindmillReader.Factory()); - - // Aliases for PubsubReader - factories.put("PubsubReader", new PubsubReader.Factory()); - factories.put("com.google.cloud.dataflow.sdk.runners.worker.PubsubSource", - new PubsubReader.Factory()); - - // Custom sources - factories.put( - "com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources", - new WorkerCustomSources.Factory()); - factories.put( - "com.google.cloud.dataflow.sdk.runners.dataflow.WorkerCustomSources", - new WorkerCustomSources.Factory()); - - return new ReaderRegistry(factories); - } - - /** - * Builds a new {@link ReaderRegistry} with the provided mutable map of initial mappings. - * - *

      Owns and mutates the provided map, which must be mutable. This constructor should only be - * called by methods in this class that are aware of this requirement and abstract from this - * behavior. - */ - private ReaderRegistry(Map factories) { - // ConcatReader requires special treatment: Recursive access to the registry since it calls - // back to create its sub-readers lazily. - this.factories = factories; - this.factories.put(ConcatReader.SOURCE_NAME, ConcatReaderFactory.withRegistry(this)); - } - - /** - * A map from the short names of predefined sources to the associated {@link ReaderFactory}. - */ - private final Map factories; - - /** - * Returns a new {@link ReaderRegistry} with the provided identifier associated with the - * provided {@link ReaderFactory}, overriding any existing binding for that identifier. - */ - public ReaderRegistry register(String readerSpecType, ReaderFactory factory) { - Map newFactories = Maps.newHashMap(); - newFactories.putAll(factories); - newFactories.put(readerSpecType, factory); - return new ReaderRegistry(newFactories); - } - - /** - * Creates a {@link NativeReader} according to the provided {@code sourceSpec}, - * by dispatching on the type of {@link CloudObject} to instantiate. - */ - @Override - public NativeReader create( - CloudObject sourceSpec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - - String objClassName = sourceSpec.getClassName(); - ReaderFactory readerFactory = factories.get(objClassName); - if (readerFactory == null) { - throw new IllegalArgumentException(String.format( - "Unable to create a Reader: Unknown Reader type in Source specification: %s", - objClassName)); - } - return readerFactory.create( - sourceSpec, coder, options, executionContext, addCounterMutator, operationName); - } - - /** - * Creates a {@link NativeReader} from a Dataflow API {@link Source} specification, using the - * {@link Coder} contained in the {@link Source} specification. - */ - public NativeReader create( - Source cloudSource, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - - cloudSource = CloudSourceUtils.flattenBaseSpecs(cloudSource); - CloudObject sourceSpec = CloudObject.fromSpec(cloudSource.getSpec()); - Coder coder = null; - if (cloudSource.getCodec() != null) { - coder = Serializer.deserialize(cloudSource.getCodec(), Coder.class); - } - return create(sourceSpec, coder, options, executionContext, addCounterMutator, operationName); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java deleted file mode 100644 index 29980bd015..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchModeExecutionContext.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.worker.DataflowExecutionContext; -import com.google.cloud.dataflow.sdk.runners.worker.DataflowSideInputReader; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderFactory; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderRegistry; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.util.Objects; - -/** - * {@link ExecutionContext} for use in batch mode. - */ -public class BatchModeExecutionContext - extends DataflowExecutionContext { - private Object key; - - private final PipelineOptions options; - private final ReaderFactory readerFactory; - - protected BatchModeExecutionContext(PipelineOptions options, ReaderFactory readerFactory) { - this.options = options; - this.readerFactory = readerFactory; - } - - /** - * Returns a {@link BatchModeExecutionContext} configured according to default - * pipeline options. - */ - public static BatchModeExecutionContext withDefaultOptions() { - return new BatchModeExecutionContext( - PipelineOptionsFactory.create(), - ReaderRegistry.defaultRegistry()); - } - - /** - * Returns a {@link BatchModeExecutionContext} configured according to the provided options. - */ - public static BatchModeExecutionContext fromOptions(PipelineOptions options) { - return new BatchModeExecutionContext(options, ReaderRegistry.defaultRegistry()); - } - - /** - * Create a new {@link ExecutionContext.StepContext}. - */ - @Override - protected StepContext createStepContext( - String stepName, String transformName, StateSampler stateSampler) { - return new StepContext(stepName, transformName); - } - - /** - * Sets the key of the work currently being processed. - */ - public void setKey(Object key) { - if (!Objects.equals(key, this.key)) { - switchStateKey(key); - } - - this.key = key; - } - - /** - * @param newKey the key being switched to - */ - protected void switchStateKey(Object newKey) { - // When the key changes, we clear out the in-memory state stored in the step contexts. - // In BatchMode a specific key is only processed in a single chunk - // because the state is either used after a GroupByKeyOnly where - // each key only occurs once, or after some ParDo's that preserved - // the key. - for (ExecutionContext.StepContext stepContext : getAllStepContexts()) { - InMemoryStateInternals stateInternals = - (InMemoryStateInternals) stepContext.stateInternals(); - stateInternals.clear(); - } - } - - /** - * Returns the key of the work currently being processed. - * - *

      If there is not a currently defined key, returns null. - */ - public Object getKey() { - return key; - } - - @Override - protected SideInputReader getSideInputReader( - Iterable sideInputInfos) throws Exception { - return DataflowSideInputReader.of( - sideInputInfos, readerFactory, options, this); - } - - @Override - protected SideInputReader getSideInputReaderForViews( - Iterable> views) throws Exception { - throw new UnsupportedOperationException( - "BatchModeExecutionContext.withoutSideInputs().getSideInputReaderForViews(...)"); - } - - - /** - * {@link ExecutionContext.StepContext} used in batch mode. - */ - public class StepContext extends BaseExecutionContext.StepContext { - - private final InMemoryStateInternals stateInternals = new InMemoryStateInternals(); - - private StepContext(String stepName, String transformName) { - super(BatchModeExecutionContext.this, stepName, transformName); - } - - @Override - public StateInternals stateInternals() { - return stateInternals; - } - - @Override - public TimerInternals timerInternals() { - throw new UnsupportedOperationException("Batch mode cannot return timerInternals"); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java index 616fbe1b39..af3055521f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java @@ -17,13 +17,9 @@ package com.google.cloud.dataflow.sdk.util; import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderRegistry; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; import java.util.HashMap; -import java.util.List; import java.util.Map; /** @@ -52,21 +48,4 @@ public static Source flattenBaseSpecs(Source source) { result.setBaseSpecs(null); return result; } - - /** - * Creates a {@link NativeReader} from the given Dataflow Source API definition and - * reads all elements from it. - */ - - public static List readElemsFromSource(PipelineOptions options, Source source) { - try { - @SuppressWarnings("unchecked") - NativeReader reader = - (NativeReader) - ReaderRegistry.defaultRegistry().create(source, options, null, null, null); - return ReaderUtils.readAllFromReader(reader); - } catch (Exception e) { - throw new RuntimeException("Failed to read from source: " + source.toString(), e); - } - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java index fe350aad60..e09251b6a9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java @@ -16,24 +16,14 @@ package com.google.cloud.dataflow.sdk.runners.dataflow; import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; -import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; -import static com.google.cloud.dataflow.sdk.util.Structs.getObject; -import static com.google.common.base.Throwables.getStackTraceAsString; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.Source; -import com.google.api.services.dataflow.model.Step; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -42,8 +32,6 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipeline; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -52,11 +40,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CloudSourceUtils; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.Preconditions; @@ -70,10 +53,7 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; /** * Tests for {@link CustomSources}. @@ -290,164 +270,4 @@ public void testRangeProgressAndSplitAtFraction() throws Exception { assertFalse(reader.advance()); } } - - /** - * A source that cannot do anything. Intended to be overridden for testing of individual methods. - */ - private static class MockSource extends BoundedSource { - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - return Arrays.asList(this); - } - - @Override - public void validate() { } - - @Override - public boolean producesSortedKeys(PipelineOptions options) { - return false; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) { - throw new UnsupportedOperationException(); - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() { - return ""; - } - - @Override - public Coder getDefaultOutputCoder() { - return BigEndianIntegerCoder.of(); - } - } - - private static class FailingReader extends BoundedSource.BoundedReader { - private BoundedSource source; - - private FailingReader(BoundedSource source) { - this.source = source; - } - - @Override - public BoundedSource getCurrentSource() { - return source; - } - - @Override - public boolean start() throws IOException { - throw new IOException("Intentional error"); - } - - @Override - public boolean advance() throws IOException { - throw new IllegalStateException("Should have failed in start()"); - } - - @Override - public Integer getCurrent() throws NoSuchElementException { - throw new IllegalStateException("Should have failed in start()"); - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - throw new IllegalStateException("Should have failed in start()"); - } - - @Override - public void close() throws IOException {} - - @Override - public Double getFractionConsumed() { - return null; - } - - @Override - public BoundedSource splitAtFraction(double fraction) { - return null; - } - } - - private static class SourceProducingFailingReader extends MockSource { - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return new FailingReader(this); - } - - @Override - public String toString() { - return "Some description"; - } - } - - @Test - public void testFailureToStartReadingIncludesSourceDetails() throws Exception { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - Source source = translateIOToCloudSource(new SourceProducingFailingReader(), options); - // Unfortunately Hamcrest doesn't have a matcher that can match on the exception's - // printStackTrace(), however we just want to verify that the error and source description - // would be contained in the exception *somewhere*, not necessarily in the top-level - // Exception object. So instead we use Throwables.getStackTraceAsString and match on that. - try { - CloudSourceUtils.readElemsFromSource(options, source); - fail("Expected to fail"); - } catch (Exception e) { - assertThat( - getStackTraceAsString(e), - allOf(containsString("Intentional error"), containsString("Some description"))); - } - } - - private static Source translateIOToCloudSource( - BoundedSource io, DataflowPipelineOptions options) throws Exception { - options.setProject("test-project"); - options.setTempLocation("gs://test-tmp"); - options.setPathValidatorClass(NoopPathValidator.class); - options.setGcpCredential(new TestCredential()); - - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - DataflowPipeline p = DataflowPipeline.create(options); - p.begin().apply(Read.from(io)); - - Job workflow = translator.translate( - p, p.getRunner(), new ArrayList()).getJob(); - Step step = workflow.getSteps().get(0); - - return stepToCloudSource(step); - } - - private static Source stepToCloudSource(Step step) - throws Exception { - Source res = dictionaryToCloudSource( - getDictionary(step.getProperties(), PropertyNames.SOURCE_STEP_INPUT)); - // Encoding is specified in the step, not in the source itself. This is - // normal: incoming Dataflow API Source objects in map tasks will have the - // encoding filled in from the step's output encoding. - @SuppressWarnings("unchecked") - List> outputInfo = - (List>) step.getProperties().get(PropertyNames.OUTPUT_INFO); - - CloudObject encoding = CloudObject.fromSpec(getObject(outputInfo.get(0), - PropertyNames.ENCODING)); - res.setCodec(encoding); - return res; - } - - // Duplicated from runners.worker.SourceTranslationUtils to break dependency on worker - private static Source dictionaryToCloudSource(Map params) throws Exception { - Source res = new Source(); - res.setSpec(getDictionary(params, PropertyNames.SOURCE_SPEC)); - // SOURCE_METADATA and SOURCE_DOES_NOT_NEED_SPLITTING do not have to be - // translated, because they only make sense in cloud Source objects produced by the user. - return res; - } } From 64eefa348fae6816e80c2d6033cceea051c3a4fd Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 5 Feb 2016 19:54:18 -0800 Subject: [PATCH 092/751] Handle SynchronizedProcessingTime in InMemoryWatermarkManager Bundles carry their time-of-commit Synchronized processing time. Split Bundle into a pre/post commit dichotomy, in order to enforce either write-only (from the producer perspective) and read-only (from the consumer perspective). Processing Time Timers will be implemented primarily on top of the new SynchronizedProcessingTime watermarks. This will be alongside implementation of ProcessingTime-based Synchronized Processing Time holds. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114007176 --- .../util/InMemoryWatermarkManager.java | 261 ++++++++++++++---- .../util/InMemoryWatermarkManagerTest.java | 206 ++++++++++++-- 2 files changed, 392 insertions(+), 75 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java index 417b33b3c5..96a8f5bdb3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java @@ -33,6 +33,7 @@ import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -147,6 +148,19 @@ public boolean isAdvanced() { return advanced; } + /** + * Returns the {@link WatermarkUpdate} that is a result of combining the two watermark updates. + * + * If either of the input {@link WatermarkUpdate WatermarkUpdates} were advanced, the result + * {@link WatermarkUpdate} has been advanced. + */ + public WatermarkUpdate union(WatermarkUpdate that) { + if (this.advanced) { + return this; + } + return that; + } + /** * Returns the {@link WatermarkUpdate} based on the former and current * {@link Instant timestamps}. @@ -302,22 +316,119 @@ public String toString() { } } - /** - * A {@code Watermark} that is after the latest time it is possible to represent in the global - * window. This is a distinguished value representing a complete {@link PTransform}. - */ - private static final Watermark THE_END_OF_TIME = new Watermark() { + private static class SynchronizedProcessingTimeInputWatermark implements Watermark { + private final Collection inputWms; + private final Collection> pendingBundles; + + private AtomicReference earliestHold; + + public SynchronizedProcessingTimeInputWatermark(Collection inputWms) { + this.inputWms = inputWms; + this.pendingBundles = new HashSet<>(); + Instant initialHold = BoundedWindow.TIMESTAMP_MAX_VALUE; + for (Watermark wm : inputWms) { + initialHold = INSTANT_ORDERING.min(initialHold, wm.get()); + } + earliestHold = new AtomicReference<>(initialHold); + } + + @Override + public Instant get() { + return earliestHold.get(); + } + + @Override + public synchronized WatermarkUpdate refresh() { + Instant oldHold = earliestHold.get(); + Instant minTime = THE_END_OF_TIME.get(); + for (Watermark input : inputWms) { + minTime = INSTANT_ORDERING.min(minTime, input.get()); + } + for (CommittedBundle bundle : pendingBundles) { + // TODO: Track elements in the bundle by the processing time they were output instead of + // entire bundles. Requried to support arbitrarily splitting and merging bundles between + // steps + minTime = INSTANT_ORDERING.min(minTime, bundle.getSynchronizedProcessingOutputWatermark()); + } + earliestHold.set(minTime); + return WatermarkUpdate.fromTimestamps(oldHold, minTime); + } + + public synchronized void addPending(CommittedBundle bundle) { + pendingBundles.add(bundle); + } + + public synchronized void removePending(CommittedBundle bundle) { + pendingBundles.remove(bundle); + } + + public synchronized Instant getEarliestTimerTimestamp() { + // TODO: use unfired and pending timers to determine earliest timestamp. Requires supporting + // timers. + Instant earliest = THE_END_OF_TIME.get(); + return earliest; + } + @Override - public WatermarkUpdate refresh() { - // THE_END_OF_TIME is a distinguished value that cannot be advanced. - return WatermarkUpdate.NO_CHANGE; + public String toString() { + return MoreObjects.toStringHelper(SynchronizedProcessingTimeInputWatermark.class) + .add("earliestHold", earliestHold) + .toString(); + } + } + + private static class SynchronizedProcessingTimeOutputWatermark implements Watermark { + private final SynchronizedProcessingTimeInputWatermark inputWm; + private AtomicReference latestRefresh; + + public SynchronizedProcessingTimeOutputWatermark( + SynchronizedProcessingTimeInputWatermark inputWm) { + this.inputWm = inputWm; + this.latestRefresh = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); } @Override public Instant get() { - return BoundedWindow.TIMESTAMP_MAX_VALUE; + return latestRefresh.get(); + } + + @Override + public synchronized WatermarkUpdate refresh() { + // Hold the output synchronized processing time to the input watermark, which takes into + // account buffered bundles, and the earliest pending timer, which determines what to hold + // downstream timers to. + Instant oldRefresh = latestRefresh.get(); + Instant newTimestamp = + INSTANT_ORDERING.min(inputWm.get(), inputWm.getEarliestTimerTimestamp()); + latestRefresh.set(newTimestamp); + return WatermarkUpdate.fromTimestamps(oldRefresh, newTimestamp); } - }; + + @Override + public String toString() { + return MoreObjects.toStringHelper(SynchronizedProcessingTimeOutputWatermark.class) + .add("latestRefresh", latestRefresh) + .toString(); + } + } + + /** + * The {@code Watermark} that is after the latest time it is possible to represent in the global + * window. This is a distinguished value representing a complete {@link PTransform}. + */ + private static final Watermark THE_END_OF_TIME = + new Watermark() { + @Override + public WatermarkUpdate refresh() { + // THE_END_OF_TIME is a distinguished value that cannot be advanced. + return WatermarkUpdate.NO_CHANGE; + } + + @Override + public Instant get() { + return BoundedWindow.TIMESTAMP_MAX_VALUE; + } + }; private static final Ordering INSTANT_ORDERING = Ordering.natural(); @@ -380,12 +491,36 @@ private TransformWatermarks getTransformWatermark(AppliedPTransform tra new AppliedPTransformInputWatermark(inputCollectionWatermarks); AppliedPTransformOutputWatermark outputWatermark = new AppliedPTransformOutputWatermark(inputWatermark); - wms = new TransformWatermarks(inputWatermark, outputWatermark); + + SynchronizedProcessingTimeInputWatermark inputProcessingWatermark = + new SynchronizedProcessingTimeInputWatermark(getInputProcessingWatermarks(transform)); + SynchronizedProcessingTimeOutputWatermark outputProcessingWatermark = + new SynchronizedProcessingTimeOutputWatermark(inputProcessingWatermark); + + wms = + new TransformWatermarks( + inputWatermark, outputWatermark, inputProcessingWatermark, outputProcessingWatermark); transformToWatermarks.put(transform, wms); } return wms; } + private Collection getInputProcessingWatermarks( + AppliedPTransform transform) { + ImmutableList.Builder inputWmsBuilder = ImmutableList.builder(); + Collection inputs = transform.getInput().expand(); + if (inputs.isEmpty()) { + inputWmsBuilder.add(THE_END_OF_TIME); + } + for (PValue pvalue : inputs) { + Watermark producerOutputWatermark = + getTransformWatermark(pvalue.getProducingTransformInternal()) + .synchronizedProcessingOutputWatermark; + inputWmsBuilder.add(producerOutputWatermark); + } + return inputWmsBuilder.build(); + } + private List getInputWatermarks(AppliedPTransform transform) { ImmutableList.Builder inputWatermarksBuilder = ImmutableList.builder(); Collection inputs = transform.getInput().expand(); @@ -394,7 +529,7 @@ private List getInputWatermarks(AppliedPTransform transform) } for (PValue pvalue : inputs) { Watermark producerOutputWatermark = - getTransformWatermark(pvalue.getProducingTransformInternal()).outputWatermark(); + getTransformWatermark(pvalue.getProducingTransformInternal()).outputWatermark; inputWatermarksBuilder.add(producerOutputWatermark); } List inputCollectionWatermarks = inputWatermarksBuilder.build(); @@ -408,7 +543,7 @@ private List getInputWatermarks(AppliedPTransform transform) * * @return a snapshot of the input watermark and output watermark for the provided transform */ - public synchronized TransformWatermarks getWatermarks(AppliedPTransform transform) { + public TransformWatermarks getWatermarks(AppliedPTransform transform) { return transformToWatermarks.get(transform); } @@ -418,23 +553,24 @@ public synchronized TransformWatermarks getWatermarks(AppliedPTransform *

      The output watermark of a transform that takes no input is determined by that transform, as * there are no input {@link PCollection PCollections}. * - * @param watermark the output watermark of the transform. If the transform has buffered input - * elements, the watermark should be the minimum of all buffered elements. - * @return both watermarks of the source transform + * @param eventTimeWatermark the output watermark of the transform. If the transform has buffered + * input elements, the watermark should be the minimum of all buffered + * elements. */ - public TransformWatermarks updateOutputWatermark(AppliedPTransform transform, - Iterable> outputs, Instant watermark) { + public void updateOutputWatermark( + AppliedPTransform transform, + Iterable> outputs, + Instant eventTimeWatermark) { TransformWatermarks watermarks = getWatermarks(transform); - watermarks.outputWatermark().setHold(watermark); + watermarks.setEventTimeHold(eventTimeWatermark); for (CommittedBundle output : outputs) { PCollection pCollection = output.getPCollection(); for (AppliedPTransform consumer : consumers.get(pCollection)) { - addPending(consumer, output.getElements()); + addPending(consumer, output); } } refreshWatermarks(transform); - return watermarks; } /** @@ -455,16 +591,16 @@ public TransformWatermarks updateOutputWatermark(AppliedPTransform tran * @param outputs the bundles the transform has output * @param earliestHold the earliest watermark hold in the transform's state. {@code null} if there * is no hold - * @return the updated watermark of the transform */ - public TransformWatermarks updateWatermarks(CommittedBundle completed, - AppliedPTransform transform, Collection> outputs, + public void updateWatermarks( + CommittedBundle completed, + AppliedPTransform transform, + Iterable> outputs, @Nullable Instant earliestHold) { updatePending(completed, transform, outputs); TransformWatermarks transformWms = transformToWatermarks.get(transform); - transformWms.outputWatermark().setHold(earliestHold); + transformWms.setEventTimeHold(earliestHold); refreshWatermarks(transform); - return transformWms; } private void refreshWatermarks(AppliedPTransform transform) { @@ -475,7 +611,7 @@ private void refreshWatermarks(AppliedPTransform transform) { Collection> downstreamTransforms = consumers.get(outputPValue); if (downstreamTransforms != null) { for (AppliedPTransform downstreamTransform : downstreamTransforms) { - refreshWatermarks(downstreamTransform); + refreshWatermarks(downstreamTransform); } } } @@ -483,19 +619,21 @@ private void refreshWatermarks(AppliedPTransform transform) { } /** - * Removes all elements consumed by the input bundle from the {@link PTransform PTransforms} - * collection of pending elements, and adds all elements produced by the {@link PTransform} to the - * pending queue of each consumer. + * Removes all of the completed Timers from the collection of pending timers, adds all new timers, + * and removes all deleted timers. Removes all elements consumed by the input bundle from the + * {@link PTransform PTransforms} collection of pending elements, and adds all elements produced + * by the {@link PTransform} to the pending queue of each consumer. */ - private void updatePending(CommittedBundle input, AppliedPTransform transform, - Collection> outputs) { - AppliedPTransformInputWatermark inputWatermark = - transformToWatermarks.get(transform).inputWatermark(); - inputWatermark.removePending(input.getElements()); + private void updatePending( + CommittedBundle input, + AppliedPTransform transform, + Iterable> outputs) { + TransformWatermarks completedTransform = transformToWatermarks.get(transform); + completedTransform.removePending(input); for (CommittedBundle bundle : outputs) { for (AppliedPTransform consumer : consumers.get(bundle.getPCollection())) { - addPending(consumer, bundle.getElements()); + addPending(consumer, bundle); } } } @@ -505,9 +643,9 @@ private void updatePending(CommittedBundle input, AppliedPTransform * elements for the provided {@link AppliedPTransform}. */ private void addPending( - AppliedPTransform transform, Iterable> pending) { + AppliedPTransform transform, CommittedBundle pending) { TransformWatermarks watermarks = transformToWatermarks.get(transform); - watermarks.inputWatermark().addPending(pending); + watermarks.addPending(pending); } /** @@ -517,11 +655,33 @@ public class TransformWatermarks { private final AppliedPTransformInputWatermark inputWatermark; private final AppliedPTransformOutputWatermark outputWatermark; + private final SynchronizedProcessingTimeInputWatermark synchronizedProcessingInputWatermark; + private final SynchronizedProcessingTimeOutputWatermark synchronizedProcessingOutputWatermark; + private TransformWatermarks( AppliedPTransformInputWatermark inputWatermark, - AppliedPTransformOutputWatermark outputWatermark) { + AppliedPTransformOutputWatermark outputWatermark, + SynchronizedProcessingTimeInputWatermark sychronizedProcessingWatermark, + SynchronizedProcessingTimeOutputWatermark outputProcessingWatermark) { this.inputWatermark = inputWatermark; this.outputWatermark = outputWatermark; + + this.synchronizedProcessingInputWatermark = sychronizedProcessingWatermark; + this.synchronizedProcessingOutputWatermark = outputProcessingWatermark; + } + + private void setEventTimeHold(Instant hold) { + outputWatermark.setHold(hold); + } + + private void removePending(CommittedBundle bundle) { + inputWatermark.removePending(bundle.getElements()); + synchronizedProcessingInputWatermark.removePending(bundle); + } + + private void addPending(CommittedBundle bundle) { + inputWatermark.addPending(bundle.getElements()); + synchronizedProcessingInputWatermark.addPending(bundle); } /** @@ -531,6 +691,14 @@ public Instant getInputWatermark() { return inputWatermark.get(); } + public Instant getSynchronizedProcessingInputTime() { + return INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingInputWatermark.get()); + } + + public Instant getSynchronizedProcessingOutputTime() { + return INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingOutputWatermark.get()); + } + /** * Returns the output watermark of the {@link AppliedPTransform}. */ @@ -538,17 +706,12 @@ public Instant getOutputWatermark() { return outputWatermark.get(); } - AppliedPTransformInputWatermark inputWatermark() { - return inputWatermark; - } - - AppliedPTransformOutputWatermark outputWatermark() { - return outputWatermark; - } - private WatermarkUpdate refresh() { inputWatermark.refresh(); - return outputWatermark.refresh(); + synchronizedProcessingInputWatermark.refresh(); + WatermarkUpdate eventOutputUpdate = outputWatermark.refresh(); + WatermarkUpdate syncOutputUpdate = synchronizedProcessingOutputWatermark.refresh(); + return eventOutputUpdate.union(syncOutputUpdate); } @Override @@ -556,6 +719,8 @@ public String toString() { return MoreObjects.toStringHelper(TransformWatermarks.class) .add("inputWatermark", inputWatermark) .add("outputWatermark", outputWatermark) + .add("inputProcessingTime", synchronizedProcessingInputWatermark) + .add("outputProcessingTime", synchronizedProcessingOutputWatermark) .toString(); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java index d32fa6b869..2186718169 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java @@ -39,8 +39,10 @@ import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; +import org.joda.time.DateTimeUtils; import org.joda.time.Instant; import org.joda.time.ReadableInstant; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,6 +59,8 @@ */ @RunWith(JUnit4.class) public class InMemoryWatermarkManagerTest implements Serializable { + private static final Instant INITIAL_PROCESSING_TIME = new Instant(1000L); + private PCollection createdInts; private PCollection filtered; @@ -69,6 +73,8 @@ public class InMemoryWatermarkManagerTest implements Serializable { @Before public void setup() { + DateTimeUtils.setCurrentMillisFixed(INITIAL_PROCESSING_TIME.getMillis()); + TestPipeline p = TestPipeline.create(); createdInts = p.apply("createdInts", Create.of(1, 2, 3)); @@ -102,6 +108,10 @@ public void setup() { manager = InMemoryWatermarkManager.create(rootTransforms, consumers); } + @After + public void tearDown() { + DateTimeUtils.setCurrentMillisSystem(); + } /** * Demonstrates that getWatermark, when called on an {@link AppliedPTransform} that has not @@ -124,9 +134,12 @@ public void getWatermarkForUntouchedTransform() { public void getWatermarkForUpdatedSourceTransform() { CommittedBundle output = globallyWindowedBundle(createdInts, 1); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(output), new Instant(8000L)); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(output), new Instant(8000L)); TransformWatermarks updatedSourceWatermark = - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(output), new Instant(8000L)); + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(updatedSourceWatermark.getOutputWatermark(), equalTo(new Instant(8000L))); } @@ -170,9 +183,12 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle flattenedBundleSecondCreate = globallyWindowedBundle(flattened, -1); // We have finished processing the bundle from the second PCollection, but we haven't consumed // anything from the first PCollection yet; so our watermark shouldn't advance + manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), + Collections.>singleton(flattenedBundleSecondCreate), null); TransformWatermarks transformAfterProcessing = - manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(flattenedBundleSecondCreate), null); + manager.getWatermarks(flattened.getProducingTransformInternal()); + manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), + Collections.>singleton(flattenedBundleSecondCreate), null); assertThat( transformAfterProcessing.getInputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); @@ -185,10 +201,12 @@ public void getWatermarkForMultiInputTransform() { timestampedBundle(createdInts, TimestampedValue.of(5, firstCollectionTimestamp)); // the source is done, but elements are still buffered. The source output watermark should be // past the end of the global window - TransformWatermarks firstSourceWatermarks = manager.updateOutputWatermark( + manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), Collections.>singleton(firstPcollectionBundle), new Instant(Long.MAX_VALUE)); + TransformWatermarks firstSourceWatermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( firstSourceWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); @@ -212,9 +230,12 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle completedFlattenBundle = InProcessBundle.unkeyed(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), + Collections.>singleton(completedFlattenBundle), null); + manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), + Collections.>singleton(completedFlattenBundle), null); TransformWatermarks afterConsumingAllInput = - manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(completedFlattenBundle), null); + manager.getWatermarks(flattened.getProducingTransformInternal()); assertThat( afterConsumingAllInput.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); @@ -232,9 +253,10 @@ public void getWatermarkForMultiConsumedCollection() { CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), TimestampedValue.of(3, new Instant(-1000L))); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); TransformWatermarks createdAfterProducing = - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( createdAfterProducing.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); @@ -243,9 +265,10 @@ public void getWatermarkForMultiConsumedCollection() { timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), null); TransformWatermarks keyedWatermarks = - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), null); + manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat( @@ -258,9 +281,10 @@ public void getWatermarkForMultiConsumedCollection() { CommittedBundle filteredBundle = timestampedBundle(filtered, TimestampedValue.of(2, new Instant(1234L))); + manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), + Collections.>singleton(filteredBundle), null); TransformWatermarks filteredProcessedWatermarks = - manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), - Collections.>singleton(filteredBundle), null); + manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat( filteredProcessedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); @@ -285,9 +309,10 @@ public void updateWatermarkWithWatermarkHolds() { timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), new Instant(500L)); TransformWatermarks keyedWatermarks = - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), new Instant(500L)); + manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); @@ -301,16 +326,18 @@ public void updateWatermarkWithWatermarkHolds() { public void updateOutputWatermarkShouldBeMonotonic() { CommittedBundle firstInput = InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - TransformWatermarks firstWatermarks = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), Collections.>singleton(firstInput), new Instant(0L)); +TransformWatermarks firstWatermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); CommittedBundle secondInput = InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - TransformWatermarks secondWatermarks = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), Collections.>singleton(secondInput), new Instant(-250L)); +TransformWatermarks secondWatermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); } @@ -330,9 +357,12 @@ public void updateWatermarkWithHoldsShouldBeMonotonic() { timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), new Instant(500L)); + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), new Instant(500L)); TransformWatermarks keyedWatermarks = - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), new Instant(500L)); + manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); @@ -364,20 +394,22 @@ public void updateWatermarkWithLateData() { TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); // Finish processing the on-time data. The watermarks should progress to be equal to the source + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle), null); + TransformWatermarks onTimeWatermarks = - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), null); + manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); assertThat(onTimeWatermarks.getOutputWatermark(), equalTo(sourceWatermark)); CommittedBundle lateDataBundle = timestampedBundle(createdInts, TimestampedValue.of(3, new Instant(-1000L))); - // the late data arrives in a downstream PCollection after its watermark has advanced past it; // we don't advance the watermark past the current watermark until we've consumed the late data - TransformWatermarks bufferedLateWm = manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), Collections.>singleton(lateDataBundle), new Instant(2_000_000L)); + TransformWatermarks bufferedLateWm = + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); // The input watermark should be held to its previous value (not advanced due to late data; not @@ -400,10 +432,12 @@ public void updateWatermarkWithLateData() { @Test public void getWatermarksAfterOnlyEmptyOutput() { CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); - TransformWatermarks updatedSourceWatermarks = manager.updateOutputWatermark( + manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + TransformWatermarks updatedSourceWatermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( updatedSourceWatermarks.getOutputWatermark(), @@ -430,17 +464,20 @@ public void getWatermarksAfterHoldAndEmptyOutput() { Collections.>singleton(firstCreateOutput), new Instant(12_000L)); CommittedBundle firstFilterOutput = globallyWindowedBundle(filtered); + manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), + Collections.>singleton(firstFilterOutput), new Instant(10_000L)); TransformWatermarks firstFilterWatermarks = - manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), - Collections.>singleton(firstFilterOutput), new Instant(10_000L)); + manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat(firstFilterWatermarks.getInputWatermark(), not(earlierThan(new Instant(12_000L)))); assertThat(firstFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); - TransformWatermarks updatedSourceWatermarks = manager.updateOutputWatermark( + manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + TransformWatermarks updatedSourceWatermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( updatedSourceWatermarks.getOutputWatermark(), @@ -454,6 +491,121 @@ public void getWatermarksAfterHoldAndEmptyOutput() { assertThat(finishedFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); } + @Test + public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { + TransformWatermarks watermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); + assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(INITIAL_PROCESSING_TIME)); + assertThat( + watermarks.getSynchronizedProcessingOutputTime(), + equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + + TransformWatermarks filteredWatermarks = + manager.getWatermarks(filtered.getProducingTransformInternal()); + // Non-root processing watermarks don't progress until data has been processed + assertThat( + filteredWatermarks.getSynchronizedProcessingInputTime(), + not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + assertThat( + filteredWatermarks.getSynchronizedProcessingOutputTime(), + not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + + CommittedBundle createOutput = + InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); + + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + TransformWatermarks createAfterUpdate = + manager.getWatermarks(createdInts.getProducingTransformInternal()); + assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); + assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + + TransformWatermarks filterAfterProduced = + manager.getWatermarks(filtered.getProducingTransformInternal()); + assertThat( + filterAfterProduced.getSynchronizedProcessingInputTime(), not(laterThan(Instant.now()))); + assertThat( + filterAfterProduced.getSynchronizedProcessingOutputTime(), not(laterThan(Instant.now()))); + + DateTimeUtils.setCurrentMillisFixed(1500L); + assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); + assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + assertThat( + filterAfterProduced.getSynchronizedProcessingInputTime(), + not(laterThan(new Instant(1250L)))); + assertThat( + filterAfterProduced.getSynchronizedProcessingOutputTime(), + not(laterThan(new Instant(1250L)))); + + CommittedBundle filterOutputBundle = + InProcessBundle.unkeyed(intsToFlatten).commit(new Instant(1250L)); + manager.updateWatermarks(createOutput, filtered.getProducingTransformInternal(), + Collections.>singleton(filterOutputBundle), + BoundedWindow.TIMESTAMP_MAX_VALUE); + TransformWatermarks filterAfterConsumed = + manager.getWatermarks(filtered.getProducingTransformInternal()); + assertThat( + filterAfterConsumed.getSynchronizedProcessingInputTime(), + not(laterThan(createAfterUpdate.getSynchronizedProcessingOutputTime()))); + assertThat( + filterAfterConsumed.getSynchronizedProcessingOutputTime(), + not(laterThan(filterAfterConsumed.getSynchronizedProcessingInputTime()))); + } + + /** + * Demonstrates that the Synchronized Processing Time output watermark cannot progress past + * pending timers in the same set. This propagates to all downstream SynchronizedProcessingTimes. + */ + @Test + public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { + // TODO: Support Timers; add test + } + + /** + * Demonstrates that if any earlier processing holds appear in the synchronized processing time + * output hold the result is monotonic. + */ + @Test + public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { + TransformWatermarks watermarks = + manager.getWatermarks(createdInts.getProducingTransformInternal()); + assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(INITIAL_PROCESSING_TIME)); + + TransformWatermarks filteredWatermarks = + manager.getWatermarks(filtered.getProducingTransformInternal()); + // Non-root processing watermarks don't progress until data has been processed + assertThat( + filteredWatermarks.getSynchronizedProcessingInputTime(), + not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + assertThat( + filteredWatermarks.getSynchronizedProcessingOutputTime(), + not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); + + CommittedBundle createOutput = + InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); + + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), + Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + TransformWatermarks createAfterUpdate = + manager.getWatermarks(createdInts.getProducingTransformInternal()); + assertThat( + createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(Instant.now()))); + assertThat( + createAfterUpdate.getSynchronizedProcessingOutputTime(), not(laterThan(Instant.now()))); + + CommittedBundle createSecondOutput = + InProcessBundle.unkeyed(createdInts).commit(new Instant(750L)); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + Collections.>singleton(createSecondOutput), + BoundedWindow.TIMESTAMP_MAX_VALUE); + + assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + } + + @Test + public void getSynchronizedProcessingTimeInputIsHeldToEarliestUpstream() {} + private static Matcher earlierThan(final Instant laterInstant) { return new BaseMatcher() { @Override From 1452daa2be31638b59100cbf5431a326a4097906 Mon Sep 17 00:00:00 2001 From: klk Date: Sat, 6 Feb 2016 11:36:58 -0800 Subject: [PATCH 093/751] Move streaming worker code into worker module ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114030419 --- .../sdk/runners/worker/KeyedWorkItems.java | 287 --------- .../sdk/runners/worker/PubsubReader.java | 92 --- .../sdk/runners/worker/PubsubSink.java | 132 ---- .../sdk/runners/worker/SinkRegistry.java | 118 ---- .../runners/worker/StreamingDoFnRunners.java | 65 -- .../worker/StreamingModeExecutionContext.java | 562 ----------------- .../worker/StreamingSideInputDoFnRunner.java | 295 --------- .../worker/UngroupedWindmillReader.java | 118 ---- .../sdk/runners/worker/WindmillSink.java | 182 ------ .../worker/WindowingWindmillReader.java | 135 ---- .../runners/worker/WorkerCustomSources.java | 580 ------------------ .../dataflow/sdk/util/TimerOrElement.java | 57 -- 12 files changed, 2623 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java deleted file mode 100644 index 7a9ece1eda..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyedWorkItems.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.InputMessageBundle; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Message; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.Timer; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.ComposedKeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.base.Throwables; -import com.google.common.collect.FluentIterable; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -/** - * Static utility methods that provide {@link KeyedWorkItem} implementations. - */ -public class KeyedWorkItems { - /** - * Return an implementation of {@link KeyedWorkItem} that wraps around - * a {@code Windmill.WorkItem}. - * - * @param the key type - * @param the element type - */ - public static KeyedWorkItem windmillWorkItem( - K key, - Windmill.WorkItem workItem, - Coder windowCoder, - Coder> windowsCoder, - Coder valueCoder) { - return new WindmillKeyedWorkItem<>(key, workItem, windowCoder, windowsCoder, valueCoder); - } - - /** - * Returns an implementation of {@link KeyedWorkItem} that wraps around an elements iterable. - * - * @param the key type - * @param the element type - */ - public static KeyedWorkItem elementsWorkItem( - K key, Iterable> elementsIterable) { - return ComposedKeyedWorkItem.create(key, Collections.emptyList(), elementsIterable); - } - - /** - * Returns an implementation of {@link KeyedWorkItem} that wraps around an timers iterable. - * - * @param the key type - * @param the element type - */ - public static KeyedWorkItem timersWorkItem( - K key, Iterable timersIterable) { - return ComposedKeyedWorkItem.create( - key, timersIterable, Collections.>emptyList()); - } - - /** - * Returns an implementation of {@link KeyedWorkItem} that wraps around - * an timers iterable and an elements iterable. - * - * @param the key type - * @param the element type - */ - public static KeyedWorkItem workItem( - K key, Iterable timersIterable, Iterable> elementsIterable) { - return ComposedKeyedWorkItem.create(key, timersIterable, elementsIterable); - } - - private static class WindmillKeyedWorkItem implements KeyedWorkItem { - private static final Predicate IS_WATERMARK = new Predicate() { - @Override - public boolean apply(Timer input) { - return input.getType() == Timer.Type.WATERMARK; - } - }; - - private final Windmill.WorkItem workItem; - private final K key; - - private final transient Coder windowCoder; - private final transient Coder> windowsCoder; - private final transient Coder valueCoder; - - WindmillKeyedWorkItem( - K key, - Windmill.WorkItem workItem, - Coder windowCoder, - Coder> windowsCoder, - Coder valueCoder) { - this.key = key; - this.workItem = workItem; - this.windowCoder = windowCoder; - this.windowsCoder = windowsCoder; - this.valueCoder = valueCoder; - } - - @Override - public K key() { - return key; - } - - @Override - public Iterable timersIterable() { - FluentIterable allTimers = FluentIterable.from(workItem.getTimers().getTimersList()); - FluentIterable eventTimers = allTimers.filter(IS_WATERMARK); - FluentIterable nonEventTimers = allTimers.filter(Predicates.not(IS_WATERMARK)); - return eventTimers.append(nonEventTimers).transform(new Function() { - private TimeDomain getTimeDomain(Windmill.Timer.Type type) { - switch (type) { - case REALTIME: - return TimeDomain.PROCESSING_TIME; - case DEPENDENT_REALTIME: - return TimeDomain.SYNCHRONIZED_PROCESSING_TIME; - case WATERMARK: - return TimeDomain.EVENT_TIME; - default: - throw new IllegalArgumentException("Unsupported timer type " + type); - } - } - - @Override - public TimerData apply(Timer timer) { - String tag = timer.getTag().toStringUtf8(); - String namespaceString = tag.substring(0, tag.indexOf('+')); - StateNamespace namespace = StateNamespaces.fromString(namespaceString, windowCoder); - - Instant timestamp = new Instant(TimeUnit.MICROSECONDS.toMillis(timer.getTimestamp())); - return TimerData.of(namespace, timestamp, getTimeDomain(timer.getType())); - } - }); - } - - @Override - public Iterable> elementsIterable() { - return FluentIterable.from(workItem.getMessageBundlesList()) - .transformAndConcat(new Function>() { - @Override - public Iterable apply(InputMessageBundle input) { - return input.getMessagesList(); - } - }) - .transform(new Function>() { - @Override - public WindowedValue apply(Message message) { - try { - Instant timestamp = new Instant( - TimeUnit.MICROSECONDS.toMillis(message.getTimestamp())); - Collection windows = - WindmillSink.decodeMetadataWindows(windowsCoder, message.getMetadata()); - PaneInfo pane = WindmillSink.decodeMetadataPane(message.getMetadata()); - - InputStream inputStream = message.getData().newInput(); - ElemT value = valueCoder.decode(inputStream, Coder.Context.OUTER); - return WindowedValue.of(value, timestamp, windows, pane); - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - }); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof WindmillKeyedWorkItem)) { - return false; - } - - WindmillKeyedWorkItem that = (WindmillKeyedWorkItem) other; - return Objects.equals(this.key, that.key) - && Objects.equals(this.workItem, that.workItem); - } - - @Override - public int hashCode() { - return Objects.hash(key, workItem); - } - } - - /** - * Coder that forwards {@code ByteSizeObserver} calls to an underlying element coder. - * {@code TimerOrElement} objects never need to be encoded, so this class does not - * support the {@code encode} and {@code decode} methods. - */ - public static class FakeKeyedWorkItemCoder extends StandardCoder> { - final Coder elemCoder; - - /** - * Creates a new {@code TimerOrElement.Coder} that wraps the given {@link Coder}. - */ - public static FakeKeyedWorkItemCoder of(Coder elemCoder) { - return new FakeKeyedWorkItemCoder<>(elemCoder); - } - - @JsonCreator - public static FakeKeyedWorkItemCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List components) { - return of((Coder) components.get(0)); - } - - @Override - public void encode(KeyedWorkItem value, OutputStream outStream, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public KeyedWorkItem decode(InputStream inStream, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isRegisterByteSizeObserverCheap(KeyedWorkItem value, Context context) { - return true; - } - - @Override - public void registerByteSizeObserver( - KeyedWorkItem value, ElementByteSizeObserver observer, Context context) - throws Exception { - if (value instanceof WindmillKeyedWorkItem) { - long serializedSize = ((WindmillKeyedWorkItem) value).workItem.getSerializedSize(); - observer.update(serializedSize); - } else { - throw new UnsupportedOperationException(); - } - } - - @Override - public void verifyDeterministic() throws NonDeterministicException {} - - @Override - public List> getCoderArguments() { - return Arrays.asList(elemCoder); - } - - public Coder getElementCoder() { - return elemCoder; - } - - protected FakeKeyedWorkItemCoder(Coder elemCoder) { - this.elemCoder = elemCoder; - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java deleted file mode 100644 index b341c0553a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubReader.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.ValueOnlyWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * A Reader that receives elements from Pubsub, via a Windmill server. - */ -class PubsubReader extends NativeReader> { - private final ValueOnlyWindowedValueCoder coder; - private StreamingModeExecutionContext context; - - PubsubReader(Coder> coder, StreamingModeExecutionContext context) { - @SuppressWarnings({"unchecked", "rawtypes"}) - ValueOnlyWindowedValueCoder typedCoder = (ValueOnlyWindowedValueCoder) coder; - this.coder = typedCoder; - this.context = context; - } - - static class Factory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject cloudSourceSpec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - @SuppressWarnings("unchecked") - Coder> typedCoder = (Coder>) coder; - return new PubsubReader<>(typedCoder, (StreamingModeExecutionContext) executionContext); - } - } - - @Override - public NativeReaderIterator> iterator() throws IOException { - return new PubsubReaderIterator(context.getWork()); - } - - class PubsubReaderIterator extends WindmillReaderIteratorBase { - protected PubsubReaderIterator(Windmill.WorkItem work) { - super(work); - } - - @Override - protected WindowedValue decodeMessage(Windmill.Message message) throws IOException { - long timestampMillis = TimeUnit.MICROSECONDS.toMillis(message.getTimestamp()); - InputStream data = message.getData().newInput(); - notifyElementRead(data.available()); - @SuppressWarnings("unchecked") - T value = (T) coder.getValueCoder().decode(data, Coder.Context.OUTER); - return WindowedValue.timestampedValueInGlobalWindow(value, new Instant(timestampMillis)); - } - } - - @Override - public boolean supportsRestart() { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java deleted file mode 100644 index 4fe7c27243..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PubsubSink.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.protobuf.ByteString; - -import java.io.IOException; - -import javax.annotation.Nullable; - -/** - * A sink that writes to Pubsub, via a Windmill server. - * - * @param the type of the elements written to the sink - */ -class PubsubSink extends Sink> { - private final String topic; - private final String timestampLabel; - private final String idLabel; - private final Coder> coder; - private final StreamingModeExecutionContext context; - - PubsubSink( - String topic, - String timestampLabel, - String idLabel, - Coder> coder, - StreamingModeExecutionContext context) { - this.topic = topic; - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - this.coder = coder; - this.context = context; - } - - public static class Factory implements SinkFactory { - @Override - public PubsubSink create( - CloudObject spec, - Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext context, - @Nullable CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - String topic = getString(spec, "pubsub_topic"); - String timestampLabel = getString(spec, "pubsub_timestamp_label", ""); - String idLabel = getString(spec, "pubsub_id_label", ""); - - @SuppressWarnings("unchecked") - Coder> typedCoder = - (Coder>) coder; - - return new PubsubSink<>( - topic, timestampLabel, idLabel, typedCoder, (StreamingModeExecutionContext) context); - } - } - - @Override - public SinkWriter> writer() { - return new PubsubWriter(topic); - } - - /** The SinkWriter for a PubsubSink. */ - class PubsubWriter implements SinkWriter> { - private Windmill.PubSubMessageBundle.Builder outputBuilder; - - private PubsubWriter(String topic) { - outputBuilder = - Windmill.PubSubMessageBundle.newBuilder() - .setTopic(topic) - .setTimestampLabel(timestampLabel) - .setIdLabel(idLabel); - } - - private ByteString encode(Coder coder, T object) throws IOException { - ByteString.Output stream = ByteString.newOutput(); - coder.encode(object, stream, Coder.Context.OUTER); - return stream.toByteString(); - } - - @Override - public long add(WindowedValue data) throws IOException { - ByteString byteString = encode(coder, data); - - outputBuilder.addMessages( - Windmill.Message.newBuilder() - .setData(byteString) - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(data.getTimestamp())) - .build()); - - return byteString.size(); - } - - @Override - public void close() throws IOException { - Windmill.PubSubMessageBundle pubsubMessages = outputBuilder.build(); - if (pubsubMessages.getMessagesCount() > 0) { - context.getOutputBuilder().addPubsubMessages(pubsubMessages); - } - outputBuilder.clear(); - } - } - - @Override - public boolean supportsRestart() { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java deleted file mode 100644 index d73c88035b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkRegistry.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * An immutable registry from {@link String} identifiers (provided to the worker by the Dataflow - * service) to appropriate {@link SinkFactory} instances. - */ -public final class SinkRegistry implements SinkFactory { - - public static SinkRegistry defaultRegistry() { - Map predefinedSinkFactories = new HashMap<>(); - predefinedSinkFactories.put("TextSink", new TextSinkFactory()); - predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.TextSink", - new TextSinkFactory()); - - predefinedSinkFactories.put("AvroSink", new AvroSinkFactory()); - predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.AvroSink", - new AvroSinkFactory()); - - predefinedSinkFactories.put("IsmSink", new IsmSinkFactory()); - predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.IsmSink", - new IsmSinkFactory()); - - predefinedSinkFactories.put("ShuffleSink", new ShuffleSinkFactory()); - predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.ShuffleSink", - new ShuffleSinkFactory()); - - predefinedSinkFactories.put("PubsubSink", new PubsubSink.Factory()); - predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.PubsubSink", - new PubsubSink.Factory()); - - predefinedSinkFactories.put("WindmillSink", new WindmillSink.Factory()); - predefinedSinkFactories.put("com.google.cloud.dataflow.sdk.runners.worker.WindmillSink", - new WindmillSink.Factory()); - - return new SinkRegistry(predefinedSinkFactories); - } - - /** - * Builds a new {@link SinkRegistry} with the provided mutable map of initial mappings. - * - *

      Owns and mutates the provided map, which must be mutable. This constructor should only be - * called by methods in this class that are aware of this requirement and abstract from this - * behavior. - */ - private SinkRegistry(Map factories) { - this.factories = factories; - } - - /** - * A map from the short names of predefined sinks to the associated {@link SinkFactory}. - */ - private final Map factories; - - /** - * Returns a new {@link SinkRegistry} with the provided identifier associated with the - * provided {@link SinkFactory}, overriding any existing binding for that identifier. - */ - public SinkRegistry register(String readerSpecType, SinkFactory factory) { - Map newFactories = new HashMap<>(); - newFactories.putAll(factories); - newFactories.put(readerSpecType, factory); - return new SinkRegistry(newFactories); - } - - /** - * Creates a {@link Sink} from a Dataflow API Sink definition. - * - * @throws Exception if the sink could not be decoded and - * constructed - */ - @Override - public Sink create( - CloudObject sinkSpec, - Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - - String objClassName = sinkSpec.getClassName(); - - SinkFactory factory = factories.get(objClassName); - if (factory == null) { - throw new IllegalArgumentException(String.format( - "Unable to create a Sink: Unknown Sink type in specification: %s", - objClassName)); - } - return factory.create(sinkSpec, coder, options, executionContext, addCounterMutator); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java deleted file mode 100644 index f3c2a859e3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDoFnRunners.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.util.List; - -/** - * Utility methods for creating {@link DoFnRunner} instances used by streaming Dataflow. - */ -public final class StreamingDoFnRunners { - private StreamingDoFnRunners() { - // Do not instantiate - } - - /** - * Returns an implementation of {@link DoFnRunner} that handles streaming side inputs. - * - *

      It blocks and caches input elements if their side inputs are not ready. - */ - public static DoFnRunner streamingSideInputRunner( - PipelineOptions options, - DoFnInfo doFnInfo, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator) { - return new StreamingSideInputDoFnRunner<>( - options, - doFnInfo, - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - doFnInfo.getWindowingStrategy()); - } - - -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java deleted file mode 100644 index 3b8dd591e2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingModeExecutionContext.java +++ /dev/null @@ -1,562 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; -import com.google.cloud.dataflow.sdk.runners.worker.StateFetcher.SideInputState; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Preconditions; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableSet; -import com.google.protobuf.ByteString; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ThreadLocalRandom; - -import javax.annotation.Nullable; - -/** - * {@link ExecutionContext} for use in streaming mode. - */ -public class StreamingModeExecutionContext - extends DataflowExecutionContext { - - private final String stageName; - private final Map, Map> sideInputCache; - - // Per-key cache of active Reader objects in use by this process. - private final ConcurrentMap readerCache; - private final ConcurrentMap stateNameMap; - private final WindmillStateCache.ForComputation stateCache; - - private Windmill.WorkItem work; - @Nullable private Instant inputDataWatermark; - @Nullable private Instant outputDataWatermark; - @Nullable private Instant synchronizedProcessingTime; - private WindmillStateReader stateReader; - private StateFetcher stateFetcher; - private Windmill.WorkItemCommitRequest.Builder outputBuilder; - private UnboundedSource.UnboundedReader activeReader; - - public StreamingModeExecutionContext(String stageName, - ConcurrentMap readerCache, - ConcurrentMap stateNameMap, WindmillStateCache.ForComputation stateCache) { - this.stageName = stageName; - this.sideInputCache = new HashMap<>(); - this.readerCache = readerCache; - this.stateNameMap = stateNameMap; - this.stateCache = stateCache; - } - - public void start( - Windmill.WorkItem work, - @Nullable Instant inputDataWatermark, - @Nullable Instant outputDataWatermark, - @Nullable Instant synchronizedProcessingTime, - WindmillStateReader stateReader, - StateFetcher stateFetcher, - Windmill.WorkItemCommitRequest.Builder outputBuilder) { - this.work = work; - this.inputDataWatermark = inputDataWatermark; - this.outputDataWatermark = outputDataWatermark; - this.synchronizedProcessingTime = synchronizedProcessingTime; - this.stateReader = stateReader; - this.stateFetcher = stateFetcher; - this.outputBuilder = outputBuilder; - this.sideInputCache.clear(); - - for (ExecutionContext.StepContext stepContext : getAllStepContexts()) { - ((StepContext) stepContext) - .start(stateReader, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime); - } - } - - @Override - public StepContext createStepContext( - String stepName, String transformName, StateSampler stateSampler) { - StepContext context = new StepContext(stepName, transformName, stateSampler); - context.start(stateReader, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime); - return context; - } - - @Override - protected SideInputReader getSideInputReader(Iterable sideInputInfos) { - throw new UnsupportedOperationException( - "Cannot call getSideInputReader for StreamingDataflowWorker: " - + "the MapTask specification should not have had any SideInputInfo descriptors " - + "since the streaming runner does not yet support them."); - } - - @Override - protected SideInputReader getSideInputReaderForViews( - Iterable> views) { - return StreamingModeSideInputReader.of(views, this); - } - - /** - * Fetches the requested sideInput, and maintains a view of the cache that doesn't remove - * items until the active work item is finished. - */ - private T fetchSideInput(PCollectionView view, BoundedWindow sideInputWindow, - String stateFamily, SideInputState state, - Supplier scopedReadStateSupplier) { - Map tagCache = sideInputCache.get(view.getTagInternal()); - if (tagCache == null) { - tagCache = new HashMap<>(); - sideInputCache.put(view.getTagInternal(), tagCache); - } - - @SuppressWarnings("unchecked") - T sideInput = (T) tagCache.get(sideInputWindow); - if (sideInput == null) { - if (state == SideInputState.CACHED_IN_WORKITEM) { - throw new IllegalStateException( - "Expected side input to be cached. Tag: " - + view.getTagInternal().getId()); - } - T typed = stateFetcher.fetchSideInput( - view, sideInputWindow, stateFamily, state, scopedReadStateSupplier); - sideInput = typed; - if (sideInput != null) { - tagCache.put(sideInputWindow, sideInput); - return sideInput; - } else { - return null; - } - } else { - return sideInput; - } - } - - public Iterable getSideInputNotifications() { - return work.getGlobalDataIdNotificationsList(); - } - - public ByteString getSerializedKey() { - return work.getKey(); - } - - public long getWorkToken() { - return work.getWorkToken(); - } - - public Windmill.WorkItem getWork() { - return work; - } - - public Windmill.WorkItemCommitRequest.Builder getOutputBuilder() { - return outputBuilder; - } - - public UnboundedSource.UnboundedReader getCachedReader() { - ReaderCacheEntry entry = readerCache.get(getSerializedKey()); - if (entry == null) { - return null; - } else if (entry.token != getWork().getCacheToken()) { - readerCache.remove(getSerializedKey()); - return null; - } else { - return entry.reader; - } - } - - public void setActiveReader(UnboundedSource.UnboundedReader reader) { - activeReader = reader; - } - - public UnboundedSource.CheckpointMark getReaderCheckpoint( - Coder coder) { - try { - ByteString state = work.getSourceState().getState(); - if (state.isEmpty()) { - return null; - } - return coder.decode(state.newInput(), Coder.Context.OUTER); - } catch (IOException e) { - throw new RuntimeException("Exception while decoding checkpoint", e); - } - } - - public Map flushState() { - Map callbacks = new HashMap<>(); - - for (ExecutionContext.StepContext stepContext : getAllStepContexts()) { - ((StepContext) stepContext).flushState(); - } - - - if (activeReader != null) { - Windmill.SourceState.Builder sourceStateBuilder = - outputBuilder.getSourceStateUpdatesBuilder(); - final UnboundedSource.CheckpointMark checkpointMark = activeReader.getCheckpointMark(); - final Instant watermark = activeReader.getWatermark(); - long id = ThreadLocalRandom.current().nextLong(); - sourceStateBuilder.addFinalizeIds(id); - callbacks.put( - id, - new Runnable() { - @Override - public void run() { - try { - checkpointMark.finalizeCheckpoint(); - } catch (IOException e) { - throw new RuntimeException("Exception while finalizing checkpoint", e); - } - } - }); - - @SuppressWarnings("unchecked") - Coder checkpointCoder = - ((UnboundedSource) activeReader.getCurrentSource()) - .getCheckpointMarkCoder(); - if (checkpointCoder != null) { - ByteString.Output stream = ByteString.newOutput(); - try { - checkpointCoder.encode(checkpointMark, stream, Coder.Context.OUTER); - } catch (IOException e) { - throw new RuntimeException("Exception while encoding checkpoint", e); - } - sourceStateBuilder.setState(stream.toByteString()); - } - outputBuilder.setSourceWatermark( - WindmillTimeUtils.harnessToWindmillTimestamp(watermark)); - - long backlogBytes = activeReader.getSplitBacklogBytes(); - if (backlogBytes == UnboundedSource.UnboundedReader.BACKLOG_UNKNOWN - && CustomSources.isFirstUnboundedSourceSplit(getSerializedKey())) { - // Only call getTotalBacklogBytes() on the first split. - backlogBytes = activeReader.getTotalBacklogBytes(); - } - if (backlogBytes != UnboundedSource.UnboundedReader.BACKLOG_UNKNOWN) { - outputBuilder.addCounterUpdates( - Windmill.Counter.newBuilder() - .setName("dataflow_backlog_size-" + stageName) - .setKind(Windmill.Counter.Kind.SUM) - .setIntScalar(backlogBytes) - .setCumulative(true) - .build()); - } - - readerCache.put( - getSerializedKey(), new ReaderCacheEntry(activeReader, getWork().getCacheToken())); - } - return callbacks; - } - - public List getReadyCommitCallbackIds() { - return work.getSourceState().getFinalizeIdsList(); - } - - /** - * Produce a tag that is guaranteed to be unique for the given namespace, domain and timestamp. - * - *

      This is necessary because Windmill will deduplicate based only on this tag. - */ - public static ByteString timerTag(TimerData key) { - String tagString = String.format("%s+%d:%d", - key.getNamespace().stringKey(), key.getDomain().ordinal(), - key.getTimestamp().getMillis()); - return ByteString.copyFromUtf8(tagString); - } - - private static class WindmillTimerInternals implements TimerInternals { - private Map timers = new HashMap<>(); - @Nullable private Instant inputDataWatermark; - @Nullable private Instant outputDataWatermark; - @Nullable private Instant synchronizedProcessingTime; - private String stateFamily; - - public WindmillTimerInternals(String stateFamily, @Nullable Instant inputDataWatermark, - @Nullable Instant outputDataWatermark, @Nullable Instant synchronizedProcessingTime) { - this.inputDataWatermark = inputDataWatermark; - this.outputDataWatermark = outputDataWatermark; - this.stateFamily = stateFamily; - } - - @Override - public void setTimer(TimerData timerKey) { - timers.put(timerKey, true); - } - - @Override - public void deleteTimer(TimerData timerKey) { - timers.put(timerKey, false); - } - - @Override - public Instant currentProcessingTime() { - return Instant.now(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return synchronizedProcessingTime; - } - - /** - * {@inheritDoc} - * - *

      Note that this value may be arbitrarily behind the global input watermark. Windmill - * simply reports the last known input watermark value at the time the GetWork response was - * constructed. However, if an element in a GetWork request has a timestamp at or ahead - * of the local input watermark then Windmill will not allow the local input watermark - * to advance until that element has been committed. - */ - @Override - @Nullable - public Instant currentInputWatermarkTime() { - return inputDataWatermark; - } - - /** - * {@inheritDoc} - * - *

      Note that Windmill will provisionally hold the output watermark to the timestamp of the - * earliest element in a computation's GetWork response. (Elements with timestamps already - * behind the output watermark at the point the GetWork response is constructed will have - * no influence on the output watermark). The provisional hold will last until this work item is - * committed. It is the responsibility of the harness to impose any persistent holds it needs. - */ - @Override - @Nullable - public Instant currentOutputWatermarkTime() { - return outputDataWatermark; - } - - public void persistTo(Windmill.WorkItemCommitRequest.Builder outputBuilder) { - for (Entry entry : timers.entrySet()) { - Windmill.Timer.Builder timer = outputBuilder.addOutputTimersBuilder() - .setTag(timerTag(entry.getKey())) - .setType(timerType(entry.getKey().getDomain())); - if (stateFamily != null) { - timer.setStateFamily(stateFamily); - } - - // If the timer was being set (not deleted) then set a timestamp for it. - if (entry.getValue()) { - timer.setTimestamp( - WindmillTimeUtils.harnessToWindmillTimestamp(entry.getKey().getTimestamp())); - } - } - timers.clear(); - } - - private Windmill.Timer.Type timerType(TimeDomain domain) { - switch (domain) { - case EVENT_TIME: return Windmill.Timer.Type.WATERMARK; - case PROCESSING_TIME: return Windmill.Timer.Type.REALTIME; - case SYNCHRONIZED_PROCESSING_TIME: return Windmill.Timer.Type.DEPENDENT_REALTIME; - default: - throw new IllegalArgumentException("Unrecgonized TimeDomain: " + domain); - } - } - } - - class StepContext extends BaseExecutionContext.StepContext { - private static final String DEFAULT_STATE_FAMILY = ""; - - private WindmillStateInternals stateInternals; - private WindmillTimerInternals timerInternals; - private final String stateFamily; - private final Supplier scopedReadStateSupplier; - - public StepContext( - final String stepName, String transformName, final StateSampler stateSampler) { - super(StreamingModeExecutionContext.this, stepName, transformName); - - String mappedName = stateNameMap.get(transformName); - this.stateFamily = mappedName == null ? DEFAULT_STATE_FAMILY : mappedName; - - this.scopedReadStateSupplier = new Supplier() { - private int readState = -1; // Uninitialized value. - - @Override - public StateSampler.ScopedState get() { - if (stateSampler == null) { - return null; - } - if (readState == -1) { - readState = stateSampler.stateForName(stepName + "-windmill-read", StateKind.FRAMEWORK); - } - return stateSampler.scopedState(readState); - } - }; - } - - /** - * Update the {@code stateReader} used by this {@code StepContext}. - */ - public void start( - WindmillStateReader stateReader, @Nullable Instant inputDataWatermark, - @Nullable Instant outputDataWatermark, - @Nullable Instant synchronizedProcessingTime) { - this.stateInternals = new WindmillStateInternals(stateFamily, stateReader, - stateCache.forKey(getSerializedKey(), stateFamily, getWork().getCacheToken()), - scopedReadStateSupplier); - this.timerInternals = -new WindmillTimerInternals( - stateFamily, inputDataWatermark, outputDataWatermark, synchronizedProcessingTime); - } - - public void flushState() { - stateInternals.persist(outputBuilder); - timerInternals.persistTo(outputBuilder); - } - - public Iterable getSideInputNotifications() { - return StreamingModeExecutionContext.this.getSideInputNotifications(); - } - - @Override - public void writePCollectionViewData( - TupleTag tag, - Iterable> data, Coder>> dataCoder, - W window, Coder windowCoder) throws IOException { - if (getSerializedKey().size() != 0) { - throw new IllegalStateException("writePCollectionViewData must follow a Combine.globally"); - } - - ByteString.Output dataStream = ByteString.newOutput(); - dataCoder.encode(data, dataStream, Coder.Context.OUTER); - - ByteString.Output windowStream = ByteString.newOutput(); - windowCoder.encode(window, windowStream, Coder.Context.OUTER); - - Windmill.GlobalData.Builder builder = Windmill.GlobalData.newBuilder() - .setDataId( - Windmill.GlobalDataId.newBuilder() - .setTag(tag.getId()) - .setVersion(windowStream.toByteString()) - .build()) - .setData(dataStream.toByteString()); - if (stateFamily != null) { - builder.setStateFamily(stateFamily); - } - - outputBuilder.addGlobalDataUpdates(builder.build()); - } - - /** - * Fetch the given side input asynchronously and return true if it is present. - */ - public boolean issueSideInputFetch( - PCollectionView view, BoundedWindow mainInputWindow, SideInputState state) { - BoundedWindow sideInputWindow = - view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(mainInputWindow); - return fetchSideInput(view, sideInputWindow, stateFamily, state, scopedReadStateSupplier) - != null; - } - - /** - * Note that there is data on the current key that is blocked on the given side input. - */ - public void addBlockingSideInput(Windmill.GlobalDataRequest sideInput) { - if (stateFamily != null) { - sideInput = - Windmill.GlobalDataRequest.newBuilder(sideInput).setStateFamily(stateFamily).build(); - } - outputBuilder.addGlobalDataRequests(sideInput); - outputBuilder.addGlobalDataIdRequests(sideInput.getDataId()); - } - - /** - * Note that there is data on the current key that is blocked on the given side inputs. - */ - public void addBlockingSideInputs(Iterable sideInputs) { - for (Windmill.GlobalDataRequest sideInput : sideInputs) { - addBlockingSideInput(sideInput); - } - } - - @Override - public StateInternals stateInternals() { - return Preconditions.checkNotNull(stateInternals); - } - - @Override - public TimerInternals timerInternals() { - return Preconditions.checkNotNull(timerInternals); - } - } - - /** - * A {@link SideInputReader} that fetches side inputs from the streaming worker's - * cache. - */ - public static class StreamingModeSideInputReader implements SideInputReader { - private StreamingModeExecutionContext context; - private Set> viewSet; - - private StreamingModeSideInputReader( - Iterable> views, StreamingModeExecutionContext context) { - this.context = context; - this.viewSet = ImmutableSet.copyOf(views); - } - - public static StreamingModeSideInputReader of( - Iterable> views, StreamingModeExecutionContext context) { - return new StreamingModeSideInputReader(views, context); - } - - @Override - public T get(PCollectionView view, BoundedWindow window) { - if (!contains(view)) { - throw new RuntimeException("get() called with unknown view"); - } - - // We are only fetching the cached value here, so we don't need stateFamily or - // readStateSupplier. - return context.fetchSideInput(view, window, null /* unused stateFamily */, - SideInputState.CACHED_IN_WORKITEM, null /* unused readStateSupplier */); - } - - @Override - public boolean contains(PCollectionView view) { - return viewSet.contains(view); - } - - @Override - public boolean isEmpty() { - return viewSet.isEmpty(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java deleted file mode 100644 index be916adf76..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingSideInputDoFnRunner.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.Proto2Coder; -import com.google.cloud.dataflow.sdk.coders.SetCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.StateFetcher.SideInputState; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.GlobalDataRequest; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.ValueState; -import com.google.cloud.dataflow.sdk.util.state.WatermarkStateInternal; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Throwables; -import com.google.common.collect.Iterables; -import com.google.protobuf.ByteString; - -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Runs a DoFn by constructing the appropriate contexts and passing them in. - * - * @param the type of the DoFn's (main) input elements - * @param the type of the DoFn's (main) output elements - * @param the type of the windows of the main input - */ -public class StreamingSideInputDoFnRunner - extends DoFnRunnerBase { - private StreamingModeExecutionContext.StepContext stepContext; - private Map> sideInputViews; - - private final StateTag>> elementsAddr; - private final StateTag watermarkHoldingAddr; - private final StateTag>>> blockedMapAddr; - - private Map> blockedMap; - - private WindowFn windowFn; - - public StreamingSideInputDoFnRunner( - PipelineOptions options, - DoFnInfo doFnInfo, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - super(options, doFnInfo.getDoFn(), sideInputReader, outputManager, - mainOutputTag, sideOutputTags, stepContext, - addCounterMutator, doFnInfo.getWindowingStrategy()); - this.stepContext = (StreamingModeExecutionContext.StepContext) stepContext; - - this.windowFn = windowingStrategy.getWindowFn(); - - this.sideInputViews = new HashMap<>(); - for (PCollectionView view : doFnInfo.getSideInputViews()) { - sideInputViews.put(view.getTagInternal().getId(), view); - } - - this.blockedMapAddr = blockedMapAddr(windowFn); - this.elementsAddr = StateTags.makeSystemTagInternal(StateTags.bag("elem", - WindowedValue.getFullCoder(doFnInfo.getInputCoder(), windowFn.windowCoder()))); - this.watermarkHoldingAddr = - StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal("hold", - doFnInfo.getWindowingStrategy().getOutputTimeFn())); - - this.blockedMap = stepContext.stateInternals().state(StateNamespaces.global(), blockedMapAddr) - .get().read(); - if (this.blockedMap == null) { - this.blockedMap = new HashMap<>(); - } - } - - @VisibleForTesting static - StateTag>>> blockedMapAddr(WindowFn windowFn) { - return StateTags.value("blockedMap", MapCoder.of( - windowFn.windowCoder(), SetCoder.of(Proto2Coder.of(Windmill.GlobalDataRequest.class)))); - } - - /** - * Computes the set of main input windows for which all side inputs are ready and cached. - */ - private Set getReadyWindows() { - Set readyWindows = new HashSet<>(); - - for (Windmill.GlobalDataId id : stepContext.getSideInputNotifications()) { - if (sideInputViews.get(id.getTag()) == null) { - // Side input is for a different DoFn; ignore it. - continue; - } - - for (Map.Entry> entry : blockedMap.entrySet()) { - Set windowBlockedSet = entry.getValue(); - Set found = new HashSet<>(); - for (Windmill.GlobalDataRequest request : windowBlockedSet) { - if (id.equals(request.getDataId())) { - found.add(request); - } - } - - windowBlockedSet.removeAll(found); - - if (windowBlockedSet.isEmpty()) { - // Notifications were received for all side inputs for this window. - // Issue fetches for all the needed side inputs to make sure they are all present - // in the local cache. If not, note the side inputs as still being blocked. - try { - W window = entry.getKey(); - boolean allSideInputsCached = true; - for (PCollectionView view : sideInputViews.values()) { - if (!stepContext.issueSideInputFetch( - view, window, SideInputState.KNOWN_READY)) { - Windmill.GlobalDataRequest request = buildGlobalDataRequest(view, window); - stepContext.addBlockingSideInput(request); - windowBlockedSet.add(request); - allSideInputsCached = false; - } - } - - if (allSideInputsCached) { - readyWindows.add(window); - } - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - } - } - - return readyWindows; - } - - @Override - public void startBundle() { - super.startBundle(); - - // Find the set of ready windows. - Set readyWindows = getReadyWindows(); - - // Pre-fetch the elements for each of the ready windows. - for (W window : readyWindows) { - elementBag(window).get(); - WatermarkStateInternal watermarkHold = watermarkHold(window); - watermarkHold.get(); - watermarkHold.clear(); - } - - // Run the DoFn code now that all side inputs are ready. - for (W window : readyWindows) { - blockedMap.remove(window); - - BagState> elementsBag = elementBag(window); - Iterable> elements = elementsBag.get().read(); - for (WindowedValue elem : elements) { - try { - fn.processElement(createProcessContext(elem)); - } catch (Exception ex) { - throw wrapUserCodeException(ex); - } - } - - elementsBag.clear(); - } - } - - /** - * Compute the set of side inputs that are not yet ready for the given main input window. - */ - private Set computeBlockedSideInputs(W window) throws IOException { - Set blocked = blockedMap.get(window); - if (blocked == null) { - for (PCollectionView view : sideInputViews.values()) { - if (!stepContext.issueSideInputFetch(view, window, SideInputState.UNKNOWN)) { - if (blocked == null) { - blocked = new HashSet<>(); - blockedMap.put(window, blocked); - } - blocked.add(buildGlobalDataRequest(view, window)); - } - } - } - return blocked; - } - - @VisibleForTesting BagState> elementBag(W window) { - return stepContext.stateInternals() - .state(StateNamespaces.window(windowFn.windowCoder(), window), elementsAddr); - } - - @VisibleForTesting WatermarkStateInternal watermarkHold(W window) { - return stepContext.stateInternals() - .state(StateNamespaces.window(windowFn.windowCoder(), window), watermarkHoldingAddr); - } - - @Override - public void invokeProcessElement(WindowedValue elem) { - @SuppressWarnings("unchecked") - W window = (W) Iterables.getOnlyElement(elem.getWindows()); - - Set blocked; - try { - blocked = computeBlockedSideInputs(window); - } catch (IOException ex) { - // Can't leak IOException here - throw Throwables.propagate(ex); - } - - if (blocked == null) { - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.processElement(createProcessContext(elem)); - } catch (Exception ex) { - throw wrapUserCodeException(ex); - } - } else { - elementBag(window).add(elem); - watermarkHold(window).add(elem.getTimestamp()); - - stepContext.addBlockingSideInputs(blocked); - } - } - - @Override - public void finishBundle() { - super.finishBundle(); - stepContext.stateInternals().state(StateNamespaces.global(), blockedMapAddr).set(blockedMap); - } - - private Windmill.GlobalDataRequest buildGlobalDataRequest( - PCollectionView view, BoundedWindow mainWindow) throws IOException { - @SuppressWarnings("unchecked") - WindowingStrategy sideWindowStrategy = - (WindowingStrategy) view.getWindowingStrategyInternal(); - - WindowFn sideWindowFn = sideWindowStrategy.getWindowFn(); - - Coder sideInputWindowCoder = sideWindowFn.windowCoder(); - - SideWindowT sideInputWindow = sideWindowFn.getSideInputWindow(mainWindow); - - ByteString.Output windowStream = ByteString.newOutput(); - sideInputWindowCoder.encode(sideInputWindow, windowStream, Coder.Context.OUTER); - - return Windmill.GlobalDataRequest.newBuilder() - .setDataId(Windmill.GlobalDataId.newBuilder() - .setTag(view.getTagInternal().getId()) - .setVersion(windowStream.toByteString()) - .build()) - .setExistenceWatermarkDeadline(WindmillTimeUtils.harnessToWindmillTimestamp( - sideWindowStrategy - .getTrigger() - .getSpec() - .getWatermarkThatGuaranteesFiring(sideInputWindow))) - .build(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java deleted file mode 100644 index abcb9c5fe9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedWindmillReader.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * A Reader that receives input data from a Windmill server, and returns it as - * individual elements. - */ -class UngroupedWindmillReader extends NativeReader> { - private final Coder valueCoder; - private final Coder> windowsCoder; - private StreamingModeExecutionContext context; - - UngroupedWindmillReader(Coder> coder, StreamingModeExecutionContext context) { - FullWindowedValueCoder inputCoder = (FullWindowedValueCoder) coder; - this.valueCoder = inputCoder.getValueCoder(); - this.windowsCoder = inputCoder.getWindowsCoder(); - this.context = context; - } - - static class Factory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - @SuppressWarnings("unchecked") - Coder> typedCoder = (Coder>) coder; - return new UngroupedWindmillReader<>( - typedCoder, (StreamingModeExecutionContext) executionContext); - } - } - - @Override - public NativeReaderIterator> iterator() throws IOException { - return new UngroupedWindmillReaderIterator(context.getWork()); - } - - class UngroupedWindmillReaderIterator extends WindmillReaderIteratorBase { - UngroupedWindmillReaderIterator(Windmill.WorkItem work) { - super(work); - } - - @Override - protected WindowedValue decodeMessage(Windmill.Message message) throws IOException { - Instant timestampMillis = new Instant(TimeUnit.MICROSECONDS.toMillis(message.getTimestamp())); - InputStream data = message.getData().newInput(); - InputStream metadata = message.getMetadata().newInput(); - Collection windows = WindmillSink.decodeMetadataWindows( - windowsCoder, message.getMetadata()); - PaneInfo pane = WindmillSink.decodeMetadataPane(message.getMetadata()); - if (valueCoder instanceof KvCoder) { - KvCoder kvCoder = (KvCoder) valueCoder; - InputStream key = context.getSerializedKey().newInput(); - notifyElementRead(key.available() + data.available() + metadata.available()); - - @SuppressWarnings("unchecked") - T result = (T) KV.of( - decode(kvCoder.getKeyCoder(), key), - decode(kvCoder.getValueCoder(), data)); - return WindowedValue.of(result, timestampMillis, windows, pane); - } else { - notifyElementRead(data.available() + metadata.available()); - return WindowedValue.of(decode(valueCoder, data), timestampMillis, windows, pane); - } - } - - private X decode(Coder coder, InputStream input) throws IOException { - return coder.decode(input, Coder.Context.OUTER); - } - } - - @Override - public boolean supportsRestart() { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java deleted file mode 100644 index 7c92d3e892..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillSink.java +++ /dev/null @@ -1,182 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId.ValueWithRecordIdCoder; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.protobuf.ByteString; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.Nullable; - -class WindmillSink extends Sink> { - private WindmillStreamWriter writer; - private final Coder valueCoder; - private final Coder> windowsCoder; - private StreamingModeExecutionContext context; - - WindmillSink(String destinationName, - Coder> coder, - StreamingModeExecutionContext context) { - this.writer = new WindmillStreamWriter(destinationName); - FullWindowedValueCoder inputCoder = (FullWindowedValueCoder) coder; - this.valueCoder = inputCoder.getValueCoder(); - this.windowsCoder = inputCoder.getWindowsCoder(); - this.context = context; - } - - public static ByteString encodeMetadata( - Coder> windowsCoder, - Collection windows, - PaneInfo pane) throws IOException { - ByteString.Output stream = ByteString.newOutput(); - PaneInfoCoder.INSTANCE.encode(pane, stream, Coder.Context.NESTED); - windowsCoder.encode(windows, stream, Coder.Context.OUTER); - return stream.toByteString(); - } - - public static PaneInfo decodeMetadataPane(ByteString metadata) throws IOException { - InputStream inStream = metadata.newInput(); - return PaneInfoCoder.INSTANCE.decode(inStream, Coder.Context.NESTED); - } - - public static Collection decodeMetadataWindows( - Coder> windowsCoder, - ByteString metadata) throws IOException { - InputStream inStream = metadata.newInput(); - PaneInfoCoder.INSTANCE.decode(inStream, Coder.Context.NESTED); - return windowsCoder.decode(inStream, Coder.Context.OUTER); - } - - public static class Factory implements SinkFactory { - @Override - public WindmillSink create( - CloudObject spec, - Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext context, - @Nullable CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - - @SuppressWarnings("unchecked") - Coder> typedCoder = (Coder>) coder; - return new WindmillSink<>( - getString(spec, "stream_id"), typedCoder, (StreamingModeExecutionContext) context); - } - } - - @Override - public SinkWriter> writer() { - return writer; - } - - class WindmillStreamWriter implements SinkWriter> { - private Map productionMap; - private final String destinationName; - - private WindmillStreamWriter(String destinationName) { - this.destinationName = destinationName; - productionMap = new HashMap(); - } - - private ByteString encode(Coder coder, T object) throws IOException { - ByteString.Output stream = ByteString.newOutput(); - coder.encode(object, stream, Coder.Context.OUTER); - return stream.toByteString(); - } - - @Override - public long add(WindowedValue data) throws IOException { - ByteString key, value; - ByteString id = ByteString.EMPTY; - ByteString metadata = encodeMetadata(windowsCoder, data.getWindows(), data.getPane()); - if (valueCoder instanceof KvCoder) { - KvCoder kvCoder = (KvCoder) valueCoder; - KV kv = (KV) data.getValue(); - key = encode(kvCoder.getKeyCoder(), kv.getKey()); - Coder valueCoder = kvCoder.getValueCoder(); - // If ids are explicitly provided, use that instead of the windmill-generated id. - // This is used when reading an UnboundedSource to deduplicate records. - if (valueCoder instanceof ValueWithRecordIdCoder) { - ValueWithRecordId valueAndId = (ValueWithRecordId) kv.getValue(); - value = - encode(((ValueWithRecordIdCoder) valueCoder).getValueCoder(), valueAndId.getValue()); - id = ByteString.copyFrom(valueAndId.getId()); - } else { - value = encode(valueCoder, kv.getValue()); - } - } else { - key = context.getSerializedKey(); - value = encode(valueCoder, data.getValue()); - } - - Windmill.KeyedMessageBundle.Builder keyedOutput = productionMap.get(key); - if (keyedOutput == null) { - keyedOutput = Windmill.KeyedMessageBundle.newBuilder().setKey(key); - productionMap.put(key, keyedOutput); - } - - Windmill.Message.Builder builder = Windmill.Message.newBuilder() - .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(data.getTimestamp())) - .setData(value) - .setMetadata(metadata); - keyedOutput.addMessages(builder.build()); - keyedOutput.addMessagesIds(id); - return key.size() + value.size() + metadata.size() + id.size(); - } - - @Override - public void close() throws IOException { - Windmill.OutputMessageBundle.Builder outputBuilder = - Windmill.OutputMessageBundle.newBuilder().setDestinationStreamId(destinationName); - - for (Windmill.KeyedMessageBundle.Builder keyedOutput : productionMap.values()) { - outputBuilder.addBundles(keyedOutput.build()); - } - if (outputBuilder.getBundlesCount() > 0) { - context.getOutputBuilder().addOutputMessages(outputBuilder.build()); - } - productionMap.clear(); - } - } - - @Override - public boolean supportsRestart() { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java deleted file mode 100644 index 5cff492296..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindowingWindmillReader.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItems.FakeKeyedWorkItemCoder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItem; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.io.IOException; -import java.util.Collection; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A Reader that receives input data from a Windmill server, and returns a singleton iterable - * containing the work item. - */ -class WindowingWindmillReader extends NativeReader>> { - - private final KvCoder kvCoder; - private final Coder windowCoder; - private final Coder> windowsCoder; - private StreamingModeExecutionContext context; - - WindowingWindmillReader(Coder>> coder, - StreamingModeExecutionContext context) { - FullWindowedValueCoder> inputCoder = - (FullWindowedValueCoder>) coder; - this.windowsCoder = inputCoder.getWindowsCoder(); - this.windowCoder = inputCoder.getWindowCoder(); - Coder elementCoder = - ((FakeKeyedWorkItemCoder) inputCoder.getValueCoder()).getElementCoder(); - if (!(elementCoder instanceof KvCoder)) { - throw new IllegalArgumentException( - "WindowingWindmillReader only works with KvCoders."); - } - @SuppressWarnings("unchecked") - KvCoder kvCoder = (KvCoder) - elementCoder; - this.kvCoder = kvCoder; - this.context = context; - } - - static class Factory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext context, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - @SuppressWarnings({"rawtypes", "unchecked"}) - Coder>> typedCoder = - (Coder>>) coder; - return WindowingWindmillReader.create(typedCoder, (StreamingModeExecutionContext) context); - } - } - - /** - * Creates a {@link WindowingWindmillReader} from the provided {@link Coder} - * and {@link StreamingModeExecutionContext}. - */ - public static WindowingWindmillReader create( - Coder>> coder, - StreamingModeExecutionContext context) { - return new WindowingWindmillReader(coder, context); - } - - @Override - public NativeReaderIterator>> iterator() throws IOException { - final K key = kvCoder.getKeyCoder().decode( - context.getSerializedKey().newInput(), Coder.Context.OUTER); - final WorkItem workItem = context.getWork(); - final WindowedValue> value = - WindowedValue.valueInEmptyWindows( - KeyedWorkItems.windmillWorkItem( - key, workItem, windowCoder, windowsCoder, kvCoder.getValueCoder())); - - return new NativeReaderIterator>>() { - private WindowedValue> current; - - @Override - public boolean start() throws IOException { - current = value; - return true; - } - - @Override - public boolean advance() throws IOException { - current = null; - return false; - } - - @Override - public WindowedValue> getCurrent() { - if (current == null) { - throw new NoSuchElementException(); - } - return value; - } - }; - } - - @Override - public boolean supportsRestart() { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java deleted file mode 100644 index 192b9ee456..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WorkerCustomSources.java +++ /dev/null @@ -1,580 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources.serializeToCloudSource; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.deserializeFromByteArray; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.Base64; -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.DerivedSource; -import com.google.api.services.dataflow.model.DynamicSourceSplit; -import com.google.api.services.dataflow.model.SourceOperationResponse; -import com.google.api.services.dataflow.model.SourceSplitOptions; -import com.google.api.services.dataflow.model.SourceSplitRequest; -import com.google.api.services.dataflow.model.SourceSplitResponse; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.Source; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.annotations.VisibleForTesting; -import com.google.protobuf.ByteString; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A helper class for supporting sources defined as {@code Source}. - * - *

      Provides a bridge between the high-level {@code Source} API and the - * low-level {@code CloudSource} class. - */ -public class WorkerCustomSources { - private static final String SERIALIZED_SOURCE = "serialized_source"; - @VisibleForTesting static final String SERIALIZED_SOURCE_SPLITS = "serialized_source_splits"; - private static final long DEFAULT_DESIRED_BUNDLE_SIZE_BYTES = 64 * (1 << 20); - /** - * The current limit on the size of a ReportWorkItemStatus RPC to Google Cloud Dataflow, which - * includes the initial splits, is 20 MB. - */ - public static final long DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES = 20 * (1 << 20); - - private static final Logger LOG = LoggerFactory.getLogger(WorkerCustomSources.class); - - /** - * A {@code DynamicSplitResult} specified explicitly by a pair of {@code BoundedSource} - * objects describing the primary and residual sources. - */ - public static final class BoundedSourceSplit implements NativeReader.DynamicSplitResult { - public final BoundedSource primary; - public final BoundedSource residual; - - public BoundedSourceSplit(BoundedSource primary, BoundedSource residual) { - this.primary = primary; - this.residual = residual; - } - - @Override - public String toString() { - return String.format("", primary, residual); - } - } - - public static DynamicSourceSplit toSourceSplit( - BoundedSourceSplit sourceSplitResult, PipelineOptions options) { - DynamicSourceSplit sourceSplit = new DynamicSourceSplit(); - com.google.api.services.dataflow.model.Source primarySource; - com.google.api.services.dataflow.model.Source residualSource; - try { - primarySource = serializeToCloudSource(sourceSplitResult.primary, options); - residualSource = serializeToCloudSource(sourceSplitResult.residual, options); - } catch (Exception e) { - throw new RuntimeException("Failed to serialize one of the parts of the source split", e); - } - sourceSplit.setPrimary( - new DerivedSource() - .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") - .setSource(primarySource)); - sourceSplit.setResidual( - new DerivedSource() - .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") - .setSource(residualSource)); - return sourceSplit; - } - - /** - * Executes a protocol-level split {@code SourceOperationRequest} for bounded sources - * by deserializing its source to a {@code BoundedSource}, splitting it, and - * serializing results back. - * - *

      When the splits produced by this function are too large to be serialized to the Dataflow - * API, splitting is retried once with an increase in the desired bundle size. This change aims - * to work around API limitations on split size. - */ - public static SourceOperationResponse performSplit( - SourceSplitRequest request, PipelineOptions options) throws Exception { - return performSplitWithApiLimit(request, options, DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES); - } - - /** - * A helper method like {@link #performSplit(SourceSplitRequest, PipelineOptions)} but that - * allows overriding the API size limit for testing. - */ - static SourceOperationResponse performSplitWithApiLimit( - SourceSplitRequest request, PipelineOptions options, long apiByteLimit) throws Exception { - Source anySource = deserializeFromCloudSource(request.getSource().getSpec()); - checkArgument( - anySource instanceof BoundedSource, "Cannot split a non-Bounded source: %s", anySource); - BoundedSource source = (BoundedSource) anySource; - - // Compute the desired bundle size given by the service, or default if none was provided. - long desiredBundleSizeBytes = DEFAULT_DESIRED_BUNDLE_SIZE_BYTES; - SourceSplitOptions splitOptions = request.getOptions(); - if (splitOptions != null && splitOptions.getDesiredBundleSizeBytes() != null) { - desiredBundleSizeBytes = splitOptions.getDesiredBundleSizeBytes(); - } - - // Try generating initial splits normally. - SourceSplitResponse splits = performSplit(source, options, desiredBundleSizeBytes); - long serializedSize = DataflowApiUtils.computeSerializedSizeBytes(splits); - - // If split response is too large, scale desired size for expected DATAFLOW_API_SIZE_BYTES/2. - if (serializedSize > apiByteLimit) { - double expansion = 2 * (double) serializedSize / apiByteLimit; - long expandedBundleSizeBytes = (long) (desiredBundleSizeBytes * expansion); - LOG.warn( - "Splitting source {} into bundles of estimated size {} bytes produced {} bundles, which" - + " have total serialized size {} bytes. As this is too large for the Google Cloud" - + " Dataflow API, retrying splitting once with increased desiredBundleSizeBytes {}" - + " to reduce the number of splits.", - source, - desiredBundleSizeBytes, - splits.getBundles().size(), - serializedSize, - expandedBundleSizeBytes); - splits = performSplit(source, options, expandedBundleSizeBytes); - } - - return new SourceOperationResponse().setSplit(splits); - } - - /** - * Factory to create a {@link WorkerCustomSources} from a Dataflow API - * source specification. - */ - public static class Factory implements ReaderFactory { - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - // The parameter "coder" is deliberately never used. It is an artifact of ReaderFactory: - // some readers need a coder, some don't (i.e. for some it doesn't even make sense), - // but ReaderFactory passes it to all readers anyway. - return WorkerCustomSources.create(spec, options, executionContext); - } - } - - public static NativeReader> create( - final CloudObject spec, final PipelineOptions options, ExecutionContext executionContext) - throws Exception { - - @SuppressWarnings("unchecked") - final Source source = (Source) deserializeFromCloudSource(spec); - - if (source instanceof BoundedSource) { - @SuppressWarnings({"unchecked", "rawtypes"}) - NativeReader> reader = - (NativeReader) - new NativeReader>() { - @Override - public NativeReaderIterator> iterator() throws IOException { - return new BoundedReaderIterator<>( - ((BoundedSource) source).createReader(options)); - } - }; - return reader; - } else if (source instanceof UnboundedSource) { - @SuppressWarnings({"unchecked", "rawtypes"}) - NativeReader> reader = - (NativeReader) - new UnboundedReader( - options, spec, (StreamingModeExecutionContext) executionContext); - return reader; - } else { - throw new IllegalArgumentException("Unexpected source kind: " + source.getClass()); - } - } - - private static final ByteString firstSplitKey = ByteString.copyFromUtf8("0000000000000001"); - - public static boolean isFirstUnboundedSourceSplit(ByteString splitKey) { - return splitKey.equals(firstSplitKey); - } - - /** - * {@link NativeReader} for reading from {@link UnboundedSource UnboundedSources}. - */ - private static class UnboundedReader - extends NativeReader>> { - private final PipelineOptions options; - private final CloudObject spec; - private final StreamingModeExecutionContext context; - - UnboundedReader( - PipelineOptions options, CloudObject spec, StreamingModeExecutionContext context) { - this.options = options; - this.spec = spec; - this.context = context; - } - - @Override - @SuppressWarnings("unchecked") - public NativeReaderIterator>> iterator() { - UnboundedSource.UnboundedReader reader = - (UnboundedSource.UnboundedReader) context.getCachedReader(); - final boolean started = reader != null; - if (reader == null) { - String key = context.getSerializedKey().toStringUtf8(); - // Key is expected to be a zero-padded integer representing the split index. - int splitIndex = Integer.parseInt(key.substring(0, 16), 16) - 1; - - UnboundedSource splitSource = parseSource(splitIndex); - - UnboundedSource.CheckpointMark checkpoint = null; - if (splitSource.getCheckpointMarkCoder() != null) { - checkpoint = context.getReaderCheckpoint(splitSource.getCheckpointMarkCoder()); - } - - reader = splitSource.createReader(options, checkpoint); - } - - context.setActiveReader(reader); - - return new UnboundedReaderIterator<>(reader, started); - } - - @Override - public boolean supportsRestart() { - return true; - } - - @SuppressWarnings("unchecked") - private UnboundedSource parseSource(int index) { - List serializedSplits = null; - try { - serializedSplits = getStrings(spec, SERIALIZED_SOURCE_SPLITS, null); - } catch (Exception e) { - throw new RuntimeException("Parsing serialized source splits failed: ", e); - } - checkArgument(serializedSplits != null, "UnboundedSource object did not contain splits"); - checkArgument( - index < serializedSplits.size(), - "UnboundedSource splits contained too few splits. Requested index was %s, size was %s", - index, - serializedSplits.size()); - Object rawSource = deserializeFromByteArray( - decodeBase64(serializedSplits.get(index)), "UnboundedSource split"); - if (!(rawSource instanceof UnboundedSource)) { - throw new IllegalArgumentException("Expected UnboundedSource, got " + rawSource.getClass()); - } - return (UnboundedSource) rawSource; - } - } - - private static SourceSplitResponse performSplit( - BoundedSource source, PipelineOptions options, long desiredBundleSizeBytes) - throws Exception { - LOG.debug("Splitting source {} into bundles of size {}", source, desiredBundleSizeBytes); - - List> bundles = - ((BoundedSource) source).splitIntoBundles(desiredBundleSizeBytes, options); - List splits = new ArrayList<>(bundles.size()); - - // Produce simple independent, unsplittable bundles with no metadata attached. - LOG.debug("Splitting produced {} bundles", bundles.size()); - for (BoundedSource split : bundles) { - try { - split.validate(); - } catch (Exception e) { - throw new IllegalArgumentException( - String.format( - "Splitting a valid source produced an invalid source." - + "\nOriginal source: %s\nInvalid source: %s", - source, - split), - e); - } - - splits.add( - new DerivedSource() - .setDerivationMode("SOURCE_DERIVATION_MODE_INDEPENDENT") - .setSource(serializeToCloudSource(split, options).setDoesNotNeedSplitting(true))); - } - - // Return all the splits in the SourceSplitResponse. - return new SourceSplitResponse() - .setBundles(splits) - .setOutcome("SOURCE_SPLIT_OUTCOME_SPLITTING_HAPPENED"); - } - - private static Source deserializeFromCloudSource(Map spec) throws Exception { - Source source = (Source) deserializeFromByteArray( - Base64.decodeBase64(getString(spec, SERIALIZED_SOURCE)), "Source"); - try { - source.validate(); - } catch (Exception e) { - LOG.error("Invalid source: {}", source, e); - throw e; - } - return source; - } - - public static void evaluateReadHelper( - Read.Bounded transform, DirectPipelineRunner.EvaluationContext context) { - try { - List> output = new ArrayList<>(); - BoundedSource source = transform.getSource(); - try (BoundedSource.BoundedReader reader = - source.createReader(context.getPipelineOptions())) { - for (boolean available = reader.start(); available; available = reader.advance()) { - output.add( - DirectPipelineRunner.ValueWithMetadata.of( - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp()))); - } - } - context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static class BoundedReaderIterator - extends NativeReader.NativeReaderIterator> { - private BoundedSource.BoundedReader reader; - - private BoundedReaderIterator(BoundedSource.BoundedReader reader) { - this.reader = reader; - } - - @Override - public boolean start() throws IOException { - try { - return reader.start(); - } catch (Exception e) { - throw new IOException( - "Failed to start reading from source: " + reader.getCurrentSource(), e); - } - } - - @Override - public boolean advance() throws IOException { - try { - return reader.advance(); - } catch (Exception e) { - throw new IOException( - "Failed to advance reader of source: " + reader.getCurrentSource(), e); - } - } - - @Override - public WindowedValue getCurrent() throws NoSuchElementException { - return WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp()); - } - - @Override - public void close() throws IOException { - reader.close(); - } - - @Override - public NativeReader.Progress getProgress() { - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - Double fractionConsumed = reader.getFractionConsumed(); - if (fractionConsumed != null) { - progress.setFractionConsumed(fractionConsumed); - } - return SourceTranslationUtils.cloudProgressToReaderProgress(progress); - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest request) { - ApproximateSplitRequest stopPosition = - SourceTranslationUtils.splitRequestToApproximateSplitRequest(request); - Double fractionConsumed = stopPosition.getFractionConsumed(); - if (fractionConsumed == null) { - // Only truncating at a fraction is currently supported. - LOG.info( - "Rejecting split request because custom sources only support splits at fraction: {}", - stopPosition); - return null; - } - BoundedSource original = reader.getCurrentSource(); - BoundedSource residual = reader.splitAtFraction(fractionConsumed); - if (residual == null) { - LOG.info("Rejecting split request because custom reader returned null residual source."); - return null; - } - // Try to catch some potential subclass implementation errors early. - BoundedSource primary = reader.getCurrentSource(); - if (original == primary) { - throw new IllegalStateException( - "Successful split did not change the current source: primary is identical to original" - + " (Source objects MUST be immutable): " + primary); - } - if (original == residual) { - throw new IllegalStateException( - "Successful split did not change the current source: residual is identical to original" - + " (Source objects MUST be immutable): " + residual); - } - try { - primary.validate(); - } catch (Exception e) { - throw new IllegalStateException( - "Successful split produced an illegal primary source. " - + "\nOriginal: " + original + "\nPrimary: " + primary + "\nResidual: " + residual); - } - try { - residual.validate(); - } catch (Exception e) { - throw new IllegalStateException( - "Successful split produced an illegal residual source. " - + "\nOriginal: " + original + "\nPrimary: " + primary + "\nResidual: " + residual); - } - return new BoundedSourceSplit(primary, residual); - } - - @Override - public double getRemainingParallelism() { - return Double.NaN; - } - } - - // Commit at least once every 10 seconds or 10k records. This keeps the watermark advancing - // smoothly, and ensures that not too much work will have to be reprocessed in the event of - // a crash. - @VisibleForTesting - static final int MAX_UNBOUNDED_BUNDLE_SIZE = 10000; - @VisibleForTesting - static final Duration MAX_UNBOUNDED_BUNDLE_READ_TIME = Duration.standardSeconds(10); - - private static class UnboundedReaderIterator - extends NativeReader.NativeReaderIterator>> { - private final UnboundedSource.UnboundedReader reader; - private final boolean started; - private final Instant endTime; - private int elemsRead; - - private UnboundedReaderIterator(UnboundedSource.UnboundedReader reader, boolean started) { - this.reader = reader; - this.endTime = Instant.now().plus(MAX_UNBOUNDED_BUNDLE_READ_TIME); - this.elemsRead = 0; - this.started = started; - } - - @Override - public boolean start() throws IOException { - if (started) { - // This is a reader that has been restored from the unbounded reader cache. - // It has already been started, so this call to start() should delegate - // to advance() instead. - return advance(); - } - try { - if (!reader.start()) { - return false; - } - } catch (Exception e) { - throw new IOException( - "Failed to start reading from source: " + reader.getCurrentSource(), e); - } - elemsRead++; - return true; - } - - @Override - public boolean advance() throws IOException { - if (elemsRead >= MAX_UNBOUNDED_BUNDLE_SIZE - || Instant.now().isAfter(endTime)) { - return false; - } - - // Backoff starting at 100ms, for approximately 1s total. 100+150+225+337.5~=1000. - BackOff backoff = new AttemptBoundedExponentialBackOff(5, 100); - while (true) { - try { - if (reader.advance()) { - elemsRead++; - return true; - } - } catch (Exception e) { - throw new IOException("Failed to advance source: " + reader.getCurrentSource(), e); - } - long nextBackoff = backoff.nextBackOffMillis(); - if (nextBackoff == BackOff.STOP) { - return false; - } - try { - Thread.sleep(nextBackoff); - } catch (InterruptedException e) { - // ignore. - } - } - } - - @Override - public WindowedValue> getCurrent() throws NoSuchElementException { - WindowedValue result = - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp()); - return result.withValue( - new ValueWithRecordId<>(result.getValue(), reader.getCurrentRecordId())); - } - - @Override - public void close() {} - - @Override - public NativeReader.Progress getProgress() { - return null; - } - - @Override - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest request) { - return null; - } - - @Override - public double getRemainingParallelism() { - return Double.NaN; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java deleted file mode 100644 index 7cd5f82340..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerOrElement.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.worker.KeyedWorkItems.FakeKeyedWorkItemCoder; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -/** - * Empty class which exists because the back end will sometimes insert uses of - * {@code com.google.cloud.dataflow.sdk.util.TimerOrElement$TimerOrElementCoder} and we'd like to be - * able to rename/move that without breaking things. - */ -public class TimerOrElement { - - // TimerOrElement should never be created. - private TimerOrElement() {} - - /** - * Empty class which exists because the back end will sometimes insert uses of - * {@code com.google.cloud.dataflow.sdk.util.TimerOrElement$TimerOrElementCoder} and we'd like to - * be able to rename/move that without breaking things. - */ - public static class TimerOrElementCoder extends FakeKeyedWorkItemCoder { - - private TimerOrElementCoder(Coder elemCoder) { - super(elemCoder); - } - - public static TimerOrElementCoder of(Coder elemCoder) { - return new TimerOrElementCoder<>(elemCoder); - } - - @JsonCreator - public static TimerOrElementCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List components) { - return of((Coder) components.get(0)); - } - } -} From c27412e86090686afa60418e2489bd9cbed68919 Mon Sep 17 00:00:00 2001 From: klk Date: Sat, 6 Feb 2016 16:32:51 -0800 Subject: [PATCH 094/751] Move Windmill-specific code and dependents to worker module ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114037017 --- .../MetricTrackingWindmillServerStub.java | 66 -- .../sdk/runners/worker/StateFetcher.java | 232 ----- .../worker/WindmillReaderIteratorBase.java | 71 -- .../runners/worker/WindmillStateCache.java | 312 ------- .../worker/WindmillStateInternals.java | 848 ------------------ .../runners/worker/WindmillStateReader.java | 657 -------------- .../sdk/runners/worker/WindmillTimeUtils.java | 106 --- .../worker/windmill/WindmillServerStub.java | 45 - 8 files changed, 2337 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MetricTrackingWindmillServerStub.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcher.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillTimeUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/windmill/WindmillServerStub.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MetricTrackingWindmillServerStub.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MetricTrackingWindmillServerStub.java deleted file mode 100644 index ba96c473b7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/MetricTrackingWindmillServerStub.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServerStub; -import com.google.cloud.dataflow.sdk.util.MemoryMonitor; - -import java.io.PrintWriter; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Wrapper around a {@link WindmillServerStub} that tracks metrics for the number of in-flight - * requests and throttles requests when memory pressure is high. - */ -public class MetricTrackingWindmillServerStub { - private final AtomicInteger activeSideInputs = new AtomicInteger(); - private final AtomicInteger activeStateReads = new AtomicInteger(); - private final WindmillServerStub server; - private final MemoryMonitor gcThrashingMonitor; - - public MetricTrackingWindmillServerStub( - WindmillServerStub server, MemoryMonitor gcThrashingMonitor) { - this.server = server; - this.gcThrashingMonitor = gcThrashingMonitor; - } - - public Windmill.GetDataResponse getStateData(Windmill.GetDataRequest request) { - gcThrashingMonitor.waitForResources("GetStateData"); - activeStateReads.getAndIncrement(); - try { - return server.getData(request); - } finally { - activeStateReads.getAndDecrement(); - } - } - - public Windmill.GetDataResponse getSideInputData(Windmill.GetDataRequest request) { - gcThrashingMonitor.waitForResources("GetSideInputData"); - activeSideInputs.getAndIncrement(); - try { - return server.getData(request); - } finally { - activeSideInputs.getAndDecrement(); - } - } - - public void printHtml(PrintWriter writer) { - writer.println("Active Fetches:"); - writer.println(" Side Inputs: " + activeSideInputs.get()); - writer.println(" State Reads: " + activeStateReads.get()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcher.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcher.java deleted file mode 100644 index 3f2aa38adc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StateFetcher.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Supplier; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.Weigher; -import com.google.protobuf.ByteString; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; -import java.util.Objects; -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -/** - * Class responsible for fetching state from the windmill server. - */ -class StateFetcher { - private static final Logger LOG = LoggerFactory.getLogger(StateFetcher.class); - - private Cache sideInputCache; - private MetricTrackingWindmillServerStub server; - private long bytesRead = 0L; - - public StateFetcher(MetricTrackingWindmillServerStub server) { - this(server, CacheBuilder - .newBuilder() - .maximumWeight(100000000 /* 100 MB */) - .expireAfterWrite(1, TimeUnit.MINUTES) - .weigher(new Weigher() { - @Override - public int weigh(SideInputId id, SideInputCacheEntry entry) { - return entry.encodedSize; - } - }) - .build()); - } - - public StateFetcher(MetricTrackingWindmillServerStub server, - Cache sideInputCache) { - this.server = server; - this.sideInputCache = sideInputCache; - } - - /** - * Returns a view of the underlying cache that keeps track of bytes read separately. - */ - public StateFetcher byteTrackingView() { - return new StateFetcher(server, sideInputCache); - } - - public long getBytesRead() { - return bytesRead; - } - - /** - * Indicates the caller's knowledge of whether a particular side input has been computed. - */ - public enum SideInputState { - CACHED_IN_WORKITEM, KNOWN_READY, UNKNOWN; - } - - /** - * Fetch the given side input, storing it in a process-level cache. - * - *

      If state is KNOWN_READY, attempt to fetch the data regardless of whether a - * not-ready entry was cached. - */ - public T fetchSideInput(final PCollectionView view, - final SideWindowT sideWindow, final String stateFamily, SideInputState state, - final Supplier scopedReadStateSupplier) { - final SideInputId id = new SideInputId(view.getTagInternal(), sideWindow); - - Callable fetchCallable = new Callable() { - @Override - public SideInputCacheEntry call() throws Exception { - @SuppressWarnings("unchecked") - WindowingStrategy sideWindowStrategy = - (WindowingStrategy) view.getWindowingStrategyInternal(); - - Coder windowCoder = sideWindowStrategy.getWindowFn().windowCoder(); - - ByteString.Output windowStream = ByteString.newOutput(); - windowCoder.encode(sideWindow, windowStream, Coder.Context.OUTER); - - @SuppressWarnings("unchecked") - Windmill.GlobalDataRequest request = - Windmill.GlobalDataRequest.newBuilder() - .setDataId(Windmill.GlobalDataId.newBuilder() - .setTag(view.getTagInternal().getId()) - .setVersion(windowStream.toByteString()) - .build()) - .setStateFamily(stateFamily) - .setExistenceWatermarkDeadline(WindmillTimeUtils.harnessToWindmillTimestamp( - sideWindowStrategy - .getTrigger().getSpec() - .getWatermarkThatGuaranteesFiring(sideWindow))) - .build(); - - Windmill.GetDataResponse response; - try (StateSampler.ScopedState scope = scopedReadStateSupplier.get()) { - response = server.getSideInputData( - Windmill.GetDataRequest.newBuilder() - .addGlobalDataFetchRequests(request) - .addGlobalDataToFetch(request.getDataId()) - .build()); - } - - Windmill.GlobalData data = response.getGlobalData(0); - bytesRead += data.getSerializedSize(); - - Iterable> rawData; - if (data.getIsReady()) { - if (data.getData().size() > 0) { - rawData = view.getCoderInternal().decode( - data.getData().newInput(), Coder.Context.OUTER); - } else { - rawData = Collections.emptyList(); - } - - return new SideInputCacheEntry( - view.fromIterableInternal(rawData), data.getData().size()); - } else { - return SideInputCacheEntry.notReady(); - } - } - }; - - try { - if (state == SideInputState.KNOWN_READY) { - SideInputCacheEntry entry = sideInputCache.getIfPresent(id); - if (entry == null) { - return (T) sideInputCache.get(id, fetchCallable).value; - } else if (!entry.isReady()) { - // Invalidate the existing not-ready entry. This must be done atomically - // so that another thread doesn't replace the entry with a ready entry, which - // would then be deleted here. - synchronized (entry) { - SideInputCacheEntry newEntry = sideInputCache.getIfPresent(id); - if (newEntry != null && !newEntry.isReady()) { - sideInputCache.invalidate(id); - } - } - - return (T) sideInputCache.get(id, fetchCallable).value; - } else { - return (T) entry.value; - } - } else { - return (T) sideInputCache.get(id, fetchCallable).value; - } - } catch (Exception e) { - LOG.error("Fetch failed: ", e); - throw new RuntimeException("Exception while fetching side input: ", e); - } - } - - /** - * Struct representing a side input for a particular window. - */ - static class SideInputId { - private final TupleTag tag; - private final BoundedWindow window; - - public SideInputId(TupleTag tag, BoundedWindow window) { - this.tag = tag; - this.window = window; - } - - @Override - public boolean equals(Object other) { - if (other instanceof SideInputId) { - SideInputId otherId = (SideInputId) other; - return tag.equals(otherId.tag) && window.equals(otherId.window); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(tag, window); - } - } - - /** - * Entry in the side input cache that stores the value (null if not ready), and - * the encoded size of the value. - */ - static class SideInputCacheEntry { - public final Object value; - public final int encodedSize; - - public SideInputCacheEntry(Object value, int encodedSize) { - this.value = value; - this.encodedSize = encodedSize; - } - - public static SideInputCacheEntry notReady() { - return new SideInputCacheEntry(null, 0); - } - - public boolean isReady() { - return value != null; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java deleted file mode 100644 index 9a57621803..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillReaderIteratorBase.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.io.IOException; -import java.util.NoSuchElementException; - -/** - * Base class for iterators that decode messages from bundles inside a {@link Windmill.WorkItem}. - */ -public abstract class WindmillReaderIteratorBase - extends NativeReader.NativeReaderIterator> { - private Windmill.WorkItem work; - private int bundleIndex = 0; - private int messageIndex = -1; - private WindowedValue current; - - protected WindmillReaderIteratorBase(Windmill.WorkItem work) { - this.work = work; - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - if (bundleIndex == work.getMessageBundlesCount() - || messageIndex == work.getMessageBundles(bundleIndex).getMessagesCount()) { - return false; - } - ++messageIndex; - for (; bundleIndex < work.getMessageBundlesCount(); ++bundleIndex, messageIndex = 0) { - Windmill.InputMessageBundle bundle = work.getMessageBundles(bundleIndex); - if (messageIndex < bundle.getMessagesCount()) { - current = decodeMessage(bundle.getMessages(messageIndex)); - return true; - } - } - current = null; - return false; - } - - protected abstract WindowedValue decodeMessage(Windmill.Message message) throws IOException; - - @Override - public WindowedValue getCurrent() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return current; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java deleted file mode 100644 index 9849ed8695..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.runners.worker.status.BaseStatusServlet; -import com.google.cloud.dataflow.sdk.runners.worker.status.StatusDataProvider; -import com.google.cloud.dataflow.sdk.util.Weighted; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.RemovalCause; -import com.google.common.cache.RemovalListener; -import com.google.common.cache.RemovalNotification; -import com.google.common.cache.Weigher; -import com.google.protobuf.ByteString; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Process-wide cache of per-key state. - */ -public class WindmillStateCache implements StatusDataProvider { - // Estimate of overhead per StateId. - private static final int PER_STATE_ID_OVERHEAD = 20; - // Initial size of hash tables per entry. - private static final int INITIAL_HASH_MAP_CAPACITY = 4; - // Overhead of each hash map entry. - private static final int HASH_MAP_ENTRY_OVERHEAD = 16; - // Overhead of each cache entry. Two longs, plus a hash table. - private static final int PER_CACHE_ENTRY_OVERHEAD = - 16 + HASH_MAP_ENTRY_OVERHEAD * INITIAL_HASH_MAP_CAPACITY; - - private Cache stateCache; - private int displayedWeight = 0; // Only used for status pages and unit tests. - - public WindmillStateCache() { - final Weigher weigher = Weighers.weightedKeysAndValues(); - - stateCache = - CacheBuilder.newBuilder() - .maximumWeight(100000000 /* 100 MB */) - .recordStats() - .weigher(weigher) - .removalListener(new RemovalListener() { - @Override - public void onRemoval(RemovalNotification removal) { - if (removal.getCause() != RemovalCause.REPLACED) { - displayedWeight -= weigher.weigh(removal.getKey(), removal.getValue()); - } - } - }) - .build(); - } - - public long getWeight() { - return displayedWeight; - } - - /** - * Per-computation view of the state cache. - */ - public class ForComputation { - private final String computation; - private ForComputation(String computation) { - this.computation = computation; - } - - /** - * Returns a per-computation, per-key view of the state cache. - */ - public ForKey forKey(ByteString key, String stateFamily, long cacheToken) { - return new ForKey(computation, key, stateFamily, cacheToken); - } - } - - /** - * Per-computation, per-key view of the state cache. - */ - public class ForKey { - private final String computation; - private final ByteString key; - private final String stateFamily; - private final long cacheToken; - - private ForKey(String computation, ByteString key, String stateFamily, long cacheToken) { - this.computation = computation; - this.key = key; - this.stateFamily = stateFamily; - this.cacheToken = cacheToken; - } - - public T get(StateNamespace namespace, StateTag address) { - return WindmillStateCache.this.get( - computation, key, stateFamily, cacheToken, namespace, address); - } - - public void put( - StateNamespace namespace, StateTag address, T value, long weight) { - WindmillStateCache.this.put( - computation, key, stateFamily, cacheToken, namespace, address, value, weight); - } - } - - /** - * Returns a per-computation view of the state cache. - */ - public ForComputation forComputation(String computation) { - return new ForComputation(computation); - } - - private T get(String computation, ByteString processingKey, String stateFamily, - long token, StateNamespace namespace, StateTag address) { - StateId id = new StateId(computation, processingKey, stateFamily, namespace); - StateCacheEntry entry = stateCache.getIfPresent(id); - if (entry == null) { - return null; - } - if (entry.getToken() != token) { - stateCache.invalidate(id); - return null; - } - return entry.get(namespace, address); - } - - private void put(String computation, ByteString processingKey, - String stateFamily, long token, StateNamespace namespace, StateTag address, T value, - long weight) { - StateId id = new StateId(computation, processingKey, stateFamily, namespace); - StateCacheEntry entry = stateCache.getIfPresent(id); - if (entry == null || entry.getToken() != token) { - entry = new StateCacheEntry(token); - this.displayedWeight += id.getWeight(); - this.displayedWeight += entry.getWeight(); - } - this.displayedWeight += entry.put(namespace, address, value, weight); - // Always add back to the cache to update the weight. - stateCache.put(id, entry); - } - - /** - * Struct identifying a cache entry that contains all data for a key and namespace. - */ - private static class StateId implements Weighted { - public final String computation; - public final ByteString processingKey; - public final String stateFamily; - public final Object namespaceKey; - - public StateId(String computation, ByteString processingKey, String stateFamily, - StateNamespace namespace) { - this.computation = computation; - this.processingKey = processingKey; - this.stateFamily = stateFamily; - this.namespaceKey = namespace.getCacheKey(); - } - - @Override - public boolean equals(Object other) { - if (other instanceof StateId) { - StateId otherId = (StateId) other; - return computation.equals(otherId.computation) - && processingKey.equals(otherId.processingKey) - && stateFamily.equals(otherId.stateFamily) - && namespaceKey.equals(otherId.namespaceKey); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(computation, processingKey, namespaceKey); - } - - @Override - public long getWeight() { - return processingKey.size() + PER_STATE_ID_OVERHEAD; - } - } - - /** - * Entry in the state cache that stores a map of values and a token representing the - * validity of the values. - */ - private static class StateCacheEntry implements Weighted { - private final long token; - private final Map, WeightedValue> values; - private long weight; - - public StateCacheEntry(long token) { - this.values = new HashMap<>(INITIAL_HASH_MAP_CAPACITY); - this.token = token; - this.weight = 0; - } - - @SuppressWarnings("unchecked") - public T get(StateNamespace namespace, StateTag tag) { - WeightedValue weightedValue = - (WeightedValue) values.get(new NamespacedTag(namespace, tag)); - return weightedValue == null ? null : weightedValue.value; - } - - public long put( - StateNamespace namespace, StateTag tag, T value, long weight) { - WeightedValue weightedValue = - (WeightedValue) values.get(new NamespacedTag(namespace, tag)); - long weightDelta = 0; - if (weightedValue == null) { - weightedValue = new WeightedValue(); - weightDelta += HASH_MAP_ENTRY_OVERHEAD; - } else { - weightDelta -= weightedValue.weight; - } - weightedValue.value = value; - weightedValue.weight = weight; - weightDelta += weight; - this.weight += weightDelta; - values.put(new NamespacedTag(namespace, tag), weightedValue); - return weightDelta; - } - - @Override - public long getWeight() { - return weight + PER_CACHE_ENTRY_OVERHEAD; - } - - public long getToken() { - return token; - } - - private static class NamespacedTag { - private final StateNamespace namespace; - private final StateTag tag; - NamespacedTag(StateNamespace namespace, StateTag tag) { - this.namespace = namespace; - this.tag = tag; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof NamespacedTag)) { - return false; - } - NamespacedTag that = (NamespacedTag) other; - return namespace.equals(that.namespace) && tag.equals(that.tag); - } - - @Override - public int hashCode() { - return Objects.hash(namespace, tag); - } - } - - private static class WeightedValue { - public long weight = 0; - public T value = null; - } - } - - /** - * Print summary statistics of the cache to the given {@link PrintWriter}. - */ - @Override - public void appendSummaryHtml(PrintWriter response) { - response.println("Cache Stats:

    Hit RatioEvictionsSizeWeight
    "); - response.println( - ""); - response.println(""); - response.println(""); - response.println(""); - response.println(""); - response.println("
    Hit RatioEvictionsSizeWeight
    " + stateCache.stats().hitRate() + "" + stateCache.stats().evictionCount() + "" + stateCache.size() + "" + getWeight() + "

    "); - } - - - public BaseStatusServlet statusServlet() { - return new BaseStatusServlet("/cachez") { - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - - PrintWriter writer = response.getWriter(); - writer.println("

    Cache Information

    "); - appendSummaryHtml(writer); - } - }; - } - - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternals.java deleted file mode 100644 index 87eaa1f58f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateInternals.java +++ /dev/null @@ -1,848 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.WorkItemCommitRequest; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.util.Weighted; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; -import com.google.cloud.dataflow.sdk.util.state.MergingStateInternals; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateTable; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.ValueState; -import com.google.cloud.dataflow.sdk.util.state.WatermarkStateInternal; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.base.Supplier; -import com.google.common.base.Throwables; -import com.google.common.collect.Iterables; -import com.google.common.collect.Iterators; -import com.google.common.util.concurrent.Futures; -import com.google.protobuf.ByteString; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import javax.annotation.concurrent.NotThreadSafe; - -/** - * Implementation of {@link StateInternals} using Windmill to manage the underlying data. - */ -class WindmillStateInternals extends MergingStateInternals { - private static class CachingStateTable extends StateTable { - private final String stateFamily; - private final WindmillStateReader reader; - private final WindmillStateCache.ForKey cache; - private final Supplier scopedReadStateSupplier; - - public CachingStateTable(String stateFamily, - WindmillStateReader reader, WindmillStateCache.ForKey cache, - Supplier scopedReadStateSupplier) { - this.stateFamily = stateFamily; - this.reader = reader; - this.cache = cache; - this.scopedReadStateSupplier = scopedReadStateSupplier; - } - - @Override - protected StateBinder binderForNamespace(final StateNamespace namespace) { - // Look up state objects in the cache or create new ones if not found. The state will - // be added to the cache in persist(). - return new StateBinder() { - @Override - public BagState bindBag(StateTag> address, Coder elemCoder) { - WindmillBag result = (WindmillBag) cache.get(namespace, address); - if (result == null) { - result = new WindmillBag(namespace, address, stateFamily, elemCoder); - } - result.initializeForWorkItem(reader, scopedReadStateSupplier); - return result; - } - - @Override - public WatermarkStateInternal bindWatermark( - StateTag address, OutputTimeFn outputTimeFn) { - WindmillWatermarkState result = (WindmillWatermarkState) cache.get(namespace, address); - if (result == null) { - result = new WindmillWatermarkState(namespace, address, stateFamily, outputTimeFn); - } - result.initializeForWorkItem(reader, scopedReadStateSupplier); - return result; - } - - @Override - public CombiningValueStateInternal - bindCombiningValue(StateTag> address, - Coder accumCoder, CombineFn combineFn) { - WindmillCombiningValue result = new WindmillCombiningValue<>( - namespace, address, stateFamily, accumCoder, combineFn, cache); - result.initializeForWorkItem(reader, scopedReadStateSupplier); - return result; - } - - @Override - public ValueState bindValue(StateTag> address, Coder coder) { - WindmillValue result = (WindmillValue) cache.get(namespace, address); - if (result == null) { - result = new WindmillValue(namespace, address, stateFamily, coder); - } - result.initializeForWorkItem(reader, scopedReadStateSupplier); - return result; - } - }; - } - }; - - private WindmillStateCache.ForKey cache; - Supplier scopedReadStateSupplier; - private StateTable workItemState; - - public WindmillStateInternals(String stateFamily, WindmillStateReader reader, - WindmillStateCache.ForKey cache, Supplier scopedReadStateSupplier) { - this.cache = cache; - this.scopedReadStateSupplier = scopedReadStateSupplier; - this.workItemState = new CachingStateTable(stateFamily, reader, cache, scopedReadStateSupplier); - } - - public void persist(final Windmill.WorkItemCommitRequest.Builder commitBuilder) { - List> commitsToMerge = new ArrayList<>(); - - // Call persist on each first, which may schedule some futures for reading. - for (State location : workItemState.values()) { - if (!(location instanceof WindmillState)) { - throw new IllegalStateException(String.format( - "%s wasn't created by %s -- unable to persist it", - location.getClass().getSimpleName(), - getClass().getSimpleName())); - } - - try { - commitsToMerge.add(((WindmillState) location).persist(cache)); - } catch (IOException e) { - throw new RuntimeException("Unable to persist state", e); - } - } - - // Clear out the map of already retrieved state instances. - workItemState.clear(); - - try (StateSampler.ScopedState scope = scopedReadStateSupplier.get()) { - for (Future commitFuture : commitsToMerge) { - commitBuilder.mergeFrom(commitFuture.get()); - } - } catch (ExecutionException | InterruptedException exc) { - throw new RuntimeException("Failed to retrieve Windmill state during persist()", exc); - } - } - - /** - * Encodes the given namespace and address as {@code <namespace>+<address>}. - */ - @VisibleForTesting - static ByteString encodeKey(StateNamespace namespace, StateTag address) { - try { - // Use ByteString.Output rather than concatenation and String.format. We build these keys - // a lot, and this leads to better performance results. See associated benchmarks. - ByteString.Output stream = ByteString.newOutput(); - OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8); - - // stringKey starts and ends with a slash. We separate it from the - // StateTag ID by a '+' (which is guaranteed not to be in the stringKey) because the - // ID comes from the user. - namespace.appendTo(writer); - writer.write('+'); - address.appendTo(writer); - writer.flush(); - return stream.toByteString(); - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - - /** - * Abstract base class for all Windmill state. - * - *

    Note that these are not thread safe; each state object is associated with a key - * and thus only accessed by a single thread at once. - */ - @NotThreadSafe - private abstract static class WindmillState { - protected Supplier scopedReadStateSupplier; - protected WindmillStateReader reader; - - /** - * Return an asynchronously computed {@link WorkItemCommitRequest}. The request should - * be of a form that can be merged with others (only add to repeated fields). - */ - abstract Future persist(WindmillStateCache.ForKey cache) - throws IOException; - - void initializeForWorkItem( - WindmillStateReader reader, Supplier scopedReadStateSupplier) { - this.reader = reader; - this.scopedReadStateSupplier = scopedReadStateSupplier; - } - - StateSampler.ScopedState scopedReadState() { - return scopedReadStateSupplier.get(); - } - } - - /** - * Base class for implementations of {@link WindmillState} where the {@link #persist} call does - * not require any asynchronous reading. - */ - private abstract static class SimpleWindmillState extends WindmillState { - @Override - public final Future persist(WindmillStateCache.ForKey cache) - throws IOException { - return Futures.immediateFuture(persistDirectly(cache)); - } - - /** - * Returns a {@link WorkItemCommitRequest} that can be used to persist this state to - * Windmill. - */ - protected abstract WorkItemCommitRequest persistDirectly(WindmillStateCache.ForKey cache) - throws IOException; - } - - @Override - public T state(StateNamespace namespace, StateTag address) { - return workItemState.get(namespace, address); - } - - private static class WindmillValue extends SimpleWindmillState implements ValueState { - private final StateNamespace namespace; - private final StateTag> address; - private final ByteString stateKey; - private final String stateFamily; - private final Coder coder; - - /** Whether we've modified the value since creation of this state. */ - private boolean modified = false; - /** Whether the in memory value is the true value. */ - private boolean valueIsKnown = false; - private T value; - - private WindmillValue(StateNamespace namespace, StateTag> address, - String stateFamily, Coder coder) { - this.namespace = namespace; - this.address = address; - this.stateKey = encodeKey(namespace, address); - this.stateFamily = stateFamily; - this.coder = coder; - } - - @Override - public void clear() { - modified = true; - valueIsKnown = true; - value = null; - } - - @Override - public StateContents get() { - final Future future = valueIsKnown ? Futures.immediateFuture(value) - : reader.valueFuture(stateKey, stateFamily, coder); - - return new StateContents() { - @Override - public T read() { - try (StateSampler.ScopedState scope = scopedReadState()) { - valueIsKnown = true; - return future.get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException("Unable to read value from state", e); - } - } - }; - } - - @Override - public void set(T value) { - modified = true; - valueIsKnown = true; - this.value = value; - } - - @Override - protected WorkItemCommitRequest persistDirectly(WindmillStateCache.ForKey cache) - throws IOException { - if (!modified) { - // No in-memory changes. - return WorkItemCommitRequest.newBuilder().buildPartial(); - } - - ByteString.Output stream = ByteString.newOutput(); - if (value != null) { - coder.encode(value, stream, Coder.Context.OUTER); - } - ByteString encoded = stream.toByteString(); - - WorkItemCommitRequest.Builder commitBuilder = WorkItemCommitRequest.newBuilder(); - // Update the entry of the cache with the new value and change in encoded size. - cache.put(namespace, address, this, encoded.size()); - - modified = false; - - commitBuilder - .addValueUpdatesBuilder() - .setTag(stateKey) - .setStateFamily(stateFamily) - .getValueBuilder() - .setData(encoded) - .setTimestamp(Long.MAX_VALUE); - - return commitBuilder.buildPartial(); - } - } - - private static class WindmillBag extends SimpleWindmillState implements BagState { - - private final StateNamespace namespace; - private final StateTag> address; - private final ByteString stateKey; - private final String stateFamily; - private final Coder elemCoder; - - private boolean cleared; - // Cache of all values in this bag. Null if the persisted state is unknown. - private ConcatIterables cachedValues = null; - private List localAdditions = new ArrayList<>(); - private long encodedSize = 0; - - private WindmillBag(StateNamespace namespace, StateTag> address, String stateFamily, - Coder elemCoder) { - this.namespace = namespace; - this.address = address; - this.stateKey = encodeKey(namespace, address); - this.stateFamily = stateFamily; - this.elemCoder = elemCoder; - } - - @Override - public void clear() { - cleared = true; - cachedValues = new ConcatIterables(); - localAdditions.clear(); - encodedSize = 0; - } - - private Iterable fetchData(Future> persistedData) { - try (StateSampler.ScopedState scope = scopedReadState()) { - if (cachedValues != null) { - return cachedValues; - } - Iterable data = persistedData.get(); - if (data instanceof Weighted) { - // We have a known bounded amount of data; cache it. - cachedValues = new ConcatIterables(); - cachedValues.extendWith(data); - encodedSize = ((Weighted) data).getWeight(); - return cachedValues; - } else { - // This is an iterable that may not fit in memory at once; don't cache it. - return data; - } - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException("Unable to read state", e); - } - } - - public boolean valuesAreCached() { - return cachedValues != null; - } - - @Override - public StateContents> get() { - // If we clear after calling get() but before calling read(), technically we didn't need the - // underlying windmill read. But, we need to register the desire now if we aren't going to - // clear (in order to get it added to the prefetch). - final Future> persistedData = (cachedValues != null) - ? null - : reader.listFuture(stateKey, stateFamily, elemCoder); - - return new StateContents>() { - @Override - public Iterable read() { - return Iterables.concat(fetchData(persistedData), localAdditions); - } - }; - } - - @Override - public StateContents isEmpty() { - // If we clear after calling isEmpty() but before calling read(), technically we didn't need - // the underlying windmill read. But, we need to register the desire now if we aren't going to - // clear (in order to get it added to the prefetch). - final Future> persistedData = (cachedValues != null) - ? null - : reader.listFuture(stateKey, stateFamily, elemCoder); - - return new StateContents() { - @Override - public Boolean read() { - return Iterables.isEmpty(fetchData(persistedData)) && localAdditions.isEmpty(); - } - }; - } - - @Override - public void add(T input) { - localAdditions.add(input); - } - - @Override - public WorkItemCommitRequest persistDirectly(WindmillStateCache.ForKey cache) - throws IOException { - WorkItemCommitRequest.Builder commitBuilder = WorkItemCommitRequest.newBuilder(); - - if (cleared) { - commitBuilder.addListUpdatesBuilder() - .setTag(stateKey) - .setStateFamily(stateFamily) - .setEndTimestamp(Long.MAX_VALUE); - } - - if (!localAdditions.isEmpty()) { - byte[] zero = {0x0}; - Windmill.TagList.Builder listUpdatesBuilder = - commitBuilder.addListUpdatesBuilder().setTag(stateKey).setStateFamily(stateFamily); - for (T value : localAdditions) { - ByteString.Output stream = ByteString.newOutput(); - - // Windmill does not support empty data for tag list state; prepend a zero byte. - stream.write(zero); - - // Encode the value - elemCoder.encode(value, stream, Coder.Context.OUTER); - ByteString encoded = stream.toByteString(); - if (cachedValues != null) { - encodedSize += encoded.size() - 1; - } - - listUpdatesBuilder.addValuesBuilder() - .setData(encoded) - .setTimestamp(Long.MAX_VALUE); - } - } - - if (cachedValues != null) { - cachedValues.extendWith(localAdditions); - // Don't reuse the localAdditions object; we don't want future changes to it to modify the - // value of cachedValues. - localAdditions = new ArrayList(); - cache.put(namespace, address, this, encodedSize); - } else { - localAdditions.clear(); - } - cleared = false; - - return commitBuilder.buildPartial(); - } - } - - private static class ConcatIterables implements Iterable { - List> iterables; - - public ConcatIterables() { - this.iterables = new ArrayList<>(); - } - - public void extendWith(Iterable iterable) { - iterables.add(iterable); - } - - @Override - public Iterator iterator() { - return Iterators.concat( - Iterables.transform( - iterables, - new Function, Iterator>() { - @Override - public Iterator apply(Iterable iterable) { - return iterable.iterator(); - } - }) - .iterator()); - } - } - - private static class WindmillWatermarkState - extends WindmillState implements WatermarkStateInternal { - // The encoded size of an Instant. - private static final int ENCODED_SIZE = 8; - - private final OutputTimeFn outputTimeFn; - private final StateNamespace namespace; - private final StateTag address; - private final ByteString stateKey; - private final String stateFamily; - - private boolean cleared = false; - // The hold value, Optional.absent() if no hold, or null if unknown. - private Optional cachedValue = null; - private Instant localAdditions = null; - - private WindmillWatermarkState(StateNamespace namespace, - StateTag address, String stateFamily, - OutputTimeFn outputTimeFn) { - this.namespace = namespace; - this.address = address; - this.stateKey = encodeKey(namespace, address); - this.stateFamily = stateFamily; - this.outputTimeFn = outputTimeFn; - } - - @Override - public void clear() { - cleared = true; - cachedValue = Optional.absent(); - localAdditions = null; - } - - /** - * {@inheritDoc} - * - *

    Does nothing. There is only one hold and it is not extraneous. - * See {@link MergedWatermarkStateInternal} for a nontrivial implementation. - */ - @Override - public void releaseExtraneousHolds() { } - - @Override - public StateContents get() { - // If we clear after calling get() but before calling read(), technically we didn't need the - // underlying windmill read. But, we need to register the desire now if we aren't going to - // clear (in order to get it added to the prefetch). - final Future persistedData = (cachedValue != null) - ? Futures.immediateFuture(cachedValue.orNull()) - : reader.watermarkFuture(stateKey, stateFamily); - - return new StateContents() { - @Override - public Instant read() { - try (StateSampler.ScopedState scope = scopedReadState()) { - Instant persistedHold = persistedData.get(); - if (persistedHold == null || persistedHold.equals(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - cachedValue = Optional.absent(); - } else { - cachedValue = Optional.of(persistedHold); - } - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException("Unable to read state", e); - } - - if (localAdditions == null) { - return cachedValue.orNull(); - } else if (!cachedValue.isPresent()) { - return localAdditions; - } else { - return outputTimeFn.combine(localAdditions, cachedValue.get()); - } - } - }; - } - - @Override - public StateContents isEmpty() { - throw new UnsupportedOperationException(); - } - - @Override - public void add(Instant outputTime) { - localAdditions = (localAdditions == null) ? outputTime - : outputTimeFn.combine(outputTime, localAdditions); - } - - @Override - public Future persist(final WindmillStateCache.ForKey cache) { - Future result; - - if (!cleared && localAdditions == null) { - // Nothing to do - return Futures.immediateFuture(WorkItemCommitRequest.newBuilder().buildPartial()); - } else if (cleared && localAdditions == null) { - // Just clearing the persisted state; blind delete - WorkItemCommitRequest.Builder commitBuilder = WorkItemCommitRequest.newBuilder(); - commitBuilder.addWatermarkHoldsBuilder() - .setTag(stateKey) - .setStateFamily(stateFamily) - .setReset(true); - - result = Futures.immediateFuture(commitBuilder.buildPartial()); - } else if (cleared && localAdditions != null) { - // Since we cleared before adding, we can do a blind overwrite of persisted state - WorkItemCommitRequest.Builder commitBuilder = WorkItemCommitRequest.newBuilder(); - commitBuilder.addWatermarkHoldsBuilder() - .setTag(stateKey) - .setStateFamily(stateFamily) - .setReset(true) - .addTimestamps(WindmillTimeUtils.harnessToWindmillTimestamp(localAdditions)); - - cachedValue = Optional.of(localAdditions); - - result = Futures.immediateFuture(commitBuilder.buildPartial()); - } else if (!cleared && localAdditions != null) { - // Otherwise, we need to combine the local additions with the already persisted data - result = combineWithPersisted(); - } else { - throw new IllegalStateException("Unreachable condition"); - } - - return Futures.lazyTransform( - result, new Function() { - @Override - public WorkItemCommitRequest apply(WorkItemCommitRequest result) { - cleared = false; - localAdditions = null; - if (cachedValue != null) { - cache.put( - namespace, address, WindmillWatermarkState.this, ENCODED_SIZE); - } - return result; - } - }); - } - - /** - * Combines local additions with persisted data and mutates the {@code commitBuilder} - * to write the result. - */ - private Future combineWithPersisted() { - boolean windmillCanCombine = false; - - // If the combined output time depends only on the window, then we are just blindly adding - // the same value that may or may not already be present. This depends on the state only being - // used for one window. - windmillCanCombine |= outputTimeFn.dependsOnlyOnWindow(); - - // If the combined output time depends only on the earliest input timestamp, then because - // assignOutputTime is monotonic, the hold only depends on the earliest output timestamp - // (which is the value submitted as a watermark hold). The only way holds for later inputs - // can be redundant is if the are later (or equal) to the earliest. So taking the MIN - // implicitly, as Windmill does, has the desired behavior. - windmillCanCombine |= outputTimeFn.dependsOnlyOnEarliestInputTimestamp(); - - if (windmillCanCombine) { - // We do a blind write and let Windmill take the MIN - WorkItemCommitRequest.Builder commitBuilder = WorkItemCommitRequest.newBuilder(); - commitBuilder.addWatermarkHoldsBuilder() - .setTag(stateKey) - .setStateFamily(stateFamily) - .addTimestamps( - WindmillTimeUtils.harnessToWindmillTimestamp(localAdditions)); - - if (cachedValue != null) { - cachedValue = Optional.of(cachedValue.isPresent() - ? outputTimeFn.combine(cachedValue.get(), localAdditions) - : localAdditions); - } - - return Futures.immediateFuture(commitBuilder.buildPartial()); - } else { - // The non-fast path does a read-modify-write - return Futures.lazyTransform((cachedValue != null) - ? Futures.immediateFuture(cachedValue.orNull()) - : reader.watermarkFuture(stateKey, stateFamily), - new Function() { - @Override - public WorkItemCommitRequest apply(Instant priorHold) { - cachedValue = Optional.of((priorHold != null) - ? outputTimeFn.combine(priorHold, localAdditions) - : localAdditions); - - WorkItemCommitRequest.Builder commitBuilder = WorkItemCommitRequest.newBuilder(); - commitBuilder.addWatermarkHoldsBuilder() - .setTag(stateKey) - .setStateFamily(stateFamily) - .setReset(true) - .addTimestamps(WindmillTimeUtils.harnessToWindmillTimestamp(cachedValue.get())); - - return commitBuilder.buildPartial(); - } - }); - } - } - } - - private static class WindmillCombiningValue - extends WindmillState implements CombiningValueStateInternal { - private final WindmillBag bag; - private final CombineFn combineFn; - - /* We use a separate, in-memory AccumT rather than relying on the WindmillWatermarkBag's - * localAdditions, because we want to combine multiple InputT's to a single AccumT - * before adding it. - */ - private AccumT localAdditionsAccum; - private boolean hasLocalAdditions = false; - - private WindmillCombiningValue(StateNamespace namespace, - StateTag> address, String stateFamily, - Coder accumCoder, CombineFn combineFn, - WindmillStateCache.ForKey cache) { - StateTag> internalBagAddress = StateTags.convertToBagTagInternal(address); - WindmillBag cachedBag = - (WindmillBag) cache.get(namespace, internalBagAddress); - this.bag = - (cachedBag != null) - ? cachedBag - : new WindmillBag<>(namespace, internalBagAddress, stateFamily, accumCoder); - this.combineFn = combineFn; - this.localAdditionsAccum = combineFn.createAccumulator(); - } - - @Override - void initializeForWorkItem( - WindmillStateReader reader, Supplier scopedReadStateSupplier) { - super.initializeForWorkItem(reader, scopedReadStateSupplier); - this.bag.initializeForWorkItem(reader, scopedReadStateSupplier); - } - - @Override - public StateContents get() { - final StateContents accum = getAccum(); - return new StateContents() { - @Override - public OutputT read() { - return combineFn.extractOutput(accum.read()); - } - }; - } - - @Override - public void add(InputT input) { - hasLocalAdditions = true; - localAdditionsAccum = combineFn.addInput(localAdditionsAccum, input); - } - - @Override - public void clear() { - bag.clear(); - localAdditionsAccum = combineFn.createAccumulator(); - hasLocalAdditions = false; - } - - @Override - public Future persist(WindmillStateCache.ForKey cache) - throws IOException { - if (hasLocalAdditions) { - if (COMPACT_NOW.get().get() || bag.valuesAreCached()) { - // Implicitly clears the bag and combines local and persisted accumulators. - localAdditionsAccum = getAccum().read(); - } - bag.add(combineFn.compact(localAdditionsAccum)); - localAdditionsAccum = combineFn.createAccumulator(); - hasLocalAdditions = false; - } - - return bag.persist(cache); - } - - @Override - public StateContents getAccum() { - final StateContents> future = bag.get(); - - return new StateContents() { - @Override - public AccumT read() { - Iterable accums = Iterables.concat( - future.read(), Collections.singleton(localAdditionsAccum)); - - // Compact things - AccumT merged = combineFn.mergeAccumulators(accums); - bag.clear(); - localAdditionsAccum = merged; - hasLocalAdditions = true; - return merged; - } - }; - } - - @Override - public StateContents isEmpty() { - final StateContents isEmptyFuture = bag.isEmpty(); - - return new StateContents() { - @Override - public Boolean read() { - return !hasLocalAdditions && isEmptyFuture.read(); - } - }; - } - - - @Override - public void addAccum(AccumT accum) { - hasLocalAdditions = true; - localAdditionsAccum = combineFn.mergeAccumulators(Arrays.asList(localAdditionsAccum, accum)); - } - } - - @VisibleForTesting - static final ThreadLocal> COMPACT_NOW = - new ThreadLocal>() { - public Supplier initialValue() { - return new Supplier() { - /* The rate at which, on average, this will return true. */ - static final double RATE = 0.002; - Random random = new Random(); - long counter = nextSample(); - - private long nextSample() { - // Use geometric distribution to find next true value. - // This lets us avoid invoking random.nextDouble() on every call. - return (long) Math.floor(Math.log(random.nextDouble()) / Math.log(1 - RATE)); - } - - public Boolean get() { - counter--; - if (counter < 0) { - counter = nextSample(); - return true; - } else { - return false; - } - } - }; - } - }; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java deleted file mode 100644 index 53e9104074..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateReader.java +++ /dev/null @@ -1,657 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.TagList; -import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill.TagValue; -import com.google.cloud.dataflow.sdk.util.Weighted; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.base.Preconditions; -import com.google.common.collect.AbstractIterator; -import com.google.common.collect.ForwardingList; -import com.google.common.util.concurrent.ForwardingFuture; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.SettableFuture; -import com.google.protobuf.ByteString; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import javax.annotation.Nullable; - -/** - * Reads persistent state from {@link Windmill}. Returns {@code Future}s containing the data that - * has been read. Will not initiate a read until {@link Future#get} is called, at which point all - * the pending futures will be read. - */ -class WindmillStateReader { - /** - * Ideal maximum bytes in a TagList response. However, Windmill will always return - * at least one value if possible irrespective of this limit. - */ - public static final long MAX_LIST_BYTES = 8L << 20; // 8MB - - /** - * When combined with a key and computationId, represents the unique address for - * state managed by Windmill. - */ - private static class StateTag { - private enum Kind { - VALUE, - LIST, - WATERMARK; - } - - private final Kind kind; - private final ByteString tag; - private final String stateFamily; - - /** - * For {@link Kind#LIST} kinds: A previous 'continuation_token' returned by Windmill to signal - * the resulting list was incomplete. Sending that token will request the next page of values. - * Null for first request. - * - *

    Null for other kinds. - */ - @Nullable - private final ByteString requestToken; - - private StateTag( - Kind kind, ByteString tag, String stateFamily, @Nullable ByteString requestToken) { - this.kind = kind; - this.tag = tag; - this.stateFamily = Preconditions.checkNotNull(stateFamily); - this.requestToken = requestToken; - } - - private StateTag(Kind kind, ByteString tag, String stateFamily) { - this(kind, tag, stateFamily, null); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof StateTag)) { - return false; - } - - StateTag that = (StateTag) obj; - return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) - && Objects.equal(this.stateFamily, that.stateFamily) - && Objects.equal(this.requestToken, that.requestToken); - } - - @Override - public int hashCode() { - return Objects.hashCode(kind, tag, stateFamily, requestToken); - } - - @Override - public String toString() { - return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily - + (requestToken == null ? "" : ("," + requestToken.toStringUtf8())) + ")"; - } - } - - /** - * An in-memory collection of deserialized values and an optional continuation token to pass to - * Windmill when fetching the next page of values. - */ - private static class ValuesAndContToken { - private final List values; - - /** Token to pass to next request for next page of values. Null if done. */ - @Nullable - private final ByteString continuationToken; - - public ValuesAndContToken(List values, @Nullable ByteString continuationToken) { - this.values = values; - this.continuationToken = continuationToken; - } - } - - private final String computation; - private final ByteString key; - private final long workToken; - - private final MetricTrackingWindmillServerStub metrics; - - private long bytesRead = 0L; - - public WindmillStateReader(MetricTrackingWindmillServerStub metrics, String computation, - ByteString key, long workToken) { - this.metrics = metrics; - this.computation = computation; - this.key = key; - this.workToken = workToken; - } - - private static final class CoderAndFuture { - private Coder coder; - private final SettableFuture future; - - private CoderAndFuture(Coder coder, SettableFuture future) { - this.coder = coder; - this.future = future; - } - - private SettableFuture getFuture() { - return future; - } - - private SettableFuture getNonDoneFuture(StateTag stateTag) { - if (future.isDone()) { - throw new IllegalStateException("Future for " + stateTag + " is already done"); - } - return future; - } - - private Coder getAndClearCoder() { - if (coder == null) { - throw new IllegalStateException("Coder has already been cleared from cache"); - } - Coder result = coder; - coder = null; - return result; - } - - private void checkNoCoder() { - if (coder != null) { - throw new IllegalStateException("Unexpected coder"); - } - } - } - - @VisibleForTesting - ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); - private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); - - private Future stateFuture( - StateTag stateTag, @Nullable Coder coder) { - CoderAndFuture coderAndFuture = - new CoderAndFuture(coder, SettableFuture.create()); - CoderAndFuture existingCoderAndFutureWildcard = - waiting.putIfAbsent(stateTag, coderAndFuture); - if (existingCoderAndFutureWildcard == null) { - // Schedule a new request. It's response is guaranteed to find the future and coder. - pendingLookups.add(stateTag); - } else { - // Piggy-back on the pending or already answered request. - @SuppressWarnings("unchecked") - CoderAndFuture existingCoderAndFuture = - (CoderAndFuture) existingCoderAndFutureWildcard; - coderAndFuture = existingCoderAndFuture; - } - - return wrappedFuture(coderAndFuture.getFuture()); - } - - private CoderAndFuture getWaiting( - StateTag stateTag, boolean shouldRemove) { - CoderAndFuture coderAndFutureWildcard; - if (shouldRemove) { - coderAndFutureWildcard = waiting.remove(stateTag); - } else { - coderAndFutureWildcard = waiting.get(stateTag); - } - if (coderAndFutureWildcard == null) { - throw new IllegalStateException("Missing future for " + stateTag); - } - @SuppressWarnings("unchecked") - CoderAndFuture coderAndFuture = - (CoderAndFuture) coderAndFutureWildcard; - return coderAndFuture; - } - - public Future watermarkFuture(ByteString encodedTag, String stateFamily) { - return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); - } - - public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { - return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); - } - - public Future> listFuture( - ByteString encodedTag, String stateFamily, Coder elemCoder) { - // First request has no continuation token. - StateTag stateTag = new StateTag(StateTag.Kind.LIST, encodedTag, stateFamily); - // Convert the ValuesAndContToken to Iterable. - return valuesToPagingIterableFuture( - stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); - } - - /** - * Internal request to fetch the next 'page' of values in a TagList. Return null if - * no continuation token is in {@code contTag}, which signals there are no more pages. - */ - @Nullable - private Future> continuationListFuture( - StateTag contStateTag, Coder elemCoder) { - if (contStateTag.requestToken == null) { - // We're done. - return null; - } - return stateFuture(contStateTag, elemCoder); - } - - private Future wrappedFuture(final Future future) { - // If the underlying lookup is already complete, we don't need to create the wrapper. - if (future.isDone()) { - return future; - } - - return new ForwardingFuture() { - @Override - protected Future delegate() { - return future; - } - - @Override - public T get() throws InterruptedException, ExecutionException { - if (!future.isDone()) { - startBatchAndBlock(); - } - return super.get(); - } - - @Override - public T get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - if (!future.isDone()) { - startBatchAndBlock(); - } - return super.get(timeout, unit); - } - }; - } - - /** - * Return future which transforms a {@code ValuesAndContToken} result into the - * initial Iterable result expected from the external caller. - */ - private Future> valuesToPagingIterableFuture(final StateTag stateTag, - final Coder elemCoder, final Future> future) { - return Futures.lazyTransform(future, new Function, Iterable>() { - @Override - public Iterable apply(ValuesAndContToken valuesAndContToken) { - if (valuesAndContToken.continuationToken == null) { - // Number of values is small enough Windmill sent us the entire list in one response. - return valuesAndContToken.values; - } else { - // Return an iterable which knows how to come back for more. - StateTag contStateTag = new StateTag(stateTag.kind, stateTag.tag, stateTag.stateFamily, - valuesAndContToken.continuationToken); - return new TagListPagingIterable<>(valuesAndContToken.values, contStateTag, elemCoder); - } - } - }); - } - - public void startBatchAndBlock() { - // First, drain work out of the pending lookups into a set. These will be the items we fetch. - HashSet toFetch = new HashSet<>(); - while (!pendingLookups.isEmpty()) { - StateTag stateTag = pendingLookups.poll(); - if (stateTag == null) { - break; - } - - if (!toFetch.add(stateTag)) { - throw new IllegalStateException("Duplicate tags being fetched."); - } - } - - // If we failed to drain anything, some other thread pulled it off the queue. We have no work - // to do. - if (toFetch.isEmpty()) { - return; - } - - Windmill.GetDataRequest request = createRequest(toFetch); - Windmill.GetDataResponse response = metrics.getStateData(request); - - if (response == null) { - throw new RuntimeException("Windmill unexpectedly returned null for request " + request); - } - - consumeResponse(request, response, toFetch); - } - - public long getBytesRead() { - return bytesRead; - } - - private Windmill.GetDataRequest createRequest(Iterable toFetch) { - Windmill.GetDataRequest.Builder request = Windmill.GetDataRequest.newBuilder(); - Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = - request.addRequestsBuilder() - .setComputationId(computation) - .addRequestsBuilder() - .setKey(key) - .setWorkToken(workToken); - - for (StateTag stateTag : toFetch) { - switch (stateTag.kind) { - case LIST: - TagList.Builder tagList = - keyedDataBuilder.addListsToFetchBuilder() - .setTag(stateTag.tag) - .setStateFamily(stateTag.stateFamily) - .setEndTimestamp(Long.MAX_VALUE) - .setFetchMaxBytes(MAX_LIST_BYTES); - if (stateTag.requestToken != null) { - // We're asking for the next page. - tagList.setRequestToken(stateTag.requestToken); - } - break; - - case WATERMARK: - keyedDataBuilder.addWatermarkHoldsToFetchBuilder() - .setTag(stateTag.tag) - .setStateFamily(stateTag.stateFamily); - break; - - case VALUE: - keyedDataBuilder.addValuesToFetchBuilder() - .setTag(stateTag.tag) - .setStateFamily(stateTag.stateFamily); - break; - - default: - throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); - } - } - - return request.build(); - } - - private void consumeResponse(Windmill.GetDataRequest request, - Windmill.GetDataResponse getDataResponse, Set toFetch) { - // Validate the response is for our computation/key. - if (getDataResponse.getDataCount() == 0) { - throw new RuntimeException("No computation in response to request: " + request); - } else if (getDataResponse.getDataCount() > 1) { - throw new RuntimeException("Expected exactly one computation in response, but got: " - + getDataResponse.getDataList()); - } - - Windmill.ComputationGetDataResponse computationResponse = getDataResponse.getData(0); - - if (!computation.equals(computationResponse.getComputationId())) { - throw new RuntimeException("Expected data for computation " + computation + " but was " - + computationResponse.getComputationId()); - } - - if (computationResponse.getDataCount() == 0) { - throw new RuntimeException("No key in response to request: " + request); - } else if (computationResponse.getDataCount() > 1) { - throw new RuntimeException( - "Expected exactly one key in response, but was: " + computationResponse.getDataList()); - } - - Windmill.KeyedGetDataResponse response = computationResponse.getData(0); - bytesRead += response.getSerializedSize(); - - if (response.getFailed()) { - // Set up all the futures for this key to throw an exception: - KeyTokenInvalidException keyTokenInvalidException = - new KeyTokenInvalidException(key.toStringUtf8()); - for (StateTag stateTag : toFetch) { - waiting.get(stateTag).future.setException(keyTokenInvalidException); - } - return; - } - - if (!key.equals(response.getKey())) { - throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); - } - - - for (Windmill.TagList tagList : response.getListsList()) { - StateTag stateTag = new StateTag(StateTag.Kind.LIST, tagList.getTag(), - tagList.getStateFamily(), tagList.hasRequestToken() ? tagList.getRequestToken() : null); - if (!toFetch.remove(stateTag)) { - throw new IllegalStateException( - "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); - } - consumeTagList(tagList, stateTag); - } - - for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { - StateTag stateTag = - new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); - if (!toFetch.remove(stateTag)) { - throw new IllegalStateException( - "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); - } - consumeWatermark(hold, stateTag); - } - - for (Windmill.TagValue value : response.getValuesList()) { - StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); - if (!toFetch.remove(stateTag)) { - throw new IllegalStateException( - "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); - } - consumeTagValue(value, stateTag); - } - - if (!toFetch.isEmpty()) { - throw new IllegalStateException( - "Didn't receive responses for all pending fetches. Missing: " + toFetch); - } - } - - @VisibleForTesting - static class WeightedList extends ForwardingList implements Weighted { - private List delegate; - long weight; - - WeightedList(List delegate) { - this.delegate = delegate; - this.weight = 0; - } - - @Override - protected List delegate() { - return delegate; - } - - @Override - public boolean add(T elem) { - throw new UnsupportedOperationException("Must use AddWeighted()"); - } - - @Override - public long getWeight() { - return weight; - } - - public void addWeighted(T elem, long weight) { - delegate.add(elem); - this.weight += weight; - } - } - - /** - * The deserialized values in {@code tagList} as a read-only array list. - */ - private List tagListPageValues(TagList tagList, Coder elemCoder) { - if (tagList.getValuesCount() == 0) { - return new WeightedList(Collections.emptyList()); - } - - WeightedList valueList = new WeightedList<>(new ArrayList(tagList.getValuesCount())); - for (Windmill.Value value : tagList.getValuesList()) { - if (value.hasData() && !value.getData().isEmpty()) { - // Drop the first byte of the data; it's the zero byte we prepended to avoid writing - // empty data. - InputStream inputStream = value.getData().substring(1).newInput(); - try { - valueList.addWeighted( - elemCoder.decode(inputStream, Coder.Context.OUTER), value.getData().size() - 1); - } catch (IOException e) { - throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); - } - } - } - return valueList; - } - - private void consumeTagList(TagList tagList, StateTag stateTag) { - boolean shouldRemove; - if (stateTag.requestToken == null) { - // This is the response for the first page. - // Leave the future in the cache so subsequent requests for the first page - // can return immediately. - shouldRemove = false; - } else { - // This is a response for a subsequent page. - // Don't cache the future since we may need to make multiple requests with different - // continuation tokens. - shouldRemove = true; - } - CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); - SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); - Coder coder = coderAndFuture.getAndClearCoder(); - List values = this.tagListPageValues(tagList, coder); - future.set(new ValuesAndContToken( - values, tagList.hasContinuationToken() ? tagList.getContinuationToken() : null)); - } - - private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { - CoderAndFuture coderAndFuture = getWaiting(stateTag, false); - SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); - // No coders for watermarks - coderAndFuture.checkNoCoder(); - - Instant hold = null; - for (long timestamp : watermarkHold.getTimestampsList()) { - Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); - if (hold == null || instant.isBefore(hold)) { - hold = instant; - } - } - - future.set(hold); - } - - private void consumeTagValue(TagValue tagValue, StateTag stateTag) { - CoderAndFuture coderAndFuture = getWaiting(stateTag, false); - SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); - Coder coder = coderAndFuture.getAndClearCoder(); - - if (tagValue.hasValue() && tagValue.getValue().hasData() - && !tagValue.getValue().getData().isEmpty()) { - InputStream inputStream = tagValue.getValue().getData().newInput(); - try { - T value = coder.decode(inputStream, Coder.Context.OUTER); - future.set(value); - } catch (IOException e) { - throw new IllegalStateException("Unable to decode value using " + coder, e); - } - } else { - future.set(null); - } - } - - /** - * An iterable over elements backed by paginated GetData requests to Windmill. The - * iterable may be iterated over an arbitrary number of times and multiple iterators - * may be active simultaneously. - * - *

    There are two pattern we wish to support with low -memory and -latency: - *

      - *
    1. Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache - * the initial 'page' of values returned by Windmill from our first request for the lifetime - * of the iterable. - *
    2. Iterate through all elements of a very large collection. We'll send the GetData request - * for the next page when the current page is begun. We'll discard intermediate pages and only - * retain the first. Thus the maximum memory pressure is one page plus one page per call to - * iterator. - *
    - */ - private class TagListPagingIterable implements Iterable { - /** Initial values returned for the first page. Never reclaimed. */ - private final List firstPage; - - /** State tag with continuation token set for second page. */ - private final StateTag secondPageCont; - - /** Coder for elements. */ - private final Coder elemCoder; - - private TagListPagingIterable(List firstPage, StateTag secondPageCont, Coder elemCoder) { - this.firstPage = firstPage; - this.secondPageCont = secondPageCont; - this.elemCoder = elemCoder; - } - - @Override - public Iterator iterator() { - return new AbstractIterator() { - private Iterator currentPage = firstPage.iterator(); - private StateTag nextPageCont = secondPageCont; - private Future> pendingNextPage = - continuationListFuture(nextPageCont, elemCoder); - - @Override - protected T computeNext() { - while (true) { - if (currentPage.hasNext()) { - return currentPage.next(); - } - if (pendingNextPage == null) { - return endOfData(); - } - - ValuesAndContToken valuesAndContToken; - try { - valuesAndContToken = pendingNextPage.get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException("Unable to read value from state", e); - } - currentPage = valuesAndContToken.values.iterator(); - nextPageCont = new StateTag(nextPageCont.kind, nextPageCont.tag, - nextPageCont.stateFamily, valuesAndContToken.continuationToken); - pendingNextPage = continuationListFuture(nextPageCont, elemCoder); - } - } - }; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillTimeUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillTimeUtils.java deleted file mode 100644 index e107aea380..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillTimeUtils.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.common.base.Preconditions; - -import org.joda.time.Instant; - -import javax.annotation.Nullable; - -/** - * Some timestamp conversion helpers for working with Windmill. - */ -class WindmillTimeUtils { - /** - * Convert a Windmill output watermark to a harness watermark. - * - *

    Windmill tracks time in microseconds while the harness uses milliseconds. - * Windmill will 'speculatively' hold the output watermark for a computation to the - * earliest input message timestamp, provided that message timestamp is at or after - * the current output watermark. Thus for soundness we must ensure - * 'Windmill considers message late' implies 'harness considers message late'. Thus we - * round up when converting from microseconds to milliseconds. - * - *

    In other words, harness output watermark >= windmill output watermark. - */ - @Nullable - static Instant windmillToHarnessOutputWatermark(long watermarkUs) { - if (watermarkUs == Long.MIN_VALUE) { - // Unknown. - return null; - } else if (watermarkUs == Long.MAX_VALUE) { - // End of time. - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } else { - // Round up to nearest millisecond. - return new Instant((watermarkUs + 999) / 1000); - } - } - - /** - * Convert a Windmill input watermark to a harness input watermark. - * - *

    We round down, thus harness input watermark <= windmill output watermark. - */ - @Nullable - static Instant windmillToHarnessInputWatermark(long watermarkUs) { - if (watermarkUs == Long.MIN_VALUE) { - // Unknown. - return null; - } else if (watermarkUs == Long.MAX_VALUE) { - // End of time. - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } else { - // Round down to nearest millisecond. - return new Instant(watermarkUs / 1000); - } - } - - /** - * Convert a Windmill message timestamp to a harness timestamp. - * - *

    For soundness we require the test - * {@code harness message timestamp >= harness output watermark} to imply - * {@code windmill message timestamp >= windmill output watermark}. Thus - * we round timestamps down and output watermarks up. - */ - static Instant windmillToHarnessTimestamp(long timestampUs) { - // Windmill should never send us an unknown timestamp. - Preconditions.checkArgument(timestampUs != Long.MIN_VALUE); - if (timestampUs == Long.MAX_VALUE) { - // End of time. - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } else { - // Round down to nearest millisecond. - return new Instant(timestampUs / 1000); - } - } - - /** - * Convert a harness timestamp to a Windmill timestamp. - */ - static long harnessToWindmillTimestamp(Instant timestamp) { - if (timestamp.equals(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - // End of time. - return Long.MAX_VALUE; - } else { - return timestamp.getMillis() * 1000; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/windmill/WindmillServerStub.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/windmill/WindmillServerStub.java deleted file mode 100644 index 8b55824de3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/windmill/WindmillServerStub.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.windmill; - -/** - * Stub for communicating with a Windmill server. - */ -public abstract class WindmillServerStub { - /** - * Get a batch of work to process. - */ - public abstract Windmill.GetWorkResponse getWork(Windmill.GetWorkRequest request); - /** - * Get addition data such as state needed to process work. - */ - public abstract Windmill.GetDataResponse getData(Windmill.GetDataRequest request); - /** - * Commit the work, issuing any output productions, state modifications etc. - */ - public abstract Windmill.CommitWorkResponse commitWork( - Windmill.CommitWorkRequest request); - /** - * Get configuration data from the server. - */ - public abstract Windmill.GetConfigResponse getConfig(Windmill.GetConfigRequest request); - - /** - * Report execution information to the server. - */ - public abstract Windmill.ReportStatsResponse reportStats(Windmill.ReportStatsRequest request); -} From fba2172c420db68a46436690d50dbf7615c4fda2 Mon Sep 17 00:00:00 2001 From: klk Date: Sat, 6 Feb 2016 18:31:35 -0800 Subject: [PATCH 095/751] Move Reader classes and dependents to worker module This excludes AvroReader and TextReader which are shared with the DirectPipelineRunner evaluators. That issue will be dealt with outside of this change. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114039786 --- .../worker/ApplianceShuffleReader.java | 77 -- .../sdk/runners/worker/AvroByteReader.java | 117 --- .../sdk/runners/worker/AvroReaderFactory.java | 69 -- .../runners/worker/BigQueryAvroReader.java | 160 --- .../worker/BigQueryAvroReaderFactory.java | 68 -- .../sdk/runners/worker/BigQueryReader.java | 161 --- .../runners/worker/BigQueryReaderFactory.java | 73 -- .../worker/ChunkingShuffleBatchReader.java | 96 -- .../sdk/runners/worker/ConcatReader.java | 275 ----- .../worker/GroupingShuffleRangeTracker.java | 168 --- .../sdk/runners/worker/InMemoryReader.java | 183 ---- .../runners/worker/InMemoryReaderFactory.java | 58 -- .../sdk/runners/worker/IsmReader.java | 962 ------------------ .../worker/PartitioningShuffleReader.java | 125 --- .../PartitioningShuffleReaderFactory.java | 70 -- .../sdk/runners/worker/ReaderCacheEntry.java | 32 - .../sdk/runners/worker/ShuffleReader.java | 48 - .../sdk/runners/worker/TextReaderFactory.java | 71 -- .../worker/UngroupedShuffleReader.java | 99 -- .../worker/UngroupedShuffleReaderFactory.java | 69 -- 20 files changed, 2981 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleBatchReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTracker.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java deleted file mode 100644 index 8ebcd52e0b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleReader.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import java.io.IOException; - -import javax.annotation.concurrent.ThreadSafe; - -/** - * ApplianceShuffleReader reads chunks of data from a shuffle dataset - * for a position range. - * - *

    It is a JNI wrapper of an equivalent C++ class. - */ -@ThreadSafe -public final class ApplianceShuffleReader implements ShuffleReader { - static { - ShuffleLibrary.load(); - } - - /** - * Pointer to the underlying C++ ShuffleReader object. - */ - private long nativePointer; - - /** - * Mutator that can be used to update counters. - */ - private CounterSet.AddCounterMutator addCounterMutator; - - /** - * @param shuffleReaderConfig opaque configuration for creating a - * shuffle reader - * @param addCounterMutator mutator that can be used to update counters - */ - public ApplianceShuffleReader( - byte[] shuffleReaderConfig, - CounterSet.AddCounterMutator addCounterMutator) { - this.nativePointer = createFromConfig(shuffleReaderConfig); - this.addCounterMutator = addCounterMutator; - } - - @Override - public void finalize() { - destroy(); - } - - /** - * Native methods for interacting with the underlying native shuffle client - * code. {@code createFromConfig()} returns a pointer to a newly created - * C++ ShuffleReader object. - */ - private native long createFromConfig(byte[] shuffleReaderConfig); - private native void destroy(); - - public native String getDatasetId(); - - @Override - public native ReadChunkResult readIncludingPosition( - byte[] startPosition, byte[] endPosition) throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java deleted file mode 100644 index 418dd05d9c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteReader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.apache.avro.Schema; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A source that reads Avro files. Records are read from the Avro file as a - * series of byte arrays. The coder provided is used to deserialize each record - * from a byte array. - * - * @param the type of the elements read from the source - */ -public class AvroByteReader extends NativeReader { - final AvroReader avroReader; - final Coder coder; - private final Schema schema = Schema.create(Schema.Type.BYTES); - - public AvroByteReader(String filename, @Nullable Long startPosition, @Nullable Long endPosition, - Coder coder, @Nullable PipelineOptions options) { - this.coder = coder; - avroReader = new AvroReader<>( - filename, startPosition, endPosition, AvroCoder.of(ByteBuffer.class, schema), options); - } - - @Override - public AvroByteFileIterator iterator() throws IOException { - return new AvroByteFileIterator(); - } - - class AvroByteFileIterator extends NativeReaderIterator { - private final NativeReaderIterator> avroFileIterator; - private T current; - - public AvroByteFileIterator() throws IOException { - avroFileIterator = avroReader.iterator(); - } - - @Override - public boolean start() throws IOException { - if (!avroFileIterator.start()) { - return false; - } - updateCurrent(); - return true; - } - - @Override - public boolean advance() throws IOException { - if (!avroFileIterator.advance()) { - return false; - } - updateCurrent(); - return true; - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return current; - } - - private void updateCurrent() throws IOException { - ByteBuffer inBuffer = avroFileIterator.getCurrent().getValue(); - byte[] encodedElem = new byte[inBuffer.remaining()]; - inBuffer.get(encodedElem); - assert inBuffer.remaining() == 0; - inBuffer.clear(); - notifyElementRead(encodedElem.length); - current = CoderUtils.decodeFromByteArray(coder, encodedElem); - } - - @Override - public void close() throws IOException { - avroFileIterator.close(); - } - - @Override - public Progress getProgress() { - return avroFileIterator.getProgress(); - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - return avroFileIterator.requestDynamicSplit(splitRequest); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactory.java deleted file mode 100644 index 75242abd41..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReaderFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getLong; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue.ValueOnlyWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import javax.annotation.Nullable; - -/** - * Creates an AvroReader from a CloudObject spec. - */ -public class AvroReaderFactory implements ReaderFactory { - - public AvroReaderFactory() {} - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - return create(spec, coder, options); - } - - NativeReader create(CloudObject spec, Coder coder, PipelineOptions options) - throws Exception { - String filename = getString(spec, PropertyNames.FILENAME); - Long startOffset = getLong(spec, PropertyNames.START_OFFSET, null); - Long endOffset = getLong(spec, PropertyNames.END_OFFSET, null); - - // See AvroSinkFactory#create for an explanation of this logic. - if (coder instanceof ValueOnlyWindowedValueCoder - && ((ValueOnlyWindowedValueCoder) coder).getValueCoder() instanceof AvroCoder) { - ValueOnlyWindowedValueCoder valueCoder = (ValueOnlyWindowedValueCoder) coder; - return new AvroReader<>( - filename, startOffset, endOffset, (AvroCoder) valueCoder.getValueCoder(), options); - } else { - return new AvroByteReader<>(filename, startOffset, endOffset, coder, options); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java deleted file mode 100644 index a7ad24b3da..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReader.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.common.base.MoreObjects.firstNonNull; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.cloud.dataflow.sdk.io.AvroSource; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.OffsetBasedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.AvroUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.apache.avro.Schema; -import org.apache.avro.Schema.Parser; -import org.apache.avro.generic.GenericRecord; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -import javax.annotation.Nullable; - -/** - * A reader for Avro files exported by BigQuery, which converts them to {@link TableRow} records. - */ -public class BigQueryAvroReader extends NativeReader> { - private static final Logger LOG = LoggerFactory.getLogger(BigQueryAvroReader.class); - - @Nullable - final Long startPosition; - @Nullable - final Long endPosition; - final String filename; - final AvroSource avroSource; - final TableSchema tableSchema; - final PipelineOptions options; - - public BigQueryAvroReader( - String filename, - @Nullable Long startPosition, - @Nullable Long endPosition, - TableSchema schema, - @Nullable PipelineOptions options) - throws IOException { - this.filename = filename; - this.startPosition = startPosition; - this.endPosition = endPosition; - Schema recordSchema = - new Parser().parse(AvroUtils.readMetadataFromFile(filename).getSchemaString()); - this.tableSchema = schema; - this.options = options; - this.avroSource = AvroSource.from(filename).withSchema(recordSchema); - } - - @Override - public BigQueryAvroFileIterator iterator() throws IOException { - Long endPosition = firstNonNull(this.endPosition, Long.MAX_VALUE); - Long startPosition = firstNonNull(this.startPosition, 0L); - BoundedSource.BoundedReader reader; - if (startPosition == 0 && endPosition == Long.MAX_VALUE) { - // Read entire file (or collection of files). - reader = avroSource.createReader(options); - } else { - // Read a subrange of file. - reader = avroSource.createForSubrangeOfFile(filename, startPosition, endPosition) - .createReader(options); - } - return new BigQueryAvroFileIterator((AvroSource.AvroReader) reader); - } - - class BigQueryAvroFileIterator extends LegacyReaderIterator> { - final AvroSource.AvroReader reader; - boolean hasStarted = false; - long blockOffset = -1; - - public BigQueryAvroFileIterator(AvroSource.AvroReader reader) { - this.reader = reader; - } - - @Override - protected WindowedValue nextImpl() throws IOException { - GenericRecord next = reader.getCurrent(); - // Coarse-grained reporting of input bytes consumed. - // After completing reading a block, the block offset changes. - long currentOffset = reader.getCurrentBlockOffset(); - if (currentOffset != blockOffset) { - notifyElementRead(reader.getCurrentBlockSize()); - blockOffset = currentOffset; - } - return WindowedValue.valueInGlobalWindow( - AvroUtils.convertGenericRecordToTableRow(next, tableSchema)); - } - - @Override - protected boolean hasNextImpl() throws IOException { - if (!hasStarted) { - hasStarted = true; - return reader.start(); - } - return reader.advance(); - } - - @Override - public Progress getProgress() { - Double readerProgress = reader.getFractionConsumed(); - if (readerProgress == null) { - return null; - } - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - progress.setFractionConsumed(readerProgress); - return cloudProgressToReaderProgress(progress); - } - - @Override - public void close() throws IOException { - reader.close(); - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - ApproximateSplitRequest splitProgress = - SourceTranslationUtils.splitRequestToApproximateSplitRequest(splitRequest); - double splitAtFraction = splitProgress.getFractionConsumed(); - LOG.info("Received request for dynamic split at {}", splitAtFraction); - OffsetBasedSource residual = reader.splitAtFraction(splitAtFraction); - if (residual == null) { - LOG.info("Rejected split request for split at {}", splitAtFraction); - return null; - } - com.google.api.services.dataflow.model.Position acceptedPosition = - new com.google.api.services.dataflow.model.Position(); - acceptedPosition.setByteOffset(residual.getStartOffset()); - LOG.info("Accepted split for position {} which resulted in a new source with byte offset {}", - splitAtFraction, residual.getStartOffset()); - return new DynamicSplitResultWithPosition( - SourceTranslationUtils.cloudPositionToReaderPosition(acceptedPosition)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java deleted file mode 100644 index 9ab6534049..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryAvroReaderFactory.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getLong; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.io.IOException; - -import javax.annotation.Nullable; - -/** - * Creates an AvroReader specifically for the output of a BigQuery export job. - */ -public class BigQueryAvroReaderFactory implements ReaderFactory { - - public BigQueryAvroReaderFactory() {} - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - return createTyped(spec, options); - } - - private static TableSchema parseTableSchema(String schemaStr) throws IOException { - checkArgument(!schemaStr.isEmpty(), "Provided BigQuery schema is empty"); - return JacksonFactory.getDefaultInstance().fromString(schemaStr, TableSchema.class); - } - - NativeReader createTyped(CloudObject spec, PipelineOptions options) throws Exception { - String filename = getString(spec, PropertyNames.FILENAME); - Long startOffset = getLong(spec, PropertyNames.START_OFFSET, null); - Long endOffset = getLong(spec, PropertyNames.END_OFFSET, null); - TableSchema bqSchema = parseTableSchema(getString(spec, PropertyNames.BIGQUERY_EXPORT_SCHEMA)); - return new BigQueryAvroReader(filename, startOffset, endOffset, bqSchema, options); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java deleted file mode 100644 index 975bf38218..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReader.java +++ /dev/null @@ -1,161 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.annotations.VisibleForTesting; - -import java.io.IOException; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A source that reads a BigQuery table and yields TableRow objects. - * - *

    The source is a wrapper over the {@code BigQueryTableRowIterator} class, which issues a - * query for all rows of a table and then iterates over the result. There is no support for - * progress reporting because the source is used only in situations where the entire table must be - * read by each worker (i.e. the source is used as a side input). - */ -public class BigQueryReader extends NativeReader> { - @Nullable private final TableReference tableRef; - @Nullable private final String query; - @Nullable private final String projectId; - @Nullable private final Boolean flattenResults; - private final Bigquery bigQueryClient; - - private BigQueryReader(TableReference tableRef, String query, String projectId, - Bigquery bigQueryClient, Boolean flattenResults) { - this.tableRef = tableRef; - this.query = query; - this.projectId = projectId; - this.flattenResults = flattenResults; - this.bigQueryClient = checkNotNull(bigQueryClient, "bigQueryClient"); - } - - /** - * Returns a {@code BigQueryReader} that uses the specified client to read from the specified - * table. - */ - static BigQueryReader fromTable(TableReference tableRef, Bigquery bigQueryClient) { - return new BigQueryReader(tableRef, null, null, bigQueryClient, null); - } - - /** - * Returns a {@code BigQueryReader} that uses the specified client to read the results from - * executing the specified query in the specified project. - */ - static BigQueryReader fromQuery( - String query, String projectId, Bigquery bigQueryClient, boolean flatten) { - return new BigQueryReader(null, query, projectId, bigQueryClient, flatten); - } - - public TableReference getTableRef() { - return tableRef; - } - - public String getQuery() { - return query; - } - - @Override - public BigQueryReaderIterator iterator() throws IOException { - if (tableRef != null) { - return new BigQueryReaderIterator(tableRef, bigQueryClient); - } else { - return new BigQueryReaderIterator(query, projectId, bigQueryClient, flattenResults); - } - } - - /** - * A ReaderIterator that yields TableRow objects for each row of a BigQuery table. - */ - @VisibleForTesting - static class BigQueryReaderIterator extends NativeReaderIterator> { - private BigQueryTableRowIterator rowIterator; - private WindowedValue current; - - public BigQueryReaderIterator(TableReference tableRef, Bigquery bigQueryClient) { - rowIterator = BigQueryTableRowIterator.fromTable(tableRef, bigQueryClient); - } - - public BigQueryReaderIterator(String query, String projectId, Bigquery bigQueryClient, - @Nullable Boolean flattenResults) { - rowIterator = BigQueryTableRowIterator.fromQuery(query, projectId, bigQueryClient, - flattenResults); - } - - @Override - public boolean start() throws IOException { - try { - rowIterator.open(); - } catch (InterruptedException e) { - throw new IOException(e); - } - return advance(); - } - - @Override - public boolean advance() throws IOException { - try { - if (!rowIterator.advance()) { - return false; - } - } catch (InterruptedException e) { - throw new IOException(e); - } - current = WindowedValue.valueInGlobalWindow(rowIterator.getCurrent()); - return true; - } - - @Override - public WindowedValue getCurrent() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return current; - } - - @Override - public Progress getProgress() { - // For now reporting progress is not supported because this source is used only when - // an entire table needs to be read by each worker (used as a side input for instance). - return null; - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - // For now dynamic splitting is not supported because this source - // is used only when an entire table needs to be read by each worker (used - // as a side input for instance). - return null; - } - - @Override - public void close() throws IOException { - rowIterator.close(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java deleted file mode 100644 index 06486e9a17..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/BigQueryReaderFactory.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.TableReference; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import javax.annotation.Nullable; - -/** - * Creates a BigQueryReader from a {@link CloudObject} spec. - */ -public class BigQueryReaderFactory implements ReaderFactory { - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - return createTyped(spec, options); - } - - private BigQueryReader createTyped(CloudObject spec, PipelineOptions options) throws Exception { - Bigquery client = Transport.newBigQueryClient(options.as(BigQueryOptions.class)).build(); - - String query = getString(spec, PropertyNames.BIGQUERY_QUERY, null); - if (query != null) { - String project = options.as(GcpOptions.class).getProject(); - Boolean flatten = getBoolean(spec, PropertyNames.BIGQUERY_FLATTEN_RESULTS, true); - return BigQueryReader.fromQuery(query, project, client, flatten); - } else { - String tableId = getString(spec, PropertyNames.BIGQUERY_TABLE, null); - checkArgument(tableId != null, "Either a table or a query has to be specified"); - String project = getString(spec, PropertyNames.BIGQUERY_PROJECT); - String dataset = getString(spec, PropertyNames.BIGQUERY_DATASET); - return BigQueryReader.fromTable( - new TableReference().setProjectId(project).setDatasetId(dataset).setTableId(tableId), - client); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleBatchReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleBatchReader.java deleted file mode 100644 index 5ee398d1b1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleBatchReader.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleBatchReader; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.ShufflePosition; -import com.google.common.io.ByteStreams; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.util.ArrayList; - -import javax.annotation.Nullable; - -/** - * ChunkingShuffleBatchReader reads data from a shuffle dataset using a - * ShuffleReader. - */ -final class ChunkingShuffleBatchReader implements ShuffleBatchReader { - private ShuffleReader reader; - - /** - * @param reader used to read from a shuffle dataset - */ - public ChunkingShuffleBatchReader(ShuffleReader reader) { - this.reader = reader; - } - - @Override - public ShuffleBatchReader.Batch read( - @Nullable ShufflePosition startShufflePosition, - @Nullable ShufflePosition endShufflePosition) throws IOException { - @Nullable byte[] startPosition = - ByteArrayShufflePosition.getPosition(startShufflePosition); - @Nullable byte[] endPosition = - ByteArrayShufflePosition.getPosition(endShufflePosition); - - ShuffleReader.ReadChunkResult result = - reader.readIncludingPosition(startPosition, endPosition); - DataInputStream input = - new DataInputStream(new ByteArrayInputStream(result.chunk)); - ArrayList entries = new ArrayList<>(); - while (input.available() > 0) { - entries.add(getShuffleEntry(input)); - } - return new Batch(entries, result.nextStartPosition == null ? null - : ByteArrayShufflePosition.of(result.nextStartPosition)); - } - - /** - * Extracts a ShuffleEntry by parsing bytes from a given InputStream. - * - * @param input stream to read from - * @return parsed ShuffleEntry - */ - static ShuffleEntry getShuffleEntry(DataInputStream input) throws IOException { - byte[] position = getFixedLengthPrefixedByteArray(input); - byte[] key = getFixedLengthPrefixedByteArray(input); - byte[] skey = getFixedLengthPrefixedByteArray(input); - byte[] value = getFixedLengthPrefixedByteArray(input); - return new ShuffleEntry(position, key, skey, value); - } - - /** - * Extracts a length-prefix-encoded byte array from a given InputStream. - * - * @param dataInputStream stream to read from - * @return parsed byte array - */ - static byte[] getFixedLengthPrefixedByteArray(DataInputStream dataInputStream) - throws IOException { - int length = dataInputStream.readInt(); - if (length < 0) { - throw new IOException("invalid length: " + length); - } - byte[] data = new byte[length]; - ByteStreams.readFully(dataInputStream, data); - return data; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java deleted file mode 100644 index d7c0429d42..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ConcatReader.java +++ /dev/null @@ -1,275 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.ConcatPosition; -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.DataflowReaderProgress; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A {@link NativeReader} that reads elements from a given set of encoded {@link Source}s. Creates - * {@link NativeReader}s for sources lazily, i.e. only when elements from the particular - * {@code NativeReader} are about to be read. - * - *

    This class does does not cache {@link NativeReader}s and instead creates new set of - * {@link NativeReader}s for every new {@link ConcatIterator}. Because of this, multiple - * {@link ConcatIterator}s created using the same {@link ConcatReader} will not be able to share - * any state between each other. This design was chosen since keeping a large number of - * {@link NativeReader} objects alive within a single {@link ConcatReader} could be highly - * memory consuming. - * - *

    For progress reporting and dynamic work rebalancing purposes, {@link ConcatIterator} uses - * a position of type {@link ConcatPosition}. Progress reporting and dynamic work rebalancing - * currently work only at the granularity of full sources being concatenated. - * - * @param Type of the elements read by the {@link NativeReader}s. - */ -public class ConcatReader extends NativeReader { - private static final Logger LOG = LoggerFactory.getLogger(ConcatReader.class); - - public static final String SOURCE_NAME = "ConcatSource"; - - private final List sources; - private final PipelineOptions options; - private final ExecutionContext executionContext; - private final CounterSet.AddCounterMutator addCounterMutator; - private final String operationName; - private final ReaderFactory readerFactory; - - /** - * Create a {@link ConcatReader} using a given list of encoded {@link Source}s. - */ - public ConcatReader( - ReaderFactory readerFactory, - PipelineOptions options, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - String operationName, - List sources) { - Preconditions.checkNotNull(sources); - this.readerFactory = readerFactory; - this.sources = sources; - this.options = options; - this.executionContext = executionContext; - this.addCounterMutator = addCounterMutator; - this.operationName = operationName; - } - - public Iterator getSources() { - return sources.iterator(); - } - - @Override - public ConcatIterator iterator() throws IOException { - return new ConcatIterator( - readerFactory, - options, - executionContext, - addCounterMutator, - operationName, - sources); - } - - @VisibleForTesting - static class ConcatIterator extends NativeReaderIterator { - private int currentIteratorIndex = -1; - @Nullable private NativeReaderIterator currentIterator = null; - private final List sources; - private final PipelineOptions options; - private final ExecutionContext executionContext; - private final CounterSet.AddCounterMutator addCounterMutator; - private final String operationName; - private final OffsetRangeTracker rangeTracker; - private final ReaderFactory readerFactory; - - public ConcatIterator( - ReaderFactory readerFactory, - PipelineOptions options, - ExecutionContext executionContext, - CounterSet.AddCounterMutator addCounterMutator, - String operationName, - List sources) { - this.readerFactory = readerFactory; - this.sources = sources; - this.options = options; - this.executionContext = executionContext; - this.addCounterMutator = addCounterMutator; - this.operationName = operationName; - this.rangeTracker = new OffsetRangeTracker(0, sources.size()); - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - while (true) { - // Invariant: we call currentIterator.start() immediately when opening an iterator - // (below). So if currentIterator != null, then start() has already been called on it. - if (currentIterator != null && currentIterator.advance()) { - // Happy case: current iterator has a next record. - return true; - } - // Now current iterator is either non-existent or exhausted. - // Close it, and try opening a new one. - if (currentIterator != null) { - currentIterator.close(); - currentIterator = null; - } - - if (!rangeTracker.tryReturnRecordAt(true, currentIteratorIndex + 1)) { - return false; - } - currentIteratorIndex++; - if (currentIteratorIndex == sources.size()) { - // All sources were read. - return false; - } - - Source currentSource = sources.get(currentIteratorIndex); - try { - Coder coder = null; - if (currentSource.getCodec() != null) { - coder = Serializer.deserialize(currentSource.getCodec(), Coder.class); - } - @SuppressWarnings("unchecked") - NativeReader currentReader = - (NativeReader) - readerFactory.create( - CloudObject.fromSpec(currentSource.getSpec()), coder, options, - executionContext, addCounterMutator, - operationName); - currentIterator = currentReader.iterator(); - } catch (Exception e) { - throw new IOException("Failed to create a reader for source: " + currentSource, e); - } - if (!currentIterator.start()) { - currentIterator.close(); - currentIterator = null; - continue; - } - // Happy case: newly opened iterator has a first record. - return true; - } - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (currentIterator == null) { - throw new NoSuchElementException(); - } - return currentIterator.getCurrent(); - } - - @Override - public void close() throws IOException { - if (currentIterator != null) { - currentIterator.close(); - } - } - - @Override - public Progress getProgress() { - if (currentIteratorIndex < 0) { - // Reading has not been started yet. - return null; - } - - ConcatPosition concatPosition = new ConcatPosition(); - concatPosition.setIndex(currentIteratorIndex); - Progress progressOfCurrentIterator = currentIterator.getProgress(); - if (!(progressOfCurrentIterator instanceof DataflowReaderProgress)) { - throw new IllegalArgumentException("Cannot process progress " + progressOfCurrentIterator - + " since ConcatReader can only handle readers that generate a progress of type " - + "DataflowReaderProgress"); - } - com.google.api.services.dataflow.model.Position positionOfCurrentIterator = - ((DataflowReaderProgress) progressOfCurrentIterator).cloudProgress.getPosition(); - - if (positionOfCurrentIterator != null) { - concatPosition.setPosition(positionOfCurrentIterator); - } - - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - com.google.api.services.dataflow.model.Position currentPosition = - new com.google.api.services.dataflow.model.Position(); - currentPosition.setConcatPosition(concatPosition); - progress.setPosition(currentPosition); - - return cloudProgressToReaderProgress(progress); - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - checkNotNull(splitRequest); - - ApproximateSplitRequest splitProgress = splitRequestToApproximateSplitRequest(splitRequest); - com.google.api.services.dataflow.model.Position cloudPosition = splitProgress.getPosition(); - if (cloudPosition == null) { - LOG.warn("Concat only supports split at a Position. Requested: {}", splitRequest); - return null; - } - - ConcatPosition concatPosition = cloudPosition.getConcatPosition(); - if (concatPosition == null) { - LOG.warn( - "ConcatReader only supports split at a ConcatPosition. Requested: {}", cloudPosition); - return null; - } - - if (rangeTracker.trySplitAtPosition(concatPosition.getIndex())) { - com.google.api.services.dataflow.model.Position positionToSplit = - new com.google.api.services.dataflow.model.Position(); - positionToSplit.setConcatPosition( - new ConcatPosition().setIndex((int) rangeTracker.getStopPosition().longValue())); - return new DynamicSplitResultWithPosition(cloudPositionToReaderPosition(positionToSplit)); - } else { - LOG.debug("Could not perform the dynamic split request " + splitRequest); - return null; - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTracker.java deleted file mode 100644 index 0092142d4c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/GroupingShuffleRangeTracker.java +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.io.range.RangeTracker; -import com.google.common.annotations.VisibleForTesting; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.Nullable; - -/** - * A {@link RangeTracker} for positions used by {@code GroupingShuffleReader} - * ({@code ByteArrayShufflePosition}). - * - *

    These positions roughly correspond to hashes of keys. In case of hash collisions, - * multiple groups can have the same position. In that case, the first group at a particular - * position is considered a split point (because it is the first to be returned when reading - * a position range starting at this position), others are not. - */ -public class GroupingShuffleRangeTracker implements RangeTracker { - private static final Logger LOG = LoggerFactory.getLogger(GroupingShuffleRangeTracker.class); - - // null means "no limit": read from the beginning of the data. - @Nullable private final ByteArrayShufflePosition startPosition; - - // null means "no limit": read until the end of the data. - @Nullable private ByteArrayShufflePosition stopPosition; - - private ByteArrayShufflePosition lastGroupStart = null; - private boolean lastGroupWasAtSplitPoint = false; - - public GroupingShuffleRangeTracker( - @Nullable ByteArrayShufflePosition startPosition, - @Nullable ByteArrayShufflePosition stopPosition) { - this.startPosition = startPosition; - this.stopPosition = stopPosition; - } - - @Override - public ByteArrayShufflePosition getStartPosition() { - return startPosition; - } - - @Override - public synchronized ByteArrayShufflePosition getStopPosition() { - return stopPosition; - } - - public synchronized ByteArrayShufflePosition getLastGroupStart() { - return lastGroupStart; - } - - @Override - public synchronized boolean tryReturnRecordAt( - boolean isAtSplitPoint, ByteArrayShufflePosition groupStart) { - if (lastGroupStart == null && !isAtSplitPoint) { - throw new IllegalStateException( - String.format("The first group [at %s] must be at a split point", - groupStart.encodeBase64())); - } - if (this.startPosition != null && groupStart.compareTo(this.startPosition) < 0) { - throw new IllegalStateException( - String.format( - "Trying to return record at %s which is before the starting position at %s", - groupStart, - this.startPosition)); - } - int comparedToLast = (lastGroupStart == null) ? 1 : groupStart.compareTo(this.lastGroupStart); - if (comparedToLast < 0) { - throw new IllegalStateException( - String.format( - "Trying to return group at %s which is before the last-returned group at %s", - groupStart, - this.lastGroupStart)); - } - if (isAtSplitPoint) { - if (comparedToLast == 0) { - throw new IllegalStateException( - String.format( - "Trying to return a group at a split point with same position as the " - + "previous group: both at %s, last group was %s", - groupStart, - lastGroupWasAtSplitPoint ? "at a split point." : "not at a split point.")); - } - if (stopPosition != null && groupStart.compareTo(stopPosition) >= 0) { - return false; - } - } else if (comparedToLast != 0) { - // This case is not a violation of general RangeTracker semantics, but it is - // contrary to how GroupingShuffleReader in particular works. Hitting it would - // mean it's behaving unexpectedly. - throw new IllegalStateException( - String.format( - "Trying to return a group not at a split point, but with a different position " - + "than the previous group: last group was %s at %s, current at %s", - lastGroupWasAtSplitPoint ? "a split point" : "a non-split point", - lastGroupStart, groupStart)); - } - this.lastGroupStart = groupStart; - this.lastGroupWasAtSplitPoint = isAtSplitPoint; - return true; - } - - @Override - public synchronized boolean trySplitAtPosition(ByteArrayShufflePosition splitPosition) { - if (lastGroupStart == null) { - LOG.debug("Refusing to split {} at {}: unstarted", this, splitPosition); - return false; - } - if (splitPosition.compareTo(lastGroupStart) <= 0) { - LOG.debug( - "Refusing to split {} at {}: already past proposed split position", this, splitPosition); - return false; - } - if ((stopPosition != null && splitPosition.compareTo(stopPosition) >= 0) - || (startPosition != null && splitPosition.compareTo(startPosition) <= 0)) { - LOG.error( - "Refusing to split {} at {}: proposed split position out of range", this, splitPosition); - return false; - } - LOG.debug("Agreeing to split {} at {}", this, splitPosition); - this.stopPosition = splitPosition; - return true; - } - - @Override - public synchronized double getFractionConsumed() { - // GroupingShuffle sources have special support on the service and the service - // will estimate progress from positions for us. - throw new UnsupportedOperationException(); - } - - @Override - public synchronized String toString() { - if (lastGroupStart != null) { - return String.format( - "", - lastGroupStart, startPosition, stopPosition); - } else { - return String.format("", startPosition, stopPosition); - } - } - - @VisibleForTesting - GroupingShuffleRangeTracker copy() { - GroupingShuffleRangeTracker res = - new GroupingShuffleRangeTracker(this.startPosition, this.stopPosition); - res.lastGroupStart = this.lastGroupStart; - res.lastGroupWasAtSplitPoint = lastGroupWasAtSplitPoint; - return res; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java deleted file mode 100644 index ffcfa0ca4f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReader.java +++ /dev/null @@ -1,183 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Preconditions.checkNotNull; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; -import static com.google.common.base.MoreObjects.firstNonNull; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A source that yields a set of precomputed elements. - * - * @param the type of the elements read from the source - */ -public class InMemoryReader extends NativeReader { - private static final Logger LOG = LoggerFactory.getLogger(InMemoryReader.class); - - final List encodedElements; - final int startIndex; - final int endIndex; - final Coder coder; - - public InMemoryReader( - List encodedElements, - @Nullable Integer startIndex, - @Nullable Integer endIndex, - Coder coder) { - checkNotNull(encodedElements); - this.encodedElements = encodedElements; - int maxIndex = encodedElements.size(); - this.startIndex = Math.min(maxIndex, firstNonNull(startIndex, 0)); - this.endIndex = Math.min(maxIndex, firstNonNull(endIndex, maxIndex)); - checkArgument(this.startIndex >= 0, "negative start index: " + startIndex); - checkArgument( - this.endIndex >= this.startIndex, - "end index before start: [" + this.startIndex + ", " + this.endIndex + ")"); - this.coder = coder; - } - - @Override - public InMemoryReaderIterator iterator() throws IOException { - return new InMemoryReaderIterator(); - } - - @Override - public double getTotalParallelism() { - return this.endIndex - this.startIndex; - } - - /** - * A ReaderIterator that yields an in-memory list of elements. - */ - class InMemoryReaderIterator extends NativeReaderIterator { - @VisibleForTesting - OffsetRangeTracker tracker; - @Nullable private Integer lastReturnedIndex; - private T current; - - public InMemoryReaderIterator() { - this.tracker = new OffsetRangeTracker(startIndex, endIndex); - this.lastReturnedIndex = null; - } - - @Override - public boolean start() throws IOException { - Preconditions.checkState(lastReturnedIndex == null, "Already started"); - if (!tracker.tryReturnRecordAt(true, startIndex)) { - return false; - } - current = decode(encodedElements.get(startIndex)); - lastReturnedIndex = startIndex; - return true; - } - - @Override - public boolean advance() throws IOException { - Preconditions.checkNotNull(lastReturnedIndex, "Not started"); - if (!tracker.tryReturnRecordAt(true, (long) lastReturnedIndex + 1)) { - return false; - } - ++lastReturnedIndex; - current = decode(encodedElements.get(lastReturnedIndex)); - return true; - } - - @Override - public T getCurrent() throws NoSuchElementException { - return current; - } - - private T decode(String encodedElementString) throws CoderException { - // TODO: Replace with the real encoding used by the - // front end, when we know what it is. - byte[] encodedElement = StringUtils.jsonStringToByteArray(encodedElementString); - notifyElementRead(encodedElement.length); - return CoderUtils.decodeFromByteArray(coder, encodedElement); - } - - @Override - public Progress getProgress() { - if (lastReturnedIndex == null) { - return null; - } - // Currently we assume that only a record index position is reported as - // current progress. An implementer can override this method to update - // other metrics, e.g. completion percentage or remaining time. - com.google.api.services.dataflow.model.Position currentPosition = - new com.google.api.services.dataflow.model.Position(); - currentPosition.setRecordIndex((long) lastReturnedIndex); - - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - progress.setPosition(currentPosition); - - return cloudProgressToReaderProgress(progress); - } - - @Override - public double getRemainingParallelism() { - // Use the starting index if no elements have yet been returned. - return tracker.getStopPosition() - firstNonNull(lastReturnedIndex, startIndex); - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - checkNotNull(splitRequest); - - com.google.api.services.dataflow.model.Position splitPosition = - splitRequestToApproximateSplitRequest(splitRequest).getPosition(); - if (splitPosition == null) { - LOG.warn("InMemoryReader only supports split at a Position. Requested: {}", - splitRequest); - return null; - } - - Long splitIndex = splitPosition.getRecordIndex(); - if (splitIndex == null) { - LOG.warn("InMemoryReader only supports split at a record index. Requested: {}", - splitPosition); - return null; - } - - if (!tracker.trySplitAtPosition(splitIndex)) { - return null; - } - return new DynamicSplitResultWithPosition(cloudPositionToReaderPosition(splitPosition)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java deleted file mode 100644 index 3a8f748348..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/InMemoryReaderFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getInt; -import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.util.Collections; - -import javax.annotation.Nullable; - -/** - * Creates an InMemoryReader from a CloudObject spec. - */ -public class InMemoryReaderFactory implements ReaderFactory { - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - return create(spec, coder); - } - - InMemoryReader create(CloudObject spec, Coder coder) throws Exception { - return new InMemoryReader<>( - getStrings(spec, PropertyNames.ELEMENTS, Collections.emptyList()), - getInt(spec, PropertyNames.START_INDEX, null), - getInt(spec, PropertyNames.END_INDEX, null), - coder); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java deleted file mode 100644 index 3b85f1e1c9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmReader.java +++ /dev/null @@ -1,962 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.Footer; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.FooterCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShard; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefix; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefixCoder; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.RandomAccessData; -import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter; -import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter.ScalableBloomFilterCoder; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.MoreObjects; -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; -import com.google.common.cache.Cache; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.Ordering; -import com.google.common.io.ByteStreams; -import com.google.common.primitives.Longs; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SeekableByteChannel; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.SortedMap; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; - -/** - * A {@link NativeReader} that reads Ism files. - * - * @param the type of the value written to the sink - */ -public class IsmReader extends NativeReader>> { - /** - * This constant represents the distance we would rather read and drop bytes for - * versus doing an actual repositioning of the underlying stream. Tuned for operation - * within GCS. - */ - private static final int SEEK_VS_READ = 6 * 1024 * 1024; - private static final int MAX_SHARD_INDEX_AND_FOOTER_SIZE = 1024 * 1024; - - private final String filename; - private final IsmRecordCoder coder; - - /** Lazily initialized on first read. */ - private long length; - private Footer footer; - - /** A map indexed by shard id, storing the Ism shard descriptors. */ - private NavigableMap shardIdToShardMap; - - /** - * A map sorted and indexed by the block offset for a given shard. The sorting is important so - * the {@link LazyIsmPrefixReaderIterator} can read through the file in increasing order. - */ - private NavigableMap shardOffsetToShardMap; - - /** Values lazily initialized per shard on first keyed read of each shard. */ - private Map> indexPerShard; - ScalableBloomFilter bloomFilter; - - /** - * A cache instance which if set on this reader is used to cache blocks of data that are read. - * Each value represents the decoded form of a block. - */ - private final Cache>>>> cache; - - /** - * Produces a reader for the specified {@code filename} and {@code coder}. - * See {@link IsmFormat} for encoded format details. - */ - IsmReader( - final String filename, - IsmRecordCoder coder, - Cache>>>> cache) { - checkNotNull(cache); - IsmFormat.validateCoderIsCompatible(coder); - this.filename = filename; - this.coder = coder; - this.cache = cache; - } - - @Override - public IsmPrefixReaderIterator iterator() throws IOException { - return new LazyIsmPrefixReaderIterator(); - } - - /** - * Returns a reader over a set of key components. The key components are encoded to their - * byte representations and used as a key prefix. - * - *

    If the file is empty or their is no key with the same prefix, then we return - * an empty reader iterator. - * - *

    If less than the required number of shard key components is passed in, then a reader - * iterator over all the keys is returned. - * - *

    Otherwise we return a reader iterator which only iterates over keys which have the - * same key prefix. - */ - public IsmPrefixReaderIterator overKeyComponents(List keyComponents) throws IOException { - checkNotNull(keyComponents); - checkArgument(keyComponents.size() <= coder.getKeyComponentCoders().size(), - "Expected at most %s key component(s) but received %s.", - coder.getKeyComponentCoders().size(), keyComponents); - - Optional inChannel = - initializeFooterAndShardIndex(Optional.absent()); - - // If this file is empty, we can return an empty iterator. - if (footer.getNumberOfKeys() == 0) { - return new EmptyIsmPrefixReaderIterator(keyComponents); - } - - // If not enough key components to figure out which shard was requested, we return a reader - // iterator over all the keys. - if (keyComponents.size() < coder.getNumberOfShardKeyCoders(keyComponents)) { - return new ShardAwareIsmPrefixReaderIterator(keyComponents, openIfNeeded(inChannel)); - } - - RandomAccessData keyBytes = new RandomAccessData(); - int shardId = coder.encodeAndHash(keyComponents, keyBytes); - - // If this file does not contain the shard or Bloom filter does not contain the key prefix, - // we know that we can return an empty reader iterator. - if (!shardIdToShardMap.containsKey(shardId)) { - return new EmptyIsmPrefixReaderIterator(keyComponents); - } - inChannel = initializeForKeyedRead(shardId, inChannel); - closeIfPresent(inChannel); - if (!bloomFilterMightContain(keyBytes)) { - return new EmptyIsmPrefixReaderIterator(keyComponents); - } - - // Otherwise we may actually contain the key so construct a reader iterator - // which will fetch the data blocks containing the requested key prefix. - - // We find the first key in the index which may contain our prefix - RandomAccessData floorKey = indexPerShard.get(shardId).floorKey(keyBytes); - - // We compute an upper bound on the key prefix by incrementing the prefix - RandomAccessData keyBytesUpperBound = keyBytes.increment(); - // Compute the sub-range of the index map that we want to iterate over since - // any of these blocks may contain the key prefix. - Iterator blockEntries = - indexPerShard.get(shardId).subMap(floorKey, keyBytesUpperBound).values().iterator(); - - return new WithinShardIsmPrefixReaderIterator( - keyComponents, - keyBytes, - keyBytesUpperBound, - blockEntries); - } - - /** Returns the coder associated with this IsmReader. */ - public IsmRecordCoder getCoder() { - return coder; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(IsmReader.class) - .add("filename", filename) - .add("coder", coder) - .toString(); - } - - // Overridable by tests to get around the bloom filter not containing any values. - @VisibleForTesting - boolean bloomFilterMightContain(RandomAccessData keyBytes) { - return bloomFilter.mightContain(keyBytes.array(), 0, keyBytes.size()); - } - - /** - * Initialize this Ism reader by reading the footer and shard index. Returns a channel for re-use - * if this method was required to open one. - */ - private synchronized Optional - initializeFooterAndShardIndex(Optional inChannel) throws IOException { - if (footer != null) { - checkState(shardIdToShardMap != null, - "Expected shard id to shard map to have been initialized."); - checkState(shardOffsetToShardMap != null, - "Expected shard offset to shard map to have been initialized."); - return inChannel; - } - checkState(shardIdToShardMap == null, - "Expected shard id to shard map to not have been initialized."); - checkState(shardOffsetToShardMap == null, - "Expected shard offset to shard map to not have been initialized."); - - SeekableByteChannel rawChannel = openIfNeeded(inChannel); - this.length = rawChannel.size(); - - // We read the last chunk of data, for small files we will capture the entire file. - // We may capture the Bloom filter, shard index, and footer for slightly larger files. - // Otherwise we are guaranteed to capture the footer and the shard index. - long startPosition = Math.max(length - MAX_SHARD_INDEX_AND_FOOTER_SIZE, 0); - position(rawChannel, startPosition); - RandomAccessData data = - new RandomAccessData(ByteStreams.toByteArray(Channels.newInputStream(rawChannel))); - - // Read the fixed length footer. - this.footer = FooterCoder.of().decode( - data.asInputStream(data.size() - Footer.FIXED_LENGTH, Footer.FIXED_LENGTH), Context.OUTER); - - checkState(startPosition < footer.getIndexPosition(), - "Malformed file, expected to have been able to read entire shard index."); - int offsetWithinReadData = (int) (footer.getIndexPosition() - startPosition); - - // Decode the list of Ism shard descriptors - List ismShards = IsmFormat.ISM_SHARD_INDEX_CODER.decode( - data.asInputStream(offsetWithinReadData, data.size() - offsetWithinReadData), - Context.NESTED); - - // Build the shard id to shard descriptor map - ImmutableSortedMap.Builder shardIdToShardMapBuilder = - ImmutableSortedMap.orderedBy(Ordering.natural()); - for (IsmShard ismShard : ismShards) { - shardIdToShardMapBuilder.put(ismShard.getId(), ismShard); - } - shardIdToShardMap = shardIdToShardMapBuilder.build(); - - // Build the shard block offset to shard descriptor map - ImmutableSortedMap.Builder shardOffsetToShardMapBuilder = - ImmutableSortedMap.orderedBy(Ordering.natural()); - for (IsmShard ismShard : ismShards) { - shardOffsetToShardMapBuilder.put(ismShard.getBlockOffset(), ismShard); - } - shardOffsetToShardMap = shardOffsetToShardMapBuilder.build(); - - // We may have gotten the Bloom filter, if so lets store it. - if (startPosition < footer.getBloomFilterPosition()) { - offsetWithinReadData = (int) (footer.getBloomFilterPosition() - startPosition); - bloomFilter = ScalableBloomFilterCoder.of().decode( - data.asInputStream(offsetWithinReadData, data.size() - offsetWithinReadData), - Context.NESTED); - } - - // TODO: We may have gotten the entire file so we should populate our cache to - // prevent a re-read of the same data. - - return Optional.of(rawChannel); - } - - /** - * Initializes the Bloom filter and index per shard. We prepopulate empty indices - * for shards where the index offset matches the following shard block offset. - * Re-uses the provided channel, returning it or a new one if this method - * was required to open one. - */ - private synchronized Optional initializeBloomFilterAndIndexPerShard( - Optional inChannel) throws IOException { - if (indexPerShard != null) { - checkState(bloomFilter != null, "Expected Bloom filter to have been initialized."); - return inChannel; - } - - SeekableByteChannel rawChannel = openIfNeeded(inChannel); - - // initializeFooterAndShardIndex may have initialized the Bloom filter - // if the file is small enough. - if (bloomFilter == null) { - // Set the position to where the bloom filter is and read it in. - position(rawChannel, footer.getBloomFilterPosition()); - bloomFilter = ScalableBloomFilterCoder.of().decode( - Channels.newInputStream(rawChannel), Context.NESTED); - } - - indexPerShard = new HashMap<>(); - // If a shard is small, it may not contain an index and we can detect this and - // prepopulate the shard index map with an empty entry if the start of the index - // and start of the next block are equal - Iterator shardIterator = shardOffsetToShardMap.values().iterator(); - - // If file is empty we just return here. - if (!shardIterator.hasNext()) { - return Optional.of(rawChannel); - } - - // If the current shard's index position is equal to the next shards block offset - // then we know that the index contains no data and we can pre-populate it with - // the empty map. - IsmShard currentShard = shardIterator.next(); - while (shardIterator.hasNext()) { - IsmShard nextShard = shardIterator.next(); - if (currentShard.getIndexOffset() == nextShard.getBlockOffset()) { - indexPerShard.put(currentShard.getId(), - ImmutableSortedMap.orderedBy( - RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR) - .put( - new RandomAccessData(0), - new IsmShardKey( - IsmReader.this.filename, - new RandomAccessData(0), - currentShard.getBlockOffset(), - currentShard.getIndexOffset())).build()); - } - currentShard = nextShard; - } - - // Add an entry for the last shard if its index offset is equivalent to the - // start of the Bloom filter, then we know that the index is empty. - if (currentShard.getIndexOffset() == footer.getBloomFilterPosition()) { - indexPerShard.put(currentShard.getId(), - ImmutableSortedMap.orderedBy( - RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR) - .put( - new RandomAccessData(0), - new IsmShardKey( - IsmReader.this.filename, - new RandomAccessData(0), - currentShard.getBlockOffset(), - currentShard.getIndexOffset())).build()); - } - - return Optional.of(rawChannel); - } - - /** A unique key used to fully describe an Ism shard. */ - static class IsmShardKey { - private final String filename; - private final RandomAccessData firstKey; - private final long startOffset; - private final long endOffset; - - private IsmShardKey( - String filename, RandomAccessData firstKey, long startOffset, long endOffset) { - this.filename = filename; - this.firstKey = firstKey; - this.startOffset = startOffset; - this.endOffset = endOffset; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(IsmShardKey.class) - .add("filename", filename) - .add("firstKey", firstKey) - .add("startOffset", startOffset) - .add("endOffset", endOffset) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof IsmShardKey)) { - return false; - } - IsmShardKey cacheEntry = (IsmShardKey) obj; - return startOffset == cacheEntry.startOffset - && endOffset == cacheEntry.endOffset - && Objects.equals(filename, cacheEntry.filename) - && Objects.equals(firstKey, cacheEntry.firstKey); - } - - @Override - public int hashCode() { - return Longs.hashCode(startOffset) + Longs.hashCode(endOffset); - } - } - - /** - * Initializes the footer, shard index, Bloom filter and index for the requested shard id if - * they have not been initialized yet. Re-uses the provided channel, returning it or a - * new one if this method was required to open one. - */ - private Optional initializeForKeyedRead( - int shardId, Optional inChannel) throws IOException { - inChannel = initializeFooterAndShardIndex(inChannel); - - IsmShard shardWithIndex = shardIdToShardMap.get(shardId); - - // If this shard id is not within this file, we can return immediately. - if (shardWithIndex == null) { - return inChannel; - } - - inChannel = initializeBloomFilterAndIndexPerShard(inChannel); - - // If the index has been populated and contains the shard id, we can return. - if (indexPerShard != null && indexPerShard.containsKey(shardId)) { - checkState(bloomFilter != null, "Bloom filter expected to have been initialized."); - return inChannel; - } - - checkState(indexPerShard.get(shardId) == null, - "Expected to not have initialized index for shard %s", shardId); - - Long startOfNextBlock = shardOffsetToShardMap.higherKey(shardWithIndex.getBlockOffset()); - // If this is the last block, then we need to grab the position of the Bloom filter - // as the upper bound. - if (startOfNextBlock == null) { - startOfNextBlock = footer.getBloomFilterPosition(); - } - - // Open the channel if needed and seek to the start of the index. - SeekableByteChannel rawChannel = openIfNeeded(inChannel); - rawChannel.position(shardWithIndex.getIndexOffset()); - InputStream inStream = Channels.newInputStream(rawChannel); - - ImmutableSortedMap.Builder builder = - ImmutableSortedMap.orderedBy(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR); - - // Read the first key - RandomAccessData currentKeyBytes = new RandomAccessData(); - readKey(inStream, currentKeyBytes); - long currentOffset = VarInt.decodeLong(inStream); - - // Insert the entry that happens at the beginning limiting the shard block by the - // first keys block offset. - builder.put( - new RandomAccessData(0), - new IsmShardKey( - IsmReader.this.filename, - new RandomAccessData(0), - shardWithIndex.getBlockOffset(), - currentOffset)); - - // While another index entry exists, insert an index entry with the key, and offsets - // that limit the range of the shard block. - while (rawChannel.position() < startOfNextBlock) { - RandomAccessData nextKeyBytes = currentKeyBytes.copy(); - readKey(inStream, nextKeyBytes); - long nextOffset = VarInt.decodeLong(inStream); - - builder.put(currentKeyBytes, - new IsmShardKey( - IsmReader.this.filename, currentKeyBytes, currentOffset, nextOffset)); - - currentKeyBytes = nextKeyBytes; - currentOffset = nextOffset; - } - - // Upper bound the last entry with the index offset. - builder.put(currentKeyBytes, - new IsmShardKey( - IsmReader.this.filename, - currentKeyBytes, - currentOffset, - shardWithIndex.getIndexOffset())); - indexPerShard.put(shardId, builder.build()); - - return Optional.of(rawChannel); - } - - /** A function which takes an IsmShardKey fully describing a data block to read and return. */ - private class IsmCacheLoader - implements Callable>>>> { - - private final IsmShardKey key; - private IsmCacheLoader(IsmShardKey key) { - this.key = key; - } - - @Override - public WeightedValue>>> call() - throws IOException { - // Open a channel and build a sorted map from key to value for each key value - // pair found within the data block. - try (SeekableByteChannel rawChannel = open()) { - try (WithinShardIsmReaderIterator readerIterator = new WithinShardIsmReaderIterator( - rawChannel, key.firstKey, key.startOffset, key.endOffset)) { - - ImmutableSortedMap.Builder>> mapBuilder = - ImmutableSortedMap.orderedBy(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR); - while (readerIterator.hasNext()) { - RandomAccessData nextKey = readerIterator.peekKey().copy(); - WindowedValue> next = readerIterator.next(); - mapBuilder.put(nextKey, next); - } - // We return the size of the data block as the weight of this data block. - return WeightedValue.of( - (NavigableMap>>) mapBuilder.build(), - key.endOffset - key.startOffset); - } - } - } - } - - /** - * Fetches the data block requested. - * - * If the cache is available, we will load and cache the requested block. Otherwise, we will - * load and return the block. - */ - private NavigableMap>> - fetch(IsmShardKey key) throws IOException { - try { - if (cache == null) { - return new IsmCacheLoader(key).call().getValue(); - } else { - return cache.get(key, new IsmCacheLoader(key)).getValue(); - } - } catch (ExecutionException e) { - // Try and re-throw the root cause if its an IOException - Throwables.propagateIfPossible(e.getCause(), IOException.class); - throw new IOException(e.getCause()); - } - } - - /** The base class of Ism reader iterators which operate over a given key prefix. */ - abstract class IsmPrefixReaderIterator - extends LegacyReaderIterator>> { - private final List keyComponents; - private IsmPrefixReaderIterator(List keyComponents) { - this.keyComponents = keyComponents; - } - - /** - * Returns the list of key components representing this iterators key prefix. - */ - protected List getKeyComponents() { - return keyComponents; - } - - /** - * Concatenates this reader iterators key components with the additionally supplied - * key components and encodes them into their byte representations producing a key. - * Returns the exact record represented by the key generated above. - * - * Null is returned if no key has all the key components as a prefix within this file. - */ - public final WindowedValue> get(List additionalKeyComponents) - throws IOException { - RandomAccessData keyBytes = new RandomAccessData(); - int shardId = coder.encodeAndHash( - ImmutableList.builder().addAll(keyComponents).addAll(additionalKeyComponents).build(), - keyBytes); - return getBlock(keyBytes, shardId).get(keyBytes); - } - - /** - * Returns the record for the last key having this iterators key prefix. - * Last is defined as the largest key with the same key prefix when comparing key's - * byte representations using an unsigned lexicographical byte order. - * - * Null is returned if the prefix is not present within this file. - */ - public WindowedValue> getLast() throws IOException { - RandomAccessData keyBytes = new RandomAccessData(); - int shardId = coder.encodeAndHash(keyComponents, keyBytes); - - Optional inChannel = - initializeFooterAndShardIndex(Optional.absent()); - - // Key is not stored here - if (!shardIdToShardMap.containsKey(shardId) - || !bloomFilterMightContain(keyBytes)) { - return null; - } - - inChannel = initializeForKeyedRead(shardId, inChannel); - closeIfPresent(inChannel); - - final NavigableMap indexInShard = indexPerShard.get(shardId); - RandomAccessData end = keyBytes.increment(); - final IsmShardKey cacheEntry = indexInShard.floorEntry(end).getValue(); - - NavigableMap>> block = fetch(cacheEntry); - - RandomAccessData lastKey = block.lastKey(); - - // If the requested key is greater then the last key within the block, then it - // does not exist. - if (RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare(keyBytes, lastKey) > 0) { - return null; - } - - Entry>> rval = block.floorEntry(end); - - // If the prefix matches completely then we can return - if (RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.commonPrefixLength( - keyBytes, rval.getKey()) == keyBytes.size()) { - return rval.getValue(); - } - return null; - } - } - - /** An empty reader iterator. */ - class EmptyIsmPrefixReaderIterator extends IsmPrefixReaderIterator { - private EmptyIsmPrefixReaderIterator(List keyComponents) { - super(keyComponents); - } - - @Override - public boolean hasNextImpl() throws IOException { - return false; - } - - @Override - public WindowedValue> nextImpl() throws IOException, NoSuchElementException { - throw new NoSuchElementException(); - } - } - - /** A reader iterator which initializes its input stream lazily. */ - class LazyIsmPrefixReaderIterator extends IsmPrefixReaderIterator { - private IsmPrefixReaderIterator delegate; - - public LazyIsmPrefixReaderIterator() { - super(ImmutableList.of()); - } - - @Override - public boolean hasNextImpl() throws IOException { - return getDelegate().hasNext(); - } - - @Override - public WindowedValue> nextImpl() - throws IOException, NoSuchElementException { - WindowedValue> rval = getDelegate().next(); - return rval; - } - - @Override - public void close() throws IOException { - if (delegate != null) { - delegate.close(); - } - } - - /** Return a reader, caching the creation on the first call. */ - private IsmPrefixReaderIterator getDelegate() throws IOException { - if (delegate == null) { - delegate = overKeyComponents(getKeyComponents()); - } - return delegate; - } - } - - /** - * Returns a map from key to value, where the keys are in increasing lexicographical order. - * If the requested key is not contained within this file, an empty map is returned. - */ - private NavigableMap>> - getBlock(RandomAccessData keyBytes, int shardId) throws IOException { - Optional inChannel = - initializeFooterAndShardIndex(Optional.absent()); - - // Key is not stored here so return an empty map. - if (!shardIdToShardMap.containsKey(shardId) - || !bloomFilterMightContain(keyBytes)) { - return ImmutableSortedMap.>>orderedBy( - RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR).build(); - } - - inChannel = initializeForKeyedRead(shardId, inChannel); - closeIfPresent(inChannel); - - final NavigableMap indexInShard = indexPerShard.get(shardId); - final IsmShardKey cacheEntry = indexInShard.floorEntry(keyBytes).getValue(); - return fetch(cacheEntry); - } - - /** - * A reader iterator that returns all elements from prefix (inclusive) to - * prefixUpperBound (exclusive) within the set of block entries provided. - */ - private class WithinShardIsmPrefixReaderIterator extends IsmPrefixReaderIterator { - private final Iterator blockEntriesIterator; - Iterator>> iterator; - private final RandomAccessData prefix; - private final RandomAccessData prefixUpperBound; - - private WithinShardIsmPrefixReaderIterator( - List keyComponents, - RandomAccessData prefix, - RandomAccessData prefixUpperBound, - Iterator blockEntriesIterator) { - super(keyComponents); - checkNotNull(blockEntriesIterator); - this.prefix = prefix; - this.prefixUpperBound = prefixUpperBound; - this.blockEntriesIterator = blockEntriesIterator; - } - - @Override - public boolean hasNextImpl() throws IOException { - // This is in a while loop because the blocks that we are asked to look into may - // not contain the key prefix. - while (iterator == null || !iterator.hasNext()) { - // If there are no blocks to iterate over we can return false - if (!blockEntriesIterator.hasNext()) { - return false; - } - - IsmShardKey nextBlock = blockEntriesIterator.next(); - NavigableMap>> map = - fetch(nextBlock); - SortedMap>> submap = - map.subMap(prefix, prefixUpperBound); - Collection>> values = submap.values(); - iterator = values.iterator(); - } - return iterator.hasNext(); - } - - @Override - public WindowedValue> nextImpl() - throws IOException, NoSuchElementException { - return iterator.next(); - } - } - - /** A reader iterator that returns all records across all shards contained within this file. */ - private class ShardAwareIsmPrefixReaderIterator extends IsmPrefixReaderIterator { - private final SeekableByteChannel rawChannel; - private WithinShardIsmReaderIterator delegate; - private Iterator shardEntries; - - private ShardAwareIsmPrefixReaderIterator( - List keyComponents, SeekableByteChannel rawChannel) throws IOException { - super(keyComponents); - checkState(shardOffsetToShardMap.size() > 0, - "Expected that shard offset to shard map has been initialized and is not empty."); - - this.rawChannel = rawChannel; - this.shardEntries = shardOffsetToShardMap.values().iterator(); - IsmShard firstShard = shardEntries.next(); - delegate = new WithinShardIsmReaderIterator( - rawChannel, - new RandomAccessData(), - firstShard.getBlockOffset(), - firstShard.getIndexOffset()); - } - - @Override - public boolean hasNextImpl() throws IOException { - // If the current shard has a value, or we have another shard index to - // look into then we know that there is another value. - return delegate.hasNext() || shardEntries.hasNext(); - } - - @Override - public WindowedValue> nextImpl() - throws IOException, NoSuchElementException { - // If our current shard index is empty, we need to move to the next one. - if (!delegate.hasNext()) { - moveToNextShard(); - } - WindowedValue> rval = delegate.next(); - return rval; - } - - @Override - public void close() throws IOException { - rawChannel.close(); - } - - @Override - public WindowedValue> getLast() throws IOException { - // Since this is an iterator over all of the file, we return the last record within the file. - int lastShardId = shardOffsetToShardMap.lastEntry().getValue().getId(); - initializeForKeyedRead(lastShardId, Optional.absent()); - NavigableMap>> lastBlock = - getBlock(indexPerShard.get(lastShardId).lastKey(), lastShardId); - return lastBlock.lastEntry().getValue(); - } - - private void moveToNextShard() throws IOException { - IsmShard nextIsmShard = shardEntries.next(); - checkState(nextIsmShard.getBlockOffset() >= rawChannel.position(), - "Expected channel read order to be sequential."); - - delegate = new WithinShardIsmReaderIterator( - rawChannel, new RandomAccessData(), - nextIsmShard.getBlockOffset(), nextIsmShard.getIndexOffset()); - - checkState(delegate.hasNext(), "Expected each shard to contain at least one entry."); - } - } - - /** - * A reader iterator for Ism formatted files which returns a sequence of Ism records - * from the underlying channel from where it is currently positioned till - * the supplied limit. - * - * This reader iterator will use the supplied bytes as the bytes for the previous key - * which is required to do the KeyPrefix based key decoding. - */ - private class WithinShardIsmReaderIterator - extends LegacyReaderIterator>> { - private final SeekableByteChannel rawChannel; - private final InputStream inStream; - private long readLimit; - private RandomAccessData keyBytes; - private boolean keyIsPeeked; - private long position; - - private WithinShardIsmReaderIterator( - SeekableByteChannel rawChannel, - RandomAccessData currentKeyBytes, - long newPosition, - long newLimit) throws IOException { - checkNotNull(rawChannel); - checkNotNull(currentKeyBytes); - checkArgument(newLimit >= 0L); - checkArgument(newPosition <= newLimit); - this.rawChannel = rawChannel; - this.inStream = Channels.newInputStream(rawChannel); - this.keyBytes = currentKeyBytes.copy(); - this.position = newPosition; - this.readLimit = newLimit; - this.keyIsPeeked = false; - IsmReader.position(rawChannel, newPosition); - } - - @Override - public boolean hasNextImpl() throws IOException { - if (position > readLimit) { - throw new IllegalStateException("Read past end of stream"); - } - return position < readLimit; - } - - @Override - public WindowedValue> nextImpl() throws IOException, NoSuchElementException { - RandomAccessData peekedKey = peekKey(); - keyIsPeeked = false; - - InputStream keyInputStream = peekedKey.asInputStream(0, peekedKey.size()); - List keyComponents = new ArrayList<>(coder.getKeyComponentCoders().size()); - for (int i = 0; i < coder.getKeyComponentCoders().size(); ++i) { - keyComponents.add(coder.getKeyComponentCoder(i).decode( - keyInputStream, - Context.NESTED)); - } - - final IsmRecord ismRecord; - if (IsmFormat.isMetadataKey(keyComponents)) { - byte[] metadata = ByteArrayCoder.of().decode(inStream, Context.NESTED); - ismRecord = IsmRecord.meta(keyComponents, metadata); - } else { - V value = coder.getValueCoder().decode(inStream, Context.NESTED); - ismRecord = IsmRecord.of(keyComponents, value); - } - - long newPosition = rawChannel.position(); - notifyElementRead(newPosition - position); - position = newPosition; - return valueInEmptyWindows(ismRecord); - } - - public RandomAccessData peekKey() throws IOException, NoSuchElementException { - if (keyIsPeeked) { - return keyBytes; - } - readKey(inStream, keyBytes); - keyIsPeeked = true; - - return keyBytes; - } - } - - /** - * Decodes a KeyPrefix from the stream and then reads unshared key bytes from the stream - * placing them into the supplied keyBytes at position - * keyBytes[shared key bytes : shared key bytes + unshared key bytes]. - */ - private static void readKey(InputStream inStream, RandomAccessData keyBytes) - throws IOException { - KeyPrefix keyPrefix = KeyPrefixCoder.of().decode(inStream, Context.NESTED); - // currentKey = prevKey[0 : sharedKeySize] + read(unsharedKeySize) - keyBytes.readFrom( - inStream, - keyPrefix.getSharedKeySize() /* start to overwrite the previous key at sharedKeySize */, - keyPrefix.getUnsharedKeySize() /* read unsharedKeySize bytes from the stream */); - // Reset the length incase the next key was shorter. - keyBytes.resetTo(keyPrefix.getSharedKeySize() + keyPrefix.getUnsharedKeySize()); - } - - /** Closes the underlying channel if present. */ - private void closeIfPresent(Optional inChannel) throws IOException { - if (inChannel.isPresent()) { - inChannel.get().close(); - } - } - - /** Returns a channel, opening a new one if required. */ - private SeekableByteChannel openIfNeeded(Optional inChannel) - throws IOException { - if (inChannel.isPresent()) { - return inChannel.get(); - } - return open(); - } - - /** Opens a new channel. */ - private SeekableByteChannel open() - throws IOException { - ReadableByteChannel channel = IOChannelUtils.getFactory(filename).open(filename); - Preconditions.checkArgument(channel instanceof SeekableByteChannel, - "IsmReader requires a SeekableByteChannel for path %s but received %s.", - filename, channel); - return (SeekableByteChannel) channel; - } - - /** - * Seeks into the channel intelligently by either resetting the position or reading and - * discarding bytes. - */ - private static void position(SeekableByteChannel inChannel, long newPosition) throws IOException { - long currentPosition = inChannel.position(); - // If just doing a read is cheaper discarding the bytes lets just do the read - if (currentPosition < newPosition && newPosition - currentPosition <= SEEK_VS_READ) { - ByteStreams.skipFully(Channels.newInputStream(inChannel), newPosition - currentPosition); - } else { - // Otherwise we will perform a seek - inChannel.position(newPosition); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java deleted file mode 100644 index 72abe59a81..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReader.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntryReader; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.Preconditions; - -import java.io.IOException; -import java.util.Iterator; - -/** - * A source that reads from a key-sharded dataset, and returns KVs without - * any values grouping. - * - * @param the type of the keys read from the shuffle - * @param the type of the values read from the shuffle - */ -public class PartitioningShuffleReader extends NativeReader>> { - final byte[] shuffleReaderConfig; - final String startShufflePosition; - final String stopShufflePosition; - final CounterSet.AddCounterMutator addCounterMutator; - Coder keyCoder; - WindowedValueCoder windowedValueCoder; - - public PartitioningShuffleReader(PipelineOptions options, byte[] shuffleReaderConfig, - String startShufflePosition, String stopShufflePosition, Coder>> coder, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - this.shuffleReaderConfig = shuffleReaderConfig; - this.startShufflePosition = startShufflePosition; - this.stopShufflePosition = stopShufflePosition; - this.addCounterMutator = addCounterMutator; - initCoder(coder); - } - - /** - * Given a {@code WindowedValueCoder>}, splits it into a coder for K - * and a {@code WindowedValueCoder} with the same kind of windows. - */ - private void initCoder(Coder>> coder) throws Exception { - if (!(coder instanceof WindowedValueCoder)) { - throw new Exception("unexpected kind of coder for WindowedValue: " + coder); - } - WindowedValueCoder> windowedElemCoder = ((WindowedValueCoder>) coder); - Coder> elemCoder = windowedElemCoder.getValueCoder(); - if (!(elemCoder instanceof KvCoder)) { - throw new Exception("unexpected kind of coder for elements read from " - + "a key-partitioning shuffle: " + elemCoder); - } - @SuppressWarnings("unchecked") - KvCoder kvCoder = (KvCoder) elemCoder; - this.keyCoder = kvCoder.getKeyCoder(); - windowedValueCoder = windowedElemCoder.withValueCoder(kvCoder.getValueCoder()); - } - - @Override - public NativeReaderIterator>> iterator() throws IOException { - Preconditions.checkArgument(shuffleReaderConfig != null); - return iterator(new BatchingShuffleEntryReader( - new ChunkingShuffleBatchReader( - new ApplianceShuffleReader( - shuffleReaderConfig, - addCounterMutator)))); - } - - PartitioningShuffleReaderIterator iterator(ShuffleEntryReader reader) { - return new PartitioningShuffleReaderIterator(reader); - } - - /** - * A ReaderIterator that reads from a ShuffleEntryReader, - * extracts K and {@code WindowedValue}, and returns a constructed - * {@code WindowedValue}. - */ - class PartitioningShuffleReaderIterator extends LegacyReaderIterator>> { - Iterator iterator; - - PartitioningShuffleReaderIterator(ShuffleEntryReader reader) { - this.iterator = reader.read( - ByteArrayShufflePosition.fromBase64(startShufflePosition), - ByteArrayShufflePosition.fromBase64(stopShufflePosition)); - } - - @Override - protected boolean hasNextImpl() throws IOException { - return iterator.hasNext(); - } - - @Override - protected WindowedValue> nextImpl() throws IOException { - ShuffleEntry record = iterator.next(); - K key = CoderUtils.decodeFromByteArray(keyCoder, record.getKey()); - WindowedValue windowedValue = - CoderUtils.decodeFromByteArray(windowedValueCoder, record.getValue()); - notifyElementRead(record.length()); - return windowedValue.withValue(KV.of(key, windowedValue.getValue())); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java deleted file mode 100644 index cb68eefa3f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/PartitioningShuffleReaderFactory.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.values.KV; - -import javax.annotation.Nullable; - -/** - * Creates a PartitioningShuffleReader from a CloudObject spec. - */ -public class PartitioningShuffleReaderFactory implements ReaderFactory { - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - checkNotNull(options, "PipelineOptions must not be null in PartitioningShuffleReaderFactory"); - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder>> typedCoder = - (Coder>>) coder; - return createTyped(spec, options, typedCoder, addCounterMutator); - } - - public PartitioningShuffleReader createTyped( - CloudObject spec, - PipelineOptions options, - Coder>> coder, - CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - return new PartitioningShuffleReader( - options, - decodeBase64(getString(spec, PropertyNames.SHUFFLE_READER_CONFIG)), - getString(spec, PropertyNames.START_SHUFFLE_POSITION, null), - getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), - coder, - addCounterMutator); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java deleted file mode 100644 index 0fe0800810..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderCacheEntry.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.io.UnboundedSource; - -/** - * Entry in a per-key UnboundedSource#UnboundedReader cache. - */ -public class ReaderCacheEntry { - UnboundedSource.UnboundedReader reader; - long token; - - public ReaderCacheEntry(UnboundedSource.UnboundedReader reader, long token) { - this.reader = reader; - this.token = token; - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReader.java deleted file mode 100644 index 273456ddc5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleReader.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import java.io.IOException; - -/** - * ShuffleReader reads chunks of data from a shuffle dataset for - * a given position range. - */ -interface ShuffleReader { - /** Represents a chunk of data read from a shuffle dataset. */ - public static class ReadChunkResult { - public final byte[] chunk; - public final byte[] nextStartPosition; - public ReadChunkResult(byte[] chunk, byte[] nextStartPosition) { - this.chunk = chunk; - this.nextStartPosition = nextStartPosition; - } - } - - /** - * Reads a chunk of data for keys in the given position range. - * The chunk is a sequence of pairs encoded as: - * {@code - } - * where the sizes are 4-byte big-endian integers. - * - * @param startPosition the start of the requested range (inclusive) - * @param endPosition the end of the requested range (exclusive) - */ - public ReadChunkResult readIncludingPosition( - byte[] startPosition, byte[] endPosition) throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactory.java deleted file mode 100644 index 2845498eb3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReaderFactory.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.getLong; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import javax.annotation.Nullable; - -/** - * Creates a TextReader from a CloudObject spec. - */ -public class TextReaderFactory implements ReaderFactory { - - private static final TextReaderFactory INSTANCE = new TextReaderFactory(); - - public static TextReaderFactory getInstance() { - return INSTANCE; - } - - private TextReaderFactory() {} - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - return create(spec, coder); - } - - public TextReader create(CloudObject spec, Coder coder) throws Exception { - String filenameOrPattern = getString(spec, PropertyNames.FILENAME, null); - if (filenameOrPattern == null) { - filenameOrPattern = getString(spec, PropertyNames.FILEPATTERN, null); - } - return new TextReader<>(filenameOrPattern, - getBoolean(spec, PropertyNames.STRIP_TRAILING_NEWLINES, true), - getLong(spec, PropertyNames.START_OFFSET, null), - getLong(spec, PropertyNames.END_OFFSET, null), coder, - Enum.valueOf(TextIO.CompressionType.class, - getString(spec, PropertyNames.COMPRESSION_TYPE, "AUTO"))); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java deleted file mode 100644 index 391f169bf6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReader.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.BatchingShuffleEntryReader; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntryReader; -import com.google.common.base.Preconditions; - -import java.io.IOException; -import java.util.Iterator; - -import javax.annotation.Nullable; - -/** - * A source that reads from a shuffled dataset, without any key grouping. - * Returns just the values. (This reader is for an UNGROUPED shuffle session.) - * - * @param the type of the elements read from the source - */ -public class UngroupedShuffleReader extends NativeReader { - final byte[] shuffleReaderConfig; - final String startShufflePosition; - final String stopShufflePosition; - final Coder coder; - final CounterSet.AddCounterMutator addCounterMutator; - - public UngroupedShuffleReader( - @SuppressWarnings("unused") PipelineOptions options, byte[] shuffleReaderConfig, - @Nullable String startShufflePosition, @Nullable String stopShufflePosition, Coder coder, - @Nullable CounterSet.AddCounterMutator addCounterMutator) { - this.shuffleReaderConfig = shuffleReaderConfig; - this.startShufflePosition = startShufflePosition; - this.stopShufflePosition = stopShufflePosition; - this.coder = coder; - this.addCounterMutator = addCounterMutator; - } - - @Override - public NativeReaderIterator iterator() throws IOException { - Preconditions.checkArgument(shuffleReaderConfig != null); - return iterator(new BatchingShuffleEntryReader( - new ChunkingShuffleBatchReader( - new ApplianceShuffleReader( - shuffleReaderConfig, - addCounterMutator)))); - } - - UngroupedShuffleReaderIterator iterator(ShuffleEntryReader reader) { - return new UngroupedShuffleReaderIterator(reader); - } - - /** - * A ReaderIterator that reads from a ShuffleEntryReader and extracts - * just the values. - */ - class UngroupedShuffleReaderIterator extends LegacyReaderIterator { - Iterator iterator; - - UngroupedShuffleReaderIterator(ShuffleEntryReader reader) { - this.iterator = reader.read( - ByteArrayShufflePosition.fromBase64(startShufflePosition), - ByteArrayShufflePosition.fromBase64(stopShufflePosition)); - } - - @Override - protected boolean hasNextImpl() throws IOException { - return iterator.hasNext(); - } - - @Override - protected T nextImpl() throws IOException { - ShuffleEntry record = iterator.next(); - // Throw away the primary and the secondary keys. - byte[] value = record.getValue(); - notifyElementRead(record.length()); - return CoderUtils.decodeFromByteArray(coder, value); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java deleted file mode 100644 index dbf0bed403..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UngroupedShuffleReaderFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import javax.annotation.Nullable; - -/** - * Creates an UngroupedShuffleReader from a CloudObject spec. - */ -public class UngroupedShuffleReaderFactory implements ReaderFactory { - - @Override - public NativeReader create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception { - return create(spec, coder, options, addCounterMutator); - } - - public UngroupedShuffleReader create( - CloudObject spec, - Coder coder, - PipelineOptions options, - CounterSet.AddCounterMutator addCounterMutator) throws Exception { - return create(options, spec, coder, addCounterMutator); - } - - UngroupedShuffleReader create( - PipelineOptions options, - CloudObject spec, - Coder coder, - CounterSet.AddCounterMutator addCounterMutator) throws Exception { - return new UngroupedShuffleReader<>(options, - decodeBase64(getString(spec, PropertyNames.SHUFFLE_READER_CONFIG)), - getString(spec, PropertyNames.START_SHUFFLE_POSITION, null), - getString(spec, PropertyNames.END_SHUFFLE_POSITION, null), - coder, - addCounterMutator); - } -} From 9be2b2dbf232c6e7c85c44f0a4c3dbebeaf95732 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 8 Feb 2016 09:24:27 -0800 Subject: [PATCH 096/751] Move over IO sink factories and dependants This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114117322 --- .../worker/ApplianceShuffleWriter.java | 79 -- .../sdk/runners/worker/AvroByteSink.java | 83 --- .../sdk/runners/worker/AvroSinkFactory.java | 88 --- .../worker/ChunkingShuffleEntryWriter.java | 87 --- .../dataflow/sdk/runners/worker/IsmSink.java | 278 ------- .../sdk/runners/worker/IsmSinkFactory.java | 71 -- .../sdk/runners/worker/OrderedCode.java | 679 ------------------ .../runners/worker/ShuffleEntryWriter.java | 38 - .../sdk/runners/worker/ShuffleSink.java | 295 -------- .../runners/worker/ShuffleSinkFactory.java | 58 -- .../sdk/runners/worker/SinkFactory.java | 43 -- .../sdk/runners/worker/TextSinkFactory.java | 53 -- .../runners/worker/UserCodeTimeTracker.java | 156 ---- 13 files changed, 2008 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleEntryWriter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCode.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleEntryWriter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTracker.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java deleted file mode 100644 index ca633f00ea..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ApplianceShuffleWriter.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import java.io.IOException; -import javax.annotation.concurrent.ThreadSafe; - -/** - * ApplianceShuffleWriter writes chunks of data to a shuffle dataset. - * - *

    It is a JNI wrapper of an equivalent C++ class. - */ -@ThreadSafe -public final class ApplianceShuffleWriter implements ShuffleWriter { - static { - ShuffleLibrary.load(); - } - - /** - * Pointer to the underlying native shuffle writer code. - */ - private long nativePointer; - - /** - * Mutator that can be used to update counters. - */ - private final CounterSet.AddCounterMutator addCounterMutator; - - /** - * @param shuffleWriterConfig opaque configuration for creating a - * shuffle writer - * @param bufferSize the writer buffer size - * @param addCounterMutator mutator that can be used to update counters - */ - public ApplianceShuffleWriter( - byte[] shuffleWriterConfig, - long bufferSize, - CounterSet.AddCounterMutator addCounterMutator) { - this.nativePointer = createFromConfig(shuffleWriterConfig, bufferSize); - this.addCounterMutator = addCounterMutator; - } - - @Override - public void finalize() { - destroy(); - } - - /** - * Native methods for interacting with the underlying native shuffle - * writer code. - */ - private native long createFromConfig(byte[] shuffleWriterConfig, - long bufferSize); - private native void destroy(); - - public native String getDatasetId(); - - @Override - public native void write(byte[] chunk) throws IOException; - - @Override - public native void close() throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSink.java deleted file mode 100644 index 2fc0f4d5c3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroByteSink.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericDatumWriter; - -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * A sink that writes Avro files. Records are written to the Avro file as a - * series of byte arrays. The coder provided is used to serialize each record - * into a byte array. - * - * @param the type of the elements written to the sink - */ -public class AvroByteSink extends Sink { - - final AvroSink avroSink; - final Coder coder; - private final Schema schema = Schema.create(Schema.Type.BYTES); - - public AvroByteSink(String filenamePrefix, Coder coder) { - this(filenamePrefix, "", "", 1, coder); - } - - public AvroByteSink(String filenamePrefix, String shardFormat, String filenameSuffix, - int shardCount, Coder coder) { - this.coder = coder; - avroSink = new AvroSink<>( - filenamePrefix, shardFormat, filenameSuffix, shardCount, - WindowedValue.getValueOnlyCoder(AvroCoder.of(ByteBuffer.class, schema))); - } - - @Override - public SinkWriter writer() throws IOException { - return new AvroByteFileWriter(); - } - - /** The SinkWriter for an AvroByteSink. */ - class AvroByteFileWriter implements SinkWriter { - - private final SinkWriter> avroFileWriter; - - public AvroByteFileWriter() throws IOException { - avroFileWriter = avroSink.writer(new GenericDatumWriter(schema)); - } - - @Override - public long add(T value) throws IOException { - byte[] encodedElem = CoderUtils.encodeToByteArray(coder, value); - ByteBuffer encodedBuffer = ByteBuffer.wrap(encodedElem); - avroFileWriter.add(WindowedValue.valueInGlobalWindow(encodedBuffer)); - return encodedElem.length; - } - - @Override - public void close() throws IOException { - avroFileWriter.close(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java deleted file mode 100644 index bb881da9ec..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSinkFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue.ValueOnlyWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import javax.annotation.Nullable; - -/** - * Creates an {@link AvroSink} from a {@link CloudObject} spec. - */ -public final class AvroSinkFactory implements SinkFactory { - - @Override - public Sink create( - CloudObject spec, - Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - // Avro sinks are used both for outputting user data at the end of a pipeline and for - // materializing PCollections as intermediate results. It is important to distinguish these - // two cases because one requires only the values (outputting with AvroSink) and one requires - // the values along with their window and timestamp (materializing intermediate results with - // AvroByteSink). - // - // The logic we would like is "use AvroSink when writing at the end of a pipeline; use - // AvroByteSink for materialized results". - // - // ValueOnlyWindowedValueCoder is used to decode/encode the values read from a Source, and used - // to encode the values written to a Sink. FullWindowedValueCoder is used as the coder between - // other edges in a Dataflow pipeline graph. - // - // Checking that the provided coder is an instance of ValueOnlyWindowedValueCoder is almost - // enough to identify a user's AvroSink at the end of a pipeline, but it does not eliminate the - // case when we are materializing immediately after reading from a Source. If this was the - // entire check to decide to use AvroSink, there could be a crash when we materialized the - // output of a Source that does not use AvroCoder, such as TextIO with StringUtf8Coder. - // - // Adding the additional test that the inner value coder is an AvroCoder will eliminate the - // TextIO case but will leave sources that, like AvroSource, use AvroCoder to represent their - // values. This fixes the potential crash, but still would use AvroSink for intermediate - // results immediately after such a Source. - // - // Luckily, using AvroSink in these cases is safe. Though AvroSink will only encode the value, - // and will drop the associated timestamp and window, the dropped values were applied by - // ValueOnlyWindowedValueCoder and will be reapplied by the same when the file is re-read by - // later in the pipeline. - // - // Otherwise, this is definitely a materialized result and we should use the AvroByteSink to - // include the window and timestamp. - // - // See AvroReaderFactory#create for the accompanying reader logic. - String filename = getString(spec, PropertyNames.FILENAME); - - if (coder instanceof ValueOnlyWindowedValueCoder - && ((ValueOnlyWindowedValueCoder) coder).getValueCoder() instanceof AvroCoder) { - return new AvroSink(filename, (ValueOnlyWindowedValueCoder) coder); - } else { - return new AvroByteSink<>(filename, coder); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleEntryWriter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleEntryWriter.java deleted file mode 100644 index c8a408d054..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ChunkingShuffleEntryWriter.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import javax.annotation.concurrent.NotThreadSafe; - -/** - * ChunkingShuffleEntryWriter buffers ShuffleEntries and writes them - * in batches to a shuffle dataset using a given writer. - */ -@NotThreadSafe -final class ChunkingShuffleEntryWriter implements ShuffleEntryWriter { - // Approximate maximum size of a chunk in bytes. - private static final int MAX_CHUNK_SIZE = 1 << 20; - - private static final byte[] EMPTY_BYTES = new byte[0]; - - private ByteArrayOutputStream chunk = new ByteArrayOutputStream(); - - private DataOutputStream output = new DataOutputStream(chunk); - - private final ShuffleWriter writer; - - /** - * @param writer used to write chunks created by this writer - */ - public ChunkingShuffleEntryWriter(ShuffleWriter writer) { - this.writer = checkNotNull(writer); - } - - @Override - public void put(ShuffleEntry entry) throws IOException { - if (chunk.size() >= MAX_CHUNK_SIZE) { - writeChunk(); - } - - putFixedLengthPrefixedByteArray(entry.getKey(), output); - putFixedLengthPrefixedByteArray(entry.getSecondaryKey(), output); - putFixedLengthPrefixedByteArray(entry.getValue(), output); - } - - @Override - public void close() throws IOException { - writeChunk(); - writer.close(); - } - - private void writeChunk() throws IOException { - if (chunk.size() > 0) { - writer.write(chunk.toByteArray()); - chunk.reset(); - output = new DataOutputStream(chunk); - } - } - - static void putFixedLengthPrefixedByteArray(byte[] data, - DataOutputStream output) - throws IOException { - if (data == null) { - data = EMPTY_BYTES; - } - output.writeInt(data.length); - output.write(data, 0, data.length); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java deleted file mode 100644 index cdb565fff0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSink.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.Footer; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.FooterCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmShard; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefix; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.KeyPrefixCoder; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.RandomAccessData; -import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter; -import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter.ScalableBloomFilterCoder; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Optional; -import com.google.common.io.CountingOutputStream; - -import java.io.IOException; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.util.ArrayList; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -/** - * A {@link Sink} that writes Ism files. - * - * @param the type of the value written to the sink - */ -public class IsmSink extends Sink>> { - private static final int BLOCK_SIZE_BYTES = 1024 * 1024; - private final String filename; - private final IsmRecordCoder coder; - - /** - * Produces a sink for the specified {@code filename} and {@code coder}. - * See {@link IsmFormat} for encoded format details. - */ - IsmSink(String filename, IsmRecordCoder coder) { - IsmFormat.validateCoderIsCompatible(coder); - this.filename = filename; - this.coder = coder; - } - - @Override - public SinkWriter>> writer() throws IOException { - return new IsmSinkWriter(IOChannelUtils.create(filename, MimeTypes.BINARY)); - } - - // Can be overridden by tests to generate files with smaller block sizes for testing. - @VisibleForTesting - long getBlockSize() { - return BLOCK_SIZE_BYTES; - } - - private class IsmSinkWriter implements SinkWriter>> { - private final CountingOutputStream out; - private final RandomAccessData indexOut; - private RandomAccessData previousKeyBytes; - private Optional previousShard; - private RandomAccessData currentKeyBytes; - private RandomAccessData lastIndexKeyBytes; - private long lastIndexedPosition; - private long numberOfKeysWritten; - private SortedMap shardKeyToShardMap; - private final ScalableBloomFilter.Builder bloomFilterBuilder; - - /** - * Creates an IsmSinkWriter for the given channel. - */ - private IsmSinkWriter(WritableByteChannel channel) { - checkNotNull(channel); - out = new CountingOutputStream(Channels.newOutputStream(channel)); - indexOut = new RandomAccessData(); - previousShard = Optional.absent(); - previousKeyBytes = new RandomAccessData(); - currentKeyBytes = new RandomAccessData(); - lastIndexKeyBytes = new RandomAccessData(); - bloomFilterBuilder = ScalableBloomFilter.builder(); - shardKeyToShardMap = new TreeMap<>(); - } - - @Override - public long add(WindowedValue> windowedRecord) throws IOException { - // The windowed portion of the value is ignored. - IsmRecord record = windowedRecord.getValue(); - - checkArgument(coder.getKeyComponentCoders().size() == record.getKeyComponents().size()); - - List keyOffsetPositions = new ArrayList<>(); - final int currentShard = - coder.encodeAndHash(record.getKeyComponents(), currentKeyBytes, keyOffsetPositions); - // Put each component of the key into the Bloom filter so that we can use the Bloom - // filter for key prefix checks. - for (Integer offsetPosition : keyOffsetPositions) { - bloomFilterBuilder.put(currentKeyBytes.array(), 0, offsetPosition); - } - - // If we are moving to another shard, finish outputting the last shard. - if (previousShard.isPresent() && currentShard != previousShard.get()) { - // We reset last shard to be empty. - finishShard(); - } - - long currentPosition = out.getCount(); - - // If we are doing a reset because the shard number is changing we - // assume 0 bytes are saved from the previous key. - int sharedKeySize; - if (!previousShard.isPresent()) { - sharedKeySize = 0; - // Create a new shard record for the current value being output validating - // that we have never seen this shard before. - IsmShard ismShard = IsmShard.of(currentShard, currentPosition); - checkState(shardKeyToShardMap.put(currentShard, ismShard) == null, - "Unexpected insertion of keys %s for shard which already exists %s. " - + "Ism files expect that all shards are written contiguously.", - record.getKeyComponents(), ismShard); - } else { - sharedKeySize = commonPrefixLengthWithOrderCheck(previousKeyBytes, currentKeyBytes); - } - - // Put key-value mapping record into block buffer - int unsharedKeySize = currentKeyBytes.size() - sharedKeySize; - KeyPrefix keyPrefix = new KeyPrefix(sharedKeySize, unsharedKeySize); - KeyPrefixCoder.of().encode(keyPrefix, out, Context.NESTED); - currentKeyBytes.writeTo(out, sharedKeySize, unsharedKeySize); - if (IsmFormat.isMetadataKey(record.getKeyComponents())) { - ByteArrayCoder.of().encode(record.getMetadata(), out, Context.NESTED); - } else { - coder.getValueCoder().encode(record.getValue(), out, Context.NESTED); - } - - // If we have emitted enough bytes to add another entry into the index - if (out.getCount() > lastIndexedPosition + getBlockSize()) { - int sharedIndexKeySize = - commonPrefixLengthWithOrderCheck(lastIndexKeyBytes, currentKeyBytes); - int unsharedIndexKeySize = currentKeyBytes.size() - sharedIndexKeySize; - KeyPrefix indexKeyPrefix = new KeyPrefix(sharedIndexKeySize, unsharedIndexKeySize); - KeyPrefixCoder.of().encode(indexKeyPrefix, indexOut.asOutputStream(), Context.NESTED); - currentKeyBytes.writeTo( - indexOut.asOutputStream(), sharedIndexKeySize, unsharedIndexKeySize); - VarInt.encode(currentPosition, indexOut.asOutputStream()); - lastIndexKeyBytes.resetTo(0); - currentKeyBytes.writeTo(lastIndexKeyBytes.asOutputStream(), 0, currentKeyBytes.size()); - lastIndexedPosition = out.getCount(); - } - - // Remember the shard for the current key. - previousShard = Optional.of(currentShard); - - // Swap the current key and the previous key, resetting the previous key to be re-used. - RandomAccessData temp = previousKeyBytes; - previousKeyBytes = currentKeyBytes; - currentKeyBytes = temp; - currentKeyBytes.resetTo(0); - - numberOfKeysWritten += 1; - return out.getCount() - currentPosition; - } - - /** - * Compute the length of the common prefix of the previous key and the given key - * and perform a key order check. We check that the currently being inserted key - * is strictly greater than the previous key. - */ - private int commonPrefixLengthWithOrderCheck( - RandomAccessData prevKeyBytes, RandomAccessData currentKeyBytes) { - int offset = RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR - .commonPrefixLength(prevKeyBytes, currentKeyBytes); - int compare = RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR - .compare(prevKeyBytes, currentKeyBytes, offset); - if (compare < 0) { - return offset; - } else if (compare == 0) { - throw new IllegalArgumentException(IsmSinkWriter.class.getSimpleName() - + " expects keys to be written in strictly increasing order but was given " - + prevKeyBytes + " as the previous key and " + currentKeyBytes - + " as the current key. Expected " + prevKeyBytes.array()[offset + 1] + " <= " - + currentKeyBytes.array()[offset + 1] + " at position " + (offset + 1) + "."); - } else { - throw new IllegalArgumentException(IsmSinkWriter.class.getSimpleName() - + " expects keys to be written in strictly increasing order but was given " - + prevKeyBytes + " as the previous key and " + currentKeyBytes - + " as the current key. Expected length of previous key " + prevKeyBytes.size() - + " <= " + currentKeyBytes.size() + " to current key."); - } - } - - /** - * Outputs the end of a shard. This is done by: - *

      - *
    • updating the shard index for the current shard with the index offset
    • - *
    • writing out the index for the shard
    • - *
    • resetting the last indexed position
    • - *
    • forgetting the last shard
    • - *
    - */ - private void finishShard() throws IOException { - // Update the last shard record as to the position of the index. - IsmShard ismShard = shardKeyToShardMap.get(previousShard.get()); - shardKeyToShardMap.put( - previousShard.get(), ismShard.withIndexOffset(out.getCount())); - - indexOut.writeTo(out, 0, indexOut.size()); - indexOut.resetTo(0); - - // Reset the last indexed position to here. - lastIndexedPosition = out.getCount(); - lastIndexKeyBytes = new RandomAccessData(); - - // Clear the last shard. - previousShard = Optional.absent(); - } - - /** - * Completes the construction of the Ism file. This is done by: - *
      - *
    • finishing the last shard if present
    • - *
    • writing out the Bloom filter
    • - *
    • writing out the shard index
    • - *
    • writing out the footer
    • - *
    - * - * @throws IOException if an underlying write fails - */ - private void finish() throws IOException { - // Update the last shard if at least one element was written. - if (previousShard.isPresent()) { - finishShard(); - } - - long startOfBloomFilter = out.getCount(); - ScalableBloomFilterCoder.of().encode(bloomFilterBuilder.build(), out, Context.NESTED); - - long startOfIndex = out.getCount(); - IsmFormat.ISM_SHARD_INDEX_CODER.encode( - new ArrayList<>(shardKeyToShardMap.values()), out, Context.NESTED); - - FooterCoder.of().encode(new Footer(startOfIndex, startOfBloomFilter, numberOfKeysWritten), - out, Coder.Context.OUTER); - } - - @Override - public void close() throws IOException { - finish(); - out.close(); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java deleted file mode 100644 index 03ce0327c8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmSinkFactory.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import javax.annotation.Nullable; - -/** - * Creates an {@link IsmSink} from a {@link CloudObject} spec. Note that it is invalid to use a - * non {@link IsmRecordCoder} with this sink factory. - */ -public class IsmSinkFactory implements SinkFactory { - - @Override - public Sink create( - CloudObject spec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator) throws Exception { - - // The validity of this coder is checked in detail by the typed create, below - @SuppressWarnings("unchecked") - Coder>> typedCoder = - (Coder>>) coder; - - String filename = getString(spec, PropertyNames.FILENAME); - - checkArgument(typedCoder instanceof WindowedValueCoder, - "%s only supports using %s but got %s.", IsmSink.class, WindowedValueCoder.class, - typedCoder); - WindowedValueCoder> windowedCoder = - (WindowedValueCoder>) typedCoder; - - checkArgument(windowedCoder.getValueCoder() instanceof IsmRecordCoder, - "%s only supports using %s but got %s.", - IsmSink.class, IsmRecordCoder.class, windowedCoder.getValueCoder()); - @SuppressWarnings("unchecked") - IsmRecordCoder ismCoder = - (IsmRecordCoder) windowedCoder.getValueCoder(); - - return new IsmSink<>(filename, ismCoder); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCode.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCode.java deleted file mode 100644 index 37f8a1be2e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/OrderedCode.java +++ /dev/null @@ -1,679 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.common.math.LongMath; -import com.google.common.primitives.Longs; - -import java.math.RoundingMode; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * This module provides routines for encoding a sequence of typed - * entities into a byte array. The resulting byte arrays can be - * lexicographically compared to yield the same comparison value that - * would have been generated if the encoded items had been compared - * one by one according to their type. - * - *

    More precisely, suppose: - *

      - *
    1. byte array A is generated by encoding the sequence of items [A_1..A_n] - *
    2. byte array B is generated by encoding the sequence of items [B_1..B_n] - *
    3. The types match; i.e., for all i: A_i was encoded using - * the same routine as B_i - *
    - * Then: - * Comparing A vs. B lexicographically is the same as comparing - * the vectors [A_1..A_n] and [B_1..B_n] lexicographically. - * - *

    This class is NOT thread safe. - */ -public class OrderedCode { - // We want to encode a few extra symbols in strings: - // Separator between items - // Infinite string - // - // Therefore we need an alphabet with at least 258 characters. We - // achieve this by using two-letter sequences starting with '\0' and '\xff' - // as extra symbols: - // encoded as => \0\1 - // \0 encoded as => \0\xff - // \xff encoded as => \xff\x00 - // encoded as => \xff\xff - // - // The remaining two letter sequences starting with '\0' and '\xff' - // are currently unused. - - public static final byte ESCAPE1 = 0x00; - public static final byte NULL_CHARACTER = - (byte) 0xff; // Combined with ESCAPE1 - public static final byte SEPARATOR = 0x01; // Combined with ESCAPE1 - - public static final byte ESCAPE2 = (byte) 0xff; - public static final byte INFINITY = - (byte) 0xff; // Combined with ESCAPE2 - public static final byte FF_CHARACTER = 0x00; // Combined with ESCAPE2 - - public static final byte[] ESCAPE1_SEPARATOR = { ESCAPE1, SEPARATOR }; - - public static final byte[] INFINITY_ENCODED = { ESCAPE2, INFINITY }; - - /** - * This array maps encoding length to header bits in the first two bytes for - * SignedNumIncreasing encoding. - */ - private static final byte[][] LENGTH_TO_HEADER_BITS = { - { 0, 0 }, - { (byte) 0x80, 0 }, - { (byte) 0xc0, 0 }, - { (byte) 0xe0, 0 }, - { (byte) 0xf0, 0 }, - { (byte) 0xf8, 0 }, - { (byte) 0xfc, 0 }, - { (byte) 0xfe, 0 }, - { (byte) 0xff, 0 }, - { (byte) 0xff, (byte) 0x80 }, - { (byte) 0xff, (byte) 0xc0 } - }; - - /** - * This array maps encoding lengths to the header bits that overlap with - * the payload and need fixing during readSignedNumIncreasing. - */ - private static final long[] LENGTH_TO_MASK = { - 0L, - 0x80L, - 0xc000L, - 0xe00000L, - 0xf0000000L, - 0xf800000000L, - 0xfc0000000000L, - 0xfe000000000000L, - 0xff00000000000000L, - 0x8000000000000000L, - 0L - }; - - /** - * This array maps the number of bits in a number to the encoding - * length produced by WriteSignedNumIncreasing. - * For positive numbers, the number of bits is 1 plus the most significant - * bit position (the highest bit position in a positive long is 63). - * For a negative number n, we count the bits in ~n. - * That is, length = BITS_TO_LENGTH[log2Floor(n < 0 ? ~n : n) + 1]. - */ - private static final short[] BITS_TO_LENGTH = { - 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, - 3, 3, 3, 3, 3, 3, 3, - 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, - 6, 6, 6, 6, 6, 6, 6, - 7, 7, 7, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, - 9, 9, 9, 9, 9, 9, 9, - 10 - }; - - /** - * stores the current encoded value as a list of byte arrays. Note that this - * is manipulated as we read/write items. - * Note that every item will fit on at most one array. One array may - * have more than one item (eg when used for decoding). While encoding, - * one array will have exactly one item. While returning the encoded array - * we will merge all the arrays in this list. - */ - private final ArrayList encodedArrays = new ArrayList<>(); - - /** - * This is the current position on the first array. Will be non-zero - * only if the ordered code was created using encoded byte array. - */ - private int firstArrayPosition = 0; - - /** - * Creates OrderedCode from scractch. Typically used at encoding time. - */ - public OrderedCode(){ - } - - /** - * Creates OrderedCode from a given encoded byte array. Typically used at - * decoding time. - * - *

    For better performance, it uses the input array provided (not a copy). - * Therefore the input array should not be modified. - */ - public OrderedCode(byte[] encodedByteArray) { - encodedArrays.add(encodedByteArray); - } - - /** - * Adds the given byte array item to the OrderedCode. It encodes the input - * byte array, followed by a separator and appends the result to its - * internal encoded byte array store. - * - *

    It works with the input array, - * so the input array 'value' should not be modified till the method returns. - * - * @param value bytes to be written. - * @see #readBytes() - */ - public void writeBytes(byte[] value) { - // Determine the length of the encoded array - int encodedLength = 2; // for separator - for (byte b : value) { - if ((b == ESCAPE1) || (b == ESCAPE2)) { - encodedLength += 2; - } else { - encodedLength++; - } - } - - byte[] encodedArray = new byte[encodedLength]; - int copyStart = 0; - int outIndex = 0; - for (int i = 0; i < value.length; i++) { - byte b = value[i]; - if (b == ESCAPE1) { - System.arraycopy(value, copyStart, encodedArray, outIndex, - i - copyStart); - outIndex += i - copyStart; - encodedArray[outIndex++] = ESCAPE1; - encodedArray[outIndex++] = NULL_CHARACTER; - copyStart = i + 1; - } else if (b == ESCAPE2) { - System.arraycopy(value, copyStart, encodedArray, outIndex, - i - copyStart); - outIndex += i - copyStart; - encodedArray[outIndex++] = ESCAPE2; - encodedArray[outIndex++] = FF_CHARACTER; - copyStart = i + 1; - } - } - if (copyStart < value.length) { - System.arraycopy(value, copyStart, encodedArray, outIndex, - value.length - copyStart); - outIndex += value.length - copyStart; - } - encodedArray[outIndex++] = ESCAPE1; - encodedArray[outIndex] = SEPARATOR; - - encodedArrays.add(encodedArray); - } - - /** - * Encodes the long item, in big-endian format, and appends the result to its - * internal encoded byte array store. - * - *

    Note that the specified long is treated like a uint64, e.g. - * {@code new OrderedCode().writeNumIncreasing(-1L).getEncodedBytes()} - * is greater than - * {@code new OrderedCode().writeNumIncreasing(Long.MAX_VALUE).getEncodedBytes()}. - * - * @see #readNumIncreasing() - */ - public void writeNumIncreasing(long value) { - // Values are encoded with a single byte length prefix, followed - // by the actual value in big-endian format with leading 0 bytes - // dropped. - byte[] bufer = new byte[9]; // 8 bytes for value plus one byte for length - int len = 0; - while (value != 0) { - len++; - bufer[9 - len] = (byte) (value & 0xff); - value >>>= 8; - } - bufer[9 - len - 1] = (byte) len; - len++; - byte[] encodedArray = new byte[len]; - System.arraycopy(bufer, 9 - len, encodedArray, 0, len); - encodedArrays.add(encodedArray); - } - - /** - * Return floor(log2(n)) for positive integer n. Returns -1 iff n == 0. - */ - int log2Floor(long n) { - if (n < 0) { - throw new IllegalArgumentException("must be non-negative"); - } - return n == 0 ? -1 : LongMath.log2(n, RoundingMode.FLOOR); - } - - /** - * Calculates the encoding length in bytes of the signed number n. - */ - int getSignedEncodingLength(long n) { - return BITS_TO_LENGTH[log2Floor(n < 0 ? ~n : n) + 1]; - } - - /** - * Encodes the long item, in big-endian format, and appends the result to its - * internal encoded byte array store. - * - *

    Note that the specified long is treated like an int64, i.e. - * {@code new OrderedCode().writeNumIncreasing(-1L).getEncodedBytes()} - * is less than - * {@code new OrderedCode().writeNumIncreasing(0L).getEncodedBytes()}. - * - * @see #readSignedNumIncreasing() - */ - public void writeSignedNumIncreasing(long val) { - long x = val < 0 ? ~val : val; - if (x < 64) { // Fast path for encoding length == 1. - byte[] encodedArray = - new byte[] { (byte) (LENGTH_TO_HEADER_BITS[1][0] ^ val) }; - encodedArrays.add(encodedArray); - return; - } - // buf = val in network byte order, sign extended to 10 bytes. - byte signByte = val < 0 ? (byte) 0xff : 0; - byte[] buf = new byte[2 + Longs.BYTES]; - buf[0] = buf[1] = signByte; - System.arraycopy(Longs.toByteArray(val), 0, buf, 2, Longs.BYTES); - int len = getSignedEncodingLength(x); - if (len < 2) { - throw new IllegalStateException( - "Invalid length (" + len + ")" + - " returned by getSignedEncodingLength(" + x + ")"); - } - int beginIndex = buf.length - len; - buf[beginIndex] ^= LENGTH_TO_HEADER_BITS[len][0]; - buf[beginIndex + 1] ^= LENGTH_TO_HEADER_BITS[len][1]; - - byte[] encodedArray = new byte[len]; - System.arraycopy(buf, beginIndex, encodedArray, 0, len); - encodedArrays.add(encodedArray); - } - - /** - * Encodes and appends INFINITY item to its internal encoded byte array - * store. - * - * @see #readInfinity() - */ - public void writeInfinity() { - writeTrailingBytes(INFINITY_ENCODED); - } - - /** - * Appends the byte array item to its internal encoded byte array - * store. This is used for the last item and is not encoded. It - * also can be used to write a fixed number of bytes that will be - * read back using {@link #readBytes(int)}. - * - * - *

    It stores the input array in the store, - * so the input array 'value' should not be modified. - * - * @param value bytes to be written. - * @see #readTrailingBytes() - * @see #readBytes(int) - */ - public void writeTrailingBytes(byte[] value) { - if ((value == null) || (value.length == 0)) { - throw new IllegalArgumentException( - "Value cannot be null or have 0 elements"); - } - - encodedArrays.add(value); - } - - /** - * Returns the next byte array item from its encoded byte array store and - * removes the item from the store. - * - * @see #writeBytes(byte[]) - */ - public byte[] readBytes() { - if ((encodedArrays == null) || (encodedArrays.size() == 0) || - ((encodedArrays.get(0)).length - firstArrayPosition <= 0)) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - // Determine the length of the decoded array - // We only scan up to "length-2" since a valid string must end with - // a two character terminator: 'ESCAPE1 SEPARATOR' - byte[] store = encodedArrays.get(0); - int decodedLength = 0; - boolean valid = false; - int i = firstArrayPosition; - while (i < store.length - 1) { - byte b = store[i++]; - if (b == ESCAPE1) { - b = store[i++]; - if (b == SEPARATOR) { - valid = true; - break; - } else if (b == NULL_CHARACTER) { - decodedLength++; - } else { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - } else if (b == ESCAPE2) { - b = store[i++]; - if (b == FF_CHARACTER) { - decodedLength++; - } else { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - } else { - decodedLength++; - } - } - if (!valid) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - byte[] decodedArray = new byte[decodedLength]; - int copyStart = firstArrayPosition; - int outIndex = 0; - int j = firstArrayPosition; - while (j < store.length - 1) { - byte b = store[j++]; // note that j has been incremented - if (b == ESCAPE1) { - System.arraycopy(store, copyStart, decodedArray, outIndex, - j - copyStart - 1); - outIndex += j - copyStart - 1; - // ESCAPE1 SEPARATOR ends component - // ESCAPE1 NULL_CHARACTER represents '\0' - b = store[j++]; - if (b == SEPARATOR) { - if ((store.length - j) == 0) { - // we are done with the first array - encodedArrays.remove(0); - firstArrayPosition = 0; - } else { - firstArrayPosition = j; - } - return decodedArray; - } else if (b == NULL_CHARACTER) { - decodedArray[outIndex++] = 0x00; - } // else not required - handled during length determination - copyStart = j; - } else if (b == ESCAPE2) { - System.arraycopy(store, copyStart, decodedArray, outIndex, - j - copyStart - 1); - outIndex += j - copyStart - 1; - // ESCAPE2 FF_CHARACTER represents '\xff' - // ESCAPE2 INFINITY is an error - b = store[j++]; - if (b == FF_CHARACTER) { - decodedArray[outIndex++] = (byte) 0xff; - } // else not required - handled during length determination - copyStart = j; - } - } - // not required due to the first phase, but need to entertain the compiler - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - /** - * Returns the next long item (encoded in big-endian format via - * {@code writeNumIncreasing(long)}) from its internal encoded byte array - * store and removes the item from the store. - * - * @see #writeNumIncreasing(long) - */ - public long readNumIncreasing() { - if ((encodedArrays == null) || (encodedArrays.size() == 0) || - ((encodedArrays.get(0)).length - firstArrayPosition < 1)) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - byte[] store = encodedArrays.get(0); - // Decode length byte - int len = store[firstArrayPosition]; - if ((firstArrayPosition + len + 1 > store.length) || len > 8) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - long result = 0; - for (int i = 0; i < len; i++) { - result <<= 8; - result |= (store[firstArrayPosition + i + 1] & 0xff); - } - - if ((store.length - firstArrayPosition - len - 1) == 0) { - // we are done with the first array - encodedArrays.remove(0); - firstArrayPosition = 0; - } else { - firstArrayPosition = firstArrayPosition + len + 1; - } - - return result; - } - - /** - * Returns the next long item (encoded via - * {@code writeSignedNumIncreasing(long)}) from its internal encoded byte - * array store and removes the item from the store. - * - * @see #writeSignedNumIncreasing(long) - */ - public long readSignedNumIncreasing() { - if ((encodedArrays == null) || (encodedArrays.size() == 0) || - ((encodedArrays.get(0)).length - firstArrayPosition < 1)) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - byte[] store = encodedArrays.get(0); - - long xorMask = ((store[firstArrayPosition] & 0x80) == 0) ? ~0L : 0L; - // Store first byte as an int rather than a (signed) byte -- to avoid - // accidental byte-to-int promotion later, which would extend the byte's - // sign bit (if any). - int firstByte = - (store[firstArrayPosition] & 0xff) ^ (int) (xorMask & 0xff); - - // Now calculate and test length, and set x to raw (unmasked) result. - int len; - long x; - if (firstByte != 0xff) { - len = 7 - log2Floor(firstByte ^ 0xff); - if (store.length - firstArrayPosition < len) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - x = xorMask; // Sign extend using xorMask. - for (int i = firstArrayPosition; i < firstArrayPosition + len; i++) { - x = (x << 8) | (store[i] & 0xff); - } - } else { - len = 8; - if (store.length - firstArrayPosition < len) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - int secondByte = - (store[firstArrayPosition + 1] & 0xff) ^ (int) (xorMask & 0xff); - if (secondByte >= 0x80) { - if (secondByte < 0xc0) { - len = 9; - } else { - int thirdByte = - (store[firstArrayPosition + 2] & 0xff) ^ (int) (xorMask & 0xff); - if (secondByte == 0xc0 && thirdByte < 0x80) { - len = 10; - } else { - // Either len > 10 or len == 10 and #bits > 63. - throw new IllegalArgumentException("Invalid encoded byte array"); - } - } - if (store.length - firstArrayPosition < len) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - } - x = Longs.fromByteArray(Arrays.copyOfRange( - store, firstArrayPosition + len - 8, firstArrayPosition + len)); - } - - x ^= LENGTH_TO_MASK[len]; // Remove spurious header bits. - - if (len != getSignedEncodingLength(x)) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - if ((store.length - firstArrayPosition - len) == 0) { - // We are done with the first array. - encodedArrays.remove(0); - firstArrayPosition = 0; - } else { - firstArrayPosition = firstArrayPosition + len; - } - - return x; - } - - /** - * Removes INFINITY item from its internal encoded byte array store - * if present. Returns whether INFINITY was present. - * - * @see #writeInfinity() - */ - public boolean readInfinity() { - if ((encodedArrays == null) || (encodedArrays.size() == 0) || - ((encodedArrays.get(0)).length - firstArrayPosition < 1)) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - byte[] store = encodedArrays.get(0); - if (store.length - firstArrayPosition < 2) { - return false; - } - if ((store[firstArrayPosition] == ESCAPE2) && - (store[firstArrayPosition + 1] == INFINITY)) { - if ((store.length - firstArrayPosition - 2) == 0) { - // we are done with the first array - encodedArrays.remove(0); - firstArrayPosition = 0; - } else { - firstArrayPosition = firstArrayPosition + 2; - } - return true; - } else { - return false; - } - } - - /** - * Returns the trailing byte array item from its internal encoded byte array - * store and removes the item from the store. - * - * @see #writeTrailingBytes(byte[]) - */ - public byte[] readTrailingBytes() { - // one item is contained within one byte array - if ((encodedArrays == null) || (encodedArrays.size() != 1)) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - byte[] store = encodedArrays.get(0); - encodedArrays.remove(0); - assert encodedArrays.size() == 0; - return Arrays.copyOfRange(store, firstArrayPosition, store.length); - } - - /** - * Reads (unencoded) {@code len} bytes. - * - * @see #writeTrailingBytes(byte[]) - */ - public byte[] readBytes(int len) { - if ((encodedArrays == null) || (encodedArrays.size() == 0) || - ((encodedArrays.get(0)).length - firstArrayPosition < len)) { - throw new IllegalArgumentException("Invalid encoded byte array"); - } - - byte[] store = encodedArrays.get(0); - - byte[] result; - if (store.length - firstArrayPosition == len) { - // We are done with the first array. - result = encodedArrays.remove(0); - firstArrayPosition = 0; - } else { - result = new byte[len]; - System.arraycopy(store, firstArrayPosition, result, 0, len); - firstArrayPosition = firstArrayPosition + len; - } - return result; - } - - /** - * Returns the encoded bytes that represent the current state of the - * OrderedCode. - * - * - *

    NOTE: This method returns OrederedCode's internal array (not a - * copy) for better performance. Therefore the returned array should not be - * modified. - */ - public byte[] getEncodedBytes() { - if (encodedArrays.size() == 0) { - return new byte[0]; - } - if ((encodedArrays.size() == 1) && (firstArrayPosition == 0)) { - return encodedArrays.get(0); - } - - int totalLength = 0; - - for (int i = 0; i < encodedArrays.size(); i++) { - byte[] bytes = encodedArrays.get(i); - if (i == 0) { - totalLength += bytes.length - firstArrayPosition; - } else { - totalLength += bytes.length; - } - } - - byte[] encodedBytes = new byte[totalLength]; - int destPos = 0; - for (int i = 0; i < encodedArrays.size(); i++) { - byte[] bytes = encodedArrays.get(i); - if (i == 0) { - System.arraycopy(bytes, firstArrayPosition, encodedBytes, destPos, - bytes.length - firstArrayPosition); - destPos += bytes.length - firstArrayPosition; - } else { - System.arraycopy(bytes, 0, encodedBytes, destPos, bytes.length); - destPos += bytes.length; - } - } - - // replace the store with merged array, so that repeated calls - // don't need to merge. The reads can handle both the versions. - encodedArrays.clear(); - encodedArrays.add(encodedBytes); - firstArrayPosition = 0; - - return encodedBytes; - } - - /** - * Returns true if this has more encoded bytes that haven't been read, - * false otherwise. Return value of true doesn't imply anything about - * validity of remaining data. - * @return true if it has more encoded bytes that haven't been read, - * false otherwise. - */ - public boolean hasRemainingEncodedBytes() { - // We delete an array after fully consuming it. - return encodedArrays != null && encodedArrays.size() != 0; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleEntryWriter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleEntryWriter.java deleted file mode 100644 index bf1c21fed6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleEntryWriter.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; - -import java.io.IOException; - -import javax.annotation.concurrent.NotThreadSafe; - -/** - * ShuffleEntryWriter provides an interface for writing key/value - * entries to a shuffle dataset. - */ -@NotThreadSafe -interface ShuffleEntryWriter extends AutoCloseable { - /** - * Writes an entry to a shuffle dataset. - */ - public void put(ShuffleEntry entry) throws IOException; - - @Override - public void close() throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java deleted file mode 100644 index ea538db1a4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSink.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerHarnessOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.ShuffleEntry; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.Preconditions; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * A sink that writes to a shuffle dataset. - * - * @param the type of the elements written to the sink - */ -public class ShuffleSink extends Sink> { - enum ShuffleKind { - UNGROUPED, - PARTITION_KEYS, - GROUP_KEYS, - GROUP_KEYS_AND_SORT_VALUES - } - - static final long SHUFFLE_WRITER_BUFFER_SIZE = 128 << 20; - - final byte[] shuffleWriterConfig; - - final ShuffleKind shuffleKind; - - final PipelineOptions options; - - final CounterSet.AddCounterMutator addCounterMutator; - - boolean shardByKey; - boolean groupValues; - boolean sortValues; - - WindowedValueCoder windowedElemCoder; - WindowedValueCoder windowedValueCoder; - Coder elemCoder; - Coder keyCoder; - Coder valueCoder; - Coder sortKeyCoder; - Coder sortValueCoder; - - public static ShuffleKind parseShuffleKind(String shuffleKind) throws Exception { - try { - return Enum.valueOf(ShuffleKind.class, shuffleKind.trim().toUpperCase()); - } catch (IllegalArgumentException e) { - throw new Exception("unexpected shuffle_kind", e); - } - } - - public ShuffleSink(PipelineOptions options, byte[] shuffleWriterConfig, ShuffleKind shuffleKind, - Coder> coder, CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - this.shuffleWriterConfig = shuffleWriterConfig; - this.shuffleKind = shuffleKind; - this.options = options; - this.addCounterMutator = addCounterMutator; - initCoder(coder); - } - - private void initCoder(Coder> coder) throws Exception { - switch (shuffleKind) { - case UNGROUPED: - this.shardByKey = false; - this.groupValues = false; - this.sortValues = false; - break; - case PARTITION_KEYS: - this.shardByKey = true; - this.groupValues = false; - this.sortValues = false; - break; - case GROUP_KEYS: - this.shardByKey = true; - this.groupValues = true; - this.sortValues = false; - break; - case GROUP_KEYS_AND_SORT_VALUES: - this.shardByKey = true; - this.groupValues = true; - this.sortValues = true; - break; - default: - throw new AssertionError("unexpected shuffle kind"); - } - - this.windowedElemCoder = (WindowedValueCoder) coder; - this.elemCoder = windowedElemCoder.getValueCoder(); - if (shardByKey) { - if (!(elemCoder instanceof KvCoder)) { - throw new Exception("unexpected kind of coder for elements written to " - + "a key-grouping shuffle"); - } - KvCoder kvCoder = (KvCoder) elemCoder; - this.keyCoder = kvCoder.getKeyCoder(); - this.valueCoder = kvCoder.getValueCoder(); - if (sortValues) { - // TODO: Decide the representation of sort-keyed values. - // For now, we'll just use KVs. - if (!(valueCoder instanceof KvCoder)) { - throw new Exception("unexpected kind of coder for values written to " - + "a value-sorting shuffle"); - } - KvCoder kvValueCoder = (KvCoder) valueCoder; - this.sortKeyCoder = kvValueCoder.getKeyCoder(); - this.sortValueCoder = kvValueCoder.getValueCoder(); - } else { - this.sortKeyCoder = null; - this.sortValueCoder = null; - } - if (groupValues) { - this.windowedValueCoder = null; - } else { - this.windowedValueCoder = this.windowedElemCoder.withValueCoder(this.valueCoder); - } - } else { - this.keyCoder = null; - this.valueCoder = null; - this.sortKeyCoder = null; - this.sortValueCoder = null; - this.windowedValueCoder = null; - } - } - - /** - * Returns a SinkWriter that allows writing to this ShuffleSink, - * using the given ShuffleEntryWriter. The dataset ID is used to - * construct names of counters that track per-worker per-dataset - * bytes written to shuffle. - */ - public SinkWriter> writer(ShuffleEntryWriter writer, String datasetId) { - return new ShuffleSinkWriter(writer, options, addCounterMutator, datasetId); - } - - /** The SinkWriter for a ShuffleSink. */ - class ShuffleSinkWriter implements SinkWriter> { - private static final String COUNTER_WORKER_PREFIX = "worker-"; - private static final String COUNTER_DATASET_PREFIX = "-dataset-"; - private static final String COUNTER_SUFFIX = "-shuffle-bytes"; - - private ShuffleEntryWriter writer; - private long seqNum = 0; - private final Counter perWorkerPerDatasetBytesCounter; - // How many bytes were written to a given shuffle session, across all workers. - private final Counter perDatasetBytesCounter; - - ShuffleSinkWriter( - ShuffleEntryWriter writer, - PipelineOptions options, - CounterSet.AddCounterMutator addCounterMutator, - String datasetId) { - this.writer = writer; - DataflowWorkerHarnessOptions dataflowOptions = - options.as(DataflowWorkerHarnessOptions.class); - this.perWorkerPerDatasetBytesCounter = addCounterMutator.addCounter( - Counter.longs( - COUNTER_WORKER_PREFIX + dataflowOptions.getWorkerId() - + COUNTER_DATASET_PREFIX + datasetId + COUNTER_SUFFIX, - SUM)); - this.perDatasetBytesCounter = addCounterMutator.addCounter( - Counter.longs("dax-shuffle-" + datasetId + "-written-bytes", SUM)); - } - - @Override - public long add(WindowedValue windowedElem) throws IOException { - byte[] keyBytes; - byte[] secondaryKeyBytes; - byte[] valueBytes; - T elem = windowedElem.getValue(); - if (shardByKey) { - if (!(elem instanceof KV)) { - throw new AssertionError("expecting the values written to a key-grouping shuffle " - + "to be KVs"); - } - KV kv = (KV) elem; - Object key = kv.getKey(); - Object value = kv.getValue(); - - keyBytes = CoderUtils.encodeToByteArray(keyCoder, key); - - if (sortValues) { - if (!(value instanceof KV)) { - throw new AssertionError("expecting the value parts of the KVs written to " - + "a value-sorting shuffle to also be KVs"); - } - KV kvValue = (KV) value; - Object sortKey = kvValue.getKey(); - Object sortValue = kvValue.getValue(); - - // Sort values by key and then timestamp so that any GroupAlsoByWindows - // can run more efficiently. - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - sortKeyCoder.encode(sortKey, baos, Context.NESTED); - if (!windowedElem.getTimestamp().equals(BoundedWindow.TIMESTAMP_MIN_VALUE)) { - // Empty timestamp suffixes sort before all other sort value keys with - // the same prefix. So We can omit this suffix for this common value here - // for efficiency and only encode when its not the minimum timestamp. - InstantCoder.of().encode(windowedElem.getTimestamp(), baos, Context.OUTER); - } - secondaryKeyBytes = baos.toByteArray(); - valueBytes = CoderUtils.encodeToByteArray(sortValueCoder, sortValue); - } else if (groupValues) { - // Sort values by timestamp so that GroupAlsoByWindows can run efficiently. - if (windowedElem.getTimestamp().equals(BoundedWindow.TIMESTAMP_MIN_VALUE)) { - // Empty secondary keys sort before all other secondary keys, so we - // can omit this common value here for efficiency. - secondaryKeyBytes = null; - } else { - secondaryKeyBytes = - CoderUtils.encodeToByteArray(InstantCoder.of(), windowedElem.getTimestamp()); - } - valueBytes = CoderUtils.encodeToByteArray(valueCoder, value); - } else { - secondaryKeyBytes = null; - valueBytes = CoderUtils.encodeToByteArray( - windowedValueCoder, - windowedElem.withValue(value)); - } - - } else { - // Not partitioning or grouping by key, just resharding values. - // is ignored, except by the shuffle splitter. Use a seq# - // as the key, so we can split records anywhere. This also works - // for writing a single-sharded ordered PCollection through a - // shuffle, since the order of elements in the input will be - // preserved in the output. - keyBytes = CoderUtils.encodeToByteArray(BigEndianLongCoder.of(), seqNum++); - - secondaryKeyBytes = null; - valueBytes = CoderUtils.encodeToByteArray(windowedElemCoder, windowedElem); - } - - ShuffleEntry entry = new ShuffleEntry(keyBytes, secondaryKeyBytes, valueBytes); - writer.put(entry); - long bytes = entry.length(); - perWorkerPerDatasetBytesCounter.addValue(bytes); - perDatasetBytesCounter.addValue(bytes); - return bytes; - } - - @Override - public void close() throws IOException { - writer.close(); - } - } - - @Override - public SinkWriter> writer() throws IOException { - Preconditions.checkArgument(shuffleWriterConfig != null); - ApplianceShuffleWriter applianceWriter = new ApplianceShuffleWriter( - shuffleWriterConfig, SHUFFLE_WRITER_BUFFER_SIZE, addCounterMutator); - String datasetId = applianceWriter.getDatasetId(); - return writer(new ChunkingShuffleEntryWriter(applianceWriter), datasetId); - } - - @Override - protected StateKind getStateSamplerStateKind() { - return StateKind.FRAMEWORK; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java deleted file mode 100644 index 360a20bad8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleSinkFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.cloud.dataflow.sdk.runners.worker.ShuffleSink.parseShuffleKind; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import javax.annotation.Nullable; - -/** - * Creates a {@link ShuffleSink} from a {@link CloudObject} spec. - */ -public class ShuffleSinkFactory implements SinkFactory { - - @Override - public ShuffleSink create( - CloudObject spec, - Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - - @SuppressWarnings("unchecked") - Coder> typedCoder = - (Coder>) coder; - - return new ShuffleSink<>( - options, - decodeBase64(getString(spec, PropertyNames.SHUFFLE_WRITER_CONFIG, null)), - parseShuffleKind(getString(spec, PropertyNames.SHUFFLE_KIND)), - typedCoder, - addCounterMutator); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java deleted file mode 100644 index 6abef2c3b6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SinkFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import javax.annotation.Nullable; - -/** - * Constructs a {@link Sink} from a Dataflow service {@link CloudObject} specification. - */ -public interface SinkFactory { - - /** - * Creates a {@link Sink} from a Dataflow API Sink definition. - */ - Sink create( - CloudObject sinkSpec, - Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator) - throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java deleted file mode 100644 index 30b91b2cef..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSinkFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import javax.annotation.Nullable; - -/** - * Creates a {@link TextSink} from a {@link CloudObject} spec. - */ -public final class TextSinkFactory implements SinkFactory { - @Override - public TextSink create( - CloudObject spec, - Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator) - throws Exception { - return TextSink.create( - getString(spec, PropertyNames.FILENAME), - "", // No shard template - "", // No suffix - 1, // Exactly one output file - getBoolean(spec, PropertyNames.APPEND_TRAILING_NEWLINES, true), - getString(spec, PropertyNames.HEADER, null), - getString(spec, PropertyNames.FOOTER, null), - coder); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTracker.java deleted file mode 100644 index 15d8de9c84..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/UserCodeTimeTracker.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; - -import org.eclipse.jetty.util.ConcurrentHashSet; - -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * This class tracks the user code time spent on every work item executed by a Dataflow worker. - * User code time is the time spent on doing Dataflow SDK operations other than shuffling (like - * GroupByKey or CoGroupByKey) and reading / writing states from / to windmill. - * - *

    We assume that user code in work items is CPU-bound. To account for proportional slowdown in - * case there are more work items concurrently executing user code than there are CPUs, we introduce - * "effective user code time" that is invariant to the level of multithreading. More precisely, - * a unit of time spent in user code counts as min(1, numCPUs / numActiveItemsInUserCode) units of - * "effective time in user code". - */ -public class UserCodeTimeTracker { - private static class WorkItemInfo { - final Counter counter; - - public WorkItemInfo(String counterPrefix, AddCounterMutator mutator) { - counter = mutator.addCounter( - Counter.longs(counterPrefix + "user-code-msecs", Counter.AggregationKind.SUM)); - } - } - - /** - * Mapping from item id to WorkItemInfo. - */ - private final Map itemMap = new ConcurrentHashMap(); - - /** - * Set of the item ids in states with the kind StateSampler.StateKind.USER. - */ - private final Set itemsInUserState = new ConcurrentHashSet(); - - /** - * Records the start of the work. - * @param counterPrefix counter prefix associated with this work item. - * @param itemId id of the work. - * @param mutator counter mutator associated with this work item. - */ - public void workStarted(String counterPrefix, long itemId, AddCounterMutator mutator) { - if (itemMap.put(itemId, new WorkItemInfo(counterPrefix, mutator)) != null) { - throw new IllegalArgumentException("Item " + itemId + " already started."); - } - } - - /** - * Records the finish of the work. - * @param itemId id of the work. - */ - public void workFinished(long itemId) { - if (itemMap.remove(itemId) == null) { - throw new IllegalArgumentException("Item " + itemId + " never started."); - } - itemsInUserState.remove(itemId); - } - - /** - * Records the observation that the work with {@code itemId} has been in a state with {@code kind} - * for {@code elapsedMs} milliseconds. - * It is supposed to be called in a callback of a StateSampler. - * @param itemId the id of the work - * @param kind kind of the associated state - * @param elapsedMs time duration in milliseconds since the previous observation of this work - * item's state - */ - public void workObservedInState( - long itemId, StateKind kind, long elapsedMs) { - if (kind == StateSampler.StateKind.USER) { - itemsInUserState.add(itemId); - } else { - itemsInUserState.remove(itemId); - return; - } - - WorkItemInfo info = itemMap.get(itemId); - if (info == null) { - throw new NoSuchElementException("Item " + itemId + " doesn't exist."); - } - int numProcessors = getNumProcessors(); - int numActives = itemsInUserState.size(); - long userCodeMsecs = (long) (elapsedMs * Math.min(1.0, 1.0 * numProcessors / numActives)); - - info.counter.addValue(userCodeMsecs); - } - - /** - * Returns an AutoCloseable that will call {@link #workStarted} at first and will automatically - * call {@link #workFinished} upon closing. - * @param counterPrefix counter prefix associated with this work item. - * @param itemId id of the work. - * @param mutator counter mutator associated with this work item. - * @return an AutoCloseable that automatically call {@link #workFinished} upon closing. - */ - public AutoCloseable scopedWork( - String counterPrefix, final long itemId, final CounterSet.AddCounterMutator mutator) { - workStarted(counterPrefix, itemId, mutator); - return new AutoCloseable() { - @Override - public void close() throws Exception { - workFinished(itemId); - } - }; - } - - protected int getNumProcessors() { - return Runtime.getRuntime().availableProcessors(); - } - - /** - * A simple callback to be used to invoke {@code UserCodeTimeTracker.workObservedInState} from - * the StateSampler. - */ - public static class StateSamplerCallback implements StateSampler.SamplingCallback { - private final UserCodeTimeTracker tracker; - - private final long itemId; - - StateSamplerCallback(UserCodeTimeTracker tracker, long itemId) { - this.tracker = tracker; - this.itemId = itemId; - } - - @Override - public void run(int state, StateKind kind, long elapsedMs) { - tracker.workObservedInState(itemId, kind, elapsedMs); - } - } -} From 72097504b820e8ed054efb043b1b39c8e81283d5 Mon Sep 17 00:00:00 2001 From: tudorm Date: Mon, 8 Feb 2016 10:12:24 -0800 Subject: [PATCH 097/751] Render the /threadz page using plain text. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114122363 --- .../sdk/runners/worker/status/ThreadzServlet.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java index 0c8dc6a8aa..a1faba3180 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java @@ -35,21 +35,19 @@ public ThreadzServlet() { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.setContentType("text/html;charset=utf-8"); + response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); PrintWriter writer = response.getWriter(); - writer.println(""); Map stacks = Thread.getAllStackTraces(); for (Map.Entry entry : stacks.entrySet()) { Thread thread = entry.getKey(); - writer.println("Thread: " + thread + " State: " + thread.getState() + "
    "); + writer.println("--- Thread: " + thread + " State: " + + thread.getState() + " stack: ---"); for (StackTraceElement element : entry.getValue()) { - writer.println("  " + element + "
    "); + writer.println(" " + element); } - writer.println("
    "); } - writer.println(""); } } From d6e5cc9d5dcf119dfde9b54fe66ade99d9dec163 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 8 Feb 2016 11:05:01 -0800 Subject: [PATCH 098/751] Move remainder of status servlets This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114128541 --- .../worker/status/BaseStatusServlet.java | 60 --- .../runners/worker/status/HealthzServlet.java | 40 -- .../runners/worker/status/HeapzServlet.java | 97 ---- .../worker/status/StatusDataProvider.java | 25 - .../runners/worker/status/ThreadzServlet.java | 53 --- .../runners/worker/status/package-info.java | 23 - .../dataflow/sdk/util/MemoryMonitor.java | 428 ------------------ .../dataflow/sdk/util/MemoryMonitorTest.java | 86 ---- 8 files changed, 812 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MemoryMonitorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java deleted file mode 100644 index 23245bbab2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/BaseStatusServlet.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import com.google.common.base.Strings; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Base class for status servlets. - */ -public abstract class BaseStatusServlet extends HttpServlet { - - private final String path; - - protected BaseStatusServlet(String path) { - this.path = path.startsWith("/") ? path : "/" + path; - } - - /** - * Return the path that this servlet should listen on. - */ - public String getPath() { - return path; - } - - /** - * Return the servlet that this path is on, modified to include the specified query - * {@code parameters} if any. - */ - protected String getPath(String parameters) { - if (Strings.isNullOrEmpty(parameters)) { - return path; - } else { - return path + "?" + parameters; - } - } - - @Override - protected abstract void doGet(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java deleted file mode 100644 index 1f7c83c83f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HealthzServlet.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Respond to /healthz with "ok". - */ -public class HealthzServlet extends BaseStatusServlet { - - public HealthzServlet() { - super("healthz"); - } - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws IOException { - response.setContentType("text/html;charset=utf-8"); - response.setStatus(HttpServletResponse.SC_OK); - response.getWriter().println("ok"); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java deleted file mode 100644 index 363d26fb57..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/HeapzServlet.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import com.google.cloud.dataflow.sdk.util.MemoryMonitor; -import com.google.common.io.Files; - -import java.io.File; -import java.io.IOException; - -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MalformedObjectNameException; -import javax.management.ReflectionException; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Respond to /heapz with a page allowing downloading of the heap dumps. - * - *

    Respond to /heapz?action=download with a download of the actual heap dump. - */ -public class HeapzServlet extends BaseStatusServlet { - - public HeapzServlet() { - super("heapz"); - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String action = req.getParameter("action"); - if (action == null || action.isEmpty()) { - resp.setContentType("text/html;charset=utf-8"); - resp.setStatus(HttpServletResponse.SC_OK); - - ServletOutputStream writer = resp.getOutputStream(); - writer.println(""); - writer.println(String.format( - "Click here to download heap dump", getPath("action=download"))); - writer.println(""); - return; - } else if ("download".equals(action)) { - doDownload(resp); - } - } - - private void doDownload(HttpServletResponse resp) throws IOException { - File file; - - try { - file = MemoryMonitor.dumpHeap(); - } catch (MalformedObjectNameException - | InstanceNotFoundException | ReflectionException | MBeanException e) { - resp.setContentType("text/html;charset=utf-8"); - resp.setStatus(HttpServletResponse.SC_OK); - - ServletOutputStream writer = resp.getOutputStream(); - writer.println("\nFailed to dump heap:
    \n

    ");
    -      writer.println(e.toString());
    -      writer.println("
    \n"); - return; - } - - resp.setContentType("application/octet-stream"); - resp.setContentLength((int) file.length()); - resp.setHeader( - "Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); - - try { - Files.copy(file, resp.getOutputStream()); - resp.setStatus(HttpServletResponse.SC_OK); - } catch (IOException e) { - resp.reset(); - resp.setContentType("text/html;charset=utf-8"); - ServletOutputStream writer = resp.getOutputStream(); - writer.println("\nFailed to dump heap:
    \n
    \n");
    -      writer.println(e.toString());
    -      writer.println("
    \n"); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java deleted file mode 100644 index 91e962d331..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/StatusDataProvider.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import java.io.PrintWriter; - -/** - * Interface for providing information to the /statusz page. - */ -public interface StatusDataProvider { - void appendSummaryHtml(PrintWriter writer); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java deleted file mode 100644 index a1faba3180..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/ThreadzServlet.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.status; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Respond to /threadz with the stack traces of all running threads. - */ -class ThreadzServlet extends BaseStatusServlet { - - public ThreadzServlet() { - super("threadz"); - } - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws IOException { - response.setContentType("text/plain;charset=utf-8"); - response.setStatus(HttpServletResponse.SC_OK); - - PrintWriter writer = response.getWriter(); - - Map stacks = Thread.getAllStackTraces(); - for (Map.Entry entry : stacks.entrySet()) { - Thread thread = entry.getKey(); - writer.println("--- Thread: " + thread + " State: " - + thread.getState() + " stack: ---"); - for (StackTraceElement element : entry.getValue()) { - writer.println(" " + element); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java deleted file mode 100644 index 9138c155a6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/status/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Server and tools for the Worker Status pages. - */ -@ParametersAreNonnullByDefault -package com.google.cloud.dataflow.sdk.runners.worker.status; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java deleted file mode 100644 index 78df47ad5d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MemoryMonitor.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.runners.worker.status.StatusDataProvider; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.util.concurrent.AtomicDouble; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.PrintWriter; -import java.lang.management.GarbageCollectorMXBean; -import java.lang.management.ManagementFactory; -import java.util.ArrayDeque; -import java.util.Queue; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.ReflectionException; - -/** - * A runnable which monitors a server for GC thrashing. - * - *

    Note: Only one instance of this should be initialized per server and - * it should be done when the server starts running. - * - *

    This runnable works as follows: - *

      - *
    • It wakes up periodically and determines how much time was spend on garbage - * collection since the last time it woke up. - *
    • If the time spent in garbage collection in the last period of time - * exceeds a certain threshold, that period is marked as "being in GC thrashing" - *
    • It keeps track of the GC thrashing status of the last few periods. - *
    • Every time the runnable's thread wakes up, it computes the ratio - * {@code (# monitored periods in GC thrashing) / (# monitored periods)}. - *
    • If this ratio exceeds a certain threshold, it is assumed that the server - * is in GC thrashing. - *
    • It can also shutdown the current jvm runtime when a threshold of consecutive gc - * thrashing count is met. A heap dump is made before shutdown. - *
    - */ -public class MemoryMonitor implements Runnable, StatusDataProvider { - private static final Logger LOG = LoggerFactory.getLogger(MemoryMonitor.class); - - /** Directory to hold heap dumps if not overridden. */ - private static final String DEFAULT_LOGGING_DIR = "dataflow/logs"; - - /** - * Amount of time (in ms) this thread must sleep - * between two consecutive iterations. - */ - public static final long DEFAULT_SLEEP_TIME_MILLIS = 15 * 1000; // 15 sec. - - /** - * The number of periods to take into account when determining - * if the server is in GC thrashing. - */ - private static final int NUM_MONITORED_PERIODS = 4; // ie 1 min's worth. - - /** - * The GC thrashing threshold (0.00 - 100.00) for every period. If - * the time spent on garbage collection in one period exceeds this - * threshold, that period is considered to be in GC thrashing. - */ - private static final double GC_THRASHING_PERCENTAGE_PER_PERIOD = 50.0; - - /** - * The (# monitored periods in GC thrashing) / (# monitored - * periods) threshold after which the server is considered to be in - * GC thrashing, expressed as a percentage. - */ - private static final double GC_THRASHING_PERCENTAGE_PER_SERVER = 60.0; - - /** - * The amount of memory (in bytes) we should pre-allocate, in order - * to be able to dump the heap. - * - * Since the server is in GC thrashing when we try to dump the heap, we - * might not be able to successfully do it. However, if we pre-allocate a - * big enough block of memory and "release" it right before trying to dump - * the heap, the pre-allocated block of memory will get GCed, and the heap - * dump might succeed. - */ - private static final int HEAP_DUMP_RESERVED_BYTES = 10 << 20; // 10MB - - /** - * Shutdown the current JVM instance after given consecutive gc thrashing - * periods are detected. This offers an opportunity to fast kill a JVM server - * if it is about to enter a long lasting gc thrashing state, which is almost - * never a desired behavior for a healthy server. 0 to disable. - */ - private static final int DEFAULT_SHUT_DOWN_AFTER_NUM_GCTHRASHING = 8; // ie 2 min's worth. - - /** - * Delay between logging the current memory state. - */ - private static final int NORMAL_LOGGING_PERIOD_MILLIS = 5 * 60 * 1000; // 5 min. - - /** - * Abstract interface for providing GC stats (for testing). - */ - public interface GCStatsProvider { - /** - * Return the total milliseconds spent in GC since JVM was started. - */ - long totalGCTimeMilliseconds(); - } - - /** - * True system GC stats. - */ - private static class SystemGCStatsProvider implements GCStatsProvider { - @Override - public long totalGCTimeMilliseconds() { - long inGC = 0; - for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { - inGC += gc.getCollectionTime(); - } - return inGC; - } - } - - /** Where to get GC stats. */ - private final GCStatsProvider gcStatsProvider; - - /** Actual sleep time, in milliseconds, for main monitor. */ - private final long sleepTimeMillis; - - /** Actual number of cycles before shutting down VM. */ - private final int shutDownAfterNumGCThrashing; - - /** - * The state of the periods that are taken into account when - * deciding if the server is in GC thrashing. - */ - private final Queue periodIsThrashing = new ArrayDeque<>(); - - /** - * Keeps track of the time the server spent in GC since it started running. - */ - private long timeInGC = 0; - - /** - * A reserved block of memory, needed to dump the heap. Dumping the heap - * requires memory. However, since we try to do it when the server is in - * GC thrashing, no memory is available and dumpHeap() brings the server - * down. If we pre-allocate a block of memory though, and "release" it - * right before dumping the heap, this block of memory will be - * garbage collected, thus giving dumpHeap() enough space to dump the heap. - */ - @SuppressWarnings("unused") - private byte[] reservedForDumpingHeap = new byte[HEAP_DUMP_RESERVED_BYTES]; - - private final AtomicBoolean isThrashing = new AtomicBoolean(false); - - private final AtomicBoolean isStarted = new AtomicBoolean(false); - - private final AtomicDouble lastMeasuredGCPercentage = new AtomicDouble(0.0); - private final AtomicDouble maxGCPercentage = new AtomicDouble(0.0); - private final AtomicInteger numPushbacks = new AtomicInteger(0); - - /** Wait point for threads in pushback waiting for gc thrashing to pass. */ - private final Object waitingForResources = new Object(); - - public MemoryMonitor() { - gcStatsProvider = new SystemGCStatsProvider(); - sleepTimeMillis = DEFAULT_SLEEP_TIME_MILLIS; - shutDownAfterNumGCThrashing = DEFAULT_SHUT_DOWN_AFTER_NUM_GCTHRASHING; - } - - /** - * For testing only: Construct memory monitor which takes GC stats from given provider - * and uses given sleep time and shutdown threshold. - */ - @VisibleForTesting - public MemoryMonitor( - GCStatsProvider gcStatsProvider, long sleepTimeMillis, int shutDownAfterNumGCThrashing) { - this.gcStatsProvider = gcStatsProvider; - this.sleepTimeMillis = sleepTimeMillis; - this.shutDownAfterNumGCThrashing = shutDownAfterNumGCThrashing; - } - - /** - * Check if we've observed high gc workload in sufficient - * sample periods to justify classifying the server as in gc thrashing. - */ - private void updateIsThrashing() { - // have we monitored enough periods? - if (periodIsThrashing.size() < NUM_MONITORED_PERIODS) { - setIsThrashing(false); - return; - } - - // count the number of periods in GC thrashing - int numPeriodsInGCThrashing = 0; - for (Boolean state : periodIsThrashing) { - numPeriodsInGCThrashing += (state ? 1 : 0); - } - - // Did we have too many periods in GC thrashing? - boolean serverInGcThrashing = (numPeriodsInGCThrashing * 100 - >= periodIsThrashing.size() * GC_THRASHING_PERCENTAGE_PER_SERVER); - setIsThrashing(serverInGcThrashing); - } - - /** - * Set the thrashing state. - */ - private void setIsThrashing(boolean serverInGcThrashing) { - synchronized (waitingForResources) { - boolean prev = isThrashing.getAndSet(serverInGcThrashing); - if (prev && !serverInGcThrashing) { - waitingForResources.notifyAll(); - } - } - } - - /** - * Determines if too much time was spent on garbage collection in the last - * period of time. - * - * @param now The current time. - * @param lastTimeWokeUp The last time this thread woke up. - * - * @return The state of the last period of time. - */ - private boolean wasLastPeriodInGCThrashing(long now, long lastTimeWokeUp) { - // Find out how much time was spent on garbage collection - // since the start of the server. This queries the set of garbage collectors for - // how long each one has spent doing GC. - long inGC = gcStatsProvider.totalGCTimeMilliseconds(); - - // Compare the amount of time spent in GC thrashing to the given threshold; - // if config.getSleepTimeMillis() is equal to 0 (should happen in tests only), - // then we compare percentage-per-period to 100% - double gcPercentage = (inGC - timeInGC) * 100 / (now - lastTimeWokeUp); - - lastMeasuredGCPercentage.set(gcPercentage); - maxGCPercentage.set(Math.max(maxGCPercentage.get(), gcPercentage)); - timeInGC = inGC; - - return gcPercentage > GC_THRASHING_PERCENTAGE_PER_PERIOD; - } - - /** - * Updates the data we monitor. - * - * @param now The current time. - * @param lastTimeWokeUp The last time this thread woke up. - */ - private void updateData(long now, long lastTimeWokeUp) { - // remove data that's no longer relevant - int numIntervals = NUM_MONITORED_PERIODS; - while (periodIsThrashing.size() >= numIntervals) { - periodIsThrashing.poll(); - } - // store the state of the last period - boolean wasThrashing = wasLastPeriodInGCThrashing(now, lastTimeWokeUp); - periodIsThrashing.offer(wasThrashing); - } - - /** - * Dumps the heap to a file and return the name of the file, or - * null if the heap could not be dumped. - * - * @return The name of the file the heap was dumped to. - */ - private File tryToDumpHeap() { - // clearing this list should "release" some memory - // that will be needed to dump the heap - reservedForDumpingHeap = null; - - try { - return dumpHeap(); - } catch (Exception e) { - return null; - } - } - - /** - * Runs this thread. - */ - @Override - public void run() { - checkState(!isStarted.getAndSet(true), "run() called twice"); - - try { - long lastTimeWokeUp = System.currentTimeMillis(); - long lastLog = -1; - int currentThrashingCount = 0; - while (true) { - Thread.sleep(sleepTimeMillis); - long now = System.currentTimeMillis(); - - updateData(now, lastTimeWokeUp); - updateIsThrashing(); - - if (lastLog < 0 || lastLog + NORMAL_LOGGING_PERIOD_MILLIS < now) { - LOG.info("Memory is {}", describeMemory()); - lastLog = now; - } - - if (isThrashing.get()) { - currentThrashingCount++; - - if (shutDownAfterNumGCThrashing > 0 - && (currentThrashingCount >= shutDownAfterNumGCThrashing)) { - File heapDumpFile = tryToDumpHeap(); - LOG.error( - "Shutting down JVM after {} consecutive periods of measured GC thrashing. " - + "Memory is {}. Heap dump written to {}", - currentThrashingCount, describeMemory(), heapDumpFile); - System.exit(1); - } - } else { - // Reset the counter whenever the server is evaluated not under gc thrashing. - currentThrashingCount = 0; - } - - lastTimeWokeUp = now; - } - } catch (InterruptedException e) { - // most probably means that the server is shutting down - // in any case, there's not much we can do here - LOG.info("The GCThrashingMonitor was interrupted."); - } - } - - /** - * Return only when the server is not in the GC thrashing state. - */ - public void waitForResources(String context) { - if (!isThrashing.get()) { - return; - } - numPushbacks.incrementAndGet(); - LOG.info("Waiting for resources for {}. Memory is {}", context, describeMemory()); - synchronized (waitingForResources) { - // No big deal if isThrashing became false in the meantime. - while (isThrashing.get()) { - try { - waitingForResources.wait(); - } catch (InterruptedException e1) { - LOG.debug("waitForResources was interrupted."); - } - } - } - LOG.info("Resources granted for {}. Memory is {}", context, describeMemory()); - } - - /** - * Return the path for logging heap dumps. - */ - private static String getLoggingDir() { - String defaultPath = System.getProperty("java.io.tmpdir", DEFAULT_LOGGING_DIR); - String jsonLogFile = System.getProperty("dataflow.worker.logging.filepath"); - if (jsonLogFile == null) { - return defaultPath; - } - String logPath = new File(jsonLogFile).getParent(); - if (logPath == null) { - return defaultPath; - } - return logPath; - } - - /** - * Dump the current heap profile to a file and return its name. - */ - public static File dumpHeap() throws - MalformedObjectNameException, InstanceNotFoundException, ReflectionException, MBeanException { - boolean liveObjectsOnly = true; - String fileName = String.format( - "%s/heap_dump_%d.hprof", getLoggingDir(), System.currentTimeMillis()); - - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName oname = new ObjectName("com.sun.management:type=HotSpotDiagnostic"); - Object[] parameters = {fileName, liveObjectsOnly}; - String[] signatures = {"java.lang.String", boolean.class.getName()}; - mbs.invoke(oname, "dumpHeap", parameters, signatures); - - return new File(fileName); - } - - /** - * Return a string describing the current memory state of the server. - */ - private String describeMemory() { - Runtime runtime = Runtime.getRuntime(); - long maxMemory = runtime.maxMemory(); - long totalMemory = runtime.totalMemory(); - long usedMemory = totalMemory - runtime.freeMemory(); - return String.format( - "used/total/max = %d/%d/%d MB, GC last/max = %.2f/%.2f %%, #pushbacks=%d, gc thrashing=%s", - usedMemory >> 20, totalMemory >> 20, maxMemory >> 20, lastMeasuredGCPercentage.get(), - maxGCPercentage.get(), numPushbacks.get(), isThrashing.get()); - } - - @Override - public void appendSummaryHtml(PrintWriter writer) { - writer.print("Memory: "); - writer.print(describeMemory()); - writer.println("
    "); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MemoryMonitorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MemoryMonitorTest.java deleted file mode 100644 index c175165b6d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MemoryMonitorTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Test the memory monitor will block threads when the server is in a (faked) GC thrashing state. - */ -@RunWith(JUnit4.class) -public class MemoryMonitorTest { - static class FakeGCStatsProvider implements MemoryMonitor.GCStatsProvider { - AtomicBoolean inGCThrashingState = new AtomicBoolean(false); - long lastCallTimestamp = System.currentTimeMillis(); - long lastGCResult = 0; - - @Override - public long totalGCTimeMilliseconds() { - if (inGCThrashingState.get()) { - long now = System.currentTimeMillis(); - lastGCResult += now - lastCallTimestamp; - lastCallTimestamp = now; - } - return lastGCResult; - } - } - - private FakeGCStatsProvider provider; - private MemoryMonitor monitor; - private Thread thread; - - @Before - public void setup() { - provider = new FakeGCStatsProvider(); - // Update every 10ms, never shutdown VM. - monitor = new MemoryMonitor(provider, 10, 0); - thread = new Thread(monitor); - thread.start(); - } - - @Test(timeout = 1000) - public void detectGCThrashing() throws InterruptedException { - sleepMillis(100); - monitor.waitForResources("Test1"); - provider.inGCThrashingState.set(true); - sleepMillis(100); - final Semaphore s = new Semaphore(0); - new Thread(new Runnable() { - @Override - public void run() { - monitor.waitForResources("Test2"); - s.release(); - } - }).start(); - assertFalse(s.tryAcquire(100, TimeUnit.MILLISECONDS)); - provider.inGCThrashingState.set(false); - assertTrue(s.tryAcquire(100, TimeUnit.MILLISECONDS)); - monitor.waitForResources("Test3"); - } -} From 9894b42e8e7ca56a3493231560fdb07e21cdb7e1 Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 8 Feb 2016 11:18:45 -0800 Subject: [PATCH 099/751] Decouple StateContext from ReduceFn Prior to this change, the definition of a trigger as a state machine directly referenced ReduceFn.StateContext. But triggers (and other possible uses of state) can and should be defined without dependency on ReduceFn, and the StateContext interface is actually already independent of ReduceFn. This change removes the extraneous coupling. This is also preparatory for the keying of state APIs whereby ReduceFn will use a KeyedStateContext, which in turn allows easy support for KeyedCombineFn in the state API. Triggers will still use a non-keyed StateContext as they are independent of the type of key or what the key happens to be, so having a decoupled interface supports the feature. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114130211 --- .../windowing/AfterDelayFromFirstElement.java | 4 +- .../sdk/transforms/windowing/AfterPane.java | 4 +- .../sdk/transforms/windowing/Trigger.java | 27 ++-- .../sdk/util/MergingStateContext.java | 39 +++++ .../dataflow/sdk/util/PaneInfoTracker.java | 1 - .../cloud/dataflow/sdk/util/ReduceFn.java | 41 ----- .../sdk/util/ReduceFnContextFactory.java | 7 +- .../dataflow/sdk/util/ReduceFnRunner.java | 2 +- .../cloud/dataflow/sdk/util/StateContext.java | 43 +++++ .../dataflow/sdk/util/SystemReduceFn.java | 2 +- .../sdk/util/TriggerContextFactory.java | 150 +++++++++++++----- .../dataflow/sdk/util/TriggerRunner.java | 13 +- 12 files changed, 221 insertions(+), 112 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java index 0272629399..1e2e4cc59e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -17,8 +17,8 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; +import com.google.cloud.dataflow.sdk.util.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java index 642efd1875..61a7d18bd4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java @@ -20,8 +20,8 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; +import com.google.cloud.dataflow.sdk.util.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java index 1cb88ebd0e..32d1069d66 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java @@ -18,7 +18,8 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.cloud.dataflow.sdk.util.ReduceFn; +import com.google.cloud.dataflow.sdk.util.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.common.base.Joiner; @@ -189,7 +190,7 @@ public abstract class TriggerContext { public abstract TriggerInfo trigger(); /** Returns the interface for accessing persistent state. */ - public abstract ReduceFn.StateContext state(); + public abstract StateContext state(); /** The window that the current context is executing in. */ public abstract W window(); @@ -216,7 +217,7 @@ public abstract class TriggerContext { } /** - * Extended {@link Context} containing information accessible to the {@link #onElement} + * Extended {@link TriggerContext} containing information accessible to the {@link #onElement} * operational hook. */ public abstract class OnElementContext extends TriggerContext { @@ -243,7 +244,7 @@ public abstract class OnElementContext extends TriggerContext { } /** - * Extended {@link Context} containing information accessible to the {@link #onMerge} + * Extended {@link TriggerContext} containing information accessible to the {@link #onMerge} * operational hook. */ public abstract class OnMergeContext extends TriggerContext { @@ -269,7 +270,7 @@ public abstract class OnMergeContext extends TriggerContext { public abstract OnMergeContext forTrigger(ExecutableTrigger trigger); @Override - public abstract ReduceFn.MergingStateContext state(); + public abstract MergingStateContext state(); @Override public abstract MergingTriggerInfo trigger(); @@ -322,10 +323,8 @@ protected Trigger(@Nullable List> subTriggers) { /** * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onElement} call. - * - * @param state {@link ReduceFn.StateContext} to prefetch from. */ - public void prefetchOnElement(ReduceFn.StateContext state) { + public void prefetchOnElement(StateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnElement(state); @@ -336,10 +335,8 @@ public void prefetchOnElement(ReduceFn.StateContext state) { /** * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onMerge} call. - * - * @param state {@link ReduceFn.MergingStateContext} to prefetch from. */ - public void prefetchOnMerge(ReduceFn.MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnMerge(state); @@ -350,10 +347,8 @@ public void prefetchOnMerge(ReduceFn.MergingStateContext state) { /** * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #shouldFire} call. - * - * @param state {@link ReduceFn.StateContext} to prefetch from. */ - public void prefetchShouldFire(ReduceFn.StateContext state) { + public void prefetchShouldFire(StateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchShouldFire(state); @@ -364,10 +359,8 @@ public void prefetchShouldFire(ReduceFn.StateContext state) { /** * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onFire} call. - * - * @param state {@link ReduceFn.StateContext} to prefetch from. */ - public void prefetchOnFire(ReduceFn.StateContext state) { + public void prefetchOnFire(StateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnFire(state); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java new file mode 100644 index 0000000000..877cbf9843 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.state.MergeableState; +import com.google.cloud.dataflow.sdk.util.state.State; +import com.google.cloud.dataflow.sdk.util.state.StateTag; + +import java.util.Map; + +/** Interface for interacting with persistent state within {@link #onMerge}. */ +public interface MergingStateContext extends StateContext { + /** + * Analogous to {@link #access}, but across all windows which are about to be merged. + */ + > StateT mergingAccess(StateTag address); + + /** + * Analogous to {@link #access}, but returned as a map from each window which is + * about to be merged to the corresponding state. + */ + public abstract Map + mergingAccessInEachMergingWindow(StateTag address); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index 05360f79d4..b3235c042a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -19,7 +19,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java index 3ac2126fdd..5f541412dc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java @@ -19,15 +19,12 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.util.state.MergeableState; -import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateTag; import org.joda.time.Instant; import java.io.Serializable; import java.util.Collection; -import java.util.Map; import javax.annotation.Nullable; @@ -41,44 +38,6 @@ */ public abstract class ReduceFn implements Serializable { - /** Interface for interacting with persistent state. */ - public interface StateContext { - /** - * Access the storage for the given {@code address} in the current window. - * - *

    Never accounts for merged windows. When windows are merged, any state accessed via - * this method must be eagerly combined and written into the result window. - */ - StateT access(StateTag address); - - /** - * Access the storage for the given {@code address} in all of the windows that were - * merged into the current window. - * - *

    If no windows were merged, this reads and writes to just the current window. - * Otherwise, when windows merge we do not eagerly combine state, but rather defer the - * combination to reading time. Thus reads will be from all 'merged windows' for the - * current window, and writes will be to the designated 'writing window' for the current window. - */ - > StateT accessAcrossMergedWindows( - StateTag address); - } - - /** Interface for interacting with persistent state within {@link #onMerge}. */ - public interface MergingStateContext extends StateContext { - /** - * Analogous to {@link #access}, but across all windows which are about to be merged. - */ - > StateT mergingAccess(StateTag address); - - /** - * Analogous to {@link #access}, but returned as a map from each window which is - * about to be merged to the corresponding state. - */ - public abstract Map - mergingAccessInEachMergingWindow(StateTag address); - } - /** * Interface for interacting with time. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index baa48cc7a7..7563814ef6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -20,8 +20,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.ReduceFn.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext; import com.google.cloud.dataflow.sdk.util.ReduceFn.Timers; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.state.MergeableState; @@ -136,7 +134,7 @@ public Instant currentEventTime() { } static class StateContextImpl - implements ReduceFn.StateContext { + implements StateContext { private final ActiveWindowSet activeWindows; private final W window; @@ -185,8 +183,7 @@ public StorageT access(StateTag address) { } } - static class MergingStateContextImpl - implements ReduceFn.MergingStateContext { + static class MergingStateContextImpl implements MergingStateContext { private final StateContextImpl delegate; private final Collection mergingWindows; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 5fc2bc22ba..83eadf337c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -309,7 +309,7 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W contextFactory.forMerge(toBeMerged, mergeResult); // Prefetch various state. - triggerRunner.prefetchForMerge(mergeResultContext.state()); + triggerRunner.prefetchForMerge(mergeResult, toBeMerged, mergeResultContext.state()); // Run the reduceFn to perform any needed merging. try { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java new file mode 100644 index 0000000000..95bf94dfb2 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.util.state.MergeableState; +import com.google.cloud.dataflow.sdk.util.state.State; +import com.google.cloud.dataflow.sdk.util.state.StateTag; + +/** Interface for interacting with persistent state. */ +public interface StateContext { + /** + * Access the storage for the given {@code address} in the current window. + * + *

    Never accounts for merged windows. When windows are merged, any state accessed via + * this method must be eagerly combined and written into the result window. + */ + StateT access(StateTag address); + + /** + * Access the storage for the given {@code address} in all of the windows that were + * merged into the current window. + * + *

    If no windows were merged, this reads and writes to just the current window. + * Otherwise, when windows merge we do not eagerly combine state, but rather defer the + * combination to reading time. Thus reads will be from all 'merged windows' for the + * current window, and writes will be to the designated 'writing window' for the current window. + */ + > StateT accessAcrossMergedWindows(StateTag address); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java index 08ba98121b..5b6fa784e6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java @@ -116,7 +116,7 @@ public void onMerge(OnMergeContext c) throws Exception { } @Override - public void prefetchOnTrigger(com.google.cloud.dataflow.sdk.util.ReduceFn.StateContext c) { + public void prefetchOnTrigger(StateContext c) { c.accessAcrossMergedWindows(bufferTag).get(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 83ea415d4d..308b849549 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -20,17 +20,23 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergingTriggerInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerInfo; +import com.google.cloud.dataflow.sdk.util.state.MergeableState; +import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; +import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import org.joda.time.Instant; +import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.Map; import javax.annotation.Nullable; @@ -46,12 +52,15 @@ public class TriggerContextFactory { private final WindowingStrategy windowingStrategy; private StateInternals stateInternals; private ActiveWindowSet activeWindows; + private final Coder windowCoder; + public TriggerContextFactory(WindowingStrategy windowingStrategy, StateInternals stateInternals, ActiveWindowSet activeWindows) { this.windowingStrategy = windowingStrategy; this.stateInternals = stateInternals; this.activeWindows = activeWindows; + this.windowCoder = windowingStrategy.getWindowFn().windowCoder(); } public Trigger.TriggerContext base(W window, ReduceFn.Timers timers, @@ -75,6 +84,15 @@ public Trigger.OnMergeContext createOnMergeContext( mergingWindows, finishedSets); } + public StateContext createStateContext(W window, ExecutableTrigger trigger) { + return new StateContextImpl(window, trigger); + } + + public MergingStateContext createMergingStateContext( + W window, Collection mergingWindows, ExecutableTrigger trigger) { + return new MergingStateContextImpl(new StateContextImpl(window, trigger), mergingWindows); + } + private class TriggerInfoImpl implements Trigger.TriggerInfo { protected final ExecutableTrigger trigger; @@ -246,38 +264,91 @@ public boolean apply(FinishedTriggers finishedSet) { } } - private ReduceFnContextFactory.StateContextImpl triggerState( - W window, ExecutableTrigger trigger) { - return new TriggerStateContextImpl( - activeWindows, windowingStrategy.getWindowFn().windowCoder(), - stateInternals, window, trigger); - } + private class StateContextImpl implements StateContext { - private class TriggerStateContextImpl - extends ReduceFnContextFactory.StateContextImpl { - - private int triggerIndex; + private final int triggerIndex; + private final StateNamespace namespace; + private final W window; - public TriggerStateContextImpl(ActiveWindowSet activeWindows, - Coder windowCoder, StateInternals stateInternals, W window, + public StateContextImpl( + W window, ExecutableTrigger trigger) { - super(activeWindows, windowCoder, stateInternals, window); + this.window = window; this.triggerIndex = trigger.getTriggerIndex(); - // Annoyingly, since we hadn't set the triggerIndex yet (we can't do it before super) - // This will would otherwise have incorporated 0 as the trigger index. - this.windowNamespace = namespaceFor(window); + // Must be called after setting windowCoder, window, and triggerIndex + this.namespace = namespaceFor(window); } - @Override - protected StateNamespace namespaceFor(W window) { + private StateNamespace namespaceFor(W window) { return StateNamespaces.windowAndTrigger(windowCoder, window, triggerIndex); } + + @Override + public StateT access(StateTag address) { + return stateInternals.state(namespace, address); + } + + @Override + public > StateT accessAcrossMergedWindows( + StateTag address) { + List readNamespaces = new ArrayList<>(); + for (W readWindow : activeWindows.readStateAddresses(window)) { + readNamespaces.add(namespaceFor(readWindow)); + } + StateNamespace writeNamespace = namespaceFor(activeWindows.writeStateAddress(window)); + return stateInternals.mergedState(readNamespaces, writeNamespace, address, window); + } + } + + private class MergingStateContextImpl implements MergingStateContext { + + private final StateContextImpl delegate; + private final Collection mergingWindows; + + public MergingStateContextImpl(StateContextImpl delegate, Collection mergingWindows) { + this.delegate = delegate; + this.mergingWindows = mergingWindows; + } + + @Override + public StorageT access(StateTag address) { + return delegate.access(address); + } + + @Override + public > StorageT accessAcrossMergedWindows( + StateTag address) { + return delegate.accessAcrossMergedWindows(address); + } + + @Override + public > StateT mergingAccess(StateTag address) { + List readNamespaces = new ArrayList<>(); + for (W mergingWindow : mergingWindows) { + readNamespaces.add(delegate.namespaceFor(mergingWindow)); + } + return stateInternals.mergedState( + readNamespaces, delegate.namespace, address, delegate.window); + } + + @Override + public Map mergingAccessInEachMergingWindow( + StateTag address) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (W mergingWindow : mergingWindows) { + StateT stateForWindow = stateInternals.state( + delegate.namespaceFor(mergingWindow), address); + builder.put(mergingWindow, stateForWindow); + } + return builder.build(); + } } private class TriggerContextImpl extends Trigger.TriggerContext { - private final ReduceFnContextFactory.StateContextImpl state; + private final W window; + private final StateContextImpl state; private final ReduceFn.Timers timers; private final TriggerInfoImpl triggerInfo; @@ -287,14 +358,15 @@ private TriggerContextImpl( ExecutableTrigger trigger, FinishedTriggers finishedSet) { trigger.getSpec().super(); - this.state = triggerState(window, trigger); + this.window = window; + this.state = new StateContextImpl(window, trigger); this.timers = new TriggerTimers(window, timers); this.triggerInfo = new TriggerInfoImpl(trigger, finishedSet, this); } @Override public Trigger.TriggerContext forTrigger(ExecutableTrigger trigger) { - return new TriggerContextImpl(state.window(), timers, trigger, triggerInfo.finishedSet); + return new TriggerContextImpl(window, timers, trigger, triggerInfo.finishedSet); } @Override @@ -303,13 +375,13 @@ public TriggerInfo trigger() { } @Override - public ReduceFn.StateContext state() { + public StateContext state() { return state; } @Override public W window() { - return state.window(); + return window; } @Override @@ -337,7 +409,8 @@ public Instant currentEventTime() { private class OnElementContextImpl extends Trigger.OnElementContext { - private final ReduceFnContextFactory.StateContextImpl state; + private final W window; + private final StateContextImpl state; private final ReduceFn.Timers timers; private final TriggerInfoImpl triggerInfo; private final Instant eventTimestamp; @@ -349,7 +422,8 @@ private OnElementContextImpl( FinishedTriggers finishedSet, Instant eventTimestamp) { trigger.getSpec().super(); - this.state = triggerState(window, trigger); + this.window = window; + this.state = new StateContextImpl(window, trigger); this.timers = new TriggerTimers(window, timers); this.triggerInfo = new TriggerInfoImpl(trigger, finishedSet, this); this.eventTimestamp = eventTimestamp; @@ -364,7 +438,7 @@ public Instant eventTimestamp() { @Override public Trigger.OnElementContext forTrigger(ExecutableTrigger trigger) { return new OnElementContextImpl( - state.window(), timers, trigger, triggerInfo.finishedSet, eventTimestamp); + window, timers, trigger, triggerInfo.finishedSet, eventTimestamp); } @Override @@ -373,13 +447,13 @@ public TriggerInfo trigger() { } @Override - public ReduceFn.StateContext state() { + public StateContext state() { return state; } @Override public W window() { - return state.window(); + return window; } @Override @@ -413,7 +487,9 @@ public Instant currentEventTime() { private class OnMergeContextImpl extends Trigger.OnMergeContext { - private final ReduceFnContextFactory.MergingStateContextImpl state; + private final MergingStateContext state; + private final W window; + private final Collection mergingWindows; private final ReduceFn.Timers timers; private final MergingTriggerInfoImpl triggerInfo; @@ -425,8 +501,10 @@ private OnMergeContextImpl( Collection mergingWindows, Map finishedSets) { trigger.getSpec().super(); - this.state = new ReduceFnContextFactory.MergingStateContextImpl<>( - triggerState(window, trigger), mergingWindows); + this.mergingWindows = mergingWindows; + this.window = window; + this.state = + new MergingStateContextImpl(new StateContextImpl(window, trigger), mergingWindows); this.timers = new TriggerTimers(window, timers); this.triggerInfo = new MergingTriggerInfoImpl(trigger, finishedSet, this, finishedSets); } @@ -434,17 +512,17 @@ private OnMergeContextImpl( @Override public Trigger.OnMergeContext forTrigger(ExecutableTrigger trigger) { return new OnMergeContextImpl( - state.window(), timers, trigger, triggerInfo.finishedSet, - state.mergingWindows(), triggerInfo.finishedSets); + window, timers, trigger, triggerInfo.finishedSet, + mergingWindows, triggerInfo.finishedSets); } @Override public Iterable oldWindows() { - return state.mergingWindows(); + return mergingWindows; } @Override - public ReduceFn.MergingStateContext state() { + public MergingStateContext state() { return state; } @@ -455,7 +533,7 @@ public MergingTriggerInfo trigger() { @Override public W window() { - return state.window(); + return window; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index c846dac860..a8a61cfaf5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -26,6 +26,7 @@ import com.google.common.collect.ImmutableMap; import java.util.BitSet; +import java.util.Collection; import java.util.Map; /** @@ -70,25 +71,25 @@ private FinishedTriggersBitSet readFinishedBits(ValueState state) { } /** Return true if the trigger is closed in the window corresponding to the specified state. */ - public boolean isClosed(ReduceFn.StateContext state) { + public boolean isClosed(StateContext state) { return readFinishedBits(state.access(FINISHED_BITS_TAG)).isFinished(rootTrigger); } - public void prefetchForValue(ReduceFn.StateContext state) { + public void prefetchForValue(StateContext state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } rootTrigger.getSpec().prefetchOnElement(state); } - public void prefetchOnFire(ReduceFn.StateContext state) { + public void prefetchOnFire(StateContext state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } rootTrigger.getSpec().prefetchOnFire(state); } - public void prefetchShouldFire(ReduceFn.StateContext state) { + public void prefetchShouldFire(StateContext state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } @@ -108,7 +109,7 @@ public void processValue(ReduceFn.ProcessValueContext c) throws Exce persistFinishedSet(c.state(), finishedSet); } - public void prefetchForMerge(ReduceFn.MergingStateContext state) { + public void prefetchForMerge(W window, Collection mergingWindows, MergingStateContext state) { if (isFinishedSetNeeded()) { for (ValueState value : state.mergingAccessInEachMergingWindow(FINISHED_BITS_TAG).values()) { @@ -162,7 +163,7 @@ public void onFire(ReduceFn.Context c) throws Exception { } private void persistFinishedSet( - ReduceFn.StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { + StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { if (!isFinishedSetNeeded()) { return; } From 314e8dd974fb0c9eec9bfc7814d9f0c15e99d167 Mon Sep 17 00:00:00 2001 From: kirpichov Date: Mon, 8 Feb 2016 12:40:08 -0800 Subject: [PATCH 100/751] Allows specifying if an OffsetBasedSource supports dynamic splitting ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114139165 --- .../cloud/dataflow/sdk/io/OffsetBasedSource.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java index df244f28f2..d581b80ca2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java @@ -187,6 +187,17 @@ public long getBytesPerOffset() { */ public abstract OffsetBasedSource createSourceForSubrange(long start, long end); + /** + * Whether this source should allow dynamic splitting of the offset ranges. + * + *

    True by default. Override this to return false if the source cannot + * support dynamic splitting correctly. If this returns false, + * {@link OffsetBasedSource.OffsetBasedReader#splitAtFraction} will refuse all split requests. + */ + public boolean allowsDynamicSplitting() { + return true; + } + /** * A {@link Source.Reader} that implements code common to readers of all * {@link OffsetBasedSource}s. @@ -288,6 +299,9 @@ public Double getFractionConsumed() { @Override public final synchronized OffsetBasedSource splitAtFraction(double fraction) { + if (!getCurrentSource().allowsDynamicSplitting()) { + return null; + } if (rangeTracker.getStopPosition() == Long.MAX_VALUE) { LOG.debug( "Refusing to split unbounded OffsetBasedReader {} at fraction {}", From 12dd58ca55ba3157848079813b65e89aec2c7c9b Mon Sep 17 00:00:00 2001 From: peihe Date: Mon, 8 Feb 2016 14:07:29 -0800 Subject: [PATCH 101/751] Create a top level GroupingTable interface and its factory class ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114147875 --- .../sdk/util/common/worker/GroupingTable.java | 34 ++ .../util/common/worker/GroupingTables.java | 522 ++++++++++++++++++ 2 files changed, 556 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java new file mode 100644 index 0000000000..30cc4edd7f --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; + +/** + * An interface that groups inputs to an accumulator and flushes the output. + */ +public interface GroupingTable { + + /** + * Adds a pair to this table, possibly flushing some entries to output + * if the table is full. + */ + void put(Object pair, Receiver receiver) throws Exception; + + /** + * Flushes all entries in this table to output. + */ + void flush(Receiver output) throws Exception; +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java new file mode 100644 index 0000000000..18a78b6679 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java @@ -0,0 +1,522 @@ +/******************************************************************************* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; + +import com.google.common.annotations.VisibleForTesting; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; + +/** + * Static utility methods that provide {@link GroupingTable} implementations. + */ +public class GroupingTables { + /** + * Returns a {@link GroupingTable} that groups inputs into a {@link List}. + */ + public static GroupingTable> buffering( + GroupingKeyCreator groupingKeyCreator, + PairInfo pairInfo, + SizeEstimator keySizer, + SizeEstimator valueSizer) { + return new BufferingGroupingTable<>( + DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, keySizer, valueSizer); + } + + /** + * Returns a {@link GroupingTable} that groups inputs into a {@link List} with + * sampling {@link SizeEstimator SizeEstimators}. + */ + public static GroupingTable> bufferingAndSampling( + GroupingKeyCreator groupingKeyCreator, + PairInfo pairInfo, + SizeEstimator keySizer, + SizeEstimator valueSizer, + double sizeEstimatorSampleRate) { + return new BufferingGroupingTable<>( + DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, + new SamplingSizeEstimator<>(keySizer, sizeEstimatorSampleRate, 1.0), + new SamplingSizeEstimator<>(valueSizer, sizeEstimatorSampleRate, 1.0)); + } + + /** + * Returns a {@link GroupingTable} that combines inputs into a accumulator. + */ + public static GroupingTable combining( + GroupingKeyCreator groupingKeyCreator, + PairInfo pairInfo, + Combiner combineFn, + SizeEstimator keySizer, + SizeEstimator accumulatorSizer) { + return new CombiningGroupingTable<>( + DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, + combineFn, keySizer, accumulatorSizer); + } + + /** + * Returns a {@link GroupingTable} that combines inputs into a accumulator with + * sampling {@link SizeEstimator SizeEstimators}. + */ + public static GroupingTable combiningAndSampling( + GroupingKeyCreator groupingKeyCreator, + PairInfo pairInfo, + Combiner combineFn, + SizeEstimator keySizer, + SizeEstimator accumulatorSizer, + double sizeEstimatorSampleRate) { + return new CombiningGroupingTable<>( + DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, combineFn, + new SamplingSizeEstimator<>(keySizer, sizeEstimatorSampleRate, 1.0), + new SamplingSizeEstimator<>(accumulatorSizer, sizeEstimatorSampleRate, 1.0)); + } + + /** + * Provides client-specific operations for grouping keys. + */ + public static interface GroupingKeyCreator { + public Object createGroupingKey(K key) throws Exception; + } + + /** + * Provides client-specific operations for size estimates. + */ + public static interface SizeEstimator { + public long estimateSize(T element) throws Exception; + } + + /** + * Provides client-specific operations for working with elements + * that are key/value or key/values pairs. + */ + public interface PairInfo { + public Iterable getKeysFromInputPair(Object pair); + public Object getValueFromInputPair(Object pair); + public Object makeOutputPair(Object key, Object value); + } + + /** + * Provides client-specific operations for combining values. + */ + public interface Combiner { + public AccumT createAccumulator(K key); + public AccumT add(K key, AccumT accumulator, InputT value); + public AccumT merge(K key, Iterable accumulators); + public AccumT compact(K key, AccumT accumulator); + public OutputT extract(K key, AccumT accumulator); + } + + // By default, how many bytes we allow the grouping table to consume before + // it has to be flushed. + static final long DEFAULT_MAX_GROUPING_TABLE_BYTES = 100_000_000L; + + // How many bytes a word in the JVM has. + static final int BYTES_PER_JVM_WORD = getBytesPerJvmWord(); + /** + * The number of bytes of overhead to store an entry in the + * grouping table (a {@code HashMap}), + * ignoring the actual number of bytes in the keys and values: + *
      + *
    • an array element (1 word), + *
    • a HashMap.Entry (4 words), + *
    • a StructuralByteArray (1 words), + *
    • a backing array (guessed at 1 word for the length), + *
    • a KeyAndValues (2 words), + *
    • an ArrayList (2 words), + *
    • a backing array (1 word), + *
    • per-object overhead (JVM-specific, guessed at 2 words * 6 objects). + *
    + */ + static final int PER_KEY_OVERHEAD = 24 * BYTES_PER_JVM_WORD; + + /** + * A base class of {@link GroupingTable} that provides the implementation of + * {@link #put} and {@link #flush}. + * + *

    Subclasses override {@link #createTableEntry}. + */ + @VisibleForTesting + public abstract static class GroupingTableBase + implements GroupingTable{ + // Keep the table relatively full to increase the chance of collisions. + private static final double TARGET_LOAD = 0.9; + + private long maxSize; + private final GroupingKeyCreator groupingKeyCreator; + private final PairInfo pairInfo; + + private long size = 0; + private Map> table; + + private GroupingTableBase(long maxSize, + GroupingKeyCreator groupingKeyCreator, + PairInfo pairInfo) { + this.maxSize = maxSize; + this.groupingKeyCreator = groupingKeyCreator; + this.pairInfo = pairInfo; + this.table = new HashMap<>(); + } + + interface GroupingTableEntry { + public K getKey(); + public AccumT getValue(); + public void add(InputT value) throws Exception; + public long getSize(); + public void compact() throws Exception; + } + + public abstract GroupingTableEntry createTableEntry(K key) throws Exception; + + /** + * Adds a pair to this table, possibly flushing some entries to output + * if the table is full. + */ + @SuppressWarnings("unchecked") + @Override + public void put(Object pair, Receiver receiver) throws Exception { + for (Object key : pairInfo.getKeysFromInputPair(pair)) { + put((K) key, + (InputT) pairInfo.getValueFromInputPair(pair), + receiver); + } + } + + /** + * Adds the key and value to this table, possibly flushing some entries + * to output if the table is full. + */ + public void put(K key, InputT value, Receiver receiver) throws Exception { + Object groupingKey = groupingKeyCreator.createGroupingKey(key); + GroupingTableEntry entry = table.get(groupingKey); + if (entry == null) { + entry = createTableEntry(key); + table.put(groupingKey, entry); + size += PER_KEY_OVERHEAD; + } else { + size -= entry.getSize(); + } + entry.add(value); + size += entry.getSize(); + + if (size >= maxSize) { + long targetSize = (long) (TARGET_LOAD * maxSize); + Iterator> entries = + table.values().iterator(); + while (size >= targetSize) { + if (!entries.hasNext()) { + // Should never happen, but sizes may be estimates... + size = 0; + break; + } + GroupingTableEntry toFlush = entries.next(); + entries.remove(); + size -= toFlush.getSize() + PER_KEY_OVERHEAD; + output(toFlush, receiver); + } + } + } + + /** + * Output the given entry. Does not actually remove it from the table or + * update this table's size. + */ + private void output(GroupingTableEntry entry, Receiver receiver) + throws Exception { + entry.compact(); + receiver.process(pairInfo.makeOutputPair(entry.getKey(), entry.getValue())); + } + + /** + * Flushes all entries in this table to output. + */ + @Override + public void flush(Receiver output) throws Exception { + for (GroupingTableEntry entry : table.values()) { + output(entry, output); + } + table.clear(); + size = 0; + } + + @VisibleForTesting + public void setMaxSize(long maxSize) { + this.maxSize = maxSize; + } + + @VisibleForTesting + public long size() { + return size; + } + } + + /** + * A grouping table that simply buffers all inserted values in a list. + */ + private static class BufferingGroupingTable extends GroupingTableBase> { + + public final SizeEstimator keySizer; + public final SizeEstimator valueSizer; + + private BufferingGroupingTable(long maxSize, + GroupingKeyCreator groupingKeyCreator, + PairInfo pairInfo, + SizeEstimator keySizer, + SizeEstimator valueSizer) { + super(maxSize, groupingKeyCreator, pairInfo); + this.keySizer = keySizer; + this.valueSizer = valueSizer; + } + + @Override + public GroupingTableEntry> createTableEntry(final K key) throws Exception { + return new GroupingTableEntry>() { + long size = keySizer.estimateSize(key); + final List values = new ArrayList<>(); + + @Override + public K getKey() { + return key; + } + + @Override + public List getValue() { + return values; + } + + @Override + public long getSize() { + return size; + } + + @Override + public void compact() { } + + @Override + public void add(V value) throws Exception { + values.add(value); + size += BYTES_PER_JVM_WORD + valueSizer.estimateSize(value); + } + }; + } + } + + /** + * A grouping table that uses the given combiner to combine values in place. + */ + private static class CombiningGroupingTable + extends GroupingTableBase { + + private final Combiner combiner; + private final SizeEstimator keySizer; + private final SizeEstimator accumulatorSizer; + + private CombiningGroupingTable(long maxSize, + GroupingKeyCreator groupingKeyCreator, + PairInfo pairInfo, + Combiner combineFn, + SizeEstimator keySizer, + SizeEstimator accumulatorSizer) { + super(maxSize, groupingKeyCreator, pairInfo); + this.combiner = combineFn; + this.keySizer = keySizer; + this.accumulatorSizer = accumulatorSizer; + } + + @Override + public GroupingTableEntry createTableEntry(final K key) throws Exception { + return new GroupingTableEntry() { + final long keySize = keySizer.estimateSize(key); + AccumT accumulator = combiner.createAccumulator(key); + long accumulatorSize = 0; // never used before a value is added... + + @Override + public K getKey() { + return key; + } + + @Override + public AccumT getValue() { + return accumulator; + } + + @Override + public long getSize() { + return keySize + accumulatorSize; + } + + @Override + public void compact() throws Exception { + AccumT newAccumulator = combiner.compact(key, accumulator); + if (newAccumulator != accumulator) { + accumulator = newAccumulator; + accumulatorSize = accumulatorSizer.estimateSize(newAccumulator); + } + } + + @Override + public void add(InputT value) throws Exception { + accumulator = combiner.add(key, accumulator, value); + accumulatorSize = accumulatorSizer.estimateSize(accumulator); + } + }; + } + } + + /** + * Returns the number of bytes in a JVM word. In case we failed to + * find the answer, returns 8. + */ + private static int getBytesPerJvmWord() { + String wordSizeInBits = System.getProperty("sun.arch.data.model"); + try { + return Integer.parseInt(wordSizeInBits) / 8; + } catch (NumberFormatException e) { + // The JVM word size is unknown. Assume 64-bit. + return 8; + } + } + + //////////////////////////////////////////////////////////////////////////// + // Size sampling. + + /** + * Implements size estimation by adaptively delegating to an underlying + * (potentially more expensive) estimator for some elements and returning + * the average value for others. + */ + @VisibleForTesting + static class SamplingSizeEstimator implements SizeEstimator { + + /** + * The degree of confidence required in our expected value predictions + * before we allow under-sampling. + * + *

    The value of 3.0 is a confidence interval of about 99.7% for a + * a high-degree-of-freedom t-distribution. + */ + public static final double CONFIDENCE_INTERVAL_SIGMA = 3; + + /** + * The desired size of our confidence interval (relative to the measured + * expected value). + * + *

    The value of 0.25 is plus or minus 25%. + */ + public static final double CONFIDENCE_INTERVAL_SIZE = 0.25; + + /** + * Default number of elements that must be measured before elements are skipped. + */ + public static final long DEFAULT_MIN_SAMPLED = 20; + + private final SizeEstimator underlying; + private final double minSampleRate; + private final double maxSampleRate; + private final long minSampled; + private final Random random; + + private long totalElements = 0; + private long sampledElements = 0; + private long sampledSum = 0; + private double sampledSumSquares = 0; + private long estimate; + + private long nextSample = 0; + + private SamplingSizeEstimator( + SizeEstimator underlying, + double minSampleRate, + double maxSampleRate) { + this(underlying, minSampleRate, maxSampleRate, DEFAULT_MIN_SAMPLED, new Random()); + } + + @VisibleForTesting + SamplingSizeEstimator(SizeEstimator underlying, + double minSampleRate, + double maxSampleRate, + long minSampled, + Random random) { + this.underlying = underlying; + this.minSampleRate = minSampleRate; + this.maxSampleRate = maxSampleRate; + this.minSampled = minSampled; + this.random = random; + } + + @Override + public long estimateSize(T element) throws Exception { + if (sampleNow()) { + return recordSample(underlying.estimateSize(element)); + } else { + return estimate; + } + } + + private boolean sampleNow() { + totalElements++; + return --nextSample < 0; + } + + private long recordSample(long value) { + sampledElements += 1; + sampledSum += value; + sampledSumSquares += value * value; + estimate = (long) Math.ceil(sampledSum / sampledElements); + long target = desiredSampleSize(); + if (sampledElements < minSampled || sampledElements < target) { + // Sample immediately. + nextSample = 0; + } else { + double rate = cap( + minSampleRate, + maxSampleRate, + Math.max(1.0 / (totalElements - minSampled + 1), // slowly ramp down + target / (double) totalElements)); // "future" target + // Uses the geometric distribution to return the likely distance between + // successive independent trials of a fixed probability p. This gives the + // same uniform distribution of branching on Math.random() < p, but with + // one random number generation per success rather than one + // per test, which can be a significant savings if p is small. + nextSample = rate == 1.0 + ? 0 + : (long) Math.floor(Math.log(random.nextDouble()) / Math.log(1 - rate)); + } + return value; + } + + private static final double cap(double min, double max, double value) { + return Math.min(max, Math.max(min, value)); + } + + private long desiredSampleSize() { + // We have no a-priori information on the actual distribution of data + // sizes, so compute our desired sample as if it were normal. + // Yes this formula is unstable for small stddev, but we only care about large stddev. + double mean = sampledSum / (double) sampledElements; + double sumSquareDiff = + (sampledSumSquares - (2 * mean * sampledSum) + (sampledElements * mean * mean)); + double stddev = Math.sqrt(sumSquareDiff / (sampledElements - 1)); + double sqrtDesiredSamples = + (CONFIDENCE_INTERVAL_SIGMA * stddev) / (CONFIDENCE_INTERVAL_SIZE * mean); + return (long) Math.ceil(sqrtDesiredSamples * sqrtDesiredSamples); + } + } +} + From a2d8cd5e719cb60e6dea32b35e10c6caabb3a923 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 8 Feb 2016 15:47:00 -0800 Subject: [PATCH 102/751] Experimental Cloud Bigtable sink This commit adds an experimental sink for Google Cloud Bigtable. The sink is experimental and may break in future versions, though we believe the user-facing API is stable. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114158575 --- checkstyle.xml | 2 +- pom.xml | 1 + sdk/pom.xml | 31 ++ .../dataflow/sdk/io/bigtable/BigtableIO.java | 431 ++++++++++++++++++ .../sdk/io/bigtable/BigtableService.java | 63 +++ .../sdk/io/bigtable/BigtableServiceImpl.java | 146 ++++++ .../cloud/dataflow/sdk/util/ApiSurface.java | 2 + .../sdk/io/bigtable/BigtableIOTest.java | 273 +++++++++++ 8 files changed, 948 insertions(+), 1 deletion(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java diff --git a/checkstyle.xml b/checkstyle.xml index 5d7c563dfb..f38dd74b34 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -110,7 +110,7 @@ page at http://checkstyle.sourceforge.net/config.html --> - + diff --git a/pom.xml b/pom.xml index 78b82b6d65..03d2a8ddc3 100644 --- a/pom.xml +++ b/pom.xml @@ -69,6 +69,7 @@ 1.7.7 v2-rev248-1.21.0 + 0.2.3 v1b3-rev14-1.21.0 v1beta2-rev1-4.0.0 1.21.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index 2526c10b65..1d7458052c 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -299,6 +299,7 @@ true + com.google.cloud.bigtable:bigtable-client-core com.google.guava:guava @@ -324,6 +325,17 @@ com.google.thirdparty com.google.cloud.dataflow.sdk.repackaged.com.google.thirdparty + + com.google.cloud.bigtable + com.google.cloud.dataflow.sdk.repackaged.com.google.cloud.bigtable + + com.google.cloud.bigtable.config.BigtableOptions* + com.google.cloud.bigtable.config.CredentialOptions* + com.google.cloud.bigtable.config.RetryOptions* + com.google.cloud.bigtable.grpc.BigtableClusterName + com.google.cloud.bigtable.grpc.BigtableTableName + + @@ -341,6 +353,7 @@ ${project.artifactId}-bundled-${project.version} + com.google.cloud.bigtable:bigtable-client-core com.google.guava:guava @@ -432,6 +445,24 @@ 0.5.160127 + + io.grpc + grpc-all + 0.12.0 + + + + com.google.cloud.bigtable + bigtable-protos + ${bigtable.version} + + + + com.google.cloud.bigtable + bigtable-client-core + ${bigtable.version} + + com.google.api-client google-api-client diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java new file mode 100644 index 0000000000..379450a880 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -0,0 +1,431 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.bigtable.v1.Mutation; +import com.google.cloud.bigtable.config.BigtableOptions; +import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; +import com.google.cloud.dataflow.sdk.io.Sink.Writer; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.base.MoreObjects; +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.concurrent.ConcurrentLinkedQueue; + +import javax.annotation.Nullable; + +/** + * A bounded sink for Google Cloud Bigtable. + * + *

    For more information, see the online documentation at + * Google Cloud Bigtable. + * + *

    Writing to Cloud Bigtable

    + * + *

    The Bigtable sink executes a set of row mutations on a single table. It takes as input a + * {@link PCollection PCollection<KV<ByteString, Iterable<Mutation>>>}, where the + * {@link ByteString} is the key of the row being mutated, and each {@link Mutation} represents an + * idempotent transformation to that row. + * + *

    To configure a Cloud Bigtable sink, you must supply a table id and a {@link BigtableOptions} + * or builder configured with the project and other information necessary to identify the + * Bigtable cluster, for example: + * + *

    {@code
    + * BigtableOptions.Builder optionsBuilder =
    + *     new BigtableOptions.Builder()
    + *         .setProjectId("project")
    + *         .setClusterId("cluster")
    + *         .setZoneId("zone");
    + *
    + * PCollection>> data = ...;
    + *
    + * data.apply("write",
    + *     BigtableIO.write()
    + *         .withBigtableOptions(optionsBuilder)
    + *         .withTableId("table"));
    + * }
    + * + *

    Experimental

    + * + *

    This connector for Cloud Bigtable is considered experimental and may break or receive + * backwards-incompatible changes in future versions of the Cloud Dataflow SDK. Cloud Bigtable is + * in Beta, and thus it may introduce breaking changes in future revisions of its service or APIs. + * + *

    Permissions

    + * + *

    Permission requirements depend on the {@link PipelineRunner} that is used to execute the + * Dataflow job. Please refer to the documentation of corresponding + * {@link PipelineRunner PipelineRunners} for more details. + */ +@Experimental +public class BigtableIO { + private static final Logger logger = LoggerFactory.getLogger(BigtableIO.class); + + /** + * Creates an uninitialized {@link BigtableIO.Write}. Before use, the {@code Write} must be + * initialized with a + * {@link BigtableIO.Write#withBigtableOptions(BigtableOptions) BigtableOptions} that specifies + * the destination Cloud Bigtable cluster, and a {@link BigtableIO.Write#withTableId table} that + * specifies which table to write. + */ + @Experimental + public static Write write() { + return new Write(null, "", null); + } + + /** + * A {@link PTransform} that writes to Google Cloud Bigtable. See the class-level Javadoc on + * {@link BigtableIO} for more information. + * + * @see BigtableIO + */ + @Experimental + public static class Write + extends PTransform>>, PDone> { + /** + * Used to define the Cloud Bigtable cluster and any options for the networking layer. + * Cannot actually be {@code null} at validation time, but may start out {@code null} while + * source is being built. + */ + @Nullable private final BigtableOptions options; + private final String tableId; + @Nullable private final BigtableService bigtableService; + + private Write( + @Nullable BigtableOptions options, + String tableId, + @Nullable BigtableService bigtableService) { + this.options = options; + this.tableId = checkNotNull(tableId, "tableId"); + this.bigtableService = bigtableService; + } + + /** + * Returns a new {@link BigtableIO.Write} that will write to the Cloud Bigtable cluster + * indicated by the given options, and using any other specified customizations. + * + *

    Does not modify this object. + */ + public Write withBigtableOptions(BigtableOptions options) { + checkNotNull(options, "options"); + return withBigtableOptions(options.toBuilder()); + } + + /** + * Returns a new {@link BigtableIO.Write} that will write to the Cloud Bigtable cluster + * indicated by the given options, and using any other specified customizations. + * + *

    Clones the given {@link BigtableOptions.Builder} is cloned so that any further changes + * will have no effect on the returned {@link BigtableIO.Write}. + * + *

    Does not modify this object. + */ + public Write withBigtableOptions(BigtableOptions.Builder optionsBuilder) { + checkNotNull(optionsBuilder, "optionsBuilder"); + // TODO: is there a better way to clone a Builder? Want it to be immune from user changes. + BigtableOptions.Builder clonedBuilder = optionsBuilder.build().toBuilder(); + BigtableOptions optionsWithAgent = clonedBuilder.setUserAgent(getUserAgent()).build(); + return new Write(optionsWithAgent, tableId, bigtableService); + } + + /** + * Returns a new {@link BigtableIO.Write} that will write to the specified table. + * + *

    Does not modify this object. + */ + public Write withTableId(String tableId) { + checkNotNull(tableId, "tableId"); + return new Write(options, tableId, bigtableService); + } + + /** + * Returns the Google Cloud Bigtable cluster being written to, and other parameters. + */ + public BigtableOptions getBigtableOptions() { + return options; + } + + /** + * Returns the table being written to. + */ + public String getTableId() { + return tableId; + } + + @Override + public PDone apply(PCollection>> input) { + Sink sink = new Sink(tableId, getBigtableService()); + return input.apply(com.google.cloud.dataflow.sdk.io.Write.to(sink)); + } + + @Override + public void validate(PCollection>> input) { + checkArgument(options != null, "BigtableOptions not specified"); + checkArgument(!tableId.isEmpty(), "Table ID not specified"); + try { + checkArgument( + getBigtableService().tableExists(tableId), "Table %s does not exist", tableId); + } catch (IOException e) { + logger.warn("Error checking whether table {} exists; proceeding.", tableId, e); + } + } + + /** + * Returns a new {@link BigtableIO.Write} that will write using the given Cloud Bigtable + * service implementation. + * + *

    This is used for testing. + * + *

    Does not modify this object. + */ + Write withBigtableService(BigtableService bigtableService) { + checkNotNull(bigtableService, "bigtableService"); + return new Write(options, tableId, bigtableService); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(Write.class) + .add("options", options) + .add("tableId", tableId) + .toString(); + } + + /** + * Helper function that either returns the mock Bigtable service supplied by + * {@link #withBigtableService} or creates and returns an implementation that talks to + * {@code Cloud Bigtable}. + */ + private BigtableService getBigtableService() { + if (bigtableService != null) { + return bigtableService; + } + return new BigtableServiceImpl(options); + } + } + + private static class Sink + extends com.google.cloud.dataflow.sdk.io.Sink>> { + + public Sink(String tableId, BigtableService bigtableService) { + this.tableId = checkNotNull(tableId, "tableId"); + this.bigtableService = checkNotNull(bigtableService, "bigtableService"); + } + + public String getTableId() { + return tableId; + } + + public BigtableService getBigtableService() { + return bigtableService; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(Sink.class) + .add("bigtableService", bigtableService) + .add("tableId", tableId) + .toString(); + } + + /////////////////////////////////////////////////////////////////////////////// + private final String tableId; + private final BigtableService bigtableService; + + @Override + public WriteOperation>, Long> createWriteOperation( + PipelineOptions options) { + return new BigtableWriteOperation(this); + } + + /** Does nothing, as it is redundant with {@link Write#validate}. */ + @Override + public void validate(PipelineOptions options) {} + } + + private static class BigtableWriteOperation + extends WriteOperation>, Long> { + private final Sink sink; + + public BigtableWriteOperation(Sink sink) { + this.sink = sink; + } + + @Override + public Writer>, Long> createWriter(PipelineOptions options) + throws Exception { + return new BigtableWriter(this); + } + + @Override + public void initialize(PipelineOptions options) {} + + @Override + public void finalize(Iterable writerResults, PipelineOptions options) { + long count = 0; + for (Long value : writerResults) { + value += count; + } + logger.debug("Wrote {} elements to BigtableIO.Sink {}", sink); + } + + @Override + public Sink getSink() { + return sink; + } + + @Override + public Coder getWriterResultCoder() { + return VarLongCoder.of(); + } + } + + private static class BigtableWriter extends Writer>, Long> { + private final BigtableWriteOperation writeOperation; + private final Sink sink; + private BigtableService.Writer bigtableWriter; + private long recordsWritten; + private final ConcurrentLinkedQueue failures; + + public BigtableWriter(BigtableWriteOperation writeOperation) { + this.writeOperation = writeOperation; + this.sink = writeOperation.getSink(); + this.failures = new ConcurrentLinkedQueue<>(); + } + + @Override + public void open(String uId) throws Exception { + bigtableWriter = sink.getBigtableService().openForWriting(sink.getTableId()); + recordsWritten = 0; + } + + /** + * If any write has asynchronously failed, fail the bundle with a useful error. + */ + private void checkForFailures() throws IOException { + // Note that this function is never called by multiple threads and is the only place that + // we remove from failures, so this code is safe. + if (failures.isEmpty()) { + return; + } + + StringBuilder logEntry = new StringBuilder(); + int i = 0; + for (; i < 10 && !failures.isEmpty(); ++i) { + BigtableWriteException exc = failures.remove(); + logEntry.append("\n").append(exc.getMessage()); + if (exc.getCause() != null) { + logEntry.append(": ").append(exc.getCause().getMessage()); + } + } + String message = + String.format( + "At least %d errors occurred writing to Bigtable. First %d errors: %s", + i + failures.size(), + i, + logEntry.toString()); + logger.error(message); + throw new IOException(message); + } + + @Override + public void write(KV> rowMutations) throws Exception { + checkForFailures(); + Futures.addCallback( + bigtableWriter.writeRecord(rowMutations), new WriteExceptionCallback(rowMutations)); + ++recordsWritten; + } + + @Override + public Long close() throws Exception { + bigtableWriter.close(); + bigtableWriter = null; + checkForFailures(); + logger.info("Wrote {} records", recordsWritten); + return recordsWritten; + } + + @Override + public WriteOperation>, Long> getWriteOperation() { + return writeOperation; + } + + private class WriteExceptionCallback implements FutureCallback { + private final KV> value; + + public WriteExceptionCallback(KV> value) { + this.value = value; + } + + @Override + public void onFailure(Throwable cause) { + failures.add(new BigtableWriteException(value, cause)); + } + + @Override + public void onSuccess(Empty produced) {} + } + } + + /** + * An exception that puts information about the failed record being written in its message. + */ + static class BigtableWriteException extends IOException { + public BigtableWriteException(KV> record, Throwable cause) { + super( + String.format( + "Error mutating row %s with mutations %s", + record.getKey().toStringUtf8(), + record.getValue()), + cause); + } + } + + /** + * A helper function to produce a Cloud Bigtable user agent string. + */ + private static String getUserAgent() { + String javaVersion = System.getProperty("java.specification.version"); + DataflowReleaseInfo info = DataflowReleaseInfo.getReleaseInfo(); + return String.format( + "%s/%s (%s); %s", + info.getName(), + info.getVersion(), + javaVersion, + "0.2.3" /* TODO get Bigtable client version directly from jar. */); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java new file mode 100644 index 0000000000..03ddd3a6ae --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; + +import com.google.bigtable.v1.Mutation; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; + +import java.io.IOException; +import java.io.Serializable; + +/** + * An interface for real or fake implementations of Cloud Bigtable. + */ +interface BigtableService extends Serializable { + + /** + * The interface of a class that can write to Cloud Bigtable. + */ + interface Writer { + /** + * Writes a single row transaction to Cloud Bigtable. The key of the {@code record} is the + * row key to be mutated and the iterable of mutations represent the changes to be made to the + * row. + * + * @throws IOException if there is an error submitting the write. + */ + ListenableFuture writeRecord(KV> record) + throws IOException; + + /** + * Closes the writer. + * + * @throws IOException if any writes did not succeed + */ + void close() throws IOException; + } + + /** + * Returns {@code true} if the table with the give name exists. + */ + boolean tableExists(String tableId) throws IOException; + + /** + * Returns a {@link Writer} that will write to the specified table. + */ + Writer openForWriting(String tableId) throws IOException; +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java new file mode 100644 index 0000000000..196e64c241 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; + +import com.google.bigtable.admin.table.v1.GetTableRequest; +import com.google.bigtable.v1.MutateRowRequest; +import com.google.bigtable.v1.Mutation; +import com.google.cloud.bigtable.config.BigtableOptions; +import com.google.cloud.bigtable.grpc.BigtableSession; +import com.google.cloud.bigtable.grpc.async.AsyncExecutor; +import com.google.cloud.bigtable.grpc.async.HeapSizeManager; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.base.MoreObjects; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; + +import io.grpc.Status.Code; +import io.grpc.StatusRuntimeException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +/** + * An implementation of {@link BigtableService} that actually communicates with the Cloud Bigtable + * service. + */ +class BigtableServiceImpl implements BigtableService { + private static final Logger logger = LoggerFactory.getLogger(BigtableService.class); + + public BigtableServiceImpl(BigtableOptions options) { + this.options = options; + } + + private final BigtableOptions options; + + @Override + public BigtableWriterImpl openForWriting(String tableId) throws IOException { + BigtableSession session = new BigtableSession(options); + String tableName = options.getClusterName().toTableNameStr(tableId); + return new BigtableWriterImpl(session, tableName); + } + + @Override + public boolean tableExists(String tableId) throws IOException { + if (!BigtableSession.isAlpnProviderEnabled()) { + logger.info( + "Skipping existence check for table {} (BigtableOptions {}) because ALPN is not" + + " configured.", + tableId, + options); + return true; + } + + try (BigtableSession session = new BigtableSession(options)) { + GetTableRequest getTable = + GetTableRequest.newBuilder() + .setName(options.getClusterName().toTableNameStr(tableId)) + .build(); + session.getTableAdminClient().getTable(getTable); + return true; + } catch (StatusRuntimeException e) { + if (e.getStatus().getCode() == Code.NOT_FOUND) { + return false; + } + String message = + String.format( + "Error checking whether table %s (BigtableOptions %s) exists", tableId, options); + logger.error(message, e); + throw new IOException(message, e); + } + } + + private class BigtableWriterImpl implements Writer { + private BigtableSession session; + private AsyncExecutor executor; + private final MutateRowRequest.Builder partialBuilder; + + public BigtableWriterImpl(BigtableSession session, String tableName) { + this.session = session; + this.executor = + new AsyncExecutor( + session.getDataClient(), + new HeapSizeManager( + AsyncExecutor.ASYNC_MUTATOR_MAX_MEMORY_DEFAULT, + AsyncExecutor.MAX_INFLIGHT_RPCS_DEFAULT)); + + partialBuilder = MutateRowRequest.newBuilder().setTableName(tableName); + } + + @Override + public void close() throws IOException { + try { + if (executor != null) { + executor.flush(); + executor = null; + } + } finally { + if (session != null) { + session.close(); + session = null; + } + } + } + + @Override + public ListenableFuture writeRecord(KV> record) + throws IOException { + MutateRowRequest r = + partialBuilder + .clone() + .setRowKey(record.getKey()) + .addAllMutations(record.getValue()) + .build(); + try { + return executor.mutateRowAsync(r); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Write interrupted", e); + } + } + } + + @Override + public String toString() { + return MoreObjects + .toStringHelper(BigtableServiceImpl.class) + .add("options", options) + .toString(); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java index 20ba6698f1..a9892ca037 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java @@ -551,6 +551,8 @@ public static ApiSurface getSdkApiSurface() throws IOException { .pruningPrefix("java") .pruningPrefix("com.google.api") .pruningPrefix("com.google.auth") + .pruningPrefix("com.google.bigtable") + .pruningPrefix("com.google.cloud.bigtable") .pruningPrefix("com.google.protobuf") .pruningPrefix("org.joda.time") .pruningPrefix("org.apache.avro") diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java new file mode 100644 index 0000000000..e3a9940a2f --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -0,0 +1,273 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; + +import static com.google.common.base.Preconditions.checkArgument; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import com.google.bigtable.v1.Mutation; +import com.google.bigtable.v1.Mutation.SetCell; +import com.google.cloud.bigtable.config.BigtableOptions; +import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.collect.ImmutableList; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.Nullable; + +/** + * Unit tests for {@link BigtableIO}. + */ +@RunWith(JUnit4.class) +public class BigtableIOTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + @Rule public ExpectedLogs logged = ExpectedLogs.none(BigtableIO.class); + + /** + * These tests requires a static instance of the {@link FakeBigtableService} because the writers + * go through a serialization step when executing the test and would not affect passed-in objects + * otherwise. + */ + private static FakeBigtableService service; + private static final BigtableOptions BIGTABLE_OPTIONS = + new BigtableOptions.Builder() + .setProjectId("project") + .setClusterId("cluster") + .setZoneId("zone") + .build(); + private Coder>> bigtableCoder; + private static final TypeDescriptor>> BIGTABLE_WRITE_TYPE = + new TypeDescriptor>>() {}; + + @Before + public void setup() throws Exception { + service = new FakeBigtableService(); + bigtableCoder = TestPipeline.create().getCoderRegistry().getCoder(BIGTABLE_WRITE_TYPE); + } + + @Test + public void testWriteBuildsCorrectly() { + BigtableIO.Write write = + BigtableIO.write().withBigtableOptions(BIGTABLE_OPTIONS).withTableId("table"); + assertEquals("table", write.getTableId()); + assertEquals("project", write.getBigtableOptions().getProjectId()); + assertEquals("zone", write.getBigtableOptions().getZoneId()); + assertEquals("cluster", write.getBigtableOptions().getClusterId()); + } + + @Test + public void testWriteBuildsCorrectlyInDifferentOrder() { + BigtableIO.Write write = + BigtableIO.write().withTableId("table").withBigtableOptions(BIGTABLE_OPTIONS); + assertEquals("cluster", write.getBigtableOptions().getClusterId()); + assertEquals("project", write.getBigtableOptions().getProjectId()); + assertEquals("zone", write.getBigtableOptions().getZoneId()); + assertEquals("table", write.getTableId()); + } + + @Test + public void testWriteValidationFailsMissingTable() { + BigtableIO.Write write = BigtableIO.write().withBigtableOptions(BIGTABLE_OPTIONS); + + thrown.expect(IllegalArgumentException.class); + + write.validate(null); + } + + @Test + public void testSinkValidationFailsMissingOptions() { + BigtableIO.Write write = BigtableIO.write().withTableId("table"); + + thrown.expect(IllegalArgumentException.class); + + write.validate(null); + } + + /** Helper function to make a single row mutation to be written. */ + private static KV> makeRowWithSetCell(String key, String value) { + ByteString rowKey = ByteString.copyFromUtf8(key); + Iterable mutations = + ImmutableList.of( + Mutation.newBuilder() + .setSetCell(SetCell.newBuilder().setValue(ByteString.copyFromUtf8(value))) + .build()); + return KV.of(rowKey, mutations); + } + + /** Helper function to make a single bad row mutation (no set cell). */ + private static KV> makeBadRow(String key) { + Iterable mutations = ImmutableList.of(Mutation.newBuilder().build()); + return KV.of(ByteString.copyFromUtf8(key), mutations); + } + + /** Tests that a record gets written to the service and messages are logged. */ + @Test + public void testWriting() throws Exception { + final String table = "table"; + final String key = "key"; + final String value = "value"; + + service.createTable(table); + + BigtableIO.Write write = + BigtableIO.write() + .withBigtableOptions(BIGTABLE_OPTIONS) + .withTableId(table) + .withBigtableService(service); + + TestPipeline p = TestPipeline.create(); + p.apply("single row", Create.of(makeRowWithSetCell(key, value)).withCoder(bigtableCoder)) + .apply("write", write); + p.run(); + + logged.verifyInfo("Wrote 1 records"); + + assertEquals(1, service.tables.size()); + assertNotNull(service.getTable(table)); + Map rows = service.getTable(table); + assertEquals(1, rows.size()); + assertEquals(ByteString.copyFromUtf8(value), rows.get(ByteString.copyFromUtf8(key))); + } + + /** Tests that when writing to a non-existent table, the write fails. */ + @Test + public void testWritingFailsTableDoesNotExist() throws Exception { + final String table = "TEST-TABLE"; + + BigtableIO.Write write = + BigtableIO.write() + .withBigtableOptions(BIGTABLE_OPTIONS) + .withTableId(table) + .withBigtableService(service); + + PCollection>> emptyInput = + TestPipeline.create().apply(Create.>>of()); + + // Exception will be thrown by write.validate() when write is applied. + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(String.format("Table %s does not exist", table)); + + emptyInput.apply("write", write); + } + + /** Tests that when writing an element fails, the write fails. */ + @Test + public void testWritingFailsBadElement() throws Exception { + final String table = "TEST-TABLE"; + final String key = "KEY"; + service.createTable(table); + + BigtableIO.Write write = + BigtableIO.write() + .withBigtableOptions(BIGTABLE_OPTIONS) + .withTableId(table) + .withBigtableService(service); + + TestPipeline p = TestPipeline.create(); + p.apply(Create.of(makeBadRow(key)).withCoder(bigtableCoder)).apply(write); + + thrown.expect(PipelineExecutionException.class); + thrown.expectCause(Matchers.instanceOf(IOException.class)); + thrown.expectMessage("At least 1 errors occurred writing to Bigtable. First 1 errors:"); + thrown.expectMessage("Error mutating row " + key + " with mutations []: cell value missing"); + p.run(); + } + + /** + * A {@link BigtableService} implementation that stores tables and their contents in memory. + */ + private static class FakeBigtableService implements BigtableService { + private final Map> tables = new HashMap<>(); + + @Nullable + public Map getTable(String tableId) { + return tables.get(tableId); + } + + public void createTable(String tableId) { + tables.put(tableId, new HashMap()); + } + + @Override + public boolean tableExists(String tableId) { + return tables.containsKey(tableId); + } + + @Override + public FakeBigtableWriter openForWriting(String tableId) { + checkArgument(tableExists(tableId), "Table %s does not exist", tableId); + return new FakeBigtableWriter(tableId); + } + } + + /** + * A {@link BigtableService.Writer} implementation that writes to the static instance of + * {@link FakeBigtableService} stored in {@link #service}. + * + *

    This writer only supports {@link Mutation Mutations} that consist only of {@link SetCell} + * entries. The column family in the {@link SetCell} is ignored; only the value is used. + * + *

    When no {@link SetCell} is provided, the write will fail and this will be exposed via an + * exception on the returned {@link ListenableFuture}. + */ + private static class FakeBigtableWriter implements BigtableService.Writer { + private final String tableId; + + public FakeBigtableWriter(String tableId) { + this.tableId = tableId; + } + + @Override + public ListenableFuture writeRecord(KV> record) { + Map table = service.getTable(tableId); + ByteString key = record.getKey(); + for (Mutation m : record.getValue()) { + SetCell cell = m.getSetCell(); + if (cell.getValue().isEmpty()) { + return Futures.immediateFailedCheckedFuture(new IOException("cell value missing")); + } + table.put(key, cell.getValue()); + } + return Futures.immediateFuture(Empty.getDefaultInstance()); + } + + @Override + public void close() {} + } +} From a1be25667298a17afbfc7cbc4d67f150b0df3a35 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 8 Feb 2016 18:45:20 -0800 Subject: [PATCH 103/751] Tighten BigtableIO's API surface exposure ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114173876 --- .../java/com/google/cloud/dataflow/sdk/util/ApiSurface.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java index a9892ca037..7c0e7bdfca 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java @@ -551,8 +551,9 @@ public static ApiSurface getSdkApiSurface() throws IOException { .pruningPrefix("java") .pruningPrefix("com.google.api") .pruningPrefix("com.google.auth") - .pruningPrefix("com.google.bigtable") - .pruningPrefix("com.google.cloud.bigtable") + .pruningPrefix("com.google.bigtable.v1") + .pruningPrefix("com.google.cloud.bigtable.config") + .pruningPrefix("com.google.cloud.bigtable.grpc.Bigtable*Name") .pruningPrefix("com.google.protobuf") .pruningPrefix("org.joda.time") .pruningPrefix("org.apache.avro") From f087da6d7ccafea5d6d23e109209b916d13f5a77 Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 8 Feb 2016 21:11:04 -0800 Subject: [PATCH 104/751] Separate Timers interface from ReduceFn Prior to this change, the definition of a trigger as a state machine referenced ReduceFn.Timers. However, triggers (and other possible uses of timers) can and should be defined independently from ReduceFn. The Timers interface is actually already independent. This change removes the extraneous coupling. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114180206 --- .../sdk/annotations/Experimental.java | 3 + .../cloud/dataflow/sdk/util/ReduceFn.java | 38 ------------ .../sdk/util/ReduceFnContextFactory.java | 3 +- .../cloud/dataflow/sdk/util/Timers.java | 60 +++++++++++++++++++ .../sdk/util/TriggerContextFactory.java | 24 ++++---- .../dataflow/sdk/util/TriggerTester.java | 2 +- 6 files changed, 77 insertions(+), 53 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java index f094442ec3..cac2aa8435 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java @@ -71,6 +71,9 @@ public enum Kind { /** State-related experimental APIs. */ STATE, + /** Timer-related experimental APIs. */ + TIMERS, + /** Experimental APIs related to customizing the output time for computed values. */ OUTPUT_TIME } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java index 5f541412dc..91fd3c4941 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java @@ -17,7 +17,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.util.state.MergeableState; import com.google.cloud.dataflow.sdk.util.state.StateContents; @@ -26,8 +25,6 @@ import java.io.Serializable; import java.util.Collection; -import javax.annotation.Nullable; - /** * Specification for processing to happen after elements have been grouped by key. * @@ -38,41 +35,6 @@ */ public abstract class ReduceFn implements Serializable { - /** - * Interface for interacting with time. - */ - public interface Timers { - /** - * Sets a timer to fire when the watermark or processing time is beyond the given timestamp. - * Timers are not guaranteed to fire immediately, but will be delivered at some time afterwards. - * - *

    As with {@link StateContext}, timers are implicitly scoped to the current window. All - * timer firings for a window will be received, but the implementation should choose to ignore - * those that are not applicable. - * - * @param timestamp the time at which the trigger’s {@link Trigger#onTimer} callback should - * execute - * @param timeDomain the domain that the {@code timestamp} applies to - */ - public abstract void setTimer(Instant timestamp, TimeDomain timeDomain); - - /** - * Removes the timer set in this trigger context for the given {@code window}, {@code timestmap} - * and {@code timeDomain}. - */ - public abstract void deleteTimer(Instant timestamp, TimeDomain timeDomain); - - /** Returns the current processing time. */ - public abstract Instant currentProcessingTime(); - - /** Returns the current synchronized processing time or {@code null} if unknown. */ - @Nullable - public abstract Instant currentSynchronizedProcessingTime(); - - /** Returns the current event time or {@code null} if unknown. */ - @Nullable - public abstract Instant currentEventTime(); - } /** Information accessible to all the processing methods in this {@code ReduceFn}. */ public abstract class Context { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index 7563814ef6..92c23e7132 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -20,7 +20,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.ReduceFn.Timers; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.state.MergeableState; import com.google.cloud.dataflow.sdk.util.state.State; @@ -96,7 +95,7 @@ public ReduceFn.OnMergeContext forMerge( } - private class TimersImpl implements ReduceFn.Timers { + private class TimersImpl implements Timers { private final StateNamespace namespace; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java new file mode 100644 index 0000000000..7d4b4f2abe --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.annotations.Experimental; + +import org.joda.time.Instant; + +import javax.annotation.Nullable; + +/** + * Interface for interacting with time. + */ +@Experimental(Experimental.Kind.TIMERS) +public interface Timers { + /** + * Sets a timer to fire when the event time watermark, the current processing time, or + * the synchronized processing time watermark surpasses a given timestamp. + * + *

    See {@link TimeDomain} for details on the time domains available. + * + *

    Timers are not guaranteed to fire immediately, but will be delivered at some time + * afterwards. + * + *

    An implementation of {@link Timers} implicitly scopes timers that are set - they may + * be scoped to a key and window, or a key, window, and trigger, etc. + * + * @param timestamp the time at which the timer should be delivered + * @param timeDomain the domain that the {@code timestamp} applies to + */ + public abstract void setTimer(Instant timestamp, TimeDomain timeDomain); + + /** Removes the timer set in this context for the {@code timestmap} and {@code timeDomain}. */ + public abstract void deleteTimer(Instant timestamp, TimeDomain timeDomain); + + /** Returns the current processing time. */ + public abstract Instant currentProcessingTime(); + + /** Returns the current synchronized processing time or {@code null} if unknown. */ + @Nullable + public abstract Instant currentSynchronizedProcessingTime(); + + /** Returns the current event time or {@code null} if unknown. */ + @Nullable + public abstract Instant currentEventTime(); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 308b849549..61c064a10f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -63,13 +63,13 @@ public TriggerContextFactory(WindowingStrategy windowingStrategy, this.windowCoder = windowingStrategy.getWindowFn().windowCoder(); } - public Trigger.TriggerContext base(W window, ReduceFn.Timers timers, + public Trigger.TriggerContext base(W window, Timers timers, ExecutableTrigger rootTrigger, FinishedTriggers finishedSet) { return new TriggerContextImpl(window, timers, rootTrigger, finishedSet); } public Trigger.OnElementContext createOnElementContext( - W window, ReduceFn.Timers timers, Instant elementTimestamp, + W window, Timers timers, Instant elementTimestamp, ExecutableTrigger rootTrigger, FinishedTriggers finishedSet) { return new OnElementContextImpl( window, timers, rootTrigger, finishedSet, @@ -77,7 +77,7 @@ public Trigger.OnElementContext createOnElementContext( } public Trigger.OnMergeContext createOnMergeContext( - W window, ReduceFn.Timers timers, Collection mergingWindows, + W window, Timers timers, Collection mergingWindows, ExecutableTrigger rootTrigger, FinishedTriggers finishedSet, Map finishedSets) { return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, @@ -175,12 +175,12 @@ public void setFinished(boolean finished, int subTriggerIndex) { } } - private class TriggerTimers implements ReduceFn.Timers { + private class TriggerTimers implements Timers { - private final ReduceFn.Timers timers; + private final Timers timers; private final W window; - public TriggerTimers(W window, ReduceFn.Timers timers) { + public TriggerTimers(W window, Timers timers) { this.timers = timers; this.window = window; } @@ -349,12 +349,12 @@ private class TriggerContextImpl extends Trigger.TriggerContext { private final W window; private final StateContextImpl state; - private final ReduceFn.Timers timers; + private final Timers timers; private final TriggerInfoImpl triggerInfo; private TriggerContextImpl( W window, - ReduceFn.Timers timers, + Timers timers, ExecutableTrigger trigger, FinishedTriggers finishedSet) { trigger.getSpec().super(); @@ -411,13 +411,13 @@ private class OnElementContextImpl extends Trigger.OnElementContext { private final W window; private final StateContextImpl state; - private final ReduceFn.Timers timers; + private final Timers timers; private final TriggerInfoImpl triggerInfo; private final Instant eventTimestamp; private OnElementContextImpl( W window, - ReduceFn.Timers timers, + Timers timers, ExecutableTrigger trigger, FinishedTriggers finishedSet, Instant eventTimestamp) { @@ -490,12 +490,12 @@ private class OnMergeContextImpl extends Trigger.OnMergeContext { private final MergingStateContext state; private final W window; private final Collection mergingWindows; - private final ReduceFn.Timers timers; + private final Timers timers; private final MergingTriggerInfoImpl triggerInfo; private OnMergeContextImpl( W window, - ReduceFn.Timers timers, + Timers timers, ExecutableTrigger trigger, FinishedTriggers finishedSet, Collection mergingWindows, diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index 0c362e6438..4fdd2d305a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -544,7 +544,7 @@ public void advanceSynchronizedProcessingTime(Instant newSynchronizedProcessingT } } - private class TestTimers implements ReduceFn.Timers { + private class TestTimers implements Timers { private final StateNamespace namespace; public TestTimers(StateNamespace namespace) { From 546ee4f8b49c1f1e658507f574ce78cb86ef7f55 Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 8 Feb 2016 21:58:54 -0800 Subject: [PATCH 105/751] Merge TimeTrigger into its only subclass Since AfterWatermark is no longer a TimeTrigger, there is only one subclass of TimeTrigger, and it is AfterDelayFromFirstElement. This CL has no behavioral change, but only adjusts implementation details of experimental features that have public visibility due to package and class hierarchy organization. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114182277 --- .../windowing/AfterDelayFromFirstElement.java | 189 ++++++++++++++- .../sdk/transforms/windowing/TimeTrigger.java | 223 ------------------ .../windowing/AfterProcessingTimeTest.java | 3 +- .../transforms/windowing/TimeTriggerTest.java | 94 -------- 4 files changed, 188 insertions(+), 321 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java index 1e2e4cc59e..1eb84d1a2c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -16,23 +16,45 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; +import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.coders.InstantCoder; +import com.google.cloud.dataflow.sdk.transforms.Min; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnElementContext; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnMergeContext; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerContext; import com.google.cloud.dataflow.sdk.util.MergingStateContext; import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; +import com.google.cloud.dataflow.sdk.util.state.StateTag; +import com.google.cloud.dataflow.sdk.util.state.StateTags; +import com.google.common.collect.ImmutableList; +import org.joda.time.Duration; import org.joda.time.Instant; import java.util.List; +import java.util.Objects; import javax.annotation.Nullable; /** * A base class for triggers that happen after a processing time delay from the arrival * of the first element in a pane. + * + *

    This class is for internal use only and may change at any time. */ -abstract class AfterDelayFromFirstElement extends TimeTrigger { +@Experimental(Experimental.Kind.TRIGGER) +public abstract class AfterDelayFromFirstElement extends OnceTrigger { + + protected static final List> IDENTITY = + ImmutableList.>of(); + + protected static final StateTag> DELAYED_UNTIL_TAG = + StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( + "delayed", InstantCoder.of(), Min.MinFn.naturalOrder())); /** * To complete an implementation, return the desired time from the TriggerContext. @@ -40,11 +62,28 @@ abstract class AfterDelayFromFirstElement extends TimeT @Nullable public abstract Instant getCurrentTime(Trigger.TriggerContext context); + /** + * To complete an implementation, return a new instance like this one, but incorporating + * the provided timestamp mapping functions. Generally should be used by calling the + * constructor of this class from the constructor of the subclass. + */ + protected abstract AfterDelayFromFirstElement newWith( + List> transform); + + /** + * A list of timestampMappers m1, m2, m3, ... m_n considered to be composed in sequence. The + * overall mapping for an instance `instance` is `m_n(... m3(m2(m1(instant))`, + * implemented via #computeTargetTimestamp + */ + protected final List> timestampMappers; + private final TimeDomain timeDomain; public AfterDelayFromFirstElement( - TimeDomain timeDomain, List> timestampMappers) { - super(timestampMappers); + TimeDomain timeDomain, + List> timestampMappers) { + super(null); + this.timestampMappers = timestampMappers; this.timeDomain = timeDomain; } @@ -52,6 +91,64 @@ private Instant getTargetTimestamp(OnElementContext c) { return computeTargetTimestamp(c.currentProcessingTime()); } + /** + * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater + * than the timestamp. + * + *

    TODO: Consider sharing this with FixedWindows, and bring over the equivalent of + * CalendarWindows. + */ + public AfterDelayFromFirstElement alignedTo(final Duration size, final Instant offset) { + return newWith(new AlignFn(size, offset)); + } + + /** + * Aligns the time to be the smallest multiple of {@code size} greater than the timestamp + * since the epoch. + */ + public AfterDelayFromFirstElement alignedTo(final Duration size) { + return alignedTo(size, new Instant(0)); + } + + /** + * Adds some delay to the original target time. + * + * @param delay the delay to add + * @return An updated time trigger that will wait the additional time before firing. + */ + public AfterDelayFromFirstElement plusDelayOf(final Duration delay) { + return newWith(new DelayFn(delay)); + } + + /** + * @deprecated This will be removed in the next major version. Please use only + * {@link #plusDelayOf} and {@link #alignedTo}. + */ + @Deprecated + public OnceTrigger mappedTo(SerializableFunction timestampMapper) { + return newWith(timestampMapper); + } + + @Override + public boolean isCompatible(Trigger other) { + if (!getClass().equals(other.getClass())) { + return false; + } + + AfterDelayFromFirstElement that = (AfterDelayFromFirstElement) other; + return this.timestampMappers.equals(that.timestampMappers); + } + + + private AfterDelayFromFirstElement newWith( + SerializableFunction timestampMapper) { + return newWith( + ImmutableList.>builder() + .addAll(timestampMappers) + .add(timestampMapper) + .build()); + } + @Override public void prefetchOnElement(StateContext state) { state.access(DELAYED_UNTIL_TAG).get(); @@ -124,4 +221,90 @@ && getCurrentTime(context) != null protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { clear(context); } + + protected Instant computeTargetTimestamp(Instant time) { + Instant result = time; + for (SerializableFunction timestampMapper : timestampMappers) { + result = timestampMapper.apply(result); + } + return result; + } + + /** + * A {@link SerializableFunction} to delay the timestamp at which this triggers fires. + */ + private static final class DelayFn implements SerializableFunction { + private final Duration delay; + + public DelayFn(Duration delay) { + this.delay = delay; + } + + @Override + public Instant apply(Instant input) { + return input.plus(delay); + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + + if (!(object instanceof DelayFn)) { + return false; + } + + return this.delay.equals(((DelayFn) object).delay); + } + + @Override + public int hashCode() { + return Objects.hash(delay); + } + } + + /** + * A {@link SerializableFunction} to align an instant to the nearest interval boundary. + */ + static final class AlignFn implements SerializableFunction { + private final Duration size; + private final Instant offset; + + + /** + * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater + * than the timestamp. + */ + public AlignFn(Duration size, Instant offset) { + this.size = size; + this.offset = offset; + } + + @Override + public Instant apply(Instant point) { + long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis(); + return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart); + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + + if (!(object instanceof AlignFn)) { + return false; + } + + AlignFn other = (AlignFn) object; + return other.size.equals(this.size) + && other.offset.equals(this.offset); + } + + @Override + public int hashCode() { + return Objects.hash(size, offset); + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java deleted file mode 100644 index 0263c85900..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTrigger.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.List; -import java.util.Objects; - -/** - * Support for manipulating the time at which time-based {@link Trigger}s fire. - * - * @param {@link BoundedWindow} subclass used to represent the windows used. - */ -@Experimental(Experimental.Kind.TRIGGER) -public abstract class TimeTrigger extends OnceTrigger { - - protected static final StateTag> DELAYED_UNTIL_TAG = - StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( - "delayed", InstantCoder.of(), Min.MinFn.naturalOrder())); - - protected static final List> IDENTITY; - static { - IDENTITY = ImmutableList.>of(); - } - - /** - * A list of timestampMappers m1, m2, m3, ... m_n considered to be composed in sequence. The - * overall mapping for an instance `instance` is `m_n(... m3(m2(m1(instant))`, - * implemented via #computeTargetTimestamp - */ - protected final List> timestampMappers; - - protected TimeTrigger( - List> timestampMappers) { - super(null); - this.timestampMappers = timestampMappers; - } - - protected Instant computeTargetTimestamp(Instant time) { - Instant result = time; - for (SerializableFunction timestampMapper : timestampMappers) { - result = timestampMapper.apply(result); - } - return result; - } - - /** - * Adds some delay to the original target time. - * - * @param delay the delay to add - * @return An updated time trigger that will wait the additional time before firing. - */ - public TimeTrigger plusDelayOf(final Duration delay) { - return newWith(new DelayFn(delay)); - } - - /** - * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater - * than the timestamp. - * - *

    TODO: Consider sharing this with FixedWindows, and bring over the equivalent of - * CalendarWindows. - */ - public TimeTrigger alignedTo(final Duration size, final Instant offset) { - return newWith(new AlignFn(size, offset)); - } - - /** - * Aligns the time to be the smallest multiple of {@code size} greater than the timestamp - * since the epoch. - */ - public TimeTrigger alignedTo(final Duration size) { - return alignedTo(size, new Instant(0)); - } - - /** - * Adjust the time at which the trigger will fire. - * - *

    The {@code timestampMapper} function must have the following properties for all values - * {@code a} and {@code b}: - * - *

      - *
    • Deterministic: If {@code a = b} then {@code timestampMapper(a) = timestampMapper(b)} - *
    • Monotonicity: If {@code a < b} then {@code timestampMapper(a) <= timestampMapper(b)} - *
    - * - * @param timestampMapper Function that will be invoked on the proposed trigger time to determine - * the time at which the trigger should actually fire. - */ - public TimeTrigger mappedTo(SerializableFunction timestampMapper) { - return newWith(timestampMapper); - } - - @Override - public boolean isCompatible(Trigger other) { - if (!getClass().equals(other.getClass())) { - return false; - } - - TimeTrigger that = (TimeTrigger) other; - return this.timestampMappers.equals(that.timestampMappers); - } - - private TimeTrigger newWith(SerializableFunction timestampMapper) { - return newWith(ImmutableList.>builder() - .addAll(timestampMappers) - .add(timestampMapper) - .build()); - } - - /** - * Method to create an updated version of this {@code TimeTrigger} modified to use the specified - * {@code transform}. - * - * @param transform The new transform to apply to target times. - * @return a new {@code TimeTrigger}. - */ - protected abstract TimeTrigger newWith(List> transform); - - /** - * A {@link SerializableFunction} to delay the timestamp at which this triggers fires. - */ - private static final class DelayFn implements SerializableFunction { - private final Duration delay; - - public DelayFn(Duration delay) { - this.delay = delay; - } - - @Override - public Instant apply(Instant input) { - return input.plus(delay); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - - if (!(object instanceof DelayFn)) { - return false; - } - - return this.delay.equals(((DelayFn) object).delay); - } - - @Override - public int hashCode() { - return Objects.hash(delay); - } - } - - /** - * A {@link SerializableFunction} to align an instant to the nearest interval boundary. - */ - private static final class AlignFn implements SerializableFunction { - private final Duration size; - private final Instant offset; - - - /** - * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater - * than the timestamp. - */ - public AlignFn(Duration size, Instant offset) { - this.size = size; - this.offset = offset; - } - - @Override - public Instant apply(Instant point) { - long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis(); - return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - - if (!(object instanceof AlignFn)) { - return false; - } - - AlignFn other = (AlignFn) object; - return other.size.equals(this.size) - && other.offset.equals(this.offset); - } - - @Override - public int hashCode() { - return Objects.hash(size, offset); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java index 0e35fe221f..a3bb3c372e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; @@ -135,7 +136,7 @@ public void testFireDeadline() throws Exception { @Test public void testContinuation() throws Exception { - TimeTrigger firstElementPlus1 = + OnceTrigger firstElementPlus1 = AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.standardHours(1)); assertEquals( new AfterSynchronizedProcessingTime<>(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java deleted file mode 100644 index b15a6037d7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TimeTriggerTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collections; -import java.util.List; - -/** - * Tests for the various time operations in {@link TimeTrigger}. - */ -@RunWith(JUnit4.class) -public class TimeTriggerTest { - @Test - public void testAlignTo() { - TimeTrigger size10 = new TestTimeTrigger().alignedTo(new Duration(10)); - TimeTrigger size10offset5 = - new TestTimeTrigger().alignedTo(new Duration(10), new Instant(5)); - - assertEquals(new Instant(100), size10.computeTargetTimestamp(new Instant(100))); - assertEquals(new Instant(110), size10.computeTargetTimestamp(new Instant(105))); - assertEquals(new Instant(105), size10offset5.computeTargetTimestamp(new Instant(105))); - assertEquals(new Instant(115), size10offset5.computeTargetTimestamp(new Instant(110))); - } - - private static class TestTimeTrigger extends TimeTrigger { - - private TestTimeTrigger() { - this(Collections.>emptyList()); - } - - private TestTimeTrigger(List> timestampMappers) { - super(timestampMappers); - } - - @Override - public Instant computeTargetTimestamp(Instant time) { - return super.computeTargetTimestamp(time); - } - - @Override - protected TestTimeTrigger newWith(List> transform) { - return new TestTimeTrigger(transform); - } - - @Override - public void onElement(OnElementContext c) throws Exception { } - - @Override - public void onMerge(OnMergeContext c) throws Exception { } - - @Override - protected Trigger getContinuationTrigger( - List> continuationTriggers) { - return null; - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(IntervalWindow window) { - return null; - } - - @Override - public boolean shouldFire(TriggerContext context) throws Exception { - return false; - } - - @Override - public void onOnlyFiring(TriggerContext context) throws Exception { } - } -} From d58d7da34799ef5f6e822a6db30bd9c92695f6fe Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 8 Feb 2016 23:11:16 -0800 Subject: [PATCH 106/751] ApiSurface: add debug messages ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114185275 --- .../cloud/dataflow/sdk/util/ApiSurface.java | 72 ++++++++++++++++++- 1 file changed, 69 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java index 7c0e7bdfca..7a9c87733b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java @@ -29,6 +29,9 @@ import com.google.common.reflect.Parameter; import com.google.common.reflect.TypeToken; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; @@ -73,11 +76,13 @@ */ @SuppressWarnings("rawtypes") public class ApiSurface { + private static Logger logger = LoggerFactory.getLogger(ApiSurface.class); /** * Returns an empty {@link ApiSurface}. */ public static ApiSurface empty() { + logger.debug("Returning an empty ApiSurface"); return new ApiSurface(Collections.>emptySet(), Collections.emptySet()); } @@ -103,13 +108,14 @@ public ApiSurface includingPackage(String packageName) throws IOException { ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader()); Set> newRootClasses = Sets.newHashSet(); - newRootClasses.addAll(rootClasses); for (ClassInfo classInfo : classPath.getTopLevelClassesRecursive(packageName)) { Class clazz = classInfo.load(); if (exposed(clazz.getModifiers())) { newRootClasses.add(clazz); } } + logger.debug("Including package {} and subpackages: {}", packageName, newRootClasses); + newRootClasses.addAll(rootClasses); return new ApiSurface(newRootClasses, patternsToPrune); } @@ -119,8 +125,9 @@ public ApiSurface includingPackage(String packageName) throws IOException { */ public ApiSurface includingClass(Class clazz) { Set> newRootClasses = Sets.newHashSet(); - newRootClasses.addAll(rootClasses); + logger.debug("Including class {}", clazz); newRootClasses.add(clazz); + newRootClasses.addAll(rootClasses); return new ApiSurface(newRootClasses, patternsToPrune); } @@ -354,6 +361,8 @@ private void visit(Type type) { * See {@link #addExposedTypes(Type, Class)}. */ private void addExposedTypes(TypeToken type, Class cause) { + logger.debug( + "Adding exposed types from {}, which is the type in type token {}", type.getType(), type); addExposedTypes(type.getType(), cause); } @@ -364,14 +373,19 @@ private void addExposedTypes(TypeToken type, Class cause) { */ private void addExposedTypes(Type type, Class cause) { if (type instanceof TypeVariable) { + logger.debug("Adding exposed types from {}, which is a type variable", type); addExposedTypes((TypeVariable) type, cause); } else if (type instanceof WildcardType) { + logger.debug("Adding exposed types from {}, which is a wildcard type", type); addExposedTypes((WildcardType) type, cause); } else if (type instanceof GenericArrayType) { + logger.debug("Adding exposed types from {}, which is a generic array type", type); addExposedTypes((GenericArrayType) type, cause); } else if (type instanceof ParameterizedType) { + logger.debug("Adding exposed types from {}, which is a parameterized type", type); addExposedTypes((ParameterizedType) type, cause); } else if (type instanceof Class) { + logger.debug("Adding exposed types from {}, which is a class", type); addExposedTypes((Class) type, cause); } else { throw new IllegalArgumentException("Unknown implementation of Type"); @@ -389,6 +403,7 @@ private void addExposedTypes(TypeVariable type, Class cause) { } visit(type); for (Type bound : type.getBounds()) { + logger.debug("Adding exposed types from {}, which is a type bound on {}", bound, type); addExposedTypes(bound, cause); } } @@ -400,9 +415,17 @@ private void addExposedTypes(TypeVariable type, Class cause) { private void addExposedTypes(WildcardType type, Class cause) { visit(type); for (Type lowerBound : type.getLowerBounds()) { + logger.debug( + "Adding exposed types from {}, which is a type lower bound on wildcard type {}", + lowerBound, + type); addExposedTypes(lowerBound, cause); } for (Type upperBound : type.getUpperBounds()) { + logger.debug( + "Adding exposed types from {}, which is a type upper bound on wildcard type {}", + upperBound, + type); addExposedTypes(upperBound, cause); } } @@ -417,6 +440,10 @@ private void addExposedTypes(GenericArrayType type, Class cause) { return; } visit(type); + logger.debug( + "Adding exposed types from {}, which is the component type on generic array type {}", + type.getGenericComponentType(), + type); addExposedTypes(type.getGenericComponentType(), cause); } @@ -441,8 +468,16 @@ private void addExposedTypes(ParameterizedType type, Class cause) { // The type parameters themselves may not be pruned, // for example with List probably the // standard List is pruned, but MyApiType is not. + logger.debug( + "Adding exposed types from {}, which is the raw type on parameterized type {}", + type.getRawType(), + type); addExposedTypes(type.getRawType(), cause); for (Type typeArg : type.getActualTypeArguments()) { + logger.debug( + "Adding exposed types from {}, which is a type argument on parameterized type {}", + typeArg, + type); addExposedTypes(typeArg, cause); } } @@ -467,20 +502,29 @@ private void addExposedTypes(Class clazz, Class cause) { TypeToken token = TypeToken.of(clazz); for (TypeToken superType : token.getTypes()) { if (!superType.equals(token)) { + logger.debug( + "Adding exposed types from {}, which is a super type token on {}", superType, clazz); addExposedTypes(superType, clazz); } } for (Class innerClass : clazz.getDeclaredClasses()) { if (exposed(innerClass.getModifiers())) { + logger.debug( + "Adding exposed types from {}, which is an exposed inner class of {}", + innerClass, + clazz); addExposedTypes(innerClass, clazz); } } for (Field field : clazz.getDeclaredFields()) { if (exposed(field.getModifiers())) { + logger.debug("Adding exposed types from {}, which is an exposed field on {}", field, clazz); addExposedTypes(field, clazz); } } for (Invokable invokable : getExposedInvokables(token)) { + logger.debug( + "Adding exposed types from {}, which is an exposed invokable on {}", invokable, clazz); addExposedTypes(invokable, clazz); } } @@ -488,19 +532,39 @@ private void addExposedTypes(Class clazz, Class cause) { private void addExposedTypes(Invokable invokable, Class cause) { addExposedTypes(invokable.getReturnType(), cause); for (Annotation annotation : invokable.getAnnotations()) { + logger.debug( + "Adding exposed types from {}, which is an annotation on invokable {}", + annotation, + invokable); addExposedTypes(annotation.annotationType(), cause); } for (Parameter parameter : invokable.getParameters()) { + logger.debug( + "Adding exposed types from {}, which is a parameter on invokable {}", + parameter, + invokable); addExposedTypes(parameter, cause); } for (TypeToken exceptionType : invokable.getExceptionTypes()) { + logger.debug( + "Adding exposed types from {}, which is an exception type on invokable {}", + exceptionType, + invokable); addExposedTypes(exceptionType, cause); } } private void addExposedTypes(Parameter parameter, Class cause) { + logger.debug( + "Adding exposed types from {}, which is the type of parameter {}", + parameter.getType(), + parameter); addExposedTypes(parameter.getType(), cause); for (Annotation annotation : parameter.getAnnotations()) { + logger.debug( + "Adding exposed types from {}, which is an annotation on parameter {}", + annotation, + parameter); addExposedTypes(annotation.annotationType(), cause); } } @@ -508,6 +572,8 @@ private void addExposedTypes(Parameter parameter, Class cause) { private void addExposedTypes(Field field, Class cause) { addExposedTypes(field.getGenericType(), cause); for (Annotation annotation : field.getDeclaredAnnotations()) { + logger.debug( + "Adding exposed types from {}, which is an annotation on field {}", annotation, field); addExposedTypes(annotation.annotationType(), cause); } } @@ -515,7 +581,7 @@ private void addExposedTypes(Field field, Class cause) { /** * Returns an {@link Invokable} for each public methods or constructors of a type. */ - private Set getExposedInvokables(TypeToken type) { + private Set getExposedInvokables(TypeToken type) { Set invokables = Sets.newHashSet(); for (Constructor constructor : type.getRawType().getConstructors()) { From 5ae27f08aad0f793e34b98fb3b1456e9c4f0c8b9 Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 9 Feb 2016 09:15:14 -0800 Subject: [PATCH 107/751] Migrate AvroIO to internally use Read.from(AvroSource) File expansion validation has moved into the Dataflow SDK for Java and is performed during application of the AvroIO.Read transform. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114225417 --- .../google/cloud/dataflow/sdk/io/AvroIO.java | 72 +++++++------------ .../runners/DataflowPipelineTranslator.java | 2 - .../runners/dataflow/AvroIOTranslator.java | 30 -------- .../sdk/io/AvroIOGeneratedClassTest.java | 48 ++++++------- 4 files changed, 51 insertions(+), 101 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java index b18e7266e5..9ee7e6b13c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java @@ -16,21 +16,20 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.Read.Bounded; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.ValueWithMetadata; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.AvroReader; import com.google.cloud.dataflow.sdk.runners.worker.AvroSink; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.base.Preconditions; @@ -40,7 +39,6 @@ import org.apache.avro.reflect.ReflectData; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; @@ -299,15 +297,30 @@ public PCollection apply(PInput input) { if (schema == null) { throw new IllegalStateException("need to set the schema of an AvroIO.Read transform"); } + if (validate) { + try { + checkState( + !IOChannelUtils.getFactory(filepattern).match(filepattern).isEmpty(), + "Unable to find any files matching %s", + filepattern); + } catch (IOException e) { + throw new IllegalStateException( + String.format("Failed to validate %s", filepattern), e); + } + } - // Force the output's Coder to be what the read is using, and - // unchangeable later, to ensure that we read the input in the - // format specified by the Read transform. - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - IsBounded.BOUNDED) - .setCoder(getDefaultOutputCoder()); + @SuppressWarnings("unchecked") + Bounded read = + type == GenericRecord.class + ? (Bounded) com.google.cloud.dataflow.sdk.io.Read.from( + AvroSource.from(filepattern).withSchema(schema)) + : com.google.cloud.dataflow.sdk.io.Read.from( + AvroSource.from(filepattern).withSchema(type)); + + PCollection pcol = input.getPipeline().apply(read); + // Honor the default output coder that would have been used by this PTransform. + pcol.setCoder(getDefaultOutputCoder()); + return pcol; } @Override @@ -326,21 +339,6 @@ public Schema getSchema() { public boolean needsValidation() { return validate; } - - static { - @SuppressWarnings("rawtypes") - DirectPipelineRunner.TransformEvaluator transformEvaluator = - new DirectPipelineRunner.TransformEvaluator() { - @Override - @SuppressWarnings("unchecked") - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateReadHelper(transform, context); - } - }; - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, transformEvaluator); - } } /** Disallow construction of utility class. */ @@ -781,22 +779,6 @@ private static void validateOutputComponent(String partialFilePattern) { /** Disallow construction of utility class. */ private AvroIO() {} - private static void evaluateReadHelper( - Read.Bound transform, DirectPipelineRunner.EvaluationContext context) { - AvroReader reader = new AvroReader<>(transform.filepattern, null, null, - (AvroCoder) transform.getDefaultOutputCoder(), context.getPipelineOptions()); - try { - List> elems = ReaderUtils.readAllFromReader(reader); - List> output = new ArrayList<>(); - for (WindowedValue elem : elems) { - output.add(ValueWithMetadata.of(elem)); - } - context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - private static void evaluateWriteHelper( Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { List> elems = diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index cef03a8598..1d14254c24 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -1028,8 +1028,6 @@ private void translateHelper( /////////////////////////////////////////////////////////////////////////// // IO Translation. - registerTransformTranslator( - AvroIO.Read.Bound.class, new AvroIOTranslator.ReadTranslator()); registerTransformTranslator( AvroIO.Write.Bound.class, new AvroIOTranslator.WriteTranslator()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java index 652bc4ac20..b114021c4d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java @@ -31,36 +31,6 @@ */ public class AvroIOTranslator { - /** - * Implements AvroIO Read translation for the Dataflow backend. - */ - @SuppressWarnings("rawtypes") - public static class ReadTranslator implements TransformTranslator { - - @Override - public void translate( - AvroIO.Read.Bound transform, - TranslationContext context) { - translateReadHelper(transform, context); - } - - private void translateReadHelper( - AvroIO.Read.Bound transform, - TranslationContext context) { - if (context.getPipelineOptions().isStreaming()) { - throw new IllegalArgumentException("AvroIO not supported in streaming mode."); - } - - PathValidator validator = context.getPipelineOptions().getPathValidator(); - String filepattern = validator.validateInputFilePatternSupported(transform.getFilepattern()); - context.addStep(transform, "ParallelRead"); - context.addInput(PropertyNames.FORMAT, "avro"); - context.addInput(PropertyNames.FILEPATTERN, filepattern); - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - context.addInput(PropertyNames.VALIDATE_SOURCE, transform.needsValidation()); - } - } - /** * Implements AvroIO Write translation for the Dataflow backend. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java index 22fecd369a..6bb459de7a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java @@ -148,102 +148,102 @@ void runTestRead(AvroIO.Read.Bound read, String expectedName, T[] expecte public void testReadFromGeneratedClass() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class), - "AvroIO.Read.out", generateAvroObjects()); + "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()), - "AvroIO.Read.out", generateAvroObjects()); + "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class), - "MyRead.out", generateAvroObjects()); + "MyRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()), - "MyRead.out", generateAvroObjects()); + "MyRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class) .named("HerRead"), - "HerRead.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(AvroGeneratedUser.class), - "HerRead.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .named("HerRead") .from(avroFile.getPath()), - "HerRead.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()) .named("HerRead"), - "HerRead.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); } @Test public void testReadFromSchema() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schema), - "AvroIO.Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .from(avroFile.getPath()), - "AvroIO.Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(schema), - "MyRead.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(schema) .from(avroFile.getPath()), - "MyRead.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schema) .named("HerRead"), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(schema), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .named("HerRead") .from(avroFile.getPath()), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .from(avroFile.getPath()) .named("HerRead"), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); } @Test public void testReadFromSchemaString() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schemaString), - "AvroIO.Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .from(avroFile.getPath()), - "AvroIO.Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(schemaString), - "MyRead.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(schemaString) .from(avroFile.getPath()), - "MyRead.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schemaString) .named("HerRead"), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(schemaString), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .named("HerRead") .from(avroFile.getPath()), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .from(avroFile.getPath()) .named("HerRead"), - "HerRead.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); } void runTestWrite(AvroIO.Write.Bound write, String expectedName) From 38702c351c6948a0e2d7221f24ea090d85dc0b0b Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 9 Feb 2016 10:31:47 -0800 Subject: [PATCH 108/751] Upgrade to SLF4J 1.7.14 so that we can use slf4j-api MDC Since SLF4J 1.7.13, the MDC now functions correctly because of fix: https://github.com/qos-ch/slf4j/commit/fd5d546503b1b7ba3d865382da2a0dbda0c13cb3 This is for ASF Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114233927 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 03d2a8ddc3..071b5df4ea 100644 --- a/pom.xml +++ b/pom.xml @@ -80,7 +80,7 @@ 4.11 3.0.0-beta-1 v1-rev7-1.21.0 - 1.7.7 + 1.7.14 v1-rev53-1.21.0 From c71eb08e9c4d48d76bc3720f501b8922d9525a4c Mon Sep 17 00:00:00 2001 From: markshields Date: Tue, 9 Feb 2016 11:27:00 -0800 Subject: [PATCH 109/751] Eagerly merge all window state * Remove MergeableState extends State, replace with static helpers. * Always merge state. New pipelines will have at most one state address window per active window. * 'Premerge' any windows which have more than one to ensure reload on legacy pipelines works with new code. * Prefetch for merging before any merging occurs. This helps reduce pauses for round GetData trips when elements for multiple windows end up in the same bundle. (We don't attempt to prefetch for firing since that is much less common and would require substantial additional bookkeeping to pull off.) * Various interface fiddles to make this work. * BUG: We were not merging end-of-window or garbage collection holds correctly. We implement two optimizations on watermark hold merging to not incur a performance penalty: - If the hold depends only on the window, update it on merge and clear all the existing holds, who's values are now irrelevant. - If there's only a single active window and we know the hold depends only on the earliest event time then the merged result will be equal to the current effective hold. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114240537 --- .../windowing/AfterDelayFromFirstElement.java | 34 +- .../sdk/transforms/windowing/AfterPane.java | 20 +- .../transforms/windowing/AfterWatermark.java | 8 + .../transforms/windowing/OutputTimeFn.java | 2 +- .../sdk/transforms/windowing/Trigger.java | 17 +- .../sdk/transforms/windowing/WindowFn.java | 4 +- .../dataflow/sdk/util/ActiveWindowSet.java | 27 +- .../sdk/util/MergingActiveWindowSet.java | 120 ++++- .../sdk/util/MergingStateContext.java | 23 +- .../dataflow/sdk/util/NonEmptyPanes.java | 48 +- .../sdk/util/NonMergingActiveWindowSet.java | 8 + .../cloud/dataflow/sdk/util/ReduceFn.java | 29 +- .../sdk/util/ReduceFnContextFactory.java | 245 +++++---- .../dataflow/sdk/util/ReduceFnRunner.java | 463 ++++++++++-------- .../cloud/dataflow/sdk/util/StateContext.java | 12 - .../dataflow/sdk/util/SystemReduceFn.java | 63 ++- .../sdk/util/TriggerContextFactory.java | 108 ++-- .../dataflow/sdk/util/TriggerRunner.java | 48 +- .../dataflow/sdk/util/WatermarkHold.java | 127 ++--- .../dataflow/sdk/util/state/BagState.java | 2 +- .../sdk/util/state/CombiningValueState.java | 17 +- .../state/CombiningValueStateInternal.java | 5 + .../util/state/InMemoryStateInternals.java | 35 +- .../sdk/util/state/MergeableState.java | 40 -- .../dataflow/sdk/util/state/MergedBag.java | 93 ---- .../sdk/util/state/MergedCombiningValue.java | 125 ----- .../state/MergedWatermarkStateInternal.java | 141 ------ .../sdk/util/state/MergingStateInternals.java | 93 ---- .../sdk/util/state/StateInternals.java | 16 - .../dataflow/sdk/util/state/StateMerging.java | 251 ++++++++++ .../dataflow/sdk/util/state/StateTag.java | 4 +- .../dataflow/sdk/util/state/StateTags.java | 44 +- .../dataflow/sdk/util/state/ValueState.java | 7 + .../util/state/WatermarkStateInternal.java | 11 +- .../dataflow/sdk/util/ReduceFnTester.java | 2 +- .../dataflow/sdk/util/TriggerTester.java | 31 +- .../state/InMemoryStateInternalsTest.java | 157 +++--- 37 files changed, 1198 insertions(+), 1282 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergeableState.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedBag.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedCombiningValue.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedWatermarkStateInternal.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateInternals.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java index 1eb84d1a2c..51de85e862 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -18,16 +18,16 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.InstantCoder; +import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.Min; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnElementContext; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnMergeContext; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerContext; import com.google.cloud.dataflow.sdk.util.MergingStateContext; import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; +import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.common.collect.ImmutableList; @@ -52,7 +52,8 @@ public abstract class AfterDelayFromFirstElement extend protected static final List> IDENTITY = ImmutableList.>of(); - protected static final StateTag> DELAYED_UNTIL_TAG = + protected static final StateTag, + Instant>> DELAYED_UNTIL_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "delayed", InstantCoder.of(), Min.MinFn.naturalOrder())); @@ -171,25 +172,36 @@ public void onElement(OnElementContext c) throws Exception { } @Override - public void prefetchOnMerge(MergingStateContext state) { - state.mergingAccess(DELAYED_UNTIL_TAG).get(); + public void prefetchOnMerge(MergingStateContext state) { + super.prefetchOnMerge(state); + StateMerging.prefetchCombiningValues(state, DELAYED_UNTIL_TAG); } @Override public void onMerge(OnMergeContext c) throws Exception { + // NOTE: We could try to delete all timers which are still active, but we would + // need access to a timer context for each merging window. + // for (CombiningValueStateInternal, Instant> state : + // c.state().accessInEachMergingWindow(DELAYED_UNTIL_TAG).values()) { + // Instant timestamp = state.get().read(); + // if (timestamp != null) { + // .deleteTimer(timestamp, timeDomain); + // } + // } + // Instead let them fire and be ignored. + // If the trigger is already finished, there is no way it will become re-activated if (c.trigger().isFinished()) { + StateMerging.clear(c.state(), DELAYED_UNTIL_TAG); + // NOTE: We do not attempt to delete the timers. return; } // Determine the earliest point across all the windows, and delay to that. - CombiningValueState mergingDelays = - c.state().mergingAccess(DELAYED_UNTIL_TAG); + StateMerging.mergeCombiningValues(c.state(), DELAYED_UNTIL_TAG); - Instant earliestTargetTime = mergingDelays.get().read(); + Instant earliestTargetTime = c.state().access(DELAYED_UNTIL_TAG).get().read(); if (earliestTargetTime != null) { - mergingDelays.clear(); - mergingDelays.add(earliestTargetTime); c.setTimer(earliestTargetTime, timeDomain); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java index 61a7d18bd4..8eed3fcea7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java @@ -22,7 +22,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; import com.google.cloud.dataflow.sdk.util.MergingStateContext; import com.google.cloud.dataflow.sdk.util.StateContext; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; +import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -40,7 +41,8 @@ @Experimental(Experimental.Kind.TRIGGER) public class AfterPane extends OnceTrigger{ - private static final StateTag> ELEMENTS_IN_PANE_TAG = +private static final StateTag> + ELEMENTS_IN_PANE_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "count", VarLongCoder.of(), new Sum.SumLongFn())); @@ -64,21 +66,23 @@ public void onElement(OnElementContext c) throws Exception { } @Override - public void prefetchOnMerge(MergingStateContext state) { - state.mergingAccess(ELEMENTS_IN_PANE_TAG).get(); + public void prefetchOnMerge(MergingStateContext state) { + super.prefetchOnMerge(state); + StateMerging.prefetchCombiningValues(state, ELEMENTS_IN_PANE_TAG); } @Override public void onMerge(OnMergeContext context) throws Exception { + // If we've already received enough elements and finished in some window, + // then this trigger is just finished. if (context.trigger().finishedInAnyMergingWindow()) { context.trigger().setFinished(true); + StateMerging.clear(context.state(), ELEMENTS_IN_PANE_TAG); return; } - // Eagerly merge - long count = context.state().mergingAccess(ELEMENTS_IN_PANE_TAG).get().read(); - context.state().mergingAccess(ELEMENTS_IN_PANE_TAG).clear(); - context.state().access(ELEMENTS_IN_PANE_TAG).add(count); + // Otherwise, compute the sum of elements in all the active panes. + StateMerging.mergeCombiningValues(context.state(), ELEMENTS_IN_PANE_TAG); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index 694a538f6c..1330337926 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -179,6 +179,9 @@ public void onElement(OnElementContext c) throws Exception { @Override public void onMerge(OnMergeContext c) throws Exception { + // NOTE that the ReduceFnRunner will delete all end-of-window timers for the + // merged-away windows. + ExecutableTrigger earlySubtrigger = c.trigger().subTrigger(EARLY_INDEX); // We check the early trigger to determine if we are still processing it or // if the end of window has transitioned us to the late trigger @@ -328,11 +331,16 @@ public AfterWatermarkLate withLateFirings(OnceTrigger lateFirings) { @Override public void onElement(OnElementContext c) throws Exception { + // NOTE: The ReduceFnRunner will have already set an end-of-window timer, so this is + // redundant. However we leave it here so that the trigger machinery can stand on its own. c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); } @Override public void onMerge(OnMergeContext c) throws Exception { + // NOTE that the ReduceFnRunner will delete all end-of-window timers for the + // merged-away windows. + if (!c.trigger().finishedInAllMergingWindows()) { // If the trigger is still active in any merging window then it is still active in the new // merged window, because even if the merged window is "done" some pending elements haven't diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java index 785bc5ab5a..c5d943d3c5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java @@ -179,7 +179,7 @@ public Instant merge(W resultWindow, Iterable mergingTimestam * {@inheritDoc} * * @return {@code false}. An {@link OutputTimeFn} that depends only on the window should extend - * {@link DependsOnlyOnWindow}. + * {@link OutputTimeFn.DependsOnlyOnWindow}. */ @Override public final boolean dependsOnlyOnWindow() { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java index 32d1069d66..4afcf11a4b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java @@ -232,8 +232,7 @@ public abstract class OnElementContext extends TriggerContext { * timer firings for a window will be received, but the implementation should choose to ignore * those that are not applicable. * - * @param timestamp the time at which the trigger’s {@link Trigger#onTimer} callback should - * execute + * @param timestamp the time at which the trigger should be re-evaluated * @param domain the domain that the {@code timestamp} applies to */ public abstract void setTimer(Instant timestamp, TimeDomain domain); @@ -248,9 +247,6 @@ public abstract class OnElementContext extends TriggerContext { * operational hook. */ public abstract class OnMergeContext extends TriggerContext { - /** The old windows that were merged. */ - public abstract Iterable oldWindows(); - /** * Sets a timer to fire when the watermark or processing time is beyond the given timestamp. * Timers are not guaranteed to fire immediately, but will be delivered at some time afterwards. @@ -259,8 +255,7 @@ public abstract class OnMergeContext extends TriggerContext { * timer firings for a window will be received, but the implementation should choose to ignore * those that are not applicable. * - * @param timestamp the time at which the trigger’s {@link Trigger#onTimer} callback should - * execute + * @param timestamp the time at which the trigger should be re-evaluated * @param domain the domain that the {@code timestamp} applies to */ public abstract void setTimer(Instant timestamp, TimeDomain domain); @@ -270,7 +265,7 @@ public abstract class OnMergeContext extends TriggerContext { public abstract OnMergeContext forTrigger(ExecutableTrigger trigger); @Override - public abstract MergingStateContext state(); + public abstract MergingStateContext state(); @Override public abstract MergingTriggerInfo trigger(); @@ -294,11 +289,11 @@ protected Trigger(@Nullable List> subTriggers) { * *

    Leaf triggers should update their state by inspecting their status and any state * in the merging windows. Composite triggers should update their state by calling - * {@link ExecutableTrigger#invokeMerge} on their sub-triggers, and applying appropriate logic. + * {@link ExecutableTrigger#invokeOnMerge} on their sub-triggers, and applying appropriate logic. * *

    A trigger such as {@link AfterWatermark#pastEndOfWindow} may no longer be finished; * it is the responsibility of the trigger itself to record this fact. It is forbidden for - * a trigger to become finished due to {@link onMerge}, as it has not yet fired the pending + * a trigger to become finished due to {@link #onMerge}, as it has not yet fired the pending * elements that led to it being ready to fire. * *

    The implementation does not need to clear out any state associated with the old windows. @@ -336,7 +331,7 @@ public void prefetchOnElement(StateContext state) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onMerge} call. */ - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnMerge(state); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java index 0423cfb5ea..d51fc7ead4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java @@ -132,8 +132,8 @@ public abstract void merge(Collection toBeMerged, W mergeResult) public abstract W getSideInputWindow(final BoundedWindow window); /** - * @deprecated Implement {@link #getOutputTimeFn} to return either the appropriate - * {@link ElementaryOutputTimeFn} or a custom {@link OutputTimeFn} extending + * @deprecated Implement {@link #getOutputTimeFn} to return one of the appropriate + * {@link OutputTimeFns}, or a custom {@link OutputTimeFn} extending * {@link OutputTimeFn.Defaults}. */ @Deprecated diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java index c5854ea4ea..9af11ca453 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java @@ -67,12 +67,20 @@ public interface ActiveWindowSet { */ public interface MergeCallback { /** - * Called when windows are about to be merged. + * Called when windows are about to be merged, but before any {@link #onMerge} callback + * has been made. + */ + void prefetchOnMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) + throws Exception; + + /** + * Called when windows are about to be merged, after all {@link #prefetchOnMerge} calls + * have been made, but before the active window set has been updated to reflect the merge. * * @param toBeMerged the windows about to be merged. * @param activeToBeMerged the subset of {@code toBeMerged} corresponding to windows which * are currently ACTIVE (and about to be merged). The remaining windows have been deemed - * EPHEMERAL. + * EPHEMERAL, and thus have no state associated with them. * @param mergeResult the result window, either a member of {@code toBeMerged} or new. */ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) @@ -128,10 +136,17 @@ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeRe /** * Invoke {@link WindowFn#mergeWindows} on the {@code WindowFn} associated with this window set, * merging as many of the active windows as possible. {@code mergeCallback} will be invoked for - * each group of windows that are merged. After this no NEW windows will remain. + * each group of windows that are merged. After this no NEW windows will remain, all merge + * result windows will be ACTIVE, and all windows which have been merged away will not be ACTIVE. */ void merge(MergeCallback mergeCallback) throws Exception; + /** + * Signal that all state in {@link #readStateAddresses} for {@code window} has been merged into + * the {@link #writeStateAddress} for {@code window}. + */ + void merged(W window); + /** * Return the state address windows for ACTIVE {@code window} from which all state associated * should be read and merged. @@ -143,4 +158,10 @@ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeRe * written. Always one of the results of {@link #readStateAddresses}. */ W writeStateAddress(W window); + + /** + * Return the state address window into which all new state should be written after + * ACTIVE windows {@code toBeMerged} have been merged into {@code mergeResult}. + */ + W mergedWriteStateAddress(Collection toBeMerged, W mergeResult); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index ebf1540e6e..3a6960980d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -32,6 +32,8 @@ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; import java.util.Set; @@ -134,6 +136,11 @@ public void removeEphemeralWindows() { @Override public void persist() { + if (activeWindowToStateAddressWindows.isEmpty()) { + // Force all persistent state to disappear. + valueState.clear(); + return; + } if (activeWindowToStateAddressWindows.equals(originalActiveWindowToStateAddressWindows)) { // No change. return; @@ -171,14 +178,14 @@ public boolean isActive(W window) { @Override public void addNew(W window) { if (!windowToActiveWindow.containsKey(window)) { - activeWindowToStateAddressWindows.put(window, new HashSet()); + activeWindowToStateAddressWindows.put(window, new LinkedHashSet()); } } @Override public void addActive(W window) { if (!windowToActiveWindow.containsKey(window)) { - Set stateAddressWindows = new HashSet<>(); + Set stateAddressWindows = new LinkedHashSet<>(); stateAddressWindows.add(window); activeWindowToStateAddressWindows.put(window, stateAddressWindows); windowToActiveWindow.put(window, window); @@ -203,10 +210,18 @@ public void remove(W window) { private class MergeContextImpl extends WindowFn.MergeContext { private MergeCallback mergeCallback; + private final List> allToBeMerged; + private final List> allActiveToBeMerged; + private final List allMergeResults; + private final Set seen; public MergeContextImpl(MergeCallback mergeCallback) { windowFn.super(); this.mergeCallback = mergeCallback; + allToBeMerged = new ArrayList<>(); + allActiveToBeMerged = new ArrayList<>(); + allMergeResults = new ArrayList<>(); + seen = new HashSet<>(); } @Override @@ -216,15 +231,65 @@ public Collection windows() { @Override public void merge(Collection toBeMerged, W mergeResult) throws Exception { - recordMerge(mergeCallback, toBeMerged, mergeResult); + // The arguments have come from userland. + Preconditions.checkNotNull(toBeMerged); + Preconditions.checkNotNull(mergeResult); + List copyOfToBeMerged = new ArrayList<>(toBeMerged.size()); + List activeToBeMerged = new ArrayList<>(toBeMerged.size()); + boolean includesMergeResult = false; + for (W window : toBeMerged) { + Preconditions.checkNotNull(window); + Preconditions.checkState( + isActive(window), "Expecting merge window %s to be active", window); + if (window.equals(mergeResult)) { + includesMergeResult = true; + } + boolean notDup = seen.add(window); + Preconditions.checkState( + notDup, "Expecting merge window %s to appear in at most one merge set", window); + copyOfToBeMerged.add(window); + if (!activeWindowToStateAddressWindows.get(window).isEmpty()) { + activeToBeMerged.add(window); + } + } + if (!includesMergeResult) { + Preconditions.checkState( + !isActive(mergeResult), "Expecting result window %s to be new", mergeResult); + } + allToBeMerged.add(copyOfToBeMerged); + allActiveToBeMerged.add(activeToBeMerged); + allMergeResults.add(mergeResult); + } + + public void recordMerges() throws Exception { + for (int i = 0; i < allToBeMerged.size(); i++) { + mergeCallback.prefetchOnMerge( + allToBeMerged.get(i), allActiveToBeMerged.get(i), allMergeResults.get(i)); + } + for (int i = 0; i < allToBeMerged.size(); i++) { + mergeCallback.onMerge( + allToBeMerged.get(i), allActiveToBeMerged.get(i), allMergeResults.get(i)); + recordMerge(allToBeMerged.get(i), allMergeResults.get(i)); + } + allToBeMerged.clear(); + allActiveToBeMerged.clear(); + allMergeResults.clear(); + seen.clear(); } } @Override public void merge(MergeCallback mergeCallback) throws Exception { + MergeContextImpl context = new MergeContextImpl(mergeCallback); + // See what the window function does with the NEW and already ACTIVE windows. - windowFn.mergeWindows(new MergeContextImpl(mergeCallback)); + // Entering userland. + windowFn.mergeWindows(context); + + // Actually do the merging and invoke the callbacks. + context.recordMerges(); + // Any remaining NEW windows should become implicitly ACTIVE. for (Map.Entry> entry : activeWindowToStateAddressWindows.entrySet()) { if (entry.getValue().isEmpty()) { // This window was NEW but since it survived merging must now become ACTIVE. @@ -238,11 +303,11 @@ public void merge(MergeCallback mergeCallback) throws Exception { /** * A {@code WindowFn.mergeWindows} call has requested {@code toBeMerged} (which must * all be ACTIVE} be considered equivalent to {@code activeWindow} (which is either a - * member of {@code toBeMerged} or is a new window). + * member of {@code toBeMerged} or is a new window). Make the corresponding change in + * the active window set. */ - private void recordMerge(MergeCallback mergeCallback, Collection toBeMerged, W mergeResult) - throws Exception { - Set newStateAddressWindows = new HashSet<>(); + private void recordMerge(Collection toBeMerged, W mergeResult) throws Exception { + Set newStateAddressWindows = new LinkedHashSet<>(); Set existingStateAddressWindows = activeWindowToStateAddressWindows.get(mergeResult); if (existingStateAddressWindows != null) { // Preserve all the existing state address windows for mergeResult. @@ -256,8 +321,6 @@ private void recordMerge(MergeCallback mergeCallback, Collection toBeMerge newEphemeralWindows.addAll(existingEphemeralWindows); } - Collection activeToBeMerged = new ArrayList<>(); - for (W other : toBeMerged) { Set otherStateAddressWindows = activeWindowToStateAddressWindows.get(other); Preconditions.checkState(otherStateAddressWindows != null, "Window %s is not ACTIVE", other); @@ -284,21 +347,16 @@ private void recordMerge(MergeCallback mergeCallback, Collection toBeMerge // Now other equiv mergeResult. if (otherStateAddressWindows.contains(other)) { // Other was ACTIVE and is now known to be MERGED. - newStateAddressWindows.add(other); - activeToBeMerged.add(other); } else if (otherStateAddressWindows.isEmpty()) { // Other was NEW thus has no state. It is now EPHEMERAL. newEphemeralWindows.add(other); } else if (other.equals(mergeResult)) { // Other was ACTIVE, was never used to store elements, but is still ACTIVE. // Leave it as active. - activeToBeMerged.add(other); } else { // Other was ACTIVE, was never used to store element, as is no longer considered ACTIVE. // It is now EPHEMERAL. newEphemeralWindows.add(other); - // However, since it may have metadata state, include it in the ACTIVE to be merged set. - activeToBeMerged.add(other); } windowToActiveWindow.put(other, mergeResult); } @@ -315,7 +373,16 @@ private void recordMerge(MergeCallback mergeCallback, Collection toBeMerge activeWindowToEphemeralWindows.put(mergeResult, newEphemeralWindows); } - mergeCallback.onMerge(toBeMerged, activeToBeMerged, mergeResult); + merged(mergeResult); + } + + @Override + public void merged(W window) { + Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); + Preconditions.checkState(stateAddressWindows != null, "Window %s is not ACTIVE", window); + W first = Iterables.getFirst(stateAddressWindows, null); + stateAddressWindows.clear(); + stateAddressWindows.add(first); } /** @@ -343,6 +410,21 @@ public W writeStateAddress(W window) { return result; } + @Override + public W mergedWriteStateAddress(Collection toBeMerged, W mergeResult) { + Set stateAddressWindows = activeWindowToStateAddressWindows.get(mergeResult); + if (stateAddressWindows != null && !stateAddressWindows.isEmpty()) { + return Iterables.getFirst(stateAddressWindows, null); + } + for (W mergedWindow : toBeMerged) { + stateAddressWindows = activeWindowToStateAddressWindows.get(mergedWindow); + if (stateAddressWindows != null && !stateAddressWindows.isEmpty()) { + return Iterables.getFirst(stateAddressWindows, null); + } + } + return mergeResult; + } + @VisibleForTesting public void checkInvariants() { Set knownStateAddressWindows = new HashSet<>(); @@ -422,13 +504,13 @@ public String toString() { * Replace null {@code multimap} with empty map, and replace null entries in {@code multimap} with * empty sets. */ - private static Map> emptyIfNull(Map> multimap) { + private static Map> emptyIfNull(@Nullable Map> multimap) { if (multimap == null) { return new HashMap<>(); } else { for (Map.Entry> entry : multimap.entrySet()) { if (entry.getValue() == null) { - entry.setValue(new HashSet()); + entry.setValue(new LinkedHashSet()); } } return multimap; @@ -439,7 +521,7 @@ private static Map> emptyIfNull(Map> multimap) { private static Map> deepCopy(Map> multimap) { Map> newMultimap = new HashMap<>(); for (Map.Entry> entry : multimap.entrySet()) { - newMultimap.put(entry.getKey(), new HashSet(entry.getValue())); + newMultimap.put(entry.getKey(), new LinkedHashSet(entry.getValue())); } return newMultimap; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java index 877cbf9843..98d62f919c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java @@ -17,23 +17,18 @@ package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.state.MergeableState; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateTag; import java.util.Map; -/** Interface for interacting with persistent state within {@link #onMerge}. */ -public interface MergingStateContext extends StateContext { - /** - * Analogous to {@link #access}, but across all windows which are about to be merged. - */ - > StateT mergingAccess(StateTag address); - - /** - * Analogous to {@link #access}, but returned as a map from each window which is - * about to be merged to the corresponding state. - */ - public abstract Map - mergingAccessInEachMergingWindow(StateTag address); +/** Interface for interacting with persistent state when merging windows. */ +public interface MergingStateContext extends StateContext { + /** + * Analogous to {@link #access}, but returned as a map from each window which is + * about to be merged to the corresponding state. Only includes windows which + * are known to have state. + */ + public Map accessInEachMergingWindow( + StateTag address); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java index f567888260..2d5fa41964 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java @@ -19,8 +19,9 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; +import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -31,7 +32,6 @@ * @param The kind of windows being tracked. */ public abstract class NonEmptyPanes { - public static NonEmptyPanes create( WindowingStrategy strategy, ReduceFn reduceFn) { if (strategy.getMode() == AccumulationMode.DISCARDING_FIRED_PANES) { @@ -57,13 +57,22 @@ public static NonEmptyPanes create( */ public abstract StateContents isEmpty(ReduceFn.Context context); + /** + * Prefetch in preparation for merging. + */ + public abstract void prefetchOnMerge(MergingStateContext state); + + /** + * Eagerly merge backing state. + */ + public abstract void onMerge(MergingStateContext context); + /** * An implementation of {@code NonEmptyPanes} optimized for use with discarding mode. Uses the * presence of data in the accumulation buffer to record non-empty panes. */ private static class DiscardingModeNonEmptyPanes extends NonEmptyPanes { - private ReduceFn reduceFn; private DiscardingModeNonEmptyPanes(ReduceFn reduceFn) { @@ -84,33 +93,50 @@ public void recordContent(ReduceFn.Context context) { public void clearPane(ReduceFn.Context context) { // Nothing to do -- the reduceFn is tracking contents } + + @Override + public void prefetchOnMerge(MergingStateContext state) { + // Nothing to do -- the reduceFn is tracking contents + } + + @Override + public void onMerge(MergingStateContext context) { + // Nothing to do -- the reduceFn is tracking contents + } } /** * An implementation of {@code NonEmptyPanes} for general use. */ private static class GeneralNonEmptyPanes extends NonEmptyPanes { - - private static final StateTag> PANE_ADDITIONS_TAG = + private static final StateTag> + PANE_ADDITIONS_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "count", VarLongCoder.of(), new Sum.SumLongFn())); @Override public void recordContent(ReduceFn.Context context) { - context.state().accessAcrossMergedWindows(PANE_ADDITIONS_TAG).add(1L); + context.state().access(PANE_ADDITIONS_TAG).add(1L); } @Override public void clearPane(ReduceFn.Context context) { - context.state().accessAcrossMergedWindows(PANE_ADDITIONS_TAG).clear(); + context.state().access(PANE_ADDITIONS_TAG).clear(); } @Override public StateContents isEmpty(ReduceFn.Context context) { - // Since we only check for empty element sets when a trigger fires it's unreasonable - // to require a prefetch. - return context.state().accessAcrossMergedWindows(PANE_ADDITIONS_TAG).isEmpty(); + return context.state().access(PANE_ADDITIONS_TAG).isEmpty(); + } + + @Override + public void prefetchOnMerge(MergingStateContext state) { + StateMerging.prefetchCombiningValues(state, PANE_ADDITIONS_TAG); + } + + @Override + public void onMerge(MergingStateContext context) { + StateMerging.mergeCombiningValues(context, PANE_ADDITIONS_TAG); } } } - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java index 10d7666f5d..cb7f9b06e7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.common.collect.ImmutableSet; +import java.util.Collection; import java.util.Set; /** @@ -64,6 +65,8 @@ public void remove(W window) {} @Override public void merge(MergeCallback mergeCallback) throws Exception {} + @Override + public void merged(W window) {} @Override public Set readStateAddresses(W window) { @@ -74,4 +77,9 @@ public Set readStateAddresses(W window) { public W writeStateAddress(W window) { return window; } + + @Override + public W mergedWriteStateAddress(Collection toBeMerged, W mergeResult) { + return mergeResult; + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java index 91fd3c4941..b1b323d79e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java @@ -17,13 +17,11 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.state.MergeableState; import com.google.cloud.dataflow.sdk.util.state.StateContents; import org.joda.time.Instant; import java.io.Serializable; -import java.util.Collection; /** * Specification for processing to happen after elements have been grouped by key. @@ -65,16 +63,9 @@ public abstract class ProcessValueContext extends Context { /** Information accessible within {@link #onMerge}. */ public abstract class OnMergeContext extends Context { - /** - * Return the collection of windows that were merged. - * - *

    Note that this may include the result window. - */ - public abstract Collection mergingWindows(); - /** Return the interface for accessing state. */ @Override - public abstract MergingStateContext state(); + public abstract MergingStateContext state(); } /** Information accessible within {@link #onTrigger}. */ @@ -95,16 +86,6 @@ public abstract class OnTriggerContext extends Context { /** * Called when windows are merged. - * - *

    There are generally two strategies for implementing this and handling merging of state: - *

      - *
    • Lazily merge the state when outputting. This is especially easy if all the state is stored - * in {@link MergeableState}, since an automatically merged view can be retrieved. - *
    • Eagerly merge the state inside the {@link #onMerge} implementation. Load all the state - * from the merging windows and write it back to the result window. In this case the state in the - * result window should be cleared into between the read and write in case it was in the source - * windows. - *
    */ public abstract void onMerge(OnMergeContext c) throws Exception; @@ -116,6 +97,14 @@ public abstract class OnTriggerContext extends Context { */ public abstract void onTrigger(OnTriggerContext c) throws Exception; + /** + * Called before {@link #onMerge} is invoked to provide an opportunity to prefetch any needed + * state. + * + * @param c Context to use prefetch from. + */ + public void prefetchOnMerge(MergingStateContext c) throws Exception {} + /** * Called before {@link #onTrigger} is invoked to provide an opportunity to prefetch any needed * state. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index 92c23e7132..2fa2c3ff9a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.state.MergeableState; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateInternals; @@ -34,9 +33,7 @@ import org.joda.time.Instant; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import java.util.Map; import javax.annotation.Nullable; @@ -45,7 +42,6 @@ * Factory for creating instances of the various {@link ReduceFn} contexts. */ class ReduceFnContextFactory { - public interface OnTriggerCallbacks { void output(OutputT toOutput); } @@ -57,10 +53,9 @@ public interface OnTriggerCallbacks { private ActiveWindowSet activeWindows; private TimerInternals timerInternals; - ReduceFnContextFactory( - K key, ReduceFn reduceFn, WindowingStrategy windowingStrategy, - StateInternals stateInternals, ActiveWindowSet activeWindows, - TimerInternals timerInternals) { + ReduceFnContextFactory(K key, ReduceFn reduceFn, + WindowingStrategy windowingStrategy, StateInternals stateInternals, + ActiveWindowSet activeWindows, TimerInternals timerInternals) { this.key = key; this.reduceFn = reduceFn; this.windowingStrategy = windowingStrategy; @@ -69,34 +64,46 @@ public interface OnTriggerCallbacks { this.timerInternals = timerInternals; } - private StateContextImpl stateContext(W window) { - return new StateContextImpl<>( - activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, window); + /** Where should we look for state associated with a given window? */ + public static enum StateStyle { + /** All state is associated with the window itself. */ + DIRECT, + /** State is associated with the 'state address' windows tracked by the active window set. */ + RENAMED + } + + private StateContextImpl stateContext(W window, StateStyle style) { + return new StateContextImpl<>(activeWindows, windowingStrategy.getWindowFn().windowCoder(), + stateInternals, window, style); } - public ReduceFn.Context base(W window) { - return new ContextImpl(stateContext(window)); + public ReduceFn.Context base(W window, StateStyle style) { + return new ContextImpl(stateContext(window, style)); } public ReduceFn.ProcessValueContext forValue( - W window, InputT value, Instant timestamp) { - return new ProcessValueContextImpl(stateContext(window), value, timestamp); + W window, InputT value, Instant timestamp, StateStyle style) { + return new ProcessValueContextImpl(stateContext(window, style), value, timestamp); } - public ReduceFn.OnTriggerContext forTrigger( - W window, StateContents pane, OnTriggerCallbacks callbacks) { - return new OnTriggerContextImpl(stateContext(window), pane, callbacks); + public ReduceFn.OnTriggerContext forTrigger(W window, + StateContents pane, StateStyle style, OnTriggerCallbacks callbacks) { + return new OnTriggerContextImpl(stateContext(window, style), pane, callbacks); } public ReduceFn.OnMergeContext forMerge( - Collection mergingWindows, W resultWindow) { + Collection activeToBeMerged, W mergeResult, StateStyle style) { return new OnMergeContextImpl( - new MergingStateContextImpl(stateContext(resultWindow), mergingWindows)); + new MergingStateContextImpl(activeWindows, windowingStrategy.getWindowFn().windowCoder(), + stateInternals, style, activeToBeMerged, mergeResult)); } + public ReduceFn.OnMergeContext forPremerge(W window) { + return new OnPremergeContextImpl(new PremergingStateContextImpl( + activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, window)); + } private class TimersImpl implements Timers { - private final StateNamespace namespace; public TimersImpl(StateNamespace namespace) { @@ -132,110 +139,130 @@ public Instant currentEventTime() { } } - static class StateContextImpl - implements StateContext { + // ====================================================================== + // StateContexts + // ====================================================================== - private final ActiveWindowSet activeWindows; - private final W window; - protected StateNamespace windowNamespace; + static class StateContextImpl implements StateContext { + protected final ActiveWindowSet activeWindows; + protected final W window; + protected final StateNamespace windowNamespace; protected final Coder windowCoder; - private final StateInternals stateInternals; + protected final StateInternals stateInternals; + protected final StateStyle style; - public StateContextImpl( - ActiveWindowSet activeWindows, - Coder windowCoder, - StateInternals stateInternals, - W window) { + public StateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, + StateInternals stateInternals, W window, StateStyle style) { this.activeWindows = activeWindows; this.windowCoder = windowCoder; this.stateInternals = stateInternals; this.window = checkNotNull(window); this.windowNamespace = namespaceFor(window); + this.style = style; } protected StateNamespace namespaceFor(W window) { return StateNamespaces.window(windowCoder, window); } + protected StateNamespace windowNamespace() { + return windowNamespace; + } + W window() { return window; } StateNamespace namespace() { - return windowNamespace; - } - - @Override - public StorageT access(StateTag address) { - return stateInternals.state(windowNamespace, address); + return windowNamespace(); } @Override - public > StorageT accessAcrossMergedWindows( - StateTag address) { - List readNamespaces = new ArrayList<>(); - for (W readWindow : activeWindows.readStateAddresses(window)) { - readNamespaces.add(namespaceFor(readWindow)); + public StateT access(StateTag address) { + switch (style) { + case DIRECT: + return stateInternals.state(windowNamespace(), address); + case RENAMED: + return stateInternals.state( + namespaceFor(activeWindows.writeStateAddress(window)), address); } - StateNamespace writeNamespace = namespaceFor(activeWindows.writeStateAddress(window)); - return stateInternals.mergedState(readNamespaces, writeNamespace, address, window); + throw new RuntimeException(); // cases are exhaustive. } } - static class MergingStateContextImpl implements MergingStateContext { + static class MergingStateContextImpl + extends StateContextImpl implements MergingStateContext { + private final Collection activeToBeMerged; - private final StateContextImpl delegate; - private final Collection mergingWindows; - - public MergingStateContextImpl(StateContextImpl delegate, Collection mergingWindows) { - this.delegate = delegate; - this.mergingWindows = mergingWindows; - } - - W window() { - return delegate.window(); + public MergingStateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, + StateInternals stateInternals, StateStyle style, Collection activeToBeMerged, + W mergeResult) { + super(activeWindows, windowCoder, stateInternals, mergeResult, style); + this.activeToBeMerged = activeToBeMerged; } - Collection mergingWindows() { - return mergingWindows; + @Override + public StateT access(StateTag address) { + switch (style) { + case DIRECT: + return stateInternals.state(windowNamespace(), address); + case RENAMED: + return stateInternals.state( + namespaceFor(activeWindows.mergedWriteStateAddress(activeToBeMerged, window)), + address); + } + throw new RuntimeException(); // cases are exhaustive. } @Override - public StorageT access(StateTag address) { - return delegate.access(address); + public Map accessInEachMergingWindow( + StateTag address) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (W mergingWindow : activeToBeMerged) { + StateNamespace namespace = null; + switch (style) { + case DIRECT: + namespace = namespaceFor(mergingWindow); + break; + case RENAMED: + namespace = namespaceFor(activeWindows.writeStateAddress(mergingWindow)); + break; + } + Preconditions.checkNotNull(namespace); // cases are exhaustive. + builder.put(mergingWindow, stateInternals.state(namespace, address)); + } + return builder.build(); } + } - @Override - public > StorageT accessAcrossMergedWindows( - StateTag address) { - return delegate.accessAcrossMergedWindows(address); + static class PremergingStateContextImpl + extends StateContextImpl implements MergingStateContext { + public PremergingStateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, + StateInternals stateInternals, W window) { + super(activeWindows, windowCoder, stateInternals, window, StateStyle.RENAMED); } - @Override - public > StateT mergingAccess(StateTag address) { - List readNamespaces = new ArrayList<>(); - for (W mergingWindow : mergingWindows) { - readNamespaces.add(delegate.namespaceFor(mergingWindow)); - } - return delegate.stateInternals.mergedState( - readNamespaces, delegate.windowNamespace, address, delegate.window); + Collection mergingWindows() { + return activeWindows.readStateAddresses(window); } @Override - public Map mergingAccessInEachMergingWindow( + public Map accessInEachMergingWindow( StateTag address) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (W mergingWindow : mergingWindows) { - StateT stateForWindow = delegate.stateInternals.state( - delegate.namespaceFor(mergingWindow), address); - builder.put(mergingWindow, stateForWindow); + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (W stateAddressWindow : activeWindows.readStateAddresses(window)) { + StateT stateForWindow = stateInternals.state(namespaceFor(stateAddressWindow), address); + builder.put(stateAddressWindow, stateForWindow); } return builder.build(); } } - private class ContextImpl extends ReduceFn.Context { + // ====================================================================== + // Contexts + // ====================================================================== + private class ContextImpl extends ReduceFn.Context { private final StateContextImpl state; private final TimersImpl timers; @@ -252,7 +279,7 @@ public K key() { @Override public W window() { - return state.window; + return state.window(); } @Override @@ -273,7 +300,6 @@ public Timers timers() { private class ProcessValueContextImpl extends ReduceFn.ProcessValueContext { - private final InputT value; private final Instant timestamp; private final StateContextImpl state; @@ -294,7 +320,7 @@ public K key() { @Override public W window() { - return state.window; + return state.window(); } @Override @@ -323,16 +349,14 @@ public Timers timers() { } } - private class OnTriggerContextImpl - extends ReduceFn.OnTriggerContext { - + private class OnTriggerContextImpl extends ReduceFn.OnTriggerContext { private final StateContextImpl state; private final StateContents pane; private final OnTriggerCallbacks callbacks; private final TimersImpl timers; - private OnTriggerContextImpl(StateContextImpl state, - StateContents pane, OnTriggerCallbacks callbacks) { + private OnTriggerContextImpl(StateContextImpl state, StateContents pane, + OnTriggerCallbacks callbacks) { reduceFn.super(); this.state = state; this.pane = pane; @@ -347,7 +371,7 @@ public K key() { @Override public W window() { - return state.window; + return state.window(); } @Override @@ -376,16 +400,14 @@ public Timers timers() { } } - private class OnMergeContextImpl - extends ReduceFn.OnMergeContext { - + private class OnMergeContextImpl extends ReduceFn.OnMergeContext { private final MergingStateContextImpl state; private final TimersImpl timers; private OnMergeContextImpl(MergingStateContextImpl state) { reduceFn.super(); this.state = state; - this.timers = new TimersImpl(state.delegate.namespace()); + this.timers = new TimersImpl(state.namespace()); } @Override @@ -399,18 +421,49 @@ public WindowingStrategy windowingStrategy() { } @Override - public MergingStateContext state() { + public MergingStateContext state() { return state; } @Override - public Collection mergingWindows() { - return state.mergingWindows; + public W window() { + return state.window(); + } + + @Override + public Timers timers() { + return timers; + } + } + + private class OnPremergeContextImpl extends ReduceFn.OnMergeContext { + private final PremergingStateContextImpl state; + private final TimersImpl timers; + + private OnPremergeContextImpl(PremergingStateContextImpl state) { + reduceFn.super(); + this.state = state; + this.timers = new TimersImpl(state.namespace()); + } + + @Override + public K key() { + return key; + } + + @Override + public WindowingStrategy windowingStrategy() { + return windowingStrategy; + } + + @Override + public MergingStateContext state() { + return state; } @Override public W window() { - return state.delegate.window; + return state.window(); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 83eadf337c..85b9bae4ba 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; @@ -23,8 +24,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.ActiveWindowSet.MergeCallback; import com.google.cloud.dataflow.sdk.util.ReduceFnContextFactory.OnTriggerCallbacks; +import com.google.cloud.dataflow.sdk.util.ReduceFnContextFactory.StateStyle; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.util.state.StateContents; @@ -70,7 +71,8 @@ * @param The output type that will be produced for each key. * @param The type of windows this operates on. */ -public class ReduceFnRunner { +public class ReduceFnRunner + implements ActiveWindowSet.MergeCallback { private final WindowingStrategy windowingStrategy; private final WindowingInternals> windowingInternals; @@ -83,22 +85,23 @@ public class ReduceFnRunner { * Track which windows are still active and which 'state address' windows contain state * for a merged window. * - *

    In general, when windows are merged we prefer to defer merging their state until the - * overall state is needed. In other words, we prefer to merge state 'lazily' (on read) - * instead of 'eagerly' (on merge). + *

      + *
    • State: Global map for all active windows for this computation and key. + *
    • Lifetime: Cleared when no active windows need to be tracked. A window lives within + * the active window set until its trigger is closed or the window is garbage collected. + *
    */ private final ActiveWindowSet activeWindows; /** - * User's reduce function (or {@link SystemReduceFn} for simple GroupByKey operations). - * May store its own state. + * Always a {@link SystemReduceFn}. * *
      - *
    • Merging: Uses {@link #activeWindows} to determine the 'state address' windows under which - * state is read and written. Merging may be done lazily, in which case state is merged - * only when a pane fires. - *
    • Lifetime: Possibly cleared when a pane fires. Always cleared when a window is - * garbage collected. + *
    • State: A bag of accumulated values, or the intermediate result of a combiner. + *
    • State style: RENAMED + *
    • Merging: Concatenate or otherwise combine the state from each merged window. + *
    • Lifetime: Cleared when a pane fires if DISCARDING_FIRED_PANES. Otherwise cleared + * when trigger is finished or when the window is garbage collected. *
    */ private final ReduceFn reduceFn; @@ -107,7 +110,9 @@ public class ReduceFnRunner { * Manage the setting and firing of timer events. * *
      - *
    • Merging: Timers are cancelled when windows are merged away. + *
    • Merging: End-of-window and garbage collection timers are cancelled when windows are + * merged away. Timers created by triggers are never garbage collected and are left to + * fire and be ignored. *
    • Lifetime: Timers automatically disappear after they fire. *
    */ @@ -117,10 +122,14 @@ public class ReduceFnRunner { * Manage the execution and state for triggers. * *
      - *
    • Merging: All state is keyed by actual window, so does not depend on {@link #activeWindows}. - * Individual triggers know how to eagerly merge their state on merge. + *
    • State: Tracks which sub-triggers have finished, and any additional state needed to + * determine when the trigger should fire. + *
    • State style: DIRECT + *
    • Merging: Finished bits are explicitly managed. Other state is eagerly merged as + * needed. *
    • Lifetime: Most trigger state is cleared when the final pane is emitted. However - * a tombstone is left behind which must be cleared when the window is garbage collected. + * the finished bits are left behind and must be cleared when the window is + * garbage collected. *
    */ private final TriggerRunner triggerRunner; @@ -129,16 +138,11 @@ public class ReduceFnRunner { * Store the output watermark holds for each window. * *
      - *
    • Merging: Generally uses {@link #activeWindows} to maintain the 'state address' windows - * under which holds are stored, and holds are merged lazily only when a pane fires. - * However there are two special cases: - *
        - *
      • Depending on the window's {@link OutputTimeFn}, it is possible holds need to be read, - * recalculated, cleared, and added back on merging. - *
      • When a pane fires it may be necessary to add (back) an end-of-window or - * garbage collection hold. If the current window is no longer active these holds will - * be associated with the current window. - *
      + *
    • State: Bag of hold timestamps. + *
    • State style: RENAMED + *
    • Merging: Depending on {@link OutputTimeFn}, may need to be recalculated on merging. + * When a pane fires it may be necessary to add (back) an end-of-window or garbage collection + * hold. *
    • Lifetime: Cleared when a pane fires or when the window is garbage collected. *
    */ @@ -150,9 +154,12 @@ public class ReduceFnRunner { * Store the previously emitted pane (if any) for each window. * *
      + *
    • State: The previous {@link PaneInfo} passed to the user's {@link DoFn#processElement}, + * if any. + *
    • Style style: DIRECT *
    • Merging: Always keyed by actual window, so does not depend on {@link #activeWindows}. * Cleared when window is merged away. - *
    • Lifetime: Cleared when trigger is finished or window is garbage collected. + *
    • Lifetime: Cleared when trigger is closed or window is garbage collected. *
    */ private final PaneInfoTracker paneInfoTracker; @@ -161,8 +168,9 @@ public class ReduceFnRunner { * Store whether we've seen any elements for a window since the last pane was emitted. * *
      - *
    • Merging: Uses {@link #activeWindows} determine the state address windows under which - * counts are stored. Merging is done lazily when checking if a pane needs to fire. + *
    • State: Unless DISCARDING_FIRED_PANES, a count of number of elements added so far. + *
    • State style: RENAMED. + *
    • Merging: Counts are summed when windows are merged. *
    • Lifetime: Cleared when pane fires or window is garbage collected. *
    */ @@ -170,8 +178,7 @@ public class ReduceFnRunner { public ReduceFnRunner(K key, WindowingStrategy windowingStrategy, TimerInternals timerInternals, WindowingInternals> windowingInternals, - Aggregator droppedDueToClosedWindow, - ReduceFn reduceFn) { + Aggregator droppedDueToClosedWindow, ReduceFn reduceFn) { this.key = key; this.timerInternals = timerInternals; this.paneInfoTracker = new PaneInfoTracker(timerInternals); @@ -206,7 +213,7 @@ private ActiveWindowSet createActiveWindowSet() { @VisibleForTesting boolean isFinished(W window) { - return triggerRunner.isClosed(contextFactory.base(window).state()); + return triggerRunner.isClosed(contextFactory.base(window, StateStyle.DIRECT).state()); } /** @@ -246,9 +253,12 @@ public void processElements(Iterable> values) throws Excep // Trigger output from any window for which the trigger is ready for (W mergedWindow : windowsToConsider) { - ReduceFn.Context context = contextFactory.base(mergedWindow); - triggerRunner.prefetchShouldFire(context.state()); - emitIfAppropriate(context, false /* isEndOfWindow */); + ReduceFn.Context directContext = + contextFactory.base(mergedWindow, StateStyle.DIRECT); + ReduceFn.Context renamedContext = + contextFactory.base(mergedWindow, StateStyle.RENAMED); + triggerRunner.prefetchShouldFire(directContext.state()); + emitIfAppropriate(directContext, renamedContext, false/* isEndOfWindow */); } // We're all done with merging and emitting elements so can compress the activeWindow state. @@ -277,12 +287,31 @@ private void collectAndMergeWindows(Iterable> values) { @SuppressWarnings("unchecked") W window = (W) untypedWindow; - ReduceFn.Context context = contextFactory.base(window); - if (triggerRunner.isClosed(context.state())) { + ReduceFn.Context directContext = + contextFactory.base(window, StateStyle.DIRECT); + if (triggerRunner.isClosed(directContext.state())) { // This window has already been closed. // We will update the counter for this in the corresponding processElement call. continue; } + + if (activeWindows.isActive(window)) { + Set stateAddressWindows = activeWindows.readStateAddresses(window); + if (stateAddressWindows.size() > 1) { + // This is a legacy window who's state has not been eagerly merged. + // Do that now. + ReduceFn.OnMergeContext premergeContext = + contextFactory.forPremerge(window); + try { + reduceFn.onMerge(premergeContext); + } catch (Exception e) { + throw wrapMaybeUserException(e); + } + watermarkHold.onMerge(premergeContext); + activeWindows.merged(window); + } + } + // Add this window as NEW if we've not yet seen it. activeWindows.addNew(window); } @@ -291,66 +320,94 @@ private void collectAndMergeWindows(Iterable> values) { // Merge all of the active windows and retain a mapping from source windows to result windows. mergeActiveWindows(); - // Make sure we've scheduled timers for any ACTIVE windows we just introduced. + // Make sure we've scheduled end-of-window or garbage collection timers for any + // ACTIVE windows we just introduced. // (Timers for ACTIVE windows which are now MERGED will have been discarded above.) for (W window : Sets.difference(activeWindows.getActiveWindows(), currentlyActiveWindows)) { - scheduleEndOfWindowOrGarbageCollectionTimer(contextFactory.base(window)); + scheduleEndOfWindowOrGarbageCollectionTimer(contextFactory.base(window, StateStyle.DIRECT)); } } - private void mergeActiveWindows() { + /** + * Called from the active window set to indicate {@code toBeMerged} (of which only + * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) will later + * be merged into {@code mergeResult}. + */ + @Override + public void prefetchOnMerge( + Collection toBeMerged, Collection activeToBeMerged, W mergeResult) throws Exception { + ReduceFn.OnMergeContext directMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); + ReduceFn.OnMergeContext renamedMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); + + // Prefetch various state. + triggerRunner.prefetchForMerge(directMergeContext.state()); try { - activeWindows.merge(new MergeCallback() { - @Override - public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) - throws Exception { - // At this point activeWindows has already incorporated the results of the merge. - ReduceFn.OnMergeContext mergeResultContext = - contextFactory.forMerge(toBeMerged, mergeResult); - - // Prefetch various state. - triggerRunner.prefetchForMerge(mergeResult, toBeMerged, mergeResultContext.state()); - - // Run the reduceFn to perform any needed merging. - try { - reduceFn.onMerge(mergeResultContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.prefetchOnMerge(renamedMergeContext.state()); + } catch (Exception e) { + throw wrapMaybeUserException(e); + } + watermarkHold.prefetchOnMerge(renamedMergeContext.state()); + nonEmptyPanes.prefetchOnMerge(renamedMergeContext.state()); + } + + /** + * Called from the active window set to indicate {@code toBeMerged} (of which only + * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) are about + * to be merged into {@code mergeResult}. + */ + @Override + public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) + throws Exception { + // At this point activeWindows has NOT incorporated the results of the merge. + ReduceFn.OnMergeContext directMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); + ReduceFn.OnMergeContext renamedMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); + + // Run the reduceFn to perform any needed merging. + try { + reduceFn.onMerge(renamedMergeContext); + } catch (Exception e) { + throw wrapMaybeUserException(e); + } - // Merge the watermark holds if the output time function is not just MIN. - // Otherwise, leave all the merging window watermark holds where they are. - watermarkHold.onMerge(mergeResultContext); + // Merge the watermark holds. + watermarkHold.onMerge(renamedMergeContext); - // Have the trigger merge state as needed - try { - triggerRunner.onMerge(mergeResultContext); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Failed to merge the triggers", e); - } + // Merge non-empty pane state. + nonEmptyPanes.onMerge(renamedMergeContext.state()); - for (W active : activeToBeMerged) { - if (active.equals(mergeResult)) { - // Not merged away. - continue; - } - WindowTracing.debug("ReduceFnRunner.mergeActiveWindows/onMerge: Merging {} into {}", - active, mergeResult); - // Currently ACTIVE window is about to become MERGED. - ReduceFn.Context clearContext = contextFactory.base(active); - // We are going to take care of any cleanup now, so cancel timers. - cancelEndOfWindowAndGarbageCollectionTimers(clearContext); - // All the trigger state has been merged. Clear any tombstones. - triggerRunner.clearEverything(clearContext); - // We no longer care about any previous panes of merged away windows. The - // merge result window gets to start fresh if it is new. - paneInfoTracker.clear(clearContext.state()); - // Any reduceFn state, watermark holds and non-empty pane state have either been - // merged away or will be lazily merged when the next pane fires. - } - } - }); + // Have the trigger merge state as needed + try { + triggerRunner.onMerge(directMergeContext); + } catch (Exception e) { + Throwables.propagateIfPossible(e); + throw new RuntimeException("Failed to merge the triggers", e); + } + + for (W active : activeToBeMerged) { + if (active.equals(mergeResult)) { + // Not merged away. + continue; + } + // Cleanup flavor A: Currently ACTIVE window is about to become MERGED. + // Clear any state not already cleared by the onMerge calls above. + WindowTracing.debug("ReduceFnRunner.onMerge: Merging {} into {}", active, mergeResult); + ReduceFn.Context directClearContext = + contextFactory.base(active, StateStyle.DIRECT); + // No need for the end-of-window or garbage collection timers. + cancelEndOfWindowAndGarbageCollectionTimers(directClearContext); + // We no longer care about any previous panes of merged away windows. The + // merge result window gets to start fresh if it is new. + paneInfoTracker.clear(directClearContext.state()); + } + } + + private void mergeActiveWindows() { + try { + activeWindows.merge(this); } catch (Exception e) { Throwables.propagateIfPossible(e); throw new RuntimeException("Exception while merging windows", e); @@ -378,51 +435,54 @@ private Collection processElement(WindowedValue value) { // Prefetch in each of the windows if we're going to need to process triggers for (W window : windows) { - ReduceFn.ProcessValueContext context = - contextFactory.forValue(window, value.getValue(), value.getTimestamp()); - triggerRunner.prefetchForValue(context.state()); + ReduceFn.ProcessValueContext directContext = contextFactory.forValue( + window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); + triggerRunner.prefetchForValue(directContext.state()); } // Process the element for each (representative) window it belongs to. for (W window : windows) { - ReduceFn.ProcessValueContext context = - contextFactory.forValue(window, value.getValue(), value.getTimestamp()); + ReduceFn.ProcessValueContext directContext = contextFactory.forValue( + window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); + ReduceFn.ProcessValueContext renamedContext = contextFactory.forValue( + window, value.getValue(), value.getTimestamp(), StateStyle.RENAMED); // Check to see if the triggerRunner thinks the window is closed. If so, drop that window. - if (triggerRunner.isClosed(context.state())) { + if (triggerRunner.isClosed(directContext.state())) { droppedDueToClosedWindow.addValue(1L); WindowTracing.debug( "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", - value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); + + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", + value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); continue; } - nonEmptyPanes.recordContent(context); + nonEmptyPanes.recordContent(renamedContext); // Make sure we've scheduled the end-of-window or garbage collection timer for this window // However if we have pre-merged then they will already have been scheduled. if (windowingStrategy.getWindowFn().isNonMerging()) { - scheduleEndOfWindowOrGarbageCollectionTimer(context); + scheduleEndOfWindowOrGarbageCollectionTimer(directContext); } // Hold back progress of the output watermark until we have processed the pane this - // element will be included within. Also add a hold at the end-of-window or garbage - // collection time to allow empty panes to contribute elements which won't be dropped - // due to lateness. - watermarkHold.addHolds(context); + // element will be included within. If the element is too late for that, place a hold at + // the end-of-window or garbage collection time to allow empty panes to contribute elements + // which won't be dropped due to lateness by a following computation (assuming the following + // computation uses the same allowed lateness value...) + watermarkHold.addHolds(renamedContext); // Execute the reduceFn, which will buffer the value as appropriate try { - reduceFn.processValue(context); + reduceFn.processValue(renamedContext); } catch (Exception e) { throw wrapMaybeUserException(e); } // Run the trigger to update its state try { - triggerRunner.processValue(context); + triggerRunner.processValue(directContext); } catch (Exception e) { Throwables.propagateIfPossible(e); throw new RuntimeException("Failed to run trigger", e); @@ -442,14 +502,24 @@ public void onTimer(TimerData timer) { @SuppressWarnings("unchecked") WindowNamespace windowNamespace = (WindowNamespace) timer.getNamespace(); W window = windowNamespace.getWindow(); - - if (!activeWindows.isActive(window)) { + ReduceFn.Context directContext = + contextFactory.base(window, StateStyle.DIRECT); + ReduceFn.Context renamedContext = + contextFactory.base(window, StateStyle.RENAMED); + + // Has this window had its trigger finish? + // - The trigger may implement isClosed as constant false. + // - If the window function does not support windowing then all windows will be considered + // active. + // So we must combine the above. + boolean windowIsActive = + activeWindows.isActive(window) && !triggerRunner.isClosed(directContext.state()); + + if (!windowIsActive) { WindowTracing.debug( "ReduceFnRunner.onTimer: Note that timer {} is for non-ACTIVE window {}", timer, window); } - ReduceFn.Context context = contextFactory.base(window); - // If this is an end-of-window timer then we should test if an AfterWatermark trigger // will fire. // It's fine if the window trigger has such trigger, this flag is only used to decide @@ -470,18 +540,18 @@ public void onTimer(TimerData timer) { key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - if (activeWindows.isActive(window) && !triggerRunner.isClosed(context.state())) { + if (windowIsActive) { // We need to call onTrigger to emit the final pane if required. // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, // and the watermark has passed the end of the window. boolean isWatermarkTrigger = isEndOfWindowTimer; - onTrigger(context, isWatermarkTrigger, - true /* isFinished */, false /* willStillBeActive */); + onTrigger(directContext, renamedContext, isWatermarkTrigger, true/* isFinished */); } - // Clear all the state for this window since we'll never see elements for it again. + // Cleanup flavor B: Clear all the remaining state for this window since we'll never + // see elements for it again. try { - clearAllState(context); + clearAllState(directContext, renamedContext, windowIsActive); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, UserCodeException.class); throw new RuntimeException( @@ -493,9 +563,9 @@ public void onTimer(TimerData timer) { + "inputWatermark:{}; outputWatermark:{}", key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - if (activeWindows.isActive(window) && !triggerRunner.isClosed(context.state())) { + if (windowIsActive) { try { - emitIfAppropriate(context, isEndOfWindowTimer); + emitIfAppropriate(directContext, renamedContext, isEndOfWindowTimer); } catch (Exception e) { Throwables.propagateIfPossible(e); throw Throwables.propagate(e); @@ -514,9 +584,9 @@ public void onTimer(TimerData timer) { WindowTracing.debug( "ReduceFnRunner.onTimer: Scheduling cleanup timer for key:{}; window:{} at {} with " + "inputWatermark:{}; outputWatermark:{}", - key, context.window(), cleanupTime, timerInternals.currentInputWatermarkTime(), + key, directContext.window(), cleanupTime, timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - context.timers().setTimer(cleanupTime, TimeDomain.EVENT_TIME); + directContext.timers().setTimer(cleanupTime, TimeDomain.EVENT_TIME); } } } @@ -525,27 +595,42 @@ public void onTimer(TimerData timer) { * Clear all the state associated with {@code context}'s window. * Should only be invoked if we know all future elements for this window will be considered * beyond allowed lateness. - * This is a superset of the clearing done by {@link #handleTriggerResult} below since: + * This is a superset of the clearing done by {@link #emitIfAppropriate} below since: *
      *
    1. We can clear the trigger state tombstone since we'll never need to ask about it again. *
    2. We can clear any remaining garbage collection hold. *
    */ - private void clearAllState(ReduceFn.Context context) throws Exception { - boolean isActive = activeWindows.isActive(context.window()); - watermarkHold.clearHolds(context, isActive); - if (isActive) { - // The trigger never finished, so make sure we clear any remaining state. + private void clearAllState(ReduceFn.Context directContext, + ReduceFn.Context renamedContext, boolean windowIsActive) + throws Exception { + if (windowIsActive) { + // Since window is still active the trigger has not closed. try { - reduceFn.clearState(context); + reduceFn.clearState(renamedContext); } catch (Exception e) { throw wrapMaybeUserException(e); } - nonEmptyPanes.clearPane(context); - activeWindows.remove(context.window()); + watermarkHold.clearHolds(renamedContext); + nonEmptyPanes.clearPane(renamedContext); + triggerRunner.clearState(directContext); + } else { + // Needed only for backwards compatibility over UPDATE. + // Clear any end-of-window or garbage collection holds keyed by the current window. + // Only needed if: + // - We have merging windows. + // - We are DISCARDING_FIRED_PANES. + // - A pane has fired. + // - But the trigger is not (yet) closed. + if (windowingStrategy.getMode() == AccumulationMode.DISCARDING_FIRED_PANES + && !windowingStrategy.getWindowFn().isNonMerging()) { + watermarkHold.clearHolds(directContext); + } } - triggerRunner.clearEverything(context); - paneInfoTracker.clear(context.state()); + paneInfoTracker.clear(directContext.state()); + activeWindows.remove(directContext.window()); + // We'll never need to test for the trigger being closed again. + triggerRunner.clearFinished(directContext); } /** Should the reduce function state be cleared? */ @@ -564,16 +649,17 @@ private boolean shouldDiscardAfterFiring(boolean isFinished) { /** * Possibly emit a pane if a trigger is ready to fire or timers require it, and cleanup state. */ - private void emitIfAppropriate(ReduceFn.Context context, - boolean isEndOfWindow) throws Exception { - if (!triggerRunner.shouldFire(context)) { + private void emitIfAppropriate(ReduceFn.Context directContext, + ReduceFn.Context renamedContext, boolean isEndOfWindow) + throws Exception { + if (!triggerRunner.shouldFire(directContext)) { // Ignore unless trigger is ready to fire return; } // Inform the trigger of the transition to see if it is finished - triggerRunner.onFire(context); - boolean isFinished = triggerRunner.isClosed(context.state()); + triggerRunner.onFire(directContext); + boolean isFinished = triggerRunner.isClosed(directContext.state()); // Will be able to clear all element state after triggering? boolean shouldDiscard = shouldDiscardAfterFiring(isFinished); @@ -581,45 +667,33 @@ private void emitIfAppropriate(ReduceFn.Context context, // Run onTrigger to produce the actual pane contents. // As a side effect it will clear all element holds, but not necessarily any // end-of-window or garbage collection holds. - onTrigger(context, isEndOfWindow, isFinished, !shouldDiscard); + onTrigger(directContext, renamedContext, isEndOfWindow, isFinished); // Now that we've triggered, the pane is empty. - nonEmptyPanes.clearPane(context); + nonEmptyPanes.clearPane(renamedContext); // Cleanup buffered data if appropriate if (shouldDiscard) { - // Clear the reduceFn state across all windows in the equivalence class for the current - // window. + // Cleanup flavor C: The user does not want any buffered data to persist between panes. try { - reduceFn.clearState(context); + reduceFn.clearState(renamedContext); } catch (Exception e) { throw wrapMaybeUserException(e); } - - // Remove the window from active set. - // This will forget the equivalence class for this window. - WindowTracing.debug("ReduceFnRunner.handleTriggerResult: removing {}", context.window()); - activeWindows.remove(context.window()); - - if (!triggerRunner.isClosed(context.state())) { - // We still need to consider this window active since we may have had to add an - // end-of-window or garbage collection hold above. - activeWindows.addActive(context.window()); - } } - if (triggerRunner.isClosed(context.state())) { - // If we're finishing, clear up the trigger tree as well. - // However, we'll leave behind a tombstone so we know the trigger is finished. + if (isFinished) { + // Cleanup flavor D: If trigger is closed we will ignore all new incoming elements. + // Clear state not otherwise cleared by onTrigger and clearPane above. + // Remember the trigger is, indeed, closed until the window is garbage collected. try { - triggerRunner.clearState(context); - paneInfoTracker.clear(context.state()); + triggerRunner.clearState(directContext); + paneInfoTracker.clear(directContext.state()); } catch (Exception e) { Throwables.propagateIfPossible(e); throw new RuntimeException("Exception while clearing trigger state", e); } - // No more watermark holds will be placed (even for end-of-window or garbage - // collection holds). + activeWindows.remove(directContext.window()); } } @@ -636,8 +710,7 @@ private boolean needToEmit( // This is the unique ON_TIME pane, triggered by an AfterWatermark. return true; } - if (isFinished - && windowingStrategy.getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS) { + if (isFinished && windowingStrategy.getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS) { // This is known to be the final pane, and the user has requested it even when empty. return true; } @@ -646,22 +719,23 @@ private boolean needToEmit( /** * Run the {@link ReduceFn#onTrigger} method and produce any necessary output. - * - * @param context the context for the pane to fire - * @param isWatermarkTrigger true if this triggering is for an AfterWatermark trigger - * @param isFinish true if this will be the last triggering processed */ - private void onTrigger(final ReduceFn.Context context, - boolean isWatermarkTrigger, boolean isFinished, boolean willStillBeActive) { + private void onTrigger(final ReduceFn.Context directContext, + ReduceFn.Context renamedContext, boolean isWatermarkTrigger, + boolean isFinished) { // Collect state. - StateContents outputTimestampFuture = watermarkHold.extractAndRelease( - context, isFinished, willStillBeActive); - StateContents paneFuture = paneInfoTracker.getNextPaneInfo( - context, isWatermarkTrigger, isFinished); - StateContents isEmptyFuture = nonEmptyPanes.isEmpty(context); + StateContents outputTimestampFuture = + watermarkHold.extractAndRelease(renamedContext, isFinished); + StateContents paneFuture = + paneInfoTracker.getNextPaneInfo(directContext, isWatermarkTrigger, isFinished); + StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext); - reduceFn.prefetchOnTrigger(context.state()); - triggerRunner.prefetchOnFire(context.state()); + try { + reduceFn.prefetchOnTrigger(renamedContext.state()); + } catch (Exception e) { + throw wrapMaybeUserException(e); + } + triggerRunner.prefetchOnFire(directContext.state()); // Is a no-op. Why? // Calculate the pane info. final PaneInfo pane = paneFuture.read(); @@ -671,31 +745,38 @@ private void onTrigger(final ReduceFn.Context context, // Only emit a pane if it has data or empty panes are observable. if (needToEmit(isEmptyFuture.read(), isWatermarkTrigger, isFinished, pane.getTiming())) { // Run reduceFn.onTrigger method. - final List windows = Collections.singletonList(context.window()); - ReduceFn.OnTriggerContext triggerContext = contextFactory.forTrigger( - context.window(), paneFuture, new OnTriggerCallbacks() { - @Override - public void output(OutputT toOutput) { - // We're going to output panes, so commit the (now used) PaneInfo. - // TODO: Unnecessary if isFinal? - paneInfoTracker.storeCurrentPaneInfo(context, pane); - - // Output the actual value. - windowingInternals.outputWindowedValue( - KV.of(key, toOutput), outputTimestamp, windows, pane); - } - }); + final List windows = Collections.singletonList(directContext.window()); + ReduceFn.OnTriggerContext renamedTriggerContext = + contextFactory.forTrigger(directContext.window(), paneFuture, StateStyle.RENAMED, + new OnTriggerCallbacks() { + @Override + public void output(OutputT toOutput) { + // We're going to output panes, so commit the (now used) PaneInfo. + // TODO: This is unnecessary if the trigger isFinished since the saved + // state will be immediately deleted. + paneInfoTracker.storeCurrentPaneInfo(directContext, pane); + + // Output the actual value. + windowingInternals.outputWindowedValue( + KV.of(key, toOutput), outputTimestamp, windows, pane); + } + }); try { - reduceFn.onTrigger(triggerContext); + reduceFn.onTrigger(renamedTriggerContext); } catch (Exception e) { throw wrapMaybeUserException(e); } } } - private void scheduleEndOfWindowOrGarbageCollectionTimer(ReduceFn.Context context) { - Instant fireTime = context.window().maxTimestamp(); + /** + * Make sure we will notice when the input watermark passes the end-of-window or garbage + * collection time. + */ + private void scheduleEndOfWindowOrGarbageCollectionTimer( + ReduceFn.Context directContext) { + Instant fireTime = directContext.window().maxTimestamp(); String which = "end-of-window"; Instant inputWM = timerInternals.currentInputWatermarkTime(); if (inputWM != null && fireTime.isBefore(inputWM)) { @@ -707,9 +788,9 @@ private void scheduleEndOfWindowOrGarbageCollectionTimer(ReduceFn.Co WindowTracing.trace( "ReduceFnRunner.scheduleEndOfWindowOrGarbageCollectionTimer: Scheduling {} timer at {} for " + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", - which, fireTime, key, context.window(), inputWM, + which, fireTime, key, directContext.window(), inputWM, timerInternals.currentOutputWatermarkTime()); - context.timers().setTimer(fireTime, TimeDomain.EVENT_TIME); + directContext.timers().setTimer(fireTime, TimeDomain.EVENT_TIME); } private void cancelEndOfWindowAndGarbageCollectionTimers(ReduceFn.Context context) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java index 95bf94dfb2..f66d6863b9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.util; -import com.google.cloud.dataflow.sdk.util.state.MergeableState; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateTag; @@ -29,15 +28,4 @@ public interface StateContext { * this method must be eagerly combined and written into the result window. */ StateT access(StateTag address); - - /** - * Access the storage for the given {@code address} in all of the windows that were - * merged into the current window. - * - *

    If no windows were merged, this reads and writes to just the current window. - * Otherwise, when windows merge we do not eagerly combine state, but rather defer the - * combination to reading time. Thus reads will be from all 'merged windows' for the - * current window, and writes will be to the designated 'writing window' for the current window. - */ - > StateT accessAcrossMergedWindows(StateTag address); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java index 5b6fa784e6..5d6101aedf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java @@ -24,8 +24,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.state.BagState; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; -import com.google.cloud.dataflow.sdk.util.state.MergeableState; +import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -39,9 +40,8 @@ * @param The output type that will be produced for each key. * @param The type of windows this operates on. */ -public class SystemReduceFn +public abstract class SystemReduceFn extends ReduceFn { - private static final String BUFFER_NAME = "buf"; /** @@ -65,10 +65,19 @@ public static Factory, W> buff final StateTag> bufferTag = StateTags.makeSystemTagInternal(StateTags.bag(BUFFER_NAME, inputCoder)); return new Factory, W>() { - @Override public ReduceFn, W> create(K key) { - return new SystemReduceFn, W>(bufferTag); + return new SystemReduceFn, Iterable, W>(bufferTag) { + @Override + public void prefetchOnMerge(MergingStateContext state) throws Exception { + StateMerging.prefetchBags(state, bufferTag); + } + + @Override + public void onMerge(OnMergeContext c) throws Exception { + StateMerging.mergeBags(c.state(), bufferTag); + } + }; } }; } @@ -77,63 +86,63 @@ public ReduceFn, W> create(K key) { * Create a factory that produces {@link SystemReduceFn} instances that combine all of the input * values using a {@link CombineFn}. */ - public static - Factory combining( - final Coder keyCoder, final AppliedCombineFn combineFn) { + public static Factory + combining( + final Coder keyCoder, final AppliedCombineFn combineFn) { checkArgument( !(combineFn.getFn() instanceof RequiresContextInternal), "Combiner lifting is not supported for combine functions with contexts: %s", combineFn.getFn().getClass().getName()); return new Factory() { - @Override public ReduceFn create(K key) { - StateTag> bufferTag = + final StateTag> bufferTag = StateTags.makeSystemTagInternal(StateTags.combiningValue( BUFFER_NAME, combineFn.getAccumulatorCoder(), (CombineFn) combineFn.getFn().forKey(key, keyCoder))); - return new SystemReduceFn(bufferTag); + return new SystemReduceFn(bufferTag) { + @Override + public void prefetchOnMerge(MergingStateContext state) throws Exception { + StateMerging.prefetchCombiningValues(state, bufferTag); + } + + @Override + public void onMerge(OnMergeContext c) throws Exception { + StateMerging.mergeCombiningValues(c.state(), bufferTag); + } + }; } }; } - private StateTag> bufferTag; + private StateTag> bufferTag; - public SystemReduceFn(StateTag> bufferTag) { + public SystemReduceFn(StateTag> bufferTag) { this.bufferTag = bufferTag; } @Override public void processValue(ProcessValueContext c) throws Exception { - c.state().accessAcrossMergedWindows(bufferTag).add(c.value()); - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - // All of the state used by SystemReduceFn is mergeable. Rather than eagerly reading it in - // to perform the merge here, we wait until the output is desired, and combine the values - // from all the source windows at that point. + c.state().access(bufferTag).add(c.value()); } @Override public void prefetchOnTrigger(StateContext c) { - c.accessAcrossMergedWindows(bufferTag).get(); + c.access(bufferTag).get(); } @Override public void onTrigger(OnTriggerContext c) throws Exception { - c.output(c.state().accessAcrossMergedWindows(bufferTag).get().read()); + c.output(c.state().access(bufferTag).get().read()); } @Override public void clearState(Context c) throws Exception { - c.state().accessAcrossMergedWindows(bufferTag).clear(); + c.state().access(bufferTag).clear(); } @Override public StateContents isEmpty(StateContext state) { - // Since we only check for empty element sets when a trigger fires it's unreasonable - // to require a prefetch. - return state.accessAcrossMergedWindows(bufferTag).isEmpty(); + return state.access(bufferTag).isEmpty(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 61c064a10f..1b204818e3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -20,7 +20,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergingTriggerInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerInfo; -import com.google.cloud.dataflow.sdk.util.state.MergeableState; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; @@ -34,9 +33,7 @@ import org.joda.time.Instant; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import java.util.Map; import javax.annotation.Nullable; @@ -51,6 +48,8 @@ public class TriggerContextFactory { private final WindowingStrategy windowingStrategy; private StateInternals stateInternals; + // Future triggers may be able to exploit the active window to state address window mapping. + @SuppressWarnings("unused") private ActiveWindowSet activeWindows; private final Coder windowCoder; @@ -71,26 +70,22 @@ public Trigger.TriggerContext base(W window, Timers timers, public Trigger.OnElementContext createOnElementContext( W window, Timers timers, Instant elementTimestamp, ExecutableTrigger rootTrigger, FinishedTriggers finishedSet) { - return new OnElementContextImpl( - window, timers, rootTrigger, finishedSet, - elementTimestamp); + return new OnElementContextImpl(window, timers, rootTrigger, finishedSet, elementTimestamp); } - public Trigger.OnMergeContext createOnMergeContext( - W window, Timers timers, Collection mergingWindows, + public Trigger.OnMergeContext createOnMergeContext(W window, Timers timers, ExecutableTrigger rootTrigger, FinishedTriggers finishedSet, Map finishedSets) { - return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, - mergingWindows, finishedSets); + return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, finishedSets); } - public StateContext createStateContext(W window, ExecutableTrigger trigger) { + public StateContext createStateContext(W window, ExecutableTrigger trigger) { return new StateContextImpl(window, trigger); } - public MergingStateContext createMergingStateContext( - W window, Collection mergingWindows, ExecutableTrigger trigger) { - return new MergingStateContextImpl(new StateContextImpl(window, trigger), mergingWindows); + public MergingStateContext createMergingStateContext(ExecutableTrigger trigger, + Collection mergingWindows, W mergeResult) { + return new MergingStateContextImpl(trigger, mergingWindows, mergeResult); } private class TriggerInfoImpl implements Trigger.TriggerInfo { @@ -265,80 +260,46 @@ public boolean apply(FinishedTriggers finishedSet) { } private class StateContextImpl implements StateContext { - - private final int triggerIndex; - private final StateNamespace namespace; - private final W window; + protected final int triggerIndex; + protected final StateNamespace windowNamespace; public StateContextImpl( W window, ExecutableTrigger trigger) { - this.window = window; this.triggerIndex = trigger.getTriggerIndex(); - - // Must be called after setting windowCoder, window, and triggerIndex - this.namespace = namespaceFor(window); + this.windowNamespace = namespaceFor(window); } - private StateNamespace namespaceFor(W window) { + protected StateNamespace namespaceFor(W window) { return StateNamespaces.windowAndTrigger(windowCoder, window, triggerIndex); } @Override public StateT access(StateTag address) { - return stateInternals.state(namespace, address); - } - - @Override - public > StateT accessAcrossMergedWindows( - StateTag address) { - List readNamespaces = new ArrayList<>(); - for (W readWindow : activeWindows.readStateAddresses(window)) { - readNamespaces.add(namespaceFor(readWindow)); - } - StateNamespace writeNamespace = namespaceFor(activeWindows.writeStateAddress(window)); - return stateInternals.mergedState(readNamespaces, writeNamespace, address, window); + return stateInternals.state(windowNamespace, address); } } - private class MergingStateContextImpl implements MergingStateContext { - - private final StateContextImpl delegate; - private final Collection mergingWindows; + private class MergingStateContextImpl extends StateContextImpl implements MergingStateContext { + private final Collection activeToBeMerged; - public MergingStateContextImpl(StateContextImpl delegate, Collection mergingWindows) { - this.delegate = delegate; - this.mergingWindows = mergingWindows; + public MergingStateContextImpl(ExecutableTrigger trigger, Collection activeToBeMerged, + W mergeResult) { + super(mergeResult, trigger); + this.activeToBeMerged = activeToBeMerged; } @Override public StorageT access(StateTag address) { - return delegate.access(address); + return stateInternals.state(windowNamespace, address); } @Override - public > StorageT accessAcrossMergedWindows( - StateTag address) { - return delegate.accessAcrossMergedWindows(address); - } - - @Override - public > StateT mergingAccess(StateTag address) { - List readNamespaces = new ArrayList<>(); - for (W mergingWindow : mergingWindows) { - readNamespaces.add(delegate.namespaceFor(mergingWindow)); - } - return stateInternals.mergedState( - readNamespaces, delegate.namespace, address, delegate.window); - } - - @Override - public Map mergingAccessInEachMergingWindow( + public Map accessInEachMergingWindow( StateTag address) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (W mergingWindow : mergingWindows) { - StateT stateForWindow = stateInternals.state( - delegate.namespaceFor(mergingWindow), address); + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (W mergingWindow : activeToBeMerged) { + StateT stateForWindow = stateInternals.state(namespaceFor(mergingWindow), address); builder.put(mergingWindow, stateForWindow); } return builder.build(); @@ -486,8 +447,7 @@ public Instant currentEventTime() { } private class OnMergeContextImpl extends Trigger.OnMergeContext { - - private final MergingStateContext state; + private final MergingStateContext state; private final W window; private final Collection mergingWindows; private final Timers timers; @@ -498,13 +458,11 @@ private OnMergeContextImpl( Timers timers, ExecutableTrigger trigger, FinishedTriggers finishedSet, - Collection mergingWindows, Map finishedSets) { trigger.getSpec().super(); - this.mergingWindows = mergingWindows; + this.mergingWindows = finishedSets.keySet(); this.window = window; - this.state = - new MergingStateContextImpl(new StateContextImpl(window, trigger), mergingWindows); + this.state = new MergingStateContextImpl(trigger, mergingWindows, window); this.timers = new TriggerTimers(window, timers); this.triggerInfo = new MergingTriggerInfoImpl(trigger, finishedSet, this, finishedSets); } @@ -512,17 +470,11 @@ private OnMergeContextImpl( @Override public Trigger.OnMergeContext forTrigger(ExecutableTrigger trigger) { return new OnMergeContextImpl( - window, timers, trigger, triggerInfo.finishedSet, - mergingWindows, triggerInfo.finishedSets); - } - - @Override - public Iterable oldWindows() { - return mergingWindows; + window, timers, trigger, triggerInfo.finishedSet, triggerInfo.finishedSets); } @Override - public MergingStateContext state() { + public MergingStateContext state() { return state; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index a8a61cfaf5..cb6b5d5a4f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -26,7 +26,6 @@ import com.google.common.collect.ImmutableMap; import java.util.BitSet; -import java.util.Collection; import java.util.Map; /** @@ -109,10 +108,9 @@ public void processValue(ReduceFn.ProcessValueContext c) throws Exce persistFinishedSet(c.state(), finishedSet); } - public void prefetchForMerge(W window, Collection mergingWindows, MergingStateContext state) { + public void prefetchForMerge(MergingStateContext state) { if (isFinishedSetNeeded()) { - for (ValueState value : - state.mergingAccessInEachMergingWindow(FINISHED_BITS_TAG).values()) { + for (ValueState value : state.accessInEachMergingWindow(FINISHED_BITS_TAG).values()) { value.get(); } } @@ -128,22 +126,24 @@ public void onMerge(ReduceFn.OnMergeContext c) throws Exception { readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); // And read the finished bits in each merging window. - ImmutableMap.Builder mergingFinishedSets = ImmutableMap.builder(); - Map> mergingFinishedSetState = - c.state().mergingAccessInEachMergingWindow(FINISHED_BITS_TAG); - for (W window : c.mergingWindows()) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (Map.Entry> entry : + c.state().accessInEachMergingWindow(FINISHED_BITS_TAG).entrySet()) { // Don't need to clone these, since the trigger context doesn't allow modification - mergingFinishedSets.put(window, readFinishedBits(mergingFinishedSetState.get(window))); + builder.put(entry.getKey(), readFinishedBits(entry.getValue())); } + ImmutableMap mergingFinishedSets = builder.build(); Trigger.OnMergeContext mergeContext = contextFactory.createOnMergeContext( - c.window(), c.timers(), c.mergingWindows(), rootTrigger, - finishedSet, mergingFinishedSets.build()); + c.window(), c.timers(), rootTrigger, finishedSet, mergingFinishedSets); // Run the merge from the trigger rootTrigger.invokeOnMerge(mergeContext); persistFinishedSet(c.state(), finishedSet); + + // Clear the finished bits. + clearFinished(c); } public boolean shouldFire(ReduceFn.Context c) throws Exception { @@ -162,8 +162,7 @@ public void onFire(ReduceFn.Context c) throws Exception { persistFinishedSet(c.state(), finishedSet); } - private void persistFinishedSet( - StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { + private void persistFinishedSet(StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { if (!isFinishedSetNeeded()) { return; } @@ -178,6 +177,15 @@ private void persistFinishedSet( } } + /** + * Clear finished bits. + */ + public void clearFinished(ReduceFn.Context c) { + if (isFinishedSetNeeded()) { + c.state().access(FINISHED_BITS_TAG).clear(); + } + } + /** * Clear the state used for executing triggers, but leave the finished set to indicate * the window is closed. @@ -185,19 +193,7 @@ private void persistFinishedSet( public void clearState(ReduceFn.Context c) throws Exception { // Don't need to clone, because we'll be clearing the finished bits anyways. FinishedTriggers finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)); - rootTrigger.invokeClear(contextFactory.base( - c.window(), c.timers(), rootTrigger, finishedSet)); - } - - /** - * Clear all the state for executing triggers, including the finished bits. This should only be - * called after the allowed lateness has elapsed, so that the window will never be recreated. - */ - public void clearEverything(ReduceFn.Context c) throws Exception { - clearState(c); - if (isFinishedSetNeeded()) { - c.state().access(FINISHED_BITS_TAG).clear(); - } + rootTrigger.invokeClear(contextFactory.base(c.window(), c.timers(), rootTrigger, finishedSet)); } private boolean isFinishedSetNeeded() { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index 0c6413eacc..715857c5a8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.cloud.dataflow.sdk.util.state.WatermarkStateInternal; @@ -48,8 +49,8 @@ public class WatermarkHold implements Serializable { * Return tag for state containing the output watermark hold * used for elements. */ - public static StateTag watermarkHoldTagForOutputTimeFn( - OutputTimeFn outputTimeFn) { + public static StateTag> + watermarkHoldTagForOutputTimeFn(OutputTimeFn outputTimeFn) { return StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal("hold", outputTimeFn)); } @@ -57,16 +58,16 @@ public static StateTag watermarkHoldTagForOutputTimeFn( * Tag for state containing end-of-window and garbage collection output watermark holds. * (We can't piggy-back on the data hold state since the outputTimeFn may be * {@link OutputTimeFns#outputAtLatestInputTimestamp()}, in which case every pane will - * would take the end-of-window time as its element time. + * would take the end-of-window time as its element time.) */ @VisibleForTesting - public static final StateTag EXTRA_HOLD_TAG = + public static final StateTag> EXTRA_HOLD_TAG = StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal( "extra", OutputTimeFns.outputAtEarliestInputTimestamp())); private final TimerInternals timerInternals; private final WindowingStrategy windowingStrategy; - private final StateTag elementHoldTag; + private final StateTag> elementHoldTag; public WatermarkHold(TimerInternals timerInternals, WindowingStrategy windowingStrategy) { this.timerInternals = timerInternals; @@ -178,7 +179,7 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind */ public void addHolds(ReduceFn.ProcessValueContext context) { if (!addElementHold(context)) { - addEndOfWindowOrGarbageCollectionHolds(context, true); + addEndOfWindowOrGarbageCollectionHolds(context); } } @@ -220,7 +221,7 @@ private boolean addElementHold(ReduceFn.ProcessValueContext context) tooLate = true; } else { tooLate = false; - context.state().accessAcrossMergedWindows(elementHoldTag).add(elementHold); + context.state().access(elementHoldTag).add(elementHold); } WindowTracing.trace( "WatermarkHold.addHolds: element hold at {} is {} for " @@ -237,10 +238,9 @@ private boolean addElementHold(ReduceFn.ProcessValueContext context) *

    The end-of-window hold guarantees that an empty {@code ON_TIME} pane can be given * a timestamp which will not be considered beyond allowed lateness by any downstream computation. */ - private void addEndOfWindowOrGarbageCollectionHolds( - ReduceFn.Context context, boolean isActive) { - if (!addEndOfWindowHold(context, isActive)) { - addGarbageCollectionHold(context, isActive); + private void addEndOfWindowOrGarbageCollectionHolds(ReduceFn.Context context) { + if (!addEndOfWindowHold(context)) { + addGarbageCollectionHold(context); } } @@ -250,7 +250,7 @@ private void addEndOfWindowOrGarbageCollectionHolds( *

    The end-of-window hold guarantees that any empty {@code ON_TIME} pane can be given * a timestamp which will not be considered beyond allowed lateness by any downstream computation. */ - private boolean addEndOfWindowHold(ReduceFn.Context context, boolean isActive) { + private boolean addEndOfWindowHold(ReduceFn.Context context) { // Only add an end-of-window hold if we can be sure the end-of-window timer // has not yet fired. Otherwise we risk holding up the output watermark until // the garbage collection timer fires, which may be a very long time in the future. @@ -264,21 +264,13 @@ private boolean addEndOfWindowHold(ReduceFn.Context context, boolean tooLate = false; Preconditions.checkState(outputWM == null || !eowHold.isBefore(outputWM), "End-of-window hold %s cannot be before output watermark %s", eowHold, outputWM); - if (isActive) { - context.state().accessAcrossMergedWindows(EXTRA_HOLD_TAG).add(eowHold); - } else { - // The window is not currently ACTIVE, so we can't use accessAcrossMergedWindows - // to collect its state. Instead, store the holds under the window itself. The - // caller will be responsible for ensuring the active window set now considers this - // window ACTIVE. - context.state().access(EXTRA_HOLD_TAG).add(eowHold); - } + context.state().access(EXTRA_HOLD_TAG).add(eowHold); } WindowTracing.trace( - "WatermarkHold.addEndOfWindowHold: end-of-window hold for %s at {} is {} for " + "WatermarkHold.addEndOfWindowHold: end-of-window hold at {} is {} for " + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - isActive ? "active" : "inactive", eowHold, tooLate ? "too late" : "on-time", context.key(), - context.window(), inputWM, outputWM); + eowHold, tooLate ? "too late" : "on-time", context.key(), context.window(), inputWM, + outputWM); return !tooLate; } @@ -290,7 +282,7 @@ private boolean addEndOfWindowHold(ReduceFn.Context context, boolean * computation. If we are sure no empty final panes can be emitted then there's no need * for an additional hold. */ - private void addGarbageCollectionHold(ReduceFn.Context context, boolean isActive) { + private void addGarbageCollectionHold(ReduceFn.Context context) { // Only add a garbage collection hold if we are sure we need an empty final pane and // the window will be garbage collected after the end-of-window trigger. if (context.windowingStrategy().getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS @@ -299,44 +291,39 @@ private void addGarbageCollectionHold(ReduceFn.Context context, bool Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); WindowTracing.trace( - "WatermarkHold.addGarbageCollectionHold: garbage collection hold for %s at {} for " + "WatermarkHold.addGarbageCollectionHold: garbage collection at {} hold for " + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - isActive ? "active" : "inactive", gcHold, context.key(), context.window(), inputWM, - outputWM); + gcHold, context.key(), context.window(), inputWM, outputWM); Preconditions.checkState(inputWM == null || !gcHold.isBefore(inputWM), "Garbage collection hold %s cannot be before input watermark %s", gcHold, inputWM); - if (isActive) { - context.state().accessAcrossMergedWindows(EXTRA_HOLD_TAG).add(gcHold); - } else { - // See comment above for addEndOfWindowHold. - context.state().access(EXTRA_HOLD_TAG).add(gcHold); - } + context.state().access(EXTRA_HOLD_TAG).add(gcHold); } } + /** + * Prefetch watermark holds in preparation for merging. + */ + public void prefetchOnMerge(MergingStateContext state) { + StateMerging.prefetchWatermarks(state, elementHoldTag); + } + /** * Updates the watermark hold when windows merge if it is possible the merged value does * not equal all of the existing holds. For example, if the new window implies a later * watermark hold, then earlier holds may be released. - * - *

    Note that state may be left behind in merged windows. */ - public void onMerge(final ReduceFn.OnMergeContext context) { + public void onMerge(ReduceFn.OnMergeContext context) { WindowTracing.debug("onMerge: for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", context.key(), context.window(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - // If the output hold depends only on the window, then there may not be a hold in place - // for the new merged window, so add one. - if (windowingStrategy.getOutputTimeFn().dependsOnlyOnWindow()) { - Instant arbitraryTimestamp = new Instant(0); - context.state() - .accessAcrossMergedWindows(elementHoldTag) - .add(windowingStrategy.getOutputTimeFn().assignOutputTime( - arbitraryTimestamp, context.window())); - } - - context.state().accessAcrossMergedWindows(elementHoldTag).releaseExtraneousHolds(); - context.state().accessAcrossMergedWindows(EXTRA_HOLD_TAG).releaseExtraneousHolds(); + StateMerging.mergeWatermarks(context.state(), elementHoldTag, context.window()); + // If we had a cheap way to determine if we have an element hold then we could + // avoid adding an unnecessary end-of-window or garbage collection hold. + // Simply reading the above merged watermark would impose an additional read for the + // common case that the active window has just one undelying state address window and + // the hold depends on the min of the elemest timestamps. + StateMerging.clear(context.state(), EXTRA_HOLD_TAG); + addEndOfWindowOrGarbageCollectionHolds(context); } /** @@ -347,24 +334,19 @@ public void onMerge(final ReduceFn.OnMergeContext context) { * from the windowing strategy of this {@link WatermarkHold}, combined across all the non-late * elements in the current pane. If there is no such value the timestamp is the end * of the window. - * - *

    If {@code willStillBeActive} then any end-of-window or garbage collection holds will - * be reestablished in one of the target windows alread in use for this window. Otherwise, - * the holds will be placed in this window itself. */ - public StateContents extractAndRelease(final ReduceFn.Context context, - final boolean isFinal, final boolean willStillBeActive) { + public StateContents extractAndRelease( + final ReduceFn.Context context, final boolean isFinished) { WindowTracing.debug( "extractAndRelease: for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", context.key(), context.window(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - final WatermarkStateInternal elementHoldState = - context.state().accessAcrossMergedWindows(elementHoldTag); + final WatermarkStateInternal elementHoldState = context.state().access(elementHoldTag); // Since we only extract holds when a trigger fires it is unreasonable to expect // the state to be prefetched. final StateContents elementHoldFuture = elementHoldState.get(); - final WatermarkStateInternal extraHoldState = - context.state().accessAcrossMergedWindows(EXTRA_HOLD_TAG); + final WatermarkStateInternal extraHoldState = + context.state().access(EXTRA_HOLD_TAG); final StateContents extraHoldFuture = extraHoldState.get(); return new StateContents() { @Override @@ -399,8 +381,10 @@ public Instant read() { elementHoldState.clear(); extraHoldState.clear(); - if (!isFinal) { - addEndOfWindowOrGarbageCollectionHolds(context, willStillBeActive); + if (!isFinished) { + // Only need to leave behind an end-of-window or garbage collection hold + // if future elements will be processed. + addEndOfWindowOrGarbageCollectionHolds(context); } return hold; @@ -409,21 +393,14 @@ public Instant read() { } /** - * Clear any remaining holds. If {@code isActive} then we assume holds could be placed in any - * of the target windows for this window. Otherwise we assume only this window has any - * end-of-window or garbage collection holds. + * Clear any remaining holds. */ - public void clearHolds(ReduceFn.Context context, boolean isActive) { + public void clearHolds(ReduceFn.Context context) { WindowTracing.debug( - "WatermarkHold.clearHolds: For key:{}; %s window:{}; " - + "inputWatermark:{}; outputWatermark:{}", - context.key(), isActive ? "active" : "inactive", context.window(), - timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - if (isActive) { - context.state().accessAcrossMergedWindows(elementHoldTag).clear(); - context.state().accessAcrossMergedWindows(EXTRA_HOLD_TAG).clear(); - } else { - context.state().access(EXTRA_HOLD_TAG).clear(); - } + "WatermarkHold.clearHolds: For key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + context.key(), context.window(), timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + context.state().access(elementHoldTag).clear(); + context.state().access(EXTRA_HOLD_TAG).clear(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java index 7f1e8bc7ad..5e0eef6a55 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java @@ -20,5 +20,5 @@ * * @param The type of elements in the bag. */ -public interface BagState extends MergeableState> { +public interface BagState extends CombiningValueState> { } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueState.java index 67e8698a3e..ee1fcac1d8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueState.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueState.java @@ -24,5 +24,20 @@ * @param the type of values added to the state * @param the type of value extracted from the state */ -public interface CombiningValueState extends MergeableState { +public interface CombiningValueState extends State { + /** + * Add a value to the buffer. + */ + void add(InputT value); + + /** + * Return the {@link StateContents} object to use for accessing the contents of the buffer. + */ + StateContents get(); + + /** + * Return true if this state is empty. + */ + StateContents isEmpty(); + } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java index 26df372a48..bba93b7869 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java @@ -38,4 +38,9 @@ public interface CombiningValueStateInternal * merge it with the previous accumulator, or may buffer this accumulator for a future merge. */ void addAccum(AccumT accum); + + /** + * Return the combiner function for this state. + */ + CombineFn getCombineFn(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 64341b9180..80e6ee992c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -37,7 +37,7 @@ * and for running tests that need state. */ @Experimental(Kind.STATE) -public class InMemoryStateInternals extends MergingStateInternals { +public class InMemoryStateInternals implements StateInternals { private interface InMemoryState { boolean isEmptyForTesting(); } @@ -65,10 +65,10 @@ public BagState bindBag(final StateTag> address, Coder ele } @Override - public WatermarkStateInternal bindWatermark( - StateTag address, + public WatermarkStateInternal bindWatermark( + StateTag> address, OutputTimeFn outputTimeFn) { - return new WatermarkStateInternalImplementation(outputTimeFn); + return new WatermarkStateInternalImplementation(outputTimeFn); } }; } @@ -125,15 +125,15 @@ public boolean isEmptyForTesting() { } } - private final class WatermarkStateInternalImplementation - implements WatermarkStateInternal, InMemoryState { + private final class WatermarkStateInternalImplementation + implements WatermarkStateInternal, InMemoryState { - private final OutputTimeFn outputTimeFn; + private final OutputTimeFn outputTimeFn; @Nullable private Instant combinedHold = null; - public WatermarkStateInternalImplementation(OutputTimeFn outputTimeFn) { + public WatermarkStateInternalImplementation(OutputTimeFn outputTimeFn) { this.outputTimeFn = outputTimeFn; } @@ -144,15 +144,6 @@ public void clear() { combinedHold = null; } - /** - * {@inheritDoc} - * - *

    Does nothing. There is only one hold and it is not extraneous. - * See {@link MergedWatermarkStateInternal} for a nontrivial implementation. - */ - @Override - public void releaseExtraneousHolds() { } - @Override public StateContents get() { return new StateContents() { @@ -184,6 +175,11 @@ public Boolean read() { }; } + @Override + public OutputTimeFn getOutputTimeFn() { + return outputTimeFn; + } + @Override public String toString() { return Objects.toString(combinedHold); @@ -251,6 +247,11 @@ public void addAccum(AccumT accum) { this.accum = combineFn.mergeAccumulators(Arrays.asList(this.accum, accum)); } + @Override + public CombineFn getCombineFn() { + return combineFn; + } + @Override public boolean isEmptyForTesting() { return isCleared; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergeableState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergeableState.java deleted file mode 100644 index ed81e9e55a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergeableState.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -/** - * {@code State} that is automatically mergeable and supports buffering values. - * - * @param The type of values put into the buffer. - * @param The type of values extracted from the buffer. - */ -public interface MergeableState extends State { - - /** - * Add a value to the buffer. - */ - void add(InputT value); - - /** - * Return the {@link StateContents} object to use for accessing the contents of the buffer. - */ - StateContents get(); - - /** - * Return true if this state is empty. - */ - StateContents isEmpty(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedBag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedBag.java deleted file mode 100644 index f39a681347..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedBag.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.common.collect.Iterables; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Implementation of {@link BagState} reads from all the sources and writes to the specified result. - * - * @param the type of elements in the bag - */ -class MergedBag implements BagState { - private final Collection> sources; - private final BagState result; - - public MergedBag(Collection> sources, BagState result) { - this.sources = sources; - this.result = result; - } - - @Override - public void clear() { - for (State source : sources) { - source.clear(); - } - result.clear(); - } - - @Override - public void add(T input) { - result.add(input); - } - - @Override - public StateContents> get() { - // Initiate the get's right away - final List>> futures = new ArrayList<>(sources.size()); - for (BagState source : sources) { - futures.add(source.get()); - } - - // But defer the actual reads until later. - return new StateContents>() { - @Override - public Iterable read() { - List> allIterables = new ArrayList<>(); - for (StateContents> future : futures) { - allIterables.add(future.read()); - } - return Iterables.concat(allIterables); - } - }; - } - - @Override - public StateContents isEmpty() { - // Initiate the get's right away - final List> futures = new ArrayList<>(sources.size()); - for (BagState source : sources) { - futures.add(source.isEmpty()); - } - - // But defer the actual reads until later. - return new StateContents() { - @Override - public Boolean read() { - for (StateContents future : futures) { - if (!future.read()) { - return false; - } - } - return true; - } - }; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedCombiningValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedCombiningValue.java deleted file mode 100644 index 56451a771e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedCombiningValue.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Base implementation of a {@link CombiningValueState} reading from multiple sources and writing to - * a single result. - * - * @param the type of values added to the state - * @param the type of accumulators that are actually stored - * @param the type of value extracted from the state - */ -class MergedCombiningValue - implements CombiningValueStateInternal { - - private final Collection> sources; - private final CombiningValueStateInternal result; - private final CombineFn combineFn; - - public MergedCombiningValue( - Collection> sources, - CombiningValueStateInternal result, - CombineFn combineFn) { - this.sources = sources; - this.result = result; - this.combineFn = combineFn; - } - - @Override - public void clear() { - for (State source : sources) { - source.clear(); - } - result.clear(); - } - - @Override - public StateContents get() { - final StateContents accum = getAccum(); - return new StateContents() { - @Override - public OutputT read() { - return combineFn.extractOutput(accum.read()); - } - }; - } - - @Override - public void add(InputT input) { - result.add(input); - } - - @Override - public void addAccum(AccumT accum) { - result.addAccum(accum); - } - - @Override - public StateContents getAccum() { - final List> futures = new ArrayList<>(sources.size()); - for (CombiningValueStateInternal source : sources) { - futures.add(source.getAccum()); - } - - return new StateContents() { - @Override - public AccumT read() { - List accumulators = new ArrayList<>(futures.size()); - for (StateContents future : futures) { - accumulators.add(future.read()); - } - - // Combine the accumualtors and compact the underyling state. - AccumT combined = combineFn.mergeAccumulators(accumulators); - clear(); - addAccum(combined); - - // This should be in memory. Since we may have mutated combined by - // incorporating it into the result, we re-read it from memory. - return result.getAccum().read(); - } - }; - } - - @Override - public StateContents isEmpty() { - // Initiate the get's right away - final List> futures = new ArrayList<>(sources.size()); - for (CombiningValueStateInternal source : sources) { - futures.add(source.isEmpty()); - } - - // But defer the actual reads until later. - return new StateContents() { - @Override - public Boolean read() { - for (StateContents future : futures) { - if (!future.read()) { - return false; - } - } - return true; - } - }; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedWatermarkStateInternal.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedWatermarkStateInternal.java deleted file mode 100644 index 7a1e416aaa..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergedWatermarkStateInternal.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Implementation of {@link WatermarkStateInternal} reading from multiple sources and writing to a - * single result. - */ -class MergedWatermarkStateInternal implements WatermarkStateInternal { - - private final Collection sources; - private final WatermarkStateInternal result; - private final OutputTimeFn outputTimeFn; - private final W resultWindow; - - public MergedWatermarkStateInternal( - Collection sources, - WatermarkStateInternal result, - W resultWindow, - OutputTimeFn outputTimeFn) { - this.sources = sources; - this.result = result; - this.resultWindow = resultWindow; - this.outputTimeFn = outputTimeFn; - } - - @Override - public void clear() { - for (State source : sources) { - source.clear(); - } - result.clear(); - } - - @Override - public void add(Instant outputTimestamp) { - result.add(outputTimestamp); - } - - @Override - public StateContents get() { - // Short circuit if output times depend only on the window, hence are all equal. - if (outputTimeFn.dependsOnlyOnWindow()) { - return result.get(); - } - - // Get the underlying StateContents's right away. - final List> reads = new ArrayList<>(sources.size()); - for (WatermarkStateInternal source : sources) { - reads.add(source.get()); - } - - // But defer actually reading them. - return new StateContents() { - @Override - public Instant read() { - List outputTimesToMerge = Lists.newArrayListWithCapacity(sources.size()); - for (StateContents read : reads) { - Instant sourceOutputTime = read.read(); - if (sourceOutputTime != null) { - outputTimesToMerge.add(sourceOutputTime); - } - } - - if (outputTimesToMerge.isEmpty()) { - return null; - } else { - // Also, compact the state - clear(); - Instant mergedOutputTime = outputTimeFn.merge(resultWindow, outputTimesToMerge); - add(mergedOutputTime); - return mergedOutputTime; - } - } - }; - } - - @Override - public StateContents isEmpty() { - // Initiate the get's right away - final List> futures = new ArrayList<>(sources.size()); - for (WatermarkStateInternal source : sources) { - futures.add(source.isEmpty()); - } - - // But defer the actual reads until later. - return new StateContents() { - @Override - public Boolean read() { - for (StateContents future : futures) { - if (!future.read()) { - return false; - } - } - return true; - } - }; - } - - @Override - public void releaseExtraneousHolds() { - if (outputTimeFn.dependsOnlyOnEarliestInputTimestamp()) { - // The backend is implicitly already holding the output watermark to - // the minimum of all holds in all merged windows. Therefore, we don't need to - // explicitly change it. - // When the final (post merged) session window fires, we will collect all holds - // over all intermediate (pre merged) windows, take their min, and clear them. - // Therefore we also don't need to garbage collect any state here. - } else { - // The output time function may be able to move the hold forward. get() implements - // the necessary combining logic, and as a side effect will compact the hold - // in Windmill state. This ensures Windmill's output watermark can progress, and - // there is no stale hold left behind. - get().read(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateInternals.java deleted file mode 100644 index f47c9ddbcf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateInternals.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; - -import java.util.ArrayList; -import java.util.List; - -/** - * Abstract implementation of {@link StateInternals} that provides {@link #mergedState} in terms of - * {@link #state}. - */ -@Experimental(Kind.STATE) -public abstract class MergingStateInternals implements StateInternals { - - @Override - public > T mergedState( - final Iterable sourceNamespaces, - final StateNamespace resultNamespace, - StateTag address, - final BoundedWindow resultWindow) { - return address.bind(new StateBinder() { - @Override - public ValueState bindValue(StateTag> address, Coder coder) { - throw new IllegalStateException( - "Value is not mergable. Should not be passed to mergedState"); - } - - @Override - public BagState bindBag(StateTag> address, Coder elemCoder) { - List> sources = new ArrayList<>(); - for (StateNamespace sourceNamespace : sourceNamespaces) { - sources.add(state(sourceNamespace, address)); - } - - BagState results = state(resultNamespace, address); - return new MergedBag<>(sources, results); - } - - @Override - public - CombiningValueStateInternal bindCombiningValue( - StateTag> address, - Coder accumCoder, CombineFn combineFn) { - List> sources = new ArrayList<>(); - for (StateNamespace sourceNamespace : sourceNamespaces) { - sources.add(state(sourceNamespace, address)); - } - CombiningValueStateInternal result = - state(resultNamespace, address); - return new MergedCombiningValue<>(sources, result, combineFn); - } - - @Override - public WatermarkStateInternal bindWatermark( - StateTag address, - OutputTimeFn outputTimeFn) { - List sources = new ArrayList<>(); - for (StateNamespace sourceNamespace : sourceNamespaces) { - sources.add(state(sourceNamespace, address)); - } - WatermarkStateInternal result = state(resultNamespace, address); - - // It is the responsibility of the SDK to only pass allowed result windows. - @SuppressWarnings("unchecked") - W typedResultWindow = (W) resultWindow; - - return new MergedWatermarkStateInternal( - sources, result, typedResultWindow, outputTimeFn); - } - }); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java index f8038823b7..5f4dc6372f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java @@ -18,7 +18,6 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; /** * {@code StateInternals} describes the functionality a runner needs to provide for the @@ -43,19 +42,4 @@ public interface StateInternals { * Return the state associated with {@code address} in the specified {@code namespace}. */ T state(StateNamespace namespace, StateTag address); - - /** - * Return state that reads from all the source namespaces. Only required to ensure that - * resultNamespace contains all the data that is added. - * - *

    Merging state is potentially destructive, in that it may move information from the - * {@code sourceNamespaces} to {@code resultNamespace}. As a result, after calling this all - * future calls should include as their namespaces a superset of - * {@code sourceNamespaces} and {@code resultNamespace}. - */ - > T mergedState( - Iterable sourceNamespaces, - StateNamespace resultNamespace, - StateTag address, - BoundedWindow resultWindow); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java new file mode 100644 index 0000000000..858091983d --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java @@ -0,0 +1,251 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.state; + +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.MergingStateContext; +import com.google.common.base.Preconditions; + +import org.joda.time.Instant; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * Helpers for merging state. + */ +public class StateMerging { + /** + * Clear all state in {@code address} in all windows under merge (even result windows) + * in {@code context}. + */ + public static void clear( + MergingStateContext context, StateTag address) { + for (StateT state : context.accessInEachMergingWindow(address).values()) { + state.clear(); + } + } + + /** + * Prefetch all bag state in {@code address} across all windows under merge in + * {@code context}, except for the bag state in the final state address window which we can + * blindly append to. + */ + public static void prefetchBags( + MergingStateContext context, StateTag> address) { + Map> map = context.accessInEachMergingWindow(address); + if (map.isEmpty()) { + // Nothing to prefetch. + return; + } + BagState result = context.access(address); + // Prefetch everything except what's already in result. + for (BagState source : map.values()) { + if (!source.equals(result)) { + source.get(); + } + } + } + + /** + * Merge all bag state in {@code address} across all windows under merge. + */ + public static void mergeBags( + MergingStateContext context, StateTag> address) { + mergeBags(context.accessInEachMergingWindow(address).values(), context.access(address)); + } + + /** + * Merge all bag state in {@code sources} (which may include {@code result}) into {@code result}. + */ + public static void mergeBags( + Collection> sources, BagState result) { + if (sources.isEmpty()) { + // Nothing to merge. + return; + } + // Prefetch everything except what's already in result. + List>> futures = new ArrayList<>(sources.size()); + for (BagState source : sources) { + if (!source.equals(result)) { + futures.add(source.get()); + } + } + if (futures.isEmpty()) { + // Result already holds all the values. + return; + } + // Transfer from sources to result. + for (StateContents> future : futures) { + for (T element : future.read()) { + result.add(element); + } + } + // Clear sources except for result. + for (BagState source : sources) { + if (!source.equals(result)) { + source.clear(); + } + } + } + + /** + * Prefetch all combining value state for {@code address} across all merging windows in {@code + * context}. + */ + public static , W extends BoundedWindow> void + prefetchCombiningValues(MergingStateContext context, StateTag address) { + for (StateT state : context.accessInEachMergingWindow(address).values()) { + state.get(); + } + } + + /** + * Merge all value state in {@code address} across all merging windows in {@code context}. + */ + public static void mergeCombiningValues( + MergingStateContext context, + StateTag> address) { + mergeCombiningValues( + context.accessInEachMergingWindow(address).values(), context.access(address)); + } + + /** + * Merge all value state from {@code sources} (which may include {@code result}) into + * {@code result}. + */ + public static void mergeCombiningValues( + Collection> sources, + CombiningValueStateInternal result) { + if (sources.isEmpty()) { + // Nothing to merge. + return; + } + if (sources.size() == 1 && sources.contains(result)) { + // Result already holds combined value. + return; + } + // Prefetch. + List> futures = new ArrayList<>(sources.size()); + for (CombiningValueStateInternal source : sources) { + futures.add(source.getAccum()); + } + // Read. + List accumulators = new ArrayList<>(futures.size()); + for (StateContents future : futures) { + accumulators.add(future.read()); + } + // Merge (possibly update and return one of the existing accumulators). + AccumT merged = result.getCombineFn().mergeAccumulators(accumulators); + // Clear sources. + for (CombiningValueStateInternal source : sources) { + source.clear(); + } + // Update result. + result.addAccum(merged); + } + + /** + * Prefetch all watermark state for {@code address} across all merging windows in + * {@code context}. + */ + public static void prefetchWatermarks( + MergingStateContext context, StateTag> address) { + Map> map = context.accessInEachMergingWindow(address); + WatermarkStateInternal result = context.access(address); + if (map.isEmpty()) { + // Nothing to prefetch. + return; + } + if (map.size() == 1 && map.values().contains(result) + && result.getOutputTimeFn().dependsOnlyOnEarliestInputTimestamp()) { + // Nothing to change. + return; + } + if (result.getOutputTimeFn().dependsOnlyOnWindow()) { + // No need to read existing holds. + return; + } + // Prefetch. + for (WatermarkStateInternal source : map.values()) { + source.get(); + } + } + + /** + * Merge all watermark state in {@code address} across all merging windows in {@code context}, + * where the final merge result window is {@code mergeResult}. + */ + public static void mergeWatermarks( + MergingStateContext context, StateTag> address, + W mergeResult) { + mergeWatermarks( + context.accessInEachMergingWindow(address).values(), context.access(address), mergeResult); + } + + /** + * Merge all watermark state in {@code sources} (which must include {@code result} if non-empty) + * into {@code result}, where the final merge result window is {@code mergeResult}. + */ + public static void mergeWatermarks( + Collection> sources, WatermarkStateInternal result, + W resultWindow) { + if (sources.isEmpty()) { + // Nothing to merge. + return; + } + if (sources.size() == 1 && sources.contains(result) + && result.getOutputTimeFn().dependsOnlyOnEarliestInputTimestamp()) { + // Nothing to merge. + return; + } + if (result.getOutputTimeFn().dependsOnlyOnWindow()) { + // Clear sources. + for (WatermarkStateInternal source : sources) { + source.clear(); + } + // Update directly from window-derived hold. + Instant hold = result.getOutputTimeFn().assignOutputTime( + BoundedWindow.TIMESTAMP_MIN_VALUE, resultWindow); + Preconditions.checkState(hold.isAfter(BoundedWindow.TIMESTAMP_MIN_VALUE)); + result.add(hold); + } else { + // Prefetch. + List> futures = new ArrayList<>(sources.size()); + for (WatermarkStateInternal source : sources) { + futures.add(source.get()); + } + // Read. + List outputTimesToMerge = new ArrayList<>(sources.size()); + for (StateContents future : futures) { + Instant sourceOutputTime = future.read(); + if (sourceOutputTime != null) { + outputTimesToMerge.add(sourceOutputTime); + } + } + // Clear sources. + for (WatermarkStateInternal source : sources) { + source.clear(); + } + if (!outputTimesToMerge.isEmpty()) { + // Merge and update. + result.add(result.getOutputTimeFn().merge(resultWindow, outputTimesToMerge)); + } + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java index be114f893f..d221543309 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java @@ -59,8 +59,8 @@ public interface StateBinder { *

    This accepts the {@link OutputTimeFn} that dictates how watermark hold timestamps * added to the returned {@link WatermarkStateInternal} are to be combined. */ - WatermarkStateInternal bindWatermark( - StateTag address, + WatermarkStateInternal bindWatermark( + StateTag> address, OutputTimeFn outputTimeFn); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index 4ad50df242..89e2013431 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -64,8 +64,9 @@ public static StateTag> value(String id, Coder valueCoder) * Create a state tag for values that use a {@link CombineFn} to automatically merge * multiple {@code InputT}s into a single {@code OutputT}. */ - public static StateTag> - combiningValue( + public static + StateTag> + combiningValue( String id, Coder accumCoder, CombineFn combineFn) { return combiningValueInternal(id, accumCoder, combineFn); } @@ -77,8 +78,9 @@ public static StateTag> value(String id, Coder valueCoder) *

    This determines the {@code Coder} from the given {@code Coder}, and * should only be used to initialize static values. */ - public static StateTag> - combiningValueFromInputInternal( + public static StateTag> + combiningValueFromInputInternal( String id, Coder inputCoder, CombineFn combineFn) { try { Coder accumCoder = combineFn.getAccumulatorCoder(STANDARD_REGISTRY, inputCoder); @@ -90,19 +92,13 @@ public static StateTag> value(String id, Coder valueCoder) } } - private static StateTag> - combiningValueInternal( + private static StateTag> + combiningValueInternal( String id, Coder accumCoder, CombineFn combineFn) { - StateTag> internal = + return new CombiningValueStateTag( new StructuredId(id), accumCoder, combineFn); - - // This is a safe cast, since StateTag only supports reading, and - // CombiningValue is a super-interface of - // CombiningValueInternal - @SuppressWarnings({"unchecked", "rawtypes"}) - StateTag> external = (StateTag) internal; - return external; } /** @@ -116,8 +112,8 @@ public static StateTag> bag(String id, Coder elemCoder) { /** * Create a state tag for holding the watermark. */ - public static StateTag - watermarkStateInternal(String id, OutputTimeFn outputTimeFn) { + public static StateTag> + watermarkStateInternal(String id, OutputTimeFn outputTimeFn) { return new WatermarkStateTagInternal(new StructuredId(id), outputTimeFn); } @@ -138,7 +134,10 @@ public static StateTag> convertToBagT if (!(combiningTag instanceof CombiningValueStateTag)) { throw new IllegalArgumentException("Unexpected StateTag " + combiningTag); } - return ((CombiningValueStateTag) combiningTag).asBagTag(); + @SuppressWarnings("unchecked") + CombiningValueStateTag typedTag = + (CombiningValueStateTag) combiningTag; + return typedTag.asBagTag(); } private static class StructuredId implements Serializable { @@ -158,10 +157,6 @@ public StructuredId asKind(StateKind kind) { return new StructuredId(kind, rawId); } - public String getIdString() { - return kind.prefix + rawId; - } - public void appendTo(Appendable sb) throws IOException { sb.append(kind.prefix).append(rawId); } @@ -221,6 +216,7 @@ public String toString() { protected abstract StateTag asKind(StateKind kind); + @Override public void appendTo(Appendable sb) throws IOException { id.appendTo(sb); } @@ -375,7 +371,7 @@ protected StateTag> asKind(StateKind kind) { } private static class WatermarkStateTagInternal - extends StateTagBase { + extends StateTagBase> { /** * When multiple output times are added to hold the watermark, this determines how they are @@ -390,7 +386,7 @@ private WatermarkStateTagInternal(StructuredId id, OutputTimeFn outpu } @Override - public WatermarkStateInternal bind(StateBinder visitor) { + public WatermarkStateInternal bind(StateBinder visitor) { return visitor.bindWatermark(this, outputTimeFn); } @@ -414,7 +410,7 @@ public int hashCode() { } @Override - protected StateTag asKind(StateKind kind) { + protected StateTag> asKind(StateKind kind) { return new WatermarkStateTagInternal(id.asKind(kind), outputTimeFn); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java index d72c67e22c..f575dfc7f5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java @@ -25,6 +25,13 @@ */ @Experimental(Kind.STATE) public interface ValueState extends State { + /** + * Return the {@link StateContents} object to use for accessing the contents of the buffer. + */ StateContents get(); + + /** + * Set the value of the buffer. + */ void set(T input); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkStateInternal.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkStateInternal.java index 9521088185..19972aab2e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkStateInternal.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkStateInternal.java @@ -17,6 +17,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import org.joda.time.Instant; @@ -28,11 +29,11 @@ *

    For internal use only. This API may change at any time. */ @Experimental(Kind.STATE) -public interface WatermarkStateInternal extends MergeableState { - +public interface WatermarkStateInternal + extends CombiningValueState { /** - * Release all holds for windows which have been merged away and incorporate their - * combined values (according to {@link OutputTimeFn#merge}) into the result window hold. + * Return the {@link OutputTimeFn} which will be used to determine a watermark hold time given + * an element timestamp, and to combine watermarks from windows which are about to be merged. */ - void releaseExtraneousHolds(); + OutputTimeFn getOutputTimeFn(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index c2220051d0..2088ac3c34 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -373,7 +373,7 @@ public Instant earliestWatermarkHold() { Instant minimum = null; for (State storage : inMemoryState.values()) { if (storage instanceof WatermarkStateInternal) { - Instant hold = ((WatermarkStateInternal) storage).get().read(); + Instant hold = ((WatermarkStateInternal) storage).get().read(); if (minimum == null || (hold != null && hold.isBefore(minimum))) { minimum = hold; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index 4fdd2d305a..ea631cfba0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -309,30 +309,26 @@ public void setSubTriggerFinishedForWindow(int subTriggerIndex, W window, boolea * since it is just to test the trigger's {@code OnMerge} method. */ public final void mergeWindows() throws Exception { - final Map> windowToComponents = new HashMap<>(); - activeWindows.merge(new MergeCallback() { + @Override + public void prefetchOnMerge(Collection toBeMerged, Collection activeToBeMerged, + W mergeResult) throws Exception {} + @Override public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) throws Exception { - windowToComponents.put(mergeResult, toBeMerged); + Map mergingFinishedSets = + Maps.newHashMapWithExpectedSize(activeToBeMerged.size()); + for (W oldWindow : activeToBeMerged) { + mergingFinishedSets.put(oldWindow, getFinishedSet(oldWindow)); + } + executableTrigger.invokeOnMerge(contextFactory.createOnMergeContext(mergeResult, + new TestTimers(windowNamespace(mergeResult)), executableTrigger, + getFinishedSet(mergeResult), mergingFinishedSets)); timerInternals.setTimer(TimerData.of( windowNamespace(mergeResult), mergeResult.maxTimestamp(), TimeDomain.EVENT_TIME)); } }); - - for (Map.Entry> merged : windowToComponents.entrySet()) { - W window = merged.getKey(); - Collection oldWindows = merged.getValue(); - Map mergingFinishedSets = - Maps.newHashMapWithExpectedSize(oldWindows.size()); - for (W oldWindow : oldWindows) { - mergingFinishedSets.put(oldWindow, getFinishedSet(oldWindow)); - } - executableTrigger.invokeOnMerge( - contextFactory.createOnMergeContext(window, new TestTimers(windowNamespace(window)), - oldWindows, executableTrigger, getFinishedSet(window), mergingFinishedSets)); - } } private FinishedTriggers getFinishedSet(W window) { @@ -368,7 +364,8 @@ public Instant earliestWatermarkHold() { Instant minimum = null; for (State storage : inMemoryState.values()) { if (storage instanceof WatermarkStateInternal) { - Instant hold = ((WatermarkStateInternal) storage).get().read(); + @SuppressWarnings("unchecked") + Instant hold = ((WatermarkStateInternal) storage).get().read(); if (minimum == null || (hold != null && hold.isBefore(minimum))) { minimum = hold; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java index bf9c6f7bb8..ca4c785229 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java @@ -39,29 +39,24 @@ */ @RunWith(JUnit4.class) public class InMemoryStateInternalsTest { - private static final BoundedWindow WINDOW_1 = new IntervalWindow(new Instant(0), new Instant(10)); - private static final BoundedWindow WINDOW_3 = new IntervalWindow(new Instant(5), new Instant(20)); private static final StateNamespace NAMESPACE_1 = new StateNamespaceForTest("ns1"); private static final StateNamespace NAMESPACE_2 = new StateNamespaceForTest("ns2"); private static final StateNamespace NAMESPACE_3 = new StateNamespaceForTest("ns3"); private static final StateTag> STRING_VALUE_ADDR = StateTags.value("stringValue", StringUtf8Coder.of()); - private static final StateTag> SUM_INTEGER_ADDR = - StateTags.combiningValueFromInputInternal( + private static final StateTag> + SUM_INTEGER_ADDR = StateTags.combiningValueFromInputInternal( "sumInteger", VarIntCoder.of(), new Sum.SumIntegerFn()); private static final StateTag> STRING_BAG_ADDR = StateTags.bag("stringBag", StringUtf8Coder.of()); - private static final StateTag WATERMARK_EARLIEST_ADDR = - StateTags.watermarkStateInternal("watermark", - OutputTimeFns.outputAtEarliestInputTimestamp()); - private static final StateTag WATERMARK_LATEST_ADDR = - StateTags.watermarkStateInternal("watermark", - OutputTimeFns.outputAtLatestInputTimestamp()); - private static final StateTag WATERMARK_EOW_ADDR = - StateTags.watermarkStateInternal("watermark", - OutputTimeFns.outputAtEndOfWindow()); + private static final StateTag> WATERMARK_EARLIEST_ADDR = + StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); + private static final StateTag> WATERMARK_LATEST_ADDR = + StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtLatestInputTimestamp()); + private static final StateTag> WATERMARK_EOW_ADDR = + StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEndOfWindow()); InMemoryStateInternals underTest = new InMemoryStateInternals(); @@ -71,7 +66,8 @@ public void testValue() throws Exception { // State instances are cached, but depend on the namespace. assertThat(underTest.state(NAMESPACE_1, STRING_VALUE_ADDR), Matchers.sameInstance(value)); - assertThat(underTest.state(NAMESPACE_2, STRING_VALUE_ADDR), + assertThat( + underTest.state(NAMESPACE_2, STRING_VALUE_ADDR), Matchers.not(Matchers.sameInstance(value))); assertThat(value.get().read(), Matchers.nullValue()); @@ -131,42 +127,29 @@ public void testMergeBagIntoSource() throws Exception { bag2.add("World"); bag1.add("!"); - BagState merged = underTest.mergedState( - Arrays.asList(NAMESPACE_1, NAMESPACE_2), NAMESPACE_1, STRING_BAG_ADDR, WINDOW_1); + StateMerging.mergeBags(Arrays.asList(bag1, bag2), bag1); // Reading the merged bag gets both the contents - assertThat(merged.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!")); - - // Adding to the merged bag adds to namespace 1 - merged.add("..."); - assertThat(merged.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!", "...")); - assertThat(bag1.get().read(), Matchers.containsInAnyOrder("Hello", "!", "...")); - assertThat(bag2.get().read(), Matchers.not(Matchers.contains("..."))); + assertThat(bag1.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!")); + assertThat(bag2.get().read(), Matchers.emptyIterable()); } @Test public void testMergeBagIntoNewNamespace() throws Exception { BagState bag1 = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); BagState bag2 = underTest.state(NAMESPACE_2, STRING_BAG_ADDR); + BagState bag3 = underTest.state(NAMESPACE_3, STRING_BAG_ADDR); bag1.add("Hello"); bag2.add("World"); bag1.add("!"); - BagState merged = underTest.mergedState( - Arrays.asList(NAMESPACE_1, NAMESPACE_2, NAMESPACE_3), - NAMESPACE_3, STRING_BAG_ADDR, WINDOW_3); + StateMerging.mergeBags(Arrays.asList(bag1, bag2, bag3), bag3); // Reading the merged bag gets both the contents - assertThat(merged.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!")); - - // Adding to the merged bag adds to namespace 3 - merged.add("..."); - assertThat(merged.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!", "...")); - assertThat(bag1.get().read(), Matchers.not(Matchers.contains("..."))); - assertThat(bag2.get().read(), Matchers.not(Matchers.contains("..."))); - assertThat( - underTest.state(NAMESPACE_3, STRING_BAG_ADDR).get().read(), Matchers.contains("...")); + assertThat(bag3.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!")); + assertThat(bag1.get().read(), Matchers.emptyIterable()); + assertThat(bag2.get().read(), Matchers.emptyIterable()); } @Test @@ -206,8 +189,10 @@ public void testCombiningIsEmpty() throws Exception { @Test public void testMergeCombiningValueIntoSource() throws Exception { - CombiningValueState value1 = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - CombiningValueState value2 = underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); + CombiningValueStateInternal value1 = + underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); + CombiningValueStateInternal value2 = + underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); value1.add(5); value2.add(10); @@ -216,59 +201,38 @@ public void testMergeCombiningValueIntoSource() throws Exception { assertThat(value1.get().read(), Matchers.equalTo(11)); assertThat(value2.get().read(), Matchers.equalTo(10)); - CombiningValueState merged = underTest.mergedState( - Arrays.asList(NAMESPACE_1, NAMESPACE_2), NAMESPACE_1, SUM_INTEGER_ADDR, WINDOW_1); - - assertThat(value1.get().read(), Matchers.equalTo(11)); - assertThat(value2.get().read(), Matchers.equalTo(10)); - assertThat(merged.get().read(), Matchers.equalTo(21)); + // Merging clears the old values and updates the result value. + StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value1); - // Reading the merged value compressed the old values. assertThat(value1.get().read(), Matchers.equalTo(21)); assertThat(value2.get().read(), Matchers.equalTo(0)); - - merged.add(8); - assertThat(merged.get().read(), Matchers.equalTo(29)); - assertThat(value1.get().read(), Matchers.equalTo(29)); - assertThat(value2.get().read(), Matchers.equalTo(0)); } @Test public void testMergeCombiningValueIntoNewNamespace() throws Exception { - CombiningValueState value1 = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - CombiningValueState value2 = underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); + CombiningValueStateInternal value1 = + underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); + CombiningValueStateInternal value2 = + underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); + CombiningValueStateInternal value3 = + underTest.state(NAMESPACE_3, SUM_INTEGER_ADDR); value1.add(5); value2.add(10); value1.add(6); - assertThat(value1.get().read(), Matchers.equalTo(11)); - assertThat(value2.get().read(), Matchers.equalTo(10)); - - CombiningValueState merged = underTest.mergedState( - Arrays.asList(NAMESPACE_1, NAMESPACE_2, NAMESPACE_3), - NAMESPACE_3, SUM_INTEGER_ADDR, WINDOW_3); - - assertThat(value1.get().read(), Matchers.equalTo(11)); - assertThat(value2.get().read(), Matchers.equalTo(10)); - assertThat(merged.get().read(), Matchers.equalTo(21)); + StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value3); - // Reading the merged value compressed the old values. - CombiningValueState value3 = underTest.state(NAMESPACE_3, SUM_INTEGER_ADDR); + // Merging clears the old values and updates the result value. assertThat(value1.get().read(), Matchers.equalTo(0)); assertThat(value2.get().read(), Matchers.equalTo(0)); assertThat(value3.get().read(), Matchers.equalTo(21)); - - merged.add(8); - assertThat(merged.get().read(), Matchers.equalTo(29)); - assertThat(value1.get().read(), Matchers.equalTo(0)); - assertThat(value2.get().read(), Matchers.equalTo(0)); - assertThat(value3.get().read(), Matchers.equalTo(29)); } @Test public void testWatermarkEarliestState() throws Exception { - WatermarkStateInternal value = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); + WatermarkStateInternal value = + underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR)); @@ -295,7 +259,8 @@ public void testWatermarkEarliestState() throws Exception { @Test public void testWatermarkLatestState() throws Exception { - WatermarkStateInternal value = underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); + WatermarkStateInternal value = + underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR)); @@ -322,7 +287,7 @@ public void testWatermarkLatestState() throws Exception { @Test public void testWatermarkEndOfWindowState() throws Exception { - WatermarkStateInternal value = underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR); + WatermarkStateInternal value = underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR)); @@ -341,7 +306,8 @@ public void testWatermarkEndOfWindowState() throws Exception { @Test public void testWatermarkStateIsEmpty() throws Exception { - WatermarkStateInternal value = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); + WatermarkStateInternal value = + underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); StateContents readFuture = value.isEmpty(); @@ -354,54 +320,43 @@ public void testWatermarkStateIsEmpty() throws Exception { @Test public void testMergeEarliestWatermarkIntoSource() throws Exception { - WatermarkStateInternal value1 = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); - WatermarkStateInternal value2 = underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR); + WatermarkStateInternal value1 = + underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); + WatermarkStateInternal value2 = + underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR); value1.add(new Instant(3000)); value2.add(new Instant(5000)); value1.add(new Instant(4000)); value2.add(new Instant(2000)); - WatermarkStateInternal merged = underTest.mergedState( - Arrays.asList(NAMESPACE_1, NAMESPACE_2), NAMESPACE_1, WATERMARK_EARLIEST_ADDR, WINDOW_1); - - assertThat(value1.get().read(), Matchers.equalTo(new Instant(3000))); - assertThat(value2.get().read(), Matchers.equalTo(new Instant(2000))); - assertThat(merged.get().read(), Matchers.equalTo(new Instant(2000))); + // Merging clears the old values and updates the merged value. + StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value1, WINDOW_1); - // Reading the merged value compressed the old values assertThat(value1.get().read(), Matchers.equalTo(new Instant(2000))); assertThat(value2.get().read(), Matchers.equalTo(null)); - - merged.add(new Instant(1000)); - assertThat(merged.get().read(), Matchers.equalTo(new Instant(1000))); } @Test public void testMergeLatestWatermarkIntoSource() throws Exception { - WatermarkStateInternal value1 = underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); - WatermarkStateInternal value2 = underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR); + WatermarkStateInternal value1 = + underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); + WatermarkStateInternal value2 = + underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR); + WatermarkStateInternal value3 = + underTest.state(NAMESPACE_3, WATERMARK_LATEST_ADDR); value1.add(new Instant(3000)); value2.add(new Instant(5000)); value1.add(new Instant(4000)); value2.add(new Instant(2000)); - WatermarkStateInternal merged = underTest.mergedState( - Arrays.asList(NAMESPACE_1, NAMESPACE_2), NAMESPACE_1, WATERMARK_LATEST_ADDR, WINDOW_1); + // Merging clears the old values and updates the result value. + StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value3, WINDOW_1); - assertThat(value1.get().read(), Matchers.equalTo(new Instant(4000))); - assertThat(value2.get().read(), Matchers.equalTo(new Instant(5000))); - assertThat(merged.get().read(), Matchers.equalTo(new Instant(5000))); - - // Reading the merged value compressed the old values - assertThat(value1.get().read(), Matchers.equalTo(new Instant(5000))); + // Merging clears the old values and updates the result value. + assertThat(value3.get().read(), Matchers.equalTo(new Instant(5000))); + assertThat(value1.get().read(), Matchers.equalTo(null)); assertThat(value2.get().read(), Matchers.equalTo(null)); - - merged.add(new Instant(1000)); - assertThat(merged.get().read(), Matchers.equalTo(new Instant(5000))); - - merged.add(new Instant(7000)); - assertThat(merged.get().read(), Matchers.equalTo(new Instant(7000))); } } From 26f5dc4fd98c89af3062cc40dbcd82cb3d969cf4 Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 9 Feb 2016 13:25:22 -0800 Subject: [PATCH 110/751] Add the Ism side input reader This creates an Ism source aware side input reader which fronts the different PCollection view types for Google Cloud Dataflow when processing batch pipelines. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114252920 --- .../dataflow/sdk/util/PCollectionViews.java | 68 ++++++++++++------- 1 file changed, 42 insertions(+), 26 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java index e5308aa58a..7e735473c3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java @@ -41,6 +41,8 @@ import java.util.NoSuchElementException; import java.util.Objects; +import javax.annotation.Nullable; + /** * Implementations of {@link PCollectionView} shared across the SDK. * @@ -117,16 +119,18 @@ public static PCollectionView * *

    Instantiate via {@link PCollectionViews#singletonView}. */ - private static class SingletonPCollectionView + public static class SingletonPCollectionView extends PCollectionViewBase { - private byte[] encodedDefaultValue; - private transient T defaultValue; - private Coder valueCoder; + @Nullable private byte[] encodedDefaultValue; + @Nullable private transient T defaultValue; + @Nullable private Coder valueCoder; + private boolean hasDefault; - public SingletonPCollectionView( + private SingletonPCollectionView( Pipeline pipeline, WindowingStrategy windowingStrategy, boolean hasDefault, T defaultValue, Coder valueCoder) { super(pipeline, windowingStrategy, valueCoder); + this.hasDefault = hasDefault; this.defaultValue = defaultValue; this.valueCoder = valueCoder; if (hasDefault) { @@ -138,25 +142,37 @@ public SingletonPCollectionView( } } - @Override - protected T fromElements(Iterable> contents) { - if (encodedDefaultValue != null && defaultValue == null) { - try { - defaultValue = CoderUtils.decodeFromByteArray(valueCoder, encodedDefaultValue); - } catch (IOException e) { - throw new RuntimeException("Unexpected IOException: ", e); + /** + * Returns the default value that was specified. + * + *

    For internal use only. + * + * @throws NoSuchElementException if no default was specified. + */ + public T getDefaultValue() { + if (!hasDefault) { + throw new NoSuchElementException("Empty PCollection accessed as a singleton view."); + } + // Lazily decode the default value once + synchronized (this) { + if (encodedDefaultValue != null) { + try { + defaultValue = CoderUtils.decodeFromByteArray(valueCoder, encodedDefaultValue); + encodedDefaultValue = null; + } catch (IOException e) { + throw new RuntimeException("Unexpected IOException: ", e); + } } } + return defaultValue; + } + @Override + protected T fromElements(Iterable> contents) { try { return Iterables.getOnlyElement(contents).getValue(); } catch (NoSuchElementException exc) { - if (encodedDefaultValue != null) { - return defaultValue; - } else { - throw new NoSuchElementException( - "Empty PCollection accessed as a singleton view."); - } + return getDefaultValue(); } catch (IllegalArgumentException exc) { throw new IllegalArgumentException( "PCollection with more than one element " @@ -172,9 +188,9 @@ protected T fromElements(Iterable> contents) { * *

    Instantiate via {@link PCollectionViews#iterableView}. */ - private static class IterablePCollectionView + public static class IterablePCollectionView extends PCollectionViewBase, W> { - public IterablePCollectionView( + private IterablePCollectionView( Pipeline pipeline, WindowingStrategy windowingStrategy, Coder valueCoder) { super(pipeline, windowingStrategy, valueCoder); } @@ -199,9 +215,9 @@ public T apply(WindowedValue input) { * *

    Instantiate via {@link PCollectionViews#listView}. */ - private static class ListPCollectionView + public static class ListPCollectionView extends PCollectionViewBase, W> { - public ListPCollectionView( + private ListPCollectionView( Pipeline pipeline, WindowingStrategy windowingStrategy, Coder valueCoder) { super(pipeline, windowingStrategy, valueCoder); } @@ -225,9 +241,9 @@ public T apply(WindowedValue input) { * *

    For internal use only. */ - private static class MultimapPCollectionView + public static class MultimapPCollectionView extends PCollectionViewBase, Map>, W> { - public MultimapPCollectionView( + private MultimapPCollectionView( Pipeline pipeline, WindowingStrategy windowingStrategy, Coder> valueCoder) { @@ -254,9 +270,9 @@ protected Map> fromElements(Iterable>> ele * *

    For internal use only. */ - private static class MapPCollectionView + public static class MapPCollectionView extends PCollectionViewBase, Map, W> { - public MapPCollectionView( + private MapPCollectionView( Pipeline pipeline, WindowingStrategy windowingStrategy, Coder> valueCoder) { From c36a2e98e1a088571f542320d282a57a5dc26ff8 Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 9 Feb 2016 14:54:13 -0800 Subject: [PATCH 111/751] Move over various worker classes to worker maven module This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114262848 --- .../worker/CachingSideInputReader.java | 90 ------- .../sdk/runners/worker/DataflowApiUtils.java | 60 ----- .../worker/DataflowExecutionContext.java | 77 ------ .../worker/DataflowSideInputReader.java | 172 ------------ .../worker/KeyTokenInvalidException.java | 38 --- .../sdk/runners/worker/ReaderFactory.java | 48 ---- .../sdk/runners/worker/ShuffleLibrary.java | 48 ---- .../sdk/runners/worker/ShuffleWriter.java | 37 --- .../sdk/runners/worker/SideInputUtils.java | 253 ------------------ .../StreamingGroupAlsoByWindowsDoFn.java | 66 ----- ...eamingGroupAlsoByWindowsReshuffleDoFn.java | 53 ---- .../dataflow/sdk/runners/worker/Weighers.java | 48 ---- 12 files changed, 990 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowExecutionContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleWriter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/Weighers.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReader.java deleted file mode 100644 index afd77f0666..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CachingSideInputReader.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WeightedSideInputReader; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.cache.Cache; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; - -/** - * A {@link SideInputReader} that maintains a cache of side inputs per window. - * - *

    For internal use only. - * - *

    Package-private here so that the dependency on Guava does not leak into the public API - * surface. Note that Guava is "shaded" so the {@code Cache} class here is not actually compatible - * with a {@code Cache} created by anything other than the SDK. - */ -final class CachingSideInputReader - extends WeightedSideInputReader.Defaults - implements WeightedSideInputReader { - private final WeightedSideInputReader subReader; - private final Cache, WeightedValue> cache; - - private CachingSideInputReader(WeightedSideInputReader subReader, - Cache, WeightedValue> cache) { - this.subReader = subReader; - this.cache = cache; - } - - public static CachingSideInputReader of(WeightedSideInputReader subReader, - Cache, WeightedValue> cache) { - return new CachingSideInputReader(subReader, cache); - } - - @Override - public boolean contains(PCollectionView view) { - return subReader.contains(view); - } - - @Override - public boolean isEmpty() { - return subReader.isEmpty(); - } - - @Override - public WeightedValue getWeighted( - final PCollectionView view, final BoundedWindow window) { - PCollectionViewWindow cacheKey = PCollectionViewWindow.of(view, window); - - try { - @SuppressWarnings("unchecked") // safely uncasting the thing from the callback - WeightedValue sideInputContents = (WeightedValue) cache.get(cacheKey, - new Callable>() { - @Override - public WeightedValue call() { - @SuppressWarnings("unchecked") // safe covariant cast - WeightedValue value = - (WeightedValue) subReader.getWeighted(view, window); - return value; - } - }); - return sideInputContents; - } catch (ExecutionException checkedException) { - // The call to subReader.getWeighted() is not permitted to throw any checked exceptions, - // so the Callable created above should not throw any either. - throw new RuntimeException("Unexpected checked exception.", checkedException.getCause()); - } - } - } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java deleted file mode 100644 index 5c0d7d7da0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowApiUtils.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.client.json.GenericJson; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.JsonGenerator; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.common.io.ByteStreams; -import com.google.common.io.CountingOutputStream; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -/** - * A utility class for generic interactions with the Google Cloud Dataflow API. - */ -public final class DataflowApiUtils { - /** - * Determines the serialized size (in bytes) of the {@link GenericJson} object that will be - * serialized and sent to the Google Cloud Dataflow service API. - * - *

    Uses only constant memory. - */ - public static long computeSerializedSizeBytes(GenericJson object) throws IOException { - JsonFactory factory = object.getFactory(); - if (factory == null) { - factory = Transport.getJsonFactory(); - } - - CountingOutputStream stream = new CountingOutputStream(ByteStreams.nullOutputStream()); - JsonGenerator generator = null; - try { - generator = factory.createJsonGenerator(stream, StandardCharsets.UTF_8); - generator.serialize(object); - generator.close(); // also closes the stream. - } finally { - if (generator != null) { - generator.close(); - } - } - return stream.getCount(); - } - - // Prevent construction of utility class. - private DataflowApiUtils() {} -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowExecutionContext.java deleted file mode 100644 index da48470d61..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowExecutionContext.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.NullSideInputReader; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.Iterables; - -import javax.annotation.Nullable; - -/** - * Extensions to {@link BaseExecutionContext} specific to the Dataflow worker. - */ -public abstract class DataflowExecutionContext - extends BaseExecutionContext { - - /** - * Returns a {@link SideInputReader} based on {@link SideInputInfo} descriptors - * and {@link PCollectionView PCollectionViews}. - * - *

    If side input source metadata is provided by the service in - * {@link SideInputInfo sideInputInfos}, we request - * a {@link SideInputReader} from the {@code executionContext} using that info. - * If no side input source metadata is provided but the DoFn expects side inputs, as a - * fallback, we request a {@link SideInputReader} based only on the expected views. - * - *

    These cases are not disjoint: Whenever a {@link DoFn} takes side inputs, - * {@code doFnInfo.getSideInputViews()} should be non-empty. - * - *

    A note on the behavior of the Dataflow service: Today, the first case corresponds to - * batch mode, while the fallback corresponds to streaming mode. - */ - public SideInputReader getSideInputReader( - @Nullable Iterable sideInputInfos, - @Nullable Iterable> views) throws Exception { - if (sideInputInfos != null && sideInputInfos.iterator().hasNext()) { - return getSideInputReader(sideInputInfos); - } else if (views != null && Iterables.size(views) > 0) { - return getSideInputReaderForViews(views); - } else { - return NullSideInputReader.empty(); - } - } - - /** - * Returns a {@link SideInputReader} for all the side inputs described in the given - * {@link SideInputInfo} descriptors. - */ - protected abstract SideInputReader getSideInputReader( - Iterable sideInputInfos) throws Exception; - - /** - * Returns a {@link SideInputReader} for all the provided views, where the execution context - * itself knows how to read data for the view. - */ - protected abstract SideInputReader getSideInputReaderForViews( - Iterable> views) throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java deleted file mode 100644 index 109fc58da8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/DataflowSideInputReader.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PTuple; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WeightedSideInputReader; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -import java.util.HashMap; -import java.util.Map; -import java.util.Observable; -import java.util.Observer; - -/** - * A simple side input reader that re-reads a side input from its iterable each time it is - * requested. - * - *

    Sizes are accurate only for {@link PCollectionView} implementations that read the same - * amount of data for each access. - */ -public class DataflowSideInputReader - extends WeightedSideInputReader.Defaults - implements WeightedSideInputReader { - - /** An observer for each side input to count its size as it is being read. */ - private final Map, ByteSizeObserver> observers; - - /** A byte count saved as overhead per side input, not cleared when the observer is reset. */ - private final Map, Long> overheads; - - /** A list of TupleTags representing the side input values. */ - private final PTuple sideInputValues; - - private DataflowSideInputReader( - Iterable sideInputInfos, - ReaderFactory readerFactory, - PipelineOptions options, - ExecutionContext executionContext) throws Exception { - // Initializing the values may or may not actually read through the - // source. The full size is the amount read here plus the amount - // read when view.fromIterableInternal() is called. - this.observers = new HashMap<>(); - this.overheads = new HashMap<>(); - - PTuple sideInputValuesBeingBuilt = PTuple.empty(); - for (SideInputInfo sideInputInfo : sideInputInfos) { - TupleTag tag = new TupleTag<>(sideInputInfo.getTag()); - ByteSizeObserver observer = new ByteSizeObserver(); - Object sideInputValue = SideInputUtils.readSideInput( - options, sideInputInfo, readerFactory, observer, executionContext); - overheads.put(tag, observer.getBytes()); - observer.reset(); - observers.put(tag, observer); - sideInputValuesBeingBuilt = sideInputValuesBeingBuilt.and(tag, sideInputValue); - } - sideInputValues = sideInputValuesBeingBuilt; - } - - /** - * Creates a new {@link SideInputReader} that will provide side inputs - * according to the provided {@link SideInputInfo} descriptors. - */ - public static DataflowSideInputReader of( - Iterable sideInputInfos, - ReaderFactory readerFactory, - PipelineOptions options, - ExecutionContext context) - throws Exception { - return new DataflowSideInputReader(sideInputInfos, readerFactory, options, context); - } - - @Override - public boolean contains(PCollectionView view) { - return sideInputValues.has(view.getTagInternal()); - } - - @Override - public boolean isEmpty() { - return sideInputValues.isEmpty(); - } - - /** - * Gets a side input for a view and window by reading data according to the corresponding - * {@link SideInputInfo}, passing the result through the view's - * {@link PCollectionView#fromIterableInternal} conversion method, and extracting - * the value for the appropriate window. - */ - @Override - public WeightedValue getWeighted(PCollectionView view, final BoundedWindow window) { - final TupleTag>> tag = view.getTagInternal(); - if (!sideInputValues.has(tag)) { - throw new IllegalArgumentException("calling getSideInput() with unknown view"); - } - - // It is hard to estimate the size with any accuracy here, and there will be improvements - // possible, but it is only required to estimate in a way so that a cache will not OOM. - T value; - long overhead = overheads.get(tag); - final ByteSizeObserver observer = observers.get(tag); - if (view.getWindowingStrategyInternal().getWindowFn() instanceof GlobalWindows) { - value = view.fromIterableInternal(sideInputValues.get(tag)); - long bytesRead = observer.getBytes(); - observer.reset(); - return WeightedValue.of(value, overhead + bytesRead); - } else { - final long[] sum = new long[]{ 0L }; - value = view.fromIterableInternal( - Iterables.filter(sideInputValues.get(tag), - new Predicate>() { - @Override - public boolean apply(WindowedValue element) { - boolean containsWindow = element.getWindows().contains(window); - // Only sum up the size of the elements within the window. - if (containsWindow) { - sum[0] += observer.getBytes(); - } - observer.reset(); - return containsWindow; - } - })); - return WeightedValue.of(value, overhead + sum[0]); - } - } - - /** - * An observer for counting the bytes read and then resetting. - */ - private static class ByteSizeObserver implements Observer { - /** a byte count beyond overhead, cleared when the observer is reset. */ - private long byteCount = 0; - - @Override - public void update(Observable reader, Object obj) { - Preconditions.checkArgument(obj instanceof Long, "unexpected parameter object"); - byteCount = byteCount + (long) obj; - } - - public void reset() { - byteCount = 0; - } - - public long getBytes() { - return byteCount; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java deleted file mode 100644 index 096a50d356..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/KeyTokenInvalidException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -/** - * Indicates that the key token was invalid when data was attempted to be fetched. - */ -public class KeyTokenInvalidException extends RuntimeException { - public KeyTokenInvalidException(String key) { - super("Unable to fetch data due to token mismatch for key " + key); - } - - /** - * Returns whether an exception was caused by a {@link KeyTokenInvalidException}. - */ - public static boolean isKeyTokenInvalidException(Throwable t) { - while (t != null) { - if (t instanceof KeyTokenInvalidException) { - return true; - } - t = t.getCause(); - } - return false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java deleted file mode 100644 index f65858a2b5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import javax.annotation.Nullable; - -/** - * Creates a {@link NativeReader} from a Dataflow API source definition, presented as a - * {@link CloudObject}. - */ -public interface ReaderFactory { - - /** - * Creates a {@link NativeReader} from a Dataflow API source definition, presented as a - * {@link CloudObject}. - * - * @throws Exception if a {@link NativeReader} could not be created - */ - NativeReader create( - CloudObject cloudSourceSpec, - @Nullable Coder coder, - @Nullable PipelineOptions options, - @Nullable ExecutionContext executionContext, - @Nullable CounterSet.AddCounterMutator addCounterMutator, - @Nullable String operationName) - throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java deleted file mode 100644 index 999809b2f8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleLibrary.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; - -/** - * Native library used to read from and write to a shuffle dataset. - */ -class ShuffleLibrary { - /** - * Loads the native shuffle library. - */ - static void load() { - try { - final String shuffleClientLibraryPropertyKey = "batch.shuffle_client_library"; - String shuffleClientLibrary = "libshuffle_client_jni.so.stripped"; - if (System.getProperties().containsKey(shuffleClientLibraryPropertyKey)) { - shuffleClientLibrary = System.getProperty(shuffleClientLibraryPropertyKey); - } - File tempfile = File.createTempFile("libshuffle_client_jni", ".so"); - InputStream input = ClassLoader.getSystemResourceAsStream(shuffleClientLibrary); - Files.copy(input, tempfile.toPath(), StandardCopyOption.REPLACE_EXISTING); - System.load(tempfile.getAbsolutePath()); - } catch (IOException e) { - throw new RuntimeException("Loading shuffle_client failed:", e); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleWriter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleWriter.java deleted file mode 100644 index 386a2f10fe..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ShuffleWriter.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import java.io.IOException; - -/** - * ShuffleWriter writes chunks of records to a shuffle dataset. - */ -interface ShuffleWriter extends AutoCloseable { - /** - * Writes a chunk of records. The chunk is a sequence of pairs encoded as: - * - * where the sizes are 4-byte big-endian integers. - */ - public void write(byte[] chunk) throws IOException; - - /** - * Flushes written records and closes this writer. - */ - @Override - public void close() throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java deleted file mode 100644 index 8254bceba0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SideInputUtils.java +++ /dev/null @@ -1,253 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.getString; - -import com.google.api.services.dataflow.model.SideInputInfo; -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.common.collect.Iterables; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Observer; - -/** - * Utilities for working with side inputs. - */ -public class SideInputUtils { - static final String SINGLETON_KIND = "singleton"; - static final String COLLECTION_KIND = "collection"; - - /** - * Reads the given side input, producing the contents associated - * with a {@code PCollectionView}. - * - * @throws Exception anything thrown by the delegate {@link NativeReader} - * @see com.google.cloud.dataflow.sdk.values.PCollectionView - */ - public static Object readSideInput( - PipelineOptions options, - SideInputInfo sideInputInfo, - ReaderFactory readerFactory, - Observer observer, - ExecutionContext executionContext) - throws Exception { - Iterable elements = - readSideInputSources(options, sideInputInfo.getSources(), readerFactory, observer, - executionContext); - return readSideInputValue(sideInputInfo.getKind(), elements); - } - - public static Object readSideInput( - PipelineOptions options, - SideInputInfo sideInputInfo, - ReaderFactory readerFactory, - ExecutionContext executionContext) - throws Exception { - Iterable elements = readSideInputSources( - options, sideInputInfo.getSources(), readerFactory, null, executionContext); - return readSideInputValue(sideInputInfo.getKind(), elements); - } - - private static Iterable readSideInputSources( - PipelineOptions options, - List sideInputSources, - ReaderFactory readerFactory, - Observer observer, - ExecutionContext executionContext) - throws Exception { - int numSideInputSources = sideInputSources.size(); - if (numSideInputSources == 0) { - throw new Exception("expecting at least one side input Source"); - } else if (numSideInputSources == 1) { - return readSideInputSource( - options, sideInputSources.get(0), readerFactory, observer, executionContext); - } else { - List> shards = new ArrayList<>(); - for (Source sideInputSource : sideInputSources) { - shards.add(readSideInputSource( - options, sideInputSource, readerFactory, observer, executionContext)); - } - return Iterables.concat(shards); - } - } - - private static Iterable readSideInputSource( - PipelineOptions options, - Source sideInputSource, - ReaderFactory readerFactory, - Observer observer, - ExecutionContext executionContext) - throws Exception { - Coder coder = null; - if (sideInputSource.getCodec() != null) { - coder = Serializer.deserialize(sideInputSource.getCodec(), Coder.class); - } - // We don't do shuffle sanity check on side inputs, as they don't have to be read completely. - @SuppressWarnings("unchecked") - NativeReader reader = - (NativeReader) readerFactory.create(CloudObject.fromSpec(sideInputSource.getSpec()), - coder, options, executionContext, null, null); - if (observer != null) { - reader.addObserver(observer); - } - return new ReaderIterable<>(reader); - } - - static Object readSideInputValue(Map sideInputKind, Iterable elements) - throws Exception { - String className = getString(sideInputKind, PropertyNames.OBJECT_TYPE_NAME); - if (SINGLETON_KIND.equals(className)) { - Iterator iter = elements.iterator(); - if (iter.hasNext()) { - Object elem = iter.next(); - if (!iter.hasNext()) { - return elem; - } - } - throw new Exception("expecting a singleton side input to have a single value"); - - } else if (COLLECTION_KIND.equals(className)) { - return elements; - - } else { - throw new Exception("unexpected kind of side input: " + className); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - - static class ReaderIterable implements Iterable { - final NativeReader reader; - - public ReaderIterable(NativeReader reader) { - this.reader = reader; - } - - @Override - public Iterator iterator() { - try { - return new NativeReaderToIteratorAdapter<>(reader.iterator()); - } catch (Exception exn) { - throw new RuntimeException(exn); - } - } - } - - private static class NativeReaderToIteratorAdapter implements Iterator { - private enum NextState { - UNKNOWN_BEFORE_START, - UNKNOWN_BEFORE_ADVANCE, - AVAILABLE, - UNAVAILABLE - } - - private NativeReader.NativeReaderIterator reader; - private NextState state; - - /** - * Creates an iterator adapter for the given reader. - */ - private NativeReaderToIteratorAdapter(NativeReader.NativeReaderIterator reader) { - this.reader = reader; - this.state = NextState.UNKNOWN_BEFORE_START; - } - - @Override - public boolean hasNext() { - try { - switch (state) { - case UNKNOWN_BEFORE_START: - if (reader.start()) { - state = NextState.AVAILABLE; - return true; - } else { - state = NextState.UNAVAILABLE; - return false; - } - case UNKNOWN_BEFORE_ADVANCE: - if (reader.advance()) { - state = NextState.AVAILABLE; - return true; - } else { - state = NextState.UNAVAILABLE; - return false; - } - case AVAILABLE: - return true; - case UNAVAILABLE: - return false; - default: - throw new AssertionError(); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - state = NextState.UNKNOWN_BEFORE_ADVANCE; - return reader.getCurrent(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Builds a {@link SideInputInfo} for a "singleton" side input. - */ - public static SideInputInfo createSingletonSideInputInfo(Source sideInputSource) { - SideInputInfo sideInputInfo = new SideInputInfo(); - sideInputInfo.setSources(Arrays.asList(sideInputSource)); - sideInputInfo.setKind(CloudObject.forClassName("singleton")); - return sideInputInfo; - } - - /** - * Builds a {@link SideInputInfo} for a "collection" side input. - */ - public static SideInputInfo createCollectionSideInputInfo(Source... sideInputSources) { - SideInputInfo sideInputInfo = new SideInputInfo(); - sideInputInfo.setSources(Arrays.asList(sideInputSources)); - sideInputInfo.setKind(CloudObject.forClassName("collection")); - return sideInputInfo; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java deleted file mode 100644 index c589ec3762..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsDoFn.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowViaWindowSetDoFn; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; -import com.google.cloud.dataflow.sdk.util.SystemReduceFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.Preconditions; - -/** - * DoFn that merges windows and groups elements in those windows. - * - * @param key type - * @param input value element type - * @param output value element type - * @param window type - */ -@SystemDoFnInternal -public abstract class StreamingGroupAlsoByWindowsDoFn - extends DoFn, KV> { - public static - DoFn, KV> create( - final WindowingStrategy windowingStrategy, - final AppliedCombineFn combineFn, - final Coder keyCoder) { - Preconditions.checkNotNull(combineFn); - DoFn, KV> fn = - GroupAlsoByWindowViaWindowSetDoFn.create( - windowingStrategy, - SystemReduceFn.combining(keyCoder, combineFn)); - return fn; - } - - public static - DoFn, KV>> createForIterable( - final WindowingStrategy windowingStrategy, final Coder inputCoder) { - // If the windowing strategy indicates we're doing a reshuffle, use the special-path. - if (StreamingGroupAlsoByWindowsReshuffleDoFn.isReshuffle(windowingStrategy)) { - return new StreamingGroupAlsoByWindowsReshuffleDoFn<>(); - } else { - return GroupAlsoByWindowViaWindowSetDoFn.create( - windowingStrategy, SystemReduceFn.buffering(inputCoder)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java deleted file mode 100644 index ddd9b00bd1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingGroupAlsoByWindowsReshuffleDoFn.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.ReshuffleTrigger; -import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; - -import java.util.Collections; - -/** - * Implementation of {@link StreamingGroupAlsoByWindowsDoFn} used for the {@link ReshuffleTrigger} - * which outputs each element as a separate pane. - * - * @param key type - * @param value element type - */ -@SystemDoFnInternal -public class StreamingGroupAlsoByWindowsReshuffleDoFn - extends DoFn, KV>> { - - public static boolean isReshuffle(WindowingStrategy strategy) { - return strategy.getTrigger().getSpec() instanceof ReshuffleTrigger; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - @SuppressWarnings("unchecked") - K key = c.element().key(); - for (WindowedValue item : c.element().elementsIterable()) { - c.windowingInternals().outputWindowedValue( - KV.of(key, (Iterable) Collections.singletonList(item.getValue())), - item.getTimestamp(), item.getWindows(), item.getPane()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/Weighers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/Weighers.java deleted file mode 100644 index 5bafca766e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/Weighers.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.Weighted; -import com.google.common.cache.Weigher; - -/** - * A {@code Weigher} - * - *

    For internal use only. - * - *

    Package-private here so that the dependency on Guava does not leak into the public API - * surface. - */ -class Weighers { - public static Weigher fixedWeightKeys(final int keyWeight) { - return new Weigher() { - @Override - public int weigh(Object key, Weighted value) { - return (int) Math.min(keyWeight + value.getWeight(), Integer.MAX_VALUE); - } - }; - } - - public static Weigher weightedKeysAndValues() { - return new Weigher() { - @Override - public int weigh(Weighted key, Weighted value) { - return (int) Math.min(key.getWeight() + value.getWeight(), Integer.MAX_VALUE); - } - }; - } -} From 1067af65008a5cc595dba871b1ee7feacf6ec30c Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 9 Feb 2016 17:22:44 -0800 Subject: [PATCH 112/751] Move over several shuffle classes to the worker maven module This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114278581 --- .../worker/ByteArrayShufflePosition.java | 111 ---- .../worker/BatchingShuffleEntryReader.java | 148 ----- .../worker/CachingShuffleBatchReader.java | 228 -------- .../worker/GroupingShuffleEntryIterator.java | 250 --------- .../sdk/util/common/worker/GroupingTable.java | 34 -- .../util/common/worker/GroupingTables.java | 522 ------------------ .../worker/KeyGroupedShuffleEntries.java | 35 -- .../common/worker/ShuffleBatchReader.java | 61 -- .../sdk/util/common/worker/ShuffleEntry.java | 112 ---- .../common/worker/ShuffleEntryReader.java | 50 -- .../util/common/worker/ShufflePosition.java | 23 - 11 files changed, 1574 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ByteArrayShufflePosition.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingShuffleEntryIterator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/KeyGroupedShuffleEntries.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleBatchReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntry.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShufflePosition.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ByteArrayShufflePosition.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ByteArrayShufflePosition.java deleted file mode 100644 index 019cb5513c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ByteArrayShufflePosition.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Base64.decodeBase64; -import static com.google.api.client.util.Base64.encodeBase64URLSafeString; - -import com.google.cloud.dataflow.sdk.util.common.worker.ShufflePosition; -import com.google.common.base.Preconditions; -import com.google.common.primitives.Bytes; -import com.google.common.primitives.UnsignedBytes; - -import java.util.Arrays; - -import javax.annotation.Nullable; - -/** - * Represents a position of a {@link GroupingShuffleReader} as an opaque array of bytes, - * encoded in a way such that lexicographic ordering of the bytes is consistent with the inherent - * ordering of {@link GroupingShuffleReader} positions. - */ -public class ByteArrayShufflePosition - implements Comparable, ShufflePosition { - private final byte[] position; - - public ByteArrayShufflePosition(byte[] position) { - this.position = position; - } - - public static ByteArrayShufflePosition fromBase64(@Nullable String position) { - return ByteArrayShufflePosition.of(decodeBase64(position)); - } - - public static ByteArrayShufflePosition of(@Nullable byte[] position) { - if (position == null) { - return null; - } - return new ByteArrayShufflePosition(position); - } - - public static byte[] getPosition(@Nullable ShufflePosition shufflePosition) { - if (shufflePosition == null) { - return null; - } - Preconditions.checkArgument( - shufflePosition instanceof ByteArrayShufflePosition); - ByteArrayShufflePosition adapter = (ByteArrayShufflePosition) shufflePosition; - return adapter.getPosition(); - } - - public byte[] getPosition() { - return position; - } - - public String encodeBase64() { - return encodeBase64URLSafeString(position); - } - - /** - * Returns the {@link ByteArrayShufflePosition} that immediately follows this one, i.e. there - * are no possible {@link ByteArrayShufflePosition ByteArrayShufflePositions} between this and - * its successor. - */ - public ByteArrayShufflePosition immediateSuccessor() { - return new ByteArrayShufflePosition(Bytes.concat(position, new byte[] {0})); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof ByteArrayShufflePosition) { - ByteArrayShufflePosition that = (ByteArrayShufflePosition) o; - return Arrays.equals(this.position, that.position); - } - return false; - } - - @Override - public int hashCode() { - return Arrays.hashCode(position); - } - - @Override - public String toString() { - return "ShufflePosition(base64:" + encodeBase64() + ")"; - } - - @Override - public int compareTo(ByteArrayShufflePosition o) { - if (this == o) { - return 0; - } - return UnsignedBytes.lexicographicalComparator().compare(position, o.position); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReader.java deleted file mode 100644 index d30c01be9c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/BatchingShuffleEntryReader.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.util.common.Reiterator; - -import java.util.ListIterator; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; -import javax.annotation.concurrent.NotThreadSafe; - -/** - * BatchingShuffleEntryReader provides a mechanism for reading entries from - * a shuffle dataset. - */ -@NotThreadSafe -public final class BatchingShuffleEntryReader implements ShuffleEntryReader { - private final ShuffleBatchReader batchReader; - - /** - * Constructs a {@link BatchingShuffleEntryReader}. - * - * @param batchReader supplies the underlying - * {@link ShuffleBatchReader} to read batches of entries from - */ - public BatchingShuffleEntryReader( - ShuffleBatchReader batchReader) { - this.batchReader = checkNotNull(batchReader); - } - - @Override - public Reiterator read( - @Nullable ShufflePosition startPosition, - @Nullable ShufflePosition endPosition) { - return new ShuffleReadIterator(startPosition, endPosition); - } - - /** - * ShuffleReadIterator iterates over a (potentially huge) sequence of shuffle - * entries. - */ - private final class ShuffleReadIterator implements Reiterator { - // Shuffle service returns entries in pages. If the response contains a - // non-null nextStartPosition, we have to ask for more pages. The response - // with null nextStartPosition signifies the end of stream. - @Nullable private final ShufflePosition endPosition; - @Nullable private ShufflePosition nextStartPosition; - - /** The most recently read batch. */ - @Nullable ShuffleBatchReader.Batch currentBatch; - /** An iterator over the most recently read batch. */ - @Nullable private ListIterator entries; - - ShuffleReadIterator(@Nullable ShufflePosition startPosition, - @Nullable ShufflePosition endPosition) { - this.nextStartPosition = startPosition; - this.endPosition = endPosition; - } - - private ShuffleReadIterator(ShuffleReadIterator it) { - this.endPosition = it.endPosition; - this.nextStartPosition = it.nextStartPosition; - this.currentBatch = it.currentBatch; - // The idea here: if the iterator being copied was in the middle of a - // batch (the typical case), create a new iteration state at the same - // point in the same batch. - this.entries = (it.entries == null - ? null - : it.currentBatch.entries.listIterator(it.entries.nextIndex())); - } - - @Override - public boolean hasNext() { - fillEntriesIfNeeded(); - // TODO: Report API errors to the caller using checked - // exceptions. - return entries.hasNext(); - } - - @Override - public ShuffleEntry next() throws NoSuchElementException { - fillEntriesIfNeeded(); - ShuffleEntry entry = entries.next(); - return entry; - } - - @Override - public void remove() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public ShuffleReadIterator copy() { - return new ShuffleReadIterator(this); - } - - private void fillEntriesIfNeeded() { - if (entries != null && entries.hasNext()) { - // Has more records in the current page, or error. - return; - } - - if (entries != null && nextStartPosition == null) { - // End of stream. - checkState(!entries.hasNext()); - return; - } - - do { - fillEntries(); - } while (!entries.hasNext() && nextStartPosition != null); - } - - private void fillEntries() { - try { - ShuffleBatchReader.Batch batch = - batchReader.read(nextStartPosition, endPosition); - nextStartPosition = batch.nextStartPosition; - entries = batch.entries.listIterator(); - currentBatch = batch; - } catch (RuntimeException e) { - throw e; - } catch (Throwable t) { - throw new RuntimeException(t); - } - - checkState(entries != null); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReader.java deleted file mode 100644 index c7cffc58b7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/CachingShuffleBatchReader.java +++ /dev/null @@ -1,228 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.common.base.Objects; -import com.google.common.base.Throwables; - -import java.io.IOException; -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.util.HashMap; - -import javax.annotation.Nullable; - -/** A {@link ShuffleBatchReader} that caches batches as they're read. */ -public final class CachingShuffleBatchReader implements ShuffleBatchReader { - private final ShuffleBatchReader reader; - - // The cache itself is implemented as a HashMap of RangeReadReference values, - // keyed by the start and end positions describing the range of a particular - // request (represented by BatchRange). - // - // The first reader for a particular range builds an AsyncReadResult for the - // result, inserts it into the cache, drops the lock, and then completes the - // read; subsequent readers simply wait for the AsyncReadResult to complete. - // - // Note that overlapping ranges are considered distinct; cached entries for - // one range are not used for any other range, even if doing so would avoid a - // fetch. - // - // So this is not a particularly sophisticated algorithm: a smarter cache - // would be able to use subranges of previous requests to satisfy new - // requests. But in this particular case, we expect that the simple algorithm - // will work well. For a given shuffle source, the splits read by various - // iterators over that source starting from a particular position (which is - // how this class is used in practice) should turn out to be constant, if the - // result returned by the service for a particular [start, end) range are - // consistent. So we're not expecting to see overlapping ranges of entries - // within a cache. - // - // It's also been shown -- by implementing it -- that the more thorough - // algorithm is relatively complex, with numerous edge cases requiring very - // careful thought to get right. It's doable, but non-trivial and hard to - // understand and maintain; without a compelling justification, it's better to - // stick with the simpler implementation. - // - // @VisibleForTesting - final HashMap cache = new HashMap<>(); - - // The queue of references that have been collected by the garbage collector. - // This queue should only be used with references of class RangeReadReference. - private final ReferenceQueue refQueue = new ReferenceQueue<>(); - - /** - * Constructs a new {@link CachingShuffleBatchReader}. - * - * @param reader supplies the downstream {@link ShuffleBatchReader} - * this {@code CachingShuffleBatchReader} will use to issue reads - */ - public CachingShuffleBatchReader(ShuffleBatchReader reader) { - this.reader = checkNotNull(reader); - } - - @Override - public Batch read( - @Nullable ShufflePosition startPosition, - @Nullable ShufflePosition endPosition) throws IOException { - - @Nullable AsyncReadResult waitResult = null; - @Nullable AsyncReadResult runResult = null; - final BatchRange batchRange = new BatchRange(startPosition, endPosition); - - synchronized (cache) { - // Remove any GCd entries. - for (Reference ref = refQueue.poll(); - ref != null; - ref = refQueue.poll()) { - RangeReadReference rangeReadRef = (RangeReadReference) ref; - cache.remove(rangeReadRef.getBatchRange()); - } - - // Find the range reference; note that one might not be in the map, or it - // might contain a null if its target has been GCd. - @Nullable RangeReadReference rangeReadRef = cache.get(batchRange); - - // Get a strong reference to the existing AsyncReadResult for the range, if possible. - if (rangeReadRef != null) { - waitResult = rangeReadRef.get(); - } - - // Create a new AsyncReadResult if one is needed. - if (waitResult == null) { - runResult = new AsyncReadResult(); - waitResult = runResult; - rangeReadRef = null; // Replace the previous RangeReadReference. - } - - // Insert a new RangeReadReference into the map if we don't have a usable - // one (either we weren't able to find one in the map, or we did but it - // was already cleared by the GC). - if (rangeReadRef == null) { - cache.put(batchRange, - new RangeReadReference(batchRange, runResult, refQueue)); - } - } // Drop the cache lock. - - if (runResult != null) { - // This thread created the AsyncReadResult, and is responsible for - // actually performing the read. - try { - Batch result = reader.read(startPosition, endPosition); - runResult.setResult(result); - } catch (RuntimeException | IOException e) { - runResult.setException(e); - synchronized (cache) { - // No reason to continue to cache the fact that there was a problem. - // Note that since this thread holds a strong reference to the - // AsyncReadResult, it won't be GCd, so the soft reference held by the - // cache is guaranteed to still be present. - cache.remove(batchRange); - } - } - } - - return waitResult.getResult(); - } - - /** The key for the entries stored in the batch cache. */ - // @VisibleForTesting - static final class BatchRange { - @Nullable private final ShufflePosition startPosition; - @Nullable private final ShufflePosition endPosition; - - public BatchRange(@Nullable ShufflePosition startPosition, - @Nullable ShufflePosition endPosition) { - this.startPosition = startPosition; - this.endPosition = endPosition; - } - - @Override - public boolean equals(Object o) { - return o == this - || (o instanceof BatchRange - && Objects.equal(((BatchRange) o).startPosition, startPosition) - && Objects.equal(((BatchRange) o).endPosition, endPosition)); - } - - @Override - public int hashCode() { - return Objects.hashCode(startPosition, endPosition); - } - } - - /** Holds an asynchronously batch read result. */ - private static final class AsyncReadResult { - @Nullable private Batch batch = null; - @Nullable private Throwable thrown = null; - - public synchronized void setResult(Batch b) { - batch = b; - notifyAll(); - } - - public synchronized void setException(Throwable t) { - thrown = t; - notifyAll(); - } - - public synchronized Batch getResult() throws IOException { - while (batch == null && thrown == null) { - try { - wait(); - } catch (InterruptedException e) { - throw new RuntimeException("interrupted", e); - } - } - if (thrown != null) { - // N.B. setException can only be called with a RuntimeException or an - // IOException, so propagateIfPossible should always do the throw. - Throwables.propagateIfPossible(thrown, IOException.class); - throw new RuntimeException("unexpected", thrown); - } - return batch; - } - } - - /** - * Maintains a soft reference to an AsyncReadResult. - * - *

    This class extends {@link SoftReference} so that when the garbage - * collector collects a batch and adds its reference to the cache's reference - * queue, that reference can be cast back to {@code RangeReadReference}, - * allowing us to identify the reference's position in the cache (and to - * therefore remove it). - */ - // @VisibleForTesting - static final class RangeReadReference extends SoftReference { - private final BatchRange range; - - public RangeReadReference( - BatchRange range, AsyncReadResult result, - ReferenceQueue refQueue) { - super(result, refQueue); - this.range = checkNotNull(range); - } - - public BatchRange getBatchRange() { - return range; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingShuffleEntryIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingShuffleEntryIterator.java deleted file mode 100644 index f9b3a23371..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingShuffleEntryIterator.java +++ /dev/null @@ -1,250 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservableIterable; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservableIterator; -import com.google.cloud.dataflow.sdk.util.common.PeekingReiterator; -import com.google.cloud.dataflow.sdk.util.common.Reiterable; -import com.google.cloud.dataflow.sdk.util.common.Reiterator; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * An iterator through KeyGroupedShuffleEntries. - */ -public abstract class GroupingShuffleEntryIterator - implements Iterator { - /** The iterator through the underlying shuffle records. */ - private PeekingReiterator shuffleIterator; - - /** - * The key of the most recent KeyGroupedShuffleEntries returned by - * {@link #next}, if any. - * - *

    If currentKeyBytes is non-null, then it's the key for the last entry - * returned by {@link #next}, and all incoming entries with that key should - * be skipped over by this iterator (since this iterator is iterating over - * keys, not the individual values associated with a given key). - * - *

    If currentKeyBytes is null, and shuffleIterator.hasNext(), then the - * key of shuffleIterator.next() is the key of the next - * KeyGroupedShuffleEntries to return from {@link #next}. - */ - @Nullable private byte[] currentKeyBytes = null; - - /** - * The size of the shuffle entries read so far for the current key - * (if currentKeyBytes is non-null), or the previous key (if currentKeyBytes - * is null). - */ - private long totalByteSizeOfEntriesForCurrentKey = 0L; - - /** - * Counter to increment with the bytes read from the underlying shuffle - * iterator, or null if no counting is needed. - */ - @Nullable private Counter bytesCounter; - - /** - * Constructs a GroupingShuffleEntryIterator, given a Reiterator - * over ungrouped ShuffleEntries, assuming the ungrouped - * ShuffleEntries for a given key are consecutive. The counter given - * as argument, if non-null, will be updated with the byte size of the entries - * read. - */ - public GroupingShuffleEntryIterator( - Reiterator shuffleIterator, Counter bytesCounter) { - this.shuffleIterator = - new PeekingReiterator<>( - new ProgressTrackingReiterator<>( - shuffleIterator, - new ProgressTrackerGroup() { - @Override - protected void report(ShuffleEntry entry) { - notifyElementRead(entry.length()); - } - }.start())); - this.bytesCounter = bytesCounter; - } - - /** - * Notifies observers about a new ShuffleEntry (key and value, not - * key and iterable of values) read. - */ - protected abstract void notifyElementRead(long byteSize); - - @Override - public boolean hasNext() { - advanceIteratorToNextKey(); - return shuffleIterator.hasNext(); - } - - @Override - public KeyGroupedShuffleEntries next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - ShuffleEntry entry = shuffleIterator.peek(); - currentKeyBytes = entry.getKey(); - return new KeyGroupedShuffleEntries( - entry.getPosition(), - currentKeyBytes, - new ValuesIterable(new ValuesIterator(currentKeyBytes))); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - private void advanceIteratorToNextKey() { - if (currentKeyBytes != null) { - // We need to advance the iterator to the next key. - while (shuffleIterator.hasNext()) { - ShuffleEntry entry = shuffleIterator.peek(); - if (!Arrays.equals(entry.getKey(), currentKeyBytes)) { - break; - } - totalByteSizeOfEntriesForCurrentKey += shuffleIterator.next().length(); - } - currentKeyBytes = null; - } - // We are now at key boundary. - if (bytesCounter != null) { - // Commit the size of the currently read key group. - bytesCounter.addValue(totalByteSizeOfEntriesForCurrentKey); - } - totalByteSizeOfEntriesForCurrentKey = 0L; - } - - private static class ValuesIterable - extends ElementByteSizeObservableIterable - implements Reiterable { - private final ValuesIterator base; - - public ValuesIterable(ValuesIterator base) { - this.base = checkNotNull(base); - } - - @Override - public ValuesIterator createIterator() { - return base.copy(); - } - } - - /** - * Provides the {@link Reiterator} used to iterate through the - * shuffle entries of a KeyGroupedShuffleEntries. - */ - private class ValuesIterator - extends ElementByteSizeObservableIterator - implements Reiterator { - // N.B. This class is *not* static; it maintains a reference to its - // enclosing KeyGroupedShuffleEntriesIterator instance so that it can update - // that instance's shuffleIterator as an optimization. - - private final byte[] valueKeyBytes; - private final PeekingReiterator valueShuffleIterator; - private final ProgressTracker tracker; - private boolean nextKnownValid = false; - private long byteSizeRead = 0L; - - public ValuesIterator(byte[] valueKeyBytes) { - this.valueKeyBytes = checkNotNull(valueKeyBytes); - this.valueShuffleIterator = shuffleIterator.copy(); - // N.B. The ProgressTrackerGroup captures the reference to the original - // ValuesIterator for a given values iteration, which happens to be - // exactly what we want, since this is also the ValuesIterator whose - // base Observable has the references to all of the Observers watching - // the iteration. Copied ValuesIterator instances do *not* have these - // Observers, but that's fine, since the derived ProgressTracker - // instances reference the ProgressTrackerGroup, which references the - // original ValuesIterator, which does have them. - this.tracker = new ProgressTrackerGroup() { - @Override - protected void report(ShuffleEntry entry) { - notifyValueReturned(entry.length()); - } - }.start(); - } - - private ValuesIterator(ValuesIterator it, long byteSizeRead) { - this.valueKeyBytes = it.valueKeyBytes; - this.valueShuffleIterator = it.valueShuffleIterator.copy(); - this.tracker = it.tracker.copy(); - this.nextKnownValid = it.nextKnownValid; - this.byteSizeRead = byteSizeRead; - } - - @Override - public boolean hasNext() { - if (nextKnownValid) { - return true; - } - if (!valueShuffleIterator.hasNext()) { - return false; - } - ShuffleEntry entry = valueShuffleIterator.peek(); - nextKnownValid = Arrays.equals(entry.getKey(), valueKeyBytes); - - // Opportunistically update the parent KeyGroupedShuffleEntriesIterator, - // potentially allowing it to skip a large number of key/value pairs - // with this key. - if (!nextKnownValid && valueKeyBytes == currentKeyBytes) { - shuffleIterator = valueShuffleIterator.copy(); - currentKeyBytes = null; - // We update the bytes read size for the key as this is the first - // ValuesIterator copy to finish reading the values of the - // "parent" GroupingShuffleEntryIterator. Setting currentKeyBytes - // to null prevents other copies from also recording their bytes read. - totalByteSizeOfEntriesForCurrentKey = byteSizeRead; - } - - return nextKnownValid; - } - - @Override - public ShuffleEntry next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - ShuffleEntry entry = valueShuffleIterator.next(); - byteSizeRead += entry.length(); - nextKnownValid = false; - tracker.saw(entry); - return entry; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public ValuesIterator copy() { - return new ValuesIterator(this, byteSizeRead); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java deleted file mode 100644 index 30cc4edd7f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTable.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -/** - * An interface that groups inputs to an accumulator and flushes the output. - */ -public interface GroupingTable { - - /** - * Adds a pair to this table, possibly flushing some entries to output - * if the table is full. - */ - void put(Object pair, Receiver receiver) throws Exception; - - /** - * Flushes all entries in this table to output. - */ - void flush(Receiver output) throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java deleted file mode 100644 index 18a78b6679..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/GroupingTables.java +++ /dev/null @@ -1,522 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.common.annotations.VisibleForTesting; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; - -/** - * Static utility methods that provide {@link GroupingTable} implementations. - */ -public class GroupingTables { - /** - * Returns a {@link GroupingTable} that groups inputs into a {@link List}. - */ - public static GroupingTable> buffering( - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - SizeEstimator keySizer, - SizeEstimator valueSizer) { - return new BufferingGroupingTable<>( - DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, keySizer, valueSizer); - } - - /** - * Returns a {@link GroupingTable} that groups inputs into a {@link List} with - * sampling {@link SizeEstimator SizeEstimators}. - */ - public static GroupingTable> bufferingAndSampling( - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - SizeEstimator keySizer, - SizeEstimator valueSizer, - double sizeEstimatorSampleRate) { - return new BufferingGroupingTable<>( - DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, - new SamplingSizeEstimator<>(keySizer, sizeEstimatorSampleRate, 1.0), - new SamplingSizeEstimator<>(valueSizer, sizeEstimatorSampleRate, 1.0)); - } - - /** - * Returns a {@link GroupingTable} that combines inputs into a accumulator. - */ - public static GroupingTable combining( - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - Combiner combineFn, - SizeEstimator keySizer, - SizeEstimator accumulatorSizer) { - return new CombiningGroupingTable<>( - DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, - combineFn, keySizer, accumulatorSizer); - } - - /** - * Returns a {@link GroupingTable} that combines inputs into a accumulator with - * sampling {@link SizeEstimator SizeEstimators}. - */ - public static GroupingTable combiningAndSampling( - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - Combiner combineFn, - SizeEstimator keySizer, - SizeEstimator accumulatorSizer, - double sizeEstimatorSampleRate) { - return new CombiningGroupingTable<>( - DEFAULT_MAX_GROUPING_TABLE_BYTES, groupingKeyCreator, pairInfo, combineFn, - new SamplingSizeEstimator<>(keySizer, sizeEstimatorSampleRate, 1.0), - new SamplingSizeEstimator<>(accumulatorSizer, sizeEstimatorSampleRate, 1.0)); - } - - /** - * Provides client-specific operations for grouping keys. - */ - public static interface GroupingKeyCreator { - public Object createGroupingKey(K key) throws Exception; - } - - /** - * Provides client-specific operations for size estimates. - */ - public static interface SizeEstimator { - public long estimateSize(T element) throws Exception; - } - - /** - * Provides client-specific operations for working with elements - * that are key/value or key/values pairs. - */ - public interface PairInfo { - public Iterable getKeysFromInputPair(Object pair); - public Object getValueFromInputPair(Object pair); - public Object makeOutputPair(Object key, Object value); - } - - /** - * Provides client-specific operations for combining values. - */ - public interface Combiner { - public AccumT createAccumulator(K key); - public AccumT add(K key, AccumT accumulator, InputT value); - public AccumT merge(K key, Iterable accumulators); - public AccumT compact(K key, AccumT accumulator); - public OutputT extract(K key, AccumT accumulator); - } - - // By default, how many bytes we allow the grouping table to consume before - // it has to be flushed. - static final long DEFAULT_MAX_GROUPING_TABLE_BYTES = 100_000_000L; - - // How many bytes a word in the JVM has. - static final int BYTES_PER_JVM_WORD = getBytesPerJvmWord(); - /** - * The number of bytes of overhead to store an entry in the - * grouping table (a {@code HashMap}), - * ignoring the actual number of bytes in the keys and values: - *
      - *
    • an array element (1 word), - *
    • a HashMap.Entry (4 words), - *
    • a StructuralByteArray (1 words), - *
    • a backing array (guessed at 1 word for the length), - *
    • a KeyAndValues (2 words), - *
    • an ArrayList (2 words), - *
    • a backing array (1 word), - *
    • per-object overhead (JVM-specific, guessed at 2 words * 6 objects). - *
    - */ - static final int PER_KEY_OVERHEAD = 24 * BYTES_PER_JVM_WORD; - - /** - * A base class of {@link GroupingTable} that provides the implementation of - * {@link #put} and {@link #flush}. - * - *

    Subclasses override {@link #createTableEntry}. - */ - @VisibleForTesting - public abstract static class GroupingTableBase - implements GroupingTable{ - // Keep the table relatively full to increase the chance of collisions. - private static final double TARGET_LOAD = 0.9; - - private long maxSize; - private final GroupingKeyCreator groupingKeyCreator; - private final PairInfo pairInfo; - - private long size = 0; - private Map> table; - - private GroupingTableBase(long maxSize, - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo) { - this.maxSize = maxSize; - this.groupingKeyCreator = groupingKeyCreator; - this.pairInfo = pairInfo; - this.table = new HashMap<>(); - } - - interface GroupingTableEntry { - public K getKey(); - public AccumT getValue(); - public void add(InputT value) throws Exception; - public long getSize(); - public void compact() throws Exception; - } - - public abstract GroupingTableEntry createTableEntry(K key) throws Exception; - - /** - * Adds a pair to this table, possibly flushing some entries to output - * if the table is full. - */ - @SuppressWarnings("unchecked") - @Override - public void put(Object pair, Receiver receiver) throws Exception { - for (Object key : pairInfo.getKeysFromInputPair(pair)) { - put((K) key, - (InputT) pairInfo.getValueFromInputPair(pair), - receiver); - } - } - - /** - * Adds the key and value to this table, possibly flushing some entries - * to output if the table is full. - */ - public void put(K key, InputT value, Receiver receiver) throws Exception { - Object groupingKey = groupingKeyCreator.createGroupingKey(key); - GroupingTableEntry entry = table.get(groupingKey); - if (entry == null) { - entry = createTableEntry(key); - table.put(groupingKey, entry); - size += PER_KEY_OVERHEAD; - } else { - size -= entry.getSize(); - } - entry.add(value); - size += entry.getSize(); - - if (size >= maxSize) { - long targetSize = (long) (TARGET_LOAD * maxSize); - Iterator> entries = - table.values().iterator(); - while (size >= targetSize) { - if (!entries.hasNext()) { - // Should never happen, but sizes may be estimates... - size = 0; - break; - } - GroupingTableEntry toFlush = entries.next(); - entries.remove(); - size -= toFlush.getSize() + PER_KEY_OVERHEAD; - output(toFlush, receiver); - } - } - } - - /** - * Output the given entry. Does not actually remove it from the table or - * update this table's size. - */ - private void output(GroupingTableEntry entry, Receiver receiver) - throws Exception { - entry.compact(); - receiver.process(pairInfo.makeOutputPair(entry.getKey(), entry.getValue())); - } - - /** - * Flushes all entries in this table to output. - */ - @Override - public void flush(Receiver output) throws Exception { - for (GroupingTableEntry entry : table.values()) { - output(entry, output); - } - table.clear(); - size = 0; - } - - @VisibleForTesting - public void setMaxSize(long maxSize) { - this.maxSize = maxSize; - } - - @VisibleForTesting - public long size() { - return size; - } - } - - /** - * A grouping table that simply buffers all inserted values in a list. - */ - private static class BufferingGroupingTable extends GroupingTableBase> { - - public final SizeEstimator keySizer; - public final SizeEstimator valueSizer; - - private BufferingGroupingTable(long maxSize, - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - SizeEstimator keySizer, - SizeEstimator valueSizer) { - super(maxSize, groupingKeyCreator, pairInfo); - this.keySizer = keySizer; - this.valueSizer = valueSizer; - } - - @Override - public GroupingTableEntry> createTableEntry(final K key) throws Exception { - return new GroupingTableEntry>() { - long size = keySizer.estimateSize(key); - final List values = new ArrayList<>(); - - @Override - public K getKey() { - return key; - } - - @Override - public List getValue() { - return values; - } - - @Override - public long getSize() { - return size; - } - - @Override - public void compact() { } - - @Override - public void add(V value) throws Exception { - values.add(value); - size += BYTES_PER_JVM_WORD + valueSizer.estimateSize(value); - } - }; - } - } - - /** - * A grouping table that uses the given combiner to combine values in place. - */ - private static class CombiningGroupingTable - extends GroupingTableBase { - - private final Combiner combiner; - private final SizeEstimator keySizer; - private final SizeEstimator accumulatorSizer; - - private CombiningGroupingTable(long maxSize, - GroupingKeyCreator groupingKeyCreator, - PairInfo pairInfo, - Combiner combineFn, - SizeEstimator keySizer, - SizeEstimator accumulatorSizer) { - super(maxSize, groupingKeyCreator, pairInfo); - this.combiner = combineFn; - this.keySizer = keySizer; - this.accumulatorSizer = accumulatorSizer; - } - - @Override - public GroupingTableEntry createTableEntry(final K key) throws Exception { - return new GroupingTableEntry() { - final long keySize = keySizer.estimateSize(key); - AccumT accumulator = combiner.createAccumulator(key); - long accumulatorSize = 0; // never used before a value is added... - - @Override - public K getKey() { - return key; - } - - @Override - public AccumT getValue() { - return accumulator; - } - - @Override - public long getSize() { - return keySize + accumulatorSize; - } - - @Override - public void compact() throws Exception { - AccumT newAccumulator = combiner.compact(key, accumulator); - if (newAccumulator != accumulator) { - accumulator = newAccumulator; - accumulatorSize = accumulatorSizer.estimateSize(newAccumulator); - } - } - - @Override - public void add(InputT value) throws Exception { - accumulator = combiner.add(key, accumulator, value); - accumulatorSize = accumulatorSizer.estimateSize(accumulator); - } - }; - } - } - - /** - * Returns the number of bytes in a JVM word. In case we failed to - * find the answer, returns 8. - */ - private static int getBytesPerJvmWord() { - String wordSizeInBits = System.getProperty("sun.arch.data.model"); - try { - return Integer.parseInt(wordSizeInBits) / 8; - } catch (NumberFormatException e) { - // The JVM word size is unknown. Assume 64-bit. - return 8; - } - } - - //////////////////////////////////////////////////////////////////////////// - // Size sampling. - - /** - * Implements size estimation by adaptively delegating to an underlying - * (potentially more expensive) estimator for some elements and returning - * the average value for others. - */ - @VisibleForTesting - static class SamplingSizeEstimator implements SizeEstimator { - - /** - * The degree of confidence required in our expected value predictions - * before we allow under-sampling. - * - *

    The value of 3.0 is a confidence interval of about 99.7% for a - * a high-degree-of-freedom t-distribution. - */ - public static final double CONFIDENCE_INTERVAL_SIGMA = 3; - - /** - * The desired size of our confidence interval (relative to the measured - * expected value). - * - *

    The value of 0.25 is plus or minus 25%. - */ - public static final double CONFIDENCE_INTERVAL_SIZE = 0.25; - - /** - * Default number of elements that must be measured before elements are skipped. - */ - public static final long DEFAULT_MIN_SAMPLED = 20; - - private final SizeEstimator underlying; - private final double minSampleRate; - private final double maxSampleRate; - private final long minSampled; - private final Random random; - - private long totalElements = 0; - private long sampledElements = 0; - private long sampledSum = 0; - private double sampledSumSquares = 0; - private long estimate; - - private long nextSample = 0; - - private SamplingSizeEstimator( - SizeEstimator underlying, - double minSampleRate, - double maxSampleRate) { - this(underlying, minSampleRate, maxSampleRate, DEFAULT_MIN_SAMPLED, new Random()); - } - - @VisibleForTesting - SamplingSizeEstimator(SizeEstimator underlying, - double minSampleRate, - double maxSampleRate, - long minSampled, - Random random) { - this.underlying = underlying; - this.minSampleRate = minSampleRate; - this.maxSampleRate = maxSampleRate; - this.minSampled = minSampled; - this.random = random; - } - - @Override - public long estimateSize(T element) throws Exception { - if (sampleNow()) { - return recordSample(underlying.estimateSize(element)); - } else { - return estimate; - } - } - - private boolean sampleNow() { - totalElements++; - return --nextSample < 0; - } - - private long recordSample(long value) { - sampledElements += 1; - sampledSum += value; - sampledSumSquares += value * value; - estimate = (long) Math.ceil(sampledSum / sampledElements); - long target = desiredSampleSize(); - if (sampledElements < minSampled || sampledElements < target) { - // Sample immediately. - nextSample = 0; - } else { - double rate = cap( - minSampleRate, - maxSampleRate, - Math.max(1.0 / (totalElements - minSampled + 1), // slowly ramp down - target / (double) totalElements)); // "future" target - // Uses the geometric distribution to return the likely distance between - // successive independent trials of a fixed probability p. This gives the - // same uniform distribution of branching on Math.random() < p, but with - // one random number generation per success rather than one - // per test, which can be a significant savings if p is small. - nextSample = rate == 1.0 - ? 0 - : (long) Math.floor(Math.log(random.nextDouble()) / Math.log(1 - rate)); - } - return value; - } - - private static final double cap(double min, double max, double value) { - return Math.min(max, Math.max(min, value)); - } - - private long desiredSampleSize() { - // We have no a-priori information on the actual distribution of data - // sizes, so compute our desired sample as if it were normal. - // Yes this formula is unstable for small stddev, but we only care about large stddev. - double mean = sampledSum / (double) sampledElements; - double sumSquareDiff = - (sampledSumSquares - (2 * mean * sampledSum) + (sampledElements * mean * mean)); - double stddev = Math.sqrt(sumSquareDiff / (sampledElements - 1)); - double sqrtDesiredSamples = - (CONFIDENCE_INTERVAL_SIGMA * stddev) / (CONFIDENCE_INTERVAL_SIZE * mean); - return (long) Math.ceil(sqrtDesiredSamples * sqrtDesiredSamples); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/KeyGroupedShuffleEntries.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/KeyGroupedShuffleEntries.java deleted file mode 100644 index 17177a2516..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/KeyGroupedShuffleEntries.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.Reiterable; - -/** - * A collection of ShuffleEntries, all with the same key. - */ -public class KeyGroupedShuffleEntries { - public final byte[] position; - public final byte[] key; - public final Reiterable values; - - public KeyGroupedShuffleEntries(byte[] position, byte[] key, - Reiterable values) { - this.position = position; - this.key = key; - this.values = values; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleBatchReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleBatchReader.java deleted file mode 100644 index 00e575adb3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleBatchReader.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import java.io.IOException; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * ShuffleBatchReader provides an interface for reading a batch of - * key/value entries from a shuffle dataset. - */ -public interface ShuffleBatchReader { - /** The result returned by #read. */ - public static class Batch { - public final List entries; - @Nullable public final ShufflePosition nextStartPosition; - - public Batch(List entries, - @Nullable ShufflePosition nextStartPosition) { - this.entries = entries; - this.nextStartPosition = nextStartPosition; - } - } - - /** - * Reads a batch of data from a shuffle dataset. - * - * @param startPosition encodes the initial key from where to read. - * This parameter may be null, indicating that the read should start - * with the first key in the dataset. - * - * @param endPosition encodes the key "just past" the end of the - * range to be read; keys up to endPosition will be returned, but - * keys equal to or greater than endPosition will not. This - * parameter may be null, indicating that the read should end just - * past the last key in the dataset (that is, the last key in the - * dataset will be included in the read, as long as that key is - * greater than or equal to startPosition). - * - * @return the first {@link Batch} of entries - */ - public Batch read(@Nullable ShufflePosition startPosition, - @Nullable ShufflePosition endPosition) - throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntry.java deleted file mode 100644 index c5f37c6e48..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntry.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import java.util.Arrays; - -/** - * Entry written to/read from a shuffle dataset. - */ -public class ShuffleEntry { - final byte[] position; - final byte[] key; - final byte[] secondaryKey; - final byte[] value; - - public ShuffleEntry(byte[] key, byte[] secondaryKey, byte[] value) { - this.position = null; - this.key = key; - this.secondaryKey = secondaryKey; - this.value = value; - } - - public ShuffleEntry(byte[] position, byte[] key, byte[] secondaryKey, - byte[] value) { - this.position = position; - this.key = key; - this.secondaryKey = secondaryKey; - this.value = value; - } - - public byte[] getPosition() { - return position; - } - - public byte[] getKey() { - return key; - } - - public byte[] getSecondaryKey() { - return secondaryKey; - } - - public byte[] getValue() { - return value; - } - - /** - * Returns the size of this entry in bytes, excluding {@code position}. - */ - public int length() { - return (key == null ? 0 : key.length) - + (secondaryKey == null ? 0 : secondaryKey.length) - + (value == null ? 0 : value.length); - } - - @Override - public String toString() { - return "ShuffleEntry(" - + byteArrayToString(position) + "," - + byteArrayToString(key) + "," - + byteArrayToString(secondaryKey) + "," - + byteArrayToString(value) + ")"; - } - - public static String byteArrayToString(byte[] bytes) { - // TODO: Use a more compact and readable representation, - // particularly for (nearly-)ascii keys and values. - return Arrays.toString(bytes); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof ShuffleEntry) { - ShuffleEntry that = (ShuffleEntry) o; - return (this.position == null ? that.position == null - : Arrays.equals(this.position, that.position)) - && (this.key == null ? that.key == null - : Arrays.equals(this.key, that.key)) - && (this.secondaryKey == null ? that.secondaryKey == null - : Arrays.equals(this.secondaryKey, that.secondaryKey)) - && (this.value == null ? that.value == null - : Arrays.equals(this.value, that.value)); - } - return false; - } - - @Override - public int hashCode() { - return getClass().hashCode() - + (position == null ? 0 : Arrays.hashCode(position)) - + (key == null ? 0 : Arrays.hashCode(key)) - + (secondaryKey == null ? 0 : Arrays.hashCode(secondaryKey)) - + (value == null ? 0 : Arrays.hashCode(value)); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryReader.java deleted file mode 100644 index 3fc75791d1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShuffleEntryReader.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.Reiterator; - -import javax.annotation.Nullable; -import javax.annotation.concurrent.NotThreadSafe; - -/** - * ShuffleEntryReader provides an interface for reading key/value - * entries from a shuffle dataset. - */ -@NotThreadSafe -public interface ShuffleEntryReader { - /** - * Returns an iterator that reads a range of entries from a shuffle dataset. - * - * @param startPosition encodes the initial key from where to read. - * This parameter may be null, indicating that the read should start - * with the first key in the dataset. - * - * @param endPosition encodes the key "just past" the end of the - * range to be read; keys up to endPosition will be returned, but - * keys equal to or greater than endPosition will not. This - * parameter may be null, indicating that the read should end just - * past the last key in the dataset (that is, the last key in the - * dataset will be included in the read, as long as that key is - * greater than or equal to startPosition). - * - * @return a {@link Reiterator} over the requested range of entries. - */ - public Reiterator read( - @Nullable ShufflePosition startPosition, - @Nullable ShufflePosition endPosition); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShufflePosition.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShufflePosition.java deleted file mode 100644 index b3a7d5b598..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ShufflePosition.java +++ /dev/null @@ -1,23 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -/** - * Represents a position in a stream of ShuffleEntries. - */ -public interface ShufflePosition { -} From 478b1de33c58d45ad4631a54b776c34830ff5fd6 Mon Sep 17 00:00:00 2001 From: peihe Date: Wed, 10 Feb 2016 00:48:15 -0800 Subject: [PATCH 113/751] Add a DoFnRunner for StreamingGroupAlsoByWindows with side inputs Refactor streaming side inputs code into StreamingSideInputFetcher. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114300609 --- .../sdk/util/ComposedKeyedWorkItem.java | 56 ------ .../cloud/dataflow/sdk/util/DoFnRunners.java | 16 +- .../dataflow/sdk/util/KeyedWorkItems.java | 93 +++++++++ .../sdk/util/LateDataDroppingDoFnRunner.java | 180 ++++++++++-------- .../dataflow/sdk/util/TimerInternals.java | 73 +++++++ .../util/LateDataDroppingDoFnRunnerTest.java | 115 +++++++++++ .../dataflow/sdk/util/TimerInternalsTest.java | 52 +++++ 7 files changed, 440 insertions(+), 145 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java deleted file mode 100644 index 25dd6a7dd0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ComposedKeyedWorkItem.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; - -/** - * A {@link KeyedWorkItem} composed of an underlying key, {@link TimerData} iterable, and element - * iterable. - */ -public class ComposedKeyedWorkItem implements KeyedWorkItem { - - private final K key; - private final Iterable timers; - private final Iterable> elements; - - public static ComposedKeyedWorkItem create( - K key, Iterable timers, Iterable> elements) { - return new ComposedKeyedWorkItem(key, timers, elements); - } - - private ComposedKeyedWorkItem( - K key, Iterable timers, Iterable> elements) { - this.key = key; - this.timers = timers; - this.elements = elements; - } - - @Override - public K key() { - return key; - } - - @Override - public Iterable timersIterable() { - return timers; - } - - @Override - public Iterable> elementsIterable() { - return elements; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java index d78b45a09a..64a0968e0f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java @@ -46,7 +46,7 @@ public interface OutputManager { * *

    It invokes {@link DoFn#processElement} for each input. */ - static DoFnRunner simpleRunner( + public static DoFnRunner simpleRunner( PipelineOptions options, DoFn fn, SideInputReader sideInputReader, @@ -73,7 +73,7 @@ static DoFnRunner simpleRunner( * *

    It drops elements from expired windows before they reach the underlying {@link DoFn}. */ - static + public static DoFnRunner, KV> lateDataDroppingRunner( PipelineOptions options, ReduceFnExecutor reduceFnExecutor, @@ -84,10 +84,10 @@ DoFnRunner, KV> lateDataDroppingRunner( StepContext stepContext, CounterSet.AddCounterMutator addCounterMutator, WindowingStrategy windowingStrategy) { - LateDataDroppingDoFnRunner runner = - new LateDataDroppingDoFnRunner<>( + DoFnRunner, KV> simpleDoFnRunner = + simpleRunner( options, - reduceFnExecutor, + reduceFnExecutor.asDoFn(), sideInputReader, outputManager, mainOutputTag, @@ -95,7 +95,11 @@ DoFnRunner, KV> lateDataDroppingRunner( stepContext, addCounterMutator, windowingStrategy); - return runner; + return new LateDataDroppingDoFnRunner<>( + simpleDoFnRunner, + windowingStrategy, + stepContext.timerInternals(), + reduceFnExecutor.getDroppedDueToLatenessAggregator()); } public static DoFnRunner createDefault( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java new file mode 100644 index 0000000000..b94397c222 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; + +import java.util.Collections; + +/** + * Static utility methods that provide {@link KeyedWorkItem} implementations. + */ +public class KeyedWorkItems { + /** + * Returns an implementation of {@link KeyedWorkItem} that wraps around an elements iterable. + * + * @param the key type + * @param the element type + */ + public static KeyedWorkItem elementsWorkItem( + K key, Iterable> elementsIterable) { + return new ComposedKeyedWorkItem<>(key, Collections.emptyList(), elementsIterable); + } + + /** + * Returns an implementation of {@link KeyedWorkItem} that wraps around an timers iterable. + * + * @param the key type + * @param the element type + */ + public static KeyedWorkItem timersWorkItem( + K key, Iterable timersIterable) { + return new ComposedKeyedWorkItem<>( + key, timersIterable, Collections.>emptyList()); + } + + /** + * Returns an implementation of {@link KeyedWorkItem} that wraps around + * an timers iterable and an elements iterable. + * + * @param the key type + * @param the element type + */ + public static KeyedWorkItem workItem( + K key, Iterable timersIterable, Iterable> elementsIterable) { + return new ComposedKeyedWorkItem<>(key, timersIterable, elementsIterable); + } + + /** + * A {@link KeyedWorkItem} composed of an underlying key, {@link TimerData} iterable, and element + * iterable. + */ + public static class ComposedKeyedWorkItem implements KeyedWorkItem { + + private final K key; + private final Iterable timers; + private final Iterable> elements; + + private ComposedKeyedWorkItem( + K key, Iterable timers, Iterable> elements) { + this.key = key; + this.timers = timers; + this.elements = elements; + } + + @Override + public K key() { + return key; + } + + @Override + public Iterable timersIterable() { + return timers; + } + + @Override + public Iterable> elementsIterable() { + return elements; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java index e1f13d539d..31927ab882 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java @@ -15,117 +15,131 @@ */ package com.google.cloud.dataflow.sdk.util; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import org.joda.time.Instant; -import java.util.List; - /** - * A customized {@link DoFnRunner} that handles late data dropping. + * A customized {@link DoFnRunner} that handles late data dropping for + * a {@link KeyedWorkItem} input {@link DoFn}. * *

    It expands windows before checking data lateness. * + *

    {@link KeyedWorkItem KeyedWorkItems} are always in empty windows. + * * @param key type * @param input value element type * @param output value element type * @param window type */ public class LateDataDroppingDoFnRunner - extends DoFnRunnerBase, KV> { - private final WindowingStrategy windowingStrategy; - private final TimerInternals timerInternals; - private final Aggregator droppedDueToLateness; + implements DoFnRunner, KV> { + private final DoFnRunner, KV> doFnRunner; + private final LateDataFilter lateDataFilter; public LateDataDroppingDoFnRunner( - PipelineOptions options, - ReduceFnExecutor reduceFnExecutor, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag> mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - super( - options, - reduceFnExecutor.asDoFn(), - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - windowingStrategy); - this.windowingStrategy = windowingStrategy; - this.timerInternals = stepContext.timerInternals(); + DoFnRunner, KV> doFnRunner, + WindowingStrategy windowingStrategy, + TimerInternals timerInternals, + Aggregator droppedDueToLateness) { + this.doFnRunner = doFnRunner; + lateDataFilter = new LateDataFilter(windowingStrategy, timerInternals, droppedDueToLateness); + } + + @Override + public void startBundle() { + doFnRunner.startBundle(); + } - droppedDueToLateness = reduceFnExecutor.getDroppedDueToLatenessAggregator(); + @Override + public void processElement(WindowedValue> elem) { + Iterable> nonLateElements = lateDataFilter.filter( + elem.getValue().key(), elem.getValue().elementsIterable()); + KeyedWorkItem keyedWorkItem = KeyedWorkItems.workItem( + elem.getValue().key(), elem.getValue().timersIterable(), nonLateElements); + doFnRunner.processElement(elem.withValue(keyedWorkItem)); } @Override - public void invokeProcessElement(WindowedValue> elem) { - final K key = elem.getValue().key(); - Iterable>> elements = Iterables.transform( - elem.getValue().elementsIterable(), - new Function, Iterable>>() { - @Override - public Iterable> apply(final WindowedValue input) { - return Iterables.transform( - input.getWindows(), - new Function>() { - @Override - public WindowedValue apply(BoundedWindow window) { - return WindowedValue.of( - input.getValue(), input.getTimestamp(), window, input.getPane()); - } - }); - }}); + public void finishBundle() { + doFnRunner.finishBundle(); + } + + /** + * It filters late data in a {@link KeyedWorkItem}. + */ + @VisibleForTesting + static class LateDataFilter { + private final WindowingStrategy windowingStrategy; + private final TimerInternals timerInternals; + private final Aggregator droppedDueToLateness; + + public LateDataFilter( + WindowingStrategy windowingStrategy, + TimerInternals timerInternals, + Aggregator droppedDueToLateness) { + this.windowingStrategy = windowingStrategy; + this.timerInternals = timerInternals; + this.droppedDueToLateness = droppedDueToLateness; + } - Iterable> nonLateElements = Iterables.filter( - Iterables.concat(elements), - new Predicate>() { - @Override - public boolean apply(WindowedValue input) { - BoundedWindow window = Iterables.getOnlyElement(input.getWindows()); - if (canDropDueToExpiredWindow(window)) { - // The element is too late for this window. - droppedDueToLateness.addValue(1L); - WindowTracing.debug( - "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since too far behind inputWatermark:{}; outputWatermark:{}", - input.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - return false; - } else { - return true; + /** + * Returns an {@code Iterable>} that only contains + * non-late input elements. + */ + public Iterable> filter( + final K key, Iterable> elements) { + Iterable>> windowsExpandedElements = Iterables.transform( + elements, + new Function, Iterable>>() { + @Override + public Iterable> apply(final WindowedValue input) { + return Iterables.transform( + input.getWindows(), + new Function>() { + @Override + public WindowedValue apply(BoundedWindow window) { + return WindowedValue.of( + input.getValue(), input.getTimestamp(), window, input.getPane()); + } + }); + }}); + + Iterable> nonLateElements = Iterables.filter( + Iterables.concat(windowsExpandedElements), + new Predicate>() { + @Override + public boolean apply(WindowedValue input) { + BoundedWindow window = Iterables.getOnlyElement(input.getWindows()); + if (canDropDueToExpiredWindow(window)) { + // The element is too late for this window. + droppedDueToLateness.addValue(1L); + WindowTracing.debug( + "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " + + "since too far behind inputWatermark:{}; outputWatermark:{}", + input.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + return false; + } else { + return true; + } } - } - }); - KeyedWorkItem inputs = ComposedKeyedWorkItem.create( - elem.getValue().key(), elem.getValue().timersIterable(), nonLateElements); - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.processElement(createProcessContext(elem.withValue(inputs))); - } catch (Exception ex) { - throw wrapUserCodeException(ex); + }); + return nonLateElements; } - } - /** Is {@code window} expired w.r.t. the garbage collection watermark? */ - private boolean canDropDueToExpiredWindow(BoundedWindow window) { - Instant inputWM = timerInternals.currentInputWatermarkTime(); - return inputWM != null - && window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()).isBefore(inputWM); + /** Is {@code window} expired w.r.t. the garbage collection watermark? */ + private boolean canDropDueToExpiredWindow(BoundedWindow window) { + Instant inputWM = timerInternals.currentInputWatermarkTime(); + return inputWM != null + && window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()).isBefore(inputWM); + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java index bedff3e8d6..f47f73d26f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java @@ -18,11 +18,27 @@ import static com.google.common.base.Preconditions.checkNotNull; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.InstantCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; import com.google.common.base.MoreObjects; +import com.google.common.base.Preconditions; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.Instant; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.List; import java.util.Objects; import javax.annotation.Nullable; @@ -193,4 +209,61 @@ public int compareTo(TimerData o) { return Long.compare(timestamp.getMillis(), o.getTimestamp().getMillis()); } } + + /** + * A {@link Coder} for {@link TimerData}. + */ + public class TimerDataCoder extends StandardCoder { + private static final StringUtf8Coder STRING_CODER = StringUtf8Coder.of(); + private static final InstantCoder INSTANT_CODER = InstantCoder.of(); + private final Coder windowCoder; + + public static TimerDataCoder of(Coder windowCoder) { + return new TimerDataCoder(windowCoder); + } + + @SuppressWarnings("unchecked") + @JsonCreator + public static TimerDataCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) + List> components) { + Preconditions.checkArgument(components.size() == 1, + "Expecting 1 components, got " + components.size()); + return of((Coder) components.get(0)); + } + + private TimerDataCoder(Coder windowCoder) { + this.windowCoder = windowCoder; + } + + @Override + public void encode(TimerData timer, OutputStream outStream, Context context) + throws CoderException, IOException { + Context nestedContext = context.nested(); + STRING_CODER.encode(timer.namespace.stringKey(), outStream, nestedContext); + INSTANT_CODER.encode(timer.timestamp, outStream, nestedContext); + STRING_CODER.encode(timer.domain.name(), outStream, nestedContext); + } + + @Override + public TimerData decode(InputStream inStream, Context context) + throws CoderException, IOException { + Context nestedContext = context.nested(); + StateNamespace namespace = + StateNamespaces.fromString(STRING_CODER.decode(inStream, nestedContext), windowCoder); + Instant timestamp = INSTANT_CODER.decode(inStream, nestedContext); + TimeDomain domain = TimeDomain.valueOf(STRING_CODER.decode(inStream, nestedContext)); + return TimerData.of(namespace, timestamp, domain); + } + + @Override + public List> getCoderArguments() { + return Arrays.asList(windowCoder); + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + verifyDeterministic("window coder must be deterministic", windowCoder); + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java new file mode 100644 index 0000000000..c951d4c9a1 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.LateDataDroppingDoFnRunner.LateDataFilter; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.Arrays; + +/** + * Unit tests for {@link LateDataDroppingDoFnRunner}. + */ +@RunWith(JUnit4.class) +public class LateDataDroppingDoFnRunnerTest { + private static final FixedWindows WINDOW_FN = FixedWindows.of(Duration.millis(10)); + + @Mock private TimerInternals mockTimerInternals; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testLateDataFilter() throws Exception { + when(mockTimerInternals.currentInputWatermarkTime()).thenReturn(new Instant(15L)); + + InMemoryLongSumAggregator droppedDueToLateness = + new InMemoryLongSumAggregator("droppedDueToLateness"); + LateDataFilter lateDataFilter = new LateDataFilter( + WindowingStrategy.of(WINDOW_FN), mockTimerInternals, droppedDueToLateness); + + Iterable> actual = lateDataFilter.filter( + "a", + ImmutableList.of( + createDatum(13, 13L), + createDatum(5, 5L), // late element, earlier than 4L. + createDatum(16, 16L), + createDatum(18, 18L))); + + Iterable> expected = ImmutableList.of( + createDatum(13, 13L), + createDatum(16, 16L), + createDatum(18, 18L)); + assertThat(expected, containsInAnyOrder(Iterables.toArray(actual, WindowedValue.class))); + assertEquals(1, droppedDueToLateness.sum); + } + + private WindowedValue createDatum(T element, long timestampMillis) { + Instant timestamp = new Instant(timestampMillis); + return WindowedValue.of( + element, + timestamp, + Arrays.asList(WINDOW_FN.assignWindow(timestamp)), + PaneInfo.NO_FIRING); + } + + private static class InMemoryLongSumAggregator implements Aggregator { + private final String name; + private long sum = 0; + + public InMemoryLongSumAggregator(String name) { + this.name = name; + } + + @Override + public void addValue(Long value) { + sum += value; + } + + @Override + public String getName() { + return name; + } + + @Override + public CombineFn getCombineFn() { + return new Sum.SumLongFn(); + } + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java new file mode 100644 index 0000000000..68aecf0b53 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerDataCoder; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; + +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Unit tests for {@link TimerInternals}. + */ +@RunWith(JUnit4.class) +public class TimerInternalsTest { + + @Test + public void testTimerDataCoder() throws Exception { + CoderProperties.coderDecodeEncodeEqual( + TimerDataCoder.of(GlobalWindow.Coder.INSTANCE), + TimerData.of(StateNamespaces.global(), new Instant(0), TimeDomain.EVENT_TIME)); + + Coder windowCoder = IntervalWindow.getCoder(); + CoderProperties.coderDecodeEncodeEqual( + TimerDataCoder.of(windowCoder), + TimerData.of( + StateNamespaces.window( + windowCoder, new IntervalWindow(new Instant(0), new Instant(100))), + new Instant(99), TimeDomain.PROCESSING_TIME)); + } +} + From f833d2ece00b5df3803f1a746e3eb90c936511cf Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 10 Feb 2016 09:25:11 -0800 Subject: [PATCH 114/751] Handle Timers in InMemoryWatermarkManager Timers are updated whenever watermarks are; timers are extracted on-demand using the #extractTimers method. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114334216 --- .../util/InMemoryWatermarkManager.java | 695 +++++++++++++++-- .../util/InMemoryWatermarkManagerTest.java | 714 ++++++++++++++++-- 2 files changed, 1277 insertions(+), 132 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java index 96a8f5bdb3..fb2e53686d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java @@ -20,22 +20,37 @@ import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; +import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import com.google.common.collect.SortedMultiset; import com.google.common.collect.TreeMultiset; import org.joda.time.Instant; +import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.NavigableSet; +import java.util.Objects; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.TreeSet; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; @@ -126,7 +141,6 @@ private static interface Watermark { * also be updated */ WatermarkUpdate refresh(); - } /** @@ -185,11 +199,14 @@ public static WatermarkUpdate fromTimestamps(Instant oldTime, Instant currentTim private static class AppliedPTransformInputWatermark implements Watermark { private final Collection inputWatermarks; private final SortedMultiset> pendingElements; + private final Map> objectTimers; + private AtomicReference currentWatermark; public AppliedPTransformInputWatermark(Collection inputWatermarks) { this.inputWatermarks = inputWatermarks; this.pendingElements = TreeMultiset.create(PENDING_ELEMENT_COMPARATOR); + this.objectTimers = new HashMap<>(); currentWatermark = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); } @@ -229,20 +246,44 @@ public synchronized WatermarkUpdate refresh() { return WatermarkUpdate.fromTimestamps(oldWatermark, newWatermark); } - public synchronized void addPending(Iterable> newPending) { + private synchronized void addPendingElements(Iterable> newPending) { for (WindowedValue pendingElement : newPending) { pendingElements.add(pendingElement); } } - public synchronized void removePending(Iterable> finishedElements) { + private synchronized void removePendingElements( + Iterable> finishedElements) { for (WindowedValue finishedElement : finishedElements) { pendingElements.remove(finishedElement); } } + private synchronized void updateTimers(TimerUpdate update) { + NavigableSet keyTimers = objectTimers.get(update.key); + if (keyTimers == null) { + keyTimers = new TreeSet<>(); + objectTimers.put(update.key, keyTimers); + } + for (TimerData timer : update.setTimers) { + if (TimeDomain.EVENT_TIME.equals(timer.getDomain())) { + keyTimers.add(timer); + } + } + for (TimerData timer : update.deletedTimers) { + if (TimeDomain.EVENT_TIME.equals(timer.getDomain())) { + keyTimers.remove(timer); + } + } + // We don't keep references to timers that have been fired and delivered via #getFiredTimers() + } + + private synchronized Map> extractFiredEventTimeTimers() { + return extractFiredTimers(currentWatermark.get(), objectTimers); + } + @Override - public String toString() { + public synchronized String toString() { return MoreObjects.toStringHelper(AppliedPTransformInputWatermark.class) .add("pendingElements", pendingElements) .add("currentWatermark", currentWatermark) @@ -260,17 +301,21 @@ public String toString() { */ private static class AppliedPTransformOutputWatermark implements Watermark { private final Watermark inputWatermark; - private Instant currentHold; + private final PerKeyHolds holds; private AtomicReference currentWatermark; public AppliedPTransformOutputWatermark(AppliedPTransformInputWatermark inputWatermark) { this.inputWatermark = inputWatermark; - currentHold = BoundedWindow.TIMESTAMP_MAX_VALUE; + holds = new PerKeyHolds(); currentWatermark = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); } - public synchronized void setHold(Instant newHold) { - currentHold = newHold; + public synchronized void updateHold(Object key, Instant newHold) { + if (newHold == null) { + holds.removeHold(key); + } else { + holds.updateHold(key, newHold); + } } @Override @@ -296,35 +341,54 @@ public Instant get() { @Override public synchronized WatermarkUpdate refresh() { Instant oldWatermark = currentWatermark.get(); - Instant newWatermark; - if (currentHold == null) { - newWatermark = inputWatermark.get(); - } else { - newWatermark = INSTANT_ORDERING.min(inputWatermark.get(), currentHold); - } + Instant newWatermark = INSTANT_ORDERING.min(inputWatermark.get(), holds.getMinHold()); newWatermark = INSTANT_ORDERING.max(oldWatermark, newWatermark); currentWatermark.set(newWatermark); return WatermarkUpdate.fromTimestamps(oldWatermark, newWatermark); } @Override - public String toString() { + public synchronized String toString() { return MoreObjects.toStringHelper(AppliedPTransformOutputWatermark.class) - .add("currentHold", currentHold) + .add("holds", holds) .add("currentWatermark", currentWatermark) .toString(); } } + /** + * The input {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} hold for an + * {@link AppliedPTransform}. + * + *

    At any point, the hold value of an {@link SynchronizedProcessingTimeInputWatermark} is equal + * to the minimum across all pending bundles at the {@link AppliedPTransform} and all upstream + * {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} watermarks. The value of the input + * synchronized processing time at any step is equal to the maximum of: + *

      + *
    • The most recently returned synchronized processing input time + *
    • The minimum of + *
        + *
      • The current processing time + *
      • The current synchronized processing time input hold + *
      + *
    + */ private static class SynchronizedProcessingTimeInputWatermark implements Watermark { private final Collection inputWms; private final Collection> pendingBundles; + private final Map> processingTimers; + private final Map> synchronizedProcessingTimers; + + private final PriorityQueue pendingTimers; private AtomicReference earliestHold; public SynchronizedProcessingTimeInputWatermark(Collection inputWms) { this.inputWms = inputWms; this.pendingBundles = new HashSet<>(); + this.processingTimers = new HashMap<>(); + this.synchronizedProcessingTimers = new HashMap<>(); + this.pendingTimers = new PriorityQueue<>(); Instant initialHold = BoundedWindow.TIMESTAMP_MAX_VALUE; for (Watermark wm : inputWms) { initialHold = INSTANT_ORDERING.min(initialHold, wm.get()); @@ -337,6 +401,19 @@ public Instant get() { return earliestHold.get(); } + /** + * {@inheritDoc}. + * + *

    When refresh is called, the value of the {@link SynchronizedProcessingTimeInputWatermark} + * becomes equal to the minimum value of + *

      + *
    • the timestamps of all currently pending bundles
    • + *
    • all input {@link PCollection} synchronized processing time watermarks
    • + *
    + * + *

    Note that this value is not monotonic, but the returned value for the synchronized + * processing time must be. + */ @Override public synchronized WatermarkUpdate refresh() { Instant oldHold = earliestHold.get(); @@ -362,21 +439,116 @@ public synchronized void removePending(CommittedBundle bundle) { pendingBundles.remove(bundle); } + /** + * Return the earliest timestamp of the earliest timer that has not been completed. This is + * either the earliest timestamp across timers that have not been completed, or the earliest + * timestamp across timers that have been delivered but have not been completed. + */ public synchronized Instant getEarliestTimerTimestamp() { - // TODO: use unfired and pending timers to determine earliest timestamp. Requires supporting - // timers. Instant earliest = THE_END_OF_TIME.get(); + for (NavigableSet timers : processingTimers.values()) { + if (!timers.isEmpty()) { + earliest = INSTANT_ORDERING.min(timers.first().getTimestamp(), earliest); + } + } + for (NavigableSet timers : synchronizedProcessingTimers.values()) { + if (!timers.isEmpty()) { + earliest = INSTANT_ORDERING.min(timers.first().getTimestamp(), earliest); + } + } + if (!pendingTimers.isEmpty()) { + earliest = INSTANT_ORDERING.min(pendingTimers.peek().getTimestamp(), earliest); + } return earliest; } + private synchronized void updateTimers(TimerUpdate update) { + for (TimerData completedTimer : update.completedTimers) { + pendingTimers.remove(completedTimer); + } + Map> timerMap = timerMap(update.key); + for (TimerData addedTimer : update.setTimers) { + NavigableSet timerQueue = timerMap.get(addedTimer.getDomain()); + if (timerQueue != null) { + timerQueue.add(addedTimer); + } + } + for (TimerData deletedTimer : update.deletedTimers) { + NavigableSet timerQueue = timerMap.get(deletedTimer.getDomain()); + if (timerQueue != null) { + timerQueue.remove(deletedTimer); + } + } + } + + private synchronized Map> extractFiredDomainTimers( + TimeDomain domain, Instant firingTime) { + Map> firedTimers; + switch (domain) { + case PROCESSING_TIME: + firedTimers = extractFiredTimers(firingTime, processingTimers); + break; + case SYNCHRONIZED_PROCESSING_TIME: + firedTimers = + extractFiredTimers( + INSTANT_ORDERING.min(firingTime, earliestHold.get()), + synchronizedProcessingTimers); + break; + default: + throw new IllegalArgumentException( + "Called getFiredTimers on a Synchronized Processing Time watermark" + + " and gave a non-processing time domain " + + domain); + } + for (Map.Entry> firedTimer : firedTimers.entrySet()) { + pendingTimers.addAll(firedTimer.getValue()); + } + return firedTimers; + } + + private Map> timerMap(Object key) { + NavigableSet processingQueue = processingTimers.get(key); + if (processingQueue == null) { + processingQueue = new TreeSet<>(); + processingTimers.put(key, processingQueue); + } + NavigableSet synchronizedProcessingQueue = + synchronizedProcessingTimers.get(key); + if (synchronizedProcessingQueue == null) { + synchronizedProcessingQueue = new TreeSet<>(); + synchronizedProcessingTimers.put(key, synchronizedProcessingQueue); + } + EnumMap> result = new EnumMap<>(TimeDomain.class); + result.put(TimeDomain.PROCESSING_TIME, processingQueue); + result.put(TimeDomain.SYNCHRONIZED_PROCESSING_TIME, synchronizedProcessingQueue); + return result; + } + @Override - public String toString() { + public synchronized String toString() { return MoreObjects.toStringHelper(SynchronizedProcessingTimeInputWatermark.class) .add("earliestHold", earliestHold) .toString(); } } + /** + * The output {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} hold for an + * {@link AppliedPTransform}. + * + *

    At any point, the hold value of an {@link SynchronizedProcessingTimeOutputWatermark} is + * equal to the minimum across all incomplete timers at the {@link AppliedPTransform} and all + * upstream {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} watermarks. The value of the output + * synchronized processing time at any step is equal to the maximum of: + *

      + *
    • The most recently returned synchronized processing output time + *
    • The minimum of + *
        + *
      • The current processing time + *
      • The current synchronized processing time output hold + *
      + *
    + */ private static class SynchronizedProcessingTimeOutputWatermark implements Watermark { private final SynchronizedProcessingTimeInputWatermark inputWm; private AtomicReference latestRefresh; @@ -392,6 +564,21 @@ public Instant get() { return latestRefresh.get(); } + /** + * {@inheritDoc}. + * + *

    When refresh is called, the value of the {@link SynchronizedProcessingTimeOutputWatermark} + * becomes equal to the minimum value of: + *

      + *
    • the current input watermark. + *
    • all {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} timers that are based on the input + * watermark. + *
    • all {@link TimeDomain#PROCESSING_TIME} timers that are based on the input watermark. + *
    + * + *

    Note that this value is not monotonic, but the returned value for the synchronized + * processing time must be. + */ @Override public synchronized WatermarkUpdate refresh() { // Hold the output synchronized processing time to the input watermark, which takes into @@ -405,7 +592,7 @@ public synchronized WatermarkUpdate refresh() { } @Override - public String toString() { + public synchronized String toString() { return MoreObjects.toStringHelper(SynchronizedProcessingTimeOutputWatermark.class) .add("latestRefresh", latestRefresh) .toString(); @@ -416,8 +603,7 @@ public String toString() { * The {@code Watermark} that is after the latest time it is possible to represent in the global * window. This is a distinguished value representing a complete {@link PTransform}. */ - private static final Watermark THE_END_OF_TIME = - new Watermark() { + private static final Watermark THE_END_OF_TIME = new Watermark() { @Override public WatermarkUpdate refresh() { // THE_END_OF_TIME is a distinguished value that cannot be advanced. @@ -440,11 +626,42 @@ public Instant get() { private static final Ordering> PENDING_ELEMENT_COMPARATOR = (new WindowedValueByTimestampComparator()).compound(Ordering.arbitrary()); + /** + * For each (Object, PriorityQueue) pair in the provided map, remove each Timer that is before the + * latestTime argument and put in in the result with the same key, then remove all of the keys + * which have no more pending timers. + * + * The result collection retains ordering of timers (from earliest to latest). + */ + private static Map> extractFiredTimers( + Instant latestTime, Map> objectTimers) { + Map> result = new HashMap<>(); + Set emptyKeys = new HashSet<>(); + for (Map.Entry> pendingTimers : objectTimers.entrySet()) { + NavigableSet timers = pendingTimers.getValue(); + if (!timers.isEmpty() && timers.first().getTimestamp().isBefore(latestTime)) { + ArrayList keyFiredTimers = new ArrayList<>(); + result.put(pendingTimers.getKey(), keyFiredTimers); + while (!timers.isEmpty() && timers.first().getTimestamp().isBefore(latestTime)) { + keyFiredTimers.add(timers.first()); + timers.remove(timers.first()); + } + } + if (timers.isEmpty()) { + emptyKeys.add(pendingTimers.getKey()); + } + } + objectTimers.keySet().removeAll(emptyKeys); + return result; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + /** * A map from each {@link PCollection} to all {@link AppliedPTransform PTransform applications} * that consume that {@link PCollection}. */ - private final Map, Collection>> consumers; + private final Map>> consumers; /** * The input and output watermark of each {@link AppliedPTransform}. @@ -462,13 +679,13 @@ public Instant get() { */ public static InMemoryWatermarkManager create( Collection> rootTransforms, - Map, Collection>> consumers) { + Map>> consumers) { return new InMemoryWatermarkManager(rootTransforms, consumers); } private InMemoryWatermarkManager( Collection> rootTransforms, - Map, Collection>> consumers) { + Map>> consumers) { this.consumers = consumers; transformToWatermarks = new HashMap<>(); @@ -559,10 +776,12 @@ public TransformWatermarks getWatermarks(AppliedPTransform transform) { */ public void updateOutputWatermark( AppliedPTransform transform, + TimerUpdate timerUpdate, Iterable> outputs, Instant eventTimeWatermark) { TransformWatermarks watermarks = getWatermarks(transform); - watermarks.setEventTimeHold(eventTimeWatermark); + watermarks.updateTimers(timerUpdate); + watermarks.setEventTimeHold(null, eventTimeWatermark); for (CommittedBundle output : outputs) { PCollection pCollection = output.getPCollection(); @@ -595,15 +814,17 @@ public void updateOutputWatermark( public void updateWatermarks( CommittedBundle completed, AppliedPTransform transform, + TimerUpdate timerUpdate, Iterable> outputs, @Nullable Instant earliestHold) { - updatePending(completed, transform, outputs); + updatePending(completed, transform, timerUpdate, outputs); TransformWatermarks transformWms = transformToWatermarks.get(transform); - transformWms.setEventTimeHold(earliestHold); + transformWms.setEventTimeHold(completed.getKey(), earliestHold); refreshWatermarks(transform); } - private void refreshWatermarks(AppliedPTransform transform) { + private void refreshWatermarks( + AppliedPTransform transform) { TransformWatermarks myWatermarks = transformToWatermarks.get(transform); WatermarkUpdate updateResult = myWatermarks.refresh(); if (updateResult.isAdvanced()) { @@ -611,7 +832,7 @@ private void refreshWatermarks(AppliedPTransform transform) { Collection> downstreamTransforms = consumers.get(outputPValue); if (downstreamTransforms != null) { for (AppliedPTransform downstreamTransform : downstreamTransforms) { - refreshWatermarks(downstreamTransform); + refreshWatermarks(downstreamTransform); } } } @@ -627,8 +848,10 @@ private void refreshWatermarks(AppliedPTransform transform) { private void updatePending( CommittedBundle input, AppliedPTransform transform, + TimerUpdate timerUpdate, Iterable> outputs) { TransformWatermarks completedTransform = transformToWatermarks.get(transform); + completedTransform.updateTimers(timerUpdate); completedTransform.removePending(input); for (CommittedBundle bundle : outputs) { @@ -648,6 +871,145 @@ private void addPending( watermarks.addPending(pending); } + /** + * Returns a map of each {@link PTransform} that has pending timers to those timers. All of the + * pending timers will be removed from this {@link InMemoryWatermarkManager}. + * + * This method exists primarily to extract processing time timers, as watermark timers will be + * returned whenever a watermark is updated through + * {@link #updateOutputWatermark(AppliedPTransform, TimerUpdate, Iterable, Instant)} and + * {@link #updateWatermarks(CommittedBundle, AppliedPTransform, TimerUpdate, Iterable, Instant)}. + */ + public Map, Map> extractFiredTimers() { + Map, Map> allTimers = new HashMap<>(); + for (Map.Entry, TransformWatermarks> watermarksEntry : + transformToWatermarks.entrySet()) { + Map keyFiredTimers = watermarksEntry.getValue().extractFiredTimers(); + if (!keyFiredTimers.isEmpty()) { + allTimers.put(watermarksEntry.getKey(), keyFiredTimers); + } + } + return allTimers; + } + + /** + * Returns true if, for any {@link TransformWatermarks} returned by + * {@link #getWatermarks(AppliedPTransform)}, the output watermark will be equal to + * {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. + */ + public boolean isDone() { + for (Map.Entry, TransformWatermarks> watermarksEntry : + transformToWatermarks.entrySet()) { + Instant endOfTime = THE_END_OF_TIME.get(); + if (watermarksEntry.getValue().getOutputWatermark().isBefore(endOfTime)) { + return false; + } + } + return true; + } + + /** + * A (key, Instant) pair that holds the watermark. Holds are per-key, but the watermark is global, + * and as such the watermark manager must track holds and the release of holds on a per-key basis. + * + *

    The {@link #compareTo(KeyedHold)} method of {@link KeyedHold} is not consistent with equals, + * as the key is arbitrarily ordered via identity, rather than object equality. + */ + private static final class KeyedHold implements Comparable { + private static final Ordering KEY_ORDERING = Ordering.arbitrary().nullsLast(); + + private final Object key; + private final Instant timestamp; + + /** + * Create a new KeyedHold with the specified key and timestamp. + */ + public static KeyedHold of(Object key, Instant timestamp) { + return new KeyedHold(key, MoreObjects.firstNonNull(timestamp, THE_END_OF_TIME.get())); + } + + private KeyedHold(Object key, Instant timestamp) { + this.key = key; + this.timestamp = timestamp; + } + + @Override + public int compareTo(KeyedHold that) { + return ComparisonChain.start() + .compare(this.timestamp, that.timestamp) + .compare(this.key, that.key, KEY_ORDERING) + .result(); + } + + @Override + public int hashCode() { + return Objects.hash(timestamp, key); + } + + @Override + public boolean equals(Object other) { + if (other == null || !(other instanceof KeyedHold)) { + return false; + } + KeyedHold that = (KeyedHold) other; + return Objects.equals(this.timestamp, that.timestamp) && Objects.equals(this.key, that.key); + } + + /** + * Get the value of this {@link KeyedHold}. + */ + public Instant getTimestamp() { + return timestamp; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(KeyedHold.class) + .add("key", key) + .add("hold", timestamp) + .toString(); + } + } + + private static class PerKeyHolds { + private final Map keyedHolds; + private final PriorityQueue allHolds; + + private PerKeyHolds() { + this.keyedHolds = new HashMap<>(); + this.allHolds = new PriorityQueue<>(); + } + + /** + * Gets the minimum hold across all keys in this {@link PerKeyHolds}, or THE_END_OF_TIME if + * there are no holds within this {@link PerKeyHolds}. + */ + public Instant getMinHold() { + return allHolds.isEmpty() ? THE_END_OF_TIME.get() : allHolds.peek().getTimestamp(); + } + + /** + * Updates the hold of the provided key to the provided value, removing any other holds for + * the same key. + */ + public void updateHold(@Nullable Object key, Instant newHold) { + removeHold(key); + KeyedHold newKeyedHold = KeyedHold.of(key, newHold); + keyedHolds.put(key, newKeyedHold); + allHolds.offer(newKeyedHold); + } + + /** + * Removes the hold of the provided key. + */ + public void removeHold(Object key) { + KeyedHold oldHold = keyedHolds.get(key); + if (oldHold != null) { + allHolds.remove(oldHold); + } + } + } + /** * A reference to the input and output watermarks of an {@link AppliedPTransform}. */ @@ -658,30 +1020,21 @@ public class TransformWatermarks { private final SynchronizedProcessingTimeInputWatermark synchronizedProcessingInputWatermark; private final SynchronizedProcessingTimeOutputWatermark synchronizedProcessingOutputWatermark; + private Instant latestSynchronizedInputWm; + private Instant latestSynchronizedOutputWm; + private TransformWatermarks( AppliedPTransformInputWatermark inputWatermark, AppliedPTransformOutputWatermark outputWatermark, - SynchronizedProcessingTimeInputWatermark sychronizedProcessingWatermark, - SynchronizedProcessingTimeOutputWatermark outputProcessingWatermark) { + SynchronizedProcessingTimeInputWatermark inputSynchProcessingWatermark, + SynchronizedProcessingTimeOutputWatermark outputSynchProcessingWatermark) { this.inputWatermark = inputWatermark; this.outputWatermark = outputWatermark; - this.synchronizedProcessingInputWatermark = sychronizedProcessingWatermark; - this.synchronizedProcessingOutputWatermark = outputProcessingWatermark; - } - - private void setEventTimeHold(Instant hold) { - outputWatermark.setHold(hold); - } - - private void removePending(CommittedBundle bundle) { - inputWatermark.removePending(bundle.getElements()); - synchronizedProcessingInputWatermark.removePending(bundle); - } - - private void addPending(CommittedBundle bundle) { - inputWatermark.addPending(bundle.getElements()); - synchronizedProcessingInputWatermark.addPending(bundle); + this.synchronizedProcessingInputWatermark = inputSynchProcessingWatermark; + this.synchronizedProcessingOutputWatermark = outputSynchProcessingWatermark; + this.latestSynchronizedInputWm = BoundedWindow.TIMESTAMP_MIN_VALUE; + this.latestSynchronizedOutputWm = BoundedWindow.TIMESTAMP_MIN_VALUE; } /** @@ -691,19 +1044,37 @@ public Instant getInputWatermark() { return inputWatermark.get(); } - public Instant getSynchronizedProcessingInputTime() { - return INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingInputWatermark.get()); + /** + * Returns the output watermark of the {@link AppliedPTransform}. + */ + public Instant getOutputWatermark() { + return outputWatermark.get(); } - public Instant getSynchronizedProcessingOutputTime() { - return INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingOutputWatermark.get()); + /** + * Returns the synchronized processing input time of the {@link AppliedPTransform}. + * + *

    The returned value is guaranteed to be monotonically increasing, and outside of the + * presence of holds, will increase as the system time progresses. + */ + public synchronized Instant getSynchronizedProcessingInputTime() { + latestSynchronizedInputWm = INSTANT_ORDERING.max( + latestSynchronizedInputWm, + INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingInputWatermark.get())); + return latestSynchronizedInputWm; } /** - * Returns the output watermark of the {@link AppliedPTransform}. + * Returns the synchronized processing output time of the {@link AppliedPTransform}. + * + *

    The returned value is guaranteed to be monotonically increasing, and outside of the + * presence of holds, will increase as the system time progresses. */ - public Instant getOutputWatermark() { - return outputWatermark.get(); + public synchronized Instant getSynchronizedProcessingOutputTime() { + latestSynchronizedOutputWm = INSTANT_ORDERING.max( + latestSynchronizedOutputWm, + INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingOutputWatermark.get())); + return latestSynchronizedOutputWm; } private WatermarkUpdate refresh() { @@ -714,6 +1085,67 @@ private WatermarkUpdate refresh() { return eventOutputUpdate.union(syncOutputUpdate); } + private void setEventTimeHold(Object key, Instant newHold) { + outputWatermark.updateHold(key, newHold); + } + + private void removePending(CommittedBundle bundle) { + inputWatermark.removePendingElements(bundle.getElements()); + synchronizedProcessingInputWatermark.removePending(bundle); + } + + private void addPending(CommittedBundle bundle) { + inputWatermark.addPendingElements(bundle.getElements()); + synchronizedProcessingInputWatermark.addPending(bundle); + } + + private Map extractFiredTimers() { + Map> eventTimeTimers = inputWatermark.extractFiredEventTimeTimers(); + Map> processingTimers; + Map> synchronizedTimers; + if (inputWatermark.get().equals(BoundedWindow.TIMESTAMP_MAX_VALUE)) { + processingTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( + TimeDomain.PROCESSING_TIME, BoundedWindow.TIMESTAMP_MAX_VALUE); + synchronizedTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( + TimeDomain.PROCESSING_TIME, BoundedWindow.TIMESTAMP_MAX_VALUE); + } else { + processingTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( + TimeDomain.PROCESSING_TIME, Instant.now()); + synchronizedTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( + TimeDomain.SYNCHRONIZED_PROCESSING_TIME, getSynchronizedProcessingInputTime()); + } + Map>> groupedTimers = new HashMap<>(); + groupFiredTimers(groupedTimers, eventTimeTimers, processingTimers, synchronizedTimers); + + Map keyFiredTimers = new HashMap<>(); + for (Map.Entry>> firedTimers : + groupedTimers.entrySet()) { + keyFiredTimers.put(firedTimers.getKey(), new FiredTimers(firedTimers.getValue())); + } + return keyFiredTimers; + } + + @SafeVarargs + private final void groupFiredTimers( + Map>> groupedToMutate, + Map>... timersToGroup) { + for (Map> subGroup : timersToGroup) { + for (Map.Entry> newTimers : subGroup.entrySet()) { + Map> grouped = groupedToMutate.get(newTimers.getKey()); + if (grouped == null) { + grouped = new HashMap<>(); + groupedToMutate.put(newTimers.getKey(), grouped); + } + grouped.put(newTimers.getValue().get(0).getDomain(), newTimers.getValue()); + } + } + } + + private void updateTimers(TimerUpdate update) { + inputWatermark.updateTimers(update); + synchronizedProcessingInputWatermark.updateTimers(update); + } + @Override public String toString() { return MoreObjects.toStringHelper(TransformWatermarks.class) @@ -725,6 +1157,159 @@ public String toString() { } } + /** + * A collection of newly set, deleted, and completed timers. + * + *

    setTimers and deletedTimers are collections of {@link TimerData} that have been added to the + * {@link TimerInternals} of an executed step. completedTimers are timers that were delivered as + * the input to the executed step. + */ + public static class TimerUpdate { + private final Object key; + private final Iterable completedTimers; + + private final Iterable setTimers; + private final Iterable deletedTimers; + + /** + * Returns a TimerUpdate for a null key with no timers. + */ + public static TimerUpdate empty() { + return new TimerUpdate( + null, + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); + } + + /** + * Creates a new {@link TimerUpdate} builder with the provided completed timers that needs the + * set and deleted timers to be added to it. + */ + public static TimerUpdateBuilder builder(Object key) { + return new TimerUpdateBuilder(key); + } + + /** + * A {@link TimerUpdate} builder that needs to be provided with set timers and deleted timers. + */ + public static final class TimerUpdateBuilder { + private final Object key; + private final Collection completedTimers; + private final Collection setTimers; + private final Collection deletedTimers; + + private TimerUpdateBuilder(Object key) { + this.key = key; + this.completedTimers = new HashSet<>(); + this.setTimers = new HashSet<>(); + this.deletedTimers = new HashSet<>(); + } + + /** + * Adds all of the provided timers to the collection of completed timers, and returns this + * {@link TimerUpdateBuilder}. + */ + public TimerUpdateBuilder withCompletedTimers(Iterable completedTimers) { + Iterables.addAll(this.completedTimers, completedTimers); + return this; + } + + /** + * Adds the provided timer to the collection of set timers, removing it from deleted timers if + * it has previously been deleted. Returns this {@link TimerUpdateBuilder}. + */ + public TimerUpdateBuilder setTimer(TimerData setTimer) { + deletedTimers.remove(setTimer); + setTimers.add(setTimer); + return this; + } + + /** + * Adds the provided timer to the collection of deleted timers, removing it from set timers if + * it has previously been set. Returns this {@link TimerUpdateBuilder}. + */ + public TimerUpdateBuilder deletedTimer(TimerData deletedTimer) { + deletedTimers.add(deletedTimer); + setTimers.remove(deletedTimer); + return this; + } + + /** + * Returns a new {@link TimerUpdate} with the most recently set completedTimers, setTimers, + * and deletedTimers. + */ + public TimerUpdate build() { + return new TimerUpdate(key, ImmutableSet.copyOf(completedTimers), + ImmutableSet.copyOf(setTimers), ImmutableSet.copyOf(deletedTimers)); + } + } + + private TimerUpdate( + Object key, + Iterable completedTimers, + Iterable setTimers, + Iterable deletedTimers) { + this.key = key; + this.completedTimers = completedTimers; + this.setTimers = setTimers; + this.deletedTimers = deletedTimers; + } + + @VisibleForTesting + Object getKey() { + return key; + } + + @VisibleForTesting + Iterable getCompletedTimers() { + return completedTimers; + } + + @VisibleForTesting + Iterable getSetTimers() { + return setTimers; + } + + @VisibleForTesting + Iterable getDeletedTimers() { + return deletedTimers; + } + } + + /** + * A pair of {@link TimerData} and key which can be delivered to the appropriate + * {@link AppliedPTransform}. A timer fires at the transform that set it with a specific key when + * the time domain in which it lives progresses past a specified time, as determined by the + * {@link InMemoryWatermarkManager}. + */ + public static class FiredTimers { + private final Map> timers; + + private FiredTimers(Map> timers) { + this.timers = timers; + } + + /** + * Gets all of the timers that have fired within the provided {@link TimeDomain}. If no timers + * fired within the provided domain, return an empty collection. + * + *

    Timers within a {@link TimeDomain} are guaranteed to be in order of increasing timestamp. + */ + public Collection getTimers(TimeDomain domain) { + Collection domainTimers = timers.get(domain); + if (domainTimers == null) { + return Collections.emptyList(); + } + return domainTimers; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(FiredTimers.class).add("timers", timers).toString(); + } + } + private static class WindowedValueByTimestampComparator extends Ordering> { @Override public int compare(WindowedValue o1, WindowedValue o2) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java index 2186718169..a549047524 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java @@ -15,24 +15,37 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess.util; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.FiredTimers; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TransformWatermarks; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.cloud.dataflow.sdk.values.PValue; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.collect.ImmutableList; @@ -61,15 +74,16 @@ public class InMemoryWatermarkManagerTest implements Serializable { private static final Instant INITIAL_PROCESSING_TIME = new Instant(1000L); - private PCollection createdInts; + private transient PCollection createdInts; - private PCollection filtered; - private PCollection> keyed; + private transient PCollection filtered; + private transient PCollection filteredTimesTwo; + private transient PCollection> keyed; - private PCollection intsToFlatten; - private PCollection flattened; + private transient PCollection intsToFlatten; + private transient PCollection flattened; - private InMemoryWatermarkManager manager; + private transient InMemoryWatermarkManager manager; @Before public void setup() { @@ -80,6 +94,12 @@ public void setup() { createdInts = p.apply("createdInts", Create.of(1, 2, 3)); filtered = createdInts.apply("filtered", Filter.greaterThan(1)); + filteredTimesTwo = filtered.apply("timesTwo", ParDo.of(new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) throws Exception { + c.output(c.element() * 2); + }})); + keyed = createdInts.apply("keyed", WithKeys.of("MyKey")); intsToFlatten = p.apply("intsToFlatten", Create.of(-1, 256, 65535)); @@ -91,12 +111,17 @@ public void setup() { createdInts.getProducingTransformInternal(), intsToFlatten.getProducingTransformInternal()); - Map, Collection>> consumers = new HashMap<>(); + Map>> consumers = new HashMap<>(); consumers.put( createdInts, - ImmutableList.>of(filtered.getProducingTransformInternal(), + ImmutableList.>of( + filtered.getProducingTransformInternal(), keyed.getProducingTransformInternal(), flattened.getProducingTransformInternal())); - consumers.put(filtered, Collections.>emptyList()); + consumers.put( + filtered, + Collections.>singleton( + filteredTimesTwo.getProducingTransformInternal())); + consumers.put(filteredTimesTwo, Collections.>emptyList()); consumers.put(keyed, Collections.>emptyList()); consumers.put( @@ -133,11 +158,11 @@ public void getWatermarkForUntouchedTransform() { @Test public void getWatermarkForUpdatedSourceTransform() { CommittedBundle output = globallyWindowedBundle(createdInts, 1); - - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(output), new Instant(8000L)); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(output), new Instant(8000L)); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(output), + new Instant(8000L)); TransformWatermarks updatedSourceWatermark = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -154,8 +179,9 @@ public void getWatermarkForMultiInputTransform() { manager.updateOutputWatermark( intsToFlatten.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(secondPcollectionBundle), - new Instant(Long.MAX_VALUE)); + BoundedWindow.TIMESTAMP_MAX_VALUE); // We didn't do anything for the first source, so we shouldn't have progressed the watermark TransformWatermarks firstSourceWatermark = @@ -183,12 +209,17 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle flattenedBundleSecondCreate = globallyWindowedBundle(flattened, -1); // We have finished processing the bundle from the second PCollection, but we haven't consumed // anything from the first PCollection yet; so our watermark shouldn't advance - manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(flattenedBundleSecondCreate), null); + manager.updateWatermarks( + secondPcollectionBundle, + flattened.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(flattenedBundleSecondCreate), + null); TransformWatermarks transformAfterProcessing = manager.getWatermarks(flattened.getProducingTransformInternal()); manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(flattenedBundleSecondCreate), null); + TimerUpdate.empty(), Collections.>singleton(flattenedBundleSecondCreate), + null); assertThat( transformAfterProcessing.getInputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); @@ -203,6 +234,7 @@ public void getWatermarkForMultiInputTransform() { // past the end of the global window manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(firstPcollectionBundle), new Instant(Long.MAX_VALUE)); TransformWatermarks firstSourceWatermarks = @@ -230,10 +262,12 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle completedFlattenBundle = InProcessBundle.unkeyed(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(completedFlattenBundle), null); - manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), - Collections.>singleton(completedFlattenBundle), null); + manager.updateWatermarks( + firstPcollectionBundle, + flattened.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(completedFlattenBundle), + null); TransformWatermarks afterConsumingAllInput = manager.getWatermarks(flattened.getProducingTransformInternal()); assertThat( @@ -250,11 +284,17 @@ public void getWatermarkForMultiInputTransform() { */ @Test public void getWatermarkForMultiConsumedCollection() { - CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); +CommittedBundle createdBundle = + timestampedBundle( + createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), + TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(createdBundle), + new Instant(Long.MAX_VALUE)); TransformWatermarks createdAfterProducing = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( @@ -265,8 +305,12 @@ public void getWatermarkForMultiConsumedCollection() { timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), null); + manager.updateWatermarks( + createdBundle, + keyed.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(keyBundle), + null); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -281,8 +325,12 @@ public void getWatermarkForMultiConsumedCollection() { CommittedBundle filteredBundle = timestampedBundle(filtered, TimestampedValue.of(2, new Instant(1234L))); - manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), - Collections.>singleton(filteredBundle), null); + manager.updateWatermarks( + createdBundle, + filtered.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(filteredBundle), + null); TransformWatermarks filteredProcessedWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat( @@ -299,18 +347,30 @@ public void getWatermarkForMultiConsumedCollection() { */ @Test public void updateWatermarkWithWatermarkHolds() { - CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + CommittedBundle createdBundle = + timestampedBundle( + createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), + TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(createdBundle), + new Instant(Long.MAX_VALUE)); CommittedBundle> keyBundle = - timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + timestampedBundle( + keyed, + TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), new Instant(500L)); + manager.updateWatermarks( + createdBundle, + keyed.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(keyBundle), + new Instant(500L)); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -318,6 +378,60 @@ public void updateWatermarkWithWatermarkHolds() { assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); } + /** + * Demonstrates that the watermark of an {@link AppliedPTransform} is held to the provided + * watermark hold. + */ + @Test + public void updateWatermarkWithKeyedWatermarkHolds() { + CommittedBundle firstKeyBundle = + InProcessBundle.keyed(createdInts, "Odd") + .add(WindowedValue.timestampedValueInGlobalWindow(1, new Instant(1_000_000L))) + .add(WindowedValue.timestampedValueInGlobalWindow(3, new Instant(-1000L))) + .commit(Instant.now()); + + CommittedBundle secondKeyBundle = + InProcessBundle.keyed(createdInts, "Even") + .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) + .commit(Instant.now()); + + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + ImmutableList.of(firstKeyBundle, secondKeyBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); + + manager.updateWatermarks(firstKeyBundle, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>emptyList(), new Instant(-1000L)); + manager.updateWatermarks(secondKeyBundle, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>emptyList(), new Instant(1234L)); + + TransformWatermarks filteredWatermarks = + manager.getWatermarks(filtered.getProducingTransformInternal()); + assertThat( + filteredWatermarks.getInputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); + + CommittedBundle fauxFirstKeyTimerBundle = + InProcessBundle.keyed(createdInts, "Odd").commit(Instant.now()); + manager.updateWatermarks(fauxFirstKeyTimerBundle, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>emptyList(), + BoundedWindow.TIMESTAMP_MAX_VALUE); + + assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(1234L))); + + CommittedBundle fauxSecondKeyTimerBundle = + InProcessBundle.keyed(createdInts, "Even").commit(Instant.now()); + manager.updateWatermarks(fauxSecondKeyTimerBundle, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>emptyList(), new Instant(5678L)); + assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(5678L))); + + manager.updateWatermarks(fauxSecondKeyTimerBundle, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>emptyList(), + BoundedWindow.TIMESTAMP_MAX_VALUE); + assertThat( + filteredWatermarks.getOutputWatermark(), + not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); + } + /** * Demonstrates that updated output watermarks are monotonic in the presence of late data, when * called on an {@link AppliedPTransform} that consumes no input. @@ -326,17 +440,23 @@ public void updateWatermarkWithWatermarkHolds() { public void updateOutputWatermarkShouldBeMonotonic() { CommittedBundle firstInput = InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(firstInput), new Instant(0L)); -TransformWatermarks firstWatermarks = + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(firstInput), + new Instant(0L)); + TransformWatermarks firstWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); CommittedBundle secondInput = InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(secondInput), new Instant(-250L)); -TransformWatermarks secondWatermarks = + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(secondInput), + new Instant(-250L)); + TransformWatermarks secondWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); } @@ -347,20 +467,30 @@ public void updateOutputWatermarkShouldBeMonotonic() { */ @Test public void updateWatermarkWithHoldsShouldBeMonotonic() { - CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + CommittedBundle createdBundle = + timestampedBundle( + createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), + TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(createdBundle), + new Instant(Long.MAX_VALUE)); CommittedBundle> keyBundle = - timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + timestampedBundle( + keyed, + TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), new Instant(500L)); - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), new Instant(500L)); + manager.updateWatermarks( + createdBundle, + keyed.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(keyBundle), + new Instant(500L)); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -386,17 +516,23 @@ public void updateWatermarkWithLateData() { CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, sourceWatermark), TimestampedValue.of(2, new Instant(1234L))); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createdBundle), sourceWatermark); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(createdBundle), + sourceWatermark); CommittedBundle> keyBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), sourceWatermark), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); // Finish processing the on-time data. The watermarks should progress to be equal to the source - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(keyBundle), null); - + manager.updateWatermarks( + createdBundle, + keyed.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(keyBundle), + null); TransformWatermarks onTimeWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); @@ -406,9 +542,12 @@ public void updateWatermarkWithLateData() { timestampedBundle(createdInts, TimestampedValue.of(3, new Instant(-1000L))); // the late data arrives in a downstream PCollection after its watermark has advanced past it; // we don't advance the watermark past the current watermark until we've consumed the late data - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(lateDataBundle), new Instant(2_000_000L)); - TransformWatermarks bufferedLateWm = + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(lateDataBundle), + new Instant(2_000_000L)); + TransformWatermarks bufferedLateWm = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); @@ -421,8 +560,12 @@ public void updateWatermarkWithLateData() { CommittedBundle> lateKeyedBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(lateDataBundle, keyed.getProducingTransformInternal(), - Collections.>singleton(lateKeyedBundle), null); + manager.updateWatermarks( + lateDataBundle, + keyed.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(lateKeyedBundle), + null); } /** @@ -434,6 +577,7 @@ public void getWatermarksAfterOnlyEmptyOutput() { CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = @@ -460,12 +604,19 @@ public void getWatermarksAfterOnlyEmptyOutput() { @Test public void getWatermarksAfterHoldAndEmptyOutput() { CommittedBundle firstCreateOutput = globallyWindowedBundle(createdInts, 1, 2); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(firstCreateOutput), new Instant(12_000L)); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(firstCreateOutput), + new Instant(12_000L)); CommittedBundle firstFilterOutput = globallyWindowedBundle(filtered); - manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), - Collections.>singleton(firstFilterOutput), new Instant(10_000L)); + manager.updateWatermarks( + firstCreateOutput, + filtered.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(firstFilterOutput), + new Instant(10_000L)); TransformWatermarks firstFilterWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat(firstFilterWatermarks.getInputWatermark(), not(earlierThan(new Instant(12_000L)))); @@ -474,6 +625,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = @@ -513,8 +665,11 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { CommittedBundle createOutput = InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(createOutput), + BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); @@ -539,7 +694,10 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { CommittedBundle filterOutputBundle = InProcessBundle.unkeyed(intsToFlatten).commit(new Instant(1250L)); - manager.updateWatermarks(createOutput, filtered.getProducingTransformInternal(), + manager.updateWatermarks( + createOutput, + filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(filterOutputBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks filterAfterConsumed = @@ -555,10 +713,88 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { /** * Demonstrates that the Synchronized Processing Time output watermark cannot progress past * pending timers in the same set. This propagates to all downstream SynchronizedProcessingTimes. + * + *

    Also demonstrate that the result is monotonic. */ - @Test +// @Test public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { - // TODO: Support Timers; add test + CommittedBundle createdBundle = globallyWindowedBundle(createdInts, 1, 2, 4, 8); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(createdBundle), new Instant(1248L)); + + TransformWatermarks filteredWms = + manager.getWatermarks(filtered.getProducingTransformInternal()); + TransformWatermarks filteredDoubledWms = + manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); + Instant initialFilteredWm = filteredWms.getSynchronizedProcessingOutputTime(); + Instant initialFilteredDoubledWm = filteredDoubledWms.getSynchronizedProcessingOutputTime(); + + CommittedBundle filteredBundle = globallyWindowedBundle(filtered, 2, 8); + TimerData pastTimer = + TimerData.of(StateNamespaces.global(), new Instant(250L), TimeDomain.PROCESSING_TIME); + TimerData futureTimer = + TimerData.of(StateNamespaces.global(), new Instant(4096L), TimeDomain.PROCESSING_TIME); + TimerUpdate timers = + TimerUpdate.builder("key").setTimer(pastTimer).setTimer(futureTimer).build(); + manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), timers, + Collections.>singleton(filteredBundle), + BoundedWindow.TIMESTAMP_MAX_VALUE); + DateTimeUtils.setCurrentMillisFixed(INITIAL_PROCESSING_TIME.plus(250L).getMillis()); + // We're held based on the past timer + assertThat( + filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(INITIAL_PROCESSING_TIME))); + assertThat( + filteredDoubledWms.getSynchronizedProcessingOutputTime(), + not(laterThan(INITIAL_PROCESSING_TIME))); + // And we're monotonic + assertThat( + filteredWms.getSynchronizedProcessingOutputTime(), not(earlierThan(initialFilteredWm))); + assertThat( + filteredDoubledWms.getSynchronizedProcessingOutputTime(), + not(earlierThan(initialFilteredDoubledWm))); + + Map, Map> firedTimers = + manager.extractFiredTimers(); + assertThat( + firedTimers.get(filtered.getProducingTransformInternal()) + .get("key") + .getTimers(TimeDomain.PROCESSING_TIME), + contains(pastTimer)); + // Our timer has fired, but has not been completed, so it holds our synchronized processing WM + assertThat( + filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(INITIAL_PROCESSING_TIME))); + assertThat( + filteredDoubledWms.getSynchronizedProcessingOutputTime(), + not(laterThan(INITIAL_PROCESSING_TIME))); + + CommittedBundle filteredTimerBundle = + InProcessBundle.keyed(filtered, "key").commit(BoundedWindow.TIMESTAMP_MAX_VALUE); + CommittedBundle filteredTimerResult = + InProcessBundle.keyed(filteredTimesTwo, "key") + .commit(filteredWms.getSynchronizedProcessingOutputTime()); + // Complete the processing time timer + manager.updateWatermarks(filteredTimerBundle, filtered.getProducingTransformInternal(), + TimerUpdate.builder("key") + .withCompletedTimers(Collections.singleton(pastTimer)) + .build(), + Collections.>singleton(filteredTimerResult), + BoundedWindow.TIMESTAMP_MAX_VALUE); + + DateTimeUtils.setCurrentMillisFixed(INITIAL_PROCESSING_TIME.plus(500L).getMillis()); + assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(Instant.now()))); + // filtered should be held to the time at which the filteredTimerResult fired + assertThat( + filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(INITIAL_PROCESSING_TIME)); + + manager.updateWatermarks(filteredTimerResult, filteredTimesTwo.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>emptyList(), + BoundedWindow.TIMESTAMP_MAX_VALUE); + assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + + DateTimeUtils.setCurrentMillisFixed(Long.MAX_VALUE); + assertThat(filteredWms.getSynchronizedProcessingOutputTime(), equalTo(new Instant(4096))); + assertThat( + filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(new Instant(4096))); } /** @@ -584,8 +820,11 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { CommittedBundle createOutput = InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), - Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(createOutput), + BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( @@ -597,6 +836,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { InProcessBundle.unkeyed(createdInts).commit(new Instant(750L)); manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(createSecondOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -604,7 +844,327 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { } @Test - public void getSynchronizedProcessingTimeInputIsHeldToEarliestUpstream() {} + public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers() { + CommittedBundle created = globallyWindowedBundle(createdInts, 1, 2, 3); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(created), new Instant(40_900L)); + + CommittedBundle filteredBundle = globallyWindowedBundle(filtered, 2, 4); + Instant upstreamHold = new Instant(2048L); + TimerData upstreamProcessingTimer = + TimerData.of(StateNamespaces.global(), upstreamHold, TimeDomain.PROCESSING_TIME); + manager.updateWatermarks(created, filtered.getProducingTransformInternal(), + TimerUpdate.builder("key") + .setTimer(upstreamProcessingTimer) + .build(), + Collections.>singleton(filteredBundle), + BoundedWindow.TIMESTAMP_MAX_VALUE); + + TransformWatermarks downstreamWms = + manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); + + DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis()); + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); + + manager.extractFiredTimers(); + // Pending processing time timers that have been fired but aren't completed hold the + // synchronized processing time + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); + + CommittedBundle otherCreated = globallyWindowedBundle(createdInts, 4, 8, 12); + manager.updateWatermarks(otherCreated, filtered.getProducingTransformInternal(), + TimerUpdate.builder("key") + .withCompletedTimers(Collections.singleton(upstreamProcessingTimer)) + .build(), + Collections.>emptyList(), BoundedWindow.TIMESTAMP_MAX_VALUE); + + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), not(earlierThan(Instant.now()))); + } + + @Test + public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { + CommittedBundle created = globallyWindowedBundle(createdInts, 1, 2, 3); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(created), new Instant(29_919_235L)); + + Instant upstreamHold = new Instant(2048L); + CommittedBundle filteredBundle = + InProcessBundle.keyed(filtered, "key").commit(upstreamHold); + manager.updateWatermarks(created, filtered.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(filteredBundle), + BoundedWindow.TIMESTAMP_MAX_VALUE); + + TransformWatermarks downstreamWms = + manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); + + DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis()); + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); + } + + @Test + public void extractFiredTimersReturnsFiredEventTimeTimers() { + Map, Map> initialTimers = + manager.extractFiredTimers(); + // Watermarks haven't advanced + assertThat(initialTimers.entrySet(), emptyIterable()); + + // Advance WM of keyed past the first timer, but ahead of the second and third + CommittedBundle createdBundle = globallyWindowedBundle(filtered); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.singleton(createdBundle), + new Instant(1500L)); + + TimerData earliestTimer = + TimerData.of(StateNamespaces.global(), new Instant(1000), TimeDomain.EVENT_TIME); + TimerData middleTimer = + TimerData.of(StateNamespaces.global(), new Instant(5000L), TimeDomain.EVENT_TIME); + TimerData lastTimer = + TimerData.of(StateNamespaces.global(), new Instant(10000L), TimeDomain.EVENT_TIME); + Object key = new Object(); + TimerUpdate update = + TimerUpdate.builder(key) + .setTimer(earliestTimer) + .setTimer(middleTimer) + .setTimer(lastTimer) + .build(); + + manager.updateWatermarks( + createdBundle, + filtered.getProducingTransformInternal(), + update, + Collections.>singleton(globallyWindowedBundle(intsToFlatten)), + new Instant(1000L)); + + Map, Map> firstTransformFiredTimers = + manager.extractFiredTimers(); + assertThat( + firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); + Map firstFilteredTimers = + firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); + assertThat(firstFilteredTimers.get(key), not(nullValue())); + FiredTimers firstFired = firstFilteredTimers.get(key); + assertThat(firstFired.getTimers(TimeDomain.EVENT_TIME), contains(earliestTimer)); + + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>emptyList(), + new Instant(50_000L)); + Map, Map> secondTransformFiredTimers = + manager.extractFiredTimers(); + assertThat( + secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); + Map secondFilteredTimers = + secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); + assertThat(secondFilteredTimers.get(key), not(nullValue())); + FiredTimers secondFired = secondFilteredTimers.get(key); + // Contains, in order, middleTimer and then lastTimer + assertThat(secondFired.getTimers(TimeDomain.EVENT_TIME), contains(middleTimer, lastTimer)); + } + + @Test + public void extractFiredTimersReturnsFiredProcessingTimeTimers() { + Map, Map> initialTimers = + manager.extractFiredTimers(); + // Watermarks haven't advanced + assertThat(initialTimers.entrySet(), emptyIterable()); + + // Advance WM of keyed past the first timer, but ahead of the second and third + CommittedBundle createdBundle = globallyWindowedBundle(filtered); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.singleton(createdBundle), + new Instant(1500L)); + + TimerData earliestTimer = + TimerData.of(StateNamespaces.global(), new Instant(999L), TimeDomain.PROCESSING_TIME); + TimerData middleTimer = + TimerData.of(StateNamespaces.global(), new Instant(5000L), TimeDomain.PROCESSING_TIME); + TimerData lastTimer = + TimerData.of(StateNamespaces.global(), new Instant(10000L), TimeDomain.PROCESSING_TIME); + Object key = new Object(); + TimerUpdate update = + TimerUpdate.builder(key) + .setTimer(lastTimer) + .setTimer(earliestTimer) + .setTimer(middleTimer).build(); + + manager.updateWatermarks( + createdBundle, + filtered.getProducingTransformInternal(), + update, + Collections.>singleton(globallyWindowedBundle(intsToFlatten)), + new Instant(1000L)); + + Map, Map> firstTransformFiredTimers = + manager.extractFiredTimers(); + assertThat( + firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); + Map firstFilteredTimers = + firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); + assertThat(firstFilteredTimers.get(key), not(nullValue())); + FiredTimers firstFired = firstFilteredTimers.get(key); + assertThat(firstFired.getTimers(TimeDomain.PROCESSING_TIME), contains(earliestTimer)); + + DateTimeUtils.setCurrentMillisFixed(50_000L); + manager.updateOutputWatermark( + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>emptyList(), + new Instant(50_000L)); + Map, Map> secondTransformFiredTimers = + manager.extractFiredTimers(); + assertThat( + secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); + Map secondFilteredTimers = + secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); + assertThat(secondFilteredTimers.get(key), not(nullValue())); + FiredTimers secondFired = secondFilteredTimers.get(key); + // Contains, in order, middleTimer and then lastTimer + assertThat(secondFired.getTimers(TimeDomain.PROCESSING_TIME), contains(middleTimer, lastTimer)); + } + + @Test + public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { + Map, Map> initialTimers = + manager.extractFiredTimers(); + // Watermarks haven't advanced + assertThat(initialTimers.entrySet(), emptyIterable()); + + // Advance WM of keyed past the first timer, but ahead of the second and third + CommittedBundle createdBundle = globallyWindowedBundle(filtered); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.singleton(createdBundle), new Instant(1500L)); + + TimerData earliestTimer = TimerData.of( + StateNamespaces.global(), new Instant(999L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + TimerData middleTimer = TimerData.of( + StateNamespaces.global(), new Instant(5000L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + TimerData lastTimer = TimerData.of( + StateNamespaces.global(), new Instant(10000L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + Object key = new Object(); + TimerUpdate update = + TimerUpdate.builder(key) + .setTimer(lastTimer) + .setTimer(earliestTimer) + .setTimer(middleTimer).build(); + + manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), update, + Collections.>singleton(globallyWindowedBundle(intsToFlatten)), + new Instant(1000L)); + + Map, Map> firstTransformFiredTimers = + manager.extractFiredTimers(); + assertThat( + firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); + Map firstFilteredTimers = + firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); + assertThat(firstFilteredTimers.get(key), not(nullValue())); + FiredTimers firstFired = firstFilteredTimers.get(key); + assertThat( + firstFired.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), contains(earliestTimer)); + + DateTimeUtils.setCurrentMillisFixed(50_000L); + manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>emptyList(), new Instant(50_000L)); + Map, Map> secondTransformFiredTimers = + manager.extractFiredTimers(); + assertThat( + secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); + Map secondFilteredTimers = + secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); + assertThat(secondFilteredTimers.get(key), not(nullValue())); + FiredTimers secondFired = secondFilteredTimers.get(key); + // Contains, in order, middleTimer and then lastTimer + assertThat( + secondFired.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), + contains(middleTimer, lastTimer)); + } + + @Test + public void timerUpdateBuilderBuildAddsAllAddedTimers() { + TimerData set = TimerData.of(StateNamespaces.global(), new Instant(10L), TimeDomain.EVENT_TIME); + TimerData deleted = + TimerData.of(StateNamespaces.global(), new Instant(24L), TimeDomain.PROCESSING_TIME); + TimerData completedOne = TimerData.of( + StateNamespaces.global(), new Instant(1024L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + TimerData completedTwo = + TimerData.of(StateNamespaces.global(), new Instant(2048L), TimeDomain.EVENT_TIME); + + TimerUpdate update = + TimerUpdate.builder("foo") + .withCompletedTimers(ImmutableList.of(completedOne, completedTwo)) + .setTimer(set) + .deletedTimer(deleted) + .build(); + + assertThat(update.getCompletedTimers(), containsInAnyOrder(completedOne, completedTwo)); + assertThat(update.getSetTimers(), contains(set)); + assertThat(update.getDeletedTimers(), contains(deleted)); + } + + @Test + public void timerUpdateBuilderWithSetThenDeleteHasOnlyDeleted() { + TimerUpdateBuilder builder = TimerUpdate.builder(null); + TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); + + TimerUpdate built = builder.setTimer(timer).deletedTimer(timer).build(); + + assertThat(built.getSetTimers(), emptyIterable()); + assertThat(built.getDeletedTimers(), contains(timer)); + } + + @Test + public void timerUpdateBuilderWithDeleteThenSetHasOnlySet() { + TimerUpdateBuilder builder = TimerUpdate.builder(null); + TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); + + TimerUpdate built = builder.deletedTimer(timer).setTimer(timer).build(); + + assertThat(built.getSetTimers(), contains(timer)); + assertThat(built.getDeletedTimers(), emptyIterable()); + } + + @Test + public void timerUpdateBuilderWithSetAfterBuildNotAddedToBuilt() { + TimerUpdateBuilder builder = TimerUpdate.builder(null); + TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); + + TimerUpdate built = builder.build(); + builder.setTimer(timer); + assertThat(built.getSetTimers(), emptyIterable()); + builder.build(); + assertThat(built.getSetTimers(), emptyIterable()); + } + + @Test + public void timerUpdateBuilderWithDeleteAfterBuildNotAddedToBuilt() { + TimerUpdateBuilder builder = TimerUpdate.builder(null); + TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); + + TimerUpdate built = builder.build(); + builder.deletedTimer(timer); + assertThat(built.getDeletedTimers(), emptyIterable()); + builder.build(); + assertThat(built.getDeletedTimers(), emptyIterable()); + } + + @Test + public void timerUpdateBuilderWithCompletedAfterBuildNotAddedToBuilt() { + TimerUpdateBuilder builder = TimerUpdate.builder(null); + TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); + + TimerUpdate built = builder.build(); + builder.withCompletedTimers(ImmutableList.of(timer)); + assertThat(built.getCompletedTimers(), emptyIterable()); + builder.build(); + assertThat(built.getCompletedTimers(), emptyIterable()); + } private static Matcher earlierThan(final Instant laterInstant) { return new BaseMatcher() { From 62e516b568b9fb4967e52826658200f1ff6d9e98 Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 10 Feb 2016 10:11:40 -0800 Subject: [PATCH 115/751] Move over worker logging classes to worker maven module This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114339317 --- .../logging/DataflowWorkerLoggingHandler.java | 258 ------------------ .../DataflowWorkerLoggingInitializer.java | 148 ---------- .../JulLoggerPrintStreamAdapterFactory.java | 128 --------- .../DataflowWorkerLoggingHandlerTest.java | 246 ----------------- .../DataflowWorkerLoggingInitializerTest.java | 139 ---------- ...ulLoggerPrintStreamAdapterFactoryTest.java | 82 ------ 6 files changed, 1001 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandler.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializer.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactory.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandlerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandler.java deleted file mode 100644 index 85d2b1b169..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandler.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.logging; - -import static com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingInitializer.LEVELS; - -import com.google.common.base.MoreObjects; -import com.google.common.base.Supplier; -import com.google.common.io.CountingOutputStream; - -import com.fasterxml.jackson.core.JsonEncoding; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.logging.ErrorManager; -import java.util.logging.Handler; -import java.util.logging.LogRecord; - -/** - * Formats {@link LogRecord} into JSON format for Cloud Logging. - * Any exception is represented using {@link Throwable#printStackTrace()}. - */ -public class DataflowWorkerLoggingHandler extends Handler { - /** - * Formats the throwable as per {@link Throwable#printStackTrace()}. - * - * @param thrown The throwable to format. - * @return A string containing the contents of {@link Throwable#printStackTrace()}. - */ - public static String formatException(Throwable thrown) { - if (thrown == null) { - return null; - } - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - thrown.printStackTrace(pw); - pw.close(); - return sw.toString(); - } - - /** - * Constructs a handler that writes to a rotating set of files. - */ - public DataflowWorkerLoggingHandler(String filename, long sizeLimit) throws IOException { - this(new FileOutputStreamFactory(filename), sizeLimit); - } - - /** - * Constructs a handler that writes to arbitrary output streams. No rollover if sizeLimit is - * zero or negative. - */ - DataflowWorkerLoggingHandler(Supplier factory, long sizeLimit) - throws IOException { - this.outputStreamFactory = factory; - this.generatorFactory = new ObjectMapper().getFactory(); - this.sizeLimit = sizeLimit < 1 ? Long.MAX_VALUE : sizeLimit; - createOutputStream(); - } - - @Override - public synchronized void publish(LogRecord record) { - if (!isLoggable(record)) { - return; - } - - rolloverOutputStreamIfNeeded(); - - try { - // Generating a JSON map like: - // {"timestamp": {"seconds": 1435835832, "nanos": 123456789}, ... "message": "hello"} - generator.writeStartObject(); - // Write the timestamp. - generator.writeFieldName("timestamp"); - generator.writeStartObject(); - generator.writeNumberField("seconds", record.getMillis() / 1000); - generator.writeNumberField("nanos", (record.getMillis() % 1000) * 1000000); - generator.writeEndObject(); - // Write the severity. - generator.writeObjectField( - "severity", - MoreObjects.firstNonNull(LEVELS.get(record.getLevel()), record.getLevel().getName())); - // Write the other labels. - writeIfNotNull("message", record.getMessage()); - writeIfNotNull("thread", String.valueOf(record.getThreadID())); - writeIfNotNull("job", DataflowWorkerLoggingMDC.getJobId()); - writeIfNotNull("stage", DataflowWorkerLoggingMDC.getStageName()); - writeIfNotNull("step", DataflowWorkerLoggingMDC.getStepName()); - writeIfNotNull("worker", DataflowWorkerLoggingMDC.getWorkerId()); - writeIfNotNull("work", DataflowWorkerLoggingMDC.getWorkId()); - writeIfNotNull("logger", record.getLoggerName()); - writeIfNotNull("exception", formatException(record.getThrown())); - generator.writeEndObject(); - generator.writeRaw(System.lineSeparator()); - } catch (IOException | RuntimeException e) { - reportFailure("Unable to publish", e, ErrorManager.WRITE_FAILURE); - } - - // This implementation is based on that of java.util.logging.FileHandler, which flushes in a - // synchronized context like this. Unfortunately the maximum throughput for generating log - // entries will be the inverse of the flush latency. That could be as little as one hundred - // log entries per second on some systems. For higher throughput this should be changed to - // batch publish operations while writes and flushes are in flight on a different thread. - flush(); - } - - /** - * Check if a LogRecord will be logged. - * - *

    This method checks if the LogRecord has an appropriate level and - * whether it satisfies any Filter. It will also return false if - * the handler has been closed, or the LogRecord is null. - */ - @Override - public boolean isLoggable(LogRecord record) { - return generator != null && record != null && super.isLoggable(record); - } - - @Override - public synchronized void flush() { - try { - if (generator != null) { - generator.flush(); - } - } catch (IOException | RuntimeException e) { - reportFailure("Unable to flush", e, ErrorManager.FLUSH_FAILURE); - } -} - - @Override - public synchronized void close() { - // Flush any in-flight content, though there should not actually be any because - // the generator is currently flushed in the synchronized publish() method. - flush(); - // Close the generator and log file. - try { - if (generator != null) { - generator.close(); - } - } catch (IOException | RuntimeException e) { - reportFailure("Unable to close", e, ErrorManager.CLOSE_FAILURE); - } finally { - generator = null; - counter = null; - } - } - - /** - * Unique file generator. Uses filenames with timestamp. - */ - private static final class FileOutputStreamFactory implements Supplier { - private final String filepath; - private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss_SSS"); - - public FileOutputStreamFactory(String filepath) { - this.filepath = filepath; - } - - @Override - public OutputStream get() { - try { - String filename = filepath + "." + formatter.format(new Date()); - return new BufferedOutputStream( - new FileOutputStream(new File(filename), true /* append */)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private void createOutputStream() throws IOException { - CountingOutputStream stream = new CountingOutputStream(outputStreamFactory.get()); - generator = generatorFactory.createGenerator(stream, JsonEncoding.UTF8); - counter = stream; - - // Avoid 1 space indent for every line. We already add a newline after each log record. - generator.setPrettyPrinter(new MinimalPrettyPrinter("")); - } - - /** - * Rollover to a new output stream (log file) if we have reached the size limit. Ensure that - * the rollover fails or succeeds atomically. - */ - private void rolloverOutputStreamIfNeeded() { - if (counter.getCount() < sizeLimit) { - return; - } - - try { - JsonGenerator old = generator; - createOutputStream(); - - try { - // Rollover successful. Attempt to close old stream, but ignore on failure. - old.close(); - } catch (IOException | RuntimeException e) { - reportFailure("Unable to close old log file", e, ErrorManager.CLOSE_FAILURE); - } - } catch (IOException | RuntimeException e) { - reportFailure("Unable to create new log file", e, ErrorManager.OPEN_FAILURE); - } - } - - /** - * Appends a JSON key/value pair if the specified val is not null. - */ - private void writeIfNotNull(String name, String val) throws IOException { - if (val != null) { - generator.writeStringField(name, val); - } - } - - /** - * Report logging failure to ErrorManager. Does not throw. - */ - private void reportFailure(String message, Exception e, int code) { - try { - ErrorManager manager = getErrorManager(); - if (manager != null) { - manager.error(message, e, code); - } - } catch (Throwable t) { - // Failed to report logging failure. No meaningful action left. - } - } - - // Null after close(). - private JsonGenerator generator; - private CountingOutputStream counter; - - private final long sizeLimit; - private final Supplier outputStreamFactory; - private final JsonFactory generatorFactory; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializer.java deleted file mode 100644 index 167859e0a0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializer.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.logging; - -import static com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.Level.DEBUG; -import static com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.Level.ERROR; -import static com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.Level.INFO; -import static com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.Level.TRACE; -import static com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.Level.WARN; - -import com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions; -import com.google.common.collect.ImmutableBiMap; -import com.google.common.collect.Lists; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.util.List; -import java.util.Map; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; - -/** - * Sets up {@link java.util.logging} configuration on the Dataflow worker with a rotating - * file logger. The file logger uses the {@link DataflowWorkerLoggingHandler} format. - * A user can override the logging level by customizing the options found within - * {@link DataflowWorkerLoggingOptions}. A user can override the location by specifying the - * Java system property "dataflow.worker.logging.basepath" and the file size in MB before - * rolling over to a new file by specifying the Java system property "dataflow.worker. - * loggging.filesize_mb". The default log level is INFO, the default location is a file - * named dataflow-json.log within the system temporary directory and the default file size - * is 1 GB. - */ -public class DataflowWorkerLoggingInitializer { - private static final String ROOT_LOGGER_NAME = ""; - private static final String DEFAULT_LOGGING_LOCATION = - new File(System.getProperty("java.io.tmpdir"), "dataflow-json.log").getPath(); - private static final String FILEPATH_PROPERTY = "dataflow.worker.logging.filepath"; - private static final String FILESIZE_MB_PROPERTY = "dataflow.worker.logging.filesize_mb"; - - static final ImmutableBiMap LEVELS = - ImmutableBiMap.builder() - .put(Level.SEVERE, ERROR) - .put(Level.WARNING, WARN) - .put(Level.INFO, INFO) - .put(Level.FINE, DEBUG) - .put(Level.FINEST, TRACE) - .build(); - - /** - * This default log level is overridden by the log level found at - * {@code DataflowWorkerLoggingOptions#getDefaultWorkerLogLevel()}. - */ - private static final DataflowWorkerLoggingOptions.Level DEFAULT_LOG_LEVEL = - LEVELS.get(Level.INFO); - - /* We need to store a reference to the configured loggers so that they are not - * garbage collected. java.util.logging only has weak references to the loggers - * so if they are garbage collection, our hierarchical configuration will be lost. */ - private static List configuredLoggers = Lists.newArrayList(); - private static PrintStream originalStdOut; - private static PrintStream originalStdErr; - private static boolean initialized = false; - - /** - * Sets up the initial logging configuration. - */ - public static synchronized void initialize() { - if (initialized) { - return; - } - - try { - String filepath = System.getProperty(FILEPATH_PROPERTY, DEFAULT_LOGGING_LOCATION); - int filesizeMb = Integer.parseInt(System.getProperty(FILESIZE_MB_PROPERTY, "1024")); - - DataflowWorkerLoggingHandler loggingHandler = - new DataflowWorkerLoggingHandler(filepath, filesizeMb * 1024 * 1024); - loggingHandler.setLevel(Level.ALL); - - // Reset the global log manager, get the root logger and remove the default log handlers. - LogManager logManager = LogManager.getLogManager(); - logManager.reset(); - Logger rootLogger = logManager.getLogger(ROOT_LOGGER_NAME); - for (Handler handler : rootLogger.getHandlers()) { - rootLogger.removeHandler(handler); - } - - Level logLevel = LEVELS.inverse().get(DEFAULT_LOG_LEVEL); - rootLogger.setLevel(logLevel); - rootLogger.addHandler(loggingHandler); - - originalStdOut = System.out; - originalStdErr = System.err; - System.setOut(JulLoggerPrintStreamAdapterFactory.create("System.out", Level.INFO)); - System.setErr(JulLoggerPrintStreamAdapterFactory.create("System.err", Level.SEVERE)); - - initialized = true; - } catch (SecurityException | IOException | NumberFormatException e) { - throw new ExceptionInInitializerError(e); - } - } - - /** - * Reconfigures logging with the passed in options. - */ - public static synchronized void configure(DataflowWorkerLoggingOptions options) { - initialize(); - - if (options.getDefaultWorkerLogLevel() != null) { - LogManager.getLogManager().getLogger(ROOT_LOGGER_NAME).setLevel( - LEVELS.inverse().get(options.getDefaultWorkerLogLevel())); - } - - if (options.getWorkerLogLevelOverrides() != null) { - for (Map.Entry loggerOverride : - options.getWorkerLogLevelOverrides().entrySet()) { - Logger logger = Logger.getLogger(loggerOverride.getKey()); - logger.setLevel(LEVELS.inverse().get(loggerOverride.getValue())); - configuredLoggers.add(logger); - } - } - } - - // Visible for testing - static void reset() { - configuredLoggers = Lists.newArrayList(); - System.setOut(originalStdOut); - System.setErr(originalStdErr); - initialized = false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactory.java deleted file mode 100644 index 86ffa281cc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactory.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.logging; - -import com.google.common.base.Throwables; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A {@link PrintStream} factory that creates {@link PrintStream}s which output - * to the named JUL {@link Logger} at the specified {@link Level}. - */ -class JulLoggerPrintStreamAdapterFactory { - private static final AtomicBoolean outputWarning = new AtomicBoolean(false); - - /** - * Creates a {@link PrintStream} which redirects all output to a JUL {@link Logger} - * with the given {@code name} at the specified {@code level}. - */ - static PrintStream create(String name, Level level) { - try { - return new PrintStream( - new JulLoggerAdapterOutputStream(name, level), - false, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw Throwables.propagate(e); - } - } - - /** - * An output stream adapter which is able to take a stream of UTF-8 data and output - * to a named JUL logger. The log messages will be buffered until the system - * dependent new line separator is seen, at which point the buffered string will be - * output. - */ - private static class JulLoggerAdapterOutputStream extends OutputStream { - private static final String LOGGING_DISCLAIMER = String.format( - "Please use a logger instead of System.out or System.err.%n" - + "Please switch to using org.slf4j.Logger.%n" - + "See: https://cloud.google.com/dataflow/pipelines/logging"); - // This limits the number of bytes which we buffer in case we don't see a newline character. - private static final int BUFFER_LIMIT = 1 << 14; // 16384 bytes - private static final byte[] NEW_LINE = System.lineSeparator().getBytes(StandardCharsets.UTF_8); - private Logger logger; - private ByteArrayOutputStream baos; - private Level logLevel; - private int matched = 0; - - private JulLoggerAdapterOutputStream(String name, Level logLevel) { - this.logger = Logger.getLogger(name); - this.logLevel = logLevel; - this.baos = new ByteArrayOutputStream(BUFFER_LIMIT); - } - - @Override - public void write(int b) { - if (outputWarning.compareAndSet(false, true)) { - logger.warning(LOGGING_DISCLAIMER); - } - baos.write(b); - // Check to see if the next byte matches further into new line string. - if (NEW_LINE[matched] == b) { - matched += 1; - // If we have matched the entire new line, output the contents of the buffer. - if (matched == NEW_LINE.length) { - output(); - } - } else { - // Reset the match - matched = 0; - } - if (baos.size() == BUFFER_LIMIT) { - output(); - } - } - - @Override - public void flush() throws IOException { - output(); - } - - @Override - public void close() throws IOException { - output(); - } - - private void output() { - // If nothing was output, do not log anything - if (baos.size() == 0) { - return; - } - try { - String message = baos.toString(StandardCharsets.UTF_8.name()); - // Strip the new line if it exists - if (message.endsWith(System.lineSeparator())) { - message = message.substring(0, message.length() - System.lineSeparator().length()); - } - logger.log(logLevel, message); - } catch (UnsupportedEncodingException e) { - logger.severe(String.format("Unable to decode string output to stdout/stderr %s", e)); - } - matched = 0; - baos.reset(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandlerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandlerTest.java deleted file mode 100644 index 78705059f1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingHandlerTest.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.logging; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.testing.RestoreDataflowLoggingMDC; -import com.google.common.base.Supplier; -import com.google.common.base.Throwables; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.logging.Level; -import java.util.logging.LogRecord; - -/** Unit tests for {@link DataflowWorkerLoggingHandler}. */ -@RunWith(JUnit4.class) -public class DataflowWorkerLoggingHandlerTest { - @Rule public TestRule restoreMDC = new RestoreDataflowLoggingMDC(); - - /** Returns the json-escaped string for the platform specific line separator.*/ - private static String escapeNewline() { - try { - String quoted = new ObjectMapper().writeValueAsString(System.lineSeparator()); - int len = quoted.length(); - if (len < 3 || quoted.charAt(0) != '\"' || quoted.charAt(len - 1) != '\"') { - return "Failed to escape newline; expected quoted intermediate value"; - } - // Strip the quotes. - return quoted.substring(1, len - 1); - - } catch (JsonProcessingException e) { - throw Throwables.propagate(e); - } - } - - // Typically \n or \r\n - private static String escapedNewline = escapeNewline(); - - private static class FixedOutputStreamFactory implements Supplier { - private OutputStream[] streams; - private int next = 0; - - public FixedOutputStreamFactory(OutputStream... streams) { - this.streams = streams; - } - - @Override - public OutputStream get() { - return streams[next++]; - } - } - - /** - * Encodes a LogRecord into a Json string. - */ - private static String createJson(LogRecord record) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - FixedOutputStreamFactory factory = new FixedOutputStreamFactory(output); - DataflowWorkerLoggingHandler handler = new DataflowWorkerLoggingHandler(factory, 0); - // Format the record as JSON. - handler.publish(record); - // Decode the binary output as UTF-8 and return the generated string. - return new String(output.toByteArray(), StandardCharsets.UTF_8); - } - - @Test - public void testOutputStreamRollover() throws IOException { - ByteArrayOutputStream first = new ByteArrayOutputStream(); - ByteArrayOutputStream second = new ByteArrayOutputStream(); - - LogRecord record = createLogRecord("test.message", null); - String expected = "{\"timestamp\":{\"seconds\":0,\"nanos\":1000000},\"severity\":\"INFO\"," - + "\"message\":\"test.message\",\"thread\":\"2\",\"logger\":\"LoggerName\"}" - + System.lineSeparator(); - - FixedOutputStreamFactory factory = new FixedOutputStreamFactory(first, second); - DataflowWorkerLoggingHandler handler - = new DataflowWorkerLoggingHandler(factory, expected.length() + 1 /* sizelimit */); - - // Using |expected|+1 for size limit means that we will rollover after writing 2 log messages. - // We thus expect to see 2 messsages written to 'first' and 1 message to 'second', - - handler.publish(record); - handler.publish(record); - handler.publish(record); - - assertEquals(expected + expected, new String(first.toByteArray(), StandardCharsets.UTF_8)); - assertEquals(expected, new String(second.toByteArray(), StandardCharsets.UTF_8)); - } - - @Test - public void testWithUnsetValuesInMDC() throws IOException { - assertEquals( - "{\"timestamp\":{\"seconds\":0,\"nanos\":1000000},\"severity\":\"INFO\"," - + "\"message\":\"test.message\",\"thread\":\"2\",\"logger\":\"LoggerName\"}" - + System.lineSeparator(), - createJson(createLogRecord("test.message", null))); - } - - @Test - public void testWithAllValuesInMDC() throws IOException { - DataflowWorkerLoggingMDC.setJobId("testJobId"); - DataflowWorkerLoggingMDC.setStageName("testStage"); - DataflowWorkerLoggingMDC.setStepName("testStep"); - DataflowWorkerLoggingMDC.setWorkerId("testWorkerId"); - DataflowWorkerLoggingMDC.setWorkId("testWorkId"); - - createLogRecord("test.message", null); - assertEquals( - "{\"timestamp\":{\"seconds\":0,\"nanos\":1000000},\"severity\":\"INFO\"," - + "\"message\":\"test.message\",\"thread\":\"2\",\"job\":\"testJobId\"," - + "\"stage\":\"testStage\",\"step\":\"testStep\",\"worker\":\"testWorkerId\"," - + "\"work\":\"testWorkId\",\"logger\":\"LoggerName\"}" - + System.lineSeparator(), - createJson(createLogRecord("test.message", null))); - } - - @Test - public void testWithMessage() throws IOException { - DataflowWorkerLoggingMDC.setJobId("testJobId"); - DataflowWorkerLoggingMDC.setWorkerId("testWorkerId"); - DataflowWorkerLoggingMDC.setWorkId("testWorkId"); - - assertEquals( - "{\"timestamp\":{\"seconds\":0,\"nanos\":1000000},\"severity\":\"INFO\"," - + "\"message\":\"test.message\",\"thread\":\"2\",\"job\":\"testJobId\"," - + "\"worker\":\"testWorkerId\",\"work\":\"testWorkId\",\"logger\":\"LoggerName\"}" - + System.lineSeparator(), - createJson(createLogRecord("test.message", null))); - } - - @Test - public void testWithMessageAndException() throws IOException { - DataflowWorkerLoggingMDC.setJobId("testJobId"); - DataflowWorkerLoggingMDC.setWorkerId("testWorkerId"); - DataflowWorkerLoggingMDC.setWorkId("testWorkId"); - - assertEquals( - "{\"timestamp\":{\"seconds\":0,\"nanos\":1000000},\"severity\":\"INFO\"," - + "\"message\":\"test.message\",\"thread\":\"2\",\"job\":\"testJobId\"," - + "\"worker\":\"testWorkerId\",\"work\":\"testWorkId\",\"logger\":\"LoggerName\"," - + "\"exception\":\"java.lang.Throwable: exception.test.message" - + escapedNewline - + "\\tat declaringClass1.method1(file1.java:1)" - + escapedNewline - + "\\tat declaringClass2.method2(file2.java:1)" - + escapedNewline - + "\\tat declaringClass3.method3(file3.java:1)" - + escapedNewline - + "\"}" - + System.lineSeparator(), - createJson(createLogRecord("test.message", createThrowable()))); - } - - @Test - public void testWithException() throws IOException { - DataflowWorkerLoggingMDC.setJobId("testJobId"); - DataflowWorkerLoggingMDC.setWorkerId("testWorkerId"); - DataflowWorkerLoggingMDC.setWorkId("testWorkId"); - - assertEquals( - "{\"timestamp\":{\"seconds\":0,\"nanos\":1000000},\"severity\":\"INFO\"," - + "\"thread\":\"2\",\"job\":\"testJobId\",\"worker\":\"testWorkerId\"," - + "\"work\":\"testWorkId\",\"logger\":\"LoggerName\"," - + "\"exception\":\"java.lang.Throwable: exception.test.message" - + escapedNewline - + "\\tat declaringClass1.method1(file1.java:1)" - + escapedNewline - + "\\tat declaringClass2.method2(file2.java:1)" - + escapedNewline - + "\\tat declaringClass3.method3(file3.java:1)" - + escapedNewline - + "\"}" - + System.lineSeparator(), - createJson(createLogRecord(null, createThrowable()))); - } - - @Test - public void testWithoutExceptionOrMessage() throws IOException { - DataflowWorkerLoggingMDC.setJobId("testJobId"); - DataflowWorkerLoggingMDC.setWorkerId("testWorkerId"); - DataflowWorkerLoggingMDC.setWorkId("testWorkId"); - - assertEquals( - "{\"timestamp\":{\"seconds\":0,\"nanos\":1000000},\"severity\":\"INFO\"," - + "\"thread\":\"2\",\"job\":\"testJobId\",\"worker\":\"testWorkerId\"," - + "\"work\":\"testWorkId\",\"logger\":\"LoggerName\"}" - + System.lineSeparator(), - createJson(createLogRecord(null, null))); - } - - /** - * @return A throwable with a fixed stack trace. - */ - private Throwable createThrowable() { - Throwable throwable = new Throwable("exception.test.message"); - throwable.setStackTrace(new StackTraceElement[]{ - new StackTraceElement("declaringClass1", "method1", "file1.java", 1), - new StackTraceElement("declaringClass2", "method2", "file2.java", 1), - new StackTraceElement("declaringClass3", "method3", "file3.java", 1), - }); - return throwable; - } - - /** - * Creates and returns a LogRecord with a given message and throwable. - * - * @param message The message to place in the {@link LogRecord} - * @param throwable The throwable to place in the {@link LogRecord} - * @return A {@link LogRecord} with the given message and throwable. - */ - private LogRecord createLogRecord(String message, Throwable throwable) { - LogRecord logRecord = new LogRecord(Level.INFO, message); - logRecord.setLoggerName("LoggerName"); - logRecord.setMillis(1L); - logRecord.setThreadID(2); - logRecord.setThrown(throwable); - return logRecord; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializerTest.java deleted file mode 100644 index 0af9f877b1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingInitializerTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.logging; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions; -import com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.WorkerLogLevelOverrides; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.junit.runners.model.Statement; - -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; - -/** Unit tests for {@link DataflowWorkerLoggingInitializer}. */ -@RunWith(JUnit4.class) -public class DataflowWorkerLoggingInitializerTest { - @After - public void tearDown() { - LogManager.getLogManager().reset(); - DataflowWorkerLoggingInitializer.reset(); - } - - @Test - public void testWithDefaults() { - DataflowWorkerLoggingOptions options = - PipelineOptionsFactory.as(DataflowWorkerLoggingOptions.class); - - DataflowWorkerLoggingInitializer.initialize(); - DataflowWorkerLoggingInitializer.configure(options); - - Logger rootLogger = LogManager.getLogManager().getLogger(""); - assertEquals(1, rootLogger.getHandlers().length); - assertEquals(Level.INFO, rootLogger.getLevel()); - assertTrue(isDataflowWorkerLoggingHandler(rootLogger.getHandlers()[0], Level.ALL)); - } - - @Test - public void testWithConfigurationOverride() { - DataflowWorkerLoggingOptions options = - PipelineOptionsFactory.as(DataflowWorkerLoggingOptions.class); - options.setDefaultWorkerLogLevel(DataflowWorkerLoggingOptions.Level.WARN); - - DataflowWorkerLoggingInitializer.initialize(); - DataflowWorkerLoggingInitializer.configure(options); - - Logger rootLogger = LogManager.getLogManager().getLogger(""); - assertEquals(1, rootLogger.getHandlers().length); - assertEquals(Level.WARNING, rootLogger.getLevel()); - assertTrue(isDataflowWorkerLoggingHandler(rootLogger.getHandlers()[0], Level.ALL)); - } - - @Test - public void testWithCustomLogLevels() { - DataflowWorkerLoggingOptions options = - PipelineOptionsFactory.as(DataflowWorkerLoggingOptions.class); - options.setWorkerLogLevelOverrides(new WorkerLogLevelOverrides() - .addOverrideForName("A", DataflowWorkerLoggingOptions.Level.DEBUG) - .addOverrideForName("B", DataflowWorkerLoggingOptions.Level.ERROR)); - - DataflowWorkerLoggingInitializer.initialize(); - DataflowWorkerLoggingInitializer.configure(options); - - Logger aLogger = LogManager.getLogManager().getLogger("A"); - assertEquals(0, aLogger.getHandlers().length); - assertEquals(Level.FINE, aLogger.getLevel()); - assertTrue(aLogger.getUseParentHandlers()); - - Logger bLogger = LogManager.getLogManager().getLogger("B"); - assertEquals(Level.SEVERE, bLogger.getLevel()); - assertEquals(0, bLogger.getHandlers().length); - assertTrue(aLogger.getUseParentHandlers()); - } - - private boolean isDataflowWorkerLoggingHandler(Handler handler, Level level) { - return handler instanceof DataflowWorkerLoggingHandler && level.equals(handler.getLevel()); - } - - @Test - public void testSystemOutToLogger() throws Throwable { - DataflowWorkerLoggingInitializer.initialize(); - Description description = Description.createTestDescription( - DataflowWorkerLoggingInitializerTest.class, "testSystemOutToLogger"); - ExpectedLogs systemOut = ExpectedLogs.none("System.out"); - // We evaluate the test rule with the logging inside of it explicitly since - // DataflowWorkerLoggingInitializer.initialize() resets all log handlers - // not allowing us to use ExpectedLogs as a test rule. - systemOut.apply(new Statement() { - @Override - public void evaluate() { - System.out.println("afterInitialization"); - } - }, description).evaluate(); - systemOut.verifyInfo("afterInitialization"); - } - - @Test - public void testSystemErrToLogger() throws Throwable { - DataflowWorkerLoggingInitializer.initialize(); - Description description = Description.createTestDescription( - DataflowWorkerLoggingInitializerTest.class, "testSystemErrToLogger"); - ExpectedLogs systemErr = ExpectedLogs.none("System.err"); - // We evaluate the test rule with the logging inside of it explicitly since - // DataflowWorkerLoggingInitializer.initialize() resets all log handlers - // not allowing us to use ExpectedLogs as a test rule. - systemErr.apply(new Statement() { - @Override - public void evaluate() { - System.err.println("afterInitialization"); - } - }, description).evaluate(); - systemErr.verifyError("afterInitialization"); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactoryTest.java deleted file mode 100644 index 07ea5aafe6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/worker/logging/JulLoggerPrintStreamAdapterFactoryTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.logging; - -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.PrintStream; -import java.util.logging.Level; - -/** Tests for {@link JulLoggerPrintStreamAdapterFactory}. */ -@RunWith(JUnit4.class) -public class JulLoggerPrintStreamAdapterFactoryTest { - private static final String NAME = "test"; - @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(NAME); - - @Test - public void testLogOnNewLine() { - PrintStream printStream = JulLoggerPrintStreamAdapterFactory.create(NAME, Level.INFO); - printStream.println("blah"); - expectedLogs.verifyInfo("blah"); - } - - @Test - public void testLogOnlyUptoNewLine() { - PrintStream printStream = JulLoggerPrintStreamAdapterFactory.create(NAME, Level.INFO); - printStream.println("blah"); - printStream.print("foo"); - expectedLogs.verifyInfo("blah"); - expectedLogs.verifyNotLogged("foo"); - } - - @Test - public void testLogMultiLine() { - PrintStream printStream = JulLoggerPrintStreamAdapterFactory.create(NAME, Level.INFO); - printStream.format("blah%nfoo%n"); - expectedLogs.verifyInfo("blah"); - expectedLogs.verifyInfo("foo"); - } - - @Test - public void testDontLogIfNoNewLine() { - PrintStream printStream = JulLoggerPrintStreamAdapterFactory.create(NAME, Level.INFO); - printStream.print("blah"); - expectedLogs.verifyNotLogged("blah"); - } - - @Test - public void testLogOnFlush() { - PrintStream printStream = JulLoggerPrintStreamAdapterFactory.create(NAME, Level.INFO); - printStream.print("blah"); - printStream.flush(); - expectedLogs.verifyInfo("blah"); - } - - @Test - public void testLogOnClose() { - PrintStream printStream = JulLoggerPrintStreamAdapterFactory.create(NAME, Level.INFO); - printStream.print("blah"); - printStream.close(); - expectedLogs.verifyInfo("blah"); - } -} - From 38b5bc030b6fe8038ceeaf2acef54d59b1c904cf Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 10 Feb 2016 10:21:09 -0800 Subject: [PATCH 116/751] Move worker implementation classes of aggregators to worker maven module This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114340519 --- .../dataflow/sdk/util/CloudMetricUtils.java | 73 ------------------- .../dataflow/sdk/util/common/Metric.java | 49 ------------- .../sdk/util/CloudMetricUtilsTest.java | 66 ----------------- .../dataflow/sdk/util/common/MetricTest.java | 40 ---------- 4 files changed, 228 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Metric.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/MetricTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtils.java deleted file mode 100644 index 8a66fc3f21..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtils.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.services.dataflow.model.MetricStructuredName; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.util.common.Metric; -import com.google.cloud.dataflow.sdk.util.common.Metric.DoubleMetric; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Utilities for working with Dataflow API Metrics. - */ -public class CloudMetricUtils { - // Do not instantiate. - private CloudMetricUtils() {} - - /** - * Returns a List of {@link MetricUpdate}s representing the given Metrics. - */ - public static List extractCloudMetrics( - Collection> metrics, - String workerId) { - List cloudMetrics = new ArrayList<>(metrics.size()); - for (Metric metric : metrics) { - cloudMetrics.add(extractCloudMetric(metric, workerId)); - } - return cloudMetrics; - } - - /** - * Returns a {@link MetricUpdate} representing the given Metric. - */ - public static MetricUpdate extractCloudMetric(Metric metric, String workerId) { - if (metric instanceof DoubleMetric) { - return extractCloudMetric( - metric, - ((DoubleMetric) metric).getValue(), - workerId); - } else { - throw new IllegalArgumentException("unexpected kind of Metric"); - } - } - - private static MetricUpdate extractCloudMetric( - Metric metric, Double value, String workerId) { - MetricStructuredName name = new MetricStructuredName(); - name.setName(metric.getName()); - Map context = new HashMap<>(); - context.put("workerId", workerId); - name.setContext(context); - return new MetricUpdate().setName(name).setScalar(CloudObject.forFloat(value)); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Metric.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Metric.java deleted file mode 100644 index 5245abf559..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Metric.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -/** - * A metric (e.g., CPU usage) that can be reported by a worker. - * - * @param the type of the metric's value - */ -public abstract class Metric { - String name; - T value; - - public Metric(String name, T value) { - this.name = name; - this.value = value; - } - - public String getName() { - return name; - } - - public T getValue() { - return value; - } - - /** - * A double-valued Metric. - */ - public static class DoubleMetric extends Metric { - public DoubleMetric(String name, double value) { - super(name, value); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtilsTest.java deleted file mode 100644 index ff3451f51a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudMetricUtilsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.api.services.dataflow.model.MetricStructuredName; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.util.common.Metric; -import com.google.cloud.dataflow.sdk.util.common.Metric.DoubleMetric; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** Unit tests for {@link CloudMetricUtils}. */ -@RunWith(JUnit4.class) -public class CloudMetricUtilsTest { - private void addDoubleMetric(String name, double value, String workerId, - List> metrics, - List cloudMetrics) { - metrics.add(new DoubleMetric(name, value)); - MetricStructuredName structuredName = new MetricStructuredName(); - structuredName.setName(name); - Map context = new HashMap<>(); - context.put("workerId", workerId); - structuredName.setContext(context); - cloudMetrics.add(new MetricUpdate() - .setName(structuredName) - .setScalar(CloudObject.forFloat(value))); - } - - @Test - public void testExtractCloudMetrics() { - List> metrics = new ArrayList<>(); - List expected = new ArrayList<>(); - String workerId = "worker-id"; - - addDoubleMetric("m1", 3.14, workerId, metrics, expected); - addDoubleMetric("m2", 2.17, workerId, metrics, expected); - addDoubleMetric("m3", -66.666, workerId, metrics, expected); - - List actual = CloudMetricUtils.extractCloudMetrics(metrics, workerId); - - assertEquals(expected, actual); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/MetricTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/MetricTest.java deleted file mode 100644 index d7810c676f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/MetricTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.util.common.Metric.DoubleMetric; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link Metric}. */ -@RunWith(JUnit4.class) -public class MetricTest { - @Test - public void testDoubleMetric() { - String name = "metric-name"; - double value = 3.14; - - DoubleMetric doubleMetric = new DoubleMetric(name, value); - - assertEquals(name, doubleMetric.getName()); - assertEquals((Double) value, doubleMetric.getValue()); - } -} From 39422b9c436d05a5d883add5063edccd445d4399 Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 10 Feb 2016 10:30:13 -0800 Subject: [PATCH 117/751] Remove Base64Utils which is dead code This is for Apache Beam ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114341725 --- .../cloud/dataflow/sdk/util/Base64Utils.java | 30 ----------- .../dataflow/sdk/util/Base64UtilsTest.java | 53 ------------------- 2 files changed, 83 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Base64Utils.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/Base64UtilsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Base64Utils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Base64Utils.java deleted file mode 100644 index 457048eb9c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Base64Utils.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * Utilities related to Base64 encoding. - */ -public class Base64Utils { - /** - * Returns an upper bound of the length of non-chunked Base64 encoded version - * of the string of the given length. - */ - public static int getBase64Length(int length) { - return 4 * ((length + 2) / 3); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/Base64UtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/Base64UtilsTest.java deleted file mode 100644 index 441a3dc7b6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/Base64UtilsTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.api.client.util.Base64.encodeBase64URLSafeString; - -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link Base64Utils}. */ -@RunWith(JUnit4.class) -public class Base64UtilsTest { - void testLength(int length) { - byte[] b = new byte[length]; - // Make sure that the estimated length is an upper bound. - assertThat( - Base64Utils.getBase64Length(length), - greaterThanOrEqualTo(encodeBase64URLSafeString(b).length())); - // Make sure that it's a tight upper bound (no more than 4 characters off). - assertThat( - Base64Utils.getBase64Length(length), - lessThan(4 + encodeBase64URLSafeString(b).length())); - } - - @Test - public void getBase64Length() { - for (int i = 0; i < 100; ++i) { - testLength(i); - } - for (int i = 1000; i < 1100; ++i) { - testLength(i); - } - } -} From a0e271582865c63cdef088466d64524c0cb206eb Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 10 Feb 2016 16:57:01 -0800 Subject: [PATCH 118/751] Move over several Dataflow worker specific classes to the worker maven module This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114385369 --- .../sdk/runners/worker/AvroReader.java | 184 ---------- .../sdk/runners/worker/IsmFormat.java | 3 +- .../sdk/util/BoundedQueueExecutor.java | 70 ---- .../dataflow/sdk/util/CloudSourceUtils.java | 51 --- .../sdk/util/PCollectionViewWindow.java | 67 ---- .../sdk/util/ScalableBloomFilter.java | 331 ------------------ .../sdk/util/WeightedSideInputReader.java | 48 --- .../sdk/util/CloudSourceUtilsTest.java | 83 ----- .../sdk/util/ScalableBloomFilterTest.java | 169 --------- 9 files changed, 1 insertion(+), 1005 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BoundedQueueExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedSideInputReader.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilterTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java deleted file mode 100644 index 90452c1f04..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroReader.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.io.AvroSource; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.OffsetBasedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import org.apache.avro.generic.GenericRecord; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A source that reads Avro files. - * - * @param the type of the elements read from the source - */ -public class AvroReader extends NativeReader> { - private static final Logger LOG = LoggerFactory.getLogger(AvroReader.class); - - @Nullable - final Long startPosition; - @Nullable - final Long endPosition; - final String filename; - final AvroSource avroSource; - final AvroCoder avroCoder; - final PipelineOptions options; - - @SuppressWarnings("unchecked") - public AvroReader(String filename, @Nullable Long startPosition, @Nullable Long endPosition, - AvroCoder coder, @Nullable PipelineOptions options) { - - this.avroCoder = coder; - - this.startPosition = startPosition; - this.endPosition = endPosition; - this.filename = filename; - this.options = options; - - Class type = avroCoder.getType(); - AvroSource source; - if (type.equals(GenericRecord.class)) { - source = (AvroSource) AvroSource.from(filename).withSchema(avroCoder.getSchema()); - } else { - source = AvroSource.from(filename).withSchema(type); - } - - - this.avroSource = source; - } - - @Override - public AvroFileIterator iterator() throws IOException { - Long endPosition = this.endPosition; - Long startPosition = this.startPosition; - if (endPosition == null) { - endPosition = Long.MAX_VALUE; - } - if (startPosition == null) { - startPosition = 0L; - } - BoundedSource.BoundedReader reader; - if (startPosition == 0 && endPosition == Long.MAX_VALUE) { - // Read entire file (or collection of files). - reader = avroSource.createReader(options); - } else { - // Read a subrange of file. - reader = avroSource.createForSubrangeOfFile(filename, startPosition, endPosition) - .createReader(options); - } - return new AvroFileIterator((AvroSource.AvroReader) reader); - } - - class AvroFileIterator extends NativeReaderIterator> { - private final AvroSource.AvroReader reader; - private long blockOffset = -1; - private WindowedValue current; - - public AvroFileIterator(AvroSource.AvroReader reader) { - this.reader = reader; - } - - @Override - public boolean start() throws IOException { - if (!reader.start()) { - return false; - } - updateBlockOffsetAndCurrent(); - return true; - } - - @Override - public boolean advance() throws IOException { - if (!reader.advance()) { - return false; - } - updateBlockOffsetAndCurrent(); - return true; - } - - private void updateBlockOffsetAndCurrent() { - // Coarse-grained reporting of input bytes consumed. - // After completing reading a block, the block offset changes. - long currentOffset = reader.getCurrentBlockOffset(); - if (currentOffset != blockOffset) { - notifyElementRead(reader.getCurrentBlockSize()); - blockOffset = currentOffset; - } - current = WindowedValue.valueInGlobalWindow(reader.getCurrent()); - } - - @Override - public WindowedValue getCurrent() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return current; - } - - @Override - public Progress getProgress() { - Double readerProgress = reader.getFractionConsumed(); - if (readerProgress == null) { - return null; - } - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - progress.setFractionConsumed(readerProgress); - return cloudProgressToReaderProgress(progress); - } - - @Override - public void close() throws IOException { - reader.close(); - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - ApproximateSplitRequest splitProgress = - SourceTranslationUtils.splitRequestToApproximateSplitRequest(splitRequest); - double splitAtFraction = splitProgress.getFractionConsumed(); - LOG.info("Received request for dynamic split at {}", splitAtFraction); - OffsetBasedSource residual = reader.splitAtFraction(splitAtFraction); - if (residual == null) { - LOG.info("Rejected split request for split at {}", splitAtFraction); - return null; - } - com.google.api.services.dataflow.model.Position acceptedPosition = - new com.google.api.services.dataflow.model.Position(); - acceptedPosition.setByteOffset(residual.getStartOffset()); - LOG.info("Accepted split for position {} which resulted in a new source with byte offset {}", - splitAtFraction, residual.getStartOffset()); - return new DynamicSplitResultWithPosition( - SourceTranslationUtils.cloudPositionToReaderPosition(acceptedPosition)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java index 182d3f2464..318de9b5b8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java @@ -32,7 +32,6 @@ import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.RandomAccessData; -import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter; import com.google.cloud.dataflow.sdk.util.VarInt; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; @@ -67,7 +66,7 @@ *

    An Ism file is composed of these high level sections (in order): *

      *
    • shard block
    • - *
    • bloom filter (See {@link ScalableBloomFilter} for details on encoding format)
    • + *
    • bloom filter (See {@code ScalableBloomFilter} for details on encoding format)
    • *
    • shard index
    • *
    • footer (See {@link Footer} for details on encoding format)
    • *
    diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BoundedQueueExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BoundedQueueExecutor.java deleted file mode 100644 index aaa71d7bf6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BoundedQueueExecutor.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * Executor that blocks on execute() if its queue is full. - */ -public class BoundedQueueExecutor extends ThreadPoolExecutor { - private static class ReducableSemaphore extends Semaphore { - ReducableSemaphore(int permits) { - super(permits); - } - - @Override - public void reducePermits(int permits) { - super.reducePermits(permits); - } - } - private ReducableSemaphore semaphore; - - public BoundedQueueExecutor(int maximumPoolSize, - long keepAliveTime, - TimeUnit unit, - int maximumQueueSize, - ThreadFactory threadFactory) { - super(maximumPoolSize, maximumPoolSize, keepAliveTime, unit, - new LinkedBlockingQueue(), threadFactory); - this.semaphore = new ReducableSemaphore(maximumQueueSize); - allowCoreThreadTimeOut(true); - } - - // Before adding a Runnable to the queue, acquire the semaphore. - @Override - public void execute(Runnable r) { - semaphore.acquireUninterruptibly(); - super.execute(r); - } - - // Forcibly add something to the queue, ignoring the length limit. - public void forceExecute(Runnable r) { - semaphore.reducePermits(1); - super.execute(r); - } - - // Release the semaphore after taking a Runnable off the queue. - @Override - public void beforeExecute(Thread t, Runnable r) { - semaphore.release(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java deleted file mode 100644 index af3055521f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtils.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.util.HashMap; -import java.util.Map; - -/** - * Utilities for working with Source Dataflow API definitions and - * {@link NativeReader} - * objects. - */ -public class CloudSourceUtils { - /** - * Returns a copy of the source with {@code baseSpecs} flattened into {@code spec}. - * On conflict for a parameter name, values in {@code spec} override values in {@code baseSpecs}, - * and later values in {@code baseSpecs} override earlier ones. - */ - public static Source flattenBaseSpecs(Source source) { - if (source.getBaseSpecs() == null) { - return source; - } - Map params = new HashMap<>(); - for (Map baseSpec : source.getBaseSpecs()) { - params.putAll(baseSpec); - } - params.putAll(source.getSpec()); - - Source result = source.clone(); - result.setSpec(params); - result.setBaseSpecs(null); - return result; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java deleted file mode 100644 index 7cf636eb63..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.util.Objects; - -/** - * A pair of a {@link PCollectionView} and a {@link BoundedWindow}, which can - * be thought of as window "of" the view. This is a value class for use e.g. - * as a compound cache key. - * - * @param the type of the underlying PCollectionView - */ -public final class PCollectionViewWindow { - - private final PCollectionView view; - private final BoundedWindow window; - - private PCollectionViewWindow(PCollectionView view, BoundedWindow window) { - this.view = view; - this.window = window; - } - - public static PCollectionViewWindow of(PCollectionView view, BoundedWindow window) { - return new PCollectionViewWindow<>(view, window); - } - - public PCollectionView getView() { - return view; - } - - public BoundedWindow getWindow() { - return window; - } - - @Override - public boolean equals(Object otherObject) { - if (!(otherObject instanceof PCollectionViewWindow)) { - return false; - } - @SuppressWarnings("unchecked") - PCollectionViewWindow other = (PCollectionViewWindow) otherObject; - return getView().equals(other.getView()) && getWindow().equals(other.getWindow()); - } - - @Override - public int hashCode() { - return Objects.hash(getView(), getWindow()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilter.java deleted file mode 100644 index b509dcfa28..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilter.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.MoreObjects; -import com.google.common.hash.BloomFilter; -import com.google.common.hash.Funnel; -import com.google.common.hash.PrimitiveSink; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * A Bloom filter implementation with an expected false positive probability of {@code 0.000001} - * which grows dynamically with the number of insertions. For less than {@code 2^20} insertions - * which would modify a Bloom filter, we brute force all the Bloom filter combinations in powers of - * {@code 2} to only produce a scalable Bloom filter with one slice. - * - *

    Otherwise, we use an implementation of - * Scalable Bloom Filters - * by Paulo Sergio Almeida, Carlos Baquero, Nuno Preguica, David Hutchison. Our implementation - * has an effective positive probability of {@code 0.000001}, given that we use a ratio of - * {@code 0.9} and a scaling factor of {@code 2}. - */ -public class ScalableBloomFilter implements Serializable { - /** - * A {@link Coder} for scalable Bloom filters. The encoded format is: - *

      - *
    • var int encoding of number of Bloom filter slices - *
    • N Bloom filter slices - *
    - * - *

    The encoded form of each Bloom filter slice is: - *

      - *
    • 1 signed byte for the strategy - *
    • 1 unsigned byte for the number of hash functions - *
    • 1 big endian int, the number of longs in our bitset - *
    • N big endian longs of our bitset - *
    - */ - public static class ScalableBloomFilterCoder extends AtomicCoder { - private static final ScalableBloomFilterCoder INSTANCE = new ScalableBloomFilterCoder(); - - @JsonCreator - public static ScalableBloomFilterCoder of() { - return INSTANCE; - } - - @Override - public void encode(ScalableBloomFilter value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - VarInt.encode(value.bloomFilterSlices.size(), outStream); - for (BloomFilter bloomFilter : value.bloomFilterSlices) { - bloomFilter.writeTo(outStream); - } - } - - @Override - public ScalableBloomFilter decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - int numberOfBloomFilters = VarInt.decodeInt(inStream); - List> bloomFilters = new ArrayList<>(numberOfBloomFilters); - for (int i = 0; i < numberOfBloomFilters; ++i) { - bloomFilters.add(BloomFilter.readFrom(inStream, ByteBufferFunnel.INSTANCE)); - } - return new ScalableBloomFilter(bloomFilters); - } - - @Override - public boolean consistentWithEquals() { - return true; - } - } - - private final List> bloomFilterSlices; - private ScalableBloomFilter(List> bloomFilters) { - this.bloomFilterSlices = bloomFilters; - } - - /** - * Returns false if the Bloom filter definitely does not contain the byte - * representation of an element contained in {@code buf} from {@code [offset, offset + length)}. - */ - public boolean mightContain(byte[] buf, int offset, int length) { - ByteBuffer byteBuffer = ByteBuffer.wrap(buf, offset, length); - return mightContain(byteBuffer); - } - - /** - * Returns false if the Bloom filter definitely does not contain the byte - * representation of an element contained in {@code byteBuffer} from {@code [position, limit)}. - */ - public boolean mightContain(ByteBuffer byteBuffer) { - for (int i = bloomFilterSlices.size() - 1; i >= 0; i--) { - if (bloomFilterSlices.get(i).mightContain(byteBuffer)) { - return true; - } - } - return false; - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (!(other instanceof ScalableBloomFilter)) { - return false; - } - ScalableBloomFilter scalableBloomFilter = (ScalableBloomFilter) other; - if (bloomFilterSlices.size() != scalableBloomFilter.bloomFilterSlices.size()) { - return false; - } - for (int i = 0; i < bloomFilterSlices.size(); ++i) { - if (!bloomFilterSlices.get(i).equals(scalableBloomFilter.bloomFilterSlices.get(i))) { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - return bloomFilterSlices.hashCode(); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(ScalableBloomFilter.class) - .add("bloomFilterSlices", bloomFilterSlices) - .toString(); - } - - @VisibleForTesting - int numberOfBloomFilterSlices() { - return bloomFilterSlices.size(); - } - - /** - * Returns a scalable Bloom filter builder allowing one to construct a Bloom filter - * with an expected false positive probability of {@code 0.000001} irrespective - * of the number of elements inserted. - */ - public static Builder builder() { - return builder(Builder.MAX_INSERTIONS_FOR_ADD_TO_ALL_MODE_LOG_2); - } - - @VisibleForTesting - static Builder builder(int maxInsertionsForAddToAllModeLog2) { - return new Builder(maxInsertionsForAddToAllModeLog2); - } - - /** - * A scalable Bloom filter builder which during the build process will attempt to - * create a Bloom filter no larger than twice the required size for small Bloom filters. - * For large Bloom filters, we create a list of Bloom filters which are successively twice as - * large as the previous which we insert elements into. - * - *

    This scalable Bloom filter builder uses 8mb of memory per instance to start when - * fewer than {@code 2^20} elements have been inserted. Afterwards, it increases in space usage - * by a factor of {@code 2.2} for every doubling in the number of unique insertions. - */ - public static class Builder { - private static final long MAX_ELEMENTS = 1L << 62; - private static final int MAX_INSERTIONS_FOR_ADD_TO_ALL_MODE_LOG_2 = 20; - private static final double DEFAULT_FALSE_POSITIVE_PROBABILITY = 0.000001; - private static final double RATIO = 0.9; - - private enum Mode { - ADD_TO_ALL, ADD_TO_LAST - } - - private final List> bloomFilters; - private Mode mode; - private long numberOfInsertions; - - private Builder(int maxInsertionsForAddToAllModeLog2) { - checkArgument(maxInsertionsForAddToAllModeLog2 < Long.SIZE - 1, - "%s does not support an initial size with more than 2^63 elements.", - ScalableBloomFilter.class.getSimpleName()); - this.bloomFilters = new ArrayList<>(); - this.mode = Mode.ADD_TO_ALL; - // 1, 2, 4, 8, 16, 32, ... - for (int i = 0; i <= maxInsertionsForAddToAllModeLog2; ++i) { - bloomFilters.add(BloomFilter.create( - ByteBufferFunnel.INSTANCE, - 1 << i, - DEFAULT_FALSE_POSITIVE_PROBABILITY)); - } - } - - /** - * Returns true if the Bloom filter was modified by inserting the byte - * representation of an element contained in {@code buf} from {@code [offset, offset + length)}. - */ - public boolean put(final byte[] buf, final int off, final int len) { - ByteBuffer buffer = ByteBuffer.wrap(buf, off, len); - return put(buffer); - } - - /** - * Returns true if the Bloom filter was modified by inserting the byte - * representation of an element contained in {@code byteBuffer} from {@code [position, limit)}. - */ - public boolean put(final ByteBuffer byteBuffer) { - // Check to see if we gain any information by adding this element. - switch (mode) { - case ADD_TO_ALL: - if (bloomFilters.get(bloomFilters.size() - 1).mightContain(byteBuffer)) { - // We do not gain any information by adding this element - return false; - } - break; - case ADD_TO_LAST: - for (int i = bloomFilters.size() - 1; i >= 0; i--) { - if (bloomFilters.get(i).mightContain(byteBuffer)) { - // One of the Bloom filters already considers that this element exists so skip - // adding it. - return false; - } - } - break; - default: - throw new IllegalStateException("Unknown builder mode: " + mode); - } - - // We now need to add the element to the appropriate Bloom filter(s) depending on the mode. - switch (mode) { - case ADD_TO_ALL: - int bloomFilterToStartWith = - Long.SIZE - Long.numberOfLeadingZeros(numberOfInsertions); - // If we were to attempt to add to a non-existent Bloom filter, we need to - // swap to the other mode. - if (bloomFilterToStartWith == bloomFilters.size()) { - BloomFilter last = bloomFilters.get(bloomFilters.size() - 1); - bloomFilters.clear(); - bloomFilters.add(last); - mode = Mode.ADD_TO_LAST; - addToLast(byteBuffer); - } else { - for (int i = bloomFilterToStartWith; i < bloomFilters.size(); ++i) { - bloomFilters.get(i).put(byteBuffer); - } - } - break; - case ADD_TO_LAST: - addToLast(byteBuffer); - break; - default: - throw new IllegalStateException("Unknown builder mode: " + mode); - } - numberOfInsertions += 1; - return true; - } - - /** - * Returns a scalable Bloom filter with the elements that were added. - */ - public ScalableBloomFilter build() { - switch (mode) { - case ADD_TO_ALL: - int bloomFilterToUse = Long.SIZE - Long.numberOfLeadingZeros(numberOfInsertions); - if (Long.bitCount(numberOfInsertions) == 1) { - bloomFilterToUse -= 1; - } - return new ScalableBloomFilter(Arrays.asList(bloomFilters.get(bloomFilterToUse))); - case ADD_TO_LAST: - return new ScalableBloomFilter(bloomFilters); - default: - throw new IllegalStateException("Unknown builder mode: " + mode); - } - } - - private void addToLast(ByteBuffer byteBuffer) { - // If we are a power of 2, we have hit the number of expected insertions - // for the last Bloom filter and we have to add a new one. - if (Long.bitCount(numberOfInsertions) == 1) { - checkArgument(numberOfInsertions <= MAX_ELEMENTS, - "%s does not support Bloom filter slices with more than 2^63 elements.", - ScalableBloomFilter.class); - bloomFilters.add(BloomFilter.create( - ByteBufferFunnel.INSTANCE, - numberOfInsertions, - DEFAULT_FALSE_POSITIVE_PROBABILITY * Math.pow(RATIO, bloomFilters.size()))); - } - BloomFilter last = bloomFilters.get(bloomFilters.size() - 1); - last.put(byteBuffer); - } - } - - /** - * Writes {@link ByteBuffer}s to {@link PrimitiveSink}s and meant to be used - * with Guava's {@link BloomFilter} API. This {@link Funnel} does not modify the - * underlying byte buffer and assumes that {@code ByteBuffer#array} returns the backing data. - */ - private static class ByteBufferFunnel implements Funnel { - private static final ByteBufferFunnel INSTANCE = new ByteBufferFunnel(); - @Override - public void funnel(ByteBuffer from, PrimitiveSink into) { - into.putBytes(from.array(), from.position(), from.remaining()); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedSideInputReader.java deleted file mode 100644 index 0323f2cafd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedSideInputReader.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -/** - * Extension to {@link SideInputReader} that can approximate the size of the side input. - */ -public interface WeightedSideInputReader extends SideInputReader { - - /** - * Returns the value of the requested {@link PCollectionView} for the given {@link BoundedWindow} - * along with a rough estimate of the number of bytes of memory it consumes. - * - *

    It is valid for a side input value to be {@code null}. In this case, the return - * value of this method must still be non-{@code null}. It should be a {@link Weighted} - * object where {@link WeightedValue#getValue()} returns {@code null} and - * {@link WeightedValue#getWeight()} may still return any non-negative value. - */ - WeightedValue getWeighted(PCollectionView view, BoundedWindow window); - - /** - * Abstract class providing default implementations for methods of - * {@link WeightedSideInputReader}. - */ - abstract static class Defaults implements WeightedSideInputReader { - @Override - public T get(PCollectionView view, BoundedWindow window) { - return getWeighted(view, window).getValue(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtilsTest.java deleted file mode 100644 index 6df36a9c38..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CloudSourceUtilsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.api.services.dataflow.model.Source; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Map; - -/** - * Tests for {@code CloudSourceUtils}. - */ -@RunWith(JUnit4.class) -public class CloudSourceUtilsTest { - @Test - public void testFlattenBaseSpecs() throws Exception { - // G = grandparent, P = parent, C = child. - CloudObject grandparent = CloudObject.forClassName("text"); - addString(grandparent, "G", "g_g"); - addString(grandparent, "GP", "gp_g"); - addString(grandparent, "GC", "gc_g"); - addString(grandparent, "GPC", "gpc_g"); - - CloudObject parent = CloudObject.forClassName("text"); - addString(parent, "P", "p_p"); - addString(parent, "PC", "pc_p"); - addString(parent, "GP", "gp_p"); - addString(parent, "GPC", "gpc_p"); - - CloudObject child = CloudObject.forClassName("text"); - addString(child, "C", "c_c"); - addString(child, "PC", "pc_c"); - addString(child, "GC", "gc_c"); - addString(child, "GPC", "gpc_c"); - - Source source = new Source(); - source.setBaseSpecs(new ArrayList>()); - source.getBaseSpecs().add(grandparent); - source.getBaseSpecs().add(parent); - source.setSpec(child); - source.setCodec(makeCloudEncoding(StringUtf8Coder.class.getName())); - - Source flat = CloudSourceUtils.flattenBaseSpecs(source); - assertNull(flat.getBaseSpecs()); - assertEquals( - StringUtf8Coder.class.getName(), - getString(flat.getCodec(), PropertyNames.OBJECT_TYPE_NAME)); - - CloudObject flatSpec = CloudObject.fromSpec(flat.getSpec()); - assertEquals("g_g", getString(flatSpec, "G")); - assertEquals("p_p", getString(flatSpec, "P")); - assertEquals("c_c", getString(flatSpec, "C")); - assertEquals("gp_p", getString(flatSpec, "GP")); - assertEquals("gc_c", getString(flatSpec, "GC")); - assertEquals("pc_c", getString(flatSpec, "PC")); - assertEquals("gpc_c", getString(flatSpec, "GPC")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilterTest.java deleted file mode 100644 index ad72e29147..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ScalableBloomFilterTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter.Builder; -import com.google.cloud.dataflow.sdk.util.ScalableBloomFilter.ScalableBloomFilterCoder; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.nio.ByteBuffer; - -/** - * Tests for {@link ScalableBloomFilter}. - */ -@RunWith(JUnit4.class) -public class ScalableBloomFilterTest { - private static final ByteBuffer BUFFER = ByteBuffer.wrap(new byte[]{ 0x01, 0x02 }); - - @Test - public void testBuilderModeAddAll() throws Exception { - Builder builder = ScalableBloomFilter.builder(); - assertTrue("Expected Bloom filter to have been modified.", builder.put(BUFFER)); - - // Re-adding should skip and not record the insertion. - assertFalse("Expected Bloom filter to not have been modified.", builder.put(BUFFER)); - - // Verify insertion - int maxValue = insertAndVerifyContents(builder, 31); - - // Verify that we only have one bloom filter instead of many since the number of insertions - // is small. - ScalableBloomFilter bloomFilter = builder.build(); - assertEquals(1, bloomFilter.numberOfBloomFilterSlices()); - verifyCoder(builder.build(), maxValue); - } - - @Test - public void testBuilderModeAddAllModeAtThreshold() throws Exception { - // Use a builder where the insertion threshold to swap to add to last mode is 2^4 elements. - Builder builder = ScalableBloomFilter.builder(4); - - // Verify insertion - int maxValue = insertAndVerifyContents(builder, 16); - - ScalableBloomFilter bloomFilter = builder.build(); - // Verify at the threshold we have only built a single Bloom filter slice. - assertEquals(1, bloomFilter.numberOfBloomFilterSlices()); - - verifyCoder(bloomFilter, maxValue); - } - - @Test - public void testBuilderModeAddAllModeAtThresholdPlusOne() throws Exception { - // Use a builder where the insertion threshold to swap to add to last mode is 2^4 elements. - Builder builder = ScalableBloomFilter.builder(4); - - // Verify insertion - int maxValue = insertAndVerifyContents(builder, 17); - - ScalableBloomFilter bloomFilter = builder.build(); - // Verify that at one over the threshold, we created two Bloom filter slices. - assertEquals(2, bloomFilter.numberOfBloomFilterSlices()); - - verifyCoder(bloomFilter, maxValue); - } - - @Test - public void testBuilderModeAddLastMode() throws Exception { - // Use a builder where the insertion threshold to swap to add to last mode is 2^4 elements. - Builder builder = ScalableBloomFilter.builder(4); - - // Verify insertion - int maxValue = insertAndVerifyContents(builder, (int) Math.pow(2, 12) - 16); - - ScalableBloomFilter bloomFilter = builder.build(); - // Verify that we swapped to the scalable mode. - // This is 9 because we inserted 16 elements swapping us into the add to all mode. - // Then at every power of 2 (e.g. 32, 64, 128, ..) we add another filter. - // Thus we have a filter for every power of 2 from 2^4 to 2^12 giving us 9 filters. - assertEquals(9, bloomFilter.numberOfBloomFilterSlices()); - - verifyCoder(bloomFilter, maxValue); - } - - @Test - public void testScalableBloomFilterCoder() throws Exception { - Builder builderA = ScalableBloomFilter.builder(); - builderA.put(BUFFER); - ScalableBloomFilter filterA = builderA.build(); - Builder builderB = ScalableBloomFilter.builder(); - builderB.put(BUFFER); - ScalableBloomFilter filterB = builderB.build(); - - CoderProperties.coderDecodeEncodeEqual(ScalableBloomFilterCoder.of(), filterA); - CoderProperties.coderDeterministic(ScalableBloomFilterCoder.of(), filterA, filterB); - CoderProperties.coderConsistentWithEquals(ScalableBloomFilterCoder.of(), filterA, filterB); - CoderProperties.coderSerializable(ScalableBloomFilterCoder.of()); - CoderProperties.structuralValueConsistentWithEquals( - ScalableBloomFilterCoder.of(), filterA, filterB); - } - - /** - * Inserts elements {@code 0, 1, ...} until the internal bloom filters have - * been modified {@code maxNumberOfInsertions} times. Returns the largest value inserted. - */ - private int insertAndVerifyContents(Builder builder, int maxNumberOfInsertions) { - ByteBuffer byteBuffer = ByteBuffer.allocate(4); - int value = -1; - while (maxNumberOfInsertions > 0) { - value += 1; - byteBuffer.clear(); - byteBuffer.putInt(value); - byteBuffer.rewind(); - if (builder.put(byteBuffer)) { - maxNumberOfInsertions -= 1; - } - } - - verifyContents(builder.build(), value); - return value; - } - - /** - * Verifies that the bloom filter contains all the values from {@code [0, 1, ..., maxValue]}. - */ - private void verifyContents(ScalableBloomFilter bloomFilter, int maxValue) { - ByteBuffer byteBuffer = ByteBuffer.allocate(4); - // Verify that all the values exist - for (int i = 0; i <= maxValue; ++i) { - byteBuffer.clear(); - byteBuffer.putInt(i); - byteBuffer.rewind(); - assertTrue(bloomFilter.mightContain(byteBuffer)); - } - } - - /** - * Verifies that the coder correctly encodes and decodes and that all the values - * {@code [0, 1, 2, ..., maxValue]} are contained within the decoded bloom filter. - */ - private void verifyCoder(ScalableBloomFilter bloomFilter, int maxValue) throws Exception { - byte[] encodedValue = - CoderUtils.encodeToByteArray(ScalableBloomFilterCoder.of(), bloomFilter); - ScalableBloomFilter decoded = - CoderUtils.decodeFromByteArray(ScalableBloomFilterCoder.of(), encodedValue); - verifyContents(decoded, maxValue); - } -} - From a6c3e409081402630f324c5e8b84278b162c7138 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 10 Feb 2016 17:12:02 -0800 Subject: [PATCH 119/751] ByteKey: a key represented byte[] - wraps the array and provides zero-copy access via ByteString - base for key-value storage systems like Google Cloud Bigtable or Apache HBase ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114386886 --- .../cloud/dataflow/sdk/io/range/ByteKey.java | 170 +++++++++++++++++ .../dataflow/sdk/io/range/ByteKeyTest.java | 178 ++++++++++++++++++ 2 files changed, 348 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java new file mode 100644 index 0000000000..19c560fd5e --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.protobuf.ByteString; +import com.google.protobuf.ByteString.ByteIterator; + +import java.io.Serializable; + +/** + * A class representing a key consisting of an array of bytes. Arbitrary-length + * {@code byte[]} keys are typical in key-value stores such as Google Cloud Bigtable. + * + *

    Instances of {@link ByteKey} are immutable. + * + *

    {@link ByteKey} implements {@link Comparable Comparable<ByteKey>} by comparing the + * arrays in lexicographic order. The smallest {@link ByteKey} is a zero-length array; the successor + * to a key is the same key with an additional 0 byte appended; and keys have unbounded size. + * + *

    Note that the empty {@link ByteKey} compares smaller than all other keys, but some systems + * have the semantic that when an empty {@link ByteKey} is used as an upper bound, it represents + * the largest possible key. In these cases, implementors should use {@link #isEmpty} to test + * whether an upper bound key is empty. + */ +public final class ByteKey implements Comparable, Serializable { + /** + * Creates a new {@link ByteKey} backed by the specified {@link ByteString}. + */ + public static ByteKey of(ByteString value) { + return new ByteKey(value); + } + + /** + * Creates a new {@link ByteKey} backed by a copy of the specified {@code byte[]}. + * + *

    Makes a copy of the underlying array. + */ + public static ByteKey copyFrom(byte[] bytes) { + return of(ByteString.copyFrom(bytes)); + } + + /** + * Creates a new {@link ByteKey} backed by a copy of the specified {@code int[]}. This method is + * primarily used as a convenience to create a {@link ByteKey} in code without casting down to + * signed Java {@link Byte bytes}: + * + *

    {@code
    +   * ByteKey key = ByteKey.of(0xde, 0xad, 0xbe, 0xef);
    +   * }
    + * + *

    Makes a copy of the input. + */ + public static ByteKey of(int... bytes) { + byte[] ret = new byte[bytes.length]; + for (int i = 0; i < bytes.length; ++i) { + ret[i] = (byte) (bytes[i] & 0xff); + } + return ByteKey.copyFrom(ret); + } + + /** + * Returns an immutable {@link ByteString} representing this {@link ByteKey}. + * + *

    Does not copy. + */ + public ByteString getValue() { + return value; + } + + /** + * Returns a newly-allocated {@code byte[]} representing this {@link ByteKey}. + * + *

    Copies the underlying {@code byte[]}. + */ + public byte[] getBytes() { + return value.toByteArray(); + } + + /** + * Returns {@code true} if the {@code byte[]} backing this {@link ByteKey} is of length 0. + */ + public boolean isEmpty() { + return value.isEmpty(); + } + + /** + * {@link ByteKey} implements {@link Comparable Comparable<ByteKey>} by comparing the + * arrays in lexicographic order. The smallest {@link ByteKey} is a zero-length array; the + * successor to a key is the same key with an additional 0 byte appended; and keys have unbounded + * size. + */ + @Override + public int compareTo(ByteKey other) { + checkNotNull(other, "other"); + ByteIterator thisIt = value.iterator(); + ByteIterator otherIt = other.value.iterator(); + while (thisIt.hasNext() && otherIt.hasNext()) { + // (byte & 0xff) converts [-128,127] bytes to [0,255] ints. + int cmp = (thisIt.nextByte() & 0xff) - (otherIt.nextByte() & 0xff); + if (cmp != 0) { + return cmp; + } + } + // If we get here, the prefix of both arrays is equal up to the shorter array. The array with + // more bytes is larger. + return value.size() - other.value.size(); + } + + //////////////////////////////////////////////////////////////////////////////////// + private final ByteString value; + + private ByteKey(ByteString value) { + this.value = value; + } + + /** Array used as a helper in {@link #toString}. */ + private static final char[] HEX = + new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + // Prints the key as a string "[deadbeef]". + @Override + public String toString() { + char[] encoded = new char[2 * value.size() + 2]; + encoded[0] = '['; + int cnt = 1; + ByteIterator iterator = value.iterator(); + while (iterator.hasNext()) { + byte b = iterator.nextByte(); + encoded[cnt] = HEX[(b & 0xF0) >>> 4]; + ++cnt; + encoded[cnt] = HEX[b & 0xF]; + ++cnt; + } + encoded[cnt] = ']'; + return new String(encoded); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ByteKey)) { + return false; + } + ByteKey other = (ByteKey) o; + return (other.value.size() == value.size()) && this.compareTo(other) == 0; + } + + @Override + public int hashCode() { + return value.hashCode(); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java new file mode 100644 index 0000000000..66c5d394ba --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static org.hamcrest.Matchers.lessThan; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Arrays; + +/** + * Tests of {@link ByteKey}. + */ +@RunWith(JUnit4.class) +public class ByteKeyTest { + // A big list of byte[] keys, in ascending sorted order. + private static final ByteKey[] TEST_KEYS = + new ByteKey[] { + ByteKey.of(), + ByteKey.of(0), + ByteKey.of(0, 1), + ByteKey.of(0, 1, 1), + ByteKey.of(0, 1, 2), + ByteKey.of(0, 1, 2, 0xfe), + ByteKey.of(0, 1, 3, 0xfe), + ByteKey.of(0, 0xfe, 0xfe, 0xfe), + ByteKey.of(0, 0xfe, 0xfe, 0xff), + ByteKey.of(0, 0xfe, 0xff, 0), + ByteKey.of(0, 0xff, 0xff, 0), + ByteKey.of(0, 0xff, 0xff, 1), + ByteKey.of(0, 0xff, 0xff, 0xfe), + ByteKey.of(0, 0xff, 0xff, 0xff), + ByteKey.of(1), + ByteKey.of(1, 2), + ByteKey.of(1, 2, 3), + ByteKey.of(3), + ByteKey.of(0xdd), + ByteKey.of(0xfe), + ByteKey.of(0xfe, 0xfe), + ByteKey.of(0xfe, 0xff), + ByteKey.of(0xff), + ByteKey.of(0xff, 0), + ByteKey.of(0xff, 0xfe), + ByteKey.of(0xff, 0xff), + ByteKey.of(0xff, 0xff, 0xff), + ByteKey.of(0xff, 0xff, 0xff, 0xff), + }; + + /** + * Tests {@link ByteKey#compareTo(ByteKey)} using exhaustive testing within a large sorted list + * of keys. + */ + @Test + public void testCompareToExhaustive() { + // Verify that the comparison gives the correct result for all values in both directions. + for (int i = 0; i < TEST_KEYS.length; ++i) { + for (int j = 0; j < TEST_KEYS.length; ++j) { + ByteKey left = TEST_KEYS[i]; + ByteKey right = TEST_KEYS[j]; + int cmp = left.compareTo(right); + if (i < j && !(cmp < 0)) { + fail( + String.format( + "Expected that cmp(%s, %s) < 0, got %d [i=%d, j=%d]", left, right, cmp, i, j)); + } else if (i == j && !(cmp == 0)) { + fail( + String.format( + "Expected that cmp(%s, %s) == 0, got %d [i=%d, j=%d]", left, right, cmp, i, j)); + } else if (i > j && !(cmp > 0)) { + fail( + String.format( + "Expected that cmp(%s, %s) > 0, got %d [i=%d, j=%d]", left, right, cmp, i, j)); + } + } + } + } + + /** + * Tests {@link ByteKey#equals}. + */ + @Test + public void testEquals() { + // Verify that the comparison gives the correct result for all values in both directions. + for (int i = 0; i < TEST_KEYS.length; ++i) { + for (int j = 0; j < TEST_KEYS.length; ++j) { + ByteKey left = TEST_KEYS[i]; + ByteKey right = TEST_KEYS[j]; + boolean eq = left.equals(right); + if (i == j) { + assertTrue(String.format("Expected that %s is equal to itself.", left), eq); + assertTrue( + String.format("Expected that %s is equal to a copy of itself.", left), + left.equals(ByteKey.of(right.getValue()))); + } else { + assertFalse(String.format("Expected that %s is not equal to %s", left, right), eq); + } + } + } + } + + /** + * Tests {@link ByteKey#hashCode}. + */ + @Test + public void testHashCode() { + // Verify that the hashCode is equal when i==j, and usually not equal otherwise. + int collisions = 0; + for (int i = 0; i < TEST_KEYS.length; ++i) { + int left = TEST_KEYS[i].hashCode(); + int leftClone = ByteKey.of(TEST_KEYS[i].getValue()).hashCode(); + assertEquals( + String.format("Expected same hash code for %s and a copy of itself", TEST_KEYS[i]), + left, + leftClone); + for (int j = i + 1; j < TEST_KEYS.length; ++j) { + int right = TEST_KEYS[j].hashCode(); + if (left == right) { + ++collisions; + } + } + } + int totalUnequalTests = TEST_KEYS.length * (TEST_KEYS.length - 1) / 2; + assertThat("Too many hash collisions", collisions, lessThan(totalUnequalTests / 2)); + } + + /** + * Tests {@link ByteKey#toString}. + */ + @Test + public void testToString() { + assertEquals("[]", ByteKey.of().toString()); + assertEquals("[00]", ByteKey.of(0).toString()); + assertEquals("[0000]", ByteKey.of(0x00, 0x00).toString()); + assertEquals( + "[0123456789abcdef]", + ByteKey.of(0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef).toString()); + } + + /** + * Tests {@link ByteKey#isEmpty}. + */ + @Test + public void testIsEmpty() { + assertTrue("[] is empty", ByteKey.of().isEmpty()); + assertFalse("[00]", ByteKey.of(0).isEmpty()); + } + + /** + * Tests {@link ByteKey#getBytes}. + */ + @Test + public void testGetBytes() { + assertTrue("[] equal after getBytes", Arrays.equals(new byte[] {}, ByteKey.of().getBytes())); + assertTrue( + "[00] equal after getBytes", Arrays.equals(new byte[] {0x00}, ByteKey.of(0x00).getBytes())); + } +} From 35dbb0c872039f19d957d7146028eb1e0df4346a Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 11 Feb 2016 12:54:23 -0800 Subject: [PATCH 120/751] Remove duplicate definition of MetricUpdate utilities Moved previous references to point to correct utilities class. This allows for moving remaining cloud counter classes to worker maven module. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114467570 --- .../dataflow/sdk/util/CloudCounterUtils.java | 14 ++ .../sdk/util/CounterAggregatorTest.java | 8 +- .../dataflow/sdk/util/common/CounterTest.java | 132 ++---------------- .../sdk/util/common/CounterTestUtils.java | 42 ------ 4 files changed, 31 insertions(+), 165 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java index b1b50d40f3..4e13e0640f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java @@ -34,6 +34,13 @@ public class CloudCounterUtils { private static final Logger LOG = LoggerFactory.getLogger(CloudCounterUtils.class); + /** + * Extracts MetricUpdate updates from the given counter set. This is used mainly + * for testing. + * + * @param delta specifies whether or not to extract the cumulative + * aggregate values or the deltas since the last extraction. + */ public static List extractCounters( CounterSet counters, boolean delta) { synchronized (counters) { @@ -52,6 +59,13 @@ public static List extractCounters( } } + /** + * Extracts a MetricUpdate update from the given counter. This is used mainly + * for testing. + * + * @param delta specifies whether or not to extract the cumulative + * aggregate value or the delta since the last extraction. + */ public static MetricUpdate extractCounter(Counter counter, boolean delta) { // TODO: Omit no-op counter updates, for counters whose // values haven't changed since the last time we sent them. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java index 47ec579d04..4cc2f6a30e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java @@ -25,7 +25,6 @@ import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; -import com.google.api.services.dataflow.model.MetricUpdate; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; @@ -38,7 +37,7 @@ import com.google.cloud.dataflow.sdk.util.common.CounterProvider; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.cloud.dataflow.sdk.util.common.CounterTestUtils; +import com.google.common.collect.Iterables; import org.hamcrest.Matchers; import org.junit.Assert; @@ -72,10 +71,7 @@ private void testAggregator(List items, aggregator.addValue(item); } - List cloudCounterSet = CounterTestUtils.extractCounterUpdates(counters, false); - Assert.assertEquals(cloudCounterSet.size(), 1); - Assert.assertEquals(cloudCounterSet.get(0), - CounterTestUtils.extractCounterUpdate(expectedCounter, false)); + assertEquals(Iterables.getOnlyElement(counters), expectedCounter); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java index 33d5d3e647..619f523445 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java @@ -16,9 +16,7 @@ package com.google.cloud.dataflow.sdk.util.common; -import static com.google.cloud.dataflow.sdk.util.Values.asBoolean; import static com.google.cloud.dataflow.sdk.util.Values.asDouble; -import static com.google.cloud.dataflow.sdk.util.Values.asLong; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.AND; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; @@ -29,8 +27,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.util.CloudCounterUtils; import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; import org.junit.Rule; @@ -40,9 +36,7 @@ import org.junit.runners.JUnit4; import java.util.Arrays; -import java.util.HashSet; import java.util.List; -import java.util.Set; /** * Unit tests for the {@link Counter} API. @@ -53,101 +47,25 @@ public class CounterTest { @Rule public ExpectedException thrown = ExpectedException.none(); - private static MetricUpdate flush(Counter c) { - // TODO: Move this out into a separate Counter test. - return CounterTestUtils.extractCounterUpdate(c, true); + private static void flush(Counter c) { + switch (c.getKind()) { + case SUM: + case MAX: + case MIN: + case AND: + case OR: + c.getAndResetDelta(); + break; + case MEAN: + c.getAndResetMeanDelta(); + break; + default: + throw new IllegalArgumentException("Unknown counter kind " + c.getKind()); + } } private static final double EPSILON = 0.00000000001; - @Test - public void testNameKindAndCloudCounterRepresentation() { - Counter c1 = Counter.longs("c1", SUM); - Counter c2 = Counter.doubles("c2", MAX); - Counter c3 = Counter.doubles("c3", MIN); - Counter c4 = Counter.doubles("c4", MEAN); - Counter c5 = Counter.ints("c5", MIN); - Counter c6 = Counter.booleans("c6", AND); - Counter c7 = Counter.booleans("c7", OR); - - assertEquals("c1", c1.getName()); - assertEquals(SUM, c1.getKind()); - MetricUpdate cc = flush(c1); - assertEquals("c1", cc.getName().getName()); - assertEquals("SUM", cc.getKind()); - assertEquals(0L, asLong(cc.getScalar()).longValue()); - c1.addValue(123L).addValue(-13L); - cc = flush(c1); - assertEquals(110L, asLong(cc.getScalar()).longValue()); - - assertEquals("c2", c2.getName()); - assertEquals(MAX, c2.getKind()); - cc = flush(c2); - assertEquals("c2", cc.getName().getName()); - assertEquals("MAX", cc.getKind()); - assertEquals(Double.NEGATIVE_INFINITY, asDouble(cc.getScalar()), EPSILON); - c2.resetToValue(0.0).addValue(Math.PI).addValue(Math.E); - cc = flush(c2); - assertEquals(Math.PI, asDouble(cc.getScalar()), EPSILON); - - assertEquals("c3", c3.getName()); - assertEquals(MIN, c3.getKind()); - c3.addValue(Math.PI).addValue(-Math.PI).addValue(-Math.sqrt(2)); - cc = flush(c3); - assertEquals("c3", cc.getName().getName()); - assertEquals("MIN", cc.getKind()); - assertEquals(-Math.PI, asDouble(cc.getScalar()), EPSILON); - - assertEquals("c4", c4.getName()); - assertEquals(MEAN, c4.getKind()); - cc = flush(c4); // zero-count means are not sent to the service - assertEquals(null, cc); - c4.addValue(Math.PI).addValue(Math.E).addValue(Math.sqrt(2)); - cc = flush(c4); - assertEquals("c4", cc.getName().getName()); - assertEquals("MEAN", cc.getKind()); - Object ms = cc.getMeanSum(); - Object mc = cc.getMeanCount(); - assertEquals(Math.PI + Math.E + Math.sqrt(2), asDouble(ms), EPSILON); - assertEquals(3, asLong(mc).longValue()); - c4.addValue(2.0).addValue(5.0); - cc = flush(c4); - ms = cc.getMeanSum(); - mc = cc.getMeanCount(); - assertEquals(7.0, asDouble(ms), EPSILON); - assertEquals(2L, asLong(mc).longValue()); - - assertEquals("c5", c5.getName()); - assertEquals(MIN, c5.getKind()); - cc = flush(c5); - assertEquals("c5", cc.getName().getName()); - assertEquals("MIN", cc.getKind()); - assertEquals(Integer.MAX_VALUE, asLong(cc.getScalar()).longValue()); - c5.addValue(123).addValue(-13); - cc = flush(c5); - assertEquals(-13, asLong(cc.getScalar()).longValue()); - - assertEquals("c6", c6.getName()); - assertEquals(AND, c6.getKind()); - cc = flush(c6); - assertEquals("c6", cc.getName().getName()); - assertEquals("AND", cc.getKind()); - assertEquals(true, asBoolean(cc.getScalar())); - c6.addValue(false); - cc = flush(c6); - assertEquals(false, asBoolean(cc.getScalar())); - - assertEquals("c7", c7.getName()); - assertEquals(OR, c7.getKind()); - cc = flush(c7); - assertEquals("c7", cc.getName().getName()); - assertEquals("OR", cc.getKind()); - assertEquals(false, asBoolean(cc.getScalar())); - c7.addValue(true); - cc = flush(c7); - assertEquals(true, asBoolean(cc.getScalar())); - } - @Test public void testCompatibility() { // Equal counters are compatible, of all kinds. @@ -591,7 +509,6 @@ public void testBoolOr() { assertBool(expectedTotal, expectedDelta, c); } - // Incompatibility tests. @Test(expected = IllegalArgumentException.class) @@ -634,25 +551,6 @@ public void testOrDouble() { Counter.doubles("counter", OR); } - @Test - public void testExtraction() { - Counter[] counters = {Counter.longs("c1", SUM), - Counter.doubles("c2", MAX)}; - CounterSet set = new CounterSet(); - for (Counter c : counters) { - set.addCounter(c); - } - - Set cloudCountersFromSet = new HashSet<>( - CloudCounterUtils.extractCounters(set, true)); - - Set cloudCountersFromArray = - new HashSet<>(CounterTestUtils.extractCounterUpdates(Arrays.asList(counters), true)); - - assertEquals(cloudCountersFromSet, cloudCountersFromArray); - assertEquals(2, cloudCountersFromSet.size()); - } - @Test public void testMergeIncompatibleCounters() { Counter longSums = Counter.longs("longsums", SUM); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java index 5c9af99d14..faaa34110d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java @@ -18,59 +18,17 @@ import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import com.google.api.services.dataflow.model.MetricUpdate; import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.util.CloudCounterUtils; import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; import org.junit.Assert; import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; /** * Utilities for testing {@link Counter}s. */ public class CounterTestUtils { - - /** - * Extracts a MetricUpdate update from the given counter. This is used mainly - * for testing. - * - * @param extractDelta specifies whether or not to extract the cumulative - * aggregate value or the delta since the last extraction. - */ - public static MetricUpdate extractCounterUpdate(Counter counter, - boolean extractDelta) { - // This may be invoked asynchronously with regular counter updates but - // access to counter data is synchronized, so this is safe. - return CloudCounterUtils.extractCounter(counter, extractDelta); - } - - /** - * Extracts MetricUpdate updates from the given counters. This is used mainly - * for testing. - * - * @param extractDelta specifies whether or not to extract the cumulative - * aggregate values or the deltas since the last extraction. - */ - public static List extractCounterUpdates( - Collection> counters, boolean extractDelta) { - // This may be invoked asynchronously with regular counter updates but - // access to counter data is synchronized, so this is safe. Note however - // that the result is NOT an atomic snapshot across all given counters. - List cloudCounters = new ArrayList<>(counters.size()); - for (Counter counter : counters) { - MetricUpdate cloudCounter = extractCounterUpdate(counter, extractDelta); - if (null != cloudCounter) { - cloudCounters.add(cloudCounter); - } - } - return cloudCounters; - } - /** * A utility method that passes the given (unencoded) elements through * coder's registerByteSizeObserver() and encode() methods, and confirms From b494fef291bc0444f50bde68d10f57be3145ffe1 Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 11 Feb 2016 13:45:21 -0800 Subject: [PATCH 121/751] Enable new Ism side input format by default for batch Dataflow jobs The new side input format uses an index that significantly increases performance for list, map, and multimap views in the global window. In the non global window case, the indexed format increases performance for all views. For performance reasons, it is important to use a deterministic key coder for map and multimap views. Dataflow falls back to using a singleton implementation which may cause memory and/or performance problems. A warning is now emitted when using PCollection map and multimap views with non-deterministic key coders. ----Release Notes---- Enabled indexed side input format for batch Dataflow pipelines significantly increasing performance for list, map, multimap, and non global windowed views. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114473202 --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- .../dataflow/sdk/runners/DataflowPipelineTranslatorTest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index c3efb791ee..fcee7edd6c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -321,8 +321,8 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); builder.put(Read.Unbounded.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); - if (options.getExperiments() != null - && options.getExperiments().contains("enable_ism_side_input")) { + if (options.getExperiments() == null + || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); builder.put(View.AsMultimap.class, BatchViewAsMultimap.class); builder.put(View.AsSingleton.class, BatchViewAsSingleton.class); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index c55d215da8..98efc001a9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -647,6 +647,7 @@ public void testToSingletonTranslation() throws Exception { // in bad ways during refactor DataflowPipelineOptions options = buildPipelineOptions(); + options.setExperiments(ImmutableList.of("disable_ism_side_input")); DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); DataflowPipeline pipeline = DataflowPipeline.create(options); @@ -673,6 +674,7 @@ public void testToIterableTranslation() throws Exception { // in bad ways during refactor DataflowPipelineOptions options = buildPipelineOptions(); + options.setExperiments(ImmutableList.of("disable_ism_side_input")); DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); DataflowPipeline pipeline = DataflowPipeline.create(options); @@ -698,7 +700,6 @@ public void testToSingletonTranslationWithIsmSideInput() throws Exception { // in bad ways during refactor DataflowPipelineOptions options = buildPipelineOptions(); - options.setExperiments(ImmutableList.of("enable_ism_side_input")); DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); DataflowPipeline pipeline = DataflowPipeline.create(options); @@ -727,7 +728,6 @@ public void testToIterableTranslationWithIsmSideInput() throws Exception { // in bad ways during refactor DataflowPipelineOptions options = buildPipelineOptions(); - options.setExperiments(ImmutableList.of("enable_ism_side_input")); DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); DataflowPipeline pipeline = DataflowPipeline.create(options); From 3f77c3928be77bedc62749db26e2aadb75b02251 Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 11 Feb 2016 16:31:26 -0800 Subject: [PATCH 122/751] Use shaded guava from within worker maven module This drops the maven replacer plugin which made the worker module src use the guava that was shaded within the sdk module. Fixed checkstyle issues that appeared during migration. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114491104 --- worker/pom.xml | 44 -------------------------------------------- 1 file changed, 44 deletions(-) diff --git a/worker/pom.xml b/worker/pom.xml index aff36240b5..0a107a5f3e 100644 --- a/worker/pom.xml +++ b/worker/pom.xml @@ -42,47 +42,7 @@ - - ${project.build.directory}/generated/src/main/java - ${project.build.directory}/generated/src/test/java - - - - com.google.code.maven-replacer-plugin - replacer - 1.5.3 - - - process-sources - - replace - - - - - ${project.basedir} - ${project.build.directory} - generated - - src/**/*.java - - - - import com.google.common. - import com.google.cloud.dataflow.sdk.repackaged.com.google.common. - - - import com.google.thirdparty. - import com.google.cloud.dataflow.sdk.repackaged.com.google.thirdparty. - - - - - org.apache.maven.plugins maven-compiler-plugin @@ -107,10 +67,6 @@ false true ${project.build.directory}/generated-test-sources/** - - ${project.build.directory}/src/main/java - ${project.build.directory}/src/test/java From 3c57e542a8e354a15cfe3df3c47b5e9e843cf71d Mon Sep 17 00:00:00 2001 From: dhalperi Date: Thu, 11 Feb 2016 17:00:19 -0800 Subject: [PATCH 123/751] ByteKey: add a static instance EMPTY for the empty key ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114493446 --- .../com/google/cloud/dataflow/sdk/io/range/ByteKey.java | 3 +++ .../google/cloud/dataflow/sdk/io/range/ByteKeyTest.java | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java index 19c560fd5e..30772da793 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java @@ -39,6 +39,9 @@ * whether an upper bound key is empty. */ public final class ByteKey implements Comparable, Serializable { + /** An empty key. */ + public static final ByteKey EMPTY = ByteKey.of(); + /** * Creates a new {@link ByteKey} backed by the specified {@link ByteString}. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java index 66c5d394ba..5c81287c8b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java @@ -37,7 +37,7 @@ public class ByteKeyTest { // A big list of byte[] keys, in ascending sorted order. private static final ByteKey[] TEST_KEYS = new ByteKey[] { - ByteKey.of(), + ByteKey.EMPTY, ByteKey.of(0), ByteKey.of(0, 1), ByteKey.of(0, 1, 1), @@ -149,7 +149,7 @@ public void testHashCode() { */ @Test public void testToString() { - assertEquals("[]", ByteKey.of().toString()); + assertEquals("[]", ByteKey.EMPTY.toString()); assertEquals("[00]", ByteKey.of(0).toString()); assertEquals("[0000]", ByteKey.of(0x00, 0x00).toString()); assertEquals( @@ -162,7 +162,7 @@ public void testToString() { */ @Test public void testIsEmpty() { - assertTrue("[] is empty", ByteKey.of().isEmpty()); + assertTrue("[] is empty", ByteKey.EMPTY.isEmpty()); assertFalse("[00]", ByteKey.of(0).isEmpty()); } @@ -171,7 +171,7 @@ public void testIsEmpty() { */ @Test public void testGetBytes() { - assertTrue("[] equal after getBytes", Arrays.equals(new byte[] {}, ByteKey.of().getBytes())); + assertTrue("[] equal after getBytes", Arrays.equals(new byte[] {}, ByteKey.EMPTY.getBytes())); assertTrue( "[00] equal after getBytes", Arrays.equals(new byte[] {0x00}, ByteKey.of(0x00).getBytes())); } From 0e204fe32194592ea22b0d20423c3dee06082346 Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 11 Feb 2016 17:30:33 -0800 Subject: [PATCH 124/751] Move miscellaneous worker classes to worker maven module This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114495743 --- .../dataflow/sdk/util/CloudCounterUtils.java | 115 --------- .../sdk/util/common/ForwardingReiterator.java | 85 ------- .../sdk/util/common/TaggedReiteratorList.java | 167 ------------- .../worker/ProgressTrackingReiterator.java | 57 ----- .../util/common/TaggedReiteratorListTest.java | 220 ------------------ 5 files changed, 644 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ForwardingReiterator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorList.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackingReiterator.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorListTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java deleted file mode 100644 index 4e13e0640f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudCounterUtils.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.services.dataflow.model.MetricStructuredName; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * Utilities for working with CloudCounters. - */ -public class CloudCounterUtils { - private static final Logger LOG = LoggerFactory.getLogger(CloudCounterUtils.class); - - /** - * Extracts MetricUpdate updates from the given counter set. This is used mainly - * for testing. - * - * @param delta specifies whether or not to extract the cumulative - * aggregate values or the deltas since the last extraction. - */ - public static List extractCounters( - CounterSet counters, boolean delta) { - synchronized (counters) { - List cloudCounters = new ArrayList<>(counters.size()); - for (Counter counter : counters) { - try { - MetricUpdate cloudCounter = extractCounter(counter, delta); - if (cloudCounter != null) { - cloudCounters.add(cloudCounter); - } - } catch (IllegalArgumentException exn) { - LOG.warn("Error extracting counter value: ", exn); - } - } - return cloudCounters; - } - } - - /** - * Extracts a MetricUpdate update from the given counter. This is used mainly - * for testing. - * - * @param delta specifies whether or not to extract the cumulative - * aggregate value or the delta since the last extraction. - */ - public static MetricUpdate extractCounter(Counter counter, boolean delta) { - // TODO: Omit no-op counter updates, for counters whose - // values haven't changed since the last time we sent them. - synchronized (counter) { - MetricStructuredName name = new MetricStructuredName(); - name.setName(counter.getName()); - MetricUpdate metricUpdate = new MetricUpdate() - .setName(name) - .setKind(counter.getKind().name()) - .setCumulative(!delta); - switch (counter.getKind()) { - case SUM: - case MAX: - case MIN: - case AND: - case OR: - Object aggregate; - if (delta) { - aggregate = counter.getAndResetDelta(); - } else { - aggregate = counter.getAggregate(); - } - metricUpdate.setScalar( - CloudObject.forKnownType(aggregate)); - break; - case MEAN: { - CounterMean mean; - if (delta) { - mean = counter.getAndResetMeanDelta(); - } else { - mean = counter.getMean(); - } - if (mean.getCount() <= 0) { - return null; - } - metricUpdate.setMeanSum( - CloudObject.forKnownType(mean.getAggregate())); - metricUpdate.setMeanCount(CloudObject.forKnownType(mean.getCount())); - break; - } - default: - throw new IllegalArgumentException("unexpected kind of counter"); - } - return metricUpdate; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ForwardingReiterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ForwardingReiterator.java deleted file mode 100644 index c63114e1bb..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ForwardingReiterator.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * A {@link Reiterator} that forwards to another {@code Reiterator}, useful for - * implementing {@code Reiterator} wrappers. - * - * @param the type of elements returned by this iterator - */ -public abstract class ForwardingReiterator - implements Reiterator, Cloneable { - private Reiterator base; - - /** - * Constructs a {@link ForwardingReiterator}. - * @param base supplies a base reiterator to forward requests to. This - * reiterator will be used directly; it will not be copied by the constructor. - */ - public ForwardingReiterator(Reiterator base) { - this.base = checkNotNull(base); - } - - @Override - protected ForwardingReiterator clone() { - ForwardingReiterator result; - try { - @SuppressWarnings("unchecked") - ForwardingReiterator declResult = (ForwardingReiterator) super.clone(); - result = declResult; - } catch (CloneNotSupportedException e) { - throw new AssertionError( - "Object.clone() for a ForwardingReiterator threw " - + "CloneNotSupportedException; this should not happen, " - + "since ForwardingReiterator implements Cloneable.", - e); - } - result.base = base.copy(); - return result; - } - - @Override - public boolean hasNext() { - return base.hasNext(); - } - - @Override - public T next() { - return base.next(); - } - - @Override - public void remove() { - base.remove(); - } - - /** - * {@inheritDoc} - * - *

    This implementation uses {@link #clone} to construct a duplicate of the - * {@link Reiterator}. Derived classes must either implement - * {@link Cloneable} semantics, or must provide an alternative implementation - * of this method. - */ - @Override - public ForwardingReiterator copy() { - return clone(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorList.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorList.java deleted file mode 100644 index 9e79b960b9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorList.java +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Provides a view a of re-iterable of tagged values, with monotonically - * increasing tags, as a list of tagged re-iterables. - * - *

    This class, and the returned iterators, are not threadsafe. - */ -public class TaggedReiteratorList extends AbstractList> { - - /** - * Interface for extracting the tag and value from an opaque element. - */ - public interface TagExtractor { - public int getTag(T elem); - public Object getValue(T elem); - } - - private final TagExtractor extractor; - - private final List> starts; - - private final int size; - - public TaggedReiteratorList(Reiterator taggedReiterator, - TagExtractor extractor) { - this(taggedReiterator, extractor, -1); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public TaggedReiteratorList(Reiterator taggedReiterator, - TagExtractor extractor, - int size) { - starts = new ArrayList<>(); - starts.add(new PeekingReiterator((Reiterator) taggedReiterator)); - this.extractor = (TagExtractor) extractor; - this.size = size; - } - - @Override - public Reiterator get(int tag) { - return new SubIterator(tag); - } - - @Override - public int size() { - if (size == -1) { - throw new UnsupportedOperationException(); - } else { - return size; - } - } - - private PeekingReiterator getStart(int tag) { - if (tag >= starts.size()) { - PeekingReiterator start = getStart(tag - 1); - while (start.hasNext() && extractor.getTag(start.peek()) < tag) { - start.next(); - } - starts.add(start); - } - // Use the stored value, store a copy. - return starts.set(tag, starts.get(tag).copy()); - } - - private static final PeekingReiterator EMPTY_TAIL = - new PeekingReiterator( - new Reiterator() { - @Override - public boolean hasNext() { - return false; - } - - @Override - public Object next() { - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new IllegalArgumentException(); - } - - @Override - public Reiterator copy() { - throw new IllegalArgumentException(); - } - }); - - private class SubIterator implements Reiterator { - - private final int tag; - private PeekingReiterator iterator; - - private SubIterator(int tag) { - this(tag, null); - } - - private SubIterator(int tag, PeekingReiterator iterator) { - this.tag = tag; - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - if (iterator == null) { - iterator = getStart(tag); - } - if (iterator.hasNext() && extractor.getTag(iterator.peek()) == tag) { - return true; - } else { - if (iterator != EMPTY_TAIL) { - // Set up for the common case that we're iterating over the - // next tag soon. - if (starts.size() > tag + 1) { - starts.set(tag + 1, iterator); - } else { - starts.add(tag + 1, iterator); - } - iterator = EMPTY_TAIL; - } - return false; - } - } - - @Override - public Object next() { - if (hasNext()) { - return extractor.getValue(iterator.next()); - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new IllegalArgumentException(); - } - - @Override - public Reiterator copy() { - return new SubIterator( - tag, iterator == null || iterator == EMPTY_TAIL ? iterator : iterator.copy()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackingReiterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackingReiterator.java deleted file mode 100644 index 47e8a949f3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackingReiterator.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.util.common.ForwardingReiterator; -import com.google.cloud.dataflow.sdk.util.common.Reiterator; - -/** - * Implements a {@link Reiterator} that uses a - * {@link ProgressTrackerGroup.Tracker ProgressTracker} to track how far - * it's gotten through some base {@code Reiterator}. - * {@link ProgressTrackingReiterator#copy} copies the {@code ProgressTracker}, - * allowing for an independent progress state. - * - * @param the type of the elements of this iterator - */ -public final class ProgressTrackingReiterator - extends ForwardingReiterator { - private ProgressTracker tracker; - - public ProgressTrackingReiterator(Reiterator base, - ProgressTracker tracker) { - super(base); - this.tracker = checkNotNull(tracker); - } - - @Override - public T next() { - T result = super.next(); - tracker.saw(result); - return result; - } - - @Override - protected ProgressTrackingReiterator clone() { - ProgressTrackingReiterator result = - (ProgressTrackingReiterator) super.clone(); - result.tracker = tracker.copy(); - return result; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorListTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorListTest.java deleted file mode 100644 index 6cd3811148..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/TaggedReiteratorListTest.java +++ /dev/null @@ -1,220 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -/** - * Tests for {@link TaggedReiteratorList}. - */ -@RunWith(JUnit4.class) -public class TaggedReiteratorListTest { - - @Test - public void testSingleIterator() { - TaggedReiteratorList iter = create(new String[] {"a", "b", "c"}); - assertEquals(iter.get(0), "a", "b", "c"); - assertEquals(iter.get(0), "a", "b", "c"); - assertEquals(iter.get(1) /*empty*/); - assertEquals(iter.get(0), "a", "b", "c"); - } - - @Test - public void testSequentialAccess() { - TaggedReiteratorList iter = create(3, new String[] {"a", "b", "c"}); - for (int i = 0; i < 2; i++) { - assertEquals(iter.get(0), "a0", "b0", "c0"); - assertEquals(iter.get(1), "a1", "b1", "c1"); - assertEquals(iter.get(2), "a2", "b2", "c2"); - } - for (int i = 0; i < 2; i++) { - assertEquals(iter.get(2), "a2", "b2", "c2"); - assertEquals(iter.get(1), "a1", "b1", "c1"); - assertEquals(iter.get(0), "a0", "b0", "c0"); - } - } - - @Test - public void testRandomAccess() { - TaggedReiteratorList iter = create(6, new String[] {"a", "b"}); - assertEquals(iter.get(3), "a3", "b3"); - assertEquals(iter.get(1), "a1", "b1"); - assertEquals(iter.get(5), "a5", "b5"); - assertEquals(iter.get(0), "a0", "b0"); - assertEquals(iter.get(4), "a4", "b4"); - assertEquals(iter.get(4), "a4", "b4"); - assertEquals(iter.get(1), "a1", "b1"); - } - - @Test - public void testPartialIteration() { - TaggedReiteratorList iter = create(6, new String[] {"a", "b", "c"}); - Iterator get0 = iter.get(0); - Iterator get1 = iter.get(1); - Iterator get3 = iter.get(3); - assertEquals(asList(get0, 1), "a0"); - assertEquals(asList(get1, 2), "a1", "b1"); - assertEquals(asList(get3, 3), "a3", "b3", "c3"); - Iterator get2 = iter.get(2); - Iterator get0Again = iter.get(0); - assertEquals(asList(get0, 1), "b0"); - assertEquals(get2, "a2", "b2", "c2"); - assertEquals(get0Again, "a0", "b0", "c0"); - assertEquals(asList(get0), "c0"); - Iterator get4 = iter.get(4); - assertEquals(get4, "a4", "b4", "c4"); - assertEquals(get4 /*empty*/); - assertEquals(iter.get(4), "a4", "b4", "c4"); - } - - @Test - public void testNextIteration() { - TaggedReiteratorList iter = create(2, new String[] {"a", "b", "c"}); - Reiterator get0 = iter.get(0); - assertEquals(get0, "a0", "b0", "c0"); - Iterator get1 = iter.get(1); - Assert.assertEquals(get1.next(), "a1"); - assertEquals(get0.copy() /*empty*/); - Assert.assertEquals(get1.next(), "b1"); - assertEquals(iter.get(1), "a1", "b1", "c1"); - } - - @Test - public void testEmpties() { - TaggedReiteratorList iter = create(new String[] {}, - new String[] {"a", "b", "c"}, - new String[] {}, - new String[] {}, - new String[] {"d"}); - assertEquals(iter.get(2) /*empty*/); - assertEquals(iter.get(1), "a", "b", "c"); - assertEquals(iter.get(2) /*empty*/); - assertEquals(iter.get(0) /*empty*/); - assertEquals(iter.get(2) /*empty*/); - assertEquals(iter.get(4), "d"); - assertEquals(iter.get(3) /*empty*/); - } - - ///////////////////////////////////////////////////////////////////////////// - // Helpers - - private TaggedReiteratorList create(String[]... values) { - ArrayList taggedValues = new ArrayList<>(); - for (int tag = 0; tag < values.length; tag++) { - for (String value : values[tag]) { - taggedValues.add(new TaggedValue(tag, value)); - } - } - return new TaggedReiteratorList( - new TestReiterator(taggedValues.toArray(new TaggedValue[0])), - new TaggedValueExtractor()); - } - - private TaggedReiteratorList create(int repeat, String... values) { - ArrayList taggedValues = new ArrayList<>(); - for (int tag = 0; tag < repeat; tag++) { - for (String value : values) { - taggedValues.add(new TaggedValue(tag, value + tag)); - } - } - return new TaggedReiteratorList( - new TestReiterator(taggedValues.toArray(new TaggedValue[0])), - new TaggedValueExtractor()); - } - - private List asList(Iterator iter) { - return asList(iter, Integer.MAX_VALUE); - } - - private List asList(Iterator iter, int limit) { - List list = new ArrayList<>(); - for (int i = 0; i < limit && iter.hasNext(); i++) { - list.add(iter.next()); - } - return list; - } - - private void assertEquals(Iterator actual, Object... expected) { - assertEquals(asList(actual), expected); - } - - private void assertEquals(List actual, Object... expected) { - Assert.assertEquals(Arrays.asList(expected), actual); - } - - private static class TestReiterator implements Reiterator { - private final TaggedValue[] values; - private int pos = 0; - public TestReiterator(TaggedValue... values) { - this(values, 0); - } - private TestReiterator(TaggedValue[] values, int pos) { - this.values = values; - this.pos = pos; - } - - @Override - public boolean hasNext() { - return pos < values.length; - } - - @Override - public TaggedValue next() { - return values[pos++]; - } - - @Override - public void remove() { - throw new IllegalArgumentException(); - } - - @Override - public TestReiterator copy() { - return new TestReiterator(values, pos); - } - } - - private static class TaggedValueExtractor - implements TaggedReiteratorList.TagExtractor { - @Override - public int getTag(TaggedValue elem) { - return elem.tag; - } - - @Override - public String getValue(TaggedValue elem) { - return elem.value; - } - } - - private static class TaggedValue { - public final int tag; - public final String value; - public TaggedValue(int tag, String value) { - this.tag = tag; - this.value = value; - } - } -} From aaf27d3184ac836eda2cd3d24d795e8463a39522 Mon Sep 17 00:00:00 2001 From: millsd Date: Thu, 11 Feb 2016 17:30:53 -0800 Subject: [PATCH 125/751] Allow StreamingDataflowWorker to run against a remote gRPC windmill ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114495775 --- worker/pom.xml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/worker/pom.xml b/worker/pom.xml index 0a107a5f3e..5c5dca1a2d 100644 --- a/worker/pom.xml +++ b/worker/pom.xml @@ -42,6 +42,13 @@ + + + src/main/resources + true + + + org.apache.maven.plugins @@ -225,6 +232,19 @@ ${guava.version} + + io.grpc + grpc-all + 0.12.0 + + + + com.google.auth + google-auth-library-oauth2-http + 0.3.0 + compile + + org.hamcrest From 2d88e6fae73154dfc6c0bcfae95f7423e247d64e Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 11 Feb 2016 17:39:35 -0800 Subject: [PATCH 126/751] Move CustomSources logic to live in more appropriate places This reduces the remainder of stuff in CustomSources to just translation source translation. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114496358 --- .../google/cloud/dataflow/sdk/io/Read.java | 29 ++++++++++- .../sdk/runners/DataflowPipelineRunner.java | 7 +-- .../sdk/runners/dataflow/CustomSources.java | 52 ------------------- .../sdk/runners/dataflow/ReadTranslator.java | 28 ++++++++-- 4 files changed, 54 insertions(+), 62 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java index 710fd643b3..cde87696bb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java @@ -20,9 +20,9 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; @@ -30,6 +30,9 @@ import org.joda.time.Duration; +import java.util.ArrayList; +import java.util.List; + import javax.annotation.Nullable; /** @@ -152,7 +155,29 @@ private static void registerDefaultTransformEvaluator() { @Override public void evaluate( Bounded transform, DirectPipelineRunner.EvaluationContext context) { - CustomSources.evaluateReadHelper(transform, context); + evaluateReadHelper(transform, context); + } + + private void evaluateReadHelper( + Read.Bounded transform, DirectPipelineRunner.EvaluationContext context) { + try { + List> output = new ArrayList<>(); + BoundedSource source = transform.getSource(); + try (BoundedSource.BoundedReader reader = + source.createReader(context.getPipelineOptions())) { + for (boolean available = reader.start(); + available; + available = reader.advance()) { + output.add( + DirectPipelineRunner.ValueWithMetadata.of( + WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp()))); + } + } + context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); + } catch (Exception e) { + throw new RuntimeException(e); + } } }); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index fcee7edd6c..f3d4825ff9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -59,9 +59,9 @@ import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.JobSpecification; import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; -import com.google.cloud.dataflow.sdk.runners.dataflow.CustomSources; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; +import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; @@ -1673,8 +1673,6 @@ W> applyForSingleton( finalValueCoder); } - - private static PCollectionView applyForMapLike( DataflowPipelineRunner runner, PCollection> input, @@ -2037,8 +2035,7 @@ private static class ReadWithIdsTranslator @Override public void translate(ReadWithIds transform, DataflowPipelineTranslator.TranslationContext context) { - CustomSources.translateReadHelper( - transform.getSource(), transform, context); + ReadTranslator.translateReadHelper(transform.getSource(), transform, context); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java index 238ec4b0f3..8160693195 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java @@ -17,7 +17,6 @@ package com.google.cloud.dataflow.sdk.runners.dataflow; import static com.google.api.client.util.Base64.encodeBase64String; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudSourceToDictionary; import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; import static com.google.cloud.dataflow.sdk.util.Structs.addString; import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; @@ -25,22 +24,14 @@ import com.google.api.services.dataflow.model.SourceMetadata; import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Source; import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; -import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -124,47 +115,4 @@ public static com.google.api.services.dataflow.model.Source serializeToCloudSour cloudSource.setMetadata(metadata); return cloudSource; } - - public static void evaluateReadHelper( - Read.Bounded transform, DirectPipelineRunner.EvaluationContext context) { - try { - List> output = new ArrayList<>(); - BoundedSource source = transform.getSource(); - try (BoundedSource.BoundedReader reader = - source.createReader(context.getPipelineOptions())) { - for (boolean available = reader.start(); available; available = reader.advance()) { - output.add( - DirectPipelineRunner.ValueWithMetadata.of( - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp()))); - } - } - context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static void translateReadHelper(Source source, - PTransform transform, - DataflowPipelineTranslator.TranslationContext context) { - try { - context.addStep(transform, "ParallelRead"); - context.addInput(PropertyNames.FORMAT, PropertyNames.CUSTOM_SOURCE_FORMAT); - context.addInput( - PropertyNames.SOURCE_STEP_INPUT, - cloudSourceToDictionary(serializeToCloudSource(source, context.getPipelineOptions()))); - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - // Commit at least once every 10 seconds or 10k records. This keeps the watermark advancing - // smoothly, and ensures that not too much work will have to be reprocessed in the event of - // a crash. - @VisibleForTesting - static final int MAX_UNBOUNDED_BUNDLE_SIZE = 10000; - @VisibleForTesting - static final Duration MAX_UNBOUNDED_BUNDLE_READ_TIME = Duration.standardSeconds(10); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java index a7d0914da2..2513d431cb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java @@ -16,10 +16,16 @@ package com.google.cloud.dataflow.sdk.runners.dataflow; -import static com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import static com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; +import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudSourceToDictionary; import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.Source; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.values.PValue; /** * Translator for the {@code Read} {@code PTransform} for the Dataflow back-end. @@ -27,6 +33,22 @@ public class ReadTranslator implements TransformTranslator> { @Override public void translate(Read.Bounded transform, TranslationContext context) { - CustomSources.translateReadHelper(transform.getSource(), transform, context); + translateReadHelper(transform.getSource(), transform, context); + } + + public static void translateReadHelper(Source source, + PTransform transform, + DataflowPipelineTranslator.TranslationContext context) { + try { + context.addStep(transform, "ParallelRead"); + context.addInput(PropertyNames.FORMAT, PropertyNames.CUSTOM_SOURCE_FORMAT); + context.addInput( + PropertyNames.SOURCE_STEP_INPUT, + cloudSourceToDictionary( + CustomSources.serializeToCloudSource(source, context.getPipelineOptions()))); + context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); + } catch (Exception e) { + throw new RuntimeException(e); + } } } From f0198ddd1b15ec892671db7df1960855dc9a03bc Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 11 Feb 2016 18:47:25 -0800 Subject: [PATCH 127/751] Add filename-based compression selection to CompressedSource ----Release Notes---- - CompressedSource now detects compression according to filename by default. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114500494 --- .../dataflow/sdk/io/CompressedSource.java | 98 +++++++++++++++++-- .../dataflow/sdk/io/CompressedSourceTest.java | 98 +++++++++++++++++-- 2 files changed, 180 insertions(+), 16 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index 687fa04ab6..ba42fdc8d1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -43,8 +43,15 @@ * .withDecompression(CompressedSource.CompressionMode.GZIP))); * } * - *

    Default compression modes are {@link CompressionMode#GZIP} and {@link CompressionMode#BZIP2}. - * User-defined compression types are supported by implementing {@link DecompressingChannelFactory}. + *

    Supported compression algorithms are {@link CompressionMode#GZIP} and + * {@link CompressionMode#BZIP2}. User-defined compression types are supported by implementing + * {@link DecompressingChannelFactory}. + * + *

    By default, the compression algorithm is selected from those supported in + * {@link CompressionMode} based on the file name provided to the source, namely + * {@code ".bz2"} indicates {@link CompressionMode#BZIP2} and {@code ".gz"} indicates + * {@link CompressionMode#GZIP}. If the file name does not match any of the supported + * algorithms, it is assumed to be uncompressed data. * * @param The type to read from the compressed file. */ @@ -53,7 +60,6 @@ public class CompressedSource extends FileBasedSource { /** * Factory interface for creating channels that decompress the content of an underlying channel. */ - // TODO: Refactor decompressing channel/stream creation and default instances to util classes. public static interface DecompressingChannelFactory extends Serializable { /** * Given a channel, create a channel that decompresses the content read from the channel. @@ -63,18 +69,49 @@ public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channe throws IOException; } + /** + * Factory interface for creating channels that decompress the content of an underlying channel, + * based on both the channel and the file name. + */ + private static interface FileNameBasedDecompressingChannelFactory + extends DecompressingChannelFactory { + /** + * Given a channel, create a channel that decompresses the content read from the channel. + * @throws IOException + */ + ReadableByteChannel createDecompressingChannel(String fileName, ReadableByteChannel channel) + throws IOException; + } + /** * Default compression types supported by the {@code CompressedSource}. */ public enum CompressionMode implements DecompressingChannelFactory { + /** + * Reads a byte channel assuming it is compressed with gzip. + */ GZIP { + @Override + public boolean matches(String fileName) { + return fileName.toLowerCase().endsWith(".gz"); + } + @Override public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) throws IOException { return Channels.newChannel(new GzipCompressorInputStream(Channels.newInputStream(channel))); } }, + + /** + * Reads a byte channel assuming it is compressed with bzip2. + */ BZIP2 { + @Override + public boolean matches(String fileName) { + return fileName.toLowerCase().endsWith(".bz2"); + } + @Override public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) throws IOException { @@ -83,11 +120,48 @@ public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channe } }; + /** + * Returns {@code true} if the given file name implies that the contents are compressed + * according to the compression embodied by this factory. + */ + public abstract boolean matches(String fileName); + @Override public abstract ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) throws IOException; } + /** + * Reads a byte channel detecting compression according to the file name. If the filename + * is not any other known {@link CompressionMode}, it is presumed to be uncompressed. + */ + private static class DecompressAccordingToFilename + implements FileNameBasedDecompressingChannelFactory { + + @Override + public ReadableByteChannel createDecompressingChannel( + String fileName, ReadableByteChannel channel) throws IOException { + for (CompressionMode type : CompressionMode.values()) { + if (type.matches(fileName)) { + return type.createDecompressingChannel(channel); + } + } + // Uncompressed + return channel; + } + + @Override + public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) { + throw new UnsupportedOperationException( + String.format("%s does not support createDecompressingChannel(%s) but only" + + " createDecompressingChannel(%s,%s)", + getClass().getSimpleName(), + String.class.getSimpleName(), + ReadableByteChannel.class.getSimpleName(), + ReadableByteChannel.class.getSimpleName())); + } + } + private final FileBasedSource sourceDelegate; private final DecompressingChannelFactory channelFactory; @@ -102,11 +176,12 @@ public static Read.Bounded readFromSource( } /** - * Creates a {@code CompressedSource} from an underlying {@code FileBasedSource} that must be - * further configured with {@link CompressedSource#withDecompression}. + * Creates a {@code CompressedSource} from an underlying {@code FileBasedSource}. The type + * of compression used will be based on the file name extension unless explicitly + * configured via {@link CompressedSource#withDecompression}. */ public static CompressedSource from(FileBasedSource sourceDelegate) { - return new CompressedSource<>(sourceDelegate, null); + return new CompressedSource<>(sourceDelegate, new DecompressAccordingToFilename()); } /** @@ -252,7 +327,16 @@ protected final boolean isAtSplitPoint() { */ @Override protected final void startReading(ReadableByteChannel channel) throws IOException { - readerDelegate.startReading(source.getChannelFactory().createDecompressingChannel(channel)); + if (source.getChannelFactory() instanceof FileNameBasedDecompressingChannelFactory) { + FileNameBasedDecompressingChannelFactory channelFactory = + (FileNameBasedDecompressingChannelFactory) source.getChannelFactory(); + readerDelegate.startReading(channelFactory.createDecompressingChannel( + getCurrentSource().getFileOrPatternSpec(), + channel)); + } else { + readerDelegate.startReading(source.getChannelFactory().createDecompressingChannel( + channel)); + } } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index d0a9b7be03..7583ee0226 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; import com.google.cloud.dataflow.sdk.io.CompressedSource.CompressionMode; +import com.google.cloud.dataflow.sdk.io.CompressedSource.DecompressingChannelFactory; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -45,6 +46,8 @@ import java.util.List; import java.util.NoSuchElementException; +import javax.annotation.Nullable; + /** * Tests for CompressedSource. */ @@ -92,6 +95,69 @@ public void testCompressedReadBzip2() throws Exception { runReadTest(input, CompressionMode.BZIP2); } + /** + * Test reading according to filepattern when the file is bzipped. + */ + @Test + public void testCompressedAccordingToFilepatternGzip() throws Exception { + byte[] input = generateInput(100); + File tmpFile = tmpFolder.newFile("test.gz"); + writeFile(tmpFile, input, CompressionMode.GZIP); + verifyReadContents(input, tmpFile, null /* default auto decompression factory */); + } + + /** + * Test reading according to filepattern when the file is gzipped. + */ + @Test + public void testCompressedAccordingToFilepatternBzip2() throws Exception { + byte[] input = generateInput(100); + File tmpFile = tmpFolder.newFile("test.bz2"); + writeFile(tmpFile, input, CompressionMode.BZIP2); + verifyReadContents(input, tmpFile, null /* default auto decompression factory */); + } + + /** + * Test reading multiple files with different compression. + */ + @Test + public void testHeterogeneousCompression() throws Exception { + String baseName = "test-input"; + + // Expected data + byte[] generated = generateInput(1000); + List expected = new ArrayList<>(); + + // Every sort of compression + File uncompressedFile = tmpFolder.newFile(baseName + ".bin"); + generated = generateInput(1000); + try (OutputStream outStream = new FileOutputStream(uncompressedFile)) { + outStream.write(generated); + } + expected.addAll(Bytes.asList(generated)); + + File gzipFile = tmpFolder.newFile(baseName + ".gz"); + generated = generateInput(1000); + writeFile(gzipFile, generated, CompressionMode.GZIP); + expected.addAll(Bytes.asList(generated)); + + File bzip2File = tmpFolder.newFile(baseName + ".bz2"); + generated = generateInput(1000); + writeFile(bzip2File, generateInput(1000), CompressionMode.BZIP2); + expected.addAll(Bytes.asList(generated)); + + String filePattern = new File(tmpFolder.getRoot().toString(), baseName + ".*").toString(); + + Pipeline p = TestPipeline.create(); + + CompressedSource source = + CompressedSource.from(new ByteSource(filePattern, 1)); + PCollection output = p.apply(Read.from(source)); + + DataflowAssert.that(output).containsInAnyOrder(expected); + p.run(); + } + /** * Test reading multiple files. */ @@ -134,7 +200,7 @@ private byte[] generateInput(int size) { /** * Get a compressing stream for a given compression mode. */ - private OutputStream getStreamForMode(CompressionMode mode, OutputStream stream) + private OutputStream getOutputStreamForMode(CompressionMode mode, OutputStream stream) throws IOException { switch (mode) { case GZIP: @@ -150,7 +216,7 @@ private OutputStream getStreamForMode(CompressionMode mode, OutputStream stream) * Writes a single output file. */ private void writeFile(File file, byte[] input, CompressionMode mode) throws IOException { - try (OutputStream os = getStreamForMode(mode, new FileOutputStream(file))) { + try (OutputStream os = getOutputStreamForMode(mode, new FileOutputStream(file))) { os.write(input); } } @@ -158,21 +224,35 @@ private void writeFile(File file, byte[] input, CompressionMode mode) throws IOE /** * Run a single read test, writing and reading back input with the given compression mode. */ - private void runReadTest(byte[] input, CompressionMode mode) throws IOException { + private void runReadTest(byte[] input, + CompressionMode inputCompressionMode, + @Nullable DecompressingChannelFactory decompressionFactory) + throws IOException { File tmpFile = tmpFolder.newFile(); - writeFile(tmpFile, input, mode); + writeFile(tmpFile, input, inputCompressionMode); + verifyReadContents(input, tmpFile, decompressionFactory); + } + private void verifyReadContents(byte[] expected, File inputFile, + @Nullable DecompressingChannelFactory decompressionFactory) { Pipeline p = TestPipeline.create(); - CompressedSource source = - CompressedSource.from(new ByteSource(tmpFile.toPath().toString(), 1)) - .withDecompression(mode); + CompressedSource.from(new ByteSource(inputFile.toPath().toString(), 1)); + if (decompressionFactory != null) { + source = source.withDecompression(decompressionFactory); + } PCollection output = p.apply(Read.from(source)); - - DataflowAssert.that(output).containsInAnyOrder(Bytes.asList(input)); + DataflowAssert.that(output).containsInAnyOrder(Bytes.asList(expected)); p.run(); } + /** + * Run a single read test, writing and reading back input with the given compression mode. + */ + private void runReadTest(byte[] input, CompressionMode mode) throws IOException { + runReadTest(input, mode, mode); + } + /** * Dummy source for use in tests. */ From dbcc0af0d80d57dace086c520d635516d1650602 Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 11 Feb 2016 21:12:27 -0800 Subject: [PATCH 128/751] Make internal state APIs explicitly keyed This is preparatory plumbing for making the key to which state is associated available to the State implementation, for example to use a KeyedCombineFn. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114507418 --- .../windowing/AfterDelayFromFirstElement.java | 14 ++-- .../sdk/transforms/windowing/AfterPane.java | 10 +-- .../sdk/transforms/windowing/Trigger.java | 16 ++-- .../sdk/util/BaseExecutionContext.java | 2 +- .../sdk/util/DirectModeExecutionContext.java | 14 ++-- .../dataflow/sdk/util/DoFnRunnerBase.java | 2 +- .../dataflow/sdk/util/ExecutionContext.java | 2 +- .../GroupAlsoByWindowsAndCombineDoFn.java | 1 - .../sdk/util/MergingActiveWindowSet.java | 4 +- .../sdk/util/MergingStateContext.java | 34 -------- .../dataflow/sdk/util/NonEmptyPanes.java | 53 ++++++------ .../dataflow/sdk/util/PaneInfoTracker.java | 5 +- .../cloud/dataflow/sdk/util/ReduceFn.java | 20 +++-- .../sdk/util/ReduceFnContextFactory.java | 76 +++++++++-------- .../dataflow/sdk/util/ReduceFnRunner.java | 21 +++-- .../dataflow/sdk/util/SystemReduceFn.java | 21 +++-- .../sdk/util/TriggerContextFactory.java | 28 ++++--- .../dataflow/sdk/util/TriggerRunner.java | 29 ++++--- .../dataflow/sdk/util/WatermarkHold.java | 9 +- .../dataflow/sdk/util/WindowingInternals.java | 6 +- .../util/state/InMemoryStateInternals.java | 39 ++++++--- .../sdk/util/state/MergingStateContext.java | 39 +++++++++ .../sdk/util/{ => state}/StateContext.java | 18 ++-- .../sdk/util/state/StateInternals.java | 7 +- .../dataflow/sdk/util/state/StateMerging.java | 34 ++++---- .../dataflow/sdk/util/state/StateTable.java | 16 ++-- .../dataflow/sdk/util/state/StateTag.java | 18 ++-- .../dataflow/sdk/util/state/StateTags.java | 83 ++++++++++++------- .../sdk/util/MergingActiveWindowSetTest.java | 4 +- .../dataflow/sdk/util/ReduceFnTester.java | 48 +++++++---- .../dataflow/sdk/util/TriggerTester.java | 18 ++-- .../state/InMemoryStateInternalsTest.java | 16 ++-- .../dataflow/sdk/util/state/StateTagTest.java | 34 ++++---- 33 files changed, 431 insertions(+), 310 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateContext.java rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/{ => state}/StateContext.java (65%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java index 51de85e862..9c9a0956ab 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -22,11 +22,11 @@ import com.google.cloud.dataflow.sdk.transforms.Min; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -52,8 +52,8 @@ public abstract class AfterDelayFromFirstElement extend protected static final List> IDENTITY = ImmutableList.>of(); - protected static final StateTag, - Instant>> DELAYED_UNTIL_TAG = + protected static final StateTag, Instant>> DELAYED_UNTIL_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "delayed", InstantCoder.of(), Min.MinFn.naturalOrder())); @@ -151,7 +151,7 @@ private AfterDelayFromFirstElement newWith( } @Override - public void prefetchOnElement(StateContext state) { + public void prefetchOnElement(StateContext state) { state.access(DELAYED_UNTIL_TAG).get(); } @@ -172,7 +172,7 @@ public void onElement(OnElementContext c) throws Exception { } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { super.prefetchOnMerge(state); StateMerging.prefetchCombiningValues(state, DELAYED_UNTIL_TAG); } @@ -207,7 +207,7 @@ public void onMerge(OnMergeContext c) throws Exception { } @Override - public void prefetchShouldFire(StateContext state) { + public void prefetchShouldFire(StateContext state) { state.access(DELAYED_UNTIL_TAG).get(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java index 8eed3fcea7..79a370757b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java @@ -20,9 +20,9 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -41,7 +41,7 @@ @Experimental(Experimental.Kind.TRIGGER) public class AfterPane extends OnceTrigger{ -private static final StateTag> +private static final StateTag> ELEMENTS_IN_PANE_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "count", VarLongCoder.of(), new Sum.SumLongFn())); @@ -66,7 +66,7 @@ public void onElement(OnElementContext c) throws Exception { } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { super.prefetchOnMerge(state); StateMerging.prefetchCombiningValues(state, ELEMENTS_IN_PANE_TAG); } @@ -86,7 +86,7 @@ public void onMerge(OnMergeContext context) throws Exception { } @Override - public void prefetchShouldFire(StateContext state) { + public void prefetchShouldFire(StateContext state) { state.access(ELEMENTS_IN_PANE_TAG).get(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java index 4afcf11a4b..3d4029e298 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java @@ -18,9 +18,9 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.cloud.dataflow.sdk.util.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.StateContext; import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.common.base.Joiner; import org.joda.time.Instant; @@ -190,7 +190,7 @@ public abstract class TriggerContext { public abstract TriggerInfo trigger(); /** Returns the interface for accessing persistent state. */ - public abstract StateContext state(); + public abstract StateContext state(); /** The window that the current context is executing in. */ public abstract W window(); @@ -265,7 +265,7 @@ public abstract class OnMergeContext extends TriggerContext { public abstract OnMergeContext forTrigger(ExecutableTrigger trigger); @Override - public abstract MergingStateContext state(); + public abstract MergingStateContext state(); @Override public abstract MergingTriggerInfo trigger(); @@ -319,7 +319,7 @@ protected Trigger(@Nullable List> subTriggers) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onElement} call. */ - public void prefetchOnElement(StateContext state) { + public void prefetchOnElement(StateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnElement(state); @@ -331,7 +331,7 @@ public void prefetchOnElement(StateContext state) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onMerge} call. */ - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnMerge(state); @@ -343,7 +343,7 @@ public void prefetchOnMerge(MergingStateContext state) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #shouldFire} call. */ - public void prefetchShouldFire(StateContext state) { + public void prefetchShouldFire(StateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchShouldFire(state); @@ -355,7 +355,7 @@ public void prefetchShouldFire(StateContext state) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onFire} call. */ - public void prefetchOnFire(StateContext state) { + public void prefetchOnFire(StateContext state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnFire(state); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java index 9d04896203..6a0ccf3531 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java @@ -147,7 +147,7 @@ public void writePCollectionViewData( } @Override - public abstract StateInternals stateInternals(); + public abstract StateInternals stateInternals(); @Override public abstract TimerInternals timerInternals(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java index 12f2d208d6..6e970535db 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java @@ -16,12 +16,13 @@ package com.google.cloud.dataflow.sdk.util; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.ValueWithMetadata; import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -99,8 +100,9 @@ public List> getSideOutput(TupleTag tag) { */ public static class StepContext extends BaseExecutionContext.StepContext { - private final Map stateInternals = Maps.newHashMap(); - private InMemoryStateInternals currentStateInternals = null; + /** A map from each key to the state associated with it. */ + private final Map> stateInternals = Maps.newHashMap(); + private InMemoryStateInternals currentStateInternals = null; private StepContext(ExecutionContext executionContext, String stepName, String transformName) { super(executionContext, stepName, transformName); @@ -110,14 +112,14 @@ private StepContext(ExecutionContext executionContext, String stepName, String t public void switchKey(Object newKey) { currentStateInternals = stateInternals.get(newKey); if (currentStateInternals == null) { - currentStateInternals = new InMemoryStateInternals(); + currentStateInternals = InMemoryStateInternals.forKey(newKey); stateInternals.put(newKey, currentStateInternals); } } @Override - public StateInternals stateInternals() { - return Preconditions.checkNotNull(currentStateInternals); + public StateInternals stateInternals() { + return checkNotNull(currentStateInternals); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index f4dfeb20b6..a3e22a660f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -549,7 +549,7 @@ public void writePCollectionViewData( } @Override - public StateInternals stateInternals() { + public StateInternals stateInternals() { return context.stepContext.stateInternals(); } }; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java index 83d74e6668..cff5b95cf9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java @@ -95,7 +95,7 @@ void writePCollectionViewData( Coder windowCoder) throws IOException; - StateInternals stateInternals(); + StateInternals stateInternals(); TimerInternals timerInternals(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java index 2fc6c650e2..c0a5cae2ed 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java @@ -89,7 +89,6 @@ public GroupAlsoByWindowsAndCombineDoFn( @SuppressWarnings("unchecked") WindowingStrategy objectWindowingStrategy = (WindowingStrategy) strategy; this.windowingStrategy = objectWindowingStrategy; - } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index 3a6960980d..eab7786b2e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -109,10 +109,10 @@ public class MergingActiveWindowSet implements ActiveWi */ private final ValueState>> valueState; - public MergingActiveWindowSet(WindowFn windowFn, StateInternals state) { + public MergingActiveWindowSet(WindowFn windowFn, StateInternals state) { this.windowFn = windowFn; - StateTag>>> mergeTreeAddr = + StateTag>>> mergeTreeAddr = StateTags.makeSystemTagInternal(StateTags.value( "tree", MapCoder.of(windowFn.windowCoder(), SetCoder.of(windowFn.windowCoder())))); valueState = state.state(StateNamespaces.global(), mergeTreeAddr); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java deleted file mode 100644 index 98d62f919c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingStateContext.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateTag; - -import java.util.Map; - -/** Interface for interacting with persistent state when merging windows. */ -public interface MergingStateContext extends StateContext { - /** - * Analogous to {@link #access}, but returned as a map from each window which is - * about to be merged to the corresponding state. Only includes windows which - * are known to have state. - */ - public Map accessInEachMergingWindow( - StateTag address); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java index 2d5fa41964..91a74a85ef 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; @@ -31,9 +32,10 @@ * * @param The kind of windows being tracked. */ -public abstract class NonEmptyPanes { - public static NonEmptyPanes create( - WindowingStrategy strategy, ReduceFn reduceFn) { +public abstract class NonEmptyPanes { + + public static NonEmptyPanes create( + WindowingStrategy strategy, ReduceFn reduceFn) { if (strategy.getMode() == AccumulationMode.DISCARDING_FIRED_PANES) { return new DiscardingModeNonEmptyPanes<>(reduceFn); } else { @@ -45,62 +47,63 @@ public static NonEmptyPanes create( * Record that some content has been added to the window in {@code context}, and therefore the * current pane is not empty. */ - public abstract void recordContent(ReduceFn.Context context); + public abstract void recordContent(ReduceFn.Context context); /** * Record that the given pane is empty. */ - public abstract void clearPane(ReduceFn.Context context); + public abstract void clearPane(ReduceFn.Context context); /** * Return true if the current pane for the window in {@code context} is empty. */ - public abstract StateContents isEmpty(ReduceFn.Context context); + public abstract StateContents isEmpty(ReduceFn.Context context); /** * Prefetch in preparation for merging. */ - public abstract void prefetchOnMerge(MergingStateContext state); + public abstract void prefetchOnMerge(MergingStateContext state); /** * Eagerly merge backing state. */ - public abstract void onMerge(MergingStateContext context); + public abstract void onMerge(MergingStateContext context); /** * An implementation of {@code NonEmptyPanes} optimized for use with discarding mode. Uses the * presence of data in the accumulation buffer to record non-empty panes. */ - private static class DiscardingModeNonEmptyPanes - extends NonEmptyPanes { - private ReduceFn reduceFn; + private static class DiscardingModeNonEmptyPanes + extends NonEmptyPanes { + + private ReduceFn reduceFn; - private DiscardingModeNonEmptyPanes(ReduceFn reduceFn) { + private DiscardingModeNonEmptyPanes(ReduceFn reduceFn) { this.reduceFn = reduceFn; } @Override - public StateContents isEmpty(ReduceFn.Context context) { + public StateContents isEmpty(ReduceFn.Context context) { return reduceFn.isEmpty(context.state()); } @Override - public void recordContent(ReduceFn.Context context) { + public void recordContent(ReduceFn.Context context) { // Nothing to do -- the reduceFn is tracking contents } @Override - public void clearPane(ReduceFn.Context context) { + public void clearPane(ReduceFn.Context context) { // Nothing to do -- the reduceFn is tracking contents } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { // Nothing to do -- the reduceFn is tracking contents } @Override - public void onMerge(MergingStateContext context) { + public void onMerge(MergingStateContext context) { // Nothing to do -- the reduceFn is tracking contents } } @@ -108,34 +111,36 @@ public void onMerge(MergingStateContext context) { /** * An implementation of {@code NonEmptyPanes} for general use. */ - private static class GeneralNonEmptyPanes extends NonEmptyPanes { - private static final StateTag> + private static class GeneralNonEmptyPanes + extends NonEmptyPanes { + + private static final StateTag> PANE_ADDITIONS_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "count", VarLongCoder.of(), new Sum.SumLongFn())); @Override - public void recordContent(ReduceFn.Context context) { + public void recordContent(ReduceFn.Context context) { context.state().access(PANE_ADDITIONS_TAG).add(1L); } @Override - public void clearPane(ReduceFn.Context context) { + public void clearPane(ReduceFn.Context context) { context.state().access(PANE_ADDITIONS_TAG).clear(); } @Override - public StateContents isEmpty(ReduceFn.Context context) { + public StateContents isEmpty(ReduceFn.Context context) { return context.state().access(PANE_ADDITIONS_TAG).isEmpty(); } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { StateMerging.prefetchCombiningValues(state, PANE_ADDITIONS_TAG); } @Override - public void onMerge(MergingStateContext context) { + public void onMerge(MergingStateContext context) { StateMerging.mergeCombiningValues(context, PANE_ADDITIONS_TAG); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index b3235c042a..e055b5828e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.cloud.dataflow.sdk.util.state.ValueState; @@ -42,10 +43,10 @@ public PaneInfoTracker(TimerInternals timerInternals) { } @VisibleForTesting - static final StateTag> PANE_INFO_TAG = + static final StateTag> PANE_INFO_TAG = StateTags.makeSystemTagInternal(StateTags.value("pane", PaneInfoCoder.INSTANCE)); - public void clear(StateContext state) { + public void clear(StateContext state) { state.access(PANE_INFO_TAG).clear(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java index b1b323d79e..1ee86ffa08 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java @@ -17,7 +17,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import org.joda.time.Instant; @@ -46,7 +48,7 @@ public abstract class Context { public abstract WindowingStrategy windowingStrategy(); /** Return the interface for accessing state. */ - public abstract StateContext state(); + public abstract StateContext state(); /** Return the interface for accessing timers. */ public abstract Timers timers(); @@ -65,7 +67,7 @@ public abstract class ProcessValueContext extends Context { public abstract class OnMergeContext extends Context { /** Return the interface for accessing state. */ @Override - public abstract MergingStateContext state(); + public abstract MergingStateContext state(); } /** Information accessible within {@link #onTrigger}. */ @@ -87,7 +89,7 @@ public abstract class OnTriggerContext extends Context { /** * Called when windows are merged. */ - public abstract void onMerge(OnMergeContext c) throws Exception; + public abstract void onMerge(OnMergeContext context) throws Exception; /** * Called when triggers fire. @@ -95,7 +97,7 @@ public abstract class OnTriggerContext extends Context { *

    Implementations of {@link ReduceFn} should call {@link OnTriggerContext#output} to emit * any results that should be included in the pane produced by this trigger firing. */ - public abstract void onTrigger(OnTriggerContext c) throws Exception; + public abstract void onTrigger(OnTriggerContext context) throws Exception; /** * Called before {@link #onMerge} is invoked to provide an opportunity to prefetch any needed @@ -103,24 +105,24 @@ public abstract class OnTriggerContext extends Context { * * @param c Context to use prefetch from. */ - public void prefetchOnMerge(MergingStateContext c) throws Exception {} + public void prefetchOnMerge(MergingStateContext c) throws Exception {} /** * Called before {@link #onTrigger} is invoked to provide an opportunity to prefetch any needed * state. * - * @param c Context to use prefetch from. + * @param context Context to use prefetch from. */ - public void prefetchOnTrigger(StateContext c) {} + public void prefetchOnTrigger(StateContext context) {} /** * Called to clear any persisted state that the {@link ReduceFn} may be holding. This will be * called when the windowing is closing and will receive no future interactions. */ - public abstract void clearState(Context c) throws Exception; + public abstract void clearState(Context context) throws Exception; /** * Returns true if the there is no buffered state. */ - public abstract StateContents isEmpty(StateContext c); + public abstract StateContents isEmpty(StateContext context); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index 2fa2c3ff9a..e6caf75567 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -21,8 +21,10 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; @@ -49,12 +51,12 @@ public interface OnTriggerCallbacks { private final K key; private final ReduceFn reduceFn; private final WindowingStrategy windowingStrategy; - private StateInternals stateInternals; + private StateInternals stateInternals; private ActiveWindowSet activeWindows; private TimerInternals timerInternals; ReduceFnContextFactory(K key, ReduceFn reduceFn, - WindowingStrategy windowingStrategy, StateInternals stateInternals, + WindowingStrategy windowingStrategy, StateInternals stateInternals, ActiveWindowSet activeWindows, TimerInternals timerInternals) { this.key = key; this.reduceFn = reduceFn; @@ -72,8 +74,9 @@ public static enum StateStyle { RENAMED } - private StateContextImpl stateContext(W window, StateStyle style) { - return new StateContextImpl<>(activeWindows, windowingStrategy.getWindowFn().windowCoder(), + private StateContextImpl stateContext(W window, StateStyle style) { + return new StateContextImpl( + activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, window, style); } @@ -94,12 +97,13 @@ public ReduceFn.OnTriggerContext forTrigger(W window, public ReduceFn.OnMergeContext forMerge( Collection activeToBeMerged, W mergeResult, StateStyle style) { return new OnMergeContextImpl( - new MergingStateContextImpl(activeWindows, windowingStrategy.getWindowFn().windowCoder(), + new MergingStateContextImpl(activeWindows, + windowingStrategy.getWindowFn().windowCoder(), stateInternals, style, activeToBeMerged, mergeResult)); } public ReduceFn.OnMergeContext forPremerge(W window) { - return new OnPremergeContextImpl(new PremergingStateContextImpl( + return new OnPremergeContextImpl(new PremergingStateContextImpl( activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, window)); } @@ -142,17 +146,20 @@ public Instant currentEventTime() { // ====================================================================== // StateContexts // ====================================================================== + static class StateContextImpl + implements StateContext { + - static class StateContextImpl implements StateContext { protected final ActiveWindowSet activeWindows; protected final W window; protected final StateNamespace windowNamespace; protected final Coder windowCoder; - protected final StateInternals stateInternals; + protected final StateInternals stateInternals; protected final StateStyle style; public StateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, - StateInternals stateInternals, W window, StateStyle style) { + StateInternals stateInternals, W window, StateStyle style) { + this.activeWindows = activeWindows; this.windowCoder = windowCoder; this.stateInternals = stateInternals; @@ -178,7 +185,7 @@ StateNamespace namespace() { } @Override - public StateT access(StateTag address) { + public StateT access(StateTag address) { switch (style) { case DIRECT: return stateInternals.state(windowNamespace(), address); @@ -190,19 +197,19 @@ public StateT access(StateTag address) { } } - static class MergingStateContextImpl - extends StateContextImpl implements MergingStateContext { + static class MergingStateContextImpl + extends StateContextImpl implements MergingStateContext { private final Collection activeToBeMerged; public MergingStateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, - StateInternals stateInternals, StateStyle style, Collection activeToBeMerged, + StateInternals stateInternals, StateStyle style, Collection activeToBeMerged, W mergeResult) { super(activeWindows, windowCoder, stateInternals, mergeResult, style); this.activeToBeMerged = activeToBeMerged; } @Override - public StateT access(StateTag address) { + public StateT access(StateTag address) { switch (style) { case DIRECT: return stateInternals.state(windowNamespace(), address); @@ -216,7 +223,7 @@ public StateT access(StateTag address) { @Override public Map accessInEachMergingWindow( - StateTag address) { + StateTag address) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (W mergingWindow : activeToBeMerged) { StateNamespace namespace = null; @@ -235,10 +242,10 @@ public Map accessInEachMergingWindow( } } - static class PremergingStateContextImpl - extends StateContextImpl implements MergingStateContext { + static class PremergingStateContextImpl + extends StateContextImpl implements MergingStateContext { public PremergingStateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, - StateInternals stateInternals, W window) { + StateInternals stateInternals, W window) { super(activeWindows, windowCoder, stateInternals, window, StateStyle.RENAMED); } @@ -248,7 +255,7 @@ Collection mergingWindows() { @Override public Map accessInEachMergingWindow( - StateTag address) { + StateTag address) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (W stateAddressWindow : activeWindows.readStateAddresses(window)) { StateT stateForWindow = stateInternals.state(namespaceFor(stateAddressWindow), address); @@ -263,10 +270,10 @@ public Map accessInEachMergingWindow( // ====================================================================== private class ContextImpl extends ReduceFn.Context { - private final StateContextImpl state; + private final StateContextImpl state; private final TimersImpl timers; - private ContextImpl(StateContextImpl state) { + private ContextImpl(StateContextImpl state) { reduceFn.super(); this.state = state; this.timers = new TimersImpl(state.namespace()); @@ -288,7 +295,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public StateContext state() { + public StateContext state() { return state; } @@ -302,10 +309,11 @@ private class ProcessValueContextImpl extends ReduceFn.ProcessValueContext { private final InputT value; private final Instant timestamp; - private final StateContextImpl state; + private final StateContextImpl state; private final TimersImpl timers; - private ProcessValueContextImpl(StateContextImpl state, InputT value, Instant timestamp) { + private ProcessValueContextImpl(StateContextImpl state, + InputT value, Instant timestamp) { reduceFn.super(); this.state = state; this.value = value; @@ -329,7 +337,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public StateContext state() { + public StateContext state() { return state; } @@ -350,12 +358,12 @@ public Timers timers() { } private class OnTriggerContextImpl extends ReduceFn.OnTriggerContext { - private final StateContextImpl state; + private final StateContextImpl state; private final StateContents pane; private final OnTriggerCallbacks callbacks; private final TimersImpl timers; - private OnTriggerContextImpl(StateContextImpl state, StateContents pane, + private OnTriggerContextImpl(StateContextImpl state, StateContents pane, OnTriggerCallbacks callbacks) { reduceFn.super(); this.state = state; @@ -380,7 +388,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public StateContext state() { + public StateContext state() { return state; } @@ -401,10 +409,10 @@ public Timers timers() { } private class OnMergeContextImpl extends ReduceFn.OnMergeContext { - private final MergingStateContextImpl state; + private final MergingStateContextImpl state; private final TimersImpl timers; - private OnMergeContextImpl(MergingStateContextImpl state) { + private OnMergeContextImpl(MergingStateContextImpl state) { reduceFn.super(); this.state = state; this.timers = new TimersImpl(state.namespace()); @@ -421,7 +429,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public MergingStateContext state() { + public MergingStateContext state() { return state; } @@ -437,10 +445,10 @@ public Timers timers() { } private class OnPremergeContextImpl extends ReduceFn.OnMergeContext { - private final PremergingStateContextImpl state; + private final PremergingStateContextImpl state; private final TimersImpl timers; - private OnPremergeContextImpl(PremergingStateContextImpl state) { + private OnPremergeContextImpl(PremergingStateContextImpl state) { reduceFn.super(); this.state = state; this.timers = new TimersImpl(state.namespace()); @@ -457,7 +465,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public MergingStateContext state() { + public MergingStateContext state() { return state; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 85b9bae4ba..675eae00cc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -29,6 +29,7 @@ import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowNamespace; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -174,7 +175,7 @@ public class ReduceFnRunner *

  • Lifetime: Cleared when pane fires or window is garbage collected. * */ - private final NonEmptyPanes nonEmptyPanes; + private final NonEmptyPanes nonEmptyPanes; public ReduceFnRunner(K key, WindowingStrategy windowingStrategy, TimerInternals timerInternals, WindowingInternals> windowingInternals, @@ -194,9 +195,15 @@ public ReduceFnRunner(K key, WindowingStrategy windowingStrategy, this.nonEmptyPanes = NonEmptyPanes.create(this.windowingStrategy, this.reduceFn); // Note this may trigger a GetData request to load the existing window set. this.activeWindows = createActiveWindowSet(); + + // It is the user of ReduceFnRunner's responsibility to have state internals with a + // compatible key type. This is generally assured by graph construction time validation. + @SuppressWarnings("unchecked") + StateInternals stateInternals = (StateInternals) this.windowingInternals.stateInternals(); + this.contextFactory = new ReduceFnContextFactory(key, reduceFn, this.windowingStrategy, - this.windowingInternals.stateInternals(), this.activeWindows, timerInternals); + stateInternals, this.activeWindows, timerInternals); this.watermarkHold = new WatermarkHold<>(timerInternals, windowingStrategy); this.triggerRunner = new TriggerRunner<>( @@ -257,7 +264,7 @@ public void processElements(Iterable> values) throws Excep contextFactory.base(mergedWindow, StateStyle.DIRECT); ReduceFn.Context renamedContext = contextFactory.base(mergedWindow, StateStyle.RENAMED); - triggerRunner.prefetchShouldFire(directContext.state()); + triggerRunner.prefetchShouldFire(mergedWindow, directContext.state()); emitIfAppropriate(directContext, renamedContext, false/* isEndOfWindow */); } @@ -342,7 +349,7 @@ public void prefetchOnMerge( contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); // Prefetch various state. - triggerRunner.prefetchForMerge(directMergeContext.state()); + triggerRunner.prefetchForMerge(mergeResult, activeToBeMerged, directMergeContext.state()); try { reduceFn.prefetchOnMerge(renamedMergeContext.state()); } catch (Exception e) { @@ -437,7 +444,7 @@ private Collection processElement(WindowedValue value) { for (W window : windows) { ReduceFn.ProcessValueContext directContext = contextFactory.forValue( window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); - triggerRunner.prefetchForValue(directContext.state()); + triggerRunner.prefetchForValue(window, directContext.state()); } // Process the element for each (representative) window it belongs to. @@ -731,11 +738,11 @@ private void onTrigger(final ReduceFn.Context directConte StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext); try { - reduceFn.prefetchOnTrigger(renamedContext.state()); + reduceFn.prefetchOnTrigger(directContext.state()); } catch (Exception e) { throw wrapMaybeUserException(e); } - triggerRunner.prefetchOnFire(directContext.state()); // Is a no-op. Why? + triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); // Is a no-op. Why? // Calculate the pane info. final PaneInfo pane = paneFuture.read(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java index 5d6101aedf..6068f913db 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java @@ -25,7 +25,9 @@ import com.google.cloud.dataflow.sdk.util.state.BagState; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -62,14 +64,14 @@ public interface Factory extends Se */ public static Factory, W> buffering( final Coder inputCoder) { - final StateTag> bufferTag = + final StateTag> bufferTag = StateTags.makeSystemTagInternal(StateTags.bag(BUFFER_NAME, inputCoder)); return new Factory, W>() { @Override public ReduceFn, W> create(K key) { return new SystemReduceFn, Iterable, W>(bufferTag) { @Override - public void prefetchOnMerge(MergingStateContext state) throws Exception { + public void prefetchOnMerge(MergingStateContext state) throws Exception { StateMerging.prefetchBags(state, bufferTag); } @@ -96,13 +98,13 @@ public void onMerge(OnMergeContext c) throws Exception { return new Factory() { @Override public ReduceFn create(K key) { - final StateTag> bufferTag = + final StateTag> bufferTag = StateTags.makeSystemTagInternal(StateTags.combiningValue( BUFFER_NAME, combineFn.getAccumulatorCoder(), (CombineFn) combineFn.getFn().forKey(key, keyCoder))); return new SystemReduceFn(bufferTag) { @Override - public void prefetchOnMerge(MergingStateContext state) throws Exception { + public void prefetchOnMerge(MergingStateContext state) throws Exception { StateMerging.prefetchCombiningValues(state, bufferTag); } @@ -115,9 +117,10 @@ public void onMerge(OnMergeContext c) throws Exception { }; } - private StateTag> bufferTag; + private StateTag> bufferTag; - public SystemReduceFn(StateTag> bufferTag) { + public SystemReduceFn( + StateTag> bufferTag) { this.bufferTag = bufferTag; } @@ -127,8 +130,8 @@ public void processValue(ProcessValueContext c) throws Exception { } @Override - public void prefetchOnTrigger(StateContext c) { - c.access(bufferTag).get(); + public void prefetchOnTrigger(StateContext state) { + state.access(bufferTag).get(); } @Override @@ -142,7 +145,7 @@ public void clearState(Context c) throws Exception { } @Override - public StateContents isEmpty(StateContext state) { + public StateContents isEmpty(StateContext state) { return state.access(bufferTag).isEmpty(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 1b204818e3..05cf137e8c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -20,7 +20,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergingTriggerInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerInfo; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; import com.google.cloud.dataflow.sdk.util.state.State; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; @@ -47,15 +49,14 @@ public class TriggerContextFactory { private final WindowingStrategy windowingStrategy; - private StateInternals stateInternals; + private StateInternals stateInternals; // Future triggers may be able to exploit the active window to state address window mapping. @SuppressWarnings("unused") private ActiveWindowSet activeWindows; private final Coder windowCoder; - public TriggerContextFactory(WindowingStrategy windowingStrategy, - StateInternals stateInternals, ActiveWindowSet activeWindows) { + StateInternals stateInternals, ActiveWindowSet activeWindows) { this.windowingStrategy = windowingStrategy; this.stateInternals = stateInternals; this.activeWindows = activeWindows; @@ -79,12 +80,12 @@ public Trigger.OnMergeContext createOnMergeContext(W window, Timers timers, return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, finishedSets); } - public StateContext createStateContext(W window, ExecutableTrigger trigger) { + public StateContext createStateContext(W window, ExecutableTrigger trigger) { return new StateContextImpl(window, trigger); } - public MergingStateContext createMergingStateContext(ExecutableTrigger trigger, - Collection mergingWindows, W mergeResult) { + public MergingStateContext createMergingStateContext( + W mergeResult, Collection mergingWindows, ExecutableTrigger trigger) { return new MergingStateContextImpl(trigger, mergingWindows, mergeResult); } @@ -259,7 +260,7 @@ public boolean apply(FinishedTriggers finishedSet) { } } - private class StateContextImpl implements StateContext { + private class StateContextImpl implements StateContext { protected final int triggerIndex; protected final StateNamespace windowNamespace; @@ -275,12 +276,13 @@ protected StateNamespace namespaceFor(W window) { } @Override - public StateT access(StateTag address) { + public StateT access(StateTag address) { return stateInternals.state(windowNamespace, address); } } - private class MergingStateContextImpl extends StateContextImpl implements MergingStateContext { + private class MergingStateContextImpl extends StateContextImpl + implements MergingStateContext { private final Collection activeToBeMerged; public MergingStateContextImpl(ExecutableTrigger trigger, Collection activeToBeMerged, @@ -290,13 +292,13 @@ public MergingStateContextImpl(ExecutableTrigger trigger, Collection activ } @Override - public StorageT access(StateTag address) { + public StorageT access(StateTag address) { return stateInternals.state(windowNamespace, address); } @Override public Map accessInEachMergingWindow( - StateTag address) { + StateTag address) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (W mergingWindow : activeToBeMerged) { StateT stateForWindow = stateInternals.state(namespaceFor(mergingWindow), address); @@ -447,7 +449,7 @@ public Instant currentEventTime() { } private class OnMergeContextImpl extends Trigger.OnMergeContext { - private final MergingStateContext state; + private final MergingStateContext state; private final W window; private final Collection mergingWindows; private final Timers timers; @@ -474,7 +476,7 @@ public Trigger.OnMergeContext forTrigger(ExecutableTrigger trigger) { } @Override - public MergingStateContext state() { + public MergingStateContext state() { return state; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index cb6b5d5a4f..eadacc0ff8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -18,6 +18,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.cloud.dataflow.sdk.util.state.ValueState; @@ -26,6 +28,7 @@ import com.google.common.collect.ImmutableMap; import java.util.BitSet; +import java.util.Collection; import java.util.Map; /** @@ -43,7 +46,7 @@ */ public class TriggerRunner { @VisibleForTesting - static final StateTag> FINISHED_BITS_TAG = + static final StateTag> FINISHED_BITS_TAG = StateTags.makeSystemTagInternal(StateTags.value("closed", BitSetCoder.of())); private final ExecutableTrigger rootTrigger; @@ -70,29 +73,30 @@ private FinishedTriggersBitSet readFinishedBits(ValueState state) { } /** Return true if the trigger is closed in the window corresponding to the specified state. */ - public boolean isClosed(StateContext state) { + public boolean isClosed(StateContext state) { return readFinishedBits(state.access(FINISHED_BITS_TAG)).isFinished(rootTrigger); } - public void prefetchForValue(StateContext state) { + public void prefetchForValue(W window, StateContext state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } - rootTrigger.getSpec().prefetchOnElement(state); + rootTrigger.getSpec().prefetchOnElement(contextFactory.createStateContext(window, rootTrigger)); } - public void prefetchOnFire(StateContext state) { + public void prefetchOnFire(W window, StateContext state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } - rootTrigger.getSpec().prefetchOnFire(state); + rootTrigger.getSpec().prefetchOnFire(contextFactory.createStateContext(window, rootTrigger)); } - public void prefetchShouldFire(StateContext state) { + public void prefetchShouldFire(W window, StateContext state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } - rootTrigger.getSpec().prefetchShouldFire(state); + rootTrigger.getSpec().prefetchShouldFire( + contextFactory.createStateContext(window, rootTrigger)); } /** @@ -108,13 +112,15 @@ public void processValue(ReduceFn.ProcessValueContext c) throws Exce persistFinishedSet(c.state(), finishedSet); } - public void prefetchForMerge(MergingStateContext state) { + public void prefetchForMerge( + W window, Collection mergingWindows, MergingStateContext state) { if (isFinishedSetNeeded()) { for (ValueState value : state.accessInEachMergingWindow(FINISHED_BITS_TAG).values()) { value.get(); } } - rootTrigger.getSpec().prefetchOnMerge(state); + rootTrigger.getSpec().prefetchOnMerge(contextFactory.createMergingStateContext( + window, mergingWindows, rootTrigger)); } /** @@ -162,7 +168,8 @@ public void onFire(ReduceFn.Context c) throws Exception { persistFinishedSet(c.state(), finishedSet); } - private void persistFinishedSet(StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { + private void persistFinishedSet( + StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { if (!isFinishedSetNeeded()) { return; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index 715857c5a8..d379cecf48 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; +import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; @@ -49,7 +50,7 @@ public class WatermarkHold implements Serializable { * Return tag for state containing the output watermark hold * used for elements. */ - public static StateTag> + public static StateTag> watermarkHoldTagForOutputTimeFn(OutputTimeFn outputTimeFn) { return StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal("hold", outputTimeFn)); } @@ -61,13 +62,13 @@ public class WatermarkHold implements Serializable { * would take the end-of-window time as its element time.) */ @VisibleForTesting - public static final StateTag> EXTRA_HOLD_TAG = + public static final StateTag> EXTRA_HOLD_TAG = StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal( "extra", OutputTimeFns.outputAtEarliestInputTimestamp())); private final TimerInternals timerInternals; private final WindowingStrategy windowingStrategy; - private final StateTag> elementHoldTag; + private final StateTag> elementHoldTag; public WatermarkHold(TimerInternals timerInternals, WindowingStrategy windowingStrategy) { this.timerInternals = timerInternals; @@ -303,7 +304,7 @@ private void addGarbageCollectionHold(ReduceFn.Context context) { /** * Prefetch watermark holds in preparation for merging. */ - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateContext state) { StateMerging.prefetchWatermarks(state, elementHoldTag); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java index aa1ec00ee7..9ffdbee35f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java @@ -39,7 +39,11 @@ */ public interface WindowingInternals { - StateInternals stateInternals(); + /** + * Unsupported state internals. The key type is unknown. It is up to the user to use the + * correct type of key. + */ + StateInternals stateInternals(); /** * Output the value at the specified timestamp in the listed windows. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 80e6ee992c..2963dc21e6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -37,36 +37,55 @@ * and for running tests that need state. */ @Experimental(Kind.STATE) -public class InMemoryStateInternals implements StateInternals { +public class InMemoryStateInternals implements StateInternals { + + public static InMemoryStateInternals forKey(K key) { + return new InMemoryStateInternals<>(key); + } + + private final K key; + + protected InMemoryStateInternals(K key) { + this.key = key; + } + + @Override + public K getKey() { + return key; + } + private interface InMemoryState { boolean isEmptyForTesting(); } - protected final StateTable inMemoryState = new StateTable() { + protected final StateTable inMemoryState = new StateTable() { @Override - protected StateBinder binderForNamespace(final StateNamespace namespace) { - return new StateBinder() { + protected StateBinder binderForNamespace(final StateNamespace namespace) { + return new StateBinder() { @Override - public ValueState bindValue(StateTag> address, Coder coder) { + public ValueState bindValue( + StateTag> address, Coder coder) { return new InMemoryValue(); } @Override - public BagState bindBag(final StateTag> address, Coder elemCoder) { + public BagState bindBag( + final StateTag> address, Coder elemCoder) { return new InMemoryBag(); } @Override public CombiningValueStateInternal bindCombiningValue( - StateTag> address, - Coder accumCoder, final CombineFn combineFn) { + StateTag> + address, Coder accumCoder, + final CombineFn combineFn) { return new InMemoryCombiningValue(combineFn); } @Override public WatermarkStateInternal bindWatermark( - StateTag> address, + StateTag> address, OutputTimeFn outputTimeFn) { return new WatermarkStateInternalImplementation(outputTimeFn); } @@ -87,7 +106,7 @@ protected boolean isEmptyForTesting(State state) { } @Override - public T state(StateNamespace namespace, StateTag address) { + public T state(StateNamespace namespace, StateTag address) { return inMemoryState.get(namespace, address); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateContext.java new file mode 100644 index 0000000000..03efb5e703 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateContext.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.state; + +import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; + +import java.util.Map; + +/** + * Interface for interacting with persistent state at the moment windows are merging. + * + *

    For internal use only. + */ +@Experimental(Kind.STATE) +public interface MergingStateContext extends StateContext { + /** + * Analogous to {@link #access}, but returned as a map from each window which is + * about to be merged to the corresponding state. Only includes windows which + * are known to have state. + */ + Map accessInEachMergingWindow( + StateTag address); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java similarity index 65% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java index f66d6863b9..8a73308388 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StateContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java @@ -14,18 +14,24 @@ * the License. */ -package com.google.cloud.dataflow.sdk.util; +package com.google.cloud.dataflow.sdk.util.state; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateTag; +import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -/** Interface for interacting with persistent state. */ -public interface StateContext { +/** + * Interface for interacting with per-key persistent state identified via a + * {@link StateTag}. + * + *

    For internal use only. + */ +@Experimental(Kind.STATE) +public interface StateContext { /** * Access the storage for the given {@code address} in the current window. * *

    Never accounts for merged windows. When windows are merged, any state accessed via * this method must be eagerly combined and written into the result window. */ - StateT access(StateTag address); + StateT access(StateTag address); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java index 5f4dc6372f..78aed87009 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java @@ -36,10 +36,13 @@ * used directly, and is highly likely to change. */ @Experimental(Kind.STATE) -public interface StateInternals { +public interface StateInternals { + + /** The key for this {@link StateInternals}. */ + K getKey(); /** * Return the state associated with {@code address} in the specified {@code namespace}. */ - T state(StateNamespace namespace, StateTag address); + T state(StateNamespace namespace, StateTag address); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java index 858091983d..fd783d2bcd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.util.state; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.MergingStateContext; import com.google.common.base.Preconditions; import org.joda.time.Instant; @@ -34,8 +33,8 @@ public class StateMerging { * Clear all state in {@code address} in all windows under merge (even result windows) * in {@code context}. */ - public static void clear( - MergingStateContext context, StateTag address) { + public static void clear( + MergingStateContext context, StateTag address) { for (StateT state : context.accessInEachMergingWindow(address).values()) { state.clear(); } @@ -46,8 +45,8 @@ public static void clear( * {@code context}, except for the bag state in the final state address window which we can * blindly append to. */ - public static void prefetchBags( - MergingStateContext context, StateTag> address) { + public static void prefetchBags( + MergingStateContext context, StateTag> address) { Map> map = context.accessInEachMergingWindow(address); if (map.isEmpty()) { // Nothing to prefetch. @@ -65,8 +64,8 @@ public static void prefetchBags( /** * Merge all bag state in {@code address} across all windows under merge. */ - public static void mergeBags( - MergingStateContext context, StateTag> address) { + public static void mergeBags( + MergingStateContext context, StateTag> address) { mergeBags(context.accessInEachMergingWindow(address).values(), context.access(address)); } @@ -108,8 +107,9 @@ public static void mergeBags( * Prefetch all combining value state for {@code address} across all merging windows in {@code * context}. */ - public static , W extends BoundedWindow> void - prefetchCombiningValues(MergingStateContext context, StateTag address) { + public static , W extends BoundedWindow> void + prefetchCombiningValues(MergingStateContext context, + StateTag address) { for (StateT state : context.accessInEachMergingWindow(address).values()) { state.get(); } @@ -118,9 +118,9 @@ public static void mergeBags( /** * Merge all value state in {@code address} across all merging windows in {@code context}. */ - public static void mergeCombiningValues( - MergingStateContext context, - StateTag> address) { + public static void mergeCombiningValues( + MergingStateContext context, + StateTag> address) { mergeCombiningValues( context.accessInEachMergingWindow(address).values(), context.access(address)); } @@ -164,8 +164,9 @@ public static void mergeCombi * Prefetch all watermark state for {@code address} across all merging windows in * {@code context}. */ - public static void prefetchWatermarks( - MergingStateContext context, StateTag> address) { + public static void prefetchWatermarks( + MergingStateContext context, + StateTag> address) { Map> map = context.accessInEachMergingWindow(address); WatermarkStateInternal result = context.access(address); if (map.isEmpty()) { @@ -191,8 +192,9 @@ public static void prefetchWatermarks( * Merge all watermark state in {@code address} across all merging windows in {@code context}, * where the final merge result window is {@code mergeResult}. */ - public static void mergeWatermarks( - MergingStateContext context, StateTag> address, + public static void mergeWatermarks( + MergingStateContext context, + StateTag> address, W mergeResult) { mergeWatermarks( context.accessInEachMergingWindow(address).values(), context.access(address), mergeResult); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java index be9ae18550..5529b9fb64 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java @@ -27,19 +27,19 @@ /** * Table mapping {@code StateNamespace} and {@code StateTag} to a {@code State} instance. */ -public abstract class StateTable { +public abstract class StateTable { - private final Table, State> stateTable = - Tables.newCustomTable(new HashMap, State>>(), - new Supplier, State>>() { + private final Table, State> stateTable = + Tables.newCustomTable(new HashMap, State>>(), + new Supplier, State>>() { @Override - public Map, State> get() { + public Map, State> get() { return new HashMap<>(); } }); public StateT get( - StateNamespace namespace, StateTag tag) { + StateNamespace namespace, StateTag tag) { State storage = stateTable.get(namespace, tag); if (storage != null) { @SuppressWarnings("unchecked") @@ -68,7 +68,7 @@ public boolean isNamespaceInUse(StateNamespace namespace) { return stateTable.containsRow(namespace); } - public Map, State> getTagsInUse(StateNamespace namespace) { + public Map, State> getTagsInUse(StateNamespace namespace) { return stateTable.row(namespace); } @@ -80,5 +80,5 @@ public Set getNamespacesInUse() { * Provide the {@code StateBinder} to use for creating {@code Storage} instances * in the specified {@code namespace}. */ - protected abstract StateBinder binderForNamespace(StateNamespace namespace); + protected abstract StateBinder binderForNamespace(StateNamespace namespace); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java index d221543309..db052f8682 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java @@ -35,22 +35,26 @@ * *

    Currently, this can only be used in a step immediately following a {@link GroupByKey}. * + * @param The type of key that must be used with the state tag. Contravariant: methods should + * accept values of type {@code KeyedStateTag}. * @param The type of state being tagged. */ @Experimental(Kind.STATE) -public interface StateTag extends Serializable { +public interface StateTag extends Serializable { /** * Visitor for binding a {@link StateTag} and to the associated {@link State}. + * + * @param the type of key this binder embodies. */ - public interface StateBinder { - ValueState bindValue(StateTag> address, Coder coder); + public interface StateBinder { + ValueState bindValue(StateTag> address, Coder coder); - BagState bindBag(StateTag> address, Coder elemCoder); + BagState bindBag(StateTag> address, Coder elemCoder); CombiningValueStateInternal bindCombiningValue( - StateTag> address, + StateTag> address, Coder accumCoder, CombineFn combineFn); /** @@ -60,7 +64,7 @@ public interface StateBinder { * added to the returned {@link WatermarkStateInternal} are to be combined. */ WatermarkStateInternal bindWatermark( - StateTag> address, + StateTag> address, OutputTimeFn outputTimeFn); } @@ -75,5 +79,5 @@ WatermarkStateInternal bindWatermark( /** * Use the {@code binder} to create an instance of {@code StateT} appropriate for this address. */ - StateT bind(StateBinder binder); + StateT bind(StateBinder binder); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index 89e2013431..b072f6d7b1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -36,6 +36,7 @@ public class StateTags { private static final CoderRegistry STANDARD_REGISTRY = new CoderRegistry(); + static { STANDARD_REGISTRY.registerStandardCoders(); } @@ -53,10 +54,14 @@ private enum StateKind { private StateTags() { } + private interface SystemStateTag { + StateTag asKind(StateKind kind); + } + /** * Create a simple state tag for values of type {@code T}. */ - public static StateTag> value(String id, Coder valueCoder) { + public static StateTag> value(String id, Coder valueCoder) { return new ValueStateTag<>(new StructuredId(id), valueCoder); } @@ -65,7 +70,7 @@ public static StateTag> value(String id, Coder valueCoder) * multiple {@code InputT}s into a single {@code OutputT}. */ public static - StateTag> + StateTag> combiningValue( String id, Coder accumCoder, CombineFn combineFn) { return combiningValueInternal(id, accumCoder, combineFn); @@ -78,10 +83,10 @@ public static StateTag> value(String id, Coder valueCoder) *

    This determines the {@code Coder} from the given {@code Coder}, and * should only be used to initialize static values. */ - public static StateTag> + public static + StateTag> combiningValueFromInputInternal( - String id, Coder inputCoder, CombineFn combineFn) { + String id, Coder inputCoder, CombineFn combineFn) { try { Coder accumCoder = combineFn.getAccumulatorCoder(STANDARD_REGISTRY, inputCoder); return combiningValueInternal(id, accumCoder, combineFn); @@ -93,7 +98,7 @@ public static StateTag> value(String id, Coder valueCoder) } private static StateTag> + OutputT> StateTag> combiningValueInternal( String id, Coder accumCoder, CombineFn combineFn) { return @@ -105,14 +110,14 @@ public static StateTag> value(String id, Coder valueCoder) * Create a state tag that is optimized for adding values frequently, and * occasionally retrieving all the values that have been added. */ - public static StateTag> bag(String id, Coder elemCoder) { + public static StateTag> bag(String id, Coder elemCoder) { return new BagStateTag(new StructuredId(id), elemCoder); } /** * Create a state tag for holding the watermark. */ - public static StateTag> + public static StateTag> watermarkStateInternal(String id, OutputTimeFn outputTimeFn) { return new WatermarkStateTagInternal(new StructuredId(id), outputTimeFn); } @@ -121,19 +126,22 @@ public static StateTag> bag(String id, Coder elemCoder) { * Convert an arbitrary {@code StateTag} to a system-internal tag that is guaranteed not to * collide with any user tags. */ - public static StateTag makeSystemTagInternal( - StateTag tag) { - if (!(tag instanceof StateTagBase)) { + public static StateTag makeSystemTagInternal( + StateTag tag) { + if (!(tag instanceof SystemStateTag)) { throw new IllegalArgumentException("Expected subclass of StateTagBase, got " + tag); } - return ((StateTagBase) tag).asKind(StateKind.SYSTEM); + return ((SystemStateTag) tag).asKind(StateKind.SYSTEM); } - public static StateTag> convertToBagTagInternal( - StateTag> combiningTag) { + public static StateTag> + convertToBagTagInternal( + StateTag> combiningTag) { if (!(combiningTag instanceof CombiningValueStateTag)) { throw new IllegalArgumentException("Unexpected StateTag " + combiningTag); } + // Checked above; conversion to a bag tag depends on the provided tag being one of those + // created via the factory methods in this class. @SuppressWarnings("unchecked") CombiningValueStateTag typedTag = (CombiningValueStateTag) combiningTag; @@ -194,7 +202,11 @@ public int hashCode() { } } - private abstract static class StateTagBase implements StateTag { + /** + * A base class that just manages the structured ids. + */ + private abstract static class StateTagBase + implements StateTag, SystemStateTag { protected final StructuredId id; @@ -214,12 +226,13 @@ public String toString() { .toString(); } - protected abstract StateTag asKind(StateKind kind); - @Override public void appendTo(Appendable sb) throws IOException { id.appendTo(sb); } + + @Override + public abstract StateTag asKind(StateKind kind); } /** @@ -227,7 +240,8 @@ public void appendTo(Appendable sb) throws IOException { * * @param the type of value being stored */ - private static class ValueStateTag extends StateTagBase> { + private static class ValueStateTag extends StateTagBase> + implements StateTag> { private final Coder coder; @@ -237,7 +251,7 @@ private ValueStateTag(StructuredId id, Coder coder) { } @Override - public ValueState bind(StateBinder visitor) { + public ValueState bind(StateBinder visitor) { return visitor.bindValue(this, coder); } @@ -262,20 +276,22 @@ public int hashCode() { } @Override - protected StateTag> asKind(StateKind kind) { + public StateTag> asKind(StateKind kind) { return new ValueStateTag(id.asKind(kind), coder); } } /** - * A general purpose state cell for values of type {@code T}. + * A state cell for values that are combined according to a {@link CombineFn}. * * @param the type of input values * @param type of mutable accumulator values * @param type of output values */ private static class CombiningValueStateTag - extends StateTagBase> { + extends StateTagBase> + implements StateTag>, + SystemStateTag> { private final Coder accumCoder; private final CombineFn combineFn; @@ -289,7 +305,8 @@ private CombiningValueStateTag( } @Override - public CombiningValueStateInternal bind(StateBinder visitor) { + public CombiningValueStateInternal bind( + StateBinder visitor) { return visitor.bindCombiningValue(this, accumCoder, combineFn); } @@ -314,12 +331,13 @@ public int hashCode() { } @Override - protected StateTag> asKind( - StateKind kind) { + public StateTag> + asKind(StateKind kind) { return new CombiningValueStateTag<>(id.asKind(kind), accumCoder, combineFn); + } - private StateTag> asBagTag() { + private StateTag> asBagTag() { return new BagStateTag(id, accumCoder); } } @@ -330,7 +348,8 @@ private StateTag> asBagTag() { * * @param the type of value in the bag */ - private static class BagStateTag extends StateTagBase> { + private static class BagStateTag extends StateTagBase> + implements StateTag>{ private final Coder elemCoder; @@ -340,7 +359,7 @@ private BagStateTag(StructuredId id, Coder elemCoder) { } @Override - public BagState bind(StateBinder visitor) { + public BagState bind(StateBinder visitor) { return visitor.bindBag(this, elemCoder); } @@ -365,13 +384,13 @@ public int hashCode() { } @Override - protected StateTag> asKind(StateKind kind) { + public StateTag> asKind(StateKind kind) { return new BagStateTag<>(id.asKind(kind), elemCoder); } } private static class WatermarkStateTagInternal - extends StateTagBase> { + extends StateTagBase> { /** * When multiple output times are added to hold the watermark, this determines how they are @@ -386,7 +405,7 @@ private WatermarkStateTagInternal(StructuredId id, OutputTimeFn outpu } @Override - public WatermarkStateInternal bind(StateBinder visitor) { + public WatermarkStateInternal bind(StateBinder visitor) { return visitor.bindWatermark(this, outputTimeFn); } @@ -410,7 +429,7 @@ public int hashCode() { } @Override - protected StateTag> asKind(StateKind kind) { + public StateTag> asKind(StateKind kind) { return new WatermarkStateTagInternal(id.asKind(kind), outputTimeFn); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java index 0b1a7521f4..8f66e5a41c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java @@ -44,13 +44,13 @@ @RunWith(JUnit4.class) public class MergingActiveWindowSetTest { private Sessions windowFn; - private StateInternals state; + private StateInternals state; private MergingActiveWindowSet set; @Before public void before() { windowFn = Sessions.withGapDuration(Duration.millis(10)); - state = new InMemoryStateInternals(); + state = InMemoryStateInternals.forKey("dummyKey"); set = new MergingActiveWindowSet<>(windowFn, state); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index 2088ac3c34..f7fe75eac4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -70,6 +70,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Set; @@ -86,7 +87,10 @@ * @param The type of windows being used. */ public class ReduceFnTester { - private final TestInMemoryStateInternals stateInternals = new TestInMemoryStateInternals(); + private static final String KEY = "TEST_KEY"; + + private final TestInMemoryStateInternals stateInternals = + new TestInMemoryStateInternals<>(KEY); private final TestTimerInternals timerInternals = new TestTimerInternals(); private final WindowFn windowFn; @@ -95,7 +99,6 @@ public class ReduceFnTester { private final WindowingStrategy objectStrategy; private final ReduceFn reduceFn; - private static final String KEY = "TEST_KEY"; private ExecutableTrigger executableTrigger; private final InMemoryLongSumAggregator droppedDueToClosedWindow = @@ -180,28 +183,29 @@ public boolean isMarkedFinished(W window) { public final void assertHasOnlyGlobalAndFinishedSetsFor(W... expectedWindows) { assertHasOnlyGlobalAndAllowedTags( ImmutableSet.copyOf(expectedWindows), - ImmutableSet.>of(TriggerRunner.FINISHED_BITS_TAG)); + ImmutableSet.>of(TriggerRunner.FINISHED_BITS_TAG)); } @SafeVarargs public final void assertHasOnlyGlobalAndFinishedSetsAndPaneInfoFor(W... expectedWindows) { assertHasOnlyGlobalAndAllowedTags( ImmutableSet.copyOf(expectedWindows), - ImmutableSet.>of(TriggerRunner.FINISHED_BITS_TAG, PaneInfoTracker.PANE_INFO_TAG, + ImmutableSet.>of( + TriggerRunner.FINISHED_BITS_TAG, PaneInfoTracker.PANE_INFO_TAG, WatermarkHold.watermarkHoldTagForOutputTimeFn(objectStrategy.getOutputTimeFn()), WatermarkHold.EXTRA_HOLD_TAG)); } public final void assertHasOnlyGlobalState() { assertHasOnlyGlobalAndAllowedTags( - Collections.emptySet(), Collections.>emptySet()); + Collections.emptySet(), Collections.>emptySet()); } @SafeVarargs public final void assertHasOnlyGlobalAndPaneInfoFor(W... expectedWindows) { assertHasOnlyGlobalAndAllowedTags( ImmutableSet.copyOf(expectedWindows), - ImmutableSet.>of( + ImmutableSet.>of( PaneInfoTracker.PANE_INFO_TAG, WatermarkHold.watermarkHoldTagForOutputTimeFn(objectStrategy.getOutputTimeFn()), WatermarkHold.EXTRA_HOLD_TAG)); @@ -212,30 +216,30 @@ public final void assertHasOnlyGlobalAndPaneInfoFor(W... expectedWindows) { * {@code expectedWindows} and that each of these windows has only tags from {@code allowedTags}. */ private void assertHasOnlyGlobalAndAllowedTags( - Set expectedWindows, Set> allowedTags) { + Set expectedWindows, Set> allowedTags) { Set expectedWindowsSet = new HashSet<>(); for (W expectedWindow : expectedWindows) { expectedWindowsSet.add(windowNamespace(expectedWindow)); } - Map>> actualWindows = new HashMap<>(); + Map>> actualWindows = new HashMap<>(); for (StateNamespace namespace : stateInternals.getNamespacesInUse()) { if (namespace instanceof StateNamespaces.GlobalNamespace) { continue; } else if (namespace instanceof StateNamespaces.WindowNamespace) { - Set> tagsInUse = stateInternals.getTagsInUse(namespace); + Set> tagsInUse = stateInternals.getTagsInUse(namespace); if (tagsInUse.isEmpty()) { continue; } actualWindows.put(namespace, tagsInUse); - Set> unexpected = Sets.difference(tagsInUse, allowedTags); + Set> unexpected = Sets.difference(tagsInUse, allowedTags); if (unexpected.isEmpty()) { continue; } else { fail(namespace + " has unexpected states: " + tagsInUse); } } else if (namespace instanceof StateNamespaces.WindowAndTriggerNamespace) { - Set> tagsInUse = stateInternals.getTagsInUse(namespace); + Set> tagsInUse = stateInternals.getTagsInUse(namespace); assertTrue(namespace + " contains " + tagsInUse, tagsInUse.isEmpty()); } else { fail("Unrecognized namespace " + namespace); @@ -353,10 +357,16 @@ public void fireTimer(W window, Instant timestamp, TimeDomain domain) { /** * Simulate state. */ - private static class TestInMemoryStateInternals extends InMemoryStateInternals { - public Set> getTagsInUse(StateNamespace namespace) { - Set> inUse = new HashSet<>(); - for (Map.Entry, State> entry : inMemoryState.getTagsInUse(namespace).entrySet()) { + private static class TestInMemoryStateInternals extends InMemoryStateInternals { + + public TestInMemoryStateInternals(K key) { + super(key); + } + + public Set> getTagsInUse(StateNamespace namespace) { + Set> inUse = new HashSet<>(); + for (Entry, State> entry : + inMemoryState.getTagsInUse(namespace).entrySet()) { if (!isEmptyForTesting(entry.getValue())) { inUse.add(entry.getKey()); } @@ -426,8 +436,12 @@ public void writePCollectionViewData( } @Override - public StateInternals stateInternals() { - return stateInternals; + public StateInternals stateInternals() { + // Safe for testing only + @SuppressWarnings({"unchecked", "rawtypes"}) + TestInMemoryStateInternals untypedStateInternals = + (TestInMemoryStateInternals) stateInternals; + return untypedStateInternals; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index ea631cfba0..e5507ced8d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -96,7 +96,8 @@ public SimpleTriggerTester withAllowedLateness(Duration allowedLateness) thro protected final WindowingStrategy windowingStrategy; - private final TestInMemoryStateInternals stateInternals = new TestInMemoryStateInternals(); + private final TestInMemoryStateInternals stateInternals = + new TestInMemoryStateInternals(); private final TestTimerInternals timerInternals = new TestTimerInternals(); private final TriggerContextFactory contextFactory; private final WindowFn windowFn; @@ -176,7 +177,7 @@ public void assertCleared(W window) { @SuppressWarnings("unchecked") WindowAndTriggerNamespace namespace = (WindowAndTriggerNamespace) untypedNamespace; if (namespace.getWindow().equals(window)) { - Set> tagsInUse = stateInternals.getTagsInUse(namespace); + Set tagsInUse = stateInternals.getTagsInUse(namespace); assertTrue("Trigger has not cleared tags: " + tagsInUse, tagsInUse.isEmpty()); } } @@ -343,11 +344,16 @@ private FinishedTriggers getFinishedSet(W window) { /** * Simulate state. */ - private static class TestInMemoryStateInternals extends InMemoryStateInternals { + private static class TestInMemoryStateInternals extends InMemoryStateInternals { - public Set> getTagsInUse(StateNamespace namespace) { - Set> inUse = new HashSet<>(); - for (Map.Entry, State> entry : inMemoryState.getTagsInUse(namespace).entrySet()) { + public TestInMemoryStateInternals() { + super(null); + } + + public Set> getTagsInUse(StateNamespace namespace) { + Set> inUse = new HashSet<>(); + for (Map.Entry, State> entry : + inMemoryState.getTagsInUse(namespace).entrySet()) { if (!isEmptyForTesting(entry.getValue())) { inUse.add(entry.getKey()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java index ca4c785229..4df13ae939 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java @@ -44,21 +44,23 @@ public class InMemoryStateInternalsTest { private static final StateNamespace NAMESPACE_2 = new StateNamespaceForTest("ns2"); private static final StateNamespace NAMESPACE_3 = new StateNamespaceForTest("ns3"); - private static final StateTag> STRING_VALUE_ADDR = + private static final StateTag> STRING_VALUE_ADDR = StateTags.value("stringValue", StringUtf8Coder.of()); - private static final StateTag> + private static final StateTag> SUM_INTEGER_ADDR = StateTags.combiningValueFromInputInternal( "sumInteger", VarIntCoder.of(), new Sum.SumIntegerFn()); - private static final StateTag> STRING_BAG_ADDR = + private static final StateTag> STRING_BAG_ADDR = StateTags.bag("stringBag", StringUtf8Coder.of()); - private static final StateTag> WATERMARK_EARLIEST_ADDR = + private static final StateTag> + WATERMARK_EARLIEST_ADDR = StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - private static final StateTag> WATERMARK_LATEST_ADDR = + private static final StateTag> + WATERMARK_LATEST_ADDR = StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtLatestInputTimestamp()); - private static final StateTag> WATERMARK_EOW_ADDR = + private static final StateTag> WATERMARK_EOW_ADDR = StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEndOfWindow()); - InMemoryStateInternals underTest = new InMemoryStateInternals(); + InMemoryStateInternals underTest = InMemoryStateInternals.forKey("dummyKey"); @Test public void testValue() throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java index fa3c82634a..47f7224e90 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java @@ -38,10 +38,10 @@ public class StateTagTest { @Test public void testValueEquality() { - StateTag fooVarInt1 = StateTags.value("foo", VarIntCoder.of()); - StateTag fooVarInt2 = StateTags.value("foo", VarIntCoder.of()); - StateTag fooBigEndian = StateTags.value("foo", BigEndianIntegerCoder.of()); - StateTag barVarInt = StateTags.value("bar", VarIntCoder.of()); + StateTag fooVarInt1 = StateTags.value("foo", VarIntCoder.of()); + StateTag fooVarInt2 = StateTags.value("foo", VarIntCoder.of()); + StateTag fooBigEndian = StateTags.value("foo", BigEndianIntegerCoder.of()); + StateTag barVarInt = StateTags.value("bar", VarIntCoder.of()); assertEquals(fooVarInt1, fooVarInt2); assertNotEquals(fooVarInt1, fooBigEndian); @@ -50,10 +50,10 @@ public void testValueEquality() { @Test public void testBagEquality() { - StateTag fooVarInt1 = StateTags.bag("foo", VarIntCoder.of()); - StateTag fooVarInt2 = StateTags.bag("foo", VarIntCoder.of()); - StateTag fooBigEndian = StateTags.bag("foo", BigEndianIntegerCoder.of()); - StateTag barVarInt = StateTags.bag("bar", VarIntCoder.of()); + StateTag fooVarInt1 = StateTags.bag("foo", VarIntCoder.of()); + StateTag fooVarInt2 = StateTags.bag("foo", VarIntCoder.of()); + StateTag fooBigEndian = StateTags.bag("foo", BigEndianIntegerCoder.of()); + StateTag barVarInt = StateTags.bag("bar", VarIntCoder.of()); assertEquals(fooVarInt1, fooVarInt2); assertNotEquals(fooVarInt1, fooBigEndian); @@ -62,14 +62,14 @@ public void testBagEquality() { @Test public void testWatermarkBagEquality() { - StateTag foo1 = StateTags.watermarkStateInternal( + StateTag foo1 = StateTags.watermarkStateInternal( "foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - StateTag foo2 = StateTags.watermarkStateInternal( + StateTag foo2 = StateTags.watermarkStateInternal( "foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - StateTag bar = StateTags.watermarkStateInternal( + StateTag bar = StateTags.watermarkStateInternal( "bar", OutputTimeFns.outputAtEarliestInputTimestamp()); - StateTag bar2 = StateTags.watermarkStateInternal( + StateTag bar2 = StateTags.watermarkStateInternal( "bar", OutputTimeFns.outputAtLatestInputTimestamp()); // Same id, same fn. @@ -87,12 +87,12 @@ public void testCombiningValueEquality() { Coder input2 = BigEndianIntegerCoder.of(); MinIntegerFn minFn = new Min.MinIntegerFn(); - StateTag fooCoder1Max1 = StateTags.combiningValueFromInputInternal("foo", input1, maxFn); - StateTag fooCoder1Max2 = StateTags.combiningValueFromInputInternal("foo", input1, maxFn); - StateTag fooCoder1Min = StateTags.combiningValueFromInputInternal("foo", input1, minFn); + StateTag fooCoder1Max1 = StateTags.combiningValueFromInputInternal("foo", input1, maxFn); + StateTag fooCoder1Max2 = StateTags.combiningValueFromInputInternal("foo", input1, maxFn); + StateTag fooCoder1Min = StateTags.combiningValueFromInputInternal("foo", input1, minFn); - StateTag fooCoder2Max = StateTags.combiningValueFromInputInternal("foo", input2, maxFn); - StateTag barCoder1Max = StateTags.combiningValueFromInputInternal("bar", input1, maxFn); + StateTag fooCoder2Max = StateTags.combiningValueFromInputInternal("foo", input2, maxFn); + StateTag barCoder1Max = StateTags.combiningValueFromInputInternal("bar", input1, maxFn); // Same name, coder and combineFn assertEquals(fooCoder1Max1, fooCoder1Max2); From 6edc6e0f0bdd608cbdf3c3db82b7d0b3a18e3f59 Mon Sep 17 00:00:00 2001 From: klk Date: Fri, 12 Feb 2016 09:00:20 -0800 Subject: [PATCH 129/751] Add KeyedCombiningValueStateTag containing a KeyedCombineFn This state tag binds to state that combines values added to it according to a KeyedCombineFn. The interface to the state itself is the same as that for a CombingFn - the key is provided by the keyed StateContext in which the state cell is used. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114539022 --- .../state/CombiningValueStateInternal.java | 4 +- .../util/state/InMemoryStateInternals.java | 30 ++++--- .../dataflow/sdk/util/state/StateMerging.java | 2 +- .../dataflow/sdk/util/state/StateTag.java | 6 ++ .../dataflow/sdk/util/state/StateTags.java | 86 +++++++++++++++---- 5 files changed, 100 insertions(+), 28 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java index bba93b7869..2f18b9c80b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java @@ -40,7 +40,7 @@ public interface CombiningValueStateInternal void addAccum(AccumT accum); /** - * Return the combiner function for this state. + * Merge the given accumulators according to the underlying combiner. */ - CombineFn getCombineFn(); + AccumT mergeAccumulators(Iterable accumulators); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 2963dc21e6..7f42f6bcfc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; @@ -80,7 +81,7 @@ public BagState bindBag( StateTag> address, Coder accumCoder, final CombineFn combineFn) { - return new InMemoryCombiningValue(combineFn); + return new InMemoryCombiningValue(combineFn.asKeyedFn()); } @Override @@ -89,6 +90,15 @@ public WatermarkStateInternal bindWatermark( OutputTimeFn outputTimeFn) { return new WatermarkStateInternalImplementation(outputTimeFn); } + + @Override + public CombiningValueStateInternal + bindKeyedCombiningValue( + StateTag> + address, Coder accumCoder, + KeyedCombineFn combineFn) { + return new InMemoryCombiningValue(combineFn); + } }; } }; @@ -208,19 +218,19 @@ public String toString() { private final class InMemoryCombiningValue implements CombiningValueStateInternal, InMemoryState { private boolean isCleared = true; - private final CombineFn combineFn; + private final KeyedCombineFn combineFn; private AccumT accum; - private InMemoryCombiningValue(CombineFn combineFn) { + private InMemoryCombiningValue(KeyedCombineFn combineFn) { this.combineFn = combineFn; - accum = combineFn.createAccumulator(); + accum = combineFn.createAccumulator(key); } @Override public void clear() { // Even though we're clearing we can't remove this from the in-memory state map, since // other users may already have a handle on this CombiningValue. - accum = combineFn.createAccumulator(); + accum = combineFn.createAccumulator(key); isCleared = true; } @@ -229,7 +239,7 @@ public StateContents get() { return new StateContents() { @Override public OutputT read() { - return combineFn.extractOutput(accum); + return combineFn.extractOutput(key, accum); } }; } @@ -237,7 +247,7 @@ public OutputT read() { @Override public void add(InputT input) { isCleared = false; - accum = combineFn.addInput(accum, input); + accum = combineFn.addInput(key, accum, input); } @Override @@ -263,12 +273,12 @@ public Boolean read() { @Override public void addAccum(AccumT accum) { isCleared = false; - this.accum = combineFn.mergeAccumulators(Arrays.asList(this.accum, accum)); + this.accum = combineFn.mergeAccumulators(key, Arrays.asList(this.accum, accum)); } @Override - public CombineFn getCombineFn() { - return combineFn; + public AccumT mergeAccumulators(Iterable accumulators) { + return combineFn.mergeAccumulators(key, accumulators); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java index fd783d2bcd..9cea213547 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java @@ -151,7 +151,7 @@ public static void mergeCombi accumulators.add(future.read()); } // Merge (possibly update and return one of the existing accumulators). - AccumT merged = result.getCombineFn().mergeAccumulators(accumulators); + AccumT merged = result.mergeAccumulators(accumulators); // Clear sources. for (CombiningValueStateInternal source : sources) { source.clear(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java index db052f8682..e7b02dfc5a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; @@ -57,6 +58,11 @@ public interface StateBinder { StateTag> address, Coder accumCoder, CombineFn combineFn); + CombiningValueStateInternal + bindKeyedCombiningValue( + StateTag> address, + Coder accumCoder, KeyedCombineFn combineFn); + /** * Bind to a watermark {@link StateTag}. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index b072f6d7b1..caa1ab643f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderRegistry; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.common.base.MoreObjects; @@ -76,6 +77,18 @@ public static StateTag> value(String id, Coder valu return combiningValueInternal(id, accumCoder, combineFn); } + /** + * Create a state tag for values that use a {@link KeyedCombineFn} to automatically merge + * multiple {@code InputT}s into a single {@code OutputT}. The key provided to the + * {@link KeyedCombineFn} comes from the keyed {@link StateContext}. + */ + public static StateTag> + keyedCombiningValue(String id, Coder accumCoder, + KeyedCombineFn combineFn) { + return keyedCombiningValueInternal(id, accumCoder, combineFn); + } + /** * Create a state tag for values that use a {@link CombineFn} to automatically merge * multiple {@code InputT}s into a single {@code OutputT}. @@ -106,6 +119,15 @@ public static StateTag> value(String id, Coder valu new StructuredId(id), accumCoder, combineFn); } + private static + StateTag> keyedCombiningValueInternal( + String id, + Coder accumCoder, + KeyedCombineFn combineFn) { + return new KeyedCombiningValueStateTag( + new StructuredId(id), accumCoder, combineFn); + } + /** * Create a state tag that is optimized for adding values frequently, and * occasionally retrieving all the values that have been added. @@ -123,7 +145,7 @@ public static StateTag> bag(String id, Coder elemCode } /** - * Convert an arbitrary {@code StateTag} to a system-internal tag that is guaranteed not to + * Convert an arbitrary {@link StateTag} to a system-internal tag that is guaranteed not to * collide with any user tags. */ public static StateTag makeSystemTagInternal( @@ -131,20 +153,23 @@ public static StateTag makeSystemTagInterna if (!(tag instanceof SystemStateTag)) { throw new IllegalArgumentException("Expected subclass of StateTagBase, got " + tag); } - return ((SystemStateTag) tag).asKind(StateKind.SYSTEM); + // Checked above + @SuppressWarnings("unchecked") + SystemStateTag typedTag = (SystemStateTag) tag; + return typedTag.asKind(StateKind.SYSTEM); } - public static StateTag> + public static StateTag> convertToBagTagInternal( - StateTag> combiningTag) { + StateTag> combiningTag) { if (!(combiningTag instanceof CombiningValueStateTag)) { throw new IllegalArgumentException("Unexpected StateTag " + combiningTag); } // Checked above; conversion to a bag tag depends on the provided tag being one of those // created via the factory methods in this class. @SuppressWarnings("unchecked") - CombiningValueStateTag typedTag = - (CombiningValueStateTag) combiningTag; + KeyedCombiningValueStateTag typedTag = + (KeyedCombiningValueStateTag) combiningTag; return typedTag.asBagTag(); } @@ -289,7 +314,7 @@ public StateTag> asKind(StateKind kind) { * @param type of output values */ private static class CombiningValueStateTag - extends StateTagBase> + extends KeyedCombiningValueStateTag implements StateTag>, SystemStateTag> { @@ -299,15 +324,47 @@ private static class CombiningValueStateTag private CombiningValueStateTag( StructuredId id, Coder accumCoder, CombineFn combineFn) { - super(id); + super(id, accumCoder, combineFn.asKeyedFn()); this.combineFn = combineFn; this.accumCoder = accumCoder; } + @Override + public StateTag> + asKind(StateKind kind) { + return new CombiningValueStateTag( + id.asKind(kind), accumCoder, combineFn); + } + } + + + /** + * A general purpose state cell for values of type {@code T}. + * + * @param the type of keys + * @param the type of input values + * @param type of mutable accumulator values + * @param type of output values + */ + private static class KeyedCombiningValueStateTag + extends StateTagBase> + implements SystemStateTag> { + + private final Coder accumCoder; + private final KeyedCombineFn keyedCombineFn; + + protected KeyedCombiningValueStateTag( + StructuredId id, + Coder accumCoder, KeyedCombineFn combineFn) { + super(id); + this.keyedCombineFn = combineFn; + this.accumCoder = accumCoder; + } + @Override public CombiningValueStateInternal bind( - StateBinder visitor) { - return visitor.bindCombiningValue(this, accumCoder, combineFn); + StateBinder visitor) { + return visitor.bindKeyedCombiningValue(this, accumCoder, keyedCombineFn); } @Override @@ -320,7 +377,7 @@ public boolean equals(Object obj) { return false; } - CombiningValueStateTag that = (CombiningValueStateTag) obj; + KeyedCombiningValueStateTag that = (KeyedCombiningValueStateTag) obj; return Objects.equals(this.id, that.id) && Objects.equals(this.accumCoder, that.accumCoder); } @@ -331,10 +388,9 @@ public int hashCode() { } @Override - public StateTag> - asKind(StateKind kind) { - return new CombiningValueStateTag<>(id.asKind(kind), accumCoder, combineFn); - + public StateTag> asKind( + StateKind kind) { + return new KeyedCombiningValueStateTag<>(id.asKind(kind), accumCoder, keyedCombineFn); } private StateTag> asBagTag() { From da1a5bf75ff46aded43b0a1e827a2e677a646cac Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 12 Feb 2016 18:57:35 -0800 Subject: [PATCH 130/751] Explicitly select GroupAlsoByWindow in default GBK The default expansion of GroupByKey uses the default, general version of GroupAlsoByWindow. Make GroupAlsoByWindowViaOutputBufferDoFn visible outside of the util package. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114589839 --- .../dataflow/sdk/transforms/GroupByKey.java | 20 ++++++++++++------- ...GroupAlsoByWindowsViaOutputBufferDoFn.java | 2 +- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java index 6c9defadfe..dee7d956ef 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java @@ -25,13 +25,15 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.ValueWithMetadata; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.InvalidWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsDoFn; +import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsViaOutputBufferDoFn; import com.google.cloud.dataflow.sdk.util.ReifyTimestampAndWindowsDoFn; +import com.google.cloud.dataflow.sdk.util.SystemReduceFn; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; @@ -418,14 +420,18 @@ public PCollection>> apply( inputIterableWindowedValueCoder.getValueCoder(); Coder> outputValueCoder = IterableCoder.of(inputIterableElementValueCoder); - Coder>> outputKvCoder = - KvCoder.of(keyCoder, outputValueCoder); + Coder>> outputKvCoder = KvCoder.of(keyCoder, outputValueCoder); - GroupAlsoByWindowsDoFn, ?> fn = - GroupAlsoByWindowsDoFn.createForIterable( - windowingStrategy, inputIterableElementValueCoder); + return input + .apply(ParDo.of(groupAlsoByWindowsFn(windowingStrategy, inputIterableElementValueCoder))) + .setCoder(outputKvCoder); + } - return input.apply(ParDo.of(fn)).setCoder(outputKvCoder); + private GroupAlsoByWindowsViaOutputBufferDoFn, W> + groupAlsoByWindowsFn( + WindowingStrategy strategy, Coder inputIterableElementValueCoder) { + return new GroupAlsoByWindowsViaOutputBufferDoFn, W>( + strategy, SystemReduceFn.buffering(inputIterableElementValueCoder)); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java index bb3b2194b6..de137da665 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java @@ -30,7 +30,7 @@ * implementation is applicable. */ @SystemDoFnInternal -class GroupAlsoByWindowsViaOutputBufferDoFn +public class GroupAlsoByWindowsViaOutputBufferDoFn extends GroupAlsoByWindowsDoFn { private final WindowingStrategy strategy; From 7a9838149c1b40c354b460e609dd417242ef8c69 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Fri, 12 Feb 2016 19:17:46 -0800 Subject: [PATCH 131/751] Add ByteKeyRange and ByteKeyRangeTracker The former abstracts a range of ByteKeys, and the latter uses the range to provide a RangeTracker to support Dynamic Work Rebalancing. This is useful for services like Google Cloud Bigtable or its open-source analog Apache HBase that use byte arrays as keys. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114590566 --- .../dataflow/sdk/io/range/ByteKeyRange.java | 376 ++++++++++++++ .../sdk/io/range/ByteKeyRangeTracker.java | 117 +++++ .../sdk/io/range/ByteKeyRangeTest.java | 463 ++++++++++++++++++ .../sdk/io/range/ByteKeyRangeTrackerTest.java | 118 +++++ .../dataflow/sdk/io/range/ByteKeyTest.java | 4 +- 5 files changed, 1076 insertions(+), 2 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java new file mode 100644 index 0000000000..6f58d393f9 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java @@ -0,0 +1,376 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; +import static com.google.common.base.Verify.verify; + +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +/** + * A class representing a range of {@link ByteKey ByteKeys}. + * + *

    Instances of {@link ByteKeyRange} are immutable. + * + *

    A {@link ByteKeyRange} enforces the restriction that its start and end keys must form a valid, + * non-empty range {@code [startKey, endKey)} that is inclusive of the start key and exclusive of + * the end key. + * + *

    When the end key is empty, it is treated as the largest possible key. + * + *

    Interpreting {@link ByteKey} in a {@link ByteKeyRange}

    + * + *

    The primary role of {@link ByteKeyRange} is to provide functionality for + * {@link #estimateFractionForKey(ByteKey)}, {@link #interpolateKey(double)}, and + * {@link #split(int)}, which are used for Google Cloud Dataflow's + * Autoscaling + * and Dynamic Work Rebalancing features. + * + *

    {@link ByteKeyRange} implements these features by treating a {@link ByteKey}'s underlying + * {@code byte[]} as the binary expansion of floating point numbers in the range {@code [0.0, 1.0]}. + * For example, the keys {@code ByteKey.of(0x80)}, {@code ByteKey.of(0xc0)}, and + * {@code ByteKey.of(0xe0)} are interpreted as {@code 0.5}, {@code 0.75}, and {@code 0.875} + * respectively. The empty {@code ByteKey.EMPTY} is interpreted as {@code 0.0} when used as the + * start of a range and {@code 1.0} when used as the end key. + * + *

    Key interpolation, fraction estimation, and range splitting are all interpreted in these + * floating-point semantics. See the respective implementations for further details. Note: + * the underlying implementations of these functions use {@link BigInteger} and {@link BigDecimal}, + * so they can be slow and should not be called in hot loops. Dataflow's dynamic work + * rebalancing will only invoke these functions during periodic control operations, so they are not + * called on the critical path. + * + * @see ByteKey + */ +public final class ByteKeyRange implements Serializable { + private static final Logger logger = LoggerFactory.getLogger(ByteKeyRange.class); + + /** The range of all keys, with empty start and end keys. */ + public static final ByteKeyRange ALL_KEYS = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.EMPTY); + + /** + * Creates a new {@link ByteKeyRange} with the given start and end keys. + * + *

    Note that if {@code endKey} is empty, it is treated as the largest possible key. + * + * @see ByteKeyRange + * + * @throws IllegalArgumentException if {@code endKey} is less than or equal to {@code startKey}, + * unless {@code endKey} is empty indicating the maximum possible {@link ByteKey}. + */ + public static ByteKeyRange of(ByteKey startKey, ByteKey endKey) { + return new ByteKeyRange(startKey, endKey); + } + + /** + * Returns the {@link ByteKey} representing the lower bound of this {@link ByteKeyRange}. + */ + public ByteKey getStartKey() { + return startKey; + } + + /** + * Returns the {@link ByteKey} representing the upper bound of this {@link ByteKeyRange}. + * + *

    Note that if {@code endKey} is empty, it is treated as the largest possible key. + */ + public ByteKey getEndKey() { + return endKey; + } + + /** + * Returns {@code true} if the specified {@link ByteKey} is contained within this range. + */ + public Boolean containsKey(ByteKey key) { + return key.compareTo(startKey) >= 0 && endsAfterKey(key); + } + + /** + * Returns {@code true} if the specified {@link ByteKeyRange} overlaps this range. + */ + public Boolean overlaps(ByteKeyRange other) { + // If each range starts before the other range ends, then they must overlap. + // { [] } -- one range inside the other OR { [ } ] -- partial overlap. + return endsAfterKey(other.startKey) && other.endsAfterKey(startKey); + } + + /** + * Returns a list of up to {@code numSplits + 1} {@link ByteKey ByteKeys} in ascending order, + * where the keys have been interpolated to form roughly equal sub-ranges of this + * {@link ByteKeyRange}, assuming a uniform distribution of keys within this range. + * + *

    The first {@link ByteKey} in the result is guaranteed to be equal to {@link #getStartKey}, + * and the last {@link ByteKey} in the result is guaranteed to be equal to {@link #getEndKey}. + * Thus the resulting list exactly spans the same key range as this {@link ByteKeyRange}. + * + *

    Note that the number of keys returned is not always equal to {@code numSplits + 1}. + * Specifically, if this range is unsplittable (e.g., because the start and end keys are equal + * up to padding by zero bytes), the list returned will only contain the start and end key. + * + * @throws IllegalArgumentException if the specified number of splits is < 1 + * @see ByteKeyRange the ByteKeyRange class Javadoc for more information about split semantics. + */ + public List split(int numSplits) { + checkArgument(numSplits > 0, "numSplits %s must be a positive integer", numSplits); + + try { + ImmutableList.Builder ret = ImmutableList.builder(); + ret.add(startKey); + for (int i = 1; i < numSplits; ++i) { + ret.add(interpolateKey(i / (double) numSplits)); + } + ret.add(endKey); + return ret.build(); + } catch (IllegalStateException e) { + // The range is not splittable -- just return + return ImmutableList.of(startKey, endKey); + } + } + + /** + * Returns the fraction of this range {@code [startKey, endKey)} that is in the interval + * {@code [startKey, key)}. + * + * @throws IllegalArgumentException if {@code key} does not fall within this range + * @see ByteKeyRange the ByteKeyRange class Javadoc for more information about fraction semantics. + */ + public double estimateFractionForKey(ByteKey key) { + checkNotNull(key, "key"); + checkArgument(!key.isEmpty(), "Cannot compute fraction for an empty key"); + checkArgument( + key.compareTo(startKey) >= 0, "Expected key %s >= range start key %s", key, startKey); + + if (key.equals(endKey)) { + return 1.0; + } + checkArgument(containsKey(key), "Cannot compute fraction for %s outside this %s", key, this); + + byte[] startBytes = startKey.getBytes(); + byte[] endBytes = endKey.getBytes(); + byte[] keyBytes = key.getBytes(); + // If the endKey is unspecified, add a leading 1 byte to it and a leading 0 byte to all other + // keys, to get a concrete least upper bound for the desired range. + if (endKey.isEmpty()) { + startBytes = addHeadByte(startBytes, (byte) 0); + endBytes = addHeadByte(endBytes, (byte) 1); + keyBytes = addHeadByte(keyBytes, (byte) 0); + } + + // Pad to the longest of all 3 keys. + int paddedKeyLength = Math.max(Math.max(startBytes.length, endBytes.length), keyBytes.length); + BigInteger rangeStartInt = paddedPositiveInt(startBytes, paddedKeyLength); + BigInteger rangeEndInt = paddedPositiveInt(endBytes, paddedKeyLength); + BigInteger keyInt = paddedPositiveInt(keyBytes, paddedKeyLength); + + // Keys are equal subject to padding by 0. + BigInteger range = rangeEndInt.subtract(rangeStartInt); + if (range.equals(BigInteger.ZERO)) { + logger.warn( + "Using 0.0 as the default fraction for this near-empty range {} where start and end keys" + + " differ only by trailing zeros.", + this); + return 0.0; + } + + // Compute the progress (key-start)/(end-start) scaling by 2^64, dividing (which rounds), + // and then scaling down after the division. This gives ample precision when converted to + // double. + BigInteger progressScaled = keyInt.subtract(rangeStartInt).shiftLeft(64); + return progressScaled.divide(range).doubleValue() / Math.pow(2, 64); + } + + /** + * Returns a {@link ByteKey} {@code key} such that {@code [startKey, key)} represents + * approximately the specified fraction of the range {@code [startKey, endKey)}. The interpolation + * is computed assuming a uniform distribution of keys. + * + *

    For example, given the largest possible range (defined by empty start and end keys), the + * fraction {@code 0.5} will return the {@code ByteKey.of(0x80)}, which will also be returned for + * ranges {@code [0x40, 0xc0)} and {@code [0x6f, 0x91)}. + * + *

    The key returned will never be empty. + * + * @throws IllegalArgumentException if {@code fraction} is outside the range [0, 1) + * @throws IllegalStateException if this range cannot be interpolated + * @see ByteKeyRange the ByteKeyRange class Javadoc for more information about fraction semantics. + */ + public ByteKey interpolateKey(double fraction) { + checkArgument( + fraction >= 0.0 && fraction < 1.0, "Fraction %s must be in the range [0, 1)", fraction); + byte[] startBytes = startKey.getBytes(); + byte[] endBytes = endKey.getBytes(); + // If the endKey is unspecified, add a leading 1 byte to it and a leading 0 byte to all other + // keys, to get a concrete least upper bound for the desired range. + if (endKey.isEmpty()) { + startBytes = addHeadByte(startBytes, (byte) 0); + endBytes = addHeadByte(endBytes, (byte) 1); + } + + // Pad to the longest key. + int paddedKeyLength = Math.max(startBytes.length, endBytes.length); + BigInteger rangeStartInt = paddedPositiveInt(startBytes, paddedKeyLength); + BigInteger rangeEndInt = paddedPositiveInt(endBytes, paddedKeyLength); + + // If the keys are equal subject to padding by 0, we can't interpolate. + BigInteger range = rangeEndInt.subtract(rangeStartInt); + checkState( + !range.equals(BigInteger.ZERO), + "Refusing to interpolate for near-empty %s where start and end keys differ only by trailing" + + " zero bytes.", + this); + + // Add precision so that range is at least 53 (double mantissa length) bits long. This way, we + // can interpolate small ranges finely, e.g., split the range key 3 to key 4 into 1024 parts. + // We add precision to range by adding zero bytes to the end of the keys, aka shifting the + // underlying BigInteger left by a multiple of 8 bits. + int bytesNeeded = ((53 - range.bitLength()) + 7) / 8; + if (bytesNeeded > 0) { + range = range.shiftLeft(bytesNeeded * 8); + rangeStartInt = rangeStartInt.shiftLeft(bytesNeeded * 8); + paddedKeyLength += bytesNeeded; + } + + BigInteger interpolatedOffset = + new BigDecimal(range).multiply(BigDecimal.valueOf(fraction)).toBigInteger(); + + int outputKeyLength = endKey.isEmpty() ? (paddedKeyLength - 1) : paddedKeyLength; + return ByteKey.copyFrom( + fixupHeadZeros(rangeStartInt.add(interpolatedOffset).toByteArray(), outputKeyLength)); + } + + /** + * Returns new {@link ByteKeyRange} like this one, but with the specified start key. + */ + public ByteKeyRange withStartKey(ByteKey startKey) { + return new ByteKeyRange(startKey, endKey); + } + + /** + * Returns new {@link ByteKeyRange} like this one, but with the specified end key. + */ + public ByteKeyRange withEndKey(ByteKey endKey) { + return new ByteKeyRange(startKey, endKey); + } + + //////////////////////////////////////////////////////////////////////////////////// + private final ByteKey startKey; + private final ByteKey endKey; + + private ByteKeyRange(ByteKey startKey, ByteKey endKey) { + this.startKey = checkNotNull(startKey, "startKey"); + this.endKey = checkNotNull(endKey, "endKey"); + checkArgument(endsAfterKey(startKey), "Start %s must be less than end %s", startKey, endKey); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(ByteKeyRange.class) + .add("startKey", startKey) + .add("endKey", endKey) + .toString(); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ByteKeyRange)) { + return false; + } + ByteKeyRange other = (ByteKeyRange) o; + return Objects.equals(startKey, other.startKey) && Objects.equals(endKey, other.endKey); + } + + @Override + public int hashCode() { + return Objects.hash(startKey, endKey); + } + + /** + * Returns a copy of the specified array with the specified byte added at the front. + */ + private static byte[] addHeadByte(byte[] array, byte b) { + byte[] ret = new byte[array.length + 1]; + ret[0] = b; + System.arraycopy(array, 0, ret, 1, array.length); + return ret; + } + + /** + * Ensures the array is exactly {@code size} bytes long. Returns the input array if the condition + * is met, otherwise either adds or removes zero bytes from the beginning of {@code array}. + */ + private static byte[] fixupHeadZeros(byte[] array, int size) { + int padding = size - array.length; + if (padding == 0) { + return array; + } + + if (padding < 0) { + // There is one zero byte at the beginning, added by BigInteger to make there be a sign + // bit when converting to bytes. + verify( + padding == -1, + "key %s: expected length %d with exactly one byte of padding, found %d", + ByteKey.copyFrom(array), + size, + -padding); + verify( + (array[0] == 0) && ((array[1] & 0x80) == 0x80), + "key %s: is 1 byte longer than expected, indicating BigInteger padding. Expect first byte" + + " to be zero with set MSB in second byte.", + ByteKey.copyFrom(array)); + return Arrays.copyOfRange(array, 1, array.length); + } + + byte[] ret = new byte[size]; + System.arraycopy(array, 0, ret, padding, array.length); + return ret; + } + + /** + * Returns {@code true} when the specified {@code key} is smaller this range's end key. The only + * semantic change from {@code (key.compareTo(getEndKey()) < 0)} is that the empty end key is + * treated as larger than all possible {@link ByteKey keys}. + */ + boolean endsAfterKey(ByteKey key) { + return endKey.isEmpty() || key.compareTo(endKey) < 0; + } + + /** Builds a BigInteger out of the specified array, padded to the desired byte length. */ + private static BigInteger paddedPositiveInt(byte[] bytes, int length) { + int bytePaddingNeeded = length - bytes.length; + checkArgument( + bytePaddingNeeded >= 0, "Required bytes.length {} < length {}", bytes.length, length); + BigInteger ret = new BigInteger(1, bytes); + return (bytePaddingNeeded == 0) ? ret : ret.shiftLeft(8 * bytePaddingNeeded); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java new file mode 100644 index 0000000000..f6796cc5af --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static com.google.common.base.MoreObjects.toStringHelper; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; + +/** + * A {@link RangeTracker} for {@link ByteKey ByteKeys} in {@link ByteKeyRange ByteKeyRanges}. + * + * @see ByteKey + * @see ByteKeyRange + */ +public final class ByteKeyRangeTracker implements RangeTracker { + private static final Logger logger = LoggerFactory.getLogger(ByteKeyRangeTracker.class); + + /** Instantiates a new {@link ByteKeyRangeTracker} with the specified range. */ + public static ByteKeyRangeTracker of(ByteKeyRange range) { + return new ByteKeyRangeTracker(range); + } + + @Override + public synchronized ByteKey getStartPosition() { + return range.getStartKey(); + } + + @Override + public synchronized ByteKey getStopPosition() { + return range.getEndKey(); + } + + @Override + public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, ByteKey recordStart) { + if (isAtSplitPoint && !range.containsKey(recordStart)) { + return false; + } + position = recordStart; + return true; + } + + @Override + public synchronized boolean trySplitAtPosition(ByteKey splitPosition) { + // Unstarted. + if (position == null) { + logger.warn( + "{}: Rejecting split request at {} because no records have been returned.", + this, + splitPosition); + return false; + } + + // Started, but not after current position. + if (splitPosition.compareTo(position) <= 0) { + logger.warn( + "{}: Rejecting split request at {} because it is not after current position {}.", + this, + splitPosition, + position); + return false; + } + + // Sanity check. + if (!range.containsKey(splitPosition)) { + logger.warn( + "{}: Rejecting split request at {} because it is not within the range.", + this, + splitPosition); + return false; + } + + range = range.withEndKey(splitPosition); + return true; + } + + @Override + public synchronized double getFractionConsumed() { + if (position == null) { + return 0; + } + return range.estimateFractionForKey(position); + } + + /////////////////////////////////////////////////////////////////////////////// + private ByteKeyRange range; + @Nullable private ByteKey position; + + private ByteKeyRangeTracker(ByteKeyRange range) { + this.range = range; + this.position = null; + } + + @Override + public String toString() { + return toStringHelper(ByteKeyRangeTracker.class) + .add("range", range) + .add("position", position) + .toString(); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java new file mode 100644 index 0000000000..a90bb5acaa --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java @@ -0,0 +1,463 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThan; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Arrays; +import java.util.List; + +/** + * Tests for {@link ByteKeyRange}. + */ +@RunWith(JUnit4.class) +public class ByteKeyRangeTest { + // A set of ranges for testing. + private static final ByteKeyRange RANGE_1_10 = ByteKeyRange.of(ByteKey.of(1), ByteKey.of(10)); + private static final ByteKeyRange RANGE_5_10 = ByteKeyRange.of(ByteKey.of(5), ByteKey.of(10)); + private static final ByteKeyRange RANGE_5_50 = ByteKeyRange.of(ByteKey.of(5), ByteKey.of(50)); + private static final ByteKeyRange RANGE_10_50 = ByteKeyRange.of(ByteKey.of(10), ByteKey.of(50)); + private static final ByteKeyRange UP_TO_1 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(1)); + private static final ByteKeyRange UP_TO_5 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(5)); + private static final ByteKeyRange UP_TO_10 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(10)); + private static final ByteKeyRange UP_TO_50 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(50)); + private static final ByteKeyRange AFTER_1 = ByteKeyRange.of(ByteKey.of(1), ByteKey.EMPTY); + private static final ByteKeyRange AFTER_5 = ByteKeyRange.of(ByteKey.of(5), ByteKey.EMPTY); + private static final ByteKeyRange AFTER_10 = ByteKeyRange.of(ByteKey.of(10), ByteKey.EMPTY); + private static final ByteKeyRange[] TEST_RANGES = + new ByteKeyRange[] { + ByteKeyRange.ALL_KEYS, + RANGE_1_10, + RANGE_5_10, + RANGE_5_50, + RANGE_10_50, + UP_TO_1, + UP_TO_5, + UP_TO_10, + UP_TO_50, + AFTER_1, + AFTER_5, + AFTER_10, + }; + + private static final ByteKey[] RANGE_TEST_KEYS = + ImmutableList.builder() + .addAll(Arrays.asList(ByteKeyTest.TEST_KEYS)) + .add(ByteKey.EMPTY) + .build() + .toArray(ByteKeyTest.TEST_KEYS); + + /** + * Tests that the two ranges do not overlap, passing each in as the first range in the comparison. + */ + private static void bidirectionalNonOverlap(ByteKeyRange left, ByteKeyRange right) { + bidirectionalOverlapHelper(left, right, false); + } + + /** + * Tests that the two ranges overlap, passing each in as the first range in the comparison. + */ + private static void bidirectionalOverlap(ByteKeyRange left, ByteKeyRange right) { + bidirectionalOverlapHelper(left, right, true); + } + + /** + * Helper function for tests with a good error message. + */ + private static void bidirectionalOverlapHelper( + ByteKeyRange left, ByteKeyRange right, boolean result) { + assertEquals(String.format("%s overlaps %s", left, right), result, left.overlaps(right)); + assertEquals(String.format("%s overlaps %s", right, left), result, right.overlaps(left)); + } + + /** + * Tests of {@link ByteKeyRange#overlaps(ByteKeyRange)} with cases that should return true. + */ + @Test + public void testOverlappingRanges() { + bidirectionalOverlap(ByteKeyRange.ALL_KEYS, ByteKeyRange.ALL_KEYS); + bidirectionalOverlap(ByteKeyRange.ALL_KEYS, RANGE_1_10); + bidirectionalOverlap(UP_TO_1, UP_TO_1); + bidirectionalOverlap(UP_TO_1, UP_TO_5); + bidirectionalOverlap(UP_TO_50, AFTER_10); + bidirectionalOverlap(UP_TO_50, RANGE_1_10); + bidirectionalOverlap(UP_TO_10, UP_TO_50); + bidirectionalOverlap(RANGE_1_10, RANGE_5_50); + bidirectionalOverlap(AFTER_1, AFTER_5); + bidirectionalOverlap(RANGE_5_10, RANGE_1_10); + bidirectionalOverlap(RANGE_5_10, RANGE_5_50); + } + + /** + * Tests of {@link ByteKeyRange#overlaps(ByteKeyRange)} with cases that should return false. + */ + @Test + public void testNonOverlappingRanges() { + bidirectionalNonOverlap(UP_TO_1, AFTER_1); + bidirectionalNonOverlap(UP_TO_1, AFTER_5); + bidirectionalNonOverlap(RANGE_5_10, RANGE_10_50); + } + + /** + * Verifies that all keys in the given list are strictly ordered by size. + */ + private static void ensureOrderedKeys(List keys) { + for (int i = 0; i < keys.size() - 1; ++i) { + // This will throw if these two keys do not form a valid range. + ByteKeyRange.of(keys.get(i), keys.get(i + 1)); + // Also, a key is only allowed empty if it is the first key. + if (i > 0 && keys.get(i).isEmpty()) { + fail(String.format("Intermediate key %s/%s may not be empty", i, keys.size())); + } + } + } + + /** Tests for {@link ByteKeyRange#split(int)} with invalid inputs. */ + @Test + public void testRejectsInvalidSplit() { + try { + fail(String.format("%s.split(0) should fail: %s", RANGE_1_10, RANGE_1_10.split(0))); + } catch (IllegalArgumentException expected) { + // pass + } + + try { + fail(String.format("%s.split(-3) should fail: %s", RANGE_1_10, RANGE_1_10.split(-3))); + } catch (IllegalArgumentException expected) { + // pass + } + } + + /** Tests for {@link ByteKeyRange#split(int)} with weird inputs. */ + @Test + public void testSplitSpecialInputs() { + // Range split by 1 returns list of its keys. + assertEquals( + "Split 1 should return input", + ImmutableList.of(RANGE_1_10.getStartKey(), RANGE_1_10.getEndKey()), + RANGE_1_10.split(1)); + + // Unsplittable range returns list of its keys. + ByteKeyRange unsplittable = ByteKeyRange.of(ByteKey.of(), ByteKey.of(0, 0, 0, 0)); + assertEquals( + "Unsplittable should return input", + ImmutableList.of(unsplittable.getStartKey(), unsplittable.getEndKey()), + unsplittable.split(5)); + } + + /** Tests for {@link ByteKeyRange#split(int)}. */ + @Test + public void testSplitKeysCombinatorial() { + List sizes = ImmutableList.of(1, 2, 5, 10, 25, 32, 64); + for (int i = 0; i < RANGE_TEST_KEYS.length; ++i) { + for (int j = i + 1; j < RANGE_TEST_KEYS.length; ++j) { + ByteKeyRange range = ByteKeyRange.of(RANGE_TEST_KEYS[i], RANGE_TEST_KEYS[j]); + for (int s : sizes) { + List splits = range.split(s); + ensureOrderedKeys(splits); + assertThat("At least two entries in splits", splits.size(), greaterThanOrEqualTo(2)); + assertEquals("First split equals start of range", splits.get(0), RANGE_TEST_KEYS[i]); + assertEquals( + "Last split equals end of range", splits.get(splits.size() - 1), RANGE_TEST_KEYS[j]); + } + } + } + } + + /** Manual tests for {@link ByteKeyRange#estimateFractionForKey}. */ + @Test + public void testEstimateFractionForKey() { + final double delta = 0.0000001; + + /* 0x80 is halfway between [] and [] */ + assertEquals(0.5, ByteKeyRange.ALL_KEYS.estimateFractionForKey(ByteKey.of(0x80)), delta); + + /* 0x80 is halfway between [00] and [] */ + ByteKeyRange after0 = ByteKeyRange.of(ByteKey.of(0), ByteKey.EMPTY); + assertEquals(0.5, after0.estimateFractionForKey(ByteKey.of(0x80)), delta); + + /* 0x80 is halfway between [0000] and [] */ + ByteKeyRange after00 = ByteKeyRange.of(ByteKey.of(0, 0), ByteKey.EMPTY); + assertEquals(0.5, after00.estimateFractionForKey(ByteKey.of(0x80)), delta); + + /* 0x7f is halfway between [] and [fe] */ + ByteKeyRange upToFE = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0xfe)); + assertEquals(0.5, upToFE.estimateFractionForKey(ByteKey.of(0x7f)), delta); + + /* 0x40 is one-quarter of the way between [] and [] */ + assertEquals(0.25, ByteKeyRange.ALL_KEYS.estimateFractionForKey(ByteKey.of(0x40)), delta); + + /* 0x40 is one-half of the way between [] and [0x80] */ + ByteKeyRange upTo80 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0x80)); + assertEquals(0.50, upTo80.estimateFractionForKey(ByteKey.of(0x40)), delta); + + /* 0x40 is one-half of the way between [0x30] and [0x50] */ + ByteKeyRange range30to50 = ByteKeyRange.of(ByteKey.of(0x30), ByteKey.of(0x50)); + assertEquals(0.50, range30to50.estimateFractionForKey(ByteKey.of(0x40)), delta); + + /* 0x40 is one-half of the way between [0x30, 0, 1] and [0x4f, 0xff, 0xff, 0, 0] */ + ByteKeyRange range31to4f = + ByteKeyRange.of(ByteKey.of(0x30, 0, 1), ByteKey.of(0x4f, 0xff, 0xff, 0, 0)); + assertEquals(0.50, range31to4f.estimateFractionForKey(ByteKey.of(0x40)), delta); + + /* Exact fractions from 0 to 47 for a prime range. */ + ByteKeyRange upTo47 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(47)); + for (int i = 0; i <= 47; ++i) { + assertEquals("i=" + i, i / 47.0, upTo47.estimateFractionForKey(ByteKey.of(i)), delta); + } + + /* Exact fractions from 0 to 83 for a prime range. */ + ByteKeyRange rangeFDECtoFDEC83 = + ByteKeyRange.of(ByteKey.of(0xfd, 0xec), ByteKey.of(0xfd, 0xec, 83)); + for (int i = 0; i <= 83; ++i) { + assertEquals( + "i=" + i, + i / 83.0, + rangeFDECtoFDEC83.estimateFractionForKey(ByteKey.of(0xfd, 0xec, i)), + delta); + } + } + + /** Exhaustive tests for {@link ByteKeyRange#estimateFractionForKey}. */ + @Test + public void testEstimateFractionForKeyCombinatorial() { + double last; + for (int i = 0; i < RANGE_TEST_KEYS.length; ++i) { + for (int k = i + 1; k < RANGE_TEST_KEYS.length; ++k) { + ByteKeyRange range = ByteKeyRange.of(RANGE_TEST_KEYS[i], RANGE_TEST_KEYS[k]); + last = 0.0; + for (int j = i; j < k; ++j) { + ByteKey key = RANGE_TEST_KEYS[j]; + if (key.isEmpty()) { + // Cannot compute progress for unspecified key + continue; + } + double fraction = range.estimateFractionForKey(key); + try { + assertThat(fraction, greaterThanOrEqualTo(last)); + } catch (AssertionError e) { + throw new AssertionError( + String.format( + "Range %s estimated fraction for key %s should be >= fraction for key %s", + range, + key, + RANGE_TEST_KEYS[i]), + e); + } + last = fraction; + } + } + } + } + + /** Manual tests for {@link ByteKeyRange#interpolateKey}. */ + @Test + public void testInterpolateKey() { + /* 0x80 is halfway between [] and [] */ + assertEqualExceptPadding(ByteKey.of(0x80), ByteKeyRange.ALL_KEYS.interpolateKey(0.5)); + + /* 0x80 is halfway between [00] and [] */ + ByteKeyRange after0 = ByteKeyRange.of(ByteKey.of(0), ByteKey.EMPTY); + assertEqualExceptPadding(ByteKey.of(0x80), after0.interpolateKey(0.5)); + + /* 0x80 is halfway between [0000] and [] -- padding to longest key */ + ByteKeyRange after00 = ByteKeyRange.of(ByteKey.of(0, 0), ByteKey.EMPTY); + assertEqualExceptPadding(ByteKey.of(0x80), after00.interpolateKey(0.5)); + + /* 0x7f is halfway between [] and [fe] */ + ByteKeyRange upToFE = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0xfe)); + assertEqualExceptPadding(ByteKey.of(0x7f), upToFE.interpolateKey(0.5)); + + /* 0x40 is one-quarter of the way between [] and [] */ + assertEqualExceptPadding(ByteKey.of(0x40), ByteKeyRange.ALL_KEYS.interpolateKey(0.25)); + + /* 0x40 is halfway between [] and [0x80] */ + ByteKeyRange upTo80 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0x80)); + assertEqualExceptPadding(ByteKey.of(0x40), upTo80.interpolateKey(0.5)); + + /* 0x40 is halfway between [0x30] and [0x50] */ + ByteKeyRange range30to50 = ByteKeyRange.of(ByteKey.of(0x30), ByteKey.of(0x50)); + assertEqualExceptPadding(ByteKey.of(0x40), range30to50.interpolateKey(0.5)); + + /* 0x40 is halfway between [0x30, 0, 1] and [0x4f, 0xff, 0xff, 0, 0] */ + ByteKeyRange range31to4f = + ByteKeyRange.of(ByteKey.of(0x30, 0, 1), ByteKey.of(0x4f, 0xff, 0xff, 0, 0)); + assertEqualExceptPadding(ByteKey.of(0x40), range31to4f.interpolateKey(0.5)); + } + + /** Tests that {@link ByteKeyRange#interpolateKey} does not return the empty key. */ + @Test + public void testInterpolateKeyIsNotEmpty() { + String fmt = "Interpolating %s at fraction 0.0 should not return the empty key"; + for (ByteKeyRange range : TEST_RANGES) { + range = ByteKeyRange.ALL_KEYS; + assertFalse(String.format(fmt, range), range.interpolateKey(0.0).isEmpty()); + } + } + + /** + * Combinatorial tests for {@link ByteKeyRange#interpolateKey}, which also checks + * {@link ByteKeyRange#estimateFractionForKey} by converting the interpolated keys back to + * fractions. + */ + @Test + public void testInterpolateKeyAndEstimateFractionCombinatorial() { + double delta = 0.0000001; + double[] testFractions = + new double[] {0.01, 0.1, 0.123, 0.2, 0.3, 0.45738, 0.5, 0.6, 0.7182, 0.8, 0.95, 0.97, 0.99}; + for (int i = 0; i < RANGE_TEST_KEYS.length; ++i) { + for (int j = i + 1; j < RANGE_TEST_KEYS.length; ++j) { + ByteKeyRange range = ByteKeyRange.of(RANGE_TEST_KEYS[i], RANGE_TEST_KEYS[j]); + ByteKey last = RANGE_TEST_KEYS[i]; + for (double fraction : testFractions) { + try { + ByteKey key = range.interpolateKey(fraction); + String message = String.format("%s, %s", range, fraction); + assertThat(message, key, greaterThanOrEqualTo(last)); + assertThat(message, range.estimateFractionForKey(key), closeTo(fraction, delta)); + last = key; + } catch (IllegalStateException e) { + assertThat( + String.format("range: %s fraction: %f", range, fraction), + e.getMessage(), + containsString("near-empty ByteKeyRange")); + continue; + } + } + } + } + } + + /** Test {@link ByteKeyRange} getters. */ + @Test + public void testKeyGetters() { + // [1,) + assertEquals(AFTER_1.getStartKey(), ByteKey.of(1)); + assertEquals(AFTER_1.getEndKey(), ByteKey.EMPTY); + // [1, 10) + assertEquals(RANGE_1_10.getStartKey(), ByteKey.of(1)); + assertEquals(RANGE_1_10.getEndKey(), ByteKey.of(10)); + // [, 10) + assertEquals(UP_TO_10.getStartKey(), ByteKey.EMPTY); + assertEquals(UP_TO_10.getEndKey(), ByteKey.of(10)); + } + + /** Test {@link ByteKeyRange#toString}. */ + @Test + public void testToString() { + assertEquals("ByteKeyRange{startKey=[], endKey=[0a]}", UP_TO_10.toString()); + } + + /** Test {@link ByteKeyRange#equals}. */ + @Test + public void testEquals() { + // Verify that the comparison gives the correct result for all values in both directions. + for (int i = 0; i < TEST_RANGES.length; ++i) { + for (int j = 0; j < TEST_RANGES.length; ++j) { + ByteKeyRange left = TEST_RANGES[i]; + ByteKeyRange right = TEST_RANGES[j]; + boolean eq = left.equals(right); + if (i == j) { + assertTrue(String.format("Expected that %s is equal to itself.", left), eq); + assertTrue( + String.format("Expected that %s is equal to a copy of itself.", left), + left.equals(ByteKeyRange.of(right.getStartKey(), right.getEndKey()))); + } else { + assertFalse(String.format("Expected that %s is not equal to %s", left, right), eq); + } + } + } + } + + /** Test that {@link ByteKeyRange#of} rejects invalid ranges. */ + @Test + public void testRejectsInvalidRanges() { + ByteKey[] testKeys = ByteKeyTest.TEST_KEYS; + for (int i = 0; i < testKeys.length; ++i) { + for (int j = i; j < testKeys.length; ++j) { + if (testKeys[i].isEmpty() || testKeys[j].isEmpty()) { + continue; // these are valid ranges. + } + try { + ByteKeyRange range = ByteKeyRange.of(testKeys[j], testKeys[i]); + fail(String.format("Expected failure constructing %s", range)); + } catch (IllegalArgumentException expected) { + // pass + } + } + } + } + + /** Test {@link ByteKeyRange#hashCode}. */ + @Test + public void testHashCode() { + // Verify that the hashCode is equal when i==j, and usually not equal otherwise. + int collisions = 0; + for (int i = 0; i < TEST_RANGES.length; ++i) { + ByteKeyRange current = TEST_RANGES[i]; + int left = current.hashCode(); + int leftClone = ByteKeyRange.of(current.getStartKey(), current.getEndKey()).hashCode(); + assertEquals( + String.format("Expected same hash code for %s and a copy of itself", current), + left, + leftClone); + for (int j = i + 1; j < TEST_RANGES.length; ++j) { + int right = TEST_RANGES[j].hashCode(); + if (left == right) { + ++collisions; + } + } + } + int totalUnequalTests = TEST_RANGES.length * (TEST_RANGES.length - 1) / 2; + assertThat("Too many hash collisions", collisions, lessThan(totalUnequalTests / 2)); + } + + /** Asserts the two keys are equal except trailing zeros. */ + private static void assertEqualExceptPadding(ByteKey expected, ByteKey key) { + ByteString shortKey = expected.getValue(); + ByteString longKey = key.getValue(); + if (shortKey.size() > longKey.size()) { + shortKey = key.getValue(); + longKey = expected.getValue(); + } + for (int i = 0; i < shortKey.size(); ++i) { + if (shortKey.byteAt(i) != longKey.byteAt(i)) { + fail(String.format("Expected %s (up to trailing zeros), got %s", expected, key)); + } + } + for (int j = shortKey.size(); j < longKey.size(); ++j) { + if (longKey.byteAt(j) != 0) { + fail(String.format("Expected %s (up to trailing zeros), got %s", expected, key)); + } + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java new file mode 100644 index 0000000000..234e6e9d95 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link ByteKeyRangeTracker}. */ +@RunWith(JUnit4.class) +public class ByteKeyRangeTrackerTest { + private static final ByteKey START_KEY = ByteKey.of(0x12); + private static final ByteKey MIDDLE_KEY = ByteKey.of(0x23); + private static final ByteKey BEFORE_END_KEY = ByteKey.of(0x33); + private static final ByteKey END_KEY = ByteKey.of(0x34); + private static final double RANGE_SIZE = 0x34 - 0x12; + private static final ByteKeyRange RANGE = ByteKeyRange.of(START_KEY, END_KEY); + + /** Tests for {@link ByteKeyRangeTracker#toString}. */ + @Test + public void testToString() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + String expected = String.format("ByteKeyRangeTracker{range=%s, position=null}", RANGE); + assertEquals(expected, tracker.toString()); + + tracker.tryReturnRecordAt(true, MIDDLE_KEY); + expected = String.format("ByteKeyRangeTracker{range=%s, position=%s}", RANGE, MIDDLE_KEY); + assertEquals(expected, tracker.toString()); + } + + /** Tests for {@link ByteKeyRangeTracker#of}. */ + @Test + public void testBuilding() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + + assertEquals(START_KEY, tracker.getStartPosition()); + assertEquals(END_KEY, tracker.getStopPosition()); + } + + /** Tests for {@link ByteKeyRangeTracker#getFractionConsumed()}. */ + @Test + public void testGetFractionConsumed() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + double delta = 0.00001; + + assertEquals(0.0, tracker.getFractionConsumed(), delta); + + tracker.tryReturnRecordAt(true, START_KEY); + assertEquals(0.0, tracker.getFractionConsumed(), delta); + + tracker.tryReturnRecordAt(true, MIDDLE_KEY); + assertEquals(0.5, tracker.getFractionConsumed(), delta); + + tracker.tryReturnRecordAt(true, BEFORE_END_KEY); + assertEquals(1 - 1 / RANGE_SIZE, tracker.getFractionConsumed(), delta); + } + + /** Tests for {@link ByteKeyRangeTracker#tryReturnRecordAt}. */ + @Test + public void testTryReturnRecordAt() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + + // Should be able to emit at the same key twice, should that happen. + // Should be able to emit within range (in order, but system guarantees won't try out of order). + // Should not be able to emit past end of range. + + assertTrue(tracker.tryReturnRecordAt(true, START_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, START_KEY)); + + assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); + + assertTrue(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); + + assertFalse(tracker.tryReturnRecordAt(true, END_KEY)); // after end + + assertTrue(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); // still succeeds + } + + /** Tests for {@link ByteKeyRangeTracker#trySplitAtPosition}. */ + @Test + public void testSplitAtPosition() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + + // Unstarted, should not split. + assertFalse(tracker.trySplitAtPosition(MIDDLE_KEY)); + + // Start it, split it before the end. + assertTrue(tracker.tryReturnRecordAt(true, START_KEY)); + assertTrue(tracker.trySplitAtPosition(BEFORE_END_KEY)); + assertEquals(BEFORE_END_KEY, tracker.getStopPosition()); + + // Should not be able to split it after the end. + assertFalse(tracker.trySplitAtPosition(END_KEY)); + + // Should not be able to split after emitting. + assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); + assertFalse(tracker.trySplitAtPosition(MIDDLE_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java index 5c81287c8b..922ac5b803 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java @@ -34,8 +34,8 @@ */ @RunWith(JUnit4.class) public class ByteKeyTest { - // A big list of byte[] keys, in ascending sorted order. - private static final ByteKey[] TEST_KEYS = + /* A big list of byte[] keys, in ascending sorted order. */ + static final ByteKey[] TEST_KEYS = new ByteKey[] { ByteKey.EMPTY, ByteKey.of(0), From ced1724bcd57b488885a9b09bcbaae17dc37486b Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 15 Feb 2016 13:20:21 -0800 Subject: [PATCH 132/751] Make some ReduceFnRunner implementation details private The ReduceFnRunner calls into ActiveWindowSet#onMerge, which calls back to ReduceFnRunner#onMerge. The existence of this mechanism is an implementation detail, subject to change, and the appropriate methods on ReduceFnRunner need not be public; they have no relevance to its primary API. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114705912 --- .../dataflow/sdk/util/ReduceFnRunner.java | 143 +++++++++--------- 1 file changed, 73 insertions(+), 70 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 675eae00cc..f60faadf25 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -72,8 +72,7 @@ * @param The output type that will be produced for each key. * @param The type of windows this operates on. */ -public class ReduceFnRunner - implements ActiveWindowSet.MergeCallback { +public class ReduceFnRunner { private final WindowingStrategy windowingStrategy; private final WindowingInternals> windowingInternals; @@ -82,6 +81,8 @@ public class ReduceFnRunner private final K key; + private final OnMergeCallback onMergeCallback = new OnMergeCallback(); + /** * Track which windows are still active and which 'state address' windows contain state * for a merged window. @@ -335,86 +336,88 @@ private void collectAndMergeWindows(Iterable> values) { } } - /** - * Called from the active window set to indicate {@code toBeMerged} (of which only - * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) will later - * be merged into {@code mergeResult}. - */ - @Override - public void prefetchOnMerge( - Collection toBeMerged, Collection activeToBeMerged, W mergeResult) throws Exception { - ReduceFn.OnMergeContext directMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); - ReduceFn.OnMergeContext renamedMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); - - // Prefetch various state. - triggerRunner.prefetchForMerge(mergeResult, activeToBeMerged, directMergeContext.state()); - try { - reduceFn.prefetchOnMerge(renamedMergeContext.state()); - } catch (Exception e) { - throw wrapMaybeUserException(e); + private class OnMergeCallback implements ActiveWindowSet.MergeCallback { + /** + * Called from the active window set to indicate {@code toBeMerged} (of which only + * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) will later + * be merged into {@code mergeResult}. + */ + @Override + public void prefetchOnMerge( + Collection toBeMerged, Collection activeToBeMerged, W mergeResult) throws Exception { + ReduceFn.OnMergeContext directMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); + ReduceFn.OnMergeContext renamedMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); + + // Prefetch various state. + triggerRunner.prefetchForMerge(mergeResult, activeToBeMerged, directMergeContext.state()); + try { + reduceFn.prefetchOnMerge(renamedMergeContext.state()); + } catch (Exception e) { + throw wrapMaybeUserException(e); + } + watermarkHold.prefetchOnMerge(renamedMergeContext.state()); + nonEmptyPanes.prefetchOnMerge(renamedMergeContext.state()); } - watermarkHold.prefetchOnMerge(renamedMergeContext.state()); - nonEmptyPanes.prefetchOnMerge(renamedMergeContext.state()); - } - - /** - * Called from the active window set to indicate {@code toBeMerged} (of which only - * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) are about - * to be merged into {@code mergeResult}. - */ - @Override - public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) - throws Exception { - // At this point activeWindows has NOT incorporated the results of the merge. - ReduceFn.OnMergeContext directMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); - ReduceFn.OnMergeContext renamedMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); - // Run the reduceFn to perform any needed merging. - try { - reduceFn.onMerge(renamedMergeContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + /** + * Called from the active window set to indicate {@code toBeMerged} (of which only + * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) are about + * to be merged into {@code mergeResult}. + */ + @Override + public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) + throws Exception { + // At this point activeWindows has NOT incorporated the results of the merge. + ReduceFn.OnMergeContext directMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); + ReduceFn.OnMergeContext renamedMergeContext = + contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); + + // Run the reduceFn to perform any needed merging. + try { + reduceFn.onMerge(renamedMergeContext); + } catch (Exception e) { + throw wrapMaybeUserException(e); + } - // Merge the watermark holds. - watermarkHold.onMerge(renamedMergeContext); + // Merge the watermark holds. + watermarkHold.onMerge(renamedMergeContext); - // Merge non-empty pane state. - nonEmptyPanes.onMerge(renamedMergeContext.state()); + // Merge non-empty pane state. + nonEmptyPanes.onMerge(renamedMergeContext.state()); - // Have the trigger merge state as needed - try { - triggerRunner.onMerge(directMergeContext); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Failed to merge the triggers", e); - } + // Have the trigger merge state as needed + try { + triggerRunner.onMerge(directMergeContext); + } catch (Exception e) { + Throwables.propagateIfPossible(e); + throw new RuntimeException("Failed to merge the triggers", e); + } - for (W active : activeToBeMerged) { - if (active.equals(mergeResult)) { - // Not merged away. - continue; + for (W active : activeToBeMerged) { + if (active.equals(mergeResult)) { + // Not merged away. + continue; + } + // Cleanup flavor A: Currently ACTIVE window is about to become MERGED. + // Clear any state not already cleared by the onMerge calls above. + WindowTracing.debug("ReduceFnRunner.onMerge: Merging {} into {}", active, mergeResult); + ReduceFn.Context directClearContext = + contextFactory.base(active, StateStyle.DIRECT); + // No need for the end-of-window or garbage collection timers. + cancelEndOfWindowAndGarbageCollectionTimers(directClearContext); + // We no longer care about any previous panes of merged away windows. The + // merge result window gets to start fresh if it is new. + paneInfoTracker.clear(directClearContext.state()); } - // Cleanup flavor A: Currently ACTIVE window is about to become MERGED. - // Clear any state not already cleared by the onMerge calls above. - WindowTracing.debug("ReduceFnRunner.onMerge: Merging {} into {}", active, mergeResult); - ReduceFn.Context directClearContext = - contextFactory.base(active, StateStyle.DIRECT); - // No need for the end-of-window or garbage collection timers. - cancelEndOfWindowAndGarbageCollectionTimers(directClearContext); - // We no longer care about any previous panes of merged away windows. The - // merge result window gets to start fresh if it is new. - paneInfoTracker.clear(directClearContext.state()); } } private void mergeActiveWindows() { try { - activeWindows.merge(this); + activeWindows.merge(onMergeCallback); } catch (Exception e) { Throwables.propagateIfPossible(e); throw new RuntimeException("Exception while merging windows", e); From f108866da54266bc50d6d431e180efdc5737a6ac Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 15 Feb 2016 19:27:46 -0800 Subject: [PATCH 133/751] Treat ReduceFn and Trigger exceptions as system exceptions The ReduceFn and Trigger callback APIs are for internal use only, so logic for catching and propagating user exceptions at the ReduceFnRunner level is extraneous. A ReduceFn may contain state utilizing a user's CombineFn, which can throw only unchecked exceptions. For compatibility with existing combine logic, these exceptions are not ever explicitly wrapped. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114717351 --- .../sdk/util/BatchTimerInternals.java | 10 +- .../dataflow/sdk/util/ReduceFnRunner.java | 126 +++++------------- .../dataflow/sdk/util/ReduceFnTester.java | 11 +- 3 files changed, 42 insertions(+), 105 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java index 8df5406417..b6a1493239 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java @@ -101,7 +101,8 @@ public String toString() { .toString(); } - public void advanceInputWatermark(ReduceFnRunner runner, Instant newInputWatermark) { + public void advanceInputWatermark(ReduceFnRunner runner, Instant newInputWatermark) + throws Exception { Preconditions.checkState(!newInputWatermark.isBefore(inputWatermarkTime), "Cannot move input watermark time backwards from %s to %s", inputWatermarkTime, newInputWatermark); @@ -109,14 +110,16 @@ public void advanceInputWatermark(ReduceFnRunner runner, Instant new advance(runner, newInputWatermark, TimeDomain.EVENT_TIME); } - public void advanceProcessingTime(ReduceFnRunner runner, Instant newProcessingTime) { + public void advanceProcessingTime(ReduceFnRunner runner, Instant newProcessingTime) + throws Exception { Preconditions.checkState(!newProcessingTime.isBefore(processingTime), "Cannot move processing time backwards from %s to %s", processingTime, newProcessingTime); processingTime = newProcessingTime; advance(runner, newProcessingTime, TimeDomain.PROCESSING_TIME); } - private void advance(ReduceFnRunner runner, Instant newTime, TimeDomain domain) { + private void advance(ReduceFnRunner runner, Instant newTime, TimeDomain domain) + throws Exception { PriorityQueue timers = queue(domain); boolean shouldFire = false; @@ -128,7 +131,6 @@ private void advance(ReduceFnRunner runner, Instant newTime, TimeDom // Remove before firing, so that if the trigger adds another identical // timer we don't remove it. timers.remove(); - runner.onTimer(timer); } } while (shouldFire); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index f60faadf25..4d5ba69d51 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -35,7 +35,6 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import com.google.common.collect.Sets; import org.joda.time.Duration; @@ -280,7 +279,7 @@ public void persist() { /** * Extract the windows associated with the values, and invoke merge. */ - private void collectAndMergeWindows(Iterable> values) { + private void collectAndMergeWindows(Iterable> values) throws Exception { // No-op if no merging can take place if (windowingStrategy.getWindowFn().isNonMerging()) { return; @@ -310,11 +309,7 @@ private void collectAndMergeWindows(Iterable> values) { // Do that now. ReduceFn.OnMergeContext premergeContext = contextFactory.forPremerge(window); - try { - reduceFn.onMerge(premergeContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.onMerge(premergeContext); watermarkHold.onMerge(premergeContext); activeWindows.merged(window); } @@ -352,11 +347,7 @@ public void prefetchOnMerge( // Prefetch various state. triggerRunner.prefetchForMerge(mergeResult, activeToBeMerged, directMergeContext.state()); - try { - reduceFn.prefetchOnMerge(renamedMergeContext.state()); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.prefetchOnMerge(renamedMergeContext.state()); watermarkHold.prefetchOnMerge(renamedMergeContext.state()); nonEmptyPanes.prefetchOnMerge(renamedMergeContext.state()); } @@ -376,11 +367,7 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); // Run the reduceFn to perform any needed merging. - try { - reduceFn.onMerge(renamedMergeContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.onMerge(renamedMergeContext); // Merge the watermark holds. watermarkHold.onMerge(renamedMergeContext); @@ -389,12 +376,7 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W nonEmptyPanes.onMerge(renamedMergeContext.state()); // Have the trigger merge state as needed - try { - triggerRunner.onMerge(directMergeContext); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Failed to merge the triggers", e); - } + triggerRunner.onMerge(directMergeContext); for (W active : activeToBeMerged) { if (active.equals(mergeResult)) { @@ -415,13 +397,8 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W } } - private void mergeActiveWindows() { - try { - activeWindows.merge(onMergeCallback); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Exception while merging windows", e); - } + private void mergeActiveWindows() throws Exception { + activeWindows.merge(onMergeCallback); } /** @@ -430,7 +407,7 @@ private void mergeActiveWindows() { * * @return the set of windows in which the element was actually processed */ - private Collection processElement(WindowedValue value) { + private Collection processElement(WindowedValue value) throws Exception { // Redirect element windows to the ACTIVE windows they have been merged into. // It is possible two of the element's windows have been merged into the same window. // In that case we'll process the same element for the same window twice. @@ -484,19 +461,10 @@ private Collection processElement(WindowedValue value) { watermarkHold.addHolds(renamedContext); // Execute the reduceFn, which will buffer the value as appropriate - try { - reduceFn.processValue(renamedContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.processValue(renamedContext); // Run the trigger to update its state - try { - triggerRunner.processValue(directContext); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Failed to run trigger", e); - } + triggerRunner.processValue(directContext); } return windows; @@ -505,7 +473,7 @@ private Collection processElement(WindowedValue value) { /** * Called when an end-of-window, garbage collection, or trigger-specific timer fires. */ - public void onTimer(TimerData timer) { + public void onTimer(TimerData timer) throws Exception { // Which window is the timer for? Preconditions.checkArgument(timer.getNamespace() instanceof WindowNamespace, "Expected timer to be in WindowNamespace, but was in %s", timer.getNamespace()); @@ -560,13 +528,7 @@ public void onTimer(TimerData timer) { // Cleanup flavor B: Clear all the remaining state for this window since we'll never // see elements for it again. - try { - clearAllState(directContext, renamedContext, windowIsActive); - } catch (Exception e) { - Throwables.propagateIfInstanceOf(e, UserCodeException.class); - throw new RuntimeException( - "Exception while garbage collecting window " + windowNamespace.getWindow(), e); - } + clearAllState(directContext, renamedContext, windowIsActive); } else { WindowTracing.debug( "ReduceFnRunner.onTimer: Triggering for key:{}; window:{} at {} with " @@ -574,12 +536,7 @@ public void onTimer(TimerData timer) { key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); if (windowIsActive) { - try { - emitIfAppropriate(directContext, renamedContext, isEndOfWindowTimer); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw Throwables.propagate(e); - } + emitIfAppropriate(directContext, renamedContext, isEndOfWindowTimer); } if (isEndOfWindowTimer) { @@ -611,16 +568,14 @@ public void onTimer(TimerData timer) { *

  • We can clear any remaining garbage collection hold. * */ - private void clearAllState(ReduceFn.Context directContext, - ReduceFn.Context renamedContext, boolean windowIsActive) - throws Exception { + private void clearAllState( + ReduceFn.Context directContext, + ReduceFn.Context renamedContext, + boolean windowIsActive) + throws Exception { if (windowIsActive) { // Since window is still active the trigger has not closed. - try { - reduceFn.clearState(renamedContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.clearState(renamedContext); watermarkHold.clearHolds(renamedContext); nonEmptyPanes.clearPane(renamedContext); triggerRunner.clearState(directContext); @@ -685,24 +640,15 @@ private void emitIfAppropriate(ReduceFn.Context directCon // Cleanup buffered data if appropriate if (shouldDiscard) { // Cleanup flavor C: The user does not want any buffered data to persist between panes. - try { - reduceFn.clearState(renamedContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.clearState(renamedContext); } if (isFinished) { // Cleanup flavor D: If trigger is closed we will ignore all new incoming elements. // Clear state not otherwise cleared by onTrigger and clearPane above. // Remember the trigger is, indeed, closed until the window is garbage collected. - try { - triggerRunner.clearState(directContext); - paneInfoTracker.clear(directContext.state()); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException("Exception while clearing trigger state", e); - } + triggerRunner.clearState(directContext); + paneInfoTracker.clear(directContext.state()); activeWindows.remove(directContext.window()); } } @@ -730,9 +676,12 @@ private boolean needToEmit( /** * Run the {@link ReduceFn#onTrigger} method and produce any necessary output. */ - private void onTrigger(final ReduceFn.Context directContext, - ReduceFn.Context renamedContext, boolean isWatermarkTrigger, - boolean isFinished) { + private void onTrigger( + final ReduceFn.Context directContext, + ReduceFn.Context renamedContext, + boolean isWatermarkTrigger, + boolean isFinished) + throws Exception { // Collect state. StateContents outputTimestampFuture = watermarkHold.extractAndRelease(renamedContext, isFinished); @@ -740,11 +689,7 @@ private void onTrigger(final ReduceFn.Context directConte paneInfoTracker.getNextPaneInfo(directContext, isWatermarkTrigger, isFinished); StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext); - try { - reduceFn.prefetchOnTrigger(directContext.state()); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.prefetchOnTrigger(directContext.state()); triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); // Is a no-op. Why? // Calculate the pane info. @@ -772,11 +717,7 @@ public void output(OutputT toOutput) { } }); - try { - reduceFn.onTrigger(renamedTriggerContext); - } catch (Exception e) { - throw wrapMaybeUserException(e); - } + reduceFn.onTrigger(renamedTriggerContext); } } @@ -816,11 +757,4 @@ private void cancelEndOfWindowAndGarbageCollectionTimers(ReduceFn.Co context.timers().deleteTimer(timer, TimeDomain.EVENT_TIME); } } - - ////////////////////////////////////////////////////////////////////////////////////////////////// - - private RuntimeException wrapMaybeUserException(Throwable t) { - // Any exceptions that happen inside a non-system ReduceFn are considered user code. - throw UserCodeException.wrapIf(!(reduceFn instanceof SystemReduceFn), t); - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index f7fe75eac4..b23ce97efa 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -347,7 +347,7 @@ public WindowedValue apply(TimestampedValue input) { runner.persist(); } - public void fireTimer(W window, Instant timestamp, TimeDomain domain) { + public void fireTimer(W window, Instant timestamp, TimeDomain domain) throws Exception { ReduceFnRunner runner = createRunner(); runner.onTimer( TimerData.of(StateNamespaces.window(windowFn.windowCoder(), window), timestamp, domain)); @@ -587,7 +587,7 @@ public String toString() { } public void advanceInputWatermark( - ReduceFnRunner runner, Instant newInputWatermark) { + ReduceFnRunner runner, Instant newInputWatermark) throws Exception { Preconditions.checkNotNull(newInputWatermark); Preconditions.checkState( inputWatermarkTime == null || !newInputWatermark.isBefore(inputWatermarkTime), @@ -626,7 +626,7 @@ private void advanceOutputWatermark(Instant newOutputWatermark) { } public void advanceProcessingTime( - ReduceFnRunner runner, Instant newProcessingTime) { + ReduceFnRunner runner, Instant newProcessingTime) throws Exception { Preconditions.checkState(!newProcessingTime.isBefore(processingTime), "Cannot move processing time backwards from %s to %s", processingTime, newProcessingTime); WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", processingTime, @@ -636,7 +636,7 @@ public void advanceProcessingTime( } public void advanceSynchronizedProcessingTime( - ReduceFnRunner runner, Instant newSynchronizedProcessingTime) { + ReduceFnRunner runner, Instant newSynchronizedProcessingTime) throws Exception { Preconditions.checkState(!newSynchronizedProcessingTime.isBefore(synchronizedProcessingTime), "Cannot move processing time backwards from %s to %s", processingTime, newSynchronizedProcessingTime); @@ -648,7 +648,8 @@ public void advanceSynchronizedProcessingTime( } private void advanceAndFire( - ReduceFnRunner runner, Instant currentTime, TimeDomain domain) { + ReduceFnRunner runner, Instant currentTime, TimeDomain domain) + throws Exception { PriorityQueue queue = queue(domain); boolean shouldFire = false; From 841e2a2d01c761e95c7042a4497a4467f127c0cb Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 15 Feb 2016 20:34:12 -0800 Subject: [PATCH 134/751] Decouple NonEmptyPanes from ReduceFn somewhat NonEmptyPanes is a useful utility class for runner implementers. It has meaning relative to concepts in triggers and windowing without reference to ReduceFn. This change removes extraneous references to ReduceFn contexts from the methods of NonEmptyPanes, which only actually use state (and this is all they should ever really do). Some NonEmptyPanes implementations still refer to a (private) ReduceFn instance to decide whether their state is empty. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114719638 --- .../dataflow/sdk/util/NonEmptyPanes.java | 29 ++++++++++--------- .../dataflow/sdk/util/ReduceFnRunner.java | 8 ++--- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java index 91a74a85ef..f31d6659a9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -34,7 +35,7 @@ */ public abstract class NonEmptyPanes { - public static NonEmptyPanes create( + static NonEmptyPanes create( WindowingStrategy strategy, ReduceFn reduceFn) { if (strategy.getMode() == AccumulationMode.DISCARDING_FIRED_PANES) { return new DiscardingModeNonEmptyPanes<>(reduceFn); @@ -47,17 +48,17 @@ public static NonEmptyPanes create( * Record that some content has been added to the window in {@code context}, and therefore the * current pane is not empty. */ - public abstract void recordContent(ReduceFn.Context context); + public abstract void recordContent(StateContext context); /** * Record that the given pane is empty. */ - public abstract void clearPane(ReduceFn.Context context); + public abstract void clearPane(StateContext state); /** * Return true if the current pane for the window in {@code context} is empty. */ - public abstract StateContents isEmpty(ReduceFn.Context context); + public abstract StateContents isEmpty(StateContext context); /** * Prefetch in preparation for merging. @@ -83,17 +84,17 @@ private DiscardingModeNonEmptyPanes(ReduceFn reduceFn) { } @Override - public StateContents isEmpty(ReduceFn.Context context) { - return reduceFn.isEmpty(context.state()); + public StateContents isEmpty(StateContext state) { + return reduceFn.isEmpty(state); } @Override - public void recordContent(ReduceFn.Context context) { + public void recordContent(StateContext state) { // Nothing to do -- the reduceFn is tracking contents } @Override - public void clearPane(ReduceFn.Context context) { + public void clearPane(StateContext state) { // Nothing to do -- the reduceFn is tracking contents } @@ -120,18 +121,18 @@ private static class GeneralNonEmptyPanes "count", VarLongCoder.of(), new Sum.SumLongFn())); @Override - public void recordContent(ReduceFn.Context context) { - context.state().access(PANE_ADDITIONS_TAG).add(1L); + public void recordContent(StateContext state) { + state.access(PANE_ADDITIONS_TAG).add(1L); } @Override - public void clearPane(ReduceFn.Context context) { - context.state().access(PANE_ADDITIONS_TAG).clear(); + public void clearPane(StateContext state) { + state.access(PANE_ADDITIONS_TAG).clear(); } @Override - public StateContents isEmpty(ReduceFn.Context context) { - return context.state().access(PANE_ADDITIONS_TAG).isEmpty(); + public StateContents isEmpty(StateContext state) { + return state.access(PANE_ADDITIONS_TAG).isEmpty(); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 4d5ba69d51..af6d185e6b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -445,7 +445,7 @@ private Collection processElement(WindowedValue value) throws Excepti continue; } - nonEmptyPanes.recordContent(renamedContext); + nonEmptyPanes.recordContent(renamedContext.state()); // Make sure we've scheduled the end-of-window or garbage collection timer for this window // However if we have pre-merged then they will already have been scheduled. @@ -577,7 +577,7 @@ private void clearAllState( // Since window is still active the trigger has not closed. reduceFn.clearState(renamedContext); watermarkHold.clearHolds(renamedContext); - nonEmptyPanes.clearPane(renamedContext); + nonEmptyPanes.clearPane(renamedContext.state()); triggerRunner.clearState(directContext); } else { // Needed only for backwards compatibility over UPDATE. @@ -635,7 +635,7 @@ private void emitIfAppropriate(ReduceFn.Context directCon onTrigger(directContext, renamedContext, isEndOfWindow, isFinished); // Now that we've triggered, the pane is empty. - nonEmptyPanes.clearPane(renamedContext); + nonEmptyPanes.clearPane(renamedContext.state()); // Cleanup buffered data if appropriate if (shouldDiscard) { @@ -687,7 +687,7 @@ private void onTrigger( watermarkHold.extractAndRelease(renamedContext, isFinished); StateContents paneFuture = paneInfoTracker.getNextPaneInfo(directContext, isWatermarkTrigger, isFinished); - StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext); + StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext.state()); reduceFn.prefetchOnTrigger(directContext.state()); triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); // Is a no-op. Why? From 857ee11b4d613f8a3dea1e4cc0d4007d2e207f24 Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 15 Feb 2016 21:32:08 -0800 Subject: [PATCH 135/751] Decouple TriggerRunner from ReduceFn Before this change, TriggerRunner has (at least) two major responsibilities: 1. Track state about a root trigger that neither the trigger nor its ExecutableTrigger wrapper track. 2. Extract the appropriate bits from the ReduceFn contexts to invoke the trigger. This change removes responsibility 2, moving it into ReduceFnRunner. The implementation of TriggerRunner may still have residual behavioral dependencies on the implementation of ReduceFnRunner (its only client) but these are unintended. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114721856 --- .../dataflow/sdk/util/ReduceFnRunner.java | 22 ++++--- .../dataflow/sdk/util/TriggerRunner.java | 61 +++++++++++-------- 2 files changed, 49 insertions(+), 34 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index af6d185e6b..d817e74c7f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -376,7 +376,8 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W nonEmptyPanes.onMerge(renamedMergeContext.state()); // Have the trigger merge state as needed - triggerRunner.onMerge(directMergeContext); + triggerRunner.onMerge( + directMergeContext.window(), directMergeContext.timers(), directMergeContext.state()); for (W active : activeToBeMerged) { if (active.equals(mergeResult)) { @@ -464,7 +465,11 @@ private Collection processElement(WindowedValue value) throws Excepti reduceFn.processValue(renamedContext); // Run the trigger to update its state - triggerRunner.processValue(directContext); + triggerRunner.processValue( + directContext.window(), + directContext.timestamp(), + directContext.timers(), + directContext.state()); } return windows; @@ -578,7 +583,8 @@ private void clearAllState( reduceFn.clearState(renamedContext); watermarkHold.clearHolds(renamedContext); nonEmptyPanes.clearPane(renamedContext.state()); - triggerRunner.clearState(directContext); + triggerRunner.clearState( + directContext.window(), directContext.timers(), directContext.state()); } else { // Needed only for backwards compatibility over UPDATE. // Clear any end-of-window or garbage collection holds keyed by the current window. @@ -595,7 +601,7 @@ private void clearAllState( paneInfoTracker.clear(directContext.state()); activeWindows.remove(directContext.window()); // We'll never need to test for the trigger being closed again. - triggerRunner.clearFinished(directContext); + triggerRunner.clearFinished(directContext.state()); } /** Should the reduce function state be cleared? */ @@ -617,13 +623,14 @@ private boolean shouldDiscardAfterFiring(boolean isFinished) { private void emitIfAppropriate(ReduceFn.Context directContext, ReduceFn.Context renamedContext, boolean isEndOfWindow) throws Exception { - if (!triggerRunner.shouldFire(directContext)) { + if (!triggerRunner.shouldFire( + directContext.window(), directContext.timers(), directContext.state())) { // Ignore unless trigger is ready to fire return; } // Inform the trigger of the transition to see if it is finished - triggerRunner.onFire(directContext); + triggerRunner.onFire(directContext.window(), directContext.timers(), directContext.state()); boolean isFinished = triggerRunner.isClosed(directContext.state()); // Will be able to clear all element state after triggering? @@ -647,7 +654,8 @@ private void emitIfAppropriate(ReduceFn.Context directCon // Cleanup flavor D: If trigger is closed we will ignore all new incoming elements. // Clear state not otherwise cleared by onTrigger and clearPane above. // Remember the trigger is, indeed, closed until the window is garbage collected. - triggerRunner.clearState(directContext); + triggerRunner.clearState( + directContext.window(), directContext.timers(), directContext.state()); paneInfoTracker.clear(directContext.state()); activeWindows.remove(directContext.window()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index eadacc0ff8..d84c02ba23 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -27,19 +27,25 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; +import org.joda.time.Instant; + import java.util.BitSet; import java.util.Collection; import java.util.Map; /** - * Executes a trigger within the context provided by {@link ReduceFnRunner}. + * Executes a trigger while tracking which of its subtriggers are finished. * - *

    This is responsible for: + *

    Specifically, the responsibilities are: * *

      - *
    • Tracking the finished bits for the trigger tree, included whether the root trigger - * has finished. - *
    • Ensuring that the timer and state associated with each trigger node is separate. + *
    • Invoking the trigger's methods via its {@link ExecutableTrigger} wrapper by + * constructing the appropriate trigger contexts.
    • + *
    • Tracking which of a trigger's subtriggers are finished.
    • + *
    • Adjusting the trigger's subtriggers' finished states upon firing, according to the + * trigger's own {@link Trigger#onFire} method.
    • + *
    • Adjusting the trigger's subtriggers' finished states upon merging, according to the + * trigger's own {@link Trigger#onMerge} method.
    • *
    * * @param The kind of windows being processed. @@ -102,14 +108,15 @@ public void prefetchShouldFire(W window, StateContext state) { /** * Run the trigger logic to deal with a new value. */ - public void processValue(ReduceFn.ProcessValueContext c) throws Exception { + public void processValue(W window, Instant timestamp, Timers timers, StateContext state) + throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. FinishedTriggersBitSet finishedSet = - readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); + readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); Trigger.OnElementContext triggerContext = contextFactory.createOnElementContext( - c.window(), c.timers(), c.timestamp(), rootTrigger, finishedSet); + window, timers, timestamp, rootTrigger, finishedSet); rootTrigger.invokeOnElement(triggerContext); - persistFinishedSet(c.state(), finishedSet); + persistFinishedSet(state, finishedSet); } public void prefetchForMerge( @@ -126,46 +133,46 @@ public void prefetchForMerge( /** * Run the trigger merging logic as part of executing the specified merge. */ - public void onMerge(ReduceFn.OnMergeContext c) throws Exception { + public void onMerge(W window, Timers timers, MergingStateContext state) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. FinishedTriggersBitSet finishedSet = - readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); + readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); // And read the finished bits in each merging window. ImmutableMap.Builder builder = ImmutableMap.builder(); for (Map.Entry> entry : - c.state().accessInEachMergingWindow(FINISHED_BITS_TAG).entrySet()) { + state.accessInEachMergingWindow(FINISHED_BITS_TAG).entrySet()) { // Don't need to clone these, since the trigger context doesn't allow modification builder.put(entry.getKey(), readFinishedBits(entry.getValue())); } ImmutableMap mergingFinishedSets = builder.build(); Trigger.OnMergeContext mergeContext = contextFactory.createOnMergeContext( - c.window(), c.timers(), rootTrigger, finishedSet, mergingFinishedSets); + window, timers, rootTrigger, finishedSet, mergingFinishedSets); // Run the merge from the trigger rootTrigger.invokeOnMerge(mergeContext); - persistFinishedSet(c.state(), finishedSet); + persistFinishedSet(state, finishedSet); // Clear the finished bits. - clearFinished(c); + clearFinished(state); } - public boolean shouldFire(ReduceFn.Context c) throws Exception { - FinishedTriggers finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); - Trigger.TriggerContext context = contextFactory.base(c.window(), c.timers(), + public boolean shouldFire(W window, Timers timers, StateContext state) throws Exception { + FinishedTriggers finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); + Trigger.TriggerContext context = contextFactory.base(window, timers, rootTrigger, finishedSet); return rootTrigger.invokeShouldFire(context); } - public void onFire(ReduceFn.Context c) throws Exception { + public void onFire(W window, Timers timers, StateContext state) throws Exception { FinishedTriggersBitSet finishedSet = - readFinishedBits(c.state().access(FINISHED_BITS_TAG)).copy(); - Trigger.TriggerContext context = contextFactory.base(c.window(), c.timers(), + readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); + Trigger.TriggerContext context = contextFactory.base(window, timers, rootTrigger, finishedSet); rootTrigger.invokeOnFire(context); - persistFinishedSet(c.state(), finishedSet); + persistFinishedSet(state, finishedSet); } private void persistFinishedSet( @@ -187,9 +194,9 @@ private void persistFinishedSet( /** * Clear finished bits. */ - public void clearFinished(ReduceFn.Context c) { + public void clearFinished(StateContext state) { if (isFinishedSetNeeded()) { - c.state().access(FINISHED_BITS_TAG).clear(); + state.access(FINISHED_BITS_TAG).clear(); } } @@ -197,10 +204,10 @@ public void clearFinished(ReduceFn.Context c) { * Clear the state used for executing triggers, but leave the finished set to indicate * the window is closed. */ - public void clearState(ReduceFn.Context c) throws Exception { + public void clearState(W window, Timers timers, StateContext state) throws Exception { // Don't need to clone, because we'll be clearing the finished bits anyways. - FinishedTriggers finishedSet = readFinishedBits(c.state().access(FINISHED_BITS_TAG)); - rootTrigger.invokeClear(contextFactory.base(c.window(), c.timers(), rootTrigger, finishedSet)); + FinishedTriggers finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)); + rootTrigger.invokeClear(contextFactory.base(window, timers, rootTrigger, finishedSet)); } private boolean isFinishedSetNeeded() { From 897d7441376c3a37e7e064669db5c005487d8af2 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 09:25:13 -0800 Subject: [PATCH 136/751] Support reading uncompressed files when gzip is expected Some services will decompress gzipped files on the user's behalf in particular circumstances. For example, GCS does this based on the content encoding of the file. This change makes CompressedSource support the resulting uncompressed data transparently. ----Release Notes---- - CompressedSource now supports reading uncompressed files even when gzip is expected. This enables transparent compatibility with services that decompress gzipped files on the user's behalf. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114760618 --- .../dataflow/sdk/io/CompressedSource.java | 21 +++++++- .../dataflow/sdk/io/CompressedSourceTest.java | 48 +++++++++++++++++-- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index ba42fdc8d1..74ba05e475 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -20,15 +20,19 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.common.base.Preconditions; +import com.google.common.io.ByteStreams; +import com.google.common.primitives.Ints; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import java.io.IOException; +import java.io.PushbackInputStream; import java.io.Serializable; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.NoSuchElementException; +import java.util.zip.GZIPInputStream; /** * A Source that reads from compressed files. A {@code CompressedSources} wraps a delegate @@ -99,7 +103,22 @@ public boolean matches(String fileName) { @Override public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) throws IOException { - return Channels.newChannel(new GzipCompressorInputStream(Channels.newInputStream(channel))); + // Determine if the input stream is gzipped. The input stream returned from the + // GCS connector may already be decompressed; GCS does this based on the + // content-encoding property. + PushbackInputStream stream = new PushbackInputStream(Channels.newInputStream(channel), 2); + byte[] headerBytes = new byte[2]; + int bytesRead = ByteStreams.read( + stream /* source */, headerBytes /* dest */, 0 /* offset */, 2 /* len */); + stream.unread(headerBytes, 0, bytesRead); + if (bytesRead >= 2) { + byte zero = 0x00; + int header = Ints.fromBytes(zero, zero, headerBytes[1], headerBytes[0]); + if (header == GZIPInputStream.GZIP_MAGIC) { + return Channels.newChannel(new GzipCompressorInputStream(stream)); + } + } + return Channels.newChannel(stream); } }, diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index 7583ee0226..f402e82f11 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.io.Files; import com.google.common.primitives.Bytes; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; @@ -45,6 +46,7 @@ import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; +import java.util.Random; import javax.annotation.Nullable; @@ -131,9 +133,7 @@ public void testHeterogeneousCompression() throws Exception { // Every sort of compression File uncompressedFile = tmpFolder.newFile(baseName + ".bin"); generated = generateInput(1000); - try (OutputStream outStream = new FileOutputStream(uncompressedFile)) { - outStream.write(generated); - } + Files.write(generated, uncompressedFile); expected.addAll(Bytes.asList(generated)); File gzipFile = tmpFolder.newFile(baseName + ".gz"); @@ -158,6 +158,42 @@ public void testHeterogeneousCompression() throws Exception { p.run(); } + /** + * Test reading an uncompressed file with {@link CompressionMode#GZIP}, since we must support + * this due to properties of services that we read from. + */ + @Test + public void testFalseGzipStream() throws Exception { + byte[] input = generateInput(1000); + File tmpFile = tmpFolder.newFile("test.gz"); + Files.write(input, tmpFile); + verifyReadContents(input, tmpFile, CompressionMode.GZIP); + } + + /** + * Test reading an empty input file with gzip; it must be interpreted as uncompressed because + * the gzip header is two bytes. + */ + @Test + public void testEmptyReadGzipUncompressed() throws Exception { + byte[] input = generateInput(0); + File tmpFile = tmpFolder.newFile("test.gz"); + Files.write(input, tmpFile); + verifyReadContents(input, tmpFile, CompressionMode.GZIP); + } + + /** + * Test reading single byte input with gzip; it must be interpreted as uncompressed because + * the gzip header is two bytes. + */ + @Test + public void testOneByteReadGzipUncompressed() throws Exception { + byte[] input = generateInput(1); + File tmpFile = tmpFolder.newFile("test.gz"); + Files.write(input, tmpFile); + verifyReadContents(input, tmpFile, CompressionMode.GZIP); + } + /** * Test reading multiple files. */ @@ -190,9 +226,11 @@ public void testCompressedReadMultipleFiles() throws Exception { * Generate byte array of given size. */ private byte[] generateInput(int size) { + // Arbitrary but fixed seed + Random random = new Random(285930); byte[] buff = new byte[size]; for (int i = 0; i < size; i++) { - buff[i] = (byte) (i % Byte.MAX_VALUE); + buff[i] = (byte) (random.nextInt() % Byte.MAX_VALUE); } return buff; } @@ -288,7 +326,7 @@ public Coder getDefaultOutputCoder() { private static class ByteReader extends FileBasedReader { ByteBuffer buff = ByteBuffer.allocate(1); Byte current; - long offset = 0; + long offset = -1; ReadableByteChannel channel; public ByteReader(ByteSource source) { From 290d69f02332d6752b135d9fff233a08dc6f5aef Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 10:01:35 -0800 Subject: [PATCH 137/751] Explicitly provide StateInternals to ReduceFnRunner Previously, this key parameter was carried along via WindowingInternals. This change makes the dependency explicit, eliminating the coupling between the two. WindowingInternals is used only to output a windowed value, while StateInternals is used extensively for all state, including Trigger, FinishedTriggers, and ActiveWindowSet. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114764052 --- .../GroupAlsoByWindowViaWindowSetDoFn.java | 8 +++ ...GroupAlsoByWindowsViaOutputBufferDoFn.java | 18 ++++- .../dataflow/sdk/util/ReduceFnRunner.java | 66 ++++++++++++++----- .../dataflow/sdk/util/ReduceFnTester.java | 10 ++- 4 files changed, 80 insertions(+), 22 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java index e9f23fb327..0e1c8d8e6b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.DoFnRunner.ReduceFnExecutor; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.values.KV; /** @@ -63,10 +64,17 @@ public void processElement(ProcessContext c) throws Exception { K key = c.element().key(); TimerInternals timerInternals = c.windowingInternals().timerInternals(); + + // It is the responsibility of the user of GroupAlsoByWindowsViaWindowSet to only + // provide a WindowingInternals instance with the appropriate key type for StateInternals. + @SuppressWarnings("unchecked") + StateInternals stateInternals = (StateInternals) c.windowingInternals().stateInternals(); + ReduceFnRunner runner = new ReduceFnRunner<>( key, windowingStrategy, + stateInternals, timerInternals, c.windowingInternals(), droppedDueToClosedWindow, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java index de137da665..6cd9381561 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.collect.Iterables; @@ -54,9 +55,20 @@ public void processElement( // watermark, knowing that we have all data and it is in timestamp order. BatchTimerInternals timerInternals = new BatchTimerInternals(Instant.now()); - ReduceFnRunner runner = new ReduceFnRunner<>( - key, strategy, timerInternals, c.windowingInternals(), - droppedDueToClosedWindow, reduceFnFactory.create(key)); + // It is the responsibility of the user of GroupAlsoByWindowsViaOutputBufferDoFn to only + // provide a WindowingInternals instance with the appropriate key type for StateInternals. + @SuppressWarnings("unchecked") + StateInternals stateInternals = (StateInternals) c.windowingInternals().stateInternals(); + + ReduceFnRunner runner = + new ReduceFnRunner( + key, + strategy, + stateInternals, + timerInternals, + c.windowingInternals(), + droppedDueToClosedWindow, + reduceFnFactory.create(key)); Iterable>> chunks = Iterables.partition(c.element().getValue(), 1000); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index d817e74c7f..8d0cf3125a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -74,7 +74,9 @@ public class ReduceFnRunner { private final WindowingStrategy windowingStrategy; - private final WindowingInternals> windowingInternals; + private final OutputWindowedValue> outputter; + + private final StateInternals stateInternals; private final Aggregator droppedDueToClosedWindow; @@ -177,13 +179,19 @@ public class ReduceFnRunner { */ private final NonEmptyPanes nonEmptyPanes; - public ReduceFnRunner(K key, WindowingStrategy windowingStrategy, - TimerInternals timerInternals, WindowingInternals> windowingInternals, - Aggregator droppedDueToClosedWindow, ReduceFn reduceFn) { + public ReduceFnRunner( + K key, + WindowingStrategy windowingStrategy, + StateInternals stateInternals, + TimerInternals timerInternals, + WindowingInternals> windowingInternals, + Aggregator droppedDueToClosedWindow, + ReduceFn reduceFn) { this.key = key; this.timerInternals = timerInternals; this.paneInfoTracker = new PaneInfoTracker(timerInternals); - this.windowingInternals = windowingInternals; + this.stateInternals = stateInternals; + this.outputter = new OutputViaWindowingInternals<>(windowingInternals); this.droppedDueToClosedWindow = droppedDueToClosedWindow; this.reduceFn = reduceFn; @@ -196,26 +204,21 @@ public ReduceFnRunner(K key, WindowingStrategy windowingStrategy, // Note this may trigger a GetData request to load the existing window set. this.activeWindows = createActiveWindowSet(); - // It is the user of ReduceFnRunner's responsibility to have state internals with a - // compatible key type. This is generally assured by graph construction time validation. - @SuppressWarnings("unchecked") - StateInternals stateInternals = (StateInternals) this.windowingInternals.stateInternals(); - this.contextFactory = new ReduceFnContextFactory(key, reduceFn, this.windowingStrategy, stateInternals, this.activeWindows, timerInternals); this.watermarkHold = new WatermarkHold<>(timerInternals, windowingStrategy); - this.triggerRunner = new TriggerRunner<>( - windowingStrategy.getTrigger(), - new TriggerContextFactory<>( - windowingStrategy, this.windowingInternals.stateInternals(), activeWindows)); + this.triggerRunner = + new TriggerRunner<>( + windowingStrategy.getTrigger(), + new TriggerContextFactory<>(windowingStrategy, stateInternals, activeWindows)); } private ActiveWindowSet createActiveWindowSet() { return windowingStrategy.getWindowFn().isNonMerging() - ? new NonMergingActiveWindowSet() : new MergingActiveWindowSet( - windowingStrategy.getWindowFn(), windowingInternals.stateInternals()); + ? new NonMergingActiveWindowSet() + : new MergingActiveWindowSet(windowingStrategy.getWindowFn(), stateInternals); } @VisibleForTesting @@ -720,7 +723,7 @@ public void output(OutputT toOutput) { paneInfoTracker.storeCurrentPaneInfo(directContext, pane); // Output the actual value. - windowingInternals.outputWindowedValue( + outputter.outputWindowedValue( KV.of(key, toOutput), outputTimestamp, windows, pane); } }); @@ -765,4 +768,33 @@ private void cancelEndOfWindowAndGarbageCollectionTimers(ReduceFn.Co context.timers().deleteTimer(timer, TimeDomain.EVENT_TIME); } } + + /** + * An object that can output a value with all of its windowing information. This is a deliberately + * restricted subinterface of {@link WindowingInternals} to express how it is used here. + */ + private interface OutputWindowedValue { + void outputWindowedValue(OutputT output, Instant timestamp, + Collection windows, PaneInfo pane); + } + + private static class OutputViaWindowingInternals + implements OutputWindowedValue { + + private final WindowingInternals windowingInternals; + + public OutputViaWindowingInternals(WindowingInternals windowingInternals) { + this.windowingInternals = windowingInternals; + } + + @Override + public void outputWindowedValue( + OutputT output, + Instant timestamp, + Collection windows, + PaneInfo pane) { + windowingInternals.outputWindowedValue(output, timestamp, windows, pane); + } + + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index b23ce97efa..ccc07b3c7a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -167,8 +167,14 @@ private ReduceFnTester(WindowingStrategy wildcardStrategy, } ReduceFnRunner createRunner() { - return new ReduceFnRunner<>(KEY, objectStrategy, timerInternals, windowingInternals, - droppedDueToClosedWindow, reduceFn); + return new ReduceFnRunner<>( + KEY, + objectStrategy, + stateInternals, + timerInternals, + windowingInternals, + droppedDueToClosedWindow, + reduceFn); } public ExecutableTrigger getTrigger() { From 0467210197ef700c7af67e5df9fad03cc9cf92cb Mon Sep 17 00:00:00 2001 From: ccy Date: Tue, 16 Feb 2016 10:19:21 -0800 Subject: [PATCH 138/751] Fix typo in TimerInternals comment. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114766329 --- .../java/com/google/cloud/dataflow/sdk/util/TimerInternals.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java index f47f73d26f..c823ed39b1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java @@ -115,7 +115,7 @@ public interface TimerInternals { * | | | | | * | | D | C | B | A * | | | | | - * GIWN <= GOWM <= LOWM <= LIWM <= GIWM + * GIWM <= GOWM <= LOWM <= LIWM <= GIWM * (next stage) * -------------------------------------------------> event time * From 18d07e32c6459d53f12b850c0e52036a922686a6 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 10:23:26 -0800 Subject: [PATCH 139/751] Fix propagation of streaming keys ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114766873 --- .../com/google/cloud/dataflow/sdk/transforms/CombineTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java index 63789a7c20..37ed20415f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms; import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; +import static com.google.common.base.Preconditions.checkNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -948,6 +949,7 @@ public Accumulator createAccumulator(String key) { @Override public Accumulator addInput(String key, Accumulator accumulator, Integer value) { + checkNotNull(key); try { assertThat(accumulator.value, Matchers.startsWith(key)); return new Accumulator(accumulator.value + String.valueOf(value)); From 72521c73dfc23af589d911dd55b66d1dfffd48c6 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 10:24:12 -0800 Subject: [PATCH 140/751] Do not assume channel is nonempty in TextIO gzip detection ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114766943 --- .../com/google/cloud/dataflow/sdk/io/TextIO.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 2e95b968a2..bf72f6bf19 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -33,6 +33,7 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.base.Preconditions; +import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; @@ -721,11 +722,14 @@ public InputStream createInputStream(InputStream inputStream) throws IOException // GCS connector may already be decompressed, and no action is required. PushbackInputStream stream = new PushbackInputStream(inputStream, 2); byte[] headerBytes = new byte[2]; - int bytesRead = stream.read(headerBytes); + int bytesRead = ByteStreams.read( + stream /* source */, headerBytes /* dest */, 0 /* offset */, 2 /* len */); stream.unread(headerBytes, 0, bytesRead); - int header = Ints.fromBytes((byte) 0, (byte) 0, headerBytes[1], headerBytes[0]); - if (header == GZIPInputStream.GZIP_MAGIC) { - return new GZIPInputStream(stream); + if (bytesRead >= 2) { + int header = Ints.fromBytes((byte) 0, (byte) 0, headerBytes[1], headerBytes[0]); + if (header == GZIPInputStream.GZIP_MAGIC) { + return new GZIPInputStream(stream); + } } return stream; } From 5f5c26ff77b755996bfaae91ef0a31f7ef6c2d86 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 11:11:47 -0800 Subject: [PATCH 141/751] Make WatermarkHold package-private The class WatermarkHold is a tighly coupled class that should never be used other than by ReduceFnRunner. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114772638 --- .../com/google/cloud/dataflow/sdk/util/WatermarkHold.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index d379cecf48..a79b8d32de 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -34,7 +34,7 @@ import java.io.Serializable; /** - * Implements the logic needed to hold the output watermark for a computation back + * Implements the logic to hold the output watermark for a computation back * until it has seen all the elements it needs based on the input watermark for the * computation. * @@ -43,9 +43,12 @@ * to the output watermark in order to prevent it progressing beyond a time within a window. * The hold will be 'cleared' when the associated pane is emitted. * + *

    This class is only intended for use by {@link ReduceFnRunner}. The two evolve together and + * will likely break any other uses. + * * @param The kind of {@link BoundedWindow} the hold is for. */ -public class WatermarkHold implements Serializable { +class WatermarkHold implements Serializable { /** * Return tag for state containing the output watermark hold * used for elements. From 20dd7075abaa24329f4dc8075edb3102a8726fa4 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 12:17:00 -0800 Subject: [PATCH 142/751] Minor revision of ReduceFnRunner docs ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114780446 --- .../dataflow/sdk/util/ReduceFnRunner.java | 83 ++++++++++++------- 1 file changed, 51 insertions(+), 32 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 8d0cf3125a..a015b06c50 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -55,15 +55,15 @@ * the triggering logic. The {@code ReduceFnRunner}s responsibilities are: * *

      - *
    • Tracking the windows that are active (have buffered data) as elements arrive and - * triggers are fired. - *
    • Holding the watermark based on the timestamps of elements in a pane and releasing it - * when the trigger fires. - *
    • Dropping data that exceeds the maximum allowed lateness. - *
    • Calling the appropriate callbacks on {@link ReduceFn} based on trigger execution, timer - * firings, etc. - *
    • Scheduling garbage collection of state associated with a specific window, and making that - * happen when the appropriate timer fires. + *
    • Tracking the windows that are active (have buffered data) as elements arrive and + * triggers are fired. + *
    • Holding the watermark based on the timestamps of elements in a pane and releasing it + * when the trigger fires. + *
    • Calling the appropriate callbacks on {@link ReduceFn} based on trigger execution, timer + * firings, etc, and providing appropriate contexts to the {@link ReduceFn} for actions + * such as output. + *
    • Scheduling garbage collection of state associated with a specific window, and making that + * happen when the appropriate timer fires. *
    * * @param The type of key being processed. @@ -72,6 +72,21 @@ * @param The type of windows this operates on. */ public class ReduceFnRunner { + + /** + * The {@link ReduceFnRunner} depends on most aspects of the {@link WindowingStrategy}. + * + *
      + *
    • It runs the trigger from the {@link WindowingStrategy}.
    • + *
    • It merges windows according to the {@link WindowingStrategy}.
    • + *
    • It chooses how to track active windows and clear out expired windows + * according to the {@link WindowingStrategy}, based on the allowed lateness and + * whether windows can merge.
    • + *
    • It decides whether to emit empty final panes according to whether the + * {@link WindowingStrategy} requires it.
    • + *
    • It uses discarding or accumulation mode according to the {@link WindowingStrategy}.
    • + *
    + */ private final WindowingStrategy windowingStrategy; private final OutputWindowedValue> outputter; @@ -201,7 +216,8 @@ public ReduceFnRunner( this.windowingStrategy = objectWindowingStrategy; this.nonEmptyPanes = NonEmptyPanes.create(this.windowingStrategy, this.reduceFn); - // Note this may trigger a GetData request to load the existing window set. + + // Note this may incur I/O to load persisted window set data. this.activeWindows = createActiveWindowSet(); this.contextFactory = @@ -232,21 +248,22 @@ boolean isFinished(W window) { * *

    The general strategy is: *

      - *
    1. Use {@link WindowedValue#getWindows} (itself determined using - * {@link WindowFn#assignWindows}) to determine which windows each element belongs to. Some of - * those windows will already have state associated with them. The rest are considered NEW. - *
    2. Use {@link WindowFn#mergeWindows} to attempt to merge currently ACTIVE and NEW windows. - * Each NEW window will become either ACTIVE, MERGED, or EPHEMERAL. (See {@link ActiveWindowSet} - * for definitions of these terms.) - *
    3. If at all possible, eagerly substitute EPHEMERAL windows with their ACTIVE state address - * windows before any state is associated with the EPHEMERAL window. In the common case that - * windows for new elements are merged into existing ACTIVE windows then no additional storage - * or merging overhead will be incurred. - *
    4. Otherwise, keep track of the state address windows for ACTIVE windows so that their - * states can be merged on-demand when a pane fires. - *
    5. Process the element for each of the windows it's windows have been merged into according - * to {@link ActiveWindowSet}. Processing may require running triggers, setting timers, setting - * holds, and invoking {@link ReduceFn#onTrigger}. + *
    6. Use {@link WindowedValue#getWindows} (itself determined using + * {@link WindowFn#assignWindows}) to determine which windows each element belongs to. Some + * of those windows will already have state associated with them. The rest are considered + * NEW. + *
    7. Use {@link WindowFn#mergeWindows} to attempt to merge currently ACTIVE and NEW windows. + * Each NEW window will become either ACTIVE, MERGED, or EPHEMERAL. (See {@link + * ActiveWindowSet} for definitions of these terms.) + *
    8. If at all possible, eagerly substitute EPHEMERAL windows with their ACTIVE state address + * windows before any state is associated with the EPHEMERAL window. In the common case that + * windows for new elements are merged into existing ACTIVE windows then no additional + * storage or merging overhead will be incurred. + *
    9. Otherwise, keep track of the state address windows for ACTIVE windows so that their + * states can be merged on-demand when a pane fires. + *
    10. Process the element for each of the windows it's windows have been merged into according + * to {@link ActiveWindowSet}. Processing may require running triggers, setting timers, + * setting holds, and invoking {@link ReduceFn#onTrigger}. *
    */ public void processElements(Iterable> values) throws Exception { @@ -413,8 +430,10 @@ private void mergeActiveWindows() throws Exception { */ private Collection processElement(WindowedValue value) throws Exception { // Redirect element windows to the ACTIVE windows they have been merged into. - // It is possible two of the element's windows have been merged into the same window. - // In that case we'll process the same element for the same window twice. + // The compressed representation (value, {window1, window2, ...}) actually represents + // distinct elements (value, window1), (value, window2), ... + // so if window1 and window2 merge, the resulting window will contain both copies + // of the value. Collection windows = new ArrayList<>(); for (BoundedWindow untypedWindow : value.getWindows()) { @SuppressWarnings("unchecked") @@ -506,10 +525,10 @@ public void onTimer(TimerData timer) throws Exception { "ReduceFnRunner.onTimer: Note that timer {} is for non-ACTIVE window {}", timer, window); } - // If this is an end-of-window timer then we should test if an AfterWatermark trigger - // will fire. - // It's fine if the window trigger has such trigger, this flag is only used to decide - // if an emitted pane should be classified as ON_TIME. + // If this is an end-of-window timer then: + // 1. We need to set a GC timer + // 2. We need to let the PaneInfoTracker know that we are transitioning from early to late, + // and possibly emitting an on-time pane. boolean isEndOfWindowTimer = TimeDomain.EVENT_TIME == timer.getDomain() && timer.getTimestamp().equals(window.maxTimestamp()); @@ -701,7 +720,7 @@ private void onTrigger( StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext.state()); reduceFn.prefetchOnTrigger(directContext.state()); - triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); // Is a no-op. Why? + triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); // Calculate the pane info. final PaneInfo pane = paneFuture.read(); From 6e902d7ebab9d5e9e49b25305d2f16aae1e09c75 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 13:15:00 -0800 Subject: [PATCH 143/751] Minor revision of ActiveWindowSet javadoc ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114786308 --- .../dataflow/sdk/util/ActiveWindowSet.java | 48 +++++++++------- .../sdk/util/MergingActiveWindowSet.java | 57 ++++++++++--------- 2 files changed, 55 insertions(+), 50 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java index 9af11ca453..69350cb3eb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java @@ -31,31 +31,35 @@ * the windows are merged. The rest is combined lazily when the final state is actually * required when emitting a pane. We keep track of this using an {@link ActiveWindowSet}. * - *

    An element may belong to one or more windows. Each key may have zero or more windows - * corresponding to elements with that key. A window can be in one of five states: + *

    An {@link ActiveWindowSet} considers a window to be in one of the following states: + * *

      - *
    1. NEW: We have just encountered the window on an incoming element and do not yet know if - * it should be merged into an ACTIVE window since we have not yet called - * {@link WindowFn#mergeWindows}. - *
    2. EPHEMERAL: A NEW window has been merged into an ACTIVE window before any state has been - * associated with that window. Thus the window is neither ACTIVE nor MERGED. These windows - * are not persistently represented since if they reappear the merge function should again - * redirect them to an ACTIVE window. (We could collapse EPHEMERAL into MERGED, but keeping them - * separate cuts down on the number of windows we need to keep track of in the common case - * of SessionWindows over in-order events.) - *
    3. ACTIVE: A NEW window has state associated with it and has not itself been merged away. - * The window may have one or more 'state address' windows under which its non-empty state is - * stored. The true state for an ACTIVE window must be derived by reading all of the state in its - * state address windows. - *
    4. MERGED: An ACTIVE window has been merged into another ACTIVE window after it had state - * associated with it. The window will thus appear as a state address window for exactly one - * ACTIVE window. - *
    5. GARBAGE: The window has been garbage collected. No new elements (even late elements) will - * ever be assigned to that window. These windows are not explicitly represented anywhere. - * (Garbage collection is performed by {@link ReduceFnRunner#onTimer}). + *
    6. NEW: The initial state for a window on an incoming element; we do not yet know + * if it should be merged into an ACTIVE window, or whether it is already present as an + * ACTIVE window, since we have not yet called + * {@link WindowFn#mergeWindows}.
    7. + *
    8. ACTIVE: A window that has state associated with it and has not itself been merged + * away. The window may have one or more state address windows under which its + * non-empty state is stored. A state value for an ACTIVE window must be derived by reading + * the state in all of its state address windows.
    9. + *
    10. EPHEMERAL: A NEW window that has been merged into an ACTIVE window before any state + * has been associated with that window. Thus the window is neither ACTIVE nor MERGED. These + * windows are not persistently represented since if they reappear the merge function should + * again redirect them to an ACTIVE window. EPHEMERAL windows are an optimization for + * the common case of in-order events and {@link Sessions session window} by never associating + * state with windows that are created and immediately merged away.
    11. + *
    12. MERGED: An ACTIVE window has been merged into another ACTIVE window after it had + * state associated with it. The window will thus appear as a state address window for exactly + * one ACTIVE window.
    13. + *
    14. EXPIRED: The window has expired and may have been garbage collected. No new elements + * (even late elements) will ever be assigned to that window. These windows are not explicitly + * represented anywhere; it is expected that the user of {@link ActiveWindowSet} will store + * no state associated with the window.
    15. *
    * - *

    If no windows will ever be merged we can use the dummy implementation {@link + *

    + * + *

    If no windows will ever be merged we can use the trivial implementation {@link * NonMergingActiveWindowSet}. Otherwise, the actual implementation of this data structure is in * {@link MergingActiveWindowSet}. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index eab7786b2e..d0a49dcfa8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -40,38 +40,39 @@ import javax.annotation.Nullable; /** - * Implementation of {@link ActiveWindowSet} for use with {@link WindowFn}s that support - * merging. In effect maintains an equivalence class of windows (where two windows which have - * been merged are in the same class), but also manages which windows contain state which - * must be merged when a pane is fired. + * An {@link ActiveWindowSet} for merging {@link WindowFn} implementations. * - *

    Note that this object must be serialized and stored when work units are committed such - * that subsequent work units can recover the equivalence classes etc. + *

    The underlying notion of {@link MergingActiveWindowSet} is that of representing equivalence + * classes of merged windows as a mapping from the merged "super-window" to a set of + * state address windows in which some state has been persisted. The mapping need not + * contain EPHEMERAL windows, because they are created and merged without any persistent state. + * Each window must be a state address window for at most one window, so the mapping is + * invertible. * - * @param the type of window being managed + *

    The states of a non-expired window are treated as follows: + * + *

      + *
    • NEW: a NEW has an empty set of associated state address windows.
    • + *
    • ACTIVE: an ACTIVE window will be associated with some nonempty set of state + * address windows. If the window has not merged, this will necessarily be the singleton set + * containing just itself, but it is not required that an ACTIVE window be amongst its + * state address windows.
    • + *
    • MERGED: a MERGED window will be in the set of associated windows for some + * other window - that window is retrieved via {@link #representative} (this reverse + * association is implemented in O(1) time).
    • + *
    • EPHEMERAL: EPHEMERAL windows are not persisted but are tracked transiently; + * an EPHEMERAL window must be registered with this {@link ActiveWindowSet} by a call + * to {@link #recordMerge} prior to any request for a {@link #representative}.
    • + *
    + * + *

    To illustrate why an ACTIVE window need not be amongst its own state address windows, + * consider two active windows W1 and W2 that are merged to form W12. Further writes may be + * applied to either of W1 or W2, since a read of W12 implies reading both of W12 and merging + * their results. Hence W12 need not have state directly associated with it. */ public class MergingActiveWindowSet implements ActiveWindowSet { private final WindowFn windowFn; - /** - * A map from ACTIVE windows to their state address windows. Writes to the ACTIVE window - * state can be redirected to any one of the state address windows. Reads need to merge - * from all state address windows. If the set is empty then the window is NEW. - * - *

      - *
    • The state address windows will be empty if the window is NEW, we don't yet know what other - * windows it may be merged into, and the window does not yet have any state associated with it. - * In this way we can distinguish between MERGED and EPHEMERAL windows when merging. - *
    • The state address windows will contain just the window itself it it has never been merged - * but has state. - *
    • It is possible none of the state address windows correspond to the window itself. For - * example, two windows W1 and W2 with state may be merged to form W12. From then on additional - * state can be added to just W1 or W2. Thus the state address windows for W12 do not need to - * include W12. - *
    • If W1 is in the set for W2 then W1 is not a state address window of any other active - * window. Furthermore W1 will map to W2 in {@link #windowToActiveWindow}. - *
    - */ @Nullable private Map> activeWindowToStateAddressWindows; @@ -301,8 +302,8 @@ public void merge(MergeCallback mergeCallback) throws Exception { } /** - * A {@code WindowFn.mergeWindows} call has requested {@code toBeMerged} (which must - * all be ACTIVE} be considered equivalent to {@code activeWindow} (which is either a + * A {@link WindowFn#mergeWindows} call has determined that {@code toBeMerged} (which must + * all be ACTIVE}) should be considered equivalent to {@code activeWindow} (which is either a * member of {@code toBeMerged} or is a new window). Make the corresponding change in * the active window set. */ From 7f354a1fd3b51be6dafba431ec48da1a228441cb Mon Sep 17 00:00:00 2001 From: millsd Date: Tue, 16 Feb 2016 13:24:12 -0800 Subject: [PATCH 144/751] Make empty flatten work in streaming ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114787305 --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f3d4825ff9..126eb558c9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -367,6 +367,9 @@ public OutputT apply( @SuppressWarnings("unchecked") OutputT windowed = (OutputT) applyWindow((Window.Bound) transform, (PCollection) input); return windowed; + } else if (Flatten.FlattenPCollectionList.class.equals(transform.getClass()) + && ((PCollectionList) input).size() == 0) { + return (OutputT) Pipeline.applyTransform(input, Create.of()); } else if (overrides.containsKey(transform.getClass())) { // It is the responsibility of whoever constructs overrides to ensure this is type safe. @SuppressWarnings("unchecked") From 0ebc99925f66ad185d87540f9f53b010b6f78376 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 16 Feb 2016 14:17:31 -0800 Subject: [PATCH 145/751] Minor revision of TriggerRunner javadoc ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114793024 --- .../cloud/dataflow/sdk/util/TriggerRunner.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index d84c02ba23..3629c5b7c8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -34,20 +34,24 @@ import java.util.Map; /** - * Executes a trigger while tracking which of its subtriggers are finished. + * Executes a trigger while managing persistence of information about which subtriggers are + * finished. Subtriggers include all recursive trigger expressions as well as the entire trigger. * *

    Specifically, the responsibilities are: * *

      *
    • Invoking the trigger's methods via its {@link ExecutableTrigger} wrapper by * constructing the appropriate trigger contexts.
    • - *
    • Tracking which of a trigger's subtriggers are finished.
    • - *
    • Adjusting the trigger's subtriggers' finished states upon firing, according to the - * trigger's own {@link Trigger#onFire} method.
    • - *
    • Adjusting the trigger's subtriggers' finished states upon merging, according to the - * trigger's own {@link Trigger#onMerge} method.
    • + *
    • Committing a record of which subtriggers are finished to persistent state.
    • + *
    • Restoring the record of which subtriggers are finished from persistent state.
    • + *
    • Clearing out the persisted finished set when a caller indicates + * (via {#link #clearFinished}) that it is no longer needed.
    • *
    * + *

    These responsibilities are intertwined: trigger contexts include mutable information about + * which subtriggers are finished. This class provides the information when building the contexts + * and commits the information when the method of the {@link ExecutableTrigger} returns. + * * @param The kind of windows being processed. */ public class TriggerRunner { From 50721f5935b8ca06774daa2f1fdfc97b3810df09 Mon Sep 17 00:00:00 2001 From: tgroh Date: Tue, 16 Feb 2016 14:28:44 -0800 Subject: [PATCH 146/751] Improve IntraBundleParallelizationTest Instead of tracking elapsed time, track the maximum number of simultaneous calls to process element by using an atomic integer. This improves reliability of the test by removing reliance on the progress of time. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114794225 --- .../IntraBundleParallelizationTest.java | 93 +++++++++++++------ 1 file changed, 65 insertions(+), 28 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java index a15c694fe9..76dd67e097 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java @@ -36,7 +36,6 @@ import org.junit.runners.JUnit4; import java.util.ArrayList; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** @@ -49,7 +48,10 @@ public class IntraBundleParallelizationTest { private static final AtomicInteger numProcessed = new AtomicInteger(); private static final AtomicInteger numFailures = new AtomicInteger(); private static int concurrentElements = 0; - private static int maxConcurrency = 0; + private static int maxDownstreamConcurrency = 0; + + private static final AtomicInteger maxFnConcurrency = new AtomicInteger(); + private static final AtomicInteger currentFnConcurrency = new AtomicInteger(); @Before public void setUp() { @@ -57,7 +59,10 @@ public void setUp() { numProcessed.set(0); numFailures.set(0); concurrentElements = 0; - maxConcurrency = 0; + maxDownstreamConcurrency = 0; + + maxFnConcurrency.set(0); + currentFnConcurrency.set(0); } /** @@ -68,6 +73,7 @@ private static class DelayFn extends DoFn { @Override public void processElement(ProcessContext c) { + startConcurrentCall(); try { sleepMillis(DELAY_MS); } catch (InterruptedException e) { @@ -75,6 +81,7 @@ public void processElement(ProcessContext c) { throw new RuntimeException("Interrupted"); } c.output(c.element()); + finishConcurrentCall(); } } @@ -88,14 +95,19 @@ private ExceptionThrowingFn(int numSuccesses) { @Override public void processElement(ProcessContext c) { - numProcessed.incrementAndGet(); - if (numSuccesses.decrementAndGet() >= 0) { - c.output(c.element()); - return; - } + startConcurrentCall(); + try { + numProcessed.incrementAndGet(); + if (numSuccesses.decrementAndGet() >= 0) { + c.output(c.element()); + return; + } - numFailures.incrementAndGet(); - throw new RuntimeException("Expected failure"); + numFailures.incrementAndGet(); + throw new RuntimeException("Expected failure"); + } finally { + finishConcurrentCall(); + } } } @@ -109,8 +121,8 @@ public void processElement(ProcessContext c) { // how this DoFn is called. synchronized (ConcurrencyMeasuringFn.class) { concurrentElements++; - if (concurrentElements > maxConcurrency) { - maxConcurrency = concurrentElements; + if (concurrentElements > maxDownstreamConcurrency) { + maxDownstreamConcurrency = concurrentElements; } } @@ -122,23 +134,38 @@ public void processElement(ProcessContext c) { } } + private static void startConcurrentCall() { + int currentlyExecuting = currentFnConcurrency.incrementAndGet(); + int maxConcurrency; + do { + maxConcurrency = maxFnConcurrency.get(); + } while (maxConcurrency < currentlyExecuting + && !maxFnConcurrency.compareAndSet(maxConcurrency, currentlyExecuting)); + } + + private static void finishConcurrentCall() { + currentFnConcurrency.decrementAndGet(); + } + + /** + * Test that the DoFn is parallelized up the the Max Parallelism factor within a bundle, but not + * greater than that amount. + */ @Test public void testParallelization() { - long minDuration = Long.MAX_VALUE; + int maxConcurrency = Integer.MIN_VALUE; // Take the minimum from multiple runs. for (int i = 0; i < 5; ++i) { - minDuration = Math.min(minDuration, + maxConcurrency = Math.max(maxConcurrency, run(2 * PARALLELISM_FACTOR, PARALLELISM_FACTOR, new DelayFn())); } - // The minimum is guaranteed to be >= 2x the delay interval, since no more than half the - // elements can be scheduled at once. - assertThat(minDuration, - greaterThanOrEqualTo(2 * DelayFn.DELAY_MS)); - // Also, it should take <= 8x the delay interval since we should be at least - // parallelizing some of the work. - assertThat(minDuration, - lessThanOrEqualTo(8 * DelayFn.DELAY_MS)); + // We should run at least some elements in parallel on some run + assertThat(maxConcurrency, + greaterThanOrEqualTo(2)); + // No run should execute more elements concurrency than the maximum concurrency allowed. + assertThat(maxConcurrency, + lessThanOrEqualTo(PARALLELISM_FACTOR)); } @Test(timeout = 5000L) @@ -186,7 +213,18 @@ public void testIntraBundleParallelizationGetName() { IntraBundleParallelization.of(new DelayFn()).withMaxParallelism(1).getName()); } - private long run(int numElements, int maxParallelism, DoFn doFn) { + /** + * Runs the provided doFn inside of an {@link IntraBundleParallelization} transform. + * + *

    This method assumes that the DoFn passed to it will call {@link #startConcurrentCall()} + * before processing each elements and {@link #finishConcurrentCall()} after each element. + * + * @param numElements the size of the input + * @param maxParallelism how many threads to execute in parallel + * @param doFn the DoFn to execute + * @return the maximum observed parallelism of the DoFn + */ + private int run(int numElements, int maxParallelism, DoFn doFn) { Pipeline pipeline = TestPipeline.create(); ArrayList data = new ArrayList<>(numElements); @@ -200,14 +238,13 @@ private long run(int numElements, int maxParallelism, DoFn doF .apply(IntraBundleParallelization.of(doFn).withMaxParallelism(maxParallelism)) .apply(ParDo.of(downstream)); - long startTime = System.nanoTime(); - pipeline.run(); + // All elements should have completed. + assertEquals(0, currentFnConcurrency.get()); // Downstream methods should not see parallel threads. - assertEquals(1, maxConcurrency); + assertEquals(1, maxDownstreamConcurrency); - long endTime = System.nanoTime(); - return TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS); + return maxFnConcurrency.get(); } } From c1dc715fce0b6042774d217980493d813a35b4be Mon Sep 17 00:00:00 2001 From: tgroh Date: Tue, 16 Feb 2016 14:40:40 -0800 Subject: [PATCH 147/751] Move specialized GroupAlsoByWindow implementations Move to the worker package. The default expansions that use the GroupAlsoByWindowsDoFn and ReduceFnRunner use the versions left in the sdk module; dataflow-specific replacements are moved to the worker module. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114795550 --- .../GroupAlsoByWindowsAndCombineDoFn.java | 192 ------------ .../sdk/util/GroupAlsoByWindowsDoFn.java | 38 +-- .../GroupAlsoByWindowsViaIteratorsDoFn.java | 281 ------------------ .../GroupAlsoByWindowsAndCombineDoFnTest.java | 85 ------ .../sdk/util/GroupAlsoByWindowsDoFnTest.java | 130 -------- ...roupAlsoByWindowsViaIteratorsDoFnTest.java | 103 ------- ...pAlsoByWindowsViaOutputBufferDoFnTest.java | 68 ----- 7 files changed, 5 insertions(+), 892 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFn.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFnTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java deleted file mode 100644 index c0a5cae2ed..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFn.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import org.joda.time.Instant; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; - -/** - * {@link GroupAlsoByWindowsDoFn} that uses combiner to accumulate input elements for non-merging - * window functions with the default triggering strategy. - * - * @param key type - * @param value input type - * @param accumulator type - * @param value output type - * @param window type - */ -@SystemDoFnInternal -class GroupAlsoByWindowsAndCombineDoFn - extends GroupAlsoByWindowsDoFn { - - public static boolean isSupported(WindowingStrategy strategy) { - // TODO: Add support for other triggers. - if (!(strategy.getTrigger().getSpec() instanceof DefaultTrigger)) { - return false; - } - - // Right now, we support ACCUMULATING_FIRED_PANES because it is the same as - // DISCARDING_FIRED_PANES. In Batch mode there is no late data so the default - // trigger (after watermark) will only fire once. - if (!(strategy.getMode().equals(AccumulationMode.DISCARDING_FIRED_PANES) - || strategy.getMode().equals(AccumulationMode.ACCUMULATING_FIRED_PANES))) { - return false; - } - - return true; - } - - private final KeyedCombineFn combineFn; - private WindowingStrategy windowingStrategy; - - public GroupAlsoByWindowsAndCombineDoFn( - WindowingStrategy strategy, - KeyedCombineFn combineFn) { - - checkArgument(GroupAlsoByWindowsAndCombineDoFn.isSupported(strategy), - "%s does not support non-default triggering, " - + "found in windowing strategy: %s", - getClass(), - strategy); - this.combineFn = combineFn; - - // To make a MergeContext that is compatible with the type of windowFn, we need to remove - // the wildcard from the element type. - @SuppressWarnings("unchecked") - WindowingStrategy objectWindowingStrategy = (WindowingStrategy) strategy; - this.windowingStrategy = objectWindowingStrategy; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - final K key = c.element().getKey(); - Iterator> iterator = c.element().getValue().iterator(); - - final PriorityQueue liveWindows = - new PriorityQueue<>(11, new Comparator() { - @Override - public int compare(BoundedWindow w1, BoundedWindow w2) { - return Long.signum(w1.maxTimestamp().getMillis() - w2.maxTimestamp().getMillis()); - } - }); - - final Map accumulators = Maps.newHashMap(); - final Map accumulatorOutputTimestamps = Maps.newHashMap(); - - WindowFn.MergeContext mergeContext = - windowingStrategy.getWindowFn().new MergeContext() { - @Override - public Collection windows() { - return liveWindows; - } - - @Override - public void merge(Collection toBeMerged, W mergeResult) throws Exception { - List accumsToBeMerged = Lists.newArrayListWithCapacity(toBeMerged.size()); - List timestampsToBeMerged = Lists.newArrayListWithCapacity(toBeMerged.size()); - for (W window : toBeMerged) { - accumsToBeMerged.add(accumulators.remove(window)); - timestampsToBeMerged.add(accumulatorOutputTimestamps.remove(window)); - } - liveWindows.removeAll(toBeMerged); - - - Instant mergedOutputTimestamp = - windowingStrategy.getOutputTimeFn().merge(mergeResult, timestampsToBeMerged); - accumulatorOutputTimestamps.put(mergeResult, mergedOutputTimestamp); - liveWindows.add(mergeResult); - accumulators.put(mergeResult, combineFn.mergeAccumulators(key, accumsToBeMerged)); - } - }; - - while (iterator.hasNext()) { - WindowedValue e = iterator.next(); - - @SuppressWarnings("unchecked") - Collection windows = (Collection) e.getWindows(); - for (W window : windows) { - Instant outputTime = - windowingStrategy.getOutputTimeFn().assignOutputTime(e.getTimestamp(), window); - Instant accumulatorOutputTime = accumulatorOutputTimestamps.get(window); - if (accumulatorOutputTime == null) { - accumulatorOutputTimestamps.put(window, outputTime); - } else { - accumulatorOutputTimestamps.put(window, - windowingStrategy.getOutputTimeFn().combine(outputTime, accumulatorOutputTime)); - } - - AccumT accum = accumulators.get(window); - checkState((accumulatorOutputTime == null && accum == null) - || (accumulatorOutputTime != null && accum != null), - "accumulator and accumulatorOutputTime should both be null or both be non-null"); - if (accum == null) { - accum = combineFn.createAccumulator(key); - liveWindows.add(window); - } - accum = combineFn.addInput(key, accum, e.getValue()); - accumulators.put(window, accum); - } - - windowingStrategy.getWindowFn().mergeWindows(mergeContext); - - while (!liveWindows.isEmpty() - && liveWindows.peek().maxTimestamp().isBefore(e.getTimestamp())) { - closeWindow(key, liveWindows.poll(), accumulators, accumulatorOutputTimestamps, c); - } - } - - // To have gotten here, we've either not had any elements added, or we've only run merge - // and then closed windows. We don't need to retry merging. - while (!liveWindows.isEmpty()) { - closeWindow(key, liveWindows.poll(), accumulators, accumulatorOutputTimestamps, c); - } - } - - private void closeWindow( - K key, W window, Map accumulators, - Map accumulatorOutputTimes, - ProcessContext context) { - AccumT accum = accumulators.remove(window); - Instant timestamp = accumulatorOutputTimes.remove(window); - checkState(accum != null && timestamp != null); - context.windowingInternals().outputWindowedValue( - KV.of(key, combineFn.extractOutput(key, accum)), - timestamp, - Arrays.asList(window), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java index f15a0c5e2a..175921d434 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java @@ -16,11 +16,8 @@ package com.google.cloud.dataflow.sdk.util; -import static com.google.common.base.Preconditions.checkNotNull; - import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; @@ -47,40 +44,15 @@ public abstract class GroupAlsoByWindowsDoFn GroupAlsoByWindowsDoFn, W> - createForIterable(WindowingStrategy windowingStrategy, Coder inputCoder) { - - return GroupAlsoByWindowsViaIteratorsDoFn.isSupported(windowingStrategy) - ? new GroupAlsoByWindowsViaIteratorsDoFn(windowingStrategy) - : new GroupAlsoByWindowsViaOutputBufferDoFn<>( - windowingStrategy, - SystemReduceFn.buffering(inputCoder)); - } - - /** - * Construct a {@link GroupAlsoByWindowsDoFn} using the {@code combineFn} if available. - */ - public static - GroupAlsoByWindowsDoFn - create( - final WindowingStrategy windowingStrategy, - final AppliedCombineFn combineFn, - final Coder keyCoder) { - - checkNotNull(combineFn); - - return GroupAlsoByWindowsAndCombineDoFn.isSupported(windowingStrategy) - ? new GroupAlsoByWindowsAndCombineDoFn<>( - windowingStrategy, - (KeyedCombineFn) combineFn.getFn()) - : new GroupAlsoByWindowsViaOutputBufferDoFn<>( - windowingStrategy, - SystemReduceFn.combining(keyCoder, combineFn)); + createDefault(WindowingStrategy windowingStrategy, Coder inputCoder) { + return new GroupAlsoByWindowsViaOutputBufferDoFn<>( + windowingStrategy, SystemReduceFn.buffering(inputCoder)); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFn.java deleted file mode 100644 index 400824017c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFn.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.common.PeekingReiterator; -import com.google.cloud.dataflow.sdk.util.common.Reiterable; -import com.google.cloud.dataflow.sdk.util.common.Reiterator; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Iterables; -import com.google.common.collect.ListMultimap; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * {@link GroupAlsoByWindowsDoFn} that uses reiterators to handle non-merging window functions with - * the default triggering strategy. - * - * @param key type - * @param value element type - * @param window type - */ -@SystemDoFnInternal -class GroupAlsoByWindowsViaIteratorsDoFn - extends GroupAlsoByWindowsDoFn, W> { - private final WindowingStrategy strategy; - - public static boolean isSupported(WindowingStrategy strategy) { - if (!strategy.getWindowFn().isNonMerging()) { - return false; - } - - // TODO: Add support for other triggers. - if (!(strategy.getTrigger().getSpec() instanceof DefaultTrigger)) { - return false; - } - - // It must be possible to compute the output timestamp of a pane from the input timestamp - // of the element with the earliest input timestamp. - if (!strategy.getOutputTimeFn().dependsOnlyOnEarliestInputTimestamp()) { - return false; - } - // Right now, we support ACCUMULATING_FIRED_PANES because it is the same as - // DISCARDING_FIRED_PANES. In Batch mode there is no late data so the default - // trigger (after watermark) will only fire once. - if (!(strategy.getMode().equals(AccumulationMode.DISCARDING_FIRED_PANES) - || strategy.getMode().equals(AccumulationMode.ACCUMULATING_FIRED_PANES))) { - return false; - } - - return true; - } - - public GroupAlsoByWindowsViaIteratorsDoFn(WindowingStrategy strategy) { - checkArgument(GroupAlsoByWindowsViaIteratorsDoFn.isSupported(strategy), - "%s does not support merging, non-default triggering, " - + "or any OutputTimeFn where dependsOnlyOnEarliest() is false, " - + "found in windowing strategy: %s", - getClass(), - strategy); - this.strategy = strategy; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - K key = c.element().getKey(); - // This iterable is required to be in order of increasing timestamps - Iterable> value = c.element().getValue(); - PeekingReiterator> iterator; - - if (value instanceof Collection) { - iterator = new PeekingReiterator<>(new ListReiterator>( - new ArrayList>((Collection>) value), 0)); - } else if (value instanceof Reiterable) { - iterator = new PeekingReiterator<>(((Reiterable>) value).iterator()); - } else { - throw new IllegalArgumentException( - "Input to GroupAlsoByWindowsDoFn must be a Collection or Reiterable"); - } - - // This ListMultimap is a map of window maxTimestamps to the list of active - // windows with that maxTimestamp. - ListMultimap windows = ArrayListMultimap.create(); - - while (iterator.hasNext()) { - WindowedValue e = iterator.peek(); - for (BoundedWindow window : e.getWindows()) { - // If this window is not already in the active set, emit a new WindowReiterable - // corresponding to this window, starting at this element in the input Reiterable. - if (!windows.containsEntry(window.maxTimestamp(), window)) { - // This window was produced by strategy.getWindowFn() - @SuppressWarnings("unchecked") - W typedWindow = (W) window; - // Iterating through the WindowReiterable may advance iterator as an optimization - // for as long as it detects that there are no new windows. - windows.put(window.maxTimestamp(), window); - c.windowingInternals().outputWindowedValue( - KV.of(key, (Iterable) new WindowReiterable(iterator, window)), - strategy.getOutputTimeFn().assignOutputTime(e.getTimestamp(), typedWindow), - Arrays.asList(window), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - } - } - // Copy the iterator in case the next DoFn cached its version of the iterator instead - // of immediately iterating through it. - // And, only advance the iterator if the consuming operation hasn't done so. - iterator = iterator.copy(); - if (iterator.hasNext() && iterator.peek() == e) { - iterator.next(); - } - - // Remove all windows with maxTimestamp behind the current timestamp. - Iterator windowIterator = windows.keys().iterator(); - while (windowIterator.hasNext() - && windowIterator.next().isBefore(e.getTimestamp())) { - windowIterator.remove(); - } - } - } - - /** - * {@link Reiterable} representing a view of all elements in a base - * {@link Reiterator} that are in a given window. - */ - private static class WindowReiterable implements Reiterable { - private PeekingReiterator> baseIterator; - private BoundedWindow window; - - public WindowReiterable( - PeekingReiterator> baseIterator, BoundedWindow window) { - this.baseIterator = baseIterator; - this.window = window; - } - - @Override - public Reiterator iterator() { - // We don't copy the baseIterator when creating the first WindowReiterator - // so that the WindowReiterator can advance the baseIterator. We have to - // make a copy afterwards so that future calls to iterator() will start - // at the right spot. - Reiterator result = new WindowReiterator(baseIterator, window); - baseIterator = baseIterator.copy(); - return result; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .addValue(Iterables.toString(this)) - .toString(); - } - } - - /** - * The {@link Reiterator} used by - * {@link com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsViaIteratorsDoFn.WindowReiterable}. - */ - private static class WindowReiterator implements Reiterator { - private PeekingReiterator> iterator; - private BoundedWindow window; - - public WindowReiterator(PeekingReiterator> iterator, BoundedWindow window) { - this.iterator = iterator; - this.window = window; - } - - @Override - public Reiterator copy() { - return new WindowReiterator(iterator.copy(), window); - } - - @Override - public boolean hasNext() { - skipToValidElement(); - return (iterator.hasNext() && iterator.peek().getWindows().contains(window)); - } - - @Override - public V next() { - skipToValidElement(); - WindowedValue next = iterator.next(); - if (!next.getWindows().contains(window)) { - throw new NoSuchElementException("No next item in window"); - } - return next.getValue(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - /** - * Moves the underlying iterator forward until it either points to the next - * element in the correct window, or is past the end of the window. - */ - private void skipToValidElement() { - while (iterator.hasNext()) { - WindowedValue peek = iterator.peek(); - if (peek.getTimestamp().isAfter(window.maxTimestamp())) { - // We are past the end of this window, so there can't be any more - // elements in this iterator. - break; - } - if (!(peek.getWindows().size() == 1 && peek.getWindows().contains(window))) { - // We have reached new windows; we need to copy the iterator so we don't - // keep advancing the outer loop in processElement. - iterator = iterator.copy(); - } - if (!peek.getWindows().contains(window)) { - // The next element is not in the right window: skip it. - iterator.next(); - } else { - // The next element is in the right window. - break; - } - } - } - } - - /** - * {@link Reiterator} that wraps a {@link List}. - */ - private static class ListReiterator implements Reiterator { - private List list; - private int index; - - public ListReiterator(List list, int index) { - this.list = list; - this.index = index; - } - - @Override - public T next() { - return list.get(index++); - } - - @Override - public boolean hasNext() { - return index < list.size(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public Reiterator copy() { - return new ListReiterator(list, index); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFnTest.java deleted file mode 100644 index 11df7e19d0..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsAndCombineDoFnTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsProperties.GroupAlsoByWindowsDoFnFactory; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link GroupAlsoByWindowsAndCombineDoFn}. */ -@RunWith(JUnit4.class) -public class GroupAlsoByWindowsAndCombineDoFnTest { - - private class GABWAndCombineDoFnFactory - implements GroupAlsoByWindowsDoFnFactory { - - private final KeyedCombineFn keyedCombineFn; - - public GABWAndCombineDoFnFactory( - KeyedCombineFn keyedCombineFn) { - this.keyedCombineFn = keyedCombineFn; - } - - @Override - public GroupAlsoByWindowsDoFn - forStrategy(WindowingStrategy windowingStrategy) { - - return new GroupAlsoByWindowsAndCombineDoFn( - windowingStrategy, - keyedCombineFn); - } - } - - @Test - public void testEmptyInputEmptyOutput() throws Exception { - GroupAlsoByWindowsProperties.emptyInputEmptyOutput( - new GABWAndCombineDoFnFactory<>(new Sum.SumLongFn().asKeyedFn())); - } - - @Test - public void testCombinesElementsInSlidingWindows() throws Exception { - CombineFn combineFn = new Sum.SumLongFn(); - - GroupAlsoByWindowsProperties.combinesElementsInSlidingWindows( - new GABWAndCombineDoFnFactory<>(combineFn.asKeyedFn()), - combineFn); - } - - @Test - public void testCombinesIntoSessions() throws Exception { - CombineFn combineFn = new Sum.SumLongFn(); - - GroupAlsoByWindowsProperties.combinesElementsPerSession( - new GABWAndCombineDoFnFactory<>(combineFn.asKeyedFn()), - combineFn); - } - - @Test - public void testCombinesIntoSessionsWithEndOfWindowTimestamp() throws Exception { - CombineFn combineFn = new Sum.SumLongFn(); - - GroupAlsoByWindowsProperties.combinesElementsPerSessionWithEndOfWindowTimestamp( - new GABWAndCombineDoFnFactory<>(combineFn.asKeyedFn()), - combineFn); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFnTest.java deleted file mode 100644 index 48e4e1656b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFnTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; - -import org.joda.time.Duration; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Unit tests for the static factory methods in the abstract - * class {@link GroupAlsoByWindowsDoFn}. - */ -@RunWith(JUnit4.class) -public class GroupAlsoByWindowsDoFnTest { - - @Test - public void testCreateNoncombiningNonmerging() throws Exception { - Coder inputCoder = VarLongCoder.of(); - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))); - - assertThat( - GroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, inputCoder), - instanceOf(GroupAlsoByWindowsViaIteratorsDoFn.class)); - } - - @Test - public void testCreateNoncombiningMerging() throws Exception { - Coder inputCoder = VarLongCoder.of(); - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))); - - assertThat( - GroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, inputCoder), - instanceOf(GroupAlsoByWindowsViaOutputBufferDoFn.class)); - } - - @Test - public void testCreateNoncombiningWithTrigger() throws Exception { - Coder inputCoder = VarLongCoder.of(); - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withTrigger(AfterPane.elementCountAtLeast(1)); - - assertThat( - GroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, inputCoder), - instanceOf(GroupAlsoByWindowsViaOutputBufferDoFn.class)); - } - - @Test - public void testCreateCombiningNonmerging() throws Exception { - Coder keyCoder = StringUtf8Coder.of(); - AppliedCombineFn appliedFn = AppliedCombineFn.withInputCoder( - new Sum.SumLongFn().asKeyedFn(), - new CoderRegistry(), - KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))); - - assertThat( - GroupAlsoByWindowsDoFn.create(windowingStrategy, - appliedFn, - keyCoder), - instanceOf(GroupAlsoByWindowsAndCombineDoFn.class)); - } - - @Test - public void testCreateCombiningMerging() throws Exception { - Coder keyCoder = StringUtf8Coder.of(); - AppliedCombineFn appliedFn = AppliedCombineFn.withInputCoder( - new Sum.SumLongFn().asKeyedFn(), - new CoderRegistry(), - KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))); - - assertThat( - GroupAlsoByWindowsDoFn.create(windowingStrategy, - appliedFn, - keyCoder), - instanceOf(GroupAlsoByWindowsAndCombineDoFn.class)); - } - - @Test - public void testCreateCombiningWithTrigger() throws Exception { - Coder keyCoder = StringUtf8Coder.of(); - AppliedCombineFn appliedFn = AppliedCombineFn.withInputCoder( - new Sum.SumLongFn().asKeyedFn(), - new CoderRegistry(), - KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))) - .withTrigger(AfterPane.elementCountAtLeast(1)); - - assertThat( - GroupAlsoByWindowsDoFn.create(windowingStrategy, - appliedFn, - keyCoder), - instanceOf(GroupAlsoByWindowsViaOutputBufferDoFn.class)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFnTest.java deleted file mode 100644 index 4134144355..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaIteratorsDoFnTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsProperties.GroupAlsoByWindowsDoFnFactory; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Unit tests for {@link GroupAlsoByWindowsViaIteratorsDoFn}. - * - *

    Note the absence of tests for sessions, as merging window functions are not supported. - */ -@RunWith(JUnit4.class) -public class GroupAlsoByWindowsViaIteratorsDoFnTest { - - @Rule - public final transient ExpectedException thrown = ExpectedException.none(); - - private class GABWViaIteratorsDoFnFactory - implements GroupAlsoByWindowsDoFnFactory> { - @Override - public GroupAlsoByWindowsDoFn, W> - forStrategy(WindowingStrategy windowingStrategy) { - return new GroupAlsoByWindowsViaIteratorsDoFn(windowingStrategy); - } - } - - @Test - public void testEmptyInputEmptyOutput() throws Exception { - GroupAlsoByWindowsProperties.emptyInputEmptyOutput( - new GABWViaIteratorsDoFnFactory<>()); - } - - @Test - public void testGroupsElementsIntoFixedWindows() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindows( - new GABWViaIteratorsDoFnFactory()); - } - - @Test - public void testGroupsElementsIntoSlidingWindows() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoSlidingWindows( - new GABWViaIteratorsDoFnFactory()); - } - - @Test - public void testGroupsIntoOverlappingNonmergingWindows() throws Exception { - GroupAlsoByWindowsProperties.groupsIntoOverlappingNonmergingWindows( - new GABWViaIteratorsDoFnFactory()); - } - - @Test - public void testGroupsElementsIntoFixedWindowsWithEndOfWindowTimestamp() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindowsWithEndOfWindowTimestamp( - new GABWViaIteratorsDoFnFactory()); - } - - @Test - public void testLatestTimestampNotSupported() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("OutputTimeFn"); - thrown.expectMessage("not support"); - - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindowsWithLatestTimestamp( - new GABWViaIteratorsDoFnFactory()); - } - - @Test - public void testGroupsElementsIntoFixedWindowsWithCustomTimestamp() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindowsWithCustomTimestamp( - new GABWViaIteratorsDoFnFactory()); - } - - @Test - public void testMergingNotSupported() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("merging"); - thrown.expectMessage("not support"); - - GroupAlsoByWindowsProperties.groupsElementsInMergedSessions( - new GABWViaIteratorsDoFnFactory()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java index 6109bf7442..1e8458de76 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java @@ -17,12 +17,7 @@ package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsProperties.GroupAlsoByWindowsDoFnFactory; @@ -54,27 +49,6 @@ public BufferingGABWViaOutputBufferDoFnFactory(Coder inputCoder) { } } - private class CombiningGABWViaOutputBufferDoFnFactory - implements GroupAlsoByWindowsDoFnFactory { - - private final Coder keyCoder; - private final AppliedCombineFn combineFn; - - public CombiningGABWViaOutputBufferDoFnFactory( - Coder keyCoder, AppliedCombineFn combineFn) { - this.keyCoder = keyCoder; - this.combineFn = combineFn; - } - - @Override - public GroupAlsoByWindowsDoFn - forStrategy(WindowingStrategy windowingStrategy) { - return new GroupAlsoByWindowsViaOutputBufferDoFn( - windowingStrategy, - SystemReduceFn.combining(keyCoder, combineFn)); - } - } - @Test public void testEmptyInputEmptyOutput() throws Exception { GroupAlsoByWindowsProperties.emptyInputEmptyOutput( @@ -93,20 +67,6 @@ public void testGroupsElementsIntoSlidingWindows() throws Exception { new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); } - @Test - public void testCombinesElementsInSlidingWindows() throws Exception { - CombineFn combineFn = new Sum.SumLongFn(); - AppliedCombineFn appliedFn = AppliedCombineFn.withInputCoder( - combineFn.asKeyedFn(), new CoderRegistry(), - KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); - - GroupAlsoByWindowsProperties.combinesElementsInSlidingWindows( - new CombiningGABWViaOutputBufferDoFnFactory<>( - StringUtf8Coder.of(), - appliedFn), - combineFn); - } - @Test public void testGroupsIntoOverlappingNonmergingWindows() throws Exception { GroupAlsoByWindowsProperties.groupsIntoOverlappingNonmergingWindows( @@ -119,20 +79,6 @@ public void testGroupsIntoSessions() throws Exception { new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); } - @Test - public void testCombinesIntoSessions() throws Exception { - CombineFn combineFn = new Sum.SumLongFn(); - AppliedCombineFn appliedFn = AppliedCombineFn.withInputCoder( - combineFn.asKeyedFn(), new CoderRegistry(), - KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); - - GroupAlsoByWindowsProperties.combinesElementsPerSession( - new CombiningGABWViaOutputBufferDoFnFactory<>( - StringUtf8Coder.of(), - appliedFn), - combineFn); - } - @Test public void testGroupsElementsIntoFixedWindowsWithEndOfWindowTimestamp() throws Exception { GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindowsWithEndOfWindowTimestamp( @@ -162,18 +108,4 @@ public void testGroupsElementsIntoSessionsWithLatestTimestamp() throws Exception GroupAlsoByWindowsProperties.groupsElementsInMergedSessionsWithLatestTimestamp( new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); } - - @Test - public void testCombinesIntoSessionsWithEndOfWindowTimestamp() throws Exception { - CombineFn combineFn = new Sum.SumLongFn(); - AppliedCombineFn appliedFn = AppliedCombineFn.withInputCoder( - combineFn.asKeyedFn(), new CoderRegistry(), - KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); - - GroupAlsoByWindowsProperties.combinesElementsPerSessionWithEndOfWindowTimestamp( - new CombiningGABWViaOutputBufferDoFnFactory<>( - StringUtf8Coder.of(), - appliedFn), - combineFn); - } } From c1a2e1f5f006e6d2d7fba7993f104472ddacedee Mon Sep 17 00:00:00 2001 From: tgroh Date: Tue, 16 Feb 2016 16:31:35 -0800 Subject: [PATCH 148/751] Declare SideInputs on Combine.GroupedValues This ensures the default expansion properly declares its SideInputs. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114807110 --- .../java/com/google/cloud/dataflow/sdk/transforms/Combine.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java index 0e3ae9be48..cc0347a124 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java @@ -2189,7 +2189,7 @@ public void processElement(ProcessContext c) { c.output(KV.of(key, combineFnRunner.apply(key, c.element().getValue(), c))); } - })); + }).withSideInputs(sideInputs)); try { Coder> outputCoder = getDefaultOutputCoder(input); From 75843ea37395c0c0ce0f5c42c41110ad4a06d8b8 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 17 Feb 2016 10:27:00 -0800 Subject: [PATCH 149/751] Update Dataflow API version to v1b3-rev19-1.21.0 ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114873638 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 071b5df4ea..7d0cba9e1d 100644 --- a/pom.xml +++ b/pom.xml @@ -70,7 +70,7 @@ 1.7.7 v2-rev248-1.21.0 0.2.3 - v1b3-rev14-1.21.0 + v1b3-rev19-1.21.0 v1beta2-rev1-4.0.0 1.21.0 19.0 From e30515402a38cdaee4ab23412a23b8e8563ce820 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 17 Feb 2016 10:44:57 -0800 Subject: [PATCH 150/751] Add InProcess Clock abstraction, nanoTime implementation The Clock abstraction represents access to the current runner processing time. The default implementation uses a nanosecond offset from a base milliseconds to calculate the current time. Use the clock in InMemoryWatermarkManager when calculating the processing time. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114875746 --- .../sdk/runners/inprocess/util/Clock.java | 29 +++++++ .../util/InMemoryWatermarkManager.java | 16 +++- .../inprocess/util/NanosOffsetClock.java | 58 +++++++++++++ .../util/InMemoryWatermarkManagerTest.java | 82 +++++++++---------- .../sdk/runners/inprocess/util/MockClock.java | 50 +++++++++++ 5 files changed, 188 insertions(+), 47 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/Clock.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/NanosOffsetClock.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/Clock.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/Clock.java new file mode 100644 index 0000000000..f2d57117f7 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/Clock.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import org.joda.time.Instant; + +/** + * Access to the current time. + */ +public interface Clock { + /** + * Returns the current time as an {@link Instant}. + */ + Instant now(); +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java index fb2e53686d..b3a1d92695 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java @@ -657,6 +657,11 @@ private static Map> extractFiredTimers( //////////////////////////////////////////////////////////////////////////////////////////////// + /** + * The {@link Clock} providing the current time in the {@link TimeDomain#PROCESSING_TIME} domain. + */ + private final Clock clock; + /** * A map from each {@link PCollection} to all {@link AppliedPTransform PTransform applications} * that consume that {@link PCollection}. @@ -678,14 +683,17 @@ private static Map> extractFiredTimers( * transforms that consume it as a part of their input */ public static InMemoryWatermarkManager create( + Clock clock, Collection> rootTransforms, Map>> consumers) { - return new InMemoryWatermarkManager(rootTransforms, consumers); + return new InMemoryWatermarkManager(clock, rootTransforms, consumers); } private InMemoryWatermarkManager( + Clock clock, Collection> rootTransforms, Map>> consumers) { + this.clock = clock; this.consumers = consumers; transformToWatermarks = new HashMap<>(); @@ -1060,7 +1068,7 @@ public Instant getOutputWatermark() { public synchronized Instant getSynchronizedProcessingInputTime() { latestSynchronizedInputWm = INSTANT_ORDERING.max( latestSynchronizedInputWm, - INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingInputWatermark.get())); + INSTANT_ORDERING.min(clock.now(), synchronizedProcessingInputWatermark.get())); return latestSynchronizedInputWm; } @@ -1073,7 +1081,7 @@ public synchronized Instant getSynchronizedProcessingInputTime() { public synchronized Instant getSynchronizedProcessingOutputTime() { latestSynchronizedOutputWm = INSTANT_ORDERING.max( latestSynchronizedOutputWm, - INSTANT_ORDERING.min(Instant.now(), synchronizedProcessingOutputWatermark.get())); + INSTANT_ORDERING.min(clock.now(), synchronizedProcessingOutputWatermark.get())); return latestSynchronizedOutputWm; } @@ -1110,7 +1118,7 @@ private Map extractFiredTimers() { TimeDomain.PROCESSING_TIME, BoundedWindow.TIMESTAMP_MAX_VALUE); } else { processingTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( - TimeDomain.PROCESSING_TIME, Instant.now()); + TimeDomain.PROCESSING_TIME, clock.now()); synchronizedTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( TimeDomain.SYNCHRONIZED_PROCESSING_TIME, getSynchronizedProcessingInputTime()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/NanosOffsetClock.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/NanosOffsetClock.java new file mode 100644 index 0000000000..623f07d675 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/NanosOffsetClock.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; + +import org.joda.time.Instant; + +import java.util.concurrent.TimeUnit; + +/** + * A {@link Clock} that uses {@link System#nanoTime()} to track the progress of time. + */ +public class NanosOffsetClock implements Clock { + private final long baseMillis; + private final long nanosAtBaseMillis; + + public static NanosOffsetClock create() { + return new NanosOffsetClock(); + } + + private NanosOffsetClock() { + baseMillis = System.currentTimeMillis(); + nanosAtBaseMillis = System.nanoTime(); + } + + @Override + public Instant now() { + return new Instant( + baseMillis + (TimeUnit.MILLISECONDS.convert( + System.nanoTime() - nanosAtBaseMillis, TimeUnit.NANOSECONDS))); + } + + /** + * Creates instances of {@link NanosOffsetClock}. + */ + public static class Factory implements DefaultValueFactory { + @Override + public Clock create(PipelineOptions options) { + return new NanosOffsetClock(); + } + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java index a549047524..54bc8bfa54 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java @@ -52,10 +52,8 @@ import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; -import org.joda.time.DateTimeUtils; import org.joda.time.Instant; import org.joda.time.ReadableInstant; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -72,7 +70,7 @@ */ @RunWith(JUnit4.class) public class InMemoryWatermarkManagerTest implements Serializable { - private static final Instant INITIAL_PROCESSING_TIME = new Instant(1000L); + private transient MockClock clock; private transient PCollection createdInts; @@ -87,8 +85,6 @@ public class InMemoryWatermarkManagerTest implements Serializable { @Before public void setup() { - DateTimeUtils.setCurrentMillisFixed(INITIAL_PROCESSING_TIME.getMillis()); - TestPipeline p = TestPipeline.create(); createdInts = p.apply("createdInts", Create.of(1, 2, 3)); @@ -130,12 +126,9 @@ public void processElement(DoFn.ProcessContext c) throws Excep flattened.getProducingTransformInternal())); consumers.put(flattened, Collections.>emptyList()); - manager = InMemoryWatermarkManager.create(rootTransforms, consumers); - } + clock = MockClock.fromInstant(new Instant(1000)); - @After - public void tearDown() { - DateTimeUtils.setCurrentMillisSystem(); + manager = InMemoryWatermarkManager.create(clock, rootTransforms, consumers); } /** @@ -388,12 +381,12 @@ public void updateWatermarkWithKeyedWatermarkHolds() { InProcessBundle.keyed(createdInts, "Odd") .add(WindowedValue.timestampedValueInGlobalWindow(1, new Instant(1_000_000L))) .add(WindowedValue.timestampedValueInGlobalWindow(3, new Instant(-1000L))) - .commit(Instant.now()); + .commit(clock.now()); CommittedBundle secondKeyBundle = InProcessBundle.keyed(createdInts, "Even") .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) - .commit(Instant.now()); + .commit(clock.now()); manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), ImmutableList.of(firstKeyBundle, secondKeyBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -411,7 +404,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); CommittedBundle fauxFirstKeyTimerBundle = - InProcessBundle.keyed(createdInts, "Odd").commit(Instant.now()); + InProcessBundle.keyed(createdInts, "Odd").commit(clock.now()); manager.updateWatermarks(fauxFirstKeyTimerBundle, filtered.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>emptyList(), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -419,7 +412,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(1234L))); CommittedBundle fauxSecondKeyTimerBundle = - InProcessBundle.keyed(createdInts, "Even").commit(Instant.now()); + InProcessBundle.keyed(createdInts, "Even").commit(clock.now()); manager.updateWatermarks(fauxSecondKeyTimerBundle, filtered.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>emptyList(), new Instant(5678L)); assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(5678L))); @@ -647,7 +640,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { TransformWatermarks watermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(INITIAL_PROCESSING_TIME)); + assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(clock.now())); assertThat( watermarks.getSynchronizedProcessingOutputTime(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); @@ -672,19 +665,19 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); - assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(clock.now())); + assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); TransformWatermarks filterAfterProduced = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat( - filterAfterProduced.getSynchronizedProcessingInputTime(), not(laterThan(Instant.now()))); + filterAfterProduced.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); assertThat( - filterAfterProduced.getSynchronizedProcessingOutputTime(), not(laterThan(Instant.now()))); + filterAfterProduced.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); - DateTimeUtils.setCurrentMillisFixed(1500L); - assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); - assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + clock.set(new Instant(1500L)); + assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(clock.now())); + assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); assertThat( filterAfterProduced.getSynchronizedProcessingInputTime(), not(laterThan(new Instant(1250L)))); @@ -739,13 +732,14 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), timers, Collections.>singleton(filteredBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); - DateTimeUtils.setCurrentMillisFixed(INITIAL_PROCESSING_TIME.plus(250L).getMillis()); + Instant startTime = clock.now(); + clock.set(startTime.plus(250L)); // We're held based on the past timer assertThat( - filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(INITIAL_PROCESSING_TIME))); + filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); assertThat( filteredDoubledWms.getSynchronizedProcessingOutputTime(), - not(laterThan(INITIAL_PROCESSING_TIME))); + not(laterThan(startTime))); // And we're monotonic assertThat( filteredWms.getSynchronizedProcessingOutputTime(), not(earlierThan(initialFilteredWm))); @@ -762,10 +756,10 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { contains(pastTimer)); // Our timer has fired, but has not been completed, so it holds our synchronized processing WM assertThat( - filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(INITIAL_PROCESSING_TIME))); + filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); assertThat( filteredDoubledWms.getSynchronizedProcessingOutputTime(), - not(laterThan(INITIAL_PROCESSING_TIME))); + not(laterThan(startTime))); CommittedBundle filteredTimerBundle = InProcessBundle.keyed(filtered, "key").commit(BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -780,18 +774,19 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { Collections.>singleton(filteredTimerResult), BoundedWindow.TIMESTAMP_MAX_VALUE); - DateTimeUtils.setCurrentMillisFixed(INITIAL_PROCESSING_TIME.plus(500L).getMillis()); - assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(Instant.now()))); + clock.set(startTime.plus(500L)); + assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); // filtered should be held to the time at which the filteredTimerResult fired assertThat( - filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(INITIAL_PROCESSING_TIME)); + filteredDoubledWms.getSynchronizedProcessingOutputTime(), + not(earlierThan(filteredTimerResult.getSynchronizedProcessingOutputWatermark()))); manager.updateWatermarks(filteredTimerResult, filteredTimesTwo.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>emptyList(), BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); - DateTimeUtils.setCurrentMillisFixed(Long.MAX_VALUE); + clock.set(new Instant(Long.MAX_VALUE)); assertThat(filteredWms.getSynchronizedProcessingOutputTime(), equalTo(new Instant(4096))); assertThat( filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(new Instant(4096))); @@ -803,9 +798,10 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { */ @Test public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { + Instant startTime = clock.now(); TransformWatermarks watermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(INITIAL_PROCESSING_TIME)); + assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(startTime)); TransformWatermarks filteredWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -828,9 +824,9 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( - createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(Instant.now()))); + createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); assertThat( - createAfterUpdate.getSynchronizedProcessingOutputTime(), not(laterThan(Instant.now()))); + createAfterUpdate.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); CommittedBundle createSecondOutput = InProcessBundle.unkeyed(createdInts).commit(new Instant(750L)); @@ -840,7 +836,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { Collections.>singleton(createSecondOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(Instant.now())); + assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); } @Test @@ -862,9 +858,9 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( TransformWatermarks downstreamWms = manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(clock.now())); - DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis()); + clock.set(BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); manager.extractFiredTimers(); @@ -879,7 +875,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( .build(), Collections.>emptyList(), BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), not(earlierThan(Instant.now()))); + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), not(earlierThan(clock.now()))); } @Test @@ -897,9 +893,9 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { TransformWatermarks downstreamWms = manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(Instant.now())); + assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(clock.now())); - DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis()); + clock.set(BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); } @@ -1011,7 +1007,7 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { FiredTimers firstFired = firstFilteredTimers.get(key); assertThat(firstFired.getTimers(TimeDomain.PROCESSING_TIME), contains(earliestTimer)); - DateTimeUtils.setCurrentMillisFixed(50_000L); + clock.set(new Instant(50_000L)); manager.updateOutputWatermark( createdInts.getProducingTransformInternal(), TimerUpdate.empty(), @@ -1069,7 +1065,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { assertThat( firstFired.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), contains(earliestTimer)); - DateTimeUtils.setCurrentMillisFixed(50_000L); + clock.set(new Instant(50_000L)); manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>emptyList(), new Instant(50_000L)); Map, Map> secondTransformFiredTimers = diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java new file mode 100644 index 0000000000..b45238474d --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import static com.google.common.base.Preconditions.checkArgument; + +import org.joda.time.Instant; + +/** + * A clock that returns a constant value for now which can be set with calls to + * {@link #set(Instant)}. + * + *

    For uses of the {@link Clock} interface in unit tests. + */ +public class MockClock implements Clock { + + private Instant now; + + public static MockClock fromInstant(Instant initial) { + return new MockClock(initial); + } + + private MockClock(Instant initialNow) { + this.now = initialNow; + } + + public void set(Instant newNow) { + checkArgument(!newNow.isBefore(now), "Cannot move MockClock backwards in time from %s to %s", + now, newNow); + this.now = newNow; + } + + @Override + public Instant now() { + return now; + } +} From aa7f07fa5b22f3656d52dc9e1d4557bceb87c013 Mon Sep 17 00:00:00 2001 From: bchambers Date: Wed, 17 Feb 2016 11:18:29 -0800 Subject: [PATCH 151/751] Improve TypeDescriptor inference of SimpleFunction Add the ability to get a TypeDescriptor from an *instance* of a context Object. This allows walking up the enclosing instances, and accessing the associated types. Specifically, allow the use of a concrete SimpleFunction inside a concrete PTransform to infer types from the enclosing PTransform instance. Make the inferred type in MapElements and FlatMapElements transient so we get Coder inference errors (more descriptive) rather than Serialization errors. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114879890 --- .../sdk/transforms/FlatMapElements.java | 2 +- .../dataflow/sdk/transforms/MapElements.java | 2 +- .../sdk/transforms/SimpleFunction.java | 4 +- .../dataflow/sdk/values/TypeDescriptor.java | 78 +++++++++++++++++++ .../sdk/transforms/FlatMapElementsTest.java | 31 ++++++++ .../sdk/transforms/MapElementsTest.java | 30 +++++++ .../sdk/values/TypeDescriptorTest.java | 74 ++++++++++++++---- 7 files changed, 202 insertions(+), 19 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java index b0837c46ff..fbaad5be6d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java @@ -121,7 +121,7 @@ private static TypeDescriptor getIterableElementType( ////////////////////////////////////////////////////////////////////////////////////////////////// private final SerializableFunction> fn; - private final TypeDescriptor outputType; + private final transient TypeDescriptor outputType; private FlatMapElements( SerializableFunction> fn, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java index 6d82dc49c0..8997050864 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java @@ -91,7 +91,7 @@ public MapElements withOutputType(TypeDescriptor outpu /////////////////////////////////////////////////////////////////// private final SerializableFunction fn; - private final TypeDescriptor outputType; + private final transient TypeDescriptor outputType; private MapElements( SerializableFunction fn, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java index 921bba8df7..ef6fd81a23 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java @@ -34,7 +34,7 @@ public abstract class SimpleFunction *

    See {@link #getOutputTypeDescriptor} for more discussion. */ public TypeDescriptor getInputTypeDescriptor() { - return new TypeDescriptor(getClass()) {}; + return new TypeDescriptor(this) {}; } /** @@ -49,6 +49,6 @@ public TypeDescriptor getInputTypeDescriptor() { * {@code PCollection}. */ public TypeDescriptor getOutputTypeDescriptor() { - return new TypeDescriptor(getClass()) {}; + return new TypeDescriptor(this) {}; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java index 8667010918..559d67ce05 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java @@ -22,11 +22,15 @@ import com.google.common.reflect.TypeToken; import java.io.Serializable; +import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.List; +import javax.annotation.Nullable; + /** * A description of a Java type, including actual generic parameters where possible. * @@ -66,6 +70,80 @@ protected TypeDescriptor() { token = new TypeToken(getClass()) {}; } + /** + * Creates a {@link TypeDescriptor} representing the type parameter {@code T}, which should + * resolve to a concrete type in the context of the class {@code clazz}. + * + *

    Unlike {@link TypeDescriptor#TypeDescriptor(Class)} this will also use context's of the + * enclosing instances while attempting to resolve the type. This means that the types of any + * classes instantiated in the concrete instance should be resolvable. + */ + protected TypeDescriptor(Object instance) { + TypeToken unresolvedToken = new TypeToken(getClass()) {}; + + // While we haven't fully resolved the parameters, refine it using the captured + // enclosing instance of the object. + unresolvedToken = TypeToken.of(instance.getClass()).resolveType(unresolvedToken.getType()); + + if (hasUnresolvedParameters(unresolvedToken.getType())) { + for (Field field : instance.getClass().getDeclaredFields()) { + Object fieldInstance = getEnclosingInstance(field, instance); + if (fieldInstance != null) { + unresolvedToken = + TypeToken.of(fieldInstance.getClass()).resolveType(unresolvedToken.getType()); + if (!hasUnresolvedParameters(unresolvedToken.getType())) { + break; + } + } + } + } + + // Once we've either fully resolved the parameters or exhausted enclosing instances, we have + // the best approximation to the token we can get. + @SuppressWarnings("unchecked") + TypeToken typedToken = (TypeToken) unresolvedToken; + token = typedToken; + } + + private boolean hasUnresolvedParameters(Type type) { + if (type instanceof TypeVariable) { + return true; + } else if (type instanceof ParameterizedType) { + ParameterizedType param = (ParameterizedType) type; + for (Type arg : param.getActualTypeArguments()) { + if (hasUnresolvedParameters(arg)) { + return true; + } + } + } + return false; + } + + /** + * Returns the enclosing instance if the field is synthetic and it is able to access it, or + * {@literal null} if not. + */ + @Nullable + private Object getEnclosingInstance(Field field, Object instance) { + if (!field.isSynthetic()) { + return null; + } + + boolean accessible = field.isAccessible(); + try { + field.setAccessible(true); + return field.get(instance); + } catch (IllegalArgumentException | IllegalAccessException e) { + // If we fail to get the enclosing instance field, do nothing. In the worst case, we won't + // refine the type based on information in this enclosing class -- that is consistent with + // previous behavior and is still a correct answer that can be fixed by returning the correct + // type descriptor. + return null; + } finally { + field.setAccessible(accessible); + } + } + /** * Creates a {@link TypeDescriptor} representing the type parameter * {@code T}, which should resolve to a concrete type in the context diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java index 6acefb050e..8938b0398f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.collect.ImmutableList; @@ -34,6 +35,7 @@ import org.junit.runners.JUnit4; import java.io.Serializable; +import java.util.Collections; import java.util.List; import java.util.Set; @@ -89,5 +91,34 @@ public Set apply(String input) { equalTo((TypeDescriptor) new TypeDescriptor() {})); assertThat(pipeline.getCoderRegistry().getDefaultCoder(output.getTypeDescriptor()), equalTo(pipeline.getCoderRegistry().getDefaultCoder(new TypeDescriptor() {}))); + + // Make sure the pipeline runs + pipeline.run(); + } + + @Test + public void testVoidValues() throws Exception { + Pipeline pipeline = TestPipeline.create(); + pipeline + .apply(Create.of("hello")) + .apply(WithKeys.of("k")) + .apply(new VoidValues() {}); + // Make sure the pipeline runs + pipeline.run(); + } + + static class VoidValues + extends PTransform>, PCollection>> { + + @Override + public PCollection> apply(PCollection> input) { + return input.apply(FlatMapElements., KV>via( + new SimpleFunction, Iterable>>() { + @Override + public Iterable> apply(KV input) { + return Collections.singletonList(KV.of(input.getKey(), null)); + } + })); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java index 99607a26b7..be3e720646 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; @@ -100,5 +101,34 @@ public String apply(String input) { equalTo((TypeDescriptor) new TypeDescriptor() {})); assertThat(pipeline.getCoderRegistry().getDefaultCoder(output.getTypeDescriptor()), equalTo(pipeline.getCoderRegistry().getDefaultCoder(new TypeDescriptor() {}))); + + // Make sure the pipelien runs too + pipeline.run(); + } + + @Test + public void testVoidValues() throws Exception { + Pipeline pipeline = TestPipeline.create(); + pipeline + .apply(Create.of("hello")) + .apply(WithKeys.of("k")) + .apply(new VoidValues() {}); + // Make sure the pipeline runs + pipeline.run(); + } + + static class VoidValues + extends PTransform>, PCollection>> { + + @Override + public PCollection> apply(PCollection> input) { + return input.apply(MapElements., KV>via( + new SimpleFunction, KV>() { + @Override + public KV apply(KV input) { + return KV.of(input.getKey(), null); + } + })); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java index 5d4591beea..a811a7cf65 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java @@ -61,22 +61,26 @@ public void testTypeDescriptorGeneric() throws Exception { } private static class TypeRememberer { - public TypeToken token; - public TypeDescriptor descriptor; + public final TypeDescriptor descriptorByClass; + public final TypeDescriptor descriptorByInstance; public TypeRememberer() { - token = new TypeToken(getClass()){}; - descriptor = new TypeDescriptor(getClass()){}; + descriptorByClass = new TypeDescriptor(getClass()){}; + descriptorByInstance = new TypeDescriptor(this) {}; } } @Test public void testTypeDescriptorNested() throws Exception { TypeRememberer rememberer = new TypeRememberer(){}; - assertEquals(rememberer.token.getType(), rememberer.descriptor.getType()); + assertEquals(new TypeToken() {}.getType(), rememberer.descriptorByClass.getType()); + assertEquals(new TypeToken() {}.getType(), rememberer.descriptorByInstance.getType()); TypeRememberer> genericRememberer = new TypeRememberer>(){}; - assertEquals(genericRememberer.token.getType(), genericRememberer.descriptor.getType()); + assertEquals(new TypeToken>() {}.getType(), + genericRememberer.descriptorByClass.getType()); + assertEquals(new TypeToken>() {}.getType(), + genericRememberer.descriptorByInstance.getType()); } private static class Id { @@ -104,15 +108,10 @@ public void testGetArgumentTypes() throws Exception { } private static class TypeRemembererer { - public TypeToken token1; - public TypeToken token2; - public TypeDescriptor descriptor1; public TypeDescriptor descriptor2; public TypeRemembererer() { - token1 = new TypeToken(getClass()){}; - token2 = new TypeToken(getClass()){}; descriptor1 = new TypeDescriptor(getClass()){}; descriptor2 = new TypeDescriptor(getClass()){}; } @@ -121,13 +120,15 @@ public TypeRemembererer() { @Test public void testTypeDescriptorNested2() throws Exception { TypeRemembererer remembererer = new TypeRemembererer(){}; - assertEquals(remembererer.token1.getType(), remembererer.descriptor1.getType()); - assertEquals(remembererer.token2.getType(), remembererer.descriptor2.getType()); + assertEquals(new TypeToken() {}.getType(), remembererer.descriptor1.getType()); + assertEquals(new TypeToken() {}.getType(), remembererer.descriptor2.getType()); TypeRemembererer, Set> genericRemembererer = new TypeRemembererer, Set>(){}; - assertEquals(genericRemembererer.token1.getType(), genericRemembererer.descriptor1.getType()); - assertEquals(genericRemembererer.token2.getType(), genericRemembererer.descriptor2.getType()); + assertEquals(new TypeToken>() {}.getType(), + genericRemembererer.descriptor1.getType()); + assertEquals(new TypeToken>() {}.getType(), + genericRemembererer.descriptor2.getType()); } private static class GenericClass { } @@ -146,4 +147,47 @@ public void testGetTypeParameterBad() throws Exception { thrown.expectMessage("MerpleT"); // just check that the message gives actionable details TypeDescriptor.of(GenericClass.class).getTypeParameter("MerpleT"); } + + private static class GenericMaker { + public TypeRememberer> getRememberer() { + return new TypeRememberer>() {}; + } + } + + private static class GenericMaker2 { + public GenericMaker> getGenericMaker() { + return new GenericMaker>() {}; + } + } + + @Test + public void testEnclosing() throws Exception { + TypeRememberer> rememberer = new GenericMaker(){}.getRememberer(); + assertEquals( + new TypeToken>() {}.getType(), rememberer.descriptorByInstance.getType()); + + // descriptorByClass *is not* able to find the type of T because it comes from the enclosing + // instance of GenericMaker. + // assertEquals(new TypeToken>() {}.getType(), rememberer.descriptorByClass.getType()); + } + + @Test + public void testEnclosing2() throws Exception { + // If we don't override, the best we can get is List> + // TypeRememberer>> rememberer = + // new GenericMaker2(){}.getGenericMaker().getRememberer(); + // assertNotEquals( + // new TypeToken>>() {}.getType(), + // rememberer.descriptorByInstance.getType()); + + // If we've overridden the getGenericMaker we can determine the types. + TypeRememberer>> rememberer = new GenericMaker2() { + @Override public GenericMaker> getGenericMaker() { + return new GenericMaker>() {}; + } + }.getGenericMaker().getRememberer(); + assertEquals( + new TypeToken>>() {}.getType(), + rememberer.descriptorByInstance.getType()); + } } From 3f24ca3316d01c2b756c3f3900a926489fdb04e3 Mon Sep 17 00:00:00 2001 From: millsd Date: Wed, 17 Feb 2016 11:35:42 -0800 Subject: [PATCH 152/751] Fix AfterSynchronizedProcessingTime.java ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114881925 --- .../transforms/windowing/AfterSynchronizedProcessingTime.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java index a811a9b273..0a274c9ce0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java @@ -32,8 +32,7 @@ class AfterSynchronizedProcessingTime @Override @Nullable public Instant getCurrentTime(Trigger.TriggerContext context) { - // TODO: plumb synchronized processing time - return context.currentProcessingTime(); + return context.currentSynchronizedProcessingTime(); } public AfterSynchronizedProcessingTime() { From d30c981b21f17520322f9ea121df62153aef13c0 Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 17 Feb 2016 12:14:44 -0800 Subject: [PATCH 153/751] Remove debug statement from test ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114886024 --- .../java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java index aa45050e50..16b4640962 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java @@ -828,7 +828,6 @@ public void processElement(ProcessContext c) { assertEquals((int) c.element(), c.sideInput(view).size()); assertEquals((int) c.element(), c.sideInput(view).entrySet().size()); for (Entry entry : c.sideInput(view).entrySet()) { - System.out.println("LCWIKL: " + entry); c.output(KV.of(entry.getKey(), entry.getValue())); } } From 54999c58c88981d17674dac4f64b950fabc7d19a Mon Sep 17 00:00:00 2001 From: markshields Date: Wed, 17 Feb 2016 12:28:40 -0800 Subject: [PATCH 154/751] Make sure every hold is accompanied by a proximate timer We now maintain the invariant that every hold inside(outside) a window is accompanied by a timer inside(outside) the window. Consider this situation: - Input watermark beyond end-of-window. - Any AfterWatermark trigger already fired. - Output watermark still inside window. - Element added which is behind input watermark but ahead of output watermark. Previously we would set a hold inside the window which would not be cleared until the window was garbage collected - possibly a very long time in the future. We now set at most a garbage collection hold. To make the invariant checkable even with merging windows we always create end-of-window or garbage collection times in ReduceFnRunner.processElement. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114887337 --- .../transforms/windowing/AfterWatermark.java | 5 +- .../dataflow/sdk/util/PaneInfoTracker.java | 16 +-- .../dataflow/sdk/util/ReduceFnRunner.java | 100 ++++++++----- .../dataflow/sdk/util/WatermarkHold.java | 136 +++++++++++------- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 66 +++++++-- .../dataflow/sdk/util/ReduceFnTester.java | 63 +++++++- 6 files changed, 275 insertions(+), 111 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index 1330337926..da16db99c6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -331,8 +331,9 @@ public AfterWatermarkLate withLateFirings(OnceTrigger lateFirings) { @Override public void onElement(OnElementContext c) throws Exception { - // NOTE: The ReduceFnRunner will have already set an end-of-window timer, so this is - // redundant. However we leave it here so that the trigger machinery can stand on its own. + // We're interested in knowing when the input watermark passes the end of the window. + // (It is possible this has already happened, in which case the timer will be fired + // almost immediately). c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index e055b5828e..f0fa9936b0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -54,13 +54,13 @@ public void clear(StateContext state) { * Return a (future for) the pane info appropriate for {@code context}. The pane info * includes the timing for the pane, who's calculation is quite subtle. * - * @param isWatermarkTrigger should be {@code true} only if the pane is being emitted - * because a {@link AfterWatermark#pastEndOfWindow} trigger has fired. + * @param isEndOfWindow should be {@code true} only if the pane is being emitted + * because an end-of-window timer has fired and the trigger agreed we should fire. * @param isFinal should be {@code true} only if the triggering machinery can guarantee * no further firings for the */ public StateContents getNextPaneInfo(ReduceFn.Context context, - final boolean isWatermarkTrigger, final boolean isFinal) { + final boolean isEndOfWindow, final boolean isFinal) { final Object key = context.key(); final StateContents previousPaneFuture = context.state().access(PaneInfoTracker.PANE_INFO_TAG).get(); @@ -70,7 +70,7 @@ public StateContents getNextPaneInfo(ReduceFn.Context cont @Override public PaneInfo read() { PaneInfo previousPane = previousPaneFuture.read(); - return describePane(key, windowMaxTimestamp, previousPane, isWatermarkTrigger, isFinal); + return describePane(key, windowMaxTimestamp, previousPane, isEndOfWindow, isFinal); } }; } @@ -80,7 +80,7 @@ public void storeCurrentPaneInfo(ReduceFn.Context context, PaneInfo } private PaneInfo describePane(Object key, Instant windowMaxTimestamp, PaneInfo previousPane, - boolean isWatermarkTrigger, boolean isFinal) { + boolean isEndOfWindow, boolean isFinal) { boolean isFirst = previousPane == null; Timing previousTiming = isFirst ? null : previousPane.getTiming(); long index = isFirst ? 0 : previousPane.getIndex() + 1; @@ -104,7 +104,7 @@ private PaneInfo describePane(Object key, Instant windowMaxTimestamp, PaneIn // emitted a non-EARLY pane. Irrespective of how this pane was triggered we must // consider this pane LATE. timing = Timing.LATE; - } else if (isWatermarkTrigger) { + } else if (isEndOfWindow) { // This is the unique ON_TIME firing for the window. timing = Timing.ON_TIME; } else { @@ -115,8 +115,8 @@ private PaneInfo describePane(Object key, Instant windowMaxTimestamp, PaneIn WindowTracing.debug( "describePane: {} pane (prev was {}) for key:{}; windowMaxTimestamp:{}; " - + "inputWatermark:{}; outputWatermark:{}; isWatermarkTrigger:{}; isLateForOutput:{}", - timing, previousTiming, key, windowMaxTimestamp, inputWM, outputWM, isWatermarkTrigger, + + "inputWatermark:{}; outputWatermark:{}; isEndOfWindow:{}; isLateForOutput:{}", + timing, previousTiming, key, windowMaxTimestamp, inputWM, outputWM, isEndOfWindow, isLateForOutput); if (previousPane != null) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index a015b06c50..d550a2395c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; @@ -35,7 +36,6 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import com.google.common.collect.Sets; import org.joda.time.Duration; import org.joda.time.Instant; @@ -47,6 +47,8 @@ import java.util.List; import java.util.Set; +import javax.annotation.Nullable; + /** * Manages the execution of a {@link ReduceFn} after a {@link GroupByKeyOnly} has partitioned the * {@link PCollection} by key. @@ -305,8 +307,6 @@ private void collectAndMergeWindows(Iterable> values) thro return; } - Set currentlyActiveWindows = Sets.newHashSet(activeWindows.getActiveWindows()); - // Collect the windows from all elements (except those which are too late) and // make sure they are already in the active window set or are added as NEW windows. for (WindowedValue value : values) { @@ -342,13 +342,6 @@ private void collectAndMergeWindows(Iterable> values) thro // Merge all of the active windows and retain a mapping from source windows to result windows. mergeActiveWindows(); - - // Make sure we've scheduled end-of-window or garbage collection timers for any - // ACTIVE windows we just introduced. - // (Timers for ACTIVE windows which are now MERGED will have been discarded above.) - for (W window : Sets.difference(activeWindows.getActiveWindows(), currentlyActiveWindows)) { - scheduleEndOfWindowOrGarbageCollectionTimer(contextFactory.base(window, StateStyle.DIRECT)); - } } private class OnMergeCallback implements ActiveWindowSet.MergeCallback { @@ -410,6 +403,9 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W ReduceFn.Context directClearContext = contextFactory.base(active, StateStyle.DIRECT); // No need for the end-of-window or garbage collection timers. + // We will establish a new end-of-window or garbage collection timer for the mergeResult + // window in processElement below. There must be at least one element for the mergeResult + // window since a new element with a new window must have triggered this onMerge. cancelEndOfWindowAndGarbageCollectionTimers(directClearContext); // We no longer care about any previous panes of merged away windows. The // merge result window gets to start fresh if it is new. @@ -470,18 +466,27 @@ private Collection processElement(WindowedValue value) throws Excepti nonEmptyPanes.recordContent(renamedContext.state()); - // Make sure we've scheduled the end-of-window or garbage collection timer for this window - // However if we have pre-merged then they will already have been scheduled. - if (windowingStrategy.getWindowFn().isNonMerging()) { - scheduleEndOfWindowOrGarbageCollectionTimer(directContext); - } + // Make sure we've scheduled the end-of-window or garbage collection timer for this window. + Instant timer = scheduleEndOfWindowOrGarbageCollectionTimer(directContext); // Hold back progress of the output watermark until we have processed the pane this // element will be included within. If the element is too late for that, place a hold at // the end-of-window or garbage collection time to allow empty panes to contribute elements // which won't be dropped due to lateness by a following computation (assuming the following // computation uses the same allowed lateness value...) - watermarkHold.addHolds(renamedContext); + @Nullable Instant hold = watermarkHold.addHolds(renamedContext); + + if (hold != null) { + // Assert that holds have a proximate timer. + boolean holdInWindow = !hold.isAfter(window.maxTimestamp()); + boolean timerInWindow = !timer.isAfter(window.maxTimestamp()); + Preconditions.checkState( + holdInWindow == timerInWindow, + "set a hold at %s, a timer at %s, which disagree as to whether they are in window %s", + hold, + timer, + directContext.window()); + } // Execute the reduceFn, which will buffer the value as appropriate reduceFn.processValue(renamedContext); @@ -529,7 +534,7 @@ public void onTimer(TimerData timer) throws Exception { // 1. We need to set a GC timer // 2. We need to let the PaneInfoTracker know that we are transitioning from early to late, // and possibly emitting an on-time pane. - boolean isEndOfWindowTimer = + boolean isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() && timer.getTimestamp().equals(window.maxTimestamp()); @@ -549,8 +554,7 @@ public void onTimer(TimerData timer) throws Exception { // We need to call onTrigger to emit the final pane if required. // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, // and the watermark has passed the end of the window. - boolean isWatermarkTrigger = isEndOfWindowTimer; - onTrigger(directContext, renamedContext, isWatermarkTrigger, true/* isFinished */); + onTrigger(directContext, renamedContext, isEndOfWindow, true/* isFinished */); } // Cleanup flavor B: Clear all the remaining state for this window since we'll never @@ -563,10 +567,10 @@ public void onTimer(TimerData timer) throws Exception { key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); if (windowIsActive) { - emitIfAppropriate(directContext, renamedContext, isEndOfWindowTimer); + emitIfAppropriate(directContext, renamedContext, isEndOfWindow); } - if (isEndOfWindowTimer) { + if (isEndOfWindow) { // Since we are processing an on-time firing we should schedule the garbage collection // timer. (If getAllowedLateness is zero then the timer event will be considered a // cleanup event and handled by the above). @@ -687,13 +691,13 @@ private void emitIfAppropriate(ReduceFn.Context directCon * Do we need to emit a pane? */ private boolean needToEmit( - boolean isEmpty, boolean isWatermarkTrigger, boolean isFinished, PaneInfo.Timing timing) { + boolean isEmpty, boolean isEndOfWindow, boolean isFinished, PaneInfo.Timing timing) { if (!isEmpty) { // The pane has elements. return true; } - if (isWatermarkTrigger && timing == Timing.ON_TIME) { - // This is the unique ON_TIME pane, triggered by an AfterWatermark. + if (isEndOfWindow && timing == Timing.ON_TIME) { + // This is the unique ON_TIME pane. return true; } if (isFinished && windowingStrategy.getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS) { @@ -709,14 +713,14 @@ private boolean needToEmit( private void onTrigger( final ReduceFn.Context directContext, ReduceFn.Context renamedContext, - boolean isWatermarkTrigger, + boolean isEndOfWindow, boolean isFinished) throws Exception { // Collect state. StateContents outputTimestampFuture = watermarkHold.extractAndRelease(renamedContext, isFinished); StateContents paneFuture = - paneInfoTracker.getNextPaneInfo(directContext, isWatermarkTrigger, isFinished); + paneInfoTracker.getNextPaneInfo(directContext, isEndOfWindow, isFinished); StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext.state()); reduceFn.prefetchOnTrigger(directContext.state()); @@ -728,7 +732,7 @@ private void onTrigger( final Instant outputTimestamp = outputTimestampFuture.read(); // Only emit a pane if it has data or empty panes are observable. - if (needToEmit(isEmptyFuture.read(), isWatermarkTrigger, isFinished, pane.getTiming())) { + if (needToEmit(isEmptyFuture.read(), isEndOfWindow, isFinished, pane.getTiming())) { // Run reduceFn.onTrigger method. final List windows = Collections.singletonList(directContext.window()); ReduceFn.OnTriggerContext renamedTriggerContext = @@ -752,26 +756,46 @@ public void output(OutputT toOutput) { } /** - * Make sure we will notice when the input watermark passes the end-of-window or garbage - * collection time. + * Make sure we'll eventually have a timer fire which will tell us to garbage collect + * the window state. For efficiency we may need to do this in two steps rather + * than one. Return the time at which the timer will fire. + * + *

      + *
    • If allowedLateness is zero then we'll garbage collect at the end of the window. + * For simplicity we'll set our own timer for this situation even though an + * {@link AfterWatermark} trigger may have also set an end-of-window timer. + * ({@code setTimer} is idempotent.) + *
    • If allowedLateness is non-zero then we could just always set a timer for the garbage + * collection time. However if the windows are large (eg hourly) and the allowedLateness is small + * (eg seconds) then we'll end up with nearly twice the number of timers in-flight. So we + * instead set an end-of-window timer and then roll that forward to a garbage collection timer + * when it fires. We use the input watermark to distinguish those cases. + *
    */ - private void scheduleEndOfWindowOrGarbageCollectionTimer( + private Instant scheduleEndOfWindowOrGarbageCollectionTimer( ReduceFn.Context directContext) { - Instant fireTime = directContext.window().maxTimestamp(); - String which = "end-of-window"; Instant inputWM = timerInternals.currentInputWatermarkTime(); - if (inputWM != null && fireTime.isBefore(inputWM)) { - fireTime = fireTime.plus(windowingStrategy.getAllowedLateness()); + Instant endOfWindow = directContext.window().maxTimestamp(); + Instant fireTime; + String which; + if (inputWM != null && endOfWindow.isBefore(inputWM)) { + fireTime = endOfWindow.plus(windowingStrategy.getAllowedLateness()); which = "garbage collection"; - Preconditions.checkState(!fireTime.isBefore(inputWM), - "Asking to set a timer at %s behind input watermark %s", fireTime, inputWM); + } else { + fireTime = endOfWindow; + which = "end-of-window"; } WindowTracing.trace( "ReduceFnRunner.scheduleEndOfWindowOrGarbageCollectionTimer: Scheduling {} timer at {} for " - + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", - which, fireTime, key, directContext.window(), inputWM, + + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", + which, + fireTime, + key, + directContext.window(), + inputWM, timerInternals.currentOutputWatermarkTime()); directContext.timers().setTimer(fireTime, TimeDomain.EVENT_TIME); + return fireTime; } private void cancelEndOfWindowAndGarbageCollectionTimers(ReduceFn.Context context) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index a79b8d32de..4d37cdb0db 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -33,6 +33,8 @@ import java.io.Serializable; +import javax.annotation.Nullable; + /** * Implements the logic to hold the output watermark for a computation back * until it has seen all the elements it needs based on the input watermark for the @@ -53,9 +55,11 @@ class WatermarkHold implements Serializable { * Return tag for state containing the output watermark hold * used for elements. */ - public static StateTag> - watermarkHoldTagForOutputTimeFn(OutputTimeFn outputTimeFn) { - return StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal("hold", outputTimeFn)); + public static + StateTag> watermarkHoldTagForOutputTimeFn( + OutputTimeFn outputTimeFn) { + return StateTags.>makeSystemTagInternal( + StateTags.watermarkStateInternal("hold", outputTimeFn)); } /** @@ -83,13 +87,14 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind * Add a hold to prevent the output watermark progressing beyond the (possibly adjusted) timestamp * of the element in {@code context}. We allow the actual hold time to be shifted later by * {@link OutputTimeFn#assignOutputTime}, but no further than the end of the window. The hold will - * remain until cleared by {@link #extractAndRelease}. + * remain until cleared by {@link #extractAndRelease}. Return the timestamp at which the hold + * was placed, or {@literal null} if no hold was placed. * - *

    In the following we'll write {@code E} to represent an element, {@code IWM} for - * the local input watermark, {@code OWM} for the local output watermark, and {@code GCWM} for - * the garbage collection watermark (which is at {@code IWM - getAllowedLateness}). Time - * progresses from left to right, and we write {@code [ ... ]} to denote a bounded window with - * implied lower bound. + *

    In the following we'll write {@code E} to represent an element's timestamp after passing + * through the window strategy's output time function, {@code IWM} for the local input watermark, + * {@code OWM} for the local output watermark, and {@code GCWM} for the garbage collection + * watermark (which is at {@code IWM - getAllowedLateness}). Time progresses from left to right, + * and we write {@code [ ... ]} to denote a bounded window with implied lower bound. * *

    Note that the GCWM will be the same as the IWM if {@code getAllowedLateness} * is {@code ZERO}. @@ -106,10 +111,9 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind * * This is, hopefully, the common and happy case. The element is locally on-time and can * definitely make it to an {@code ON_TIME} pane which we can still set an end-of-window timer - * for. We place an element hold at E which will become the {@code ON_TIME} pane's timestamp - * if it is the earliest such hold. (Thus the OWM will not proceed past E until the next pane - * fires). We also place an end-of-window and (if required) garbage collection hold in case - * this is the first element seen for the window. + * for. We place an element hold at E, which may contribute to the {@code ON_TIME} pane's + * timestamp (depending on the output time function). Thus the OWM will not proceed past E + * until the next pane fires. * *

  • (Discard - no target window) *
    @@ -133,7 +137,7 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind
        * OWM. In effect, we get to 'launder' the locally late element and consider it as locally
        * on-time because no downstream computation can observe the difference.
        *
    -   * 
  • (Input Late) + *
  • (Maybe late 1) *
        *          |            |
        *      [   | E        ] |
    @@ -141,33 +145,34 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind
        *         OWM          IWM
        * 
    * The end-of-window timer may have already fired for this window, and thus an {@code ON_TIME} - * pane may have already been emitted. We can still place an element hold, which will be - * cleared when the next pane fires (which could be {@code ON_TIME} or {@code LATE}). We - * should not place an end-of-window hold since we cannot guarantee it will be cleared until - * the garbage collection timer fires. We can still place a garbage collection hold if required. + * pane may have already been emitted. However, if timer firings have been delayed then it + * is possible the {@code ON_TIME} pane has not yet been emitted. We can't place an element + * hold since we can't be sure if it will be cleared promptly. Thus this element *may* find + * its way into an {@code ON_TIME} pane, but if so it will *not* contribute to that pane's + * timestamp. We may however set a garbage collection hold if required. * - *
  • (Possibly unobservably late - 1) + *
  • (Maybe late 2) *
        *               |   |
        *      [     E  |   | ]
        *               |   |
        *              OWM IWM
        * 
    - * The element is too late to contribute to the output watermark hold, and thus won't - * contribute the any pane's timestamp. We don't know if a hold has been placed at or later - * than the OWM for this window. Thus we can't be sure E will make an {@code ON_TIME} pane, - * even though we know the end-of-window timer is yet to fire. We can still place an - * end-of-window hold, and a garbage collection hold if required. + * The end-of-window timer has not yet fired, so this element may still appear in an + * {@code ON_TIME} pane. However the element is too late to contribute to the output + * watermark hold, and thus won't contribute to the pane's timestamp. We can still place an + * end-of-window hold. * - *
  • (Possibly unobservably late - 2) + *
  • (Maybe late 3) *
        *               |       |
        *      [     E  |     ] |
        *               |       |
        *              OWM     IWM
        * 
    - * As for the previous case, however we don't even know if the end-of-window timer has already - * fired, or it is about to fire. We can place only the garbage collection hold, if required. + * As for the (Maybe late 2) case, however we don't even know if the end-of-window timer + * has already fired, or it is about to fire. We can place only the garbage collection hold, + * if required. * *
  • (Definitely late) *
    @@ -181,10 +186,13 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind
        *
        * 
        */
    -  public void addHolds(ReduceFn.ProcessValueContext context) {
    -    if (!addElementHold(context)) {
    -      addEndOfWindowOrGarbageCollectionHolds(context);
    +  @Nullable
    +  public Instant addHolds(ReduceFn.ProcessValueContext context) {
    +    Instant hold = addElementHold(context);
    +    if (hold == null) {
    +      hold = addEndOfWindowOrGarbageCollectionHolds(context);
         }
    +    return hold;
       }
     
       /**
    @@ -208,9 +216,11 @@ private Instant shift(Instant timestamp, W window) {
       }
     
       /**
    -   * Add an element hold if possible. Return true if was added, false if too late to add.
    +   * Add an element hold if possible. Return instant at which hold was added, or {@literal null}
    +   * if no hold was added.
        */
    -  private boolean addElementHold(ReduceFn.ProcessValueContext context) {
    +  @Nullable
    +  private Instant addElementHold(ReduceFn.ProcessValueContext context) {
         // Give the window function a chance to move the hold timestamp forward to encourage progress.
         // (A later hold implies less impediment to the output watermark making progress, which in
         // turn encourages end-of-window triggers to fire earlier in following computations.)
    @@ -219,52 +229,72 @@ private boolean addElementHold(ReduceFn.ProcessValueContext context)
         Instant outputWM = timerInternals.currentOutputWatermarkTime();
         Instant inputWM = timerInternals.currentInputWatermarkTime();
     
    -    // Only add the hold if we can be sure the backend will be able to respect it.
    +    // Only add the hold if we can be sure:
    +    // - the backend will be able to respect it
    +    // (ie the hold is at or ahead of the output watermark), AND
    +    // - a timer will be set to clear it by the end of window
    +    // (ie the end of window is at or ahead of the input watermark).
    +    String which;
         boolean tooLate;
    +    // TODO: These case labels could be tightened.
    +    // See the case analysis in addHolds above for the motivation.
         if (outputWM != null && elementHold.isBefore(outputWM)) {
    +      which = "too late to effect output watermark";
    +      tooLate = true;
    +    } else if (inputWM != null && context.window().maxTimestamp().isBefore(inputWM)) {
    +      which = "too late for end-of-window timer";
           tooLate = true;
         } else {
    +      which = "on time";
           tooLate = false;
           context.state().access(elementHoldTag).add(elementHold);
         }
         WindowTracing.trace(
             "WatermarkHold.addHolds: element hold at {} is {} for "
             + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}",
    -        elementHold, tooLate ? "too late" : "on-time", context.key(), context.window(), inputWM,
    +        elementHold, which, context.key(), context.window(), inputWM,
             outputWM);
     
    -    return !tooLate;
    +    return tooLate ? null : elementHold;
       }
     
       /**
        * Add an end-of-window hold or, if too late for that, a garbage collection hold (if required).
    +   * Return the {@link Instant} at which hold was added, or {@literal null} if no hold was added.
        *
        * 

    The end-of-window hold guarantees that an empty {@code ON_TIME} pane can be given * a timestamp which will not be considered beyond allowed lateness by any downstream computation. */ - private void addEndOfWindowOrGarbageCollectionHolds(ReduceFn.Context context) { - if (!addEndOfWindowHold(context)) { - addGarbageCollectionHold(context); + @Nullable + private Instant addEndOfWindowOrGarbageCollectionHolds(ReduceFn.Context context) { + Instant hold = addEndOfWindowHold(context); + if (hold == null) { + hold = addGarbageCollectionHold(context); } + return hold; } /** - * Add an end-of-window hold. Return true if was added, false if too late to add. + * Add an end-of-window hold. Return the {@link Instant} at which hold was added, + * or {@literal null} if no hold was added. * *

    The end-of-window hold guarantees that any empty {@code ON_TIME} pane can be given * a timestamp which will not be considered beyond allowed lateness by any downstream computation. */ - private boolean addEndOfWindowHold(ReduceFn.Context context) { - // Only add an end-of-window hold if we can be sure the end-of-window timer - // has not yet fired. Otherwise we risk holding up the output watermark until - // the garbage collection timer fires, which may be a very long time in the future. + @Nullable + private Instant addEndOfWindowHold(ReduceFn.Context context) { + // Only add an end-of-window hold if we can be sure a timer will be set to clear it + // by the end of window (ie the end of window is at or ahead of the input watermark). Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); + String which; boolean tooLate; Instant eowHold = context.window().maxTimestamp(); if (inputWM != null && eowHold.isBefore(inputWM)) { + which = "too late for end-of-window timer"; tooLate = true; } else { + which = "on time"; tooLate = false; Preconditions.checkState(outputWM == null || !eowHold.isBefore(outputWM), "End-of-window hold %s cannot be before output watermark %s", eowHold, outputWM); @@ -273,22 +303,27 @@ private boolean addEndOfWindowHold(ReduceFn.Context context) { WindowTracing.trace( "WatermarkHold.addEndOfWindowHold: end-of-window hold at {} is {} for " + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - eowHold, tooLate ? "too late" : "on-time", context.key(), context.window(), inputWM, + eowHold, which, context.key(), context.window(), inputWM, outputWM); - return !tooLate; + + return tooLate ? null : eowHold; } /** - * Add a garbage collection hold, if required. + * Add a garbage collection hold, if required. Return the {@link Instant} at which hold was added, + * or {@literal null} if no hold was added. * *

    The garbage collection hold gurantees that any empty final pane can be given * a timestamp which will not be considered beyond allowed lateness by any downstream * computation. If we are sure no empty final panes can be emitted then there's no need * for an additional hold. */ - private void addGarbageCollectionHold(ReduceFn.Context context) { - // Only add a garbage collection hold if we are sure we need an empty final pane and - // the window will be garbage collected after the end-of-window trigger. + @Nullable + private Instant addGarbageCollectionHold(ReduceFn.Context context) { + // Only add a garbage collection hold if we may need to emit an empty pane + // at garbage collection time, and garbage collection time is strictly after the + // end of window. (All non-empty panes will have holds at their output + // time derived from their incoming elements and no additional hold is required.) if (context.windowingStrategy().getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS && windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO)) { Instant gcHold = context.window().maxTimestamp().plus(windowingStrategy.getAllowedLateness()); @@ -301,6 +336,9 @@ private void addGarbageCollectionHold(ReduceFn.Context context) { Preconditions.checkState(inputWM == null || !gcHold.isBefore(inputWM), "Garbage collection hold %s cannot be before input watermark %s", gcHold, inputWM); context.state().access(EXTRA_HOLD_TAG).add(gcHold); + return gcHold; + } else { + return null; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index ced9de5413..ddc33b8e3f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -114,7 +114,8 @@ public void testOnElementBufferingDiscarding() throws Exception { // Test basic execution of a trigger using a non-combining window set and discarding mode. ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); // Pane of {1, 2} injectElement(tester, 1); @@ -143,7 +144,8 @@ public void testOnElementBufferingAccumulating() throws Exception { // Test basic execution of a trigger using a non-combining window set and accumulating mode. ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100)); + AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); injectElement(tester, 1); @@ -230,7 +232,8 @@ public void testWatermarkHoldAndLateData() throws Exception { // Test handling of late data. Specifically, ensure the watermark hold is correct. ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(10)); + AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(10), + ClosingBehavior.FIRE_IF_NON_EMPTY); // Input watermark -> null assertEquals(null, tester.getWatermarkHold()); @@ -343,11 +346,51 @@ public void testWatermarkHoldAndLateData() throws Exception { tester.assertHasOnlyGlobalAndFinishedSetsFor(); } + @Test + public void dontSetHoldIfTooLateForEndOfWindowTimer() throws Exception { + // Make sure holds are only set if they are accompanied by an end-of-window timer. + ReduceFnTester, IntervalWindow> tester = + ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, + AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(10), + ClosingBehavior.FIRE_ALWAYS); + tester.setAutoAdvanceOutputWatermark(false); + + // Case: Unobservably late + tester.advanceInputWatermark(new Instant(15)); + tester.advanceOutputWatermark(new Instant(11)); + injectElement(tester, 14); + // Hold was applied, waiting for end-of-window timer. + assertEquals(new Instant(14), tester.getWatermarkHold()); + assertEquals(new Instant(19), tester.getNextTimer(TimeDomain.EVENT_TIME)); + + // Trigger the end-of-window timer. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + tester.advanceInputWatermark(new Instant(20)); + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); + // Hold has been replaced with garbage collection hold. Waiting for garbage collection. + assertEquals(new Instant(29), tester.getWatermarkHold()); + assertEquals(new Instant(29), tester.getNextTimer(TimeDomain.EVENT_TIME)); + + // Case: Maybe late 1 + injectElement(tester, 13); + // No change to hold or timers. + assertEquals(new Instant(29), tester.getWatermarkHold()); + assertEquals(new Instant(29), tester.getNextTimer(TimeDomain.EVENT_TIME)); + + // Trigger the garbage collection timer. + tester.advanceInputWatermark(new Instant(30)); + + // Everything should be cleaned up. + assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); + tester.assertHasOnlyGlobalAndFinishedSetsFor(); + } + @Test public void testPaneInfoAllStates() throws Exception { ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); tester.advanceInputWatermark(new Instant(0)); when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); @@ -515,7 +558,8 @@ public void testPaneInfoFinalAndOnTime() throws Exception { public void testPaneInfoSkipToFinish() throws Exception { ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); tester.advanceInputWatermark(new Instant(0)); when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); @@ -529,7 +573,8 @@ public void testPaneInfoSkipToFinish() throws Exception { public void testPaneInfoSkipToNonSpeculativeAndFinish() throws Exception { ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); tester.advanceInputWatermark(new Instant(15)); when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); @@ -545,7 +590,8 @@ public void testMergeBeforeFinalizing() throws Exception { // unmerged windows. ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(0)); + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(0), + ClosingBehavior.FIRE_IF_NON_EMPTY); // All on time data, verify watermark hold. // These two windows should pre-merge immediately to [1, 20) @@ -611,7 +657,8 @@ public void testIdempotentEmptyPanesDiscarding() throws Exception { // modify PaneInfo. ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100)); + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); // Inject a couple of on-time elements and fire at the window end. injectElement(tester, 1); @@ -655,7 +702,8 @@ public void testIdempotentEmptyPanesAccumulating() throws Exception { // modify PaneInfo. ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100)); + AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); // Inject a couple of on-time elements and fire at the window end. injectElement(tester, 1); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index ccc07b3c7a..0cfb40adc7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -35,6 +35,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.transforms.windowing.TriggerBuilder; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; @@ -99,6 +100,14 @@ public class ReduceFnTester { private final WindowingStrategy objectStrategy; private final ReduceFn reduceFn; + /** + * If true, the output watermark is automatically advanced to the latest possible + * point when the input watermark is advanced. This is the default for most tests. + * If false, the output watermark must be explicitly advanced by the test, which can + * be used to exercise some of the more subtle behavior of WatermarkHold. + */ + private boolean autoAdvanceOutputWatermark; + private ExecutableTrigger executableTrigger; private final InMemoryLongSumAggregator droppedDueToClosedWindow = @@ -114,12 +123,13 @@ public class ReduceFnTester { public static ReduceFnTester, W> nonCombining(WindowFn windowFn, TriggerBuilder trigger, AccumulationMode mode, - Duration allowedDataLateness) throws Exception { + Duration allowedDataLateness, ClosingBehavior closingBehavior) throws Exception { WindowingStrategy strategy = WindowingStrategy.of(windowFn) .withTrigger(trigger.buildTrigger()) .withMode(mode) - .withAllowedLateness(allowedDataLateness); + .withAllowedLateness(allowedDataLateness) + .withClosingBehavior(closingBehavior); return nonCombining(strategy); } @@ -163,9 +173,19 @@ private ReduceFnTester(WindowingStrategy wildcardStrategy, this.windowFn = objectStrategy.getWindowFn(); this.windowingInternals = new TestWindowingInternals(); this.outputCoder = outputCoder; + this.autoAdvanceOutputWatermark = true; executableTrigger = wildcardStrategy.getTrigger(); } + public void setAutoAdvanceOutputWatermark(boolean autoAdvanceOutputWatermark) { + this.autoAdvanceOutputWatermark = autoAdvanceOutputWatermark; + } + + @Nullable + public Instant getNextTimer(TimeDomain domain) { + return timerInternals.getNextTimer(domain); + } + ReduceFnRunner createRunner() { return new ReduceFnRunner<>( KEY, @@ -306,6 +326,14 @@ public void advanceInputWatermark(Instant newInputWatermark) throws Exception { runner.persist(); } + /** + * If {@link #autoAdvanceOutputWatermark} is {@literal false}, advance the output watermark + * to the given value. Otherwise throw. + */ + public void advanceOutputWatermark(Instant newOutputWatermark) throws Exception { + timerInternals.advanceOutputWatermark(newOutputWatermark); + } + /** Advance the processing time to the specified time, firing any timers that should fire. */ public void advanceProcessingTime(Instant newProcessingTime) throws Exception { ReduceFnRunner runner = createRunner(); @@ -539,8 +567,31 @@ private class TestTimerInternals implements TimerInternals { @Nullable private Instant synchronizedProcessingTime = null; + @Nullable + public Instant getNextTimer(TimeDomain domain) { + TimerData data = null; + switch (domain) { + case EVENT_TIME: + data = watermarkTimers.peek(); + break; + case PROCESSING_TIME: + case SYNCHRONIZED_PROCESSING_TIME: + data = processingTimers.peek(); + break; + } + Preconditions.checkNotNull(data); // cases exhaustive + return data == null ? null : data.getTimestamp(); + } + private PriorityQueue queue(TimeDomain domain) { - return TimeDomain.EVENT_TIME.equals(domain) ? watermarkTimers : processingTimers; + switch (domain) { + case EVENT_TIME: + return watermarkTimers; + case PROCESSING_TIME: + case SYNCHRONIZED_PROCESSING_TIME: + return processingTimers; + } + throw new RuntimeException(); // cases exhaustive } @Override @@ -610,10 +661,12 @@ public void advanceInputWatermark( + "so output watermark = input watermark"); hold = inputWatermarkTime; } - advanceOutputWatermark(hold); + if (autoAdvanceOutputWatermark) { + advanceOutputWatermark(hold); + } } - private void advanceOutputWatermark(Instant newOutputWatermark) { + public void advanceOutputWatermark(Instant newOutputWatermark) { Preconditions.checkNotNull(newOutputWatermark); Preconditions.checkNotNull(inputWatermarkTime); if (newOutputWatermark.isAfter(inputWatermarkTime)) { From 36732d47a5b4b328b320aa457943b22c58cb935f Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 17 Feb 2016 13:45:49 -0800 Subject: [PATCH 155/751] Add support for splitting a compressed source for uncompressed files This adds support for splitting the file if the file name does not end with one of the supported compression formats (currently gz and bz2) and the delegate source also supports splitting. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114894950 --- .../dataflow/sdk/io/CompressedSource.java | 44 +++++++++++-- .../dataflow/sdk/io/FileBasedSource.java | 6 +- .../dataflow/sdk/io/CompressedSourceTest.java | 66 ++++++++++++++++++- 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index 74ba05e475..e3dca91680 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -85,6 +85,12 @@ private static interface FileNameBasedDecompressingChannelFactory */ ReadableByteChannel createDecompressingChannel(String fileName, ReadableByteChannel channel) throws IOException; + + /** + * Given a file name, returns true if the file name matches any supported compression + * scheme. + */ + boolean isCompressed(String fileName); } /** @@ -179,6 +185,16 @@ public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channe ReadableByteChannel.class.getSimpleName(), ReadableByteChannel.class.getSimpleName())); } + + @Override + public boolean isCompressed(String fileName) { + for (CompressionMode type : CompressionMode.values()) { + if (type.matches(fileName)) { + return true; + } + } + return false; + } } private final FileBasedSource sourceDelegate; @@ -253,27 +269,43 @@ public void validate() { * source for a single file. */ @Override - public CompressedSource createForSubrangeOfFile(String fileName, long start, long end) { + protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { return new CompressedSource<>(sourceDelegate.createForSubrangeOfFile(fileName, start, end), channelFactory, fileName, Long.MAX_VALUE, start, end); } /** - * Determines whether a single file represented by this source is splittable. Returns false: - * compressed sources are not splittable. + * Determines whether a single file represented by this source is splittable. Returns true + * if we are using the default decompression factory and and it determines + * from the requested file name that the file is not compressed. */ @Override protected final boolean isSplittable() throws Exception { - return false; + if (channelFactory instanceof FileNameBasedDecompressingChannelFactory) { + FileNameBasedDecompressingChannelFactory fileNameBasedChannelFactory = + (FileNameBasedDecompressingChannelFactory) channelFactory; + return !fileNameBasedChannelFactory.isCompressed(getFileOrPatternSpec()); + } + return true; } /** - * Creates a {@code CompressedReader} to read a single file. + * Creates a {@code FileBasedReader} to read a single file. * *

    Uses the delegate source to create a single file reader for the delegate source. + * Utilizes the default decompression channel factory to not wrap the source reader + * if the file name does not represent a compressed file allowing for splitting of + * the source. */ @Override - public final CompressedReader createSingleFileReader(PipelineOptions options) { + protected final FileBasedReader createSingleFileReader(PipelineOptions options) { + if (channelFactory instanceof FileNameBasedDecompressingChannelFactory) { + FileNameBasedDecompressingChannelFactory fileNameBasedChannelFactory = + (FileNameBasedDecompressingChannelFactory) channelFactory; + if (!fileNameBasedChannelFactory.isCompressed(getFileOrPatternSpec())) { + return sourceDelegate.createSingleFileReader(options); + } + } return new CompressedReader( this, sourceDelegate.createSingleFileReader(options)); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java index a11b8cc895..5d32a9d08f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java @@ -162,14 +162,16 @@ public final FileBasedSource createSourceForSubrange(long start, long end) { * @param end ending byte offset of the new {@code FileBasedSource}. May be Long.MAX_VALUE, * in which case it will be inferred using {@link #getMaxEndOffset}. */ - public abstract FileBasedSource createForSubrangeOfFile(String fileName, long start, long end); + protected abstract FileBasedSource createForSubrangeOfFile( + String fileName, long start, long end); /** * Creates and returns an instance of a {@code FileBasedReader} implementation for the current * source assuming the source represents a single file. File patterns will be handled by * {@code FileBasedSource} implementation automatically. */ - public abstract FileBasedReader createSingleFileReader(PipelineOptions options); + protected abstract FileBasedReader createSingleFileReader( + PipelineOptions options); @Override public final long getEstimatedSizeBytes(PipelineOptions options) throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index f402e82f11..14c8fe9aca 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -16,13 +16,20 @@ package com.google.cloud.dataflow.sdk.io; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; import com.google.cloud.dataflow.sdk.io.CompressedSource.CompressionMode; import com.google.cloud.dataflow.sdk.io.CompressedSource.DecompressingChannelFactory; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.io.Files; @@ -30,8 +37,10 @@ import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; +import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; +import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; @@ -158,6 +167,43 @@ public void testHeterogeneousCompression() throws Exception { p.run(); } + @Test + public void testUncompressedFileIsSplittable() throws Exception { + String baseName = "test-input"; + + File uncompressedFile = tmpFolder.newFile(baseName + ".bin"); + Files.write(generateInput(10), uncompressedFile); + + CompressedSource source = + CompressedSource.from(new ByteSource(uncompressedFile.getPath(), 1)); + assertTrue(source.isSplittable()); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testGzipFileIsNotSplittable() throws Exception { + String baseName = "test-input"; + + File compressedFile = tmpFolder.newFile(baseName + ".gz"); + writeFile(compressedFile, generateInput(10), CompressionMode.GZIP); + + CompressedSource source = + CompressedSource.from(new ByteSource(compressedFile.getPath(), 1)); + assertFalse(source.isSplittable()); + } + + @Test + public void testBzip2FileIsNotSplittable() throws Exception { + String baseName = "test-input"; + + File compressedFile = tmpFolder.newFile(baseName + ".bz2"); + writeFile(compressedFile, generateInput(10), CompressionMode.BZIP2); + + CompressedSource source = + CompressedSource.from(new ByteSource(compressedFile.getPath(), 1)); + assertFalse(source.isSplittable()); + } + /** * Test reading an uncompressed file with {@link CompressionMode#GZIP}, since we must support * this due to properties of services that we read from. @@ -170,6 +216,22 @@ public void testFalseGzipStream() throws Exception { verifyReadContents(input, tmpFile, CompressionMode.GZIP); } + /** + * Test reading an uncompressed file with {@link CompressionMode#BZIP2}, and show that + * we fail. + */ + @Test + public void testFalseBzip2Stream() throws Exception { + byte[] input = generateInput(1000); + File tmpFile = tmpFolder.newFile("test.bz2"); + Files.write(input, tmpFile); + thrown.expectCause(Matchers.allOf( + instanceOf(IOException.class), + ThrowableMessageMatcher.hasMessage( + containsString("Stream is not in the BZip2 format")))); + verifyReadContents(input, tmpFile, CompressionMode.BZIP2); + } + /** * Test reading an empty input file with gzip; it must be interpreted as uncompressed because * the gzip header is two bytes. @@ -304,12 +366,12 @@ public ByteSource(String fileName, long minBundleSize, long startOffset, long en } @Override - public FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { + protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { return new ByteSource(fileName, getMinBundleSize(), start, end); } @Override - public ByteReader createSingleFileReader(PipelineOptions options) { + protected FileBasedReader createSingleFileReader(PipelineOptions options) { return new ByteReader(this); } From 059ca33b812e8bcc65c72d9fdbb24e86ea923943 Mon Sep 17 00:00:00 2001 From: davor Date: Wed, 17 Feb 2016 13:46:54 -0800 Subject: [PATCH 156/751] Add --worker_harness_container_image PipelineOption ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114895058 --- .../DataflowPipelineWorkerPoolOptions.java | 29 +++++++++++++++++++ .../sdk/runners/DataflowPipelineRunner.java | 21 +++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java index 633b2707b4..25d15890c7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.options; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -103,6 +104,34 @@ public String getAlgorithm() { int getDiskSizeGb(); void setDiskSizeGb(int value); + /** + * Docker container image that executes Dataflow worker harness, residing in Google Container + * Registry. + */ + @Default.InstanceFactory(WorkerHarnessContainerImageFactory.class) + @Description("Docker container image that executes Dataflow worker harness, residing in Google " + + " Container Registry.") + @Hidden + String getWorkerHarnessContainerImage(); + void setWorkerHarnessContainerImage(String value); + + /** + * Returns the default Docker container image that executes Dataflow worker harness, residing in + * Google Container Registry. + */ + public static class WorkerHarnessContainerImageFactory + implements DefaultValueFactory { + @Override + public String create(PipelineOptions options) { + DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); + if (dataflowOptions.isStreaming()) { + return DataflowPipelineRunner.STREAMING_WORKER_HARNESS_CONTAINER_IMAGE; + } else { + return DataflowPipelineRunner.BATCH_WORKER_HARNESS_CONTAINER_IMAGE; + } + } + } + /** * GCE network for launching * workers. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 126eb558c9..f20caa3b96 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -27,6 +27,7 @@ import com.google.api.services.dataflow.model.DataflowPackage; import com.google.api.services.dataflow.model.Job; import com.google.api.services.dataflow.model.ListJobsResponse; +import com.google.api.services.dataflow.model.WorkerPool; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; import com.google.cloud.dataflow.sdk.PipelineResult.State; @@ -54,6 +55,7 @@ import com.google.cloud.dataflow.sdk.io.Write; import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; import com.google.cloud.dataflow.sdk.options.StreamingOptions; @@ -193,9 +195,17 @@ public class DataflowPipelineRunner extends PipelineRunner /** A set of user defined functions to invoke at different points in execution. */ private DataflowPipelineRunnerHooks hooks; - // Environment version information + // Environment version information. private static final String ENVIRONMENT_MAJOR_VERSION = "4"; + // Default Docker container images that execute Dataflow worker harness, residing in Google + // Container Registry, separately for Batch and Streaming. + // TODO: Set these once versioned containers are ready. + public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE = null; + //"dataflow.gcr.io/v1beta3/java-batch:20160201-rc00---INVALID"; + public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE = null; + //"dataflow.gcr.io/v1beta3/java-streaming:20160201-rc00---INVALID"; + // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; @@ -440,6 +450,15 @@ public DataflowPipelineJob run(Pipeline pipeline) { newJob.getEnvironment().setDataset(options.getTempDatasetId()); newJob.getEnvironment().setExperiments(options.getExperiments()); + // Set the Docker container image that executes Dataflow worker harness, residing in Google + // Container Registry. Translator is guaranteed to create a worker pool prior to this point. + String workerHarnessContainerImage = + options.as(DataflowPipelineWorkerPoolOptions.class) + .getWorkerHarnessContainerImage(); + for (WorkerPool workerPool : newJob.getEnvironment().getWorkerPools()) { + workerPool.setWorkerHarnessContainerImage(workerHarnessContainerImage); + } + // Requirements about the service. Map environmentVersion = new HashMap<>(); environmentVersion.put(PropertyNames.ENVIRONMENT_VERSION_MAJOR_KEY, ENVIRONMENT_MAJOR_VERSION); From b31d7c6abbf9db4b09191a78f3ca0cb1ca5698e5 Mon Sep 17 00:00:00 2001 From: klk Date: Wed, 17 Feb 2016 13:52:22 -0800 Subject: [PATCH 157/751] Use new keyed state API to remove ReduceFn.Factory ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114895604 --- .../GroupAlsoByWindowViaWindowSetDoFn.java | 20 +++--- ...GroupAlsoByWindowsViaOutputBufferDoFn.java | 27 ++++--- .../dataflow/sdk/util/SystemReduceFn.java | 71 +++++++------------ .../dataflow/sdk/util/state/StateTags.java | 2 +- .../dataflow/sdk/util/ReduceFnTester.java | 5 +- 5 files changed, 51 insertions(+), 74 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java index 0e1c8d8e6b..46b2e5eeb8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java @@ -36,8 +36,8 @@ public class GroupAlsoByWindowViaWindowSetDoFn< public static > DoFn> create( - WindowingStrategy strategy, SystemReduceFn.Factory factory) { - return new GroupAlsoByWindowViaWindowSetDoFn<>(strategy, factory); + WindowingStrategy strategy, SystemReduceFn reduceFn) { + return new GroupAlsoByWindowViaWindowSetDoFn<>(strategy, reduceFn); } protected final Aggregator droppedDueToClosedWindow = @@ -47,15 +47,15 @@ DoFn> create( createAggregator(GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); private final WindowingStrategy windowingStrategy; - private SystemReduceFn.Factory reduceFnFactory; + private SystemReduceFn reduceFn; private GroupAlsoByWindowViaWindowSetDoFn( WindowingStrategy windowingStrategy, - SystemReduceFn.Factory reduceFnFactory) { + SystemReduceFn reduceFn) { @SuppressWarnings("unchecked") WindowingStrategy noWildcard = (WindowingStrategy) windowingStrategy; this.windowingStrategy = noWildcard; - this.reduceFnFactory = reduceFnFactory; + this.reduceFn = reduceFn; } @Override @@ -70,7 +70,7 @@ public void processElement(ProcessContext c) throws Exception { @SuppressWarnings("unchecked") StateInternals stateInternals = (StateInternals) c.windowingInternals().stateInternals(); - ReduceFnRunner runner = + ReduceFnRunner reduceFnRunner = new ReduceFnRunner<>( key, windowingStrategy, @@ -78,13 +78,13 @@ public void processElement(ProcessContext c) throws Exception { timerInternals, c.windowingInternals(), droppedDueToClosedWindow, - reduceFnFactory.create(key)); + reduceFn); for (TimerData timer : element.timersIterable()) { - runner.onTimer(timer); + reduceFnRunner.onTimer(timer); } - runner.processElements(element.elementsIterable()); - runner.persist(); + reduceFnRunner.processElements(element.elementsIterable()); + reduceFnRunner.persist(); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java index 6cd9381561..1d1afe38d8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java @@ -35,20 +35,19 @@ public class GroupAlsoByWindowsViaOutputBufferDoFn { private final WindowingStrategy strategy; - private SystemReduceFn.Factory reduceFnFactory; + private SystemReduceFn reduceFn; public GroupAlsoByWindowsViaOutputBufferDoFn( WindowingStrategy windowingStrategy, - SystemReduceFn.Factory reduceFnFactory) { + SystemReduceFn reduceFn) { this.strategy = windowingStrategy; - this.reduceFnFactory = reduceFnFactory; + this.reduceFn = reduceFn; } @Override public void processElement( - DoFn>>, - KV>.ProcessContext c) - throws Exception { + DoFn>>, KV>.ProcessContext c) + throws Exception { K key = c.element().getKey(); // Used with Batch, we know that all the data is available for this key. We can't use the // timer manager from the context because it doesn't exist. So we create one and emulate the @@ -60,7 +59,7 @@ public void processElement( @SuppressWarnings("unchecked") StateInternals stateInternals = (StateInternals) c.windowingInternals().stateInternals(); - ReduceFnRunner runner = + ReduceFnRunner reduceFnRunner = new ReduceFnRunner( key, strategy, @@ -68,31 +67,31 @@ public void processElement( timerInternals, c.windowingInternals(), droppedDueToClosedWindow, - reduceFnFactory.create(key)); + reduceFn); Iterable>> chunks = Iterables.partition(c.element().getValue(), 1000); for (Iterable> chunk : chunks) { // Process the chunk of elements. - runner.processElements(chunk); + reduceFnRunner.processElements(chunk); // Then, since elements are sorted by their timestamp, advance the input watermark // to the first element, and fire any timers that may have been scheduled. - timerInternals.advanceInputWatermark(runner, chunk.iterator().next().getTimestamp()); + timerInternals.advanceInputWatermark(reduceFnRunner, chunk.iterator().next().getTimestamp()); // Fire any processing timers that need to fire - timerInternals.advanceProcessingTime(runner, Instant.now()); + timerInternals.advanceProcessingTime(reduceFnRunner, Instant.now()); // Leave the output watermark undefined. Since there's no late data in batch mode // there's really no need to track it as we do for streaming. } // Finish any pending windows by advancing the input watermark to infinity. - timerInternals.advanceInputWatermark(runner, BoundedWindow.TIMESTAMP_MAX_VALUE); + timerInternals.advanceInputWatermark(reduceFnRunner, BoundedWindow.TIMESTAMP_MAX_VALUE); // Finally, advance the processing time to infinity to fire any timers. - timerInternals.advanceProcessingTime(runner, BoundedWindow.TIMESTAMP_MAX_VALUE); + timerInternals.advanceProcessingTime(reduceFnRunner, BoundedWindow.TIMESTAMP_MAX_VALUE); - runner.persist(); + reduceFnRunner.persist(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java index 6068f913db..044847570f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; @@ -32,8 +33,6 @@ import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; -import java.io.Serializable; - /** * {@link ReduceFn} implementing the default reduction behaviors of {@link GroupByKey}. * @@ -46,40 +45,23 @@ public abstract class SystemReduceFn { private static final String BUFFER_NAME = "buf"; - /** - * Factory that produces {@link SystemReduceFn} instances for specific keys. - * - * @param The type of key being processed. - * @param The type of values associated with the key. - * @param The output type that will be produced for each key. - * @param The type of windows this operates on. - */ - public interface Factory extends Serializable { - ReduceFn create(K key); - } - /** * Create a factory that produces {@link SystemReduceFn} instances that that buffer all of the * input values in persistent state and produces an {@code Iterable}. */ - public static Factory, W> buffering( - final Coder inputCoder) { + public static SystemReduceFn, Iterable, W> + buffering(final Coder inputCoder) { final StateTag> bufferTag = StateTags.makeSystemTagInternal(StateTags.bag(BUFFER_NAME, inputCoder)); - return new Factory, W>() { + return new SystemReduceFn, Iterable, W>(bufferTag) { @Override - public ReduceFn, W> create(K key) { - return new SystemReduceFn, Iterable, W>(bufferTag) { - @Override - public void prefetchOnMerge(MergingStateContext state) throws Exception { - StateMerging.prefetchBags(state, bufferTag); - } + public void prefetchOnMerge(MergingStateContext state) throws Exception { + StateMerging.prefetchBags(state, bufferTag); + } - @Override - public void onMerge(OnMergeContext c) throws Exception { - StateMerging.mergeBags(c.state(), bufferTag); - } - }; + @Override + public void onMerge(OnMergeContext c) throws Exception { + StateMerging.mergeBags(c.state(), bufferTag); } }; } @@ -88,38 +70,35 @@ public void onMerge(OnMergeContext c) throws Exception { * Create a factory that produces {@link SystemReduceFn} instances that combine all of the input * values using a {@link CombineFn}. */ - public static Factory + public static SystemReduceFn combining( final Coder keyCoder, final AppliedCombineFn combineFn) { checkArgument( !(combineFn.getFn() instanceof RequiresContextInternal), "Combiner lifting is not supported for combine functions with contexts: %s", combineFn.getFn().getClass().getName()); - return new Factory() { - @Override - public ReduceFn create(K key) { - final StateTag> bufferTag = - StateTags.makeSystemTagInternal(StateTags.combiningValue( + final StateTag> bufferTag = + StateTags.makeSystemTagInternal( + StateTags.keyedCombiningValue( BUFFER_NAME, combineFn.getAccumulatorCoder(), - (CombineFn) combineFn.getFn().forKey(key, keyCoder))); - return new SystemReduceFn(bufferTag) { - @Override - public void prefetchOnMerge(MergingStateContext state) throws Exception { - StateMerging.prefetchCombiningValues(state, bufferTag); - } + (KeyedCombineFn) combineFn.getFn())); + return new SystemReduceFn(bufferTag) { + @Override + public void prefetchOnMerge(MergingStateContext state) throws Exception { + StateMerging.prefetchCombiningValues(state, bufferTag); + } - @Override - public void onMerge(OnMergeContext c) throws Exception { - StateMerging.mergeCombiningValues(c.state(), bufferTag); - } - }; + @Override + public void onMerge(OnMergeContext c) throws Exception { + StateMerging.mergeCombiningValues(c.state(), bufferTag); } }; } private StateTag> bufferTag; - public SystemReduceFn( + private SystemReduceFn( StateTag> bufferTag) { this.bufferTag = bufferTag; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index caa1ab643f..510cd79d61 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -162,7 +162,7 @@ public static StateTag makeSystemTagInterna public static StateTag> convertToBagTagInternal( StateTag> combiningTag) { - if (!(combiningTag instanceof CombiningValueStateTag)) { + if (!(combiningTag instanceof KeyedCombiningValueStateTag)) { throw new IllegalArgumentException("Unexpected StateTag " + combiningTag); } // Checked above; conversion to a bag tag depends on the provided tag being one of those diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index 0cfb40adc7..a91675cd89 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -117,7 +117,7 @@ public class ReduceFnTester { nonCombining(WindowingStrategy windowingStrategy) throws Exception { return new ReduceFnTester, W>( windowingStrategy, - SystemReduceFn.buffering(VarIntCoder.of()).create(KEY), + SystemReduceFn.buffering(VarIntCoder.of()), IterableCoder.of(VarIntCoder.of())); } @@ -146,8 +146,7 @@ public class ReduceFnTester { return new ReduceFnTester( strategy, - SystemReduceFn.combining(StringUtf8Coder.of(), fn) - .create(KEY), + SystemReduceFn.combining(StringUtf8Coder.of(), fn), outputCoder); } From cc0db49c24165e42f0d4f00919c1322b1f7b5248 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 17 Feb 2016 14:03:29 -0800 Subject: [PATCH 158/751] Implement CopyOnAccessInMemoryStateInternals This is a view of State Internals that does not write changes back to the StateInternals it reads from as underlying storage. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114896853 --- .../CopyOnAccessInMemoryStateInternals.java | 327 +++++++++++++++++ .../util/state/InMemoryStateInternals.java | 146 +++++--- .../dataflow/sdk/util/state/StateTable.java | 5 + ...opyOnAccessInMemoryStateInternalsTest.java | 343 ++++++++++++++++++ 4 files changed, 774 insertions(+), 47 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java new file mode 100644 index 0000000000..29ce6519cb --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java @@ -0,0 +1,327 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.state; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; +import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals.InMemoryState; +import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; +import com.google.common.base.Optional; + +import javax.annotation.Nullable; + +/** + * {@link StateInternals} built on top of an underlying {@link StateTable} that contains instances + * of {@link InMemoryState}. Whenever state that exists in the underlying {@link StateTable} is + * accessed, an independent copy will be created within this table. + */ +public class CopyOnAccessInMemoryStateInternals implements StateInternals { + private final K key; + private final CopyOnAccessInMemoryStateTable table; + + /** + * Creates a new {@link CopyOnAccessInMemoryStateInternals} with the underlying (possibly null) + * StateInternals. + */ + public static CopyOnAccessInMemoryStateInternals withUnderlying(K key, +@Nullable CopyOnAccessInMemoryStateInternals underlying) { + return new CopyOnAccessInMemoryStateInternals(key, underlying); + } + + private CopyOnAccessInMemoryStateInternals( + K key, CopyOnAccessInMemoryStateInternals underlying) { + this.key = key; + table = new CopyOnAccessInMemoryStateTable<>(key, underlying == null ? null : underlying.table); + } + + /** + * Ensures this {@link CopyOnAccessInMemoryStateInternals} is complete. Other copies of state for + * the same Step and Key may be discarded after invoking this method. + * + *

    For each {@link StateNamespace}, for each {@link StateTag address} in that namespace that + * has not been bound in this {@link CopyOnAccessInMemoryStateInternals}, put a reference to that + * state within this {@link StateInternals}. + * + * @return this table + */ + public CopyOnAccessInMemoryStateInternals commit() { + table.commit(); + return this; + } + + @Override + public T state(StateNamespace namespace, StateTag address) { + return table.get(namespace, address); + } + + @Override + public K getKey() { + return key; + } + + /** + * A {@link StateTable} that, when a value is retrieved with + * {@link StateTable#get(StateNamespace, StateTag)}, first attempts to obtain a copy of existing + * {@link State} from an underlying {@link StateTable}. + */ + private static class CopyOnAccessInMemoryStateTable extends StateTable { + private final K key; + private Optional> underlying; + + /** + * The StateBinderFactory currently in use by this {@link CopyOnAccessInMemoryStateTable}. + * + *

    There are three {@link StateBinderFactory} implementations used by the {@link + * CopyOnAccessInMemoryStateTable}. + *

      + *
    • The default {@link StateBinderFactory} is a {@link CopyOnBindBinderFactory}, allowing + * the table to copy any existing {@link State} values to this {@link StateTable} from the + * underlying table when accessed, at which point mutations will not be visible to the + * underlying table - effectively a "Copy by Value" binder.
    • + *
    • During the execution of the {@link #commit()} method, this is a + * {@link ReadThroughBinderFactory}, which copies the references to the existing + * {@link State} objects to this {@link StateTable}.
    • + *
    • After the execution of the {@link #commit()} method, this is an instance of + * {@link InMemoryStateBinderFactory}, which constructs new instances of state when a + * {@link StateTag} is bound.
    • + *
    + */ + private StateBinderFactory binderFactory; + + public CopyOnAccessInMemoryStateTable(K key, StateTable underlying) { + this.key = key; + this.underlying = Optional.fromNullable(underlying); + binderFactory = new CopyOnBindBinderFactory<>(key, this.underlying); + } + + /** + * Copies all values in the underlying table to this table, then discards the underlying table. + * + *

    If there is an underlying table, this replaces the existing + * {@link CopyOnBindBinderFactory} with a {@link ReadThroughBinderFactory}, then reads all of + * the values in the existing table, binding the state values to this table. The old StateTable + * should be discarded after the call to {@link #commit()}. + * + *

    After copying all of the existing values, replace the binder factory with an instance of + * {@link InMemoryStateBinderFactory} to construct new values, since all existing values + * are bound in this {@link StateTable table} and this table represents the canonical state. + */ + private void commit() { + if (underlying.isPresent()) { + ReadThroughBinderFactory readThroughBinder = + new ReadThroughBinderFactory<>(underlying.get()); + binderFactory = readThroughBinder; + readThroughBinder.readThrough(this); + } + binderFactory = new InMemoryStateBinderFactory<>(key); + underlying = Optional.absent(); + } + + @Override + protected StateBinder binderForNamespace(final StateNamespace namespace) { + StateBinder stateBinder = binderFactory.forNamespace(namespace); + return stateBinder; + } + + private static interface StateBinderFactory { + StateBinder forNamespace(StateNamespace namespace); + } + + /** + * {@link StateBinderFactory} that creates a copy of any existing state when the state is bound. + */ + private static class CopyOnBindBinderFactory implements StateBinderFactory { + private final K key; + private final Optional> underlying; + + public CopyOnBindBinderFactory(K key, Optional> underlying) { + this.key = key; + this.underlying = underlying; + } + + private boolean containedInUnderlying(StateNamespace namespace, StateTag tag) { + return underlying.isPresent() && underlying.get().isNamespaceInUse(namespace) + && underlying.get().getTagsInUse(namespace).containsKey(tag); + } + + @Override + public StateBinder forNamespace(final StateNamespace namespace) { + return new StateBinder() { + @Override + public WatermarkStateInternal bindWatermark( + StateTag> address, + OutputTimeFn outputTimeFn) { + if (containedInUnderlying(namespace, address)) { + @SuppressWarnings("unchecked") + InMemoryState> existingState = + (InMemoryStateInternals.InMemoryState>) + underlying.get().get(namespace, address); + return existingState.copy(); + } else { + return new InMemoryStateInternals.WatermarkStateInternalImplementation<>( + outputTimeFn); + } + } + + @Override + public ValueState bindValue( + StateTag> address, Coder coder) { + if (containedInUnderlying(namespace, address)) { + @SuppressWarnings("unchecked") + InMemoryState> existingState = + (InMemoryStateInternals.InMemoryState>) + underlying.get().get(namespace, address); + return existingState.copy(); + } else { + return new InMemoryStateInternals.InMemoryValue<>(); + } + } + + @Override + public CombiningValueStateInternal + bindCombiningValue( + StateTag> address, + Coder accumCoder, CombineFn combineFn) { + if (containedInUnderlying(namespace, address)) { + @SuppressWarnings("unchecked") + InMemoryState> + existingState = ( + InMemoryStateInternals + .InMemoryState>) underlying.get().get(namespace, address); + return existingState.copy(); + } else { + return new InMemoryStateInternals.InMemoryCombiningValue<>( + key, combineFn.asKeyedFn()); + } + } + + @Override + public BagState bindBag( + StateTag> address, Coder elemCoder) { + if (containedInUnderlying(namespace, address)) { + @SuppressWarnings("unchecked") + InMemoryState> existingState = + (InMemoryStateInternals.InMemoryState>) + underlying.get().get(namespace, address); + return existingState.copy(); + } else { + return new InMemoryStateInternals.InMemoryBag<>(); + } + } + + @Override + public CombiningValueStateInternal + bindKeyedCombiningValue( + StateTag> address, + Coder accumCoder, + KeyedCombineFn combineFn) { + if (containedInUnderlying(namespace, address)) { + @SuppressWarnings("unchecked") + InMemoryState> + existingState = ( + InMemoryStateInternals + .InMemoryState>) underlying.get().get(namespace, address); + return existingState.copy(); + } else { + return new InMemoryStateInternals.InMemoryCombiningValue<>(key, combineFn); + } + } + }; + } + } + + /** + * {@link StateBinderFactory} that reads directly from the underlying table. Used during calls + * to {@link CopyOnAccessInMemoryStateTable#commit()} to read all values from the underlying + * table. + */ + private static class ReadThroughBinderFactory implements StateBinderFactory { + private final StateTable underlying; + + public ReadThroughBinderFactory(StateTable underlying) { + this.underlying = underlying; + } + + public void readThrough(StateTable readTo) { + for (StateNamespace namespace : underlying.getNamespacesInUse()) { + for (StateTag address : underlying.getTagsInUse(namespace).keySet()) { + readTo.get(namespace, address); + } + } + } + + @Override + public StateBinder forNamespace(final StateNamespace namespace) { + return new StateBinder() { + @Override + public WatermarkStateInternal bindWatermark( + StateTag> address, + OutputTimeFn outputTimeFn) { + return underlying.get(namespace, address); + } + + @Override + public ValueState bindValue( + StateTag> address, Coder coder) { + return underlying.get(namespace, address); + } + + @Override + public CombiningValueStateInternal + bindCombiningValue( + StateTag> address, + Coder accumCoder, CombineFn combineFn) { + return underlying.get(namespace, address); + } + + @Override + public BagState bindBag( + StateTag> address, Coder elemCoder) { + return underlying.get(namespace, address); + } + + @Override + public CombiningValueStateInternal + bindKeyedCombiningValue( + StateTag> address, + Coder accumCoder, + KeyedCombineFn combineFn) { + return underlying.get(namespace, address); + } + }; + } + } + + private static class InMemoryStateBinderFactory implements StateBinderFactory { + private final InMemoryStateInternals.InMemoryStateBinder inMemoryStateBinder; + + public InMemoryStateBinderFactory(K key) { + inMemoryStateBinder = new InMemoryStateInternals.InMemoryStateBinder<>(key); + } + + @Override + public StateBinder forNamespace(StateNamespace namespace) { + return inMemoryStateBinder; + } + } + } + +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 7f42f6bcfc..6b98101c23 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -55,51 +55,15 @@ public K getKey() { return key; } - private interface InMemoryState { + interface InMemoryState> { boolean isEmptyForTesting(); + T copy(); } protected final StateTable inMemoryState = new StateTable() { @Override protected StateBinder binderForNamespace(final StateNamespace namespace) { - return new StateBinder() { - @Override - public ValueState bindValue( - StateTag> address, Coder coder) { - return new InMemoryValue(); - } - - @Override - public BagState bindBag( - final StateTag> address, Coder elemCoder) { - return new InMemoryBag(); - } - - @Override - public CombiningValueStateInternal - bindCombiningValue( - StateTag> - address, Coder accumCoder, - final CombineFn combineFn) { - return new InMemoryCombiningValue(combineFn.asKeyedFn()); - } - - @Override - public WatermarkStateInternal bindWatermark( - StateTag> address, - OutputTimeFn outputTimeFn) { - return new WatermarkStateInternalImplementation(outputTimeFn); - } - - @Override - public CombiningValueStateInternal - bindKeyedCombiningValue( - StateTag> - address, Coder accumCoder, - KeyedCombineFn combineFn) { - return new InMemoryCombiningValue(combineFn); - } - }; + return new InMemoryStateBinder(key); } }; @@ -112,7 +76,7 @@ public void clear() { * that the state has been properly cleaned up. */ protected boolean isEmptyForTesting(State state) { - return ((InMemoryState) state).isEmptyForTesting(); + return ((InMemoryState) state).isEmptyForTesting(); } @Override @@ -120,7 +84,55 @@ public T state(StateNamespace namespace, StateTag implements ValueState, InMemoryState { + /** + * A {@link StateBinder} that returns In Memory {@link State} objects. + */ + static class InMemoryStateBinder implements StateBinder { + private final K key; + + InMemoryStateBinder(K key) { + this.key = key; + } + + @Override + public ValueState bindValue( + StateTag> address, Coder coder) { + return new InMemoryValue(); + } + + @Override + public BagState bindBag( + final StateTag> address, Coder elemCoder) { + return new InMemoryBag(); + } + + @Override + public CombiningValueStateInternal + bindCombiningValue( + StateTag> + address, Coder accumCoder, + final CombineFn combineFn) { + return new InMemoryCombiningValue(key, combineFn.asKeyedFn()); + } + + @Override + public WatermarkStateInternal bindWatermark( + StateTag> address, + OutputTimeFn outputTimeFn) { + return new WatermarkStateInternalImplementation(outputTimeFn); + } + + @Override + public CombiningValueStateInternal + bindKeyedCombiningValue( + StateTag> + address, Coder accumCoder, + KeyedCombineFn combineFn) { + return new InMemoryCombiningValue(key, combineFn); + } + } + + static final class InMemoryValue implements ValueState, InMemoryState> { private boolean isCleared = true; private T value = null; @@ -148,14 +160,24 @@ public void set(T input) { this.value = input; } + @Override + public InMemoryValue copy() { + InMemoryValue that = new InMemoryValue<>(); + if (!this.isCleared) { + that.isCleared = this.isCleared; + that.value = this.value; + } + return that; + } + @Override public boolean isEmptyForTesting() { return isCleared; } } - private final class WatermarkStateInternalImplementation - implements WatermarkStateInternal, InMemoryState { + static final class WatermarkStateInternalImplementation + implements WatermarkStateInternal, InMemoryState> { private final OutputTimeFn outputTimeFn; @@ -213,15 +235,27 @@ public OutputTimeFn getOutputTimeFn() { public String toString() { return Objects.toString(combinedHold); } + + @Override + public WatermarkStateInternalImplementation copy() { + WatermarkStateInternalImplementation that = + new WatermarkStateInternalImplementation<>(outputTimeFn); + that.combinedHold = this.combinedHold; + return that; + } } - private final class InMemoryCombiningValue - implements CombiningValueStateInternal, InMemoryState { + static final class InMemoryCombiningValue + implements CombiningValueStateInternal, + InMemoryState> { + private final K key; private boolean isCleared = true; private final KeyedCombineFn combineFn; private AccumT accum; - private InMemoryCombiningValue(KeyedCombineFn combineFn) { + InMemoryCombiningValue( + K key, KeyedCombineFn combineFn) { + this.key = key; this.combineFn = combineFn; accum = combineFn.createAccumulator(key); } @@ -285,9 +319,20 @@ public AccumT mergeAccumulators(Iterable accumulators) { public boolean isEmptyForTesting() { return isCleared; } + + @Override + public InMemoryCombiningValue copy() { + InMemoryCombiningValue that = + new InMemoryCombiningValue<>(key, combineFn); + if (!this.isCleared) { + that.isCleared = this.isCleared; + that.addAccum(accum); + } + return that; + } } - private static final class InMemoryBag implements BagState, InMemoryState { + static final class InMemoryBag implements BagState, InMemoryState> { private List contents = new ArrayList<>(); @Override @@ -331,5 +376,12 @@ public Boolean read() { } }; } + + @Override + public InMemoryBag copy() { + InMemoryBag that = new InMemoryBag<>(); + that.contents.addAll(this.contents); + return that; + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java index 5529b9fb64..0f1209ac78 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java @@ -38,6 +38,11 @@ public abstract class StateTable { } }); + /** + * Gets the {@link State} in the specified {@link StateNamespace} with the specified {@link + * StateTag}, binding it using the {@link #binderForNamespace(StateNamespace)} if it is not + * already present in this {@link StateTable}. + */ public StateT get( StateNamespace namespace, StateTag tag) { State storage = stateTable.get(namespace, tag); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java new file mode 100644 index 0000000000..03c40140e3 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java @@ -0,0 +1,343 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.state; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.theInstance; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; +import com.google.cloud.dataflow.sdk.coders.CoderRegistry; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; + +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link CopyOnAccessInMemoryStateInternals}. + */ +@RunWith(JUnit4.class) +public class CopyOnAccessInMemoryStateInternalsTest { + private String key = "foo"; + @Test + public void testGetWithEmpty() { + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = internals.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + assertThat(stringBag.get().read(), containsInAnyOrder("baz", "bar")); + + BagState reReadStringBag = internals.state(namespace, bagTag); + assertThat(reReadStringBag.get().read(), containsInAnyOrder("baz", "bar")); + } + + @Test + public void testGetWithAbsentInUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = internals.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + assertThat(stringBag.get().read(), containsInAnyOrder("baz", "bar")); + + BagState reReadVoidBag = internals.state(namespace, bagTag); + assertThat(reReadVoidBag.get().read(), containsInAnyOrder("baz", "bar")); + + BagState underlyingState = underlying.state(namespace, bagTag); + assertThat(underlyingState.get().read(), emptyIterable()); + } + + /** + * Tests that retrieving state with an underlying StateInternals with an existing value returns + * a value that initially has equal value to the provided state but can be modified without + * modifying the existing state. + */ + @Test + public void testGetWithPresentInUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> valueTag = StateTags.value("foo", StringUtf8Coder.of()); + ValueState underlyingValue = underlying.state(namespace, valueTag); + assertThat(underlyingValue.get().read(), nullValue(String.class)); + + underlyingValue.set("bar"); + assertThat(underlyingValue.get().read(), equalTo("bar")); + + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + ValueState copyOnAccessState = internals.state(namespace, valueTag); + assertThat(copyOnAccessState.get().read(), equalTo("bar")); + + copyOnAccessState.set("baz"); + assertThat(copyOnAccessState.get().read(), equalTo("baz")); + assertThat(underlyingValue.get().read(), equalTo("bar")); + + ValueState reReadUnderlyingValue = underlying.state(namespace, valueTag); + assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + } + + @Test + public void testBagStateWithUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> valueTag = StateTags.bag("foo", VarIntCoder.of()); + BagState underlyingValue = underlying.state(namespace, valueTag); + assertThat(underlyingValue.get().read(), emptyIterable()); + + underlyingValue.add(1); + assertThat(underlyingValue.get().read(), containsInAnyOrder(1)); + + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + BagState copyOnAccessState = internals.state(namespace, valueTag); + assertThat(copyOnAccessState.get().read(), containsInAnyOrder(1)); + + copyOnAccessState.add(4); + assertThat(copyOnAccessState.get().read(), containsInAnyOrder(4, 1)); + assertThat(underlyingValue.get().read(), containsInAnyOrder(1)); + + BagState reReadUnderlyingValue = underlying.state(namespace, valueTag); + assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + } + + @Test + public void testCombiningValueStateInternalWithUnderlying() throws CannotProvideCoderException { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + CombineFn sumLongFn = new Sum.SumLongFn(); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + CoderRegistry reg = TestPipeline.create().getCoderRegistry(); + StateTag> stateTag = + StateTags.combiningValue("summer", + sumLongFn.getAccumulatorCoder(reg, reg.getDefaultCoder(Long.class)), sumLongFn); + CombiningValueState underlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.get().read(), equalTo(0L)); + + underlyingValue.add(1L); + assertThat(underlyingValue.get().read(), equalTo(1L)); + + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + CombiningValueState copyOnAccessState = internals.state(namespace, stateTag); + assertThat(copyOnAccessState.get().read(), equalTo(1L)); + + copyOnAccessState.add(4L); + assertThat(copyOnAccessState.get().read(), equalTo(5L)); + assertThat(underlyingValue.get().read(), equalTo(1L)); + + CombiningValueState reReadUnderlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + } + + @Test + public void testKeyedCombiningValueStateInternalWithUnderlying() throws Exception { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + KeyedCombineFn sumLongFn = new Sum.SumLongFn().asKeyedFn(); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + CoderRegistry reg = TestPipeline.create().getCoderRegistry(); + StateTag> stateTag = + StateTags.keyedCombiningValue( + "summer", + sumLongFn.getAccumulatorCoder( + reg, StringUtf8Coder.of(), reg.getDefaultCoder(Long.class)), + sumLongFn); + CombiningValueState underlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.get().read(), equalTo(0L)); + + underlyingValue.add(1L); + assertThat(underlyingValue.get().read(), equalTo(1L)); + + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + CombiningValueState copyOnAccessState = internals.state(namespace, stateTag); + assertThat(copyOnAccessState.get().read(), equalTo(1L)); + + copyOnAccessState.add(4L); + assertThat(copyOnAccessState.get().read(), equalTo(5L)); + assertThat(underlyingValue.get().read(), equalTo(1L)); + + CombiningValueState reReadUnderlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + } + + @Test + public void testWatermarkStateInternalWithUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + + @SuppressWarnings("unchecked") + OutputTimeFn outputTimeFn = (OutputTimeFn) + TestPipeline.create().apply(Create.of("foo")).getWindowingStrategy().getOutputTimeFn(); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> stateTag = + StateTags.watermarkStateInternal("wmstate", outputTimeFn); + WatermarkStateInternal underlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.get().read(), nullValue()); + + underlyingValue.add(new Instant(250L)); + assertThat(underlyingValue.get().read(), equalTo(new Instant(250L))); + + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + WatermarkStateInternal copyOnAccessState = internals.state(namespace, stateTag); + assertThat(copyOnAccessState.get().read(), equalTo(new Instant(250L))); + + copyOnAccessState.add(new Instant(100L)); + assertThat(copyOnAccessState.get().read(), equalTo(new Instant(100L))); + assertThat(underlyingValue.get().read(), equalTo(new Instant(250L))); + + copyOnAccessState.add(new Instant(500L)); + assertThat(copyOnAccessState.get().read(), equalTo(new Instant(100L))); + + WatermarkStateInternal reReadUnderlyingValue = + underlying.state(namespace, stateTag); + assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + } + + @Test + public void testCommitWithoutUnderlying() { + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = internals.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + assertThat(stringBag.get().read(), containsInAnyOrder("baz", "bar")); + + internals.commit(); + + BagState reReadStringBag = internals.state(namespace, bagTag); + assertThat(reReadStringBag.get().read(), containsInAnyOrder("baz", "bar")); + } + + @Test + public void testCommitWithUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = underlying.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + + internals.commit(); + BagState reReadStringBag = internals.state(namespace, bagTag); + assertThat(reReadStringBag.get().read(), containsInAnyOrder("baz", "bar")); + + reReadStringBag.add("spam"); + + BagState underlyingState = underlying.state(namespace, bagTag); + assertThat(underlyingState.get().read(), containsInAnyOrder("spam", "bar", "baz")); + assertThat(underlyingState, is(theInstance(stringBag))); + } + + @Test + public void testCommitWithOverwrittenUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = underlying.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + + BagState internalsState = internals.state(namespace, bagTag); + internalsState.add("eggs"); + internalsState.add("ham"); + internalsState.add("0x00ff00"); + internalsState.add("&"); + + internals.commit(); + + BagState reReadInternalState = internals.state(namespace, bagTag); + assertThat( + reReadInternalState.get().read(), + containsInAnyOrder("bar", "baz", "0x00ff00", "eggs", "&", "ham")); + BagState reReadUnderlyingState = underlying.state(namespace, bagTag); + assertThat(reReadUnderlyingState.get().read(), containsInAnyOrder("bar", "baz")); + } + + @Test + public void testCommitWithAddedUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + + internals.commit(); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = underlying.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + + BagState internalState = internals.state(namespace, bagTag); + assertThat(internalState.get().read(), emptyIterable()); + + BagState reReadUnderlyingState = underlying.state(namespace, bagTag); + assertThat(reReadUnderlyingState.get().read(), containsInAnyOrder("bar", "baz")); + } +} From 41c04e348fff513ea7c716dae2107b98a84cd4cd Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 17 Feb 2016 14:59:29 -0800 Subject: [PATCH 159/751] Handle null input bundles in InMemoryWatermarkManager Remove the updateOutputWatermark specializiation, and handle null input bundles in updateWatermarks. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114903177 --- .../util/InMemoryWatermarkManager.java | 70 ++--- .../util/InMemoryWatermarkManagerTest.java | 293 ++++++------------ 2 files changed, 110 insertions(+), 253 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java index b3a1d92695..ea6e00a79a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java @@ -761,6 +761,8 @@ private List getInputWatermarks(AppliedPTransform transform) return inputCollectionWatermarks; } + //////////////////////////////////////////////////////////////////////////////////////////////// + /** * Gets the input and output watermarks for an {@link AppliedPTransform}. If the * {@link AppliedPTransform PTransform} has not processed any elements, return a watermark of @@ -772,34 +774,6 @@ public TransformWatermarks getWatermarks(AppliedPTransform transform) { return transformToWatermarks.get(transform); } - /** - * Updates the output watermark of a transform that takes no input. - * - *

    The output watermark of a transform that takes no input is determined by that transform, as - * there are no input {@link PCollection PCollections}. - * - * @param eventTimeWatermark the output watermark of the transform. If the transform has buffered - * input elements, the watermark should be the minimum of all buffered - * elements. - */ - public void updateOutputWatermark( - AppliedPTransform transform, - TimerUpdate timerUpdate, - Iterable> outputs, - Instant eventTimeWatermark) { - TransformWatermarks watermarks = getWatermarks(transform); - watermarks.updateTimers(timerUpdate); - watermarks.setEventTimeHold(null, eventTimeWatermark); - - for (CommittedBundle output : outputs) { - PCollection pCollection = output.getPCollection(); - for (AppliedPTransform consumer : consumers.get(pCollection)) { - addPending(consumer, output); - } - } - refreshWatermarks(transform); - } - /** * Updates the watermarks of a transform with one or more inputs. * @@ -820,19 +794,18 @@ public void updateOutputWatermark( * is no hold */ public void updateWatermarks( - CommittedBundle completed, + @Nullable CommittedBundle completed, AppliedPTransform transform, TimerUpdate timerUpdate, Iterable> outputs, @Nullable Instant earliestHold) { updatePending(completed, transform, timerUpdate, outputs); TransformWatermarks transformWms = transformToWatermarks.get(transform); - transformWms.setEventTimeHold(completed.getKey(), earliestHold); + transformWms.setEventTimeHold(completed == null ? null : completed.getKey(), earliestHold); refreshWatermarks(transform); } - private void refreshWatermarks( - AppliedPTransform transform) { + private void refreshWatermarks(AppliedPTransform transform) { TransformWatermarks myWatermarks = transformToWatermarks.get(transform); WatermarkUpdate updateResult = myWatermarks.refresh(); if (updateResult.isAdvanced()) { @@ -860,33 +833,21 @@ private void updatePending( Iterable> outputs) { TransformWatermarks completedTransform = transformToWatermarks.get(transform); completedTransform.updateTimers(timerUpdate); - completedTransform.removePending(input); + if (input != null) { + completedTransform.removePending(input); + } for (CommittedBundle bundle : outputs) { for (AppliedPTransform consumer : consumers.get(bundle.getPCollection())) { - addPending(consumer, bundle); + TransformWatermarks watermarks = transformToWatermarks.get(consumer); + watermarks.addPending(bundle); } } } - /** - * Adds all of the provided {@link WindowedValue WindowedValues} to the collection of pending - * elements for the provided {@link AppliedPTransform}. - */ - private void addPending( - AppliedPTransform transform, CommittedBundle pending) { - TransformWatermarks watermarks = transformToWatermarks.get(transform); - watermarks.addPending(pending); - } - /** * Returns a map of each {@link PTransform} that has pending timers to those timers. All of the * pending timers will be removed from this {@link InMemoryWatermarkManager}. - * - * This method exists primarily to extract processing time timers, as watermark timers will be - * returned whenever a watermark is updated through - * {@link #updateOutputWatermark(AppliedPTransform, TimerUpdate, Iterable, Instant)} and - * {@link #updateWatermarks(CommittedBundle, AppliedPTransform, TimerUpdate, Iterable, Instant)}. */ public Map, Map> extractFiredTimers() { Map, Map> allTimers = new HashMap<>(); @@ -1324,4 +1285,15 @@ public int compare(WindowedValue o1, WindowedValue o2) { return o1.getTimestamp().compareTo(o2.getTimestamp()); } } + + public Set> getCompletedTransforms() { + Set> result = new HashSet<>(); + for (Map.Entry, TransformWatermarks> wms : + transformToWatermarks.entrySet()) { + if (wms.getValue().getOutputWatermark().equals(THE_END_OF_TIME.get())) { + result.add(wms.getKey()); + } + } + return result; + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java index 54bc8bfa54..d4979f2156 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManagerTest.java @@ -94,7 +94,8 @@ public void setup() { @Override public void processElement(DoFn.ProcessContext c) throws Exception { c.output(c.element() * 2); - }})); + } + })); keyed = createdInts.apply("keyed", WithKeys.of("MyKey")); @@ -110,8 +111,7 @@ public void processElement(DoFn.ProcessContext c) throws Excep Map>> consumers = new HashMap<>(); consumers.put( createdInts, - ImmutableList.>of( - filtered.getProducingTransformInternal(), + ImmutableList.>of(filtered.getProducingTransformInternal(), keyed.getProducingTransformInternal(), flattened.getProducingTransformInternal())); consumers.put( filtered, @@ -151,11 +151,8 @@ public void getWatermarkForUntouchedTransform() { @Test public void getWatermarkForUpdatedSourceTransform() { CommittedBundle output = globallyWindowedBundle(createdInts, 1); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(output), - new Instant(8000L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(output), new Instant(8000L)); TransformWatermarks updatedSourceWatermark = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -170,10 +167,8 @@ public void getWatermarkForUpdatedSourceTransform() { public void getWatermarkForMultiInputTransform() { CommittedBundle secondPcollectionBundle = globallyWindowedBundle(intsToFlatten, -1); - manager.updateOutputWatermark( - intsToFlatten.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(secondPcollectionBundle), + manager.updateWatermarks(null, intsToFlatten.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(secondPcollectionBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); // We didn't do anything for the first source, so we shouldn't have progressed the watermark @@ -202,11 +197,8 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle flattenedBundleSecondCreate = globallyWindowedBundle(flattened, -1); // We have finished processing the bundle from the second PCollection, but we haven't consumed // anything from the first PCollection yet; so our watermark shouldn't advance - manager.updateWatermarks( - secondPcollectionBundle, - flattened.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(flattenedBundleSecondCreate), + manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(flattenedBundleSecondCreate), null); TransformWatermarks transformAfterProcessing = manager.getWatermarks(flattened.getProducingTransformInternal()); @@ -225,9 +217,7 @@ public void getWatermarkForMultiInputTransform() { timestampedBundle(createdInts, TimestampedValue.of(5, firstCollectionTimestamp)); // the source is done, but elements are still buffered. The source output watermark should be // past the end of the global window - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(firstPcollectionBundle), new Instant(Long.MAX_VALUE)); TransformWatermarks firstSourceWatermarks = @@ -255,11 +245,8 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle completedFlattenBundle = InProcessBundle.unkeyed(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks( - firstPcollectionBundle, - flattened.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(completedFlattenBundle), + manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(completedFlattenBundle), null); TransformWatermarks afterConsumingAllInput = manager.getWatermarks(flattened.getProducingTransformInternal()); @@ -277,17 +264,11 @@ public void getWatermarkForMultiInputTransform() { */ @Test public void getWatermarkForMultiConsumedCollection() { -CommittedBundle createdBundle = - timestampedBundle( - createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(createdBundle), - new Instant(Long.MAX_VALUE)); + CommittedBundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); TransformWatermarks createdAfterProducing = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( @@ -298,12 +279,8 @@ public void getWatermarkForMultiConsumedCollection() { timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks( - createdBundle, - keyed.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(keyBundle), - null); + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(keyBundle), null); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -318,12 +295,8 @@ public void getWatermarkForMultiConsumedCollection() { CommittedBundle filteredBundle = timestampedBundle(filtered, TimestampedValue.of(2, new Instant(1234L))); - manager.updateWatermarks( - createdBundle, - filtered.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(filteredBundle), - null); + manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(filteredBundle), null); TransformWatermarks filteredProcessedWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat( @@ -340,29 +313,18 @@ public void getWatermarkForMultiConsumedCollection() { */ @Test public void updateWatermarkWithWatermarkHolds() { - CommittedBundle createdBundle = - timestampedBundle( - createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(createdBundle), - new Instant(Long.MAX_VALUE)); + CommittedBundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); CommittedBundle> keyBundle = - timestampedBundle( - keyed, - TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks( - createdBundle, - keyed.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(keyBundle), + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(keyBundle), new Instant(500L)); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); @@ -388,7 +350,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) .commit(clock.now()); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), ImmutableList.of(firstKeyBundle, secondKeyBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); manager.updateWatermarks(firstKeyBundle, filtered.getProducingTransformInternal(), @@ -433,22 +395,16 @@ public void updateWatermarkWithKeyedWatermarkHolds() { public void updateOutputWatermarkShouldBeMonotonic() { CommittedBundle firstInput = InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(firstInput), - new Instant(0L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(firstInput), new Instant(0L)); TransformWatermarks firstWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); CommittedBundle secondInput = InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(secondInput), - new Instant(-250L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(secondInput), new Instant(-250L)); TransformWatermarks secondWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); @@ -460,29 +416,18 @@ public void updateOutputWatermarkShouldBeMonotonic() { */ @Test public void updateWatermarkWithHoldsShouldBeMonotonic() { - CommittedBundle createdBundle = - timestampedBundle( - createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(createdBundle), - new Instant(Long.MAX_VALUE)); + CommittedBundle createdBundle = timestampedBundle(createdInts, + TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); CommittedBundle> keyBundle = - timestampedBundle( - keyed, - TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks( - createdBundle, - keyed.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(keyBundle), + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(keyBundle), new Instant(500L)); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); @@ -509,23 +454,16 @@ public void updateWatermarkWithLateData() { CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, sourceWatermark), TimestampedValue.of(2, new Instant(1234L))); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(createdBundle), - sourceWatermark); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(createdBundle), sourceWatermark); CommittedBundle> keyBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), sourceWatermark), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); // Finish processing the on-time data. The watermarks should progress to be equal to the source - manager.updateWatermarks( - createdBundle, - keyed.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(keyBundle), - null); + manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(keyBundle), null); TransformWatermarks onTimeWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); @@ -535,11 +473,8 @@ public void updateWatermarkWithLateData() { timestampedBundle(createdInts, TimestampedValue.of(3, new Instant(-1000L))); // the late data arrives in a downstream PCollection after its watermark has advanced past it; // we don't advance the watermark past the current watermark until we've consumed the late data - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(lateDataBundle), - new Instant(2_000_000L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(lateDataBundle), new Instant(2_000_000L)); TransformWatermarks bufferedLateWm = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); @@ -553,12 +488,8 @@ public void updateWatermarkWithLateData() { CommittedBundle> lateKeyedBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks( - lateDataBundle, - keyed.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(lateKeyedBundle), - null); + manager.updateWatermarks(lateDataBundle, keyed.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(lateKeyedBundle), null); } /** @@ -568,9 +499,7 @@ public void updateWatermarkWithLateData() { @Test public void getWatermarksAfterOnlyEmptyOutput() { CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = @@ -597,18 +526,12 @@ public void getWatermarksAfterOnlyEmptyOutput() { @Test public void getWatermarksAfterHoldAndEmptyOutput() { CommittedBundle firstCreateOutput = globallyWindowedBundle(createdInts, 1, 2); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(firstCreateOutput), - new Instant(12_000L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(firstCreateOutput), new Instant(12_000L)); CommittedBundle firstFilterOutput = globallyWindowedBundle(filtered); - manager.updateWatermarks( - firstCreateOutput, - filtered.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(firstFilterOutput), + manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(firstFilterOutput), new Instant(10_000L)); TransformWatermarks firstFilterWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -616,9 +539,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { assertThat(firstFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = @@ -658,11 +579,8 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { CommittedBundle createOutput = InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(createOutput), - BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(clock.now())); @@ -687,11 +605,8 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { CommittedBundle filterOutputBundle = InProcessBundle.unkeyed(intsToFlatten).commit(new Instant(1250L)); - manager.updateWatermarks( - createOutput, - filtered.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(filterOutputBundle), + manager.updateWatermarks(createOutput, filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(filterOutputBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks filterAfterConsumed = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -709,10 +624,10 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { * *

    Also demonstrate that the result is monotonic. */ -// @Test + // @Test public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { CommittedBundle createdBundle = globallyWindowedBundle(createdInts, 1, 2, 4, 8); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(createdBundle), new Instant(1248L)); TransformWatermarks filteredWms = @@ -735,11 +650,8 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { Instant startTime = clock.now(); clock.set(startTime.plus(250L)); // We're held based on the past timer - assertThat( - filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); - assertThat( - filteredDoubledWms.getSynchronizedProcessingOutputTime(), - not(laterThan(startTime))); + assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); + assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); // And we're monotonic assertThat( filteredWms.getSynchronizedProcessingOutputTime(), not(earlierThan(initialFilteredWm))); @@ -755,11 +667,8 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { .getTimers(TimeDomain.PROCESSING_TIME), contains(pastTimer)); // Our timer has fired, but has not been completed, so it holds our synchronized processing WM - assertThat( - filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); - assertThat( - filteredDoubledWms.getSynchronizedProcessingOutputTime(), - not(laterThan(startTime))); + assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); + assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); CommittedBundle filteredTimerBundle = InProcessBundle.keyed(filtered, "key").commit(BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -816,23 +725,17 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { CommittedBundle createOutput = InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>singleton(createOutput), - BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat( - createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); + assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); assertThat( createAfterUpdate.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); CommittedBundle createSecondOutput = InProcessBundle.unkeyed(createdInts).commit(new Instant(750L)); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(createSecondOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -842,7 +745,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { @Test public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers() { CommittedBundle created = globallyWindowedBundle(createdInts, 1, 2, 3); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(created), new Instant(40_900L)); CommittedBundle filteredBundle = globallyWindowedBundle(filtered, 2, 4); @@ -850,9 +753,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( TimerData upstreamProcessingTimer = TimerData.of(StateNamespaces.global(), upstreamHold, TimeDomain.PROCESSING_TIME); manager.updateWatermarks(created, filtered.getProducingTransformInternal(), - TimerUpdate.builder("key") - .setTimer(upstreamProcessingTimer) - .build(), + TimerUpdate.builder("key").setTimer(upstreamProcessingTimer).build(), Collections.>singleton(filteredBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -881,7 +782,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( @Test public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { CommittedBundle created = globallyWindowedBundle(createdInts, 1, 2, 3); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(created), new Instant(29_919_235L)); Instant upstreamHold = new Instant(2048L); @@ -908,11 +809,8 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { // Advance WM of keyed past the first timer, but ahead of the second and third CommittedBundle createdBundle = globallyWindowedBundle(filtered); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.singleton(createdBundle), - new Instant(1500L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.singleton(createdBundle), new Instant(1500L)); TimerData earliestTimer = TimerData.of(StateNamespaces.global(), new Instant(1000), TimeDomain.EVENT_TIME); @@ -928,10 +826,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { .setTimer(lastTimer) .build(); - manager.updateWatermarks( - createdBundle, - filtered.getProducingTransformInternal(), - update, + manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), update, Collections.>singleton(globallyWindowedBundle(intsToFlatten)), new Instant(1000L)); @@ -945,11 +840,8 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { FiredTimers firstFired = firstFilteredTimers.get(key); assertThat(firstFired.getTimers(TimeDomain.EVENT_TIME), contains(earliestTimer)); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>emptyList(), - new Instant(50_000L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>emptyList(), new Instant(50_000L)); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( @@ -971,11 +863,8 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { // Advance WM of keyed past the first timer, but ahead of the second and third CommittedBundle createdBundle = globallyWindowedBundle(filtered); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.singleton(createdBundle), - new Instant(1500L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.singleton(createdBundle), new Instant(1500L)); TimerData earliestTimer = TimerData.of(StateNamespaces.global(), new Instant(999L), TimeDomain.PROCESSING_TIME); @@ -988,12 +877,10 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { TimerUpdate.builder(key) .setTimer(lastTimer) .setTimer(earliestTimer) - .setTimer(middleTimer).build(); + .setTimer(middleTimer) + .build(); - manager.updateWatermarks( - createdBundle, - filtered.getProducingTransformInternal(), - update, + manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), update, Collections.>singleton(globallyWindowedBundle(intsToFlatten)), new Instant(1000L)); @@ -1008,11 +895,8 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { assertThat(firstFired.getTimers(TimeDomain.PROCESSING_TIME), contains(earliestTimer)); clock.set(new Instant(50_000L)); - manager.updateOutputWatermark( - createdInts.getProducingTransformInternal(), - TimerUpdate.empty(), - Collections.>emptyList(), - new Instant(50_000L)); + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + Collections.>emptyList(), new Instant(50_000L)); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( @@ -1034,7 +918,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { // Advance WM of keyed past the first timer, but ahead of the second and third CommittedBundle createdBundle = globallyWindowedBundle(filtered); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.singleton(createdBundle), new Instant(1500L)); TimerData earliestTimer = TimerData.of( @@ -1048,7 +932,8 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { TimerUpdate.builder(key) .setTimer(lastTimer) .setTimer(earliestTimer) - .setTimer(middleTimer).build(); + .setTimer(middleTimer) + .build(); manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), update, Collections.>singleton(globallyWindowedBundle(intsToFlatten)), @@ -1066,7 +951,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { firstFired.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), contains(earliestTimer)); clock.set(new Instant(50_000L)); - manager.updateOutputWatermark(createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>emptyList(), new Instant(50_000L)); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); From b7505c50e1ddaf0013c0dca9a1a77b3512e6611d Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 17 Feb 2016 15:46:26 -0800 Subject: [PATCH 160/751] Remove unneccessary type from GroupAlsoByWindowViaWindowSet ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114907928 --- .../dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java index 46b2e5eeb8..ac2df24fec 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java @@ -33,9 +33,8 @@ public class GroupAlsoByWindowViaWindowSetDoFn< K, InputT, OutputT, W extends BoundedWindow, RinT extends KeyedWorkItem> extends DoFn> implements ReduceFnExecutor { - public static > - DoFn> create( + public static + DoFn, KV> create( WindowingStrategy strategy, SystemReduceFn reduceFn) { return new GroupAlsoByWindowViaWindowSetDoFn<>(strategy, reduceFn); } From 14154791d96ba223f08c42f13563c407285331a7 Mon Sep 17 00:00:00 2001 From: millsd Date: Wed, 17 Feb 2016 16:11:22 -0800 Subject: [PATCH 161/751] Never drop late data in Reshuffle ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114910300 --- .../java/com/google/cloud/dataflow/sdk/util/Reshuffle.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java index 0ca8fa8a69..367db2dc5b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java @@ -63,11 +63,8 @@ public PCollection> apply(PCollection> input) { Window.Bound> rewindow = Window .>into(new PassThroughWindowFn<>(originalStrategy.getWindowFn())) .triggering(new ReshuffleTrigger<>()) - .discardingFiredPanes(); - if (!originalStrategy.isAllowedLatenessSpecified()) { - rewindow = rewindow.withAllowedLateness( - Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis())); - } + .discardingFiredPanes() + .withAllowedLateness(Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis())); return input.apply(rewindow) .apply(GroupByKey.create()) From 0ad8ed19613200e659ad9a921c8179564185588b Mon Sep 17 00:00:00 2001 From: dhalperi Date: Wed, 17 Feb 2016 22:05:13 -0800 Subject: [PATCH 162/751] BigtableIO: add a bounded source for Google Cloud Bigtable ----Release Notes---- Dataflow now has support for Google Cloud Bigtable using BigtableIO. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114932364 --- .../dataflow/sdk/io/bigtable/BigtableIO.java | 562 +++++++++++++++++- .../sdk/io/bigtable/BigtableService.java | 45 ++ .../sdk/io/bigtable/BigtableServiceImpl.java | 97 ++- .../sdk/io/bigtable/BigtableIOTest.java | 473 ++++++++++++++- 4 files changed, 1144 insertions(+), 33 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index 379450a880..c3f233f249 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -18,14 +18,24 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import com.google.bigtable.v1.Mutation; +import com.google.bigtable.v1.Row; +import com.google.bigtable.v1.RowFilter; +import com.google.bigtable.v1.SampleRowKeysResponse; import com.google.cloud.bigtable.config.BigtableOptions; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Proto2Coder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; import com.google.cloud.dataflow.sdk.io.Sink.Writer; +import com.google.cloud.dataflow.sdk.io.range.ByteKey; +import com.google.cloud.dataflow.sdk.io.range.ByteKeyRange; +import com.google.cloud.dataflow.sdk.io.range.ByteKeyRangeTracker; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.PTransform; @@ -33,7 +43,9 @@ import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.protobuf.ByteString; @@ -43,16 +55,53 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentLinkedQueue; import javax.annotation.Nullable; /** - * A bounded sink for Google Cloud Bigtable. + * A bounded source and sink for Google Cloud Bigtable. * *

    For more information, see the online documentation at * Google Cloud Bigtable. * + *

    Reading from Cloud Bigtable

    + * + *

    The Bigtable source returns a set of rows from a single table, returning a + * {@code PCollection<Row>}. + * + *

    To configure a Cloud Bigtable source, you must supply a table id and a {@link BigtableOptions} + * or builder configured with the project and other information necessary to identify the + * Bigtable cluster. A {@link RowFilter} may also optionally be specified using + * {@link BigtableIO.Read#withRowFilter}. For example: + * + *

    {@code
    + * BigtableOptions.Builder optionsBuilder =
    + *     new BigtableOptions.Builder()
    + *         .setProjectId("project")
    + *         .setClusterId("cluster")
    + *         .setZoneId("zone");
    + *
    + * Pipeline p = ...;
    + *
    + * // Scan the entire table.
    + * p.apply("read",
    + *     BigtableIO.read()
    + *         .withBigtableOptions(optionsBuilder)
    + *         .withTableId("table"));
    + *
    + * // Scan a subset of rows that match the specified row filter.
    + * p.apply("filtered read",
    + *     BigtableIO.read()
    + *         .withBigtableOptions(optionsBuilder)
    + *         .withTableId("table")
    + *         .withRowFilter(filter));
    + * }
    + * *

    Writing to Cloud Bigtable

    * *

    The Bigtable sink executes a set of row mutations on a single table. It takes as input a @@ -95,11 +144,24 @@ public class BigtableIO { private static final Logger logger = LoggerFactory.getLogger(BigtableIO.class); + /** + * Creates an uninitialized {@link BigtableIO.Read}. Before use, the {@code Read} must be + * initialized with a + * {@link BigtableIO.Read#withBigtableOptions(BigtableOptions) BigtableOptions} that specifies + * the source Cloud Bigtable cluster, and a {@link BigtableIO.Read#withTableId tableId} that + * specifies which table to read. A {@link RowFilter} may also optionally be specified using + * {@link BigtableIO.Read#withRowFilter}. + */ + @Experimental + public static Read read() { + return new Read(null, "", null, null); + } + /** * Creates an uninitialized {@link BigtableIO.Write}. Before use, the {@code Write} must be * initialized with a * {@link BigtableIO.Write#withBigtableOptions(BigtableOptions) BigtableOptions} that specifies - * the destination Cloud Bigtable cluster, and a {@link BigtableIO.Write#withTableId table} that + * the destination Cloud Bigtable cluster, and a {@link BigtableIO.Write#withTableId tableId} that * specifies which table to write. */ @Experimental @@ -107,6 +169,153 @@ public static Write write() { return new Write(null, "", null); } + /** + * A {@link PTransform} that reads from Google Cloud Bigtable. See the class-level Javadoc on + * {@link BigtableIO} for more information. + * + * @see BigtableIO + */ + @Experimental + public static class Read extends PTransform> { + /** + * Returns a new {@link BigtableIO.Read} that will read from the Cloud Bigtable cluster + * indicated by the given options, and using any other specified customizations. + * + *

    Does not modify this object. + */ + public Read withBigtableOptions(BigtableOptions options) { + checkNotNull(options, "options"); + return withBigtableOptions(options.toBuilder()); + } + + /** + * Returns a new {@link BigtableIO.Read} that will read from the Cloud Bigtable cluster + * indicated by the given options, and using any other specified customizations. + * + *

    Clones the given {@link BigtableOptions} builder so that any further changes + * will have no effect on the returned {@link BigtableIO.Read}. + * + *

    Does not modify this object. + */ + public Read withBigtableOptions(BigtableOptions.Builder optionsBuilder) { + checkNotNull(optionsBuilder, "optionsBuilder"); + // TODO: is there a better way to clone a Builder? Want it to be immune from user changes. + BigtableOptions.Builder clonedBuilder = optionsBuilder.build().toBuilder(); + BigtableOptions optionsWithAgent = clonedBuilder.setUserAgent(getUserAgent()).build(); + return new Read(optionsWithAgent, tableId, filter, bigtableService); + } + + /** + * Returns a new {@link BigtableIO.Read} that will filter the rows read from Cloud Bigtable + * using the given row filter. + * + *

    Does not modify this object. + */ + Read withRowFilter(RowFilter filter) { + checkNotNull(filter, "filter"); + return new Read(options, tableId, filter, bigtableService); + } + + /** + * Returns a new {@link BigtableIO.Read} that will read from the specified table. + * + *

    Does not modify this object. + */ + public Read withTableId(String tableId) { + checkNotNull(tableId, "tableId"); + return new Read(options, tableId, filter, bigtableService); + } + + /** + * Returns the Google Cloud Bigtable cluster being read from, and other parameters. + */ + public BigtableOptions getBigtableOptions() { + return options; + } + + /** + * Returns the table being read from. + */ + public String getTableId() { + return tableId; + } + + @Override + public PCollection apply(PInput input) { + BigtableSource source = + new BigtableSource(getBigtableService(), tableId, filter, ByteKeyRange.ALL_KEYS, null); + return input.getPipeline().apply(com.google.cloud.dataflow.sdk.io.Read.from(source)); + } + + @Override + public void validate(PInput input) { + checkArgument(options != null, "BigtableOptions not specified"); + checkArgument(!tableId.isEmpty(), "Table ID not specified"); + try { + checkArgument( + getBigtableService().tableExists(tableId), "Table %s does not exist", tableId); + } catch (IOException e) { + logger.warn("Error checking whether table {} exists; proceeding.", tableId, e); + } + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(Read.class) + .add("options", options) + .add("tableId", tableId) + .add("filter", filter) + .toString(); + } + + ///////////////////////////////////////////////////////////////////////////////////////// + /** + * Used to define the Cloud Bigtable cluster and any options for the networking layer. + * Cannot actually be {@code null} at validation time, but may start out {@code null} while + * source is being built. + */ + @Nullable private final BigtableOptions options; + private final String tableId; + @Nullable private final RowFilter filter; + @Nullable private final BigtableService bigtableService; + + private Read( + @Nullable BigtableOptions options, + String tableId, + @Nullable RowFilter filter, + @Nullable BigtableService bigtableService) { + this.options = options; + this.tableId = checkNotNull(tableId, "tableId"); + this.filter = filter; + this.bigtableService = bigtableService; + } + + /** + * Returns a new {@link BigtableIO.Read} that will read using the given Cloud Bigtable + * service implementation. + * + *

    This is used for testing. + * + *

    Does not modify this object. + */ + Read withBigtableService(BigtableService bigtableService) { + checkNotNull(bigtableService, "bigtableService"); + return new Read(options, tableId, filter, bigtableService); + } + + /** + * Helper function that either returns the mock Bigtable service supplied by + * {@link #withBigtableService} or creates and returns an implementation that talks to + * {@code Cloud Bigtable}. + */ + private BigtableService getBigtableService() { + if (bigtableService != null) { + return bigtableService; + } + return new BigtableServiceImpl(options); + } + } + /** * A {@link PTransform} that writes to Google Cloud Bigtable. See the class-level Javadoc on * {@link BigtableIO} for more information. @@ -149,7 +358,7 @@ public Write withBigtableOptions(BigtableOptions options) { * Returns a new {@link BigtableIO.Write} that will write to the Cloud Bigtable cluster * indicated by the given options, and using any other specified customizations. * - *

    Clones the given {@link BigtableOptions.Builder} is cloned so that any further changes + *

    Clones the given {@link BigtableOptions} builder so that any further changes * will have no effect on the returned {@link BigtableIO.Write}. * *

    Does not modify this object. @@ -238,6 +447,353 @@ private BigtableService getBigtableService() { } } + ////////////////////////////////////////////////////////////////////////////////////////// + /** Disallow construction of utility class. */ + private BigtableIO() {} + + static class BigtableSource extends BoundedSource { + public BigtableSource( + BigtableService service, + String tableId, + @Nullable RowFilter filter, + ByteKeyRange range, + Long estimatedSizeBytes) { + this.service = service; + this.tableId = tableId; + this.filter = filter; + this.range = range; + this.estimatedSizeBytes = estimatedSizeBytes; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(BigtableSource.class) + .add("tableId", tableId) + .add("filter", filter) + .add("range", range) + .add("estimatedSizeBytes", estimatedSizeBytes) + .toString(); + } + + ////// Private state and internal implementation details ////// + private final BigtableService service; + @Nullable private final String tableId; + @Nullable private final RowFilter filter; + private final ByteKeyRange range; + @Nullable private Long estimatedSizeBytes; + @Nullable private transient List sampleRowKeys; + + protected BigtableSource withStartKey(ByteKey startKey) { + checkNotNull(startKey, "startKey"); + return new BigtableSource( + service, tableId, filter, range.withStartKey(startKey), estimatedSizeBytes); + } + + protected BigtableSource withEndKey(ByteKey endKey) { + checkNotNull(endKey, "endKey"); + return new BigtableSource( + service, tableId, filter, range.withEndKey(endKey), estimatedSizeBytes); + } + + protected BigtableSource withEstimatedSizeBytes(Long estimatedSizeBytes) { + checkNotNull(estimatedSizeBytes, "estimatedSizeBytes"); + return new BigtableSource(service, tableId, filter, range, estimatedSizeBytes); + } + + /** + * Makes an API call to the Cloud Bigtable service that gives information about tablet key + * boundaries and estimated sizes. We can use these samples to ensure that splits are on + * different tablets, and possibly generate sub-splits within tablets. + */ + private List getSampleRowKeys() throws IOException { + return service.getSampleRowKeys(this); + } + + @Override + public List splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + // Update the desiredBundleSizeBytes in order to limit the + // number of splits to maximumNumberOfSplits. + long maximumNumberOfSplits = 4000; + long sizeEstimate = getEstimatedSizeBytes(options); + desiredBundleSizeBytes = + Math.max(sizeEstimate / maximumNumberOfSplits, desiredBundleSizeBytes); + + // Delegate to testable helper. + return splitIntoBundlesBasedOnSamples(desiredBundleSizeBytes, getSampleRowKeys()); + } + + /** Helper that splits this source into bundles based on Cloud Bigtable sampled row keys. */ + private List splitIntoBundlesBasedOnSamples( + long desiredBundleSizeBytes, List sampleRowKeys) { + // There are no regions, or no samples available. Just scan the entire range. + if (sampleRowKeys.isEmpty()) { + logger.info("Not splitting source {} because no sample row keys are available.", this); + return Collections.singletonList(this); + } + + logger.info( + "About to split into bundles of size {} with sampleRowKeys length {} first element {}", + desiredBundleSizeBytes, + sampleRowKeys.size(), + sampleRowKeys.get(0)); + + // Loop through all sampled responses and generate splits from the ones that overlap the + // scan range. The main complication is that we must track the end range of the previous + // sample to generate good ranges. + ByteKey lastEndKey = ByteKey.EMPTY; + long lastOffset = 0; + ImmutableList.Builder splits = ImmutableList.builder(); + for (SampleRowKeysResponse response : sampleRowKeys) { + ByteKey responseEndKey = ByteKey.of(response.getRowKey()); + long responseOffset = response.getOffsetBytes(); + checkState( + responseOffset >= lastOffset, + "Expected response byte offset %s to come after the last offset %s", + responseOffset, + lastOffset); + + if (!range.overlaps(ByteKeyRange.of(lastEndKey, responseEndKey))) { + // This region does not overlap the scan, so skip it. + lastOffset = responseOffset; + lastEndKey = responseEndKey; + continue; + } + + // Calculate the beginning of the split as the larger of startKey and the end of the last + // split. Unspecified start is smallest key so is correctly treated as earliest key. + ByteKey splitStartKey = lastEndKey; + if (splitStartKey.compareTo(range.getStartKey()) < 0) { + splitStartKey = range.getStartKey(); + } + + // Calculate the end of the split as the smaller of endKey and the end of this sample. Note + // that range.containsKey handles the case when range.getEndKey() is empty. + ByteKey splitEndKey = responseEndKey; + if (!range.containsKey(splitEndKey)) { + splitEndKey = range.getEndKey(); + } + + // We know this region overlaps the desired key range, and we know a rough estimate of its + // size. Split the key range into bundle-sized chunks and then add them all as splits. + long sampleSizeBytes = responseOffset - lastOffset; + List subSplits = + splitKeyRangeIntoBundleSizedSubranges( + sampleSizeBytes, + desiredBundleSizeBytes, + ByteKeyRange.of(splitStartKey, splitEndKey)); + splits.addAll(subSplits); + + // Move to the next region. + lastEndKey = responseEndKey; + lastOffset = responseOffset; + } + + // We must add one more region after the end of the samples if both these conditions hold: + // 1. we did not scan to the end yet (lastEndKey is concrete, not 0-length). + // 2. we want to scan to the end (endKey is empty) or farther (lastEndKey < endKey). + if (!lastEndKey.isEmpty() + && (range.getEndKey().isEmpty() || lastEndKey.compareTo(range.getEndKey()) < 0)) { + splits.add(this.withStartKey(lastEndKey).withEndKey(range.getEndKey())); + } + + List ret = splits.build(); + logger.info("Generated {} splits. First split: {}", ret.size(), ret.get(0)); + return ret; + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws IOException { + // Delegate to testable helper. + if (estimatedSizeBytes == null) { + estimatedSizeBytes = getEstimatedSizeBytesBasedOnSamples(getSampleRowKeys()); + } + return estimatedSizeBytes; + } + + /** + * Computes the estimated size in bytes based on the total size of all samples that overlap + * the key range this source will scan. + */ + private long getEstimatedSizeBytesBasedOnSamples(List samples) { + long estimatedSizeBytes = 0; + long lastOffset = 0; + ByteKey currentStartKey = ByteKey.EMPTY; + // Compute the total estimated size as the size of each sample that overlaps the scan range. + // TODO: In future, Bigtable service may provide finer grained APIs, e.g., to sample given a + // filter or to sample on a given key range. + for (SampleRowKeysResponse response : samples) { + ByteKey currentEndKey = ByteKey.of(response.getRowKey()); + long currentOffset = response.getOffsetBytes(); + if (!currentStartKey.isEmpty() && currentStartKey.equals(currentEndKey)) { + // Skip an empty region. + lastOffset = currentOffset; + continue; + } else if (range.overlaps(ByteKeyRange.of(currentStartKey, currentEndKey))) { + estimatedSizeBytes += currentOffset - lastOffset; + } + currentStartKey = currentEndKey; + lastOffset = currentOffset; + } + return estimatedSizeBytes; + } + + /** + * Cloud Bigtable returns query results ordered by key. + */ + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return true; + } + + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + return new BigtableReader(this, service); + } + + @Override + public void validate() { + checkArgument(!tableId.isEmpty(), "tableId cannot be empty"); + } + + @Override + public Coder getDefaultOutputCoder() { + return Proto2Coder.of(Row.class); + } + + /** Helper that splits the specified range in this source into bundles. */ + private List splitKeyRangeIntoBundleSizedSubranges( + long sampleSizeBytes, long desiredBundleSizeBytes, ByteKeyRange range) { + // Catch the trivial cases. Split is small enough already, or this is the last region. + logger.debug( + "Subsplit for sampleSizeBytes {} and desiredBundleSizeBytes {}", + sampleSizeBytes, + desiredBundleSizeBytes); + if (sampleSizeBytes <= desiredBundleSizeBytes) { + return Collections.singletonList( + this.withStartKey(range.getStartKey()).withEndKey(range.getEndKey())); + } + + checkArgument( + sampleSizeBytes > 0, "Sample size %s bytes must be greater than 0.", sampleSizeBytes); + checkArgument( + desiredBundleSizeBytes > 0, + "Desired bundle size %s bytes must be greater than 0.", + desiredBundleSizeBytes); + + int splitCount = (int) Math.ceil(((double) sampleSizeBytes) / (desiredBundleSizeBytes)); + List splitKeys = range.split(splitCount); + ImmutableList.Builder splits = ImmutableList.builder(); + Iterator keys = splitKeys.iterator(); + ByteKey prev = keys.next(); + while (keys.hasNext()) { + ByteKey next = keys.next(); + splits.add( + this + .withStartKey(prev) + .withEndKey(next) + .withEstimatedSizeBytes(sampleSizeBytes / splitCount)); + prev = next; + } + return splits.build(); + } + + public ByteKeyRange getRange() { + return range; + } + + public RowFilter getRowFilter() { + return filter; + } + + public String getTableId() { + return tableId; + } + } + + private static class BigtableReader extends BoundedReader { + // Thread-safety: source is protected via synchronization and is only accessed or modified + // inside a synchronized block (or constructor, which is the same). + private BigtableSource source; + private BigtableService service; + private BigtableService.Reader reader; + private final ByteKeyRangeTracker rangeTracker; + private long recordsReturned; + + public BigtableReader(BigtableSource source, BigtableService service) { + this.source = source; + this.service = service; + rangeTracker = ByteKeyRangeTracker.of(source.getRange()); + } + + @Override + public boolean start() throws IOException { + reader = service.createReader(getCurrentSource()); + boolean hasRecord = + reader.start() + && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())); + if (hasRecord) { + ++recordsReturned; + } + return hasRecord; + } + + @Override + public synchronized BigtableSource getCurrentSource() { + return source; + } + + @Override + public boolean advance() throws IOException { + boolean hasRecord = + reader.advance() + && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())); + if (hasRecord) { + ++recordsReturned; + } + return hasRecord; + } + + @Override + public Row getCurrent() throws NoSuchElementException { + return reader.getCurrentRow(); + } + + @Override + public void close() throws IOException { + logger.info("Closing reader after reading {} records.", recordsReturned); + if (reader != null) { + reader.close(); + reader = null; + } + } + + @Override + public final Double getFractionConsumed() { + return rangeTracker.getFractionConsumed(); + } + + @Override + public final synchronized BigtableSource splitAtFraction(double fraction) { + ByteKey splitKey; + try { + splitKey = source.getRange().interpolateKey(fraction); + } catch (IllegalArgumentException e) { + logger.info("%s: Failed to interpolate key for fraction %s.", source.getRange(), fraction); + return null; + } + logger.debug( + "Proposing to split {} at fraction {} (key {})", rangeTracker, fraction, splitKey); + if (!rangeTracker.trySplitAtPosition(splitKey)) { + return null; + } + BigtableSource primary = source.withEndKey(splitKey); + BigtableSource residual = source.withStartKey(splitKey); + this.source = primary; + return residual; + } + } + private static class Sink extends com.google.cloud.dataflow.sdk.io.Sink>> { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java index 03ddd3a6ae..85d706cb0a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java @@ -16,6 +16,9 @@ package com.google.cloud.dataflow.sdk.io.bigtable; import com.google.bigtable.v1.Mutation; +import com.google.bigtable.v1.Row; +import com.google.bigtable.v1.SampleRowKeysResponse; +import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.ByteString; @@ -23,6 +26,8 @@ import java.io.IOException; import java.io.Serializable; +import java.util.List; +import java.util.NoSuchElementException; /** * An interface for real or fake implementations of Cloud Bigtable. @@ -51,13 +56,53 @@ ListenableFuture writeRecord(KV> record) void close() throws IOException; } + /** + * The interface of a class that reads from Cloud Bigtable. + */ + interface Reader { + /** + * Reads the first element (including initialization, such as opening a network connection) and + * returns true if an element was found. + */ + boolean start() throws IOException; + + /** + * Attempts to read the next element, and returns true if an element has been read. + */ + boolean advance() throws IOException; + + /** + * Closes the reader. + * + * @throws IOException if there is an error. + */ + void close() throws IOException; + + /** + * Returns the last row read by a successful start() or advance(), or throws if there is no + * current row because the last such call was unsuccessful. + */ + Row getCurrentRow() throws NoSuchElementException; + } + /** * Returns {@code true} if the table with the give name exists. */ boolean tableExists(String tableId) throws IOException; + /** + * Returns a {@link Reader} that will read from the specified source. + */ + Reader createReader(BigtableSource source) throws IOException; + /** * Returns a {@link Writer} that will write to the specified table. */ Writer openForWriting(String tableId) throws IOException; + + /** + * Returns a set of row keys sampled from the underlying table. These contain information about + * the distribution of keys within the table. + */ + List getSampleRowKeys(BigtableSource source) throws IOException; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java index 196e64c241..5ab85827ec 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java @@ -18,12 +18,20 @@ import com.google.bigtable.admin.table.v1.GetTableRequest; import com.google.bigtable.v1.MutateRowRequest; import com.google.bigtable.v1.Mutation; +import com.google.bigtable.v1.ReadRowsRequest; +import com.google.bigtable.v1.Row; +import com.google.bigtable.v1.RowRange; +import com.google.bigtable.v1.SampleRowKeysRequest; +import com.google.bigtable.v1.SampleRowKeysResponse; import com.google.cloud.bigtable.config.BigtableOptions; import com.google.cloud.bigtable.grpc.BigtableSession; import com.google.cloud.bigtable.grpc.async.AsyncExecutor; import com.google.cloud.bigtable.grpc.async.HeapSizeManager; +import com.google.cloud.bigtable.grpc.scanner.ResultScanner; +import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.base.MoreObjects; +import com.google.common.io.Closer; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.ByteString; import com.google.protobuf.Empty; @@ -35,6 +43,8 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.List; +import java.util.NoSuchElementException; /** * An implementation of {@link BigtableService} that actually communicates with the Cloud Bigtable @@ -86,7 +96,75 @@ public boolean tableExists(String tableId) throws IOException { } } - private class BigtableWriterImpl implements Writer { + private class BigtableReaderImpl implements Reader { + private BigtableSession session; + private final BigtableSource source; + private ResultScanner results; + private Row currentRow; + + public BigtableReaderImpl(BigtableSession session, BigtableSource source) { + this.session = session; + this.source = source; + } + + @Override + public boolean start() throws IOException { + RowRange range = + RowRange.newBuilder() + .setStartKey(source.getRange().getStartKey().getValue()) + .setEndKey(source.getRange().getEndKey().getValue()) + .build(); + ReadRowsRequest.Builder requestB = + ReadRowsRequest.newBuilder() + .setRowRange(range) + .setTableName(options.getClusterName().toTableNameStr(source.getTableId())); + if (source.getRowFilter() != null) { + requestB.setFilter(source.getRowFilter()); + } + results = session.getDataClient().readRows(requestB.build()); + return advance(); + } + + @Override + public boolean advance() throws IOException { + currentRow = results.next(); + return (currentRow != null); + } + + @Override + public void close() throws IOException { + // Goal: by the end of this function, both results and session are null and closed, + // independent of what errors they throw or prior state. + + if (session == null) { + // Only possible when previously closed, so we know that results is also null. + return; + } + + // Session does not implement Closeable -- it's AutoCloseable. So we can't register it with + // the Closer, but we can use the Closer to simplify the error handling. + try (Closer closer = Closer.create()) { + if (results != null) { + closer.register(results); + results = null; + } + + session.close(); + } finally { + session = null; + } + } + + @Override + public Row getCurrentRow() throws NoSuchElementException { + if (currentRow == null) { + throw new NoSuchElementException(); + } + return currentRow; + } + } + + private static class BigtableWriterImpl implements Writer { private BigtableSession session; private AsyncExecutor executor; private final MutateRowRequest.Builder partialBuilder; @@ -143,4 +221,21 @@ public String toString() { .add("options", options) .toString(); } + + @Override + public Reader createReader(BigtableSource source) throws IOException { + BigtableSession session = new BigtableSession(options); + return new BigtableReaderImpl(session, source); + } + + @Override + public List getSampleRowKeys(BigtableSource source) throws IOException { + try (BigtableSession session = new BigtableSession(options)) { + SampleRowKeysRequest request = + SampleRowKeysRequest.newBuilder() + .setTableName(options.getClusterName().toTableNameStr(source.getTableId())) + .build(); + return session.getDataClient().sampleRowKeys(request); + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java index e3a9940a2f..0afac13e29 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -16,22 +16,42 @@ package com.google.cloud.dataflow.sdk.io.bigtable; +import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSourcesEqualReferenceSource; +import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionExhaustive; +import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionFails; +import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Verify.verifyNotNull; +import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import com.google.bigtable.v1.Cell; +import com.google.bigtable.v1.Column; +import com.google.bigtable.v1.Family; import com.google.bigtable.v1.Mutation; import com.google.bigtable.v1.Mutation.SetCell; +import com.google.bigtable.v1.Row; +import com.google.bigtable.v1.RowFilter; +import com.google.bigtable.v1.SampleRowKeysResponse; import com.google.cloud.bigtable.config.BigtableOptions; import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; +import com.google.cloud.dataflow.sdk.io.range.ByteKey; +import com.google.cloud.dataflow.sdk.io.range.ByteKeyRange; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.ByteString; @@ -39,6 +59,7 @@ import org.hamcrest.Matchers; import org.junit.Before; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -46,8 +67,16 @@ import org.junit.runners.JUnit4; import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; +import java.util.SortedMap; +import java.util.TreeMap; import javax.annotation.Nullable; @@ -71,6 +100,10 @@ public class BigtableIOTest { .setClusterId("cluster") .setZoneId("zone") .build(); + private static BigtableIO.Read defaultRead = + BigtableIO.read().withBigtableOptions(BIGTABLE_OPTIONS); + private static BigtableIO.Write defaultWrite = + BigtableIO.write().withBigtableOptions(BIGTABLE_OPTIONS); private Coder>> bigtableCoder; private static final TypeDescriptor>> BIGTABLE_WRITE_TYPE = new TypeDescriptor>>() {}; @@ -78,9 +111,31 @@ public class BigtableIOTest { @Before public void setup() throws Exception { service = new FakeBigtableService(); + defaultRead = defaultRead.withBigtableService(service); + defaultWrite = defaultWrite.withBigtableService(service); bigtableCoder = TestPipeline.create().getCoderRegistry().getCoder(BIGTABLE_WRITE_TYPE); } + @Test + public void testReadBuildsCorrectly() { + BigtableIO.Read read = + BigtableIO.read().withBigtableOptions(BIGTABLE_OPTIONS).withTableId("table"); + assertEquals("project", read.getBigtableOptions().getProjectId()); + assertEquals("cluster", read.getBigtableOptions().getClusterId()); + assertEquals("zone", read.getBigtableOptions().getZoneId()); + assertEquals("table", read.getTableId()); + } + + @Test + public void testReadBuildsCorrectlyInDifferentOrder() { + BigtableIO.Read read = + BigtableIO.read().withTableId("table").withBigtableOptions(BIGTABLE_OPTIONS); + assertEquals("project", read.getBigtableOptions().getProjectId()); + assertEquals("cluster", read.getBigtableOptions().getClusterId()); + assertEquals("zone", read.getBigtableOptions().getZoneId()); + assertEquals("table", read.getTableId()); + } + @Test public void testWriteBuildsCorrectly() { BigtableIO.Write write = @@ -111,7 +166,7 @@ public void testWriteValidationFailsMissingTable() { } @Test - public void testSinkValidationFailsMissingOptions() { + public void testWriteValidationFailsMissingOptions() { BigtableIO.Write write = BigtableIO.write().withTableId("table"); thrown.expect(IllegalArgumentException.class); @@ -120,7 +175,7 @@ public void testSinkValidationFailsMissingOptions() { } /** Helper function to make a single row mutation to be written. */ - private static KV> makeRowWithSetCell(String key, String value) { + private static KV> makeWrite(String key, String value) { ByteString rowKey = ByteString.copyFromUtf8(key); Iterable mutations = ImmutableList.of( @@ -131,11 +186,223 @@ private static KV> makeRowWithSetCell(String key, } /** Helper function to make a single bad row mutation (no set cell). */ - private static KV> makeBadRow(String key) { + private static KV> makeBadWrite(String key) { Iterable mutations = ImmutableList.of(Mutation.newBuilder().build()); return KV.of(ByteString.copyFromUtf8(key), mutations); } + /** Tests that when reading from a non-existent table, the read fails. */ + @Test + public void testReadingFailsTableDoesNotExist() throws Exception { + final String table = "TEST-TABLE"; + + BigtableIO.Read read = + BigtableIO.read() + .withBigtableOptions(BIGTABLE_OPTIONS) + .withTableId(table) + .withBigtableService(service); + + // Exception will be thrown by read.validate() when read is applied. + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(String.format("Table %s does not exist", table)); + + TestPipeline.create().apply(read); + } + + /** Tests that when reading from an empty table, the read succeeds. */ + @Test + public void testReadingEmptyTable() throws Exception { + final String table = "TEST-EMPTY-TABLE"; + service.createTable(table); + + TestPipeline p = TestPipeline.create(); + PCollection rows = p.apply(defaultRead.withTableId(table)); + DataflowAssert.that(rows).empty(); + + p.run(); + logged.verifyInfo(String.format("Closing reader after reading 0 records.")); + } + + /** Tests reading all rows from a table. */ + @Test + public void testReading() throws Exception { + final String table = "TEST-MANY-ROWS-TABLE"; + final int numRows = 1001; + List testRows = makeTableData(table, numRows); + + TestPipeline p = TestPipeline.create(); + PCollection rows = p.apply(defaultRead.withTableId(table)); + DataflowAssert.that(rows).containsInAnyOrder(testRows); + + p.run(); + logged.verifyInfo(String.format("Closing reader after reading %d records.", numRows)); + } + + /** A {@link Predicate} that a {@link Row Row's} key matches the given regex. */ + private static class KeyMatchesRegex implements Predicate { + private final String regex; + + public KeyMatchesRegex(String regex) { + this.regex = regex; + } + + @Override + public boolean apply(@Nullable ByteString input) { + verifyNotNull(input, "input"); + return input.toStringUtf8().matches(regex); + } + } + + /** Tests reading all rows using a filter. */ + @Test + public void testReadingWithFilter() throws Exception { + final String table = "TEST-FILTER-TABLE"; + final int numRows = 1001; + List testRows = makeTableData(table, numRows); + String regex = ".*17.*"; + final KeyMatchesRegex keyPredicate = new KeyMatchesRegex(regex); + Iterable filteredRows = + Iterables.filter( + testRows, + new Predicate() { + @Override + public boolean apply(@Nullable Row input) { + verifyNotNull(input, "input"); + return keyPredicate.apply(input.getKey()); + } + }); + + RowFilter filter = + RowFilter.newBuilder().setRowKeyRegexFilter(ByteString.copyFromUtf8(regex)).build(); + + TestPipeline p = TestPipeline.create(); + PCollection rows = p.apply(defaultRead.withTableId(table).withRowFilter(filter)); + DataflowAssert.that(rows).containsInAnyOrder(filteredRows); + + p.run(); + } + + /** + * Tests dynamic work rebalancing exhaustively. + * + *

    Because this test runs so slowly, it is disabled by default. Re-run when changing the + * {@link BigtableIO.Read} implementation. + */ + @Ignore("Slow. Rerun when changing the implementation.") + @Test + public void testReadingSplitAtFractionExhaustive() throws Exception { + final String table = "TEST-FEW-ROWS-SPLIT-EXHAUSTIVE-TABLE"; + final int numRows = 10; + final int numSamples = 1; + final long bytesPerRow = 1L; + makeTableData(table, numRows); + service.setupSampleRowKeys(table, numSamples, bytesPerRow); + + BigtableSource source = + new BigtableSource(service, table, null, service.getTableRange(table), null); + assertSplitAtFractionExhaustive(source, null); + } + + /** + * Unit tests of splitAtFraction. + */ + @Test + public void testReadingSplitAtFraction() throws Exception { + final String table = "TEST-SPLIT-AT-FRACTION"; + final int numRows = 10; + final int numSamples = 1; + final long bytesPerRow = 1L; + makeTableData(table, numRows); + service.setupSampleRowKeys(table, numSamples, bytesPerRow); + + BigtableSource source = + new BigtableSource(service, table, null, service.getTableRange(table), null); + // With 0 items read, all split requests will fail. + assertSplitAtFractionFails(source, 0, 0.1, null /* options */); + assertSplitAtFractionFails(source, 0, 1.0, null /* options */); + // With 1 items read, all split requests past 1/10th will succeed. + assertSplitAtFractionSucceedsAndConsistent(source, 1, 0.333, null /* options */); + assertSplitAtFractionSucceedsAndConsistent(source, 1, 0.666, null /* options */); + // With 3 items read, all split requests past 3/10ths will succeed. + assertSplitAtFractionFails(source, 3, 0.2, null /* options */); + assertSplitAtFractionSucceedsAndConsistent(source, 3, 0.571, null /* options */); + assertSplitAtFractionSucceedsAndConsistent(source, 3, 0.9, null /* options */); + // With 6 items read, all split requests past 6/10ths will succeed. + assertSplitAtFractionFails(source, 6, 0.5, null /* options */); + assertSplitAtFractionSucceedsAndConsistent(source, 6, 0.7, null /* options */); + } + + /** Tests reading all rows from a split table. */ + @Test + public void testReadingWithSplits() throws Exception { + final String table = "TEST-MANY-ROWS-SPLITS-TABLE"; + final int numRows = 1500; + final int numSamples = 10; + final long bytesPerRow = 100L; + + // Set up test table data and sample row keys for size estimation and splitting. + makeTableData(table, numRows); + service.setupSampleRowKeys(table, numSamples, bytesPerRow); + + // Generate source and split it. + BigtableSource source = + new BigtableSource(service, table, null /*filter*/, ByteKeyRange.ALL_KEYS, null /*size*/); + List splits = + source.splitIntoBundles(numRows * bytesPerRow / numSamples, null /* options */); + + // Test num splits and split equality. + assertThat(splits, hasSize(numSamples)); + assertSourcesEqualReferenceSource(source, splits, null /* options */); + } + + /** Tests reading all rows from a sub-split table. */ + @Test + public void testReadingWithSubSplits() throws Exception { + final String table = "TEST-MANY-ROWS-SPLITS-TABLE"; + final int numRows = 1000; + final int numSamples = 10; + final int numSplits = 20; + final long bytesPerRow = 100L; + + // Set up test table data and sample row keys for size estimation and splitting. + makeTableData(table, numRows); + service.setupSampleRowKeys(table, numSamples, bytesPerRow); + + // Generate source and split it. + BigtableSource source = + new BigtableSource(service, table, null /*filter*/, ByteKeyRange.ALL_KEYS, null /*size*/); + List splits = source.splitIntoBundles(numRows * bytesPerRow / numSplits, null); + + // Test num splits and split equality. + assertThat(splits, hasSize(numSplits)); + assertSourcesEqualReferenceSource(source, splits, null /* options */); + } + + /** Tests reading all rows from a sub-split table. */ + @Test + public void testReadingWithFilterAndSubSplits() throws Exception { + final String table = "TEST-FILTER-SUB-SPLITS"; + final int numRows = 1700; + final int numSamples = 10; + final int numSplits = 20; + final long bytesPerRow = 100L; + + // Set up test table data and sample row keys for size estimation and splitting. + makeTableData(table, numRows); + service.setupSampleRowKeys(table, numSamples, bytesPerRow); + + // Generate source and split it. + RowFilter filter = + RowFilter.newBuilder().setRowKeyRegexFilter(ByteString.copyFromUtf8(".*17.*")).build(); + BigtableSource source = + new BigtableSource(service, table, filter, ByteKeyRange.ALL_KEYS, null /*size*/); + List splits = source.splitIntoBundles(numRows * bytesPerRow / numSplits, null); + + // Test num splits and split equality. + assertThat(splits, hasSize(numSplits)); + assertSourcesEqualReferenceSource(source, splits, null /* options */); + } + /** Tests that a record gets written to the service and messages are logged. */ @Test public void testWriting() throws Exception { @@ -145,15 +412,9 @@ public void testWriting() throws Exception { service.createTable(table); - BigtableIO.Write write = - BigtableIO.write() - .withBigtableOptions(BIGTABLE_OPTIONS) - .withTableId(table) - .withBigtableService(service); - TestPipeline p = TestPipeline.create(); - p.apply("single row", Create.of(makeRowWithSetCell(key, value)).withCoder(bigtableCoder)) - .apply("write", write); + p.apply("single row", Create.of(makeWrite(key, value)).withCoder(bigtableCoder)) + .apply("write", defaultWrite.withTableId(table)); p.run(); logged.verifyInfo("Wrote 1 records"); @@ -170,12 +431,6 @@ public void testWriting() throws Exception { public void testWritingFailsTableDoesNotExist() throws Exception { final String table = "TEST-TABLE"; - BigtableIO.Write write = - BigtableIO.write() - .withBigtableOptions(BIGTABLE_OPTIONS) - .withTableId(table) - .withBigtableService(service); - PCollection>> emptyInput = TestPipeline.create().apply(Create.>>of()); @@ -183,7 +438,7 @@ public void testWritingFailsTableDoesNotExist() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format("Table %s does not exist", table)); - emptyInput.apply("write", write); + emptyInput.apply("write", defaultWrite.withTableId(table)); } /** Tests that when writing an element fails, the write fails. */ @@ -193,14 +448,9 @@ public void testWritingFailsBadElement() throws Exception { final String key = "KEY"; service.createTable(table); - BigtableIO.Write write = - BigtableIO.write() - .withBigtableOptions(BIGTABLE_OPTIONS) - .withTableId(table) - .withBigtableService(service); - TestPipeline p = TestPipeline.create(); - p.apply(Create.of(makeBadRow(key)).withCoder(bigtableCoder)).apply(write); + p.apply(Create.of(makeBadWrite(key)).withCoder(bigtableCoder)) + .apply(defaultWrite.withTableId(table)); thrown.expect(PipelineExecutionException.class); thrown.expectCause(Matchers.instanceOf(IOException.class)); @@ -209,19 +459,59 @@ public void testWritingFailsBadElement() throws Exception { p.run(); } + //////////////////////////////////////////////////////////////////////////////////////////// + private static final String COLUMN_FAMILY_NAME = "family"; + private static final ByteString COLUMN_NAME = ByteString.copyFromUtf8("column"); + private static final Column TEST_COLUMN = Column.newBuilder().setQualifier(COLUMN_NAME).build(); + private static final Family TEST_FAMILY = Family.newBuilder().setName(COLUMN_FAMILY_NAME).build(); + + /** Helper function that builds a {@link Row} in a test table that could be returned by read. */ + private static Row makeRow(ByteString key, ByteString value) { + // Build the currentRow and return true. + Column.Builder newColumn = TEST_COLUMN.toBuilder().addCells(Cell.newBuilder().setValue(value)); + return Row.newBuilder() + .setKey(key) + .addFamilies(TEST_FAMILY.toBuilder().addColumns(newColumn)) + .build(); + } + + /** Helper function to create a table and return the rows that it created. */ + private static List makeTableData(String tableId, int numRows) { + service.createTable(tableId); + Map testData = service.getTable(tableId); + + List testRows = new ArrayList<>(numRows); + for (int i = 0; i < numRows; ++i) { + ByteString key = ByteString.copyFromUtf8(String.format("key%09d", i)); + ByteString value = ByteString.copyFromUtf8(String.format("value%09d", i)); + testData.put(key, value); + testRows.add(makeRow(key, value)); + } + + return testRows; + } + + /** * A {@link BigtableService} implementation that stores tables and their contents in memory. */ private static class FakeBigtableService implements BigtableService { - private final Map> tables = new HashMap<>(); + private final Map> tables = new HashMap<>(); + private final Map> sampleRowKeys = new HashMap<>(); @Nullable - public Map getTable(String tableId) { + public SortedMap getTable(String tableId) { return tables.get(tableId); } + public ByteKeyRange getTableRange(String tableId) { + verifyTableExists(tableId); + SortedMap data = tables.get(tableId); + return ByteKeyRange.of(ByteKey.of(data.firstKey()), ByteKey.of(data.lastKey())); + } + public void createTable(String tableId) { - tables.put(tableId, new HashMap()); + tables.put(tableId, new TreeMap(new ByteStringComparator())); } @Override @@ -229,11 +519,127 @@ public boolean tableExists(String tableId) { return tables.containsKey(tableId); } + public void verifyTableExists(String tableId) { + checkArgument(tableExists(tableId), "Table %s does not exist", tableId); + } + + @Override + public FakeBigtableReader createReader(BigtableSource source) { + return new FakeBigtableReader(source); + } + @Override public FakeBigtableWriter openForWriting(String tableId) { - checkArgument(tableExists(tableId), "Table %s does not exist", tableId); return new FakeBigtableWriter(tableId); } + + @Override + public List getSampleRowKeys(BigtableSource source) { + List samples = sampleRowKeys.get(source.getTableId()); + checkArgument(samples != null, "No samples found for table %s", source.getTableId()); + return samples; + } + + /** Sets up the sample row keys for the specified table. */ + void setupSampleRowKeys(String tableId, int numSamples, long bytesPerRow) { + verifyTableExists(tableId); + checkArgument(numSamples > 0, "Number of samples must be positive: %s", numSamples); + checkArgument(bytesPerRow > 0, "Bytes/Row must be positive: %s", bytesPerRow); + + ImmutableList.Builder ret = ImmutableList.builder(); + SortedMap rows = getTable(tableId); + int currentSample = 1; + int rowsSoFar = 0; + for (Map.Entry entry : rows.entrySet()) { + if (((double) rowsSoFar) / rows.size() >= ((double) currentSample) / numSamples) { + // add the sample with the total number of bytes in the table before this key. + ret.add( + SampleRowKeysResponse.newBuilder() + .setRowKey(entry.getKey()) + .setOffsetBytes(rowsSoFar * bytesPerRow) + .build()); + // Move on to next sample + currentSample++; + } + ++rowsSoFar; + } + + // Add the last sample indicating the end of the table, with all rows before it. + ret.add(SampleRowKeysResponse.newBuilder().setOffsetBytes(rows.size() * bytesPerRow).build()); + sampleRowKeys.put(tableId, ret.build()); + } + } + + /** + * A {@link BigtableService.Reader} implementation that reads from the static instance of + * {@link FakeBigtableService} stored in {@link #service}. + * + *

    This reader does not support {@link RowFilter} objects. + */ + private static class FakeBigtableReader implements BigtableService.Reader { + private final BigtableSource source; + private Iterator> rows; + private Row currentRow; + private Predicate filter; + + public FakeBigtableReader(BigtableSource source) { + this.source = source; + if (source.getRowFilter() == null) { + filter = Predicates.alwaysTrue(); + } else { + ByteString keyRegex = source.getRowFilter().getRowKeyRegexFilter(); + checkArgument(!keyRegex.isEmpty(), "Only RowKeyRegexFilter is supported"); + filter = new KeyMatchesRegex(keyRegex.toStringUtf8()); + } + service.verifyTableExists(source.getTableId()); + } + + @Override + public boolean start() { + rows = service.tables.get(source.getTableId()).entrySet().iterator(); + return advance(); + } + + @Override + public boolean advance() { + // Loop until we find a row in range, or reach the end of the iterator. + Map.Entry entry = null; + while (rows.hasNext()) { + entry = rows.next(); + if (!filter.apply(entry.getKey()) + || !source.getRange().containsKey(ByteKey.of(entry.getKey()))) { + // Does not match row filter or does not match source range. Skip. + entry = null; + continue; + } + // Found a row inside this source's key range, stop. + break; + } + + // Return false if no more rows. + if (entry == null) { + currentRow = null; + return false; + } + + // Set the current row and return true. + currentRow = makeRow(entry.getKey(), entry.getValue()); + return true; + } + + @Override + public Row getCurrentRow() { + if (currentRow == null) { + throw new NoSuchElementException(); + } + return currentRow; + } + + @Override + public void close() { + rows = null; + currentRow = null; + } } /** @@ -255,6 +661,7 @@ public FakeBigtableWriter(String tableId) { @Override public ListenableFuture writeRecord(KV> record) { + service.verifyTableExists(tableId); Map table = service.getTable(tableId); ByteString key = record.getKey(); for (Mutation m : record.getValue()) { @@ -270,4 +677,12 @@ public ListenableFuture writeRecord(KV> re @Override public void close() {} } + + /** A serializable comparator for ByteString. Used to make row samples. */ + private static final class ByteStringComparator implements Comparator, Serializable { + @Override + public int compare(ByteString o1, ByteString o2) { + return ByteKey.of(o1).compareTo(ByteKey.of(o2)); + } + } } From 09d755d92a08145efd7830992e2e2f972e3d51d7 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Thu, 18 Feb 2016 08:43:43 -0800 Subject: [PATCH 163/751] ApproximateUnique[Test]: improve efficiency and cleanup test ApproximateUnique: *) Save a copy (and memory) in ApproximateUnique itself (~25% efficiency). ApproximateUniqueTest: *) Only set up the list of data to read once (~2%). *) Reduce the number of copies of the input data by a factor of 10 (~50%). *) Remove the local re-implementation of Count.globally. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114967356 --- .../sdk/transforms/ApproximateUnique.java | 14 ++-- .../sdk/transforms/ApproximateUniqueTest.java | 73 ++++--------------- 2 files changed, 24 insertions(+), 63 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java index f662486e3e..3c936a2b13 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java @@ -26,8 +26,9 @@ import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.hash.Hashing; +import com.google.common.hash.HashingOutputStream; +import com.google.common.io.ByteStreams; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; @@ -397,11 +398,12 @@ public Coder getAccumulatorCoder(CoderRegistry registry, /** * Encodes the given element using the given coder and hashes the encoding. */ - static long hash(T element, Coder coder) - throws CoderException, IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - coder.encode(element, baos, Context.OUTER); - return Hashing.murmur3_128().hashBytes(baos.toByteArray()).asLong(); + static long hash(T element, Coder coder) throws CoderException, IOException { + try (HashingOutputStream stream = + new HashingOutputStream(Hashing.murmur3_128(), ByteStreams.nullOutputStream())) { + coder.encode(element, stream, Context.OUTER); + return stream.hash().asLong(); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java index 66c679b1bb..39731bb931 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; @@ -200,17 +199,16 @@ public void testApproximateUniqueGetName() { * Applies {@code ApproximateUnique(sampleSize)} verifying that the estimation * error falls within the maximum allowed error of {@code 2/sqrt(sampleSize)}. */ - private void runApproximateUniquePipeline(int sampleSize) { + private static void runApproximateUniquePipeline(int sampleSize) { Pipeline p = TestPipeline.create(); - PCollection collection = readPCollection(p); - final PCollectionView exact = collection - .apply(RemoveDuplicates.create()) - .apply(Combine.globally(new CountElements())) - .apply(View.asSingleton()); - - PCollection approximate = collection - .apply(ApproximateUnique.globally(sampleSize)); + PCollection input = p.apply(Create.of(TEST_LINES)); + PCollection approximate = input.apply(ApproximateUnique.globally(sampleSize)); + final PCollectionView exact = + input + .apply(RemoveDuplicates.create()) + .apply(Count.globally()) + .apply(View.asSingleton()); PCollection> approximateAndExact = approximate .apply(ParDo.of(new DoFn>() { @@ -221,26 +219,19 @@ public void processElement(ProcessContext c) { }) .withSideInputs(exact)); - DataflowAssert.that(approximateAndExact) - .satisfies(new VerifyEstimatePerKeyFn(sampleSize)); + DataflowAssert.that(approximateAndExact).satisfies(new VerifyEstimatePerKeyFn(sampleSize)); p.run(); } - /** - * Reads a large {@code PCollection}. - */ - private PCollection readPCollection(Pipeline p) { - // TODO: Read PCollection from a set of text files. - List page = TestUtils.LINES; - final int pages = 1000; - ArrayList file = new ArrayList<>(pages * page.size()); - for (int i = 0; i < pages; i++) { - file.addAll(page); + private static final int TEST_PAGES = 100; + private static final List TEST_LINES = + new ArrayList<>(TEST_PAGES * TestUtils.LINES.size()); + + static { + for (int i = 0; i < TEST_PAGES; i++) { + TEST_LINES.addAll(TestUtils.LINES); } - assert file.size() == pages * page.size(); - PCollection words = p.apply(Create.of(file)); - return words; } /** @@ -297,36 +288,4 @@ public Void apply(Iterable> estimatePerKey) { return null; } } - - /** - * Combiner function counting the number of elements in an input PCollection. - * - * @param the type of elements in the input PCollection. - */ - private static class CountElements extends CombineFn { - - @Override - public Long createAccumulator() { - return 0L; - } - - @Override - public Long addInput(Long accumulator, T input) { - return accumulator + 1; - } - - @Override - public Long mergeAccumulators(Iterable accumulators) { - long sum = 0; - for (Long accumulator : accumulators) { - sum += accumulator; - } - return sum; - } - - @Override - public Long extractOutput(Long accumulator) { - return accumulator; - } - } } From ede5bacd6acf1f73d8dc118131fb9aa3662d8402 Mon Sep 17 00:00:00 2001 From: swegner Date: Thu, 18 Feb 2016 08:43:54 -0800 Subject: [PATCH 164/751] Refactor to use try-with-resources ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114967372 --- .../cloud/dataflow/sdk/util/ZipFilesTest.java | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java index d9e370bdd2..8c079a6bd5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java @@ -165,18 +165,13 @@ public void testAsByteSource() throws Exception { ZipFiles.zipDirectory(tmpDir, zipFile); - ZipFile zip = new ZipFile(zipFile); - try { + try (ZipFile zip = new ZipFile(zipFile)) { ZipEntry entry = zip.getEntry("zip/myTextFile.txt"); ByteSource byteSource = ZipFiles.asByteSource(zip, entry); - if (entry.getSize() != -1) { assertEquals(entry.getSize(), byteSource.size()); } - assertArrayEquals("Simple Text".getBytes(StandardCharsets.UTF_8), byteSource.read()); - } finally { - zip.close(); } } @@ -188,25 +183,18 @@ public void testAsCharSource() throws Exception { ZipFiles.zipDirectory(tmpDir, zipFile); - ZipFile zip = new ZipFile(zipFile); - try { + try (ZipFile zip = new ZipFile(zipFile)) { ZipEntry entry = zip.getEntry("zip/myTextFile.txt"); CharSource charSource = ZipFiles.asCharSource(zip, entry, StandardCharsets.UTF_8); assertEquals("Simple Text", charSource.read()); - } finally { - zip.close(); } } private void assertZipOnlyContains(String zipFileEntry) throws IOException { - ZipFile zippedFile = new ZipFile(zipFile); - try { + try (ZipFile zippedFile = new ZipFile(zipFile)) { assertEquals(1, zippedFile.size()); - ZipEntry entry = zippedFile.entries().nextElement(); assertEquals(zipFileEntry, entry.getName()); - } finally { - zippedFile.close(); } } From 72e436f7033adbb12b09146e60cf20a15ca2bad7 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Thu, 18 Feb 2016 09:09:42 -0800 Subject: [PATCH 165/751] StateSamplerTest: fewer repeats per reused counter name Speed up test. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114969466 --- .../com/google/cloud/dataflow/sdk/util/common/CounterSet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java index 873add4c85..9e9638ff33 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java @@ -82,7 +82,7 @@ public synchronized Counter addOrReuseCounter(Counter counter) { if (counter.isCompatibleWith(oldCounter)) { // Return the counter to reuse. @SuppressWarnings("unchecked") - Counter compatibleCounter = (Counter) oldCounter; + Counter compatibleCounter = (Counter) oldCounter; return compatibleCounter; } throw new IllegalArgumentException( From 570894535dc8e145ad9d8d8bba5f86b4151b685e Mon Sep 17 00:00:00 2001 From: tgroh Date: Thu, 18 Feb 2016 09:31:46 -0800 Subject: [PATCH 166/751] Add InProcessSideInputContainer This is responsible for receiving the input elements of a PCollectionView and producing the view as a SideInput. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114971466 --- .../inprocess/InProcessPipelineRunner.java | 14 + .../InProcessSideInputContainer.java | 207 ++++++++++ .../sdk/util/PCollectionViewWindow.java | 67 ++++ .../InProcessSideInputContainerTest.java | 356 ++++++++++++++++++ 4 files changed, 644 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 10ac123143..7747839d0b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -23,17 +23,21 @@ import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.TimerInternals; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PValue; import org.joda.time.Instant; @@ -234,6 +238,16 @@ PCollectionViewWriter createPCollectionViewWriter( */ SideInputReader createSideInputReader(List> sideInputs); + /** + * Schedules a callback after the watermark for a {@link PValue} after the trigger for the + * specified window (with the specified windowing strategy) must have fired from the perspective + * of that {@link PValue}, as specified by the value of + * {@link Trigger#getWatermarkThatGuaranteesFiring(BoundedWindow)} for the trigger of the + * {@link WindowingStrategy}. + */ + void callAfterOutputMustHaveBeenProduced(PValue value, BoundedWindow window, + WindowingStrategy windowingStrategy, Runnable runnable); + /** * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent * of all other {@link CounterSet CounterSets} created by this call. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java new file mode 100644 index 0000000000..bf9a2e1c53 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -0,0 +1,207 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; +import com.google.cloud.dataflow.sdk.util.SideInputReader; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.common.base.MoreObjects; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import com.google.common.util.concurrent.SettableFuture; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutionException; + +import javax.annotation.Nullable; + +/** + * An in-process container for {@link PCollectionView PCollectionViews}, which provides methods for + * constructing {@link SideInputReader SideInputReaders} which block until a side input is + * available and writing to a {@link PCollectionView}. + */ +class InProcessSideInputContainer { + private final InProcessEvaluationContext evaluationContext; + private final Collection> containedViews; + private final LoadingCache, + SettableFuture>>> viewByWindows; + + /** + * Create a new {@link InProcessSideInputContainer} with the provided views and the provided + * context. + */ + public static InProcessSideInputContainer create( + InProcessEvaluationContext context, Collection> containedViews) { + CacheLoader, SettableFuture>>> + loader = new CacheLoader, + SettableFuture>>>() { + @Override + public SettableFuture>> load( + PCollectionViewWindow view) { + return SettableFuture.create(); + } + }; + LoadingCache, SettableFuture>>> + viewByWindows = CacheBuilder.newBuilder().build(loader); + return new InProcessSideInputContainer(context, containedViews, viewByWindows); + } + + private InProcessSideInputContainer(InProcessEvaluationContext context, + Collection> containedViews, + LoadingCache, SettableFuture>>> + viewByWindows) { + this.evaluationContext = context; + this.containedViews = ImmutableSet.copyOf(containedViews); + this.viewByWindows = viewByWindows; + } + + /** + * Return a view of this {@link InProcessSideInputContainer} that contains only the views in + * the provided argument. The returned {@link InProcessSideInputContainer} is unmodifiable without + * casting, but will change as this {@link InProcessSideInputContainer} is modified. + */ + public SideInputReader withViews(Collection> newContainedViews) { + if (!containedViews.containsAll(newContainedViews)) { + Set> currentlyContained = ImmutableSet.copyOf(containedViews); + Set> newRequested = ImmutableSet.copyOf(newContainedViews); + throw new IllegalArgumentException("Can't create a SideInputReader with unknown views " + + Sets.difference(newRequested, currentlyContained)); + } + return new SideInputContainerSideInputReader(newContainedViews); + } + + /** + * Write the provided values to the provided view. + * + *

    The windowed values are first exploded, then for each window the pane is determined. For + * each window, if the pane is later than the current pane stored within this container, write + * all of the values to the container as the new values of the {@link PCollectionView}. + * + *

    The provided iterable is expected to contain only a single window and pane. + */ + public void write(PCollectionView view, Iterable> values) + throws ExecutionException { + Map>> valuesPerWindow = new HashMap<>(); + for (WindowedValue value : values) { + for (BoundedWindow window : value.getWindows()) { + Collection> windowValues = valuesPerWindow.get(window); + if (windowValues == null) { + windowValues = new ArrayList<>(); + valuesPerWindow.put(window, windowValues); + } + windowValues.add(value); + } + } + for (Map.Entry>> windowValues : + valuesPerWindow.entrySet()) { + PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, windowValues.getKey()); + SettableFuture>> future = viewByWindows.get(windowedView); + if (future.isDone()) { + try { + Iterator> existingValues = future.get().iterator(); + PaneInfo newPane = windowValues.getValue().iterator().next().getPane(); + // The current value may have no elements, if no elements were produced for the window, + // but we are recieving late data. + if (!existingValues.hasNext() + || newPane.getIndex() > existingValues.next().getPane().getIndex()) { + viewByWindows.invalidate(windowedView); + viewByWindows.get(windowedView).set(windowValues.getValue()); + } + } catch (InterruptedException e) { + // TODO: Handle meaningfully. This should never really happen when the result remains + // useful, but the result could be available and the thread can still be interrupted. + Thread.currentThread().interrupt(); + } + } else { + future.set(windowValues.getValue()); + } + } + } + + private final class SideInputContainerSideInputReader implements SideInputReader { + private final Collection> readerViews; + + private SideInputContainerSideInputReader(Collection> readerViews) { + this.readerViews = ImmutableSet.copyOf(readerViews); + } + + @Override + @Nullable + public T get(final PCollectionView view, final BoundedWindow window) { + checkArgument( + readerViews.contains(view), "calling get(PCollectionView) with unknown view: " + view); + PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, window); + try { + final SettableFuture>> future = + viewByWindows.get(windowedView); + + WindowingStrategy windowingStrategy = view.getWindowingStrategyInternal(); + evaluationContext.callAfterOutputMustHaveBeenProduced( + view, window, windowingStrategy, new Runnable() { + @Override + public void run() { + // The requested window has closed without producing elements, so reflect that in + // the PCollectionView. If set has already been called, will do nothing. + future.set(Collections.>emptyList()); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper("InProcessSideInputContainerEmptyCallback") + .add("view", view) + .add("window", window) + .toString(); + } + }); + // Safe covariant cast + @SuppressWarnings("unchecked") + Iterable> values = (Iterable>) future.get(); + return view.fromIterableInternal(values); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } catch (ExecutionException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean contains(PCollectionView view) { + return readerViews.contains(view); + } + + @Override + public boolean isEmpty() { + return readerViews.isEmpty(); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java new file mode 100644 index 0000000000..7cf636eb63 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.values.PCollectionView; + +import java.util.Objects; + +/** + * A pair of a {@link PCollectionView} and a {@link BoundedWindow}, which can + * be thought of as window "of" the view. This is a value class for use e.g. + * as a compound cache key. + * + * @param the type of the underlying PCollectionView + */ +public final class PCollectionViewWindow { + + private final PCollectionView view; + private final BoundedWindow window; + + private PCollectionViewWindow(PCollectionView view, BoundedWindow window) { + this.view = view; + this.window = window; + } + + public static PCollectionViewWindow of(PCollectionView view, BoundedWindow window) { + return new PCollectionViewWindow<>(view, window); + } + + public PCollectionView getView() { + return view; + } + + public BoundedWindow getWindow() { + return window; + } + + @Override + public boolean equals(Object otherObject) { + if (!(otherObject instanceof PCollectionViewWindow)) { + return false; + } + @SuppressWarnings("unchecked") + PCollectionViewWindow other = (PCollectionViewWindow) otherObject; + return getView().equals(other.getView()) && getWindow().equals(other.getWindow()); + } + + @Override + public int hashCode() { + return Objects.hash(getView(), getWindow()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java new file mode 100644 index 0000000000..4cfe782936 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java @@ -0,0 +1,356 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doAnswer; + +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.Mean; +import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.cloud.dataflow.sdk.util.PCollectionViews; +import com.google.cloud.dataflow.sdk.util.SideInputReader; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.common.collect.ImmutableList; + +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/** + * Tests for {@link InProcessSideInputContainer}. + */ +@RunWith(JUnit4.class) +public class InProcessSideInputContainerTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Mock + private InProcessEvaluationContext context; + + private TestPipeline pipeline; + + private InProcessSideInputContainer container; + + private PCollectionView> mapView; + private PCollectionView singletonView; + + // Not present in container. + private PCollectionView> iterableView; + + private BoundedWindow firstWindow = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(789541L); + } + + @Override + public String toString() { + return "firstWindow"; + } + }; + + private BoundedWindow secondWindow = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(14564786L); + } + + @Override + public String toString() { + return "secondWindow"; + } + }; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + pipeline = TestPipeline.create(); + + PCollection create = + pipeline.apply("forBaseCollection", Create.of(1, 2, 3, 4)); + + mapView = + create.apply("forKeyTypes", WithKeys.of("foo")) + .apply("asMapView", View.asMap()); + + singletonView = + create.apply("forCombinedTypes", Mean.globally()) + .apply("asDoubleView", View.asSingleton()); + + iterableView = create.apply("asIterableView", View.asIterable()); + + container = InProcessSideInputContainer.create( + context, ImmutableList.of(iterableView, mapView, singletonView)); + } + + @Test + public void getAfterWriteReturnsPaneInWindow() throws Exception { + WindowedValue> one = WindowedValue.of( + KV.of("one", 1), new Instant(1L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue> two = WindowedValue.of( + KV.of("two", 2), new Instant(20L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + container.write(mapView, ImmutableList.>of(one, two)); + + Map viewContents = + container.withViews(ImmutableList.>of(mapView)) + .get(mapView, firstWindow); + assertThat(viewContents, hasEntry("one", 1)); + assertThat(viewContents, hasEntry("two", 2)); + assertThat(viewContents.size(), is(2)); + } + + @Test + public void getReturnsLatestPaneInWindow() throws Exception { + WindowedValue> one = WindowedValue.of(KV.of("one", 1), new Instant(1L), + secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); + WindowedValue> two = WindowedValue.of(KV.of("two", 2), new Instant(20L), + secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); + container.write(mapView, ImmutableList.>of(one, two)); + + Map viewContents = + container.withViews(ImmutableList.>of(mapView)) + .get(mapView, secondWindow); + assertThat(viewContents, hasEntry("one", 1)); + assertThat(viewContents, hasEntry("two", 2)); + assertThat(viewContents.size(), is(2)); + + WindowedValue> three = WindowedValue.of(KV.of("three", 3), + new Instant(300L), secondWindow, PaneInfo.createPane(false, false, Timing.EARLY, 1, -1)); + container.write(mapView, ImmutableList.>of(three)); + + Map overwrittenViewContents = + container.withViews(ImmutableList.>of(mapView)) + .get(mapView, secondWindow); + assertThat(overwrittenViewContents, hasEntry("three", 3)); + assertThat(overwrittenViewContents.size(), is(1)); + } + + /** + * Demonstrates that calling get() on a window that currently has no data does not return until + * there is data in the pane. + */ + @Test + public void getBlocksUntilPaneAvailable() throws Exception { + BoundedWindow window = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(1024L); + } + }; + Future singletonFuture = + getFutureOfView(container.withViews(ImmutableList.>of(singletonView)), + singletonView, window); + + WindowedValue singletonValue = + WindowedValue.of(4.75, new Instant(475L), window, PaneInfo.ON_TIME_AND_ONLY_FIRING); + + assertThat(singletonFuture.isDone(), is(false)); + container.write(singletonView, ImmutableList.>of(singletonValue)); + assertThat(singletonFuture.get(), equalTo(4.75)); + } + + @Test + public void withPCollectionViewsWithPutInOriginalReturnsContents() throws Exception { + BoundedWindow window = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(1024L); + } + }; + SideInputReader newReader = + container.withViews(ImmutableList.>of(singletonView)); + Future singletonFuture = getFutureOfView(newReader, singletonView, window); + + WindowedValue singletonValue = + WindowedValue.of(24.125, new Instant(475L), window, PaneInfo.ON_TIME_AND_ONLY_FIRING); + + assertThat(singletonFuture.isDone(), is(false)); + container.write(singletonView, ImmutableList.>of(singletonValue)); + assertThat(singletonFuture.get(), equalTo(24.125)); + } + + @Test + public void withPCollectionViewsErrorsForContainsNotInViews() { + PCollectionView>> newView = PCollectionViews.multimapView(pipeline, + WindowingStrategy.globalDefault(), KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("with unknown views " + ImmutableList.of(newView).toString()); + + container.withViews(ImmutableList.>of(newView)); + } + + @Test + public void withViewsForViewNotInContainerFails() { + PCollectionView>> newView = PCollectionViews.multimapView(pipeline, + WindowingStrategy.globalDefault(), KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("unknown views"); + thrown.expectMessage(newView.toString()); + + container.withViews(ImmutableList.>of(newView)); + } + + @Test + public void getOnReaderForViewNotInReaderFails() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("unknown view: " + iterableView.toString()); + + container.withViews(ImmutableList.>of(mapView)) + .get(iterableView, GlobalWindow.INSTANCE); + } + + @Test + public void writeForMultipleElementsInDifferentWindowsSucceeds() throws Exception { + WindowedValue firstWindowedValue = WindowedValue.of(2.875, + firstWindow.maxTimestamp().minus(200L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue secondWindowedValue = + WindowedValue.of(4.125, secondWindow.maxTimestamp().minus(2_000_000L), secondWindow, + PaneInfo.ON_TIME_AND_ONLY_FIRING); + container.write(singletonView, ImmutableList.of(firstWindowedValue, secondWindowedValue)); + assertThat( + container.withViews(ImmutableList.>of(singletonView)) + .get(singletonView, firstWindow), + equalTo(2.875)); + assertThat( + container.withViews(ImmutableList.>of(singletonView)) + .get(singletonView, secondWindow), + equalTo(4.125)); + } + + @Test + public void writeForMultipleIdenticalElementsInSameWindowSucceeds() throws Exception { + WindowedValue firstValue = WindowedValue.of( + 44, firstWindow.maxTimestamp().minus(200L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue secondValue = WindowedValue.of( + 44, firstWindow.maxTimestamp().minus(200L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + + container.write(iterableView, ImmutableList.of(firstValue, secondValue)); + + assertThat( + container.withViews(ImmutableList.>of(iterableView)) + .get(iterableView, firstWindow), + contains(44, 44)); + } + + @Test + public void writeForElementInMultipleWindowsSucceeds() throws Exception { + WindowedValue multiWindowedValue = + WindowedValue.of(2.875, firstWindow.maxTimestamp().minus(200L), + ImmutableList.of(firstWindow, secondWindow), PaneInfo.ON_TIME_AND_ONLY_FIRING); + container.write(singletonView, ImmutableList.of(multiWindowedValue)); + assertThat( + container.withViews(ImmutableList.>of(singletonView)) + .get(singletonView, firstWindow), + equalTo(2.875)); + assertThat( + container.withViews(ImmutableList.>of(singletonView)) + .get(singletonView, secondWindow), + equalTo(2.875)); + } + + @Test + public void finishDoesNotOverwriteWrittenElements() throws Exception { + WindowedValue> one = WindowedValue.of(KV.of("one", 1), new Instant(1L), + secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); + WindowedValue> two = WindowedValue.of(KV.of("two", 2), new Instant(20L), + secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); + container.write(mapView, ImmutableList.>of(one, two)); + + immediatelyInvokeCallback(mapView, secondWindow); + + Map viewContents = + container.withViews(ImmutableList.>of(mapView)) + .get(mapView, secondWindow); + + assertThat(viewContents, hasEntry("one", 1)); + assertThat(viewContents, hasEntry("two", 2)); + assertThat(viewContents.size(), is(2)); + } + + @Test + public void finishOnPendingViewsSetsEmptyElements() throws Exception { + immediatelyInvokeCallback(mapView, secondWindow); + Future> mapFuture = getFutureOfView( + container.withViews(ImmutableList.>of(mapView)), mapView, secondWindow); + + assertThat(mapFuture.get().isEmpty(), is(true)); + } + + /** + * When a callAfterWindowCloses with the specified view's producing transform, window, and + * windowing strategy is invoked, immediately execute the callback. + */ + private void immediatelyInvokeCallback(PCollectionView view, BoundedWindow window) { + doAnswer( + new Answer() { + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + Object callback = invocation.getArguments()[3]; + Runnable callbackRunnable = (Runnable) callback; + callbackRunnable.run(); + return null; + } + }) + .when(context) + .callAfterOutputMustHaveBeenProduced(Mockito.eq(view), Mockito.eq(window), + Mockito.eq(view.getWindowingStrategyInternal()), Mockito.any(Runnable.class)); + } + + private Future getFutureOfView(final SideInputReader myReader, + final PCollectionView view, final BoundedWindow window) { + Callable callable = new Callable() { + @Override + public ValueT call() throws Exception { + return myReader.get(view, window); + } + }; + return Executors.newSingleThreadExecutor().submit(callable); + } +} From 72f838740589258c3faa90f0c635aa364795cbde Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 18 Feb 2016 13:58:59 -0800 Subject: [PATCH 167/751] Update FileIOChannelFactory.expand() to only return file resources This brings FileIOChannelFactory inline with what is occurring in GCSIOChannelFactory and is required since expand is used in FileBasedReader to find matches and FileBasedReader can not tell whether a path is a concrete resource or something else like a dir or symlink. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=114999578 --- .../sdk/util/FileIOChannelFactory.java | 27 +++++--- .../dataflow/sdk/util/IOChannelFactory.java | 3 +- .../sdk/util/FileIOChannelFactoryTest.java | 61 +++++++++++++++++-- 3 files changed, 76 insertions(+), 15 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java index e65d870146..77d0b830cb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java @@ -16,12 +16,15 @@ package com.google.cloud.dataflow.sdk.util; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedOutputStream; import java.io.File; -import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -66,17 +69,21 @@ public Collection match(String spec) throws IOException { String pathToMatch = file.getAbsolutePath().replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("\\\\")); - final PathMatcher matcher = - FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch); - File[] files = parent.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return matcher.matches(pathname.toPath()); - } - }); + final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch); + + Iterable files = com.google.common.io.Files.fileTreeTraverser().preOrderTraversal(parent); + Iterable matchedFiles = Iterables.filter(files, + Predicates.and( + com.google.common.io.Files.isFile(), + new Predicate() { + @Override + public boolean apply(File input) { + return matcher.matches(input.toPath()); + } + })); List result = new LinkedList<>(); - for (File match : files) { + for (File match : matchedFiles) { result.add(match.getPath()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java index 44b8ebd4e0..f7d0b9a27e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java @@ -40,7 +40,8 @@ public interface IOChannelFactory { * all support globs in the final component of a path (eg /foo/bar/*.txt), * however they are not required to support globs in the directory paths. * - *

    The result is the (possibly empty) set of specifications that match. + *

    The list of resources returned are required to exist and not represent abstract + * resources such as symlinks and directories. */ Collection match(String spec) throws IOException; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java index 1a8ab86153..80ec3a1308 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.util; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -54,7 +55,9 @@ private void testCreate(Path path) throws Exception { factory.create(path.toString(), MimeTypes.TEXT), StandardCharsets.UTF_8.name())) { writer.write(expected); } - assertThat(Files.readLines(path.toFile(), StandardCharsets.UTF_8), Matchers.hasItems(expected)); + assertThat( + Files.readLines(path.toFile(), StandardCharsets.UTF_8), + containsInAnyOrder(expected)); } @Test @@ -111,7 +114,7 @@ public void testMatchExact() throws Exception { temporaryFolder.newFile("ab"); assertThat(factory.match(temporaryFolder.getRoot().toPath().resolve("a").toString()), - Matchers.hasItems(expected.toArray(new String[expected.size()]))); + containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test @@ -123,11 +126,32 @@ public void testMatchNone() throws Exception { // Windows doesn't like resolving paths with * in them, so the * is appended after resolve. assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "b") + "*"), - Matchers.hasItems(expected.toArray(new String[expected.size()]))); + containsInAnyOrder(expected.toArray(new String[expected.size()]))); + } + + @Test + public void testMatchUsingExplicitPath() throws Exception { + List expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); + temporaryFolder.newFile("aa"); + + assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a")), + containsInAnyOrder(expected.toArray(new String[expected.size()]))); + } + + @Test + public void testMatchUsingExplicitPathForNonExistentFile() throws Exception { + List expected = ImmutableList.of(); + temporaryFolder.newFile("aa"); + + assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a")), + containsInAnyOrder(expected.toArray(new String[expected.size()]))); } @Test - public void testMatchMultiple() throws Exception { + public void testMatchMultipleWithoutSubdirectoryExpansion() throws Exception { + File unmatchedSubDir = temporaryFolder.newFolder("aaa"); + File unmatchedSubDirFile = File.createTempFile("sub-dir-file", "", unmatchedSubDir); + unmatchedSubDirFile.deleteOnExit(); List expected = ImmutableList.of(temporaryFolder.newFile("a").toString(), temporaryFolder.newFile("aa").toString(), temporaryFolder.newFile("ab").toString()); temporaryFolder.newFile("ba"); @@ -135,9 +159,38 @@ public void testMatchMultiple() throws Exception { // Windows doesn't like resolving paths with * in them, so the * is appended after resolve. assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a") + "*"), + containsInAnyOrder(expected.toArray(new String[expected.size()]))); + } + + @Test + public void testMatchMultipleWithSubdirectoryExpansion() throws Exception { + File matchedSubDir = temporaryFolder.newFolder("a"); + File matchedSubDirFile = File.createTempFile("sub-dir-file", "", matchedSubDir); + matchedSubDirFile.deleteOnExit(); + File unmatchedSubDir = temporaryFolder.newFolder("b"); + File unmatchedSubDirFile = File.createTempFile("sub-dir-file", "", unmatchedSubDir); + unmatchedSubDirFile.deleteOnExit(); + + List expected = ImmutableList.of(matchedSubDirFile.toString(), + temporaryFolder.newFile("aa").toString(), temporaryFolder.newFile("ab").toString()); + temporaryFolder.newFile("ba"); + temporaryFolder.newFile("bb"); + + // Windows doesn't like resolving paths with * in them, so the ** is appended after resolve. + assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a") + "**"), Matchers.hasItems(expected.toArray(new String[expected.size()]))); } + @Test + public void testMatchWithDirectoryFiltersOutDirectory() throws Exception { + List expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); + temporaryFolder.newFolder("a_dir_that_should_not_be_matched"); + + // Windows doesn't like resolving paths with * in them, so the * is appended after resolve. + assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a") + "*"), + containsInAnyOrder(expected.toArray(new String[expected.size()]))); + } + @Test public void testResolve() throws Exception { String expected = temporaryFolder.getRoot().toPath().resolve("aa").toString(); From 9877acc267514a6f95cd380ff0a8e9ca62ff32be Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 18 Feb 2016 16:03:15 -0800 Subject: [PATCH 168/751] Add validation for single objects in GcsUtil.expand We now ensure that GcsUtil.expand with a file pattern that would resolve to a single object will validate that the object exists. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115013446 --- .../cloud/dataflow/sdk/util/GcsUtil.java | 25 +++++-- .../cloud/dataflow/sdk/util/GcsUtilTest.java | 66 ++++++++++++------- 2 files changed, 62 insertions(+), 29 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java index 20a9abedc7..8fd258f6d2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java @@ -137,8 +137,8 @@ protected void setStorageClient(Storage storageClient) { /** * Expands a pattern into matched paths. The pattern path may contain globs, which are expanded - * in the result. This function may return non-existent files so this should not be used to - * validate the existence of files in GCS. + * in the result. For patterns that only match a single object, we ensure that the object + * exists. */ public List expand(GcsPath gcsPattern) throws IOException { Preconditions.checkArgument(isGcsPatternSupported(gcsPattern.getObject())); @@ -147,9 +147,24 @@ public List expand(GcsPath gcsPattern) throws IOException { String prefix = null; if (!m.matches()) { // Not a glob. - // Results of GCS storage list feature is only eventually consistent so we should not use that - // feature to check the existence of single files. - return ImmutableList.of(gcsPattern); + Storage.Objects.Get getObject = storageClient.objects().get( + gcsPattern.getBucket(), gcsPattern.getObject()); + try { + // Use a get request to fetch the metadata of the object, + // the request has strong global consistency. + ResilientOperation.retry( + ResilientOperation.getGoogleRequestCallable(getObject), + new AttemptBoundedExponentialBackOff(3, 200), + RetryDeterminer.SOCKET_ERRORS, + IOException.class); + return ImmutableList.of(gcsPattern); + } catch (IOException | InterruptedException e) { + if (e instanceof IOException && errorExtractor.itemNotFound((IOException) e)) { + // If the path was not found, return an empty list. + return ImmutableList.of(); + } + throw new IOException("Unable to match files for pattern " + gcsPattern, e); + } } else { // Part before the first wildcard character. prefix = m.group("PREFIX"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java index 89a8ef527f..e7cd7d7c22 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java @@ -69,6 +69,7 @@ import java.nio.channels.SeekableByteChannel; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -172,6 +173,7 @@ public void testGlobExpansion() throws IOException { gcsUtil.setStorageClient(mockStorage); Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); + Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); Storage.Objects.List mockStorageList = Mockito.mock(Storage.Objects.List.class); Objects modelObjects = new Objects(); @@ -189,7 +191,11 @@ public void testGlobExpansion() throws IOException { modelObjects.setItems(items); when(mockStorage.objects()).thenReturn(mockStorageObjects); + when(mockStorageObjects.get("testbucket", "testdirectory/otherfile")).thenReturn( + mockStorageGet); when(mockStorageObjects.list("testbucket")).thenReturn(mockStorageList); + when(mockStorageGet.execute()).thenReturn( + new StorageObject().setBucket("testbucket").setName("testdirectory/otherfile")); when(mockStorageList.execute()).thenReturn(modelObjects); // Test a single file. @@ -255,10 +261,10 @@ public void testRecursiveGlobExpansionFails() throws IOException { gcsUtil.expand(pattern); } - // GCSUtil.expand() should not fail for non-existent single files or directories, since GCS file - // listing is only eventually consistent. + // GCSUtil.expand() should fail when matching a single object when that object does not exist. + // We should return the empty result since GCS get object is strongly consistent. @Test - public void testNonExistent() throws IOException { + public void testNonExistentObjectReturnsEmptyResult() throws IOException { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); @@ -266,34 +272,46 @@ public void testNonExistent() throws IOException { gcsUtil.setStorageClient(mockStorage); Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); - Storage.Objects.List mockStorageList = Mockito.mock(Storage.Objects.List.class); - - Objects modelObjects = new Objects(); - List items = new ArrayList<>(); + Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); - // A directory - items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/")); - modelObjects.setItems(items); + GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentfile"); + GoogleJsonResponseException expectedException = + googleJsonResponseException(HttpStatusCodes.STATUS_CODE_NOT_FOUND, + "It don't exist", "Nothing here to see"); when(mockStorage.objects()).thenReturn(mockStorageObjects); - when(mockStorageObjects.list("testbucket")).thenReturn(mockStorageList); - when(mockStorageList.execute()).thenReturn(modelObjects); + when(mockStorageObjects.get(pattern.getBucket(), pattern.getObject())).thenReturn( + mockStorageGet); + when(mockStorageGet.execute()).thenThrow(expectedException); - { - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentfile"); - List expectedFiles = - ImmutableList.of(GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentfile")); + assertEquals(Collections.EMPTY_LIST, gcsUtil.expand(pattern)); + } - assertThat(expectedFiles, contains(gcsUtil.expand(pattern).toArray())); - } + // GCSUtil.expand() should fail for other errors such as access denied. + @Test + public void testAccessDeniedObjectThrowsIOException() throws IOException { + GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); + GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - { - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentdirectory/"); - List expectedFiles = - ImmutableList.of(GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentdirectory/")); + Storage mockStorage = Mockito.mock(Storage.class); + gcsUtil.setStorageClient(mockStorage); - assertThat(expectedFiles, contains(gcsUtil.expand(pattern).toArray())); - } + Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); + Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); + + GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/accessdeniedfile"); + GoogleJsonResponseException expectedException = + googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, + "Waves hand mysteriously", "These aren't the buckets your looking for"); + + when(mockStorage.objects()).thenReturn(mockStorageObjects); + when(mockStorageObjects.get(pattern.getBucket(), pattern.getObject())).thenReturn( + mockStorageGet); + when(mockStorageGet.execute()).thenThrow(expectedException); + + thrown.expect(IOException.class); + thrown.expectMessage("Unable to match files for pattern"); + gcsUtil.expand(pattern); } @Test From 47eec4a4dfb162fafe37f1d4ff9925d8f51448c5 Mon Sep 17 00:00:00 2001 From: peihe Date: Thu, 18 Feb 2016 17:05:29 -0800 Subject: [PATCH 169/751] Rename StateContext to StateAccessor ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115019254 --- .../windowing/AfterDelayFromFirstElement.java | 10 +-- .../sdk/transforms/windowing/AfterPane.java | 8 +-- .../sdk/transforms/windowing/Trigger.java | 16 ++--- .../dataflow/sdk/util/NonEmptyPanes.java | 34 +++++------ .../dataflow/sdk/util/PaneInfoTracker.java | 4 +- .../cloud/dataflow/sdk/util/ReduceFn.java | 14 ++--- .../sdk/util/ReduceFnContextFactory.java | 61 +++++++++---------- .../dataflow/sdk/util/SystemReduceFn.java | 12 ++-- .../sdk/util/TriggerContextFactory.java | 40 ++++++------ .../dataflow/sdk/util/TriggerRunner.java | 28 ++++----- .../dataflow/sdk/util/WatermarkHold.java | 4 +- ...Context.java => MergingStateAccessor.java} | 5 +- .../{StateContext.java => StateAccessor.java} | 5 +- .../dataflow/sdk/util/state/StateMerging.java | 14 ++--- .../dataflow/sdk/util/state/StateTags.java | 2 +- 15 files changed, 128 insertions(+), 129 deletions(-) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/{MergingStateContext.java => MergingStateAccessor.java} (87%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/{StateContext.java => StateAccessor.java} (89%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java index 9c9a0956ab..43e77de6bc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -25,8 +25,8 @@ import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.state.StateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -151,7 +151,7 @@ private AfterDelayFromFirstElement newWith( } @Override - public void prefetchOnElement(StateContext state) { + public void prefetchOnElement(StateAccessor state) { state.access(DELAYED_UNTIL_TAG).get(); } @@ -172,7 +172,7 @@ public void onElement(OnElementContext c) throws Exception { } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateAccessor state) { super.prefetchOnMerge(state); StateMerging.prefetchCombiningValues(state, DELAYED_UNTIL_TAG); } @@ -207,7 +207,7 @@ public void onMerge(OnMergeContext c) throws Exception { } @Override - public void prefetchShouldFire(StateContext state) { + public void prefetchShouldFire(StateAccessor state) { state.access(DELAYED_UNTIL_TAG).get(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java index 79a370757b..729cd3e063 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java @@ -21,8 +21,8 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.state.StateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -66,7 +66,7 @@ public void onElement(OnElementContext c) throws Exception { } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateAccessor state) { super.prefetchOnMerge(state); StateMerging.prefetchCombiningValues(state, ELEMENTS_IN_PANE_TAG); } @@ -86,7 +86,7 @@ public void onMerge(OnMergeContext context) throws Exception { } @Override - public void prefetchShouldFire(StateContext state) { + public void prefetchShouldFire(StateAccessor state) { state.access(ELEMENTS_IN_PANE_TAG).get(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java index 3d4029e298..4471563e70 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java @@ -19,8 +19,8 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.state.StateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.common.base.Joiner; import org.joda.time.Instant; @@ -190,7 +190,7 @@ public abstract class TriggerContext { public abstract TriggerInfo trigger(); /** Returns the interface for accessing persistent state. */ - public abstract StateContext state(); + public abstract StateAccessor state(); /** The window that the current context is executing in. */ public abstract W window(); @@ -265,7 +265,7 @@ public abstract class OnMergeContext extends TriggerContext { public abstract OnMergeContext forTrigger(ExecutableTrigger trigger); @Override - public abstract MergingStateContext state(); + public abstract MergingStateAccessor state(); @Override public abstract MergingTriggerInfo trigger(); @@ -319,7 +319,7 @@ protected Trigger(@Nullable List> subTriggers) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onElement} call. */ - public void prefetchOnElement(StateContext state) { + public void prefetchOnElement(StateAccessor state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnElement(state); @@ -331,7 +331,7 @@ public void prefetchOnElement(StateContext state) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onMerge} call. */ - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateAccessor state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnMerge(state); @@ -343,7 +343,7 @@ public void prefetchOnMerge(MergingStateContext state) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #shouldFire} call. */ - public void prefetchShouldFire(StateContext state) { + public void prefetchShouldFire(StateAccessor state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchShouldFire(state); @@ -355,7 +355,7 @@ public void prefetchShouldFire(StateContext state) { * Called to allow the trigger to prefetch any state it will likely need to read from during * an {@link #onFire} call. */ - public void prefetchOnFire(StateContext state) { + public void prefetchOnFire(StateAccessor state) { if (subTriggers != null) { for (Trigger trigger : subTriggers) { trigger.prefetchOnFire(state); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java index f31d6659a9..4d6131451e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java @@ -20,9 +20,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -48,27 +48,27 @@ static NonEmptyPanes create( * Record that some content has been added to the window in {@code context}, and therefore the * current pane is not empty. */ - public abstract void recordContent(StateContext context); + public abstract void recordContent(StateAccessor context); /** * Record that the given pane is empty. */ - public abstract void clearPane(StateContext state); + public abstract void clearPane(StateAccessor state); /** * Return true if the current pane for the window in {@code context} is empty. */ - public abstract StateContents isEmpty(StateContext context); + public abstract StateContents isEmpty(StateAccessor context); /** * Prefetch in preparation for merging. */ - public abstract void prefetchOnMerge(MergingStateContext state); + public abstract void prefetchOnMerge(MergingStateAccessor state); /** * Eagerly merge backing state. */ - public abstract void onMerge(MergingStateContext context); + public abstract void onMerge(MergingStateAccessor context); /** * An implementation of {@code NonEmptyPanes} optimized for use with discarding mode. Uses the @@ -84,27 +84,27 @@ private DiscardingModeNonEmptyPanes(ReduceFn reduceFn) { } @Override - public StateContents isEmpty(StateContext state) { + public StateContents isEmpty(StateAccessor state) { return reduceFn.isEmpty(state); } @Override - public void recordContent(StateContext state) { + public void recordContent(StateAccessor state) { // Nothing to do -- the reduceFn is tracking contents } @Override - public void clearPane(StateContext state) { + public void clearPane(StateAccessor state) { // Nothing to do -- the reduceFn is tracking contents } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateAccessor state) { // Nothing to do -- the reduceFn is tracking contents } @Override - public void onMerge(MergingStateContext context) { + public void onMerge(MergingStateAccessor context) { // Nothing to do -- the reduceFn is tracking contents } } @@ -121,27 +121,27 @@ private static class GeneralNonEmptyPanes "count", VarLongCoder.of(), new Sum.SumLongFn())); @Override - public void recordContent(StateContext state) { + public void recordContent(StateAccessor state) { state.access(PANE_ADDITIONS_TAG).add(1L); } @Override - public void clearPane(StateContext state) { + public void clearPane(StateAccessor state) { state.access(PANE_ADDITIONS_TAG).clear(); } @Override - public StateContents isEmpty(StateContext state) { + public StateContents isEmpty(StateAccessor state) { return state.access(PANE_ADDITIONS_TAG).isEmpty(); } @Override - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateAccessor state) { StateMerging.prefetchCombiningValues(state, PANE_ADDITIONS_TAG); } @Override - public void onMerge(MergingStateContext context) { + public void onMerge(MergingStateAccessor context) { StateMerging.mergeCombiningValues(context, PANE_ADDITIONS_TAG); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index f0fa9936b0..e66f9a7b0d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -19,8 +19,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.cloud.dataflow.sdk.util.state.ValueState; @@ -46,7 +46,7 @@ public PaneInfoTracker(TimerInternals timerInternals) { static final StateTag> PANE_INFO_TAG = StateTags.makeSystemTagInternal(StateTags.value("pane", PaneInfoCoder.INSTANCE)); - public void clear(StateContext state) { + public void clear(StateAccessor state) { state.access(PANE_INFO_TAG).clear(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java index 1ee86ffa08..ae0913ae4f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java @@ -17,9 +17,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateContext; import org.joda.time.Instant; @@ -48,7 +48,7 @@ public abstract class Context { public abstract WindowingStrategy windowingStrategy(); /** Return the interface for accessing state. */ - public abstract StateContext state(); + public abstract StateAccessor state(); /** Return the interface for accessing timers. */ public abstract Timers timers(); @@ -67,7 +67,7 @@ public abstract class ProcessValueContext extends Context { public abstract class OnMergeContext extends Context { /** Return the interface for accessing state. */ @Override - public abstract MergingStateContext state(); + public abstract MergingStateAccessor state(); } /** Information accessible within {@link #onTrigger}. */ @@ -105,7 +105,7 @@ public abstract class OnTriggerContext extends Context { * * @param c Context to use prefetch from. */ - public void prefetchOnMerge(MergingStateContext c) throws Exception {} + public void prefetchOnMerge(MergingStateAccessor c) throws Exception {} /** * Called before {@link #onTrigger} is invoked to provide an opportunity to prefetch any needed @@ -113,7 +113,7 @@ public void prefetchOnMerge(MergingStateContext c) throws Exception {} * * @param context Context to use prefetch from. */ - public void prefetchOnTrigger(StateContext context) {} + public void prefetchOnTrigger(StateAccessor context) {} /** * Called to clear any persisted state that the {@link ReduceFn} may be holding. This will be @@ -124,5 +124,5 @@ public void prefetchOnTrigger(StateContext context) {} /** * Returns true if the there is no buffered state. */ - public abstract StateContents isEmpty(StateContext context); + public abstract StateContents isEmpty(StateAccessor context); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index e6caf75567..d0296d1ad6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -21,10 +21,10 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; import com.google.cloud.dataflow.sdk.util.state.State; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; @@ -74,8 +74,8 @@ public static enum StateStyle { RENAMED } - private StateContextImpl stateContext(W window, StateStyle style) { - return new StateContextImpl( + private StateAccessorImpl stateContext(W window, StateStyle style) { + return new StateAccessorImpl( activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, window, style); } @@ -97,13 +97,13 @@ public ReduceFn.OnTriggerContext forTrigger(W window, public ReduceFn.OnMergeContext forMerge( Collection activeToBeMerged, W mergeResult, StateStyle style) { return new OnMergeContextImpl( - new MergingStateContextImpl(activeWindows, + new MergingStateAccessorImpl(activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, style, activeToBeMerged, mergeResult)); } public ReduceFn.OnMergeContext forPremerge(W window) { - return new OnPremergeContextImpl(new PremergingStateContextImpl( + return new OnPremergeContextImpl(new PremergingStateAccessorImpl( activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, window)); } @@ -144,10 +144,9 @@ public Instant currentEventTime() { } // ====================================================================== - // StateContexts + // StateAccessors // ====================================================================== - static class StateContextImpl - implements StateContext { + static class StateAccessorImpl implements StateAccessor { protected final ActiveWindowSet activeWindows; @@ -157,7 +156,7 @@ static class StateContextImpl protected final StateInternals stateInternals; protected final StateStyle style; - public StateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, + public StateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, StateInternals stateInternals, W window, StateStyle style) { this.activeWindows = activeWindows; @@ -197,11 +196,11 @@ public StateT access(StateTag address) } } - static class MergingStateContextImpl - extends StateContextImpl implements MergingStateContext { + static class MergingStateAccessorImpl + extends StateAccessorImpl implements MergingStateAccessor { private final Collection activeToBeMerged; - public MergingStateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, + public MergingStateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, StateInternals stateInternals, StateStyle style, Collection activeToBeMerged, W mergeResult) { super(activeWindows, windowCoder, stateInternals, mergeResult, style); @@ -242,9 +241,9 @@ public Map accessInEachMergingWindow( } } - static class PremergingStateContextImpl - extends StateContextImpl implements MergingStateContext { - public PremergingStateContextImpl(ActiveWindowSet activeWindows, Coder windowCoder, + static class PremergingStateAccessorImpl + extends StateAccessorImpl implements MergingStateAccessor { + public PremergingStateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, StateInternals stateInternals, W window) { super(activeWindows, windowCoder, stateInternals, window, StateStyle.RENAMED); } @@ -270,10 +269,10 @@ public Map accessInEachMergingWindow( // ====================================================================== private class ContextImpl extends ReduceFn.Context { - private final StateContextImpl state; + private final StateAccessorImpl state; private final TimersImpl timers; - private ContextImpl(StateContextImpl state) { + private ContextImpl(StateAccessorImpl state) { reduceFn.super(); this.state = state; this.timers = new TimersImpl(state.namespace()); @@ -295,7 +294,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public StateContext state() { + public StateAccessor state() { return state; } @@ -309,10 +308,10 @@ private class ProcessValueContextImpl extends ReduceFn.ProcessValueContext { private final InputT value; private final Instant timestamp; - private final StateContextImpl state; + private final StateAccessorImpl state; private final TimersImpl timers; - private ProcessValueContextImpl(StateContextImpl state, + private ProcessValueContextImpl(StateAccessorImpl state, InputT value, Instant timestamp) { reduceFn.super(); this.state = state; @@ -337,7 +336,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public StateContext state() { + public StateAccessor state() { return state; } @@ -358,12 +357,12 @@ public Timers timers() { } private class OnTriggerContextImpl extends ReduceFn.OnTriggerContext { - private final StateContextImpl state; + private final StateAccessorImpl state; private final StateContents pane; private final OnTriggerCallbacks callbacks; private final TimersImpl timers; - private OnTriggerContextImpl(StateContextImpl state, StateContents pane, + private OnTriggerContextImpl(StateAccessorImpl state, StateContents pane, OnTriggerCallbacks callbacks) { reduceFn.super(); this.state = state; @@ -388,7 +387,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public StateContext state() { + public StateAccessor state() { return state; } @@ -409,10 +408,10 @@ public Timers timers() { } private class OnMergeContextImpl extends ReduceFn.OnMergeContext { - private final MergingStateContextImpl state; + private final MergingStateAccessorImpl state; private final TimersImpl timers; - private OnMergeContextImpl(MergingStateContextImpl state) { + private OnMergeContextImpl(MergingStateAccessorImpl state) { reduceFn.super(); this.state = state; this.timers = new TimersImpl(state.namespace()); @@ -429,7 +428,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public MergingStateContext state() { + public MergingStateAccessor state() { return state; } @@ -445,10 +444,10 @@ public Timers timers() { } private class OnPremergeContextImpl extends ReduceFn.OnMergeContext { - private final PremergingStateContextImpl state; + private final PremergingStateAccessorImpl state; private final TimersImpl timers; - private OnPremergeContextImpl(PremergingStateContextImpl state) { + private OnPremergeContextImpl(PremergingStateAccessorImpl state) { reduceFn.super(); this.state = state; this.timers = new TimersImpl(state.namespace()); @@ -465,7 +464,7 @@ public WindowingStrategy windowingStrategy() { } @Override - public MergingStateContext state() { + public MergingStateAccessor state() { return state; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java index 044847570f..233e1da9a3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java @@ -26,9 +26,9 @@ import com.google.cloud.dataflow.sdk.util.state.BagState; import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateContents; -import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -55,7 +55,7 @@ public abstract class SystemReduceFn, Iterable, W>(bufferTag) { @Override - public void prefetchOnMerge(MergingStateContext state) throws Exception { + public void prefetchOnMerge(MergingStateAccessor state) throws Exception { StateMerging.prefetchBags(state, bufferTag); } @@ -85,7 +85,7 @@ public void onMerge(OnMergeContext c) throws Exception { (KeyedCombineFn) combineFn.getFn())); return new SystemReduceFn(bufferTag) { @Override - public void prefetchOnMerge(MergingStateContext state) throws Exception { + public void prefetchOnMerge(MergingStateAccessor state) throws Exception { StateMerging.prefetchCombiningValues(state, bufferTag); } @@ -109,7 +109,7 @@ public void processValue(ProcessValueContext c) throws Exception { } @Override - public void prefetchOnTrigger(StateContext state) { + public void prefetchOnTrigger(StateAccessor state) { state.access(bufferTag).get(); } @@ -124,7 +124,7 @@ public void clearState(Context c) throws Exception { } @Override - public StateContents isEmpty(StateContext state) { + public StateContents isEmpty(StateAccessor state) { return state.access(bufferTag).isEmpty(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 05cf137e8c..c27e731e8e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -20,9 +20,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergingTriggerInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerInfo; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateContext; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; @@ -80,13 +80,13 @@ public Trigger.OnMergeContext createOnMergeContext(W window, Timers timers, return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, finishedSets); } - public StateContext createStateContext(W window, ExecutableTrigger trigger) { - return new StateContextImpl(window, trigger); + public StateAccessor createStateContext(W window, ExecutableTrigger trigger) { + return new StateAccessorImpl(window, trigger); } - public MergingStateContext createMergingStateContext( + public MergingStateAccessor createMergingStateContext( W mergeResult, Collection mergingWindows, ExecutableTrigger trigger) { - return new MergingStateContextImpl(trigger, mergingWindows, mergeResult); + return new MergingStateAccessorImpl(trigger, mergingWindows, mergeResult); } private class TriggerInfoImpl implements Trigger.TriggerInfo { @@ -260,11 +260,11 @@ public boolean apply(FinishedTriggers finishedSet) { } } - private class StateContextImpl implements StateContext { + private class StateAccessorImpl implements StateAccessor { protected final int triggerIndex; protected final StateNamespace windowNamespace; - public StateContextImpl( + public StateAccessorImpl( W window, ExecutableTrigger trigger) { this.triggerIndex = trigger.getTriggerIndex(); @@ -281,11 +281,11 @@ public StateT access(StateTag add } } - private class MergingStateContextImpl extends StateContextImpl - implements MergingStateContext { + private class MergingStateAccessorImpl extends StateAccessorImpl + implements MergingStateAccessor { private final Collection activeToBeMerged; - public MergingStateContextImpl(ExecutableTrigger trigger, Collection activeToBeMerged, + public MergingStateAccessorImpl(ExecutableTrigger trigger, Collection activeToBeMerged, W mergeResult) { super(mergeResult, trigger); this.activeToBeMerged = activeToBeMerged; @@ -311,7 +311,7 @@ public Map accessInEachMergingWindow( private class TriggerContextImpl extends Trigger.TriggerContext { private final W window; - private final StateContextImpl state; + private final StateAccessorImpl state; private final Timers timers; private final TriggerInfoImpl triggerInfo; @@ -322,7 +322,7 @@ private TriggerContextImpl( FinishedTriggers finishedSet) { trigger.getSpec().super(); this.window = window; - this.state = new StateContextImpl(window, trigger); + this.state = new StateAccessorImpl(window, trigger); this.timers = new TriggerTimers(window, timers); this.triggerInfo = new TriggerInfoImpl(trigger, finishedSet, this); } @@ -338,7 +338,7 @@ public TriggerInfo trigger() { } @Override - public StateContext state() { + public StateAccessor state() { return state; } @@ -373,7 +373,7 @@ public Instant currentEventTime() { private class OnElementContextImpl extends Trigger.OnElementContext { private final W window; - private final StateContextImpl state; + private final StateAccessorImpl state; private final Timers timers; private final TriggerInfoImpl triggerInfo; private final Instant eventTimestamp; @@ -386,7 +386,7 @@ private OnElementContextImpl( Instant eventTimestamp) { trigger.getSpec().super(); this.window = window; - this.state = new StateContextImpl(window, trigger); + this.state = new StateAccessorImpl(window, trigger); this.timers = new TriggerTimers(window, timers); this.triggerInfo = new TriggerInfoImpl(trigger, finishedSet, this); this.eventTimestamp = eventTimestamp; @@ -410,7 +410,7 @@ public TriggerInfo trigger() { } @Override - public StateContext state() { + public StateAccessor state() { return state; } @@ -449,7 +449,7 @@ public Instant currentEventTime() { } private class OnMergeContextImpl extends Trigger.OnMergeContext { - private final MergingStateContext state; + private final MergingStateAccessor state; private final W window; private final Collection mergingWindows; private final Timers timers; @@ -464,7 +464,7 @@ private OnMergeContextImpl( trigger.getSpec().super(); this.mergingWindows = finishedSets.keySet(); this.window = window; - this.state = new MergingStateContextImpl(trigger, mergingWindows, window); + this.state = new MergingStateAccessorImpl(trigger, mergingWindows, window); this.timers = new TriggerTimers(window, timers); this.triggerInfo = new MergingTriggerInfoImpl(trigger, finishedSet, this, finishedSets); } @@ -476,7 +476,7 @@ public Trigger.OnMergeContext forTrigger(ExecutableTrigger trigger) { } @Override - public MergingStateContext state() { + public MergingStateAccessor state() { return state; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index 3629c5b7c8..e78411eb83 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -18,8 +18,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; -import com.google.cloud.dataflow.sdk.util.state.StateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.cloud.dataflow.sdk.util.state.ValueState; @@ -83,25 +83,25 @@ private FinishedTriggersBitSet readFinishedBits(ValueState state) { } /** Return true if the trigger is closed in the window corresponding to the specified state. */ - public boolean isClosed(StateContext state) { + public boolean isClosed(StateAccessor state) { return readFinishedBits(state.access(FINISHED_BITS_TAG)).isFinished(rootTrigger); } - public void prefetchForValue(W window, StateContext state) { + public void prefetchForValue(W window, StateAccessor state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } rootTrigger.getSpec().prefetchOnElement(contextFactory.createStateContext(window, rootTrigger)); } - public void prefetchOnFire(W window, StateContext state) { + public void prefetchOnFire(W window, StateAccessor state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } rootTrigger.getSpec().prefetchOnFire(contextFactory.createStateContext(window, rootTrigger)); } - public void prefetchShouldFire(W window, StateContext state) { + public void prefetchShouldFire(W window, StateAccessor state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).get(); } @@ -112,7 +112,7 @@ public void prefetchShouldFire(W window, StateContext state) { /** * Run the trigger logic to deal with a new value. */ - public void processValue(W window, Instant timestamp, Timers timers, StateContext state) + public void processValue(W window, Instant timestamp, Timers timers, StateAccessor state) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. FinishedTriggersBitSet finishedSet = @@ -124,7 +124,7 @@ public void processValue(W window, Instant timestamp, Timers timers, StateContex } public void prefetchForMerge( - W window, Collection mergingWindows, MergingStateContext state) { + W window, Collection mergingWindows, MergingStateAccessor state) { if (isFinishedSetNeeded()) { for (ValueState value : state.accessInEachMergingWindow(FINISHED_BITS_TAG).values()) { value.get(); @@ -137,7 +137,7 @@ public void prefetchForMerge( /** * Run the trigger merging logic as part of executing the specified merge. */ - public void onMerge(W window, Timers timers, MergingStateContext state) throws Exception { + public void onMerge(W window, Timers timers, MergingStateAccessor state) throws Exception { // Clone so that we can detect changes and so that changes here don't pollute merging. FinishedTriggersBitSet finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); @@ -163,14 +163,14 @@ public void onMerge(W window, Timers timers, MergingStateContext state) th clearFinished(state); } - public boolean shouldFire(W window, Timers timers, StateContext state) throws Exception { + public boolean shouldFire(W window, Timers timers, StateAccessor state) throws Exception { FinishedTriggers finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); Trigger.TriggerContext context = contextFactory.base(window, timers, rootTrigger, finishedSet); return rootTrigger.invokeShouldFire(context); } - public void onFire(W window, Timers timers, StateContext state) throws Exception { + public void onFire(W window, Timers timers, StateAccessor state) throws Exception { FinishedTriggersBitSet finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); Trigger.TriggerContext context = contextFactory.base(window, timers, @@ -180,7 +180,7 @@ public void onFire(W window, Timers timers, StateContext state) throws Except } private void persistFinishedSet( - StateContext state, FinishedTriggersBitSet modifiedFinishedSet) { + StateAccessor state, FinishedTriggersBitSet modifiedFinishedSet) { if (!isFinishedSetNeeded()) { return; } @@ -198,7 +198,7 @@ private void persistFinishedSet( /** * Clear finished bits. */ - public void clearFinished(StateContext state) { + public void clearFinished(StateAccessor state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).clear(); } @@ -208,7 +208,7 @@ public void clearFinished(StateContext state) { * Clear the state used for executing triggers, but leave the finished set to indicate * the window is closed. */ - public void clearState(W window, Timers timers, StateContext state) throws Exception { + public void clearState(W window, Timers timers, StateAccessor state) throws Exception { // Don't need to clone, because we'll be clearing the finished bits anyways. FinishedTriggers finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)); rootTrigger.invokeClear(contextFactory.base(window, timers, rootTrigger, finishedSet)); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index 4d37cdb0db..d0614db092 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -19,7 +19,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.util.state.MergingStateContext; +import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; @@ -345,7 +345,7 @@ private Instant addGarbageCollectionHold(ReduceFn.Context context) { /** * Prefetch watermark holds in preparation for merging. */ - public void prefetchOnMerge(MergingStateContext state) { + public void prefetchOnMerge(MergingStateAccessor state) { StateMerging.prefetchWatermarks(state, elementHoldTag); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateAccessor.java similarity index 87% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateContext.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateAccessor.java index 03efb5e703..40211d739b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateAccessor.java @@ -23,12 +23,13 @@ import java.util.Map; /** - * Interface for interacting with persistent state at the moment windows are merging. + * Interface for accessing persistent state while windows are merging. * *

    For internal use only. */ @Experimental(Kind.STATE) -public interface MergingStateContext extends StateContext { +public interface MergingStateAccessor + extends StateAccessor { /** * Analogous to {@link #access}, but returned as a map from each window which is * about to be merged to the corresponding state. Only includes windows which diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateAccessor.java similarity index 89% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateAccessor.java index 8a73308388..6cfbecff70 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateAccessor.java @@ -20,13 +20,12 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; /** - * Interface for interacting with per-key persistent state identified via a - * {@link StateTag}. + * Interface for accessing a {@link StateTag} in the current context. * *

    For internal use only. */ @Experimental(Kind.STATE) -public interface StateContext { +public interface StateAccessor { /** * Access the storage for the given {@code address} in the current window. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java index 9cea213547..3c53a20413 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java @@ -34,7 +34,7 @@ public class StateMerging { * in {@code context}. */ public static void clear( - MergingStateContext context, StateTag address) { + MergingStateAccessor context, StateTag address) { for (StateT state : context.accessInEachMergingWindow(address).values()) { state.clear(); } @@ -46,7 +46,7 @@ public static void clear( * blindly append to. */ public static void prefetchBags( - MergingStateContext context, StateTag> address) { + MergingStateAccessor context, StateTag> address) { Map> map = context.accessInEachMergingWindow(address); if (map.isEmpty()) { // Nothing to prefetch. @@ -65,7 +65,7 @@ public static void prefetchBags( * Merge all bag state in {@code address} across all windows under merge. */ public static void mergeBags( - MergingStateContext context, StateTag> address) { + MergingStateAccessor context, StateTag> address) { mergeBags(context.accessInEachMergingWindow(address).values(), context.access(address)); } @@ -108,7 +108,7 @@ public static void mergeBags( * context}. */ public static , W extends BoundedWindow> void - prefetchCombiningValues(MergingStateContext context, + prefetchCombiningValues(MergingStateAccessor context, StateTag address) { for (StateT state : context.accessInEachMergingWindow(address).values()) { state.get(); @@ -119,7 +119,7 @@ public static void mergeBags( * Merge all value state in {@code address} across all merging windows in {@code context}. */ public static void mergeCombiningValues( - MergingStateContext context, + MergingStateAccessor context, StateTag> address) { mergeCombiningValues( context.accessInEachMergingWindow(address).values(), context.access(address)); @@ -165,7 +165,7 @@ public static void mergeCombi * {@code context}. */ public static void prefetchWatermarks( - MergingStateContext context, + MergingStateAccessor context, StateTag> address) { Map> map = context.accessInEachMergingWindow(address); WatermarkStateInternal result = context.access(address); @@ -193,7 +193,7 @@ public static void prefetchWatermarks( * where the final merge result window is {@code mergeResult}. */ public static void mergeWatermarks( - MergingStateContext context, + MergingStateAccessor context, StateTag> address, W mergeResult) { mergeWatermarks( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index 510cd79d61..df5ab0310c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -80,7 +80,7 @@ public static StateTag> value(String id, Coder valu /** * Create a state tag for values that use a {@link KeyedCombineFn} to automatically merge * multiple {@code InputT}s into a single {@code OutputT}. The key provided to the - * {@link KeyedCombineFn} comes from the keyed {@link StateContext}. + * {@link KeyedCombineFn} comes from the keyed {@link StateAccessor}. */ public static StateTag> From c6382a189a9e0970f1d679478a307c0ea906f415 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Thu, 18 Feb 2016 17:35:11 -0800 Subject: [PATCH 170/751] ByteKeyRange: parameterize expensive combinatorial tests Breaks two different R*R*T combinatorial into R*R O(T) tests using JUnit Parameterized test suite. Here R is the number of keys in a range and T is another test parameter. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115021282 --- .../ByteKeyRangeEstimateFractionTest.java | 69 ++++++++++++++++++ .../range/ByteKeyRangeInterpolateKeyTest.java | 73 +++++++++++++++++++ .../sdk/io/range/ByteKeyRangeTest.java | 69 +----------------- 3 files changed, 143 insertions(+), 68 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java new file mode 100644 index 0000000000..71928f400e --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.Assert.assertThat; + +import com.google.common.collect.ImmutableList; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +/** + * A combinatorial test of {@link ByteKeyRange#estimateFractionForKey(ByteKey)}. + */ +@RunWith(Parameterized.class) +public class ByteKeyRangeEstimateFractionTest { + private static final ByteKey[] TEST_KEYS = ByteKeyRangeTest.RANGE_TEST_KEYS; + + @Parameters(name = "{index}: i={0}, k={1}") + public static Iterable data() { + ImmutableList.Builder ret = ImmutableList.builder(); + for (int i = 0; i < TEST_KEYS.length; ++i) { + for (int k = i + 1; k < TEST_KEYS.length; ++k) { + ret.add(new Object[] {i, k}); + } + } + return ret.build(); + } + + @Parameter(0) + public int i; + + @Parameter(1) + public int k; + + @Test + public void testEstimateFractionForKey() { + double last = 0.0; + ByteKeyRange range = ByteKeyRange.of(TEST_KEYS[i], TEST_KEYS[k]); + for (int j = i; j < k; ++j) { + ByteKey key = TEST_KEYS[j]; + if (key.isEmpty()) { + // Cannot compute progress for unspecified key + continue; + } + double fraction = range.estimateFractionForKey(key); + assertThat(fraction, greaterThanOrEqualTo(last)); + last = fraction; + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java new file mode 100644 index 0000000000..c41f905455 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.range; + +import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.Assert.assertThat; + +import com.google.common.collect.ImmutableList; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +/** + * Combinatorial tests for {@link ByteKeyRange#interpolateKey}, which also checks + * {@link ByteKeyRange#estimateFractionForKey} by converting the interpolated keys back to + * fractions. + */ +@RunWith(Parameterized.class) +public class ByteKeyRangeInterpolateKeyTest { + private static final ByteKey[] TEST_KEYS = ByteKeyRangeTest.RANGE_TEST_KEYS; + + @Parameters(name = "{index}: {0}") + public static Iterable data() { + ImmutableList.Builder ret = ImmutableList.builder(); + for (int i = 0; i < TEST_KEYS.length; ++i) { + for (int j = i + 1; j < TEST_KEYS.length; ++j) { + ret.add(new Object[] {ByteKeyRange.of(TEST_KEYS[i], TEST_KEYS[j])}); + } + } + return ret.build(); + } + + @Parameter public ByteKeyRange range; + + @Test + public void testInterpolateKeyAndEstimateFraction() { + double delta = 0.0000001; + double[] testFractions = + new double[] {0.01, 0.1, 0.123, 0.2, 0.3, 0.45738, 0.5, 0.6, 0.7182, 0.8, 0.95, 0.97, 0.99}; + ByteKey last = range.getStartKey(); + for (double fraction : testFractions) { + String message = Double.toString(fraction); + try { + ByteKey key = range.interpolateKey(fraction); + assertThat(message, key, greaterThanOrEqualTo(last)); + assertThat(message, range.estimateFractionForKey(key), closeTo(fraction, delta)); + last = key; + } catch (IllegalStateException e) { + assertThat(message, e.getMessage(), containsString("near-empty ByteKeyRange")); + continue; + } + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java index a90bb5acaa..f5c5d67d7b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java @@ -16,8 +16,6 @@ package com.google.cloud.dataflow.sdk.io.range; -import static org.hamcrest.Matchers.closeTo; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; @@ -69,7 +67,7 @@ public class ByteKeyRangeTest { AFTER_10, }; - private static final ByteKey[] RANGE_TEST_KEYS = + static final ByteKey[] RANGE_TEST_KEYS = ImmutableList.builder() .addAll(Arrays.asList(ByteKeyTest.TEST_KEYS)) .add(ByteKey.EMPTY) @@ -247,38 +245,6 @@ public void testEstimateFractionForKey() { } } - /** Exhaustive tests for {@link ByteKeyRange#estimateFractionForKey}. */ - @Test - public void testEstimateFractionForKeyCombinatorial() { - double last; - for (int i = 0; i < RANGE_TEST_KEYS.length; ++i) { - for (int k = i + 1; k < RANGE_TEST_KEYS.length; ++k) { - ByteKeyRange range = ByteKeyRange.of(RANGE_TEST_KEYS[i], RANGE_TEST_KEYS[k]); - last = 0.0; - for (int j = i; j < k; ++j) { - ByteKey key = RANGE_TEST_KEYS[j]; - if (key.isEmpty()) { - // Cannot compute progress for unspecified key - continue; - } - double fraction = range.estimateFractionForKey(key); - try { - assertThat(fraction, greaterThanOrEqualTo(last)); - } catch (AssertionError e) { - throw new AssertionError( - String.format( - "Range %s estimated fraction for key %s should be >= fraction for key %s", - range, - key, - RANGE_TEST_KEYS[i]), - e); - } - last = fraction; - } - } - } - } - /** Manual tests for {@link ByteKeyRange#interpolateKey}. */ @Test public void testInterpolateKey() { @@ -324,39 +290,6 @@ public void testInterpolateKeyIsNotEmpty() { } } - /** - * Combinatorial tests for {@link ByteKeyRange#interpolateKey}, which also checks - * {@link ByteKeyRange#estimateFractionForKey} by converting the interpolated keys back to - * fractions. - */ - @Test - public void testInterpolateKeyAndEstimateFractionCombinatorial() { - double delta = 0.0000001; - double[] testFractions = - new double[] {0.01, 0.1, 0.123, 0.2, 0.3, 0.45738, 0.5, 0.6, 0.7182, 0.8, 0.95, 0.97, 0.99}; - for (int i = 0; i < RANGE_TEST_KEYS.length; ++i) { - for (int j = i + 1; j < RANGE_TEST_KEYS.length; ++j) { - ByteKeyRange range = ByteKeyRange.of(RANGE_TEST_KEYS[i], RANGE_TEST_KEYS[j]); - ByteKey last = RANGE_TEST_KEYS[i]; - for (double fraction : testFractions) { - try { - ByteKey key = range.interpolateKey(fraction); - String message = String.format("%s, %s", range, fraction); - assertThat(message, key, greaterThanOrEqualTo(last)); - assertThat(message, range.estimateFractionForKey(key), closeTo(fraction, delta)); - last = key; - } catch (IllegalStateException e) { - assertThat( - String.format("range: %s fraction: %f", range, fraction), - e.getMessage(), - containsString("near-empty ByteKeyRange")); - continue; - } - } - } - } - } - /** Test {@link ByteKeyRange} getters. */ @Test public void testKeyGetters() { From 4533b90722dfe3168f136564d7ccbf17381022c1 Mon Sep 17 00:00:00 2001 From: lcwik Date: Thu, 18 Feb 2016 17:50:55 -0800 Subject: [PATCH 171/751] Migrate TextIO.Read to be a custom source This allows for other runners to utilize the TextIO.Read transform since it no longer relies on the internal details of the Google Cloud Dataflow runner. Note that validation has moved to when the PTransform is being applied. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115022452 --- examples/pom.xml | 7 + .../examples/MinimalWordCountJava8Test.java | 45 ++- .../google/cloud/dataflow/sdk/io/TextIO.java | 286 ++++++++++++++++-- .../runners/DataflowPipelineTranslator.java | 2 - .../sdk/runners/dataflow/ReadTranslator.java | 10 + .../runners/dataflow/TextIOTranslator.java | 34 --- .../cloud/dataflow/sdk/io/TextIOTest.java | 240 +++++++++++---- .../runners/DataflowPipelineRunnerTest.java | 40 ++- .../DataflowPipelineTranslatorTest.java | 17 +- .../sdk/runners/TransformTreeTest.java | 43 ++- 10 files changed, 561 insertions(+), 163 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 8e708ced69..adea4b1298 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -498,5 +498,12 @@ junit ${junit.version} + + + org.mockito + mockito-all + 1.9.5 + test + diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java index 5286d61a07..fcae41c6bb 100644 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java +++ b/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java @@ -18,20 +18,33 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.options.GcsOptions; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.FlatMapElements; import com.google.cloud.dataflow.sdk.transforms.MapElements; +import com.google.cloud.dataflow.sdk.util.GcsUtil; +import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import java.io.IOException; import java.io.Serializable; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import java.util.Arrays; +import java.util.List; /** * To keep {@link MinimalWordCountJava8} simple, it is not factored or testable. This test @@ -44,8 +57,9 @@ public class MinimalWordCountJava8Test implements Serializable { * A basic smoke test that ensures there is no crash at pipeline construction time. */ @Test - public void testMinimalWordCountJava8() { + public void testMinimalWordCountJava8() throws Exception { Pipeline p = TestPipeline.create(); + p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); p.apply(TextIO.Read.from("gs://dataflow-samples/shakespeare/*")) .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) @@ -57,4 +71,33 @@ public void testMinimalWordCountJava8() { .withOutputType(new TypeDescriptor() {})) .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); } + + private GcsUtil buildMockGcsUtil() throws IOException { + GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); + + // Any request to open gets a new bogus channel + Mockito + .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + + // Any request for expansion returns a list containing the original GcsPath + // This is required to pass validation that occurs in TextIO during apply() + Mockito + .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) + .then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); + + return mockGcsUtil; + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index bf72f6bf19..71e755eebe 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -16,32 +16,41 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.Read.Bounded; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.runners.worker.TextReader; import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; +import com.google.protobuf.ByteString; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.SeekableByteChannel; import java.util.List; +import java.util.NoSuchElementException; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; @@ -203,7 +212,7 @@ public static class Bound extends PTransform> { @Nullable private final String filepattern; /** The Coder to use to decode each line. */ - @Nullable private final Coder coder; + private final Coder coder; /** An option to indicate if input validation is desired. Default is true. */ private final boolean validate; @@ -292,14 +301,48 @@ public PCollection apply(PInput input) { if (filepattern == null) { throw new IllegalStateException("need to set the filepattern of a TextIO.Read transform"); } - // Force the output's Coder to be what the read is using, and - // unchangeable later, to ensure that we read the input in the - // format specified by the Read transform. - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - IsBounded.BOUNDED) - .setCoder(coder); + + if (validate) { + try { + checkState( + !IOChannelUtils.getFactory(filepattern).match(filepattern).isEmpty(), + "Unable to find any files matching %s", + filepattern); + } catch (IOException e) { + throw new IllegalStateException( + String.format("Failed to validate %s", filepattern), e); + } + } + + // Create a source specific to the requested compression type. + final Bounded read; + switch(compressionType) { + case UNCOMPRESSED: + read = com.google.cloud.dataflow.sdk.io.Read.from( + new TextSource(filepattern, coder)); + break; + case AUTO: + read = com.google.cloud.dataflow.sdk.io.Read.from( + CompressedSource.from(new TextSource(filepattern, coder))); + break; + case BZIP2: + read = com.google.cloud.dataflow.sdk.io.Read.from( + CompressedSource.from(new TextSource(filepattern, coder)) + .withDecompression(CompressedSource.CompressionMode.BZIP2)); + break; + case GZIP: + read = com.google.cloud.dataflow.sdk.io.Read.from( + CompressedSource.from(new TextSource(filepattern, coder)) + .withDecompression(CompressedSource.CompressionMode.GZIP)); + break; + default: + throw new IllegalArgumentException("Unknown compression mode: " + compressionType); + } + + PCollection pcol = input.getPipeline().apply("Read", read); + // Honor the default output coder that would have been used by this PTransform. + pcol.setCoder(getDefaultOutputCoder()); + return pcol; } @Override @@ -318,17 +361,6 @@ public boolean needsValidation() { public TextIO.CompressionType getCompressionType() { return compressionType; } - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateReadHelper(transform, context); - } - }); - } } /** Disallow construction of utility classes. */ @@ -781,16 +813,204 @@ private static void validateOutputComponent(String partialFilePattern) { /** Disable construction of utility class. */ private TextIO() {} - private static void evaluateReadHelper( - Read.Bound transform, DirectPipelineRunner.EvaluationContext context) { - TextReader reader = - new TextReader<>(transform.filepattern, true, null, null, transform.coder, - transform.getCompressionType()); - try { - List elems = ReaderUtils.readAllFromReader(reader); - context.setPCollection(context.getOutput(transform), elems); - } catch (IOException e) { - throw new RuntimeException(e); + /** + * A {@link FileBasedSource} which can decode records delimited by new line characters. + * + *

    This source splits the data into records using {@code UTF-8} {@code \n}, {@code \r}, or + * {@code \r\n} as the delimiter. This source is not strict and supports decoding the last record + * even if it is not delimited. Finally, no records are decoded if the stream is empty. + * + *

    This source supports reading from any arbitrary byte position within the stream. If the + * starting position is not {@code 0}, then bytes are skipped until the first delimiter is found + * representing the beginning of the first record to be decoded. + */ + @VisibleForTesting + static class TextSource extends FileBasedSource { + /** The Coder to use to decode each line. */ + private final Coder coder; + + @VisibleForTesting + TextSource(String fileSpec, Coder coder) { + super(fileSpec, 1L); + this.coder = coder; + } + + private TextSource(String fileName, long start, long end, Coder coder) { + super(fileName, 1L, start, end); + this.coder = coder; + } + + @Override + protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { + return new TextSource<>(fileName, start, end, coder); + } + + @Override + protected FileBasedReader createSingleFileReader(PipelineOptions options) { + return new TextBasedReader<>(this); + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return false; + } + + @Override + public Coder getDefaultOutputCoder() { + return coder; + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader FileBasedReader} + * which can decode records delimited by new line characters. + * + * See {@link TextSource} for further details. + */ + @VisibleForTesting + static class TextBasedReader extends FileBasedReader { + private static final int READ_BUFFER_SIZE = 8192; + private final Coder coder; + private final ByteBuffer readBuffer = ByteBuffer.allocate(READ_BUFFER_SIZE); + private ByteString buffer; + private int startOfSeparatorInBuffer; + private int endOfSeparatorInBuffer; + private long startOfNextRecord; + private boolean eof; + private boolean elementIsPresent; + private T currentValue; + private ReadableByteChannel inChannel; + + private TextBasedReader(TextSource source) { + super(source); + coder = source.coder; + buffer = ByteString.EMPTY; + } + + @Override + protected long getCurrentOffset() throws NoSuchElementException { + if (!elementIsPresent) { + throw new NoSuchElementException(); + } + return startOfNextRecord; + } + + @Override + public T getCurrent() throws NoSuchElementException { + if (!elementIsPresent) { + throw new NoSuchElementException(); + } + return currentValue; + } + + @Override + protected void startReading(ReadableByteChannel channel) throws IOException { + this.inChannel = channel; + // If the first offset is greater than zero, we need to skip bytes until we see our + // first separator. + if (getCurrentSource().getStartOffset() > 0) { + checkState(channel instanceof SeekableByteChannel, + "%s only supports reading from a SeekableByteChannel when given a start offset" + + " greater than 0.", TextSource.class.getSimpleName()); + long requiredPosition = getCurrentSource().getStartOffset() - 1; + ((SeekableByteChannel) channel).position(requiredPosition); + findSeparatorBounds(); + buffer = buffer.substring(endOfSeparatorInBuffer); + startOfNextRecord = requiredPosition + endOfSeparatorInBuffer; + endOfSeparatorInBuffer = 0; + startOfSeparatorInBuffer = 0; + } + } + + /** + * Locates the start position and end position of the next delimiter. Will + * consume the channel till either EOF or the delimiter bounds are found. + * + *

    This fills the buffer and updates the positions as follows: + *

    {@code
    +       * ------------------------------------------------------
    +       * | element bytes | delimiter bytes | unconsumed bytes |
    +       * ------------------------------------------------------
    +       * 0            start of          end of              buffer
    +       *              separator         separator           size
    +       *              in buffer         in buffer
    +       * }
    + */ + private void findSeparatorBounds() throws IOException { + int bytePositionInBuffer = 0; + while (true) { + if (!tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 1)) { + startOfSeparatorInBuffer = endOfSeparatorInBuffer = bytePositionInBuffer; + break; + } + + byte currentByte = buffer.byteAt(bytePositionInBuffer); + + if (currentByte == '\n') { + startOfSeparatorInBuffer = bytePositionInBuffer; + endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; + break; + } else if (currentByte == '\r') { + startOfSeparatorInBuffer = bytePositionInBuffer; + endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; + + if (tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 2)) { + currentByte = buffer.byteAt(bytePositionInBuffer + 1); + if (currentByte == '\n') { + endOfSeparatorInBuffer += 1; + } + } + break; + } + + // Move to the next byte in buffer. + bytePositionInBuffer += 1; + } + } + + @Override + protected boolean readNextRecord() throws IOException { + startOfNextRecord += endOfSeparatorInBuffer; + findSeparatorBounds(); + + // If we have reached EOF file and consumed all of the buffer then we know + // that there are no more records. + if (eof && buffer.size() == 0) { + elementIsPresent = false; + return false; + } + + decodeCurrentElement(); + return true; + } + + /** + * Decodes the current element updating the buffer to only contain the unconsumed bytes. + * + * This invalidates the currently stored {@code startOfSeparatorInBuffer} and + * {@code endOfSeparatorInBuffer}. + */ + private void decodeCurrentElement() throws IOException { + ByteString dataToDecode = buffer.substring(0, startOfSeparatorInBuffer); + currentValue = coder.decode(dataToDecode.newInput(), Context.OUTER); + elementIsPresent = true; + buffer = buffer.substring(endOfSeparatorInBuffer); + } + + /** + * Returns false if we were unable to ensure the minimum capacity by consuming the channel. + */ + private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOException { + // While we aren't at EOF or haven't fulfilled the minimum buffer capacity, + // attempt to read more bytes. + while (buffer.size() <= minCapacity && !eof) { + eof = inChannel.read(readBuffer) == -1; + readBuffer.flip(); + buffer = buffer.concat(ByteString.copyFrom(readBuffer)); + readBuffer.clear(); + } + // Return true if we were able to honor the minimum buffer capacity request + return buffer.size() >= minCapacity; + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 1d14254c24..f7217f7610 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -1042,8 +1042,6 @@ private void translateHelper( DataflowPipelineRunner.StreamingPubsubIOWrite.class, new PubsubIOTranslator.WriteTranslator()); - registerTransformTranslator( - TextIO.Read.Bound.class, new TextIOTranslator.ReadTranslator()); registerTransformTranslator( TextIO.Write.Bound.class, new TextIOTranslator.WriteTranslator()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java index 2513d431cb..47a1926764 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java @@ -18,6 +18,7 @@ import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudSourceToDictionary; +import com.google.cloud.dataflow.sdk.io.FileBasedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Source; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; @@ -40,6 +41,15 @@ public static void translateReadHelper(Source source, PTransform transform, DataflowPipelineTranslator.TranslationContext context) { try { + // TODO: Move this validation out of translation once IOChannelUtils is portable + // and can be reconstructed on the worker. + if (source instanceof FileBasedSource) { + String filePatternOrSpec = ((FileBasedSource) source).getFileOrPatternSpec(); + context.getPipelineOptions() + .getPathValidator() + .validateInputFilePatternSupported(filePatternOrSpec); + } + context.addStep(transform, "ParallelRead"); context.addInput(PropertyNames.FORMAT, PropertyNames.CUSTOM_SOURCE_FORMAT); context.addInput( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java index abdf07fa58..d6c96c31bd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java @@ -29,40 +29,6 @@ * TextIO transform support code for the Dataflow backend. */ public class TextIOTranslator { - - /** - * Implements TextIO Read translation for the Dataflow backend. - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public static class ReadTranslator implements TransformTranslator { - @Override - public void translate( - TextIO.Read.Bound transform, - TranslationContext context) { - translateReadHelper(transform, context); - } - - private void translateReadHelper( - TextIO.Read.Bound transform, - TranslationContext context) { - if (context.getPipelineOptions().isStreaming()) { - throw new IllegalArgumentException("TextIO not supported in streaming mode."); - } - - PathValidator validator = context.getPipelineOptions().getPathValidator(); - String filepattern = validator.validateInputFilePatternSupported(transform.getFilepattern()); - - context.addStep(transform, "ParallelRead"); - // TODO: How do we want to specify format and - // format-specific properties? - context.addInput(PropertyNames.FORMAT, "text"); - context.addInput(PropertyNames.FILEPATTERN, filepattern); - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - context.addInput(PropertyNames.VALIDATE_SOURCE, transform.needsValidation()); - context.addInput(PropertyNames.COMPRESSION_TYPE, transform.getCompressionType().toString()); - } - } - /** * Implements TextIO Write translation for the Dataflow backend. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index abd8333bc4..6ad81e4ea0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -20,7 +20,7 @@ import static com.google.cloud.dataflow.sdk.TestUtils.LINES_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_INTS_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES_ARRAY; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; @@ -30,9 +30,12 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.TextIO.CompressionType; +import com.google.cloud.dataflow.sdk.io.TextIO.TextSource; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -43,6 +46,7 @@ import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.collect.ImmutableList; import org.junit.Rule; import org.junit.Test; @@ -51,6 +55,8 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import java.io.BufferedReader; import java.io.File; @@ -58,8 +64,11 @@ import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; -import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -74,60 +83,31 @@ public class TextIOTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); - private static class EmptySeekableByteChannel implements SeekableByteChannel { - @Override - public long position() { - return 0L; - } - - @Override - public SeekableByteChannel position(long newPosition) { - return this; - } - - @Override - public long size() { - return 0L; - } - - @Override - public SeekableByteChannel truncate(long size) { - return this; - } - - @Override - public int write(ByteBuffer src) { - return 0; - } - - @Override - public int read(ByteBuffer dst) { - return 0; - } - - @Override - public boolean isOpen() { - return true; - } - - @Override - public void close() { } - } - private GcsUtil buildMockGcsUtil() throws IOException { GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); // Any request to open gets a new bogus channel Mockito .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .thenReturn(new EmptySeekableByteChannel()); - - // Any request for expansion gets a single bogus URL - // after we first run the expansion code (which will generally - // return no results, which causes a crash we aren't testing) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + + // Any request for expansion returns a list containing the original GcsPath + // This is required to pass validation that occurs in TextIO during apply() Mockito .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .thenReturn(Arrays.asList(GcsPath.fromUri("gs://bucket/foo"))); + .then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); return mockGcsUtil; } @@ -189,25 +169,31 @@ public void testReadEmptyInts() throws Exception { } @Test - public void testReadNamed() { + public void testReadNulls() throws Exception { + runTestRead(new Void[]{ null, null, null }, VoidCoder.of()); + } + + @Test + public void testReadNamed() throws Exception { + String file = tmpFolder.newFile().getAbsolutePath(); Pipeline p = TestPipeline.create(); { PCollection output1 = - p.apply(TextIO.Read.from("/tmp/file.txt")); - assertEquals("TextIO.Read.out", output1.getName()); + p.apply(TextIO.Read.from(file)); + assertEquals("TextIO.Read/Read.out", output1.getName()); } { PCollection output2 = - p.apply(TextIO.Read.named("MyRead").from("/tmp/file.txt")); - assertEquals("MyRead.out", output2.getName()); + p.apply(TextIO.Read.named("MyRead").from(file)); + assertEquals("MyRead/Read.out", output2.getName()); } { PCollection output3 = - p.apply(TextIO.Read.from("/tmp/file.txt").named("HerRead")); - assertEquals("HerRead.out", output3.getName()); + p.apply(TextIO.Read.from(file).named("HerRead")); + assertEquals("HerRead/Read.out", output3.getName()); } } @@ -378,12 +364,11 @@ private void applyRead(Pipeline pipeline, String path) { public void testBadWildcardRecursive() throws Exception { Pipeline pipeline = TestPipeline.create(); - pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); - - // Check that running does fail. + // Check that applying does fail. expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("wildcard"); - pipeline.run(); + + pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); } @Test @@ -411,7 +396,7 @@ public void testCompressionTypeIsSet() throws Exception { @Test public void testCompressedRead() throws Exception { String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; - File tmpFile = tmpFolder.newFile("test"); + File tmpFile = tmpFolder.newFile(); String filename = tmpFile.getPath(); List expected = new ArrayList<>(); @@ -431,14 +416,12 @@ public void testCompressedRead() throws Exception { DataflowAssert.that(output).containsInAnyOrder(expected); p.run(); - - tmpFile.delete(); } @Test public void testGZIPReadWhenUncompressed() throws Exception { String[] lines = {"Meritorious condor", "Obnoxious duck"}; - File tmpFile = tmpFolder.newFile("test"); + File tmpFile = tmpFolder.newFile(); String filename = tmpFile.getPath(); List expected = new ArrayList<>(); @@ -456,8 +439,6 @@ public void testGZIPReadWhenUncompressed() throws Exception { DataflowAssert.that(output).containsInAnyOrder(expected); p.run(); - - tmpFile.delete(); } @Test @@ -471,4 +452,133 @@ public void testTextIOGetName() { assertEquals( "ReadMyFile [TextIO.Read]", TextIO.Read.named("ReadMyFile").from("somefile").toString()); } + + @Test + public void testReadEmptyLines() throws Exception { + runTestReadWithData("\n\n\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("", "", "")); + } + + @Test + public void testReadFileWithLineFeedDelimiter() throws Exception { + runTestReadWithData("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnDelimiter() throws Exception { + runTestReadWithData("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnAndLineFeedDelimiter() throws Exception { + runTestReadWithData("asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithMixedDelimiters() throws Exception { + runTestReadWithData("asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { + runTestReadWithData("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() throws Exception { + runTestReadWithData("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() + throws Exception { + runTestReadWithData("asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { + runTestReadWithData("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + private void runTestReadWithData(byte[] data, List expectedResults) throws Exception { + TextSource source = prepareSource(data); + List actual = SourceTestUtils.readFromSource(source, PipelineOptionsFactory.create()); + assertThat(actual, containsInAnyOrder(new ArrayList<>(expectedResults).toArray(new String[0]))); + } + + @Test + public void testSplittingSourceWithEmptyLines() throws Exception { + TextSource source = prepareSource("\n\n\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithLineFeedDelimiter() throws Exception { + TextSource source = prepareSource("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnDelimiter() throws Exception { + TextSource source = prepareSource("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiter() throws Exception { + TextSource source = prepareSource( + "asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithMixedDelimiters() throws Exception { + TextSource source = prepareSource( + "asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { + TextSource source = prepareSource("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() + throws Exception { + TextSource source = prepareSource("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() + throws Exception { + TextSource source = prepareSource( + "asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { + TextSource source = prepareSource("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + private TextSource prepareSource(byte[] data) throws IOException { + File file = tmpFolder.newFile(); + Files.write(file.toPath(), data); + + TextSource source = new TextSource<>(file.toPath().toString(), StringUtf8Coder.of()); + + return source; + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 6d9f90f39e..c7175cb3b0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -19,6 +19,7 @@ import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertEquals; @@ -95,18 +96,22 @@ import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; +import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.ArrayList; @@ -175,12 +180,23 @@ private static Dataflow buildMockDataflow( private GcsUtil buildMockGcsUtil(boolean bucketExists) throws IOException { GcsUtil mockGcsUtil = mock(GcsUtil.class); - when(mockGcsUtil.create( - any(GcsPath.class), anyString())) - .thenReturn(FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE)); + when(mockGcsUtil.create(any(GcsPath.class), anyString())) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + when(mockGcsUtil.isGcsPatternSupported(anyString())).thenReturn(true); + when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(bucketExists); return mockGcsUtil; } @@ -425,10 +441,12 @@ public void testNonGcsFilePathInReadFailure() throws IOException { ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); - p.apply(TextIO.Read.named("ReadMyNonGcsFile").from("/tmp/file")); + p.apply(TextIO.Read.named("ReadMyNonGcsFile").from(tmpFolder.newFile().getPath())); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); + thrown.expectCause(Matchers.allOf( + instanceOf(IllegalArgumentException.class), + ThrowableMessageMatcher.hasMessage( + containsString("expected a valid 'gs://' path but was given")))); p.run(); assertValidJob(jobCaptor.getValue()); } @@ -455,8 +473,9 @@ public void testMultiSlashGcsFileReadPath() throws IOException { p.apply(TextIO.Read.named("ReadInvalidGcsFile") .from("gs://bucket/tmp//file")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("consecutive slashes"); + thrown.expectCause(Matchers.allOf( + instanceOf(IllegalArgumentException.class), + ThrowableMessageMatcher.hasMessage(containsString("consecutive slashes")))); p.run(); assertValidJob(jobCaptor.getValue()); } @@ -1126,6 +1145,7 @@ public void testToIsmRecordForMapLikeDoFnWithoutUniqueKeysThrowsException() thro try { doFnTester.processBatch(inputElements); + fail("Expected UserCodeException"); } catch (UserCodeException e) { assertTrue(e.getCause() instanceof IllegalStateException); IllegalStateException rootCause = (IllegalStateException) e.getCause(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 98efc001a9..b9c94ad00b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -19,6 +19,8 @@ import static com.google.cloud.dataflow.sdk.util.Structs.addObject; import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; import static com.google.cloud.dataflow.sdk.util.Structs.getString; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -66,13 +68,17 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; +import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentMatcher; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import java.io.IOException; import java.util.Collections; @@ -138,6 +144,12 @@ private static Dataflow buildMockDataflow( private static DataflowPipelineOptions buildPipelineOptions() throws IOException { GcsUtil mockGcsUtil = mock(GcsUtil.class); + when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(true); when(mockGcsUtil.isGcsPatternSupported(anyString())).thenCallRealMethod(); @@ -635,8 +647,9 @@ public void testBadWildcardRecursive() throws Exception { pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); // Check that translation does fail. - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unsupported wildcard usage"); + thrown.expectCause(Matchers.allOf( + instanceOf(IllegalArgumentException.class), + ThrowableMessageMatcher.hasMessage(containsString("Unsupported wildcard usage")))); t.translate(pipeline, pipeline.getRunner(), Collections.emptyList()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java index cb34e5c117..f1b7cd7fd0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java @@ -18,10 +18,15 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -34,11 +39,13 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PValue; -import org.junit.Assert; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.File; import java.util.Arrays; import java.util.EnumSet; @@ -47,6 +54,7 @@ */ @RunWith(JUnit4.class) public class TransformTreeTest { + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); enum TransformsSeen { READ, @@ -103,11 +111,14 @@ protected Coder getDefaultOutputCoder() { // visits the nodes and verifies that the hierarchy was captured. @Test public void testCompositeCapture() throws Exception { + File inputFile = tmpFolder.newFile(); + File outputFile = tmpFolder.newFile(); + Pipeline p = DirectPipeline.createForTest(); - p.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/object")) + p.apply(TextIO.Read.named("ReadMyFile").from(inputFile.getPath())) .apply(Sample.any(10)) - .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/object")); + .apply(TextIO.Write.named("WriteMyFile").to(outputFile.getPath())); final EnumSet visited = EnumSet.noneOf(TransformsSeen.class); @@ -119,19 +130,19 @@ public void testCompositeCapture() throws Exception { public void enterCompositeTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); if (transform instanceof Sample.SampleAny) { - Assert.assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); - Assert.assertNotNull(node.getEnclosingNode()); - Assert.assertTrue(node.isCompositeNode()); + assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); + assertNotNull(node.getEnclosingNode()); + assertTrue(node.isCompositeNode()); } - Assert.assertThat(transform, not(instanceOf(TextIO.Read.Bound.class))); - Assert.assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); + assertThat(transform, not(instanceOf(Read.Bounded.class))); + assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); } @Override public void leaveCompositeTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); if (transform instanceof Sample.SampleAny) { - Assert.assertTrue(left.add(TransformsSeen.SAMPLE_ANY)); + assertTrue(left.add(TransformsSeen.SAMPLE_ANY)); } } @@ -139,11 +150,11 @@ public void leaveCompositeTransform(TransformTreeNode node) { public void visitTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); // Pick is a composite, should not be visited here. - Assert.assertThat(transform, not(instanceOf(Sample.SampleAny.class))); - if (transform instanceof TextIO.Read.Bound) { - Assert.assertTrue(visited.add(TransformsSeen.READ)); + assertThat(transform, not(instanceOf(Sample.SampleAny.class))); + if (transform instanceof Read.Bounded) { + assertTrue(visited.add(TransformsSeen.READ)); } else if (transform instanceof TextIO.Write.Bound) { - Assert.assertTrue(visited.add(TransformsSeen.WRITE)); + assertTrue(visited.add(TransformsSeen.WRITE)); } } @@ -152,8 +163,8 @@ public void visitValue(PValue value, TransformTreeNode producer) { } }); - Assert.assertTrue(visited.equals(EnumSet.allOf(TransformsSeen.class))); - Assert.assertTrue(left.equals(EnumSet.of(TransformsSeen.SAMPLE_ANY))); + assertTrue(visited.equals(EnumSet.allOf(TransformsSeen.class))); + assertTrue(left.equals(EnumSet.of(TransformsSeen.SAMPLE_ANY))); } @Test(expected = IllegalStateException.class) @@ -163,7 +174,7 @@ public void testOutputChecking() throws Exception { p.apply(new InvalidCompositeTransform()); p.traverseTopologically(new RecordingPipelineVisitor()); - Assert.fail("traversal should have failed with an IllegalStateException"); + fail("traversal should have failed with an IllegalStateException"); } @Test From 966b8f0be4a689a9685b0ac8be6c534a6d0f38ae Mon Sep 17 00:00:00 2001 From: tgroh Date: Thu, 18 Feb 2016 17:54:25 -0800 Subject: [PATCH 172/751] Make earliest Watermark State available in CopyOnAccessState This makes it the responsibility of the state to track watermark holds, rather than interrogating it for all watermark holds externally. Update InMemoryStateInternals#isEmptyForTesting to InMemoryStateInternals#isCleared; use to verify that all states copied during a commit are non-cleared, so cleared states are removed from the state table (and can be reclaimed). ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115022701 --- .../CopyOnAccessInMemoryStateInternals.java | 95 +++++++++-- .../util/state/InMemoryStateInternals.java | 12 +- ...opyOnAccessInMemoryStateInternalsTest.java | 156 ++++++++++++++++++ 3 files changed, 243 insertions(+), 20 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java index 29ce6519cb..2a8fa47d88 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.sdk.util.state; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; @@ -24,6 +26,10 @@ import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; import com.google.common.base.Optional; +import org.joda.time.Instant; + +import java.util.Map; + import javax.annotation.Nullable; /** @@ -39,15 +45,16 @@ public class CopyOnAccessInMemoryStateInternals implements StateInternals * Creates a new {@link CopyOnAccessInMemoryStateInternals} with the underlying (possibly null) * StateInternals. */ - public static CopyOnAccessInMemoryStateInternals withUnderlying(K key, -@Nullable CopyOnAccessInMemoryStateInternals underlying) { + public static CopyOnAccessInMemoryStateInternals withUnderlying( + K key, @Nullable CopyOnAccessInMemoryStateInternals underlying) { return new CopyOnAccessInMemoryStateInternals(key, underlying); } private CopyOnAccessInMemoryStateInternals( K key, CopyOnAccessInMemoryStateInternals underlying) { this.key = key; - table = new CopyOnAccessInMemoryStateTable<>(key, underlying == null ? null : underlying.table); + table = + new CopyOnAccessInMemoryStateTable(key, underlying == null ? null : underlying.table); } /** @@ -58,6 +65,10 @@ private CopyOnAccessInMemoryStateInternals( * has not been bound in this {@link CopyOnAccessInMemoryStateInternals}, put a reference to that * state within this {@link StateInternals}. * + *

    Additionally, stores the {@link WatermarkStateInternal} with the earliest time bound in the + * state table after the commit is completed, enabling calls to + * {@link #getEarliestWatermarkHold()}. + * * @return this table */ public CopyOnAccessInMemoryStateInternals commit() { @@ -65,6 +76,22 @@ public CopyOnAccessInMemoryStateInternals commit() { return this; } + /** + * Gets the earliest Watermark Hold present in this table. + * + *

    Must be called after this state has been committed. Will throw an + * {@link IllegalStateException} if the state has not been committed. + */ + public Instant getEarliestWatermarkHold() { + // After commit, the watermark hold is always present, but may be + // BoundedWindow#TIMESTAMP_MAX_VALUE if there is no hold set. + checkState( + table.earliestWatermarkHold.isPresent(), + "Can't get the earliest watermark hold in a %s before it is committed", + getClass().getSimpleName()); + return table.earliestWatermarkHold.get(); + } + @Override public T state(StateNamespace namespace, StateTag address) { return table.get(namespace, address); @@ -97,17 +124,23 @@ private static class CopyOnAccessInMemoryStateTable extends StateTable { *

  • During the execution of the {@link #commit()} method, this is a * {@link ReadThroughBinderFactory}, which copies the references to the existing * {@link State} objects to this {@link StateTable}.
  • - *
  • After the execution of the {@link #commit()} method, this is an instance of - * {@link InMemoryStateBinderFactory}, which constructs new instances of state when a - * {@link StateTag} is bound.
  • + *
  • After the execution of the {@link #commit()} method, this is an + * instance of {@link InMemoryStateBinderFactory}, which constructs new instances of state + * when a {@link StateTag} is bound.
  • * */ private StateBinderFactory binderFactory; + /** + * The earliest watermark hold in this table. + */ + private Optional earliestWatermarkHold; + public CopyOnAccessInMemoryStateTable(K key, StateTable underlying) { this.key = key; this.underlying = Optional.fromNullable(underlying); binderFactory = new CopyOnBindBinderFactory<>(key, this.underlying); + earliestWatermarkHold = Optional.absent(); } /** @@ -123,20 +156,40 @@ public CopyOnAccessInMemoryStateTable(K key, StateTable underlying) { * are bound in this {@link StateTable table} and this table represents the canonical state. */ private void commit() { + Instant earliestHold = getEarliestWatermarkHold(); if (underlying.isPresent()) { ReadThroughBinderFactory readThroughBinder = new ReadThroughBinderFactory<>(underlying.get()); binderFactory = readThroughBinder; - readThroughBinder.readThrough(this); + Instant earliestUnderlyingHold = readThroughBinder.readThroughAndGetEarliestHold(this); + if (earliestUnderlyingHold.isBefore(earliestHold)) { + earliestHold = earliestUnderlyingHold; + } } + earliestWatermarkHold = Optional.of(earliestHold); binderFactory = new InMemoryStateBinderFactory<>(key); underlying = Optional.absent(); } + /** + * Get the earliest watermark hold in this table. Ignores the contents of any underlying table. + */ + private Instant getEarliestWatermarkHold() { + Instant earliest = BoundedWindow.TIMESTAMP_MAX_VALUE; + for (State existingState : this.values()) { + if (existingState instanceof WatermarkStateInternal) { + Instant hold = ((WatermarkStateInternal) existingState).get().read(); + if (hold != null && hold.isBefore(earliest)) { + earliest = hold; + } + } + } + return earliest; + } + @Override protected StateBinder binderForNamespace(final StateNamespace namespace) { - StateBinder stateBinder = binderFactory.forNamespace(namespace); - return stateBinder; + return binderFactory.forNamespace(namespace); } private static interface StateBinderFactory { @@ -250,8 +303,8 @@ public BagState bindBag( /** * {@link StateBinderFactory} that reads directly from the underlying table. Used during calls - * to {@link CopyOnAccessInMemoryStateTable#commit()} to read all values from the underlying - * table. + * to {@link CopyOnAccessInMemoryStateTable#commit()} to read all values from + * the underlying table. */ private static class ReadThroughBinderFactory implements StateBinderFactory { private final StateTable underlying; @@ -260,12 +313,26 @@ public ReadThroughBinderFactory(StateTable underlying) { this.underlying = underlying; } - public void readThrough(StateTable readTo) { + public Instant readThroughAndGetEarliestHold(StateTable readTo) { + Instant earliestHold = BoundedWindow.TIMESTAMP_MAX_VALUE; for (StateNamespace namespace : underlying.getNamespacesInUse()) { - for (StateTag address : underlying.getTagsInUse(namespace).keySet()) { - readTo.get(namespace, address); + for (Map.Entry, ? extends State> existingState : + underlying.getTagsInUse(namespace).entrySet()) { + if (!((InMemoryState) existingState.getValue()).isCleared()) { + // Only read through non-cleared values to ensure that completed windows are + // eventually discarded, and remember the earliest watermark hold from among those + // values. + State state = readTo.get(namespace, existingState.getKey()); + if (state instanceof WatermarkStateInternal) { + Instant hold = ((WatermarkStateInternal) state).get().read(); + if (hold != null && hold.isBefore(earliestHold)) { + earliestHold = hold; + } + } + } } } + return earliestHold; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 6b98101c23..658494bcbb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -56,7 +56,7 @@ public K getKey() { } interface InMemoryState> { - boolean isEmptyForTesting(); + boolean isCleared(); T copy(); } @@ -76,7 +76,7 @@ public void clear() { * that the state has been properly cleaned up. */ protected boolean isEmptyForTesting(State state) { - return ((InMemoryState) state).isEmptyForTesting(); + return ((InMemoryState) state).isCleared(); } @Override @@ -171,7 +171,7 @@ public InMemoryValue copy() { } @Override - public boolean isEmptyForTesting() { + public boolean isCleared() { return isCleared; } } @@ -212,7 +212,7 @@ public void add(Instant outputTime) { } @Override - public boolean isEmptyForTesting() { + public boolean isCleared() { return combinedHold == null; } @@ -316,7 +316,7 @@ public AccumT mergeAccumulators(Iterable accumulators) { } @Override - public boolean isEmptyForTesting() { + public boolean isCleared() { return isCleared; } @@ -363,7 +363,7 @@ public void add(T input) { } @Override - public boolean isEmptyForTesting() { + public boolean isCleared() { return contents.isEmpty(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java index 03c40140e3..b9f12536f4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java @@ -34,9 +34,12 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import org.joda.time.Instant; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -45,6 +48,7 @@ */ @RunWith(JUnit4.class) public class CopyOnAccessInMemoryStateInternalsTest { + @Rule public ExpectedException thrown = ExpectedException.none(); private String key = "foo"; @Test public void testGetWithEmpty() { @@ -286,6 +290,34 @@ public void testCommitWithUnderlying() { assertThat(underlyingState, is(theInstance(stringBag))); } + @Test + public void testCommitWithClearedInUnderlying() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + CopyOnAccessInMemoryStateInternals secondUnderlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, secondUnderlying); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = underlying.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + stringBag.clear(); + // We should not read through the cleared bag + secondUnderlying.commit(); + + // Should not be visible + stringBag.add("foo"); + + internals.commit(); + BagState internalsStringBag = internals.state(namespace, bagTag); + assertThat(internalsStringBag.get().read(), emptyIterable()); + } + @Test public void testCommitWithOverwrittenUnderlying() { CopyOnAccessInMemoryStateInternals underlying = @@ -340,4 +372,128 @@ public void testCommitWithAddedUnderlying() { BagState reReadUnderlyingState = underlying.state(namespace, bagTag); assertThat(reReadUnderlyingState.get().read(), containsInAnyOrder("bar", "baz")); } + + @Test + public void testGetEarliestWatermarkHoldAfterCommit() { + BoundedWindow first = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(2048L); + } + }; + BoundedWindow second = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(689743L); + } + }; + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); + + StateTag> firstHoldAddress = + StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); + WatermarkStateInternal firstHold = + internals.state(StateNamespaces.window(null, first), firstHoldAddress); + firstHold.add(new Instant(22L)); + + StateTag> secondHoldAddress = + StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); + WatermarkStateInternal secondHold = + internals.state(StateNamespaces.window(null, second), secondHoldAddress); + secondHold.add(new Instant(2L)); + + internals.commit(); + assertThat(internals.getEarliestWatermarkHold(), equalTo(new Instant(2L))); + } + + @Test + public void testGetEarliestWatermarkHoldWithEarliestInUnderlyingTable() { + BoundedWindow first = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(2048L); + } + }; + BoundedWindow second = new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(689743L); + } + }; + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); + StateTag> firstHoldAddress = + StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); + WatermarkStateInternal firstHold = + underlying.state(StateNamespaces.window(null, first), firstHoldAddress); + firstHold.add(new Instant(22L)); + + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying("foo", underlying.commit()); + + StateTag> secondHoldAddress = + StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); + WatermarkStateInternal secondHold = + internals.state(StateNamespaces.window(null, second), secondHoldAddress); + secondHold.add(new Instant(244L)); + + internals.commit(); + assertThat(internals.getEarliestWatermarkHold(), equalTo(new Instant(22L))); + } + + @Test + public void testGetEarliestWatermarkHoldWithEarliestInNewTable() { + BoundedWindow first = + new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(2048L); + } + }; + BoundedWindow second = + new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(689743L); + } + }; + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); + StateTag> firstHoldAddress = + StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); + WatermarkStateInternal firstHold = + underlying.state(StateNamespaces.window(null, first), firstHoldAddress); + firstHold.add(new Instant(224L)); + + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying("foo", underlying.commit()); + + StateTag> secondHoldAddress = + StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); + WatermarkStateInternal secondHold = + internals.state(StateNamespaces.window(null, second), secondHoldAddress); + secondHold.add(new Instant(24L)); + + internals.commit(); + assertThat(internals.getEarliestWatermarkHold(), equalTo(new Instant(24L))); + } + + @Test + public void testGetEarliestHoldBeforeCommit() { + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + + internals + .state( + StateNamespaces.global(), + StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp())) + .add(new Instant(1234L)); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage(CopyOnAccessInMemoryStateInternals.class.getSimpleName()); + thrown.expectMessage("Can't get the earliest watermark hold"); + thrown.expectMessage("before it is committed"); + + internals.getEarliestWatermarkHold(); + } } From af9b77c3c41e6c0fda9f4a1c6f30db3d3f73c174 Mon Sep 17 00:00:00 2001 From: tgroh Date: Thu, 18 Feb 2016 19:16:02 -0800 Subject: [PATCH 173/751] Add ForwardingPTransform This is a PTransform that forwards all nonoverriden method calls to a delegate, provided by an extending class. This can be used to construct PTransform overrides that only override specific methods (e.g. apply for a Runner PTransform override) ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115027379 --- .../inprocess/ForwardingPTransform.java | 54 ++++++++++ .../inprocess/ForwardingPTransformTest.java | 100 ++++++++++++++++++ 2 files changed, 154 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java new file mode 100644 index 0000000000..b736e35d31 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; +import com.google.cloud.dataflow.sdk.values.TypedPValue; + +/** + * A base class for implementing {@link PTransform} overrides, which behave identically to the + * delegate transform but with overridden methods. Implementors are required to implement + * {@link #delegate()}, which returns the object to forward calls to, and {@link #apply(PInput)}. + */ +public abstract class ForwardingPTransform + extends PTransform { + protected abstract PTransform delegate(); + + @Override + public OutputT apply(InputT input) { + return delegate().apply(input); + } + + @Override + public void validate(InputT input) { + delegate().validate(input); + } + + @Override + public String getName() { + return delegate().getName(); + } + + @Override + public Coder getDefaultOutputCoder(InputT input, @SuppressWarnings("unused") + TypedPValue output) throws CannotProvideCoderException { + return delegate().getDefaultOutputCoder(input, output); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java new file mode 100644 index 0000000000..2e283f50b8 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** + * Tests for {@link ForwardingPTransform}. + */ +@RunWith(JUnit4.class) +public class ForwardingPTransformTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Mock private PTransform, PCollection> delegate; + + private ForwardingPTransform, PCollection> forwarding; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + forwarding = + new ForwardingPTransform, PCollection>() { + @Override + protected PTransform, PCollection> delegate() { + return delegate; + } + }; + } + + @Test + public void applyDelegates() { + @SuppressWarnings("unchecked") + PCollection collection = mock(PCollection.class); + @SuppressWarnings("unchecked") + PCollection output = mock(PCollection.class); + when(delegate.apply(collection)).thenReturn(output); + PCollection result = forwarding.apply(collection); + assertThat(result, equalTo(output)); + } + + @Test + public void getNameDelegates() { + String name = "My_forwardingptransform-name;for!thisTest"; + when(delegate.getName()).thenReturn(name); + assertThat(forwarding.getName(), equalTo(name)); + } + + @Test + public void validateDelegates() { + @SuppressWarnings("unchecked") + PCollection input = mock(PCollection.class); + doThrow(RuntimeException.class).when(delegate).validate(input); + + thrown.expect(RuntimeException.class); + forwarding.validate(input); + } + + @Test + public void getDefaultOutputCoderDelegates() throws Exception { + @SuppressWarnings("unchecked") + PCollection input = mock(PCollection.class); + @SuppressWarnings("unchecked") + PCollection output = mock(PCollection.class); + @SuppressWarnings("unchecked") + Coder outputCoder = mock(Coder.class); + + when(delegate.getDefaultOutputCoder(input, output)).thenReturn(outputCoder); + assertThat(forwarding.getDefaultOutputCoder(input, output), equalTo(outputCoder)); + } +} From 2f627c346a06cb788e1fbcc086746806044f504b Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 18 Feb 2016 19:46:57 -0800 Subject: [PATCH 174/751] Move test for post-GBK timestamp ordering to worker module This test is not part of the spec. As long as the keys and windows are grouped, the grouped values can be in any order. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115028575 --- .../transforms/windowing/WindowingTest.java | 51 ------------------- 1 file changed, 51 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java index c216190081..1c1248bd0c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java @@ -16,10 +16,6 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.io.TextIO; @@ -31,15 +27,12 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.collect.Iterables; import org.joda.time.Duration; import org.joda.time.Instant; @@ -194,50 +187,6 @@ public void testWindowPreservation() { p.run(); } - @Test - @Category(RunnableOnService.class) - public void testElementsSortedByTimestamp() { - // The Windowing API does not guarantee that elements will be sorted by - // timestamp, but the implementation currently relies on this, so it - // needs to be tested. - - Pipeline p = TestPipeline.create(); - - PCollection> a = p - .apply(Create.timestamped( - TimestampedValue.of(KV.of("k", "a"), new Instant(1)), - TimestampedValue.of(KV.of("k", "b"), new Instant(4)), - TimestampedValue.of(KV.of("k", "c"), new Instant(3)), - TimestampedValue.of(KV.of("k", "d"), new Instant(5)), - TimestampedValue.of(KV.of("k", "e"), new Instant(2)), - TimestampedValue.of(KV.of("k", "f"), new Instant(-5)), - TimestampedValue.of(KV.of("k", "g"), new Instant(-6)), - TimestampedValue.of(KV.of("k", "h"), new Instant(-255)), - TimestampedValue.of(KV.of("k", "i"), new Instant(-256)), - TimestampedValue.of(KV.of("k", "j"), new Instant(255)))); - - PCollection> b = a - .apply(Window.>into( - FixedWindows.of(new Duration(1000)).withOffset(new Duration(500)))); - - PCollection>> output = b - .apply(GroupByKey.create()); - - DataflowAssert.that(output).satisfies( - new SerializableFunction>>, Void>() { - @Override - public Void apply(Iterable>> contents) { - KV> element = Iterables.getOnlyElement(contents); - assertThat(element.getKey(), equalTo("k")); - assertThat(element.getValue(), - contains("i", "h", "g", "f", "a", "e", "c", "b", "d", "j")); - return null; - } - }); - - p.run(); - } - @Test public void testEmptyInput() { Pipeline p = TestPipeline.create(); From ade6ae841dcc4f2427d37084f203b5c4f593767d Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 18 Feb 2016 20:57:56 -0800 Subject: [PATCH 175/751] Move DataflowWorkerLoggingMDC to the worker module ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115031881 --- .../logging/DataflowWorkerLoggingMDC.java | 98 ------------------- .../dataflow/sdk/util/DoFnRunnerBase.java | 32 ++---- .../testing/RestoreDataflowLoggingMDC.java | 52 ---------- .../RestoreDataflowLoggingMDCTest.java | 81 --------------- 4 files changed, 10 insertions(+), 253 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingMDC.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDC.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDCTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingMDC.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingMDC.java deleted file mode 100644 index 4d387c22c1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/logging/DataflowWorkerLoggingMDC.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker.logging; - -/** - * Mapped diagnostic context for the Dataflow worker. - */ -public class DataflowWorkerLoggingMDC { - private static final InheritableThreadLocal jobId = new InheritableThreadLocal<>(); - private static final InheritableThreadLocal stageName = new InheritableThreadLocal<>(); - private static final InheritableThreadLocal stepName = new InheritableThreadLocal<>(); - private static final InheritableThreadLocal workerId = new InheritableThreadLocal<>(); - private static final InheritableThreadLocal workId = new InheritableThreadLocal<>(); - - /** - * Sets the Job ID of the current thread, which will be inherited by child threads. - */ - public static void setJobId(String newJobId) { - jobId.set(newJobId); - } - - /** - * Sets the Stage Name of the current thread, which will be inherited by child threads. - */ - public static void setStageName(String newStageName) { - stageName.set(newStageName); - } - - /** - * Sets the Step Name of the current thread, which will be inherited by child threads. - */ - public static void setStepName(String newStepName) { - stepName.set(newStepName); - } - - /** - * Sets the Worker ID of the current thread, which will be inherited by child threads. - */ - public static void setWorkerId(String newWorkerId) { - workerId.set(newWorkerId); - } - - /** - * Sets the Work ID of the current thread, which will be inherited by child threads. - */ - public static void setWorkId(String newWorkId) { - workId.set(newWorkId); - } - - /** - * Gets the Job ID of the current thread. - */ - public static String getJobId() { - return jobId.get(); - } - - /** - * Gets the Stage Name of the current thread. - */ - public static String getStageName() { - return stageName.get(); - } - - /** - * Gets the Step Name of the current thread. - */ - public static String getStepName() { - return stepName.get(); - } - - /** - * Gets the Worker ID of the current thread. - */ - public static String getWorkerId() { - return workerId.get(); - } - - /** - * Gets the Work ID of the current thread. - */ - public static String getWorkId() { - return workId.get(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index a3e22a660f..25ead03bce 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -20,7 +20,6 @@ import com.google.cloud.dataflow.sdk.coders.IterableCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -133,28 +132,17 @@ public void startBundle() { @Override public void processElement(WindowedValue elem) { - // TODO: Move the DataflowWorkerLoggingMDC into wrapper used on the Dataflow worker in - // invokeProcessElement - // Setup new thread local logging before running user code, and restore it after. - // Needs to happen here (per-element) since fusion may be running this as part of a call to - // output in an earlier step. - String previousStepName = DataflowWorkerLoggingMDC.getStepName(); - DataflowWorkerLoggingMDC.setStepName(context.stepContext.getStepName()); - try { - if (elem.getWindows().size() <= 1 - || (!RequiresWindowAccess.class.isAssignableFrom(fn.getClass()) - && context.sideInputReader.isEmpty())) { - invokeProcessElement(elem); - } else { - // We could modify the windowed value (and the processContext) to - // avoid repeated allocations, but this is more straightforward. - for (BoundedWindow window : elem.getWindows()) { - invokeProcessElement(WindowedValue.of( - elem.getValue(), elem.getTimestamp(), window, elem.getPane())); - } + if (elem.getWindows().size() <= 1 + || (!RequiresWindowAccess.class.isAssignableFrom(fn.getClass()) + && context.sideInputReader.isEmpty())) { + invokeProcessElement(elem); + } else { + // We could modify the windowed value (and the processContext) to + // avoid repeated allocations, but this is more straightforward. + for (BoundedWindow window : elem.getWindows()) { + invokeProcessElement(WindowedValue.of( + elem.getValue(), elem.getTimestamp(), window, elem.getPane())); } - } finally { - DataflowWorkerLoggingMDC.setStepName(previousStepName); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDC.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDC.java deleted file mode 100644 index e64853e837..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDC.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; - -import org.junit.rules.ExternalResource; - -/** - * Saves and restores the current thread-local logging parameters for tests. - */ -public class RestoreDataflowLoggingMDC extends ExternalResource { - private String previousJobId; - private String previousStageName; - private String previousStepName; - private String previousWorkerId; - private String previousWorkId; - - public RestoreDataflowLoggingMDC() {} - - @Override - protected void before() throws Throwable { - previousJobId = DataflowWorkerLoggingMDC.getJobId(); - previousStageName = DataflowWorkerLoggingMDC.getStageName(); - previousStepName = DataflowWorkerLoggingMDC.getStepName(); - previousWorkerId = DataflowWorkerLoggingMDC.getWorkerId(); - previousWorkId = DataflowWorkerLoggingMDC.getWorkId(); - } - - @Override - protected void after() { - DataflowWorkerLoggingMDC.setJobId(previousJobId); - DataflowWorkerLoggingMDC.setStageName(previousStageName); - DataflowWorkerLoggingMDC.setStepName(previousStepName); - DataflowWorkerLoggingMDC.setWorkerId(previousWorkerId); - DataflowWorkerLoggingMDC.setWorkId(previousWorkId); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDCTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDCTest.java deleted file mode 100644 index c122b281bb..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreDataflowLoggingMDCTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.runners.worker.logging.DataflowWorkerLoggingMDC; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link RestoreDataflowLoggingMDC}. */ -@RunWith(JUnit4.class) -public class RestoreDataflowLoggingMDCTest { - @Rule public TestRule restoreMDC = new RestoreDataflowLoggingMDC(); - - /** - * Asserts that all fields of DataflowWorkerLoggingMDC field are null, except a single - * index with the expected value. - */ - void assertOneNonNullThreadStatic(int idx, String expected) { - String[] strs = - new String[] { - DataflowWorkerLoggingMDC.getJobId(), - DataflowWorkerLoggingMDC.getStageName(), - DataflowWorkerLoggingMDC.getStepName(), - DataflowWorkerLoggingMDC.getWorkerId(), - DataflowWorkerLoggingMDC.getWorkId() - }; - for (int i = 0; i < strs.length; i++) { - assertEquals(i == idx ? expected : null, strs[i]); - } - } - - @Test - public void testLoggingParamsClearedA() { - DataflowWorkerLoggingMDC.setJobId("job"); - assertOneNonNullThreadStatic(0, "job"); - } - - @Test - public void testLoggingParamsClearedB() { - DataflowWorkerLoggingMDC.setStageName("stage"); - assertOneNonNullThreadStatic(1, "stage"); - } - - @Test - public void testLoggingParamsClearedC() { - DataflowWorkerLoggingMDC.setStepName("step"); - assertOneNonNullThreadStatic(2, "step"); - } - - @Test - public void testLoggingParamsClearedD() { - DataflowWorkerLoggingMDC.setWorkerId("worker"); - assertOneNonNullThreadStatic(3, "worker"); - } - - @Test - public void testLoggingParamsClearedE() { - DataflowWorkerLoggingMDC.setWorkId("work"); - assertOneNonNullThreadStatic(4, "work"); - } -} From e0d7d0ccb303c04da1068026b42e96afbfd7a3e7 Mon Sep 17 00:00:00 2001 From: lcwik Date: Fri, 19 Feb 2016 09:34:26 -0800 Subject: [PATCH 176/751] Rolling back since this breaks tests Migrate TextIO.Read to be a custom source This allows for other runners to utilize the TextIO.Read transform since it no longer relies on the internal details of the Google Cloud Dataflow runner. Note that validation has moved to when the PTransform is being applied. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115071294 --- examples/pom.xml | 7 - .../examples/MinimalWordCountJava8Test.java | 45 +-- .../google/cloud/dataflow/sdk/io/TextIO.java | 286 ++---------------- .../runners/DataflowPipelineTranslator.java | 2 + .../sdk/runners/dataflow/ReadTranslator.java | 10 - .../runners/dataflow/TextIOTranslator.java | 34 +++ .../cloud/dataflow/sdk/io/TextIOTest.java | 240 ++++----------- .../runners/DataflowPipelineRunnerTest.java | 40 +-- .../DataflowPipelineTranslatorTest.java | 17 +- .../sdk/runners/TransformTreeTest.java | 43 +-- 10 files changed, 163 insertions(+), 561 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index adea4b1298..8e708ced69 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -498,12 +498,5 @@ junit ${junit.version} - - - org.mockito - mockito-all - 1.9.5 - test - diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java index fcae41c6bb..5286d61a07 100644 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java +++ b/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java @@ -18,33 +18,20 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.GcsOptions; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.FlatMapElements; import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import java.io.IOException; import java.io.Serializable; -import java.nio.channels.FileChannel; -import java.nio.channels.SeekableByteChannel; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; import java.util.Arrays; -import java.util.List; /** * To keep {@link MinimalWordCountJava8} simple, it is not factored or testable. This test @@ -57,9 +44,8 @@ public class MinimalWordCountJava8Test implements Serializable { * A basic smoke test that ensures there is no crash at pipeline construction time. */ @Test - public void testMinimalWordCountJava8() throws Exception { + public void testMinimalWordCountJava8() { Pipeline p = TestPipeline.create(); - p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); p.apply(TextIO.Read.from("gs://dataflow-samples/shakespeare/*")) .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) @@ -71,33 +57,4 @@ public void testMinimalWordCountJava8() throws Exception { .withOutputType(new TypeDescriptor() {})) .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); } - - private GcsUtil buildMockGcsUtil() throws IOException { - GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); - - // Any request to open gets a new bogus channel - Mockito - .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); - - // Any request for expansion returns a list containing the original GcsPath - // This is required to pass validation that occurs in TextIO during apply() - Mockito - .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); - - return mockGcsUtil; - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 71e755eebe..bf72f6bf19 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -16,41 +16,32 @@ package com.google.cloud.dataflow.sdk.io; -import static com.google.common.base.Preconditions.checkState; - import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.runners.worker.TextReader; import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; -import com.google.protobuf.ByteString; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SeekableByteChannel; import java.util.List; -import java.util.NoSuchElementException; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; @@ -212,7 +203,7 @@ public static class Bound extends PTransform> { @Nullable private final String filepattern; /** The Coder to use to decode each line. */ - private final Coder coder; + @Nullable private final Coder coder; /** An option to indicate if input validation is desired. Default is true. */ private final boolean validate; @@ -301,48 +292,14 @@ public PCollection apply(PInput input) { if (filepattern == null) { throw new IllegalStateException("need to set the filepattern of a TextIO.Read transform"); } - - if (validate) { - try { - checkState( - !IOChannelUtils.getFactory(filepattern).match(filepattern).isEmpty(), - "Unable to find any files matching %s", - filepattern); - } catch (IOException e) { - throw new IllegalStateException( - String.format("Failed to validate %s", filepattern), e); - } - } - - // Create a source specific to the requested compression type. - final Bounded read; - switch(compressionType) { - case UNCOMPRESSED: - read = com.google.cloud.dataflow.sdk.io.Read.from( - new TextSource(filepattern, coder)); - break; - case AUTO: - read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource(filepattern, coder))); - break; - case BZIP2: - read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource(filepattern, coder)) - .withDecompression(CompressedSource.CompressionMode.BZIP2)); - break; - case GZIP: - read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource(filepattern, coder)) - .withDecompression(CompressedSource.CompressionMode.GZIP)); - break; - default: - throw new IllegalArgumentException("Unknown compression mode: " + compressionType); - } - - PCollection pcol = input.getPipeline().apply("Read", read); - // Honor the default output coder that would have been used by this PTransform. - pcol.setCoder(getDefaultOutputCoder()); - return pcol; + // Force the output's Coder to be what the read is using, and + // unchangeable later, to ensure that we read the input in the + // format specified by the Read transform. + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), + WindowingStrategy.globalDefault(), + IsBounded.BOUNDED) + .setCoder(coder); } @Override @@ -361,6 +318,17 @@ public boolean needsValidation() { public TextIO.CompressionType getCompressionType() { return compressionType; } + + static { + DirectPipelineRunner.registerDefaultTransformEvaluator( + Bound.class, new DirectPipelineRunner.TransformEvaluator() { + @Override + public void evaluate( + Bound transform, DirectPipelineRunner.EvaluationContext context) { + evaluateReadHelper(transform, context); + } + }); + } } /** Disallow construction of utility classes. */ @@ -813,204 +781,16 @@ private static void validateOutputComponent(String partialFilePattern) { /** Disable construction of utility class. */ private TextIO() {} - /** - * A {@link FileBasedSource} which can decode records delimited by new line characters. - * - *

    This source splits the data into records using {@code UTF-8} {@code \n}, {@code \r}, or - * {@code \r\n} as the delimiter. This source is not strict and supports decoding the last record - * even if it is not delimited. Finally, no records are decoded if the stream is empty. - * - *

    This source supports reading from any arbitrary byte position within the stream. If the - * starting position is not {@code 0}, then bytes are skipped until the first delimiter is found - * representing the beginning of the first record to be decoded. - */ - @VisibleForTesting - static class TextSource extends FileBasedSource { - /** The Coder to use to decode each line. */ - private final Coder coder; - - @VisibleForTesting - TextSource(String fileSpec, Coder coder) { - super(fileSpec, 1L); - this.coder = coder; - } - - private TextSource(String fileName, long start, long end, Coder coder) { - super(fileName, 1L, start, end); - this.coder = coder; - } - - @Override - protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { - return new TextSource<>(fileName, start, end, coder); - } - - @Override - protected FileBasedReader createSingleFileReader(PipelineOptions options) { - return new TextBasedReader<>(this); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public Coder getDefaultOutputCoder() { - return coder; - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader FileBasedReader} - * which can decode records delimited by new line characters. - * - * See {@link TextSource} for further details. - */ - @VisibleForTesting - static class TextBasedReader extends FileBasedReader { - private static final int READ_BUFFER_SIZE = 8192; - private final Coder coder; - private final ByteBuffer readBuffer = ByteBuffer.allocate(READ_BUFFER_SIZE); - private ByteString buffer; - private int startOfSeparatorInBuffer; - private int endOfSeparatorInBuffer; - private long startOfNextRecord; - private boolean eof; - private boolean elementIsPresent; - private T currentValue; - private ReadableByteChannel inChannel; - - private TextBasedReader(TextSource source) { - super(source); - coder = source.coder; - buffer = ByteString.EMPTY; - } - - @Override - protected long getCurrentOffset() throws NoSuchElementException { - if (!elementIsPresent) { - throw new NoSuchElementException(); - } - return startOfNextRecord; - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (!elementIsPresent) { - throw new NoSuchElementException(); - } - return currentValue; - } - - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - this.inChannel = channel; - // If the first offset is greater than zero, we need to skip bytes until we see our - // first separator. - if (getCurrentSource().getStartOffset() > 0) { - checkState(channel instanceof SeekableByteChannel, - "%s only supports reading from a SeekableByteChannel when given a start offset" - + " greater than 0.", TextSource.class.getSimpleName()); - long requiredPosition = getCurrentSource().getStartOffset() - 1; - ((SeekableByteChannel) channel).position(requiredPosition); - findSeparatorBounds(); - buffer = buffer.substring(endOfSeparatorInBuffer); - startOfNextRecord = requiredPosition + endOfSeparatorInBuffer; - endOfSeparatorInBuffer = 0; - startOfSeparatorInBuffer = 0; - } - } - - /** - * Locates the start position and end position of the next delimiter. Will - * consume the channel till either EOF or the delimiter bounds are found. - * - *

    This fills the buffer and updates the positions as follows: - *

    {@code
    -       * ------------------------------------------------------
    -       * | element bytes | delimiter bytes | unconsumed bytes |
    -       * ------------------------------------------------------
    -       * 0            start of          end of              buffer
    -       *              separator         separator           size
    -       *              in buffer         in buffer
    -       * }
    - */ - private void findSeparatorBounds() throws IOException { - int bytePositionInBuffer = 0; - while (true) { - if (!tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 1)) { - startOfSeparatorInBuffer = endOfSeparatorInBuffer = bytePositionInBuffer; - break; - } - - byte currentByte = buffer.byteAt(bytePositionInBuffer); - - if (currentByte == '\n') { - startOfSeparatorInBuffer = bytePositionInBuffer; - endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; - break; - } else if (currentByte == '\r') { - startOfSeparatorInBuffer = bytePositionInBuffer; - endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; - - if (tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 2)) { - currentByte = buffer.byteAt(bytePositionInBuffer + 1); - if (currentByte == '\n') { - endOfSeparatorInBuffer += 1; - } - } - break; - } - - // Move to the next byte in buffer. - bytePositionInBuffer += 1; - } - } - - @Override - protected boolean readNextRecord() throws IOException { - startOfNextRecord += endOfSeparatorInBuffer; - findSeparatorBounds(); - - // If we have reached EOF file and consumed all of the buffer then we know - // that there are no more records. - if (eof && buffer.size() == 0) { - elementIsPresent = false; - return false; - } - - decodeCurrentElement(); - return true; - } - - /** - * Decodes the current element updating the buffer to only contain the unconsumed bytes. - * - * This invalidates the currently stored {@code startOfSeparatorInBuffer} and - * {@code endOfSeparatorInBuffer}. - */ - private void decodeCurrentElement() throws IOException { - ByteString dataToDecode = buffer.substring(0, startOfSeparatorInBuffer); - currentValue = coder.decode(dataToDecode.newInput(), Context.OUTER); - elementIsPresent = true; - buffer = buffer.substring(endOfSeparatorInBuffer); - } - - /** - * Returns false if we were unable to ensure the minimum capacity by consuming the channel. - */ - private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOException { - // While we aren't at EOF or haven't fulfilled the minimum buffer capacity, - // attempt to read more bytes. - while (buffer.size() <= minCapacity && !eof) { - eof = inChannel.read(readBuffer) == -1; - readBuffer.flip(); - buffer = buffer.concat(ByteString.copyFrom(readBuffer)); - readBuffer.clear(); - } - // Return true if we were able to honor the minimum buffer capacity request - return buffer.size() >= minCapacity; - } + private static void evaluateReadHelper( + Read.Bound transform, DirectPipelineRunner.EvaluationContext context) { + TextReader reader = + new TextReader<>(transform.filepattern, true, null, null, transform.coder, + transform.getCompressionType()); + try { + List elems = ReaderUtils.readAllFromReader(reader); + context.setPCollection(context.getOutput(transform), elems); + } catch (IOException e) { + throw new RuntimeException(e); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index f7217f7610..1d14254c24 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -1042,6 +1042,8 @@ private void translateHelper( DataflowPipelineRunner.StreamingPubsubIOWrite.class, new PubsubIOTranslator.WriteTranslator()); + registerTransformTranslator( + TextIO.Read.Bound.class, new TextIOTranslator.ReadTranslator()); registerTransformTranslator( TextIO.Write.Bound.class, new TextIOTranslator.WriteTranslator()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java index 47a1926764..2513d431cb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java @@ -18,7 +18,6 @@ import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudSourceToDictionary; -import com.google.cloud.dataflow.sdk.io.FileBasedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Source; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; @@ -41,15 +40,6 @@ public static void translateReadHelper(Source source, PTransform transform, DataflowPipelineTranslator.TranslationContext context) { try { - // TODO: Move this validation out of translation once IOChannelUtils is portable - // and can be reconstructed on the worker. - if (source instanceof FileBasedSource) { - String filePatternOrSpec = ((FileBasedSource) source).getFileOrPatternSpec(); - context.getPipelineOptions() - .getPathValidator() - .validateInputFilePatternSupported(filePatternOrSpec); - } - context.addStep(transform, "ParallelRead"); context.addInput(PropertyNames.FORMAT, PropertyNames.CUSTOM_SOURCE_FORMAT); context.addInput( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java index d6c96c31bd..abdf07fa58 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java @@ -29,6 +29,40 @@ * TextIO transform support code for the Dataflow backend. */ public class TextIOTranslator { + + /** + * Implements TextIO Read translation for the Dataflow backend. + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static class ReadTranslator implements TransformTranslator { + @Override + public void translate( + TextIO.Read.Bound transform, + TranslationContext context) { + translateReadHelper(transform, context); + } + + private void translateReadHelper( + TextIO.Read.Bound transform, + TranslationContext context) { + if (context.getPipelineOptions().isStreaming()) { + throw new IllegalArgumentException("TextIO not supported in streaming mode."); + } + + PathValidator validator = context.getPipelineOptions().getPathValidator(); + String filepattern = validator.validateInputFilePatternSupported(transform.getFilepattern()); + + context.addStep(transform, "ParallelRead"); + // TODO: How do we want to specify format and + // format-specific properties? + context.addInput(PropertyNames.FORMAT, "text"); + context.addInput(PropertyNames.FILEPATTERN, filepattern); + context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); + context.addInput(PropertyNames.VALIDATE_SOURCE, transform.needsValidation()); + context.addInput(PropertyNames.COMPRESSION_TYPE, transform.getCompressionType().toString()); + } + } + /** * Implements TextIO Write translation for the Dataflow backend. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 6ad81e4ea0..abd8333bc4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -20,7 +20,7 @@ import static com.google.cloud.dataflow.sdk.TestUtils.LINES_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_INTS_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES_ARRAY; -import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; @@ -30,12 +30,9 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.TextIO.CompressionType; -import com.google.cloud.dataflow.sdk.io.TextIO.TextSource; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -46,7 +43,6 @@ import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.collect.ImmutableList; import org.junit.Rule; import org.junit.Test; @@ -55,8 +51,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.io.BufferedReader; import java.io.File; @@ -64,11 +58,8 @@ import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; -import java.nio.channels.FileChannel; +import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -83,31 +74,60 @@ public class TextIOTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); + private static class EmptySeekableByteChannel implements SeekableByteChannel { + @Override + public long position() { + return 0L; + } + + @Override + public SeekableByteChannel position(long newPosition) { + return this; + } + + @Override + public long size() { + return 0L; + } + + @Override + public SeekableByteChannel truncate(long size) { + return this; + } + + @Override + public int write(ByteBuffer src) { + return 0; + } + + @Override + public int read(ByteBuffer dst) { + return 0; + } + + @Override + public boolean isOpen() { + return true; + } + + @Override + public void close() { } + } + private GcsUtil buildMockGcsUtil() throws IOException { GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); // Any request to open gets a new bogus channel Mockito .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); - - // Any request for expansion returns a list containing the original GcsPath - // This is required to pass validation that occurs in TextIO during apply() + .thenReturn(new EmptySeekableByteChannel()); + + // Any request for expansion gets a single bogus URL + // after we first run the expansion code (which will generally + // return no results, which causes a crash we aren't testing) Mockito .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); + .thenReturn(Arrays.asList(GcsPath.fromUri("gs://bucket/foo"))); return mockGcsUtil; } @@ -169,31 +189,25 @@ public void testReadEmptyInts() throws Exception { } @Test - public void testReadNulls() throws Exception { - runTestRead(new Void[]{ null, null, null }, VoidCoder.of()); - } - - @Test - public void testReadNamed() throws Exception { - String file = tmpFolder.newFile().getAbsolutePath(); + public void testReadNamed() { Pipeline p = TestPipeline.create(); { PCollection output1 = - p.apply(TextIO.Read.from(file)); - assertEquals("TextIO.Read/Read.out", output1.getName()); + p.apply(TextIO.Read.from("/tmp/file.txt")); + assertEquals("TextIO.Read.out", output1.getName()); } { PCollection output2 = - p.apply(TextIO.Read.named("MyRead").from(file)); - assertEquals("MyRead/Read.out", output2.getName()); + p.apply(TextIO.Read.named("MyRead").from("/tmp/file.txt")); + assertEquals("MyRead.out", output2.getName()); } { PCollection output3 = - p.apply(TextIO.Read.from(file).named("HerRead")); - assertEquals("HerRead/Read.out", output3.getName()); + p.apply(TextIO.Read.from("/tmp/file.txt").named("HerRead")); + assertEquals("HerRead.out", output3.getName()); } } @@ -364,11 +378,12 @@ private void applyRead(Pipeline pipeline, String path) { public void testBadWildcardRecursive() throws Exception { Pipeline pipeline = TestPipeline.create(); - // Check that applying does fail. + pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); + + // Check that running does fail. expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("wildcard"); - - pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); + pipeline.run(); } @Test @@ -396,7 +411,7 @@ public void testCompressionTypeIsSet() throws Exception { @Test public void testCompressedRead() throws Exception { String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; - File tmpFile = tmpFolder.newFile(); + File tmpFile = tmpFolder.newFile("test"); String filename = tmpFile.getPath(); List expected = new ArrayList<>(); @@ -416,12 +431,14 @@ public void testCompressedRead() throws Exception { DataflowAssert.that(output).containsInAnyOrder(expected); p.run(); + + tmpFile.delete(); } @Test public void testGZIPReadWhenUncompressed() throws Exception { String[] lines = {"Meritorious condor", "Obnoxious duck"}; - File tmpFile = tmpFolder.newFile(); + File tmpFile = tmpFolder.newFile("test"); String filename = tmpFile.getPath(); List expected = new ArrayList<>(); @@ -439,6 +456,8 @@ public void testGZIPReadWhenUncompressed() throws Exception { DataflowAssert.that(output).containsInAnyOrder(expected); p.run(); + + tmpFile.delete(); } @Test @@ -452,133 +471,4 @@ public void testTextIOGetName() { assertEquals( "ReadMyFile [TextIO.Read]", TextIO.Read.named("ReadMyFile").from("somefile").toString()); } - - @Test - public void testReadEmptyLines() throws Exception { - runTestReadWithData("\n\n\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("", "", "")); - } - - @Test - public void testReadFileWithLineFeedDelimiter() throws Exception { - runTestReadWithData("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnDelimiter() throws Exception { - runTestReadWithData("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnAndLineFeedDelimiter() throws Exception { - runTestReadWithData("asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithMixedDelimiters() throws Exception { - runTestReadWithData("asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { - runTestReadWithData("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() throws Exception { - runTestReadWithData("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() - throws Exception { - runTestReadWithData("asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { - runTestReadWithData("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - private void runTestReadWithData(byte[] data, List expectedResults) throws Exception { - TextSource source = prepareSource(data); - List actual = SourceTestUtils.readFromSource(source, PipelineOptionsFactory.create()); - assertThat(actual, containsInAnyOrder(new ArrayList<>(expectedResults).toArray(new String[0]))); - } - - @Test - public void testSplittingSourceWithEmptyLines() throws Exception { - TextSource source = prepareSource("\n\n\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithLineFeedDelimiter() throws Exception { - TextSource source = prepareSource("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnDelimiter() throws Exception { - TextSource source = prepareSource("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiter() throws Exception { - TextSource source = prepareSource( - "asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithMixedDelimiters() throws Exception { - TextSource source = prepareSource( - "asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { - TextSource source = prepareSource("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() - throws Exception { - TextSource source = prepareSource("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() - throws Exception { - TextSource source = prepareSource( - "asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { - TextSource source = prepareSource("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - private TextSource prepareSource(byte[] data) throws IOException { - File file = tmpFolder.newFile(); - Files.write(file.toPath(), data); - - TextSource source = new TextSource<>(file.toPath().toString(), StringUtf8Coder.of()); - - return source; - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index c7175cb3b0..6d9f90f39e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -19,7 +19,6 @@ import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertEquals; @@ -96,22 +95,18 @@ import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.FileChannel; -import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.ArrayList; @@ -180,23 +175,12 @@ private static Dataflow buildMockDataflow( private GcsUtil buildMockGcsUtil(boolean bucketExists) throws IOException { GcsUtil mockGcsUtil = mock(GcsUtil.class); - when(mockGcsUtil.create(any(GcsPath.class), anyString())) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); - + when(mockGcsUtil.create( + any(GcsPath.class), anyString())) + .thenReturn(FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE)); when(mockGcsUtil.isGcsPatternSupported(anyString())).thenReturn(true); - when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(bucketExists); return mockGcsUtil; } @@ -441,12 +425,10 @@ public void testNonGcsFilePathInReadFailure() throws IOException { ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); - p.apply(TextIO.Read.named("ReadMyNonGcsFile").from(tmpFolder.newFile().getPath())); + p.apply(TextIO.Read.named("ReadMyNonGcsFile").from("/tmp/file")); - thrown.expectCause(Matchers.allOf( - instanceOf(IllegalArgumentException.class), - ThrowableMessageMatcher.hasMessage( - containsString("expected a valid 'gs://' path but was given")))); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); p.run(); assertValidJob(jobCaptor.getValue()); } @@ -473,9 +455,8 @@ public void testMultiSlashGcsFileReadPath() throws IOException { p.apply(TextIO.Read.named("ReadInvalidGcsFile") .from("gs://bucket/tmp//file")); - thrown.expectCause(Matchers.allOf( - instanceOf(IllegalArgumentException.class), - ThrowableMessageMatcher.hasMessage(containsString("consecutive slashes")))); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("consecutive slashes"); p.run(); assertValidJob(jobCaptor.getValue()); } @@ -1145,7 +1126,6 @@ public void testToIsmRecordForMapLikeDoFnWithoutUniqueKeysThrowsException() thro try { doFnTester.processBatch(inputElements); - fail("Expected UserCodeException"); } catch (UserCodeException e) { assertTrue(e.getCause() instanceof IllegalStateException); IllegalStateException rootCause = (IllegalStateException) e.getCause(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index b9c94ad00b..98efc001a9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -19,8 +19,6 @@ import static com.google.cloud.dataflow.sdk.util.Structs.addObject; import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -68,17 +66,13 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; -import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentMatcher; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.io.IOException; import java.util.Collections; @@ -144,12 +138,6 @@ private static Dataflow buildMockDataflow( private static DataflowPipelineOptions buildPipelineOptions() throws IOException { GcsUtil mockGcsUtil = mock(GcsUtil.class); - when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(true); when(mockGcsUtil.isGcsPatternSupported(anyString())).thenCallRealMethod(); @@ -647,9 +635,8 @@ public void testBadWildcardRecursive() throws Exception { pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); // Check that translation does fail. - thrown.expectCause(Matchers.allOf( - instanceOf(IllegalArgumentException.class), - ThrowableMessageMatcher.hasMessage(containsString("Unsupported wildcard usage")))); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Unsupported wildcard usage"); t.translate(pipeline, pipeline.getRunner(), Collections.emptyList()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java index f1b7cd7fd0..cb34e5c117 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java @@ -18,15 +18,10 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -39,13 +34,11 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PValue; -import org.junit.Rule; +import org.junit.Assert; import org.junit.Test; -import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.File; import java.util.Arrays; import java.util.EnumSet; @@ -54,7 +47,6 @@ */ @RunWith(JUnit4.class) public class TransformTreeTest { - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); enum TransformsSeen { READ, @@ -111,14 +103,11 @@ protected Coder getDefaultOutputCoder() { // visits the nodes and verifies that the hierarchy was captured. @Test public void testCompositeCapture() throws Exception { - File inputFile = tmpFolder.newFile(); - File outputFile = tmpFolder.newFile(); - Pipeline p = DirectPipeline.createForTest(); - p.apply(TextIO.Read.named("ReadMyFile").from(inputFile.getPath())) + p.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/object")) .apply(Sample.any(10)) - .apply(TextIO.Write.named("WriteMyFile").to(outputFile.getPath())); + .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/object")); final EnumSet visited = EnumSet.noneOf(TransformsSeen.class); @@ -130,19 +119,19 @@ public void testCompositeCapture() throws Exception { public void enterCompositeTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); if (transform instanceof Sample.SampleAny) { - assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); - assertNotNull(node.getEnclosingNode()); - assertTrue(node.isCompositeNode()); + Assert.assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); + Assert.assertNotNull(node.getEnclosingNode()); + Assert.assertTrue(node.isCompositeNode()); } - assertThat(transform, not(instanceOf(Read.Bounded.class))); - assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); + Assert.assertThat(transform, not(instanceOf(TextIO.Read.Bound.class))); + Assert.assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); } @Override public void leaveCompositeTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); if (transform instanceof Sample.SampleAny) { - assertTrue(left.add(TransformsSeen.SAMPLE_ANY)); + Assert.assertTrue(left.add(TransformsSeen.SAMPLE_ANY)); } } @@ -150,11 +139,11 @@ public void leaveCompositeTransform(TransformTreeNode node) { public void visitTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); // Pick is a composite, should not be visited here. - assertThat(transform, not(instanceOf(Sample.SampleAny.class))); - if (transform instanceof Read.Bounded) { - assertTrue(visited.add(TransformsSeen.READ)); + Assert.assertThat(transform, not(instanceOf(Sample.SampleAny.class))); + if (transform instanceof TextIO.Read.Bound) { + Assert.assertTrue(visited.add(TransformsSeen.READ)); } else if (transform instanceof TextIO.Write.Bound) { - assertTrue(visited.add(TransformsSeen.WRITE)); + Assert.assertTrue(visited.add(TransformsSeen.WRITE)); } } @@ -163,8 +152,8 @@ public void visitValue(PValue value, TransformTreeNode producer) { } }); - assertTrue(visited.equals(EnumSet.allOf(TransformsSeen.class))); - assertTrue(left.equals(EnumSet.of(TransformsSeen.SAMPLE_ANY))); + Assert.assertTrue(visited.equals(EnumSet.allOf(TransformsSeen.class))); + Assert.assertTrue(left.equals(EnumSet.of(TransformsSeen.SAMPLE_ANY))); } @Test(expected = IllegalStateException.class) @@ -174,7 +163,7 @@ public void testOutputChecking() throws Exception { p.apply(new InvalidCompositeTransform()); p.traverseTopologically(new RecordingPipelineVisitor()); - fail("traversal should have failed with an IllegalStateException"); + Assert.fail("traversal should have failed with an IllegalStateException"); } @Test From ba55083b3144325f079c9fe9aca9a127178b8bbb Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 19 Feb 2016 10:34:21 -0800 Subject: [PATCH 177/751] Clear empty CopyOnAccessInMemoryStateInternals InMemoryState.clear() marks the state as cleared, but does not remove the state proper from the StateTable. If a StateTable is completely empty, we should discard it, as there is no guarantee that we will ever see elements for the key it is associated with again. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115077034 --- .../CopyOnAccessInMemoryStateInternals.java | 32 +++++++++++ ...opyOnAccessInMemoryStateInternalsTest.java | 56 ++++++++++++++++++- 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java index 2a8fa47d88..4968976987 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java @@ -25,9 +25,12 @@ import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals.InMemoryState; import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; import com.google.common.base.Optional; +import com.google.common.collect.Iterables; import org.joda.time.Instant; +import java.util.Collection; +import java.util.HashSet; import java.util.Map; import javax.annotation.Nullable; @@ -102,6 +105,10 @@ public K getKey() { return key; } + public boolean isEmpty() { + return Iterables.isEmpty(table.values()); + } + /** * A {@link StateTable} that, when a value is retrieved with * {@link StateTable#get(StateNamespace, StateTag)}, first attempts to obtain a copy of existing @@ -167,6 +174,7 @@ private void commit() { } } earliestWatermarkHold = Optional.of(earliestHold); + clearEmpty(); binderFactory = new InMemoryStateBinderFactory<>(key); underlying = Optional.absent(); } @@ -187,6 +195,30 @@ private Instant getEarliestWatermarkHold() { return earliest; } + /** + * Clear all empty {@link StateNamespace StateNamespaces} from this table. If all states are + * empty, clear the entire table. + * + *

    Because {@link InMemoryState} is not removed from the {@link StateTable} after it is + * cleared, in case contents are modified after being cleared, the table must be explicitly + * checked to ensure that it contains state and removed if not (otherwise we may never use + * the table again). + */ + private void clearEmpty() { + Collection emptyNamespaces = new HashSet<>(this.getNamespacesInUse()); + for (StateNamespace namespace : this.getNamespacesInUse()) { + for (State existingState : this.getTagsInUse(namespace).values()) { + if (!((InMemoryState) existingState).isCleared()) { + emptyNamespaces.remove(namespace); + break; + } + } + } + for (StateNamespace empty : emptyNamespaces) { + this.clearNamespace(empty); + } + } + @Override protected StateBinder binderForNamespace(final StateNamespace namespace) { return binderFactory.forNamespace(namespace); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java index b9f12536f4..00887857ed 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java @@ -22,6 +22,9 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.theInstance; import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.CoderRegistry; @@ -262,6 +265,7 @@ public void testCommitWithoutUnderlying() { BagState reReadStringBag = internals.state(namespace, bagTag); assertThat(reReadStringBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(internals.isEmpty(), is(false)); } @Test @@ -288,6 +292,7 @@ public void testCommitWithUnderlying() { BagState underlyingState = underlying.state(namespace, bagTag); assertThat(underlyingState.get().read(), containsInAnyOrder("spam", "bar", "baz")); assertThat(underlyingState, is(theInstance(stringBag))); + assertThat(internals.isEmpty(), is(false)); } @Test @@ -295,7 +300,7 @@ public void testCommitWithClearedInUnderlying() { CopyOnAccessInMemoryStateInternals underlying = CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); CopyOnAccessInMemoryStateInternals secondUnderlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + spy(CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying)); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, secondUnderlying); @@ -316,6 +321,8 @@ public void testCommitWithClearedInUnderlying() { internals.commit(); BagState internalsStringBag = internals.state(namespace, bagTag); assertThat(internalsStringBag.get().read(), emptyIterable()); + verify(secondUnderlying, never()).state(namespace, bagTag); + assertThat(internals.isEmpty(), is(false)); } @Test @@ -373,6 +380,53 @@ public void testCommitWithAddedUnderlying() { assertThat(reReadUnderlyingState.get().read(), containsInAnyOrder("bar", "baz")); } + @Test + public void testCommitWithEmptyTableIsEmpty() { + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + + internals.commit(); + + assertThat(internals.isEmpty(), is(true)); + } + + @Test + public void testCommitWithOnlyClearedValuesIsEmpty() { + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = internals.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("foo"); + stringBag.clear(); + + internals.commit(); + + assertThat(internals.isEmpty(), is(true)); + } + + @Test + public void testCommitWithEmptyNewAndFullUnderlyingIsNotEmpty() { + CopyOnAccessInMemoryStateInternals underlying = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); + CopyOnAccessInMemoryStateInternals internals = + CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); + + StateNamespace namespace = new StateNamespaceForTest("foo"); + StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); + BagState stringBag = underlying.state(namespace, bagTag); + assertThat(stringBag.get().read(), emptyIterable()); + + stringBag.add("bar"); + stringBag.add("baz"); + + internals.commit(); + assertThat(internals.isEmpty(), is(false)); + } + @Test public void testGetEarliestWatermarkHoldAfterCommit() { BoundedWindow first = new BoundedWindow() { From 9005cf56fa665321e7da0eb675e7898d581432ca Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 19 Feb 2016 11:50:08 -0800 Subject: [PATCH 178/751] Add Timers and State to InProcessTransformResult Move ImmutableInProcessTransformResult to SingleStepTransformResult. This more accurately describes the item than 'Immutable', especially as the structure contains multiple mutable elements. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115085535 --- .../inprocess/InProcessTransformResult.java | 31 +++++++-- ...rmResult.java => StepTransformResult.java} | 67 +++++++++++++++---- .../BoundedReadEvaluatorFactory.java | 4 +- .../evaluator/FlattenEvaluatorFactory.java | 4 +- .../evaluator/GroupByKeyEvaluatorFactory.java | 6 +- .../evaluator/ParDoInProcessEvaluator.java | 4 +- .../UnboundedReadEvaluatorFactory.java | 4 +- .../evaluator/ViewEvaluatorFactory.java | 4 +- 8 files changed, 94 insertions(+), 30 deletions(-) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{util/ImmutableInProcessTransformResult.java => StepTransformResult.java} (62%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java index c44f77c863..c9cfb6610c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -16,9 +16,12 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; import org.joda.time.Instant; @@ -29,7 +32,7 @@ */ public interface InProcessTransformResult { /** - * @return the {@link AppliedPTransform} that produced this result + * Returns the {@link AppliedPTransform} that produced this result. */ AppliedPTransform getTransform(); @@ -40,13 +43,33 @@ public interface InProcessTransformResult { Iterable> getOutputBundles(); /** - * @return the {@link CounterSet} used by this {@link PTransform}, or null if this transform did - * not use a {@link CounterSet} + * Returns the {@link CounterSet} used by this {@link PTransform}, or null if this transform did + * not use a {@link CounterSet}. */ @Nullable CounterSet getCounters(); /** - * @return the Watermark Hold for the transform at the time this result was produced + * Returns the Watermark Hold for the transform at the time this result was produced. + * + * If the transform does not set any watermark hold, returns + * {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. */ Instant getWatermarkHold(); + + /** + * Returns the State used by the transform. + * + * If this evaluation did not access state, this may return null. + */ + CopyOnAccessInMemoryStateInternals getState(); + + /** + * Returns a TimerUpdateBuilder that was produced as a result of this evaluation. If the + * evaluation was triggered due to the delivery of one or more timers, those timers must be added + * to the builder before it is complete. + * + *

    If this evaluation did not add or remove any timers, returns an empty TimerUpdate. + */ + TimerUpdate getTimerUpdate(); + } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java similarity index 62% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java index c55887f784..54cdbf03f5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/ImmutableInProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Google Inc. + * Copyright (C) 2016 Google Inc. * * Licensed 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 @@ -13,13 +13,15 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.util; +package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; +import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import org.joda.time.Instant; @@ -29,19 +31,25 @@ /** * An immutable {@link InProcessTransformResult}. */ -public class ImmutableInProcessTransformResult implements InProcessTransformResult { +public class StepTransformResult implements InProcessTransformResult { private final AppliedPTransform transform; private final Iterable> bundles; + private final CopyOnAccessInMemoryStateInternals state; + private final TimerUpdate timerUpdate; private final CounterSet counters; private final Instant watermarkHold; - private ImmutableInProcessTransformResult( + private StepTransformResult( AppliedPTransform transform, Iterable> outputBundles, + CopyOnAccessInMemoryStateInternals state, + TimerUpdate timerUpdate, CounterSet counters, Instant watermarkHold) { this.transform = transform; this.bundles = outputBundles; + this.state = state; + this.timerUpdate = timerUpdate; this.counters = counters; this.watermarkHold = watermarkHold; } @@ -66,8 +74,17 @@ public Instant getWatermarkHold() { return watermarkHold; } - public static Builder withHold(AppliedPTransform transform, - Instant watermarkHold) { + @Override + public CopyOnAccessInMemoryStateInternals getState() { + return state; + } + + @Override + public TimerUpdate getTimerUpdate() { + return timerUpdate; + } + + public static Builder withHold(AppliedPTransform transform, Instant watermarkHold) { return new Builder(transform, watermarkHold); } @@ -75,25 +92,39 @@ public static Builder withoutHold(AppliedPTransform transform) { return new Builder(transform, BoundedWindow.TIMESTAMP_MAX_VALUE); } + @Override + public String toString() { + return MoreObjects.toStringHelper(StepTransformResult.class) + .add("transform", transform) + .toString(); + } + /** - * A builder for creating instances of {@link ImmutableInProcessTransformResult}. + * A builder for creating instances of {@link StepTransformResult}. */ public static class Builder { private final AppliedPTransform transform; private final ImmutableList.Builder> bundlesBuilder; + private CopyOnAccessInMemoryStateInternals state; + private TimerUpdate timerUpdate; private CounterSet counters; private final Instant watermarkHold; - public Builder(AppliedPTransform transform, - Instant watermarkHold) { + private Builder(AppliedPTransform transform, Instant watermarkHold) { this.transform = transform; this.watermarkHold = watermarkHold; this.bundlesBuilder = ImmutableList.builder(); + this.timerUpdate = TimerUpdate.builder(null).build(); } - public ImmutableInProcessTransformResult build() { - return new ImmutableInProcessTransformResult( - transform, bundlesBuilder.build(), counters, watermarkHold); + public StepTransformResult build() { + return new StepTransformResult( + transform, + bundlesBuilder.build(), + state, + timerUpdate, + counters, + watermarkHold); } public Builder withCounters(CounterSet counters) { @@ -101,6 +132,16 @@ public Builder withCounters(CounterSet counters) { return this; } + public Builder withState(CopyOnAccessInMemoryStateInternals state) { + this.state = state; + return this; + } + + public Builder withTimerUpdate(TimerUpdate timerUpdate) { + this.timerUpdate = timerUpdate; + return this; + } + public Builder addOutput( UncommittedBundle outputBundle, UncommittedBundle... outputBundles) { bundlesBuilder.add(outputBundle); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java index 7679fa78ac..58263cb809 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java @@ -21,9 +21,9 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; @@ -105,7 +105,7 @@ public InProcessTransformResult finishBundle() throws IOException { reader.getCurrent(), reader.getCurrentTimestamp())); contentsRemaining = reader.advance(); } - return ImmutableInProcessTransformResult + return StepTransformResult .withHold(transform, BoundedWindow.TIMESTAMP_MAX_VALUE) .addOutput(output) .build(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java index 29910b29b3..4bc1683ea1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java @@ -20,9 +20,9 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; @@ -54,7 +54,7 @@ private TransformEvaluator createInMemoryEvaluator( final UncommittedBundle outputBundle = evaluationContext.createBundle(inputBundle, application.getOutput()); final InProcessTransformResult result = - ImmutableInProcessTransformResult.withoutHold(application).addOutput(outputBundle).build(); + StepTransformResult.withoutHold(application).addOutput(outputBundle).build(); return new FlattenEvaluator<>(outputBundle, result); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java index 7598b1e495..1cc157b8d8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java @@ -25,10 +25,10 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult.Builder; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult.Builder; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; @@ -125,7 +125,7 @@ public void processElement(WindowedValue> element) { @Override public InProcessTransformResult finishBundle() { - Builder resultBuilder = ImmutableInProcessTransformResult.withoutHold(application); + Builder resultBuilder = StepTransformResult.withoutHold(application); for (Map.Entry, List> groupedEntry : groupingMap.entrySet()) { K key = groupedEntry.getKey().key; KV> groupedKv = KV.>of(key, groupedEntry.getValue()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java index 797a175f4d..fdc107ec5f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java @@ -17,7 +17,7 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.DoFnRunner; @@ -55,7 +55,7 @@ public InProcessTransformResult finishBundle() { fnRunner.finishBundle(); // TODO Use a real value Instant hold = BoundedWindow.TIMESTAMP_MAX_VALUE; - return ImmutableInProcessTransformResult.withHold(transform, hold) + return StepTransformResult.withHold(transform, hold) .addOutput(outputBundles) .withCounters(counters) .build(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java index e40941edde..4c383d3787 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java @@ -24,9 +24,9 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -109,7 +109,7 @@ public InProcessTransformResult finishBundle() throws IOException { checkpointMark.finalizeCheckpoint(); // TODO: When exercising create initial splits, make this the minimum across all existing // readers - return ImmutableInProcessTransformResult.withHold(transform, reader.getWatermark()) + return StepTransformResult.withHold(transform, reader.getWatermark()) .addOutput(output) .build(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java index d651871099..a78f7236d6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java @@ -19,9 +19,9 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; +import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.util.ImmutableInProcessTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; @@ -65,7 +65,7 @@ public void processElement(WindowedValue element) { @Override public InProcessTransformResult finishBundle() { writer.add(elements); - return ImmutableInProcessTransformResult.withoutHold(application).build(); + return StepTransformResult.withoutHold(application).build(); } }; } From f801524b864691aacedbf14567b6439fd7087dbd Mon Sep 17 00:00:00 2001 From: lcwik Date: Fri, 19 Feb 2016 13:37:06 -0800 Subject: [PATCH 179/751] Migrate TextIO.Read to be a custom source This allows for other runners to utilize the TextIO.Read transform since it no longer relies on the internal details of the Google Cloud Dataflow runner. Note that validation has moved to when the PTransform is being applied. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115094963 --- examples/pom.xml | 7 + .../examples/MinimalWordCountJava8Test.java | 45 ++- .../google/cloud/dataflow/sdk/io/TextIO.java | 286 ++++++++++++++++-- .../runners/DataflowPipelineTranslator.java | 2 - .../sdk/runners/dataflow/ReadTranslator.java | 10 + .../runners/dataflow/TextIOTranslator.java | 34 --- .../cloud/dataflow/sdk/io/TextIOTest.java | 240 +++++++++++---- .../runners/DataflowPipelineRunnerTest.java | 40 ++- .../DataflowPipelineTranslatorTest.java | 17 +- .../sdk/runners/TransformTreeTest.java | 43 ++- 10 files changed, 561 insertions(+), 163 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 8e708ced69..adea4b1298 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -498,5 +498,12 @@ junit ${junit.version} + + + org.mockito + mockito-all + 1.9.5 + test + diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java index 5286d61a07..fcae41c6bb 100644 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java +++ b/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java @@ -18,20 +18,33 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.options.GcsOptions; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.FlatMapElements; import com.google.cloud.dataflow.sdk.transforms.MapElements; +import com.google.cloud.dataflow.sdk.util.GcsUtil; +import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import java.io.IOException; import java.io.Serializable; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import java.util.Arrays; +import java.util.List; /** * To keep {@link MinimalWordCountJava8} simple, it is not factored or testable. This test @@ -44,8 +57,9 @@ public class MinimalWordCountJava8Test implements Serializable { * A basic smoke test that ensures there is no crash at pipeline construction time. */ @Test - public void testMinimalWordCountJava8() { + public void testMinimalWordCountJava8() throws Exception { Pipeline p = TestPipeline.create(); + p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); p.apply(TextIO.Read.from("gs://dataflow-samples/shakespeare/*")) .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) @@ -57,4 +71,33 @@ public void testMinimalWordCountJava8() { .withOutputType(new TypeDescriptor() {})) .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); } + + private GcsUtil buildMockGcsUtil() throws IOException { + GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); + + // Any request to open gets a new bogus channel + Mockito + .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + + // Any request for expansion returns a list containing the original GcsPath + // This is required to pass validation that occurs in TextIO during apply() + Mockito + .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) + .then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); + + return mockGcsUtil; + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index bf72f6bf19..71e755eebe 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -16,32 +16,41 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.Read.Bounded; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; import com.google.cloud.dataflow.sdk.runners.worker.TextReader; import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; +import com.google.protobuf.ByteString; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.SeekableByteChannel; import java.util.List; +import java.util.NoSuchElementException; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; @@ -203,7 +212,7 @@ public static class Bound extends PTransform> { @Nullable private final String filepattern; /** The Coder to use to decode each line. */ - @Nullable private final Coder coder; + private final Coder coder; /** An option to indicate if input validation is desired. Default is true. */ private final boolean validate; @@ -292,14 +301,48 @@ public PCollection apply(PInput input) { if (filepattern == null) { throw new IllegalStateException("need to set the filepattern of a TextIO.Read transform"); } - // Force the output's Coder to be what the read is using, and - // unchangeable later, to ensure that we read the input in the - // format specified by the Read transform. - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - IsBounded.BOUNDED) - .setCoder(coder); + + if (validate) { + try { + checkState( + !IOChannelUtils.getFactory(filepattern).match(filepattern).isEmpty(), + "Unable to find any files matching %s", + filepattern); + } catch (IOException e) { + throw new IllegalStateException( + String.format("Failed to validate %s", filepattern), e); + } + } + + // Create a source specific to the requested compression type. + final Bounded read; + switch(compressionType) { + case UNCOMPRESSED: + read = com.google.cloud.dataflow.sdk.io.Read.from( + new TextSource(filepattern, coder)); + break; + case AUTO: + read = com.google.cloud.dataflow.sdk.io.Read.from( + CompressedSource.from(new TextSource(filepattern, coder))); + break; + case BZIP2: + read = com.google.cloud.dataflow.sdk.io.Read.from( + CompressedSource.from(new TextSource(filepattern, coder)) + .withDecompression(CompressedSource.CompressionMode.BZIP2)); + break; + case GZIP: + read = com.google.cloud.dataflow.sdk.io.Read.from( + CompressedSource.from(new TextSource(filepattern, coder)) + .withDecompression(CompressedSource.CompressionMode.GZIP)); + break; + default: + throw new IllegalArgumentException("Unknown compression mode: " + compressionType); + } + + PCollection pcol = input.getPipeline().apply("Read", read); + // Honor the default output coder that would have been used by this PTransform. + pcol.setCoder(getDefaultOutputCoder()); + return pcol; } @Override @@ -318,17 +361,6 @@ public boolean needsValidation() { public TextIO.CompressionType getCompressionType() { return compressionType; } - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateReadHelper(transform, context); - } - }); - } } /** Disallow construction of utility classes. */ @@ -781,16 +813,204 @@ private static void validateOutputComponent(String partialFilePattern) { /** Disable construction of utility class. */ private TextIO() {} - private static void evaluateReadHelper( - Read.Bound transform, DirectPipelineRunner.EvaluationContext context) { - TextReader reader = - new TextReader<>(transform.filepattern, true, null, null, transform.coder, - transform.getCompressionType()); - try { - List elems = ReaderUtils.readAllFromReader(reader); - context.setPCollection(context.getOutput(transform), elems); - } catch (IOException e) { - throw new RuntimeException(e); + /** + * A {@link FileBasedSource} which can decode records delimited by new line characters. + * + *

    This source splits the data into records using {@code UTF-8} {@code \n}, {@code \r}, or + * {@code \r\n} as the delimiter. This source is not strict and supports decoding the last record + * even if it is not delimited. Finally, no records are decoded if the stream is empty. + * + *

    This source supports reading from any arbitrary byte position within the stream. If the + * starting position is not {@code 0}, then bytes are skipped until the first delimiter is found + * representing the beginning of the first record to be decoded. + */ + @VisibleForTesting + static class TextSource extends FileBasedSource { + /** The Coder to use to decode each line. */ + private final Coder coder; + + @VisibleForTesting + TextSource(String fileSpec, Coder coder) { + super(fileSpec, 1L); + this.coder = coder; + } + + private TextSource(String fileName, long start, long end, Coder coder) { + super(fileName, 1L, start, end); + this.coder = coder; + } + + @Override + protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { + return new TextSource<>(fileName, start, end, coder); + } + + @Override + protected FileBasedReader createSingleFileReader(PipelineOptions options) { + return new TextBasedReader<>(this); + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return false; + } + + @Override + public Coder getDefaultOutputCoder() { + return coder; + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader FileBasedReader} + * which can decode records delimited by new line characters. + * + * See {@link TextSource} for further details. + */ + @VisibleForTesting + static class TextBasedReader extends FileBasedReader { + private static final int READ_BUFFER_SIZE = 8192; + private final Coder coder; + private final ByteBuffer readBuffer = ByteBuffer.allocate(READ_BUFFER_SIZE); + private ByteString buffer; + private int startOfSeparatorInBuffer; + private int endOfSeparatorInBuffer; + private long startOfNextRecord; + private boolean eof; + private boolean elementIsPresent; + private T currentValue; + private ReadableByteChannel inChannel; + + private TextBasedReader(TextSource source) { + super(source); + coder = source.coder; + buffer = ByteString.EMPTY; + } + + @Override + protected long getCurrentOffset() throws NoSuchElementException { + if (!elementIsPresent) { + throw new NoSuchElementException(); + } + return startOfNextRecord; + } + + @Override + public T getCurrent() throws NoSuchElementException { + if (!elementIsPresent) { + throw new NoSuchElementException(); + } + return currentValue; + } + + @Override + protected void startReading(ReadableByteChannel channel) throws IOException { + this.inChannel = channel; + // If the first offset is greater than zero, we need to skip bytes until we see our + // first separator. + if (getCurrentSource().getStartOffset() > 0) { + checkState(channel instanceof SeekableByteChannel, + "%s only supports reading from a SeekableByteChannel when given a start offset" + + " greater than 0.", TextSource.class.getSimpleName()); + long requiredPosition = getCurrentSource().getStartOffset() - 1; + ((SeekableByteChannel) channel).position(requiredPosition); + findSeparatorBounds(); + buffer = buffer.substring(endOfSeparatorInBuffer); + startOfNextRecord = requiredPosition + endOfSeparatorInBuffer; + endOfSeparatorInBuffer = 0; + startOfSeparatorInBuffer = 0; + } + } + + /** + * Locates the start position and end position of the next delimiter. Will + * consume the channel till either EOF or the delimiter bounds are found. + * + *

    This fills the buffer and updates the positions as follows: + *

    {@code
    +       * ------------------------------------------------------
    +       * | element bytes | delimiter bytes | unconsumed bytes |
    +       * ------------------------------------------------------
    +       * 0            start of          end of              buffer
    +       *              separator         separator           size
    +       *              in buffer         in buffer
    +       * }
    + */ + private void findSeparatorBounds() throws IOException { + int bytePositionInBuffer = 0; + while (true) { + if (!tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 1)) { + startOfSeparatorInBuffer = endOfSeparatorInBuffer = bytePositionInBuffer; + break; + } + + byte currentByte = buffer.byteAt(bytePositionInBuffer); + + if (currentByte == '\n') { + startOfSeparatorInBuffer = bytePositionInBuffer; + endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; + break; + } else if (currentByte == '\r') { + startOfSeparatorInBuffer = bytePositionInBuffer; + endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; + + if (tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 2)) { + currentByte = buffer.byteAt(bytePositionInBuffer + 1); + if (currentByte == '\n') { + endOfSeparatorInBuffer += 1; + } + } + break; + } + + // Move to the next byte in buffer. + bytePositionInBuffer += 1; + } + } + + @Override + protected boolean readNextRecord() throws IOException { + startOfNextRecord += endOfSeparatorInBuffer; + findSeparatorBounds(); + + // If we have reached EOF file and consumed all of the buffer then we know + // that there are no more records. + if (eof && buffer.size() == 0) { + elementIsPresent = false; + return false; + } + + decodeCurrentElement(); + return true; + } + + /** + * Decodes the current element updating the buffer to only contain the unconsumed bytes. + * + * This invalidates the currently stored {@code startOfSeparatorInBuffer} and + * {@code endOfSeparatorInBuffer}. + */ + private void decodeCurrentElement() throws IOException { + ByteString dataToDecode = buffer.substring(0, startOfSeparatorInBuffer); + currentValue = coder.decode(dataToDecode.newInput(), Context.OUTER); + elementIsPresent = true; + buffer = buffer.substring(endOfSeparatorInBuffer); + } + + /** + * Returns false if we were unable to ensure the minimum capacity by consuming the channel. + */ + private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOException { + // While we aren't at EOF or haven't fulfilled the minimum buffer capacity, + // attempt to read more bytes. + while (buffer.size() <= minCapacity && !eof) { + eof = inChannel.read(readBuffer) == -1; + readBuffer.flip(); + buffer = buffer.concat(ByteString.copyFrom(readBuffer)); + readBuffer.clear(); + } + // Return true if we were able to honor the minimum buffer capacity request + return buffer.size() >= minCapacity; + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 1d14254c24..f7217f7610 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -1042,8 +1042,6 @@ private void translateHelper( DataflowPipelineRunner.StreamingPubsubIOWrite.class, new PubsubIOTranslator.WriteTranslator()); - registerTransformTranslator( - TextIO.Read.Bound.class, new TextIOTranslator.ReadTranslator()); registerTransformTranslator( TextIO.Write.Bound.class, new TextIOTranslator.WriteTranslator()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java index 2513d431cb..47a1926764 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java @@ -18,6 +18,7 @@ import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudSourceToDictionary; +import com.google.cloud.dataflow.sdk.io.FileBasedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Source; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; @@ -40,6 +41,15 @@ public static void translateReadHelper(Source source, PTransform transform, DataflowPipelineTranslator.TranslationContext context) { try { + // TODO: Move this validation out of translation once IOChannelUtils is portable + // and can be reconstructed on the worker. + if (source instanceof FileBasedSource) { + String filePatternOrSpec = ((FileBasedSource) source).getFileOrPatternSpec(); + context.getPipelineOptions() + .getPathValidator() + .validateInputFilePatternSupported(filePatternOrSpec); + } + context.addStep(transform, "ParallelRead"); context.addInput(PropertyNames.FORMAT, PropertyNames.CUSTOM_SOURCE_FORMAT); context.addInput( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java index abdf07fa58..d6c96c31bd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java @@ -29,40 +29,6 @@ * TextIO transform support code for the Dataflow backend. */ public class TextIOTranslator { - - /** - * Implements TextIO Read translation for the Dataflow backend. - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public static class ReadTranslator implements TransformTranslator { - @Override - public void translate( - TextIO.Read.Bound transform, - TranslationContext context) { - translateReadHelper(transform, context); - } - - private void translateReadHelper( - TextIO.Read.Bound transform, - TranslationContext context) { - if (context.getPipelineOptions().isStreaming()) { - throw new IllegalArgumentException("TextIO not supported in streaming mode."); - } - - PathValidator validator = context.getPipelineOptions().getPathValidator(); - String filepattern = validator.validateInputFilePatternSupported(transform.getFilepattern()); - - context.addStep(transform, "ParallelRead"); - // TODO: How do we want to specify format and - // format-specific properties? - context.addInput(PropertyNames.FORMAT, "text"); - context.addInput(PropertyNames.FILEPATTERN, filepattern); - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - context.addInput(PropertyNames.VALIDATE_SOURCE, transform.needsValidation()); - context.addInput(PropertyNames.COMPRESSION_TYPE, transform.getCompressionType().toString()); - } - } - /** * Implements TextIO Write translation for the Dataflow backend. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index abd8333bc4..6ad81e4ea0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -20,7 +20,7 @@ import static com.google.cloud.dataflow.sdk.TestUtils.LINES_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_INTS_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES_ARRAY; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; @@ -30,9 +30,12 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.TextIO.CompressionType; +import com.google.cloud.dataflow.sdk.io.TextIO.TextSource; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -43,6 +46,7 @@ import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.collect.ImmutableList; import org.junit.Rule; import org.junit.Test; @@ -51,6 +55,8 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import java.io.BufferedReader; import java.io.File; @@ -58,8 +64,11 @@ import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; -import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -74,60 +83,31 @@ public class TextIOTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); - private static class EmptySeekableByteChannel implements SeekableByteChannel { - @Override - public long position() { - return 0L; - } - - @Override - public SeekableByteChannel position(long newPosition) { - return this; - } - - @Override - public long size() { - return 0L; - } - - @Override - public SeekableByteChannel truncate(long size) { - return this; - } - - @Override - public int write(ByteBuffer src) { - return 0; - } - - @Override - public int read(ByteBuffer dst) { - return 0; - } - - @Override - public boolean isOpen() { - return true; - } - - @Override - public void close() { } - } - private GcsUtil buildMockGcsUtil() throws IOException { GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); // Any request to open gets a new bogus channel Mockito .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .thenReturn(new EmptySeekableByteChannel()); - - // Any request for expansion gets a single bogus URL - // after we first run the expansion code (which will generally - // return no results, which causes a crash we aren't testing) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + + // Any request for expansion returns a list containing the original GcsPath + // This is required to pass validation that occurs in TextIO during apply() Mockito .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .thenReturn(Arrays.asList(GcsPath.fromUri("gs://bucket/foo"))); + .then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); return mockGcsUtil; } @@ -189,25 +169,31 @@ public void testReadEmptyInts() throws Exception { } @Test - public void testReadNamed() { + public void testReadNulls() throws Exception { + runTestRead(new Void[]{ null, null, null }, VoidCoder.of()); + } + + @Test + public void testReadNamed() throws Exception { + String file = tmpFolder.newFile().getAbsolutePath(); Pipeline p = TestPipeline.create(); { PCollection output1 = - p.apply(TextIO.Read.from("/tmp/file.txt")); - assertEquals("TextIO.Read.out", output1.getName()); + p.apply(TextIO.Read.from(file)); + assertEquals("TextIO.Read/Read.out", output1.getName()); } { PCollection output2 = - p.apply(TextIO.Read.named("MyRead").from("/tmp/file.txt")); - assertEquals("MyRead.out", output2.getName()); + p.apply(TextIO.Read.named("MyRead").from(file)); + assertEquals("MyRead/Read.out", output2.getName()); } { PCollection output3 = - p.apply(TextIO.Read.from("/tmp/file.txt").named("HerRead")); - assertEquals("HerRead.out", output3.getName()); + p.apply(TextIO.Read.from(file).named("HerRead")); + assertEquals("HerRead/Read.out", output3.getName()); } } @@ -378,12 +364,11 @@ private void applyRead(Pipeline pipeline, String path) { public void testBadWildcardRecursive() throws Exception { Pipeline pipeline = TestPipeline.create(); - pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); - - // Check that running does fail. + // Check that applying does fail. expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("wildcard"); - pipeline.run(); + + pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); } @Test @@ -411,7 +396,7 @@ public void testCompressionTypeIsSet() throws Exception { @Test public void testCompressedRead() throws Exception { String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; - File tmpFile = tmpFolder.newFile("test"); + File tmpFile = tmpFolder.newFile(); String filename = tmpFile.getPath(); List expected = new ArrayList<>(); @@ -431,14 +416,12 @@ public void testCompressedRead() throws Exception { DataflowAssert.that(output).containsInAnyOrder(expected); p.run(); - - tmpFile.delete(); } @Test public void testGZIPReadWhenUncompressed() throws Exception { String[] lines = {"Meritorious condor", "Obnoxious duck"}; - File tmpFile = tmpFolder.newFile("test"); + File tmpFile = tmpFolder.newFile(); String filename = tmpFile.getPath(); List expected = new ArrayList<>(); @@ -456,8 +439,6 @@ public void testGZIPReadWhenUncompressed() throws Exception { DataflowAssert.that(output).containsInAnyOrder(expected); p.run(); - - tmpFile.delete(); } @Test @@ -471,4 +452,133 @@ public void testTextIOGetName() { assertEquals( "ReadMyFile [TextIO.Read]", TextIO.Read.named("ReadMyFile").from("somefile").toString()); } + + @Test + public void testReadEmptyLines() throws Exception { + runTestReadWithData("\n\n\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("", "", "")); + } + + @Test + public void testReadFileWithLineFeedDelimiter() throws Exception { + runTestReadWithData("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnDelimiter() throws Exception { + runTestReadWithData("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnAndLineFeedDelimiter() throws Exception { + runTestReadWithData("asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithMixedDelimiters() throws Exception { + runTestReadWithData("asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { + runTestReadWithData("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() throws Exception { + runTestReadWithData("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() + throws Exception { + runTestReadWithData("asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + @Test + public void testReadFileWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { + runTestReadWithData("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), + ImmutableList.of("asdf", "hjkl", "xyz")); + } + + private void runTestReadWithData(byte[] data, List expectedResults) throws Exception { + TextSource source = prepareSource(data); + List actual = SourceTestUtils.readFromSource(source, PipelineOptionsFactory.create()); + assertThat(actual, containsInAnyOrder(new ArrayList<>(expectedResults).toArray(new String[0]))); + } + + @Test + public void testSplittingSourceWithEmptyLines() throws Exception { + TextSource source = prepareSource("\n\n\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithLineFeedDelimiter() throws Exception { + TextSource source = prepareSource("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnDelimiter() throws Exception { + TextSource source = prepareSource("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiter() throws Exception { + TextSource source = prepareSource( + "asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithMixedDelimiters() throws Exception { + TextSource source = prepareSource( + "asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { + TextSource source = prepareSource("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() + throws Exception { + TextSource source = prepareSource("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() + throws Exception { + TextSource source = prepareSource( + "asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + @Test + public void testSplittingSourceWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { + TextSource source = prepareSource("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } + + private TextSource prepareSource(byte[] data) throws IOException { + File file = tmpFolder.newFile(); + Files.write(file.toPath(), data); + + TextSource source = new TextSource<>(file.toPath().toString(), StringUtf8Coder.of()); + + return source; + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 6d9f90f39e..c7175cb3b0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -19,6 +19,7 @@ import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertEquals; @@ -95,18 +96,22 @@ import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; +import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.ArrayList; @@ -175,12 +180,23 @@ private static Dataflow buildMockDataflow( private GcsUtil buildMockGcsUtil(boolean bucketExists) throws IOException { GcsUtil mockGcsUtil = mock(GcsUtil.class); - when(mockGcsUtil.create( - any(GcsPath.class), anyString())) - .thenReturn(FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE)); + when(mockGcsUtil.create(any(GcsPath.class), anyString())) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + when(mockGcsUtil.isGcsPatternSupported(anyString())).thenReturn(true); + when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(bucketExists); return mockGcsUtil; } @@ -425,10 +441,12 @@ public void testNonGcsFilePathInReadFailure() throws IOException { ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); - p.apply(TextIO.Read.named("ReadMyNonGcsFile").from("/tmp/file")); + p.apply(TextIO.Read.named("ReadMyNonGcsFile").from(tmpFolder.newFile().getPath())); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); + thrown.expectCause(Matchers.allOf( + instanceOf(IllegalArgumentException.class), + ThrowableMessageMatcher.hasMessage( + containsString("expected a valid 'gs://' path but was given")))); p.run(); assertValidJob(jobCaptor.getValue()); } @@ -455,8 +473,9 @@ public void testMultiSlashGcsFileReadPath() throws IOException { p.apply(TextIO.Read.named("ReadInvalidGcsFile") .from("gs://bucket/tmp//file")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("consecutive slashes"); + thrown.expectCause(Matchers.allOf( + instanceOf(IllegalArgumentException.class), + ThrowableMessageMatcher.hasMessage(containsString("consecutive slashes")))); p.run(); assertValidJob(jobCaptor.getValue()); } @@ -1126,6 +1145,7 @@ public void testToIsmRecordForMapLikeDoFnWithoutUniqueKeysThrowsException() thro try { doFnTester.processBatch(inputElements); + fail("Expected UserCodeException"); } catch (UserCodeException e) { assertTrue(e.getCause() instanceof IllegalStateException); IllegalStateException rootCause = (IllegalStateException) e.getCause(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 98efc001a9..b9c94ad00b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -19,6 +19,8 @@ import static com.google.cloud.dataflow.sdk.util.Structs.addObject; import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; import static com.google.cloud.dataflow.sdk.util.Structs.getString; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -66,13 +68,17 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; +import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentMatcher; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import java.io.IOException; import java.util.Collections; @@ -138,6 +144,12 @@ private static Dataflow buildMockDataflow( private static DataflowPipelineOptions buildPipelineOptions() throws IOException { GcsUtil mockGcsUtil = mock(GcsUtil.class); + when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(true); when(mockGcsUtil.isGcsPatternSupported(anyString())).thenCallRealMethod(); @@ -635,8 +647,9 @@ public void testBadWildcardRecursive() throws Exception { pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); // Check that translation does fail. - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unsupported wildcard usage"); + thrown.expectCause(Matchers.allOf( + instanceOf(IllegalArgumentException.class), + ThrowableMessageMatcher.hasMessage(containsString("Unsupported wildcard usage")))); t.translate(pipeline, pipeline.getRunner(), Collections.emptyList()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java index cb34e5c117..f1b7cd7fd0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java @@ -18,10 +18,15 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -34,11 +39,13 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PValue; -import org.junit.Assert; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.File; import java.util.Arrays; import java.util.EnumSet; @@ -47,6 +54,7 @@ */ @RunWith(JUnit4.class) public class TransformTreeTest { + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); enum TransformsSeen { READ, @@ -103,11 +111,14 @@ protected Coder getDefaultOutputCoder() { // visits the nodes and verifies that the hierarchy was captured. @Test public void testCompositeCapture() throws Exception { + File inputFile = tmpFolder.newFile(); + File outputFile = tmpFolder.newFile(); + Pipeline p = DirectPipeline.createForTest(); - p.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/object")) + p.apply(TextIO.Read.named("ReadMyFile").from(inputFile.getPath())) .apply(Sample.any(10)) - .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/object")); + .apply(TextIO.Write.named("WriteMyFile").to(outputFile.getPath())); final EnumSet visited = EnumSet.noneOf(TransformsSeen.class); @@ -119,19 +130,19 @@ public void testCompositeCapture() throws Exception { public void enterCompositeTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); if (transform instanceof Sample.SampleAny) { - Assert.assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); - Assert.assertNotNull(node.getEnclosingNode()); - Assert.assertTrue(node.isCompositeNode()); + assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); + assertNotNull(node.getEnclosingNode()); + assertTrue(node.isCompositeNode()); } - Assert.assertThat(transform, not(instanceOf(TextIO.Read.Bound.class))); - Assert.assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); + assertThat(transform, not(instanceOf(Read.Bounded.class))); + assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); } @Override public void leaveCompositeTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); if (transform instanceof Sample.SampleAny) { - Assert.assertTrue(left.add(TransformsSeen.SAMPLE_ANY)); + assertTrue(left.add(TransformsSeen.SAMPLE_ANY)); } } @@ -139,11 +150,11 @@ public void leaveCompositeTransform(TransformTreeNode node) { public void visitTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); // Pick is a composite, should not be visited here. - Assert.assertThat(transform, not(instanceOf(Sample.SampleAny.class))); - if (transform instanceof TextIO.Read.Bound) { - Assert.assertTrue(visited.add(TransformsSeen.READ)); + assertThat(transform, not(instanceOf(Sample.SampleAny.class))); + if (transform instanceof Read.Bounded) { + assertTrue(visited.add(TransformsSeen.READ)); } else if (transform instanceof TextIO.Write.Bound) { - Assert.assertTrue(visited.add(TransformsSeen.WRITE)); + assertTrue(visited.add(TransformsSeen.WRITE)); } } @@ -152,8 +163,8 @@ public void visitValue(PValue value, TransformTreeNode producer) { } }); - Assert.assertTrue(visited.equals(EnumSet.allOf(TransformsSeen.class))); - Assert.assertTrue(left.equals(EnumSet.of(TransformsSeen.SAMPLE_ANY))); + assertTrue(visited.equals(EnumSet.allOf(TransformsSeen.class))); + assertTrue(left.equals(EnumSet.of(TransformsSeen.SAMPLE_ANY))); } @Test(expected = IllegalStateException.class) @@ -163,7 +174,7 @@ public void testOutputChecking() throws Exception { p.apply(new InvalidCompositeTransform()); p.traverseTopologically(new RecordingPipelineVisitor()); - Assert.fail("traversal should have failed with an IllegalStateException"); + fail("traversal should have failed with an IllegalStateException"); } @Test From d9c4b1e069ec9fa2adcd54b4335852257a5e85db Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 19 Feb 2016 14:47:49 -0800 Subject: [PATCH 180/751] Remove InProcessPipelineRunner evaluator package Make primitive evaluators package-private. The evaluators are not part of the API surface for the InProcessPipelineRunner, and are thus unavailable. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115101650 --- .../{evaluator => }/BoundedReadEvaluatorFactory.java | 8 ++------ .../inprocess/{evaluator => }/EvaluatorKey.java | 2 +- .../{evaluator => }/FlattenEvaluatorFactory.java | 9 ++------- .../{evaluator => }/GroupByKeyEvaluatorFactory.java | 9 ++------- .../inprocess/{evaluator => }/InProcessCreate.java | 4 ++-- .../{evaluator => }/ParDoInProcessEvaluator.java | 4 +--- .../{evaluator => }/ParDoMultiEvaluatorFactory.java | 10 +++------- .../{evaluator => }/ParDoSingleEvaluatorFactory.java | 10 +++------- .../{evaluator => }/UnboundedReadEvaluatorFactory.java | 8 ++------ .../{evaluator => }/ViewEvaluatorFactory.java | 9 ++------- .../BoundedReadEvaluatorFactoryTest.java | 5 +---- .../{evaluator => }/FlattenEvaluatorFactoryTest.java | 4 +--- .../GroupByKeyEvaluatorFactoryTest.java | 3 +-- .../inprocess/{evaluator => }/InProcessCreateTest.java | 2 +- .../ParDoMultiEvaluatorFactoryTest.java | 3 +-- .../ParDoSingleEvaluatorFactoryTest.java | 3 +-- .../UnboundedReadEvaluatorFactoryTest.java | 5 +---- .../{evaluator => }/ViewEvaluatorFactoryTest.java | 3 +-- 18 files changed, 28 insertions(+), 73 deletions(-) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/BoundedReadEvaluatorFactory.java (90%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/EvaluatorKey.java (96%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/FlattenEvaluatorFactory.java (85%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/GroupByKeyEvaluatorFactory.java (91%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/InProcessCreate.java (97%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/ParDoInProcessEvaluator.java (92%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/ParDoMultiEvaluatorFactory.java (88%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/ParDoSingleEvaluatorFactory.java (88%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/UnboundedReadEvaluatorFactory.java (91%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/ViewEvaluatorFactory.java (82%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/BoundedReadEvaluatorFactoryTest.java (93%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/FlattenEvaluatorFactoryTest.java (95%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/GroupByKeyEvaluatorFactoryTest.java (97%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/InProcessCreateTest.java (97%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/ParDoMultiEvaluatorFactoryTest.java (97%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/ParDoSingleEvaluatorFactoryTest.java (96%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/UnboundedReadEvaluatorFactoryTest.java (94%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/{evaluator => }/ViewEvaluatorFactoryTest.java (95%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java similarity index 90% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java index 58263cb809..d11187c99e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java @@ -13,17 +13,13 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.io.Read.Bounded; import com.google.cloud.dataflow.sdk.io.Source.Reader; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; @@ -40,7 +36,7 @@ * A {@link TransformEvaluatorFactory} that produces {@link TransformEvaluator TransformEvaluators} * for the {@link Bounded Read.Bounded} primitive {@link PTransform}. */ -public class BoundedReadEvaluatorFactory implements TransformEvaluatorFactory { +final class BoundedReadEvaluatorFactory implements TransformEvaluatorFactory { /* * An evaluator for a Source is stateful, to ensure data is not read multiple times. * Evaluators are cached here to ensure that the reader is not restarted if the evaluator is diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/EvaluatorKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java similarity index 96% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/EvaluatorKey.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java index 5f7ff6a6a3..745f8f2718 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/EvaluatorKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java similarity index 85% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java index 4bc1683ea1..d8b5312161 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java @@ -13,16 +13,11 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; @@ -35,7 +30,7 @@ * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the {@link Flatten} * {@link PTransform}. */ -public class FlattenEvaluatorFactory implements TransformEvaluatorFactory { +class FlattenEvaluatorFactory implements TransformEvaluatorFactory { @SuppressWarnings({"unchecked", "rawtypes"}) @Override public TransformEvaluator forApplication( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java similarity index 91% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java index 1cc157b8d8..44d6909274 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java @@ -13,22 +13,17 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult.Builder; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; @@ -47,7 +42,7 @@ * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the {@link GroupByKey} * {@link PTransform}. */ -public class GroupByKeyEvaluatorFactory implements TransformEvaluatorFactory { +class GroupByKeyEvaluatorFactory implements TransformEvaluatorFactory { @Override @SuppressWarnings({"unchecked", "rawtypes"}) public TransformEvaluator forApplication( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java similarity index 97% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreate.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java index cdd1b01d82..0ff881f62d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreate.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -44,7 +44,7 @@ * The coder is inferred via the {@link Values#getDefaultOutputCoder(PInput)} method on the original * transform. */ -public class InProcessCreate extends PTransform> { +class InProcessCreate extends PTransform> { private final Create.Values original; private final InMemorySource source; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java similarity index 92% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index fdc107ec5f..a2b083b0af 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -13,11 +13,9 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.DoFnRunner; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java similarity index 88% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java index c6ee134581..ad68a6b204 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java @@ -13,18 +13,14 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.evaluator.ParDoInProcessEvaluator.BundleOutputManager; +import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; @@ -44,7 +40,7 @@ * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the * {@link BoundMulti} primitive {@link PTransform}. */ -public class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory { +class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory { @Override public TransformEvaluator forApplication( AppliedPTransform application, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java similarity index 88% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java index c6e3f8accc..737d0e9981 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java @@ -13,18 +13,14 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.evaluator.ParDoInProcessEvaluator.BundleOutputManager; +import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; @@ -41,7 +37,7 @@ * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the * {@link Bound ParDo.Bound} primitive {@link PTransform}. */ -public class ParDoSingleEvaluatorFactory implements TransformEvaluatorFactory { +class ParDoSingleEvaluatorFactory implements TransformEvaluatorFactory { @Override public TransformEvaluator forApplication( final AppliedPTransform application, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java similarity index 91% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index 4c383d3787..1852ceec09 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.io.Read.Unbounded; import com.google.cloud.dataflow.sdk.io.UnboundedSource; @@ -23,10 +23,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -42,7 +38,7 @@ * A {@link TransformEvaluatorFactory} that produces {@link TransformEvaluator TransformEvaluators} * for the {@link Unbounded Read.Unbounded} primitive {@link PTransform}. */ -public class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { +class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { /* * An evaluator for a Source is stateful, to ensure the CheckpointMark is properly persisted. * Evaluators are cached here to ensure that the checkpoint mark is appropriately reused diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java similarity index 82% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java index a78f7236d6..654652ca1a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java @@ -13,15 +13,10 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; @@ -36,7 +31,7 @@ * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the * {@link CreatePCollectionView} primitive {@link PTransform}. */ -public class ViewEvaluatorFactory implements TransformEvaluatorFactory { +class ViewEvaluatorFactory implements TransformEvaluatorFactory { @SuppressWarnings({"rawtypes", "unchecked"}) @Override public TransformEvaluator forApplication( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java similarity index 93% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java index 81095b0a0d..0a4c4a1000 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/BoundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; @@ -27,9 +27,6 @@ import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java similarity index 95% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java index 8fa411464e..c2b9995577 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/FlattenEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertThat; @@ -23,8 +23,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java similarity index 97% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java index 1d7031dee7..d8cb237b9f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/GroupByKeyEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreateTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java similarity index 97% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreateTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java index 2b685dce05..31deb71552 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/InProcessCreateTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.junit.Assert.fail; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java similarity index 97% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java index 939121be41..5251a768b9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoMultiEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @@ -24,7 +24,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java similarity index 96% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java index b0e30034ee..c2e148b0d1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ParDoSingleEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @@ -24,7 +24,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java similarity index 94% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java index c8500f30cb..28f2db5498 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertThat; @@ -25,9 +25,6 @@ import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessTransformResult; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluatorFactory; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java similarity index 95% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java index 34a9344d28..c29308f1d9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/evaluator/ViewEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java @@ -13,7 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ -package com.google.cloud.dataflow.sdk.runners.inprocess.evaluator; +package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.nullValue; @@ -24,7 +24,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; -import com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; From b968d0a75310f286fd881c9d7e9248884179b72f Mon Sep 17 00:00:00 2001 From: dhalperi Date: Fri, 19 Feb 2016 15:03:13 -0800 Subject: [PATCH 181/751] Proto2Coder: fix static modifier check The original bitmask check was wrong -- needed to be & not |. Fix but just by using the existing static utility method from Modifier. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115103309 --- .../java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java index a012cc36cf..7d2373841e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java @@ -140,7 +140,7 @@ public Proto2Coder withExtensionsFrom(Iterable> moreExtensionHosts) Method registerAllExtensions = extensionHost.getDeclaredMethod( "registerAllExtensions", ExtensionRegistry.class); Preconditions.checkArgument( - 0 != (registerAllExtensions.getModifiers() | Modifier.STATIC), + Modifier.isStatic(registerAllExtensions.getModifiers()), "Method registerAllExtensions() must be static for use with Proto2Coder"); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException(e); From bc857b8359e2e4f7100e5526dc748f6dc25a7603 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Fri, 19 Feb 2016 16:07:38 -0800 Subject: [PATCH 182/751] Proto2Coder: minor cleanup No functional changes, purely reformatting. Separating as prep work for upcoming changes to detect proto2 vs proto3 objects. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115109541 --- .../dataflow/sdk/coders/Proto2Coder.java | 60 +++++++++---------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java index 7d2373841e..b107f37f88 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java @@ -15,10 +15,11 @@ */ package com.google.cloud.dataflow.sdk.coders; +import static com.google.common.base.Preconditions.checkArgument; + import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.Structs; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @@ -88,23 +89,26 @@ private Proto2Coder(Class protoMessageClass, List> extensionHostClas this.extensionHostClasses = extensionHostClasses; } - private static final CoderProvider PROVIDER = new CoderProvider() { - @Override - public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { - if (type.isSubtypeOf(new TypeDescriptor() {})) { - @SuppressWarnings("unchecked") - TypeDescriptor messageType = (TypeDescriptor) type; - @SuppressWarnings("unchecked") - Coder coder = (Coder) Proto2Coder.of(messageType); - return coder; - } else { - throw new CannotProvideCoderException( - String.format("Cannot provide Proto2Coder because %s " - + "is not a subclass of protocol buffer Messsage", - type)); - } - } - }; + private static final CoderProvider PROVIDER = + new CoderProvider() { + @Override + public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { + if (type.isSubtypeOf(new TypeDescriptor() {})) { + @SuppressWarnings("unchecked") + TypeDescriptor messageType = + (TypeDescriptor) type; + @SuppressWarnings("unchecked") + Coder coder = (Coder) Proto2Coder.of(messageType); + return coder; + } else { + throw new CannotProvideCoderException( + String.format( + "Cannot provide Proto2Coder because %s " + + "is not a subclass of protocol buffer Messsage", + type)); + } + } + }; public static CoderProvider coderProvider() { return PROVIDER; @@ -137,9 +141,9 @@ public Proto2Coder withExtensionsFrom(Iterable> moreExtensionHosts) for (Class extensionHost : moreExtensionHosts) { // Attempt to access the required method, to make sure it's present. try { - Method registerAllExtensions = extensionHost.getDeclaredMethod( - "registerAllExtensions", ExtensionRegistry.class); - Preconditions.checkArgument( + Method registerAllExtensions = + extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class); + checkArgument( Modifier.isStatic(registerAllExtensions.getModifiers()), "Method registerAllExtensions() must be static for use with Proto2Coder"); } catch (NoSuchMethodException | SecurityException e) { @@ -188,8 +192,7 @@ public Proto2Coder addExtensionsFrom(Iterable> extensionHosts) { for (Class extensionHost : extensionHosts) { try { // Attempt to access the declared method, to make sure it's present. - extensionHost - .getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class); + extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(e); } @@ -277,14 +280,11 @@ private Parser getParser() { if (memoizedParser == null) { try { @SuppressWarnings("unchecked") - T protoMessageInstance = (T) protoMessageClass - .getMethod("getDefaultInstance").invoke(null); + T protoMessageInstance = (T) protoMessageClass.getMethod("getDefaultInstance").invoke(null); @SuppressWarnings("unchecked") Parser tParser = (Parser) protoMessageInstance.getParserForType(); memoizedParser = tParser; - } catch (IllegalAccessException - | InvocationTargetException - | NoSuchMethodException e) { + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalArgumentException(e); } } @@ -301,9 +301,7 @@ private ExtensionRegistry getExtensionRegistry() { extensionHost .getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class) .invoke(null, memoizedExtensionRegistry); - } catch (IllegalAccessException - | InvocationTargetException - | NoSuchMethodException e) { + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalStateException(e); } } From 84618188d4d5b26f9937236d58ed1daba99b61aa Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 19 Feb 2016 16:09:25 -0800 Subject: [PATCH 183/751] Add InProcessTimerInternals This implementation of TimerInternals uses a clock to track the current processing time, a TimerUpdateBuilder to track updated timers, and a WatermarkManager.TransformWatermarks to track synchronzied processing time and input and output event time watermarks. Update MockClock to provide an advance method. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115109711 --- .../util/InProcessTimerInternals.java | 84 +++++++++++ .../util/InProcessTimerInternalsTest.java | 131 ++++++++++++++++++ .../sdk/runners/inprocess/util/MockClock.java | 10 ++ 3 files changed, 225 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternals.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternalsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternals.java new file mode 100644 index 0000000000..c4feef681e --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternals.java @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TransformWatermarks; +import com.google.cloud.dataflow.sdk.util.TimerInternals; + +import org.joda.time.Instant; + +import javax.annotation.Nullable; + +/** + * An implementation of {@link TimerInternals} where all relevant data exists in memory. + */ +public class InProcessTimerInternals implements TimerInternals { + private final Clock processingTimeClock; + private final TransformWatermarks watermarks; + private final TimerUpdateBuilder timerUpdateBuilder; + + public static InProcessTimerInternals create( + Clock clock, TransformWatermarks watermarks, TimerUpdateBuilder timerUpdateBuilder) { + return new InProcessTimerInternals(clock, watermarks, timerUpdateBuilder); + } + + private InProcessTimerInternals( + Clock clock, TransformWatermarks watermarks, TimerUpdateBuilder timerUpdateBuilder) { + this.processingTimeClock = clock; + this.watermarks = watermarks; + this.timerUpdateBuilder = timerUpdateBuilder; + } + + @Override + public void setTimer(TimerData timerKey) { + timerUpdateBuilder.setTimer(timerKey); + } + + @Override + public void deleteTimer(TimerData timerKey) { + timerUpdateBuilder.deletedTimer(timerKey); + } + + public TimerUpdate getTimerUpdate() { + return timerUpdateBuilder.build(); + } + + @Override + public Instant currentProcessingTime() { + return processingTimeClock.now(); + } + + @Override + @Nullable + public Instant currentSynchronizedProcessingTime() { + return watermarks.getSynchronizedProcessingInputTime(); + } + + @Override + @Nullable + public Instant currentInputWatermarkTime() { + return watermarks.getInputWatermark(); + } + + @Override + @Nullable + public Instant currentOutputWatermarkTime() { + return watermarks.getOutputWatermark(); + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternalsTest.java new file mode 100644 index 0000000000..cfe820d561 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InProcessTimerInternalsTest.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess.util; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TransformWatermarks; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** + * Tests for {@link InProcessTimerInternals}. + */ +@RunWith(JUnit4.class) +public class InProcessTimerInternalsTest { + private MockClock clock; + @Mock private TransformWatermarks watermarks; + + private TimerUpdateBuilder timerUpdateBuilder; + + private InProcessTimerInternals internals; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + clock = MockClock.fromInstant(new Instant(0)); + + timerUpdateBuilder = TimerUpdate.builder(1234); + + internals = InProcessTimerInternals.create(clock, watermarks, timerUpdateBuilder); + } + + @Test + public void setTimerAddsToBuilder() { + TimerData eventTimer = + TimerData.of(StateNamespaces.global(), new Instant(20145L), TimeDomain.EVENT_TIME); + TimerData processingTimer = + TimerData.of(StateNamespaces.global(), new Instant(125555555L), TimeDomain.PROCESSING_TIME); + TimerData synchronizedProcessingTimer = + TimerData.of( + StateNamespaces.global(), + new Instant(98745632189L), + TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + internals.setTimer(eventTimer); + internals.setTimer(processingTimer); + internals.setTimer(synchronizedProcessingTimer); + + assertThat( + internals.getTimerUpdate().getSetTimers(), + containsInAnyOrder(eventTimer, synchronizedProcessingTimer, processingTimer)); + } + + @Test + public void deleteTimerDeletesOnBuilder() { + TimerData eventTimer = + TimerData.of(StateNamespaces.global(), new Instant(20145L), TimeDomain.EVENT_TIME); + TimerData processingTimer = + TimerData.of(StateNamespaces.global(), new Instant(125555555L), TimeDomain.PROCESSING_TIME); + TimerData synchronizedProcessingTimer = + TimerData.of( + StateNamespaces.global(), + new Instant(98745632189L), + TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + internals.deleteTimer(eventTimer); + internals.deleteTimer(processingTimer); + internals.deleteTimer(synchronizedProcessingTimer); + + assertThat( + internals.getTimerUpdate().getDeletedTimers(), + containsInAnyOrder(eventTimer, synchronizedProcessingTimer, processingTimer)); + } + + @Test + public void getProcessingTimeIsClockNow() { + assertThat(internals.currentProcessingTime(), equalTo(clock.now())); + Instant oldProcessingTime = internals.currentProcessingTime(); + + clock.advance(Duration.standardHours(12)); + + assertThat(internals.currentProcessingTime(), equalTo(clock.now())); + assertThat( + internals.currentProcessingTime(), + equalTo(oldProcessingTime.plus(Duration.standardHours(12)))); + } + + @Test + public void getSynchronizedProcessingTimeIsWatermarkSynchronizedInputTime() { + when(watermarks.getSynchronizedProcessingInputTime()).thenReturn(new Instant(12345L)); + assertThat(internals.currentSynchronizedProcessingTime(), equalTo(new Instant(12345L))); + } + + @Test + public void getInputWatermarkTimeUsesWatermarkTime() { + when(watermarks.getInputWatermark()).thenReturn(new Instant(8765L)); + assertThat(internals.currentInputWatermarkTime(), equalTo(new Instant(8765L))); + } + + @Test + public void getOutputWatermarkTimeUsesWatermarkTime() { + when(watermarks.getOutputWatermark()).thenReturn(new Instant(25525L)); + assertThat(internals.currentOutputWatermarkTime(), equalTo(new Instant(25525L))); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java index b45238474d..440ed43575 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/MockClock.java @@ -17,6 +17,7 @@ import static com.google.common.base.Preconditions.checkArgument; +import org.joda.time.Duration; import org.joda.time.Instant; /** @@ -43,8 +44,17 @@ public void set(Instant newNow) { this.now = newNow; } + public void advance(Duration duration) { + checkArgument( + duration.getMillis() > 0, + "Cannot move MockClock backwards in time by duration %s", + duration); + set(now.plus(duration)); + } + @Override public Instant now() { return now; } + } From 234d5eb4517d188111eeea0058ccce7f7ca742e9 Mon Sep 17 00:00:00 2001 From: klk Date: Fri, 19 Feb 2016 18:28:00 -0800 Subject: [PATCH 184/751] Move VerifyDynamicWorkRebalancing and dependents to worker module This is a worker-specific test with some hacks in it to make sure it only runs there. This first change simply moves the test to the right module. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115119281 --- .../testing/VerifyDynamicWorkRebalancing.java | 190 ------------------ .../sdk/transforms/GroupByKeyTest.java | 30 --- 2 files changed, 220 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/VerifyDynamicWorkRebalancing.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/VerifyDynamicWorkRebalancing.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/VerifyDynamicWorkRebalancing.java deleted file mode 100644 index a49d0b496e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/VerifyDynamicWorkRebalancing.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineJob; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Collection; - -/** - * Test framework for verifying that particular elements of a collection can be processed - * in parallel via dynamic work rebalancing, regardless of the initial work partitioning. - * The motivating use case is verifying the quality of an implementation of - * {@link com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader#splitAtFraction} - * (correctness in terms of data consistency can already be verified by methods in - * {@link com.google.cloud.dataflow.sdk.testing.SourceTestUtils}). - * - *

    This test works by blocking at a pre-selected set of sentinel values and making sure - * the work gets split up such that a thread eventually gets allocated to each of them. - */ -public class VerifyDynamicWorkRebalancing { - - private static final Logger LOG = LoggerFactory.getLogger(VerifyDynamicWorkRebalancing.class); - - private VerifyDynamicWorkRebalancing() { - // Do not instantiate. - } - - /** - * Reads a source and attempts to dynamically rebalance work to bundles each containing a single - * one of the sentinel values using the dataflow runner. It does this by waiting at each - * sentinel value and letting the service dynamically split the work into bundles until - * the sentinels are completely separated. - * - *

    Sentinels should be chosen such that the source's inherent parallelization allows them - * to be separated. For example, in a simple record-based file format, they can be chosen - * arbitrarily (e.g. every record is a sentinel), however e.g. in a block-based file format - * where parallelization can only happen down to blocks, but not down to individual records, - * sentinels must be in different blocks. However, there should be not too many sentinels, - * because the test naturally requires at least as many threads (possibly via autoscaling) - * as there are sentinels to complete successfully. - * - * @param source a source PTransform producing the PCollection to be split - * @param sentinels a collection of elements that should be separable in the source - * @param nonSentinelSleepMsec how long each non-sentinel element should take to process - */ - public static void run( - PTransform> source, - Collection sentinels, - long nonSentinelSleepMsec) { - runWithPipeline(configurePipeline(sentinels.size(), nonSentinelSleepMsec), - source, sentinels, nonSentinelSleepMsec); - } - - /** - * Like {@link #run}, but uses a pre-configured pipeline. - */ - public static void runWithPipeline( - Pipeline p, - PTransform> source, - Collection sentinels, - long nonSentinelSleepMsec) { - HangOnSentinels hangingDoFn = new HangOnSentinels(sentinels, nonSentinelSleepMsec); - p.apply(source).apply(ParDo.of(hangingDoFn)); - PipelineResult result = p.run(); - long start = System.currentTimeMillis(); - try { - int seenSentinels; - do { - seenSentinels = - Iterables.getOnlyElement( - result.getAggregatorValues(hangingDoFn.sentinelCounter).getValues(), 0); - int seenNonSentinels = - Iterables.getOnlyElement( - result.getAggregatorValues(hangingDoFn.nonSentinelCounter).getValues(), 0); - LOG.info("Seen {} sentinels, {} non-sentinels so far.", seenSentinels, seenNonSentinels); - sleep(1000); - } while (seenSentinels < sentinels.size()); - LOG.info("Took {} ms to separate all the sentinels.", System.currentTimeMillis() - start); - LOG.info("Canceling..."); - ((DataflowPipelineJob) result).cancel(); - LOG.info("Done."); - } catch (AggregatorRetrievalException exn) { - throw new RuntimeException(exn); - } catch (IOException exn) { - throw new RuntimeException(exn); - } - } - - private static Pipeline configurePipeline(int sentinelCount, long nonSentinelSleepMsec) { - if (TestPipeline.isIntegrationTest()) { - // The existing implementation updates the progress at this rate, but never while a data item - // (e.g. a sentinel value) is being processed, so if non-sentinel sleeps are smaller than - // the progress update period, that can lead to reporting progress a few items behind, - // leading to the service making stale split suggestions which will be refused by the worker, - // and the sentinel will not be separated. - // TODO: fix progress reporting and dynamic work rebalancing to work well regardless of this - // condition. - Preconditions.checkArgument( - nonSentinelSleepMsec > ReadOperation.DEFAULT_PROGRESS_UPDATE_PERIOD_MS); - // Does not work in (single-threaded) direct runner. Also, we can't use TestPipeline.create() - // directly as we need a handle on the job (to monitor and cancel it) while it's running. - PipelineOptions options = TestPipeline.getPipelineOptions(); - options - .as(DataflowPipelineDebugOptions.class) - .setNumberOfWorkerHarnessThreads(sentinelCount); - // Enable autoscaling so the system will scale up to enough workers to trigger dynamic - // work rebalancing. - options - .as(DataflowPipelineWorkerPoolOptions.class) - .setAutoscalingAlgorithm( - DataflowPipelineWorkerPoolOptions.AutoscalingAlgorithmType.THROUGHPUT_BASED); - return new TestPipeline(DataflowPipelineRunner.fromOptions(options), options); - } else { - // Support for other runners could be added here. - throw new IllegalArgumentException("Unsupported for this runner."); - } - } - - private static class HangOnSentinels extends DoFn { - - private Collection sentinels; - private final long nonSentinelSleepMsec; - - public final Aggregator sentinelCounter = - createAggregator("sentinels", new Sum.SumIntegerFn()); - public final Aggregator nonSentinelCounter = - createAggregator("nonSentinels", new Sum.SumIntegerFn()); - - public HangOnSentinels(Collection sentinels, long nonSentinelSleepMsec) { - this.sentinels = sentinels; - this.nonSentinelSleepMsec = nonSentinelSleepMsec; - } - - public void processElement(ProcessContext c) { - if (sentinels.contains(c.element())) { - sentinelCounter.addValue(1); - while (true) { - LOG.info("Waiting at sentinel {}.", c.element()); - sleep(10000); - } - } else { - nonSentinelCounter.addValue(1); - sleep(nonSentinelSleepMsec); - } - } - } - - private static void sleep(long slowdownMsec) { - try { - Thread.sleep(slowdownMsec); - } catch (InterruptedException exn) { - throw new RuntimeException(exn); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java index 11a0ad1c7d..455541ae7b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java @@ -30,13 +30,11 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.testing.VerifyDynamicWorkRebalancing; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.InvalidWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; @@ -59,7 +57,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -429,31 +426,4 @@ public void processElement(ProcessContext c) throws Exception { public void testGroupByKeyGetName() { Assert.assertEquals("GroupByKey", GroupByKey.create().getName()); } - - @Test - @Category(RunnableOnService.class) - public void testDynamicWorkRebalancing() { - if (TestPipeline.isIntegrationTest() - && !TestPipeline.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { - VerifyDynamicWorkRebalancing.run( - new PTransform>() { - public PCollection apply(PBegin begin) { - List> ungroupedPairs = new ArrayList<>(); - for (int k = 0; k < 100; k++) { - ungroupedPairs.add(KV.of(k, (Void) null)); - } - return begin - .apply(Create.of(ungroupedPairs)) - .apply(GroupByKey.create()) - .apply(Keys.create()); - } - }, - // Verified manually to trigger dynamic work rebalancing. - // Also, the current implementation starts with an initial splitting into 3 bundles by - // default, so by the pigeonhole principle at least one bundle has more than one sentinel. - Arrays.asList(5, 7, 17, 18, 19), - 120); - return; - } - } } From 015e1afede0abb3fc087d4c5d4072f7801ed5d45 Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 19 Feb 2016 20:08:10 -0800 Subject: [PATCH 185/751] Allow TransformEvaluatorFactory#forApplication to throw Certain Transforms (like sources) can throw an exception while being constructed. This allows the transforms to throw an exception while being constructed rather than on first application. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115122695 --- .../sdk/runners/inprocess/TransformEvaluatorFactory.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java index 7941c1651b..3b672e0def 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java @@ -34,8 +34,10 @@ public interface TransformEvaluatorFactory { * Any work that must be done before input elements are processed (such as calling * {@link DoFn#startBundle(DoFn.Context)}) must be done before the {@link TransformEvaluator} is * made available to the caller. + * + * @throws Exception whenever constructing the underlying evaluator throws an exception */ TransformEvaluator forApplication( AppliedPTransform application, @Nullable CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext); + InProcessEvaluationContext evaluationContext) throws Exception; } From 0e77510fc9b79bf4e78e3fcef6d447ee45ea1682 Mon Sep 17 00:00:00 2001 From: tgroh Date: Fri, 19 Feb 2016 20:16:57 -0800 Subject: [PATCH 186/751] Add TypeDescriptors to Primitive PTransforms in Tests GroupByKeyTest and ViewTest both do not provide a TypeDescriptor on the PCollection that they output, which stops automated coder inference. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115122994 --- .../sdk/transforms/GroupByKeyTest.java | 43 +++++++++++-------- .../dataflow/sdk/transforms/ViewTest.java | 21 ++++++--- 2 files changed, 40 insertions(+), 24 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java index 455541ae7b..75eb92fcb4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java @@ -46,6 +46,7 @@ import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import org.joda.time.Duration; import org.joda.time.Instant; @@ -327,19 +328,23 @@ public void testRemerge() { public void testGroupByKeyDirectUnbounded() { Pipeline p = createTestDirectRunner(); - PCollection> input = p - .apply(new PTransform>>() { - @Override - public PCollection> apply(PBegin input) { - return PCollection.createPrimitiveOutputInternal(input.getPipeline(), - WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED); - } - }); + PCollection> input = + p.apply( + new PTransform>>() { + @Override + public PCollection> apply(PBegin input) { + return PCollection.>createPrimitiveOutputInternal( + input.getPipeline(), + WindowingStrategy.globalDefault(), + PCollection.IsBounded.UNBOUNDED) + .setTypeDescriptorInternal(new TypeDescriptor>() {}); + } + }); thrown.expect(IllegalStateException.class); thrown.expectMessage( "GroupByKey cannot be applied to non-bounded PCollection in the GlobalWindow without " - + "a trigger. Use a Window.into or Window.triggering transform prior to GroupByKey."); + + "a trigger. Use a Window.into or Window.triggering transform prior to GroupByKey."); input.apply("GroupByKey", GroupByKey.create()); } @@ -348,14 +353,18 @@ public PCollection> apply(PBegin input) { public void testGroupByKeyServiceUnbounded() { Pipeline p = createTestServiceRunner(); - PCollection> input = p - .apply(new PTransform>>() { - @Override - public PCollection> apply(PBegin input) { - return PCollection.createPrimitiveOutputInternal(input.getPipeline(), - WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED); - } - }); + PCollection> input = + p.apply( + new PTransform>>() { + @Override + public PCollection> apply(PBegin input) { + return PCollection.>createPrimitiveOutputInternal( + input.getPipeline(), + WindowingStrategy.globalDefault(), + PCollection.IsBounded.UNBOUNDED) + .setTypeDescriptorInternal(new TypeDescriptor>() {}); + } + }); thrown.expect(IllegalStateException.class); thrown.expectMessage( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java index 16b4640962..145956961f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java @@ -51,6 +51,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; @@ -1365,13 +1366,19 @@ private void testViewUnbounded( thrown.expectMessage("Unable to create a side-input view from input"); thrown.expectCause( ThrowableMessageMatcher.hasMessage(Matchers.containsString("non-bounded PCollection"))); - pipeline.apply(new PTransform>>() { - @Override - public PCollection> apply(PBegin input) { - return PCollection.createPrimitiveOutputInternal(input.getPipeline(), - WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED); - } - }).apply(view); + pipeline + .apply( + new PTransform>>() { + @Override + public PCollection> apply(PBegin input) { + return PCollection.>createPrimitiveOutputInternal( + input.getPipeline(), + WindowingStrategy.globalDefault(), + PCollection.IsBounded.UNBOUNDED) + .setTypeDescriptorInternal(new TypeDescriptor>() {}); + } + }) + .apply(view); } private void testViewNonmerging( From d58b7dbbf01715a3e5aa023e35d6ef7455caf33f Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 22 Feb 2016 12:12:12 -0800 Subject: [PATCH 187/751] Remove native Dataflow text reader This can be removed since users were migrated to the custom source implementation. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115255914 --- .../google/cloud/dataflow/sdk/io/TextIO.java | 42 +- .../sdk/runners/worker/TextReader.java | 592 ------------------ .../dataflow/sdk/util/IOFactoryTest.java | 87 --- 3 files changed, 3 insertions(+), 718 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 71e755eebe..0bb2861831 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -26,7 +26,6 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.TextReader; import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; @@ -37,22 +36,15 @@ import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import com.google.common.io.ByteStreams; -import com.google.common.primitives.Ints; import com.google.protobuf.ByteString; -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; - import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SeekableByteChannel; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Pattern; -import java.util.zip.GZIPInputStream; import javax.annotation.Nullable; @@ -735,7 +727,7 @@ public void evaluate( /** * Possible text file compression types. */ - public static enum CompressionType implements TextReader.DecompressingStreamFactory { + public static enum CompressionType { /** * Automatically determine the compression type based on filename extension. */ @@ -747,34 +739,11 @@ public static enum CompressionType implements TextReader.DecompressingStreamFact /** * GZipped. */ - GZIP(".gz") { - @Override - public InputStream createInputStream(InputStream inputStream) throws IOException { - // Determine if the input stream is gzipped. The input stream returned from the - // GCS connector may already be decompressed, and no action is required. - PushbackInputStream stream = new PushbackInputStream(inputStream, 2); - byte[] headerBytes = new byte[2]; - int bytesRead = ByteStreams.read( - stream /* source */, headerBytes /* dest */, 0 /* offset */, 2 /* len */); - stream.unread(headerBytes, 0, bytesRead); - if (bytesRead >= 2) { - int header = Ints.fromBytes((byte) 0, (byte) 0, headerBytes[1], headerBytes[0]); - if (header == GZIPInputStream.GZIP_MAGIC) { - return new GZIPInputStream(stream); - } - } - return stream; - } - }, + GZIP(".gz"), /** * BZipped. */ - BZIP2(".bz2") { - @Override - public InputStream createInputStream(InputStream inputStream) throws IOException { - return new BZip2CompressorInputStream(inputStream); - } - }; + BZIP2(".bz2"); private String filenameSuffix; @@ -790,11 +759,6 @@ private CompressionType(String suffix) { public boolean matches(String filename) { return filename.toLowerCase().endsWith(filenameSuffix.toLowerCase()); } - - @Override - public InputStream createInputStream(InputStream inputStream) throws IOException { - return inputStream; - } } // Pattern which matches old-style shard output patterns, which are now diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java deleted file mode 100644 index cda7fedbf1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextReader.java +++ /dev/null @@ -1,592 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Preconditions.checkNotNull; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudPositionToReaderPosition; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudProgressToReaderProgress; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.splitRequestToApproximateSplitRequest; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; -import com.google.cloud.dataflow.sdk.util.common.worker.ProgressTracker; -import com.google.cloud.dataflow.sdk.util.common.worker.ProgressTrackerGroup; -import com.google.common.annotations.VisibleForTesting; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SeekableByteChannel; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A source that reads text files. - * - * @param the type of the elements read from the source - */ -public class TextReader extends NativeReader { - private static final Logger LOG = LoggerFactory.getLogger(TextReader.class); - - @VisibleForTesting static final int BUF_SIZE = 200; - - // The following fields are package-private to be visible in tests. - @VisibleForTesting final String filepattern; - @VisibleForTesting @Nullable final Long startPosition; - @VisibleForTesting @Nullable final Long endPosition; - @VisibleForTesting final Coder coder; - @VisibleForTesting final TextIO.CompressionType compressionType; - @VisibleForTesting final boolean stripTrailingNewlines; - @VisibleForTesting @Nullable private Collection expandedFilepattern; - - public TextReader(String filepattern, boolean stripTrailingNewlines, - @Nullable Long startPosition, @Nullable Long endPosition, Coder coder, - TextIO.CompressionType compressionType) { - this.filepattern = filepattern; - this.startPosition = startPosition; - this.endPosition = endPosition; - this.coder = coder; - this.stripTrailingNewlines = stripTrailingNewlines; - this.compressionType = compressionType; - } - - @Override - public double getTotalParallelism() { - try { - if (compressionType == TextIO.CompressionType.UNCOMPRESSED) { - // All files are splittable. - return getTotalParallelismSplittable(); - } else if (compressionType == TextIO.CompressionType.AUTO) { - for (String file : expandedFilepattern()) { - if (FilenameBasedStreamFactory.getCompressionTypeForAuto(file) - == TextIO.CompressionType.UNCOMPRESSED) { - // At least one file is splittable. - return getTotalParallelismSplittable(); - } - } - // All files were compressed. - return getTotalParallelismUnsplittable(); - } else { - // No compressed formats support dynamic work rebalancing yet. - return getTotalParallelismUnsplittable(); - } - } catch (IOException exn) { - throw new RuntimeException(exn); - } - } - - private double getTotalParallelismSplittable() { - // Assume splittable at every byte. - return (endPosition == null ? Double.POSITIVE_INFINITY : endPosition) - - (startPosition == null ? 0 : startPosition); - } - - private double getTotalParallelismUnsplittable() throws IOException { - // Total parallelism is the number of files matched by the filepattern. - return expandedFilepattern().size(); - } - - private NativeReaderIterator newReaderIteratorForRangeInFile( - IOChannelFactory factory, String oneFile, long startPosition, @Nullable Long endPosition) - throws IOException { - return newReaderIteratorForRangeWithStrictStart( - factory, oneFile, stripTrailingNewlines, startPosition, endPosition); - } - - private NativeReaderIterator newReaderIteratorForFiles( - IOChannelFactory factory, Collection files) throws IOException { - if (files.size() == 1) { - return newReaderIteratorForFile(factory, files.iterator().next(), stripTrailingNewlines); - } - - return new TextFileMultiIterator(factory, files.iterator(), stripTrailingNewlines); - } - - private TextFileIterator newReaderIteratorForFile( - IOChannelFactory factory, String input, boolean stripTrailingNewlines) throws IOException { - return newReaderIteratorForRangeWithStrictStart(factory, input, stripTrailingNewlines, 0, null); - } - - /** - * Returns a new iterator for lines in the given range in the given - * file. Does NOT skip the first line if the range starts in the - * middle of a line (instead, the latter half that starts at - * startOffset will be returned as the first element). - */ - private TextFileIterator newReaderIteratorForRangeWithStrictStart(IOChannelFactory factory, - String input, boolean stripTrailingNewlines, long startOffset, @Nullable Long endOffset) - throws IOException { - ReadableByteChannel reader = factory.open(input); - if (!(reader instanceof SeekableByteChannel)) { - throw new UnsupportedOperationException("Unable to seek in stream for " + input); - } - - SeekableByteChannel seeker = (SeekableByteChannel) reader; - - return new TextFileIterator( - new CopyableSeekableByteChannel(seeker), stripTrailingNewlines, startOffset, endOffset, - new FilenameBasedStreamFactory(input, compressionType)); - } - - private Collection expandedFilepattern() throws IOException { - if (expandedFilepattern == null) { - IOChannelFactory factory = IOChannelUtils.getFactory(filepattern); - expandedFilepattern = factory.match(filepattern); - } - return expandedFilepattern; - } - - @Override - public NativeReaderIterator iterator() throws IOException { - IOChannelFactory factory = IOChannelUtils.getFactory(filepattern); - Collection inputs = expandedFilepattern(); - if (inputs.isEmpty()) { - throw new FileNotFoundException("No match for file pattern '" + filepattern + "'"); - } - - if (startPosition != null || endPosition != null) { - if (inputs.size() != 1) { - throw new IllegalArgumentException( - "Offset range specified: [" + startPosition + ", " + endPosition + "), so " - + "an exact filename was expected, but more than 1 file matched \"" + filepattern - + "\" (total " + inputs.size() + "): apparently a filepattern was given."); - } - - return newReaderIteratorForRangeInFile(factory, inputs.iterator().next(), - startPosition == null ? 0 : startPosition, endPosition); - } else { - return newReaderIteratorForFiles(factory, inputs); - } - } - - /** - * Factory interface for creating a decompressing {@link InputStream}. - */ - public interface DecompressingStreamFactory { - /** - * Create a decompressing {@link InputStream} from an existing {@link InputStream}. - * - * @param inputStream the existing stream - * @return a stream that decompresses the contents of the existing stream - * @throws IOException - */ - public InputStream createInputStream(InputStream inputStream) throws IOException; - } - - /** - * Factory for creating decompressing input streams based on a filename and - * a {@link TextIO.CompressionType}. If the compression mode is AUTO, the filename - * is checked against known extensions to determine a compression type to use. - */ - protected static class FilenameBasedStreamFactory - implements DecompressingStreamFactory { - private String filename; - private TextIO.CompressionType compressionType; - - public FilenameBasedStreamFactory(String filename, TextIO.CompressionType compressionType) { - this.filename = filename; - this.compressionType = compressionType; - } - - protected TextIO.CompressionType getCompressionTypeForAuto() { - return getCompressionTypeForAuto(filename); - } - - protected static TextIO.CompressionType getCompressionTypeForAuto(String filepattern) { - for (TextIO.CompressionType type : TextIO.CompressionType.values()) { - if (type.matches(filepattern) && type != TextIO.CompressionType.AUTO - && type != TextIO.CompressionType.UNCOMPRESSED) { - return type; - } - } - return TextIO.CompressionType.UNCOMPRESSED; - } - - @Override - public InputStream createInputStream(InputStream inputStream) throws IOException { - if (compressionType == TextIO.CompressionType.AUTO) { - return getCompressionTypeForAuto().createInputStream(inputStream); - } - return compressionType.createInputStream(inputStream); - } - } - - private class TextFileMultiIterator extends LazyMultiReaderIterator { - private final IOChannelFactory factory; - private final boolean stripTrailingNewlines; - - public TextFileMultiIterator( - IOChannelFactory factory, Iterator inputs, boolean stripTrailingNewlines) { - super(inputs); - this.factory = factory; - this.stripTrailingNewlines = stripTrailingNewlines; - } - - @Override - protected NativeReaderIterator open(String input) throws IOException { - return newReaderIteratorForFile(factory, input, stripTrailingNewlines); - } - } - - class TextFileIterator extends NativeReaderIterator { - private final CopyableSeekableByteChannel seeker; - private final PushbackInputStream stream; - private final OffsetRangeTracker rangeTracker; - private final ProgressTracker progressTracker; - private final long startOffset; - private long offset; - private T current; - private ScanState state; - - TextFileIterator(CopyableSeekableByteChannel seeker, boolean stripTrailingNewlines, - long startOffset, @Nullable Long endOffset, - DecompressingStreamFactory compressionStreamFactory) throws IOException { - this.offset = Math.max(0, startOffset - 1); - this.seeker = checkNotNull(seeker); - this.seeker.position(offset); - InputStream inputStream = - compressionStreamFactory.createInputStream(Channels.newInputStream(seeker)); - BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); - this.stream = new PushbackInputStream(bufferedStream, BUF_SIZE); - long stopOffset = (endOffset == null) ? OffsetRangeTracker.OFFSET_INFINITY : endOffset; - this.startOffset = startOffset; - this.rangeTracker = new OffsetRangeTracker(startOffset, stopOffset); - this.progressTracker = checkNotNull(new ProgressTrackerGroup() { - @Override - protected void report(Integer lineLength) { - notifyElementRead(lineLength.longValue()); - } - }.start()); - - this.state = new ScanState(BUF_SIZE, stripTrailingNewlines); - } - - /** - * Reads a line of text. A line is considered to be terminated by any - * one of a line feed ({@code '\n'}), a carriage return - * ({@code '\r'}), or a carriage return followed immediately by a linefeed - * ({@code "\r\n"}). - * - * @return a {@code ByteArrayOutputStream} containing the contents of the - * line, with any line-termination characters stripped if - * stripTrailingNewlines==true, or {@code null} if the end of the stream has - * been reached. - * @throws IOException if an I/O error occurs - */ - @Nullable - protected ByteArrayOutputStream readElement() throws IOException { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(BUF_SIZE); - - int charsConsumed = 0; - while (true) { - // Attempt to read blocks of data at a time - // until a separator is found. - if (!state.readBytes(stream)) { - break; - } - - int consumed = state.consumeUntilSeparator(buffer); - charsConsumed += consumed; - if (consumed > 0 && state.separatorFound()) { - if (state.lastByteRead() == '\r') { - charsConsumed += state.copyCharIfLinefeed(buffer, stream); - } - break; - } - } - - if (charsConsumed == 0) { - // Note that charsConsumed includes the size of any separators that may - // have been stripped off -- so if we didn't get anything, we're at the - // end of the file. - return null; - } - - offset += charsConsumed; - return buffer; - } - - @Override - public boolean start() throws IOException { - if (this.startOffset > 0) { - long savedOffset = offset; - // Skip initial partial line. - if (readElement() == null) { - return false; - } else { - progressTracker.saw((int) (offset - savedOffset)); - } - } - return advance(); - } - - @Override - public boolean advance() throws IOException { - long startOffset = offset; - ByteArrayOutputStream element = readElement(); // As a side effect, updates "offset" - if (element != null && rangeTracker.tryReturnRecordAt(true, startOffset)) { - current = CoderUtils.decodeFromByteArray(coder, element.toByteArray()); - progressTracker.saw((int) (offset - startOffset)); - } else { - current = null; - } - return current != null; - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return current; - } - - @Override - public Progress getProgress() { - // Currently we assume that only a offset position and fraction are reported as - // current progress. An implementor can override this method to update - // other metrics, e.g. report a different completion percentage or remaining time. - com.google.api.services.dataflow.model.Position currentPosition = - new com.google.api.services.dataflow.model.Position(); - currentPosition.setByteOffset(offset); - - ApproximateReportedProgress progress = new ApproximateReportedProgress(); - progress.setPosition(currentPosition); - - // If endOffset is unspecified, we don't know the fraction consumed. - if (rangeTracker.getStopPosition() != Long.MAX_VALUE) { - progress.setFractionConsumed(rangeTracker.getFractionConsumed()); - } - - return cloudProgressToReaderProgress(progress); - } - - @Override - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) { - checkNotNull(splitRequest); - - // Currently, file-based Reader only supports split at a byte offset. - ApproximateSplitRequest splitProgress = splitRequestToApproximateSplitRequest(splitRequest); - com.google.api.services.dataflow.model.Position splitPosition = splitProgress.getPosition(); - if (splitPosition == null) { - if (splitProgress.getFractionConsumed() != null) { - float fractionConsumed = splitProgress.getFractionConsumed().floatValue(); - if (fractionConsumed <= 0 || fractionConsumed >= 1) { - LOG.warn( - "TextReader cannot be split since the provided fraction of " - + "work to be completed is out of the valid range (0, 1). Requested: {}", - splitRequest); - } - - splitPosition = new com.google.api.services.dataflow.model.Position(); - if (getEndOffset() == Long.MAX_VALUE) { - LOG.warn( - "TextReader cannot be split since the end offset is set to Long.MAX_VALUE." - + " Requested: {}", - splitRequest); - return null; - } - - splitPosition.setByteOffset( - rangeTracker.getPositionForFractionConsumed(fractionConsumed)); - } else { - LOG.warn( - "TextReader requires either a position or percentage of work to be complete to" - + " perform a dynamic split request. Requested: {}", - splitRequest); - return null; - } - } else if (splitPosition.getByteOffset() == null) { - LOG.warn( - "TextReader cannot be split since the provided split position " - + "does not contain a valid offset. Requested: {}", - splitRequest); - return null; - } - Long splitOffset = splitPosition.getByteOffset(); - - if (rangeTracker.trySplitAtPosition(splitOffset)) { - return new DynamicSplitResultWithPosition(cloudPositionToReaderPosition(splitPosition)); - } else { - return null; - } - } - - /** - * Returns the end offset of the iterator or Long.MAX_VALUE if unspecified. - * This method is called for test ONLY. - */ - long getEndOffset() { - return rangeTracker.getStopPosition(); - } - - /** - * Returns the start offset of the iterator. - * This method is called for test ONLY. - */ - long getStartOffset() { - return rangeTracker.getStartPosition(); - } - - @Override - public void close() throws IOException { - stream.close(); - } - } - - /** - * ScanState encapsulates the state for the current buffer of text - * being scanned. - */ - private static class ScanState { - private int start; // Valid bytes in buf start at this index - private int pos; // Where the separator is in the buf (if one was found) - private int end; // the index of the end of bytes in buf - private final byte[] buf; - private final boolean stripTrailingNewlines; - private byte lastByteRead; - - public ScanState(int size, boolean stripTrailingNewlines) { - this.start = 0; - this.pos = 0; - this.end = 0; - this.buf = new byte[size]; - this.stripTrailingNewlines = stripTrailingNewlines; - } - - public boolean readBytes(PushbackInputStream stream) throws IOException { - if (start < end) { - return true; - } - assert end <= buf.length : end + " > " + buf.length; - int bytesRead = stream.read(buf, end, buf.length - end); - if (bytesRead == -1) { - return false; - } - end += bytesRead; - return true; - } - - /** - * Consumes characters until a separator character is found or the - * end of buffer is reached. - * - *

    Updates the state to indicate the position of the separator - * character. If pos==len, no separator was found. - * - * @return the number of characters consumed. - */ - public int consumeUntilSeparator(ByteArrayOutputStream out) { - for (pos = start; pos < end; ++pos) { - lastByteRead = buf[pos]; - if (separatorFound()) { - int charsConsumed = (pos - start + 1); // The separator is consumed - copyToOutputBuffer(out); - start = pos + 1; // skip the separator - return charsConsumed; - } - } - // No separator found - assert pos == end; - int charsConsumed = (pos - start); - out.write(buf, start, charsConsumed); - start = 0; - end = 0; - pos = 0; - return charsConsumed; - } - - public boolean separatorFound() { - return lastByteRead == '\n' || lastByteRead == '\r'; - } - - public byte lastByteRead() { - return buf[pos]; - } - - /** - * Copies data from the input buffer to the output buffer. - * - *

    If stripTrailing==false, line-termination characters are included in the copy. - */ - private void copyToOutputBuffer(ByteArrayOutputStream out) { - int charsCopied = pos - start; - if (!stripTrailingNewlines && separatorFound()) { - charsCopied++; - } - out.write(buf, start, charsCopied); - } - - /** - * Scans the input buffer to determine if a matched carriage return - * has an accompanying linefeed and process the input buffer accordingly. - * - *

    If stripTrailingNewlines==false and a linefeed character is detected, - * it is included in the copy. - * - * @return the number of characters consumed - */ - private int copyCharIfLinefeed(ByteArrayOutputStream out, PushbackInputStream stream) - throws IOException { - int charsConsumed = 0; - // Check to make sure we don't go off the end of the buffer - if ((pos + 1) < end) { - if (buf[pos + 1] == '\n') { - charsConsumed++; - pos++; - start++; - if (!stripTrailingNewlines) { - out.write('\n'); - } - } - } else { - // We are at the end of the buffer and need one more - // byte. Get it the slow but safe way. - int b = stream.read(); - if (b == '\n') { - charsConsumed++; - if (!stripTrailingNewlines) { - out.write(b); - } - } else if (b != -1) { - // Consider replacing unread() since it may be slow if - // iterators are cloned frequently. - stream.unread(b); - } - } - return charsConsumed; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java deleted file mode 100644 index 0b8c48b3cf..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOFactoryTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.runners.worker.ReaderUtils; -import com.google.cloud.dataflow.sdk.runners.worker.TextReader; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.Collection; - -/** - * Tests for IOFactory. - */ -@RunWith(JUnit4.class) -public class IOFactoryTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Test - public void testLocalFileIO() throws Exception { - // Create some files to match against. - File foo1 = tmpFolder.newFile("foo1"); - foo1.createNewFile(); - File foo2 = tmpFolder.newFile("foo2"); - foo2.createNewFile(); - tmpFolder.newFile("barf").createNewFile(); - - FileIOChannelFactory factory = new FileIOChannelFactory(); - Collection paths = factory.match(tmpFolder.getRoot().getCanonicalPath() + "/f*"); - - Assert.assertEquals(2, paths.size()); - Assert.assertTrue(paths.contains(foo1.getCanonicalPath())); - Assert.assertTrue(paths.contains(foo2.getCanonicalPath())); - } - - @Test - public void testMultiFileRead() throws Exception { - File file1 = tmpFolder.newFile("file1"); - try (FileOutputStream output = new FileOutputStream(file1)) { - output.write("1\n2".getBytes()); - } - - File file2 = tmpFolder.newFile("file2"); - try (FileOutputStream output = new FileOutputStream(file2)) { - output.write("3\n4\n".getBytes()); - } - - File file3 = tmpFolder.newFile("file3"); - try (FileOutputStream output = new FileOutputStream(file3)) { - output.write("5".getBytes()); - } - - - TextReader reader = new TextReader<>( - tmpFolder.getRoot() + "/file*", true /* strip newlines */, null, null, StringUtf8Coder.of(), - TextIO.CompressionType.UNCOMPRESSED); - - assertThat(ReaderUtils.readAllFromReader(reader), containsInAnyOrder("1", "2", "3", "4", "5")); - } -} From 209364e6ac6890845c9a51253e6c97b31ad2191c Mon Sep 17 00:00:00 2001 From: tgroh Date: Mon, 22 Feb 2016 12:21:09 -0800 Subject: [PATCH 188/751] Encode elements in InProcessCreate There is no requirement that the elements of a Create are seralizable - however, they must be encodeable; because applying a read will ensure the elements are seralizable, we must ensure that all elements succeed; do so via encoding all of the available elements into the source, and decoding them in the reader. Implement getEstimatedSizeBytes and splitIntoBundles, now that we know the size of the elements in bytes. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115256859 --- .../runners/inprocess/InProcessCreate.java | 154 +++++++++++------- .../inprocess/InProcessCreateTest.java | 126 ++++++++++++++ 2 files changed, 223 insertions(+), 57 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java index 0ff881f62d..9023b7b2dc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java @@ -18,35 +18,39 @@ import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.Create.Values; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Optional; +import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.google.common.collect.PeekingIterator; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collections; +import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; +import javax.annotation.Nullable; + /** - * An in memory implementation of the {@link Values Create.Values} {@link PTransform}, implemented' + * An in-process implementation of the {@link Values Create.Values} {@link PTransform}, implemented * using a {@link BoundedSource}. * * The coder is inferred via the {@link Values#getDefaultOutputCoder(PInput)} method on the original * transform. */ -class InProcessCreate extends PTransform> { +class InProcessCreate extends ForwardingPTransform> { private final Create.Values original; - private final InMemorySource source; public static InProcessCreate from(Create.Values original) { return new InProcessCreate<>(original); @@ -54,38 +58,88 @@ public static InProcessCreate from(Create.Values original) { private InProcessCreate(Values original) { this.original = original; - this.source = new InMemorySource<>(original.getElements()); } @Override public PCollection apply(PInput input) { - input.getPipeline().getCoderRegistry(); - PCollection result = input.getPipeline().apply(Read.from(source)); + Coder elementCoder; try { - result.setCoder(original.getDefaultOutputCoder(input)); + elementCoder = original.getDefaultOutputCoder(input); } catch (CannotProvideCoderException e) { - throw new IllegalArgumentException("Unable to infer a coder and no Coder was specified. " - + "Please set a coder by invoking Create.withCoder() explicitly.", e); + throw new IllegalArgumentException( + "Unable to infer a coder and no Coder was specified. " + + "Please set a coder by invoking Create.withCoder() explicitly.", + e); + } + InMemorySource source; + try { + source = new InMemorySource<>(original.getElements(), elementCoder); + } catch (IOException e) { + throw Throwables.propagate(e); } + PCollection result = input.getPipeline().apply(Read.from(source)); + result.setCoder(elementCoder); return result; } - private static class InMemorySource extends BoundedSource { - private final Iterable elements; + @Override + public PTransform> delegate() { + return original; + } - public InMemorySource(Iterable elements) { - this.elements = elements; + @VisibleForTesting + static class InMemorySource extends BoundedSource { + private final Collection allElementsBytes; + private final long totalSize; + private final Coder coder; + + public InMemorySource(Iterable elements, Coder elemCoder) + throws CoderException, IOException { + allElementsBytes = new ArrayList<>(); + long totalSize = 0L; + for (T element : elements) { + byte[] bytes = CoderUtils.encodeToByteArray(elemCoder, element); + allElementsBytes.add(bytes); + totalSize += bytes.length; + } + this.totalSize = totalSize; + this.coder = elemCoder; + } + + /** + * Create a new source with the specified bytes. The new source owns the input element bytes, + * which must not be modified after this constructor is called. + */ + private InMemorySource(Collection elementBytes, long totalSize, Coder coder) { + this.allElementsBytes = ImmutableList.copyOf(elementBytes); + this.totalSize = totalSize; + this.coder = coder; } @Override public List> splitIntoBundles( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - return Collections.singletonList(this); + ImmutableList.Builder> resultBuilder = ImmutableList.builder(); + long currentSourceSize = 0L; + List currentElems = new ArrayList<>(); + for (byte[] elemBytes : allElementsBytes) { + currentElems.add(elemBytes); + currentSourceSize += elemBytes.length; + if (currentSourceSize >= desiredBundleSizeBytes) { + resultBuilder.add(new InMemorySource<>(currentElems, currentSourceSize, coder)); + currentElems.clear(); + currentSourceSize = 0L; + } + } + if (!currentElems.isEmpty()) { + resultBuilder.add(new InMemorySource<>(currentElems, currentSourceSize, coder)); + } + return resultBuilder.build(); } @Override public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return 0L; + return totalSize; } @Override @@ -95,7 +149,7 @@ public boolean producesSortedKeys(PipelineOptions options) throws Exception { @Override public BoundedSource.BoundedReader createReader(PipelineOptions options) throws IOException { - return new IterableReader(); + return new BytesReader(); } @Override @@ -103,42 +157,19 @@ public void validate() {} @Override public Coder getDefaultOutputCoder() { - // Return a coder that exclusively throws exceptions. The coder is set properly in apply, or - // an illegal argument exception is thrown. - return new StandardCoder() { - @Override - public void encode(T value, OutputStream outStream, - com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - throw new CoderException("Default Create Coder cannot be used"); - } - - @Override - public T decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - throw new CoderException("Default Create Coder cannot be used"); - } - - @Override - public List> getCoderArguments() { - return Collections.emptyList(); - } - - @Override - public void verifyDeterministic() - throws com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException { - throw new NonDeterministicException( - this, Collections.singletonList("Default Create Coder cannot be used")); - } - }; + return coder; } - private class IterableReader extends BoundedReader { - private final PeekingIterator iter; + private class BytesReader extends BoundedReader { + private final PeekingIterator iter; + /** + * Use an optional to distinguish between null next element (as Optional.absent()) and no next + * element (next is null). + */ + @Nullable private Optional next; - public IterableReader() { - this.iter = Iterators.peekingIterator(elements.iterator()); + public BytesReader() { + this.iter = Iterators.peekingIterator(allElementsBytes.iterator()); } @Override @@ -148,18 +179,27 @@ public BoundedSource getCurrentSource() { @Override public boolean start() throws IOException { - return iter.hasNext(); + return advance(); } @Override public boolean advance() throws IOException { - iter.next(); - return iter.hasNext(); + boolean hasNext = iter.hasNext(); + if (hasNext) { + next = Optional.fromNullable(CoderUtils.decodeFromByteArray(coder, iter.next())); + } else { + next = null; + } + return hasNext; } @Override + @Nullable public T getCurrent() throws NoSuchElementException { - return iter.peek(); + if (next == null) { + throw new NoSuchElementException(); + } + return next.orNull(); } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java index 31deb71552..4db014e3ee 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java @@ -15,13 +15,31 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.NullableCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessCreate.InMemorySource; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableList; import org.hamcrest.Matchers; import org.junit.Rule; @@ -30,7 +48,12 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.io.Serializable; +import java.util.Collections; +import java.util.List; /** * Tests for {@link InProcessCreate}. @@ -50,6 +73,19 @@ public void testConvertsCreate() { DataflowAssert.that(p.apply(converted)).containsInAnyOrder(2, 1, 3); } + @Test + public void testConvertsCreateWithNullElements() { + Create.Values og = + Create.of("foo", null, "spam", "ham", null, "eggs") + .withCoder(NullableCoder.of(StringUtf8Coder.of())); + + InProcessCreate converted = InProcessCreate.from(og); + TestPipeline p = TestPipeline.create(); + + DataflowAssert.that(p.apply(converted)) + .containsInAnyOrder(null, "foo", null, "spam", "ham", "eggs"); + } + static class Record implements Serializable {} static class Record2 extends Record {} @@ -70,4 +106,94 @@ public void testThrowsIllegalArgumentWhenCannotInferCoder() { fail("Unexpectedly Inferred Coder " + c.getCoder()); } + + /** + * An unserializable class to demonstrate encoding of elements. + */ + private static class UnserializableRecord { + private final String myString; + + private UnserializableRecord(String myString) { + this.myString = myString; + } + + @Override + public int hashCode() { + return myString.hashCode(); + } + + @Override + public boolean equals(Object o) { + return myString.equals(((UnserializableRecord) o).myString); + } + + static class UnserializableRecordCoder extends StandardCoder { + private final Coder stringCoder = StringUtf8Coder.of(); + + @Override + public void encode( + UnserializableRecord value, + OutputStream outStream, + com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + stringCoder.encode(value.myString, outStream, context.nested()); + } + + @Override + public UnserializableRecord decode( + InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + return new UnserializableRecord(stringCoder.decode(inStream, context.nested())); + } + + @Override + public List> getCoderArguments() { + return Collections.emptyList(); + } + + @Override + public void verifyDeterministic() throws Coder.NonDeterministicException { + stringCoder.verifyDeterministic(); + } + } + } + + @Test + public void testSerializableOnUnserializableElements() throws Exception { + List elements = + ImmutableList.of( + new UnserializableRecord("foo"), + new UnserializableRecord("bar"), + new UnserializableRecord("baz")); + InMemorySource source = + new InMemorySource<>(elements, new UnserializableRecord.UnserializableRecordCoder()); + SerializableUtils.ensureSerializable(source); + } + + @Test + public void testSplitIntoBundles() throws Exception { + InProcessCreate.InMemorySource source = + new InMemorySource<>(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), BigEndianIntegerCoder.of()); + PipelineOptions options = PipelineOptionsFactory.create(); + List> splitSources = source.splitIntoBundles(12, options); + assertThat(splitSources, hasSize(3)); + SourceTestUtils.assertSourcesEqualReferenceSource(source, splitSources, options); + } + + @Test + public void testDoesNotProduceSortedKeys() throws Exception { + InProcessCreate.InMemorySource source = + new InMemorySource<>(ImmutableList.of("spam", "ham", "eggs"), StringUtf8Coder.of()); + assertThat(source.producesSortedKeys(PipelineOptionsFactory.create()), is(false)); + } + + @Test + public void testGetDefaultOutputCoderReturnsConstructorCoder() throws Exception { + Coder coder = VarIntCoder.of(); + InProcessCreate.InMemorySource source = + new InMemorySource<>(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), coder); + + Coder defaultCoder = source.getDefaultOutputCoder(); + assertThat(defaultCoder, equalTo(coder)); + } } From c857afaf1911175a6d907f53167e39e9b639c665 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 22 Feb 2016 13:49:38 -0800 Subject: [PATCH 189/751] Expose base output file name on FileBasedSink ----Release Notes---- Add the ability to get the base output filename to FileBasedSinks. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115265994 --- .../google/cloud/dataflow/sdk/io/FileBasedSink.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index f14f4bf7a0..7c301679ca 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -120,6 +120,13 @@ public FileBasedSink(String baseOutputFilename, String extension, String fileNam this.fileNamingTemplate = fileNamingTemplate; } + /** + * Returns the base output filename for this file based sink. + */ + public String getBaseOutputFilename() { + return baseOutputFilename; + } + /** * Perform pipeline-construction-time validation. The default implementation is a no-op. * Subclasses should override to ensure the sink is valid and can be written to. It is recommended @@ -806,6 +813,7 @@ public void flush() throws IOException { } static class ReshardForWrite extends PTransform, PCollection> { + @Override public PCollection apply(PCollection input) { return input // TODO: This would need to be adapted to write per-window shards. @@ -815,10 +823,12 @@ public PCollection apply(PCollection input) { .apply("RandomKey", ParDo.of( new DoFn>() { transient long counter, step; + @Override public void startBundle(Context c) { counter = (long) (Math.random() * Long.MAX_VALUE); step = 1 + 2 * (long) (Math.random() * Long.MAX_VALUE); } + @Override public void processElement(ProcessContext c) { counter += step; c.output(KV.of(counter, c.element())); @@ -827,6 +837,7 @@ public void processElement(ProcessContext c) { .apply(GroupByKey.create()) .apply("Ungroup", ParDo.of( new DoFn>, T>() { + @Override public void processElement(ProcessContext c) { for (T item : c.element().getValue()) { c.output(item); From 7ff52a0e184f984254bd9ad4dd71a9f67193e593 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 22 Feb 2016 14:33:36 -0800 Subject: [PATCH 190/751] Move over Google Cloud Dataflow worker utilities to worker module Note that CopyableSeekableByteChannel and LazyMultiReaderIterator were deleted and not moved because they were only used by TextReader which has now been removed as well. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115271204 --- .../worker/CopyableSeekableByteChannel.java | 270 -------------- .../worker/LazyMultiReaderIterator.java | 87 ----- .../sdk/runners/worker/ReaderUtils.java | 74 ---- .../util/common/worker/ElementCounter.java | 32 -- .../sdk/util/common/worker/Operation.java | 182 ---------- .../util/common/worker/OutputReceiver.java | 74 ---- .../util/common/worker/ProgressTracker.java | 38 -- .../common/worker/ProgressTrackerGroup.java | 71 ---- .../sdk/util/common/worker/ReadOperation.java | 333 ------------------ .../sdk/util/common/worker/Receiver.java | 27 -- 10 files changed, 1188 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannel.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ElementCounter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Operation.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiver.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTracker.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackerGroup.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Receiver.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannel.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannel.java deleted file mode 100644 index 55d25b9444..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/CopyableSeekableByteChannel.java +++ /dev/null @@ -1,270 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.api.client.util.Preconditions.checkNotNull; -import static com.google.api.client.util.Preconditions.checkState; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SeekableByteChannel; - -import javax.annotation.concurrent.GuardedBy; - -/** - * A {@link SeekableByteChannel} that adds copy semantics. - * - *

    This implementation uses a lock to ensure that only one thread accesses - * the underlying {@code SeekableByteChannel} at any given time. - * - *

    {@link SeekableByteChannel#close} is called on the underlying channel once - * all {@code CopyableSeekableByteChannel} objects copied from the initial - * {@code CopyableSeekableByteChannel} are closed. - * - *

    The implementation keeps track of the position of each - * {@code CopyableSeekableByteChannel}; on access, it synchronizes with the - * other {@code CopyableSeekableByteChannel} instances accessing the underlying - * channel, seeks to its own position, performs the operation, updates its local - * position, and returns the result. - */ -final class CopyableSeekableByteChannel implements SeekableByteChannel { - /** This particular stream's position in the base stream. */ - private long pos; - - /** - * The synchronization object keeping track of the base - * {@link SeekableByteChannel}, its reference count, and its current position. - * This also doubles as the lock shared by all - * {@link CopyableSeekableByteChannel} instances derived from some original - * instance. - */ - private final Sync sync; - - /** - * Indicates whether this {@link CopyableSeekableByteChannel} is closed. - * - *

    Invariant: Unclosed channels own a reference to the base channel, - * allowing us to make {@link #close} idempotent. - * - *

    This is only modified under the sync lock. - */ - private boolean closed; - - /** - * Constructs a new {@link CopyableSeekableByteChannel}. The supplied base - * channel will be closed when this channel and all derived channels are - * closed. - */ - public CopyableSeekableByteChannel(SeekableByteChannel base) throws IOException { - this(new Sync(base), 0); - - // Update the position to match the original stream's position. - // - // This doesn't actually need to be synchronized, but it's a little more - // obviously correct to always access sync.position while holding sync's - // internal monitor. - synchronized (sync) { - sync.position = base.position(); - pos = sync.position; - } - } - - /** - * The internal constructor used when deriving a new - * {@link CopyableSeekableByteChannel}. - * - *

    N.B. This signature is deliberately incompatible with the public - * constructor. - * - *

    Ordinarily, one would implement copy using a copy constructor, and pass - * the object being copied -- but that signature would be compatible with the - * public constructor creating a new set of - * {@code CopyableSeekableByteChannel} objects for some base channel. The - * copy constructor would still be the one called, since its type is more - * specific, but that's fragile; it'd be easy to tweak the signature of the - * constructor used for copies without changing callers, which would silently - * fall back to using the public constructor. So instead, we're careful to - * give this internal constructor its own unique signature. - */ - private CopyableSeekableByteChannel(Sync sync, long pos) { - this.sync = checkNotNull(sync); - checkState(sync.base.isOpen(), - "the base SeekableByteChannel is not open"); - synchronized (sync) { - sync.refCount++; - } - this.pos = pos; - this.closed = false; - } - - /** - * Creates a new {@link CopyableSeekableByteChannel} derived from an existing - * channel, referencing the same base channel. - */ - public CopyableSeekableByteChannel copy() throws IOException { - synchronized (sync) { - if (closed) { - throw new ClosedChannelException(); - } - return new CopyableSeekableByteChannel(sync, pos); - } - } - - // SeekableByteChannel implementation - - @Override - public long position() throws IOException { - synchronized (sync) { - if (closed) { - throw new ClosedChannelException(); - } - return pos; - } - } - - @Override - public CopyableSeekableByteChannel position(long newPosition) - throws IOException { - synchronized (sync) { - if (closed) { - throw new ClosedChannelException(); - } - // Verify that the position is valid for the base channel. - sync.base.position(newPosition); - this.pos = newPosition; - this.sync.position = newPosition; - } - return this; - } - - @Override - public int read(ByteBuffer dst) throws IOException { - synchronized (sync) { - if (closed) { - throw new ClosedChannelException(); - } - reposition(); - int bytesRead = sync.base.read(dst); - notePositionAdded(bytesRead); - return bytesRead; - } - } - - @Override - public long size() throws IOException { - synchronized (sync) { - if (closed) { - throw new ClosedChannelException(); - } - return sync.base.size(); - } - } - - @Override - public CopyableSeekableByteChannel truncate(long size) throws IOException { - synchronized (sync) { - if (closed) { - throw new ClosedChannelException(); - } - sync.base.truncate(size); - return this; - } - } - - @Override - public int write(ByteBuffer src) throws IOException { - synchronized (sync) { - if (closed) { - throw new ClosedChannelException(); - } - reposition(); - int bytesWritten = sync.base.write(src); - notePositionAdded(bytesWritten); - return bytesWritten; - } - } - - @Override - public boolean isOpen() { - synchronized (sync) { - if (closed) { - return false; - } - return sync.base.isOpen(); - } - } - - @Override - public void close() throws IOException { - synchronized (sync) { - if (closed) { - return; - } - closed = true; - sync.refCount--; - if (sync.refCount == 0) { - sync.base.close(); - } - } - } - - /** - * Updates the base stream's position to match the position required by this - * {@link CopyableSeekableByteChannel}. - */ - @GuardedBy("sync") - private void reposition() throws IOException { - if (pos != sync.position) { - sync.base.position(pos); - sync.position = pos; - } - } - - /** - * Notes that the specified amount has been logically added to the current - * stream's position. - */ - @GuardedBy("sync") - private void notePositionAdded(int amount) { - if (amount < 0) { - return; // Handles EOF indicators. - } - pos += amount; - sync.position += amount; - } - - /** - * A simple value type used to synchronize a set of - * {@link CopyableSeekableByteChannel} instances referencing a single - * underlying channel. - */ - private static final class Sync { - // N.B. Another way to do this would be to implement something like a - // RefcountingForwardingSeekableByteChannel. Doing so would have the - // advantage of clearly isolating the mutable state, at the cost of a lot - // more code. - public final SeekableByteChannel base; - @GuardedBy("this") public long refCount = 0; - @GuardedBy("this") public long position = 0; - - public Sync(SeekableByteChannel base) throws IOException { - this.base = checkNotNull(base); - position = base.position(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java deleted file mode 100644 index 4a35fa6f70..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/LazyMultiReaderIterator.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.io.IOException; -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * Implements a ReaderIterator over a collection of inputs. - * - *

    The sources are used sequentially, each consumed entirely before moving - * to the next source. - * - *

    The input is lazily constructed by using the abstract method {@code open} - * to create a source iterator for inputs on demand. This allows the resources - * to be produced lazily, as an open source iterator may consume process - * resources such as file descriptors. - */ -abstract class LazyMultiReaderIterator extends NativeReader.NativeReaderIterator { - private final Iterator inputs; - private NativeReader.NativeReaderIterator current; - - public LazyMultiReaderIterator(Iterator inputs) { - this.inputs = inputs; - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - boolean currentStarted = true; - while (true) { - // Try moving through the current reader - if (current != null) { - if (currentStarted ? current.advance() : current.start()) { - return true; - } - current.close(); - current = null; - } - // Current reader is done - move on to the next one. - if (!inputs.hasNext()) { - return false; - } - current = open(inputs.next()); - currentStarted = false; - } - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return current.getCurrent(); - } - - @Override - public void close() throws IOException { - if (current != null) { - current.close(); - current = null; - } - } - - protected abstract NativeReader.NativeReaderIterator open(String input) throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java deleted file mode 100644 index 3e065f40dd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/ReaderUtils.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Utilities for working with {@link NativeReader} objects. - */ -public class ReaderUtils { - /** - * Creates a {@link NativeReader.NativeReaderIterator} from the given {@link NativeReader} and - * reads it to the end. - * - * @param reader {@link NativeReader} to read from - */ - public static List readAllFromReader(NativeReader reader) throws IOException { - try (NativeReader.NativeReaderIterator iterator = reader.iterator()) { - return readRemainingFromIterator(iterator, false); - } - } - - /** - * Read elements from a {@link NativeReader.NativeReaderIterator} until either the reader is - * exhausted, or {@code n} elements are read. Specifying {@code n == Integer.MAX_VALUE} means - * read all remaining elements. - */ - public static List readNItemsFromIterator( - NativeReader.NativeReaderIterator reader, int n, boolean started) throws IOException { - List res = new ArrayList<>(); - for (long i = 0; n == Integer.MAX_VALUE || i < n; i++) { - if (!((i == 0 && !started) ? reader.start() : reader.advance())) { - break; - } - res.add(reader.getCurrent()); - } - return res; - } - - /** - * Read elements from a {@link NativeReader.NativeReaderIterator} until either the reader is - * exhausted, or n elements are read. Specifying {@code n == Integer.MAX_VALUE} means - * read all remaining elements. - */ - public static List readNItemsFromUnstartedIterator( - NativeReader.NativeReaderIterator reader, int n) throws IOException { - return readNItemsFromIterator(reader, n, false); - } - - /** - * Read elements from a {@link NativeReader.NativeReaderIterator} until the reader is exhausted. - */ - public static List readRemainingFromIterator( - NativeReader.NativeReaderIterator reader, boolean started) throws IOException { - return readNItemsFromIterator(reader, Integer.MAX_VALUE, started); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ElementCounter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ElementCounter.java deleted file mode 100644 index eb90b06ff6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ElementCounter.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -/** - * Abstract interface that counts elements processed. - */ -public interface ElementCounter { - /** - * Updates output counters. - */ - public void update(Object elem) throws Exception; - - /** - * Finishes output counters lazy updates. - */ - public void finishLazyUpdate(Object elem); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Operation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Operation.java deleted file mode 100644 index df7450cc45..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Operation.java +++ /dev/null @@ -1,182 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -/** - * The abstract base class for Operations, which correspond to - * Instructions in the original MapTask InstructionGraph. - * - *

    Call start() to start the operation. - * - *

    A read operation's start() method actually reads the data, and in - * effect runs the pipeline. - * - *

    Call finish() to finish the operation. - * - *

    Since both start() and finish() may call process() on - * this operation's consumers, start an operation after - * starting its consumers, and finish an operation before - * finishing its consumers. - */ -public abstract class Operation { - /** The name of this operation. */ - public final String operationName; - - /** - * The array of consuming receivers, one per operation output - * "port" (e.g., DoFn main or side output). A receiver might be - * null if that output isn't being consumed. - */ - public final OutputReceiver[] receivers; - - /** - * The possible initialization states of an Operation. - * For internal self-checking purposes. - */ - public enum InitializationState { - // start() hasn't yet been called. - UNSTARTED, - - // start() has been called, but finish() hasn't yet been called. - STARTED, - - // finish() has been called. - FINISHED - } - - /** - * The initialization state of this Operation. - * - *

    Written from one thread, but can be read by concurrent threads. - */ - public InitializationState initializationState = - InitializationState.UNSTARTED; - - /** - * The lock protecting the initialization state. - * - *

    Subclasses can use this lock to protect their own state. - * However, this lock should be held only for short, bounded - * amounts of time. - */ - protected final Object initializationStateLock = new Object(); - - protected final StateSampler stateSampler; - - protected final int startState; - protected final int processState; - protected final int finishState; - - public Operation(String operationName, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler, - StateSampler.StateKind stateKind) { - this.operationName = operationName; - this.receivers = receivers; - this.stateSampler = stateSampler; - startState = stateSampler.stateForName(operationName + "-start", stateKind); - processState = stateSampler.stateForName(operationName + "-process", stateKind); - finishState = stateSampler.stateForName(operationName + "-finish", stateKind); - } - - /** - * Constructs an operation in the USER state kind. - */ - public Operation(String operationName, - OutputReceiver[] receivers, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - this(operationName, receivers, counterPrefix, addCounterMutator, - stateSampler, StateSampler.StateKind.USER); - } - - /** - * Checks that this operation is not yet started, throwing an - * exception otherwise. - */ - void checkUnstarted() { - if (!(initializationState == InitializationState.UNSTARTED - || (initializationState == InitializationState.FINISHED - && supportsRestart()))) { - throw new AssertionError( - "expecting this instruction to not yet be started"); - } - } - - /** - * Checks that this operation has been started but not yet finished, - * throwing an exception otherwise. - */ - void checkStarted() { - if (initializationState != InitializationState.STARTED) { - throw new AssertionError( - "expecting this instruction to be started"); - } - } - - /** - * Checks that this operation has been finished, throwing an - * exception otherwise. - */ - void checkFinished() { - if (initializationState != InitializationState.FINISHED) { - throw new AssertionError( - "expecting this instruction to be finished"); - } - } - - /** - * Returns true if this Operation has been finished. - */ - boolean isFinished() { - return (initializationState == InitializationState.FINISHED); - } - - /** - * Starts this Operation's execution. Called after all successsor - * consuming operations have been started. - */ - public void start() throws Exception { - synchronized (initializationStateLock) { - checkUnstarted(); - initializationState = InitializationState.STARTED; - } - } - - /** - * Finishes this Operation's execution. Called after all - * predecessor producing operations have been finished. - */ - public void finish() throws Exception { - synchronized (initializationStateLock) { - checkStarted(); - initializationState = InitializationState.FINISHED; - } - } - - /** - * Returns true if this Operation can be started again after it is finished. - */ - public boolean supportsRestart() { - return false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiver.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiver.java deleted file mode 100644 index 12c77f7571..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/OutputReceiver.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import java.util.ArrayList; -import java.util.List; - -/** - * Receiver that forwards each input it receives to each of a list of - * output Receivers. Additionally, it invokes output counters who track size - * information for elements passing through. - */ -public class OutputReceiver implements Receiver { - private final List outputs = new ArrayList<>(); - private final List outputCounters = new ArrayList<>(); - - /** - * Adds a new receiver that this OutputReceiver forwards to. - */ - public void addOutput(Receiver receiver) { - outputs.add(receiver); - } - - public void addOutputCounter(ElementCounter outputCounter) { - outputCounters.add(outputCounter); - } - - - @Override - public void process(Object elem) throws Exception { - for (ElementCounter counter : outputCounters) { - counter.update(elem); - } - - // Fan-out. - for (Receiver out : outputs) { - if (out != null) { - out.process(elem); - } - } - - for (ElementCounter counter : outputCounters) { - counter.finishLazyUpdate(elem); - } - } - - /** Invoked by tests only. */ - public int getReceiverCount() { - return outputs.size(); - } - - /** Invoked by tests only. */ - public Receiver getOnlyReceiver() { - if (outputs.size() != 1) { - throw new AssertionError("only one receiver expected"); - } - - return outputs.get(0); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTracker.java deleted file mode 100644 index b88edebd62..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTracker.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -/** - * Provides an interface to an object capable of tracking progress through a - * collection of elements to be processed. - * - * @param the type of elements being tracked - */ -public interface ProgressTracker { - /** - * Copies this {@link ProgressTracker}. The copied tracker will maintain its - * own independent notion of the caller's progress through the collection of - * elements being processed. - */ - public ProgressTracker copy(); - - /** - * Reports an element to this {@link ProgressTracker}, as the element is about - * to be processed. - */ - public void saw(T element); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackerGroup.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackerGroup.java deleted file mode 100644 index 77e05c6030..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ProgressTrackerGroup.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -/** - * Implements a group of linked - * {@link ProgressTracker ProgressTrackers} that - * collectively track how far a processing loop has gotten through the elements - * it's processing. Individual {@code ProgressTracker} instances may be copied, - * capturing an independent view of the progress of the system; this turns out - * to be useful for some non-trivial processing loops. The furthest point - * reached by any {@code ProgressTracker} is the one reported. - * - *

    This class is abstract. Its single extension point is - * {@link #report}, which should be overriden to provide a function that - * handles the reporting of the supplied element, as appropriate. - * - * @param the type of elements being tracked - */ -public abstract class ProgressTrackerGroup { - // TODO: Instead of an abstract class, strongly consider adding an - // interface like Receiver to the SDK, so that this class can be final and all - // that good stuff. - private long nextIndexToReport = 0; - - public ProgressTrackerGroup() {} - - public final ProgressTracker start() { - return new Tracker(0); - } - - /** Reports the indicated element. */ - protected abstract void report(T element); - - private final class Tracker implements ProgressTracker { - private long nextElementIndex; - - private Tracker(long nextElementIndex) { - this.nextElementIndex = nextElementIndex; - } - - @Override - public ProgressTracker copy() { - return new Tracker(nextElementIndex); - } - - @Override - public void saw(T element) { - long thisElementIndex = nextElementIndex; - nextElementIndex++; - if (thisElementIndex == nextIndexToReport) { - nextIndexToReport = nextElementIndex; - report(element); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java deleted file mode 100644 index c46e2a3669..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/ReadOperation.java +++ /dev/null @@ -1,333 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Observable; -import java.util.Observer; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -/** - * A read operation. - * - *

    Its start() method iterates through all elements of the source - * and emits them on its output. - */ -public class ReadOperation extends Operation { - private static final Logger LOG = LoggerFactory.getLogger(ReadOperation.class); - - // This is the rate at which the local, threadsafe progress variable is updated from the iterator, - // not the rate of reporting. - public static final long DEFAULT_PROGRESS_UPDATE_PERIOD_MS = 100; - - /** - * For the reader parallelism counters, large enough values should be sufficient, and there - * are issues with arbitrarily large values. - * - * Specifically, When reporting parallelism as a part of a sum, we want to cap it at a value that - * won't impose an artifical constraint on the services view of available parallelism, but small - * enough that that adding and subtracting this value for every bundle will not overwhelm values - * as small as 1.0. - */ - @VisibleForTesting - public static final double LARGE_PARALLELISM_BOUND = 1e7; - - /** The Reader this operation reads from. */ - public final NativeReader reader; - - /** The total byte counter for all data read by this operation. */ - final Counter byteCount; - - /** The counter for estimating total parallelism in this task. */ - private final Counter totalParallelismCounter; - - /** The counter for estimating remaining parallelism in this task. */ - private final Counter remainingParallelismCounter; - - /** - * The Reader's iterator this operation reads from, created by start(). - * - * Guarded by {@link Operation#initializationStateLock}. - */ - volatile NativeReader.NativeReaderIterator readerIterator = null; - - /** - * A cache of {@link #readerIterator}'s progress updated inside the read loop - * at a bounded rate. - * - *

    Necessary so that ReadOperation.getProgress() can return immediately, rather than - * potentially wait for a read to complete (which can take an unbounded time, delay a worker - * progress update, and cause lease expiration and all sorts of trouble). - */ - private AtomicReference progress = new AtomicReference<>(); - - /** - * On every iteration of the read loop, "progress" is fetched from - * {@link #readerIterator} if requested. - */ - private long progressUpdatePeriodMs = DEFAULT_PROGRESS_UPDATE_PERIOD_MS; - - /** - * Signals whether the next iteration of the read loop should update the progress. - * - *

    Set to true every progressUpdatePeriodMs. - */ - private AtomicBoolean isProgressUpdateRequested = new AtomicBoolean(true); - - - public ReadOperation( - String operationName, - NativeReader reader, - OutputReceiver[] receivers, - String counterPrefix, - String systemStageName, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - super(operationName, receivers, counterPrefix, addCounterMutator, - stateSampler, reader.getStateSamplerStateKind()); - this.reader = reader; - this.byteCount = addCounterMutator.addCounter( - Counter.longs(bytesCounterName(counterPrefix, operationName), SUM)); - reader.addObserver(new ReaderObserver()); - reader.setStateSamplerAndOperationName(stateSampler, operationName); - this.totalParallelismCounter = addCounterMutator.addCounter( - Counter.doubles(totalParallelismCounterName(systemStageName), SUM)); - // Set only when a task is started or split. - totalParallelismCounter.resetToValue(boundParallelism(reader.getTotalParallelism())); - this.remainingParallelismCounter = addCounterMutator.addCounter( - Counter.doubles(remainingParallelismCounterName(systemStageName), SUM)); - } - - static ReadOperation forTest( - NativeReader reader, - OutputReceiver outputReceiver, - String counterPrefix, - CounterSet.AddCounterMutator addCounterMutator, - StateSampler stateSampler) { - return new ReadOperation("ReadOperation", reader, new OutputReceiver[]{outputReceiver}, - counterPrefix, "systemStageName", addCounterMutator, stateSampler); - } - - public static final long DONT_UPDATE_PERIODICALLY = -1; - public static final long UPDATE_ON_EACH_ITERATION = 0; - - /** - * Controls the frequency at which progress is updated. The given value must - * be positive or one of the special values of DONT_UPDATE_PERIODICALLY or - * UPDATE_ON_EACH_ITERATION. - */ - public void setProgressUpdatePeriodMs(long millis) { - assert millis > 0 || millis == DONT_UPDATE_PERIODICALLY || millis == UPDATE_ON_EACH_ITERATION; - progressUpdatePeriodMs = millis; - } - - protected String bytesCounterName(String counterPrefix, String operationName) { - return operationName + "-ByteCount"; - } - - protected String totalParallelismCounterName(String systemStageName) { - return "dataflow_total_parallelism-" + systemStageName; - } - - protected String remainingParallelismCounterName(String systemStageName) { - return "dataflow_remaining_parallelism-" + systemStageName; - } - - public NativeReader getReader() { - return reader; - } - - @Override - public void start() throws Exception { - try (StateSampler.ScopedState start = stateSampler.scopedState(startState)) { - assert start != null; - super.start(); - runReadLoop(); - } - } - - @Override - public boolean supportsRestart() { - return reader.supportsRestart(); - } - - protected void runReadLoop() throws Exception { - Receiver receiver = receivers[0]; - if (receiver == null) { - // No consumer of this data; don't do anything. - return; - } - - try (StateSampler.ScopedState process = stateSampler.scopedState(processState)) { - assert process != null; - { - // Call reader.iterator() outside the lock, because it can take an - // unbounded amount of time. - NativeReader.NativeReaderIterator iterator = reader.iterator(); - synchronized (initializationStateLock) { - readerIterator = iterator; - } - } - - // TODO: Consider using the ExecutorService from PipelineOptions instead. - Thread updateRequester = null; - if (progressUpdatePeriodMs > 0) { - updateRequester = new Thread() { - @Override - public void run() { - while (true) { - isProgressUpdateRequested.set(true); - try { - Thread.sleep(progressUpdatePeriodMs); - } catch (InterruptedException e) { - break; - } - } - } - }; - updateRequester.start(); - } - - try { - // Force a progress update at the beginning and at the end. - setProgressFromIterator(); - for (boolean more = readerIterator.start(); more; more = readerIterator.advance()) { - if (isProgressUpdateRequested.getAndSet(false) || - progressUpdatePeriodMs == UPDATE_ON_EACH_ITERATION) { - setProgressFromIterator(); - } - receiver.process(readerIterator.getCurrent()); - } - setProgressFromIterator(); - } finally { - if (updateRequester != null) { - updateRequester.interrupt(); - updateRequester.join(); - } - } - } - } - - @Override - public void finish() throws Exception { - // Mark operation finished before closing the reader, so that anybody who checks if - // it's finished (e.g. requestDynamicSplit) won't use a closed reader. - super.finish(); - readerIterator.close(); - } - - private void setProgressFromIterator() { - try { - progress.set(readerIterator.getProgress()); - remainingParallelismCounter.resetToValue( - boundParallelism(readerIterator.getRemainingParallelism())); - } catch (UnsupportedOperationException e) { - // Ignore: same semantics as null. - } catch (Exception e) { - // This is not a normal situation, but should not kill the task. - LOG.warn("Progress estimation failed", e); - } - } - - /** - * Returns a (possibly slightly stale) value of the progress of the task. - * Guaranteed to not block indefinitely. Needs to be thread-safe for sources - * which support dynamic work rebalancing. - * - * @return the task progress, or {@code null} if the source iterator has not - * been initialized - */ - public NativeReader.Progress getProgress() { - return progress.get(); - } - - /** - * Relays the split request to {@code ReaderIterator}. - */ - public NativeReader.DynamicSplitResult requestDynamicSplit( - NativeReader.DynamicSplitRequest splitRequest) { - synchronized (initializationStateLock) { - if (isFinished()) { - LOG.info("Iterator is in the Finished state, returning null stop position."); - return null; - } - if (readerIterator == null) { - LOG.info("Iterator has not been initialized, refusing to split at {}", splitRequest); - return null; - } - NativeReader.DynamicSplitResult result = readerIterator.requestDynamicSplit(splitRequest); - if (result != null) { - // After a successful split, the stop position changed and progress has to be recomputed. - setProgressFromIterator(); - totalParallelismCounter.resetToValue(boundParallelism(reader.getTotalParallelism())); - } - return result; - } - } - - /** - * This is an observer on the instance of the source. Whenever source reads - * an element, update() gets called with the byte size of the element, which - * gets added up into the ReadOperation's byte counter. - * - *

    Note that when the reader is a {@link GroupingShuffleReader}, update() - * is called for each underlying {@link ShuffleEntry} being read, with the - * byte size of the {@code ShuffleEntry} - it is not called for each grouped - * shuffle element (i.e. key and iterable of values). - */ - private class ReaderObserver implements Observer { - @Override - public void update(Observable obs, Object obj) { - Preconditions.checkArgument(obs == reader, "unexpected observable"); - Preconditions.checkArgument(obj instanceof Long, "unexpected parameter object"); - byteCount.addValue((long) obj); - } - } - - /** - * JSON doesn't correctly handle non-finite values, and we want to bound how large each - * term in the total sum is. See {@link #LARGE_PARALLELISM_BOUND}. - * - *

    TODO: Remove this hack once we move to gRPC or report this value in a more structured - * format. - */ - private static double boundParallelism(double x) { - if (Double.isNaN(x) || x < 1) { - if (x < 1) { - LOG.warn("Invalid parallelism value: " + x); - } - // Irrational; sums won't come out to an integral value. This is to better avoid - // accidental coincidences which would imply the remaining parallelism is zero when it's not. - // Also, negative so that it's recognized as "invalid." - return -LARGE_PARALLELISM_BOUND * Math.sqrt(2); - } else if (x > LARGE_PARALLELISM_BOUND) { - return LARGE_PARALLELISM_BOUND; - } else { - return x; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Receiver.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Receiver.java deleted file mode 100644 index ca13ea3185..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Receiver.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -/** - * Abstract interface of things that accept inputs one at a time via process(). - */ -public interface Receiver { - /** - * Processes the element. - */ - void process(Object outputElem) throws Exception; -} From 2e171b509ebe163ac54332eec626dccdfa18c9ad Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 22 Feb 2016 15:59:23 -0800 Subject: [PATCH 191/751] Add new test proto messages that use map fields Directly, and transitively. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115280894 --- sdk/src/main/proto/proto2_coder_test_messages.proto | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sdk/src/main/proto/proto2_coder_test_messages.proto b/sdk/src/main/proto/proto2_coder_test_messages.proto index 56efd89c36..eb3c3dfa9b 100644 --- a/sdk/src/main/proto/proto2_coder_test_messages.proto +++ b/sdk/src/main/proto/proto2_coder_test_messages.proto @@ -41,3 +41,11 @@ extend MessageC { optional MessageA field1 = 101; optional MessageB field2 = 102; } + +message MessageWithMap { + map field1 = 1; +} + +message ReferencesMessageWithMap { + repeated MessageWithMap field1 = 1; +} From c11af5fbf37accb49d73bcf206b15f7cc59636bc Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 22 Feb 2016 16:09:35 -0800 Subject: [PATCH 192/751] Migrate AvroIO.Write to a custom sink Note for user requested sharding limits to be supported, each pipeline runner must support applying those sharding limits. Google Cloud Dataflow supports sharding limits. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115282027 --- .../google/cloud/dataflow/sdk/io/AvroIO.java | 188 +++++++++--------- .../sdk/runners/DataflowPipelineRunner.java | 179 +++++++++++++++++ .../runners/DataflowPipelineTranslator.java | 5 - .../runners/dataflow/AvroIOTranslator.java | 87 -------- .../sdk/io/AvroIOGeneratedClassTest.java | 48 ++--- .../cloud/dataflow/sdk/io/AvroIOTest.java | 45 +++++ 6 files changed, 337 insertions(+), 215 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java index 9ee7e6b13c..70420105c5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java @@ -22,24 +22,25 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.AvroSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; +import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.avro.Schema; +import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.reflect.ReflectData; import java.io.IOException; -import java.util.List; +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -317,7 +318,7 @@ public PCollection apply(PInput input) { : com.google.cloud.dataflow.sdk.io.Read.from( AvroSource.from(filepattern).withSchema(type)); - PCollection pcol = input.getPipeline().apply(read); + PCollection pcol = input.getPipeline().apply("Read", read); // Honor the default output coder that would have been used by this PTransform. pcol.setCoder(getDefaultOutputCoder()); return pcol; @@ -473,8 +474,6 @@ public static class Bound extends PTransform, PDone> { final int numShards; /** Shard template string. */ final String shardTemplate; - /** Insert a shuffle before writing to decouple parallelism when numShards != 0. */ - final boolean forceReshard; /** The class type of the records. */ final Class type; /** The schema of the output file. */ @@ -484,18 +483,16 @@ public static class Bound extends PTransform, PDone> { final boolean validate; Bound(Class type) { - this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, true, type, null, true); + this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, type, null, true); } Bound(String name, String filenamePrefix, String filenameSuffix, int numShards, - String shardTemplate, boolean forceReshard, Class type, Schema schema, - boolean validate) { + String shardTemplate, Class type, Schema schema, boolean validate) { super(name); this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; this.numShards = numShards; this.shardTemplate = shardTemplate; - this.forceReshard = forceReshard; this.type = type; this.schema = schema; this.validate = validate; @@ -509,7 +506,7 @@ public static class Bound extends PTransform, PDone> { */ public Bound named(String name) { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } @@ -525,7 +522,7 @@ public Bound named(String name) { public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } @@ -540,7 +537,7 @@ public Bound to(String filenamePrefix) { public Bound withSuffix(String filenameSuffix) { validateOutputComponent(filenameSuffix); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } @@ -559,31 +556,9 @@ public Bound withSuffix(String filenameSuffix) { * @see ShardNameTemplate */ public Bound withNumShards(int numShards) { - return withNumShards(numShards, forceReshard); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that uses the provided shard count. - * - *

    Constraining the number of shards is likely to reduce - * the performance of a pipeline. If forceReshard is true, the output - * will be shuffled to obtain the desired sharding. If it is false, - * data will not be reshuffled, but parallelism of preceeding stages - * may be constrained. Setting this value is not recommended - * unless you require a specific number of output files. - * - *

    Does not modify this object. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - * @param forceReshard whether to force a reshard to obtain the desired sharding. - * @see ShardNameTemplate - */ - private Bound withNumShards(int numShards, boolean forceReshard) { Preconditions.checkArgument(numShards >= 0); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } @@ -597,7 +572,7 @@ private Bound withNumShards(int numShards, boolean forceReshard) { */ public Bound withShardNameTemplate(String shardTemplate) { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } @@ -611,22 +586,7 @@ public Bound withShardNameTemplate(String shardTemplate) { *

    Does not modify this object. */ public Bound withoutSharding() { - return withoutSharding(forceReshard); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that forces a single file as output. - * - *

    This is a shortcut for - * {@code .withNumShards(1, forceReshard).withShardNameTemplate("")} - * - *

    Does not modify this object. - * - * @param forceReshard whether to force a reshard to obtain the desired sharding. - */ - private Bound withoutSharding(boolean forceReshard) { - return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", type, schema, validate); } @@ -641,7 +601,7 @@ private Bound withoutSharding(boolean forceReshard) { */ public Bound withSchema(Class type) { return new Bound<>(name, filenamePrefix, filenameSuffix, numShards, shardTemplate, - forceReshard, type, ReflectData.get().getSchema(type), validate); + type, ReflectData.get().getSchema(type), validate); } /** @@ -653,7 +613,7 @@ public Bound withSchema(Class type) { */ public Bound withSchema(Schema schema) { return new Bound<>(name, filenamePrefix, filenameSuffix, numShards, shardTemplate, - forceReshard, GenericRecord.class, schema, validate); + GenericRecord.class, schema, validate); } /** @@ -679,7 +639,7 @@ public Bound withSchema(String schema) { */ public Bound withoutValidation() { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, false); } @@ -693,14 +653,12 @@ public PDone apply(PCollection input) { throw new IllegalStateException("need to set the schema of an AvroIO.Write transform"); } - if (numShards > 0 && forceReshard) { - // Reshard and re-apply a version of this write without resharding. - return input - .apply(new FileBasedSink.ReshardForWrite()) - .apply(withNumShards(numShards, false)); - } else { - return PDone.in(input.getPipeline()); - } + // Note that custom sinks currently do not expose sharding controls. + // Thus pipeline runner writers need to individually add support internally to + // apply user requested sharding limits. + return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( + new AvroSink<>( + filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema)))); } /** @@ -742,21 +700,6 @@ public Schema getSchema() { public boolean needsValidation() { return validate; } - - static { - @SuppressWarnings("rawtypes") - DirectPipelineRunner.TransformEvaluator transformEvaluator = - new DirectPipelineRunner.TransformEvaluator() { - @Override - @SuppressWarnings("unchecked") - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateWriteHelper(transform, context); - } - }; - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, transformEvaluator); - } } /** Disallow construction of utility class. */ @@ -779,25 +722,72 @@ private static void validateOutputComponent(String partialFilePattern) { /** Disallow construction of utility class. */ private AvroIO() {} - private static void evaluateWriteHelper( - Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { - List> elems = - context.getPCollectionWindowedValues(context.getInput(transform)); - int numShards = transform.numShards; - if (numShards < 1) { - // System gets to choose. For direct mode, choose 1. - numShards = 1; + /** + * A {@link FileBasedSink} for Avro files. + */ + @VisibleForTesting + static class AvroSink extends FileBasedSink { + private final AvroCoder coder; + + @VisibleForTesting + AvroSink( + String baseOutputFilename, String extension, String fileNameTemplate, AvroCoder coder) { + super(baseOutputFilename, extension, fileNameTemplate); + this.coder = coder; + } + + @Override + public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { + return new AvroWriteOperation<>(this, coder); + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation + * FileBasedWriteOperation} for Avro files. + */ + private static class AvroWriteOperation extends FileBasedWriteOperation { + private final AvroCoder coder; + + private AvroWriteOperation(AvroSink sink, AvroCoder coder) { + super(sink); + this.coder = coder; + } + + @Override + public FileBasedWriter createWriter(PipelineOptions options) throws Exception { + return new AvroWriter<>(this, coder); + } } - AvroSink writer = new AvroSink<>(transform.filenamePrefix, transform.shardTemplate, - transform.filenameSuffix, numShards, - WindowedValue.getValueOnlyCoder(AvroCoder.of(transform.type, transform.schema))); - try (Sink.SinkWriter> sink = writer.writer()) { - for (WindowedValue elem : elems) { - sink.add(elem); - } - } catch (IOException exn) { - throw new RuntimeException( - "unable to write to output file \"" + transform.filenamePrefix + "\"", exn); + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} + * for Avro files. + */ + private static class AvroWriter extends FileBasedWriter { + private final AvroCoder coder; + private DataFileWriter dataFileWriter; + + public AvroWriter(FileBasedWriteOperation writeOperation, AvroCoder coder) { + super(writeOperation); + this.mimeType = MimeTypes.BINARY; + this.coder = coder; + } + + @Override + protected void prepareWrite(WritableByteChannel channel) throws Exception { + dataFileWriter = new DataFileWriter<>(coder.createDatumWriter()); + dataFileWriter.create(coder.getSchema(), Channels.newOutputStream(channel)); + } + + @Override + public void write(T value) throws Exception { + dataFileWriter.append(value); + } + + @Override + protected void writeFooter() throws Exception { + dataFileWriter.close(); + } } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f20caa3b96..5a57f7fc43 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -32,6 +32,7 @@ import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; import com.google.cloud.dataflow.sdk.PipelineResult.State; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -48,8 +49,10 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; +import com.google.cloud.dataflow.sdk.io.FileBasedSink; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.io.Write; @@ -60,6 +63,8 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.JobSpecification; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; @@ -83,6 +88,7 @@ import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; @@ -331,6 +337,8 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); builder.put(Read.Unbounded.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); + builder.put(Write.Bound.class, BatchWrite.class); + builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); if (options.getExperiments() == null || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); @@ -1918,6 +1926,177 @@ public Iterable apply(Iterable> input) { } } + /** + * A {@link PTransform} that uses shuffle to create a fusion break. This allows pushing + * parallelism limits such as sharding controls further down the pipeline. + */ + private static class ReshardForWrite extends PTransform, PCollection> { + @Override + public PCollection apply(PCollection input) { + return input + // TODO: This would need to be adapted to write per-window shards. + .apply(Window.into(new GlobalWindows()) + .triggering(DefaultTrigger.of()) + .discardingFiredPanes()) + .apply("RandomKey", ParDo.of( + new DoFn>() { + transient long counter, step; + @Override + public void startBundle(Context c) { + counter = (long) (Math.random() * Long.MAX_VALUE); + step = 1 + 2 * (long) (Math.random() * Long.MAX_VALUE); + } + @Override + public void processElement(ProcessContext c) { + counter += step; + c.output(KV.of(counter, c.element())); + } + })) + .apply(GroupByKey.create()) + .apply("Ungroup", ParDo.of( + new DoFn>, T>() { + @Override + public void processElement(ProcessContext c) { + for (T item : c.element().getValue()) { + c.output(item); + } + } + })); + } + } + + /** + * Specialized implementation which overrides + * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} to provide Google + * Cloud Dataflow specific path validation of {@link FileBasedSink}s. + */ + private static class BatchWrite extends PTransform, PDone> { + private final DataflowPipelineRunner runner; + private final Write.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchWrite(DataflowPipelineRunner runner, Write.Bound transform) { + this.runner = runner; + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + if (transform.getSink() instanceof FileBasedSink) { + FileBasedSink sink = (FileBasedSink) transform.getSink(); + PathValidator validator = runner.options.getPathValidator(); + validator.validateOutputFilePrefixSupported(sink.getBaseOutputFilename()); + } + return transform.apply(input); + } + } + + /** + * Specialized implementation which overrides + * {@link com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound AvroIO.Write.Bound} with + * a native sink instead of a custom sink as workaround until custom sinks + * have support for sharding controls. + */ + private static class BatchAvroIOWrite extends PTransform, PDone> { + private final AvroIO.Write.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchAvroIOWrite(DataflowPipelineRunner runner, AvroIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + if (transform.getNumShards() > 0) { + return input + .apply(new ReshardForWrite()) + .apply(new BatchAvroIONativeWrite<>(transform)); + } else { + return transform.apply(input); + } + } + } + + /** + * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way + * to provide the native definition of the Avro sink. + */ + private static class BatchAvroIONativeWrite extends PTransform, PDone> { + private final AvroIO.Write.Bound transform; + public BatchAvroIONativeWrite(AvroIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + return PDone.in(input.getPipeline()); + } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + BatchAvroIONativeWrite.class, new BatchAvroIONativeWriteTranslator()); + } + } + + /** + * AvroIO.Write.Bound support code for the Dataflow backend when applying parallelism limits + * through user requested sharding limits. + */ + private static class BatchAvroIONativeWriteTranslator + implements TransformTranslator> { + @SuppressWarnings("unchecked") + @Override + public void translate(@SuppressWarnings("rawtypes") BatchAvroIONativeWrite transform, + TranslationContext context) { + translateWriteHelper(transform, transform.transform, context); + } + + private void translateWriteHelper( + BatchAvroIONativeWrite transform, + AvroIO.Write.Bound originalTransform, + TranslationContext context) { + // Note that the original transform can not be used during add step/add input + // and is only passed in to get properties from it. + + checkState(originalTransform.getNumShards() > 0, + "Native AvroSink is expected to only be used when sharding controls are required."); + + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + + // TODO: drop this check when server supports alternative templates. + switch (originalTransform.getShardTemplate()) { + case ShardNameTemplate.INDEX_OF_MAX: + break; // supported by server + case "": + // Empty shard template allowed - forces single output. + Preconditions.checkArgument(originalTransform.getNumShards() <= 1, + "Num shards must be <= 1 when using an empty sharding template"); + break; + default: + throw new UnsupportedOperationException("Shard template " + + originalTransform.getShardTemplate() + + " not yet supported by Dataflow service"); + } + + context.addInput(PropertyNames.FORMAT, "avro"); + context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); + context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, originalTransform.getShardTemplate()); + context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); + context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); + + context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); + + context.addEncodingInput( + WindowedValue.getValueOnlyCoder( + AvroCoder.of(originalTransform.getType(), originalTransform.getSchema()))); + } + } + /** * Specialized (non-)implementation for * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index f7217f7610..885260ebb2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -41,7 +41,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; @@ -49,7 +48,6 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; -import com.google.cloud.dataflow.sdk.runners.dataflow.AvroIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; @@ -1028,9 +1026,6 @@ private void translateHelper( /////////////////////////////////////////////////////////////////////////// // IO Translation. - registerTransformTranslator( - AvroIO.Write.Bound.class, new AvroIOTranslator.WriteTranslator()); - registerTransformTranslator( BigQueryIO.Read.Bound.class, new BigQueryIOTranslator.ReadTranslator()); registerTransformTranslator( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java deleted file mode 100644 index b114021c4d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.util.PathValidator; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.common.base.Preconditions; - -/** - * Avro transform support code for the Dataflow backend. - */ -public class AvroIOTranslator { - - /** - * Implements AvroIO Write translation for the Dataflow backend. - */ - @SuppressWarnings("rawtypes") - public static class WriteTranslator implements TransformTranslator { - - @Override - public void translate( - AvroIO.Write.Bound transform, - TranslationContext context) { - translateWriteHelper(transform, context); - } - - private void translateWriteHelper( - AvroIO.Write.Bound transform, - TranslationContext context) { - PathValidator validator = context.getPipelineOptions().getPathValidator(); - String filenamePrefix = validator.validateOutputFilePrefixSupported( - transform.getFilenamePrefix()); - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (transform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(transform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + transform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - context.addInput(PropertyNames.FORMAT, "avro"); - context.addInput(PropertyNames.FILENAME_PREFIX, filenamePrefix); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, transform.getShardTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, transform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, transform.needsValidation()); - - long numShards = transform.getNumShards(); - if (numShards > 0) { - context.addInput(PropertyNames.NUM_SHARDS, numShards); - } - - context.addEncodingInput( - WindowedValue.getValueOnlyCoder( - AvroCoder.of(transform.getType(), transform.getSchema()))); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java index 6bb459de7a..927d3a3903 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java @@ -148,102 +148,102 @@ void runTestRead(AvroIO.Read.Bound read, String expectedName, T[] expecte public void testReadFromGeneratedClass() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class), - "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); + "AvroIO.Read/Read.out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()), - "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); + "AvroIO.Read/Read.out", generateAvroObjects()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class), - "MyRead/Read(AvroSource).out", generateAvroObjects()); + "MyRead/Read.out", generateAvroObjects()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()), - "MyRead/Read(AvroSource).out", generateAvroObjects()); + "MyRead/Read.out", generateAvroObjects()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class) .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroObjects()); + "HerRead/Read.out", generateAvroObjects()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(AvroGeneratedUser.class), - "HerRead/Read(AvroSource).out", generateAvroObjects()); + "HerRead/Read.out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .named("HerRead") .from(avroFile.getPath()), - "HerRead/Read(AvroSource).out", generateAvroObjects()); + "HerRead/Read.out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()) .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroObjects()); + "HerRead/Read.out", generateAvroObjects()); } @Test public void testReadFromSchema() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schema), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); + "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .from(avroFile.getPath()), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); + "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(schema), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); + "MyRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(schema) .from(avroFile.getPath()), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); + "MyRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schema) .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(schema), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .named("HerRead") .from(avroFile.getPath()), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .from(avroFile.getPath()) .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); } @Test public void testReadFromSchemaString() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schemaString), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); + "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .from(avroFile.getPath()), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); + "AvroIO.Read/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(schemaString), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); + "MyRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(schemaString) .from(avroFile.getPath()), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); + "MyRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schemaString) .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(schemaString), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .named("HerRead") .from(avroFile.getPath()), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .from(avroFile.getPath()) .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + "HerRead/Read.out", generateAvroGenericRecords()); } void runTestWrite(AvroIO.Write.Bound write, String expectedName) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java index 30c578bbda..207b2ba514 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java @@ -16,19 +16,28 @@ package com.google.cloud.dataflow.sdk.io; +import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.DefaultCoder; +import com.google.cloud.dataflow.sdk.io.AvroIO.AvroSink; +import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation; +import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.DirectPipeline; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterators; +import org.apache.avro.file.DataFileReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.reflect.Nullable; import org.junit.Rule; @@ -38,6 +47,10 @@ import org.junit.runners.JUnit4; import java.io.File; +import java.nio.channels.FileChannel; +import java.nio.channels.WritableByteChannel; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -189,6 +202,38 @@ public void testAvroIOWriteAndReadSchemaUpgrade() throws Throwable { p.run(); } + @Test + public void testAvroSinkWrite() throws Exception { + String[] expectedElements = new String[]{ "first", "second", "third" }; + PipelineOptions options = PipelineOptionsFactory.create(); + AvroCoder coder = AvroCoder.of(String.class); + File tmpFile = tmpFolder.newFile(); + AvroSink avroSink = new AvroSink<>( + "prefix", "suffix", ShardNameTemplate.INDEX_OF_MAX, coder); + FileBasedWriteOperation writeOperation = avroSink.createWriteOperation(options); + FileBasedWriter writer = writeOperation.createWriter(options); + + WritableByteChannel channel = FileChannel.open(tmpFile.toPath(), StandardOpenOption.WRITE); + writer.prepareWrite(channel); + writer.writeHeader(); + for (String element : expectedElements) { + writer.write(element); + // We expect the channel to remain open + assertTrue(channel.isOpen()); + } + + writer.close(); + // Ensure that we properly close the channel + assertFalse(channel.isOpen()); + + // Validate that the data written matches the expected elements in the expected order + try (DataFileReader reader = new DataFileReader<>(tmpFile, coder.createDatumReader())) { + List actualElements = new ArrayList<>(); + Iterators.addAll(actualElements, reader); + assertThat(actualElements, contains(expectedElements)); + } + } + // TODO: for Write only, test withSuffix, withNumShards, // withShardNameTemplate and withoutSharding. } From 1d0c6d0ef0ca24e2b1b7eb330dd0340f696f25ed Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 22 Feb 2016 17:17:35 -0800 Subject: [PATCH 193/751] Move Google Cloud Dataflow worker utilities to worker module SourceTranslationUtils had a component that was used for custom source read translation. This component was moved directly into the read translation so that the native reader source utilities could move to the worker maven module along with the native reader base class. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115288815 --- .../sdk/runners/dataflow/ReadTranslator.java | 41 +- .../worker/SourceTranslationUtils.java | 150 -------- .../sdk/util/common/worker/NativeReader.java | 364 ------------------ 3 files changed, 40 insertions(+), 515 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceTranslationUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java index 47a1926764..f110e84adc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.runners.dataflow; -import static com.google.cloud.dataflow.sdk.runners.worker.SourceTranslationUtils.cloudSourceToDictionary; +import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; +import static com.google.cloud.dataflow.sdk.util.Structs.addDictionary; +import static com.google.cloud.dataflow.sdk.util.Structs.addLong; +import com.google.api.services.dataflow.model.SourceMetadata; import com.google.cloud.dataflow.sdk.io.FileBasedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Source; @@ -28,6 +31,9 @@ import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.values.PValue; +import java.util.HashMap; +import java.util.Map; + /** * Translator for the {@code Read} {@code PTransform} for the Dataflow back-end. */ @@ -61,4 +67,37 @@ public static void translateReadHelper(Source source, throw new RuntimeException(e); } } + + // Represents a cloud Source as a dictionary for encoding inside the {@code SOURCE_STEP_INPUT} + // property of CloudWorkflowStep.input. + private static Map cloudSourceToDictionary( + com.google.api.services.dataflow.model.Source source) { + // Do not translate encoding - the source's encoding is translated elsewhere + // to the step's output info. + Map res = new HashMap<>(); + addDictionary(res, PropertyNames.SOURCE_SPEC, source.getSpec()); + if (source.getMetadata() != null) { + addDictionary(res, PropertyNames.SOURCE_METADATA, + cloudSourceMetadataToDictionary(source.getMetadata())); + } + if (source.getDoesNotNeedSplitting() != null) { + addBoolean( + res, PropertyNames.SOURCE_DOES_NOT_NEED_SPLITTING, source.getDoesNotNeedSplitting()); + } + return res; + } + + private static Map cloudSourceMetadataToDictionary(SourceMetadata metadata) { + Map res = new HashMap<>(); + if (metadata.getProducesSortedKeys() != null) { + addBoolean(res, PropertyNames.SOURCE_PRODUCES_SORTED_KEYS, metadata.getProducesSortedKeys()); + } + if (metadata.getEstimatedSizeBytes() != null) { + addLong(res, PropertyNames.SOURCE_ESTIMATED_SIZE_BYTES, metadata.getEstimatedSizeBytes()); + } + if (metadata.getInfinite() != null) { + addBoolean(res, PropertyNames.SOURCE_IS_INFINITE, metadata.getInfinite()); + } + return res; + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceTranslationUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceTranslationUtils.java deleted file mode 100644 index 6c2c2c2da2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/SourceTranslationUtils.java +++ /dev/null @@ -1,150 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addDictionary; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; - -import com.google.api.services.dataflow.model.ApproximateReportedProgress; -import com.google.api.services.dataflow.model.ApproximateSplitRequest; -import com.google.api.services.dataflow.model.Position; -import com.google.api.services.dataflow.model.Source; -import com.google.api.services.dataflow.model.SourceMetadata; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.worker.NativeReader; - -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * Utilities for representing input-specific objects - * using Dataflow model protos. - */ -public class SourceTranslationUtils { - public static NativeReader.Progress cloudProgressToReaderProgress( - @Nullable ApproximateReportedProgress cloudProgress) { - return cloudProgress == null ? null : new DataflowReaderProgress(cloudProgress); - } - - public static NativeReader.Position cloudPositionToReaderPosition( - @Nullable Position cloudPosition) { - return cloudPosition == null ? null : new DataflowReaderPosition(cloudPosition); - } - - public static ApproximateReportedProgress readerProgressToCloudProgress( - @Nullable NativeReader.Progress readerProgress) { - return readerProgress == null ? null : ((DataflowReaderProgress) readerProgress).cloudProgress; - } - - public static Position toCloudPosition(@Nullable NativeReader.Position readerPosition) { - return readerPosition == null ? null : ((DataflowReaderPosition) readerPosition).cloudPosition; - } - - public static ApproximateSplitRequest splitRequestToApproximateSplitRequest( - @Nullable NativeReader.DynamicSplitRequest splitRequest) { - return (splitRequest == null) - ? null : ((DataflowDynamicSplitRequest) splitRequest).splitRequest; - } - - public static NativeReader.DynamicSplitRequest toDynamicSplitRequest( - @Nullable ApproximateSplitRequest splitRequest) { - return (splitRequest == null) ? null : new DataflowDynamicSplitRequest(splitRequest); - } - - static class DataflowReaderProgress implements NativeReader.Progress { - public final ApproximateReportedProgress cloudProgress; - - public DataflowReaderProgress(ApproximateReportedProgress cloudProgress) { - this.cloudProgress = cloudProgress; - } - - @Override - public String toString() { - return String.valueOf(cloudProgress); - } - } - - static class DataflowReaderPosition implements NativeReader.Position { - public final Position cloudPosition; - - public DataflowReaderPosition(Position cloudPosition) { - this.cloudPosition = cloudPosition; - } - - @Override - public String toString() { - return String.valueOf(cloudPosition); - } - } - - // Represents a cloud Source as a dictionary for encoding inside the {@code SOURCE_STEP_INPUT} - // property of CloudWorkflowStep.input. - public static Map cloudSourceToDictionary(Source source) { - // Do not translate encoding - the source's encoding is translated elsewhere - // to the step's output info. - Map res = new HashMap<>(); - addDictionary(res, PropertyNames.SOURCE_SPEC, source.getSpec()); - if (source.getMetadata() != null) { - addDictionary(res, PropertyNames.SOURCE_METADATA, - cloudSourceMetadataToDictionary(source.getMetadata())); - } - if (source.getDoesNotNeedSplitting() != null) { - addBoolean( - res, PropertyNames.SOURCE_DOES_NOT_NEED_SPLITTING, source.getDoesNotNeedSplitting()); - } - return res; - } - - private static Map cloudSourceMetadataToDictionary(SourceMetadata metadata) { - Map res = new HashMap<>(); - if (metadata.getProducesSortedKeys() != null) { - addBoolean(res, PropertyNames.SOURCE_PRODUCES_SORTED_KEYS, metadata.getProducesSortedKeys()); - } - if (metadata.getEstimatedSizeBytes() != null) { - addLong(res, PropertyNames.SOURCE_ESTIMATED_SIZE_BYTES, metadata.getEstimatedSizeBytes()); - } - if (metadata.getInfinite() != null) { - addBoolean(res, PropertyNames.SOURCE_IS_INFINITE, metadata.getInfinite()); - } - return res; - } - - public static Source dictionaryToCloudSource(Map params) throws Exception { - Source res = new Source(); - res.setSpec(getDictionary(params, PropertyNames.SOURCE_SPEC)); - // SOURCE_METADATA and SOURCE_DOES_NOT_NEED_SPLITTING do not have to be - // translated, because they only make sense in cloud Source objects produced by the user. - return res; - } - - private static class DataflowDynamicSplitRequest implements NativeReader.DynamicSplitRequest { - public final ApproximateSplitRequest splitRequest; - - private DataflowDynamicSplitRequest(ApproximateSplitRequest splitRequest) { - this.splitRequest = splitRequest; - } - - @Override - public String toString() { - return String.valueOf(splitRequest); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java deleted file mode 100644 index 20f399ffa4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/NativeReader.java +++ /dev/null @@ -1,364 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; - -import java.io.IOException; -import java.util.NoSuchElementException; -import java.util.Observable; - -import javax.annotation.Nullable; - -/** - * Abstract base class for native readers in the Dataflow runner. - * - *

    A {@link com.google.api.services.dataflow.model.Source} is read from by getting an - * {@code Iterator}-like value and iterating through it. - * - *

    This class is intended for formats that have built-in support on the Dataflow service. - * Do not introduce new implementations: for creating new input formats, use - * {@link com.google.cloud.dataflow.sdk.io.Source} instead. - * - * @param the type of the elements read from the source - */ -public abstract class NativeReader extends Observable { - /** - * StateSampler object for readers interested in further breaking - * down of the state space at a finer granularity. - */ - protected StateSampler stateSampler = null; - - /** - * Name to be used as a prefix with {@code stateSampler}. - */ - protected String stateSamplerOperationName = null; - - /** - * Sets the state sampler and the state sampler operation name. - * - * @param stateSampler the {@link StateSampler} object - * @param stateSamplerOperationName the operation name to be used by - * the state sampler - */ - public void setStateSamplerAndOperationName( - StateSampler stateSampler, String stateSamplerOperationName) { - this.stateSampler = stateSampler; - this.stateSamplerOperationName = stateSamplerOperationName; - } - - /** - * Returns a ReaderIterator that allows reading from this source. - */ - public abstract NativeReaderIterator iterator() throws IOException; - - /** - * A stateful iterator over the data in a {@link NativeReader}. - * - *

    Partially thread-safe: methods {@link #start}, {@link #advance}, {@link #getCurrent}, - * {@link #close} are called serially, but {@link #requestDynamicSplit} can be called - * asynchronously to those. - * - *

    There will not be multiple concurrent calls to {@link #requestDynamicSplit}). - * {@link #getProgress} can be called concurrently to any other call, including itself, if - * {@link #requestDynamicSplit} is implemented. - */ - public abstract static class NativeReaderIterator implements AutoCloseable { - - /** - * A value to return from {@link #getRemainingParallelism()} when remaining parallelism - * can be interpolated from {@link NativeReader#getTotalParallelism} and the progress fraction. - */ - public static final double REMAINING_PARALLELISM_FROM_PROGRESS_FRACTION = Double.NaN; - - /** - * Returns a representation of how far this iterator is through the source. - * - * @return the progress, or {@code null} if no progress measure can be provided - * (implementors are discouraged from throwing {@code UnsupportedOperationException} - * in this case). By default, returns {@code null}. - */ - @Nullable - public Progress getProgress() { - return null; - } - - /** - * Attempts to split the input in two parts: the "primary" part and the "residual" part. - * The current {@link NativeReaderIterator} keeps processing the primary part, while the - * residual part will be processed elsewhere (e.g. perhaps on a different worker). - * - *

    The primary and residual parts, if concatenated, must represent the same input as the - * current input of this {@link NativeReaderIterator} before this call. - * - *

    The boundary between the primary part and the residual part is specified in - * a framework-specific way using {@link NativeReader.DynamicSplitRequest}: e.g., if the - * framework supports the notion of positions, it might be a position at which the input is - * asked to split itself (which is not necessarily the same position at which it will - * split itself); it might be an approximate fraction of input, or something else. - * - *

    {@link NativeReader.DynamicSplitResult} encodes, in a framework-specific way, the - * information sufficient to construct a description of the resulting primary and - * residual inputs. - * For example, it might, again, be a position demarcating these parts, or it might be a pair of - * fully-specified input descriptions, or something else. - * - *

    After a successful call to {@link #requestDynamicSplit}, subsequent calls should be - * interpreted relative to the new primary. - * - *

    This call should not affect the range of input represented by the {@link NativeReader} - * that produced this {@link NativeReaderIterator}. - * - * @return {@code null} if the {@link NativeReader.DynamicSplitRequest} cannot be honored - * (in that case the input represented by this {@link NativeReaderIterator} stays the same), - * or a {@link NativeReader.DynamicSplitResult} describing how the input was split into - * a primary and residual part. By default, returns {@code null}. - */ - @Nullable - public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest request) { - return null; - } - - /** - * Returns an estimate of the degree of parallelism that could be achieved by - * {@link #requestDynamicSplit} taking into account what has already been consumed. - * E.g., if the reader has just returned the last record in the source, the remaining - * parallelism is 1 because it can't be split up any further. If the reader just - * returned the 3rd record in a perfectly parallelizable source with 5 records, - * the remaining parallelism is 3 because it could be processed in parallel by this - * worker and two others. If the reader does not support dynamic splitting, - * the remaining parallelism is always 1. - * - *

    An exact number isn't required, mostly we want to be able to distinguish - * between many, few, or one. Should not block. - * - *

    An implementor may return {@link #REMAINING_PARALLELISM_FROM_PROGRESS_FRACTION}, - * in which case the remaining parallelism will be interpolated from - * {@link NativeReader#getTotalParallelism} using the current progress fraction. - * Infinity may also be returned (indicating no known bound on parallelism), - * as may fractional estimates (in which case the sum over all shards is taken). - * - *

    By default, returns {@link #REMAINING_PARALLELISM_FROM_PROGRESS_FRACTION}. - */ - public double getRemainingParallelism() { - return REMAINING_PARALLELISM_FROM_PROGRESS_FRACTION; - } - - /** - * Initializes the reader and advances the reader to the first record. - * - *

    This method should be called exactly once. The invocation should occur prior to calling - * {@link #advance} or {@link #getCurrent}. This method may perform expensive operations that - * are needed to initialize the reader. - * - * @return {@code true} if a record was read, {@code false} if there is no more input available. - */ - public abstract boolean start() throws IOException; - - /** - * Advances the reader to the next valid record. - * - *

    It is an error to call this without having called {@link #start} first. - * - * @return {@code true} if a record was read, {@code false} if there is no more input available. - */ - public abstract boolean advance() throws IOException; - - /** - * Returns the value of the data item that was read by the last {@link #start} or - * {@link #advance} call. The returned value must be effectively immutable and remain valid - * indefinitely. - * - *

    Multiple calls to this method without an intervening call to {@link #advance} should - * return the same result. - * - * @throws NoSuchElementException if {@link #start} was never called, or if - * the last {@link #start} or {@link #advance} returned {@code false} - */ - public abstract T getCurrent() throws NoSuchElementException; - - /** - * @inheritDoc - */ - @Override - public void close() throws IOException { - // By default, do nothing. - } - } - - /** - * Adapter from old-style reader interface ({@link #hasNext}, {@link #next}) to new-style - * iteration interface ({@link NativeReaderIterator#start}, {@link NativeReaderIterator#advance}, - * {@link NativeReaderIterator#getCurrent}). - * - * This class is temporary and the intention is to get rid of its subclasses one by one, - * converting them to use the new-style interface directly, and then remove this class. - * - *

    Provides basic treatment of hasNext()/next() to simplify implementations (e.g. ensuring - * hasNext() is called only once and verifying hasNext() in next()) and default no-op - * implementations of other operations. - * - *

    This class is intended for internal usage. Users of Dataflow must not subclass it. - */ - public abstract static class LegacyReaderIterator extends NativeReaderIterator { - private Boolean cachedHasNext; - private T current; - private boolean hasCurrent; - - public final boolean hasNext() throws IOException { - if (cachedHasNext == null) { - cachedHasNext = hasNextImpl(); - } - return cachedHasNext; - } - - protected abstract boolean hasNextImpl() throws IOException; - - public final T next() throws IOException, NoSuchElementException { - if (!hasNext()) { - throw new NoSuchElementException(); - } - cachedHasNext = null; - return nextImpl(); - } - - protected abstract T nextImpl() throws IOException; - - @Override - public boolean start() throws IOException { - hasCurrent = advance(); - return hasCurrent; - } - - @Override - public boolean advance() throws IOException { - if (!hasNext()) { - hasCurrent = false; - return false; - } - current = next(); - hasCurrent = true; - return true; - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (!hasCurrent) { - throw new NoSuchElementException(); - } - return current; - } - } - - /** - * A representation of how far a {@code ReaderIterator} is through a - * {@code Reader}. - * - *

    The common worker framework does not interpret instances of - * this interface. But a tool-specific framework can make assumptions - * about the implementation, and so the concrete Reader subclasses used - * by a tool-specific framework should match. - */ - public interface Progress {} - - /** - * A representation of a position in an iteration through a - * {@code Reader}. - * - *

    See the comment on {@link Progress} for how instances of this - * interface are used by the rest of the framework. - */ - public interface Position {} - - /** - * A framework-specific way to specify how {@link NativeReaderIterator#requestDynamicSplit} - * should split the input into a primary and residual part. - */ - public interface DynamicSplitRequest {} - - /** - * A framework-specific way to specify how {@link NativeReaderIterator#requestDynamicSplit} - * has split the input into a primary and residual part. - */ - public interface DynamicSplitResult {} - - /** - * A {@link NativeReader.DynamicSplitResult} that specifies the boundary between the primary and - * residual parts of the input using a {@link Position}. - */ - public static final class DynamicSplitResultWithPosition implements DynamicSplitResult { - private final Position acceptedPosition; - - public DynamicSplitResultWithPosition(Position acceptedPosition) { - this.acceptedPosition = acceptedPosition; - } - - public Position getAcceptedPosition() { - return acceptedPosition; - } - - @Override - public String toString() { - return String.valueOf(acceptedPosition); - } - } - - /** - * Utility method to notify observers about a new element, which has - * been read by this Reader, and its size in bytes. Normally, there - * is only one observer, which is a ReadOperation that encapsules - * this Reader. Derived classes must call this method whenever they - * read additional data, even if that element may never be returned - * from the corresponding source iterator. - */ - protected void notifyElementRead(long byteSize) { - setChanged(); - notifyObservers(byteSize); - } - - /** - * Returns whether this Reader can be restarted. - */ - public boolean supportsRestart() { - return false; - } - - /** - * Returns an estimate of the parallelism of the source being read by this reader, i.e. - * the number of bundles it could be split into. An exact number isn't required, mostly - * we want to be able to distinguish between many, few, or one. Used to cap the parallelism - * Dataflow will allocate for this part of the pipeline. Should not block. - * - *

    Defaults to positive infinity, indicating unbounded parallelism. An unsplittable source - * would have parallelism exactly 1. - * - *

    See also {@link NativeReaderIterator#getRemainingParallelism} which may be implemented to - * complement this method if a better-than-linear estimate of remaining parallelism can be - * obtained (e.g. it is easy to detect when one is at the last record). - */ - public double getTotalParallelism() { - // By default, don't assume any limitations. - return Double.POSITIVE_INFINITY; - } - - /** - * The default state kind of all the states reported in this reader. - * Defaults to {@link StateKind#USER}. - */ - protected StateKind getStateSamplerStateKind() { - return StateKind.USER; - } -} From 7871cbb95bb36c245c3fc8384f1dc1f219a4a4a7 Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 22 Feb 2016 19:50:21 -0800 Subject: [PATCH 194/751] Port state to new, future-free API Before this change, a prefetch-then-batched read access pattern was achieved as follows: - First call State#get for some number of state cells, retrieving future-like StateContents objects - the underlying StateInternals can note all of these to batch their actual I/O. - Then call StateContents#read on each of those. After this change, StateContents is removed and the same pattern is achieved as follows: - First call State#readLater for some number of state cells, registering intent to read them - the underlying StateInternals can note all of these in the same manner to batch their actual I/O. - Then call State#read on each of those. The principle driving change is the "rename" of StateContents to the new ReadableState interface, which then all State subinterfaces extend. Classes driving this change: - ReadableState (just #get) - ValueState (adds #write) - CombiningState (adds #add) - AccumulatorCombiningState (adds #mergeAccumulators) - BagState (just a CombiningState) - WatermarkHoldState (adds #getOutputTimeFn) - InMemoryStateInternals - WindmillStateInternals The remainder of the change is trivial porting to the new API. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115298579 --- .../windowing/AfterDelayFromFirstElement.java | 18 +- .../sdk/transforms/windowing/AfterPane.java | 8 +- .../sdk/util/MergingActiveWindowSet.java | 4 +- .../dataflow/sdk/util/NonEmptyPanes.java | 12 +- .../dataflow/sdk/util/PaneInfoTracker.java | 22 ++- .../cloud/dataflow/sdk/util/ReduceFn.java | 4 +- .../sdk/util/ReduceFnContextFactory.java | 8 +- .../dataflow/sdk/util/ReduceFnRunner.java | 15 +- .../dataflow/sdk/util/SystemReduceFn.java | 20 +-- .../sdk/util/TriggerContextFactory.java | 3 +- .../dataflow/sdk/util/TriggerRunner.java | 18 +- .../dataflow/sdk/util/WatermarkHold.java | 36 ++-- ...al.java => AccumulatorCombiningState.java} | 15 +- .../dataflow/sdk/util/state/BagState.java | 4 +- ...ingValueState.java => CombiningState.java} | 11 +- .../CopyOnAccessInMemoryStateInternals.java | 48 ++--- .../util/state/InMemoryStateInternals.java | 122 +++++++------ ...{StateContents.java => ReadableState.java} | 18 +- .../cloud/dataflow/sdk/util/state/State.java | 2 +- .../dataflow/sdk/util/state/StateMerging.java | 57 +++--- .../dataflow/sdk/util/state/StateTag.java | 14 +- .../dataflow/sdk/util/state/StateTags.java | 34 ++-- .../dataflow/sdk/util/state/ValueState.java | 12 +- ...eInternal.java => WatermarkHoldState.java} | 7 +- .../dataflow/sdk/util/ReduceFnTester.java | 6 +- .../dataflow/sdk/util/TriggerTester.java | 6 +- ...opyOnAccessInMemoryStateInternalsTest.java | 166 +++++++++--------- .../state/InMemoryStateInternalsTest.java | 150 +++++++--------- 28 files changed, 431 insertions(+), 409 deletions(-) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/{CombiningValueStateInternal.java => AccumulatorCombiningState.java} (74%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/{CombiningValueState.java => CombiningState.java} (81%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/{StateContents.java => ReadableState.java} (67%) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/{WatermarkStateInternal.java => WatermarkHoldState.java} (90%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java index 43e77de6bc..71968e919c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -23,8 +23,8 @@ import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; +import com.google.cloud.dataflow.sdk.util.state.CombiningState; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateMerging; @@ -52,7 +52,7 @@ public abstract class AfterDelayFromFirstElement extend protected static final List> IDENTITY = ImmutableList.>of(); - protected static final StateTag, Instant>> DELAYED_UNTIL_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "delayed", InstantCoder.of(), Min.MinFn.naturalOrder())); @@ -152,13 +152,13 @@ private AfterDelayFromFirstElement newWith( @Override public void prefetchOnElement(StateAccessor state) { - state.access(DELAYED_UNTIL_TAG).get(); + state.access(DELAYED_UNTIL_TAG).readLater(); } @Override public void onElement(OnElementContext c) throws Exception { - CombiningValueState delayUntilState = c.state().access(DELAYED_UNTIL_TAG); - Instant oldDelayUntil = delayUntilState.get().read(); + CombiningState delayUntilState = c.state().access(DELAYED_UNTIL_TAG); + Instant oldDelayUntil = delayUntilState.read(); // Since processing time can only advance, resulting in target wake-up times we would // ignore anyhow, we don't bother with it if it is already set. @@ -200,7 +200,7 @@ public void onMerge(OnMergeContext c) throws Exception { // Determine the earliest point across all the windows, and delay to that. StateMerging.mergeCombiningValues(c.state(), DELAYED_UNTIL_TAG); - Instant earliestTargetTime = c.state().access(DELAYED_UNTIL_TAG).get().read(); + Instant earliestTargetTime = c.state().access(DELAYED_UNTIL_TAG).read(); if (earliestTargetTime != null) { c.setTimer(earliestTargetTime, timeDomain); } @@ -208,7 +208,7 @@ public void onMerge(OnMergeContext c) throws Exception { @Override public void prefetchShouldFire(StateAccessor state) { - state.access(DELAYED_UNTIL_TAG).get(); + state.access(DELAYED_UNTIL_TAG).readLater(); } @Override @@ -223,7 +223,7 @@ public Instant getWatermarkThatGuaranteesFiring(W window) { @Override public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - Instant delayedUntil = context.state().access(DELAYED_UNTIL_TAG).get().read(); + Instant delayedUntil = context.state().access(DELAYED_UNTIL_TAG).read(); return delayedUntil != null && getCurrentTime(context) != null && getCurrentTime(context).isAfter(delayedUntil); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java index 729cd3e063..28c8560ac4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java @@ -20,7 +20,7 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateMerging; @@ -41,7 +41,7 @@ @Experimental(Experimental.Kind.TRIGGER) public class AfterPane extends OnceTrigger{ -private static final StateTag> +private static final StateTag> ELEMENTS_IN_PANE_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "count", VarLongCoder.of(), new Sum.SumLongFn())); @@ -87,12 +87,12 @@ public void onMerge(OnMergeContext context) throws Exception { @Override public void prefetchShouldFire(StateAccessor state) { - state.access(ELEMENTS_IN_PANE_TAG).get(); + state.access(ELEMENTS_IN_PANE_TAG).readLater(); } @Override public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - long count = context.state().access(ELEMENTS_IN_PANE_TAG).get().read(); + long count = context.state().access(ELEMENTS_IN_PANE_TAG).read(); return count >= countElems; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index d0a49dcfa8..95e378d9f4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -119,7 +119,7 @@ public MergingActiveWindowSet(WindowFn windowFn, StateInternals st valueState = state.state(StateNamespaces.global(), mergeTreeAddr); // Little use trying to prefetch this state since the ReduceFnRunner is stymied until it is // available. - activeWindowToStateAddressWindows = emptyIfNull(valueState.get().read()); + activeWindowToStateAddressWindows = emptyIfNull(valueState.read()); activeWindowToEphemeralWindows = new HashMap<>(); originalActiveWindowToStateAddressWindows = deepCopy(activeWindowToStateAddressWindows); windowToActiveWindow = invert(activeWindowToStateAddressWindows); @@ -155,7 +155,7 @@ public void persist() { Preconditions.checkState( activeWindowToEphemeralWindows.isEmpty(), "Unexpected EPHEMERAL windows before persist"); - valueState.set(activeWindowToStateAddressWindows); + valueState.write(activeWindowToStateAddressWindows); // No need to update originalActiveWindowToStateAddressWindows since this object is about to // become garbage. } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java index 4d6131451e..1270f01423 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java @@ -19,10 +19,10 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -58,7 +58,7 @@ static NonEmptyPanes create( /** * Return true if the current pane for the window in {@code context} is empty. */ - public abstract StateContents isEmpty(StateAccessor context); + public abstract ReadableState isEmpty(StateAccessor context); /** * Prefetch in preparation for merging. @@ -84,7 +84,7 @@ private DiscardingModeNonEmptyPanes(ReduceFn reduceFn) { } @Override - public StateContents isEmpty(StateAccessor state) { + public ReadableState isEmpty(StateAccessor state) { return reduceFn.isEmpty(state); } @@ -115,7 +115,7 @@ public void onMerge(MergingStateAccessor context) { private static class GeneralNonEmptyPanes extends NonEmptyPanes { - private static final StateTag> + private static final StateTag> PANE_ADDITIONS_TAG = StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "count", VarLongCoder.of(), new Sum.SumLongFn())); @@ -131,7 +131,7 @@ public void clearPane(StateAccessor state) { } @Override - public StateContents isEmpty(StateAccessor state) { + public ReadableState isEmpty(StateAccessor state) { return state.access(PANE_ADDITIONS_TAG).isEmpty(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index e66f9a7b0d..38499c2e2b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -19,8 +19,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; import com.google.cloud.dataflow.sdk.util.state.ValueState; @@ -51,22 +51,28 @@ public void clear(StateAccessor state) { } /** - * Return a (future for) the pane info appropriate for {@code context}. The pane info - * includes the timing for the pane, who's calculation is quite subtle. + * Return a ({@link ReadableState} for) the pane info appropriate for {@code context}. The pane + * info includes the timing for the pane, who's calculation is quite subtle. * * @param isEndOfWindow should be {@code true} only if the pane is being emitted * because an end-of-window timer has fired and the trigger agreed we should fire. * @param isFinal should be {@code true} only if the triggering machinery can guarantee * no further firings for the */ - public StateContents getNextPaneInfo(ReduceFn.Context context, + public ReadableState getNextPaneInfo(ReduceFn.Context context, final boolean isEndOfWindow, final boolean isFinal) { final Object key = context.key(); - final StateContents previousPaneFuture = - context.state().access(PaneInfoTracker.PANE_INFO_TAG).get(); + final ReadableState previousPaneFuture = + context.state().access(PaneInfoTracker.PANE_INFO_TAG); final Instant windowMaxTimestamp = context.window().maxTimestamp(); - return new StateContents() { + return new ReadableState() { + @Override + public ReadableState readLater() { + previousPaneFuture.readLater(); + return this; + } + @Override public PaneInfo read() { PaneInfo previousPane = previousPaneFuture.read(); @@ -76,7 +82,7 @@ public PaneInfo read() { } public void storeCurrentPaneInfo(ReduceFn.Context context, PaneInfo currentPane) { - context.state().access(PANE_INFO_TAG).set(currentPane); + context.state().access(PANE_INFO_TAG).write(currentPane); } private PaneInfo describePane(Object key, Instant windowMaxTimestamp, PaneInfo previousPane, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java index ae0913ae4f..c5ef2ea126 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java @@ -18,8 +18,8 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateContents; import org.joda.time.Instant; @@ -124,5 +124,5 @@ public void prefetchOnTrigger(StateAccessor context) {} /** * Returns true if the there is no buffered state. */ - public abstract StateContents isEmpty(StateAccessor context); + public abstract ReadableState isEmpty(StateAccessor context); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index d0296d1ad6..b2ab752edf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -22,9 +22,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; @@ -90,7 +90,7 @@ public ReduceFn.ProcessValueContext forValue( } public ReduceFn.OnTriggerContext forTrigger(W window, - StateContents pane, StateStyle style, OnTriggerCallbacks callbacks) { + ReadableState pane, StateStyle style, OnTriggerCallbacks callbacks) { return new OnTriggerContextImpl(stateContext(window, style), pane, callbacks); } @@ -358,11 +358,11 @@ public Timers timers() { private class OnTriggerContextImpl extends ReduceFn.OnTriggerContext { private final StateAccessorImpl state; - private final StateContents pane; + private final ReadableState pane; private final OnTriggerCallbacks callbacks; private final TimersImpl timers; - private OnTriggerContextImpl(StateAccessorImpl state, StateContents pane, + private OnTriggerContextImpl(StateAccessorImpl state, ReadableState pane, OnTriggerCallbacks callbacks) { reduceFn.super(); this.state = state; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index d550a2395c..ec83688fb4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -29,7 +29,7 @@ import com.google.cloud.dataflow.sdk.util.ReduceFnContextFactory.StateStyle; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowNamespace; import com.google.cloud.dataflow.sdk.values.KV; @@ -716,12 +716,13 @@ private void onTrigger( boolean isEndOfWindow, boolean isFinished) throws Exception { - // Collect state. - StateContents outputTimestampFuture = - watermarkHold.extractAndRelease(renamedContext, isFinished); - StateContents paneFuture = - paneInfoTracker.getNextPaneInfo(directContext, isEndOfWindow, isFinished); - StateContents isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext.state()); + // Prefetch necessary states + ReadableState outputTimestampFuture = + watermarkHold.extractAndRelease(renamedContext, isFinished).readLater(); + ReadableState paneFuture = + paneInfoTracker.getNextPaneInfo(directContext, isEndOfWindow, isFinished).readLater(); + ReadableState isEmptyFuture = + nonEmptyPanes.isEmpty(renamedContext.state()).readLater(); reduceFn.prefetchOnTrigger(directContext.state()); triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java index 233e1da9a3..d5d912672d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java @@ -23,12 +23,12 @@ import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueState; -import com.google.cloud.dataflow.sdk.util.state.CombiningValueStateInternal; +import com.google.cloud.dataflow.sdk.util.state.CombiningState; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; +import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateContents; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; @@ -78,7 +78,7 @@ public void onMerge(OnMergeContext c) throws Exception { !(combineFn.getFn() instanceof RequiresContextInternal), "Combiner lifting is not supported for combine functions with contexts: %s", combineFn.getFn().getClass().getName()); - final StateTag> bufferTag = + final StateTag> bufferTag = StateTags.makeSystemTagInternal( StateTags.keyedCombiningValue( BUFFER_NAME, combineFn.getAccumulatorCoder(), @@ -96,10 +96,10 @@ public void onMerge(OnMergeContext c) throws Exception { }; } - private StateTag> bufferTag; + private StateTag> bufferTag; - private SystemReduceFn( - StateTag> bufferTag) { + public SystemReduceFn( + StateTag> bufferTag) { this.bufferTag = bufferTag; } @@ -110,12 +110,12 @@ public void processValue(ProcessValueContext c) throws Exception { @Override public void prefetchOnTrigger(StateAccessor state) { - state.access(bufferTag).get(); + state.access(bufferTag).readLater(); } @Override public void onTrigger(OnTriggerContext c) throws Exception { - c.output(c.state().access(bufferTag).get().read()); + c.output(c.state().access(bufferTag).read()); } @Override @@ -124,7 +124,7 @@ public void clearState(Context c) throws Exception { } @Override - public StateContents isEmpty(StateAccessor state) { + public ReadableState isEmpty(StateAccessor state) { return state.access(bufferTag).isEmpty(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index c27e731e8e..87e8b00f58 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -292,7 +292,8 @@ public MergingStateAccessorImpl(ExecutableTrigger trigger, Collection acti } @Override - public StorageT access(StateTag address) { + public StateT access( + StateTag address) { return stateInternals.state(windowNamespace, address); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index e78411eb83..1b78ddc5b1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -76,7 +76,7 @@ private FinishedTriggersBitSet readFinishedBits(ValueState state) { return FinishedTriggersBitSet.emptyWithCapacity(rootTrigger.getFirstIndexAfterSubtree()); } - BitSet bitSet = state.get().read(); + BitSet bitSet = state.read(); return bitSet == null ? FinishedTriggersBitSet.emptyWithCapacity(rootTrigger.getFirstIndexAfterSubtree()) : FinishedTriggersBitSet.fromBitSet(bitSet); @@ -89,21 +89,21 @@ public boolean isClosed(StateAccessor state) { public void prefetchForValue(W window, StateAccessor state) { if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).get(); + state.access(FINISHED_BITS_TAG).readLater(); } rootTrigger.getSpec().prefetchOnElement(contextFactory.createStateContext(window, rootTrigger)); } public void prefetchOnFire(W window, StateAccessor state) { if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).get(); + state.access(FINISHED_BITS_TAG).readLater(); } rootTrigger.getSpec().prefetchOnFire(contextFactory.createStateContext(window, rootTrigger)); } public void prefetchShouldFire(W window, StateAccessor state) { if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).get(); + state.access(FINISHED_BITS_TAG).readLater(); } rootTrigger.getSpec().prefetchShouldFire( contextFactory.createStateContext(window, rootTrigger)); @@ -127,7 +127,7 @@ public void prefetchForMerge( W window, Collection mergingWindows, MergingStateAccessor state) { if (isFinishedSetNeeded()) { for (ValueState value : state.accessInEachMergingWindow(FINISHED_BITS_TAG).values()) { - value.get(); + value.readLater(); } } rootTrigger.getSpec().prefetchOnMerge(contextFactory.createMergingStateContext( @@ -185,12 +185,12 @@ private void persistFinishedSet( return; } - ValueState finishedSet = state.access(FINISHED_BITS_TAG); - if (!finishedSet.get().equals(modifiedFinishedSet)) { + ValueState finishedSetState = state.access(FINISHED_BITS_TAG); + if (!readFinishedBits(finishedSetState).equals(modifiedFinishedSet)) { if (modifiedFinishedSet.getBitSet().isEmpty()) { - finishedSet.clear(); + finishedSetState.clear(); } else { - finishedSet.set(modifiedFinishedSet.getBitSet()); + finishedSetState.write(modifiedFinishedSet.getBitSet()); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index d0614db092..d537ddb0e8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -20,11 +20,11 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateContents; +import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.StateMerging; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.WatermarkStateInternal; +import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; @@ -56,9 +56,9 @@ class WatermarkHold implements Serializable { * used for elements. */ public static - StateTag> watermarkHoldTagForOutputTimeFn( + StateTag> watermarkHoldTagForOutputTimeFn( OutputTimeFn outputTimeFn) { - return StateTags.>makeSystemTagInternal( + return StateTags.>makeSystemTagInternal( StateTags.watermarkStateInternal("hold", outputTimeFn)); } @@ -69,13 +69,13 @@ StateTag> watermarkHoldTagForOutputTimeFn( * would take the end-of-window time as its element time.) */ @VisibleForTesting - public static final StateTag> EXTRA_HOLD_TAG = + public static final StateTag> EXTRA_HOLD_TAG = StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal( "extra", OutputTimeFns.outputAtEarliestInputTimestamp())); private final TimerInternals timerInternals; private final WindowingStrategy windowingStrategy; - private final StateTag> elementHoldTag; + private final StateTag> elementHoldTag; public WatermarkHold(TimerInternals timerInternals, WindowingStrategy windowingStrategy) { this.timerInternals = timerInternals; @@ -377,25 +377,27 @@ public void onMerge(ReduceFn.OnMergeContext context) { * elements in the current pane. If there is no such value the timestamp is the end * of the window. */ - public StateContents extractAndRelease( + public ReadableState extractAndRelease( final ReduceFn.Context context, final boolean isFinished) { WindowTracing.debug( "extractAndRelease: for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", context.key(), context.window(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - final WatermarkStateInternal elementHoldState = context.state().access(elementHoldTag); - // Since we only extract holds when a trigger fires it is unreasonable to expect - // the state to be prefetched. - final StateContents elementHoldFuture = elementHoldState.get(); - final WatermarkStateInternal extraHoldState = - context.state().access(EXTRA_HOLD_TAG); - final StateContents extraHoldFuture = extraHoldState.get(); - return new StateContents() { + final WatermarkHoldState elementHoldState = context.state().access(elementHoldTag); + final WatermarkHoldState extraHoldState = context.state().access(EXTRA_HOLD_TAG); + return new ReadableState() { + @Override + public ReadableState readLater() { + elementHoldState.readLater(); + extraHoldState.readLater(); + return this; + } + @Override public Instant read() { // Read both the element and extra holds. - Instant elementHold = elementHoldFuture.read(); - Instant extraHold = extraHoldFuture.read(); + Instant elementHold = elementHoldState.read(); + Instant extraHold = extraHoldState.read(); Instant hold; // Find the minimum, accounting for null. if (elementHold == null) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/AccumulatorCombiningState.java similarity index 74% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/AccumulatorCombiningState.java index 2f18b9c80b..0d78b13bad 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueStateInternal.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/AccumulatorCombiningState.java @@ -19,19 +19,21 @@ /** * State for a single value that is managed by a {@link CombineFn}. This is an internal extension - * to {@link CombiningValueState} that includes the {@code AccumT} type. + * to {@link CombiningState} that includes the {@code AccumT} type. * * @param the type of values added to the state * @param the type of accumulator * @param the type of value extracted from the state */ -public interface CombiningValueStateInternal - extends CombiningValueState { +public interface AccumulatorCombiningState + extends CombiningState { /** - * Read the merged accumulator for this combining value. + * Read the merged accumulator for this combining value. It is implied that reading the + * state involes reading the accumulator, so {@link #readLater} is sufficient to prefetch for + * this. */ - StateContents getAccum(); + AccumT getAccum(); /** * Add an accumulator to this combining value. Depending on implementation this may immediately @@ -43,4 +45,7 @@ public interface CombiningValueStateInternal * Merge the given accumulators according to the underlying combiner. */ AccumT mergeAccumulators(Iterable accumulators); + + @Override + AccumulatorCombiningState readLater(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java index 5e0eef6a55..363e480797 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java @@ -20,5 +20,7 @@ * * @param The type of elements in the bag. */ -public interface BagState extends CombiningValueState> { +public interface BagState extends CombiningState> { + @Override + BagState readLater(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningState.java similarity index 81% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueState.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningState.java index ee1fcac1d8..673bebbfb4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningValueState.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningState.java @@ -24,20 +24,17 @@ * @param the type of values added to the state * @param the type of value extracted from the state */ -public interface CombiningValueState extends State { +public interface CombiningState extends ReadableState, State { /** * Add a value to the buffer. */ void add(InputT value); - /** - * Return the {@link StateContents} object to use for accessing the contents of the buffer. - */ - StateContents get(); - /** * Return true if this state is empty. */ - StateContents isEmpty(); + ReadableState isEmpty(); + @Override + CombiningState readLater(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java index 4968976987..19e45d6f00 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java @@ -68,7 +68,7 @@ private CopyOnAccessInMemoryStateInternals( * has not been bound in this {@link CopyOnAccessInMemoryStateInternals}, put a reference to that * state within this {@link StateInternals}. * - *

    Additionally, stores the {@link WatermarkStateInternal} with the earliest time bound in the + *

    Additionally, stores the {@link WatermarkHoldState} with the earliest time bound in the * state table after the commit is completed, enabling calls to * {@link #getEarliestWatermarkHold()}. * @@ -185,8 +185,8 @@ private void commit() { private Instant getEarliestWatermarkHold() { Instant earliest = BoundedWindow.TIMESTAMP_MAX_VALUE; for (State existingState : this.values()) { - if (existingState instanceof WatermarkStateInternal) { - Instant hold = ((WatermarkStateInternal) existingState).get().read(); + if (existingState instanceof WatermarkHoldState) { + Instant hold = ((WatermarkHoldState) existingState).read(); if (hold != null && hold.isBefore(earliest)) { earliest = hold; } @@ -249,17 +249,17 @@ private boolean containedInUnderlying(StateNamespace namespace, StateTag forNamespace(final StateNamespace namespace) { return new StateBinder() { @Override - public WatermarkStateInternal bindWatermark( - StateTag> address, + public WatermarkHoldState bindWatermark( + StateTag> address, OutputTimeFn outputTimeFn) { if (containedInUnderlying(namespace, address)) { @SuppressWarnings("unchecked") - InMemoryState> existingState = - (InMemoryStateInternals.InMemoryState>) + InMemoryState> existingState = + (InMemoryStateInternals.InMemoryState>) underlying.get().get(namespace, address); return existingState.copy(); } else { - return new InMemoryStateInternals.WatermarkStateInternalImplementation<>( + return new InMemoryStateInternals.InMemoryWatermarkHold<>( outputTimeFn); } } @@ -279,16 +279,16 @@ public ValueState bindValue( } @Override - public CombiningValueStateInternal + public AccumulatorCombiningState bindCombiningValue( - StateTag> address, + StateTag> address, Coder accumCoder, CombineFn combineFn) { if (containedInUnderlying(namespace, address)) { @SuppressWarnings("unchecked") - InMemoryState> + InMemoryState> existingState = ( InMemoryStateInternals - .InMemoryState>) underlying.get().get(namespace, address); return existingState.copy(); } else { @@ -312,17 +312,17 @@ public BagState bindBag( } @Override - public CombiningValueStateInternal + public AccumulatorCombiningState bindKeyedCombiningValue( - StateTag> address, + StateTag> address, Coder accumCoder, KeyedCombineFn combineFn) { if (containedInUnderlying(namespace, address)) { @SuppressWarnings("unchecked") - InMemoryState> + InMemoryState> existingState = ( InMemoryStateInternals - .InMemoryState>) underlying.get().get(namespace, address); return existingState.copy(); } else { @@ -355,8 +355,8 @@ public Instant readThroughAndGetEarliestHold(StateTable readTo) { // eventually discarded, and remember the earliest watermark hold from among those // values. State state = readTo.get(namespace, existingState.getKey()); - if (state instanceof WatermarkStateInternal) { - Instant hold = ((WatermarkStateInternal) state).get().read(); + if (state instanceof WatermarkHoldState) { + Instant hold = ((WatermarkHoldState) state).read(); if (hold != null && hold.isBefore(earliestHold)) { earliestHold = hold; } @@ -371,8 +371,8 @@ public Instant readThroughAndGetEarliestHold(StateTable readTo) { public StateBinder forNamespace(final StateNamespace namespace) { return new StateBinder() { @Override - public WatermarkStateInternal bindWatermark( - StateTag> address, + public WatermarkHoldState bindWatermark( + StateTag> address, OutputTimeFn outputTimeFn) { return underlying.get(namespace, address); } @@ -384,9 +384,9 @@ public ValueState bindValue( } @Override - public CombiningValueStateInternal + public AccumulatorCombiningState bindCombiningValue( - StateTag> address, + StateTag> address, Coder accumCoder, CombineFn combineFn) { return underlying.get(namespace, address); } @@ -398,9 +398,9 @@ public BagState bindBag( } @Override - public CombiningValueStateInternal + public AccumulatorCombiningState bindKeyedCombiningValue( - StateTag> address, + StateTag> address, Coder accumCoder, KeyedCombineFn combineFn) { return underlying.get(namespace, address); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 658494bcbb..4a2555f358 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -107,25 +107,25 @@ public BagState bindBag( } @Override - public CombiningValueStateInternal + public AccumulatorCombiningState bindCombiningValue( - StateTag> + StateTag> address, Coder accumCoder, final CombineFn combineFn) { return new InMemoryCombiningValue(key, combineFn.asKeyedFn()); } @Override - public WatermarkStateInternal bindWatermark( - StateTag> address, + public WatermarkHoldState bindWatermark( + StateTag> address, OutputTimeFn outputTimeFn) { - return new WatermarkStateInternalImplementation(outputTimeFn); + return new InMemoryWatermarkHold(outputTimeFn); } @Override - public CombiningValueStateInternal + public AccumulatorCombiningState bindKeyedCombiningValue( - StateTag> + StateTag> address, Coder accumCoder, KeyedCombineFn combineFn) { return new InMemoryCombiningValue(key, combineFn); @@ -145,17 +145,17 @@ public void clear() { } @Override - public StateContents get() { - return new StateContents() { - @Override - public T read() { - return value; - } - }; + public InMemoryValue readLater() { + return this; } @Override - public void set(T input) { + public T read() { + return value; + } + + @Override + public void write(T input) { isCleared = false; this.value = input; } @@ -176,18 +176,23 @@ public boolean isCleared() { } } - static final class WatermarkStateInternalImplementation - implements WatermarkStateInternal, InMemoryState> { + static final class InMemoryWatermarkHold + implements WatermarkHoldState, InMemoryState> { private final OutputTimeFn outputTimeFn; @Nullable private Instant combinedHold = null; - public WatermarkStateInternalImplementation(OutputTimeFn outputTimeFn) { + public InMemoryWatermarkHold(OutputTimeFn outputTimeFn) { this.outputTimeFn = outputTimeFn; } + @Override + public InMemoryWatermarkHold readLater() { + return this; + } + @Override public void clear() { // Even though we're clearing we can't remove this from the in-memory state map, since @@ -196,13 +201,8 @@ public void clear() { } @Override - public StateContents get() { - return new StateContents() { - @Override - public Instant read() { - return combinedHold; - } - }; + public Instant read() { + return combinedHold; } @Override @@ -217,8 +217,12 @@ public boolean isCleared() { } @Override - public StateContents isEmpty() { - return new StateContents() { + public ReadableState isEmpty() { + return new ReadableState() { + @Override + public ReadableState readLater() { + return this; + } @Override public Boolean read() { return combinedHold == null; @@ -237,17 +241,17 @@ public String toString() { } @Override - public WatermarkStateInternalImplementation copy() { - WatermarkStateInternalImplementation that = - new WatermarkStateInternalImplementation<>(outputTimeFn); + public InMemoryWatermarkHold copy() { + InMemoryWatermarkHold that = + new InMemoryWatermarkHold<>(outputTimeFn); that.combinedHold = this.combinedHold; return that; } } static final class InMemoryCombiningValue - implements CombiningValueStateInternal, - InMemoryState> { + implements AccumulatorCombiningState, + InMemoryState> { private final K key; private boolean isCleared = true; private final KeyedCombineFn combineFn; @@ -260,6 +264,11 @@ static final class InMemoryCombiningValue accum = combineFn.createAccumulator(key); } + @Override + public InMemoryCombiningValue readLater() { + return this; + } + @Override public void clear() { // Even though we're clearing we can't remove this from the in-memory state map, since @@ -269,13 +278,8 @@ public void clear() { } @Override - public StateContents get() { - return new StateContents() { - @Override - public OutputT read() { - return combineFn.extractOutput(key, accum); - } - }; + public OutputT read() { + return combineFn.extractOutput(key, accum); } @Override @@ -285,18 +289,17 @@ public void add(InputT input) { } @Override - public StateContents getAccum() { - return new StateContents() { - @Override - public AccumT read() { - return accum; - } - }; + public AccumT getAccum() { + return accum; } @Override - public StateContents isEmpty() { - return new StateContents() { + public ReadableState isEmpty() { + return new ReadableState() { + @Override + public ReadableState readLater() { + return this; + } @Override public Boolean read() { return isCleared; @@ -348,13 +351,13 @@ public void clear() { } @Override - public StateContents> get() { - return new StateContents>() { - @Override - public Iterable read() { - return contents; - } - }; + public InMemoryBag readLater() { + return this; + } + + @Override + public Iterable read() { + return contents; } @Override @@ -368,8 +371,13 @@ public boolean isCleared() { } @Override - public StateContents isEmpty() { - return new StateContents() { + public ReadableState isEmpty() { + return new ReadableState() { + @Override + public ReadableState readLater() { + return this; + } + @Override public Boolean read() { return contents.isEmpty(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContents.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ReadableState.java similarity index 67% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContents.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ReadableState.java index e00462fe5b..8f690a33de 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContents.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ReadableState.java @@ -31,9 +31,23 @@ * @param The type of value returned by {@link #read}. */ @Experimental(Kind.STATE) -public interface StateContents { +public interface ReadableState { /** - * Read the current value. + * Read the current value, blocking until it is available. + * + *

    If there will be many calls to {@link #read} for different state in short succession, + * you should first call {@link #readLater} for all of them so the reads can potentially be + * batched (depending on the underlying {@link StateInternals} implementation}. */ T read(); + + /** + * Indicate that the value will be read later. + * + *

    This allows a {@link StateInternals} implementation to start an asynchronous prefetch or + * to include this state in the next batch of reads. + * + * @return this for convenient chaining + */ + ReadableState readLater(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java index f53e4c198f..0cef786ad5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java @@ -19,7 +19,7 @@ * Base interface for all state locations. * *

    Specific types of state add appropriate accessors for reading and writing values, see - * {@link ValueState}, {@link BagState}, and {@link CombiningValueState}. + * {@link ValueState}, {@link BagState}, and {@link CombiningState}. */ public interface State { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java index 3c53a20413..0b33ea9b8e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java @@ -56,7 +56,7 @@ public static void prefetchBags( // Prefetch everything except what's already in result. for (BagState source : map.values()) { if (!source.equals(result)) { - source.get(); + source.readLater(); } } } @@ -79,10 +79,11 @@ public static void mergeBags( return; } // Prefetch everything except what's already in result. - List>> futures = new ArrayList<>(sources.size()); + List>> futures = new ArrayList<>(sources.size()); for (BagState source : sources) { if (!source.equals(result)) { - futures.add(source.get()); + source.readLater(); + futures.add(source); } } if (futures.isEmpty()) { @@ -90,7 +91,7 @@ public static void mergeBags( return; } // Transfer from sources to result. - for (StateContents> future : futures) { + for (ReadableState> future : futures) { for (T element : future.read()) { result.add(element); } @@ -107,11 +108,11 @@ public static void mergeBags( * Prefetch all combining value state for {@code address} across all merging windows in {@code * context}. */ - public static , W extends BoundedWindow> void + public static , W extends BoundedWindow> void prefetchCombiningValues(MergingStateAccessor context, StateTag address) { for (StateT state : context.accessInEachMergingWindow(address).values()) { - state.get(); + state.readLater(); } } @@ -120,7 +121,7 @@ public static void mergeBags( */ public static void mergeCombiningValues( MergingStateAccessor context, - StateTag> address) { + StateTag> address) { mergeCombiningValues( context.accessInEachMergingWindow(address).values(), context.access(address)); } @@ -130,8 +131,8 @@ public static void mergeCo * {@code result}. */ public static void mergeCombiningValues( - Collection> sources, - CombiningValueStateInternal result) { + Collection> sources, + AccumulatorCombiningState result) { if (sources.isEmpty()) { // Nothing to merge. return; @@ -141,19 +142,19 @@ public static void mergeCombi return; } // Prefetch. - List> futures = new ArrayList<>(sources.size()); - for (CombiningValueStateInternal source : sources) { - futures.add(source.getAccum()); + List> futures = new ArrayList<>(sources.size()); + for (AccumulatorCombiningState source : sources) { + source.readLater(); } // Read. List accumulators = new ArrayList<>(futures.size()); - for (StateContents future : futures) { - accumulators.add(future.read()); + for (AccumulatorCombiningState source : sources) { + accumulators.add(source.getAccum()); } // Merge (possibly update and return one of the existing accumulators). AccumT merged = result.mergeAccumulators(accumulators); // Clear sources. - for (CombiningValueStateInternal source : sources) { + for (AccumulatorCombiningState source : sources) { source.clear(); } // Update result. @@ -166,9 +167,9 @@ public static void mergeCombi */ public static void prefetchWatermarks( MergingStateAccessor context, - StateTag> address) { - Map> map = context.accessInEachMergingWindow(address); - WatermarkStateInternal result = context.access(address); + StateTag> address) { + Map> map = context.accessInEachMergingWindow(address); + WatermarkHoldState result = context.access(address); if (map.isEmpty()) { // Nothing to prefetch. return; @@ -183,8 +184,8 @@ public static void prefetchWatermarks( return; } // Prefetch. - for (WatermarkStateInternal source : map.values()) { - source.get(); + for (WatermarkHoldState source : map.values()) { + source.readLater(); } } @@ -194,7 +195,7 @@ public static void prefetchWatermarks( */ public static void mergeWatermarks( MergingStateAccessor context, - StateTag> address, + StateTag> address, W mergeResult) { mergeWatermarks( context.accessInEachMergingWindow(address).values(), context.access(address), mergeResult); @@ -205,7 +206,7 @@ public static void mergeWatermarks( * into {@code result}, where the final merge result window is {@code mergeResult}. */ public static void mergeWatermarks( - Collection> sources, WatermarkStateInternal result, + Collection> sources, WatermarkHoldState result, W resultWindow) { if (sources.isEmpty()) { // Nothing to merge. @@ -218,7 +219,7 @@ public static void mergeWatermarks( } if (result.getOutputTimeFn().dependsOnlyOnWindow()) { // Clear sources. - for (WatermarkStateInternal source : sources) { + for (WatermarkHoldState source : sources) { source.clear(); } // Update directly from window-derived hold. @@ -228,20 +229,20 @@ public static void mergeWatermarks( result.add(hold); } else { // Prefetch. - List> futures = new ArrayList<>(sources.size()); - for (WatermarkStateInternal source : sources) { - futures.add(source.get()); + List> futures = new ArrayList<>(sources.size()); + for (WatermarkHoldState source : sources) { + futures.add(source); } // Read. List outputTimesToMerge = new ArrayList<>(sources.size()); - for (StateContents future : futures) { + for (ReadableState future : futures) { Instant sourceOutputTime = future.read(); if (sourceOutputTime != null) { outputTimesToMerge.add(sourceOutputTime); } } // Clear sources. - for (WatermarkStateInternal source : sources) { + for (WatermarkHoldState source : sources) { source.clear(); } if (!outputTimesToMerge.isEmpty()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java index e7b02dfc5a..2924763b89 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java @@ -53,24 +53,24 @@ public interface StateBinder { BagState bindBag(StateTag> address, Coder elemCoder); - CombiningValueStateInternal + AccumulatorCombiningState bindCombiningValue( - StateTag> address, + StateTag> address, Coder accumCoder, CombineFn combineFn); - CombiningValueStateInternal + AccumulatorCombiningState bindKeyedCombiningValue( - StateTag> address, + StateTag> address, Coder accumCoder, KeyedCombineFn combineFn); /** * Bind to a watermark {@link StateTag}. * *

    This accepts the {@link OutputTimeFn} that dictates how watermark hold timestamps - * added to the returned {@link WatermarkStateInternal} are to be combined. + * added to the returned {@link WatermarkHoldState} are to be combined. */ - WatermarkStateInternal bindWatermark( - StateTag> address, + WatermarkHoldState bindWatermark( + StateTag> address, OutputTimeFn outputTimeFn); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index df5ab0310c..c1efb601b3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -71,7 +71,7 @@ public static StateTag> value(String id, Coder valu * multiple {@code InputT}s into a single {@code OutputT}. */ public static - StateTag> + StateTag> combiningValue( String id, Coder accumCoder, CombineFn combineFn) { return combiningValueInternal(id, accumCoder, combineFn); @@ -83,7 +83,7 @@ public static StateTag> value(String id, Coder valu * {@link KeyedCombineFn} comes from the keyed {@link StateAccessor}. */ public static StateTag> + OutputT> StateTag> keyedCombiningValue(String id, Coder accumCoder, KeyedCombineFn combineFn) { return keyedCombiningValueInternal(id, accumCoder, combineFn); @@ -97,7 +97,7 @@ public static StateTag> value(String id, Coder valu * should only be used to initialize static values. */ public static - StateTag> + StateTag> combiningValueFromInputInternal( String id, Coder inputCoder, CombineFn combineFn) { try { @@ -111,7 +111,7 @@ public static StateTag> value(String id, Coder valu } private static StateTag> + OutputT> StateTag> combiningValueInternal( String id, Coder accumCoder, CombineFn combineFn) { return @@ -120,7 +120,7 @@ public static StateTag> value(String id, Coder valu } private static - StateTag> keyedCombiningValueInternal( + StateTag> keyedCombiningValueInternal( String id, Coder accumCoder, KeyedCombineFn combineFn) { @@ -139,7 +139,7 @@ public static StateTag> bag(String id, Coder elemCode /** * Create a state tag for holding the watermark. */ - public static StateTag> + public static StateTag> watermarkStateInternal(String id, OutputTimeFn outputTimeFn) { return new WatermarkStateTagInternal(new StructuredId(id), outputTimeFn); } @@ -161,7 +161,7 @@ public static StateTag makeSystemTagInterna public static StateTag> convertToBagTagInternal( - StateTag> combiningTag) { + StateTag> combiningTag) { if (!(combiningTag instanceof KeyedCombiningValueStateTag)) { throw new IllegalArgumentException("Unexpected StateTag " + combiningTag); } @@ -315,8 +315,8 @@ public StateTag> asKind(StateKind kind) { */ private static class CombiningValueStateTag extends KeyedCombiningValueStateTag - implements StateTag>, - SystemStateTag> { + implements StateTag>, + SystemStateTag> { private final Coder accumCoder; private final CombineFn combineFn; @@ -330,7 +330,7 @@ private CombiningValueStateTag( } @Override - public StateTag> + public StateTag> asKind(StateKind kind) { return new CombiningValueStateTag( id.asKind(kind), accumCoder, combineFn); @@ -347,8 +347,8 @@ private CombiningValueStateTag( * @param type of output values */ private static class KeyedCombiningValueStateTag - extends StateTagBase> - implements SystemStateTag> { + extends StateTagBase> + implements SystemStateTag> { private final Coder accumCoder; private final KeyedCombineFn keyedCombineFn; @@ -362,7 +362,7 @@ protected KeyedCombiningValueStateTag( } @Override - public CombiningValueStateInternal bind( + public AccumulatorCombiningState bind( StateBinder visitor) { return visitor.bindKeyedCombiningValue(this, accumCoder, keyedCombineFn); } @@ -388,7 +388,7 @@ public int hashCode() { } @Override - public StateTag> asKind( + public StateTag> asKind( StateKind kind) { return new KeyedCombiningValueStateTag<>(id.asKind(kind), accumCoder, keyedCombineFn); } @@ -446,7 +446,7 @@ public StateTag> asKind(StateKind kind) { } private static class WatermarkStateTagInternal - extends StateTagBase> { + extends StateTagBase> { /** * When multiple output times are added to hold the watermark, this determines how they are @@ -461,7 +461,7 @@ private WatermarkStateTagInternal(StructuredId id, OutputTimeFn outpu } @Override - public WatermarkStateInternal bind(StateBinder visitor) { + public WatermarkHoldState bind(StateBinder visitor) { return visitor.bindWatermark(this, outputTimeFn); } @@ -485,7 +485,7 @@ public int hashCode() { } @Override - public StateTag> asKind(StateKind kind) { + public StateTag> asKind(StateKind kind) { return new WatermarkStateTagInternal(id.asKind(kind), outputTimeFn); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java index f575dfc7f5..19c12bb164 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java @@ -24,14 +24,12 @@ * @param The type of values being stored. */ @Experimental(Kind.STATE) -public interface ValueState extends State { - /** - * Return the {@link StateContents} object to use for accessing the contents of the buffer. - */ - StateContents get(); - +public interface ValueState extends ReadableState, State { /** * Set the value of the buffer. */ - void set(T input); + void write(T input); + + @Override + ValueState readLater(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkStateInternal.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkHoldState.java similarity index 90% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkStateInternal.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkHoldState.java index 19972aab2e..8a1adc9558 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkStateInternal.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkHoldState.java @@ -29,11 +29,14 @@ *

    For internal use only. This API may change at any time. */ @Experimental(Kind.STATE) -public interface WatermarkStateInternal - extends CombiningValueState { +public interface WatermarkHoldState + extends CombiningState { /** * Return the {@link OutputTimeFn} which will be used to determine a watermark hold time given * an element timestamp, and to combine watermarks from windows which are about to be merged. */ OutputTimeFn getOutputTimeFn(); + + @Override + WatermarkHoldState readLater(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index a91675cd89..bade9f915e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -45,7 +45,7 @@ import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.WatermarkStateInternal; +import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.cloud.dataflow.sdk.values.TupleTag; @@ -415,8 +415,8 @@ public Set getNamespacesInUse() { public Instant earliestWatermarkHold() { Instant minimum = null; for (State storage : inMemoryState.values()) { - if (storage instanceof WatermarkStateInternal) { - Instant hold = ((WatermarkStateInternal) storage).get().read(); + if (storage instanceof WatermarkHoldState) { + Instant hold = ((WatermarkHoldState) storage).read(); if (minimum == null || (hold != null && hold.isBefore(minimum))) { minimum = hold; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index e5507ced8d..0c71830202 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -38,7 +38,7 @@ import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowAndTriggerNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowNamespace; import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.WatermarkStateInternal; +import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.base.MoreObjects; import com.google.common.base.Throwables; @@ -369,9 +369,9 @@ public Set getNamespacesInUse() { public Instant earliestWatermarkHold() { Instant minimum = null; for (State storage : inMemoryState.values()) { - if (storage instanceof WatermarkStateInternal) { + if (storage instanceof WatermarkHoldState) { @SuppressWarnings("unchecked") - Instant hold = ((WatermarkStateInternal) storage).get().read(); + Instant hold = ((WatermarkHoldState) storage).read(); if (minimum == null || (hold != null && hold.isBefore(minimum))) { minimum = hold; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java index 00887857ed..5bb0f59772 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java @@ -60,14 +60,14 @@ public void testGetWithEmpty() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); - assertThat(stringBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(stringBag.read(), containsInAnyOrder("baz", "bar")); BagState reReadStringBag = internals.state(namespace, bagTag); - assertThat(reReadStringBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(reReadStringBag.read(), containsInAnyOrder("baz", "bar")); } @Test @@ -80,17 +80,17 @@ public void testGetWithAbsentInUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); - assertThat(stringBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(stringBag.read(), containsInAnyOrder("baz", "bar")); BagState reReadVoidBag = internals.state(namespace, bagTag); - assertThat(reReadVoidBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(reReadVoidBag.read(), containsInAnyOrder("baz", "bar")); BagState underlyingState = underlying.state(namespace, bagTag); - assertThat(underlyingState.get().read(), emptyIterable()); + assertThat(underlyingState.read(), emptyIterable()); } /** @@ -106,22 +106,22 @@ public void testGetWithPresentInUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> valueTag = StateTags.value("foo", StringUtf8Coder.of()); ValueState underlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.get().read(), nullValue(String.class)); + assertThat(underlyingValue.read(), nullValue(String.class)); - underlyingValue.set("bar"); - assertThat(underlyingValue.get().read(), equalTo("bar")); + underlyingValue.write("bar"); + assertThat(underlyingValue.read(), equalTo("bar")); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); ValueState copyOnAccessState = internals.state(namespace, valueTag); - assertThat(copyOnAccessState.get().read(), equalTo("bar")); + assertThat(copyOnAccessState.read(), equalTo("bar")); - copyOnAccessState.set("baz"); - assertThat(copyOnAccessState.get().read(), equalTo("baz")); - assertThat(underlyingValue.get().read(), equalTo("bar")); + copyOnAccessState.write("baz"); + assertThat(copyOnAccessState.read(), equalTo("baz")); + assertThat(underlyingValue.read(), equalTo("bar")); ValueState reReadUnderlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); } @Test @@ -132,89 +132,89 @@ public void testBagStateWithUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> valueTag = StateTags.bag("foo", VarIntCoder.of()); BagState underlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.get().read(), emptyIterable()); + assertThat(underlyingValue.read(), emptyIterable()); underlyingValue.add(1); - assertThat(underlyingValue.get().read(), containsInAnyOrder(1)); + assertThat(underlyingValue.read(), containsInAnyOrder(1)); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); BagState copyOnAccessState = internals.state(namespace, valueTag); - assertThat(copyOnAccessState.get().read(), containsInAnyOrder(1)); + assertThat(copyOnAccessState.read(), containsInAnyOrder(1)); copyOnAccessState.add(4); - assertThat(copyOnAccessState.get().read(), containsInAnyOrder(4, 1)); - assertThat(underlyingValue.get().read(), containsInAnyOrder(1)); + assertThat(copyOnAccessState.read(), containsInAnyOrder(4, 1)); + assertThat(underlyingValue.read(), containsInAnyOrder(1)); BagState reReadUnderlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); } @Test - public void testCombiningValueStateInternalWithUnderlying() throws CannotProvideCoderException { + public void testAccumulatorCombiningStateWithUnderlying() throws CannotProvideCoderException { CopyOnAccessInMemoryStateInternals underlying = CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); CombineFn sumLongFn = new Sum.SumLongFn(); StateNamespace namespace = new StateNamespaceForTest("foo"); CoderRegistry reg = TestPipeline.create().getCoderRegistry(); - StateTag> stateTag = + StateTag> stateTag = StateTags.combiningValue("summer", sumLongFn.getAccumulatorCoder(reg, reg.getDefaultCoder(Long.class)), sumLongFn); - CombiningValueState underlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.get().read(), equalTo(0L)); + CombiningState underlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.read(), equalTo(0L)); underlyingValue.add(1L); - assertThat(underlyingValue.get().read(), equalTo(1L)); + assertThat(underlyingValue.read(), equalTo(1L)); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - CombiningValueState copyOnAccessState = internals.state(namespace, stateTag); - assertThat(copyOnAccessState.get().read(), equalTo(1L)); + CombiningState copyOnAccessState = internals.state(namespace, stateTag); + assertThat(copyOnAccessState.read(), equalTo(1L)); copyOnAccessState.add(4L); - assertThat(copyOnAccessState.get().read(), equalTo(5L)); - assertThat(underlyingValue.get().read(), equalTo(1L)); + assertThat(copyOnAccessState.read(), equalTo(5L)); + assertThat(underlyingValue.read(), equalTo(1L)); - CombiningValueState reReadUnderlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + CombiningState reReadUnderlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); } @Test - public void testKeyedCombiningValueStateInternalWithUnderlying() throws Exception { + public void testKeyedAccumulatorCombiningStateWithUnderlying() throws Exception { CopyOnAccessInMemoryStateInternals underlying = CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); KeyedCombineFn sumLongFn = new Sum.SumLongFn().asKeyedFn(); StateNamespace namespace = new StateNamespaceForTest("foo"); CoderRegistry reg = TestPipeline.create().getCoderRegistry(); - StateTag> stateTag = + StateTag> stateTag = StateTags.keyedCombiningValue( "summer", sumLongFn.getAccumulatorCoder( reg, StringUtf8Coder.of(), reg.getDefaultCoder(Long.class)), sumLongFn); - CombiningValueState underlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.get().read(), equalTo(0L)); + CombiningState underlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.read(), equalTo(0L)); underlyingValue.add(1L); - assertThat(underlyingValue.get().read(), equalTo(1L)); + assertThat(underlyingValue.read(), equalTo(1L)); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - CombiningValueState copyOnAccessState = internals.state(namespace, stateTag); - assertThat(copyOnAccessState.get().read(), equalTo(1L)); + CombiningState copyOnAccessState = internals.state(namespace, stateTag); + assertThat(copyOnAccessState.read(), equalTo(1L)); copyOnAccessState.add(4L); - assertThat(copyOnAccessState.get().read(), equalTo(5L)); - assertThat(underlyingValue.get().read(), equalTo(1L)); + assertThat(copyOnAccessState.read(), equalTo(5L)); + assertThat(underlyingValue.read(), equalTo(1L)); - CombiningValueState reReadUnderlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + CombiningState reReadUnderlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); } @Test - public void testWatermarkStateInternalWithUnderlying() { + public void testWatermarkHoldStateWithUnderlying() { CopyOnAccessInMemoryStateInternals underlying = CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); @@ -223,29 +223,29 @@ public void testWatermarkStateInternalWithUnderlying() { TestPipeline.create().apply(Create.of("foo")).getWindowingStrategy().getOutputTimeFn(); StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> stateTag = + StateTag> stateTag = StateTags.watermarkStateInternal("wmstate", outputTimeFn); - WatermarkStateInternal underlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.get().read(), nullValue()); + WatermarkHoldState underlyingValue = underlying.state(namespace, stateTag); + assertThat(underlyingValue.read(), nullValue()); underlyingValue.add(new Instant(250L)); - assertThat(underlyingValue.get().read(), equalTo(new Instant(250L))); + assertThat(underlyingValue.read(), equalTo(new Instant(250L))); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - WatermarkStateInternal copyOnAccessState = internals.state(namespace, stateTag); - assertThat(copyOnAccessState.get().read(), equalTo(new Instant(250L))); + WatermarkHoldState copyOnAccessState = internals.state(namespace, stateTag); + assertThat(copyOnAccessState.read(), equalTo(new Instant(250L))); copyOnAccessState.add(new Instant(100L)); - assertThat(copyOnAccessState.get().read(), equalTo(new Instant(100L))); - assertThat(underlyingValue.get().read(), equalTo(new Instant(250L))); + assertThat(copyOnAccessState.read(), equalTo(new Instant(100L))); + assertThat(underlyingValue.read(), equalTo(new Instant(250L))); copyOnAccessState.add(new Instant(500L)); - assertThat(copyOnAccessState.get().read(), equalTo(new Instant(100L))); + assertThat(copyOnAccessState.read(), equalTo(new Instant(100L))); - WatermarkStateInternal reReadUnderlyingValue = + WatermarkHoldState reReadUnderlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.get().read(), equalTo(reReadUnderlyingValue.get().read())); + assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); } @Test @@ -255,16 +255,16 @@ public void testCommitWithoutUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); - assertThat(stringBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(stringBag.read(), containsInAnyOrder("baz", "bar")); internals.commit(); BagState reReadStringBag = internals.state(namespace, bagTag); - assertThat(reReadStringBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(reReadStringBag.read(), containsInAnyOrder("baz", "bar")); assertThat(internals.isEmpty(), is(false)); } @@ -278,19 +278,19 @@ public void testCommitWithUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); internals.commit(); BagState reReadStringBag = internals.state(namespace, bagTag); - assertThat(reReadStringBag.get().read(), containsInAnyOrder("baz", "bar")); + assertThat(reReadStringBag.read(), containsInAnyOrder("baz", "bar")); reReadStringBag.add("spam"); BagState underlyingState = underlying.state(namespace, bagTag); - assertThat(underlyingState.get().read(), containsInAnyOrder("spam", "bar", "baz")); + assertThat(underlyingState.read(), containsInAnyOrder("spam", "bar", "baz")); assertThat(underlyingState, is(theInstance(stringBag))); assertThat(internals.isEmpty(), is(false)); } @@ -307,7 +307,7 @@ public void testCommitWithClearedInUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); @@ -320,7 +320,7 @@ public void testCommitWithClearedInUnderlying() { internals.commit(); BagState internalsStringBag = internals.state(namespace, bagTag); - assertThat(internalsStringBag.get().read(), emptyIterable()); + assertThat(internalsStringBag.read(), emptyIterable()); verify(secondUnderlying, never()).state(namespace, bagTag); assertThat(internals.isEmpty(), is(false)); } @@ -335,7 +335,7 @@ public void testCommitWithOverwrittenUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); @@ -350,10 +350,10 @@ public void testCommitWithOverwrittenUnderlying() { BagState reReadInternalState = internals.state(namespace, bagTag); assertThat( - reReadInternalState.get().read(), + reReadInternalState.read(), containsInAnyOrder("bar", "baz", "0x00ff00", "eggs", "&", "ham")); BagState reReadUnderlyingState = underlying.state(namespace, bagTag); - assertThat(reReadUnderlyingState.get().read(), containsInAnyOrder("bar", "baz")); + assertThat(reReadUnderlyingState.read(), containsInAnyOrder("bar", "baz")); } @Test @@ -368,16 +368,16 @@ public void testCommitWithAddedUnderlying() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); BagState internalState = internals.state(namespace, bagTag); - assertThat(internalState.get().read(), emptyIterable()); + assertThat(internalState.read(), emptyIterable()); BagState reReadUnderlyingState = underlying.state(namespace, bagTag); - assertThat(reReadUnderlyingState.get().read(), containsInAnyOrder("bar", "baz")); + assertThat(reReadUnderlyingState.read(), containsInAnyOrder("bar", "baz")); } @Test @@ -398,7 +398,7 @@ public void testCommitWithOnlyClearedValuesIsEmpty() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("foo"); stringBag.clear(); @@ -418,7 +418,7 @@ public void testCommitWithEmptyNewAndFullUnderlyingIsNotEmpty() { StateNamespace namespace = new StateNamespaceForTest("foo"); StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.get().read(), emptyIterable()); + assertThat(stringBag.read(), emptyIterable()); stringBag.add("bar"); stringBag.add("baz"); @@ -444,15 +444,15 @@ public Instant maxTimestamp() { CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); - StateTag> firstHoldAddress = + StateTag> firstHoldAddress = StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal firstHold = + WatermarkHoldState firstHold = internals.state(StateNamespaces.window(null, first), firstHoldAddress); firstHold.add(new Instant(22L)); - StateTag> secondHoldAddress = + StateTag> secondHoldAddress = StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal secondHold = + WatermarkHoldState secondHold = internals.state(StateNamespaces.window(null, second), secondHoldAddress); secondHold.add(new Instant(2L)); @@ -476,18 +476,18 @@ public Instant maxTimestamp() { }; CopyOnAccessInMemoryStateInternals underlying = CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); - StateTag> firstHoldAddress = + StateTag> firstHoldAddress = StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal firstHold = + WatermarkHoldState firstHold = underlying.state(StateNamespaces.window(null, first), firstHoldAddress); firstHold.add(new Instant(22L)); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying("foo", underlying.commit()); - StateTag> secondHoldAddress = + StateTag> secondHoldAddress = StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal secondHold = + WatermarkHoldState secondHold = internals.state(StateNamespaces.window(null, second), secondHoldAddress); secondHold.add(new Instant(244L)); @@ -513,18 +513,18 @@ public Instant maxTimestamp() { }; CopyOnAccessInMemoryStateInternals underlying = CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); - StateTag> firstHoldAddress = + StateTag> firstHoldAddress = StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal firstHold = + WatermarkHoldState firstHold = underlying.state(StateNamespaces.window(null, first), firstHoldAddress); firstHold.add(new Instant(224L)); CopyOnAccessInMemoryStateInternals internals = CopyOnAccessInMemoryStateInternals.withUnderlying("foo", underlying.commit()); - StateTag> secondHoldAddress = + StateTag> secondHoldAddress = StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkStateInternal secondHold = + WatermarkHoldState secondHold = internals.state(StateNamespaces.window(null, second), secondHoldAddress); secondHold.add(new Instant(24L)); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java index 4df13ae939..0c10560e4a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java @@ -46,18 +46,18 @@ public class InMemoryStateInternalsTest { private static final StateTag> STRING_VALUE_ADDR = StateTags.value("stringValue", StringUtf8Coder.of()); - private static final StateTag> + private static final StateTag> SUM_INTEGER_ADDR = StateTags.combiningValueFromInputInternal( "sumInteger", VarIntCoder.of(), new Sum.SumIntegerFn()); private static final StateTag> STRING_BAG_ADDR = StateTags.bag("stringBag", StringUtf8Coder.of()); - private static final StateTag> + private static final StateTag> WATERMARK_EARLIEST_ADDR = StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - private static final StateTag> + private static final StateTag> WATERMARK_LATEST_ADDR = StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtLatestInputTimestamp()); - private static final StateTag> WATERMARK_EOW_ADDR = + private static final StateTag> WATERMARK_EOW_ADDR = StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEndOfWindow()); InMemoryStateInternals underTest = InMemoryStateInternals.forKey("dummyKey"); @@ -72,16 +72,14 @@ public void testValue() throws Exception { underTest.state(NAMESPACE_2, STRING_VALUE_ADDR), Matchers.not(Matchers.sameInstance(value))); - assertThat(value.get().read(), Matchers.nullValue()); - StateContents readFuture = value.get(); - value.set("hello"); - assertThat(readFuture.read(), Matchers.equalTo("hello")); - assertThat(value.get().read(), Matchers.equalTo("hello")); - value.set("world"); - assertThat(readFuture.read(), Matchers.equalTo("world")); + assertThat(value.read(), Matchers.nullValue()); + value.write("hello"); + assertThat(value.read(), Matchers.equalTo("hello")); + value.write("world"); + assertThat(value.read(), Matchers.equalTo("world")); value.clear(); - assertThat(value.get().read(), Matchers.nullValue()); + assertThat(value.read(), Matchers.nullValue()); assertThat(underTest.state(NAMESPACE_1, STRING_VALUE_ADDR), Matchers.sameInstance(value)); } @@ -93,17 +91,15 @@ public void testBag() throws Exception { assertEquals(value, underTest.state(NAMESPACE_1, STRING_BAG_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, STRING_BAG_ADDR))); - assertThat(value.get().read(), Matchers.emptyIterable()); - StateContents> readFuture = value.get(); + assertThat(value.read(), Matchers.emptyIterable()); value.add("hello"); - assertThat(readFuture.read(), Matchers.containsInAnyOrder("hello")); - assertThat(value.get().read(), Matchers.containsInAnyOrder("hello")); + assertThat(value.read(), Matchers.containsInAnyOrder("hello")); value.add("world"); - assertThat(value.get().read(), Matchers.containsInAnyOrder("hello", "world")); + assertThat(value.read(), Matchers.containsInAnyOrder("hello", "world")); value.clear(); - assertThat(value.get().read(), Matchers.emptyIterable()); + assertThat(value.read(), Matchers.emptyIterable()); assertThat(underTest.state(NAMESPACE_1, STRING_BAG_ADDR), Matchers.sameInstance(value)); } @@ -112,7 +108,7 @@ public void testBagIsEmpty() throws Exception { BagState value = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); - StateContents readFuture = value.isEmpty(); + ReadableState readFuture = value.isEmpty(); value.add("hello"); assertThat(readFuture.read(), Matchers.is(false)); @@ -132,8 +128,8 @@ public void testMergeBagIntoSource() throws Exception { StateMerging.mergeBags(Arrays.asList(bag1, bag2), bag1); // Reading the merged bag gets both the contents - assertThat(bag1.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!")); - assertThat(bag2.get().read(), Matchers.emptyIterable()); + assertThat(bag1.read(), Matchers.containsInAnyOrder("Hello", "World", "!")); + assertThat(bag2.read(), Matchers.emptyIterable()); } @Test @@ -149,39 +145,37 @@ public void testMergeBagIntoNewNamespace() throws Exception { StateMerging.mergeBags(Arrays.asList(bag1, bag2, bag3), bag3); // Reading the merged bag gets both the contents - assertThat(bag3.get().read(), Matchers.containsInAnyOrder("Hello", "World", "!")); - assertThat(bag1.get().read(), Matchers.emptyIterable()); - assertThat(bag2.get().read(), Matchers.emptyIterable()); + assertThat(bag3.read(), Matchers.containsInAnyOrder("Hello", "World", "!")); + assertThat(bag1.read(), Matchers.emptyIterable()); + assertThat(bag2.read(), Matchers.emptyIterable()); } @Test public void testCombiningValue() throws Exception { - CombiningValueState value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); + CombiningState value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR))); - assertThat(value.get().read(), Matchers.equalTo(0)); - StateContents readFuture = value.get(); + assertThat(value.read(), Matchers.equalTo(0)); value.add(2); - assertThat(readFuture.read(), Matchers.equalTo(2)); - assertThat(value.get().read(), Matchers.equalTo(2)); + assertThat(value.read(), Matchers.equalTo(2)); value.add(3); - assertThat(readFuture.read(), Matchers.equalTo(5)); + assertThat(value.read(), Matchers.equalTo(5)); value.clear(); - assertThat(readFuture.read(), Matchers.equalTo(0)); + assertThat(value.read(), Matchers.equalTo(0)); assertThat(underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR), Matchers.sameInstance(value)); } @Test public void testCombiningIsEmpty() throws Exception { - CombiningValueState value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); + CombiningState value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); - StateContents readFuture = value.isEmpty(); + ReadableState readFuture = value.isEmpty(); value.add(5); assertThat(readFuture.read(), Matchers.is(false)); @@ -191,32 +185,32 @@ public void testCombiningIsEmpty() throws Exception { @Test public void testMergeCombiningValueIntoSource() throws Exception { - CombiningValueStateInternal value1 = + AccumulatorCombiningState value1 = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - CombiningValueStateInternal value2 = + AccumulatorCombiningState value2 = underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); value1.add(5); value2.add(10); value1.add(6); - assertThat(value1.get().read(), Matchers.equalTo(11)); - assertThat(value2.get().read(), Matchers.equalTo(10)); + assertThat(value1.read(), Matchers.equalTo(11)); + assertThat(value2.read(), Matchers.equalTo(10)); // Merging clears the old values and updates the result value. StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value1); - assertThat(value1.get().read(), Matchers.equalTo(21)); - assertThat(value2.get().read(), Matchers.equalTo(0)); + assertThat(value1.read(), Matchers.equalTo(21)); + assertThat(value2.read(), Matchers.equalTo(0)); } @Test public void testMergeCombiningValueIntoNewNamespace() throws Exception { - CombiningValueStateInternal value1 = + AccumulatorCombiningState value1 = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - CombiningValueStateInternal value2 = + AccumulatorCombiningState value2 = underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); - CombiningValueStateInternal value3 = + AccumulatorCombiningState value3 = underTest.state(NAMESPACE_3, SUM_INTEGER_ADDR); value1.add(5); @@ -226,93 +220,83 @@ public void testMergeCombiningValueIntoNewNamespace() throws Exception { StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value3); // Merging clears the old values and updates the result value. - assertThat(value1.get().read(), Matchers.equalTo(0)); - assertThat(value2.get().read(), Matchers.equalTo(0)); - assertThat(value3.get().read(), Matchers.equalTo(21)); + assertThat(value1.read(), Matchers.equalTo(0)); + assertThat(value2.read(), Matchers.equalTo(0)); + assertThat(value3.read(), Matchers.equalTo(21)); } @Test public void testWatermarkEarliestState() throws Exception { - WatermarkStateInternal value = + WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR))); - assertThat(value.get().read(), Matchers.nullValue()); - StateContents readFuture = value.get(); + assertThat(value.read(), Matchers.nullValue()); value.add(new Instant(2000)); - assertThat(readFuture.read(), Matchers.equalTo(new Instant(2000))); - assertThat(value.get().read(), Matchers.equalTo(new Instant(2000))); + assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.add(new Instant(3000)); - assertThat(readFuture.read(), Matchers.equalTo(new Instant(2000))); - assertThat(value.get().read(), Matchers.equalTo(new Instant(2000))); + assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.add(new Instant(1000)); - assertThat(readFuture.read(), Matchers.equalTo(new Instant(1000))); - assertThat(value.get().read(), Matchers.equalTo(new Instant(1000))); + assertThat(value.read(), Matchers.equalTo(new Instant(1000))); value.clear(); - assertThat(readFuture.read(), Matchers.equalTo(null)); + assertThat(value.read(), Matchers.equalTo(null)); assertThat(underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR), Matchers.sameInstance(value)); } @Test public void testWatermarkLatestState() throws Exception { - WatermarkStateInternal value = + WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR))); - assertThat(value.get().read(), Matchers.nullValue()); - StateContents readFuture = value.get(); + assertThat(value.read(), Matchers.nullValue()); value.add(new Instant(2000)); - assertThat(readFuture.read(), Matchers.equalTo(new Instant(2000))); - assertThat(value.get().read(), Matchers.equalTo(new Instant(2000))); + assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.add(new Instant(3000)); - assertThat(readFuture.read(), Matchers.equalTo(new Instant(3000))); - assertThat(value.get().read(), Matchers.equalTo(new Instant(3000))); + assertThat(value.read(), Matchers.equalTo(new Instant(3000))); value.add(new Instant(1000)); - assertThat(readFuture.read(), Matchers.equalTo(new Instant(3000))); - assertThat(value.get().read(), Matchers.equalTo(new Instant(3000))); + assertThat(value.read(), Matchers.equalTo(new Instant(3000))); value.clear(); - assertThat(readFuture.read(), Matchers.equalTo(null)); + assertThat(value.read(), Matchers.equalTo(null)); assertThat(underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR), Matchers.sameInstance(value)); } @Test public void testWatermarkEndOfWindowState() throws Exception { - WatermarkStateInternal value = underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR); + WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_EOW_ADDR))); - assertThat(value.get().read(), Matchers.nullValue()); - StateContents readFuture = value.get(); + assertThat(value.read(), Matchers.nullValue()); value.add(new Instant(2000)); - assertThat(readFuture.read(), Matchers.equalTo(new Instant(2000))); - assertThat(value.get().read(), Matchers.equalTo(new Instant(2000))); + assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.clear(); - assertThat(readFuture.read(), Matchers.equalTo(null)); + assertThat(value.read(), Matchers.equalTo(null)); assertThat(underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR), Matchers.sameInstance(value)); } @Test public void testWatermarkStateIsEmpty() throws Exception { - WatermarkStateInternal value = + WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); - StateContents readFuture = value.isEmpty(); + ReadableState readFuture = value.isEmpty(); value.add(new Instant(1000)); assertThat(readFuture.read(), Matchers.is(false)); @@ -322,9 +306,9 @@ public void testWatermarkStateIsEmpty() throws Exception { @Test public void testMergeEarliestWatermarkIntoSource() throws Exception { - WatermarkStateInternal value1 = + WatermarkHoldState value1 = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); - WatermarkStateInternal value2 = + WatermarkHoldState value2 = underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR); value1.add(new Instant(3000)); @@ -335,17 +319,17 @@ public void testMergeEarliestWatermarkIntoSource() throws Exception { // Merging clears the old values and updates the merged value. StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value1, WINDOW_1); - assertThat(value1.get().read(), Matchers.equalTo(new Instant(2000))); - assertThat(value2.get().read(), Matchers.equalTo(null)); + assertThat(value1.read(), Matchers.equalTo(new Instant(2000))); + assertThat(value2.read(), Matchers.equalTo(null)); } @Test public void testMergeLatestWatermarkIntoSource() throws Exception { - WatermarkStateInternal value1 = + WatermarkHoldState value1 = underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); - WatermarkStateInternal value2 = + WatermarkHoldState value2 = underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR); - WatermarkStateInternal value3 = + WatermarkHoldState value3 = underTest.state(NAMESPACE_3, WATERMARK_LATEST_ADDR); value1.add(new Instant(3000)); @@ -357,8 +341,8 @@ public void testMergeLatestWatermarkIntoSource() throws Exception { StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value3, WINDOW_1); // Merging clears the old values and updates the result value. - assertThat(value3.get().read(), Matchers.equalTo(new Instant(5000))); - assertThat(value1.get().read(), Matchers.equalTo(null)); - assertThat(value2.get().read(), Matchers.equalTo(null)); + assertThat(value3.read(), Matchers.equalTo(new Instant(5000))); + assertThat(value1.read(), Matchers.equalTo(null)); + assertThat(value2.read(), Matchers.equalTo(null)); } } From 24288e7ba5be86d927cffaccbd4c768797f4361d Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 22 Feb 2016 20:25:49 -0800 Subject: [PATCH 195/751] Move some worker-and-example-only dependencies out of sdk Following the separation of the worker module, running $ mvn dependency:analyze -pl sdk yields [WARNING] Used undeclared dependencies found: [WARNING] com.google.code.findbugs:jsr305:jar:3.0.1:compile [WARNING] javax.xml.stream:stax-api:jar:1.0-2:compile [WARNING] com.google.http-client:google-http-client:jar:1.21.0:compile [WARNING] Unused declared dependencies found: [WARNING] org.eclipse.jetty:jetty-servlet:jar:9.2.10.v20150310:compile [WARNING] org.codehaus.woodstox:woodstox-core-asl:jar:4.1.2:compile [WARNING] org.eclipse.jetty:jetty-server:jar:9.2.10.v20150310:compile [WARNING] javax.servlet:javax.servlet-api:jar:3.1.0:compile [WARNING] org.tukaani:xz:jar:1.5:compile This change removes unused dependencies. The `xz` and `woodstox` dependencies are for optional features of AvroSource and XmlSource. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115300250 --- examples/pom.xml | 6 ++++++ .../main/resources/archetype-resources/pom.xml | 6 ++++++ sdk/pom.xml | 18 ------------------ worker/pom.xml | 18 ++++++++++++++++++ 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index adea4b1298..3900a23ba2 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -484,6 +484,12 @@ runtime + + javax.servlet + javax.servlet-api + 3.1.0 + + diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 85310878d7..bffa376f56 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -166,6 +166,12 @@ 18.0 + + javax.servlet + javax.servlet-api + 3.1.0 + + org.slf4j diff --git a/sdk/pom.xml b/sdk/pom.xml index 1d7458052c..e3744fd435 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -640,24 +640,6 @@ ${joda.version} - - org.eclipse.jetty - jetty-server - 9.2.10.v20150310 - - - - org.eclipse.jetty - jetty-servlet - 9.2.10.v20150310 - - - - javax.servlet - javax.servlet-api - 3.1.0 - - org.hamcrest From c0a814b89bcbcb3541591f7eccd7db5ada2b0a17 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 22 Feb 2016 21:01:59 -0800 Subject: [PATCH 196/751] Change visibility of FileBasedSource subclass methods and fix return types for existing subclasses. Limit createForSubrangeOfFile and createSingleFileReader to protected for FileBasedSource and all of its subclasses. Also change the return type for subclasses to return FileBasedSource and FileBasedReader instead of the specific types. Note that these methods were meant to be used only by the FileBasedSource/BlockBasedSource and not called by users but if they did, this change would be backwards incompatible because of the return type and visibility changes. This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115301831 --- .../java/com/google/cloud/dataflow/sdk/io/AvroSource.java | 4 ++-- .../com/google/cloud/dataflow/sdk/io/BlockBasedSource.java | 4 ++-- .../java/com/google/cloud/dataflow/sdk/io/XmlSource.java | 4 ++-- .../google/cloud/dataflow/sdk/io/FileBasedSourceTest.java | 5 +++-- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java index da8458c2f7..297663e96f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java @@ -242,7 +242,7 @@ public void validate() { } @Override - public AvroSource createForSubrangeOfFile(String fileName, long start, long end) { + public BlockBasedSource createForSubrangeOfFile(String fileName, long start, long end) { byte[] syncMarker = this.syncMarker; String codec = this.codec; String readSchemaString = this.readSchemaString; @@ -274,7 +274,7 @@ public AvroSource createForSubrangeOfFile(String fileName, long start, long e } @Override - public AvroReader createSingleFileReader(PipelineOptions options) { + protected BlockBasedReader createSingleFileReader(PipelineOptions options) { return new AvroReader(this); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java index 9ef4cdcf30..f4a9c7db07 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java @@ -81,14 +81,14 @@ public BlockBasedSource(String fileName, long minBundleSize, long startOffset, l * Creates a {@code BlockBasedSource} for the specified range in a single file. */ @Override - public abstract BlockBasedSource createForSubrangeOfFile( + protected abstract BlockBasedSource createForSubrangeOfFile( String fileName, long start, long end); /** * Creates a {@code BlockBasedReader}. */ @Override - public abstract BlockBasedReader createSingleFileReader(PipelineOptions options); + protected abstract BlockBasedReader createSingleFileReader(PipelineOptions options); /** * A {@code Block} represents a block of records that can be read. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java index 668361b7d9..d684d2216c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java @@ -183,13 +183,13 @@ private XmlSource(String fileOrPattern, long minBundleSize, long startOffset, lo } @Override - public FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { + protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { return new XmlSource( fileName, getMinBundleSize(), start, end, rootElement, recordElement, recordClass); } @Override - public FileBasedReader createSingleFileReader(PipelineOptions options) { + protected FileBasedReader createSingleFileReader(PipelineOptions options) { return new XMLReader(this); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java index d50c6a63b9..7cf4398393 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java @@ -112,12 +112,13 @@ public Coder getDefaultOutputCoder() { } @Override - public FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { + protected FileBasedSource createForSubrangeOfFile( + String fileName, long start, long end) { return new TestFileBasedSource(fileName, getMinBundleSize(), start, end, splitHeader); } @Override - public FileBasedReader createSingleFileReader(PipelineOptions options) { + protected FileBasedReader createSingleFileReader(PipelineOptions options) { if (splitHeader == null) { return new TestReader(this); } else { From 13a042aed7d01a126a1ff7ecb66e723474191fe0 Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 22 Feb 2016 21:17:40 -0800 Subject: [PATCH 197/751] Make TestPipeline slightly less DataflowPipelineRunner-centric ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115302769 --- .../dataflow/sdk/testing/TestPipeline.java | 69 +++++++++++-------- .../sdk/testing/TestPipelineTest.java | 18 +++-- 2 files changed, 53 insertions(+), 34 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java index 05b5bad135..a05a7785d9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java @@ -19,22 +19,23 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.PipelineResult; import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; +import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.common.base.Optional; import com.google.common.collect.Iterators; import com.fasterxml.jackson.databind.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.Iterator; +import javax.annotation.Nullable; + /** * A creator of test pipelines that can be used inside of tests that can be * configured to run locally or against the live service. @@ -67,7 +68,6 @@ */ public class TestPipeline extends Pipeline { private static final String PROPERTY_DATAFLOW_OPTIONS = "dataflowOptions"; - private static final Logger LOG = LoggerFactory.getLogger(TestPipeline.class); private static final ObjectMapper MAPPER = new ObjectMapper(); /** @@ -77,28 +77,22 @@ public class TestPipeline extends Pipeline { * {@link Pipeline#run} to execute the pipeline and check the tests. */ public static TestPipeline create() { - if (isIntegrationTest()) { - TestDataflowPipelineOptions options = getPipelineOptions(); - LOG.info("Using passed in options: " + options); - options.setStableUniqueNames(CheckEnabled.ERROR); - return new TestPipeline(TestDataflowPipelineRunner.fromOptions(options), options); - } else { - DirectPipelineRunner directRunner = DirectPipelineRunner.createForTest(); - directRunner.getPipelineOptions().setAppName(getAppName()); - directRunner.getPipelineOptions().setStableUniqueNames(CheckEnabled.ERROR); - return new TestPipeline(directRunner, directRunner.getPipelineOptions()); - } + return fromOptions(testingPipelineOptions()); + } + + public static TestPipeline fromOptions(PipelineOptions options) { + return new TestPipeline(PipelineRunner.fromOptions(options), options); } /** - * Returns whether this test is running on the Cloud Dataflow service as described - * in {@link TestPipeline}. + * Returns whether a {@link TestPipeline} supports dynamic work rebalancing, and thus tests + * of dynamic work rebalancing are expected to pass. */ - public static boolean isIntegrationTest() { - return Boolean.parseBoolean(System.getProperty("runIntegrationTestOnService")); + public boolean supportsDynamicWorkRebalancing() { + return getRunner() instanceof DataflowPipelineRunner; } - TestPipeline(PipelineRunner runner, PipelineOptions options) { + private TestPipeline(PipelineRunner runner, PipelineOptions options) { super(runner, options); } @@ -126,14 +120,28 @@ public String toString() { } /** - * Creates PipelineOptions for testing with a DataflowPipelineRunner. + * Creates {@link PipelineOptions} for testing. */ - public static TestDataflowPipelineOptions getPipelineOptions() { + public static PipelineOptions testingPipelineOptions() { try { - TestDataflowPipelineOptions options = PipelineOptionsFactory.fromArgs( - MAPPER.readValue(System.getProperty(PROPERTY_DATAFLOW_OPTIONS), String[].class)) - .as(TestDataflowPipelineOptions.class); - options.setAppName(getAppName()); + @Nullable String systemDataflowOptions = System.getProperty(PROPERTY_DATAFLOW_OPTIONS); + PipelineOptions options = + systemDataflowOptions == null + ? PipelineOptionsFactory.create() + : PipelineOptionsFactory.fromArgs( + MAPPER.readValue( + System.getProperty(PROPERTY_DATAFLOW_OPTIONS), String[].class)) + .as(PipelineOptions.class); + + options.as(ApplicationNameOptions.class).setAppName(getAppName()); + if (isIntegrationTest()) { + // TODO: adjust everyone's integration test frameworks to set the runner class via the + // pipeline options via PROPERTY_DATAFLOW_OPTIONS + options.setRunner(TestDataflowPipelineRunner.class); + } else { + options.as(GcpOptions.class).setGcpCredential(new TestCredential()); + } + options.setStableUniqueNames(CheckEnabled.ERROR); return options; } catch (IOException e) { throw new RuntimeException("Unable to instantiate test options from system property " @@ -141,6 +149,13 @@ public static TestDataflowPipelineOptions getPipelineOptions() { } } + /** + * Returns whether a {@link TestPipeline} should be treated as an integration test. + */ + private static boolean isIntegrationTest() { + return Boolean.parseBoolean(System.getProperty("runIntegrationTestOnService")); + } + /** Returns the class + method name of the test, or a default name. */ private static String getAppName() { Optional stackTraceElement = findCallersStackTrace(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java index d74ba6a27b..397920a1db 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java @@ -21,6 +21,10 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.options.GcpOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.fasterxml.jackson.databind.ObjectMapper; @@ -57,15 +61,17 @@ public void testCreationOfPipelineOptions() throws Exception { "--diskSizeGb=2" }); System.getProperties().put("dataflowOptions", stringOptions); - TestDataflowPipelineOptions options = TestPipeline.getPipelineOptions(); + DataflowPipelineOptions options = + TestPipeline.testingPipelineOptions().as(DataflowPipelineOptions.class); assertEquals(DataflowPipelineRunner.class, options.getRunner()); assertThat(options.getJobName(), startsWith("testpipelinetest0testcreationofpipelineoptions-")); - assertEquals("testProject", options.getProject()); + assertEquals("testProject", options.as(GcpOptions.class).getProject()); assertEquals("testApiRootUrl", options.getApiRootUrl()); assertEquals("testDataflowEndpoint", options.getDataflowEndpoint()); assertEquals("testTempLocation", options.getTempLocation()); assertEquals("testServiceAccountName", options.getServiceAccountName()); - assertEquals("testServiceAccountKeyfile", options.getServiceAccountKeyfile()); + assertEquals( + "testServiceAccountKeyfile", options.as(GcpOptions.class).getServiceAccountKeyfile()); assertEquals("testZone", options.getZone()); assertEquals(2, options.getDiskSizeGb()); } @@ -75,11 +81,9 @@ public void testCreationOfPipelineOptionsFromReallyVerboselyNamedTestCase() thro ObjectMapper mapper = new ObjectMapper(); String stringOptions = mapper.writeValueAsString(new String[]{}); System.getProperties().put("dataflowOptions", stringOptions); - TestDataflowPipelineOptions options = TestPipeline.getPipelineOptions(); - assertThat(options.getAppName(), startsWith( + PipelineOptions options = TestPipeline.testingPipelineOptions(); + assertThat(options.as(ApplicationNameOptions.class).getAppName(), startsWith( "TestPipelineTest-testCreationOfPipelineOptionsFromReallyVerboselyNamedTestCase")); - assertThat(options.getJobName(), startsWith( - "testpipelinetest0testcreationofpipelineoptionsfrom")); } @Test From 6b372ecb3dee573569dfbce415f45265eb3f6f67 Mon Sep 17 00:00:00 2001 From: klk Date: Mon, 22 Feb 2016 21:42:17 -0800 Subject: [PATCH 198/751] Add used-but-undeclared dependency on google-http-client Prior to this change, running $ mvn dependency:analyze -pl sdk yields [WARNING] Used undeclared dependencies found: [WARNING] com.google.code.findbugs:jsr305:jar:3.0.1:compile [WARNING] javax.xml.stream:stax-api:jar:1.0-2:compile [WARNING] com.google.http-client:google-http-client:jar:1.21.0:compile [WARNING] Unused declared dependencies found: [WARNING] org.codehaus.woodstox:woodstox-core-asl:jar:4.1.2:compile [WARNING] org.tukaani:xz:jar:1.5:compile This is accurate. Many classes depend on com.google.api.client.util from the google-http-client package. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115303825 --- sdk/pom.xml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sdk/pom.xml b/sdk/pom.xml index e3744fd435..bdbdd5f31c 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -517,6 +517,20 @@ + + com.google.http-client + google-http-client + ${google-clients.version} + + + + com.google.guava + guava-jdk5 + + + + com.google.http-client google-http-client-jackson2 From d7b5189c5708b48308060dd40d6f3ab073759d28 Mon Sep 17 00:00:00 2001 From: lcwik Date: Mon, 22 Feb 2016 23:59:46 -0800 Subject: [PATCH 199/751] Migrate TextIO.Write to a custom sink Note for user requested sharding limits to be supported, each pipeline runner must support applying those sharding limits. Google Cloud Dataflow supports sharding limits. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115310814 --- .../google/cloud/dataflow/sdk/io/TextIO.java | 187 +++++++++--------- .../sdk/runners/DataflowPipelineRunner.java | 108 +++++++++- .../runners/DataflowPipelineTranslator.java | 5 - .../runners/dataflow/TextIOTranslator.java | 91 --------- .../cloud/dataflow/sdk/io/TextIOTest.java | 22 --- .../runners/DataflowPipelineRunnerTest.java | 21 +- .../DataflowPipelineTranslatorTest.java | 4 +- .../sdk/runners/TransformTreeTest.java | 9 +- 8 files changed, 209 insertions(+), 238 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 0bb2861831..d342f250b2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -26,11 +26,9 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; +import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; @@ -39,10 +37,13 @@ import com.google.protobuf.ByteString; import java.io.IOException; +import java.io.OutputStream; import java.nio.ByteBuffer; +import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SeekableByteChannel; -import java.util.List; +import java.nio.channels.WritableByteChannel; +import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import java.util.regex.Pattern; @@ -66,7 +67,7 @@ * *

    See the following examples: * - *

     {@code
    + * 
    {@code
      * Pipeline p = ...;
      *
      * // A simple Read of a local file (only runs locally):
    @@ -79,7 +80,7 @@
      *     p.apply(TextIO.Read.named("ReadNumbers")
      *                        .from("gs://my_bucket/path/to/numbers-*.txt")
      *                        .withCoder(TextualIntegerCoder.of()));
    - * } 
    + * }
    * *

    To write a {@link PCollection} to one or more text files, use * {@link TextIO.Write}, specifying {@link TextIO.Write#to(String)} to specify @@ -94,7 +95,7 @@ * will be overwritten. * *

    For example: - *

     {@code
    + * 
    {@code
      * // A simple Write to a local file (only runs locally):
      * PCollection lines = ...;
      * lines.apply(TextIO.Write.to("/path/to/file.txt"));
    @@ -106,7 +107,7 @@
      *                           .to("gs://my_bucket/path/to/numbers")
      *                           .withSuffix(".txt")
      *                           .withCoder(TextualIntegerCoder.of()));
    - * } 
    + * }
    * *

    Permissions

    *

    When run using the {@link DirectPipelineRunner}, your pipeline can read and write text files @@ -477,9 +478,6 @@ public static class Bound extends PTransform, PDone> { /** Requested number of shards. 0 for automatic. */ private final int numShards; - /** Insert a shuffle before writing to decouple parallelism when numShards != 0. */ - private final boolean forceReshard; - /** The shard template of each file written, combined with prefix and suffix. */ private final String shardTemplate; @@ -487,17 +485,16 @@ public static class Bound extends PTransform, PDone> { private final boolean validate; Bound(Coder coder) { - this(null, null, "", coder, 0, true, ShardNameTemplate.INDEX_OF_MAX, true); + this(null, null, "", coder, 0, ShardNameTemplate.INDEX_OF_MAX, true); } private Bound(String name, String filenamePrefix, String filenameSuffix, Coder coder, - int numShards, boolean forceReshard, String shardTemplate, boolean validate) { + int numShards, String shardTemplate, boolean validate) { super(name); this.coder = coder; this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; this.numShards = numShards; - this.forceReshard = forceReshard; this.shardTemplate = shardTemplate; this.validate = validate; } @@ -510,7 +507,7 @@ private Bound(String name, String filenamePrefix, String filenameSuffix, Coder named(String name) { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, - forceReshard, shardTemplate, validate); + shardTemplate, validate); } /** @@ -523,7 +520,7 @@ public Bound named(String name) { */ public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -537,7 +534,7 @@ public Bound to(String filenamePrefix) { */ public Bound withSuffix(String nameExtension) { validateOutputComponent(nameExtension); - return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, shardTemplate, validate); } @@ -556,30 +553,8 @@ public Bound withSuffix(String nameExtension) { * @see ShardNameTemplate */ public Bound withNumShards(int numShards) { - return withNumShards(numShards, forceReshard); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that uses the provided shard count. - * - *

    Constraining the number of shards is likely to reduce - * the performance of a pipeline. If forceReshard is true, the output - * will be shuffled to obtain the desired sharding. If it is false, - * data will not be reshuffled, but parallelism of preceeding stages - * may be constrained. Setting this value is not recommended - * unless you require a specific number of output files. - * - *

    Does not modify this object. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - * @param forceReshard whether to force a reshard to obtain the desired sharding. - * @see ShardNameTemplate - */ - private Bound withNumShards(int numShards, boolean forceReshard) { Preconditions.checkArgument(numShards >= 0); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -592,7 +567,7 @@ private Bound withNumShards(int numShards, boolean forceReshard) { * @see ShardNameTemplate */ public Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -610,25 +585,7 @@ public Bound withShardNameTemplate(String shardTemplate) { *

    Does not modify this object. */ public Bound withoutSharding() { - return withoutSharding(forceReshard); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that forces a single file as output. - * - *

    Constraining the number of shards is likely to reduce - * the performance of a pipeline. Using this setting is not recommended - * unless you truly require a single output file. - * - *

    This is a shortcut for - * {@code .withNumShards(1, forceReshard).withShardNameTemplate("")} - * - *

    Does not modify this object. - */ - private Bound withoutSharding(boolean forceReshard) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, forceReshard, "", - validate); + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, "", validate); } /** @@ -640,7 +597,7 @@ private Bound withoutSharding(boolean forceReshard) { * @param the type of the elements of the input {@link PCollection} */ public Bound withCoder(Coder coder) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -655,7 +612,7 @@ public Bound withCoder(Coder coder) { *

    Does not modify this object. */ public Bound withoutValidation() { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, false); } @@ -665,14 +622,13 @@ public PDone apply(PCollection input) { throw new IllegalStateException( "need to set the filename prefix of a TextIO.Write transform"); } - if (numShards > 0 && forceReshard) { - // Reshard and re-apply a version of this write without resharding. - return input - .apply(new FileBasedSink.ReshardForWrite()) - .apply(withNumShards(numShards, false)); - } else { - return PDone.in(input.getPipeline()); - } + + // Note that custom sinks currently do not expose sharding controls. + // Thus pipeline runner writers need to individually add support internally to + // apply user requested sharding limits. + return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( + new TextSink<>( + filenamePrefix, filenameSuffix, shardTemplate, coder))); } /** @@ -710,17 +666,6 @@ public Coder getCoder() { public boolean needsValidation() { return validate; } - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateWriteHelper(transform, context); - } - }); - } } } @@ -978,24 +923,70 @@ private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOExcep } } - private static void evaluateWriteHelper( - Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { - List elems = context.getPCollection(context.getInput(transform)); - int numShards = transform.numShards; - if (numShards < 1) { - // System gets to choose. For direct mode, choose 1. - numShards = 1; + /** + * A {@link FileBasedSink} for text files. Produces text files with the new line separator + * {@code '\n'} represented in {@code UTF-8} format as the record separator. + * Each record (including the last) is terminated. + */ + @VisibleForTesting + static class TextSink extends FileBasedSink { + private final Coder coder; + + @VisibleForTesting + TextSink( + String baseOutputFilename, String extension, String fileNameTemplate, Coder coder) { + super(baseOutputFilename, extension, fileNameTemplate); + this.coder = coder; } - TextSink> writer = TextSink.createForDirectPipelineRunner( - transform.filenamePrefix, transform.getShardNameTemplate(), transform.filenameSuffix, - numShards, true, null, null, transform.coder); - try (Sink.SinkWriter> sink = writer.writer()) { - for (T elem : elems) { - sink.add(WindowedValue.valueInGlobalWindow(elem)); - } - } catch (IOException exn) { - throw new RuntimeException( - "unable to write to output file \"" + transform.filenamePrefix + "\"", exn); + + @Override + public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { + return new TextWriteOperation<>(this, coder); + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation + * FileBasedWriteOperation} for text files. + */ + private static class TextWriteOperation extends FileBasedWriteOperation { + private final Coder coder; + + private TextWriteOperation(TextSink sink, Coder coder) { + super(sink); + this.coder = coder; + } + + @Override + public FileBasedWriter createWriter(PipelineOptions options) throws Exception { + return new TextWriter<>(this, coder); + } + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} + * for text files. + */ + private static class TextWriter extends FileBasedWriter { + private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); + private final Coder coder; + private OutputStream out; + + public TextWriter(FileBasedWriteOperation writeOperation, Coder coder) { + super(writeOperation); + this.mimeType = MimeTypes.TEXT; + this.coder = coder; + } + + @Override + protected void prepareWrite(WritableByteChannel channel) throws Exception { + out = Channels.newOutputStream(channel); + } + + @Override + public void write(T value) throws Exception { + coder.encode(value, out, Context.OUTER); + out.write(NEWLINE); + } } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 5a57f7fc43..396d308c37 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -339,6 +339,7 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(Window.Bound.class, AssignWindows.class); builder.put(Write.Bound.class, BatchWrite.class); builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); + builder.put(TextIO.Write.Bound.class, BatchTextIOWrite.class); if (options.getExperiments() == null || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); @@ -1993,6 +1994,111 @@ public PDone apply(PCollection input) { } } + /** + * Specialized implementation which overrides + * {@link com.google.cloud.dataflow.sdk.io.TextIO.Write.Bound TextIO.Write.Bound} with + * a native sink instead of a custom sink as workaround until custom sinks + * have support for sharding controls. + */ + private static class BatchTextIOWrite extends PTransform, PDone> { + private final TextIO.Write.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchTextIOWrite(DataflowPipelineRunner runner, TextIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + if (transform.getNumShards() > 0) { + return input + .apply(new ReshardForWrite()) + .apply(new BatchTextIONativeWrite<>(transform)); + } else { + return transform.apply(input); + } + } + } + + /** + * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way + * to provide the native definition of the Text sink. + */ + private static class BatchTextIONativeWrite extends PTransform, PDone> { + private final TextIO.Write.Bound transform; + public BatchTextIONativeWrite(TextIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + return PDone.in(input.getPipeline()); + } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + BatchTextIONativeWrite.class, new BatchTextIONativeWriteTranslator()); + } + } + + /** + * TextIO.Write.Bound support code for the Dataflow backend when applying parallelism limits + * through user requested sharding limits. + */ + private static class BatchTextIONativeWriteTranslator + implements TransformTranslator> { + @SuppressWarnings("unchecked") + @Override + public void translate(@SuppressWarnings("rawtypes") BatchTextIONativeWrite transform, + TranslationContext context) { + translateWriteHelper(transform, transform.transform, context); + } + + private void translateWriteHelper( + BatchTextIONativeWrite transform, + TextIO.Write.Bound originalTransform, + TranslationContext context) { + // Note that the original transform can not be used during add step/add input + // and is only passed in to get properties from it. + + checkState(originalTransform.getNumShards() > 0, + "Native TextSink is expected to only be used when sharding controls are required."); + + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + + // TODO: drop this check when server supports alternative templates. + switch (originalTransform.getShardTemplate()) { + case ShardNameTemplate.INDEX_OF_MAX: + break; // supported by server + case "": + // Empty shard template allowed - forces single output. + Preconditions.checkArgument(originalTransform.getNumShards() <= 1, + "Num shards must be <= 1 when using an empty sharding template"); + break; + default: + throw new UnsupportedOperationException("Shard template " + + originalTransform.getShardTemplate() + + " not yet supported by Dataflow service"); + } + + // TODO: How do we want to specify format and + // format-specific properties? + context.addInput(PropertyNames.FORMAT, "text"); + context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); + context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, + originalTransform.getShardNameTemplate()); + context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); + context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); + context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); + context.addEncodingInput( + WindowedValue.getValueOnlyCoder(originalTransform.getCoder())); + + } + } + /** * Specialized implementation which overrides * {@link com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound AvroIO.Write.Bound} with @@ -2088,9 +2194,7 @@ private void translateWriteHelper( context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, originalTransform.getShardTemplate()); context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); - context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); - context.addEncodingInput( WindowedValue.getValueOnlyCoder( AvroCoder.of(originalTransform.getType(), originalTransform.getSchema()))); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 885260ebb2..22ec3bb5c4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -44,14 +44,12 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; -import com.google.cloud.dataflow.sdk.runners.dataflow.TextIOTranslator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -1037,9 +1035,6 @@ private void translateHelper( DataflowPipelineRunner.StreamingPubsubIOWrite.class, new PubsubIOTranslator.WriteTranslator()); - registerTransformTranslator( - TextIO.Write.Bound.class, new TextIOTranslator.WriteTranslator()); - registerTransformTranslator(Read.Bounded.class, new ReadTranslator()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java deleted file mode 100644 index d6c96c31bd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.util.PathValidator; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.common.base.Preconditions; - -/** - * TextIO transform support code for the Dataflow backend. - */ -public class TextIOTranslator { - /** - * Implements TextIO Write translation for the Dataflow backend. - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public static class WriteTranslator implements TransformTranslator { - @Override - public void translate( - TextIO.Write.Bound transform, - TranslationContext context) { - translateWriteHelper(transform, context); - } - - private void translateWriteHelper( - TextIO.Write.Bound transform, - TranslationContext context) { - if (context.getPipelineOptions().isStreaming()) { - throw new IllegalArgumentException("TextIO not supported in streaming mode."); - } - - PathValidator validator = context.getPipelineOptions().getPathValidator(); - String filenamePrefix = validator.validateOutputFilePrefixSupported( - transform.getFilenamePrefix()); - - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (transform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(transform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + transform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - // TODO: How do we want to specify format and - // format-specific properties? - context.addInput(PropertyNames.FORMAT, "text"); - context.addInput(PropertyNames.FILENAME_PREFIX, filenamePrefix); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, - transform.getShardNameTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, transform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, transform.needsValidation()); - - long numShards = transform.getNumShards(); - if (numShards > 0) { - context.addInput(PropertyNames.NUM_SHARDS, numShards); - } - - context.addEncodingInput( - WindowedValue.getValueOnlyCoder(transform.getCoder())); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 6ad81e4ea0..0a8e381108 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -263,28 +263,6 @@ public void testWriteEmptyInts() throws Exception { runTestWrite(NO_INTS_ARRAY, TextualIntegerCoder.of()); } - @Test - public void testWriteSharded() throws IOException { - File outFolder = tmpFolder.newFolder(); - String filename = outFolder.toPath().resolve("output").toString(); - - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(Arrays.asList(LINES_ARRAY)) - .withCoder(StringUtf8Coder.of())); - - input.apply(TextIO.Write.to(filename).withNumShards(2).withSuffix(".txt")); - - p.run(); - - String[] files = outFolder.list(); - - assertThat(Arrays.asList(files), - containsInAnyOrder("output-00000-of-00002.txt", - "output-00001-of-00002.txt")); - } - @Test public void testWriteNamed() { { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index c7175cb3b0..c5f2d3fe71 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -453,16 +453,12 @@ public void testNonGcsFilePathInReadFailure() throws IOException { @Test public void testNonGcsFilePathInWriteFailure() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); - p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")) - .apply(TextIO.Write.named("WriteMyNonGcsFile").to("/tmp/file")); + Pipeline p = buildDataflowPipeline(buildPipelineOptions()); + PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); - p.run(); - assertValidJob(jobCaptor.getValue()); + pc.apply(TextIO.Write.named("WriteMyNonGcsFile").to("/tmp/file")); } @Test @@ -482,17 +478,12 @@ public void testMultiSlashGcsFileReadPath() throws IOException { @Test public void testMultiSlashGcsFileWritePath() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); - p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")) - .apply(TextIO.Write.named("WriteInvalidGcsFile") - .to("gs://bucket/tmp//file")); + Pipeline p = buildDataflowPipeline(buildPipelineOptions()); + PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("consecutive slashes"); - p.run(); - assertValidJob(jobCaptor.getValue()); + pc.apply(TextIO.Write.named("WriteInvalidGcsFile").to("gs://bucket/tmp//file")); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index b9c94ad00b..72090a0866 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -403,7 +403,7 @@ public void testPredefinedAddStep() throws Exception { pipeline.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/in")) .apply(ParDo.of(new NoOpFn())) .apply(new EmbeddedTransform(predefinedStep.clone())) - .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/out")); + .apply(ParDo.of(new NoOpFn())); Job job = translator.translate( pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); @@ -456,7 +456,7 @@ private static Step createPredefinedStep() throws Exception { Job job = translator.translate( pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - assertEquals(3, job.getSteps().size()); + assertEquals(13, job.getSteps().size()); Step step = job.getSteps().get(1); assertEquals(stepName, getString(step.getProperties(), PropertyNames.USER_NAME)); return step; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java index f1b7cd7fd0..68e1db1a52 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java @@ -28,6 +28,7 @@ import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.io.Write; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; @@ -133,9 +134,12 @@ public void enterCompositeTransform(TransformTreeNode node) { assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); assertNotNull(node.getEnclosingNode()); assertTrue(node.isCompositeNode()); + } else if (transform instanceof Write.Bound) { + assertTrue(visited.add(TransformsSeen.WRITE)); + assertNotNull(node.getEnclosingNode()); + assertTrue(node.isCompositeNode()); } assertThat(transform, not(instanceOf(Read.Bounded.class))); - assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); } @Override @@ -151,10 +155,9 @@ public void visitTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); // Pick is a composite, should not be visited here. assertThat(transform, not(instanceOf(Sample.SampleAny.class))); + assertThat(transform, not(instanceOf(Write.Bound.class))); if (transform instanceof Read.Bounded) { assertTrue(visited.add(TransformsSeen.READ)); - } else if (transform instanceof TextIO.Write.Bound) { - assertTrue(visited.add(TransformsSeen.WRITE)); } } From 9f546efebc5c9307dd85e6eec79038285cffa12b Mon Sep 17 00:00:00 2001 From: lcwik Date: Tue, 23 Feb 2016 00:37:55 -0800 Subject: [PATCH 200/751] Move Google Cloud Dataflow native sinks to worker module This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115313244 --- .../dataflow/sdk/runners/worker/AvroSink.java | 135 -------- .../dataflow/sdk/runners/worker/TextSink.java | 291 ------------------ .../dataflow/sdk/util/common/worker/Sink.java | 64 ---- 3 files changed, 490 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java deleted file mode 100644 index b101a2b0fc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.ShardingWritableByteChannel; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.ValueOnlyWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.apache.avro.Schema; -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.io.DatumWriter; - -import java.io.IOException; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.util.ArrayList; -import java.util.Random; - -/** - * A sink that writes Avro files. - * - * @param the type of the elements written to the sink - */ -public class AvroSink extends Sink> { - - final String filenamePrefix; - final String shardFormat; - final String filenameSuffix; - final int shardCount; - final AvroCoder avroCoder; - final Schema schema; - - public AvroSink(String filename, ValueOnlyWindowedValueCoder coder) { - this(filename, "", "", 1, coder); - } - - public AvroSink(String filenamePrefix, String shardFormat, String filenameSuffix, int shardCount, - ValueOnlyWindowedValueCoder coder) { - if (!(coder.getValueCoder() instanceof AvroCoder)) { - throw new IllegalArgumentException(String.format( - "AvroSink requires an AvroCoder, not a %s", coder.getValueCoder().getClass())); - } - - this.filenamePrefix = filenamePrefix; - this.shardFormat = shardFormat; - this.filenameSuffix = filenameSuffix; - this.shardCount = shardCount; - this.avroCoder = (AvroCoder) coder.getValueCoder(); - this.schema = this.avroCoder.getSchema(); - } - - public SinkWriter> writer(DatumWriter datumWriter) throws IOException { - WritableByteChannel writer = IOChannelUtils.create( - filenamePrefix, shardFormat, filenameSuffix, shardCount, MimeTypes.BINARY); - - if (writer instanceof ShardingWritableByteChannel) { - return new AvroShardingFileWriter(datumWriter, (ShardingWritableByteChannel) writer); - } else { - return new AvroFileWriter(datumWriter, writer); - } - } - - @Override - public SinkWriter> writer() throws IOException { - return writer(avroCoder.createDatumWriter()); - } - - /** The SinkWriter for an AvroSink. */ - class AvroFileWriter implements SinkWriter> { - DataFileWriter fileWriter; - - public AvroFileWriter(DatumWriter datumWriter, WritableByteChannel outputChannel) - throws IOException { - fileWriter = new DataFileWriter<>(datumWriter); - fileWriter.create(schema, Channels.newOutputStream(outputChannel)); - } - - @Override - public long add(WindowedValue value) throws IOException { - fileWriter.append(value.getValue()); - // DataFileWriter doesn't support returning the length written. Use the - // coder instead. - return CoderUtils.encodeToByteArray(avroCoder, value.getValue()).length; - } - - @Override - public void close() throws IOException { - fileWriter.close(); - } - } - - /** The SinkWriter for an AvroSink, which supports sharding. */ - class AvroShardingFileWriter implements SinkWriter> { - private ArrayList fileWriters = new ArrayList<>(); - private final Random random = new Random(); - - public AvroShardingFileWriter( - DatumWriter datumWriter, ShardingWritableByteChannel outputChannel) throws IOException { - for (int i = 0; i < outputChannel.getNumShards(); i++) { - fileWriters.add(new AvroFileWriter(datumWriter, outputChannel.getChannel(i))); - } - } - - @Override - public long add(WindowedValue value) throws IOException { - return fileWriters.get(random.nextInt(fileWriters.size())).add(value); - } - - @Override - public void close() throws IOException { - for (AvroFileWriter fileWriter : fileWriters) { - fileWriter.close(); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java deleted file mode 100644 index f48183cc17..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.ShardingWritableByteChannel; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.nio.channels.WritableByteChannel; -import java.util.Random; - -import javax.annotation.Nullable; - -/** - * A sink that writes text files. - * - * @param the type of the elements written to the sink - */ -public class TextSink extends Sink { - - static final byte[] NEWLINE = getNewline(); - - private static byte[] getNewline() { - String newline = "\n"; - try { - return newline.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("UTF-8 not supported", e); - } - } - - final String namePrefix; - final String shardFormat; - final String nameSuffix; - final int shardCount; - final boolean appendTrailingNewlines; - final String header; - final String footer; - final Coder coder; - - /** - * For testing only. - * - *

    Used by simple tests that write to a single unsharded file. - */ - public static TextSink> createForTest( - String filename, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - return create(filename, - "", - "", - 1, - appendTrailingNewlines, - header, - footer, - WindowedValue.getValueOnlyCoder(coder)); - } - - /** - * For DirectPipelineRunner only. - * It wraps the coder with {@code WindowedValue.ValueOnlyCoder}. - */ - public static TextSink> createForDirectPipelineRunner( - String filenamePrefix, - String shardFormat, - String filenameSuffix, - int shardCount, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - return create(filenamePrefix, - shardFormat, - filenameSuffix, - shardCount, - appendTrailingNewlines, - header, - footer, - WindowedValue.getValueOnlyCoder(coder)); - } - - /** - * Constructs a new TextSink. - * - * @param filenamePrefix the prefix of output filenames. - * @param shardFormat the shard name template to use for output filenames. - * @param filenameSuffix the suffix of output filenames. - * @param shardCount the number of outupt shards to produce. - * @param appendTrailingNewlines true to append newlines to each output line. - * @param header text to place at the beginning of each output file. - * @param footer text to place at the end of each output file. - * @param coder the code used to encode elements for output. - */ - public static TextSink create(String filenamePrefix, - String shardFormat, - String filenameSuffix, - int shardCount, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - return new TextSink<>(filenamePrefix, - shardFormat, - filenameSuffix, - shardCount, - appendTrailingNewlines, - header, - footer, - coder); - } - - private TextSink(String filenamePrefix, - String shardFormat, - String filenameSuffix, - int shardCount, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - this.namePrefix = filenamePrefix; - this.shardFormat = shardFormat; - this.nameSuffix = filenameSuffix; - this.shardCount = shardCount; - this.appendTrailingNewlines = appendTrailingNewlines; - this.header = header; - this.footer = footer; - this.coder = coder; - } - - @Override - public SinkWriter writer() throws IOException { - String mimeType; - - if (!(coder instanceof WindowedValueCoder)) { - throw new IOException( - "Expected WindowedValueCoder for inputCoder, got: " - + coder.getClass().getName()); - } - Coder valueCoder = ((WindowedValueCoder) coder).getValueCoder(); - if (valueCoder.equals(StringUtf8Coder.of())) { - mimeType = MimeTypes.TEXT; - } else { - mimeType = MimeTypes.BINARY; - } - - WritableByteChannel writer = IOChannelUtils.create(namePrefix, shardFormat, - nameSuffix, shardCount, mimeType); - - if (writer instanceof ShardingWritableByteChannel) { - return new ShardingTextFileWriter((ShardingWritableByteChannel) writer); - } else { - return new TextFileWriter(writer); - } - } - - /** - * Abstract SinkWriter base class shared by sharded and unsharded Text - * writer implementations. - */ - abstract class AbstractTextFileWriter implements SinkWriter { - protected void init() throws IOException { - if (header != null) { - printLine(ShardingWritableByteChannel.ALL_SHARDS, - CoderUtils.encodeToByteArray(StringUtf8Coder.of(), header)); - } - } - - /** - * Adds a value to the sink. Returns the size in bytes of the data written. - * The return value does -not- include header/footer size. - */ - @Override - public long add(T value) throws IOException { - return printLine(getShardNum(value), - CoderUtils.encodeToByteArray(coder, value)); - } - - @Override - public void close() throws IOException { - if (footer != null) { - printLine(ShardingWritableByteChannel.ALL_SHARDS, - CoderUtils.encodeToByteArray(StringUtf8Coder.of(), footer)); - } - } - - protected long printLine(int shardNum, byte[] line) throws IOException { - long length = line.length; - write(shardNum, ByteBuffer.wrap(line)); - - if (appendTrailingNewlines) { - write(shardNum, ByteBuffer.wrap(NEWLINE)); - length += NEWLINE.length; - } - - return length; - } - - protected abstract void write(int shardNum, ByteBuffer buf) - throws IOException; - protected abstract int getShardNum(T value); - } - - /** An unsharded SinkWriter for a TextSink. */ - class TextFileWriter extends AbstractTextFileWriter { - private final WritableByteChannel outputChannel; - - TextFileWriter(WritableByteChannel outputChannel) throws IOException { - this.outputChannel = outputChannel; - init(); - } - - @Override - public void close() throws IOException { - try { - super.close(); - } finally { - outputChannel.close(); - } - } - - @Override - protected void write(int shardNum, ByteBuffer buf) throws IOException { - outputChannel.write(buf); - } - - @Override - protected int getShardNum(T value) { - return 0; - } - } - - /** A sharding SinkWriter for a TextSink. */ - class ShardingTextFileWriter extends AbstractTextFileWriter { - private final Random rng = new Random(); - private final int numShards; - private final ShardingWritableByteChannel outputChannel; - - // TODO: add support for user-defined sharding function. - ShardingTextFileWriter(ShardingWritableByteChannel outputChannel) - throws IOException { - this.outputChannel = outputChannel; - numShards = outputChannel.getNumShards(); - init(); - } - - @Override - public void close() throws IOException { - try { - super.close(); - } finally { - outputChannel.close(); - } - } - - @Override - protected void write(int shardNum, ByteBuffer buf) throws IOException { - outputChannel.writeToShard(shardNum, buf); - } - - @Override - protected int getShardNum(T value) { - return rng.nextInt(numShards); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java deleted file mode 100644 index b48d70b360..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; - -import java.io.IOException; - -/** - * Abstract base class for Sinks. - * - *

    A Sink is written to by getting a SinkWriter and adding values to - * it. - * - * @param the type of the elements written to the sink - */ -public abstract class Sink { - /** - * Returns a Writer that allows writing to this Sink. - */ - public abstract SinkWriter writer() throws IOException; - - /** - * Writes to a Sink. - */ - public interface SinkWriter extends AutoCloseable { - /** - * Adds a value to the sink. Returns the size in bytes of the data written. - */ - public long add(ElemT value) throws IOException; - - @Override - public void close() throws IOException; - } - - /** - * Returns whether this Sink can be restarted. - */ - public boolean supportsRestart() { - return false; - } - - /** - * The default state kind of all the states reported in this Sink. - * Defaults to {@link StateKind#USER}. - */ - protected StateKind getStateSamplerStateKind() { - return StateKind.USER; - } -} From 51068d1635f4bb3143412a7708852e21816a1d27 Mon Sep 17 00:00:00 2001 From: sgmc Date: Tue, 23 Feb 2016 09:29:49 -0800 Subject: [PATCH 201/751] Reverts "Move Google Cloud Dataflow native sinks to worker module" ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115349469 --- .../dataflow/sdk/runners/worker/AvroSink.java | 135 ++++++++ .../dataflow/sdk/runners/worker/TextSink.java | 291 ++++++++++++++++++ .../dataflow/sdk/util/common/worker/Sink.java | 64 ++++ 3 files changed, 490 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java new file mode 100644 index 0000000000..b101a2b0fc --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.coders.AvroCoder; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.cloud.dataflow.sdk.util.MimeTypes; +import com.google.cloud.dataflow.sdk.util.ShardingWritableByteChannel; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowedValue.ValueOnlyWindowedValueCoder; +import com.google.cloud.dataflow.sdk.util.common.worker.Sink; + +import org.apache.avro.Schema; +import org.apache.avro.file.DataFileWriter; +import org.apache.avro.io.DatumWriter; + +import java.io.IOException; +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; +import java.util.ArrayList; +import java.util.Random; + +/** + * A sink that writes Avro files. + * + * @param the type of the elements written to the sink + */ +public class AvroSink extends Sink> { + + final String filenamePrefix; + final String shardFormat; + final String filenameSuffix; + final int shardCount; + final AvroCoder avroCoder; + final Schema schema; + + public AvroSink(String filename, ValueOnlyWindowedValueCoder coder) { + this(filename, "", "", 1, coder); + } + + public AvroSink(String filenamePrefix, String shardFormat, String filenameSuffix, int shardCount, + ValueOnlyWindowedValueCoder coder) { + if (!(coder.getValueCoder() instanceof AvroCoder)) { + throw new IllegalArgumentException(String.format( + "AvroSink requires an AvroCoder, not a %s", coder.getValueCoder().getClass())); + } + + this.filenamePrefix = filenamePrefix; + this.shardFormat = shardFormat; + this.filenameSuffix = filenameSuffix; + this.shardCount = shardCount; + this.avroCoder = (AvroCoder) coder.getValueCoder(); + this.schema = this.avroCoder.getSchema(); + } + + public SinkWriter> writer(DatumWriter datumWriter) throws IOException { + WritableByteChannel writer = IOChannelUtils.create( + filenamePrefix, shardFormat, filenameSuffix, shardCount, MimeTypes.BINARY); + + if (writer instanceof ShardingWritableByteChannel) { + return new AvroShardingFileWriter(datumWriter, (ShardingWritableByteChannel) writer); + } else { + return new AvroFileWriter(datumWriter, writer); + } + } + + @Override + public SinkWriter> writer() throws IOException { + return writer(avroCoder.createDatumWriter()); + } + + /** The SinkWriter for an AvroSink. */ + class AvroFileWriter implements SinkWriter> { + DataFileWriter fileWriter; + + public AvroFileWriter(DatumWriter datumWriter, WritableByteChannel outputChannel) + throws IOException { + fileWriter = new DataFileWriter<>(datumWriter); + fileWriter.create(schema, Channels.newOutputStream(outputChannel)); + } + + @Override + public long add(WindowedValue value) throws IOException { + fileWriter.append(value.getValue()); + // DataFileWriter doesn't support returning the length written. Use the + // coder instead. + return CoderUtils.encodeToByteArray(avroCoder, value.getValue()).length; + } + + @Override + public void close() throws IOException { + fileWriter.close(); + } + } + + /** The SinkWriter for an AvroSink, which supports sharding. */ + class AvroShardingFileWriter implements SinkWriter> { + private ArrayList fileWriters = new ArrayList<>(); + private final Random random = new Random(); + + public AvroShardingFileWriter( + DatumWriter datumWriter, ShardingWritableByteChannel outputChannel) throws IOException { + for (int i = 0; i < outputChannel.getNumShards(); i++) { + fileWriters.add(new AvroFileWriter(datumWriter, outputChannel.getChannel(i))); + } + } + + @Override + public long add(WindowedValue value) throws IOException { + return fileWriters.get(random.nextInt(fileWriters.size())).add(value); + } + + @Override + public void close() throws IOException { + for (AvroFileWriter fileWriter : fileWriters) { + fileWriter.close(); + } + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java new file mode 100644 index 0000000000..f48183cc17 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java @@ -0,0 +1,291 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.cloud.dataflow.sdk.util.MimeTypes; +import com.google.cloud.dataflow.sdk.util.ShardingWritableByteChannel; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; +import com.google.cloud.dataflow.sdk.util.common.worker.Sink; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.channels.WritableByteChannel; +import java.util.Random; + +import javax.annotation.Nullable; + +/** + * A sink that writes text files. + * + * @param the type of the elements written to the sink + */ +public class TextSink extends Sink { + + static final byte[] NEWLINE = getNewline(); + + private static byte[] getNewline() { + String newline = "\n"; + try { + return newline.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("UTF-8 not supported", e); + } + } + + final String namePrefix; + final String shardFormat; + final String nameSuffix; + final int shardCount; + final boolean appendTrailingNewlines; + final String header; + final String footer; + final Coder coder; + + /** + * For testing only. + * + *

    Used by simple tests that write to a single unsharded file. + */ + public static TextSink> createForTest( + String filename, + boolean appendTrailingNewlines, + @Nullable String header, + @Nullable String footer, + Coder coder) { + return create(filename, + "", + "", + 1, + appendTrailingNewlines, + header, + footer, + WindowedValue.getValueOnlyCoder(coder)); + } + + /** + * For DirectPipelineRunner only. + * It wraps the coder with {@code WindowedValue.ValueOnlyCoder}. + */ + public static TextSink> createForDirectPipelineRunner( + String filenamePrefix, + String shardFormat, + String filenameSuffix, + int shardCount, + boolean appendTrailingNewlines, + @Nullable String header, + @Nullable String footer, + Coder coder) { + return create(filenamePrefix, + shardFormat, + filenameSuffix, + shardCount, + appendTrailingNewlines, + header, + footer, + WindowedValue.getValueOnlyCoder(coder)); + } + + /** + * Constructs a new TextSink. + * + * @param filenamePrefix the prefix of output filenames. + * @param shardFormat the shard name template to use for output filenames. + * @param filenameSuffix the suffix of output filenames. + * @param shardCount the number of outupt shards to produce. + * @param appendTrailingNewlines true to append newlines to each output line. + * @param header text to place at the beginning of each output file. + * @param footer text to place at the end of each output file. + * @param coder the code used to encode elements for output. + */ + public static TextSink create(String filenamePrefix, + String shardFormat, + String filenameSuffix, + int shardCount, + boolean appendTrailingNewlines, + @Nullable String header, + @Nullable String footer, + Coder coder) { + return new TextSink<>(filenamePrefix, + shardFormat, + filenameSuffix, + shardCount, + appendTrailingNewlines, + header, + footer, + coder); + } + + private TextSink(String filenamePrefix, + String shardFormat, + String filenameSuffix, + int shardCount, + boolean appendTrailingNewlines, + @Nullable String header, + @Nullable String footer, + Coder coder) { + this.namePrefix = filenamePrefix; + this.shardFormat = shardFormat; + this.nameSuffix = filenameSuffix; + this.shardCount = shardCount; + this.appendTrailingNewlines = appendTrailingNewlines; + this.header = header; + this.footer = footer; + this.coder = coder; + } + + @Override + public SinkWriter writer() throws IOException { + String mimeType; + + if (!(coder instanceof WindowedValueCoder)) { + throw new IOException( + "Expected WindowedValueCoder for inputCoder, got: " + + coder.getClass().getName()); + } + Coder valueCoder = ((WindowedValueCoder) coder).getValueCoder(); + if (valueCoder.equals(StringUtf8Coder.of())) { + mimeType = MimeTypes.TEXT; + } else { + mimeType = MimeTypes.BINARY; + } + + WritableByteChannel writer = IOChannelUtils.create(namePrefix, shardFormat, + nameSuffix, shardCount, mimeType); + + if (writer instanceof ShardingWritableByteChannel) { + return new ShardingTextFileWriter((ShardingWritableByteChannel) writer); + } else { + return new TextFileWriter(writer); + } + } + + /** + * Abstract SinkWriter base class shared by sharded and unsharded Text + * writer implementations. + */ + abstract class AbstractTextFileWriter implements SinkWriter { + protected void init() throws IOException { + if (header != null) { + printLine(ShardingWritableByteChannel.ALL_SHARDS, + CoderUtils.encodeToByteArray(StringUtf8Coder.of(), header)); + } + } + + /** + * Adds a value to the sink. Returns the size in bytes of the data written. + * The return value does -not- include header/footer size. + */ + @Override + public long add(T value) throws IOException { + return printLine(getShardNum(value), + CoderUtils.encodeToByteArray(coder, value)); + } + + @Override + public void close() throws IOException { + if (footer != null) { + printLine(ShardingWritableByteChannel.ALL_SHARDS, + CoderUtils.encodeToByteArray(StringUtf8Coder.of(), footer)); + } + } + + protected long printLine(int shardNum, byte[] line) throws IOException { + long length = line.length; + write(shardNum, ByteBuffer.wrap(line)); + + if (appendTrailingNewlines) { + write(shardNum, ByteBuffer.wrap(NEWLINE)); + length += NEWLINE.length; + } + + return length; + } + + protected abstract void write(int shardNum, ByteBuffer buf) + throws IOException; + protected abstract int getShardNum(T value); + } + + /** An unsharded SinkWriter for a TextSink. */ + class TextFileWriter extends AbstractTextFileWriter { + private final WritableByteChannel outputChannel; + + TextFileWriter(WritableByteChannel outputChannel) throws IOException { + this.outputChannel = outputChannel; + init(); + } + + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + outputChannel.close(); + } + } + + @Override + protected void write(int shardNum, ByteBuffer buf) throws IOException { + outputChannel.write(buf); + } + + @Override + protected int getShardNum(T value) { + return 0; + } + } + + /** A sharding SinkWriter for a TextSink. */ + class ShardingTextFileWriter extends AbstractTextFileWriter { + private final Random rng = new Random(); + private final int numShards; + private final ShardingWritableByteChannel outputChannel; + + // TODO: add support for user-defined sharding function. + ShardingTextFileWriter(ShardingWritableByteChannel outputChannel) + throws IOException { + this.outputChannel = outputChannel; + numShards = outputChannel.getNumShards(); + init(); + } + + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + outputChannel.close(); + } + } + + @Override + protected void write(int shardNum, ByteBuffer buf) throws IOException { + outputChannel.writeToShard(shardNum, buf); + } + + @Override + protected int getShardNum(T value) { + return rng.nextInt(numShards); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java new file mode 100644 index 0000000000..b48d70b360 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; + +import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; + +import java.io.IOException; + +/** + * Abstract base class for Sinks. + * + *

    A Sink is written to by getting a SinkWriter and adding values to + * it. + * + * @param the type of the elements written to the sink + */ +public abstract class Sink { + /** + * Returns a Writer that allows writing to this Sink. + */ + public abstract SinkWriter writer() throws IOException; + + /** + * Writes to a Sink. + */ + public interface SinkWriter extends AutoCloseable { + /** + * Adds a value to the sink. Returns the size in bytes of the data written. + */ + public long add(ElemT value) throws IOException; + + @Override + public void close() throws IOException; + } + + /** + * Returns whether this Sink can be restarted. + */ + public boolean supportsRestart() { + return false; + } + + /** + * The default state kind of all the states reported in this Sink. + * Defaults to {@link StateKind#USER}. + */ + protected StateKind getStateSamplerStateKind() { + return StateKind.USER; + } +} From 45f5951a0a697b7044f15cd09418854641c9e98a Mon Sep 17 00:00:00 2001 From: bchambers Date: Tue, 23 Feb 2016 09:43:54 -0800 Subject: [PATCH 202/751] Add the slf4j-jdk bridge to the integration tests ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115350827 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7d0cba9e1d..9ff5cd218e 100644 --- a/pom.xml +++ b/pom.xml @@ -159,7 +159,7 @@ org.codehaus.mojo exec-maven-plugin - 1.1 + 1.4.0 verify From 3904c9074e66733686285d09ce5068d28f303dd8 Mon Sep 17 00:00:00 2001 From: sgmc Date: Tue, 23 Feb 2016 09:53:38 -0800 Subject: [PATCH 203/751] Revert "Migrate TextIO.Write to a custom sink" ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115351833 --- .../google/cloud/dataflow/sdk/io/TextIO.java | 187 +++++++++--------- .../sdk/runners/DataflowPipelineRunner.java | 108 +--------- .../runners/DataflowPipelineTranslator.java | 5 + .../runners/dataflow/TextIOTranslator.java | 91 +++++++++ .../cloud/dataflow/sdk/io/TextIOTest.java | 22 +++ .../runners/DataflowPipelineRunnerTest.java | 21 +- .../DataflowPipelineTranslatorTest.java | 4 +- .../sdk/runners/TransformTreeTest.java | 9 +- 8 files changed, 238 insertions(+), 209 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index d342f250b2..0bb2861831 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -26,9 +26,11 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; @@ -37,13 +39,10 @@ import com.google.protobuf.ByteString; import java.io.IOException; -import java.io.OutputStream; import java.nio.ByteBuffer; -import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SeekableByteChannel; -import java.nio.channels.WritableByteChannel; -import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Pattern; @@ -67,7 +66,7 @@ * *

    See the following examples: * - *

    {@code
    + * 
     {@code
      * Pipeline p = ...;
      *
      * // A simple Read of a local file (only runs locally):
    @@ -80,7 +79,7 @@
      *     p.apply(TextIO.Read.named("ReadNumbers")
      *                        .from("gs://my_bucket/path/to/numbers-*.txt")
      *                        .withCoder(TextualIntegerCoder.of()));
    - * }
    + * }
    * *

    To write a {@link PCollection} to one or more text files, use * {@link TextIO.Write}, specifying {@link TextIO.Write#to(String)} to specify @@ -95,7 +94,7 @@ * will be overwritten. * *

    For example: - *

    {@code
    + * 
     {@code
      * // A simple Write to a local file (only runs locally):
      * PCollection lines = ...;
      * lines.apply(TextIO.Write.to("/path/to/file.txt"));
    @@ -107,7 +106,7 @@
      *                           .to("gs://my_bucket/path/to/numbers")
      *                           .withSuffix(".txt")
      *                           .withCoder(TextualIntegerCoder.of()));
    - * }
    + * }
    * *

    Permissions

    *

    When run using the {@link DirectPipelineRunner}, your pipeline can read and write text files @@ -478,6 +477,9 @@ public static class Bound extends PTransform, PDone> { /** Requested number of shards. 0 for automatic. */ private final int numShards; + /** Insert a shuffle before writing to decouple parallelism when numShards != 0. */ + private final boolean forceReshard; + /** The shard template of each file written, combined with prefix and suffix. */ private final String shardTemplate; @@ -485,16 +487,17 @@ public static class Bound extends PTransform, PDone> { private final boolean validate; Bound(Coder coder) { - this(null, null, "", coder, 0, ShardNameTemplate.INDEX_OF_MAX, true); + this(null, null, "", coder, 0, true, ShardNameTemplate.INDEX_OF_MAX, true); } private Bound(String name, String filenamePrefix, String filenameSuffix, Coder coder, - int numShards, String shardTemplate, boolean validate) { + int numShards, boolean forceReshard, String shardTemplate, boolean validate) { super(name); this.coder = coder; this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; this.numShards = numShards; + this.forceReshard = forceReshard; this.shardTemplate = shardTemplate; this.validate = validate; } @@ -507,7 +510,7 @@ private Bound(String name, String filenamePrefix, String filenameSuffix, Coder named(String name) { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, - shardTemplate, validate); + forceReshard, shardTemplate, validate); } /** @@ -520,7 +523,7 @@ public Bound named(String name) { */ public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, shardTemplate, validate); } @@ -534,7 +537,7 @@ public Bound to(String filenamePrefix) { */ public Bound withSuffix(String nameExtension) { validateOutputComponent(nameExtension); - return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, + return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, forceReshard, shardTemplate, validate); } @@ -553,8 +556,30 @@ public Bound withSuffix(String nameExtension) { * @see ShardNameTemplate */ public Bound withNumShards(int numShards) { + return withNumShards(numShards, forceReshard); + } + + /** + * Returns a transform for writing to text files that's like this one but + * that uses the provided shard count. + * + *

    Constraining the number of shards is likely to reduce + * the performance of a pipeline. If forceReshard is true, the output + * will be shuffled to obtain the desired sharding. If it is false, + * data will not be reshuffled, but parallelism of preceeding stages + * may be constrained. Setting this value is not recommended + * unless you require a specific number of output files. + * + *

    Does not modify this object. + * + * @param numShards the number of shards to use, or 0 to let the system + * decide. + * @param forceReshard whether to force a reshard to obtain the desired sharding. + * @see ShardNameTemplate + */ + private Bound withNumShards(int numShards, boolean forceReshard) { Preconditions.checkArgument(numShards >= 0); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, shardTemplate, validate); } @@ -567,7 +592,7 @@ public Bound withNumShards(int numShards) { * @see ShardNameTemplate */ public Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, shardTemplate, validate); } @@ -585,7 +610,25 @@ public Bound withShardNameTemplate(String shardTemplate) { *

    Does not modify this object. */ public Bound withoutSharding() { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, "", validate); + return withoutSharding(forceReshard); + } + + /** + * Returns a transform for writing to text files that's like this one but + * that forces a single file as output. + * + *

    Constraining the number of shards is likely to reduce + * the performance of a pipeline. Using this setting is not recommended + * unless you truly require a single output file. + * + *

    This is a shortcut for + * {@code .withNumShards(1, forceReshard).withShardNameTemplate("")} + * + *

    Does not modify this object. + */ + private Bound withoutSharding(boolean forceReshard) { + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, forceReshard, "", + validate); } /** @@ -597,7 +640,7 @@ public Bound withoutSharding() { * @param the type of the elements of the input {@link PCollection} */ public Bound withCoder(Coder coder) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, shardTemplate, validate); } @@ -612,7 +655,7 @@ public Bound withCoder(Coder coder) { *

    Does not modify this object. */ public Bound withoutValidation() { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, shardTemplate, false); } @@ -622,13 +665,14 @@ public PDone apply(PCollection input) { throw new IllegalStateException( "need to set the filename prefix of a TextIO.Write transform"); } - - // Note that custom sinks currently do not expose sharding controls. - // Thus pipeline runner writers need to individually add support internally to - // apply user requested sharding limits. - return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( - new TextSink<>( - filenamePrefix, filenameSuffix, shardTemplate, coder))); + if (numShards > 0 && forceReshard) { + // Reshard and re-apply a version of this write without resharding. + return input + .apply(new FileBasedSink.ReshardForWrite()) + .apply(withNumShards(numShards, false)); + } else { + return PDone.in(input.getPipeline()); + } } /** @@ -666,6 +710,17 @@ public Coder getCoder() { public boolean needsValidation() { return validate; } + + static { + DirectPipelineRunner.registerDefaultTransformEvaluator( + Bound.class, new DirectPipelineRunner.TransformEvaluator() { + @Override + public void evaluate( + Bound transform, DirectPipelineRunner.EvaluationContext context) { + evaluateWriteHelper(transform, context); + } + }); + } } } @@ -923,70 +978,24 @@ private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOExcep } } - /** - * A {@link FileBasedSink} for text files. Produces text files with the new line separator - * {@code '\n'} represented in {@code UTF-8} format as the record separator. - * Each record (including the last) is terminated. - */ - @VisibleForTesting - static class TextSink extends FileBasedSink { - private final Coder coder; - - @VisibleForTesting - TextSink( - String baseOutputFilename, String extension, String fileNameTemplate, Coder coder) { - super(baseOutputFilename, extension, fileNameTemplate); - this.coder = coder; + private static void evaluateWriteHelper( + Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { + List elems = context.getPCollection(context.getInput(transform)); + int numShards = transform.numShards; + if (numShards < 1) { + // System gets to choose. For direct mode, choose 1. + numShards = 1; } - - @Override - public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { - return new TextWriteOperation<>(this, coder); - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation - * FileBasedWriteOperation} for text files. - */ - private static class TextWriteOperation extends FileBasedWriteOperation { - private final Coder coder; - - private TextWriteOperation(TextSink sink, Coder coder) { - super(sink); - this.coder = coder; - } - - @Override - public FileBasedWriter createWriter(PipelineOptions options) throws Exception { - return new TextWriter<>(this, coder); - } - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} - * for text files. - */ - private static class TextWriter extends FileBasedWriter { - private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); - private final Coder coder; - private OutputStream out; - - public TextWriter(FileBasedWriteOperation writeOperation, Coder coder) { - super(writeOperation); - this.mimeType = MimeTypes.TEXT; - this.coder = coder; - } - - @Override - protected void prepareWrite(WritableByteChannel channel) throws Exception { - out = Channels.newOutputStream(channel); - } - - @Override - public void write(T value) throws Exception { - coder.encode(value, out, Context.OUTER); - out.write(NEWLINE); - } + TextSink> writer = TextSink.createForDirectPipelineRunner( + transform.filenamePrefix, transform.getShardNameTemplate(), transform.filenameSuffix, + numShards, true, null, null, transform.coder); + try (Sink.SinkWriter> sink = writer.writer()) { + for (T elem : elems) { + sink.add(WindowedValue.valueInGlobalWindow(elem)); + } + } catch (IOException exn) { + throw new RuntimeException( + "unable to write to output file \"" + transform.filenamePrefix + "\"", exn); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 396d308c37..5a57f7fc43 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -339,7 +339,6 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(Window.Bound.class, AssignWindows.class); builder.put(Write.Bound.class, BatchWrite.class); builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); - builder.put(TextIO.Write.Bound.class, BatchTextIOWrite.class); if (options.getExperiments() == null || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); @@ -1994,111 +1993,6 @@ public PDone apply(PCollection input) { } } - /** - * Specialized implementation which overrides - * {@link com.google.cloud.dataflow.sdk.io.TextIO.Write.Bound TextIO.Write.Bound} with - * a native sink instead of a custom sink as workaround until custom sinks - * have support for sharding controls. - */ - private static class BatchTextIOWrite extends PTransform, PDone> { - private final TextIO.Write.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchTextIOWrite(DataflowPipelineRunner runner, TextIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - if (transform.getNumShards() > 0) { - return input - .apply(new ReshardForWrite()) - .apply(new BatchTextIONativeWrite<>(transform)); - } else { - return transform.apply(input); - } - } - } - - /** - * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way - * to provide the native definition of the Text sink. - */ - private static class BatchTextIONativeWrite extends PTransform, PDone> { - private final TextIO.Write.Bound transform; - public BatchTextIONativeWrite(TextIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - return PDone.in(input.getPipeline()); - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - BatchTextIONativeWrite.class, new BatchTextIONativeWriteTranslator()); - } - } - - /** - * TextIO.Write.Bound support code for the Dataflow backend when applying parallelism limits - * through user requested sharding limits. - */ - private static class BatchTextIONativeWriteTranslator - implements TransformTranslator> { - @SuppressWarnings("unchecked") - @Override - public void translate(@SuppressWarnings("rawtypes") BatchTextIONativeWrite transform, - TranslationContext context) { - translateWriteHelper(transform, transform.transform, context); - } - - private void translateWriteHelper( - BatchTextIONativeWrite transform, - TextIO.Write.Bound originalTransform, - TranslationContext context) { - // Note that the original transform can not be used during add step/add input - // and is only passed in to get properties from it. - - checkState(originalTransform.getNumShards() > 0, - "Native TextSink is expected to only be used when sharding controls are required."); - - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (originalTransform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(originalTransform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + originalTransform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - // TODO: How do we want to specify format and - // format-specific properties? - context.addInput(PropertyNames.FORMAT, "text"); - context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, - originalTransform.getShardNameTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); - context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); - context.addEncodingInput( - WindowedValue.getValueOnlyCoder(originalTransform.getCoder())); - - } - } - /** * Specialized implementation which overrides * {@link com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound AvroIO.Write.Bound} with @@ -2194,7 +2088,9 @@ private void translateWriteHelper( context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, originalTransform.getShardTemplate()); context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); + context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); + context.addEncodingInput( WindowedValue.getValueOnlyCoder( AvroCoder.of(originalTransform.getType(), originalTransform.getSchema()))); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 22ec3bb5c4..885260ebb2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -44,12 +44,14 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; +import com.google.cloud.dataflow.sdk.runners.dataflow.TextIOTranslator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -1035,6 +1037,9 @@ private void translateHelper( DataflowPipelineRunner.StreamingPubsubIOWrite.class, new PubsubIOTranslator.WriteTranslator()); + registerTransformTranslator( + TextIO.Write.Bound.class, new TextIOTranslator.WriteTranslator()); + registerTransformTranslator(Read.Bounded.class, new ReadTranslator()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java new file mode 100644 index 0000000000..d6c96c31bd --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; + +import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; +import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; +import com.google.cloud.dataflow.sdk.util.PathValidator; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.common.base.Preconditions; + +/** + * TextIO transform support code for the Dataflow backend. + */ +public class TextIOTranslator { + /** + * Implements TextIO Write translation for the Dataflow backend. + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static class WriteTranslator implements TransformTranslator { + @Override + public void translate( + TextIO.Write.Bound transform, + TranslationContext context) { + translateWriteHelper(transform, context); + } + + private void translateWriteHelper( + TextIO.Write.Bound transform, + TranslationContext context) { + if (context.getPipelineOptions().isStreaming()) { + throw new IllegalArgumentException("TextIO not supported in streaming mode."); + } + + PathValidator validator = context.getPipelineOptions().getPathValidator(); + String filenamePrefix = validator.validateOutputFilePrefixSupported( + transform.getFilenamePrefix()); + + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + + // TODO: drop this check when server supports alternative templates. + switch (transform.getShardTemplate()) { + case ShardNameTemplate.INDEX_OF_MAX: + break; // supported by server + case "": + // Empty shard template allowed - forces single output. + Preconditions.checkArgument(transform.getNumShards() <= 1, + "Num shards must be <= 1 when using an empty sharding template"); + break; + default: + throw new UnsupportedOperationException("Shard template " + + transform.getShardTemplate() + + " not yet supported by Dataflow service"); + } + + // TODO: How do we want to specify format and + // format-specific properties? + context.addInput(PropertyNames.FORMAT, "text"); + context.addInput(PropertyNames.FILENAME_PREFIX, filenamePrefix); + context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, + transform.getShardNameTemplate()); + context.addInput(PropertyNames.FILENAME_SUFFIX, transform.getFilenameSuffix()); + context.addInput(PropertyNames.VALIDATE_SINK, transform.needsValidation()); + + long numShards = transform.getNumShards(); + if (numShards > 0) { + context.addInput(PropertyNames.NUM_SHARDS, numShards); + } + + context.addEncodingInput( + WindowedValue.getValueOnlyCoder(transform.getCoder())); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 0a8e381108..6ad81e4ea0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -263,6 +263,28 @@ public void testWriteEmptyInts() throws Exception { runTestWrite(NO_INTS_ARRAY, TextualIntegerCoder.of()); } + @Test + public void testWriteSharded() throws IOException { + File outFolder = tmpFolder.newFolder(); + String filename = outFolder.toPath().resolve("output").toString(); + + Pipeline p = TestPipeline.create(); + + PCollection input = + p.apply(Create.of(Arrays.asList(LINES_ARRAY)) + .withCoder(StringUtf8Coder.of())); + + input.apply(TextIO.Write.to(filename).withNumShards(2).withSuffix(".txt")); + + p.run(); + + String[] files = outFolder.list(); + + assertThat(Arrays.asList(files), + containsInAnyOrder("output-00000-of-00002.txt", + "output-00001-of-00002.txt")); + } + @Test public void testWriteNamed() { { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index c5f2d3fe71..c7175cb3b0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -453,12 +453,16 @@ public void testNonGcsFilePathInReadFailure() throws IOException { @Test public void testNonGcsFilePathInWriteFailure() throws IOException { - Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + + Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); + p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")) + .apply(TextIO.Write.named("WriteMyNonGcsFile").to("/tmp/file")); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); - pc.apply(TextIO.Write.named("WriteMyNonGcsFile").to("/tmp/file")); + p.run(); + assertValidJob(jobCaptor.getValue()); } @Test @@ -478,12 +482,17 @@ public void testMultiSlashGcsFileReadPath() throws IOException { @Test public void testMultiSlashGcsFileWritePath() throws IOException { - Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + + Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); + p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")) + .apply(TextIO.Write.named("WriteInvalidGcsFile") + .to("gs://bucket/tmp//file")); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("consecutive slashes"); - pc.apply(TextIO.Write.named("WriteInvalidGcsFile").to("gs://bucket/tmp//file")); + p.run(); + assertValidJob(jobCaptor.getValue()); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 72090a0866..b9c94ad00b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -403,7 +403,7 @@ public void testPredefinedAddStep() throws Exception { pipeline.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/in")) .apply(ParDo.of(new NoOpFn())) .apply(new EmbeddedTransform(predefinedStep.clone())) - .apply(ParDo.of(new NoOpFn())); + .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/out")); Job job = translator.translate( pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); @@ -456,7 +456,7 @@ private static Step createPredefinedStep() throws Exception { Job job = translator.translate( pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - assertEquals(13, job.getSteps().size()); + assertEquals(3, job.getSteps().size()); Step step = job.getSteps().get(1); assertEquals(stepName, getString(step.getProperties(), PropertyNames.USER_NAME)); return step; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java index 68e1db1a52..f1b7cd7fd0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java @@ -28,7 +28,6 @@ import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.Write; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; @@ -134,12 +133,9 @@ public void enterCompositeTransform(TransformTreeNode node) { assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); assertNotNull(node.getEnclosingNode()); assertTrue(node.isCompositeNode()); - } else if (transform instanceof Write.Bound) { - assertTrue(visited.add(TransformsSeen.WRITE)); - assertNotNull(node.getEnclosingNode()); - assertTrue(node.isCompositeNode()); } assertThat(transform, not(instanceOf(Read.Bounded.class))); + assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); } @Override @@ -155,9 +151,10 @@ public void visitTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); // Pick is a composite, should not be visited here. assertThat(transform, not(instanceOf(Sample.SampleAny.class))); - assertThat(transform, not(instanceOf(Write.Bound.class))); if (transform instanceof Read.Bounded) { assertTrue(visited.add(TransformsSeen.READ)); + } else if (transform instanceof TextIO.Write.Bound) { + assertTrue(visited.add(TransformsSeen.WRITE)); } } From 635541a74438a02d18910fba6a76c5aacc2c7816 Mon Sep 17 00:00:00 2001 From: tgroh Date: Tue, 23 Feb 2016 10:12:17 -0800 Subject: [PATCH 204/751] Add KeyedWorkItemCoder ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115354168 --- .../dataflow/sdk/util/KeyedWorkItemCoder.java | 120 ++++++++++++++++++ .../dataflow/sdk/util/KeyedWorkItems.java | 29 ++++- .../sdk/util/KeyedWorkItemCoderTest.java | 61 +++++++++ 3 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java new file mode 100644 index 0000000000..398e82a8d6 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.IterableCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerDataCoder; +import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; +import com.google.common.collect.ImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; + +/** + * A {@link Coder} for {@link KeyedWorkItem KeyedWorkItems}. + */ +public class KeyedWorkItemCoder extends StandardCoder> { + /** + * Create a new {@link KeyedWorkItemCoder} with the provided key coder, element coder, and window + * coder. + */ + public static KeyedWorkItemCoder of( + Coder keyCoder, Coder elemCoder, Coder windowCoder) { + return new KeyedWorkItemCoder<>(keyCoder, elemCoder, windowCoder); + } + + @JsonCreator + public static KeyedWorkItemCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { + checkArgument(components.size() == 3, "Expecting 3 components, got %s", components.size()); + @SuppressWarnings("unchecked") + Coder keyCoder = (Coder) components.get(0); + @SuppressWarnings("unchecked") + Coder elemCoder = (Coder) components.get(1); + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) components.get(2); + return new KeyedWorkItemCoder<>(keyCoder, elemCoder, windowCoder); + } + + private final Coder keyCoder; + private final Coder elemCoder; + private final Coder windowCoder; + private final Coder> timersCoder; + private final Coder>> elemsCoder; + + private KeyedWorkItemCoder( + Coder keyCoder, Coder elemCoder, Coder windowCoder) { + this.keyCoder = keyCoder; + this.elemCoder = elemCoder; + this.windowCoder = windowCoder; + this.timersCoder = IterableCoder.of(TimerDataCoder.of(windowCoder)); + this.elemsCoder = IterableCoder.of(FullWindowedValueCoder.of(elemCoder, windowCoder)); + } + + @Override + public void encode(KeyedWorkItem value, OutputStream outStream, Coder.Context context) + throws CoderException, IOException { + Coder.Context nestedContext = context.nested(); + keyCoder.encode(value.key(), outStream, nestedContext); + timersCoder.encode(value.timersIterable(), outStream, nestedContext); + elemsCoder.encode(value.elementsIterable(), outStream, nestedContext); + } + + @Override + public KeyedWorkItem decode(InputStream inStream, Coder.Context context) + throws CoderException, IOException { + Coder.Context nestedContext = context.nested(); + K key = keyCoder.decode(inStream, nestedContext); + Iterable timers = timersCoder.decode(inStream, nestedContext); + Iterable> elems = elemsCoder.decode(inStream, nestedContext); + return KeyedWorkItems.workItem(key, timers, elems); + } + + @Override + public List> getCoderArguments() { + return ImmutableList.of(keyCoder, elemCoder, windowCoder); + } + + @Override + public void verifyDeterministic() throws Coder.NonDeterministicException { + keyCoder.verifyDeterministic(); + timersCoder.verifyDeterministic(); + elemsCoder.verifyDeterministic(); + } + + /** + * {@inheritDoc}. + * + * {@link KeyedWorkItemCoder} is not consistent with equals as it can return a + * {@link KeyedWorkItem} of a type different from the originally encoded type. + */ + @Override + public boolean consistentWithEquals() { + return false; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java index b94397c222..734bd2c537 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.util; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.common.base.MoreObjects; +import com.google.common.collect.Iterables; import java.util.Collections; +import java.util.Objects; /** * Static utility methods that provide {@link KeyedWorkItem} implementations. @@ -63,7 +66,6 @@ public static KeyedWorkItem workItem( * iterable. */ public static class ComposedKeyedWorkItem implements KeyedWorkItem { - private final K key; private final Iterable timers; private final Iterable> elements; @@ -89,5 +91,30 @@ public Iterable timersIterable() { public Iterable> elementsIterable() { return elements; } + + @Override + public boolean equals(Object other) { + if (other == null || !(other instanceof ComposedKeyedWorkItem)) { + return false; + } + KeyedWorkItem that = (KeyedWorkItem) other; + return Objects.equals(this.key, that.key()) + && Iterables.elementsEqual(this.timersIterable(), that.timersIterable()) + && Iterables.elementsEqual(this.elementsIterable(), that.elementsIterable()); + } + + @Override + public int hashCode() { + return Objects.hash(key, timers, elements); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(ComposedKeyedWorkItem.class) + .add("key", key) + .add("elements", elements) + .add("timers", timers) + .toString(); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java new file mode 100644 index 0000000000..e6cd454fbe --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; +import com.google.common.collect.ImmutableList; + +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link KeyedWorkItems}. + */ +@RunWith(JUnit4.class) +public class KeyedWorkItemCoderTest { + @Test + public void testCoderProperties() throws Exception { + CoderProperties.coderSerializable( + KeyedWorkItemCoder.of(StringUtf8Coder.of(), VarIntCoder.of(), GlobalWindow.Coder.INSTANCE)); + } + + @Test + public void testEncodeDecodeEqual() throws Exception { + Iterable timers = + ImmutableList.of( + TimerData.of(StateNamespaces.global(), new Instant(500L), TimeDomain.EVENT_TIME)); + Iterable> elements = + ImmutableList.of( + WindowedValue.valueInGlobalWindow(1), + WindowedValue.valueInGlobalWindow(4), + WindowedValue.valueInGlobalWindow(8)); + + KeyedWorkItemCoder coder = + KeyedWorkItemCoder.of(StringUtf8Coder.of(), VarIntCoder.of(), GlobalWindow.Coder.INSTANCE); + + CoderProperties.coderDecodeEncodeEqual(coder, KeyedWorkItems.workItem("foo", timers, elements)); + CoderProperties.coderDecodeEncodeEqual(coder, KeyedWorkItems.elementsWorkItem("foo", elements)); + CoderProperties.coderDecodeEncodeEqual( + coder, KeyedWorkItems.timersWorkItem("foo", timers)); + } +} From 2e89a4b3ddfd5d395aa8d6c4f73b501712b907a7 Mon Sep 17 00:00:00 2001 From: sgmc Date: Tue, 23 Feb 2016 10:21:54 -0800 Subject: [PATCH 205/751] Revert "Migrate AvroIO.Write to a custom sink" ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115355272 --- .../google/cloud/dataflow/sdk/io/AvroIO.java | 188 +++++++++--------- .../sdk/runners/DataflowPipelineRunner.java | 179 ----------------- .../runners/DataflowPipelineTranslator.java | 5 + .../runners/dataflow/AvroIOTranslator.java | 87 ++++++++ .../sdk/io/AvroIOGeneratedClassTest.java | 48 ++--- .../cloud/dataflow/sdk/io/AvroIOTest.java | 45 ----- 6 files changed, 215 insertions(+), 337 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java index 70420105c5..9ee7e6b13c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java @@ -22,25 +22,24 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.runners.worker.AvroSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.worker.Sink; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.avro.Schema; -import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.reflect.ReflectData; import java.io.IOException; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; +import java.util.List; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -318,7 +317,7 @@ public PCollection apply(PInput input) { : com.google.cloud.dataflow.sdk.io.Read.from( AvroSource.from(filepattern).withSchema(type)); - PCollection pcol = input.getPipeline().apply("Read", read); + PCollection pcol = input.getPipeline().apply(read); // Honor the default output coder that would have been used by this PTransform. pcol.setCoder(getDefaultOutputCoder()); return pcol; @@ -474,6 +473,8 @@ public static class Bound extends PTransform, PDone> { final int numShards; /** Shard template string. */ final String shardTemplate; + /** Insert a shuffle before writing to decouple parallelism when numShards != 0. */ + final boolean forceReshard; /** The class type of the records. */ final Class type; /** The schema of the output file. */ @@ -483,16 +484,18 @@ public static class Bound extends PTransform, PDone> { final boolean validate; Bound(Class type) { - this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, type, null, true); + this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, true, type, null, true); } Bound(String name, String filenamePrefix, String filenameSuffix, int numShards, - String shardTemplate, Class type, Schema schema, boolean validate) { + String shardTemplate, boolean forceReshard, Class type, Schema schema, + boolean validate) { super(name); this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; this.numShards = numShards; this.shardTemplate = shardTemplate; + this.forceReshard = forceReshard; this.type = type; this.schema = schema; this.validate = validate; @@ -506,7 +509,7 @@ public static class Bound extends PTransform, PDone> { */ public Bound named(String name) { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, schema, validate); } @@ -522,7 +525,7 @@ public Bound named(String name) { public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, schema, validate); } @@ -537,7 +540,7 @@ public Bound to(String filenamePrefix) { public Bound withSuffix(String filenameSuffix) { validateOutputComponent(filenameSuffix); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, schema, validate); } @@ -556,9 +559,31 @@ public Bound withSuffix(String filenameSuffix) { * @see ShardNameTemplate */ public Bound withNumShards(int numShards) { + return withNumShards(numShards, forceReshard); + } + + /** + * Returns a new {@link PTransform} that's like this one but + * that uses the provided shard count. + * + *

    Constraining the number of shards is likely to reduce + * the performance of a pipeline. If forceReshard is true, the output + * will be shuffled to obtain the desired sharding. If it is false, + * data will not be reshuffled, but parallelism of preceeding stages + * may be constrained. Setting this value is not recommended + * unless you require a specific number of output files. + * + *

    Does not modify this object. + * + * @param numShards the number of shards to use, or 0 to let the system + * decide. + * @param forceReshard whether to force a reshard to obtain the desired sharding. + * @see ShardNameTemplate + */ + private Bound withNumShards(int numShards, boolean forceReshard) { Preconditions.checkArgument(numShards >= 0); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, schema, validate); } @@ -572,7 +597,7 @@ public Bound withNumShards(int numShards) { */ public Bound withShardNameTemplate(String shardTemplate) { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, schema, validate); } @@ -586,7 +611,22 @@ public Bound withShardNameTemplate(String shardTemplate) { *

    Does not modify this object. */ public Bound withoutSharding() { - return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", + return withoutSharding(forceReshard); + } + + /** + * Returns a new {@link PTransform} that's like this one but + * that forces a single file as output. + * + *

    This is a shortcut for + * {@code .withNumShards(1, forceReshard).withShardNameTemplate("")} + * + *

    Does not modify this object. + * + * @param forceReshard whether to force a reshard to obtain the desired sharding. + */ + private Bound withoutSharding(boolean forceReshard) { + return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", forceReshard, type, schema, validate); } @@ -601,7 +641,7 @@ public Bound withoutSharding() { */ public Bound withSchema(Class type) { return new Bound<>(name, filenamePrefix, filenameSuffix, numShards, shardTemplate, - type, ReflectData.get().getSchema(type), validate); + forceReshard, type, ReflectData.get().getSchema(type), validate); } /** @@ -613,7 +653,7 @@ public Bound withSchema(Class type) { */ public Bound withSchema(Schema schema) { return new Bound<>(name, filenamePrefix, filenameSuffix, numShards, shardTemplate, - GenericRecord.class, schema, validate); + forceReshard, GenericRecord.class, schema, validate); } /** @@ -639,7 +679,7 @@ public Bound withSchema(String schema) { */ public Bound withoutValidation() { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, schema, false); } @@ -653,12 +693,14 @@ public PDone apply(PCollection input) { throw new IllegalStateException("need to set the schema of an AvroIO.Write transform"); } - // Note that custom sinks currently do not expose sharding controls. - // Thus pipeline runner writers need to individually add support internally to - // apply user requested sharding limits. - return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( - new AvroSink<>( - filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema)))); + if (numShards > 0 && forceReshard) { + // Reshard and re-apply a version of this write without resharding. + return input + .apply(new FileBasedSink.ReshardForWrite()) + .apply(withNumShards(numShards, false)); + } else { + return PDone.in(input.getPipeline()); + } } /** @@ -700,6 +742,21 @@ public Schema getSchema() { public boolean needsValidation() { return validate; } + + static { + @SuppressWarnings("rawtypes") + DirectPipelineRunner.TransformEvaluator transformEvaluator = + new DirectPipelineRunner.TransformEvaluator() { + @Override + @SuppressWarnings("unchecked") + public void evaluate( + Bound transform, DirectPipelineRunner.EvaluationContext context) { + evaluateWriteHelper(transform, context); + } + }; + DirectPipelineRunner.registerDefaultTransformEvaluator( + Bound.class, transformEvaluator); + } } /** Disallow construction of utility class. */ @@ -722,72 +779,25 @@ private static void validateOutputComponent(String partialFilePattern) { /** Disallow construction of utility class. */ private AvroIO() {} - /** - * A {@link FileBasedSink} for Avro files. - */ - @VisibleForTesting - static class AvroSink extends FileBasedSink { - private final AvroCoder coder; - - @VisibleForTesting - AvroSink( - String baseOutputFilename, String extension, String fileNameTemplate, AvroCoder coder) { - super(baseOutputFilename, extension, fileNameTemplate); - this.coder = coder; - } - - @Override - public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { - return new AvroWriteOperation<>(this, coder); - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation - * FileBasedWriteOperation} for Avro files. - */ - private static class AvroWriteOperation extends FileBasedWriteOperation { - private final AvroCoder coder; - - private AvroWriteOperation(AvroSink sink, AvroCoder coder) { - super(sink); - this.coder = coder; - } - - @Override - public FileBasedWriter createWriter(PipelineOptions options) throws Exception { - return new AvroWriter<>(this, coder); - } + private static void evaluateWriteHelper( + Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { + List> elems = + context.getPCollectionWindowedValues(context.getInput(transform)); + int numShards = transform.numShards; + if (numShards < 1) { + // System gets to choose. For direct mode, choose 1. + numShards = 1; } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} - * for Avro files. - */ - private static class AvroWriter extends FileBasedWriter { - private final AvroCoder coder; - private DataFileWriter dataFileWriter; - - public AvroWriter(FileBasedWriteOperation writeOperation, AvroCoder coder) { - super(writeOperation); - this.mimeType = MimeTypes.BINARY; - this.coder = coder; - } - - @Override - protected void prepareWrite(WritableByteChannel channel) throws Exception { - dataFileWriter = new DataFileWriter<>(coder.createDatumWriter()); - dataFileWriter.create(coder.getSchema(), Channels.newOutputStream(channel)); - } - - @Override - public void write(T value) throws Exception { - dataFileWriter.append(value); - } - - @Override - protected void writeFooter() throws Exception { - dataFileWriter.close(); - } + AvroSink writer = new AvroSink<>(transform.filenamePrefix, transform.shardTemplate, + transform.filenameSuffix, numShards, + WindowedValue.getValueOnlyCoder(AvroCoder.of(transform.type, transform.schema))); + try (Sink.SinkWriter> sink = writer.writer()) { + for (WindowedValue elem : elems) { + sink.add(elem); + } + } catch (IOException exn) { + throw new RuntimeException( + "unable to write to output file \"" + transform.filenamePrefix + "\"", exn); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 5a57f7fc43..f20caa3b96 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -32,7 +32,6 @@ import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; import com.google.cloud.dataflow.sdk.PipelineResult.State; import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -49,10 +48,8 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.FileBasedSink; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.io.Write; @@ -63,8 +60,6 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.JobSpecification; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; @@ -88,7 +83,6 @@ import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; @@ -337,8 +331,6 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); builder.put(Read.Unbounded.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); - builder.put(Write.Bound.class, BatchWrite.class); - builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); if (options.getExperiments() == null || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); @@ -1926,177 +1918,6 @@ public Iterable apply(Iterable> input) { } } - /** - * A {@link PTransform} that uses shuffle to create a fusion break. This allows pushing - * parallelism limits such as sharding controls further down the pipeline. - */ - private static class ReshardForWrite extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection input) { - return input - // TODO: This would need to be adapted to write per-window shards. - .apply(Window.into(new GlobalWindows()) - .triggering(DefaultTrigger.of()) - .discardingFiredPanes()) - .apply("RandomKey", ParDo.of( - new DoFn>() { - transient long counter, step; - @Override - public void startBundle(Context c) { - counter = (long) (Math.random() * Long.MAX_VALUE); - step = 1 + 2 * (long) (Math.random() * Long.MAX_VALUE); - } - @Override - public void processElement(ProcessContext c) { - counter += step; - c.output(KV.of(counter, c.element())); - } - })) - .apply(GroupByKey.create()) - .apply("Ungroup", ParDo.of( - new DoFn>, T>() { - @Override - public void processElement(ProcessContext c) { - for (T item : c.element().getValue()) { - c.output(item); - } - } - })); - } - } - - /** - * Specialized implementation which overrides - * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} to provide Google - * Cloud Dataflow specific path validation of {@link FileBasedSink}s. - */ - private static class BatchWrite extends PTransform, PDone> { - private final DataflowPipelineRunner runner; - private final Write.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchWrite(DataflowPipelineRunner runner, Write.Bound transform) { - this.runner = runner; - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - if (transform.getSink() instanceof FileBasedSink) { - FileBasedSink sink = (FileBasedSink) transform.getSink(); - PathValidator validator = runner.options.getPathValidator(); - validator.validateOutputFilePrefixSupported(sink.getBaseOutputFilename()); - } - return transform.apply(input); - } - } - - /** - * Specialized implementation which overrides - * {@link com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound AvroIO.Write.Bound} with - * a native sink instead of a custom sink as workaround until custom sinks - * have support for sharding controls. - */ - private static class BatchAvroIOWrite extends PTransform, PDone> { - private final AvroIO.Write.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchAvroIOWrite(DataflowPipelineRunner runner, AvroIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - if (transform.getNumShards() > 0) { - return input - .apply(new ReshardForWrite()) - .apply(new BatchAvroIONativeWrite<>(transform)); - } else { - return transform.apply(input); - } - } - } - - /** - * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way - * to provide the native definition of the Avro sink. - */ - private static class BatchAvroIONativeWrite extends PTransform, PDone> { - private final AvroIO.Write.Bound transform; - public BatchAvroIONativeWrite(AvroIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - return PDone.in(input.getPipeline()); - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - BatchAvroIONativeWrite.class, new BatchAvroIONativeWriteTranslator()); - } - } - - /** - * AvroIO.Write.Bound support code for the Dataflow backend when applying parallelism limits - * through user requested sharding limits. - */ - private static class BatchAvroIONativeWriteTranslator - implements TransformTranslator> { - @SuppressWarnings("unchecked") - @Override - public void translate(@SuppressWarnings("rawtypes") BatchAvroIONativeWrite transform, - TranslationContext context) { - translateWriteHelper(transform, transform.transform, context); - } - - private void translateWriteHelper( - BatchAvroIONativeWrite transform, - AvroIO.Write.Bound originalTransform, - TranslationContext context) { - // Note that the original transform can not be used during add step/add input - // and is only passed in to get properties from it. - - checkState(originalTransform.getNumShards() > 0, - "Native AvroSink is expected to only be used when sharding controls are required."); - - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (originalTransform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(originalTransform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + originalTransform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - context.addInput(PropertyNames.FORMAT, "avro"); - context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, originalTransform.getShardTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); - - context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); - - context.addEncodingInput( - WindowedValue.getValueOnlyCoder( - AvroCoder.of(originalTransform.getType(), originalTransform.getSchema()))); - } - } - /** * Specialized (non-)implementation for * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 885260ebb2..f7217f7610 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -41,6 +41,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.IterableCoder; +import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; @@ -48,6 +49,7 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; +import com.google.cloud.dataflow.sdk.runners.dataflow.AvroIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; @@ -1026,6 +1028,9 @@ private void translateHelper( /////////////////////////////////////////////////////////////////////////// // IO Translation. + registerTransformTranslator( + AvroIO.Write.Bound.class, new AvroIOTranslator.WriteTranslator()); + registerTransformTranslator( BigQueryIO.Read.Bound.class, new BigQueryIOTranslator.ReadTranslator()); registerTransformTranslator( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java new file mode 100644 index 0000000000..b114021c4d --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; + +import com.google.cloud.dataflow.sdk.coders.AvroCoder; +import com.google.cloud.dataflow.sdk.io.AvroIO; +import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; +import com.google.cloud.dataflow.sdk.util.PathValidator; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.common.base.Preconditions; + +/** + * Avro transform support code for the Dataflow backend. + */ +public class AvroIOTranslator { + + /** + * Implements AvroIO Write translation for the Dataflow backend. + */ + @SuppressWarnings("rawtypes") + public static class WriteTranslator implements TransformTranslator { + + @Override + public void translate( + AvroIO.Write.Bound transform, + TranslationContext context) { + translateWriteHelper(transform, context); + } + + private void translateWriteHelper( + AvroIO.Write.Bound transform, + TranslationContext context) { + PathValidator validator = context.getPipelineOptions().getPathValidator(); + String filenamePrefix = validator.validateOutputFilePrefixSupported( + transform.getFilenamePrefix()); + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + + // TODO: drop this check when server supports alternative templates. + switch (transform.getShardTemplate()) { + case ShardNameTemplate.INDEX_OF_MAX: + break; // supported by server + case "": + // Empty shard template allowed - forces single output. + Preconditions.checkArgument(transform.getNumShards() <= 1, + "Num shards must be <= 1 when using an empty sharding template"); + break; + default: + throw new UnsupportedOperationException("Shard template " + + transform.getShardTemplate() + + " not yet supported by Dataflow service"); + } + + context.addInput(PropertyNames.FORMAT, "avro"); + context.addInput(PropertyNames.FILENAME_PREFIX, filenamePrefix); + context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, transform.getShardTemplate()); + context.addInput(PropertyNames.FILENAME_SUFFIX, transform.getFilenameSuffix()); + context.addInput(PropertyNames.VALIDATE_SINK, transform.needsValidation()); + + long numShards = transform.getNumShards(); + if (numShards > 0) { + context.addInput(PropertyNames.NUM_SHARDS, numShards); + } + + context.addEncodingInput( + WindowedValue.getValueOnlyCoder( + AvroCoder.of(transform.getType(), transform.getSchema()))); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java index 927d3a3903..6bb459de7a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java @@ -148,102 +148,102 @@ void runTestRead(AvroIO.Read.Bound read, String expectedName, T[] expecte public void testReadFromGeneratedClass() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class), - "AvroIO.Read/Read.out", generateAvroObjects()); + "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()), - "AvroIO.Read/Read.out", generateAvroObjects()); + "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class), - "MyRead/Read.out", generateAvroObjects()); + "MyRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()), - "MyRead/Read.out", generateAvroObjects()); + "MyRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(AvroGeneratedUser.class) .named("HerRead"), - "HerRead/Read.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(AvroGeneratedUser.class), - "HerRead/Read.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .named("HerRead") .from(avroFile.getPath()), - "HerRead/Read.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) .from(avroFile.getPath()) .named("HerRead"), - "HerRead/Read.out", generateAvroObjects()); + "HerRead/Read(AvroSource).out", generateAvroObjects()); } @Test public void testReadFromSchema() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schema), - "AvroIO.Read/Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .from(avroFile.getPath()), - "AvroIO.Read/Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(schema), - "MyRead/Read.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(schema) .from(avroFile.getPath()), - "MyRead/Read.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schema) .named("HerRead"), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(schema), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .named("HerRead") .from(avroFile.getPath()), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schema) .from(avroFile.getPath()) .named("HerRead"), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); } @Test public void testReadFromSchemaString() throws Exception { runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schemaString), - "AvroIO.Read/Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .from(avroFile.getPath()), - "AvroIO.Read/Read.out", generateAvroGenericRecords()); + "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .from(avroFile.getPath()) .withSchema(schemaString), - "MyRead/Read.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.named("MyRead") .withSchema(schemaString) .from(avroFile.getPath()), - "MyRead/Read.out", generateAvroGenericRecords()); + "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .withSchema(schemaString) .named("HerRead"), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.from(avroFile.getPath()) .named("HerRead") .withSchema(schemaString), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .named("HerRead") .from(avroFile.getPath()), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); runTestRead(AvroIO.Read.withSchema(schemaString) .from(avroFile.getPath()) .named("HerRead"), - "HerRead/Read.out", generateAvroGenericRecords()); + "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); } void runTestWrite(AvroIO.Write.Bound write, String expectedName) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java index 207b2ba514..30c578bbda 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java @@ -16,28 +16,19 @@ package com.google.cloud.dataflow.sdk.io; -import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO.AvroSink; -import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation; -import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.DirectPipeline; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterators; -import org.apache.avro.file.DataFileReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.reflect.Nullable; import org.junit.Rule; @@ -47,10 +38,6 @@ import org.junit.runners.JUnit4; import java.io.File; -import java.nio.channels.FileChannel; -import java.nio.channels.WritableByteChannel; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -202,38 +189,6 @@ public void testAvroIOWriteAndReadSchemaUpgrade() throws Throwable { p.run(); } - @Test - public void testAvroSinkWrite() throws Exception { - String[] expectedElements = new String[]{ "first", "second", "third" }; - PipelineOptions options = PipelineOptionsFactory.create(); - AvroCoder coder = AvroCoder.of(String.class); - File tmpFile = tmpFolder.newFile(); - AvroSink avroSink = new AvroSink<>( - "prefix", "suffix", ShardNameTemplate.INDEX_OF_MAX, coder); - FileBasedWriteOperation writeOperation = avroSink.createWriteOperation(options); - FileBasedWriter writer = writeOperation.createWriter(options); - - WritableByteChannel channel = FileChannel.open(tmpFile.toPath(), StandardOpenOption.WRITE); - writer.prepareWrite(channel); - writer.writeHeader(); - for (String element : expectedElements) { - writer.write(element); - // We expect the channel to remain open - assertTrue(channel.isOpen()); - } - - writer.close(); - // Ensure that we properly close the channel - assertFalse(channel.isOpen()); - - // Validate that the data written matches the expected elements in the expected order - try (DataFileReader reader = new DataFileReader<>(tmpFile, coder.createDatumReader())) { - List actualElements = new ArrayList<>(); - Iterators.addAll(actualElements, reader); - assertThat(actualElements, contains(expectedElements)); - } - } - // TODO: for Write only, test withSuffix, withNumShards, // withShardNameTemplate and withoutSharding. } From 01a0da02daed5f1609237ae85c82fd056ea76339 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Tue, 23 Feb 2016 17:35:40 -0800 Subject: [PATCH 206/751] Resubmit "Migrate AvroIO.Write to a custom sink" Note for user requested sharding limits to be supported, each pipeline runner must support applying those sharding limits. Google Cloud Dataflow supports sharding limits. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115402880 --- .../google/cloud/dataflow/sdk/io/AvroIO.java | 223 +++++++++--------- .../sdk/runners/DataflowPipelineRunner.java | 189 +++++++++++++++ .../runners/DataflowPipelineTranslator.java | 5 - .../runners/dataflow/AvroIOTranslator.java | 87 ------- .../sdk/io/AvroIOGeneratedClassTest.java | 186 ++++++++------- .../cloud/dataflow/sdk/io/AvroIOTest.java | 34 ++- 6 files changed, 433 insertions(+), 291 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java index 9ee7e6b13c..f016b5b47b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java @@ -22,24 +22,25 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.AvroSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; +import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.avro.Schema; +import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.reflect.ReflectData; import java.io.IOException; -import java.util.List; +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -317,7 +318,7 @@ public PCollection apply(PInput input) { : com.google.cloud.dataflow.sdk.io.Read.from( AvroSource.from(filepattern).withSchema(type)); - PCollection pcol = input.getPipeline().apply(read); + PCollection pcol = input.getPipeline().apply("Read", read); // Honor the default output coder that would have been used by this PTransform. pcol.setCoder(getDefaultOutputCoder()); return pcol; @@ -473,8 +474,6 @@ public static class Bound extends PTransform, PDone> { final int numShards; /** Shard template string. */ final String shardTemplate; - /** Insert a shuffle before writing to decouple parallelism when numShards != 0. */ - final boolean forceReshard; /** The class type of the records. */ final Class type; /** The schema of the output file. */ @@ -484,18 +483,23 @@ public static class Bound extends PTransform, PDone> { final boolean validate; Bound(Class type) { - this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, true, type, null, true); + this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, type, null, true); } - Bound(String name, String filenamePrefix, String filenameSuffix, int numShards, - String shardTemplate, boolean forceReshard, Class type, Schema schema, + Bound( + String name, + String filenamePrefix, + String filenameSuffix, + int numShards, + String shardTemplate, + Class type, + Schema schema, boolean validate) { super(name); this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; this.numShards = numShards; this.shardTemplate = shardTemplate; - this.forceReshard = forceReshard; this.type = type; this.schema = schema; this.validate = validate; @@ -509,8 +513,7 @@ public static class Bound extends PTransform, PDone> { */ public Bound named(String name) { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, - type, schema, validate); + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } /** @@ -525,8 +528,7 @@ public Bound named(String name) { public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, - type, schema, validate); + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } /** @@ -540,8 +542,7 @@ public Bound to(String filenamePrefix) { public Bound withSuffix(String filenameSuffix) { validateOutputComponent(filenameSuffix); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, type, - schema, validate); + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } /** @@ -559,32 +560,9 @@ public Bound withSuffix(String filenameSuffix) { * @see ShardNameTemplate */ public Bound withNumShards(int numShards) { - return withNumShards(numShards, forceReshard); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that uses the provided shard count. - * - *

    Constraining the number of shards is likely to reduce - * the performance of a pipeline. If forceReshard is true, the output - * will be shuffled to obtain the desired sharding. If it is false, - * data will not be reshuffled, but parallelism of preceeding stages - * may be constrained. Setting this value is not recommended - * unless you require a specific number of output files. - * - *

    Does not modify this object. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - * @param forceReshard whether to force a reshard to obtain the desired sharding. - * @see ShardNameTemplate - */ - private Bound withNumShards(int numShards, boolean forceReshard) { Preconditions.checkArgument(numShards >= 0); return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, - type, schema, validate); + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } /** @@ -597,8 +575,7 @@ private Bound withNumShards(int numShards, boolean forceReshard) { */ public Bound withShardNameTemplate(String shardTemplate) { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, - type, schema, validate); + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); } /** @@ -611,23 +588,7 @@ public Bound withShardNameTemplate(String shardTemplate) { *

    Does not modify this object. */ public Bound withoutSharding() { - return withoutSharding(forceReshard); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that forces a single file as output. - * - *

    This is a shortcut for - * {@code .withNumShards(1, forceReshard).withShardNameTemplate("")} - * - *

    Does not modify this object. - * - * @param forceReshard whether to force a reshard to obtain the desired sharding. - */ - private Bound withoutSharding(boolean forceReshard) { - return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", forceReshard, - type, schema, validate); + return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", type, schema, validate); } /** @@ -640,8 +601,15 @@ private Bound withoutSharding(boolean forceReshard) { * @param the type of the elements of the input PCollection */ public Bound withSchema(Class type) { - return new Bound<>(name, filenamePrefix, filenameSuffix, numShards, shardTemplate, - forceReshard, type, ReflectData.get().getSchema(type), validate); + return new Bound<>( + name, + filenamePrefix, + filenameSuffix, + numShards, + shardTemplate, + type, + ReflectData.get().getSchema(type), + validate); } /** @@ -652,8 +620,15 @@ public Bound withSchema(Class type) { *

    Does not modify this object. */ public Bound withSchema(Schema schema) { - return new Bound<>(name, filenamePrefix, filenameSuffix, numShards, shardTemplate, - forceReshard, GenericRecord.class, schema, validate); + return new Bound<>( + name, + filenamePrefix, + filenameSuffix, + numShards, + shardTemplate, + GenericRecord.class, + schema, + validate); } /** @@ -679,8 +654,7 @@ public Bound withSchema(String schema) { */ public Bound withoutValidation() { return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, forceReshard, - type, schema, false); + name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, false); } @Override @@ -693,14 +667,14 @@ public PDone apply(PCollection input) { throw new IllegalStateException("need to set the schema of an AvroIO.Write transform"); } - if (numShards > 0 && forceReshard) { - // Reshard and re-apply a version of this write without resharding. - return input - .apply(new FileBasedSink.ReshardForWrite()) - .apply(withNumShards(numShards, false)); - } else { - return PDone.in(input.getPipeline()); - } + // Note that custom sinks currently do not expose sharding controls. + // Thus pipeline runner writers need to individually add support internally to + // apply user requested sharding limits. + return input.apply( + "Write", + com.google.cloud.dataflow.sdk.io.Write.to( + new AvroSink<>( + filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema)))); } /** @@ -742,21 +716,6 @@ public Schema getSchema() { public boolean needsValidation() { return validate; } - - static { - @SuppressWarnings("rawtypes") - DirectPipelineRunner.TransformEvaluator transformEvaluator = - new DirectPipelineRunner.TransformEvaluator() { - @Override - @SuppressWarnings("unchecked") - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateWriteHelper(transform, context); - } - }; - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, transformEvaluator); - } } /** Disallow construction of utility class. */ @@ -779,25 +738,73 @@ private static void validateOutputComponent(String partialFilePattern) { /** Disallow construction of utility class. */ private AvroIO() {} - private static void evaluateWriteHelper( - Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { - List> elems = - context.getPCollectionWindowedValues(context.getInput(transform)); - int numShards = transform.numShards; - if (numShards < 1) { - // System gets to choose. For direct mode, choose 1. - numShards = 1; + /** + * A {@link FileBasedSink} for Avro files. + */ + @VisibleForTesting + static class AvroSink extends FileBasedSink { + private final AvroCoder coder; + + @VisibleForTesting + AvroSink( + String baseOutputFilename, String extension, String fileNameTemplate, AvroCoder coder) { + super(baseOutputFilename, extension, fileNameTemplate); + this.coder = coder; + } + + @Override + public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { + return new AvroWriteOperation<>(this, coder); + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation + * FileBasedWriteOperation} for Avro files. + */ + private static class AvroWriteOperation extends FileBasedWriteOperation { + private final AvroCoder coder; + + private AvroWriteOperation(AvroSink sink, AvroCoder coder) { + super(sink); + this.coder = coder; + } + + @Override + public FileBasedWriter createWriter(PipelineOptions options) throws Exception { + return new AvroWriter<>(this, coder); + } } - AvroSink writer = new AvroSink<>(transform.filenamePrefix, transform.shardTemplate, - transform.filenameSuffix, numShards, - WindowedValue.getValueOnlyCoder(AvroCoder.of(transform.type, transform.schema))); - try (Sink.SinkWriter> sink = writer.writer()) { - for (WindowedValue elem : elems) { - sink.add(elem); - } - } catch (IOException exn) { - throw new RuntimeException( - "unable to write to output file \"" + transform.filenamePrefix + "\"", exn); + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} + * for Avro files. + */ + private static class AvroWriter extends FileBasedWriter { + private final AvroCoder coder; + private DataFileWriter dataFileWriter; + + public AvroWriter(FileBasedWriteOperation writeOperation, AvroCoder coder) { + super(writeOperation); + this.mimeType = MimeTypes.BINARY; + this.coder = coder; + } + + @SuppressWarnings("deprecation") // uses internal test functionality. + @Override + protected void prepareWrite(WritableByteChannel channel) throws Exception { + dataFileWriter = new DataFileWriter<>(coder.createDatumWriter()); + dataFileWriter.create(coder.getSchema(), Channels.newOutputStream(channel)); + } + + @Override + public void write(T value) throws Exception { + dataFileWriter.append(value); + } + + @Override + protected void writeFooter() throws Exception { + dataFileWriter.flush(); + } } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f20caa3b96..ac0dceae96 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -32,6 +32,7 @@ import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; import com.google.cloud.dataflow.sdk.PipelineResult.State; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -48,8 +49,10 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; +import com.google.cloud.dataflow.sdk.io.FileBasedSink; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.io.Write; @@ -60,6 +63,8 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.JobSpecification; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; @@ -83,6 +88,7 @@ import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; @@ -331,6 +337,8 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); builder.put(Read.Unbounded.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); + builder.put(Write.Bound.class, BatchWrite.class); + builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); if (options.getExperiments() == null || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); @@ -1918,6 +1926,187 @@ public Iterable apply(Iterable> input) { } } + /** + * A {@link PTransform} that uses shuffle to create a fusion break. This allows pushing + * parallelism limits such as sharding controls further down the pipeline. + */ + private static class ReshardForWrite extends PTransform, PCollection> { + @Override + public PCollection apply(PCollection input) { + return input + // TODO: This would need to be adapted to write per-window shards. + .apply( + Window.into(new GlobalWindows()) + .triggering(DefaultTrigger.of()) + .discardingFiredPanes()) + .apply( + "RandomKey", + ParDo.of( + new DoFn>() { + transient long counter, step; + + @Override + public void startBundle(Context c) { + counter = (long) (Math.random() * Long.MAX_VALUE); + step = 1 + 2 * (long) (Math.random() * Long.MAX_VALUE); + } + + @Override + public void processElement(ProcessContext c) { + counter += step; + c.output(KV.of(counter, c.element())); + } + })) + .apply(GroupByKey.create()) + .apply( + "Ungroup", + ParDo.of( + new DoFn>, T>() { + @Override + public void processElement(ProcessContext c) { + for (T item : c.element().getValue()) { + c.output(item); + } + } + })); + } + } + + /** + * Specialized implementation which overrides + * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} to provide Google + * Cloud Dataflow specific path validation of {@link FileBasedSink}s. + */ + private static class BatchWrite extends PTransform, PDone> { + private final DataflowPipelineRunner runner; + private final Write.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchWrite(DataflowPipelineRunner runner, Write.Bound transform) { + this.runner = runner; + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + if (transform.getSink() instanceof FileBasedSink) { + FileBasedSink sink = (FileBasedSink) transform.getSink(); + PathValidator validator = runner.options.getPathValidator(); + validator.validateOutputFilePrefixSupported(sink.getBaseOutputFilename()); + } + return transform.apply(input); + } + } + + /** + * Specialized implementation which overrides + * {@link com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound AvroIO.Write.Bound} with + * a native sink instead of a custom sink as workaround until custom sinks + * have support for sharding controls. + */ + private static class BatchAvroIOWrite extends PTransform, PDone> { + private final AvroIO.Write.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchAvroIOWrite(DataflowPipelineRunner runner, AvroIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + if (transform.getNumShards() > 0) { + return input.apply(new ReshardForWrite()).apply(new BatchAvroIONativeWrite<>(transform)); + } else { + return transform.apply(input); + } + } + } + + /** + * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way + * to provide the native definition of the Avro sink. + */ + private static class BatchAvroIONativeWrite extends PTransform, PDone> { + private final AvroIO.Write.Bound transform; + + public BatchAvroIONativeWrite(AvroIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + return PDone.in(input.getPipeline()); + } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + BatchAvroIONativeWrite.class, new BatchAvroIONativeWriteTranslator()); + } + } + + /** + * AvroIO.Write.Bound support code for the Dataflow backend when applying parallelism limits + * through user requested sharding limits. + */ + private static class BatchAvroIONativeWriteTranslator + implements TransformTranslator> { + @SuppressWarnings("unchecked") + @Override + public void translate( + @SuppressWarnings("rawtypes") BatchAvroIONativeWrite transform, + TranslationContext context) { + translateWriteHelper(transform, transform.transform, context); + } + + private void translateWriteHelper( + BatchAvroIONativeWrite transform, + AvroIO.Write.Bound originalTransform, + TranslationContext context) { + // Note that the original transform can not be used during add step/add input + // and is only passed in to get properties from it. + + checkState( + originalTransform.getNumShards() > 0, + "Native AvroSink is expected to only be used when sharding controls are required."); + + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + + // TODO: drop this check when server supports alternative templates. + switch (originalTransform.getShardTemplate()) { + case ShardNameTemplate.INDEX_OF_MAX: + break; // supported by server + case "": + // Empty shard template allowed - forces single output. + Preconditions.checkArgument( + originalTransform.getNumShards() <= 1, + "Num shards must be <= 1 when using an empty sharding template"); + break; + default: + throw new UnsupportedOperationException( + "Shard template " + + originalTransform.getShardTemplate() + + " not yet supported by Dataflow service"); + } + + context.addInput(PropertyNames.FORMAT, "avro"); + context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); + context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, originalTransform.getShardTemplate()); + context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); + context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); + + context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); + + context.addEncodingInput( + WindowedValue.getValueOnlyCoder( + AvroCoder.of(originalTransform.getType(), originalTransform.getSchema()))); + } + } + /** * Specialized (non-)implementation for * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index f7217f7610..885260ebb2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -41,7 +41,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; @@ -49,7 +48,6 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; -import com.google.cloud.dataflow.sdk.runners.dataflow.AvroIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; @@ -1028,9 +1026,6 @@ private void translateHelper( /////////////////////////////////////////////////////////////////////////// // IO Translation. - registerTransformTranslator( - AvroIO.Write.Bound.class, new AvroIOTranslator.WriteTranslator()); - registerTransformTranslator( BigQueryIO.Read.Bound.class, new BigQueryIOTranslator.ReadTranslator()); registerTransformTranslator( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java deleted file mode 100644 index b114021c4d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AvroIOTranslator.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.util.PathValidator; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.common.base.Preconditions; - -/** - * Avro transform support code for the Dataflow backend. - */ -public class AvroIOTranslator { - - /** - * Implements AvroIO Write translation for the Dataflow backend. - */ - @SuppressWarnings("rawtypes") - public static class WriteTranslator implements TransformTranslator { - - @Override - public void translate( - AvroIO.Write.Bound transform, - TranslationContext context) { - translateWriteHelper(transform, context); - } - - private void translateWriteHelper( - AvroIO.Write.Bound transform, - TranslationContext context) { - PathValidator validator = context.getPipelineOptions().getPathValidator(); - String filenamePrefix = validator.validateOutputFilePrefixSupported( - transform.getFilenamePrefix()); - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (transform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(transform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + transform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - context.addInput(PropertyNames.FORMAT, "avro"); - context.addInput(PropertyNames.FILENAME_PREFIX, filenamePrefix); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, transform.getShardTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, transform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, transform.needsValidation()); - - long numShards = transform.getNumShards(); - if (numShards > 0) { - context.addInput(PropertyNames.NUM_SHARDS, numShards); - } - - context.addEncodingInput( - WindowedValue.getValueOnlyCoder( - AvroCoder.of(transform.getType(), transform.getSchema()))); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java index 6bb459de7a..6a7679f5ed 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java @@ -146,104 +146,110 @@ void runTestRead(AvroIO.Read.Bound read, String expectedName, T[] expecte @Test public void testReadFromGeneratedClass() throws Exception { - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .withSchema(AvroGeneratedUser.class), - "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); - runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) - .from(avroFile.getPath()), - "AvroIO.Read/Read(AvroSource).out", generateAvroObjects()); - runTestRead(AvroIO.Read.named("MyRead") - .from(avroFile.getPath()) - .withSchema(AvroGeneratedUser.class), - "MyRead/Read(AvroSource).out", generateAvroObjects()); - runTestRead(AvroIO.Read.named("MyRead") - .withSchema(AvroGeneratedUser.class) - .from(avroFile.getPath()), - "MyRead/Read(AvroSource).out", generateAvroObjects()); - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .withSchema(AvroGeneratedUser.class) - .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroObjects()); - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .named("HerRead") - .withSchema(AvroGeneratedUser.class), - "HerRead/Read(AvroSource).out", generateAvroObjects()); - runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) - .named("HerRead") - .from(avroFile.getPath()), - "HerRead/Read(AvroSource).out", generateAvroObjects()); - runTestRead(AvroIO.Read.withSchema(AvroGeneratedUser.class) - .from(avroFile.getPath()) - .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroObjects()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).withSchema(AvroGeneratedUser.class), + "AvroIO.Read/Read.out", + generateAvroObjects()); + runTestRead( + AvroIO.Read.withSchema(AvroGeneratedUser.class).from(avroFile.getPath()), + "AvroIO.Read/Read.out", + generateAvroObjects()); + runTestRead( + AvroIO.Read.named("MyRead").from(avroFile.getPath()).withSchema(AvroGeneratedUser.class), + "MyRead/Read.out", + generateAvroObjects()); + runTestRead( + AvroIO.Read.named("MyRead").withSchema(AvroGeneratedUser.class).from(avroFile.getPath()), + "MyRead/Read.out", + generateAvroObjects()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).withSchema(AvroGeneratedUser.class).named("HerRead"), + "HerRead/Read.out", + generateAvroObjects()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).named("HerRead").withSchema(AvroGeneratedUser.class), + "HerRead/Read.out", + generateAvroObjects()); + runTestRead( + AvroIO.Read.withSchema(AvroGeneratedUser.class).named("HerRead").from(avroFile.getPath()), + "HerRead/Read.out", + generateAvroObjects()); + runTestRead( + AvroIO.Read.withSchema(AvroGeneratedUser.class).from(avroFile.getPath()).named("HerRead"), + "HerRead/Read.out", + generateAvroObjects()); } @Test public void testReadFromSchema() throws Exception { - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .withSchema(schema), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.withSchema(schema) - .from(avroFile.getPath()), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.named("MyRead") - .from(avroFile.getPath()) - .withSchema(schema), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.named("MyRead") - .withSchema(schema) - .from(avroFile.getPath()), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .withSchema(schema) - .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .named("HerRead") - .withSchema(schema), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.withSchema(schema) - .named("HerRead") - .from(avroFile.getPath()), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.withSchema(schema) - .from(avroFile.getPath()) - .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).withSchema(schema), + "AvroIO.Read/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.withSchema(schema).from(avroFile.getPath()), + "AvroIO.Read/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.named("MyRead").from(avroFile.getPath()).withSchema(schema), + "MyRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.named("MyRead").withSchema(schema).from(avroFile.getPath()), + "MyRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).withSchema(schema).named("HerRead"), + "HerRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).named("HerRead").withSchema(schema), + "HerRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.withSchema(schema).named("HerRead").from(avroFile.getPath()), + "HerRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.withSchema(schema).from(avroFile.getPath()).named("HerRead"), + "HerRead/Read.out", + generateAvroGenericRecords()); } @Test public void testReadFromSchemaString() throws Exception { - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .withSchema(schemaString), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.withSchema(schemaString) - .from(avroFile.getPath()), - "AvroIO.Read/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.named("MyRead") - .from(avroFile.getPath()) - .withSchema(schemaString), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.named("MyRead") - .withSchema(schemaString) - .from(avroFile.getPath()), - "MyRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .withSchema(schemaString) - .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.from(avroFile.getPath()) - .named("HerRead") - .withSchema(schemaString), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.withSchema(schemaString) - .named("HerRead") - .from(avroFile.getPath()), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); - runTestRead(AvroIO.Read.withSchema(schemaString) - .from(avroFile.getPath()) - .named("HerRead"), - "HerRead/Read(AvroSource).out", generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).withSchema(schemaString), + "AvroIO.Read/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.withSchema(schemaString).from(avroFile.getPath()), + "AvroIO.Read/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.named("MyRead").from(avroFile.getPath()).withSchema(schemaString), + "MyRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.named("MyRead").withSchema(schemaString).from(avroFile.getPath()), + "MyRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).withSchema(schemaString).named("HerRead"), + "HerRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.from(avroFile.getPath()).named("HerRead").withSchema(schemaString), + "HerRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.withSchema(schemaString).named("HerRead").from(avroFile.getPath()), + "HerRead/Read.out", + generateAvroGenericRecords()); + runTestRead( + AvroIO.Read.withSchema(schemaString).from(avroFile.getPath()).named("HerRead"), + "HerRead/Read.out", + generateAvroGenericRecords()); } void runTestWrite(AvroIO.Write.Bound write, String expectedName) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java index 30c578bbda..2258a9136f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java @@ -16,19 +16,25 @@ package com.google.cloud.dataflow.sdk.io; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.DefaultCoder; import com.google.cloud.dataflow.sdk.runners.DirectPipeline; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterators; +import org.apache.avro.file.DataFileReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.reflect.Nullable; import org.junit.Rule; @@ -38,6 +44,7 @@ import org.junit.runners.JUnit4; import java.io.File; +import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -104,7 +111,7 @@ public boolean equals(Object other) { } @Test - public void testAvroIOWriteAndRead() throws Throwable { + public void testAvroIOWriteAndReadASingleFile() throws Throwable { DirectPipeline p = DirectPipeline.createForTest(); List values = ImmutableList.of(new GenericClass(3, "hi"), new GenericClass(5, "bar")); @@ -189,6 +196,31 @@ public void testAvroIOWriteAndReadSchemaUpgrade() throws Throwable { p.run(); } + @SuppressWarnings("deprecation") // using AvroCoder#createDatumReader for tests. + @Test + public void testAvroSinkWrite() throws Exception { + String outputFilePrefix = new File(tmpFolder.getRoot(), "prefix").getAbsolutePath(); + String[] expectedElements = new String[] {"first", "second", "third"}; + + TestPipeline p = TestPipeline.create(); + p.apply(Create.of(expectedElements)) + .apply(AvroIO.Write.to(outputFilePrefix).withSchema(String.class)); + p.run(); + + // Validate that the data written matches the expected elements in the expected order + String expectedName = + IOChannelUtils.constructName( + outputFilePrefix, ShardNameTemplate.INDEX_OF_MAX, "" /* no suffix */, 0, 1); + File outputFile = new File(expectedName); + assertTrue("Expected output file " + expectedName, outputFile.exists()); + try (DataFileReader reader = + new DataFileReader<>(outputFile, AvroCoder.of(String.class).createDatumReader())) { + List actualElements = new ArrayList<>(); + Iterators.addAll(actualElements, reader); + assertThat(actualElements, containsInAnyOrder(expectedElements)); + } + } + // TODO: for Write only, test withSuffix, withNumShards, // withShardNameTemplate and withoutSharding. } From 96b02f4737457d158db60ae467e7098839c383ab Mon Sep 17 00:00:00 2001 From: tgroh Date: Tue, 23 Feb 2016 17:52:25 -0800 Subject: [PATCH 207/751] Add GroupByKey InProcess override This takes a GroupByKey primitive and implements it as a sequence of composite transforms, including a simpler GroupByKeyOnly primitive. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115404181 --- .../inprocess/GroupByKeyEvaluatorFactory.java | 128 +++++++++++++++--- .../inprocess/InProcessPipelineRunner.java | 9 ++ .../dataflow/sdk/transforms/GroupByKey.java | 2 +- .../GroupByKeyEvaluatorFactoryTest.java | 114 ++++++++++------ 4 files changed, 190 insertions(+), 63 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java index 44d6909274..0347281749 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java @@ -19,18 +19,29 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.IterableCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult.Builder; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey.ReifyTimestampsAndWindows; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowViaWindowSetDoFn; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItemCoder; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItems; +import com.google.cloud.dataflow.sdk.util.SystemReduceFn; import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.Arrays; @@ -53,52 +64,56 @@ public TransformEvaluator forApplication( (AppliedPTransform) application, (CommittedBundle) inputBundle, evaluationContext); } - private TransformEvaluator> createEvaluator( + private TransformEvaluator>> createEvaluator( final AppliedPTransform< - PCollection>, PCollection>>, GroupByKeyOnly> + PCollection>>, PCollection>, + InProcessGroupByKeyOnly> application, final CommittedBundle> inputBundle, final InProcessEvaluationContext evaluationContext) { return new GroupByKeyEvaluator(evaluationContext, inputBundle, application); } - private static class GroupByKeyEvaluator implements TransformEvaluator> { + private static class GroupByKeyEvaluator + implements TransformEvaluator>> { private final InProcessEvaluationContext evaluationContext; private final CommittedBundle> inputBundle; private final AppliedPTransform< - PCollection>, PCollection>>, GroupByKeyOnly> + PCollection>>, PCollection>, + InProcessGroupByKeyOnly> application; private final Coder keyCoder; - private Map, List> groupingMap; + private Map, List>> groupingMap; public GroupByKeyEvaluator( InProcessEvaluationContext evaluationContext, CommittedBundle> inputBundle, AppliedPTransform< - PCollection>, PCollection>>, GroupByKeyOnly> + PCollection>>, PCollection>, + InProcessGroupByKeyOnly> application) { this.evaluationContext = evaluationContext; this.inputBundle = inputBundle; this.application = application; - PCollection> input = application.getInput(); + PCollection>> input = application.getInput(); keyCoder = getKeyCoder(input.getCoder()); groupingMap = new HashMap<>(); } - private Coder getKeyCoder(Coder> coder) { + private Coder getKeyCoder(Coder>> coder) { if (!(coder instanceof KvCoder)) { throw new IllegalStateException(); } @SuppressWarnings("unchecked") - Coder keyCoder = ((KvCoder) coder).getKeyCoder(); + Coder keyCoder = ((KvCoder>) coder).getKeyCoder(); return keyCoder; } @Override - public void processElement(WindowedValue> element) { - KV kv = element.getValue(); + public void processElement(WindowedValue>> element) { + KV> kv = element.getValue(); K key = kv.getKey(); byte[] encodedKey; try { @@ -111,20 +126,23 @@ public void processElement(WindowedValue> element) { exn); } GroupingKey groupingKey = new GroupingKey<>(key, encodedKey); - if (!groupingMap.containsKey(groupingKey)) { - groupingMap.put(groupingKey, new ArrayList()); + List> values = groupingMap.get(groupingKey); + if (values == null) { + values = new ArrayList>(); + groupingMap.put(groupingKey, values); } - List values = groupingMap.get(groupingKey); values.add(kv.getValue()); } @Override public InProcessTransformResult finishBundle() { Builder resultBuilder = StepTransformResult.withoutHold(application); - for (Map.Entry, List> groupedEntry : groupingMap.entrySet()) { + for (Map.Entry, List>> groupedEntry : + groupingMap.entrySet()) { K key = groupedEntry.getKey().key; - KV> groupedKv = KV.>of(key, groupedEntry.getValue()); - UncommittedBundle>> bundle = + KeyedWorkItem groupedKv = + KeyedWorkItems.elementsWorkItem(key, groupedEntry.getValue()); + UncommittedBundle> bundle = evaluationContext.createKeyedBundle(inputBundle, key, application.getOutput()); bundle.add(WindowedValue.valueInEmptyWindows(groupedKv)); resultBuilder.addOutput(bundle); @@ -157,4 +175,78 @@ public int hashCode() { } } } + + /** + * An in-memory implementation of the {@link GroupByKey} primitive as a composite + * {@link PTransform}. + */ + public static final class InProcessGroupByKey + extends ForwardingPTransform>, PCollection>>> { + private final GroupByKey original; + + public InProcessGroupByKey(GroupByKey from) { + this.original = from; + } + + @Override + public PTransform>, PCollection>>> delegate() { + return original; + } + + @Override + public PCollection>> apply(PCollection> input) { + KvCoder inputCoder = (KvCoder) input.getCoder(); + + // This operation groups by the combination of key and window, + // merging windows as needed, using the windows assigned to the + // key/value input elements and the window merge operation of the + // window function associated with the input PCollection. + WindowingStrategy windowingStrategy = input.getWindowingStrategy(); + + // Use the default GroupAlsoByWindow implementation + DoFn, KV>> groupAlsoByWindow = + groupAlsoByWindow(windowingStrategy, inputCoder.getValueCoder()); + + // By default, implement GroupByKey via a series of lower-level operations. + return input + // Make each input element's timestamp and assigned windows + // explicit, in the value part. + .apply(new ReifyTimestampsAndWindows()) + + .apply(new InProcessGroupByKeyOnly()) + .setCoder(KeyedWorkItemCoder.of(inputCoder.getKeyCoder(), + inputCoder.getValueCoder(), input.getWindowingStrategy().getWindowFn().windowCoder())) + + // Group each key's values by window, merging windows as needed. + .apply("GroupAlsoByWindow", ParDo.of(groupAlsoByWindow)) + + // And update the windowing strategy as appropriate. + .setWindowingStrategyInternal(original.updateWindowingStrategy(windowingStrategy)) + .setCoder( + KvCoder.of(inputCoder.getKeyCoder(), IterableCoder.of(inputCoder.getValueCoder()))); + } + + private + DoFn, KV>> groupAlsoByWindow( + final WindowingStrategy windowingStrategy, final Coder inputCoder) { + return GroupAlsoByWindowViaWindowSetDoFn.create( + windowingStrategy, SystemReduceFn.buffering(inputCoder)); + } + } + + /** + * An implementation primitive to use in the evaluation of a {@link GroupByKey} + * {@link PTransform}. + */ + public static final class InProcessGroupByKeyOnly + extends PTransform>>, PCollection>> { + @Override + public PCollection> apply(PCollection>> input) { + return PCollection.>createPrimitiveOutputInternal( + input.getPipeline(), input.getWindowingStrategy(), input.isBounded()); + } + + @VisibleForTesting + InProcessGroupByKeyOnly() {} + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 7747839d0b..72642da122 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKey; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; @@ -38,6 +39,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.collect.ImmutableMap; import org.joda.time.Instant; @@ -53,6 +55,13 @@ */ @Experimental public class InProcessPipelineRunner { + @SuppressWarnings({"rawtypes", "unused"}) + private static Map, Class> + defaultTransformOverrides = + ImmutableMap., Class>builder() + .put(GroupByKey.class, InProcessGroupByKey.class) + .build(); + private static Map, TransformEvaluatorFactory> defaultEvaluatorFactories = new ConcurrentHashMap<>(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java index dee7d956ef..8fde3e0869 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java @@ -296,7 +296,7 @@ static Coder getKeyCoder(Coder> inputCoder) { /** * Returns the {@code Coder} of the values of the input to this transform. */ - static Coder getInputValueCoder(Coder> inputCoder) { + public static Coder getInputValueCoder(Coder> inputCoder) { return getInputKvCoder(inputCoder).getValueCoder(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java index d8cb237b9f..bb8a15dc8b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java @@ -28,8 +28,9 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItems; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -58,20 +59,22 @@ public void testInMemoryEvaluator() throws Exception { KV firstBar = KV.of("bar", 22); KV secondBar = KV.of("bar", 12); KV firstBaz = KV.of("baz", Integer.MAX_VALUE); - PCollection> kvs = + PCollection> values = p.apply(Create.of(firstFoo, firstBar, secondFoo, firstBaz, secondBar, thirdFoo)); - PCollection>> groupedKvs = - kvs.apply(new GroupByKeyOnly()); + PCollection>> kvs = + values.apply(new GroupByKey.ReifyTimestampsAndWindows()); + PCollection> groupedKvs = + kvs.apply(new GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly()); - CommittedBundle> inputBundle = - InProcessBundle.unkeyed(kvs).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); + CommittedBundle>> inputBundle = + InProcessBundle.unkeyed(kvs).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle>> fooBundle = + UncommittedBundle> fooBundle = InProcessBundle.keyed(groupedKvs, "foo"); - UncommittedBundle>> barBundle = + UncommittedBundle> barBundle = InProcessBundle.keyed(groupedKvs, "bar"); - UncommittedBundle>> bazBundle = + UncommittedBundle> bazBundle = InProcessBundle.keyed(groupedKvs, "baz"); when(evaluationContext.createKeyedBundle(inputBundle, "foo", groupedKvs)).thenReturn(fooBundle); @@ -80,41 +83,64 @@ public void testInMemoryEvaluator() throws Exception { // The input to a GroupByKey is assumed to be a KvCoder @SuppressWarnings("unchecked") - Coder keyCoder = ((KvCoder) kvs.getCoder()).getKeyCoder(); - TransformEvaluator> evaluator = - new GroupByKeyEvaluatorFactory().forApplication( - groupedKvs.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow(firstFoo)); - evaluator.processElement(WindowedValue.valueInGlobalWindow(secondFoo)); - evaluator.processElement(WindowedValue.valueInGlobalWindow(thirdFoo)); - evaluator.processElement(WindowedValue.valueInGlobalWindow(firstBar)); - evaluator.processElement(WindowedValue.valueInGlobalWindow(secondBar)); - evaluator.processElement(WindowedValue.valueInGlobalWindow(firstBaz)); + Coder keyCoder = + ((KvCoder>) kvs.getCoder()).getKeyCoder(); + TransformEvaluator>> evaluator = + new GroupByKeyEvaluatorFactory() + .forApplication( + groupedKvs.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(firstFoo))); + evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(secondFoo))); + evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(thirdFoo))); + evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(firstBar))); + evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(secondBar))); + evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(firstBaz))); evaluator.finishBundle(); assertThat( fooBundle.commit(Instant.now()).getElements(), - contains(new KIterVMatcher( - KV.>of("foo", ImmutableSet.of(-1, 1, 3)), keyCoder))); + contains( + new KeyedWorkItemMatcher( + KeyedWorkItems.elementsWorkItem( + "foo", + ImmutableSet.of( + WindowedValue.valueInGlobalWindow(-1), + WindowedValue.valueInGlobalWindow(1), + WindowedValue.valueInGlobalWindow(3))), + keyCoder))); assertThat( barBundle.commit(Instant.now()).getElements(), - contains(new KIterVMatcher( - KV.>of("bar", ImmutableSet.of(12, 22)), keyCoder))); + contains( + new KeyedWorkItemMatcher( + KeyedWorkItems.elementsWorkItem( + "bar", + ImmutableSet.of( + WindowedValue.valueInGlobalWindow(12), + WindowedValue.valueInGlobalWindow(22))), + keyCoder))); assertThat( bazBundle.commit(Instant.now()).getElements(), - contains(new KIterVMatcher( - KV.>of("baz", ImmutableSet.of(Integer.MAX_VALUE)), - keyCoder))); + contains( + new KeyedWorkItemMatcher( + KeyedWorkItems.elementsWorkItem( + "baz", + ImmutableSet.of(WindowedValue.valueInGlobalWindow(Integer.MAX_VALUE))), + keyCoder))); } - private static class KIterVMatcher extends BaseMatcher>>> { - private final KV> myKv; + private KV> gwValue(KV kv) { + return KV.of(kv.getKey(), WindowedValue.valueInGlobalWindow(kv.getValue())); + } + + private static class KeyedWorkItemMatcher + extends BaseMatcher>> { + private final KeyedWorkItem myWorkItem; private final Coder keyCoder; - public KIterVMatcher(KV> myKv, Coder keyCoder) { - this.myKv = myKv; + public KeyedWorkItemMatcher(KeyedWorkItem myWorkItem, Coder keyCoder) { + this.myWorkItem = myWorkItem; this.keyCoder = keyCoder; } @@ -123,20 +149,20 @@ public boolean matches(Object item) { if (item == null || !(item instanceof WindowedValue)) { return false; } - @SuppressWarnings("unchecked") - WindowedValue>> that = (WindowedValue>>) item; - Multiset myValues = HashMultiset.create(); - Multiset thatValues = HashMultiset.create(); - for (V value : myKv.getValue()) { + WindowedValue> that = (WindowedValue>) item; + Multiset> myValues = HashMultiset.create(); + Multiset> thatValues = HashMultiset.create(); + for (WindowedValue value : myWorkItem.elementsIterable()) { myValues.add(value); } - for (V value : that.getValue().getValue()) { + for (WindowedValue value : that.getValue().elementsIterable()) { thatValues.add(value); } try { return myValues.equals(thatValues) - && keyCoder.structuralValue(myKv.getKey()) - .equals(keyCoder.structuralValue(that.getValue().getKey())); + && keyCoder + .structuralValue(myWorkItem.key()) + .equals(keyCoder.structuralValue(that.getValue().key())); } catch (Exception e) { return false; } @@ -144,11 +170,11 @@ public boolean matches(Object item) { @Override public void describeTo(Description description) { - description.appendText("KV> containing key ") - .appendValue(myKv.getKey()) + description + .appendText("KeyedWorkItem containing key ") + .appendValue(myWorkItem.key()) .appendText(" and values ") - .appendValueList("[", ", ", "]", myKv.getValue()); + .appendValueList("[", ", ", "]", myWorkItem.elementsIterable()); } } } - From 6926d8ee1d5fa2afece0024e64e18dc06ec857c4 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Tue, 23 Feb 2016 18:38:04 -0800 Subject: [PATCH 208/751] Proto2Coder: recompute the extension registry when mutated Proto2Coder's deprecated methods mutate the existing coder's extension host set, but it may already have been memoized. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115407399 --- .../cloud/dataflow/sdk/coders/Proto2Coder.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java index b107f37f88..56ec0c7d7b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java @@ -198,6 +198,11 @@ public Proto2Coder addExtensionsFrom(Iterable> extensionHosts) { } extensionHostClasses.add(extensionHost); } + // The memoized extension registry needs to be recomputed because we have mutated this object. + synchronized (this) { + memoizedExtensionRegistry = null; + getExtensionRegistry(); + } return this; } @@ -293,18 +298,19 @@ private Parser getParser() { private transient ExtensionRegistry memoizedExtensionRegistry; - private ExtensionRegistry getExtensionRegistry() { + private synchronized ExtensionRegistry getExtensionRegistry() { if (memoizedExtensionRegistry == null) { - memoizedExtensionRegistry = ExtensionRegistry.newInstance(); + ExtensionRegistry registry = ExtensionRegistry.newInstance(); for (Class extensionHost : extensionHostClasses) { try { extensionHost .getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class) - .invoke(null, memoizedExtensionRegistry); + .invoke(null, registry); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalStateException(e); } } + memoizedExtensionRegistry = registry.getUnmodifiable(); } return memoizedExtensionRegistry; } From 6613031bfed700567bdc2d4eab6b754c4392ce77 Mon Sep 17 00:00:00 2001 From: peihe Date: Tue, 23 Feb 2016 18:49:00 -0800 Subject: [PATCH 209/751] Support CombineFnWithContext in GroupAlsoByWindows This requires plumbing pipeline options and side inputs to State API, including: 1. Adding bindKeyedCombiningValueWithContext() to StateTag.java 2. Adding StateContext to StateInternals.java 3. Plumbing through the remaining files ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115408034 --- .../sdk/util/CombineContextFactory.java | 18 +++ .../dataflow/sdk/util/CombineFnUtil.java | 97 +++++++++++++ .../dataflow/sdk/util/DoFnRunnerBase.java | 5 + .../GroupAlsoByWindowViaWindowSetDoFn.java | 3 +- ...GroupAlsoByWindowsViaOutputBufferDoFn.java | 3 +- .../sdk/util/ReduceFnContextFactory.java | 64 ++++---- .../dataflow/sdk/util/ReduceFnRunner.java | 6 +- .../dataflow/sdk/util/SystemReduceFn.java | 19 ++- .../sdk/util/TriggerContextFactory.java | 4 +- .../dataflow/sdk/util/TriggerRunner.java | 9 +- .../dataflow/sdk/util/WindowingInternals.java | 5 + .../CopyOnAccessInMemoryStateInternals.java | 72 ++++++--- .../util/state/InMemoryStateInternals.java | 35 ++++- .../dataflow/sdk/util/state/StateContext.java | 41 ++++++ .../sdk/util/state/StateContexts.java | 107 ++++++++++++++ .../sdk/util/state/StateInternals.java | 7 + .../dataflow/sdk/util/state/StateTable.java | 8 +- .../dataflow/sdk/util/state/StateTag.java | 7 + .../dataflow/sdk/util/state/StateTags.java | 83 ++++++++++- .../dataflow/sdk/util/CombineFnUtilTest.java | 62 ++++++++ .../dataflow/sdk/util/ReduceFnRunnerTest.java | 137 +++++++++++++++++- .../dataflow/sdk/util/ReduceFnTester.java | 58 +++++++- 22 files changed, 763 insertions(+), 87 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java index bf09587367..6f2b89b84d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.state.StateContext; import com.google.cloud.dataflow.sdk.values.PCollectionView; /** @@ -62,6 +63,23 @@ public T sideInput(PCollectionView view) { }; } + /** + * Returns a {@code Combine.Context} that wraps a {@link StateContext}. + */ + public static Context createFromStateContext(final StateContext c) { + return new Context() { + @Override + public PipelineOptions getPipelineOptions() { + return c.getPipelineOptions(); + } + + @Override + public T sideInput(PCollectionView view) { + return c.sideInput(view); + } + }; + } + /** * Returns a {@code Combine.Context} from {@code PipelineOptions}, {@code SideInputReader}, * and the main input window. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java new file mode 100644 index 0000000000..6201e6e7bb --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java @@ -0,0 +1,97 @@ + +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderRegistry; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.util.state.StateContext; + +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectOutputStream; + +/** + * Static utility methods that create combine function instances. + */ +public class CombineFnUtil { + /** + * Returns the partial application of the {@link KeyedCombineFnWithContext} to a specific + * context to produce a {@link KeyedCombineFn}. + * + *

    The returned {@link KeyedCombineFn} cannot be serialized. + */ + public static KeyedCombineFn + bindContext( + KeyedCombineFnWithContext combineFn, + StateContext stateContext) { + Context context = CombineContextFactory.createFromStateContext(stateContext); + return new NonSerializableBoundedKeyedCombineFn<>(combineFn, context); + } + + private static class NonSerializableBoundedKeyedCombineFn + extends KeyedCombineFn { + private final KeyedCombineFnWithContext combineFn; + private final Context context; + + private NonSerializableBoundedKeyedCombineFn( + KeyedCombineFnWithContext combineFn, + Context context) { + this.combineFn = combineFn; + this.context = context; + } + @Override + public AccumT createAccumulator(K key) { + return combineFn.createAccumulator(key, context); + } + @Override + public AccumT addInput(K key, AccumT accumulator, InputT value) { + return combineFn.addInput(key, accumulator, value, context); + } + @Override + public AccumT mergeAccumulators(K key, Iterable accumulators) { + return combineFn.mergeAccumulators(key, accumulators, context); + } + @Override + public OutputT extractOutput(K key, AccumT accumulator) { + return combineFn.extractOutput(key, accumulator, context); + } + @Override + public AccumT compact(K key, AccumT accumulator) { + return combineFn.compact(key, accumulator, context); + } + @Override + public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, + Coder inputCoder) throws CannotProvideCoderException { + return combineFn.getAccumulatorCoder(registry, keyCoder, inputCoder); + } + @Override + public Coder getDefaultOutputCoder(CoderRegistry registry, Coder keyCoder, + Coder inputCoder) throws CannotProvideCoderException { + return combineFn.getDefaultOutputCoder(registry, keyCoder, inputCoder); + } + + private void writeObject(@SuppressWarnings("unused") ObjectOutputStream out) + throws IOException { + throw new NotSerializableException( + "Cannot serialize the CombineFn resulting from CombineFnUtil.bindContext."); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index 25ead03bce..04ec59f57d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -540,6 +540,11 @@ public void writePCollectionViewData( public StateInternals stateInternals() { return context.stepContext.stateInternals(); } + + @Override + public T sideInput(PCollectionView view, BoundedWindow mainInputWindow) { + return context.sideInput(view, mainInputWindow); + } }; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java index ac2df24fec..f6246d1641 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java @@ -77,7 +77,8 @@ public void processElement(ProcessContext c) throws Exception { timerInternals, c.windowingInternals(), droppedDueToClosedWindow, - reduceFn); + reduceFn, + c.getPipelineOptions()); for (TimerData timer : element.timersIterable()) { reduceFnRunner.onTimer(timer); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java index 1d1afe38d8..d394e81a0e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java @@ -67,7 +67,8 @@ public void processElement( timerInternals, c.windowingInternals(), droppedDueToClosedWindow, - reduceFn); + reduceFn, + c.getPipelineOptions()); Iterable>> chunks = Iterables.partition(c.element().getValue(), 1000); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index b2ab752edf..bdbaf1098e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; @@ -25,6 +26,8 @@ import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; +import com.google.cloud.dataflow.sdk.util.state.StateContext; +import com.google.cloud.dataflow.sdk.util.state.StateContexts; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; @@ -51,19 +54,24 @@ public interface OnTriggerCallbacks { private final K key; private final ReduceFn reduceFn; private final WindowingStrategy windowingStrategy; - private StateInternals stateInternals; - private ActiveWindowSet activeWindows; - private TimerInternals timerInternals; + private final StateInternals stateInternals; + private final ActiveWindowSet activeWindows; + private final TimerInternals timerInternals; + private final WindowingInternals windowingInternals; + private final PipelineOptions options; ReduceFnContextFactory(K key, ReduceFn reduceFn, WindowingStrategy windowingStrategy, StateInternals stateInternals, - ActiveWindowSet activeWindows, TimerInternals timerInternals) { + ActiveWindowSet activeWindows, TimerInternals timerInternals, + WindowingInternals windowingInternals, PipelineOptions options) { this.key = key; this.reduceFn = reduceFn; this.windowingStrategy = windowingStrategy; this.stateInternals = stateInternals; this.activeWindows = activeWindows; this.timerInternals = timerInternals; + this.windowingInternals = windowingInternals; + this.options = options; } /** Where should we look for state associated with a given window? */ @@ -74,24 +82,25 @@ public static enum StateStyle { RENAMED } - private StateAccessorImpl stateContext(W window, StateStyle style) { + private StateAccessorImpl stateAccessor(W window, StateStyle style) { return new StateAccessorImpl( activeWindows, windowingStrategy.getWindowFn().windowCoder(), - stateInternals, window, style); + stateInternals, StateContexts.createFromComponents(options, windowingInternals, window), + style); } public ReduceFn.Context base(W window, StateStyle style) { - return new ContextImpl(stateContext(window, style)); + return new ContextImpl(stateAccessor(window, style)); } public ReduceFn.ProcessValueContext forValue( W window, InputT value, Instant timestamp, StateStyle style) { - return new ProcessValueContextImpl(stateContext(window, style), value, timestamp); + return new ProcessValueContextImpl(stateAccessor(window, style), value, timestamp); } public ReduceFn.OnTriggerContext forTrigger(W window, ReadableState pane, StateStyle style, OnTriggerCallbacks callbacks) { - return new OnTriggerContextImpl(stateContext(window, style), pane, callbacks); + return new OnTriggerContextImpl(stateAccessor(window, style), pane, callbacks); } public ReduceFn.OnMergeContext forMerge( @@ -150,20 +159,20 @@ static class StateAccessorImpl implements StateAcces protected final ActiveWindowSet activeWindows; - protected final W window; + protected final StateContext context; protected final StateNamespace windowNamespace; protected final Coder windowCoder; protected final StateInternals stateInternals; protected final StateStyle style; public StateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, - StateInternals stateInternals, W window, StateStyle style) { + StateInternals stateInternals, StateContext context, StateStyle style) { this.activeWindows = activeWindows; this.windowCoder = windowCoder; this.stateInternals = stateInternals; - this.window = checkNotNull(window); - this.windowNamespace = namespaceFor(window); + this.context = checkNotNull(context); + this.windowNamespace = namespaceFor(context.window()); this.style = style; } @@ -176,7 +185,7 @@ protected StateNamespace windowNamespace() { } W window() { - return window; + return context.window(); } StateNamespace namespace() { @@ -187,10 +196,10 @@ StateNamespace namespace() { public StateT access(StateTag address) { switch (style) { case DIRECT: - return stateInternals.state(windowNamespace(), address); + return stateInternals.state(windowNamespace(), address, context); case RENAMED: return stateInternals.state( - namespaceFor(activeWindows.writeStateAddress(window)), address); + namespaceFor(activeWindows.writeStateAddress(context.window())), address, context); } throw new RuntimeException(); // cases are exhaustive. } @@ -203,7 +212,8 @@ static class MergingStateAccessorImpl public MergingStateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, StateInternals stateInternals, StateStyle style, Collection activeToBeMerged, W mergeResult) { - super(activeWindows, windowCoder, stateInternals, mergeResult, style); + super(activeWindows, windowCoder, stateInternals, + StateContexts.windowOnly(mergeResult), style); this.activeToBeMerged = activeToBeMerged; } @@ -211,11 +221,13 @@ public MergingStateAccessorImpl(ActiveWindowSet activeWindows, Coder windo public StateT access(StateTag address) { switch (style) { case DIRECT: - return stateInternals.state(windowNamespace(), address); + return stateInternals.state(windowNamespace(), address, context); case RENAMED: return stateInternals.state( - namespaceFor(activeWindows.mergedWriteStateAddress(activeToBeMerged, window)), - address); + namespaceFor(activeWindows.mergedWriteStateAddress( + activeToBeMerged, context.window())), + address, + context); } throw new RuntimeException(); // cases are exhaustive. } @@ -235,7 +247,7 @@ public Map accessInEachMergingWindow( break; } Preconditions.checkNotNull(namespace); // cases are exhaustive. - builder.put(mergingWindow, stateInternals.state(namespace, address)); + builder.put(mergingWindow, stateInternals.state(namespace, address, context)); } return builder.build(); } @@ -245,19 +257,21 @@ static class PremergingStateAccessorImpl extends StateAccessorImpl implements MergingStateAccessor { public PremergingStateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, StateInternals stateInternals, W window) { - super(activeWindows, windowCoder, stateInternals, window, StateStyle.RENAMED); + super(activeWindows, windowCoder, stateInternals, + StateContexts.windowOnly(window), StateStyle.RENAMED); } Collection mergingWindows() { - return activeWindows.readStateAddresses(window); + return activeWindows.readStateAddresses(context.window()); } @Override public Map accessInEachMergingWindow( StateTag address) { ImmutableMap.Builder builder = ImmutableMap.builder(); - for (W stateAddressWindow : activeWindows.readStateAddresses(window)) { - StateT stateForWindow = stateInternals.state(namespaceFor(stateAddressWindow), address); + for (W stateAddressWindow : activeWindows.readStateAddresses(context.window())) { + StateT stateForWindow = + stateInternals.state(namespaceFor(stateAddressWindow), address, context); builder.put(stateAddressWindow, stateForWindow); } return builder.build(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index ec83688fb4..fe5c474210 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -15,6 +15,7 @@ */ package com.google.cloud.dataflow.sdk.util; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; @@ -203,7 +204,8 @@ public ReduceFnRunner( TimerInternals timerInternals, WindowingInternals> windowingInternals, Aggregator droppedDueToClosedWindow, - ReduceFn reduceFn) { + ReduceFn reduceFn, + PipelineOptions options) { this.key = key; this.timerInternals = timerInternals; this.paneInfoTracker = new PaneInfoTracker(timerInternals); @@ -224,7 +226,7 @@ public ReduceFnRunner( this.contextFactory = new ReduceFnContextFactory(key, reduceFn, this.windowingStrategy, - stateInternals, this.activeWindows, timerInternals); + stateInternals, this.activeWindows, timerInternals, windowingInternals, options); this.watermarkHold = new WatermarkHold<>(timerInternals, windowingStrategy); this.triggerRunner = diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java index d5d912672d..16657925e3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java @@ -15,12 +15,11 @@ */ package com.google.cloud.dataflow.sdk.util; -import static com.google.common.base.Preconditions.checkArgument; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; @@ -74,15 +73,19 @@ public void onMerge(OnMergeContext c) throws Exception { AccumT, OutputT, W> combining( final Coder keyCoder, final AppliedCombineFn combineFn) { - checkArgument( - !(combineFn.getFn() instanceof RequiresContextInternal), - "Combiner lifting is not supported for combine functions with contexts: %s", - combineFn.getFn().getClass().getName()); - final StateTag> bufferTag = - StateTags.makeSystemTagInternal( + final StateTag> bufferTag; + if (combineFn.getFn() instanceof KeyedCombineFnWithContext) { + bufferTag = StateTags.makeSystemTagInternal( + StateTags.keyedCombiningValueWithContext( + BUFFER_NAME, combineFn.getAccumulatorCoder(), + (KeyedCombineFnWithContext) combineFn.getFn())); + + } else { + bufferTag = StateTags.makeSystemTagInternal( StateTags.keyedCombiningValue( BUFFER_NAME, combineFn.getAccumulatorCoder(), (KeyedCombineFn) combineFn.getFn())); + } return new SystemReduceFn(bufferTag) { @Override public void prefetchOnMerge(MergingStateAccessor state) throws Exception { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 87e8b00f58..64ff402a9a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -80,11 +80,11 @@ public Trigger.OnMergeContext createOnMergeContext(W window, Timers timers, return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, finishedSets); } - public StateAccessor createStateContext(W window, ExecutableTrigger trigger) { + public StateAccessor createStateAccessor(W window, ExecutableTrigger trigger) { return new StateAccessorImpl(window, trigger); } - public MergingStateAccessor createMergingStateContext( + public MergingStateAccessor createMergingStateAccessor( W mergeResult, Collection mergingWindows, ExecutableTrigger trigger) { return new MergingStateAccessorImpl(trigger, mergingWindows, mergeResult); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index 1b78ddc5b1..dcfd03516b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -91,14 +91,15 @@ public void prefetchForValue(W window, StateAccessor state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).readLater(); } - rootTrigger.getSpec().prefetchOnElement(contextFactory.createStateContext(window, rootTrigger)); + rootTrigger.getSpec().prefetchOnElement( + contextFactory.createStateAccessor(window, rootTrigger)); } public void prefetchOnFire(W window, StateAccessor state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).readLater(); } - rootTrigger.getSpec().prefetchOnFire(contextFactory.createStateContext(window, rootTrigger)); + rootTrigger.getSpec().prefetchOnFire(contextFactory.createStateAccessor(window, rootTrigger)); } public void prefetchShouldFire(W window, StateAccessor state) { @@ -106,7 +107,7 @@ public void prefetchShouldFire(W window, StateAccessor state) { state.access(FINISHED_BITS_TAG).readLater(); } rootTrigger.getSpec().prefetchShouldFire( - contextFactory.createStateContext(window, rootTrigger)); + contextFactory.createStateAccessor(window, rootTrigger)); } /** @@ -130,7 +131,7 @@ public void prefetchForMerge( value.readLater(); } } - rootTrigger.getSpec().prefetchOnMerge(contextFactory.createMergingStateContext( + rootTrigger.getSpec().prefetchOnMerge(contextFactory.createMergingStateAccessor( window, mergingWindows, rootTrigger)); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java index 9ffdbee35f..12fcd532a2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java @@ -74,4 +74,9 @@ void writePCollectionViewData( TupleTag tag, Iterable> data, Coder elemCoder) throws IOException; + + /** + * Return the value of the side input for the window of a main input element. + */ + T sideInput(PCollectionView view, BoundedWindow mainInputWindow); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java index 19e45d6f00..3683b74d9a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java @@ -20,8 +20,10 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; +import com.google.cloud.dataflow.sdk.util.CombineFnUtil; import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals.InMemoryState; import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; import com.google.common.base.Optional; @@ -97,7 +99,13 @@ public Instant getEarliestWatermarkHold() { @Override public T state(StateNamespace namespace, StateTag address) { - return table.get(namespace, address); + return state(namespace, address, StateContexts.nullContext()); + } + + @Override + public T state( + StateNamespace namespace, StateTag address, StateContext c) { + return table.get(namespace, address, c); } @Override @@ -220,12 +228,12 @@ private void clearEmpty() { } @Override - protected StateBinder binderForNamespace(final StateNamespace namespace) { - return binderFactory.forNamespace(namespace); + protected StateBinder binderForNamespace(final StateNamespace namespace, StateContext c) { + return binderFactory.forNamespace(namespace, c); } private static interface StateBinderFactory { - StateBinder forNamespace(StateNamespace namespace); + StateBinder forNamespace(StateNamespace namespace, StateContext c); } /** @@ -246,7 +254,7 @@ private boolean containedInUnderlying(StateNamespace namespace, StateTag forNamespace(final StateNamespace namespace) { + public StateBinder forNamespace(final StateNamespace namespace, final StateContext c) { return new StateBinder() { @Override public WatermarkHoldState bindWatermark( @@ -256,7 +264,7 @@ public WatermarkHoldState bindWatermark( @SuppressWarnings("unchecked") InMemoryState> existingState = (InMemoryStateInternals.InMemoryState>) - underlying.get().get(namespace, address); + underlying.get().get(namespace, address, c); return existingState.copy(); } else { return new InMemoryStateInternals.InMemoryWatermarkHold<>( @@ -271,7 +279,7 @@ public ValueState bindValue( @SuppressWarnings("unchecked") InMemoryState> existingState = (InMemoryStateInternals.InMemoryState>) - underlying.get().get(namespace, address); + underlying.get().get(namespace, address, c); return existingState.copy(); } else { return new InMemoryStateInternals.InMemoryValue<>(); @@ -289,7 +297,7 @@ public ValueState bindValue( existingState = ( InMemoryStateInternals .InMemoryState>) underlying.get().get(namespace, address); + OutputT>>) underlying.get().get(namespace, address, c); return existingState.copy(); } else { return new InMemoryStateInternals.InMemoryCombiningValue<>( @@ -304,7 +312,7 @@ public BagState bindBag( @SuppressWarnings("unchecked") InMemoryState> existingState = (InMemoryStateInternals.InMemoryState>) - underlying.get().get(namespace, address); + underlying.get().get(namespace, address, c); return existingState.copy(); } else { return new InMemoryStateInternals.InMemoryBag<>(); @@ -323,12 +331,22 @@ public BagState bindBag( existingState = ( InMemoryStateInternals .InMemoryState>) underlying.get().get(namespace, address); + OutputT>>) underlying.get().get(namespace, address, c); return existingState.copy(); } else { return new InMemoryStateInternals.InMemoryCombiningValue<>(key, combineFn); } } + + @Override + public AccumulatorCombiningState + bindKeyedCombiningValueWithContext( + StateTag> address, + Coder accumCoder, + KeyedCombineFnWithContext combineFn) { + return bindKeyedCombiningValue( + address, accumCoder, CombineFnUtil.bindContext(combineFn, c)); + } }; } } @@ -354,7 +372,8 @@ public Instant readThroughAndGetEarliestHold(StateTable readTo) { // Only read through non-cleared values to ensure that completed windows are // eventually discarded, and remember the earliest watermark hold from among those // values. - State state = readTo.get(namespace, existingState.getKey()); + State state = + readTo.get(namespace, existingState.getKey(), StateContexts.nullContext()); if (state instanceof WatermarkHoldState) { Instant hold = ((WatermarkHoldState) state).read(); if (hold != null && hold.isBefore(earliestHold)) { @@ -368,19 +387,19 @@ public Instant readThroughAndGetEarliestHold(StateTable readTo) { } @Override - public StateBinder forNamespace(final StateNamespace namespace) { + public StateBinder forNamespace(final StateNamespace namespace, final StateContext c) { return new StateBinder() { @Override public WatermarkHoldState bindWatermark( StateTag> address, OutputTimeFn outputTimeFn) { - return underlying.get(namespace, address); + return underlying.get(namespace, address, c); } @Override public ValueState bindValue( StateTag> address, Coder coder) { - return underlying.get(namespace, address); + return underlying.get(namespace, address, c); } @Override @@ -388,13 +407,13 @@ public ValueState bindValue( bindCombiningValue( StateTag> address, Coder accumCoder, CombineFn combineFn) { - return underlying.get(namespace, address); + return underlying.get(namespace, address, c); } @Override public BagState bindBag( StateTag> address, Coder elemCoder) { - return underlying.get(namespace, address); + return underlying.get(namespace, address, c); } @Override @@ -403,24 +422,33 @@ public BagState bindBag( StateTag> address, Coder accumCoder, KeyedCombineFn combineFn) { - return underlying.get(namespace, address); + return underlying.get(namespace, address, c); + } + + @Override + public AccumulatorCombiningState + bindKeyedCombiningValueWithContext( + StateTag> address, + Coder accumCoder, + KeyedCombineFnWithContext combineFn) { + return bindKeyedCombiningValue( + address, accumCoder, CombineFnUtil.bindContext(combineFn, c)); } }; } } private static class InMemoryStateBinderFactory implements StateBinderFactory { - private final InMemoryStateInternals.InMemoryStateBinder inMemoryStateBinder; + private final K key; public InMemoryStateBinderFactory(K key) { - inMemoryStateBinder = new InMemoryStateInternals.InMemoryStateBinder<>(key); + this.key = key; } @Override - public StateBinder forNamespace(StateNamespace namespace) { - return inMemoryStateBinder; + public StateBinder forNamespace(StateNamespace namespace, StateContext c) { + return new InMemoryStateInternals.InMemoryStateBinder<>(key, c); } } } - } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java index 4a2555f358..8404801260 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java @@ -20,8 +20,10 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; +import com.google.cloud.dataflow.sdk.util.CombineFnUtil; import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; import org.joda.time.Instant; @@ -62,8 +64,8 @@ interface InMemoryState> { protected final StateTable inMemoryState = new StateTable() { @Override - protected StateBinder binderForNamespace(final StateNamespace namespace) { - return new InMemoryStateBinder(key); + protected StateBinder binderForNamespace(StateNamespace namespace, StateContext c) { + return new InMemoryStateBinder(key, c); } }; @@ -81,7 +83,13 @@ protected boolean isEmptyForTesting(State state) { @Override public T state(StateNamespace namespace, StateTag address) { - return inMemoryState.get(namespace, address); + return inMemoryState.get(namespace, address, StateContexts.nullContext()); + } + + @Override + public T state( + StateNamespace namespace, StateTag address, final StateContext c) { + return inMemoryState.get(namespace, address, c); } /** @@ -89,9 +97,11 @@ public T state(StateNamespace namespace, StateTag implements StateBinder { private final K key; + private final StateContext c; - InMemoryStateBinder(K key) { + InMemoryStateBinder(K key, StateContext c) { this.key = key; + this.c = c; } @Override @@ -109,8 +119,8 @@ public BagState bindBag( @Override public AccumulatorCombiningState bindCombiningValue( - StateTag> - address, Coder accumCoder, + StateTag> address, + Coder accumCoder, final CombineFn combineFn) { return new InMemoryCombiningValue(key, combineFn.asKeyedFn()); } @@ -125,11 +135,20 @@ public WatermarkHoldState bindWatermark( @Override public AccumulatorCombiningState bindKeyedCombiningValue( - StateTag> - address, Coder accumCoder, + StateTag> address, + Coder accumCoder, KeyedCombineFn combineFn) { return new InMemoryCombiningValue(key, combineFn); } + + @Override + public AccumulatorCombiningState + bindKeyedCombiningValueWithContext( + StateTag> address, + Coder accumCoder, + KeyedCombineFnWithContext combineFn) { + return bindKeyedCombiningValue(address, accumCoder, CombineFnUtil.bindContext(combineFn, c)); + } } static final class InMemoryValue implements ValueState, InMemoryState> { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java new file mode 100644 index 0000000000..96387d8508 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.state; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.values.PCollectionView; + +/** + * Information accessible the state API. + */ +public interface StateContext { + /** + * Returns the {@code PipelineOptions} specified with the + * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner}. + */ + public abstract PipelineOptions getPipelineOptions(); + + /** + * Returns the value of the side input for the corresponding state window. + */ + public abstract T sideInput(PCollectionView view); + + /** + * Returns the window corresponding to the state. + */ + public abstract W window(); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java new file mode 100644 index 0000000000..e301d438cd --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.state; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowingInternals; +import com.google.cloud.dataflow.sdk.values.PCollectionView; + +import javax.annotation.Nullable; + +/** + * Factory that produces {@link StateContext} based on different inputs. + */ +public class StateContexts { + private static final StateContext NULL_CONTEXT = + new StateContext() { + @Override + public PipelineOptions getPipelineOptions() { + throw new IllegalArgumentException("cannot call getPipelineOptions() in a null context"); + } + + @Override + public T sideInput(PCollectionView view) { + throw new IllegalArgumentException("cannot call sideInput() in a null context"); + } + + @Override + public BoundedWindow window() { + throw new IllegalArgumentException("cannot call window() in a null context"); + }}; + + /** + * Returns a fake {@link StateContext}. + */ + @SuppressWarnings("unchecked") + public static StateContext nullContext() { + return (StateContext) NULL_CONTEXT; + } + + /** + * Returns a {@link StateContext} that only contains the state window. + */ + public static StateContext windowOnly(final W window) { + return new StateContext() { + @Override + public PipelineOptions getPipelineOptions() { + throw new IllegalArgumentException( + "cannot call getPipelineOptions() in a window only context"); + } + @Override + public T sideInput(PCollectionView view) { + throw new IllegalArgumentException("cannot call sideInput() in a window only context"); + } + @Override + public W window() { + return window; + } + }; + } + + /** + * Returns a {@link StateContext} from {@code PipelineOptions}, {@link WindowingInternals}, + * and the state window. + */ + public static StateContext createFromComponents( + @Nullable final PipelineOptions options, + final WindowingInternals windowingInternals, + final W window) { + @SuppressWarnings("unchecked") + StateContext typedNullContext = (StateContext) NULL_CONTEXT; + if (options == null) { + return typedNullContext; + } else { + return new StateContext() { + + @Override + public PipelineOptions getPipelineOptions() { + return options; + } + + @Override + public T sideInput(PCollectionView view) { + return windowingInternals.sideInput(view, window); + } + + @Override + public W window() { + return window; + } + }; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java index 78aed87009..b31afb4698 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java @@ -45,4 +45,11 @@ public interface StateInternals { * Return the state associated with {@code address} in the specified {@code namespace}. */ T state(StateNamespace namespace, StateTag address); + + /** + * Return the state associated with {@code address} in the specified {@code namespace} + * with the {@link StateContext}. + */ + T state( + StateNamespace namespace, StateTag address, StateContext c); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java index 0f1209ac78..edd1dae279 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java @@ -40,11 +40,11 @@ public abstract class StateTable { /** * Gets the {@link State} in the specified {@link StateNamespace} with the specified {@link - * StateTag}, binding it using the {@link #binderForNamespace(StateNamespace)} if it is not + * StateTag}, binding it using the {@link #binderForNamespace} if it is not * already present in this {@link StateTable}. */ public StateT get( - StateNamespace namespace, StateTag tag) { + StateNamespace namespace, StateTag tag, StateContext c) { State storage = stateTable.get(namespace, tag); if (storage != null) { @SuppressWarnings("unchecked") @@ -52,7 +52,7 @@ public StateT get( return typedStorage; } - StateT typedStorage = tag.bind(binderForNamespace(namespace)); + StateT typedStorage = tag.bind(binderForNamespace(namespace, c)); stateTable.put(namespace, tag, typedStorage); return typedStorage; } @@ -85,5 +85,5 @@ public Set getNamespacesInUse() { * Provide the {@code StateBinder} to use for creating {@code Storage} instances * in the specified {@code namespace}. */ - protected abstract StateBinder binderForNamespace(StateNamespace namespace); + protected abstract StateBinder binderForNamespace(StateNamespace namespace, StateContext c); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java index 2924763b89..c87bdb788c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; @@ -63,6 +64,12 @@ public interface StateBinder { StateTag> address, Coder accumCoder, KeyedCombineFn combineFn); + AccumulatorCombiningState + bindKeyedCombiningValueWithContext( + StateTag> address, + Coder accumCoder, + KeyedCombineFnWithContext combineFn); + /** * Bind to a watermark {@link StateTag}. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index c1efb601b3..0cbaa52369 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.coders.CoderRegistry; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.common.base.MoreObjects; @@ -89,6 +90,24 @@ public static StateTag> value(String id, Coder valu return keyedCombiningValueInternal(id, accumCoder, combineFn); } + /** + * Create a state tag for values that use a {@link KeyedCombineFnWithContext} to automatically + * merge multiple {@code InputT}s into a single {@code OutputT}. The key provided to the + * {@link KeyedCombineFn} comes from the keyed {@link StateAccessor}, the context provided comes + * from the {@link StateContext}. + */ + public static + StateTag> + keyedCombiningValueWithContext( + String id, + Coder accumCoder, + KeyedCombineFnWithContext combineFn) { + return new KeyedCombiningValueWithContextStateTag( + new StructuredId(id), + accumCoder, + combineFn); + } + /** * Create a state tag for values that use a {@link CombineFn} to automatically merge * multiple {@code InputT}s into a single {@code OutputT}. @@ -337,9 +356,67 @@ private CombiningValueStateTag( } } + /** + * A state cell for values that are combined according to a {@link KeyedCombineFnWithContext}. + * + * @param the type of keys + * @param the type of input values + * @param type of mutable accumulator values + * @param type of output values + */ + private static class KeyedCombiningValueWithContextStateTag + extends StateTagBase> + implements SystemStateTag> { + + private final Coder accumCoder; + private final KeyedCombineFnWithContext combineFn; + + protected KeyedCombiningValueWithContextStateTag( + StructuredId id, + Coder accumCoder, + KeyedCombineFnWithContext combineFn) { + super(id); + this.combineFn = combineFn; + this.accumCoder = accumCoder; + } + + @Override + public AccumulatorCombiningState bind( + StateBinder visitor) { + return visitor.bindKeyedCombiningValueWithContext(this, accumCoder, combineFn); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof KeyedCombiningValueWithContextStateTag)) { + return false; + } + + KeyedCombiningValueWithContextStateTag that = + (KeyedCombiningValueWithContextStateTag) obj; + return Objects.equals(this.id, that.id) + && Objects.equals(this.accumCoder, that.accumCoder); + } + + @Override + public int hashCode() { + return Objects.hash(getClass(), id, accumCoder); + } + + @Override + public StateTag> asKind( + StateKind kind) { + return new KeyedCombiningValueWithContextStateTag<>( + id.asKind(kind), accumCoder, combineFn); + } + } /** - * A general purpose state cell for values of type {@code T}. + * A state cell for values that are combined according to a {@link KeyedCombineFn}. * * @param the type of keys * @param the type of input values @@ -355,9 +432,9 @@ private static class KeyedCombiningValueStateTag protected KeyedCombiningValueStateTag( StructuredId id, - Coder accumCoder, KeyedCombineFn combineFn) { + Coder accumCoder, KeyedCombineFn keyedCombineFn) { super(id); - this.keyedCombineFn = combineFn; + this.keyedCombineFn = keyedCombineFn; this.accumCoder = accumCoder; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java new file mode 100644 index 0000000000..978ee50f44 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.withSettings; + +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.util.state.StateContexts; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.NotSerializableException; +import java.io.ObjectOutputStream; + +/** + * Unit tests for {@link CombineFnUtil}. + */ +@RunWith(JUnit4.class) +public class CombineFnUtilTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + KeyedCombineFnWithContext mockCombineFn; + + @SuppressWarnings("unchecked") + @Before + public void setUp() { + mockCombineFn = mock(KeyedCombineFnWithContext.class, withSettings().serializable()); + } + + @Test + public void testNonSerializable() throws Exception { + expectedException.expect(NotSerializableException.class); + expectedException.expectMessage( + "Cannot serialize the CombineFn resulting from CombineFnUtil.bindContext."); + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(buffer); + oos.writeObject(CombineFnUtil.bindContext(mockCombineFn, StateContexts.nullContext())); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index ddc33b8e3f..c85b1ca4a5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -25,18 +25,26 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; import com.google.cloud.dataflow.sdk.WindowMatchers; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterEach; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterFirst; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; @@ -47,7 +55,9 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; +import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.common.base.Preconditions; import org.joda.time.Duration; import org.joda.time.Instant; @@ -55,12 +65,14 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import java.util.Iterator; import java.util.List; /** @@ -71,8 +83,10 @@ */ @RunWith(JUnit4.class) public class ReduceFnRunnerTest { - @Mock + @Mock private SideInputReader mockSideInputReader; private Trigger mockTrigger; + private PCollectionView mockView; + private IntervalWindow firstWindow; private static Trigger.TriggerContext anyTriggerContext() { @@ -85,7 +99,17 @@ private static Trigger.OnElementContext anyElementContext() { @Before public void setUp() { MockitoAnnotations.initMocks(this); + + @SuppressWarnings("unchecked") + Trigger mockTriggerUnchecked = + mock(Trigger.class, withSettings().serializable()); + mockTrigger = mockTriggerUnchecked; when(mockTrigger.buildTrigger()).thenReturn(mockTrigger); + + @SuppressWarnings("unchecked") + PCollectionView mockViewUnchecked = + mock(PCollectionView.class, withSettings().serializable()); + mockView = mockViewUnchecked; firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); } @@ -227,6 +251,53 @@ public void testOnElementCombiningAccumulating() throws Exception { tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); } + @Test + public void testOnElementCombiningWithContext() throws Exception { + Integer expectedValue = 5; + WindowingStrategy windowingStrategy = WindowingStrategy + .of(FixedWindows.of(Duration.millis(10))) + .withTrigger(mockTrigger) + .withMode(AccumulationMode.DISCARDING_FIRED_PANES) + .withAllowedLateness(Duration.millis(100)); + + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + options.setValue(5); + + when(mockSideInputReader.contains(Matchers.>any())).thenReturn(true); + when(mockSideInputReader.get( + Matchers.>any(), any(BoundedWindow.class))).thenReturn(5); + + @SuppressWarnings({"rawtypes", "unchecked", "unused"}) + Object suppressWarningsVar = when(mockView.getWindowingStrategyInternal()) + .thenReturn((WindowingStrategy) windowingStrategy); + + SumAndVerifyContextFn combineFn = new SumAndVerifyContextFn(mockView, expectedValue); + // Test basic execution of a trigger using a non-combining window set and discarding mode. + ReduceFnTester tester = ReduceFnTester.combining( + windowingStrategy, combineFn.asKeyedFn(), + VarIntCoder.of(), options, mockSideInputReader); + + injectElement(tester, 2); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + injectElement(tester, 3); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + injectElement(tester, 4); + + // This element shouldn't be seen, because the trigger has finished + injectElement(tester, 6); + + assertThat( + tester.extractOutput(), + contains( + isSingleWindowedValue(equalTo(5), 2, 0, 10), + isSingleWindowedValue(equalTo(4), 4, 0, 10))); + assertTrue(tester.isMarkedFinished(firstWindow)); + tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); + } + @Test public void testWatermarkHoldAndLateData() throws Exception { // Test handling of late data. Specifically, ensure the watermark hold is correct. @@ -873,4 +944,68 @@ public void testProcessingTime() throws Exception { output.get(3), WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 3, 2))); } + + private static class SumAndVerifyContextFn extends CombineFnWithContext { + + private final PCollectionView view; + private final int expectedValue; + + private SumAndVerifyContextFn(PCollectionView view, int expectedValue) { + this.view = view; + this.expectedValue = expectedValue; + } + @Override + public int[] createAccumulator(Context c) { + Preconditions.checkArgument( + c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); + Preconditions.checkArgument(c.sideInput(view) == expectedValue); + return wrap(0); + } + + @Override + public int[] addInput(int[] accumulator, Integer input, Context c) { + Preconditions.checkArgument( + c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); + Preconditions.checkArgument(c.sideInput(view) == expectedValue); + accumulator[0] += input.intValue(); + return accumulator; + } + + @Override + public int[] mergeAccumulators(Iterable accumulators, Context c) { + Preconditions.checkArgument( + c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); + Preconditions.checkArgument(c.sideInput(view) == expectedValue); + Iterator iter = accumulators.iterator(); + if (!iter.hasNext()) { + return createAccumulator(c); + } else { + int[] running = iter.next(); + while (iter.hasNext()) { + running[0] += iter.next()[0]; + } + return running; + } + } + + @Override + public Integer extractOutput(int[] accumulator, Context c) { + Preconditions.checkArgument( + c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); + Preconditions.checkArgument(c.sideInput(view) == expectedValue); + return accumulator[0]; + } + + private int[] wrap(int value) { + return new int[] { value }; + } + } + + /** + * A {@link PipelineOptions} to test combining with context. + */ + public interface TestOptions extends PipelineOptions { + Integer getValue(); + void setValue(Integer value); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index bade9f915e..d4620a7827 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -26,9 +26,12 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; @@ -47,6 +50,7 @@ import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.common.base.Function; @@ -99,6 +103,7 @@ public class ReduceFnTester { private final Coder outputCoder; private final WindowingStrategy objectStrategy; private final ReduceFn reduceFn; + private final PipelineOptions options; /** * If true, the output watermark is automatically advanced to the latest possible @@ -118,7 +123,9 @@ public class ReduceFnTester { return new ReduceFnTester, W>( windowingStrategy, SystemReduceFn.buffering(VarIntCoder.of()), - IterableCoder.of(VarIntCoder.of())); + IterableCoder.of(VarIntCoder.of()), + PipelineOptionsFactory.create(), + NullSideInputReader.empty()); } public static ReduceFnTester, W> @@ -147,9 +154,30 @@ public class ReduceFnTester { return new ReduceFnTester( strategy, SystemReduceFn.combining(StringUtf8Coder.of(), fn), - outputCoder); + outputCoder, + PipelineOptionsFactory.create(), + NullSideInputReader.empty()); } + public static ReduceFnTester + combining(WindowingStrategy strategy, + KeyedCombineFnWithContext combineFn, + Coder outputCoder, + PipelineOptions options, + SideInputReader sideInputReader) throws Exception { + CoderRegistry registry = new CoderRegistry(); + registry.registerStandardCoders(); + AppliedCombineFn fn = + AppliedCombineFn.withInputCoder( + combineFn, registry, KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())); + + return new ReduceFnTester( + strategy, + SystemReduceFn.combining(StringUtf8Coder.of(), fn), + outputCoder, + options, + sideInputReader); + } public static ReduceFnTester combining(WindowFn windowFn, Trigger trigger, AccumulationMode mode, KeyedCombineFn combineFn, Coder outputCoder, @@ -163,17 +191,19 @@ public class ReduceFnTester { } private ReduceFnTester(WindowingStrategy wildcardStrategy, - ReduceFn reduceFn, Coder outputCoder) throws Exception { + ReduceFn reduceFn, Coder outputCoder, + PipelineOptions options, SideInputReader sideInputReader) throws Exception { @SuppressWarnings("unchecked") WindowingStrategy objectStrategy = (WindowingStrategy) wildcardStrategy; this.objectStrategy = objectStrategy; this.reduceFn = reduceFn; this.windowFn = objectStrategy.getWindowFn(); - this.windowingInternals = new TestWindowingInternals(); + this.windowingInternals = new TestWindowingInternals(sideInputReader); this.outputCoder = outputCoder; this.autoAdvanceOutputWatermark = true; - executableTrigger = wildcardStrategy.getTrigger(); + this.executableTrigger = wildcardStrategy.getTrigger(); + this.options = options; } public void setAutoAdvanceOutputWatermark(boolean autoAdvanceOutputWatermark) { @@ -193,7 +223,8 @@ ReduceFnRunner createRunner() { timerInternals, windowingInternals, droppedDueToClosedWindow, - reduceFn); + reduceFn, + options); } public ExecutableTrigger getTrigger() { @@ -432,6 +463,11 @@ public Instant earliestWatermarkHold() { */ private class TestWindowingInternals implements WindowingInternals> { private List>> outputs = new ArrayList<>(); + private SideInputReader sideInputReader; + + private TestWindowingInternals(SideInputReader sideInputReader) { + this.sideInputReader = sideInputReader; + } @Override public void outputWindowedValue(KV output, Instant timestamp, @@ -476,6 +512,16 @@ public StateInternals stateInternals() { (TestInMemoryStateInternals) stateInternals; return untypedStateInternals; } + + @Override + public T sideInput(PCollectionView view, BoundedWindow mainInputWindow) { + if (!sideInputReader.contains(view)) { + throw new IllegalArgumentException("calling sideInput() with unknown view"); + } + BoundedWindow sideInputWindow = + view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(mainInputWindow); + return sideInputReader.get(view, sideInputWindow); + } } private static class TestAssignContext From 87b28e7dd1b2f8ca31eb155cc5bad4f98717664b Mon Sep 17 00:00:00 2001 From: tgroh Date: Tue, 23 Feb 2016 19:12:37 -0800 Subject: [PATCH 210/751] Add InProcess Override for CreatePCollectionView Because windowing is used to retrieve values from a PCollectionView, the elements must go through a GroupByKey. Provide a PTransform override for use in the InProcess runner to apply global grouping by window and pane, and a WriteView primitive to store the contents of the view in a PCollectionView. Update the View PTransform to make the view it returns available outside of the application. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115409320 --- .../inprocess/InProcessPipelineRunner.java | 5 +- .../inprocess/ViewEvaluatorFactory.java | 69 ++++++++++++++++--- .../cloud/dataflow/sdk/transforms/View.java | 5 ++ .../inprocess/ViewEvaluatorFactoryTest.java | 33 +++++++-- 4 files changed, 96 insertions(+), 16 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 72642da122..26c5061f67 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -20,10 +20,12 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKey; +import com.google.cloud.dataflow.sdk.runners.inprocess.ViewEvaluatorFactory.InProcessCreatePCollectionView; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; @@ -60,6 +62,7 @@ public class InProcessPipelineRunner { defaultTransformOverrides = ImmutableMap., Class>builder() .put(GroupByKey.class, InProcessGroupByKey.class) + .put(CreatePCollectionView.class, InProcessCreatePCollectionView.class) .build(); private static Map, TransformEvaluatorFactory> defaultEvaluatorFactories = @@ -222,7 +225,7 @@ UncommittedBundle createKeyedBundle( * Create a bundle whose elements will be used in a PCollectionView. */ PCollectionViewWriter createPCollectionViewWriter( - PCollection input, PCollectionView output); + PCollection> input, PCollectionView output); /** * Get the options used by this {@link Pipeline}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java index 654652ca1a..f47cd1de98 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java @@ -15,11 +15,16 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.Values; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; @@ -30,6 +35,12 @@ /** * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the * {@link CreatePCollectionView} primitive {@link PTransform}. + * + *

    The {@link ViewEvaluatorFactory} produces {@link TransformEvaluator TransformEvaluators} for + * the {@link WriteView} {@link PTransform}, which is part of the + * {@link InProcessCreatePCollectionView} composite transform. This transform is an override for the + * {@link CreatePCollectionView} transform that applies windowing and triggers before the view is + * written. */ class ViewEvaluatorFactory implements TransformEvaluatorFactory { @SuppressWarnings({"rawtypes", "unchecked"}) @@ -42,19 +53,21 @@ public TransformEvaluator forApplication( (AppliedPTransform) application, evaluationContext); } - private TransformEvaluator createEvaluator( - final AppliedPTransform, PCollectionView, - CreatePCollectionView> application, + private TransformEvaluator> createEvaluator( + final AppliedPTransform>, PCollectionView, WriteView> + application, InProcessEvaluationContext context) { - PCollection input = application.getInput(); + PCollection> input = application.getInput(); final PCollectionViewWriter writer = context.createPCollectionViewWriter(input, application.getOutput()); - return new TransformEvaluator() { + return new TransformEvaluator>() { private final List> elements = new ArrayList<>(); @Override - public void processElement(WindowedValue element) { - elements.add(element); + public void processElement(WindowedValue> element) { + for (InT input : element.getValue()) { + elements.add(element.withValue(input)); + } } @Override @@ -64,5 +77,45 @@ public InProcessTransformResult finishBundle() { } }; } -} + /** + * An in-process override for {@link CreatePCollectionView}. + */ + public static class InProcessCreatePCollectionView + extends PTransform, PCollectionView> { + private final CreatePCollectionView og; + + private InProcessCreatePCollectionView(CreatePCollectionView og) { + this.og = og; + } + + @Override + public PCollectionView apply(PCollection input) { + return input.apply(WithKeys.of((Void) null)) + .setCoder(KvCoder.of(VoidCoder.of(), input.getCoder())) + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(new WriteView(og)); + } + } + + /** + * An in-process implementation of the {@link CreatePCollectionView} primitive. + * + * This implementation requires the input {@link PCollection} to be an iterable, which is provided + * to {@link PCollectionView#fromIterableInternal(Iterable)}. + */ + public static final class WriteView + extends PTransform>, PCollectionView> { + private final CreatePCollectionView og; + + WriteView(CreatePCollectionView og) { + this.og = og; + } + + @Override + public PCollectionView apply(PCollection> input) { + return og.getView(); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java index a41da34399..e2c4487ae5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.util.PCollectionViews; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.KV; @@ -435,6 +436,10 @@ public static CreatePCollectionView of( return new CreatePCollectionView<>(view); } + public PCollectionView getView() { + return view; + } + @Override public PCollectionView apply(PCollection input) { return view; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java index c29308f1d9..021709b37f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java @@ -21,16 +21,24 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.Values; +import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.util.PCollectionViews; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.common.collect.ImmutableList; import org.joda.time.Instant; import org.junit.Test; @@ -45,19 +53,30 @@ public class ViewEvaluatorFactoryTest { @Test public void testInMemoryEvaluator() throws Exception { TestPipeline p = TestPipeline.create(); + PCollection input = p.apply(Create.of("foo", "bar")); - PCollectionView> view = input.apply(View.asIterable()); + CreatePCollectionView> createView = + CreatePCollectionView.of( + PCollectionViews.iterableView(p, input.getWindowingStrategy(), StringUtf8Coder.of())); + PCollection> concat = + input.apply(WithKeys.of((Void) null)) + .setCoder(KvCoder.of(VoidCoder.of(), StringUtf8Coder.of())) + .apply(GroupByKey.create()) + .apply(Values.>create()); + PCollectionView> view = + concat.apply(new ViewEvaluatorFactory.WriteView<>(createView)); InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); TestViewWriter> viewWriter = new TestViewWriter<>(); - when(context.createPCollectionViewWriter(input, view)).thenReturn(viewWriter); + when(context.createPCollectionViewWriter(concat, view)).thenReturn(viewWriter); CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); - TransformEvaluator evaluator = new ViewEvaluatorFactory().forApplication( - view.getProducingTransformInternal(), inputBundle, context); + TransformEvaluator> evaluator = + new ViewEvaluatorFactory() + .forApplication(view.getProducingTransformInternal(), inputBundle, context); - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement(WindowedValue.valueInGlobalWindow("bar")); + evaluator.processElement( + WindowedValue.>valueInGlobalWindow(ImmutableList.of("foo", "bar"))); assertThat(viewWriter.latest, nullValue()); evaluator.finishBundle(); From db708bb9a157d0b86519f9309d5c0b945a72ebde Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 23 Feb 2016 19:53:21 -0800 Subject: [PATCH 211/751] Update maven-dependency-plugin to latest Prior to version 2.10 configuration options we require are unavailable. Specifically, to have a strict dependency policy with our optional dependency configurations, we will need: - ignoredUnusedDeclaredDependencies - ignoredUsedUndeclaredDependencies ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115411144 --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 9ff5cd218e..cf24c7bda0 100644 --- a/pom.xml +++ b/pom.xml @@ -293,6 +293,7 @@ org.apache.maven.plugins maven-dependency-plugin + 2.10 true From 01fd8595e7d54009d313e98889fdf322d98b5c63 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Tue, 23 Feb 2016 20:07:32 -0800 Subject: [PATCH 212/751] ProtoCoder: a Coder for Protocol Buffers Messages ----Release Notes---- Adds ProtoCoder, which is a Coder for Protocol Buffers messages. ProtoCoder has the following advantages over Proto2Coder: * ProtoCoder is designed to support Protocol Buffers syntax versions 2 and 3, not just proto2. * ProtoCoder dynamically inspects the Message type it encodes and will throw a Coder.NonDeterministicException when the configured message cannot be encoded deterministically. * Because early versions of the Protocol Buffers 2 syntax did not allow non-deterministic types, Proto2Coder does not do this type inspection and instead always claims to be able to coder deterministically. For backwards compatibility, we are not changing this behavior. Proto2Coder is now deprecated; we recommend that all users switch to ProtoCoder. [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115411869 --- sdk/pom.xml | 2 +- .../dataflow/sdk/coders/CoderRegistry.java | 5 +- .../dataflow/sdk/coders/Proto2Coder.java | 3 + .../sdk/coders/StringDelegateCoder.java | 4 +- .../sdk/coders/protobuf/ProtoCoder.java | 411 ++++++++++++++++++ .../sdk/coders/protobuf/ProtobufUtil.java | 171 ++++++++ .../sdk/coders/CoderRegistryTest.java | 14 +- .../dataflow/sdk/coders/Proto2CoderTest.java | 1 + .../sdk/coders/protobuf/ProtoCoderTest.java | 182 ++++++++ .../sdk/coders/protobuf/ProtobufUtilTest.java | 195 +++++++++ 10 files changed, 980 insertions(+), 8 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java diff --git a/sdk/pom.xml b/sdk/pom.xml index bdbdd5f31c..bc6d519f74 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -442,7 +442,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-proto-library-all - 0.5.160127 + 0.5.160222 diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java index 1ef09712d4..00982e64ff 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java @@ -18,6 +18,7 @@ import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException.ReasonCode; +import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.values.KV; @@ -81,8 +82,8 @@ public class CoderRegistry implements CoderProvider { private static final Logger LOG = LoggerFactory.getLogger(CoderRegistry.class); public CoderRegistry() { - setFallbackCoderProvider(CoderProviders.firstOf(Proto2Coder.coderProvider(), - SerializableCoder.PROVIDER)); + setFallbackCoderProvider( + CoderProviders.firstOf(ProtoCoder.coderProvider(), SerializableCoder.PROVIDER)); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java index 56ec0c7d7b..ef91ba96e8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java @@ -17,6 +17,7 @@ import static com.google.common.base.Preconditions.checkArgument; +import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.Structs; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; @@ -71,7 +72,9 @@ * * * @param the type of elements handled by this coder, must extend {@code Message} + * @deprecated Use {@link ProtoCoder}. */ +@Deprecated public class Proto2Coder extends AtomicCoder { /** The class of Protobuf message to be encoded. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java index 9696b58511..1fc1247226 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.coders; +import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; + import java.lang.reflect.InvocationTargetException; /** @@ -35,7 +37,7 @@ * *

    This method of encoding is not designed for ease of evolution of {@code Clazz}; * it should only be used in cases where the class is stable or the encoding is not - * important. If evolution of the class is important, see {@link Proto2Coder}, {@link AvroCoder}, + * important. If evolution of the class is important, see {@link ProtoCoder}, {@link AvroCoder}, * or {@link JAXBCoder}. * * @param The type of objects coded. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java new file mode 100644 index 0000000000..d8c8e9e243 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java @@ -0,0 +1,411 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.api.services.datastore.DatastoreV1; +import com.google.api.services.datastore.DatastoreV1.Entity; +import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.CoderProvider; +import com.google.cloud.dataflow.sdk.coders.CoderRegistry; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.util.Structs; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.protobuf.ExtensionRegistry; +import com.google.protobuf.Message; +import com.google.protobuf.Parser; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.annotation.Nullable; + +/** + * A {@link Coder} using Google Protocol Buffers binary format. {@link ProtoCoder} supports both + * Protocol Buffers syntax versions 2 and 3. + * + *

    To learn more about Protocol Buffers, visit: + * https://developers.google.com/protocol-buffers + * + *

    {@link ProtoCoder} is registered in the global {@link CoderRegistry} as the default + * {@link Coder} for any {@link Message} object. Custom message extensions are also supported, but + * these extensions must be registered for a particular {@link ProtoCoder} instance and that + * instance must be registered on the {@link PCollection} that needs the extensions: + * + *

    {@code
    + * import MyProtoFile;
    + * import MyProtoFile.MyMessage;
    + *
    + * Coder coder = ProtoCoder.of(MyMessage.class).withExtensionsFrom(MyProtoFile.class);
    + * PCollection records =  input.apply(...).setCoder(coder);
    + * }
    + * + *

    Versioning

    + * + *

    {@link ProtoCoder} supports both versions 2 and 3 of the Protocol Buffers syntax. However, + * the Java runtime version of the google.com.protobuf library must match exactly the + * version of protoc that was used to produce the JAR files containing the compiled + * .proto messages. + * + *

    For more information, see the + * Protocol Buffers documentation. + * + *

    {@link ProtoCoder} and Determinism

    + * + *

    In general, Protocol Buffers messages can be encoded deterministically within a single + * pipeline as long as: + * + *

      + *
    • The encoded messages (and any transitively linked messages) do not use map + * fields.
    • + *
    • Every Java VM that encodes or decodes the messages use the same runtime version of the + * Protocol Buffers library and the same compiled .proto file JAR.
    • + *
    + * + *

    {@link ProtoCoder} and Encoding Stability

    + * + *

    When changing Protocol Buffers messages, follow the rules in the Protocol Buffers language + * guides for + * {@code proto2} + * and + * {@code proto3} + * syntaxes, depending on your message type. Following these guidelines will ensure that the + * old encoded data can be read by new versions of the code. + * + *

    Generally, any change to the message type, registered extensions, runtime library, or + * compiled proto JARs may change the encoding. Thus even if both the original and updated messages + * can be encoded deterministically within a single job, these deterministic encodings may not be + * the same across jobs. + * + * @param the Protocol Buffers {@link Message} handled by this {@link Coder}. + */ +public class ProtoCoder extends AtomicCoder { + + /** + * A {@link CoderProvider} that returns a {@link ProtoCoder} with an empty + * {@link ExtensionRegistry}. + */ + public static CoderProvider coderProvider() { + return PROVIDER; + } + + /** + * Returns a {@link ProtoCoder} for the given Protocol Buffers {@link Message}. + */ + public static ProtoCoder of(Class protoMessageClass) { + return new ProtoCoder(protoMessageClass, ImmutableSet.>of()); + } + + /** + * Returns a {@link ProtoCoder} for the Protocol Buffers {@link Message} indicated by the given + * {@link TypeDescriptor}. + */ + public static ProtoCoder of(TypeDescriptor protoMessageType) { + @SuppressWarnings("unchecked") + Class protoMessageClass = (Class) protoMessageType.getRawType(); + return of(protoMessageClass); + } + + /** + * Returns a {@link ProtoCoder} like this one, but with the extensions from the given classes + * registered. + * + *

    Each of the extension host classes must be an class automatically generated by the + * Protocol Buffers compiler, {@code protoc}, that contains messages. For example, the class + * {@link Proto2CoderTestMessages} is the extension host for the {@link Message} classes + * {@link MessageA Proto2CoderTestMessages.MessageA} and the class {@link DatastoreV1} is the + * extension host for the Google Cloud Datastore {@link Entity} entity type. + * + *

    Does not modify this object. + */ + public ProtoCoder withExtensionsFrom(Iterable> moreExtensionHosts) { + for (Class extensionHost : moreExtensionHosts) { + // Attempt to access the required method, to make sure it's present. + try { + Method registerAllExtensions = + extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class); + checkArgument( + Modifier.isStatic(registerAllExtensions.getModifiers()), + "Method registerAllExtensions() must be static"); + } catch (NoSuchMethodException | SecurityException e) { + throw new IllegalArgumentException( + String.format("Unable to register extensions for %s", extensionHost.getCanonicalName()), + e); + } + } + + return new ProtoCoder( + protoMessageClass, + new ImmutableSet.Builder>() + .addAll(extensionHostClasses) + .addAll(moreExtensionHosts) + .build()); + } + + /** + * See {@link #withExtensionsFrom(Iterable)}. + * + *

    Does not modify this object. + */ + public ProtoCoder withExtensionsFrom(Class... moreExtensionHosts) { + return withExtensionsFrom(Arrays.asList(moreExtensionHosts)); + } + + @Override + public void encode(T value, OutputStream outStream, Context context) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null " + protoMessageClass.getSimpleName()); + } + if (context.isWholeStream) { + value.writeTo(outStream); + } else { + value.writeDelimitedTo(outStream); + } + } + + @Override + public T decode(InputStream inStream, Context context) throws IOException { + if (context.isWholeStream) { + return getParser().parseFrom(inStream, getExtensionRegistry()); + } else { + return getParser().parseDelimitedFrom(inStream, getExtensionRegistry()); + } + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ProtoCoder)) { + return false; + } + ProtoCoder otherCoder = (ProtoCoder) other; + return protoMessageClass.equals(otherCoder.protoMessageClass) + && Sets.newHashSet(extensionHostClasses) + .equals(Sets.newHashSet(otherCoder.extensionHostClasses)); + } + + @Override + public int hashCode() { + return Objects.hash(protoMessageClass, extensionHostClasses); + } + + /** + * The encoding identifier is designed to support evolution as per the design of Protocol + * Buffers. In order to use this class effectively, carefully follow the advice in the Protocol + * Buffers documentation at + * Updating + * A Message Type. + * + *

    In particular, the encoding identifier is guaranteed to be the same for {@link ProtoCoder} + * instances of the same principal message class, with the same registered extension host classes, + * and otherwise distinct. Note that the encoding ID does not encode any version of the message + * or extensions, nor does it include the message schema. + * + *

    When modifying a message class, here are the broadest guidelines; see the above link + * for greater detail. + * + *

      + *
    • Do not change the numeric tags for any fields. + *
    • Never remove a required field. + *
    • Only add optional or repeated fields, with sensible defaults. + *
    • When changing the type of a field, consult the Protocol Buffers documentation to ensure + * the new and old types are interchangeable. + *
    + * + *

    Code consuming this message class should be prepared to support all versions of + * the class until it is certain that no remaining serialized instances exist. + * + *

    If backwards incompatible changes must be made, the best recourse is to change the name + * of your Protocol Buffers message class. + */ + @Override + public String getEncodingId() { + return protoMessageClass.getName() + getSortedExtensionClasses().toString(); + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + ProtobufUtil.verifyDeterministic(this); + } + + /** + * Returns the Protocol Buffers {@link Message} type this {@link ProtoCoder} supports. + */ + public Class getMessageType() { + return protoMessageClass; + } + + /** + * Returns the {@link ExtensionRegistry} listing all known Protocol Buffers extension messages + * to {@code T} registered with this {@link ProtoCoder}. + */ + public ExtensionRegistry getExtensionRegistry() { + if (memoizedExtensionRegistry == null) { + ExtensionRegistry registry = ExtensionRegistry.newInstance(); + for (Class extensionHost : extensionHostClasses) { + try { + extensionHost + .getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class) + .invoke(null, registry); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new IllegalStateException(e); + } + } + memoizedExtensionRegistry = registry.getUnmodifiable(); + } + return memoizedExtensionRegistry; + } + + //////////////////////////////////////////////////////////////////////////////////// + // Private implementation details below. + + /** The {@link Message} type to be coded. */ + private final Class protoMessageClass; + + /** + * All extension host classes included in this {@link ProtoCoder}. The extensions from these + * classes will be included in the {@link ExtensionRegistry} used during encoding and decoding. + */ + private final Set> extensionHostClasses; + + // Constants used to serialize and deserialize + private static final String PROTO_MESSAGE_CLASS = "proto_message_class"; + private static final String PROTO_EXTENSION_HOSTS = "proto_extension_hosts"; + + // Transient fields that are lazy initialized and then memoized. + private transient ExtensionRegistry memoizedExtensionRegistry; + private transient Parser memoizedParser; + + /** Private constructor. */ + private ProtoCoder(Class protoMessageClass, Set> extensionHostClasses) { + this.protoMessageClass = protoMessageClass; + this.extensionHostClasses = extensionHostClasses; + } + + /** + * @deprecated For JSON deserialization only. + */ + @JsonCreator + @Deprecated + public static ProtoCoder of( + @JsonProperty(PROTO_MESSAGE_CLASS) String protoMessageClassName, + @Nullable @JsonProperty(PROTO_EXTENSION_HOSTS) List extensionHostClassNames) { + + try { + @SuppressWarnings("unchecked") + Class protoMessageClass = (Class) Class.forName(protoMessageClassName); + List> extensionHostClasses = Lists.newArrayList(); + if (extensionHostClassNames != null) { + for (String extensionHostClassName : extensionHostClassNames) { + extensionHostClasses.add(Class.forName(extensionHostClassName)); + } + } + return of(protoMessageClass).withExtensionsFrom(extensionHostClasses); + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException(e); + } + } + + @Override + public CloudObject asCloudObject() { + CloudObject result = super.asCloudObject(); + Structs.addString(result, PROTO_MESSAGE_CLASS, protoMessageClass.getName()); + List extensionHostClassNames = Lists.newArrayList(); + for (String className : getSortedExtensionClasses()) { + extensionHostClassNames.add(CloudObject.forString(className)); + } + Structs.addList(result, PROTO_EXTENSION_HOSTS, extensionHostClassNames); + return result; + } + + /** Get the memoized {@link Parser}, possibly initializing it lazily. */ + private Parser getParser() { + if (memoizedParser == null) { + try { + @SuppressWarnings("unchecked") + T protoMessageInstance = (T) protoMessageClass.getMethod("getDefaultInstance").invoke(null); + @SuppressWarnings("unchecked") + Parser tParser = (Parser) protoMessageInstance.getParserForType(); + memoizedParser = tParser; + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new IllegalArgumentException(e); + } + } + return memoizedParser; + } + + /** + * The implementation of the {@link CoderProvider} for this {@link ProtoCoder} returned by + * {@link #coderProvider()}. + */ + private static final CoderProvider PROVIDER = + new CoderProvider() { + @Override + public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { + if (!type.isSubtypeOf(new TypeDescriptor() {})) { + throw new CannotProvideCoderException( + String.format( + "Cannot provide %s because %s is not a subclass of %s", + ProtoCoder.class.getSimpleName(), + type, + Message.class.getName())); + } + + @SuppressWarnings("unchecked") + TypeDescriptor messageType = (TypeDescriptor) type; + try { + @SuppressWarnings("unchecked") + Coder coder = (Coder) ProtoCoder.of(messageType); + return coder; + } catch (IllegalArgumentException e) { + throw new CannotProvideCoderException(e); + } + } + }; + + private SortedSet getSortedExtensionClasses() { + SortedSet ret = new TreeSet<>(); + for (Class clazz : extensionHostClasses) { + ret.add(clazz.getName()); + } + return ret; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java new file mode 100644 index 0000000000..597b1de843 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor.Syntax; +import com.google.protobuf.Descriptors.GenericDescriptor; +import com.google.protobuf.ExtensionRegistry; +import com.google.protobuf.ExtensionRegistry.ExtensionInfo; +import com.google.protobuf.Message; + +import java.lang.reflect.InvocationTargetException; +import java.util.HashSet; +import java.util.Set; + +/** + * Utility functions for reflecting and analyzing Protocol Buffers classes. + * + *

    Used by {@link ProtoCoder}, but in a separate file for testing and isolation. + */ +class ProtobufUtil { + /** + * Returns the {@link Descriptor} for the given Protocol Buffers {@link Message}. + * + * @throws IllegalArgumentException if there is an error in Java reflection. + */ + static Descriptor getDescriptorForClass(Class clazz) { + try { + return (Descriptor) clazz.getMethod("getDescriptor").invoke(null); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new IllegalArgumentException(e); + } + } + + /** + * Returns the {@link Descriptor} for the given Protocol Buffers {@link Message} as well as + * every class it can include transitively. + * + * @throws IllegalArgumentException if there is an error in Java reflection. + */ + static Set getRecursiveDescriptorsForClass( + Class clazz, ExtensionRegistry registry) { + Descriptor root = getDescriptorForClass(clazz); + Set descriptors = new HashSet<>(); + recursivelyAddDescriptors(root, descriptors, registry); + return descriptors; + } + + /** + * Recursively walks the given {@link Message} class and verifies that every field or message + * linked in uses the Protocol Buffers proto2 syntax. + */ + static void checkProto2Syntax(Class clazz, ExtensionRegistry registry) { + for (GenericDescriptor d : getRecursiveDescriptorsForClass(clazz, registry)) { + Syntax s = d.getFile().getSyntax(); + checkArgument( + s == Syntax.PROTO2, + "Message %s or one of its dependencies does not use proto2 syntax: %s in file %s", + clazz.getName(), + d.getFullName(), + d.getFile().getName()); + } + } + + /** + * Recursively checks whether the specified class uses any Protocol Buffers fields that cannot + * be deterministically encoded. + * + * @throws NonDeterministicException if the object cannot be encoded deterministically. + */ + static void verifyDeterministic(ProtoCoder coder) throws NonDeterministicException { + Class message = coder.getMessageType(); + ExtensionRegistry registry = coder.getExtensionRegistry(); + Set descriptors = getRecursiveDescriptorsForClass(message, registry); + for (Descriptor d : descriptors) { + for (FieldDescriptor fd : d.getFields()) { + // If there is a transitively reachable Protocol Buffers map field, then this object cannot + // be encoded deterministically. + if (fd.isMapField()) { + String reason = + String.format( + "Protocol Buffers message %s transitively includes Map field %s (from file %s)." + + " Maps cannot be deterministically encoded.", + message.getName(), + fd.getFullName(), + fd.getFile().getFullName()); + throw new NonDeterministicException(coder, reason); + } + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Disable construction of utility class + private ProtobufUtil() {} + + private static void recursivelyAddDescriptors( + Descriptor message, Set descriptors, ExtensionRegistry registry) { + if (descriptors.contains(message)) { + return; + } + descriptors.add(message); + + for (FieldDescriptor f : message.getFields()) { + recursivelyAddDescriptors(f, descriptors, registry); + } + for (FieldDescriptor f : message.getExtensions()) { + recursivelyAddDescriptors(f, descriptors, registry); + } + for (ExtensionInfo info : + registry.getAllImmutableExtensionsByExtendedType(message.getFullName())) { + recursivelyAddDescriptors(info.descriptor, descriptors, registry); + } + for (ExtensionInfo info : + registry.getAllMutableExtensionsByExtendedType(message.getFullName())) { + recursivelyAddDescriptors(info.descriptor, descriptors, registry); + } + } + + private static void recursivelyAddDescriptors( + FieldDescriptor field, Set descriptors, ExtensionRegistry registry) { + switch (field.getType()) { + case BOOL: + case BYTES: + case DOUBLE: + case ENUM: + case FIXED32: + case FIXED64: + case FLOAT: + case INT32: + case INT64: + case SFIXED32: + case SFIXED64: + case SINT32: + case SINT64: + case STRING: + case UINT32: + case UINT64: + // Primitive types do not transitively access anything else. + break; + + case GROUP: + case MESSAGE: + // Recursively adds all the fields from this nested Message. + recursivelyAddDescriptors(field.getMessageType(), descriptors, registry); + break; + + default: + throw new UnsupportedOperationException( + "Unexpected Protocol Buffers field type: " + field.getType()); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java index 7fd0d22ea5..2f350b288d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java @@ -22,6 +22,8 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.CoderRegistry.IncompatibleCoderException; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; +import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -33,6 +35,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.collect.ImmutableList; +import com.google.protobuf.Duration; import org.junit.Rule; import org.junit.Test; @@ -82,11 +85,14 @@ public void testSerializableFallbackCoderProvider() throws Exception { } @Test - public void testProto2CoderFallbackCoderProvider() throws Exception { + public void testProtoCoderFallbackCoderProvider() throws Exception { CoderRegistry registry = getStandardRegistry(); - Coder coder = - registry.getDefaultCoder(Proto2CoderTestMessages.MessageA.class); - assertEquals(coder, Proto2Coder.of(new TypeDescriptor() {})); + + // MessageA is a Protocol Buffers test message with syntax 2 + assertEquals(registry.getDefaultCoder(MessageA.class), ProtoCoder.of(MessageA.class)); + + // Duration is a Protocol Buffers default type with syntax 3 + assertEquals(registry.getDefaultCoder(Duration.class), ProtoCoder.of(Duration.class)); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java index f4c355715a..91ebc65438 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java @@ -35,6 +35,7 @@ /** * Tests for Proto2Coder. */ +@SuppressWarnings("deprecation") // test of a deprecated coder. @RunWith(JUnit4.class) public class Proto2CoderTest { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java new file mode 100644 index 0000000000..6f4e99d388 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.ListCoder; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageB; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageC; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageWithMap; +import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.collect.ImmutableList; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link ProtoCoder}. + */ +@RunWith(JUnit4.class) +public class ProtoCoderTest { + + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testFactoryMethodAgreement() throws Exception { + assertEquals(ProtoCoder.of(new TypeDescriptor() {}), ProtoCoder.of(MessageA.class)); + + assertEquals( + ProtoCoder.of(new TypeDescriptor() {}), + ProtoCoder.coderProvider().getCoder(new TypeDescriptor() {})); + } + + @Test + public void testProviderCannotProvideCoder() throws Exception { + thrown.expect(CannotProvideCoderException.class); + thrown.expectMessage("java.lang.Integer is not a subclass of com.google.protobuf.Message"); + + ProtoCoder.coderProvider().getCoder(new TypeDescriptor() {}); + } + + @Test + public void testCoderEncodeDecodeEqual() throws Exception { + MessageA value = + MessageA.newBuilder() + .setField1("hello") + .addField2(MessageB.newBuilder().setField1(true).build()) + .addField2(MessageB.newBuilder().setField1(false).build()) + .build(); + CoderProperties.coderDecodeEncodeEqual(ProtoCoder.of(MessageA.class), value); + } + + @Test + public void testCoderEncodeDecodeEqualNestedContext() throws Exception { + MessageA value1 = + MessageA.newBuilder() + .setField1("hello") + .addField2(MessageB.newBuilder().setField1(true).build()) + .addField2(MessageB.newBuilder().setField1(false).build()) + .build(); + MessageA value2 = + MessageA.newBuilder() + .setField1("world") + .addField2(MessageB.newBuilder().setField1(false).build()) + .addField2(MessageB.newBuilder().setField1(true).build()) + .build(); + CoderProperties.coderDecodeEncodeEqual( + ListCoder.of(ProtoCoder.of(MessageA.class)), ImmutableList.of(value1, value2)); + } + + @Test + public void testCoderEncodeDecodeExtensionsEqual() throws Exception { + MessageC value = + MessageC.newBuilder() + .setExtension( + Proto2CoderTestMessages.field1, + MessageA.newBuilder() + .setField1("hello") + .addField2(MessageB.newBuilder().setField1(true).build()) + .build()) + .setExtension( + Proto2CoderTestMessages.field2, MessageB.newBuilder().setField1(false).build()) + .build(); + CoderProperties.coderDecodeEncodeEqual( + ProtoCoder.of(MessageC.class).withExtensionsFrom(Proto2CoderTestMessages.class), value); + } + + @Test + public void testCoderSerialization() throws Exception { + ProtoCoder coder = ProtoCoder.of(MessageA.class); + CoderProperties.coderSerializable(coder); + } + + @Test + public void testCoderExtensionsSerialization() throws Exception { + ProtoCoder coder = + ProtoCoder.of(MessageC.class).withExtensionsFrom(Proto2CoderTestMessages.class); + CoderProperties.coderSerializable(coder); + } + + @Test + public void testEncodingId() throws Exception { + Coder coderA = ProtoCoder.of(MessageA.class); + CoderProperties.coderHasEncodingId(coderA, MessageA.class.getName() + "[]"); + + ProtoCoder coder = + ProtoCoder.of(MessageC.class).withExtensionsFrom(Proto2CoderTestMessages.class); + CoderProperties.coderHasEncodingId( + coder, + String.format("%s[%s]", MessageC.class.getName(), Proto2CoderTestMessages.class.getName())); + } + + @Test + public void encodeNullThrowsCoderException() throws Exception { + thrown.expect(CoderException.class); + thrown.expectMessage("cannot encode a null MessageA"); + + CoderUtils.encodeToBase64(ProtoCoder.of(MessageA.class), null); + } + + @Test + public void testDeterministicCoder() throws NonDeterministicException { + Coder coder = ProtoCoder.of(MessageA.class); + coder.verifyDeterministic(); + } + + @Test + public void testNonDeterministicCoder() throws NonDeterministicException { + thrown.expect(NonDeterministicException.class); + thrown.expectMessage(MessageWithMap.class.getName() + " transitively includes Map field"); + + Coder coder = ProtoCoder.of(MessageWithMap.class); + coder.verifyDeterministic(); + } + + @Test + public void testNonDeterministicProperty() throws CoderException { + MessageWithMap.Builder msg1B = MessageWithMap.newBuilder(); + MessageWithMap.Builder msg2B = MessageWithMap.newBuilder(); + + // Built in reverse order but with equal contents. + for (int i = 0; i < 10; ++i) { + msg1B.getMutableField1().put("key" + i, MessageA.getDefaultInstance()); + msg2B.getMutableField1().put("key" + (9 - i), MessageA.getDefaultInstance()); + } + + // Assert the messages are equal. + MessageWithMap msg1 = msg1B.build(); + MessageWithMap msg2 = msg2B.build(); + assertEquals(msg2, msg1); + + // Assert the encoded messages are not equal. + Coder coder = ProtoCoder.of(MessageWithMap.class); + assertNotEquals(CoderUtils.encodeToBase64(coder, msg2), CoderUtils.encodeToBase64(coder, msg1)); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java new file mode 100644 index 0000000000..f2192e62e6 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java @@ -0,0 +1,195 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; + +import static com.google.cloud.dataflow.sdk.coders.protobuf.ProtobufUtil.checkProto2Syntax; +import static com.google.cloud.dataflow.sdk.coders.protobuf.ProtobufUtil.getRecursiveDescriptorsForClass; +import static com.google.cloud.dataflow.sdk.coders.protobuf.ProtobufUtil.verifyDeterministic; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import com.google.api.services.datastore.DatastoreV1.Entity; +import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageB; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageC; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageWithMap; +import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.ReferencesMessageWithMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import com.google.protobuf.Any; +import com.google.protobuf.Descriptors.GenericDescriptor; +import com.google.protobuf.Duration; +import com.google.protobuf.ExtensionRegistry; +import com.google.protobuf.Message; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.HashSet; +import java.util.Set; + +/** + * Tests for {@link ProtobufUtil}. + */ +@RunWith(JUnit4.class) +public class ProtobufUtilTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + private static final Set MESSAGE_A_ONLY = + ImmutableSet.of("proto2_coder_test_messages.MessageA"); + + private static final Set MESSAGE_B_ONLY = + ImmutableSet.of("proto2_coder_test_messages.MessageB"); + + private static final Set MESSAGE_C_ONLY = + ImmutableSet.of("proto2_coder_test_messages.MessageC"); + + // map fields are actually represented as a nested Message in generated Java code. + private static final Set WITH_MAP_ONLY = + ImmutableSet.of( + "proto2_coder_test_messages.MessageWithMap", + "proto2_coder_test_messages.MessageWithMap.Field1Entry"); + + private static final Set REFERS_MAP_ONLY = + ImmutableSet.of("proto2_coder_test_messages.ReferencesMessageWithMap"); + + // A references A and B. + private static final Set MESSAGE_A_ALL = Sets.union(MESSAGE_A_ONLY, MESSAGE_B_ONLY); + + // C, only with registered extensions, references A. + private static final Set MESSAGE_C_EXT = Sets.union(MESSAGE_C_ONLY, MESSAGE_A_ALL); + + // MessageWithMap references A. + private static final Set WITH_MAP_ALL = Sets.union(WITH_MAP_ONLY, MESSAGE_A_ALL); + + // ReferencesMessageWithMap references MessageWithMap. + private static final Set REFERS_MAP_ALL = Sets.union(REFERS_MAP_ONLY, WITH_MAP_ALL); + + @Test + public void testRecursiveDescriptorsMessageA() { + assertThat(getRecursiveDescriptorFullNames(MessageA.class), equalTo(MESSAGE_A_ALL)); + } + + @Test + public void testRecursiveDescriptorsMessageB() { + assertThat(getRecursiveDescriptorFullNames(MessageB.class), equalTo(MESSAGE_B_ONLY)); + } + + @Test + public void testRecursiveDescriptorsMessageC() { + assertThat(getRecursiveDescriptorFullNames(MessageC.class), equalTo(MESSAGE_C_ONLY)); + } + + @Test + public void testRecursiveDescriptorsMessageCWithExtensions() { + // With extensions, Message C has a reference to Message A and Message B. + ExtensionRegistry registry = ExtensionRegistry.newInstance(); + Proto2CoderTestMessages.registerAllExtensions(registry); + assertThat(getRecursiveDescriptorFullNames(MessageC.class, registry), equalTo(MESSAGE_C_EXT)); + } + + @Test + public void testRecursiveDescriptorsMessageWithMap() { + assertThat(getRecursiveDescriptorFullNames(MessageWithMap.class), equalTo(WITH_MAP_ALL)); + } + + @Test + public void testRecursiveDescriptorsReferencesMessageWithMap() { + assertThat( + getRecursiveDescriptorFullNames(ReferencesMessageWithMap.class), equalTo(REFERS_MAP_ALL)); + } + + @Test + public void testVerifyProto2() { + // Everything in Dataflow's Proto2TestMessages uses Proto2 syntax. + checkProto2Syntax(MessageA.class, ExtensionRegistry.getEmptyRegistry()); + checkProto2Syntax(MessageB.class, ExtensionRegistry.getEmptyRegistry()); + checkProto2Syntax(MessageC.class, ExtensionRegistry.getEmptyRegistry()); + checkProto2Syntax(MessageWithMap.class, ExtensionRegistry.getEmptyRegistry()); + checkProto2Syntax(ReferencesMessageWithMap.class, ExtensionRegistry.getEmptyRegistry()); + } + + @Test + public void testAnyIsNotProto2() { + // Any is a core Protocol Buffers type that uses proto3 syntax. + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(Any.class.getCanonicalName()); + thrown.expectMessage("in file " + Any.getDescriptor().getFile().getName()); + + checkProto2Syntax(Any.class, ExtensionRegistry.getEmptyRegistry()); + } + + @Test + public void testDurationIsNotProto2() { + // Duration is a core Protocol Buffers type that uses proto3 syntax. + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(Duration.class.getCanonicalName()); + thrown.expectMessage("in file " + Duration.getDescriptor().getFile().getName()); + + checkProto2Syntax(Duration.class, ExtensionRegistry.getEmptyRegistry()); + } + + @Test + public void testEntityIsDeterministic() throws NonDeterministicException { + // Cloud Datastore's Entities can be encoded deterministically. + verifyDeterministic(ProtoCoder.of(Entity.class)); + } + + @Test + public void testMessageWithMapIsNotDeterministic() throws NonDeterministicException { + String mapFieldName = MessageWithMap.getDescriptor().findFieldByNumber(1).getFullName(); + thrown.expect(NonDeterministicException.class); + thrown.expectMessage(MessageWithMap.class.getName()); + thrown.expectMessage("transitively includes Map field " + mapFieldName); + thrown.expectMessage("file " + MessageWithMap.getDescriptor().getFile().getName()); + + verifyDeterministic(ProtoCoder.of(MessageWithMap.class)); + } + + @Test + public void testMessageWithTransitiveMapIsNotDeterministic() throws NonDeterministicException { + String mapFieldName = MessageWithMap.getDescriptor().findFieldByNumber(1).getFullName(); + thrown.expect(NonDeterministicException.class); + thrown.expectMessage(ReferencesMessageWithMap.class.getName()); + thrown.expectMessage("transitively includes Map field " + mapFieldName); + thrown.expectMessage("file " + MessageWithMap.getDescriptor().getFile().getName()); + + verifyDeterministic(ProtoCoder.of(ReferencesMessageWithMap.class)); + } + + //////////////////////////////////////////////////////////////////////////////////////////// + + /** Helper used to test the recursive class traversal and print good error messages. */ + private static Set getRecursiveDescriptorFullNames(Class clazz) { + return getRecursiveDescriptorFullNames(clazz, ExtensionRegistry.getEmptyRegistry()); + } + + /** Helper used to test the recursive class traversal and print good error messages. */ + private static Set getRecursiveDescriptorFullNames( + Class clazz, ExtensionRegistry registry) { + Set result = new HashSet<>(); + for (GenericDescriptor d : getRecursiveDescriptorsForClass(clazz, registry)) { + result.add(d.getFullName()); + } + return result; + } +} From f7fc939c1266caa0e7139c50904e66fca97b44c2 Mon Sep 17 00:00:00 2001 From: klk Date: Tue, 23 Feb 2016 22:17:46 -0800 Subject: [PATCH 213/751] Add used-but-undeclared findbugs JSR305 dependencies This artifact provides annotations such as @Nullable, @ThreadSafe, and @NotThreadSafe, which we use throughout the SDK. Relevant pieces of diff from `mvn dependency:tree -Dverbose`: [INFO] com.google.cloud.dataflow:google-cloud-dataflow-java-sdk-all:jar:... +[INFO] +- com.google.code.findbugs:jsr305:jar:3.0.1:compile [INFO] +- com.google.cloud.bigtable:bigtable-protos:jar:0.2.3:compile -[INFO] | +- com.google.code.findbugs:jsr305:jar:3.0.1:compile +[INFO] | +- (com.google.code.findbugs:jsr305:jar:3.0.1:compile - omitted...) And pieces that did not change but are simply other dependencies that also depend on it so their entries were already omitted: [INFO] +- io.grpc:grpc-all:jar:0.12.0:compile [INFO] | +- io.grpc:grpc-core:jar:0.12.0:compile [INFO] | +- (com.google.code.findbugs:jsr305:jar:3.0.0:compile - omit...) [INFO] +- com.google.cloud.bigdataoss:gcsio:jar:1.4.3:compile [INFO] | +- (com.google.code.findbugs:jsr305:jar:2.0.3:compile - omitted...) [INFO] +- com.google.cloud.bigdataoss:util:jar:1.4.3:compile [INFO] | +- (com.google.code.findbugs:jsr305:jar:2.0.3:compile - omitted...) [INFO] +- com.google.cloud.bigtable:bigtable-client-core:jar:0.2.3:compile [INFO] | +- (com.google.code.findbugs:jsr305:jar:3.0.1:compile - omitted...) [INFO] +- com.google.oauth-client:google-oauth-client:jar:1.21.0:compile [INFO] | +- (com.google.code.findbugs:jsr305:jar:1.3.9:compile - omitted...) [INFO] +- com.google.http-client:google-http-client:jar:1.21.0:compile [INFO] | +- (com.google.code.findbugs:jsr305:jar:1.3.9:compile - omitted...) ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115418405 --- examples/pom.xml | 6 ++++++ pom.xml | 1 + sdk/pom.xml | 6 ++++++ worker/pom.xml | 6 ++++++ 4 files changed, 19 insertions(+) diff --git a/examples/pom.xml b/examples/pom.xml index 3900a23ba2..d7834cb3ef 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -465,6 +465,12 @@ ${guava.version} + + com.google.code.findbugs + jsr305 + ${jsr305.version} + + joda-time joda-time diff --git a/pom.xml b/pom.xml index cf24c7bda0..d946605100 100644 --- a/pom.xml +++ b/pom.xml @@ -77,6 +77,7 @@ 1.3 2.7.0 2.4 + 3.0.1 4.11 3.0.0-beta-1 v1-rev7-1.21.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index bc6d519f74..aeead722ca 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -612,6 +612,12 @@ ${protobuf.version} + + com.google.code.findbugs + jsr305 + ${jsr305.version} + + com.fasterxml.jackson.core jackson-core diff --git a/worker/pom.xml b/worker/pom.xml index e621ed4715..ab9e172dbf 100644 --- a/worker/pom.xml +++ b/worker/pom.xml @@ -263,6 +263,12 @@ 3.1.0 + + com.google.code.findbugs + jsr305 + ${jsr305.version} + + org.hamcrest From d15d924d5dae18a07067cc3a71ba3b50431fe3d7 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 24 Feb 2016 08:42:55 -0800 Subject: [PATCH 214/751] Handle PCollectionList.empty() in FlattenEvaluatorFactory PCollectionList.empty() is a valid argument to a Flatten#pCollections PTransform. It should succeed and produce no output. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115455733 --- .../inprocess/FlattenEvaluatorFactory.java | 8 ++++++- .../FlattenEvaluatorFactoryTest.java | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java index d8b5312161..14428888e2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Google Inc. + * Copyright (C) 2016 Google Inc. * * Licensed 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 @@ -46,6 +46,12 @@ private TransformEvaluator createInMemoryEvaluator( application, final CommittedBundle inputBundle, final InProcessEvaluationContext evaluationContext) { + if (inputBundle == null) { + // it is impossible to call processElement on a flatten with no input bundle. A Flatten with + // no input bundle occurs as an output of Flatten.pcollections(PCollectionList.empty()) + return new FlattenEvaluator<>( + null, StepTransformResult.withoutHold(application).build()); + } final UncommittedBundle outputBundle = evaluationContext.createBundle(inputBundle, application.getOutput()); final InProcessTransformResult result = diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java index c2b9995577..dac42b60f8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -112,4 +113,26 @@ public void testFlattenInMemoryEvaluator() throws Exception { WindowedValue.timestampedValueInGlobalWindow(-4, new Instant(-4096)), WindowedValue.valueInGlobalWindow(-1))); } + + @Test + public void testFlattenInMemoryEvaluatorWithEmptyPCollectionList() throws Exception { + TestPipeline p = TestPipeline.create(); + PCollectionList list = PCollectionList.empty(p); + + PCollection flattened = list.apply(Flatten.pCollections()); + + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + + FlattenEvaluatorFactory factory = new FlattenEvaluatorFactory(); + TransformEvaluator emptyEvaluator = + factory.forApplication(flattened.getProducingTransformInternal(), null, context); + + InProcessTransformResult leftSideResult = emptyEvaluator.finishBundle(); + + assertThat(leftSideResult.getOutputBundles(), emptyIterable()); + assertThat( + leftSideResult.getTransform(), + Matchers.>equalTo(flattened.getProducingTransformInternal())); + } + } From 1cc0211c19910d1d67d28ade1fd0c044bec8421d Mon Sep 17 00:00:00 2001 From: herohde Date: Wed, 24 Feb 2016 11:20:32 -0800 Subject: [PATCH 215/751] Set worker harness container image to INVALID until next release ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115473121 --- pom.xml | 1 - .../sdk/runners/DataflowPipelineRunner.java | 9 +- worker/pom.xml | 301 ------------------ 3 files changed, 4 insertions(+), 307 deletions(-) delete mode 100644 worker/pom.xml diff --git a/pom.xml b/pom.xml index d946605100..760a10d92f 100644 --- a/pom.xml +++ b/pom.xml @@ -88,7 +88,6 @@ pom sdk - worker examples maven-archetypes/starter maven-archetypes/examples diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index ac0dceae96..54fadeac3d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -206,11 +206,10 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. - // TODO: Set these once versioned containers are ready. - public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE = null; - //"dataflow.gcr.io/v1beta3/java-batch:20160201-rc00---INVALID"; - public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE = null; - //"dataflow.gcr.io/v1beta3/java-streaming:20160201-rc00---INVALID"; + public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE + = "dataflow.gcr.io/v1beta3/java-batch:INVALID"; + public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE + = "dataflow.gcr.io/v1beta3/java-streaming:INVALID"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; diff --git a/worker/pom.xml b/worker/pom.xml deleted file mode 100644 index ab9e172dbf..0000000000 --- a/worker/pom.xml +++ /dev/null @@ -1,301 +0,0 @@ - - - - 4.0.0 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-parent - 1.5.0-SNAPSHOT - - - com.google.cloud.dataflow - google-cloud-dataflow-java-worker-all - Google Cloud Dataflow Java Worker - All - Google Cloud Dataflow Java SDK provides a simple, Java-based - interface for processing virtually any size data using Google cloud - resources. This artifact includes entire Dataflow Java Worker. - http://cloud.google.com/dataflow - - jar - - - ${maven.build.timestamp} - yyyy-MM-dd HH:mm - none - - - - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.12 - - - com.puppycrawl.tools - checkstyle - 6.6 - - - - ../checkstyle.xml - true - true - false - true - ${project.build.directory}/generated-test-sources/** - - - - - check - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - default-jar - - jar - - - - default-test-jar - - test-jar - - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - compile - - jar - - - - attach-test-sources - test-compile - - test-jar - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4.1 - - - - bundle-and-repackage - package - - shade - - - true - - - com.google.guava:guava - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - com.google.common - com.google.cloud.dataflow.worker.repackaged.com.google.common - - - com.google.thirdparty - com.google.cloud.dataflow.worker.repackaged.com.google.thirdparty - - - - - - - - bundle-rest-without-repackaging - package - - shade - - - true - ${project.artifactId}-bundled-${project.version} - - - com.google.guava:guava - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - - org.jacoco - jacoco-maven-plugin - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${project.version} - provided - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${project.version} - test-jar - test - - - - com.google.guava - guava - ${guava.version} - - - - io.grpc - grpc-all - 0.12.0 - - - - com.google.auth - google-auth-library-oauth2-http - 0.3.0 - compile - - - - org.eclipse.jetty - jetty-server - 9.2.10.v20150310 - - - - org.eclipse.jetty - jetty-servlet - 9.2.10.v20150310 - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - com.google.code.findbugs - jsr305 - ${jsr305.version} - - - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - test - - - - junit - junit - ${junit.version} - test - - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - test - - - - org.mockito - mockito-all - 1.9.5 - test - - - From 045e3436e6b2ce9593c1f8ebeaa57ea7d229134e Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 24 Feb 2016 13:56:45 -0800 Subject: [PATCH 216/751] Handle Undeclared Side Outputs in ParDoInProcessEvaluator The value of an Undeclared Side Output is ignored by the InProcessPipelineRunner. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115489641 --- .../inprocess/ParDoInProcessEvaluator.java | 17 ++++- .../ParDoMultiEvaluatorFactoryTest.java | 74 +++++++++++++++++++ .../ParDoSingleEvaluatorFactoryTest.java | 42 +++++++++++ 3 files changed, 131 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index a2b083b0af..f0b2ca2564 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -27,7 +27,10 @@ import org.joda.time.Instant; +import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; +import java.util.List; import java.util.Map; class ParDoInProcessEvaluator { @@ -61,6 +64,7 @@ public InProcessTransformResult finishBundle() { static class BundleOutputManager implements OutputManager { private final Map, UncommittedBundle> bundles; + private final Map, List> undeclaredOutputs; public static BundleOutputManager create(Map, UncommittedBundle> outputBundles) { return new BundleOutputManager(outputBundles); @@ -68,6 +72,7 @@ public static BundleOutputManager create(Map, UncommittedBundle> private BundleOutputManager(Map, UncommittedBundle> bundles) { this.bundles = bundles; + undeclaredOutputs = new HashMap<>(); } @SuppressWarnings("unchecked") @@ -75,8 +80,16 @@ private BundleOutputManager(Map, UncommittedBundle> bundles) { public void output(TupleTag tag, WindowedValue output) { @SuppressWarnings("rawtypes") UncommittedBundle bundle = bundles.get(tag); - bundle.add(output); + if (bundle == null) { + List undeclaredContents = undeclaredOutputs.get(tag); + if (undeclaredContents == null) { + undeclaredContents = new ArrayList(); + undeclaredOutputs.put(tag, undeclaredContents); + } + undeclaredContents.add(output); + } else { + bundle.add(output); + } } } } - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java index 5251a768b9..c55a9d53a8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java @@ -137,5 +137,79 @@ public void processElement(ProcessContext c) { WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), WindowedValue.valueInGlobalWindow(5, PaneInfo.ON_TIME_AND_ONLY_FIRING))); } + + @Test + public void testParDoMultiUndeclaredSideOutput() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + + TupleTag> mainOutputTag = new TupleTag>() {}; + final TupleTag elementTag = new TupleTag<>(); + final TupleTag lengthTag = new TupleTag<>(); + + BoundMulti> pardo = + ParDo.of(new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output(KV.of(c.element(), c.element().length())); + c.sideOutput(elementTag, c.element()); + c.sideOutput(lengthTag, c.element().length()); + } + }).withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); + PCollectionTuple outputTuple = input.apply(pardo); + + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + + PCollection> mainOutput = outputTuple.get(mainOutputTag); + PCollection elementOutput = outputTuple.get(elementTag); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + + when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); + when(evaluationContext.createBundle(inputBundle, elementOutput)) + .thenReturn(elementOutputBundle); + + InProcessExecutionContext executionContext = + new InProcessExecutionContext(); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal())) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = + new ParDoMultiEvaluatorFactory().forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); + evaluator.processElement( + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getOutputBundles(), + Matchers.>containsInAnyOrder( + mainOutputBundle, elementOutputBundle)); + assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + assertThat(result.getCounters(), equalTo(counters)); + + assertThat( + mainOutputBundle.commit(Instant.now()).getElements(), + Matchers.>>containsInAnyOrder( + WindowedValue.valueInGlobalWindow(KV.of("foo", 3)), + WindowedValue.timestampedValueInGlobalWindow(KV.of("bara", 4), new Instant(1000)), + WindowedValue.valueInGlobalWindow( + KV.of("bazam", 5), PaneInfo.ON_TIME_AND_ONLY_FIRING))); + assertThat( + elementOutputBundle.commit(Instant.now()).getElements(), + Matchers.>containsInAnyOrder( + WindowedValue.valueInGlobalWindow("foo"), + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000)), + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING))); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java index c2e148b0d1..4fc765ce5d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java @@ -34,6 +34,7 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TupleTag; import org.hamcrest.Matchers; import org.joda.time.Instant; @@ -92,5 +93,46 @@ public void testParDoInMemoryTransformEvaluator() throws Exception { WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), WindowedValue.valueInGlobalWindow(5, PaneInfo.ON_TIME_AND_ONLY_FIRING))); } + + @Test + public void testSideOutputToUndeclaredSideOutputSucceeds() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + final TupleTag sideOutputTag = new TupleTag() {}; + PCollection collection = input.apply(ParDo.of(new DoFn() { + @Override public void processElement(ProcessContext c) { + c.sideOutput(sideOutputTag, c.element().length()); + } + })); + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + UncommittedBundle outputBundle = + InProcessBundle.unkeyed(collection); + when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); + InProcessExecutionContext executionContext = + new InProcessExecutionContext(); + when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal())) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + TransformEvaluator evaluator = + new ParDoSingleEvaluatorFactory().forApplication( + collection.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); + evaluator.processElement( + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getOutputBundles(), Matchers.>containsInAnyOrder(outputBundle)); + assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + assertThat(result.getCounters(), equalTo(counters)); + } } From 639e9d95b61704ae1740a0a1f02f76c3d480fa48 Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 24 Feb 2016 15:24:22 -0800 Subject: [PATCH 217/751] Rollback revert "Migrate TextIO.Write to a custom sink" Note for user requested sharding limits to be supported, each pipeline runner must support applying those sharding limits. DirectPipelineRunner and Google Cloud Dataflow supports sharding limits. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115500204 --- .../cloud/dataflow/sdk/io/FileBasedSink.java | 17 +- .../google/cloud/dataflow/sdk/io/TextIO.java | 187 +++++++++--------- .../sdk/runners/DataflowPipelineRunner.java | 131 ++++++++++-- .../runners/DataflowPipelineTranslator.java | 6 - .../sdk/runners/DirectPipelineRunner.java | 89 +++++++++ .../runners/dataflow/TextIOTranslator.java | 91 --------- .../dataflow/sdk/io/FileBasedSinkTest.java | 29 ++- .../cloud/dataflow/sdk/io/TextIOTest.java | 22 --- .../runners/DataflowPipelineRunnerTest.java | 21 +- .../DataflowPipelineTranslatorTest.java | 4 +- .../sdk/runners/DirectPipelineRunnerTest.java | 80 +++++++- .../sdk/runners/TransformTreeTest.java | 9 +- 12 files changed, 414 insertions(+), 272 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index 7c301679ca..dda500c369 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -355,7 +355,7 @@ protected final List generateDestinationFilenames(int numFiles) { String baseOutputFilename = getSink().baseOutputFilename; String fileNamingTemplate = getSink().fileNamingTemplate; - String suffix = (extension.length() == 0) ? extension : ("." + extension); + String suffix = getFileExtension(extension); for (int i = 0; i < numFiles; i++) { destFilenames.add(IOChannelUtils.constructName( baseOutputFilename, fileNamingTemplate, suffix, i, numFiles)); @@ -363,6 +363,21 @@ protected final List generateDestinationFilenames(int numFiles) { return destFilenames; } + /** + * Returns the file extension to be used. If the user did not request a file + * extension then this method returns the empty string. Otherwise this method + * adds a {@code "."} to the beginning of the users extension if one is not present. + */ + private String getFileExtension(String usersExtension) { + if (usersExtension == null || usersExtension.isEmpty()) { + return ""; + } + if (usersExtension.startsWith(".")) { + return usersExtension; + } + return "." + usersExtension; + } + /** * Removes temporary output files. Uses the temporary filename to find files to remove. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 0bb2861831..d342f250b2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -26,11 +26,9 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.worker.TextSink; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; +import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; @@ -39,10 +37,13 @@ import com.google.protobuf.ByteString; import java.io.IOException; +import java.io.OutputStream; import java.nio.ByteBuffer; +import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SeekableByteChannel; -import java.util.List; +import java.nio.channels.WritableByteChannel; +import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import java.util.regex.Pattern; @@ -66,7 +67,7 @@ * *

    See the following examples: * - *

     {@code
    + * 
    {@code
      * Pipeline p = ...;
      *
      * // A simple Read of a local file (only runs locally):
    @@ -79,7 +80,7 @@
      *     p.apply(TextIO.Read.named("ReadNumbers")
      *                        .from("gs://my_bucket/path/to/numbers-*.txt")
      *                        .withCoder(TextualIntegerCoder.of()));
    - * } 
    + * }
    * *

    To write a {@link PCollection} to one or more text files, use * {@link TextIO.Write}, specifying {@link TextIO.Write#to(String)} to specify @@ -94,7 +95,7 @@ * will be overwritten. * *

    For example: - *

     {@code
    + * 
    {@code
      * // A simple Write to a local file (only runs locally):
      * PCollection lines = ...;
      * lines.apply(TextIO.Write.to("/path/to/file.txt"));
    @@ -106,7 +107,7 @@
      *                           .to("gs://my_bucket/path/to/numbers")
      *                           .withSuffix(".txt")
      *                           .withCoder(TextualIntegerCoder.of()));
    - * } 
    + * }
    * *

    Permissions

    *

    When run using the {@link DirectPipelineRunner}, your pipeline can read and write text files @@ -477,9 +478,6 @@ public static class Bound extends PTransform, PDone> { /** Requested number of shards. 0 for automatic. */ private final int numShards; - /** Insert a shuffle before writing to decouple parallelism when numShards != 0. */ - private final boolean forceReshard; - /** The shard template of each file written, combined with prefix and suffix. */ private final String shardTemplate; @@ -487,17 +485,16 @@ public static class Bound extends PTransform, PDone> { private final boolean validate; Bound(Coder coder) { - this(null, null, "", coder, 0, true, ShardNameTemplate.INDEX_OF_MAX, true); + this(null, null, "", coder, 0, ShardNameTemplate.INDEX_OF_MAX, true); } private Bound(String name, String filenamePrefix, String filenameSuffix, Coder coder, - int numShards, boolean forceReshard, String shardTemplate, boolean validate) { + int numShards, String shardTemplate, boolean validate) { super(name); this.coder = coder; this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; this.numShards = numShards; - this.forceReshard = forceReshard; this.shardTemplate = shardTemplate; this.validate = validate; } @@ -510,7 +507,7 @@ private Bound(String name, String filenamePrefix, String filenameSuffix, Coder named(String name) { return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, - forceReshard, shardTemplate, validate); + shardTemplate, validate); } /** @@ -523,7 +520,7 @@ public Bound named(String name) { */ public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -537,7 +534,7 @@ public Bound to(String filenamePrefix) { */ public Bound withSuffix(String nameExtension) { validateOutputComponent(nameExtension); - return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, shardTemplate, validate); } @@ -556,30 +553,8 @@ public Bound withSuffix(String nameExtension) { * @see ShardNameTemplate */ public Bound withNumShards(int numShards) { - return withNumShards(numShards, forceReshard); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that uses the provided shard count. - * - *

    Constraining the number of shards is likely to reduce - * the performance of a pipeline. If forceReshard is true, the output - * will be shuffled to obtain the desired sharding. If it is false, - * data will not be reshuffled, but parallelism of preceeding stages - * may be constrained. Setting this value is not recommended - * unless you require a specific number of output files. - * - *

    Does not modify this object. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - * @param forceReshard whether to force a reshard to obtain the desired sharding. - * @see ShardNameTemplate - */ - private Bound withNumShards(int numShards, boolean forceReshard) { Preconditions.checkArgument(numShards >= 0); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -592,7 +567,7 @@ private Bound withNumShards(int numShards, boolean forceReshard) { * @see ShardNameTemplate */ public Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -610,25 +585,7 @@ public Bound withShardNameTemplate(String shardTemplate) { *

    Does not modify this object. */ public Bound withoutSharding() { - return withoutSharding(forceReshard); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that forces a single file as output. - * - *

    Constraining the number of shards is likely to reduce - * the performance of a pipeline. Using this setting is not recommended - * unless you truly require a single output file. - * - *

    This is a shortcut for - * {@code .withNumShards(1, forceReshard).withShardNameTemplate("")} - * - *

    Does not modify this object. - */ - private Bound withoutSharding(boolean forceReshard) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, forceReshard, "", - validate); + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, "", validate); } /** @@ -640,7 +597,7 @@ private Bound withoutSharding(boolean forceReshard) { * @param the type of the elements of the input {@link PCollection} */ public Bound withCoder(Coder coder) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, validate); } @@ -655,7 +612,7 @@ public Bound withCoder(Coder coder) { *

    Does not modify this object. */ public Bound withoutValidation() { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, forceReshard, + return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, shardTemplate, false); } @@ -665,14 +622,13 @@ public PDone apply(PCollection input) { throw new IllegalStateException( "need to set the filename prefix of a TextIO.Write transform"); } - if (numShards > 0 && forceReshard) { - // Reshard and re-apply a version of this write without resharding. - return input - .apply(new FileBasedSink.ReshardForWrite()) - .apply(withNumShards(numShards, false)); - } else { - return PDone.in(input.getPipeline()); - } + + // Note that custom sinks currently do not expose sharding controls. + // Thus pipeline runner writers need to individually add support internally to + // apply user requested sharding limits. + return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( + new TextSink<>( + filenamePrefix, filenameSuffix, shardTemplate, coder))); } /** @@ -710,17 +666,6 @@ public Coder getCoder() { public boolean needsValidation() { return validate; } - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateWriteHelper(transform, context); - } - }); - } } } @@ -978,24 +923,70 @@ private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOExcep } } - private static void evaluateWriteHelper( - Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { - List elems = context.getPCollection(context.getInput(transform)); - int numShards = transform.numShards; - if (numShards < 1) { - // System gets to choose. For direct mode, choose 1. - numShards = 1; + /** + * A {@link FileBasedSink} for text files. Produces text files with the new line separator + * {@code '\n'} represented in {@code UTF-8} format as the record separator. + * Each record (including the last) is terminated. + */ + @VisibleForTesting + static class TextSink extends FileBasedSink { + private final Coder coder; + + @VisibleForTesting + TextSink( + String baseOutputFilename, String extension, String fileNameTemplate, Coder coder) { + super(baseOutputFilename, extension, fileNameTemplate); + this.coder = coder; } - TextSink> writer = TextSink.createForDirectPipelineRunner( - transform.filenamePrefix, transform.getShardNameTemplate(), transform.filenameSuffix, - numShards, true, null, null, transform.coder); - try (Sink.SinkWriter> sink = writer.writer()) { - for (T elem : elems) { - sink.add(WindowedValue.valueInGlobalWindow(elem)); - } - } catch (IOException exn) { - throw new RuntimeException( - "unable to write to output file \"" + transform.filenamePrefix + "\"", exn); + + @Override + public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { + return new TextWriteOperation<>(this, coder); + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation + * FileBasedWriteOperation} for text files. + */ + private static class TextWriteOperation extends FileBasedWriteOperation { + private final Coder coder; + + private TextWriteOperation(TextSink sink, Coder coder) { + super(sink); + this.coder = coder; + } + + @Override + public FileBasedWriter createWriter(PipelineOptions options) throws Exception { + return new TextWriter<>(this, coder); + } + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} + * for text files. + */ + private static class TextWriter extends FileBasedWriter { + private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); + private final Coder coder; + private OutputStream out; + + public TextWriter(FileBasedWriteOperation writeOperation, Coder coder) { + super(writeOperation); + this.mimeType = MimeTypes.TEXT; + this.coder = coder; + } + + @Override + protected void prepareWrite(WritableByteChannel channel) throws Exception { + out = Channels.newOutputStream(channel); + } + + @Override + public void write(T value) throws Exception { + coder.encode(value, out, Context.OUTER); + out.write(NEWLINE); + } } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 54fadeac3d..06b2295080 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -338,6 +338,7 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(Window.Bound.class, AssignWindows.class); builder.put(Write.Bound.class, BatchWrite.class); builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); + builder.put(TextIO.Write.Bound.class, BatchTextIOWrite.class); if (options.getExperiments() == null || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); @@ -1999,6 +2000,111 @@ public PDone apply(PCollection input) { } } + /** + * Specialized implementation which overrides + * {@link com.google.cloud.dataflow.sdk.io.TextIO.Write.Bound TextIO.Write.Bound} with + * a native sink instead of a custom sink as workaround until custom sinks + * have support for sharding controls. + */ + private static class BatchTextIOWrite extends PTransform, PDone> { + private final TextIO.Write.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchTextIOWrite(DataflowPipelineRunner runner, TextIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + if (transform.getNumShards() > 0) { + return input + .apply(new ReshardForWrite()) + .apply(new BatchTextIONativeWrite<>(transform)); + } else { + return transform.apply(input); + } + } + } + + /** + * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way + * to provide the native definition of the Text sink. + */ + private static class BatchTextIONativeWrite extends PTransform, PDone> { + private final TextIO.Write.Bound transform; + public BatchTextIONativeWrite(TextIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + return PDone.in(input.getPipeline()); + } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + BatchTextIONativeWrite.class, new BatchTextIONativeWriteTranslator()); + } + } + + /** + * TextIO.Write.Bound support code for the Dataflow backend when applying parallelism limits + * through user requested sharding limits. + */ + private static class BatchTextIONativeWriteTranslator + implements TransformTranslator> { + @SuppressWarnings("unchecked") + @Override + public void translate(@SuppressWarnings("rawtypes") BatchTextIONativeWrite transform, + TranslationContext context) { + translateWriteHelper(transform, transform.transform, context); + } + + private void translateWriteHelper( + BatchTextIONativeWrite transform, + TextIO.Write.Bound originalTransform, + TranslationContext context) { + // Note that the original transform can not be used during add step/add input + // and is only passed in to get properties from it. + + checkState(originalTransform.getNumShards() > 0, + "Native TextSink is expected to only be used when sharding controls are required."); + + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + + // TODO: drop this check when server supports alternative templates. + switch (originalTransform.getShardTemplate()) { + case ShardNameTemplate.INDEX_OF_MAX: + break; // supported by server + case "": + // Empty shard template allowed - forces single output. + Preconditions.checkArgument(originalTransform.getNumShards() <= 1, + "Num shards must be <= 1 when using an empty sharding template"); + break; + default: + throw new UnsupportedOperationException("Shard template " + + originalTransform.getShardTemplate() + + " not yet supported by Dataflow service"); + } + + // TODO: How do we want to specify format and + // format-specific properties? + context.addInput(PropertyNames.FORMAT, "text"); + context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); + context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, + originalTransform.getShardNameTemplate()); + context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); + context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); + context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); + context.addEncodingInput( + WindowedValue.getValueOnlyCoder(originalTransform.getCoder())); + + } + } + /** * Specialized implementation which overrides * {@link com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound AvroIO.Write.Bound} with @@ -2018,7 +2124,9 @@ public BatchAvroIOWrite(DataflowPipelineRunner runner, AvroIO.Write.Bound tra @Override public PDone apply(PCollection input) { if (transform.getNumShards() > 0) { - return input.apply(new ReshardForWrite()).apply(new BatchAvroIONativeWrite<>(transform)); + return input + .apply(new ReshardForWrite()) + .apply(new BatchAvroIONativeWrite<>(transform)); } else { return transform.apply(input); } @@ -2031,7 +2139,6 @@ public PDone apply(PCollection input) { */ private static class BatchAvroIONativeWrite extends PTransform, PDone> { private final AvroIO.Write.Bound transform; - public BatchAvroIONativeWrite(AvroIO.Write.Bound transform) { this.transform = transform; } @@ -2055,8 +2162,7 @@ private static class BatchAvroIONativeWriteTranslator implements TransformTranslator> { @SuppressWarnings("unchecked") @Override - public void translate( - @SuppressWarnings("rawtypes") BatchAvroIONativeWrite transform, + public void translate(@SuppressWarnings("rawtypes") BatchAvroIONativeWrite transform, TranslationContext context) { translateWriteHelper(transform, transform.transform, context); } @@ -2068,8 +2174,7 @@ private void translateWriteHelper( // Note that the original transform can not be used during add step/add input // and is only passed in to get properties from it. - checkState( - originalTransform.getNumShards() > 0, + checkState(originalTransform.getNumShards() > 0, "Native AvroSink is expected to only be used when sharding controls are required."); context.addStep(transform, "ParallelWrite"); @@ -2078,18 +2183,16 @@ private void translateWriteHelper( // TODO: drop this check when server supports alternative templates. switch (originalTransform.getShardTemplate()) { case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server + break; // supported by server case "": // Empty shard template allowed - forces single output. - Preconditions.checkArgument( - originalTransform.getNumShards() <= 1, + Preconditions.checkArgument(originalTransform.getNumShards() <= 1, "Num shards must be <= 1 when using an empty sharding template"); break; default: - throw new UnsupportedOperationException( - "Shard template " - + originalTransform.getShardTemplate() - + " not yet supported by Dataflow service"); + throw new UnsupportedOperationException("Shard template " + + originalTransform.getShardTemplate() + + " not yet supported by Dataflow service"); } context.addInput(PropertyNames.FORMAT, "avro"); @@ -2097,9 +2200,7 @@ private void translateWriteHelper( context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, originalTransform.getShardTemplate()); context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); - context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); - context.addEncodingInput( WindowedValue.getValueOnlyCoder( AvroCoder.of(originalTransform.getType(), originalTransform.getSchema()))); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 885260ebb2..ae3a403103 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -44,14 +44,12 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; -import com.google.cloud.dataflow.sdk.runners.dataflow.TextIOTranslator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -998,7 +996,6 @@ private void translateSingleHelper( } }); - registerTransformTranslator( Window.Bound.class, new DataflowPipelineTranslator.TransformTranslator() { @@ -1037,9 +1034,6 @@ private void translateHelper( DataflowPipelineRunner.StreamingPubsubIOWrite.class, new PubsubIOTranslator.WriteTranslator()); - registerTransformTranslator( - TextIO.Write.Bound.class, new TextIOTranslator.WriteTranslator()); - registerTransformTranslator(Read.Bounded.class, new ReadTranslator()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java index 332a49603a..4543b5a534 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.runners; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; @@ -24,6 +25,8 @@ import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.ListCoder; +import com.google.cloud.dataflow.sdk.io.FileBasedSink; +import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; @@ -36,6 +39,8 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.Partition; +import com.google.cloud.dataflow.sdk.transforms.Partition.PartitionFn; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; @@ -51,6 +56,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; import com.google.cloud.dataflow.sdk.values.PValue; @@ -232,6 +238,8 @@ public OutputT apply( PTransform transform, InputT input) { if (transform instanceof Combine.GroupedValues) { return (OutputT) applyTestCombine((Combine.GroupedValues) transform, (PCollection) input); + } else if (transform instanceof TextIO.Write.Bound) { + return (OutputT) applyTextIOWrite((TextIO.Write.Bound) transform, (PCollection) input); } else { return super.apply(transform, input); } @@ -253,6 +261,87 @@ private PCollection> applyTestCombin return output; } + private static class ElementProcessingOrderPartitionFn implements PartitionFn { + private int elementNumber; + @Override + public int partitionFor(T elem, int numPartitions) { + return elementNumber++ % numPartitions; + } + } + + /** + * Applies TextIO.Write honoring user requested sharding controls (i.e. withNumShards) + * by applying a partition function based upon the number of shards the user requested. + */ + private static class DirectTextIOWrite extends PTransform, PDone> { + private final TextIO.Write.Bound transform; + + private DirectTextIOWrite(TextIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + checkState(transform.getNumShards() > 1, + "DirectTextIOWrite is expected to only be used when sharding controls are required."); + + // Evenly distribute all the elements across the partitions. + PCollectionList partitionedElements = + input.apply(Partition.of(transform.getNumShards(), + new ElementProcessingOrderPartitionFn())); + + // For each input PCollection partition, create a write transform that represents + // one of the specific shards. + for (int i = 0; i < transform.getNumShards(); ++i) { + /* + * This logic mirrors the file naming strategy within + * {@link FileBasedSink#generateDestinationFilenames()} + */ + String outputFilename = IOChannelUtils.constructName( + transform.getFilenamePrefix(), + transform.getShardNameTemplate(), + getFileExtension(transform.getFilenameSuffix()), + i, + transform.getNumShards()); + + String transformName = String.format("%s(Shard:%s)", transform.getName(), i); + partitionedElements.get(i).apply(transformName, + transform.withNumShards(1).withShardNameTemplate("").withSuffix("").to(outputFilename)); + } + return PDone.in(input.getPipeline()); + } + } + + /** + * Returns the file extension to be used. If the user did not request a file + * extension then this method returns the empty string. Otherwise this method + * adds a {@code "."} to the beginning of the users extension if one is not present. + * + *

    This is copied from {@link FileBasedSink} to not expose it. + */ + private static String getFileExtension(String usersExtension) { + if (usersExtension == null || usersExtension.isEmpty()) { + return ""; + } + if (usersExtension.startsWith(".")) { + return usersExtension; + } + return "." + usersExtension; + } + + /** + * Apply the override for TextIO.Write.Bound if the user requested sharding controls + * greater than one. + */ + private PDone applyTextIOWrite(TextIO.Write.Bound transform, PCollection input) { + if (transform.getNumShards() <= 1) { + // By default, the DirectPipelineRunner outputs to only 1 shard. Since the user never + // requested sharding controls greater than 1, we default to outputting to 1 file. + return super.apply(transform.withNumShards(1), input); + } + return input.apply(new DirectTextIOWrite<>(transform)); + } + /** * The implementation may split the {@link KeyedCombineFn} into ADD, MERGE and EXTRACT phases ( * see {@code com.google.cloud.dataflow.sdk.runners.worker.CombineValuesFn}). In order to emulate diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java deleted file mode 100644 index d6c96c31bd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/TextIOTranslator.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.util.PathValidator; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.common.base.Preconditions; - -/** - * TextIO transform support code for the Dataflow backend. - */ -public class TextIOTranslator { - /** - * Implements TextIO Write translation for the Dataflow backend. - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public static class WriteTranslator implements TransformTranslator { - @Override - public void translate( - TextIO.Write.Bound transform, - TranslationContext context) { - translateWriteHelper(transform, context); - } - - private void translateWriteHelper( - TextIO.Write.Bound transform, - TranslationContext context) { - if (context.getPipelineOptions().isStreaming()) { - throw new IllegalArgumentException("TextIO not supported in streaming mode."); - } - - PathValidator validator = context.getPipelineOptions().getPathValidator(); - String filenamePrefix = validator.validateOutputFilePrefixSupported( - transform.getFilenamePrefix()); - - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (transform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(transform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + transform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - // TODO: How do we want to specify format and - // format-specific properties? - context.addInput(PropertyNames.FORMAT, "text"); - context.addInput(PropertyNames.FILENAME_PREFIX, filenamePrefix); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, - transform.getShardNameTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, transform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, transform.needsValidation()); - - long numShards = transform.getNumShards(); - if (numShards > 0) { - context.addInput(PropertyNames.NUM_SHARDS, numShards); - } - - context.addEncodingInput( - WindowedValue.getValueOnlyCoder(transform.getCoder())); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java index 8236ae6835..da23f3a562 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java @@ -56,7 +56,6 @@ public class FileBasedSinkTest { private String baseOutputFilename = "output"; private String baseTemporaryFilename = "temp"; - private String testExtension = "test"; private String appendToTempFolder(String filename) { return Paths.get(tmpFolder.getRoot().getPath(), filename).toString(); @@ -314,7 +313,7 @@ public void testCopyToOutputFiles() throws Exception { public void testGenerateOutputFilenamesWithTemplate() { List expected; List actual; - SimpleSink sink = buildSink(".SS.of.NN"); + SimpleSink sink = new SimpleSink(getBaseOutputFilename(), "test", ".SS.of.NN"); SimpleSink.SimpleWriteOperation writeOp = new SimpleSink.SimpleWriteOperation(sink); expected = Arrays.asList(appendToTempFolder("output.00.of.03.test"), @@ -329,6 +328,23 @@ public void testGenerateOutputFilenamesWithTemplate() { expected = new ArrayList<>(); actual = writeOp.generateDestinationFilenames(0); assertEquals(expected, actual); + + // Also validate that we handle the case where the user specified "." that we do + // not prefix an additional "." making "..test" + sink = new SimpleSink(getBaseOutputFilename(), ".test", ".SS.of.NN"); + writeOp = new SimpleSink.SimpleWriteOperation(sink); + expected = Arrays.asList(appendToTempFolder("output.00.of.03.test"), + appendToTempFolder("output.01.of.03.test"), appendToTempFolder("output.02.of.03.test")); + actual = writeOp.generateDestinationFilenames(3); + assertEquals(expected, actual); + + expected = Arrays.asList(appendToTempFolder("output.00.of.01.test")); + actual = writeOp.generateDestinationFilenames(1); + assertEquals(expected, actual); + + expected = new ArrayList<>(); + actual = writeOp.generateDestinationFilenames(0); + assertEquals(expected, actual); } /** @@ -457,14 +473,7 @@ public void write(String value) throws Exception { * Build a SimpleSink with default options. */ private SimpleSink buildSink() { - return new SimpleSink(getBaseOutputFilename(), testExtension); - } - - /** - * Build a SimpleSink with default options and the given shard template. - */ - private SimpleSink buildSink(String shardTemplate) { - return new SimpleSink(getBaseOutputFilename(), testExtension, shardTemplate); + return new SimpleSink(getBaseOutputFilename(), "test"); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 6ad81e4ea0..0a8e381108 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -263,28 +263,6 @@ public void testWriteEmptyInts() throws Exception { runTestWrite(NO_INTS_ARRAY, TextualIntegerCoder.of()); } - @Test - public void testWriteSharded() throws IOException { - File outFolder = tmpFolder.newFolder(); - String filename = outFolder.toPath().resolve("output").toString(); - - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(Arrays.asList(LINES_ARRAY)) - .withCoder(StringUtf8Coder.of())); - - input.apply(TextIO.Write.to(filename).withNumShards(2).withSuffix(".txt")); - - p.run(); - - String[] files = outFolder.list(); - - assertThat(Arrays.asList(files), - containsInAnyOrder("output-00000-of-00002.txt", - "output-00001-of-00002.txt")); - } - @Test public void testWriteNamed() { { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index c7175cb3b0..c5f2d3fe71 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -453,16 +453,12 @@ public void testNonGcsFilePathInReadFailure() throws IOException { @Test public void testNonGcsFilePathInWriteFailure() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); - p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")) - .apply(TextIO.Write.named("WriteMyNonGcsFile").to("/tmp/file")); + Pipeline p = buildDataflowPipeline(buildPipelineOptions()); + PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); - p.run(); - assertValidJob(jobCaptor.getValue()); + pc.apply(TextIO.Write.named("WriteMyNonGcsFile").to("/tmp/file")); } @Test @@ -482,17 +478,12 @@ public void testMultiSlashGcsFileReadPath() throws IOException { @Test public void testMultiSlashGcsFileWritePath() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); - p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")) - .apply(TextIO.Write.named("WriteInvalidGcsFile") - .to("gs://bucket/tmp//file")); + Pipeline p = buildDataflowPipeline(buildPipelineOptions()); + PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("consecutive slashes"); - p.run(); - assertValidJob(jobCaptor.getValue()); + pc.apply(TextIO.Write.named("WriteInvalidGcsFile").to("gs://bucket/tmp//file")); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index b9c94ad00b..72090a0866 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -403,7 +403,7 @@ public void testPredefinedAddStep() throws Exception { pipeline.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/in")) .apply(ParDo.of(new NoOpFn())) .apply(new EmbeddedTransform(predefinedStep.clone())) - .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/out")); + .apply(ParDo.of(new NoOpFn())); Job job = translator.translate( pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); @@ -456,7 +456,7 @@ private static Step createPredefinedStep() throws Exception { Job job = translator.translate( pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - assertEquals(3, job.getSteps().size()); + assertEquals(13, job.getSteps().size()); Step step = job.getSteps().get(1); assertEquals(stepName, getString(step.getProperties(), PropertyNames.USER_NAME)); return step; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java index 904e4bbddc..4a0f91c917 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java @@ -16,35 +16,48 @@ package com.google.cloud.dataflow.sdk.runners; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.isA; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; +import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.common.io.Files; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; /** Tests for {@link DirectPipelineRunner}. */ @RunWith(JUnit4.class) public class DirectPipelineRunnerTest implements Serializable { - - @Rule - public transient ExpectedException expectedException = ExpectedException.none(); + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); + @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testToString() { @@ -54,6 +67,7 @@ public void testToString() { runner.toString()); } + /** A {@link Coder} that fails during decoding. */ private static class CrashingCoder extends AtomicCoder { @Override public void encode(T value, OutputStream stream, Context context) throws CoderException { @@ -68,18 +82,21 @@ public T decode( } } + /** A {@link DoFn} that outputs {@code 'hello'}. */ + private static class HelloDoFn extends DoFn { + @Override + public void processElement(DoFn.ProcessContext c) throws Exception { + c.output("hello"); + } + } + @Test public void testCoderException() { DirectPipeline pipeline = DirectPipeline.createForTest(); pipeline .apply("CreateTestData", Create.of(42)) - .apply("CrashDuringCoding", ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext context) { - context.output("hello"); - } - })) + .apply("CrashDuringCoding", ParDo.of(new HelloDoFn())) .setCoder(new CrashingCoder()); expectedException.expect(RuntimeException.class); @@ -92,4 +109,49 @@ public void testDirectPipelineOptions() { DirectPipelineOptions options = PipelineOptionsFactory.create().as(DirectPipelineOptions.class); assertNull(options.getDirectPipelineRunnerRandomSeed()); } + + @Test + public void testTextIOWriteWithDefaultShardingStrategy() throws Exception { + String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "output"); + Pipeline p = DirectPipeline.createForTest(); + String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; + p.apply(Create.of(expectedElements)) + .apply(TextIO.Write.to(prefix).withSuffix("txt")); + p.run(); + + String filename = + IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".txt", 0, 1); + List fileContents = + Files.readLines(new File(filename), StandardCharsets.UTF_8); + // Ensure that each file got at least one record + assertFalse(fileContents.isEmpty()); + + assertThat(fileContents, containsInAnyOrder(expectedElements)); + } + + @Test + public void testTextIOWriteWithLimitedNumberOfShards() throws Exception { + final int numShards = 3; + String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "shardedOutput"); + Pipeline p = DirectPipeline.createForTest(); + String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; + p.apply(Create.of(expectedElements)) + .apply(TextIO.Write.to(prefix).withNumShards(numShards).withSuffix("txt")); + p.run(); + + List allContents = new ArrayList<>(); + for (int i = 0; i < numShards; ++i) { + String shardFileName = + IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".txt", i, 3); + List shardFileContents = + Files.readLines(new File(shardFileName), StandardCharsets.UTF_8); + + // Ensure that each file got at least one record + assertFalse(shardFileContents.isEmpty()); + + allContents.addAll(shardFileContents); + } + + assertThat(allContents, containsInAnyOrder(expectedElements)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java index f1b7cd7fd0..68e1db1a52 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java @@ -28,6 +28,7 @@ import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.io.Write; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; @@ -133,9 +134,12 @@ public void enterCompositeTransform(TransformTreeNode node) { assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); assertNotNull(node.getEnclosingNode()); assertTrue(node.isCompositeNode()); + } else if (transform instanceof Write.Bound) { + assertTrue(visited.add(TransformsSeen.WRITE)); + assertNotNull(node.getEnclosingNode()); + assertTrue(node.isCompositeNode()); } assertThat(transform, not(instanceOf(Read.Bounded.class))); - assertThat(transform, not(instanceOf(TextIO.Write.Bound.class))); } @Override @@ -151,10 +155,9 @@ public void visitTransform(TransformTreeNode node) { PTransform transform = node.getTransform(); // Pick is a composite, should not be visited here. assertThat(transform, not(instanceOf(Sample.SampleAny.class))); + assertThat(transform, not(instanceOf(Write.Bound.class))); if (transform instanceof Read.Bounded) { assertTrue(visited.add(TransformsSeen.READ)); - } else if (transform instanceof TextIO.Write.Bound) { - assertTrue(visited.add(TransformsSeen.WRITE)); } } From ca98da2a372210325e1c8985292b4040d1ac8c62 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 24 Feb 2016 16:01:50 -0800 Subject: [PATCH 218/751] Update Timers and State in the InProcess ParDoEvaluator If the ParDo accessed state, put the committed value into the transform result, and likewise with timers. Add a #commitState method to InProcessStepContext to return the committed state. Implement stateInternals() and timerInternals() to provide actual implementations of StateInternals and TimerInternals. Use concrete types due to implementation requirements. stateInternals() and timerInternals() construct response values the first time they are called based on the underlying data structure; #commitState returns null if and only if stateInternals was not used by the transform, and likewise for #getTimerUpdate ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115504122 --- .../inprocess/InProcessExecutionContext.java | 108 +++++++++ .../inprocess/InProcessPipelineRunner.java | 47 +--- .../inprocess/ParDoInProcessEvaluator.java | 34 ++- .../inprocess/ParDoMultiEvaluatorFactory.java | 25 +- .../ParDoSingleEvaluatorFactory.java | 30 +-- .../util/InMemoryWatermarkManager.java | 17 ++ .../ParDoMultiEvaluatorFactoryTest.java | 223 +++++++++++++++++- .../ParDoSingleEvaluatorFactoryTest.java | 184 ++++++++++++++- 8 files changed, 556 insertions(+), 112 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java new file mode 100644 index 0000000000..6342cd48a9 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.util.Clock; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TransformWatermarks; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessTimerInternals; +import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.TimerInternals; +import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; +import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; + +/** + * Execution Context for the {@link InProcessPipelineRunner}. + * + * This implementation is not thread safe. A new {@link InProcessExecutionContext} must be created + * for each thread that requires it. + */ +class InProcessExecutionContext + extends BaseExecutionContext { + private final Clock clock; + private final Object key; + private final CopyOnAccessInMemoryStateInternals existingState; + private final TransformWatermarks watermarks; + + public InProcessExecutionContext(Clock clock, Object key, + CopyOnAccessInMemoryStateInternals existingState, TransformWatermarks watermarks) { + this.clock = clock; + this.key = key; + this.existingState = existingState; + this.watermarks = watermarks; + } + + @Override + protected InProcessStepContext createStepContext( + String stepName, String transformName, StateSampler stateSampler) { + return new InProcessStepContext(this, stepName, transformName); + } + + /** + * Step Context for the {@link InProcessPipelineRunner}. + */ + public class InProcessStepContext + extends com.google.cloud.dataflow.sdk.util.BaseExecutionContext.StepContext { + private CopyOnAccessInMemoryStateInternals stateInternals; + private InProcessTimerInternals timerInternals; + + public InProcessStepContext( + ExecutionContext executionContext, String stepName, String transformName) { + super(executionContext, stepName, transformName); + } + + @Override + public CopyOnAccessInMemoryStateInternals stateInternals() { + if (stateInternals == null) { + stateInternals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, existingState); + } + return stateInternals; + } + + @Override + public InProcessTimerInternals timerInternals() { + if (timerInternals == null) { + timerInternals = + InProcessTimerInternals.create(clock, watermarks, TimerUpdate.builder(key)); + } + return timerInternals; + } + + /** + * Commits the state of this step, and returns the committed state. If the step has not + * accessed any state, return null. + */ + public CopyOnAccessInMemoryStateInternals commitState() { + if (stateInternals != null) { + return stateInternals.commit(); + } + return null; + } + + /** + * Gets the timer update of the {@link TimerInternals} of this {@link InProcessStepContext}, + * which is empty if the {@link TimerInternals} were never accessed. + */ + public TimerUpdate getTimerUpdate() { + if (timerInternals == null) { + return TimerUpdate.empty(); + } + return timerInternals.getTimerUpdate(); + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 26c5061f67..124de46b94 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -28,16 +28,12 @@ import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; import com.google.cloud.dataflow.sdk.util.ExecutionContext; import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.TimerInternals; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PValue; @@ -158,46 +154,6 @@ public static interface PCollectionViewWriter { void add(Iterable> values); } - /** - * Execution Context for the InMemoryPipelineRunner. - * - * This implementation is not thread safe. A new InMemoryExecutionContext must be created for each - * thread that requires it. - */ - public static class InProcessExecutionContext - extends BaseExecutionContext { - @Override - protected InProcessStepContext createStepContext( - String stepName, String transformName, StateSampler stateSampler) { - return new InProcessStepContext(this, stepName, transformName); - } - - /** - * Step Context for the InMemoryPipelineRunner. - */ - public class InProcessStepContext - extends com.google.cloud.dataflow.sdk.util.BaseExecutionContext.StepContext { - public InProcessStepContext( - InProcessExecutionContext executionContext, String stepName, String transformName) { - super(executionContext, stepName, transformName); - } - - @Override - public StateInternals stateInternals() { - // TODO get or create state for current key. - throw new UnsupportedOperationException("StateInternals not yet meaningfully supported"); - } - - @Override - public TimerInternals timerInternals() { - // TODO: Have the executionContext/evaluationContext pass this in - throw new UnsupportedOperationException("TimerInternals not yet meaningfully supported"); - } - } - - } - - /** * The evaluation context for the {@link InProcessPipelineRunner}. Contains state shared within * the current evaluation. @@ -235,7 +191,8 @@ PCollectionViewWriter createPCollectionViewWriter( /** * Get an {@link ExecutionContext} for the provided application. */ - InProcessExecutionContext getExecutionContext(AppliedPTransform application); + InProcessExecutionContext getExecutionContext( + AppliedPTransform application, @Nullable Object key); /** * Get the Step Name for the provided application. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index f0b2ca2564..2a21e8cbf5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -15,49 +15,63 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.DoFnRunner; import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TupleTag; -import org.joda.time.Instant; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; -class ParDoInProcessEvaluator { +class ParDoInProcessEvaluator implements TransformEvaluator { private final DoFnRunner fnRunner; private final AppliedPTransform, ?, ?> transform; private final CounterSet counters; private final Collection> outputBundles; + private final InProcessStepContext stepContext; - public ParDoInProcessEvaluator(DoFnRunner fnRunner, - AppliedPTransform, ?, ?> transform, CounterSet counters, - Collection> outputBundles) { + public ParDoInProcessEvaluator( + DoFnRunner fnRunner, + AppliedPTransform, ?, ?> transform, + CounterSet counters, + Collection> outputBundles, + InProcessStepContext stepContext) { this.fnRunner = fnRunner; this.transform = transform; this.counters = counters; this.outputBundles = outputBundles; + this.stepContext = stepContext; } + @Override public void processElement(WindowedValue element) { fnRunner.processElement(element); } + @Override public InProcessTransformResult finishBundle() { fnRunner.finishBundle(); - // TODO Use a real value - Instant hold = BoundedWindow.TIMESTAMP_MAX_VALUE; - return StepTransformResult.withHold(transform, hold) + StepTransformResult.Builder resultBuilder; + CopyOnAccessInMemoryStateInternals state = stepContext.commitState(); + if (state != null) { + resultBuilder = + StepTransformResult.withHold(transform, state.getEarliestWatermarkHold()) + .withState(state); + } else { + resultBuilder = StepTransformResult.withoutHold(transform); + } + return resultBuilder .addOutput(outputBundles) + .withTimerUpdate(stepContext.getTimerUpdate()) .withCounters(counters) .build(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java index ad68a6b204..e3ae1a028c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java @@ -15,10 +15,9 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -27,7 +26,6 @@ import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti; import com.google.cloud.dataflow.sdk.util.DoFnRunner; import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionTuple; @@ -46,20 +44,7 @@ public TransformEvaluator forApplication( AppliedPTransform application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - @SuppressWarnings({"unchecked", "rawtypes"}) - final ParDoInProcessEvaluator multiEvaluator = - createMultiEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); - return new TransformEvaluator() { - @Override - public void processElement(WindowedValue value) { - multiEvaluator.processElement(value); - } - - @Override - public InProcessTransformResult finishBundle() { - return multiEvaluator.finishBundle(); - } - }; + return createMultiEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); } private static ParDoInProcessEvaluator createMultiEvaluator( @@ -74,7 +59,8 @@ private static ParDoInProcessEvaluator createMultiEvaluator( outputEntry.getKey(), evaluationContext.createBundle(inputBundle, outputEntry.getValue())); } - InProcessExecutionContext executionContext = evaluationContext.getExecutionContext(application); + InProcessExecutionContext executionContext = + evaluationContext.getExecutionContext(application, inputBundle.getKey()); String stepName = evaluationContext.getStepName(application); InProcessStepContext stepContext = executionContext.getOrCreateStepContext(stepName, stepName, null); @@ -96,6 +82,7 @@ private static ParDoInProcessEvaluator createMultiEvaluator( runner.startBundle(); - return new ParDoInProcessEvaluator<>(runner, application, counters, outputBundles.values()); + return new ParDoInProcessEvaluator<>( + runner, application, counters, outputBundles.values(), stepContext); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java index 737d0e9981..cd79c219bd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java @@ -15,10 +15,9 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -26,7 +25,6 @@ import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; import com.google.cloud.dataflow.sdk.util.DoFnRunner; import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TupleTag; @@ -43,22 +41,7 @@ public TransformEvaluator forApplication( final AppliedPTransform application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - @SuppressWarnings({"unchecked", "rawtypes"}) - final ParDoInProcessEvaluator evaluator = - createSingleEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); - TransformEvaluator singleEvaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue value) { - evaluator.processElement(value); - } - - @Override - public InProcessTransformResult finishBundle() { - return evaluator.finishBundle(); - } - }; - return singleEvaluator; + return createSingleEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); } private static ParDoInProcessEvaluator createSingleEvaluator( @@ -69,7 +52,8 @@ private static ParDoInProcessEvaluator createSingleEva UncommittedBundle outputBundle = evaluationContext.createBundle(inputBundle, application.getOutput()); - InProcessExecutionContext executionContext = evaluationContext.getExecutionContext(application); + InProcessExecutionContext executionContext = + evaluationContext.getExecutionContext(application, inputBundle.getKey()); String stepName = evaluationContext.getStepName(application); InProcessStepContext stepContext = executionContext.getOrCreateStepContext(stepName, stepName, null); @@ -92,6 +76,10 @@ private static ParDoInProcessEvaluator createSingleEva runner.startBundle(); return new ParDoInProcessEvaluator( - runner, application, counters, Collections.>singleton(outputBundle)); + runner, + application, + counters, + Collections.>singleton(outputBundle), + stepContext); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java index ea6e00a79a..4428e413b8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/util/InMemoryWatermarkManager.java @@ -1244,6 +1244,23 @@ Iterable getSetTimers() { Iterable getDeletedTimers() { return deletedTimers; } + + @Override + public int hashCode() { + return Objects.hash(key, completedTimers, setTimers, deletedTimers); + } + + @Override + public boolean equals(Object other) { + if (other == null || !(other instanceof TimerUpdate)) { + return false; + } + TimerUpdate that = (TimerUpdate) other; + return Objects.equals(this.key, that.key) + && Objects.equals(this.completedTimers, that.completedTimers) + && Objects.equals(this.setTimers, that.setTimers) + && Objects.equals(this.deletedTimers, that.deletedTimers); + } } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java index c55a9d53a8..80863b9b76 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java @@ -15,15 +15,19 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -31,9 +35,20 @@ import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.BagState; +import com.google.cloud.dataflow.sdk.util.state.StateNamespace; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; +import com.google.cloud.dataflow.sdk.util.state.StateTag; +import com.google.cloud.dataflow.sdk.util.state.StateTags; +import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionTuple; @@ -41,6 +56,7 @@ import com.google.cloud.dataflow.sdk.values.TupleTagList; import org.hamcrest.Matchers; +import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; @@ -81,20 +97,18 @@ public void processElement(ProcessContext c) { PCollection lengthOutput = outputTuple.get(lengthTag); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = - InProcessBundle.unkeyed(mainOutput); - UncommittedBundle elementOutputBundle = - InProcessBundle.unkeyed(elementOutput); - UncommittedBundle lengthOutputBundle = - InProcessBundle.unkeyed(lengthOutput); + UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + UncommittedBundle lengthOutputBundle = InProcessBundle.unkeyed(lengthOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); when(evaluationContext.createBundle(inputBundle, elementOutput)) .thenReturn(elementOutputBundle); when(evaluationContext.createBundle(inputBundle, lengthOutput)).thenReturn(lengthOutputBundle); - InProcessExecutionContext executionContext = new InProcessExecutionContext(); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal())) + InProcessExecutionContext executionContext = + new InProcessExecutionContext(null, null, null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) .thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -173,8 +187,8 @@ public void processElement(ProcessContext c) { .thenReturn(elementOutputBundle); InProcessExecutionContext executionContext = - new InProcessExecutionContext(); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal())) + new InProcessExecutionContext(null, null, null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) .thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -211,5 +225,190 @@ public void processElement(ProcessContext c) { WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000)), WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING))); } -} + @Test + public void finishBundleWithStatePutsStateInResult() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + + TupleTag> mainOutputTag = new TupleTag>() {}; + final TupleTag elementTag = new TupleTag<>(); + + final StateTag> watermarkTag = + StateTags.watermarkStateInternal("myId", OutputTimeFns.outputAtEndOfWindow()); + final StateTag> bagTag = StateTags.bag("myBag", StringUtf8Coder.of()); + final StateNamespace windowNs = + StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE); + BoundMulti> pardo = + ParDo.of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.windowingInternals() + .stateInternals() + .state(StateNamespaces.global(), watermarkTag) + .add(new Instant(20202L + c.element().length())); + c.windowingInternals() + .stateInternals() + .state( + StateNamespaces.window( + GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE), + bagTag) + .add(c.element()); + } + }) + .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); + PCollectionTuple outputTuple = input.apply(pardo); + + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + + PCollection> mainOutput = outputTuple.get(mainOutputTag); + PCollection elementOutput = outputTuple.get(elementTag); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + + when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); + when(evaluationContext.createBundle(inputBundle, elementOutput)) + .thenReturn(elementOutputBundle); + + InProcessExecutionContext executionContext = + new InProcessExecutionContext(null, "myKey", null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = + new ParDoMultiEvaluatorFactory().forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); + evaluator.processElement( + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getOutputBundles(), + Matchers.>containsInAnyOrder(mainOutputBundle, elementOutputBundle)); + assertThat(result.getWatermarkHold(), equalTo(new Instant(20205L))); + assertThat(result.getState(), not(nullValue())); + assertThat( + result.getState().state(StateNamespaces.global(), watermarkTag).read(), + equalTo(new Instant(20205L))); + assertThat( + result.getState().state(windowNs, bagTag).read(), + containsInAnyOrder("foo", "bara", "bazam")); + } + + @Test + public void finishBundleWithStateAndTimersPutsTimersInResult() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + + TupleTag> mainOutputTag = new TupleTag>() {}; + final TupleTag elementTag = new TupleTag<>(); + + final TimerData addedTimer = + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0).plus(Duration.standardMinutes(5)), + new Instant(1) + .plus(Duration.standardMinutes(5)) + .plus(Duration.standardHours(1)))), + new Instant(54541L), + TimeDomain.EVENT_TIME); + final TimerData deletedTimer = + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardHours(1)))), + new Instant(3400000), + TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + + BoundMulti> pardo = + ParDo.of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.windowingInternals().stateInternals(); + c.windowingInternals() + .timerInternals() + .setTimer( + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0).plus(Duration.standardMinutes(5)), + new Instant(1) + .plus(Duration.standardMinutes(5)) + .plus(Duration.standardHours(1)))), + new Instant(54541L), + TimeDomain.EVENT_TIME)); + c.windowingInternals() + .timerInternals() + .deleteTimer( + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0), + new Instant(0).plus(Duration.standardHours(1)))), + new Instant(3400000), + TimeDomain.SYNCHRONIZED_PROCESSING_TIME)); + } + }) + .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); + PCollectionTuple outputTuple = input.apply(pardo); + + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + + PCollection> mainOutput = outputTuple.get(mainOutputTag); + PCollection elementOutput = outputTuple.get(elementTag); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + + when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); + when(evaluationContext.createBundle(inputBundle, elementOutput)) + .thenReturn(elementOutputBundle); + + InProcessExecutionContext executionContext = + new InProcessExecutionContext(null, "myKey", null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = + new ParDoMultiEvaluatorFactory().forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); + evaluator.processElement( + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getTimerUpdate(), + equalTo( + TimerUpdate.builder("myKey") + .setTimer(addedTimer) + .setTimer(addedTimer) + .setTimer(addedTimer) + .deletedTimer(deletedTimer) + .deletedTimer(deletedTimer) + .deletedTimer(deletedTimer) + .build())); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java index 4fc765ce5d..919e69e9dd 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java @@ -15,28 +15,45 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessExecutionContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.util.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.util.InProcessBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.BagState; +import com.google.cloud.dataflow.sdk.util.state.StateNamespace; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; +import com.google.cloud.dataflow.sdk.util.state.StateTag; +import com.google.cloud.dataflow.sdk.util.state.StateTags; +import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TupleTag; import org.hamcrest.Matchers; +import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; @@ -65,8 +82,9 @@ public void testParDoInMemoryTransformEvaluator() throws Exception { UncommittedBundle outputBundle = InProcessBundle.unkeyed(collection); when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); - InProcessExecutionContext executionContext = new InProcessExecutionContext(); - when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal())) + InProcessExecutionContext executionContext = + new InProcessExecutionContext(null, null, null, null); + when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), null)) .thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -112,8 +130,8 @@ public void testSideOutputToUndeclaredSideOutputSucceeds() throws Exception { InProcessBundle.unkeyed(collection); when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); InProcessExecutionContext executionContext = - new InProcessExecutionContext(); - when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal())) + new InProcessExecutionContext(null, null, null, null); + when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), null)) .thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -134,5 +152,161 @@ public void testSideOutputToUndeclaredSideOutputSucceeds() throws Exception { assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); assertThat(result.getCounters(), equalTo(counters)); } + + @Test + public void finishBundleWithStatePutsStateInResult() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + + final StateTag> watermarkTag = + StateTags.watermarkStateInternal("myId", OutputTimeFns.outputAtEarliestInputTimestamp()); + final StateTag> bagTag = StateTags.bag("myBag", StringUtf8Coder.of()); + final StateNamespace windowNs = + StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE); + ParDo.Bound> pardo = + ParDo.of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.windowingInternals() + .stateInternals() + .state(StateNamespaces.global(), watermarkTag) + .add(new Instant(124443L - c.element().length())); + c.windowingInternals() + .stateInternals() + .state( + StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE), + bagTag) + .add(c.element()); + } + }); + PCollection> mainOutput = input.apply(pardo); + + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + + when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); + + InProcessExecutionContext executionContext = + new InProcessExecutionContext(null, "myKey", null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = + new ParDoSingleEvaluatorFactory() + .forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + evaluator.processElement( + WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); + evaluator.processElement( + WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat(result.getWatermarkHold(), equalTo(new Instant(124438L))); + assertThat(result.getState(), not(nullValue())); + assertThat( + result.getState().state(StateNamespaces.global(), watermarkTag).read(), + equalTo(new Instant(124438L))); + assertThat( + result.getState().state(windowNs, bagTag).read(), + containsInAnyOrder("foo", "bara", "bazam")); + } + + @Test + public void finishBundleWithStateAndTimersPutsTimersInResult() throws Exception { + TestPipeline p = TestPipeline.create(); + + PCollection input = p.apply(Create.of("foo", "bara", "bazam")); + + final TimerData addedTimer = + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0).plus(Duration.standardMinutes(5)), + new Instant(1) + .plus(Duration.standardMinutes(5)) + .plus(Duration.standardHours(1)))), + new Instant(54541L), + TimeDomain.EVENT_TIME); + final TimerData deletedTimer = + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardHours(1)))), + new Instant(3400000), + TimeDomain.SYNCHRONIZED_PROCESSING_TIME); + + ParDo.Bound> pardo = + ParDo.of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.windowingInternals().stateInternals(); + c.windowingInternals() + .timerInternals() + .setTimer( + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0).plus(Duration.standardMinutes(5)), + new Instant(1) + .plus(Duration.standardMinutes(5)) + .plus(Duration.standardHours(1)))), + new Instant(54541L), + TimeDomain.EVENT_TIME)); + c.windowingInternals() + .timerInternals() + .deleteTimer( + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0), + new Instant(0).plus(Duration.standardHours(1)))), + new Instant(3400000), + TimeDomain.SYNCHRONIZED_PROCESSING_TIME)); + } + }); + PCollection> mainOutput = input.apply(pardo); + + CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + + InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); + UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + + when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); + + InProcessExecutionContext executionContext = + new InProcessExecutionContext(null, "myKey", null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) + .thenReturn(executionContext); + CounterSet counters = new CounterSet(); + when(evaluationContext.createCounterSet()).thenReturn(counters); + + TransformEvaluator evaluator = + new ParDoSingleEvaluatorFactory() + .forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + + evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); + + InProcessTransformResult result = evaluator.finishBundle(); + assertThat( + result.getTimerUpdate(), + equalTo( + TimerUpdate.builder("myKey") + .setTimer(addedTimer) + .deletedTimer(deletedTimer) + .build())); + } } From 7b28d235000b9232a4fe55ebde76f77be26bd094 Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 24 Feb 2016 16:27:52 -0800 Subject: [PATCH 219/751] Rollback reverts "Move Google Cloud Dataflow native sinks to worker module" This is for Apache Beam. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115507028 --- .../dataflow/sdk/runners/worker/AvroSink.java | 135 -------- .../dataflow/sdk/runners/worker/TextSink.java | 291 ------------------ .../dataflow/sdk/util/common/worker/Sink.java | 64 ---- 3 files changed, 490 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java deleted file mode 100644 index b101a2b0fc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/AvroSink.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.ShardingWritableByteChannel; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.ValueOnlyWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import org.apache.avro.Schema; -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.io.DatumWriter; - -import java.io.IOException; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.util.ArrayList; -import java.util.Random; - -/** - * A sink that writes Avro files. - * - * @param the type of the elements written to the sink - */ -public class AvroSink extends Sink> { - - final String filenamePrefix; - final String shardFormat; - final String filenameSuffix; - final int shardCount; - final AvroCoder avroCoder; - final Schema schema; - - public AvroSink(String filename, ValueOnlyWindowedValueCoder coder) { - this(filename, "", "", 1, coder); - } - - public AvroSink(String filenamePrefix, String shardFormat, String filenameSuffix, int shardCount, - ValueOnlyWindowedValueCoder coder) { - if (!(coder.getValueCoder() instanceof AvroCoder)) { - throw new IllegalArgumentException(String.format( - "AvroSink requires an AvroCoder, not a %s", coder.getValueCoder().getClass())); - } - - this.filenamePrefix = filenamePrefix; - this.shardFormat = shardFormat; - this.filenameSuffix = filenameSuffix; - this.shardCount = shardCount; - this.avroCoder = (AvroCoder) coder.getValueCoder(); - this.schema = this.avroCoder.getSchema(); - } - - public SinkWriter> writer(DatumWriter datumWriter) throws IOException { - WritableByteChannel writer = IOChannelUtils.create( - filenamePrefix, shardFormat, filenameSuffix, shardCount, MimeTypes.BINARY); - - if (writer instanceof ShardingWritableByteChannel) { - return new AvroShardingFileWriter(datumWriter, (ShardingWritableByteChannel) writer); - } else { - return new AvroFileWriter(datumWriter, writer); - } - } - - @Override - public SinkWriter> writer() throws IOException { - return writer(avroCoder.createDatumWriter()); - } - - /** The SinkWriter for an AvroSink. */ - class AvroFileWriter implements SinkWriter> { - DataFileWriter fileWriter; - - public AvroFileWriter(DatumWriter datumWriter, WritableByteChannel outputChannel) - throws IOException { - fileWriter = new DataFileWriter<>(datumWriter); - fileWriter.create(schema, Channels.newOutputStream(outputChannel)); - } - - @Override - public long add(WindowedValue value) throws IOException { - fileWriter.append(value.getValue()); - // DataFileWriter doesn't support returning the length written. Use the - // coder instead. - return CoderUtils.encodeToByteArray(avroCoder, value.getValue()).length; - } - - @Override - public void close() throws IOException { - fileWriter.close(); - } - } - - /** The SinkWriter for an AvroSink, which supports sharding. */ - class AvroShardingFileWriter implements SinkWriter> { - private ArrayList fileWriters = new ArrayList<>(); - private final Random random = new Random(); - - public AvroShardingFileWriter( - DatumWriter datumWriter, ShardingWritableByteChannel outputChannel) throws IOException { - for (int i = 0; i < outputChannel.getNumShards(); i++) { - fileWriters.add(new AvroFileWriter(datumWriter, outputChannel.getChannel(i))); - } - } - - @Override - public long add(WindowedValue value) throws IOException { - return fileWriters.get(random.nextInt(fileWriters.size())).add(value); - } - - @Override - public void close() throws IOException { - for (AvroFileWriter fileWriter : fileWriters) { - fileWriter.close(); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java deleted file mode 100644 index f48183cc17..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/TextSink.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.ShardingWritableByteChannel; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.common.worker.Sink; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.nio.channels.WritableByteChannel; -import java.util.Random; - -import javax.annotation.Nullable; - -/** - * A sink that writes text files. - * - * @param the type of the elements written to the sink - */ -public class TextSink extends Sink { - - static final byte[] NEWLINE = getNewline(); - - private static byte[] getNewline() { - String newline = "\n"; - try { - return newline.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("UTF-8 not supported", e); - } - } - - final String namePrefix; - final String shardFormat; - final String nameSuffix; - final int shardCount; - final boolean appendTrailingNewlines; - final String header; - final String footer; - final Coder coder; - - /** - * For testing only. - * - *

    Used by simple tests that write to a single unsharded file. - */ - public static TextSink> createForTest( - String filename, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - return create(filename, - "", - "", - 1, - appendTrailingNewlines, - header, - footer, - WindowedValue.getValueOnlyCoder(coder)); - } - - /** - * For DirectPipelineRunner only. - * It wraps the coder with {@code WindowedValue.ValueOnlyCoder}. - */ - public static TextSink> createForDirectPipelineRunner( - String filenamePrefix, - String shardFormat, - String filenameSuffix, - int shardCount, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - return create(filenamePrefix, - shardFormat, - filenameSuffix, - shardCount, - appendTrailingNewlines, - header, - footer, - WindowedValue.getValueOnlyCoder(coder)); - } - - /** - * Constructs a new TextSink. - * - * @param filenamePrefix the prefix of output filenames. - * @param shardFormat the shard name template to use for output filenames. - * @param filenameSuffix the suffix of output filenames. - * @param shardCount the number of outupt shards to produce. - * @param appendTrailingNewlines true to append newlines to each output line. - * @param header text to place at the beginning of each output file. - * @param footer text to place at the end of each output file. - * @param coder the code used to encode elements for output. - */ - public static TextSink create(String filenamePrefix, - String shardFormat, - String filenameSuffix, - int shardCount, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - return new TextSink<>(filenamePrefix, - shardFormat, - filenameSuffix, - shardCount, - appendTrailingNewlines, - header, - footer, - coder); - } - - private TextSink(String filenamePrefix, - String shardFormat, - String filenameSuffix, - int shardCount, - boolean appendTrailingNewlines, - @Nullable String header, - @Nullable String footer, - Coder coder) { - this.namePrefix = filenamePrefix; - this.shardFormat = shardFormat; - this.nameSuffix = filenameSuffix; - this.shardCount = shardCount; - this.appendTrailingNewlines = appendTrailingNewlines; - this.header = header; - this.footer = footer; - this.coder = coder; - } - - @Override - public SinkWriter writer() throws IOException { - String mimeType; - - if (!(coder instanceof WindowedValueCoder)) { - throw new IOException( - "Expected WindowedValueCoder for inputCoder, got: " - + coder.getClass().getName()); - } - Coder valueCoder = ((WindowedValueCoder) coder).getValueCoder(); - if (valueCoder.equals(StringUtf8Coder.of())) { - mimeType = MimeTypes.TEXT; - } else { - mimeType = MimeTypes.BINARY; - } - - WritableByteChannel writer = IOChannelUtils.create(namePrefix, shardFormat, - nameSuffix, shardCount, mimeType); - - if (writer instanceof ShardingWritableByteChannel) { - return new ShardingTextFileWriter((ShardingWritableByteChannel) writer); - } else { - return new TextFileWriter(writer); - } - } - - /** - * Abstract SinkWriter base class shared by sharded and unsharded Text - * writer implementations. - */ - abstract class AbstractTextFileWriter implements SinkWriter { - protected void init() throws IOException { - if (header != null) { - printLine(ShardingWritableByteChannel.ALL_SHARDS, - CoderUtils.encodeToByteArray(StringUtf8Coder.of(), header)); - } - } - - /** - * Adds a value to the sink. Returns the size in bytes of the data written. - * The return value does -not- include header/footer size. - */ - @Override - public long add(T value) throws IOException { - return printLine(getShardNum(value), - CoderUtils.encodeToByteArray(coder, value)); - } - - @Override - public void close() throws IOException { - if (footer != null) { - printLine(ShardingWritableByteChannel.ALL_SHARDS, - CoderUtils.encodeToByteArray(StringUtf8Coder.of(), footer)); - } - } - - protected long printLine(int shardNum, byte[] line) throws IOException { - long length = line.length; - write(shardNum, ByteBuffer.wrap(line)); - - if (appendTrailingNewlines) { - write(shardNum, ByteBuffer.wrap(NEWLINE)); - length += NEWLINE.length; - } - - return length; - } - - protected abstract void write(int shardNum, ByteBuffer buf) - throws IOException; - protected abstract int getShardNum(T value); - } - - /** An unsharded SinkWriter for a TextSink. */ - class TextFileWriter extends AbstractTextFileWriter { - private final WritableByteChannel outputChannel; - - TextFileWriter(WritableByteChannel outputChannel) throws IOException { - this.outputChannel = outputChannel; - init(); - } - - @Override - public void close() throws IOException { - try { - super.close(); - } finally { - outputChannel.close(); - } - } - - @Override - protected void write(int shardNum, ByteBuffer buf) throws IOException { - outputChannel.write(buf); - } - - @Override - protected int getShardNum(T value) { - return 0; - } - } - - /** A sharding SinkWriter for a TextSink. */ - class ShardingTextFileWriter extends AbstractTextFileWriter { - private final Random rng = new Random(); - private final int numShards; - private final ShardingWritableByteChannel outputChannel; - - // TODO: add support for user-defined sharding function. - ShardingTextFileWriter(ShardingWritableByteChannel outputChannel) - throws IOException { - this.outputChannel = outputChannel; - numShards = outputChannel.getNumShards(); - init(); - } - - @Override - public void close() throws IOException { - try { - super.close(); - } finally { - outputChannel.close(); - } - } - - @Override - protected void write(int shardNum, ByteBuffer buf) throws IOException { - outputChannel.writeToShard(shardNum, buf); - } - - @Override - protected int getShardNum(T value) { - return rng.nextInt(numShards); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java deleted file mode 100644 index b48d70b360..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/Sink.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler.StateKind; - -import java.io.IOException; - -/** - * Abstract base class for Sinks. - * - *

    A Sink is written to by getting a SinkWriter and adding values to - * it. - * - * @param the type of the elements written to the sink - */ -public abstract class Sink { - /** - * Returns a Writer that allows writing to this Sink. - */ - public abstract SinkWriter writer() throws IOException; - - /** - * Writes to a Sink. - */ - public interface SinkWriter extends AutoCloseable { - /** - * Adds a value to the sink. Returns the size in bytes of the data written. - */ - public long add(ElemT value) throws IOException; - - @Override - public void close() throws IOException; - } - - /** - * Returns whether this Sink can be restarted. - */ - public boolean supportsRestart() { - return false; - } - - /** - * The default state kind of all the states reported in this Sink. - * Defaults to {@link StateKind#USER}. - */ - protected StateKind getStateSamplerStateKind() { - return StateKind.USER; - } -} From 8b5257fc64be2697d001bd335302e14591aca044 Mon Sep 17 00:00:00 2001 From: tgroh Date: Wed, 24 Feb 2016 17:58:23 -0800 Subject: [PATCH 220/751] Use a static variable for CoderCalled in WriteTest The test is broken when Create serializes the created values at apply-time rather than at execution-time, as the modification happens after the Create is applied within the Write PTransform. Moving to a static variable allows the state of the operation to be captured at any time without breaking the test, so long as the captured (and executed) operation uses the same ClassLoader as the test. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115515376 --- .../main/java/com/google/cloud/dataflow/sdk/io/Write.java | 2 +- .../java/com/google/cloud/dataflow/sdk/io/WriteTest.java | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java index 4d130cc865..0b78b8384e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java @@ -117,7 +117,7 @@ private PDone createWrite( PCollection input, WriteOperation writeOperation) { Pipeline p = input.getPipeline(); - // A coder to user for the WriteOperation. + // A coder to use for the WriteOperation. @SuppressWarnings("unchecked") Coder> operationCoder = (Coder>) SerializableCoder.of(writeOperation.getClass()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java index 2340187f1c..b92f2f18ea 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java @@ -184,8 +184,12 @@ private enum State { FINALIZED } + // Must be static in case the WriteOperation is serialized before the its coder is obtained. + // If this occurs, the value will be modified but not reflected in the WriteOperation that is + // executed by the runner, and the finalize method will fail. + private static volatile boolean coderCalled = false; + private State state = State.INITIAL; - private boolean coderCalled = false; private final TestSink sink; private final UUID id = UUID.randomUUID(); From 510a55dbbf9b6d1a94817f7e8e78e8211dd559a4 Mon Sep 17 00:00:00 2001 From: lcwik Date: Wed, 24 Feb 2016 18:01:53 -0800 Subject: [PATCH 221/751] Honor user requested shard limits for AvroIO.Write on DirectPipelineRunner During the migration to custom sink within AvroIO, shard controls were removed for DirectPipelineRunner. This change adds them back. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115515647 --- .../sdk/runners/DirectPipelineRunner.java | 59 +++++++++++++++++++ .../sdk/runners/DirectPipelineRunnerTest.java | 53 +++++++++++++++++ 2 files changed, 112 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java index 4543b5a534..872cfef7fb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.ListCoder; +import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.FileBasedSink; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; @@ -240,6 +241,8 @@ public OutputT apply( return (OutputT) applyTestCombine((Combine.GroupedValues) transform, (PCollection) input); } else if (transform instanceof TextIO.Write.Bound) { return (OutputT) applyTextIOWrite((TextIO.Write.Bound) transform, (PCollection) input); + } else if (transform instanceof AvroIO.Write.Bound) { + return (OutputT) applyAvroIOWrite((AvroIO.Write.Bound) transform, (PCollection) input); } else { return super.apply(transform, input); } @@ -342,6 +345,62 @@ private PDone applyTextIOWrite(TextIO.Write.Bound transform, PCollection< return input.apply(new DirectTextIOWrite<>(transform)); } + /** + * Applies AvroIO.Write honoring user requested sharding controls (i.e. withNumShards) + * by applying a partition function based upon the number of shards the user requested. + */ + private static class DirectAvroIOWrite extends PTransform, PDone> { + private final AvroIO.Write.Bound transform; + + private DirectAvroIOWrite(AvroIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + checkState(transform.getNumShards() > 1, + "DirectAvroIOWrite is expected to only be used when sharding controls are required."); + + // Evenly distribute all the elements across the partitions. + PCollectionList partitionedElements = + input.apply(Partition.of(transform.getNumShards(), + new ElementProcessingOrderPartitionFn())); + + // For each input PCollection partition, create a write transform that represents + // one of the specific shards. + for (int i = 0; i < transform.getNumShards(); ++i) { + /* + * This logic mirrors the file naming strategy within + * {@link FileBasedSink#generateDestinationFilenames()} + */ + String outputFilename = IOChannelUtils.constructName( + transform.getFilenamePrefix(), + transform.getShardNameTemplate(), + getFileExtension(transform.getFilenameSuffix()), + i, + transform.getNumShards()); + + String transformName = String.format("%s(Shard:%s)", transform.getName(), i); + partitionedElements.get(i).apply(transformName, + transform.withNumShards(1).withShardNameTemplate("").withSuffix("").to(outputFilename)); + } + return PDone.in(input.getPipeline()); + } + } + + /** + * Apply the override for AvroIO.Write.Bound if the user requested sharding controls + * greater than one. + */ + private PDone applyAvroIOWrite(AvroIO.Write.Bound transform, PCollection input) { + if (transform.getNumShards() <= 1) { + // By default, the DirectPipelineRunner outputs to only 1 shard. Since the user never + // requested sharding controls greater than 1, we default to outputting to 1 file. + return super.apply(transform.withNumShards(1), input); + } + return input.apply(new DirectAvroIOWrite<>(transform)); + } + /** * The implementation may split the {@link KeyedCombineFn} into ADD, MERGE and EXTRACT phases ( * see {@code com.google.cloud.dataflow.sdk.runners.worker.CombineValuesFn}). In order to emulate diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java index 4a0f91c917..6524e144f8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java @@ -25,8 +25,10 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; @@ -36,8 +38,10 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.common.collect.Iterables; import com.google.common.io.Files; +import org.apache.avro.file.DataFileReader; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -154,4 +158,53 @@ public void testTextIOWriteWithLimitedNumberOfShards() throws Exception { assertThat(allContents, containsInAnyOrder(expectedElements)); } + + @Test + public void testAvroIOWriteWithDefaultShardingStrategy() throws Exception { + String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "output"); + Pipeline p = DirectPipeline.createForTest(); + String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; + p.apply(Create.of(expectedElements)) + .apply(AvroIO.Write.withSchema(String.class).to(prefix).withSuffix(".avro")); + p.run(); + + String filename = + IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".avro", 0, 1); + List fileContents = new ArrayList<>(); + Iterables.addAll(fileContents, DataFileReader.openReader( + new File(filename), AvroCoder.of(String.class).createDatumReader())); + + // Ensure that each file got at least one record + assertFalse(fileContents.isEmpty()); + + assertThat(fileContents, containsInAnyOrder(expectedElements)); + } + + @Test + public void testAvroIOWriteWithLimitedNumberOfShards() throws Exception { + final int numShards = 3; + String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "shardedOutput"); + Pipeline p = DirectPipeline.createForTest(); + String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; + p.apply(Create.of(expectedElements)) + .apply(AvroIO.Write.withSchema(String.class).to(prefix) + .withNumShards(numShards).withSuffix(".avro")); + p.run(); + + List allContents = new ArrayList<>(); + for (int i = 0; i < numShards; ++i) { + String shardFileName = + IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".avro", i, 3); + List shardFileContents = new ArrayList<>(); + Iterables.addAll(shardFileContents, DataFileReader.openReader( + new File(shardFileName), AvroCoder.of(String.class).createDatumReader())); + + // Ensure that each file got at least one record + assertFalse(shardFileContents.isEmpty()); + + allContents.addAll(shardFileContents); + } + + assertThat(allContents, containsInAnyOrder(expectedElements)); + } } From 6c710405af5fef7e8a6b334a7e393dc5d8ab006e Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 25 Feb 2016 10:07:00 -0800 Subject: [PATCH 222/751] Adjust dependencies to avoid pulling in unneeded stax-api This is the javax.xml.stream API that is provided with Java 1.6 and up. - The dependency on stax-api from stax2-api switched from "compile" scope to "provided" scope in current versions, so we can remove the transitive dependency simply by upgrade. - The woodstox-core-asl package is upgraded to a version explicitly compatible with the new version of stax2-api. - The dependency on stax-api from woodstox-core-asl remains in "compile" scope even after upgrade, so this change explicitly suppresses it. Selected bits of `mvn dependency:tree -Dverbose`: [INFO] com.google.cloud.dataflow:google-cloud-dataflow-java-sdk-all:jar:1...) -[INFO] +- org.codehaus.woodstox:stax2-api:jar:3.1.1:compile -[INFO] | \- javax.xml.stream:stax-api:jar:1.0-2:compile -[INFO] +- org.codehaus.woodstox:woodstox-core-asl:jar:4.1.2:compile -[INFO] | +- (javax.xml.stream:stax-api:jar:1.0-2:compile - omitted for d...) -[INFO] | \- (org.codehaus.woodstox:stax2-api:jar:3.1.1:compile - omitted...) +[INFO] +- org.codehaus.woodstox:stax2-api:jar:3.1.4:compile +[INFO] +- org.codehaus.woodstox:woodstox-core-asl:jar:4.4.1:compile +[INFO] | \- (org.codehaus.woodstox:stax2-api:jar:3.1.4:compile - omitted...) ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115574469 --- pom.xml | 2 ++ sdk/pom.xml | 11 +++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 760a10d92f..bfade1a610 100644 --- a/pom.xml +++ b/pom.xml @@ -82,7 +82,9 @@ 3.0.0-beta-1 v1-rev7-1.21.0 1.7.14 + 3.1.4 v1-rev53-1.21.0 + 4.4.1 pom diff --git a/sdk/pom.xml b/sdk/pom.xml index aeead722ca..1f15b02643 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -667,15 +667,22 @@ org.codehaus.woodstox stax2-api - 3.1.1 + ${stax2.version} true org.codehaus.woodstox woodstox-core-asl - 4.1.2 + ${woodstox.version} true + + + + javax.xml.stream + stax-api + + @@ -661,8 +674,11 @@ org.codehaus.woodstox @@ -675,6 +691,7 @@ org.codehaus.woodstox woodstox-core-asl ${woodstox.version} + runtime true @@ -687,12 +704,14 @@ org.tukaani xz 1.5 + runtime true diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java index d684d2216c..1ead39187d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java @@ -17,6 +17,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.JAXBCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.common.base.Preconditions; import org.codehaus.stax2.XMLInputFactory2; @@ -94,18 +95,21 @@ *

    Currently, only XML files that use single-byte characters are supported. Using a file that * contains multi-byte characters may result in data loss or duplication. * - *

    To use {@code XmlSource}, explicitly declare dependencies on following two jars from Woodstox - * StAX XML parser. - * (1) stax2-api-3.1.1.jar - * (2) woodstox-core-asl-4.1.2.jar - * These dependencies have been declared as optional in Maven sdk/pom.xml file of Google Cloud - * Dataflow. + *

    To use {@link XmlSource}: + *

      + *
    1. Explicitly declare a dependency on org.codehaus.woodstox:stax2-api
    2. + *
    3. Include a compatible implementation on the classpath at run-time, + * such as org.codehaus.woodstox:woodstox-core-asl
    4. + *
    + * + *

    These dependencies have been declared as optional in Maven sdk/pom.xml file of + * Google Cloud Dataflow. * *

    Permissions

    * Permission requirements depend on the * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner PipelineRunner} that is * used to execute the Dataflow job. Please refer to the documentation of corresponding - * {@code PipelineRunner}s for more details. + * {@link PipelineRunner PipelineRunners} for more details. * * @param Type of the objects that represent the records of the XML file. The * {@code PCollection} generated by this source will be of this type. From c290b5e1b4b65a74ef73889722fde285a168b346 Mon Sep 17 00:00:00 2001 From: klk Date: Thu, 25 Feb 2016 15:37:18 -0800 Subject: [PATCH 228/751] Fix worker dependencies and turn on strict checking Here is a pruned and edited tree diff of the dependency:tree output. It is formatted to emphasize the packages that were SDK deps that are now direct deps. Many of these are actually provided by lots of transitive dependencies. [INFO] com.google.cloud.dataflow:google-cloud-dataflow-java-worker-all [INFO] +- com.google.cloud.dataflow:google-cloud-dataflow-java-sdk-all -[INFO] | +- com.google.api-client:google-api-client:jar:1.21.0 -[INFO] | +- com.google.apis:google-api-services-bigquery:jar:v2-rev248-1... -[INFO] | +- com.google.apis:google-api-services-dataflow:jar:v1b3-rev19-... -[INFO] | +- com.google.cloud.dataflow:google-cloud-dataflow-java-proto-l... -[INFO] | +- com.google.http-client:google-http-client:jar:1.19.0 -[INFO] | +- com.google.http-client:google-http-client-jackson2:jar:1.19.... -[INFO] | +- com.google.protobuf:protobuf-java:jar:3.0.0-beta-1 -[INFO] | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0 -[INFO] | +- com.fasterxml.jackson.core:jackson-core:jar:2.7.0 -[INFO] | +- com.fasterxml.jackson.core:jackson-databind:jar:2.7.0 -[INFO] | +- org.apache.avro:avro:jar:1.7.7 -[INFO] | +- joda-time:joda-time:jar:2.4 -[INFO] | +- org.slf4j:slf4j-api:jar:1.7.14 +[INFO] +- com.google.api-client:google-api-client:jar:1.21.0 +[INFO] +- com.google.apis:google-api-services-bigquery:jar:v2-rev248-1.21... +[INFO] +- com.google.apis:google-api-services-dataflow:jar:v1b3-rev19-1.2... +[INFO] +- com.google.apis:google-api-services-datastore-protobuf:jar:v1be... +[INFO] +- com.google.cloud.dataflow:google-cloud-dataflow-java-proto-libr... +[INFO] +- com.google.http-client:google-http-client:jar:1.21.0 +[INFO] +- com.google.http-client:google-http-client-jackson2:jar:1.21.0 +[INFO] +- com.google.protobuf:protobuf-java:jar:3.0.0-beta-1:compile +[INFO] +- com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0 +[INFO] +- com.fasterxml.jackson.core:jackson-core:jar:2.7.0 +[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.7.0 +[INFO] +- joda-time:joda-time:jar:2.4 +[INFO] +- org.apache.avro:avro:jar:1.7.7 +[INFO] +- org.slf4j:slf4j-api:jar:1.7.14 One from gRPC: [INFO] +- io.grpc:grpc-all:jar:0.12.0 [INFO] | +- io.grpc:grpc-netty:jar:0.12.0 -[INFO] | | | +- io.netty:netty-handler:jar:4.1.0.Beta8 +[INFO] +- io.netty:netty-handler:jar:4.1.0.Beta8 One from jetty: [INFO] +- org.eclipse.jetty:jetty-server:jar:9.2.10.v20150310 [INFO] | +- org.eclipse.jetty:jetty-http:jar:9.2.10.v20150310 -[INFO] | | \- org.eclipse.jetty:jetty-util:jar:9.2.10.v20150310 +[INFO] +- org.eclipse.jetty:jetty-util:jar:9.2.10.v20150310 ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115612383 --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index bfade1a610..ba130d25a3 100644 --- a/pom.xml +++ b/pom.xml @@ -71,6 +71,7 @@ v2-rev248-1.21.0 0.2.3 v1b3-rev19-1.21.0 + 0.5.160222 v1beta2-rev1-4.0.0 1.21.0 19.0 From d4dcaaa0500a6dbd314fe7119d73c461b2de17f7 Mon Sep 17 00:00:00 2001 From: davor Date: Thu, 25 Feb 2016 18:01:30 -0800 Subject: [PATCH 229/751] Update worker harness container image Pin version to the GitHub push 20160225-00. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=115626265 --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 06b2295080..6eb6c2f7ad 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -207,9 +207,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:INVALID"; + = "dataflow.gcr.io/v1beta3/java-batch:github-20160225-00"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:INVALID"; + = "dataflow.gcr.io/v1beta3/java-streaming:github-20160225-00"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 049751dbd8232cb5a5d807718f4dbdb96e2c84f7 Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Mon, 29 Feb 2016 23:11:42 -0800 Subject: [PATCH 230/751] Exclude old version of Google API client libraries Our com.google.apis:google-api-services-datastore-protobuf dependency has a transitive dependency on a very old Google API client library. This change suppresses that dependency and replaces it by depending on a version that matches our other API dependencies. --- sdk/pom.xml | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/sdk/pom.xml b/sdk/pom.xml index 4995da06d3..c49c175709 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -544,6 +544,28 @@ + + + com.google.http-client + google-http-client-jackson + ${google-clients.version} + + + + com.google.guava + guava-jdk5 + + + + org.codehaus.jackson + jackson-core-asl + + + runtime + + com.google.http-client google-http-client-jackson2 @@ -558,6 +580,21 @@ + + com.google.http-client + google-http-client-protobuf + ${google-clients.version} + + + + com.google.guava + guava-jdk5 + + + runtime + + com.google.oauth-client google-oauth-client-java6 @@ -597,6 +634,27 @@ com.google.guava guava-jdk5 + + + com.google.http-client + google-http-client + + + com.google.api-client + google-api-client + + + com.google.oauth-client + google-oauth-client + + + com.google.http-client + google-http-client-jackson + + + com.google.http-client + google-http-client-protobuf + From 9130c7cef6a438fa9e5644ee91a4abf5cd69032f Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Mon, 29 Feb 2016 10:58:10 -0800 Subject: [PATCH 231/751] Delete windmill.proto (not part of Beam) --- sdk/src/main/proto/windmill.proto | 327 ------------------------------ 1 file changed, 327 deletions(-) delete mode 100644 sdk/src/main/proto/windmill.proto diff --git a/sdk/src/main/proto/windmill.proto b/sdk/src/main/proto/windmill.proto deleted file mode 100644 index d9d9706cd0..0000000000 --- a/sdk/src/main/proto/windmill.proto +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/* - * Protocol Buffers describing the interface between streaming Dataflow workers - * and the Windmill servers. - */ - -syntax = "proto2"; - -package windmill; - -option java_package = "com.google.cloud.dataflow.sdk.runners.worker.windmill"; -option java_outer_classname = "Windmill"; - -//////////////////////////////////////////////////////////////////////////////// -// API Data types - -message Message { - required int64 timestamp = 1 [default=-0x8000000000000000]; - required bytes data = 2; - optional bytes metadata = 3; -} - -message Timer { - required bytes tag = 1; - optional int64 timestamp = 2 [default=-0x8000000000000000]; - enum Type { - WATERMARK = 0; - REALTIME = 1; - DEPENDENT_REALTIME = 2; - } - optional Type type = 3 [default = WATERMARK]; - optional string state_family = 4; -} - -message InputMessageBundle { - required string source_computation_id = 1; - repeated Message messages = 2; -} - -message KeyedMessageBundle { - required bytes key = 1; - repeated Message messages = 2; - repeated bytes messages_ids = 3; -} - -message OutputMessageBundle { - optional string destination_computation_id = 1; - optional string destination_stream_id = 3; - repeated KeyedMessageBundle bundles = 2; -} - -message PubSubMessageBundle { - required string topic = 1; - repeated Message messages = 2; - optional string timestamp_label = 3; - optional string id_label = 4; -} - -message TimerBundle { - repeated Timer timers = 1; -} - -message Value { - required int64 timestamp = 1 [default=-0x8000000000000000]; - required bytes data = 2; -} - -message TagValue { - required bytes tag = 1; - optional Value value = 2; - optional string state_family = 3; -} - -message TagList { - required bytes tag = 1; - // In request: All items till this timestamp (inclusive) are deleted before - // adding the new ones listed below. - optional int64 end_timestamp = 2 [default=-0x8000000000000000]; - repeated Value values = 3; - optional string state_family = 4; - - // In request: A previously returned continuation_token from an - // earlier request. Indicates we wish to fetch the next page of - // values. - // In response: Copied from request. - optional bytes request_token = 7; - // In response only: Set when there are values after those returned - // above, but they were suppressed to respect the fetch_max_bytes - // limit. Subsequent requests should copy this to request_token to - // retrieve the next page of values. - optional bytes continuation_token = 5; - // For a TagList fetch request, attempt to limit the size of each fetched tag - // list to this byte limit. - optional int64 fetch_max_bytes = 6 [default = 0x7fffffffffffffff]; -} - -message GlobalDataId { - required string tag = 1; - required bytes version = 2; -} - -message GlobalData { - required GlobalDataId data_id = 1; - optional bool is_ready = 2; - optional bytes data = 3; - optional string state_family = 4; -} - -message SourceState { - optional bytes state = 1; - repeated fixed64 finalize_ids = 2; -} - -message WatermarkHold { - required bytes tag = 1; - repeated int64 timestamps = 2 [packed=true]; - optional bool reset = 3; - optional string state_family = 4; -} - -message WorkItem { - required bytes key = 1; - required fixed64 work_token = 2; - - optional fixed64 cache_token = 7; - - repeated InputMessageBundle message_bundles = 3; - optional TimerBundle timers = 4; - repeated GlobalDataId global_data_id_notifications = 5; - optional SourceState source_state = 6; - optional int64 output_data_watermark = 8 [default=-0x8000000000000000]; -} - -message ComputationWorkItems { - required string computation_id = 1; - repeated WorkItem work = 2; - optional int64 input_data_watermark = 3 [default=-0x8000000000000000]; - optional int64 dependent_realtime_input_watermark = 4 - [default = -0x8000000000000000]; -} - -//////////////////////////////////////////////////////////////////////////////// -// API calls - -// GetWork - -message GetWorkRequest { - required fixed64 client_id = 1; - optional string worker_id = 4; - optional string job_id = 5; - optional int64 max_items = 2 [default = 0xffffffff]; - optional int64 max_bytes = 3 [default = 0x7fffffffffffffff]; - // reserved field number = 6 -} - -message GetWorkResponse { - repeated ComputationWorkItems work = 1; -} - -// GetData - -message KeyedGetDataRequest { - required bytes key = 1; - required fixed64 work_token = 2; - repeated TagValue values_to_fetch = 3; - repeated TagList lists_to_fetch = 4; - repeated WatermarkHold watermark_holds_to_fetch = 5; -} - -message ComputationGetDataRequest { - required string computation_id = 1; - repeated KeyedGetDataRequest requests = 2; -} - -message GetDataRequest { - optional string job_id = 4; - repeated ComputationGetDataRequest requests = 1; - repeated GlobalDataRequest global_data_fetch_requests = 3; - - // DEPRECATED - repeated GlobalDataId global_data_to_fetch = 2; -} - -message KeyedGetDataResponse { - required bytes key = 1; - // The response for this key is not populated due to the fetch failing. - optional bool failed = 2; - repeated TagValue values = 3; - repeated TagList lists = 4; - repeated WatermarkHold watermark_holds = 5; -} - -message ComputationGetDataResponse { - required string computation_id = 1; - repeated KeyedGetDataResponse data = 2; -} - -message GetDataResponse { - repeated ComputationGetDataResponse data = 1; - repeated GlobalData global_data = 2; -} - -// CommitWork - -message Counter { - optional string name = 1; - enum Kind { - SUM = 0; - MAX = 1; - MIN = 2; - MEAN = 3; - }; - optional Kind kind = 2; - - // For SUM, MAX, MIN, AND, OR, MEAN at most one of the following should be - // set. For MEAN it is the sum - optional double double_scalar = 3; - optional int64 int_scalar = 4; - - // Only set for MEAN. Count of elements contributing to the sum. - optional int64 mean_count = 6; - - // True if this metric is reported as the total cumulative aggregate - // value accumulated since the worker started working on this WorkItem. - // By default this is false, indicating that this metric is reported - // as a delta that is not associated with any WorkItem. - optional bool cumulative = 7; -} - -message GlobalDataRequest { - required GlobalDataId data_id = 1; - optional int64 existence_watermark_deadline = 2 [default=0x7FFFFFFFFFFFFFFF]; - optional string state_family = 3; -} - -// next id: 15 -message WorkItemCommitRequest { - required bytes key = 1; - required fixed64 work_token = 2; - repeated OutputMessageBundle output_messages = 3; - repeated PubSubMessageBundle pubsub_messages = 7; - repeated Timer output_timers = 4; - repeated TagValue value_updates = 5; - repeated TagList list_updates = 6; - repeated Counter counter_updates = 8; - repeated GlobalDataRequest global_data_requests = 11; - repeated GlobalData global_data_updates = 10; - optional SourceState source_state_updates = 12; - optional int64 source_watermark = 13 [default=-0x8000000000000000]; - repeated WatermarkHold watermark_holds = 14; - - // DEPRECATED - repeated GlobalDataId global_data_id_requests = 9; -} - -message ComputationCommitWorkRequest { - required string computation_id = 1; - repeated WorkItemCommitRequest requests = 2; -} - -message CommitWorkRequest { - optional string job_id = 2; - repeated ComputationCommitWorkRequest requests = 1; -} - -message CommitWorkResponse {} - -// Configuration - -message GetConfigRequest { - optional string job_id = 2; - repeated string computations = 1; -} - -message GetConfigResponse { - repeated string cloud_works = 1; - - message NameMapEntry { - optional string user_name = 1; - optional string system_name = 2; - } - - // Map of user names to system names - repeated NameMapEntry name_map = 2; - - message SystemNameToComputationIdMapEntry { - optional string system_name = 1; - optional string computation_id = 2; - } - repeated SystemNameToComputationIdMapEntry - system_name_to_computation_id_map = 3; -} - -// Reporting - -message Exception { - repeated string stack_frames = 1; - optional Exception cause = 2; -} - -message ReportStatsRequest { - optional string job_id = 6; - optional string computation_id = 1; - optional bytes key = 2; - optional fixed64 work_token = 3; - repeated Exception exceptions = 4; - repeated Counter counter_updates = 5; -} - -message ReportStatsResponse { - optional bool failed = 1; -} From a29ef93ef19d1d3ea32993cf7f5e633fecba653b Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Mon, 29 Feb 2016 10:58:29 -0800 Subject: [PATCH 232/751] Delete windmill_service.proto (not part of Beam) --- sdk/src/main/proto/windmill_service.proto | 27 ----------------------- 1 file changed, 27 deletions(-) delete mode 100644 sdk/src/main/proto/windmill_service.proto diff --git a/sdk/src/main/proto/windmill_service.proto b/sdk/src/main/proto/windmill_service.proto deleted file mode 100644 index bd25fe5efc..0000000000 --- a/sdk/src/main/proto/windmill_service.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto2"; - -import "windmill.proto"; - -package google.dataflow.windmillservice.v1alpha1; - -// The Cloud Windmill Service API used by GCE to acquire and process streaming -// Dataflow work. -service CloudWindmillServiceV1Alpha1 { - // Gets streaming Dataflow work. - rpc GetWork(.windmill.GetWorkRequest) returns(.windmill.GetWorkResponse); - - // Gets data from Windmill. - rpc GetData(.windmill.GetDataRequest) returns(.windmill.GetDataResponse); - - // Commits previously acquired work. - rpc CommitWork(.windmill.CommitWorkRequest) - returns(.windmill.CommitWorkResponse); - - // Gets dependant configuration from windmill. - rpc GetConfig(.windmill.GetConfigRequest) - returns(.windmill.GetConfigResponse); - - // Reports stats to Windmill. - rpc ReportStats(.windmill.ReportStatsRequest) - returns(.windmill.ReportStatsResponse); -} \ No newline at end of file From bf464a3346b15f4156a1335d305a440693b0de0d Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 29 Feb 2016 15:24:49 -0800 Subject: [PATCH 233/751] Move 'update' pipeline option to correct interface --- .../sdk/options/DataflowPipelineDebugOptions.java | 4 ++++ .../sdk/options/DataflowPipelineOptions.java | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index e94b56df87..3ceec89449 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -172,11 +172,15 @@ public Dataflow create(PipelineOptions options) { /** * Whether to update the currently running pipeline with the same name as this one. + * + * @deprecated This property is replaced by @{link DataflowPipelineOptions#getUpdate()} */ @JsonIgnore + @Deprecated @Description("If set, replace the existing pipeline with the name specified by --jobName with " + "this pipeline, preserving state.") boolean getUpdate(); + @Deprecated void setUpdate(boolean value); /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java index a0f188af07..1aa434299c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java @@ -91,6 +91,19 @@ public interface DataflowPipelineOptions extends String getJobName(); void setJobName(String value); + /** + * Whether to update the currently running pipeline with the same name as this one. + */ + @Override + @SuppressWarnings("deprecation") // base class member deprecated in favor of this one. + @Description( + "If set, replace the existing pipeline with the name specified by --jobName with " + + "this pipeline, preserving state.") + boolean getUpdate(); + @Override + @SuppressWarnings("deprecation") // base class member deprecated in favor of this one. + void setUpdate(boolean value); + /** * Returns a normalized job name constructed from {@link ApplicationNameOptions#getAppName()}, the * local system user name (if available), and the current time. The normalization makes sure that From f7c9052760dde2affa3fd17a6eb9c20898a62744 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 1 Mar 2016 11:38:09 -0800 Subject: [PATCH 234/751] Remove JsonIgnore attribute --- .../cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index 3ceec89449..a14be44987 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -175,7 +175,6 @@ public Dataflow create(PipelineOptions options) { * * @deprecated This property is replaced by @{link DataflowPipelineOptions#getUpdate()} */ - @JsonIgnore @Deprecated @Description("If set, replace the existing pipeline with the name specified by --jobName with " + "this pipeline, preserving state.") From 01e8e1788dbe8322789fab8b2df177f31cd746f9 Mon Sep 17 00:00:00 2001 From: Pei He Date: Wed, 2 Mar 2016 16:28:43 -0800 Subject: [PATCH 235/751] [BEAM-80] Decide EARLY or ON_TIME based on input watermark This change is based on trigger specs. --- .../dataflow/sdk/util/PaneInfoTracker.java | 30 +++++++++--------- .../dataflow/sdk/util/ReduceFnRunner.java | 31 +++++++------------ .../dataflow/sdk/util/ReduceFnRunnerTest.java | 9 +++--- 3 files changed, 32 insertions(+), 38 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index 38499c2e2b..a7818a30a0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -54,13 +54,11 @@ public void clear(StateAccessor state) { * Return a ({@link ReadableState} for) the pane info appropriate for {@code context}. The pane * info includes the timing for the pane, who's calculation is quite subtle. * - * @param isEndOfWindow should be {@code true} only if the pane is being emitted - * because an end-of-window timer has fired and the trigger agreed we should fire. * @param isFinal should be {@code true} only if the triggering machinery can guarantee * no further firings for the */ - public ReadableState getNextPaneInfo(ReduceFn.Context context, - final boolean isEndOfWindow, final boolean isFinal) { + public ReadableState getNextPaneInfo( + ReduceFn.Context context, final boolean isFinal) { final Object key = context.key(); final ReadableState previousPaneFuture = context.state().access(PaneInfoTracker.PANE_INFO_TAG); @@ -76,7 +74,7 @@ public ReadableState readLater() { @Override public PaneInfo read() { PaneInfo previousPane = previousPaneFuture.read(); - return describePane(key, windowMaxTimestamp, previousPane, isEndOfWindow, isFinal); + return describePane(key, windowMaxTimestamp, previousPane, isFinal); } }; } @@ -85,8 +83,8 @@ public void storeCurrentPaneInfo(ReduceFn.Context context, PaneInfo context.state().access(PANE_INFO_TAG).write(currentPane); } - private PaneInfo describePane(Object key, Instant windowMaxTimestamp, PaneInfo previousPane, - boolean isEndOfWindow, boolean isFinal) { + private PaneInfo describePane( + Object key, Instant windowMaxTimestamp, PaneInfo previousPane, boolean isFinal) { boolean isFirst = previousPane == null; Timing previousTiming = isFirst ? null : previousPane.getTiming(); long index = isFirst ? 0 : previousPane.getIndex() + 1; @@ -104,26 +102,28 @@ private PaneInfo describePane(Object key, Instant windowMaxTimestamp, PaneIn // if the output watermark is behind the end of the window. boolean onlyEarlyPanesSoFar = previousTiming == null || previousTiming == Timing.EARLY; + // True is the input watermark hasn't passed the window's max timestamp. + boolean isEarlyForInput = inputWM == null || !inputWM.isAfter(windowMaxTimestamp); + Timing timing; if (isLateForOutput || !onlyEarlyPanesSoFar) { // The output watermark has already passed the end of this window, or we have already // emitted a non-EARLY pane. Irrespective of how this pane was triggered we must // consider this pane LATE. timing = Timing.LATE; - } else if (isEndOfWindow) { - // This is the unique ON_TIME firing for the window. - timing = Timing.ON_TIME; - } else { - // All other cases are EARLY. + } else if (isEarlyForInput) { + // This is an EARLY firing. timing = Timing.EARLY; nonSpeculativeIndex = -1; + } else { + // This is the unique ON_TIME firing for the window. + timing = Timing.ON_TIME; } WindowTracing.debug( "describePane: {} pane (prev was {}) for key:{}; windowMaxTimestamp:{}; " - + "inputWatermark:{}; outputWatermark:{}; isEndOfWindow:{}; isLateForOutput:{}", - timing, previousTiming, key, windowMaxTimestamp, inputWM, outputWM, isEndOfWindow, - isLateForOutput); + + "inputWatermark:{}; outputWatermark:{}; isLateForOutput:{}", + timing, previousTiming, key, windowMaxTimestamp, inputWM, outputWM, isLateForOutput); if (previousPane != null) { // Timing transitions should follow EARLY* ON_TIME? LATE* diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index fe5c474210..1a009bb051 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -289,7 +289,7 @@ public void processElements(Iterable> values) throws Excep ReduceFn.Context renamedContext = contextFactory.base(mergedWindow, StateStyle.RENAMED); triggerRunner.prefetchShouldFire(mergedWindow, directContext.state()); - emitIfAppropriate(directContext, renamedContext, false/* isEndOfWindow */); + emitIfAppropriate(directContext, renamedContext); } // We're all done with merging and emitting elements so can compress the activeWindow state. @@ -532,14 +532,6 @@ public void onTimer(TimerData timer) throws Exception { "ReduceFnRunner.onTimer: Note that timer {} is for non-ACTIVE window {}", timer, window); } - // If this is an end-of-window timer then: - // 1. We need to set a GC timer - // 2. We need to let the PaneInfoTracker know that we are transitioning from early to late, - // and possibly emitting an on-time pane. - boolean isEndOfWindow = - TimeDomain.EVENT_TIME == timer.getDomain() - && timer.getTimestamp().equals(window.maxTimestamp()); - // If this is a garbage collection timer then we should trigger and garbage collect the window. Instant cleanupTime = window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()); boolean isGarbageCollection = @@ -556,7 +548,7 @@ public void onTimer(TimerData timer) throws Exception { // We need to call onTrigger to emit the final pane if required. // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, // and the watermark has passed the end of the window. - onTrigger(directContext, renamedContext, isEndOfWindow, true/* isFinished */); + onTrigger(directContext, renamedContext, true/* isFinished */); } // Cleanup flavor B: Clear all the remaining state for this window since we'll never @@ -569,9 +561,12 @@ public void onTimer(TimerData timer) throws Exception { key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); if (windowIsActive) { - emitIfAppropriate(directContext, renamedContext, isEndOfWindow); + emitIfAppropriate(directContext, renamedContext); } + // If this is an end-of-window timer then, we need to set a GC timer + boolean isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() + && timer.getTimestamp().equals(window.maxTimestamp()); if (isEndOfWindow) { // Since we are processing an on-time firing we should schedule the garbage collection // timer. (If getAllowedLateness is zero then the timer event will be considered a @@ -649,7 +644,7 @@ private boolean shouldDiscardAfterFiring(boolean isFinished) { * Possibly emit a pane if a trigger is ready to fire or timers require it, and cleanup state. */ private void emitIfAppropriate(ReduceFn.Context directContext, - ReduceFn.Context renamedContext, boolean isEndOfWindow) + ReduceFn.Context renamedContext) throws Exception { if (!triggerRunner.shouldFire( directContext.window(), directContext.timers(), directContext.state())) { @@ -667,7 +662,7 @@ private void emitIfAppropriate(ReduceFn.Context directCon // Run onTrigger to produce the actual pane contents. // As a side effect it will clear all element holds, but not necessarily any // end-of-window or garbage collection holds. - onTrigger(directContext, renamedContext, isEndOfWindow, isFinished); + onTrigger(directContext, renamedContext, isFinished); // Now that we've triggered, the pane is empty. nonEmptyPanes.clearPane(renamedContext.state()); @@ -692,13 +687,12 @@ private void emitIfAppropriate(ReduceFn.Context directCon /** * Do we need to emit a pane? */ - private boolean needToEmit( - boolean isEmpty, boolean isEndOfWindow, boolean isFinished, PaneInfo.Timing timing) { + private boolean needToEmit(boolean isEmpty, boolean isFinished, PaneInfo.Timing timing) { if (!isEmpty) { // The pane has elements. return true; } - if (isEndOfWindow && timing == Timing.ON_TIME) { + if (timing == Timing.ON_TIME) { // This is the unique ON_TIME pane. return true; } @@ -715,14 +709,13 @@ private boolean needToEmit( private void onTrigger( final ReduceFn.Context directContext, ReduceFn.Context renamedContext, - boolean isEndOfWindow, boolean isFinished) throws Exception { // Prefetch necessary states ReadableState outputTimestampFuture = watermarkHold.extractAndRelease(renamedContext, isFinished).readLater(); ReadableState paneFuture = - paneInfoTracker.getNextPaneInfo(directContext, isEndOfWindow, isFinished).readLater(); + paneInfoTracker.getNextPaneInfo(directContext, isFinished).readLater(); ReadableState isEmptyFuture = nonEmptyPanes.isEmpty(renamedContext.state()).readLater(); @@ -735,7 +728,7 @@ private void onTrigger( final Instant outputTimestamp = outputTimestampFuture.read(); // Only emit a pane if it has data or empty panes are observable. - if (needToEmit(isEmptyFuture.read(), isEndOfWindow, isFinished, pane.getTiming())) { + if (needToEmit(isEmptyFuture.read(), isFinished, pane.getTiming())) { // Run reduceFn.onTrigger method. final List windows = Collections.singletonList(directContext.window()); ReduceFn.OnTriggerContext renamedTriggerContext = diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index c85b1ca4a5..4fb3e37cb4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -479,19 +479,20 @@ public void testPaneInfoAllStates() throws Exception { when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); injectElement(tester, 3); assertThat(tester.extractOutput(), contains( - // This is late, because the trigger wasn't waiting for AfterWatermark - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.EARLY, 2, -1)))); + WindowMatchers.valueWithPaneInfo( + PaneInfo.createPane(false, false, Timing.ON_TIME, 2, 0)))); when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); injectElement(tester, 4); assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.EARLY, 3, -1)))); + WindowMatchers.valueWithPaneInfo( + PaneInfo.createPane(false, false, Timing.LATE, 3, 1)))); when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); triggerShouldFinish(mockTrigger); injectElement(tester, 5); assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.EARLY, 4, -1)))); + WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 4, 2)))); } @Test From 9144597d82b133dfadd606cbf74fc31aac4dc7c0 Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Wed, 2 Mar 2016 18:53:08 -0800 Subject: [PATCH 236/751] Fix up checkstyle --- .../dataflow/sdk/options/DataflowPipelineDebugOptions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index a14be44987..1da2b435fa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -172,7 +172,7 @@ public Dataflow create(PipelineOptions options) { /** * Whether to update the currently running pipeline with the same name as this one. - * + * * @deprecated This property is replaced by @{link DataflowPipelineOptions#getUpdate()} */ @Deprecated From 75ac950fb24d9a801df723ca3b6d9d1c4cea2558 Mon Sep 17 00:00:00 2001 From: Pei He Date: Wed, 2 Mar 2016 13:36:23 -0800 Subject: [PATCH 237/751] [BEAM-80] Swap the order of timers and elements sent to ReduceFnRunner --- .../dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java index f6246d1641..89a4fcb720 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java @@ -80,10 +80,10 @@ public void processElement(ProcessContext c) throws Exception { reduceFn, c.getPipelineOptions()); + reduceFnRunner.processElements(element.elementsIterable()); for (TimerData timer : element.timersIterable()) { reduceFnRunner.onTimer(timer); } - reduceFnRunner.processElements(element.elementsIterable()); reduceFnRunner.persist(); } From 47b28ea1d47336753f5e0a0c0209f0d7e1679bfb Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 2 Mar 2016 13:17:02 -0800 Subject: [PATCH 238/751] [BEAM-87] Support opt-in for heap dumps --- .../sdk/options/DataflowPipelineDebugOptions.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index a14be44987..76e20c434c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -211,6 +211,19 @@ public Dataflow create(PipelineOptions options) { int getNumberOfWorkerHarnessThreads(); void setNumberOfWorkerHarnessThreads(int value); + /** + * If {@literal true}, save a heap dump before killing a thread or process which is GC + * thrashing or out of memory. + * + *

    + * CAUTION: Heap dumps can of comparable size to the default boot disk. Consider increasing + * the boot disk size before setting this flag to true. + */ + @Description("If {@literal true}, save a heap dump before killing a thread or process " + + "which is GC thrashing or out of memory.") + boolean getDumpHeapOnOOM(); + void setDumpHeapOnOOM(boolean dumpHeapBeforeExit); + /** * Creates a {@link PathValidator} object using the class specified in * {@link #getPathValidatorClass()}. From c48467bbca18d83989b6b12e3c067054ea12f795 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Thu, 3 Mar 2016 10:53:25 -0800 Subject: [PATCH 239/751] Clarrify heap file path. --- .../dataflow/sdk/options/DataflowPipelineDebugOptions.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index 76e20c434c..f8b0f4cdca 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -213,7 +213,8 @@ public Dataflow create(PipelineOptions options) { /** * If {@literal true}, save a heap dump before killing a thread or process which is GC - * thrashing or out of memory. + * thrashing or out of memory. The location of the heap file will either be echoed back + * to the user, or the user will be given the oppourtunity to download the heap file. * *

    * CAUTION: Heap dumps can of comparable size to the default boot disk. Consider increasing From 3f5d5e0b6f6979b9a852dfd9ac842d5fb3f07696 Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Thu, 3 Mar 2016 14:19:51 -0800 Subject: [PATCH 240/751] Fix typo --- .../dataflow/sdk/options/DataflowPipelineDebugOptions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index f8b0f4cdca..f1d28edcd9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -214,7 +214,7 @@ public Dataflow create(PipelineOptions options) { /** * If {@literal true}, save a heap dump before killing a thread or process which is GC * thrashing or out of memory. The location of the heap file will either be echoed back - * to the user, or the user will be given the oppourtunity to download the heap file. + * to the user, or the user will be given the opportunity to download the heap file. * *

    * CAUTION: Heap dumps can of comparable size to the default boot disk. Consider increasing From df81ecd551ce5358b7f581155054935142812ce6 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 2 Mar 2016 20:49:53 -0800 Subject: [PATCH 241/751] [BEAM-90] TestCountingSource can throw on checkpointing --- .../runners/dataflow/TestCountingSource.java | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java index 181ddcae5b..d0863a46f5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java @@ -27,6 +27,8 @@ import com.google.cloud.dataflow.sdk.values.KV; import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; @@ -46,31 +48,47 @@ */ public class TestCountingSource extends UnboundedSource, TestCountingSource.CounterMark> { + private static final Logger LOG = LoggerFactory.getLogger(TestCountingSource.class); + private static List finalizeTracker; private final int numMessagesPerShard; private final int shardNumber; private final boolean dedup; + private final boolean throwOnFirstSnapshot; + + /** + * We only allow an exception to be thrown from getCheckpointMark + * at most once. This must be static since the entire TestCountingSource + * instance may re-serialized when the pipeline recovers and retries. + */ + private static boolean thrown = false; public static void setFinalizeTracker(List finalizeTracker) { TestCountingSource.finalizeTracker = finalizeTracker; } public TestCountingSource(int numMessagesPerShard) { - this(numMessagesPerShard, 0, false); + this(numMessagesPerShard, 0, false, false); } public TestCountingSource withDedup() { - return new TestCountingSource(numMessagesPerShard, shardNumber, true); + return new TestCountingSource(numMessagesPerShard, shardNumber, true, throwOnFirstSnapshot); } private TestCountingSource withShardNumber(int shardNumber) { - return new TestCountingSource(numMessagesPerShard, shardNumber, dedup); + return new TestCountingSource(numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot); } - private TestCountingSource(int numMessagesPerShard, int shardNumber, boolean dedup) { + public TestCountingSource withThrowOnFirstSnapshot(boolean throwOnFirstSnapshot) { + return new TestCountingSource(numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot); + } + + private TestCountingSource( + int numMessagesPerShard, int shardNumber, boolean dedup, boolean throwOnFirstSnapshot) { this.numMessagesPerShard = numMessagesPerShard; this.shardNumber = shardNumber; this.dedup = dedup; + this.throwOnFirstSnapshot = throwOnFirstSnapshot; } public int getShardNumber() { @@ -187,6 +205,11 @@ public Instant getWatermark() { @Override public CheckpointMark getCheckpointMark() { + if (throwOnFirstSnapshot && !thrown) { + thrown = true; + LOG.error("Throwing exception while checkpointing counter"); + throw new RuntimeException("failed during checkpoint"); + } return new CounterMark(current); } From 495c689d3da9f0c25b771084a719a9c153558508 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 3 Mar 2016 18:40:12 -0800 Subject: [PATCH 242/751] BigtableIO.Read: use PBegin, rather than PInput Sources should start from the beginning of a pipeline. --- .../google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index c3f233f249..562d253d77 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -41,9 +41,9 @@ import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.FutureCallback; @@ -176,7 +176,7 @@ public static Write write() { * @see BigtableIO */ @Experimental - public static class Read extends PTransform> { + public static class Read extends PTransform> { /** * Returns a new {@link BigtableIO.Read} that will read from the Cloud Bigtable cluster * indicated by the given options, and using any other specified customizations. @@ -241,14 +241,14 @@ public String getTableId() { } @Override - public PCollection apply(PInput input) { + public PCollection apply(PBegin input) { BigtableSource source = new BigtableSource(getBigtableService(), tableId, filter, ByteKeyRange.ALL_KEYS, null); return input.getPipeline().apply(com.google.cloud.dataflow.sdk.io.Read.from(source)); } @Override - public void validate(PInput input) { + public void validate(PBegin input) { checkArgument(options != null, "BigtableOptions not specified"); checkArgument(!tableId.isEmpty(), "Table ID not specified"); try { From 30ca892202fe6c0ecbeca2051b0a1ad8c79e353c Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Fri, 4 Mar 2016 09:45:59 -0800 Subject: [PATCH 243/751] Fix malformatted @links in javadoc comments --- .../dataflow/sdk/options/DataflowPipelineDebugOptions.java | 2 +- .../google/cloud/dataflow/sdk/transforms/DoFnWithContext.java | 2 +- .../java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java | 2 +- .../cloud/dataflow/sdk/transforms/DoFnWithContextTest.java | 2 +- .../google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java | 2 +- .../google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index 1da2b435fa..c96c5141bc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -173,7 +173,7 @@ public Dataflow create(PipelineOptions options) { /** * Whether to update the currently running pipeline with the same name as this one. * - * @deprecated This property is replaced by @{link DataflowPipelineOptions#getUpdate()} + * @deprecated This property is replaced by {@link DataflowPipelineOptions#getUpdate()} */ @Deprecated @Description("If set, replace the existing pipeline with the name specified by --jobName with " diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java index 10bf0eb16a..4f131adc91 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java @@ -407,7 +407,7 @@ public final Aggregator createAggregator( } /** - * Finalize the @{link DoFnWithContext} construction to prepare for processing. + * Finalize the {@link DoFnWithContext} construction to prepare for processing. * This method should be called by runners before any processing methods. */ void prepareForProcessing() { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java index f6df14a72b..a709a233ab 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java @@ -179,7 +179,7 @@ public void processElement(DoFn.ProcessContext c) throws Excepti } /** - * Initialize a test pipeline with the specified @{link DoFn}. + * Initialize a test pipeline with the specified {@link DoFn}. */ private TestPipeline createTestPipeline(DoFn fn) { TestPipeline pipeline = TestPipeline.create(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java index 228b961421..9f54a6e0ee 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java @@ -213,7 +213,7 @@ public void processElement(ProcessContext c) {} } /** - * Initialize a test pipeline with the specified @{link DoFn}. + * Initialize a test pipeline with the specified {@link DoFn}. */ private TestPipeline createTestPipeline(DoFnWithContext fn) { TestPipeline pipeline = TestPipeline.create(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java index 4af60dbe91..e75a3e8cb4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java @@ -33,7 +33,7 @@ import java.util.List; /** - * Tests for base @{link DoFnRunnerBase} functionality. + * Tests for base {@link DoFnRunnerBase} functionality. */ @RunWith(JUnit4.class) public class SimpleDoFnRunnerTest { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java index 5cf385cf31..7982a99efe 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java @@ -37,7 +37,7 @@ import java.io.IOException; /** - * Tests for @{link UserCodeException} functionality. + * Tests for {@link UserCodeException} functionality. */ @RunWith(JUnit4.class) public class UserCodeExceptionTest { From 6346595eec1e4af40ddb63fd5c5b2c8708dd7e01 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Wed, 2 Mar 2016 14:03:28 -0800 Subject: [PATCH 244/751] Add CountingInput as a PTransform This transform produces an unbounded PCollection containing longs based on a CountingSource. Deprecate methods producing a Source in CountingSource. --- .../cloud/dataflow/sdk/io/CountingInput.java | 191 ++++++++++++++++++ .../cloud/dataflow/sdk/io/CountingSource.java | 31 ++- .../dataflow/sdk/io/CountingInputTest.java | 122 +++++++++++ 3 files changed, 334 insertions(+), 10 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java new file mode 100644 index 0000000000..07609ba716 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.cloud.dataflow.sdk.io.CountingSource.NowTimestampFn; +import com.google.cloud.dataflow.sdk.io.Read.Unbounded; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.values.PBegin; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; +import com.google.common.base.Optional; + +import org.joda.time.Duration; +import org.joda.time.Instant; + +/** + * A {@link PTransform} that produces longs. When used to produce a + * {@link IsBounded#BOUNDED bounded} {@link PCollection}, {@link CountingInput} starts at {@code 0} + * and counts up to a specified maximum. When used to produce an + * {@link IsBounded#UNBOUNDED unbounded} {@link PCollection}, it counts up to {@link Long#MAX_VALUE} + * and then never produces more output. (In practice, this limit should never be reached.) + * + *

    The bounded {@link CountingInput} is implemented based on {@link OffsetBasedSource} and + * {@link OffsetBasedSource.OffsetBasedReader}, so it performs efficient initial splitting and it + * supports dynamic work rebalancing. + * + *

    To produce a bounded {@code PCollection}, use {@link CountingInput#upTo(long)}: + * + *

    {@code
    + * Pipeline p = ...
    + * PTransform> producer = CountingInput.upTo(1000);
    + * PCollection bounded = p.apply(producer);
    + * }
    + * + *

    To produce an unbounded {@code PCollection}, use {@link CountingInput#unbounded()}, + * calling {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to provide values + * with timestamps other than {@link Instant#now}. + * + *

    {@code
    + * Pipeline p = ...
    + *
    + * // To create an unbounded producer that uses processing time as the element timestamp.
    + * PCollection unbounded = p.apply(CountingInput.unbounded());
    + * // Or, to create an unbounded source that uses a provided function to set the element timestamp.
    + * PCollection unboundedWithTimestamps =
    + *     p.apply(CountingInput.unbounded().withTimestampFn(someFn));
    + * }
    + */ +public class CountingInput { + /** + * Creates a {@link BoundedCountingInput} that will produce the specified number of elements, + * from {@code 0} to {@code numElements - 1}. + */ + public static BoundedCountingInput upTo(long numElements) { + checkArgument(numElements > 0, "numElements (%s) must be greater than 0", numElements); + return new BoundedCountingInput(numElements); + } + + /** + * Creates an {@link UnboundedCountingInput} that will produce numbers starting from {@code 0} up + * to {@link Long#MAX_VALUE}. + * + *

    After {@link Long#MAX_VALUE}, the transform never produces more output. (In practice, this + * limit should never be reached.) + * + *

    Elements in the resulting {@link PCollection PCollection<Long>} will by default have + * timestamps corresponding to processing time at element generation, provided by + * {@link Instant#now}. Use the transform returned by + * {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to control the output + * timestamps. + */ + public static UnboundedCountingInput unbounded() { + return new UnboundedCountingInput( + new NowTimestampFn(), Optional.absent(), Optional.absent()); + } + + /** + * A {@link PTransform} that will produce a specified number of {@link Long Longs} starting from + * 0. + */ + public static class BoundedCountingInput extends PTransform> { + private final long numElements; + + private BoundedCountingInput(long numElements) { + this.numElements = numElements; + } + + @SuppressWarnings("deprecation") + @Override + public PCollection apply(PBegin begin) { + return begin.apply(Read.from(CountingSource.upTo(numElements))); + } + } + + /** + * A {@link PTransform} that will produce numbers starting from {@code 0} up to + * {@link Long#MAX_VALUE}. + * + *

    After {@link Long#MAX_VALUE}, the transform never produces more output. (In practice, this + * limit should never be reached.) + * + *

    Elements in the resulting {@link PCollection PCollection<Long>} will by default have + * timestamps corresponding to processing time at element generation, provided by + * {@link Instant#now}. Use the transform returned by + * {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to control the output + * timestamps. + */ + public static class UnboundedCountingInput extends PTransform> { + private final SerializableFunction timestampFn; + private final Optional maxNumRecords; + private final Optional maxReadTime; + + private UnboundedCountingInput( + SerializableFunction timestampFn, + Optional maxNumRecords, + Optional maxReadTime) { + this.timestampFn = timestampFn; + this.maxNumRecords = maxNumRecords; + this.maxReadTime = maxReadTime; + } + + /** + * Returns an {@link UnboundedCountingInput} like this one, but where output elements have the + * timestamp specified by the timestampFn. + * + *

    Note that the timestamps produced by {@code timestampFn} may not decrease. + */ + public UnboundedCountingInput withTimestampFn(SerializableFunction timestampFn) { + return new UnboundedCountingInput(timestampFn, maxNumRecords, maxReadTime); + } + + /** + * Returns an {@link UnboundedCountingInput} like this one, but that will read at most the + * specified number of elements. + * + *

    A bounded amount of elements will be produced by the result transform, and the result + * {@link PCollection} will be {@link IsBounded#BOUNDED bounded}. + */ + public UnboundedCountingInput withMaxNumRecords(long maxRecords) { + checkArgument( + maxRecords > 0, "MaxRecords must be a positive (nonzero) value. Got %s", maxRecords); + return new UnboundedCountingInput(timestampFn, Optional.of(maxRecords), maxReadTime); + } + + /** + * Returns an {@link UnboundedCountingInput} like this one, but that will read for at most the + * specified amount of time. + * + *

    A bounded amount of elements will be produced by the result transform, and the result + * {@link PCollection} will be {@link IsBounded#BOUNDED bounded}. + */ + public UnboundedCountingInput withMaxReadTime(Duration readTime) { + checkNotNull(readTime, "ReadTime cannot be null"); + return new UnboundedCountingInput(timestampFn, maxNumRecords, Optional.of(readTime)); + } + + @SuppressWarnings("deprecation") + @Override + public PCollection apply(PBegin begin) { + Unbounded read = Read.from(CountingSource.unboundedWithTimestampFn(timestampFn)); + if (!maxNumRecords.isPresent() && !maxReadTime.isPresent()) { + return begin.apply(read); + } else if (maxNumRecords.isPresent() && !maxReadTime.isPresent()) { + return begin.apply(read.withMaxNumRecords(maxNumRecords.get())); + } else if (!maxNumRecords.isPresent() && maxReadTime.isPresent()) { + return begin.apply(read.withMaxReadTime(maxReadTime.get())); + } else { + return begin.apply( + read.withMaxReadTime(maxReadTime.get()).withMaxNumRecords(maxNumRecords.get())); + } + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java index 2938534168..412f3a7ec9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.DefaultCoder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.io.CountingInput.UnboundedCountingInput; import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; @@ -48,29 +49,33 @@ * *

    {@code
      * Pipeline p = ...
    - * BoundedSource source = CountingSource.upTo(1000);
    - * PCollection bounded = p.apply(Read.from(source));
    + * PTransform> producer = CountingInput.upTo(1000);
    + * PCollection bounded = p.apply(producer);
      * }
    * - *

    To produce an unbounded {@code PCollection}, use {@link CountingSource#unbounded} or - * {@link CountingSource#unboundedWithTimestampFn}: + *

    To produce an unbounded {@code PCollection}, use {@link CountingInput#unbounded()}, + * calling {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to provide values + * with timestamps other than {@link Instant#now}. * *

    {@code
      * Pipeline p = ...
      *
    - * // To create an unbounded source that uses processing time as the element timestamp.
    - * UnboundedSource source = CountingSource.unbounded();
    + * // To create an unbounded PCollection that uses processing time as the element timestamp.
    + * PCollection unbounded = p.apply(CountingInput.unbounded());
      * // Or, to create an unbounded source that uses a provided function to set the element timestamp.
    - * UnboundedSource source = CountingSource.unboundedWithTimestampFn(someFn);
    + * PCollection unboundedWithTimestamps =
    + *     p.apply(CountingInput.unbounded().withTimestampFn(someFn));
      *
    - * PCollection unbounded = p.apply(Read.from(source));
      * }
    */ public class CountingSource { /** * Creates a {@link BoundedSource} that will produce the specified number of elements, * from {@code 0} to {@code numElements - 1}. + * + * @deprecated use {@link CountingInput#upTo(long)} instead */ + @Deprecated public static BoundedSource upTo(long numElements) { checkArgument(numElements > 0, "numElements (%s) must be greater than 0", numElements); return new BoundedCountingSource(0, numElements); @@ -85,7 +90,10 @@ public static BoundedSource upTo(long numElements) { * *

    Elements in the resulting {@link PCollection PCollection<Long>} will have timestamps * corresponding to processing time at element generation, provided by {@link Instant#now}. + * + * @deprecated use {@link CountingInput#unbounded()} instead */ + @Deprecated public static UnboundedSource unbounded() { return unboundedWithTimestampFn(new NowTimestampFn()); } @@ -98,7 +106,11 @@ public static UnboundedSource unbounded() { * limit should never be reached.) * *

    Note that the timestamps produced by {@code timestampFn} may not decrease. + * + * @deprecated use {@link CountingInput#unbounded()} and call + * {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} instead */ + @Deprecated public static UnboundedSource unboundedWithTimestampFn( SerializableFunction timestampFn) { return new UnboundedCountingSource(0, 1, timestampFn); @@ -109,11 +121,10 @@ public static UnboundedSource unboundedWithTimestampFn( /** Prevent instantiation. */ private CountingSource() {} - /** * A function that returns {@link Instant#now} as the timestamp for each generated element. */ - private static class NowTimestampFn implements SerializableFunction { + static class NowTimestampFn implements SerializableFunction { @Override public Instant apply(Long input) { return Instant.now(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java new file mode 100644 index 0000000000..948a892b58 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.io.CountingInput.UnboundedCountingInput; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.RunnableOnService; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Max; +import com.google.cloud.dataflow.sdk.transforms.Min; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +/** + * Tests for {@link CountingInput}. + */ +public class CountingInputTest { + public static void addCountingAsserts(PCollection input, long numElements) { + // Count == numElements + DataflowAssert.thatSingleton(input.apply("Count", Count.globally())) + .isEqualTo(numElements); + // Unique count == numElements + DataflowAssert.thatSingleton( + input + .apply(RemoveDuplicates.create()) + .apply("UniqueCount", Count.globally())) + .isEqualTo(numElements); + // Min == 0 + DataflowAssert.thatSingleton(input.apply("Min", Min.globally())).isEqualTo(0L); + // Max == numElements-1 + DataflowAssert.thatSingleton(input.apply("Max", Max.globally())) + .isEqualTo(numElements - 1); + } + + @Test + @Category(RunnableOnService.class) + public void testBoundedInput() { + Pipeline p = TestPipeline.create(); + long numElements = 1000; + PCollection input = p.apply(CountingInput.upTo(numElements)); + + addCountingAsserts(input, numElements); + p.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testUnboundedInput() { + Pipeline p = TestPipeline.create(); + long numElements = 1000; + + PCollection input = p.apply(CountingInput.unbounded().withMaxNumRecords(numElements)); + + addCountingAsserts(input, numElements); + p.run(); + } + + private static class ElementValueDiff extends DoFn { + @Override + public void processElement(ProcessContext c) throws Exception { + c.output(c.element() - c.timestamp().getMillis()); + } + } + + @Test + @Category(RunnableOnService.class) + public void testUnboundedInputTimestamps() { + Pipeline p = TestPipeline.create(); + long numElements = 1000; + + PCollection input = + p.apply( + CountingInput.unbounded() + .withTimestampFn(new ValueAsTimestampFn()) + .withMaxNumRecords(numElements)); + addCountingAsserts(input, numElements); + + PCollection diffs = + input + .apply("TimestampDiff", ParDo.of(new ElementValueDiff())) + .apply("RemoveDuplicateTimestamps", RemoveDuplicates.create()); + // This assert also confirms that diffs only has one unique value. + DataflowAssert.thatSingleton(diffs).isEqualTo(0L); + + p.run(); + } + + /** + * A timestamp function that uses the given value as the timestamp. Because the input values will + * not wrap, this function is non-decreasing and meets the timestamp function criteria laid out + * in {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)}. + */ + private static class ValueAsTimestampFn implements SerializableFunction { + @Override + public Instant apply(Long input) { + return new Instant(input); + } + } +} From 0bc381b5c47170268f615fb9435e2d0d1c1d30f9 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Fri, 4 Mar 2016 15:07:15 -0800 Subject: [PATCH 245/751] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 52e1d3a5cb..973618b106 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,5 +31,5 @@ install: script: - travis_retry mvn versions:set -DnewVersion=manual_build - - travis_retry mvn $MAVEN_OVERRIDE install -U + - travis_retry mvn $MAVEN_OVERRIDE verify -U - travis_retry travis/test_wordcount.sh From 000048103dd0f059ee3f24cdbfd5bf2588788f7f Mon Sep 17 00:00:00 2001 From: Pei He Date: Thu, 3 Mar 2016 19:33:34 -0800 Subject: [PATCH 246/751] Upgrade mockito to 1.10.19 --- examples/pom.xml | 2 +- sdk/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index d7834cb3ef..22183670c2 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -514,7 +514,7 @@ org.mockito mockito-all - 1.9.5 + 1.10.19 test diff --git a/sdk/pom.xml b/sdk/pom.xml index c49c175709..da41c1c752 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -806,7 +806,7 @@ org.mockito mockito-all - 1.9.5 + 1.10.19 test From a3b05ffd3df71dd1c58d71e8db5e992e4ed11d0b Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Fri, 4 Mar 2016 17:16:36 -0800 Subject: [PATCH 247/751] Update .travis.yml Revert "mvn verify" back to "mvn install" since it breaks the following script. When we are at it, update the script to be less sensitive whether artifacts are installed. This doesn't fully fix the Travis coverage, since there's still too much logging generated in the 'verify' phase. --- .travis.yml | 3 +-- travis/test_wordcount.sh | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 973618b106..95baf695f8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,6 +30,5 @@ install: - travis_retry mvn install clean -U -DskipTests=true script: - - travis_retry mvn versions:set -DnewVersion=manual_build - - travis_retry mvn $MAVEN_OVERRIDE verify -U + - travis_retry mvn $MAVEN_OVERRIDE install -U - travis_retry travis/test_wordcount.sh diff --git a/travis/test_wordcount.sh b/travis/test_wordcount.sh index 2e8a58b8cb..fdb9d10a85 100755 --- a/travis/test_wordcount.sh +++ b/travis/test_wordcount.sh @@ -18,7 +18,8 @@ set -e set -o pipefail PASS=1 -JAR_FILE=examples/target/google-cloud-dataflow-java-examples-all-bundled-manual_build.jar +VERSION=$(mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep -v '\[') +JAR_FILE=examples/target/google-cloud-dataflow-java-examples-all-bundled-${VERSION}.jar function check_result_hash { local name=$1 From 37dec8f1a0f1975f49bb736357440f11e395c5d0 Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Fri, 4 Mar 2016 10:13:15 -0800 Subject: [PATCH 248/751] [BEAM-95] Use snappy compression on objects serialized via SerializableUtils --- .../google/cloud/dataflow/sdk/util/SerializableUtils.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java index cacba0ea17..501b4307fc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java @@ -23,6 +23,9 @@ import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.common.base.Preconditions; +import org.xerial.snappy.SnappyInputStream; +import org.xerial.snappy.SnappyOutputStream; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -43,7 +46,7 @@ public class SerializableUtils { public static byte[] serializeToByteArray(Serializable value) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - try (ObjectOutputStream oos = new ObjectOutputStream(buffer)) { + try (ObjectOutputStream oos = new ObjectOutputStream(new SnappyOutputStream(buffer))) { oos.writeObject(value); } return buffer.toByteArray(); @@ -66,7 +69,7 @@ public static Object deserializeFromByteArray(byte[] encodedValue, String description) { try { try (ObjectInputStream ois = new ObjectInputStream( - new ByteArrayInputStream(encodedValue))) { + new SnappyInputStream(new ByteArrayInputStream(encodedValue)))) { return ois.readObject(); } } catch (IOException | ClassNotFoundException exn) { From 2fe4337a35af148edcd0867416dbbd1b7c11fe47 Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Fri, 4 Mar 2016 10:15:59 -0800 Subject: [PATCH 249/751] [BEAM-95] Add dependency explicitly to SDK pom --- sdk/pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sdk/pom.xml b/sdk/pom.xml index c49c175709..5c6553b749 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -719,6 +719,12 @@ ${avro.version} + + org.xerial.snappy + snappy-java + 1.1.2.1 + + org.apache.commons commons-compress From 8a6536a4ab419e8fc121ef61d667fb775ab6958d Mon Sep 17 00:00:00 2001 From: sammcveety Date: Wed, 2 Mar 2016 21:27:08 -0800 Subject: [PATCH 250/751] [BEAM-93] Add subnetwork support and increment Dataflow API dependency --- pom.xml | 2 +- .../DataflowPipelineWorkerPoolOptions.java | 12 +++++++ .../runners/DataflowPipelineTranslator.java | 3 ++ .../DataflowPipelineTranslatorTest.java | 34 +++++++++++++++++++ 4 files changed, 50 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ba130d25a3..51741cf719 100644 --- a/pom.xml +++ b/pom.xml @@ -70,7 +70,7 @@ 1.7.7 v2-rev248-1.21.0 0.2.3 - v1b3-rev19-1.21.0 + v1b3-rev22-1.21.0 0.5.160222 v1beta2-rev1-4.0.0 1.21.0 diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java index 25d15890c7..be5cfdc2a7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java @@ -144,6 +144,18 @@ public String create(PipelineOptions options) { String getNetwork(); void setNetwork(String value); + /** + * GCE subnetwork for launching + * workers. + * + *

    Default is up to the Dataflow service. Expected format is zones/ZONE/subnetworks/SUBNETWORK. + */ + @Description("GCE subnetwork for launching workers. For more information, see the reference " + + "documentation https://cloud.google.com/compute/docs/networking. " + + "Default is up to the Dataflow service.") + String getSubnetwork(); + void setSubnetwork(String value); + /** * GCE availability zone for launching workers. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index ae3a403103..d0cc4e53d5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -442,6 +442,9 @@ public Job translate(List packages) { if (!Strings.isNullOrEmpty(options.getNetwork())) { workerPool.setNetwork(options.getNetwork()); } + if (!Strings.isNullOrEmpty(options.getSubnetwork())) { + workerPool.setSubnetwork(options.getSubnetwork()); + } if (options.getDiskSizeGb() > 0) { workerPool.setDiskSizeGb(options.getDiskSizeGb()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 72090a0866..497552f901 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -230,6 +230,40 @@ public void testNetworkConfigMissing() throws IOException { assertNull(job.getEnvironment().getWorkerPools().get(0).getNetwork()); } + @Test + public void testSubnetworkConfig() throws IOException { + final String testSubnetwork = "zones/ZONE/subnetworks/SUBNETWORK"; + + DataflowPipelineOptions options = buildPipelineOptions(); + options.setSubnetwork(testSubnetwork); + + DataflowPipeline p = buildPipeline(options); + p.traverseTopologically(new RecordingPipelineVisitor()); + Job job = + DataflowPipelineTranslator.fromOptions(options) + .translate(p, p.getRunner(), Collections.emptyList()) + .getJob(); + + assertEquals(1, job.getEnvironment().getWorkerPools().size()); + assertEquals(testSubnetwork, + job.getEnvironment().getWorkerPools().get(0).getSubnetwork()); + } + + @Test + public void testSubnetworkConfigMissing() throws IOException { + DataflowPipelineOptions options = buildPipelineOptions(); + + DataflowPipeline p = buildPipeline(options); + p.traverseTopologically(new RecordingPipelineVisitor()); + Job job = + DataflowPipelineTranslator.fromOptions(options) + .translate(p, p.getRunner(), Collections.emptyList()) + .getJob(); + + assertEquals(1, job.getEnvironment().getWorkerPools().size()); + assertNull(job.getEnvironment().getWorkerPools().get(0).getSubnetwork()); + } + @Test public void testScalingAlgorithmMissing() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); From 135f0a097801b432dd0af70e0af59d77628e7fa7 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Mon, 7 Mar 2016 18:22:01 -0800 Subject: [PATCH 251/751] Fix up --- .../dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java index be5cfdc2a7..dd3d83a077 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java @@ -148,7 +148,7 @@ public String create(PipelineOptions options) { * GCE subnetwork for launching * workers. * - *

    Default is up to the Dataflow service. Expected format is zones/ZONE/subnetworks/SUBNETWORK. + *

    Default is up to the Dataflow service. Expected format is zones/ZONE/subnetworks/SUBNETWORK. */ @Description("GCE subnetwork for launching workers. For more information, see the reference " + "documentation https://cloud.google.com/compute/docs/networking. " From 2997027fde162344f4043e1bdc391bf90efa3122 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Fri, 4 Mar 2016 17:32:04 -0800 Subject: [PATCH 252/751] Fixup CountingInputTest.java by adding JUnit version number --- .../com/google/cloud/dataflow/sdk/io/CountingInputTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java index 948a892b58..1daadc7e2b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java @@ -33,10 +33,13 @@ import org.joda.time.Instant; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests for {@link CountingInput}. */ +@RunWith(JUnit4.class) public class CountingInputTest { public static void addCountingAsserts(PCollection input, long numElements) { // Count == numElements From 683cbb8a00988166f94446e7abb505a4cca7b6ca Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Thu, 3 Mar 2016 19:17:07 -0800 Subject: [PATCH 253/751] Send travis-ci emails to their default recipients --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 95baf695f8..096e5ad42a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,10 @@ sudo: false notifications: email: - recipients: - - dataflow-sdk-build-notifications+travis@google.com + # Group email notifications are disabled for now, since we cannot do it on a per-branch basis. + # Right now, it would trigger a notification for each fork, which generates a lot of spam. + # recipients: + # - dataflow-sdk-build-notifications+travis@google.com on_success: change on_failure: always From c6794689d286a42a6b71fbb86d4f094eea8ca97f Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Thu, 3 Mar 2016 20:21:57 -0800 Subject: [PATCH 254/751] Remove hardcoded package name in CoderUtils --- .../java/com/google/cloud/dataflow/sdk/util/CoderUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java index 771bf09eb3..ddab933f54 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java @@ -286,7 +286,7 @@ private Class getClassForId(String id) { // com.google.cloud.dataflow.sdk.coders. We do this via creating // the class object so that class loaders have a chance to get // involved -- and since we need the class object anyway. - return Class.forName("com.google.cloud.dataflow.sdk.coders." + id); + return Class.forName(Coder.class.getPackage().getName() + "." + id); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to convert coder ID " + id + " to class", e); } From e37ddc65208699231e38951c2398b5e43dc92be5 Mon Sep 17 00:00:00 2001 From: Daniel Mills Date: Fri, 4 Mar 2016 15:39:45 -0800 Subject: [PATCH 255/751] Update sdk pregenerated protos to 0.5.160304 Make pre-generated proto libraries a test-only dep --- sdk/pom.xml | 13 +++++++------ .../dataflow/sdk/coders/protobuf/ProtoCoder.java | 7 +------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index c1587965f1..8e7b4634b4 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -452,12 +452,6 @@ - - com.google.cloud.dataflow - google-cloud-dataflow-java-proto-library-all - 0.5.160222 - - io.grpc grpc-all @@ -815,5 +809,12 @@ 1.10.19 test + + + com.google.cloud.dataflow + google-cloud-dataflow-java-proto-library-all + 0.5.160304 + test + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java index d8c8e9e243..9e4bb502c7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java @@ -25,8 +25,6 @@ import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.CoderProvider; import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; import com.google.cloud.dataflow.sdk.util.CloudObject; import com.google.cloud.dataflow.sdk.util.Structs; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -147,10 +145,7 @@ public static ProtoCoder of(TypeDescriptor protoMessag * registered. * *

    Each of the extension host classes must be an class automatically generated by the - * Protocol Buffers compiler, {@code protoc}, that contains messages. For example, the class - * {@link Proto2CoderTestMessages} is the extension host for the {@link Message} classes - * {@link MessageA Proto2CoderTestMessages.MessageA} and the class {@link DatastoreV1} is the - * extension host for the Google Cloud Datastore {@link Entity} entity type. + * Protocol Buffers compiler, {@code protoc}, that contains messages. * *

    Does not modify this object. */ From 4c983ab347b0dde620b73b908254dfa38b72866f Mon Sep 17 00:00:00 2001 From: bchambers Date: Wed, 2 Mar 2016 17:38:49 -0800 Subject: [PATCH 256/751] Register debuggee with Cloud Debugger prior to job submission to Cloud Dataflow --- pom.xml | 1 + sdk/pom.xml | 14 +++++ .../sdk/options/CloudDebuggerOptions.java | 9 ++- .../sdk/runners/DataflowPipelineRunner.java | 57 +++++++++++++++++-- .../cloud/dataflow/sdk/util/Transport.java | 9 +++ 5 files changed, 85 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 51741cf719..a36b35c920 100644 --- a/pom.xml +++ b/pom.xml @@ -71,6 +71,7 @@ v2-rev248-1.21.0 0.2.3 v1b3-rev22-1.21.0 + v2-rev6-1.21.0 0.5.160222 v1beta2-rev1-4.0.0 1.21.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index 8e7b4634b4..f782b78532 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -496,6 +496,20 @@ + + com.google.apis + google-api-services-clouddebugger + ${clouddebugger.version} + + + + com.google.guava + guava-jdk5 + + + + com.google.apis google-api-services-pubsub diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java index 62be4c9ec2..2e1ad9451f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.options; +import com.google.api.services.clouddebugger.v2.model.Debuggee; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import javax.annotation.Nullable; + /** * Options for controlling Cloud Debugger. */ @@ -32,5 +35,9 @@ public interface CloudDebuggerOptions { @Description("Whether to enable the Cloud Debugger snapshot agent for the current job.") boolean getEnableCloudDebugger(); void setEnableCloudDebugger(boolean enabled); -} + @Description("The Cloud Debugger debugee to associate with. This should not be set directly.") + @Hidden + @Nullable Debuggee getDebuggee(); + void setDebuggee(Debuggee debuggee); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 6eb6c2f7ad..0612cca4d0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -23,6 +23,10 @@ import static com.google.common.base.Preconditions.checkState; import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.services.clouddebugger.v2.Clouddebugger; +import com.google.api.services.clouddebugger.v2.model.Debuggee; +import com.google.api.services.clouddebugger.v2.model.RegisterDebuggeeRequest; +import com.google.api.services.clouddebugger.v2.model.RegisterDebuggeeResponse; import com.google.api.services.dataflow.Dataflow; import com.google.api.services.dataflow.model.DataflowPackage; import com.google.api.services.dataflow.model.Job; @@ -168,6 +172,8 @@ import java.util.SortedSet; import java.util.TreeSet; +import javax.annotation.Nullable; + /** * A {@link PipelineRunner} that executes the operations in the * pipeline by first translating them to the Dataflow representation @@ -420,6 +426,43 @@ private PCollection applyWindow( return super.apply(new AssignWindows<>(transform), input); } + private void maybeRegisterDebuggee(DataflowPipelineOptions options, String uniquifier) { + if (!options.getEnableCloudDebugger()) { + return; + } + + if (options.getDebuggee() != null) { + throw new RuntimeException("Should not specify the debuggee"); + } + + Clouddebugger debuggerClient = Transport.newClouddebuggerClient(options).build(); + Debuggee debuggee = registerDebuggee(debuggerClient, uniquifier); + options.setDebuggee(debuggee); + } + + private Debuggee registerDebuggee(Clouddebugger debuggerClient, String uniquifier) { + RegisterDebuggeeRequest registerReq = new RegisterDebuggeeRequest(); + registerReq.setDebuggee(new Debuggee() + .setProject(options.getProject()) + .setUniquifier(uniquifier) + .setDescription(uniquifier) + .setAgentVersion("google.com/cloud-dataflow-java/v1")); + + try { + RegisterDebuggeeResponse registerResponse = + debuggerClient.controller().debuggees().register(registerReq).execute(); + Debuggee debuggee = registerResponse.getDebuggee(); + if (debuggee.getStatus() != null && debuggee.getStatus().getIsError()) { + throw new RuntimeException("Unable to register with the debugger: " + + debuggee.getStatus().getDescription().getFormat()); + } + + return debuggee; + } catch (IOException e) { + throw new RuntimeException("Unable to register with the debugger: ", e); + } + } + @Override public DataflowPipelineJob run(Pipeline pipeline) { logWarningIfPCollectionViewHasNonDeterministicKeyCoder(pipeline); @@ -428,9 +471,7 @@ public DataflowPipelineJob run(Pipeline pipeline) { + "related to Google Compute Engine usage and other Google Cloud Services."); List packages = options.getStager().stageFiles(); - JobSpecification jobSpecification = - translator.translate(pipeline, this, packages); - Job newJob = jobSpecification.getJob(); + // Set a unique client_request_id in the CreateJob request. // This is used to ensure idempotence of job creation across retried @@ -442,6 +483,15 @@ public DataflowPipelineJob run(Pipeline pipeline) { int randomNum = new Random().nextInt(9000) + 1000; String requestId = DateTimeFormat.forPattern("YYYYMMddHHmmssmmm").withZone(DateTimeZone.UTC) .print(DateTimeUtils.currentTimeMillis()) + "_" + randomNum; + + // Try to create a debuggee ID. This must happen before the job is translated since it may + // update the options. + DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); + maybeRegisterDebuggee(dataflowOptions, requestId); + + JobSpecification jobSpecification = + translator.translate(pipeline, this, packages); + Job newJob = jobSpecification.getJob(); newJob.setClientRequestId(requestId); String version = DataflowReleaseInfo.getReleaseInfo().getVersion(); @@ -450,7 +500,6 @@ public DataflowPipelineJob run(Pipeline pipeline) { newJob.getEnvironment().setUserAgent(DataflowReleaseInfo.getReleaseInfo()); // The Dataflow Service may write to the temporary directory directly, so // must be verified. - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); if (!Strings.isNullOrEmpty(options.getTempLocation())) { newJob.getEnvironment().setTempStoragePrefix( dataflowOptions.getPathValidator().verifyPath(options.getTempLocation())); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java index 7735a9e01f..15fe286339 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java @@ -23,6 +23,7 @@ import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.clouddebugger.v2.Clouddebugger; import com.google.api.services.dataflow.Dataflow; import com.google.api.services.pubsub.Pubsub; import com.google.api.services.storage.Storage; @@ -148,6 +149,14 @@ public static Dataflow.Builder newDataflowClient(DataflowPipelineOptions options .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); } + public static Clouddebugger.Builder newClouddebuggerClient(DataflowPipelineOptions options) { + return new Clouddebugger.Builder(getTransport(), + getJsonFactory(), + chainHttpRequestInitializer(options.getGcpCredential(), new RetryHttpRequestInitializer())) + .setApplicationName(options.getAppName()) + .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); + } + /** * Returns a Dataflow client that does not automatically retry failed * requests. From b1fbbf101b7464de384c79e5f1bf4052a097f573 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Mon, 7 Mar 2016 18:03:09 -0800 Subject: [PATCH 257/751] Fixup CL --- pom.xml | 2 +- .../google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java | 2 -- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 +--- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index a36b35c920..d3e6e070f3 100644 --- a/pom.xml +++ b/pom.xml @@ -70,8 +70,8 @@ 1.7.7 v2-rev248-1.21.0 0.2.3 - v1b3-rev22-1.21.0 v2-rev6-1.21.0 + v1b3-rev22-1.21.0 0.5.160222 v1beta2-rev1-4.0.0 1.21.0 diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java index 9e4bb502c7..111c24dc19 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java @@ -17,8 +17,6 @@ import static com.google.common.base.Preconditions.checkArgument; -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.Entity; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 0612cca4d0..c90b904235 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -172,8 +172,6 @@ import java.util.SortedSet; import java.util.TreeSet; -import javax.annotation.Nullable; - /** * A {@link PipelineRunner} that executes the operations in the * pipeline by first translating them to the Dataflow representation @@ -430,7 +428,7 @@ private void maybeRegisterDebuggee(DataflowPipelineOptions options, String uniqu if (!options.getEnableCloudDebugger()) { return; } - + if (options.getDebuggee() != null) { throw new RuntimeException("Should not specify the debuggee"); } From 69593dff32265eb335a89399a16035a7f0670634 Mon Sep 17 00:00:00 2001 From: davor Date: Wed, 9 Mar 2016 13:47:10 -0800 Subject: [PATCH 258/751] Select worker harness container image for release 1.5.0 ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=116798931 --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index c90b904235..29f9b85cc5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -211,9 +211,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:github-20160225-00"; + = "dataflow.gcr.io/v1beta3/java-batch:1.5.0"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:github-20160225-00"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.5.0"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 122f8851c2c41b72a1db126cd88455206c801e3d Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 9 Mar 2016 14:02:35 -0800 Subject: [PATCH 259/751] Only remove window from active window set if it is still active --- .../dataflow/sdk/util/MergingActiveWindowSet.java | 13 +++++-------- .../cloud/dataflow/sdk/util/ReduceFnRunner.java | 9 ++++++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index 95e378d9f4..5af4ea5676 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -72,9 +72,7 @@ */ public class MergingActiveWindowSet implements ActiveWindowSet { private final WindowFn windowFn; - - @Nullable - private Map> activeWindowToStateAddressWindows; + private final Map> activeWindowToStateAddressWindows; /** * As above, but only for EPHEMERAL windows. Does not need to be persisted. @@ -94,16 +92,14 @@ public class MergingActiveWindowSet implements ActiveWi * MERGED. Otherwise W1 is EPHEMERAL. * */ - @Nullable - private Map windowToActiveWindow; + private final Map windowToActiveWindow; /** * Deep clone of {@link #activeWindowToStateAddressWindows} as of last commit. * *

    Used to avoid writing to state if no changes have been made during the work unit. */ - @Nullable - private Map> originalActiveWindowToStateAddressWindows; + private final Map> originalActiveWindowToStateAddressWindows; /** * Handle representing our state in the backend. @@ -195,6 +191,7 @@ public void addActive(W window) { @Override public void remove(W window) { + Preconditions.checkState(isActive(window), "Window %s is not active", window); for (W stateAddressWindow : activeWindowToStateAddressWindows.get(window)) { windowToActiveWindow.remove(stateAddressWindow); } @@ -522,7 +519,7 @@ private static Map> emptyIfNull(@Nullable Map> multimap) private static Map> deepCopy(Map> multimap) { Map> newMultimap = new HashMap<>(); for (Map.Entry> entry : multimap.entrySet()) { - newMultimap.put(entry.getKey(), new LinkedHashSet(entry.getValue())); + newMultimap.put(entry.getKey(), new LinkedHashSet<>(entry.getValue())); } return newMultimap; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 1a009bb051..2b6e0d43db 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -523,7 +523,7 @@ public void onTimer(TimerData timer) throws Exception { // - The trigger may implement isClosed as constant false. // - If the window function does not support windowing then all windows will be considered // active. - // So we must combine the above. + // So we must take conjunction of activeWindows and triggerRunner state. boolean windowIsActive = activeWindows.isActive(window) && !triggerRunner.isClosed(directContext.state()); @@ -602,7 +602,7 @@ private void clearAllState( boolean windowIsActive) throws Exception { if (windowIsActive) { - // Since window is still active the trigger has not closed. + // Since window was still active the trigger may not have closed. reduceFn.clearState(renamedContext); watermarkHold.clearHolds(renamedContext); nonEmptyPanes.clearPane(renamedContext.state()); @@ -622,7 +622,10 @@ private void clearAllState( } } paneInfoTracker.clear(directContext.state()); - activeWindows.remove(directContext.window()); + if (activeWindows.isActive(directContext.window())) { + // Don't need to track address state windows anymore + activeWindows.remove(directContext.window()); + } // We'll never need to test for the trigger being closed again. triggerRunner.clearFinished(directContext.state()); } From 5bfbf852d72b3ec4b15cfef76bd9542ffb7e6ac0 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 9 Mar 2016 16:50:16 -0800 Subject: [PATCH 260/751] Add unit test. --- .../dataflow/sdk/util/ReduceFnRunner.java | 5 ++- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 38 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 2b6e0d43db..2e2d1f6c7d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -602,7 +602,8 @@ private void clearAllState( boolean windowIsActive) throws Exception { if (windowIsActive) { - // Since window was still active the trigger may not have closed. + // Since both the window is in the active window set AND the trigger was not yet closed, + // it is possible we still have state. reduceFn.clearState(renamedContext); watermarkHold.clearHolds(renamedContext); nonEmptyPanes.clearPane(renamedContext.state()); @@ -623,7 +624,7 @@ private void clearAllState( } paneInfoTracker.clear(directContext.state()); if (activeWindows.isActive(directContext.window())) { - // Don't need to track address state windows anymore + // Don't need to track address state windows anymore. activeWindows.remove(directContext.window()); } // We'll never need to test for the trigger being closed again. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index 4fb3e37cb4..e1348f7e25 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -686,6 +686,44 @@ public void testMergeBeforeFinalizing() throws Exception { equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); } + /** + * It is possible for a session window's trigger to be closed at the point at which + * the (merged) session window is garbage collected. Make sure we don't accidentally + * assume the window is still active. + */ + @Test + public void testMergingWithCloseBeforeGC() throws Exception { + ReduceFnTester, IntervalWindow> tester = + ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), + ClosingBehavior.FIRE_IF_NON_EMPTY); + + // Two elements in two overlapping session windows. + tester.injectElements( + TimestampedValue.of(1, new Instant(1)), // in [1, 11) + TimestampedValue.of(10, new Instant(10))); // in [10, 20) + + // Close the trigger, but the gargbage collection timer is still pending. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + tester.advanceInputWatermark(new Instant(30)); + + // Now the garbage collection timer will fire, finding the trigger already closed. + tester.advanceInputWatermark(new Instant(100)); + + List>> output = tester.extractOutput(); + assertThat(output.size(), equalTo(1)); + assertThat(output.get(0), + isSingleWindowedValue(containsInAnyOrder(1, 10), + 1, // timestamp + 1, // window start + 20)); // window end + assertThat( + output.get(0).getPane(), + equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); + } + + /** * Tests that when data is assigned to multiple windows but some of those windows have * had their triggers finish, then the data is dropped and counted accurately. From 47417df043872abeabef5bde23ff6a8280577084 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Thu, 10 Mar 2016 08:49:47 -0800 Subject: [PATCH 261/751] Whitespace --- .../com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index e1348f7e25..c60af85572 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -723,7 +723,6 @@ public void testMergingWithCloseBeforeGC() throws Exception { equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); } - /** * Tests that when data is assigned to multiple windows but some of those windows have * had their triggers finish, then the data is dropped and counted accurately. From 1d89968512dd3850fbdf1737f2296e8a9f67ad71 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Thu, 10 Mar 2016 14:11:20 -0800 Subject: [PATCH 262/751] remove is idempotent --- examples/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- .../cloud/dataflow/sdk/util/MergingActiveWindowSet.java | 8 ++++++-- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 22183670c2..c15f73f688 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT com.google.cloud.dataflow diff --git a/pom.xml b/pom.xml index d3e6e070f3..2737e657ec 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index f782b78532..d7e10a53a8 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT com.google.cloud.dataflow diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index 5af4ea5676..96629b1601 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -191,8 +191,12 @@ public void addActive(W window) { @Override public void remove(W window) { - Preconditions.checkState(isActive(window), "Window %s is not active", window); - for (W stateAddressWindow : activeWindowToStateAddressWindows.get(window)) { + Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); + if (stateAddressWindows == null) { + // Window is no longer active. + return; + } + for (W stateAddressWindow : stateAddressWindows) { windowToActiveWindow.remove(stateAddressWindow); } activeWindowToStateAddressWindows.remove(window); From 5fbe84d66c4953c65a937419c4b2c2dbbb00ff33 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Thu, 10 Mar 2016 14:16:55 -0800 Subject: [PATCH 263/751] Undo --- examples/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index c15f73f688..22183670c2 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.5.0-SNAPSHOT com.google.cloud.dataflow diff --git a/pom.xml b/pom.xml index 2737e657ec..d3e6e070f3 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.6.0-SNAPSHOT + 1.5.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index d7e10a53a8..f782b78532 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.5.0-SNAPSHOT com.google.cloud.dataflow From 29292f602b0060d09180bc1ff1311246de63c43c Mon Sep 17 00:00:00 2001 From: davor Date: Wed, 9 Mar 2016 14:32:12 -0800 Subject: [PATCH 264/751] Version management Declare version 1.6.0-SNAPSHOT. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=116803966 --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 22183670c2..c15f73f688 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 6cb1852562..4e999083b0 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index b5b32514dc..0aa71c49f9 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index d3e6e070f3..2737e657ec 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index f782b78532..d7e10a53a8 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT com.google.cloud.dataflow From 02cd954000074958b135e7c4415792ccdb237b39 Mon Sep 17 00:00:00 2001 From: Neville Li Date: Wed, 23 Mar 2016 06:05:51 +0800 Subject: [PATCH 265/751] make BigtableIO#Read#withRowFilter public --- .../com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index 562d253d77..7ecccf14a6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -211,7 +211,7 @@ public Read withBigtableOptions(BigtableOptions.Builder optionsBuilder) { * *

    Does not modify this object. */ - Read withRowFilter(RowFilter filter) { + public Read withRowFilter(RowFilter filter) { checkNotNull(filter, "filter"); return new Read(options, tableId, filter, bigtableService); } From 9651ed46db4c0915de2d45b849b8eb17c657645d Mon Sep 17 00:00:00 2001 From: sammcveety Date: Tue, 22 Mar 2016 11:58:19 -0700 Subject: [PATCH 266/751] Update AutoComplete.java Allow for the Datastore dependency of this test to be in a different project than the main project for the job. --- .../cloud/dataflow/examples/complete/AutoComplete.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java index 1bccc4ace2..f897338889 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java @@ -57,6 +57,7 @@ import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import org.joda.time.Duration; @@ -432,10 +433,14 @@ private static interface Options extends ExamplePubsubTopicOptions, ExampleBigQu Boolean getOutputToBigQuery(); void setOutputToBigQuery(Boolean value); - @Description("Whether output to Datastoree") + @Description("Whether output to Datastore") @Default.Boolean(false) Boolean getOutputToDatastore(); void setOutputToDatastore(Boolean value); + + @Description("Datastore output dataset ID, defaults to project ID") + String getOutputDataset(); + void setOutputDataset(String value); } public static void main(String[] args) throws IOException { @@ -477,7 +482,8 @@ public static void main(String[] args) throws IOException { if (options.getOutputToDatastore()) { toWrite .apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind()))) - .apply(DatastoreIO.writeTo(options.getProject())); + .apply(DatastoreIO.writeTo(MoreObjects.firstNonNull( + options.getOutputDataset(), options.getProject()))); } if (options.getOutputToBigQuery()) { dataflowUtils.setupBigQueryTable(); From f16cbb1e4799597071ce82359522a2df218fdc1c Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 15 Mar 2016 00:45:42 -0700 Subject: [PATCH 267/751] Minor Javadoc fixes - Add package-info.java to two missing packages. - Fix a compile error leftover from changing a link to a code block, which requires dropping HTML escaping of brackets. --- .../sdk/coders/protobuf/package-info.java | 23 +++++++++++++++++++ .../dataflow/sdk/io/bigtable/BigtableIO.java | 2 +- .../sdk/io/bigtable/package-info.java | 22 ++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java new file mode 100644 index 0000000000..b5bcf18eda --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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. + */ + +/** + * Defines a {@link com.google.cloud.dataflow.sdk.coders.Coder} + * for Protocol Buffers messages, {@code ProtoCoder}. + * + * @see com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder + */ +package com.google.cloud.dataflow.sdk.coders.protobuf; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index 7ecccf14a6..7d59b09c8d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -72,7 +72,7 @@ *

    Reading from Cloud Bigtable

    * *

    The Bigtable source returns a set of rows from a single table, returning a - * {@code PCollection<Row>}. + * {@code PCollection}. * *

    To configure a Cloud Bigtable source, you must supply a table id and a {@link BigtableOptions} * or builder configured with the project and other information necessary to identify the diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java new file mode 100644 index 0000000000..112a954d71 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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. + */ + +/** + * Defines transforms for reading and writing from Google Cloud Bigtable. + * + * @see com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO + */ +package com.google.cloud.dataflow.sdk.io.bigtable; From 21e1f34db8c00754ec92101aacc7803530060766 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 26 Feb 2016 17:28:37 -0800 Subject: [PATCH 268/751] Implement InProcessEvaluationContext This is the primary "global state" object for the evaluation of a Pipeline using the InProcessPipelineRunner, and is responsible for properly routing information about the state of the pipeline to transform evaluators. Remove the InProcessEvaluationContext from the InProcessPipelineRunner class, and implement as a class directly. Fix associated imports. --- .../BoundedReadEvaluatorFactory.java | 1 - .../sdk/runners/inprocess/EvaluatorKey.java | 1 - .../inprocess/FlattenEvaluatorFactory.java | 1 - .../inprocess/GroupByKeyEvaluatorFactory.java | 1 - .../inprocess/InMemoryWatermarkManager.java | 14 +- .../runners/inprocess/InProcessBundle.java | 20 +- .../inprocess/InProcessEvaluationContext.java | 364 +++++++++++++++ .../inprocess/InProcessPipelineOptions.java | 7 +- .../inprocess/InProcessPipelineRunner.java | 106 +---- .../InProcessSideInputContainer.java | 71 ++- .../inprocess/ParDoMultiEvaluatorFactory.java | 1 - .../ParDoSingleEvaluatorFactory.java | 1 - .../sdk/runners/inprocess/StepAndKey.java | 68 +++ .../inprocess/TransformEvaluatorFactory.java | 1 - .../inprocess/TransformEvaluatorRegistry.java | 72 +++ .../UnboundedReadEvaluatorFactory.java | 1 - .../inprocess/ViewEvaluatorFactory.java | 1 - .../inprocess/WatermarkCallbackExecutor.java | 143 ++++++ .../BoundedReadEvaluatorFactoryTest.java | 2 +- .../FlattenEvaluatorFactoryTest.java | 1 - .../GroupByKeyEvaluatorFactoryTest.java | 1 - .../InMemoryWatermarkManagerTest.java | 12 + .../InProcessEvaluationContextTest.java | 436 ++++++++++++++++++ .../InProcessSideInputContainerTest.java | 92 ++-- .../ParDoMultiEvaluatorFactoryTest.java | 1 - .../ParDoSingleEvaluatorFactoryTest.java | 1 - .../UnboundedReadEvaluatorFactoryTest.java | 1 - .../inprocess/ViewEvaluatorFactoryTest.java | 1 - .../WatermarkCallbackExecutorTest.java | 126 +++++ 29 files changed, 1372 insertions(+), 176 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java index 1c0279897a..2a164c3518 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java @@ -18,7 +18,6 @@ import com.google.cloud.dataflow.sdk.io.Read.Bounded; import com.google.cloud.dataflow.sdk.io.Source.Reader; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java index 745f8f2718..307bc5cdb5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java @@ -15,7 +15,6 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import java.util.Objects; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java index 14428888e2..bde1df45e9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Flatten; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java index 0347281749..ec63be84c9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java @@ -22,7 +22,6 @@ import com.google.cloud.dataflow.sdk.coders.IterableCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult.Builder; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index e280e22d2b..7cf53aafe6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -1209,8 +1209,11 @@ public TimerUpdateBuilder deletedTimer(TimerData deletedTimer) { * and deletedTimers. */ public TimerUpdate build() { - return new TimerUpdate(key, ImmutableSet.copyOf(completedTimers), - ImmutableSet.copyOf(setTimers), ImmutableSet.copyOf(deletedTimers)); + return new TimerUpdate( + key, + ImmutableSet.copyOf(completedTimers), + ImmutableSet.copyOf(setTimers), + ImmutableSet.copyOf(deletedTimers)); } } @@ -1245,6 +1248,13 @@ Iterable getDeletedTimers() { return deletedTimers; } + /** + * Returns a {@link TimerUpdate} that is like this one, but with the specified completed timers. + */ + public TimerUpdate withCompletedTimers(Iterable completedTimers) { + return new TimerUpdate(this.key, completedTimers, setTimers, deletedTimers); + } + @Override public int hashCode() { return Objects.hash(key, completedTimers, setTimers, deletedTimers); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java index cc20161097..112ba17d14 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Google Inc. + * Copyright (C) 2016 Google Inc. * * Licensed 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 @@ -22,7 +22,6 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; -import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.collect.ImmutableList; import org.joda.time.Instant; @@ -64,6 +63,11 @@ private InProcessBundle(PCollection pcollection, boolean keyed, Object key) { this.elements = ImmutableList.builder(); } + @Override + public PCollection getPCollection() { + return pcollection; + } + @Override public InProcessBundle add(WindowedValue element) { checkState(!committed, "Can't add element %s to committed bundle %s", element, this); @@ -105,12 +109,12 @@ public Instant getSynchronizedProcessingOutputWatermark() { @Override public String toString() { - ToStringHelper toStringHelper = - MoreObjects.toStringHelper(this).add("pcollection", pcollection); - if (keyed) { - toStringHelper = toStringHelper.add("key", key); - } - return toStringHelper.add("elements", elements).toString(); + return MoreObjects.toStringHelper(this) + .omitNullValues() + .add("pcollection", pcollection) + .add("key", key) + .add("elements", committedElements) + .toString(); } }; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java new file mode 100644 index 0000000000..757e9e11d9 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -0,0 +1,364 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; +import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; +import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; +import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.SideInputReader; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import javax.annotation.Nullable; + +/** + * The evaluation context for a specific pipeline being executed by the + * {@link InProcessPipelineRunner}. Contains state shared within the execution across all + * transforms. + * + *

    {@link InProcessEvaluationContext} contains shared state for an execution of the + * {@link InProcessPipelineRunner} that can be used while evaluating a {@link PTransform}. This + * consists of views into underlying state and watermark implementations, access to read and write + * {@link PCollectionView PCollectionViews}, and constructing {@link CounterSet CounterSets} and + * {@link ExecutionContext ExecutionContexts}. This includes executing callbacks asynchronously when + * state changes to the appropriate point (e.g. when a {@link PCollectionView} is requested and + * known to be empty). + * + *

    {@link InProcessEvaluationContext} also handles results by committing finalizing bundles based + * on the current global state and updating the global state appropriately. This includes updating + * the per-{@link StepAndKey} state, updating global watermarks, and executing any callbacks that + * can be executed. + */ +class InProcessEvaluationContext { + /** The step name for each {@link AppliedPTransform} in the {@link Pipeline}. */ + private final Map, String> stepNames; + + /** The options that were used to create this {@link Pipeline}. */ + private final InProcessPipelineOptions options; + + /** The current processing time and event time watermarks and timers. */ + private final InMemoryWatermarkManager watermarkManager; + + /** Executes callbacks based on the progression of the watermark. */ + private final WatermarkCallbackExecutor callbackExecutor; + + /** The stateInternals of the world, by applied PTransform and key. */ + private final ConcurrentMap> + applicationStateInternals; + + private final InProcessSideInputContainer sideInputContainer; + + private final CounterSet mergedCounters; + + public static InProcessEvaluationContext create( + InProcessPipelineOptions options, + Collection> rootTransforms, + Map>> valueToConsumers, + Map, String> stepNames, + Collection> views) { + return new InProcessEvaluationContext( + options, rootTransforms, valueToConsumers, stepNames, views); + } + + private InProcessEvaluationContext( + InProcessPipelineOptions options, + Collection> rootTransforms, + Map>> valueToConsumers, + Map, String> stepNames, + Collection> views) { + this.options = checkNotNull(options); + checkNotNull(rootTransforms); + checkNotNull(valueToConsumers); + checkNotNull(stepNames); + checkNotNull(views); + this.stepNames = stepNames; + + this.watermarkManager = + InMemoryWatermarkManager.create( + NanosOffsetClock.create(), rootTransforms, valueToConsumers); + this.sideInputContainer = InProcessSideInputContainer.create(this, views); + + this.applicationStateInternals = new ConcurrentHashMap<>(); + this.mergedCounters = new CounterSet(); + + this.callbackExecutor = WatermarkCallbackExecutor.create(); + } + + /** + * Handle the provided {@link InProcessTransformResult}, produced after evaluating the provided + * {@link CommittedBundle} (potentially null, if the result of a root {@link PTransform}). + * + *

    The result is the output of running the transform contained in the + * {@link InProcessTransformResult} on the contents of the provided bundle. + * + * @param completedBundle the bundle that was processed to produce the result. Potentially + * {@code null} if the transform that produced the result is a root + * transform + * @param completedTimers the timers that were delivered to produce the {@code completedBundle}, + * or an empty iterable if no timers were delivered + * @param result the result of evaluating the input bundle + * @return the committed bundles contained within the handled {@code result} + */ + public synchronized Iterable> handleResult( + @Nullable CommittedBundle completedBundle, + Iterable completedTimers, + InProcessTransformResult result) { + Iterable> committedBundles = + commitBundles(result.getOutputBundles()); + // Update watermarks and timers + watermarkManager.updateWatermarks( + completedBundle, + result.getTransform(), + result.getTimerUpdate().withCompletedTimers(completedTimers), + committedBundles, + result.getWatermarkHold()); + fireAllAvailableCallbacks(); + // Update counters + if (result.getCounters() != null) { + mergedCounters.merge(result.getCounters()); + } + // Update state internals + CopyOnAccessInMemoryStateInternals theirState = result.getState(); + if (theirState != null) { + CopyOnAccessInMemoryStateInternals committedState = theirState.commit(); + StepAndKey stepAndKey = + StepAndKey.of( + result.getTransform(), completedBundle == null ? null : completedBundle.getKey()); + if (!committedState.isEmpty()) { + applicationStateInternals.put(stepAndKey, committedState); + } else { + applicationStateInternals.remove(stepAndKey); + } + } + return committedBundles; + } + + private Iterable> commitBundles( + Iterable> bundles) { + ImmutableList.Builder> completed = ImmutableList.builder(); + for (UncommittedBundle inProgress : bundles) { + AppliedPTransform producing = + inProgress.getPCollection().getProducingTransformInternal(); + TransformWatermarks watermarks = watermarkManager.getWatermarks(producing); + CommittedBundle committed = + inProgress.commit(watermarks.getSynchronizedProcessingOutputTime()); + // Empty bundles don't impact watermarks and shouldn't trigger downstream execution, so + // filter them out + if (!Iterables.isEmpty(committed.getElements())) { + completed.add(committed); + } + } + return completed.build(); + } + + private void fireAllAvailableCallbacks() { + for (AppliedPTransform transform : stepNames.keySet()) { + fireAvailableCallbacks(transform); + } + } + + private void fireAvailableCallbacks(AppliedPTransform producingTransform) { + TransformWatermarks watermarks = watermarkManager.getWatermarks(producingTransform); + callbackExecutor.fireForWatermark(producingTransform, watermarks.getOutputWatermark()); + } + + /** + * Create a {@link UncommittedBundle} for use by a source. + */ + public UncommittedBundle createRootBundle(PCollection output) { + return InProcessBundle.unkeyed(output); + } + + /** + * Create a {@link UncommittedBundle} whose elements belong to the specified {@link + * PCollection}. + */ + public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { + return input.isKeyed() + ? InProcessBundle.keyed(output, input.getKey()) + : InProcessBundle.unkeyed(output); + } + + /** + * Create a {@link UncommittedBundle} with the specified keys at the specified step. For use by + * {@link InProcessGroupByKeyOnly} {@link PTransform PTransforms}. + */ + public UncommittedBundle createKeyedBundle( + CommittedBundle input, Object key, PCollection output) { + return InProcessBundle.keyed(output, key); + } + + /** + * Create a {@link PCollectionViewWriter}, whose elements will be used in the provided + * {@link PCollectionView}. + */ + public PCollectionViewWriter createPCollectionViewWriter( + PCollection> input, final PCollectionView output) { + return new PCollectionViewWriter() { + @Override + public void add(Iterable> values) { + sideInputContainer.write(output, values); + } + }; + } + + /** + * Schedule a callback to be executed after output would be produced for the given window + * if there had been input. + * + *

    Output would be produced when the watermark for a {@link PValue} passes the point at + * which the trigger for the specified window (with the specified windowing strategy) must have + * fired from the perspective of that {@link PValue}, as specified by the value of + * {@link Trigger#getWatermarkThatGuaranteesFiring(BoundedWindow)} for the trigger of the + * {@link WindowingStrategy}. When the callback has fired, either values will have been produced + * for a key in that window, the window is empty, or all elements in the window are late. The + * callback will be executed regardless of whether values have been produced. + */ + public void scheduleAfterOutputWouldBeProduced( + PValue value, + BoundedWindow window, + WindowingStrategy windowingStrategy, + Runnable runnable) { + AppliedPTransform producing = getProducing(value); + callbackExecutor.callOnGuaranteedFiring(producing, window, windowingStrategy, runnable); + + fireAvailableCallbacks(lookupProducing(value)); + } + + private AppliedPTransform getProducing(PValue value) { + if (value.getProducingTransformInternal() != null) { + return value.getProducingTransformInternal(); + } + return lookupProducing(value); + } + + private AppliedPTransform lookupProducing(PValue value) { + for (AppliedPTransform transform : stepNames.keySet()) { + if (transform.getOutput().equals(value) || transform.getOutput().expand().contains(value)) { + return transform; + } + } + return null; + } + + /** + * Get the options used by this {@link Pipeline}. + */ + public InProcessPipelineOptions getPipelineOptions() { + return options; + } + + /** + * Get an {@link ExecutionContext} for the provided {@link AppliedPTransform} and key. + */ + public InProcessExecutionContext getExecutionContext( + AppliedPTransform application, Object key) { + StepAndKey stepAndKey = StepAndKey.of(application, key); + return new InProcessExecutionContext( + options.getClock(), + key, + (CopyOnAccessInMemoryStateInternals) applicationStateInternals.get(stepAndKey), + watermarkManager.getWatermarks(application)); + } + + /** + * Get all of the steps used in this {@link Pipeline}. + */ + public Collection> getSteps() { + return stepNames.keySet(); + } + + /** + * Get the Step Name for the provided application. + */ + public String getStepName(AppliedPTransform application) { + return stepNames.get(application); + } + + /** + * Returns a {@link SideInputReader} capable of reading the provided + * {@link PCollectionView PCollectionViews}. + * @param sideInputs the {@link PCollectionView PCollectionViews} the result should be able to + * read + * @return a {@link SideInputReader} that can read all of the provided + * {@link PCollectionView PCollectionViews} + */ + public SideInputReader createSideInputReader(final List> sideInputs) { + return sideInputContainer.createReaderForViews(sideInputs); + } + + /** + * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent + * of all other {@link CounterSet CounterSets} created by this call. + * + * The {@link InProcessEvaluationContext} is responsible for unifying the counters present in + * all created {@link CounterSet CounterSets} when the transforms that call this method + * complete. + */ + public CounterSet createCounterSet() { + return new CounterSet(); + } + + /** + * Returns all of the counters that have been merged into this context via calls to + * {@link CounterSet#merge(CounterSet)}. + */ + public CounterSet getCounters() { + return mergedCounters; + } + + /** + * Extracts all timers that have been fired and have not already been extracted. + * + *

    This is a destructive operation. Timers will only appear in the result of this method once + * for each time they are set. + */ + public Map, Map> extractFiredTimers() { + return watermarkManager.extractFiredTimers(); + } + + /** + * Returns true if all steps are done. + */ + public boolean isDone() { + return watermarkManager.isDone(); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java index d659d962f0..60c8543a2f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java @@ -15,10 +15,15 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.PipelineOptions; /** * Options that can be used to configure the {@link InProcessPipelineRunner}. */ -public interface InProcessPipelineOptions extends PipelineOptions {} +public interface InProcessPipelineOptions extends PipelineOptions { + @Default.InstanceFactory(NanosOffsetClock.Factory.class) + Clock getClock(); + void setClock(Clock clock); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 124de46b94..7a268ee5fa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -17,31 +17,22 @@ import static com.google.common.base.Preconditions.checkArgument; -import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKey; import com.google.cloud.dataflow.sdk.runners.inprocess.ViewEvaluatorFactory.InProcessCreatePCollectionView; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.collect.ImmutableMap; import org.joda.time.Instant; -import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -82,6 +73,11 @@ public class InProcessPipelineRunner { * @param the type of elements that can be added to this bundle */ public static interface UncommittedBundle { + /** + * Returns the PCollection that the elements of this bundle belong to. + */ + PCollection getPCollection(); + /** * Outputs an element to this bundle. * @@ -110,7 +106,7 @@ public static interface UncommittedBundle { public static interface CommittedBundle { /** - * @return the PCollection that the elements of this bundle belong to + * Returns the PCollection that the elements of this bundle belong to. */ PCollection getPCollection(); @@ -154,84 +150,22 @@ public static interface PCollectionViewWriter { void add(Iterable> values); } - /** - * The evaluation context for the {@link InProcessPipelineRunner}. Contains state shared within - * the current evaluation. - */ - public static interface InProcessEvaluationContext { - /** - * Create a {@link UncommittedBundle} for use by a source. - */ - UncommittedBundle createRootBundle(PCollection output); - - /** - * Create a {@link UncommittedBundle} whose elements belong to the specified {@link - * PCollection}. - */ - UncommittedBundle createBundle(CommittedBundle input, PCollection output); - - /** - * Create a {@link UncommittedBundle} with the specified keys at the specified step. For use by - * {@link GroupByKeyOnly} {@link PTransform PTransforms}. - */ - UncommittedBundle createKeyedBundle( - CommittedBundle input, Object key, PCollection output); - - /** - * Create a bundle whose elements will be used in a PCollectionView. - */ - PCollectionViewWriter createPCollectionViewWriter( - PCollection> input, PCollectionView output); - - /** - * Get the options used by this {@link Pipeline}. - */ - InProcessPipelineOptions getPipelineOptions(); - - /** - * Get an {@link ExecutionContext} for the provided application. - */ - InProcessExecutionContext getExecutionContext( - AppliedPTransform application, @Nullable Object key); - - /** - * Get the Step Name for the provided application. - */ - String getStepName(AppliedPTransform application); - - /** - * @param sideInputs the {@link PCollectionView PCollectionViews} the result should be able to - * read - * @return a {@link SideInputReader} that can read all of the provided - * {@link PCollectionView PCollectionViews} - */ - SideInputReader createSideInputReader(List> sideInputs); + //////////////////////////////////////////////////////////////////////////////////////////////// + private final InProcessPipelineOptions options; - /** - * Schedules a callback after the watermark for a {@link PValue} after the trigger for the - * specified window (with the specified windowing strategy) must have fired from the perspective - * of that {@link PValue}, as specified by the value of - * {@link Trigger#getWatermarkThatGuaranteesFiring(BoundedWindow)} for the trigger of the - * {@link WindowingStrategy}. - */ - void callAfterOutputMustHaveBeenProduced(PValue value, BoundedWindow window, - WindowingStrategy windowingStrategy, Runnable runnable); + public static InProcessPipelineRunner fromOptions(PipelineOptions options) { + return new InProcessPipelineRunner(options.as(InProcessPipelineOptions.class)); + } - /** - * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent - * of all other {@link CounterSet CounterSets} created by this call. - * - * The {@link InProcessEvaluationContext} is responsible for unifying the counters present in - * all created {@link CounterSet CounterSets} when the transforms that call this method - * complete. - */ - CounterSet createCounterSet(); + private InProcessPipelineRunner(InProcessPipelineOptions options) { + this.options = options; + } - /** - * Returns all of the counters that have been merged into this context via calls to - * {@link CounterSet#merge(CounterSet)}. - */ - CounterSet getCounters(); + /** + * Returns the {@link PipelineOptions} used to create this {@link InProcessPipelineRunner}. + */ + public InProcessPipelineOptions getPipelineOptions() { + return options; } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java index bf9a2e1c53..37c9fcfa65 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -17,7 +17,6 @@ import static com.google.common.base.Preconditions.checkArgument; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; @@ -26,6 +25,7 @@ import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.common.base.MoreObjects; +import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -89,7 +89,7 @@ private InProcessSideInputContainer(InProcessEvaluationContext context, * the provided argument. The returned {@link InProcessSideInputContainer} is unmodifiable without * casting, but will change as this {@link InProcessSideInputContainer} is modified. */ - public SideInputReader withViews(Collection> newContainedViews) { + public SideInputReader createReaderForViews(Collection> newContainedViews) { if (!containedViews.containsAll(newContainedViews)) { Set> currentlyContained = ImmutableSet.copyOf(containedViews); Set> newRequested = ImmutableSet.copyOf(newContainedViews); @@ -108,8 +108,20 @@ public SideInputReader withViews(Collection> newContainedView * *

    The provided iterable is expected to contain only a single window and pane. */ - public void write(PCollectionView view, Iterable> values) - throws ExecutionException { + public void write(PCollectionView view, Iterable> values) { + Map>> valuesPerWindow = + indexValuesByWindow(values); + for (Map.Entry>> windowValues : + valuesPerWindow.entrySet()) { + updatePCollectionViewWindowValues(view, windowValues.getKey(), windowValues.getValue()); + } + } + + /** + * Index the provided values by all {@link BoundedWindow windows} in which they appear. + */ + private Map>> indexValuesByWindow( + Iterable> values) { Map>> valuesPerWindow = new HashMap<>(); for (WindowedValue value : values) { for (BoundedWindow window : value.getWindows()) { @@ -121,29 +133,40 @@ public void write(PCollectionView view, Iterable> windowValues.add(value); } } - for (Map.Entry>> windowValues : - valuesPerWindow.entrySet()) { - PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, windowValues.getKey()); - SettableFuture>> future = viewByWindows.get(windowedView); + return valuesPerWindow; + } + + /** + * Set the value of the {@link PCollectionView} in the {@link BoundedWindow} to be based on the + * specified values, if the values are part of a later pane than currently exist within the + * {@link PCollectionViewWindow}. + */ + private void updatePCollectionViewWindowValues( + PCollectionView view, BoundedWindow window, Collection> windowValues) { + PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, window); + SettableFuture>> future = null; + try { + future = viewByWindows.get(windowedView); if (future.isDone()) { - try { - Iterator> existingValues = future.get().iterator(); - PaneInfo newPane = windowValues.getValue().iterator().next().getPane(); - // The current value may have no elements, if no elements were produced for the window, - // but we are recieving late data. - if (!existingValues.hasNext() - || newPane.getIndex() > existingValues.next().getPane().getIndex()) { - viewByWindows.invalidate(windowedView); - viewByWindows.get(windowedView).set(windowValues.getValue()); - } - } catch (InterruptedException e) { - // TODO: Handle meaningfully. This should never really happen when the result remains - // useful, but the result could be available and the thread can still be interrupted. - Thread.currentThread().interrupt(); + Iterator> existingValues = future.get().iterator(); + PaneInfo newPane = windowValues.iterator().next().getPane(); + // The current value may have no elements, if no elements were produced for the window, + // but we are recieving late data. + if (!existingValues.hasNext() + || newPane.getIndex() > existingValues.next().getPane().getIndex()) { + viewByWindows.invalidate(windowedView); + viewByWindows.get(windowedView).set(windowValues); } } else { - future.set(windowValues.getValue()); + future.set(windowValues); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + if (future != null && !future.isDone()) { + future.set(Collections.>emptyList()); } + } catch (ExecutionException e) { + Throwables.propagate(e.getCause()); } } @@ -165,7 +188,7 @@ public T get(final PCollectionView view, final BoundedWindow window) { viewByWindows.get(windowedView); WindowingStrategy windowingStrategy = view.getWindowingStrategyInternal(); - evaluationContext.callAfterOutputMustHaveBeenProduced( + evaluationContext.scheduleAfterOutputWouldBeProduced( view, window, windowingStrategy, new Runnable() { @Override public void run() { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java index e3ae1a028c..24142c2151 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java @@ -17,7 +17,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java index cd79c219bd..af5914bab0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java @@ -17,7 +17,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java new file mode 100644 index 0000000000..15955724eb --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.common.base.MoreObjects; + +import java.util.Objects; + +/** + * A (Step, Key) pair. This is useful as a map key or cache key for things that are available + * per-step in a keyed manner (e.g. State). + */ +final class StepAndKey { + private final AppliedPTransform step; + private final Object key; + + /** + * Create a new {@link StepAndKey} with the provided step and key. + */ + public static StepAndKey of(AppliedPTransform step, Object key) { + return new StepAndKey(step, key); + } + + private StepAndKey(AppliedPTransform step, Object key) { + this.step = step; + this.key = key; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(StepAndKey.class) + .add("step", step.getFullName()) + .add("key", key) + .toString(); + } + + @Override + public int hashCode() { + return Objects.hash(step, key); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (!(other instanceof StepAndKey)) { + return false; + } else { + StepAndKey that = (StepAndKey) other; + return Objects.equals(this.step, that.step) + && Objects.equals(this.key, that.key); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java index 3b672e0def..860ddfe48f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java new file mode 100644 index 0000000000..0c8cb7e80a --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +import javax.annotation.Nullable; + +/** + * A {@link TransformEvaluatorFactory} that delegates to primitive {@link TransformEvaluatorFactory} + * implementations based on the type of {@link PTransform} of the application. + */ +class TransformEvaluatorRegistry implements TransformEvaluatorFactory { + public static TransformEvaluatorRegistry defaultRegistry() { + @SuppressWarnings("rawtypes") + ImmutableMap, TransformEvaluatorFactory> primitives = + ImmutableMap., TransformEvaluatorFactory>builder() + .put(Read.Bounded.class, new BoundedReadEvaluatorFactory()) + .put(Read.Unbounded.class, new UnboundedReadEvaluatorFactory()) + .put(ParDo.Bound.class, new ParDoSingleEvaluatorFactory()) + .put(ParDo.BoundMulti.class, new ParDoMultiEvaluatorFactory()) + .put( + GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly.class, + new GroupByKeyEvaluatorFactory()) + .put(FlattenPCollectionList.class, new FlattenEvaluatorFactory()) + .put(ViewEvaluatorFactory.WriteView.class, new ViewEvaluatorFactory()) + .build(); + return new TransformEvaluatorRegistry(primitives); + } + + // the TransformEvaluatorFactories can construct instances of all generic types of transform, + // so all instances of a primitive can be handled with the same evaluator factory. + @SuppressWarnings("rawtypes") + private final Map, TransformEvaluatorFactory> factories; + + private TransformEvaluatorRegistry( + @SuppressWarnings("rawtypes") + Map, TransformEvaluatorFactory> factories) { + this.factories = factories; + } + + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + @Nullable CommittedBundle inputBundle, + InProcessEvaluationContext evaluationContext) + throws Exception { + TransformEvaluatorFactory factory = factories.get(application.getTransform().getClass()); + return factory.forApplication(application, inputBundle, evaluationContext); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index 4beac337d6..97f0e25d38 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java index f47cd1de98..314d81f6aa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java @@ -17,7 +17,6 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java new file mode 100644 index 0000000000..27d59b9a64 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.common.collect.ComparisonChain; +import com.google.common.collect.Ordering; + +import org.joda.time.Instant; + +import java.util.PriorityQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Executes callbacks that occur based on the progression of the watermark per-step. + * + *

    Callbacks are registered by calls to + * {@link #callOnGuaranteedFiring(AppliedPTransform, BoundedWindow, WindowingStrategy, Runnable)}, + * and are executed after a call to {@link #fireForWatermark(AppliedPTransform, Instant)} with the + * same {@link AppliedPTransform} and a watermark sufficient to ensure that the trigger for the + * windowing strategy would have been produced. + * + *

    NOTE: {@link WatermarkCallbackExecutor} does not track the latest observed watermark for any + * {@link AppliedPTransform} - any call to + * {@link #callOnGuaranteedFiring(AppliedPTransform, BoundedWindow, WindowingStrategy, Runnable)} + * that could have potentially already fired should be followed by a call to + * {@link #fireForWatermark(AppliedPTransform, Instant)} for the same transform with the current + * value of the watermark. + */ +class WatermarkCallbackExecutor { + /** + * Create a new {@link WatermarkCallbackExecutor}. + */ + public static WatermarkCallbackExecutor create() { + return new WatermarkCallbackExecutor(); + } + + private final ConcurrentMap, PriorityQueue> + callbacks; + private final ExecutorService executor; + + private WatermarkCallbackExecutor() { + this.callbacks = new ConcurrentHashMap<>(); + this.executor = Executors.newSingleThreadExecutor(); + } + + /** + * Execute the provided {@link Runnable} after the next call to + * {@link #fireForWatermark(AppliedPTransform, Instant)} where the window is guaranteed to have + * produced output. + */ + public void callOnGuaranteedFiring( + AppliedPTransform step, + BoundedWindow window, + WindowingStrategy windowingStrategy, + Runnable runnable) { + WatermarkCallback callback = + WatermarkCallback.onGuaranteedFiring(window, windowingStrategy, runnable); + + PriorityQueue callbackQueue = callbacks.get(step); + if (callbackQueue == null) { + callbackQueue = new PriorityQueue<>(11, new CallbackOrdering()); + if (callbacks.putIfAbsent(step, callbackQueue) != null) { + callbackQueue = callbacks.get(step); + } + } + + synchronized (callbackQueue) { + callbackQueue.offer(callback); + } + } + + /** + * Schedule all pending callbacks that must have produced output by the time of the provided + * watermark. + */ + public void fireForWatermark(AppliedPTransform step, Instant watermark) { + PriorityQueue callbackQueue = callbacks.get(step); + if (callbackQueue == null) { + return; + } + synchronized (callbackQueue) { + while (!callbackQueue.isEmpty() && callbackQueue.peek().shouldFire(watermark)) { + executor.submit(callbackQueue.poll().getCallback()); + } + } + } + + private static class WatermarkCallback { + public static WatermarkCallback onGuaranteedFiring( + BoundedWindow window, WindowingStrategy strategy, Runnable callback) { + @SuppressWarnings("unchecked") + Instant firingAfter = + strategy.getTrigger().getSpec().getWatermarkThatGuaranteesFiring((W) window); + return new WatermarkCallback(firingAfter, callback); + } + + private final Instant fireAfter; + private final Runnable callback; + + private WatermarkCallback(Instant fireAfter, Runnable callback) { + this.fireAfter = fireAfter; + this.callback = callback; + } + + public boolean shouldFire(Instant currentWatermark) { + return currentWatermark.isAfter(fireAfter) + || currentWatermark.equals(BoundedWindow.TIMESTAMP_MAX_VALUE); + } + + public Runnable getCallback() { + return callback; + } + } + + private static class CallbackOrdering extends Ordering { + @Override + public int compare(WatermarkCallback left, WatermarkCallback right) { + return ComparisonChain.start() + .compare(left.fireAfter, right.fireAfter) + .compare(left.callback, right.callback, Ordering.arbitrary()) + .result(); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java index 9f22fbbe9e..43955149ee 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java @@ -25,7 +25,7 @@ import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; +import com.google.cloud.dataflow.sdk.io.Read.Bounded; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java index bf25970aff..0120b9880d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java @@ -22,7 +22,6 @@ import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java index 5c9e824afe..4ced82f8c7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java @@ -23,7 +23,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index 24251522d8..52398cf73a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -1047,6 +1047,18 @@ public void timerUpdateBuilderWithCompletedAfterBuildNotAddedToBuilt() { assertThat(built.getCompletedTimers(), emptyIterable()); } + @Test + public void timerUpdateWithCompletedTimersNotAddedToExisting() { + TimerUpdateBuilder builder = TimerUpdate.builder(null); + TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); + + TimerUpdate built = builder.build(); + assertThat(built.getCompletedTimers(), emptyIterable()); + assertThat( + built.withCompletedTimers(ImmutableList.of(timer)).getCompletedTimers(), contains(timer)); + assertThat(built.getCompletedTimers(), emptyIterable()); + } + private static Matcher earlierThan(final Instant laterInstant) { return new BaseMatcher() { @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java new file mode 100644 index 0000000000..149096040a --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -0,0 +1,436 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; +import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.cloud.dataflow.sdk.util.SideInputReader; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.util.common.Counter; +import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.state.BagState; +import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; +import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; +import com.google.cloud.dataflow.sdk.util.state.StateTag; +import com.google.cloud.dataflow.sdk.util.state.StateTags; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Tests for {@link InProcessEvaluationContext}. + */ +@RunWith(JUnit4.class) +public class InProcessEvaluationContextTest { + private TestPipeline p; + private InProcessEvaluationContext context; + private PCollection created; + private PCollection> downstream; + private PCollectionView> view; + + @Before + public void setup() { + InProcessPipelineRunner runner = + InProcessPipelineRunner.fromOptions(PipelineOptionsFactory.create()); + p = TestPipeline.create(); + created = p.apply(Create.of(1, 2, 3)); + downstream = created.apply(WithKeys.of("foo")); + view = created.apply(View.asIterable()); + Collection> rootTransforms = + ImmutableList.>of(created.getProducingTransformInternal()); + Map>> valueToConsumers = new HashMap<>(); + valueToConsumers.put( + created, + ImmutableList.>of( + downstream.getProducingTransformInternal(), view.getProducingTransformInternal())); + valueToConsumers.put(downstream, ImmutableList.>of()); + valueToConsumers.put(view, ImmutableList.>of()); + + Map, String> stepNames = new HashMap<>(); + stepNames.put(created.getProducingTransformInternal(), "s1"); + stepNames.put(downstream.getProducingTransformInternal(), "s2"); + stepNames.put(view.getProducingTransformInternal(), "s3"); + + Collection> views = ImmutableList.>of(view); + context = InProcessEvaluationContext.create( + runner.getPipelineOptions(), + rootTransforms, + valueToConsumers, + stepNames, + views); + } + + @Test + public void writeToViewWriterThenReadReads() { + PCollectionViewWriter> viewWriter = + context.createPCollectionViewWriter( + PCollection.>createPrimitiveOutputInternal( + p, WindowingStrategy.globalDefault(), IsBounded.BOUNDED), + view); + BoundedWindow window = new TestBoundedWindow(new Instant(1024L)); + BoundedWindow second = new TestBoundedWindow(new Instant(899999L)); + WindowedValue firstValue = + WindowedValue.of(1, new Instant(1222), window, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue secondValue = + WindowedValue.of( + 2, new Instant(8766L), second, PaneInfo.createPane(true, false, Timing.ON_TIME, 0, 0)); + Iterable> values = ImmutableList.of(firstValue, secondValue); + viewWriter.add(values); + + SideInputReader reader = + context.createSideInputReader(ImmutableList.>of(view)); + assertThat(reader.get(view, window), containsInAnyOrder(1)); + assertThat(reader.get(view, second), containsInAnyOrder(2)); + + WindowedValue overrittenSecondValue = + WindowedValue.of( + 4444, new Instant(8677L), second, PaneInfo.createPane(false, true, Timing.LATE, 1, 1)); + viewWriter.add(Collections.singleton(overrittenSecondValue)); + assertThat(reader.get(view, second), containsInAnyOrder(4444)); + } + + @Test + public void getExecutionContextSameStepSameKeyState() { + InProcessExecutionContext fooContext = + context.getExecutionContext(created.getProducingTransformInternal(), "foo"); + + StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); + + InProcessStepContext stepContext = fooContext.getOrCreateStepContext("s1", "s1", null); + stepContext.stateInternals().state(StateNamespaces.global(), intBag).add(1); + + context.handleResult( + InProcessBundle.keyed(created, "foo").commit(Instant.now()), + ImmutableList.of(), + StepTransformResult.withoutHold(created.getProducingTransformInternal()) + .withState(stepContext.commitState()) + .build()); + + InProcessExecutionContext secondFooContext = + context.getExecutionContext(created.getProducingTransformInternal(), "foo"); + assertThat( + secondFooContext + .getOrCreateStepContext("s1", "s1", null) + .stateInternals() + .state(StateNamespaces.global(), intBag) + .read(), + contains(1)); + } + + + @Test + public void getExecutionContextDifferentKeysIndependentState() { + InProcessExecutionContext fooContext = + context.getExecutionContext(created.getProducingTransformInternal(), "foo"); + + StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); + + fooContext + .getOrCreateStepContext("s1", "s1", null) + .stateInternals() + .state(StateNamespaces.global(), intBag) + .add(1); + + InProcessExecutionContext barContext = + context.getExecutionContext(created.getProducingTransformInternal(), "bar"); + assertThat(barContext, not(equalTo(fooContext))); + assertThat( + barContext + .getOrCreateStepContext("s1", "s1", null) + .stateInternals() + .state(StateNamespaces.global(), intBag) + .read(), + emptyIterable()); + } + + @Test + public void getExecutionContextDifferentStepsIndependentState() { + String myKey = "foo"; + InProcessExecutionContext fooContext = + context.getExecutionContext(created.getProducingTransformInternal(), myKey); + + StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); + + fooContext + .getOrCreateStepContext("s1", "s1", null) + .stateInternals() + .state(StateNamespaces.global(), intBag) + .add(1); + + InProcessExecutionContext barContext = + context.getExecutionContext(downstream.getProducingTransformInternal(), myKey); + assertThat( + barContext + .getOrCreateStepContext("s1", "s1", null) + .stateInternals() + .state(StateNamespaces.global(), intBag) + .read(), + emptyIterable()); + } + + @Test + public void handleResultMergesCounters() { + CounterSet counters = context.createCounterSet(); + Counter myCounter = Counter.longs("foo", AggregationKind.SUM); + counters.addCounter(myCounter); + + myCounter.addValue(4L); + InProcessTransformResult result = + StepTransformResult.withoutHold(created.getProducingTransformInternal()) + .withCounters(counters) + .build(); + context.handleResult(null, ImmutableList.of(), result); + assertThat((Long) context.getCounters().getExistingCounter("foo").getAggregate(), equalTo(4L)); + + CounterSet againCounters = context.createCounterSet(); + Counter myLongCounterAgain = Counter.longs("foo", AggregationKind.SUM); + againCounters.add(myLongCounterAgain); + myLongCounterAgain.addValue(8L); + + InProcessTransformResult secondResult = + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()) + .withCounters(againCounters) + .build(); + context.handleResult( + InProcessBundle.unkeyed(created).commit(Instant.now()), + ImmutableList.of(), + secondResult); + assertThat((Long) context.getCounters().getExistingCounter("foo").getAggregate(), equalTo(12L)); + } + + @Test + public void handleResultStoresState() { + String myKey = "foo"; + InProcessExecutionContext fooContext = + context.getExecutionContext(downstream.getProducingTransformInternal(), myKey); + + StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); + + CopyOnAccessInMemoryStateInternals state = + fooContext.getOrCreateStepContext("s1", "s1", null).stateInternals(); + BagState bag = state.state(StateNamespaces.global(), intBag); + bag.add(1); + bag.add(2); + bag.add(4); + + InProcessTransformResult stateResult = + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()) + .withState(state) + .build(); + + context.handleResult( + InProcessBundle.keyed(created, myKey).commit(Instant.now()), + ImmutableList.of(), + stateResult); + + InProcessExecutionContext afterResultContext = + context.getExecutionContext(downstream.getProducingTransformInternal(), myKey); + + CopyOnAccessInMemoryStateInternals afterResultState = + afterResultContext.getOrCreateStepContext("s1", "s1", null).stateInternals(); + assertThat(afterResultState.state(StateNamespaces.global(), intBag).read(), contains(1, 2, 4)); + } + + @Test + public void callAfterOutputMustHaveBeenProducedAfterEndOfWatermarkCallsback() throws Exception { + final CountDownLatch callLatch = new CountDownLatch(1); + Runnable callback = + new Runnable() { + @Override + public void run() { + callLatch.countDown(); + } + }; + + // Should call back after the end of the global window + context.scheduleAfterOutputWouldBeProduced( + downstream, GlobalWindow.INSTANCE, WindowingStrategy.globalDefault(), callback); + + InProcessTransformResult result = + StepTransformResult.withHold(created.getProducingTransformInternal(), new Instant(0)) + .build(); + + context.handleResult(null, ImmutableList.of(), result); + + // Difficult to demonstrate that we took no action in a multithreaded world; poll for a bit + // will likely be flaky if this logic is broken + assertThat(callLatch.await(500L, TimeUnit.MILLISECONDS), is(false)); + + InProcessTransformResult finishedResult = + StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); + context.handleResult(null, ImmutableList.of(), finishedResult); + // Obtain the value via blocking call + assertThat(callLatch.await(1, TimeUnit.SECONDS), is(true)); + } + + @Test + public void callAfterOutputMustHaveBeenProducedAlreadyAfterCallsImmediately() throws Exception { + InProcessTransformResult finishedResult = + StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); + context.handleResult(null, ImmutableList.of(), finishedResult); + + final CountDownLatch callLatch = new CountDownLatch(1); + Runnable callback = + new Runnable() { + @Override + public void run() { + callLatch.countDown(); + } + }; + context.scheduleAfterOutputWouldBeProduced( + downstream, GlobalWindow.INSTANCE, WindowingStrategy.globalDefault(), callback); + assertThat(callLatch.await(1, TimeUnit.SECONDS), is(true)); + } + + @Test + public void extractFiredTimersExtractsTimers() { + InProcessTransformResult holdResult = + StepTransformResult.withHold(created.getProducingTransformInternal(), new Instant(0)) + .build(); + context.handleResult(null, ImmutableList.of(), holdResult); + + String key = "foo"; + TimerData toFire = + TimerData.of(StateNamespaces.global(), new Instant(100L), TimeDomain.EVENT_TIME); + InProcessTransformResult timerResult = + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()) + .withState(CopyOnAccessInMemoryStateInternals.withUnderlying(key, null)) + .withTimerUpdate(TimerUpdate.builder(key).setTimer(toFire).build()) + .build(); + + // haven't added any timers, must be empty + assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); + context.handleResult( + InProcessBundle.keyed(created, key).commit(Instant.now()), + ImmutableList.of(), + timerResult); + + // timer hasn't fired + assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); + + InProcessTransformResult advanceResult = + StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); + // Should cause the downstream timer to fire + context.handleResult(null, ImmutableList.of(), advanceResult); + + Map, Map> fired = context.extractFiredTimers(); + assertThat( + fired, + Matchers.>hasKey(downstream.getProducingTransformInternal())); + Map downstreamFired = + fired.get(downstream.getProducingTransformInternal()); + assertThat(downstreamFired, Matchers.hasKey(key)); + + FiredTimers firedForKey = downstreamFired.get(key); + assertThat(firedForKey.getTimers(TimeDomain.PROCESSING_TIME), emptyIterable()); + assertThat(firedForKey.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), emptyIterable()); + assertThat(firedForKey.getTimers(TimeDomain.EVENT_TIME), contains(toFire)); + + // Don't reextract timers + assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); + } + + @Test + public void createBundleUnkeyedResultUnkeyed() { + CommittedBundle> newBundle = + context + .createBundle(InProcessBundle.unkeyed(created).commit(Instant.now()), downstream) + .commit(Instant.now()); + assertThat(newBundle.isKeyed(), is(false)); + } + + @Test + public void createBundleKeyedResultPropagatesKey() { + CommittedBundle> newBundle = + context + .createBundle(InProcessBundle.keyed(created, "foo").commit(Instant.now()), downstream) + .commit(Instant.now()); + assertThat(newBundle.isKeyed(), is(true)); + assertThat(newBundle.getKey(), Matchers.equalTo("foo")); + } + + @Test + public void createRootBundleUnkeyed() { + assertThat(context.createRootBundle(created).commit(Instant.now()).isKeyed(), is(false)); + } + + @Test + public void createKeyedBundleKeyed() { + CommittedBundle> keyedBundle = + context + .createKeyedBundle( + InProcessBundle.unkeyed(created).commit(Instant.now()), "foo", downstream) + .commit(Instant.now()); + assertThat(keyedBundle.isKeyed(), is(true)); + assertThat(keyedBundle.getKey(), Matchers.equalTo("foo")); + } + + private static class TestBoundedWindow extends BoundedWindow { + private final Instant ts; + + public TestBoundedWindow(Instant ts) { + this.ts = ts; + } + + @Override + public Instant maxTimestamp() { + return ts; + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java index 4cfe782936..16b4eb7d07 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java @@ -24,7 +24,6 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.Mean; @@ -137,7 +136,7 @@ public void getAfterWriteReturnsPaneInWindow() throws Exception { container.write(mapView, ImmutableList.>of(one, two)); Map viewContents = - container.withViews(ImmutableList.>of(mapView)) + container.createReaderForViews(ImmutableList.>of(mapView)) .get(mapView, firstWindow); assertThat(viewContents, hasEntry("one", 1)); assertThat(viewContents, hasEntry("two", 2)); @@ -153,7 +152,7 @@ public void getReturnsLatestPaneInWindow() throws Exception { container.write(mapView, ImmutableList.>of(one, two)); Map viewContents = - container.withViews(ImmutableList.>of(mapView)) + container.createReaderForViews(ImmutableList.>of(mapView)) .get(mapView, secondWindow); assertThat(viewContents, hasEntry("one", 1)); assertThat(viewContents, hasEntry("two", 2)); @@ -164,7 +163,7 @@ public void getReturnsLatestPaneInWindow() throws Exception { container.write(mapView, ImmutableList.>of(three)); Map overwrittenViewContents = - container.withViews(ImmutableList.>of(mapView)) + container.createReaderForViews(ImmutableList.>of(mapView)) .get(mapView, secondWindow); assertThat(overwrittenViewContents, hasEntry("three", 3)); assertThat(overwrittenViewContents.size(), is(1)); @@ -176,15 +175,18 @@ public void getReturnsLatestPaneInWindow() throws Exception { */ @Test public void getBlocksUntilPaneAvailable() throws Exception { - BoundedWindow window = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(1024L); - } - }; + BoundedWindow window = + new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(1024L); + } + }; Future singletonFuture = - getFutureOfView(container.withViews(ImmutableList.>of(singletonView)), - singletonView, window); + getFutureOfView( + container.createReaderForViews(ImmutableList.>of(singletonView)), + singletonView, + window); WindowedValue singletonValue = WindowedValue.of(4.75, new Instant(475L), window, PaneInfo.ON_TIME_AND_ONLY_FIRING); @@ -203,7 +205,7 @@ public Instant maxTimestamp() { } }; SideInputReader newReader = - container.withViews(ImmutableList.>of(singletonView)); + container.createReaderForViews(ImmutableList.>of(singletonView)); Future singletonFuture = getFutureOfView(newReader, singletonView, window); WindowedValue singletonValue = @@ -216,25 +218,31 @@ public Instant maxTimestamp() { @Test public void withPCollectionViewsErrorsForContainsNotInViews() { - PCollectionView>> newView = PCollectionViews.multimapView(pipeline, - WindowingStrategy.globalDefault(), KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); + PCollectionView>> newView = + PCollectionViews.multimapView( + pipeline, + WindowingStrategy.globalDefault(), + KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("with unknown views " + ImmutableList.of(newView).toString()); - container.withViews(ImmutableList.>of(newView)); + container.createReaderForViews(ImmutableList.>of(newView)); } @Test public void withViewsForViewNotInContainerFails() { - PCollectionView>> newView = PCollectionViews.multimapView(pipeline, - WindowingStrategy.globalDefault(), KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); + PCollectionView>> newView = + PCollectionViews.multimapView( + pipeline, + WindowingStrategy.globalDefault(), + KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("unknown views"); thrown.expectMessage(newView.toString()); - container.withViews(ImmutableList.>of(newView)); + container.createReaderForViews(ImmutableList.>of(newView)); } @Test @@ -242,7 +250,7 @@ public void getOnReaderForViewNotInReaderFails() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("unknown view: " + iterableView.toString()); - container.withViews(ImmutableList.>of(mapView)) + container.createReaderForViews(ImmutableList.>of(mapView)) .get(iterableView, GlobalWindow.INSTANCE); } @@ -255,11 +263,11 @@ public void writeForMultipleElementsInDifferentWindowsSucceeds() throws Exceptio PaneInfo.ON_TIME_AND_ONLY_FIRING); container.write(singletonView, ImmutableList.of(firstWindowedValue, secondWindowedValue)); assertThat( - container.withViews(ImmutableList.>of(singletonView)) + container.createReaderForViews(ImmutableList.>of(singletonView)) .get(singletonView, firstWindow), equalTo(2.875)); assertThat( - container.withViews(ImmutableList.>of(singletonView)) + container.createReaderForViews(ImmutableList.>of(singletonView)) .get(singletonView, secondWindow), equalTo(4.125)); } @@ -274,7 +282,7 @@ public void writeForMultipleIdenticalElementsInSameWindowSucceeds() throws Excep container.write(iterableView, ImmutableList.of(firstValue, secondValue)); assertThat( - container.withViews(ImmutableList.>of(iterableView)) + container.createReaderForViews(ImmutableList.>of(iterableView)) .get(iterableView, firstWindow), contains(44, 44)); } @@ -286,11 +294,11 @@ public void writeForElementInMultipleWindowsSucceeds() throws Exception { ImmutableList.of(firstWindow, secondWindow), PaneInfo.ON_TIME_AND_ONLY_FIRING); container.write(singletonView, ImmutableList.of(multiWindowedValue)); assertThat( - container.withViews(ImmutableList.>of(singletonView)) + container.createReaderForViews(ImmutableList.>of(singletonView)) .get(singletonView, firstWindow), equalTo(2.875)); assertThat( - container.withViews(ImmutableList.>of(singletonView)) + container.createReaderForViews(ImmutableList.>of(singletonView)) .get(singletonView, secondWindow), equalTo(2.875)); } @@ -306,7 +314,7 @@ public void finishDoesNotOverwriteWrittenElements() throws Exception { immediatelyInvokeCallback(mapView, secondWindow); Map viewContents = - container.withViews(ImmutableList.>of(mapView)) + container.createReaderForViews(ImmutableList.>of(mapView)) .get(mapView, secondWindow); assertThat(viewContents, hasEntry("one", 1)); @@ -317,8 +325,11 @@ public void finishDoesNotOverwriteWrittenElements() throws Exception { @Test public void finishOnPendingViewsSetsEmptyElements() throws Exception { immediatelyInvokeCallback(mapView, secondWindow); - Future> mapFuture = getFutureOfView( - container.withViews(ImmutableList.>of(mapView)), mapView, secondWindow); + Future> mapFuture = + getFutureOfView( + container.createReaderForViews(ImmutableList.>of(mapView)), + mapView, + secondWindow); assertThat(mapFuture.get().isEmpty(), is(true)); } @@ -329,18 +340,21 @@ public void finishOnPendingViewsSetsEmptyElements() throws Exception { */ private void immediatelyInvokeCallback(PCollectionView view, BoundedWindow window) { doAnswer( - new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object callback = invocation.getArguments()[3]; - Runnable callbackRunnable = (Runnable) callback; - callbackRunnable.run(); - return null; - } - }) + new Answer() { + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + Object callback = invocation.getArguments()[3]; + Runnable callbackRunnable = (Runnable) callback; + callbackRunnable.run(); + return null; + } + }) .when(context) - .callAfterOutputMustHaveBeenProduced(Mockito.eq(view), Mockito.eq(window), - Mockito.eq(view.getWindowingStrategyInternal()), Mockito.any(Runnable.class)); + .scheduleAfterOutputWouldBeProduced( + Mockito.eq(view), + Mockito.eq(window), + Mockito.eq(view.getWindowingStrategyInternal()), + Mockito.any(Runnable.class)); } private Future getFutureOfView(final SideInputReader myReader, diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java index 033f9de204..66430b6a7f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java @@ -26,7 +26,6 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java index ae599bab62..3b928b9077 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java @@ -26,7 +26,6 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java index f139c5648e..a9bbcc8cc5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java index 2f5cd0fb88..2f5bdde6ad 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java @@ -25,7 +25,6 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessEvaluationContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java new file mode 100644 index 0000000000..be3e062fbd --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Tests for {@link WatermarkCallbackExecutor}. + */ +@RunWith(JUnit4.class) +public class WatermarkCallbackExecutorTest { + private WatermarkCallbackExecutor executor = WatermarkCallbackExecutor.create(); + private AppliedPTransform create; + private AppliedPTransform sum; + + @Before + public void setup() { + TestPipeline p = TestPipeline.create(); + PCollection created = p.apply(Create.of(1, 2, 3)); + create = created.getProducingTransformInternal(); + sum = created.apply(Sum.integersGlobally()).getProducingTransformInternal(); + } + + @Test + public void onGuaranteedFiringFiresAfterTrigger() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + executor.callOnGuaranteedFiring( + create, + GlobalWindow.INSTANCE, + WindowingStrategy.globalDefault(), + new CountDownLatchCallback(latch)); + + executor.fireForWatermark(create, BoundedWindow.TIMESTAMP_MAX_VALUE); + assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(true)); + } + + @Test + public void multipleCallbacksShouldFireFires() throws Exception { + CountDownLatch latch = new CountDownLatch(2); + WindowFn windowFn = FixedWindows.of(Duration.standardMinutes(10)); + IntervalWindow window = + new IntervalWindow(new Instant(0L), new Instant(0L).plus(Duration.standardMinutes(10))); + executor.callOnGuaranteedFiring( + create, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); + executor.callOnGuaranteedFiring( + create, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); + + executor.fireForWatermark(create, new Instant(0L).plus(Duration.standardMinutes(10))); + assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(true)); + } + + @Test + public void noCallbacksShouldFire() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + WindowFn windowFn = FixedWindows.of(Duration.standardMinutes(10)); + IntervalWindow window = + new IntervalWindow(new Instant(0L), new Instant(0L).plus(Duration.standardMinutes(10))); + executor.callOnGuaranteedFiring( + create, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); + + executor.fireForWatermark(create, new Instant(0L).plus(Duration.standardMinutes(5))); + assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(false)); + } + + @Test + public void unrelatedStepShouldNotFire() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + WindowFn windowFn = FixedWindows.of(Duration.standardMinutes(10)); + IntervalWindow window = + new IntervalWindow(new Instant(0L), new Instant(0L).plus(Duration.standardMinutes(10))); + executor.callOnGuaranteedFiring( + sum, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); + + executor.fireForWatermark(create, new Instant(0L).plus(Duration.standardMinutes(20))); + assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(false)); + } + + private static class CountDownLatchCallback implements Runnable { + private final CountDownLatch latch; + + public CountDownLatchCallback(CountDownLatch latch) { + this.latch = latch; + } + + @Override + public void run() { + latch.countDown(); + } + } +} From 5104624701a1d05344603ab6081be1be74124ac0 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Wed, 16 Mar 2016 13:28:02 -0700 Subject: [PATCH 269/751] Fix AfterWatermark Early and Late javadoc The docs were reversed - the late trigger is only considered after the watermark has passed the end of the window, and the early trigger only before the watermark has passed the end of the window. --- .../dataflow/sdk/transforms/windowing/AfterWatermark.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index da16db99c6..fac2c2841b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -80,7 +80,7 @@ public static FromEndOfWindow pastEndOfWindow() { public interface AfterWatermarkEarly extends TriggerBuilder { /** * Creates a new {@code Trigger} like the this, except that it fires repeatedly whenever - * the given {@code Trigger} fires before the watermark has passed the end of the window. + * the given {@code Trigger} fires after the watermark has passed the end of the window. */ TriggerBuilder withLateFirings(OnceTrigger lateTrigger); } @@ -91,7 +91,7 @@ public interface AfterWatermarkEarly extends TriggerBui public interface AfterWatermarkLate extends TriggerBuilder { /** * Creates a new {@code Trigger} like the this, except that it fires repeatedly whenever - * the given {@code Trigger} fires after the watermark has passed the end of the window. + * the given {@code Trigger} fires before the watermark has passed the end of the window. */ TriggerBuilder withEarlyFirings(OnceTrigger earlyTrigger); } From c2fe45d3271deff14b2ba3627c287012ea072898 Mon Sep 17 00:00:00 2001 From: Pei He Date: Thu, 10 Mar 2016 14:17:36 -0800 Subject: [PATCH 270/751] [BEAM-80] Enable combiner lifting for combine with contexts --- .../runners/DataflowPipelineTranslator.java | 3 +++ .../cloud/dataflow/sdk/transforms/Combine.java | 18 +++--------------- .../cloud/dataflow/sdk/util/PropertyNames.java | 1 + 3 files changed, 7 insertions(+), 15 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index d0cc4e53d5..0feae957f8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -952,6 +952,9 @@ private void groupByKeyHelper( context.addInput( PropertyNames.SERIALIZED_FN, byteArrayToJsonString(serializeToByteArray(windowingStrategy))); + context.addInput( + PropertyNames.IS_MERGING_WINDOW_FN, + !windowingStrategy.getWindowFn().isNonMerging()); } }); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java index cc0347a124..b8d20e303f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java @@ -1690,21 +1690,9 @@ public List> getSideInputs() { @Override public PCollection> apply(PCollection> input) { - if (fn instanceof RequiresContextInternal) { - return input - .apply(GroupByKey.create(fewKeys)) - .apply(ParDo.of(new DoFn>, KV>>() { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element()); - } - })) - .apply(Combine.groupedValues(fn).withSideInputs(sideInputs)); - } else { - return input - .apply(GroupByKey.create(fewKeys)) - .apply(Combine.groupedValues(fn).withSideInputs(sideInputs)); - } + return input + .apply(GroupByKey.create(fewKeys)) + .apply(Combine.groupedValues(fn).withSideInputs(sideInputs)); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java index 5611fabe28..ec6518976b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java @@ -65,6 +65,7 @@ public class PropertyNames { public static final String INPUTS = "inputs"; public static final String INPUT_CODER = "input_coder"; public static final String IS_GENERATED = "is_generated"; + public static final String IS_MERGING_WINDOW_FN = "is_merging_window_fn"; public static final String IS_PAIR_LIKE = "is_pair_like"; public static final String IS_STREAM_LIKE = "is_stream_like"; public static final String IS_WRAPPER = "is_wrapper"; From 1556b0462bf9c9f2670a218f27d7698af659aa98 Mon Sep 17 00:00:00 2001 From: Pei He Date: Fri, 4 Mar 2016 13:54:34 -0800 Subject: [PATCH 271/751] [BEAM-96] Add composed `CombineFn` builders in `CombineFns` * `compose()` or `composeKeyed()` are used to start composition * `with()` is used to add an input-transformation, a `CombineFn` and an output `TupleTag`. * A non-`CombineFn` initial builder is used to ensure that every composition includes at least one item * Duplicate output tags are not allowed in the same composition --- .../dataflow/sdk/transforms/CombineFns.java | 1100 +++++++++++++++++ .../sdk/transforms/CombineFnsTest.java | 413 +++++++ 2 files changed, 1513 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java new file mode 100644 index 0000000000..656c010d91 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java @@ -0,0 +1,1100 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.CoderRegistry; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.GlobalCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +/** + * Static utility methods that create combine function instances. + */ +public class CombineFns { + + /** + * Returns a {@link ComposeKeyedCombineFnBuilder} to construct a composed + * {@link PerKeyCombineFn}. + * + *

    The same {@link TupleTag} cannot be used in a composition multiple times. + * + *

    Example: + *

    { @code
    +   * PCollection> latencies = ...;
    +   *
    +   * TupleTag maxLatencyTag = new TupleTag();
    +   * TupleTag meanLatencyTag = new TupleTag();
    +   *
    +   * SimpleFunction identityFn =
    +   *     new SimpleFunction() {
    +   *       @Override
    +   *       public Integer apply(Integer input) {
    +   *           return input;
    +   *       }};
    +   * PCollection> maxAndMean = latencies.apply(
    +   *     Combine.perKey(
    +   *         CombineFns.composeKeyed()
    +   *            .with(identityFn, new MaxIntegerFn(), maxLatencyTag)
    +   *            .with(identityFn, new MeanFn(), meanLatencyTag)));
    +   *
    +   * PCollection finalResultCollection = maxAndMean
    +   *     .apply(ParDo.of(
    +   *         new DoFn, T>() {
    +   *           @Override
    +   *           public void processElement(ProcessContext c) throws Exception {
    +   *             KV e = c.element();
    +   *             Integer maxLatency = e.getValue().get(maxLatencyTag);
    +   *             Double meanLatency = e.getValue().get(meanLatencyTag);
    +   *             .... Do Something ....
    +   *             c.output(...some T...);
    +   *           }
    +   *         }));
    +   * } 
    + */ + public static ComposeKeyedCombineFnBuilder composeKeyed() { + return new ComposeKeyedCombineFnBuilder(); + } + + /** + * Returns a {@link ComposeCombineFnBuilder} to construct a composed + * {@link GlobalCombineFn}. + * + *

    The same {@link TupleTag} cannot be used in a composition multiple times. + * + *

    Example: + *

    { @code
    +   * PCollection globalLatencies = ...;
    +   *
    +   * TupleTag maxLatencyTag = new TupleTag();
    +   * TupleTag meanLatencyTag = new TupleTag();
    +   *
    +   * SimpleFunction identityFn =
    +   *     new SimpleFunction() {
    +   *       @Override
    +   *       public Integer apply(Integer input) {
    +   *           return input;
    +   *       }};
    +   * PCollection maxAndMean = globalLatencies.apply(
    +   *     Combine.globally(
    +   *         CombineFns.compose()
    +   *            .with(identityFn, new MaxIntegerFn(), maxLatencyTag)
    +   *            .with(identityFn, new MeanFn(), meanLatencyTag)));
    +   *
    +   * PCollection finalResultCollection = maxAndMean
    +   *     .apply(ParDo.of(
    +   *         new DoFn() {
    +   *           @Override
    +   *           public void processElement(ProcessContext c) throws Exception {
    +   *             CoCombineResult e = c.element();
    +   *             Integer maxLatency = e.get(maxLatencyTag);
    +   *             Double meanLatency = e.get(meanLatencyTag);
    +   *             .... Do Something ....
    +   *             c.output(...some T...);
    +   *           }
    +   *         }));
    +   * } 
    + */ + public static ComposeCombineFnBuilder compose() { + return new ComposeCombineFnBuilder(); + } + + ///////////////////////////////////////////////////////////////////////////// + + /** + * A builder class to construct a composed {@link PerKeyCombineFn}. + */ + public static class ComposeKeyedCombineFnBuilder { + /** + * Returns a {@link ComposedKeyedCombineFn} that can take additional + * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. + * + *

    The {@link ComposedKeyedCombineFn} extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them with the {@code keyedCombineFn}, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public ComposedKeyedCombineFn with( + SimpleFunction extractInputFn, + KeyedCombineFn keyedCombineFn, + TupleTag outputTag) { + return new ComposedKeyedCombineFn() + .with(extractInputFn, keyedCombineFn, outputTag); + } + + /** + * Returns a {@link ComposedKeyedCombineFnWithContext} that can take additional + * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. + * + *

    The {@link ComposedKeyedCombineFnWithContext} extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them with the {@code keyedCombineFnWithContext}, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public ComposedKeyedCombineFnWithContext with( + SimpleFunction extractInputFn, + KeyedCombineFnWithContext keyedCombineFnWithContext, + TupleTag outputTag) { + return new ComposedKeyedCombineFnWithContext() + .with(extractInputFn, keyedCombineFnWithContext, outputTag); + } + + /** + * Returns a {@link ComposedKeyedCombineFn} that can take additional + * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. + */ + public ComposedKeyedCombineFn with( + SimpleFunction extractInputFn, + CombineFn combineFn, + TupleTag outputTag) { + return with(extractInputFn, combineFn.asKeyedFn(), outputTag); + } + + /** + * Returns a {@link ComposedKeyedCombineFnWithContext} that can take additional + * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. + */ + public ComposedKeyedCombineFnWithContext with( + SimpleFunction extractInputFn, + CombineFnWithContext combineFnWithContext, + TupleTag outputTag) { + return with(extractInputFn, combineFnWithContext.asKeyedFn(), outputTag); + } + } + + /** + * A builder class to construct a composed {@link GlobalCombineFn}. + */ + public static class ComposeCombineFnBuilder { + /** + * Returns a {@link ComposedCombineFn} that can take additional + * {@link GlobalCombineFn GlobalCombineFns} and apply them as a single combine function. + * + *

    The {@link ComposedCombineFn} extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them with the {@code combineFn}, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public ComposedCombineFn with( + SimpleFunction extractInputFn, + CombineFn combineFn, + TupleTag outputTag) { + return new ComposedCombineFn() + .with(extractInputFn, combineFn, outputTag); + } + + /** + * Returns a {@link ComposedCombineFnWithContext} that can take additional + * {@link GlobalCombineFn GlobalCombineFns} and apply them as a single combine function. + * + *

    The {@link ComposedCombineFnWithContext} extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them with the {@code combineFnWithContext}, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public ComposedCombineFnWithContext with( + SimpleFunction extractInputFn, + CombineFnWithContext combineFnWithContext, + TupleTag outputTag) { + return new ComposedCombineFnWithContext() + .with(extractInputFn, combineFnWithContext, outputTag); + } + } + + ///////////////////////////////////////////////////////////////////////////// + + /** + * A tuple of outputs produced by a composed combine functions. + * + *

    See {@link #compose()} or {@link #composeKeyed()}) for details. + */ + public static class CoCombineResult implements Serializable { + + private enum NullValue { + INSTANCE; + } + + private final Map, Object> valuesMap; + + /** + * The constructor of {@link CoCombineResult}. + * + *

    Null values should have been filtered out from the {@code valuesMap}. + * {@link TupleTag TupleTags} that associate with null values doesn't exist in the key set of + * {@code valuesMap}. + * + * @throws NullPointerException if any key or value in {@code valuesMap} is null + */ + CoCombineResult(Map, Object> valuesMap) { + ImmutableMap.Builder, Object> builder = ImmutableMap.builder(); + for (Entry, Object> entry : valuesMap.entrySet()) { + if (entry.getValue() != null) { + builder.put(entry); + } else { + builder.put(entry.getKey(), NullValue.INSTANCE); + } + } + this.valuesMap = builder.build(); + } + + /** + * Returns the value represented by the given {@link TupleTag}. + * + *

    It is an error to request a non-exist tuple tag from the {@link CoCombineResult}. + */ + @SuppressWarnings("unchecked") + public V get(TupleTag tag) { + checkArgument( + valuesMap.keySet().contains(tag), "TupleTag " + tag + " is not in the CoCombineResult"); + Object value = valuesMap.get(tag); + if (value == NullValue.INSTANCE) { + return null; + } else { + return (V) value; + } + } + } + + ///////////////////////////////////////////////////////////////////////////// + + /** + * A composed {@link CombineFn} that applies multiple {@link CombineFn CombineFns}. + * + *

    For each {@link CombineFn} it extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public static class ComposedCombineFn extends CombineFn { + + private final List> combineFns; + private final List> extractInputFns; + private final List> outputTags; + private final int combineFnCount; + + private ComposedCombineFn() { + this.extractInputFns = ImmutableList.of(); + this.combineFns = ImmutableList.of(); + this.outputTags = ImmutableList.of(); + this.combineFnCount = 0; + } + + private ComposedCombineFn( + ImmutableList> extractInputFns, + ImmutableList> combineFns, + ImmutableList> outputTags) { + @SuppressWarnings({"unchecked", "rawtypes"}) + List> castedExtractInputFns = (List) extractInputFns; + this.extractInputFns = castedExtractInputFns; + + @SuppressWarnings({"unchecked", "rawtypes"}) + List> castedCombineFns = (List) combineFns; + this.combineFns = castedCombineFns; + + this.outputTags = outputTags; + this.combineFnCount = this.combineFns.size(); + } + + /** + * Returns a {@link ComposedCombineFn} with an additional {@link CombineFn}. + */ + public ComposedCombineFn with( + SimpleFunction extractInputFn, + CombineFn combineFn, + TupleTag outputTag) { + checkUniqueness(outputTags, outputTag); + return new ComposedCombineFn<>( + ImmutableList.>builder() + .addAll(extractInputFns) + .add(extractInputFn) + .build(), + ImmutableList.>builder() + .addAll(combineFns) + .add(combineFn) + .build(), + ImmutableList.>builder() + .addAll(outputTags) + .add(outputTag) + .build()); + } + + /** + * Returns a {@link ComposedCombineFnWithContext} with an additional + * {@link CombineFnWithContext}. + */ + public ComposedCombineFnWithContext with( + SimpleFunction extractInputFn, + CombineFnWithContext combineFn, + TupleTag outputTag) { + checkUniqueness(outputTags, outputTag); + List> fnsWithContext = Lists.newArrayList(); + for (CombineFn fn : combineFns) { + fnsWithContext.add(toFnWithContext(fn)); + } + return new ComposedCombineFnWithContext<>( + ImmutableList.>builder() + .addAll(extractInputFns) + .add(extractInputFn) + .build(), + ImmutableList.>builder() + .addAll(fnsWithContext) + .add(combineFn) + .build(), + ImmutableList.>builder() + .addAll(outputTags) + .add(outputTag) + .build()); + } + + @Override + public Object[] createAccumulator() { + Object[] accumsArray = new Object[combineFnCount]; + for (int i = 0; i < combineFnCount; ++i) { + accumsArray[i] = combineFns.get(i).createAccumulator(); + } + return accumsArray; + } + + @Override + public Object[] addInput(Object[] accumulator, DataT value) { + for (int i = 0; i < combineFnCount; ++i) { + Object input = extractInputFns.get(i).apply(value); + accumulator[i] = combineFns.get(i).addInput(accumulator[i], input); + } + return accumulator; + } + + @Override + public Object[] mergeAccumulators(Iterable accumulators) { + Iterator iter = accumulators.iterator(); + if (!iter.hasNext()) { + return createAccumulator(); + } else { + // Reuses the first accumulator, and overwrites its values. + // It is safe because {@code accum[i]} only depends on + // the i-th component of each accumulator. + Object[] accum = iter.next(); + for (int i = 0; i < combineFnCount; ++i) { + accum[i] = combineFns.get(i).mergeAccumulators(new ProjectionIterable(accumulators, i)); + } + return accum; + } + } + + @Override + public CoCombineResult extractOutput(Object[] accumulator) { + Map, Object> valuesMap = Maps.newHashMap(); + for (int i = 0; i < combineFnCount; ++i) { + valuesMap.put( + outputTags.get(i), + combineFns.get(i).extractOutput(accumulator[i])); + } + return new CoCombineResult(valuesMap); + } + + @Override + public Object[] compact(Object[] accumulator) { + for (int i = 0; i < combineFnCount; ++i) { + accumulator[i] = combineFns.get(i).compact(accumulator[i]); + } + return accumulator; + } + + @Override + public Coder getAccumulatorCoder(CoderRegistry registry, Coder dataCoder) + throws CannotProvideCoderException { + List> coders = Lists.newArrayList(); + for (int i = 0; i < combineFnCount; ++i) { + Coder inputCoder = + registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); + coders.add(combineFns.get(i).getAccumulatorCoder(registry, inputCoder)); + } + return new ComposedAccumulatorCoder(coders); + } + } + + /** + * A composed {@link CombineFnWithContext} that applies multiple + * {@link CombineFnWithContext CombineFnWithContexts}. + * + *

    For each {@link CombineFnWithContext} it extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public static class ComposedCombineFnWithContext + extends CombineFnWithContext { + + private final List> extractInputFns; + private final List> combineFnWithContexts; + private final List> outputTags; + private final int combineFnCount; + + private ComposedCombineFnWithContext() { + this.extractInputFns = ImmutableList.of(); + this.combineFnWithContexts = ImmutableList.of(); + this.outputTags = ImmutableList.of(); + this.combineFnCount = 0; + } + + private ComposedCombineFnWithContext( + ImmutableList> extractInputFns, + ImmutableList> combineFnWithContexts, + ImmutableList> outputTags) { + @SuppressWarnings({"unchecked", "rawtypes"}) + List> castedExtractInputFns = + (List) extractInputFns; + this.extractInputFns = castedExtractInputFns; + + @SuppressWarnings({"rawtypes", "unchecked"}) + List> castedCombineFnWithContexts + = (List) combineFnWithContexts; + this.combineFnWithContexts = castedCombineFnWithContexts; + + this.outputTags = outputTags; + this.combineFnCount = this.combineFnWithContexts.size(); + } + + /** + * Returns a {@link ComposedCombineFnWithContext} with an additional {@link GlobalCombineFn}. + */ + public ComposedCombineFnWithContext with( + SimpleFunction extractInputFn, + GlobalCombineFn globalCombineFn, + TupleTag outputTag) { + checkUniqueness(outputTags, outputTag); + return new ComposedCombineFnWithContext<>( + ImmutableList.>builder() + .addAll(extractInputFns) + .add(extractInputFn) + .build(), + ImmutableList.>builder() + .addAll(combineFnWithContexts) + .add(toFnWithContext(globalCombineFn)) + .build(), + ImmutableList.>builder() + .addAll(outputTags) + .add(outputTag) + .build()); + } + + @Override + public Object[] createAccumulator(Context c) { + Object[] accumsArray = new Object[combineFnCount]; + for (int i = 0; i < combineFnCount; ++i) { + accumsArray[i] = combineFnWithContexts.get(i).createAccumulator(c); + } + return accumsArray; + } + + @Override + public Object[] addInput(Object[] accumulator, DataT value, Context c) { + for (int i = 0; i < combineFnCount; ++i) { + Object input = extractInputFns.get(i).apply(value); + accumulator[i] = combineFnWithContexts.get(i).addInput(accumulator[i], input, c); + } + return accumulator; + } + + @Override + public Object[] mergeAccumulators(Iterable accumulators, Context c) { + Iterator iter = accumulators.iterator(); + if (!iter.hasNext()) { + return createAccumulator(c); + } else { + // Reuses the first accumulator, and overwrites its values. + // It is safe because {@code accum[i]} only depends on + // the i-th component of each accumulator. + Object[] accum = iter.next(); + for (int i = 0; i < combineFnCount; ++i) { + accum[i] = combineFnWithContexts.get(i).mergeAccumulators( + new ProjectionIterable(accumulators, i), c); + } + return accum; + } + } + + @Override + public CoCombineResult extractOutput(Object[] accumulator, Context c) { + Map, Object> valuesMap = Maps.newHashMap(); + for (int i = 0; i < combineFnCount; ++i) { + valuesMap.put( + outputTags.get(i), + combineFnWithContexts.get(i).extractOutput(accumulator[i], c)); + } + return new CoCombineResult(valuesMap); + } + + @Override + public Object[] compact(Object[] accumulator, Context c) { + for (int i = 0; i < combineFnCount; ++i) { + accumulator[i] = combineFnWithContexts.get(i).compact(accumulator[i], c); + } + return accumulator; + } + + @Override + public Coder getAccumulatorCoder(CoderRegistry registry, Coder dataCoder) + throws CannotProvideCoderException { + List> coders = Lists.newArrayList(); + for (int i = 0; i < combineFnCount; ++i) { + Coder inputCoder = + registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); + coders.add(combineFnWithContexts.get(i).getAccumulatorCoder(registry, inputCoder)); + } + return new ComposedAccumulatorCoder(coders); + } + } + + /** + * A composed {@link KeyedCombineFn} that applies multiple {@link KeyedCombineFn KeyedCombineFns}. + * + *

    For each {@link KeyedCombineFn} it extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public static class ComposedKeyedCombineFn + extends KeyedCombineFn { + + private final List> extractInputFns; + private final List> keyedCombineFns; + private final List> outputTags; + private final int combineFnCount; + + private ComposedKeyedCombineFn() { + this.extractInputFns = ImmutableList.of(); + this.keyedCombineFns = ImmutableList.of(); + this.outputTags = ImmutableList.of(); + this.combineFnCount = 0; + } + + private ComposedKeyedCombineFn( + ImmutableList> extractInputFns, + ImmutableList> keyedCombineFns, + ImmutableList> outputTags) { + @SuppressWarnings({"unchecked", "rawtypes"}) + List> castedExtractInputFns = (List) extractInputFns; + this.extractInputFns = castedExtractInputFns; + + @SuppressWarnings({"unchecked", "rawtypes"}) + List> castedKeyedCombineFns = + (List) keyedCombineFns; + this.keyedCombineFns = castedKeyedCombineFns; + this.outputTags = outputTags; + this.combineFnCount = this.keyedCombineFns.size(); + } + + /** + * Returns a {@link ComposedKeyedCombineFn} with an additional {@link KeyedCombineFn}. + */ + public ComposedKeyedCombineFn with( + SimpleFunction extractInputFn, + KeyedCombineFn keyedCombineFn, + TupleTag outputTag) { + checkUniqueness(outputTags, outputTag); + return new ComposedKeyedCombineFn<>( + ImmutableList.>builder() + .addAll(extractInputFns) + .add(extractInputFn) + .build(), + ImmutableList.>builder() + .addAll(keyedCombineFns) + .add(keyedCombineFn) + .build(), + ImmutableList.>builder() + .addAll(outputTags) + .add(outputTag) + .build()); + } + + /** + * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional + * {@link KeyedCombineFnWithContext}. + */ + public ComposedKeyedCombineFnWithContext with( + SimpleFunction extractInputFn, + KeyedCombineFnWithContext keyedCombineFn, + TupleTag outputTag) { + checkUniqueness(outputTags, outputTag); + List> fnsWithContext = + Lists.newArrayList(); + for (KeyedCombineFn fn : keyedCombineFns) { + fnsWithContext.add(toFnWithContext(fn)); + } + return new ComposedKeyedCombineFnWithContext<>( + ImmutableList.>builder() + .addAll(extractInputFns) + .add(extractInputFn) + .build(), + ImmutableList.>builder() + .addAll(fnsWithContext) + .add(keyedCombineFn) + .build(), + ImmutableList.>builder() + .addAll(outputTags) + .add(outputTag) + .build()); + } + + /** + * Returns a {@link ComposedKeyedCombineFn} with an additional {@link CombineFn}. + */ + public ComposedKeyedCombineFn with( + SimpleFunction extractInputFn, + CombineFn keyedCombineFn, + TupleTag outputTag) { + return with(extractInputFn, keyedCombineFn.asKeyedFn(), outputTag); + } + + /** + * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional + * {@link CombineFnWithContext}. + */ + public ComposedKeyedCombineFnWithContext with( + SimpleFunction extractInputFn, + CombineFnWithContext keyedCombineFn, + TupleTag outputTag) { + return with(extractInputFn, keyedCombineFn.asKeyedFn(), outputTag); + } + + @Override + public Object[] createAccumulator(K key) { + Object[] accumsArray = new Object[combineFnCount]; + for (int i = 0; i < combineFnCount; ++i) { + accumsArray[i] = keyedCombineFns.get(i).createAccumulator(key); + } + return accumsArray; + } + + @Override + public Object[] addInput(K key, Object[] accumulator, DataT value) { + for (int i = 0; i < combineFnCount; ++i) { + Object input = extractInputFns.get(i).apply(value); + accumulator[i] = keyedCombineFns.get(i).addInput(key, accumulator[i], input); + } + return accumulator; + } + + @Override + public Object[] mergeAccumulators(K key, final Iterable accumulators) { + Iterator iter = accumulators.iterator(); + if (!iter.hasNext()) { + return createAccumulator(key); + } else { + // Reuses the first accumulator, and overwrites its values. + // It is safe because {@code accum[i]} only depends on + // the i-th component of each accumulator. + Object[] accum = iter.next(); + for (int i = 0; i < combineFnCount; ++i) { + accum[i] = keyedCombineFns.get(i).mergeAccumulators( + key, new ProjectionIterable(accumulators, i)); + } + return accum; + } + } + + @Override + public CoCombineResult extractOutput(K key, Object[] accumulator) { + Map, Object> valuesMap = Maps.newHashMap(); + for (int i = 0; i < combineFnCount; ++i) { + valuesMap.put( + outputTags.get(i), + keyedCombineFns.get(i).extractOutput(key, accumulator[i])); + } + return new CoCombineResult(valuesMap); + } + + @Override + public Object[] compact(K key, Object[] accumulator) { + for (int i = 0; i < combineFnCount; ++i) { + accumulator[i] = keyedCombineFns.get(i).compact(key, accumulator[i]); + } + return accumulator; + } + + @Override + public Coder getAccumulatorCoder( + CoderRegistry registry, Coder keyCoder, Coder dataCoder) + throws CannotProvideCoderException { + List> coders = Lists.newArrayList(); + for (int i = 0; i < combineFnCount; ++i) { + Coder inputCoder = + registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); + coders.add(keyedCombineFns.get(i).getAccumulatorCoder(registry, keyCoder, inputCoder)); + } + return new ComposedAccumulatorCoder(coders); + } + } + + /** + * A composed {@link KeyedCombineFnWithContext} that applies multiple + * {@link KeyedCombineFnWithContext KeyedCombineFnWithContexts}. + * + *

    For each {@link KeyedCombineFnWithContext} it extracts inputs from {@code DataT} with + * the {@code extractInputFn} and combines them, + * and then it outputs each combined value with a {@link TupleTag} to a + * {@link CoCombineResult}. + */ + public static class ComposedKeyedCombineFnWithContext + extends KeyedCombineFnWithContext { + + private final List> extractInputFns; + private final List> keyedCombineFns; + private final List> outputTags; + private final int combineFnCount; + + private ComposedKeyedCombineFnWithContext() { + this.extractInputFns = ImmutableList.of(); + this.keyedCombineFns = ImmutableList.of(); + this.outputTags = ImmutableList.of(); + this.combineFnCount = 0; + } + + private ComposedKeyedCombineFnWithContext( + ImmutableList> extractInputFns, + ImmutableList> keyedCombineFns, + ImmutableList> outputTags) { + @SuppressWarnings({"unchecked", "rawtypes"}) + List> castedExtractInputFns = + (List) extractInputFns; + this.extractInputFns = castedExtractInputFns; + + @SuppressWarnings({"unchecked", "rawtypes"}) + List> castedKeyedCombineFns = + (List) keyedCombineFns; + this.keyedCombineFns = castedKeyedCombineFns; + this.outputTags = outputTags; + this.combineFnCount = this.keyedCombineFns.size(); + } + + /** + * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional + * {@link PerKeyCombineFn}. + */ + public ComposedKeyedCombineFnWithContext with( + SimpleFunction extractInputFn, + PerKeyCombineFn perKeyCombineFn, + TupleTag outputTag) { + checkUniqueness(outputTags, outputTag); + return new ComposedKeyedCombineFnWithContext<>( + ImmutableList.>builder() + .addAll(extractInputFns) + .add(extractInputFn) + .build(), + ImmutableList.>builder() + .addAll(keyedCombineFns) + .add(toFnWithContext(perKeyCombineFn)) + .build(), + ImmutableList.>builder() + .addAll(outputTags) + .add(outputTag) + .build()); + } + + /** + * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional + * {@link GlobalCombineFn}. + */ + public ComposedKeyedCombineFnWithContext with( + SimpleFunction extractInputFn, + GlobalCombineFn perKeyCombineFn, + TupleTag outputTag) { + return with(extractInputFn, perKeyCombineFn.asKeyedFn(), outputTag); + } + + @Override + public Object[] createAccumulator(K key, Context c) { + Object[] accumsArray = new Object[combineFnCount]; + for (int i = 0; i < combineFnCount; ++i) { + accumsArray[i] = keyedCombineFns.get(i).createAccumulator(key, c); + } + return accumsArray; + } + + @Override + public Object[] addInput(K key, Object[] accumulator, DataT value, Context c) { + for (int i = 0; i < combineFnCount; ++i) { + Object input = extractInputFns.get(i).apply(value); + accumulator[i] = keyedCombineFns.get(i).addInput(key, accumulator[i], input, c); + } + return accumulator; + } + + @Override + public Object[] mergeAccumulators(K key, Iterable accumulators, Context c) { + Iterator iter = accumulators.iterator(); + if (!iter.hasNext()) { + return createAccumulator(key, c); + } else { + // Reuses the first accumulator, and overwrites its values. + // It is safe because {@code accum[i]} only depends on + // the i-th component of each accumulator. + Object[] accum = iter.next(); + for (int i = 0; i < combineFnCount; ++i) { + accum[i] = keyedCombineFns.get(i).mergeAccumulators( + key, new ProjectionIterable(accumulators, i), c); + } + return accum; + } + } + + @Override + public CoCombineResult extractOutput(K key, Object[] accumulator, Context c) { + Map, Object> valuesMap = Maps.newHashMap(); + for (int i = 0; i < combineFnCount; ++i) { + valuesMap.put( + outputTags.get(i), + keyedCombineFns.get(i).extractOutput(key, accumulator[i], c)); + } + return new CoCombineResult(valuesMap); + } + + @Override + public Object[] compact(K key, Object[] accumulator, Context c) { + for (int i = 0; i < combineFnCount; ++i) { + accumulator[i] = keyedCombineFns.get(i).compact(key, accumulator[i], c); + } + return accumulator; + } + + @Override + public Coder getAccumulatorCoder( + CoderRegistry registry, Coder keyCoder, Coder dataCoder) + throws CannotProvideCoderException { + List> coders = Lists.newArrayList(); + for (int i = 0; i < combineFnCount; ++i) { + Coder inputCoder = + registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); + coders.add(keyedCombineFns.get(i).getAccumulatorCoder( + registry, keyCoder, inputCoder)); + } + return new ComposedAccumulatorCoder(coders); + } + } + + ///////////////////////////////////////////////////////////////////////////// + + private static class ProjectionIterable implements Iterable { + private final Iterable iterable; + private final int column; + + private ProjectionIterable(Iterable iterable, int column) { + this.iterable = iterable; + this.column = column; + } + + @Override + public Iterator iterator() { + final Iterator iter = iterable.iterator(); + return new Iterator() { + @Override + public boolean hasNext() { + return iter.hasNext(); + } + + @Override + public Object next() { + return iter.next()[column]; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + } + + private static class ComposedAccumulatorCoder extends StandardCoder { + private List> coders; + private int codersCount; + + public ComposedAccumulatorCoder(List> coders) { + this.coders = ImmutableList.copyOf(coders); + this.codersCount = coders.size(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @JsonCreator + public static ComposedAccumulatorCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) + List> components) { + return new ComposedAccumulatorCoder((List) components); + } + + @Override + public void encode(Object[] value, OutputStream outStream, Context context) + throws CoderException, IOException { + checkArgument(value.length == codersCount); + Context nestedContext = context.nested(); + for (int i = 0; i < codersCount; ++i) { + coders.get(i).encode(value[i], outStream, nestedContext); + } + } + + @Override + public Object[] decode(InputStream inStream, Context context) + throws CoderException, IOException { + Object[] ret = new Object[codersCount]; + Context nestedContext = context.nested(); + for (int i = 0; i < codersCount; ++i) { + ret[i] = coders.get(i).decode(inStream, nestedContext); + } + return ret; + } + + @Override + public List> getCoderArguments() { + return coders; + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + for (int i = 0; i < codersCount; ++i) { + coders.get(i).verifyDeterministic(); + } + } + } + + @SuppressWarnings("unchecked") + private static CombineFnWithContext + toFnWithContext(GlobalCombineFn globalCombineFn) { + if (globalCombineFn instanceof CombineFnWithContext) { + return (CombineFnWithContext) globalCombineFn; + } else { + final CombineFn combineFn = + (CombineFn) globalCombineFn; + return new CombineFnWithContext() { + @Override + public AccumT createAccumulator(Context c) { + return combineFn.createAccumulator(); + } + @Override + public AccumT addInput(AccumT accumulator, InputT input, Context c) { + return combineFn.addInput(accumulator, input); + } + @Override + public AccumT mergeAccumulators(Iterable accumulators, Context c) { + return combineFn.mergeAccumulators(accumulators); + } + @Override + public OutputT extractOutput(AccumT accumulator, Context c) { + return combineFn.extractOutput(accumulator); + } + @Override + public AccumT compact(AccumT accumulator, Context c) { + return combineFn.compact(accumulator); + } + @Override + public OutputT defaultValue() { + return combineFn.defaultValue(); + } + @Override + public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) + throws CannotProvideCoderException { + return combineFn.getAccumulatorCoder(registry, inputCoder); + } + @Override + public Coder getDefaultOutputCoder( + CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { + return combineFn.getDefaultOutputCoder(registry, inputCoder); + } + }; + } + } + + private static KeyedCombineFnWithContext + toFnWithContext(PerKeyCombineFn perKeyCombineFn) { + if (perKeyCombineFn instanceof KeyedCombineFnWithContext) { + @SuppressWarnings("unchecked") + KeyedCombineFnWithContext keyedCombineFnWithContext = + (KeyedCombineFnWithContext) perKeyCombineFn; + return keyedCombineFnWithContext; + } else { + @SuppressWarnings("unchecked") + final KeyedCombineFn keyedCombineFn = + (KeyedCombineFn) perKeyCombineFn; + return new KeyedCombineFnWithContext() { + @Override + public AccumT createAccumulator(K key, Context c) { + return keyedCombineFn.createAccumulator(key); + } + @Override + public AccumT addInput(K key, AccumT accumulator, InputT value, Context c) { + return keyedCombineFn.addInput(key, accumulator, value); + } + @Override + public AccumT mergeAccumulators(K key, Iterable accumulators, Context c) { + return keyedCombineFn.mergeAccumulators(key, accumulators); + } + @Override + public OutputT extractOutput(K key, AccumT accumulator, Context c) { + return keyedCombineFn.extractOutput(key, accumulator); + } + @Override + public AccumT compact(K key, AccumT accumulator, Context c) { + return keyedCombineFn.compact(key, accumulator); + } + @Override + public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, + Coder inputCoder) throws CannotProvideCoderException { + return keyedCombineFn.getAccumulatorCoder(registry, keyCoder, inputCoder); + } + @Override + public Coder getDefaultOutputCoder(CoderRegistry registry, Coder keyCoder, + Coder inputCoder) throws CannotProvideCoderException { + return keyedCombineFn.getDefaultOutputCoder(registry, keyCoder, inputCoder); + } + }; + } + } + + private static void checkUniqueness( + List> registeredTags, TupleTag outputTag) { + checkArgument( + !registeredTags.contains(outputTag), + "Cannot compose with tuple tag %s because it is already present in the composition.", + outputTag); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java new file mode 100644 index 0000000000..ad37708677 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java @@ -0,0 +1,413 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms; + +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.NullableCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.RunnableOnService; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Combine.BinaryCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineFns.CoCombineResult; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; +import com.google.cloud.dataflow.sdk.transforms.Min.MinIntegerFn; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matchers; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; + +/** + * Unit tests for {@link CombineFns}. + */ +@RunWith(JUnit4.class) +public class CombineFnsTest { + @Rule public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void testDuplicatedTags() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("it is already present in the composition"); + + TupleTag tag = new TupleTag(); + CombineFns.compose() + .with(new GetIntegerFunction(), new MaxIntegerFn(), tag) + .with(new GetIntegerFunction(), new MinIntegerFn(), tag); + } + + @Test + public void testDuplicatedTagsKeyed() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("it is already present in the composition"); + + TupleTag tag = new TupleTag(); + CombineFns.composeKeyed() + .with(new GetIntegerFunction(), new MaxIntegerFn(), tag) + .with(new GetIntegerFunction(), new MinIntegerFn(), tag); + } + + @Test + public void testDuplicatedTagsWithContext() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("it is already present in the composition"); + + TupleTag tag = new TupleTag(); + CombineFns.compose() + .with( + new GetUserStringFunction(), + new ConcatStringWithContext(null /* view */).forKey("G", StringUtf8Coder.of()), + tag) + .with( + new GetUserStringFunction(), + new ConcatStringWithContext(null /* view */).forKey("G", StringUtf8Coder.of()), + tag); + } + + @Test + public void testDuplicatedTagsWithContextKeyed() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("it is already present in the composition"); + + TupleTag tag = new TupleTag(); + CombineFns.composeKeyed() + .with( + new GetUserStringFunction(), + new ConcatStringWithContext(null /* view */), + tag) + .with( + new GetUserStringFunction(), + new ConcatStringWithContext(null /* view */), + tag); + } + + @Test + @Category(RunnableOnService.class) + public void testComposedCombine() { + Pipeline p = TestPipeline.create(); + p.getCoderRegistry().registerCoder(UserString.class, UserStringCoder.of()); + + PCollection>> perKeyInput = p.apply( + Create.timestamped( + Arrays.asList( + KV.of("a", KV.of(1, UserString.of("1"))), + KV.of("a", KV.of(1, UserString.of("1"))), + KV.of("a", KV.of(4, UserString.of("4"))), + KV.of("b", KV.of(1, UserString.of("1"))), + KV.of("b", KV.of(13, UserString.of("13")))), + Arrays.asList(0L, 4L, 7L, 10L, 16L)) + .withCoder(KvCoder.of( + StringUtf8Coder.of(), + KvCoder.of(BigEndianIntegerCoder.of(), UserStringCoder.of())))); + + TupleTag maxIntTag = new TupleTag(); + TupleTag concatStringTag = new TupleTag(); + PCollection>> combineGlobally = perKeyInput + .apply(Values.>create()) + .apply(Combine.globally(CombineFns.compose() + .with( + new GetIntegerFunction(), + new MaxIntegerFn(), + maxIntTag) + .with( + new GetUserStringFunction(), + new ConcatString(), + concatStringTag))) + .apply(WithKeys.of("global")) + .apply( + "ExtractGloballyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); + + PCollection>> combinePerKey = perKeyInput + .apply(Combine.perKey(CombineFns.composeKeyed() + .with( + new GetIntegerFunction(), + new MaxIntegerFn().asKeyedFn(), + maxIntTag) + .with( + new GetUserStringFunction(), + new ConcatString().asKeyedFn(), + concatStringTag))) + .apply("ExtractPerKeyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); + DataflowAssert.that(combineGlobally).containsInAnyOrder( + KV.of("global", KV.of(13, "111134"))); + DataflowAssert.that(combinePerKey).containsInAnyOrder( + KV.of("a", KV.of(4, "114")), + KV.of("b", KV.of(13, "113"))); + p.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testComposedCombineWithContext() { + Pipeline p = TestPipeline.create(); + p.getCoderRegistry().registerCoder(UserString.class, UserStringCoder.of()); + + PCollectionView view = p + .apply(Create.of("I")) + .apply(View.asSingleton()); + + PCollection>> perKeyInput = p.apply( + Create.timestamped( + Arrays.asList( + KV.of("a", KV.of(1, UserString.of("1"))), + KV.of("a", KV.of(1, UserString.of("1"))), + KV.of("a", KV.of(4, UserString.of("4"))), + KV.of("b", KV.of(1, UserString.of("1"))), + KV.of("b", KV.of(13, UserString.of("13")))), + Arrays.asList(0L, 4L, 7L, 10L, 16L)) + .withCoder(KvCoder.of( + StringUtf8Coder.of(), + KvCoder.of(BigEndianIntegerCoder.of(), UserStringCoder.of())))); + + TupleTag maxIntTag = new TupleTag(); + TupleTag concatStringTag = new TupleTag(); + PCollection>> combineGlobally = perKeyInput + .apply(Values.>create()) + .apply(Combine.globally(CombineFns.compose() + .with( + new GetIntegerFunction(), + new MaxIntegerFn(), + maxIntTag) + .with( + new GetUserStringFunction(), + new ConcatStringWithContext(view).forKey("G", StringUtf8Coder.of()), + concatStringTag)) + .withoutDefaults() + .withSideInputs(ImmutableList.of(view))) + .apply(WithKeys.of("global")) + .apply( + "ExtractGloballyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); + + PCollection>> combinePerKey = perKeyInput + .apply(Combine.perKey(CombineFns.composeKeyed() + .with( + new GetIntegerFunction(), + new MaxIntegerFn().asKeyedFn(), + maxIntTag) + .with( + new GetUserStringFunction(), + new ConcatStringWithContext(view), + concatStringTag)) + .withSideInputs(ImmutableList.of(view))) + .apply("ExtractPerKeyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); + DataflowAssert.that(combineGlobally).containsInAnyOrder( + KV.of("global", KV.of(13, "111134GI"))); + DataflowAssert.that(combinePerKey).containsInAnyOrder( + KV.of("a", KV.of(4, "114Ia")), + KV.of("b", KV.of(13, "113Ib"))); + p.run(); + } + + @Test + @Category(RunnableOnService.class) + public void testComposedCombineNullValues() { + Pipeline p = TestPipeline.create(); + p.getCoderRegistry().registerCoder(UserString.class, NullableCoder.of(UserStringCoder.of())); + p.getCoderRegistry().registerCoder(String.class, NullableCoder.of(StringUtf8Coder.of())); + + PCollection>> perKeyInput = p.apply( + Create.timestamped( + Arrays.asList( + KV.of("a", KV.of(1, UserString.of("1"))), + KV.of("a", KV.of(1, UserString.of("1"))), + KV.of("a", KV.of(4, UserString.of("4"))), + KV.of("b", KV.of(1, UserString.of("1"))), + KV.of("b", KV.of(13, UserString.of("13")))), + Arrays.asList(0L, 4L, 7L, 10L, 16L)) + .withCoder(KvCoder.of( + StringUtf8Coder.of(), + KvCoder.of( + BigEndianIntegerCoder.of(), NullableCoder.of(UserStringCoder.of()))))); + + TupleTag maxIntTag = new TupleTag(); + TupleTag concatStringTag = new TupleTag(); + + PCollection>> combinePerKey = perKeyInput + .apply(Combine.perKey(CombineFns.composeKeyed() + .with( + new GetIntegerFunction(), + new MaxIntegerFn().asKeyedFn(), + maxIntTag) + .with( + new GetUserStringFunction(), + new OutputNullString().asKeyedFn(), + concatStringTag))) + .apply("ExtractPerKeyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); + DataflowAssert.that(combinePerKey).containsInAnyOrder( + KV.of("a", KV.of(4, (String) null)), + KV.of("b", KV.of(13, (String) null))); + p.run(); + } + + private static class UserString implements Serializable { + private String strValue; + + static UserString of(String strValue) { + UserString ret = new UserString(); + ret.strValue = strValue; + return ret; + } + } + + private static class UserStringCoder extends StandardCoder { + public static UserStringCoder of() { + return INSTANCE; + } + + private static final UserStringCoder INSTANCE = new UserStringCoder(); + + @Override + public void encode(UserString value, OutputStream outStream, Context context) + throws CoderException, IOException { + StringUtf8Coder.of().encode(value.strValue, outStream, context); + } + + @Override + public UserString decode(InputStream inStream, Context context) + throws CoderException, IOException { + return UserString.of(StringUtf8Coder.of().decode(inStream, context)); + } + + @Override + public List> getCoderArguments() { + return null; + } + + @Override + public void verifyDeterministic() throws NonDeterministicException {} + } + + private static class GetIntegerFunction + extends SimpleFunction, Integer> { + @Override + public Integer apply(KV input) { + return input.getKey(); + } + } + + private static class GetUserStringFunction + extends SimpleFunction, UserString> { + @Override + public UserString apply(KV input) { + return input.getValue(); + } + } + + private static class ConcatString extends BinaryCombineFn { + @Override + public UserString apply(UserString left, UserString right) { + String retStr = left.strValue + right.strValue; + char[] chars = retStr.toCharArray(); + Arrays.sort(chars); + return UserString.of(new String(chars)); + } + } + + private static class OutputNullString extends BinaryCombineFn { + @Override + public UserString apply(UserString left, UserString right) { + return null; + } + } + + private static class ConcatStringWithContext + extends KeyedCombineFnWithContext { + private final PCollectionView view; + + private ConcatStringWithContext(PCollectionView view) { + this.view = view; + } + + @Override + public UserString createAccumulator(String key, CombineWithContext.Context c) { + return UserString.of(key + c.sideInput(view)); + } + + @Override + public UserString addInput( + String key, UserString accumulator, UserString input, CombineWithContext.Context c) { + assertThat(accumulator.strValue, Matchers.startsWith(key + c.sideInput(view))); + accumulator.strValue += input.strValue; + return accumulator; + } + + @Override + public UserString mergeAccumulators( + String key, Iterable accumulators, CombineWithContext.Context c) { + String keyPrefix = key + c.sideInput(view); + String all = keyPrefix; + for (UserString accumulator : accumulators) { + assertThat(accumulator.strValue, Matchers.startsWith(keyPrefix)); + all += accumulator.strValue.substring(keyPrefix.length()); + accumulator.strValue = "cleared in mergeAccumulators"; + } + return UserString.of(all); + } + + @Override + public UserString extractOutput( + String key, UserString accumulator, CombineWithContext.Context c) { + assertThat(accumulator.strValue, Matchers.startsWith(key + c.sideInput(view))); + char[] chars = accumulator.strValue.toCharArray(); + Arrays.sort(chars); + return UserString.of(new String(chars)); + } + } + + private static class ExtractResultDoFn + extends DoFn, KV>>{ + + private final TupleTag maxIntTag; + private final TupleTag concatStringTag; + + ExtractResultDoFn(TupleTag maxIntTag, TupleTag concatStringTag) { + this.maxIntTag = maxIntTag; + this.concatStringTag = concatStringTag; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + UserString userString = c.element().getValue().get(concatStringTag); + KV value = KV.of( + c.element().getValue().get(maxIntTag), + userString == null ? null : userString.strValue); + c.output(KV.of(c.element().getKey(), value)); + } + } +} From d5a8c75f2cdcd3e3fcd529023d0ac9f682d0fa47 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 26 Feb 2016 17:29:43 -0800 Subject: [PATCH 272/751] Add ExecutorServiceParallelExecutor as an InProcessExecutor This is responsible for scheduling transform evaluations and communicating results back to the evaluation context. The executor handle PTransforms that block arbitarily waiting for additional input. --- .../runners/inprocess/CompletionCallback.java | 33 ++ .../ExecutorServiceParallelExecutor.java | 394 ++++++++++++++++++ .../inprocess/InMemoryWatermarkManager.java | 2 +- .../inprocess/InProcessEvaluationContext.java | 21 +- .../runners/inprocess/InProcessExecutor.java | 46 ++ .../inprocess/InProcessPipelineOptions.java | 7 +- .../inprocess/InProcessPipelineRunner.java | 25 -- .../runners/inprocess/TransformExecutor.java | 114 +++++ .../inprocess/TransformExecutorService.java | 34 ++ .../inprocess/TransformExecutorServices.java | 153 +++++++ .../TransformExecutorServicesTest.java | 134 ++++++ .../inprocess/TransformExecutorTest.java | 312 ++++++++++++++ 12 files changed, 1247 insertions(+), 28 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java new file mode 100644 index 0000000000..2792631560 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; + +/** + * A callback for completing a bundle of input. + */ +interface CompletionCallback { + /** + * Handle a successful result. + */ + void handleResult(CommittedBundle inputBundle, InProcessTransformResult result); + + /** + * Handle a result that terminated abnormally due to the provided {@link Throwable}. + */ + void handleThrowable(CommittedBundle inputBundle, Throwable t); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java new file mode 100644 index 0000000000..ae686f2979 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -0,0 +1,394 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; +import com.google.cloud.dataflow.sdk.util.KeyedWorkItems; +import com.google.cloud.dataflow.sdk.util.TimeDomain; +import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.base.MoreObjects; +import com.google.common.base.Optional; +import com.google.common.collect.ImmutableList; + +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; + +import javax.annotation.Nullable; + +/** + * An {@link InProcessExecutor} that uses an underlying {@link ExecutorService} and + * {@link InProcessEvaluationContext} to execute a {@link Pipeline}. + */ +final class ExecutorServiceParallelExecutor implements InProcessExecutor { + private static final Logger LOG = LoggerFactory.getLogger(ExecutorServiceParallelExecutor.class); + + private final ExecutorService executorService; + + private final Map>> valueToConsumers; + private final Set keyedPValues; + private final TransformEvaluatorRegistry registry; + private final InProcessEvaluationContext evaluationContext; + + private final ConcurrentMap currentEvaluations; + private final ConcurrentMap, Boolean> scheduledExecutors; + + private final Queue allUpdates; + private final BlockingQueue visibleUpdates; + + private final TransformExecutorService parallelExecutorService; + private final CompletionCallback defaultCompletionCallback; + + private Collection> rootNodes; + + public static ExecutorServiceParallelExecutor create( + ExecutorService executorService, + Map>> valueToConsumers, + Set keyedPValues, + TransformEvaluatorRegistry registry, + InProcessEvaluationContext context) { + return new ExecutorServiceParallelExecutor( + executorService, valueToConsumers, keyedPValues, registry, context); + } + + private ExecutorServiceParallelExecutor( + ExecutorService executorService, + Map>> valueToConsumers, + Set keyedPValues, + TransformEvaluatorRegistry registry, + InProcessEvaluationContext context) { + this.executorService = executorService; + this.valueToConsumers = valueToConsumers; + this.keyedPValues = keyedPValues; + this.registry = registry; + this.evaluationContext = context; + + currentEvaluations = new ConcurrentHashMap<>(); + scheduledExecutors = new ConcurrentHashMap<>(); + + this.allUpdates = new ConcurrentLinkedQueue<>(); + this.visibleUpdates = new ArrayBlockingQueue<>(20); + + parallelExecutorService = + TransformExecutorServices.parallel(executorService, scheduledExecutors); + defaultCompletionCallback = new DefaultCompletionCallback(); + } + + @Override + public void start(Collection> roots) { + rootNodes = ImmutableList.copyOf(roots); + Runnable monitorRunnable = new MonitorRunnable(); + executorService.submit(monitorRunnable); + } + + @SuppressWarnings("unchecked") + public void scheduleConsumption( + AppliedPTransform consumer, + @Nullable CommittedBundle bundle, + CompletionCallback onComplete) { + evaluateBundle(consumer, bundle, onComplete); + } + + private void evaluateBundle( + final AppliedPTransform transform, + @Nullable final CommittedBundle bundle, + final CompletionCallback onComplete) { + TransformExecutorService transformExecutor; + if (isKeyed(bundle.getPCollection())) { + final StepAndKey stepAndKey = + StepAndKey.of(transform, bundle == null ? null : bundle.getKey()); + transformExecutor = getSerialExecutorService(stepAndKey); + } else { + transformExecutor = parallelExecutorService; + } + TransformExecutor callable = + TransformExecutor.create( + registry, evaluationContext, bundle, transform, onComplete, transformExecutor); + transformExecutor.schedule(callable); + } + + private boolean isKeyed(PValue pvalue) { + return keyedPValues.contains(pvalue); + } + + private void scheduleConsumers(CommittedBundle bundle) { + for (AppliedPTransform consumer : valueToConsumers.get(bundle.getPCollection())) { + scheduleConsumption(consumer, bundle, defaultCompletionCallback); + } + } + + private TransformExecutorService getSerialExecutorService(StepAndKey stepAndKey) { + if (!currentEvaluations.containsKey(stepAndKey)) { + currentEvaluations.putIfAbsent( + stepAndKey, TransformExecutorServices.serial(executorService, scheduledExecutors)); + } + return currentEvaluations.get(stepAndKey); + } + + @Override + public void awaitCompletion() throws Throwable { + VisibleExecutorUpdate update; + do { + update = visibleUpdates.take(); + if (update.throwable.isPresent()) { + throw update.throwable.get(); + } + } while (!update.isDone()); + executorService.shutdown(); + } + + /** + * The default {@link CompletionCallback}. The default completion callback is used to complete + * transform evaluations that are triggered due to the arrival of elements from an upstream + * transform, or for a source transform. + */ + private class DefaultCompletionCallback implements CompletionCallback { + @Override + public void handleResult(CommittedBundle inputBundle, InProcessTransformResult result) { + Iterable> resultBundles = + evaluationContext.handleResult(inputBundle, Collections.emptyList(), result); + for (CommittedBundle outputBundle : resultBundles) { + allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); + } + } + + @Override + public void handleThrowable(CommittedBundle inputBundle, Throwable t) { + allUpdates.offer(ExecutorUpdate.fromThrowable(t)); + } + } + + /** + * A {@link CompletionCallback} where the completed bundle was produced to deliver some collection + * of {@link TimerData timers}. When the evaluator completes successfully, reports all of the + * timers used to create the input to the {@link InProcessEvaluationContext evaluation context} + * as part of the result. + */ + private class TimerCompletionCallback implements CompletionCallback { + private final Iterable timers; + + private TimerCompletionCallback(Iterable timers) { + this.timers = timers; + } + + @Override + public void handleResult(CommittedBundle inputBundle, InProcessTransformResult result) { + Iterable> resultBundles = + evaluationContext.handleResult(inputBundle, timers, result); + for (CommittedBundle outputBundle : resultBundles) { + allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); + } + } + + @Override + public void handleThrowable(CommittedBundle inputBundle, Throwable t) { + allUpdates.offer(ExecutorUpdate.fromThrowable(t)); + } + } + + /** + * An internal status update on the state of the executor. + * + * Used to signal when the executor should be shut down (due to an exception). + */ + private static class ExecutorUpdate { + private final Optional> bundle; + private final Optional throwable; + + public static ExecutorUpdate fromBundle(CommittedBundle bundle) { + return new ExecutorUpdate(bundle, null); + } + + public static ExecutorUpdate fromThrowable(Throwable t) { + return new ExecutorUpdate(null, t); + } + + private ExecutorUpdate(CommittedBundle producedBundle, Throwable throwable) { + this.bundle = Optional.fromNullable(producedBundle); + this.throwable = Optional.fromNullable(throwable); + } + + public Optional> getBundle() { + return bundle; + } + + public Optional getException() { + return throwable; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(ExecutorUpdate.class) + .add("bundle", bundle) + .add("exception", throwable) + .toString(); + } + } + + /** + * An update of interest to the user. Used in {@link #awaitCompletion} to decide whether to + * return normally or throw an exception. + */ + private static class VisibleExecutorUpdate { + private final Optional throwable; + private final boolean done; + + public static VisibleExecutorUpdate fromThrowable(Throwable e) { + return new VisibleExecutorUpdate(false, e); + } + + public static VisibleExecutorUpdate finished() { + return new VisibleExecutorUpdate(true, null); + } + + private VisibleExecutorUpdate(boolean done, @Nullable Throwable exception) { + this.throwable = Optional.fromNullable(exception); + this.done = done; + } + + public boolean isDone() { + return done; + } + } + + private class MonitorRunnable implements Runnable { + private final String runnableName = + String.format( + "%s$%s-monitor", + evaluationContext.getPipelineOptions().getAppName(), + ExecutorServiceParallelExecutor.class.getSimpleName()); + + @Override + public void run() { + String oldName = Thread.currentThread().getName(); + Thread.currentThread().setName(runnableName); + try { + ExecutorUpdate update = allUpdates.poll(); + if (update != null) { + LOG.debug("Executor Update: {}", update); + if (update.getBundle().isPresent()) { + scheduleConsumers(update.getBundle().get()); + } else if (update.getException().isPresent()) { + visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); + } + } + fireTimers(); + mightNeedMoreWork(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOG.error("Monitor died due to being interrupted"); + while (!visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(e))) { + visibleUpdates.poll(); + } + } catch (Throwable t) { + LOG.error("Monitor thread died due to throwable", t); + while (!visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(t))) { + visibleUpdates.poll(); + } + } finally { + if (!shouldShutdown()) { + // The monitor thread should always be scheduled; but we only need to be scheduled once + executorService.submit(this); + } + Thread.currentThread().setName(oldName); + } + } + + private void fireTimers() throws Exception { + try { + for (Map.Entry, Map> transformTimers : + evaluationContext.extractFiredTimers().entrySet()) { + AppliedPTransform transform = transformTimers.getKey(); + for (Map.Entry keyTimers : transformTimers.getValue().entrySet()) { + for (TimeDomain domain : TimeDomain.values()) { + Collection delivery = keyTimers.getValue().getTimers(domain); + if (delivery.isEmpty()) { + continue; + } + KeyedWorkItem work = + KeyedWorkItems.timersWorkItem(keyTimers.getKey(), delivery); + @SuppressWarnings({"unchecked", "rawtypes"}) + CommittedBundle bundle = + InProcessBundle.>keyed( + (PCollection) transform.getInput(), keyTimers.getKey()) + .add(WindowedValue.valueInEmptyWindows(work)) + .commit(Instant.now()); + scheduleConsumption(transform, bundle, new TimerCompletionCallback(delivery)); + } + } + } + } catch (Exception e) { + LOG.error("Internal Error while delivering timers", e); + throw e; + } + } + + private boolean shouldShutdown() { + if (evaluationContext.isDone()) { + LOG.debug("Pipeline is finished. Shutting down. {}"); + while (!visibleUpdates.offer(VisibleExecutorUpdate.finished())) { + visibleUpdates.poll(); + } + executorService.shutdown(); + return true; + } + return false; + } + + private void mightNeedMoreWork() { + synchronized (scheduledExecutors) { + for (TransformExecutor executor : scheduledExecutors.keySet()) { + Thread thread = executor.getThread(); + if (thread != null) { + switch (thread.getState()) { + case BLOCKED: + case WAITING: + case TERMINATED: + case TIMED_WAITING: + break; + default: + return; + } + } + } + } + // All current TransformExecutors are blocked; add more work from the roots. + for (AppliedPTransform root : rootNodes) { + scheduleConsumption(root, null, defaultCompletionCallback); + } + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 7cf53aafe6..094526d962 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -866,7 +866,7 @@ private void updatePending( * {@link #getWatermarks(AppliedPTransform)}, the output watermark will be equal to * {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. */ - public boolean isDone() { + public boolean allWatermarksAtPositiveInfinity() { for (Map.Entry, TransformWatermarks> watermarksEntry : transformToWatermarks.entrySet()) { Instant endOfTime = THE_END_OF_TIME.get(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 757e9e11d9..2908fba818 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -36,6 +36,7 @@ import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.collect.ImmutableList; @@ -359,6 +360,24 @@ public CounterSet getCounters() { * Returns true if all steps are done. */ public boolean isDone() { - return watermarkManager.isDone(); + if (!options.isShutdownUnboundedProducersWithMaxWatermark() && containsUnboundedPCollection()) { + return false; + } + if (!watermarkManager.allWatermarksAtPositiveInfinity()) { + return false; + } + return true; + } + + private boolean containsUnboundedPCollection() { + for (AppliedPTransform transform : stepNames.keySet()) { + for (PValue value : transform.getInput().expand()) { + if (value instanceof PCollection + && ((PCollection) value).isBounded().equals(IsBounded.UNBOUNDED)) { + return true; + } + } + } + return false; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java new file mode 100644 index 0000000000..7b60bca17d --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; + +import java.util.Collection; + +/** + * An executor that schedules and executes {@link AppliedPTransform AppliedPTransforms} for both + * source and intermediate {@link PTransform PTransforms}. + */ +interface InProcessExecutor { + /** + * Starts this executor. The provided collection is the collection of root transforms to + * initially schedule. + * + * @param rootTransforms + */ + void start(Collection> rootTransforms); + + /** + * Blocks until the job being executed enters a terminal state. A job is completed after all + * root {@link AppliedPTransform AppliedPTransforms} have completed, and all + * {@link CommittedBundle Bundles} have been consumed. Jobs may also terminate abnormally. + * + * @throws Throwable whenever an executor thread throws anything, transfers the throwable to the + * waiting thread and rethrows it + */ + void awaitCompletion() throws Throwable; +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java index 60c8543a2f..27e9a4be6e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java @@ -15,15 +15,20 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.PipelineOptions; /** * Options that can be used to configure the {@link InProcessPipelineRunner}. */ -public interface InProcessPipelineOptions extends PipelineOptions { +public interface InProcessPipelineOptions extends PipelineOptions, ApplicationNameOptions { @Default.InstanceFactory(NanosOffsetClock.Factory.class) Clock getClock(); void setClock(Clock clock); + + boolean isShutdownUnboundedProducersWithMaxWatermark(); + + void setShutdownUnboundedProducersWithMaxWatermark(boolean shutdown); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 7a268ee5fa..32859dae63 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKey; import com.google.cloud.dataflow.sdk.runners.inprocess.ViewEvaluatorFactory.InProcessCreatePCollectionView; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; @@ -167,28 +166,4 @@ private InProcessPipelineRunner(InProcessPipelineOptions options) { public InProcessPipelineOptions getPipelineOptions() { return options; } - - /** - * An executor that schedules and executes {@link AppliedPTransform AppliedPTransforms} for both - * source and intermediate {@link PTransform PTransforms}. - */ - public static interface InProcessExecutor { - /** - * @param root the root {@link AppliedPTransform} to schedule - */ - void scheduleRoot(AppliedPTransform root); - - /** - * @param consumer the {@link AppliedPTransform} to schedule - * @param bundle the input bundle to the consumer - */ - void scheduleConsumption(AppliedPTransform consumer, CommittedBundle bundle); - - /** - * Blocks until the job being executed enters a terminal state. A job is completed after all - * root {@link AppliedPTransform AppliedPTransforms} have completed, and all - * {@link CommittedBundle Bundles} have been consumed. Jobs may also terminate abnormally. - */ - void awaitCompletion(); - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java new file mode 100644 index 0000000000..d630749387 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.common.base.Throwables; + +import java.util.concurrent.Callable; + +import javax.annotation.Nullable; + +/** + * A {@link Callable} responsible for constructing a {@link TransformEvaluator} from a + * {@link TransformEvaluatorFactory} and evaluating it on some bundle of input, and registering + * the result using a registered {@link CompletionCallback}. + * + *

    A {@link TransformExecutor} that is currently executing also provides access to the thread + * that it is being executed on. + */ +class TransformExecutor implements Callable { + public static TransformExecutor create( + TransformEvaluatorFactory factory, + InProcessEvaluationContext evaluationContext, + CommittedBundle inputBundle, + AppliedPTransform transform, + CompletionCallback completionCallback, + TransformExecutorService transformEvaluationState) { + return new TransformExecutor<>( + factory, + evaluationContext, + inputBundle, + transform, + completionCallback, + transformEvaluationState); + } + + private final TransformEvaluatorFactory evaluatorFactory; + private final InProcessEvaluationContext evaluationContext; + + /** The transform that will be evaluated. */ + private final AppliedPTransform transform; + /** The inputs this {@link TransformExecutor} will deliver to the transform. */ + private final CommittedBundle inputBundle; + + private final CompletionCallback onComplete; + private final TransformExecutorService transformEvaluationState; + + private Thread thread; + + private TransformExecutor( + TransformEvaluatorFactory factory, + InProcessEvaluationContext evaluationContext, + CommittedBundle inputBundle, + AppliedPTransform transform, + CompletionCallback completionCallback, + TransformExecutorService transformEvaluationState) { + this.evaluatorFactory = factory; + this.evaluationContext = evaluationContext; + + this.inputBundle = inputBundle; + this.transform = transform; + + this.onComplete = completionCallback; + + this.transformEvaluationState = transformEvaluationState; + } + + @Override + public InProcessTransformResult call() { + this.thread = Thread.currentThread(); + try { + TransformEvaluator evaluator = + evaluatorFactory.forApplication(transform, inputBundle, evaluationContext); + if (inputBundle != null) { + for (WindowedValue value : inputBundle.getElements()) { + evaluator.processElement(value); + } + } + InProcessTransformResult result = evaluator.finishBundle(); + onComplete.handleResult(inputBundle, result); + return result; + } catch (Throwable t) { + onComplete.handleThrowable(inputBundle, t); + throw Throwables.propagate(t); + } finally { + this.thread = null; + transformEvaluationState.complete(this); + } + } + + /** + * If this {@link TransformExecutor} is currently executing, return the thread it is executing in. + * Otherwise, return null. + */ + @Nullable + public Thread getThread() { + return this.thread; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java new file mode 100644 index 0000000000..3f00da6ebe --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +/** + * Schedules and completes {@link TransformExecutor TransformExecutors}, controlling concurrency as + * appropriate for the {@link StepAndKey} the executor exists for. + */ +interface TransformExecutorService { + /** + * Schedule the provided work to be eventually executed. + */ + void schedule(TransformExecutor work); + + /** + * Finish executing the provided work. This may cause additional + * {@link TransformExecutor TransformExecutors} to be evaluated. + */ + void complete(TransformExecutor completed); +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java new file mode 100644 index 0000000000..34efdf694e --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java @@ -0,0 +1,153 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.common.base.MoreObjects; + +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Static factory methods for constructing instances of {@link TransformExecutorService}. + */ +final class TransformExecutorServices { + private TransformExecutorServices() { + // Do not instantiate + } + + /** + * Returns an EvaluationState that evaluates {@link TransformExecutor TransformExecutors} in + * parallel. + */ + public static TransformExecutorService parallel( + ExecutorService executor, Map, Boolean> scheduled) { + return new ParallelEvaluationState(executor, scheduled); + } + + /** + * Returns an EvaluationState that evaluates {@link TransformExecutor TransformExecutors} in + * serial. + */ + public static TransformExecutorService serial( + ExecutorService executor, Map, Boolean> scheduled) { + return new SerialEvaluationState(executor, scheduled); + } + + /** + * A {@link TransformExecutorService} with unlimited parallelism. Any {@link TransformExecutor} + * scheduled will be immediately submitted to the {@link ExecutorService}. + * + *

    A principal use of this is for the evaluation of an unkeyed Step. Unkeyed computations are + * processed in parallel. + */ + private static class ParallelEvaluationState implements TransformExecutorService { + private final ExecutorService executor; + private final Map, Boolean> scheduled; + + private ParallelEvaluationState( + ExecutorService executor, Map, Boolean> scheduled) { + this.executor = executor; + this.scheduled = scheduled; + } + + @Override + public void schedule(TransformExecutor work) { + executor.submit(work); + scheduled.put(work, true); + } + + @Override + public void complete(TransformExecutor completed) { + scheduled.remove(completed); + } + } + + /** + * A {@link TransformExecutorService} with a single work queue. Any {@link TransformExecutor} + * scheduled will be placed on the work queue. Only one item of work will be submitted to the + * {@link ExecutorService} at any time. + * + *

    A principal use of this is for the serial evaluation of a (Step, Key) pair. + * Keyed computations are processed serially per step. + */ + private static class SerialEvaluationState implements TransformExecutorService { + private final ExecutorService executor; + private final Map, Boolean> scheduled; + + private AtomicReference> currentlyEvaluating; + private final Queue> workQueue; + + private SerialEvaluationState( + ExecutorService executor, Map, Boolean> scheduled) { + this.scheduled = scheduled; + this.executor = executor; + this.currentlyEvaluating = new AtomicReference<>(); + this.workQueue = new ConcurrentLinkedQueue<>(); + } + + /** + * Schedules the work, adding it to the work queue if there is a bundle currently being + * evaluated and scheduling it immediately otherwise. + */ + @Override + public void schedule(TransformExecutor work) { + workQueue.offer(work); + updateCurrentlyEvaluating(); + } + + @Override + public void complete(TransformExecutor completed) { + if (!currentlyEvaluating.compareAndSet(completed, null)) { + throw new IllegalStateException( + "Finished work " + + completed + + " but could not complete due to unexpected currently executing " + + currentlyEvaluating.get()); + } + scheduled.remove(completed); + updateCurrentlyEvaluating(); + } + + private void updateCurrentlyEvaluating() { + if (currentlyEvaluating.get() == null) { + // Only synchronize if we need to update what's currently evaluating + synchronized (this) { + TransformExecutor newWork = workQueue.poll(); + if (newWork != null) { + if (currentlyEvaluating.compareAndSet(null, newWork)) { + scheduled.put(newWork, true); + executor.submit(newWork); + } else { + workQueue.offer(newWork); + } + } + } + } + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(SerialEvaluationState.class) + .add("currentlyEvaluating", currentlyEvaluating) + .add("workQueue", workQueue) + .toString(); + } + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java new file mode 100644 index 0000000000..2c66dc2c32 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.any; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import com.google.common.util.concurrent.MoreExecutors; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; + +/** + * Tests for {@link TransformExecutorServices}. + */ +@RunWith(JUnit4.class) +public class TransformExecutorServicesTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + private ExecutorService executorService; + private Map, Boolean> scheduled; + + @Before + public void setup() { + executorService = MoreExecutors.newDirectExecutorService(); + scheduled = new ConcurrentHashMap<>(); + } + + @Test + public void parallelScheduleMultipleSchedulesBothImmediately() { + @SuppressWarnings("unchecked") + TransformExecutor first = mock(TransformExecutor.class); + @SuppressWarnings("unchecked") + TransformExecutor second = mock(TransformExecutor.class); + + TransformExecutorService parallel = + TransformExecutorServices.parallel(executorService, scheduled); + parallel.schedule(first); + parallel.schedule(second); + + verify(first).call(); + verify(second).call(); + assertThat( + scheduled, + Matchers.allOf( + Matchers., Boolean>hasEntry(first, true), + Matchers., Boolean>hasEntry(second, true))); + + parallel.complete(first); + assertThat(scheduled, Matchers., Boolean>hasEntry(second, true)); + assertThat( + scheduled, + not( + Matchers., Boolean>hasEntry( + Matchers.>equalTo(first), any(Boolean.class)))); + parallel.complete(second); + assertThat(scheduled.isEmpty(), is(true)); + } + + @Test + public void serialScheduleTwoWaitsForFirstToComplete() { + @SuppressWarnings("unchecked") + TransformExecutor first = mock(TransformExecutor.class); + @SuppressWarnings("unchecked") + TransformExecutor second = mock(TransformExecutor.class); + + TransformExecutorService serial = TransformExecutorServices.serial(executorService, scheduled); + serial.schedule(first); + verify(first).call(); + + serial.schedule(second); + verify(second, never()).call(); + + assertThat(scheduled, Matchers., Boolean>hasEntry(first, true)); + assertThat( + scheduled, + not( + Matchers., Boolean>hasEntry( + Matchers.>equalTo(second), any(Boolean.class)))); + + serial.complete(first); + verify(second).call(); + assertThat(scheduled, Matchers., Boolean>hasEntry(second, true)); + assertThat( + scheduled, + not( + Matchers., Boolean>hasEntry( + Matchers.>equalTo(first), any(Boolean.class)))); + + serial.complete(second); + } + + @Test + public void serialCompleteNotExecutingTaskThrows() { + @SuppressWarnings("unchecked") + TransformExecutor first = mock(TransformExecutor.class); + @SuppressWarnings("unchecked") + TransformExecutor second = mock(TransformExecutor.class); + + TransformExecutorService serial = TransformExecutorServices.serial(executorService, scheduled); + serial.schedule(first); + thrown.expect(IllegalStateException.class); + thrown.expectMessage("unexpected currently executing"); + + serial.complete(second); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java new file mode 100644 index 0000000000..bd6325278a --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -0,0 +1,312 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.util.concurrent.MoreExecutors; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Tests for {@link TransformExecutor}. + */ +@RunWith(JUnit4.class) +public class TransformExecutorTest { + private PCollection created; + private PCollection> downstream; + + private CountDownLatch evaluatorCompleted; + + private RegisteringCompletionCallback completionCallback; + private TransformExecutorService transformEvaluationState; + @Mock private InProcessEvaluationContext evaluationContext; + @Mock private TransformEvaluatorRegistry registry; + private Map, Boolean> scheduled; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + scheduled = new HashMap<>(); + transformEvaluationState = + TransformExecutorServices.parallel(MoreExecutors.newDirectExecutorService(), scheduled); + + evaluatorCompleted = new CountDownLatch(1); + completionCallback = new RegisteringCompletionCallback(evaluatorCompleted); + + TestPipeline p = TestPipeline.create(); + created = p.apply(Create.of("foo", "spam", "third")); + downstream = created.apply(WithKeys.of(3)); + } + + @Test + public void callWithNullInputBundleFinishesBundleAndCompletes() throws Exception { + final InProcessTransformResult result = + StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); + final AtomicBoolean finishCalled = new AtomicBoolean(false); + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception { + throw new IllegalArgumentException("Shouldn't be called"); + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + finishCalled.set(true); + return result; + } + }; + + when(registry.forApplication(created.getProducingTransformInternal(), null, evaluationContext)) + .thenReturn(evaluator); + + TransformExecutor executor = + TransformExecutor.create( + registry, + evaluationContext, + null, + created.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + executor.call(); + + assertThat(finishCalled.get(), is(true)); + assertThat(completionCallback.handledResult, equalTo(result)); + assertThat(completionCallback.handledThrowable, is(nullValue())); + assertThat(scheduled, not(Matchers.>hasKey(executor))); + } + + @Test + public void inputBundleProcessesEachElementFinishesAndCompletes() throws Exception { + final InProcessTransformResult result = + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); + final Collection> elementsProcessed = new ArrayList<>(); + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception { + elementsProcessed.add(element); + return; + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + return result; + } + }; + + WindowedValue foo = WindowedValue.valueInGlobalWindow("foo"); + WindowedValue spam = WindowedValue.valueInGlobalWindow("spam"); + WindowedValue third = WindowedValue.valueInGlobalWindow("third"); + CommittedBundle inputBundle = + InProcessBundle.unkeyed(created).add(foo).add(spam).add(third).commit(Instant.now()); + when( + registry.forApplication( + downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) + .thenReturn(evaluator); + + TransformExecutor executor = + TransformExecutor.create( + registry, + evaluationContext, + inputBundle, + downstream.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + + Executors.newSingleThreadExecutor().submit(executor); + + evaluatorCompleted.await(); + + assertThat(elementsProcessed, containsInAnyOrder(spam, third, foo)); + assertThat(completionCallback.handledResult, equalTo(result)); + assertThat(completionCallback.handledThrowable, is(nullValue())); + assertThat(scheduled, not(Matchers.>hasKey(executor))); + } + + @Test + public void processElementThrowsExceptionCallsback() throws Exception { + final InProcessTransformResult result = + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); + final Exception exception = new Exception(); + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception { + throw exception; + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + return result; + } + }; + + WindowedValue foo = WindowedValue.valueInGlobalWindow("foo"); + CommittedBundle inputBundle = + InProcessBundle.unkeyed(created).add(foo).commit(Instant.now()); + when( + registry.forApplication( + downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) + .thenReturn(evaluator); + + TransformExecutor executor = + TransformExecutor.create( + registry, + evaluationContext, + inputBundle, + downstream.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + Executors.newSingleThreadExecutor().submit(executor); + + evaluatorCompleted.await(); + + assertThat(completionCallback.handledResult, is(nullValue())); + assertThat(completionCallback.handledThrowable, Matchers.equalTo(exception)); + assertThat(scheduled, not(Matchers.>hasKey(executor))); + } + + @Test + public void finishBundleThrowsExceptionCallsback() throws Exception { + final Exception exception = new Exception(); + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception {} + + @Override + public InProcessTransformResult finishBundle() throws Exception { + throw exception; + } + }; + + CommittedBundle inputBundle = InProcessBundle.unkeyed(created).commit(Instant.now()); + when( + registry.forApplication( + downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) + .thenReturn(evaluator); + + TransformExecutor executor = + TransformExecutor.create( + registry, + evaluationContext, + inputBundle, + downstream.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + Executors.newSingleThreadExecutor().submit(executor); + + evaluatorCompleted.await(); + + assertThat(completionCallback.handledResult, is(nullValue())); + assertThat(completionCallback.handledThrowable, Matchers.equalTo(exception)); + assertThat(scheduled, not(Matchers.>hasKey(executor))); + } + + @Test + public void duringCallGetThreadIsNonNull() throws Exception { + final InProcessTransformResult result = + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); + final CountDownLatch testLatch = new CountDownLatch(1); + final CountDownLatch evaluatorLatch = new CountDownLatch(1); + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception { + throw new IllegalArgumentException("Shouldn't be called"); + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + testLatch.countDown(); + evaluatorLatch.await(); + return result; + } + }; + + when(registry.forApplication(created.getProducingTransformInternal(), null, evaluationContext)) + .thenReturn(evaluator); + + TransformExecutor executor = + TransformExecutor.create( + registry, + evaluationContext, + null, + created.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + + Executors.newSingleThreadExecutor().submit(executor); + testLatch.await(); + assertThat(executor.getThread(), not(nullValue())); + + // Finish the execution so everything can get closed down cleanly. + evaluatorLatch.countDown(); + } + + private static class RegisteringCompletionCallback implements CompletionCallback { + private InProcessTransformResult handledResult = null; + private Throwable handledThrowable = null; + private final CountDownLatch onMethod; + + private RegisteringCompletionCallback(CountDownLatch onMethod) { + this.onMethod = onMethod; + } + + @Override + public void handleResult(CommittedBundle inputBundle, InProcessTransformResult result) { + handledResult = result; + onMethod.countDown(); + } + + @Override + public void handleThrowable(CommittedBundle inputBundle, Throwable t) { + handledThrowable = t; + onMethod.countDown(); + } + } +} From 931eb73a19c522663000a8517913e9ab81145e57 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 15 Mar 2016 11:50:38 -0700 Subject: [PATCH 273/751] Close Readers in InProcess Read Evaluators The readers were formerly left open, which prevents release of any resources that should be released. --- .../BoundedReadEvaluatorFactory.java | 49 +++-- .../UnboundedReadEvaluatorFactory.java | 53 +++--- .../BoundedReadEvaluatorFactoryTest.java | 136 +++++++++++++- .../UnboundedReadEvaluatorFactoryTest.java | 168 ++++++++++++++++++ 4 files changed, 366 insertions(+), 40 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java index 2a164c3518..eaea3ed293 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.Read.Bounded; import com.google.cloud.dataflow.sdk.io.Source.Reader; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; @@ -78,8 +80,7 @@ private TransformEvaluator getTransformEvaluator( @SuppressWarnings("unchecked") private Queue> getTransformEvaluatorQueue( final AppliedPTransform, Bounded> transform, - final InProcessEvaluationContext evaluationContext) - throws IOException { + final InProcessEvaluationContext evaluationContext) { // Key by the application and the context the evaluation is occurring in (which call to // Pipeline#run). EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); @@ -101,21 +102,25 @@ private Queue> getTransformEvaluatorQueu return evaluatorQueue; } + /** + * A {@link BoundedReadEvaluator} produces elements from an underlying {@link BoundedSource}, + * discarding all input elements. Within the call to {@link #finishBundle()}, the evaluator + * creates the {@link BoundedReader} and consumes all available input. + * + *

    A {@link BoundedReadEvaluator} should only be created once per {@link BoundedSource}, and + * each evaluator should only be called once per evaluation of the pipeline. Otherwise, the source + * may produce duplicate elements. + */ private static class BoundedReadEvaluator implements TransformEvaluator { private final AppliedPTransform, Bounded> transform; private final InProcessEvaluationContext evaluationContext; - private final Reader reader; private boolean contentsRemaining; public BoundedReadEvaluator( AppliedPTransform, Bounded> transform, - InProcessEvaluationContext evaluationContext) - throws IOException { + InProcessEvaluationContext evaluationContext) { this.transform = transform; this.evaluationContext = evaluationContext; - reader = - transform.getTransform().getSource().createReader(evaluationContext.getPipelineOptions()); - contentsRemaining = reader.start(); } @Override @@ -123,17 +128,25 @@ public void processElement(WindowedValue element) {} @Override public InProcessTransformResult finishBundle() throws IOException { - UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); - while (contentsRemaining) { - output.add( - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp())); - contentsRemaining = reader.advance(); + try (final Reader reader = + transform + .getTransform() + .getSource() + .createReader(evaluationContext.getPipelineOptions());) { + contentsRemaining = reader.start(); + UncommittedBundle output = + evaluationContext.createRootBundle(transform.getOutput()); + while (contentsRemaining) { + output.add( + WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp())); + contentsRemaining = reader.advance(); + } + reader.close(); + return StepTransformResult.withHold(transform, BoundedWindow.TIMESTAMP_MAX_VALUE) + .addOutput(output) + .build(); } - return StepTransformResult - .withHold(transform, BoundedWindow.TIMESTAMP_MAX_VALUE) - .addOutput(output) - .build(); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index 97f0e25d38..549afabcc0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -99,6 +99,16 @@ private Queue> getTransformEvaluatorQu return evaluatorQueue; } + /** + * A {@link UnboundedReadEvaluator} produces elements from an underlying {@link UnboundedSource}, + * discarding all input elements. Within the call to {@link #finishBundle()}, the evaluator + * creates the {@link UnboundedReader} and consumes some currently available input. + * + *

    Calls to {@link UnboundedReadEvaluator} are not internally thread-safe, and should only be + * used by a single thread at a time. Each {@link UnboundedReadEvaluator} maintains its own + * checkpoint, and constructs its reader from the current checkpoint in each call to + * {@link #finishBundle()}. + */ private static class UnboundedReadEvaluator implements TransformEvaluator { private static final int ARBITRARY_MAX_ELEMENTS = 10; private final AppliedPTransform, Unbounded> transform; @@ -122,28 +132,29 @@ public void processElement(WindowedValue element) {} @Override public InProcessTransformResult finishBundle() throws IOException { UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); - UnboundedReader reader = - createReader( - transform.getTransform().getSource(), evaluationContext.getPipelineOptions()); - int numElements = 0; - if (reader.start()) { - do { - output.add( - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp())); - numElements++; - } while (numElements < ARBITRARY_MAX_ELEMENTS && reader.advance()); + try (UnboundedReader reader = + createReader( + transform.getTransform().getSource(), evaluationContext.getPipelineOptions());) { + int numElements = 0; + if (reader.start()) { + do { + output.add( + WindowedValue.timestampedValueInGlobalWindow( + reader.getCurrent(), reader.getCurrentTimestamp())); + numElements++; + } while (numElements < ARBITRARY_MAX_ELEMENTS && reader.advance()); + } + checkpointMark = reader.getCheckpointMark(); + checkpointMark.finalizeCheckpoint(); + // TODO: When exercising create initial splits, make this the minimum watermark across all + // existing readers + StepTransformResult result = + StepTransformResult.withHold(transform, reader.getWatermark()) + .addOutput(output) + .build(); + evaluatorQueue.offer(this); + return result; } - checkpointMark = reader.getCheckpointMark(); - checkpointMark.finalizeCheckpoint(); - // TODO: When exercising create initial splits, make this the minimum watermark across all - // existing readers - StepTransformResult result = - StepTransformResult.withHold(transform, reader.getWatermark()) - .addOutput(output) - .build(); - evaluatorQueue.offer(this); - return result; } private UnboundedReader createReader( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java index 43955149ee..e641dd6181 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java @@ -18,24 +18,39 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Read.Bounded; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableList; +import org.joda.time.Instant; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.Mock; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; /** * Tests for {@link BoundedReadEvaluatorFactory}. @@ -45,7 +60,7 @@ public class BoundedReadEvaluatorFactoryTest { private BoundedSource source; private PCollection longs; private TransformEvaluatorFactory factory; - private InProcessEvaluationContext context; + @Mock private InProcessEvaluationContext context; @Before public void setup() { @@ -146,6 +161,125 @@ public void boundedSourceEvaluatorSimultaneousEvaluations() throws Exception { gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); } + @Test + public void boundedSourceEvaluatorClosesReader() throws Exception { + TestSource source = new TestSource<>(BigEndianLongCoder.of(), 1L, 2L, 3L); + + TestPipeline p = TestPipeline.create(); + PCollection pcollection = p.apply(Read.from(source)); + AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + + UncommittedBundle output = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(pcollection)).thenReturn(output); + + TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); + evaluator.finishBundle(); + CommittedBundle committed = output.commit(Instant.now()); + assertThat(committed.getElements(), containsInAnyOrder(gw(2L), gw(3L), gw(1L))); + assertThat(TestSource.readerClosed, is(true)); + } + + @Test + public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { + TestSource source = new TestSource<>(BigEndianLongCoder.of()); + + TestPipeline p = TestPipeline.create(); + PCollection pcollection = p.apply(Read.from(source)); + AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + + UncommittedBundle output = InProcessBundle.unkeyed(longs); + when(context.createRootBundle(pcollection)).thenReturn(output); + + TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); + evaluator.finishBundle(); + CommittedBundle committed = output.commit(Instant.now()); + assertThat(committed.getElements(), emptyIterable()); + assertThat(TestSource.readerClosed, is(true)); + } + + private static class TestSource extends BoundedSource { + private static boolean readerClosed; + private final Coder coder; + private final T[] elems; + + public TestSource(Coder coder, T... elems) { + this.elems = elems; + this.coder = coder; + readerClosed = false; + } + + @Override + public List> splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + return ImmutableList.of(this); + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + return 0; + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return false; + } + + @Override + public BoundedSource.BoundedReader createReader(PipelineOptions options) throws IOException { + return new TestReader<>(this, elems); + } + + @Override + public void validate() { + } + + @Override + public Coder getDefaultOutputCoder() { + return coder; + } + } + + private static class TestReader extends BoundedReader { + private final BoundedSource source; + private final List elems; + private int index; + + public TestReader(BoundedSource source, T... elems) { + this.source = source; + this.elems = Arrays.asList(elems); + this.index = -1; + } + + @Override + public BoundedSource getCurrentSource() { + return source; + } + + @Override + public boolean start() throws IOException { + return advance(); + } + + @Override + public boolean advance() throws IOException { + if (elems.size() > index + 1) { + index++; + return true; + } + return false; + } + + @Override + public T getCurrent() throws NoSuchElementException { + return elems.get(index); + } + + @Override + public void close() throws IOException { + TestSource.readerClosed = true; + } + } + private static WindowedValue gw(Long elem) { return WindowedValue.valueInGlobalWindow(elem); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java index a9bbcc8cc5..20a7d60bce 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java @@ -18,20 +18,30 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.io.CountingSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableList; import org.hamcrest.Matchers; import org.joda.time.DateTime; @@ -41,6 +51,15 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; + +import javax.annotation.Nullable; /** * Tests for {@link UnboundedReadEvaluatorFactory}. */ @@ -111,6 +130,41 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleSequentialCalls() t tgw(15L), tgw(13L), tgw(10L))); } + @Test + public void boundedSourceEvaluatorClosesReader() throws Exception { + TestUnboundedSource source = + new TestUnboundedSource<>(BigEndianLongCoder.of(), 1L, 2L, 3L); + + TestPipeline p = TestPipeline.create(); + PCollection pcollection = p.apply(Read.from(source)); + AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + + when(context.createRootBundle(pcollection)).thenReturn(output); + + TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); + evaluator.finishBundle(); + CommittedBundle committed = output.commit(Instant.now()); + assertThat(ImmutableList.copyOf(committed.getElements()), hasSize(3)); + assertThat(TestUnboundedSource.readerClosedCount, equalTo(1)); + } + + @Test + public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { + TestUnboundedSource source = new TestUnboundedSource<>(BigEndianLongCoder.of()); + + TestPipeline p = TestPipeline.create(); + PCollection pcollection = p.apply(Read.from(source)); + AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + + when(context.createRootBundle(pcollection)).thenReturn(output); + + TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); + evaluator.finishBundle(); + CommittedBundle committed = output.commit(Instant.now()); + assertThat(committed.getElements(), emptyIterable()); + assertThat(TestUnboundedSource.readerClosedCount, equalTo(1)); + } + // TODO: Once the source is split into multiple sources before evaluating, this test will have to // be updated. /** @@ -156,4 +210,118 @@ public Instant apply(Long input) { return new Instant(input); } } + + private static class TestUnboundedSource extends UnboundedSource { + static int readerClosedCount; + private final Coder coder; + private final List elems; + + public TestUnboundedSource(Coder coder, T... elems) { + readerClosedCount = 0; + this.coder = coder; + this.elems = Arrays.asList(elems); + } + + @Override + public List> generateInitialSplits( + int desiredNumSplits, PipelineOptions options) throws Exception { + return ImmutableList.of(this); + } + + @Override + public UnboundedSource.UnboundedReader createReader( + PipelineOptions options, TestCheckpointMark checkpointMark) { + return new TestUnboundedReader(elems); + } + + @Override + @Nullable + public Coder getCheckpointMarkCoder() { + return new TestCheckpointMark.Coder(); + } + + @Override + public void validate() {} + + @Override + public Coder getDefaultOutputCoder() { + return coder; + } + + private class TestUnboundedReader extends UnboundedReader { + private final List elems; + private int index; + + public TestUnboundedReader(List elems) { + this.elems = elems; + this.index = -1; + } + + @Override + public boolean start() throws IOException { + return advance(); + } + + @Override + public boolean advance() throws IOException { + if (index + 1 < elems.size()) { + index++; + return true; + } + return false; + } + + @Override + public Instant getWatermark() { + return Instant.now(); + } + + @Override + public CheckpointMark getCheckpointMark() { + return new TestCheckpointMark(); + } + + @Override + public UnboundedSource getCurrentSource() { + TestUnboundedSource source = TestUnboundedSource.this; + return source; + } + + @Override + public T getCurrent() throws NoSuchElementException { + return elems.get(index); + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + return Instant.now(); + } + + @Override + public void close() throws IOException { + readerClosedCount++; + } + } + } + + private static class TestCheckpointMark implements CheckpointMark { + @Override + public void finalizeCheckpoint() throws IOException {} + + public static class Coder extends AtomicCoder { + @Override + public void encode( + TestCheckpointMark value, + OutputStream outStream, + com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException {} + + @Override + public TestCheckpointMark decode( + InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + return new TestCheckpointMark(); + } + } + } } From 2d3ad38ffc3f12bfdf77d9d1d58fddfb6e740dd0 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 18 Mar 2016 16:20:56 -0700 Subject: [PATCH 274/751] Look up a runner if it is not registered If a fully qualified runner is passed as the value of --runner, and it is not present within the map of registered runners, attempts to look up the runner using Class#forName, and uses the result class if the result class is an instance of PipelineRunner. This brings the behavior in line with the described behavior in PipelineOptions. --- .../sdk/options/PipelineOptionsFactory.java | 31 +++++++++++++--- .../options/PipelineOptionsFactoryTest.java | 36 +++++++++++++++++++ 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java index e77b89f9a4..48cff6df93 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.options; +import static com.google.common.base.Preconditions.checkArgument; + import com.google.cloud.dataflow.sdk.options.Validation.Required; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; @@ -1391,7 +1393,10 @@ private static ListMultimap parseCommandLine( * split up each string on ','. * *

    We special case the "runner" option. It is mapped to the class of the {@link PipelineRunner} - * based off of the {@link PipelineRunner}s simple class name or fully qualified class name. + * based off of the {@link PipelineRunner PipelineRunners} simple class name. If the provided + * runner name is not registered via a {@link PipelineRunnerRegistrar}, we attempt to obtain the + * class that the name represents using {@link Class#forName(String)} and use the result class if + * it subclasses {@link PipelineRunner}. * *

    If strict parsing is enabled, unknown options or options that cannot be converted to * the expected java type using an {@link ObjectMapper} will be ignored. @@ -1442,10 +1447,26 @@ public boolean apply(@Nullable String input) { JavaType type = MAPPER.getTypeFactory().constructType(method.getGenericReturnType()); if ("runner".equals(entry.getKey())) { String runner = Iterables.getOnlyElement(entry.getValue()); - Preconditions.checkArgument(SUPPORTED_PIPELINE_RUNNERS.containsKey(runner), - "Unknown 'runner' specified '%s', supported pipeline runners %s", - runner, Sets.newTreeSet(SUPPORTED_PIPELINE_RUNNERS.keySet())); - convertedOptions.put("runner", SUPPORTED_PIPELINE_RUNNERS.get(runner)); + if (SUPPORTED_PIPELINE_RUNNERS.containsKey(runner)) { + convertedOptions.put("runner", SUPPORTED_PIPELINE_RUNNERS.get(runner)); + } else { + try { + Class runnerClass = Class.forName(runner); + checkArgument( + PipelineRunner.class.isAssignableFrom(runnerClass), + "Class '%s' does not implement PipelineRunner. Supported pipeline runners %s", + runner, + Sets.newTreeSet(SUPPORTED_PIPELINE_RUNNERS.keySet())); + convertedOptions.put("runner", runnerClass); + } catch (ClassNotFoundException e) { + String msg = + String.format( + "Unknown 'runner' specified '%s', supported pipeline runners %s", + runner, + Sets.newTreeSet(SUPPORTED_PIPELINE_RUNNERS.keySet())); + throw new IllegalArgumentException(msg, e); + } + } } else if ((returnType.isArray() && (SIMPLE_TYPES.contains(returnType.getComponentType()) || returnType.getComponentType().isEnum())) || Collection.class.isAssignableFrom(returnType)) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java index e687f27989..045a8ad0f2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java @@ -25,8 +25,12 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.PipelineResult; import com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.RestoreSystemProperties; import com.google.common.collect.ArrayListMultimap; @@ -824,6 +828,14 @@ public void testSettingRunner() { assertEquals(BlockingDataflowPipelineRunner.class, options.getRunner()); } + @Test + public void testSettingRunnerFullName() { + String[] args = + new String[] {String.format("--runner=%s", DataflowPipelineRunner.class.getName())}; + PipelineOptions opts = PipelineOptionsFactory.fromArgs(args).create(); + assertEquals(opts.getRunner(), DataflowPipelineRunner.class); + } + @Test public void testSettingUnknownRunner() { String[] args = new String[] {"--runner=UnknownRunner"}; @@ -834,6 +846,30 @@ public void testSettingUnknownRunner() { PipelineOptionsFactory.fromArgs(args).create(); } + private static class ExampleTestRunner extends PipelineRunner { + @Override + public PipelineResult run(Pipeline pipeline) { + return null; + } + } + + @Test + public void testSettingRunnerCanonicalClassNameNotInSupportedExists() { + String[] args = new String[] {String.format("--runner=%s", ExampleTestRunner.class.getName())}; + PipelineOptions opts = PipelineOptionsFactory.fromArgs(args).create(); + assertEquals(opts.getRunner(), ExampleTestRunner.class); + } + + @Test + public void testSettingRunnerCanonicalClassNameNotInSupportedNotPipelineRunner() { + String[] args = new String[] {"--runner=java.lang.String"}; + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("does not implement PipelineRunner"); + expectedException.expectMessage("java.lang.String"); + + PipelineOptionsFactory.fromArgs(args).create(); + } + @Test public void testUsingArgumentWithUnknownPropertyIsNotAllowed() { String[] args = new String[] {"--unknownProperty=value"}; From 30f8f6b30fbcb083dd5617160c6af10a3dc4f3d0 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 7 Mar 2016 13:47:30 -0800 Subject: [PATCH 275/751] Filter Synthetic Methods in PipelineOptionsFactory --- .../dataflow/sdk/options/PipelineOptions.java | 3 +- .../sdk/options/PipelineOptionsFactory.java | 41 ++++++--- .../PipelineOptionsFactoryJava8Test.java | 90 +++++++++++++++++++ 3 files changed, 122 insertions(+), 12 deletions(-) create mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java index 923033d5da..8ff1fa9783 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java @@ -137,7 +137,8 @@ * *

    {@link Default @Default} represents a set of annotations that can be used to annotate getter * properties on {@link PipelineOptions} with information representing the default value to be - * returned if no value is specified. + * returned if no value is specified. Any default implementation (using the {@code default} keyword) + * is ignored. * *

    {@link Hidden @Hidden} hides an option from being listed when {@code --help} * is invoked via {@link PipelineOptionsFactory#fromArgs(String[])}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java index 48cff6df93..4781d1c829 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java @@ -445,13 +445,21 @@ Class getProxyClass() { private static final Map>> SUPPORTED_PIPELINE_RUNNERS; /** Classes that are used as the boundary in the stack trace to find the callers class name. */ - private static final Set PIPELINE_OPTIONS_FACTORY_CLASSES = ImmutableSet.of( - PipelineOptionsFactory.class.getName(), - Builder.class.getName()); + private static final Set PIPELINE_OPTIONS_FACTORY_CLASSES = + ImmutableSet.of(PipelineOptionsFactory.class.getName(), Builder.class.getName()); /** Methods that are ignored when validating the proxy class. */ private static final Set IGNORED_METHODS; + /** A predicate that checks if a method is synthetic via {@link Method#isSynthetic()}. */ + private static final Predicate NOT_SYNTHETIC_PREDICATE = + new Predicate() { + @Override + public boolean apply(Method input) { + return !input.isSynthetic(); + } + }; + /** The set of options that have been registered and visible to the user. */ private static final Set> REGISTERED_OPTIONS = Sets.newConcurrentHashSet(); @@ -664,7 +672,9 @@ public static void printHelp(PrintStream out, Class i Preconditions.checkNotNull(iface); validateWellFormed(iface, REGISTERED_OPTIONS); - Iterable methods = ReflectHelpers.getClosureOfMethodsOnInterface(iface); + Iterable methods = + Iterables.filter( + ReflectHelpers.getClosureOfMethodsOnInterface(iface), NOT_SYNTHETIC_PREDICATE); ListMultimap, Method> ifaceToMethods = ArrayListMultimap.create(); for (Method method : methods) { // Process only methods that are not marked as hidden. @@ -878,7 +888,8 @@ private static List getPropertyDescriptors(Class beanClas throws IntrospectionException { // The sorting is important to make this method stable. SortedSet methods = Sets.newTreeSet(MethodComparator.INSTANCE); - methods.addAll(Arrays.asList(beanClass.getMethods())); + methods.addAll( + Collections2.filter(Arrays.asList(beanClass.getMethods()), NOT_SYNTHETIC_PREDICATE)); SortedMap propertyNamesToGetters = getPropertyNamesToGetters(methods); List descriptors = Lists.newArrayList(); @@ -1019,8 +1030,9 @@ private static List validateClass(Class klass) throws IntrospectionException { Set methods = Sets.newHashSet(IGNORED_METHODS); // Ignore static methods, "equals", "hashCode", "toString" and "as" on the generated class. + // Ignore synthetic methods for (Method method : klass.getMethods()) { - if (Modifier.isStatic(method.getModifiers())) { + if (Modifier.isStatic(method.getModifiers()) || method.isSynthetic()) { methods.add(method); } } @@ -1037,6 +1049,7 @@ private static List validateClass(Class interfaceMethods = FluentIterable .from(ReflectHelpers.getClosureOfMethodsOnInterface(iface)) + .filter(NOT_SYNTHETIC_PREDICATE) .toSortedSet(MethodComparator.INSTANCE); SortedSetMultimap methodNameToMethodMap = TreeMultimap.create(MethodNameComparator.INSTANCE, MethodComparator.INSTANCE); @@ -1061,10 +1074,13 @@ private static List validateClass(Class allInterfaceMethods = FluentIterable - .from(ReflectHelpers.getClosureOfMethodsOnInterfaces(validatedPipelineOptionsInterfaces)) - .append(ReflectHelpers.getClosureOfMethodsOnInterface(iface)) - .toSortedSet(MethodComparator.INSTANCE); + Iterable allInterfaceMethods = + FluentIterable.from( + ReflectHelpers.getClosureOfMethodsOnInterfaces( + validatedPipelineOptionsInterfaces)) + .append(ReflectHelpers.getClosureOfMethodsOnInterface(iface)) + .filter(NOT_SYNTHETIC_PREDICATE) + .toSortedSet(MethodComparator.INSTANCE); SortedSetMultimap methodNameToAllMethodMap = TreeMultimap.create(MethodNameComparator.INSTANCE, MethodComparator.INSTANCE); for (Method method : allInterfaceMethods) { @@ -1148,7 +1164,10 @@ private static List validateClass(Class unknownMethods = new TreeSet<>(MethodComparator.INSTANCE); - unknownMethods.addAll(Sets.difference(Sets.newHashSet(klass.getMethods()), methods)); + unknownMethods.addAll( + Sets.filter( + Sets.difference(Sets.newHashSet(klass.getMethods()), methods), + NOT_SYNTHETIC_PREDICATE)); Preconditions.checkArgument(unknownMethods.isEmpty(), "Methods %s on [%s] do not conform to being bean properties.", FluentIterable.from(unknownMethods).transform(ReflectHelpers.METHOD_FORMATTER), diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java new file mode 100644 index 0000000000..b7e1467436 --- /dev/null +++ b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Java 8 tests for {@link PipelineOptionsFactory}. + */ +@RunWith(JUnit4.class) +public class PipelineOptionsFactoryJava8Test { + @Rule public ExpectedException thrown = ExpectedException.none(); + + private static interface OptionsWithDefaultMethod extends PipelineOptions { + default Number getValue() { + return 1024; + } + + void setValue(Number value); + } + + @Test + public void testDefaultMethodIgnoresDefaultImplementation() { + OptionsWithDefaultMethod optsWithDefault = + PipelineOptionsFactory.as(OptionsWithDefaultMethod.class); + assertThat(optsWithDefault.getValue(), nullValue()); + + optsWithDefault.setValue(12.25); + assertThat(optsWithDefault.getValue(), equalTo(Double.valueOf(12.25))); + } + + private static interface ExtendedOptionsWithDefault extends OptionsWithDefaultMethod {} + + @Test + public void testDefaultMethodInExtendedClassIgnoresDefaultImplementation() { + OptionsWithDefaultMethod extendedOptsWithDefault = + PipelineOptionsFactory.as(ExtendedOptionsWithDefault.class); + assertThat(extendedOptsWithDefault.getValue(), nullValue()); + + extendedOptsWithDefault.setValue(Double.NEGATIVE_INFINITY); + assertThat(extendedOptsWithDefault.getValue(), equalTo(Double.NEGATIVE_INFINITY)); + } + + private static interface Options extends PipelineOptions { + Number getValue(); + + void setValue(Number value); + } + + private static interface SubtypeReturingOptions extends Options { + @Override + Integer getValue(); + void setValue(Integer value); + } + + @Test + public void testReturnTypeConflictThrows() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage( + "Method [getValue] has multiple definitions [public abstract java.lang.Integer " + + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryJava8Test$" + + "SubtypeReturingOptions.getValue(), public abstract java.lang.Number " + + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryJava8Test$Options" + + ".getValue()] with different return types for [" + + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryJava8Test$" + + "SubtypeReturingOptions]."); + PipelineOptionsFactory.as(SubtypeReturingOptions.class); + } +} From 42d1f15854184901c8abf4c85a6698848ed3d105 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 17 Mar 2016 10:22:42 -0700 Subject: [PATCH 276/751] Add DisplayData builder API to SDK This allows generating the display data which will be attached to PTransforms. --- sdk/pom.xml | 7 + .../cloud/dataflow/sdk/transforms/DoFn.java | 13 +- .../dataflow/sdk/transforms/PTransform.java | 14 +- .../cloud/dataflow/sdk/transforms/ParDo.java | 13 + .../sdk/transforms/display/DisplayData.java | 517 ++++++++++++++ .../transforms/display/HasDisplayData.java | 53 ++ .../dataflow/sdk/transforms/DoFnTest.java | 15 + .../sdk/transforms/PTransformTest.java | 41 ++ .../dataflow/sdk/transforms/ParDoTest.java | 23 + .../display/DisplayDataMatchers.java | 98 +++ .../display/DisplayDataMatchersTest.java | 81 +++ .../transforms/display/DisplayDataTest.java | 633 ++++++++++++++++++ .../dataflow/sdk/util/ApiSurfaceTest.java | 3 +- 13 files changed, 1508 insertions(+), 3 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java diff --git a/sdk/pom.xml b/sdk/pom.xml index d7e10a53a8..2639bc13db 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -685,6 +685,13 @@ ${guava.version} + + com.google.guava + guava-testlib + ${guava.version} + test + + com.google.protobuf protobuf-java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java index af06cc8796..5ba9992143 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java @@ -24,6 +24,8 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.WindowingInternals; @@ -69,7 +71,7 @@ * @param the type of the (main) input elements * @param the type of the (main) output elements */ -public abstract class DoFn implements Serializable { +public abstract class DoFn implements Serializable, HasDisplayData { /** * Information accessible to all methods in this {@code DoFn}. @@ -366,6 +368,15 @@ public void startBundle(Context c) throws Exception { public void finishBundle(Context c) throws Exception { } + /** + * {@inheritDoc} + * + *

    By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(DisplayData.Builder builder) { + } ///////////////////////////////////////////////////////////////////////////// diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java index 8a7450997a..d4496b8c74 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java @@ -19,6 +19,8 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.util.StringUtils; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; @@ -168,7 +170,7 @@ * @param the type of the output of this PTransform */ public abstract class PTransform - implements Serializable /* See the note above */ { + implements Serializable /* See the note above */, HasDisplayData { /** * Applies this {@code PTransform} on the given {@code InputT}, and returns its * {@code Output}. @@ -309,4 +311,14 @@ public Coder getDefaultOutputCoder( Coder defaultOutputCoder = (Coder) getDefaultOutputCoder(input); return defaultOutputCoder; } + + /** + * {@inheritDoc} + * + *

    By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(Builder builder) { + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java index 0922767adc..c77ac4447c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; @@ -787,6 +788,18 @@ protected String getKindString() { } } + /** + * {@inheritDoc} + * + *

    {@link ParDo} registers its internal {@link DoFn} as a subcomponent for display metadata. + * {@link DoFn} implementations can register display data by overriding + * {@link DoFn#populateDisplayData}. + */ + @Override + public void populateDisplayData(Builder builder) { + builder.include(fn); + } + public DoFn getFn() { return fn; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java new file mode 100644 index 0000000000..05fa7c7881 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -0,0 +1,517 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import org.apache.avro.reflect.Nullable; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +import java.util.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Static display metadata associated with a pipeline component. Display data is useful for + * pipeline runner UIs and diagnostic dashboards to display details about + * {@link PTransform PTransforms} that make up a pipeline. + * + *

    Components specify their display data by implementing the {@link HasDisplayData} + * interface. + */ +public class DisplayData { + private static final DisplayData EMPTY = new DisplayData(Maps.newHashMap()); + private static final DateTimeFormatter TIMESTAMP_FORMATTER = ISODateTimeFormat.dateTime(); + + private final ImmutableMap entries; + + private DisplayData(Map entries) { + this.entries = ImmutableMap.copyOf(entries); + } + + /** + * Default empty {@link DisplayData} instance. + */ + public static DisplayData none() { + return EMPTY; + } + + /** + * Collect the {@link DisplayData} from a component. This will traverse all subcomponents + * specified via {@link Builder#include} in the given component. Data in this component will be in + * a namespace derived from the component. + */ + public static DisplayData from(HasDisplayData component) { + checkNotNull(component); + return InternalBuilder.forRoot(component).build(); + } + + public Collection items() { + return entries.values(); + } + + public Map asMap() { + return entries; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + boolean isFirstLine = true; + for (Map.Entry entry : entries.entrySet()) { + if (isFirstLine) { + isFirstLine = false; + } else { + builder.append("\n"); + } + + builder.append(entry); + } + + return builder.toString(); + } + + /** + * Utility to build up display metadata from a component and its included + * subcomponents. + */ + public interface Builder { + /** + * Include display metadata from the specified subcomponent. For example, a {@link ParDo} + * transform includes display metadata from the encapsulated {@link DoFn}. + * + * @return A builder instance to continue to build in a fluent-style. + */ + Builder include(HasDisplayData subComponent); + + /** + * Register the given string display metadata. The metadata item will be registered with type + * {@link DisplayData.Type#STRING}, and is identified by the specified key and namespace from + * the current transform or component. + */ + ItemBuilder add(String key, String value); + + /** + * Register the given numeric display metadata. The metadata item will be registered with type + * {@link DisplayData.Type#INTEGER}, and is identified by the specified key and namespace from + * the current transform or component. + */ + ItemBuilder add(String key, long value); + + /** + * Register the given floating point display metadata. The metadata item will be registered with + * type {@link DisplayData.Type#FLOAT}, and is identified by the specified key and namespace + * from the current transform or component. + */ + ItemBuilder add(String key, double value); + + /** + * Register the given timestamp display metadata. The metadata item will be registered with type + * {@link DisplayData.Type#TIMESTAMP}, and is identified by the specified key and namespace from + * the current transform or component. + */ + ItemBuilder add(String key, Instant value); + + /** + * Register the given duration display metadata. The metadata item will be registered with type + * {@link DisplayData.Type#DURATION}, and is identified by the specified key and namespace from + * the current transform or component. + */ + ItemBuilder add(String key, Duration value); + + /** + * Register the given class display metadata. The metadata item will be registered with type + * {@link DisplayData.Type#JAVA_CLASS}, and is identified by the specified key and namespace + * from the current transform or component. + */ + ItemBuilder add(String key, Class value); + } + + /** + * Utility to append optional fields to display metadata, or register additional display metadata + * items. + */ + public interface ItemBuilder extends Builder { + /** + * Add a human-readable label to describe the most-recently added metadata field. + * A label is optional; if unspecified, UIs should display the metadata key to identify the + * display item. + * + *

    Specifying a null value will clear the label if it was previously defined. + */ + ItemBuilder withLabel(@Nullable String label); + + /** + * Add a link URL to the most-recently added display metadata. A link URL is optional and + * can be provided to point the reader to additional details about the metadata. + * + *

    Specifying a null value will clear the URL if it was previously defined. + */ + ItemBuilder withLinkUrl(@Nullable String url); + } + + /** + * A display metadata item. DisplayData items are registered via {@link Builder#add} within + * {@link HasDisplayData#populateDisplayData} implementations. Each metadata item is uniquely + * identified by the specified key and namespace generated from the registering component's + * class name. + */ + public static class Item { + private final String key; + private final String ns; + private final Type type; + private final String value; + private final String shortValue; + private final String label; + private final String url; + + private static Item create(String namespace, String key, Type type, T value) { + FormattedItemValue formatted = type.format(value); + return new Item( + namespace, key, type, formatted.getLongValue(), formatted.getShortValue(), null, null); + } + + private Item( + String namespace, + String key, + Type type, + String value, + String shortValue, + String url, + String label) { + this.ns = namespace; + this.key = key; + this.type = type; + this.value = value; + this.shortValue = shortValue; + this.url = url; + this.label = label; + } + + public String getNamespace() { + return ns; + } + + public String getKey() { + return key; + } + + /** + * Retrieve the {@link DisplayData.Type} of display metadata. All metadata conforms to a + * predefined set of allowed types. + */ + public Type getType() { + return type; + } + + /** + * Retrieve the value of the metadata item. + */ + public String getValue() { + return value; + } + + /** + * Return the optional short value for an item. Types may provide a short-value to displayed + * instead of or in addition to the full {@link Item#value}. + * + *

    Some display data types will not provide a short value, in which case the return value + * will be null. + */ + @Nullable + public String getShortValue() { + return shortValue; + } + + /** + * Retrieve the optional label for an item. The label is a human-readable description of what + * the metadata represents. UIs may choose to display the label instead of the item key. + * + *

    If no label was specified, this will return {@code null}. + */ + @Nullable + public String getLabel() { + return label; + } + + /** + * Retrieve the optional link URL for an item. The URL points to an address where the reader + * can find additional context for the display metadata. + * + *

    If no URL was specified, this will return {@code null}. + */ + @Nullable + public String getUrl() { + return url; + } + + @Override + public String toString() { + return getValue(); + } + + private Item withLabel(String label) { + return new Item(this.ns, this.key, this.type, this.value, this.shortValue, this.url, label); + } + + private Item withUrl(String url) { + return new Item(this.ns, this.key, this.type, this.value, this.shortValue, url, this.label); + } + } + + /** + * Unique identifier for a display metadata item within a component. + * Identifiers are composed of the key they are registered with and a namespace generated from + * the class of the component which registered the item. + * + *

    Display metadata registered with the same key from different components will have different + * namespaces and thus will both be represented in the composed {@link DisplayData}. If a + * single component registers multiple metadata items with the same key, only the most recent + * item will be retained; previous versions are discarded. + */ + public static class Identifier { + private final String ns; + private final String key; + + static Identifier of(Class namespace, String key) { + return new Identifier(namespace.getName(), key); + } + + private Identifier(String ns, String key) { + this.ns = ns; + this.key = key; + } + + public String getNamespace() { + return ns; + } + + public String getKey() { + return key; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Identifier) { + Identifier that = (Identifier) obj; + return Objects.equals(this.ns, that.ns) + && Objects.equals(this.key, that.key); + } + + return false; + } + + @Override + public int hashCode() { + return Objects.hash(ns, key); + } + + @Override + public String toString() { + return String.format("%s:%s", ns, key); + } + } + + /** + * Display metadata type. + */ + enum Type { + STRING { + @Override + FormattedItemValue format(Object value) { + return new FormattedItemValue((String) value); + } + }, + INTEGER { + @Override + FormattedItemValue format(Object value) { + return new FormattedItemValue(Long.toString((long) value)); + } + }, + FLOAT { + @Override + FormattedItemValue format(Object value) { + return new FormattedItemValue(Double.toString((Double) value)); + } + }, + TIMESTAMP() { + @Override + FormattedItemValue format(Object value) { + return new FormattedItemValue((TIMESTAMP_FORMATTER.print((Instant) value))); + } + }, + DURATION { + @Override + FormattedItemValue format(Object value) { + return new FormattedItemValue(Long.toString(((Duration) value).getMillis())); + } + }, + JAVA_CLASS { + @Override + FormattedItemValue format(Object value) { + Class clazz = (Class) value; + return new FormattedItemValue(clazz.getName(), clazz.getSimpleName()); + } + }; + + /** + * Format the display metadata value into a long string representation, and optionally + * a shorter representation for display. + * + *

    Internal-only. Value objects can be safely cast to the expected Java type. + */ + abstract FormattedItemValue format(Object value); + } + + private static class FormattedItemValue { + private final String shortValue; + private final String longValue; + + private FormattedItemValue(String longValue) { + this(longValue, null); + } + + private FormattedItemValue(String longValue, String shortValue) { + this.longValue = longValue; + this.shortValue = shortValue; + } + + private String getLongValue () { + return this.longValue; + } + + private String getShortValue() { + return this.shortValue; + } + } + + private static class InternalBuilder implements ItemBuilder { + private final Map entries; + private final Set visited; + + private Class latestNs; + private Item latestItem; + private Identifier latestIdentifier; + + private InternalBuilder() { + this.entries = Maps.newHashMap(); + this.visited = Sets.newIdentityHashSet(); + } + + private static InternalBuilder forRoot(HasDisplayData instance) { + InternalBuilder builder = new InternalBuilder(); + builder.include(instance); + return builder; + } + + @Override + public Builder include(HasDisplayData subComponent) { + checkNotNull(subComponent); + boolean newComponent = visited.add(subComponent); + if (newComponent) { + Class prevNs = this.latestNs; + this.latestNs = subComponent.getClass(); + subComponent.populateDisplayData(this); + this.latestNs = prevNs; + } + + return this; + } + + @Override + public ItemBuilder add(String key, String value) { + checkNotNull(value); + return addItem(key, Type.STRING, value); + } + + @Override + public ItemBuilder add(String key, long value) { + return addItem(key, Type.INTEGER, value); + } + + @Override + public ItemBuilder add(String key, double value) { + return addItem(key, Type.FLOAT, value); + } + + @Override + public ItemBuilder add(String key, Instant value) { + checkNotNull(value); + return addItem(key, Type.TIMESTAMP, value); + } + + @Override + public ItemBuilder add(String key, Duration value) { + checkNotNull(value); + return addItem(key, Type.DURATION, value); + } + + @Override + public ItemBuilder add(String key, Class value) { + checkNotNull(value); + return addItem(key, Type.JAVA_CLASS, value); + } + + private ItemBuilder addItem(String key, Type type, T value) { + checkNotNull(key); + checkArgument(!key.isEmpty()); + + Identifier id = Identifier.of(latestNs, key); + if (entries.containsKey(id)) { + throw new IllegalArgumentException("DisplayData key already exists. All display data " + + "for a component must be registered with a unique key.\nKey: " + id); + } + Item item = Item.create(id.getNamespace(), key, type, value); + entries.put(id, item); + + latestItem = item; + latestIdentifier = id; + + return this; + } + + @Override + public ItemBuilder withLabel(String label) { + latestItem = latestItem.withLabel(label); + entries.put(latestIdentifier, latestItem); + return this; + } + + @Override + public ItemBuilder withLinkUrl(String url) { + latestItem = latestItem.withUrl(url); + entries.put(latestIdentifier, latestItem); + return this; + } + + private DisplayData build() { + return new DisplayData(this.entries); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java new file mode 100644 index 0000000000..b2eca3d881 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; + +import com.google.cloud.dataflow.sdk.transforms.PTransform; + +/** + * Marker interface for {@link PTransform PTransforms} and components used within + * {@link PTransform PTransforms} to specify display metadata to be used within UIs and diagnostic + * tools. + * + *

    Display metadata is optional and may be collected during pipeline construction. It should + * only be used to informational purposes. Tools and components should not assume that display data + * will always be collected, or that collected display data will always be displayed. + */ +public interface HasDisplayData { + /** + * Register display metadata for the given transform or component. Metadata can be registered + * directly on the provided builder, as well as via included sub-components. + * + *

    +   * {@code
    +   * @Override
    +   * public void populateDisplayData(DisplayData.Builder builder) {
    +   *  builder
    +   *     .include(subComponent)
    +   *     .add("minFilter", 42)
    +   *     .add("topic", "projects/myproject/topics/mytopic")
    +   *       .withLabel("Pub/Sub Topic")
    +   *     .add("serviceInstance", "myservice.com/fizzbang")
    +   *       .withLinkUrl("http://www.myservice.com/fizzbang");
    +   * }
    +   * }
    +   * 
    + * + * @param builder The builder to populate with display metadata. + */ + void populateDisplayData(DisplayData.Builder builder); +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java index a709a233ab..dabad7bae7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java @@ -17,14 +17,17 @@ package com.google.cloud.dataflow.sdk.transforms; import static org.hamcrest.CoreMatchers.isA; +import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.junit.Rule; import org.junit.Test; @@ -188,4 +191,16 @@ private TestPipeline createTestPipeline(DoFn return pipeline; } + + @Test + public void testPopulateDisplayDataDefaultBehavior() { + DoFn usesDefault = + new DoFn() { + @Override + public void processElement(ProcessContext c) throws Exception {} + }; + + DisplayData data = DisplayData.from(usesDefault); + assertThat(data.items(), empty()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java new file mode 100644 index 0000000000..cea1b38df7 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms; + +import static org.hamcrest.Matchers.empty; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link PTransform} base class. + */ +@RunWith(JUnit4.class) +public class PTransformTest { + @Test + public void testPopulateDisplayDataDefaultBehavior() { + PTransform, PCollection> transform = + new PTransform, PCollection>() {}; + DisplayData displayData = DisplayData.from(transform); + assertThat(displayData.items(), empty()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java index f3f9bde92d..1ff46e41c2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; import static com.google.cloud.dataflow.sdk.util.StringUtils.jsonStringToByteArray; @@ -39,6 +41,9 @@ import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; +import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.IllegalMutationException; @@ -1515,4 +1520,22 @@ public void testMutatingInputCoderDoFnError() throws Exception { thrown.expectMessage("must not be mutated"); pipeline.run(); } + + @Test + public void testIncludesDoFnDisplayData() { + Bound parDo = + ParDo.of( + new DoFn() { + @Override + public void processElement(ProcessContext c) {} + + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar"); + } + }); + + DisplayData displayData = DisplayData.from(parDo); + assertThat(displayData, hasDisplayItem(hasKey("foo"))); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java new file mode 100644 index 0000000000..2753aafa7b --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; + +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Item; + +import org.hamcrest.Description; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.hamcrest.TypeSafeDiagnosingMatcher; + +import java.util.Collection; + +/** + * Hamcrest matcher for making assertions on {@link DisplayData} instances. + */ +public class DisplayDataMatchers { + /** + * Do not instantiate. + */ + private DisplayDataMatchers() {} + + /** + * Creates a matcher that matches if the examined {@link DisplayData} contains any items. + */ + public static Matcher hasDisplayItem() { + return hasDisplayItem(Matchers.any(DisplayData.Item.class)); + } + + /** + * Creates a matcher that matches if the examined {@link DisplayData} contains any item + * matching the specified {@code itemMatcher}. + */ + public static Matcher hasDisplayItem(Matcher itemMatcher) { + return new HasDisplayDataItemMatcher(itemMatcher); + } + + private static class HasDisplayDataItemMatcher extends TypeSafeDiagnosingMatcher { + private final Matcher itemMatcher; + + private HasDisplayDataItemMatcher(Matcher itemMatcher) { + this.itemMatcher = itemMatcher; + } + + @Override + public void describeTo(Description description) { + description.appendText("display data with item: "); + itemMatcher.describeTo(description); + } + + @Override + protected boolean matchesSafely(DisplayData data, Description mismatchDescription) { + Collection items = data.items(); + boolean isMatch = Matchers.hasItem(itemMatcher).matches(items); + if (!isMatch) { + mismatchDescription.appendText("found " + items.size() + " non-matching items"); + } + + return isMatch; + } + } + + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a key + * with the specified value. + */ + public static Matcher hasKey(String key) { + return hasKey(Matchers.is(key)); + } + + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a key + * matching the specified key matcher. + */ + public static Matcher hasKey(Matcher keyMatcher) { + return new FeatureMatcher(keyMatcher, "with key", "key") { + @Override + protected String featureValueOf(DisplayData.Item actual) { + return actual.getKey(); + } + }; + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java new file mode 100644 index 0000000000..2636cf85c8 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; + +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.core.StringStartsWith.startsWith; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.StringDescription; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Unit tests for {@link DisplayDataMatchers}. + */ +@RunWith(JUnit4.class) +public class DisplayDataMatchersTest { + @Test + public void testHasDisplayItem() { + Matcher matcher = hasDisplayItem(); + + assertFalse(matcher.matches(DisplayData.none())); + assertTrue(matcher.matches(createDisplayDataWithItem("foo", "bar"))); + } + + @Test + public void testHasDisplayItemDescription() { + Matcher matcher = hasDisplayItem(); + Description desc = new StringDescription(); + Description mismatchDesc = new StringDescription(); + + matcher.describeTo(desc); + matcher.describeMismatch(DisplayData.none(), mismatchDesc); + + assertThat(desc.toString(), startsWith("display data with item: ")); + assertThat(mismatchDesc.toString(), containsString("found 0 non-matching items")); + } + + @Test + public void testHasKey() { + Matcher matcher = hasDisplayItem(hasKey("foo")); + + assertTrue(matcher.matches(createDisplayDataWithItem("foo", "bar"))); + assertFalse(matcher.matches(createDisplayDataWithItem("fooz", "bar"))); + } + + private DisplayData createDisplayDataWithItem(final String key, final String value) { + return DisplayData.from( + new PTransform, PCollection>() { + @Override + public void populateDisplayData(Builder builder) { + builder.add(key, value); + } + }); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java new file mode 100644 index 0000000000..13dd618657 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -0,0 +1,633 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; + +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Item; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.testing.EqualsTester; + +import org.hamcrest.CustomTypeSafeMatcher; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Tests for {@link DisplayData} class. + */ +@RunWith(JUnit4.class) +public class DisplayDataTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + private static final DateTimeFormatter ISO_FORMATTER = ISODateTimeFormat.dateTime(); + + @Test + public void testTypicalUsage() { + final HasDisplayData subComponent1 = + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("ExpectedAnswer", 42); + } + }; + + final HasDisplayData subComponent2 = + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("Location", "Seattle").add("Forecast", "Rain"); + } + }; + + PTransform transform = + new PTransform, PCollection>() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .include(subComponent1) + .include(subComponent2) + .add("MinSproggles", 200) + .withLabel("Mimimum Required Sproggles") + .add("LazerOrientation", "NORTH") + .add("TimeBomb", Instant.now().plus(Duration.standardDays(1))) + .add("FilterLogic", subComponent1.getClass()) + .add("ServiceUrl", "google.com/fizzbang") + .withLinkUrl("http://www.google.com/fizzbang"); + } + }; + + DisplayData data = DisplayData.from(transform); + + assertThat(data.items(), not(empty())); + assertThat( + data.items(), + everyItem( + allOf( + hasKey(not(isEmptyOrNullString())), + hasNamespace( + Matchers.>isOneOf( + transform.getClass(), subComponent1.getClass(), subComponent2.getClass())), + hasType(notNullValue(DisplayData.Type.class)), + hasValue(not(isEmptyOrNullString()))))); + } + + @Test + public void testDefaultInstance() { + DisplayData none = DisplayData.none(); + assertThat(none.items(), empty()); + } + + @Test + public void testCanBuild() { + DisplayData data = + DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("Foo", "bar"); + } + }); + + assertThat(data.items(), hasSize(1)); + assertThat(data, hasDisplayItem(hasKey("Foo"))); + } + + @Test + public void testAsMap() { + DisplayData data = + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }); + + Map map = data.asMap(); + assertEquals(map.size(), 1); + assertThat(data, hasDisplayItem(hasKey("foo"))); + assertEquals(map.values(), data.items()); + } + + @Test + public void testItemProperties() { + final Instant value = Instant.now(); + DisplayData data = DisplayData.from(new ConcreteComponent(value)); + + @SuppressWarnings("unchecked") + DisplayData.Item item = (DisplayData.Item) data.items().toArray()[0]; + assertThat( + item, + allOf( + hasNamespace(Matchers.>is(ConcreteComponent.class)), + hasKey("now"), + hasType(is(DisplayData.Type.TIMESTAMP)), + hasValue(is(ISO_FORMATTER.print(value))), + hasShortValue(nullValue(String.class)), + hasLabel(is("the current instant")), + hasUrl(is("http://time.gov")))); + } + + static class ConcreteComponent implements HasDisplayData { + private Instant value; + + ConcreteComponent(Instant value) { + this.value = value; + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("now", value).withLabel("the current instant").withLinkUrl("http://time.gov"); + } + } + + @Test + public void testUnspecifiedOptionalProperties() { + DisplayData data = + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }); + + assertThat( + data, + hasDisplayItem(allOf(hasLabel(nullValue(String.class)), hasUrl(nullValue(String.class))))); + } + + @Test + public void testIncludes() { + final HasDisplayData subComponent = + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + + DisplayData data = + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.include(subComponent); + } + }); + + assertThat( + data, + hasDisplayItem( + allOf( + hasKey("foo"), + hasNamespace(Matchers.>is(subComponent.getClass()))))); + } + + @Test + public void testIdentifierEquality() { + new EqualsTester() + .addEqualityGroup( + DisplayData.Identifier.of(DisplayDataTest.class, "1"), + DisplayData.Identifier.of(DisplayDataTest.class, "1")) + .addEqualityGroup(DisplayData.Identifier.of(Object.class, "1")) + .addEqualityGroup(DisplayData.Identifier.of(DisplayDataTest.class, "2")) + .testEquals(); + } + + @Test + public void testAnonymousClassNamespace() { + DisplayData data = + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }); + + DisplayData.Item item = (DisplayData.Item) data.items().toArray()[0]; + final Pattern anonClassRegex = Pattern.compile( + Pattern.quote(DisplayDataTest.class.getName()) + "\\$\\d+$"); + assertThat(item.getNamespace(), new CustomTypeSafeMatcher( + "anonymous class regex: " + anonClassRegex) { + @Override + protected boolean matchesSafely(String item) { + java.util.regex.Matcher m = anonClassRegex.matcher(item); + return m.matches(); + } + }); + } + + @Test + public void testAcceptsKeysWithDifferentNamespaces() { + DisplayData data = + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("foo", "bar") + .include( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }); + } + }); + + assertThat(data.items(), hasSize(2)); + } + + @Test + public void testDuplicateKeyThrowsException() { + thrown.expect(IllegalArgumentException.class); + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("foo", "bar") + .add("foo", "baz"); + } + }); + } + + @Test + public void testToString() { + HasDisplayData component = new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + + DisplayData data = DisplayData.from(component); + assertEquals(String.format("%s:foo=bar", component.getClass().getName()), data.toString()); + } + + @Test + public void testHandlesIncludeCycles() { + + final IncludeSubComponent componentA = + new IncludeSubComponent() { + @Override + String getId() { + return "componentA"; + } + }; + final IncludeSubComponent componentB = + new IncludeSubComponent() { + @Override + String getId() { + return "componentB"; + } + }; + + HasDisplayData component = + new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.include(componentA); + } + }; + + componentA.subComponent = componentB; + componentB.subComponent = componentA; + + DisplayData data = DisplayData.from(component); + assertThat(data.items(), hasSize(2)); + } + + @Test + public void testIncludesSubcomponentsWithObjectEquality() { + DisplayData data = DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .include(new EqualsEverything("foo1", "bar1")) + .include(new EqualsEverything("foo2", "bar2")); + } + }); + + assertThat(data.items(), hasSize(2)); + } + + private static class EqualsEverything implements HasDisplayData { + private final String value; + private final String key; + EqualsEverything(String key, String value) { + this.key = key; + this.value = value; + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(key, value); + } + + @Override + public int hashCode() { + return 1; + } + + @Override + public boolean equals(Object obj) { + return true; + } + } + + abstract static class IncludeSubComponent implements HasDisplayData { + HasDisplayData subComponent; + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("id", getId()).include(subComponent); + } + + abstract String getId(); + } + + @Test + public void testTypeMappings() { + DisplayData data = + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("string", "foobar") + .add("integer", 123) + .add("float", 3.14) + .add("java_class", DisplayDataTest.class) + .add("timestamp", Instant.now()) + .add("duration", Duration.standardHours(1)); + } + }); + + Collection items = data.items(); + assertThat( + items, hasItem(allOf(hasKey("string"), hasType(is(DisplayData.Type.STRING))))); + assertThat( + items, hasItem(allOf(hasKey("integer"), hasType(is(DisplayData.Type.INTEGER))))); + assertThat(items, hasItem(allOf(hasKey("float"), hasType(is(DisplayData.Type.FLOAT))))); + assertThat( + items, + hasItem(allOf(hasKey("java_class"), hasType(is(DisplayData.Type.JAVA_CLASS))))); + assertThat( + items, + hasItem(allOf(hasKey("timestamp"), hasType(is(DisplayData.Type.TIMESTAMP))))); + assertThat( + items, hasItem(allOf(hasKey("duration"), hasType(is(DisplayData.Type.DURATION))))); + } + + @Test + public void testStringFormatting() throws IOException { + final Instant now = Instant.now(); + final Duration oneHour = Duration.standardHours(1); + + HasDisplayData component = new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("string", "foobar") + .add("integer", 123) + .add("float", 3.14) + .add("java_class", DisplayDataTest.class) + .add("timestamp", now) + .add("duration", oneHour); + } + }; + DisplayData data = DisplayData.from(component); + + Collection items = data.items(); + assertThat(items, hasItem(allOf(hasKey("string"), hasValue(is("foobar"))))); + assertThat(items, hasItem(allOf(hasKey("integer"), hasValue(is("123"))))); + assertThat(items, hasItem(allOf(hasKey("float"), hasValue(is("3.14"))))); + assertThat(items, hasItem(allOf(hasKey("java_class"), + hasValue(is(DisplayDataTest.class.getName())), + hasShortValue(is(DisplayDataTest.class.getSimpleName()))))); + assertThat(items, hasItem(allOf(hasKey("timestamp"), + hasValue(is(ISO_FORMATTER.print(now)))))); + assertThat(items, hasItem(allOf(hasKey("duration"), + hasValue(is(Long.toString(oneHour.getMillis())))))); + } + + @Test + public void testContextProperlyReset() { + final HasDisplayData subComponent = + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + + HasDisplayData component = + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .include(subComponent) + .add("alpha", "bravo"); + } + }; + + DisplayData data = DisplayData.from(component); + assertThat( + data.items(), + hasItem( + allOf( + hasKey("alpha"), + hasNamespace(Matchers.>is(component.getClass()))))); + } + + @Test + public void testFromNull() { + thrown.expect(NullPointerException.class); + DisplayData.from(null); + } + + @Test + public void testIncludeNull() { + thrown.expect(NullPointerException.class); + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.include(null); + } + }); + } + + @Test + public void testNullKey() { + thrown.expect(NullPointerException.class); + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add(null, "foo"); + } + }); + } + + @Test + public void testRejectsNullValues() { + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + try { + builder.add("key", (String) null); + throw new RuntimeException("Should throw on null string value"); + } catch (NullPointerException ex) { + // Expected + } + + try { + builder.add("key", (Class) null); + throw new RuntimeException("Should throw on null class value"); + } catch (NullPointerException ex) { + // Expected + } + + try { + builder.add("key", (Duration) null); + throw new RuntimeException("Should throw on null duration value"); + } catch (NullPointerException ex) { + // Expected + } + + try { + builder.add("key", (Instant) null); + throw new RuntimeException("Should throw on null instant value"); + } catch (NullPointerException ex) { + // Expected + } + } + }); + } + + public void testAcceptsNullOptionalValues() { + DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("key", "value") + .withLabel(null) + .withLinkUrl(null); + } + }); + + // Should not throw + } + + private static Matcher hasNamespace(Matcher> nsMatcher) { + return new FeatureMatcher>( + nsMatcher, "display item with namespace", "namespace") { + @Override + protected Class featureValueOf(DisplayData.Item actual) { + try { + return Class.forName(actual.getNamespace()); + } catch (ClassNotFoundException e) { + return null; + } + } + }; + } + + private static Matcher hasType(Matcher typeMatcher) { + return new FeatureMatcher( + typeMatcher, "display item with type", "type") { + @Override + protected DisplayData.Type featureValueOf(DisplayData.Item actual) { + return actual.getType(); + } + }; + } + + private static Matcher hasLabel(Matcher labelMatcher) { + return new FeatureMatcher( + labelMatcher, "display item with label", "label") { + @Override + protected String featureValueOf(DisplayData.Item actual) { + return actual.getLabel(); + } + }; + } + + private static Matcher hasUrl(Matcher urlMatcher) { + return new FeatureMatcher( + urlMatcher, "display item with url", "URL") { + @Override + protected String featureValueOf(DisplayData.Item actual) { + return actual.getUrl(); + } + }; + } + + private static Matcher hasValue(Matcher valueMatcher) { + return new FeatureMatcher( + valueMatcher, "display item with value", "value") { + @Override + protected String featureValueOf(DisplayData.Item actual) { + return actual.getValue(); + } + }; + } + + private static Matcher hasShortValue(Matcher valueStringMatcher) { + return new FeatureMatcher( + valueStringMatcher, "display item with short value", "short value") { + @Override + protected String featureValueOf(DisplayData.Item actual) { + return actual.getShortValue(); + } + }; + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java index e995b821de..fcfe1d8f2f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java @@ -49,7 +49,8 @@ public void testOurApiSurface() throws Exception { .pruningClassName("com.google.cloud.dataflow.sdk.util.common.ReflectHelpers") .pruningClassName("com.google.cloud.dataflow.sdk.DataflowMatchers") .pruningClassName("com.google.cloud.dataflow.sdk.TestUtils") - .pruningClassName("com.google.cloud.dataflow.sdk.WindowMatchers"); + .pruningClassName("com.google.cloud.dataflow.sdk.WindowMatchers") + .pruningClassName("com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers"); checkedApiSurface.getExposedClasses(); From 3f99e1fb00f17c3e5a84d1f563d085ce815d7a98 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 26 Feb 2016 17:30:13 -0800 Subject: [PATCH 277/751] Implement InProcessPipelineRunner#run Appropriately construct an evaluation context and executor, and start the pipeline when run is called. Implement InProcessPipelineResult. Apply PTransform overrides. --- ...achedThreadPoolExecutorServiceFactory.java | 42 ++++ .../ConsumerTrackingPipelineVisitor.java | 173 +++++++++++++ .../inprocess/ExecutorServiceFactory.java | 32 +++ .../ExecutorServiceParallelExecutor.java | 2 +- .../inprocess/GroupByKeyEvaluatorFactory.java | 8 +- .../inprocess/InProcessPipelineOptions.java | 56 +++++ .../inprocess/InProcessPipelineRunner.java | 228 +++++++++++++++-- .../inprocess/KeyedPValueTrackingVisitor.java | 95 +++++++ .../ConsumerTrackingPipelineVisitorTest.java | 233 ++++++++++++++++++ .../InProcessPipelineRunnerTest.java | 77 ++++++ .../KeyedPValueTrackingVisitorTest.java | 189 ++++++++++++++ 11 files changed, 1104 insertions(+), 31 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CachedThreadPoolExecutorServiceFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CachedThreadPoolExecutorServiceFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CachedThreadPoolExecutorServiceFactory.java new file mode 100644 index 0000000000..3350d2b4d5 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CachedThreadPoolExecutorServiceFactory.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * A {@link ExecutorServiceFactory} that produces cached thread pools via + * {@link Executors#newCachedThreadPool()}. + */ +class CachedThreadPoolExecutorServiceFactory + implements DefaultValueFactory, ExecutorServiceFactory { + private static final CachedThreadPoolExecutorServiceFactory INSTANCE = + new CachedThreadPoolExecutorServiceFactory(); + + @Override + public ExecutorServiceFactory create(PipelineOptions options) { + return INSTANCE; + } + + @Override + public ExecutorService create() { + return Executors.newCachedThreadPool(); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java new file mode 100644 index 0000000000..c602b23c41 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java @@ -0,0 +1,173 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.PValue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Tracks the {@link AppliedPTransform AppliedPTransforms} that consume each {@link PValue} in the + * {@link Pipeline}. This is used to schedule consuming {@link PTransform PTransforms} to consume + * input after the upstream transform has produced and committed output. + */ +public class ConsumerTrackingPipelineVisitor implements PipelineVisitor { + private Map>> valueToConsumers = new HashMap<>(); + private Collection> rootTransforms = new ArrayList<>(); + private Collection> views = new ArrayList<>(); + private Map, String> stepNames = new HashMap<>(); + private Set toFinalize = new HashSet<>(); + private int numTransforms = 0; + private boolean finalized = false; + + @Override + public void enterCompositeTransform(TransformTreeNode node) { + checkState( + !finalized, + "Attempting to traverse a pipeline (node %s) with a %s " + + "which has already visited a Pipeline and is finalized", + node.getFullName(), + ConsumerTrackingPipelineVisitor.class.getSimpleName()); + } + + @Override + public void leaveCompositeTransform(TransformTreeNode node) { + checkState( + !finalized, + "Attempting to traverse a pipeline (node %s) with a %s which is already finalized", + node.getFullName(), + ConsumerTrackingPipelineVisitor.class.getSimpleName()); + if (node.isRootNode()) { + finalized = true; + } + } + + @Override + public void visitTransform(TransformTreeNode node) { + toFinalize.removeAll(node.getInput().expand()); + AppliedPTransform appliedTransform = getAppliedTransform(node); + if (node.getInput().expand().isEmpty()) { + rootTransforms.add(appliedTransform); + } else { + for (PValue value : node.getInput().expand()) { + valueToConsumers.get(value).add(appliedTransform); + stepNames.put(appliedTransform, genStepName()); + } + } + } + + private AppliedPTransform getAppliedTransform(TransformTreeNode node) { + @SuppressWarnings({"rawtypes", "unchecked"}) + AppliedPTransform application = AppliedPTransform.of( + node.getFullName(), node.getInput(), node.getOutput(), (PTransform) node.getTransform()); + return application; + } + + @Override + public void visitValue(PValue value, TransformTreeNode producer) { + toFinalize.add(value); + for (PValue expandedValue : value.expand()) { + valueToConsumers.put(expandedValue, new ArrayList>()); + if (expandedValue instanceof PCollectionView) { + views.add((PCollectionView) expandedValue); + } + expandedValue.recordAsOutput(getAppliedTransform(producer)); + } + value.recordAsOutput(getAppliedTransform(producer)); + } + + private String genStepName() { + return String.format("s%s", numTransforms++); + } + + + /** + * Returns a mapping of each fully-expanded {@link PValue} to each + * {@link AppliedPTransform} that consumes it. For each AppliedPTransform in the collection + * returned from {@code getValueToCustomers().get(PValue)}, + * {@code AppliedPTransform#getInput().expand()} will contain the argument {@link PValue}. + */ + public Map>> getValueToConsumers() { + checkState( + finalized, + "Can't call getValueToConsumers before the Pipeline has been completely traversed"); + + return valueToConsumers; + } + + /** + * Returns the mapping for each {@link AppliedPTransform} in the {@link Pipeline} to a unique step + * name. + */ + public Map, String> getStepNames() { + checkState( + finalized, "Can't call getStepNames before the Pipeline has been completely traversed"); + + return stepNames; + } + + /** + * Returns the root transforms of the {@link Pipeline}. A root {@link AppliedPTransform} consumes + * a {@link PInput} where the {@link PInput#expand()} returns an empty collection. + */ + public Collection> getRootTransforms() { + checkState( + finalized, + "Can't call getRootTransforms before the Pipeline has been completely traversed"); + + return rootTransforms; + } + + /** + * Returns all of the {@link PCollectionView PCollectionViews} contained in the visited + * {@link Pipeline}. + */ + public Collection> getViews() { + checkState(finalized, "Can't call getViews before the Pipeline has been completely traversed"); + + return views; + } + + /** + * Returns all of the {@link PValue PValues} that have been produced but not consumed. These + * {@link PValue PValues} should be finalized by the {@link PipelineRunner} before the + * {@link Pipeline} is executed. + */ + public Set getUnfinalizedPValues() { + checkState( + finalized, + "Can't call getUnfinalizedPValues before the Pipeline has been completely traversed"); + + return toFinalize; + } +} + + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java new file mode 100644 index 0000000000..480bcdefed --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import java.util.concurrent.ExecutorService; + +/** + * A factory that creates {@link ExecutorService ExecutorServices}. + * {@link ExecutorService ExecutorServices} created by this factory should be independent of one + * another (e.g., if any executor is shut down the remaining executors should continue to process + * work). + */ +public interface ExecutorServiceFactory { + /** + * Create a new {@link ExecutorService}. + */ + ExecutorService create(); +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index ae686f2979..c72a1155f5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -126,7 +126,7 @@ private void evaluateBundle( @Nullable final CommittedBundle bundle, final CompletionCallback onComplete) { TransformExecutorService transformExecutor; - if (isKeyed(bundle.getPCollection())) { + if (bundle != null && isKeyed(bundle.getPCollection())) { final StepAndKey stepAndKey = StepAndKey.of(transform, bundle == null ? null : bundle.getKey()); transformExecutor = getSerialExecutorService(stepAndKey); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java index ec63be84c9..b1d5d35869 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java @@ -59,8 +59,10 @@ public TransformEvaluator forApplication( AppliedPTransform application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - return createEvaluator( - (AppliedPTransform) application, (CommittedBundle) inputBundle, evaluationContext); + @SuppressWarnings({"cast", "unchecked", "rawtypes"}) + TransformEvaluator evaluator = createEvaluator( + (AppliedPTransform) application, (CommittedBundle) inputBundle, evaluationContext); + return evaluator; } private TransformEvaluator>> createEvaluator( @@ -183,7 +185,7 @@ public static final class InProcessGroupByKey extends ForwardingPTransform>, PCollection>>> { private final GroupByKey original; - public InProcessGroupByKey(GroupByKey from) { + private InProcessGroupByKey(GroupByKey from) { this.original = from; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java index 27e9a4be6e..5ee0e88b5b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java @@ -15,20 +15,76 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; import com.google.cloud.dataflow.sdk.options.Default; +import com.google.cloud.dataflow.sdk.options.Description; +import com.google.cloud.dataflow.sdk.options.Hidden; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.Validation.Required; +import com.google.cloud.dataflow.sdk.transforms.PTransform; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; /** * Options that can be used to configure the {@link InProcessPipelineRunner}. */ public interface InProcessPipelineOptions extends PipelineOptions, ApplicationNameOptions { + /** + * Gets the {@link ExecutorServiceFactory} to use to create instances of {@link ExecutorService} + * to execute {@link PTransform PTransforms}. + * + *

    Note that {@link ExecutorService ExecutorServices} returned by the factory must ensure that + * it cannot enter a state in which it will not schedule additional pending work unless currently + * scheduled work completes, as this may cause the {@link Pipeline} to cease processing. + * + *

    Defaults to a {@link CachedThreadPoolExecutorServiceFactory}, which produces instances of + * {@link Executors#newCachedThreadPool()}. + */ + @JsonIgnore + @Required + @Hidden + @Default.InstanceFactory(CachedThreadPoolExecutorServiceFactory.class) + ExecutorServiceFactory getExecutorServiceFactory(); + + void setExecutorServiceFactory(ExecutorServiceFactory executorService); + + /** + * Gets the {@link Clock} used by this pipeline. The clock is used in place of accessing the + * system time when time values are required by the evaluator. + */ @Default.InstanceFactory(NanosOffsetClock.Factory.class) + @JsonIgnore + @Required + @Hidden + @Description( + "The processing time source used by the pipeline. When the current time is " + + "needed by the evaluator, the result of clock#now() is used.") Clock getClock(); void setClock(Clock clock); + @Default.Boolean(false) + @Description( + "If the pipeline should shut down producers which have reached the maximum " + + "representable watermark. If this is set to true, a pipeline in which all PTransforms " + + "have reached the maximum watermark will be shut down, even if there are unbounded " + + "sources that could produce additional (late) data. By default, if the pipeline " + + "contains any unbounded PCollections, it will run until explicitly shut down.") boolean isShutdownUnboundedProducersWithMaxWatermark(); void setShutdownUnboundedProducersWithMaxWatermark(boolean shutdown); + + @Default.Boolean(true) + @Description( + "If the pipeline should block awaiting completion of the pipeline. If set to true, " + + "a call to Pipeline#run() will block until all PTransforms are complete. Otherwise, " + + "the Pipeline will execute asynchronously. If set to false, the completion of the " + + "pipeline can be awaited on by use of InProcessPipelineResult#awaitCompletion().") + boolean isBlockOnRun(); + + void setBlockOnRun(boolean b); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 32859dae63..a1c8756c5e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Google Inc. + * Copyright (C) 2016 Google Inc. * * Licensed 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 @@ -15,25 +15,46 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import static com.google.common.base.Preconditions.checkArgument; - +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; +import com.google.cloud.dataflow.sdk.PipelineResult; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.AggregatorPipelineExtractor; +import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; +import com.google.cloud.dataflow.sdk.runners.AggregatorValues; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKey; -import com.google.cloud.dataflow.sdk.runners.inprocess.ViewEvaluatorFactory.InProcessCreatePCollectionView; +import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; +import com.google.cloud.dataflow.sdk.util.InstanceBuilder; +import com.google.cloud.dataflow.sdk.util.MapAggregatorValues; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; +import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.Counter; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; +import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import org.joda.time.Instant; +import java.util.Collection; +import java.util.HashMap; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; import javax.annotation.Nullable; @@ -42,28 +63,25 @@ * {@link PCollection PCollections}. */ @Experimental -public class InProcessPipelineRunner { - @SuppressWarnings({"rawtypes", "unused"}) +public class InProcessPipelineRunner + extends PipelineRunner { + /** + * The default set of transform overrides to use in the {@link InProcessPipelineRunner}. + * + *

    A transform override must have a single-argument constructor that takes an instance of the + * type of transform it is overriding. + */ + @SuppressWarnings("rawtypes") private static Map, Class> defaultTransformOverrides = ImmutableMap., Class>builder() + .put(Create.Values.class, InProcessCreate.class) .put(GroupByKey.class, InProcessGroupByKey.class) - .put(CreatePCollectionView.class, InProcessCreatePCollectionView.class) + .put( + CreatePCollectionView.class, + ViewEvaluatorFactory.InProcessCreatePCollectionView.class) .build(); - private static Map, TransformEvaluatorFactory> defaultEvaluatorFactories = - new ConcurrentHashMap<>(); - - /** - * Register a default transform evaluator. - */ - public static > void registerTransformEvaluatorFactory( - Class clazz, TransformEvaluatorFactory evaluator) { - checkArgument(defaultEvaluatorFactories.put(clazz, evaluator) == null, - "Defining a default factory %s to evaluate Transforms of type %s multiple times", evaluator, - clazz); - } - /** * Part of a {@link PCollection}. Elements are output to a bundle, which will cause them to be * executed by {@link PTransform PTransforms} that consume the {@link PCollection} this bundle is @@ -73,7 +91,7 @@ public class InProcessPipelineRunner { */ public static interface UncommittedBundle { /** - * Returns the PCollection that the elements of this bundle belong to. + * Returns the PCollection that the elements of this {@link UncommittedBundle} belong to. */ PCollection getPCollection(); @@ -103,14 +121,13 @@ public static interface UncommittedBundle { * @param the type of elements contained within this bundle */ public static interface CommittedBundle { - /** * Returns the PCollection that the elements of this bundle belong to. */ PCollection getPCollection(); /** - * Returns weather this bundle is keyed. A bundle that is part of a {@link PCollection} that + * Returns whether this bundle is keyed. A bundle that is part of a {@link PCollection} that * occurs after a {@link GroupByKey} is keyed by the result of the last {@link GroupByKey}. */ boolean isKeyed(); @@ -119,11 +136,12 @@ public static interface CommittedBundle { * Returns the (possibly null) key that was output in the most recent {@link GroupByKey} in the * execution of this bundle. */ - @Nullable Object getKey(); + @Nullable + Object getKey(); /** - * @return an {@link Iterable} containing all of the elements that have been added to this - * {@link CommittedBundle} + * Returns an {@link Iterable} containing all of the elements that have been added to this + * {@link CommittedBundle}. */ Iterable> getElements(); @@ -166,4 +184,160 @@ private InProcessPipelineRunner(InProcessPipelineOptions options) { public InProcessPipelineOptions getPipelineOptions() { return options; } + + @Override + public OutputT apply( + PTransform transform, InputT input) { + Class overrideClass = defaultTransformOverrides.get(transform.getClass()); + if (overrideClass != null) { + // It is the responsibility of whoever constructs overrides to ensure this is type safe. + @SuppressWarnings("unchecked") + Class> transformClass = + (Class>) transform.getClass(); + + @SuppressWarnings("unchecked") + Class> customTransformClass = + (Class>) overrideClass; + + PTransform customTransform = + InstanceBuilder.ofType(customTransformClass) + .withArg(transformClass, transform) + .build(); + + // This overrides the contents of the apply method without changing the TransformTreeNode that + // is generated by the PCollection application. + return super.apply(customTransform, input); + } else { + return super.apply(transform, input); + } + } + + @Override + public InProcessPipelineResult run(Pipeline pipeline) { + ConsumerTrackingPipelineVisitor consumerTrackingVisitor = new ConsumerTrackingPipelineVisitor(); + pipeline.traverseTopologically(consumerTrackingVisitor); + for (PValue unfinalized : consumerTrackingVisitor.getUnfinalizedPValues()) { + unfinalized.finishSpecifying(); + } + @SuppressWarnings("rawtypes") + KeyedPValueTrackingVisitor keyedPValueVisitor = + KeyedPValueTrackingVisitor.create( + ImmutableSet.>of( + GroupByKey.class, InProcessGroupByKeyOnly.class)); + pipeline.traverseTopologically(keyedPValueVisitor); + + InProcessEvaluationContext context = + InProcessEvaluationContext.create( + getPipelineOptions(), + consumerTrackingVisitor.getRootTransforms(), + consumerTrackingVisitor.getValueToConsumers(), + consumerTrackingVisitor.getStepNames(), + consumerTrackingVisitor.getViews()); + + // independent executor service for each run + ExecutorService executorService = + context.getPipelineOptions().getExecutorServiceFactory().create(); + InProcessExecutor executor = + ExecutorServiceParallelExecutor.create( + executorService, + consumerTrackingVisitor.getValueToConsumers(), + keyedPValueVisitor.getKeyedPValues(), + TransformEvaluatorRegistry.defaultRegistry(), + context); + executor.start(consumerTrackingVisitor.getRootTransforms()); + + Map, Collection>> aggregatorSteps = + new AggregatorPipelineExtractor(pipeline).getAggregatorSteps(); + InProcessPipelineResult result = + new InProcessPipelineResult(executor, context, aggregatorSteps); + if (options.isBlockOnRun()) { + try { + result.awaitCompletion(); + } catch (UserCodeException userException) { + throw new PipelineExecutionException(userException.getCause()); + } catch (Throwable t) { + Throwables.propagate(t); + } + } + return result; + } + + /** + * The result of running a {@link Pipeline} with the {@link InProcessPipelineRunner}. + * + * Throws {@link UnsupportedOperationException} for all methods. + */ + public static class InProcessPipelineResult implements PipelineResult { + private final InProcessExecutor executor; + private final InProcessEvaluationContext evaluationContext; + private final Map, Collection>> aggregatorSteps; + private State state; + + private InProcessPipelineResult( + InProcessExecutor executor, + InProcessEvaluationContext evaluationContext, + Map, Collection>> aggregatorSteps) { + this.executor = executor; + this.evaluationContext = evaluationContext; + this.aggregatorSteps = aggregatorSteps; + // Only ever constructed after the executor has started. + this.state = State.RUNNING; + } + + @Override + public State getState() { + return state; + } + + @Override + public AggregatorValues getAggregatorValues(Aggregator aggregator) + throws AggregatorRetrievalException { + CounterSet counters = evaluationContext.getCounters(); + Collection> steps = aggregatorSteps.get(aggregator); + Map stepValues = new HashMap<>(); + for (AppliedPTransform transform : evaluationContext.getSteps()) { + if (steps.contains(transform.getTransform())) { + String stepName = + String.format( + "user-%s-%s", evaluationContext.getStepName(transform), aggregator.getName()); + Counter counter = (Counter) counters.getExistingCounter(stepName); + if (counter != null) { + stepValues.put(transform.getFullName(), counter.getAggregate()); + } + } + } + return new MapAggregatorValues<>(stepValues); + } + + /** + * Blocks until the {@link Pipeline} execution represented by this + * {@link InProcessPipelineResult} is complete, returning the terminal state. + * + *

    If the pipeline terminates abnormally by throwing an exception, this will rethrow the + * exception. Future calls to {@link #getState()} will return + * {@link com.google.cloud.dataflow.sdk.PipelineResult.State#FAILED}. + * + *

    NOTE: if the {@link Pipeline} contains an {@link IsBounded#UNBOUNDED unbounded} + * {@link PCollection}, and the {@link PipelineRunner} was created with + * {@link InProcessPipelineOptions#isShutdownUnboundedProducersWithMaxWatermark()} set to false, + * this method will never return. + * + * See also {@link InProcessExecutor#awaitCompletion()}. + */ + public State awaitCompletion() throws Throwable { + if (!state.isTerminal()) { + try { + executor.awaitCompletion(); + state = State.DONE; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw e; + } catch (Throwable t) { + state = State.FAILED; + throw t; + } + } + return state; + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java new file mode 100644 index 0000000000..23a8c0f506 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; +import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PValue; + +import java.util.HashSet; +import java.util.Set; + +/** + * A pipeline visitor that tracks all keyed {@link PValue PValues}. A {@link PValue} is keyed if it + * is the result of a {@link PTransform} that produces keyed outputs. A {@link PTransform} that + * produces keyed outputs is assumed to colocate output elements that share a key. + * + *

    All {@link GroupByKey} transforms, or their runner-specific implementation primitive, produce + * keyed output. + */ +// TODO: Handle Key-preserving transforms when appropriate and more aggressively make PTransforms +// unkeyed +class KeyedPValueTrackingVisitor implements PipelineVisitor { + @SuppressWarnings("rawtypes") + private final Set> producesKeyedOutputs; + private final Set keyedValues; + private boolean finalized; + + public static KeyedPValueTrackingVisitor create( + @SuppressWarnings("rawtypes") Set> producesKeyedOutputs) { + return new KeyedPValueTrackingVisitor(producesKeyedOutputs); + } + + private KeyedPValueTrackingVisitor( + @SuppressWarnings("rawtypes") Set> producesKeyedOutputs) { + this.producesKeyedOutputs = producesKeyedOutputs; + this.keyedValues = new HashSet<>(); + } + + @Override + public void enterCompositeTransform(TransformTreeNode node) { + checkState( + !finalized, + "Attempted to use a %s that has already been finalized on a pipeline (visiting node %s)", + KeyedPValueTrackingVisitor.class.getSimpleName(), + node); + } + + @Override + public void leaveCompositeTransform(TransformTreeNode node) { + checkState( + !finalized, + "Attempted to use a %s that has already been finalized on a pipeline (visiting node %s)", + KeyedPValueTrackingVisitor.class.getSimpleName(), + node); + if (node.isRootNode()) { + finalized = true; + } else if (producesKeyedOutputs.contains(node.getTransform().getClass())) { + keyedValues.addAll(node.getExpandedOutputs()); + } + } + + @Override + public void visitTransform(TransformTreeNode node) {} + + @Override + public void visitValue(PValue value, TransformTreeNode producer) { + if (producesKeyedOutputs.contains(producer.getTransform().getClass())) { + keyedValues.addAll(value.expand()); + } + } + + public Set getKeyedPValues() { + checkState( + finalized, "can't call getKeyedPValues before a Pipeline has been completely traversed"); + return keyedValues; + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java new file mode 100644 index 0000000000..d921f6cdb5 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java @@ -0,0 +1,233 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.emptyIterable; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.io.CountingInput; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.PValue; + +import org.hamcrest.Matchers; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; +import java.util.List; + +/** + * Tests for {@link ConsumerTrackingPipelineVisitor}. + */ +@RunWith(JUnit4.class) +public class ConsumerTrackingPipelineVisitorTest implements Serializable { + @Rule public transient ExpectedException thrown = ExpectedException.none(); + + private transient TestPipeline p = TestPipeline.create(); + private transient ConsumerTrackingPipelineVisitor visitor = new ConsumerTrackingPipelineVisitor(); + + @Test + public void getViewsReturnsViews() { + PCollectionView> listView = + p.apply("listCreate", Create.of("foo", "bar")) + .apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) + throws Exception { + c.output(Integer.toString(c.element().length())); + } + })) + .apply(View.asList()); + PCollectionView singletonView = + p.apply("singletonCreate", Create.of(1, 2, 3)).apply(View.asSingleton()); + p.traverseTopologically(visitor); + assertThat( + visitor.getViews(), + Matchers.>containsInAnyOrder(listView, singletonView)); + } + + @Test + public void getRootTransformsContainsPBegins() { + PCollection created = p.apply(Create.of("foo", "bar")); + PCollection counted = p.apply(CountingInput.upTo(1234L)); + PCollection unCounted = p.apply(CountingInput.unbounded()); + p.traverseTopologically(visitor); + assertThat( + visitor.getRootTransforms(), + Matchers.>containsInAnyOrder( + created.getProducingTransformInternal(), + counted.getProducingTransformInternal(), + unCounted.getProducingTransformInternal())); + } + + @Test + public void getRootTransformsContainsEmptyFlatten() { + PCollection empty = + PCollectionList.empty(p).apply(Flatten.pCollections()); + p.traverseTopologically(visitor); + assertThat( + visitor.getRootTransforms(), + Matchers.>containsInAnyOrder( + empty.getProducingTransformInternal())); + } + + @Test + public void getValueToConsumersSucceeds() { + PCollection created = p.apply(Create.of("1", "2", "3")); + PCollection transformed = + created.apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) + throws Exception { + c.output(Integer.toString(c.element().length())); + } + })); + + PCollection flattened = + PCollectionList.of(created).and(transformed).apply(Flatten.pCollections()); + + p.traverseTopologically(visitor); + + assertThat( + visitor.getValueToConsumers().get(created), + Matchers.>containsInAnyOrder( + transformed.getProducingTransformInternal(), + flattened.getProducingTransformInternal())); + assertThat( + visitor.getValueToConsumers().get(transformed), + Matchers.>containsInAnyOrder( + flattened.getProducingTransformInternal())); + assertThat(visitor.getValueToConsumers().get(flattened), emptyIterable()); + } + + @Test + public void getUnfinalizedPValuesContainsDanglingOutputs() { + PCollection created = p.apply(Create.of("1", "2", "3")); + PCollection transformed = + created.apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) + throws Exception { + c.output(Integer.toString(c.element().length())); + } + })); + + p.traverseTopologically(visitor); + assertThat(visitor.getUnfinalizedPValues(), Matchers.contains(transformed)); + } + + @Test + public void getUnfinalizedPValuesEmpty() { + p.apply(Create.of("1", "2", "3")) + .apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) + throws Exception { + c.output(Integer.toString(c.element().length())); + } + })) + .apply( + new PTransform() { + @Override + public PDone apply(PInput input) { + return PDone.in(input.getPipeline()); + } + }); + + p.traverseTopologically(visitor); + assertThat(visitor.getUnfinalizedPValues(), emptyIterable()); + } + + @Test + public void traverseMultipleTimesThrows() { + p.apply(Create.of(1, 2, 3)); + + p.traverseTopologically(visitor); + thrown.expect(IllegalStateException.class); + thrown.expectMessage(ConsumerTrackingPipelineVisitor.class.getSimpleName()); + thrown.expectMessage("is finalized"); + p.traverseTopologically(visitor); + } + + @Test + public void traverseIndependentPathsSucceeds() { + p.apply("left", Create.of(1, 2, 3)); + p.apply("right", Create.of("foo", "bar", "baz")); + + p.traverseTopologically(visitor); + } + + @Test + public void getRootTransformsWithoutVisitingThrows() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("completely traversed"); + thrown.expectMessage("getRootTransforms"); + visitor.getRootTransforms(); + } + @Test + public void getStepNamesWithoutVisitingThrows() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("completely traversed"); + thrown.expectMessage("getStepNames"); + visitor.getStepNames(); + } + @Test + public void getUnfinalizedPValuesWithoutVisitingThrows() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("completely traversed"); + thrown.expectMessage("getUnfinalizedPValues"); + visitor.getUnfinalizedPValues(); + } + + @Test + public void getValueToConsumersWithoutVisitingThrows() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("completely traversed"); + thrown.expectMessage("getValueToConsumers"); + visitor.getValueToConsumers(); + } + + @Test + public void getViewsWithoutVisitingThrows() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("completely traversed"); + thrown.expectMessage("getViews"); + visitor.getViews(); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java new file mode 100644 index 0000000000..adb64cd625 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessPipelineResult; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.MapElements; +import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; + +/** + * Tests for basic {@link InProcessPipelineRunner} functionality. + */ +@RunWith(JUnit4.class) +public class InProcessPipelineRunnerTest implements Serializable { + @Test + public void wordCountShouldSucceed() throws Throwable { + Pipeline p = getPipeline(); + + PCollection> counts = + p.apply(Create.of("foo", "bar", "foo", "baz", "bar", "foo")) + .apply(MapElements.via(new SimpleFunction() { + @Override + public String apply(String input) { + return input; + } + })) + .apply(Count.perElement()); + PCollection countStrs = + counts.apply(MapElements.via(new SimpleFunction, String>() { + @Override + public String apply(KV input) { + String str = String.format("%s: %s", input.getKey(), input.getValue()); + return str; + } + })); + + DataflowAssert.that(countStrs).containsInAnyOrder("baz: 1", "bar: 2", "foo: 3"); + + InProcessPipelineResult result = ((InProcessPipelineResult) p.run()); + result.awaitCompletion(); + } + + private Pipeline getPipeline() { + PipelineOptions opts = PipelineOptionsFactory.create(); + opts.setRunner(InProcessPipelineRunner.class); + + Pipeline p = Pipeline.create(opts); + return p; + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java new file mode 100644 index 0000000000..0aaccc2848 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.IterableCoder; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.Keys; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableSet; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Collections; +import java.util.Set; + +/** + * Tests for {@link KeyedPValueTrackingVisitor}. + */ +@RunWith(JUnit4.class) +public class KeyedPValueTrackingVisitorTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + private KeyedPValueTrackingVisitor visitor; + private Pipeline p; + + @Before + public void setup() { + PipelineOptions options = PipelineOptionsFactory.create(); + + p = Pipeline.create(options); + @SuppressWarnings("rawtypes") + Set> producesKeyed = + ImmutableSet.>of(PrimitiveKeyer.class, CompositeKeyer.class); + visitor = KeyedPValueTrackingVisitor.create(producesKeyed); + } + + @Test + public void primitiveProducesKeyedOutputUnkeyedInputKeyedOutput() { + PCollection keyed = + p.apply(Create.of(1, 2, 3)).apply(new PrimitiveKeyer()); + + p.traverseTopologically(visitor); + assertThat(visitor.getKeyedPValues(), hasItem(keyed)); + } + + @Test + public void primitiveProducesKeyedOutputKeyedInputKeyedOutut() { + PCollection keyed = + p.apply(Create.of(1, 2, 3)) + .apply("firstKey", new PrimitiveKeyer()) + .apply("secondKey", new PrimitiveKeyer()); + + p.traverseTopologically(visitor); + assertThat(visitor.getKeyedPValues(), hasItem(keyed)); + } + + @Test + public void compositeProducesKeyedOutputUnkeyedInputKeyedOutput() { + PCollection keyed = + p.apply(Create.of(1, 2, 3)).apply(new CompositeKeyer()); + + p.traverseTopologically(visitor); + assertThat(visitor.getKeyedPValues(), hasItem(keyed)); + } + + @Test + public void compositeProducesKeyedOutputKeyedInputKeyedOutut() { + PCollection keyed = + p.apply(Create.of(1, 2, 3)) + .apply("firstKey", new CompositeKeyer()) + .apply("secondKey", new CompositeKeyer()); + + p.traverseTopologically(visitor); + assertThat(visitor.getKeyedPValues(), hasItem(keyed)); + } + + + @Test + public void noInputUnkeyedOutput() { + PCollection>> unkeyed = + p.apply( + Create.of(KV.>of(-1, Collections.emptyList())) + .withCoder(KvCoder.of(VarIntCoder.of(), IterableCoder.of(VoidCoder.of())))); + + p.traverseTopologically(visitor); + assertThat(visitor.getKeyedPValues(), not(hasItem(unkeyed))); + } + + @Test + public void keyedInputNotProducesKeyedOutputUnkeyedOutput() { + PCollection onceKeyed = + p.apply(Create.of(1, 2, 3)) + .apply(new PrimitiveKeyer()) + .apply(ParDo.of(new IdentityFn())); + + p.traverseTopologically(visitor); + assertThat(visitor.getKeyedPValues(), not(hasItem(onceKeyed))); + } + + @Test + public void unkeyedInputNotProducesKeyedOutputUnkeyedOutput() { + PCollection unkeyed = + p.apply(Create.of(1, 2, 3)).apply(ParDo.of(new IdentityFn())); + + p.traverseTopologically(visitor); + assertThat(visitor.getKeyedPValues(), not(hasItem(unkeyed))); + } + + @Test + public void traverseMultipleTimesThrows() { + p.apply( + Create.>of( + KV.of(1, (Void) null), KV.of(2, (Void) null), KV.of(3, (Void) null)) + .withCoder(KvCoder.of(VarIntCoder.of(), VoidCoder.of()))) + .apply(GroupByKey.create()) + .apply(Keys.create()); + + p.traverseTopologically(visitor); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage("already been finalized"); + thrown.expectMessage(KeyedPValueTrackingVisitor.class.getSimpleName()); + p.traverseTopologically(visitor); + } + + @Test + public void getKeyedPValuesBeforeTraverseThrows() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("completely traversed"); + thrown.expectMessage("getKeyedPValues"); + visitor.getKeyedPValues(); + } + + private static class PrimitiveKeyer extends PTransform, PCollection> { + @Override + public PCollection apply(PCollection input) { + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), input.getWindowingStrategy(), input.isBounded()) + .setCoder(input.getCoder()); + } + } + + private static class CompositeKeyer extends PTransform, PCollection> { + @Override + public PCollection apply(PCollection input) { + return input.apply(new PrimitiveKeyer()).apply(ParDo.of(new IdentityFn())); + } + } + + private static class IdentityFn extends DoFn { + @Override + public void processElement(DoFn.ProcessContext c) throws Exception { + c.output(c.element()); + } + } +} From 3f739326f89d4ad5823ea1f1180c815439140665 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 18 Mar 2016 15:20:49 -0700 Subject: [PATCH 278/751] Improve PipelineOptionsFactoryTest Currently the test uses the literal string for the default runner and available runners. Instead, refer to the default runner class and extract the simple name from that class. Automatically figure out portions of the error message for unknown runners. --- .../options/PipelineOptionsFactoryTest.java | 39 +++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java index 045a8ad0f2..8b5dff5397 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.options; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -53,10 +54,14 @@ import java.io.PrintStream; import java.util.List; import java.util.Map; +import java.util.Set; /** Tests for {@link PipelineOptionsFactory}. */ @RunWith(JUnit4.class) public class PipelineOptionsFactoryTest { + private static final Class> DEFAULT_RUNNER_CLASS = + DirectPipelineRunner.class; + @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule public TestRule restoreSystemProperties = new RestoreSystemProperties(); @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(PipelineOptionsFactory.class); @@ -68,8 +73,9 @@ public void testAutomaticRegistrationOfPipelineOptions() { @Test public void testAutomaticRegistrationOfRunners() { - assertEquals(DirectPipelineRunner.class, - PipelineOptionsFactory.getRegisteredRunners().get("DirectPipelineRunner")); + assertEquals( + DEFAULT_RUNNER_CLASS, + PipelineOptionsFactory.getRegisteredRunners().get(DEFAULT_RUNNER_CLASS.getSimpleName())); } @Test @@ -840,9 +846,14 @@ public void testSettingRunnerFullName() { public void testSettingUnknownRunner() { String[] args = new String[] {"--runner=UnknownRunner"}; expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unknown 'runner' specified 'UnknownRunner', supported " - + "pipeline runners [BlockingDataflowPipelineRunner, DataflowPipelineRunner, " - + "DirectPipelineRunner]"); + expectedException.expectMessage( + "Unknown 'runner' specified 'UnknownRunner', supported " + "pipeline runners"); + Set registeredRunners = PipelineOptionsFactory.getRegisteredRunners().keySet(); + assertThat(registeredRunners, hasItem(DEFAULT_RUNNER_CLASS.getSimpleName())); + for (String registeredRunner : registeredRunners) { + expectedException.expectMessage(registeredRunner); + } + PipelineOptionsFactory.fromArgs(args).create(); } @@ -927,13 +938,19 @@ public void testUsingArgumentStartingWithIllegalCharacterIsIgnoredWithoutStrictP @Test public void testEmptyArgumentIsIgnored() { - String[] args = new String[] {"", "--diskSizeGb=100", "", "", "--runner=DirectPipelineRunner"}; + String[] args = + new String[] { + "", "--diskSizeGb=100", "", "", "--runner=" + DEFAULT_RUNNER_CLASS.getSimpleName() + }; PipelineOptionsFactory.fromArgs(args).create(); } @Test public void testNullArgumentIsIgnored() { - String[] args = new String[] {"--diskSizeGb=100", null, null, "--runner=DirectPipelineRunner"}; + String[] args = + new String[] { + "--diskSizeGb=100", null, null, "--runner=" + DEFAULT_RUNNER_CLASS.getSimpleName() + }; PipelineOptionsFactory.fromArgs(args).create(); } @@ -985,7 +1002,7 @@ public void testSpecificHelpAsArgument() { String output = new String(baos.toByteArray()); assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: DirectPipelineRunner")); + assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); assertThat(output, containsString("The pipeline runner that will be used to execute the pipeline.")); } @@ -1000,7 +1017,7 @@ public void testSpecificHelpAsArgumentWithSimpleClassName() { String output = new String(baos.toByteArray()); assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: DirectPipelineRunner")); + assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); assertThat(output, containsString("The pipeline runner that will be used to execute the pipeline.")); } @@ -1015,7 +1032,7 @@ public void testSpecificHelpAsArgumentWithClassNameSuffix() { String output = new String(baos.toByteArray()); assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: DirectPipelineRunner")); + assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); assertThat(output, containsString("The pipeline runner that will be used to execute the pipeline.")); } @@ -1096,7 +1113,7 @@ public void testProgrammaticPrintHelpForSpecificType() { String output = new String(baos.toByteArray()); assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: DirectPipelineRunner")); + assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); assertThat(output, containsString("The pipeline runner that will be used to execute the pipeline.")); } From 39e70e695ee268816d92650d39a2647573b2832b Mon Sep 17 00:00:00 2001 From: bchambers Date: Tue, 8 Mar 2016 10:36:27 -0800 Subject: [PATCH 279/751] Print link to debugger UI After successfully registering a debuggee, print a link to go to the appropriate UI. --- .../dataflow/sdk/runners/DataflowPipelineRunner.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 29f9b85cc5..972cc5ebdc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -424,6 +424,12 @@ private PCollection applyWindow( return super.apply(new AssignWindows<>(transform), input); } + private String debuggerMessage(String projectId, String uniquifier) { + return String.format("To debug your job, visit Google Cloud Debugger at: " + + "https://console.developers.google.com/debug?project=%s&dbgee=%s", + projectId, uniquifier); + } + private void maybeRegisterDebuggee(DataflowPipelineOptions options, String uniquifier) { if (!options.getEnableCloudDebugger()) { return; @@ -436,6 +442,8 @@ private void maybeRegisterDebuggee(DataflowPipelineOptions options, String uniqu Clouddebugger debuggerClient = Transport.newClouddebuggerClient(options).build(); Debuggee debuggee = registerDebuggee(debuggerClient, uniquifier); options.setDebuggee(debuggee); + + System.out.println(debuggerMessage(options.getProject(), debuggee.getUniquifier())); } private Debuggee registerDebuggee(Clouddebugger debuggerClient, String uniquifier) { From d3348595c63a75c11dfaa1f19d0643858c8e26a2 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 21 Mar 2016 17:00:35 -0700 Subject: [PATCH 280/751] Schedule roots less aggressively The excess scheduling of known-empty bundles can consume excessive resources. --- .../ExecutorServiceParallelExecutor.java | 76 +++++++++--- .../inprocess/InMemoryWatermarkManager.java | 16 --- .../inprocess/InProcessEvaluationContext.java | 46 ++++++-- .../InProcessEvaluationContextTest.java | 110 +++++++++++++++++- 4 files changed, 200 insertions(+), 48 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index c72a1155f5..68a1b8c167 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -304,8 +304,8 @@ public void run() { visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); } } - fireTimers(); - mightNeedMoreWork(); + boolean timersFired = fireTimers(); + addWorkIfNecessary(timersFired); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.error("Monitor died due to being interrupted"); @@ -326,8 +326,12 @@ public void run() { } } - private void fireTimers() throws Exception { + /** + * Fires any available timers. Returns true if at least one timer was fired. + */ + private boolean fireTimers() throws Exception { try { + boolean firedTimers = false; for (Map.Entry, Map> transformTimers : evaluationContext.extractFiredTimers().entrySet()) { AppliedPTransform transform = transformTimers.getKey(); @@ -346,9 +350,11 @@ private void fireTimers() throws Exception { .add(WindowedValue.valueInEmptyWindows(work)) .commit(Instant.now()); scheduleConsumption(transform, bundle, new TimerCompletionCallback(delivery)); + firedTimers = true; } } } + return firedTimers; } catch (Exception e) { LOG.error("Internal Error while delivering timers", e); throw e; @@ -367,26 +373,58 @@ private boolean shouldShutdown() { return false; } - private void mightNeedMoreWork() { - synchronized (scheduledExecutors) { - for (TransformExecutor executor : scheduledExecutors.keySet()) { - Thread thread = executor.getThread(); - if (thread != null) { - switch (thread.getState()) { - case BLOCKED: - case WAITING: - case TERMINATED: - case TIMED_WAITING: - break; - default: - return; - } - } + /** + * If all active {@link TransformExecutor TransformExecutors} are in a blocked state, + * add more work from root nodes that may have additional work. This ensures that if a pipeline + * has elements available from the root nodes it will add those elements when necessary. + */ + private void addWorkIfNecessary(boolean firedTimers) { + // If any timers have fired, they will add more work; We don't need to add more + if (firedTimers) { + return; + } + for (TransformExecutor executor : scheduledExecutors.keySet()) { + if (!isExecutorBlocked(executor)) { + // We have at least one executor that can proceed without adding additional work + return; } } // All current TransformExecutors are blocked; add more work from the roots. for (AppliedPTransform root : rootNodes) { - scheduleConsumption(root, null, defaultCompletionCallback); + if (!evaluationContext.isDone(root)) { + scheduleConsumption(root, null, defaultCompletionCallback); + } + } + } + + /** + * Return true if the provided executor might make more progress if no action is taken. + * + *

    May return false even if all executor threads are currently blocked or cleaning up, as + * these can cause more work to be scheduled. If this does not occur, after these calls + * terminate, future calls will return true if all executors are waiting. + */ + private boolean isExecutorBlocked(TransformExecutor executor) { + Thread thread = executor.getThread(); + if (thread == null) { + return false; + } + switch (thread.getState()) { + case TERMINATED: + throw new IllegalStateException(String.format( + "Unexpectedly encountered a Terminated TransformExecutor %s", executor)); + case WAITING: + case TIMED_WAITING: + // The thread is waiting for some external input. Adding more work may cause the thread + // to stop waiting (e.g. the thread is waiting on an unbounded side input) + return true; + case BLOCKED: + // The executor is blocked on acquisition of a java monitor. This usually means it is + // making a call to the EvaluationContext, but not a model-blocking call - and will + // eventually complete, at which point we may reevaluate. + default: + // NEW and RUNNABLE threads can make progress + return false; } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 094526d962..a9a62a6aa3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -861,22 +861,6 @@ private void updatePending( return allTimers; } - /** - * Returns true if, for any {@link TransformWatermarks} returned by - * {@link #getWatermarks(AppliedPTransform)}, the output watermark will be equal to - * {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. - */ - public boolean allWatermarksAtPositiveInfinity() { - for (Map.Entry, TransformWatermarks> watermarksEntry : - transformToWatermarks.entrySet()) { - Instant endOfTime = THE_END_OF_TIME.get(); - if (watermarksEntry.getValue().getOutputWatermark().isBefore(endOfTime)) { - return false; - } - } - return true; - } - /** * A (key, Instant) pair that holds the watermark. Holds are per-key, but the watermark is global, * and as such the watermark manager must track holds and the release of holds on a per-key basis. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 2908fba818..4aeb0d3b2a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -357,27 +357,49 @@ public CounterSet getCounters() { } /** - * Returns true if all steps are done. + * Returns true if the step will not produce additional output. + * + *

    If the provided transform produces only {@link IsBounded#BOUNDED} + * {@link PCollection PCollections}, returns true if the watermark is at + * {@link BoundedWindow#TIMESTAMP_MAX_VALUE positive infinity}. + * + *

    If the provided transform produces any {@link IsBounded#UNBOUNDED} + * {@link PCollection PCollections}, returns the value of + * {@link InProcessPipelineOptions#isShutdownUnboundedProducersWithMaxWatermark()}. */ - public boolean isDone() { - if (!options.isShutdownUnboundedProducersWithMaxWatermark() && containsUnboundedPCollection()) { + public boolean isDone(AppliedPTransform transform) { + // if the PTransform's watermark isn't at the max value, it isn't done + if (watermarkManager + .getWatermarks(transform) + .getOutputWatermark() + .isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE)) { return false; } - if (!watermarkManager.allWatermarksAtPositiveInfinity()) { - return false; + // If the PTransform has any unbounded outputs, and unbounded producers should not be shut down, + // the PTransform may produce additional output. It is not done. + for (PValue output : transform.getOutput().expand()) { + if (output instanceof PCollection) { + IsBounded bounded = ((PCollection) output).isBounded(); + if (bounded.equals(IsBounded.UNBOUNDED) + && !options.isShutdownUnboundedProducersWithMaxWatermark()) { + return false; + } + } } + // The PTransform's watermark was at positive infinity and all of its outputs are known to be + // done. It is done. return true; } - private boolean containsUnboundedPCollection() { + /** + * Returns true if all steps are done. + */ + public boolean isDone() { for (AppliedPTransform transform : stepNames.keySet()) { - for (PValue value : transform.getInput().expand()) { - if (value instanceof PCollection - && ((PCollection) value).isBounded().equals(IsBounded.UNBOUNDED)) { - return true; - } + if (!isDone(transform)) { + return false; } } - return false; + return true; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index 149096040a..1a0f5053f4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -24,12 +24,14 @@ import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.io.CountingInput; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -58,6 +60,7 @@ import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import org.hamcrest.Matchers; import org.joda.time.Instant; @@ -80,25 +83,33 @@ public class InProcessEvaluationContextTest { private TestPipeline p; private InProcessEvaluationContext context; + private PCollection created; private PCollection> downstream; private PCollectionView> view; + private PCollection unbounded; + @Before public void setup() { InProcessPipelineRunner runner = InProcessPipelineRunner.fromOptions(PipelineOptionsFactory.create()); + p = TestPipeline.create(); + created = p.apply(Create.of(1, 2, 3)); downstream = created.apply(WithKeys.of("foo")); view = created.apply(View.asIterable()); + unbounded = p.apply(CountingInput.unbounded()); Collection> rootTransforms = - ImmutableList.>of(created.getProducingTransformInternal()); + ImmutableList.>of( + created.getProducingTransformInternal(), unbounded.getProducingTransformInternal()); Map>> valueToConsumers = new HashMap<>(); valueToConsumers.put( created, ImmutableList.>of( downstream.getProducingTransformInternal(), view.getProducingTransformInternal())); + valueToConsumers.put(unbounded, ImmutableList.>of()); valueToConsumers.put(downstream, ImmutableList.>of()); valueToConsumers.put(view, ImmutableList.>of()); @@ -106,6 +117,7 @@ public void setup() { stepNames.put(created.getProducingTransformInternal(), "s1"); stepNames.put(downstream.getProducingTransformInternal(), "s2"); stepNames.put(view.getProducingTransformInternal(), "s3"); + stepNames.put(unbounded.getProducingTransformInternal(), "s4"); Collection> views = ImmutableList.>of(view); context = InProcessEvaluationContext.create( @@ -421,6 +433,102 @@ public void createKeyedBundleKeyed() { assertThat(keyedBundle.getKey(), Matchers.equalTo("foo")); } + @Test + public void isDoneWithUnboundedPCollectionAndShutdown() { + context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(true); + assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(false)); + + context.handleResult( + null, + ImmutableList.of(), + StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); + assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(true)); + } + + @Test + public void isDoneWithUnboundedPCollectionAndNotShutdown() { + context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(false); + assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(false)); + + context.handleResult( + null, + ImmutableList.of(), + StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); + assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(false)); + } + + @Test + public void isDoneWithOnlyBoundedPCollections() { + context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(false); + assertThat(context.isDone(created.getProducingTransformInternal()), is(false)); + + context.handleResult( + null, + ImmutableList.of(), + StepTransformResult.withoutHold(created.getProducingTransformInternal()).build()); + assertThat(context.isDone(created.getProducingTransformInternal()), is(true)); + } + + @Test + public void isDoneWithPartiallyDone() { + context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(true); + assertThat(context.isDone(), is(false)); + + UncommittedBundle rootBundle = context.createRootBundle(created); + rootBundle.add(WindowedValue.valueInGlobalWindow(1)); + Iterable> handleResult = + context.handleResult( + null, + ImmutableList.of(), + StepTransformResult.withoutHold(created.getProducingTransformInternal()) + .addOutput(rootBundle) + .build()); + @SuppressWarnings("unchecked") + CommittedBundle committedBundle = + (CommittedBundle) Iterables.getOnlyElement(handleResult); + context.handleResult( + null, + ImmutableList.of(), + StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); + context.handleResult( + committedBundle, + ImmutableList.of(), + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build()); + assertThat(context.isDone(), is(false)); + + context.handleResult( + committedBundle, + ImmutableList.of(), + StepTransformResult.withoutHold(view.getProducingTransformInternal()).build()); + assertThat(context.isDone(), is(true)); + } + + @Test + public void isDoneWithUnboundedAndNotShutdown() { + context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(false); + assertThat(context.isDone(), is(false)); + + context.handleResult( + null, + ImmutableList.of(), + StepTransformResult.withoutHold(created.getProducingTransformInternal()).build()); + context.handleResult( + null, + ImmutableList.of(), + StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); + context.handleResult( + context.createRootBundle(created).commit(Instant.now()), + ImmutableList.of(), + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build()); + assertThat(context.isDone(), is(false)); + + context.handleResult( + context.createRootBundle(created).commit(Instant.now()), + ImmutableList.of(), + StepTransformResult.withoutHold(view.getProducingTransformInternal()).build()); + assertThat(context.isDone(), is(false)); + } + private static class TestBoundedWindow extends BoundedWindow { private final Instant ts; From cf3638e16f1e62f224f4bbcc5975de775688c229 Mon Sep 17 00:00:00 2001 From: Pei He Date: Mon, 29 Feb 2016 15:30:08 -0800 Subject: [PATCH 281/751] [BEAM-80] Fix the Unexpected StateTag error in convertToBagTagInternal It adds asBagTag() in KeyedCombiningValueWithContextStateTag, and allows convertToBagTagInternal accept it. --- .../dataflow/sdk/util/CombineFnUtil.java | 57 ++++++++++++++++ .../dataflow/sdk/util/state/StateTags.java | 24 +++++-- .../dataflow/sdk/util/state/StateTagTest.java | 65 +++++++++++++++++++ 3 files changed, 139 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java index 6201e6e7bb..d9744800b9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java @@ -19,7 +19,10 @@ import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderRegistry; +import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.GlobalCombineFn; +import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.util.state.StateContext; @@ -46,6 +49,60 @@ public class CombineFnUtil { return new NonSerializableBoundedKeyedCombineFn<>(combineFn, context); } + /** + * Return a {@link CombineFnWithContext} from the given {@link GlobalCombineFn}. + */ + public static + CombineFnWithContext toFnWithContext( + GlobalCombineFn globalCombineFn) { + if (globalCombineFn instanceof CombineFnWithContext) { + @SuppressWarnings("unchecked") + CombineFnWithContext combineFnWithContext = + (CombineFnWithContext) globalCombineFn; + return combineFnWithContext; + } else { + @SuppressWarnings("unchecked") + final CombineFn combineFn = + (CombineFn) globalCombineFn; + return new CombineFnWithContext() { + @Override + public AccumT createAccumulator(Context c) { + return combineFn.createAccumulator(); + } + @Override + public AccumT addInput(AccumT accumulator, InputT input, Context c) { + return combineFn.addInput(accumulator, input); + } + @Override + public AccumT mergeAccumulators(Iterable accumulators, Context c) { + return combineFn.mergeAccumulators(accumulators); + } + @Override + public OutputT extractOutput(AccumT accumulator, Context c) { + return combineFn.extractOutput(accumulator); + } + @Override + public AccumT compact(AccumT accumulator, Context c) { + return combineFn.compact(accumulator); + } + @Override + public OutputT defaultValue() { + return combineFn.defaultValue(); + } + @Override + public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) + throws CannotProvideCoderException { + return combineFn.getAccumulatorCoder(registry, inputCoder); + } + @Override + public Coder getDefaultOutputCoder( + CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { + return combineFn.getDefaultOutputCoder(registry, inputCoder); + } + }; + } + } + private static class NonSerializableBoundedKeyedCombineFn extends KeyedCombineFn { private final KeyedCombineFnWithContext combineFn; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java index 0cbaa52369..ec9a78feab 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java @@ -181,15 +181,21 @@ public static StateTag makeSystemTagInterna public static StateTag> convertToBagTagInternal( StateTag> combiningTag) { - if (!(combiningTag instanceof KeyedCombiningValueStateTag)) { + if (combiningTag instanceof KeyedCombiningValueStateTag) { + // Checked above; conversion to a bag tag depends on the provided tag being one of those + // created via the factory methods in this class. + @SuppressWarnings("unchecked") + KeyedCombiningValueStateTag typedTag = + (KeyedCombiningValueStateTag) combiningTag; + return typedTag.asBagTag(); + } else if (combiningTag instanceof KeyedCombiningValueWithContextStateTag) { + @SuppressWarnings("unchecked") + KeyedCombiningValueWithContextStateTag typedTag = + (KeyedCombiningValueWithContextStateTag) combiningTag; + return typedTag.asBagTag(); + } else { throw new IllegalArgumentException("Unexpected StateTag " + combiningTag); } - // Checked above; conversion to a bag tag depends on the provided tag being one of those - // created via the factory methods in this class. - @SuppressWarnings("unchecked") - KeyedCombiningValueStateTag typedTag = - (KeyedCombiningValueStateTag) combiningTag; - return typedTag.asBagTag(); } private static class StructuredId implements Serializable { @@ -413,6 +419,10 @@ public StateTag> asKind( return new KeyedCombiningValueWithContextStateTag<>( id.asKind(kind), accumCoder, combineFn); } + + private StateTag> asBagTag() { + return new BagStateTag(id, accumCoder); + } } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java index 47f7224e90..b4ff36fae3 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java @@ -20,12 +20,15 @@ import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderRegistry; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.transforms.Combine.Holder; import com.google.cloud.dataflow.sdk.transforms.Max; import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; import com.google.cloud.dataflow.sdk.transforms.Min; import com.google.cloud.dataflow.sdk.transforms.Min.MinIntegerFn; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; +import com.google.cloud.dataflow.sdk.util.CombineFnUtil; import org.junit.Test; import org.junit.runner.RunWith; @@ -80,6 +83,7 @@ public void testWatermarkBagEquality() { assertEquals(bar, bar2); } + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testCombiningValueEquality() { MaxIntegerFn maxFn = new Max.MaxIntegerFn(); @@ -96,13 +100,74 @@ public void testCombiningValueEquality() { // Same name, coder and combineFn assertEquals(fooCoder1Max1, fooCoder1Max2); + assertEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max2)); + + // Different combineFn, but we treat them as equal since we only serialize the bits. + assertEquals(fooCoder1Max1, fooCoder1Min); + assertEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) fooCoder1Min)); + + // Different input coder coder. + assertNotEquals(fooCoder1Max1, fooCoder2Max); + assertNotEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) fooCoder2Max)); + + // These StateTags have different IDs. + assertNotEquals(fooCoder1Max1, barCoder1Max); + assertNotEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) barCoder1Max)); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testCombiningValueWithContextEquality() { + CoderRegistry registry = new CoderRegistry(); + registry.registerStandardCoders(); + + MaxIntegerFn maxFn = new Max.MaxIntegerFn(); + MinIntegerFn minFn = new Min.MinIntegerFn(); + + Coder> accum1 = maxFn.getAccumulatorCoder(registry, VarIntCoder.of()); + Coder> accum2 = minFn.getAccumulatorCoder(registry, BigEndianIntegerCoder.of()); + + StateTag fooCoder1Max1 = StateTags.keyedCombiningValueWithContext( + "foo", accum1, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); + StateTag fooCoder1Max2 = StateTags.keyedCombiningValueWithContext( + "foo", accum1, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); + StateTag fooCoder1Min = StateTags.keyedCombiningValueWithContext( + "foo", accum1, CombineFnUtil.toFnWithContext(minFn).asKeyedFn()); + + StateTag fooCoder2Max = StateTags.keyedCombiningValueWithContext( + "foo", accum2, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); + StateTag barCoder1Max = StateTags.keyedCombiningValueWithContext( + "bar", accum1, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); + + // Same name, coder and combineFn + assertEquals(fooCoder1Max1, fooCoder1Max2); + assertEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max2)); // Different combineFn, but we treat them as equal since we only serialize the bits. assertEquals(fooCoder1Max1, fooCoder1Min); + assertEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) fooCoder1Min)); // Different input coder coder. assertNotEquals(fooCoder1Max1, fooCoder2Max); + assertNotEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) fooCoder2Max)); // These StateTags have different IDs. assertNotEquals(fooCoder1Max1, barCoder1Max); + assertNotEquals( + StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), + StateTags.convertToBagTagInternal((StateTag) barCoder1Max)); } } From ff6617f6d22c487991d7edbbf4a4b607b2b2f6ca Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 2 Mar 2016 20:45:59 -0800 Subject: [PATCH 282/751] Basic non-null checks --- .../dataflow/sdk/util/ReduceFnRunner.java | 51 ++++++++++++++++- .../dataflow/sdk/util/TriggerRunner.java | 2 + .../dataflow/sdk/util/WatermarkHold.java | 55 ++++++++++++++----- 3 files changed, 92 insertions(+), 16 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 2e2d1f6c7d..f1d45828f9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -499,6 +499,11 @@ private Collection processElement(WindowedValue value) throws Excepti directContext.timestamp(), directContext.timers(), directContext.state()); + + // At this point, if triggerRunner.shouldFire before the processValue then + // triggerRunner.shouldFire after the processValue. In other words adding values + // cannot take a trigger state from firing to non-firing. + // (We don't actually assert this since it is too slow.) } return windows; @@ -568,6 +573,11 @@ public void onTimer(TimerData timer) throws Exception { boolean isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() && timer.getTimestamp().equals(window.maxTimestamp()); if (isEndOfWindow) { + // If the window strategy trigger includes a watermark trigger then at this point + // there should be no data holds, either because we'd already cleared them on an + // earlier onTrigger, or because we just cleared them on the above emitIfAppropriate. + // We could assert this but it is very expensive. + // Since we are processing an on-time firing we should schedule the garbage collection // timer. (If getAllowedLateness is zero then the timer event will be considered a // cleanup event and handled by the above). @@ -715,8 +725,11 @@ private void onTrigger( ReduceFn.Context renamedContext, boolean isFinished) throws Exception { + Instant inputWM = timerInternals.currentInputWatermarkTime(); + Preconditions.checkNotNull(inputWM); + // Prefetch necessary states - ReadableState outputTimestampFuture = + ReadableState outputTimestampFuture = watermarkHold.extractAndRelease(renamedContext, isFinished).readLater(); ReadableState paneFuture = paneInfoTracker.getNextPaneInfo(directContext, isFinished).readLater(); @@ -729,7 +742,41 @@ private void onTrigger( // Calculate the pane info. final PaneInfo pane = paneFuture.read(); // Extract the window hold, and as a side effect clear it. - final Instant outputTimestamp = outputTimestampFuture.read(); + + WatermarkHold.OldAndNewHolds pair = outputTimestampFuture.read(); + final Instant outputTimestamp = pair.oldHold; + @Nullable Instant newHold = pair.newHold; + + if (newHold != null && inputWM != null) { + // We can't be finished yet. + Preconditions.checkState( + !isFinished, "new hold at %s but finished %s", newHold, directContext.window()); + // The hold cannot be behind the input watermark. + Preconditions.checkState( + !newHold.isBefore(inputWM), "new hold %s is before input watermark %s", newHold, inputWM); + if (newHold.isAfter(directContext.window().maxTimestamp())) { + // The hold must be for garbage collection, which can't have happened yet. + Preconditions.checkState( + newHold.isEqual( + directContext.window().maxTimestamp().plus(windowingStrategy.getAllowedLateness())), + "new hold %s should be at garbage collection for window %s plus %s", + newHold, + directContext.window(), + windowingStrategy.getAllowedLateness()); + } else { + // The hold must be for the end-of-window, which can't have happened yet. + Preconditions.checkState( + newHold.isEqual(directContext.window().maxTimestamp()), + "new hold %s should be at end of window %s", + newHold, + directContext.window()); + Preconditions.checkState( + !isEndOfWindow, + "new hold at %s for %s but this is the watermark trigger", + newHold, + directContext.window()); + } + } // Only emit a pane if it has data or empty panes are observable. if (needToEmit(isEmptyFuture.read(), isFinished, pane.getTiming())) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index dcfd03516b..8fc498112e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -172,6 +172,8 @@ public boolean shouldFire(W window, Timers timers, StateAccessor state) throw } public void onFire(W window, Timers timers, StateAccessor state) throws Exception { + // shouldFire should be false. + // However it is too expensive to assert. FinishedTriggersBitSet finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); Trigger.TriggerContext context = contextFactory.base(window, timers, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index d537ddb0e8..31e36c5ef3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -228,6 +228,7 @@ private Instant addElementHold(ReduceFn.ProcessValueContext context) Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); + Preconditions.checkNotNull(inputWM); // Only add the hold if we can be sure: // - the backend will be able to respect it @@ -287,6 +288,8 @@ private Instant addEndOfWindowHold(ReduceFn.Context context) { // by the end of window (ie the end of window is at or ahead of the input watermark). Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); + Preconditions.checkNotNull(inputWM); + String which; boolean tooLate; Instant eowHold = context.window().maxTimestamp(); @@ -329,6 +332,8 @@ private Instant addGarbageCollectionHold(ReduceFn.Context context) { Instant gcHold = context.window().maxTimestamp().plus(windowingStrategy.getAllowedLateness()); Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); + Preconditions.checkNotNull(inputWM); + WindowTracing.trace( "WatermarkHold.addGarbageCollectionHold: garbage collection at {} hold for " + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", @@ -368,6 +373,19 @@ public void onMerge(ReduceFn.OnMergeContext context) { addEndOfWindowOrGarbageCollectionHolds(context); } + /** + * Result of {@link #extractAndRelease}. + */ + public static class OldAndNewHolds { + public final Instant oldHold; + @Nullable public final Instant newHold; + + public OldAndNewHolds(Instant oldHold, @Nullable Instant newHold) { + this.oldHold = oldHold; + this.newHold = newHold; + } + } + /** * Return (a future for) the earliest hold for {@code context}. Clear all the holds after * reading, but add/restore an end-of-window or garbage collection hold if required. @@ -377,7 +395,7 @@ public void onMerge(ReduceFn.OnMergeContext context) { * elements in the current pane. If there is no such value the timestamp is the end * of the window. */ - public ReadableState extractAndRelease( + public ReadableState extractAndRelease( final ReduceFn.Context context, final boolean isFinished) { WindowTracing.debug( "extractAndRelease: for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", @@ -385,38 +403,38 @@ public ReadableState extractAndRelease( timerInternals.currentOutputWatermarkTime()); final WatermarkHoldState elementHoldState = context.state().access(elementHoldTag); final WatermarkHoldState extraHoldState = context.state().access(EXTRA_HOLD_TAG); - return new ReadableState() { + return new ReadableState() { @Override - public ReadableState readLater() { + public ReadableState readLater() { elementHoldState.readLater(); extraHoldState.readLater(); return this; } @Override - public Instant read() { + public OldAndNewHolds read() { // Read both the element and extra holds. Instant elementHold = elementHoldState.read(); Instant extraHold = extraHoldState.read(); - Instant hold; + Instant oldHold; // Find the minimum, accounting for null. if (elementHold == null) { - hold = extraHold; + oldHold = extraHold; } else if (extraHold == null) { - hold = elementHold; + oldHold = elementHold; } else if (elementHold.isBefore(extraHold)) { - hold = elementHold; + oldHold = elementHold; } else { - hold = extraHold; + oldHold = extraHold; } - if (hold == null || hold.isAfter(context.window().maxTimestamp())) { + if (oldHold == null || oldHold.isAfter(context.window().maxTimestamp())) { // If no hold (eg because all elements came in behind the output watermark), or // the hold was for garbage collection, take the end of window as the result. WindowTracing.debug( "WatermarkHold.extractAndRelease.read: clipping from {} to end of window " + "for key:{}; window:{}", - hold, context.key(), context.window()); - hold = context.window().maxTimestamp(); + oldHold, context.key(), context.window()); + oldHold = context.window().maxTimestamp(); } WindowTracing.debug("WatermarkHold.extractAndRelease.read: clearing for key:{}; window:{}", context.key(), context.window()); @@ -425,13 +443,14 @@ public Instant read() { elementHoldState.clear(); extraHoldState.clear(); + @Nullable Instant newHold = null; if (!isFinished) { // Only need to leave behind an end-of-window or garbage collection hold // if future elements will be processed. - addEndOfWindowOrGarbageCollectionHolds(context); + newHold = addEndOfWindowOrGarbageCollectionHolds(context); } - return hold; + return new OldAndNewHolds(oldHold, newHold); } }; } @@ -447,4 +466,12 @@ public void clearHolds(ReduceFn.Context context) { context.state().access(elementHoldTag).clear(); context.state().access(EXTRA_HOLD_TAG).clear(); } + + /** + * Return the current data hold, or null if none. Does not clear. For debugging only. + */ + @Nullable + public Instant getDataCurrent(ReduceFn.Context context) { + return context.state().access(elementHoldTag).read(); + } } From c2e002a73acf3b692c6cfcae8bedccdf16677a74 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Fri, 4 Mar 2016 15:16:33 -0800 Subject: [PATCH 283/751] Input watermarks can never be null. --- .../inprocess/InMemoryWatermarkManager.java | 3 ++- .../inprocess/InProcessTimerInternals.java | 1 - .../sdk/util/LateDataDroppingDoFnRunner.java | 3 +-- .../dataflow/sdk/util/PaneInfoTracker.java | 2 +- .../sdk/util/ReduceFnContextFactory.java | 1 - .../dataflow/sdk/util/ReduceFnRunner.java | 18 +++++++++--------- .../dataflow/sdk/util/TimerInternals.java | 4 ++-- .../google/cloud/dataflow/sdk/util/Timers.java | 3 +-- .../sdk/util/TriggerContextFactory.java | 1 - .../cloud/dataflow/sdk/util/WatermarkHold.java | 9 +++------ .../dataflow/sdk/io/CountingInputTest.java | 1 + .../dataflow/sdk/util/ReduceFnTester.java | 8 +++----- .../cloud/dataflow/sdk/util/TriggerTester.java | 10 ++++------ 13 files changed, 27 insertions(+), 37 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index a9a62a6aa3..c4d67db121 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -28,6 +28,7 @@ import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; +import com.google.common.base.Preconditions; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -994,7 +995,7 @@ private TransformWatermarks( * Returns the input watermark of the {@link AppliedPTransform}. */ public Instant getInputWatermark() { - return inputWatermark.get(); + return Preconditions.checkNotNull(inputWatermark.get()); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java index 06ba7b82f4..1d075c54c2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java @@ -70,7 +70,6 @@ public Instant currentSynchronizedProcessingTime() { } @Override - @Nullable public Instant currentInputWatermarkTime() { return watermarks.getInputWatermark(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java index 31927ab882..3dfa06474e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java @@ -138,8 +138,7 @@ public boolean apply(WindowedValue input) { /** Is {@code window} expired w.r.t. the garbage collection watermark? */ private boolean canDropDueToExpiredWindow(BoundedWindow window) { Instant inputWM = timerInternals.currentInputWatermarkTime(); - return inputWM != null - && window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()).isBefore(inputWM); + return window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()).isBefore(inputWM); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index a7818a30a0..9fa36b0eb7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -103,7 +103,7 @@ private PaneInfo describePane( boolean onlyEarlyPanesSoFar = previousTiming == null || previousTiming == Timing.EARLY; // True is the input watermark hasn't passed the window's max timestamp. - boolean isEarlyForInput = inputWM == null || !inputWM.isAfter(windowMaxTimestamp); + boolean isEarlyForInput = !inputWM.isAfter(windowMaxTimestamp); Timing timing; if (isLateForOutput || !onlyEarlyPanesSoFar) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index bdbaf1098e..7649d520bb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -146,7 +146,6 @@ public Instant currentSynchronizedProcessingTime() { } @Override - @Nullable public Instant currentEventTime() { return timerInternals.currentInputWatermarkTime(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index f1d45828f9..560d8ecd44 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -537,6 +537,10 @@ public void onTimer(TimerData timer) throws Exception { "ReduceFnRunner.onTimer: Note that timer {} is for non-ACTIVE window {}", timer, window); } + // If this is an end-of-window timer then, we need to set a GC timer + boolean isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() + && timer.getTimestamp().equals(window.maxTimestamp()); + // If this is a garbage collection timer then we should trigger and garbage collect the window. Instant cleanupTime = window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()); boolean isGarbageCollection = @@ -553,7 +557,7 @@ public void onTimer(TimerData timer) throws Exception { // We need to call onTrigger to emit the final pane if required. // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, // and the watermark has passed the end of the window. - onTrigger(directContext, renamedContext, true/* isFinished */); + onTrigger(directContext, renamedContext, true/* isFinished */, isEndOfWindow); } // Cleanup flavor B: Clear all the remaining state for this window since we'll never @@ -569,9 +573,6 @@ public void onTimer(TimerData timer) throws Exception { emitIfAppropriate(directContext, renamedContext); } - // If this is an end-of-window timer then, we need to set a GC timer - boolean isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() - && timer.getTimestamp().equals(window.maxTimestamp()); if (isEndOfWindow) { // If the window strategy trigger includes a watermark trigger then at this point // there should be no data holds, either because we'd already cleared them on an @@ -676,7 +677,7 @@ private void emitIfAppropriate(ReduceFn.Context directCon // Run onTrigger to produce the actual pane contents. // As a side effect it will clear all element holds, but not necessarily any // end-of-window or garbage collection holds. - onTrigger(directContext, renamedContext, isFinished); + onTrigger(directContext, renamedContext, isFinished, false /*isEndOfWindow*/); // Now that we've triggered, the pane is empty. nonEmptyPanes.clearPane(renamedContext.state()); @@ -723,10 +724,9 @@ private boolean needToEmit(boolean isEmpty, boolean isFinished, PaneInfo.Timing private void onTrigger( final ReduceFn.Context directContext, ReduceFn.Context renamedContext, - boolean isFinished) + boolean isFinished, boolean isEndOfWindow) throws Exception { Instant inputWM = timerInternals.currentInputWatermarkTime(); - Preconditions.checkNotNull(inputWM); // Prefetch necessary states ReadableState outputTimestampFuture = @@ -747,7 +747,7 @@ private void onTrigger( final Instant outputTimestamp = pair.oldHold; @Nullable Instant newHold = pair.newHold; - if (newHold != null && inputWM != null) { + if (newHold != null) { // We can't be finished yet. Preconditions.checkState( !isFinished, "new hold at %s but finished %s", newHold, directContext.window()); @@ -825,7 +825,7 @@ private Instant scheduleEndOfWindowOrGarbageCollectionTimer( Instant endOfWindow = directContext.window().maxTimestamp(); Instant fireTime; String which; - if (inputWM != null && endOfWindow.isBefore(inputWM)) { + if (endOfWindow.isBefore(inputWM)) { fireTime = endOfWindow.plus(windowingStrategy.getAllowedLateness()); which = "garbage collection"; } else { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java index c823ed39b1..b26e6e87b0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java @@ -79,10 +79,11 @@ public interface TimerInternals { /** * Return the current, local input watermark timestamp for this computation - * in the {@link TimeDomain#EVENT_TIME} time domain. Return {@code null} if unknown. + * in the {@link TimeDomain#EVENT_TIME} time domain. * *

    This value: *

      + *
    1. Is never {@literal null}, but may be {@link BoundedWindow#TIMESTAMP_MIN_VALUE}. *
    2. Is monotonically increasing. *
    3. May differ between workers due to network and other delays. *
    4. Will never be ahead of the global input watermark for this computation. But it @@ -95,7 +96,6 @@ public interface TimerInternals { * it is possible for an element to be considered locally on-time even though it is * globally late. */ - @Nullable Instant currentInputWatermarkTime(); /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java index 7d4b4f2abe..2ddf5245b8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java @@ -54,7 +54,6 @@ public interface Timers { @Nullable public abstract Instant currentSynchronizedProcessingTime(); - /** Returns the current event time or {@code null} if unknown. */ - @Nullable + /** Returns the current event time. */ public abstract Instant currentEventTime(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java index 64ff402a9a..50e8b324ea 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java @@ -209,7 +209,6 @@ public Instant currentSynchronizedProcessingTime() { } @Override - @Nullable public Instant currentEventTime() { return timers.currentEventTime(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index 31e36c5ef3..7f814c457a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -228,7 +228,6 @@ private Instant addElementHold(ReduceFn.ProcessValueContext context) Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); - Preconditions.checkNotNull(inputWM); // Only add the hold if we can be sure: // - the backend will be able to respect it @@ -242,7 +241,7 @@ private Instant addElementHold(ReduceFn.ProcessValueContext context) if (outputWM != null && elementHold.isBefore(outputWM)) { which = "too late to effect output watermark"; tooLate = true; - } else if (inputWM != null && context.window().maxTimestamp().isBefore(inputWM)) { + } else if (context.window().maxTimestamp().isBefore(inputWM)) { which = "too late for end-of-window timer"; tooLate = true; } else { @@ -288,12 +287,11 @@ private Instant addEndOfWindowHold(ReduceFn.Context context) { // by the end of window (ie the end of window is at or ahead of the input watermark). Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); - Preconditions.checkNotNull(inputWM); String which; boolean tooLate; Instant eowHold = context.window().maxTimestamp(); - if (inputWM != null && eowHold.isBefore(inputWM)) { + if (eowHold.isBefore(inputWM)) { which = "too late for end-of-window timer"; tooLate = true; } else { @@ -332,13 +330,12 @@ private Instant addGarbageCollectionHold(ReduceFn.Context context) { Instant gcHold = context.window().maxTimestamp().plus(windowingStrategy.getAllowedLateness()); Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); - Preconditions.checkNotNull(inputWM); WindowTracing.trace( "WatermarkHold.addGarbageCollectionHold: garbage collection at {} hold for " + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", gcHold, context.key(), context.window(), inputWM, outputWM); - Preconditions.checkState(inputWM == null || !gcHold.isBefore(inputWM), + Preconditions.checkState(!gcHold.isBefore(inputWM), "Garbage collection hold %s cannot be before input watermark %s", gcHold, inputWM); context.state().access(EXTRA_HOLD_TAG).add(gcHold); return gcHold; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java index 1daadc7e2b..cc609532ba 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java @@ -1,3 +1,4 @@ + /* * Copyright (C) 2016 Google Inc. * diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index d4620a7827..4aeaa0cb99 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -599,7 +599,7 @@ private class TestTimerInternals implements TimerInternals { /** Current input watermark. */ @Nullable - private Instant inputWatermarkTime = null; + private Instant inputWatermarkTime = BoundedWindow.TIMESTAMP_MIN_VALUE; /** Current output watermark. */ @Nullable @@ -666,9 +666,8 @@ public Instant currentSynchronizedProcessingTime() { } @Override - @Nullable public Instant currentInputWatermarkTime() { - return inputWatermarkTime; + return Preconditions.checkNotNull(inputWatermarkTime); } @Override @@ -692,7 +691,7 @@ public void advanceInputWatermark( ReduceFnRunner runner, Instant newInputWatermark) throws Exception { Preconditions.checkNotNull(newInputWatermark); Preconditions.checkState( - inputWatermarkTime == null || !newInputWatermark.isBefore(inputWatermarkTime), + !newInputWatermark.isBefore(inputWatermarkTime), "Cannot move input watermark time backwards from %s to %s", inputWatermarkTime, newInputWatermark); WindowTracing.trace("TestTimerInternals.advanceInputWatermark: from {} to {}", @@ -713,7 +712,6 @@ public void advanceInputWatermark( public void advanceOutputWatermark(Instant newOutputWatermark) { Preconditions.checkNotNull(newOutputWatermark); - Preconditions.checkNotNull(inputWatermarkTime); if (newOutputWatermark.isAfter(inputWatermarkTime)) { WindowTracing.trace( "TestTimerInternals.advanceOutputWatermark: clipping output watermark from {} to {}", diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index 0c71830202..f291438f8b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -41,6 +41,7 @@ import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.base.MoreObjects; +import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -428,7 +429,7 @@ private class TestTimerInternals implements TimerInternals { /** Current input watermark. */ @Nullable - private Instant inputWatermarkTime = null; + private Instant inputWatermarkTime = BoundedWindow.TIMESTAMP_MIN_VALUE; /** Current output watermark. */ @Nullable @@ -471,9 +472,8 @@ public Instant currentSynchronizedProcessingTime() { } @Override - @Nullable public Instant currentInputWatermarkTime() { - return inputWatermarkTime; + return Preconditions.checkNotNull(inputWatermarkTime); } @Override @@ -495,7 +495,7 @@ public String toString() { public void advanceInputWatermark(Instant newInputWatermark) throws Exception { checkNotNull(newInputWatermark); - checkState(inputWatermarkTime == null || !newInputWatermark.isBefore(inputWatermarkTime), + checkState(!newInputWatermark.isBefore(inputWatermarkTime), "Cannot move input watermark time backwards from %s to %s", inputWatermarkTime, newInputWatermark); WindowTracing.trace("TestTimerInternals.advanceInputWatermark: from {} to {}", @@ -513,7 +513,6 @@ public void advanceInputWatermark(Instant newInputWatermark) throws Exception { private void advanceOutputWatermark(Instant newOutputWatermark) throws Exception { checkNotNull(newOutputWatermark); - checkNotNull(inputWatermarkTime); if (newOutputWatermark.isAfter(inputWatermarkTime)) { WindowTracing.trace( "TestTimerInternals.advanceOutputWatermark: clipping output watermark from {} to {}", @@ -577,7 +576,6 @@ public Instant currentSynchronizedProcessingTime() { } @Override - @Nullable public Instant currentEventTime() { return timerInternals.currentInputWatermarkTime(); } From d665051a0c7e491694d8c8a59e27191a258904b0 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 22 Mar 2016 10:43:56 -0700 Subject: [PATCH 284/751] Integrate DisplayData into DataflowPipelineRunner --- .../runners/DataflowPipelineTranslator.java | 12 +++ .../sdk/transforms/display/DisplayData.java | 15 ++- .../dataflow/sdk/util/PropertyNames.java | 1 + .../DataflowPipelineTranslatorTest.java | 98 ++++++++++++++++++- .../transforms/display/DisplayDataTest.java | 2 +- 5 files changed, 122 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 0feae957f8..155c454b38 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -59,6 +59,7 @@ import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; @@ -79,6 +80,7 @@ import com.google.cloud.dataflow.sdk.values.TypedPValue; import com.google.common.base.Preconditions; import com.google.common.base.Strings; +import com.google.common.collect.Lists; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -548,6 +550,7 @@ public void addStep(PTransform transform, String type) { currentStep.setKind(type); steps.add(currentStep); addInput(PropertyNames.USER_NAME, getFullName(transform)); + addDisplayData(PropertyNames.DISPLAY_DATA, DisplayData.from(transform)); } @Override @@ -725,6 +728,15 @@ private void addOutput(String name, PValue value, Coder valueCoder) { outputInfoList.add(outputInfo); } + private void addDisplayData(String name, DisplayData displayData) { + List> serializedItems = Lists.newArrayList(); + for (DisplayData.Item item : displayData.items()) { + serializedItems.add(MAPPER.convertValue(item, Map.class)); + } + + addList(getProperties(), name, serializedItems); + } + @Override public OutputReference asOutputReference(PValue value) { AppliedPTransform transform = diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 05fa7c7881..dadc7309da 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -26,6 +26,9 @@ import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; + import org.apache.avro.reflect.Nullable; import org.joda.time.Duration; import org.joda.time.Instant; @@ -214,10 +217,12 @@ private Item( this.label = label; } + @JsonGetter("namespace") public String getNamespace() { return ns; } + @JsonGetter("key") public String getKey() { return key; } @@ -226,6 +231,7 @@ public String getKey() { * Retrieve the {@link DisplayData.Type} of display metadata. All metadata conforms to a * predefined set of allowed types. */ + @JsonGetter("type") public Type getType() { return type; } @@ -233,6 +239,7 @@ public Type getType() { /** * Retrieve the value of the metadata item. */ + @JsonGetter("value") public String getValue() { return value; } @@ -244,6 +251,8 @@ public String getValue() { *

      Some display data types will not provide a short value, in which case the return value * will be null. */ + @JsonGetter("shortValue") + @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable public String getShortValue() { return shortValue; @@ -255,6 +264,8 @@ public String getShortValue() { * *

      If no label was specified, this will return {@code null}. */ + @JsonGetter("label") + @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable public String getLabel() { return label; @@ -266,8 +277,10 @@ public String getLabel() { * *

      If no URL was specified, this will return {@code null}. */ + @JsonGetter("linkUrl") + @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable - public String getUrl() { + public String getLinkUrl() { return url; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java index ec6518976b..81572ea207 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java @@ -103,4 +103,5 @@ public class PropertyNames { public static final String VALIDATE_SINK = "validate_sink"; public static final String VALIDATE_SOURCE = "validate_source"; public static final String VALUE = "value"; + public static final String DISPLAY_DATA = "display_data"; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 497552f901..65f8dde266 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -20,9 +20,11 @@ import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; import static com.google.cloud.dataflow.sdk.util.Structs.getString; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; @@ -53,6 +55,7 @@ import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.GcsUtil; import com.google.cloud.dataflow.sdk.util.OutputReference; import com.google.cloud.dataflow.sdk.util.PropertyNames; @@ -81,6 +84,8 @@ import org.mockito.stubbing.Answer; import java.io.IOException; +import java.io.Serializable; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; @@ -91,9 +96,9 @@ * Tests for DataflowPipelineTranslator. */ @RunWith(JUnit4.class) -public class DataflowPipelineTranslatorTest { +public class DataflowPipelineTranslatorTest implements Serializable { - @Rule public ExpectedException thrown = ExpectedException.none(); + @Rule public transient ExpectedException thrown = ExpectedException.none(); // A Custom Mockito matcher for an initial Job that checks that all // expected fields are set. @@ -496,7 +501,7 @@ private static Step createPredefinedStep() throws Exception { return step; } - private static class NoOpFn extends DoFn{ + private static class NoOpFn extends DoFn { @Override public void processElement(ProcessContext c) throws Exception { c.output(c.element()); } @@ -796,4 +801,89 @@ public void testToIterableTranslationWithIsmSideInput() throws Exception { Step collectionToSingletonStep = steps.get(2); assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); } + + @Test + public void testStepDisplayData() throws Exception { + DataflowPipelineOptions options = buildPipelineOptions(); + DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); + DataflowPipeline pipeline = DataflowPipeline.create(options); + + DoFn fn1 = new DoFn() { + @Override + public void processElement(ProcessContext c) throws Exception { + c.output(c.element()); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("foo", "bar") + .add("foo2", DataflowPipelineTranslatorTest.class) + .withLabel("Test Class") + .withLinkUrl("http://www.google.com"); + } + }; + + DoFn fn2 = new DoFn() { + @Override + public void processElement(ProcessContext c) throws Exception { + c.output(c.element()); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo3", "barge"); + } + }; + + pipeline + .apply(Create.of(1, 2, 3)) + .apply(ParDo.of(fn1)) + .apply(ParDo.of(fn2)); + + Job job = translator.translate( + pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); + + List steps = job.getSteps(); + assertEquals(3, steps.size()); + + Map parDo1Properties = steps.get(1).getProperties(); + Map parDo2Properties = steps.get(2).getProperties(); + assertThat(parDo1Properties, hasKey("display_data")); + + Collection> fn1displayData = + (Collection>) parDo1Properties.get("display_data"); + Collection> fn2displayData = + (Collection>) parDo2Properties.get("display_data"); + + ImmutableList expectedFn1DisplayData = ImmutableList.of( + ImmutableMap.builder() + .put("namespace", fn1.getClass().getName()) + .put("key", "foo") + .put("type", "STRING") + .put("value", "bar") + .build(), + ImmutableMap.builder() + .put("namespace", fn1.getClass().getName()) + .put("key", "foo2") + .put("type", "JAVA_CLASS") + .put("value", DataflowPipelineTranslatorTest.class.getName()) + .put("shortValue", DataflowPipelineTranslatorTest.class.getSimpleName()) + .put("label", "Test Class") + .put("linkUrl", "http://www.google.com") + .build() + ); + + ImmutableList expectedFn2DisplayData = ImmutableList.of( + ImmutableMap.builder() + .put("namespace", fn2.getClass().getName()) + .put("key", "foo3") + .put("type", "STRING") + .put("value", "barge") + .build() + ); + + assertEquals(expectedFn1DisplayData, fn1displayData); + assertEquals(expectedFn2DisplayData, fn2displayData); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index 13dd618657..dfc8c38f52 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -606,7 +606,7 @@ private static Matcher hasUrl(Matcher urlMatcher) { urlMatcher, "display item with url", "URL") { @Override protected String featureValueOf(DisplayData.Item actual) { - return actual.getUrl(); + return actual.getLinkUrl(); } }; } From 173e1189b183d9316a10116e329204aff964f617 Mon Sep 17 00:00:00 2001 From: Daniel Mills Date: Wed, 23 Mar 2016 17:37:17 -0700 Subject: [PATCH 285/751] Validate that Pubsub resource names are at least 3 chars --- .../main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java index 653b31f059..ae7ac0db42 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java @@ -105,6 +105,7 @@ public class PubsubIO { private static final Pattern PUBSUB_NAME_REGEXP = Pattern.compile("[a-zA-Z][-._~%+a-zA-Z0-9]+"); + private static final int PUBSUB_NAME_MIN_LENGTH = 3; private static final int PUBSUB_NAME_MAX_LENGTH = 255; private static final String SUBSCRIPTION_RANDOM_TEST_PREFIX = "_random/"; @@ -120,6 +121,10 @@ private static void validateProjectName(String project) { } private static void validatePubsubName(String name) { + if (name.length() < PUBSUB_NAME_MIN_LENGTH) { + throw new IllegalArgumentException( + "Pubsub object name is shorter than 3 characters: " + name); + } if (name.length() > PUBSUB_NAME_MAX_LENGTH) { throw new IllegalArgumentException( "Pubsub object name is longer than 255 characters: " + name); From 701c2042375978427f7efbb3bdd0f54dded78714 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 4 Mar 2016 08:53:50 -0800 Subject: [PATCH 286/751] Add ModelEnforcements ModelEnforcements ensure that user-written code conforms to the model, in order to ensure that it is portable between runners. Add EncodabilityEnforcement and ImmutabilityEnforcement. EncodabilityEnforcement ensures that all values can be encoded. ImmutabilityEnforcement ensures that values are not mutated within the processing of a Bundle. --- .../inprocess/AbstractModelEnforcement.java | 36 +++ .../EncodabilityEnforcementFactory.java | 69 +++++ .../ImmutabilityEnforcementFactory.java | 94 +++++++ .../runners/inprocess/ModelEnforcement.java | 61 ++++ .../inprocess/ModelEnforcementFactory.java | 28 ++ .../EncodabilityEnforcementFactoryTest.java | 260 ++++++++++++++++++ .../ImmutabilityEnforcementFactoryTest.java | 130 +++++++++ 7 files changed, 678 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java new file mode 100644 index 0000000000..32b2a676c1 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.util.WindowedValue; + +/** + * An abstract {@link ModelEnforcement} that provides default empty implementations for each method. + */ +abstract class AbstractModelEnforcement implements ModelEnforcement { + @Override + public void beforeElement(WindowedValue element) {} + + @Override + public void afterElement(WindowedValue element) {} + + @Override + public void afterFinish( + CommittedBundle input, + InProcessTransformResult result, + Iterable> outputs) {} +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java new file mode 100644 index 0000000000..0e38b55085 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +/** + * Enforces that all elements in a {@link PCollection} can be encoded using that + * {@link PCollection PCollection's} {@link Coder}. + */ +class EncodabilityEnforcementFactory implements ModelEnforcementFactory { + public static EncodabilityEnforcementFactory create() { + return new EncodabilityEnforcementFactory(); + } + + @Override + public ModelEnforcement forBundle( + CommittedBundle input, AppliedPTransform consumer) { + return new EncodabilityEnforcement<>(input); + } + + private static class EncodabilityEnforcement extends AbstractModelEnforcement { + private Coder coder; + + public EncodabilityEnforcement(CommittedBundle input) { + coder = SerializableUtils.clone(input.getPCollection().getCoder()); + } + + @Override + public void beforeElement(WindowedValue element) { + try { + T clone = CoderUtils.clone(coder, element.getValue()); + if (coder.consistentWithEquals()) { + checkArgument( + coder.structuralValue(element.getValue()).equals(coder.structuralValue(clone)), + "Coder %s of class %s does not maintain structural value equality" + + " on input element %s", + coder, + coder.getClass().getSimpleName(), + element.getValue()); + } + } catch (Exception e) { + throw UserCodeException.wrap(e); + } + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java new file mode 100644 index 0000000000..dfc56a9d3c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.util.IllegalMutationException; +import com.google.cloud.dataflow.sdk.util.MutationDetector; +import com.google.cloud.dataflow.sdk.util.MutationDetectors; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowedValue; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * {@link ModelEnforcement} that enforces elements are not modified over the course of processing + * an element. + * + *

      Implies {@link EncodabilityEnforcment}. + */ +class ImmutabilityEnforcementFactory implements ModelEnforcementFactory { + public static ModelEnforcementFactory create() { + return new ImmutabilityEnforcementFactory(); + } + + @Override + public ModelEnforcement forBundle( + CommittedBundle input, AppliedPTransform consumer) { + return new ImmutabilityCheckingEnforcement(input, consumer); + } + + private static class ImmutabilityCheckingEnforcement extends AbstractModelEnforcement { + private final AppliedPTransform transform; + private final Map, MutationDetector> mutationElements; + private final Coder coder; + + private ImmutabilityCheckingEnforcement( + CommittedBundle input, AppliedPTransform transform) { + this.transform = transform; + coder = SerializableUtils.clone(input.getPCollection().getCoder()); + mutationElements = new IdentityHashMap<>(); + } + + @Override + public void beforeElement(WindowedValue element) { + try { + mutationElements.put( + element, MutationDetectors.forValueWithCoder(element.getValue(), coder)); + } catch (CoderException e) { + throw UserCodeException.wrap(e); + } + } + + @Override + public void afterFinish( + CommittedBundle input, + InProcessTransformResult result, + Iterable> outputs) { + for (MutationDetector detector : mutationElements.values()) { + try { + detector.verifyUnmodified(); + } catch (IllegalMutationException e) { + throw UserCodeException.wrap( + new IllegalMutationException( + String.format( + "PTransform %s illegaly mutated value %s of class %s." + + " Input values must not be mutated in any way.", + transform.getFullName(), + e.getSavedValue(), + e.getSavedValue().getClass()), + e.getSavedValue(), + e.getNewValue())); + } + } + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java new file mode 100644 index 0000000000..66bea3767a --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +/** + * Enforcement tools that verify that executing code conforms to the model. + * + *

      ModelEnforcement is performed on a per-element and per-bundle basis. The + * {@link ModelEnforcement} is provided with the input bundle as part of + * {@link ModelEnforcementFactory#forBundle(CommittedBundle, AppliedPTransform)}, each element + * before and after that element is provided to an underlying {@link TransformEvaluator}, and the + * output {@link InProcessTransformResult} and committed output bundles after the + * {@link TransformEvaluator} has completed. + * + *

      Typically, {@link ModelEnforcement} will obtain required metadata (such as the {@link Coder} + * of the input {@link PCollection} on construction, and then enforce per-element behavior + * (such as the immutability of input elements). When the element is output or the bundle is + * completed, the required conditions can be enforced across all elements. + */ +public interface ModelEnforcement { + /** + * Called before a call to {@link TransformEvaluator#processElement(WindowedValue)} on the + * provided {@link WindowedValue}. + */ + void beforeElement(WindowedValue element); + + /** + * Called after a call to {@link TransformEvaluator#processElement(WindowedValue)} on the + * provided {@link WindowedValue}. + */ + void afterElement(WindowedValue element); + + /** + * Called after a bundle has been completed and {@link TransformEvaluator#finishBundle()} has been + * called, producing the provided {@link InProcessTransformResult} and + * {@link CommittedBundle output bundles}. + */ + void afterFinish( + CommittedBundle input, + InProcessTransformResult result, + Iterable> outputs); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java new file mode 100644 index 0000000000..66c01b3c81 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; + +/** + * Creates {@link ModelEnforcement} instances for an {@link AppliedPTransform} on an input + * {@link CommittedBundle bundle}. {@link ModelEnforcement} instances are created before the + * {@link TransformEvaluator} is created. + */ +public interface ModelEnforcementFactory { + ModelEnforcement forBundle(CommittedBundle input, AppliedPTransform consumer); +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java new file mode 100644 index 0000000000..dcc9775bd8 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java @@ -0,0 +1,260 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.isA; + +import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Collections; + +/** + * Tests for {@link EncodabilityEnforcementFactory}. + */ +public class EncodabilityEnforcementFactoryTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + private EncodabilityEnforcementFactory factory = EncodabilityEnforcementFactory.create(); + + @Test + public void encodeFailsThrows() { + TestPipeline p = TestPipeline.create(); + PCollection unencodable = + p.apply(Create.of(new Record()).withCoder(new RecordNoEncodeCoder())); + AppliedPTransform consumer = + unencodable.apply(Count.globally()).getProducingTransformInternal(); + + WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); + CommittedBundle input = + InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + ModelEnforcement enforcement = factory.forBundle(input, consumer); + + thrown.expect(UserCodeException.class); + thrown.expectCause(isA(CoderException.class)); + thrown.expectMessage("Encode not allowed"); + enforcement.beforeElement(record); + } + + @Test + public void decodeFailsThrows() { + TestPipeline p = TestPipeline.create(); + PCollection unencodable = + p.apply(Create.of(new Record()).withCoder(new RecordNoDecodeCoder())); + AppliedPTransform consumer = + unencodable.apply(Count.globally()).getProducingTransformInternal(); + WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); + + CommittedBundle input = + InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + ModelEnforcement enforcement = factory.forBundle(input, consumer); + + thrown.expect(UserCodeException.class); + thrown.expectCause(isA(CoderException.class)); + thrown.expectMessage("Decode not allowed"); + enforcement.beforeElement(record); + } + + @Test + public void consistentWithEqualsStructuralValueNotEqualThrows() { + TestPipeline p = TestPipeline.create(); + PCollection unencodable = + p.apply(Create.of(new Record()).withCoder(new RecordStructuralValueCoder())); + AppliedPTransform consumer = + unencodable.apply(Count.globally()).getProducingTransformInternal(); + + WindowedValue record = + WindowedValue.valueInGlobalWindow( + new Record() { + @Override + public String toString() { + return "OriginalRecord"; + } + }); + + CommittedBundle input = + InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + ModelEnforcement enforcement = factory.forBundle(input, consumer); + + thrown.expect(UserCodeException.class); + thrown.expectCause(isA(IllegalArgumentException.class)); + thrown.expectMessage("does not maintain structural value equality"); + thrown.expectMessage(RecordStructuralValueCoder.class.getSimpleName()); + thrown.expectMessage("OriginalRecord"); + enforcement.beforeElement(record); + } + + @Test + public void notConsistentWithEqualsStructuralValueNotEqualSucceeds() { + TestPipeline p = TestPipeline.create(); + PCollection unencodable = + p.apply( + Create.of(new Record()) + .withCoder(new RecordNotConsistentWithEqualsStructuralValueCoder())); + AppliedPTransform consumer = + unencodable.apply(Count.globally()).getProducingTransformInternal(); + + WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); + + CommittedBundle input = + InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + ModelEnforcement enforcement = factory.forBundle(input, consumer); + + enforcement.beforeElement(record); + enforcement.afterElement(record); + enforcement.afterFinish( + input, + StepTransformResult.withoutHold(consumer).build(), + Collections.>emptyList()); + } + + @Test + public void structurallyEqualResultsSucceeds() { + TestPipeline p = TestPipeline.create(); + PCollection unencodable = p.apply(Create.of(1).withCoder(VarIntCoder.of())); + AppliedPTransform consumer = + unencodable.apply(Count.globally()).getProducingTransformInternal(); + + WindowedValue value = WindowedValue.valueInGlobalWindow(1); + + CommittedBundle input = + InProcessBundle.unkeyed(unencodable).add(value).commit(Instant.now()); + ModelEnforcement enforcement = factory.forBundle(input, consumer); + + enforcement.beforeElement(value); + enforcement.afterElement(value); + enforcement.afterFinish( + input, + StepTransformResult.withoutHold(consumer).build(), + Collections.>emptyList()); + } + + private static class Record {} + private static class RecordNoEncodeCoder extends AtomicCoder { + + @Override + public void encode( + Record value, + OutputStream outStream, + com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + throw new CoderException("Encode not allowed"); + } + + @Override + public Record decode( + InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + return null; + } + } + + private static class RecordNoDecodeCoder extends AtomicCoder { + @Override + public void encode( + Record value, + OutputStream outStream, + com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException {} + + @Override + public Record decode( + InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + throw new CoderException("Decode not allowed"); + } + } + + private static class RecordStructuralValueCoder extends AtomicCoder { + @Override + public void encode( + Record value, + OutputStream outStream, + com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException {} + + @Override + public Record decode( + InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + return new Record() { + @Override + public String toString() { + return "DecodedRecord"; + } + }; + } + + @Override + public boolean consistentWithEquals() { + return true; + } + + @Override + public Object structuralValue(Record value) { + return value; + } + } + + private static class RecordNotConsistentWithEqualsStructuralValueCoder + extends AtomicCoder { + @Override + public void encode( + Record value, + OutputStream outStream, + com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException {} + + @Override + public Record decode( + InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws CoderException, IOException { + return new Record() { + @Override + public String toString() { + return "DecodedRecord"; + } + }; + } + + @Override + public boolean consistentWithEquals() { + return false; + } + + @Override + public Object structuralValue(Record value) { + return value; + } + } + +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java new file mode 100644 index 0000000000..87e12ce55f --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.isA; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.util.IllegalMutationException; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; +import java.util.Collections; + +/** + * Tests for {@link ImmutabilityEnforcementFactory}. + */ +@RunWith(JUnit4.class) +public class ImmutabilityEnforcementFactoryTest implements Serializable { + @Rule public transient ExpectedException thrown = ExpectedException.none(); + private transient ImmutabilityEnforcementFactory factory; + private transient PCollection pcollection; + private transient AppliedPTransform consumer; + + @Before + public void setup() { + factory = new ImmutabilityEnforcementFactory(); + TestPipeline p = TestPipeline.create(); + pcollection = + p.apply(Create.of("foo".getBytes(), "spamhameggs".getBytes())) + .apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) + throws Exception { + c.element()[0] = 'b'; + } + })); + consumer = pcollection.apply(Count.globally()).getProducingTransformInternal(); + } + + @Test + public void unchangedSucceeds() { + WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); + CommittedBundle elements = + InProcessBundle.unkeyed(pcollection).add(element).commit(Instant.now()); + + ModelEnforcement enforcement = factory.forBundle(elements, consumer); + enforcement.beforeElement(element); + enforcement.afterElement(element); + enforcement.afterFinish( + elements, + StepTransformResult.withoutHold(consumer).build(), + Collections.>emptyList()); + } + + @Test + public void mutatedDuringProcessElementThrows() { + WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); + CommittedBundle elements = + InProcessBundle.unkeyed(pcollection).add(element).commit(Instant.now()); + + ModelEnforcement enforcement = factory.forBundle(elements, consumer); + enforcement.beforeElement(element); + element.getValue()[0] = 'f'; + thrown.equals(UserCodeException.class); + thrown.expectCause(isA(IllegalMutationException.class)); + thrown.expectMessage(consumer.getFullName()); + thrown.expectMessage("illegaly mutated"); + thrown.expectMessage("Input values must not be mutated"); + enforcement.afterElement(element); + enforcement.afterFinish( + elements, + StepTransformResult.withoutHold(consumer).build(), + Collections.>emptyList()); + } + + @Test + public void mutatedAfterProcessElementFails() { + + WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); + CommittedBundle elements = + InProcessBundle.unkeyed(pcollection).add(element).commit(Instant.now()); + + ModelEnforcement enforcement = factory.forBundle(elements, consumer); + enforcement.beforeElement(element); + enforcement.afterElement(element); + + element.getValue()[0] = 'f'; + thrown.equals(UserCodeException.class); + thrown.expectCause(isA(IllegalMutationException.class)); + thrown.expectMessage(consumer.getFullName()); + thrown.expectMessage("illegaly mutated"); + thrown.expectMessage("Input values must not be mutated"); + enforcement.afterFinish( + elements, + StepTransformResult.withoutHold(consumer).build(), + Collections.>emptyList()); + } +} + From e5309810a50a69fc20b72115c5be5b1bc1570622 Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Thu, 31 Mar 2016 15:03:59 -0700 Subject: [PATCH 287/751] Repeatedly#onFire should clear all finished bits Previously, Repeatedly#onFire only cleared the finished bits associated with the root of the sub-tree, as demonstrated by the new unit tests. This led to problems with AfterFirst#shouldFire, which checked to see if any of the sub-triggers have their finished bits set. Now, Repeatedly#onFire calls #resetTree, which clears all the finished bits in the entire sub-tree. --- .../sdk/transforms/windowing/Repeatedly.java | 4 +- .../transforms/windowing/RepeatedlyTest.java | 83 +++++++++++++++++++ 2 files changed, 85 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java index e77e2a1203..5f29c8ffe3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java @@ -89,8 +89,8 @@ public void onFire(TriggerContext context) throws Exception { getRepeated(context).invokeOnFire(context); if (context.trigger().isFinished(REPEATED)) { - context.trigger().setFinished(false, REPEATED); - getRepeated(context).invokeClear(context); + // Reset tree will recursively clear the finished bits, and invoke clear. + context.forTrigger(getRepeated(context)).trigger().resetTree(); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java index f445b52565..e14c15c4e2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java @@ -125,4 +125,87 @@ public void testShouldFireAfterMerge() throws Exception { IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); assertTrue(tester.shouldFire(mergedWindow)); } + + @Test + public void testRepeatedlyAfterFirstElementCount() throws Exception { + SimpleTriggerTester tester = + TriggerTester.forTrigger( + Repeatedly.forever( + AfterFirst.of( + AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(15)), + AfterPane.elementCountAtLeast(5))), + new GlobalWindows()); + + GlobalWindow window = GlobalWindow.INSTANCE; + + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + + tester.injectElements(2, 3, 4, 5); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.shouldFire(window)); + } + + @Test + public void testRepeatedlyAfterFirstProcessingTime() throws Exception { + SimpleTriggerTester tester = + TriggerTester.forTrigger( + Repeatedly.forever( + AfterFirst.of( + AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(15)), + AfterPane.elementCountAtLeast(5))), + new GlobalWindows()); + + GlobalWindow window = GlobalWindow.INSTANCE; + + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + + tester.advanceProcessingTime(new Instant(0).plus(Duration.standardMinutes(15))); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.shouldFire(window)); + } + + @Test + public void testRepeatedlyElementCount() throws Exception { + SimpleTriggerTester tester = + TriggerTester.forTrigger( + Repeatedly.forever(AfterPane.elementCountAtLeast(5)), + new GlobalWindows()); + + GlobalWindow window = GlobalWindow.INSTANCE; + + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + + tester.injectElements(2, 3, 4, 5); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.shouldFire(window)); + } + + @Test + public void testRepeatedlyProcessingTime() throws Exception { + SimpleTriggerTester tester = + TriggerTester.forTrigger( + Repeatedly.forever( + AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(15))), + new GlobalWindows()); + + GlobalWindow window = GlobalWindow.INSTANCE; + + tester.injectElements(1); + assertFalse(tester.shouldFire(window)); + + tester.advanceProcessingTime(new Instant(0).plus(Duration.standardMinutes(15))); + assertTrue(tester.shouldFire(window)); + tester.fireIfShouldFire(window); + assertFalse(tester.shouldFire(window)); + } + } From da166bf8b156a6a0bd1335b4f002f9f7f49f972a Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Thu, 31 Mar 2016 10:57:55 -0700 Subject: [PATCH 288/751] Drop elements in closed windows before mapping window Previously, the sequence was: 1. Map a window to a representative of its equivalence class according to merging. 2. Drop the element if that window was closed. But this crashes if the original window was already closed. The new sequence is reversed. This is safe, because it is not possible to map to a representative which is closed, as it is no longer a candidate for merges. --- .../dataflow/sdk/util/ReduceFnRunner.java | 29 +++++++------- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 38 +++++++++++++++++++ 2 files changed, 54 insertions(+), 13 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 560d8ecd44..7fc7ccc34d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -436,8 +436,22 @@ private Collection processElement(WindowedValue value) throws Excepti for (BoundedWindow untypedWindow : value.getWindows()) { @SuppressWarnings("unchecked") W window = (W) untypedWindow; + + ReduceFn.Context directContext = + contextFactory.base(window, StateStyle.DIRECT); + if (triggerRunner.isClosed(directContext.state())) { + // This window has already been closed. + droppedDueToClosedWindow.addValue(1L); + WindowTracing.debug( + "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " + + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", + value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + continue; + } + W active = activeWindows.representative(window); - Preconditions.checkState(active != null, "Window %s should have been added", window); + Preconditions.checkState(active != null, "Window %s has no representative", window); windows.add(active); } @@ -448,24 +462,13 @@ private Collection processElement(WindowedValue value) throws Excepti triggerRunner.prefetchForValue(window, directContext.state()); } - // Process the element for each (representative) window it belongs to. + // Process the element for each (representative, not closed) window it belongs to. for (W window : windows) { ReduceFn.ProcessValueContext directContext = contextFactory.forValue( window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); ReduceFn.ProcessValueContext renamedContext = contextFactory.forValue( window, value.getValue(), value.getTimestamp(), StateStyle.RENAMED); - // Check to see if the triggerRunner thinks the window is closed. If so, drop that window. - if (triggerRunner.isClosed(directContext.state())) { - droppedDueToClosedWindow.addValue(1L); - WindowTracing.debug( - "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", - value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - continue; - } - nonEmptyPanes.recordContent(renamedContext.state()); // Make sure we've scheduled the end-of-window or garbage collection timer for this window. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index c60af85572..646accd252 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -723,6 +723,44 @@ public void testMergingWithCloseBeforeGC() throws Exception { equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); } + /** + * If a later event tries to reuse an earlier session window which has been closed, we + * should reject that element and not fail due to the window no longer having a representative. + */ + @Test + public void testMergingWithReusedWindow() throws Exception { + ReduceFnTester, IntervalWindow> tester = + ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), + ClosingBehavior.FIRE_IF_NON_EMPTY); + + // One elements in one session window. + tester.injectElements(TimestampedValue.of(1, new Instant(1))); // in [1, 11), gc at 21. + + // Close the trigger, but the gargbage collection timer is still pending. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + tester.advanceInputWatermark(new Instant(15)); + + // Another element in the same session window. + // Should be discarded with 'window closed'. + tester.injectElements(TimestampedValue.of(1, new Instant(1))); // in [1, 11), gc at 21. + + // Now the garbage collection timer will fire, finding the trigger already closed. + tester.advanceInputWatermark(new Instant(100)); + + List>> output = tester.extractOutput(); + assertThat(output.size(), equalTo(1)); + assertThat(output.get(0), + isSingleWindowedValue(containsInAnyOrder(1), + 1, // timestamp + 1, // window start + 11)); // window end + assertThat( + output.get(0).getPane(), + equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); + } + /** * Tests that when data is assigned to multiple windows but some of those windows have * had their triggers finish, then the data is dropped and counted accurately. From b1cc366f04094bc2d79fdc112a3c9c7d8e13c75a Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 28 Mar 2016 09:35:33 -0700 Subject: [PATCH 289/751] Execute ModelEnforcements in TransformExecutor This allows a configurable application of Model Enforcement based on the class of transform being executed, both before and after an element is processed and after the transform completes. --- .../runners/inprocess/CompletionCallback.java | 5 +- .../ExecutorServiceParallelExecutor.java | 35 ++- .../inprocess/InProcessPipelineRunner.java | 7 + .../runners/inprocess/TransformExecutor.java | 64 ++++- .../inprocess/TransformExecutorTest.java | 221 +++++++++++++++++- 5 files changed, 318 insertions(+), 14 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java index 2792631560..d45520c196 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java @@ -22,9 +22,10 @@ */ interface CompletionCallback { /** - * Handle a successful result. + * Handle a successful result, returning the committed outputs of the result. */ - void handleResult(CommittedBundle inputBundle, InProcessTransformResult result); + Iterable> handleResult( + CommittedBundle inputBundle, InProcessTransformResult result); /** * Handle a result that terminated abnormally due to the provided {@link Throwable}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index 68a1b8c167..fcd8182b8e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; import com.google.cloud.dataflow.sdk.util.KeyedWorkItems; import com.google.cloud.dataflow.sdk.util.TimeDomain; @@ -60,6 +61,10 @@ final class ExecutorServiceParallelExecutor implements InProcessExecutor { private final Map>> valueToConsumers; private final Set keyedPValues; private final TransformEvaluatorRegistry registry; + @SuppressWarnings("rawtypes") + private final Map, Collection> + transformEnforcements; + private final InProcessEvaluationContext evaluationContext; private final ConcurrentMap currentEvaluations; @@ -78,9 +83,11 @@ public static ExecutorServiceParallelExecutor create( Map>> valueToConsumers, Set keyedPValues, TransformEvaluatorRegistry registry, + @SuppressWarnings("rawtypes") + Map, Collection> transformEnforcements, InProcessEvaluationContext context) { return new ExecutorServiceParallelExecutor( - executorService, valueToConsumers, keyedPValues, registry, context); + executorService, valueToConsumers, keyedPValues, registry, transformEnforcements, context); } private ExecutorServiceParallelExecutor( @@ -88,11 +95,14 @@ private ExecutorServiceParallelExecutor( Map>> valueToConsumers, Set keyedPValues, TransformEvaluatorRegistry registry, + @SuppressWarnings("rawtypes") + Map, Collection> transformEnforcements, InProcessEvaluationContext context) { this.executorService = executorService; this.valueToConsumers = valueToConsumers; this.keyedPValues = keyedPValues; this.registry = registry; + this.transformEnforcements = transformEnforcements; this.evaluationContext = context; currentEvaluations = new ConcurrentHashMap<>(); @@ -126,6 +136,7 @@ private void evaluateBundle( @Nullable final CommittedBundle bundle, final CompletionCallback onComplete) { TransformExecutorService transformExecutor; + if (bundle != null && isKeyed(bundle.getPCollection())) { final StepAndKey stepAndKey = StepAndKey.of(transform, bundle == null ? null : bundle.getKey()); @@ -133,9 +144,21 @@ private void evaluateBundle( } else { transformExecutor = parallelExecutorService; } + + Collection enforcements = + MoreObjects.firstNonNull( + transformEnforcements.get(transform.getTransform().getClass()), + Collections.emptyList()); + TransformExecutor callable = TransformExecutor.create( - registry, evaluationContext, bundle, transform, onComplete, transformExecutor); + registry, + enforcements, + evaluationContext, + bundle, + transform, + onComplete, + transformExecutor); transformExecutor.schedule(callable); } @@ -176,12 +199,14 @@ public void awaitCompletion() throws Throwable { */ private class DefaultCompletionCallback implements CompletionCallback { @Override - public void handleResult(CommittedBundle inputBundle, InProcessTransformResult result) { + public Iterable> handleResult( + CommittedBundle inputBundle, InProcessTransformResult result) { Iterable> resultBundles = evaluationContext.handleResult(inputBundle, Collections.emptyList(), result); for (CommittedBundle outputBundle : resultBundles) { allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); } + return resultBundles; } @Override @@ -204,12 +229,14 @@ private TimerCompletionCallback(Iterable timers) { } @Override - public void handleResult(CommittedBundle inputBundle, InProcessTransformResult result) { + public Iterable> handleResult( + CommittedBundle inputBundle, InProcessTransformResult result) { Iterable> resultBundles = evaluationContext.handleResult(inputBundle, timers, result); for (CommittedBundle outputBundle : resultBundles) { allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); } + return resultBundles; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index a1c8756c5e..82d5e170f6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -52,6 +52,7 @@ import org.joda.time.Instant; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -243,6 +244,7 @@ public InProcessPipelineResult run(Pipeline pipeline) { consumerTrackingVisitor.getValueToConsumers(), keyedPValueVisitor.getKeyedPValues(), TransformEvaluatorRegistry.defaultRegistry(), + defaultModelEnforcements(options), context); executor.start(consumerTrackingVisitor.getRootTransforms()); @@ -262,6 +264,11 @@ public InProcessPipelineResult run(Pipeline pipeline) { return result; } + private Map, Collection> + defaultModelEnforcements(InProcessPipelineOptions options) { + return Collections.emptyMap(); + } + /** * The result of running a {@link Pipeline} with the {@link InProcessPipelineRunner}. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java index d630749387..7e1d84e38b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -20,6 +20,8 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.common.base.Throwables; +import java.util.ArrayList; +import java.util.Collection; import java.util.concurrent.Callable; import javax.annotation.Nullable; @@ -35,6 +37,7 @@ class TransformExecutor implements Callable { public static TransformExecutor create( TransformEvaluatorFactory factory, + Iterable modelEnforcements, InProcessEvaluationContext evaluationContext, CommittedBundle inputBundle, AppliedPTransform transform, @@ -42,6 +45,7 @@ public static TransformExecutor create( TransformExecutorService transformEvaluationState) { return new TransformExecutor<>( factory, + modelEnforcements, evaluationContext, inputBundle, transform, @@ -50,6 +54,8 @@ public static TransformExecutor create( } private final TransformEvaluatorFactory evaluatorFactory; + private final Iterable modelEnforcements; + private final InProcessEvaluationContext evaluationContext; /** The transform that will be evaluated. */ @@ -64,12 +70,14 @@ public static TransformExecutor create( private TransformExecutor( TransformEvaluatorFactory factory, + Iterable modelEnforcements, InProcessEvaluationContext evaluationContext, CommittedBundle inputBundle, AppliedPTransform transform, CompletionCallback completionCallback, TransformExecutorService transformEvaluationState) { this.evaluatorFactory = factory; + this.modelEnforcements = modelEnforcements; this.evaluationContext = evaluationContext; this.inputBundle = inputBundle; @@ -84,15 +92,17 @@ private TransformExecutor( public InProcessTransformResult call() { this.thread = Thread.currentThread(); try { + Collection> enforcements = new ArrayList<>(); + for (ModelEnforcementFactory enforcementFactory : modelEnforcements) { + ModelEnforcement enforcement = enforcementFactory.forBundle(inputBundle, transform); + enforcements.add(enforcement); + } TransformEvaluator evaluator = evaluatorFactory.forApplication(transform, inputBundle, evaluationContext); - if (inputBundle != null) { - for (WindowedValue value : inputBundle.getElements()) { - evaluator.processElement(value); - } - } - InProcessTransformResult result = evaluator.finishBundle(); - onComplete.handleResult(inputBundle, result); + + processElements(evaluator, enforcements); + + InProcessTransformResult result = finishBundle(evaluator, enforcements); return result; } catch (Throwable t) { onComplete.handleThrowable(inputBundle, t); @@ -103,6 +113,46 @@ public InProcessTransformResult call() { } } + /** + * Processes all the elements in the input bundle using the transform evaluator, applying any + * necessary {@link ModelEnforcement ModelEnforcements}. + */ + private void processElements( + TransformEvaluator evaluator, Collection> enforcements) + throws Exception { + if (inputBundle != null) { + for (WindowedValue value : inputBundle.getElements()) { + for (ModelEnforcement enforcement : enforcements) { + enforcement.beforeElement(value); + } + + evaluator.processElement(value); + + for (ModelEnforcement enforcement : enforcements) { + enforcement.afterElement(value); + } + } + } + } + + /** + * Finishes processing the input bundle and commit the result using the + * {@link CompletionCallback}, applying any {@link ModelEnforcement} if necessary. + * + * @return the {@link InProcessTransformResult} produced by + * {@link TransformEvaluator#finishBundle()} + */ + private InProcessTransformResult finishBundle( + TransformEvaluator evaluator, Collection> enforcements) + throws Exception { + InProcessTransformResult result = evaluator.finishBundle(); + Iterable> outputs = onComplete.handleResult(inputBundle, result); + for (ModelEnforcement enforcement : enforcements) { + enforcement.afterFinish(inputBundle, result, outputs); + } + return result; + } + /** * If this {@link TransformExecutor} is currently executing, return the thread it is executing in. * Otherwise, return null. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index bd6325278a..7741263c77 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -15,18 +15,24 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -35,7 +41,9 @@ import org.hamcrest.Matchers; import org.joda.time.Instant; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; @@ -43,10 +51,13 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -54,6 +65,7 @@ */ @RunWith(JUnit4.class) public class TransformExecutorTest { + @Rule public ExpectedException thrown = ExpectedException.none(); private PCollection created; private PCollection> downstream; @@ -106,6 +118,7 @@ public InProcessTransformResult finishBundle() throws Exception { TransformExecutor executor = TransformExecutor.create( registry, + Collections.emptyList(), evaluationContext, null, created.getProducingTransformInternal(), @@ -151,6 +164,7 @@ public InProcessTransformResult finishBundle() throws Exception { TransformExecutor executor = TransformExecutor.create( registry, + Collections.emptyList(), evaluationContext, inputBundle, downstream.getProducingTransformInternal(), @@ -196,6 +210,7 @@ public InProcessTransformResult finishBundle() throws Exception { TransformExecutor executor = TransformExecutor.create( registry, + Collections.emptyList(), evaluationContext, inputBundle, downstream.getProducingTransformInternal(), @@ -233,6 +248,7 @@ public InProcessTransformResult finishBundle() throws Exception { TransformExecutor executor = TransformExecutor.create( registry, + Collections.emptyList(), evaluationContext, inputBundle, downstream.getProducingTransformInternal(), @@ -274,6 +290,7 @@ public InProcessTransformResult finishBundle() throws Exception { TransformExecutor executor = TransformExecutor.create( registry, + Collections.emptyList(), evaluationContext, null, created.getProducingTransformInternal(), @@ -288,6 +305,171 @@ public InProcessTransformResult finishBundle() throws Exception { evaluatorLatch.countDown(); } + @Test + public void callWithEnforcementAppliesEnforcement() throws Exception { + final InProcessTransformResult result = + StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); + + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception { + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + return result; + } + }; + + WindowedValue fooElem = WindowedValue.valueInGlobalWindow("foo"); + WindowedValue barElem = WindowedValue.valueInGlobalWindow("bar"); + CommittedBundle inputBundle = + InProcessBundle.unkeyed(created).add(fooElem).add(barElem).commit(Instant.now()); + when( + registry.forApplication( + downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) + .thenReturn(evaluator); + + TestEnforcementFactory enforcement = new TestEnforcementFactory(); + TransformExecutor executor = + TransformExecutor.create( + registry, + Collections.singleton(enforcement), + evaluationContext, + inputBundle, + downstream.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + + executor.call(); + TestEnforcement testEnforcement = enforcement.instance; + assertThat( + testEnforcement.beforeElements, + Matchers.>containsInAnyOrder(barElem, fooElem)); + assertThat( + testEnforcement.afterElements, + Matchers.>containsInAnyOrder(barElem, fooElem)); + assertThat(testEnforcement.finishedBundles, contains(result)); + } + + @Test + public void callWithEnforcementThrowsOnFinishPropagates() throws Exception { + PCollection pcBytes = + created.apply( + new PTransform, PCollection>() { + @Override + public PCollection apply(PCollection input) { + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), input.getWindowingStrategy(), input.isBounded()) + .setCoder(ByteArrayCoder.of()); + } + }); + + final InProcessTransformResult result = + StepTransformResult.withoutHold(pcBytes.getProducingTransformInternal()).build(); + final CountDownLatch testLatch = new CountDownLatch(1); + final CountDownLatch evaluatorLatch = new CountDownLatch(1); + + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception {} + + @Override + public InProcessTransformResult finishBundle() throws Exception { + testLatch.countDown(); + evaluatorLatch.await(); + return result; + } + }; + + WindowedValue fooBytes = WindowedValue.valueInGlobalWindow("foo".getBytes()); + CommittedBundle inputBundle = + InProcessBundle.unkeyed(pcBytes).add(fooBytes).commit(Instant.now()); + when( + registry.forApplication( + pcBytes.getProducingTransformInternal(), inputBundle, evaluationContext)) + .thenReturn(evaluator); + + TransformExecutor executor = + TransformExecutor.create( + registry, + Collections.singleton(ImmutabilityEnforcementFactory.create()), + evaluationContext, + inputBundle, + pcBytes.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + + Future task = Executors.newSingleThreadExecutor().submit(executor); + testLatch.await(); + fooBytes.getValue()[0] = 'b'; + evaluatorLatch.countDown(); + + thrown.expectCause(isA(UserCodeException.class)); + task.get(); + } + + @Test + public void callWithEnforcementThrowsOnElementPropagates() throws Exception { + PCollection pcBytes = + created.apply( + new PTransform, PCollection>() { + @Override + public PCollection apply(PCollection input) { + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), input.getWindowingStrategy(), input.isBounded()) + .setCoder(ByteArrayCoder.of()); + } + }); + + final InProcessTransformResult result = + StepTransformResult.withoutHold(pcBytes.getProducingTransformInternal()).build(); + final CountDownLatch testLatch = new CountDownLatch(1); + final CountDownLatch evaluatorLatch = new CountDownLatch(1); + + TransformEvaluator evaluator = + new TransformEvaluator() { + @Override + public void processElement(WindowedValue element) throws Exception { + testLatch.countDown(); + evaluatorLatch.await(); + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + return result; + } + }; + + WindowedValue fooBytes = WindowedValue.valueInGlobalWindow("foo".getBytes()); + CommittedBundle inputBundle = + InProcessBundle.unkeyed(pcBytes).add(fooBytes).commit(Instant.now()); + when( + registry.forApplication( + pcBytes.getProducingTransformInternal(), inputBundle, evaluationContext)) + .thenReturn(evaluator); + + TransformExecutor executor = + TransformExecutor.create( + registry, + Collections.singleton(ImmutabilityEnforcementFactory.create()), + evaluationContext, + inputBundle, + pcBytes.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + + Future task = Executors.newSingleThreadExecutor().submit(executor); + testLatch.await(); + fooBytes.getValue()[0] = 'b'; + evaluatorLatch.countDown(); + + thrown.expectCause(isA(UserCodeException.class)); + task.get(); + } + private static class RegisteringCompletionCallback implements CompletionCallback { private InProcessTransformResult handledResult = null; private Throwable handledThrowable = null; @@ -298,9 +480,11 @@ private RegisteringCompletionCallback(CountDownLatch onMethod) { } @Override - public void handleResult(CommittedBundle inputBundle, InProcessTransformResult result) { + public Iterable> handleResult( + CommittedBundle inputBundle, InProcessTransformResult result) { handledResult = result; onMethod.countDown(); + return Collections.emptyList(); } @Override @@ -309,4 +493,39 @@ public void handleThrowable(CommittedBundle inputBundle, Throwable t) { onMethod.countDown(); } } + + private static class TestEnforcementFactory implements ModelEnforcementFactory { + private TestEnforcement instance; + @Override + public TestEnforcement forBundle( + CommittedBundle input, AppliedPTransform consumer) { + TestEnforcement newEnforcement = new TestEnforcement<>(); + instance = newEnforcement; + return newEnforcement; + } + } + + private static class TestEnforcement implements ModelEnforcement { + private final List> beforeElements = new ArrayList<>(); + private final List> afterElements = new ArrayList<>(); + private final List finishedBundles = new ArrayList<>(); + + @Override + public void beforeElement(WindowedValue element) { + beforeElements.add(element); + } + + @Override + public void afterElement(WindowedValue element) { + afterElements.add(element); + } + + @Override + public void afterFinish( + CommittedBundle input, + InProcessTransformResult result, + Iterable> outputs) { + finishedBundles.add(result); + } + } } From 5efb3ef6cf7d4f5efea348cd151a23d58f4a0a23 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 31 Mar 2016 10:40:37 -0700 Subject: [PATCH 290/751] Explicitly track the Source a ReadEvaluator is using This permits use of sources that are not the initial source used in the transform. BoundedSource#splitIntoBundles and UnboundedSource#generateInitialSplits generate multiple source objects for the same transform in order to permit parallelism. Also some cleanups: - Use proper scoping, interfaces in BoundedReadEvaluator - Use BoundedReader instead of Reader - contentsRemaining should be method-scoped not instance-scoped --- .../BoundedReadEvaluatorFactory.java | 26 ++++++++++--------- .../UnboundedReadEvaluatorFactory.java | 14 +++++++--- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java index eaea3ed293..a69db5d559 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java @@ -18,7 +18,6 @@ import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.io.Source.Reader; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -60,8 +59,7 @@ public TransformEvaluator forApplication( private TransformEvaluator getTransformEvaluator( final AppliedPTransform, Bounded> transform, - final InProcessEvaluationContext evaluationContext) - throws IOException { + final InProcessEvaluationContext evaluationContext) { BoundedReadEvaluator evaluator = getTransformEvaluatorQueue(transform, evaluationContext).poll(); if (evaluator == null) { @@ -91,8 +89,9 @@ private Queue> getTransformEvaluatorQueu if (sourceEvaluators.putIfAbsent(key, evaluatorQueue) == null) { // If no queue existed in the evaluators, add an evaluator to initialize the evaluator // factory for this transform + BoundedSource source = transform.getTransform().getSource(); BoundedReadEvaluator evaluator = - new BoundedReadEvaluator(transform, evaluationContext); + new BoundedReadEvaluator(transform, evaluationContext, source); evaluatorQueue.offer(evaluator); } else { // otherwise return the existing Queue that arrived before us @@ -114,13 +113,19 @@ private Queue> getTransformEvaluatorQueu private static class BoundedReadEvaluator implements TransformEvaluator { private final AppliedPTransform, Bounded> transform; private final InProcessEvaluationContext evaluationContext; - private boolean contentsRemaining; + /** + * The source being read from by this {@link BoundedReadEvaluator}. This may not be the same + * as the source derived from {@link #transform} due to splitting. + */ + private BoundedSource source; public BoundedReadEvaluator( AppliedPTransform, Bounded> transform, - InProcessEvaluationContext evaluationContext) { + InProcessEvaluationContext evaluationContext, + BoundedSource source) { this.transform = transform; this.evaluationContext = evaluationContext; + this.source = source; } @Override @@ -128,12 +133,9 @@ public void processElement(WindowedValue element) {} @Override public InProcessTransformResult finishBundle() throws IOException { - try (final Reader reader = - transform - .getTransform() - .getSource() - .createReader(evaluationContext.getPipelineOptions());) { - contentsRemaining = reader.start(); + try (final BoundedReader reader = + source.createReader(evaluationContext.getPipelineOptions());) { + boolean contentsRemaining = reader.start(); UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); while (contentsRemaining) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index 549afabcc0..cba9007cc6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -88,8 +88,10 @@ private Queue> getTransformEvaluatorQu if (sourceEvaluators.putIfAbsent(key, evaluatorQueue) == null) { // If no queue existed in the evaluators, add an evaluator to initialize the evaluator // factory for this transform + UnboundedSource source = transform.getTransform().getSource(); UnboundedReadEvaluator evaluator = - new UnboundedReadEvaluator(transform, evaluationContext, evaluatorQueue); + new UnboundedReadEvaluator( + transform, evaluationContext, source, evaluatorQueue); evaluatorQueue.offer(evaluator); } else { // otherwise return the existing Queue that arrived before us @@ -114,15 +116,22 @@ private static class UnboundedReadEvaluator implements TransformEvaluat private final AppliedPTransform, Unbounded> transform; private final InProcessEvaluationContext evaluationContext; private final Queue> evaluatorQueue; + /** + * The source being read from by this {@link UnboundedReadEvaluator}. This may not be the same + * source as derived from {@link #transform} due to splitting. + */ + private final UnboundedSource source; private CheckpointMark checkpointMark; public UnboundedReadEvaluator( AppliedPTransform, Unbounded> transform, InProcessEvaluationContext evaluationContext, + UnboundedSource source, Queue> evaluatorQueue) { this.transform = transform; this.evaluationContext = evaluationContext; this.evaluatorQueue = evaluatorQueue; + this.source = source; this.checkpointMark = null; } @@ -133,8 +142,7 @@ public void processElement(WindowedValue element) {} public InProcessTransformResult finishBundle() throws IOException { UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); try (UnboundedReader reader = - createReader( - transform.getTransform().getSource(), evaluationContext.getPipelineOptions());) { + createReader(source, evaluationContext.getPipelineOptions());) { int numElements = 0; if (reader.start()) { do { From 5b7df74c8b795f3c4cc6c08730282bbe0e2f6d5a Mon Sep 17 00:00:00 2001 From: Daniel Mills Date: Thu, 31 Mar 2016 11:10:53 -0700 Subject: [PATCH 291/751] Add backoff if insertAll hits rate limits in BQTableInserter --- .../sdk/util/BigQueryTableInserter.java | 24 ++++++- .../IntervalBoundedExponentialBackOff.java | 2 +- .../sdk/util/BigQueryTableInserterTest.java | 64 +++++++++++++++++++ 3 files changed, 88 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java index cd51062756..b1df15d8c1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java @@ -73,6 +73,10 @@ public class BigQueryTableInserter { // The initial backoff after a failure inserting rows into BigQuery. private static final long INITIAL_INSERT_BACKOFF_INTERVAL_MS = 200L; + // Backoff time bounds for rate limit exceeded errors. + private static final long INITIAL_RATE_LIMIT_EXCEEDED_BACKOFF_MS = TimeUnit.SECONDS.toMillis(1); + private static final long MAX_RATE_LIMIT_EXCEEDED_BACKOFF_MS = TimeUnit.MINUTES.toMillis(2); + private final Bigquery client; private final TableReference defaultRef; private final long maxRowsPerBatch; @@ -215,7 +219,25 @@ public void insertAll(TableReference ref, List rowList, executor.submit(new Callable>() { @Override public List call() throws IOException { - return insert.execute().getInsertErrors(); + BackOff backoff = new IntervalBoundedExponentialBackOff( + MAX_RATE_LIMIT_EXCEEDED_BACKOFF_MS, INITIAL_RATE_LIMIT_EXCEEDED_BACKOFF_MS); + while (true) { + try { + return insert.execute().getInsertErrors(); + } catch (IOException e) { + if (new ApiErrorExtractor().rateLimited(e)) { + LOG.info("BigQuery insertAll exceeded rate limit, retrying"); + try { + Thread.sleep(backoff.nextBackOffMillis()); + } catch (InterruptedException interrupted) { + throw new IOException( + "Interrupted while waiting before retrying insertAll"); + } + } else { + throw e; + } + } + } } })); strideIndices.add(strideIndex); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java index 4406ee5c52..3521584ae0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java @@ -53,7 +53,7 @@ public class IntervalBoundedExponentialBackOff implements BackOff { private final long initialIntervalMillis; private int currentAttempt; - public IntervalBoundedExponentialBackOff(int maximumIntervalMillis, long initialIntervalMillis) { + public IntervalBoundedExponentialBackOff(long maximumIntervalMillis, long initialIntervalMillis) { Preconditions.checkArgument( maximumIntervalMillis > 0, "Maximum interval must be greater than zero."); Preconditions.checkArgument( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java index d53315ba66..86448f6ed4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java @@ -40,7 +40,9 @@ import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableDataInsertAllResponse; import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.hadoop.util.RetryBoundedBackOff; import com.google.common.collect.ImmutableList; @@ -58,6 +60,8 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; /** * Tests of {@link BigQueryTableInserter}. @@ -236,4 +240,64 @@ public void testCreateTableDoesNotRetry() throws IOException { throw e; } } + + /** + * Tests that {@link BigQueryTableInserter#insertAll} retries quota rate limited attempts. + */ + @Test + public void testInsertRetry() throws IOException { + TableReference ref = + new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); + List rows = new ArrayList<>(); + rows.add(new TableRow()); + + // First response is 403 rate limited, second response has valid payload. + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(403).thenReturn(200); + when(response.getContent()) + .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403))) + .thenReturn(toStream(new TableDataInsertAllResponse())); + + BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); + + inserter.insertAll(ref, rows); + verify(response, times(2)).getStatusCode(); + verify(response, times(2)).getContent(); + verify(response, times(2)).getContentType(); + expectedLogs.verifyInfo("BigQuery insertAll exceeded rate limit, retrying"); + } + + /** + * Tests that {@link BigQueryTableInserter#insertAll} does not retry non-rate-limited attempts. + */ + @Test + public void testInsertDoesNotRetry() throws Throwable { + TableReference ref = + new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); + List rows = new ArrayList<>(); + rows.add(new TableRow()); + + // First response is 403 not-rate-limited, second response has valid payload but should not + // be invoked. + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(403).thenReturn(200); + when(response.getContent()) + .thenReturn(toStream(errorWithReasonAndStatus("actually forbidden", 403))) + .thenReturn(toStream(new TableDataInsertAllResponse())); + + thrown.expect(GoogleJsonResponseException.class); + thrown.expectMessage("actually forbidden"); + + BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); + + try { + inserter.insertAll(ref, rows); + fail(); + } catch (RuntimeException e) { + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + throw e.getCause(); + } + } } From b7973e7ccbe25bdbdc41cbc1bc72b8abe01f4c6f Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 4 Apr 2016 11:10:18 -0700 Subject: [PATCH 292/751] Give root transforms step names Fix a bug where steps would only be given step names if they were a non-root node. Use the ConsumerTrackingPipelineVisitor in the InProcessEvaluationContext test to handle runner-expanded transforms --- .../ConsumerTrackingPipelineVisitor.java | 2 +- .../ConsumerTrackingPipelineVisitorTest.java | 37 ++++++++++++++ .../InProcessEvaluationContextTest.java | 50 +++++++------------ 3 files changed, 56 insertions(+), 33 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java index c602b23c41..65a342b64e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java @@ -74,12 +74,12 @@ public void leaveCompositeTransform(TransformTreeNode node) { public void visitTransform(TransformTreeNode node) { toFinalize.removeAll(node.getInput().expand()); AppliedPTransform appliedTransform = getAppliedTransform(node); + stepNames.put(appliedTransform, genStepName()); if (node.getInput().expand().isEmpty()) { rootTransforms.add(appliedTransform); } else { for (PValue value : node.getInput().expand()) { valueToConsumers.get(value).add(appliedTransform); - stepNames.put(appliedTransform, genStepName()); } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java index d921f6cdb5..1d23c92ccf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java @@ -174,6 +174,43 @@ public PDone apply(PInput input) { assertThat(visitor.getUnfinalizedPValues(), emptyIterable()); } + @Test + public void getStepNamesContainsAllTransforms() { + PCollection created = p.apply(Create.of("1", "2", "3")); + PCollection transformed = + created.apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(DoFn.ProcessContext c) + throws Exception { + c.output(Integer.toString(c.element().length())); + } + })); + PDone finished = + transformed.apply( + new PTransform() { + @Override + public PDone apply(PInput input) { + return PDone.in(input.getPipeline()); + } + }); + + p.traverseTopologically(visitor); + assertThat( + visitor.getStepNames(), + Matchers., String>hasEntry( + created.getProducingTransformInternal(), "s0")); + assertThat( + visitor.getStepNames(), + Matchers., String>hasEntry( + transformed.getProducingTransformInternal(), "s1")); + assertThat( + visitor.getStepNames(), + Matchers., String>hasEntry( + finished.getProducingTransformInternal(), "s2")); + } + @Test public void traverseMultipleTimesThrows() { p.apply(Create.of(1, 2, 3)); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index 1a0f5053f4..05e38babc6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -71,7 +71,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -88,7 +87,8 @@ public class InProcessEvaluationContextTest { private PCollection> downstream; private PCollectionView> view; private PCollection unbounded; - + private Collection> rootTransforms; + private Map>> valueToConsumers; @Before public void setup() { @@ -101,31 +101,19 @@ public void setup() { downstream = created.apply(WithKeys.of("foo")); view = created.apply(View.asIterable()); unbounded = p.apply(CountingInput.unbounded()); - Collection> rootTransforms = - ImmutableList.>of( - created.getProducingTransformInternal(), unbounded.getProducingTransformInternal()); - Map>> valueToConsumers = new HashMap<>(); - valueToConsumers.put( - created, - ImmutableList.>of( - downstream.getProducingTransformInternal(), view.getProducingTransformInternal())); - valueToConsumers.put(unbounded, ImmutableList.>of()); - valueToConsumers.put(downstream, ImmutableList.>of()); - valueToConsumers.put(view, ImmutableList.>of()); - - Map, String> stepNames = new HashMap<>(); - stepNames.put(created.getProducingTransformInternal(), "s1"); - stepNames.put(downstream.getProducingTransformInternal(), "s2"); - stepNames.put(view.getProducingTransformInternal(), "s3"); - stepNames.put(unbounded.getProducingTransformInternal(), "s4"); - - Collection> views = ImmutableList.>of(view); - context = InProcessEvaluationContext.create( + + ConsumerTrackingPipelineVisitor cVis = new ConsumerTrackingPipelineVisitor(); + p.traverseTopologically(cVis); + rootTransforms = cVis.getRootTransforms(); + valueToConsumers = cVis.getValueToConsumers(); + + context = + InProcessEvaluationContext.create( runner.getPipelineOptions(), rootTransforms, valueToConsumers, - stepNames, - views); + cVis.getStepNames(), + cVis.getViews()); } @Test @@ -490,16 +478,14 @@ public void isDoneWithPartiallyDone() { null, ImmutableList.of(), StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); - context.handleResult( - committedBundle, - ImmutableList.of(), - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build()); assertThat(context.isDone(), is(false)); - context.handleResult( - committedBundle, - ImmutableList.of(), - StepTransformResult.withoutHold(view.getProducingTransformInternal()).build()); + for (AppliedPTransform consumers : valueToConsumers.get(created)) { + context.handleResult( + committedBundle, + ImmutableList.of(), + StepTransformResult.withoutHold(consumers).build()); + } assertThat(context.isDone(), is(true)); } From 034e080bf823ca62319e7316b50b3a958bc6bbf0 Mon Sep 17 00:00:00 2001 From: kirpichov Date: Mon, 4 Apr 2016 13:31:23 -0700 Subject: [PATCH 293/751] [BEAM-167] Fix custom source gzip input to read concatenated gzip files This applies patch from kirpichov@google.com from https://gist.github.com/jkff/d8d984a33a41ec607328cee8e418c174 --- .../dataflow/sdk/io/CompressedSource.java | 2 +- .../dataflow/sdk/io/CompressedSourceTest.java | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index e3dca91680..b0636ea35f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -121,7 +121,7 @@ public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channe byte zero = 0x00; int header = Ints.fromBytes(zero, zero, headerBytes[1], headerBytes[0]); if (header == GZIPInputStream.GZIP_MAGIC) { - return Channels.newChannel(new GzipCompressorInputStream(stream)); + return Channels.newChannel(new GzipCompressorInputStream(stream, true)); } } return Channels.newChannel(stream); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index 14c8fe9aca..86c39a47f1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -46,16 +46,19 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Random; +import java.util.zip.GZIPOutputStream; import javax.annotation.Nullable; @@ -97,6 +100,43 @@ public void testEmptyReadGzip() throws Exception { runReadTest(input, CompressionMode.GZIP); } + private static byte[] compressGzip(byte[] input) throws IOException { + ByteArrayOutputStream res = new ByteArrayOutputStream(); + try (GZIPOutputStream gzipStream = new GZIPOutputStream(res)) { + gzipStream.write(input); + } + return res.toByteArray(); + } + + private static byte[] concat(byte[] first, byte[] second) { + byte[] res = new byte[first.length + second.length]; + System.arraycopy(first, 0, res, 0, first.length); + System.arraycopy(second, 0, res, first.length, second.length); + return res; + } + + @Test + public void testReadConcatenatedGzip() throws IOException { + byte[] header = "a,b,c\n".getBytes(StandardCharsets.UTF_8); + byte[] body = "1,2,3\n4,5,6\n7,8,9\n".getBytes(StandardCharsets.UTF_8); + byte[] expected = concat(header, body); + byte[] totalGz = concat(compressGzip(header), compressGzip(body)); + File tmpFile = tmpFolder.newFile(); + try (FileOutputStream os = new FileOutputStream(tmpFile)) { + os.write(totalGz); + } + + Pipeline p = TestPipeline.create(); + + CompressedSource source = + CompressedSource.from(new ByteSource(tmpFile.getAbsolutePath(), 1)) + .withDecompression(CompressionMode.GZIP); + PCollection output = p.apply(Read.from(source)); + + DataflowAssert.that(output).containsInAnyOrder(Bytes.asList(expected)); + p.run(); + } + /** * Test reading empty input with bzip2. */ From b2b4a2f4ab88174d38cb29338e113b0d4dd34085 Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Mon, 4 Apr 2016 13:35:25 -0700 Subject: [PATCH 294/751] [BEAM-167] Add comment for the test explaining why concatenation of gzip files is valid --- .../google/cloud/dataflow/sdk/io/CompressedSourceTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index 86c39a47f1..fe855101c6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -115,6 +115,12 @@ private static byte[] concat(byte[] first, byte[] second) { return res; } + /** + * Test a concatenation of gzip files is correctly decompressed. + * + *

      A concatenation of gzip files as one file is a valid gzip file and should decompress + * to be the concatenation of those individual files. + */ @Test public void testReadConcatenatedGzip() throws IOException { byte[] header = "a,b,c\n".getBytes(StandardCharsets.UTF_8); From 7df80d41430d071e933831069ad12638011b6684 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 4 Apr 2016 14:40:00 -0700 Subject: [PATCH 295/751] IntervalBoundedExponentialBackOff: add deprecated copy of old API This fixes a bug submitting jobs to Google Cloud Dataflow service. --- .../sdk/util/IntervalBoundedExponentialBackOff.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java index 3521584ae0..5e73ad8fe8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java @@ -53,6 +53,12 @@ public class IntervalBoundedExponentialBackOff implements BackOff { private final long initialIntervalMillis; private int currentAttempt; + // BEAM-168: https://issues.apache.org/jira/browse/BEAM-168 + @Deprecated + public IntervalBoundedExponentialBackOff(int maximumIntervalMillis, long initialIntervalMillis) { + this((long) maximumIntervalMillis, initialIntervalMillis); + } + public IntervalBoundedExponentialBackOff(long maximumIntervalMillis, long initialIntervalMillis) { Preconditions.checkArgument( maximumIntervalMillis > 0, "Maximum interval must be greater than zero."); From a6261e1aa28fb35dc5de3f618d6f9a958b84b6df Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 17 Mar 2016 17:39:45 -0700 Subject: [PATCH 296/751] Add BundleFactory, ImmutabilityCheckingBundleFactory This allows checks to be made on the contents of bundles. ImmutabilityCheckingBundleFactory produces bundles that ensure that elements output to a bundle are not modified after being output. --- .../sdk/runners/inprocess/BundleFactory.java | 48 ++++ .../ExecutorServiceParallelExecutor.java | 5 +- .../ImmutabilityCheckingBundleFactory.java | 129 ++++++++++ .../inprocess/InProcessBundleFactory.java | 155 ++++++++++++ .../inprocess/InProcessEvaluationContext.java | 18 +- .../inprocess/InProcessPipelineRunner.java | 5 + .../BoundedReadEvaluatorFactoryTest.java | 21 +- .../FlattenEvaluatorFactoryTest.java | 11 +- .../GroupByKeyEvaluatorFactoryTest.java | 10 +- .../InMemoryWatermarkManagerTest.java | 49 ++-- .../InProcessEvaluationContextTest.java | 11 +- .../ParDoMultiEvaluatorFactoryTest.java | 95 ++++---- .../ParDoSingleEvaluatorFactoryTest.java | 129 +++++----- .../inprocess/TransformExecutorTest.java | 10 +- .../UnboundedReadEvaluatorFactoryTest.java | 10 +- .../inprocess/ViewEvaluatorFactoryTest.java | 5 +- ...ImmutabilityCheckingBundleFactoryTest.java | 220 ++++++++++++++++++ .../inprocess/InProcessBundleFactoryTest.java | 197 ++++++++++++++++ 18 files changed, 974 insertions(+), 154 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java create mode 100644 sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java create mode 100644 sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java new file mode 100644 index 0000000000..84403afc8a --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PCollection; + +/** + * A factory that creates {@link UncommittedBundle UncommittedBundles}. + */ +public interface BundleFactory { + /** + * Create an {@link UncommittedBundle} from an empty input. Elements added to the bundle belong to + * the {@code output} {@link PCollection}. + */ + public UncommittedBundle createRootBundle(PCollection output); + + /** + * Create an {@link UncommittedBundle} from the specified input. Elements added to the bundle + * belong to the {@code output} {@link PCollection}. + */ + public UncommittedBundle createBundle(CommittedBundle input, PCollection output); + + /** + * Create an {@link UncommittedBundle} with the specified keys at the specified step. For use by + * {@link InProcessGroupByKeyOnly} {@link PTransform PTransforms}. Elements added to the bundle + * belong to the {@code output} {@link PCollection}. + */ + public UncommittedBundle createKeyedBundle( + CommittedBundle input, Object key, PCollection output); +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index fcd8182b8e..dd73d67f0c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -372,8 +372,9 @@ private boolean fireTimers() throws Exception { KeyedWorkItems.timersWorkItem(keyTimers.getKey(), delivery); @SuppressWarnings({"unchecked", "rawtypes"}) CommittedBundle bundle = - InProcessBundle.>keyed( - (PCollection) transform.getInput(), keyTimers.getKey()) + evaluationContext + .createKeyedBundle( + null, keyTimers.getKey(), (PCollection) transform.getInput()) .add(WindowedValue.valueInEmptyWindows(work)) .commit(Instant.now()); scheduleConsumption(transform, bundle, new TimerCompletionCallback(delivery)); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java new file mode 100644 index 0000000000..908636a2c2 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.client.util.Throwables; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.util.IllegalMutationException; +import com.google.cloud.dataflow.sdk.util.MutationDetector; +import com.google.cloud.dataflow.sdk.util.MutationDetectors; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.SetMultimap; + +import org.joda.time.Instant; + +/** + * A {@link BundleFactory} that ensures that elements added to it are not mutated after being + * output. Immutability checks are enforced at the time {@link UncommittedBundle#commit(Instant)} is + * called, checking the value at that time against the value at the time the element was added. All + * elements added to the bundle will be encoded by the {@link Coder} of the underlying + * {@link PCollection}. + * + *

      This catches errors during the execution of a {@link DoFn} caused by modifying an element + * after it is added to an output {@link PCollection}. + */ +class ImmutabilityCheckingBundleFactory implements BundleFactory { + /** + * Create a new {@link ImmutabilityCheckingBundleFactory} that uses the underlying + * {@link BundleFactory} to create the output bundle. + */ + public static ImmutabilityCheckingBundleFactory create(BundleFactory underlying) { + return new ImmutabilityCheckingBundleFactory(underlying); + } + + private final BundleFactory underlying; + + private ImmutabilityCheckingBundleFactory(BundleFactory underlying) { + this.underlying = checkNotNull(underlying); + } + + @Override + public UncommittedBundle createRootBundle(PCollection output) { + return new ImmutabilityEnforcingBundle<>(underlying.createRootBundle(output)); + } + + @Override + public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { + return new ImmutabilityEnforcingBundle<>(underlying.createBundle(input, output)); + } + + @Override + public UncommittedBundle createKeyedBundle( + CommittedBundle input, Object key, PCollection output) { + return new ImmutabilityEnforcingBundle<>(underlying.createKeyedBundle(input, key, output)); + } + + private static class ImmutabilityEnforcingBundle implements UncommittedBundle { + private final UncommittedBundle underlying; + private final SetMultimap, MutationDetector> mutationDetectors; + private Coder coder; + + public ImmutabilityEnforcingBundle(UncommittedBundle underlying) { + this.underlying = underlying; + mutationDetectors = HashMultimap.create(); + coder = SerializableUtils.clone(getPCollection().getCoder()); + } + + @Override + public PCollection getPCollection() { + return underlying.getPCollection(); + } + + @Override + public UncommittedBundle add(WindowedValue element) { + try { + mutationDetectors.put( + element, MutationDetectors.forValueWithCoder(element.getValue(), coder)); + } catch (CoderException e) { + throw Throwables.propagate(e); + } + underlying.add(element); + return this; + } + + @Override + public CommittedBundle commit(Instant synchronizedProcessingTime) { + for (MutationDetector detector : mutationDetectors.values()) { + try { + detector.verifyUnmodified(); + } catch (IllegalMutationException exn) { + throw UserCodeException.wrap( + new IllegalMutationException( + String.format( + "PTransform %s mutated value %s after it was output (new value was %s)." + + " Values must not be mutated in any way after being output.", + underlying.getPCollection().getProducingTransformInternal().getFullName(), + exn.getSavedValue(), + exn.getNewValue()), + exn.getSavedValue(), + exn.getNewValue(), + exn)); + } + } + return underlying.commit(synchronizedProcessingTime); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java new file mode 100644 index 0000000000..30bf3d6763 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; + +import org.joda.time.Instant; + +import javax.annotation.Nullable; + +/** + * A factory that produces bundles that perform no additional validation. + */ +class InProcessBundleFactory implements BundleFactory { + public static InProcessBundleFactory create() { + return new InProcessBundleFactory(); + } + + private InProcessBundleFactory() {} + + @Override + public UncommittedBundle createRootBundle(PCollection output) { + return InProcessBundle.unkeyed(output); + } + + @Override + public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { + return input.isKeyed() + ? InProcessBundle.keyed(output, input.getKey()) + : InProcessBundle.unkeyed(output); + } + + @Override + public UncommittedBundle createKeyedBundle( + CommittedBundle input, Object key, PCollection output) { + return InProcessBundle.keyed(output, key); + } + + /** + * A {@link UncommittedBundle} that buffers elements in memory. + */ + private static final class InProcessBundle implements UncommittedBundle { + private final PCollection pcollection; + private final boolean keyed; + private final Object key; + private boolean committed = false; + private ImmutableList.Builder> elements; + + /** + * Create a new {@link InProcessBundle} for the specified {@link PCollection} without a key. + */ + public static InProcessBundle unkeyed(PCollection pcollection) { + return new InProcessBundle(pcollection, false, null); + } + + /** + * Create a new {@link InProcessBundle} for the specified {@link PCollection} with the specified + * key. + * + *

      See {@link CommittedBundle#getKey()} and {@link CommittedBundle#isKeyed()} for more + * information. + */ + public static InProcessBundle keyed(PCollection pcollection, Object key) { + return new InProcessBundle(pcollection, true, key); + } + + private InProcessBundle(PCollection pcollection, boolean keyed, Object key) { + this.pcollection = pcollection; + this.keyed = keyed; + this.key = key; + this.elements = ImmutableList.builder(); + } + + @Override + public PCollection getPCollection() { + return pcollection; + } + + @Override + public InProcessBundle add(WindowedValue element) { + checkState( + !committed, + "Can't add element %s to committed bundle in PCollection %s", + element, + pcollection); + elements.add(element); + return this; + } + + @Override + public CommittedBundle commit(final Instant synchronizedCompletionTime) { + checkState(!committed, "Can't commit already committed bundle %s", this); + committed = true; + final Iterable> committedElements = elements.build(); + return new CommittedBundle() { + @Override + @Nullable + public Object getKey() { + return key; + } + + @Override + public boolean isKeyed() { + return keyed; + } + + @Override + public Iterable> getElements() { + return committedElements; + } + + @Override + public PCollection getPCollection() { + return pcollection; + } + + @Override + public Instant getSynchronizedProcessingOutputWatermark() { + return synchronizedCompletionTime; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .omitNullValues() + .add("pcollection", pcollection) + .add("key", key) + .add("elements", committedElements) + .toString(); + } + }; + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 4aeb0d3b2a..b2aa45ef62 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -75,6 +75,7 @@ class InProcessEvaluationContext { /** The options that were used to create this {@link Pipeline}. */ private final InProcessPipelineOptions options; + private final BundleFactory bundleFactory; /** The current processing time and event time watermarks and timers. */ private final InMemoryWatermarkManager watermarkManager; @@ -91,21 +92,24 @@ class InProcessEvaluationContext { public static InProcessEvaluationContext create( InProcessPipelineOptions options, + BundleFactory bundleFactory, Collection> rootTransforms, Map>> valueToConsumers, Map, String> stepNames, Collection> views) { return new InProcessEvaluationContext( - options, rootTransforms, valueToConsumers, stepNames, views); + options, bundleFactory, rootTransforms, valueToConsumers, stepNames, views); } private InProcessEvaluationContext( InProcessPipelineOptions options, + BundleFactory bundleFactory, Collection> rootTransforms, Map>> valueToConsumers, Map, String> stepNames, Collection> views) { this.options = checkNotNull(options); + this.bundleFactory = checkNotNull(bundleFactory); checkNotNull(rootTransforms); checkNotNull(valueToConsumers); checkNotNull(stepNames); @@ -205,7 +209,7 @@ private void fireAvailableCallbacks(AppliedPTransform producingTransfor * Create a {@link UncommittedBundle} for use by a source. */ public UncommittedBundle createRootBundle(PCollection output) { - return InProcessBundle.unkeyed(output); + return bundleFactory.createRootBundle(output); } /** @@ -213,9 +217,7 @@ public UncommittedBundle createRootBundle(PCollection output) { * PCollection}. */ public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { - return input.isKeyed() - ? InProcessBundle.keyed(output, input.getKey()) - : InProcessBundle.unkeyed(output); + return bundleFactory.createBundle(input, output); } /** @@ -224,7 +226,7 @@ public UncommittedBundle createBundle(CommittedBundle input, PCollecti */ public UncommittedBundle createKeyedBundle( CommittedBundle input, Object key, PCollection output) { - return InProcessBundle.keyed(output, key); + return bundleFactory.createKeyedBundle(input, key, output); } /** @@ -353,7 +355,9 @@ public CounterSet getCounters() { * for each time they are set. */ public Map, Map> extractFiredTimers() { - return watermarkManager.extractFiredTimers(); + Map, Map> fired = + watermarkManager.extractFiredTimers(); + return fired; } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 82d5e170f6..9b6db8f730 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -230,6 +230,7 @@ public InProcessPipelineResult run(Pipeline pipeline) { InProcessEvaluationContext context = InProcessEvaluationContext.create( getPipelineOptions(), + createBundleFactory(getPipelineOptions()), consumerTrackingVisitor.getRootTransforms(), consumerTrackingVisitor.getValueToConsumers(), consumerTrackingVisitor.getStepNames(), @@ -269,6 +270,10 @@ public InProcessPipelineResult run(Pipeline pipeline) { return Collections.emptyMap(); } + private BundleFactory createBundleFactory(InProcessPipelineOptions pipelineOptions) { + return InProcessBundleFactory.create(); + } + /** * The result of running a {@link Pipeline} with the {@link InProcessPipelineRunner}. * diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java index e641dd6181..5de5a59b25 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java @@ -20,7 +20,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; @@ -46,6 +45,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import java.io.IOException; import java.util.Arrays; @@ -61,20 +61,22 @@ public class BoundedReadEvaluatorFactoryTest { private PCollection longs; private TransformEvaluatorFactory factory; @Mock private InProcessEvaluationContext context; + private BundleFactory bundleFactory; @Before public void setup() { + MockitoAnnotations.initMocks(this); source = CountingSource.upTo(10L); TestPipeline p = TestPipeline.create(); longs = p.apply(Read.from(source)); factory = new BoundedReadEvaluatorFactory(); - context = mock(InProcessEvaluationContext.class); + bundleFactory = InProcessBundleFactory.create(); } @Test public void boundedSourceInMemoryTransformEvaluatorProducesElements() throws Exception { - UncommittedBundle output = InProcessBundle.unkeyed(longs); + UncommittedBundle output = bundleFactory.createRootBundle(longs); when(context.createRootBundle(longs)).thenReturn(output); TransformEvaluator evaluator = @@ -94,8 +96,7 @@ public void boundedSourceInMemoryTransformEvaluatorProducesElements() throws Exc */ @Test public void boundedSourceInMemoryTransformEvaluatorAfterFinishIsEmpty() throws Exception { - UncommittedBundle output = - InProcessBundle.unkeyed(longs); + UncommittedBundle output = bundleFactory.createRootBundle(longs); when(context.createRootBundle(longs)).thenReturn(output); TransformEvaluator evaluator = @@ -109,7 +110,7 @@ public void boundedSourceInMemoryTransformEvaluatorAfterFinishIsEmpty() throws E containsInAnyOrder( gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); - UncommittedBundle secondOutput = InProcessBundle.unkeyed(longs); + UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); when(context.createRootBundle(longs)).thenReturn(secondOutput); TransformEvaluator secondEvaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); @@ -130,8 +131,8 @@ public void boundedSourceInMemoryTransformEvaluatorAfterFinishIsEmpty() throws E */ @Test public void boundedSourceEvaluatorSimultaneousEvaluations() throws Exception { - UncommittedBundle output = InProcessBundle.unkeyed(longs); - UncommittedBundle secondOutput = InProcessBundle.unkeyed(longs); + UncommittedBundle output = bundleFactory.createRootBundle(longs); + UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); when(context.createRootBundle(longs)).thenReturn(output).thenReturn(secondOutput); // create both evaluators before finishing either. @@ -169,7 +170,7 @@ public void boundedSourceEvaluatorClosesReader() throws Exception { PCollection pcollection = p.apply(Read.from(source)); AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - UncommittedBundle output = InProcessBundle.unkeyed(longs); + UncommittedBundle output = bundleFactory.createRootBundle(pcollection); when(context.createRootBundle(pcollection)).thenReturn(output); TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); @@ -187,7 +188,7 @@ public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { PCollection pcollection = p.apply(Read.from(source)); AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - UncommittedBundle output = InProcessBundle.unkeyed(longs); + UncommittedBundle output = bundleFactory.createRootBundle(pcollection); when(context.createRootBundle(pcollection)).thenReturn(output); TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java index 0120b9880d..42777a47e7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java @@ -43,6 +43,7 @@ */ @RunWith(JUnit4.class) public class FlattenEvaluatorFactoryTest { + private BundleFactory bundleFactory = InProcessBundleFactory.create(); @Test public void testFlattenInMemoryEvaluator() throws Exception { TestPipeline p = TestPipeline.create(); @@ -52,13 +53,15 @@ public void testFlattenInMemoryEvaluator() throws Exception { PCollection flattened = list.apply(Flatten.pCollections()); - CommittedBundle leftBundle = InProcessBundle.unkeyed(left).commit(Instant.now()); - CommittedBundle rightBundle = InProcessBundle.unkeyed(right).commit(Instant.now()); + CommittedBundle leftBundle = + bundleFactory.createRootBundle(left).commit(Instant.now()); + CommittedBundle rightBundle = + bundleFactory.createRootBundle(right).commit(Instant.now()); InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - UncommittedBundle flattenedLeftBundle = InProcessBundle.unkeyed(flattened); - UncommittedBundle flattenedRightBundle = InProcessBundle.unkeyed(flattened); + UncommittedBundle flattenedLeftBundle = bundleFactory.createRootBundle(flattened); + UncommittedBundle flattenedRightBundle = bundleFactory.createRootBundle(flattened); when(context.createBundle(leftBundle, flattened)).thenReturn(flattenedLeftBundle); when(context.createBundle(rightBundle, flattened)).thenReturn(flattenedRightBundle); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java index 4ced82f8c7..deb2a64e78 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java @@ -48,6 +48,8 @@ */ @RunWith(JUnit4.class) public class GroupByKeyEvaluatorFactoryTest { + private BundleFactory bundleFactory = InProcessBundleFactory.create(); + @Test public void testInMemoryEvaluator() throws Exception { TestPipeline p = TestPipeline.create(); @@ -65,15 +67,15 @@ public void testInMemoryEvaluator() throws Exception { kvs.apply(new GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly()); CommittedBundle>> inputBundle = - InProcessBundle.unkeyed(kvs).commit(Instant.now()); + bundleFactory.createRootBundle(kvs).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); UncommittedBundle> fooBundle = - InProcessBundle.keyed(groupedKvs, "foo"); + bundleFactory.createKeyedBundle(null, "foo", groupedKvs); UncommittedBundle> barBundle = - InProcessBundle.keyed(groupedKvs, "bar"); + bundleFactory.createKeyedBundle(null, "bar", groupedKvs); UncommittedBundle> bazBundle = - InProcessBundle.keyed(groupedKvs, "baz"); + bundleFactory.createKeyedBundle(null, "baz", groupedKvs); when(evaluationContext.createKeyedBundle(inputBundle, "foo", groupedKvs)).thenReturn(fooBundle); when(evaluationContext.createKeyedBundle(inputBundle, "bar", groupedKvs)).thenReturn(barBundle); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index 52398cf73a..455fcca120 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -82,6 +82,7 @@ public class InMemoryWatermarkManagerTest implements Serializable { private transient PCollection flattened; private transient InMemoryWatermarkManager manager; + private transient BundleFactory bundleFactory; @Before public void setup() { @@ -129,6 +130,7 @@ public void processElement(DoFn.ProcessContext c) throws Excep clock = MockClock.fromInstant(new Instant(1000)); manager = InMemoryWatermarkManager.create(clock, rootTransforms, consumers); + bundleFactory = InProcessBundleFactory.create(); } /** @@ -244,7 +246,7 @@ public void getWatermarkForMultiInputTransform() { assertThat(withBufferedElements.getOutputWatermark(), equalTo(firstCollectionTimestamp)); CommittedBundle completedFlattenBundle = - InProcessBundle.unkeyed(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); + bundleFactory.createRootBundle(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(completedFlattenBundle), null); @@ -340,13 +342,13 @@ public void updateWatermarkWithWatermarkHolds() { @Test public void updateWatermarkWithKeyedWatermarkHolds() { CommittedBundle firstKeyBundle = - InProcessBundle.keyed(createdInts, "Odd") + bundleFactory.createKeyedBundle(null, "Odd", createdInts) .add(WindowedValue.timestampedValueInGlobalWindow(1, new Instant(1_000_000L))) .add(WindowedValue.timestampedValueInGlobalWindow(3, new Instant(-1000L))) .commit(clock.now()); CommittedBundle secondKeyBundle = - InProcessBundle.keyed(createdInts, "Even") + bundleFactory.createKeyedBundle(null, "Even", createdInts) .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) .commit(clock.now()); @@ -366,7 +368,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); CommittedBundle fauxFirstKeyTimerBundle = - InProcessBundle.keyed(createdInts, "Odd").commit(clock.now()); + bundleFactory.createKeyedBundle(null, "Odd", createdInts).commit(clock.now()); manager.updateWatermarks(fauxFirstKeyTimerBundle, filtered.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>emptyList(), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -374,7 +376,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(1234L))); CommittedBundle fauxSecondKeyTimerBundle = - InProcessBundle.keyed(createdInts, "Even").commit(clock.now()); + bundleFactory.createKeyedBundle(null, "Even", createdInts).commit(clock.now()); manager.updateWatermarks(fauxSecondKeyTimerBundle, filtered.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>emptyList(), new Instant(5678L)); assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(5678L))); @@ -394,7 +396,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { @Test public void updateOutputWatermarkShouldBeMonotonic() { CommittedBundle firstInput = - InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); + bundleFactory.createRootBundle(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(firstInput), new Instant(0L)); TransformWatermarks firstWatermarks = @@ -402,7 +404,7 @@ public void updateOutputWatermarkShouldBeMonotonic() { assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); CommittedBundle secondInput = - InProcessBundle.unkeyed(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); + bundleFactory.createRootBundle(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(secondInput), new Instant(-250L)); TransformWatermarks secondWatermarks = @@ -577,7 +579,7 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); CommittedBundle createOutput = - InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); + bundleFactory.createRootBundle(createdInts).commit(new Instant(1250L)); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -604,7 +606,7 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { not(laterThan(new Instant(1250L)))); CommittedBundle filterOutputBundle = - InProcessBundle.unkeyed(intsToFlatten).commit(new Instant(1250L)); + bundleFactory.createRootBundle(intsToFlatten).commit(new Instant(1250L)); manager.updateWatermarks(createOutput, filtered.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(filterOutputBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -671,9 +673,11 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); CommittedBundle filteredTimerBundle = - InProcessBundle.keyed(filtered, "key").commit(BoundedWindow.TIMESTAMP_MAX_VALUE); + bundleFactory + .createKeyedBundle(null, "key", filtered) + .commit(BoundedWindow.TIMESTAMP_MAX_VALUE); CommittedBundle filteredTimerResult = - InProcessBundle.keyed(filteredTimesTwo, "key") + bundleFactory.createKeyedBundle(null, "key", filteredTimesTwo) .commit(filteredWms.getSynchronizedProcessingOutputTime()); // Complete the processing time timer manager.updateWatermarks(filteredTimerBundle, filtered.getProducingTransformInternal(), @@ -723,7 +727,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); CommittedBundle createOutput = - InProcessBundle.unkeyed(createdInts).commit(new Instant(1250L)); + bundleFactory.createRootBundle(createdInts).commit(new Instant(1250L)); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -734,7 +738,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { createAfterUpdate.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); CommittedBundle createSecondOutput = - InProcessBundle.unkeyed(createdInts).commit(new Instant(750L)); + bundleFactory.createRootBundle(createdInts).commit(new Instant(750L)); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(createSecondOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -782,13 +786,20 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( @Test public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { CommittedBundle created = globallyWindowedBundle(createdInts, 1, 2, 3); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(created), new Instant(29_919_235L)); + manager.updateWatermarks( + null, + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton(created), + new Instant(29_919_235L)); Instant upstreamHold = new Instant(2048L); CommittedBundle filteredBundle = - InProcessBundle.keyed(filtered, "key").commit(upstreamHold); - manager.updateWatermarks(created, filtered.getProducingTransformInternal(), TimerUpdate.empty(), + bundleFactory.createKeyedBundle(null, "key", filtered).commit(upstreamHold); + manager.updateWatermarks( + created, + filtered.getProducingTransformInternal(), + TimerUpdate.empty(), Collections.>singleton(filteredBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -1092,7 +1103,7 @@ public void describeTo(Description description) { @SafeVarargs private final CommittedBundle timestampedBundle( PCollection pc, TimestampedValue... values) { - UncommittedBundle bundle = InProcessBundle.unkeyed(pc); + UncommittedBundle bundle = bundleFactory.createRootBundle(pc); for (TimestampedValue value : values) { bundle.add( WindowedValue.timestampedValueInGlobalWindow(value.getValue(), value.getTimestamp())); @@ -1102,7 +1113,7 @@ private final CommittedBundle timestampedBundle( @SafeVarargs private final CommittedBundle globallyWindowedBundle(PCollection pc, T... values) { - UncommittedBundle bundle = InProcessBundle.unkeyed(pc); + UncommittedBundle bundle = bundleFactory.createRootBundle(pc); for (T value : values) { bundle.add(WindowedValue.valueInGlobalWindow(value)); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index 05e38babc6..6268b4b771 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -110,6 +110,7 @@ public void setup() { context = InProcessEvaluationContext.create( runner.getPipelineOptions(), + InProcessBundleFactory.create(), rootTransforms, valueToConsumers, cVis.getStepNames(), @@ -156,7 +157,9 @@ public void getExecutionContextSameStepSameKeyState() { stepContext.stateInternals().state(StateNamespaces.global(), intBag).add(1); context.handleResult( - InProcessBundle.keyed(created, "foo").commit(Instant.now()), + InProcessBundleFactory.create() + .createKeyedBundle(null, "foo", created) + .commit(Instant.now()), ImmutableList.of(), StepTransformResult.withoutHold(created.getProducingTransformInternal()) .withState(stepContext.commitState()) @@ -248,7 +251,7 @@ public void handleResultMergesCounters() { .withCounters(againCounters) .build(); context.handleResult( - InProcessBundle.unkeyed(created).commit(Instant.now()), + context.createRootBundle(created).commit(Instant.now()), ImmutableList.of(), secondResult); assertThat((Long) context.getCounters().getExistingCounter("foo").getAggregate(), equalTo(12L)); @@ -275,7 +278,7 @@ public void handleResultStoresState() { .build(); context.handleResult( - InProcessBundle.keyed(created, myKey).commit(Instant.now()), + context.createKeyedBundle(null, myKey, created).commit(Instant.now()), ImmutableList.of(), stateResult); @@ -357,7 +360,7 @@ public void extractFiredTimersExtractsTimers() { // haven't added any timers, must be empty assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); context.handleResult( - InProcessBundle.keyed(created, key).commit(Instant.now()), + context.createKeyedBundle(null, key, created).commit(Instant.now()), ImmutableList.of(), timerResult); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java index 66430b6a7f..50a7ed9180 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java @@ -67,6 +67,8 @@ */ @RunWith(JUnit4.class) public class ParDoMultiEvaluatorFactoryTest implements Serializable { + private transient BundleFactory bundleFactory = InProcessBundleFactory.create(); + @Test public void testParDoMultiInMemoryTransformEvaluator() throws Exception { TestPipeline p = TestPipeline.create(); @@ -78,26 +80,30 @@ public void testParDoMultiInMemoryTransformEvaluator() throws Exception { final TupleTag lengthTag = new TupleTag<>(); BoundMulti> pardo = - ParDo.of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.element().length())); - c.sideOutput(elementTag, c.element()); - c.sideOutput(lengthTag, c.element().length()); - } - }).withOutputTags(mainOutputTag, TupleTagList.of(elementTag).and(lengthTag)); + ParDo.of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output(KV.of(c.element(), c.element().length())); + c.sideOutput(elementTag, c.element()); + c.sideOutput(lengthTag, c.element().length()); + } + }) + .withOutputTags(mainOutputTag, TupleTagList.of(elementTag).and(lengthTag)); PCollectionTuple outputTuple = input.apply(pardo); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); PCollection> mainOutput = outputTuple.get(mainOutputTag); PCollection elementOutput = outputTuple.get(elementTag); PCollection lengthOutput = outputTuple.get(lengthTag); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); - UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); - UncommittedBundle lengthOutputBundle = InProcessBundle.unkeyed(lengthOutput); + UncommittedBundle> mainOutputBundle = + bundleFactory.createRootBundle(mainOutput); + UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); + UncommittedBundle lengthOutputBundle = bundleFactory.createRootBundle(lengthOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); when(evaluationContext.createBundle(inputBundle, elementOutput)) @@ -112,8 +118,9 @@ public void processElement(ProcessContext c) { when(evaluationContext.createCounterSet()).thenReturn(counters); com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory().forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + new ParDoMultiEvaluatorFactory() + .forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); evaluator.processElement( @@ -161,24 +168,28 @@ public void testParDoMultiUndeclaredSideOutput() throws Exception { final TupleTag lengthTag = new TupleTag<>(); BoundMulti> pardo = - ParDo.of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.element().length())); - c.sideOutput(elementTag, c.element()); - c.sideOutput(lengthTag, c.element().length()); - } - }).withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); + ParDo.of( + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.output(KV.of(c.element(), c.element().length())); + c.sideOutput(elementTag, c.element()); + c.sideOutput(lengthTag, c.element().length()); + } + }) + .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); PCollectionTuple outputTuple = input.apply(pardo); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); PCollection> mainOutput = outputTuple.get(mainOutputTag); PCollection elementOutput = outputTuple.get(elementTag); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); - UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + UncommittedBundle> mainOutputBundle = + bundleFactory.createRootBundle(mainOutput); + UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); when(evaluationContext.createBundle(inputBundle, elementOutput)) @@ -192,8 +203,9 @@ public void processElement(ProcessContext c) { when(evaluationContext.createCounterSet()).thenReturn(counters); com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory().forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + new ParDoMultiEvaluatorFactory() + .forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); evaluator.processElement( @@ -204,8 +216,7 @@ public void processElement(ProcessContext c) { InProcessTransformResult result = evaluator.finishBundle(); assertThat( result.getOutputBundles(), - Matchers.>containsInAnyOrder( - mainOutputBundle, elementOutputBundle)); + Matchers.>containsInAnyOrder(mainOutputBundle, elementOutputBundle)); assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); assertThat(result.getCounters(), equalTo(counters)); @@ -259,14 +270,16 @@ public void processElement(ProcessContext c) { .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); PCollectionTuple outputTuple = input.apply(pardo); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); PCollection> mainOutput = outputTuple.get(mainOutputTag); PCollection elementOutput = outputTuple.get(elementTag); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); - UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + UncommittedBundle> mainOutputBundle = + bundleFactory.createRootBundle(mainOutput); + UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); when(evaluationContext.createBundle(inputBundle, elementOutput)) @@ -280,8 +293,9 @@ public void processElement(ProcessContext c) { when(evaluationContext.createCounterSet()).thenReturn(counters); com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory().forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + new ParDoMultiEvaluatorFactory() + .forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); evaluator.processElement( @@ -366,14 +380,16 @@ public void processElement(ProcessContext c) { .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); PCollectionTuple outputTuple = input.apply(pardo); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); PCollection> mainOutput = outputTuple.get(mainOutputTag); PCollection elementOutput = outputTuple.get(elementTag); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); - UncommittedBundle elementOutputBundle = InProcessBundle.unkeyed(elementOutput); + UncommittedBundle> mainOutputBundle = + bundleFactory.createRootBundle(mainOutput); + UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); when(evaluationContext.createBundle(inputBundle, elementOutput)) @@ -387,8 +403,9 @@ public void processElement(ProcessContext c) { when(evaluationContext.createCounterSet()).thenReturn(counters); com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory().forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); + new ParDoMultiEvaluatorFactory() + .forApplication( + mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); evaluator.processElement( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java index 3b928b9077..8cec0ba609 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java @@ -64,21 +64,27 @@ */ @RunWith(JUnit4.class) public class ParDoSingleEvaluatorFactoryTest implements Serializable { + private transient BundleFactory bundleFactory = InProcessBundleFactory.create(); + @Test public void testParDoInMemoryTransformEvaluator() throws Exception { TestPipeline p = TestPipeline.create(); PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - PCollection collection = input.apply(ParDo.of(new DoFn() { - @Override public void processElement(ProcessContext c) { - c.output(c.element().length()); - } - })); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + PCollection collection = + input.apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.output(c.element().length()); + } + })); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle outputBundle = - InProcessBundle.unkeyed(collection); + UncommittedBundle outputBundle = bundleFactory.createRootBundle(collection); when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); InProcessExecutionContext executionContext = new InProcessExecutionContext(null, null, null, null); @@ -88,8 +94,9 @@ public void testParDoInMemoryTransformEvaluator() throws Exception { when(evaluationContext.createCounterSet()).thenReturn(counters); com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoSingleEvaluatorFactory().forApplication( - collection.getProducingTransformInternal(), inputBundle, evaluationContext); + new ParDoSingleEvaluatorFactory() + .forApplication( + collection.getProducingTransformInternal(), inputBundle, evaluationContext); evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); evaluator.processElement( @@ -116,16 +123,20 @@ public void testSideOutputToUndeclaredSideOutputSucceeds() throws Exception { PCollection input = p.apply(Create.of("foo", "bara", "bazam")); final TupleTag sideOutputTag = new TupleTag() {}; - PCollection collection = input.apply(ParDo.of(new DoFn() { - @Override public void processElement(ProcessContext c) { - c.sideOutput(sideOutputTag, c.element().length()); - } - })); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + PCollection collection = + input.apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(ProcessContext c) { + c.sideOutput(sideOutputTag, c.element().length()); + } + })); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle outputBundle = - InProcessBundle.unkeyed(collection); + UncommittedBundle outputBundle = bundleFactory.createRootBundle(collection); when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); InProcessExecutionContext executionContext = new InProcessExecutionContext(null, null, null, null); @@ -135,8 +146,9 @@ public void testSideOutputToUndeclaredSideOutputSucceeds() throws Exception { when(evaluationContext.createCounterSet()).thenReturn(counters); TransformEvaluator evaluator = - new ParDoSingleEvaluatorFactory().forApplication( - collection.getProducingTransformInternal(), inputBundle, evaluationContext); + new ParDoSingleEvaluatorFactory() + .forApplication( + collection.getProducingTransformInternal(), inputBundle, evaluationContext); evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); evaluator.processElement( @@ -181,10 +193,12 @@ public void processElement(ProcessContext c) { }); PCollection> mainOutput = input.apply(pardo); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + UncommittedBundle> mainOutputBundle = + bundleFactory.createRootBundle(mainOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); @@ -244,42 +258,44 @@ public void finishBundleWithStateAndTimersPutsTimersInResult() throws Exception ParDo.Bound> pardo = ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.windowingInternals().stateInternals(); - c.windowingInternals() - .timerInternals() - .setTimer( - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0).plus(Duration.standardMinutes(5)), - new Instant(1) - .plus(Duration.standardMinutes(5)) - .plus(Duration.standardHours(1)))), - new Instant(54541L), - TimeDomain.EVENT_TIME)); - c.windowingInternals() - .timerInternals() - .deleteTimer( - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0), - new Instant(0).plus(Duration.standardHours(1)))), - new Instant(3400000), - TimeDomain.SYNCHRONIZED_PROCESSING_TIME)); - } - }); + new DoFn>() { + @Override + public void processElement(ProcessContext c) { + c.windowingInternals().stateInternals(); + c.windowingInternals() + .timerInternals() + .setTimer( + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0).plus(Duration.standardMinutes(5)), + new Instant(1) + .plus(Duration.standardMinutes(5)) + .plus(Duration.standardHours(1)))), + new Instant(54541L), + TimeDomain.EVENT_TIME)); + c.windowingInternals() + .timerInternals() + .deleteTimer( + TimerData.of( + StateNamespaces.window( + IntervalWindow.getCoder(), + new IntervalWindow( + new Instant(0), + new Instant(0).plus(Duration.standardHours(1)))), + new Instant(3400000), + TimeDomain.SYNCHRONIZED_PROCESSING_TIME)); + } + }); PCollection> mainOutput = input.apply(pardo); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = InProcessBundle.unkeyed(mainOutput); + UncommittedBundle> mainOutputBundle = + bundleFactory.createRootBundle(mainOutput); when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); @@ -301,10 +317,7 @@ public void processElement(ProcessContext c) { assertThat( result.getTimerUpdate(), equalTo( - TimerUpdate.builder("myKey") - .setTimer(addedTimer) - .deletedTimer(deletedTimer) - .build())); + TimerUpdate.builder("myKey").setTimer(addedTimer).deletedTimer(deletedTimer).build())); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index 7741263c77..b14b34bb24 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -73,6 +73,7 @@ public class TransformExecutorTest { private RegisteringCompletionCallback completionCallback; private TransformExecutorService transformEvaluationState; + private BundleFactory bundleFactory; @Mock private InProcessEvaluationContext evaluationContext; @Mock private TransformEvaluatorRegistry registry; private Map, Boolean> scheduled; @@ -81,6 +82,8 @@ public class TransformExecutorTest { public void setup() { MockitoAnnotations.initMocks(this); + bundleFactory = InProcessBundleFactory.create(); + scheduled = new HashMap<>(); transformEvaluationState = TransformExecutorServices.parallel(MoreExecutors.newDirectExecutorService(), scheduled); @@ -155,7 +158,7 @@ public InProcessTransformResult finishBundle() throws Exception { WindowedValue spam = WindowedValue.valueInGlobalWindow("spam"); WindowedValue third = WindowedValue.valueInGlobalWindow("third"); CommittedBundle inputBundle = - InProcessBundle.unkeyed(created).add(foo).add(spam).add(third).commit(Instant.now()); + bundleFactory.createRootBundle(created).add(foo).add(spam).add(third).commit(Instant.now()); when( registry.forApplication( downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) @@ -201,7 +204,7 @@ public InProcessTransformResult finishBundle() throws Exception { WindowedValue foo = WindowedValue.valueInGlobalWindow("foo"); CommittedBundle inputBundle = - InProcessBundle.unkeyed(created).add(foo).commit(Instant.now()); + bundleFactory.createRootBundle(created).add(foo).commit(Instant.now()); when( registry.forApplication( downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) @@ -239,7 +242,8 @@ public InProcessTransformResult finishBundle() throws Exception { } }; - CommittedBundle inputBundle = InProcessBundle.unkeyed(created).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(created).commit(Instant.now()); when( registry.forApplication( downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java index 20a7d60bce..ab0b939597 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java @@ -70,6 +70,8 @@ public class UnboundedReadEvaluatorFactoryTest { private InProcessEvaluationContext context; private UncommittedBundle output; + private BundleFactory bundleFactory = InProcessBundleFactory.create(); + @Before public void setup() { UnboundedSource source = @@ -79,7 +81,7 @@ public void setup() { factory = new UnboundedReadEvaluatorFactory(); context = mock(InProcessEvaluationContext.class); - output = InProcessBundle.unkeyed(longs); + output = bundleFactory.createRootBundle(longs); when(context.createRootBundle(longs)).thenReturn(output); } @@ -116,7 +118,7 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleSequentialCalls() t tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), tgw(3L), tgw(0L))); - UncommittedBundle secondOutput = InProcessBundle.unkeyed(longs); + UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); when(context.createRootBundle(longs)).thenReturn(secondOutput); TransformEvaluator secondEvaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); @@ -139,6 +141,7 @@ public void boundedSourceEvaluatorClosesReader() throws Exception { PCollection pcollection = p.apply(Read.from(source)); AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + UncommittedBundle output = bundleFactory.createRootBundle(pcollection); when(context.createRootBundle(pcollection)).thenReturn(output); TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); @@ -156,6 +159,7 @@ public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { PCollection pcollection = p.apply(Read.from(source)); AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + UncommittedBundle output = bundleFactory.createRootBundle(pcollection); when(context.createRootBundle(pcollection)).thenReturn(output); TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); @@ -173,7 +177,7 @@ public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { */ @Test public void unboundedSourceWithMultipleSimultaneousEvaluatorsIndependent() throws Exception { - UncommittedBundle secondOutput = InProcessBundle.unkeyed(longs); + UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); TransformEvaluator evaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java index 2f5bdde6ad..26cafa74cc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java @@ -48,6 +48,8 @@ */ @RunWith(JUnit4.class) public class ViewEvaluatorFactoryTest { + private BundleFactory bundleFactory = InProcessBundleFactory.create(); + @Test public void testInMemoryEvaluator() throws Exception { TestPipeline p = TestPipeline.create(); @@ -68,7 +70,8 @@ public void testInMemoryEvaluator() throws Exception { TestViewWriter> viewWriter = new TestViewWriter<>(); when(context.createPCollectionViewWriter(concat, view)).thenReturn(viewWriter); - CommittedBundle inputBundle = InProcessBundle.unkeyed(input).commit(Instant.now()); + CommittedBundle inputBundle = + bundleFactory.createRootBundle(input).commit(Instant.now()); TransformEvaluator> evaluator = new ViewEvaluatorFactory() .forApplication(view.getProducingTransformInternal(), inputBundle, context); diff --git a/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java b/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java new file mode 100644 index 0000000000..40b1d5a69e --- /dev/null +++ b/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java @@ -0,0 +1,220 @@ +/* + * 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.isA; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.util.IllegalMutationException; +import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link ImmutabilityCheckingBundleFactory}. + */ +@RunWith(JUnit4.class) +public class ImmutabilityCheckingBundleFactoryTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + private ImmutabilityCheckingBundleFactory factory; + private PCollection created; + private PCollection transformed; + + @Before + public void setup() { + TestPipeline p = TestPipeline.create(); + created = p.apply(Create.of().withCoder(ByteArrayCoder.of())); + transformed = created.apply(ParDo.of(new IdentityDoFn())); + factory = ImmutabilityCheckingBundleFactory.create(InProcessBundleFactory.create()); + } + + @Test + public void noMutationRootBundleSucceeds() { + UncommittedBundle root = factory.createRootBundle(created); + byte[] array = new byte[] {0, 1, 2}; + root.add(WindowedValue.valueInGlobalWindow(array)); + CommittedBundle committed = root.commit(Instant.now()); + + assertThat( + committed.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(array))); + } + + @Test + public void noMutationKeyedBundleSucceeds() { + CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); + UncommittedBundle keyed = factory.createKeyedBundle(root, "mykey", transformed); + + WindowedValue windowedArray = + WindowedValue.of( + new byte[] {4, 8, 12}, + new Instant(891L), + new IntervalWindow(new Instant(0), new Instant(1000)), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + keyed.add(windowedArray); + + CommittedBundle committed = keyed.commit(Instant.now()); + assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); + } + + @Test + public void noMutationCreateBundleSucceeds() { + CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); + UncommittedBundle intermediate = factory.createBundle(root, transformed); + + WindowedValue windowedArray = + WindowedValue.of( + new byte[] {4, 8, 12}, + new Instant(891L), + new IntervalWindow(new Instant(0), new Instant(1000)), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + intermediate.add(windowedArray); + + CommittedBundle committed = intermediate.commit(Instant.now()); + assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); + } + + @Test + public void mutationBeforeAddRootBundleSucceeds() { + UncommittedBundle root = factory.createRootBundle(created); + byte[] array = new byte[] {0, 1, 2}; + array[1] = 2; + root.add(WindowedValue.valueInGlobalWindow(array)); + CommittedBundle committed = root.commit(Instant.now()); + + assertThat( + committed.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(array))); + } + + @Test + public void mutationBeforeAddKeyedBundleSucceeds() { + CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); + UncommittedBundle keyed = factory.createKeyedBundle(root, "mykey", transformed); + + byte[] array = new byte[] {4, 8, 12}; + array[0] = Byte.MAX_VALUE; + WindowedValue windowedArray = + WindowedValue.of( + array, + new Instant(891L), + new IntervalWindow(new Instant(0), new Instant(1000)), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + keyed.add(windowedArray); + + CommittedBundle committed = keyed.commit(Instant.now()); + assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); + } + + @Test + public void mutationBeforeAddCreateBundleSucceeds() { + CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); + UncommittedBundle intermediate = factory.createBundle(root, transformed); + + byte[] array = new byte[] {4, 8, 12}; + WindowedValue windowedArray = + WindowedValue.of( + array, + new Instant(891L), + new IntervalWindow(new Instant(0), new Instant(1000)), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + array[2] = -3; + intermediate.add(windowedArray); + + CommittedBundle committed = intermediate.commit(Instant.now()); + assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); + } + + @Test + public void mutationAfterAddRootBundleThrows() { + UncommittedBundle root = factory.createRootBundle(created); + byte[] array = new byte[] {0, 1, 2}; + root.add(WindowedValue.valueInGlobalWindow(array)); + + array[1] = 2; + thrown.expect(UserCodeException.class); + thrown.expectCause(isA(IllegalMutationException.class)); + thrown.expectMessage("Values must not be mutated in any way after being output"); + CommittedBundle committed = root.commit(Instant.now()); + } + + @Test + public void mutationAfterAddKeyedBundleThrows() { + CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); + UncommittedBundle keyed = factory.createKeyedBundle(root, "mykey", transformed); + + byte[] array = new byte[] {4, 8, 12}; + WindowedValue windowedArray = + WindowedValue.of( + array, + new Instant(891L), + new IntervalWindow(new Instant(0), new Instant(1000)), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + keyed.add(windowedArray); + + array[0] = Byte.MAX_VALUE; + thrown.expect(UserCodeException.class); + thrown.expectCause(isA(IllegalMutationException.class)); + thrown.expectMessage("Values must not be mutated in any way after being output"); + CommittedBundle committed = keyed.commit(Instant.now()); + } + + @Test + public void mutationAfterAddCreateBundleThrows() { + CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); + UncommittedBundle intermediate = factory.createBundle(root, transformed); + + byte[] array = new byte[] {4, 8, 12}; + WindowedValue windowedArray = + WindowedValue.of( + array, + new Instant(891L), + new IntervalWindow(new Instant(0), new Instant(1000)), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + intermediate.add(windowedArray); + + array[2] = -3; + thrown.expect(UserCodeException.class); + thrown.expectCause(isA(IllegalMutationException.class)); + thrown.expectMessage("Values must not be mutated in any way after being output"); + CommittedBundle committed = intermediate.commit(Instant.now()); + } + + private static class IdentityDoFn extends DoFn { + @Override + public void processElement(DoFn.ProcessContext c) throws Exception { + c.output(c.element()); + } + } +} diff --git a/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java b/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java new file mode 100644 index 0000000000..060d43cfe7 --- /dev/null +++ b/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java @@ -0,0 +1,197 @@ +/* + * 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +/** + * Tests for {@link InProcessBundleFactory}. + */ +@RunWith(JUnit4.class) +public class InProcessBundleFactoryTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + private InProcessBundleFactory bundleFactory = InProcessBundleFactory.create(); + + private PCollection created; + private PCollection> downstream; + + @Before + public void setup() { + TestPipeline p = TestPipeline.create(); + created = p.apply(Create.of(1, 2, 3)); + downstream = created.apply(WithKeys.of("foo")); + } + + @Test + public void createRootBundleShouldCreateWithNullKey() { + PCollection pcollection = TestPipeline.create().apply(Create.of(1)); + + UncommittedBundle inFlightBundle = bundleFactory.createRootBundle(pcollection); + + CommittedBundle bundle = inFlightBundle.commit(Instant.now()); + + assertThat(bundle.isKeyed(), is(false)); + assertThat(bundle.getKey(), nullValue()); + } + + private void createKeyedBundle(Object key) { + PCollection pcollection = TestPipeline.create().apply(Create.of(1)); + + UncommittedBundle inFlightBundle = + bundleFactory.createKeyedBundle(null, key, pcollection); + + CommittedBundle bundle = inFlightBundle.commit(Instant.now()); + assertThat(bundle.isKeyed(), is(true)); + assertThat(bundle.getKey(), equalTo(key)); + } + + @Test + public void keyedWithNullKeyShouldCreateKeyedBundle() { + createKeyedBundle(null); + } + + @Test + public void keyedWithKeyShouldCreateKeyedBundle() { + createKeyedBundle(new Object()); + } + + private void afterCommitGetElementsShouldHaveAddedElements(Iterable> elems) { + PCollection pcollection = TestPipeline.create().apply(Create.of()); + + UncommittedBundle bundle = bundleFactory.createRootBundle(pcollection); + Collection>> expectations = new ArrayList<>(); + for (WindowedValue elem : elems) { + bundle.add(elem); + expectations.add(equalTo(elem)); + } + Matcher>> containsMatcher = + Matchers.>containsInAnyOrder(expectations); + assertThat(bundle.commit(Instant.now()).getElements(), containsMatcher); + } + + @Test + public void getElementsBeforeAddShouldReturnEmptyIterable() { + afterCommitGetElementsShouldHaveAddedElements(Collections.>emptyList()); + } + + @Test + public void getElementsAfterAddShouldReturnAddedElements() { + WindowedValue firstValue = WindowedValue.valueInGlobalWindow(1); + WindowedValue secondValue = + WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1000L)); + + afterCommitGetElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); + } + + @Test + public void addAfterCommitShouldThrowException() { + PCollection pcollection = TestPipeline.create().apply(Create.of()); + + UncommittedBundle bundle = bundleFactory.createRootBundle(pcollection); + bundle.add(WindowedValue.valueInGlobalWindow(1)); + CommittedBundle firstCommit = bundle.commit(Instant.now()); + assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage("3"); + thrown.expectMessage("committed"); + + bundle.add(WindowedValue.valueInGlobalWindow(3)); + } + + @Test + public void commitAfterCommitShouldThrowException() { + PCollection pcollection = TestPipeline.create().apply(Create.of()); + + UncommittedBundle bundle = bundleFactory.createRootBundle(pcollection); + bundle.add(WindowedValue.valueInGlobalWindow(1)); + CommittedBundle firstCommit = bundle.commit(Instant.now()); + assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage("committed"); + + bundle.commit(Instant.now()); + } + + @Test + public void createBundleUnkeyedResultUnkeyed() { + CommittedBundle> newBundle = + bundleFactory + .createBundle(bundleFactory.createRootBundle(created).commit(Instant.now()), downstream) + .commit(Instant.now()); + assertThat(newBundle.isKeyed(), is(false)); + } + + @Test + public void createBundleKeyedResultPropagatesKey() { + CommittedBundle> newBundle = + bundleFactory + .createBundle( + bundleFactory.createKeyedBundle(null, "foo", created).commit(Instant.now()), + downstream) + .commit(Instant.now()); + assertThat(newBundle.isKeyed(), is(true)); + assertThat(newBundle.getKey(), Matchers.equalTo("foo")); + } + + @Test + public void createRootBundleUnkeyed() { + assertThat(bundleFactory.createRootBundle(created).commit(Instant.now()).isKeyed(), is(false)); + } + + @Test + public void createKeyedBundleKeyed() { + CommittedBundle> keyedBundle = + bundleFactory + .createKeyedBundle( + bundleFactory.createRootBundle(created).commit(Instant.now()), "foo", downstream) + .commit(Instant.now()); + assertThat(keyedBundle.isKeyed(), is(true)); + assertThat(keyedBundle.getKey(), Matchers.equalTo("foo")); + } +} From e6e843644ec99efcf3193be31a74d4cce0c37528 Mon Sep 17 00:00:00 2001 From: Rafal Wojdyla Date: Tue, 5 Apr 2016 18:10:00 -0400 Subject: [PATCH 297/751] Correct URL for subnetwork --- .../sdk/options/DataflowPipelineWorkerPoolOptions.java | 5 ++++- .../dataflow/sdk/runners/DataflowPipelineTranslatorTest.java | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java index dd3d83a077..cc96e802f1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java @@ -148,7 +148,10 @@ public String create(PipelineOptions options) { * GCE subnetwork for launching * workers. * - *

      Default is up to the Dataflow service. Expected format is zones/ZONE/subnetworks/SUBNETWORK. + *

      Default is up to the Dataflow service. Expected format is + * regions/REGION/subnetworks/SUBNETWORK. + * + *

      You may also need to specify network option. */ @Description("GCE subnetwork for launching workers. For more information, see the reference " + "documentation https://cloud.google.com/compute/docs/networking. " diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 65f8dde266..fef108dff3 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -237,7 +237,7 @@ public void testNetworkConfigMissing() throws IOException { @Test public void testSubnetworkConfig() throws IOException { - final String testSubnetwork = "zones/ZONE/subnetworks/SUBNETWORK"; + final String testSubnetwork = "regions/REGION/subnetworks/SUBNETWORK"; DataflowPipelineOptions options = buildPipelineOptions(); options.setSubnetwork(testSubnetwork); From 31b5052501eb406833d420013e0bd0339af27ada Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 6 Apr 2016 10:42:03 -0700 Subject: [PATCH 298/751] Port incubator-beam/pull/118 --- .../dataflow/sdk/util/ActiveWindowSet.java | 23 +++- .../sdk/util/MergingActiveWindowSet.java | 101 +++++++++------ .../sdk/util/NonMergingActiveWindowSet.java | 11 +- .../dataflow/sdk/util/ReduceFnRunner.java | 62 +++++---- .../dataflow/sdk/util/TriggerRunner.java | 17 ++- .../sdk/util/MergingActiveWindowSetTest.java | 23 ++-- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 121 +++++++++++++++++- .../dataflow/sdk/util/ReduceFnTester.java | 4 + .../dataflow/sdk/util/TriggerTester.java | 2 +- 9 files changed, 273 insertions(+), 91 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java index 69350cb3eb..55ebaed849 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.common.annotations.VisibleForTesting; import java.util.Collection; import java.util.Set; @@ -92,9 +93,10 @@ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeRe } /** - * Remove EPHEMERAL windows since we only need to know about them while processing new elements. + * Remove EPHEMERAL windows and remaining NEW windows since we only need to know about them + * while processing new elements. */ - void removeEphemeralWindows(); + void cleanupTemporaryWindows(); /** * Save any state changes needed. @@ -107,7 +109,7 @@ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeRe * yet been seen. */ @Nullable - W representative(W window); + W mergeResultWindow(W window); /** * Return (a view of) the set of currently ACTIVE windows. @@ -120,16 +122,23 @@ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeRe boolean isActive(W window); /** - * If {@code window} is not already known to be ACTIVE, MERGED or EPHEMERAL then add it - * as NEW. All NEW windows will be accounted for as ACTIVE, MERGED or EPHEMERAL by a call - * to {@link #merge}. + * Called when an incoming element indicates it is a member of {@code window}, but before we + * have started processing that element. If {@code window} is not already known to be ACTIVE, + * MERGED or EPHEMERAL then add it as NEW. + */ + void ensureWindowExists(W window); + + /** + * Called when a NEW or ACTIVE window is now known to be ACTIVE. + * Ensure that if it is NEW then it becomes ACTIVE (with itself as its only state address window). */ - void addNew(W window); + void ensureWindowIsActive(W window); /** * If {@code window} is not already known to be ACTIVE, MERGED or EPHEMERAL then add it * as ACTIVE. */ + @VisibleForTesting void addActive(W window); /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index 96629b1601..ae50facd03 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -32,6 +32,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -72,6 +73,9 @@ */ public class MergingActiveWindowSet implements ActiveWindowSet { private final WindowFn windowFn; + /** + * Map ACTIVE and NEW windows to their state address windows. Persisted. + */ private final Map> activeWindowToStateAddressWindows; /** @@ -80,10 +84,8 @@ public class MergingActiveWindowSet implements ActiveWi private final Map> activeWindowToEphemeralWindows; /** - * A map from window to the ACTIVE window it has been merged into. - * - *

      Does not need to be persisted. - * + * A map from window to the ACTIVE window it has been merged into. Does not need to be persisted. + *

      *

        *
      • Key window may be ACTIVE, MERGED or EPHEMERAL. *
      • ACTIVE windows map to themselves. @@ -96,7 +98,7 @@ public class MergingActiveWindowSet implements ActiveWi /** * Deep clone of {@link #activeWindowToStateAddressWindows} as of last commit. - * + *

        *

        Used to avoid writing to state if no changes have been made during the work unit. */ private final Map> originalActiveWindowToStateAddressWindows; @@ -122,7 +124,19 @@ public MergingActiveWindowSet(WindowFn windowFn, StateInternals st } @Override - public void removeEphemeralWindows() { + public void cleanupTemporaryWindows() { + // All NEW windows can be forgotten. + Iterator>> iter = + activeWindowToStateAddressWindows.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry> entry = iter.next(); + if (entry.getValue().isEmpty()) { + windowToActiveWindow.remove(entry.getKey()); + iter.remove(); + } + } + + // All EPHEMERAL windows can be forgotten. for (Map.Entry> entry : activeWindowToEphemeralWindows.entrySet()) { for (W ephemeral : entry.getValue()) { windowToActiveWindow.remove(ephemeral); @@ -158,7 +172,7 @@ public void persist() { @Override @Nullable - public W representative(W window) { + public W mergeResultWindow(W window) { return windowToActiveWindow.get(window); } @@ -173,13 +187,30 @@ public boolean isActive(W window) { } @Override - public void addNew(W window) { + public void ensureWindowExists(W window) { if (!windowToActiveWindow.containsKey(window)) { + Preconditions.checkState(!activeWindowToStateAddressWindows.containsKey(window)); activeWindowToStateAddressWindows.put(window, new LinkedHashSet()); + windowToActiveWindow.put(window, window); } } @Override + public void ensureWindowIsActive(W window) { + Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); + Preconditions.checkState(stateAddressWindows != null, + "Cannot ensure window %s is active since it is neither ACTIVE nor NEW", + window); + if (stateAddressWindows.isEmpty()) { + // Window was NEW, make it ACTIVE. + Preconditions.checkState(windowToActiveWindow.containsKey(window) + && windowToActiveWindow.get(window).equals(window)); + stateAddressWindows.add(window); + } + } + + @Override + @VisibleForTesting public void addActive(W window) { if (!windowToActiveWindow.containsKey(window)) { Set stateAddressWindows = new LinkedHashSet<>(); @@ -191,21 +222,17 @@ public void addActive(W window) { @Override public void remove(W window) { - Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); - if (stateAddressWindows == null) { - // Window is no longer active. - return; - } - for (W stateAddressWindow : stateAddressWindows) { - windowToActiveWindow.remove(stateAddressWindow); + Set stateAddressWindows = activeWindowToStateAddressWindows.remove(window); + if (stateAddressWindows != null) { + for (W stateAddressWindow : stateAddressWindows) { + windowToActiveWindow.remove(stateAddressWindow); + } } - activeWindowToStateAddressWindows.remove(window); - Set ephemeralWindows = activeWindowToEphemeralWindows.get(window); + Set ephemeralWindows = activeWindowToEphemeralWindows.remove(window); if (ephemeralWindows != null) { for (W ephemeralWindow : ephemeralWindows) { windowToActiveWindow.remove(ephemeralWindow); } - activeWindowToEphemeralWindows.remove(window); } windowToActiveWindow.remove(window); } @@ -291,15 +318,6 @@ public void merge(MergeCallback mergeCallback) throws Exception { // Actually do the merging and invoke the callbacks. context.recordMerges(); - // Any remaining NEW windows should become implicitly ACTIVE. - for (Map.Entry> entry : activeWindowToStateAddressWindows.entrySet()) { - if (entry.getValue().isEmpty()) { - // This window was NEW but since it survived merging must now become ACTIVE. - W window = entry.getKey(); - entry.getValue().add(window); - windowToActiveWindow.put(window, window); - } - } } /** @@ -433,12 +451,15 @@ public void checkInvariants() { for (Map.Entry> entry : activeWindowToStateAddressWindows.entrySet()) { W active = entry.getKey(); Preconditions.checkState(!entry.getValue().isEmpty(), - "Unexpected empty state address window set for ACTIVE window %s", active); + "Unexpected empty state address window set for ACTIVE window %s", + active); for (W stateAddressWindow : entry.getValue()) { Preconditions.checkState(knownStateAddressWindows.add(stateAddressWindow), - "%s is in more than one state address window set", stateAddressWindow); + "%s is in more than one state address window set", + stateAddressWindow); Preconditions.checkState(active.equals(windowToActiveWindow.get(stateAddressWindow)), - "%s should have %s as its ACTIVE window", stateAddressWindow, active); + "%s should have %s as its ACTIVE window", stateAddressWindow, + active); } } for (Map.Entry> entry : activeWindowToEphemeralWindows.entrySet()) { @@ -449,14 +470,16 @@ public void checkInvariants() { !entry.getValue().isEmpty(), "Unexpected empty EPHEMERAL set for %s", active); for (W ephemeralWindow : entry.getValue()) { Preconditions.checkState(knownStateAddressWindows.add(ephemeralWindow), - "%s is EPHEMERAL/state address of more than one ACTIVE window", ephemeralWindow); + "%s is EPHEMERAL/state address of more than one ACTIVE window", + ephemeralWindow); Preconditions.checkState(active.equals(windowToActiveWindow.get(ephemeralWindow)), "%s should have %s as its ACTIVE window", ephemeralWindow, active); } } for (Map.Entry entry : windowToActiveWindow.entrySet()) { Preconditions.checkState(activeWindowToStateAddressWindows.containsKey(entry.getValue()), - "%s should be ACTIVE since representative for %s", entry.getValue(), entry.getKey()); + "%s should be ACTIVE since mergeResultWindow for %s", + entry.getValue(), entry.getKey()); } } @@ -519,7 +542,9 @@ private static Map> emptyIfNull(@Nullable Map> multimap) } } - /** Return a deep copy of {@code multimap}. */ + /** + * Return a deep copy of {@code multimap}. + */ private static Map> deepCopy(Map> multimap) { Map> newMultimap = new HashMap<>(); for (Map.Entry> entry : multimap.entrySet()) { @@ -528,15 +553,19 @@ private static Map> deepCopy(Map> multimap) { return newMultimap; } - /** Return inversion of {@code multimap}, which must be invertible. */ + /** + * Return inversion of {@code multimap}, which must be invertible. + */ private static Map invert(Map> multimap) { Map result = new HashMap<>(); for (Map.Entry> entry : multimap.entrySet()) { W active = entry.getKey(); for (W target : entry.getValue()) { W previous = result.put(target, active); - Preconditions.checkState(previous == null, - "Window %s has both %s and %s as representatives", target, previous, active); + Preconditions.checkState( + previous == null, + "Multimap is not invertible: Window %s has both %s and %s as representatives", + target, previous, active); } } return result; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java index cb7f9b06e7..6fddc5d604 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java @@ -17,6 +17,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import java.util.Collection; @@ -30,13 +31,13 @@ */ public class NonMergingActiveWindowSet implements ActiveWindowSet { @Override - public void removeEphemeralWindows() {} + public void cleanupTemporaryWindows() {} @Override public void persist() {} @Override - public W representative(W window) { + public W mergeResultWindow(W window) { // Always represented by itself. return window; } @@ -54,9 +55,13 @@ public boolean isActive(W window) { } @Override - public void addNew(W window) {} + public void ensureWindowExists(W window) {} @Override + public void ensureWindowIsActive(W window) {} + + @Override + @VisibleForTesting public void addActive(W window) {} @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 7fc7ccc34d..106b356cb8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -18,7 +18,6 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; @@ -246,6 +245,11 @@ boolean isFinished(W window) { return triggerRunner.isClosed(contextFactory.base(window, StateStyle.DIRECT).state()); } + @VisibleForTesting + boolean hasNoActiveWindows() { + return activeWindows.getActiveWindows().isEmpty(); + } + /** * Incorporate {@code values} into the underlying reduce function, and manage holds, timers, * triggers, and window merging. @@ -293,7 +297,11 @@ public void processElements(Iterable> values) throws Excep } // We're all done with merging and emitting elements so can compress the activeWindow state. - activeWindows.removeEphemeralWindows(); + // Any windows which are still NEW must have come in on a new element which was then discarded + // due to the window's trigger being closed. We can thus delete them. + // Any windows which are EPHEMERAL must have come in on a new element but been merged away + // into some other ACTIVE window. We can thus also delete them. + activeWindows.cleanupTemporaryWindows(); } public void persist() { @@ -316,13 +324,7 @@ private void collectAndMergeWindows(Iterable> values) thro @SuppressWarnings("unchecked") W window = (W) untypedWindow; - ReduceFn.Context directContext = - contextFactory.base(window, StateStyle.DIRECT); - if (triggerRunner.isClosed(directContext.state())) { - // This window has already been closed. - // We will update the counter for this in the corresponding processElement call. - continue; - } + // For backwards compat with pre 1.4 only. if (activeWindows.isActive(window)) { Set stateAddressWindows = activeWindows.readStateAddresses(window); @@ -337,8 +339,11 @@ private void collectAndMergeWindows(Iterable> values) thro } } - // Add this window as NEW if we've not yet seen it. - activeWindows.addNew(window); + // Add this window as NEW if it is not currently ACTIVE or MERGED. + // If we had already seen this window and closed its trigger, then the + // window will not be ACTIVE or MERGED. It will then be added as NEW here, + // and fall into the merging logic as usual. + activeWindows.ensureWindowExists(window); } } @@ -390,7 +395,7 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W // Merge non-empty pane state. nonEmptyPanes.onMerge(renamedMergeContext.state()); - // Have the trigger merge state as needed + // Have the trigger merge state as needed. triggerRunner.onMerge( directMergeContext.window(), directMergeContext.timers(), directMergeContext.state()); @@ -439,19 +444,8 @@ private Collection processElement(WindowedValue value) throws Excepti ReduceFn.Context directContext = contextFactory.base(window, StateStyle.DIRECT); - if (triggerRunner.isClosed(directContext.state())) { - // This window has already been closed. - droppedDueToClosedWindow.addValue(1L); - WindowTracing.debug( - "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", - value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - continue; - } - - W active = activeWindows.representative(window); - Preconditions.checkState(active != null, "Window %s has no representative", window); + W active = activeWindows.mergeResultWindow(window); + Preconditions.checkState(active != null, "Window %s has no mergeResultWindow", window); windows.add(active); } @@ -462,10 +456,24 @@ private Collection processElement(WindowedValue value) throws Excepti triggerRunner.prefetchForValue(window, directContext.state()); } - // Process the element for each (representative, not closed) window it belongs to. + // Process the element for each (mergeResultWindow, not closed) window it belongs to. + List triggerableWindows = new ArrayList<>(windows.size()); for (W window : windows) { ReduceFn.ProcessValueContext directContext = contextFactory.forValue( window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); + if (triggerRunner.isClosed(directContext.state())) { + // This window has already been closed. + droppedDueToClosedWindow.addValue(1L); + WindowTracing.debug( + "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " + + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", + value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + continue; + } + + triggerableWindows.add(window); + activeWindows.ensureWindowIsActive(window); ReduceFn.ProcessValueContext renamedContext = contextFactory.forValue( window, value.getValue(), value.getTimestamp(), StateStyle.RENAMED); @@ -509,7 +517,7 @@ private Collection processElement(WindowedValue value) throws Excepti // (We don't actually assert this since it is too slow.) } - return windows; + return triggerableWindows; } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index 8fc498112e..8c096fdab3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -82,6 +82,13 @@ private FinishedTriggersBitSet readFinishedBits(ValueState state) { : FinishedTriggersBitSet.fromBitSet(bitSet); } + private void clearFinishedBits(ValueState state) { + if (!isFinishedSetNeeded()) { + // Nothing to clear. + return; + } + state.clear(); + } /** Return true if the trigger is closed in the window corresponding to the specified state. */ public boolean isClosed(StateAccessor state) { return readFinishedBits(state.access(FINISHED_BITS_TAG)).isFinished(rootTrigger); @@ -149,6 +156,8 @@ public void onMerge(W window, Timers timers, MergingStateAccessor state) t state.accessInEachMergingWindow(FINISHED_BITS_TAG).entrySet()) { // Don't need to clone these, since the trigger context doesn't allow modification builder.put(entry.getKey(), readFinishedBits(entry.getValue())); + // Clear the underlying finished bits. + clearFinishedBits(entry.getValue()); } ImmutableMap mergingFinishedSets = builder.build(); @@ -160,8 +169,6 @@ public void onMerge(W window, Timers timers, MergingStateAccessor state) t persistFinishedSet(state, finishedSet); - // Clear the finished bits. - clearFinished(state); } public boolean shouldFire(W window, Timers timers, StateAccessor state) throws Exception { @@ -199,12 +206,10 @@ private void persistFinishedSet( } /** - * Clear finished bits. + * Clear the finished bits. */ public void clearFinished(StateAccessor state) { - if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).clear(); - } + clearFinishedBits(state.access(FINISHED_BITS_TAG)); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java index 8f66e5a41c..16287bde83 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java @@ -82,20 +82,23 @@ public Collection windows() { }; for (IntervalWindow window : windowFn.assignWindows(context)) { - set.addNew(window); + set.ensureWindowExists(window); } } private void merge(ActiveWindowSet.MergeCallback callback) throws Exception { System.out.println("MERGE"); set.merge(callback); + for (IntervalWindow window : set.getActiveWindows()) { + set.ensureWindowIsActive(window); + } set.checkInvariants(); System.out.println(set); } private void pruneAndPersist() { System.out.println("PRUNE"); - set.removeEphemeralWindows(); + set.cleanupTemporaryWindows(); set.checkInvariants(); System.out.println(set); set.persist(); @@ -126,10 +129,10 @@ public void test() throws Exception { verify(callback).onMerge(ImmutableList.of(window(1, 10), window(2, 10)), ImmutableList.of(), window(1, 11)); assertEquals(ImmutableSet.of(window(1, 11), window(15, 10)), set.getActiveWindows()); - assertEquals(window(1, 11), set.representative(window(1, 10))); - assertEquals(window(1, 11), set.representative(window(2, 10))); - assertEquals(window(1, 11), set.representative(window(1, 11))); - assertEquals(window(15, 10), set.representative(window(15, 10))); + assertEquals(window(1, 11), set.mergeResultWindow(window(1, 10))); + assertEquals(window(1, 11), set.mergeResultWindow(window(2, 10))); + assertEquals(window(1, 11), set.mergeResultWindow(window(1, 11))); + assertEquals(window(15, 10), set.mergeResultWindow(window(15, 10))); assertEquals( ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 11))); assertEquals( @@ -145,7 +148,7 @@ public void test() throws Exception { verify(callback).onMerge(ImmutableList.of(window(1, 11), window(3, 10)), ImmutableList.of(window(1, 11)), window(1, 12)); assertEquals(ImmutableSet.of(window(1, 12), window(15, 10)), set.getActiveWindows()); - assertEquals(window(1, 12), set.representative(window(3, 10))); + assertEquals(window(1, 12), set.mergeResultWindow(window(3, 10))); // NEW 8+10 // => @@ -158,9 +161,9 @@ public void test() throws Exception { verify(callback).onMerge(ImmutableList.of(window(1, 12), window(8, 10), window(15, 10)), ImmutableList.of(window(1, 12), window(15, 10)), window(1, 24)); assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveWindows()); - assertEquals(window(1, 24), set.representative(window(1, 12))); - assertEquals(window(1, 24), set.representative(window(1, 11))); - assertEquals(window(1, 24), set.representative(window(15, 10))); + assertEquals(window(1, 24), set.mergeResultWindow(window(1, 12))); + assertEquals(window(1, 24), set.mergeResultWindow(window(1, 11))); + assertEquals(window(1, 24), set.mergeResultWindow(window(15, 10))); // NEW 9+10 // => diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index 646accd252..73b35b66f5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -723,9 +723,41 @@ public void testMergingWithCloseBeforeGC() throws Exception { equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); } + /** + * Ensure a closed trigger has its state recorded in the merge result window. + */ + @Test + public void testMergingWithCloseTrigger() throws Exception { + ReduceFnTester, IntervalWindow> tester = + ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), + ClosingBehavior.FIRE_IF_NON_EMPTY); + + // Create a new merged session window. + tester.injectElements(TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(2, new Instant(2))); + + // Force the trigger to be closed for the merged window. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + tester.advanceInputWatermark(new Instant(13)); + + // Trigger is now closed. + assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); + + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); + + // Revisit the same session window. + tester.injectElements(TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(2, new Instant(2))); + + // Trigger is still closed. + assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); + } + /** * If a later event tries to reuse an earlier session window which has been closed, we - * should reject that element and not fail due to the window no longer having a representative. + * should reject that element and not fail due to the window no longer being active. */ @Test public void testMergingWithReusedWindow() throws Exception { @@ -745,6 +777,8 @@ public void testMergingWithReusedWindow() throws Exception { // Another element in the same session window. // Should be discarded with 'window closed'. tester.injectElements(TimestampedValue.of(1, new Instant(1))); // in [1, 11), gc at 21. + // And nothing should be left in the active window state. + assertTrue(tester.hasNoActiveWindows()); // Now the garbage collection timer will fire, finding the trigger already closed. tester.advanceInputWatermark(new Instant(100)); @@ -761,6 +795,91 @@ public void testMergingWithReusedWindow() throws Exception { equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); } + /** + * When a merged window's trigger is closed we record that state using the merged window rather + * than the original windows. + */ + @Test + public void testMergingWithClosedRepresentative() throws Exception { + ReduceFnTester, IntervalWindow> tester = + ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), + ClosingBehavior.FIRE_IF_NON_EMPTY); + + // 2 elements into merged session window. + // Close the trigger, but the garbage collection timer is still pending. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + tester.injectElements(TimestampedValue.of(1, new Instant(1)), // in [1, 11), gc at 21. + TimestampedValue.of(8, new Instant(8))); // in [8, 18), gc at 28. + + // More elements into the same merged session window. + // It has not yet been gced. + // Should be discarded with 'window closed'. + tester.injectElements(TimestampedValue.of(1, new Instant(1)), // in [1, 11), gc at 21. + TimestampedValue.of(2, new Instant(2)), // in [2, 12), gc at 22. + TimestampedValue.of(8, new Instant(8))); // in [8, 18), gc at 28. + + // Now the garbage collection timer will fire, finding the trigger already closed. + tester.advanceInputWatermark(new Instant(100)); + + List>> output = tester.extractOutput(); + + assertThat(output.size(), equalTo(1)); + assertThat(output.get(0), + isSingleWindowedValue(containsInAnyOrder(1, 8), + 1, // timestamp + 1, // window start + 18)); // window end + assertThat( + output.get(0).getPane(), + equalTo(PaneInfo.createPane(true, true, Timing.EARLY, 0, 0))); + } + + /** + * If an element for a closed session window ends up being merged into other still-open + * session windows, the resulting session window is not 'poisoned'. + */ + @Test + public void testMergingWithClosedDoesNotPoison() throws Exception { + ReduceFnTester, IntervalWindow> tester = + ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, + AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), + ClosingBehavior.FIRE_IF_NON_EMPTY); + + // 1 element, force its trigger to close. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); + triggerShouldFinish(mockTrigger); + tester.injectElements(TimestampedValue.of(2, new Instant(2))); + + // 3 elements, one already closed. + when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); + tester.injectElements(TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(2, new Instant(2)), + TimestampedValue.of(3, new Instant(3))); + + tester.advanceInputWatermark(new Instant(100)); + + List>> output = tester.extractOutput(); + assertThat(output.size(), equalTo(2)); + assertThat(output.get(0), + isSingleWindowedValue(containsInAnyOrder(2), + 2, // timestamp + 2, // window start + 12)); // window end + assertThat( + output.get(0).getPane(), + equalTo(PaneInfo.createPane(true, true, Timing.EARLY, 0, 0))); + assertThat(output.get(1), + isSingleWindowedValue(containsInAnyOrder(1, 2, 3), + 1, // timestamp + 1, // window start + 13)); // window end + assertThat( + output.get(1).getPane(), + equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); + } + /** * Tests that when data is assigned to multiple windows but some of those windows have * had their triggers finish, then the data is dropped and counted accurately. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index 4aeaa0cb99..da31d81dd7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -235,6 +235,10 @@ public boolean isMarkedFinished(W window) { return createRunner().isFinished(window); } + public boolean hasNoActiveWindows() { + return createRunner().hasNoActiveWindows(); + } + @SafeVarargs public final void assertHasOnlyGlobalAndFinishedSetsFor(W... expectedWindows) { assertHasOnlyGlobalAndAllowedTags( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index f291438f8b..555de74a63 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -262,7 +262,7 @@ public final void injectElements(Collection> values) th for (BoundedWindow untypedWindow : windowedValue.getWindows()) { // SDK is responsible for type safety @SuppressWarnings("unchecked") - W window = activeWindows.representative((W) untypedWindow); + W window = activeWindows.mergeResultWindow((W) untypedWindow); Trigger.OnElementContext context = contextFactory.createOnElementContext(window, new TestTimers(windowNamespace(window)), windowedValue.getTimestamp(), From 0c95a3d5af512a558cb575fee9bd9c1496497bd0 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 18 Mar 2016 11:00:20 -0700 Subject: [PATCH 299/751] Implement InProcessCreate with an OffsetBasedSource This allows dynamic splits to be exercised in the create. --- .../runners/inprocess/InProcessCreate.java | 147 +++++++++--------- .../inprocess/InProcessCreateTest.java | 62 ++++++-- 2 files changed, 123 insertions(+), 86 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java index 9023b7b2dc..614989fc22 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java @@ -19,6 +19,8 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.OffsetBasedSource; +import com.google.cloud.dataflow.sdk.io.OffsetBasedSource.OffsetBasedReader; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -31,12 +33,8 @@ import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterators; -import com.google.common.collect.PeekingIterator; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; @@ -73,7 +71,7 @@ public PCollection apply(PInput input) { } InMemorySource source; try { - source = new InMemorySource<>(original.getElements(), elementCoder); + source = InMemorySource.fromIterable(original.getElements(), elementCoder); } catch (IOException e) { throw Throwables.propagate(e); } @@ -88,55 +86,34 @@ public PTransform> delegate() { } @VisibleForTesting - static class InMemorySource extends BoundedSource { - private final Collection allElementsBytes; + static class InMemorySource extends OffsetBasedSource { + private final List allElementsBytes; private final long totalSize; private final Coder coder; - public InMemorySource(Iterable elements, Coder elemCoder) + public static InMemorySource fromIterable(Iterable elements, Coder elemCoder) throws CoderException, IOException { - allElementsBytes = new ArrayList<>(); + ImmutableList.Builder allElementsBytes = ImmutableList.builder(); long totalSize = 0L; for (T element : elements) { byte[] bytes = CoderUtils.encodeToByteArray(elemCoder, element); allElementsBytes.add(bytes); totalSize += bytes.length; } - this.totalSize = totalSize; - this.coder = elemCoder; + return new InMemorySource<>(allElementsBytes.build(), totalSize, elemCoder); } /** * Create a new source with the specified bytes. The new source owns the input element bytes, * which must not be modified after this constructor is called. */ - private InMemorySource(Collection elementBytes, long totalSize, Coder coder) { + private InMemorySource(List elementBytes, long totalSize, Coder coder) { + super(0, elementBytes.size(), 1); this.allElementsBytes = ImmutableList.copyOf(elementBytes); this.totalSize = totalSize; this.coder = coder; } - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - ImmutableList.Builder> resultBuilder = ImmutableList.builder(); - long currentSourceSize = 0L; - List currentElems = new ArrayList<>(); - for (byte[] elemBytes : allElementsBytes) { - currentElems.add(elemBytes); - currentSourceSize += elemBytes.length; - if (currentSourceSize >= desiredBundleSizeBytes) { - resultBuilder.add(new InMemorySource<>(currentElems, currentSourceSize, coder)); - currentElems.clear(); - currentSourceSize = 0L; - } - } - if (!currentElems.isEmpty()) { - resultBuilder.add(new InMemorySource<>(currentElems, currentSourceSize, coder)); - } - return resultBuilder.build(); - } - @Override public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { return totalSize; @@ -149,7 +126,7 @@ public boolean producesSortedKeys(PipelineOptions options) throws Exception { @Override public BoundedSource.BoundedReader createReader(PipelineOptions options) throws IOException { - return new BytesReader(); + return new BytesReader<>(this); } @Override @@ -160,50 +137,80 @@ public Coder getDefaultOutputCoder() { return coder; } - private class BytesReader extends BoundedReader { - private final PeekingIterator iter; - /** - * Use an optional to distinguish between null next element (as Optional.absent()) and no next - * element (next is null). - */ - @Nullable private Optional next; + @Override + public long getMaxEndOffset(PipelineOptions options) throws Exception { + return allElementsBytes.size(); + } - public BytesReader() { - this.iter = Iterators.peekingIterator(allElementsBytes.iterator()); - } + @Override + public OffsetBasedSource createSourceForSubrange(long start, long end) { + List primaryElems = allElementsBytes.subList((int) start, (int) end); + long primarySizeEstimate = + (long) (totalSize * primaryElems.size() / (double) allElementsBytes.size()); + return new InMemorySource<>(primaryElems, primarySizeEstimate, coder); + } - @Override - public BoundedSource getCurrentSource() { - return InMemorySource.this; + @Override + public long getBytesPerOffset() { + if (allElementsBytes.size() == 0) { + return 0L; } + return totalSize / allElementsBytes.size(); + } + } - @Override - public boolean start() throws IOException { - return advance(); - } + private static class BytesReader extends OffsetBasedReader { + private int index; + /** + * Use an optional to distinguish between null next element (as Optional.absent()) and no next + * element (next is null). + */ + @Nullable private Optional next; - @Override - public boolean advance() throws IOException { - boolean hasNext = iter.hasNext(); - if (hasNext) { - next = Optional.fromNullable(CoderUtils.decodeFromByteArray(coder, iter.next())); - } else { - next = null; - } - return hasNext; - } + public BytesReader(InMemorySource source) { + super(source); + index = -1; + } - @Override - @Nullable - public T getCurrent() throws NoSuchElementException { - if (next == null) { - throw new NoSuchElementException(); - } - return next.orNull(); + @Override + @Nullable + public T getCurrent() throws NoSuchElementException { + if (next == null) { + throw new NoSuchElementException(); } + return next.orNull(); + } + + @Override + public void close() throws IOException {} + + @Override + protected long getCurrentOffset() { + return index; + } - @Override - public void close() throws IOException {} + @Override + protected boolean startImpl() throws IOException { + return advanceImpl(); + } + + @Override + public synchronized InMemorySource getCurrentSource() { + return (InMemorySource) super.getCurrentSource(); + } + + @Override + protected boolean advanceImpl() throws IOException { + InMemorySource source = getCurrentSource(); + index++; + if (index >= source.allElementsBytes.size()) { + return false; + } + next = + Optional.fromNullable( + CoderUtils.decodeFromByteArray( + source.coder, source.allElementsBytes.get(index))); + return true; } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java index 4db014e3ee..543ab2968a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java @@ -22,11 +22,11 @@ import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.NullableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.io.BoundedSource; @@ -34,6 +34,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessCreate.InMemorySource; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -44,6 +45,7 @@ import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; +import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -52,8 +54,9 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; -import java.util.Collections; +import java.util.ArrayList; import java.util.List; +import java.util.Random; /** * Tests for {@link InProcessCreate}. @@ -64,6 +67,7 @@ public class InProcessCreateTest { public ExpectedException thrown = ExpectedException.none(); @Test + @Category(RunnableOnService.class) public void testConvertsCreate() { TestPipeline p = TestPipeline.create(); Create.Values og = Create.of(1, 2, 3); @@ -74,6 +78,7 @@ public void testConvertsCreate() { } @Test + @Category(RunnableOnService.class) public void testConvertsCreateWithNullElements() { Create.Values og = Create.of("foo", null, "spam", "ham", null, "eggs") @@ -127,7 +132,7 @@ public boolean equals(Object o) { return myString.equals(((UnserializableRecord) o).myString); } - static class UnserializableRecordCoder extends StandardCoder { + static class UnserializableRecordCoder extends AtomicCoder { private final Coder stringCoder = StringUtf8Coder.of(); @Override @@ -145,17 +150,28 @@ public UnserializableRecord decode( throws CoderException, IOException { return new UnserializableRecord(stringCoder.decode(inStream, context.nested())); } + } + } - @Override - public List> getCoderArguments() { - return Collections.emptyList(); - } + @Test + @Category(RunnableOnService.class) + public void testConvertsUnserializableElements() throws Exception { + List elements = + ImmutableList.of( + new UnserializableRecord("foo"), + new UnserializableRecord("bar"), + new UnserializableRecord("baz")); + InProcessCreate create = + InProcessCreate.from( + Create.of(elements).withCoder(new UnserializableRecord.UnserializableRecordCoder())); - @Override - public void verifyDeterministic() throws Coder.NonDeterministicException { - stringCoder.verifyDeterministic(); - } - } + TestPipeline p = TestPipeline.create(); + DataflowAssert.that(p.apply(create)) + .containsInAnyOrder( + new UnserializableRecord("foo"), + new UnserializableRecord("bar"), + new UnserializableRecord("baz")); + p.run(); } @Test @@ -166,14 +182,15 @@ public void testSerializableOnUnserializableElements() throws Exception { new UnserializableRecord("bar"), new UnserializableRecord("baz")); InMemorySource source = - new InMemorySource<>(elements, new UnserializableRecord.UnserializableRecordCoder()); + InMemorySource.fromIterable(elements, new UnserializableRecord.UnserializableRecordCoder()); SerializableUtils.ensureSerializable(source); } @Test public void testSplitIntoBundles() throws Exception { InProcessCreate.InMemorySource source = - new InMemorySource<>(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), BigEndianIntegerCoder.of()); + InMemorySource.fromIterable( + ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), BigEndianIntegerCoder.of()); PipelineOptions options = PipelineOptionsFactory.create(); List> splitSources = source.splitIntoBundles(12, options); assertThat(splitSources, hasSize(3)); @@ -183,7 +200,7 @@ public void testSplitIntoBundles() throws Exception { @Test public void testDoesNotProduceSortedKeys() throws Exception { InProcessCreate.InMemorySource source = - new InMemorySource<>(ImmutableList.of("spam", "ham", "eggs"), StringUtf8Coder.of()); + InMemorySource.fromIterable(ImmutableList.of("spam", "ham", "eggs"), StringUtf8Coder.of()); assertThat(source.producesSortedKeys(PipelineOptionsFactory.create()), is(false)); } @@ -191,9 +208,22 @@ public void testDoesNotProduceSortedKeys() throws Exception { public void testGetDefaultOutputCoderReturnsConstructorCoder() throws Exception { Coder coder = VarIntCoder.of(); InProcessCreate.InMemorySource source = - new InMemorySource<>(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), coder); + InMemorySource.fromIterable(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), coder); Coder defaultCoder = source.getDefaultOutputCoder(); assertThat(defaultCoder, equalTo(coder)); } + + @Test + public void testSplitAtFraction() throws Exception { + List elements = new ArrayList<>(); + Random random = new Random(); + for (int i = 0; i < 25; i++) { + elements.add(random.nextInt()); + } + InProcessCreate.InMemorySource source = + InMemorySource.fromIterable(elements, VarIntCoder.of()); + + SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); + } } From b3b502613ee80333b153b0499dc5635e872ffb72 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 7 Apr 2016 08:57:12 -0700 Subject: [PATCH 300/751] Fix Test locations --- ...ImmutabilityCheckingBundleFactoryTest.java | 22 ++++++++--------- .../inprocess/InProcessBundleFactoryTest.java | 24 +++++++++---------- 2 files changed, 21 insertions(+), 25 deletions(-) rename {sdks/java/core => sdk}/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java (92%) rename {sdks/java/core => sdk}/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java (91%) diff --git a/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java similarity index 92% rename from sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java index 40b1d5a69e..7d29061335 100644 --- a/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java @@ -1,19 +1,17 @@ /* - * 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 + * Copyright (C) 2016 Google Inc. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed 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. + * 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 com.google.cloud.dataflow.sdk.runners.inprocess; diff --git a/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java similarity index 91% rename from sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java index 060d43cfe7..939976bfad 100644 --- a/sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java @@ -1,19 +1,17 @@ -/* - * 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 + /* + * Copyright (C) 2016 Google Inc. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed 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. + * 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 com.google.cloud.dataflow.sdk.runners.inprocess; From ea3ba7eff6456413d10f4c1c88bcdb8111eb190b Mon Sep 17 00:00:00 2001 From: bchambers Date: Thu, 31 Mar 2016 15:18:09 -0700 Subject: [PATCH 301/751] DebuggingWordCount now takes filter as an option Previously it was hard-coded as "Flourish|stomach". Now it is a PipelineOption with that as the default. This allows "breaking" the pipeline by mis-specifying the pattern without changing the code. --- .../dataflow/examples/DebuggingWordCount.java | 20 ++++++++++++++++-- .../src/main/java/DebuggingWordCount.java | 21 +++++++++++++++++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java index 8823dbc323..df4cd74efc 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java @@ -16,9 +16,10 @@ package com.google.cloud.dataflow.examples; -import com.google.cloud.dataflow.examples.WordCount.WordCountOptions; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.options.Default; +import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.transforms.Aggregator; @@ -150,6 +151,21 @@ public void processElement(ProcessContext c) { } } + /** + * Options supported by {@link DebuggingWordCount}. + * + *

        Inherits standard configuration options and all options defined in + * {@link WordCount.WordCountOptions}. + */ + public static interface WordCountOptions extends WordCount.WordCountOptions { + + @Description("Regex filter pattern to use in DebuggingWordCount. " + + "Only words matching this pattern will be counted.") + @Default.String("Flourish|stomach") + String getFilterPattern(); + void setFilterPattern(String value); + } + public static void main(String[] args) { WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() .as(WordCountOptions.class); @@ -158,7 +174,7 @@ public static void main(String[] args) { PCollection> filteredWords = p.apply(TextIO.Read.named("ReadLines").from(options.getInputFile())) .apply(new WordCount.CountWords()) - .apply(ParDo.of(new FilterTextFn("Flourish|stomach"))); + .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); /** * Concept #4: DataflowAssert is a set of convenient PTransforms in the style of diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java index 3cf2bc0dff..299e3b7fe2 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java @@ -16,9 +16,11 @@ package ${package}; -import ${package}.WordCount.WordCountOptions; +import ${package}.WordCount; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.options.Default; +import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.transforms.Aggregator; @@ -149,6 +151,21 @@ public void processElement(ProcessContext c) { } } } + + /** + * Options supported by {@link DebuggingWordCount}. + * + *

        Inherits standard configuration options and all options defined in + * {@link WordCount.WordCountOptions}. + */ + public static interface WordCountOptions extends WordCount.WordCountOptions { + + @Description("Regex filter pattern to use in DebuggingWordCount. " + + "Only words matching this pattern will be counted.") + @Default.String("Flourish|stomach") + String getFilterPattern(); + void setFilterPattern(String value); + } public static void main(String[] args) { WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() @@ -158,7 +175,7 @@ public static void main(String[] args) { PCollection> filteredWords = p.apply(TextIO.Read.named("ReadLines").from(options.getInputFile())) .apply(new WordCount.CountWords()) - .apply(ParDo.of(new FilterTextFn("Flourish|stomach"))); + .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); /** * Concept #4: DataflowAssert is a set of convenient PTransforms in the style of From cdb7d0b84e89e502ab518005a7e0f658d073c43d Mon Sep 17 00:00:00 2001 From: bchambers Date: Fri, 1 Apr 2016 11:28:04 -0700 Subject: [PATCH 302/751] Add the MaxConditionCost option --- .../sdk/options/CloudDebuggerOptions.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java index 2e1ad9451f..16acc9cd25 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java @@ -29,15 +29,23 @@ @Hidden public interface CloudDebuggerOptions { - /** - * Whether to enable the Cloud Debugger snapshot agent for the current job. - */ + /** Whether to enable the Cloud Debugger snapshot agent for the current job. */ @Description("Whether to enable the Cloud Debugger snapshot agent for the current job.") boolean getEnableCloudDebugger(); void setEnableCloudDebugger(boolean enabled); - @Description("The Cloud Debugger debugee to associate with. This should not be set directly.") + /** The Cloud Debugger debuggee to associate with. This should not be set directly. */ + @Description("The Cloud Debugger debuggee to associate with. This should not be set directly.") @Hidden @Nullable Debuggee getDebuggee(); void setDebuggee(Debuggee debuggee); + + /** The maximum cost (as a ratio of CPU time) allowed for evaluating conditional snapshots. */ + @Description( + "The maximum cost (as a ratio of CPU time) allowed for evaluating conditional snapshots. " + + "Should be a double between 0 and 1. " + + "Snapshots will be cancelled if evaluating conditions takes more than this ratio of time.") + @Default.Double(0.01) + double getMaxConditionCost(); + void setMaxConditionCost(double maxConditionCost); } From 9a5f1b61a7894c5f03465ea4eb6be09ef70a33d6 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 29 Mar 2016 18:37:30 -0700 Subject: [PATCH 303/751] Add TextIO and AvroIO withNumShards tests --- .../cloud/dataflow/sdk/io/AvroIOTest.java | 68 ++++++++++++++----- .../cloud/dataflow/sdk/io/TextIOTest.java | 56 +++++++++++---- 2 files changed, 91 insertions(+), 33 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java index 2258a9136f..7db558dc5a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.DefaultCoder; +import com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound; import com.google.cloud.dataflow.sdk.runners.DirectPipeline; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -44,6 +45,7 @@ import org.junit.runners.JUnit4; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -197,30 +199,60 @@ public void testAvroIOWriteAndReadSchemaUpgrade() throws Throwable { } @SuppressWarnings("deprecation") // using AvroCoder#createDatumReader for tests. - @Test - public void testAvroSinkWrite() throws Exception { - String outputFilePrefix = new File(tmpFolder.getRoot(), "prefix").getAbsolutePath(); - String[] expectedElements = new String[] {"first", "second", "third"}; - + private void runTestWrite(String[] expectedElements, int numShards) throws IOException { + File baseOutputFile = new File(tmpFolder.getRoot(), "prefix"); + String outputFilePrefix = baseOutputFile.getAbsolutePath(); TestPipeline p = TestPipeline.create(); - p.apply(Create.of(expectedElements)) - .apply(AvroIO.Write.to(outputFilePrefix).withSchema(String.class)); + Bound write = AvroIO.Write.to(outputFilePrefix).withSchema(String.class); + if (numShards > 1) { + write = write.withNumShards(numShards); + } else { + write = write.withoutSharding(); + } + p.apply(Create.of(expectedElements)).apply(write); p.run(); // Validate that the data written matches the expected elements in the expected order - String expectedName = - IOChannelUtils.constructName( - outputFilePrefix, ShardNameTemplate.INDEX_OF_MAX, "" /* no suffix */, 0, 1); - File outputFile = new File(expectedName); - assertTrue("Expected output file " + expectedName, outputFile.exists()); - try (DataFileReader reader = - new DataFileReader<>(outputFile, AvroCoder.of(String.class).createDatumReader())) { - List actualElements = new ArrayList<>(); - Iterators.addAll(actualElements, reader); - assertThat(actualElements, containsInAnyOrder(expectedElements)); + List expectedFiles = new ArrayList<>(); + if (numShards == 1) { + expectedFiles.add(baseOutputFile); + } else { + for (int i = 0; i < numShards; i++) { + expectedFiles.add( + new File( + IOChannelUtils.constructName( + outputFilePrefix, + write.getShardNameTemplate(), + "" /* no suffix */, + i, + numShards))); + } + } + + List actualElements = new ArrayList<>(); + for (File outputFile : expectedFiles) { + assertTrue("Expected output file " + outputFile.getName(), outputFile.exists()); + try (DataFileReader reader = + new DataFileReader<>(outputFile, AvroCoder.of(String.class).createDatumReader())) { + Iterators.addAll(actualElements, reader); + } } + assertThat(actualElements, containsInAnyOrder(expectedElements)); } - // TODO: for Write only, test withSuffix, withNumShards, + @Test + public void testAvroSinkWrite() throws Exception { + String[] expectedElements = new String[] {"first", "second", "third"}; + + runTestWrite(expectedElements, 1); + } + + @Test + public void testAvroSinkShardedWrite() throws Exception { + String[] expectedElements = new String[] {"first", "second", "third", "fourth", "fifth"}; + + runTestWrite(expectedElements, 4); + } + // TODO: for Write only, test withSuffix, // withShardNameTemplate and withoutSharding. } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 0a8e381108..40d11d9866 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -42,6 +42,7 @@ import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.GcsUtil; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -198,36 +199,57 @@ public void testReadNamed() throws Exception { } void runTestWrite(T[] elems, Coder coder) throws Exception { - File tmpFile = tmpFolder.newFile("file.txt"); - String filename = tmpFile.getPath(); + runTestWrite(elems, coder, 1); + } + + void runTestWrite(T[] elems, Coder coder, int numShards) throws Exception { + String filename = tmpFolder.newFile("file.txt").getPath(); Pipeline p = TestPipeline.create(); - PCollection input = - p.apply(Create.of(Arrays.asList(elems)).withCoder(coder)); + PCollection input = p.apply(Create.of(Arrays.asList(elems)).withCoder(coder)); TextIO.Write.Bound write; if (coder.equals(StringUtf8Coder.of())) { - TextIO.Write.Bound writeStrings = - TextIO.Write.to(filename).withoutSharding(); + TextIO.Write.Bound writeStrings = TextIO.Write.to(filename); // T==String write = (TextIO.Write.Bound) writeStrings; } else { - write = TextIO.Write.to(filename).withCoder(coder).withoutSharding(); + write = TextIO.Write.to(filename).withCoder(coder); + } + if (numShards == 1) { + write = write.withoutSharding(); + } else { + write = write.withNumShards(numShards).withShardNameTemplate(ShardNameTemplate.INDEX_OF_MAX); } input.apply(write); p.run(); + List expectedFiles = new ArrayList<>(); + if (numShards == 1) { + expectedFiles.add(new File(filename)); + } else { + for (int i = 0; i < numShards; i++) { + expectedFiles.add( + new File( + tmpFolder.getRoot(), + IOChannelUtils.constructName( + "file.txt", ShardNameTemplate.INDEX_OF_MAX, "", i, numShards))); + } + } + List actual = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader(new FileReader(tmpFile))) { - for (;;) { - String line = reader.readLine(); - if (line == null) { - break; + for (File tmpFile : expectedFiles) { + try (BufferedReader reader = new BufferedReader(new FileReader(tmpFile))) { + for (;;) { + String line = reader.readLine(); + if (line == null) { + break; + } + actual.add(line); } - actual.add(line); } } @@ -239,8 +261,7 @@ void runTestWrite(T[] elems, Coder coder) throws Exception { expected[i] = line; } - assertThat(actual, - containsInAnyOrder(expected)); + assertThat(actual, containsInAnyOrder(expected)); } @Test @@ -284,6 +305,11 @@ public void testWriteNamed() { } } + @Test + public void testShardedWrite() throws Exception { + runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), 5); + } + @Test public void testUnsupportedFilePattern() throws IOException { File outFolder = tmpFolder.newFolder(); From 5890836bc4d326fe74a153a09347d9d766e4b90b Mon Sep 17 00:00:00 2001 From: Eugene Kirpichov Date: Thu, 7 Apr 2016 12:29:38 -0700 Subject: [PATCH 304/751] [BEAM-182] Bound trials in assertSplitAtFraction At most 100 trials per item and 1000 trials total. This appears to be enough for tests such as AvroSourceTest in the majority of cases, which means if bugs exist, they will be found often enough. --- .../dataflow/sdk/testing/SourceTestUtils.java | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java index b8f9b0b423..df92332c86 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java @@ -31,6 +31,8 @@ import com.google.cloud.dataflow.sdk.values.KV; import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; @@ -71,6 +73,8 @@ *

        Like {@link DataflowAssert}, requires JUnit and Hamcrest to be present in the classpath. */ public class SourceTestUtils { + private static final Logger LOG = LoggerFactory.getLogger(SourceTestUtils.class); + // A wrapper around a value of type T that compares according to the structural // value provided by a Coder, but prints both the original and structural value, // to help get good error messages from JUnit equality assertion failures and such. @@ -530,6 +534,9 @@ private static void assertSplitAtFractionBinary( } } + private static final int MAX_CONCURRENT_SPLITTING_TRIALS_PER_ITEM = 100; + private static final int MAX_CONCURRENT_SPLITTING_TRIALS_TOTAL = 1000; + /** * Asserts that for each possible start position, * {@link BoundedSource.BoundedReader#splitAtFraction} at every interesting fraction (halfway @@ -571,6 +578,7 @@ public static void assertSplitAtFractionExhaustive( // To ensure that the test is non-vacuous, make sure that the splitting succeeds // at least once and fails at least once. ExecutorService executor = Executors.newFixedThreadPool(2); + int numTotalTrials = 0; for (int i = 0; i < expectedItems.size(); i++) { double minNonTrivialFraction = 2.0; // Greater than any possible fraction. for (double fraction : allNonTrivialFractions.get(i)) { @@ -581,16 +589,41 @@ public static void assertSplitAtFractionExhaustive( // detect vacuousness. continue; } + int numTrials = 0; boolean haveSuccess = false, haveFailure = false; - while (!haveSuccess || !haveFailure) { + while (true) { + ++numTrials; + if (numTrials > MAX_CONCURRENT_SPLITTING_TRIALS_PER_ITEM) { + LOG.warn( + "After {} concurrent splitting trials at item #{}, observed only {}, " + + "giving up on this item", + numTrials, i, haveSuccess ? "success" : "failure"); + break; + } if (assertSplitAtFractionConcurrent( executor, source, expectedItems, i, minNonTrivialFraction, options)) { haveSuccess = true; } else { haveFailure = true; } + if (haveSuccess && haveFailure) { + LOG.info( + "{} trials to observe both success and failure of concurrent splitting at item #{}", + numTrials, i); + break; + } + } + numTotalTrials += numTrials; + if (numTotalTrials > MAX_CONCURRENT_SPLITTING_TRIALS_TOTAL) { + LOG.warn( + "After {} total concurrent splitting trials, considered only {} items, giving up.", + numTotalTrials, i); + break; } } + LOG.info( + "{} total concurrent splitting trials for {} items", + numTotalTrials, expectedItems.size()); } } From a4b1e8fae1f4d40f4eec018ff18eac4d538fa3c0 Mon Sep 17 00:00:00 2001 From: Pei He Date: Fri, 8 Apr 2016 14:26:58 -0700 Subject: [PATCH 305/751] Move tempLocation to PipelineOptions. It is back ported from: https://github.com/apache/incubator-beam/pull/44 --- .../sdk/options/DataflowPipelineOptions.java | 20 ------------------- .../dataflow/sdk/options/PipelineOptions.java | 14 +++++++++++++ .../sdk/runners/DataflowPipelineRunner.java | 4 ++++ .../runners/DataflowPipelineRunnerTest.java | 7 ++----- 4 files changed, 20 insertions(+), 25 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java index 1aa434299c..5b73cac16e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java @@ -34,8 +34,6 @@ public interface DataflowPipelineOptions extends GcsOptions, StreamingOptions, CloudDebuggerOptions, DataflowWorkerLoggingOptions, DataflowProfilingOptions { - static final String DATAFLOW_STORAGE_LOCATION = "Dataflow Storage Location"; - @Description("Project id. Required when running a Dataflow in the cloud. " + "See https://cloud.google.com/storage/docs/projects for further details.") @Override @@ -45,23 +43,6 @@ public interface DataflowPipelineOptions extends @Override void setProject(String value); - /** - * GCS path for temporary files, e.g. gs://bucket/object - * - *

        Must be a valid Cloud Storage URL, beginning with the prefix "gs://" - * - *

        At least one of {@link #getTempLocation()} or {@link #getStagingLocation()} must be set. If - * {@link #getTempLocation()} is not set, then the Dataflow pipeline defaults to using - * {@link #getStagingLocation()}. - */ - @Description("GCS path for temporary files, eg \"gs://bucket/object\". " - + "Must be a valid Cloud Storage URL, beginning with the prefix \"gs://\". " - + "At least one of tempLocation or stagingLocation must be set. If tempLocation is unset, " - + "defaults to using stagingLocation.") - @Validation.Required(groups = {DATAFLOW_STORAGE_LOCATION}) - String getTempLocation(); - void setTempLocation(String value); - /** * GCS path for staging local files, e.g. gs://bucket/object * @@ -75,7 +56,6 @@ public interface DataflowPipelineOptions extends + "Must be a valid Cloud Storage URL, beginning with the prefix \"gs://\". " + "At least one of stagingLocation or tempLocation must be set. If stagingLocation is unset, " + "defaults to using tempLocation.") - @Validation.Required(groups = {DATAFLOW_STORAGE_LOCATION}) String getStagingLocation(); void setStagingLocation(String value); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java index 8ff1fa9783..41fa45c9fc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java @@ -246,4 +246,18 @@ public static enum CheckEnabled { @Default.Enum("WARNING") CheckEnabled getStableUniqueNames(); void setStableUniqueNames(CheckEnabled enabled); + + /** + * A pipeline level default location for storing temporary files. + * + *

        This can be a path of any file system. + * + *

        {@link #getTempLocation()} can be used as a default location in other + * {@link PipelineOptions}. + * + *

        If it is unset, {@link PipelineRunner} can override it. + */ + @Description("A pipeline level default location for storing temporary files.") + String getTempLocation(); + void setTempLocation(String value); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 972cc5ebdc..99bbb257d6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -251,6 +251,10 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { } PathValidator validator = dataflowOptions.getPathValidator(); + Preconditions.checkArgument(!(Strings.isNullOrEmpty(dataflowOptions.getTempLocation()) + && Strings.isNullOrEmpty(dataflowOptions.getStagingLocation())), + "Missing required value: at least one of tempLocation or stagingLocation must be set."); + if (dataflowOptions.getStagingLocation() != null) { validator.validateOutputFilePrefixSupported(dataflowOptions.getStagingLocation()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index c5f2d3fe71..05ee798162 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -649,11 +649,8 @@ public void testNoStagingLocationAndNoTempLocationFails() { options.setProject("foo-project"); thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Missing required value for group"); - thrown.expectMessage(DataflowPipelineOptions.DATAFLOW_STORAGE_LOCATION); - thrown.expectMessage("getStagingLocation"); - thrown.expectMessage("getTempLocation"); - + thrown.expectMessage( + "Missing required value: at least one of tempLocation or stagingLocation must be set."); DataflowPipelineRunner.fromOptions(options); } From 08d8bb8028414cb0d917226676b93252c7226301 Mon Sep 17 00:00:00 2001 From: Henning Rohde Date: Fri, 8 Apr 2016 17:05:57 -0700 Subject: [PATCH 306/751] [BEAM-186] Fix pubsub injector for streaming examples --- .../cloud/dataflow/examples/common/DataflowExampleUtils.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java index 4dfdd85b80..416ee62fa6 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java @@ -354,6 +354,8 @@ public void runInjectorPipeline(PTransform> copiedOptions.setServiceAccountKeyfile(options.getServiceAccountKeyfile()); } copiedOptions.setStreaming(false); + copiedOptions.setWorkerHarnessContainerImage( + DataflowPipelineRunner.BATCH_WORKER_HARNESS_CONTAINER_IMAGE); copiedOptions.setNumWorkers(options.as(DataflowExampleOptions.class).getInjectorNumWorkers()); copiedOptions.setJobName(options.getJobName() + "-injector"); Pipeline injectorPipeline = Pipeline.create(copiedOptions); From d18ab5d64a5f80db29222e3a8e2d41423b89e99b Mon Sep 17 00:00:00 2001 From: Henning Rohde Date: Fri, 8 Apr 2016 17:49:21 -0700 Subject: [PATCH 307/751] [BEAM-186] Fix pubsub injector for streaming example archtypes --- .../src/main/java/common/DataflowExampleUtils.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java index 98617699ad..ccf1f9e8b9 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java @@ -272,6 +272,8 @@ public void setupRunner() { public void runInjectorPipeline(String inputFile, String topic) { DataflowPipelineOptions copiedOptions = options.cloneAs(DataflowPipelineOptions.class); copiedOptions.setStreaming(false); + copiedOptions.setWorkerHarnessContainerImage( + DataflowPipelineRunner.BATCH_WORKER_HARNESS_CONTAINER_IMAGE); copiedOptions.setNumWorkers( options.as(ExamplePubsubTopicOptions.class).getInjectorNumWorkers()); copiedOptions.setJobName(options.getJobName() + "-injector"); From 4074824775ebdfaf0b30845e687856e2a246ac52 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 29 Mar 2016 10:27:37 -0700 Subject: [PATCH 308/751] Schedule all pending work before firing timers Pull all available work off of the ExecutorUpdate queue during each execution of the MonitorRunnable. --- .../runners/inprocess/ExecutorServiceParallelExecutor.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index dd73d67f0c..fa2c428057 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -323,13 +323,15 @@ public void run() { Thread.currentThread().setName(runnableName); try { ExecutorUpdate update = allUpdates.poll(); - if (update != null) { + // pull all of the pending work off of the queue + while (update != null) { LOG.debug("Executor Update: {}", update); if (update.getBundle().isPresent()) { scheduleConsumers(update.getBundle().get()); } else if (update.getException().isPresent()) { visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); } + update = allUpdates.poll(); } boolean timersFired = fireTimers(); addWorkIfNecessary(timersFired); From 33ccb5617bdad9fe22f5d7a843d205967c8f361b Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 29 Mar 2016 10:56:10 -0700 Subject: [PATCH 309/751] Use a weakValues LoadingCache for serial TransformExecutorServices This allows the garbage collector to clean up references to TransformExecutorServices which are not currently in use. --- .../ExecutorServiceParallelExecutor.java | 36 +++++++++++++------ 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index fa2c428057..cca19552dc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -29,6 +29,9 @@ import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import org.joda.time.Instant; @@ -67,7 +70,7 @@ final class ExecutorServiceParallelExecutor implements InProcessExecutor { private final InProcessEvaluationContext evaluationContext; - private final ConcurrentMap currentEvaluations; + private final LoadingCache executorServices; private final ConcurrentMap, Boolean> scheduledExecutors; private final Queue allUpdates; @@ -105,8 +108,12 @@ private ExecutorServiceParallelExecutor( this.transformEnforcements = transformEnforcements; this.evaluationContext = context; - currentEvaluations = new ConcurrentHashMap<>(); scheduledExecutors = new ConcurrentHashMap<>(); + // Weak Values allows TransformExecutorServices that are no longer in use to be reclaimed. + // Executing TransformExecutorServices have a strong reference to their TransformExecutorService + // which stops the TransformExecutorServices from being prematurely garbage collected + executorServices = + CacheBuilder.newBuilder().weakValues().build(serialTransformExecutorServiceCacheLoader()); this.allUpdates = new ConcurrentLinkedQueue<>(); this.visibleUpdates = new ArrayBlockingQueue<>(20); @@ -116,6 +123,16 @@ private ExecutorServiceParallelExecutor( defaultCompletionCallback = new DefaultCompletionCallback(); } + private CacheLoader + serialTransformExecutorServiceCacheLoader() { + return new CacheLoader() { + @Override + public TransformExecutorService load(StepAndKey stepAndKey) throws Exception { + return TransformExecutorServices.serial(executorService, scheduledExecutors); + } + }; + } + @Override public void start(Collection> roots) { rootNodes = ImmutableList.copyOf(roots); @@ -140,7 +157,12 @@ private void evaluateBundle( if (bundle != null && isKeyed(bundle.getPCollection())) { final StepAndKey stepAndKey = StepAndKey.of(transform, bundle == null ? null : bundle.getKey()); - transformExecutor = getSerialExecutorService(stepAndKey); + // This executor will remain reachable until it has executed all scheduled transforms. + // The TransformExecutors keep a strong reference to the Executor, the ExecutorService keeps + // a reference to the scheduled TransformExecutor callable. Follow-up TransformExecutors + // (scheduled due to the completion of another TransformExecutor) are provided to the + // ExecutorService before the Earlier TransformExecutor callable completes. + transformExecutor = executorServices.getUnchecked(stepAndKey); } else { transformExecutor = parallelExecutorService; } @@ -172,14 +194,6 @@ private void scheduleConsumers(CommittedBundle bundle) { } } - private TransformExecutorService getSerialExecutorService(StepAndKey stepAndKey) { - if (!currentEvaluations.containsKey(stepAndKey)) { - currentEvaluations.putIfAbsent( - stepAndKey, TransformExecutorServices.serial(executorService, scheduledExecutors)); - } - return currentEvaluations.get(stepAndKey); - } - @Override public void awaitCompletion() throws Throwable { VisibleExecutorUpdate update; From 5dce8e219c8b1eb5055c6d0f72bfcb64db9ed767 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 11 Apr 2016 08:54:58 -0700 Subject: [PATCH 310/751] Fix multithreaded visibility issue with TransformExecutor Use an AtomicReference to ensure the thread the Executor is being run on will be visible to other threads. Add a checkState to ensure that the executor will not run more than once. Stop setting the active thread to null, as the Transform Executor should be discarded from any refernces and not hold the overall execution. --- .../runners/inprocess/TransformExecutor.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java index 7e1d84e38b..b9bdce11f7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -23,6 +25,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; @@ -66,7 +69,7 @@ public static TransformExecutor create( private final CompletionCallback onComplete; private final TransformExecutorService transformEvaluationState; - private Thread thread; + private final AtomicReference thread; private TransformExecutor( TransformEvaluatorFactory factory, @@ -86,11 +89,18 @@ private TransformExecutor( this.onComplete = completionCallback; this.transformEvaluationState = transformEvaluationState; + this.thread = new AtomicReference<>(); } @Override public InProcessTransformResult call() { - this.thread = Thread.currentThread(); + checkState( + thread.compareAndSet(null, Thread.currentThread()), + "Tried to execute %s for %s on thread %s, but is already executing on thread %s", + TransformExecutor.class.getSimpleName(), + transform.getFullName(), + Thread.currentThread(), + thread.get()); try { Collection> enforcements = new ArrayList<>(); for (ModelEnforcementFactory enforcementFactory : modelEnforcements) { @@ -108,7 +118,6 @@ public InProcessTransformResult call() { onComplete.handleThrowable(inputBundle, t); throw Throwables.propagate(t); } finally { - this.thread = null; transformEvaluationState.complete(this); } } @@ -159,6 +168,6 @@ private InProcessTransformResult finishBundle( */ @Nullable public Thread getThread() { - return this.thread; + return thread.get(); } } From 9940d579b27ed25227548a127b47b412df10ac80 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 8 Apr 2016 09:29:31 -0700 Subject: [PATCH 311/751] Add WindowIntoEvaluatorFactory This is a TransformEvaluator-based implementation of the Window#into primitve, as opposed to the DoFn ProcessContext internals-based implementation. --- .../PassthroughTransformEvaluator.java | 47 ++++ .../inprocess/TransformEvaluatorRegistry.java | 2 + .../inprocess/WindowEvaluatorFactory.java | 128 ++++++++++ .../inprocess/WindowEvaluatorFactoryTest.java | 219 ++++++++++++++++++ 4 files changed, 396 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java new file mode 100644 index 0000000000..0392dab19b --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.util.WindowedValue; + +class PassthroughTransformEvaluator implements TransformEvaluator { + public static PassthroughTransformEvaluator create( + AppliedPTransform transform, UncommittedBundle output) { + return new PassthroughTransformEvaluator<>(transform, output); + } + + private final AppliedPTransform transform; + private final UncommittedBundle output; + + private PassthroughTransformEvaluator( + AppliedPTransform transform, UncommittedBundle output) { + this.transform = transform; + this.output = output; + } + + @Override + public void processElement(WindowedValue element) throws Exception { + output.add(element); + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + return StepTransformResult.withoutHold(transform).addOutput(output).build(); + } + +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java index 0c8cb7e80a..9dd9c9115d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.common.collect.ImmutableMap; import java.util.Map; @@ -45,6 +46,7 @@ public static TransformEvaluatorRegistry defaultRegistry() { new GroupByKeyEvaluatorFactory()) .put(FlattenPCollectionList.class, new FlattenEvaluatorFactory()) .put(ViewEvaluatorFactory.WriteView.class, new ViewEvaluatorFactory()) + .put(Window.Bound.class, new WindowEvaluatorFactory()) .build(); return new TransformEvaluatorRegistry(primitives); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java new file mode 100644 index 0000000000..ecf02a1739 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import org.joda.time.Instant; + +import java.util.Collection; + +import javax.annotation.Nullable; + +/** + * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the + * {@link Bound Window.Bound} primitive {@link PTransform}. + */ +class WindowEvaluatorFactory implements TransformEvaluatorFactory { + + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + @Nullable CommittedBundle inputBundle, + InProcessEvaluationContext evaluationContext) + throws Exception { + return createTransformEvaluator( + (AppliedPTransform) application, inputBundle, evaluationContext); + } + + private TransformEvaluator createTransformEvaluator( + AppliedPTransform, PCollection, Window.Bound> transform, + CommittedBundle inputBundle, + InProcessEvaluationContext evaluationContext) { + WindowFn fn = transform.getTransform().getWindowFn(); + UncommittedBundle outputBundle = + evaluationContext.createBundle(inputBundle, transform.getOutput()); + if (fn == null) { + return PassthroughTransformEvaluator.create(transform, outputBundle); + } + return new WindowIntoEvaluator<>(fn, evaluationContext, outputBundle); + } + + private static class WindowIntoEvaluator implements TransformEvaluator { + private final WindowFn windowFn; + private final InProcessEvaluationContext context; + private final UncommittedBundle outputBundle; + + @SuppressWarnings("unchecked") + public WindowIntoEvaluator( + WindowFn windowFn, + InProcessEvaluationContext context, + UncommittedBundle outputBundle) { + // Safe contravariant cast + this.windowFn = (WindowFn) windowFn; + this.context = context; + this.outputBundle = outputBundle; + } + + @Override + public void processElement(WindowedValue element) throws Exception { + Collection windows = assignWindows(windowFn, element); + outputBundle.add( + WindowedValue.of( + element.getValue(), element.getTimestamp(), windows, PaneInfo.NO_FIRING)); + } + + private Collection assignWindows( + WindowFn windowFn, WindowedValue element) throws Exception { + WindowFn.AssignContext assignContext = + new InProcessAssignContext<>(windowFn, element); + Collection windows = windowFn.assignWindows(assignContext); + return windows; + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + return StepTransformResult.withoutHold(null).addOutput(outputBundle).build(); + } + } + + private static class InProcessAssignContext + extends WindowFn.AssignContext { + private final WindowedValue value; + + public InProcessAssignContext(WindowFn fn, WindowedValue value) { + fn.super(); + this.value = value; + } + + @Override + public InputT element() { + return value.getValue(); + } + + @Override + public Instant timestamp() { + return value.getTimestamp(); + } + + @Override + public Collection windows() { + return value.getWindows(); + } + + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java new file mode 100644 index 0000000000..e928c28559 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java @@ -0,0 +1,219 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + +import org.hamcrest.Matchers; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** + * Tests for {@link WindowEvaluatorFactory}. + */ +@RunWith(JUnit4.class) +public class WindowEvaluatorFactoryTest { + private static final Instant EPOCH = new Instant(0); + + private PCollection input; + private WindowEvaluatorFactory factory; + + @Mock private InProcessEvaluationContext evaluationContext; + + private BundleFactory bundleFactory; + + private WindowedValue first = + WindowedValue.timestampedValueInGlobalWindow(3L, new Instant(2L)); + private WindowedValue second = + WindowedValue.timestampedValueInGlobalWindow( + Long.valueOf(1L), EPOCH.plus(Duration.standardDays(3))); + private WindowedValue third = + WindowedValue.of( + Long.valueOf(2L), + new Instant(-10L), + new IntervalWindow(new Instant(-100), EPOCH), + PaneInfo.NO_FIRING); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + TestPipeline p = TestPipeline.create(); + input = p.apply(Create.of(1L, 2L, 3L)); + + bundleFactory = InProcessBundleFactory.create(); + factory = new WindowEvaluatorFactory(); + } + + @Test + public void nullWindowFunSucceeds() throws Exception { + Bound transform = + Window.triggering( + AfterWatermark.pastEndOfWindow().withEarlyFirings(AfterPane.elementCountAtLeast(1))) + .accumulatingFiredPanes(); + PCollection triggering = input.apply(transform); + + CommittedBundle inputBundle = createInputBundle(); + + UncommittedBundle outputBundle = createOutputBundle(triggering, inputBundle); + + InProcessTransformResult result = runEvaluator(triggering, inputBundle, transform); + + assertThat( + Iterables.getOnlyElement(result.getOutputBundles()), + Matchers.>equalTo(outputBundle)); + CommittedBundle committed = outputBundle.commit(Instant.now()); + assertThat(committed.getElements(), containsInAnyOrder(third, first, second)); + } + + @Test + public void singleWindowFnSucceeds() throws Exception { + Duration windowDuration = Duration.standardDays(7); + Bound transform = Window.into(FixedWindows.of(windowDuration)); + PCollection windowed = input.apply(transform); + + CommittedBundle inputBundle = createInputBundle(); + + UncommittedBundle outputBundle = createOutputBundle(windowed, inputBundle); + + BoundedWindow firstSecondWindow = new IntervalWindow(EPOCH, EPOCH.plus(windowDuration)); + BoundedWindow thirdWindow = new IntervalWindow(EPOCH.minus(windowDuration), EPOCH); + + InProcessTransformResult result = runEvaluator(windowed, inputBundle, transform); + + assertThat( + Iterables.getOnlyElement(result.getOutputBundles()), + Matchers.>equalTo(outputBundle)); + CommittedBundle committed = outputBundle.commit(Instant.now()); + + WindowedValue expectedNewFirst = + WindowedValue.of(3L, new Instant(2L), firstSecondWindow, PaneInfo.NO_FIRING); + WindowedValue expectedNewSecond = + WindowedValue.of( + 1L, EPOCH.plus(Duration.standardDays(3)), firstSecondWindow, PaneInfo.NO_FIRING); + WindowedValue expectedNewThird = + WindowedValue.of(2L, new Instant(-10L), thirdWindow, PaneInfo.NO_FIRING); + assertThat( + committed.getElements(), + containsInAnyOrder(expectedNewFirst, expectedNewSecond, expectedNewThird)); + } + + @Test + public void multipleWindowsWindowFnSucceeds() throws Exception { + Duration windowDuration = Duration.standardDays(6); + Duration slidingBy = Duration.standardDays(3); + Bound transform = Window.into(SlidingWindows.of(windowDuration).every(slidingBy)); + PCollection windowed = input.apply(transform); + + CommittedBundle inputBundle = createInputBundle(); + UncommittedBundle outputBundle = createOutputBundle(windowed, inputBundle); + + InProcessTransformResult result = runEvaluator(windowed, inputBundle, transform); + + assertThat( + Iterables.getOnlyElement(result.getOutputBundles()), + Matchers.>equalTo(outputBundle)); + CommittedBundle committed = outputBundle.commit(Instant.now()); + + BoundedWindow w1 = new IntervalWindow(EPOCH, EPOCH.plus(windowDuration)); + BoundedWindow w2 = + new IntervalWindow(EPOCH.plus(slidingBy), EPOCH.plus(slidingBy).plus(windowDuration)); + BoundedWindow wMinus1 = new IntervalWindow(EPOCH.minus(windowDuration), EPOCH); + BoundedWindow wMinusSlide = + new IntervalWindow(EPOCH.minus(windowDuration).plus(slidingBy), EPOCH.plus(slidingBy)); + + WindowedValue expectedFirst = + WindowedValue.of( + first.getValue(), + first.getTimestamp(), + ImmutableSet.of(w1, wMinusSlide), + PaneInfo.NO_FIRING); + WindowedValue expectedSecond = + WindowedValue.of( + second.getValue(), second.getTimestamp(), ImmutableSet.of(w1, w2), PaneInfo.NO_FIRING); + WindowedValue expectedThird = + WindowedValue.of( + third.getValue(), + third.getTimestamp(), + ImmutableSet.of(wMinus1, wMinusSlide), + PaneInfo.NO_FIRING); + + assertThat( + committed.getElements(), containsInAnyOrder(expectedFirst, expectedSecond, expectedThird)); + } + + private CommittedBundle createInputBundle() { + CommittedBundle inputBundle = + bundleFactory + .createRootBundle(input) + .add(first) + .add(second) + .add(third) + .commit(Instant.now()); + return inputBundle; + } + + private UncommittedBundle createOutputBundle( + PCollection output, CommittedBundle inputBundle) { + UncommittedBundle outputBundle = bundleFactory.createBundle(inputBundle, output); + when(evaluationContext.createBundle(inputBundle, output)).thenReturn(outputBundle); + return outputBundle; + } + + private InProcessTransformResult runEvaluator( + PCollection windowed, + CommittedBundle inputBundle, + Window.Bound windowTransform /* Required while Window.Bound is a composite */) + throws Exception { + TransformEvaluator evaluator = + factory.forApplication( + AppliedPTransform.of("Window", input, windowed, windowTransform), + inputBundle, + evaluationContext); + + evaluator.processElement(first); + evaluator.processElement(second); + evaluator.processElement(third); + InProcessTransformResult result = evaluator.finishBundle(); + return result; + } +} From 90d1c19743d0e9487edc5609248b614a8f63517b Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 29 Mar 2016 10:03:25 -0700 Subject: [PATCH 312/751] Add PTransformOverrideFactory This constructs an appropriate custom PTransform override for the runner it is meant to be used in, which is applied in place of the original PTransform. --- .../inprocess/GroupByKeyEvaluatorFactory.java | 21 +++++++++- .../runners/inprocess/InProcessCreate.java | 18 ++++++++ .../inprocess/InProcessPipelineRunner.java | 41 ++++++------------- .../inprocess/PTransformOverrideFactory.java | 31 ++++++++++++++ .../inprocess/ViewEvaluatorFactory.java | 32 +++++++++++++-- 5 files changed, 110 insertions(+), 33 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java index b1d5d35869..3e133010f3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java @@ -40,6 +40,8 @@ import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; @@ -177,11 +179,28 @@ public int hashCode() { } } + /** + * A {@link PTransformOverrideFactory} for {@link GroupByKey} PTransforms. + */ + public static final class InProcessGroupByKeyOverrideFactory + implements PTransformOverrideFactory { + @Override + public PTransform override( + PTransform transform) { + if (transform instanceof GroupByKey) { + @SuppressWarnings({"rawtypes", "unchecked"}) + PTransform override = new InProcessGroupByKey((GroupByKey) transform); + return override; + } + return transform; + } + } + /** * An in-memory implementation of the {@link GroupByKey} primitive as a composite * {@link PTransform}. */ - public static final class InProcessGroupByKey + private static final class InProcessGroupByKey extends ForwardingPTransform>, PCollection>>> { private final GroupByKey original; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java index 614989fc22..b28db6bbd7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java @@ -29,6 +29,7 @@ import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Throwables; @@ -50,6 +51,23 @@ class InProcessCreate extends ForwardingPTransform> { private final Create.Values original; + /** + * A {@link PTransformOverrideFactory} for {@link InProcessCreate}. + */ + public static class InProcessCreateOverrideFactory implements PTransformOverrideFactory { + @Override + public PTransform override( + PTransform transform) { + if (transform instanceof Create.Values) { + @SuppressWarnings("unchecked") + PTransform override = + (PTransform) from((Create.Values) transform); + return override; + } + return transform; + } + } + public static InProcessCreate from(Create.Values original) { return new InProcessCreate<>(original); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 9b6db8f730..64b18590da 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -24,15 +24,16 @@ import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; import com.google.cloud.dataflow.sdk.runners.AggregatorValues; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKey; import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; +import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOverrideFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessCreate.InProcessCreateOverrideFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.ViewEvaluatorFactory.InProcessViewOverrideFactory; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; import com.google.cloud.dataflow.sdk.util.MapAggregatorValues; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.UserCodeException; @@ -73,14 +74,12 @@ public class InProcessPipelineRunner * type of transform it is overriding. */ @SuppressWarnings("rawtypes") - private static Map, Class> + private static Map, PTransformOverrideFactory> defaultTransformOverrides = - ImmutableMap., Class>builder() - .put(Create.Values.class, InProcessCreate.class) - .put(GroupByKey.class, InProcessGroupByKey.class) - .put( - CreatePCollectionView.class, - ViewEvaluatorFactory.InProcessCreatePCollectionView.class) + ImmutableMap., PTransformOverrideFactory>builder() + .put(Create.Values.class, new InProcessCreateOverrideFactory()) + .put(GroupByKey.class, new InProcessGroupByKeyOverrideFactory()) + .put(CreatePCollectionView.class, new InProcessViewOverrideFactory()) .build(); /** @@ -189,28 +188,14 @@ public InProcessPipelineOptions getPipelineOptions() { @Override public OutputT apply( PTransform transform, InputT input) { - Class overrideClass = defaultTransformOverrides.get(transform.getClass()); - if (overrideClass != null) { - // It is the responsibility of whoever constructs overrides to ensure this is type safe. - @SuppressWarnings("unchecked") - Class> transformClass = - (Class>) transform.getClass(); + PTransformOverrideFactory overrideFactory = defaultTransformOverrides.get(transform.getClass()); + if (overrideFactory != null) { + PTransform customTransform = overrideFactory.override(transform); - @SuppressWarnings("unchecked") - Class> customTransformClass = - (Class>) overrideClass; - - PTransform customTransform = - InstanceBuilder.ofType(customTransformClass) - .withArg(transformClass, transform) - .build(); - - // This overrides the contents of the apply method without changing the TransformTreeNode that - // is generated by the PCollection application. return super.apply(customTransform, input); - } else { - return super.apply(transform, input); } + // If there is no override, or we should not apply the override, apply the original transform + return super.apply(transform, input); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java new file mode 100644 index 0000000000..f32552614a --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; + +interface PTransformOverrideFactory { + /** + * Create a {@link PTransform} override for the provided {@link PTransform} if applicable. + * Otherwise, return the input {@link PTransform}. + * + *

        The returned PTransform must be semantically equivalent to the input {@link PTransform}. + */ + PTransform override( + PTransform transform); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java index 314d81f6aa..abdd61185b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java @@ -27,6 +27,8 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; import java.util.ArrayList; import java.util.List; @@ -48,8 +50,10 @@ public TransformEvaluator forApplication( AppliedPTransform application, InProcessPipelineRunner.CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - return createEvaluator( - (AppliedPTransform) application, evaluationContext); + @SuppressWarnings({"cast", "unchecked", "rawtypes"}) + TransformEvaluator evaluator = createEvaluator( + (AppliedPTransform) application, evaluationContext); + return evaluator; } private TransformEvaluator> createEvaluator( @@ -77,11 +81,26 @@ public InProcessTransformResult finishBundle() { }; } + public static class InProcessViewOverrideFactory implements PTransformOverrideFactory { + @Override + public + PTransform override(PTransform transform) { + if (transform instanceof CreatePCollectionView) { + + } + @SuppressWarnings({"rawtypes", "unchecked"}) + PTransform createView = + (PTransform) + new InProcessCreatePCollectionView<>((CreatePCollectionView) transform); + return createView; + } + } + /** * An in-process override for {@link CreatePCollectionView}. */ - public static class InProcessCreatePCollectionView - extends PTransform, PCollectionView> { + private static class InProcessCreatePCollectionView + extends ForwardingPTransform, PCollectionView> { private final CreatePCollectionView og; private InProcessCreatePCollectionView(CreatePCollectionView og) { @@ -96,6 +115,11 @@ public PCollectionView apply(PCollection input) { .apply(Values.>create()) .apply(new WriteView(og)); } + + @Override + protected PTransform, PCollectionView> delegate() { + return og; + } } /** From 7dced85eb0aba73d05f291c499179c2fcef1dc4a Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 4 Apr 2016 16:48:15 -0700 Subject: [PATCH 313/751] Apply ModelEnforcement in the InProcessPipelineRunner This ensures that user code does not violate the model. Add a flag to control application of immutability enforcement. This flag is enabled by default. --- .../inprocess/InProcessPipelineOptions.java | 9 +++++++ .../inprocess/InProcessPipelineRunner.java | 25 ++++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java index 5ee0e88b5b..9c10510bf9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java @@ -87,4 +87,13 @@ public interface InProcessPipelineOptions extends PipelineOptions, ApplicationNa boolean isBlockOnRun(); void setBlockOnRun(boolean b); + + @Default.Boolean(true) + @Description( + "Controls whether the runner should ensure that all of the elements of every " + + "PCollection are not mutated. PTransforms are not permitted to mutate input elements " + + "at any point, or output elements after they are output.") + boolean isTestImmutability(); + + void setTestImmutability(boolean test); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 9b6db8f730..c0cb1bc7c9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -31,6 +31,7 @@ import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; import com.google.cloud.dataflow.sdk.util.InstanceBuilder; import com.google.cloud.dataflow.sdk.util.MapAggregatorValues; @@ -46,13 +47,13 @@ import com.google.cloud.dataflow.sdk.values.POutput; import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.joda.time.Instant; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -267,11 +268,29 @@ public InProcessPipelineResult run(Pipeline pipeline) { private Map, Collection> defaultModelEnforcements(InProcessPipelineOptions options) { - return Collections.emptyMap(); + ImmutableMap.Builder, Collection> + enforcements = ImmutableMap.builder(); + Collection parDoEnforcements = createParDoEnforcements(options); + enforcements.put(ParDo.Bound.class, parDoEnforcements); + enforcements.put(ParDo.BoundMulti.class, parDoEnforcements); + return enforcements.build(); + } + + private Collection createParDoEnforcements( + InProcessPipelineOptions options) { + ImmutableList.Builder enforcements = ImmutableList.builder(); + if (options.isTestImmutability()) { + enforcements.add(ImmutabilityEnforcementFactory.create()); + } + return enforcements.build(); } private BundleFactory createBundleFactory(InProcessPipelineOptions pipelineOptions) { - return InProcessBundleFactory.create(); + BundleFactory bundleFactory = InProcessBundleFactory.create(); + if (pipelineOptions.isTestImmutability()) { + bundleFactory = ImmutabilityCheckingBundleFactory.create(bundleFactory); + } + return bundleFactory; } /** From 55ba18bae28fc6304713c76bf95ced798a94643c Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 5 Apr 2016 13:19:24 -0700 Subject: [PATCH 314/751] Improve ImmutabilityEnforcement Check per-element, to catch failures within a call to ProcessElement more quickly. Move wrapping of exceptions over the course of calls to ProcessElement to ParDoInProcessEvaluator. --- .../ImmutabilityEnforcementFactory.java | 36 +++++++++++-------- .../inprocess/ParDoInProcessEvaluator.java | 13 +++++-- .../ImmutabilityEnforcementFactoryTest.java | 9 ++--- .../inprocess/TransformExecutorTest.java | 6 ++-- 4 files changed, 38 insertions(+), 26 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java index dfc56a9d3c..0f2607ff45 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java @@ -68,26 +68,34 @@ public void beforeElement(WindowedValue element) { } } + @Override + public void afterElement(WindowedValue element) { + verifyUnmodified(mutationElements.get(element)); + } + @Override public void afterFinish( CommittedBundle input, InProcessTransformResult result, Iterable> outputs) { for (MutationDetector detector : mutationElements.values()) { - try { - detector.verifyUnmodified(); - } catch (IllegalMutationException e) { - throw UserCodeException.wrap( - new IllegalMutationException( - String.format( - "PTransform %s illegaly mutated value %s of class %s." - + " Input values must not be mutated in any way.", - transform.getFullName(), - e.getSavedValue(), - e.getSavedValue().getClass()), - e.getSavedValue(), - e.getNewValue())); - } + verifyUnmodified(detector); + } + } + + private void verifyUnmodified(MutationDetector detector) { + try { + detector.verifyUnmodified(); + } catch (IllegalMutationException e) { + throw new IllegalMutationException( + String.format( + "PTransform %s illegaly mutated value %s of class %s." + + " Input values must not be mutated in any way.", + transform.getFullName(), + e.getSavedValue(), + e.getSavedValue().getClass()), + e.getSavedValue(), + e.getNewValue()); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index 2a21e8cbf5..17546f1953 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.util.DoFnRunner; import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; @@ -54,12 +55,20 @@ public ParDoInProcessEvaluator( @Override public void processElement(WindowedValue element) { - fnRunner.processElement(element); + try { + fnRunner.processElement(element); + } catch (Exception e) { + throw UserCodeException.wrap(e); + } } @Override public InProcessTransformResult finishBundle() { - fnRunner.finishBundle(); + try { + fnRunner.finishBundle(); + } catch (Exception e) { + throw UserCodeException.wrap(e); + } StepTransformResult.Builder resultBuilder; CopyOnAccessInMemoryStateInternals state = stepContext.commitState(); if (state != null) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java index 87e12ce55f..0b5de689ec 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java @@ -15,8 +15,6 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import static org.hamcrest.Matchers.isA; - import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -25,7 +23,6 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -92,8 +89,7 @@ public void mutatedDuringProcessElementThrows() { ModelEnforcement enforcement = factory.forBundle(elements, consumer); enforcement.beforeElement(element); element.getValue()[0] = 'f'; - thrown.equals(UserCodeException.class); - thrown.expectCause(isA(IllegalMutationException.class)); + thrown.expect(IllegalMutationException.class); thrown.expectMessage(consumer.getFullName()); thrown.expectMessage("illegaly mutated"); thrown.expectMessage("Input values must not be mutated"); @@ -116,8 +112,7 @@ public void mutatedAfterProcessElementFails() { enforcement.afterElement(element); element.getValue()[0] = 'f'; - thrown.equals(UserCodeException.class); - thrown.expectCause(isA(IllegalMutationException.class)); + thrown.expect(IllegalMutationException.class); thrown.expectMessage(consumer.getFullName()); thrown.expectMessage("illegaly mutated"); thrown.expectMessage("Input values must not be mutated"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index b14b34bb24..bbf7c51757 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -32,7 +32,7 @@ import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.util.UserCodeException; +import com.google.cloud.dataflow.sdk.util.IllegalMutationException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -411,7 +411,7 @@ public InProcessTransformResult finishBundle() throws Exception { fooBytes.getValue()[0] = 'b'; evaluatorLatch.countDown(); - thrown.expectCause(isA(UserCodeException.class)); + thrown.expectCause(isA(IllegalMutationException.class)); task.get(); } @@ -470,7 +470,7 @@ public InProcessTransformResult finishBundle() throws Exception { fooBytes.getValue()[0] = 'b'; evaluatorLatch.countDown(); - thrown.expectCause(isA(UserCodeException.class)); + thrown.expectCause(isA(IllegalMutationException.class)); task.get(); } From 2852f0076b0697139ca04567e384fa415ba909df Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 8 Apr 2016 10:03:10 -0700 Subject: [PATCH 315/751] Add InProcessRegistrar Adds @AutoService for the InProcessPipelineRunner and InProcessPipelineOptions --- .../runners/inprocess/InProcessRegistrar.java | 52 ++++++++++++++ .../InProcessPipelineRegistrarTest.java | 71 +++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java new file mode 100644 index 0000000000..52f238f9d0 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.auto.service.AutoService; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; +import com.google.common.collect.ImmutableList; + +/** + * Contains the {@link PipelineRunnerRegistrar} and {@link PipelineOptionsRegistrar} for the + * {@link InProcessPipelineRunner}. + */ +public class InProcessRegistrar { + private InProcessRegistrar() {} + /** + * Registers the {@link InProcessPipelineRunner}. + */ + @AutoService(PipelineRunnerRegistrar.class) + public static class InProcessRunner implements PipelineRunnerRegistrar { + @Override + public Iterable>> getPipelineRunners() { + return ImmutableList.>>of(InProcessPipelineRunner.class); + } + } + + /** + * Registers the {@link InProcessPipelineOptions}. + */ + @AutoService(PipelineOptionsRegistrar.class) + public static class InProcessOptions implements PipelineOptionsRegistrar { + @Override + public Iterable> getPipelineOptions() { + return ImmutableList.>of(InProcessPipelineOptions.class); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java new file mode 100644 index 0000000000..18898f0403 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; +import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessRegistrar.InProcessRunner; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.ServiceLoader; + +/** Tests for {@link InProcessRunner}. */ +@RunWith(JUnit4.class) +public class InProcessPipelineRegistrarTest { + @Test + public void testCorrectOptionsAreReturned() { + assertEquals( + ImmutableList.of(InProcessPipelineOptions.class), + new InProcessRegistrar.InProcessOptions().getPipelineOptions()); + } + + @Test + public void testCorrectRunnersAreReturned() { + assertEquals( + ImmutableList.of(InProcessPipelineRunner.class), + new InProcessRegistrar.InProcessRunner().getPipelineRunners()); + } + + @Test + public void testServiceLoaderForOptions() { + for (PipelineOptionsRegistrar registrar : + Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class).iterator())) { + if (registrar instanceof InProcessRegistrar.InProcessOptions) { + return; + } + } + fail("Expected to find " + InProcessRegistrar.InProcessOptions.class); + } + + @Test + public void testServiceLoaderForRunner() { + for (PipelineRunnerRegistrar registrar : + Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class).iterator())) { + if (registrar instanceof InProcessRegistrar.InProcessRunner) { + return; + } + } + fail("Expected to find " + InProcessRegistrar.InProcessRunner.class); + } +} From fcbfa83a45189bef43831f2a089882f9b9896849 Mon Sep 17 00:00:00 2001 From: Pei He Date: Mon, 11 Apr 2016 12:35:36 -0700 Subject: [PATCH 316/751] Implement BigQueryIO.Write as a custom sink. This is back ported from: https://github.com/apache/incubator-beam/pull/48 --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 369 +++++++++++++----- .../dataflow/sdk/util/BigQueryServices.java | 59 +++ .../sdk/util/BigQueryServicesImpl.java | 194 +++++++++ .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 192 ++++++++- .../sdk/util/BigQueryServicesImplTest.java | 260 ++++++++++++ 5 files changed, 969 insertions(+), 105 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index ab7df6f081..f4094e5274 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -16,14 +16,19 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.api.client.json.JsonFactory; import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.QueryRequest; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.Coder.Context; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StandardCoder; @@ -31,10 +36,12 @@ import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQuerySink; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.options.GcpOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Aggregator; @@ -44,22 +51,29 @@ import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.BigQueryServices; +import com.google.cloud.dataflow.sdk.util.BigQueryServices.LoadService; +import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl; import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; +import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.Reshuffle; import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.hadoop.util.ApiErrorExtractor; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; +import com.google.common.base.Strings; +import com.google.common.collect.Lists; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -70,6 +84,9 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -724,12 +741,12 @@ public static Bound withoutValidation() { * {@link PCollection} of {@link TableRow TableRows} to a BigQuery table. */ public static class Bound extends PTransform, PDone> { - final TableReference table; + @Nullable final String jsonTableRef; - final SerializableFunction tableRefFunction; + @Nullable final SerializableFunction tableRefFunction; // Table schema. The schema is required only if the table does not exist. - final TableSchema schema; + @Nullable final String jsonSchema; // Options for creating the table. Valid values are CREATE_IF_NEEDED and // CREATE_NEVER. @@ -742,6 +759,9 @@ public static class Bound extends PTransform, PDone> { // An option to indicate if table validation is desired. Default is true. final boolean validate; + // A fake or mock BigQueryServices for tests. + @Nullable private BigQueryServices testBigQueryServices; + private static class TranslateTableSpecFunction implements SerializableFunction { private SerializableFunction tableSpecFunction; @@ -764,20 +784,22 @@ public TableReference apply(BoundedWindow value) { @Deprecated public Bound() { this(null, null, null, null, CreateDisposition.CREATE_IF_NEEDED, - WriteDisposition.WRITE_EMPTY, true); + WriteDisposition.WRITE_EMPTY, true, null); } - private Bound(String name, TableReference ref, - SerializableFunction tableRefFunction, TableSchema schema, - CreateDisposition createDisposition, WriteDisposition writeDisposition, - boolean validate) { + private Bound(String name, @Nullable String jsonTableRef, + @Nullable SerializableFunction tableRefFunction, + @Nullable String jsonSchema, + CreateDisposition createDisposition, WriteDisposition writeDisposition, boolean validate, + @Nullable BigQueryServices testBigQueryServices) { super(name); - this.table = ref; + this.jsonTableRef = jsonTableRef; this.tableRefFunction = tableRefFunction; - this.schema = schema; - this.createDisposition = createDisposition; - this.writeDisposition = writeDisposition; + this.jsonSchema = jsonSchema; + this.createDisposition = checkNotNull(createDisposition, "createDisposition"); + this.writeDisposition = checkNotNull(writeDisposition, "writeDisposition"); this.validate = validate; + this.testBigQueryServices = testBigQueryServices; } /** @@ -786,8 +808,8 @@ private Bound(String name, TableReference ref, *

        Does not modify this object. */ public Bound named(String name) { - return new Bound(name, table, tableRefFunction, schema, createDisposition, - writeDisposition, validate); + return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, + writeDisposition, validate, testBigQueryServices); } /** @@ -806,8 +828,8 @@ public Bound to(String tableSpec) { *

        Does not modify this object. */ public Bound to(TableReference table) { - return new Bound(name, table, tableRefFunction, schema, createDisposition, - writeDisposition, validate); + return new Bound(name, toJsonString(table), tableRefFunction, jsonSchema, createDisposition, + writeDisposition, validate, testBigQueryServices); } /** @@ -835,8 +857,8 @@ public Bound to( */ public Bound toTableReference( SerializableFunction tableRefFunction) { - return new Bound(name, table, tableRefFunction, schema, createDisposition, - writeDisposition, validate); + return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, + writeDisposition, validate, testBigQueryServices); } /** @@ -846,8 +868,8 @@ public Bound toTableReference( *

        Does not modify this object. */ public Bound withSchema(TableSchema schema) { - return new Bound(name, table, tableRefFunction, schema, createDisposition, - writeDisposition, validate); + return new Bound(name, jsonTableRef, tableRefFunction, toJsonString(schema), + createDisposition, writeDisposition, validate, testBigQueryServices); } /** @@ -856,8 +878,8 @@ public Bound withSchema(TableSchema schema) { *

        Does not modify this object. */ public Bound withCreateDisposition(CreateDisposition createDisposition) { - return new Bound(name, table, tableRefFunction, schema, createDisposition, - writeDisposition, validate); + return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, + writeDisposition, validate, testBigQueryServices); } /** @@ -866,8 +888,8 @@ public Bound withCreateDisposition(CreateDisposition createDisposition) { *

        Does not modify this object. */ public Bound withWriteDisposition(WriteDisposition writeDisposition) { - return new Bound(name, table, tableRefFunction, schema, createDisposition, - writeDisposition, validate); + return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, + writeDisposition, validate, testBigQueryServices); } /** @@ -876,8 +898,14 @@ public Bound withWriteDisposition(WriteDisposition writeDisposition) { *

        Does not modify this object. */ public Bound withoutValidation() { - return new Bound(name, table, tableRefFunction, schema, createDisposition, - writeDisposition, false); + return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, + writeDisposition, false, testBigQueryServices); + } + + @VisibleForTesting + Bound withTestServices(BigQueryServices testServices) { + return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, + writeDisposition, validate, testServices); } private static void verifyTableEmpty( @@ -906,6 +934,7 @@ private static void verifyTableEmpty( public PDone apply(PCollection input) { BigQueryOptions options = input.getPipeline().getOptions().as(BigQueryOptions.class); + TableReference table = getTable(); if (table == null && tableRefFunction == null) { throw new IllegalStateException( "must set the table reference of a BigQueryIO.Write transform"); @@ -916,7 +945,7 @@ public PDone apply(PCollection input) { + "transform"); } - if (createDisposition == CreateDisposition.CREATE_IF_NEEDED && schema == null) { + if (createDisposition == CreateDisposition.CREATE_IF_NEEDED && jsonSchema == null) { throw new IllegalArgumentException("CreateDisposition is CREATE_IF_NEEDED, " + "however no schema was provided."); } @@ -935,7 +964,7 @@ public PDone apply(PCollection input) { // of the pipeline. For these cases the withoutValidation method can be used to disable // the check. // Unfortunately we can't validate anything early in case tableRefFunction is specified. - if (table != null && validate) { + if (jsonTableRef != null && validate) { verifyDatasetPresence(options, table); if (getCreateDisposition() == BigQueryIO.Write.CreateDisposition.CREATE_NEVER) { verifyTablePresence(options, table); @@ -958,10 +987,34 @@ public PDone apply(PCollection input) { + "supported for unbounded PCollections or when using tablespec functions."); } - return input.apply(new StreamWithDeDup(table, tableRefFunction, schema)); + return input.apply(new StreamWithDeDup(table, tableRefFunction, getSchema())); } - return PDone.in(input.getPipeline()); + String tempLocation = options.getTempLocation(); + checkArgument(!Strings.isNullOrEmpty(tempLocation), + "BigQueryIO.Write needs a GCS temp location to store temp files."); + if (testBigQueryServices == null) { + try { + GcsPath.fromUri(tempLocation); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException(String.format( + "BigQuery temp location expected a valid 'gs://' path, but was given '%s'", + tempLocation), e); + } + } + String jobIdToken = UUID.randomUUID().toString(); + String tempFilePrefix = tempLocation + "/BigQuerySinkTemp/" + jobIdToken; + BigQueryServices bqServices = getBigQueryServices(); + return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( + new BigQuerySink( + jobIdToken, + toJsonString(table), + jsonSchema, + getWriteDisposition(), + getCreateDisposition(), + tempFilePrefix, + input.getCoder(), + bqServices))); } @Override @@ -969,17 +1022,6 @@ protected Coder getDefaultOutputCoder() { return VoidCoder.of(); } - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateWriteHelper(transform, context); - } - }); - } - /** Returns the create disposition. */ public CreateDisposition getCreateDisposition() { return createDisposition; @@ -992,24 +1034,191 @@ public WriteDisposition getWriteDisposition() { /** Returns the table schema. */ public TableSchema getSchema() { - return schema; + return fromJsonString(jsonSchema, TableSchema.class); } /** Returns the table reference, or {@code null} if a . */ public TableReference getTable() { - return table; + return fromJsonString(jsonTableRef, TableReference.class); } /** Returns {@code true} if table validation is enabled. */ public boolean getValidate() { return validate; } + + private BigQueryServices getBigQueryServices() { + if (testBigQueryServices != null) { + return testBigQueryServices; + } else { + return new BigQueryServicesImpl(); + } + } } /** Disallow construction of utility class. */ private Write() {} } + /** + * {@link BigQuerySink} is implemented as a {@link FileBasedSink}. + * + *

        It uses BigQuery load job to import files into BigQuery. + */ + static class BigQuerySink extends FileBasedSink { + private final String jobIdToken; + @Nullable private final String jsonTable; + @Nullable private final String jsonSchema; + private final WriteDisposition writeDisposition; + private final CreateDisposition createDisposition; + private final Coder coder; + private final BigQueryServices bqServices; + + public BigQuerySink( + String jobIdToken, + @Nullable String jsonTable, + @Nullable String jsonSchema, + WriteDisposition writeDisposition, + CreateDisposition createDisposition, + String tempFile, + Coder coder, + BigQueryServices bqServices) { + super(tempFile, ".json"); + this.jobIdToken = checkNotNull(jobIdToken, "jobIdToken"); + this.jsonTable = jsonTable; + this.jsonSchema = jsonSchema; + this.writeDisposition = checkNotNull(writeDisposition, "writeDisposition"); + this.createDisposition = checkNotNull(createDisposition, "createDisposition"); + this.coder = checkNotNull(coder, "coder"); + this.bqServices = checkNotNull(bqServices, "bqServices"); + } + + @Override + public FileBasedSink.FileBasedWriteOperation createWriteOperation( + PipelineOptions options) { + return new BigQueryWriteOperation(this); + } + + private static class BigQueryWriteOperation extends FileBasedWriteOperation { + // The maximum number of retry load jobs. + private static final int MAX_RETRY_LOAD_JOBS = 3; + + private final BigQuerySink bigQuerySink; + + private BigQueryWriteOperation(BigQuerySink sink) { + super(checkNotNull(sink, "sink")); + this.bigQuerySink = sink; + } + + @Override + public FileBasedWriter createWriter(PipelineOptions options) throws Exception { + return new TableRowWriter(this, bigQuerySink.coder); + } + + @Override + public void finalize(Iterable writerResults, PipelineOptions options) + throws IOException, InterruptedException { + try { + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + List tempFiles = Lists.newArrayList(); + for (FileResult result : writerResults) { + tempFiles.add(result.getFilename()); + } + if (!tempFiles.isEmpty()) { + load( + bigQuerySink.bqServices.getLoadService(bqOptions), + bigQuerySink.jobIdToken, + fromJsonString(bigQuerySink.jsonTable, TableReference.class), + tempFiles, + fromJsonString(bigQuerySink.jsonSchema, TableSchema.class), + bigQuerySink.writeDisposition, + bigQuerySink.createDisposition); + } + } finally { + removeTemporaryFiles(options); + } + } + + /** + * Import files into BigQuery with load jobs. + * + *

        Returns if files are successfully loaded into BigQuery. + * Throws a RuntimeException if: + * 1. The status of one load job is UNKNOWN. This is to avoid duplicating data. + * 2. It exceeds {@code MAX_RETRY_LOAD_JOBS}. + * + *

        If a load job failed, it will try another load job with a different job id. + */ + private void load( + LoadService loadService, + String jobIdPrefix, + TableReference ref, + List gcsUris, + @Nullable TableSchema schema, + WriteDisposition writeDisposition, + CreateDisposition createDisposition) throws InterruptedException, IOException { + JobConfigurationLoad loadConfig = new JobConfigurationLoad(); + loadConfig.setSourceUris(gcsUris); + loadConfig.setDestinationTable(ref); + loadConfig.setSchema(schema); + loadConfig.setWriteDisposition(writeDisposition.name()); + loadConfig.setCreateDisposition(createDisposition.name()); + loadConfig.setSourceFormat("NEWLINE_DELIMITED_JSON"); + + boolean retrying = false; + String projectId = ref.getProjectId(); + for (int i = 0; i < MAX_RETRY_LOAD_JOBS; ++i) { + String jobId = jobIdPrefix + "-" + i; + if (retrying) { + LOG.info("Previous load jobs failed, retrying."); + } + LOG.info("Starting BigQuery load job: {}", jobId); + loadService.startLoadJob(jobId, loadConfig); + BigQueryServices.Status jobStatus = loadService.pollJobStatus(projectId, jobId); + switch (jobStatus) { + case SUCCEEDED: + return; + case UNKNOWN: + throw new RuntimeException("Failed to poll the load job status."); + case FAILED: + LOG.info("BigQuery load job failed: {}", jobId); + retrying = true; + continue; + default: + throw new IllegalStateException("Unexpected job status: " + jobStatus); + } + } + throw new RuntimeException( + "Failed to create the load job, reached max retries: " + MAX_RETRY_LOAD_JOBS); + } + } + + private static class TableRowWriter extends FileBasedWriter { + private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); + private final Coder coder; + private OutputStream out; + + public TableRowWriter( + FileBasedWriteOperation writeOperation, Coder coder) { + super(writeOperation); + this.mimeType = MimeTypes.TEXT; + this.coder = coder; + } + + @Override + protected void prepareWrite(WritableByteChannel channel) throws Exception { + out = Channels.newOutputStream(channel); + } + + @Override + public void write(TableRow value) throws Exception { + // Use Context.OUTER to encode and NEWLINE as the delimeter. + coder.encode(value, out, Context.OUTER); + out.write(NEWLINE); + } + } + } + private static void verifyDatasetPresence(BigQueryOptions options, TableReference table) { try { Bigquery client = Transport.newBigQueryClient(options).build(); @@ -1400,6 +1609,32 @@ public PDone apply(PCollection input) { } } + private static String toJsonString(Object item) { + if (item == null) { + return null; + } + try { + return JSON_FACTORY.toString(item); + } catch (IOException e) { + throw new RuntimeException( + String.format("Cannot serialize %s to a JSON string.", item.getClass().getSimpleName()), + e); + } + } + + private static T fromJsonString(String json, Class clazz) { + if (json == null) { + return null; + } + try { + return JSON_FACTORY.fromString(json, clazz); + } catch (IOException e) { + throw new RuntimeException( + String.format("Cannot deserialize %s from a JSON string: %s.", clazz, json), + e); + } + } + ///////////////////////////////////////////////////////////////////////////// /** Disallow construction of utility class. */ @@ -1450,50 +1685,4 @@ private static List getOrCreateMapListValue(Map> map, K key } return value; } - - /** - * Direct mode write evaluator. - * - *

        This writes the entire table in a single BigQuery request. - * The table will be created if necessary. - */ - private static void evaluateWriteHelper( - Write.Bound transform, DirectPipelineRunner.EvaluationContext context) { - BigQueryOptions options = context.getPipelineOptions(); - Bigquery client = Transport.newBigQueryClient(options).build(); - BigQueryTableInserter inserter = new BigQueryTableInserter(client); - - try { - Map> tableRows = new HashMap<>(); - for (WindowedValue windowedValue : context.getPCollectionWindowedValues( - context.getInput(transform))) { - for (BoundedWindow window : windowedValue.getWindows()) { - TableReference ref; - if (transform.tableRefFunction != null) { - ref = transform.tableRefFunction.apply(window); - } else { - ref = transform.table; - } - if (ref.getProjectId() == null) { - ref.setProjectId(options.getProject()); - } - - List rows = getOrCreateMapListValue(tableRows, ref); - rows.add(windowedValue.getValue()); - } - } - - for (TableReference ref : tableRows.keySet()) { - LOG.info("Writing to BigQuery table {}", toTableSpec(ref)); - // {@link BigQueryTableInserter#getOrCreateTable} validates {@link CreateDisposition} - // and {@link WriteDisposition}. - // For each {@link TableReference}, it can only be called before rows are written. - inserter.getOrCreateTable( - ref, transform.writeDisposition, transform.createDisposition, transform.schema); - inserter.insertAll(ref, tableRows.get(ref)); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java new file mode 100644 index 0000000000..85c39ea84b --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.cloud.dataflow.sdk.options.BigQueryOptions; + +import java.io.IOException; +import java.io.Serializable; + +/** + * An interface for real, mock, or fake implementations of Cloud BigQuery services. + */ +public interface BigQueryServices extends Serializable { + + /** + * Status of a BigQuery job or request. + */ + enum Status { + SUCCEEDED, + FAILED, + UNKNOWN, + } + + /** + * Returns a real, mock, or fake {@link LoadService}. + */ + public LoadService getLoadService(BigQueryOptions bqOptions); + + /** + * An interface for the Cloud BigQuery load service. + */ + public interface LoadService { + /** + * Start a BigQuery load job. + */ + public void startLoadJob(String jobId, JobConfigurationLoad loadConfig) + throws InterruptedException, IOException; + + /** + * Poll the status of a BigQuery load job. + */ + public Status pollJobStatus(String projectId, String jobId) + throws InterruptedException, IOException; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java new file mode 100644 index 0000000000..342095baa7 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.BackOffUtils; +import com.google.api.client.util.Sleeper; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.model.Job; +import com.google.api.services.bigquery.model.JobConfiguration; +import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatus; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.dataflow.sdk.options.BigQueryOptions; +import com.google.cloud.hadoop.util.ApiErrorExtractor; +import com.google.common.annotations.VisibleForTesting; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * An implementation of {@link BigQueryServices} that actually communicates with the cloud BigQuery + * service. + */ +public class BigQueryServicesImpl implements BigQueryServices { + + // The maximum number of attempts to execute a load job RPC. + private static final int MAX_LOAD_JOB_RPC_ATTEMPTS = 10; + + // The initial backoff for executing a load job RPC. + private static final long INITIAL_LOAD_JOB_RPC_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); + // The maximum number of retries to poll the status of a load job. + // It sets to {@code Integer.MAX_VALUE} to block until the BigQuery load job finishes. + private static final int MAX_LOAD_JOB_POLL_RETRIES = Integer.MAX_VALUE; + + // The initial backoff for polling the status of a load job. + private static final long INITIAL_LOAD_JOB_POLL_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(60); + + @Override + public LoadService getLoadService(BigQueryOptions options) { + return new LoadServiceImpl(options); + } + + @VisibleForTesting + static class LoadServiceImpl implements BigQueryServices.LoadService { + private static final Logger LOG = LoggerFactory.getLogger(LoadServiceImpl.class); + + private final ApiErrorExtractor errorExtractor; + private final Bigquery client; + + @VisibleForTesting + LoadServiceImpl(Bigquery client) { + this.errorExtractor = new ApiErrorExtractor(); + this.client = client; + } + + private LoadServiceImpl(BigQueryOptions options) { + this.errorExtractor = new ApiErrorExtractor(); + this.client = Transport.newBigQueryClient(options).build(); + } + + /** + * {@inheritDoc} + * + *

        Retries the RPC for at most {@code MAX_LOAD_JOB_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC retries. + */ + @Override + public void startLoadJob( + String jobId, + JobConfigurationLoad loadConfig) throws InterruptedException, IOException { + BackOff backoff = new AttemptBoundedExponentialBackOff( + MAX_LOAD_JOB_RPC_ATTEMPTS, INITIAL_LOAD_JOB_RPC_BACKOFF_MILLIS); + startLoadJob(jobId, loadConfig, Sleeper.DEFAULT, backoff); + } + + /** + * {@inheritDoc} + * + *

        Retries the poll request for at most {@code MAX_LOAD_JOB_POLL_RETRIES} times + * until the job is DONE. + */ + @Override + public Status pollJobStatus(String projectId, String jobId) throws InterruptedException { + BackOff backoff = new AttemptBoundedExponentialBackOff( + MAX_LOAD_JOB_POLL_RETRIES, INITIAL_LOAD_JOB_POLL_BACKOFF_MILLIS); + return pollJobStatus(projectId, jobId, Sleeper.DEFAULT, backoff); + } + + @VisibleForTesting + void startLoadJob( + String jobId, + JobConfigurationLoad loadConfig, + Sleeper sleeper, + BackOff backoff) + throws InterruptedException, IOException { + TableReference ref = loadConfig.getDestinationTable(); + String projectId = ref.getProjectId(); + + Job job = new Job(); + JobReference jobRef = new JobReference(); + jobRef.setProjectId(projectId); + jobRef.setJobId(jobId); + job.setJobReference(jobRef); + JobConfiguration config = new JobConfiguration(); + config.setLoad(loadConfig); + job.setConfiguration(config); + + Exception lastException = null; + do { + try { + client.jobs().insert(projectId, job).execute(); + return; // SUCCEEDED + } catch (GoogleJsonResponseException e) { + if (errorExtractor.itemAlreadyExists(e)) { + return; // SUCCEEDED + } + // ignore and retry + LOG.warn("Ignore the error and retry inserting the job.", e); + lastException = e; + } catch (IOException e) { + // ignore and retry + LOG.warn("Ignore the error and retry inserting the job.", e); + lastException = e; + } + } while (nextBackOff(sleeper, backoff)); + throw new IOException( + String.format( + "Unable to insert job: %s, aborting after %d retries.", + jobId, MAX_LOAD_JOB_RPC_ATTEMPTS), + lastException); + } + + @VisibleForTesting + Status pollJobStatus( + String projectId, + String jobId, + Sleeper sleeper, + BackOff backoff) throws InterruptedException { + do { + try { + JobStatus status = client.jobs().get(projectId, jobId).execute().getStatus(); + if (status != null && status.getState() != null && status.getState().equals("DONE")) { + if (status.getErrorResult() != null) { + return Status.FAILED; + } else if (status.getErrors() != null && !status.getErrors().isEmpty()) { + return Status.FAILED; + } else { + return Status.SUCCEEDED; + } + } + // The job is not DONE, wait longer and retry. + } catch (IOException e) { + // ignore and retry + LOG.warn("Ignore the error and retry polling job status.", e); + } + } while (nextBackOff(sleeper, backoff)); + LOG.warn("Unable to poll job status: {}, aborting after {} retries.", + jobId, MAX_LOAD_JOB_POLL_RETRIES); + return Status.UNKNOWN; + } + + /** + * Identical to {@link BackOffUtils#next} but without checked IOException. + * @throws InterruptedException + */ + private boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { + try { + return BackOffUtils.next(sleeper, backoff); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index a081de095c..5f70df3f5b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -20,6 +20,8 @@ import static org.junit.Assert.assertNull; import com.google.api.client.util.Data; +import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; @@ -30,10 +32,14 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.util.BigQueryServices; +import com.google.cloud.dataflow.sdk.util.BigQueryServices.Status; import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.common.collect.ImmutableList; import org.hamcrest.Matchers; import org.junit.Assert; @@ -42,8 +48,15 @@ import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; /** * Tests for BigQueryIO. @@ -51,8 +64,96 @@ @RunWith(JUnit4.class) public class BigQueryIOTest { + private static class FakeBigQueryServices implements BigQueryServices { + + private Object[] startLoadJobReturns; + private Object[] pollJobStatusReturns; + + /** + * Sets the return values for the mock {@link LoadService#startLoadJob}. + * + *

        Throws if the {@link Object} is a {@link Exception}, returns otherwise. + */ + private FakeBigQueryServices startLoadJobReturns(Object... startLoadJobReturns) { + this.startLoadJobReturns = startLoadJobReturns; + return this; + } + + /** + * Sets the return values for the mock {@link LoadService#pollJobStatus}. + * + *

        Throws if the {@link Object} is a {@link Exception}, returns otherwise. + */ + private FakeBigQueryServices pollJobStatusReturns(Object... pollJobStatusReturns) { + this.pollJobStatusReturns = pollJobStatusReturns; + return this; + } + + @Override + public LoadService getLoadService(BigQueryOptions bqOptions) { + return new FakeLoadService(startLoadJobReturns, pollJobStatusReturns); + } + + private static class FakeLoadService implements BigQueryServices.LoadService { + + private Object[] startLoadJobReturns; + private Object[] pollJobStatusReturns; + private int startLoadJobCallsCount; + private int pollJobStatusCallsCount; + + public FakeLoadService(Object[] startLoadJobReturns, Object[] pollJobStatusReturns) { + this.startLoadJobReturns = startLoadJobReturns; + this.pollJobStatusReturns = pollJobStatusReturns; + this.startLoadJobCallsCount = 0; + this.pollJobStatusCallsCount = 0; + } + + @Override + public void startLoadJob(String jobId, JobConfigurationLoad loadConfig) + throws InterruptedException, IOException { + if (startLoadJobCallsCount < startLoadJobReturns.length) { + Object ret = startLoadJobReturns[startLoadJobCallsCount++]; + if (ret instanceof IOException) { + throw (IOException) ret; + } else if (ret instanceof InterruptedException) { + throw (InterruptedException) ret; + } else { + return; + } + } else { + throw new RuntimeException( + "Exceeded expected number of calls: " + startLoadJobReturns.length); + } + } + + @Override + public Status pollJobStatus(String projectId, String jobId) throws InterruptedException { + if (pollJobStatusCallsCount < pollJobStatusReturns.length) { + Object ret = pollJobStatusReturns[pollJobStatusCallsCount++]; + if (ret instanceof Status) { + return (Status) ret; + } else if (ret instanceof InterruptedException) { + throw (InterruptedException) ret; + } else { + throw new RuntimeException("Unexpected return type: " + ret.getClass()); + } + } else { + throw new RuntimeException( + "Exceeded expected number of calls: " + pollJobStatusReturns.length); + } + } + } + } + @Rule public ExpectedException thrown = ExpectedException.none(); + @Rule public ExpectedLogs logged = ExpectedLogs.none(BigQueryIO.class); + @Rule + public TemporaryFolder testFolder = new TemporaryFolder(); + @Mock + public BigQueryServices.LoadService mockBqLoadService; + + private BigQueryOptions bqOptions; private void checkReadTableObject( BigQueryIO.Read.Bound bound, String project, String dataset, String table) { @@ -92,19 +193,23 @@ private void checkWriteObjectWithValidate( BigQueryIO.Write.Bound bound, String project, String dataset, String table, TableSchema schema, CreateDisposition createDisposition, WriteDisposition writeDisposition, boolean validate) { - assertEquals(project, bound.table.getProjectId()); - assertEquals(dataset, bound.table.getDatasetId()); - assertEquals(table, bound.table.getTableId()); - assertEquals(schema, bound.schema); + assertEquals(project, bound.getTable().getProjectId()); + assertEquals(dataset, bound.getTable().getDatasetId()); + assertEquals(table, bound.getTable().getTableId()); + assertEquals(schema, bound.getSchema()); assertEquals(createDisposition, bound.createDisposition); assertEquals(writeDisposition, bound.writeDisposition); assertEquals(validate, bound.validate); } + @Before public void setUp() { - BigQueryOptions options = PipelineOptionsFactory.as(BigQueryOptions.class); - options.setProject("defaultProject"); + bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation(testFolder.getRoot().getAbsolutePath() + "/BigQueryIOTest/"); + + MockitoAnnotations.initMocks(this); } @Test @@ -221,6 +326,67 @@ public void testBuildSourceWithTableAndFlatten() { p.run(); } + @Test + public void testCustomSink() throws Exception { + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .startLoadJobReturns("done", "done", "done") + .pollJobStatusReturns(Status.FAILED, Status.FAILED, Status.SUCCEEDED); + + Pipeline p = TestPipeline.create(bqOptions); + p.apply(Create.of( + new TableRow().set("name", "a").set("number", 1), + new TableRow().set("name", "b").set("number", 2), + new TableRow().set("name", "c").set("number", 3))) + .setCoder(TableRowJsonCoder.of()) + .apply(BigQueryIO.Write.to("project-id:dataset-id.table-id") + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) + .withSchema(new TableSchema().setFields( + ImmutableList.of( + new TableFieldSchema().setName("name").setType("STRING"), + new TableFieldSchema().setName("number").setType("INTEGER")))) + .withTestServices(fakeBqServices) + .withoutValidation()); + p.run(); + + logged.verifyInfo("Starting BigQuery load job"); + logged.verifyInfo("Previous load jobs failed, retrying."); + File tempDir = new File(bqOptions.getTempLocation()); + assertEquals(0, tempDir.listFiles(new FileFilter() { + @Override + public boolean accept(File pathname) { + return pathname.isFile(); + }}).length); + } + + @Test + public void testCustomSinkUnknown() throws Exception { + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .startLoadJobReturns("done", "done") + .pollJobStatusReturns(Status.FAILED, Status.UNKNOWN); + + Pipeline p = TestPipeline.create(bqOptions); + p.apply(Create.of( + new TableRow().set("name", "a").set("number", 1), + new TableRow().set("name", "b").set("number", 2), + new TableRow().set("name", "c").set("number", 3))) + .setCoder(TableRowJsonCoder.of()) + .apply(BigQueryIO.Write.to("project-id:dataset-id.table-id") + .withCreateDisposition(CreateDisposition.CREATE_NEVER) + .withTestServices(fakeBqServices) + .withoutValidation()); + + thrown.expect(RuntimeException.class); + thrown.expectMessage("Failed to poll the load job status."); + p.run(); + + File tempDir = new File(bqOptions.getTempLocation()); + assertEquals(0, tempDir.listFiles(new FileFilter() { + @Override + public boolean accept(File pathname) { + return pathname.isFile(); + }}).length); + } + @Test public void testBuildSink() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") @@ -350,15 +516,11 @@ private void testWriteValidatesDataset(boolean streaming) { thrown.expectMessage( Matchers.either(Matchers.containsString("Unable to confirm BigQuery dataset presence")) .or(Matchers.containsString("BigQuery dataset not found for table"))); - try { - p.apply(Create.of().withCoder(TableRowJsonCoder.of())) - .apply(BigQueryIO.Write.named("WriteMyTable") - .to(tableRef) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withSchema(new TableSchema())); - } finally { - Assert.assertEquals("someproject", tableRef.getProjectId()); - } + p.apply(Create.of().withCoder(TableRowJsonCoder.of())) + .apply(BigQueryIO.Write.named("WriteMyTable") + .to(tableRef) + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) + .withSchema(new TableSchema())); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java new file mode 100644 index 0000000000..08e6686646 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java @@ -0,0 +1,260 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; +import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; +import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.json.GenericJson; +import com.google.api.client.json.Json; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.Sleeper; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.model.ErrorProto; +import com.google.api.services.bigquery.model.Job; +import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobStatus; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; +import com.google.common.collect.ImmutableList; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Tests for {@link BigQueryServicesImpl}. + */ +@RunWith(JUnit4.class) +public class BigQueryServicesImplTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(BigQueryServicesImpl.class); + @Mock private LowLevelHttpResponse response; + private Bigquery bigquery; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + // A mock transport that lets us mock the API responses. + MockHttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpRequest( + new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + return response; + } + }) + .build(); + + // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer. + bigquery = + new Bigquery.Builder( + transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()) + .build(); + } + + /** + * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#startLoadJob} succeeds. + */ + @Test + public void testStartLoadJobSucceeds() throws IOException, InterruptedException { + Job testJob = new Job(); + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(200); + when(response.getContent()).thenReturn(toStream(testJob)); + + TableReference ref = new TableReference(); + ref.setProjectId("projectId"); + JobConfigurationLoad loadConfig = new JobConfigurationLoad(); + loadConfig.setDestinationTable(ref); + + Sleeper sleeper = new FastNanoClockAndSleeper(); + BackOff backoff = new AttemptBoundedExponentialBackOff( + 5 /* attempts */, 1000 /* initialIntervalMillis */); + BigQueryServicesImpl.LoadServiceImpl loadService = + new BigQueryServicesImpl.LoadServiceImpl(bigquery); + loadService.startLoadJob("jobId", loadConfig, sleeper, backoff); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + /** + * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#startLoadJob} succeeds + * with an already exist job. + */ + @Test + public void testStartLoadJobSucceedsAlreadyExists() throws IOException, InterruptedException { + when(response.getStatusCode()).thenReturn(409); // 409 means already exists + + TableReference ref = new TableReference(); + ref.setProjectId("projectId"); + JobConfigurationLoad loadConfig = new JobConfigurationLoad(); + loadConfig.setDestinationTable(ref); + + Sleeper sleeper = new FastNanoClockAndSleeper(); + BackOff backoff = new AttemptBoundedExponentialBackOff( + 5 /* attempts */, 1000 /* initialIntervalMillis */); + BigQueryServicesImpl.LoadServiceImpl loadService = + new BigQueryServicesImpl.LoadServiceImpl(bigquery); + loadService.startLoadJob("jobId", loadConfig, sleeper, backoff); + + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + /** + * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#startLoadJob} succeeds with a retry. + */ + @Test + public void testStartLoadJobRetry() throws IOException, InterruptedException { + Job testJob = new Job(); + + // First response is 403 rate limited, second response has valid payload. + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(403).thenReturn(200); + when(response.getContent()) + .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403))) + .thenReturn(toStream(testJob)); + + TableReference ref = new TableReference(); + ref.setProjectId("projectId"); + JobConfigurationLoad loadConfig = new JobConfigurationLoad(); + loadConfig.setDestinationTable(ref); + + Sleeper sleeper = new FastNanoClockAndSleeper(); + BackOff backoff = new AttemptBoundedExponentialBackOff( + 5 /* attempts */, 1000 /* initialIntervalMillis */); + BigQueryServicesImpl.LoadServiceImpl loadService = + new BigQueryServicesImpl.LoadServiceImpl(bigquery); + loadService.startLoadJob("jobId", loadConfig, sleeper, backoff); + verify(response, times(2)).getStatusCode(); + verify(response, times(2)).getContent(); + verify(response, times(2)).getContentType(); + } + + /** + * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#pollJobStatus} succeeds. + */ + @Test + public void testPollJobStatusSucceeds() throws IOException, InterruptedException { + Job testJob = new Job(); + testJob.setStatus(new JobStatus().setState("DONE")); + + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(200); + when(response.getContent()).thenReturn(toStream(testJob)); + + BigQueryServicesImpl.LoadServiceImpl loadService = + new BigQueryServicesImpl.LoadServiceImpl(bigquery); + BigQueryServices.Status status = + loadService.pollJobStatus("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + + assertEquals(BigQueryServices.Status.SUCCEEDED, status); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + /** + * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#pollJobStatus} fails. + */ + @Test + public void testPollJobStatusFailed() throws IOException, InterruptedException { + Job testJob = new Job(); + testJob.setStatus(new JobStatus().setState("DONE").setErrorResult(new ErrorProto())); + + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(200); + when(response.getContent()).thenReturn(toStream(testJob)); + + BigQueryServicesImpl.LoadServiceImpl loadService = + new BigQueryServicesImpl.LoadServiceImpl(bigquery); + BigQueryServices.Status status = + loadService.pollJobStatus("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + + assertEquals(BigQueryServices.Status.FAILED, status); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + /** + * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#pollJobStatus} returns UNKNOWN. + */ + @Test + public void testPollJobStatusUnknown() throws IOException, InterruptedException { + Job testJob = new Job(); + testJob.setStatus(new JobStatus()); + + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(200); + when(response.getContent()).thenReturn(toStream(testJob)); + + BigQueryServicesImpl.LoadServiceImpl loadService = + new BigQueryServicesImpl.LoadServiceImpl(bigquery); + BigQueryServices.Status status = + loadService.pollJobStatus("projectId", "jobId", Sleeper.DEFAULT, BackOff.STOP_BACKOFF); + + assertEquals(BigQueryServices.Status.UNKNOWN, status); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + /** A helper to wrap a {@link GenericJson} object in a content stream. */ + private static InputStream toStream(GenericJson content) throws IOException { + return new ByteArrayInputStream(JacksonFactory.getDefaultInstance().toByteArray(content)); + } + + /** A helper that generates the error JSON payload that Google APIs produce. */ + private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, int status) { + ErrorInfo info = new ErrorInfo(); + info.setReason(reason); + info.setDomain("global"); + // GoogleJsonError contains one or more ErrorInfo objects; our utiities read the first one. + GoogleJsonError error = new GoogleJsonError(); + error.setErrors(ImmutableList.of(info)); + error.setCode(status); + // The actual JSON response is an error container. + GoogleJsonErrorContainer container = new GoogleJsonErrorContainer(); + container.setError(error); + return container; + } +} + From 6c62c4690e4268a50e6211982584cdd8b11b8ea3 Mon Sep 17 00:00:00 2001 From: swegner Date: Wed, 6 Apr 2016 16:57:56 -0700 Subject: [PATCH 317/751] Integration fixes ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=119217803 --- .../DataflowPipelineTranslatorTest.java | 64 ++++++++++--------- .../EncodabilityEnforcementFactoryTest.java | 3 + .../transforms/display/DisplayDataTest.java | 1 + 3 files changed, 37 insertions(+), 31 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index fef108dff3..83cfc9b4f9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -69,6 +69,7 @@ import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import org.hamcrest.Matchers; @@ -817,10 +818,10 @@ public void processElement(ProcessContext c) throws Exception { @Override public void populateDisplayData(DisplayData.Builder builder) { builder - .add("foo", "bar") - .add("foo2", DataflowPipelineTranslatorTest.class) - .withLabel("Test Class") - .withLinkUrl("http://www.google.com"); + .add("foo", "bar") + .add("foo2", 123) + .withLabel("Test Value") + .withLinkUrl("http://www.google.com"); } }; @@ -836,10 +837,12 @@ public void populateDisplayData(DisplayData.Builder builder) { } }; + ParDo.Bound parDo1 = ParDo.of(fn1); + ParDo.Bound parDo2 = ParDo.of(fn2); pipeline .apply(Create.of(1, 2, 3)) - .apply(ParDo.of(fn1)) - .apply(ParDo.of(fn2)); + .apply(parDo1) + .apply(parDo2); Job job = translator.translate( pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); @@ -856,34 +859,33 @@ public void populateDisplayData(DisplayData.Builder builder) { Collection> fn2displayData = (Collection>) parDo2Properties.get("display_data"); - ImmutableList expectedFn1DisplayData = ImmutableList.of( - ImmutableMap.builder() - .put("namespace", fn1.getClass().getName()) - .put("key", "foo") - .put("type", "STRING") - .put("value", "bar") - .build(), - ImmutableMap.builder() - .put("namespace", fn1.getClass().getName()) - .put("key", "foo2") - .put("type", "JAVA_CLASS") - .put("value", DataflowPipelineTranslatorTest.class.getName()) - .put("shortValue", DataflowPipelineTranslatorTest.class.getSimpleName()) - .put("label", "Test Class") - .put("linkUrl", "http://www.google.com") - .build() + ImmutableSet> expectedFn1DisplayData = ImmutableSet.of( + ImmutableMap.builder() + .put("key", "foo") + .put("type", "STRING") + .put("value", "bar") + .put("namespace", fn1.getClass().getName()) + .build(), + ImmutableMap.builder() + .put("key", "foo2") + .put("type", "INTEGER") + .put("value", "123") + .put("namespace", fn1.getClass().getName()) + .put("label", "Test Value") + .put("linkUrl", "http://www.google.com") + .build() ); - ImmutableList expectedFn2DisplayData = ImmutableList.of( - ImmutableMap.builder() - .put("namespace", fn2.getClass().getName()) - .put("key", "foo3") - .put("type", "STRING") - .put("value", "barge") - .build() + ImmutableSet> expectedFn2DisplayData = ImmutableSet.of( + ImmutableMap.builder() + .put("key", "foo3") + .put("type", "STRING") + .put("value", "barge") + .put("namespace", fn2.getClass().getName()) + .build() ); - assertEquals(expectedFn1DisplayData, fn1displayData); - assertEquals(expectedFn2DisplayData, fn2displayData); + assertEquals(expectedFn1DisplayData, ImmutableSet.copyOf(fn1displayData)); + assertEquals(expectedFn2DisplayData, ImmutableSet.copyOf(fn2displayData)); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java index dcc9775bd8..73c103ac90 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java @@ -33,6 +33,8 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.io.InputStream; @@ -42,6 +44,7 @@ /** * Tests for {@link EncodabilityEnforcementFactory}. */ +@RunWith(JUnit4.class) public class EncodabilityEnforcementFactoryTest { @Rule public ExpectedException thrown = ExpectedException.none(); private EncodabilityEnforcementFactory factory = EncodabilityEnforcementFactory.create(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index dfc8c38f52..e8128c7788 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -553,6 +553,7 @@ public void populateDisplayData(Builder builder) { }); } + @Test public void testAcceptsNullOptionalValues() { DisplayData.from( new HasDisplayData() { From 7545d86771f90959289c784ec802bc5453fbb458 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 14 Apr 2016 17:23:42 -0700 Subject: [PATCH 318/751] [BEAM-188] Write: apply GlobalWindows first And do not supply a timestamp when outputting. Note that this is safe because the functions in the Writer cannot access the window or timestamp. When we add per-Window or similar functions to the sinks, we will likely do so at a higher level. --- .../google/cloud/dataflow/sdk/io/Write.java | 9 +- .../cloud/dataflow/sdk/io/WriteTest.java | 95 +++++++++++++++---- 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java index 0b78b8384e..65d3c992d8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java @@ -32,8 +32,6 @@ import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; -import org.joda.time.Instant; - import java.util.UUID; /** @@ -151,6 +149,7 @@ public void processElement(ProcessContext c) throws Exception { // There is a dependency between this ParDo and the first (the WriteOperation PCollection // as a side input), so this will happen after the initial ParDo. PCollection results = input + .apply(Window.into(new GlobalWindows())) .apply("WriteBundles", ParDo.of(new DoFn() { // Writer that will write the records in this bundle. Lazily // initialized in processElement. @@ -181,13 +180,11 @@ public void processElement(ProcessContext c) throws Exception { public void finishBundle(Context c) throws Exception { if (writer != null) { WriteT result = writer.close(); - // Output the result of the write. - c.outputWithTimestamp(result, Instant.now()); + c.output(result); } } }).withSideInputs(writeOperationView)) - .setCoder(writeOperation.getWriterResultCoder()) - .apply(Window.into(new GlobalWindows())); + .setCoder(writeOperation.getWriterResultCoder()); final PCollectionView> resultsView = results.apply(View.asIterable()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java index b92f2f18ea..0d4a70fd19 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java @@ -32,8 +32,16 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest.TestPipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.MapElements; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; @@ -50,6 +58,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; /** * Tests for the Write PTransform. @@ -57,7 +66,47 @@ @RunWith(JUnit4.class) public class WriteTest { // Static store that can be accessed within the writer - static List sinkContents = new ArrayList<>(); + private static List sinkContents = new ArrayList<>(); + + private static final MapElements IDENTITY_MAP = + MapElements.via(new SimpleFunction() { + @Override + public String apply(String input) { + return input; + } + }); + + private static class WindowAndReshuffle extends PTransform, PCollection> { + private final Window.Bound window; + public WindowAndReshuffle(Window.Bound window) { + this.window = window; + } + + private static class AddArbitraryKey extends DoFn> { + @Override + public void processElement(ProcessContext c) throws Exception { + c.output(KV.of(ThreadLocalRandom.current().nextInt(), c.element())); + } + } + + private static class RemoveArbitraryKey extends DoFn>, T> { + @Override + public void processElement(ProcessContext c) throws Exception { + for (T s : c.element().getValue()) { + c.output(s); + } + } + } + + @Override + public PCollection apply(PCollection input) { + return input + .apply(window) + .apply(ParDo.of(new AddArbitraryKey())) + .apply(GroupByKey.create()) + .apply(ParDo.of(new RemoveArbitraryKey())); + } + } /** * Test a Write transform with a PCollection of elements. @@ -66,7 +115,7 @@ public class WriteTest { public void testWrite() { List inputs = Arrays.asList("Critical canary", "Apprehensive eagle", "Intimidating pigeon", "Pedantic gull", "Frisky finch"); - runWrite(inputs, /* not windowed */ false); + runWrite(inputs, IDENTITY_MAP); } /** @@ -75,7 +124,7 @@ public void testWrite() { @Test public void testWriteWithEmptyPCollection() { List inputs = new ArrayList<>(); - runWrite(inputs, /* not windowed */ false); + runWrite(inputs, IDENTITY_MAP); } /** @@ -85,7 +134,21 @@ public void testWriteWithEmptyPCollection() { public void testWriteWindowed() { List inputs = Arrays.asList("Critical canary", "Apprehensive eagle", "Intimidating pigeon", "Pedantic gull", "Frisky finch"); - runWrite(inputs, /* windowed */ true); + runWrite( + inputs, new WindowAndReshuffle(Window.into(FixedWindows.of(Duration.millis(2))))); + } + + /** + * Test a Write with sessions. + */ + @Test + public void testWriteWithSessions() { + List inputs = Arrays.asList("Critical canary", "Apprehensive eagle", + "Intimidating pigeon", "Pedantic gull", "Frisky finch"); + + runWrite( + inputs, + new WindowAndReshuffle(Window.into(Sessions.withGapDuration(Duration.millis(1))))); } /** @@ -93,7 +156,8 @@ public void testWriteWindowed() { * a test sink in the correct order, as well as verifies that the elements of a PCollection are * written to the sink. */ - public void runWrite(List inputs, boolean windowed) { + private static void runWrite( + List inputs, PTransform, PCollection> transform) { // Flag to validate that the pipeline options are passed to the Sink String[] args = {"--testFlag=test_value"}; PipelineOptions options = PipelineOptionsFactory.fromArgs(args).as(WriteOptions.class); @@ -102,21 +166,16 @@ public void runWrite(List inputs, boolean windowed) { // Clear the sink's contents. sinkContents.clear(); - // Construct the input PCollection and test Sink. - PCollection input; - if (windowed) { - List timestamps = new ArrayList<>(); - for (long i = 0; i < inputs.size(); i++) { - timestamps.add(i + 1); - } - input = p.apply(Create.timestamped(inputs, timestamps).withCoder(StringUtf8Coder.of())) - .apply(Window.into(FixedWindows.of(new Duration(2)))); - } else { - input = p.apply(Create.of(inputs).withCoder(StringUtf8Coder.of())); + // Prepare timestamps for the elements. + List timestamps = new ArrayList<>(); + for (long i = 0; i < inputs.size(); i++) { + timestamps.add(i + 1); } - TestSink sink = new TestSink(); - input.apply(Write.to(sink)); + TestSink sink = new TestSink(); + p.apply(Create.timestamped(inputs, timestamps).withCoder(StringUtf8Coder.of())) + .apply(transform) + .apply(Write.to(sink)); p.run(); assertThat(sinkContents, containsInAnyOrder(inputs.toArray())); From 08be8eeb610b29d19eaf45c76b859a65cfb6d964 Mon Sep 17 00:00:00 2001 From: Pei He Date: Thu, 14 Apr 2016 23:17:36 -0700 Subject: [PATCH 319/751] Override BigQueryIO.Write with native sink for Dataflow runner --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 1 - .../sdk/runners/DataflowPipelineRunner.java | 107 ++++++++++++++++++ .../runners/DataflowPipelineTranslator.java | 2 - .../dataflow/BigQueryIOTranslator.java | 55 --------- 4 files changed, 107 insertions(+), 58 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index f4094e5274..8f291b99f9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -36,7 +36,6 @@ import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQuerySink; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 99bbb257d6..0f0fc477dd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -23,6 +23,9 @@ import static com.google.common.base.Preconditions.checkState; import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.json.JsonFactory; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.clouddebugger.v2.Clouddebugger; import com.google.api.services.clouddebugger.v2.model.Debuggee; import com.google.api.services.clouddebugger.v2.model.RegisterDebuggeeRequest; @@ -49,6 +52,7 @@ import com.google.cloud.dataflow.sdk.coders.MapCoder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; @@ -228,6 +232,7 @@ public class DataflowPipelineRunner extends PipelineRunner */ public static final String PROJECT_ID_REGEXP = "[a-z][-a-z0-9:.]+[a-z0-9]"; + private static final JsonFactory JSON_FACTORY = Transport.getJsonFactory(); /** * Construct a runner from the provided options. * @@ -355,6 +360,10 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(View.AsList.class, BatchViewAsList.class); builder.put(View.AsIterable.class, BatchViewAsIterable.class); } + if (options.getExperiments() == null + || !options.getExperiments().contains("enable_custom_bigquery_sink")) { + builder.put(BigQueryIO.Write.Bound.class, BatchBigQueryIOWrite.class); + } overrides = builder.build(); } } @@ -2059,6 +2068,104 @@ public PDone apply(PCollection input) { } } + private static class BatchBigQueryIOWrite extends PTransform, PDone> { + private final BigQueryIO.Write.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchBigQueryIOWrite(DataflowPipelineRunner runner, BigQueryIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + if (transform.getTable() == null) { + // BigQueryIO.Write is using tableRefFunction with StreamWithDeDup. + return transform.apply(input); + } else { + return input + .apply(new BatchBigQueryIONativeWrite(transform)); + } + } + } + + /** + * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way + * to provide the native definition of the BigQuery sink. + */ + private static class BatchBigQueryIONativeWrite extends PTransform, PDone> { + private final BigQueryIO.Write.Bound transform; + public BatchBigQueryIONativeWrite(BigQueryIO.Write.Bound transform) { + this.transform = transform; + } + + @Override + public PDone apply(PCollection input) { + return PDone.in(input.getPipeline()); + } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + BatchBigQueryIONativeWrite.class, new BatchBigQueryIONativeWriteTranslator()); + } + } + + /** + * {@code BigQueryIO.Write.Bound} support code for the Dataflow backend. + */ + private static class BatchBigQueryIONativeWriteTranslator + implements TransformTranslator { + @SuppressWarnings("unchecked") + @Override + public void translate(BatchBigQueryIONativeWrite transform, + TranslationContext context) { + translateWriteHelper(transform, transform.transform, context); + } + + private void translateWriteHelper( + BatchBigQueryIONativeWrite transform, + BigQueryIO.Write.Bound originalTransform, + TranslationContext context) { + if (context.getPipelineOptions().isStreaming()) { + // Streaming is handled by the streaming runner. + throw new AssertionError( + "BigQueryIO is specified to use streaming write in batch mode."); + } + + TableReference table = originalTransform.getTable(); + + // Actual translation. + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.FORMAT, "bigquery"); + context.addInput(PropertyNames.BIGQUERY_TABLE, + table.getTableId()); + context.addInput(PropertyNames.BIGQUERY_DATASET, + table.getDatasetId()); + if (table.getProjectId() != null) { + context.addInput(PropertyNames.BIGQUERY_PROJECT, table.getProjectId()); + } + if (originalTransform.getSchema() != null) { + try { + context.addInput(PropertyNames.BIGQUERY_SCHEMA, + JSON_FACTORY.toString(originalTransform.getSchema())); + } catch (IOException exn) { + throw new IllegalArgumentException("Invalid table schema.", exn); + } + } + context.addInput( + PropertyNames.BIGQUERY_CREATE_DISPOSITION, + originalTransform.getCreateDisposition().name()); + context.addInput( + PropertyNames.BIGQUERY_WRITE_DISPOSITION, + originalTransform.getWriteDisposition().name()); + // Set sink encoding to TableRowJsonCoder. + context.addEncodingInput( + WindowedValue.getValueOnlyCoder(TableRowJsonCoder.of())); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + } + } + /** * Specialized implementation which overrides * {@link com.google.cloud.dataflow.sdk.io.TextIO.Write.Bound TextIO.Write.Bound} with diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 155c454b38..75fd5b3f93 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -1043,8 +1043,6 @@ private void translateHelper( registerTransformTranslator( BigQueryIO.Read.Bound.class, new BigQueryIOTranslator.ReadTranslator()); - registerTransformTranslator( - BigQueryIO.Write.Bound.class, new BigQueryIOTranslator.WriteTranslator()); registerTransformTranslator( PubsubIO.Read.Bound.class, new PubsubIOTranslator.ReadTranslator()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java index 538901c722..c327ecf434 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java @@ -16,25 +16,18 @@ package com.google.cloud.dataflow.sdk.runners.dataflow; -import com.google.api.client.json.JsonFactory; import com.google.api.services.bigquery.model.TableReference; -import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.WindowedValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - /** * BigQuery transform support code for the Dataflow backend. */ public class BigQueryIOTranslator { - private static final JsonFactory JSON_FACTORY = Transport.getJsonFactory(); private static final Logger LOG = LoggerFactory.getLogger(BigQueryIOTranslator.class); /** @@ -74,52 +67,4 @@ public void translate( context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); } } - - /** - * Implements BigQueryIO Write translation for the Dataflow backend. - */ - public static class WriteTranslator - implements DataflowPipelineTranslator.TransformTranslator { - - @Override - public void translate(BigQueryIO.Write.Bound transform, - DataflowPipelineTranslator.TranslationContext context) { - if (context.getPipelineOptions().isStreaming()) { - // Streaming is handled by the streaming runner. - throw new AssertionError( - "BigQueryIO is specified to use streaming write in batch mode."); - } - - TableReference table = transform.getTable(); - - // Actual translation. - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.FORMAT, "bigquery"); - context.addInput(PropertyNames.BIGQUERY_TABLE, - table.getTableId()); - context.addInput(PropertyNames.BIGQUERY_DATASET, - table.getDatasetId()); - if (table.getProjectId() != null) { - context.addInput(PropertyNames.BIGQUERY_PROJECT, table.getProjectId()); - } - if (transform.getSchema() != null) { - try { - context.addInput(PropertyNames.BIGQUERY_SCHEMA, - JSON_FACTORY.toString(transform.getSchema())); - } catch (IOException exn) { - throw new IllegalArgumentException("Invalid table schema.", exn); - } - } - context.addInput( - PropertyNames.BIGQUERY_CREATE_DISPOSITION, - transform.getCreateDisposition().name()); - context.addInput( - PropertyNames.BIGQUERY_WRITE_DISPOSITION, - transform.getWriteDisposition().name()); - // Set sink encoding to TableRowJsonCoder. - context.addEncodingInput( - WindowedValue.getValueOnlyCoder(TableRowJsonCoder.of())); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - } - } } From 3dab6ab684df64a860e9fdae9b7721e722d7e742 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Sat, 16 Apr 2016 17:51:03 -0700 Subject: [PATCH 320/751] BigtableIO: switch to ProtoCoder from deprecated Proto2Coder --- .../com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index 7d59b09c8d..f025d3ccd9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -27,8 +27,8 @@ import com.google.cloud.bigtable.config.BigtableOptions; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Proto2Coder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; @@ -658,7 +658,7 @@ public void validate() { @Override public Coder getDefaultOutputCoder() { - return Proto2Coder.of(Row.class); + return ProtoCoder.of(Row.class); } /** Helper that splits the specified range in this source into bundles. */ From 553730b93642cd52d6129f4fa9959f5b71e65aef Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 29 Mar 2016 17:38:22 -0700 Subject: [PATCH 321/751] Move Shared construction code to ParDoInProcessEvaluator Remove duplicate code in ParDo(Single/Multi)EvaluatorFactory; instead only extract the appropriate elements and pass them to the ParDoInProcessEvaluator. --- .../inprocess/ParDoInProcessEvaluator.java | 50 ++++++++++++++++- .../inprocess/ParDoMultiEvaluatorFactory.java | 53 +++++-------------- .../ParDoSingleEvaluatorFactory.java | 50 +++++------------ 3 files changed, 76 insertions(+), 77 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index 17546f1953..9c6ec5821f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -16,15 +16,19 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.util.DoFnRunner; +import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TupleTag; import java.util.ArrayList; @@ -34,13 +38,57 @@ import java.util.Map; class ParDoInProcessEvaluator implements TransformEvaluator { + public static ParDoInProcessEvaluator create( + InProcessEvaluationContext evaluationContext, + CommittedBundle inputBundle, + AppliedPTransform, ?, ?> application, + DoFn fn, + List> sideInputs, + TupleTag mainOutputTag, + List> sideOutputTags, + Map, PCollection> outputs) { + InProcessExecutionContext executionContext = + evaluationContext.getExecutionContext(application, inputBundle.getKey()); + String stepName = evaluationContext.getStepName(application); + InProcessStepContext stepContext = + executionContext.getOrCreateStepContext(stepName, stepName, null); + + CounterSet counters = evaluationContext.createCounterSet(); + + Map, UncommittedBundle> outputBundles = new HashMap<>(); + for (Map.Entry, PCollection> outputEntry : outputs.entrySet()) { + outputBundles.put( + outputEntry.getKey(), + evaluationContext.createBundle(inputBundle, outputEntry.getValue())); + } + + DoFnRunner runner = + DoFnRunners.createDefault( + evaluationContext.getPipelineOptions(), + fn, + evaluationContext.createSideInputReader(sideInputs), + BundleOutputManager.create(outputBundles), + mainOutputTag, + sideOutputTags, + stepContext, + counters.getAddCounterMutator(), + application.getInput().getWindowingStrategy()); + + runner.startBundle(); + + return new ParDoInProcessEvaluator<>( + runner, application, counters, outputBundles.values(), stepContext); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + private final DoFnRunner fnRunner; private final AppliedPTransform, ?, ?> transform; private final CounterSet counters; private final Collection> outputBundles; private final InProcessStepContext stepContext; - public ParDoInProcessEvaluator( + private ParDoInProcessEvaluator( DoFnRunner fnRunner, AppliedPTransform, ?, ?> transform, CounterSet counters, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java index 24142c2151..245115b95b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java @@ -15,22 +15,15 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionTuple; import com.google.cloud.dataflow.sdk.values.TupleTag; -import java.util.HashMap; import java.util.Map; /** @@ -43,45 +36,27 @@ public TransformEvaluator forApplication( AppliedPTransform application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - return createMultiEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); + @SuppressWarnings({"unchecked", "rawtypes"}) + TransformEvaluator evaluator = + createMultiEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); + return evaluator; } private static ParDoInProcessEvaluator createMultiEvaluator( AppliedPTransform, PCollectionTuple, BoundMulti> application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - PCollectionTuple output = application.getOutput(); - Map, PCollection> outputs = output.getAll(); - Map, UncommittedBundle> outputBundles = new HashMap<>(); - for (Map.Entry, PCollection> outputEntry : outputs.entrySet()) { - outputBundles.put( - outputEntry.getKey(), - evaluationContext.createBundle(inputBundle, outputEntry.getValue())); - } - InProcessExecutionContext executionContext = - evaluationContext.getExecutionContext(application, inputBundle.getKey()); - String stepName = evaluationContext.getStepName(application); - InProcessStepContext stepContext = - executionContext.getOrCreateStepContext(stepName, stepName, null); - - CounterSet counters = evaluationContext.createCounterSet(); - + Map, PCollection> outputs = application.getOutput().getAll(); DoFn fn = application.getTransform().getFn(); - DoFnRunner runner = - DoFnRunners.createDefault( - evaluationContext.getPipelineOptions(), - fn, - evaluationContext.createSideInputReader(application.getTransform().getSideInputs()), - BundleOutputManager.create(outputBundles), - application.getTransform().getMainOutputTag(), - application.getTransform().getSideOutputTags().getAll(), - stepContext, - counters.getAddCounterMutator(), - application.getInput().getWindowingStrategy()); - - runner.startBundle(); - return new ParDoInProcessEvaluator<>( - runner, application, counters, outputBundles.values(), stepContext); + return ParDoInProcessEvaluator.create( + evaluationContext, + inputBundle, + application, + fn, + application.getTransform().getSideInputs(), + application.getTransform().getMainOutputTag(), + application.getTransform().getSideOutputTags().getAll(), + outputs); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java index af5914bab0..4d46fd1c1b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java @@ -15,18 +15,13 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.collect.ImmutableMap; import java.util.Collections; @@ -40,7 +35,10 @@ public TransformEvaluator forApplication( final AppliedPTransform application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - return createSingleEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); + @SuppressWarnings({"unchecked", "rawtypes"}) + TransformEvaluator evaluator = + createSingleEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); + return evaluator; } private static ParDoInProcessEvaluator createSingleEvaluator( @@ -48,37 +46,15 @@ private static ParDoInProcessEvaluator createSingleEva Bound> application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { TupleTag mainOutputTag = new TupleTag<>("out"); - UncommittedBundle outputBundle = - evaluationContext.createBundle(inputBundle, application.getOutput()); - InProcessExecutionContext executionContext = - evaluationContext.getExecutionContext(application, inputBundle.getKey()); - String stepName = evaluationContext.getStepName(application); - InProcessStepContext stepContext = - executionContext.getOrCreateStepContext(stepName, stepName, null); - - CounterSet counters = evaluationContext.createCounterSet(); - - DoFnRunner runner = - DoFnRunners.createDefault( - evaluationContext.getPipelineOptions(), - application.getTransform().getFn(), - evaluationContext.createSideInputReader(application.getTransform().getSideInputs()), - BundleOutputManager.create( - Collections., UncommittedBundle>singletonMap( - mainOutputTag, outputBundle)), - mainOutputTag, - Collections.>emptyList(), - stepContext, - counters.getAddCounterMutator(), - application.getInput().getWindowingStrategy()); - - runner.startBundle(); - return new ParDoInProcessEvaluator( - runner, + return ParDoInProcessEvaluator.create( + evaluationContext, + inputBundle, application, - counters, - Collections.>singleton(outputBundle), - stepContext); + application.getTransform().getFn(), + application.getTransform().getSideInputs(), + mainOutputTag, + Collections.>emptyList(), + ImmutableMap., PCollection>of(mainOutputTag, application.getOutput())); } } From b0b94afe13a983da05b4758a0deab1bffd9ddfed Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 15 Apr 2016 10:23:15 -0700 Subject: [PATCH 322/751] Clone DoFns before constructing a DoFnRunner in the InProcessRunner This ensures that each thread gets an individual copy of a DoFn, so multiple threads do not interact. --- .../sdk/runners/inprocess/ParDoInProcessEvaluator.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index 9c6ec5821f..a7e25d5d63 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -23,6 +23,7 @@ import com.google.cloud.dataflow.sdk.util.DoFnRunner; import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; @@ -65,7 +66,7 @@ public static ParDoInProcessEvaluator create( DoFnRunner runner = DoFnRunners.createDefault( evaluationContext.getPipelineOptions(), - fn, + SerializableUtils.clone(fn), evaluationContext.createSideInputReader(sideInputs), BundleOutputManager.create(outputBundles), mainOutputTag, From ede3db4b4fa6686d1f430af5ba4df0e9432173bd Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Sat, 16 Apr 2016 12:19:01 -0700 Subject: [PATCH 323/751] [BEAM-50] BigQueryIO: move write validation to validate() from apply() If runners override the transform, validation will still happen. --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 56 +++++++++++-------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 8f291b99f9..eef58ab13b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -440,9 +440,6 @@ public Bound withoutResultFlattening() { return new Bound(name, query, table, validate, false); } - /** - * Validates the current {@link PTransform}. - */ @Override public void validate(PInput input) { if (table == null && query == null) { @@ -930,7 +927,7 @@ private static void verifyTableEmpty( } @Override - public PDone apply(PCollection input) { + public void validate(PCollection input) { BigQueryOptions options = input.getPipeline().getOptions().as(BigQueryOptions.class); TableReference table = getTable(); @@ -962,8 +959,8 @@ public PDone apply(PCollection input) { // Note that a presence check can fail if the table or dataset are created by earlier stages // of the pipeline. For these cases the withoutValidation method can be used to disable // the check. - // Unfortunately we can't validate anything early in case tableRefFunction is specified. - if (jsonTableRef != null && validate) { + // Unfortunately we can't validate anything early if tableRefFunction is specified. + if (table != null && validate) { verifyDatasetPresence(options, table); if (getCreateDisposition() == BigQueryIO.Write.CreateDisposition.CREATE_NEVER) { verifyTablePresence(options, table); @@ -973,9 +970,8 @@ public PDone apply(PCollection input) { } } - // In streaming, BigQuery write is taken care of by StreamWithDeDup transform. - // We also currently do this if a tablespec function is specified. if (options.isStreaming() || tableRefFunction != null) { + // We will use BigQuery's streaming write API -- validate support dispositions. if (createDisposition == CreateDisposition.CREATE_NEVER) { throw new IllegalArgumentException("CreateDispostion.CREATE_NEVER is not " + "supported for unbounded PCollections or when using tablespec functions."); @@ -985,29 +981,43 @@ public PDone apply(PCollection input) { throw new IllegalArgumentException("WriteDisposition.WRITE_TRUNCATE is not " + "supported for unbounded PCollections or when using tablespec functions."); } - - return input.apply(new StreamWithDeDup(table, tableRefFunction, getSchema())); + } else { + // We will use a BigQuery load job -- validate the temp location. + String tempLocation = options.getTempLocation(); + checkArgument( + !Strings.isNullOrEmpty(tempLocation), + "BigQueryIO.Write needs a GCS temp location to store temp files."); + if (testBigQueryServices == null) { + try { + GcsPath.fromUri(tempLocation); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + String.format( + "BigQuery temp location expected a valid 'gs://' path, but was given '%s'", + tempLocation), + e); + } + } } + } - String tempLocation = options.getTempLocation(); - checkArgument(!Strings.isNullOrEmpty(tempLocation), - "BigQueryIO.Write needs a GCS temp location to store temp files."); - if (testBigQueryServices == null) { - try { - GcsPath.fromUri(tempLocation); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(String.format( - "BigQuery temp location expected a valid 'gs://' path, but was given '%s'", - tempLocation), e); - } + @Override + public PDone apply(PCollection input) { + BigQueryOptions options = input.getPipeline().getOptions().as(BigQueryOptions.class); + + // In a streaming job, or when a tablespec function is defined, we use StreamWithDeDup + // and BigQuery's streaming import API. + if (options.isStreaming() || tableRefFunction != null) { + return input.apply(new StreamWithDeDup(getTable(), tableRefFunction, getSchema())); } + String jobIdToken = UUID.randomUUID().toString(); - String tempFilePrefix = tempLocation + "/BigQuerySinkTemp/" + jobIdToken; + String tempFilePrefix = options.getTempLocation() + "/BigQuerySinkTemp/" + jobIdToken; BigQueryServices bqServices = getBigQueryServices(); return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( new BigQuerySink( jobIdToken, - toJsonString(table), + jsonTableRef, jsonSchema, getWriteDisposition(), getCreateDisposition(), From dca985d397707c57d7af93a98c8fb4c877c9a5b7 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 18 Apr 2016 16:10:54 -0700 Subject: [PATCH 324/751] BigQueryIO: fix autocompleting project and test it This is a backport of apache/incubator-beam#205 --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 91 ++++++++++--------- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 40 +++++++- 2 files changed, 89 insertions(+), 42 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index eef58ab13b..39ac8e0857 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import com.google.api.client.json.JsonFactory; import com.google.api.services.bigquery.Bigquery; @@ -525,7 +526,7 @@ public void evaluate( } /** - * Returns the table to write, or {@code null} if reading from a query instead. + * Returns the table to read, or {@code null} if reading from a query instead. */ public TableReference getTable() { return table; @@ -930,37 +931,34 @@ private static void verifyTableEmpty( public void validate(PCollection input) { BigQueryOptions options = input.getPipeline().getOptions().as(BigQueryOptions.class); - TableReference table = getTable(); - if (table == null && tableRefFunction == null) { - throw new IllegalStateException( - "must set the table reference of a BigQueryIO.Write transform"); - } - if (table != null && tableRefFunction != null) { - throw new IllegalStateException( - "Cannot set both a table reference and a table function for a BigQueryIO.Write " - + "transform"); - } + // Exactly one of the table and table reference can be configured. + checkState( + jsonTableRef != null || tableRefFunction != null, + "must set the table reference of a BigQueryIO.Write transform"); + checkState( + jsonTableRef == null || tableRefFunction == null, + "Cannot set both a table reference and a table function for a BigQueryIO.Write" + + " transform"); - if (createDisposition == CreateDisposition.CREATE_IF_NEEDED && jsonSchema == null) { - throw new IllegalArgumentException("CreateDisposition is CREATE_IF_NEEDED, " - + "however no schema was provided."); - } + // Require a schema if creating one or more tables. + checkArgument( + createDisposition != CreateDisposition.CREATE_IF_NEEDED || jsonSchema != null, + "CreateDisposition is CREATE_IF_NEEDED, however no schema was provided."); + + // The user specified a table. + if (jsonTableRef != null && validate) { + TableReference table = getTable(); - if (table != null && table.getProjectId() == null) { // If user does not specify a project we assume the table to be located in the project - // that owns the Dataflow job. - String projectIdFromOptions = options.getProject(); - LOG.warn(String.format(BigQueryIO.SET_PROJECT_FROM_OPTIONS_WARNING, table.getDatasetId(), - table.getTableId(), projectIdFromOptions)); - table.setProjectId(projectIdFromOptions); - } + // configured in BigQueryOptions. + if (Strings.isNullOrEmpty(table.getProjectId())) { + table.setProjectId(options.getProject()); + } - // Check for destination table presence and emptiness for early failure notification. - // Note that a presence check can fail if the table or dataset are created by earlier stages - // of the pipeline. For these cases the withoutValidation method can be used to disable - // the check. - // Unfortunately we can't validate anything early if tableRefFunction is specified. - if (table != null && validate) { + // Check for destination table presence and emptiness for early failure notification. + // Note that a presence check can fail when the table or dataset is created by an earlier + // stage of the pipeline. For these cases the #withoutValidation method can be used to + // disable the check. verifyDatasetPresence(options, table); if (getCreateDisposition() == BigQueryIO.Write.CreateDisposition.CREATE_NEVER) { verifyTablePresence(options, table); @@ -971,16 +969,16 @@ public void validate(PCollection input) { } if (options.isStreaming() || tableRefFunction != null) { - // We will use BigQuery's streaming write API -- validate support dispositions. - if (createDisposition == CreateDisposition.CREATE_NEVER) { - throw new IllegalArgumentException("CreateDispostion.CREATE_NEVER is not " - + "supported for unbounded PCollections or when using tablespec functions."); - } + // We will use BigQuery's streaming write API -- validate supported dispositions. + checkArgument( + createDisposition != CreateDisposition.CREATE_NEVER, + "CreateDisposition.CREATE_NEVER is not supported for an unbounded PCollection or when" + + " using a tablespec function."); - if (writeDisposition == WriteDisposition.WRITE_TRUNCATE) { - throw new IllegalArgumentException("WriteDisposition.WRITE_TRUNCATE is not " - + "supported for unbounded PCollections or when using tablespec functions."); - } + checkArgument( + writeDisposition != WriteDisposition.WRITE_TRUNCATE, + "WriteDisposition.WRITE_TRUNCATE is not supported for an unbounded PCollection or" + + " when using a tablespec function."); } else { // We will use a BigQuery load job -- validate the temp location. String tempLocation = options.getTempLocation(); @@ -1011,13 +1009,17 @@ public PDone apply(PCollection input) { return input.apply(new StreamWithDeDup(getTable(), tableRefFunction, getSchema())); } + TableReference table = fromJsonString(jsonTableRef, TableReference.class); + if (Strings.isNullOrEmpty(table.getProjectId())) { + table.setProjectId(options.getProject()); + } String jobIdToken = UUID.randomUUID().toString(); String tempFilePrefix = options.getTempLocation() + "/BigQuerySinkTemp/" + jobIdToken; BigQueryServices bqServices = getBigQueryServices(); return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( new BigQuerySink( jobIdToken, - jsonTableRef, + table, jsonSchema, getWriteDisposition(), getCreateDisposition(), @@ -1046,7 +1048,8 @@ public TableSchema getSchema() { return fromJsonString(jsonSchema, TableSchema.class); } - /** Returns the table reference, or {@code null} if a . */ + /** Returns the table reference, or {@code null}. */ + @Nullable public TableReference getTable() { return fromJsonString(jsonTableRef, TableReference.class); } @@ -1085,7 +1088,7 @@ static class BigQuerySink extends FileBasedSink { public BigQuerySink( String jobIdToken, - @Nullable String jsonTable, + @Nullable TableReference table, @Nullable String jsonSchema, WriteDisposition writeDisposition, CreateDisposition createDisposition, @@ -1094,7 +1097,13 @@ public BigQuerySink( BigQueryServices bqServices) { super(tempFile, ".json"); this.jobIdToken = checkNotNull(jobIdToken, "jobIdToken"); - this.jsonTable = jsonTable; + if (table == null) { + this.jsonTable = null; + } else { + checkArgument(!Strings.isNullOrEmpty(table.getProjectId()), + "Table %s should have a project specified", table); + this.jsonTable = toJsonString(table); + } this.jsonSchema = jsonSchema; this.writeDisposition = checkNotNull(writeDisposition, "writeDisposition"); this.createDisposition = checkNotNull(createDisposition, "createDisposition"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 5f70df3f5b..7a7a1e5967 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -36,6 +36,8 @@ import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BigQueryServices; import com.google.cloud.dataflow.sdk.util.BigQueryServices.Status; import com.google.cloud.dataflow.sdk.util.CoderUtils; @@ -338,7 +340,7 @@ public void testCustomSink() throws Exception { new TableRow().set("name", "b").set("number", 2), new TableRow().set("name", "c").set("number", 3))) .setCoder(TableRowJsonCoder.of()) - .apply(BigQueryIO.Write.to("project-id:dataset-id.table-id") + .apply(BigQueryIO.Write.to("dataset-id.table-id") .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withSchema(new TableSchema().setFields( ImmutableList.of( @@ -604,4 +606,40 @@ public void testBigQueryIOGetName() { assertEquals("ReadMyTable", BigQueryIO.Read.named("ReadMyTable").getName()); assertEquals("WriteMyTable", BigQueryIO.Write.named("WriteMyTable").getName()); } + + @Test + public void testWriteValidateFailsCreateNoSchema() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("no schema was provided"); + TestPipeline.create() + .apply(Create.of()) + .apply(BigQueryIO.Write + .to("dataset.table") + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)); + } + + @Test + public void testWriteValidateFailsTableAndTableSpec() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("Cannot set both a table reference and a table function"); + TestPipeline.create() + .apply(Create.of()) + .apply(BigQueryIO.Write + .to("dataset.table") + .to(new SerializableFunction() { + @Override + public String apply(BoundedWindow input) { + return null; + } + })); + } + + @Test + public void testWriteValidateFailsNoTableAndNoTableSpec() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("must set the table reference of a BigQueryIO.Write transform"); + TestPipeline.create() + .apply(Create.of()) + .apply(BigQueryIO.Write.named("name")); + } } From c901add996f5b8770b99cff9942bab5fce683400 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 18 Apr 2016 12:55:26 -0700 Subject: [PATCH 325/751] Remove InProcessBundle InProcessBundle is an implementation detail of InProcessBundleFactory, which it should be contained within. --- .../runners/inprocess/InProcessBundle.java | 121 --------------- .../EncodabilityEnforcementFactoryTest.java | 11 +- .../ImmutabilityEnforcementFactoryTest.java | 8 +- .../InMemoryWatermarkManagerTest.java | 2 +- .../inprocess/InProcessBundleTest.java | 143 ------------------ .../InProcessEvaluationContextTest.java | 26 +--- .../inprocess/TransformExecutorTest.java | 6 +- 7 files changed, 23 insertions(+), 294 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java deleted file mode 100644 index 112ba17d14..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundle.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; - -import javax.annotation.Nullable; - -/** - * A {@link UncommittedBundle} that buffers elements in memory. - */ -public final class InProcessBundle implements UncommittedBundle { - private final PCollection pcollection; - private final boolean keyed; - private final Object key; - private boolean committed = false; - private ImmutableList.Builder> elements; - - /** - * Create a new {@link InProcessBundle} for the specified {@link PCollection} without a key. - */ - public static InProcessBundle unkeyed(PCollection pcollection) { - return new InProcessBundle(pcollection, false, null); - } - - /** - * Create a new {@link InProcessBundle} for the specified {@link PCollection} with the specified - * key. - * - * See {@link CommittedBundle#getKey()} and {@link CommittedBundle#isKeyed()} for more - * information. - */ - public static InProcessBundle keyed(PCollection pcollection, Object key) { - return new InProcessBundle(pcollection, true, key); - } - - private InProcessBundle(PCollection pcollection, boolean keyed, Object key) { - this.pcollection = pcollection; - this.keyed = keyed; - this.key = key; - this.elements = ImmutableList.builder(); - } - - @Override - public PCollection getPCollection() { - return pcollection; - } - - @Override - public InProcessBundle add(WindowedValue element) { - checkState(!committed, "Can't add element %s to committed bundle %s", element, this); - elements.add(element); - return this; - } - - @Override - public CommittedBundle commit(final Instant synchronizedCompletionTime) { - checkState(!committed, "Can't commit already committed bundle %s", this); - committed = true; - final Iterable> committedElements = elements.build(); - return new CommittedBundle() { - @Override - @Nullable - public Object getKey() { - return key; - } - - @Override - public boolean isKeyed() { - return keyed; - } - - @Override - public Iterable> getElements() { - return committedElements; - } - - @Override - public PCollection getPCollection() { - return pcollection; - } - - @Override - public Instant getSynchronizedProcessingOutputWatermark() { - return synchronizedCompletionTime; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .omitNullValues() - .add("pcollection", pcollection) - .add("key", key) - .add("elements", committedElements) - .toString(); - } - }; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java index 73c103ac90..559fc20285 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java @@ -48,6 +48,7 @@ public class EncodabilityEnforcementFactoryTest { @Rule public ExpectedException thrown = ExpectedException.none(); private EncodabilityEnforcementFactory factory = EncodabilityEnforcementFactory.create(); + private BundleFactory bundleFactory = InProcessBundleFactory.create(); @Test public void encodeFailsThrows() { @@ -59,7 +60,7 @@ public void encodeFailsThrows() { WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); CommittedBundle input = - InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(input, consumer); thrown.expect(UserCodeException.class); @@ -78,7 +79,7 @@ public void decodeFailsThrows() { WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); CommittedBundle input = - InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(input, consumer); thrown.expect(UserCodeException.class); @@ -105,7 +106,7 @@ public String toString() { }); CommittedBundle input = - InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(input, consumer); thrown.expect(UserCodeException.class); @@ -129,7 +130,7 @@ public void notConsistentWithEqualsStructuralValueNotEqualSucceeds() { WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); CommittedBundle input = - InProcessBundle.unkeyed(unencodable).add(record).commit(Instant.now()); + bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(input, consumer); enforcement.beforeElement(record); @@ -150,7 +151,7 @@ public void structurallyEqualResultsSucceeds() { WindowedValue value = WindowedValue.valueInGlobalWindow(1); CommittedBundle input = - InProcessBundle.unkeyed(unencodable).add(value).commit(Instant.now()); + bundleFactory.createRootBundle(unencodable).add(value).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(input, consumer); enforcement.beforeElement(value); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java index 0b5de689ec..ced1354f61 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java @@ -44,12 +44,14 @@ public class ImmutabilityEnforcementFactoryTest implements Serializable { @Rule public transient ExpectedException thrown = ExpectedException.none(); private transient ImmutabilityEnforcementFactory factory; + private transient BundleFactory bundleFactory; private transient PCollection pcollection; private transient AppliedPTransform consumer; @Before public void setup() { factory = new ImmutabilityEnforcementFactory(); + bundleFactory = InProcessBundleFactory.create(); TestPipeline p = TestPipeline.create(); pcollection = p.apply(Create.of("foo".getBytes(), "spamhameggs".getBytes())) @@ -69,7 +71,7 @@ public void processElement(DoFn.ProcessContext c) public void unchangedSucceeds() { WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); CommittedBundle elements = - InProcessBundle.unkeyed(pcollection).add(element).commit(Instant.now()); + bundleFactory.createRootBundle(pcollection).add(element).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(elements, consumer); enforcement.beforeElement(element); @@ -84,7 +86,7 @@ public void unchangedSucceeds() { public void mutatedDuringProcessElementThrows() { WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); CommittedBundle elements = - InProcessBundle.unkeyed(pcollection).add(element).commit(Instant.now()); + bundleFactory.createRootBundle(pcollection).add(element).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(elements, consumer); enforcement.beforeElement(element); @@ -105,7 +107,7 @@ public void mutatedAfterProcessElementFails() { WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); CommittedBundle elements = - InProcessBundle.unkeyed(pcollection).add(element).commit(Instant.now()); + bundleFactory.createRootBundle(pcollection).add(element).commit(Instant.now()); ModelEnforcement enforcement = factory.forBundle(elements, consumer); enforcement.beforeElement(element); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index 455fcca120..995a380c0c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -795,7 +795,7 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { Instant upstreamHold = new Instant(2048L); CommittedBundle filteredBundle = - bundleFactory.createKeyedBundle(null, "key", filtered).commit(upstreamHold); + bundleFactory.createKeyedBundle(created, "key", filtered).commit(upstreamHold); manager.updateWatermarks( created, filtered.getProducingTransformInternal(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleTest.java deleted file mode 100644 index dcba86bc25..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; - -/** - * Tests for {@link InProcessBundle}. - */ -@RunWith(JUnit4.class) -public class InProcessBundleTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void unkeyedShouldCreateWithNullKey() { - PCollection pcollection = TestPipeline.create().apply(Create.of(1)); - - InProcessBundle inFlightBundle = InProcessBundle.unkeyed(pcollection); - - CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - - assertThat(bundle.isKeyed(), is(false)); - assertThat(bundle.getKey(), nullValue()); - } - - private void keyedCreateBundle(Object key) { - PCollection pcollection = TestPipeline.create().apply(Create.of(1)); - - InProcessBundle inFlightBundle = InProcessBundle.keyed(pcollection, key); - - CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - assertThat(bundle.isKeyed(), is(true)); - assertThat(bundle.getKey(), equalTo(key)); - } - - @Test - public void keyedWithNullKeyShouldCreateKeyedBundle() { - keyedCreateBundle(null); - } - - @Test - public void keyedWithKeyShouldCreateKeyedBundle() { - keyedCreateBundle(new Object()); - } - - private void afterCommitGetElementsShouldHaveAddedElements(Iterable> elems) { - PCollection pcollection = TestPipeline.create().apply(Create.of()); - - InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); - Collection>> expectations = new ArrayList<>(); - for (WindowedValue elem : elems) { - bundle.add(elem); - expectations.add(equalTo(elem)); - } - Matcher>> containsMatcher = - Matchers.>containsInAnyOrder(expectations); - assertThat(bundle.commit(Instant.now()).getElements(), containsMatcher); - } - - @Test - public void getElementsBeforeAddShouldReturnEmptyIterable() { - afterCommitGetElementsShouldHaveAddedElements(Collections.>emptyList()); - } - - @Test - public void getElementsAfterAddShouldReturnAddedElements() { - WindowedValue firstValue = WindowedValue.valueInGlobalWindow(1); - WindowedValue secondValue = - WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1000L)); - - afterCommitGetElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); - } - - @Test - public void addAfterCommitShouldThrowException() { - PCollection pcollection = TestPipeline.create().apply(Create.of()); - - InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); - bundle.add(WindowedValue.valueInGlobalWindow(1)); - CommittedBundle firstCommit = bundle.commit(Instant.now()); - assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("3"); - thrown.expectMessage("committed"); - - bundle.add(WindowedValue.valueInGlobalWindow(3)); - } - - @Test - public void commitAfterCommitShouldThrowException() { - PCollection pcollection = TestPipeline.create().apply(Create.of()); - - InProcessBundle bundle = InProcessBundle.unkeyed(pcollection); - bundle.add(WindowedValue.valueInGlobalWindow(1)); - CommittedBundle firstCommit = bundle.commit(Instant.now()); - assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("committed"); - - bundle.commit(Instant.now()); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index 6268b4b771..d225519a79 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -90,6 +90,8 @@ public class InProcessEvaluationContextTest { private Collection> rootTransforms; private Map>> valueToConsumers; + private BundleFactory bundleFactory; + @Before public void setup() { InProcessPipelineRunner runner = @@ -107,6 +109,8 @@ public void setup() { rootTransforms = cVis.getRootTransforms(); valueToConsumers = cVis.getValueToConsumers(); + bundleFactory = InProcessBundleFactory.create(); + context = InProcessEvaluationContext.create( runner.getPipelineOptions(), @@ -389,38 +393,24 @@ public void extractFiredTimersExtractsTimers() { assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); } - @Test - public void createBundleUnkeyedResultUnkeyed() { - CommittedBundle> newBundle = - context - .createBundle(InProcessBundle.unkeyed(created).commit(Instant.now()), downstream) - .commit(Instant.now()); - assertThat(newBundle.isKeyed(), is(false)); - } - @Test public void createBundleKeyedResultPropagatesKey() { CommittedBundle> newBundle = context - .createBundle(InProcessBundle.keyed(created, "foo").commit(Instant.now()), downstream) + .createBundle( + bundleFactory.createKeyedBundle(null, "foo", created).commit(Instant.now()), + downstream) .commit(Instant.now()); - assertThat(newBundle.isKeyed(), is(true)); assertThat(newBundle.getKey(), Matchers.equalTo("foo")); } - @Test - public void createRootBundleUnkeyed() { - assertThat(context.createRootBundle(created).commit(Instant.now()).isKeyed(), is(false)); - } - @Test public void createKeyedBundleKeyed() { CommittedBundle> keyedBundle = context .createKeyedBundle( - InProcessBundle.unkeyed(created).commit(Instant.now()), "foo", downstream) + bundleFactory.createRootBundle(created).commit(Instant.now()), "foo", downstream) .commit(Instant.now()); - assertThat(keyedBundle.isKeyed(), is(true)); assertThat(keyedBundle.getKey(), Matchers.equalTo("foo")); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index bbf7c51757..de7c60bcce 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -329,7 +329,7 @@ public InProcessTransformResult finishBundle() throws Exception { WindowedValue fooElem = WindowedValue.valueInGlobalWindow("foo"); WindowedValue barElem = WindowedValue.valueInGlobalWindow("bar"); CommittedBundle inputBundle = - InProcessBundle.unkeyed(created).add(fooElem).add(barElem).commit(Instant.now()); + bundleFactory.createRootBundle(created).add(fooElem).add(barElem).commit(Instant.now()); when( registry.forApplication( downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) @@ -390,7 +390,7 @@ public InProcessTransformResult finishBundle() throws Exception { WindowedValue fooBytes = WindowedValue.valueInGlobalWindow("foo".getBytes()); CommittedBundle inputBundle = - InProcessBundle.unkeyed(pcBytes).add(fooBytes).commit(Instant.now()); + bundleFactory.createRootBundle(pcBytes).add(fooBytes).commit(Instant.now()); when( registry.forApplication( pcBytes.getProducingTransformInternal(), inputBundle, evaluationContext)) @@ -449,7 +449,7 @@ public InProcessTransformResult finishBundle() throws Exception { WindowedValue fooBytes = WindowedValue.valueInGlobalWindow("foo".getBytes()); CommittedBundle inputBundle = - InProcessBundle.unkeyed(pcBytes).add(fooBytes).commit(Instant.now()); + bundleFactory.createRootBundle(pcBytes).add(fooBytes).commit(Instant.now()); when( registry.forApplication( pcBytes.getProducingTransformInternal(), inputBundle, evaluationContext)) From 1f75fa961990529a4fc2eb2afdffa04b8367d25e Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 18 Apr 2016 16:55:57 -0700 Subject: [PATCH 326/751] Add WindowedValue#explodeWindows This takes an existing WindowedValue and returns a Collection of WindowedValues, each of which is in exactly one window. Use the explode implementation on DoFnRunnerBase --- .../dataflow/sdk/util/DoFnRunnerBase.java | 5 +- .../dataflow/sdk/util/WindowedValue.java | 13 +++++ .../dataflow/sdk/util/WindowedValueTest.java | 52 +++++++++++++++++++ 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index 04ec59f57d..37aacb0688 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -139,9 +139,8 @@ public void processElement(WindowedValue elem) { } else { // We could modify the windowed value (and the processContext) to // avoid repeated allocations, but this is more straightforward. - for (BoundedWindow window : elem.getWindows()) { - invokeProcessElement(WindowedValue.of( - elem.getValue(), elem.getTimestamp(), window, elem.getPane())); + for (WindowedValue windowedValue : elem.explodeWindows()) { + invokeProcessElement(windowedValue); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java index 1e944e2513..aaa580353c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java @@ -32,6 +32,7 @@ import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -171,6 +172,18 @@ public T getValue() { */ public abstract Collection getWindows(); + /** + * Returns a collection of {@link WindowedValue WindowedValues} identical to this one, except each + * is in exactly one of the windows that this {@link WindowedValue} is in. + */ + public Iterable> explodeWindows() { + ImmutableList.Builder> windowedValues = ImmutableList.builder(); + for (BoundedWindow w : getWindows()) { + windowedValues.add(of(getValue(), getTimestamp(), w, getPane())); + } + return windowedValues.build(); + } + /** * Returns the pane of this {@code WindowedValue} in its window. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java index 01b31ad6e6..b1f89907d5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java @@ -16,11 +16,20 @@ package com.google.cloud.dataflow.sdk.util; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import org.joda.time.Instant; import org.junit.Assert; @@ -54,4 +63,47 @@ public void testWindowedValueCoder() throws CoderException { Assert.assertEquals(value.getTimestamp(), decodedValue.getTimestamp()); Assert.assertArrayEquals(value.getWindows().toArray(), decodedValue.getWindows().toArray()); } + + @Test + public void testExplodeWindowsInNoWindowsEmptyIterable() { + WindowedValue value = + WindowedValue.of( + "foo", Instant.now(), ImmutableList.of(), PaneInfo.NO_FIRING); + + assertThat(value.explodeWindows(), emptyIterable()); + } + + @Test + public void testExplodeWindowsInOneWindowEquals() { + Instant now = Instant.now(); + BoundedWindow window = new IntervalWindow(now.minus(1000L), now.plus(1000L)); + WindowedValue value = + WindowedValue.of("foo", now, window, PaneInfo.ON_TIME_AND_ONLY_FIRING); + + assertThat(Iterables.getOnlyElement(value.explodeWindows()), equalTo(value)); + } + + @Test + public void testExplodeWindowsManyWindowsMultipleWindowedValues() { + Instant now = Instant.now(); + BoundedWindow centerWindow = new IntervalWindow(now.minus(1000L), now.plus(1000L)); + BoundedWindow pastWindow = new IntervalWindow(now.minus(1500L), now.plus(500L)); + BoundedWindow futureWindow = new IntervalWindow(now.minus(500L), now.plus(1500L)); + BoundedWindow futureFutureWindow = new IntervalWindow(now, now.plus(2000L)); + PaneInfo pane = PaneInfo.createPane(false, false, Timing.ON_TIME, 3L, 0L); + WindowedValue value = + WindowedValue.of( + "foo", + now, + ImmutableList.of(pastWindow, centerWindow, futureWindow, futureFutureWindow), + pane); + + assertThat( + value.explodeWindows(), + containsInAnyOrder( + WindowedValue.of("foo", now, futureFutureWindow, pane), + WindowedValue.of("foo", now, futureWindow, pane), + WindowedValue.of("foo", now, centerWindow, pane), + WindowedValue.of("foo", now, pastWindow, pane))); + } } From ac137098c1cf66747bf2edadad1feecea8699f31 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Thu, 21 Apr 2016 13:13:12 -0700 Subject: [PATCH 327/751] Backport https://github.com/apache/incubator-beam/pull/221/files --- .../google/cloud/dataflow/sdk/util/UserCodeException.java | 6 +++++- .../cloud/dataflow/sdk/util/UserCodeExceptionTest.java | 8 +++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java index 9b9c7a5919..12ae1059b2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java @@ -61,13 +61,17 @@ private UserCodeException(Throwable t) { * of the current thread. */ private void truncateStackTrace(Throwable t) { - StackTraceElement[] currentStack = Thread.currentThread().getStackTrace(); StackTraceElement[] throwableStack = t.getStackTrace(); int currentStackSize = currentStack.length; int throwableStackSize = throwableStack.length; + if (throwableStackSize == 0) { + // Nothing to truncate. + return; + } + int commonFrames = 0; while (framesEqual(currentStack[currentStackSize - commonFrames - 1], throwableStack[throwableStackSize - commonFrames - 1])) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java index 7982a99efe..8bb3ee7ae4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java @@ -96,6 +96,13 @@ public void testWrapIfReturnsSourceRuntimeExceptionWhenFalse() { assertEquals(runtimeException, wrapped); } + @Test + public void robustAgainstEmptyStackTrace() { + RuntimeException runtimeException = new RuntimeException("empty stack"); + runtimeException.setStackTrace(new StackTraceElement[0]); + RuntimeException wrapped = UserCodeException.wrap(runtimeException); + assertEquals(runtimeException, wrapped.getCause()); + } private void throwUserCodeException() { try { @@ -173,4 +180,3 @@ protected boolean matchesSafely(StackTraceElement item) { } } } - From 5ab67a2c1cac9323d7a60603dbc567b1f5e0421a Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 21 Apr 2016 10:51:20 -0700 Subject: [PATCH 328/751] Wrap Exceptions thrown in StartBundle in the InProcessPipelineRunner --- .../sdk/runners/inprocess/ParDoInProcessEvaluator.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index a7e25d5d63..38f62fdce5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -75,7 +75,11 @@ public static ParDoInProcessEvaluator create( counters.getAddCounterMutator(), application.getInput().getWindowingStrategy()); - runner.startBundle(); + try { + runner.startBundle(); + } catch (Exception e) { + throw UserCodeException.wrap(e); + } return new ParDoInProcessEvaluator<>( runner, application, counters, outputBundles.values(), stepContext); From 53f99f4c3cb8c78e0aa705657b2d0e8d15398aa8 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 18 Apr 2016 17:28:47 -0700 Subject: [PATCH 329/751] Track pending elements via exploded WindowedValues This allows the WindowedValues to be partially completed while the still holding the watermark. --- .../inprocess/InMemoryWatermarkManager.java | 31 +++++-- .../InMemoryWatermarkManagerTest.java | 91 ++++++++++++++----- 2 files changed, 89 insertions(+), 33 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index c4d67db121..6f68b7e42f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -27,9 +27,11 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PValue; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ComparisonChain; +import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -206,7 +208,7 @@ private static class AppliedPTransformInputWatermark implements Watermark { public AppliedPTransformInputWatermark(Collection inputWatermarks) { this.inputWatermarks = inputWatermarks; - this.pendingElements = TreeMultiset.create(PENDING_ELEMENT_COMPARATOR); + this.pendingElements = TreeMultiset.create(new WindowedValueByTimestampComparator()); this.objectTimers = new HashMap<>(); currentWatermark = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); } @@ -620,12 +622,17 @@ public Instant get() { private static final Ordering INSTANT_ORDERING = Ordering.natural(); /** - * An ordering that compares windowed values by timestamp, then arbitrarily. This ensures that - * {@link WindowedValue WindowedValues} will be sorted by timestamp, while two different - * {@link WindowedValue WindowedValues} with the same timestamp are not considered equal. + * A function that takes a WindowedValue and returns the exploded representation of that + * {@link WindowedValue}. */ - private static final Ordering> PENDING_ELEMENT_COMPARATOR = - (new WindowedValueByTimestampComparator()).compound(Ordering.arbitrary()); + private static final Function, ? extends Iterable>> + EXPLODE_WINDOWS_FN = + new Function, Iterable>>() { + @Override + public Iterable> apply(WindowedValue input) { + return input.explodeWindows(); + } + }; /** * For each (Object, PriorityQueue) pair in the provided map, remove each Timer that is before the @@ -1044,15 +1051,19 @@ private void setEventTimeHold(Object key, Instant newHold) { } private void removePending(CommittedBundle bundle) { - inputWatermark.removePendingElements(bundle.getElements()); + inputWatermark.removePendingElements(elementsFromBundle(bundle)); synchronizedProcessingInputWatermark.removePending(bundle); } private void addPending(CommittedBundle bundle) { - inputWatermark.addPendingElements(bundle.getElements()); + inputWatermark.addPendingElements(elementsFromBundle(bundle)); synchronizedProcessingInputWatermark.addPending(bundle); } + private Iterable> elementsFromBundle(CommittedBundle bundle) { + return FluentIterable.from(bundle.getElements()).transformAndConcat(EXPLODE_WINDOWS_FN); + } + private Map extractFiredTimers() { Map> eventTimeTimers = inputWatermark.extractFiredEventTimeTimers(); Map> processingTimers; @@ -1294,7 +1305,9 @@ public String toString() { private static class WindowedValueByTimestampComparator extends Ordering> { @Override public int compare(WindowedValue o1, WindowedValue o2) { - return o1.getTimestamp().compareTo(o2.getTimestamp()); + return ComparisonChain.start() + .compare(o1.getTimestamp(), o2.getTimestamp()) + .result(); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index 995a380c0c..0603a5a386 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -38,6 +38,9 @@ import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.TimeDomain; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -152,7 +155,7 @@ public void getWatermarkForUntouchedTransform() { */ @Test public void getWatermarkForUpdatedSourceTransform() { - CommittedBundle output = globallyWindowedBundle(createdInts, 1); + CommittedBundle output = multiWindowedBundle(createdInts, 1); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(output), new Instant(8000L)); TransformWatermarks updatedSourceWatermark = @@ -167,7 +170,7 @@ public void getWatermarkForUpdatedSourceTransform() { */ @Test public void getWatermarkForMultiInputTransform() { - CommittedBundle secondPcollectionBundle = globallyWindowedBundle(intsToFlatten, -1); + CommittedBundle secondPcollectionBundle = multiWindowedBundle(intsToFlatten, -1); manager.updateWatermarks(null, intsToFlatten.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(secondPcollectionBundle), @@ -196,7 +199,7 @@ public void getWatermarkForMultiInputTransform() { assertThat( transformWatermark.getOutputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - CommittedBundle flattenedBundleSecondCreate = globallyWindowedBundle(flattened, -1); + CommittedBundle flattenedBundleSecondCreate = multiWindowedBundle(flattened, -1); // We have finished processing the bundle from the second PCollection, but we haven't consumed // anything from the first PCollection yet; so our watermark shouldn't advance manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), @@ -494,13 +497,39 @@ public void updateWatermarkWithLateData() { TimerUpdate.empty(), Collections.>singleton(lateKeyedBundle), null); } + public void updateWatermarkWithDifferentWindowedValueInstances() { + manager.updateWatermarks( + null, + createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>singleton( + bundleFactory + .createRootBundle(createdInts) + .add(WindowedValue.valueInGlobalWindow(1)) + .commit(Instant.now())), + BoundedWindow.TIMESTAMP_MAX_VALUE); + + manager.updateWatermarks( + bundleFactory + .createRootBundle(createdInts) + .add(WindowedValue.valueInGlobalWindow(1)) + .commit(Instant.now()), + keyed.getProducingTransformInternal(), + TimerUpdate.empty(), + Collections.>emptyList(), + null); + TransformWatermarks onTimeWatermarks = + manager.getWatermarks(keyed.getProducingTransformInternal()); + assertThat(onTimeWatermarks.getInputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + } + /** * Demonstrates that after watermarks of an upstream transform are updated, but no output has been * produced, the watermarks of a downstream process are advanced. */ @Test public void getWatermarksAfterOnlyEmptyOutput() { - CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); + CommittedBundle emptyCreateOutput = multiWindowedBundle(createdInts); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -527,11 +556,11 @@ public void getWatermarksAfterOnlyEmptyOutput() { */ @Test public void getWatermarksAfterHoldAndEmptyOutput() { - CommittedBundle firstCreateOutput = globallyWindowedBundle(createdInts, 1, 2); + CommittedBundle firstCreateOutput = multiWindowedBundle(createdInts, 1, 2); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(firstCreateOutput), new Instant(12_000L)); - CommittedBundle firstFilterOutput = globallyWindowedBundle(filtered); + CommittedBundle firstFilterOutput = multiWindowedBundle(filtered); manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(firstFilterOutput), new Instant(10_000L)); @@ -540,7 +569,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { assertThat(firstFilterWatermarks.getInputWatermark(), not(earlierThan(new Instant(12_000L)))); assertThat(firstFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); - CommittedBundle emptyCreateOutput = globallyWindowedBundle(createdInts); + CommittedBundle emptyCreateOutput = multiWindowedBundle(createdInts); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(emptyCreateOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -628,7 +657,7 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { */ // @Test public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { - CommittedBundle createdBundle = globallyWindowedBundle(createdInts, 1, 2, 4, 8); + CommittedBundle createdBundle = multiWindowedBundle(createdInts, 1, 2, 4, 8); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(createdBundle), new Instant(1248L)); @@ -639,7 +668,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { Instant initialFilteredWm = filteredWms.getSynchronizedProcessingOutputTime(); Instant initialFilteredDoubledWm = filteredDoubledWms.getSynchronizedProcessingOutputTime(); - CommittedBundle filteredBundle = globallyWindowedBundle(filtered, 2, 8); + CommittedBundle filteredBundle = multiWindowedBundle(filtered, 2, 8); TimerData pastTimer = TimerData.of(StateNamespaces.global(), new Instant(250L), TimeDomain.PROCESSING_TIME); TimerData futureTimer = @@ -748,11 +777,11 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { @Test public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers() { - CommittedBundle created = globallyWindowedBundle(createdInts, 1, 2, 3); + CommittedBundle created = multiWindowedBundle(createdInts, 1, 2, 3); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.>singleton(created), new Instant(40_900L)); - CommittedBundle filteredBundle = globallyWindowedBundle(filtered, 2, 4); + CommittedBundle filteredBundle = multiWindowedBundle(filtered, 2, 4); Instant upstreamHold = new Instant(2048L); TimerData upstreamProcessingTimer = TimerData.of(StateNamespaces.global(), upstreamHold, TimeDomain.PROCESSING_TIME); @@ -773,7 +802,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( // synchronized processing time assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); - CommittedBundle otherCreated = globallyWindowedBundle(createdInts, 4, 8, 12); + CommittedBundle otherCreated = multiWindowedBundle(createdInts, 4, 8, 12); manager.updateWatermarks(otherCreated, filtered.getProducingTransformInternal(), TimerUpdate.builder("key") .withCompletedTimers(Collections.singleton(upstreamProcessingTimer)) @@ -785,7 +814,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( @Test public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { - CommittedBundle created = globallyWindowedBundle(createdInts, 1, 2, 3); + CommittedBundle created = multiWindowedBundle(createdInts, 1, 2, 3); manager.updateWatermarks( null, createdInts.getProducingTransformInternal(), @@ -819,7 +848,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { assertThat(initialTimers.entrySet(), emptyIterable()); // Advance WM of keyed past the first timer, but ahead of the second and third - CommittedBundle createdBundle = globallyWindowedBundle(filtered); + CommittedBundle createdBundle = multiWindowedBundle(filtered); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.singleton(createdBundle), new Instant(1500L)); @@ -837,8 +866,11 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { .setTimer(lastTimer) .build(); - manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), update, - Collections.>singleton(globallyWindowedBundle(intsToFlatten)), + manager.updateWatermarks( + createdBundle, + filtered.getProducingTransformInternal(), + update, + Collections.>singleton(multiWindowedBundle(intsToFlatten)), new Instant(1000L)); Map, Map> firstTransformFiredTimers = @@ -873,7 +905,7 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { assertThat(initialTimers.entrySet(), emptyIterable()); // Advance WM of keyed past the first timer, but ahead of the second and third - CommittedBundle createdBundle = globallyWindowedBundle(filtered); + CommittedBundle createdBundle = multiWindowedBundle(filtered); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.singleton(createdBundle), new Instant(1500L)); @@ -891,8 +923,11 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { .setTimer(middleTimer) .build(); - manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), update, - Collections.>singleton(globallyWindowedBundle(intsToFlatten)), + manager.updateWatermarks( + createdBundle, + filtered.getProducingTransformInternal(), + update, + Collections.>singleton(multiWindowedBundle(intsToFlatten)), new Instant(1000L)); Map, Map> firstTransformFiredTimers = @@ -928,7 +963,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { assertThat(initialTimers.entrySet(), emptyIterable()); // Advance WM of keyed past the first timer, but ahead of the second and third - CommittedBundle createdBundle = globallyWindowedBundle(filtered); + CommittedBundle createdBundle = multiWindowedBundle(filtered); manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), Collections.singleton(createdBundle), new Instant(1500L)); @@ -946,8 +981,11 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { .setTimer(middleTimer) .build(); - manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), update, - Collections.>singleton(globallyWindowedBundle(intsToFlatten)), + manager.updateWatermarks( + createdBundle, + filtered.getProducingTransformInternal(), + update, + Collections.>singleton(multiWindowedBundle(intsToFlatten)), new Instant(1000L)); Map, Map> firstTransformFiredTimers = @@ -1112,10 +1150,15 @@ private final CommittedBundle timestampedBundle( } @SafeVarargs - private final CommittedBundle globallyWindowedBundle(PCollection pc, T... values) { + private final CommittedBundle multiWindowedBundle(PCollection pc, T... values) { UncommittedBundle bundle = bundleFactory.createRootBundle(pc); + Collection windows = + ImmutableList.of( + GlobalWindow.INSTANCE, + new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(0))); for (T value : values) { - bundle.add(WindowedValue.valueInGlobalWindow(value)); + bundle.add( + WindowedValue.of(value, BoundedWindow.TIMESTAMP_MIN_VALUE, windows, PaneInfo.NO_FIRING)); } return bundle.commit(BoundedWindow.TIMESTAMP_MAX_VALUE); } From 9705a1c2424f4a91ec2d23a361f368f595926b80 Mon Sep 17 00:00:00 2001 From: Pei He Date: Fri, 15 Apr 2016 15:46:29 -0700 Subject: [PATCH 330/751] Fix BigQuery.Write tempFilePrefix concatenation --- .../google/cloud/dataflow/sdk/io/BigQueryIO.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 39ac8e0857..d7895ee021 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -56,6 +56,8 @@ import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl; import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; +import com.google.cloud.dataflow.sdk.util.IOChannelFactory; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.util.Reshuffle; @@ -1014,7 +1016,18 @@ public PDone apply(PCollection input) { table.setProjectId(options.getProject()); } String jobIdToken = UUID.randomUUID().toString(); - String tempFilePrefix = options.getTempLocation() + "/BigQuerySinkTemp/" + jobIdToken; + String tempLocation = options.getTempLocation(); + String tempFilePrefix; + try { + IOChannelFactory factory = IOChannelUtils.getFactory(tempLocation); + tempFilePrefix = factory.resolve( + factory.resolve(tempLocation, "BigQuerySinkTemp"), + jobIdToken); + } catch (IOException e) { + throw new RuntimeException( + String.format("Failed to resolve BigQuery temp location in %s", tempLocation), + e); + } BigQueryServices bqServices = getBigQueryServices(); return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( new BigQuerySink( From f4acfacac6fa557eb2c9d75f6bae88b351a30360 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 15 Apr 2016 10:05:36 -0700 Subject: [PATCH 331/751] Enforce JobName Preconditions in the Dataflow Runner This ensures that whenever a DataflowPipelineRunner is created, the jobName of the created options conforms to the requirements of the Dataflow Service. --- .../sdk/options/DataflowPipelineOptions.java | 7 ++-- .../sdk/runners/DataflowPipelineRunner.java | 18 +++++++++-- .../BlockingDataflowPipelineRunnerTest.java | 2 +- .../runners/DataflowPipelineRunnerTest.java | 32 +++++++++++++++---- .../sdk/runners/DataflowPipelineTest.java | 2 +- 5 files changed, 47 insertions(+), 14 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java index 5b73cac16e..9ff1338eb6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java @@ -65,8 +65,11 @@ public interface DataflowPipelineOptions extends * name will not be able to be created. Defaults to using the ApplicationName-UserName-Date. */ @Description("The Dataflow job name is used as an idempotence key within the Dataflow service. " - + "If there is an existing job that is currently active, another active job with the same " - + "name will not be able to be created. Defaults to using the ApplicationName-UserName-Date.") + + "For each running job in the same GCP project, jobs with the same name cannot be created " + + "unless the new job is an explicit update of the previous one. Defaults to using " + + "ApplicationName-UserName-Date. The job name must match the regular expression " + + "'[a-z]([-a-z0-9]{0,38}[a-z0-9])?'. The runner will automatically truncate the name of the " + + "job and convert to lower case.") @Default.InstanceFactory(JobNameFactory.class) String getJobName(); void setJobName(String value); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 0f0fc477dd..369794a0ab 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -288,13 +288,25 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { LOG.debug("Classpath elements: {}", dataflowOptions.getFilesToStage()); } - // Verify jobName according to service requirements. - String jobName = dataflowOptions.getJobName().toLowerCase(); - Preconditions.checkArgument( + // Verify jobName according to service requirements, truncating converting to lowercase if + // necessary. + String jobName = + dataflowOptions + .getJobName() + .toLowerCase(); + checkArgument( jobName.matches("[a-z]([-a-z0-9]*[a-z0-9])?"), "JobName invalid; the name must consist of only the characters " + "[-a-z0-9], starting with a letter and ending with a letter " + "or number"); + if (!jobName.equals(dataflowOptions.getJobName())) { + LOG.info( + "PipelineOptions.jobName did not match the service requirements. " + + "Using {} instead of {}.", + jobName, + dataflowOptions.getJobName()); + } + dataflowOptions.setJobName(jobName); // Verify project String project = dataflowOptions.getProject(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java index 5b1748c325..2578f0c5d2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java @@ -295,7 +295,7 @@ public void testToString() { options.setTempLocation("gs://test/temp/location"); options.setGcpCredential(new TestCredential()); options.setPathValidatorClass(NoopPathValidator.class); - assertEquals("BlockingDataflowPipelineRunner#TestJobName", + assertEquals("BlockingDataflowPipelineRunner#testjobname", BlockingDataflowPipelineRunner.fromOptions(options).toString()); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 05ee798162..584d48e407 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -19,6 +19,7 @@ import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; @@ -120,6 +121,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.regex.Pattern; /** * Tests for DataflowPipelineRunner. @@ -138,6 +140,7 @@ public class DataflowPipelineRunnerTest { private static void assertValidJob(Job job) { assertNull(job.getId()); assertNull(job.getCurrentState()); + assertTrue(Pattern.matches("[a-z]([-a-z0-9]*[a-z0-9])?", job.getName())); } private DataflowPipeline buildDataflowPipeline(DataflowPipelineOptions options) { @@ -166,11 +169,14 @@ private static Dataflow buildMockDataflow( when(mockJobs.list(eq(PROJECT_ID))).thenReturn(mockList); when(mockList.setPageToken(anyString())).thenReturn(mockList); when(mockList.execute()) - .thenReturn(new ListJobsResponse().setJobs( - Arrays.asList(new Job() - .setName("oldJobName") - .setId("oldJobId") - .setCurrentState("JOB_STATE_RUNNING")))); + .thenReturn( + new ListJobsResponse() + .setJobs( + Arrays.asList( + new Job() + .setName("oldjobname") + .setId("oldJobId") + .setCurrentState("JOB_STATE_RUNNING")))); Job resultJob = new Job(); resultJob.setId("newid"); @@ -219,6 +225,17 @@ private DataflowPipelineOptions buildPipelineOptions( return options; } + @Test + public void testFromOptionsWithUppercaseConvertsToLowercase() throws Exception { + String mixedCase = "ThisJobNameHasMixedCase"; + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); + options.setJobName(mixedCase); + + DataflowPipelineRunner runner = DataflowPipelineRunner.fromOptions(options); + assertThat(options.getJobName(), equalTo(mixedCase.toLowerCase())); + } + @Test public void testRun() throws IOException { ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); @@ -271,7 +288,7 @@ public void testUpdate() throws IOException { @Test public void testUpdateNonExistentPipeline() throws IOException { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Could not find running job named badJobName"); + thrown.expectMessage("Could not find running job named badjobname"); DataflowPipelineOptions options = buildPipelineOptions(); options.setUpdate(true); @@ -846,7 +863,8 @@ public void testToString() { options.setTempLocation("gs://test/temp/location"); options.setGcpCredential(new TestCredential()); options.setPathValidatorClass(NoopPathValidator.class); - assertEquals("DataflowPipelineRunner#TestJobName", + assertEquals( + "DataflowPipelineRunner#testjobname", DataflowPipelineRunner.fromOptions(options).toString()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java index c34627cd23..f5709ccab6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java @@ -38,7 +38,7 @@ public void testToString() { options.setTempLocation("gs://test/temp/location"); options.setGcpCredential(new TestCredential()); options.setPathValidatorClass(NoopPathValidator.class); - assertEquals("DataflowPipeline#TestJobName", + assertEquals("DataflowPipeline#testjobname" /* lowercased for service requirements */, DataflowPipeline.create(options).toString()); } } From 7aaef56c12aedecb36b4e9dddfa2730f1866967f Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 28 Mar 2016 13:38:35 -0700 Subject: [PATCH 332/751] DisplayData tweaks based on transform usage. * Add boolean-valued display data. * Implement equality for DislpayData.Item * Add ability to override namespace for included subcomponents. * Additional Matchers for testing display data * Update DisplayData inner class privacy (cherry picked from commit 014a9a5a2241b4f780efea30c14496961c55041d) --- .../sdk/transforms/display/DisplayData.java | 85 ++++++-- .../display/DisplayDataMatchers.java | 181 +++++++++++++++++- .../display/DisplayDataMatchersTest.java | 63 +++++- .../transforms/display/DisplayDataTest.java | 128 ++++++++----- 4 files changed, 391 insertions(+), 66 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index dadc7309da..54bc82b428 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -87,7 +87,7 @@ public Map asMap() { public String toString() { StringBuilder builder = new StringBuilder(); boolean isFirstLine = true; - for (Map.Entry entry : entries.entrySet()) { + for (Item entry : entries.values()) { if (isFirstLine) { isFirstLine = false; } else { @@ -106,13 +106,18 @@ public String toString() { */ public interface Builder { /** - * Include display metadata from the specified subcomponent. For example, a {@link ParDo} + * Register display metadata from the specified subcomponent. For example, a {@link ParDo} * transform includes display metadata from the encapsulated {@link DoFn}. - * - * @return A builder instance to continue to build in a fluent-style. */ Builder include(HasDisplayData subComponent); + /** + * Register display metadata from the specified subcomponent, using the specified namespace. + * For example, a {@link ParDo} transform includes display metadata from the encapsulated + * {@link DoFn}. + */ + Builder include(HasDisplayData subComponent, Class namespace); + /** * Register the given string display metadata. The metadata item will be registered with type * {@link DisplayData.Type#STRING}, and is identified by the specified key and namespace from @@ -134,6 +139,13 @@ public interface Builder { */ ItemBuilder add(String key, double value); + /** + * Register the given floating point display metadata. The metadata item will be registered with + * type {@link DisplayData.Type#BOOLEAN}, and is identified by the specified key and namespace + * from the current transform or component. + */ + ItemBuilder add(String key, boolean value); + /** * Register the given timestamp display metadata. The metadata item will be registered with type * {@link DisplayData.Type#TIMESTAMP}, and is identified by the specified key and namespace from @@ -286,7 +298,35 @@ public String getLinkUrl() { @Override public String toString() { - return getValue(); + return String.format("%s:%s=%s", ns, key, value); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Item) { + Item that = (Item) obj; + return Objects.equals(this.ns, that.ns) + && Objects.equals(this.key, that.key) + && Objects.equals(this.type, that.type) + && Objects.equals(this.value, that.value) + && Objects.equals(this.shortValue, that.shortValue) + && Objects.equals(this.label, that.label) + && Objects.equals(this.url, that.url); + } + + return false; + } + + @Override + public int hashCode() { + return Objects.hash( + this.ns, + this.key, + this.type, + this.value, + this.shortValue, + this.label, + this.url); } private Item withLabel(String label) { @@ -312,8 +352,12 @@ public static class Identifier { private final String ns; private final String key; - static Identifier of(Class namespace, String key) { - return new Identifier(namespace.getName(), key); + public static Identifier of(Class namespace, String key) { + return of(namespace.getName(), key); + } + + public static Identifier of(String namespace, String key) { + return new Identifier(namespace, key); } private Identifier(String ns, String key) { @@ -354,7 +398,7 @@ public String toString() { /** * Display metadata type. */ - enum Type { + public enum Type { STRING { @Override FormattedItemValue format(Object value) { @@ -373,6 +417,12 @@ FormattedItemValue format(Object value) { return new FormattedItemValue(Double.toString((Double) value)); } }, + BOOLEAN() { + @Override + FormattedItemValue format(Object value) { + return new FormattedItemValue(Boolean.toString((boolean) value)); + } + }, TIMESTAMP() { @Override FormattedItemValue format(Object value) { @@ -402,7 +452,7 @@ FormattedItemValue format(Object value) { abstract FormattedItemValue format(Object value); } - private static class FormattedItemValue { + static class FormattedItemValue { private final String shortValue; private final String longValue; @@ -415,11 +465,11 @@ private FormattedItemValue(String longValue, String shortValue) { this.shortValue = shortValue; } - private String getLongValue () { + String getLongValue() { return this.longValue; } - private String getShortValue() { + String getShortValue() { return this.shortValue; } } @@ -445,11 +495,17 @@ private static InternalBuilder forRoot(HasDisplayData instance) { @Override public Builder include(HasDisplayData subComponent) { + checkNotNull(subComponent); + return include(subComponent, subComponent.getClass()); + } + + @Override + public Builder include(HasDisplayData subComponent, Class namespace) { checkNotNull(subComponent); boolean newComponent = visited.add(subComponent); if (newComponent) { Class prevNs = this.latestNs; - this.latestNs = subComponent.getClass(); + this.latestNs = namespace; subComponent.populateDisplayData(this); this.latestNs = prevNs; } @@ -473,6 +529,11 @@ public ItemBuilder add(String key, double value) { return addItem(key, Type.FLOAT, value); } + @Override + public ItemBuilder add(String key, boolean value) { + return addItem(key, Type.BOOLEAN, value); + } + @Override public ItemBuilder add(String key, Instant value) { checkNotNull(value); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java index 2753aafa7b..89d1834522 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java @@ -16,13 +16,19 @@ package com.google.cloud.dataflow.sdk.transforms.display; +import static org.hamcrest.Matchers.allOf; + import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Item; +import com.google.common.collect.Sets; +import org.hamcrest.CustomTypeSafeMatcher; import org.hamcrest.Description; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.hamcrest.TypeSafeDiagnosingMatcher; +import org.joda.time.Duration; +import org.joda.time.Instant; import java.util.Collection; @@ -42,6 +48,71 @@ public static Matcher hasDisplayItem() { return hasDisplayItem(Matchers.any(DisplayData.Item.class)); } + /** + * Create a matcher that matches if the examined {@link DisplayData} contains an item with the + * specified key and String value. + */ + public static Matcher hasDisplayItem(String key, String value) { + return hasDisplayItem(key, DisplayData.Type.STRING, value); + } + + /** + * Create a matcher that matches if the examined {@link DisplayData} contains an item with the + * specified key and Boolean value. + */ + public static Matcher hasDisplayItem(String key, Boolean value) { + return hasDisplayItem(key, DisplayData.Type.BOOLEAN, value); + } + + /** + * Create a matcher that matches if the examined {@link DisplayData} contains an item with the + * specified key and Duration value. + */ + public static Matcher hasDisplayItem(String key, Duration value) { + return hasDisplayItem(key, DisplayData.Type.DURATION, value); + } + + /** + * Create a matcher that matches if the examined {@link DisplayData} contains an item with the + * specified key and Float value. + */ + public static Matcher hasDisplayItem(String key, double value) { + return hasDisplayItem(key, DisplayData.Type.FLOAT, value); + } + + /** + * Create a matcher that matches if the examined {@link DisplayData} contains an item with the + * specified key and Integer value. + */ + public static Matcher hasDisplayItem(String key, long value) { + return hasDisplayItem(key, DisplayData.Type.INTEGER, value); + } + + /** + * Create a matcher that matches if the examined {@link DisplayData} contains an item with the + * specified key and Class value. + */ + public static Matcher hasDisplayItem(String key, Class value) { + return hasDisplayItem(key, DisplayData.Type.JAVA_CLASS, value); + } + + /** + * Create a matcher that matches if the examined {@link DisplayData} contains an item with the + * specified key and Timestamp value. + */ + public static Matcher hasDisplayItem(String key, Instant value) { + return hasDisplayItem(key, DisplayData.Type.TIMESTAMP, value); + } + + private static Matcher hasDisplayItem( + String key, DisplayData.Type type, Object value) { + DisplayData.FormattedItemValue formattedValue = type.format(value); + return hasDisplayItem(allOf( + hasKey(key), + hasType(type), + hasValue(formattedValue.getLongValue()))); + } + /** * Creates a matcher that matches if the examined {@link DisplayData} contains any item * matching the specified {@code itemMatcher}. @@ -68,13 +139,93 @@ protected boolean matchesSafely(DisplayData data, Description mismatchDescriptio Collection items = data.items(); boolean isMatch = Matchers.hasItem(itemMatcher).matches(items); if (!isMatch) { - mismatchDescription.appendText("found " + items.size() + " non-matching items"); + mismatchDescription.appendText("found " + items.size() + " non-matching item(s):\n"); + mismatchDescription.appendValue(data); } return isMatch; } } + /** + * Create a matcher that matches if the examined {@link DisplayData} contains all display data + * registered from the specified subcomponent. + */ + public static Matcher includes(final HasDisplayData subComponent) { + return includes(subComponent, subComponent.getClass()); + } + + /** + * Create a matcher that matches if the examined {@link DisplayData} contains all display data + * registered from the specified subcomponent and namespace. + */ + public static Matcher includes( + final HasDisplayData subComponent, final Class namespace) { + return new CustomTypeSafeMatcher("includes subcomponent") { + @Override + protected boolean matchesSafely(DisplayData displayData) { + DisplayData subComponentData = DisplayData.from(subComponent); + if (subComponentData.items().size() == 0) { + throw new UnsupportedOperationException("subComponent contains no display data; " + + "cannot verify whether it is included"); + } + + DisplayDataComparision comparison = checkSubset(displayData, subComponentData, namespace); + return comparison.missingItems.isEmpty(); + } + + + @Override + protected void describeMismatchSafely( + DisplayData displayData, Description mismatchDescription) { + DisplayData subComponentDisplayData = DisplayData.from(subComponent); + DisplayDataComparision comparison = checkSubset( + displayData, subComponentDisplayData, subComponent.getClass()); + + mismatchDescription + .appendText("did not include:\n") + .appendValue(comparison.missingItems) + .appendText("\nNon-matching items:\n") + .appendValue(comparison.unmatchedItems); + } + + private DisplayDataComparision checkSubset( + DisplayData displayData, DisplayData included, Class namespace) { + DisplayDataComparision comparison = new DisplayDataComparision(displayData.items()); + for (Item item : included.items()) { + Item matchedItem = displayData.asMap().get( + DisplayData.Identifier.of(namespace, item.getKey())); + + if (matchedItem != null) { + comparison.matched(matchedItem); + } else { + comparison.missing(item); + } + } + + return comparison; + } + + class DisplayDataComparision { + Collection missingItems; + Collection unmatchedItems; + + DisplayDataComparision(Collection superset) { + missingItems = Sets.newHashSet(); + unmatchedItems = Sets.newHashSet(superset); + } + + void matched(Item supersetItem) { + unmatchedItems.remove(supersetItem); + } + + void missing(Item subsetItem) { + missingItems.add(subsetItem); + } + } + }; + } + /** * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a key * with the specified value. @@ -95,4 +246,32 @@ protected String featureValueOf(DisplayData.Item actual) { } }; } + + public static Matcher hasType(DisplayData.Type type) { + return hasType(Matchers.is(type)); + } + + public static Matcher hasType(Matcher typeMatcher) { + return new FeatureMatcher( + typeMatcher, "with type", "type") { + @Override + protected DisplayData.Type featureValueOf(DisplayData.Item actual) { + return actual.getType(); + } + }; + } + + public static Matcher hasValue(String value) { + return hasValue(Matchers.is(value)); + } + + public static Matcher hasValue(Matcher valueMatcher) { + return new FeatureMatcher( + valueMatcher, "with value", "value") { + @Override + protected String featureValueOf(DisplayData.Item actual) { + return actual.getValue(); + } + }; + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java index 2636cf85c8..595d519e68 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java @@ -18,11 +18,13 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; @@ -45,7 +47,7 @@ public void testHasDisplayItem() { Matcher matcher = hasDisplayItem(); assertFalse(matcher.matches(DisplayData.none())); - assertTrue(matcher.matches(createDisplayDataWithItem("foo", "bar"))); + assertThat(createDisplayDataWithItem("foo", "bar"), matcher); } @Test @@ -58,15 +60,68 @@ public void testHasDisplayItemDescription() { matcher.describeMismatch(DisplayData.none(), mismatchDesc); assertThat(desc.toString(), startsWith("display data with item: ")); - assertThat(mismatchDesc.toString(), containsString("found 0 non-matching items")); + assertThat(mismatchDesc.toString(), containsString("found 0 non-matching item(s)")); } @Test public void testHasKey() { Matcher matcher = hasDisplayItem(hasKey("foo")); - assertTrue(matcher.matches(createDisplayDataWithItem("foo", "bar"))); assertFalse(matcher.matches(createDisplayDataWithItem("fooz", "bar"))); + + assertThat(createDisplayDataWithItem("foo", "bar"), matcher); + } + + @Test + public void testHasType() { + Matcher matcher = hasDisplayItem(hasType(DisplayData.Type.JAVA_CLASS)); + + DisplayData data = DisplayData.from(new PTransform, PCollection>() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", DisplayDataMatchersTest.class); + } + }); + + assertFalse(matcher.matches(createDisplayDataWithItem("fooz", "bar"))); + assertThat(data, matcher); + } + + @Test + public void testHasValue() { + Matcher matcher = hasDisplayItem(hasValue("bar")); + + assertFalse(matcher.matches(createDisplayDataWithItem("foo", "baz"))); + assertThat(createDisplayDataWithItem("foo", "bar"), matcher); + } + + @Test + public void testIncludes() { + final HasDisplayData subComponent = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar"); + } + }; + HasDisplayData hasSubcomponent = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder + .include(subComponent) + .add("foo2", "bar2"); + } + }; + HasDisplayData sameKeyDifferentNamespace = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar"); + } + }; + Matcher matcher = includes(subComponent); + + assertFalse(matcher.matches(DisplayData.from(sameKeyDifferentNamespace))); + assertThat(DisplayData.from(hasSubcomponent), matcher); + assertThat(DisplayData.from(subComponent), matcher); } private DisplayData createDisplayDataWithItem(final String key, final String value) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index e8128c7788..27be7e6bd1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -18,6 +18,9 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.everyItem; @@ -91,7 +94,7 @@ public void populateDisplayData(DisplayData.Builder builder) { .include(subComponent2) .add("MinSproggles", 200) .withLabel("Mimimum Required Sproggles") - .add("LazerOrientation", "NORTH") + .add("FireLazers", true) .add("TimeBomb", Instant.now().plus(Duration.standardDays(1))) .add("FilterLogic", subComponent1.getClass()) .add("ServiceUrl", "google.com/fizzbang") @@ -126,12 +129,12 @@ public void testCanBuild() { DisplayData.from(new HasDisplayData() { @Override public void populateDisplayData(DisplayData.Builder builder) { - builder.add("Foo", "bar"); + builder.add("foo", "bar"); } }); assertThat(data.items(), hasSize(1)); - assertThat(data, hasDisplayItem(hasKey("Foo"))); + assertThat(data, hasDisplayItem("foo", "bar")); } @Test @@ -147,7 +150,7 @@ public void populateDisplayData(DisplayData.Builder builder) { Map map = data.asMap(); assertEquals(map.size(), 1); - assertThat(data, hasDisplayItem(hasKey("foo"))); + assertThat(data, hasDisplayItem("foo", "bar")); assertEquals(map.values(), data.items()); } @@ -163,8 +166,8 @@ public void testItemProperties() { allOf( hasNamespace(Matchers.>is(ConcreteComponent.class)), hasKey("now"), - hasType(is(DisplayData.Type.TIMESTAMP)), - hasValue(is(ISO_FORMATTER.print(value))), + hasType(DisplayData.Type.TIMESTAMP), + hasValue(ISO_FORMATTER.print(value)), hasShortValue(nullValue(String.class)), hasLabel(is("the current instant")), hasUrl(is("http://time.gov")))); @@ -218,14 +221,35 @@ public void populateDisplayData(DisplayData.Builder builder) { } }); - assertThat( - data, - hasDisplayItem( - allOf( - hasKey("foo"), - hasNamespace(Matchers.>is(subComponent.getClass()))))); + assertThat(data, includes(subComponent)); + } + + @Test + public void testIncludesNamespaceOverride() { + final HasDisplayData subComponent = new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + + final HasDisplayData namespaceOverride = new HasDisplayData(){ + @Override + public void populateDisplayData(Builder builder) { + } + }; + + DisplayData data = DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.include(subComponent, namespaceOverride.getClass()); + } + }); + + assertThat(data, includes(subComponent, namespaceOverride.getClass())); } + @Test public void testIdentifierEquality() { new EqualsTester() @@ -237,6 +261,33 @@ public void testIdentifierEquality() { .testEquals(); } + @Test + public void testItemEquality() { + HasDisplayData component1 = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar"); + } + }; + HasDisplayData component2 = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar"); + } + }; + + DisplayData component1DisplayData1 = DisplayData.from(component1); + DisplayData component1DisplayData2 = DisplayData.from(component1); + DisplayData component2DisplayData = DisplayData.from(component2); + + new EqualsTester() + .addEqualityGroup( + component1DisplayData1.items().toArray()[0], + component1DisplayData2.items().toArray()[0]) + .addEqualityGroup(component2DisplayData.items().toArray()[0]) + .testEquals(); + } + @Test public void testAnonymousClassNamespace() { DisplayData data = @@ -403,6 +454,7 @@ public void populateDisplayData(DisplayData.Builder builder) { .add("string", "foobar") .add("integer", 123) .add("float", 3.14) + .add("boolean", true) .add("java_class", DisplayDataTest.class) .add("timestamp", Instant.now()) .add("duration", Duration.standardHours(1)); @@ -411,18 +463,19 @@ public void populateDisplayData(DisplayData.Builder builder) { Collection items = data.items(); assertThat( - items, hasItem(allOf(hasKey("string"), hasType(is(DisplayData.Type.STRING))))); + items, hasItem(allOf(hasKey("string"), hasType(DisplayData.Type.STRING)))); assertThat( - items, hasItem(allOf(hasKey("integer"), hasType(is(DisplayData.Type.INTEGER))))); - assertThat(items, hasItem(allOf(hasKey("float"), hasType(is(DisplayData.Type.FLOAT))))); + items, hasItem(allOf(hasKey("integer"), hasType(DisplayData.Type.INTEGER)))); + assertThat(items, hasItem(allOf(hasKey("float"), hasType(DisplayData.Type.FLOAT)))); + assertThat(items, hasItem(allOf(hasKey("boolean"), hasType(DisplayData.Type.BOOLEAN)))); assertThat( items, - hasItem(allOf(hasKey("java_class"), hasType(is(DisplayData.Type.JAVA_CLASS))))); + hasItem(allOf(hasKey("java_class"), hasType(DisplayData.Type.JAVA_CLASS)))); assertThat( items, - hasItem(allOf(hasKey("timestamp"), hasType(is(DisplayData.Type.TIMESTAMP))))); + hasItem(allOf(hasKey("timestamp"), hasType(DisplayData.Type.TIMESTAMP)))); assertThat( - items, hasItem(allOf(hasKey("duration"), hasType(is(DisplayData.Type.DURATION))))); + items, hasItem(allOf(hasKey("duration"), hasType(DisplayData.Type.DURATION)))); } @Test @@ -437,6 +490,7 @@ public void populateDisplayData(DisplayData.Builder builder) { .add("string", "foobar") .add("integer", 123) .add("float", 3.14) + .add("boolean", true) .add("java_class", DisplayDataTest.class) .add("timestamp", now) .add("duration", oneHour); @@ -444,17 +498,13 @@ public void populateDisplayData(DisplayData.Builder builder) { }; DisplayData data = DisplayData.from(component); - Collection items = data.items(); - assertThat(items, hasItem(allOf(hasKey("string"), hasValue(is("foobar"))))); - assertThat(items, hasItem(allOf(hasKey("integer"), hasValue(is("123"))))); - assertThat(items, hasItem(allOf(hasKey("float"), hasValue(is("3.14"))))); - assertThat(items, hasItem(allOf(hasKey("java_class"), - hasValue(is(DisplayDataTest.class.getName())), - hasShortValue(is(DisplayDataTest.class.getSimpleName()))))); - assertThat(items, hasItem(allOf(hasKey("timestamp"), - hasValue(is(ISO_FORMATTER.print(now)))))); - assertThat(items, hasItem(allOf(hasKey("duration"), - hasValue(is(Long.toString(oneHour.getMillis())))))); + assertThat(data, hasDisplayItem("string", "foobar")); + assertThat(data, hasDisplayItem("integer", 123)); + assertThat(data, hasDisplayItem("float", 3.14)); + assertThat(data, hasDisplayItem("boolean", true)); + assertThat(data, hasDisplayItem("java_class", DisplayDataTest.class)); + assertThat(data, hasDisplayItem("timestamp", now)); + assertThat(data, hasDisplayItem("duration", oneHour)); } @Test @@ -582,16 +632,6 @@ protected Class featureValueOf(DisplayData.Item actual) { }; } - private static Matcher hasType(Matcher typeMatcher) { - return new FeatureMatcher( - typeMatcher, "display item with type", "type") { - @Override - protected DisplayData.Type featureValueOf(DisplayData.Item actual) { - return actual.getType(); - } - }; - } - private static Matcher hasLabel(Matcher labelMatcher) { return new FeatureMatcher( labelMatcher, "display item with label", "label") { @@ -612,16 +652,6 @@ protected String featureValueOf(DisplayData.Item actual) { }; } - private static Matcher hasValue(Matcher valueMatcher) { - return new FeatureMatcher( - valueMatcher, "display item with value", "value") { - @Override - protected String featureValueOf(DisplayData.Item actual) { - return actual.getValue(); - } - }; - } - private static Matcher hasShortValue(Matcher valueStringMatcher) { return new FeatureMatcher( valueStringMatcher, "display item with short value", "short value") { From 75ee00ee48b74331185b5b0cb3a97869d9496d48 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 5 Apr 2016 11:42:30 -0700 Subject: [PATCH 333/751] Additional APIs for registering DisplayData - Support overriding namespace when adding display data - Support inferring display data type during registration - Add APIs to conditionally register display data if not null/default. - Move additional matchers into DisplayDataMatchers (cherry picked from commit 5da22920c7c5d20695d4309429341c39af760044) --- .../sdk/transforms/display/DisplayData.java | 306 ++++++++++++++++-- .../transforms/display/HasDisplayData.java | 1 + .../display/DisplayDataMatchers.java | 43 +++ .../display/DisplayDataMatchersTest.java | 34 +- .../transforms/display/DisplayDataTest.java | 206 +++++++++--- 5 files changed, 517 insertions(+), 73 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 54bc82b428..8db1af4d97 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -75,6 +75,30 @@ public static DisplayData from(HasDisplayData component) { return InternalBuilder.forRoot(component).build(); } + /** + * Infer the {@link Type} for the given object. + * + *

        Use this method if the type of metadata is not known at compile time. For example: + * + *

        +   * {@code
        +   * @Override
        +   * public void populateDisplayData(DisplayData.Builder builder) {
        +   *   Optional type = DisplayData.inferType(foo);
        +   *   if (type.isPresent()) {
        +   *     builder.add("foo", type.get(), foo);
        +   *   }
        +   * }
        +   * }
        +   * 
        + * + * @return The inferred {@link Type}, or null if the type cannot be inferred, + */ + @Nullable + public static Type inferType(@Nullable Object value) { + return Type.tryInferFrom(value); + } + public Collection items() { return entries.values(); } @@ -100,6 +124,10 @@ public String toString() { return builder.toString(); } + private static String namespaceOf(Class clazz) { + return clazz.getName(); + } + /** * Utility to build up display metadata from a component and its included * subcomponents. @@ -125,6 +153,20 @@ public interface Builder { */ ItemBuilder add(String key, String value); + /** + * Register the given string display data if the value is not null. + * + * @see DisplayData.Builder#add(String, String) + */ + ItemBuilder addIfNotNull(String key, @Nullable String value); + + /** + * Register the given string display data if the value is different than the specified default. + * + * @see DisplayData.Builder#add(String, String) + */ + ItemBuilder addIfNotDefault(String key, @Nullable String value, @Nullable String defaultValue); + /** * Register the given numeric display metadata. The metadata item will be registered with type * {@link DisplayData.Type#INTEGER}, and is identified by the specified key and namespace from @@ -132,6 +174,13 @@ public interface Builder { */ ItemBuilder add(String key, long value); + /** + * Register the given numeric display data if the value is different than the specified default. + * + * @see DisplayData.Builder#add(String, long) + */ + ItemBuilder addIfNotDefault(String key, long value, long defaultValue); + /** * Register the given floating point display metadata. The metadata item will be registered with * type {@link DisplayData.Type#FLOAT}, and is identified by the specified key and namespace @@ -140,12 +189,27 @@ public interface Builder { ItemBuilder add(String key, double value); /** - * Register the given floating point display metadata. The metadata item will be registered with + * Register the given floating point display data if the value is different than the specified + * default. + * + * @see DisplayData.Builder#add(String, double) + */ + ItemBuilder addIfNotDefault(String key, double value, double defaultValue); + + /** + * Register the given boolean display metadata. The metadata item will be registered with * type {@link DisplayData.Type#BOOLEAN}, and is identified by the specified key and namespace * from the current transform or component. */ ItemBuilder add(String key, boolean value); + /** + * Register the given boolean display data if the value is different than the specified default. + * + * @see DisplayData.Builder#add(String, boolean) + */ + ItemBuilder addIfNotDefault(String key, boolean value, boolean defaultValue); + /** * Register the given timestamp display metadata. The metadata item will be registered with type * {@link DisplayData.Type#TIMESTAMP}, and is identified by the specified key and namespace from @@ -153,6 +217,22 @@ public interface Builder { */ ItemBuilder add(String key, Instant value); + /** + * Register the given timestamp display data if the value is not null. + * + * @see DisplayData.Builder#add(String, Instant) + */ + ItemBuilder addIfNotNull(String key, @Nullable Instant value); + + /** + * Register the given timestamp display data if the value is different than the specified + * default. + * + * @see DisplayData.Builder#add(String, Instant) + */ + ItemBuilder addIfNotDefault( + String key, @Nullable Instant value, @Nullable Instant defaultValue); + /** * Register the given duration display metadata. The metadata item will be registered with type * {@link DisplayData.Type#DURATION}, and is identified by the specified key and namespace from @@ -160,12 +240,54 @@ public interface Builder { */ ItemBuilder add(String key, Duration value); + /** + * Register the given duration display data if the value is not null. + * + * @see DisplayData.Builder#add(String, Duration) + */ + ItemBuilder addIfNotNull(String key, @Nullable Duration value); + + /** + * Register the given duration display data if the value is different than the specified + * default. + * + * @see DisplayData.Builder#add(String, Duration) + */ + ItemBuilder addIfNotDefault( + String key, @Nullable Duration value, @Nullable Duration defaultValue); + /** * Register the given class display metadata. The metadata item will be registered with type * {@link DisplayData.Type#JAVA_CLASS}, and is identified by the specified key and namespace * from the current transform or component. */ ItemBuilder add(String key, Class value); + + /** + * Register the given class display data if the value is not null. + * + * @see DisplayData.Builder#add(String, Class) + */ + ItemBuilder addIfNotNull(String key, @Nullable Class value); + + /** + * Register the given class display data if the value is different than the specified default. + * + * @see DisplayData.Builder#add(String, Class) + */ + ItemBuilder addIfNotDefault( + String key, @Nullable Class value, @Nullable Class defaultValue); + + /** + * Register the given display metadata with the specified type. + * + *

        The added display data is identified by the specified key and namespace from the current + * transform or component. + * + * @throws ClassCastException if the value cannot be safely cast to the specified type. + * @see DisplayData#inferType(Object) + */ + ItemBuilder add(String key, Type type, Object value); } /** @@ -189,6 +311,14 @@ public interface ItemBuilder extends Builder { *

        Specifying a null value will clear the URL if it was previously defined. */ ItemBuilder withLinkUrl(@Nullable String url); + + /** + * Adds an explicit namespace to the most-recently added display metadata. The namespace + * and key uniquely identify the display metadata. + * + *

        Leaving the namespace unspecified will default to the registering instance's class. + */ + ItemBuilder withNamespace(Class namespace); } /** @@ -206,10 +336,11 @@ public static class Item { private final String label; private final String url; - private static Item create(String namespace, String key, Type type, T value) { + private static Item create(Class nsClass, String key, Type type, Object value) { FormattedItemValue formatted = type.format(value); + String namespace = namespaceOf(nsClass); return new Item( - namespace, key, type, formatted.getLongValue(), formatted.getShortValue(), null, null); + namespace, key, type, formatted.getLongValue(), formatted.getShortValue(), null, null); } private Item( @@ -336,6 +467,12 @@ private Item withLabel(String label) { private Item withUrl(String url) { return new Item(this.ns, this.key, this.type, this.value, this.shortValue, url, this.label); } + + private Item withNamespace(Class nsClass) { + String namespace = namespaceOf(nsClass); + return new Item( + namespace, this.key, this.type, this.value, this.shortValue, this.url, this.label); + } } /** @@ -353,7 +490,7 @@ public static class Identifier { private final String key; public static Identifier of(Class namespace, String key) { - return of(namespace.getName(), key); + return of(namespaceOf(namespace), key); } public static Identifier of(String namespace, String key) { @@ -402,13 +539,14 @@ public enum Type { STRING { @Override FormattedItemValue format(Object value) { - return new FormattedItemValue((String) value); + return new FormattedItemValue(value.toString()); } }, INTEGER { @Override FormattedItemValue format(Object value) { - return new FormattedItemValue(Long.toString((long) value)); + Number number = (Number) value; + return new FormattedItemValue(Long.toString(number.longValue())); } }, FLOAT { @@ -450,6 +588,28 @@ FormattedItemValue format(Object value) { *

        Internal-only. Value objects can be safely cast to the expected Java type. */ abstract FormattedItemValue format(Object value); + + @Nullable + private static Type tryInferFrom(@Nullable Object value) { + Type type; + if (value instanceof Integer || value instanceof Long) { + return INTEGER; + } else if (value instanceof Double || value instanceof Float) { + return FLOAT; + } else if (value instanceof Boolean) { + return BOOLEAN; + } else if (value instanceof Instant) { + return TIMESTAMP; + } else if (value instanceof Duration) { + return DURATION; + } else if (value instanceof Class) { + return JAVA_CLASS; + } else if (value instanceof String) { + return STRING; + } else { + return null; + } + } } static class FormattedItemValue { @@ -479,8 +639,9 @@ private static class InternalBuilder implements ItemBuilder { private final Set visited; private Class latestNs; + + @Nullable private Item latestItem; - private Identifier latestIdentifier; private InternalBuilder() { this.entries = Maps.newHashMap(); @@ -502,6 +663,9 @@ public Builder include(HasDisplayData subComponent) { @Override public Builder include(HasDisplayData subComponent, Class namespace) { checkNotNull(subComponent); + checkNotNull(namespace); + + commitLatest(); boolean newComponent = visited.add(subComponent); if (newComponent) { Class prevNs = this.latestNs; @@ -516,75 +680,165 @@ public Builder include(HasDisplayData subComponent, Class namespace) { @Override public ItemBuilder add(String key, String value) { checkNotNull(value); - return addItem(key, Type.STRING, value); + return addItemIf(true, key, Type.STRING, value); + } + + @Override + public ItemBuilder addIfNotNull(String key, @Nullable String value) { + return addItemIf(value != null, key, Type.STRING, value); + } + + @Override + public ItemBuilder addIfNotDefault( + String key, @Nullable String value, @Nullable String defaultValue) { + return addItemIf(!Objects.equals(value, defaultValue), key, Type.STRING, value); } @Override public ItemBuilder add(String key, long value) { - return addItem(key, Type.INTEGER, value); + return addItemIf(true, key, Type.INTEGER, value); + } + + @Override + public ItemBuilder addIfNotDefault(String key, long value, long defaultValue) { + return addItemIf(value != defaultValue, key, Type.INTEGER, value); } @Override public ItemBuilder add(String key, double value) { - return addItem(key, Type.FLOAT, value); + return addItemIf(true, key, Type.FLOAT, value); + } + + @Override + public ItemBuilder addIfNotDefault(String key, double value, double defaultValue) { + return addItemIf(value != defaultValue, key, Type.FLOAT, value); } @Override public ItemBuilder add(String key, boolean value) { - return addItem(key, Type.BOOLEAN, value); + return addItemIf(true, key, Type.BOOLEAN, value); + } + + @Override + public ItemBuilder addIfNotDefault(String key, boolean value, boolean defaultValue) { + return addItemIf(value != defaultValue, key, Type.BOOLEAN, value); } @Override public ItemBuilder add(String key, Instant value) { checkNotNull(value); - return addItem(key, Type.TIMESTAMP, value); + return addItemIf(true, key, Type.TIMESTAMP, value); + } + + @Override + public ItemBuilder addIfNotNull(String key, @Nullable Instant value) { + return addItemIf(value != null, key, Type.TIMESTAMP, value); + } + + @Override + public ItemBuilder addIfNotDefault( + String key, @Nullable Instant value, @Nullable Instant defaultValue) { + return addItemIf(!Objects.equals(value, defaultValue), key, Type.TIMESTAMP, value); } @Override public ItemBuilder add(String key, Duration value) { checkNotNull(value); - return addItem(key, Type.DURATION, value); + return addItemIf(true, key, Type.DURATION, value); + } + + @Override + public ItemBuilder addIfNotNull(String key, @Nullable Duration value) { + return addItemIf(value != null, key, Type.DURATION, value); + } + + @Override + public ItemBuilder addIfNotDefault( + String key, @Nullable Duration value, @Nullable Duration defaultValue) { + return addItemIf(!Objects.equals(value, defaultValue), key, Type.DURATION, value); } @Override public ItemBuilder add(String key, Class value) { checkNotNull(value); - return addItem(key, Type.JAVA_CLASS, value); + return addItemIf(true, key, Type.JAVA_CLASS, value); + } + + @Override + public ItemBuilder addIfNotNull(String key, @Nullable Class value) { + return addItemIf(value != null, key, Type.JAVA_CLASS, value); + } + + @Override + public ItemBuilder addIfNotDefault( + String key, @Nullable Class value, @Nullable Class defaultValue) { + return addItemIf(!Objects.equals(value, defaultValue), key, Type.JAVA_CLASS, value); + } + + @Override + public ItemBuilder add(String key, Type type, Object value) { + checkNotNull(value); + checkNotNull(type); + return addItemIf(true, key, type, value); } - private ItemBuilder addItem(String key, Type type, T value) { + private ItemBuilder addItemIf(boolean condition, String key, Type type, Object value) { checkNotNull(key); checkArgument(!key.isEmpty()); - Identifier id = Identifier.of(latestNs, key); + commitLatest(); + if (condition) { + latestItem = Item.create(latestNs, key, type, value); + } + + return this; + } + + private void commitLatest() { + if (latestItem == null) { + return; + } + + Identifier id = Identifier.of(latestItem.getNamespace(), latestItem.getKey()); if (entries.containsKey(id)) { throw new IllegalArgumentException("DisplayData key already exists. All display data " + "for a component must be registered with a unique key.\nKey: " + id); } - Item item = Item.create(id.getNamespace(), key, type, value); - entries.put(id, item); - latestItem = item; - latestIdentifier = id; + entries.put(id, latestItem); + latestItem = null; + } + + @Override + public ItemBuilder withLabel(@Nullable String label) { + if (latestItem != null) { + latestItem = latestItem.withLabel(label); + } return this; } @Override - public ItemBuilder withLabel(String label) { - latestItem = latestItem.withLabel(label); - entries.put(latestIdentifier, latestItem); + public ItemBuilder withLinkUrl(@Nullable String url) { + if (latestItem != null) { + latestItem = latestItem.withUrl(url); + } + return this; } @Override - public ItemBuilder withLinkUrl(String url) { - latestItem = latestItem.withUrl(url); - entries.put(latestIdentifier, latestItem); + public ItemBuilder withNamespace(Class namespace) { + checkNotNull(namespace); + if (latestItem != null) { + latestItem = latestItem.withNamespace(namespace); + } + return this; } private DisplayData build() { + commitLatest(); return new DisplayData(this.entries); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java index b2eca3d881..825b19267d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java @@ -39,6 +39,7 @@ public interface HasDisplayData { * builder * .include(subComponent) * .add("minFilter", 42) + * .addIfNotDefault("useTransactions", this.txn, false) * .add("topic", "projects/myproject/topics/mytopic") * .withLabel("Pub/Sub Topic") * .add("serviceInstance", "myservice.com/fizzbang") diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java index 89d1834522..dafba359de 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java @@ -247,10 +247,44 @@ protected String featureValueOf(DisplayData.Item actual) { }; } + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} contains the + * specified namespace. + */ + public static Matcher hasNamespace(Class namespace) { + return hasNamespace(Matchers.>is(namespace)); + } + + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a namespace + * matching the specified namespace matcher. + */ + public static Matcher hasNamespace(Matcher> namespaceMatcher) { + return new FeatureMatcher>( + namespaceMatcher, "display item with namespace", "namespace") { + @Override + protected Class featureValueOf(DisplayData.Item actual) { + try { + return Class.forName(actual.getNamespace()); + } catch (ClassNotFoundException e) { + return null; + } + } + }; + } + + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} matches the + * specified type. + */ public static Matcher hasType(DisplayData.Type type) { return hasType(Matchers.is(type)); } + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} has a type + * matching the specified type matcher. + */ public static Matcher hasType(Matcher typeMatcher) { return new FeatureMatcher( typeMatcher, "with type", "type") { @@ -261,10 +295,19 @@ protected DisplayData.Type featureValueOf(DisplayData.Item actual) { }; } + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} has the specified + * value. + */ + public static Matcher hasValue(String value) { return hasValue(Matchers.is(value)); } + /** + * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a value + * matching the specified value matcher. + */ public static Matcher hasValue(Matcher valueMatcher) { return new FeatureMatcher( valueMatcher, "with value", "value") { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java index 595d519e68..4ee76d9c2f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java @@ -18,6 +18,7 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; @@ -95,6 +96,15 @@ public void testHasValue() { assertThat(createDisplayDataWithItem("foo", "bar"), matcher); } + @Test + public void testHasNamespace() { + Matcher matcher = hasDisplayItem(hasNamespace(SampleTransform.class)); + + assertFalse(matcher.matches(DisplayData.from( + new PTransform, PCollection>(){}))); + assertThat(createDisplayDataWithItem("foo", "bar"), matcher); + } + @Test public void testIncludes() { final HasDisplayData subComponent = new HasDisplayData() { @@ -124,13 +134,23 @@ public void populateDisplayData(Builder builder) { assertThat(DisplayData.from(subComponent), matcher); } + private DisplayData createDisplayDataWithItem(final String key, final String value) { - return DisplayData.from( - new PTransform, PCollection>() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(key, value); - } - }); + return DisplayData.from(new SampleTransform(key, value)); + } + + static class SampleTransform extends PTransform, PCollection> { + private final String key; + private final String value; + + SampleTransform(String key, String value) { + this.key = key; + this.value = value; + } + + @Override + public void populateDisplayData(Builder builder) { + builder.add(key, value); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index 27be7e6bd1..46b5b942f2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -18,6 +18,7 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; @@ -85,20 +86,25 @@ public void populateDisplayData(DisplayData.Builder builder) { } }; + PTransform transform = new PTransform, PCollection>() { + final Instant defaultStartTime = new Instant(0); + Instant startTime = defaultStartTime; + @Override public void populateDisplayData(DisplayData.Builder builder) { builder .include(subComponent1) .include(subComponent2) - .add("MinSproggles", 200) - .withLabel("Mimimum Required Sproggles") - .add("FireLazers", true) - .add("TimeBomb", Instant.now().plus(Duration.standardDays(1))) - .add("FilterLogic", subComponent1.getClass()) - .add("ServiceUrl", "google.com/fizzbang") - .withLinkUrl("http://www.google.com/fizzbang"); + .add("minSproggles", 200) + .withLabel("Mimimum Required Sproggles") + .add("fireLazers", true) + .addIfNotDefault("startTime", startTime, defaultStartTime) + .add("timeBomb", Instant.now().plus(Duration.standardDays(1))) + .add("filterLogic", subComponent1.getClass()) + .add("serviceUrl", "google.com/fizzbang") + .withLinkUrl("http://www.google.com/fizzbang"); } }; @@ -157,14 +163,22 @@ public void populateDisplayData(DisplayData.Builder builder) { @Test public void testItemProperties() { final Instant value = Instant.now(); - DisplayData data = DisplayData.from(new ConcreteComponent(value)); + DisplayData data = DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("now", value) + .withLabel("the current instant") + .withLinkUrl("http://time.gov") + .withNamespace(DisplayDataTest.class); + } + }); @SuppressWarnings("unchecked") DisplayData.Item item = (DisplayData.Item) data.items().toArray()[0]; assertThat( item, - allOf( - hasNamespace(Matchers.>is(ConcreteComponent.class)), + Matchers.allOf( + hasNamespace(DisplayDataTest.class), hasKey("now"), hasType(DisplayData.Type.TIMESTAMP), hasValue(ISO_FORMATTER.print(value)), @@ -173,19 +187,6 @@ public void testItemProperties() { hasUrl(is("http://time.gov")))); } - static class ConcreteComponent implements HasDisplayData { - private Instant value; - - ConcreteComponent(Instant value) { - this.value = value; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add("now", value).withLabel("the current instant").withLinkUrl("http://time.gov"); - } - } - @Test public void testUnspecifiedOptionalProperties() { DisplayData data = @@ -202,6 +203,54 @@ public void populateDisplayData(DisplayData.Builder builder) { hasDisplayItem(allOf(hasLabel(nullValue(String.class)), hasUrl(nullValue(String.class))))); } + @Test + public void testAddIfNotDefault() { + final int defaultValue = 10; + + DisplayData data = DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder + .addIfNotDefault("isDefault", defaultValue, defaultValue) + .addIfNotDefault("notDefault", defaultValue + 1, defaultValue); + } + }); + + assertThat(data, not(hasDisplayItem(hasKey("isDefault")))); + assertThat(data, hasDisplayItem("notDefault", defaultValue + 1)); + } + + @Test + public void testAddIfNotNull() { + DisplayData data = DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder + .addIfNotNull("isNull", (Class) null) + .addIfNotNull("notNull", DisplayDataTest.class); + } + }); + + assertThat(data, not(hasDisplayItem(hasKey("isNull")))); + assertThat(data, hasDisplayItem(hasKey("notNull"))); + } + + @Test + public void testModifyingConditionalItemIsSafe() { + HasDisplayData component = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.addIfNotNull("nullItem", (Class) null) + .withLinkUrl("http://abc") + .withNamespace(DisplayDataTest.class) + .withLabel("Null item shoudl be safe"); + } + }; + + DisplayData.from(component); // should not throw + } + + @Test public void testIncludes() { final HasDisplayData subComponent = @@ -249,6 +298,18 @@ public void populateDisplayData(DisplayData.Builder builder) { assertThat(data, includes(subComponent, namespaceOverride.getClass())); } + @Test + public void testNullNamespaceOverride() { + thrown.expect(NullPointerException.class); + + DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar") + .withNamespace(null); + } + }); + } @Test public void testIdentifierEquality() { @@ -348,6 +409,22 @@ public void populateDisplayData(DisplayData.Builder builder) { }); } + @Test + public void testDuplicateKeyWithNamespaceOverrideDoesntThrow() { + DisplayData displayData = DisplayData.from( + new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("foo", "bar") + .add("foo", "baz") + .withNamespace(DisplayDataTest.class); + } + }); + + assertThat(displayData.items(), hasSize(2)); + } + @Test public void testToString() { HasDisplayData component = new HasDisplayData() { @@ -427,6 +504,7 @@ public int hashCode() { } @Override + @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public boolean equals(Object obj) { return true; } @@ -478,6 +556,50 @@ public void populateDisplayData(DisplayData.Builder builder) { items, hasItem(allOf(hasKey("duration"), hasType(DisplayData.Type.DURATION)))); } + @Test + public void testExplicitItemType() { + DisplayData data = DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder + .add("integer", DisplayData.Type.INTEGER, 1234) + .add("string", DisplayData.Type.STRING, "foobar"); + } + }); + + assertThat(data, hasDisplayItem("integer", 1234)); + assertThat(data, hasDisplayItem("string", "foobar")); + } + + @Test + public void testInvalidExplicitItemType() { + HasDisplayData component = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("integer", DisplayData.Type.INTEGER, "foobar"); + } + }; + + thrown.expect(ClassCastException.class); + DisplayData.from(component); + } + + @Test + public void testKnownTypeInference() { + assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234)); + assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234L)); + assertEquals(DisplayData.Type.FLOAT, DisplayData.inferType(12.3)); + assertEquals(DisplayData.Type.FLOAT, DisplayData.inferType(12.3f)); + assertEquals(DisplayData.Type.BOOLEAN, DisplayData.inferType(true)); + assertEquals(DisplayData.Type.TIMESTAMP, DisplayData.inferType(Instant.now())); + assertEquals(DisplayData.Type.DURATION, DisplayData.inferType(Duration.millis(1234))); + assertEquals(DisplayData.Type.JAVA_CLASS, DisplayData.inferType(DisplayDataTest.class)); + assertEquals(DisplayData.Type.STRING, DisplayData.inferType("hello world")); + + assertEquals(null, DisplayData.inferType(null)); + assertEquals(null, DisplayData.inferType(new Object() {})); + } + @Test public void testStringFormatting() throws IOException { final Instant now = Instant.now(); @@ -533,7 +655,7 @@ public void populateDisplayData(DisplayData.Builder builder) { hasItem( allOf( hasKey("alpha"), - hasNamespace(Matchers.>is(component.getClass()))))); + hasNamespace(component.getClass())))); } @Test @@ -554,6 +676,23 @@ public void populateDisplayData(Builder builder) { }); } + @Test + public void testIncludeNullNamespace() { + final HasDisplayData subComponent = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + } + }; + + thrown.expect(NullPointerException.class); + DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.include(subComponent, null); + } + }); + } + @Test public void testNullKey() { thrown.expect(NullPointerException.class); @@ -610,28 +749,15 @@ public void testAcceptsNullOptionalValues() { @Override public void populateDisplayData(Builder builder) { builder.add("key", "value") - .withLabel(null) - .withLinkUrl(null); + .withLabel(null) + .withLinkUrl(null) + .withNamespace(null); } }); // Should not throw } - private static Matcher hasNamespace(Matcher> nsMatcher) { - return new FeatureMatcher>( - nsMatcher, "display item with namespace", "namespace") { - @Override - protected Class featureValueOf(DisplayData.Item actual) { - try { - return Class.forName(actual.getNamespace()); - } catch (ClassNotFoundException e) { - return null; - } - } - }; - } - private static Matcher hasLabel(Matcher labelMatcher) { return new FeatureMatcher( labelMatcher, "display item with label", "label") { From 770379fd21a07dfab4c2ef956584a7aa84384891 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 11 Apr 2016 09:08:23 -0700 Subject: [PATCH 334/751] DisplayData API tweaks - Add additional overloads for conditionally registering null display data - Serialize DisplayData using JSON primatives - Fix checkstyle error - Bind generic type parameter in DataflowPipelineTranslator#addDisplayData - Add additional tests for new APIs - Improve readability of DisplayDataTest#populateDisplayData (cherry picked from commit dba82feaca316e4f78357957c67059039589da36) --- .../runners/DataflowPipelineTranslator.java | 9 +- .../sdk/transforms/display/DisplayData.java | 103 ++++++--- .../DataflowPipelineTranslatorTest.java | 22 +- .../display/DisplayDataMatchers.java | 10 +- .../transforms/display/DisplayDataTest.java | 200 ++++++++++++++++-- 5 files changed, 280 insertions(+), 64 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 75fd5b3f93..32dfb876ff 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -80,7 +80,6 @@ import com.google.cloud.dataflow.sdk.values.TypedPValue; import com.google.common.base.Preconditions; import com.google.common.base.Strings; -import com.google.common.collect.Lists; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -729,12 +728,8 @@ private void addOutput(String name, PValue value, Coder valueCoder) { } private void addDisplayData(String name, DisplayData displayData) { - List> serializedItems = Lists.newArrayList(); - for (DisplayData.Item item : displayData.items()) { - serializedItems.add(MAPPER.convertValue(item, Map.class)); - } - - addList(getProperties(), name, serializedItems); + List> list = MAPPER.convertValue(displayData, List.class); + addList(getProperties(), name, list); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 8db1af4d97..71440124f4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -28,6 +28,7 @@ import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonValue; import org.apache.avro.reflect.Nullable; import org.joda.time.Duration; @@ -99,6 +100,7 @@ public static Type inferType(@Nullable Object value) { return Type.tryInferFrom(value); } + @JsonValue public Collection items() { return entries.values(); } @@ -174,6 +176,13 @@ public interface Builder { */ ItemBuilder add(String key, long value); + /** + * Register the given numeric display data if the value is not null. + * + * @see DisplayData.Builder#add(String, long) + */ + ItemBuilder addIfNotNull(String key, @Nullable Long value); + /** * Register the given numeric display data if the value is different than the specified default. * @@ -188,6 +197,13 @@ public interface Builder { */ ItemBuilder add(String key, double value); + /** + * Register the given floating point display data if the value is not null. + * + * @see DisplayData.Builder#add(String, double) + */ + ItemBuilder addIfNotNull(String key, @Nullable Double value); + /** * Register the given floating point display data if the value is different than the specified * default. @@ -203,6 +219,13 @@ public interface Builder { */ ItemBuilder add(String key, boolean value); + /** + * Register the given boolean display data if the value is not null. + * + * @see DisplayData.Builder#add(String, boolean) + */ + ItemBuilder addIfNotNull(String key, @Nullable Boolean value); + /** * Register the given boolean display data if the value is different than the specified default. * @@ -285,6 +308,7 @@ ItemBuilder addIfNotDefault( * transform or component. * * @throws ClassCastException if the value cannot be safely cast to the specified type. + * * @see DisplayData#inferType(Object) */ ItemBuilder add(String key, Type type, Object value); @@ -331,8 +355,8 @@ public static class Item { private final String key; private final String ns; private final Type type; - private final String value; - private final String shortValue; + private final Object value; + private final Object shortValue; private final String label; private final String url; @@ -347,8 +371,8 @@ private Item( String namespace, String key, Type type, - String value, - String shortValue, + Object value, + Object shortValue, String url, String label) { this.ns = namespace; @@ -383,7 +407,7 @@ public Type getType() { * Retrieve the value of the metadata item. */ @JsonGetter("value") - public String getValue() { + public Object getValue() { return value; } @@ -397,7 +421,7 @@ public String getValue() { @JsonGetter("shortValue") @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable - public String getShortValue() { + public Object getShortValue() { return shortValue; } @@ -539,48 +563,65 @@ public enum Type { STRING { @Override FormattedItemValue format(Object value) { - return new FormattedItemValue(value.toString()); + return new FormattedItemValue(checkType(value, String.class, STRING)); } }, INTEGER { @Override FormattedItemValue format(Object value) { - Number number = (Number) value; - return new FormattedItemValue(Long.toString(number.longValue())); + if (value instanceof Integer) { + long l = ((Integer) value).longValue(); + return format(l); + } + + return new FormattedItemValue(checkType(value, Long.class, INTEGER)); } }, FLOAT { @Override FormattedItemValue format(Object value) { - return new FormattedItemValue(Double.toString((Double) value)); + return new FormattedItemValue(checkType(value, Number.class, FLOAT)); } }, BOOLEAN() { @Override FormattedItemValue format(Object value) { - return new FormattedItemValue(Boolean.toString((boolean) value)); + return new FormattedItemValue(checkType(value, Boolean.class, BOOLEAN)); } }, TIMESTAMP() { @Override FormattedItemValue format(Object value) { - return new FormattedItemValue((TIMESTAMP_FORMATTER.print((Instant) value))); + Instant instant = checkType(value, Instant.class, TIMESTAMP); + return new FormattedItemValue((TIMESTAMP_FORMATTER.print(instant))); } }, DURATION { @Override FormattedItemValue format(Object value) { - return new FormattedItemValue(Long.toString(((Duration) value).getMillis())); + Duration duration = checkType(value, Duration.class, DURATION); + return new FormattedItemValue(duration.getMillis()); } }, JAVA_CLASS { @Override FormattedItemValue format(Object value) { - Class clazz = (Class) value; + Class clazz = checkType(value, Class.class, JAVA_CLASS); return new FormattedItemValue(clazz.getName(), clazz.getSimpleName()); } }; + private static T checkType(Object value, Class clazz, DisplayData.Type expectedType) { + if (!clazz.isAssignableFrom(value.getClass())) { + throw new ClassCastException(String.format( + "Value is not valid for DisplayData type %s: %s", expectedType, value)); + } + + @SuppressWarnings("unchecked") // type checked above. + T typedValue = (T) value; + return typedValue; + } + /** * Format the display metadata value into a long string representation, and optionally * a shorter representation for display. @@ -591,7 +632,6 @@ FormattedItemValue format(Object value) { @Nullable private static Type tryInferFrom(@Nullable Object value) { - Type type; if (value instanceof Integer || value instanceof Long) { return INTEGER; } else if (value instanceof Double || value instanceof Float) { @@ -613,23 +653,23 @@ private static Type tryInferFrom(@Nullable Object value) { } static class FormattedItemValue { - private final String shortValue; - private final String longValue; + private final Object shortValue; + private final Object longValue; - private FormattedItemValue(String longValue) { + private FormattedItemValue(Object longValue) { this(longValue, null); } - private FormattedItemValue(String longValue, String shortValue) { + private FormattedItemValue(Object longValue, Object shortValue) { this.longValue = longValue; this.shortValue = shortValue; } - String getLongValue() { + Object getLongValue() { return this.longValue; } - String getShortValue() { + Object getShortValue() { return this.shortValue; } } @@ -699,9 +739,14 @@ public ItemBuilder add(String key, long value) { return addItemIf(true, key, Type.INTEGER, value); } + @Override + public ItemBuilder addIfNotNull(String key, @Nullable Long value) { + return addItemIf(value != null, key, Type.INTEGER, value); + } + @Override public ItemBuilder addIfNotDefault(String key, long value, long defaultValue) { - return addItemIf(value != defaultValue, key, Type.INTEGER, value); + return addItemIf(!Objects.equals(value, defaultValue), key, Type.INTEGER, value); } @Override @@ -709,9 +754,14 @@ public ItemBuilder add(String key, double value) { return addItemIf(true, key, Type.FLOAT, value); } + @Override + public ItemBuilder addIfNotNull(String key, @Nullable Double value) { + return addItemIf(value != null, key, Type.FLOAT, value); + } + @Override public ItemBuilder addIfNotDefault(String key, double value, double defaultValue) { - return addItemIf(value != defaultValue, key, Type.FLOAT, value); + return addItemIf(!Objects.equals(value, defaultValue), key, Type.FLOAT, value); } @Override @@ -719,9 +769,14 @@ public ItemBuilder add(String key, boolean value) { return addItemIf(true, key, Type.BOOLEAN, value); } + @Override + public ItemBuilder addIfNotNull(String key, @Nullable Boolean value) { + return addItemIf(value != null, key, Type.BOOLEAN, value); + } + @Override public ItemBuilder addIfNotDefault(String key, boolean value, boolean defaultValue) { - return addItemIf(value != defaultValue, key, Type.BOOLEAN, value); + return addItemIf(!Objects.equals(value, defaultValue), key, Type.BOOLEAN, value); } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 83cfc9b4f9..905fee25d6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -19,6 +19,7 @@ import static com.google.cloud.dataflow.sdk.util.Structs.addObject; import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; import static com.google.cloud.dataflow.sdk.util.Structs.getString; + import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.core.IsInstanceOf.instanceOf; @@ -819,8 +820,8 @@ public void processElement(ProcessContext c) throws Exception { public void populateDisplayData(DisplayData.Builder builder) { builder .add("foo", "bar") - .add("foo2", 123) - .withLabel("Test Value") + .add("foo2", DataflowPipelineTranslatorTest.class) + .withLabel("Test Class") .withLinkUrl("http://www.google.com"); } }; @@ -833,7 +834,7 @@ public void processElement(ProcessContext c) throws Exception { @Override public void populateDisplayData(DisplayData.Builder builder) { - builder.add("foo3", "barge"); + builder.add("foo3", 1234); } }; @@ -868,19 +869,20 @@ public void populateDisplayData(DisplayData.Builder builder) { .build(), ImmutableMap.builder() .put("key", "foo2") - .put("type", "INTEGER") - .put("value", "123") + .put("type", "JAVA_CLASS") + .put("value", DataflowPipelineTranslatorTest.class.getName()) + .put("shortValue", DataflowPipelineTranslatorTest.class.getSimpleName()) .put("namespace", fn1.getClass().getName()) - .put("label", "Test Value") + .put("label", "Test Class") .put("linkUrl", "http://www.google.com") .build() ); - ImmutableSet> expectedFn2DisplayData = ImmutableSet.of( - ImmutableMap.builder() + ImmutableSet> expectedFn2DisplayData = ImmutableSet.of( + ImmutableMap.builder() .put("key", "foo3") - .put("type", "STRING") - .put("value", "barge") + .put("type", "INTEGER") + .put("value", 1234L) .put("namespace", fn2.getClass().getName()) .build() ); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java index dafba359de..064b98a54f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java @@ -300,7 +300,7 @@ protected DisplayData.Type featureValueOf(DisplayData.Item actual) { * value. */ - public static Matcher hasValue(String value) { + public static Matcher hasValue(Object value) { return hasValue(Matchers.is(value)); } @@ -308,12 +308,12 @@ public static Matcher hasValue(String value) { * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a value * matching the specified value matcher. */ - public static Matcher hasValue(Matcher valueMatcher) { - return new FeatureMatcher( + public static Matcher hasValue(Matcher valueMatcher) { + return new FeatureMatcher( valueMatcher, "with value", "value") { @Override - protected String featureValueOf(DisplayData.Item actual) { - return actual.getValue(); + protected T featureValueOf(DisplayData.Item actual) { + return (T) actual.getValue(); } }; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index 46b5b942f2..ad348f16de 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -32,14 +32,21 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Item; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.Multimap; import com.google.common.testing.EqualsTester; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.hamcrest.CustomTypeSafeMatcher; import org.hamcrest.FeatureMatcher; @@ -67,6 +74,7 @@ public class DisplayDataTest { @Rule public ExpectedException thrown = ExpectedException.none(); private static final DateTimeFormatter ISO_FORMATTER = ISODateTimeFormat.dateTime(); + private static final ObjectMapper MAPPER = new ObjectMapper(); @Test public void testTypicalUsage() { @@ -205,19 +213,29 @@ public void populateDisplayData(DisplayData.Builder builder) { @Test public void testAddIfNotDefault() { - final int defaultValue = 10; - DisplayData data = DisplayData.from(new HasDisplayData() { @Override public void populateDisplayData(Builder builder) { builder - .addIfNotDefault("isDefault", defaultValue, defaultValue) - .addIfNotDefault("notDefault", defaultValue + 1, defaultValue); + .addIfNotDefault("defaultString", "foo", "foo") + .addIfNotDefault("notDefaultString", "foo", "notFoo") + .addIfNotDefault("defaultInteger", 1, 1) + .addIfNotDefault("notDefaultInteger", 1, 2) + .addIfNotDefault("defaultDouble", 123.4, 123.4) + .addIfNotDefault("notDefaultDouble", 123.4, 234.5) + .addIfNotDefault("defaultBoolean", true, true) + .addIfNotDefault("notDefaultBoolean", true, false) + .addIfNotDefault("defaultInstant", new Instant(0), new Instant(0)) + .addIfNotDefault("notDefaultInstant", new Instant(0), Instant.now()) + .addIfNotDefault("defaultDuration", Duration.ZERO, Duration.ZERO) + .addIfNotDefault("notDefaultDuration", Duration.millis(1234), Duration.ZERO) + .addIfNotDefault("defaultClass", DisplayDataTest.class, DisplayDataTest.class) + .addIfNotDefault("notDefaultClass", DisplayDataTest.class, null); } }); - assertThat(data, not(hasDisplayItem(hasKey("isDefault")))); - assertThat(data, hasDisplayItem("notDefault", defaultValue + 1)); + assertThat(data.items(), hasSize(7)); + assertThat(data.items(), everyItem(hasKey(startsWith("notDefault")))); } @Test @@ -226,13 +244,25 @@ public void testAddIfNotNull() { @Override public void populateDisplayData(Builder builder) { builder - .addIfNotNull("isNull", (Class) null) - .addIfNotNull("notNull", DisplayDataTest.class); + .addIfNotNull("nullString", (String) null) + .addIfNotNull("notNullString", "foo") + .addIfNotNull("nullLong", (Long) null) + .addIfNotNull("notNullLong", 1234L) + .addIfNotNull("nullDouble", (Double) null) + .addIfNotNull("notNullDouble", 123.4) + .addIfNotNull("nullBoolean", (Boolean) null) + .addIfNotNull("notNullBoolean", true) + .addIfNotNull("nullInstant", (Instant) null) + .addIfNotNull("notNullInstant", Instant.now()) + .addIfNotNull("nullDuration", (Duration) null) + .addIfNotNull("notNullDuration", Duration.ZERO) + .addIfNotNull("nullClass", (Class) null) + .addIfNotNull("notNullClass", DisplayDataTest.class); } }); - assertThat(data, not(hasDisplayItem(hasKey("isNull")))); - assertThat(data, hasDisplayItem(hasKey("notNull"))); + assertThat(data.items(), hasSize(7)); + assertThat(data.items(), everyItem(hasKey(startsWith("notNull")))); } @Test @@ -562,15 +592,66 @@ public void testExplicitItemType() { @Override public void populateDisplayData(Builder builder) { builder - .add("integer", DisplayData.Type.INTEGER, 1234) + .add("integer", DisplayData.Type.INTEGER, 1234L) .add("string", DisplayData.Type.STRING, "foobar"); } }); - assertThat(data, hasDisplayItem("integer", 1234)); + assertThat(data, hasDisplayItem("integer", 1234L)); assertThat(data, hasDisplayItem("string", "foobar")); } + @Test + public void testFormatIncompatibleTypes() { + Map invalidPairs = ImmutableMap.builder() + .put(DisplayData.Type.STRING, 1234) + .put(DisplayData.Type.INTEGER, "string value") + .put(DisplayData.Type.FLOAT, "string value") + .put(DisplayData.Type.BOOLEAN, "string value") + .put(DisplayData.Type.TIMESTAMP, "string value") + .put(DisplayData.Type.DURATION, "string value") + .put(DisplayData.Type.JAVA_CLASS, "string value") + .build(); + + for (Map.Entry pair : invalidPairs.entrySet()) { + try { + DisplayData.Type type = pair.getKey(); + Object invalidValue = pair.getValue(); + + type.format(invalidValue); + fail(String.format( + "Expected exception not thrown for invalid %s value: %s", type, invalidValue)); + } catch (ClassCastException e) { + // Expected + } + } + } + + @Test + public void testFormatCompatibleTypes() { + Multimap validPairs = ImmutableMultimap + .builder() + .put(DisplayData.Type.INTEGER, 1234) + .put(DisplayData.Type.INTEGER, 1234L) + .put(DisplayData.Type.FLOAT, 123.4f) + .put(DisplayData.Type.FLOAT, 123.4) + .put(DisplayData.Type.FLOAT, 1234) + .put(DisplayData.Type.FLOAT, 1234L) + .build(); + + for (Map.Entry pair : validPairs.entries()) { + DisplayData.Type type = pair.getKey(); + Object value = pair.getValue(); + + try { + type.format(value); + } catch (ClassCastException e) { + fail(String.format("Failed to format %s for DisplayData.%s", + value.getClass().getSimpleName(), type)); + } + } + } + @Test public void testInvalidExplicitItemType() { HasDisplayData component = new HasDisplayData() { @@ -750,14 +831,95 @@ public void testAcceptsNullOptionalValues() { public void populateDisplayData(Builder builder) { builder.add("key", "value") .withLabel(null) - .withLinkUrl(null) - .withNamespace(null); + .withLinkUrl(null); } }); // Should not throw } + @Test + public void testJsonSerialization() throws IOException { + final String stringValue = "foobar"; + final int intValue = 1234; + final double floatValue = 123.4; + final boolean boolValue = true; + final int durationMillis = 1234; + + HasDisplayData component = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder + .add("string", stringValue) + .add("long", intValue) + .add("double", floatValue) + .add("boolean", boolValue) + .add("instant", new Instant(0)) + .add("duration", Duration.millis(durationMillis)) + .add("class", DisplayDataTest.class) + .withLinkUrl("http://abc") + .withLabel("baz") + ; + } + }; + DisplayData data = DisplayData.from(component); + + JsonNode json = MAPPER.readTree(MAPPER.writeValueAsBytes(data)); + assertThat(json, hasExpectedJson(component, "STRING", "string", quoted(stringValue))); + assertThat(json, hasExpectedJson(component, "INTEGER", "long", intValue)); + assertThat(json, hasExpectedJson(component, "FLOAT", "double", floatValue)); + assertThat(json, hasExpectedJson(component, "BOOLEAN", "boolean", boolValue)); + assertThat(json, hasExpectedJson(component, "DURATION", "duration", durationMillis)); + assertThat(json, hasExpectedJson( + component, "TIMESTAMP", "instant", quoted("1970-01-01T00:00:00.000Z"))); + assertThat(json, hasExpectedJson( + component, "JAVA_CLASS", "class", quoted(DisplayDataTest.class.getName()), + quoted("DisplayDataTest"), "baz", "http://abc")); + } + + private String quoted(Object obj) { + return String.format("\"%s\"", obj); + } + + private Matcher> hasExpectedJson( + HasDisplayData component, String type, String key, Object value) + throws IOException { + return hasExpectedJson(component, type, key, value, null, null, null); + } + + private Matcher> hasExpectedJson( + HasDisplayData component, + String type, + String key, + Object value, + Object shortValue, + String label, + String linkUrl) throws IOException { + Class nsClass = component.getClass(); + + StringBuilder builder = new StringBuilder(); + builder.append("{"); + builder.append(String.format("\"namespace\":\"%s\",", nsClass.getName())); + builder.append(String.format("\"type\":\"%s\",", type)); + builder.append(String.format("\"key\":\"%s\",", key)); + builder.append(String.format("\"value\":%s", value)); + + if (shortValue != null) { + builder.append(String.format(",\"shortValue\":%s", shortValue)); + } + if (label != null) { + builder.append(String.format(",\"label\":\"%s\"", label)); + } + if (linkUrl != null) { + builder.append(String.format(",\"linkUrl\":\"%s\"", linkUrl)); + } + + builder.append("}"); + + JsonNode jsonNode = MAPPER.readTree(builder.toString()); + return hasItem(jsonNode); + } + private static Matcher hasLabel(Matcher labelMatcher) { return new FeatureMatcher( labelMatcher, "display item with label", "label") { @@ -778,12 +940,14 @@ protected String featureValueOf(DisplayData.Item actual) { }; } - private static Matcher hasShortValue(Matcher valueStringMatcher) { - return new FeatureMatcher( + private static Matcher hasShortValue(Matcher valueStringMatcher) { + return new FeatureMatcher( valueStringMatcher, "display item with short value", "short value") { @Override - protected String featureValueOf(DisplayData.Item actual) { - return actual.getShortValue(); + protected T featureValueOf(DisplayData.Item actual) { + @SuppressWarnings("unchecked") + T shortValue = (T) actual.getShortValue(); + return shortValue; } }; } From 59cad93817729cf63b81238f14cb5f94a869f353 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 11 Apr 2016 15:38:39 -0700 Subject: [PATCH 335/751] Add display data to windowing transforms Expose NeverTrigger as package-private since it is necessary for display data (cherry picked from commit 450dd856f00fc898bb9d2bdc1a5331f13a6c52c1) --- .../sdk/transforms/windowing/AfterAll.java | 10 +++ .../windowing/AfterDelayFromFirstElement.java | 11 ++- .../sdk/transforms/windowing/AfterEach.java | 10 +++ .../sdk/transforms/windowing/AfterFirst.java | 10 +++ .../windowing/AfterProcessingTime.java | 11 ++- .../transforms/windowing/AfterWatermark.java | 26 ++++++- .../transforms/windowing/CalendarWindows.java | 35 ++++++++-- .../transforms/windowing/FixedWindows.java | 8 +++ .../windowing/OrFinallyTrigger.java | 5 ++ .../sdk/transforms/windowing/Repeatedly.java | 7 +- .../sdk/transforms/windowing/Sessions.java | 6 ++ .../transforms/windowing/SlidingWindows.java | 9 +++ .../sdk/transforms/windowing/Window.java | 25 +++++++ .../sdk/transforms/windowing/WindowFn.java | 14 +++- .../dataflow/sdk/util/ReshuffleTrigger.java | 5 ++ .../transforms/windowing/AfterAllTest.java | 5 ++ .../transforms/windowing/AfterEachTest.java | 10 +++ .../transforms/windowing/AfterFirstTest.java | 6 ++ .../transforms/windowing/AfterPaneTest.java | 6 ++ .../windowing/AfterProcessingTimeTest.java | 31 ++++++++ .../windowing/AfterWatermarkTest.java | 27 +++++++ .../windowing/CalendarWindowsTest.java | 32 +++++++++ .../windowing/FixedWindowsTest.java | 15 ++++ .../windowing/OrFinallyTriggerTest.java | 6 ++ .../transforms/windowing/RepeatedlyTest.java | 13 ++++ .../transforms/windowing/SessionsTest.java | 10 +++ .../windowing/SlidingWindowsTest.java | 21 ++++++ .../sdk/transforms/windowing/StubTrigger.java | 70 +++++++++++++++++++ .../sdk/transforms/windowing/TriggerTest.java | 2 +- .../sdk/transforms/windowing/WindowTest.java | 59 ++++++++++++++++ .../sdk/util/ReshuffleTriggerTest.java | 10 ++- 31 files changed, 502 insertions(+), 13 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java index bb43010ae5..d44cf6b073 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; +import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import org.joda.time.Instant; @@ -114,4 +115,13 @@ public void onOnlyFiring(TriggerContext context) throws Exception { subtrigger.invokeOnFire(context); } } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder("AfterAll.of("); + Joiner.on(", ").appendTo(builder, subTriggers); + builder.append(")"); + + return builder.toString(); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java index 71968e919c..fa4a113366 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java @@ -34,10 +34,12 @@ import org.joda.time.Duration; import org.joda.time.Instant; +import org.joda.time.format.PeriodFormat; +import org.joda.time.format.PeriodFormatter; import java.util.List; +import java.util.Locale; import java.util.Objects; - import javax.annotation.Nullable; /** @@ -57,6 +59,8 @@ public abstract class AfterDelayFromFirstElement extend StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( "delayed", InstantCoder.of(), Min.MinFn.naturalOrder())); + private static final PeriodFormatter PERIOD_FORMATTER = PeriodFormat.wordBased(Locale.ENGLISH); + /** * To complete an implementation, return the desired time from the TriggerContext. */ @@ -274,6 +278,11 @@ public boolean equals(Object object) { public int hashCode() { return Objects.hash(delay); } + + @Override + public String toString() { + return PERIOD_FORMATTER.print(delay.toPeriod()); + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java index 4b052faeb8..9adecdcab4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; +import com.google.common.base.Joiner; import org.joda.time.Instant; import java.util.Arrays; @@ -129,6 +130,15 @@ public void onFire(Trigger.TriggerContext context) throws Exception { updateFinishedState(context); } + @Override + public String toString() { + StringBuilder builder = new StringBuilder("AfterEach.inOrder("); + Joiner.on(", ").appendTo(builder, subTriggers); + builder.append(")"); + + return builder.toString(); + } + private void updateFinishedState(TriggerContext context) { context.trigger().setFinished(context.trigger().firstUnfinishedSubTrigger() == null); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java index 29b19bf9b9..d2603eaee5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; +import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import org.joda.time.Instant; @@ -109,6 +110,15 @@ protected void onOnlyFiring(TriggerContext context) throws Exception { } } + @Override + public String toString() { + StringBuilder builder = new StringBuilder("AfterFirst.of("); + Joiner.on(", ").appendTo(builder, subTriggers); + builder.append(")"); + + return builder.toString(); + } + private void updateFinishedStatus(TriggerContext c) { boolean anyFinished = false; for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java index 7e89902741..5db290127f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Objects; - import javax.annotation.Nullable; /** @@ -75,7 +74,15 @@ protected Trigger getContinuationTrigger(List> continuationTrigger @Override public String toString() { - return "AfterProcessingTime.pastFirstElementInPane(" + timestampMappers + ")"; + StringBuilder builder = new StringBuilder("AfterProcessingTime.pastFirstElementInPane()"); + for (SerializableFunction delayFn : timestampMappers) { + builder + .append(".plusDelayOf(") + .append(delayFn) + .append(")"); + } + + return builder.toString(); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index fac2c2841b..77c422a414 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -64,6 +64,8 @@ @Experimental(Experimental.Kind.TRIGGER) public class AfterWatermark { + private static final String TO_STRING = "AfterWatermark.pastEndOfWindow()"; + // Static factory class. private AfterWatermark() {} @@ -100,7 +102,7 @@ public interface AfterWatermarkLate extends TriggerBuil * A trigger which never fires. Used for the "early" trigger when only a late trigger was * specified. */ - private static class NeverTrigger extends OnceTrigger { + static class NeverTrigger extends OnceTrigger { protected NeverTrigger() { super(null); @@ -258,6 +260,26 @@ public void onFire(Trigger.TriggerContext context) throws Exception { } } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(TO_STRING); + + Trigger earlyTrigger = subTriggers.get(EARLY_INDEX); + if (!(earlyTrigger instanceof NeverTrigger)) { + builder + .append(".withEarlyFirings(") + .append(earlyTrigger) + .append(")"); + } + + builder + .append(".withLateFirings(") + .append(subTriggers.get(LATE_INDEX)) + .append(")"); + + return builder.toString(); + } + private void onNonLateFiring(Trigger.TriggerContext context) throws Exception { // We have not yet transitioned to late firings. ExecutableTrigger earlySubtrigger = context.trigger().subTrigger(EARLY_INDEX); @@ -368,7 +390,7 @@ public FromEndOfWindow getContinuationTrigger(List> continuationTr @Override public String toString() { - return "AfterWatermark.pastEndOfWindow()"; + return TO_STRING; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java index de5140f2a5..42c97b8370 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -34,6 +35,8 @@ */ public class CalendarWindows { + private static final DateTime DEFAULT_START_DATE = new DateTime(0, DateTimeZone.UTC); + /** * Returns a {@link WindowFn} that windows elements into periods measured by days. * @@ -41,7 +44,7 @@ public class CalendarWindows { * separate windows for each day. */ public static DaysWindows days(int number) { - return new DaysWindows(number, new DateTime(0, DateTimeZone.UTC), DateTimeZone.UTC); + return new DaysWindows(number, DEFAULT_START_DATE, DateTimeZone.UTC); } /** @@ -53,7 +56,7 @@ public static DaysWindows days(int number) { public static DaysWindows weeks(int number, int startDayOfWeek) { return new DaysWindows( 7 * number, - new DateTime(0, DateTimeZone.UTC).withDayOfWeek(startDayOfWeek), + DEFAULT_START_DATE.withDayOfWeek(startDayOfWeek), DateTimeZone.UTC); } @@ -66,7 +69,7 @@ public static DaysWindows weeks(int number, int startDayOfWeek) { * and the first window begins in January 2014. */ public static MonthsWindows months(int number) { - return new MonthsWindows(number, 1, new DateTime(0, DateTimeZone.UTC), DateTimeZone.UTC); + return new MonthsWindows(number, 1, DEFAULT_START_DATE, DateTimeZone.UTC); } /** @@ -78,7 +81,7 @@ public static MonthsWindows months(int number) { * America/Los_Angeles time zone. */ public static YearsWindows years(int number) { - return new YearsWindows(number, 1, 1, new DateTime(0, DateTimeZone.UTC), DateTimeZone.UTC); + return new YearsWindows(number, 1, 1, DEFAULT_START_DATE, DateTimeZone.UTC); } /** @@ -141,6 +144,14 @@ public boolean isCompatible(WindowFn other) { && timeZone == that.timeZone; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("numDays", number) + .addIfNotDefault("startDate", new DateTime(startDate, timeZone).toInstant(), + new DateTime(DEFAULT_START_DATE, DateTimeZone.UTC).toInstant()); + } + public int getNumber() { return number; } @@ -228,6 +239,14 @@ public boolean isCompatible(WindowFn other) { && timeZone == that.timeZone; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("numMonths", number) + .addIfNotDefault("startDate", new DateTime(startDate, timeZone).toInstant(), + new DateTime(DEFAULT_START_DATE, DateTimeZone.UTC).toInstant()); + } + public int getNumber() { return number; } @@ -324,6 +343,14 @@ public boolean isCompatible(WindowFn other) { && timeZone == that.timeZone; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("numYears", number) + .addIfNotDefault("startDate", new DateTime(startDate, timeZone).toInstant(), + new DateTime(DEFAULT_START_DATE, DateTimeZone.UTC).toInstant()); + } + public DateTimeZone getTimeZone() { return timeZone; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java index 12a0f1b918..67d226102f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.joda.time.Duration; import org.joda.time.Instant; @@ -81,6 +82,13 @@ public IntervalWindow assignWindow(Instant timestamp) { return new IntervalWindow(new Instant(start), size); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("size", size) + .addIfNotDefault("offset", offset, Duration.ZERO); + } + @Override public Coder windowCoder() { return IntervalWindow.getCoder(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java index 652092ad6e..afbbb45343 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java @@ -90,6 +90,11 @@ public void onFire(Trigger.TriggerContext context) throws Exception { updateFinishedState(context); } + @Override + public String toString() { + return String.format("%s.orFinally(%s)", subTriggers.get(ACTUAL), subTriggers.get(UNTIL)); + } + private void updateFinishedState(TriggerContext c) throws Exception { boolean anyStillFinished = false; for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java index 5f29c8ffe3..c1000c2261 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java @@ -42,7 +42,7 @@ public class Repeatedly extends Trigger { private static final int REPEATED = 0; /** - * Create a composite trigger that repeatedly executes the trigger {@code toRepeat}, firing each + * Create a composite trigger that repeatedly executes the trigger {@code repeated}, firing each * time it fires and ignoring any indications to finish. * *

        Unless used with {@link Trigger#orFinally} the composite trigger will never finish. @@ -94,6 +94,11 @@ public void onFire(TriggerContext context) throws Exception { } } + @Override + public String toString() { + return String.format("Repeatedly.forever(%s)", subTriggers.get(REPEATED)); + } + private ExecutableTrigger getRepeated(TriggerContext context) { return context.trigger().subTrigger(REPEATED); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java index da137c1f47..0915ae7ea4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.joda.time.Duration; @@ -96,6 +97,11 @@ public Duration getGapDuration() { return gapDuration; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("gapDuration", gapDuration); + } + @Override public boolean equals(Object object) { if (!(object instanceof Sessions)) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java index b0066d6124..ddb453b133 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.joda.time.Duration; import org.joda.time.Instant; @@ -138,6 +139,14 @@ public boolean isCompatible(WindowFn other) { return equals(other); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("size", size) + .add("period", period) + .add("offset", offset); + } + /** * Return the last start of a sliding window that contains the timestamp. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java index 6793e7648f..b22457800a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.AssignWindowsDoFn; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; @@ -603,6 +604,30 @@ private PCollection assignWindows( return input.apply("AssignWindows", ParDo.of(new AssignWindowsDoFn(windowFn))); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("windowFn", windowFn.getClass()) + .include(windowFn) + .addIfNotNull("allowedLateness", allowedLateness); + + if (trigger != null && !(trigger instanceof DefaultTrigger)) { + builder.add("trigger", trigger.toString()); + } + + if (mode != null) { + builder.add("accumulationMode", mode.toString()); + } + + if (closingBehavior != null) { + builder.add("closingBehavior", closingBehavior.toString()); + } + + if (outputTimeFn != null) { + builder.add("outputTimeFn", outputTimeFn.getClass()); + } + } + @Override protected Coder getDefaultOutputCoder(PCollection input) { return input.getCoder(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java index d51fc7ead4..3d43372103 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java @@ -19,6 +19,8 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.common.collect.Ordering; @@ -48,7 +50,7 @@ * windows used by this {@code WindowFn} */ public abstract class WindowFn - implements Serializable { + implements Serializable, HasDisplayData { /** * Information available when running {@link #assignWindows}. */ @@ -176,6 +178,16 @@ public boolean assignsToSingleWindow() { return false; } + /** + * {@inheritDoc} + * + *

        By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(DisplayData.Builder builder) { + } + /** * A compatibility adapter that will return the assigned timestamps according to the * {@link WindowFn}, which was the prior policy. Specifying the assigned output timestamps diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java index 248f00589d..fb7efd9620 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java @@ -58,4 +58,9 @@ public boolean shouldFire(Trigger.TriggerContext context) throws Exception { @Override public void onFire(Trigger.TriggerContext context) throws Exception { } + + @Override + public String toString() { + return "ReshuffleTrigger()"; + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java index 06f0c3f759..3e8ab333e1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java @@ -148,4 +148,9 @@ public void testContinuation() throws Exception { afterAll.getContinuationTrigger()); } + @Test + public void testToString() { + Trigger trigger = AfterAll.of(StubTrigger.named("t1"), StubTrigger.named("t2")); + assertEquals("AfterAll.of(t1, t2)", trigger.toString()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java index 5d6632d1c4..9c9e79ef55 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java @@ -119,4 +119,14 @@ public void testContinuation() throws Exception { trigger1.getContinuationTrigger(), trigger2.getContinuationTrigger())), afterEach.getContinuationTrigger()); } + + @Test + public void testToString() { + Trigger trigger = AfterEach.inOrder( + StubTrigger.named("t1"), + StubTrigger.named("t2"), + StubTrigger.named("t3")); + + assertEquals("AfterEach.inOrder(t1, t2, t3)", trigger.toString()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java index 135638c363..fc0a5cd5ae 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java @@ -172,4 +172,10 @@ public void testContinuation() throws Exception { AfterFirst.of(trigger1.getContinuationTrigger(), trigger2.getContinuationTrigger()), afterFirst.getContinuationTrigger()); } + + @Test + public void testToString() { + Trigger trigger = AfterFirst.of(StubTrigger.named("t1"), StubTrigger.named("t2")); + assertEquals("AfterFirst.of(t1, t2)", trigger.toString()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java index 9139bc5884..7274a997d7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java @@ -123,4 +123,10 @@ public void testContinuation() throws Exception { AfterPane.elementCountAtLeast(1), AfterPane.elementCountAtLeast(100).getContinuationTrigger().getContinuationTrigger()); } + + @Test + public void testToString() { + Trigger trigger = AfterPane.elementCountAtLeast(5); + assertEquals("AfterPane.elementCountAtLeast(5)", trigger.toString()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java index a3bb3c372e..959802fd0d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java @@ -154,4 +154,35 @@ public void testCompatibilityIdentical() throws Exception { .plusDelayOf(Duration.standardMinutes(1L)); assertTrue(t1.isCompatible(t2)); } + + @Test + public void testToString() { + Trigger trigger = AfterProcessingTime.pastFirstElementInPane(); + assertEquals("AfterProcessingTime.pastFirstElementInPane()", trigger.toString()); + } + + @Test + public void testWithDelayToString() { + Trigger trigger = AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(5)); + + assertEquals("AfterProcessingTime.pastFirstElementInPane().plusDelayOf(5 minutes)", + trigger.toString()); + } + + @Test + public void testBuiltUpToString() { + Trigger trigger = AfterWatermark.pastEndOfWindow() + .withLateFirings(AfterProcessingTime + .pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(10))) + .buildTrigger(); + + String expected = "AfterWatermark.pastEndOfWindow()" + + ".withLateFirings(AfterProcessingTime" + + ".pastFirstElementInPane()" + + ".plusDelayOf(10 minutes))"; + + assertEquals(expected, trigger.toString()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java index fb610aadd1..e1a14c7cdf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doNothing; @@ -335,4 +336,30 @@ public void testEarlyAndLateOnMergeRewinds() throws Exception { tester.advanceInputWatermark(new Instant(15)); assertTrue(tester.shouldFire(mergedWindow)); } + + @Test + public void testFromEndOfWindowToString() { + Trigger trigger = AfterWatermark.pastEndOfWindow(); + assertEquals("AfterWatermark.pastEndOfWindow()", trigger.toString()); + } + + @Test + public void testLateFiringsToString() { + Trigger trigger = AfterWatermark.pastEndOfWindow() + .withLateFirings(StubTrigger.named("t1")) + .buildTrigger(); + + assertEquals("AfterWatermark.pastEndOfWindow().withLateFirings(t1)", trigger.toString()); + } + + @Test + public void testEarlyAndLateFiringsToString() { + Trigger trigger = AfterWatermark.pastEndOfWindow() + .withEarlyFirings(StubTrigger.named("t1")) + .withLateFirings(StubTrigger.named("t2")) + .buildTrigger(); + + assertEquals("AfterWatermark.pastEndOfWindow().withEarlyFirings(t1).withLateFirings(t2)", + trigger.toString()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java index 512fcbc292..8b1fbcec85 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java @@ -18,8 +18,13 @@ import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; + import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeZone; @@ -257,4 +262,31 @@ public void testTimeZone() throws Exception { CalendarWindows.days(1).withTimeZone(timeZone), timestamps)); } + + @Test + public void testDisplayData() { + DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles"); + Instant jan1 = new DateTime(1990, 1, 1, 0, 0, timeZone).toInstant(); + + CalendarWindows.DaysWindows daysWindow = CalendarWindows.days(5) + .withStartingDay(1990, 1, 1) + .withTimeZone(timeZone); + DisplayData daysDisplayData = DisplayData.from(daysWindow); + assertThat(daysDisplayData, hasDisplayItem("numDays", 5)); + assertThat(daysDisplayData, hasDisplayItem("startDate", jan1)); + + CalendarWindows.MonthsWindows monthsWindow = CalendarWindows.months(2) + .withStartingMonth(1990, 1) + .withTimeZone(timeZone); + DisplayData monthsDisplayData = DisplayData.from(monthsWindow); + assertThat(monthsDisplayData, hasDisplayItem("numMonths", 2)); + assertThat(monthsDisplayData, hasDisplayItem("startDate", jan1)); + + CalendarWindows.YearsWindows yearsWindow = CalendarWindows.years(4) + .withStartingYear(1990) + .withTimeZone(timeZone); + DisplayData yearsDisplayData = DisplayData.from(yearsWindow); + assertThat(yearsDisplayData, hasDisplayItem("numYears", 4)); + assertThat(yearsDisplayData, hasDisplayItem("startDate", jan1)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java index 935f22e016..e143597c52 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java @@ -18,6 +18,8 @@ import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -26,6 +28,7 @@ import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.joda.time.Duration; import org.joda.time.Instant; @@ -121,4 +124,16 @@ public void testValidOutputTimes() throws Exception { FixedWindows.of(new Duration(500)), timestamp); } } + + @Test + public void testDisplayData() { + Duration offset = Duration.standardSeconds(1234); + Duration size = Duration.standardSeconds(2345); + + FixedWindows fixedWindows = FixedWindows.of(size).withOffset(offset); + DisplayData displayData = DisplayData.from(fixedWindows); + + assertThat(displayData, hasDisplayItem("size", size)); + assertThat(displayData, hasDisplayItem("offset", offset)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java index a416e60425..6a734fdb54 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java @@ -206,4 +206,10 @@ public void testContinuation() throws Exception { triggerB.getContinuationTrigger().orFinally(triggerA.getContinuationTrigger())), bOrFinallyA.getContinuationTrigger()); } + + @Test + public void testToString() { + Trigger trigger = StubTrigger.named("t1").orFinally(StubTrigger.named("t2")); + assertEquals("t1.orFinally(t2)", trigger.toString()); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java index e14c15c4e2..0a0f99cbf9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java @@ -208,4 +208,17 @@ public void testRepeatedlyProcessingTime() throws Exception { assertFalse(tester.shouldFire(window)); } + + @Test + public void testToString() { + Trigger trigger = Repeatedly.forever(new StubTrigger() { + @Override + public String toString() { + return "innerTrigger"; + } + }); + + assertEquals("Repeatedly.forever(innerTrigger)", trigger.toString()); + } + } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java index 91049cd9d9..4649a6bcc7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java @@ -18,6 +18,7 @@ import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; @@ -26,6 +27,7 @@ import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.collect.ImmutableList; import org.joda.time.Duration; @@ -153,4 +155,12 @@ public void testValidOutputAtEndTimes() throws Exception { (List) ImmutableList.of(1L, 3L), (List) ImmutableList.of(0L, 5L, 10L, 15L, 20L))); } + + @Test + public void testDisplayData() { + Duration gapDuration = Duration.standardMinutes(234); + Sessions session = Sessions.withGapDuration(gapDuration); + assertThat(DisplayData.from(session), + hasDisplayItem("gapDuration", gapDuration)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java index 33c4b8b816..2aae07804c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java @@ -18,11 +18,15 @@ import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.joda.time.Duration; import org.joda.time.Instant; @@ -190,4 +194,21 @@ public void testOutputTimesNonInterference() throws Exception { SlidingWindows.of(new Duration(1000)).every(new Duration(500)), timestamp); } } + + @Test + public void testDisplayData() { + Duration windowSize = Duration.standardSeconds(1234); + Duration offset = Duration.standardSeconds(2345); + Duration period = Duration.standardSeconds(3456); + + SlidingWindows slidingWindowFn = SlidingWindows + .of(windowSize) + .every(period) + .withOffset(offset); + + DisplayData displayData = DisplayData.from(slidingWindowFn); + assertThat(displayData, hasDisplayItem("size", windowSize)); + assertThat(displayData, hasDisplayItem("period", period)); + assertThat(displayData, hasDisplayItem("offset", offset)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java new file mode 100644 index 0000000000..a9be77b37a --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; + +import com.google.api.client.util.Lists; + +import org.joda.time.Instant; + +import java.util.List; + +/** + * No-op {@link OnceTrigger} implementation for testing. + */ +abstract class StubTrigger extends Trigger.OnceTrigger { + /** + * Create a stub {@link Trigger} instance which returns the specified name on {@link #toString()}. + */ + static StubTrigger named(final String name) { + return new StubTrigger() { + @Override + public String toString() { + return name; + } + }; + } + + protected StubTrigger() { + super(Lists.>newArrayList()); + } + + @Override + protected void onOnlyFiring(TriggerContext context) throws Exception { + } + + @Override + public void onElement(OnElementContext c) throws Exception { + } + + @Override + public void onMerge(OnMergeContext c) throws Exception { + } + + @Override + public boolean shouldFire(TriggerContext context) throws Exception { + return false; + } + + @Override + protected Trigger getContinuationTrigger(List> continuationTriggers) { + return null; + } + + @Override + public Instant getWatermarkThatGuaranteesFiring(BoundedWindow window) { + return null; + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java index ddff33fbda..c6ee3517cc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java @@ -36,7 +36,7 @@ public class TriggerTest { @Test public void testTriggerToString() throws Exception { assertEquals("AfterWatermark.pastEndOfWindow()", AfterWatermark.pastEndOfWindow().toString()); - assertEquals("Repeatedly(AfterWatermark.pastEndOfWindow())", + assertEquals("Repeatedly.forever(AfterWatermark.pastEndOfWindow())", Repeatedly.forever(AfterWatermark.pastEndOfWindow()).toString()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java index 72f2b4c12d..970b815ccc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java @@ -16,7 +16,13 @@ package com.google.cloud.dataflow.sdk.transforms.windowing; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; + import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -32,6 +38,7 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.values.KV; @@ -223,4 +230,56 @@ public void processElement(ProcessContext c) throws Exception { pipeline.run(); } + + @Test + public void testDisplayData() { + FixedWindows windowFn = FixedWindows.of(Duration.standardHours(5)); + AfterWatermark.FromEndOfWindow triggerBuilder = AfterWatermark.pastEndOfWindow(); + Duration allowedLateness = Duration.standardMinutes(10); + Window.ClosingBehavior closingBehavior = Window.ClosingBehavior.FIRE_IF_NON_EMPTY; + OutputTimeFn outputTimeFn = OutputTimeFns.outputAtEndOfWindow(); + + Window.Bound window = Window + .into(windowFn) + .triggering(triggerBuilder) + .accumulatingFiredPanes() + .withAllowedLateness(allowedLateness, closingBehavior) + .withOutputTimeFn(outputTimeFn); + + DisplayData displayData = DisplayData.from(window); + + assertThat(displayData, hasDisplayItem("windowFn", windowFn.getClass())); + assertThat(displayData, includes(windowFn)); + + assertThat(displayData, hasDisplayItem("trigger", triggerBuilder.toString())); + assertThat(displayData, + hasDisplayItem("accumulationMode", AccumulationMode.ACCUMULATING_FIRED_PANES.toString())); + assertThat(displayData, + hasDisplayItem("allowedLateness", allowedLateness)); + assertThat(displayData, hasDisplayItem("closingBehavior", closingBehavior.toString())); + assertThat(displayData, hasDisplayItem("outputTimeFn", outputTimeFn.getClass())); + } + + @Test + public void testDisplayDataExcludesUnspecifiedProperties() { + Window.Bound window = Window.into(new GlobalWindows()); + + DisplayData displayData = DisplayData.from(window); + assertThat(displayData, not(hasDisplayItem(hasKey(isOneOf( + "trigger", + "outputTimeFn", + "accumulationMode", + "allowedLateness", + "closingBehavior"))))); + + } + + @Test + public void testDisplayDataExcludesDefaultTrigger() { + Window.Bound window = Window.into(new GlobalWindows()) + .triggering(DefaultTrigger.of()); + + DisplayData data = DisplayData.from(window); + assertThat(data, not(hasDisplayItem(hasKey("trigger")))); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java index 4b3a77ce61..eb3262bcac 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java @@ -15,12 +15,14 @@ */ package com.google.cloud.dataflow.sdk.util; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import org.joda.time.Duration; import org.joda.time.Instant; @@ -34,7 +36,7 @@ @RunWith(JUnit4.class) public class ReshuffleTriggerTest { - /** Public so that other tests can instantiate ReshufleTrigger. */ + /** Public so that other tests can instantiate {@link ReshuffleTrigger}. */ public static ReshuffleTrigger forTest() { return new ReshuffleTrigger<>(); } @@ -55,4 +57,10 @@ public void testOnTimer() throws Exception { tester.fireIfShouldFire(arbitraryWindow); assertFalse(tester.isMarkedFinished(arbitraryWindow)); } + + @Test + public void testToString() { + Trigger trigger = new ReshuffleTrigger<>(); + assertEquals("ReshuffleTrigger()", trigger.toString()); + } } From 211f071314adddd00640c45efae1c34663828c28 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 12 Apr 2016 10:08:37 -0700 Subject: [PATCH 336/751] Add display data to ParDo transforms (cherry picked from commit 77a77c9d159d7f9b1e6f645e54f0a4de86180bfe) --- .../inprocess/ForwardingPTransform.java | 6 ++ .../sdk/transforms/DoFnReflector.java | 6 ++ .../sdk/transforms/DoFnWithContext.java | 14 +++- .../cloud/dataflow/sdk/transforms/Filter.java | 27 +++++++ .../dataflow/sdk/transforms/GroupByKey.java | 8 ++ .../IntraBundleParallelization.java | 9 +++ .../cloud/dataflow/sdk/transforms/ParDo.java | 62 ++++++++++++---- .../dataflow/sdk/transforms/Partition.java | 13 ++++ .../DataflowPipelineTranslatorTest.java | 22 +++++- .../inprocess/ForwardingPTransformTest.java | 10 +++ .../sdk/transforms/DoFnWithContextTest.java | 11 +++ .../dataflow/sdk/transforms/FilterTest.java | 20 +++++ .../sdk/transforms/GroupByKeyTest.java | 16 ++++ .../IntraBundleParallelizationTest.java | 27 +++++++ .../dataflow/sdk/transforms/ParDoTest.java | 74 ++++++++++++++++--- .../sdk/transforms/PartitionTest.java | 13 ++++ 16 files changed, 308 insertions(+), 30 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java index b736e35d31..cd04336d05 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; import com.google.cloud.dataflow.sdk.values.TypedPValue; @@ -51,4 +52,9 @@ public Coder getDefaultOutputCoder(InputT input, @SuppressWarnings("unuse TypedPValue output) throws CannotProvideCoderException { return delegate().getDefaultOutputCoder(input, output); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + delegate().populateDisplayData(builder); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java index 1bb05fb340..678eb1d1be 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.FinishBundle; import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.ProcessElement; import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.StartBundle; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.UserCodeException; @@ -650,6 +651,11 @@ protected TypeDescriptor getOutputTypeDescriptor() { return fn.getOutputTypeDescriptor(); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + fn.populateDisplayData(builder); + } + private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java index 4f131adc91..452de2d10e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java @@ -24,6 +24,8 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.DoFn.DelegatingAggregator; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.WindowingInternals; @@ -81,7 +83,7 @@ * @param the type of the (main) output elements */ @Experimental -public abstract class DoFnWithContext implements Serializable { +public abstract class DoFnWithContext implements Serializable, HasDisplayData { /** Information accessible to all methods in this {@code DoFnWithContext}. */ public abstract class Context { @@ -413,4 +415,14 @@ public final Aggregator createAggregator( void prepareForProcessing() { aggregatorsAreFinal = true; } + + /** + * {@inheritDoc} + * + *

        By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(DisplayData.Builder builder) { + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java index 9e123a19fc..f0860d841f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; /** @@ -98,9 +99,15 @@ public void processElement(ProcessContext c) { c.output(c.element()); } } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Filter.populateDisplayData(builder, String.format("x < %s", value)); + } }); } + /** * Returns a {@code PTransform} that takes an input * {@code PCollection} and returns a {@code PCollection} with @@ -130,6 +137,11 @@ public void processElement(ProcessContext c) { c.output(c.element()); } } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Filter.populateDisplayData(builder, String.format("x > %s", value)); + } }); } @@ -162,6 +174,11 @@ public void processElement(ProcessContext c) { c.output(c.element()); } } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Filter.populateDisplayData(builder, String.format("x ≤ %s", value)); + } }); } @@ -194,6 +211,11 @@ public void processElement(ProcessContext c) { c.output(c.element()); } } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Filter.populateDisplayData(builder, String.format("x ≥ %s", value)); + } }); } @@ -231,4 +253,9 @@ public void processElement(ProcessContext c) { protected Coder getDefaultOutputCoder(PCollection input) { return input.getCoder(); } + + private static void populateDisplayData( + DisplayData.Builder builder, String predicateDescription) { + builder.add("predicate", predicateDescription); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java index 8fde3e0869..1125ea5e50 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.ValueWithMetadata; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; @@ -315,6 +316,13 @@ static KvCoder> getOutputKvCoder(Coder> inputCode return KvCoder.of(getKeyCoder(inputCoder), getOutputValueCoder(inputCoder)); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + if (fewKeys) { + builder.add("fewKeys", true); + } + } + ///////////////////////////////////////////////////////////////////////////// /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java index b6497b71c4..335cc6e412 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.options.GcsOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.WindowingInternals; @@ -170,6 +171,14 @@ public PCollection apply(PCollection input) { return input.apply( ParDo.of(new MultiThreadedIntraBundleProcessingDoFn<>(doFn, maxParallelism))); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("maxParallelism", maxParallelism) + .add("fn", doFn.getClass()) + .include(doFn); + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java index c77ac4447c..2ab61ba5ee 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; @@ -554,7 +555,12 @@ public static UnboundMulti withOutputTags( * properties can be set on it first. */ public static Bound of(DoFn fn) { - return new Unbound().of(fn); + return of(fn, fn.getClass()); + } + + private static Bound of( + DoFn fn, Class fnClass) { + return new Unbound().of(fn, fnClass); } private static DoFn @@ -577,7 +583,7 @@ public static Bound of(DoFn */ @Experimental public static Bound of(DoFnWithContext fn) { - return of(adapt(fn)); + return of(adapt(fn), fn.getClass()); } /** @@ -664,9 +670,15 @@ public UnboundMulti withOutputTags(TupleTag mainOutp * still be specified. */ public Bound of(DoFn fn) { - return new Bound<>(name, sideInputs, fn); + return of(fn, fn.getClass()); + } + + private Bound of( + DoFn fn, Class fnClass) { + return new Bound<>(name, sideInputs, fn, fnClass); } + /** * Returns a new {@link ParDo} {@link PTransform} that's like this * transform but which will invoke the given {@link DoFnWithContext} @@ -676,7 +688,7 @@ public Bound of(DoFn fn) { * still be specified. */ public Bound of(DoFnWithContext fn) { - return of(adapt(fn)); + return of(adapt(fn), fn.getClass()); } } @@ -697,13 +709,16 @@ public static class Bound // Inherits name. private final List> sideInputs; private final DoFn fn; + private final Class fnClass; Bound(String name, List> sideInputs, - DoFn fn) { + DoFn fn, + Class fnClass) { super(name); this.sideInputs = sideInputs; this.fn = SerializableUtils.clone(fn); + this.fnClass = fnClass; } /** @@ -714,7 +729,7 @@ public static class Bound *

        See the discussion of Naming above for more explanation. */ public Bound named(String name) { - return new Bound<>(name, sideInputs, fn); + return new Bound<>(name, sideInputs, fn, fnClass); } /** @@ -742,7 +757,7 @@ public Bound withSideInputs( ImmutableList.Builder> builder = ImmutableList.builder(); builder.addAll(this.sideInputs); builder.addAll(sideInputs); - return new Bound<>(name, builder.build(), fn); + return new Bound<>(name, builder.build(), fn, fnClass); } /** @@ -756,7 +771,7 @@ public Bound withSideInputs( public BoundMulti withOutputTags(TupleTag mainOutputTag, TupleTagList sideOutputTags) { return new BoundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags, fn); + name, sideInputs, mainOutputTag, sideOutputTags, fn, fnClass); } @Override @@ -797,7 +812,7 @@ protected String getKindString() { */ @Override public void populateDisplayData(Builder builder) { - builder.include(fn); + ParDo.populateDisplayData(builder, fn, fnClass); } public DoFn getFn() { @@ -889,8 +904,12 @@ public UnboundMulti withSideInputs( * more properties can still be specified. */ public BoundMulti of(DoFn fn) { + return of(fn, fn.getClass()); + } + + public BoundMulti of(DoFn fn, Class fnClass) { return new BoundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags, fn); + name, sideInputs, mainOutputTag, sideOutputTags, fn, fnClass); } /** @@ -902,7 +921,7 @@ public BoundMulti of(DoFn fn) { * more properties can still be specified. */ public BoundMulti of(DoFnWithContext fn) { - return of(adapt(fn)); + return of(adapt(fn), fn.getClass()); } } @@ -924,17 +943,20 @@ public static class BoundMulti private final TupleTag mainOutputTag; private final TupleTagList sideOutputTags; private final DoFn fn; + private final Class fnClass; BoundMulti(String name, List> sideInputs, TupleTag mainOutputTag, TupleTagList sideOutputTags, - DoFn fn) { + DoFn fn, + Class fnClass) { super(name); this.sideInputs = sideInputs; this.mainOutputTag = mainOutputTag; this.sideOutputTags = sideOutputTags; this.fn = SerializableUtils.clone(fn); + this.fnClass = fnClass; } /** @@ -946,7 +968,7 @@ public static class BoundMulti */ public BoundMulti named(String name) { return new BoundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags, fn); + name, sideInputs, mainOutputTag, sideOutputTags, fn, fnClass); } /** @@ -977,7 +999,7 @@ public BoundMulti withSideInputs( builder.addAll(sideInputs); return new BoundMulti<>( name, builder.build(), - mainOutputTag, sideOutputTags, fn); + mainOutputTag, sideOutputTags, fn, fnClass); } @@ -1025,6 +1047,11 @@ protected String getKindString() { } } + @Override + public void populateDisplayData(Builder builder) { + ParDo.populateDisplayData(builder, fn, fnClass); + } + public DoFn getFn() { return fn; } @@ -1231,6 +1258,13 @@ private static SideInputReader makeSideInputReader( return DirectSideInputReader.of(sideInputValues); } + private static void populateDisplayData( + DisplayData.Builder builder, DoFn fn, Class fnClass) { + builder + .include(fn, fnClass) + .add("fn", fnClass); + } + /** * A {@code DoFnRunner.OutputManager} that provides facilities for checking output values for * illegal mutations. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java index bbbccbc75d..623875caa8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.cloud.dataflow.sdk.values.PCollectionTuple; @@ -120,6 +121,11 @@ public PCollectionList apply(PCollection in) { return pcs; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.include(partitionDoFn); + } + private final transient PartitionDoFn partitionDoFn; private Partition(PartitionDoFn partitionDoFn) { @@ -169,5 +175,12 @@ public void processElement(ProcessContext c) { partition + " not in [0.." + numPartitions + ")"); } } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("numPartitions", numPartitions) + .add("partitionFn", partitionFn.getClass()); + } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 905fee25d6..04a6bbd9a9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -855,19 +855,28 @@ public void populateDisplayData(DisplayData.Builder builder) { Map parDo2Properties = steps.get(2).getProperties(); assertThat(parDo1Properties, hasKey("display_data")); + @SuppressWarnings("unchecked") Collection> fn1displayData = (Collection>) parDo1Properties.get("display_data"); + @SuppressWarnings("unchecked") Collection> fn2displayData = (Collection>) parDo2Properties.get("display_data"); - ImmutableSet> expectedFn1DisplayData = ImmutableSet.of( - ImmutableMap.builder() + ImmutableSet> expectedFn1DisplayData = ImmutableSet.of( + ImmutableMap.builder() .put("key", "foo") .put("type", "STRING") .put("value", "bar") .put("namespace", fn1.getClass().getName()) .build(), - ImmutableMap.builder() + ImmutableMap.builder() + .put("key", "fn") + .put("type", "JAVA_CLASS") + .put("value", fn1.getClass().getName()) + .put("shortValue", fn1.getClass().getSimpleName()) + .put("namespace", parDo1.getClass().getName()) + .build(), + ImmutableMap.builder() .put("key", "foo2") .put("type", "JAVA_CLASS") .put("value", DataflowPipelineTranslatorTest.class.getName()) @@ -879,6 +888,13 @@ public void populateDisplayData(DisplayData.Builder builder) { ); ImmutableSet> expectedFn2DisplayData = ImmutableSet.of( + ImmutableMap.builder() + .put("key", "fn") + .put("type", "JAVA_CLASS") + .put("value", fn2.getClass().getName()) + .put("shortValue", fn2.getClass().getSimpleName()) + .put("namespace", parDo2.getClass().getName()) + .build(), ImmutableMap.builder() .put("key", "foo3") .put("type", "INTEGER") diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java index 2e283f50b8..00e9785462 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java @@ -23,6 +23,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import org.junit.Before; @@ -97,4 +98,13 @@ public void getDefaultOutputCoderDelegates() throws Exception { when(delegate.getDefaultOutputCoder(input, output)).thenReturn(outputCoder); assertThat(forwarding.getDefaultOutputCoder(input, output), equalTo(outputCoder)); } + + @Test + public void populateDisplayDataDelegates() { + DisplayData.Builder builder = mock(DisplayData.Builder.class); + doThrow(RuntimeException.class).when(delegate).populateDisplayData(builder); + + thrown.expect(RuntimeException.class); + forwarding.populateDisplayData(builder); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java index 9f54a6e0ee..081293a383 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java @@ -17,8 +17,10 @@ package com.google.cloud.dataflow.sdk.transforms; import static org.hamcrest.CoreMatchers.isA; +import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -29,6 +31,7 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.junit.Rule; import org.junit.Test; @@ -159,7 +162,15 @@ public void testDoFnWithContextUsingAggregators() { } @Test + public void testDefaultPopulateDisplayDataImplementation() { + DoFnWithContext fn = new DoFnWithContext() { + }; + DisplayData displayData = DisplayData.from(fn); + assertThat(displayData.items(), empty()); + } + @Category(RunnableOnService.class) + @Test public void testCreateAggregatorInStartBundleThrows() { TestPipeline p = createTestPipeline(new DoFnWithContext() { @StartBundle diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java index 41a4ff2fbe..06f7821de5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java @@ -16,9 +16,14 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; + import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import org.junit.Test; @@ -157,4 +162,19 @@ public void testFilterGreaterThan() { DataflowAssert.that(output).containsInAnyOrder(5, 6, 7); p.run(); } + + @Test + public void testDisplayData() { + ParDo.Bound lessThan = Filter.lessThan(123); + assertThat(DisplayData.from(lessThan), hasDisplayItem("predicate", "x < 123")); + + ParDo.Bound lessThanOrEqual = Filter.lessThanEq(234); + assertThat(DisplayData.from(lessThanOrEqual), hasDisplayItem("predicate", "x ≤ 234")); + + ParDo.Bound greaterThan = Filter.greaterThan(345); + assertThat(DisplayData.from(greaterThan), hasDisplayItem("predicate", "x > 345")); + + ParDo.Bound greaterThanOrEqual = Filter.greaterThanEq(456); + assertThat(DisplayData.from(greaterThanOrEqual), hasDisplayItem("predicate", "x ≥ 456")); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java index 75eb92fcb4..175cc02bb0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java @@ -17,6 +17,9 @@ package com.google.cloud.dataflow.sdk.transforms; import static com.google.cloud.dataflow.sdk.TestUtils.KvMatcher.isKv; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.core.Is.is; @@ -35,6 +38,7 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.InvalidWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; @@ -435,4 +439,16 @@ public void processElement(ProcessContext c) throws Exception { public void testGroupByKeyGetName() { Assert.assertEquals("GroupByKey", GroupByKey.create().getName()); } + + @Test + public void testDisplayData() { + GroupByKey groupByKey = GroupByKey.create(); + GroupByKey groupByFewKeys = GroupByKey.create(true); + + DisplayData gbkDisplayData = DisplayData.from(groupByKey); + DisplayData fewKeysDisplayData = DisplayData.from(groupByFewKeys); + + assertThat(gbkDisplayData.items(), empty()); + assertThat(fewKeysDisplayData, hasDisplayItem("fewKeys", true)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java index 76dd67e097..1ed1973819 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java @@ -17,6 +17,9 @@ package com.google.cloud.dataflow.sdk.transforms; import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; + import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThanOrEqualTo; @@ -29,6 +32,7 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import org.junit.Before; import org.junit.Test; @@ -213,6 +217,29 @@ public void testIntraBundleParallelizationGetName() { IntraBundleParallelization.of(new DelayFn()).withMaxParallelism(1).getName()); } + @Test + public void testDisplayData() { + DoFn fn = new DoFn() { + @Override + public void processElement(ProcessContext c) throws Exception { + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + + PTransform transform = IntraBundleParallelization + .withMaxParallelism(1234) + .of(fn); + + DisplayData displayData = DisplayData.from(transform); + assertThat(displayData, includes(fn)); + assertThat(displayData, hasDisplayItem("fn", fn.getClass())); + assertThat(displayData, hasDisplayItem("maxParallelism", 1234)); + } + /** * Runs the provided doFn inside of an {@link IntraBundleParallelization} transform. * diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java index 1ff46e41c2..04baade57c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java @@ -18,9 +18,12 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; import static com.google.cloud.dataflow.sdk.util.StringUtils.jsonStringToByteArray; +import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.isA; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; @@ -44,6 +47,7 @@ import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.IllegalMutationException; @@ -1522,20 +1526,66 @@ public void testMutatingInputCoderDoFnError() throws Exception { } @Test - public void testIncludesDoFnDisplayData() { - Bound parDo = - ParDo.of( - new DoFn() { - @Override - public void processElement(ProcessContext c) {} + public void testDoFnDisplayData() { + DoFn fn = new DoFn() { + @Override + public void processElement(ProcessContext c) { + } - @Override - public void populateDisplayData(Builder builder) { - builder.add("foo", "bar"); - } - }); + @Override + public void populateDisplayData(Builder builder) { + builder.add("doFnMetadata", "bar"); + } + }; + + Bound parDo = ParDo.of(fn); + + DisplayData displayData = DisplayData.from(parDo); + assertThat(displayData, hasDisplayItem(allOf( + hasKey("fn"), + hasType(DisplayData.Type.JAVA_CLASS), + DisplayDataMatchers.hasValue(fn.getClass().getName())))); + + assertThat(displayData, includes(fn)); + } + + @Test + public void testDoFnWithContextDisplayData() { + DoFnWithContext fn = new DoFnWithContext() { + @ProcessElement + public void proccessElement(ProcessContext c) {} + + @Override + public void populateDisplayData(Builder builder) { + builder.add("fnMetadata", "foobar"); + } + }; + + Bound parDo = ParDo.of(fn); + + DisplayData displayData = DisplayData.from(parDo); + assertThat(displayData, includes(fn)); + assertThat(displayData, hasDisplayItem("fn", fn.getClass())); + } + + @Test + public void testWithOutputTagsDisplayData() { + DoFnWithContext fn = new DoFnWithContext() { + @ProcessElement + public void proccessElement(ProcessContext c) {} + + @Override + public void populateDisplayData(Builder builder) { + builder.add("fnMetadata", "foobar"); + } + }; + + ParDo.BoundMulti parDo = ParDo + .withOutputTags(new TupleTag(), TupleTagList.empty()) + .of(fn); DisplayData displayData = DisplayData.from(parDo); - assertThat(displayData, hasDisplayItem(hasKey("foo"))); + assertThat(displayData, includes(fn)); + assertThat(displayData, hasDisplayItem("fn", fn.getClass())); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java index 5121a0a881..c24b3690c8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java @@ -16,6 +16,9 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -24,6 +27,7 @@ import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Partition.PartitionFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionList; @@ -137,4 +141,13 @@ public void testDroppedPartition() { public void testPartitionGetName() { assertEquals("Partition", Partition.of(3, new ModFn()).getName()); } + + @Test + public void testDisplayData() { + Partition partition = Partition.of(123, new IdentityFn()); + DisplayData displayData = DisplayData.from(partition); + + assertThat(displayData, hasDisplayItem("numPartitions", 123)); + assertThat(displayData, hasDisplayItem("partitionFn", IdentityFn.class)); + } } From 20e12d1690fe757214efe82c40b5f9c42d0fd872 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 11 Apr 2016 09:08:23 -0700 Subject: [PATCH 337/751] Add DisplayData for combine transforms If more than one combineFn have the same namespace, add a sequential suffix. This is necessary because each namespace/key pair must be unique within the transform. Add a `JavaClass` wrapper around a name/simple-name for a class. This is necessary in cases where the class may be serialized to support accessing `DisplayData` since `Class` is not serializable in some cases. (cherry picked from commit b0baa4c9d66750b1cbdbb0dc7f02e62385436bc2) --- .../sdk/transforms/ApproximateQuantiles.java | 8 + .../sdk/transforms/ApproximateUnique.java | 44 +++++ .../dataflow/sdk/transforms/Combine.java | 154 ++++++++++++++---- .../sdk/transforms/CombineFnBase.java | 27 ++- .../dataflow/sdk/transforms/CombineFns.java | 65 ++++++++ .../sdk/transforms/CombineWithContext.java | 6 + .../cloud/dataflow/sdk/transforms/Max.java | 6 + .../cloud/dataflow/sdk/transforms/Min.java | 6 + .../cloud/dataflow/sdk/transforms/Sample.java | 14 ++ .../cloud/dataflow/sdk/transforms/Top.java | 8 + .../transforms/display/ClassForDisplay.java | 91 +++++++++++ .../sdk/transforms/display/DisplayData.java | 111 +++++++++++-- .../dataflow/sdk/util/CombineFnUtil.java | 9 + .../transforms/ApproximateQuantilesTest.java | 14 ++ .../sdk/transforms/ApproximateUniqueTest.java | 18 ++ .../sdk/transforms/CombineFnsTest.java | 69 +++++++- .../dataflow/sdk/transforms/CombineTest.java | 21 +++ .../dataflow/sdk/transforms/MaxTest.java | 12 ++ .../dataflow/sdk/transforms/MinTest.java | 13 ++ .../dataflow/sdk/transforms/SampleTest.java | 15 ++ .../dataflow/sdk/transforms/TopTest.java | 14 ++ .../display/ClassForDisplayTest.java | 64 ++++++++ .../display/DisplayDataMatchers.java | 51 +++--- .../transforms/display/DisplayDataTest.java | 18 +- .../sdk/transforms/CombineJava8Test.java | 42 +++++ .../display/ClassForDisplayJava8Test.java | 46 ++++++ 26 files changed, 875 insertions(+), 71 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplay.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayTest.java create mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayJava8Test.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java index 57dd51009b..0f4e738993 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.coders.ListCoder; import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn.Accumulator; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.WeightedValue; import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; import com.google.cloud.dataflow.sdk.values.KV; @@ -357,6 +358,13 @@ public Coder> getAccumulatorCoder( CoderRegistry registry, Coder elementCoder) { return new QuantileStateCoder<>(compareFn, elementCoder); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("numQuantiles", numQuantiles) + .add("comparer", compareFn.getClass()); + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java index 3c936a2b13..27176f6f33 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java @@ -23,12 +23,15 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.hash.Hashing; import com.google.common.hash.HashingOutputStream; import com.google.common.io.ByteStreams; +import org.apache.avro.reflect.Nullable; + import java.io.IOException; import java.io.Serializable; import java.util.Arrays; @@ -165,6 +168,12 @@ static class Globally extends PTransform, PCollection> { */ private final long sampleSize; + /** + * The desired maximum estimation error or null if not specified. + */ + @Nullable + private final Double maximumEstimationError; + /** * @see ApproximateUnique#globally(int) */ @@ -176,7 +185,9 @@ public Globally(int sampleSize) { + "In general, the estimation " + "error is about 2 / sqrt(sampleSize)."); } + this.sampleSize = sampleSize; + this.maximumEstimationError = null; } /** @@ -188,7 +199,9 @@ public Globally(double maximumEstimationError) { "ApproximateUnique needs an " + "estimation error between 1% (0.01) and 50% (0.5)."); } + this.sampleSize = sampleSizeFromEstimationError(maximumEstimationError); + this.maximumEstimationError = maximumEstimationError; } @Override @@ -198,6 +211,11 @@ public PCollection apply(PCollection input) { Combine.globally( new ApproximateUniqueCombineFn<>(sampleSize, coder))); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + ApproximateUnique.populateDisplayData(builder, sampleSize, maximumEstimationError); + } } /** @@ -211,8 +229,18 @@ public PCollection apply(PCollection input) { static class PerKey extends PTransform>, PCollection>> { + /** + * The number of entries in the statistical sample; the higher this number, + * the more accurate the estimate will be. + */ private final long sampleSize; + /** + * The the desired maximum estimation error or null if not specified. + */ + @Nullable + private final Double maximumEstimationError; + /** * @see ApproximateUnique#perKey(int) */ @@ -223,7 +251,9 @@ public PerKey(int sampleSize) { + "sampleSize >= 16 for an estimation error <= 50%. In general, " + "the estimation error is about 2 / sqrt(sampleSize)."); } + this.sampleSize = sampleSize; + this.maximumEstimationError = null; } /** @@ -235,7 +265,9 @@ public PerKey(double estimationError) { "ApproximateUnique.PerKey needs an " + "estimation error between 1% (0.01) and 50% (0.5)."); } + this.sampleSize = sampleSizeFromEstimationError(estimationError); + this.maximumEstimationError = estimationError; } @Override @@ -252,6 +284,11 @@ public PCollection> apply(PCollection> input) { Combine.perKey(new ApproximateUniqueCombineFn<>( sampleSize, coder).asKeyedFn())); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + ApproximateUnique.populateDisplayData(builder, sampleSize, maximumEstimationError); + } } @@ -416,4 +453,11 @@ static long hash(T element, Coder coder) throws CoderException, IOExcepti static long sampleSizeFromEstimationError(double estimationError) { return Math.round(Math.ceil(4.0 / Math.pow(estimationError, 2.0))); } + + private static void populateDisplayData( + DisplayData.Builder builder, long sampleSize, Double maxEstimationError) { + builder + .add("sampleSize", sampleSize) + .addIfNotNull("maximumEstimationError", maxEstimationError); + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java index b8d20e303f..22afcce409 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java @@ -34,6 +34,9 @@ import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; +import com.google.cloud.dataflow.sdk.transforms.display.ClassForDisplay; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; @@ -97,9 +100,10 @@ private Combine() { */ public static Globally globally( SerializableFunction, V> combiner) { - return globally(IterableCombineFn.of(combiner)); + return globally(IterableCombineFn.of(combiner), ClassForDisplay.fromInstance(combiner)); } + /** * Returns a {@link Globally Combine.Globally} {@code PTransform} * that uses the given {@code GloballyCombineFn} to combine all @@ -117,7 +121,12 @@ public static Globally globally( */ public static Globally globally( GlobalCombineFn fn) { - return new Globally<>(fn, true, 0); + return globally(fn, ClassForDisplay.fromInstance(fn)); + } + + private static Globally globally( + GlobalCombineFn fn, ClassForDisplay fnClass) { + return new Globally<>(fn, fnClass, true, 0); } /** @@ -138,7 +147,7 @@ public static Globally globally( */ public static PerKey perKey( SerializableFunction, V> fn) { - return perKey(Combine.IterableCombineFn.of(fn)); + return perKey(IterableCombineFn.of(fn).asKeyedFn(), ClassForDisplay.fromInstance(fn)); } /** @@ -159,7 +168,7 @@ public static PerKey perKey( */ public static PerKey perKey( GlobalCombineFn fn) { - return perKey(fn.asKeyedFn()); + return perKey(fn.asKeyedFn(), ClassForDisplay.fromInstance(fn)); } /** @@ -180,7 +189,12 @@ public static PerKey perKey( */ public static PerKey perKey( PerKeyCombineFn fn) { - return new PerKey<>(fn, false /*fewKeys*/); + return perKey(fn, ClassForDisplay.fromInstance(fn)); + } + + private static PerKey perKey( + PerKeyCombineFn fn, ClassForDisplay fnClass) { + return new PerKey<>(fn, fnClass, false /*fewKeys*/); } /** @@ -188,8 +202,8 @@ public static PerKey perKey( * in {@link GroupByKey}. */ private static PerKey fewKeys( - PerKeyCombineFn fn) { - return new PerKey<>(fn, true /*fewKeys*/); + PerKeyCombineFn fn, ClassForDisplay fnClass) { + return new PerKey<>(fn, fnClass, true /*fewKeys*/); } /** @@ -215,7 +229,7 @@ private static PerKey fewKeys( */ public static GroupedValues groupedValues( SerializableFunction, V> fn) { - return groupedValues(IterableCombineFn.of(fn)); + return groupedValues(IterableCombineFn.of(fn).asKeyedFn(), ClassForDisplay.fromInstance(fn)); } /** @@ -241,7 +255,7 @@ public static GroupedValues groupedValues( */ public static GroupedValues groupedValues( GlobalCombineFn fn) { - return groupedValues(fn.asKeyedFn()); + return groupedValues(fn.asKeyedFn(), ClassForDisplay.fromInstance(fn)); } /** @@ -267,9 +281,13 @@ public static GroupedValues groupedValu */ public static GroupedValues groupedValues( PerKeyCombineFn fn) { - return new GroupedValues<>(fn); + return groupedValues(fn, ClassForDisplay.fromInstance(fn)); } + private static GroupedValues groupedValues( + PerKeyCombineFn fn, ClassForDisplay fnClass) { + return new GroupedValues<>(fn, fnClass); + } ///////////////////////////////////////////////////////////////////////////// @@ -491,6 +509,11 @@ public Coder getDefaultOutputCoder( public CombineFn forKey(K key, Coder keyCoder) { return CombineFn.this; } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + CombineFn.this.populateDisplayData(builder); + } }; } } @@ -1164,6 +1187,11 @@ public Coder getDefaultOutputCoder( CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { return KeyedCombineFn.this.getDefaultOutputCoder(registry, keyCoder, inputCoder); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + KeyedCombineFn.this.populateDisplayData(builder); + } }; } @@ -1229,31 +1257,36 @@ public static class Globally extends PTransform, PCollection> { private final GlobalCombineFn fn; + private final ClassForDisplay fnClass; private final boolean insertDefault; private final int fanout; private final List> sideInputs; - private Globally(GlobalCombineFn fn, + private Globally(GlobalCombineFn fn, ClassForDisplay fnClass, boolean insertDefault, int fanout) { this.fn = fn; + this.fnClass = fnClass; this.insertDefault = insertDefault; this.fanout = fanout; this.sideInputs = ImmutableList.>of(); } private Globally(String name, GlobalCombineFn fn, - boolean insertDefault, int fanout) { + ClassForDisplay fnClass, boolean insertDefault, int fanout) { super(name); this.fn = fn; + this.fnClass = fnClass; this.insertDefault = insertDefault; this.fanout = fanout; this.sideInputs = ImmutableList.>of(); } private Globally(String name, GlobalCombineFn fn, - boolean insertDefault, int fanout, List> sideInputs) { + ClassForDisplay fnClass, boolean insertDefault, int fanout, + List> sideInputs) { super(name); this.fn = fn; + this.fnClass = fnClass; this.insertDefault = insertDefault; this.fanout = fanout; this.sideInputs = sideInputs; @@ -1264,7 +1297,7 @@ private Globally(String name, GlobalCombineFn fn, * specified name. Does not modify this transform. */ public Globally named(String name) { - return new Globally<>(name, fn, insertDefault, fanout); + return new Globally<>(name, fn, fnClass, insertDefault, fanout); } /** @@ -1275,7 +1308,7 @@ public Globally named(String name) { * to an empty input set will be returned. */ public GloballyAsSingletonView asSingletonView() { - return new GloballyAsSingletonView<>(fn, insertDefault, fanout); + return new GloballyAsSingletonView<>(fn, fnClass, insertDefault, fanout); } /** @@ -1284,7 +1317,7 @@ public GloballyAsSingletonView asSingletonView() { * is not globally windowed and the output is not being used as a side input. */ public Globally withoutDefaults() { - return new Globally<>(name, fn, false, fanout); + return new Globally<>(name, fn, fnClass, false, fanout); } /** @@ -1295,7 +1328,7 @@ public Globally withoutDefaults() { * that will be used. */ public Globally withFanout(int fanout) { - return new Globally<>(name, fn, insertDefault, fanout); + return new Globally<>(name, fn, fnClass, insertDefault, fanout); } /** @@ -1305,7 +1338,7 @@ public Globally withFanout(int fanout) { public Globally withSideInputs( Iterable> sideInputs) { Preconditions.checkState(fn instanceof RequiresContextInternal); - return new Globally(name, fn, insertDefault, fanout, + return new Globally(name, fn, fnClass, insertDefault, fanout, ImmutableList.>copyOf(sideInputs)); } @@ -1316,7 +1349,7 @@ public PCollection apply(PCollection input) { .setCoder(KvCoder.of(VoidCoder.of(), input.getCoder())); Combine.PerKey combine = - Combine.fewKeys(fn.asKeyedFn()); + Combine.fewKeys(fn.asKeyedFn(), fnClass); if (!sideInputs.isEmpty()) { combine = combine.withSideInputs(sideInputs); } @@ -1340,6 +1373,12 @@ public PCollection apply(PCollection input) { } } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Combine.populateDisplayData(builder, fn, fnClass); + Combine.populateGlobalDisplayData(builder, fanout, insertDefault); + } + private PCollection insertDefaultValueIfEmpty(PCollection maybeEmpty) { final PCollectionView> maybeEmptyView = maybeEmpty.apply( View.asIterable()); @@ -1366,6 +1405,20 @@ public void processElement(DoFn.ProcessContext c) { } } + private static void populateDisplayData( + DisplayData.Builder builder, HasDisplayData fn, ClassForDisplay fnClass) { + builder + .include(fn, fnClass) + .add("combineFn", fnClass); + } + + private static void populateGlobalDisplayData( + DisplayData.Builder builder, int fanout, boolean insertDefault) { + builder + .addIfNotDefault("fanout", fanout, 0) + .add("emitDefaultOnEmptyInput", insertDefault); + } + /** * {@code Combine.GloballyAsSingletonView} takes a {@code PCollection} * and returns a {@code PCollectionView} whose elements are the result of @@ -1409,12 +1462,15 @@ public static class GloballyAsSingletonView extends PTransform, PCollectionView> { private final GlobalCombineFn fn; + private final ClassForDisplay fnClass; private final boolean insertDefault; private final int fanout; private GloballyAsSingletonView( - GlobalCombineFn fn, boolean insertDefault, int fanout) { + GlobalCombineFn fn, ClassForDisplay fnClass, + boolean insertDefault, int fanout) { this.fn = fn; + this.fnClass = fnClass; this.insertDefault = insertDefault; this.fanout = fanout; } @@ -1445,6 +1501,12 @@ public boolean getInsertDefault() { public GlobalCombineFn getCombineFn() { return fn; } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Combine.populateDisplayData(builder, fn, fnClass); + Combine.populateGlobalDisplayData(builder, fanout, insertDefault); + } } /** @@ -1524,6 +1586,11 @@ public List compact(List accumulator) { return accumulator.size() > 1 ? mergeToSingleton(accumulator) : accumulator; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("combineFn", combiner.getClass()); + } + private List mergeToSingleton(Iterable values) { List singleton = new ArrayList<>(); singleton.add(combiner.apply(values)); @@ -1597,30 +1664,35 @@ public static class PerKey extends PTransform>, PCollection>> { private final transient PerKeyCombineFn fn; + private final ClassForDisplay fnClass; private final boolean fewKeys; private final List> sideInputs; private PerKey( - PerKeyCombineFn fn, boolean fewKeys) { + PerKeyCombineFn fn, ClassForDisplay fnClass, + boolean fewKeys) { this.fn = fn; + this.fnClass = fnClass; this.fewKeys = fewKeys; this.sideInputs = ImmutableList.of(); } private PerKey(String name, - PerKeyCombineFn fn, + PerKeyCombineFn fn, ClassForDisplay fnClass, boolean fewKeys, List> sideInputs) { super(name); this.fn = fn; + this.fnClass = fnClass; this.fewKeys = fewKeys; this.sideInputs = sideInputs; } private PerKey( String name, PerKeyCombineFn fn, - boolean fewKeys) { + ClassForDisplay fnClass, boolean fewKeys) { super(name); this.fn = fn; + this.fnClass = fnClass; this.fewKeys = fewKeys; this.sideInputs = ImmutableList.of(); } @@ -1630,7 +1702,7 @@ private PerKey( * specified name. Does not modify this transform. */ public PerKey named(String name) { - return new PerKey(name, fn, fewKeys); + return new PerKey(name, fn, fnClass, fewKeys); } /** @@ -1640,7 +1712,7 @@ public PerKey named(String name) { public PerKey withSideInputs( Iterable> sideInputs) { Preconditions.checkState(fn instanceof RequiresContextInternal); - return new PerKey(name, fn, fewKeys, + return new PerKey(name, fn, fnClass, fewKeys, ImmutableList.>copyOf(sideInputs)); } @@ -1657,7 +1729,7 @@ public PerKey withSideInputs( */ public PerKeyWithHotKeyFanout withHotKeyFanout( SerializableFunction hotKeyFanout) { - return new PerKeyWithHotKeyFanout(name, fn, hotKeyFanout); + return new PerKeyWithHotKeyFanout(name, fn, fnClass, hotKeyFanout); } /** @@ -1665,7 +1737,7 @@ public PerKeyWithHotKeyFanout withHotKeyFanout( * constant value for every key. */ public PerKeyWithHotKeyFanout withHotKeyFanout(final int hotKeyFanout) { - return new PerKeyWithHotKeyFanout(name, fn, + return new PerKeyWithHotKeyFanout(name, fn, fnClass, new SerializableFunction(){ @Override public Integer apply(K unused) { @@ -1694,6 +1766,11 @@ public PCollection> apply(PCollection> input) { .apply(GroupByKey.create(fewKeys)) .apply(Combine.groupedValues(fn).withSideInputs(sideInputs)); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Combine.populateDisplayData(builder, fn, fnClass); + } } /** @@ -1703,13 +1780,16 @@ public static class PerKeyWithHotKeyFanout extends PTransform>, PCollection>> { private final transient PerKeyCombineFn fn; + private final ClassForDisplay fnClass; private final SerializableFunction hotKeyFanout; private PerKeyWithHotKeyFanout(String name, PerKeyCombineFn fn, + ClassForDisplay fnClass, SerializableFunction hotKeyFanout) { super(name); this.fn = fn; + this.fnClass = fnClass; this.hotKeyFanout = hotKeyFanout; } @@ -1992,6 +2072,12 @@ public void processElement(ProcessContext c) { .apply("PostCombine", Combine.perKey(postCombine)); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Combine.populateDisplayData(builder, fn, fnClass); + builder.add("fanoutFn", hotKeyFanout.getClass()); + } + /** * Used to store either an input or accumulator value, for flattening * the hot and cold key paths. @@ -2133,23 +2219,28 @@ public static class GroupedValues PCollection>> { private final PerKeyCombineFn fn; + private final ClassForDisplay fnClass; private final List> sideInputs; - private GroupedValues(PerKeyCombineFn fn) { + private GroupedValues( + PerKeyCombineFn fn, ClassForDisplay fnClass) { this.fn = SerializableUtils.clone(fn); + this.fnClass = fnClass; this.sideInputs = ImmutableList.>of(); } private GroupedValues( PerKeyCombineFn fn, + ClassForDisplay fnClass, List> sideInputs) { this.fn = SerializableUtils.clone(fn); + this.fnClass = fnClass; this.sideInputs = sideInputs; } public GroupedValues withSideInputs( Iterable> sideInputs) { - return new GroupedValues<>(fn, ImmutableList.>copyOf(sideInputs)); + return new GroupedValues<>(fn, fnClass, ImmutableList.>copyOf(sideInputs)); } /** @@ -2236,5 +2327,10 @@ public Coder> getDefaultOutputCoder( kvCoder.getKeyCoder(), kvCoder.getValueCoder()); return KvCoder.of(kvCoder.getKeyCoder(), outputValueCoder); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Combine.populateDisplayData(builder, fn, fnClass); + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java index a0b06cf1fc..d278858478 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java @@ -22,6 +22,8 @@ import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.collect.ImmutableMap; @@ -49,7 +51,7 @@ public class CombineFnBase { * @param type of mutable accumulator values * @param type of output values */ - public interface GlobalCombineFn extends Serializable { + public interface GlobalCombineFn extends Serializable, HasDisplayData { /** * Returns the {@code Coder} to use for accumulator {@code AccumT} @@ -114,7 +116,8 @@ public Coder getDefaultOutputCoder(CoderRegistry registry, Coder type of mutable accumulator values * @param type of output values */ - public interface PerKeyCombineFn extends Serializable { + public interface PerKeyCombineFn + extends Serializable, HasDisplayData { /** * Returns the {@code Coder} to use for accumulator {@code AccumT} * values, or null if it is not able to be inferred. @@ -214,6 +217,16 @@ public TypeVariable getOutputTVariable() { return (TypeVariable) new TypeDescriptor(AbstractGlobalCombineFn.class) {}.getType(); } + + /** + * {@inheritDoc} + * + *

        By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(DisplayData.Builder builder) { + } } /** @@ -279,5 +292,15 @@ public TypeVariable getOutputTVariable() { return (TypeVariable) new TypeDescriptor(AbstractPerKeyCombineFn.class) {}.getType(); } + + /** + * {@inheritDoc} + * + *

        By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(DisplayData.Builder builder) { + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java index 656c010d91..120dbbf573 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java @@ -29,12 +29,17 @@ import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -43,6 +48,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; +import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -451,6 +457,11 @@ public Coder getAccumulatorCoder(CoderRegistry registry, Coder } return new ComposedAccumulatorCoder(coders); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + CombineFns.populateDisplayData(builder, combineFns); + } } /** @@ -584,6 +595,11 @@ public Coder getAccumulatorCoder(CoderRegistry registry, Coder } return new ComposedAccumulatorCoder(coders); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + CombineFns.populateDisplayData(builder, combineFnWithContexts); + } } /** @@ -765,6 +781,11 @@ public Coder getAccumulatorCoder( } return new ComposedAccumulatorCoder(coders); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + CombineFns.populateDisplayData(builder, keyedCombineFns); + } } /** @@ -911,6 +932,11 @@ public Coder getAccumulatorCoder( } return new ComposedAccumulatorCoder(coders); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + CombineFns.populateDisplayData(builder, keyedCombineFns); + } } ///////////////////////////////////////////////////////////////////////////// @@ -1097,4 +1123,43 @@ private static void checkUniqueness( "Cannot compose with tuple tag %s because it is already present in the composition.", outputTag); } + + /** + * Populate display data for the {@code combineFns} that make up a composed combine transform. + * + *

        The same combineFn class may be used multiple times, in which case we must take special care + * to register display data with unique namespaces. + */ + private static void populateDisplayData( + DisplayData.Builder builder, List combineFns) { + + // NB: ArrayListMultimap necessary to maintain ordering of combineFns of the same type. + Multimap, HasDisplayData> combineFnMap = ArrayListMultimap.create(); + + for (int i = 0; i < combineFns.size(); i++) { + HasDisplayData combineFn = combineFns.get(i); + builder.add("combineFn" + (i + 1), combineFn.getClass()); + combineFnMap.put(combineFn.getClass(), combineFn); + } + + for (Map.Entry, Collection> combineFnEntries : + combineFnMap.asMap().entrySet()) { + + Collection classCombineFns = combineFnEntries.getValue(); + if (classCombineFns.size() == 1) { + // Only one combineFn of this type, include it directly. + builder.include(Iterables.getOnlyElement(classCombineFns)); + + } else { + // Multiple combineFns of same type, add a namespace suffix so display data is + // unique and ordered. + String baseNamespace = combineFnEntries.getKey().getName(); + for (int i = 0; i < combineFns.size(); i++) { + HasDisplayData combineFn = combineFns.get(i); + String namespace = String.format("%s#%d", baseNamespace, i + 1); + builder.include(combineFn, namespace); + } + } + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java index fdf56e33c0..b26636ee20 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollectionView; /** @@ -165,6 +166,11 @@ public Coder getDefaultOutputCoder(CoderRegistry registry, Coder key public CombineFnWithContext forKey(K key, Coder keyCoder) { return CombineFnWithContext.this; } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + CombineFnWithContext.this.populateDisplayData(builder); + } }; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java index 8678e4f33e..70e541c42e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms; import com.google.cloud.dataflow.sdk.transforms.Combine.BinaryCombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.common.Counter; import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; import com.google.cloud.dataflow.sdk.util.common.CounterProvider; @@ -203,6 +204,11 @@ public T identity() { public T apply(T left, T right) { return comparator.compare(left, right) >= 0 ? left : right; } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("comparer", comparator.getClass()); + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java index 47ab3a0ad2..5e9d7041c8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.transforms; import com.google.cloud.dataflow.sdk.transforms.Combine.BinaryCombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.common.Counter; import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; import com.google.cloud.dataflow.sdk.util.common.CounterProvider; @@ -203,6 +204,11 @@ public T identity() { public T apply(T left, T right) { return comparator.compare(left, right) <= 0 ? left : right; } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("comparer", comparator.getClass()); + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java index c5b6e7ec14..a72443ce49 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java @@ -23,6 +23,7 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; @@ -151,6 +152,11 @@ public PCollection apply(PCollection in) { .of(new SampleAnyDoFn<>(limit, iterableView))) .setCoder(in.getCoder()); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("sampleSize", limit); + } } /** @@ -186,6 +192,7 @@ public static class FixedSizedSampleFn extends CombineFn, SerializableComparator>>, Iterable> { + private final int sampleSize; private final Top.TopCombineFn, SerializableComparator>> topCombineFn; private final Random rand = new Random(); @@ -194,6 +201,8 @@ private FixedSizedSampleFn(int sampleSize) { if (sampleSize < 0) { throw new IllegalArgumentException("sample size must be >= 0"); } + + this.sampleSize = sampleSize; topCombineFn = new Top.TopCombineFn, SerializableComparator>>( sampleSize, new KV.OrderByKey()); } @@ -242,5 +251,10 @@ public Coder> getDefaultOutputCoder( CoderRegistry registry, Coder inputCoder) { return IterableCoder.of(inputCoder); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("sampleSize", sampleSize); + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java index 98fe53c0a8..e46da47539 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn.Accumulator; import com.google.cloud.dataflow.sdk.transforms.Combine.PerKey; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; @@ -390,6 +391,13 @@ public Coder> getAccumulatorCoder( return new BoundedHeapCoder<>(count, compareFn, inputCoder); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("count", count) + .add("comparer", compareFn.getClass()); + } + @Override public String getIncompatibleGlobalWindowErrorMessage() { return "Default values are not supported in Top.[of, smallest, largest]() if the output " diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplay.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplay.java new file mode 100644 index 0000000000..7316c2a272 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplay.java @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.io.Serializable; +import java.util.Objects; + +/** + * Display metadata representing a Java class. + *

        + *

        Java classes can be registered as display metadata via + * {@link DisplayData.Builder#add(String, ClassForDisplay)}. {@link ClassForDisplay} is + * serializable, unlike {@link Class} which can fail to serialize for Java 8 lambda functions. + */ +public class ClassForDisplay implements Serializable { + private final String simpleName; + private final String name; + + private ClassForDisplay(Class clazz) { + name = clazz.getName(); + simpleName = clazz.getSimpleName(); + } + + /** + * Create a {@link ClassForDisplay} instance representing the specified class. + */ + public static ClassForDisplay of(Class clazz) { + return new ClassForDisplay(checkNotNull(clazz)); + } + + /** + * Create a {@link ClassForDisplay} from the class of the specified object instance. + */ + public static ClassForDisplay fromInstance(Object obj) { + checkNotNull(obj); + return new ClassForDisplay(obj.getClass()); + } + + /** + * Retrieve the fully-qualified name of the class. + * + * @see Class#getName() + */ + public String getName() { + return name; + } + + /** + * Retrieve a simple representation of the class name. + * + * @see Class#getSimpleName() + */ + public String getSimpleName() { + return simpleName; + } + + @Override + public String toString() { + return name; + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof ClassForDisplay) { + ClassForDisplay that = (ClassForDisplay) obj; + return Objects.equals(this.name, that.name); + } + + return false; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 71440124f4..006f088a90 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -126,7 +126,7 @@ public String toString() { return builder.toString(); } - private static String namespaceOf(Class clazz) { + private static String namespaceOf(ClassForDisplay clazz) { return clazz.getName(); } @@ -136,18 +136,34 @@ private static String namespaceOf(Class clazz) { */ public interface Builder { /** - * Register display metadata from the specified subcomponent. For example, a {@link ParDo} - * transform includes display metadata from the encapsulated {@link DoFn}. + * Register display metadata from the specified subcomponent. + * + * @see #include(HasDisplayData, String) */ Builder include(HasDisplayData subComponent); /** * Register display metadata from the specified subcomponent, using the specified namespace. - * For example, a {@link ParDo} transform includes display metadata from the encapsulated - * {@link DoFn}. + * + * @see #include(HasDisplayData, String) */ Builder include(HasDisplayData subComponent, Class namespace); + /** + * Register display metadata from the specified subcomponent, using the specified namespace. + * + * @see #include(HasDisplayData, String) + */ + Builder include(HasDisplayData subComponent, ClassForDisplay namespace); + + /** + * Register display metadata from the specified subcomponent, using the specified namespace. + * + *

        For example, a {@link ParDo} transform includes display metadata from the encapsulated + * {@link DoFn}. + */ + Builder include(HasDisplayData subComponent, String namespace); + /** * Register the given string display metadata. The metadata item will be registered with type * {@link DisplayData.Type#STRING}, and is identified by the specified key and namespace from @@ -286,6 +302,13 @@ ItemBuilder addIfNotDefault( */ ItemBuilder add(String key, Class value); + /** + * Register the given class display metadata. The metadata item will be registered with type + * {@link DisplayData.Type#JAVA_CLASS}, and is identified by the specified key and namespace + * from the current transform or component. + */ + ItemBuilder add(String key, ClassForDisplay value); + /** * Register the given class display data if the value is not null. * @@ -293,6 +316,13 @@ ItemBuilder addIfNotDefault( */ ItemBuilder addIfNotNull(String key, @Nullable Class value); + /** + * Register the given class display data if the value is not null. + * + * @see DisplayData.Builder#add(String, ClassForDisplay) + */ + ItemBuilder addIfNotNull(String key, @Nullable ClassForDisplay value); + /** * Register the given class display data if the value is different than the specified default. * @@ -301,6 +331,13 @@ ItemBuilder addIfNotDefault( ItemBuilder addIfNotDefault( String key, @Nullable Class value, @Nullable Class defaultValue); + /** + * Register the given class display data if the value is different than the specified default. + * + * @see DisplayData.Builder#add(String, ClassForDisplay) + */ + ItemBuilder addIfNotDefault( + String key, @Nullable ClassForDisplay value, @Nullable ClassForDisplay defaultValue); /** * Register the given display metadata with the specified type. * @@ -343,6 +380,14 @@ public interface ItemBuilder extends Builder { *

        Leaving the namespace unspecified will default to the registering instance's class. */ ItemBuilder withNamespace(Class namespace); + + /** + * Adds an explicit namespace to the most-recently added display metadata. The namespace + * and key uniquely identify the display metadata. + * + *

        Leaving the namespace unspecified will default to the registering instance's class. + */ + ItemBuilder withNamespace(ClassForDisplay namespace); } /** @@ -360,11 +405,10 @@ public static class Item { private final String label; private final String url; - private static Item create(Class nsClass, String key, Type type, Object value) { + private static Item create(String nsClass, String key, Type type, Object value) { FormattedItemValue formatted = type.format(value); - String namespace = namespaceOf(nsClass); return new Item( - namespace, key, type, formatted.getLongValue(), formatted.getShortValue(), null, null); + nsClass, key, type, formatted.getLongValue(), formatted.getShortValue(), null, null); } private Item( @@ -492,7 +536,7 @@ private Item withUrl(String url) { return new Item(this.ns, this.key, this.type, this.value, this.shortValue, url, this.label); } - private Item withNamespace(Class nsClass) { + private Item withNamespace(ClassForDisplay nsClass) { String namespace = namespaceOf(nsClass); return new Item( namespace, this.key, this.type, this.value, this.shortValue, this.url, this.label); @@ -513,7 +557,7 @@ public static class Identifier { private final String ns; private final String key; - public static Identifier of(Class namespace, String key) { + public static Identifier of(ClassForDisplay namespace, String key) { return of(namespaceOf(namespace), key); } @@ -606,7 +650,12 @@ FormattedItemValue format(Object value) { JAVA_CLASS { @Override FormattedItemValue format(Object value) { - Class clazz = checkType(value, Class.class, JAVA_CLASS); + if (value instanceof Class) { + ClassForDisplay classForDisplay = ClassForDisplay.of((Class) value); + return format(classForDisplay); + } + + ClassForDisplay clazz = checkType(value, ClassForDisplay.class, JAVA_CLASS); return new FormattedItemValue(clazz.getName(), clazz.getSimpleName()); } }; @@ -642,7 +691,7 @@ private static Type tryInferFrom(@Nullable Object value) { return TIMESTAMP; } else if (value instanceof Duration) { return DURATION; - } else if (value instanceof Class) { + } else if (value instanceof Class || value instanceof ClassForDisplay) { return JAVA_CLASS; } else if (value instanceof String) { return STRING; @@ -678,7 +727,7 @@ private static class InternalBuilder implements ItemBuilder { private final Map entries; private final Set visited; - private Class latestNs; + private String latestNs; @Nullable private Item latestItem; @@ -702,13 +751,25 @@ public Builder include(HasDisplayData subComponent) { @Override public Builder include(HasDisplayData subComponent, Class namespace) { + checkNotNull(namespace); + return include(subComponent, ClassForDisplay.of(namespace)); + } + + @Override + public Builder include(HasDisplayData subComponent, ClassForDisplay namespace) { + checkNotNull(namespace); + return include(subComponent, namespaceOf(namespace)); + } + + @Override + public Builder include(HasDisplayData subComponent, String namespace) { checkNotNull(subComponent); checkNotNull(namespace); commitLatest(); boolean newComponent = visited.add(subComponent); if (newComponent) { - Class prevNs = this.latestNs; + String prevNs = this.latestNs; this.latestNs = namespace; subComponent.populateDisplayData(this); this.latestNs = prevNs; @@ -819,17 +880,34 @@ public ItemBuilder add(String key, Class value) { return addItemIf(true, key, Type.JAVA_CLASS, value); } + @Override + public ItemBuilder add(String key, ClassForDisplay value) { + checkNotNull(value); + return addItemIf(true, key, Type.JAVA_CLASS, value); + } + @Override public ItemBuilder addIfNotNull(String key, @Nullable Class value) { return addItemIf(value != null, key, Type.JAVA_CLASS, value); } + @Override + public ItemBuilder addIfNotNull(String key, @Nullable ClassForDisplay value) { + return addItemIf(value != null, key, Type.JAVA_CLASS, value); + } + @Override public ItemBuilder addIfNotDefault( String key, @Nullable Class value, @Nullable Class defaultValue) { return addItemIf(!Objects.equals(value, defaultValue), key, Type.JAVA_CLASS, value); } + @Override + public ItemBuilder addIfNotDefault( + String key, @Nullable ClassForDisplay value, @Nullable ClassForDisplay defaultValue) { + return addItemIf(!Objects.equals(value, defaultValue), key, Type.JAVA_CLASS, value); + } + @Override public ItemBuilder add(String key, Type type, Object value) { checkNotNull(value); @@ -885,6 +963,11 @@ public ItemBuilder withLinkUrl(@Nullable String url) { @Override public ItemBuilder withNamespace(Class namespace) { checkNotNull(namespace); + return withNamespace(ClassForDisplay.of(namespace)); + } + + @Override + public ItemBuilder withNamespace(ClassForDisplay namespace) { if (latestItem != null) { latestItem = latestItem.withNamespace(namespace); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java index d9744800b9..b895fa35e0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.state.StateContext; import java.io.IOException; @@ -99,6 +100,10 @@ public Coder getDefaultOutputCoder( CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { return combineFn.getDefaultOutputCoder(registry, inputCoder); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + combineFn.populateDisplayData(builder); + } }; } } @@ -144,6 +149,10 @@ public Coder getDefaultOutputCoder(CoderRegistry registry, Coder key Coder inputCoder) throws CannotProvideCoderException { return combineFn.getDefaultOutputCoder(registry, keyCoder, inputCoder); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + combineFn.populateDisplayData(builder); + } private void writeObject(@SuppressWarnings("unused") ObjectOutputStream out) throws IOException { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java index e366e6948d..35cb1aa111 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java @@ -17,6 +17,9 @@ package com.google.cloud.dataflow.sdk.transforms; import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import com.google.cloud.dataflow.sdk.Pipeline; @@ -27,6 +30,7 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.ApproximateQuantiles.ApproximateQuantilesCombineFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -233,6 +237,16 @@ public void testAlternateComparator() { Arrays.asList("b", "aaa", "ccccc")); } + @Test + public void testDisplayData() { + Top.Largest comparer = new Top.Largest(); + PTransform approxQuanitiles = ApproximateQuantiles.globally(20, comparer); + DisplayData displayData = DisplayData.from(approxQuanitiles); + + assertThat(displayData, hasDisplayItem("numQuantiles", 20)); + assertThat(displayData, hasDisplayItem("comparer", comparer.getClass())); + } + private Matcher> quantileMatcher( int size, int numQuantiles, int absoluteError) { List> quantiles = new ArrayList<>(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java index 39731bb931..5f008079e9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java @@ -16,6 +16,10 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -25,6 +29,7 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; @@ -288,4 +293,17 @@ public Void apply(Iterable> estimatePerKey) { return null; } } + + @Test + public void testDisplayData() { + ApproximateUnique.Globally specifiedSampleSize = ApproximateUnique.globally(1234); + ApproximateUnique.PerKey specifiedMaxError = ApproximateUnique.perKey(0.1234); + + assertThat(DisplayData.from(specifiedSampleSize), hasDisplayItem("sampleSize", 1234)); + + DisplayData maxErrorDisplayData = DisplayData.from(specifiedMaxError); + assertThat(maxErrorDisplayData, hasDisplayItem("maximumEstimationError", 0.1234)); + assertThat("calculated sampleSize should be included", maxErrorDisplayData, + hasDisplayItem(hasKey("sampleSize"))); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java index ad37708677..aa6e035f6b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java @@ -15,6 +15,9 @@ */ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; + import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.Pipeline; @@ -33,6 +36,7 @@ import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; import com.google.cloud.dataflow.sdk.transforms.Min.MinIntegerFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; @@ -58,7 +62,7 @@ * Unit tests for {@link CombineFns}. */ @RunWith(JUnit4.class) -public class CombineFnsTest { +public class CombineFnsTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test @@ -275,6 +279,69 @@ public void testComposedCombineNullValues() { p.run(); } + @Test + public void testComposedCombineDisplayData() { + SimpleFunction extractFn = new SimpleFunction() { + @Override + public String apply(String input) { + return input; + } + }; + + DisplayDataCombineFn combineFn1 = new DisplayDataCombineFn("value1"); + DisplayDataCombineFn combineFn2 = new DisplayDataCombineFn("value2"); + + CombineFns.ComposedCombineFn composedCombine = CombineFns.compose() + .with(extractFn, combineFn1, new TupleTag()) + .with(extractFn, combineFn2, new TupleTag()); + + DisplayData displayData = DisplayData.from(composedCombine); + assertThat(displayData, hasDisplayItem("combineFn1", combineFn1.getClass())); + assertThat(displayData, hasDisplayItem("combineFn2", combineFn2.getClass())); + + String nsBase = DisplayDataCombineFn.class.getName(); + assertThat(displayData, includes(combineFn1, nsBase + "#1")); + assertThat(displayData, includes(combineFn2, nsBase + "#2")); + } + + private static class DisplayDataCombineFn extends Combine.CombineFn { + private final String value; + private static int i; + private final int id; + + DisplayDataCombineFn(String value) { + id = ++i; + this.value = value; + } + + @Override + public String createAccumulator() { + return null; + } + + @Override + public String addInput(String accumulator, String input) { + return null; + } + + @Override + public String mergeAccumulators(Iterable accumulators) { + return null; + } + + @Override + public String extractOutput(String accumulator) { + return null; + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("uniqueKey" + id, value) + .add("sharedKey", value); + } + } + private static class UserString implements Serializable { private String strValue; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java index 37ed20415f..6dd838ad87 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java @@ -17,6 +17,8 @@ package com.google.cloud.dataflow.sdk.transforms; import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; import static com.google.common.base.Preconditions.checkNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -41,6 +43,7 @@ import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; @@ -678,6 +681,24 @@ public void testCombineGetName() { Combine.perKey(new TestKeyedCombineFn()).withHotKeyFanout(10).getName()); } + @Test + public void testDisplayData() { + UniqueInts combineFn = new UniqueInts() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("fnMetadata", "foobar"); + } + }; + Combine.Globally combine = Combine.globally(combineFn) + .withFanout(1234); + DisplayData displayData = DisplayData.from(combine); + + assertThat(displayData, hasDisplayItem("combineFn", combineFn.getClass())); + assertThat(displayData, hasDisplayItem("emitDefaultOnEmptyInput", true)); + assertThat(displayData, hasDisplayItem("fanout", 1234)); + assertThat(displayData, includes(combineFn)); + } + //////////////////////////////////////////////////////////////////////////// // Test classes, for different kinds of combining fns. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java index e1ea33bcf2..0dc95b4cbe 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java @@ -17,8 +17,12 @@ package com.google.cloud.dataflow.sdk.transforms; import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.collect.Lists; import org.junit.Test; @@ -63,4 +67,12 @@ public void testMaxDoubleFn() { Lists.newArrayList(1.0, 2.0, 3.0, 4.0), 4.0); } + + @Test + public void testDisplayData() { + Top.Largest comparer = new Top.Largest<>(); + + Combine.Globally max = Max.globally(comparer); + assertThat(DisplayData.from(max), hasDisplayItem("comparer", comparer.getClass())); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java index a291537adf..8ef2a73ab6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java @@ -16,9 +16,14 @@ package com.google.cloud.dataflow.sdk.transforms; + import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.collect.Lists; import org.junit.Test; @@ -63,4 +68,12 @@ public void testMinDoubleFn() { Lists.newArrayList(1.0, 2.0, 3.0, 4.0), 1.0); } + + @Test + public void testDisplayData() { + Top.Smallest comparer = new Top.Smallest<>(); + + Combine.Globally min = Min.globally(comparer); + assertThat(DisplayData.from(min), hasDisplayItem("comparer", comparer.getClass())); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java index d860513463..415f6d4aa8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java @@ -18,6 +18,9 @@ import static com.google.cloud.dataflow.sdk.TestUtils.LINES; import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -27,6 +30,7 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; @@ -257,4 +261,15 @@ public void testPickAnyWhenEmpty() { public void testSampleGetName() { assertEquals("Sample.SampleAny", Sample.any(1).getName()); } + + @Test + public void testDisplayData() { + PTransform sampleAny = Sample.any(1234); + DisplayData sampleAnyDisplayData = DisplayData.from(sampleAny); + assertThat(sampleAnyDisplayData, hasDisplayItem("sampleSize", 1234)); + + PTransform samplePerKey = Sample.fixedSizePerKey(2345); + DisplayData perKeyDisplayData = DisplayData.from(samplePerKey); + assertThat(perKeyDisplayData, hasDisplayItem("sampleSize", 2345)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java index ac06bff213..8a0cfe2f16 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java @@ -16,6 +16,9 @@ package com.google.cloud.dataflow.sdk.transforms; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import com.google.cloud.dataflow.sdk.Pipeline; @@ -24,6 +27,7 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; @@ -232,6 +236,16 @@ public void testTopGetNames() { assertEquals("Largest.PerKey", Top.largestPerKey(2).getName()); } + @Test + public void testDisplayData() { + Top.Largest comparer = new Top.Largest(); + Combine.Globally> top = Top.of(1234, comparer); + DisplayData displayData = DisplayData.from(top); + + assertThat(displayData, hasDisplayItem("count", 1234)); + assertThat(displayData, hasDisplayItem("comparer", comparer.getClass())); + } + private static class OrderByLength implements Comparator, Serializable { @Override public int compare(String a, String b) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayTest.java new file mode 100644 index 0000000000..9c6102b7f9 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; + +import static org.junit.Assert.assertEquals; + +import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.common.testing.EqualsTester; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Unit tests for {@link ClassForDisplay}. + */ +@RunWith(JUnit4.class) +public class ClassForDisplayTest { + @Rule + public final ExpectedException thrown = ExpectedException.none(); + + @Test + public void testProperties() { + ClassForDisplay thisClass = ClassForDisplay.of(ClassForDisplayTest.class); + assertEquals(ClassForDisplayTest.class.getName(), thisClass.getName()); + assertEquals(ClassForDisplayTest.class.getSimpleName(), thisClass.getSimpleName()); + } + + @Test + public void testInputValidation() { + thrown.expect(NullPointerException.class); + ClassForDisplay.of(null); + } + + @Test + public void testEquality() { + new EqualsTester() + .addEqualityGroup( + ClassForDisplay.of(ClassForDisplayTest.class), ClassForDisplay.fromInstance(this)) + .addEqualityGroup(ClassForDisplay.of(ClassForDisplay.class)) + .addEqualityGroup(ClassForDisplay.of(Class.class)) + .testEquals(); + } + + @Test + public void testSerialization() { + SerializableUtils.ensureSerializable(ClassForDisplay.of(ClassForDisplayTest.class)); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java index 064b98a54f..aa7b66f0b6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java @@ -147,40 +147,42 @@ protected boolean matchesSafely(DisplayData data, Description mismatchDescriptio } } - /** - * Create a matcher that matches if the examined {@link DisplayData} contains all display data - * registered from the specified subcomponent. - */ - public static Matcher includes(final HasDisplayData subComponent) { + /** @see #includes(HasDisplayData, String) */ + public static Matcher includes(HasDisplayData subComponent) { return includes(subComponent, subComponent.getClass()); } + /** @see #includes(HasDisplayData, String) */ + public static Matcher includes( + HasDisplayData subComponent, Class namespace) { + return includes(subComponent, namespace.getName()); + } + /** * Create a matcher that matches if the examined {@link DisplayData} contains all display data * registered from the specified subcomponent and namespace. */ public static Matcher includes( - final HasDisplayData subComponent, final Class namespace) { + final HasDisplayData subComponent, final String namespace) { return new CustomTypeSafeMatcher("includes subcomponent") { @Override protected boolean matchesSafely(DisplayData displayData) { - DisplayData subComponentData = DisplayData.from(subComponent); + DisplayData subComponentData = subComponentData(); if (subComponentData.items().size() == 0) { throw new UnsupportedOperationException("subComponent contains no display data; " + "cannot verify whether it is included"); } - DisplayDataComparision comparison = checkSubset(displayData, subComponentData, namespace); + DisplayDataComparison comparison = checkSubset(displayData, subComponentData); return comparison.missingItems.isEmpty(); } - @Override protected void describeMismatchSafely( DisplayData displayData, Description mismatchDescription) { - DisplayData subComponentDisplayData = DisplayData.from(subComponent); - DisplayDataComparision comparison = checkSubset( - displayData, subComponentDisplayData, subComponent.getClass()); + DisplayData subComponentDisplayData = subComponentData(); + DisplayDataComparison comparison = checkSubset( + displayData, subComponentDisplayData); mismatchDescription .appendText("did not include:\n") @@ -189,12 +191,21 @@ protected void describeMismatchSafely( .appendValue(comparison.unmatchedItems); } - private DisplayDataComparision checkSubset( - DisplayData displayData, DisplayData included, Class namespace) { - DisplayDataComparision comparison = new DisplayDataComparision(displayData.items()); + private DisplayData subComponentData() { + return DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.include(subComponent, namespace); + } + }); + } + + private DisplayDataComparison checkSubset( + DisplayData displayData, DisplayData included) { + DisplayDataComparison comparison = new DisplayDataComparison(displayData.items()); for (Item item : included.items()) { Item matchedItem = displayData.asMap().get( - DisplayData.Identifier.of(namespace, item.getKey())); + DisplayData.Identifier.of(item.getNamespace(), item.getKey())); if (matchedItem != null) { comparison.matched(matchedItem); @@ -206,11 +217,11 @@ private DisplayDataComparision checkSubset( return comparison; } - class DisplayDataComparision { + class DisplayDataComparison { Collection missingItems; Collection unmatchedItems; - DisplayDataComparision(Collection superset) { + DisplayDataComparison(Collection superset) { missingItems = Sets.newHashSet(); unmatchedItems = Sets.newHashSet(superset); } @@ -313,7 +324,9 @@ public static Matcher hasValue(Matcher valueMatcher) { valueMatcher, "with value", "value") { @Override protected T featureValueOf(DisplayData.Item actual) { - return (T) actual.getValue(); + @SuppressWarnings("unchecked") + T value = (T) actual.getValue(); + return value; } }; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index ad348f16de..9d5d2206b8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -336,7 +336,7 @@ public void testNullNamespaceOverride() { @Override public void populateDisplayData(Builder builder) { builder.add("foo", "bar") - .withNamespace(null); + .withNamespace((Class) null); } }); } @@ -345,10 +345,10 @@ public void populateDisplayData(Builder builder) { public void testIdentifierEquality() { new EqualsTester() .addEqualityGroup( - DisplayData.Identifier.of(DisplayDataTest.class, "1"), - DisplayData.Identifier.of(DisplayDataTest.class, "1")) - .addEqualityGroup(DisplayData.Identifier.of(Object.class, "1")) - .addEqualityGroup(DisplayData.Identifier.of(DisplayDataTest.class, "2")) + DisplayData.Identifier.of(ClassForDisplay.of(DisplayDataTest.class), "1"), + DisplayData.Identifier.of(ClassForDisplay.of(DisplayDataTest.class), "1")) + .addEqualityGroup(DisplayData.Identifier.of(ClassForDisplay.of(Object.class), "1")) + .addEqualityGroup(DisplayData.Identifier.of(ClassForDisplay.of(DisplayDataTest.class), "2")) .testEquals(); } @@ -564,6 +564,7 @@ public void populateDisplayData(DisplayData.Builder builder) { .add("float", 3.14) .add("boolean", true) .add("java_class", DisplayDataTest.class) + .add("java_class2", ClassForDisplay.of(DisplayDataTest.class)) .add("timestamp", Instant.now()) .add("duration", Duration.standardHours(1)); } @@ -579,6 +580,9 @@ public void populateDisplayData(DisplayData.Builder builder) { assertThat( items, hasItem(allOf(hasKey("java_class"), hasType(DisplayData.Type.JAVA_CLASS)))); + assertThat( + items, + hasItem(allOf(hasKey("java_class2"), hasType(DisplayData.Type.JAVA_CLASS)))); assertThat( items, hasItem(allOf(hasKey("timestamp"), hasType(DisplayData.Type.TIMESTAMP)))); @@ -674,6 +678,8 @@ public void testKnownTypeInference() { assertEquals(DisplayData.Type.BOOLEAN, DisplayData.inferType(true)); assertEquals(DisplayData.Type.TIMESTAMP, DisplayData.inferType(Instant.now())); assertEquals(DisplayData.Type.DURATION, DisplayData.inferType(Duration.millis(1234))); + assertEquals(DisplayData.Type.JAVA_CLASS, + DisplayData.inferType(ClassForDisplay.of(DisplayDataTest.class))); assertEquals(DisplayData.Type.JAVA_CLASS, DisplayData.inferType(DisplayDataTest.class)); assertEquals(DisplayData.Type.STRING, DisplayData.inferType("hello world")); @@ -769,7 +775,7 @@ public void populateDisplayData(Builder builder) { DisplayData.from(new HasDisplayData() { @Override public void populateDisplayData(Builder builder) { - builder.include(subComponent, null); + builder.include(subComponent, (ClassForDisplay) null); } }); } diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java index b569e49c95..49476172e8 100644 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java +++ b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java @@ -16,12 +16,21 @@ package com.google.cloud.dataflow.sdk.transforms; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.not; + import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.Iterables; + +import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -130,4 +139,37 @@ public void testCombinePerKeyInstanceMethodReference() { KV.of("c", 4)); pipeline.run(); } + + /** + * Tests that we can serialize {@link Combine.CombineFn CombineFns} constructed from a lambda. + * Lambdas can be problematic because the {@link Class} object is synthetic and cannot be + * deserialized. + */ + @Test + public void testLambdaSerialization() { + SerializableFunction, Object> combiner = xs -> Iterables.getFirst(xs, 0); + + boolean lambdaClassSerializationThrows; + try { + SerializableUtils.clone(combiner.getClass()); + lambdaClassSerializationThrows = false; + } catch (IllegalArgumentException e) { + // Expected + lambdaClassSerializationThrows = true; + } + Assume.assumeTrue("Expected lambda class serialization to fail. " + + "If it's fixed, we can remove special behavior in Combine.", + lambdaClassSerializationThrows); + + + Combine.Globally combine = Combine.globally(combiner); + SerializableUtils.clone(combine); // should not throw. + } + + @Test + public void testLambdaDisplayData() { + Combine.Globally combine = Combine.globally(xs -> Iterables.getFirst(xs, 0)); + DisplayData displayData = DisplayData.from(combine); + assertThat(displayData.items(), not(empty())); + } } diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayJava8Test.java new file mode 100644 index 0000000000..de6bd7df87 --- /dev/null +++ b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/display/ClassForDisplayJava8Test.java @@ -0,0 +1,46 @@ +/* + * 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 com.google.cloud.dataflow.sdk.transforms.display; + +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; + +/** + * Java 8 tests for {@link ClassForDisplay}. + */ +@RunWith(JUnit4.class) +public class ClassForDisplayJava8Test implements Serializable { + @Test + public void testLambdaClassSerialization() { + final SerializableFunction f = x -> x; + Serializable myClass = new Serializable() { + // Class references for lambdas do not serialize, which is why we support ClassForDisplay + // Specifically, the following would not work: + // Class clazz = f.getClass(); + ClassForDisplay javaClass = ClassForDisplay.fromInstance(f); + }; + + SerializableUtils.ensureSerializable(myClass); + } +} From 2de320281773701073121054d8c0e95dca25878b Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 5 Apr 2016 11:49:26 -0700 Subject: [PATCH 338/751] Publish DisplayData for PipelineOptions. (cherry picked from commit 2c16bdd68c1196c4a394c240f232150476f70b0e) --- .../sdk/options/PipelineOptionSpec.java | 87 ++++++ .../dataflow/sdk/options/PipelineOptions.java | 3 +- .../sdk/options/PipelineOptionsFactory.java | 127 ++++----- .../sdk/options/PipelineOptionsReflector.java | 110 +++++++ .../sdk/options/ProxyInvocationHandler.java | 258 +++++++++++++++-- .../sdk/transforms/display/DisplayData.java | 26 +- .../options/PipelineOptionsReflectorTest.java | 193 +++++++++++++ .../options/ProxyInvocationHandlerTest.java | 268 +++++++++++++++++- .../DataflowPipelineTranslatorTest.java | 5 +- .../transforms/display/DisplayDataTest.java | 25 ++ 10 files changed, 1007 insertions(+), 95 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java new file mode 100644 index 0000000000..54e9fc7a1b --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import com.google.common.base.MoreObjects; +import com.google.common.base.Objects; + +import java.lang.reflect.Method; + +/** + * For internal use. Specification for an option defined in a {@link PipelineOptions} interface. + */ +class PipelineOptionSpec { + private final Class clazz; + private final String name; + private final Method getter; + + static PipelineOptionSpec of(Class clazz, String name, Method getter) { + return new PipelineOptionSpec(clazz, name, getter); + } + + private PipelineOptionSpec(Class clazz, String name, Method getter) { + this.clazz = clazz; + this.name = name; + this.getter = getter; + } + + /** + * The {@link PipelineOptions} interface which defines this {@link PipelineOptionSpec}. + */ + Class getDefiningInterface() { + return clazz; + } + + /** + * Name of the property. + */ + String getName() { + return name; + } + + /** + * The getter method for this property. + */ + Method getGetterMethod() { + return getter; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("definingInterface", getDefiningInterface()) + .add("name", getName()) + .add("getterMethod", getGetterMethod()) + .toString(); + } + + @Override + public int hashCode() { + return Objects.hashCode(getDefiningInterface(), getName(), getGetterMethod()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof PipelineOptionSpec)) { + return false; + } + + PipelineOptionSpec that = (PipelineOptionSpec) obj; + return Objects.equal(this.getDefiningInterface(), that.getDefiningInterface()) + && Objects.equal(this.getName(), that.getName()) + && Objects.equal(this.getGetterMethod(), that.getGetterMethod()); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java index 41fa45c9fc..8022aa4e38 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.DoFn.Context; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.ObjectMapper; @@ -192,7 +193,7 @@ @JsonSerialize(using = Serializer.class) @JsonDeserialize(using = Deserializer.class) @ThreadSafe -public interface PipelineOptions { +public interface PipelineOptions extends HasDisplayData { /** * Transforms this object into an object of type {@code } saving each property * that has been manipulated. {@code } must extend {@link PipelineOptions}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java index 4781d1c829..872ac47099 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java @@ -21,8 +21,10 @@ import com.google.cloud.dataflow.sdk.options.Validation.Required; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.StringUtils; import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; @@ -30,7 +32,6 @@ import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.base.Throwables; -import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Collections2; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableListMultimap; @@ -41,8 +42,11 @@ import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import com.google.common.collect.Ordering; +import com.google.common.collect.RowSortedTable; import com.google.common.collect.Sets; import com.google.common.collect.SortedSetMultimap; +import com.google.common.collect.TreeBasedTable; import com.google.common.collect.TreeMultimap; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -75,6 +79,7 @@ import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; +import java.util.TreeMap; import java.util.TreeSet; import javax.annotation.Nullable; @@ -442,6 +447,7 @@ Class getProxyClass() { @SuppressWarnings("rawtypes") private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final ClassLoader CLASS_LOADER; private static final Map>> SUPPORTED_PIPELINE_RUNNERS; /** Classes that are used as the boundary in the stack trace to find the callers class name. */ @@ -508,7 +514,7 @@ static ClassLoader findClassLoader() { throw new ExceptionInInitializerError(e); } - ClassLoader classLoader = findClassLoader(); + CLASS_LOADER = findClassLoader(); // Store the list of all available pipeline runners. ImmutableMap.Builder>> builder = @@ -516,25 +522,14 @@ static ClassLoader findClassLoader() { Set pipelineRunnerRegistrars = Sets.newTreeSet(ObjectsClassComparator.INSTANCE); pipelineRunnerRegistrars.addAll( - Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class, classLoader))); + Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class, CLASS_LOADER))); for (PipelineRunnerRegistrar registrar : pipelineRunnerRegistrars) { for (Class> klass : registrar.getPipelineRunners()) { builder.put(klass.getSimpleName(), klass); } } SUPPORTED_PIPELINE_RUNNERS = builder.build(); - - // Load and register the list of all classes that extend PipelineOptions. - register(PipelineOptions.class); - Set pipelineOptionsRegistrars = - Sets.newTreeSet(ObjectsClassComparator.INSTANCE); - pipelineOptionsRegistrars.addAll( - Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class, classLoader))); - for (PipelineOptionsRegistrar registrar : pipelineOptionsRegistrars) { - for (Class klass : registrar.getPipelineOptions()) { - register(klass); - } - } + initializeRegistry(); } /** @@ -563,6 +558,33 @@ public static synchronized void register(Class iface) REGISTERED_OPTIONS.add(iface); } + /** + * Resets the set of interfaces registered with this factory to the default state. + * + * @see PipelineOptionsFactory#register(Class) + */ + @VisibleForTesting + static synchronized void resetRegistry() { + REGISTERED_OPTIONS.clear(); + initializeRegistry(); + } + + /** + * Load and register the list of all classes that extend PipelineOptions. + */ + private static void initializeRegistry() { + register(PipelineOptions.class); + Set pipelineOptionsRegistrars = + Sets.newTreeSet(ObjectsClassComparator.INSTANCE); + pipelineOptionsRegistrars.addAll( + Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class, CLASS_LOADER))); + for (PipelineOptionsRegistrar registrar : pipelineOptionsRegistrars) { + for (Class klass : registrar.getPipelineOptions()) { + register(klass); + } + } + } + /** * Validates that the interface conforms to the following: *
          @@ -672,32 +694,20 @@ public static void printHelp(PrintStream out, Class i Preconditions.checkNotNull(iface); validateWellFormed(iface, REGISTERED_OPTIONS); - Iterable methods = - Iterables.filter( - ReflectHelpers.getClosureOfMethodsOnInterface(iface), NOT_SYNTHETIC_PREDICATE); - ListMultimap, Method> ifaceToMethods = ArrayListMultimap.create(); - for (Method method : methods) { - // Process only methods that are not marked as hidden. - if (method.getAnnotation(Hidden.class) == null) { - ifaceToMethods.put(method.getDeclaringClass(), method); - } + Set properties = + PipelineOptionsReflector.getOptionSpecs(iface); + + RowSortedTable, String, Method> ifacePropGetterTable = TreeBasedTable.create( + ClassNameComparator.INSTANCE, Ordering.natural()); + for (PipelineOptionSpec prop : properties) { + ifacePropGetterTable.put(prop.getDefiningInterface(), prop.getName(), prop.getGetterMethod()); } - SortedSet> ifaces = new TreeSet<>(ClassNameComparator.INSTANCE); - // Keep interfaces that are not marked as hidden. - ifaces.addAll(Collections2.filter(ifaceToMethods.keySet(), new Predicate>() { - @Override - public boolean apply(Class input) { - return input.getAnnotation(Hidden.class) == null; - } - })); - for (Class currentIface : ifaces) { - Map propertyNamesToGetters = - getPropertyNamesToGetters(ifaceToMethods.get(currentIface)); - // Don't output anything if there are no defined options - if (propertyNamesToGetters.isEmpty()) { - continue; - } + for (Map.Entry, Map> ifaceToPropertyMap : + ifacePropGetterTable.rowMap().entrySet()) { + Class currentIface = ifaceToPropertyMap.getKey(); + Map propertyNamesToGetters = ifaceToPropertyMap.getValue(); + SortedSetMultimap requiredGroupNameToProperties = getRequiredGroupNamesToProperties(propertyNamesToGetters); @@ -884,15 +894,21 @@ public static DataflowWorkerHarnessOptions createFromSystemProperties() throws I *

          TODO: Swap back to using Introspector once the proxy class issue with AppEngine is * resolved. */ - private static List getPropertyDescriptors(Class beanClass) + private static List getPropertyDescriptors( + Class beanClass) throws IntrospectionException { // The sorting is important to make this method stable. SortedSet methods = Sets.newTreeSet(MethodComparator.INSTANCE); methods.addAll( Collections2.filter(Arrays.asList(beanClass.getMethods()), NOT_SYNTHETIC_PREDICATE)); - SortedMap propertyNamesToGetters = getPropertyNamesToGetters(methods); - List descriptors = Lists.newArrayList(); + SortedMap propertyNamesToGetters = new TreeMap<>(); + for (Map.Entry entry : + PipelineOptionsReflector.getPropertyNamesToGetters(methods).entries()) { + propertyNamesToGetters.put(entry.getKey(), entry.getValue()); + } + + List descriptors = Lists.newArrayList(); List mismatches = new ArrayList<>(); /* * Add all the getter/setter pairs to the list of descriptors removing the getter once @@ -964,28 +980,6 @@ private static void throwForTypeMismatches(List mismatches) { } } - /** - * Returns a map of the property name to the getter method it represents. - * If there are duplicate methods with the same bean name, then it is indeterminate - * as to which method will be returned. - */ - private static SortedMap getPropertyNamesToGetters(Iterable methods) { - SortedMap propertyNamesToGetters = Maps.newTreeMap(); - for (Method method : methods) { - String methodName = method.getName(); - if ((!methodName.startsWith("get") - && !methodName.startsWith("is")) - || method.getParameterTypes().length != 0 - || method.getReturnType() == void.class) { - continue; - } - String propertyName = Introspector.decapitalize( - methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3)); - propertyNamesToGetters.put(propertyName, method); - } - return propertyNamesToGetters; - } - /** * Returns a map of required groups of arguments to the properties that satisfy the requirement. */ @@ -1027,21 +1021,22 @@ private static SortedSetMultimap getRequiredGroupNamesToProperti */ private static List validateClass(Class iface, Set> validatedPipelineOptionsInterfaces, - Class klass) throws IntrospectionException { + Class klass) throws IntrospectionException { Set methods = Sets.newHashSet(IGNORED_METHODS); - // Ignore static methods, "equals", "hashCode", "toString" and "as" on the generated class. // Ignore synthetic methods for (Method method : klass.getMethods()) { if (Modifier.isStatic(method.getModifiers()) || method.isSynthetic()) { methods.add(method); } } + // Ignore standard infrastructure methods on the generated class. try { methods.add(klass.getMethod("equals", Object.class)); methods.add(klass.getMethod("hashCode")); methods.add(klass.getMethod("toString")); methods.add(klass.getMethod("as", Class.class)); methods.add(klass.getMethod("cloneAs", Class.class)); + methods.add(klass.getMethod("populateDisplayData", DisplayData.Builder.class)); } catch (NoSuchMethodException | SecurityException e) { throw Throwables.propagate(e); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java new file mode 100644 index 0000000000..094590a322 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Multimap; + +import java.beans.Introspector; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.Set; + +/** + * Utilities to reflect over {@link PipelineOptions}. + */ +class PipelineOptionsReflector { + private PipelineOptionsReflector() {} + + /** + * Retrieve metadata for the full set of pipeline options visible within the type hierarchy + * of a single {@link PipelineOptions} interface. + * + * @see PipelineOptionsReflector#getOptionSpecs(Iterable) + */ + static Set getOptionSpecs(Class optionsInterface) { + Iterable methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface); + Multimap propsToGetters = getPropertyNamesToGetters(methods); + + ImmutableSet.Builder setBuilder = ImmutableSet.builder(); + for (Map.Entry propAndGetter : propsToGetters.entries()) { + String prop = propAndGetter.getKey(); + Method getter = propAndGetter.getValue(); + + @SuppressWarnings("unchecked") + Class declaringClass = + (Class) getter.getDeclaringClass(); + + if (!PipelineOptions.class.isAssignableFrom(declaringClass)) { + continue; + } + + if (declaringClass.isAnnotationPresent(Hidden.class)) { + continue; + } + + setBuilder.add(PipelineOptionSpec.of(declaringClass, prop, getter)); + } + + return setBuilder.build(); + } + + /** + * Retrieve metadata for the full set of pipeline options visible within the type hierarchy + * closure of the set of input interfaces. An option is "visible" if: + *

          + *

            + *
          • The option is defined within the interface hierarchy closure of the input + * {@link PipelineOptions}.
          • + *
          • The defining interface is not marked {@link Hidden}.
          • + *
          + */ + static Set getOptionSpecs( + Iterable> optionsInterfaces) { + ImmutableSet.Builder setBuilder = ImmutableSet.builder(); + for (Class optionsInterface : optionsInterfaces) { + setBuilder.addAll(getOptionSpecs(optionsInterface)); + } + + return setBuilder.build(); + } + + /** + * Extract pipeline options and their respective getter methods from a series of + * {@link Method methods}. A single pipeline option may appear in many methods. + * + * @return A mapping of option name to the input methods which declare it. + */ + static Multimap getPropertyNamesToGetters(Iterable methods) { + Multimap propertyNamesToGetters = HashMultimap.create(); + for (Method method : methods) { + String methodName = method.getName(); + if ((!methodName.startsWith("get") + && !methodName.startsWith("is")) + || method.getParameterTypes().length != 0 + || method.getReturnType() == void.class) { + continue; + } + String propertyName = Introspector.decapitalize( + methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3)); + propertyNamesToGetters.put(propertyName, method); + } + return propertyNamesToGetters; + } + +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index 527f712ca4..fce2e18993 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.options; +import com.google.api.client.repackaged.com.google.common.base.Objects; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.JsonIgnorePredicate; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.Registration; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.util.InstanceBuilder; import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; import com.google.common.base.Defaults; @@ -25,8 +28,11 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.FluentIterable; +import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; import com.google.common.collect.MutableClassToInstanceMap; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -50,6 +56,8 @@ import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -58,6 +66,7 @@ import java.util.SortedMap; import java.util.TreeMap; +import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** @@ -83,16 +92,26 @@ class ProxyInvocationHandler implements InvocationHandler { private final int hashCode = (int) (Math.random() * Integer.MAX_VALUE); private final Set> knownInterfaces; private final ClassToInstanceMap interfaceToProxyCache; - private final Map options; + private final Map options; private final Map jsonOptions; private final Map gettersToPropertyNames; private final Map settersToPropertyNames; ProxyInvocationHandler(Map options) { - this(options, Maps.newHashMap()); + this(bindOptions(options), Maps.newHashMap()); } - private ProxyInvocationHandler(Map options, Map jsonOptions) { + private static Map bindOptions(Map inputOptions) { + HashMap options = Maps.newHashMap(); + for (Map.Entry entry : inputOptions.entrySet()) { + options.put(entry.getKey(), BoundValue.fromExplicitOption(entry.getValue())); + } + + return options; + } + + private ProxyInvocationHandler( + Map options, Map jsonOptions) { this.options = options; this.jsonOptions = jsonOptions; this.knownInterfaces = new HashSet<>(PipelineOptionsFactory.getRegisteredOptions()); @@ -117,21 +136,27 @@ public Object invoke(Object proxy, Method method, Object[] args) { @SuppressWarnings("unchecked") Class clazz = (Class) args[0]; return cloneAs(proxy, clazz); + } else if (args != null && "populateDisplayData".equals(method.getName()) + && args[0] instanceof DisplayData.Builder) { + @SuppressWarnings("unchecked") + DisplayData.Builder builder = (DisplayData.Builder) args[0]; + populateDisplayData(builder); + return Void.TYPE; } String methodName = method.getName(); synchronized (this) { - if (gettersToPropertyNames.keySet().contains(methodName)) { + if (gettersToPropertyNames.containsKey(methodName)) { String propertyName = gettersToPropertyNames.get(methodName); if (!options.containsKey(propertyName)) { // Lazy bind the default to the method. Object value = jsonOptions.containsKey(propertyName) ? getValueFromJson(propertyName, method) : getDefault((PipelineOptions) proxy, method); - options.put(propertyName, value); + options.put(propertyName, BoundValue.fromDefault(value)); } - return options.get(propertyName); + return options.get(propertyName).getValue(); } else if (settersToPropertyNames.containsKey(methodName)) { - options.put(settersToPropertyNames.get(methodName), args[0]); + options.put(settersToPropertyNames.get(methodName), BoundValue.fromExplicitOption(args[0])); return Void.TYPE; } } @@ -139,6 +164,70 @@ public Object invoke(Object proxy, Method method, Object[] args) { + Arrays.toString(args) + "]."); } + /** + * Track whether options values are explicitly set, or retrieved from defaults. + */ + static final class BoundValue { + @Nullable + private final Object value; + private final boolean isDefault; + + @Nullable + Object getValue() { + return value; + } + + boolean isDefault() { + return isDefault; + } + + private static BoundValue of(@Nullable Object value, boolean isDefault) { + return new BoundValue(value, isDefault); + } + + private BoundValue(@Nullable Object value, boolean isDefault) { + this.value = value; + this.isDefault = isDefault; + } + + /** + * Create a {@link BoundValue} representing an explicitly set option. + */ + static BoundValue fromExplicitOption(@Nullable Object value) { + return BoundValue.of(value, false); + } + + /** + * Create a {@link BoundValue} representing a default option value. + */ + static BoundValue fromDefault(@Nullable Object value) { + return BoundValue.of(value, true); + } + + @Override + public String toString() { + return Objects.toStringHelper(BoundValue.class) + .add("value", value) + .add("isDefault", isDefault) + .toString(); + } + + @Override + public int hashCode() { + return Objects.hashCode(value, isDefault); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BoundValue)) { + return false; + } + + BoundValue that = (BoundValue) obj; + return Objects.equal(this.value, that.value) && Objects.equal(this.isDefault, that.isDefault); + } + } + /** * Backing implementation for {@link PipelineOptions#as(Class)}. * @@ -207,6 +296,128 @@ public int hashCode() { return hashCode; } + /** + * Populate display data. See {@link HasDisplayData#populateDisplayData}. All explicitly set + * pipeline options will be added as display data. + */ + private void populateDisplayData(DisplayData.Builder builder) { + Set optionSpecs = PipelineOptionsReflector.getOptionSpecs(knownInterfaces); + Multimap optionsMap = buildOptionNameToSpecMap(optionSpecs); + + for (Map.Entry option : options.entrySet()) { + BoundValue boundValue = option.getValue(); + if (boundValue.isDefault()) { + continue; + } + + Object value = boundValue.getValue() == null ? "" : boundValue.getValue(); + DisplayData.Type type = DisplayData.inferType(value); + HashSet specs = new HashSet<>(optionsMap.get(option.getKey())); + + for (PipelineOptionSpec optionSpec : specs) { + Class pipelineInterface = optionSpec.getDefiningInterface(); + if (type != null) { + builder.add(option.getKey(), type, value) + .withNamespace(pipelineInterface); + } else { + builder.add(option.getKey(), value.toString()) + .withNamespace(pipelineInterface); + } + } + } + + for (Map.Entry jsonOption : jsonOptions.entrySet()) { + if (options.containsKey(jsonOption.getKey())) { + // Option overwritten since deserialization; don't re-write + continue; + } + + HashSet specs = new HashSet<>(optionsMap.get(jsonOption.getKey())); + if (specs.isEmpty()) { + builder.add(jsonOption.getKey(), jsonOption.getValue().toString()) + .withNamespace(UnknownPipelineOptions.class); + } else { + for (PipelineOptionSpec spec : specs) { + Object value = getValueFromJson(jsonOption.getKey(), spec.getGetterMethod()); + DisplayData.Type type = DisplayData.inferType(value); + if (type != null) { + builder.add(jsonOption.getKey(), type, value) + .withNamespace(spec.getDefiningInterface()); + } else { + builder.add(jsonOption.getKey(), value.toString()) + .withNamespace(spec.getDefiningInterface()); + } + } + } + } + } + + /** + * Marker interface used when the original {@link PipelineOptions} interface is not known at + * runtime. This can occur if {@link PipelineOptions} are deserialized from JSON. + *

          + *

          Pipeline authors can ensure {@link PipelineOptions} type information is available at + * runtime by registering their {@link PipelineOptions options} interfaces. See the "Registration" + * section of {@link PipelineOptions} documentation. + */ + interface UnknownPipelineOptions extends PipelineOptions {} + + /** + * Construct a mapping from an option name to its {@link PipelineOptions} interface(s) + * declarations. An option may be declared in multiple interfaces. If it is overridden in a + * type hierarchy, only the overriding interface will be included. + */ + private Multimap buildOptionNameToSpecMap( + Set props) { + + Multimap optionsMap = HashMultimap.create(); + for (PipelineOptionSpec prop : props) { + optionsMap.put(prop.getName(), prop); + } + + // Filter out overridden options + for (Map.Entry> entry : optionsMap.asMap().entrySet()) { + + /* Compare all interfaces for an option pairwise (iface1, iface2) to look for type + hierarchies. If one is the base-class of the other, remove it from the output and continue + iterating. + + This is an N^2 operation per-option, but the number of interfaces defining an option + should always be small (usually 1). */ + List specs = Lists.newArrayList(entry.getValue()); + if (specs.size() < 2) { + // Only one known implementing interface, no need to check for inheritance + continue; + } + + for (int i = 0; i < specs.size() - 1; i++) { + Class iface1 = specs.get(i).getDefiningInterface(); + for (int j = i + 1; j < specs.size(); j++) { + Class iface2 = specs.get(j).getDefiningInterface(); + + if (iface1.isAssignableFrom(iface2)) { + optionsMap.remove(entry.getKey(), specs.get(i)); + specs.remove(i); + + // Removed element at current "i" index. Set iterators to re-evaluate + // new "i" element in outer loop. + i--; + j = specs.size(); + } else if (iface2.isAssignableFrom(iface1)) { + optionsMap.remove(entry.getKey(), specs.get(j)); + specs.remove(j); + + // Removed element at current "j" index. Set iterator to re-evaluate + // new "j" element in inner-loop. + j--; + } + } + } + } + + return optionsMap; + } + /** * This will output all the currently set values. This is a relatively costly function * as it will call {@code toString()} on each object that has been set and format @@ -220,7 +431,9 @@ public synchronized String toString() { // Add the options that we received from deserialization sortedOptions.putAll(jsonOptions); // Override with any programmatically set options. - sortedOptions.putAll(options); + for (Map.Entry entry : options.entrySet()) { + sortedOptions.put(entry.getKey(), entry.getValue().getValue()); + } StringBuilder b = new StringBuilder(); b.append("Current Settings:\n"); @@ -345,7 +558,7 @@ public void serialize(PipelineOptions value, JsonGenerator jgen, SerializerProvi // We first filter out any properties that have been modified since // the last serialization of this PipelineOptions and then verify that // they are all serializable. - Map filteredOptions = Maps.newHashMap(handler.options); + Map filteredOptions = Maps.newHashMap(handler.options); removeIgnoredOptions(handler.knownInterfaces, filteredOptions); ensureSerializable(handler.knownInterfaces, filteredOptions); @@ -354,10 +567,23 @@ public void serialize(PipelineOptions value, JsonGenerator jgen, SerializerProvi // instances that have been modified since the previous serialization. Map serializableOptions = Maps.newHashMap(handler.jsonOptions); - serializableOptions.putAll(filteredOptions); + for (Map.Entry entry : filteredOptions.entrySet()) { + serializableOptions.put(entry.getKey(), entry.getValue().getValue()); + } + jgen.writeStartObject(); jgen.writeFieldName("options"); jgen.writeObject(serializableOptions); + + List> serializedDisplayData = Lists.newArrayList(); + for (DisplayData.Item item : DisplayData.from(value).items()) { + @SuppressWarnings("unchecked") + Map serializedItem = MAPPER.convertValue(item, Map.class); + serializedDisplayData.add(serializedItem); + } + + jgen.writeFieldName("display_data"); + jgen.writeObject(serializedDisplayData); jgen.writeEndObject(); } } @@ -367,7 +593,7 @@ public void serialize(PipelineOptions value, JsonGenerator jgen, SerializerProvi * {@link JsonIgnore @JsonIgnore} from the passed in options using the passed in interfaces. */ private void removeIgnoredOptions( - Set> interfaces, Map options) { + Set> interfaces, Map options) { // Find all the method names that are annotated with JSON ignore. Set jsonIgnoreMethodNames = FluentIterable.from( ReflectHelpers.getClosureOfMethodsOnInterfaces(interfaces)) @@ -392,7 +618,7 @@ public String apply(Method input) { * and deserializable. */ private void ensureSerializable(Set> interfaces, - Map options) throws IOException { + Map options) throws IOException { // Construct a map from property name to the return type of the getter. Map propertyToReturnType = Maps.newHashMap(); for (PropertyDescriptor descriptor @@ -404,16 +630,16 @@ private void ensureSerializable(Set> interfaces } // Attempt to serialize and deserialize each property. - for (Map.Entry entry : options.entrySet()) { + for (Map.Entry entry : options.entrySet()) { try { - String serializedValue = MAPPER.writeValueAsString(entry.getValue()); + String serializedValue = MAPPER.writeValueAsString(entry.getValue().getValue()); JavaType type = MAPPER.getTypeFactory() .constructType(propertyToReturnType.get(entry.getKey())); MAPPER.readValue(serializedValue, type); } catch (Exception e) { throw new IOException(String.format( "Failed to serialize and deserialize property '%s' with value '%s'", - entry.getKey(), entry.getValue()), e); + entry.getKey(), entry.getValue().getValue()), e); } } } @@ -433,7 +659,7 @@ public PipelineOptions deserialize(JsonParser jp, DeserializationContext ctxt) fields.put(field.getKey(), field.getValue()); } PipelineOptions options = - new ProxyInvocationHandler(Maps.newHashMap(), fields) + new ProxyInvocationHandler(Maps.newHashMap(), fields) .as(PipelineOptions.class); return options; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 006f088a90..eefbfb6078 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -109,6 +109,21 @@ public Map asMap() { return entries; } + @Override + public int hashCode() { + return entries.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof DisplayData) { + DisplayData that = (DisplayData) obj; + return Objects.equals(this.entries, that.entries); + } + + return false; + } + @Override public String toString() { StringBuilder builder = new StringBuilder(); @@ -842,7 +857,6 @@ public ItemBuilder addIfNotDefault(String key, boolean value, boolean defaultVal @Override public ItemBuilder add(String key, Instant value) { - checkNotNull(value); return addItemIf(true, key, Type.TIMESTAMP, value); } @@ -859,7 +873,6 @@ public ItemBuilder addIfNotDefault( @Override public ItemBuilder add(String key, Duration value) { - checkNotNull(value); return addItemIf(true, key, Type.DURATION, value); } @@ -876,7 +889,6 @@ public ItemBuilder addIfNotDefault( @Override public ItemBuilder add(String key, Class value) { - checkNotNull(value); return addItemIf(true, key, Type.JAVA_CLASS, value); } @@ -910,17 +922,17 @@ public ItemBuilder addIfNotDefault( @Override public ItemBuilder add(String key, Type type, Object value) { - checkNotNull(value); checkNotNull(type); return addItemIf(true, key, type, value); } private ItemBuilder addItemIf(boolean condition, String key, Type type, Object value) { - checkNotNull(key); - checkArgument(!key.isEmpty()); - + checkNotNull(key, "Display data keys cannot be null or empty."); + checkArgument(!key.isEmpty(), "Display data keys cannot be null or empty."); commitLatest(); + if (condition) { + checkNotNull(value, "Display data values cannot be null. Key: [%s]", key); latestItem = Item.create(latestNs, key, type, value); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java new file mode 100644 index 0000000000..560fef1b38 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.not; + +import com.google.common.collect.ImmutableSet; +import org.hamcrest.FeatureMatcher; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Set; + +/** + * Unit tests for {@link PipelineOptionsReflector}. + */ +@RunWith(JUnit4.class) +public class PipelineOptionsReflectorTest { + @Test + public void testGetOptionSpecs() throws NoSuchMethodException { + Set properties = + PipelineOptionsReflector.getOptionSpecs(SimpleOptions.class); + + assertThat(properties, Matchers.hasItems(PipelineOptionSpec.of( + SimpleOptions.class, "foo", SimpleOptions.class.getDeclaredMethod("getFoo")))); + } + + interface SimpleOptions extends PipelineOptions { + String getFoo(); + void setFoo(String value); + } + + @Test + public void testFiltersNonGetterMethods() { + Set properties = + PipelineOptionsReflector.getOptionSpecs(OnlyTwoValidGetters.class); + + assertThat(properties, not(hasItem(hasName(isOneOf("misspelled", "hasParameter", "prefix"))))); + } + + interface OnlyTwoValidGetters extends PipelineOptions { + String getFoo(); + void setFoo(String value); + + boolean isBar(); + void setBar(boolean value); + + String gtMisspelled(); + void setMisspelled(String value); + + String getHasParameter(String value); + void setHasParameter(String value); + + String noPrefix(); + void setNoPrefix(String value); + } + + @Test + public void testBaseClassOptions() { + Set props = + PipelineOptionsReflector.getOptionSpecs(ExtendsSimpleOptions.class); + + assertThat(props, Matchers.hasItem( + allOf(hasName("foo"), hasClass(SimpleOptions.class)))); + assertThat(props, Matchers.hasItem( + allOf(hasName("foo"), hasClass(ExtendsSimpleOptions.class)))); + assertThat(props, Matchers.hasItem( + allOf(hasName("bar"), hasClass(ExtendsSimpleOptions.class)))); + } + + interface ExtendsSimpleOptions extends SimpleOptions { + @Override String getFoo(); + @Override void setFoo(String value); + + String getBar(); + void setBar(String value); + } + + @Test + public void testExcludesNonPipelineOptionsMethods() { + Set properties = + PipelineOptionsReflector.getOptionSpecs(ExtendsNonPipelineOptions.class); + + assertThat(properties, not(hasItem(hasName("foo")))); + } + + interface NoExtendsClause { + String getFoo(); + void setFoo(String value); + } + + interface ExtendsNonPipelineOptions extends NoExtendsClause, PipelineOptions {} + + @Test + public void testExcludesHiddenInterfaces() { + Set properties = + PipelineOptionsReflector.getOptionSpecs(HiddenOptions.class); + + assertThat(properties, not(hasItem(hasName("foo")))); + } + + @Hidden + interface HiddenOptions extends PipelineOptions { + String getFoo(); + void setFoo(String value); + } + + @Test + public void testMultipleInputInterfaces() { + Set> interfaces = + ImmutableSet.>of( + BaseOptions.class, + ExtendOptions1.class, + ExtendOptions2.class); + + Set props = PipelineOptionsReflector.getOptionSpecs(interfaces); + + assertThat(props, Matchers.hasItem(allOf(hasName("baseOption"), hasClass(BaseOptions.class)))); + assertThat(props, Matchers.hasItem( + allOf(hasName("extendOption1"), hasClass(ExtendOptions1.class)))); + assertThat(props, Matchers.hasItem( + allOf(hasName("extendOption2"), hasClass(ExtendOptions2.class)))); + } + + interface BaseOptions extends PipelineOptions { + String getBaseOption(); + void setBaseOption(String value); + } + + interface ExtendOptions1 extends BaseOptions { + String getExtendOption1(); + void setExtendOption1(String value); + } + + interface ExtendOptions2 extends BaseOptions { + String getExtendOption2(); + void setExtendOption2(String value); + } + + private static Matcher hasName(String name) { + return hasName(is(name)); + } + + private static Matcher hasName(Matcher matcher) { + return new FeatureMatcher(matcher, "name", "name") { + @Override + protected String featureValueOf(PipelineOptionSpec actual) { + return actual.getName(); + } + }; + } + + private static Matcher hasClass(Class clazz) { + return new FeatureMatcher>( + Matchers.>is(clazz), "defining class", "class") { + @Override + protected Class featureValueOf(PipelineOptionSpec actual) { + return actual.getDefiningInterface(); + } + }; + } + + private static Matcher hasGetter(String methodName) { + return new FeatureMatcher( + is(methodName), "getter method", "name") { + @Override + protected String featureValueOf(PipelineOptionSpec actual) { + return actual.getGetterMethod().getName(); + } + }; + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java index 7eb5822b43..70e685d500 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java @@ -16,12 +16,23 @@ package com.google.cloud.dataflow.sdk.options; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -32,12 +43,19 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import org.hamcrest.Matchers; +import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.rules.ExternalResource; +import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -47,6 +65,14 @@ @RunWith(JUnit4.class) public class ProxyInvocationHandlerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); + @Rule public TestRule resetPipelineOptionsRegistry = new ExternalResource() { + @Override + protected void before() { + PipelineOptionsFactory.resetRegistry(); + } + }; + + private static final ObjectMapper MAPPER = new ObjectMapper(); /** A test interface with some primitives and objects. */ public static interface Simple extends PipelineOptions { @@ -431,6 +457,19 @@ public void testPartialMethodConflictProvidesSameValue() throws Exception { assertEquals(5, partialMethodConflict.as(Simple.class).getPrimitive()); } + @Test + public void testResetRegistry() { + Set> defaultRegistry = + new HashSet<>(PipelineOptionsFactory.getRegisteredOptions()); + assertThat(defaultRegistry, not(hasItem(FooOptions.class))); + + PipelineOptionsFactory.register(FooOptions.class); + assertThat(PipelineOptionsFactory.getRegisteredOptions(), hasItem(FooOptions.class)); + + PipelineOptionsFactory.resetRegistry(); + assertEquals(defaultRegistry, PipelineOptionsFactory.getRegisteredOptions()); + } + @Test public void testJsonConversionForDefault() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); @@ -682,10 +721,233 @@ public void testJsonConversionOfSerializableWithMetadataProperty() throws Except assertEquals("TestString", options2.getValue().getValue()); } + @Test + public void testDisplayDataItemProperties() { + PipelineOptions options = PipelineOptionsFactory.create(); + options.setTempLocation("myTemp"); + DisplayData displayData = DisplayData.from(options); + + assertThat(displayData, hasDisplayItem(allOf( + hasKey("tempLocation"), + hasType(DisplayData.Type.STRING), + hasValue("myTemp"), + hasNamespace(PipelineOptions.class) + ))); + } + + @Test + public void testDisplayDataTypes() { + Instant now = Instant.now(); + + TypedOptions options = PipelineOptionsFactory.as(TypedOptions.class); + options.setInteger(1234); + options.setTimestamp(now); + options.setJavaClass(ProxyInvocationHandlerTest.class); + options.setObject(new Serializable() { + @Override + public String toString() { + return "foobar"; + } + }); + + DisplayData displayData = DisplayData.from(options); + + assertThat(displayData, hasDisplayItem("integer", 1234)); + assertThat(displayData, hasDisplayItem("timestamp", now)); + assertThat(displayData, hasDisplayItem("javaClass", ProxyInvocationHandlerTest.class)); + assertThat(displayData, hasDisplayItem("object", "foobar")); + } + + interface TypedOptions extends PipelineOptions { + int getInteger(); + void setInteger(int value); + + Instant getTimestamp(); + void setTimestamp(Instant value); + + Class getJavaClass(); + void setJavaClass(Class value); + + Object getObject(); + void setObject(Object value); + } + + @Test + public void testDisplayDataInheritanceNamespace() { + ExtendsBaseOptions options = PipelineOptionsFactory.as(ExtendsBaseOptions.class); + options.setFoo("bar"); + + DisplayData displayData = DisplayData.from(options); + + assertThat(displayData, hasDisplayItem(allOf( + hasKey("foo"), + hasValue("bar"), + hasNamespace(ExtendsBaseOptions.class) + ))); + } + + interface BaseOptions extends PipelineOptions { + String getFoo(); + void setFoo(String value); + } + + interface ExtendsBaseOptions extends BaseOptions { + @Override String getFoo(); + @Override void setFoo(String value); + } + + @Test + public void testDisplayDataExcludedFromOverriddenBaseClass() { + ExtendsBaseOptions options = PipelineOptionsFactory.as(ExtendsBaseOptions.class); + options.setFoo("bar"); + + DisplayData displayData = DisplayData.from(options); + assertThat(displayData, not(hasDisplayItem(hasNamespace(BaseOptions.class)))); + } + + @Test + public void testDisplayDataIncludedForDisjointInterfaceHierarchies() { + FooOptions fooOptions = PipelineOptionsFactory.as(FooOptions.class); + fooOptions.setFoo("foo"); + + BarOptions barOptions = fooOptions.as(BarOptions.class); + barOptions.setBar("bar"); + + DisplayData data = DisplayData.from(barOptions); + assertThat(data, hasDisplayItem(allOf(hasKey("foo"), hasNamespace(FooOptions.class)))); + assertThat(data, hasDisplayItem(allOf(hasKey("bar"), hasNamespace(BarOptions.class)))); + } + + interface FooOptions extends PipelineOptions { + String getFoo(); + void setFoo(String value); + } + + interface BarOptions extends PipelineOptions { + String getBar(); + void setBar(String value); + } + + @Test + public void testDisplayDataExcludesDefaultValues() { + PipelineOptions options = PipelineOptionsFactory.as(HasDefaults.class); + DisplayData data = DisplayData.from(options); + + assertThat(data, not(hasDisplayItem(hasKey("foo")))); + } + + interface HasDefaults extends PipelineOptions { + @Default.String("bar") + String getFoo(); + void setFoo(String value); + } + + @Test + public void testDisplayDataExcludesValuesAccessedButNeverSet() { + HasDefaults options = PipelineOptionsFactory.as(HasDefaults.class); + assertEquals("bar", options.getFoo()); + + DisplayData data = DisplayData.from(options); + assertThat(data, not(hasDisplayItem(hasKey("foo")))); + } + + @Test + public void testDisplayDataIncludesExplicitlySetDefaults() { + HasDefaults options = PipelineOptionsFactory.as(HasDefaults.class); + String defaultValue = options.getFoo(); + options.setFoo(defaultValue); + + DisplayData data = DisplayData.from(options); + assertThat(data, hasDisplayItem("foo", defaultValue)); + } + + @Test + public void testDisplayDataNullValuesConvertedToEmptyString() { + FooOptions options = PipelineOptionsFactory.as(FooOptions.class); + options.setFoo(null); + + DisplayData data = DisplayData.from(options); + assertThat(data, hasDisplayItem("foo", "")); + } + + @Test + public void testDisplayDataJsonSerialization() throws IOException { + FooOptions options = PipelineOptionsFactory.as(FooOptions.class); + options.setFoo("bar"); + + @SuppressWarnings("unchecked") + Map map = MAPPER.readValue(MAPPER.writeValueAsBytes(options), Map.class); + + assertThat("main pipeline options data keyed as 'options'", map, Matchers.hasKey("options")); + assertThat("display data keyed as 'display_data'", map, Matchers.hasKey("display_data")); + + Map expectedDisplayItem = ImmutableMap.builder() + .put("namespace", FooOptions.class.getName()) + .put("key", "foo") + .put("value", "bar") + .put("type", "STRING") + .build(); + + @SuppressWarnings("unchecked") + List> deserializedDisplayData = (List>) map.get("display_data"); + assertThat(deserializedDisplayData, hasItem(expectedDisplayItem)); + } + + @Test + public void testDisplayDataFromDeserializedJson() throws Exception { + FooOptions options = PipelineOptionsFactory.as(FooOptions.class); + options.setFoo("bar"); + DisplayData data = DisplayData.from(options); + assertThat(data, hasDisplayItem("foo", "bar")); + + FooOptions deserializedOptions = serializeDeserialize(FooOptions.class, options); + DisplayData dataAfterDeserialization = DisplayData.from(deserializedOptions); + assertEquals(data, dataAfterDeserialization); + } + + @Test + public void testDisplayDataDeserializationWithRegistration() throws Exception { + PipelineOptionsFactory.register(HasClassOptions.class); + HasClassOptions options = PipelineOptionsFactory.as(HasClassOptions.class); + options.setClassOption(ProxyInvocationHandlerTest.class); + + PipelineOptions deserializedOptions = serializeDeserialize(PipelineOptions.class, options); + DisplayData displayData = DisplayData.from(deserializedOptions); + assertThat(displayData, hasDisplayItem("classOption", ProxyInvocationHandlerTest.class)); + } + + @Test + public void testDisplayDataMissingPipelineOptionsRegistration() throws Exception { + HasClassOptions options = PipelineOptionsFactory.as(HasClassOptions.class); + options.setClassOption(ProxyInvocationHandlerTest.class); + + PipelineOptions deserializedOptions = serializeDeserialize(PipelineOptions.class, options); + DisplayData displayData = DisplayData.from(deserializedOptions); + String expectedJsonValue = MAPPER.writeValueAsString(ProxyInvocationHandlerTest.class); + assertThat(displayData, hasDisplayItem("classOption", expectedJsonValue)); + } + + interface HasClassOptions extends PipelineOptions { + Class getClassOption(); + void setClassOption(Class value); + } + + @Test + public void testDisplayDataJsonValueSetAfterDeserialization() throws Exception { + FooOptions options = PipelineOptionsFactory.as(FooOptions.class); + options.setFoo("bar"); + DisplayData data = DisplayData.from(options); + assertThat(data, hasDisplayItem("foo", "bar")); + + FooOptions deserializedOptions = serializeDeserialize(FooOptions.class, options); + deserializedOptions.setFoo("baz"); + DisplayData dataAfterDeserialization = DisplayData.from(deserializedOptions); + assertThat(dataAfterDeserialization, hasDisplayItem("foo", "baz")); + } + private T serializeDeserialize(Class kls, PipelineOptions options) throws Exception { - ObjectMapper mapper = new ObjectMapper(); - String value = mapper.writeValueAsString(options); - return mapper.readValue(value, PipelineOptions.class).as(kls); + String value = MAPPER.writeValueAsString(options); + return MAPPER.readValue(value, PipelineOptions.class).as(kls); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 04a6bbd9a9..699f5022c2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -199,8 +199,9 @@ public void testSettingOfSdkPipelineOptions() throws IOException { settings.put("numberOfWorkerHarnessThreads", 0); settings.put("experiments", null); - assertEquals(ImmutableMap.of("options", settings), - job.getEnvironment().getSdkPipelineOptions()); + Map sdkPipelineOptions = job.getEnvironment().getSdkPipelineOptions(); + assertThat(sdkPipelineOptions, hasKey("options")); + assertEquals(settings, sdkPipelineOptions.get("options")); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index 9d5d2206b8..625bfa168f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -379,6 +379,31 @@ public void populateDisplayData(Builder builder) { .testEquals(); } + @Test + public void testDisplayDataEquality() { + HasDisplayData component1 = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar"); + } + }; + HasDisplayData component2 = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add("foo", "bar"); + } + }; + + DisplayData component1DisplayData1 = DisplayData.from(component1); + DisplayData component1DisplayData2 = DisplayData.from(component1); + DisplayData component2DisplayData = DisplayData.from(component2); + + new EqualsTester() + .addEqualityGroup(component1DisplayData1, component1DisplayData2) + .addEqualityGroup(component2DisplayData) + .testEquals(); + } + @Test public void testAnonymousClassNamespace() { DisplayData data = From 8da41ff5c2b3695d0bde4f6ac615a18bb1b86c97 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 21 Apr 2016 13:36:42 -0700 Subject: [PATCH 339/751] Register DisplayData from IO primatives (cherry picked from commit 359dec80969e601182dc6d98c833811da1d2be87) --- .../io/BoundedReadFromUnboundedSource.java | 11 +++++ .../dataflow/sdk/io/CompressedSource.java | 17 +++++++ .../cloud/dataflow/sdk/io/DatastoreIO.java | 21 +++++++++ .../cloud/dataflow/sdk/io/FileBasedSink.java | 40 ++++++++++------- .../dataflow/sdk/io/FileBasedSource.java | 7 +++ .../dataflow/sdk/io/OffsetBasedSource.java | 10 +++++ .../google/cloud/dataflow/sdk/io/Read.java | 15 +++++++ .../google/cloud/dataflow/sdk/io/Sink.java | 13 +++++- .../google/cloud/dataflow/sdk/io/Source.java | 13 +++++- .../google/cloud/dataflow/sdk/io/Write.java | 8 ++++ .../google/cloud/dataflow/sdk/io/XmlSink.java | 9 ++++ .../cloud/dataflow/sdk/io/XmlSource.java | 11 ++++- .../cloud/dataflow/sdk/io/AvroSourceTest.java | 15 +++++++ .../BoundedReadFromUnboundedSourceTest.java | 19 +++++++- .../dataflow/sdk/io/CompressedSourceTest.java | 27 +++++++++++ .../dataflow/sdk/io/DatastoreIOTest.java | 31 +++++++++++++ .../cloud/dataflow/sdk/io/ReadTest.java | 45 +++++++++++++++++-- .../cloud/dataflow/sdk/io/WriteTest.java | 21 +++++++++ .../cloud/dataflow/sdk/io/XmlSinkTest.java | 19 +++++++- .../cloud/dataflow/sdk/io/XmlSourceTest.java | 22 +++++++++ 20 files changed, 351 insertions(+), 23 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java index 52c730cc39..5a1a29a264 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.IntervalBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -104,6 +105,16 @@ public String getKindString() { return "Read(" + approximateSimpleName(source.getClass()) + ")"; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + // We explicitly do not register base-class data, instead we use the delegate inner source. + builder + .add("source", source.getClass()) + .addIfNotDefault("maxRecords", maxNumRecords, Long.MAX_VALUE) + .addIfNotNull("maxReadTime", maxReadTime) + .include(source); + } + private static class UnboundedToBoundedSourceAdapter extends BoundedSource> { private final UnboundedSource source; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index b0636ea35f..05f33d6ba1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; @@ -318,6 +319,22 @@ public final boolean producesSortedKeys(PipelineOptions options) throws Exceptio return sourceDelegate.producesSortedKeys(options); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + // We explicitly do not register base-class data, instead we use the delegate inner source. + builder + .include(sourceDelegate) + .add("source", sourceDelegate.getClass()); + + if (channelFactory instanceof Enum) { + // GZIP and BZIP are implemented as enums; Enum classes are anonymous, so use the .name() + // value instead + builder.add("compressionMode", ((Enum) channelFactory).name()); + } else { + builder.add("compressionMode", channelFactory.getClass()); + } + } + /** * Returns the delegate source's default output coder. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java index f618bc9d63..482cdb57ba 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java @@ -56,6 +56,7 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -396,6 +397,19 @@ public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { return getPropertyMap(entity).get("entity_bytes").getIntegerValue(); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotDefault("host", host, DEFAULT_HOST) + .addIfNotNull("dataset", datasetId) + .addIfNotNull("namespace", namespace); + + if (query != null) { + builder.add("query", query.toString()); + } + } + @Override public String toString() { return MoreObjects.toStringHelper(getClass()) @@ -597,6 +611,13 @@ public void validate(PipelineOptions options) { public DatastoreWriteOperation createWriteOperation(PipelineOptions options) { return new DatastoreWriteOperation(this); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .addIfNotDefault("host", host, DEFAULT_HOST) + .addIfNotNull("dataset", datasetId); + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index dda500c369..850ea01e45 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -32,6 +32,7 @@ import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; @@ -142,6 +143,30 @@ public void validate(PipelineOptions options) {} @Override public abstract FileBasedWriteOperation createWriteOperation(PipelineOptions options); + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + String fileNamePattern = String.format("%s%s%s", + baseOutputFilename, fileNamingTemplate, getFileExtension(extension)); + builder.add("fileNamePattern", fileNamePattern); + } + + /** + * Returns the file extension to be used. If the user did not request a file + * extension then this method returns the empty string. Otherwise this method + * adds a {@code "."} to the beginning of the users extension if one is not present. + */ + private static String getFileExtension(String usersExtension) { + if (usersExtension == null || usersExtension.isEmpty()) { + return ""; + } + if (usersExtension.startsWith(".")) { + return usersExtension; + } + return "." + usersExtension; + } + /** * Abstract {@link Sink.WriteOperation} that manages the process of writing to a * {@link FileBasedSink}. @@ -363,21 +388,6 @@ protected final List generateDestinationFilenames(int numFiles) { return destFilenames; } - /** - * Returns the file extension to be used. If the user did not request a file - * extension then this method returns the empty string. Otherwise this method - * adds a {@code "."} to the beginning of the users extension if one is not present. - */ - private String getFileExtension(String usersExtension) { - if (usersExtension == null || usersExtension.isEmpty()) { - return ""; - } - if (usersExtension.startsWith(".")) { - return usersExtension; - } - return "." + usersExtension; - } - /** * Removes temporary output files. Uses the temporary filename to find files to remove. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java index 5d32a9d08f..468a276b43 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java @@ -15,6 +15,7 @@ package com.google.cloud.dataflow.sdk.io; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.common.base.Preconditions; @@ -257,6 +258,12 @@ private static long getEstimatedSizeOfFilesBySampling( / selectedFiles.size(); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder.add("filePattern", getFileOrPatternSpec()); + } + private ListenableFuture>> createFutureForFileSplit( final String file, final long desiredBundleSizeBytes, diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java index d581b80ca2..04b61b8771 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java @@ -17,6 +17,7 @@ import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; import com.google.cloud.dataflow.sdk.io.range.RangeTracker; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.base.Preconditions; import org.slf4j.Logger; @@ -198,6 +199,15 @@ public boolean allowsDynamicSplitting() { return true; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .add("minBundleSize", minBundleSize) + .addIfNotDefault("startOffset", startOffset, 0) + .addIfNotDefault("endOffset", endOffset, Long.MAX_VALUE); + } + /** * A {@link Source.Reader} that implements code common to readers of all * {@link OffsetBasedSource}s. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java index cde87696bb..803423b474 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; @@ -143,6 +144,13 @@ public String getKindString() { return "Read(" + approximateSimpleName(source.getClass()) + ")"; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("source", source.getClass()) + .include(source); + } + static { registerDefaultTransformEvaluator(); } @@ -249,5 +257,12 @@ public final PCollection apply(PInput input) { public String getKindString() { return "Read(" + approximateSimpleName(source.getClass()) + ")"; } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("source", source.getClass()) + .include(source); + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java index a5649ceb5e..62bfbc1ad2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java @@ -17,6 +17,8 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import java.io.Serializable; @@ -118,7 +120,7 @@ * @param the type that will be written to the Sink. */ @Experimental(Experimental.Kind.SOURCE_SINK) -public abstract class Sink implements Serializable { +public abstract class Sink implements Serializable, HasDisplayData { /** * Ensures that the sink is valid and can be written to before the write operation begins. One * should use {@link com.google.common.base.Preconditions} to implement this method. @@ -130,6 +132,15 @@ public abstract class Sink implements Serializable { */ public abstract WriteOperation createWriteOperation(PipelineOptions options); + /** + * {@inheritDoc} + * + *

          By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(DisplayData.Builder builder) {} + /** * A {@link WriteOperation} defines the process of a parallel write of objects to a Sink. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java index 4a020787f5..05a86ca4a5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java @@ -18,6 +18,8 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import org.joda.time.Instant; @@ -51,7 +53,7 @@ * @param Type of elements read by the source. */ @Experimental(Experimental.Kind.SOURCE_SINK) -public abstract class Source implements Serializable { +public abstract class Source implements Serializable, HasDisplayData { /** * Checks that this source is valid, before it can be used in a pipeline. * @@ -65,6 +67,15 @@ public abstract class Source implements Serializable { */ public abstract Coder getDefaultOutputCoder(); + /** + * {@inheritDoc} + * + *

          By default, does not register any display data. Implementors may override this method + * to provide their own display metadata. + */ + @Override + public void populateDisplayData(DisplayData.Builder builder) {} + /** * The interface that readers of custom input sources must implement. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java index 65d3c992d8..2bbe878b2d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java @@ -26,6 +26,7 @@ import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -73,6 +74,13 @@ public PDone apply(PCollection input) { return createWrite(input, sink.createWriteOperation(options)); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder + .add("sink", sink.getClass()) + .include(sink); + } + /** * Returns the {@link Sink} associated with this PTransform. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java index b728c0a792..90d3bfbcdd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation; import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.Preconditions; @@ -219,6 +220,14 @@ public void validate(PipelineOptions options) { public XmlWriteOperation createWriteOperation(PipelineOptions options) { return new XmlWriteOperation<>(this); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull("rootElement", rootElementName) + .addIfNotNull("recordClass", classToBind); + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java index 1ead39187d..c8781f6e1d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.coders.JAXBCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.base.Preconditions; import org.codehaus.stax2.XMLInputFactory2; @@ -34,7 +35,6 @@ import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; - import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; @@ -214,6 +214,15 @@ public void validate() { recordClass, "recordClass is null. Use builder method withRecordClass() to set this."); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull("rootElement", rootElement) + .addIfNotNull("recordElement", recordElement) + .addIfNotNull("recordClass", recordClass); + } + @Override public Coder getDefaultOutputCoder() { return JAXBCoder.of(recordClass); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java index 0990294d20..e2c4299fe5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -28,6 +30,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.base.MoreObjects; import org.apache.avro.Schema; @@ -506,6 +509,18 @@ public void testSeekerFindAllLocations() { } } + @Test + public void testDisplayData() { + AvroSource source = AvroSource + .from("foobar.txt") + .withSchema(Bird.class) + .withMinBundleSize(1234); + + DisplayData displayData = DisplayData.from(source); + assertThat(displayData, hasDisplayItem("filePattern", "foobar.txt")); + assertThat(displayData, hasDisplayItem("minBundleSize", 1234)); + } + /** * Class that will encode to a fixed size: 16 bytes. * diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java index d01c036344..963ceb9044 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; + import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -28,6 +30,7 @@ import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -37,13 +40,14 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** Unit tests for {@link BoundedReadFromUnboundedSource}. */ @RunWith(JUnit4.class) -public class BoundedReadFromUnboundedSourceTest { +public class BoundedReadFromUnboundedSourceTest implements Serializable{ private static final int NUM_RECORDS = 100; private static List finalizeTracker = null; @@ -65,6 +69,19 @@ public void testTimeBound() throws Exception { test(false, true); } + @Test + public void testForwardsDisplayData() { + TestCountingSource src = new TestCountingSource(1234) { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + + BoundedReadFromUnboundedSource> read = Read.from(src).withMaxNumRecords(5); + assertThat(DisplayData.from(read), includes(src)); + } + private static class Checker implements SerializableFunction>, Void> { private final boolean dedup; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index fe855101c6..fe0e59ad70 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -16,9 +16,14 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; + import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.Pipeline; @@ -31,6 +36,7 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.io.Files; import com.google.common.primitives.Bytes; @@ -330,6 +336,27 @@ public void testCompressedReadMultipleFiles() throws Exception { p.run(); } + @Test + public void testDisplayData() { + ByteSource inputSource = new ByteSource("foobar.txt", 1) { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + + CompressedSource compressedSource = CompressedSource.from(inputSource); + CompressedSource gzipSource = compressedSource.withDecompression(CompressionMode.GZIP); + + DisplayData compressedSourceDisplayData = DisplayData.from(compressedSource); + DisplayData gzipDisplayData = DisplayData.from(gzipSource); + + assertThat(compressedSourceDisplayData, hasDisplayItem(hasKey("compressionMode"))); + assertThat(gzipDisplayData, hasDisplayItem("compressionMode", CompressionMode.GZIP.toString())); + assertThat(compressedSourceDisplayData, hasDisplayItem("source", inputSource.getClass())); + assertThat(compressedSourceDisplayData, includes(inputSource)); + } + /** * Generate byte array of given size. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java index 4cc3ace1b5..edf7c243f1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java @@ -17,6 +17,8 @@ package com.google.cloud.dataflow.sdk.io; import static com.google.api.services.datastore.client.DatastoreHelper.makeKey; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; @@ -54,6 +56,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.common.collect.Lists; @@ -193,6 +196,22 @@ public void testSourceValidationSucceedsNamespace() throws Exception { source.validate(); } + @Test + public void testSourceDipslayData() { + DatastoreIO.Source source = DatastoreIO.source() + .withDataset(DATASET) + .withQuery(QUERY) + .withHost(HOST) + .withNamespace(NAMESPACE); + + DisplayData displayData = DisplayData.from(source); + + assertThat(displayData, hasDisplayItem("dataset", DATASET)); + assertThat(displayData, hasDisplayItem("query", QUERY.toString())); + assertThat(displayData, hasDisplayItem("host", HOST)); + assertThat(displayData, hasDisplayItem("namespace", NAMESPACE)); + } + @Test public void testSinkDoesNotAllowNullHost() throws Exception { thrown.expect(NullPointerException.class); @@ -225,6 +244,18 @@ public void testSinkValidationSucceedsWithDataset() throws Exception { sink.validate(testPipelineOptions(null)); } + @Test + public void testSinkDipslayData() { + DatastoreIO.Sink sink = DatastoreIO.sink() + .withDataset(DATASET) + .withHost(HOST); + + DisplayData displayData = DisplayData.from(sink); + + assertThat(displayData, hasDisplayItem("dataset", DATASET)); + assertThat(displayData, hasDisplayItem("host", HOST)); + } + @Test public void testQuerySplitBasic() throws Exception { KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java index 8dc517a8e8..530687be14 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java @@ -16,10 +16,17 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; + +import static org.hamcrest.MatcherAssert.assertThat; + import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import org.joda.time.Duration; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -27,17 +34,17 @@ import org.junit.runners.JUnit4; import java.io.IOException; +import java.io.Serializable; import java.util.List; - import javax.annotation.Nullable; /** * Tests for {@link Read}. */ @RunWith(JUnit4.class) -public class ReadTest { +public class ReadTest implements Serializable{ @Rule - public ExpectedException thrown = ExpectedException.none(); + public transient ExpectedException thrown = ExpectedException.none(); @Test public void failsWhenCustomBoundedSourceIsNotSerializable() { @@ -61,6 +68,38 @@ public void succeedsWhenCustomUnboundedSourceIsSerializable() { Read.from(new SerializableUnboundedSource()); } + @Test + public void testDisplayData() { + SerializableBoundedSource boundedSource = new SerializableBoundedSource() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + SerializableUnboundedSource unboundedSource = new SerializableUnboundedSource() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + Duration maxReadTime = Duration.standardMinutes(2345); + + Read.Bounded bounded = Read.from(boundedSource); + BoundedReadFromUnboundedSource unbounded = Read.from(unboundedSource) + .withMaxNumRecords(1234) + .withMaxReadTime(maxReadTime); + + DisplayData boundedDisplayData = DisplayData.from(bounded); + assertThat(boundedDisplayData, hasDisplayItem("source", boundedSource.getClass())); + assertThat(boundedDisplayData, includes(boundedSource)); + + DisplayData unboundedDisplayData = DisplayData.from(unbounded); + assertThat(unboundedDisplayData, hasDisplayItem("source", unboundedSource.getClass())); + assertThat(unboundedDisplayData, includes(unboundedSource)); + assertThat(unboundedDisplayData, hasDisplayItem("maxRecords", 1234)); + assertThat(unboundedDisplayData, hasDisplayItem("maxReadTime", maxReadTime)); + } + private abstract static class CustomBoundedSource extends BoundedSource { @Override public List> splitIntoBundles( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java index 0d4a70fd19..ca1c7df00d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java @@ -14,6 +14,9 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includes; + import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; @@ -38,6 +41,7 @@ import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; @@ -151,6 +155,23 @@ public void testWriteWithSessions() { new WindowAndReshuffle(Window.into(Sessions.withGapDuration(Duration.millis(1))))); } + @Test + public void testDisplayData() { + TestSink sink = new TestSink() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add("foo", "bar"); + } + }; + Write.Bound write = Write.to(sink); + DisplayData displayData = DisplayData.from(write); + + assertThat(displayData, hasDisplayItem("sink", sink.getClass())); + assertThat(displayData, includes(sink)); + } + + + /** * Performs a Write transform and verifies the Write transform calls the appropriate methods on * a test sink in the correct order, as well as verifies that the elements of a PCollection are diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java index 4b8380d89e..22c1b59f45 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java @@ -16,6 +16,9 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -23,6 +26,7 @@ import com.google.cloud.dataflow.sdk.io.XmlSink.XmlWriter; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.common.collect.Lists; import org.junit.Rule; @@ -40,7 +44,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @@ -160,6 +163,20 @@ public void testCreateWriter() throws Exception { assertNotNull(writer.marshaller); } + @Test + public void testDisplayData() { + XmlSink.Bound sink = XmlSink.write() + .toFilenamePrefix("foobar") + .withRootElement("bird") + .ofRecordClass(Integer.class); + + DisplayData displayData = DisplayData.from(sink); + + assertThat(displayData, hasDisplayItem("fileNamePattern", "foobar-SSSSS-of-NNNNN.xml")); + assertThat(displayData, hasDisplayItem("rootElement", "bird")); + assertThat(displayData, hasDisplayItem("recordClass", Integer.class)); + } + /** * Write a bundle with an XmlWriter and verify the output is expected. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java index 5618ec7a10..198d3857dc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java @@ -17,6 +17,8 @@ import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionExhaustive; import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionFails; import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; @@ -30,6 +32,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.collect.ImmutableList; @@ -819,4 +822,23 @@ public void testReadXMLFilePattern() throws IOException { DataflowAssert.that(output).containsInAnyOrder(expectedResults); p.run(); } + + @Test + public void testDisplayData() { + + + XmlSource source = XmlSource + .from("foo.xml") + .withRootElement("bird") + .withRecordElement("cat") + .withMinBundleSize(1234) + .withRecordClass(Integer.class); + DisplayData displayData = DisplayData.from(source); + + assertThat(displayData, hasDisplayItem("filePattern", "foo.xml")); + assertThat(displayData, hasDisplayItem("rootElement", "bird")); + assertThat(displayData, hasDisplayItem("recordElement", "cat")); + assertThat(displayData, hasDisplayItem("recordClass", Integer.class)); + assertThat(displayData, hasDisplayItem("minBundleSize", 1234)); + } } From 44edd8b3cdf9579a7d9b377ae7e730f0d01f6fce Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 21 Apr 2016 14:04:36 -0700 Subject: [PATCH 340/751] Register DisplayData from composite IO transforms (cherry picked from commit 15b11edef1e24fbffaa37b57494746d53522e04e) --- .../google/cloud/dataflow/sdk/io/AvroIO.java | 25 ++++++++++- .../cloud/dataflow/sdk/io/BigQueryIO.java | 34 +++++++++++++- .../cloud/dataflow/sdk/io/CountingInput.java | 22 +++++++++ .../cloud/dataflow/sdk/io/PubsubIO.java | 33 ++++++++++++++ .../google/cloud/dataflow/sdk/io/TextIO.java | 27 ++++++++++- .../dataflow/sdk/io/bigtable/BigtableIO.java | 27 +++++++++++ .../cloud/dataflow/sdk/io/AvroIOTest.java | 33 ++++++++++++++ .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 45 +++++++++++++++++++ .../dataflow/sdk/io/CountingInputTest.java | 36 +++++++++++++++ .../cloud/dataflow/sdk/io/PubsubIOTest.java | 43 ++++++++++++++++++ .../cloud/dataflow/sdk/io/TextIOTest.java | 35 +++++++++++++++ .../sdk/io/bigtable/BigtableIOTest.java | 37 +++++++++++++++ 12 files changed, 394 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java index f016b5b47b..f2c094d759 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java @@ -25,6 +25,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -324,6 +325,14 @@ public PCollection apply(PInput input) { return pcol; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull("filePattern", filepattern) + .addIfNotDefault("validation", validate, true); + } + @Override protected Coder getDefaultOutputCoder() { return AvroCoder.of(type, schema); @@ -465,6 +474,8 @@ public static Bound withoutValidation() { * @param the type of each of the elements of the input PCollection */ public static class Bound extends PTransform, PDone> { + private static final String DEFAULT_SHARD_TEMPLATE = ShardNameTemplate.INDEX_OF_MAX; + /** The filename to write to. */ @Nullable final String filenamePrefix; @@ -483,7 +494,7 @@ public static class Bound extends PTransform, PDone> { final boolean validate; Bound(Class type) { - this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, type, null, true); + this(null, null, "", 0, DEFAULT_SHARD_TEMPLATE, type, null, true); } Bound( @@ -677,6 +688,18 @@ public PDone apply(PCollection input) { filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema)))); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .add("schema", type) + .addIfNotNull("filePrefix", filenamePrefix) + .addIfNotDefault("shardNameTemplate", shardTemplate, DEFAULT_SHARD_TEMPLATE) + .addIfNotDefault("fileSuffix", filenameSuffix, "") + .addIfNotDefault("numShards", numShards, 0) + .addIfNotDefault("validation", validate, true); + } + /** * Returns the current shard name template string. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index d7895ee021..2694ddaa40 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -50,6 +50,7 @@ import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BigQueryServices; import com.google.cloud.dataflow.sdk.util.BigQueryServices.LoadService; @@ -79,7 +80,6 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -516,6 +516,20 @@ protected Coder getDefaultOutputCoder() { return TableRowJsonCoder.of(); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + if (table != null) { + builder.add("table", toTableSpec(table)); + } + + builder + .addIfNotNull("query", query) + .addIfNotNull("flattenResults", flattenResults) + .addIfNotDefault("validation", validate, true); + } + static { DirectPipelineRunner.registerDefaultTransformEvaluator( Bound.class, new DirectPipelineRunner.TransformEvaluator() { @@ -1046,6 +1060,24 @@ protected Coder getDefaultOutputCoder() { return VoidCoder.of(); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder + .addIfNotNull("table", jsonTableRef) + .addIfNotNull("schema", jsonSchema); + + if (tableRefFunction != null) { + builder.add("tableFn", tableRefFunction.getClass()); + } + + builder + .add("createDisposition", createDisposition.toString()) + .add("writeDisposition", writeDisposition.toString()) + .addIfNotDefault("validation", validate, true); + } + /** Returns the create disposition. */ public CreateDisposition getCreateDisposition() { return createDisposition; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java index 07609ba716..85c3300401 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java @@ -23,6 +23,7 @@ import com.google.cloud.dataflow.sdk.io.Read.Unbounded; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; @@ -108,6 +109,12 @@ private BoundedCountingInput(long numElements) { public PCollection apply(PBegin begin) { return begin.apply(Read.from(CountingSource.upTo(numElements))); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder.add("upTo", numElements); + } } /** @@ -187,5 +194,20 @@ public PCollection apply(PBegin begin) { read.withMaxReadTime(maxReadTime.get()).withMaxNumRecords(maxNumRecords.get())); } } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder.add("timestampFn", timestampFn.getClass()); + + if (maxReadTime.isPresent()) { + builder.add("maxReadTime", maxReadTime.get()); + } + + if (maxNumRecords.isPresent()) { + builder.add("maxRecords", maxNumRecords.get()); + } + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java index ae7ac0db42..e5d08d6e8a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java @@ -40,6 +40,7 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.Transport; @@ -688,6 +689,25 @@ public PCollection apply(PInput input) { } } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder + .addIfNotNull("timestampLabel", timestampLabel) + .addIfNotNull("idLabel", idLabel) + .addIfNotNull("maxReadTime", maxReadTime) + .addIfNotDefault("maxNumRecords", maxNumRecords, 0); + + if (topic != null) { + builder.add("topic", topic.asPath()); + } + + if (subscription != null) { + builder.add("subscription", subscription.asPath()); + } + } + @Override protected Coder getDefaultOutputCoder() { return coder; @@ -973,6 +993,19 @@ public PDone apply(PCollection input) { return PDone.in(input.getPipeline()); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder + .addIfNotNull("timestampLabel", timestampLabel) + .addIfNotNull("idLabel", idLabel); + + if (topic != null) { + builder.add("topic", topic.asPath()); + } + } + @Override protected Coder getDefaultOutputCoder() { return VoidCoder.of(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index d342f250b2..2509f6f518 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -27,6 +27,7 @@ import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -338,6 +339,16 @@ public PCollection apply(PInput input) { return pcol; } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder + .add("compressionType", compressionType.toString()) + .addIfNotDefault("validation", validate, true) + .addIfNotNull("filePattern", filepattern); + } + @Override protected Coder getDefaultOutputCoder() { return coder; @@ -467,6 +478,8 @@ public static Bound withoutValidation() { * @param the type of the elements of the input PCollection */ public static class Bound extends PTransform, PDone> { + private static final String DEFAULT_SHARD_TEMPLATE = ShardNameTemplate.INDEX_OF_MAX; + /** The prefix of each file written, combined with suffix and shardTemplate. */ @Nullable private final String filenamePrefix; /** The suffix of each file written, combined with prefix and shardTemplate. */ @@ -485,7 +498,7 @@ public static class Bound extends PTransform, PDone> { private final boolean validate; Bound(Coder coder) { - this(null, null, "", coder, 0, ShardNameTemplate.INDEX_OF_MAX, true); + this(null, null, "", coder, 0, DEFAULT_SHARD_TEMPLATE, true); } private Bound(String name, String filenamePrefix, String filenameSuffix, Coder coder, @@ -631,6 +644,18 @@ public PDone apply(PCollection input) { filenamePrefix, filenameSuffix, shardTemplate, coder))); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder + .addIfNotNull("filePrefix", filenamePrefix) + .addIfNotDefault("fileSuffix", filenameSuffix, "") + .addIfNotDefault("shardNameTemplate", shardTemplate, DEFAULT_SHARD_TEMPLATE) + .addIfNotDefault("validation", validate, true) + .addIfNotDefault("numShards", numShards, 0); + } + /** * Returns the current shard name template string. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index f025d3ccd9..9e452ba7a4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -39,6 +39,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PBegin; @@ -259,6 +260,21 @@ public void validate(PBegin input) { } } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder.add("tableId", tableId); + + if (options != null) { + builder.add("bigtableOptions", options.toString()); + } + + if (filter != null) { + builder.add("rowFilter", filter.toString()); + } + } + @Override public String toString() { return MoreObjects.toStringHelper(Read.class) @@ -426,6 +442,17 @@ Write withBigtableService(BigtableService bigtableService) { return new Write(options, tableId, bigtableService); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder.add("tableId", tableId); + + if (options != null) { + builder.add("bigtableOptions", options.toString()); + } + } + @Override public String toString() { return MoreObjects.toStringHelper(Write.class) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java index 7db558dc5a..2fa3eafacf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -29,6 +31,7 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; @@ -255,4 +258,34 @@ public void testAvroSinkShardedWrite() throws Exception { } // TODO: for Write only, test withSuffix, // withShardNameTemplate and withoutSharding. + + @Test + public void testReadDisplayData() { + AvroIO.Read.Bound read = AvroIO.Read.from("foo.*") + .withoutValidation(); + + DisplayData displayData = DisplayData.from(read); + assertThat(displayData, hasDisplayItem("filePattern", "foo.*")); + assertThat(displayData, hasDisplayItem("validation", false)); + } + + @Test + public void testWriteDisplayData() { + AvroIO.Write.Bound write = AvroIO.Write + .to("foo") + .withShardNameTemplate("-SS-of-NN-") + .withSuffix("bar") + .withSchema(GenericClass.class) + .withNumShards(100) + .withoutValidation(); + + DisplayData displayData = DisplayData.from(write); + + assertThat(displayData, hasDisplayItem("filePrefix", "foo")); + assertThat(displayData, hasDisplayItem("shardNameTemplate", "-SS-of-NN-")); + assertThat(displayData, hasDisplayItem("fileSuffix", "bar")); + assertThat(displayData, hasDisplayItem("schema", GenericClass.class)); + assertThat(displayData, hasDisplayItem("numShards", 100)); + assertThat(displayData, hasDisplayItem("validation", false)); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 7a7a1e5967..79561cd917 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -16,6 +16,10 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; + +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -37,6 +41,7 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BigQueryServices; import com.google.cloud.dataflow.sdk.util.BigQueryServices.Status; @@ -389,6 +394,24 @@ public boolean accept(File pathname) { }}).length); } + @Test + public void testBuildSourceDisplayData() { + String tableSpec = "project:dataset.tableid"; + + BigQueryIO.Read.Bound read = BigQueryIO.Read + .from(tableSpec) + .fromQuery("myQuery") + .withoutResultFlattening() + .withoutValidation(); + + DisplayData displayData = DisplayData.from(read); + + assertThat(displayData, hasDisplayItem("table", tableSpec)); + assertThat(displayData, hasDisplayItem("query", "myQuery")); + assertThat(displayData, hasDisplayItem("flattenResults", false)); + assertThat(displayData, hasDisplayItem("validation", false)); + } + @Test public void testBuildSink() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") @@ -501,6 +524,28 @@ public void testBuildSinkWithWriteDispositionEmpty() { null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY); } + @Test + public void testBuildSinkDisplayData() { + String tableSpec = "project:dataset.table"; + TableSchema schema = new TableSchema().set("col1", "type1").set("col2", "type2"); + + BigQueryIO.Write.Bound write = BigQueryIO.Write + .to(tableSpec) + .withSchema(schema) + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) + .withWriteDisposition(WriteDisposition.WRITE_APPEND) + .withoutValidation(); + + DisplayData displayData = DisplayData.from(write); + + assertThat(displayData, hasDisplayItem(hasKey("table"))); + assertThat(displayData, hasDisplayItem(hasKey("schema"))); + assertThat(displayData, + hasDisplayItem("createDisposition", CreateDisposition.CREATE_IF_NEEDED.toString())); + assertThat(displayData, + hasDisplayItem("writeDisposition", WriteDisposition.WRITE_APPEND.toString())); + assertThat(displayData, hasDisplayItem("validation", false)); + } private void testWriteValidatesDataset(boolean streaming) { BigQueryOptions options = PipelineOptionsFactory.as(BigQueryOptions.class); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java index cc609532ba..d06688a29c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java @@ -17,6 +17,10 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + +import static org.hamcrest.MatcherAssert.assertThat; + import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.CountingInput.UnboundedCountingInput; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; @@ -26,11 +30,14 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.Max; import com.google.cloud.dataflow.sdk.transforms.Min; +import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.PCollection; +import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -70,6 +77,13 @@ public void testBoundedInput() { p.run(); } + @Test + public void testBoundedDisplayData() { + PTransform input = CountingInput.upTo(1234); + DisplayData displayData = DisplayData.from(input); + assertThat(displayData, hasDisplayItem("upTo", 1234)); + } + @Test @Category(RunnableOnService.class) public void testUnboundedInput() { @@ -112,6 +126,28 @@ public void testUnboundedInputTimestamps() { p.run(); } + @Test + public void testUnboundedDisplayData() { + Duration maxReadTime = Duration.standardHours(5); + SerializableFunction timestampFn = new SerializableFunction() { + @Override + public Instant apply(Long input) { + return Instant.now(); + } + }; + + PTransform input = CountingInput.unbounded() + .withMaxNumRecords(1234) + .withMaxReadTime(maxReadTime) + .withTimestampFn(timestampFn); + + DisplayData displayData = DisplayData.from(input); + + assertThat(displayData, hasDisplayItem("maxRecords", 1234)); + assertThat(displayData, hasDisplayItem("maxReadTime", maxReadTime)); + assertThat(displayData, hasDisplayItem("timestampFn", timestampFn.getClass())); + } + /** * A timestamp function that uses the given value as the timestamp. Because the input values will * not wrap, this function is non-decreasing and meets the timestamp function criteria laid out diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java index 8e7ad29bbe..0eb6ab302b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java @@ -16,12 +16,17 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import com.google.api.client.testing.http.FixedClock; import com.google.api.client.util.Clock; import com.google.api.services.pubsub.model.PubsubMessage; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; @@ -230,4 +235,42 @@ public void timestampLabelRfc3339WithTooLargeYearThrowsError() { // Year 10000 out of range. parseTimestamp("10000-10-29T23:41:41.123999Z"); } + + @Test + public void testReadDisplayData() { + String topic = "projects/project/topics/topic"; + String subscription = "projects/project/subscriptions/subscription"; + Duration maxReadTime = Duration.standardMinutes(5); + PubsubIO.Read.Bound read = PubsubIO.Read + .topic(topic) + .subscription(subscription) + .timestampLabel("myTimestamp") + .idLabel("myId") + .maxNumRecords(1234) + .maxReadTime(maxReadTime); + + DisplayData displayData = DisplayData.from(read); + + assertThat(displayData, hasDisplayItem("topic", topic)); + assertThat(displayData, hasDisplayItem("subscription", subscription)); + assertThat(displayData, hasDisplayItem("timestampLabel", "myTimestamp")); + assertThat(displayData, hasDisplayItem("idLabel", "myId")); + assertThat(displayData, hasDisplayItem("maxNumRecords", 1234)); + assertThat(displayData, hasDisplayItem("maxReadTime", maxReadTime)); + } + + @Test + public void testWriteDisplayData() { + String topic = "projects/project/topics/topic"; + PubsubIO.Write.Bound write = PubsubIO.Write + .topic(topic) + .timestampLabel("myTimestamp") + .idLabel("myId"); + + DisplayData displayData = DisplayData.from(write); + + assertThat(displayData, hasDisplayItem("topic", topic)); + assertThat(displayData, hasDisplayItem("timestampLabel", "myTimestamp")); + assertThat(displayData, hasDisplayItem("idLabel", "myId")); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 40d11d9866..4f76ac0330 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -20,6 +20,8 @@ import static com.google.cloud.dataflow.sdk.TestUtils.LINES_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_INTS_ARRAY; import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES_ARRAY; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; + import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -40,6 +42,7 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.GcsUtil; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; @@ -198,6 +201,20 @@ public void testReadNamed() throws Exception { } } + @Test + public void testReadDisplayData() { + TextIO.Read.Bound read = TextIO.Read + .from("foo.*") + .withCompressionType(CompressionType.BZIP2) + .withoutValidation(); + + DisplayData displayData = DisplayData.from(read); + + assertThat(displayData, hasDisplayItem("filePattern", "foo.*")); + assertThat(displayData, hasDisplayItem("compressionType", CompressionType.BZIP2.toString())); + assertThat(displayData, hasDisplayItem("validation", false)); + } + void runTestWrite(T[] elems, Coder coder) throws Exception { runTestWrite(elems, coder, 1); } @@ -310,6 +327,24 @@ public void testShardedWrite() throws Exception { runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), 5); } + @Test + public void testWriteDisplayData() { + TextIO.Write.Bound write = TextIO.Write + .to("foo") + .withSuffix("bar") + .withShardNameTemplate("-SS-of-NN-") + .withNumShards(100) + .withoutValidation(); + + DisplayData displayData = DisplayData.from(write); + + assertThat(displayData, hasDisplayItem("filePrefix", "foo")); + assertThat(displayData, hasDisplayItem("fileSuffix", "bar")); + assertThat(displayData, hasDisplayItem("shardNameTemplate", "-SS-of-NN-")); + assertThat(displayData, hasDisplayItem("numShards", 100)); + assertThat(displayData, hasDisplayItem("validation", false)); + } + @Test public void testUnsupportedFilePattern() throws IOException { File outFolder = tmpFolder.newFolder(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java index 0afac13e29..5878c6403a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -20,6 +20,9 @@ import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionExhaustive; import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionFails; import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent; + +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verifyNotNull; import static org.hamcrest.Matchers.hasSize; @@ -45,6 +48,7 @@ import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; @@ -403,6 +407,26 @@ public void testReadingWithFilterAndSubSplits() throws Exception { assertSourcesEqualReferenceSource(source, splits, null /* options */); } + @Test + public void testReadingDisplayData() { + RowFilter rowFilter = RowFilter.newBuilder() + .setRowKeyRegexFilter(ByteString.copyFromUtf8("foo.*")) + .build(); + + BigtableIO.Read read = BigtableIO.read() + .withBigtableOptions(BIGTABLE_OPTIONS) + .withTableId("fooTable") + .withRowFilter(rowFilter); + + DisplayData displayData = DisplayData.from(read); + + assertThat(displayData, hasDisplayItem("tableId", "fooTable")); + assertThat(displayData, hasDisplayItem("rowFilter", rowFilter.toString())); + + // BigtableIO adds user-agent to options; assert only on key and not value. + assertThat(displayData, hasDisplayItem(hasKey("bigtableOptions"))); + } + /** Tests that a record gets written to the service and messages are logged. */ @Test public void testWriting() throws Exception { @@ -459,6 +483,19 @@ public void testWritingFailsBadElement() throws Exception { p.run(); } + @Test + public void testWritingDisplayData() { + BigtableIO.Write write = BigtableIO.write() + .withTableId("fooTable") + .withBigtableOptions(BIGTABLE_OPTIONS); + + DisplayData displayData = DisplayData.from(write); + + assertThat(displayData, hasDisplayItem("tableId", "fooTable")); + // BigtableIO adds user-agent to options; assert only on key and not value. + assertThat(displayData, hasDisplayItem(hasKey("bigtableOptions"))); + } + //////////////////////////////////////////////////////////////////////////////////////////// private static final String COLUMN_FAMILY_NAME = "family"; private static final ByteString COLUMN_NAME = ByteString.copyFromUtf8("column"); From a97ec7e1dc70508b3dfcc04451670440b144c198 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 26 Apr 2016 11:44:49 -0700 Subject: [PATCH 341/751] Use java.util.Objects rather than com.google.common.repackaged --- .../dataflow/sdk/options/ProxyInvocationHandler.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index fce2e18993..d6ee0d24b2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.options; -import com.google.api.client.repackaged.com.google.common.base.Objects; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.JsonIgnorePredicate; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.Registration; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; @@ -25,6 +24,7 @@ import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; import com.google.common.base.Defaults; import com.google.common.base.Function; +import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.FluentIterable; @@ -62,6 +62,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; @@ -206,7 +207,7 @@ static BoundValue fromDefault(@Nullable Object value) { @Override public String toString() { - return Objects.toStringHelper(BoundValue.class) + return MoreObjects.toStringHelper(BoundValue.class) .add("value", value) .add("isDefault", isDefault) .toString(); @@ -214,7 +215,7 @@ public String toString() { @Override public int hashCode() { - return Objects.hashCode(value, isDefault); + return Objects.hash(value, isDefault); } @Override @@ -224,7 +225,8 @@ public boolean equals(Object obj) { } BoundValue that = (BoundValue) obj; - return Objects.equal(this.value, that.value) && Objects.equal(this.isDefault, that.isDefault); + return + Objects.equals(this.value, that.value) && Objects.equals(this.isDefault, that.isDefault); } } From 54f5bf93c46d1510f35594e1f88da483d3c0ed17 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 26 Apr 2016 14:07:10 -0700 Subject: [PATCH 342/751] Reference correct Lists import (cherry picked from commit dccada7b6d3a948518339af71e3e8fc4819584a8) --- .../sdk/transforms/windowing/AfterProcessingTimeTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java index 959802fd0d..0a8d534526 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java @@ -178,10 +178,10 @@ public void testBuiltUpToString() { .plusDelayOf(Duration.standardMinutes(10))) .buildTrigger(); - String expected = "AfterWatermark.pastEndOfWindow()" + - ".withLateFirings(AfterProcessingTime" + - ".pastFirstElementInPane()" + - ".plusDelayOf(10 minutes))"; + String expected = "AfterWatermark.pastEndOfWindow()" + + ".withLateFirings(AfterProcessingTime" + + ".pastFirstElementInPane()" + + ".plusDelayOf(10 minutes))"; assertEquals(expected, trigger.toString()); } From 947a1b718a9d56287dcf72e77620f18bd71828ed Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Tue, 26 Apr 2016 14:07:23 -0700 Subject: [PATCH 343/751] Fix multi-line string format (cherry picked from commit 236bce7c536692580d93bcc6e45a6dc37f4f9b0b) --- .../cloud/dataflow/sdk/transforms/windowing/StubTrigger.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java index a9be77b37a..43fa83cfe1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java @@ -15,7 +15,7 @@ */ package com.google.cloud.dataflow.sdk.transforms.windowing; -import com.google.api.client.util.Lists; +import com.google.common.collect.Lists; import org.joda.time.Instant; From ef31c1995427f4ccdf9068ad8024c0fc77c0301f Mon Sep 17 00:00:00 2001 From: Pei He Date: Tue, 26 Apr 2016 14:33:48 -0700 Subject: [PATCH 344/751] Add DirtyBit to represent whether Counters have been committed. --- .../dataflow/sdk/util/common/Counter.java | 462 ++++++++++++------ .../dataflow/sdk/util/common/CounterTest.java | 145 ++++++ 2 files changed, 450 insertions(+), 157 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java index 2c1985c053..a33e06bd05 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java @@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.AtomicDouble; import java.util.Objects; @@ -41,6 +42,14 @@ *

          Counters compare using value equality of their name, kind, and * cumulative value. Equal counters should have equal toString()s. * + *

          After all possible mutations have completed, the reader should check + * {@link #isDirty} for every counter, otherwise updates may be lost. + * + *

          A counter may become dirty without a corresponding update to the value. + * This generally will occur when the calls to {@code addValue()}, {@code committing()}, + * and {@code committed()} are interleaved such that the value is updated + * between the calls to committing and the read of the value. + * * @param the type of values aggregated by this counter */ public abstract class Counter { @@ -257,6 +266,76 @@ public static interface CounterMean { @Nullable public abstract CounterMean getMean(); + /** + * Represents whether counters' values have been committed to the backend. + * + *

          Runners can use this information to optimize counters updates. + * For example, if counters are committed, runners may choose to skip the updates. + * + *

          Counters' state transition table: + * {@code + * Action\Current State COMMITTED DIRTY COMMITTING + * addValue() DIRTY DIRTY DIRTY + * committing() None COMMITTING None + * committed() None None COMMITTED + * } + */ + @VisibleForTesting + enum CommitState { + /** + * There are no local updates that haven't been committed to the backend. + */ + COMMITTED, + /** + * There are local updates that haven't been committed to the backend. + */ + DIRTY, + /** + * Local updates are committing to the backend, but are still pending. + */ + COMMITTING, + } + + /** + * Returns if the counter contains non-committed aggregate. + */ + public boolean isDirty() { + return commitState.get() != CommitState.COMMITTED; + } + + /** + * Changes the counter from {@code CommitState.DIRTY} to {@code CommitState.COMMITTING}. + * + * @return true if successful. False return indicates that the commit state + * was not in {@code CommitState.DIRTY}. + */ + public boolean committing() { + return commitState.compareAndSet(CommitState.DIRTY, CommitState.COMMITTING); + } + + /** + * Changes the counter from {@code CommitState.COMMITTING} to {@code CommitState.COMMITTED}. + * + * @return true if successful. + * + *

          False return indicates that the counter was updated while the committing is pending. + * That counter update might or might not has been committed. The {@code commitState} has to + * stay in {@code CommitState.DIRTY}. + */ + public boolean committed() { + return commitState.compareAndSet(CommitState.COMMITTING, CommitState.COMMITTED); + } + + /** + * Sets the counter to {@code CommitState.DIRTY}. + * + *

          Must be called at the end of {@link #addValue}, {@link #resetToValue}, + * {@link #resetMeanToValue}, and {@link #merge}. + */ + protected void setDirty() { + commitState.set(CommitState.DIRTY); + } + /** * Returns a string representation of the Counter. Useful for debugging logs. * Example return value: "ElementCount:SUM(15)". @@ -345,9 +424,13 @@ public boolean isCompatibleWith(Counter that) { /** The kind of aggregation function to apply to this counter. */ protected final AggregationKind kind; + /** The commit state of this counter. **/ + protected final AtomicReference commitState; + protected Counter(String name, AggregationKind kind) { this.name = name; this.kind = kind; + this.commitState = new AtomicReference<>(CommitState.COMMITTED); } ////////////////////////////////////////////////////////////////////////////// @@ -388,27 +471,31 @@ private LongCounter(String name, AggregationKind kind) { @Override public LongCounter addValue(Long value) { - switch (kind) { - case SUM: - aggregate.addAndGet(value); - deltaAggregate.addAndGet(value); - break; - case MEAN: - addToMeanAndSet(value, mean); - addToMeanAndSet(value, deltaMean); - break; - case MAX: - maxAndSet(value, aggregate); - maxAndSet(value, deltaAggregate); - break; - case MIN: - minAndSet(value, aggregate); - minAndSet(value, deltaAggregate); - break; - default: - throw illegalArgumentException(); + try { + switch (kind) { + case SUM: + aggregate.addAndGet(value); + deltaAggregate.addAndGet(value); + break; + case MEAN: + addToMeanAndSet(value, mean); + addToMeanAndSet(value, deltaMean); + break; + case MAX: + maxAndSet(value, aggregate); + maxAndSet(value, deltaAggregate); + break; + case MIN: + minAndSet(value, aggregate); + minAndSet(value, deltaAggregate); + break; + default: + throw illegalArgumentException(); + } + return this; + } finally { + setDirty(); } - return this; } private void minAndSet(Long value, AtomicLong target) { @@ -463,26 +550,34 @@ public Long getAndResetDelta() { @Override public Counter resetToValue(Long value) { - if (kind == MEAN) { - throw illegalArgumentException(); + try { + if (kind == MEAN) { + throw illegalArgumentException(); + } + aggregate.set(value); + deltaAggregate.set(value); + return this; + } finally { + setDirty(); } - aggregate.set(value); - deltaAggregate.set(value); - return this; } @Override public Counter resetMeanToValue(long elementCount, Long value) { - if (kind != MEAN) { - throw illegalArgumentException(); - } - if (elementCount < 0) { - throw new IllegalArgumentException("elementCount must be non-negative"); + try { + if (kind != MEAN) { + throw illegalArgumentException(); + } + if (elementCount < 0) { + throw new IllegalArgumentException("elementCount must be non-negative"); + } + LongCounterMean counterMean = new LongCounterMean(value, elementCount); + mean.set(counterMean); + deltaMean.set(counterMean); + return this; + } finally { + setDirty(); } - LongCounterMean counterMean = new LongCounterMean(value, elementCount); - mean.set(counterMean); - deltaMean.set(counterMean); - return this; } @Override @@ -504,20 +599,25 @@ public CounterMean getMean() { @Override public Counter merge(Counter that) { - checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - switch (kind) { - case SUM: - case MIN: - case MAX: - return addValue(that.getAggregate()); - case MEAN: - CounterMean thisCounterMean = this.getMean(); - CounterMean thatCounterMean = that.getMean(); - return resetMeanToValue( - thisCounterMean.getCount() + thatCounterMean.getCount(), - thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); - default: - throw illegalArgumentException(); + try { + checkArgument( + this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + switch (kind) { + case SUM: + case MIN: + case MAX: + return addValue(that.getAggregate()); + case MEAN: + CounterMean thisCounterMean = this.getMean(); + CounterMean thatCounterMean = that.getMean(); + return resetMeanToValue( + thisCounterMean.getCount() + thatCounterMean.getCount(), + thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); + default: + throw illegalArgumentException(); + } + } finally { + setDirty(); } } @@ -583,27 +683,31 @@ private DoubleCounter(String name, AggregationKind kind) { @Override public DoubleCounter addValue(Double value) { - switch (kind) { - case SUM: - aggregate.addAndGet(value); - deltaAggregate.addAndGet(value); - break; - case MEAN: - addToMeanAndSet(value, mean); - addToMeanAndSet(value, deltaMean); - break; - case MAX: - maxAndSet(value, aggregate); - maxAndSet(value, deltaAggregate); - break; - case MIN: - minAndSet(value, aggregate); - minAndSet(value, deltaAggregate); - break; - default: - throw illegalArgumentException(); + try { + switch (kind) { + case SUM: + aggregate.addAndGet(value); + deltaAggregate.addAndGet(value); + break; + case MEAN: + addToMeanAndSet(value, mean); + addToMeanAndSet(value, deltaMean); + break; + case MAX: + maxAndSet(value, aggregate); + maxAndSet(value, deltaAggregate); + break; + case MIN: + minAndSet(value, aggregate); + minAndSet(value, deltaAggregate); + break; + default: + throw illegalArgumentException(); + } + return this; + } finally { + setDirty(); } - return this; } private void addToMeanAndSet(Double value, AtomicReference target) { @@ -649,26 +753,34 @@ public Double getAndResetDelta() { @Override public Counter resetToValue(Double value) { - if (kind == MEAN) { - throw illegalArgumentException(); + try { + if (kind == MEAN) { + throw illegalArgumentException(); + } + aggregate.set(value); + deltaAggregate.set(value); + return this; + } finally { + setDirty(); } - aggregate.set(value); - deltaAggregate.set(value); - return this; } @Override public Counter resetMeanToValue(long elementCount, Double value) { - if (kind != MEAN) { - throw illegalArgumentException(); - } - if (elementCount < 0) { - throw new IllegalArgumentException("elementCount must be non-negative"); + try { + if (kind != MEAN) { + throw illegalArgumentException(); + } + if (elementCount < 0) { + throw new IllegalArgumentException("elementCount must be non-negative"); + } + DoubleCounterMean counterMean = new DoubleCounterMean(value, elementCount); + mean.set(counterMean); + deltaMean.set(counterMean); + return this; + } finally { + setDirty(); } - DoubleCounterMean counterMean = new DoubleCounterMean(value, elementCount); - mean.set(counterMean); - deltaMean.set(counterMean); - return this; } @Override @@ -699,20 +811,25 @@ public CounterMean getMean() { @Override public Counter merge(Counter that) { - checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - switch (kind) { - case SUM: - case MIN: - case MAX: - return addValue(that.getAggregate()); - case MEAN: - CounterMean thisCounterMean = this.getMean(); - CounterMean thatCounterMean = that.getMean(); - return resetMeanToValue( - thisCounterMean.getCount() + thatCounterMean.getCount(), - thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); - default: - throw illegalArgumentException(); + try { + checkArgument( + this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + switch (kind) { + case SUM: + case MIN: + case MAX: + return addValue(that.getAggregate()); + case MEAN: + CounterMean thisCounterMean = this.getMean(); + CounterMean thatCounterMean = that.getMean(); + return resetMeanToValue( + thisCounterMean.getCount() + thatCounterMean.getCount(), + thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); + default: + throw illegalArgumentException(); + } + } finally { + setDirty(); } } @@ -760,14 +877,18 @@ private BooleanCounter(String name, AggregationKind kind) { @Override public BooleanCounter addValue(Boolean value) { - if (kind.equals(AND) && !value) { - aggregate.set(value); - deltaAggregate.set(value); - } else if (kind.equals(OR) && value) { - aggregate.set(value); - deltaAggregate.set(value); + try { + if (kind.equals(AND) && !value) { + aggregate.set(value); + deltaAggregate.set(value); + } else if (kind.equals(OR) && value) { + aggregate.set(value); + deltaAggregate.set(value); + } + return this; + } finally { + setDirty(); } - return this; } @Override @@ -784,9 +905,13 @@ public Boolean getAndResetDelta() { @Override public Counter resetToValue(Boolean value) { - aggregate.set(value); - deltaAggregate.set(value); - return this; + try { + aggregate.set(value); + deltaAggregate.set(value); + return this; + } finally { + setDirty(); + } } @Override @@ -812,8 +937,13 @@ public CounterMean getMean() { @Override public Counter merge(Counter that) { - checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - return addValue(that.getAggregate()); + try { + checkArgument( + this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + return addValue(that.getAggregate()); + } finally { + setDirty(); + } } } @@ -887,7 +1017,8 @@ public CounterMean getMean() { @Override public Counter merge(Counter that) { - checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + checkArgument( + this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); switch (kind) { default: throw illegalArgumentException(); @@ -931,27 +1062,31 @@ private IntegerCounter(String name, AggregationKind kind) { @Override public IntegerCounter addValue(Integer value) { - switch (kind) { - case SUM: - aggregate.getAndAdd(value); - deltaAggregate.getAndAdd(value); - break; - case MEAN: - addToMeanAndSet(value, mean); - addToMeanAndSet(value, deltaMean); - break; - case MAX: - maxAndSet(value, aggregate); - maxAndSet(value, deltaAggregate); - break; - case MIN: - minAndSet(value, aggregate); - minAndSet(value, deltaAggregate); - break; - default: - throw illegalArgumentException(); + try { + switch (kind) { + case SUM: + aggregate.getAndAdd(value); + deltaAggregate.getAndAdd(value); + break; + case MEAN: + addToMeanAndSet(value, mean); + addToMeanAndSet(value, deltaMean); + break; + case MAX: + maxAndSet(value, aggregate); + maxAndSet(value, deltaAggregate); + break; + case MIN: + minAndSet(value, aggregate); + minAndSet(value, deltaAggregate); + break; + default: + throw illegalArgumentException(); + } + return this; + } finally { + setDirty(); } - return this; } private void addToMeanAndSet(int value, AtomicReference target) { @@ -997,26 +1132,34 @@ public Integer getAndResetDelta() { @Override public Counter resetToValue(Integer value) { - if (kind == MEAN) { - throw illegalArgumentException(); + try { + if (kind == MEAN) { + throw illegalArgumentException(); + } + aggregate.set(value); + deltaAggregate.set(value); + return this; + } finally { + setDirty(); } - aggregate.set(value); - deltaAggregate.set(value); - return this; } @Override public Counter resetMeanToValue(long elementCount, Integer value) { - if (kind != MEAN) { - throw illegalArgumentException(); - } - if (elementCount < 0) { - throw new IllegalArgumentException("elementCount must be non-negative"); + try { + if (kind != MEAN) { + throw illegalArgumentException(); + } + if (elementCount < 0) { + throw new IllegalArgumentException("elementCount must be non-negative"); + } + IntegerCounterMean counterMean = new IntegerCounterMean(value, elementCount); + mean.set(counterMean); + deltaMean.set(counterMean); + return this; + } finally { + setDirty(); } - IntegerCounterMean counterMean = new IntegerCounterMean(value, elementCount); - mean.set(counterMean); - deltaMean.set(counterMean); - return this; } @Override @@ -1047,20 +1190,25 @@ public CounterMean getMean() { @Override public Counter merge(Counter that) { - checkArgument(this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - switch (kind) { - case SUM: - case MIN: - case MAX: - return addValue(that.getAggregate()); - case MEAN: - CounterMean thisCounterMean = this.getMean(); - CounterMean thatCounterMean = that.getMean(); - return resetMeanToValue( - thisCounterMean.getCount() + thatCounterMean.getCount(), - thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); - default: - throw illegalArgumentException(); + try { + checkArgument( + this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); + switch (kind) { + case SUM: + case MIN: + case MAX: + return addValue(that.getAggregate()); + case MEAN: + CounterMean thisCounterMean = this.getMean(); + CounterMean thatCounterMean = that.getMean(); + return resetMeanToValue( + thisCounterMean.getCount() + thatCounterMean.getCount(), + thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); + default: + throw illegalArgumentException(); + } + } finally { + setDirty(); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java index 619f523445..b47050b52c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java @@ -27,6 +27,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import com.google.cloud.dataflow.sdk.util.common.Counter.CommitState; import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; import org.junit.Rule; @@ -586,4 +587,148 @@ private void assertIncompatibleMerge(Counter left, Counter right) { thrown.expectMessage("are incompatible"); left.merge(right); } + + @Test + public void testDirtyBit() { + Counter longSum = Counter.longs("long-sum", SUM); + Counter longMean = Counter.longs("long-mean", MEAN); + Counter doubleSum = Counter.doubles("double-sum", SUM); + Counter doubleMean = Counter.doubles("double-sum", MEAN); + Counter intSum = Counter.ints("int-sum", SUM); + Counter intMean = Counter.ints("int-sum", MEAN); + Counter boolAnd = Counter.booleans("and", AND); + + // Test counters are not dirty and are COMMITTED initially. + assertFalse(longSum.isDirty()); + assertFalse(longMean.isDirty()); + assertFalse(doubleSum.isDirty()); + assertFalse(doubleMean.isDirty()); + assertFalse(intSum.isDirty()); + assertFalse(intMean.isDirty()); + assertFalse(boolAnd.isDirty()); + + assertEquals(CommitState.COMMITTED, longSum.commitState.get()); + assertEquals(CommitState.COMMITTED, longMean.commitState.get()); + assertEquals(CommitState.COMMITTED, doubleSum.commitState.get()); + assertEquals(CommitState.COMMITTED, doubleMean.commitState.get()); + assertEquals(CommitState.COMMITTED, intSum.commitState.get()); + assertEquals(CommitState.COMMITTED, intMean.commitState.get()); + assertEquals(CommitState.COMMITTED, boolAnd.commitState.get()); + + // Test counters are dirty after mutating. + longSum.addValue(1L); + longMean.resetMeanToValue(1L, 1L); + doubleSum.addValue(1.0); + doubleMean.resetMeanToValue(1L, 1.0); + intSum.addValue(1); + intMean.resetMeanToValue(1, 1); + boolAnd.addValue(true); + + assertTrue(longSum.isDirty()); + assertTrue(longMean.isDirty()); + assertTrue(doubleSum.isDirty()); + assertTrue(doubleMean.isDirty()); + assertTrue(intSum.isDirty()); + assertTrue(intMean.isDirty()); + assertTrue(boolAnd.isDirty()); + + assertEquals(CommitState.DIRTY, longSum.commitState.get()); + assertEquals(CommitState.DIRTY, longMean.commitState.get()); + assertEquals(CommitState.DIRTY, doubleSum.commitState.get()); + assertEquals(CommitState.DIRTY, doubleMean.commitState.get()); + assertEquals(CommitState.DIRTY, intSum.commitState.get()); + assertEquals(CommitState.DIRTY, intMean.commitState.get()); + assertEquals(CommitState.DIRTY, boolAnd.commitState.get()); + + // Test counters are dirty and are COMMITTING. + assertTrue(longSum.committing()); + assertTrue(longMean.committing()); + assertTrue(doubleSum.committing()); + assertTrue(doubleMean.committing()); + assertTrue(intSum.committing()); + assertTrue(intMean.committing()); + assertTrue(boolAnd.committing()); + + assertTrue(longSum.isDirty()); + assertTrue(longMean.isDirty()); + assertTrue(doubleSum.isDirty()); + assertTrue(doubleMean.isDirty()); + assertTrue(intSum.isDirty()); + assertTrue(intMean.isDirty()); + assertTrue(boolAnd.isDirty()); + + assertEquals(CommitState.COMMITTING, longSum.commitState.get()); + assertEquals(CommitState.COMMITTING, longMean.commitState.get()); + assertEquals(CommitState.COMMITTING, doubleSum.commitState.get()); + assertEquals(CommitState.COMMITTING, doubleMean.commitState.get()); + assertEquals(CommitState.COMMITTING, intSum.commitState.get()); + assertEquals(CommitState.COMMITTING, intMean.commitState.get()); + assertEquals(CommitState.COMMITTING, boolAnd.commitState.get()); + + // Test counters are dirty again after mutating. + longSum.addValue(1L); + longMean.resetMeanToValue(1L, 1L); + doubleSum.addValue(1.0); + doubleMean.resetMeanToValue(1L, 1.0); + intSum.addValue(1); + intMean.resetMeanToValue(1, 1); + boolAnd.addValue(true); + + assertFalse(longSum.committed()); + assertFalse(longMean.committed()); + assertFalse(doubleSum.committed()); + assertFalse(doubleMean.committed()); + assertFalse(intSum.committed()); + assertFalse(intMean.committed()); + assertFalse(boolAnd.committed()); + + assertTrue(longSum.isDirty()); + assertTrue(longMean.isDirty()); + assertTrue(doubleSum.isDirty()); + assertTrue(doubleMean.isDirty()); + assertTrue(intSum.isDirty()); + assertTrue(intMean.isDirty()); + assertTrue(boolAnd.isDirty()); + + assertEquals(CommitState.DIRTY, longSum.commitState.get()); + assertEquals(CommitState.DIRTY, longMean.commitState.get()); + assertEquals(CommitState.DIRTY, doubleSum.commitState.get()); + assertEquals(CommitState.DIRTY, doubleMean.commitState.get()); + assertEquals(CommitState.DIRTY, intSum.commitState.get()); + assertEquals(CommitState.DIRTY, intMean.commitState.get()); + assertEquals(CommitState.DIRTY, boolAnd.commitState.get()); + + // Test counters are not dirty and are COMMITTED. + assertTrue(longSum.committing()); + assertTrue(longMean.committing()); + assertTrue(doubleSum.committing()); + assertTrue(doubleMean.committing()); + assertTrue(intSum.committing()); + assertTrue(intMean.committing()); + assertTrue(boolAnd.committing()); + + assertTrue(longSum.committed()); + assertTrue(longMean.committed()); + assertTrue(doubleSum.committed()); + assertTrue(doubleMean.committed()); + assertTrue(intSum.committed()); + assertTrue(intMean.committed()); + assertTrue(boolAnd.committed()); + + assertFalse(longSum.isDirty()); + assertFalse(longMean.isDirty()); + assertFalse(doubleSum.isDirty()); + assertFalse(doubleMean.isDirty()); + assertFalse(intSum.isDirty()); + assertFalse(intMean.isDirty()); + assertFalse(boolAnd.isDirty()); + + assertEquals(CommitState.COMMITTED, longSum.commitState.get()); + assertEquals(CommitState.COMMITTED, longMean.commitState.get()); + assertEquals(CommitState.COMMITTED, doubleSum.commitState.get()); + assertEquals(CommitState.COMMITTED, doubleMean.commitState.get()); + assertEquals(CommitState.COMMITTED, intSum.commitState.get()); + assertEquals(CommitState.COMMITTED, intMean.commitState.get()); + assertEquals(CommitState.COMMITTED, boolAnd.commitState.get()); + } } From 579ce4c21cf0a06ca6e1e20072bf8378154d2f84 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 26 Apr 2016 15:49:46 -0700 Subject: [PATCH 345/751] checkstyle.xml: blacklist repackaged code from Google API Client --- checkstyle.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/checkstyle.xml b/checkstyle.xml index f38dd74b34..4a2e15009d 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -122,6 +122,10 @@ page at http://checkstyle.sourceforge.net/config.html --> + + + + From 682c5eb48399e0f4caedf2d621942e8b15046cbe Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 26 Apr 2016 11:46:26 -0700 Subject: [PATCH 346/751] Output InProcessGroupByKeyOnly elements in the Global Window This ensures that the values are not dropped if they are exploded (for example, in the Watermark Manager). --- .../sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java index 3e133010f3..f71d2ee745 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java @@ -147,7 +147,7 @@ public InProcessTransformResult finishBundle() { KeyedWorkItems.elementsWorkItem(key, groupedEntry.getValue()); UncommittedBundle> bundle = evaluationContext.createKeyedBundle(inputBundle, key, application.getOutput()); - bundle.add(WindowedValue.valueInEmptyWindows(groupedKv)); + bundle.add(WindowedValue.valueInGlobalWindow(groupedKv)); resultBuilder.addOutput(bundle); } return resultBuilder.build(); From 8cec8e3016ba017ff212f303a5dff9a58bab4a18 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 26 Apr 2016 17:03:16 -0700 Subject: [PATCH 347/751] Fix CreateSource#getBytesPerOffset Return 1L when there are no elements, as the default value. Return 1L when the total encoded size of all the elements is 0, for example when using VoidCoder. --- .../cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java index b28db6bbd7..12a786c2bd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java @@ -171,9 +171,9 @@ public OffsetBasedSource createSourceForSubrange(long start, long end) { @Override public long getBytesPerOffset() { if (allElementsBytes.size() == 0) { - return 0L; + return 1L; } - return totalSize / allElementsBytes.size(); + return Math.max(1L, totalSize / allElementsBytes.size()); } } From cd7fd198c16f62ccd392a505c47012ee2eec4a25 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 27 Apr 2016 11:04:10 -0700 Subject: [PATCH 348/751] [BEAM-222] Backport BEAM pull/235 (#217) This is a (partial) backport of: apache/incubator-beam#132 apache/incubator-beam#235 apache/incubator-beam#248 --- .../runners/dataflow/TestCountingSource.java | 59 ++++++++++----- .../dataflow/TestCountingSourceTest.java | 72 +++++++++++++++++++ 2 files changed, 112 insertions(+), 19 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java index d0863a46f5..16752a9641 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java @@ -55,6 +55,7 @@ public class TestCountingSource private final int shardNumber; private final boolean dedup; private final boolean throwOnFirstSnapshot; + private final boolean allowSplitting; /** * We only allow an exception to be thrown from getCheckpointMark @@ -68,27 +69,36 @@ public static void setFinalizeTracker(List finalizeTracker) { } public TestCountingSource(int numMessagesPerShard) { - this(numMessagesPerShard, 0, false, false); + this(numMessagesPerShard, 0, false, false, true); } public TestCountingSource withDedup() { - return new TestCountingSource(numMessagesPerShard, shardNumber, true, throwOnFirstSnapshot); + return new TestCountingSource( + numMessagesPerShard, shardNumber, true, throwOnFirstSnapshot, true); } private TestCountingSource withShardNumber(int shardNumber) { - return new TestCountingSource(numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot); + return new TestCountingSource( + numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot, true); } public TestCountingSource withThrowOnFirstSnapshot(boolean throwOnFirstSnapshot) { - return new TestCountingSource(numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot); + return new TestCountingSource( + numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot, true); } - private TestCountingSource( - int numMessagesPerShard, int shardNumber, boolean dedup, boolean throwOnFirstSnapshot) { + public TestCountingSource withoutSplitting() { + return new TestCountingSource( + numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot, false); + } + + private TestCountingSource(int numMessagesPerShard, int shardNumber, boolean dedup, + boolean throwOnFirstSnapshot, boolean allowSplitting) { this.numMessagesPerShard = numMessagesPerShard; this.shardNumber = shardNumber; this.dedup = dedup; this.throwOnFirstSnapshot = throwOnFirstSnapshot; + this.allowSplitting = allowSplitting; } public int getShardNumber() { @@ -99,7 +109,8 @@ public int getShardNumber() { public List generateInitialSplits( int desiredNumSplits, PipelineOptions options) { List splits = new ArrayList<>(); - for (int i = 0; i < desiredNumSplits; i++) { + int numSplits = allowSplitting ? desiredNumSplits : 1; + for (int i = 0; i < numSplits; i++) { splits.add(withShardNumber(i)); } return splits; @@ -143,7 +154,11 @@ public boolean requiresDeduping() { return dedup; } - private class CountingSourceReader extends UnboundedReader> { + /** + * Public only so that the checkpoint can be conveyed from {@link #getCheckpointMark()} to + * {@link TestCountingSource#createReader(PipelineOptions, CounterMark)} without cast. + */ + public class CountingSourceReader extends UnboundedReader> { private int current; public CountingSourceReader(int startingPoint) { @@ -152,21 +167,20 @@ public CountingSourceReader(int startingPoint) { @Override public boolean start() { - return true; + return advance(); } @Override public boolean advance() { - if (current < numMessagesPerShard - 1) { - // If testing dedup, occasionally insert a duplicate value; - if (dedup && ThreadLocalRandom.current().nextInt(5) == 0) { - return true; - } - current++; - return true; - } else { + if (current >= numMessagesPerShard - 1) { return false; } + // If testing dedup, occasionally insert a duplicate value; + if (current >= 0 && dedup && ThreadLocalRandom.current().nextInt(5) == 0) { + return true; + } + current++; + return true; } @Override @@ -204,12 +218,14 @@ public Instant getWatermark() { } @Override - public CheckpointMark getCheckpointMark() { + public CounterMark getCheckpointMark() { if (throwOnFirstSnapshot && !thrown) { thrown = true; LOG.error("Throwing exception while checkpointing counter"); throw new RuntimeException("failed during checkpoint"); } + // The checkpoint can assume all records read, including the current, have + // been commited. return new CounterMark(current); } @@ -222,7 +238,12 @@ public long getSplitBacklogBytes() { @Override public CountingSourceReader createReader( PipelineOptions options, @Nullable CounterMark checkpointMark) { - return new CountingSourceReader(checkpointMark != null ? checkpointMark.current : 0); + if (checkpointMark == null) { + LOG.debug("creating reader"); + } else { + LOG.debug("restoring reader from checkpoint with current = {}", checkpointMark.current); + } + return new CountingSourceReader(checkpointMark != null ? checkpointMark.current : -1); } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java new file mode 100644 index 0000000000..b03398f479 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; + +/** + * Test the TestCountingSource. + */ +@RunWith(JUnit4.class) +public class TestCountingSourceTest { + @Test + public void testRespectsCheckpointContract() throws IOException { + TestCountingSource source = new TestCountingSource(3); + PipelineOptions options = PipelineOptionsFactory.create(); + TestCountingSource.CountingSourceReader reader = + source.createReader(options, null /* no checkpoint */); + assertTrue(reader.start()); + assertEquals(0L, (long) reader.getCurrent().getValue()); + assertTrue(reader.advance()); + assertEquals(1L, (long) reader.getCurrent().getValue()); + TestCountingSource.CounterMark checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + reader = source.createReader(options, checkpoint); + assertTrue(reader.start()); + assertEquals(2L, (long) reader.getCurrent().getValue()); + assertFalse(reader.advance()); + } + + @Test + public void testCanResumeWithExpandedCount() throws IOException { + TestCountingSource source = new TestCountingSource(1); + PipelineOptions options = PipelineOptionsFactory.create(); + TestCountingSource.CountingSourceReader reader = + source.createReader(options, null /* no checkpoint */); + assertTrue(reader.start()); + assertEquals(0L, (long) reader.getCurrent().getValue()); + assertFalse(reader.advance()); + TestCountingSource.CounterMark checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + source = new TestCountingSource(2); + reader = source.createReader(options, checkpoint); + assertTrue(reader.start()); + assertEquals(1L, (long) reader.getCurrent().getValue()); + assertFalse(reader.advance()); + } +} From 8423338ea3b6682de1a6e25456a4ca92c72609bd Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 18 Apr 2016 12:59:24 -0700 Subject: [PATCH 349/751] Remove isKeyed property of InProcess Bundles The property of keyedness belongs to a PCollection. A BundleFactory propogates the key as far as possible, but does not track if a bundle is keyed. --- .../inprocess/InProcessBundleFactory.java | 38 +++++-------------- .../inprocess/InProcessPipelineRunner.java | 6 --- .../inprocess/InProcessBundleFactoryTest.java | 11 ------ 3 files changed, 9 insertions(+), 46 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java index 30bf3d6763..99b5c1dfea 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java @@ -40,20 +40,18 @@ private InProcessBundleFactory() {} @Override public UncommittedBundle createRootBundle(PCollection output) { - return InProcessBundle.unkeyed(output); + return InProcessBundle.create(output, null); } @Override public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { - return input.isKeyed() - ? InProcessBundle.keyed(output, input.getKey()) - : InProcessBundle.unkeyed(output); + return InProcessBundle.create(output, input.getKey()); } @Override public UncommittedBundle createKeyedBundle( - CommittedBundle input, Object key, PCollection output) { - return InProcessBundle.keyed(output, key); + CommittedBundle input, @Nullable Object key, PCollection output) { + return InProcessBundle.create(output, key); } /** @@ -61,32 +59,19 @@ public UncommittedBundle createKeyedBundle( */ private static final class InProcessBundle implements UncommittedBundle { private final PCollection pcollection; - private final boolean keyed; - private final Object key; + @Nullable private final Object key; private boolean committed = false; private ImmutableList.Builder> elements; /** - * Create a new {@link InProcessBundle} for the specified {@link PCollection} without a key. + * Create a new {@link InProcessBundle} for the specified {@link PCollection}. */ - public static InProcessBundle unkeyed(PCollection pcollection) { - return new InProcessBundle(pcollection, false, null); + public static InProcessBundle create(PCollection pcollection, @Nullable Object key) { + return new InProcessBundle(pcollection, key); } - /** - * Create a new {@link InProcessBundle} for the specified {@link PCollection} with the specified - * key. - * - *

          See {@link CommittedBundle#getKey()} and {@link CommittedBundle#isKeyed()} for more - * information. - */ - public static InProcessBundle keyed(PCollection pcollection, Object key) { - return new InProcessBundle(pcollection, true, key); - } - - private InProcessBundle(PCollection pcollection, boolean keyed, Object key) { + private InProcessBundle(PCollection pcollection, Object key) { this.pcollection = pcollection; - this.keyed = keyed; this.key = key; this.elements = ImmutableList.builder(); } @@ -119,11 +104,6 @@ public Object getKey() { return key; } - @Override - public boolean isKeyed() { - return keyed; - } - @Override public Iterable> getElements() { return committedElements; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 688f931f0d..eff1d40f96 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -127,12 +127,6 @@ public static interface CommittedBundle { */ PCollection getPCollection(); - /** - * Returns whether this bundle is keyed. A bundle that is part of a {@link PCollection} that - * occurs after a {@link GroupByKey} is keyed by the result of the last {@link GroupByKey}. - */ - boolean isKeyed(); - /** * Returns the (possibly null) key that was output in the most recent {@link GroupByKey} in the * execution of this bundle. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java index 939976bfad..9b4e630042 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java @@ -17,7 +17,6 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; @@ -72,7 +71,6 @@ public void createRootBundleShouldCreateWithNullKey() { CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - assertThat(bundle.isKeyed(), is(false)); assertThat(bundle.getKey(), nullValue()); } @@ -83,7 +81,6 @@ private void createKeyedBundle(Object key) { bundleFactory.createKeyedBundle(null, key, pcollection); CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - assertThat(bundle.isKeyed(), is(true)); assertThat(bundle.getKey(), equalTo(key)); } @@ -162,7 +159,6 @@ public void createBundleUnkeyedResultUnkeyed() { bundleFactory .createBundle(bundleFactory.createRootBundle(created).commit(Instant.now()), downstream) .commit(Instant.now()); - assertThat(newBundle.isKeyed(), is(false)); } @Test @@ -173,15 +169,9 @@ public void createBundleKeyedResultPropagatesKey() { bundleFactory.createKeyedBundle(null, "foo", created).commit(Instant.now()), downstream) .commit(Instant.now()); - assertThat(newBundle.isKeyed(), is(true)); assertThat(newBundle.getKey(), Matchers.equalTo("foo")); } - @Test - public void createRootBundleUnkeyed() { - assertThat(bundleFactory.createRootBundle(created).commit(Instant.now()).isKeyed(), is(false)); - } - @Test public void createKeyedBundleKeyed() { CommittedBundle> keyedBundle = @@ -189,7 +179,6 @@ public void createKeyedBundleKeyed() { .createKeyedBundle( bundleFactory.createRootBundle(created).commit(Instant.now()), "foo", downstream) .commit(Instant.now()); - assertThat(keyedBundle.isKeyed(), is(true)); assertThat(keyedBundle.getKey(), Matchers.equalTo("foo")); } } From 15629c8bed48012b63f72d1acb9c4bb0f2367af6 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 18 Apr 2016 16:16:48 -0700 Subject: [PATCH 350/751] Allow InProcess Evaluators to check Side Input completion This checks to ensure that the PCollectionView in the SideInputWindow for the provided window either has elements available or is empty. Schedule a future to ensure that the SideInputWindows are appropriately filled with an empty iterable after retreiving the element. --- .../inprocess/InProcessEvaluationContext.java | 23 +- .../InProcessSideInputContainer.java | 90 ++++-- .../InProcessSideInputContainerTest.java | 267 +++++++++++++----- 3 files changed, 277 insertions(+), 103 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index b2aa45ef62..2b21cc8584 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -317,17 +317,30 @@ public String getStepName(AppliedPTransform application) { } /** - * Returns a {@link SideInputReader} capable of reading the provided + * Returns a {@link ReadyCheckingSideInputReader} capable of reading the provided * {@link PCollectionView PCollectionViews}. + * * @param sideInputs the {@link PCollectionView PCollectionViews} the result should be able to - * read - * @return a {@link SideInputReader} that can read all of the provided - * {@link PCollectionView PCollectionViews} + * read + * @return a {@link SideInputReader} that can read all of the provided {@link PCollectionView + * PCollectionViews} */ - public SideInputReader createSideInputReader(final List> sideInputs) { + public ReadyCheckingSideInputReader createSideInputReader( + final List> sideInputs) { return sideInputContainer.createReaderForViews(sideInputs); } + /** + * A {@link SideInputReader} that allows callers to check to see if a {@link PCollectionView} has + * had its contents set in a window. + */ + interface ReadyCheckingSideInputReader extends SideInputReader { + /** + * Returns true if the {@link PCollectionView} is ready in the provided {@link BoundedWindow}. + */ + boolean isReady(PCollectionView view, BoundedWindow window); + } + /** * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent * of all other {@link CounterSet CounterSets} created by this call. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java index 37c9fcfa65..79480c11ca 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -17,6 +17,7 @@ import static com.google.common.base.Preconditions.checkArgument; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessEvaluationContext.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; @@ -41,6 +42,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; import javax.annotation.Nullable; @@ -85,11 +87,12 @@ private InProcessSideInputContainer(InProcessEvaluationContext context, } /** - * Return a view of this {@link InProcessSideInputContainer} that contains only the views in - * the provided argument. The returned {@link InProcessSideInputContainer} is unmodifiable without + * Return a view of this {@link InProcessSideInputContainer} that contains only the views in the + * provided argument. The returned {@link InProcessSideInputContainer} is unmodifiable without * casting, but will change as this {@link InProcessSideInputContainer} is modified. */ - public SideInputReader createReaderForViews(Collection> newContainedViews) { + public ReadyCheckingSideInputReader createReaderForViews( + Collection> newContainedViews) { if (!containedViews.containsAll(newContainedViews)) { Set> currentlyContained = ImmutableSet.copyOf(containedViews); Set> newRequested = ImmutableSet.copyOf(newContainedViews); @@ -170,41 +173,31 @@ private void updatePCollectionViewWindowValues( } } - private final class SideInputContainerSideInputReader implements SideInputReader { + private final class SideInputContainerSideInputReader implements ReadyCheckingSideInputReader { private final Collection> readerViews; private SideInputContainerSideInputReader(Collection> readerViews) { this.readerViews = ImmutableSet.copyOf(readerViews); } + @Override + public boolean isReady(final PCollectionView view, final BoundedWindow window) { + checkArgument( + readerViews.contains(view), + "Tried to check if view %s was ready in a SideInputReader that does not contain it. " + + "Contained views; %s", + view, + readerViews); + return getViewFuture(view, window).isDone(); + } + @Override @Nullable public T get(final PCollectionView view, final BoundedWindow window) { checkArgument( readerViews.contains(view), "calling get(PCollectionView) with unknown view: " + view); - PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, window); try { - final SettableFuture>> future = - viewByWindows.get(windowedView); - - WindowingStrategy windowingStrategy = view.getWindowingStrategyInternal(); - evaluationContext.scheduleAfterOutputWouldBeProduced( - view, window, windowingStrategy, new Runnable() { - @Override - public void run() { - // The requested window has closed without producing elements, so reflect that in - // the PCollectionView. If set has already been called, will do nothing. - future.set(Collections.>emptyList()); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper("InProcessSideInputContainerEmptyCallback") - .add("view", view) - .add("window", window) - .toString(); - } - }); + final Future>> future = getViewFuture(view, window); // Safe covariant cast @SuppressWarnings("unchecked") Iterable> values = (Iterable>) future.get(); @@ -217,6 +210,23 @@ public String toString() { } } + /** + * Gets the future containing the contents of the provided {@link PCollectionView} in the + * provided {@link BoundedWindow}, setting up a callback to populate the future with empty + * contents if necessary. + */ + private Future>> getViewFuture( + final PCollectionView view, final BoundedWindow window) { + PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, window); + final SettableFuture>> future = + viewByWindows.getUnchecked(windowedView); + + WindowingStrategy windowingStrategy = view.getWindowingStrategyInternal(); + evaluationContext.scheduleAfterOutputWouldBeProduced( + view, window, windowingStrategy, new WriteEmptyViewContents(view, window, future)); + return future; + } + @Override public boolean contains(PCollectionView view) { return readerViews.contains(view); @@ -227,4 +237,32 @@ public boolean isEmpty() { return readerViews.isEmpty(); } } + + private static class WriteEmptyViewContents implements Runnable { + private final PCollectionView view; + private final BoundedWindow window; + private final SettableFuture>> future; + + private WriteEmptyViewContents(PCollectionView view, BoundedWindow window, + SettableFuture>> future) { + this.future = future; + this.view = view; + this.window = window; + } + + @Override + public void run() { + // The requested window has closed without producing elements, so reflect that in + // the PCollectionView. If set has already been called, will do nothing. + future.set(Collections.>emptyList()); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("view", view) + .add("window", window) + .toString(); + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java index 16b4eb7d07..c4d855bf17 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessEvaluationContext.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.Mean; @@ -65,6 +66,32 @@ */ @RunWith(JUnit4.class) public class InProcessSideInputContainerTest { + private static final BoundedWindow FIRST_WINDOW = + new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(789541L); + } + + @Override + public String toString() { + return "firstWindow"; + } + }; + + private static final BoundedWindow SECOND_WINDOW = + new BoundedWindow() { + @Override + public Instant maxTimestamp() { + return new Instant(14564786L); + } + + @Override + public String toString() { + return "secondWindow"; + } + }; + @Rule public ExpectedException thrown = ExpectedException.none(); @@ -81,30 +108,6 @@ public class InProcessSideInputContainerTest { // Not present in container. private PCollectionView> iterableView; - private BoundedWindow firstWindow = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(789541L); - } - - @Override - public String toString() { - return "firstWindow"; - } - }; - - private BoundedWindow secondWindow = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(14564786L); - } - - @Override - public String toString() { - return "secondWindow"; - } - }; - @Before public void setup() { MockitoAnnotations.initMocks(this); @@ -117,10 +120,7 @@ public void setup() { create.apply("forKeyTypes", WithKeys.of("foo")) .apply("asMapView", View.asMap()); - singletonView = - create.apply("forCombinedTypes", Mean.globally()) - .apply("asDoubleView", View.asSingleton()); - + singletonView = create.apply("forCombinedTypes", Mean.globally().asSingletonView()); iterableView = create.apply("asIterableView", View.asIterable()); container = InProcessSideInputContainer.create( @@ -129,15 +129,18 @@ public void setup() { @Test public void getAfterWriteReturnsPaneInWindow() throws Exception { - WindowedValue> one = WindowedValue.of( - KV.of("one", 1), new Instant(1L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); - WindowedValue> two = WindowedValue.of( - KV.of("two", 2), new Instant(20L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue> one = + WindowedValue.of( + KV.of("one", 1), new Instant(1L), FIRST_WINDOW, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue> two = + WindowedValue.of( + KV.of("two", 2), new Instant(20L), FIRST_WINDOW, PaneInfo.ON_TIME_AND_ONLY_FIRING); container.write(mapView, ImmutableList.>of(one, two)); Map viewContents = - container.createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, firstWindow); + container + .createReaderForViews(ImmutableList.>of(mapView)) + .get(mapView, FIRST_WINDOW); assertThat(viewContents, hasEntry("one", 1)); assertThat(viewContents, hasEntry("two", 2)); assertThat(viewContents.size(), is(2)); @@ -145,26 +148,40 @@ public void getAfterWriteReturnsPaneInWindow() throws Exception { @Test public void getReturnsLatestPaneInWindow() throws Exception { - WindowedValue> one = WindowedValue.of(KV.of("one", 1), new Instant(1L), - secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); - WindowedValue> two = WindowedValue.of(KV.of("two", 2), new Instant(20L), - secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); + WindowedValue> one = + WindowedValue.of( + KV.of("one", 1), + new Instant(1L), + SECOND_WINDOW, + PaneInfo.createPane(true, false, Timing.EARLY)); + WindowedValue> two = + WindowedValue.of( + KV.of("two", 2), + new Instant(20L), + SECOND_WINDOW, + PaneInfo.createPane(true, false, Timing.EARLY)); container.write(mapView, ImmutableList.>of(one, two)); Map viewContents = - container.createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, secondWindow); + container + .createReaderForViews(ImmutableList.>of(mapView)) + .get(mapView, SECOND_WINDOW); assertThat(viewContents, hasEntry("one", 1)); assertThat(viewContents, hasEntry("two", 2)); assertThat(viewContents.size(), is(2)); - WindowedValue> three = WindowedValue.of(KV.of("three", 3), - new Instant(300L), secondWindow, PaneInfo.createPane(false, false, Timing.EARLY, 1, -1)); + WindowedValue> three = + WindowedValue.of( + KV.of("three", 3), + new Instant(300L), + SECOND_WINDOW, + PaneInfo.createPane(false, false, Timing.EARLY, 1, -1)); container.write(mapView, ImmutableList.>of(three)); Map overwrittenViewContents = - container.createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, secondWindow); + container + .createReaderForViews(ImmutableList.>of(mapView)) + .get(mapView, SECOND_WINDOW); assertThat(overwrittenViewContents, hasEntry("three", 3)); assertThat(overwrittenViewContents.size(), is(1)); } @@ -256,66 +273,98 @@ public void getOnReaderForViewNotInReaderFails() { @Test public void writeForMultipleElementsInDifferentWindowsSucceeds() throws Exception { - WindowedValue firstWindowedValue = WindowedValue.of(2.875, - firstWindow.maxTimestamp().minus(200L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue firstWindowedValue = + WindowedValue.of( + 2.875, + FIRST_WINDOW.maxTimestamp().minus(200L), + FIRST_WINDOW, + PaneInfo.ON_TIME_AND_ONLY_FIRING); WindowedValue secondWindowedValue = - WindowedValue.of(4.125, secondWindow.maxTimestamp().minus(2_000_000L), secondWindow, + WindowedValue.of( + 4.125, + SECOND_WINDOW.maxTimestamp().minus(2_000_000L), + SECOND_WINDOW, PaneInfo.ON_TIME_AND_ONLY_FIRING); container.write(singletonView, ImmutableList.of(firstWindowedValue, secondWindowedValue)); assertThat( - container.createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, firstWindow), + container + .createReaderForViews(ImmutableList.>of(singletonView)) + .get(singletonView, FIRST_WINDOW), equalTo(2.875)); assertThat( - container.createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, secondWindow), + container + .createReaderForViews(ImmutableList.>of(singletonView)) + .get(singletonView, SECOND_WINDOW), equalTo(4.125)); } @Test public void writeForMultipleIdenticalElementsInSameWindowSucceeds() throws Exception { - WindowedValue firstValue = WindowedValue.of( - 44, firstWindow.maxTimestamp().minus(200L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); - WindowedValue secondValue = WindowedValue.of( - 44, firstWindow.maxTimestamp().minus(200L), firstWindow, PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue firstValue = + WindowedValue.of( + 44, + FIRST_WINDOW.maxTimestamp().minus(200L), + FIRST_WINDOW, + PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue secondValue = + WindowedValue.of( + 44, + FIRST_WINDOW.maxTimestamp().minus(200L), + FIRST_WINDOW, + PaneInfo.ON_TIME_AND_ONLY_FIRING); container.write(iterableView, ImmutableList.of(firstValue, secondValue)); assertThat( - container.createReaderForViews(ImmutableList.>of(iterableView)) - .get(iterableView, firstWindow), + container + .createReaderForViews(ImmutableList.>of(iterableView)) + .get(iterableView, FIRST_WINDOW), contains(44, 44)); } @Test public void writeForElementInMultipleWindowsSucceeds() throws Exception { WindowedValue multiWindowedValue = - WindowedValue.of(2.875, firstWindow.maxTimestamp().minus(200L), - ImmutableList.of(firstWindow, secondWindow), PaneInfo.ON_TIME_AND_ONLY_FIRING); + WindowedValue.of( + 2.875, + FIRST_WINDOW.maxTimestamp().minus(200L), + ImmutableList.of(FIRST_WINDOW, SECOND_WINDOW), + PaneInfo.ON_TIME_AND_ONLY_FIRING); container.write(singletonView, ImmutableList.of(multiWindowedValue)); assertThat( - container.createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, firstWindow), + container + .createReaderForViews(ImmutableList.>of(singletonView)) + .get(singletonView, FIRST_WINDOW), equalTo(2.875)); assertThat( - container.createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, secondWindow), + container + .createReaderForViews(ImmutableList.>of(singletonView)) + .get(singletonView, SECOND_WINDOW), equalTo(2.875)); } @Test public void finishDoesNotOverwriteWrittenElements() throws Exception { - WindowedValue> one = WindowedValue.of(KV.of("one", 1), new Instant(1L), - secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); - WindowedValue> two = WindowedValue.of(KV.of("two", 2), new Instant(20L), - secondWindow, PaneInfo.createPane(true, false, Timing.EARLY)); + WindowedValue> one = + WindowedValue.of( + KV.of("one", 1), + new Instant(1L), + SECOND_WINDOW, + PaneInfo.createPane(true, false, Timing.EARLY)); + WindowedValue> two = + WindowedValue.of( + KV.of("two", 2), + new Instant(20L), + SECOND_WINDOW, + PaneInfo.createPane(true, false, Timing.EARLY)); container.write(mapView, ImmutableList.>of(one, two)); - immediatelyInvokeCallback(mapView, secondWindow); + immediatelyInvokeCallback(mapView, SECOND_WINDOW); Map viewContents = - container.createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, secondWindow); + container + .createReaderForViews(ImmutableList.>of(mapView)) + .get(mapView, SECOND_WINDOW); assertThat(viewContents, hasEntry("one", 1)); assertThat(viewContents, hasEntry("two", 2)); @@ -324,16 +373,90 @@ public void finishDoesNotOverwriteWrittenElements() throws Exception { @Test public void finishOnPendingViewsSetsEmptyElements() throws Exception { - immediatelyInvokeCallback(mapView, secondWindow); + immediatelyInvokeCallback(mapView, SECOND_WINDOW); Future> mapFuture = getFutureOfView( container.createReaderForViews(ImmutableList.>of(mapView)), mapView, - secondWindow); + SECOND_WINDOW); assertThat(mapFuture.get().isEmpty(), is(true)); } + /** + * Demonstrates that calling isReady on an empty container throws an + * {@link IllegalArgumentException}. + */ + @Test + public void isReadyInEmptyReaderThrows() { + ReadyCheckingSideInputReader reader = + container.createReaderForViews(ImmutableList.>of()); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("does not contain"); + thrown.expectMessage(ImmutableList.of().toString()); + reader.isReady(mapView, GlobalWindow.INSTANCE); + } + + /** + * Demonstrates that calling isReady returns false until elements are written to the + * {@link PCollectionView}, {@link BoundedWindow} pair, at which point it returns true. + */ + @Test + public void isReadyForSomeNotReadyViewsFalseUntilElements() { + container.write( + mapView, + ImmutableList.of( + WindowedValue.of( + KV.of("one", 1), + SECOND_WINDOW.maxTimestamp().minus(100L), + SECOND_WINDOW, + PaneInfo.ON_TIME_AND_ONLY_FIRING))); + + ReadyCheckingSideInputReader reader = + container.createReaderForViews(ImmutableList.of(mapView, singletonView)); + assertThat(reader.isReady(mapView, FIRST_WINDOW), is(false)); + assertThat(reader.isReady(mapView, SECOND_WINDOW), is(true)); + + assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(false)); + + container.write( + mapView, + ImmutableList.of( + WindowedValue.of( + KV.of("too", 2), + FIRST_WINDOW.maxTimestamp().minus(100L), + FIRST_WINDOW, + PaneInfo.ON_TIME_AND_ONLY_FIRING))); + assertThat(reader.isReady(mapView, FIRST_WINDOW), is(true)); + + container.write( + singletonView, + ImmutableList.of( + WindowedValue.of( + 1.25, + SECOND_WINDOW.maxTimestamp().minus(100L), + SECOND_WINDOW, + PaneInfo.ON_TIME_AND_ONLY_FIRING))); + assertThat(reader.isReady(mapView, SECOND_WINDOW), is(true)); + assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(true)); + + assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(false)); + assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); + } + + @Test + public void isReadyForEmptyWindowTrue() { + immediatelyInvokeCallback(mapView, GlobalWindow.INSTANCE); + + ReadyCheckingSideInputReader reader = + container.createReaderForViews(ImmutableList.of(mapView, singletonView)); + assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(true)); + assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); + + immediatelyInvokeCallback(singletonView, GlobalWindow.INSTANCE); + assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(true)); + } + /** * When a callAfterWindowCloses with the specified view's producing transform, window, and * windowing strategy is invoked, immediately execute the callback. From 374db6302ba011cdf1ffaed87fdaddc38cbaa167 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Thu, 28 Apr 2016 14:18:29 -0700 Subject: [PATCH 351/751] Update DataflowPipelineRunner.java to use worker harness container image corresponding to 1.5.1 release. --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 369794a0ab..3a5ea871c3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -215,9 +215,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.5.0"; + = "dataflow.gcr.io/v1beta3/java-batch:1.5.1"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.5.0"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.5.1"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From ba8b4ee9f1d0e36c56962f2ca96988bf9d77a322 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Mon, 2 May 2016 10:47:41 -0700 Subject: [PATCH 352/751] DataflowJavaSDK: remove all uses of Throwables.propagate (#232) It is slated to be deprecated: https://github.com/google/guava/commit/49e7d716f0f72d00c490864c3d11b815cfe93ec4 --- .../dataflow/examples/common/DataflowExampleUtils.java | 3 +-- .../java/com/google/cloud/dataflow/sdk/io/PubsubIO.java | 3 +-- .../cloud/dataflow/sdk/options/PipelineOptionsFactory.java | 7 +++---- .../cloud/dataflow/sdk/runners/DataflowPipelineJob.java | 3 +-- .../dataflow/sdk/runners/inprocess/InProcessCreate.java | 3 +-- .../sdk/runners/inprocess/InProcessPipelineRunner.java | 3 +-- .../sdk/runners/inprocess/InProcessSideInputContainer.java | 3 +-- .../dataflow/sdk/runners/inprocess/TransformExecutor.java | 6 ++++-- .../dataflow/sdk/testing/TestDataflowPipelineRunner.java | 4 ++-- .../cloud/dataflow/sdk/transforms/DoFnReflector.java | 3 +-- .../sdk/transforms/IntraBundleParallelization.java | 4 ++-- .../cloud/dataflow/sdk/util/BigQueryTableInserter.java | 3 +-- .../google/cloud/dataflow/sdk/util/MutationDetectors.java | 3 +-- .../dataflow/sdk/testing/RestoreSystemProperties.java | 4 +--- .../com/google/cloud/dataflow/sdk/util/GcsUtilTest.java | 3 +-- .../com/google/cloud/dataflow/sdk/util/ReduceFnTester.java | 3 +-- .../com/google/cloud/dataflow/sdk/util/TriggerTester.java | 3 +-- 17 files changed, 24 insertions(+), 37 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java index 416ee62fa6..c632132c07 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java @@ -47,7 +47,6 @@ import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.Strings; -import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @@ -110,7 +109,7 @@ public void setup() throws IOException { } catch (InterruptedException e) { // Ignore InterruptedException } - Throwables.propagate(lastException); + throw new RuntimeException(lastException); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java index e5d08d6e8a..b286125600 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java @@ -50,7 +50,6 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import org.joda.time.Duration; @@ -814,7 +813,7 @@ public void processElement(ProcessContext c) throws IOException { } } if (finallyBlockException != null) { - Throwables.propagate(finallyBlockException); + throw new RuntimeException(finallyBlockException); } for (PubsubMessage message : messages) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java index 872ac47099..4a5d270956 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java @@ -31,7 +31,6 @@ import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Strings; -import com.google.common.base.Throwables; import com.google.common.collect.Collections2; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableListMultimap; @@ -624,7 +623,7 @@ static synchronized Registration validateWellForm COMBINED_CACHE.put(combinedPipelineOptionsInterfaces, new Registration(allProxyClass, propertyDescriptors)); } catch (IntrospectionException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -639,7 +638,7 @@ static synchronized Registration validateWellForm INTERFACE_CACHE.put(iface, new Registration(proxyClass, propertyDescriptors)); } catch (IntrospectionException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @@ -1038,7 +1037,7 @@ private static List validateClass(Class apply(PInput input) { try { source = InMemorySource.fromIterable(original.getElements(), elementCoder); } catch (IOException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } PCollection result = input.getPipeline().apply(Read.from(source)); result.setCoder(elementCoder); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index eff1d40f96..3e333399a4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -47,7 +47,6 @@ import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -239,7 +238,7 @@ public InProcessPipelineResult run(Pipeline pipeline) { } catch (UserCodeException userException) { throw new PipelineExecutionException(userException.getCause()); } catch (Throwable t) { - Throwables.propagate(t); + throw new RuntimeException(t); } } return result; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java index 79480c11ca..697348039a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -26,7 +26,6 @@ import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.common.base.MoreObjects; -import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -169,7 +168,7 @@ private void updatePCollectionViewWindowValues( future.set(Collections.>emptyList()); } } catch (ExecutionException e) { - Throwables.propagate(e.getCause()); + throw new RuntimeException(e.getCause()); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java index b9bdce11f7..3313134120 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -20,7 +20,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.common.base.Throwables; import java.util.ArrayList; import java.util.Collection; @@ -116,7 +115,10 @@ public InProcessTransformResult call() { return result; } catch (Throwable t) { onComplete.handleThrowable(inputBundle, t); - throw Throwables.propagate(t); + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + throw new RuntimeException(t); } finally { transformEvaluationState.complete(this); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java index 9fff070f88..9424f0422f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java @@ -125,7 +125,7 @@ public void process(List messages) { try { job.cancel(); } catch (Exception e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } } @@ -149,7 +149,7 @@ public void process(List messages) { } } catch (Exception e) { Throwables.propagateIfPossible(e); - throw Throwables.propagate(e); + throw new RuntimeException(e); } return job; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java index 678eb1d1be..559603aecf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java @@ -32,7 +32,6 @@ import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; -import com.google.common.base.Throwables; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.reflect.TypeParameter; @@ -477,7 +476,7 @@ private void invoke(Method m, throw UserCodeException.wrap(e.getCause()); } catch (IllegalAccessException | IllegalArgumentException e) { // Exception in our code. - throw Throwables.propagate(e); + throw new RuntimeException(e); } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java index 335cc6e412..1ac0975247 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java @@ -217,7 +217,7 @@ public void processElement(final ProcessContext c) throws Exception { } if (failure.get() != null) { - throw Throwables.propagate(failure.get()); + throw new RuntimeException(failure.get()); } executor.submit(new Runnable() { @@ -242,7 +242,7 @@ public void finishBundle(Context c) throws Exception { // processElement calls have finished. workTickets.acquire(maxParallelism); if (failure.get() != null) { - throw Throwables.propagate(failure.get()); + throw new RuntimeException(failure.get()); } doFn.finishBundle(c); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java index b1df15d8c1..37096dbc92 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java @@ -35,7 +35,6 @@ import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.Logger; @@ -272,7 +271,7 @@ public List call() throws IOException { } catch (InterruptedException e) { throw new IOException("Interrupted while inserting " + rowsToPublish); } catch (ExecutionException e) { - Throwables.propagate(e.getCause()); + throw new RuntimeException(e.getCause()); } if (!allErrors.isEmpty() && !backoff.atMaxAttempts()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java index 412e3eb725..7558a0e19a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java @@ -18,7 +18,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.common.base.Throwables; import java.util.Arrays; import java.util.Objects; @@ -113,7 +112,7 @@ public void verifyUnmodified() { try { verifyUnmodifiedThrowingCheckedExceptions(); } catch (CoderException exn) { - Throwables.propagate(exn); + throw new RuntimeException(exn); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java index 03bc6a530c..a89be3edd7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java @@ -16,8 +16,6 @@ package com.google.cloud.dataflow.sdk.testing; -import com.google.common.base.Throwables; - import org.junit.rules.ExternalResource; import org.junit.rules.TestRule; @@ -45,7 +43,7 @@ protected void after() { System.getProperties().clear(); System.getProperties().load(bais); } catch (IOException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java index e7cd7d7c22..a1a97684d5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java @@ -52,7 +52,6 @@ import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.hadoop.gcsio.GoogleCloudStorageReadChannel; import com.google.cloud.hadoop.util.ClientRequestHelper; -import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import org.junit.Rule; @@ -151,7 +150,7 @@ public void run() { countDownLatches[currentLatch - 1].countDown(); } } catch (InterruptedException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } }); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index da31d81dd7..6e433d1bba 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -56,7 +56,6 @@ import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -406,7 +405,7 @@ public WindowedValue apply(TimestampedValue input) { windowFn, value, timestamp, Arrays.asList(GlobalWindow.INSTANCE))); return WindowedValue.of(value, timestamp, windows, PaneInfo.NO_FIRING); } catch (Exception e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } })); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index 555de74a63..ba1bf5e5e0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -42,7 +42,6 @@ import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -254,7 +253,7 @@ public final void injectElements(Collection> values) th windowedValues.add(WindowedValue.of(value, timestamp, assignedWindows, PaneInfo.NO_FIRING)); } catch (Exception e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } From e2d90308018e3191c2fb63005e0a3f0b439cfbd0 Mon Sep 17 00:00:00 2001 From: ddonnelly Date: Wed, 27 Apr 2016 13:06:23 -0700 Subject: [PATCH 353/751] Fixes broken link in PTransform.java JavaDoc ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=120945485 --- .../com/google/cloud/dataflow/sdk/transforms/PTransform.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java index d4496b8c74..21355e17ba 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java @@ -163,7 +163,7 @@ * operations that do not save or restore any state. * * @see Applying Transformations * * @param the type of the input to this PTransform From 6bc3c7d18beb0a871548c98bbdb48132b8352e1b Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 28 Apr 2016 17:38:50 -0700 Subject: [PATCH 354/751] Fix update sequence in InMemoryWatermarkManager Because the WatermarkManager is not synchronized within the call to updatePending, the sequence in which pending queues are updated must be in such a manner as to add additional restrictions, then remove any restrictions which no longer apply. This ensures any intermediate read will see at worst a more restricted watermark than the actual watermark. --- .../inprocess/InMemoryWatermarkManager.java | 34 +++++++++++++------ 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 6f68b7e42f..918a7f4a1c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -466,9 +466,6 @@ public synchronized Instant getEarliestTimerTimestamp() { } private synchronized void updateTimers(TimerUpdate update) { - for (TimerData completedTimer : update.completedTimers) { - pendingTimers.remove(completedTimer); - } Map> timerMap = timerMap(update.key); for (TimerData addedTimer : update.setTimers) { NavigableSet timerQueue = timerMap.get(addedTimer.getDomain()); @@ -476,6 +473,10 @@ private synchronized void updateTimers(TimerUpdate update) { timerQueue.add(addedTimer); } } + + for (TimerData completedTimer : update.completedTimers) { + pendingTimers.remove(completedTimer); + } for (TimerData deletedTimer : update.deletedTimers) { NavigableSet timerQueue = timerMap.get(deletedTimer.getDomain()); if (timerQueue != null) { @@ -829,10 +830,16 @@ private void refreshWatermarks(AppliedPTransform transform) { } /** - * Removes all of the completed Timers from the collection of pending timers, adds all new timers, - * and removes all deleted timers. Removes all elements consumed by the input bundle from the - * {@link PTransform PTransforms} collection of pending elements, and adds all elements produced - * by the {@link PTransform} to the pending queue of each consumer. + * First adds all produced elements to the queue of pending elements for each consumer, then adds + * all pending timers to the collection of pending timers, then removes all completed and deleted + * timers from the collection of pending timers, then removes all completed elements from the + * pending queue of the transform. + * + *

          It is required that all newly pending elements are added to the queue of pending elements + * for each consumer prior to the completed elements being removed, as doing otherwise could cause + * a Watermark to appear in a state in which the upstream (completed) element does not hold the + * watermark but the element it produced is not yet pending. This can cause the watermark to + * erroneously advance. */ private void updatePending( CommittedBundle input, @@ -840,17 +847,22 @@ private void updatePending( TimerUpdate timerUpdate, Iterable> outputs) { TransformWatermarks completedTransform = transformToWatermarks.get(transform); - completedTransform.updateTimers(timerUpdate); - if (input != null) { - completedTransform.removePending(input); - } + // Newly pending elements must be added before completed elements are removed, as the two + // do not share a Mutex within this call and thus can be interleaved with external calls to + // refresh. for (CommittedBundle bundle : outputs) { for (AppliedPTransform consumer : consumers.get(bundle.getPCollection())) { TransformWatermarks watermarks = transformToWatermarks.get(consumer); watermarks.addPending(bundle); } } + + completedTransform.updateTimers(timerUpdate); + if (input != null) { + completedTransform.removePending(input); + } + } /** From 20169e563a68960dc8bf8610dd4bf7420d83f9ee Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 28 Apr 2016 15:27:03 -0700 Subject: [PATCH 355/751] Stop cloning coders in the InProcessRunner This is excessively slow and also not useful, as coders are required to be thread-safe --- .../sdk/runners/inprocess/EncodabilityEnforcementFactory.java | 3 +-- .../runners/inprocess/ImmutabilityCheckingBundleFactory.java | 3 +-- .../sdk/runners/inprocess/ImmutabilityEnforcementFactory.java | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java index 0e38b55085..5b13949dde 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java @@ -21,7 +21,6 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -45,7 +44,7 @@ private static class EncodabilityEnforcement extends AbstractModelEnforcement private Coder coder; public EncodabilityEnforcement(CommittedBundle input) { - coder = SerializableUtils.clone(input.getPCollection().getCoder()); + coder = input.getPCollection().getCoder(); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java index 908636a2c2..4567cf75a5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java @@ -26,7 +26,6 @@ import com.google.cloud.dataflow.sdk.util.IllegalMutationException; import com.google.cloud.dataflow.sdk.util.MutationDetector; import com.google.cloud.dataflow.sdk.util.MutationDetectors; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -84,7 +83,7 @@ private static class ImmutabilityEnforcingBundle implements UncommittedBundle public ImmutabilityEnforcingBundle(UncommittedBundle underlying) { this.underlying = underlying; mutationDetectors = HashMultimap.create(); - coder = SerializableUtils.clone(getPCollection().getCoder()); + coder = getPCollection().getCoder(); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java index 0f2607ff45..a7a37028ae 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java @@ -22,7 +22,6 @@ import com.google.cloud.dataflow.sdk.util.IllegalMutationException; import com.google.cloud.dataflow.sdk.util.MutationDetector; import com.google.cloud.dataflow.sdk.util.MutationDetectors; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -54,7 +53,7 @@ private static class ImmutabilityCheckingEnforcement extends AbstractModelEnf private ImmutabilityCheckingEnforcement( CommittedBundle input, AppliedPTransform transform) { this.transform = transform; - coder = SerializableUtils.clone(input.getPCollection().getCoder()); + coder = input.getPCollection().getCoder(); mutationElements = new IdentityHashMap<>(); } From ef175b196733d16163313ceb6e7c21c6c752126d Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Mon, 2 May 2016 15:55:56 -0700 Subject: [PATCH 356/751] DataflowJavaSDK: blacklist Throwables.propagate (#236) This is a partial backport of https://github.com/apache/incubator-beam/pull/270 --- checkstyle.xml | 7 +++++++ .../inprocess/ImmutabilityCheckingBundleFactory.java | 3 +-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 4a2e15009d..d5e8317391 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -76,6 +76,13 @@ page at http://checkstyle.sourceforge.net/config.html --> + + + + + + + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java index 908636a2c2..67535f8bed 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java @@ -17,7 +17,6 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.client.util.Throwables; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; @@ -98,7 +97,7 @@ public UncommittedBundle add(WindowedValue element) { mutationDetectors.put( element, MutationDetectors.forValueWithCoder(element.getValue(), coder)); } catch (CoderException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } underlying.add(element); return this; From 29539c9b1bff983d7356a7dcfcb9fa4d88267217 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 2 May 2016 15:57:22 -0700 Subject: [PATCH 357/751] Remove redundant close in BoundedReadEvaluatorFactory (#233) The reader is already closed by virtue of being the target of the try-with-resources block that encompasses all of #finishBundle(). --- .../sdk/runners/inprocess/BoundedReadEvaluatorFactory.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java index a69db5d559..4a736a5272 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java @@ -144,7 +144,6 @@ public InProcessTransformResult finishBundle() throws IOException { reader.getCurrent(), reader.getCurrentTimestamp())); contentsRemaining = reader.advance(); } - reader.close(); return StepTransformResult.withHold(transform, BoundedWindow.TIMESTAMP_MAX_VALUE) .addOutput(output) .build(); From 41342b1367e82c8779861a67d1dd9edb0c6426f6 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 3 May 2016 13:07:04 -0700 Subject: [PATCH 358/751] [BEAM-255] Write: add limited logging This will help, for all sinks, users and developers gain insight into where time is spent. (Enabling DEBUG level will provide more insight.) --- .../com/google/cloud/dataflow/sdk/io/Write.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java index 2bbe878b2d..ccea32ec14 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java @@ -33,6 +33,9 @@ import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.UUID; /** @@ -49,6 +52,8 @@ */ @Experimental(Experimental.Kind.SOURCE_SINK) public class Write { + private static final Logger LOG = LoggerFactory.getLogger(Write.class); + /** * Creates a Write transform that writes to the given Sink. */ @@ -140,7 +145,9 @@ private PDone createWrite( @Override public void processElement(ProcessContext c) throws Exception { WriteOperation writeOperation = c.element(); + LOG.info("Initializing write operation {}", writeOperation); writeOperation.initialize(c.getPipelineOptions()); + LOG.debug("Done initializing write operation {}", writeOperation); // The WriteOperation is also the output of this ParDo, so it can have mutable // state. c.output(writeOperation); @@ -168,8 +175,10 @@ public void processElement(ProcessContext c) throws Exception { // Lazily initialize the Writer if (writer == null) { WriteOperation writeOperation = c.sideInput(writeOperationView); + LOG.info("Opening writer for write operation {}", writeOperation); writer = writeOperation.createWriter(c.getPipelineOptions()); writer.open(UUID.randomUUID().toString()); + LOG.debug("Done opening writer {} for operation {}", writer, writeOperationView); } try { writer.write(c.element()); @@ -207,9 +216,12 @@ public void finishBundle(Context c) throws Exception { .apply("Finalize", ParDo.of(new DoFn, Integer>() { @Override public void processElement(ProcessContext c) throws Exception { - Iterable results = c.sideInput(resultsView); WriteOperation writeOperation = c.element(); + LOG.info("Finalizing write operation {}", writeOperation); + Iterable results = c.sideInput(resultsView); + LOG.debug("Side input initialized to finalize write operation {}", writeOperation); writeOperation.finalize(results, c.getPipelineOptions()); + LOG.debug("Done finalizing write operation {}", writeOperation); } }).withSideInputs(resultsView)); return PDone.in(input.getPipeline()); From 5e9632d6b462a874f4cf27b2c3b95c8097890c62 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Mon, 9 May 2016 11:05:26 -0700 Subject: [PATCH 359/751] FileBasedSink: fix a format string bug (#243) --- .../java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index 850ea01e45..4555389a38 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -705,8 +705,9 @@ private static class LocalFileOperations implements FileOperations { public void copy(List srcFilenames, List destFilenames) throws IOException { Preconditions.checkArgument( srcFilenames.size() == destFilenames.size(), - String.format("Number of source files {} must equal number of destination files {}", - srcFilenames.size(), destFilenames.size())); + "Number of source files %s must equal number of destination files %s", + srcFilenames.size(), + destFilenames.size()); int numFiles = srcFilenames.size(); for (int i = 0; i < numFiles; i++) { String src = srcFilenames.get(i); From b241dbc7ba62a20a64eef999f574d11a171249f9 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Mon, 9 May 2016 12:29:23 -0700 Subject: [PATCH 360/751] pom.xml: upgrade to version 1.22.0 of the Google API client libs (#242) --- .../main/resources/archetype-resources/pom.xml | 8 ++++---- pom.xml | 12 ++++++------ sdk/pom.xml | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index bffa376f56..060c02a207 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -100,7 +100,7 @@ com.google.api-client google-api-client - 1.21.0 + 1.22.0 @@ -115,7 +115,7 @@ com.google.apis google-api-services-bigquery - v2-rev248-1.21.0 + v2-rev295-1.22.0 @@ -129,7 +129,7 @@ com.google.http-client google-http-client - 1.21.0 + 1.22.0 @@ -143,7 +143,7 @@ com.google.apis google-api-services-pubsub - v1-rev7-1.21.0 + v1-rev10-1.22.0 diff --git a/pom.xml b/pom.xml index 2737e657ec..a39cae8471 100644 --- a/pom.xml +++ b/pom.xml @@ -68,13 +68,13 @@ 1.7.7 - v2-rev248-1.21.0 + v2-rev295-1.22.0 0.2.3 - v2-rev6-1.21.0 - v1b3-rev22-1.21.0 + v2-rev8-1.22.0 + v1b3-rev26-1.22.0 0.5.160222 v1beta2-rev1-4.0.0 - 1.21.0 + 1.22.0 19.0 1.3 2.7.0 @@ -82,10 +82,10 @@ 3.0.1 4.11 3.0.0-beta-1 - v1-rev7-1.21.0 + v1-rev10-1.22.0 1.7.14 3.1.4 - v1-rev53-1.21.0 + v1-rev71-1.22.0 4.4.1 diff --git a/sdk/pom.xml b/sdk/pom.xml index 2639bc13db..f0446a809e 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -482,6 +482,24 @@ + + + com.google.api-client + google-api-client-java6 + ${google-clients.version} + runtime + + + + + com.google.api-client + google-api-client-jackson2 + ${google-clients.version} + runtime + + com.google.apis google-api-services-bigquery From c18c58f0722d2a6d97c4a8cfb62a7fb858d01bf5 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 31 Mar 2016 15:04:26 -0700 Subject: [PATCH 361/751] Refactor IsmFormat value classes to use AutoValue (cherry picked from commit fdf325d7484b1fff76c3fca2e84e5a9ec21d449f) --- sdk/pom.xml | 6 + .../sdk/runners/worker/IsmFormat.java | 241 +++++------------- 2 files changed, 64 insertions(+), 183 deletions(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index f0446a809e..477436f0cc 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -819,6 +819,12 @@ 1.0-rc2 true + + com.google.auto.value + auto-value + 1.1 + provided + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java index 318de9b5b8..dc4a095ece 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java @@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; +import com.google.auto.value.AutoValue; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -35,8 +36,6 @@ import com.google.cloud.dataflow.sdk.util.VarInt; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; -import com.google.common.base.MoreObjects.ToStringHelper; -import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashFunction; @@ -51,7 +50,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; @@ -117,44 +115,38 @@ public class IsmFormat { * keys are used to create a shard id via hashing. See {@link IsmRecordCoder#hash(List)} for * further details. */ - public static class IsmRecord { + @AutoValue + public abstract static class IsmRecord { + abstract List keyComponents(); + @Nullable abstract V value(); + @Nullable abstract byte[] metadata(); + + IsmRecord() {} + /** Returns an IsmRecord with the specified key components and value. */ public static IsmRecord of(List keyComponents, V value) { - checkNotNull(keyComponents); checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); checkArgument(!isMetadataKey(keyComponents), "Expected key components to not contain metadata key."); - return new IsmRecord<>(keyComponents, value, null); + return new AutoValue_IsmFormat_IsmRecord(keyComponents, value, null); } public static IsmRecord meta(List keyComponents, byte[] metadata) { - checkNotNull(keyComponents); checkNotNull(metadata); checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); checkArgument(isMetadataKey(keyComponents), "Expected key components to contain metadata key."); - return new IsmRecord(keyComponents, null, metadata); - } - - private final List keyComponents; - @Nullable - private final V value; - @Nullable - private final byte[] metadata; - private IsmRecord(List keyComponents, V value, byte[] metadata) { - this.keyComponents = keyComponents; - this.value = value; - this.metadata = metadata; + return new AutoValue_IsmFormat_IsmRecord(keyComponents, null, metadata); } /** Returns the list of key components. */ public List getKeyComponents() { - return keyComponents; + return keyComponents(); } /** Returns the key component at the specified index. */ public Object getKeyComponent(int index) { - return keyComponents.get(index); + return keyComponents().get(index); } /** @@ -162,9 +154,9 @@ public Object getKeyComponent(int index) { * value record. */ public V getValue() { - checkState(!isMetadataKey(keyComponents), + checkState(!isMetadataKey(keyComponents()), "This is a metadata record and not a value record."); - return value; + return value(); } /** @@ -172,37 +164,9 @@ public V getValue() { * metadata record. */ public byte[] getMetadata() { - checkState(isMetadataKey(keyComponents), + checkState(isMetadataKey(keyComponents()), "This is a value record and not a metadata record."); - return metadata; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof IsmRecord)) { - return false; - } - IsmRecord other = (IsmRecord) obj; - return Objects.equal(keyComponents, other.keyComponents) - && Objects.equal(value, other.value) - && Arrays.equals(metadata, other.metadata); - } - - @Override - public int hashCode() { - return Objects.hashCode(keyComponents, value, Arrays.hashCode(metadata)); - } - - @Override - public String toString() { - ToStringHelper builder = MoreObjects.toStringHelper(IsmRecord.class) - .add("keyComponents", keyComponents); - if (isMetadataKey(keyComponents)) { - builder.add("metadata", metadata); - } else { - builder.add("value", value); - } - return builder.toString(); + return metadata(); } } @@ -585,14 +549,17 @@ public void verifyDeterministic() throws NonDeterministicException { * A shard descriptor containing shard id, the data block offset, and the index offset for the * given shard. */ - public static class IsmShard { - private final int id; - private final long blockOffset; - private final long indexOffset; + @AutoValue + public abstract static class IsmShard { + abstract int id(); + abstract long blockOffset(); + abstract long indexOffset(); + + IsmShard() {} /** Returns an IsmShard with the given id, block offset and no index offset. */ public static IsmShard of(int id, long blockOffset) { - IsmShard ismShard = new IsmShard(id, blockOffset, -1); + IsmShard ismShard = new AutoValue_IsmFormat_IsmShard(id, blockOffset, -1); checkState(id >= 0, "%s attempting to be written with negative shard id.", ismShard); @@ -604,7 +571,7 @@ public static IsmShard of(int id, long blockOffset) { /** Returns an IsmShard with the given id, block offset, and index offset. */ public static IsmShard of(int id, long blockOffset, long indexOffset) { - IsmShard ismShard = new IsmShard(id, blockOffset, indexOffset); + IsmShard ismShard = new AutoValue_IsmFormat_IsmShard(id, blockOffset, indexOffset); checkState(id >= 0, "%s attempting to be written with negative shard id.", ismShard); @@ -617,20 +584,14 @@ public static IsmShard of(int id, long blockOffset, long indexOffset) { return ismShard; } - private IsmShard(int id, long blockOffset, long indexOffset) { - this.id = id; - this.blockOffset = blockOffset; - this.indexOffset = indexOffset; - } - /** Return the shard id. */ public int getId() { - return id; + return id(); } /** Return the absolute position within the Ism file where the data block begins. */ public long getBlockOffset() { - return blockOffset; + return blockOffset(); } /** @@ -638,39 +599,14 @@ public long getBlockOffset() { * Throws {@link IllegalStateException} if the index offset was never specified. */ public long getIndexOffset() { - checkState(indexOffset >= 0, + checkState(indexOffset() >= 0, "Unable to fetch index offset because it was never specified."); - return indexOffset; + return indexOffset(); } /** Returns a new IsmShard like this one with the specified index offset. */ public IsmShard withIndexOffset(long indexOffset) { - return of(id, blockOffset, indexOffset); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(IsmShard.class) - .add("id", id) - .add("blockOffset", blockOffset) - .add("indexOffset", indexOffset) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof IsmShard)) { - return false; - } - IsmShard other = (IsmShard) obj; - return Objects.equal(id, other.id) - && Objects.equal(blockOffset, other.blockOffset) - && Objects.equal(indexOffset, other.indexOffset); - } - - @Override - public int hashCode() { - return Objects.hashCode(id, blockOffset, indexOffset); + return of(id(), blockOffset(), indexOffset); } } @@ -742,47 +678,15 @@ public boolean consistentWithEquals() { *

        • number of unshared key bytes (variable length integer coding)
        • * */ - static class KeyPrefix { - private final int sharedKeySize; - private final int unsharedKeySize; - - KeyPrefix(int sharedBytes, int unsharedBytes) { - this.sharedKeySize = sharedBytes; - this.unsharedKeySize = unsharedBytes; - } + @AutoValue + abstract static class KeyPrefix { + public abstract int getSharedKeySize(); + public abstract int getUnsharedKeySize(); - public int getSharedKeySize() { - return sharedKeySize; - } - - public int getUnsharedKeySize() { - return unsharedKeySize; - } + KeyPrefix() {} - @Override - public int hashCode() { - return Objects.hashCode(sharedKeySize, unsharedKeySize); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (!(other instanceof KeyPrefix)) { - return false; - } - KeyPrefix keyPrefix = (KeyPrefix) other; - return sharedKeySize == keyPrefix.sharedKeySize - && unsharedKeySize == keyPrefix.unsharedKeySize; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("sharedKeySize", sharedKeySize) - .add("unsharedKeySize", unsharedKeySize) - .toString(); + static KeyPrefix of(int sharedKeySize, int unsharedKeySize) { + return new AutoValue_IsmFormat_KeyPrefix(sharedKeySize, unsharedKeySize); } } @@ -798,14 +702,14 @@ public static KeyPrefixCoder of() { @Override public void encode(KeyPrefix value, OutputStream outStream, Coder.Context context) throws CoderException, IOException { - VarInt.encode(value.sharedKeySize, outStream); - VarInt.encode(value.unsharedKeySize, outStream); + VarInt.encode(value.getSharedKeySize(), outStream); + VarInt.encode(value.getUnsharedKeySize(), outStream); } @Override public KeyPrefix decode(InputStream inStream, Coder.Context context) throws CoderException, IOException { - return new KeyPrefix(VarInt.decodeInt(inStream), VarInt.decodeInt(inStream)); + return KeyPrefix.of(VarInt.decodeInt(inStream), VarInt.decodeInt(inStream)); } @Override @@ -822,7 +726,8 @@ public boolean isRegisterByteSizeObserverCheap(KeyPrefix value, Coder.Context co protected long getEncodedElementByteSize(KeyPrefix value, Coder.Context context) throws Exception { Preconditions.checkNotNull(value); - return VarInt.getLength(value.sharedKeySize) + VarInt.getLength(value.unsharedKeySize); + return VarInt.getLength(value.getSharedKeySize()) + + VarInt.getLength(value.getUnsharedKeySize()); } } @@ -838,59 +743,29 @@ protected long getEncodedElementByteSize(KeyPrefix value, Coder.Context context) *
        • 0x01 (version key as a single byte)
        • * */ - static class Footer { + @AutoValue + abstract static class Footer { static final int LONG_BYTES = 8; static final int FIXED_LENGTH = 3 * LONG_BYTES + 1; static final byte VERSION = 2; - private final long indexPosition; - private final long bloomFilterPosition; - private final long numberOfKeys; - - Footer(long indexPosition, long bloomFilterPosition, long numberOfKeys) { - this.indexPosition = indexPosition; - this.bloomFilterPosition = bloomFilterPosition; - this.numberOfKeys = numberOfKeys; - } - - public long getIndexPosition() { - return indexPosition; - } - - public long getBloomFilterPosition() { - return bloomFilterPosition; - } - - public long getNumberOfKeys() { - return numberOfKeys; - } + public abstract long getIndexPosition(); + public abstract long getBloomFilterPosition(); + public abstract long getNumberOfKeys(); - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (!(other instanceof Footer)) { - return false; - } - Footer footer = (Footer) other; - return indexPosition == footer.indexPosition - && bloomFilterPosition == footer.bloomFilterPosition - && numberOfKeys == footer.numberOfKeys; - } + Footer() {} - @Override - public int hashCode() { - return Objects.hashCode(indexPosition, bloomFilterPosition, numberOfKeys); + static Footer of(long indexPosition, long bloomFilterPosition, long numberOfKeys) { + return new AutoValue_IsmFormat_Footer(indexPosition, bloomFilterPosition, numberOfKeys); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("version", Footer.VERSION) - .add("indexPosition", indexPosition) - .add("bloomFilterPosition", bloomFilterPosition) - .add("numberOfKeys", numberOfKeys) + .add("indexPosition", getIndexPosition()) + .add("bloomFilterPosition", getBloomFilterPosition()) + .add("numberOfKeys", getNumberOfKeys()) .toString(); } } @@ -908,9 +783,9 @@ public static FooterCoder of() { public void encode(Footer value, OutputStream outStream, Coder.Context context) throws CoderException, IOException { DataOutputStream dataOut = new DataOutputStream(outStream); - dataOut.writeLong(value.indexPosition); - dataOut.writeLong(value.bloomFilterPosition); - dataOut.writeLong(value.numberOfKeys); + dataOut.writeLong(value.getIndexPosition()); + dataOut.writeLong(value.getBloomFilterPosition()); + dataOut.writeLong(value.getNumberOfKeys()); dataOut.write(Footer.VERSION); } @@ -918,7 +793,7 @@ public void encode(Footer value, OutputStream outStream, Coder.Context context) public Footer decode(InputStream inStream, Coder.Context context) throws CoderException, IOException { DataInputStream dataIn = new DataInputStream(inStream); - Footer footer = new Footer(dataIn.readLong(), dataIn.readLong(), dataIn.readLong()); + Footer footer = Footer.of(dataIn.readLong(), dataIn.readLong(), dataIn.readLong()); int version = dataIn.read(); if (version != Footer.VERSION) { throw new IOException("Unknown version " + version + ". " From bcf60ee2b77a17d566b5a424345d1af3f1eca833 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 20 Apr 2016 13:45:32 -0700 Subject: [PATCH 362/751] Exclude generated AutoValue source from code coverage tooling (cherry picked from commit a69dd0ad2aeda40e6b2486a276e9bdca95b0b29f) --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index a39cae8471..33b48c9c10 100644 --- a/pom.xml +++ b/pom.xml @@ -205,6 +205,11 @@ + + + **/AutoValue_*.java + + From c6ea95b8492c3093e857c736ef0596362b5cfa79 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 20 Apr 2016 16:37:24 -0700 Subject: [PATCH 363/751] Fix AutoValue coverage exclusion for coveralls (cherry picked from commit 747487ba3b65295535ad06c2877af114150d4042) --- pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 33b48c9c10..2634cd379f 100644 --- a/pom.xml +++ b/pom.xml @@ -205,11 +205,11 @@ - - - **/AutoValue_*.java - - + + + **/AutoValue_*.class + + From 0039ee694c8ed63e0b9e6357b8a761d8dea9a115 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 28 Apr 2016 12:22:47 -0700 Subject: [PATCH 364/751] Add CommittedResult Return as the output to InProcessEvaluationContext#handleResult(). This allows a richer return type to improve possible behaviors when a result is returned. --- .../runners/inprocess/CommittedResult.java | 42 +++++++++++ .../runners/inprocess/CompletionCallback.java | 2 +- .../ExecutorServiceParallelExecutor.java | 16 ++-- .../inprocess/InProcessEvaluationContext.java | 4 +- .../runners/inprocess/TransformExecutor.java | 4 +- .../inprocess/CommittedResultTest.java | 73 +++++++++++++++++++ .../InProcessEvaluationContextTest.java | 4 +- .../inprocess/TransformExecutorTest.java | 4 +- 8 files changed, 132 insertions(+), 17 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java new file mode 100644 index 0000000000..d900cfac4d --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.auto.value.AutoValue; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; + +/** + * A {@link InProcessTransformResult} that has been committed. + */ +@AutoValue +abstract class CommittedResult { + /** + * Returns the {@link AppliedPTransform} that produced this result. + */ + public abstract AppliedPTransform getTransform(); + + /** + * Returns the outputs produced by the transform. + */ + public abstract Iterable> getOutputs(); + + public static CommittedResult create( + InProcessTransformResult original, Iterable> outputs) { + return new AutoValue_CommittedResult(original.getTransform(), + outputs); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java index d45520c196..6940421b93 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java @@ -24,7 +24,7 @@ interface CompletionCallback { /** * Handle a successful result, returning the committed outputs of the result. */ - Iterable> handleResult( + CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result); /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index cca19552dc..fd3d1e36a3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -213,14 +213,14 @@ public void awaitCompletion() throws Throwable { */ private class DefaultCompletionCallback implements CompletionCallback { @Override - public Iterable> handleResult( + public CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result) { - Iterable> resultBundles = + CommittedResult committedResult = evaluationContext.handleResult(inputBundle, Collections.emptyList(), result); - for (CommittedBundle outputBundle : resultBundles) { + for (CommittedBundle outputBundle : committedResult.getOutputs()) { allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); } - return resultBundles; + return committedResult; } @Override @@ -243,14 +243,14 @@ private TimerCompletionCallback(Iterable timers) { } @Override - public Iterable> handleResult( + public CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result) { - Iterable> resultBundles = + CommittedResult committedResult = evaluationContext.handleResult(inputBundle, timers, result); - for (CommittedBundle outputBundle : resultBundles) { + for (CommittedBundle outputBundle : committedResult.getOutputs()) { allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); } - return resultBundles; + return committedResult; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 2b21cc8584..a27ceb0ffa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -142,7 +142,7 @@ private InProcessEvaluationContext( * @param result the result of evaluating the input bundle * @return the committed bundles contained within the handled {@code result} */ - public synchronized Iterable> handleResult( + public synchronized CommittedResult handleResult( @Nullable CommittedBundle completedBundle, Iterable completedTimers, InProcessTransformResult result) { @@ -173,7 +173,7 @@ public synchronized Iterable> handleResult( applicationStateInternals.remove(stepAndKey); } } - return committedBundles; + return CommittedResult.create(result, committedBundles); } private Iterable> commitBundles( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java index 3313134120..7bf0e996a1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -157,9 +157,9 @@ private InProcessTransformResult finishBundle( TransformEvaluator evaluator, Collection> enforcements) throws Exception { InProcessTransformResult result = evaluator.finishBundle(); - Iterable> outputs = onComplete.handleResult(inputBundle, result); + CommittedResult outputs = onComplete.handleResult(inputBundle, result); for (ModelEnforcement enforcement : enforcements) { - enforcement.afterFinish(inputBundle, result, outputs); + enforcement.afterFinish(inputBundle, result, outputs.getOutputs()); } return result; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java new file mode 100644 index 0000000000..3046dc1119 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.PBegin; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; +import java.util.Collections; +import java.util.List; + +/** + * Tests for {@link CommittedResult}. + */ +@RunWith(JUnit4.class) +public class CommittedResultTest implements Serializable { + private transient TestPipeline p = TestPipeline.create(); + private transient AppliedPTransform transform = + AppliedPTransform.of("foo", p.begin(), PDone.in(p), new PTransform() { + }); + private transient BundleFactory bundleFactory = InProcessBundleFactory.create(); + + @Test + public void getTransformExtractsFromResult() { + CommittedResult result = + CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + Collections.>emptyList()); + + assertThat(result.getTransform(), Matchers.>equalTo(transform)); + } + + @Test + public void getOutputsEqualInput() { + List> outputs = + ImmutableList.of(bundleFactory.createRootBundle(PCollection.createPrimitiveOutputInternal(p, + WindowingStrategy.globalDefault(), + PCollection.IsBounded.BOUNDED)).commit(Instant.now()), + bundleFactory.createRootBundle(PCollection.createPrimitiveOutputInternal(p, + WindowingStrategy.globalDefault(), + PCollection.IsBounded.UNBOUNDED)).commit(Instant.now())); + CommittedResult result = + CommittedResult.create(StepTransformResult.withoutHold(transform).build(), outputs); + + assertThat(result.getOutputs(), Matchers.containsInAnyOrder(outputs.toArray())); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index d225519a79..7cfb63a84b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -457,7 +457,7 @@ public void isDoneWithPartiallyDone() { UncommittedBundle rootBundle = context.createRootBundle(created); rootBundle.add(WindowedValue.valueInGlobalWindow(1)); - Iterable> handleResult = + CommittedResult handleResult = context.handleResult( null, ImmutableList.of(), @@ -466,7 +466,7 @@ public void isDoneWithPartiallyDone() { .build()); @SuppressWarnings("unchecked") CommittedBundle committedBundle = - (CommittedBundle) Iterables.getOnlyElement(handleResult); + (CommittedBundle) Iterables.getOnlyElement(handleResult.getOutputs()); context.handleResult( null, ImmutableList.of(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index de7c60bcce..2dc2628e15 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -484,11 +484,11 @@ private RegisteringCompletionCallback(CountDownLatch onMethod) { } @Override - public Iterable> handleResult( + public CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result) { handledResult = result; onMethod.countDown(); - return Collections.emptyList(); + return CommittedResult.create(result, Collections.>emptyList()); } @Override From 844dd7112e173f8beb0b5704ad60cec471f2f3df Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 28 Apr 2016 13:42:36 -0700 Subject: [PATCH 365/751] Use CommittedResult in InMemoryWatermarkManager This enable unprocessed elements to be handled in the Watermark manager after they are added to the CommittedResult structure. --- .../inprocess/InMemoryWatermarkManager.java | 19 +- .../inprocess/InProcessEvaluationContext.java | 6 +- .../InMemoryWatermarkManagerTest.java | 368 ++++++++++++------ 3 files changed, 252 insertions(+), 141 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 918a7f4a1c..1bb55ab9dd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -797,18 +797,19 @@ public TransformWatermarks getWatermarks(AppliedPTransform transform) { * . * * @param completed the input that has completed - * @param transform the transform that has completed processing the input - * @param outputs the bundles the transform has output + * @param timerUpdate the timers that were added, removed, and completed as part of producing + * this update + * @param result the result that was produced by processing the input * @param earliestHold the earliest watermark hold in the transform's state. {@code null} if there * is no hold */ public void updateWatermarks( @Nullable CommittedBundle completed, - AppliedPTransform transform, TimerUpdate timerUpdate, - Iterable> outputs, + CommittedResult result, @Nullable Instant earliestHold) { - updatePending(completed, transform, timerUpdate, outputs); + AppliedPTransform transform = result.getTransform(); + updatePending(completed, timerUpdate, result); TransformWatermarks transformWms = transformToWatermarks.get(transform); transformWms.setEventTimeHold(completed == null ? null : completed.getKey(), earliestHold); refreshWatermarks(transform); @@ -843,15 +844,14 @@ private void refreshWatermarks(AppliedPTransform transform) { */ private void updatePending( CommittedBundle input, - AppliedPTransform transform, TimerUpdate timerUpdate, - Iterable> outputs) { - TransformWatermarks completedTransform = transformToWatermarks.get(transform); + CommittedResult result) { + TransformWatermarks completedTransform = transformToWatermarks.get(result.getTransform()); // Newly pending elements must be added before completed elements are removed, as the two // do not share a Mutex within this call and thus can be interleaved with external calls to // refresh. - for (CommittedBundle bundle : outputs) { + for (CommittedBundle bundle : result.getOutputs()) { for (AppliedPTransform consumer : consumers.get(bundle.getPCollection())) { TransformWatermarks watermarks = transformToWatermarks.get(consumer); watermarks.addPending(bundle); @@ -862,7 +862,6 @@ private void updatePending( if (input != null) { completedTransform.removePending(input); } - } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index a27ceb0ffa..4160d8bd51 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -149,11 +149,11 @@ public synchronized CommittedResult handleResult( Iterable> committedBundles = commitBundles(result.getOutputBundles()); // Update watermarks and timers + CommittedResult committedResult = CommittedResult.create(result, committedBundles); watermarkManager.updateWatermarks( completedBundle, - result.getTransform(), result.getTimerUpdate().withCompletedTimers(completedTimers), - committedBundles, + committedResult, result.getWatermarkHold()); fireAllAvailableCallbacks(); // Update counters @@ -173,7 +173,7 @@ public synchronized CommittedResult handleResult( applicationStateInternals.remove(stepAndKey); } } - return CommittedResult.create(result, committedBundles); + return committedResult; } private Iterable> commitBundles( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index 0603a5a386..5707bb0b2b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -156,8 +156,11 @@ public void getWatermarkForUntouchedTransform() { @Test public void getWatermarkForUpdatedSourceTransform() { CommittedBundle output = multiWindowedBundle(createdInts, 1); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(output), new Instant(8000L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(output)), + new Instant(8000L)); TransformWatermarks updatedSourceWatermark = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -172,8 +175,10 @@ public void getWatermarkForUpdatedSourceTransform() { public void getWatermarkForMultiInputTransform() { CommittedBundle secondPcollectionBundle = multiWindowedBundle(intsToFlatten, -1); - manager.updateWatermarks(null, intsToFlatten.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(secondPcollectionBundle), + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(intsToFlatten.getProducingTransformInternal(), + Collections.>singleton(secondPcollectionBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); // We didn't do anything for the first source, so we shouldn't have progressed the watermark @@ -202,13 +207,17 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle flattenedBundleSecondCreate = multiWindowedBundle(flattened, -1); // We have finished processing the bundle from the second PCollection, but we haven't consumed // anything from the first PCollection yet; so our watermark shouldn't advance - manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(flattenedBundleSecondCreate), + manager.updateWatermarks(secondPcollectionBundle, + TimerUpdate.empty(), + result(flattened.getProducingTransformInternal(), + Collections.>singleton(flattenedBundleSecondCreate)), null); TransformWatermarks transformAfterProcessing = manager.getWatermarks(flattened.getProducingTransformInternal()); - manager.updateWatermarks(secondPcollectionBundle, flattened.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(flattenedBundleSecondCreate), + manager.updateWatermarks(secondPcollectionBundle, + TimerUpdate.empty(), + result(flattened.getProducingTransformInternal(), + Collections.>singleton(flattenedBundleSecondCreate)), null); assertThat( transformAfterProcessing.getInputWatermark(), @@ -222,8 +231,10 @@ public void getWatermarkForMultiInputTransform() { timestampedBundle(createdInts, TimestampedValue.of(5, firstCollectionTimestamp)); // the source is done, but elements are still buffered. The source output watermark should be // past the end of the global window - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(firstPcollectionBundle), + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(firstPcollectionBundle)), new Instant(Long.MAX_VALUE)); TransformWatermarks firstSourceWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -250,8 +261,10 @@ public void getWatermarkForMultiInputTransform() { CommittedBundle completedFlattenBundle = bundleFactory.createRootBundle(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(firstPcollectionBundle, flattened.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(completedFlattenBundle), + manager.updateWatermarks(firstPcollectionBundle, + TimerUpdate.empty(), + result(flattened.getProducingTransformInternal(), + Collections.>singleton(completedFlattenBundle)), null); TransformWatermarks afterConsumingAllInput = manager.getWatermarks(flattened.getProducingTransformInternal()); @@ -272,8 +285,11 @@ public void getWatermarkForMultiConsumedCollection() { CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), TimestampedValue.of(3, new Instant(-1000L))); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle)), + new Instant(Long.MAX_VALUE)); TransformWatermarks createdAfterProducing = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( @@ -284,8 +300,11 @@ public void getWatermarkForMultiConsumedCollection() { timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(keyBundle), null); + manager.updateWatermarks(createdBundle, + TimerUpdate.empty(), + result(keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle)), + null); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -300,8 +319,11 @@ public void getWatermarkForMultiConsumedCollection() { CommittedBundle filteredBundle = timestampedBundle(filtered, TimestampedValue.of(2, new Instant(1234L))); - manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(filteredBundle), null); + manager.updateWatermarks(createdBundle, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(filteredBundle)), + null); TransformWatermarks filteredProcessedWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat( @@ -319,17 +341,23 @@ public void getWatermarkForMultiConsumedCollection() { @Test public void updateWatermarkWithWatermarkHolds() { CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(1, new Instant(1_000_000L)), + TimestampedValue.of(2, new Instant(1234L)), TimestampedValue.of(3, new Instant(-1000L))); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle)), + new Instant(Long.MAX_VALUE)); - CommittedBundle> keyBundle = - timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), - TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), - TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(keyBundle), + CommittedBundle> keyBundle = timestampedBundle(keyed, + TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), + TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), + TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); + manager.updateWatermarks(createdBundle, + TimerUpdate.empty(), + result(keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle)), new Instant(500L)); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); @@ -355,40 +383,54 @@ public void updateWatermarkWithKeyedWatermarkHolds() { .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) .commit(clock.now()); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - ImmutableList.of(firstKeyBundle, secondKeyBundle), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + ImmutableList.of(firstKeyBundle, secondKeyBundle)), + BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(firstKeyBundle, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>emptyList(), new Instant(-1000L)); - manager.updateWatermarks(secondKeyBundle, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>emptyList(), new Instant(1234L)); + manager.updateWatermarks(firstKeyBundle, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>emptyList()), + new Instant(-1000L)); + manager.updateWatermarks(secondKeyBundle, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>emptyList()), + new Instant(1234L)); TransformWatermarks filteredWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat( - filteredWatermarks.getInputWatermark(), + assertThat(filteredWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); CommittedBundle fauxFirstKeyTimerBundle = bundleFactory.createKeyedBundle(null, "Odd", createdInts).commit(clock.now()); - manager.updateWatermarks(fauxFirstKeyTimerBundle, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>emptyList(), + manager.updateWatermarks(fauxFirstKeyTimerBundle, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(1234L))); CommittedBundle fauxSecondKeyTimerBundle = bundleFactory.createKeyedBundle(null, "Even", createdInts).commit(clock.now()); - manager.updateWatermarks(fauxSecondKeyTimerBundle, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>emptyList(), new Instant(5678L)); + manager.updateWatermarks(fauxSecondKeyTimerBundle, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>emptyList()), + new Instant(5678L)); assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(5678L))); - manager.updateWatermarks(fauxSecondKeyTimerBundle, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>emptyList(), + manager.updateWatermarks(fauxSecondKeyTimerBundle, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat( - filteredWatermarks.getOutputWatermark(), + assertThat(filteredWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); } @@ -400,16 +442,21 @@ public void updateWatermarkWithKeyedWatermarkHolds() { public void updateOutputWatermarkShouldBeMonotonic() { CommittedBundle firstInput = bundleFactory.createRootBundle(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(firstInput), new Instant(0L)); + manager.updateWatermarks(null, TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(firstInput)), + new Instant(0L)); TransformWatermarks firstWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); CommittedBundle secondInput = bundleFactory.createRootBundle(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(secondInput), new Instant(-250L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(secondInput)), + new Instant(-250L)); TransformWatermarks secondWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); @@ -422,17 +469,22 @@ public void updateOutputWatermarkShouldBeMonotonic() { @Test public void updateWatermarkWithHoldsShouldBeMonotonic() { CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createdBundle), new Instant(Long.MAX_VALUE)); + TimestampedValue.of(1, new Instant(1_000_000L)), + TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle)), + new Instant(Long.MAX_VALUE)); CommittedBundle> keyBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(keyBundle), + manager.updateWatermarks(createdBundle, + TimerUpdate.empty(), + result(keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle)), new Instant(500L)); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); @@ -459,16 +511,22 @@ public void updateWatermarkWithLateData() { CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, sourceWatermark), TimestampedValue.of(2, new Instant(1234L))); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createdBundle), sourceWatermark); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle)), + sourceWatermark); CommittedBundle> keyBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), sourceWatermark), TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); // Finish processing the on-time data. The watermarks should progress to be equal to the source - manager.updateWatermarks(createdBundle, keyed.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(keyBundle), null); + manager.updateWatermarks(createdBundle, + TimerUpdate.empty(), + result(keyed.getProducingTransformInternal(), + Collections.>singleton(keyBundle)), + null); TransformWatermarks onTimeWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); @@ -478,8 +536,11 @@ public void updateWatermarkWithLateData() { timestampedBundle(createdInts, TimestampedValue.of(3, new Instant(-1000L))); // the late data arrives in a downstream PCollection after its watermark has advanced past it; // we don't advance the watermark past the current watermark until we've consumed the late data - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(lateDataBundle), new Instant(2_000_000L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(lateDataBundle)), + new Instant(2_000_000L)); TransformWatermarks bufferedLateWm = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); @@ -493,30 +554,31 @@ public void updateWatermarkWithLateData() { CommittedBundle> lateKeyedBundle = timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(lateDataBundle, keyed.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(lateKeyedBundle), null); + manager.updateWatermarks(lateDataBundle, + TimerUpdate.empty(), + result(keyed.getProducingTransformInternal(), + Collections.>singleton(lateKeyedBundle)), + null); } public void updateWatermarkWithDifferentWindowedValueInstances() { manager.updateWatermarks( null, - createdInts.getProducingTransformInternal(), TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), Collections.>singleton( bundleFactory .createRootBundle(createdInts) .add(WindowedValue.valueInGlobalWindow(1)) - .commit(Instant.now())), + .commit(Instant.now()))), BoundedWindow.TIMESTAMP_MAX_VALUE); manager.updateWatermarks( - bundleFactory - .createRootBundle(createdInts) + bundleFactory.createRootBundle(createdInts) .add(WindowedValue.valueInGlobalWindow(1)) .commit(Instant.now()), - keyed.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>emptyList(), + result(keyed.getProducingTransformInternal(), Collections.>emptyList()), null); TransformWatermarks onTimeWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); @@ -530,8 +592,10 @@ public void updateWatermarkWithDifferentWindowedValueInstances() { @Test public void getWatermarksAfterOnlyEmptyOutput() { CommittedBundle emptyCreateOutput = multiWindowedBundle(createdInts); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(emptyCreateOutput), + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(emptyCreateOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -557,12 +621,17 @@ public void getWatermarksAfterOnlyEmptyOutput() { @Test public void getWatermarksAfterHoldAndEmptyOutput() { CommittedBundle firstCreateOutput = multiWindowedBundle(createdInts, 1, 2); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(firstCreateOutput), new Instant(12_000L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(firstCreateOutput)), + new Instant(12_000L)); CommittedBundle firstFilterOutput = multiWindowedBundle(filtered); - manager.updateWatermarks(firstCreateOutput, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(firstFilterOutput), + manager.updateWatermarks(firstCreateOutput, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(firstFilterOutput)), new Instant(10_000L)); TransformWatermarks firstFilterWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -570,8 +639,10 @@ public void getWatermarksAfterHoldAndEmptyOutput() { assertThat(firstFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); CommittedBundle emptyCreateOutput = multiWindowedBundle(createdInts); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(emptyCreateOutput), + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(emptyCreateOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -610,8 +681,11 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { CommittedBundle createOutput = bundleFactory.createRootBundle(createdInts).commit(new Instant(1250L)); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createOutput)), + BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(clock.now())); @@ -636,8 +710,10 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { CommittedBundle filterOutputBundle = bundleFactory.createRootBundle(intsToFlatten).commit(new Instant(1250L)); - manager.updateWatermarks(createOutput, filtered.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>singleton(filterOutputBundle), + manager.updateWatermarks(createOutput, + TimerUpdate.empty(), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(filterOutputBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks filterAfterConsumed = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -658,8 +734,10 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { // @Test public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { CommittedBundle createdBundle = multiWindowedBundle(createdInts, 1, 2, 4, 8); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createdBundle), new Instant(1248L)); + manager.updateWatermarks(null, TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createdBundle)), + new Instant(1248L)); TransformWatermarks filteredWms = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -675,8 +753,10 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { TimerData.of(StateNamespaces.global(), new Instant(4096L), TimeDomain.PROCESSING_TIME); TimerUpdate timers = TimerUpdate.builder("key").setTimer(pastTimer).setTimer(futureTimer).build(); - manager.updateWatermarks(createdBundle, filtered.getProducingTransformInternal(), timers, - Collections.>singleton(filteredBundle), + manager.updateWatermarks(createdBundle, + timers, + result(filtered.getProducingTransformInternal(), + Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); Instant startTime = clock.now(); clock.set(startTime.plus(250L)); @@ -709,11 +789,11 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { bundleFactory.createKeyedBundle(null, "key", filteredTimesTwo) .commit(filteredWms.getSynchronizedProcessingOutputTime()); // Complete the processing time timer - manager.updateWatermarks(filteredTimerBundle, filtered.getProducingTransformInternal(), + manager.updateWatermarks(filteredTimerBundle, TimerUpdate.builder("key") - .withCompletedTimers(Collections.singleton(pastTimer)) - .build(), - Collections.>singleton(filteredTimerResult), + .withCompletedTimers(Collections.singleton(pastTimer)).build(), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(filteredTimerResult)), BoundedWindow.TIMESTAMP_MAX_VALUE); clock.set(startTime.plus(500L)); @@ -723,8 +803,10 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(earlierThan(filteredTimerResult.getSynchronizedProcessingOutputWatermark()))); - manager.updateWatermarks(filteredTimerResult, filteredTimesTwo.getProducingTransformInternal(), - TimerUpdate.empty(), Collections.>emptyList(), + manager.updateWatermarks(filteredTimerResult, + TimerUpdate.empty(), + result(filteredTimesTwo.getProducingTransformInternal(), + Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); @@ -758,18 +840,23 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { CommittedBundle createOutput = bundleFactory.createRootBundle(createdInts).commit(new Instant(1250L)); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createOutput), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createOutput)), + BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); - assertThat( - createAfterUpdate.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); + assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), + not(laterThan(clock.now()))); CommittedBundle createSecondOutput = bundleFactory.createRootBundle(createdInts).commit(new Instant(750L)); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(createSecondOutput), + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(createSecondOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); @@ -778,16 +865,20 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { @Test public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers() { CommittedBundle created = multiWindowedBundle(createdInts, 1, 2, 3); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(created), new Instant(40_900L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(created)), + new Instant(40_900L)); CommittedBundle filteredBundle = multiWindowedBundle(filtered, 2, 4); Instant upstreamHold = new Instant(2048L); TimerData upstreamProcessingTimer = TimerData.of(StateNamespaces.global(), upstreamHold, TimeDomain.PROCESSING_TIME); - manager.updateWatermarks(created, filtered.getProducingTransformInternal(), + manager.updateWatermarks(created, TimerUpdate.builder("key").setTimer(upstreamProcessingTimer).build(), - Collections.>singleton(filteredBundle), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks downstreamWms = @@ -803,11 +894,12 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); CommittedBundle otherCreated = multiWindowedBundle(createdInts, 4, 8, 12); - manager.updateWatermarks(otherCreated, filtered.getProducingTransformInternal(), + manager.updateWatermarks(otherCreated, TimerUpdate.builder("key") - .withCompletedTimers(Collections.singleton(upstreamProcessingTimer)) - .build(), - Collections.>emptyList(), BoundedWindow.TIMESTAMP_MAX_VALUE); + .withCompletedTimers(Collections.singleton(upstreamProcessingTimer)).build(), + result(filtered.getProducingTransformInternal(), + Collections.>emptyList()), + BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(downstreamWms.getSynchronizedProcessingInputTime(), not(earlierThan(clock.now()))); } @@ -817,9 +909,9 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { CommittedBundle created = multiWindowedBundle(createdInts, 1, 2, 3); manager.updateWatermarks( null, - createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(created), + result(createdInts.getProducingTransformInternal(), + Collections.>singleton(created)), new Instant(29_919_235L)); Instant upstreamHold = new Instant(2048L); @@ -827,9 +919,9 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { bundleFactory.createKeyedBundle(created, "key", filtered).commit(upstreamHold); manager.updateWatermarks( created, - filtered.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>singleton(filteredBundle), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks downstreamWms = @@ -849,8 +941,10 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { // Advance WM of keyed past the first timer, but ahead of the second and third CommittedBundle createdBundle = multiWindowedBundle(filtered); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.singleton(createdBundle), new Instant(1500L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), Collections.singleton(createdBundle)), + new Instant(1500L)); TimerData earliestTimer = TimerData.of(StateNamespaces.global(), new Instant(1000), TimeDomain.EVENT_TIME); @@ -866,11 +960,10 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { .setTimer(lastTimer) .build(); - manager.updateWatermarks( - createdBundle, - filtered.getProducingTransformInternal(), + manager.updateWatermarks(createdBundle, update, - Collections.>singleton(multiWindowedBundle(intsToFlatten)), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); Map, Map> firstTransformFiredTimers = @@ -883,8 +976,11 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { FiredTimers firstFired = firstFilteredTimers.get(key); assertThat(firstFired.getTimers(TimeDomain.EVENT_TIME), contains(earliestTimer)); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>emptyList(), new Instant(50_000L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>emptyList()), + new Instant(50_000L)); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( @@ -906,8 +1002,10 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { // Advance WM of keyed past the first timer, but ahead of the second and third CommittedBundle createdBundle = multiWindowedBundle(filtered); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.singleton(createdBundle), new Instant(1500L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), Collections.singleton(createdBundle)), + new Instant(1500L)); TimerData earliestTimer = TimerData.of(StateNamespaces.global(), new Instant(999L), TimeDomain.PROCESSING_TIME); @@ -925,9 +1023,9 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { manager.updateWatermarks( createdBundle, - filtered.getProducingTransformInternal(), update, - Collections.>singleton(multiWindowedBundle(intsToFlatten)), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); Map, Map> firstTransformFiredTimers = @@ -941,8 +1039,11 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { assertThat(firstFired.getTimers(TimeDomain.PROCESSING_TIME), contains(earliestTimer)); clock.set(new Instant(50_000L)); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>emptyList(), new Instant(50_000L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>emptyList()), + new Instant(50_000L)); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( @@ -964,8 +1065,10 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { // Advance WM of keyed past the first timer, but ahead of the second and third CommittedBundle createdBundle = multiWindowedBundle(filtered); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.singleton(createdBundle), new Instant(1500L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), Collections.singleton(createdBundle)), + new Instant(1500L)); TimerData earliestTimer = TimerData.of( StateNamespaces.global(), new Instant(999L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); @@ -983,9 +1086,9 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { manager.updateWatermarks( createdBundle, - filtered.getProducingTransformInternal(), update, - Collections.>singleton(multiWindowedBundle(intsToFlatten)), + result(filtered.getProducingTransformInternal(), + Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); Map, Map> firstTransformFiredTimers = @@ -1000,8 +1103,11 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { firstFired.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), contains(earliestTimer)); clock.set(new Instant(50_000L)); - manager.updateWatermarks(null, createdInts.getProducingTransformInternal(), TimerUpdate.empty(), - Collections.>emptyList(), new Instant(50_000L)); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + Collections.>emptyList()), + new Instant(50_000L)); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( @@ -1130,7 +1236,6 @@ public boolean matches(Object item) { ReadableInstant instant = (ReadableInstant) item; return instant.isAfter(shouldBeEarlier); } - @Override public void describeTo(Description description) { description.appendText("later than ").appendValue(shouldBeEarlier); @@ -1162,4 +1267,11 @@ private final CommittedBundle multiWindowedBundle(PCollection pc, T... } return bundle.commit(BoundedWindow.TIMESTAMP_MAX_VALUE); } + + private final CommittedResult result( + AppliedPTransform transform, + Iterable> bundles) { + return CommittedResult.create(StepTransformResult.withoutHold(transform) + .build(), bundles); + } } From f9c8460a5baf0ab0b085e182859317c0b88e4de6 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 9 May 2016 18:42:09 -0700 Subject: [PATCH 366/751] Explicitly use a ConcurrentLinkedQueue in UnboundedReadEvaluatorFactory (#245) --- .../UnboundedReadEvaluatorFactory.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index cba9007cc6..ee8f02f2c5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -44,8 +44,14 @@ class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { * An evaluator for a Source is stateful, to ensure the CheckpointMark is properly persisted. * Evaluators are cached here to ensure that the checkpoint mark is appropriately reused * and any splits are honored. + * + *

          The Queue storing available evaluators must enforce a happens-before relationship for + * elements being added to the queue to accesses after it, to ensure that updates performed to the + * state of an evaluator are properly visible. ConcurrentLinkedQueue provides this relation, but + * an arbitrary Queue implementation does not, so the concrete type is used explicitly. */ - private final ConcurrentMap>> + private final ConcurrentMap< + EvaluatorKey, ConcurrentLinkedQueue>> sourceEvaluators = new ConcurrentHashMap<>(); @SuppressWarnings({"unchecked", "rawtypes"}) @@ -81,8 +87,8 @@ private Queue> getTransformEvaluatorQu // Pipeline#run). EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); @SuppressWarnings("unchecked") - Queue> evaluatorQueue = - (Queue>) sourceEvaluators.get(key); + ConcurrentLinkedQueue> evaluatorQueue = + (ConcurrentLinkedQueue>) sourceEvaluators.get(key); if (evaluatorQueue == null) { evaluatorQueue = new ConcurrentLinkedQueue<>(); if (sourceEvaluators.putIfAbsent(key, evaluatorQueue) == null) { @@ -95,7 +101,8 @@ private Queue> getTransformEvaluatorQu evaluatorQueue.offer(evaluator); } else { // otherwise return the existing Queue that arrived before us - evaluatorQueue = (Queue>) sourceEvaluators.get(key); + evaluatorQueue = + (ConcurrentLinkedQueue>) sourceEvaluators.get(key); } } return evaluatorQueue; @@ -115,7 +122,7 @@ private static class UnboundedReadEvaluator implements TransformEvaluat private static final int ARBITRARY_MAX_ELEMENTS = 10; private final AppliedPTransform, Unbounded> transform; private final InProcessEvaluationContext evaluationContext; - private final Queue> evaluatorQueue; + private final ConcurrentLinkedQueue> evaluatorQueue; /** * The source being read from by this {@link UnboundedReadEvaluator}. This may not be the same * source as derived from {@link #transform} due to splitting. @@ -127,7 +134,7 @@ public UnboundedReadEvaluator( AppliedPTransform, Unbounded> transform, InProcessEvaluationContext evaluationContext, UnboundedSource source, - Queue> evaluatorQueue) { + ConcurrentLinkedQueue> evaluatorQueue) { this.transform = transform; this.evaluationContext = evaluationContext; this.evaluatorQueue = evaluatorQueue; From 594011e975c1a8bc3904f2228354c035323a65f5 Mon Sep 17 00:00:00 2001 From: lukecwik Date: Tue, 10 May 2016 16:55:33 -0700 Subject: [PATCH 367/751] Backport incubator-beam PR #321 (#251) * Backport incubator-beam #321 Note, maven archetypes already at Gauva 19.0 and we don't depend explicitly on google-auth-library-oauth2-http * Bring in google-auth-library-oauth2-http so it matches incubator-beam version * !fixup Change to runtime scope since we only depend on this indirectly --- sdk/pom.xml | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index 477436f0cc..40d9c5cf98 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -458,6 +458,21 @@ 0.12.0 + + com.google.auth + google-auth-library-oauth2-http + 0.4.0 + runtime + + + + com.google.guava + guava-jdk5 + + + + com.google.cloud.bigtable bigtable-protos @@ -687,13 +702,13 @@ com.google.cloud.bigdataoss gcsio - 1.4.3 + 1.4.5 com.google.cloud.bigdataoss util - 1.4.3 + 1.4.5 From 07b0e04b07a902c29326978670a2d345516772d5 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 25 Apr 2016 09:08:09 -0700 Subject: [PATCH 368/751] Refactor CommittedBundle in InProcessBundleFactory Move to a static nested class. --- .../inprocess/InProcessBundleFactory.java | 82 +++++++++++-------- 1 file changed, 50 insertions(+), 32 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java index 99b5c1dfea..da5f97c2d5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java @@ -97,38 +97,56 @@ public CommittedBundle commit(final Instant synchronizedCompletionTime) { checkState(!committed, "Can't commit already committed bundle %s", this); committed = true; final Iterable> committedElements = elements.build(); - return new CommittedBundle() { - @Override - @Nullable - public Object getKey() { - return key; - } - - @Override - public Iterable> getElements() { - return committedElements; - } - - @Override - public PCollection getPCollection() { - return pcollection; - } - - @Override - public Instant getSynchronizedProcessingOutputWatermark() { - return synchronizedCompletionTime; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .omitNullValues() - .add("pcollection", pcollection) - .add("key", key) - .add("elements", committedElements) - .toString(); - } - }; + return new CommittedInProcessBundle<>( + pcollection, key, committedElements, synchronizedCompletionTime); + } + } + private static class CommittedInProcessBundle implements CommittedBundle { + public CommittedInProcessBundle( + PCollection pcollection, + Object key, + Iterable> committedElements, + Instant synchronizedCompletionTime) { + this.pcollection = pcollection; + this.key = key; + this.committedElements = committedElements; + this.synchronizedCompletionTime = synchronizedCompletionTime; + } + + private final PCollection pcollection; + private final Object key; + private final Iterable> committedElements; + private final Instant synchronizedCompletionTime; + + @Override + @Nullable + public Object getKey() { + return key; + } + + @Override + public Iterable> getElements() { + return committedElements; + } + + @Override + public PCollection getPCollection() { + return pcollection; + } + + @Override + public Instant getSynchronizedProcessingOutputWatermark() { + return synchronizedCompletionTime; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .omitNullValues() + .add("pcollection", pcollection) + .add("key", key) + .add("elements", committedElements) + .toString(); } } } From 4f669811729b6733d3f14bf105ea89e4ce5181d6 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 25 Apr 2016 09:09:15 -0700 Subject: [PATCH 369/751] Add withElements to CommittedBundle The unprocessed elements of a partially completed bundle must be placed in a new bundle to be processed at a later time. The bundle in which they are processed should also have identical properties to the bundle which the elements were initially present in. withElements provides a simple way to create a "copy" of a bundle that contains different elements. --- .../inprocess/InProcessBundleFactory.java | 7 ++++ .../inprocess/InProcessPipelineRunner.java | 13 ++++++ .../inprocess/InProcessBundleFactoryTest.java | 42 +++++++++++++++++-- 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java index da5f97c2d5..73a18dbf33 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java @@ -101,6 +101,7 @@ public CommittedBundle commit(final Instant synchronizedCompletionTime) { pcollection, key, committedElements, synchronizedCompletionTime); } } + private static class CommittedInProcessBundle implements CommittedBundle { public CommittedInProcessBundle( PCollection pcollection, @@ -148,6 +149,12 @@ public String toString() { .add("elements", committedElements) .toString(); } + + @Override + public CommittedBundle withElements(Iterable> elements) { + return new CommittedInProcessBundle<>( + pcollection, key, ImmutableList.copyOf(elements), synchronizedCompletionTime); + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 3e333399a4..297e9e8ed9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -149,6 +149,19 @@ public static interface CommittedBundle { * timers that fired to produce this bundle. */ Instant getSynchronizedProcessingOutputWatermark(); + + /** + * Return a new {@link CommittedBundle} that is like this one, except calls to + * {@link #getElements()} will return the provided elements. This bundle is unchanged. + * + *

          + * The value of the {@link #getSynchronizedProcessingOutputWatermark() synchronized processing + * output watermark} of the returned {@link CommittedBundle} is equal to the value returned from + * the current bundle. This is used to ensure a {@link PTransform} that could not complete + * processing on input elements properly holds the synchronized processing time to the + * appropriate value. + */ + CommittedBundle withElements(Iterable> elements); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java index 9b4e630042..a88f6b3ddc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java @@ -1,4 +1,4 @@ - /* +/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not @@ -25,6 +25,8 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -94,7 +96,8 @@ public void keyedWithKeyShouldCreateKeyedBundle() { createKeyedBundle(new Object()); } - private void afterCommitGetElementsShouldHaveAddedElements(Iterable> elems) { + private CommittedBundle + afterCommitGetElementsShouldHaveAddedElements(Iterable> elems) { PCollection pcollection = TestPipeline.create().apply(Create.of()); UncommittedBundle bundle = bundleFactory.createRootBundle(pcollection); @@ -105,7 +108,10 @@ private void afterCommitGetElementsShouldHaveAddedElements(Iterable>> containsMatcher = Matchers.>containsInAnyOrder(expectations); - assertThat(bundle.commit(Instant.now()).getElements(), containsMatcher); + CommittedBundle committed = bundle.commit(Instant.now()); + assertThat(committed.getElements(), containsMatcher); + + return committed; } @Test @@ -122,6 +128,36 @@ public void getElementsAfterAddShouldReturnAddedElements() { afterCommitGetElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); } + @SuppressWarnings("unchecked") + @Test + public void withElementsShouldReturnIndependentBundle() { + WindowedValue firstValue = WindowedValue.valueInGlobalWindow(1); + WindowedValue secondValue = + WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1000L)); + + CommittedBundle committed = + afterCommitGetElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); + + WindowedValue firstReplacement = + WindowedValue.of( + 9, + new Instant(2048L), + new IntervalWindow(new Instant(2044L), Instant.now()), + PaneInfo.NO_FIRING); + WindowedValue secondReplacement = + WindowedValue.timestampedValueInGlobalWindow(-1, Instant.now()); + CommittedBundle withed = + committed.withElements(ImmutableList.of(firstReplacement, secondReplacement)); + + assertThat(withed.getElements(), containsInAnyOrder(firstReplacement, secondReplacement)); + assertThat(committed.getElements(), containsInAnyOrder(firstValue, secondValue)); + assertThat(withed.getKey(), equalTo(committed.getKey())); + assertThat(withed.getPCollection(), equalTo(committed.getPCollection())); + assertThat( + withed.getSynchronizedProcessingOutputWatermark(), + equalTo(committed.getSynchronizedProcessingOutputWatermark())); + } + @Test public void addAfterCommitShouldThrowException() { PCollection pcollection = TestPipeline.create().apply(Create.of()); From 831b2c3e0bd47f2e2977529fe4d4d16219e40c79 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 2 May 2016 10:03:43 -0700 Subject: [PATCH 370/751] Move ReadyCheckingSideInputReader to util This SideInputReader allows callers to check for a side input being available before attempting to read the contents --- .../inprocess/InProcessEvaluationContext.java | 12 +------ .../InProcessSideInputContainer.java | 2 +- .../util/ReadyCheckingSideInputReader.java | 31 +++++++++++++++++++ .../InProcessSideInputContainerTest.java | 2 +- 4 files changed, 34 insertions(+), 13 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 2b21cc8584..420c1a97a6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -29,6 +29,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.util.ExecutionContext; +import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -330,17 +331,6 @@ public ReadyCheckingSideInputReader createSideInputReader( return sideInputContainer.createReaderForViews(sideInputs); } - /** - * A {@link SideInputReader} that allows callers to check to see if a {@link PCollectionView} has - * had its contents set in a window. - */ - interface ReadyCheckingSideInputReader extends SideInputReader { - /** - * Returns true if the {@link PCollectionView} is ready in the provided {@link BoundedWindow}. - */ - boolean isReady(PCollectionView view, BoundedWindow window); - } - /** * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent * of all other {@link CounterSet CounterSets} created by this call. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java index 697348039a..e6fd49f750 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -17,10 +17,10 @@ import static com.google.common.base.Preconditions.checkArgument; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessEvaluationContext.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; +import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java new file mode 100644 index 0000000000..718c9438de --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.values.PCollectionView; + +/** + * A {@link SideInputReader} that allows callers to check to see if a {@link PCollectionView} has + * had its contents set in a window. + */ +public interface ReadyCheckingSideInputReader extends SideInputReader { + /** + * Returns true if the {@link PCollectionView} is ready in the provided {@link BoundedWindow}. + */ + boolean isReady(PCollectionView view, BoundedWindow window); +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java index c4d855bf17..9073a4715e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java @@ -24,7 +24,6 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessEvaluationContext.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.Mean; @@ -35,6 +34,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; import com.google.cloud.dataflow.sdk.util.PCollectionViews; +import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.util.SideInputReader; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; From d5604f8cf8c5babae5ffb4da748697fff8e95fae Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 2 May 2016 10:04:20 -0700 Subject: [PATCH 371/751] Add PushbackSideInputDoFnRunner This DoFnRunner wraps a DoFnRunner and provides an additional method to process an element in all the windows where all side inputs are ready, returning any elements that it could not process. --- .../sdk/util/PushbackSideInputDoFnRunner.java | 115 +++++++++ .../sdk/util/IdentitySideInputWindowFn.java | 54 ++++ .../util/PushbackSideInputDoFnRunnerTest.java | 234 ++++++++++++++++++ 3 files changed, 403 insertions(+) create mode 100644 sdks/java/core/src/main/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunner.java create mode 100644 sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java create mode 100644 sdks/java/core/src/test/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunnerTest.java diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunner.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunner.java new file mode 100644 index 0000000000..4eeedf65a1 --- /dev/null +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunner.java @@ -0,0 +1,115 @@ +/* + * 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.beam.sdk.util; + +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.values.PCollectionView; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * A {@link DoFnRunner} that can refuse to process elements that are not ready, instead returning + * them via the {@link #processElementInReadyWindows(WindowedValue)}. + */ +class PushbackSideInputDoFnRunner implements DoFnRunner { + private final DoFnRunner underlying; + private final Collection> views; + private final ReadyCheckingSideInputReader sideInputReader; + + private Set notReadyWindows; + + public static PushbackSideInputDoFnRunner create( + DoFnRunner underlying, + Collection> views, + ReadyCheckingSideInputReader sideInputReader) { + return new PushbackSideInputDoFnRunner<>(underlying, views, sideInputReader); + } + + private PushbackSideInputDoFnRunner( + DoFnRunner underlying, + Collection> views, + ReadyCheckingSideInputReader sideInputReader) { + this.underlying = underlying; + this.views = views; + this.sideInputReader = sideInputReader; + } + + @Override + public void startBundle() { + notReadyWindows = new HashSet<>(); + underlying.startBundle(); + } + + /** + * Call the underlying {@link DoFnRunner#processElement(WindowedValue)} for the provided element + * for each window the element is in that is ready. + * + * @param elem the element to process in all ready windows + * @return each element that could not be processed because it requires a side input window + * that is not ready. + */ + public Iterable> processElementInReadyWindows(WindowedValue elem) { + if (views.isEmpty()) { + processElement(elem); + return Collections.emptyList(); + } + ImmutableList.Builder> pushedBack = ImmutableList.builder(); + for (WindowedValue windowElem : elem.explodeWindows()) { + BoundedWindow mainInputWindow = Iterables.getOnlyElement(windowElem.getWindows()); + boolean isReady = !notReadyWindows.contains(mainInputWindow); + for (PCollectionView view : views) { + BoundedWindow sideInputWindow = + view.getWindowingStrategyInternal() + .getWindowFn() + .getSideInputWindow(mainInputWindow); + if (!sideInputReader.isReady(view, sideInputWindow)) { + isReady = false; + break; + } + } + if (isReady) { + processElement(windowElem); + } else { + notReadyWindows.add(mainInputWindow); + pushedBack.add(windowElem); + } + } + return pushedBack.build(); + } + + @Override + public void processElement(WindowedValue elem) { + underlying.processElement(elem); + } + + /** + * Call the underlying {@link DoFnRunner#finishBundle()}. + */ + @Override + public void finishBundle() { + notReadyWindows = null; + underlying.finishBundle(); + } +} + diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java new file mode 100644 index 0000000000..ecab6f8eb6 --- /dev/null +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java @@ -0,0 +1,54 @@ +/* + * 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.beam.sdk.util; + +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; +import org.apache.beam.sdk.transforms.windowing.NonMergingWindowFn; +import org.apache.beam.sdk.transforms.windowing.WindowFn; + +import java.util.Collection; + +/** + * A {@link WindowFn} for use during tests that returns the input window for calls to + * {@link #getSideInputWindow(BoundedWindow)}. + */ +class IdentitySideInputWindowFn extends NonMergingWindowFn { + @Override + public Collection assignWindows(WindowFn.AssignContext c) + throws Exception { + return (Collection) c.windows(); + } + + @Override + public boolean isCompatible(WindowFn other) { + return true; + } + + @Override + public Coder windowCoder() { + // not used + return (Coder) GlobalWindow.Coder.INSTANCE; + } + + @Override + public BoundedWindow getSideInputWindow(BoundedWindow window) { + return window; + } +} diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunnerTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunnerTest.java new file mode 100644 index 0000000000..88851187bb --- /dev/null +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunnerTest.java @@ -0,0 +1,234 @@ +/* + * 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.beam.sdk.util; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PCollectionView; + +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tests for {@link PushbackSideInputDoFnRunner}. + */ +@RunWith(JUnit4.class) +public class PushbackSideInputDoFnRunnerTest { + @Mock private ReadyCheckingSideInputReader reader; + private TestDoFnRunner underlying; + private PCollectionView singletonView; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + TestPipeline p = TestPipeline.create(); + PCollection created = p.apply(Create.of(1, 2, 3)); + singletonView = + created + .apply(Window.into(new IdentitySideInputWindowFn())) + .apply(Sum.integersGlobally().asSingletonView()); + + underlying = new TestDoFnRunner<>(); + } + + private PushbackSideInputDoFnRunner createRunner( + ImmutableList> views) { + PushbackSideInputDoFnRunner runner = + PushbackSideInputDoFnRunner.create(underlying, views, reader); + runner.startBundle(); + return runner; + } + + @Test + public void startFinishBundleDelegates() { + PushbackSideInputDoFnRunner runner = + createRunner(ImmutableList.>of(singletonView)); + + assertThat(underlying.started, is(true)); + assertThat(underlying.finished, is(false)); + runner.finishBundle(); + assertThat(underlying.finished, is(true)); + } + + @Test + public void processElementSideInputNotReady() { + when(reader.isReady(Mockito.eq(singletonView), Mockito.any(BoundedWindow.class))) + .thenReturn(false); + + PushbackSideInputDoFnRunner runner = + createRunner(ImmutableList.>of(singletonView)); + + WindowedValue oneWindow = + WindowedValue.of( + 2, + new Instant(-2), + new IntervalWindow(new Instant(-500L), new Instant(0L)), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + Iterable> oneWindowPushback = + runner.processElementInReadyWindows(oneWindow); + assertThat(oneWindowPushback, containsInAnyOrder(oneWindow)); + assertThat(underlying.inputElems, Matchers.>emptyIterable()); + } + + @Test + public void processElementSideInputNotReadyMultipleWindows() { + when(reader.isReady(Mockito.eq(singletonView), Mockito.any(BoundedWindow.class))) + .thenReturn(false); + + PushbackSideInputDoFnRunner runner = + createRunner(ImmutableList.>of(singletonView)); + + WindowedValue multiWindow = + WindowedValue.of( + 2, + new Instant(-2), + ImmutableList.of( + new IntervalWindow(new Instant(-500L), new Instant(0L)), + new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)), + GlobalWindow.INSTANCE), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + Iterable> multiWindowPushback = + runner.processElementInReadyWindows(multiWindow); + assertThat(multiWindowPushback, equalTo(multiWindow.explodeWindows())); + assertThat(underlying.inputElems, Matchers.>emptyIterable()); + } + + @Test + public void processElementSideInputNotReadySomeWindows() { + when(reader.isReady(Mockito.eq(singletonView), Mockito.eq(GlobalWindow.INSTANCE))) + .thenReturn(false); + when( + reader.isReady( + Mockito.eq(singletonView), + org.mockito.AdditionalMatchers.not(Mockito.eq(GlobalWindow.INSTANCE)))) + .thenReturn(true); + + PushbackSideInputDoFnRunner runner = + createRunner(ImmutableList.>of(singletonView)); + + IntervalWindow littleWindow = new IntervalWindow(new Instant(-500L), new Instant(0L)); + IntervalWindow bigWindow = + new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)); + WindowedValue multiWindow = + WindowedValue.of( + 2, + new Instant(-2), + ImmutableList.of(littleWindow, bigWindow, GlobalWindow.INSTANCE), + PaneInfo.NO_FIRING); + Iterable> multiWindowPushback = + runner.processElementInReadyWindows(multiWindow); + assertThat( + multiWindowPushback, + containsInAnyOrder(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(-2L)))); + assertThat(underlying.inputElems, + containsInAnyOrder(WindowedValue.of(2, new Instant(-2), littleWindow, PaneInfo.NO_FIRING), + WindowedValue.of(2, new Instant(-2), bigWindow, PaneInfo.NO_FIRING))); + } + + @Test + public void processElementSideInputReadyAllWindows() { + when(reader.isReady(Mockito.eq(singletonView), Mockito.any(BoundedWindow.class))) + .thenReturn(true); + + ImmutableList> views = ImmutableList.>of(singletonView); + PushbackSideInputDoFnRunner runner = createRunner(views); + + WindowedValue multiWindow = + WindowedValue.of( + 2, + new Instant(-2), + ImmutableList.of( + new IntervalWindow(new Instant(-500L), new Instant(0L)), + new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)), + GlobalWindow.INSTANCE), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + Iterable> multiWindowPushback = + runner.processElementInReadyWindows(multiWindow); + assertThat(multiWindowPushback, emptyIterable()); + assertThat(underlying.inputElems, + containsInAnyOrder(ImmutableList.copyOf(multiWindow.explodeWindows()).toArray())); + } + + @Test + public void processElementNoSideInputs() { + PushbackSideInputDoFnRunner runner = + createRunner(ImmutableList.>of()); + + WindowedValue multiWindow = + WindowedValue.of( + 2, + new Instant(-2), + ImmutableList.of( + new IntervalWindow(new Instant(-500L), new Instant(0L)), + new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)), + GlobalWindow.INSTANCE), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + Iterable> multiWindowPushback = + runner.processElementInReadyWindows(multiWindow); + assertThat(multiWindowPushback, emptyIterable()); + assertThat(underlying.inputElems, containsInAnyOrder(multiWindow)); + } + + private static class TestDoFnRunner implements DoFnRunner { + List> inputElems; + private boolean started = false; + private boolean finished = false; + + @Override + public void startBundle() { + started = true; + inputElems = new ArrayList<>(); + } + + @Override + public void processElement(WindowedValue elem) { + inputElems.add(elem); + } + + @Override + public void finishBundle() { + finished = true; + } + } +} From 0cc92549d9745440779096abd9e6487c1f2c0754 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 9 May 2016 14:03:16 -0700 Subject: [PATCH 372/751] Return null evaluators from Unavailable Reads Null TransformEvaluators for sources represent a source where all splits are currently in use or completed. Update TransformExecutor to handle null evaluators properly. Change TransformExecutor to a Runnable. --- .../inprocess/BoundedReadEvaluatorFactory.java | 8 ++------ .../inprocess/TransformEvaluatorFactory.java | 9 +++++++-- .../sdk/runners/inprocess/TransformExecutor.java | 9 ++++++--- .../inprocess/UnboundedReadEvaluatorFactory.java | 8 ++------ .../BoundedReadEvaluatorFactoryTest.java | 16 +++------------- .../inprocess/TransformExecutorServicesTest.java | 10 +++++----- .../runners/inprocess/TransformExecutorTest.java | 8 ++++---- .../UnboundedReadEvaluatorFactoryTest.java | 13 ++++--------- 8 files changed, 33 insertions(+), 48 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java index 4a736a5272..26f1f88399 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java @@ -49,6 +49,7 @@ final class BoundedReadEvaluatorFactory implements TransformEvaluatorFactory { @SuppressWarnings({"unchecked", "rawtypes"}) @Override + @Nullable public TransformEvaluator forApplication( AppliedPTransform application, @Nullable CommittedBundle inputBundle, @@ -60,12 +61,7 @@ public TransformEvaluator forApplication( private TransformEvaluator getTransformEvaluator( final AppliedPTransform, Bounded> transform, final InProcessEvaluationContext evaluationContext) { - BoundedReadEvaluator evaluator = - getTransformEvaluatorQueue(transform, evaluationContext).poll(); - if (evaluator == null) { - return EmptyTransformEvaluator.create(transform); - } - return evaluator; + return getTransformEvaluatorQueue(transform, evaluationContext).poll(); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java index 860ddfe48f..b0eb19e57e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java @@ -30,13 +30,18 @@ public interface TransformEvaluatorFactory { /** * Create a new {@link TransformEvaluator} for the application of the {@link PTransform}. * - * Any work that must be done before input elements are processed (such as calling + *

          Any work that must be done before input elements are processed (such as calling * {@link DoFn#startBundle(DoFn.Context)}) must be done before the {@link TransformEvaluator} is * made available to the caller. * + *

          May return null if the application cannot produce an evaluator (for example, it is a + * {@link Read} {@link PTransform} where all evaluators are in-use). + * + * @return An evaluator capable of processing the transform on the bundle, or null if no evaluator + * can be constructed. * @throws Exception whenever constructing the underlying evaluator throws an exception */ - TransformEvaluator forApplication( + @Nullable TransformEvaluator forApplication( AppliedPTransform application, @Nullable CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) throws Exception; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java index 3313134120..ada492abbf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -36,7 +36,7 @@ *

          A {@link TransformExecutor} that is currently executing also provides access to the thread * that it is being executed on. */ -class TransformExecutor implements Callable { +class TransformExecutor implements Runnable { public static TransformExecutor create( TransformEvaluatorFactory factory, Iterable modelEnforcements, @@ -92,7 +92,7 @@ private TransformExecutor( } @Override - public InProcessTransformResult call() { + public void run() { checkState( thread.compareAndSet(null, Thread.currentThread()), "Tried to execute %s for %s on thread %s, but is already executing on thread %s", @@ -108,11 +108,14 @@ public InProcessTransformResult call() { } TransformEvaluator evaluator = evaluatorFactory.forApplication(transform, inputBundle, evaluationContext); + if (evaluator == null) { + // Nothing to do + return; + } processElements(evaluator, enforcements); InProcessTransformResult result = finishBundle(evaluator, enforcements); - return result; } catch (Throwable t) { onComplete.handleThrowable(inputBundle, t); if (t instanceof RuntimeException) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index ee8f02f2c5..a0b62b353f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -56,6 +56,7 @@ class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { @SuppressWarnings({"unchecked", "rawtypes"}) @Override + @Nullable public TransformEvaluator forApplication(AppliedPTransform application, @Nullable CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { return getTransformEvaluator((AppliedPTransform) application, evaluationContext); @@ -64,12 +65,7 @@ public TransformEvaluator forApplication(AppliedPTransform TransformEvaluator getTransformEvaluator( final AppliedPTransform, Unbounded> transform, final InProcessEvaluationContext evaluationContext) { - UnboundedReadEvaluator currentEvaluator = - getTransformEvaluatorQueue(transform, evaluationContext).poll(); - if (currentEvaluator == null) { - return EmptyTransformEvaluator.create(transform); - } - return currentEvaluator; + return getTransformEvaluatorQueue(transform, evaluationContext).poll(); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java index 5de5a59b25..b2fdc71bc8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java @@ -19,6 +19,7 @@ import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; @@ -114,15 +115,7 @@ public void boundedSourceInMemoryTransformEvaluatorAfterFinishIsEmpty() throws E when(context.createRootBundle(longs)).thenReturn(secondOutput); TransformEvaluator secondEvaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); - InProcessTransformResult secondResult = secondEvaluator.finishBundle(); - assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - assertThat(secondResult.getOutputBundles(), emptyIterable()); - assertThat( - secondOutput.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(), emptyIterable()); - assertThat( - outputElements, - containsInAnyOrder( - gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); + assertThat(secondEvaluator, nullValue()); } /** @@ -140,8 +133,7 @@ public void boundedSourceEvaluatorSimultaneousEvaluations() throws Exception { factory.forApplication(longs.getProducingTransformInternal(), null, context); TransformEvaluator secondEvaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); - - InProcessTransformResult secondResult = secondEvaluator.finishBundle(); + assertThat(secondEvaluator, nullValue()); InProcessTransformResult result = evaluator.finishBundle(); assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); @@ -152,8 +144,6 @@ public void boundedSourceEvaluatorSimultaneousEvaluations() throws Exception { outputElements, containsInAnyOrder( gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); - assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - assertThat(secondResult.getOutputBundles(), emptyIterable()); assertThat( secondOutput.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(), emptyIterable()); assertThat( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java index 2c66dc2c32..b254f8ec61 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java @@ -65,8 +65,8 @@ public void parallelScheduleMultipleSchedulesBothImmediately() { parallel.schedule(first); parallel.schedule(second); - verify(first).call(); - verify(second).call(); + verify(first).run(); + verify(second).run(); assertThat( scheduled, Matchers.allOf( @@ -93,10 +93,10 @@ public void serialScheduleTwoWaitsForFirstToComplete() { TransformExecutorService serial = TransformExecutorServices.serial(executorService, scheduled); serial.schedule(first); - verify(first).call(); + verify(first).run(); serial.schedule(second); - verify(second, never()).call(); + verify(second, never()).run(); assertThat(scheduled, Matchers., Boolean>hasEntry(first, true)); assertThat( @@ -106,7 +106,7 @@ public void serialScheduleTwoWaitsForFirstToComplete() { Matchers.>equalTo(second), any(Boolean.class)))); serial.complete(first); - verify(second).call(); + verify(second).run(); assertThat(scheduled, Matchers., Boolean>hasEntry(second, true)); assertThat( scheduled, diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index de7c60bcce..022133b19f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -127,7 +127,7 @@ public InProcessTransformResult finishBundle() throws Exception { created.getProducingTransformInternal(), completionCallback, transformEvaluationState); - executor.call(); + executor.run(); assertThat(finishCalled.get(), is(true)); assertThat(completionCallback.handledResult, equalTo(result)); @@ -346,7 +346,7 @@ public InProcessTransformResult finishBundle() throws Exception { completionCallback, transformEvaluationState); - executor.call(); + executor.run(); TestEnforcement testEnforcement = enforcement.instance; assertThat( testEnforcement.beforeElements, @@ -406,7 +406,7 @@ public InProcessTransformResult finishBundle() throws Exception { completionCallback, transformEvaluationState); - Future task = Executors.newSingleThreadExecutor().submit(executor); + Future task = Executors.newSingleThreadExecutor().submit(executor); testLatch.await(); fooBytes.getValue()[0] = 'b'; evaluatorLatch.countDown(); @@ -465,7 +465,7 @@ public InProcessTransformResult finishBundle() throws Exception { completionCallback, transformEvaluationState); - Future task = Executors.newSingleThreadExecutor().submit(executor); + Future task = Executors.newSingleThreadExecutor().submit(executor); testLatch.await(); fooBytes.getValue()[0] = 'b'; evaluatorLatch.countDown(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java index ab0b939597..d96e9e9f21 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java @@ -19,6 +19,7 @@ import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -37,7 +38,6 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -133,7 +133,7 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleSequentialCalls() t } @Test - public void boundedSourceEvaluatorClosesReader() throws Exception { + public void evaluatorClosesReader() throws Exception { TestUnboundedSource source = new TestUnboundedSource<>(BigEndianLongCoder.of(), 1L, 2L, 3L); @@ -152,7 +152,7 @@ public void boundedSourceEvaluatorClosesReader() throws Exception { } @Test - public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { + public void evaluatorNoElementsClosesReader() throws Exception { TestUnboundedSource source = new TestUnboundedSource<>(BigEndianLongCoder.of()); TestPipeline p = TestPipeline.create(); @@ -177,15 +177,13 @@ public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { */ @Test public void unboundedSourceWithMultipleSimultaneousEvaluatorsIndependent() throws Exception { - UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); - TransformEvaluator evaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); TransformEvaluator secondEvaluator = factory.forApplication(longs.getProducingTransformInternal(), null, context); - InProcessTransformResult secondResult = secondEvaluator.finishBundle(); + assertThat(secondEvaluator, nullValue()); InProcessTransformResult result = evaluator.finishBundle(); assertThat( @@ -195,9 +193,6 @@ public void unboundedSourceWithMultipleSimultaneousEvaluatorsIndependent() throw containsInAnyOrder( tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), tgw(3L), tgw(0L))); - - assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - assertThat(secondOutput.commit(Instant.now()).getElements(), emptyIterable()); } /** From ebf32558de32e5a4e347b284c7431fcf47ac65c9 Mon Sep 17 00:00:00 2001 From: peihe Date: Tue, 10 May 2016 17:55:06 -0700 Subject: [PATCH 373/751] Re-interrupt current thread when ignoring InterruptedException Re-interrupt current thread when ignoring InterruptedException Backport: apache/incubator-beam#45 --- .../examples/common/DataflowExampleUtils.java | 8 +++----- .../com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 3 +++ .../sdk/io/BoundedReadFromUnboundedSource.java | 7 +++---- .../sdk/runners/BlockingDataflowPipelineRunner.java | 3 +++ .../dataflow/sdk/runners/DataflowPipelineJob.java | 3 +++ .../sdk/transforms/IntraBundleParallelization.java | 1 + .../dataflow/sdk/util/BigQueryTableInserter.java | 3 +++ .../dataflow/sdk/util/BigQueryTableRowIterator.java | 12 +++++++----- .../com/google/cloud/dataflow/sdk/util/GcsUtil.java | 4 ++++ .../transforms/IntraBundleParallelizationTest.java | 1 + 10 files changed, 31 insertions(+), 14 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java index c632132c07..b53f146226 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java @@ -49,6 +49,7 @@ import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import com.google.common.util.concurrent.Uninterruptibles; import java.io.IOException; import java.util.Collection; @@ -107,6 +108,7 @@ public void setup() throws IOException { } } while (BackOffUtils.next(sleeper, backOff)); } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // Ignore InterruptedException } throw new RuntimeException(lastException); @@ -443,11 +445,7 @@ public void run() { System.out.println( "The example pipeline is still running. Verifying the cancellation."); } - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - // Ignore - } + Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); } if (!cancellationVerified) { System.out.println("Failed to verify the cancellation for job: " + job.getJobId()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 2694ddaa40..8175ccaaf1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1736,6 +1736,9 @@ private static void evaluateReadHelper( LOG.info("Number of records read from BigQuery: {}", elems.size()); context.setPCollection(context.getOutput(transform), elems); } catch (IOException | InterruptedException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } throw new RuntimeException(e); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java index 5a1a29a264..84e7d82639 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java @@ -30,6 +30,7 @@ import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.util.concurrent.Uninterruptibles; import org.joda.time.Duration; import org.joda.time.Instant; @@ -38,7 +39,7 @@ import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; - +import java.util.concurrent.TimeUnit; /** * {@link PTransform} that reads a bounded amount of data from an {@link UnboundedSource}, @@ -245,9 +246,7 @@ private boolean advanceWithBackoff() throws IOException { if (reader.advance()) { return true; } - try { - Thread.sleep(nextSleep); - } catch (InterruptedException e) {} + Uninterruptibles.sleepUninterruptibly(nextSleep, TimeUnit.MILLISECONDS); nextSleep = backoff.nextBackOffMillis(); } finalizeCheckpoint(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java index 95e3dfeb91..7b45e5b34e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java @@ -118,6 +118,9 @@ public void run() { BUILTIN_JOB_TIMEOUT_SEC, TimeUnit.SECONDS, new MonitoringUtil.PrintHandler(options.getJobMessageOutput())); } catch (IOException | InterruptedException ex) { + if (ex instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } LOG.debug("Exception caught while retrieving status for job {}", job.getJobId(), ex); throw new DataflowServiceException( job, "Exception caught while retrieving status for job " + job.getJobId(), ex); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java index 0cdef7e8c5..6cf25154e8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java @@ -347,6 +347,9 @@ private boolean nextBackOff(Sleeper sleeper, BackOff backoff) { try { return BackOffUtils.next(sleeper, backoff); } catch (InterruptedException | IOException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } throw new RuntimeException(e); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java index 1ac0975247..45b7c8afaf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java @@ -213,6 +213,7 @@ public void processElement(final ProcessContext c) throws Exception { try { workTickets.acquire(); } catch (InterruptedException e) { + Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted while scheduling work", e); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java index 37096dbc92..0c51fcede0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java @@ -229,6 +229,7 @@ public List call() throws IOException { try { Thread.sleep(backoff.nextBackOffMillis()); } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); throw new IOException( "Interrupted while waiting before retrying insertAll"); } @@ -269,6 +270,7 @@ public List call() throws IOException { } } } catch (InterruptedException e) { + Thread.currentThread().interrupt(); throw new IOException("Interrupted while inserting " + rowsToPublish); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); @@ -278,6 +280,7 @@ public List call() throws IOException { try { Thread.sleep(backoff.nextBackOffMillis()); } catch (InterruptedException e) { + Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting before retrying insert of " + retryRows); } LOG.info("Retrying failed inserts to BigQuery"); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index c2c80f79c3..75b3bb9271 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -45,6 +45,7 @@ import com.google.api.services.bigquery.model.TableSchema; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; +import com.google.common.util.concurrent.Uninterruptibles; import org.joda.time.Duration; import org.slf4j.Logger; @@ -59,6 +60,7 @@ import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; +import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; @@ -412,11 +414,8 @@ private TableReference executeQueryAndWaitForCompletion() throw new IOException("Executing query " + query + " failed: " + error.getMessage()); } } - try { - Thread.sleep(QUERY_COMPLETION_POLL_TIME.getMillis()); - } catch (InterruptedException e) { - e.printStackTrace(); - } + Uninterruptibles.sleepUninterruptibly( + QUERY_COMPLETION_POLL_TIME.getMillis(), TimeUnit.MILLISECONDS); } } @@ -462,6 +461,9 @@ public void close() { deleteDataset(temporaryDatasetId); } } catch (IOException | InterruptedException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } throw new RuntimeException(e); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java index 8fd258f6d2..47adb5967b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java @@ -159,6 +159,9 @@ public List expand(GcsPath gcsPattern) throws IOException { IOException.class); return ImmutableList.of(gcsPattern); } catch (IOException | InterruptedException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } if (e instanceof IOException && errorExtractor.itemNotFound((IOException) e)) { // If the path was not found, return an empty list. return ImmutableList.of(); @@ -343,6 +346,7 @@ public boolean shouldRetry(IOException e) { } throw e; } catch (InterruptedException e) { + Thread.currentThread().interrupt(); throw new IOException( String.format("Error while attempting to verify existence of bucket gs://%s", path.getBucket()), e); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java index 1ed1973819..8a562c3eff 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java @@ -81,6 +81,7 @@ public void processElement(ProcessContext c) { try { sleepMillis(DELAY_MS); } catch (InterruptedException e) { + Thread.currentThread().interrupt(); e.printStackTrace(); throw new RuntimeException("Interrupted"); } From 142708a721fe160a4c60b2b7405ca134c0f81821 Mon Sep 17 00:00:00 2001 From: peihe Date: Tue, 10 May 2016 21:14:00 -0700 Subject: [PATCH 374/751] Backport BigQueryServices refactoring from Beam (#247) --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 53 +++++-- .../dataflow/sdk/util/BigQueryServices.java | 40 +++-- .../sdk/util/BigQueryServicesImpl.java | 150 +++++++++++------- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 82 ++++++---- .../sdk/util/BigQueryServicesImplTest.java | 80 ++++++---- 5 files changed, 259 insertions(+), 146 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 8175ccaaf1..6e13ad64c4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -22,7 +22,9 @@ import com.google.api.client.json.JsonFactory; import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.QueryRequest; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; @@ -53,7 +55,7 @@ import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BigQueryServices; -import com.google.cloud.dataflow.sdk.util.BigQueryServices.LoadService; +import com.google.cloud.dataflow.sdk.util.BigQueryServices.JobService; import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl; import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; @@ -74,7 +76,6 @@ import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; -import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; @@ -1042,6 +1043,7 @@ public PDone apply(PCollection input) { String.format("Failed to resolve BigQuery temp location in %s", tempLocation), e); } + BigQueryServices bqServices = getBigQueryServices(); return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( new BigQuerySink( @@ -1166,6 +1168,10 @@ private static class BigQueryWriteOperation extends FileBasedWriteOperation writerResults, PipelineOptions options } if (!tempFiles.isEmpty()) { load( - bigQuerySink.bqServices.getLoadService(bqOptions), + bigQuerySink.bqServices.getJobService(bqOptions), bigQuerySink.jobIdToken, fromJsonString(bigQuerySink.jsonTable, TableReference.class), tempFiles, @@ -1213,7 +1219,7 @@ public void finalize(Iterable writerResults, PipelineOptions options *

          If a load job failed, it will try another load job with a different job id. */ private void load( - LoadService loadService, + JobService jobService, String jobIdPrefix, TableReference ref, List gcsUris, @@ -1236,8 +1242,9 @@ private void load( LOG.info("Previous load jobs failed, retrying."); } LOG.info("Starting BigQuery load job: {}", jobId); - loadService.startLoadJob(jobId, loadConfig); - BigQueryServices.Status jobStatus = loadService.pollJobStatus(projectId, jobId); + jobService.startLoadJob(jobId, loadConfig); + Status jobStatus = parseStatus( + jobService.pollJob(projectId, jobId, MAX_JOB_STATUS_POLL_RETRIES)); switch (jobStatus) { case SUCCEEDED: return; @@ -1351,11 +1358,7 @@ private static class StreamingWriteFn /** Constructor. */ StreamingWriteFn(TableSchema schema) { - try { - jsonTableSchema = JSON_FACTORY.toString(schema); - } catch (IOException e) { - throw new RuntimeException("Cannot initialize BigQuery streaming writer.", e); - } + jsonTableSchema = toJsonString(schema); } /** Prepares a target BigQuery table. */ @@ -1461,8 +1464,7 @@ public static ShardedKeyCoder of(Coder keyCoder) { public static ShardedKeyCoder of( @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { - Preconditions.checkArgument(components.size() == 1, - "Expecting 1 component, got " + components.size()); + checkArgument(components.size() == 1, "Expecting 1 component, got %s", components.size()); return of(components.get(0)); } @@ -1567,7 +1569,7 @@ private static class TagWithUniqueIdsAndTable TagWithUniqueIdsAndTable(BigQueryOptions options, TableReference table, SerializableFunction tableRefFunction) { - Preconditions.checkArgument(table == null ^ tableRefFunction == null, + checkArgument(table == null ^ tableRefFunction == null, "Exactly one of table or tableRefFunction should be set"); if (table != null) { if (table.getProjectId() == null) { @@ -1672,6 +1674,29 @@ public PDone apply(PCollection input) { } } + /** + * Status of a BigQuery job or request. + */ + enum Status { + SUCCEEDED, + FAILED, + UNKNOWN, + } + + private static Status parseStatus(@Nullable Job job) { + if (job == null) { + return Status.UNKNOWN; + } + JobStatus status = job.getStatus(); + if (status.getErrorResult() != null) { + return Status.FAILED; + } else if (status.getErrors() != null && !status.getErrors().isEmpty()) { + return Status.FAILED; + } else { + return Status.SUCCEEDED; + } + } + private static String toJsonString(Object item) { if (item == null) { return null; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java index 85c39ea84b..a78c60d4b4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -15,7 +15,10 @@ */ package com.google.cloud.dataflow.sdk.util; +import com.google.api.services.bigquery.model.Job; +import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import java.io.IOException; @@ -27,33 +30,38 @@ public interface BigQueryServices extends Serializable { /** - * Status of a BigQuery job or request. + * Returns a real, mock, or fake {@link JobService}. */ - enum Status { - SUCCEEDED, - FAILED, - UNKNOWN, - } - - /** - * Returns a real, mock, or fake {@link LoadService}. - */ - public LoadService getLoadService(BigQueryOptions bqOptions); + public JobService getJobService(BigQueryOptions bqOptions); /** * An interface for the Cloud BigQuery load service. */ - public interface LoadService { + public interface JobService { /** - * Start a BigQuery load job. + * Starts a BigQuery load job. */ - public void startLoadJob(String jobId, JobConfigurationLoad loadConfig) + void startLoadJob(String jobId, JobConfigurationLoad loadConfig) throws InterruptedException, IOException; /** - * Poll the status of a BigQuery load job. + * Start a BigQuery extract job. + */ + void startExtractJob(String jobId, JobConfigurationExtract extractConfig) + throws InterruptedException, IOException; + + /** + * Start a BigQuery extract job. + */ + void startQueryJob(String jobId, JobConfigurationQuery query, boolean dryRun) + throws IOException, InterruptedException; + + /** + * Waits for the job is Done, and returns the job. + * + *

          Returns null if the {@code maxAttempts} retries reached. */ - public Status pollJobStatus(String projectId, String jobId) + Job pollJob(String projectId, String jobId, int maxAttempts) throws InterruptedException, IOException; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index 342095baa7..1bc62cac7b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -22,10 +22,11 @@ import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfiguration; +import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatus; -import com.google.api.services.bigquery.model.TableReference; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; @@ -36,43 +37,41 @@ import java.io.IOException; import java.util.concurrent.TimeUnit; + /** * An implementation of {@link BigQueryServices} that actually communicates with the cloud BigQuery * service. */ public class BigQueryServicesImpl implements BigQueryServices { - // The maximum number of attempts to execute a load job RPC. - private static final int MAX_LOAD_JOB_RPC_ATTEMPTS = 10; + // The maximum number of attempts to execute a BigQuery RPC. + private static final int MAX_RPC_ATTEMPTS = 10; - // The initial backoff for executing a load job RPC. - private static final long INITIAL_LOAD_JOB_RPC_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); - // The maximum number of retries to poll the status of a load job. - // It sets to {@code Integer.MAX_VALUE} to block until the BigQuery load job finishes. - private static final int MAX_LOAD_JOB_POLL_RETRIES = Integer.MAX_VALUE; + // The initial backoff for executing a BigQuery RPC. + private static final long INITIAL_RPC_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); - // The initial backoff for polling the status of a load job. - private static final long INITIAL_LOAD_JOB_POLL_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(60); + // The initial backoff for polling the status of a BigQuery job. + private static final long INITIAL_JOB_STATUS_POLL_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(60); @Override - public LoadService getLoadService(BigQueryOptions options) { - return new LoadServiceImpl(options); + public JobService getJobService(BigQueryOptions options) { + return new JobServiceImpl(options); } @VisibleForTesting - static class LoadServiceImpl implements BigQueryServices.LoadService { - private static final Logger LOG = LoggerFactory.getLogger(LoadServiceImpl.class); + static class JobServiceImpl implements BigQueryServices.JobService { + private static final Logger LOG = LoggerFactory.getLogger(JobServiceImpl.class); private final ApiErrorExtractor errorExtractor; private final Bigquery client; @VisibleForTesting - LoadServiceImpl(Bigquery client) { + JobServiceImpl(Bigquery client) { this.errorExtractor = new ApiErrorExtractor(); this.client = client; } - private LoadServiceImpl(BigQueryOptions options) { + private JobServiceImpl(BigQueryOptions options) { this.errorExtractor = new ApiErrorExtractor(); this.client = Transport.newBigQueryClient(options).build(); } @@ -80,7 +79,7 @@ private LoadServiceImpl(BigQueryOptions options) { /** * {@inheritDoc} * - *

          Retries the RPC for at most {@code MAX_LOAD_JOB_RPC_ATTEMPTS} times until it succeeds. + *

          Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * * @throws IOException if it exceeds max RPC retries. */ @@ -88,47 +87,84 @@ private LoadServiceImpl(BigQueryOptions options) { public void startLoadJob( String jobId, JobConfigurationLoad loadConfig) throws InterruptedException, IOException { - BackOff backoff = new AttemptBoundedExponentialBackOff( - MAX_LOAD_JOB_RPC_ATTEMPTS, INITIAL_LOAD_JOB_RPC_BACKOFF_MILLIS); - startLoadJob(jobId, loadConfig, Sleeper.DEFAULT, backoff); + Job job = new Job(); + JobReference jobRef = new JobReference(); + jobRef.setProjectId(loadConfig.getDestinationTable().getProjectId()); + jobRef.setJobId(jobId); + job.setJobReference(jobRef); + JobConfiguration jobConfig = new JobConfiguration(); + jobConfig.setLoad(loadConfig); + job.setConfiguration(jobConfig); + + startJob(job, errorExtractor, client); } /** * {@inheritDoc} * - *

          Retries the poll request for at most {@code MAX_LOAD_JOB_POLL_RETRIES} times - * until the job is DONE. + *

          Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC retries. */ @Override - public Status pollJobStatus(String projectId, String jobId) throws InterruptedException { - BackOff backoff = new AttemptBoundedExponentialBackOff( - MAX_LOAD_JOB_POLL_RETRIES, INITIAL_LOAD_JOB_POLL_BACKOFF_MILLIS); - return pollJobStatus(projectId, jobId, Sleeper.DEFAULT, backoff); - } - - @VisibleForTesting - void startLoadJob( - String jobId, - JobConfigurationLoad loadConfig, - Sleeper sleeper, - BackOff backoff) + public void startExtractJob(String jobId, JobConfigurationExtract extractConfig) throws InterruptedException, IOException { - TableReference ref = loadConfig.getDestinationTable(); - String projectId = ref.getProjectId(); + Job job = new Job(); + JobReference jobRef = new JobReference(); + jobRef.setProjectId(extractConfig.getSourceTable().getProjectId()); + jobRef.setJobId(jobId); + job.setJobReference(jobRef); + JobConfiguration jobConfig = new JobConfiguration(); + jobConfig.setExtract(extractConfig); + job.setConfiguration(jobConfig); + + startJob(job, errorExtractor, client); + } + /** + * {@inheritDoc} + * + *

          Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC retries. + */ + @Override + public void startQueryJob(String jobId, JobConfigurationQuery queryConfig, boolean dryRun) + throws IOException, InterruptedException { Job job = new Job(); JobReference jobRef = new JobReference(); - jobRef.setProjectId(projectId); + jobRef.setProjectId(queryConfig.getDestinationTable().getProjectId()); jobRef.setJobId(jobId); job.setJobReference(jobRef); - JobConfiguration config = new JobConfiguration(); - config.setLoad(loadConfig); - job.setConfiguration(config); + JobConfiguration jobConfig = new JobConfiguration(); + jobConfig.setQuery(queryConfig); + jobConfig.setDryRun(dryRun); + job.setConfiguration(jobConfig); + startJob(job, errorExtractor, client); + } + + private static void startJob(Job job, + ApiErrorExtractor errorExtractor, + Bigquery client) throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + startJob(job, errorExtractor, client, Sleeper.DEFAULT, backoff); + } + + @VisibleForTesting + static void startJob( + Job job, + ApiErrorExtractor errorExtractor, + Bigquery client, + Sleeper sleeper, + BackOff backoff) + throws InterruptedException, IOException { + JobReference jobRef = job.getJobReference(); Exception lastException = null; do { try { - client.jobs().insert(projectId, job).execute(); + client.jobs().insert(jobRef.getProjectId(), job).execute(); return; // SUCCEEDED } catch (GoogleJsonResponseException e) { if (errorExtractor.itemAlreadyExists(e)) { @@ -146,27 +182,30 @@ void startLoadJob( throw new IOException( String.format( "Unable to insert job: %s, aborting after %d retries.", - jobId, MAX_LOAD_JOB_RPC_ATTEMPTS), + jobRef.getJobId(), MAX_RPC_ATTEMPTS), lastException); } + @Override + public Job pollJob(String projectId, String jobId, int maxAttempts) + throws InterruptedException { + BackOff backoff = new AttemptBoundedExponentialBackOff( + maxAttempts, INITIAL_JOB_STATUS_POLL_BACKOFF_MILLIS); + return pollJob(projectId, jobId, Sleeper.DEFAULT, backoff); + } + @VisibleForTesting - Status pollJobStatus( + Job pollJob( String projectId, String jobId, Sleeper sleeper, BackOff backoff) throws InterruptedException { do { try { - JobStatus status = client.jobs().get(projectId, jobId).execute().getStatus(); + Job job = client.jobs().get(projectId, jobId).execute(); + JobStatus status = job.getStatus(); if (status != null && status.getState() != null && status.getState().equals("DONE")) { - if (status.getErrorResult() != null) { - return Status.FAILED; - } else if (status.getErrors() != null && !status.getErrors().isEmpty()) { - return Status.FAILED; - } else { - return Status.SUCCEEDED; - } + return job; } // The job is not DONE, wait longer and retry. } catch (IOException e) { @@ -174,16 +213,16 @@ Status pollJobStatus( LOG.warn("Ignore the error and retry polling job status.", e); } } while (nextBackOff(sleeper, backoff)); - LOG.warn("Unable to poll job status: {}, aborting after {} retries.", - jobId, MAX_LOAD_JOB_POLL_RETRIES); - return Status.UNKNOWN; + LOG.warn("Unable to poll job status: {}, aborting after reached max retries.", jobId); + return null; } /** * Identical to {@link BackOffUtils#next} but without checked IOException. * @throws InterruptedException */ - private boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { + private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) + throws InterruptedException { try { return BackOffUtils.next(sleeper, backoff); } catch (IOException e) { @@ -192,3 +231,4 @@ private boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws Interrupted } } } + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 79561cd917..4c754d50d7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -19,12 +19,17 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; import com.google.api.client.util.Data; +import com.google.api.services.bigquery.model.ErrorProto; +import com.google.api.services.bigquery.model.Job; +import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; @@ -32,6 +37,7 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Status; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; @@ -44,9 +50,9 @@ import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BigQueryServices; -import com.google.cloud.dataflow.sdk.util.BigQueryServices.Status; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import org.hamcrest.Matchers; import org.junit.Assert; @@ -64,6 +70,7 @@ import java.io.File; import java.io.FileFilter; import java.io.IOException; +import java.util.Map; /** * Tests for BigQueryIO. @@ -71,23 +78,28 @@ @RunWith(JUnit4.class) public class BigQueryIOTest { + // Status.UNKNOWN maps to null + private static final Map JOB_STATUS_MAP = ImmutableMap.of( + Status.SUCCEEDED, new Job().setStatus(new JobStatus()), + Status.FAILED, new Job().setStatus(new JobStatus().setErrorResult(new ErrorProto()))); + private static class FakeBigQueryServices implements BigQueryServices { - private Object[] startLoadJobReturns; + private Object[] startJobReturns; private Object[] pollJobStatusReturns; /** - * Sets the return values for the mock {@link LoadService#startLoadJob}. + * Sets the return values for the mock {@link JobService#startLoadJob}. * *

          Throws if the {@link Object} is a {@link Exception}, returns otherwise. */ private FakeBigQueryServices startLoadJobReturns(Object... startLoadJobReturns) { - this.startLoadJobReturns = startLoadJobReturns; + this.startJobReturns = startLoadJobReturns; return this; } /** - * Sets the return values for the mock {@link LoadService#pollJobStatus}. + * Sets the return values for the mock {@link JobService#pollJobStatus}. * *

          Throws if the {@link Object} is a {@link Exception}, returns otherwise. */ @@ -97,19 +109,19 @@ private FakeBigQueryServices pollJobStatusReturns(Object... pollJobStatusReturns } @Override - public LoadService getLoadService(BigQueryOptions bqOptions) { - return new FakeLoadService(startLoadJobReturns, pollJobStatusReturns); + public JobService getJobService(BigQueryOptions bqOptions) { + return new FakeLoadService(startJobReturns, pollJobStatusReturns); } - private static class FakeLoadService implements BigQueryServices.LoadService { + private static class FakeLoadService implements BigQueryServices.JobService { - private Object[] startLoadJobReturns; + private Object[] startJobReturns; private Object[] pollJobStatusReturns; private int startLoadJobCallsCount; private int pollJobStatusCallsCount; public FakeLoadService(Object[] startLoadJobReturns, Object[] pollJobStatusReturns) { - this.startLoadJobReturns = startLoadJobReturns; + this.startJobReturns = startLoadJobReturns; this.pollJobStatusReturns = pollJobStatusReturns; this.startLoadJobCallsCount = 0; this.pollJobStatusCallsCount = 0; @@ -118,35 +130,52 @@ public FakeLoadService(Object[] startLoadJobReturns, Object[] pollJobStatusRetur @Override public void startLoadJob(String jobId, JobConfigurationLoad loadConfig) throws InterruptedException, IOException { - if (startLoadJobCallsCount < startLoadJobReturns.length) { - Object ret = startLoadJobReturns[startLoadJobCallsCount++]; - if (ret instanceof IOException) { - throw (IOException) ret; + startJob(); + } + + @Override + public void startExtractJob(String jobId, JobConfigurationExtract extractConfig) + throws InterruptedException, IOException { + startJob(); + } + + @Override + public void startQueryJob(String jobId, JobConfigurationQuery query, boolean dryRun) + throws IOException, InterruptedException { + startJob(); + } + + @Override + public Job pollJob(String projectId, String jobId, int maxAttemps) + throws InterruptedException { + if (pollJobStatusCallsCount < pollJobStatusReturns.length) { + Object ret = pollJobStatusReturns[pollJobStatusCallsCount++]; + if (ret instanceof Status) { + return JOB_STATUS_MAP.get(ret); } else if (ret instanceof InterruptedException) { throw (InterruptedException) ret; } else { - return; + throw new RuntimeException("Unexpected return type: " + ret.getClass()); } } else { throw new RuntimeException( - "Exceeded expected number of calls: " + startLoadJobReturns.length); + "Exceeded expected number of calls: " + pollJobStatusReturns.length); } } - @Override - public Status pollJobStatus(String projectId, String jobId) throws InterruptedException { - if (pollJobStatusCallsCount < pollJobStatusReturns.length) { - Object ret = pollJobStatusReturns[pollJobStatusCallsCount++]; - if (ret instanceof Status) { - return (Status) ret; + private void startJob() throws IOException, InterruptedException { + if (startLoadJobCallsCount < startJobReturns.length) { + Object ret = startJobReturns[startLoadJobCallsCount++]; + if (ret instanceof IOException) { + throw (IOException) ret; } else if (ret instanceof InterruptedException) { throw (InterruptedException) ret; } else { - throw new RuntimeException("Unexpected return type: " + ret.getClass()); + return; } } else { throw new RuntimeException( - "Exceeded expected number of calls: " + pollJobStatusReturns.length); + "Exceeded expected number of calls: " + startJobReturns.length); } } } @@ -158,7 +187,7 @@ public Status pollJobStatus(String projectId, String jobId) throws InterruptedEx @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Mock - public BigQueryServices.LoadService mockBqLoadService; + public BigQueryServices.JobService mockBqLoadService; private BigQueryOptions bqOptions; @@ -209,7 +238,6 @@ private void checkWriteObjectWithValidate( assertEquals(validate, bound.validate); } - @Before public void setUp() { bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java index 08e6686646..e9ca0ebadd 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java @@ -35,10 +35,13 @@ import com.google.api.services.bigquery.model.ErrorProto; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.TableReference; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; +import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl.JobServiceImpl; +import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.collect.ImmutableList; import org.junit.Before; @@ -88,11 +91,16 @@ public LowLevelHttpResponse execute() throws IOException { } /** - * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#startLoadJob} succeeds. + * Tests that {@link BigQueryServicesImpl.JobServiceImpl#startLoadJob} succeeds. */ @Test public void testStartLoadJobSucceeds() throws IOException, InterruptedException { Job testJob = new Job(); + JobReference jobRef = new JobReference(); + jobRef.setJobId("jobId"); + jobRef.setProjectId("projectId"); + testJob.setJobReference(jobRef); + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); when(response.getStatusCode()).thenReturn(200); when(response.getContent()).thenReturn(toStream(testJob)); @@ -105,20 +113,24 @@ public void testStartLoadJobSucceeds() throws IOException, InterruptedException Sleeper sleeper = new FastNanoClockAndSleeper(); BackOff backoff = new AttemptBoundedExponentialBackOff( 5 /* attempts */, 1000 /* initialIntervalMillis */); - BigQueryServicesImpl.LoadServiceImpl loadService = - new BigQueryServicesImpl.LoadServiceImpl(bigquery); - loadService.startLoadJob("jobId", loadConfig, sleeper, backoff); + JobServiceImpl.startJob(testJob, new ApiErrorExtractor(), bigquery, sleeper, backoff); verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); verify(response, times(1)).getContentType(); } /** - * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#startLoadJob} succeeds + * Tests that {@link BigQueryServicesImpl.JobServiceImpl#startLoadJob} succeeds * with an already exist job. */ @Test public void testStartLoadJobSucceedsAlreadyExists() throws IOException, InterruptedException { + Job testJob = new Job(); + JobReference jobRef = new JobReference(); + jobRef.setJobId("jobId"); + jobRef.setProjectId("projectId"); + testJob.setJobReference(jobRef); + when(response.getStatusCode()).thenReturn(409); // 409 means already exists TableReference ref = new TableReference(); @@ -129,9 +141,7 @@ public void testStartLoadJobSucceedsAlreadyExists() throws IOException, Interrup Sleeper sleeper = new FastNanoClockAndSleeper(); BackOff backoff = new AttemptBoundedExponentialBackOff( 5 /* attempts */, 1000 /* initialIntervalMillis */); - BigQueryServicesImpl.LoadServiceImpl loadService = - new BigQueryServicesImpl.LoadServiceImpl(bigquery); - loadService.startLoadJob("jobId", loadConfig, sleeper, backoff); + JobServiceImpl.startJob(testJob, new ApiErrorExtractor(), bigquery, sleeper, backoff); verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); @@ -139,11 +149,15 @@ public void testStartLoadJobSucceedsAlreadyExists() throws IOException, Interrup } /** - * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#startLoadJob} succeeds with a retry. + * Tests that {@link BigQueryServicesImpl.JobServiceImpl#startLoadJob} succeeds with a retry. */ @Test public void testStartLoadJobRetry() throws IOException, InterruptedException { Job testJob = new Job(); + JobReference jobRef = new JobReference(); + jobRef.setJobId("jobId"); + jobRef.setProjectId("projectId"); + testJob.setJobReference(jobRef); // First response is 403 rate limited, second response has valid payload. when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); @@ -160,19 +174,18 @@ public void testStartLoadJobRetry() throws IOException, InterruptedException { Sleeper sleeper = new FastNanoClockAndSleeper(); BackOff backoff = new AttemptBoundedExponentialBackOff( 5 /* attempts */, 1000 /* initialIntervalMillis */); - BigQueryServicesImpl.LoadServiceImpl loadService = - new BigQueryServicesImpl.LoadServiceImpl(bigquery); - loadService.startLoadJob("jobId", loadConfig, sleeper, backoff); + JobServiceImpl.startJob(testJob, new ApiErrorExtractor(), bigquery, sleeper, backoff); + verify(response, times(2)).getStatusCode(); verify(response, times(2)).getContent(); verify(response, times(2)).getContentType(); } /** - * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#pollJobStatus} succeeds. + * Tests that {@link BigQueryServicesImpl.JobServiceImpl#pollJob} succeeds. */ @Test - public void testPollJobStatusSucceeds() throws IOException, InterruptedException { + public void testPollJobSucceeds() throws IOException, InterruptedException { Job testJob = new Job(); testJob.setStatus(new JobStatus().setState("DONE")); @@ -180,22 +193,22 @@ public void testPollJobStatusSucceeds() throws IOException, InterruptedException when(response.getStatusCode()).thenReturn(200); when(response.getContent()).thenReturn(toStream(testJob)); - BigQueryServicesImpl.LoadServiceImpl loadService = - new BigQueryServicesImpl.LoadServiceImpl(bigquery); - BigQueryServices.Status status = - loadService.pollJobStatus("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + BigQueryServicesImpl.JobServiceImpl jobService = + new BigQueryServicesImpl.JobServiceImpl(bigquery); + Job job = + jobService.pollJob("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); - assertEquals(BigQueryServices.Status.SUCCEEDED, status); + assertEquals(testJob, job); verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); verify(response, times(1)).getContentType(); } /** - * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#pollJobStatus} fails. + * Tests that {@link BigQueryServicesImpl.JobServiceImpl#pollJob} fails. */ @Test - public void testPollJobStatusFailed() throws IOException, InterruptedException { + public void testPollJobFailed() throws IOException, InterruptedException { Job testJob = new Job(); testJob.setStatus(new JobStatus().setState("DONE").setErrorResult(new ErrorProto())); @@ -203,22 +216,22 @@ public void testPollJobStatusFailed() throws IOException, InterruptedException { when(response.getStatusCode()).thenReturn(200); when(response.getContent()).thenReturn(toStream(testJob)); - BigQueryServicesImpl.LoadServiceImpl loadService = - new BigQueryServicesImpl.LoadServiceImpl(bigquery); - BigQueryServices.Status status = - loadService.pollJobStatus("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + BigQueryServicesImpl.JobServiceImpl jobService = + new BigQueryServicesImpl.JobServiceImpl(bigquery); + Job job = + jobService.pollJob("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); - assertEquals(BigQueryServices.Status.FAILED, status); + assertEquals(testJob, job); verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); verify(response, times(1)).getContentType(); } /** - * Tests that {@link BigQueryServicesImpl.LoadServiceImpl#pollJobStatus} returns UNKNOWN. + * Tests that {@link BigQueryServicesImpl.JobServiceImpl#pollJob} returns UNKNOWN. */ @Test - public void testPollJobStatusUnknown() throws IOException, InterruptedException { + public void testPollJobUnknown() throws IOException, InterruptedException { Job testJob = new Job(); testJob.setStatus(new JobStatus()); @@ -226,12 +239,12 @@ public void testPollJobStatusUnknown() throws IOException, InterruptedException when(response.getStatusCode()).thenReturn(200); when(response.getContent()).thenReturn(toStream(testJob)); - BigQueryServicesImpl.LoadServiceImpl loadService = - new BigQueryServicesImpl.LoadServiceImpl(bigquery); - BigQueryServices.Status status = - loadService.pollJobStatus("projectId", "jobId", Sleeper.DEFAULT, BackOff.STOP_BACKOFF); + BigQueryServicesImpl.JobServiceImpl jobService = + new BigQueryServicesImpl.JobServiceImpl(bigquery); + Job job = + jobService.pollJob("projectId", "jobId", Sleeper.DEFAULT, BackOff.STOP_BACKOFF); - assertEquals(BigQueryServices.Status.UNKNOWN, status); + assertEquals(null, job); verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); verify(response, times(1)).getContentType(); @@ -257,4 +270,3 @@ private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, return container; } } - From 5ac9eb2f87ebd865a2be3d2597d5cae1a402c7be Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Wed, 11 May 2016 10:35:20 -0700 Subject: [PATCH 375/751] Backport Beam incubator PR #317 --- .../sdk/runners/DataflowPipelineRunner.java | 28 ++++++++++++- .../runners/DataflowPipelineRunnerTest.java | 39 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 3a5ea871c3..e691fdac0f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -850,14 +850,36 @@ static class IsmRecordForSingularValuePerWindowDoFn extends DoFn>>>, IsmRecord>> { + private final Coder windowCoder; + IsmRecordForSingularValuePerWindowDoFn(Coder windowCoder) { + this.windowCoder = windowCoder; + } + @Override public void processElement(ProcessContext c) throws Exception { + Optional previousWindowStructuralValue = Optional.absent(); + T previousValue = null; + Iterator>> iterator = c.element().getValue().iterator(); while (iterator.hasNext()) { KV> next = iterator.next(); + Object currentWindowStructuralValue = windowCoder.structuralValue(next.getKey()); + + // Verify that the user isn't trying to have more than one element per window as + // a singleton. + checkState(!previousWindowStructuralValue.isPresent() + || !previousWindowStructuralValue.get().equals(currentWindowStructuralValue), + "Multiple values [%s, %s] found for singleton within window [%s].", + previousValue, + next.getValue().getValue(), + next.getKey()); + c.output( IsmRecord.of( ImmutableList.of(next.getKey()), next.getValue())); + + previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); + previousValue = next.getValue().getValue(); } } } @@ -875,10 +897,14 @@ public BatchViewAsSingleton(DataflowPipelineRunner runner, View.AsSingleton t @Override public PCollectionView apply(PCollection input) { + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) + input.getWindowingStrategy().getWindowFn().windowCoder(); + return BatchViewAsSingleton.applyForSingleton( runner, input, - new IsmRecordForSingularValuePerWindowDoFn(), + new IsmRecordForSingularValuePerWindowDoFn(windowCoder), transform.hasDefaultValue(), transform.defaultValue(), input.getCoder()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 584d48e407..8a10db93ca 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -58,6 +58,7 @@ import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsList; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMap; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMultimap; +import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsSingleton; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.TransformedMap; import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; @@ -947,6 +948,44 @@ public void testTextIOSinkUnsupportedInStreaming() throws Exception { testUnsupportedSink(TextIO.Write.to("foo"), "TextIO.Write", true); } + @Test + public void testBatchViewAsSingletonToIsmRecord() throws Exception { + DoFnTester>>>, + IsmRecord>> doFnTester = + DoFnTester.of( + new BatchViewAsSingleton.IsmRecordForSingularValuePerWindowDoFn + (GlobalWindow.Coder.INSTANCE)); + + assertThat( + doFnTester.processBatch( + ImmutableList.of(KV.>>>of( + 0, ImmutableList.of(KV.of(GlobalWindow.INSTANCE, valueInGlobalWindow("a")))))), + contains(IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE), valueInGlobalWindow("a")))); + } + + @Test + public void testBatchViewAsSingletonToIsmRecordWithMultipleValuesThrowsException() + throws Exception { + DoFnTester>>>, + IsmRecord>> doFnTester = + DoFnTester.of( + new BatchViewAsSingleton.IsmRecordForSingularValuePerWindowDoFn + (GlobalWindow.Coder.INSTANCE)); + + try { + doFnTester.processBatch( + ImmutableList.of(KV.>>>of( + 0, ImmutableList.of( + KV.of(GlobalWindow.INSTANCE, valueInGlobalWindow("a")), + KV.of(GlobalWindow.INSTANCE, valueInGlobalWindow("b")))))); + fail("Expected UserCodeException"); + } catch (UserCodeException e) { + assertTrue(e.getCause() instanceof IllegalStateException); + IllegalStateException rootCause = (IllegalStateException) e.getCause(); + assertThat(rootCause.getMessage(), containsString("found for singleton within window")); + } + } + @Test public void testBatchViewAsListToIsmRecordForGlobalWindow() throws Exception { DoFnTester>> doFnTester = From 6dc288bfe1ce2c3313f24b5295cbcd41bfa69474 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 29 Mar 2016 10:06:02 -0700 Subject: [PATCH 376/751] Add ShardControlledWrite override This is used for TextIO and AvroIO, which provide withNumOutputShards methods to control the number of output files. Apply this override in the InProcessPipelineRunner. --- .../inprocess/AvroIOShardedWriteFactory.java | 74 ++++++++++++ .../inprocess/InProcessPipelineRunner.java | 4 + .../inprocess/ShardControlledWrite.java | 79 +++++++++++++ .../inprocess/TextIOShardedWriteFactory.java | 76 ++++++++++++ .../cloud/dataflow/sdk/io/AvroIOTest.java | 29 +++-- .../cloud/dataflow/sdk/io/TextIOTest.java | 33 +++--- .../AvroIOShardedWriteFactoryTest.java | 110 ++++++++++++++++++ .../TextIOShardedWriteFactoryTest.java | 110 ++++++++++++++++++ 8 files changed, 487 insertions(+), 28 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java new file mode 100644 index 0000000000..de7ab1c046 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.io.AvroIO; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; + +class AvroIOShardedWriteFactory implements PTransformOverrideFactory { + @Override + public PTransform override( + PTransform transform) { + if (transform instanceof AvroIO.Write.Bound) { + @SuppressWarnings("unchecked") + AvroIO.Write.Bound originalWrite = (AvroIO.Write.Bound) transform; + if (originalWrite.getNumShards() > 1 + || (originalWrite.getNumShards() == 1 + && !"".equals(originalWrite.getShardNameTemplate()))) { + @SuppressWarnings("unchecked") + PTransform override = + (PTransform) new AvroIOShardedWrite(originalWrite); + return override; + } + } + return transform; + } + + private class AvroIOShardedWrite extends ShardControlledWrite { + private final AvroIO.Write.Bound initial; + + private AvroIOShardedWrite(AvroIO.Write.Bound initial) { + this.initial = initial; + } + + @Override + int getNumShards() { + return initial.getNumShards(); + } + + @Override + PTransform, PDone> getSingleShardTransform(int shardNum) { + String shardName = + IOChannelUtils.constructName( + initial.getFilenamePrefix(), + initial.getShardNameTemplate(), + initial.getFilenameSuffix(), + shardNum, + getNumShards()); + return initial.withoutSharding().to(shardName).withSuffix(""); + } + + @Override + protected PTransform, PDone> delegate() { + return initial; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 297e9e8ed9..5a97167325 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -19,6 +19,8 @@ import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; import com.google.cloud.dataflow.sdk.PipelineResult; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.io.AvroIO; +import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.AggregatorPipelineExtractor; import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; @@ -80,6 +82,8 @@ public class InProcessPipelineRunner .put(Create.Values.class, new InProcessCreateOverrideFactory()) .put(GroupByKey.class, new InProcessGroupByKeyOverrideFactory()) .put(CreatePCollectionView.class, new InProcessViewOverrideFactory()) + .put(AvroIO.Write.Bound.class, new AvroIOShardedWriteFactory()) + .put(TextIO.Write.Bound.class, new TextIOShardedWriteFactory()) .build(); /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java new file mode 100644 index 0000000000..47edb51f17 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.Partition; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.cloud.dataflow.sdk.values.PDone; + +import java.util.concurrent.ThreadLocalRandom; + +/** + * A write that explicitly controls its number of output shards. + */ +abstract class ShardControlledWrite + extends ForwardingPTransform, PDone> { + @Override + public PDone apply(PCollection input) { + int numShards = getNumShards(); + checkArgument( + numShards >= 1, + "%s should only be applied if the output has a controlled number of shards (> 1); got %s", + getClass().getSimpleName(), + getNumShards()); + PCollectionList shards = + input.apply( + "PartitionInto" + numShards + "Shards", + Partition.of(getNumShards(), new RandomSeedPartitionFn())); + for (int i = 0; i < shards.size(); i++) { + PCollection shard = shards.get(i); + PTransform, PDone> writeShard = getSingleShardTransform(i); + shard.apply(String.format("%s(Shard:%s)", writeShard.getName(), i), writeShard); + } + return PDone.in(input.getPipeline()); + } + + /** + * Returns the number of shards this {@link PTransform} should write to. + */ + abstract int getNumShards(); + + /** + * Returns a {@link PTransform} that performs a write to the shard with the specified shard + * number. + * + *

          This method will be called n times, where n is the value of {@link #getNumShards()}, for + * shard numbers {@code [0...n)}. + */ + abstract PTransform, PDone> getSingleShardTransform(int shardNum); + + private static class RandomSeedPartitionFn implements Partition.PartitionFn { + int nextPartition = -1; + @Override + public int partitionFor(T elem, int numPartitions) { + if (nextPartition < 0) { + nextPartition = ThreadLocalRandom.current().nextInt(numPartitions); + } + nextPartition++; + nextPartition %= numPartitions; + return nextPartition; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java new file mode 100644 index 0000000000..b4e0f9b04c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.io.TextIO.Write.Bound; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; + +class TextIOShardedWriteFactory implements PTransformOverrideFactory { + + @Override + public PTransform override( + PTransform transform) { + if (transform instanceof TextIO.Write.Bound) { + @SuppressWarnings("unchecked") + TextIO.Write.Bound originalWrite = (TextIO.Write.Bound) transform; + if (originalWrite.getNumShards() > 1 + || (originalWrite.getNumShards() == 1 + && !"".equals(originalWrite.getShardNameTemplate()))) { + @SuppressWarnings("unchecked") + PTransform override = + (PTransform) new TextIOShardedWrite(originalWrite); + return override; + } + } + return transform; + } + + private static class TextIOShardedWrite extends ShardControlledWrite { + private final TextIO.Write.Bound initial; + + private TextIOShardedWrite(Bound initial) { + this.initial = initial; + } + + @Override + int getNumShards() { + return initial.getNumShards(); + } + + @Override + PTransform, PDone> getSingleShardTransform(int shardNum) { + String shardName = + IOChannelUtils.constructName( + initial.getFilenamePrefix(), + initial.getShardTemplate(), + initial.getFilenameSuffix(), + shardNum, + getNumShards()); + return TextIO.Write.withCoder(initial.getCoder()).to(shardName).withoutSharding(); + } + + @Override + protected PTransform, PDone> delegate() { + return initial; + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java index 2fa3eafacf..509e464436 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java @@ -17,7 +17,6 @@ package com.google.cloud.dataflow.sdk.io; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -215,28 +214,28 @@ private void runTestWrite(String[] expectedElements, int numShards) throws IOExc p.apply(Create.of(expectedElements)).apply(write); p.run(); + String shardNameTemplate = write.getShardNameTemplate(); + + assertTestOutputs(expectedElements, numShards, outputFilePrefix, shardNameTemplate); + } + + public static void assertTestOutputs( + String[] expectedElements, int numShards, String outputFilePrefix, String shardNameTemplate) + throws IOException { // Validate that the data written matches the expected elements in the expected order List expectedFiles = new ArrayList<>(); - if (numShards == 1) { - expectedFiles.add(baseOutputFile); - } else { - for (int i = 0; i < numShards; i++) { - expectedFiles.add( - new File( - IOChannelUtils.constructName( - outputFilePrefix, - write.getShardNameTemplate(), - "" /* no suffix */, - i, - numShards))); - } + for (int i = 0; i < numShards; i++) { + expectedFiles.add( + new File( + IOChannelUtils.constructName( + outputFilePrefix, shardNameTemplate, "" /* no suffix */, i, numShards))); } List actualElements = new ArrayList<>(); for (File outputFile : expectedFiles) { assertTrue("Expected output file " + outputFile.getName(), outputFile.exists()); try (DataFileReader reader = - new DataFileReader<>(outputFile, AvroCoder.of(String.class).createDatumReader())) { + new DataFileReader<>(outputFile, AvroCoder.of(String.class).createDatumReader())) { Iterators.addAll(actualElements, reader); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 4f76ac0330..d6ed939ba7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -220,7 +220,8 @@ void runTestWrite(T[] elems, Coder coder) throws Exception { } void runTestWrite(T[] elems, Coder coder, int numShards) throws Exception { - String filename = tmpFolder.newFile("file.txt").getPath(); + String outputName = "file.txt"; + String baseFilename = tmpFolder.newFile(outputName).getPath(); Pipeline p = TestPipeline.create(); @@ -228,11 +229,11 @@ void runTestWrite(T[] elems, Coder coder, int numShards) throws Exception TextIO.Write.Bound write; if (coder.equals(StringUtf8Coder.of())) { - TextIO.Write.Bound writeStrings = TextIO.Write.to(filename); + TextIO.Write.Bound writeStrings = TextIO.Write.to(baseFilename); // T==String write = (TextIO.Write.Bound) writeStrings; } else { - write = TextIO.Write.to(filename).withCoder(coder); + write = TextIO.Write.to(baseFilename).withCoder(coder); } if (numShards == 1) { write = write.withoutSharding(); @@ -244,17 +245,23 @@ void runTestWrite(T[] elems, Coder coder, int numShards) throws Exception p.run(); + assertOutputFiles(elems, coder, numShards, tmpFolder, outputName, write.getShardNameTemplate()); + } + + public static void assertOutputFiles( + T[] elems, + Coder coder, + int numShards, + TemporaryFolder rootLocation, + String outputName, + String shardNameTemplate) + throws Exception { List expectedFiles = new ArrayList<>(); - if (numShards == 1) { - expectedFiles.add(new File(filename)); - } else { - for (int i = 0; i < numShards; i++) { - expectedFiles.add( - new File( - tmpFolder.getRoot(), - IOChannelUtils.constructName( - "file.txt", ShardNameTemplate.INDEX_OF_MAX, "", i, numShards))); - } + for (int i = 0; i < numShards; i++) { + expectedFiles.add( + new File( + rootLocation.getRoot(), + IOChannelUtils.constructName(outputName, shardNameTemplate, "", i, numShards))); } List actual = new ArrayList<>(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java new file mode 100644 index 0000000000..0caaff10f7 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.theInstance; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.io.AvroIO; +import com.google.cloud.dataflow.sdk.io.AvroIOTest; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.File; + +/** + * Tests for {@link AvroIOShardedWriteFactory}. + */ +@RunWith(JUnit4.class) +public class AvroIOShardedWriteFactoryTest { + + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + private AvroIOShardedWriteFactory factory; + + @Before + public void setup() { + factory = new AvroIOShardedWriteFactory(); + } + + @Test + public void originalWithoutShardingReturnsOriginal() throws Exception { + File file = tmp.newFile("foo"); + PTransform, PDone> original = + AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()).withoutSharding(); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, theInstance(original)); + } + + @Test + public void originalShardingNotSpecifiedReturnsOriginal() throws Exception { + File file = tmp.newFile("foo"); + PTransform, PDone> original = + AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, theInstance(original)); + } + + @Test + public void originalShardedToOneReturnsExplicitlySharded() throws Exception { + File file = tmp.newFile("foo"); + AvroIO.Write.Bound original = + AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()).withNumShards(1); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, not(Matchers., PDone>>equalTo(original))); + + TestPipeline p = TestPipeline.create(); + String[] elems = new String[] {"foo", "bar", "baz"}; + p.apply(Create.of(elems)).apply(overridden); + + file.delete(); + + p.run(); + AvroIOTest.assertTestOutputs(elems, 1, file.getAbsolutePath(), original.getShardNameTemplate()); + } + + @Test + public void originalShardedToManyReturnsExplicitlySharded() throws Exception { + File file = tmp.newFile("foo"); + AvroIO.Write.Bound original = + AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()).withNumShards(3); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, not(Matchers., PDone>>equalTo(original))); + + TestPipeline p = TestPipeline.create(); + String[] elems = new String[] {"foo", "bar", "baz", "spam", "ham", "eggs"}; + p.apply(Create.of(elems)).apply(overridden); + + file.delete(); + p.run(); + AvroIOTest.assertTestOutputs(elems, 3, file.getAbsolutePath(), original.getShardNameTemplate()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java new file mode 100644 index 0000000000..f0d67ab95b --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.theInstance; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.io.TextIOTest; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.File; + +/** + * Tests for {@link TextIOShardedWriteFactory}. + */ +@RunWith(JUnit4.class) +public class TextIOShardedWriteFactoryTest { + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + private TextIOShardedWriteFactory factory; + + @Before + public void setup() { + factory = new TextIOShardedWriteFactory(); + } + + @Test + public void originalWithoutShardingReturnsOriginal() throws Exception { + File file = tmp.newFile("foo"); + PTransform, PDone> original = + TextIO.Write.to(file.getAbsolutePath()).withoutSharding(); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, theInstance(original)); + } + + @Test + public void originalShardingNotSpecifiedReturnsOriginal() throws Exception { + File file = tmp.newFile("foo"); + PTransform, PDone> original = TextIO.Write.to(file.getAbsolutePath()); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, theInstance(original)); + } + + @Test + public void originalShardedToOneReturnsExplicitlySharded() throws Exception { + File file = tmp.newFile("foo"); + TextIO.Write.Bound original = + TextIO.Write.to(file.getAbsolutePath()).withNumShards(1); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, not(Matchers., PDone>>equalTo(original))); + + TestPipeline p = TestPipeline.create(); + String[] elems = new String[] {"foo", "bar", "baz"}; + p.apply(Create.of(elems)).apply(overridden); + + file.delete(); + + p.run(); + TextIOTest.assertOutputFiles( + elems, StringUtf8Coder.of(), 1, tmp, "foo", original.getShardNameTemplate()); + } + + @Test + public void originalShardedToManyReturnsExplicitlySharded() throws Exception { + File file = tmp.newFile("foo"); + TextIO.Write.Bound original = TextIO.Write.to(file.getAbsolutePath()).withNumShards(3); + PTransform, PDone> overridden = factory.override(original); + + assertThat(overridden, not(Matchers., PDone>>equalTo(original))); + + TestPipeline p = TestPipeline.create(); + String[] elems = new String[] {"foo", "bar", "baz", "spam", "ham", "eggs"}; + p.apply(Create.of(elems)).apply(overridden); + + file.delete(); + p.run(); + TextIOTest.assertOutputFiles( + elems, StringUtf8Coder.of(), 3, tmp, "foo", original.getShardNameTemplate()); + } +} From 1351c99362920da046342e0c683a433e536e8eea Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Thu, 7 Apr 2016 17:34:19 -0700 Subject: [PATCH 377/751] Correctly pass the transform in WindowEvaluatorFactory Fixes a NullPointerException when constructing the transform result. --- .../runners/inprocess/WindowEvaluatorFactory.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java index ecf02a1739..17741abf95 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java @@ -59,23 +59,24 @@ private TransformEvaluator createTransformEvaluator( if (fn == null) { return PassthroughTransformEvaluator.create(transform, outputBundle); } - return new WindowIntoEvaluator<>(fn, evaluationContext, outputBundle); + return new WindowIntoEvaluator<>(transform, fn, outputBundle); } private static class WindowIntoEvaluator implements TransformEvaluator { + private final AppliedPTransform, PCollection, Window.Bound> + transform; private final WindowFn windowFn; - private final InProcessEvaluationContext context; private final UncommittedBundle outputBundle; @SuppressWarnings("unchecked") public WindowIntoEvaluator( + AppliedPTransform, PCollection, Window.Bound> transform, WindowFn windowFn, - InProcessEvaluationContext context, UncommittedBundle outputBundle) { + this.outputBundle = outputBundle; + this.transform = transform; // Safe contravariant cast this.windowFn = (WindowFn) windowFn; - this.context = context; - this.outputBundle = outputBundle; } @Override @@ -96,7 +97,7 @@ private Collection assignWind @Override public InProcessTransformResult finishBundle() throws Exception { - return StepTransformResult.withoutHold(null).addOutput(outputBundle).build(); + return StepTransformResult.withoutHold(transform).addOutput(outputBundle).build(); } } From 46298e3ff7f86fb637efdbfd1a6897b3e405ba97 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 10 May 2016 14:06:27 -0700 Subject: [PATCH 378/751] Reuse DoFns in ParDoEvaluators This allows the runner to avoid cloning DoFns for every input bundle. --- .../inprocess/ParDoMultiEvaluatorFactory.java | 37 +++-- .../ParDoSingleEvaluatorFactory.java | 38 +++-- ...alizableCloningThreadLocalCacheLoader.java | 51 +++++++ ...ableCloningThreadLocalCacheLoaderTest.java | 96 +++++++++++++ ...adLocalInvalidatingTransformEvaluator.java | 61 ++++++++ ...calInvalidatingTransformEvaluatorTest.java | 133 ++++++++++++++++++ 6 files changed, 396 insertions(+), 20 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java index 245115b95b..9802f46f68 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java @@ -24,6 +24,9 @@ import com.google.cloud.dataflow.sdk.values.PCollectionTuple; import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.LoadingCache; + import java.util.Map; /** @@ -31,6 +34,13 @@ * {@link BoundMulti} primitive {@link PTransform}. */ class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory { + private final LoadingCache, ThreadLocal>> fnClones; + + public ParDoMultiEvaluatorFactory() { + fnClones = CacheBuilder.newBuilder() + .build(SerializableCloningThreadLocalCacheLoader.>create()); + } + @Override public TransformEvaluator forApplication( AppliedPTransform application, @@ -42,21 +52,28 @@ public TransformEvaluator forApplication( return evaluator; } - private static ParDoInProcessEvaluator createMultiEvaluator( + private TransformEvaluator createMultiEvaluator( AppliedPTransform, PCollectionTuple, BoundMulti> application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { Map, PCollection> outputs = application.getOutput().getAll(); DoFn fn = application.getTransform().getFn(); - return ParDoInProcessEvaluator.create( - evaluationContext, - inputBundle, - application, - fn, - application.getTransform().getSideInputs(), - application.getTransform().getMainOutputTag(), - application.getTransform().getSideOutputTags().getAll(), - outputs); + @SuppressWarnings({"unchecked", "rawtypes"}) ThreadLocal> fnLocal = + (ThreadLocal) fnClones.getUnchecked(application.getTransform().getFn()); + try { + TransformEvaluator parDoEvaluator = ParDoInProcessEvaluator.create(evaluationContext, + inputBundle, + application, + fnLocal.get(), + application.getTransform().getSideInputs(), + application.getTransform().getMainOutputTag(), + application.getTransform().getSideOutputTags().getAll(), + outputs); + return ThreadLocalInvalidatingTransformEvaluator.wrapping(parDoEvaluator, fnLocal); + } catch (Exception e) { + fnLocal.remove(); + throw e; + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java index 4d46fd1c1b..7de5bf2d2f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java @@ -17,10 +17,13 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableMap; import java.util.Collections; @@ -30,6 +33,13 @@ * {@link Bound ParDo.Bound} primitive {@link PTransform}. */ class ParDoSingleEvaluatorFactory implements TransformEvaluatorFactory { + private final LoadingCache, ThreadLocal>> fnClones; + + public ParDoSingleEvaluatorFactory() { + fnClones = CacheBuilder.newBuilder() + .build(SerializableCloningThreadLocalCacheLoader.>create()); + } + @Override public TransformEvaluator forApplication( final AppliedPTransform application, @@ -41,20 +51,28 @@ public TransformEvaluator forApplication( return evaluator; } - private static ParDoInProcessEvaluator createSingleEvaluator( + private TransformEvaluator createSingleEvaluator( @SuppressWarnings("rawtypes") AppliedPTransform, PCollection, Bound> application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { TupleTag mainOutputTag = new TupleTag<>("out"); - return ParDoInProcessEvaluator.create( - evaluationContext, - inputBundle, - application, - application.getTransform().getFn(), - application.getTransform().getSideInputs(), - mainOutputTag, - Collections.>emptyList(), - ImmutableMap., PCollection>of(mainOutputTag, application.getOutput())); + @SuppressWarnings({"unchecked", "rawtypes"}) ThreadLocal> fnLocal = + (ThreadLocal) fnClones.getUnchecked(application.getTransform().getFn()); + try { + ParDoInProcessEvaluator parDoEvaluator = ParDoInProcessEvaluator.create( + evaluationContext, + inputBundle, + application, + fnLocal.get(), + application.getTransform().getSideInputs(), + mainOutputTag, + Collections.>emptyList(), + ImmutableMap., PCollection>of(mainOutputTag, application.getOutput())); + return ThreadLocalInvalidatingTransformEvaluator.wrapping(parDoEvaluator, fnLocal); + } catch (Exception e) { + fnLocal.remove(); + throw e; + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java new file mode 100644 index 0000000000..5503242369 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.common.cache.CacheLoader; + +import java.io.Serializable; + +/** + * A {@link CacheLoader} that loads {@link ThreadLocal ThreadLocals} with initial values equal to + * the clone of the key. + */ +class SerializableCloningThreadLocalCacheLoader + extends CacheLoader> { + public static CacheLoader> create() { + return new SerializableCloningThreadLocalCacheLoader(); + } + + @Override + public ThreadLocal load(T key) throws Exception { + return new CloningThreadLocal<>(key); + } + + private static class CloningThreadLocal extends ThreadLocal { + private final T original; + + public CloningThreadLocal(T value) { + this.original = value; + } + + @Override + public T initialValue() { + return SerializableUtils.clone(original); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java new file mode 100644 index 0000000000..36b1607229 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsSame.theInstance; +import static org.junit.Assert.assertThat; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; + +/** + * Tests for {@link SerializableCloningThreadLocalCacheLoader}. + */ +@RunWith(JUnit4.class) +public class SerializableCloningThreadLocalCacheLoaderTest { + private SerializableCloningThreadLocalCacheLoader loader; + + @Before + public void setup() { + loader = new SerializableCloningThreadLocalCacheLoader(); + } + + @Test + public void returnsCopiesOfOriginal() throws Exception { + Record original = new Record(); + ThreadLocal loaded = loader.load(original); + assertThat(loaded.get(), not(nullValue())); + assertThat(loaded.get(), equalTo(original)); + assertThat(loaded.get(), not(theInstance(original))); + } + + @Test + public void returnsDifferentCopiesInDifferentThreads() throws Exception { + Record original = new Record(); + final ThreadLocal loaded = loader.load(original); + assertThat(loaded.get(), not(nullValue())); + assertThat(loaded.get(), equalTo(original)); + assertThat(loaded.get(), not(theInstance(original))); + + Callable otherThread = new Callable() { + @Override + public Record call() throws Exception { + return loaded.get(); + } + }; + Record sameThread = loaded.get(); + Record firstOtherThread = Executors.newSingleThreadExecutor().submit(otherThread).get(); + Record secondOtherThread = Executors.newSingleThreadExecutor().submit(otherThread).get(); + + assertThat(sameThread, equalTo(firstOtherThread)); + assertThat(sameThread, equalTo(secondOtherThread)); + assertThat(sameThread, not(theInstance(firstOtherThread))); + assertThat(sameThread, not(theInstance(secondOtherThread))); + assertThat(firstOtherThread, not(theInstance(secondOtherThread))); + } + + private static class Record implements Serializable { + private final double rand = Math.random(); + + @Override + public boolean equals(Object other) { + if (!(other instanceof Record)) { + return false; + } + Record that = (Record) other; + return this.rand == that.rand; + } + + @Override + public int hashCode() { + return 1; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java new file mode 100644 index 0000000000..42ca7dcb19 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.util.WindowedValue; + +/** + * A {@link TransformEvaluator} which delegates calls to an underlying {@link TransformEvaluator}, + * clearing the value of a {@link ThreadLocal} if any call throws an exception. + */ +class ThreadLocalInvalidatingTransformEvaluator + implements TransformEvaluator { + private final TransformEvaluator underlying; + private final ThreadLocal threadLocal; + + public static TransformEvaluator wrapping( + TransformEvaluator underlying, + ThreadLocal threadLocal) { + return new ThreadLocalInvalidatingTransformEvaluator<>(underlying, threadLocal); + } + + private ThreadLocalInvalidatingTransformEvaluator( + TransformEvaluator underlying, ThreadLocal threadLocal) { + this.underlying = underlying; + this.threadLocal = threadLocal; + } + + @Override + public void processElement(WindowedValue element) throws Exception { + try { + underlying.processElement(element); + } catch (Exception e) { + threadLocal.remove(); + throw e; + } + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + try { + return underlying.finishBundle(); + } catch (Exception e) { + threadLocal.remove(); + throw e; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java new file mode 100644 index 0000000000..ca8408a379 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +import com.google.cloud.dataflow.sdk.util.WindowedValue; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tests for {@link ThreadLocalInvalidatingTransformEvaluator}. + */ +@RunWith(JUnit4.class) +public class ThreadLocalInvalidatingTransformEvaluatorTest { + private ThreadLocal threadLocal; + + @Before + public void setup() { + threadLocal = new ThreadLocal<>(); + threadLocal.set(new Object()); + } + + @Test + public void delegatesToUnderlying() throws Exception { + RecordingTransformEvaluator underlying = new RecordingTransformEvaluator(); + Object original = threadLocal.get(); + TransformEvaluator evaluator = + ThreadLocalInvalidatingTransformEvaluator.wrapping(underlying, threadLocal); + WindowedValue first = WindowedValue.valueInGlobalWindow(new Object()); + WindowedValue second = WindowedValue.valueInGlobalWindow(new Object()); + evaluator.processElement(first); + assertThat(underlying.objects, containsInAnyOrder(first)); + evaluator.processElement(second); + evaluator.finishBundle(); + + assertThat(underlying.finishBundleCalled, is(true)); + assertThat(underlying.objects, containsInAnyOrder(second, first)); + } + + @Test + public void removesOnExceptionInProcessElement() { + ThrowingTransformEvaluator underlying = new ThrowingTransformEvaluator(); + Object original = threadLocal.get(); + assertThat(original, not(nullValue())); + TransformEvaluator evaluator = + ThreadLocalInvalidatingTransformEvaluator.wrapping(underlying, threadLocal); + + try { + evaluator.processElement(WindowedValue.valueInGlobalWindow(new Object())); + } catch (Exception e) { + assertThat(threadLocal.get(), nullValue()); + return; + } + fail("Expected ThrowingTransformEvaluator to throw on method call"); + } + + @Test + public void removesOnExceptionInFinishBundle() { + ThrowingTransformEvaluator underlying = new ThrowingTransformEvaluator(); + Object original = threadLocal.get(); + // the ThreadLocal is set when the evaluator starts + assertThat(original, not(nullValue())); + TransformEvaluator evaluator = + ThreadLocalInvalidatingTransformEvaluator.wrapping(underlying, threadLocal); + + try { + evaluator.finishBundle(); + } catch (Exception e) { + assertThat(threadLocal.get(), nullValue()); + return; + } + fail("Expected ThrowingTransformEvaluator to throw on method call"); + } + + private class RecordingTransformEvaluator implements TransformEvaluator { + private boolean finishBundleCalled; + private List> objects; + + public RecordingTransformEvaluator() { + this.finishBundleCalled = true; + this.objects = new ArrayList<>(); + } + + @Override + public void processElement(WindowedValue element) throws Exception { + objects.add(element); + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + finishBundleCalled = true; + return null; + } + } + + private class ThrowingTransformEvaluator implements TransformEvaluator { + @Override + public void processElement(WindowedValue element) throws Exception { + throw new Exception(); + } + + @Override + public InProcessTransformResult finishBundle() throws Exception { + throw new Exception(); + } + } +} From bda3ce28432536fd7069632d0d197eb1c38303a1 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 8 Apr 2016 15:02:09 -0700 Subject: [PATCH 379/751] Enforce non-null preconditions The InProcessPipelineRunner expects some result values to be non-null. Enforce those early. --- .../inprocess/InProcessTransformResult.java | 2 +- .../runners/inprocess/StepTransformResult.java | 17 +++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java index 3f9e94ad9f..3c66a781ae 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -61,6 +61,7 @@ public interface InProcessTransformResult { * * If this evaluation did not access state, this may return null. */ + @Nullable CopyOnAccessInMemoryStateInternals getState(); /** @@ -71,5 +72,4 @@ public interface InProcessTransformResult { *

          If this evaluation did not add or remove any timers, returns an empty TimerUpdate. */ TimerUpdate getTimerUpdate(); - } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java index 3c4ee29d96..c337e47105 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -28,15 +30,17 @@ import java.util.Collection; +import javax.annotation.Nullable; + /** * An immutable {@link InProcessTransformResult}. */ public class StepTransformResult implements InProcessTransformResult { private final AppliedPTransform transform; private final Iterable> bundles; - private final CopyOnAccessInMemoryStateInternals state; + @Nullable private final CopyOnAccessInMemoryStateInternals state; private final TimerUpdate timerUpdate; - private final CounterSet counters; + @Nullable private final CounterSet counters; private final Instant watermarkHold; private StepTransformResult( @@ -46,12 +50,12 @@ private StepTransformResult( TimerUpdate timerUpdate, CounterSet counters, Instant watermarkHold) { - this.transform = transform; - this.bundles = outputBundles; + this.transform = checkNotNull(transform); + this.bundles = checkNotNull(outputBundles); this.state = state; - this.timerUpdate = timerUpdate; + this.timerUpdate = checkNotNull(timerUpdate); this.counters = counters; - this.watermarkHold = watermarkHold; + this.watermarkHold = checkNotNull(watermarkHold); } @Override @@ -74,6 +78,7 @@ public Instant getWatermarkHold() { return watermarkHold; } + @Nullable @Override public CopyOnAccessInMemoryStateInternals getState() { return state; From 11c2030d9290dfcdea9a1bfd4675573021215852 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 3 May 2016 13:22:13 -0700 Subject: [PATCH 380/751] Refactor CompletionCallbacks The default and timerful completion callbacks are identical, excepting their calls to evaluationContext.commitResult; factor that code into a common location. --- .../ExecutorServiceParallelExecutor.java | 51 +++++++++++-------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index fd3d1e36a3..19d8eba6af 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -207,16 +207,20 @@ public void awaitCompletion() throws Throwable { } /** - * The default {@link CompletionCallback}. The default completion callback is used to complete - * transform evaluations that are triggered due to the arrival of elements from an upstream - * transform, or for a source transform. + * The base implementation of {@link CompletionCallback} that provides implementations for + * {@link #handleResult(CommittedBundle, InProcessTransformResult)} and + * {@link #handleThrowable(CommittedBundle, Throwable)}, given an implementation of + * {@link #getCommittedResult(CommittedBundle, InProcessTransformResult)}. */ - private class DefaultCompletionCallback implements CompletionCallback { + private abstract class CompletionCallbackBase implements CompletionCallback { + protected abstract CommittedResult getCommittedResult( + CommittedBundle inputBundle, + InProcessTransformResult result); + @Override - public CommittedResult handleResult( + public final CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result) { - CommittedResult committedResult = - evaluationContext.handleResult(inputBundle, Collections.emptyList(), result); + CommittedResult committedResult = getCommittedResult(inputBundle, result); for (CommittedBundle outputBundle : committedResult.getOutputs()) { allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); } @@ -224,18 +228,33 @@ public CommittedResult handleResult( } @Override - public void handleThrowable(CommittedBundle inputBundle, Throwable t) { + public final void handleThrowable(CommittedBundle inputBundle, Throwable t) { allUpdates.offer(ExecutorUpdate.fromThrowable(t)); } } + /** + * The default {@link CompletionCallback}. The default completion callback is used to complete + * transform evaluations that are triggered due to the arrival of elements from an upstream + * transform, or for a source transform. + */ + private class DefaultCompletionCallback extends CompletionCallbackBase { + @Override + public CommittedResult getCommittedResult( + CommittedBundle inputBundle, InProcessTransformResult result) { + return evaluationContext.handleResult(inputBundle, + Collections.emptyList(), + result); + } + } + /** * A {@link CompletionCallback} where the completed bundle was produced to deliver some collection * of {@link TimerData timers}. When the evaluator completes successfully, reports all of the * timers used to create the input to the {@link InProcessEvaluationContext evaluation context} * as part of the result. */ - private class TimerCompletionCallback implements CompletionCallback { + private class TimerCompletionCallback extends CompletionCallbackBase { private final Iterable timers; private TimerCompletionCallback(Iterable timers) { @@ -243,19 +262,9 @@ private TimerCompletionCallback(Iterable timers) { } @Override - public CommittedResult handleResult( + public CommittedResult getCommittedResult( CommittedBundle inputBundle, InProcessTransformResult result) { - CommittedResult committedResult = - evaluationContext.handleResult(inputBundle, timers, result); - for (CommittedBundle outputBundle : committedResult.getOutputs()) { - allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); - } - return committedResult; - } - - @Override - public void handleThrowable(CommittedBundle inputBundle, Throwable t) { - allUpdates.offer(ExecutorUpdate.fromThrowable(t)); + return evaluationContext.handleResult(inputBundle, timers, result); } } From e939ab516e6e109d887f5c35ac7052423a6a0f0f Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 6 May 2016 10:33:32 -0700 Subject: [PATCH 381/751] Use AutoValue for ExecutorUpdate Explicitly provide the collections the Bundle should be consumed by in the update. --- .../ExecutorServiceParallelExecutor.java | 59 ++++++++++--------- 1 file changed, 30 insertions(+), 29 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index 19d8eba6af..5b858bf0ca 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -15,6 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.auto.value.AutoValue; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; @@ -188,8 +189,9 @@ private boolean isKeyed(PValue pvalue) { return keyedPValues.contains(pvalue); } - private void scheduleConsumers(CommittedBundle bundle) { - for (AppliedPTransform consumer : valueToConsumers.get(bundle.getPCollection())) { + private void scheduleConsumers(ExecutorUpdate update) { + CommittedBundle bundle = update.getBundle().get(); + for (AppliedPTransform consumer : update.getConsumers()) { scheduleConsumption(consumer, bundle, defaultCompletionCallback); } } @@ -222,7 +224,8 @@ public final CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result) { CommittedResult committedResult = getCommittedResult(inputBundle, result); for (CommittedBundle outputBundle : committedResult.getOutputs()) { - allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle)); + allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle, + valueToConsumers.get(outputBundle.getPCollection()))); } return committedResult; } @@ -273,38 +276,36 @@ public CommittedResult getCommittedResult( * * Used to signal when the executor should be shut down (due to an exception). */ - private static class ExecutorUpdate { - private final Optional> bundle; - private final Optional throwable; - - public static ExecutorUpdate fromBundle(CommittedBundle bundle) { - return new ExecutorUpdate(bundle, null); + @AutoValue + abstract static class ExecutorUpdate { + public static ExecutorUpdate fromBundle( + CommittedBundle bundle, + Collection> consumers) { + return new AutoValue_ExecutorServiceParallelExecutor_ExecutorUpdate( + Optional.of(bundle), + consumers, + Optional.absent()); } public static ExecutorUpdate fromThrowable(Throwable t) { - return new ExecutorUpdate(null, t); - } - - private ExecutorUpdate(CommittedBundle producedBundle, Throwable throwable) { - this.bundle = Optional.fromNullable(producedBundle); - this.throwable = Optional.fromNullable(throwable); + return new AutoValue_ExecutorServiceParallelExecutor_ExecutorUpdate( + Optional.>absent(), + Collections.>emptyList(), + Optional.of(t)); } - public Optional> getBundle() { - return bundle; - } + /** + * Returns the bundle that produced this update. + */ + public abstract Optional> getBundle(); - public Optional getException() { - return throwable; - } + /** + * Returns the transforms to process the bundle. If nonempty, {@link #getBundle()} will return + * a present {@link Optional}. + */ + public abstract Collection> getConsumers(); - @Override - public String toString() { - return MoreObjects.toStringHelper(ExecutorUpdate.class) - .add("bundle", bundle) - .add("exception", throwable) - .toString(); - } + public abstract Optional getException(); } /** @@ -350,7 +351,7 @@ public void run() { while (update != null) { LOG.debug("Executor Update: {}", update); if (update.getBundle().isPresent()) { - scheduleConsumers(update.getBundle().get()); + scheduleConsumers(update); } else if (update.getException().isPresent()) { visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); } From 60a20edd16e8e951ba8886459fbb896c6fe63f23 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 3 May 2016 13:24:25 -0700 Subject: [PATCH 382/751] Allow InProcess TransformEvaluators to refuse inputs Inputs that cannot be processed (generally due to a side input not being ready) can be added to a list of unprocessed elements, which will schedule them to be executed at a later point. --- .../runners/inprocess/CommittedResult.java | 16 ++- .../ExecutorServiceParallelExecutor.java | 6 + .../inprocess/InMemoryWatermarkManager.java | 7 +- .../inprocess/InProcessEvaluationContext.java | 6 +- .../inprocess/InProcessTransformResult.java | 7 + .../inprocess/StepTransformResult.java | 17 +++ .../inprocess/CommittedResultTest.java | 34 ++++- .../InMemoryWatermarkManagerTest.java | 127 +++++++++++++++--- .../inprocess/TransformExecutorTest.java | 11 +- 9 files changed, 209 insertions(+), 22 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java index d900cfac4d..7b9cfbcf8e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java @@ -19,6 +19,8 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import javax.annotation.Nullable; + /** * A {@link InProcessTransformResult} that has been committed. */ @@ -29,14 +31,26 @@ abstract class CommittedResult { */ public abstract AppliedPTransform getTransform(); + /** + * Returns the {@link CommittedBundle} that contains the input elements that could not be + * processed by the evaluation. + * + *

          {@code null} if the input bundle was null. + */ + @Nullable + public abstract CommittedBundle getUnprocessedInputs(); + /** * Returns the outputs produced by the transform. */ public abstract Iterable> getOutputs(); public static CommittedResult create( - InProcessTransformResult original, Iterable> outputs) { + InProcessTransformResult original, + CommittedBundle unprocessedElements, + Iterable> outputs) { return new AutoValue_CommittedResult(original.getTransform(), + unprocessedElements, outputs); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index 5b858bf0ca..03b47d1abd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -34,6 +34,7 @@ import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import org.joda.time.Instant; import org.slf4j.Logger; @@ -227,6 +228,11 @@ public final CommittedResult handleResult( allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle, valueToConsumers.get(outputBundle.getPCollection()))); } + CommittedBundle unprocessedInputs = committedResult.getUnprocessedInputs(); + if (unprocessedInputs != null && !Iterables.isEmpty(unprocessedInputs.getElements())) { + allUpdates.offer(ExecutorUpdate.fromBundle(unprocessedInputs, + Collections.>singleton(committedResult.getTransform()))); + } return committedResult; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 1bb55ab9dd..d64e980e4c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -846,8 +846,6 @@ private void updatePending( CommittedBundle input, TimerUpdate timerUpdate, CommittedResult result) { - TransformWatermarks completedTransform = transformToWatermarks.get(result.getTransform()); - // Newly pending elements must be added before completed elements are removed, as the two // do not share a Mutex within this call and thus can be interleaved with external calls to // refresh. @@ -858,6 +856,11 @@ private void updatePending( } } + TransformWatermarks completedTransform = transformToWatermarks.get(result.getTransform()); + if (input != null) { + // Add the unprocessed inputs + completedTransform.addPending(result.getUnprocessedInputs()); + } completedTransform.updateTimers(timerUpdate); if (input != null) { completedTransform.removePending(input); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index db0f9717bf..fb5727e8fb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -150,7 +150,11 @@ public synchronized CommittedResult handleResult( Iterable> committedBundles = commitBundles(result.getOutputBundles()); // Update watermarks and timers - CommittedResult committedResult = CommittedResult.create(result, committedBundles); + CommittedResult committedResult = CommittedResult.create(result, + completedBundle == null ? + null : + completedBundle.withElements((Iterable) result.getUnprocessedElements()), + committedBundles); watermarkManager.updateWatermarks( completedBundle, result.getTimerUpdate().withCompletedTimers(completedTimers), diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java index 3c66a781ae..add53387b7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -20,6 +20,7 @@ import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; @@ -42,6 +43,12 @@ public interface InProcessTransformResult { */ Iterable> getOutputBundles(); + /** + * Returns elements that were provided to the {@link TransformEvaluator} as input but were not + * processed. + */ + Iterable> getUnprocessedElements(); + /** * Returns the {@link CounterSet} used by this {@link PTransform}, or null if this transform did * not use a {@link CounterSet}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java index c337e47105..b520c0666b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; import com.google.common.base.MoreObjects; @@ -38,6 +39,7 @@ public class StepTransformResult implements InProcessTransformResult { private final AppliedPTransform transform; private final Iterable> bundles; + private final Iterable> unprocessedElements; @Nullable private final CopyOnAccessInMemoryStateInternals state; private final TimerUpdate timerUpdate; @Nullable private final CounterSet counters; @@ -46,12 +48,14 @@ public class StepTransformResult implements InProcessTransformResult { private StepTransformResult( AppliedPTransform transform, Iterable> outputBundles, + Iterable> unprocessedElements, CopyOnAccessInMemoryStateInternals state, TimerUpdate timerUpdate, CounterSet counters, Instant watermarkHold) { this.transform = checkNotNull(transform); this.bundles = checkNotNull(outputBundles); + this.unprocessedElements = checkNotNull(unprocessedElements); this.state = state; this.timerUpdate = checkNotNull(timerUpdate); this.counters = counters; @@ -63,6 +67,11 @@ public Iterable> getOutputBundles() { return bundles; } + @Override + public Iterable> getUnprocessedElements() { + return unprocessedElements; + } + @Override public CounterSet getCounters() { return counters; @@ -110,6 +119,7 @@ public String toString() { public static class Builder { private final AppliedPTransform transform; private final ImmutableList.Builder> bundlesBuilder; + private final ImmutableList.Builder> unprocessedElementsBuilder; private CopyOnAccessInMemoryStateInternals state; private TimerUpdate timerUpdate; private CounterSet counters; @@ -119,6 +129,7 @@ private Builder(AppliedPTransform transform, Instant watermarkHold) { this.transform = transform; this.watermarkHold = watermarkHold; this.bundlesBuilder = ImmutableList.builder(); + this.unprocessedElementsBuilder = ImmutableList.builder(); this.timerUpdate = TimerUpdate.builder(null).build(); } @@ -126,6 +137,7 @@ public StepTransformResult build() { return new StepTransformResult( transform, bundlesBuilder.build(), + unprocessedElementsBuilder.build(), state, timerUpdate, counters, @@ -147,6 +159,11 @@ public Builder withTimerUpdate(TimerUpdate timerUpdate) { return this; } + public Builder addUnprocessedElements(Iterable> unprocessed) { + unprocessedElementsBuilder.addAll(unprocessed); + return this; + } + public Builder addOutput( UncommittedBundle outputBundle, UncommittedBundle... outputBundles) { bundlesBuilder.add(outputBundle); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java index 3046dc1119..28beaf2fcc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java @@ -15,11 +15,14 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -42,6 +45,7 @@ @RunWith(JUnit4.class) public class CommittedResultTest implements Serializable { private transient TestPipeline p = TestPipeline.create(); + private transient PCollection created = p.apply(Create.of(1, 2)); private transient AppliedPTransform transform = AppliedPTransform.of("foo", p.begin(), PDone.in(p), new PTransform() { }); @@ -51,11 +55,37 @@ public class CommittedResultTest implements Serializable { public void getTransformExtractsFromResult() { CommittedResult result = CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + bundleFactory.createRootBundle(created).commit(Instant.now()), Collections.>emptyList()); assertThat(result.getTransform(), Matchers.>equalTo(transform)); } + @Test + public void getUncommittedElementsEqualInput() { + InProcessPipelineRunner.CommittedBundle bundle = + bundleFactory.createRootBundle(created) + .add(WindowedValue.valueInGlobalWindow(2)) + .commit(Instant.now()); + CommittedResult result = + CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + bundle, + Collections.>emptyList()); + + assertThat(result.getUnprocessedInputs(), + Matchers.>equalTo(bundle)); + } + + @Test + public void getUncommittedElementsNull() { + CommittedResult result = + CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + null, + Collections.>emptyList()); + + assertThat(result.getUnprocessedInputs(), nullValue()); + } + @Test public void getOutputsEqualInput() { List> outputs = @@ -66,7 +96,9 @@ public void getOutputsEqualInput() { WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED)).commit(Instant.now())); CommittedResult result = - CommittedResult.create(StepTransformResult.withoutHold(transform).build(), outputs); + CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + bundleFactory.createRootBundle(created).commit(Instant.now()), + outputs); assertThat(result.getOutputs(), Matchers.containsInAnyOrder(outputs.toArray())); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index 5707bb0b2b..c2abd9aa0e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -68,6 +68,8 @@ import java.util.HashMap; import java.util.Map; +import javax.annotation.Nullable; + /** * Tests for {@link InMemoryWatermarkManager}. */ @@ -159,6 +161,7 @@ public void getWatermarkForUpdatedSourceTransform() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(output)), new Instant(8000L)); TransformWatermarks updatedSourceWatermark = @@ -178,6 +181,7 @@ public void getWatermarkForMultiInputTransform() { manager.updateWatermarks(null, TimerUpdate.empty(), result(intsToFlatten.getProducingTransformInternal(), + null, Collections.>singleton(secondPcollectionBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -210,6 +214,7 @@ public void getWatermarkForMultiInputTransform() { manager.updateWatermarks(secondPcollectionBundle, TimerUpdate.empty(), result(flattened.getProducingTransformInternal(), + secondPcollectionBundle.withElements(Collections.>emptyList()), Collections.>singleton(flattenedBundleSecondCreate)), null); TransformWatermarks transformAfterProcessing = @@ -217,6 +222,7 @@ public void getWatermarkForMultiInputTransform() { manager.updateWatermarks(secondPcollectionBundle, TimerUpdate.empty(), result(flattened.getProducingTransformInternal(), + secondPcollectionBundle.withElements(Collections.>emptyList()), Collections.>singleton(flattenedBundleSecondCreate)), null); assertThat( @@ -234,6 +240,7 @@ public void getWatermarkForMultiInputTransform() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(firstPcollectionBundle)), new Instant(Long.MAX_VALUE)); TransformWatermarks firstSourceWatermarks = @@ -264,6 +271,7 @@ public void getWatermarkForMultiInputTransform() { manager.updateWatermarks(firstPcollectionBundle, TimerUpdate.empty(), result(flattened.getProducingTransformInternal(), + firstPcollectionBundle.withElements(Collections.>emptyList()), Collections.>singleton(completedFlattenBundle)), null); TransformWatermarks afterConsumingAllInput = @@ -288,6 +296,7 @@ public void getWatermarkForMultiConsumedCollection() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createdBundle)), new Instant(Long.MAX_VALUE)); TransformWatermarks createdAfterProducing = @@ -303,6 +312,7 @@ public void getWatermarkForMultiConsumedCollection() { manager.updateWatermarks(createdBundle, TimerUpdate.empty(), result(keyed.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), null); TransformWatermarks keyedWatermarks = @@ -322,6 +332,7 @@ public void getWatermarkForMultiConsumedCollection() { manager.updateWatermarks(createdBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), null); TransformWatermarks filteredProcessedWatermarks = @@ -347,6 +358,7 @@ public void updateWatermarkWithWatermarkHolds() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createdBundle)), new Instant(Long.MAX_VALUE)); @@ -357,6 +369,7 @@ public void updateWatermarkWithWatermarkHolds() { manager.updateWatermarks(createdBundle, TimerUpdate.empty(), result(keyed.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), new Instant(500L)); TransformWatermarks keyedWatermarks = @@ -386,17 +399,20 @@ public void updateWatermarkWithKeyedWatermarkHolds() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, ImmutableList.of(firstKeyBundle, secondKeyBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); manager.updateWatermarks(firstKeyBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + firstKeyBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), new Instant(-1000L)); manager.updateWatermarks(secondKeyBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + secondKeyBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), new Instant(1234L)); @@ -411,6 +427,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { manager.updateWatermarks(fauxFirstKeyTimerBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + fauxFirstKeyTimerBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -421,6 +438,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { manager.updateWatermarks(fauxSecondKeyTimerBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + fauxSecondKeyTimerBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), new Instant(5678L)); assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(5678L))); @@ -428,6 +446,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { manager.updateWatermarks(fauxSecondKeyTimerBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + fauxSecondKeyTimerBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(filteredWatermarks.getOutputWatermark(), @@ -444,6 +463,7 @@ public void updateOutputWatermarkShouldBeMonotonic() { bundleFactory.createRootBundle(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(firstInput)), new Instant(0L)); TransformWatermarks firstWatermarks = @@ -455,6 +475,7 @@ public void updateOutputWatermarkShouldBeMonotonic() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(secondInput)), new Instant(-250L)); TransformWatermarks secondWatermarks = @@ -470,10 +491,12 @@ public void updateOutputWatermarkShouldBeMonotonic() { public void updateWatermarkWithHoldsShouldBeMonotonic() { CommittedBundle createdBundle = timestampedBundle(createdInts, TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); manager.updateWatermarks(null, + TimestampedValue.of(2, new Instant(1234L)), + TimestampedValue.of(3, new Instant(-1000L))); + manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createdBundle)), new Instant(Long.MAX_VALUE)); @@ -484,6 +507,7 @@ public void updateWatermarkWithHoldsShouldBeMonotonic() { manager.updateWatermarks(createdBundle, TimerUpdate.empty(), result(keyed.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), new Instant(500L)); TransformWatermarks keyedWatermarks = @@ -502,6 +526,40 @@ public void updateWatermarkWithHoldsShouldBeMonotonic() { assertThat(updatedWatermarks.getOutputWatermark(), equalTo(oldOutputWatermark)); } + @Test + public void updateWatermarkWithUnprocessedElements() { + WindowedValue first = WindowedValue.valueInGlobalWindow(1); + WindowedValue second = + WindowedValue.timestampedValueInGlobalWindow(2, new Instant(-1000L)); + WindowedValue third = + WindowedValue.timestampedValueInGlobalWindow(3, new Instant(1234L)); + CommittedBundle createdBundle = bundleFactory.createRootBundle(createdInts) + .add(first) + .add(second) + .add(third) + .commit(clock.now()); + manager.updateWatermarks(null, + TimerUpdate.empty(), + result(createdInts.getProducingTransformInternal(), + null, + Collections.>singleton(createdBundle)), + BoundedWindow.TIMESTAMP_MAX_VALUE); + + CommittedBundle> keyBundle = timestampedBundle(keyed, + TimestampedValue.of(KV.of("MyKey", 1), BoundedWindow.TIMESTAMP_MIN_VALUE)); + manager.updateWatermarks(createdBundle, + TimerUpdate.empty(), + result(keyed.getProducingTransformInternal(), + createdBundle.withElements(ImmutableList.of(second, third)), + Collections.>singleton(keyBundle)), + BoundedWindow.TIMESTAMP_MAX_VALUE); + TransformWatermarks keyedWatermarks = + manager.getWatermarks(keyed.getProducingTransformInternal()); + // the unprocessed second and third are readded to pending + assertThat( + keyedWatermarks.getInputWatermark(), not(laterThan(new Instant(-1000L)))); + } + /** * Demonstrates that updateWatermarks in the presence of late data is monotonic. */ @@ -514,6 +572,7 @@ public void updateWatermarkWithLateData() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createdBundle)), sourceWatermark); @@ -525,6 +584,7 @@ public void updateWatermarkWithLateData() { manager.updateWatermarks(createdBundle, TimerUpdate.empty(), result(keyed.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), null); TransformWatermarks onTimeWatermarks = @@ -539,6 +599,7 @@ public void updateWatermarkWithLateData() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(lateDataBundle)), new Instant(2_000_000L)); TransformWatermarks bufferedLateWm = @@ -557,6 +618,7 @@ public void updateWatermarkWithLateData() { manager.updateWatermarks(lateDataBundle, TimerUpdate.empty(), result(keyed.getProducingTransformInternal(), + lateDataBundle.withElements(Collections.>emptyList()), Collections.>singleton(lateKeyedBundle)), null); } @@ -564,8 +626,7 @@ public void updateWatermarkWithLateData() { public void updateWatermarkWithDifferentWindowedValueInstances() { manager.updateWatermarks( null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), + TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), null, Collections.>singleton( bundleFactory .createRootBundle(createdInts) @@ -573,12 +634,14 @@ public void updateWatermarkWithDifferentWindowedValueInstances() { .commit(Instant.now()))), BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks( - bundleFactory.createRootBundle(createdInts) - .add(WindowedValue.valueInGlobalWindow(1)) - .commit(Instant.now()), + CommittedBundle createdBundle = bundleFactory.createRootBundle(createdInts) + .add(WindowedValue.valueInGlobalWindow(1)) + .commit(Instant.now()); + manager.updateWatermarks(createdBundle, TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), Collections.>emptyList()), + result(keyed.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), + Collections.>emptyList()), null); TransformWatermarks onTimeWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); @@ -595,6 +658,7 @@ public void getWatermarksAfterOnlyEmptyOutput() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(emptyCreateOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = @@ -624,6 +688,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(firstCreateOutput)), new Instant(12_000L)); @@ -631,6 +696,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { manager.updateWatermarks(firstCreateOutput, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + firstCreateOutput.withElements(Collections.>emptyList()), Collections.>singleton(firstFilterOutput)), new Instant(10_000L)); TransformWatermarks firstFilterWatermarks = @@ -642,6 +708,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(emptyCreateOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks updatedSourceWatermarks = @@ -684,6 +751,7 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = @@ -713,6 +781,7 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { manager.updateWatermarks(createOutput, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + createOutput.withElements(Collections.>emptyList()), Collections.>singleton(filterOutputBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks filterAfterConsumed = @@ -734,8 +803,10 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { // @Test public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { CommittedBundle createdBundle = multiWindowedBundle(createdInts, 1, 2, 4, 8); - manager.updateWatermarks(null, TimerUpdate.empty(), + manager.updateWatermarks(null, + TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createdBundle)), new Instant(1248L)); @@ -756,6 +827,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { manager.updateWatermarks(createdBundle, timers, result(filtered.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); Instant startTime = clock.now(); @@ -793,6 +865,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { TimerUpdate.builder("key") .withCompletedTimers(Collections.singleton(pastTimer)).build(), result(filtered.getProducingTransformInternal(), + filteredTimerBundle.withElements(Collections.>emptyList()), Collections.>singleton(filteredTimerResult)), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -806,6 +879,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { manager.updateWatermarks(filteredTimerResult, TimerUpdate.empty(), result(filteredTimesTwo.getProducingTransformInternal(), + filteredTimerResult.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); @@ -843,6 +917,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks createAfterUpdate = @@ -856,6 +931,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(createSecondOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -868,6 +944,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(created)), new Instant(40_900L)); @@ -878,6 +955,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( manager.updateWatermarks(created, TimerUpdate.builder("key").setTimer(upstreamProcessingTimer).build(), result(filtered.getProducingTransformInternal(), + created.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -898,6 +976,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( TimerUpdate.builder("key") .withCompletedTimers(Collections.singleton(upstreamProcessingTimer)).build(), result(filtered.getProducingTransformInternal(), + otherCreated.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -911,6 +990,7 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>singleton(created)), new Instant(29_919_235L)); @@ -921,6 +1001,7 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { created, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), + created.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -943,7 +1024,9 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { CommittedBundle createdBundle = multiWindowedBundle(filtered); manager.updateWatermarks(null, TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), Collections.singleton(createdBundle)), + result(createdInts.getProducingTransformInternal(), + null, + Collections.singleton(createdBundle)), new Instant(1500L)); TimerData earliestTimer = @@ -963,6 +1046,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { manager.updateWatermarks(createdBundle, update, result(filtered.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); @@ -979,6 +1063,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>emptyList()), new Instant(50_000L)); Map, Map> secondTransformFiredTimers = @@ -1004,7 +1089,9 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { CommittedBundle createdBundle = multiWindowedBundle(filtered); manager.updateWatermarks(null, TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), Collections.singleton(createdBundle)), + result(createdInts.getProducingTransformInternal(), + null, + Collections.singleton(createdBundle)), new Instant(1500L)); TimerData earliestTimer = @@ -1025,7 +1112,8 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { createdBundle, update, result(filtered.getProducingTransformInternal(), - Collections.>singleton(multiWindowedBundle(intsToFlatten))), + createdBundle.withElements(Collections.>emptyList()), + Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); Map, Map> firstTransformFiredTimers = @@ -1042,6 +1130,7 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>emptyList()), new Instant(50_000L)); Map, Map> secondTransformFiredTimers = @@ -1067,7 +1156,9 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { CommittedBundle createdBundle = multiWindowedBundle(filtered); manager.updateWatermarks(null, TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), Collections.singleton(createdBundle)), + result(createdInts.getProducingTransformInternal(), + null, + Collections.singleton(createdBundle)), new Instant(1500L)); TimerData earliestTimer = TimerData.of( @@ -1088,6 +1179,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { createdBundle, update, result(filtered.getProducingTransformInternal(), + createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); @@ -1106,6 +1198,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { manager.updateWatermarks(null, TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), + null, Collections.>emptyList()), new Instant(50_000L)); Map, Map> secondTransformFiredTimers = @@ -1270,8 +1363,10 @@ private final CommittedBundle multiWindowedBundle(PCollection pc, T... private final CommittedResult result( AppliedPTransform transform, + @Nullable CommittedBundle unprocessedBundle, Iterable> bundles) { - return CommittedResult.create(StepTransformResult.withoutHold(transform) - .build(), bundles); + return CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + unprocessedBundle, + bundles); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index ff8ef8039e..5335548f6e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -488,7 +488,16 @@ public CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result) { handledResult = result; onMethod.countDown(); - return CommittedResult.create(result, Collections.>emptyList()); + @SuppressWarnings("rawtypes") Iterable unprocessedElements = + result.getUnprocessedElements() == null ? + Collections.emptyList() : + result.getUnprocessedElements(); + + CommittedBundle unprocessedBundle = + inputBundle == null ? null : inputBundle.withElements(unprocessedElements); + return CommittedResult.create(result, + unprocessedBundle, + Collections.>emptyList()); } @Override From c8acc53a8790f1611f2ec1846b17d0e8788714fd Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 28 Apr 2016 10:12:09 -0700 Subject: [PATCH 383/751] Limit the number of work schedules per MonitorRunnable run This ensures that work readded to the queue will not cause the monitor runnable to run forever before delivering timers --- .../ExecutorServiceParallelExecutor.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index 03b47d1abd..b9f83cceea 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -51,6 +51,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; @@ -341,11 +342,11 @@ public boolean isDone() { } private class MonitorRunnable implements Runnable { - private final String runnableName = - String.format( - "%s$%s-monitor", - evaluationContext.getPipelineOptions().getAppName(), - ExecutorServiceParallelExecutor.class.getSimpleName()); + // arbitrary termination condition to ensure progress in the presence of pushback + private final long maxTimeProcessingUpdatesNanos = TimeUnit.MILLISECONDS.toNanos(5L); + private final String runnableName = String.format("%s$%s-monitor", + evaluationContext.getPipelineOptions().getAppName(), + ExecutorServiceParallelExecutor.class.getSimpleName()); @Override public void run() { @@ -353,7 +354,9 @@ public void run() { Thread.currentThread().setName(runnableName); try { ExecutorUpdate update = allUpdates.poll(); + int numUpdates = 0; // pull all of the pending work off of the queue + long updatesStart = System.nanoTime(); while (update != null) { LOG.debug("Executor Update: {}", update); if (update.getBundle().isPresent()) { @@ -361,7 +364,11 @@ public void run() { } else if (update.getException().isPresent()) { visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); } - update = allUpdates.poll(); + if (System.nanoTime() - updatesStart > maxTimeProcessingUpdatesNanos) { + break; + } else { + update = allUpdates.poll(); + } } boolean timersFired = fireTimers(); addWorkIfNecessary(timersFired); From d96884054c7f5608a01acb4bd70af8caec6f8e1b Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 12 May 2016 13:46:07 -0700 Subject: [PATCH 384/751] Place PushbackSideInputDoFnRunner in the correct directory Fixes backport issue. --- .../sdk/util/PushbackSideInputDoFnRunner.java | 29 +++++----- .../sdk/util/IdentitySideInputWindowFn.java | 52 ++++++++++++++++++ .../util/PushbackSideInputDoFnRunnerTest.java | 45 ++++++++-------- .../sdk/util/IdentitySideInputWindowFn.java | 54 ------------------- 4 files changed, 86 insertions(+), 94 deletions(-) rename {sdks/java/core/src/main/java/org/apache/beam => sdk/src/main/java/com/google/cloud/dataflow}/sdk/util/PushbackSideInputDoFnRunner.java (80%) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java rename {sdks/java/core/src/test/java/org/apache/beam => sdk/src/test/java/com/google/cloud/dataflow}/sdk/util/PushbackSideInputDoFnRunnerTest.java (86%) delete mode 100644 sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java similarity index 80% rename from sdks/java/core/src/main/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunner.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java index 4eeedf65a1..3342df6bb9 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java @@ -1,25 +1,22 @@ /* - * 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 + * Copyright (C) 2016 Google Inc. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed 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. + * 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.beam.sdk.util; - -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.values.PCollectionView; +package com.google.cloud.dataflow.sdk.util; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java new file mode 100644 index 0000000000..0e858127ff --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.NonMergingWindowFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; + +import java.util.Collection; + +/** + * A {@link WindowFn} for use during tests that returns the input window for calls to + * {@link #getSideInputWindow(BoundedWindow)}. + */ +public class IdentitySideInputWindowFn extends NonMergingWindowFn { + @Override + public Collection assignWindows(WindowFn.AssignContext c) + throws Exception { + return (Collection) c.windows(); + } + + @Override + public boolean isCompatible(WindowFn other) { + return true; + } + + @Override + public Coder windowCoder() { + // not used + return (Coder) GlobalWindow.Coder.INSTANCE; + } + + @Override + public BoundedWindow getSideInputWindow(BoundedWindow window) { + return window; + } +} diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunnerTest.java similarity index 86% rename from sdks/java/core/src/test/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunnerTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunnerTest.java index 88851187bb..d1239ad97d 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/PushbackSideInputDoFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunnerTest.java @@ -1,21 +1,19 @@ /* - * 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 + * Copyright (C) 2016 Google Inc. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed 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. + * 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.beam.sdk.util; +package com.google.cloud.dataflow.sdk.util; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; @@ -24,17 +22,16 @@ import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.transforms.Sum; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.GlobalWindow; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.PaneInfo; -import org.apache.beam.sdk.transforms.windowing.Window; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PCollectionView; - +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.common.collect.ImmutableList; import org.hamcrest.Matchers; diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java deleted file mode 100644 index ecab6f8eb6..0000000000 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/IdentitySideInputWindowFn.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.beam.sdk.util; - -import org.apache.beam.sdk.coders.Coder; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.GlobalWindow; -import org.apache.beam.sdk.transforms.windowing.NonMergingWindowFn; -import org.apache.beam.sdk.transforms.windowing.WindowFn; - -import java.util.Collection; - -/** - * A {@link WindowFn} for use during tests that returns the input window for calls to - * {@link #getSideInputWindow(BoundedWindow)}. - */ -class IdentitySideInputWindowFn extends NonMergingWindowFn { - @Override - public Collection assignWindows(WindowFn.AssignContext c) - throws Exception { - return (Collection) c.windows(); - } - - @Override - public boolean isCompatible(WindowFn other) { - return true; - } - - @Override - public Coder windowCoder() { - // not used - return (Coder) GlobalWindow.Coder.INSTANCE; - } - - @Override - public BoundedWindow getSideInputWindow(BoundedWindow window) { - return window; - } -} From 9d4df91a08e9a77d7152602ee11831ef6cb89055 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Wed, 27 Apr 2016 17:27:57 -0700 Subject: [PATCH 385/751] Use PushbackDoFnRunner in the ParDoInProcessEvaluator This ensures that the evaluator does not block while processing an input bundle. --- .../inprocess/ParDoInProcessEvaluator.java | 23 +- .../sdk/util/PushbackSideInputDoFnRunner.java | 2 +- .../ParDoInProcessEvaluatorTest.java | 211 ++++++++++++++++++ 3 files changed, 230 insertions(+), 6 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java index 38f62fdce5..4fba3bdbeb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java @@ -23,6 +23,8 @@ import com.google.cloud.dataflow.sdk.util.DoFnRunner; import com.google.cloud.dataflow.sdk.util.DoFnRunners; import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; +import com.google.cloud.dataflow.sdk.util.PushbackSideInputDoFnRunner; +import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -31,6 +33,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Collection; @@ -63,17 +66,21 @@ public static ParDoInProcessEvaluator create( evaluationContext.createBundle(inputBundle, outputEntry.getValue())); } - DoFnRunner runner = + ReadyCheckingSideInputReader sideInputReader = + evaluationContext.createSideInputReader(sideInputs); + DoFnRunner underlying = DoFnRunners.createDefault( evaluationContext.getPipelineOptions(), SerializableUtils.clone(fn), - evaluationContext.createSideInputReader(sideInputs), + sideInputReader, BundleOutputManager.create(outputBundles), mainOutputTag, sideOutputTags, stepContext, counters.getAddCounterMutator(), application.getInput().getWindowingStrategy()); + PushbackSideInputDoFnRunner runner = + PushbackSideInputDoFnRunner.create(underlying, sideInputs, sideInputReader); try { runner.startBundle(); @@ -87,14 +94,16 @@ public static ParDoInProcessEvaluator create( //////////////////////////////////////////////////////////////////////////////////////////////// - private final DoFnRunner fnRunner; + private final PushbackSideInputDoFnRunner fnRunner; private final AppliedPTransform, ?, ?> transform; private final CounterSet counters; private final Collection> outputBundles; private final InProcessStepContext stepContext; + private final ImmutableList.Builder> unprocessedElements; + private ParDoInProcessEvaluator( - DoFnRunner fnRunner, + PushbackSideInputDoFnRunner fnRunner, AppliedPTransform, ?, ?> transform, CounterSet counters, Collection> outputBundles, @@ -104,12 +113,15 @@ private ParDoInProcessEvaluator( this.counters = counters; this.outputBundles = outputBundles; this.stepContext = stepContext; + + this.unprocessedElements = ImmutableList.builder(); } @Override public void processElement(WindowedValue element) { try { - fnRunner.processElement(element); + Iterable> unprocessed = fnRunner.processElementInReadyWindows(element); + unprocessedElements.addAll(unprocessed); } catch (Exception e) { throw UserCodeException.wrap(e); } @@ -135,6 +147,7 @@ public InProcessTransformResult finishBundle() { .addOutput(outputBundles) .withTimerUpdate(stepContext.getTimerUpdate()) .withCounters(counters) + .addUnprocessedElements(unprocessedElements.build()) .build(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java index 3342df6bb9..d047d739f9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java @@ -29,7 +29,7 @@ * A {@link DoFnRunner} that can refuse to process elements that are not ready, instead returning * them via the {@link #processElementInReadyWindows(WindowedValue)}. */ -class PushbackSideInputDoFnRunner implements DoFnRunner { +public class PushbackSideInputDoFnRunner implements DoFnRunner { private final DoFnRunner underlying; private final Collection> views; private final ReadyCheckingSideInputReader sideInputReader; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java new file mode 100644 index 0000000000..828b749794 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.util.IdentitySideInputWindowFn; +import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.cloud.dataflow.sdk.values.TupleTagList; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import javax.annotation.Nullable; + +/** + * Tests for {@link ParDoInProcessEvaluator}. + */ +@RunWith(JUnit4.class) +public class ParDoInProcessEvaluatorTest { + @Mock private InProcessEvaluationContext evaluationContext; + private PCollection inputPc; + private TupleTag mainOutputTag; + private List> sideOutputTags; + private BundleFactory bundleFactory; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + TestPipeline p = TestPipeline.create(); + inputPc = p.apply(Create.of(1, 2, 3)); + mainOutputTag = new TupleTag() {}; + sideOutputTags = TupleTagList.empty().getAll(); + + bundleFactory = InProcessBundleFactory.create(); + } + + @Test + public void sideInputsNotReadyResultHasUnprocessedElements() { + PCollectionView singletonView = + inputPc + .apply(Window.into(new IdentitySideInputWindowFn())) + .apply(View.asSingleton().withDefaultValue(0)); + RecorderFn fn = new RecorderFn(singletonView); + PCollection output = inputPc.apply(ParDo.of(fn).withSideInputs(singletonView)); + + CommittedBundle inputBundle = + bundleFactory.createRootBundle(inputPc).commit(Instant.now()); + UncommittedBundle outputBundle = bundleFactory.createBundle(inputBundle, output); + when(evaluationContext.createBundle(inputBundle, output)) + .thenReturn(outputBundle); + + ParDoInProcessEvaluator evaluator = + createEvaluator(singletonView, fn, inputBundle, output); + + IntervalWindow nonGlobalWindow = new IntervalWindow(new Instant(0), new Instant(10_000L)); + WindowedValue first = WindowedValue.valueInGlobalWindow(3); + WindowedValue second = + WindowedValue.of(2, new Instant(1234L), nonGlobalWindow, PaneInfo.NO_FIRING); + WindowedValue third = + WindowedValue.of( + 1, + new Instant(2468L), + ImmutableList.of(nonGlobalWindow, GlobalWindow.INSTANCE), + PaneInfo.NO_FIRING); + + evaluator.processElement(first); + evaluator.processElement(second); + evaluator.processElement(third); + InProcessTransformResult result = evaluator.finishBundle(); + + assertThat( + result.getUnprocessedElements(), + Matchers.>containsInAnyOrder( + second, WindowedValue.of(1, new Instant(2468L), nonGlobalWindow, PaneInfo.NO_FIRING))); + assertThat(result.getOutputBundles(), Matchers.>contains(outputBundle)); + assertThat(RecorderFn.processed, containsInAnyOrder(1, 3)); + assertThat( + Iterables.getOnlyElement(result.getOutputBundles()).commit(Instant.now()).getElements(), + Matchers.>containsInAnyOrder( + first.withValue(8), + WindowedValue.timestampedValueInGlobalWindow(6, new Instant(2468L)))); + } + + private ParDoInProcessEvaluator createEvaluator( + PCollectionView singletonView, + RecorderFn fn, + InProcessPipelineRunner.CommittedBundle inputBundle, + PCollection output) { + when( + evaluationContext.createSideInputReader( + ImmutableList.>of(singletonView))) + .thenReturn(new ReadyInGlobalWindowReader()); + InProcessExecutionContext executionContext = mock(InProcessExecutionContext.class); + InProcessStepContext stepContext = mock(InProcessStepContext.class); + when(executionContext.getOrCreateStepContext(Mockito.any(String.class), + Mockito.any(String.class), + Mockito.any(StateSampler.class))).thenReturn(stepContext); + when(stepContext.getTimerUpdate()).thenReturn(TimerUpdate.empty()); + when( + evaluationContext.getExecutionContext( + Mockito.any(AppliedPTransform.class), Mockito.any(Object.class))) + .thenReturn(executionContext); + when(evaluationContext.createCounterSet()).thenReturn(new CounterSet()); + + return ParDoInProcessEvaluator.create( + evaluationContext, + inputBundle, + (AppliedPTransform, ?, ?>) output.getProducingTransformInternal(), + fn, + ImmutableList.>of(singletonView), + mainOutputTag, + sideOutputTags, + ImmutableMap., PCollection>of(mainOutputTag, output)); + } + + private static class RecorderFn extends DoFn { + private static Collection processed; + private final PCollectionView view; + + public RecorderFn(PCollectionView view) { + processed = new ArrayList<>(); + this.view = view; + } + + @Override + public void processElement(DoFn.ProcessContext c) throws Exception { + processed.add(c.element()); + c.output(c.element() + c.sideInput(view)); + } + } + + private static class ReadyInGlobalWindowReader implements ReadyCheckingSideInputReader { + @Override + @Nullable + public T get(PCollectionView view, BoundedWindow window) { + if (window.equals(GlobalWindow.INSTANCE)) { + return (T) (Integer) 5; + } + fail("Should only call get in the Global Window, others are not ready"); + throw new AssertionError("Unreachable"); + } + + @Override + public boolean contains(PCollectionView view) { + return true; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public boolean isReady(PCollectionView view, BoundedWindow window) { + return window.equals(GlobalWindow.INSTANCE); + } + } +} From f472b6966439822f01ad580373b0f9160eb890ba Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 10 May 2016 17:11:23 -0700 Subject: [PATCH 386/751] More regularly schedule additional roots This ensures that even when elements are pushed back into the Pipeline Runner, roots are scheduled if necessary. As elements may be rescheduled indefinitely, this is required to ensure that unbounded roots are scheduled during pipeline execution when existing elements are blocked on side inputs. --- .../ExecutorServiceParallelExecutor.java | 46 +------------------ .../inprocess/TransformExecutorServices.java | 25 +++------- .../TransformExecutorServicesTest.java | 40 ++-------------- .../inprocess/TransformExecutorTest.java | 10 +--- 4 files changed, 12 insertions(+), 109 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index b9f83cceea..3d15e45413 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -47,9 +47,7 @@ import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; @@ -74,7 +72,6 @@ final class ExecutorServiceParallelExecutor implements InProcessExecutor { private final InProcessEvaluationContext evaluationContext; private final LoadingCache executorServices; - private final ConcurrentMap, Boolean> scheduledExecutors; private final Queue allUpdates; private final BlockingQueue visibleUpdates; @@ -111,7 +108,6 @@ private ExecutorServiceParallelExecutor( this.transformEnforcements = transformEnforcements; this.evaluationContext = context; - scheduledExecutors = new ConcurrentHashMap<>(); // Weak Values allows TransformExecutorServices that are no longer in use to be reclaimed. // Executing TransformExecutorServices have a strong reference to their TransformExecutorService // which stops the TransformExecutorServices from being prematurely garbage collected @@ -121,8 +117,7 @@ private ExecutorServiceParallelExecutor( this.allUpdates = new ConcurrentLinkedQueue<>(); this.visibleUpdates = new ArrayBlockingQueue<>(20); - parallelExecutorService = - TransformExecutorServices.parallel(executorService, scheduledExecutors); + parallelExecutorService = TransformExecutorServices.parallel(executorService); defaultCompletionCallback = new DefaultCompletionCallback(); } @@ -131,7 +126,7 @@ private ExecutorServiceParallelExecutor( return new CacheLoader() { @Override public TransformExecutorService load(StepAndKey stepAndKey) throws Exception { - return TransformExecutorServices.serial(executorService, scheduledExecutors); + return TransformExecutorServices.serial(executorService); } }; } @@ -450,12 +445,6 @@ private void addWorkIfNecessary(boolean firedTimers) { if (firedTimers) { return; } - for (TransformExecutor executor : scheduledExecutors.keySet()) { - if (!isExecutorBlocked(executor)) { - // We have at least one executor that can proceed without adding additional work - return; - } - } // All current TransformExecutors are blocked; add more work from the roots. for (AppliedPTransform root : rootNodes) { if (!evaluationContext.isDone(root)) { @@ -463,37 +452,6 @@ private void addWorkIfNecessary(boolean firedTimers) { } } } - - /** - * Return true if the provided executor might make more progress if no action is taken. - * - *

          May return false even if all executor threads are currently blocked or cleaning up, as - * these can cause more work to be scheduled. If this does not occur, after these calls - * terminate, future calls will return true if all executors are waiting. - */ - private boolean isExecutorBlocked(TransformExecutor executor) { - Thread thread = executor.getThread(); - if (thread == null) { - return false; - } - switch (thread.getState()) { - case TERMINATED: - throw new IllegalStateException(String.format( - "Unexpectedly encountered a Terminated TransformExecutor %s", executor)); - case WAITING: - case TIMED_WAITING: - // The thread is waiting for some external input. Adding more work may cause the thread - // to stop waiting (e.g. the thread is waiting on an unbounded side input) - return true; - case BLOCKED: - // The executor is blocked on acquisition of a java monitor. This usually means it is - // making a call to the EvaluationContext, but not a model-blocking call - and will - // eventually complete, at which point we may reevaluate. - default: - // NEW and RUNNABLE threads can make progress - return false; - } - } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java index 34efdf694e..a4315ec0c9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java @@ -17,7 +17,6 @@ import com.google.common.base.MoreObjects; -import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; @@ -35,18 +34,16 @@ private TransformExecutorServices() { * Returns an EvaluationState that evaluates {@link TransformExecutor TransformExecutors} in * parallel. */ - public static TransformExecutorService parallel( - ExecutorService executor, Map, Boolean> scheduled) { - return new ParallelEvaluationState(executor, scheduled); + public static TransformExecutorService parallel(ExecutorService executor) { + return new ParallelEvaluationState(executor); } /** * Returns an EvaluationState that evaluates {@link TransformExecutor TransformExecutors} in * serial. */ - public static TransformExecutorService serial( - ExecutorService executor, Map, Boolean> scheduled) { - return new SerialEvaluationState(executor, scheduled); + public static TransformExecutorService serial(ExecutorService executor) { + return new SerialEvaluationState(executor); } /** @@ -58,23 +55,18 @@ public static TransformExecutorService serial( */ private static class ParallelEvaluationState implements TransformExecutorService { private final ExecutorService executor; - private final Map, Boolean> scheduled; - private ParallelEvaluationState( - ExecutorService executor, Map, Boolean> scheduled) { + private ParallelEvaluationState(ExecutorService executor) { this.executor = executor; - this.scheduled = scheduled; } @Override public void schedule(TransformExecutor work) { executor.submit(work); - scheduled.put(work, true); } @Override public void complete(TransformExecutor completed) { - scheduled.remove(completed); } } @@ -88,14 +80,11 @@ public void complete(TransformExecutor completed) { */ private static class SerialEvaluationState implements TransformExecutorService { private final ExecutorService executor; - private final Map, Boolean> scheduled; private AtomicReference> currentlyEvaluating; private final Queue> workQueue; - private SerialEvaluationState( - ExecutorService executor, Map, Boolean> scheduled) { - this.scheduled = scheduled; + private SerialEvaluationState(ExecutorService executor) { this.executor = executor; this.currentlyEvaluating = new AtomicReference<>(); this.workQueue = new ConcurrentLinkedQueue<>(); @@ -120,7 +109,6 @@ public void complete(TransformExecutor completed) { + " but could not complete due to unexpected currently executing " + currentlyEvaluating.get()); } - scheduled.remove(completed); updateCurrentlyEvaluating(); } @@ -131,7 +119,6 @@ private void updateCurrentlyEvaluating() { TransformExecutor newWork = workQueue.poll(); if (newWork != null) { if (currentlyEvaluating.compareAndSet(null, newWork)) { - scheduled.put(newWork, true); executor.submit(newWork); } else { workQueue.offer(newWork); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java index b254f8ec61..1252f861ce 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java @@ -15,17 +15,12 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import static org.hamcrest.Matchers.any; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import com.google.common.util.concurrent.MoreExecutors; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -33,8 +28,6 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; /** @@ -45,12 +38,10 @@ public class TransformExecutorServicesTest { @Rule public ExpectedException thrown = ExpectedException.none(); private ExecutorService executorService; - private Map, Boolean> scheduled; @Before public void setup() { executorService = MoreExecutors.newDirectExecutorService(); - scheduled = new ConcurrentHashMap<>(); } @Test @@ -61,27 +52,15 @@ public void parallelScheduleMultipleSchedulesBothImmediately() { TransformExecutor second = mock(TransformExecutor.class); TransformExecutorService parallel = - TransformExecutorServices.parallel(executorService, scheduled); + TransformExecutorServices.parallel(executorService); parallel.schedule(first); parallel.schedule(second); verify(first).run(); verify(second).run(); - assertThat( - scheduled, - Matchers.allOf( - Matchers., Boolean>hasEntry(first, true), - Matchers., Boolean>hasEntry(second, true))); parallel.complete(first); - assertThat(scheduled, Matchers., Boolean>hasEntry(second, true)); - assertThat( - scheduled, - not( - Matchers., Boolean>hasEntry( - Matchers.>equalTo(first), any(Boolean.class)))); parallel.complete(second); - assertThat(scheduled.isEmpty(), is(true)); } @Test @@ -91,28 +70,15 @@ public void serialScheduleTwoWaitsForFirstToComplete() { @SuppressWarnings("unchecked") TransformExecutor second = mock(TransformExecutor.class); - TransformExecutorService serial = TransformExecutorServices.serial(executorService, scheduled); + TransformExecutorService serial = TransformExecutorServices.serial(executorService); serial.schedule(first); verify(first).run(); serial.schedule(second); verify(second, never()).run(); - assertThat(scheduled, Matchers., Boolean>hasEntry(first, true)); - assertThat( - scheduled, - not( - Matchers., Boolean>hasEntry( - Matchers.>equalTo(second), any(Boolean.class)))); - serial.complete(first); verify(second).run(); - assertThat(scheduled, Matchers., Boolean>hasEntry(second, true)); - assertThat( - scheduled, - not( - Matchers., Boolean>hasEntry( - Matchers.>equalTo(first), any(Boolean.class)))); serial.complete(second); } @@ -124,7 +90,7 @@ public void serialCompleteNotExecutingTaskThrows() { @SuppressWarnings("unchecked") TransformExecutor second = mock(TransformExecutor.class); - TransformExecutorService serial = TransformExecutorServices.serial(executorService, scheduled); + TransformExecutorService serial = TransformExecutorServices.serial(executorService); serial.schedule(first); thrown.expect(IllegalStateException.class); thrown.expectMessage("unexpected currently executing"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index 5335548f6e..fb6c9d8cb4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -52,9 +52,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -76,7 +74,6 @@ public class TransformExecutorTest { private BundleFactory bundleFactory; @Mock private InProcessEvaluationContext evaluationContext; @Mock private TransformEvaluatorRegistry registry; - private Map, Boolean> scheduled; @Before public void setup() { @@ -84,9 +81,8 @@ public void setup() { bundleFactory = InProcessBundleFactory.create(); - scheduled = new HashMap<>(); transformEvaluationState = - TransformExecutorServices.parallel(MoreExecutors.newDirectExecutorService(), scheduled); + TransformExecutorServices.parallel(MoreExecutors.newDirectExecutorService()); evaluatorCompleted = new CountDownLatch(1); completionCallback = new RegisteringCompletionCallback(evaluatorCompleted); @@ -132,7 +128,6 @@ public InProcessTransformResult finishBundle() throws Exception { assertThat(finishCalled.get(), is(true)); assertThat(completionCallback.handledResult, equalTo(result)); assertThat(completionCallback.handledThrowable, is(nullValue())); - assertThat(scheduled, not(Matchers.>hasKey(executor))); } @Test @@ -181,7 +176,6 @@ public InProcessTransformResult finishBundle() throws Exception { assertThat(elementsProcessed, containsInAnyOrder(spam, third, foo)); assertThat(completionCallback.handledResult, equalTo(result)); assertThat(completionCallback.handledThrowable, is(nullValue())); - assertThat(scheduled, not(Matchers.>hasKey(executor))); } @Test @@ -225,7 +219,6 @@ public InProcessTransformResult finishBundle() throws Exception { assertThat(completionCallback.handledResult, is(nullValue())); assertThat(completionCallback.handledThrowable, Matchers.equalTo(exception)); - assertThat(scheduled, not(Matchers.>hasKey(executor))); } @Test @@ -264,7 +257,6 @@ public InProcessTransformResult finishBundle() throws Exception { assertThat(completionCallback.handledResult, is(nullValue())); assertThat(completionCallback.handledThrowable, Matchers.equalTo(exception)); - assertThat(scheduled, not(Matchers.>hasKey(executor))); } @Test From 2a0bfe51ccc9fb25feb633331b1f7ebe7d299f6f Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 10 May 2016 11:27:37 -0700 Subject: [PATCH 387/751] Use an AtomicReference in InProcessSideInputContainer This fixes a TOCTOU race in the contents updating logic, where the determination that the current pane should replace the contents of the side input and the replacement is not a single atomic operation. Using AtomicReference allows the use of compareAndSet to ensure that the replacement can only occur on the pane that the decision to replace was made with. Fixes a race where a pane could be the latest, and replace a pane, but would be lost due to an earlier pane being written between the invalidation and loading of contents. Fixes a race where a reader can incorrectly read an empty iterable as the contents of a PCollectionView, due to occuring between the invalidate and reload steps. --- .../InProcessSideInputContainer.java | 199 ++++++++---------- .../InProcessSideInputContainerTest.java | 95 +++++---- 2 files changed, 147 insertions(+), 147 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java index e6fd49f750..2029865b7a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -30,18 +30,16 @@ import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; import com.google.common.collect.Sets; -import com.google.common.util.concurrent.SettableFuture; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; @@ -51,36 +49,26 @@ * available and writing to a {@link PCollectionView}. */ class InProcessSideInputContainer { - private final InProcessEvaluationContext evaluationContext; private final Collection> containedViews; - private final LoadingCache, - SettableFuture>>> viewByWindows; + private final LoadingCache< + PCollectionViewWindow, AtomicReference>>> + viewByWindows; /** * Create a new {@link InProcessSideInputContainer} with the provided views and the provided * context. */ public static InProcessSideInputContainer create( - InProcessEvaluationContext context, Collection> containedViews) { - CacheLoader, SettableFuture>>> - loader = new CacheLoader, - SettableFuture>>>() { - @Override - public SettableFuture>> load( - PCollectionViewWindow view) { - return SettableFuture.create(); - } - }; - LoadingCache, SettableFuture>>> - viewByWindows = CacheBuilder.newBuilder().build(loader); - return new InProcessSideInputContainer(context, containedViews, viewByWindows); + final InProcessEvaluationContext context, Collection> containedViews) { + LoadingCache, AtomicReference>>> + viewByWindows = CacheBuilder.newBuilder().build(new CallbackSchedulingLoader(context)); + return new InProcessSideInputContainer(containedViews, viewByWindows); } - private InProcessSideInputContainer(InProcessEvaluationContext context, + private InProcessSideInputContainer( Collection> containedViews, - LoadingCache, SettableFuture>>> - viewByWindows) { - this.evaluationContext = context; + LoadingCache, AtomicReference>>> + viewByWindows) { this.containedViews = ImmutableSet.copyOf(containedViews); this.viewByWindows = viewByWindows; } @@ -146,29 +134,75 @@ private Map>> indexValuesByWindow( private void updatePCollectionViewWindowValues( PCollectionView view, BoundedWindow window, Collection> windowValues) { PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, window); - SettableFuture>> future = null; - try { - future = viewByWindows.get(windowedView); - if (future.isDone()) { - Iterator> existingValues = future.get().iterator(); - PaneInfo newPane = windowValues.iterator().next().getPane(); - // The current value may have no elements, if no elements were produced for the window, - // but we are recieving late data. - if (!existingValues.hasNext() - || newPane.getIndex() > existingValues.next().getPane().getIndex()) { - viewByWindows.invalidate(windowedView); - viewByWindows.get(windowedView).set(windowValues); - } - } else { - future.set(windowValues); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - if (future != null && !future.isDone()) { - future.set(Collections.>emptyList()); - } - } catch (ExecutionException e) { - throw new RuntimeException(e.getCause()); + AtomicReference>> contents = + viewByWindows.getUnchecked(windowedView); + if (contents.compareAndSet(null, windowValues)) { + // the value had never been set, so we set it and are done. + return; + } + PaneInfo newPane = windowValues.iterator().next().getPane(); + + Iterable> existingValues; + long existingPane; + do { + existingValues = contents.get(); + existingPane = + Iterables.isEmpty(existingValues) + ? -1L + : existingValues.iterator().next().getPane().getIndex(); + } while (newPane.getIndex() > existingPane + && !contents.compareAndSet(existingValues, windowValues)); + } + + private static class CallbackSchedulingLoader extends + CacheLoader, AtomicReference>>> { + private final InProcessEvaluationContext context; + + public CallbackSchedulingLoader( + InProcessEvaluationContext context) { + this.context = context; + } + + @Override + public AtomicReference>> + load(PCollectionViewWindow view) { + + AtomicReference>> contents = new AtomicReference<>(); + WindowingStrategy windowingStrategy = view.getView().getWindowingStrategyInternal(); + + context.scheduleAfterOutputWouldBeProduced(view.getView(), + view.getWindow(), + windowingStrategy, + new WriteEmptyViewContents(view.getView(), view.getWindow(), contents)); + return contents; + } + } + + private static class WriteEmptyViewContents implements Runnable { + private final PCollectionView view; + private final BoundedWindow window; + private final AtomicReference>> contents; + + private WriteEmptyViewContents(PCollectionView view, BoundedWindow window, + AtomicReference>> contents) { + this.contents = contents; + this.view = view; + this.window = window; + } + + @Override + public void run() { + // The requested window has closed without producing elements, so reflect that in + // the PCollectionView. If set has already been called, will do nothing. + contents.compareAndSet(null, Collections.>emptyList()); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("view", view) + .add("window", window) + .toString(); } } @@ -187,43 +221,23 @@ public boolean isReady(final PCollectionView view, final BoundedWindow window + "Contained views; %s", view, readerViews); - return getViewFuture(view, window).isDone(); + return viewByWindows.getUnchecked(PCollectionViewWindow.of(view, window)).get() != null; } @Override @Nullable public T get(final PCollectionView view, final BoundedWindow window) { - checkArgument( - readerViews.contains(view), "calling get(PCollectionView) with unknown view: " + view); - try { - final Future>> future = getViewFuture(view, window); - // Safe covariant cast - @SuppressWarnings("unchecked") - Iterable> values = (Iterable>) future.get(); - return view.fromIterableInternal(values); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return null; - } catch (ExecutionException e) { - throw new RuntimeException(e); - } - } - - /** - * Gets the future containing the contents of the provided {@link PCollectionView} in the - * provided {@link BoundedWindow}, setting up a callback to populate the future with empty - * contents if necessary. - */ - private Future>> getViewFuture( - final PCollectionView view, final BoundedWindow window) { - PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, window); - final SettableFuture>> future = - viewByWindows.getUnchecked(windowedView); - - WindowingStrategy windowingStrategy = view.getWindowingStrategyInternal(); - evaluationContext.scheduleAfterOutputWouldBeProduced( - view, window, windowingStrategy, new WriteEmptyViewContents(view, window, future)); - return future; + checkArgument(readerViews.contains(view), + "calling get(PCollectionView) with unknown view: " + view); + checkArgument(isReady(view, window), + "calling get(PCollectionView) with view %s that is not ready in window %s", + view, + window); + // Safe covariant cast + @SuppressWarnings("unchecked") Iterable> values = + (Iterable>) viewByWindows + .getUnchecked(PCollectionViewWindow.of(view, window)).get(); + return view.fromIterableInternal(values); } @Override @@ -237,31 +251,4 @@ public boolean isEmpty() { } } - private static class WriteEmptyViewContents implements Runnable { - private final PCollectionView view; - private final BoundedWindow window; - private final SettableFuture>> future; - - private WriteEmptyViewContents(PCollectionView view, BoundedWindow window, - SettableFuture>> future) { - this.future = future; - this.view = view; - this.window = window; - } - - @Override - public void run() { - // The requested window has closed without producing elements, so reflect that in - // the PCollectionView. If set has already been called, will do nothing. - future.set(Collections.>emptyList()); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("view", view) - .add("window", window) - .toString(); - } - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java index 9073a4715e..7ec43b0dfd 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java @@ -20,6 +20,7 @@ import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; import static org.mockito.Mockito.doAnswer; import com.google.cloud.dataflow.sdk.coders.KvCoder; @@ -58,8 +59,10 @@ import java.util.Map; import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; /** * Tests for {@link InProcessSideInputContainer}. @@ -191,46 +194,12 @@ public void getReturnsLatestPaneInWindow() throws Exception { * there is data in the pane. */ @Test - public void getBlocksUntilPaneAvailable() throws Exception { - BoundedWindow window = - new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(1024L); - } - }; - Future singletonFuture = - getFutureOfView( - container.createReaderForViews(ImmutableList.>of(singletonView)), - singletonView, - window); - - WindowedValue singletonValue = - WindowedValue.of(4.75, new Instant(475L), window, PaneInfo.ON_TIME_AND_ONLY_FIRING); - - assertThat(singletonFuture.isDone(), is(false)); - container.write(singletonView, ImmutableList.>of(singletonValue)); - assertThat(singletonFuture.get(), equalTo(4.75)); - } - - @Test - public void withPCollectionViewsWithPutInOriginalReturnsContents() throws Exception { - BoundedWindow window = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(1024L); - } - }; - SideInputReader newReader = - container.createReaderForViews(ImmutableList.>of(singletonView)); - Future singletonFuture = getFutureOfView(newReader, singletonView, window); - - WindowedValue singletonValue = - WindowedValue.of(24.125, new Instant(475L), window, PaneInfo.ON_TIME_AND_ONLY_FIRING); + public void getNotReadyThrows() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("not ready"); - assertThat(singletonFuture.isDone(), is(false)); - container.write(singletonView, ImmutableList.>of(singletonValue)); - assertThat(singletonFuture.get(), equalTo(24.125)); + container.createReaderForViews(ImmutableList.>of(mapView)) + .get(mapView, GlobalWindow.INSTANCE); } @Test @@ -445,15 +414,20 @@ public void isReadyForSomeNotReadyViewsFalseUntilElements() { } @Test - public void isReadyForEmptyWindowTrue() { + public void isReadyForEmptyWindowTrue() throws Exception { + CountDownLatch onComplete = new CountDownLatch(1); immediatelyInvokeCallback(mapView, GlobalWindow.INSTANCE); + CountDownLatch latch = invokeLatchedCallback(singletonView, GlobalWindow.INSTANCE, onComplete); ReadyCheckingSideInputReader reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView)); assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(true)); assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); - immediatelyInvokeCallback(singletonView, GlobalWindow.INSTANCE); + latch.countDown(); + if (!onComplete.await(1500L, TimeUnit.MILLISECONDS)) { + fail("Callback to set empty values did not complete!"); + } assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(true)); } @@ -480,6 +454,45 @@ public Void answer(InvocationOnMock invocation) throws Throwable { Mockito.any(Runnable.class)); } + /** + * When a callAfterWindowCloses with the specified view's producing transform, window, and + * windowing strategy is invoked, start a thread that will invoke the callback after the returned + * {@link CountDownLatch} is counted down once. + */ + private CountDownLatch invokeLatchedCallback( + PCollectionView view, BoundedWindow window, final CountDownLatch onComplete) { + final CountDownLatch runLatch = new CountDownLatch(1); + doAnswer( + new Answer() { + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + Object callback = invocation.getArguments()[3]; + final Runnable callbackRunnable = (Runnable) callback; + Executors.newSingleThreadExecutor().submit(new Runnable() { + public void run() { + try { + if (!runLatch.await(1500L, TimeUnit.MILLISECONDS)) { + fail("Run latch didn't count down within timeout"); + } + callbackRunnable.run(); + onComplete.countDown(); + } catch (InterruptedException e) { + fail("Unexpectedly interrupted while waiting for latch to be counted down"); + } + } + }); + return null; + } + }) + .when(context) + .scheduleAfterOutputWouldBeProduced( + Mockito.eq(view), + Mockito.eq(window), + Mockito.eq(view.getWindowingStrategyInternal()), + Mockito.any(Runnable.class)); + return runLatch; + } + private Future getFutureOfView(final SideInputReader myReader, final PCollectionView view, final BoundedWindow window) { Callable callable = new Callable() { From 11ea9e24795fa22ad5a5e21811c1d4f5b9483aaa Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 10 May 2016 13:22:20 -0700 Subject: [PATCH 388/751] Cache read SideInput Contents in the InProcessSideInputContainer This ensures that while processing a bundle all elements see the same contents for any SideInput Window. --- .../InProcessSideInputContainer.java | 33 +++++++++++++++---- .../InProcessEvaluationContextTest.java | 3 ++ .../InProcessSideInputContainerTest.java | 15 +++++++-- 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java index 2029865b7a..6bb223ff34 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -26,6 +26,7 @@ import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.common.base.MoreObjects; +import com.google.common.base.Optional; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -208,9 +209,13 @@ public String toString() { private final class SideInputContainerSideInputReader implements ReadyCheckingSideInputReader { private final Collection> readerViews; + private final LoadingCache< + PCollectionViewWindow, Optional>>> + viewContents; private SideInputContainerSideInputReader(Collection> readerViews) { this.readerViews = ImmutableSet.copyOf(readerViews); + this.viewContents = CacheBuilder.newBuilder().build(new CurrentViewContentsLoader()); } @Override @@ -221,22 +226,23 @@ public boolean isReady(final PCollectionView view, final BoundedWindow window + "Contained views; %s", view, readerViews); - return viewByWindows.getUnchecked(PCollectionViewWindow.of(view, window)).get() != null; + return viewContents.getUnchecked(PCollectionViewWindow.of(view, window)).isPresent(); } @Override @Nullable public T get(final PCollectionView view, final BoundedWindow window) { - checkArgument(readerViews.contains(view), - "calling get(PCollectionView) with unknown view: " + view); - checkArgument(isReady(view, window), - "calling get(PCollectionView) with view %s that is not ready in window %s", + checkArgument( + readerViews.contains(view), "calling get(PCollectionView) with unknown view: " + view); + checkArgument( + isReady(view, window), + "calling get() on a PCollectionView %s that is not ready in window %s", view, window); // Safe covariant cast @SuppressWarnings("unchecked") Iterable> values = - (Iterable>) viewByWindows - .getUnchecked(PCollectionViewWindow.of(view, window)).get(); + (Iterable>) viewContents.getUnchecked(PCollectionViewWindow.of(view, + window)).get(); return view.fromIterableInternal(values); } @@ -251,4 +257,17 @@ public boolean isEmpty() { } } + /** + * A {@link CacheLoader} that loads the current contents of a {@link PCollectionViewWindow} into + * an optional. + */ + private class CurrentViewContentsLoader extends CacheLoader< + PCollectionViewWindow, Optional>>> { + + @Override + public Optional>> + load(PCollectionViewWindow key) { + return Optional.fromNullable(viewByWindows.getUnchecked(key).get()); + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index 7cfb63a84b..086f7642f6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -147,6 +147,9 @@ public void writeToViewWriterThenReadReads() { WindowedValue.of( 4444, new Instant(8677L), second, PaneInfo.createPane(false, true, Timing.LATE, 1, 1)); viewWriter.add(Collections.singleton(overrittenSecondValue)); + assertThat(reader.get(view, second), containsInAnyOrder(2)); + // The cached value is served in the earlier reader + reader = context.createSideInputReader(ImmutableList.>of(view)); assertThat(reader.get(view, second), containsInAnyOrder(4444)); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java index 7ec43b0dfd..a46747622a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java @@ -396,7 +396,8 @@ public void isReadyForSomeNotReadyViewsFalseUntilElements() { FIRST_WINDOW.maxTimestamp().minus(100L), FIRST_WINDOW, PaneInfo.ON_TIME_AND_ONLY_FIRING))); - assertThat(reader.isReady(mapView, FIRST_WINDOW), is(true)); + // Cached value is false + assertThat(reader.isReady(mapView, FIRST_WINDOW), is(false)); container.write( singletonView, @@ -407,10 +408,15 @@ public void isReadyForSomeNotReadyViewsFalseUntilElements() { SECOND_WINDOW, PaneInfo.ON_TIME_AND_ONLY_FIRING))); assertThat(reader.isReady(mapView, SECOND_WINDOW), is(true)); - assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(true)); + assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(false)); assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(false)); assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); + + reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView)); + assertThat(reader.isReady(mapView, SECOND_WINDOW), is(true)); + assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(true)); + assertThat(reader.isReady(mapView, FIRST_WINDOW), is(true)); } @Test @@ -428,6 +434,11 @@ public void isReadyForEmptyWindowTrue() throws Exception { if (!onComplete.await(1500L, TimeUnit.MILLISECONDS)) { fail("Callback to set empty values did not complete!"); } + // The cached value was false, so it continues to be true + assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); + + // A new reader for the same container gets a fresh look + reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView)); assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(true)); } From 5a2ebe0424541a0dc6a97db4b15ec9abd590e0e0 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 9 May 2016 15:47:27 -0700 Subject: [PATCH 389/751] Minor checkArgument style fix --- .../sdk/runners/inprocess/InProcessSideInputContainer.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java index 6bb223ff34..d0199e079a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java @@ -232,11 +232,12 @@ public boolean isReady(final PCollectionView view, final BoundedWindow window @Override @Nullable public T get(final PCollectionView view, final BoundedWindow window) { - checkArgument( - readerViews.contains(view), "calling get(PCollectionView) with unknown view: " + view); + checkArgument(readerViews.contains(view), + "call to get(PCollectionView) with unknown view: %s", + view); checkArgument( isReady(view, window), - "calling get() on a PCollectionView %s that is not ready in window %s", + "calling get() on PCollectionView %s that is not ready in window %s", view, window); // Safe covariant cast From 926f9ba5afa15b7759d211e160e374085a392552 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 2 May 2016 17:26:47 -0700 Subject: [PATCH 390/751] Update Watermarks Outside of handleResult Remove excess mutual exclusion --- .../inprocess/InMemoryWatermarkManager.java | 113 +++++++++++++++--- .../inprocess/InProcessEvaluationContext.java | 14 ++- .../inprocess/WatermarkCallbackExecutor.java | 9 +- .../InMemoryWatermarkManagerTest.java | 58 +++++++-- .../InProcessEvaluationContextTest.java | 8 +- .../WatermarkCallbackExecutorTest.java | 4 +- 6 files changed, 169 insertions(+), 37 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index d64e980e4c..992c13f5ab 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -15,6 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.auto.value.AutoValue; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -54,6 +55,7 @@ import java.util.PriorityQueue; import java.util.Set; import java.util.TreeSet; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; @@ -682,6 +684,17 @@ private static Map> extractFiredTimers( */ private final Map, TransformWatermarks> transformToWatermarks; + /** + * A queue of pending updates to the state of this {@link InMemoryWatermarkManager}. + */ + private final ConcurrentLinkedQueue pendingUpdates; + + /** + * A queue of pending {@link AppliedPTransform AppliedPTransforms} that have potentially + * stale data. + */ + private final ConcurrentLinkedQueue> pendingRefreshes; + /** * Creates a new {@link InMemoryWatermarkManager}. All watermarks within the newly created * {@link InMemoryWatermarkManager} start at {@link BoundedWindow#TIMESTAMP_MIN_VALUE}, the @@ -704,6 +717,8 @@ private InMemoryWatermarkManager( Map>> consumers) { this.clock = clock; this.consumers = consumers; + this.pendingUpdates = new ConcurrentLinkedQueue<>(); + this.pendingRefreshes = new ConcurrentLinkedQueue<>(); transformToWatermarks = new HashMap<>(); @@ -807,27 +822,38 @@ public void updateWatermarks( @Nullable CommittedBundle completed, TimerUpdate timerUpdate, CommittedResult result, - @Nullable Instant earliestHold) { - AppliedPTransform transform = result.getTransform(); - updatePending(completed, timerUpdate, result); - TransformWatermarks transformWms = transformToWatermarks.get(transform); - transformWms.setEventTimeHold(completed == null ? null : completed.getKey(), earliestHold); - refreshWatermarks(transform); + Instant earliestHold) { + pendingUpdates.offer(PendingWatermarkUpdate.create(completed, + timerUpdate, + result, + earliestHold)); } - private void refreshWatermarks(AppliedPTransform transform) { - TransformWatermarks myWatermarks = transformToWatermarks.get(transform); - WatermarkUpdate updateResult = myWatermarks.refresh(); - if (updateResult.isAdvanced()) { - for (PValue outputPValue : transform.getOutput().expand()) { - Collection> downstreamTransforms = consumers.get(outputPValue); - if (downstreamTransforms != null) { - for (AppliedPTransform downstreamTransform : downstreamTransforms) { - refreshWatermarks(downstreamTransform); - } - } - } - } + /** + * Applies all pending updates to this {@link InMemoryWatermarkManager}, causing the pending state + * of all {@link TransformWatermarks} to be advanced as far as possible. + */ + private void applyPendingUpdates() { + Set> updatedTransforms = new HashSet<>(); + PendingWatermarkUpdate pending = pendingUpdates.poll(); + while (pending != null) { + applyPendingUpdate(pending); + updatedTransforms.add(pending.getTransform()); + pending = pendingUpdates.poll(); + } + pendingRefreshes.addAll(updatedTransforms); + } + + private void applyPendingUpdate(PendingWatermarkUpdate pending) { + CommittedResult result = pending.getResult(); + AppliedPTransform transform = result.getTransform(); + CommittedBundle inputBundle = pending.getInputBundle(); + + updatePending(inputBundle, pending.getTimerUpdate(), result); + + TransformWatermarks transformWms = transformToWatermarks.get(transform); + transformWms.setEventTimeHold(inputBundle == null ? null : inputBundle.getKey(), + pending.getEarliestHold()); } /** @@ -867,6 +893,29 @@ private void updatePending( } } + /** + * Refresh the watermarks contained within this {@link InMemoryWatermarkManager}, causing all + * watermarks to be advanced as far as possible. + */ + synchronized void refreshAll() { + applyPendingUpdates(); + while (!pendingRefreshes.isEmpty()) { + refreshWatermarks(pendingRefreshes.poll()); + } + } + + private void refreshWatermarks(AppliedPTransform toRefresh) { + TransformWatermarks myWatermarks = transformToWatermarks.get(toRefresh); + WatermarkUpdate updateResult = myWatermarks.refresh(); + Set> additionalRefreshes = new HashSet<>(); + if (updateResult.isAdvanced()) { + for (PValue outputPValue : toRefresh.getOutput().expand()) { + additionalRefreshes.addAll(consumers.get(outputPValue)); + } + } + pendingRefreshes.addAll(additionalRefreshes); + } + /** * Returns a map of each {@link PTransform} that has pending timers to those timers. All of the * pending timers will be removed from this {@link InMemoryWatermarkManager}. @@ -1335,4 +1384,30 @@ public int compare(WindowedValue o1, WindowedValue o2) { } return result; } + + @AutoValue + abstract static class PendingWatermarkUpdate { + @Nullable + public abstract CommittedBundle getInputBundle(); + public abstract TimerUpdate getTimerUpdate(); + public abstract CommittedResult getResult(); + public abstract Instant getEarliestHold(); + + /** + * Gets the {@link AppliedPTransform} that generated this result. + */ + public AppliedPTransform getTransform() { + return getResult().getTransform(); + } + + public static PendingWatermarkUpdate create( + CommittedBundle inputBundle, + TimerUpdate timerUpdate, + CommittedResult result, Instant earliestHold) { + return new AutoValue_InMemoryWatermarkManager_PendingWatermarkUpdate(inputBundle, + timerUpdate, + result, + earliestHold); + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index fb5727e8fb..ac00503dc9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -40,6 +40,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; @@ -48,6 +49,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executors; import javax.annotation.Nullable; @@ -125,7 +127,7 @@ private InProcessEvaluationContext( this.applicationStateInternals = new ConcurrentHashMap<>(); this.mergedCounters = new CounterSet(); - this.callbackExecutor = WatermarkCallbackExecutor.create(); + this.callbackExecutor = WatermarkCallbackExecutor.create(Executors.newSingleThreadExecutor()); } /** @@ -143,7 +145,7 @@ private InProcessEvaluationContext( * @param result the result of evaluating the input bundle * @return the committed bundles contained within the handled {@code result} */ - public synchronized CommittedResult handleResult( + public CommittedResult handleResult( @Nullable CommittedBundle completedBundle, Iterable completedTimers, InProcessTransformResult result) { @@ -160,7 +162,6 @@ public synchronized CommittedResult handleResult( result.getTimerUpdate().withCompletedTimers(completedTimers), committedResult, result.getWatermarkHold()); - fireAllAvailableCallbacks(); // Update counters if (result.getCounters() != null) { mergedCounters.merge(result.getCounters()); @@ -355,6 +356,12 @@ public CounterSet getCounters() { return mergedCounters; } + @VisibleForTesting + void forceRefresh() { + watermarkManager.refreshAll(); + fireAllAvailableCallbacks(); + } + /** * Extracts all timers that have been fired and have not already been extracted. * @@ -362,6 +369,7 @@ public CounterSet getCounters() { * for each time they are set. */ public Map, Map> extractFiredTimers() { + forceRefresh(); Map, Map> fired = watermarkManager.extractFiredTimers(); return fired; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java index 27d59b9a64..e240544d17 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java @@ -27,7 +27,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; /** * Executes callbacks that occur based on the progression of the watermark per-step. @@ -49,17 +48,17 @@ class WatermarkCallbackExecutor { /** * Create a new {@link WatermarkCallbackExecutor}. */ - public static WatermarkCallbackExecutor create() { - return new WatermarkCallbackExecutor(); + public static WatermarkCallbackExecutor create(ExecutorService executor) { + return new WatermarkCallbackExecutor(executor); } private final ConcurrentMap, PriorityQueue> callbacks; private final ExecutorService executor; - private WatermarkCallbackExecutor() { + private WatermarkCallbackExecutor(ExecutorService executor) { this.callbacks = new ConcurrentHashMap<>(); - this.executor = Executors.newSingleThreadExecutor(); + this.executor = executor; } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index c2abd9aa0e..83e33d9cb7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -164,6 +164,7 @@ public void getWatermarkForUpdatedSourceTransform() { null, Collections.>singleton(output)), new Instant(8000L)); + manager.refreshAll(); TransformWatermarks updatedSourceWatermark = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -184,6 +185,7 @@ public void getWatermarkForMultiInputTransform() { null, Collections.>singleton(secondPcollectionBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); // We didn't do anything for the first source, so we shouldn't have progressed the watermark TransformWatermarks firstSourceWatermark = @@ -216,7 +218,7 @@ public void getWatermarkForMultiInputTransform() { result(flattened.getProducingTransformInternal(), secondPcollectionBundle.withElements(Collections.>emptyList()), Collections.>singleton(flattenedBundleSecondCreate)), - null); + BoundedWindow.TIMESTAMP_MAX_VALUE); TransformWatermarks transformAfterProcessing = manager.getWatermarks(flattened.getProducingTransformInternal()); manager.updateWatermarks(secondPcollectionBundle, @@ -224,7 +226,8 @@ public void getWatermarkForMultiInputTransform() { result(flattened.getProducingTransformInternal(), secondPcollectionBundle.withElements(Collections.>emptyList()), Collections.>singleton(flattenedBundleSecondCreate)), - null); + BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); assertThat( transformAfterProcessing.getInputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); @@ -242,7 +245,8 @@ public void getWatermarkForMultiInputTransform() { result(createdInts.getProducingTransformInternal(), null, Collections.>singleton(firstPcollectionBundle)), - new Instant(Long.MAX_VALUE)); + BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks firstSourceWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( @@ -273,7 +277,8 @@ public void getWatermarkForMultiInputTransform() { result(flattened.getProducingTransformInternal(), firstPcollectionBundle.withElements(Collections.>emptyList()), Collections.>singleton(completedFlattenBundle)), - null); + BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks afterConsumingAllInput = manager.getWatermarks(flattened.getProducingTransformInternal()); assertThat( @@ -299,6 +304,7 @@ public void getWatermarkForMultiConsumedCollection() { null, Collections.>singleton(createdBundle)), new Instant(Long.MAX_VALUE)); + manager.refreshAll(); TransformWatermarks createdAfterProducing = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat( @@ -314,7 +320,8 @@ public void getWatermarkForMultiConsumedCollection() { result(keyed.getProducingTransformInternal(), createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), - null); + BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -334,7 +341,8 @@ public void getWatermarkForMultiConsumedCollection() { result(filtered.getProducingTransformInternal(), createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), - null); + BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks filteredProcessedWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat( @@ -372,6 +380,7 @@ public void updateWatermarkWithWatermarkHolds() { createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), new Instant(500L)); + manager.refreshAll(); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -415,6 +424,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { secondKeyBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), new Instant(1234L)); + manager.refreshAll(); TransformWatermarks filteredWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -430,6 +440,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { fauxFirstKeyTimerBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(1234L))); @@ -441,6 +452,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { fauxSecondKeyTimerBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), new Instant(5678L)); + manager.refreshAll(); assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(5678L))); manager.updateWatermarks(fauxSecondKeyTimerBundle, @@ -449,6 +461,7 @@ public void updateWatermarkWithKeyedWatermarkHolds() { fauxSecondKeyTimerBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); assertThat(filteredWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); } @@ -466,6 +479,7 @@ public void updateOutputWatermarkShouldBeMonotonic() { null, Collections.>singleton(firstInput)), new Instant(0L)); + manager.refreshAll(); TransformWatermarks firstWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); @@ -478,6 +492,7 @@ public void updateOutputWatermarkShouldBeMonotonic() { null, Collections.>singleton(secondInput)), new Instant(-250L)); + manager.refreshAll(); TransformWatermarks secondWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); @@ -510,6 +525,7 @@ public void updateWatermarkWithHoldsShouldBeMonotonic() { createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), new Instant(500L)); + manager.refreshAll(); TransformWatermarks keyedWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat( @@ -586,7 +602,8 @@ public void updateWatermarkWithLateData() { result(keyed.getProducingTransformInternal(), createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(keyBundle)), - null); + BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks onTimeWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); @@ -602,6 +619,7 @@ public void updateWatermarkWithLateData() { createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(lateDataBundle)), new Instant(2_000_000L)); + manager.refreshAll(); TransformWatermarks bufferedLateWm = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); @@ -620,7 +638,8 @@ public void updateWatermarkWithLateData() { result(keyed.getProducingTransformInternal(), lateDataBundle.withElements(Collections.>emptyList()), Collections.>singleton(lateKeyedBundle)), - null); + BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); } public void updateWatermarkWithDifferentWindowedValueInstances() { @@ -643,6 +662,7 @@ public void updateWatermarkWithDifferentWindowedValueInstances() { createdBundle.withElements(Collections.>emptyList()), Collections.>emptyList()), null); + manager.refreshAll(); TransformWatermarks onTimeWatermarks = manager.getWatermarks(keyed.getProducingTransformInternal()); assertThat(onTimeWatermarks.getInputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); @@ -661,6 +681,7 @@ public void getWatermarksAfterOnlyEmptyOutput() { null, Collections.>singleton(emptyCreateOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks updatedSourceWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -699,6 +720,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { firstCreateOutput.withElements(Collections.>emptyList()), Collections.>singleton(firstFilterOutput)), new Instant(10_000L)); + manager.refreshAll(); TransformWatermarks firstFilterWatermarks = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat(firstFilterWatermarks.getInputWatermark(), not(earlierThan(new Instant(12_000L)))); @@ -711,6 +733,7 @@ public void getWatermarksAfterHoldAndEmptyOutput() { null, Collections.>singleton(emptyCreateOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks updatedSourceWatermarks = manager.getWatermarks(createdInts.getProducingTransformInternal()); @@ -754,6 +777,7 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { null, Collections.>singleton(createOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(clock.now())); @@ -784,6 +808,7 @@ public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { createOutput.withElements(Collections.>emptyList()), Collections.>singleton(filterOutputBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks filterAfterConsumed = manager.getWatermarks(filtered.getProducingTransformInternal()); assertThat( @@ -809,6 +834,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { null, Collections.>singleton(createdBundle)), new Instant(1248L)); + manager.refreshAll(); TransformWatermarks filteredWms = manager.getWatermarks(filtered.getProducingTransformInternal()); @@ -830,6 +856,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); Instant startTime = clock.now(); clock.set(startTime.plus(250L)); // We're held based on the past timer @@ -868,6 +895,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { filteredTimerBundle.withElements(Collections.>emptyList()), Collections.>singleton(filteredTimerResult)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); clock.set(startTime.plus(500L)); assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); @@ -882,6 +910,7 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { filteredTimerResult.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); clock.set(new Instant(Long.MAX_VALUE)); @@ -920,6 +949,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { null, Collections.>singleton(createOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks createAfterUpdate = manager.getWatermarks(createdInts.getProducingTransformInternal()); assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); @@ -934,6 +964,7 @@ public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { null, Collections.>singleton(createSecondOutput)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); } @@ -947,6 +978,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( null, Collections.>singleton(created)), new Instant(40_900L)); + manager.refreshAll(); CommittedBundle filteredBundle = multiWindowedBundle(filtered, 2, 4); Instant upstreamHold = new Instant(2048L); @@ -958,6 +990,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( created.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks downstreamWms = manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); @@ -979,6 +1012,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( otherCreated.withElements(Collections.>emptyList()), Collections.>emptyList()), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); assertThat(downstreamWms.getSynchronizedProcessingInputTime(), not(earlierThan(clock.now()))); } @@ -1004,6 +1038,7 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { created.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), BoundedWindow.TIMESTAMP_MAX_VALUE); + manager.refreshAll(); TransformWatermarks downstreamWms = manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); @@ -1028,6 +1063,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { null, Collections.singleton(createdBundle)), new Instant(1500L)); + manager.refreshAll(); TimerData earliestTimer = TimerData.of(StateNamespaces.global(), new Instant(1000), TimeDomain.EVENT_TIME); @@ -1049,6 +1085,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); + manager.refreshAll(); Map, Map> firstTransformFiredTimers = manager.extractFiredTimers(); @@ -1066,6 +1103,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { null, Collections.>emptyList()), new Instant(50_000L)); + manager.refreshAll(); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( @@ -1115,6 +1153,7 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); + manager.refreshAll(); Map, Map> firstTransformFiredTimers = manager.extractFiredTimers(); @@ -1133,6 +1172,7 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { null, Collections.>emptyList()), new Instant(50_000L)); + manager.refreshAll(); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( @@ -1182,6 +1222,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { createdBundle.withElements(Collections.>emptyList()), Collections.>singleton(multiWindowedBundle(intsToFlatten))), new Instant(1000L)); + manager.refreshAll(); Map, Map> firstTransformFiredTimers = manager.extractFiredTimers(); @@ -1201,6 +1242,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { null, Collections.>emptyList()), new Instant(50_000L)); + manager.refreshAll(); Map, Map> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index 7cfb63a84b..76cc1cbf6b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -314,7 +314,6 @@ public void run() { .build(); context.handleResult(null, ImmutableList.of(), result); - // Difficult to demonstrate that we took no action in a multithreaded world; poll for a bit // will likely be flaky if this logic is broken assertThat(callLatch.await(500L, TimeUnit.MILLISECONDS), is(false)); @@ -322,6 +321,7 @@ public void run() { InProcessTransformResult finishedResult = StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); context.handleResult(null, ImmutableList.of(), finishedResult); + context.forceRefresh(); // Obtain the value via blocking call assertThat(callLatch.await(1, TimeUnit.SECONDS), is(true)); } @@ -333,6 +333,7 @@ public void callAfterOutputMustHaveBeenProducedAlreadyAfterCallsImmediately() th context.handleResult(null, ImmutableList.of(), finishedResult); final CountDownLatch callLatch = new CountDownLatch(1); + context.extractFiredTimers(); Runnable callback = new Runnable() { @Override @@ -423,6 +424,7 @@ public void isDoneWithUnboundedPCollectionAndShutdown() { null, ImmutableList.of(), StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); + context.extractFiredTimers(); assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(true)); } @@ -447,6 +449,7 @@ public void isDoneWithOnlyBoundedPCollections() { null, ImmutableList.of(), StepTransformResult.withoutHold(created.getProducingTransformInternal()).build()); + context.extractFiredTimers(); assertThat(context.isDone(created.getProducingTransformInternal()), is(true)); } @@ -479,6 +482,7 @@ public void isDoneWithPartiallyDone() { ImmutableList.of(), StepTransformResult.withoutHold(consumers).build()); } + context.extractFiredTimers(); assertThat(context.isDone(), is(true)); } @@ -499,12 +503,14 @@ public void isDoneWithUnboundedAndNotShutdown() { context.createRootBundle(created).commit(Instant.now()), ImmutableList.of(), StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build()); + context.extractFiredTimers(); assertThat(context.isDone(), is(false)); context.handleResult( context.createRootBundle(created).commit(Instant.now()), ImmutableList.of(), StepTransformResult.withoutHold(view.getProducingTransformInternal()).build()); + context.extractFiredTimers(); assertThat(context.isDone(), is(false)); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java index be3e062fbd..50d56abb04 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java @@ -38,6 +38,7 @@ import org.junit.runners.JUnit4; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** @@ -45,7 +46,8 @@ */ @RunWith(JUnit4.class) public class WatermarkCallbackExecutorTest { - private WatermarkCallbackExecutor executor = WatermarkCallbackExecutor.create(); + private WatermarkCallbackExecutor executor = + WatermarkCallbackExecutor.create(Executors.newSingleThreadExecutor()); private AppliedPTransform create; private AppliedPTransform sum; From e20418b4f33fc1aeb3da3597e928ca69bc995ecd Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 10 May 2016 15:09:00 -0700 Subject: [PATCH 391/751] Switch to using a FixedThreadPool by default Reduces the number of active threads, which should improve scheduling behavior. Additionally improves caching behavior of ParDo evaluators due to increased reuse of DoFns. --- ...a => FixedThreadPoolExecutorServiceFactory.java} | 13 +++++++------ .../runners/inprocess/InProcessPipelineOptions.java | 4 ++-- 2 files changed, 9 insertions(+), 8 deletions(-) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/{CachedThreadPoolExecutorServiceFactory.java => FixedThreadPoolExecutorServiceFactory.java} (69%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CachedThreadPoolExecutorServiceFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FixedThreadPoolExecutorServiceFactory.java similarity index 69% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CachedThreadPoolExecutorServiceFactory.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FixedThreadPoolExecutorServiceFactory.java index 3350d2b4d5..d71b1b0ae8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CachedThreadPoolExecutorServiceFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FixedThreadPoolExecutorServiceFactory.java @@ -22,13 +22,14 @@ import java.util.concurrent.Executors; /** - * A {@link ExecutorServiceFactory} that produces cached thread pools via - * {@link Executors#newCachedThreadPool()}. + * A {@link ExecutorServiceFactory} that produces fixed thread pools via + * {@link Executors#newFixedThreadPool(int)}, with the number of threads equal to the available + * processors as provided by {@link Runtime#availableProcessors()}. */ -class CachedThreadPoolExecutorServiceFactory +class FixedThreadPoolExecutorServiceFactory implements DefaultValueFactory, ExecutorServiceFactory { - private static final CachedThreadPoolExecutorServiceFactory INSTANCE = - new CachedThreadPoolExecutorServiceFactory(); + private static final FixedThreadPoolExecutorServiceFactory INSTANCE = + new FixedThreadPoolExecutorServiceFactory(); @Override public ExecutorServiceFactory create(PipelineOptions options) { @@ -37,6 +38,6 @@ public ExecutorServiceFactory create(PipelineOptions options) { @Override public ExecutorService create() { - return Executors.newCachedThreadPool(); + return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java index 9c10510bf9..e904ec46ce 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java @@ -41,13 +41,13 @@ public interface InProcessPipelineOptions extends PipelineOptions, ApplicationNa * it cannot enter a state in which it will not schedule additional pending work unless currently * scheduled work completes, as this may cause the {@link Pipeline} to cease processing. * - *

          Defaults to a {@link CachedThreadPoolExecutorServiceFactory}, which produces instances of + *

          Defaults to a {@link FixedThreadPoolExecutorServiceFactory}, which produces instances of * {@link Executors#newCachedThreadPool()}. */ @JsonIgnore @Required @Hidden - @Default.InstanceFactory(CachedThreadPoolExecutorServiceFactory.class) + @Default.InstanceFactory(FixedThreadPoolExecutorServiceFactory.class) ExecutorServiceFactory getExecutorServiceFactory(); void setExecutorServiceFactory(ExecutorServiceFactory executorService); From e24938437500b610576971aace43514309dce2c2 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 12 May 2016 17:56:17 -0700 Subject: [PATCH 392/751] Run RunnableOnServiceTests with the InProcessPipelineRunner --- sdk/pom.xml | 27 +++++++++++++++++++ .../sdk/testing/DataflowAssertTest.java | 4 ++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index 40d9c5cf98..11b836b3fd 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -141,6 +141,33 @@ maven-compiler-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + InProcessPipelineRunnerTests + integration-test + + test + + + com.google.cloud.dataflow.sdk.testing.RunnableOnService + none + true + + false + + [ + "--runner=InProcessPipelineRunner" + ] + + + + + + + org.apache.maven.plugins maven-dependency-plugin diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java index 2cd3014b11..0380bb6be8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java @@ -27,6 +27,7 @@ import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; @@ -302,7 +303,8 @@ public void testContainsInAnyOrderFalse() throws Exception { private static Throwable runExpectingAssertionFailure(Pipeline pipeline) { // Even though this test will succeed or fail adequately whether local or on the service, // it results in a different exception depending on the runner. - if (pipeline.getRunner() instanceof DirectPipelineRunner) { + if (pipeline.getRunner() instanceof DirectPipelineRunner + || pipeline.getRunner() instanceof InProcessPipelineRunner) { // We cannot use thrown.expect(AssertionError.class) because the AssertionError // is first caught by JUnit and causes a test failure. try { From 2b056751ffea2a769e36afa9cc5b844dacb494fa Mon Sep 17 00:00:00 2001 From: peihe Date: Fri, 13 May 2016 11:14:32 -0700 Subject: [PATCH 393/751] Backport PR from Beam: Move copy and remove from FileBasedSink to GcsUtil. (#248) --- .../cloud/dataflow/sdk/io/FileBasedSink.java | 223 +----------------- .../cloud/dataflow/sdk/util/GcsUtil.java | 166 ++++++++++++- 2 files changed, 171 insertions(+), 218 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index 4555389a38..e9d280d707 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -16,36 +16,17 @@ package com.google.cloud.dataflow.sdk.io; -import com.google.api.client.googleapis.batch.BatchRequest; -import com.google.api.client.googleapis.batch.json.JsonBatchCallback; -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.http.HttpHeaders; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.services.storage.Storage; -import com.google.api.services.storage.StorageRequest; -import com.google.api.services.storage.model.StorageObject; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.options.GcsOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.FileIOChannelFactory; import com.google.cloud.dataflow.sdk.util.GcsIOChannelFactory; +import com.google.cloud.dataflow.sdk.util.GcsUtil; +import com.google.cloud.dataflow.sdk.util.GcsUtil.GcsUtilFactory; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.base.Preconditions; import org.slf4j.Logger; @@ -61,11 +42,8 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.LinkedList; import java.util.List; -import javax.annotation.concurrent.NotThreadSafe; - /** * Abstract {@link Sink} for file-based output. An implementation of FileBasedSink writes file-based * output and defines the format of output files (how values are written, headers/footers, MIME @@ -618,80 +596,20 @@ private static interface FileOperations { * GCS file system operations. */ private static class GcsOperations implements FileOperations { - private static final Logger LOG = LoggerFactory.getLogger(GcsOperations.class); - - /** - * Maximum number of requests permitted in a GCS batch request. - */ - private static final int MAX_REQUESTS_PER_BATCH = 1000; - - private ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); - private GcsOptions gcsOptions; - private Storage gcs; - private BatchHelper batchHelper; + private final GcsUtil gcsUtil; public GcsOperations(PipelineOptions options) { - gcsOptions = options.as(GcsOptions.class); - gcs = Transport.newStorageClient(gcsOptions).build(); - batchHelper = - new BatchHelper(gcs.getRequestFactory().getInitializer(), gcs, MAX_REQUESTS_PER_BATCH); + gcsUtil = new GcsUtilFactory().create(options); } @Override public void copy(List srcFilenames, List destFilenames) throws IOException { - Preconditions.checkArgument( - srcFilenames.size() == destFilenames.size(), - String.format("Number of source files {} must equal number of destination files {}", - srcFilenames.size(), destFilenames.size())); - for (int i = 0; i < srcFilenames.size(); i++) { - final GcsPath sourcePath = GcsPath.fromUri(srcFilenames.get(i)); - final GcsPath destPath = GcsPath.fromUri(destFilenames.get(i)); - LOG.debug("Copying {} to {}", sourcePath, destPath); - Storage.Objects.Copy copyObject = gcs.objects().copy(sourcePath.getBucket(), - sourcePath.getObject(), destPath.getBucket(), destPath.getObject(), null); - batchHelper.queue(copyObject, new JsonBatchCallback() { - @Override - public void onSuccess(StorageObject obj, HttpHeaders responseHeaders) { - LOG.debug("Successfully copied {} to {}", sourcePath, destPath); - } - - @Override - public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { - // Do nothing on item not found. - if (!errorExtractor.itemNotFound(e)) { - throw new IOException(e.toString()); - } - LOG.debug("{} does not exist.", sourcePath); - } - }); - } - batchHelper.flush(); + gcsUtil.copy(srcFilenames, destFilenames); } @Override public void remove(Collection filenames) throws IOException { - for (String filename : filenames) { - final GcsPath path = GcsPath.fromUri(filename); - LOG.debug("Removing: " + path); - Storage.Objects.Delete deleteObject = - gcs.objects().delete(path.getBucket(), path.getObject()); - batchHelper.queue(deleteObject, new JsonBatchCallback() { - @Override - public void onSuccess(Void obj, HttpHeaders responseHeaders) throws IOException { - LOG.debug("Successfully removed {}", path); - } - - @Override - public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { - // Do nothing on item not found. - if (!errorExtractor.itemNotFound(e)) { - throw new IOException(e.toString()); - } - LOG.debug("{} does not exist.", path); - } - }); - } - batchHelper.flush(); + gcsUtil.remove(filenames); } } @@ -743,133 +661,4 @@ private void removeOne(String filename) throws IOException { } } } - - /** - * BatchHelper abstracts out the logic for the maximum requests per batch for GCS. - * - *

          Copy of - * https://github.com/GoogleCloudPlatform/bigdata-interop/blob/master/gcs/src/main/java/com/google/cloud/hadoop/gcsio/BatchHelper.java - * - *

          Copied to prevent Dataflow from depending on the Hadoop-related dependencies that are not - * used in Dataflow. Hadoop-related dependencies will be removed from the Google Cloud Storage - * Connector (https://cloud.google.com/hadoop/google-cloud-storage-connector) so that this project - * and others may use the connector without introducing unnecessary dependencies. - * - *

          This class is not thread-safe; create a new BatchHelper instance per single-threaded logical - * grouping of requests. - */ - @NotThreadSafe - private static class BatchHelper { - /** - * Callback that causes a single StorageRequest to be added to the BatchRequest. - */ - protected static interface QueueRequestCallback { - void enqueue() throws IOException; - } - - private final List pendingBatchEntries; - private final BatchRequest batch; - - // Number of requests that can be queued into a single actual HTTP request - // before a sub-batch is sent. - private final long maxRequestsPerBatch; - - // Flag that indicates whether there is an in-progress flush. - private boolean flushing = false; - - /** - * Primary constructor, generally accessed only via the inner Factory class. - */ - public BatchHelper( - HttpRequestInitializer requestInitializer, Storage gcs, long maxRequestsPerBatch) { - this.pendingBatchEntries = new LinkedList<>(); - this.batch = gcs.batch(requestInitializer); - this.maxRequestsPerBatch = maxRequestsPerBatch; - } - - /** - * Adds an additional request to the batch, and possibly flushes the current contents of the - * batch if {@code maxRequestsPerBatch} has been reached. - */ - public void queue(final StorageRequest req, final JsonBatchCallback callback) - throws IOException { - QueueRequestCallback queueCallback = new QueueRequestCallback() { - @Override - public void enqueue() throws IOException { - req.queue(batch, callback); - } - }; - pendingBatchEntries.add(queueCallback); - - flushIfPossibleAndRequired(); - } - - // Flush our buffer if we have more pending entries than maxRequestsPerBatch - private void flushIfPossibleAndRequired() throws IOException { - if (pendingBatchEntries.size() > maxRequestsPerBatch) { - flushIfPossible(); - } - } - - // Flush our buffer if we are not already in a flush operation and we have data to flush. - private void flushIfPossible() throws IOException { - if (!flushing && pendingBatchEntries.size() > 0) { - flushing = true; - try { - while (batch.size() < maxRequestsPerBatch && pendingBatchEntries.size() > 0) { - QueueRequestCallback head = pendingBatchEntries.remove(0); - head.enqueue(); - } - - batch.execute(); - } finally { - flushing = false; - } - } - } - - - /** - * Sends any currently remaining requests in the batch; should be called at the end of any - * series of batched requests to ensure everything has been sent. - */ - public void flush() throws IOException { - flushIfPossible(); - } - } - - static class ReshardForWrite extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection input) { - return input - // TODO: This would need to be adapted to write per-window shards. - .apply(Window.into(new GlobalWindows()) - .triggering(DefaultTrigger.of()) - .discardingFiredPanes()) - .apply("RandomKey", ParDo.of( - new DoFn>() { - transient long counter, step; - @Override - public void startBundle(Context c) { - counter = (long) (Math.random() * Long.MAX_VALUE); - step = 1 + 2 * (long) (Math.random() * Long.MAX_VALUE); - } - @Override - public void processElement(ProcessContext c) { - counter += step; - c.output(KV.of(counter, c.element())); - } - })) - .apply(GroupByKey.create()) - .apply("Ungroup", ParDo.of( - new DoFn>, T>() { - @Override - public void processElement(ProcessContext c) { - for (T item : c.element().getValue()) { - c.output(item); - } - } - })); - } - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java index 47adb5967b..d170c9a5c6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java @@ -16,10 +16,16 @@ package com.google.cloud.dataflow.sdk.util; +import com.google.api.client.googleapis.batch.BatchRequest; +import com.google.api.client.googleapis.batch.json.JsonBatchCallback; +import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.util.BackOff; import com.google.api.client.util.Sleeper; import com.google.api.services.storage.Storage; +import com.google.api.services.storage.StorageRequest; import com.google.api.services.storage.model.Objects; import com.google.api.services.storage.model.StorageObject; import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; @@ -45,6 +51,7 @@ import java.io.IOException; import java.nio.channels.SeekableByteChannel; import java.nio.channels.WritableByteChannel; +import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -53,6 +60,7 @@ import java.util.regex.Pattern; import javax.annotation.Nullable; +import javax.annotation.concurrent.NotThreadSafe; /** * Provides operations on GCS. @@ -74,7 +82,6 @@ public static class GcsUtilFactory implements DefaultValueFactory { public GcsUtil create(PipelineOptions options) { LOG.debug("Creating new GcsUtil"); GcsOptions gcsOptions = options.as(GcsOptions.class); - return new GcsUtil(Transport.newStorageClient(gcsOptions).build(), gcsOptions.getExecutorService(), gcsOptions.getGcsUploadBufferSizeBytes()); } @@ -96,6 +103,11 @@ public GcsUtil create(PipelineOptions options) { private static final Pattern RECURSIVE_GCS_PATTERN = Pattern.compile(".*" + RECURSIVE_WILDCARD + ".*"); + /** + * Maximum number of requests permitted in a GCS batch request. + */ + private static final int MAX_REQUESTS_PER_BATCH = 1000; + ///////////////////////////////////////////////////////////////////////////// /** Client for the GCS API. */ @@ -109,6 +121,7 @@ public GcsUtil create(PipelineOptions options) { // Exposed for testing. final ExecutorService executorService; + private final BatchHelper batchHelper; /** * Returns true if the given GCS pattern is supported otherwise fails with an * exception. @@ -128,6 +141,8 @@ private GcsUtil( this.storageClient = storageClient; this.uploadBufferSizeBytes = uploadBufferSizeBytes; this.executorService = executorService; + this.batchHelper = new BatchHelper( + storageClient.getRequestFactory().getInitializer(), storageClient, MAX_REQUESTS_PER_BATCH); } // Use this only for testing purposes. @@ -353,6 +368,155 @@ public boolean shouldRetry(IOException e) { } } + public void copy(List srcFilenames, List destFilenames) throws IOException { + Preconditions.checkArgument( + srcFilenames.size() == destFilenames.size(), + String.format("Number of source files {} must equal number of destination files {}", + srcFilenames.size(), destFilenames.size())); + for (int i = 0; i < srcFilenames.size(); i++) { + final GcsPath sourcePath = GcsPath.fromUri(srcFilenames.get(i)); + final GcsPath destPath = GcsPath.fromUri(destFilenames.get(i)); + LOG.debug("Copying {} to {}", sourcePath, destPath); + Storage.Objects.Copy copyObject = storageClient.objects().copy(sourcePath.getBucket(), + sourcePath.getObject(), destPath.getBucket(), destPath.getObject(), null); + batchHelper.queue(copyObject, new JsonBatchCallback() { + @Override + public void onSuccess(StorageObject obj, HttpHeaders responseHeaders) { + LOG.debug("Successfully copied {} to {}", sourcePath, destPath); + } + + @Override + public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { + // Do nothing on item not found. + if (!errorExtractor.itemNotFound(e)) { + throw new IOException(e.toString()); + } + LOG.debug("{} does not exist.", sourcePath); + } + }); + } + batchHelper.flush(); + } + + public void remove(Collection filenames) throws IOException { + for (String filename : filenames) { + final GcsPath path = GcsPath.fromUri(filename); + LOG.debug("Removing: " + path); + Storage.Objects.Delete deleteObject = + storageClient.objects().delete(path.getBucket(), path.getObject()); + batchHelper.queue(deleteObject, new JsonBatchCallback() { + @Override + public void onSuccess(Void obj, HttpHeaders responseHeaders) throws IOException { + LOG.debug("Successfully removed {}", path); + } + + @Override + public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { + // Do nothing on item not found. + if (!errorExtractor.itemNotFound(e)) { + throw new IOException(e.toString()); + } + LOG.debug("{} does not exist.", path); + } + }); + } + batchHelper.flush(); + } + + /** + * BatchHelper abstracts out the logic for the maximum requests per batch for GCS. + * + *

          Copy of + * https://github.com/GoogleCloudPlatform/bigdata-interop/blob/master/gcs/src/main/java/com/google/cloud/hadoop/gcsio/BatchHelper.java + * + *

          Copied to prevent Dataflow from depending on the Hadoop-related dependencies that are not + * used in Dataflow. Hadoop-related dependencies will be removed from the Google Cloud Storage + * Connector (https://cloud.google.com/hadoop/google-cloud-storage-connector) so that this project + * and others may use the connector without introducing unnecessary dependencies. + * + *

          This class is not thread-safe; create a new BatchHelper instance per single-threaded logical + * grouping of requests. + */ + @NotThreadSafe + private static class BatchHelper { + /** + * Callback that causes a single StorageRequest to be added to the BatchRequest. + */ + protected static interface QueueRequestCallback { + void enqueue() throws IOException; + } + + private final List pendingBatchEntries; + private final BatchRequest batch; + + // Number of requests that can be queued into a single actual HTTP request + // before a sub-batch is sent. + private final long maxRequestsPerBatch; + + // Flag that indicates whether there is an in-progress flush. + private boolean flushing = false; + + /** + * Primary constructor, generally accessed only via the inner Factory class. + */ + public BatchHelper( + HttpRequestInitializer requestInitializer, Storage gcs, long maxRequestsPerBatch) { + this.pendingBatchEntries = new LinkedList<>(); + this.batch = gcs.batch(requestInitializer); + this.maxRequestsPerBatch = maxRequestsPerBatch; + } + + /** + * Adds an additional request to the batch, and possibly flushes the current contents of the + * batch if {@code maxRequestsPerBatch} has been reached. + */ + public void queue(final StorageRequest req, final JsonBatchCallback callback) + throws IOException { + QueueRequestCallback queueCallback = new QueueRequestCallback() { + @Override + public void enqueue() throws IOException { + req.queue(batch, callback); + } + }; + pendingBatchEntries.add(queueCallback); + + flushIfPossibleAndRequired(); + } + + // Flush our buffer if we have more pending entries than maxRequestsPerBatch + private void flushIfPossibleAndRequired() throws IOException { + if (pendingBatchEntries.size() > maxRequestsPerBatch) { + flushIfPossible(); + } + } + + // Flush our buffer if we are not already in a flush operation and we have data to flush. + private void flushIfPossible() throws IOException { + if (!flushing && pendingBatchEntries.size() > 0) { + flushing = true; + try { + while (batch.size() < maxRequestsPerBatch && pendingBatchEntries.size() > 0) { + QueueRequestCallback head = pendingBatchEntries.remove(0); + head.enqueue(); + } + + batch.execute(); + } finally { + flushing = false; + } + } + } + + + /** + * Sends any currently remaining requests in the batch; should be called at the end of any + * series of batched requests to ensure everything has been sent. + */ + public void flush() throws IOException { + flushIfPossible(); + } + } + /** * Expands glob expressions to regular expressions. * From 490526a4b6073efd2916d360bcb2fe292122ae83 Mon Sep 17 00:00:00 2001 From: peihe Date: Fri, 13 May 2016 17:00:11 -0700 Subject: [PATCH 394/751] Backprot PR from Beam: Implement BigQueryIO.Read as Source. (#263) Implement BigQueryIO.Read as BoundedSource --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 879 +++++++++++++++--- .../dataflow/sdk/util/BigQueryServices.java | 109 ++- .../sdk/util/BigQueryServicesImpl.java | 347 +++++-- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 548 +++++++++-- .../sdk/util/BigQueryServicesImplTest.java | 40 +- 5 files changed, 1656 insertions(+), 267 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 6e13ad64c4..413254a40e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -21,9 +21,16 @@ import static com.google.common.base.Preconditions.checkState; import com.google.api.client.json.JsonFactory; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.BackOffUtils; +import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Job; +import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; +import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.QueryRequest; import com.google.api.services.bigquery.model.TableReference; @@ -44,21 +51,26 @@ import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.View; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.AvroUtils; import com.google.cloud.dataflow.sdk.util.BigQueryServices; +import com.google.cloud.dataflow.sdk.util.BigQueryServices.DatasetService; import com.google.cloud.dataflow.sdk.util.BigQueryServices.JobService; import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl; import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; +import com.google.cloud.dataflow.sdk.util.GcsUtil.GcsUtilFactory; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.MimeTypes; @@ -66,40 +78,53 @@ import com.google.cloud.dataflow.sdk.util.Reshuffle; import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; +import com.google.cloud.dataflow.sdk.values.PCollectionTuple; +import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.TupleTag; +import com.google.cloud.dataflow.sdk.values.TupleTagList; import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; + +import org.apache.avro.generic.GenericRecord; +import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; +import java.io.ObjectInputStream; import java.io.OutputStream; +import java.io.Serializable; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -360,27 +385,39 @@ public static Bound withoutValidation() { * {@link PCollection} of {@link TableRow TableRows}. */ public static class Bound extends PTransform> { - TableReference table; - final String query; + @Nullable final String jsonTableRef; + @Nullable final String query; final boolean validate; - @Nullable - Boolean flattenResults; + @Nullable final Boolean flattenResults; + @Nullable final BigQueryServices testBigQueryServices; private static final String QUERY_VALIDATION_FAILURE_ERROR = "Validation of query \"%1$s\" failed. If the query depends on an earlier stage of the" + " pipeline, This validation can be disabled using #withoutValidation."; + // The maximum number of retries to poll a BigQuery job in the cleanup phase. + // We expect the jobs have already DONE, and don't need a high max retires. + private static final int CLEANUP_JOB_POLL_MAX_RETRIES = 10; + private Bound() { - this(null, null, null, true, null); + this( + null /* name */, + null /* query */, + null /* jsonTableRef */, + true /* validate */, + null /* flattenResults */, + null /* testBigQueryServices */); } - private Bound(String name, String query, TableReference reference, boolean validate, - Boolean flattenResults) { + private Bound( + String name, @Nullable String query, @Nullable String jsonTableRef, boolean validate, + @Nullable Boolean flattenResults, @Nullable BigQueryServices testBigQueryServices) { super(name); - this.table = reference; + this.jsonTableRef = jsonTableRef; this.query = query; this.validate = validate; this.flattenResults = flattenResults; + this.testBigQueryServices = testBigQueryServices; } /** @@ -389,7 +426,7 @@ private Bound(String name, String query, TableReference reference, boolean valid *

          Does not modify this object. */ public Bound named(String name) { - return new Bound(name, query, table, validate, flattenResults); + return new Bound(name, query, jsonTableRef, validate, flattenResults, testBigQueryServices); } /** @@ -408,7 +445,8 @@ public Bound from(String tableSpec) { *

          Does not modify this object. */ public Bound from(TableReference table) { - return new Bound(name, query, table, validate, flattenResults); + return new Bound( + name, query, toJsonString(table), validate, flattenResults, testBigQueryServices); } /** @@ -422,15 +460,15 @@ public Bound from(TableReference table) { * {@link BigQueryIO.Read.Bound#withoutResultFlattening}. */ public Bound fromQuery(String query) { - return new Bound(name, query, table, validate, - MoreObjects.firstNonNull(flattenResults, Boolean.TRUE)); + return new Bound(name, query, jsonTableRef, validate, + MoreObjects.firstNonNull(flattenResults, Boolean.TRUE), testBigQueryServices); } /** * Disable table validation. */ public Bound withoutValidation() { - return new Bound(name, query, table, false, flattenResults); + return new Bound(name, query, jsonTableRef, false, flattenResults, testBigQueryServices); } /** @@ -441,35 +479,34 @@ public Bound withoutValidation() { * from a table will cause an error during validation. */ public Bound withoutResultFlattening() { - return new Bound(name, query, table, validate, false); + return new Bound(name, query, jsonTableRef, validate, false, testBigQueryServices); + } + + @VisibleForTesting + Bound withTestServices(BigQueryServices testServices) { + return new Bound(name, query, jsonTableRef, validate, flattenResults, testServices); } @Override public void validate(PInput input) { - if (table == null && query == null) { - throw new IllegalStateException( - "Invalid BigQuery read operation, either table reference or query has to be set"); - } else if (table != null && query != null) { - throw new IllegalStateException("Invalid BigQuery read operation. Specifies both a" - + " query and a table, only one of these should be provided"); - } else if (table != null && flattenResults != null) { - throw new IllegalStateException("Invalid BigQuery read operation. Specifies a" - + " table with a result flattening preference, which is not configurable"); - } else if (query != null && flattenResults == null) { - throw new IllegalStateException("Invalid BigQuery read operation. Specifies a" - + " query without a result flattening preference"); - } - - BigQueryOptions bqOptions = input.getPipeline().getOptions().as(BigQueryOptions.class); - if (table != null && table.getProjectId() == null) { - // If user does not specify a project we assume the table to be located in the project - // that owns the Dataflow job. - LOG.warn(String.format(SET_PROJECT_FROM_OPTIONS_WARNING, table.getDatasetId(), - table.getTableId(), bqOptions.getProject())); - table.setProjectId(bqOptions.getProject()); - } - if (validate) { + BigQueryOptions bqOptions = input.getPipeline().getOptions().as(BigQueryOptions.class); + + TableReference table = getTableWithDefaultProject(bqOptions); + if (table == null && query == null) { + throw new IllegalStateException( + "Invalid BigQuery read operation, either table reference or query has to be set"); + } else if (table != null && query != null) { + throw new IllegalStateException("Invalid BigQuery read operation. Specifies both a" + + " query and a table, only one of these should be provided"); + } else if (table != null && flattenResults != null) { + throw new IllegalStateException("Invalid BigQuery read operation. Specifies a" + + " table with a result flattening preference, which is not configurable"); + } else if (query != null && flattenResults == null) { + throw new IllegalStateException("Invalid BigQuery read operation. Specifies a" + + " query without a result flattening preference"); + } + // Check for source table/query presence for early failure notification. // Note that a presence check can fail if the table or dataset are created by earlier // stages of the pipeline or if a query depends on earlier stages of a pipeline. For these @@ -502,14 +539,83 @@ private static void dryRunQuery(BigQueryOptions options, String query) { @Override public PCollection apply(PInput input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - IsBounded.BOUNDED) - // Force the output's Coder to be what the read is using, and - // unchangeable later, to ensure that we read the input in the - // format specified by the Read transform. - .setCoder(TableRowJsonCoder.of()); + String uuid = randomUUIDString(); + final String jobIdToken = "beam_job_" + uuid; + + BigQueryOptions bqOptions = input.getPipeline().getOptions().as(BigQueryOptions.class); + + BoundedSource source; + final BigQueryServices bqServices = getBigQueryServices(); + + final String extractDestinationDir; + String tempLocation = bqOptions.getTempLocation(); + try { + IOChannelFactory factory = IOChannelUtils.getFactory(tempLocation); + extractDestinationDir = factory.resolve(tempLocation, uuid); + } catch (IOException e) { + throw new RuntimeException( + String.format("Failed to resolve extract destination directory in %s", tempLocation)); + } + + if (!Strings.isNullOrEmpty(query)) { + String projectId = bqOptions.getProject(); + String queryTempDatasetId = "temp_dataset_" + uuid; + String queryTempTableId = "temp_table_" + uuid; + + TableReference queryTempTableRef = new TableReference() + .setProjectId(projectId) + .setDatasetId(queryTempDatasetId) + .setTableId(queryTempTableId); + + String jsonQueryTempTable; + try { + jsonQueryTempTable = JSON_FACTORY.toString(queryTempTableRef); + } catch (IOException e) { + throw new RuntimeException("Cannot initialize table to JSON strings.", e); + } + source = BigQueryQuerySource.create( + jobIdToken, query, jsonQueryTempTable, flattenResults, + extractDestinationDir, bqServices); + } else { + String jsonTable; + try { + jsonTable = JSON_FACTORY.toString(getTableWithDefaultProject(bqOptions)); + } catch (IOException e) { + throw new RuntimeException("Cannot initialize table to JSON strings.", e); + } + source = BigQueryTableSource.create( + jobIdToken, jsonTable, extractDestinationDir, bqServices); + } + PassThroughThenCleanup.CleanupOperation cleanupOperation = + new PassThroughThenCleanup.CleanupOperation() { + @Override + void cleanup(PipelineOptions options) throws Exception { + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + + JobReference jobRef = new JobReference() + .setProjectId(bqOptions.getProject()) + .setJobId(getExtractJobId(jobIdToken)); + Job extractJob = bqServices.getJobService(bqOptions).pollJob( + jobRef, CLEANUP_JOB_POLL_MAX_RETRIES); + + Collection extractFiles = null; + if (extractJob != null) { + extractFiles = getExtractFilePaths(extractDestinationDir, extractJob); + } else { + IOChannelFactory factory = IOChannelUtils.getFactory(extractDestinationDir); + Collection dirMatch = factory.match(extractDestinationDir); + if (!dirMatch.isEmpty()) { + extractFiles = factory.match(factory.resolve(extractDestinationDir, "*")); + } + } + if (extractFiles != null && !extractFiles.isEmpty()) { + new GcsUtilFactory().create(options).remove(extractFiles); + } + }}; + return input.getPipeline() + .apply(com.google.cloud.dataflow.sdk.io.Read.from(source)) + .setCoder(getDefaultOutputCoder()) + .apply(new PassThroughThenCleanup(cleanupOperation)); } @Override @@ -520,6 +626,7 @@ protected Coder getDefaultOutputCoder() { @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); + TableReference table = getTable(); if (table != null) { builder.add("table", toTableSpec(table)); @@ -531,22 +638,26 @@ public void populateDisplayData(DisplayData.Builder builder) { .addIfNotDefault("validation", validate, true); } - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, DirectPipelineRunner.EvaluationContext context) { - evaluateReadHelper(transform, context); - } - }); + /** + * Returns the table to write, or {@code null} if reading from a query instead. + * + *

          If the table's project is not specified, use the default one. + */ + @Nullable private TableReference getTableWithDefaultProject(BigQueryOptions bqOptions) { + TableReference table = getTable(); + if (table != null && table.getProjectId() == null) { + // If user does not specify a project we assume the table to be located in + // the default project. + table.setProjectId(bqOptions.getProject()); + } + return table; } /** * Returns the table to read, or {@code null} if reading from a query instead. */ public TableReference getTable() { - return table; + return fromJsonString(jsonTableRef, TableReference.class); } /** @@ -569,12 +680,567 @@ public boolean getValidate() { public Boolean getFlattenResults() { return flattenResults; } + + private BigQueryServices getBigQueryServices() { + if (testBigQueryServices != null) { + return testBigQueryServices; + } else { + return new BigQueryServicesImpl(); + } + } } /** Disallow construction of utility class. */ private Read() {} } + /** + * A {@link PTransform} that invokes {@link CleanupOperation} after the input {@link PCollection} + * has been processed. + */ + @VisibleForTesting + static class PassThroughThenCleanup extends PTransform, PCollection> { + + private CleanupOperation cleanupOperation; + + PassThroughThenCleanup(CleanupOperation cleanupOperation) { + this.cleanupOperation = cleanupOperation; + } + + @Override + public PCollection apply(PCollection input) { + TupleTag mainOutput = new TupleTag<>(); + TupleTag cleanupSignal = new TupleTag<>(); + PCollectionTuple outputs = input.apply(ParDo.of(new IdentityFn()) + .withOutputTags(mainOutput, TupleTagList.of(cleanupSignal))); + + PCollectionView cleanupSignalView = outputs.get(cleanupSignal) + .setCoder(VoidCoder.of()) + .apply(View.asSingleton().withDefaultValue(null)); + + input.getPipeline() + .apply("Create(CleanupOperation)", Create.of(cleanupOperation)) + .apply("Cleanup", ParDo.of( + new DoFn() { + @Override + public void processElement(ProcessContext c) + throws Exception { + c.element().cleanup(c.getPipelineOptions()); + } + }).withSideInputs(cleanupSignalView)); + + return outputs.get(mainOutput); + } + + private static class IdentityFn extends DoFn { + @Override + public void processElement(ProcessContext c) { + c.output(c.element()); + } + } + + abstract static class CleanupOperation implements Serializable { + abstract void cleanup(PipelineOptions options) throws Exception; + } + } + + /** + * A {@link BigQuerySourceBase} for reading BigQuery tables. + */ + @VisibleForTesting + static class BigQueryTableSource extends BigQuerySourceBase { + + static BigQueryTableSource create( + String jobIdToken, + String jsonTable, + String extractDestinationDir, + BigQueryServices bqServices) { + return new BigQueryTableSource(jobIdToken, jsonTable, extractDestinationDir, bqServices); + } + + private final String jsonTable; + private final AtomicReference tableSizeBytes; + + private BigQueryTableSource( + String jobIdToken, + String jsonTable, + String extractDestinationDir, + BigQueryServices bqServices) { + super(jobIdToken, extractDestinationDir, bqServices); + this.jsonTable = checkNotNull(jsonTable, "jsonTable"); + this.tableSizeBytes = new AtomicReference<>(); + } + + @Override + protected TableReference getTableToExtract(BigQueryOptions bqOptions) throws IOException { + return JSON_FACTORY.fromString(jsonTable, TableReference.class); + } + + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + TableReference tableRef = JSON_FACTORY.fromString(jsonTable, TableReference.class); + return new BigQueryReader(this, bqServices.getReaderFromTable(bqOptions, tableRef)); + } + + @Override + public synchronized long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + if (tableSizeBytes.get() == null) { + TableReference table = JSON_FACTORY.fromString(jsonTable, TableReference.class); + + Long numBytes = bqServices.getDatasetService(options.as(BigQueryOptions.class)) + .getTable(table.getProjectId(), table.getDatasetId(), table.getTableId()) + .getNumBytes(); + tableSizeBytes.compareAndSet(null, numBytes); + } + return tableSizeBytes.get(); + } + + @Override + protected void cleanupTempResource(BigQueryOptions bqOptions) throws Exception { + // Do nothing. + } + } + + /** + * A {@link BigQuerySourceBase} for querying BigQuery tables. + */ + @VisibleForTesting + static class BigQueryQuerySource extends BigQuerySourceBase { + + static BigQueryQuerySource create( + String jobIdToken, + String query, + String jsonQueryTempTable, + Boolean flattenResults, + String extractDestinationDir, + BigQueryServices bqServices) { + return new BigQueryQuerySource( + jobIdToken, query, jsonQueryTempTable, flattenResults, extractDestinationDir, bqServices); + } + + private final String query; + private final String jsonQueryTempTable; + private final Boolean flattenResults; + private transient AtomicReference dryRunJobStats; + + private BigQueryQuerySource( + String jobIdToken, + String query, + String jsonQueryTempTable, + Boolean flattenResults, + String extractDestinationDir, + BigQueryServices bqServices) { + super(jobIdToken, extractDestinationDir, bqServices); + this.query = checkNotNull(query, "query"); + this.jsonQueryTempTable = checkNotNull(jsonQueryTempTable, "jsonQueryTempTable"); + this.flattenResults = checkNotNull(flattenResults, "flattenResults"); + this.dryRunJobStats = new AtomicReference<>(); + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + return dryRunQueryIfNeeded(bqOptions).getTotalBytesProcessed(); + } + + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + return new BigQueryReader(this, bqServices.getReaderFromQuery( + bqOptions, query, bqOptions.getProject(), flattenResults)); + } + + @Override + protected TableReference getTableToExtract(BigQueryOptions bqOptions) + throws IOException, InterruptedException { + // 1. Find the location of the query. + TableReference dryRunTempTable = dryRunQueryIfNeeded(bqOptions) + .getQuery() + .getReferencedTables() + .get(0); + DatasetService tableService = bqServices.getDatasetService(bqOptions); + String location = tableService.getTable( + dryRunTempTable.getProjectId(), + dryRunTempTable.getDatasetId(), + dryRunTempTable.getTableId()).getLocation(); + + // 2. Create the temporary dataset in the query location. + TableReference tableToExtract = + JSON_FACTORY.fromString(jsonQueryTempTable, TableReference.class); + tableService.createDataset( + tableToExtract.getProjectId(), tableToExtract.getDatasetId(), location, ""); + + // 3. Execute the query. + String queryJobId = jobIdToken + "-query"; + executeQuery( + queryJobId, query, tableToExtract, flattenResults, bqServices.getJobService(bqOptions)); + return tableToExtract; + } + + @Override + protected void cleanupTempResource(BigQueryOptions bqOptions) throws Exception { + TableReference tableToRemove = + JSON_FACTORY.fromString(jsonQueryTempTable, TableReference.class); + + DatasetService tableService = bqServices.getDatasetService(bqOptions); + tableService.deleteTable( + tableToRemove.getProjectId(), + tableToRemove.getDatasetId(), + tableToRemove.getTableId()); + tableService.deleteDataset(tableToRemove.getProjectId(), tableToRemove.getDatasetId()); + } + + private synchronized JobStatistics dryRunQueryIfNeeded(BigQueryOptions bqOptions) + throws InterruptedException, IOException { + if (dryRunJobStats.get() == null) { + String projectId = bqOptions.getProject(); + JobStatistics jobStats = + bqServices.getJobService(bqOptions).dryRunQuery(projectId, query); + dryRunJobStats.compareAndSet(null, jobStats); + } + return dryRunJobStats.get(); + } + + private static void executeQuery( + String jobId, + String query, + TableReference destinationTable, + boolean flattenResults, + JobService jobService) throws IOException, InterruptedException { + JobReference jobRef = new JobReference() + .setProjectId(destinationTable.getProjectId()) + .setJobId(jobId); + JobConfigurationQuery queryConfig = new JobConfigurationQuery(); + queryConfig + .setQuery(query) + .setAllowLargeResults(true) + .setCreateDisposition("CREATE_IF_NEEDED") + .setDestinationTable(destinationTable) + .setFlattenResults(flattenResults) + .setPriority("BATCH") + .setWriteDisposition("WRITE_EMPTY"); + jobService.startQueryJob(jobRef, queryConfig); + Job job = jobService.pollJob(jobRef, JOB_POLL_MAX_RETRIES); + if (parseStatus(job) != Status.SUCCEEDED) { + throw new IOException("Query job failed: " + jobId); + } + return; + } + + private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException { + in.defaultReadObject(); + dryRunJobStats = new AtomicReference<>(); + } + } + + /** + * An abstract {@link BoundedSource} to read a table from BigQuery. + * + *

          This source uses a BigQuery export job to take a snapshot of the table on GCS, and then + * reads in parallel from each produced file. It is implemented by {@link BigQueryTableSource}, + * and {@link BigQueryQuerySource}, depending on the configuration of the read. + * Specifically, + *

            + *
          • {@link BigQueryTableSource} is for reading BigQuery tables
          • + *
          • {@link BigQueryQuerySource} is for querying BigQuery tables
          • + *
          + * ... + */ + private abstract static class BigQuerySourceBase extends BoundedSource { + // The maximum number of attempts to verify temp files. + private static final int MAX_FILES_VERIFY_ATTEMPTS = 10; + + // The maximum number of retries to poll a BigQuery job. + protected static final int JOB_POLL_MAX_RETRIES = Integer.MAX_VALUE; + + // The initial backoff for verifying temp files. + private static final long INITIAL_FILES_VERIFY_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); + + protected final String jobIdToken; + protected final String extractDestinationDir; + protected final BigQueryServices bqServices; + + private BigQuerySourceBase( + String jobIdToken, + String extractDestinationDir, + BigQueryServices bqServices) { + this.jobIdToken = checkNotNull(jobIdToken, "jobIdToken"); + this.extractDestinationDir = checkNotNull(extractDestinationDir, "extractDestinationDir"); + this.bqServices = checkNotNull(bqServices, "bqServices"); + } + + @Override + public List> splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + TableReference tableToExtract = getTableToExtract(bqOptions); + JobService jobService = bqServices.getJobService(bqOptions); + String extractJobId = getExtractJobId(jobIdToken); + List tempFiles = executeExtract(extractJobId, tableToExtract, jobService); + + TableSchema tableSchema = bqServices.getDatasetService(bqOptions).getTable( + tableToExtract.getProjectId(), + tableToExtract.getDatasetId(), + tableToExtract.getTableId()).getSchema(); + + cleanupTempResource(bqOptions); + return createSources(tempFiles, tableSchema); + } + + protected abstract TableReference getTableToExtract(BigQueryOptions bqOptions) throws Exception; + + protected abstract void cleanupTempResource(BigQueryOptions bqOptions) throws Exception; + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return false; + } + + @Override + public void validate() { + // Do nothing, validation is done in BigQuery.Read. + } + + @Override + public Coder getDefaultOutputCoder() { + return TableRowJsonCoder.of(); + } + + private List executeExtract( + String jobId, TableReference table, JobService jobService) + throws InterruptedException, IOException { + JobReference jobRef = new JobReference() + .setProjectId(table.getProjectId()) + .setJobId(jobId); + + String destinationUri = getExtractDestinationUri(extractDestinationDir); + JobConfigurationExtract extract = new JobConfigurationExtract() + .setSourceTable(table) + .setDestinationFormat("AVRO") + .setDestinationUris(ImmutableList.of(destinationUri)); + + LOG.info("Starting BigQuery extract job: {}", jobId); + jobService.startExtractJob(jobRef, extract); + Job extractJob = + jobService.pollJob(jobRef, JOB_POLL_MAX_RETRIES); + if (parseStatus(extractJob) != Status.SUCCEEDED) { + throw new IOException(String.format( + "Extract job %s failed, status: %s", + extractJob.getJobReference().getJobId(), extractJob.getStatus())); + } + + List tempFiles = getExtractFilePaths(extractDestinationDir, extractJob); + return ImmutableList.copyOf(tempFiles); + } + + private List> createSources( + List files, TableSchema tableSchema) throws IOException, InterruptedException { + final String jsonSchema = JSON_FACTORY.toString(tableSchema); + + SerializableFunction function = + new SerializableFunction() { + @Override + public TableRow apply(GenericRecord input) { + try { + return AvroUtils.convertGenericRecordToTableRow( + input, JSON_FACTORY.fromString(jsonSchema, TableSchema.class)); + } catch (IOException e) { + throw new RuntimeException("Failed to convert GenericRecord to TableRow", e); + } + }}; + + List> avroSources = Lists.newArrayList(); + BackOff backoff = new AttemptBoundedExponentialBackOff( + MAX_FILES_VERIFY_ATTEMPTS, INITIAL_FILES_VERIFY_BACKOFF_MILLIS); + for (String fileName : files) { + while (BackOffUtils.next(Sleeper.DEFAULT, backoff)) { + if (IOChannelUtils.getFactory(fileName).getSizeBytes(fileName) != -1) { + break; + } + } + avroSources.add(new TransformingSource<>( + AvroSource.from(fileName), function, getDefaultOutputCoder())); + } + return ImmutableList.copyOf(avroSources); + } + + protected static class BigQueryReader extends BoundedSource.BoundedReader { + private final BigQuerySourceBase source; + private final BigQueryServices.BigQueryJsonReader reader; + + private BigQueryReader( + BigQuerySourceBase source, BigQueryServices.BigQueryJsonReader reader) { + this.source = source; + this.reader = reader; + } + + @Override + public BoundedSource getCurrentSource() { + return source; + } + + @Override + public boolean start() throws IOException { + return reader.start(); + } + + @Override + public boolean advance() throws IOException { + return reader.advance(); + } + + @Override + public TableRow getCurrent() throws NoSuchElementException { + return reader.getCurrent(); + } + + @Override + public void close() throws IOException { + reader.close(); + } + } + } + + /** + * A {@link BoundedSource} that reads from {@code BoundedSource} + * and transforms elements to type {@code V}. + */ + @VisibleForTesting + static class TransformingSource extends BoundedSource { + private final BoundedSource boundedSource; + private final SerializableFunction function; + private final Coder outputCoder; + + TransformingSource( + BoundedSource boundedSource, + SerializableFunction function, + Coder outputCoder) { + this.boundedSource = boundedSource; + this.function = function; + this.outputCoder = outputCoder; + } + + @Override + public List> splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + return Lists.transform( + boundedSource.splitIntoBundles(desiredBundleSizeBytes, options), + new Function, BoundedSource>() { + @Override + public BoundedSource apply(BoundedSource input) { + return new TransformingSource<>(input, function, outputCoder); + } + }); + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + return boundedSource.getEstimatedSizeBytes(options); + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return boundedSource.producesSortedKeys(options); + } + + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + return new TransformingReader(boundedSource.createReader(options)); + } + + @Override + public void validate() { + boundedSource.validate(); + } + + @Override + public Coder getDefaultOutputCoder() { + return outputCoder; + } + + private class TransformingReader extends BoundedReader { + private final BoundedReader boundedReader; + + private TransformingReader(BoundedReader boundedReader) { + this.boundedReader = boundedReader; + } + + @Override + public synchronized BoundedSource getCurrentSource() { + return new TransformingSource<>(boundedReader.getCurrentSource(), function, outputCoder); + } + + @Override + public boolean start() throws IOException { + return boundedReader.start(); + } + + @Override + public boolean advance() throws IOException { + return boundedReader.advance(); + } + + @Override + public V getCurrent() throws NoSuchElementException { + T current = boundedReader.getCurrent(); + return function.apply(current); + } + + @Override + public void close() throws IOException { + boundedReader.close(); + } + + @Override + public synchronized BoundedSource splitAtFraction(double fraction) { + return new TransformingSource<>( + boundedReader.splitAtFraction(fraction), function, outputCoder); + } + + @Override + public Double getFractionConsumed() { + return boundedReader.getFractionConsumed(); + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + return boundedReader.getCurrentTimestamp(); + } + } + } + + private static String getExtractJobId(String jobIdToken) { + return jobIdToken + "-extract"; + } + + private static String getExtractDestinationUri(String extractDestinationDir) { + return String.format("%s/%s", extractDestinationDir, "*.avro"); + } + + private static List getExtractFilePaths(String extractDestinationDir, Job extractJob) + throws IOException { + JobStatistics jobStats = extractJob.getStatistics(); + List counts = jobStats.getExtract().getDestinationUriFileCounts(); + if (counts.size() != 1) { + String errorMessage = (counts.size() == 0 ? + "No destination uri file count received." : + String.format("More than one destination uri file count received. First two are %s, %s", + counts.get(0), counts.get(1))); + throw new RuntimeException(errorMessage); + } + long filesCount = counts.get(0); + + ImmutableList.Builder paths = ImmutableList.builder(); + IOChannelFactory factory = IOChannelUtils.getFactory(extractDestinationDir); + for (long i = 0; i < filesCount; ++i) { + String filePath = + factory.resolve(extractDestinationDir, String.format("%012d%s", i, ".avro")); + paths.add(filePath); + } + return paths.build(); + } + ///////////////////////////////////////////////////////////////////////////// /** @@ -797,8 +1463,15 @@ public TableReference apply(BoundedWindow value) { */ @Deprecated public Bound() { - this(null, null, null, null, CreateDisposition.CREATE_IF_NEEDED, - WriteDisposition.WRITE_EMPTY, true, null); + this( + null /* name */, + null /* jsonTableRef */, + null /* tableRefFunction */, + null /* jsonSchema */, + CreateDisposition.CREATE_IF_NEEDED, + WriteDisposition.WRITE_EMPTY, + true /* validate */, + null /* testBigQueryServices */); } private Bound(String name, @Nullable String jsonTableRef, @@ -1030,14 +1703,14 @@ public PDone apply(PCollection input) { if (Strings.isNullOrEmpty(table.getProjectId())) { table.setProjectId(options.getProject()); } - String jobIdToken = UUID.randomUUID().toString(); + String jobIdToken = randomUUIDString(); String tempLocation = options.getTempLocation(); String tempFilePrefix; try { IOChannelFactory factory = IOChannelUtils.getFactory(tempLocation); tempFilePrefix = factory.resolve( - factory.resolve(tempLocation, "BigQuerySinkTemp"), - jobIdToken); + factory.resolve(tempLocation, "BigQuerySinkTemp"), + jobIdToken); } catch (IOException e) { throw new RuntimeException( String.format("Failed to resolve BigQuery temp location in %s", tempLocation), @@ -1170,7 +1843,7 @@ private static class BigQueryWriteOperation extends FileBasedWriteOperation T fromJsonString(String json, Class clazz) { + @VisibleForTesting + static T fromJsonString(String json, Class clazz) { if (json == null) { return null; } @@ -1723,51 +2401,20 @@ private static T fromJsonString(String json, Class clazz) { } } - ///////////////////////////////////////////////////////////////////////////// - - /** Disallow construction of utility class. */ - private BigQueryIO() {} - /** - * Direct mode read evaluator. + * Returns a randomUUID string. * - *

          This loads the entire table into an in-memory PCollection. + *

          {@code '-'} is removed because BigQuery doesn't allow it in dataset id. */ - private static void evaluateReadHelper( - Read.Bound transform, DirectPipelineRunner.EvaluationContext context) { - BigQueryOptions options = context.getPipelineOptions(); - Bigquery client = Transport.newBigQueryClient(options).build(); - if (transform.table != null && transform.table.getProjectId() == null) { - transform.table.setProjectId(options.getProject()); - } - - BigQueryTableRowIterator iterator; - if (transform.query != null) { - LOG.info("Reading from BigQuery query {}", transform.query); - iterator = - BigQueryTableRowIterator.fromQuery( - transform.query, options.getProject(), client, transform.getFlattenResults()); - } else { - LOG.info("Reading from BigQuery table {}", toTableSpec(transform.table)); - iterator = BigQueryTableRowIterator.fromTable(transform.table, client); - } - - try (BigQueryTableRowIterator ignored = iterator) { - List elems = new ArrayList<>(); - iterator.open(); - while (iterator.advance()) { - elems.add(iterator.getCurrent()); - } - LOG.info("Number of records read from BigQuery: {}", elems.size()); - context.setPCollection(context.getOutput(transform), elems); - } catch (IOException | InterruptedException e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - throw new RuntimeException(e); - } + private static String randomUUIDString() { + return UUID.randomUUID().toString().replaceAll("-", ""); } + ///////////////////////////////////////////////////////////////////////////// + + /** Disallow construction of utility class. */ + private BigQueryIO() {} + private static List getOrCreateMapListValue(Map> map, K key) { List value = map.get(key); if (value == null) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java index a78c60d4b4..2fc93fe355 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -15,14 +15,23 @@ */ package com.google.cloud.dataflow.sdk.util; +import com.google.api.services.bigquery.model.Dataset; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatistics; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import java.io.IOException; import java.io.Serializable; +import java.util.NoSuchElementException; + +import javax.annotation.Nullable; /** * An interface for real, mock, or fake implementations of Cloud BigQuery services. @@ -34,26 +43,41 @@ public interface BigQueryServices extends Serializable { */ public JobService getJobService(BigQueryOptions bqOptions); + /** + * Returns a real, mock, or fake {@link DatasetService}. + */ + public DatasetService getDatasetService(BigQueryOptions bqOptions); + + /** + * Returns a real, mock, or fake {@link BigQueryJsonReader} to read tables. + */ + public BigQueryJsonReader getReaderFromTable(BigQueryOptions bqOptions, TableReference tableRef); + + /** + * Returns a real, mock, or fake {@link BigQueryJsonReader} to query tables. + */ + public BigQueryJsonReader getReaderFromQuery( + BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten); + /** * An interface for the Cloud BigQuery load service. */ public interface JobService { /** - * Starts a BigQuery load job. + * Start a BigQuery load job. */ - void startLoadJob(String jobId, JobConfigurationLoad loadConfig) + void startLoadJob(JobReference jobRef, JobConfigurationLoad loadConfig) throws InterruptedException, IOException; - /** * Start a BigQuery extract job. */ - void startExtractJob(String jobId, JobConfigurationExtract extractConfig) + void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) throws InterruptedException, IOException; /** - * Start a BigQuery extract job. + * Start a BigQuery query job. */ - void startQueryJob(String jobId, JobConfigurationQuery query, boolean dryRun) + void startQueryJob(JobReference jobRef, JobConfigurationQuery query) throws IOException, InterruptedException; /** @@ -61,7 +85,78 @@ void startQueryJob(String jobId, JobConfigurationQuery query, boolean dryRun) * *

          Returns null if the {@code maxAttempts} retries reached. */ - Job pollJob(String projectId, String jobId, int maxAttempts) + Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException, IOException; + + /** + * Dry runs the query in the given project. + */ + JobStatistics dryRunQuery(String projectId, String query) + throws InterruptedException, IOException; + } + + /** + * An interface to get, create and delete Cloud BigQuery datasets and tables. + */ + public interface DatasetService { + /** + * Gets the specified {@link Table} resource by table ID. + */ + Table getTable(String projectId, String datasetId, String tableId) + throws InterruptedException, IOException; + + /** + * Deletes the table specified by tableId from the dataset. + * If the table contains data, all the data will be deleted. + */ + void deleteTable(String projectId, String datasetId, String tableId) + throws IOException, InterruptedException; + + /** + * Create a {@link Dataset} with the given {@code location} and {@code description}. + */ + void createDataset(String projectId, String datasetId, String location, String description) + throws IOException, InterruptedException; + + /** + * Deletes the dataset specified by the datasetId value. + * + *

          Before you can delete a dataset, you must delete all its tables. + */ + void deleteDataset(String projectId, String datasetId) + throws IOException, InterruptedException; + } + + /** + * An interface to read the Cloud BigQuery directly. + */ + public interface BigQueryJsonReader { + /** + * Initializes the reader and advances the reader to the first record. + */ + boolean start() throws IOException; + + /** + * Advances the reader to the next valid record. + */ + boolean advance() throws IOException; + + /** + * Returns the value of the data item that was read by the last {@link #start} or + * {@link #advance} call. The returned value must be effectively immutable and remain valid + * indefinitely. + * + *

          Multiple calls to this method without an intervening call to {@link #advance} should + * return the same result. + * + * @throws java.util.NoSuchElementException if {@link #start} was never called, or if + * the last {@link #start} or {@link #advance} returned {@code false}. + */ + TableRow getCurrent() throws NoSuchElementException; + + /** + * Closes the reader. The reader cannot be used after this method is called. + */ + void close() throws IOException; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index 1bc62cac7b..e438747785 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -16,17 +16,24 @@ package com.google.cloud.dataflow.sdk.util; import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.util.BackOff; import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetReference; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfiguration; import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobStatus; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; @@ -35,8 +42,10 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; /** * An implementation of {@link BigQueryServices} that actually communicates with the cloud BigQuery @@ -44,6 +53,8 @@ */ public class BigQueryServicesImpl implements BigQueryServices { + private static final Logger LOG = LoggerFactory.getLogger(BigQueryServicesImpl.class); + // The maximum number of attempts to execute a BigQuery RPC. private static final int MAX_RPC_ATTEMPTS = 10; @@ -51,17 +62,31 @@ public class BigQueryServicesImpl implements BigQueryServices { private static final long INITIAL_RPC_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); // The initial backoff for polling the status of a BigQuery job. - private static final long INITIAL_JOB_STATUS_POLL_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(60); + private static final long INITIAL_JOB_STATUS_POLL_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); @Override public JobService getJobService(BigQueryOptions options) { return new JobServiceImpl(options); } + @Override + public DatasetService getDatasetService(BigQueryOptions options) { + return new DatasetServiceImpl(options); + } + + @Override + public BigQueryJsonReader getReaderFromTable(BigQueryOptions bqOptions, TableReference tableRef) { + return BigQueryJsonReaderImpl.fromTable(bqOptions, tableRef); + } + + @Override + public BigQueryJsonReader getReaderFromQuery( + BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten) { + return BigQueryJsonReaderImpl.fromQuery(bqOptions, query, projectId, flatten); + } + @VisibleForTesting static class JobServiceImpl implements BigQueryServices.JobService { - private static final Logger LOG = LoggerFactory.getLogger(JobServiceImpl.class); - private final ApiErrorExtractor errorExtractor; private final Bigquery client; @@ -79,22 +104,17 @@ private JobServiceImpl(BigQueryOptions options) { /** * {@inheritDoc} * - *

          Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

          the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC retries. + * @throws IOException if it exceeds max RPC . */ @Override public void startLoadJob( - String jobId, + JobReference jobRef, JobConfigurationLoad loadConfig) throws InterruptedException, IOException { - Job job = new Job(); - JobReference jobRef = new JobReference(); - jobRef.setProjectId(loadConfig.getDestinationTable().getProjectId()); - jobRef.setJobId(jobId); - job.setJobReference(jobRef); - JobConfiguration jobConfig = new JobConfiguration(); - jobConfig.setLoad(loadConfig); - job.setConfiguration(jobConfig); + Job job = new Job() + .setJobReference(jobRef) + .setConfiguration(new JobConfiguration().setLoad(loadConfig)); startJob(job, errorExtractor, client); } @@ -102,21 +122,17 @@ public void startLoadJob( /** * {@inheritDoc} * - *

          Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

          the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC retries. + * @throws IOException if it exceeds max RPC . */ @Override - public void startExtractJob(String jobId, JobConfigurationExtract extractConfig) + public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) throws InterruptedException, IOException { - Job job = new Job(); - JobReference jobRef = new JobReference(); - jobRef.setProjectId(extractConfig.getSourceTable().getProjectId()); - jobRef.setJobId(jobId); - job.setJobReference(jobRef); - JobConfiguration jobConfig = new JobConfiguration(); - jobConfig.setExtract(extractConfig); - job.setConfiguration(jobConfig); + Job job = new Job() + .setJobReference(jobRef) + .setConfiguration( + new JobConfiguration().setExtract(extractConfig)); startJob(job, errorExtractor, client); } @@ -124,22 +140,17 @@ public void startExtractJob(String jobId, JobConfigurationExtract extractConfig) /** * {@inheritDoc} * - *

          Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

          the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC retries. + * @throws IOException if it exceeds max RPC . */ @Override - public void startQueryJob(String jobId, JobConfigurationQuery queryConfig, boolean dryRun) + public void startQueryJob(JobReference jobRef, JobConfigurationQuery queryConfig) throws IOException, InterruptedException { - Job job = new Job(); - JobReference jobRef = new JobReference(); - jobRef.setProjectId(queryConfig.getDestinationTable().getProjectId()); - jobRef.setJobId(jobId); - job.setJobReference(jobRef); - JobConfiguration jobConfig = new JobConfiguration(); - jobConfig.setQuery(queryConfig); - jobConfig.setDryRun(dryRun); - job.setConfiguration(jobConfig); + Job job = new Job() + .setJobReference(jobRef) + .setConfiguration( + new JobConfiguration().setQuery(queryConfig)); startJob(job, errorExtractor, client); } @@ -158,8 +169,7 @@ static void startJob( ApiErrorExtractor errorExtractor, Bigquery client, Sleeper sleeper, - BackOff backoff) - throws InterruptedException, IOException { + BackOff backoff) throws IOException, InterruptedException { JobReference jobRef = job.getJobReference(); Exception lastException = null; do { @@ -181,28 +191,27 @@ static void startJob( } while (nextBackOff(sleeper, backoff)); throw new IOException( String.format( - "Unable to insert job: %s, aborting after %d retries.", + "Unable to insert job: %s, aborting after %d .", jobRef.getJobId(), MAX_RPC_ATTEMPTS), lastException); } @Override - public Job pollJob(String projectId, String jobId, int maxAttempts) + public Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException { BackOff backoff = new AttemptBoundedExponentialBackOff( maxAttempts, INITIAL_JOB_STATUS_POLL_BACKOFF_MILLIS); - return pollJob(projectId, jobId, Sleeper.DEFAULT, backoff); + return pollJob(jobRef, Sleeper.DEFAULT, backoff); } @VisibleForTesting Job pollJob( - String projectId, - String jobId, + JobReference jobRef, Sleeper sleeper, BackOff backoff) throws InterruptedException { do { try { - Job job = client.jobs().get(projectId, jobId).execute(); + Job job = client.jobs().get(jobRef.getProjectId(), jobRef.getJobId()).execute(); JobStatus status = job.getStatus(); if (status != null && status.getState() != null && status.getState().equals("DONE")) { return job; @@ -213,22 +222,254 @@ Job pollJob( LOG.warn("Ignore the error and retry polling job status.", e); } } while (nextBackOff(sleeper, backoff)); - LOG.warn("Unable to poll job status: {}, aborting after reached max retries.", jobId); + LOG.warn("Unable to poll job status: {}, aborting after reached max .", jobRef.getJobId()); return null; } + @Override + public JobStatistics dryRunQuery(String projectId, String query) + throws InterruptedException, IOException { + Job job = new Job() + .setConfiguration(new JobConfiguration() + .setQuery(new JobConfigurationQuery() + .setQuery(query)) + .setDryRun(true)); + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + return executeWithRetries( + client.jobs().insert(projectId, job), + String.format( + "Unable to dry run query: %s, aborting after %d retries.", + query, MAX_RPC_ATTEMPTS), + Sleeper.DEFAULT, + backoff).getStatistics(); + } + } + + @VisibleForTesting + static class DatasetServiceImpl implements DatasetService { + private final ApiErrorExtractor errorExtractor; + private final Bigquery client; + + @VisibleForTesting + DatasetServiceImpl(Bigquery client) { + this.errorExtractor = new ApiErrorExtractor(); + this.client = client; + } + + private DatasetServiceImpl(BigQueryOptions bqOptions) { + this.errorExtractor = new ApiErrorExtractor(); + this.client = Transport.newBigQueryClient(bqOptions).build(); + } + /** - * Identical to {@link BackOffUtils#next} but without checked IOException. - * @throws InterruptedException + * {@inheritDoc} + * + *

          the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC . */ - private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) - throws InterruptedException { + @Override + public Table getTable(String projectId, String datasetId, String tableId) + throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + return executeWithRetries( + client.tables().get(projectId, datasetId, tableId), + String.format( + "Unable to get table: %s, aborting after %d retries.", + tableId, MAX_RPC_ATTEMPTS), + Sleeper.DEFAULT, + backoff); + } + + /** + * {@inheritDoc} + * + *

          the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC . + */ + @Override + public void deleteTable(String projectId, String datasetId, String tableId) + throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + executeWithRetries( + client.tables().delete(projectId, datasetId, tableId), + String.format( + "Unable to delete table: %s, aborting after %d retries.", + tableId, MAX_RPC_ATTEMPTS), + Sleeper.DEFAULT, + backoff); + } + + /** + * {@inheritDoc} + * + *

          the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC . + */ + @Override + public void createDataset( + String projectId, String datasetId, String location, String description) + throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + createDataset(projectId, datasetId, location, description, Sleeper.DEFAULT, backoff); + } + + @VisibleForTesting + void createDataset( + String projectId, + String datasetId, + String location, + String description, + Sleeper sleeper, + BackOff backoff) throws IOException, InterruptedException { + DatasetReference datasetRef = new DatasetReference() + .setProjectId(projectId) + .setDatasetId(datasetId); + + Dataset dataset = new Dataset() + .setDatasetReference(datasetRef) + .setLocation(location) + .setFriendlyName(location) + .setDescription(description); + + Exception lastException; + do { + try { + client.datasets().insert(projectId, dataset).execute(); + return; // SUCCEEDED + } catch (GoogleJsonResponseException e) { + if (errorExtractor.itemAlreadyExists(e)) { + return; // SUCCEEDED + } + // ignore and retry + LOG.warn("Ignore the error and retry creating the dataset.", e); + lastException = e; + } catch (IOException e) { + LOG.warn("Ignore the error and retry creating the dataset.", e); + lastException = e; + } + } while (nextBackOff(sleeper, backoff)); + throw new IOException( + String.format( + "Unable to create dataset: %s, aborting after %d .", + datasetId, MAX_RPC_ATTEMPTS), + lastException); + } + + /** + * {@inheritDoc} + * + *

          the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC . + */ + @Override + public void deleteDataset(String projectId, String datasetId) + throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + executeWithRetries( + client.datasets().delete(projectId, datasetId), + String.format( + "Unable to delete table: %s, aborting after %d retries.", + datasetId, MAX_RPC_ATTEMPTS), + Sleeper.DEFAULT, + backoff); + } + } + + private static class BigQueryJsonReaderImpl implements BigQueryJsonReader { + BigQueryTableRowIterator iterator; + + private BigQueryJsonReaderImpl(BigQueryTableRowIterator iterator) { + this.iterator = iterator; + } + + private static BigQueryJsonReader fromQuery( + BigQueryOptions bqOptions, + String query, + String projectId, + @Nullable Boolean flattenResults) { + return new BigQueryJsonReaderImpl( + BigQueryTableRowIterator.fromQuery( + query, projectId, Transport.newBigQueryClient(bqOptions).build(), flattenResults)); + } + + private static BigQueryJsonReader fromTable( + BigQueryOptions bqOptions, + TableReference tableRef) { + return new BigQueryJsonReaderImpl(BigQueryTableRowIterator.fromTable( + tableRef, Transport.newBigQueryClient(bqOptions).build())); + } + + @Override + public boolean start() throws IOException { try { - return BackOffUtils.next(sleeper, backoff); + iterator.open(); + return iterator.advance(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during start() operation", e); + } + } + + @Override + public boolean advance() throws IOException { + try { + return iterator.advance(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during advance() operation", e); + } + } + + @Override + public TableRow getCurrent() throws NoSuchElementException { + return iterator.getCurrent(); + } + + @Override + public void close() throws IOException { + iterator.close(); + } + } + + @VisibleForTesting + static T executeWithRetries( + AbstractGoogleClientRequest request, + String errorMessage, + Sleeper sleeper, + BackOff backoff) + throws IOException, InterruptedException { + Exception lastException = null; + do { + try { + return request.execute(); } catch (IOException e) { - throw new RuntimeException(e); + LOG.warn("Ignore the error and retry the request.", e); + lastException = e; } + } while (nextBackOff(sleeper, backoff)); + throw new IOException( + errorMessage, + lastException); + } + + /** + * Identical to {@link BackOffUtils#next} but without checked IOException. + * @throws InterruptedException + */ + private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { + try { + return BackOffUtils.next(sleeper, backoff); + } catch (IOException e) { + throw new RuntimeException(e); } } } - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 4c754d50d7..54066ff7da 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -16,12 +16,17 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.cloud.dataflow.sdk.io.BigQueryIO.fromJsonString; +import static com.google.cloud.dataflow.sdk.io.BigQueryIO.toJsonString; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; import com.google.api.client.util.Data; import com.google.api.services.bigquery.model.ErrorProto; @@ -29,31 +34,55 @@ import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatistics; +import com.google.api.services.bigquery.model.JobStatistics2; +import com.google.api.services.bigquery.model.JobStatistics4; import com.google.api.services.bigquery.model.JobStatus; +import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryQuerySource; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryTableSource; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.PassThroughThenCleanup; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.PassThroughThenCleanup.CleanupOperation; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Status; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.TransformingSource; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; +import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; +import com.google.cloud.dataflow.sdk.testing.SourceTestUtils.ExpectedSplitOutcome; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.BigQueryServices; +import com.google.cloud.dataflow.sdk.util.BigQueryServices.DatasetService; +import com.google.cloud.dataflow.sdk.util.BigQueryServices.JobService; import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.IOChannelFactory; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Before; @@ -65,18 +94,24 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.io.File; import java.io.FileFilter; import java.io.IOException; +import java.io.Serializable; +import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; + +import javax.annotation.Nullable; /** * Tests for BigQueryIO. */ @RunWith(JUnit4.class) -public class BigQueryIOTest { +public class BigQueryIOTest implements Serializable { // Status.UNKNOWN maps to null private static final Map JOB_STATUS_MAP = ImmutableMap.of( @@ -85,111 +120,192 @@ Status.SUCCEEDED, new Job().setStatus(new JobStatus()), private static class FakeBigQueryServices implements BigQueryServices { - private Object[] startJobReturns; - private Object[] pollJobStatusReturns; + private String[] jsonTableRowReturns = new String[0]; + private JobService jobService; + private DatasetService datasetService; - /** - * Sets the return values for the mock {@link JobService#startLoadJob}. - * - *

          Throws if the {@link Object} is a {@link Exception}, returns otherwise. - */ - private FakeBigQueryServices startLoadJobReturns(Object... startLoadJobReturns) { - this.startJobReturns = startLoadJobReturns; + public FakeBigQueryServices withJobService(JobService jobService) { + this.jobService = jobService; return this; } - /** - * Sets the return values for the mock {@link JobService#pollJobStatus}. - * - *

          Throws if the {@link Object} is a {@link Exception}, returns otherwise. - */ - private FakeBigQueryServices pollJobStatusReturns(Object... pollJobStatusReturns) { - this.pollJobStatusReturns = pollJobStatusReturns; + public FakeBigQueryServices withDatasetService(DatasetService datasetService) { + this.datasetService = datasetService; + return this; + } + + public FakeBigQueryServices readerReturns(String... jsonTableRowReturns) { + this.jsonTableRowReturns = jsonTableRowReturns; return this; } @Override public JobService getJobService(BigQueryOptions bqOptions) { - return new FakeLoadService(startJobReturns, pollJobStatusReturns); + return jobService; } - private static class FakeLoadService implements BigQueryServices.JobService { + @Override + public DatasetService getDatasetService(BigQueryOptions bqOptions) { + return datasetService; + } - private Object[] startJobReturns; - private Object[] pollJobStatusReturns; - private int startLoadJobCallsCount; - private int pollJobStatusCallsCount; + @Override + public BigQueryJsonReader getReaderFromTable( + BigQueryOptions bqOptions, TableReference tableRef) { + return new FakeBigQueryReader(jsonTableRowReturns); + } + + @Override + public BigQueryJsonReader getReaderFromQuery( + BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten) { + return new FakeBigQueryReader(jsonTableRowReturns); + } + + private static class FakeBigQueryReader implements BigQueryJsonReader { + private static final int UNSTARTED = -1; + private static final int CLOSED = Integer.MAX_VALUE; + + private String[] jsonTableRowReturns; + private int currIndex; - public FakeLoadService(Object[] startLoadJobReturns, Object[] pollJobStatusReturns) { - this.startJobReturns = startLoadJobReturns; - this.pollJobStatusReturns = pollJobStatusReturns; - this.startLoadJobCallsCount = 0; - this.pollJobStatusCallsCount = 0; + FakeBigQueryReader(String[] jsonTableRowReturns) { + this.jsonTableRowReturns = jsonTableRowReturns; + this.currIndex = UNSTARTED; } @Override - public void startLoadJob(String jobId, JobConfigurationLoad loadConfig) - throws InterruptedException, IOException { - startJob(); + public boolean start() throws IOException { + assertEquals(UNSTARTED, currIndex); + currIndex = 0; + return currIndex < jsonTableRowReturns.length; } @Override - public void startExtractJob(String jobId, JobConfigurationExtract extractConfig) - throws InterruptedException, IOException { - startJob(); + public boolean advance() throws IOException { + return ++currIndex < jsonTableRowReturns.length; } @Override - public void startQueryJob(String jobId, JobConfigurationQuery query, boolean dryRun) - throws IOException, InterruptedException { - startJob(); + public TableRow getCurrent() throws NoSuchElementException { + if (currIndex >= jsonTableRowReturns.length) { + throw new NoSuchElementException(); + } + return fromJsonString(jsonTableRowReturns[currIndex], TableRow.class); } @Override - public Job pollJob(String projectId, String jobId, int maxAttemps) - throws InterruptedException { - if (pollJobStatusCallsCount < pollJobStatusReturns.length) { - Object ret = pollJobStatusReturns[pollJobStatusCallsCount++]; - if (ret instanceof Status) { - return JOB_STATUS_MAP.get(ret); - } else if (ret instanceof InterruptedException) { - throw (InterruptedException) ret; - } else { - throw new RuntimeException("Unexpected return type: " + ret.getClass()); - } + public void close() throws IOException { + currIndex = CLOSED; + } + } + } + + private static class FakeJobService implements JobService, Serializable { + + private Object[] startJobReturns; + private Object[] pollJobReturns; + // Both counts will be reset back to zeros after serialization. + // This is a work around for DoFn's verifyUnmodified check. + private transient int startJobCallsCount; + private transient int pollJobStatusCallsCount; + + public FakeJobService() { + this.startJobReturns = new Object[0]; + this.pollJobReturns = new Object[0]; + this.startJobCallsCount = 0; + this.pollJobStatusCallsCount = 0; + } + + /** + * Sets the return values to mock {@link JobService#startLoadJob}, + * {@link JobService#startExtractJob} and {@link JobService#startQueryJob}. + * + *

          Throws if the {@link Object} is a {@link Exception}, returns otherwise. + */ + public FakeJobService startJobReturns(Object... startJobReturns) { + this.startJobReturns = startJobReturns; + return this; + } + + /** + * Sets the return values to mock {@link JobService#pollJob}. + * + *

          Throws if the {@link Object} is a {@link Exception}, returns otherwise. + */ + public FakeJobService pollJobReturns(Object... pollJobReturns) { + this.pollJobReturns = pollJobReturns; + return this; + } + + @Override + public void startLoadJob(JobReference jobRef, JobConfigurationLoad loadConfig) + throws InterruptedException, IOException { + startJob(); + } + + @Override + public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) + throws InterruptedException, IOException { + startJob(); + } + + @Override + public void startQueryJob(JobReference jobRef, JobConfigurationQuery query) + throws IOException, InterruptedException { + startJob(); + } + + @Override + public Job pollJob(JobReference jobRef, int maxAttempts) + throws InterruptedException { + if (pollJobStatusCallsCount < pollJobReturns.length) { + Object ret = pollJobReturns[pollJobStatusCallsCount++]; + if (ret instanceof Job) { + return (Job) ret; + } else if (ret instanceof Status) { + return JOB_STATUS_MAP.get(ret); + } else if (ret instanceof InterruptedException) { + throw (InterruptedException) ret; } else { - throw new RuntimeException( - "Exceeded expected number of calls: " + pollJobStatusReturns.length); + throw new RuntimeException("Unexpected return type: " + ret.getClass()); } + } else { + throw new RuntimeException( + "Exceeded expected number of calls: " + pollJobReturns.length); } + } - private void startJob() throws IOException, InterruptedException { - if (startLoadJobCallsCount < startJobReturns.length) { - Object ret = startJobReturns[startLoadJobCallsCount++]; - if (ret instanceof IOException) { - throw (IOException) ret; - } else if (ret instanceof InterruptedException) { - throw (InterruptedException) ret; - } else { - return; - } + private void startJob() throws IOException, InterruptedException { + if (startJobCallsCount < startJobReturns.length) { + Object ret = startJobReturns[startJobCallsCount++]; + if (ret instanceof IOException) { + throw (IOException) ret; + } else if (ret instanceof InterruptedException) { + throw (InterruptedException) ret; } else { - throw new RuntimeException( - "Exceeded expected number of calls: " + startJobReturns.length); + return; } + } else { + throw new RuntimeException( + "Exceeded expected number of calls: " + startJobReturns.length); } } + + @Override + public JobStatistics dryRunQuery(String projectId, String query) + throws InterruptedException, IOException { + throw new UnsupportedOperationException(); + } } - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public ExpectedLogs logged = ExpectedLogs.none(BigQueryIO.class); - @Rule - public TemporaryFolder testFolder = new TemporaryFolder(); - @Mock - public BigQueryServices.JobService mockBqLoadService; + @Rule public transient ExpectedException thrown = ExpectedException.none(); + @Rule public transient ExpectedLogs logged = ExpectedLogs.none(BigQueryIO.class); + @Rule public transient TemporaryFolder testFolder = new TemporaryFolder(); + @Mock public transient BigQueryServices.JobService mockJobService; + @Mock private transient IOChannelFactory mockIOChannelFactory; + @Mock private transient DatasetService mockDatasetService; - private BigQueryOptions bqOptions; + private transient BigQueryOptions bqOptions; private void checkReadTableObject( BigQueryIO.Read.Bound bound, String project, String dataset, String table) { @@ -203,16 +319,16 @@ private void checkReadQueryObject( private void checkReadTableObjectWithValidate( BigQueryIO.Read.Bound bound, String project, String dataset, String table, boolean validate) { - assertEquals(project, bound.table.getProjectId()); - assertEquals(dataset, bound.table.getDatasetId()); - assertEquals(table, bound.table.getTableId()); + assertEquals(project, bound.getTable().getProjectId()); + assertEquals(dataset, bound.getTable().getDatasetId()); + assertEquals(table, bound.getTable().getTableId()); assertNull(bound.query); assertEquals(validate, bound.getValidate()); } private void checkReadQueryObjectWithValidate( BigQueryIO.Read.Bound bound, String query, boolean validate) { - assertNull(bound.table); + assertNull(bound.getTable()); assertEquals(query, bound.query); assertEquals(validate, bound.getValidate()); } @@ -239,10 +355,10 @@ private void checkWriteObjectWithValidate( } @Before - public void setUp() { + public void setUp() throws IOException { bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation(testFolder.getRoot().getAbsolutePath() + "/BigQueryIOTest/"); + bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); MockitoAnnotations.initMocks(this); } @@ -313,11 +429,7 @@ public void testValidateReadSetsDefaultProject() { thrown.expectMessage( Matchers.either(Matchers.containsString("Unable to confirm BigQuery dataset presence")) .or(Matchers.containsString("BigQuery dataset not found for table"))); - try { - p.apply(BigQueryIO.Read.named("ReadMyTable").from(tableRef)); - } finally { - Assert.assertEquals("someproject", tableRef.getProjectId()); - } + p.apply(BigQueryIO.Read.named("ReadMyTable").from(tableRef)); } @Test @@ -361,11 +473,41 @@ public void testBuildSourceWithTableAndFlatten() { p.run(); } + @Test + public void testReadFromTable() { + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .withJobService(new FakeJobService() + .startJobReturns("done", "done") + .pollJobReturns(Status.UNKNOWN)) + .readerReturns( + toJsonString(new TableRow().set("name", "a").set("number", 1)), + toJsonString(new TableRow().set("name", "b").set("number", 2)), + toJsonString(new TableRow().set("name", "c").set("number", 3))); + + Pipeline p = TestPipeline.create(bqOptions); + PCollection output = p + .apply(BigQueryIO.Read.from("foo.com:project:somedataset.sometable") + .withTestServices(fakeBqServices) + .withoutValidation()) + .apply(ParDo.of(new DoFn() { + @Override + public void processElement(ProcessContext c) throws Exception { + c.output((String) c.element().get("name")); + } + })); + + DataflowAssert.that(output) + .containsInAnyOrder(ImmutableList.of("a", "b", "c")); + + p.run(); + } + @Test public void testCustomSink() throws Exception { FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .startLoadJobReturns("done", "done", "done") - .pollJobStatusReturns(Status.FAILED, Status.FAILED, Status.SUCCEEDED); + .withJobService(new FakeJobService() + .startJobReturns("done", "done", "done") + .pollJobReturns(Status.FAILED, Status.FAILED, Status.SUCCEEDED)); Pipeline p = TestPipeline.create(bqOptions); p.apply(Create.of( @@ -396,8 +538,9 @@ public boolean accept(File pathname) { @Test public void testCustomSinkUnknown() throws Exception { FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .startLoadJobReturns("done", "done") - .pollJobStatusReturns(Status.FAILED, Status.UNKNOWN); + .withJobService(new FakeJobService() + .startJobReturns("done", "done") + .pollJobReturns(Status.FAILED, Status.UNKNOWN)); Pipeline p = TestPipeline.create(bqOptions); p.apply(Create.of( @@ -715,4 +858,239 @@ public void testWriteValidateFailsNoTableAndNoTableSpec() { .apply(Create.of()) .apply(BigQueryIO.Write.named("name")); } + + @Test + public void testBigQueryTableSourceThroughJsonAPI() throws Exception { + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .withJobService(mockJobService) + .readerReturns( + toJsonString(new TableRow().set("name", "a").set("number", "1")), + toJsonString(new TableRow().set("name", "b").set("number", "2")), + toJsonString(new TableRow().set("name", "c").set("number", "3"))); + + String jobIdToken = "testJobIdToken"; + String jsonTable = toJsonString(BigQueryIO.parseTableSpec("project.data_set.table_name")); + String extractDestinationDir = "mock://tempLocation"; + BoundedSource bqSource = + BigQueryTableSource.create(jobIdToken, jsonTable, extractDestinationDir, fakeBqServices); + + List expected = ImmutableList.of( + new TableRow().set("name", "a").set("number", "1"), + new TableRow().set("name", "b").set("number", "2"), + new TableRow().set("name", "c").set("number", "3")); + + PipelineOptions options = PipelineOptionsFactory.create(); + Assert.assertThat( + SourceTestUtils.readFromSource(bqSource, options), + CoreMatchers.is(expected)); + SourceTestUtils.assertSplitAtFractionBehavior( + bqSource, 2, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); + } + + @Test + public void testBigQueryTableSourceInitSplit() throws Exception { + Job extractJob = new Job(); + JobStatistics jobStats = new JobStatistics(); + JobStatistics4 extractStats = new JobStatistics4(); + extractStats.setDestinationUriFileCounts(ImmutableList.of(1L)); + jobStats.setExtract(extractStats); + extractJob.setStatus(new JobStatus()) + .setStatistics(jobStats); + + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .withJobService(mockJobService) + .withDatasetService(mockDatasetService) + .readerReturns( + toJsonString(new TableRow().set("name", "a").set("number", "1")), + toJsonString(new TableRow().set("name", "b").set("number", "2")), + toJsonString(new TableRow().set("name", "c").set("number", "3"))); + + String jobIdToken = "testJobIdToken"; + String jsonTable = toJsonString(BigQueryIO.parseTableSpec("project.data_set.table_name")); + String extractDestinationDir = "mock://tempLocation"; + BoundedSource bqSource = + BigQueryTableSource.create(jobIdToken, jsonTable, extractDestinationDir, fakeBqServices); + + List expected = ImmutableList.of( + new TableRow().set("name", "a").set("number", "1"), + new TableRow().set("name", "b").set("number", "2"), + new TableRow().set("name", "c").set("number", "3")); + + when(mockJobService.pollJob(Mockito.any(), Mockito.anyInt())) + .thenReturn(extractJob); + PipelineOptions options = PipelineOptionsFactory.create(); + options.setTempLocation("mock://tempLocation"); + + IOChannelUtils.setIOFactory("mock", mockIOChannelFactory); + when(mockIOChannelFactory.resolve(anyString(), anyString())) + .thenReturn("mock://tempLocation/output"); + when(mockDatasetService.getTable(anyString(), anyString(), anyString())) + .thenReturn(new Table().setSchema(new TableSchema())); + + Assert.assertThat( + SourceTestUtils.readFromSource(bqSource, options), + CoreMatchers.is(expected)); + SourceTestUtils.assertSplitAtFractionBehavior( + bqSource, 2, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); + + List> sources = bqSource.splitIntoBundles(100, options); + assertEquals(1, sources.size()); + BoundedSource actual = sources.get(0); + assertThat(actual, CoreMatchers.instanceOf(TransformingSource.class)); + + Mockito.verify(mockJobService) + .startExtractJob(Mockito.any(), Mockito.any()); + } + + @Test + public void testBigQueryQuerySourceInitSplit() throws Exception { + TableReference dryRunTable = new TableReference(); + + Job queryJob = new Job(); + JobStatistics queryJobStats = new JobStatistics(); + JobStatistics2 queryStats = new JobStatistics2(); + queryStats.setReferencedTables(ImmutableList.of(dryRunTable)); + queryJobStats.setQuery(queryStats); + queryJob.setStatus(new JobStatus()) + .setStatistics(queryJobStats); + + Job extractJob = new Job(); + JobStatistics extractJobStats = new JobStatistics(); + JobStatistics4 extractStats = new JobStatistics4(); + extractStats.setDestinationUriFileCounts(ImmutableList.of(1L)); + extractJobStats.setExtract(extractStats); + extractJob.setStatus(new JobStatus()) + .setStatistics(extractJobStats); + + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .withJobService(mockJobService) + .withDatasetService(mockDatasetService) + .readerReturns( + toJsonString(new TableRow().set("name", "a").set("number", "1")), + toJsonString(new TableRow().set("name", "b").set("number", "2")), + toJsonString(new TableRow().set("name", "c").set("number", "3"))); + + String jobIdToken = "testJobIdToken"; + String extractDestinationDir = "mock://tempLocation"; + TableReference destinationTable = BigQueryIO.parseTableSpec("project.data_set.table_name"); + String jsonDestinationTable = toJsonString(destinationTable); + BoundedSource bqSource = BigQueryQuerySource.create( + jobIdToken, "query", jsonDestinationTable, true /* flattenResults */, + extractDestinationDir, fakeBqServices); + + List expected = ImmutableList.of( + new TableRow().set("name", "a").set("number", "1"), + new TableRow().set("name", "b").set("number", "2"), + new TableRow().set("name", "c").set("number", "3")); + + PipelineOptions options = PipelineOptionsFactory.create(); + options.setTempLocation(extractDestinationDir); + + TableReference queryTable = new TableReference() + .setProjectId("testProejct") + .setDatasetId("testDataset") + .setTableId("testTable"); + when(mockJobService.dryRunQuery(anyString(), anyString())) + .thenReturn(new JobStatistics().setQuery( + new JobStatistics2() + .setTotalBytesProcessed(100L) + .setReferencedTables(ImmutableList.of(queryTable)))); + when(mockDatasetService.getTable( + eq(queryTable.getProjectId()), eq(queryTable.getDatasetId()), eq(queryTable.getTableId()))) + .thenReturn(new Table().setSchema(new TableSchema())); + when(mockDatasetService.getTable( + eq(destinationTable.getProjectId()), + eq(destinationTable.getDatasetId()), + eq(destinationTable.getTableId()))) + .thenReturn(new Table().setSchema(new TableSchema())); + IOChannelUtils.setIOFactory("mock", mockIOChannelFactory); + when(mockIOChannelFactory.resolve(anyString(), anyString())) + .thenReturn("mock://tempLocation/output"); + when(mockJobService.pollJob(Mockito.any(), Mockito.anyInt())) + .thenReturn(extractJob); + + Assert.assertThat( + SourceTestUtils.readFromSource(bqSource, options), + CoreMatchers.is(expected)); + SourceTestUtils.assertSplitAtFractionBehavior( + bqSource, 2, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); + + List> sources = bqSource.splitIntoBundles(100, options); + assertEquals(1, sources.size()); + BoundedSource actual = sources.get(0); + assertThat(actual, CoreMatchers.instanceOf(TransformingSource.class)); + + Mockito.verify(mockJobService) + .startQueryJob( + Mockito.any(), Mockito.any()); + Mockito.verify(mockJobService) + .startExtractJob(Mockito.any(), Mockito.any()); + Mockito.verify(mockDatasetService) + .createDataset(anyString(), anyString(), anyString(), anyString()); + } + + @Test + public void testTransformingSource() throws Exception { + int numElements = 10000; + @SuppressWarnings("deprecation") + BoundedSource longSource = CountingSource.upTo(numElements); + SerializableFunction toStringFn = + new SerializableFunction() { + @Override + public String apply(Long input) { + return input.toString(); + }}; + BoundedSource stringSource = new TransformingSource<>( + longSource, toStringFn, StringUtf8Coder.of()); + + List expected = Lists.newArrayList(); + for (int i = 0; i < numElements; i++) { + expected.add(String.valueOf(i)); + } + + PipelineOptions options = PipelineOptionsFactory.create(); + Assert.assertThat( + SourceTestUtils.readFromSource(stringSource, options), + CoreMatchers.is(expected)); + SourceTestUtils.assertSplitAtFractionBehavior( + stringSource, 100, 0.3, ExpectedSplitOutcome.MUST_SUCCEED_AND_BE_CONSISTENT, options); + + SourceTestUtils.assertSourcesEqualReferenceSource( + stringSource, stringSource.splitIntoBundles(100, options), options); + } + + @Test + @Category(RunnableOnService.class) + public void testPassThroughThenCleanup() throws Exception { + Pipeline p = TestPipeline.create(); + + PCollection output = p + .apply(Create.of(1, 2, 3)) + .apply(new PassThroughThenCleanup(new CleanupOperation() { + @Override + void cleanup(PipelineOptions options) throws Exception { + // no-op + }})); + + DataflowAssert.that(output).containsInAnyOrder(1, 2, 3); + + p.run(); + } + + @Test + public void testPassThroughThenCleanupExecuted() throws Exception { + Pipeline p = TestPipeline.create(); + + p.apply(Create.of()) + .apply(new PassThroughThenCleanup(new CleanupOperation() { + @Override + void cleanup(PipelineOptions options) throws Exception { + throw new RuntimeException("cleanup executed"); + }})); + + thrown.expect(RuntimeException.class); + thrown.expectMessage("cleanup executed"); + + p.run(); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java index e9ca0ebadd..d9de2ab5b0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java @@ -37,6 +37,7 @@ import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatus; +import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableReference; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; @@ -114,6 +115,7 @@ public void testStartLoadJobSucceeds() throws IOException, InterruptedException BackOff backoff = new AttemptBoundedExponentialBackOff( 5 /* attempts */, 1000 /* initialIntervalMillis */); JobServiceImpl.startJob(testJob, new ApiErrorExtractor(), bigquery, sleeper, backoff); + verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); verify(response, times(1)).getContentType(); @@ -195,8 +197,10 @@ public void testPollJobSucceeds() throws IOException, InterruptedException { BigQueryServicesImpl.JobServiceImpl jobService = new BigQueryServicesImpl.JobServiceImpl(bigquery); - Job job = - jobService.pollJob("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + JobReference jobRef = new JobReference() + .setProjectId("projectId") + .setJobId("jobId"); + Job job = jobService.pollJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); assertEquals(testJob, job); verify(response, times(1)).getStatusCode(); @@ -218,8 +222,10 @@ public void testPollJobFailed() throws IOException, InterruptedException { BigQueryServicesImpl.JobServiceImpl jobService = new BigQueryServicesImpl.JobServiceImpl(bigquery); - Job job = - jobService.pollJob("projectId", "jobId", Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + JobReference jobRef = new JobReference() + .setProjectId("projectId") + .setJobId("jobId"); + Job job = jobService.pollJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); assertEquals(testJob, job); verify(response, times(1)).getStatusCode(); @@ -241,8 +247,10 @@ public void testPollJobUnknown() throws IOException, InterruptedException { BigQueryServicesImpl.JobServiceImpl jobService = new BigQueryServicesImpl.JobServiceImpl(bigquery); - Job job = - jobService.pollJob("projectId", "jobId", Sleeper.DEFAULT, BackOff.STOP_BACKOFF); + JobReference jobRef = new JobReference() + .setProjectId("projectId") + .setJobId("jobId"); + Job job = jobService.pollJob(jobRef, Sleeper.DEFAULT, BackOff.STOP_BACKOFF); assertEquals(null, job); verify(response, times(1)).getStatusCode(); @@ -250,6 +258,26 @@ public void testPollJobUnknown() throws IOException, InterruptedException { verify(response, times(1)).getContentType(); } + @Test + public void testExecuteWithRetries() throws IOException, InterruptedException { + Table testTable = new Table(); + + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(200); + when(response.getContent()).thenReturn(toStream(testTable)); + + Table table = BigQueryServicesImpl.executeWithRetries( + bigquery.tables().get("projectId", "datasetId", "tableId"), + "Failed to get table.", + Sleeper.DEFAULT, + BackOff.STOP_BACKOFF); + + assertEquals(testTable, table); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + /** A helper to wrap a {@link GenericJson} object in a content stream. */ private static InputStream toStream(GenericJson content) throws IOException { return new ByteArrayInputStream(JacksonFactory.getDefaultInstance().toByteArray(content)); From 9ed6e02bbfb7fad2ec81b26df238ee478489c770 Mon Sep 17 00:00:00 2001 From: peihe Date: Fri, 13 May 2016 17:53:43 -0700 Subject: [PATCH 395/751] Backport from Beam PR: Fixup the log message format in GcsUtil.copy() (#264) --- .../java/com/google/cloud/dataflow/sdk/util/GcsUtil.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java index d170c9a5c6..9572a7de63 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java @@ -371,8 +371,9 @@ public boolean shouldRetry(IOException e) { public void copy(List srcFilenames, List destFilenames) throws IOException { Preconditions.checkArgument( srcFilenames.size() == destFilenames.size(), - String.format("Number of source files {} must equal number of destination files {}", - srcFilenames.size(), destFilenames.size())); + "Number of source files %s must equal number of destination files %s", + srcFilenames.size(), + destFilenames.size()); for (int i = 0; i < srcFilenames.size(); i++) { final GcsPath sourcePath = GcsPath.fromUri(srcFilenames.get(i)); final GcsPath destPath = GcsPath.fromUri(destFilenames.get(i)); From 0817bde64cef4da8125a5af1d974cf6aaa8e39fd Mon Sep 17 00:00:00 2001 From: peihe Date: Fri, 13 May 2016 17:59:34 -0700 Subject: [PATCH 396/751] Override BigQueryIO.Read with native source for Dataflow runner (#265) --- .../sdk/runners/DataflowPipelineRunner.java | 84 +++++++++++++++++++ .../runners/DataflowPipelineTranslator.java | 5 -- .../dataflow/BigQueryIOTranslator.java | 70 ---------------- 3 files changed, 84 insertions(+), 75 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index e691fdac0f..cde0e7b407 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -372,6 +372,10 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(View.AsList.class, BatchViewAsList.class); builder.put(View.AsIterable.class, BatchViewAsIterable.class); } + if (options.getExperiments() == null + || !options.getExperiments().contains("enable_custom_bigquery_source")) { + builder.put(BigQueryIO.Read.Bound.class, BatchBigQueryIONativeRead.class); + } if (options.getExperiments() == null || !options.getExperiments().contains("enable_custom_bigquery_sink")) { builder.put(BigQueryIO.Write.Bound.class, BatchBigQueryIOWrite.class); @@ -2106,6 +2110,86 @@ public PDone apply(PCollection input) { } } + /** + * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way + * to provide the native definition of the BigQuery sink. + */ + private static class BatchBigQueryIONativeRead extends PTransform> { + private final BigQueryIO.Read.Bound transform; + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public BatchBigQueryIONativeRead( + DataflowPipelineRunner runner, BigQueryIO.Read.Bound transform) { + this.transform = transform; + } + + @Override + public PCollection apply(PInput input) { + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), + WindowingStrategy.globalDefault(), + IsBounded.BOUNDED) + // Force the output's Coder to be what the read is using, and + // unchangeable later, to ensure that we read the input in the + // format specified by the Read transform. + .setCoder(TableRowJsonCoder.of()); + } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + BatchBigQueryIONativeRead.class, new BatchBigQueryIONativeReadTranslator()); + } + } + + /** + * Implements BigQueryIO Read translation for the Dataflow backend. + */ + public static class BatchBigQueryIONativeReadTranslator + implements DataflowPipelineTranslator.TransformTranslator { + + @Override + public void translate( + BatchBigQueryIONativeRead transform, + DataflowPipelineTranslator.TranslationContext context) { + translateWriteHelper(transform, transform.transform, context); + } + + private void translateWriteHelper( + BatchBigQueryIONativeRead transform, + BigQueryIO.Read.Bound originalTransform, + TranslationContext context) { + // Actual translation. + context.addStep(transform, "ParallelRead"); + context.addInput(PropertyNames.FORMAT, "bigquery"); + context.addInput(PropertyNames.BIGQUERY_EXPORT_FORMAT, "FORMAT_AVRO"); + + if (originalTransform.getQuery() != null) { + context.addInput(PropertyNames.BIGQUERY_QUERY, originalTransform.getQuery()); + context.addInput( + PropertyNames.BIGQUERY_FLATTEN_RESULTS, originalTransform.getFlattenResults()); + } else { + TableReference table = originalTransform.getTable(); + if (table.getProjectId() == null) { + // If user does not specify a project we assume the table to be located in the project + // that owns the Dataflow job. + String projectIdFromOptions = context.getPipelineOptions().getProject(); + LOG.warn(String.format(BigQueryIO.SET_PROJECT_FROM_OPTIONS_WARNING, table.getDatasetId(), + table.getDatasetId(), table.getTableId(), projectIdFromOptions)); + table.setProjectId(projectIdFromOptions); + } + + context.addInput(PropertyNames.BIGQUERY_TABLE, table.getTableId()); + context.addInput(PropertyNames.BIGQUERY_DATASET, table.getDatasetId()); + if (table.getProjectId() != null) { + context.addInput(PropertyNames.BIGQUERY_PROJECT, table.getProjectId()); + } + } + context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); + } + } + private static class BatchBigQueryIOWrite extends PTransform, PDone> { private final BigQueryIO.Write.Bound transform; /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 32dfb876ff..19bc3d82d7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -41,13 +41,11 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; -import com.google.cloud.dataflow.sdk.runners.dataflow.BigQueryIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -1036,9 +1034,6 @@ private void translateHelper( /////////////////////////////////////////////////////////////////////////// // IO Translation. - registerTransformTranslator( - BigQueryIO.Read.Bound.class, new BigQueryIOTranslator.ReadTranslator()); - registerTransformTranslator( PubsubIO.Read.Bound.class, new PubsubIOTranslator.ReadTranslator()); registerTransformTranslator( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java deleted file mode 100644 index c327ecf434..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/BigQueryIOTranslator.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.api.services.bigquery.model.TableReference; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * BigQuery transform support code for the Dataflow backend. - */ -public class BigQueryIOTranslator { - private static final Logger LOG = LoggerFactory.getLogger(BigQueryIOTranslator.class); - - /** - * Implements BigQueryIO Read translation for the Dataflow backend. - */ - public static class ReadTranslator - implements DataflowPipelineTranslator.TransformTranslator { - - @Override - public void translate( - BigQueryIO.Read.Bound transform, DataflowPipelineTranslator.TranslationContext context) { - // Actual translation. - context.addStep(transform, "ParallelRead"); - context.addInput(PropertyNames.FORMAT, "bigquery"); - context.addInput(PropertyNames.BIGQUERY_EXPORT_FORMAT, "FORMAT_AVRO"); - - if (transform.getQuery() != null) { - context.addInput(PropertyNames.BIGQUERY_QUERY, transform.getQuery()); - context.addInput(PropertyNames.BIGQUERY_FLATTEN_RESULTS, transform.getFlattenResults()); - } else { - TableReference table = transform.getTable(); - if (table.getProjectId() == null) { - // If user does not specify a project we assume the table to be located in the project - // that owns the Dataflow job. - String projectIdFromOptions = context.getPipelineOptions().getProject(); - LOG.warn(String.format(BigQueryIO.SET_PROJECT_FROM_OPTIONS_WARNING, table.getDatasetId(), - table.getDatasetId(), table.getTableId(), projectIdFromOptions)); - table.setProjectId(projectIdFromOptions); - } - - context.addInput(PropertyNames.BIGQUERY_TABLE, table.getTableId()); - context.addInput(PropertyNames.BIGQUERY_DATASET, table.getDatasetId()); - if (table.getProjectId() != null) { - context.addInput(PropertyNames.BIGQUERY_PROJECT, table.getProjectId()); - } - } - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - } -} From 19263d2bed4709f9d113994c4c9f87e2110e08a3 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Sat, 14 May 2016 17:57:11 -0700 Subject: [PATCH 397/751] SerializableCloningThreadLocalCacheLoaderTest: move to correct directory (#266) Should be in test, not main. --- .../inprocess/SerializableCloningThreadLocalCacheLoaderTest.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename sdk/src/{main => test}/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java (100%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java similarity index 100% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java From f163e6e39d028826f8adb1dd978a5f5863e4167c Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Sat, 14 May 2016 18:27:39 -0700 Subject: [PATCH 398/751] Move ThreadLocalInvalidatingTransformEvaluatorTest.java to the test subfolder Not main. --- .../inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename sdk/src/{main => test}/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java (100%) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java similarity index 100% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java From bd5cc482454bb37c755d7fafdbcb99da50710099 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Sun, 15 May 2016 17:48:43 -0700 Subject: [PATCH 399/751] BatchBigQueryIONativeReadTranslator: fixup format string Also, inline the constant and deprecate the one in BigQueryIO.java --- .../com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 2 +- .../dataflow/sdk/runners/DataflowPipelineRunner.java | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 413254a40e..dbe5f493e3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -272,7 +272,7 @@ public class BigQueryIO { private static final Pattern TABLE_SPEC = Pattern.compile(DATASET_TABLE_REGEXP); - // TODO: make this private and remove improper access from BigQueryIOTranslator. + @Deprecated // unused. public static final String SET_PROJECT_FROM_OPTIONS_WARNING = "No project specified for BigQuery table \"%1$s.%2$s\". Assuming it is in \"%3$s\". If the" + " table is in a different project please specify it as a part of the BigQuery table" diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index cde0e7b407..3690b62c7d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -2175,8 +2175,13 @@ private void translateWriteHelper( // If user does not specify a project we assume the table to be located in the project // that owns the Dataflow job. String projectIdFromOptions = context.getPipelineOptions().getProject(); - LOG.warn(String.format(BigQueryIO.SET_PROJECT_FROM_OPTIONS_WARNING, table.getDatasetId(), - table.getDatasetId(), table.getTableId(), projectIdFromOptions)); + LOG.warn( + "No project specified for BigQuery table \"{}.{}\". Assuming it is in \"{}\". If the" + + " table is in a different project please specify it as a part of the BigQuery table" + + " definition.", + table.getDatasetId(), + table.getTableId(), + projectIdFromOptions); table.setProjectId(projectIdFromOptions); } From 9ddcc89dbc7108a7ac1c3c98aba3d9bb880ea2dd Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 16 May 2016 09:31:10 -0700 Subject: [PATCH 400/751] Revert IsmFormat AutoValue conversion This reverts parts of commit c18c58f0722d2a6d97c4a8cfb62a7fb858d01bf5 to move IsmFormat.java to AutoValue. It keeps AutoValue integration which other classes depend on. --- .../sdk/runners/worker/IsmFormat.java | 241 +++++++++++++----- 1 file changed, 183 insertions(+), 58 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java index dc4a095ece..318de9b5b8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java @@ -20,7 +20,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import com.google.auto.value.AutoValue; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -36,6 +35,8 @@ import com.google.cloud.dataflow.sdk.util.VarInt; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; +import com.google.common.base.MoreObjects.ToStringHelper; +import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashFunction; @@ -50,6 +51,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; @@ -115,38 +117,44 @@ public class IsmFormat { * keys are used to create a shard id via hashing. See {@link IsmRecordCoder#hash(List)} for * further details. */ - @AutoValue - public abstract static class IsmRecord { - abstract List keyComponents(); - @Nullable abstract V value(); - @Nullable abstract byte[] metadata(); - - IsmRecord() {} - + public static class IsmRecord { /** Returns an IsmRecord with the specified key components and value. */ public static IsmRecord of(List keyComponents, V value) { + checkNotNull(keyComponents); checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); checkArgument(!isMetadataKey(keyComponents), "Expected key components to not contain metadata key."); - return new AutoValue_IsmFormat_IsmRecord(keyComponents, value, null); + return new IsmRecord<>(keyComponents, value, null); } public static IsmRecord meta(List keyComponents, byte[] metadata) { + checkNotNull(keyComponents); checkNotNull(metadata); checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); checkArgument(isMetadataKey(keyComponents), "Expected key components to contain metadata key."); - return new AutoValue_IsmFormat_IsmRecord(keyComponents, null, metadata); + return new IsmRecord(keyComponents, null, metadata); + } + + private final List keyComponents; + @Nullable + private final V value; + @Nullable + private final byte[] metadata; + private IsmRecord(List keyComponents, V value, byte[] metadata) { + this.keyComponents = keyComponents; + this.value = value; + this.metadata = metadata; } /** Returns the list of key components. */ public List getKeyComponents() { - return keyComponents(); + return keyComponents; } /** Returns the key component at the specified index. */ public Object getKeyComponent(int index) { - return keyComponents().get(index); + return keyComponents.get(index); } /** @@ -154,9 +162,9 @@ public Object getKeyComponent(int index) { * value record. */ public V getValue() { - checkState(!isMetadataKey(keyComponents()), + checkState(!isMetadataKey(keyComponents), "This is a metadata record and not a value record."); - return value(); + return value; } /** @@ -164,9 +172,37 @@ public V getValue() { * metadata record. */ public byte[] getMetadata() { - checkState(isMetadataKey(keyComponents()), + checkState(isMetadataKey(keyComponents), "This is a value record and not a metadata record."); - return metadata(); + return metadata; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof IsmRecord)) { + return false; + } + IsmRecord other = (IsmRecord) obj; + return Objects.equal(keyComponents, other.keyComponents) + && Objects.equal(value, other.value) + && Arrays.equals(metadata, other.metadata); + } + + @Override + public int hashCode() { + return Objects.hashCode(keyComponents, value, Arrays.hashCode(metadata)); + } + + @Override + public String toString() { + ToStringHelper builder = MoreObjects.toStringHelper(IsmRecord.class) + .add("keyComponents", keyComponents); + if (isMetadataKey(keyComponents)) { + builder.add("metadata", metadata); + } else { + builder.add("value", value); + } + return builder.toString(); } } @@ -549,17 +585,14 @@ public void verifyDeterministic() throws NonDeterministicException { * A shard descriptor containing shard id, the data block offset, and the index offset for the * given shard. */ - @AutoValue - public abstract static class IsmShard { - abstract int id(); - abstract long blockOffset(); - abstract long indexOffset(); - - IsmShard() {} + public static class IsmShard { + private final int id; + private final long blockOffset; + private final long indexOffset; /** Returns an IsmShard with the given id, block offset and no index offset. */ public static IsmShard of(int id, long blockOffset) { - IsmShard ismShard = new AutoValue_IsmFormat_IsmShard(id, blockOffset, -1); + IsmShard ismShard = new IsmShard(id, blockOffset, -1); checkState(id >= 0, "%s attempting to be written with negative shard id.", ismShard); @@ -571,7 +604,7 @@ public static IsmShard of(int id, long blockOffset) { /** Returns an IsmShard with the given id, block offset, and index offset. */ public static IsmShard of(int id, long blockOffset, long indexOffset) { - IsmShard ismShard = new AutoValue_IsmFormat_IsmShard(id, blockOffset, indexOffset); + IsmShard ismShard = new IsmShard(id, blockOffset, indexOffset); checkState(id >= 0, "%s attempting to be written with negative shard id.", ismShard); @@ -584,14 +617,20 @@ public static IsmShard of(int id, long blockOffset, long indexOffset) { return ismShard; } + private IsmShard(int id, long blockOffset, long indexOffset) { + this.id = id; + this.blockOffset = blockOffset; + this.indexOffset = indexOffset; + } + /** Return the shard id. */ public int getId() { - return id(); + return id; } /** Return the absolute position within the Ism file where the data block begins. */ public long getBlockOffset() { - return blockOffset(); + return blockOffset; } /** @@ -599,14 +638,39 @@ public long getBlockOffset() { * Throws {@link IllegalStateException} if the index offset was never specified. */ public long getIndexOffset() { - checkState(indexOffset() >= 0, + checkState(indexOffset >= 0, "Unable to fetch index offset because it was never specified."); - return indexOffset(); + return indexOffset; } /** Returns a new IsmShard like this one with the specified index offset. */ public IsmShard withIndexOffset(long indexOffset) { - return of(id(), blockOffset(), indexOffset); + return of(id, blockOffset, indexOffset); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(IsmShard.class) + .add("id", id) + .add("blockOffset", blockOffset) + .add("indexOffset", indexOffset) + .toString(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof IsmShard)) { + return false; + } + IsmShard other = (IsmShard) obj; + return Objects.equal(id, other.id) + && Objects.equal(blockOffset, other.blockOffset) + && Objects.equal(indexOffset, other.indexOffset); + } + + @Override + public int hashCode() { + return Objects.hashCode(id, blockOffset, indexOffset); } } @@ -678,15 +742,47 @@ public boolean consistentWithEquals() { *

        • number of unshared key bytes (variable length integer coding)
        • * */ - @AutoValue - abstract static class KeyPrefix { - public abstract int getSharedKeySize(); - public abstract int getUnsharedKeySize(); + static class KeyPrefix { + private final int sharedKeySize; + private final int unsharedKeySize; + + KeyPrefix(int sharedBytes, int unsharedBytes) { + this.sharedKeySize = sharedBytes; + this.unsharedKeySize = unsharedBytes; + } - KeyPrefix() {} + public int getSharedKeySize() { + return sharedKeySize; + } + + public int getUnsharedKeySize() { + return unsharedKeySize; + } - static KeyPrefix of(int sharedKeySize, int unsharedKeySize) { - return new AutoValue_IsmFormat_KeyPrefix(sharedKeySize, unsharedKeySize); + @Override + public int hashCode() { + return Objects.hashCode(sharedKeySize, unsharedKeySize); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof KeyPrefix)) { + return false; + } + KeyPrefix keyPrefix = (KeyPrefix) other; + return sharedKeySize == keyPrefix.sharedKeySize + && unsharedKeySize == keyPrefix.unsharedKeySize; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("sharedKeySize", sharedKeySize) + .add("unsharedKeySize", unsharedKeySize) + .toString(); } } @@ -702,14 +798,14 @@ public static KeyPrefixCoder of() { @Override public void encode(KeyPrefix value, OutputStream outStream, Coder.Context context) throws CoderException, IOException { - VarInt.encode(value.getSharedKeySize(), outStream); - VarInt.encode(value.getUnsharedKeySize(), outStream); + VarInt.encode(value.sharedKeySize, outStream); + VarInt.encode(value.unsharedKeySize, outStream); } @Override public KeyPrefix decode(InputStream inStream, Coder.Context context) throws CoderException, IOException { - return KeyPrefix.of(VarInt.decodeInt(inStream), VarInt.decodeInt(inStream)); + return new KeyPrefix(VarInt.decodeInt(inStream), VarInt.decodeInt(inStream)); } @Override @@ -726,8 +822,7 @@ public boolean isRegisterByteSizeObserverCheap(KeyPrefix value, Coder.Context co protected long getEncodedElementByteSize(KeyPrefix value, Coder.Context context) throws Exception { Preconditions.checkNotNull(value); - return VarInt.getLength(value.getSharedKeySize()) - + VarInt.getLength(value.getUnsharedKeySize()); + return VarInt.getLength(value.sharedKeySize) + VarInt.getLength(value.unsharedKeySize); } } @@ -743,29 +838,59 @@ protected long getEncodedElementByteSize(KeyPrefix value, Coder.Context context) *
        • 0x01 (version key as a single byte)
        • * */ - @AutoValue - abstract static class Footer { + static class Footer { static final int LONG_BYTES = 8; static final int FIXED_LENGTH = 3 * LONG_BYTES + 1; static final byte VERSION = 2; - public abstract long getIndexPosition(); - public abstract long getBloomFilterPosition(); - public abstract long getNumberOfKeys(); + private final long indexPosition; + private final long bloomFilterPosition; + private final long numberOfKeys; + + Footer(long indexPosition, long bloomFilterPosition, long numberOfKeys) { + this.indexPosition = indexPosition; + this.bloomFilterPosition = bloomFilterPosition; + this.numberOfKeys = numberOfKeys; + } + + public long getIndexPosition() { + return indexPosition; + } + + public long getBloomFilterPosition() { + return bloomFilterPosition; + } + + public long getNumberOfKeys() { + return numberOfKeys; + } - Footer() {} + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof Footer)) { + return false; + } + Footer footer = (Footer) other; + return indexPosition == footer.indexPosition + && bloomFilterPosition == footer.bloomFilterPosition + && numberOfKeys == footer.numberOfKeys; + } - static Footer of(long indexPosition, long bloomFilterPosition, long numberOfKeys) { - return new AutoValue_IsmFormat_Footer(indexPosition, bloomFilterPosition, numberOfKeys); + @Override + public int hashCode() { + return Objects.hashCode(indexPosition, bloomFilterPosition, numberOfKeys); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("version", Footer.VERSION) - .add("indexPosition", getIndexPosition()) - .add("bloomFilterPosition", getBloomFilterPosition()) - .add("numberOfKeys", getNumberOfKeys()) + .add("indexPosition", indexPosition) + .add("bloomFilterPosition", bloomFilterPosition) + .add("numberOfKeys", numberOfKeys) .toString(); } } @@ -783,9 +908,9 @@ public static FooterCoder of() { public void encode(Footer value, OutputStream outStream, Coder.Context context) throws CoderException, IOException { DataOutputStream dataOut = new DataOutputStream(outStream); - dataOut.writeLong(value.getIndexPosition()); - dataOut.writeLong(value.getBloomFilterPosition()); - dataOut.writeLong(value.getNumberOfKeys()); + dataOut.writeLong(value.indexPosition); + dataOut.writeLong(value.bloomFilterPosition); + dataOut.writeLong(value.numberOfKeys); dataOut.write(Footer.VERSION); } @@ -793,7 +918,7 @@ public void encode(Footer value, OutputStream outStream, Coder.Context context) public Footer decode(InputStream inStream, Coder.Context context) throws CoderException, IOException { DataInputStream dataIn = new DataInputStream(inStream); - Footer footer = Footer.of(dataIn.readLong(), dataIn.readLong(), dataIn.readLong()); + Footer footer = new Footer(dataIn.readLong(), dataIn.readLong(), dataIn.readLong()); int version = dataIn.read(); if (version != Footer.VERSION) { throw new IOException("Unknown version " + version + ". " From 85e138cc94ff28fdc5aa286df15b23eaa7aaeb6d Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 16 May 2016 09:42:21 -0700 Subject: [PATCH 401/751] Revert "Reuse DoFns in ParDoEvaluators" This reverts commit 46298e3ff7f86fb637efdbfd1a6897b3e405ba97. --- .../inprocess/ParDoMultiEvaluatorFactory.java | 37 ++--- .../ParDoSingleEvaluatorFactory.java | 38 ++--- ...alizableCloningThreadLocalCacheLoader.java | 51 ------- ...adLocalInvalidatingTransformEvaluator.java | 61 -------- ...ableCloningThreadLocalCacheLoaderTest.java | 96 ------------- ...calInvalidatingTransformEvaluatorTest.java | 133 ------------------ 6 files changed, 20 insertions(+), 396 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java index 9802f46f68..245115b95b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java @@ -24,9 +24,6 @@ import com.google.cloud.dataflow.sdk.values.PCollectionTuple; import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.LoadingCache; - import java.util.Map; /** @@ -34,13 +31,6 @@ * {@link BoundMulti} primitive {@link PTransform}. */ class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory { - private final LoadingCache, ThreadLocal>> fnClones; - - public ParDoMultiEvaluatorFactory() { - fnClones = CacheBuilder.newBuilder() - .build(SerializableCloningThreadLocalCacheLoader.>create()); - } - @Override public TransformEvaluator forApplication( AppliedPTransform application, @@ -52,28 +42,21 @@ public TransformEvaluator forApplication( return evaluator; } - private TransformEvaluator createMultiEvaluator( + private static ParDoInProcessEvaluator createMultiEvaluator( AppliedPTransform, PCollectionTuple, BoundMulti> application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { Map, PCollection> outputs = application.getOutput().getAll(); DoFn fn = application.getTransform().getFn(); - @SuppressWarnings({"unchecked", "rawtypes"}) ThreadLocal> fnLocal = - (ThreadLocal) fnClones.getUnchecked(application.getTransform().getFn()); - try { - TransformEvaluator parDoEvaluator = ParDoInProcessEvaluator.create(evaluationContext, - inputBundle, - application, - fnLocal.get(), - application.getTransform().getSideInputs(), - application.getTransform().getMainOutputTag(), - application.getTransform().getSideOutputTags().getAll(), - outputs); - return ThreadLocalInvalidatingTransformEvaluator.wrapping(parDoEvaluator, fnLocal); - } catch (Exception e) { - fnLocal.remove(); - throw e; - } + return ParDoInProcessEvaluator.create( + evaluationContext, + inputBundle, + application, + fn, + application.getTransform().getSideInputs(), + application.getTransform().getMainOutputTag(), + application.getTransform().getSideOutputTags().getAll(), + outputs); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java index 7de5bf2d2f..4d46fd1c1b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java @@ -17,13 +17,10 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableMap; import java.util.Collections; @@ -33,13 +30,6 @@ * {@link Bound ParDo.Bound} primitive {@link PTransform}. */ class ParDoSingleEvaluatorFactory implements TransformEvaluatorFactory { - private final LoadingCache, ThreadLocal>> fnClones; - - public ParDoSingleEvaluatorFactory() { - fnClones = CacheBuilder.newBuilder() - .build(SerializableCloningThreadLocalCacheLoader.>create()); - } - @Override public TransformEvaluator forApplication( final AppliedPTransform application, @@ -51,28 +41,20 @@ public TransformEvaluator forApplication( return evaluator; } - private TransformEvaluator createSingleEvaluator( + private static ParDoInProcessEvaluator createSingleEvaluator( @SuppressWarnings("rawtypes") AppliedPTransform, PCollection, Bound> application, CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { TupleTag mainOutputTag = new TupleTag<>("out"); - @SuppressWarnings({"unchecked", "rawtypes"}) ThreadLocal> fnLocal = - (ThreadLocal) fnClones.getUnchecked(application.getTransform().getFn()); - try { - ParDoInProcessEvaluator parDoEvaluator = ParDoInProcessEvaluator.create( - evaluationContext, - inputBundle, - application, - fnLocal.get(), - application.getTransform().getSideInputs(), - mainOutputTag, - Collections.>emptyList(), - ImmutableMap., PCollection>of(mainOutputTag, application.getOutput())); - return ThreadLocalInvalidatingTransformEvaluator.wrapping(parDoEvaluator, fnLocal); - } catch (Exception e) { - fnLocal.remove(); - throw e; - } + return ParDoInProcessEvaluator.create( + evaluationContext, + inputBundle, + application, + application.getTransform().getFn(), + application.getTransform().getSideInputs(), + mainOutputTag, + Collections.>emptyList(), + ImmutableMap., PCollection>of(mainOutputTag, application.getOutput())); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java deleted file mode 100644 index 5503242369..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoader.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.common.cache.CacheLoader; - -import java.io.Serializable; - -/** - * A {@link CacheLoader} that loads {@link ThreadLocal ThreadLocals} with initial values equal to - * the clone of the key. - */ -class SerializableCloningThreadLocalCacheLoader - extends CacheLoader> { - public static CacheLoader> create() { - return new SerializableCloningThreadLocalCacheLoader(); - } - - @Override - public ThreadLocal load(T key) throws Exception { - return new CloningThreadLocal<>(key); - } - - private static class CloningThreadLocal extends ThreadLocal { - private final T original; - - public CloningThreadLocal(T value) { - this.original = value; - } - - @Override - public T initialValue() { - return SerializableUtils.clone(original); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java deleted file mode 100644 index 42ca7dcb19..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluator.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -/** - * A {@link TransformEvaluator} which delegates calls to an underlying {@link TransformEvaluator}, - * clearing the value of a {@link ThreadLocal} if any call throws an exception. - */ -class ThreadLocalInvalidatingTransformEvaluator - implements TransformEvaluator { - private final TransformEvaluator underlying; - private final ThreadLocal threadLocal; - - public static TransformEvaluator wrapping( - TransformEvaluator underlying, - ThreadLocal threadLocal) { - return new ThreadLocalInvalidatingTransformEvaluator<>(underlying, threadLocal); - } - - private ThreadLocalInvalidatingTransformEvaluator( - TransformEvaluator underlying, ThreadLocal threadLocal) { - this.underlying = underlying; - this.threadLocal = threadLocal; - } - - @Override - public void processElement(WindowedValue element) throws Exception { - try { - underlying.processElement(element); - } catch (Exception e) { - threadLocal.remove(); - throw e; - } - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - try { - return underlying.finishBundle(); - } catch (Exception e) { - threadLocal.remove(); - throw e; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java deleted file mode 100644 index 36b1607229..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/SerializableCloningThreadLocalCacheLoaderTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.IsSame.theInstance; -import static org.junit.Assert.assertThat; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; - -/** - * Tests for {@link SerializableCloningThreadLocalCacheLoader}. - */ -@RunWith(JUnit4.class) -public class SerializableCloningThreadLocalCacheLoaderTest { - private SerializableCloningThreadLocalCacheLoader loader; - - @Before - public void setup() { - loader = new SerializableCloningThreadLocalCacheLoader(); - } - - @Test - public void returnsCopiesOfOriginal() throws Exception { - Record original = new Record(); - ThreadLocal loaded = loader.load(original); - assertThat(loaded.get(), not(nullValue())); - assertThat(loaded.get(), equalTo(original)); - assertThat(loaded.get(), not(theInstance(original))); - } - - @Test - public void returnsDifferentCopiesInDifferentThreads() throws Exception { - Record original = new Record(); - final ThreadLocal loaded = loader.load(original); - assertThat(loaded.get(), not(nullValue())); - assertThat(loaded.get(), equalTo(original)); - assertThat(loaded.get(), not(theInstance(original))); - - Callable otherThread = new Callable() { - @Override - public Record call() throws Exception { - return loaded.get(); - } - }; - Record sameThread = loaded.get(); - Record firstOtherThread = Executors.newSingleThreadExecutor().submit(otherThread).get(); - Record secondOtherThread = Executors.newSingleThreadExecutor().submit(otherThread).get(); - - assertThat(sameThread, equalTo(firstOtherThread)); - assertThat(sameThread, equalTo(secondOtherThread)); - assertThat(sameThread, not(theInstance(firstOtherThread))); - assertThat(sameThread, not(theInstance(secondOtherThread))); - assertThat(firstOtherThread, not(theInstance(secondOtherThread))); - } - - private static class Record implements Serializable { - private final double rand = Math.random(); - - @Override - public boolean equals(Object other) { - if (!(other instanceof Record)) { - return false; - } - Record that = (Record) other; - return this.rand == that.rand; - } - - @Override - public int hashCode() { - return 1; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java deleted file mode 100644 index ca8408a379..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ThreadLocalInvalidatingTransformEvaluatorTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for {@link ThreadLocalInvalidatingTransformEvaluator}. - */ -@RunWith(JUnit4.class) -public class ThreadLocalInvalidatingTransformEvaluatorTest { - private ThreadLocal threadLocal; - - @Before - public void setup() { - threadLocal = new ThreadLocal<>(); - threadLocal.set(new Object()); - } - - @Test - public void delegatesToUnderlying() throws Exception { - RecordingTransformEvaluator underlying = new RecordingTransformEvaluator(); - Object original = threadLocal.get(); - TransformEvaluator evaluator = - ThreadLocalInvalidatingTransformEvaluator.wrapping(underlying, threadLocal); - WindowedValue first = WindowedValue.valueInGlobalWindow(new Object()); - WindowedValue second = WindowedValue.valueInGlobalWindow(new Object()); - evaluator.processElement(first); - assertThat(underlying.objects, containsInAnyOrder(first)); - evaluator.processElement(second); - evaluator.finishBundle(); - - assertThat(underlying.finishBundleCalled, is(true)); - assertThat(underlying.objects, containsInAnyOrder(second, first)); - } - - @Test - public void removesOnExceptionInProcessElement() { - ThrowingTransformEvaluator underlying = new ThrowingTransformEvaluator(); - Object original = threadLocal.get(); - assertThat(original, not(nullValue())); - TransformEvaluator evaluator = - ThreadLocalInvalidatingTransformEvaluator.wrapping(underlying, threadLocal); - - try { - evaluator.processElement(WindowedValue.valueInGlobalWindow(new Object())); - } catch (Exception e) { - assertThat(threadLocal.get(), nullValue()); - return; - } - fail("Expected ThrowingTransformEvaluator to throw on method call"); - } - - @Test - public void removesOnExceptionInFinishBundle() { - ThrowingTransformEvaluator underlying = new ThrowingTransformEvaluator(); - Object original = threadLocal.get(); - // the ThreadLocal is set when the evaluator starts - assertThat(original, not(nullValue())); - TransformEvaluator evaluator = - ThreadLocalInvalidatingTransformEvaluator.wrapping(underlying, threadLocal); - - try { - evaluator.finishBundle(); - } catch (Exception e) { - assertThat(threadLocal.get(), nullValue()); - return; - } - fail("Expected ThrowingTransformEvaluator to throw on method call"); - } - - private class RecordingTransformEvaluator implements TransformEvaluator { - private boolean finishBundleCalled; - private List> objects; - - public RecordingTransformEvaluator() { - this.finishBundleCalled = true; - this.objects = new ArrayList<>(); - } - - @Override - public void processElement(WindowedValue element) throws Exception { - objects.add(element); - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - finishBundleCalled = true; - return null; - } - } - - private class ThrowingTransformEvaluator implements TransformEvaluator { - @Override - public void processElement(WindowedValue element) throws Exception { - throw new Exception(); - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - throw new Exception(); - } - } -} From 6ce0a1ea8eff770caa68cf0a6c0bb040c6691049 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 16 May 2016 14:30:02 -0700 Subject: [PATCH 402/751] checkstyle: enforce where line breaks happen We should do it consistently throughout the SDK. Only a few fixups. Ported from: https://github.com/checkstyle/checkstyle/blob/ccdc3c09c500ccd31d56e4d6ed9c2d86edf2e9f1/src/main/resources/google_checks.xml#L167 This is a backport of https://github.com/apache/incubator-beam/pull/341 --- checkstyle.xml | 10 ++++++++++ .../examples/complete/game/injector/Injector.java | 10 +++++----- .../cloud/dataflow/sdk/coders/CoderFactories.java | 10 +++++----- .../com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 6 +++--- .../google/cloud/dataflow/sdk/io/FileBasedSource.java | 3 +-- .../dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- .../dataflow/sdk/runners/DirectPipelineRunner.java | 11 +++++------ .../runners/inprocess/InProcessEvaluationContext.java | 6 +++--- .../cloud/dataflow/sdk/transforms/GroupByKey.java | 4 ++-- .../cloud/dataflow/sdk/transforms/Partition.java | 4 ++-- .../dataflow/sdk/transforms/join/CoGbkResult.java | 8 ++++---- .../dataflow/sdk/transforms/join/UnionCoder.java | 4 ++-- .../dataflow/sdk/util/BigQueryTableInserter.java | 8 ++++---- .../cloud/dataflow/sdk/util/InstanceBuilder.java | 6 +++--- .../google/cloud/dataflow/sdk/util/StringUtils.java | 4 ++-- .../com/google/cloud/dataflow/sdk/util/Transport.java | 4 ++-- .../cloud/dataflow/sdk/values/PCollectionList.java | 4 ++-- .../sdk/runners/inprocess/TransformExecutorTest.java | 6 +++--- .../sdk/transforms/display/DisplayDataMatchers.java | 4 ++-- .../dataflow/sdk/values/PCollectionListTest.java | 4 ++-- 20 files changed, 64 insertions(+), 56 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index d5e8317391..805414bdb7 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -409,6 +409,16 @@ page at http://checkstyle.sourceforge.net/config.html --> + + + + + + - + From 7a3cc92bab225fe316878f942a8508f0df7095e7 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 19 May 2016 17:58:49 -0700 Subject: [PATCH 423/751] DisplayData: a few build fixups --- .../java/com/google/cloud/dataflow/sdk/transforms/Combine.java | 3 ++- .../sdk/transforms/display/DisplayDataEvaluatorTest.java | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java index f608988c9e..b34fd39fa5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java @@ -1782,7 +1782,8 @@ public List> getSideInputs() { public PCollection> apply(PCollection> input) { return input .apply(GroupByKey.create(fewKeys)) - .apply(Combine.groupedValues(fn, fnDisplayData).withSideInputs(sideInputs)); + .apply(Combine.groupedValues(fn, fnDisplayData) + .withSideInputs(sideInputs)); } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java index e1921e95ee..5bbc67d963 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java @@ -29,6 +29,8 @@ import com.google.cloud.dataflow.sdk.values.POutput; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.Serializable; import java.util.Set; @@ -36,6 +38,7 @@ /** * Unit tests for {@link DisplayDataEvaluator}. */ +@RunWith(JUnit4.class) public class DisplayDataEvaluatorTest implements Serializable { @Test From 9c02fb7dbb235da21807e44aeb7e84fe822e16f0 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 18 May 2016 16:12:28 -0700 Subject: [PATCH 424/751] PubsubIO: implement an unbounded source and sink https://github.com/apache/incubator-beam/pull/120 https://github.com/apache/incubator-beam/pull/213 https://github.com/apache/incubator-beam/pull/171 https://github.com/apache/incubator-beam/pull/346 This closes #273 --- pom.xml | 1 + sdk/pom.xml | 21 +- .../cloud/dataflow/sdk/io/PubsubIO.java | 321 ++-- .../dataflow/sdk/io/PubsubUnboundedSink.java | 445 ++++++ .../sdk/io/PubsubUnboundedSource.java | 1300 +++++++++++++++++ .../sdk/runners/DataflowPipelineRunner.java | 249 +++- .../runners/DataflowPipelineTranslator.java | 8 - .../runners/dataflow/PubsubIOTranslator.java | 107 -- .../dataflow/sdk/util/BucketingFunction.java | 151 ++ .../dataflow/sdk/util/MovingFunction.java | 151 ++ .../dataflow/sdk/util/PubsubApiaryClient.java | 301 ++++ .../cloud/dataflow/sdk/util/PubsubClient.java | 544 +++++++ .../dataflow/sdk/util/PubsubGrpcClient.java | 444 ++++++ .../dataflow/sdk/util/PubsubTestClient.java | 403 +++++ .../cloud/dataflow/sdk/util/Transport.java | 4 + .../cloud/dataflow/sdk/io/PubsubIOTest.java | 158 +- .../sdk/io/PubsubUnboundedSinkTest.java | 163 +++ .../sdk/io/PubsubUnboundedSourceTest.java | 323 ++++ .../sdk/util/BucketingFunctionTest.java | 102 ++ .../dataflow/sdk/util/MovingFunctionTest.java | 113 ++ .../sdk/util/PubsubApiaryClientTest.java | 131 ++ .../dataflow/sdk/util/PubsubClientTest.java | 187 +++ .../sdk/util/PubsubGrpcClientTest.java | 167 +++ .../sdk/util/PubsubTestClientTest.java | 113 ++ 24 files changed, 5436 insertions(+), 471 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/PubsubIOTranslator.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClient.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClientTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java diff --git a/pom.xml b/pom.xml index 2634cd379f..cbc1cdcd12 100644 --- a/pom.xml +++ b/pom.xml @@ -69,6 +69,7 @@ 1.7.7 v2-rev295-1.22.0 + 0.0.2 0.2.3 v2-rev8-1.22.0 v1b3-rev26-1.22.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index 11b836b3fd..a2ef06ebb8 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -485,11 +485,30 @@ 0.12.0 + + io.netty + netty-handler + 4.1.0.Beta8 + + + + com.google.api.grpc + grpc-pubsub-v1 + ${pubsubgrpc.version} + + + + com.google.guava + guava-jdk5 + + + + com.google.auth google-auth-library-oauth2-http 0.4.0 - runtime diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java index c75e501c97..965db829c0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java @@ -16,24 +16,12 @@ package com.google.cloud.dataflow.sdk.io; -import static com.google.common.base.MoreObjects.firstNonNull; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.util.Clock; -import com.google.api.client.util.DateTime; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.AcknowledgeRequest; -import com.google.api.services.pubsub.model.PublishRequest; -import com.google.api.services.pubsub.model.PubsubMessage; -import com.google.api.services.pubsub.model.PullRequest; -import com.google.api.services.pubsub.model.PullResponse; -import com.google.api.services.pubsub.model.ReceivedMessage; -import com.google.api.services.pubsub.model.Subscription; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -43,14 +31,17 @@ import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.util.PubsubApiaryClient; +import com.google.cloud.dataflow.sdk.util.PubsubClient; +import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMap; +import com.google.common.base.Strings; import org.joda.time.Duration; import org.joda.time.Instant; @@ -60,10 +51,7 @@ import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -81,6 +69,9 @@ public class PubsubIO { private static final Logger LOG = LoggerFactory.getLogger(PubsubIO.class); + /** Factory for creating pubsub client to manage transport. */ + private static final PubsubClient.PubsubClientFactory FACTORY = PubsubApiaryClient.FACTORY; + /** The default {@link Coder} used to translate to/from Cloud Pub/Sub messages. */ public static final Coder DEFAULT_PUBSUB_CODER = StringUtf8Coder.of(); @@ -141,48 +132,6 @@ private static void validatePubsubName(String name) { } } - /** - * Returns the {@link Instant} that corresponds to the timestamp in the supplied - * {@link PubsubMessage} under the specified {@code ink label}. See - * {@link PubsubIO.Read#timestampLabel(String)} for details about how these messages are - * parsed. - * - *

          The {@link Clock} parameter is used to virtualize time for testing. - * - * @throws IllegalArgumentException if the timestamp label is provided, but there is no - * corresponding attribute in the message or the value provided is not a valid timestamp - * string. - * @see PubsubIO.Read#timestampLabel(String) - */ - @VisibleForTesting - protected static Instant assignMessageTimestamp( - PubsubMessage message, @Nullable String label, Clock clock) { - if (label == null) { - return new Instant(clock.currentTimeMillis()); - } - - // Extract message attributes, defaulting to empty map if null. - Map attributes = firstNonNull( - message.getAttributes(), ImmutableMap.of()); - - String timestampStr = attributes.get(label); - checkArgument(timestampStr != null && !timestampStr.isEmpty(), - "PubSub message is missing a timestamp in label: %s", label); - - long millisSinceEpoch; - try { - // Try parsing as milliseconds since epoch. Note there is no way to parse a string in - // RFC 3339 format here. - // Expected IllegalArgumentException if parsing fails; we use that to fall back to RFC 3339. - millisSinceEpoch = Long.parseLong(timestampStr); - } catch (IllegalArgumentException e) { - // Try parsing as RFC3339 string. DateTime.parseRfc3339 will throw an IllegalArgumentException - // if parsing fails, and the caller should handle. - millisSinceEpoch = DateTime.parseRfc3339(timestampStr).getValue(); - } - return new Instant(millisSinceEpoch); - } - /** * Populate common {@link DisplayData} between Pubsub source and sink. */ @@ -415,10 +364,9 @@ public String asPath() { * the stream. * *

          When running with a {@link PipelineRunner} that only supports bounded - * {@link PCollection PCollections} (such as {@link DirectPipelineRunner} or - * {@link DataflowPipelineRunner} without {@code --streaming}), only a bounded portion of the - * input Pub/Sub stream can be processed. As such, either {@link Bound#maxNumRecords(int)} or - * {@link Bound#maxReadTime(Duration)} must be set. + * {@link PCollection PCollections} (such as {@link DirectPipelineRunner}), + * only a bounded portion of the input Pub/Sub stream can be processed. As such, either + * {@link Bound#maxNumRecords(int)} or {@link Bound#maxReadTime(Duration)} must be set. */ public static class Read { /** @@ -684,24 +632,34 @@ public Bound maxReadTime(Duration maxReadTime) { @Override public PCollection apply(PInput input) { if (topic == null && subscription == null) { - throw new IllegalStateException("need to set either the topic or the subscription for " + throw new IllegalStateException("Need to set either the topic or the subscription for " + "a PubsubIO.Read transform"); } if (topic != null && subscription != null) { - throw new IllegalStateException("Can't set both the topic and the subscription for a " - + "PubsubIO.Read transform"); + throw new IllegalStateException("Can't set both the topic and the subscription for " + + "a PubsubIO.Read transform"); } boolean boundedOutput = getMaxNumRecords() > 0 || getMaxReadTime() != null; if (boundedOutput) { return input.getPipeline().begin() - .apply(Create.of((Void) null)).setCoder(VoidCoder.of()) - .apply(ParDo.of(new PubsubReader())).setCoder(coder); + .apply(Create.of((Void) null)).setCoder(VoidCoder.of()) + .apply(ParDo.of(new PubsubBoundedReader())).setCoder(coder); } else { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED) - .setCoder(coder); + @Nullable ProjectPath projectPath = + topic == null ? null : PubsubClient.projectPathFromId(topic.project); + @Nullable TopicPath topicPath = + topic == null ? null : PubsubClient.topicPathFromName(topic.project, topic.topic); + @Nullable SubscriptionPath subscriptionPath = + subscription == null + ? null + : PubsubClient.subscriptionPathFromName( + subscription.project, subscription.subscription); + return input.getPipeline().begin() + .apply(new PubsubUnboundedSource( + FACTORY, projectPath, topicPath, subscriptionPath, + coder, timestampLabel, idLabel)); } } @@ -755,88 +713,106 @@ public Duration getMaxReadTime() { return maxReadTime; } - private class PubsubReader extends DoFn { + /** + * Default reader when Pubsub subscription has some form of upper bound. + * + *

          TODO: Consider replacing with BoundedReadFromUnboundedSource on top + * of PubsubUnboundedSource. + * + *

          NOTE: This is not the implementation used when running on the Google Cloud Dataflow + * service in streaming mode. + * + *

          Public so can be suppressed by runners. + */ + public class PubsubBoundedReader extends DoFn { private static final int DEFAULT_PULL_SIZE = 100; + private static final int ACK_TIMEOUT_SEC = 60; @Override public void processElement(ProcessContext c) throws IOException { - Pubsub pubsubClient = - Transport.newPubsubClient(c.getPipelineOptions().as(DataflowPipelineOptions.class)) - .build(); - - String subscription; - if (getSubscription() == null) { - String topic = getTopic().asPath(); - String[] split = topic.split("/"); - subscription = - "projects/" + split[1] + "/subscriptions/" + split[3] + "_dataflow_" - + new Random().nextLong(); - Subscription subInfo = new Subscription().setAckDeadlineSeconds(60).setTopic(topic); - try { - pubsubClient.projects().subscriptions().create(subscription, subInfo).execute(); - } catch (Exception e) { - throw new RuntimeException("Failed to create subscription: ", e); + try (PubsubClient pubsubClient = + FACTORY.newClient(timestampLabel, idLabel, + c.getPipelineOptions().as(DataflowPipelineOptions.class))) { + + PubsubClient.SubscriptionPath subscriptionPath; + if (getSubscription() == null) { + TopicPath topicPath = + PubsubClient.topicPathFromName(getTopic().project, getTopic().topic); + // The subscription will be registered under this pipeline's project if we know it. + // Otherwise we'll fall back to the topic's project. + // Note that they don't need to be the same. + String projectId = + c.getPipelineOptions().as(DataflowPipelineOptions.class).getProject(); + if (Strings.isNullOrEmpty(projectId)) { + projectId = getTopic().project; + } + ProjectPath projectPath = PubsubClient.projectPathFromId(projectId); + try { + subscriptionPath = + pubsubClient.createRandomSubscription(projectPath, topicPath, ACK_TIMEOUT_SEC); + } catch (Exception e) { + throw new RuntimeException("Failed to create subscription: ", e); + } + } else { + subscriptionPath = + PubsubClient.subscriptionPathFromName(getSubscription().project, + getSubscription().subscription); } - } else { - subscription = getSubscription().asPath(); - } - Instant endTime = (getMaxReadTime() == null) - ? new Instant(Long.MAX_VALUE) : Instant.now().plus(getMaxReadTime()); + Instant endTime = (getMaxReadTime() == null) + ? new Instant(Long.MAX_VALUE) : Instant.now().plus(getMaxReadTime()); - List messages = new ArrayList<>(); + List messages = new ArrayList<>(); - Throwable finallyBlockException = null; - try { - while ((getMaxNumRecords() == 0 || messages.size() < getMaxNumRecords()) - && Instant.now().isBefore(endTime)) { - PullRequest pullRequest = new PullRequest().setReturnImmediately(false); - if (getMaxNumRecords() > 0) { - pullRequest.setMaxMessages(getMaxNumRecords() - messages.size()); - } else { - pullRequest.setMaxMessages(DEFAULT_PULL_SIZE); - } + Throwable finallyBlockException = null; + try { + while ((getMaxNumRecords() == 0 || messages.size() < getMaxNumRecords()) + && Instant.now().isBefore(endTime)) { + int batchSize = DEFAULT_PULL_SIZE; + if (getMaxNumRecords() > 0) { + batchSize = Math.min(batchSize, getMaxNumRecords() - messages.size()); + } - PullResponse pullResponse = - pubsubClient.projects().subscriptions().pull(subscription, pullRequest).execute(); - List ackIds = new ArrayList<>(); - if (pullResponse.getReceivedMessages() != null) { - for (ReceivedMessage received : pullResponse.getReceivedMessages()) { - messages.add(received.getMessage()); - ackIds.add(received.getAckId()); + List batchMessages = + pubsubClient.pull(System.currentTimeMillis(), subscriptionPath, batchSize, + false); + List ackIds = new ArrayList<>(); + for (IncomingMessage message : batchMessages) { + messages.add(message); + ackIds.add(message.ackId); + } + if (ackIds.size() != 0) { + pubsubClient.acknowledge(subscriptionPath, ackIds); } } - - if (ackIds.size() != 0) { - AcknowledgeRequest ackRequest = new AcknowledgeRequest().setAckIds(ackIds); - pubsubClient.projects() - .subscriptions() - .acknowledge(subscription, ackRequest) - .execute(); + } catch (IOException e) { + throw new RuntimeException("Unexpected exception while reading from Pubsub: ", e); + } finally { + if (getSubscription() == null) { + try { + pubsubClient.deleteSubscription(subscriptionPath); + } catch (Exception e) { + finallyBlockException = e; + } } } - } catch (IOException e) { - throw new RuntimeException("Unexpected exception while reading from Pubsub: ", e); - } finally { - if (getTopic() != null) { - try { - pubsubClient.projects().subscriptions().delete(subscription).execute(); - } catch (IOException e) { - finallyBlockException = new RuntimeException("Failed to delete subscription: ", e); - LOG.error("Failed to delete subscription: ", e); - } + if (finallyBlockException != null) { + throw new RuntimeException("Failed to delete subscription: ", finallyBlockException); } - } - if (finallyBlockException != null) { - throw new RuntimeException(finallyBlockException); - } - for (PubsubMessage message : messages) { - c.outputWithTimestamp( - CoderUtils.decodeFromByteArray(getCoder(), message.decodeData()), - assignMessageTimestamp(message, getTimestampLabel(), Clock.SYSTEM)); + for (IncomingMessage message : messages) { + c.outputWithTimestamp( + CoderUtils.decodeFromByteArray(getCoder(), message.elementBytes), + new Instant(message.timestampMsSinceEpoch)); + } } } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + Bound.this.populateDisplayData(builder); + } } } @@ -1003,8 +979,20 @@ public PDone apply(PCollection input) { if (topic == null) { throw new IllegalStateException("need to set the topic of a PubsubIO.Write transform"); } - input.apply(ParDo.of(new PubsubWriter())); - return PDone.in(input.getPipeline()); + switch (input.isBounded()) { + case BOUNDED: + input.apply(ParDo.of(new PubsubBoundedWriter())); + return PDone.in(input.getPipeline()); + case UNBOUNDED: + return input.apply(new PubsubUnboundedSink( + FACTORY, + PubsubClient.topicPathFromName(topic.project, topic.topic), + coder, + timestampLabel, + idLabel, + 100 /* numShards */)); + } + throw new RuntimeException(); // cases are exhaustive. } @Override @@ -1034,31 +1022,34 @@ public Coder getCoder() { return coder; } - private class PubsubWriter extends DoFn { + /** + * Writer to Pubsub which batches messages from bounded collections. + * + *

          NOTE: This is not the implementation used when running on the Google Cloud Dataflow + * service in streaming mode. + * + *

          Public so can be suppressed by runners. + */ + public class PubsubBoundedWriter extends DoFn { private static final int MAX_PUBLISH_BATCH_SIZE = 100; - private transient List output; - private transient Pubsub pubsubClient; + private transient List output; + private transient PubsubClient pubsubClient; @Override - public void startBundle(Context c) { + public void startBundle(Context c) throws IOException { this.output = new ArrayList<>(); + // NOTE: idLabel is ignored. this.pubsubClient = - Transport.newPubsubClient(c.getPipelineOptions().as(DataflowPipelineOptions.class)) - .build(); + FACTORY.newClient(timestampLabel, null, + c.getPipelineOptions().as(DataflowPipelineOptions.class)); } @Override public void processElement(ProcessContext c) throws IOException { - PubsubMessage message = - new PubsubMessage().encodeData(CoderUtils.encodeToByteArray(getCoder(), c.element())); - if (getTimestampLabel() != null) { - Map attributes = message.getAttributes(); - if (attributes == null) { - attributes = new HashMap<>(); - message.setAttributes(attributes); - } - attributes.put(getTimestampLabel(), String.valueOf(c.timestamp().getMillis())); - } + // NOTE: The record id is always null. + OutgoingMessage message = + new OutgoingMessage(CoderUtils.encodeToByteArray(getCoder(), c.element()), + c.timestamp().getMillis(), null); output.add(message); if (output.size() >= MAX_PUBLISH_BATCH_SIZE) { @@ -1071,18 +1062,22 @@ public void finishBundle(Context c) throws IOException { if (!output.isEmpty()) { publish(); } + output = null; + pubsubClient.close(); + pubsubClient = null; } private void publish() throws IOException { - PublishRequest publishRequest = new PublishRequest().setMessages(output); - pubsubClient.projects().topics() - .publish(getTopic().asPath(), publishRequest) - .execute(); + int n = pubsubClient.publish( + PubsubClient.topicPathFromName(getTopic().project, getTopic().topic), + output); + checkState(n == output.size()); output.clear(); } @Override public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); Bound.this.populateDisplayData(builder); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java new file mode 100644 index 0000000000..98fc29ba6e --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java @@ -0,0 +1,445 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.CustomCoder; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.NullableCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterFirst; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Repeatedly; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.PubsubClient; +import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.PubsubClientFactory; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.hash.Hashing; + +import org.joda.time.Duration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import javax.annotation.Nullable; + +/** + * A PTransform which streams messages to Pubsub. + *

            + *
          • The underlying implementation is just a {@link GroupByKey} followed by a {@link ParDo} which + * publishes as a side effect. (In the future we want to design and switch to a custom + * {@code UnboundedSink} implementation so as to gain access to system watermark and + * end-of-pipeline cleanup.) + *
          • We try to send messages in batches while also limiting send latency. + *
          • No stats are logged. Rather some counters are used to keep track of elements and batches. + *
          • Though some background threads are used by the underlying netty system all actual Pubsub + * calls are blocking. We rely on the underlying runner to allow multiple {@link DoFn} instances + * to execute concurrently and hide latency. + *
          • A failed bundle will cause messages to be resent. Thus we rely on the Pubsub consumer + * to dedup messages. + *
          + * + *

          NOTE: This is not the implementation used when running on the Google Cloud Dataflow service. + */ +public class PubsubUnboundedSink extends PTransform, PDone> { + private static final Logger LOG = LoggerFactory.getLogger(PubsubUnboundedSink.class); + + /** + * Default maximum number of messages per publish. + */ + private static final int DEFAULT_PUBLISH_BATCH_SIZE = 1000; + + /** + * Default maximum size of a publish batch, in bytes. + */ + private static final int DEFAULT_PUBLISH_BATCH_BYTES = 400000; + + /** + * Default longest delay between receiving a message and pushing it to Pubsub. + */ + private static final Duration DEFAULT_MAX_LATENCY = Duration.standardSeconds(2); + + /** + * Coder for conveying outgoing messages between internal stages. + */ + private static class OutgoingMessageCoder extends CustomCoder { + private static final NullableCoder RECORD_ID_CODER = + NullableCoder.of(StringUtf8Coder.of()); + + @Override + public void encode( + OutgoingMessage value, OutputStream outStream, Context context) + throws CoderException, IOException { + ByteArrayCoder.of().encode(value.elementBytes, outStream, Context.NESTED); + BigEndianLongCoder.of().encode(value.timestampMsSinceEpoch, outStream, Context.NESTED); + RECORD_ID_CODER.encode(value.recordId, outStream, Context.NESTED); + } + + @Override + public OutgoingMessage decode( + InputStream inStream, Context context) throws CoderException, IOException { + byte[] elementBytes = ByteArrayCoder.of().decode(inStream, Context.NESTED); + long timestampMsSinceEpoch = BigEndianLongCoder.of().decode(inStream, Context.NESTED); + @Nullable String recordId = RECORD_ID_CODER.decode(inStream, Context.NESTED); + return new OutgoingMessage(elementBytes, timestampMsSinceEpoch, recordId); + } + } + + @VisibleForTesting + static final Coder CODER = new OutgoingMessageCoder(); + + // ================================================================================ + // RecordIdMethod + // ================================================================================ + + /** + * Specify how record ids are to be generated. + */ + @VisibleForTesting + enum RecordIdMethod { + /** Leave null. */ + NONE, + /** Generate randomly. */ + RANDOM, + /** Generate deterministically. For testing only. */ + DETERMINISTIC + } + + // ================================================================================ + // ShardFn + // ================================================================================ + + /** + * Convert elements to messages and shard them. + */ + private static class ShardFn extends DoFn> { + private final Aggregator elementCounter = + createAggregator("elements", new Sum.SumLongFn()); + private final Coder elementCoder; + private final int numShards; + private final RecordIdMethod recordIdMethod; + + ShardFn(Coder elementCoder, int numShards, RecordIdMethod recordIdMethod) { + this.elementCoder = elementCoder; + this.numShards = numShards; + this.recordIdMethod = recordIdMethod; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + elementCounter.addValue(1L); + byte[] elementBytes = CoderUtils.encodeToByteArray(elementCoder, c.element()); + long timestampMsSinceEpoch = c.timestamp().getMillis(); + @Nullable String recordId = null; + switch (recordIdMethod) { + case NONE: + break; + case DETERMINISTIC: + recordId = Hashing.murmur3_128().hashBytes(elementBytes).toString(); + break; + case RANDOM: + // Since these elements go through a GroupByKey, any failures while sending to + // Pubsub will be retried without falling back and generating a new record id. + // Thus even though we may send the same message to Pubsub twice, it is guaranteed + // to have the same record id. + recordId = UUID.randomUUID().toString(); + break; + } + c.output(KV.of(ThreadLocalRandom.current().nextInt(numShards), + new OutgoingMessage(elementBytes, timestampMsSinceEpoch, recordId))); + } + + @Override + public void populateDisplayData(Builder builder) { + super.populateDisplayData(builder); + builder.add(DisplayData.item("numShards", numShards)); + } + } + + // ================================================================================ + // WriterFn + // ================================================================================ + + /** + * Publish messages to Pubsub in batches. + */ + private static class WriterFn + extends DoFn>, Void> { + private final PubsubClientFactory pubsubFactory; + private final TopicPath topic; + private final String timestampLabel; + private final String idLabel; + private final int publishBatchSize; + private final int publishBatchBytes; + + /** + * Client on which to talk to Pubsub. Null until created by {@link #startBundle}. + */ + @Nullable + private transient PubsubClient pubsubClient; + + private final Aggregator batchCounter = + createAggregator("batches", new Sum.SumLongFn()); + private final Aggregator elementCounter = + createAggregator("elements", new Sum.SumLongFn()); + private final Aggregator byteCounter = + createAggregator("bytes", new Sum.SumLongFn()); + + WriterFn( + PubsubClientFactory pubsubFactory, TopicPath topic, String timestampLabel, + String idLabel, int publishBatchSize, int publishBatchBytes) { + this.pubsubFactory = pubsubFactory; + this.topic = topic; + this.timestampLabel = timestampLabel; + this.idLabel = idLabel; + this.publishBatchSize = publishBatchSize; + this.publishBatchBytes = publishBatchBytes; + } + + /** + * BLOCKING + * Send {@code messages} as a batch to Pubsub. + */ + private void publishBatch(List messages, int bytes) + throws IOException { + long nowMsSinceEpoch = System.currentTimeMillis(); + int n = pubsubClient.publish(topic, messages); + checkState(n == messages.size(), "Attempted to publish %d messages but %d were successful", + messages.size(), n); + batchCounter.addValue(1L); + elementCounter.addValue((long) messages.size()); + byteCounter.addValue((long) bytes); + } + + @Override + public void startBundle(Context c) throws Exception { + checkState(pubsubClient == null, "startBundle invoked without prior finishBundle"); + pubsubClient = + pubsubFactory.newClient(timestampLabel, idLabel, + c.getPipelineOptions().as(DataflowPipelineOptions.class)); + } + + @Override + public void processElement(ProcessContext c) throws Exception { + List pubsubMessages = new ArrayList<>(publishBatchSize); + int bytes = 0; + for (OutgoingMessage message : c.element().getValue()) { + if (!pubsubMessages.isEmpty() + && bytes + message.elementBytes.length > publishBatchBytes) { + // Break large (in bytes) batches into smaller. + // (We've already broken by batch size using the trigger below, though that may + // run slightly over the actual PUBLISH_BATCH_SIZE. We'll consider that ok since + // the hard limit from Pubsub is by bytes rather than number of messages.) + // BLOCKS until published. + publishBatch(pubsubMessages, bytes); + pubsubMessages.clear(); + bytes = 0; + } + pubsubMessages.add(message); + bytes += message.elementBytes.length; + } + if (!pubsubMessages.isEmpty()) { + // BLOCKS until published. + publishBatch(pubsubMessages, bytes); + } + } + + @Override + public void finishBundle(Context c) throws Exception { + pubsubClient.close(); + pubsubClient = null; + } + + @Override + public void populateDisplayData(Builder builder) { + super.populateDisplayData(builder); + builder.add(DisplayData.item("topic", topic.getPath())); + builder.add(DisplayData.item("transport", pubsubFactory.getKind())); + builder.addIfNotNull(DisplayData.item("timestampLabel", timestampLabel)); + builder.addIfNotNull(DisplayData.item("idLabel", idLabel)); + } + } + + // ================================================================================ + // PubsubUnboundedSink + // ================================================================================ + + /** + * Which factory to use for creating Pubsub transport. + */ + private final PubsubClientFactory pubsubFactory; + + /** + * Pubsub topic to publish to. + */ + private final TopicPath topic; + + /** + * Coder for elements. It is the responsibility of the underlying Pubsub transport to + * re-encode element bytes if necessary, eg as Base64 strings. + */ + private final Coder elementCoder; + + /** + * Pubsub metadata field holding timestamp of each element, or {@literal null} if should use + * Pubsub message publish timestamp instead. + */ + @Nullable + private final String timestampLabel; + + /** + * Pubsub metadata field holding id for each element, or {@literal null} if need to generate + * a unique id ourselves. + */ + @Nullable + private final String idLabel; + + /** + * Number of 'shards' to use so that latency in Pubsub publish can be hidden. Generally this + * should be a small multiple of the number of available cores. Too smoll a number results + * in too much time lost to blocking Pubsub calls. To large a number results in too many + * single-element batches being sent to Pubsub with high per-batch overhead. + */ + private final int numShards; + + /** + * Maximum number of messages per publish. + */ + private final int publishBatchSize; + + /** + * Maximum size of a publish batch, in bytes. + */ + private final int publishBatchBytes; + + /** + * Longest delay between receiving a message and pushing it to Pubsub. + */ + private final Duration maxLatency; + + /** + * How record ids should be generated for each record (if {@link #idLabel} is non-{@literal + * null}). + */ + private final RecordIdMethod recordIdMethod; + + @VisibleForTesting + PubsubUnboundedSink( + PubsubClientFactory pubsubFactory, + TopicPath topic, + Coder elementCoder, + String timestampLabel, + String idLabel, + int numShards, + int publishBatchSize, + int publishBatchBytes, + Duration maxLatency, + RecordIdMethod recordIdMethod) { + this.pubsubFactory = pubsubFactory; + this.topic = topic; + this.elementCoder = elementCoder; + this.timestampLabel = timestampLabel; + this.idLabel = idLabel; + this.numShards = numShards; + this.publishBatchSize = publishBatchSize; + this.publishBatchBytes = publishBatchBytes; + this.maxLatency = maxLatency; + this.recordIdMethod = idLabel == null ? RecordIdMethod.NONE : recordIdMethod; + } + + public PubsubUnboundedSink( + PubsubClientFactory pubsubFactory, + TopicPath topic, + Coder elementCoder, + String timestampLabel, + String idLabel, + int numShards) { + this(pubsubFactory, topic, elementCoder, timestampLabel, idLabel, numShards, + DEFAULT_PUBLISH_BATCH_SIZE, DEFAULT_PUBLISH_BATCH_BYTES, DEFAULT_MAX_LATENCY, + RecordIdMethod.RANDOM); + } + + public TopicPath getTopic() { + return topic; + } + + @Nullable + public String getTimestampLabel() { + return timestampLabel; + } + + @Nullable + public String getIdLabel() { + return idLabel; + } + + public Coder getElementCoder() { + return elementCoder; + } + + @Override + public PDone apply(PCollection input) { + input.apply( + Window.named("PubsubUnboundedSink.Window") + .into(new GlobalWindows()) + .triggering( + Repeatedly.forever( + AfterFirst.of(AfterPane.elementCountAtLeast(publishBatchSize), + AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(maxLatency)))) + .discardingFiredPanes()) + .apply(ParDo.named("PubsubUnboundedSink.Shard") + .of(new ShardFn(elementCoder, numShards, recordIdMethod))) + .setCoder(KvCoder.of(VarIntCoder.of(), CODER)) + .apply(GroupByKey.create()) + .apply(ParDo.named("PubsubUnboundedSink.Writer") + .of(new WriterFn(pubsubFactory, topic, timestampLabel, idLabel, + publishBatchSize, publishBatchBytes))); + return PDone.in(input.getPipeline()); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java new file mode 100644 index 0000000000..6c60877811 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java @@ -0,0 +1,1300 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import com.google.api.client.util.Clock; + +import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.ListCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.Aggregator; +import com.google.cloud.dataflow.sdk.transforms.Combine; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.Sum.SumLongFn; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.BucketingFunction; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.MovingFunction; +import com.google.cloud.dataflow.sdk.util.PubsubClient; +import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.PubsubClientFactory; +import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; +import com.google.cloud.dataflow.sdk.values.PBegin; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Charsets; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.GeneralSecurityException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.annotation.Nullable; + +/** + * A PTransform which streams messages from Pubsub. + *

            + *
          • The underlying implementation in an {@link UnboundedSource} which receives messages + * in batches and hands them out one at a time. + *
          • The watermark (either in Pubsub processing time or custom timestamp time) is estimated + * by keeping track of the minimum of the last minutes worth of messages. This assumes Pubsub + * delivers the oldest (in Pubsub processing time) available message at least once a minute, + * and that custom timestamps are 'mostly' monotonic with Pubsub processing time. Unfortunately + * both of those assumptions are fragile. Thus the estimated watermark may get ahead of + * the 'true' watermark and cause some messages to be late. + *
          • Checkpoints are used both to ACK received messages back to Pubsub (so that they may + * be retired on the Pubsub end), and to NACK already consumed messages should a checkpoint + * need to be restored (so that Pubsub will resend those messages promptly). + *
          • The backlog is determined by each reader using the messages which have been pulled from + * Pubsub but not yet consumed downstream. The backlog does not take account of any messages queued + * by Pubsub for the subscription. Unfortunately there is currently no API to determine + * the size of the Pubsub queue's backlog. + *
          • The subscription must already exist. + *
          • The subscription timeout is read whenever a reader is started. However it is not + * checked thereafter despite the timeout being user-changeable on-the-fly. + *
          • We log vital stats every 30 seconds. + *
          • Though some background threads may be used by the underlying transport all Pubsub calls + * are blocking. We rely on the underlying runner to allow multiple + * {@link UnboundedSource.UnboundedReader} instances to execute concurrently and thus hide latency. + *
          + * + *

          NOTE: This is not the implementation used when running on the Google Cloud Dataflow service. + */ +public class PubsubUnboundedSource extends PTransform> { + private static final Logger LOG = LoggerFactory.getLogger(PubsubUnboundedSource.class); + + /** + * Default ACK timeout for created subscriptions. + */ + private static final int DEAULT_ACK_TIMEOUT_SEC = 60; + + /** + * Coder for checkpoints. + */ + private static final PubsubCheckpointCoder CHECKPOINT_CODER = new PubsubCheckpointCoder<>(); + + /** + * Maximum number of messages per pull. + */ + private static final int PULL_BATCH_SIZE = 1000; + + /** + * Maximum number of ACK ids per ACK or ACK extension call. + */ + private static final int ACK_BATCH_SIZE = 2000; + + /** + * Maximum number of messages in flight. + */ + private static final int MAX_IN_FLIGHT = 20000; + + /** + * Timeout for round trip from receiving a message to finally ACKing it back to Pubsub. + */ + private static final Duration PROCESSING_TIMEOUT = Duration.standardSeconds(120); + + /** + * Percentage of ack timeout by which to extend acks when they are near timeout. + */ + private static final int ACK_EXTENSION_PCT = 50; + + /** + * Percentage of ack timeout we should use as a safety margin. We'll try to extend acks + * by this margin before the ack actually expires. + */ + private static final int ACK_SAFETY_PCT = 20; + + /** + * For stats only: How close we can get to an ack deadline before we risk it being already + * considered passed by Pubsub. + */ + private static final Duration ACK_TOO_LATE = Duration.standardSeconds(2); + + /** + * Period of samples to determine watermark and other stats. + */ + private static final Duration SAMPLE_PERIOD = Duration.standardMinutes(1); + + /** + * Period of updates to determine watermark and other stats. + */ + private static final Duration SAMPLE_UPDATE = Duration.standardSeconds(5); + + /** + * Period for logging stats. + */ + private static final Duration LOG_PERIOD = Duration.standardSeconds(30); + + /** + * Minimum number of unread messages required before considering updating watermark. + */ + private static final int MIN_WATERMARK_MESSAGES = 10; + + /** + * Minimum number of SAMPLE_UPDATE periods over which unread messages shoud be spread + * before considering updating watermark. + */ + private static final int MIN_WATERMARK_SPREAD = 2; + + /** + * Additional sharding so that we can hide read message latency. + */ + private static final int SCALE_OUT = 4; + + // TODO: Would prefer to use MinLongFn but it is a BinaryCombineFn rather + // than a BinaryCombineLongFn. [BEAM-285] + private static final Combine.BinaryCombineLongFn MIN = + new Combine.BinaryCombineLongFn() { + @Override + public long apply(long left, long right) { + return Math.min(left, right); + } + + @Override + public long identity() { + return Long.MAX_VALUE; + } + }; + + private static final Combine.BinaryCombineLongFn MAX = + new Combine.BinaryCombineLongFn() { + @Override + public long apply(long left, long right) { + return Math.max(left, right); + } + + @Override + public long identity() { + return Long.MIN_VALUE; + } + }; + + private static final Combine.BinaryCombineLongFn SUM = new SumLongFn(); + + // ================================================================================ + // Checkpoint + // ================================================================================ + + /** + * Which messages have been durably committed and thus can now be ACKed. + * Which messages have been read but not yet committed, in which case they should be NACKed if + * we need to restore. + */ + @VisibleForTesting + static class PubsubCheckpoint implements UnboundedSource.CheckpointMark { + /** + * If the checkpoint is for persisting: the reader who's snapshotted state we are persisting. + * If the checkpoint is for restoring: initially {@literal null}, then explicitly set. + * Not persisted in durable checkpoint. + * CAUTION: Between a checkpoint being taken and {@link #finalizeCheckpoint()} being called + * the 'true' active reader may have changed. + */ + @Nullable + private PubsubReader reader; + + /** + * If the checkpoint is for persisting: The ACK ids of messages which have been passed + * downstream since the last checkpoint. + * If the checkpoint is for restoring: {@literal null}. + * Not persisted in durable checkpoint. + */ + @Nullable + private final List safeToAckIds; + + /** + * If the checkpoint is for persisting: The ACK ids of messages which have been received + * from Pubsub but not yet passed downstream at the time of the snapshot. + * If the checkpoint is for restoring: Same, but recovered from durable storage. + */ + @VisibleForTesting + final List notYetReadIds; + + public PubsubCheckpoint( + @Nullable PubsubReader reader, @Nullable List safeToAckIds, + List notYetReadIds) { + this.reader = reader; + this.safeToAckIds = safeToAckIds; + this.notYetReadIds = notYetReadIds; + } + + /** + * BLOCKING + * All messages which have been passed downstream have now been durably committed. + * We can ACK them upstream. + * CAUTION: This may never be called. + */ + @Override + public void finalizeCheckpoint() throws IOException { + checkState(reader != null && safeToAckIds != null, "Cannot finalize a restored checkpoint"); + // Even if the 'true' active reader has changed since the checkpoint was taken we are + // fine: + // - The underlying Pubsub topic will not have changed, so the following ACKs will still + // go to the right place. + // - We'll delete the ACK ids from the readers in-flight state, but that only effects + // flow control and stats, neither of which are relevant anymore. + try { + int n = safeToAckIds.size(); + List batchSafeToAckIds = new ArrayList<>(Math.min(n, ACK_BATCH_SIZE)); + for (String ackId : safeToAckIds) { + batchSafeToAckIds.add(ackId); + if (batchSafeToAckIds.size() >= ACK_BATCH_SIZE) { + reader.ackBatch(batchSafeToAckIds); + n -= batchSafeToAckIds.size(); + // CAUTION: Don't reuse the same list since ackBatch holds on to it. + batchSafeToAckIds = new ArrayList<>(Math.min(n, ACK_BATCH_SIZE)); + } + } + if (!batchSafeToAckIds.isEmpty()) { + reader.ackBatch(batchSafeToAckIds); + } + } finally { + checkState(reader.numInFlightCheckpoints.decrementAndGet() >= 0, + "Miscounted in-flight checkpoints"); + } + } + + /** + * Return current time according to {@code reader}. + */ + private static long now(PubsubReader reader) { + if (reader.outer.outer.clock == null) { + return System.currentTimeMillis(); + } else { + return reader.outer.outer.clock.currentTimeMillis(); + } + } + + /** + * BLOCKING + * NACK all messages which have been read from Pubsub but not passed downstream. + * This way Pubsub will send them again promptly. + */ + public void nackAll(PubsubReader reader) throws IOException { + checkState(this.reader == null, "Cannot nackAll on persisting checkpoint"); + List batchYetToAckIds = + new ArrayList<>(Math.min(notYetReadIds.size(), ACK_BATCH_SIZE)); + for (String ackId : notYetReadIds) { + batchYetToAckIds.add(ackId); + if (batchYetToAckIds.size() >= ACK_BATCH_SIZE) { + long nowMsSinceEpoch = now(reader); + reader.nackBatch(nowMsSinceEpoch, batchYetToAckIds); + batchYetToAckIds.clear(); + } + } + if (!batchYetToAckIds.isEmpty()) { + long nowMsSinceEpoch = now(reader); + reader.nackBatch(nowMsSinceEpoch, batchYetToAckIds); + } + } + } + + /** + * The coder for our checkpoints. + */ + private static class PubsubCheckpointCoder extends AtomicCoder> { + private static final Coder> LIST_CODER = ListCoder.of(StringUtf8Coder.of()); + + @Override + public void encode(PubsubCheckpoint value, OutputStream outStream, Context context) + throws IOException { + LIST_CODER.encode(value.notYetReadIds, outStream, context); + } + + @Override + public PubsubCheckpoint decode(InputStream inStream, Context context) throws IOException { + List notYetReadIds = LIST_CODER.decode(inStream, context); + return new PubsubCheckpoint<>(null, null, notYetReadIds); + } + } + + // ================================================================================ + // Reader + // ================================================================================ + + /** + * A reader which keeps track of which messages have been received from Pubsub + * but not yet consumed downstream and/or ACKed back to Pubsub. + */ + @VisibleForTesting + static class PubsubReader extends UnboundedSource.UnboundedReader { + /** + * For access to topic and checkpointCoder. + */ + private final PubsubSource outer; + + /** + * Client on which to talk to Pubsub. Null if closed. + */ + @Nullable + private PubsubClient pubsubClient; + + /** + * Ack timeout, in ms, as set on subscription when we first start reading. Not + * updated thereafter. -1 if not yet determined. + */ + private int ackTimeoutMs; + + /** + * ACK ids of messages we have delivered downstream but not yet ACKed. + */ + private Set safeToAckIds; + + /** + * Messages we have received from Pubsub and not yet delivered downstream. + * We preserve their order. + */ + private final Queue notYetRead; + + private static class InFlightState { + /** + * When request which yielded message was issues. + */ + long requestTimeMsSinceEpoch; + + /** + * When Pubsub will consider this message's ACK to timeout and thus it needs to be + * extended. + */ + long ackDeadlineMsSinceEpoch; + + public InFlightState(long requestTimeMsSinceEpoch, long ackDeadlineMsSinceEpoch) { + this.requestTimeMsSinceEpoch = requestTimeMsSinceEpoch; + this.ackDeadlineMsSinceEpoch = ackDeadlineMsSinceEpoch; + } + } + + /** + * Map from ACK ids of messages we have received from Pubsub but not yet ACKed to their + * in flight state. Ordered from earliest to latest ACK deadline. + */ + private final LinkedHashMap inFlight; + + /** + * Batches of successfully ACKed ids which need to be pruned from the above. + * CAUTION: Accessed by both reader and checkpointing threads. + */ + private final Queue> ackedIds; + + /** + * Byte size of undecoded elements in {@link #notYetRead}. + */ + private long notYetReadBytes; + + /** + * Bucketed map from received time (as system time, ms since epoch) to message + * timestamps (mssince epoch) of all received but not-yet read messages. + * Used to estimate watermark. + */ + private BucketingFunction minUnreadTimestampMsSinceEpoch; + + /** + * Minimum of timestamps (ms since epoch) of all recently read messages. + * Used to estimate watermark. + */ + private MovingFunction minReadTimestampMsSinceEpoch; + + /** + * System time (ms since epoch) we last received a message from Pubsub, or -1 if + * not yet received any messages. + */ + private long lastReceivedMsSinceEpoch; + + /** + * The last reported watermark (ms since epoch), or beginning of time if none yet reported. + */ + private long lastWatermarkMsSinceEpoch; + + /** + * The current message, or {@literal null} if none. + */ + @Nullable + private PubsubClient.IncomingMessage current; + + /** + * Stats only: System time (ms since epoch) we last logs stats, or -1 if never. + */ + private long lastLogTimestampMsSinceEpoch; + + /** + * Stats only: Total number of messages received. + */ + private long numReceived; + + /** + * Stats only: Number of messages which have recently been received. + */ + private MovingFunction numReceivedRecently; + + /** + * Stats only: Number of messages which have recently had their deadline extended. + */ + private MovingFunction numExtendedDeadlines; + + /** + * Stats only: Number of messages which have recenttly had their deadline extended even + * though it may be too late to do so. + */ + private MovingFunction numLateDeadlines; + + + /** + * Stats only: Number of messages which have recently been ACKed. + */ + private MovingFunction numAcked; + + /** + * Stats only: Number of messages which have recently expired (ACKs were extended for too + * long). + */ + private MovingFunction numExpired; + + /** + * Stats only: Number of messages which have recently been NACKed. + */ + private MovingFunction numNacked; + + /** + * Stats only: Number of message bytes which have recently been read by downstream consumer. + */ + private MovingFunction numReadBytes; + + /** + * Stats only: Minimum of timestamp (ms since epoch) of all recently received messages. + * Used to estimate timestamp skew. Does not contribute to watermark estimator. + */ + private MovingFunction minReceivedTimestampMsSinceEpoch; + + /** + * Stats only: Maximum of timestamp (ms since epoch) of all recently received messages. + * Used to estimate timestamp skew. + */ + private MovingFunction maxReceivedTimestampMsSinceEpoch; + + /** + * Stats only: Minimum of recent estimated watermarks (ms since epoch). + */ + private MovingFunction minWatermarkMsSinceEpoch; + + /** + * Stats ony: Maximum of recent estimated watermarks (ms since epoch). + */ + private MovingFunction maxWatermarkMsSinceEpoch; + + /** + * Stats only: Number of messages with timestamps strictly behind the estimated watermark + * at the time they are received. These may be considered 'late' by downstream computations. + */ + private MovingFunction numLateMessages; + + /** + * Stats only: Current number of checkpoints in flight. + * CAUTION: Accessed by both checkpointing and reader threads. + */ + private AtomicInteger numInFlightCheckpoints; + + /** + * Stats only: Maximum number of checkpoints in flight at any time. + */ + private int maxInFlightCheckpoints; + + private static MovingFunction newFun(Combine.BinaryCombineLongFn function) { + return new MovingFunction(SAMPLE_PERIOD.getMillis(), + SAMPLE_UPDATE.getMillis(), + MIN_WATERMARK_SPREAD, + MIN_WATERMARK_MESSAGES, + function); + } + + /** + * Construct a reader. + */ + public PubsubReader(DataflowPipelineOptions options, PubsubSource outer) + throws IOException, GeneralSecurityException { + this.outer = outer; + pubsubClient = + outer.outer.pubsubFactory.newClient(outer.outer.timestampLabel, outer.outer.idLabel, + options); + ackTimeoutMs = -1; + safeToAckIds = new HashSet<>(); + notYetRead = new ArrayDeque<>(); + inFlight = new LinkedHashMap<>(); + ackedIds = new ConcurrentLinkedQueue<>(); + notYetReadBytes = 0; + minUnreadTimestampMsSinceEpoch = new BucketingFunction(SAMPLE_UPDATE.getMillis(), + MIN_WATERMARK_SPREAD, + MIN_WATERMARK_MESSAGES, + MIN); + minReadTimestampMsSinceEpoch = newFun(MIN); + lastReceivedMsSinceEpoch = -1; + lastWatermarkMsSinceEpoch = BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis(); + current = null; + lastLogTimestampMsSinceEpoch = -1; + numReceived = 0L; + numReceivedRecently = newFun(SUM); + numExtendedDeadlines = newFun(SUM); + numLateDeadlines = newFun(SUM); + numAcked = newFun(SUM); + numExpired = newFun(SUM); + numNacked = newFun(SUM); + numReadBytes = newFun(SUM); + minReceivedTimestampMsSinceEpoch = newFun(MIN); + maxReceivedTimestampMsSinceEpoch = newFun(MAX); + minWatermarkMsSinceEpoch = newFun(MIN); + maxWatermarkMsSinceEpoch = newFun(MAX); + numLateMessages = newFun(SUM); + numInFlightCheckpoints = new AtomicInteger(); + maxInFlightCheckpoints = 0; + } + + @VisibleForTesting + PubsubClient getPubsubClient() { + return pubsubClient; + } + + /** + * BLOCKING + * ACK {@code ackIds} back to Pubsub. + * CAUTION: May be invoked from a separate checkpointing thread. + * CAUTION: Retains {@code ackIds}. + */ + void ackBatch(List ackIds) throws IOException { + pubsubClient.acknowledge(outer.outer.subscription, ackIds); + ackedIds.add(ackIds); + } + + /** + * BLOCKING + * NACK (ie request deadline extension of 0) receipt of messages from Pubsub + * with the given {@code ockIds}. Does not retain {@code ackIds}. + */ + public void nackBatch(long nowMsSinceEpoch, List ackIds) throws IOException { + pubsubClient.modifyAckDeadline(outer.outer.subscription, ackIds, 0); + numNacked.add(nowMsSinceEpoch, ackIds.size()); + } + + /** + * BLOCKING + * Extend the processing deadline for messages from Pubsub with the given {@code ackIds}. + * Does not retain {@code ackIds}. + */ + private void extendBatch(long nowMsSinceEpoch, List ackIds) throws IOException { + int extensionSec = (ackTimeoutMs * ACK_EXTENSION_PCT) / (100 * 1000); + pubsubClient.modifyAckDeadline(outer.outer.subscription, ackIds, extensionSec); + numExtendedDeadlines.add(nowMsSinceEpoch, ackIds.size()); + } + + /** + * Return the current time, in ms since epoch. + */ + private long now() { + if (outer.outer.clock == null) { + return System.currentTimeMillis(); + } else { + return outer.outer.clock.currentTimeMillis(); + } + } + + /** + * Messages which have been ACKed (via the checkpoint finalize) are no longer in flight. + * This is only used for flow control and stats. + */ + private void retire() throws IOException { + long nowMsSinceEpoch = now(); + while (true) { + List ackIds = ackedIds.poll(); + if (ackIds == null) { + return; + } + numAcked.add(nowMsSinceEpoch, ackIds.size()); + for (String ackId : ackIds) { + inFlight.remove(ackId); + safeToAckIds.remove(ackId); + } + } + } + + /** + * BLOCKING + * Extend deadline for all messages which need it. + * CAUTION: If extensions can't keep up with wallclock then we'll never return. + */ + private void extend() throws IOException { + while (true) { + long nowMsSinceEpoch = now(); + List assumeExpired = new ArrayList<>(); + List toBeExtended = new ArrayList<>(); + List toBeExpired = new ArrayList<>(); + // Messages will be in increasing deadline order. + for (Map.Entry entry : inFlight.entrySet()) { + if (entry.getValue().ackDeadlineMsSinceEpoch - (ackTimeoutMs * ACK_SAFETY_PCT) / 100 + > nowMsSinceEpoch) { + // All remaining messages don't need their ACKs to be extended. + break; + } + + if (entry.getValue().ackDeadlineMsSinceEpoch - ACK_TOO_LATE.getMillis() + < nowMsSinceEpoch) { + // Pubsub may have already considered this message to have expired. + // If so it will (eventually) be made available on a future pull request. + // If this message ends up being committed then it will be considered a duplicate + // when re-pulled. + assumeExpired.add(entry.getKey()); + continue; + } + + if (entry.getValue().requestTimeMsSinceEpoch + PROCESSING_TIMEOUT.getMillis() + < nowMsSinceEpoch) { + // This message has been in-flight for too long. + // Give up on it, otherwise we risk extending its ACK indefinitely. + toBeExpired.add(entry.getKey()); + continue; + } + + // Extend the ACK for this message. + toBeExtended.add(entry.getKey()); + if (toBeExtended.size() >= ACK_BATCH_SIZE) { + // Enough for one batch. + break; + } + } + + if (assumeExpired.isEmpty() && toBeExtended.isEmpty() && toBeExpired.isEmpty()) { + // Nothing to be done. + return; + } + + if (!assumeExpired.isEmpty()) { + // If we didn't make the ACK deadline assume expired and no longer in flight. + numLateDeadlines.add(nowMsSinceEpoch, assumeExpired.size()); + for (String ackId : assumeExpired) { + inFlight.remove(ackId); + } + } + + if (!toBeExpired.isEmpty()) { + // Expired messages are no longer considered in flight. + numExpired.add(nowMsSinceEpoch, toBeExpired.size()); + for (String ackId : toBeExpired) { + inFlight.remove(ackId); + } + } + + if (!toBeExtended.isEmpty()) { + // Pubsub extends acks from it's notion of current time. + // We'll try to track that on our side, but note the deadlines won't necessarily agree. + long newDeadlineMsSinceEpoch = nowMsSinceEpoch + (ackTimeoutMs * ACK_EXTENSION_PCT) / 100; + for (String ackId : toBeExtended) { + // Maintain increasing ack deadline order. + InFlightState state = inFlight.remove(ackId); + inFlight.put(ackId, + new InFlightState(state.requestTimeMsSinceEpoch, newDeadlineMsSinceEpoch)); + } + // BLOCKs until extended. + extendBatch(nowMsSinceEpoch, toBeExtended); + } + } + } + + /** + * BLOCKING + * Fetch another batch of messages from Pubsub. + */ + private void pull() throws IOException { + if (inFlight.size() >= MAX_IN_FLIGHT) { + // Wait for checkpoint to be finalized before pulling anymore. + // There may be lag while checkpoints are persisted and the finalizeCheckpoint method + // is invoked. By limiting the in-flight messages we can ensure we don't end up consuming + // messages faster than we can checkpoint them. + return; + } + + long requestTimeMsSinceEpoch = now(); + long deadlineMsSinceEpoch = requestTimeMsSinceEpoch + ackTimeoutMs; + + // Pull the next batch. + // BLOCKs until received. + Collection receivedMessages = + pubsubClient.pull(requestTimeMsSinceEpoch, + outer.outer.subscription, + PULL_BATCH_SIZE, true); + if (receivedMessages.isEmpty()) { + // Nothing available yet. Try again later. + return; + } + + lastReceivedMsSinceEpoch = requestTimeMsSinceEpoch; + + // Capture the received messages. + for (PubsubClient.IncomingMessage incomingMessage : receivedMessages) { + notYetRead.add(incomingMessage); + notYetReadBytes += incomingMessage.elementBytes.length; + inFlight.put(incomingMessage.ackId, + new InFlightState(requestTimeMsSinceEpoch, deadlineMsSinceEpoch)); + numReceived++; + numReceivedRecently.add(requestTimeMsSinceEpoch, 1L); + minReceivedTimestampMsSinceEpoch.add(requestTimeMsSinceEpoch, + incomingMessage.timestampMsSinceEpoch); + maxReceivedTimestampMsSinceEpoch.add(requestTimeMsSinceEpoch, + incomingMessage.timestampMsSinceEpoch); + minUnreadTimestampMsSinceEpoch.add(requestTimeMsSinceEpoch, + incomingMessage.timestampMsSinceEpoch); + } + } + + /** + * Log stats if time to do so. + */ + private void stats() { + long nowMsSinceEpoch = now(); + if (lastLogTimestampMsSinceEpoch < 0) { + lastLogTimestampMsSinceEpoch = nowMsSinceEpoch; + return; + } + long deltaMs = nowMsSinceEpoch - lastLogTimestampMsSinceEpoch; + if (deltaMs < LOG_PERIOD.getMillis()) { + return; + } + + String messageSkew = "unknown"; + long minTimestamp = minReceivedTimestampMsSinceEpoch.get(nowMsSinceEpoch); + long maxTimestamp = maxReceivedTimestampMsSinceEpoch.get(nowMsSinceEpoch); + if (minTimestamp < Long.MAX_VALUE && maxTimestamp > Long.MIN_VALUE) { + messageSkew = (maxTimestamp - minTimestamp) + "ms"; + } + + String watermarkSkew = "unknown"; + long minWatermark = minWatermarkMsSinceEpoch.get(nowMsSinceEpoch); + long maxWatermark = maxWatermarkMsSinceEpoch.get(nowMsSinceEpoch); + if (minWatermark < Long.MAX_VALUE && maxWatermark > Long.MIN_VALUE) { + watermarkSkew = (maxWatermark - minWatermark) + "ms"; + } + + String oldestInFlight = "no"; + String oldestAckId = Iterables.getFirst(inFlight.keySet(), null); + if (oldestAckId != null) { + oldestInFlight = + (nowMsSinceEpoch - inFlight.get(oldestAckId).requestTimeMsSinceEpoch) + "ms"; + } + + LOG.info("Pubsub {} has " + + "{} received messages, " + + "{} current unread messages, " + + "{} current unread bytes, " + + "{} current in-flight msgs, " + + "{} oldest in-flight, " + + "{} current in-flight checkpoints, " + + "{} max in-flight checkpoints, " + + "{}B/s recent read, " + + "{} recent received, " + + "{} recent extended, " + + "{} recent late extended, " + + "{} recent ACKed, " + + "{} recent NACKed, " + + "{} recent expired, " + + "{} recent message timestamp skew, " + + "{} recent watermark skew, " + + "{} recent late messages, " + + "{} last reported watermark", + outer.outer.subscription, + numReceived, + notYetRead.size(), + notYetReadBytes, + inFlight.size(), + oldestInFlight, + numInFlightCheckpoints.get(), + maxInFlightCheckpoints, + numReadBytes.get(nowMsSinceEpoch) / (SAMPLE_PERIOD.getMillis() / 1000L), + numReceivedRecently.get(nowMsSinceEpoch), + numExtendedDeadlines.get(nowMsSinceEpoch), + numLateDeadlines.get(nowMsSinceEpoch), + numAcked.get(nowMsSinceEpoch), + numNacked.get(nowMsSinceEpoch), + numExpired.get(nowMsSinceEpoch), + messageSkew, + watermarkSkew, + numLateMessages.get(nowMsSinceEpoch), + new Instant(lastWatermarkMsSinceEpoch)); + + lastLogTimestampMsSinceEpoch = nowMsSinceEpoch; + } + + @Override + public boolean start() throws IOException { + // Determine the ack timeout. + ackTimeoutMs = pubsubClient.ackDeadlineSeconds(outer.outer.subscription) * 1000; + return advance(); + } + + /** + * BLOCKING + * Return {@literal true} if a Pubsub messaage is available, {@literal false} if + * none is available at this time or we are over-subscribed. May BLOCK while extending + * ACKs or fetching available messages. Will not block waiting for messages. + */ + @Override + public boolean advance() throws IOException { + // Emit stats. + stats(); + + if (current != null) { + // Current is consumed. It can no longer contribute to holding back the watermark. + minUnreadTimestampMsSinceEpoch.remove(current.requestTimeMsSinceEpoch); + current = null; + } + + // Retire state associated with ACKed messages. + retire(); + + // Extend all pressing deadlines. + // Will BLOCK until done. + // If the system is pulling messages only to let them sit in a downsteam queue then + // this will have the effect of slowing down the pull rate. + // However, if the system is genuinely taking longer to process each message then + // the work to extend ACKs would be better done in the background. + extend(); + + if (notYetRead.isEmpty()) { + // Pull another batch. + // Will BLOCK until fetch returns, but will not block until a message is available. + pull(); + } + + // Take one message from queue. + current = notYetRead.poll(); + if (current == null) { + // Try again later. + return false; + } + notYetReadBytes -= current.elementBytes.length; + checkState(notYetReadBytes >= 0); + long nowMsSinceEpoch = now(); + numReadBytes.add(nowMsSinceEpoch, current.elementBytes.length); + minReadTimestampMsSinceEpoch.add(nowMsSinceEpoch, current.timestampMsSinceEpoch); + if (current.timestampMsSinceEpoch < lastWatermarkMsSinceEpoch) { + numLateMessages.add(nowMsSinceEpoch, 1L); + } + + // Current message can be considered 'read' and will be persisted by the next + // checkpoint. So it is now safe to ACK back to Pubsub. + safeToAckIds.add(current.ackId); + return true; + } + + @Override + public T getCurrent() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + try { + return CoderUtils.decodeFromByteArray(outer.outer.elementCoder, current.elementBytes); + } catch (CoderException e) { + throw new RuntimeException("Unable to decode element from Pubsub message: ", e); + } + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + return new Instant(current.timestampMsSinceEpoch); + } + + @Override + public byte[] getCurrentRecordId() throws NoSuchElementException { + if (current == null) { + throw new NoSuchElementException(); + } + return current.recordId.getBytes(Charsets.UTF_8); + } + + @Override + public void close() throws IOException { + if (pubsubClient != null) { + pubsubClient.close(); + pubsubClient = null; + } + } + + @Override + public PubsubSource getCurrentSource() { + return outer; + } + + @Override + public Instant getWatermark() { + if (pubsubClient.isEOF() && notYetRead.isEmpty()) { + // For testing only: Advance the watermark to the end of time to signal + // the test is complete. + return BoundedWindow.TIMESTAMP_MAX_VALUE; + } + + // NOTE: We'll allow the watermark to go backwards. The underlying runner is responsible + // for aggregating all reported watermarks and ensuring the aggregate is latched. + // If we attempt to latch locally then it is possible a temporary starvation of one reader + // could cause its estimated watermark to fast forward to current system time. Then when + // the reader resumes its watermark would be unable to resume tracking. + // By letting the underlying runner latch we avoid any problems due to localized starvation. + long nowMsSinceEpoch = now(); + long readMin = minReadTimestampMsSinceEpoch.get(nowMsSinceEpoch); + long unreadMin = minUnreadTimestampMsSinceEpoch.get(); + if (readMin == Long.MAX_VALUE + && unreadMin == Long.MAX_VALUE + && lastReceivedMsSinceEpoch >= 0 + && nowMsSinceEpoch > lastReceivedMsSinceEpoch + SAMPLE_PERIOD.getMillis()) { + // We don't currently have any unread messages pending, we have not had any messages + // read for a while, and we have not received any new messages from Pubsub for a while. + // Advance watermark to current time. + // TODO: Estimate a timestamp lag. + lastWatermarkMsSinceEpoch = nowMsSinceEpoch; + } else if (minReadTimestampMsSinceEpoch.isSignificant() + || minUnreadTimestampMsSinceEpoch.isSignificant()) { + // Take minimum of the timestamps in all unread messages and recently read messages. + lastWatermarkMsSinceEpoch = Math.min(readMin, unreadMin); + } + // else: We're not confident enough to estimate a new watermark. Stick with the old one. + minWatermarkMsSinceEpoch.add(nowMsSinceEpoch, lastWatermarkMsSinceEpoch); + maxWatermarkMsSinceEpoch.add(nowMsSinceEpoch, lastWatermarkMsSinceEpoch); + return new Instant(lastWatermarkMsSinceEpoch); + } + + @Override + public PubsubCheckpoint getCheckpointMark() { + int cur = numInFlightCheckpoints.incrementAndGet(); + maxInFlightCheckpoints = Math.max(maxInFlightCheckpoints, cur); + // It's possible for a checkpoint to be taken but never finalized. + // So we simply copy whatever safeToAckIds we currently have. + // It's possible a later checkpoint will be taken before an earlier one is finalized, + // in which case we'll double ACK messages to Pubsub. However Pubsub is fine with that. + List snapshotSafeToAckIds = Lists.newArrayList(safeToAckIds); + List snapshotNotYetReadIds = new ArrayList<>(notYetRead.size()); + for (PubsubClient.IncomingMessage incomingMessage : notYetRead) { + snapshotNotYetReadIds.add(incomingMessage.ackId); + } + return new PubsubCheckpoint<>(this, snapshotSafeToAckIds, snapshotNotYetReadIds); + } + + @Override + public long getSplitBacklogBytes() { + return notYetReadBytes; + } + } + + // ================================================================================ + // Source + // ================================================================================ + + @VisibleForTesting + static class PubsubSource extends UnboundedSource> { + public final PubsubUnboundedSource outer; + + public PubsubSource(PubsubUnboundedSource outer) { + this.outer = outer; + } + + @Override + public List> generateInitialSplits( + int desiredNumSplits, PipelineOptions options) throws Exception { + List> result = new ArrayList<>(desiredNumSplits); + for (int i = 0; i < desiredNumSplits * SCALE_OUT; i++) { + // Since the source is immutable and Pubsub automatically shards we simply + // replicate ourselves the requested number of times + result.add(this); + } + return result; + } + + @Override + public PubsubReader createReader( + PipelineOptions options, + @Nullable PubsubCheckpoint checkpoint) { + PubsubReader reader; + try { + reader = new PubsubReader<>(options.as(DataflowPipelineOptions.class), this); + } catch (GeneralSecurityException | IOException e) { + throw new RuntimeException("Unable to subscribe to " + outer.subscription + ": ", e); + } + if (checkpoint != null) { + // NACK all messages we may have lost. + try { + // Will BLOCK until NACKed. + checkpoint.nackAll(reader); + } catch (IOException e) { + LOG.error("Pubsub {} cannot have {} lost messages NACKed, ignoring: {}", + outer.subscription, checkpoint.notYetReadIds.size(), e); + } + } + return reader; + } + + @Nullable + @Override + public Coder> getCheckpointMarkCoder() { + @SuppressWarnings("unchecked") PubsubCheckpointCoder typedCoder = + (PubsubCheckpointCoder) CHECKPOINT_CODER; + return typedCoder; + } + + @Override + public Coder getDefaultOutputCoder() { + return outer.elementCoder; + } + + @Override + public void validate() { + // Nothing to validate. + } + + @Override + public boolean requiresDeduping() { + // We cannot prevent re-offering already read messages after a restore from checkpoint. + return true; + } + } + + // ================================================================================ + // StatsFn + // ================================================================================ + + private static class StatsFn extends DoFn { + private final Aggregator elementCounter = + createAggregator("elements", new Sum.SumLongFn()); + + private final PubsubClientFactory pubsubFactory; + private final SubscriptionPath subscription; + @Nullable + private final String timestampLabel; + @Nullable + private final String idLabel; + + public StatsFn( + PubsubClientFactory pubsubFactory, + SubscriptionPath subscription, + @Nullable + String timestampLabel, + @Nullable + String idLabel) { + this.pubsubFactory = pubsubFactory; + this.subscription = subscription; + this.timestampLabel = timestampLabel; + this.idLabel = idLabel; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + elementCounter.addValue(1L); + c.output(c.element()); + } + + @Override + public void populateDisplayData(Builder builder) { + super.populateDisplayData(builder); + builder.add(DisplayData.item("subscription", subscription.getPath())); + builder.add(DisplayData.item("transport", pubsubFactory.getKind())); + builder.addIfNotNull(DisplayData.item("timestampLabel", timestampLabel)); + builder.addIfNotNull(DisplayData.item("idLabel", idLabel)); + } + } + + // ================================================================================ + // PubsubUnboundedSource + // ================================================================================ + + /** + * For testing only: Clock to use for all timekeeping. If {@literal null} use system clock. + */ + @Nullable + private Clock clock; + + /** + * Factory for creating underlying Pubsub transport. + */ + private final PubsubClientFactory pubsubFactory; + + /** + * Project under which to create a subscription if only the {@link #topic} was given. + */ + @Nullable + private final ProjectPath project; + + /** + * Topic to read from. If {@literal null}, then {@link #subscription} must be given. + * Otherwise {@link #subscription} must be null. + */ + @Nullable + private final TopicPath topic; + + /** + * Subscription to read from. If {@literal null} then {@link #topic} must be given. + * Otherwise {@link #topic} must be null. + * + *

          If no subscription is given a random one will be created when the transorm is + * applied. This field will be update with that subscription's path. The created + * subscription is never deleted. + */ + @Nullable + private SubscriptionPath subscription; + + /** + * Coder for elements. Elements are effectively double-encoded: first to a byte array + * using this checkpointCoder, then to a base-64 string to conform to Pubsub's payload + * conventions. + */ + private final Coder elementCoder; + + /** + * Pubsub metadata field holding timestamp of each element, or {@literal null} if should use + * Pubsub message publish timestamp instead. + */ + @Nullable + private final String timestampLabel; + + /** + * Pubsub metadata field holding id for each element, or {@literal null} if need to generate + * a unique id ourselves. + */ + @Nullable + private final String idLabel; + + @VisibleForTesting + PubsubUnboundedSource( + Clock clock, + PubsubClientFactory pubsubFactory, + @Nullable ProjectPath project, + @Nullable TopicPath topic, + @Nullable SubscriptionPath subscription, + Coder elementCoder, + @Nullable String timestampLabel, + @Nullable String idLabel) { + checkArgument((topic == null) != (subscription == null), + "Exactly one of topic and subscription must be given"); + checkArgument((topic == null) == (project == null), + "Project must be given if topic is given"); + this.clock = clock; + this.pubsubFactory = checkNotNull(pubsubFactory); + this.project = project; + this.topic = topic; + this.subscription = subscription; + this.elementCoder = checkNotNull(elementCoder); + this.timestampLabel = timestampLabel; + this.idLabel = idLabel; + } + + /** + * Construct an unbounded source to consume from the Pubsub {@code subscription}. + */ + public PubsubUnboundedSource( + PubsubClientFactory pubsubFactory, + @Nullable ProjectPath project, + @Nullable TopicPath topic, + @Nullable SubscriptionPath subscription, + Coder elementCoder, + @Nullable String timestampLabel, + @Nullable String idLabel) { + this(null, pubsubFactory, project, topic, subscription, elementCoder, timestampLabel, idLabel); + } + + public Coder getElementCoder() { + return elementCoder; + } + + @Nullable + public ProjectPath getProject() { + return project; + } + + @Nullable + public TopicPath getTopic() { + return topic; + } + + @Nullable + public SubscriptionPath getSubscription() { + return subscription; + } + + @Nullable + public String getTimestampLabel() { + return timestampLabel; + } + + @Nullable + public String getIdLabel() { + return idLabel; + } + + @Override + public PCollection apply(PBegin input) { + if (subscription == null) { + try { + try (PubsubClient pubsubClient = + pubsubFactory.newClient(timestampLabel, idLabel, + input.getPipeline() + .getOptions() + .as(DataflowPipelineOptions.class))) { + subscription = + pubsubClient.createRandomSubscription(project, topic, DEAULT_ACK_TIMEOUT_SEC); + LOG.warn("Created subscription {} to topic {}." + + " Note this subscription WILL NOT be deleted when the pipeline terminates", + subscription, topic); + } + } catch (Exception e) { + throw new RuntimeException("Failed to create subscription: ", e); + } + } + + return input.getPipeline().begin() + .apply(Read.from(new PubsubSource(this))) + .apply(ParDo.named("PubsubUnboundedSource.Stats") + .of(new StatsFn(pubsubFactory, subscription, + timestampLabel, idLabel))); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 1477791538..61429b24b2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -59,6 +59,8 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.FileBasedSink; import com.google.cloud.dataflow.sdk.io.PubsubIO; +import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSink; +import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; import com.google.cloud.dataflow.sdk.io.TextIO; @@ -75,7 +77,6 @@ import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; -import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; @@ -117,6 +118,7 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PCollectionList; @@ -176,6 +178,7 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; +import javax.annotation.Nullable; /** * A {@link PipelineRunner} that executes the operations in the @@ -338,33 +341,46 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { this.pcollectionsRequiringIndexedFormat = new HashSet<>(); this.ptransformViewsWithNonDeterministicKeyCoders = new HashSet<>(); + ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); if (options.isStreaming()) { - overrides = ImmutableMap., Class>builder() - .put(Combine.GloballyAsSingletonView.class, StreamingCombineGloballyAsSingletonView.class) - .put(Create.Values.class, StreamingCreate.class) - .put(View.AsMap.class, StreamingViewAsMap.class) - .put(View.AsMultimap.class, StreamingViewAsMultimap.class) - .put(View.AsSingleton.class, StreamingViewAsSingleton.class) - .put(View.AsList.class, StreamingViewAsList.class) - .put(View.AsIterable.class, StreamingViewAsIterable.class) - .put(Write.Bound.class, StreamingWrite.class) - .put(PubsubIO.Write.Bound.class, StreamingPubsubIOWrite.class) - .put(Read.Unbounded.class, StreamingUnboundedRead.class) - .put(Read.Bounded.class, UnsupportedIO.class) - .put(AvroIO.Read.Bound.class, UnsupportedIO.class) - .put(AvroIO.Write.Bound.class, UnsupportedIO.class) - .put(BigQueryIO.Read.Bound.class, UnsupportedIO.class) - .put(TextIO.Read.Bound.class, UnsupportedIO.class) - .put(TextIO.Write.Bound.class, UnsupportedIO.class) - .put(Window.Bound.class, AssignWindows.class) - .build(); + builder.put(Combine.GloballyAsSingletonView.class, + StreamingCombineGloballyAsSingletonView.class); + builder.put(Create.Values.class, StreamingCreate.class); + builder.put(View.AsMap.class, StreamingViewAsMap.class); + builder.put(View.AsMultimap.class, StreamingViewAsMultimap.class); + builder.put(View.AsSingleton.class, StreamingViewAsSingleton.class); + builder.put(View.AsList.class, StreamingViewAsList.class); + builder.put(View.AsIterable.class, StreamingViewAsIterable.class); + builder.put(Write.Bound.class, StreamingWrite.class); + builder.put(Read.Unbounded.class, StreamingUnboundedRead.class); + builder.put(Read.Bounded.class, UnsupportedIO.class); + builder.put(AvroIO.Read.Bound.class, UnsupportedIO.class); + builder.put(AvroIO.Write.Bound.class, UnsupportedIO.class); + builder.put(BigQueryIO.Read.Bound.class, UnsupportedIO.class); + builder.put(TextIO.Read.Bound.class, UnsupportedIO.class); + builder.put(TextIO.Write.Bound.class, UnsupportedIO.class); + builder.put(Window.Bound.class, AssignWindows.class); + // In streaming mode must use either the custom Pubsub unbounded source/sink or + // defer to Windmill's built-in implementation. + builder.put(PubsubIO.Read.Bound.PubsubBoundedReader.class, UnsupportedIO.class); + builder.put(PubsubIO.Write.Bound.PubsubBoundedWriter.class, UnsupportedIO.class); + if (options.getExperiments() == null + || !options.getExperiments().contains("enable_custom_pubsub_source")) { + builder.put(PubsubUnboundedSource.class, StreamingPubsubIORead.class); + } + if (options.getExperiments() == null + || !options.getExperiments().contains("enable_custom_pubsub_sink")) { + builder.put(PubsubUnboundedSink.class, StreamingPubsubIOWrite.class); + } } else { - ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); builder.put(Read.Unbounded.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); builder.put(Write.Bound.class, BatchWrite.class); builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); builder.put(TextIO.Write.Bound.class, BatchTextIOWrite.class); + // In batch mode must use the custom Pubsub bounded source/sink. + builder.put(PubsubUnboundedSource.class, UnsupportedIO.class); + builder.put(PubsubUnboundedSink.class, UnsupportedIO.class); if (options.getExperiments() == null || !options.getExperiments().contains("disable_ism_side_input")) { builder.put(View.AsMap.class, BatchViewAsMap.class); @@ -381,8 +397,8 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { || !options.getExperiments().contains("enable_custom_bigquery_sink")) { builder.put(BigQueryIO.Write.Bound.class, BatchBigQueryIOWrite.class); } - overrides = builder.build(); } + overrides = builder.build(); } /** @@ -2535,27 +2551,104 @@ protected String getKindString() { } } + // ================================================================================ + // PubsubIO translations + // ================================================================================ + /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.io.PubsubIO.Write PubsubIO.Write} for the - * Dataflow runner in streaming mode. - * - *

          For internal use only. Subject to change at any time. - * - *

          Public so the {@link PubsubIOTranslator} can access. + * Suppress application of {@link PubsubUnboundedSource#apply} in streaming mode so that we + * can instead defer to Windmill's implementation. + */ + private static class StreamingPubsubIORead extends PTransform> { + private final PubsubUnboundedSource transform; + + /** + * Builds an instance of this class from the overridden transform. + */ + public StreamingPubsubIORead( + DataflowPipelineRunner runner, PubsubUnboundedSource transform) { + this.transform = transform; + } + + PubsubUnboundedSource getOverriddenTransform() { + return transform; + } + + @Override + public PCollection apply(PBegin input) { + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED) + .setCoder(transform.getElementCoder()); + } + + @Override + protected String getKindString() { + return "StreamingPubsubIORead"; + } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + StreamingPubsubIORead.class, new StreamingPubsubIOReadTranslator()); + } + } + + /** + * Rewrite {@link StreamingPubsubIORead} to the appropriate internal node. + */ + private static class StreamingPubsubIOReadTranslator implements + TransformTranslator { + @Override + @SuppressWarnings({"rawtypes", "unchecked"}) + public void translate( + StreamingPubsubIORead transform, + TranslationContext context) { + translateTyped(transform, context); + } + + private void translateTyped( + StreamingPubsubIORead transform, + TranslationContext context) { + Preconditions.checkState(context.getPipelineOptions().isStreaming(), + "StreamingPubsubIORead is only for streaming pipelines."); + PubsubUnboundedSource overriddenTransform = transform.getOverriddenTransform(); + context.addStep(transform, "ParallelRead"); + context.addInput(PropertyNames.FORMAT, "pubsub"); + if (overriddenTransform.getTopic() != null) { + context.addInput(PropertyNames.PUBSUB_TOPIC, + overriddenTransform.getTopic().getV1Beta1Path()); + } + if (overriddenTransform.getSubscription() != null) { + context.addInput( + PropertyNames.PUBSUB_SUBSCRIPTION, + overriddenTransform.getSubscription().getV1Beta1Path()); + } + if (overriddenTransform.getTimestampLabel() != null) { + context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, + overriddenTransform.getTimestampLabel()); + } + if (overriddenTransform.getIdLabel() != null) { + context.addInput(PropertyNames.PUBSUB_ID_LABEL, overriddenTransform.getIdLabel()); + } + context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); + } + } + + /** + * Suppress application of {@link PubsubUnboundedSink#apply} in streaming mode so that we + * can instead defer to Windmill's implementation. */ - public static class StreamingPubsubIOWrite extends PTransform, PDone> { - private final PubsubIO.Write.Bound transform; + private static class StreamingPubsubIOWrite extends PTransform, PDone> { + private final PubsubUnboundedSink transform; /** * Builds an instance of this class from the overridden transform. */ public StreamingPubsubIOWrite( - DataflowPipelineRunner runner, PubsubIO.Write.Bound transform) { + DataflowPipelineRunner runner, PubsubUnboundedSink transform) { this.transform = transform; } - public PubsubIO.Write.Bound getOverriddenTransform() { + PubsubUnboundedSink getOverriddenTransform() { return transform; } @@ -2568,8 +2661,51 @@ public PDone apply(PCollection input) { protected String getKindString() { return "StreamingPubsubIOWrite"; } + + static { + DataflowPipelineTranslator.registerTransformTranslator( + StreamingPubsubIOWrite.class, new StreamingPubsubIOWriteTranslator()); + } } + /** + * Rewrite {@link StreamingPubsubIOWrite} to the appropriate internal node. + */ + private static class StreamingPubsubIOWriteTranslator implements + TransformTranslator { + + @Override + @SuppressWarnings({"rawtypes", "unchecked"}) + public void translate( + StreamingPubsubIOWrite transform, + TranslationContext context) { + translateTyped(transform, context); + } + + private void translateTyped( + StreamingPubsubIOWrite transform, + TranslationContext context) { + Preconditions.checkState(context.getPipelineOptions().isStreaming(), + "StreamingPubsubIOWrite is only for streaming pipelines."); + PubsubUnboundedSink overriddenTransform = transform.getOverriddenTransform(); + context.addStep(transform, "ParallelWrite"); + context.addInput(PropertyNames.FORMAT, "pubsub"); + context.addInput(PropertyNames.PUBSUB_TOPIC, overriddenTransform.getTopic().getV1Beta1Path()); + if (overriddenTransform.getTimestampLabel() != null) { + context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, + overriddenTransform.getTimestampLabel()); + } + if (overriddenTransform.getIdLabel() != null) { + context.addInput(PropertyNames.PUBSUB_ID_LABEL, overriddenTransform.getIdLabel()); + } + context.addEncodingInput( + WindowedValue.getValueOnlyCoder(overriddenTransform.getElementCoder())); + context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); + } + } + + // ================================================================================ + /** * Specialized implementation for * {@link com.google.cloud.dataflow.sdk.io.Read.Unbounded Read.Unbounded} for the @@ -3111,11 +3247,14 @@ public Coder> getDefaultOutputCoder(CoderRegistry registry, Coder inp } /** - * Specialized expansion for unsupported IO transforms that throws an error. + * Specialized expansion for unsupported IO transforms and DoFns that throws an error. */ private static class UnsupportedIO extends PTransform { + @Nullable private PTransform transform; + @Nullable + private DoFn doFn; /** * Builds an instance of this class from the overridden transform. @@ -3173,13 +3312,51 @@ public UnsupportedIO(DataflowPipelineRunner runner, TextIO.Write.Bound transf this.transform = transform; } + /** + * Builds an instance of this class from the overridden doFn. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public UnsupportedIO(DataflowPipelineRunner runner, + PubsubIO.Read.Bound.PubsubBoundedReader doFn) { + this.doFn = doFn; + } + + /** + * Builds an instance of this class from the overridden doFn. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public UnsupportedIO(DataflowPipelineRunner runner, + PubsubIO.Write.Bound.PubsubBoundedWriter doFn) { + this.doFn = doFn; + } + + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public UnsupportedIO(DataflowPipelineRunner runner, PubsubUnboundedSource transform) { + this.transform = transform; + } + + /** + * Builds an instance of this class from the overridden transform. + */ + @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() + public UnsupportedIO(DataflowPipelineRunner runner, PubsubUnboundedSink transform) { + this.transform = transform; + } + + @Override public OutputT apply(InputT input) { String mode = input.getPipeline().getOptions().as(StreamingOptions.class).isStreaming() ? "streaming" : "batch"; + String name = + transform == null + ? approximateSimpleName(doFn.getClass()) + : approximatePTransformName(transform.getClass()); throw new UnsupportedOperationException( - String.format("The DataflowPipelineRunner in %s mode does not support %s.", - mode, approximatePTransformName(transform.getClass()))); + String.format("The DataflowPipelineRunner in %s mode does not support %s.", mode, name)); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index fb477d04c6..28392a48da 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -42,12 +42,10 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; -import com.google.cloud.dataflow.sdk.runners.dataflow.PubsubIOTranslator; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Combine; @@ -1050,12 +1048,6 @@ private void translateHelper( /////////////////////////////////////////////////////////////////////////// // IO Translation. - registerTransformTranslator( - PubsubIO.Read.Bound.class, new PubsubIOTranslator.ReadTranslator()); - registerTransformTranslator( - DataflowPipelineRunner.StreamingPubsubIOWrite.class, - new PubsubIOTranslator.WriteTranslator()); - registerTransformTranslator(Read.Bounded.class, new ReadTranslator()); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/PubsubIOTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/PubsubIOTranslator.java deleted file mode 100644 index 8b066ab065..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/PubsubIOTranslator.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -/** - * Pubsub transform support code for the Dataflow backend. - */ -public class PubsubIOTranslator { - - /** - * Implements PubsubIO Read translation for the Dataflow backend. - */ - public static class ReadTranslator implements TransformTranslator> { - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public void translate( - PubsubIO.Read.Bound transform, - TranslationContext context) { - translateReadHelper(transform, context); - } - - private void translateReadHelper( - PubsubIO.Read.Bound transform, - TranslationContext context) { - if (!context.getPipelineOptions().isStreaming()) { - throw new IllegalArgumentException( - "PubsubIO.Read can only be used with the Dataflow streaming runner."); - } - - context.addStep(transform, "ParallelRead"); - context.addInput(PropertyNames.FORMAT, "pubsub"); - if (transform.getTopic() != null) { - context.addInput(PropertyNames.PUBSUB_TOPIC, transform.getTopic().asV1Beta1Path()); - } - if (transform.getSubscription() != null) { - context.addInput( - PropertyNames.PUBSUB_SUBSCRIPTION, transform.getSubscription().asV1Beta1Path()); - } - if (transform.getTimestampLabel() != null) { - context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, transform.getTimestampLabel()); - } - if (transform.getIdLabel() != null) { - context.addInput(PropertyNames.PUBSUB_ID_LABEL, transform.getIdLabel()); - } - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - } - - /** - * Implements PubsubIO Write translation for the Dataflow backend. - */ - public static class WriteTranslator - implements TransformTranslator> { - - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public void translate( - DataflowPipelineRunner.StreamingPubsubIOWrite transform, - TranslationContext context) { - translateWriteHelper(transform, context); - } - - private void translateWriteHelper( - DataflowPipelineRunner.StreamingPubsubIOWrite customTransform, - TranslationContext context) { - if (!context.getPipelineOptions().isStreaming()) { - throw new IllegalArgumentException( - "PubsubIO.Write is non-primitive for the Dataflow batch runner."); - } - - PubsubIO.Write.Bound transform = customTransform.getOverriddenTransform(); - - context.addStep(customTransform, "ParallelWrite"); - context.addInput(PropertyNames.FORMAT, "pubsub"); - context.addInput(PropertyNames.PUBSUB_TOPIC, transform.getTopic().asV1Beta1Path()); - if (transform.getTimestampLabel() != null) { - context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, transform.getTimestampLabel()); - } - if (transform.getIdLabel() != null) { - context.addInput(PropertyNames.PUBSUB_ID_LABEL, transform.getIdLabel()); - } - context.addEncodingInput(WindowedValue.getValueOnlyCoder(transform.getCoder())); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(customTransform)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java new file mode 100644 index 0000000000..36efcce94c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.transforms.Combine; +import java.util.HashMap; +import java.util.Map; + +/** + * Keep track of the minimum/maximum/sum of a set of timestamped long values. + * For efficiency, bucket values by their timestamp. + */ +public class BucketingFunction { + private static class Bucket { + private int numSamples; + private long combinedValue; + + public Bucket(BucketingFunction outer) { + numSamples = 0; + combinedValue = outer.function.identity(); + } + + public void add(BucketingFunction outer, long value) { + combinedValue = outer.function.apply(combinedValue, value); + numSamples++; + } + + public boolean remove() { + numSamples--; + checkState(numSamples >= 0, "Lost count of samples"); + return numSamples == 0; + } + + public long get() { + return combinedValue; + } + } + + /** + * How large a time interval to fit within each bucket. + */ + private final long bucketWidthMs; + + /** + * How many buckets are considered 'significant'? + */ + private final int numSignificantBuckets; + + /** + * How many samples are considered 'significant'? + */ + private final int numSignificantSamples; + + /** + * Function for combining sample values. + */ + private final Combine.BinaryCombineLongFn function; + + /** + * Active buckets. + */ + private final Map buckets; + + public BucketingFunction( + long bucketWidthMs, + int numSignificantBuckets, + int numSignificantSamples, + Combine.BinaryCombineLongFn function) { + this.bucketWidthMs = bucketWidthMs; + this.numSignificantBuckets = numSignificantBuckets; + this.numSignificantSamples = numSignificantSamples; + this.function = function; + this.buckets = new HashMap<>(); + } + + /** + * Which bucket key corresponds to {@code timeMsSinceEpoch}. + */ + private long key(long timeMsSinceEpoch) { + return timeMsSinceEpoch - (timeMsSinceEpoch % bucketWidthMs); + } + + /** + * Add one sample of {@code value} (to bucket) at {@code timeMsSinceEpoch}. + */ + public void add(long timeMsSinceEpoch, long value) { + long key = key(timeMsSinceEpoch); + Bucket bucket = buckets.get(key); + if (bucket == null) { + bucket = new Bucket(this); + buckets.put(key, bucket); + } + bucket.add(this, value); + } + + /** + * Remove one sample (from bucket) at {@code timeMsSinceEpoch}. + */ + public void remove(long timeMsSinceEpoch) { + long key = key(timeMsSinceEpoch); + Bucket bucket = buckets.get(key); + if (bucket == null) { + return; + } + if (bucket.remove()) { + buckets.remove(key); + } + } + + /** + * Return the (bucketized) combined value of all samples. + */ + public long get() { + long result = function.identity(); + for (Bucket bucket : buckets.values()) { + result = function.apply(result, bucket.get()); + } + return result; + } + + /** + * Is the current result 'significant'? Ie is it drawn from enough buckets + * or from enough samples? + */ + public boolean isSignificant() { + if (buckets.size() >= numSignificantBuckets) { + return true; + } + int totalSamples = 0; + for (Bucket bucket : buckets.values()) { + totalSamples += bucket.numSamples; + } + return totalSamples >= numSignificantSamples; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java new file mode 100644 index 0000000000..04ec8db6d3 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.transforms.Combine; +import java.util.Arrays; + +/** + * Keep track of the moving minimum/maximum/sum of sampled long values. The minimum/maximum/sum + * is over at most the last {@link #samplePeriodMs}, and is updated every + * {@link #sampleUpdateMs}. + */ +public class MovingFunction { + /** + * How far back to retain samples, in ms. + */ + private final long samplePeriodMs; + + /** + * How frequently to update the moving function, in ms. + */ + private final long sampleUpdateMs; + + /** + * How many buckets are considered 'significant'? + */ + private final int numSignificantBuckets; + + /** + * How many samples are considered 'significant'? + */ + private final int numSignificantSamples; + + /** + * Function for combining sample values. + */ + private final Combine.BinaryCombineLongFn function; + + /** + * Minimum/maximum/sum of all values per bucket. + */ + private final long[] buckets; + + /** + * How many samples have been added to each bucket. + */ + private final int[] numSamples; + + /** + * Time of start of current bucket. + */ + private long currentMsSinceEpoch; + + /** + * Index of bucket corresponding to above timestamp, or -1 if no entries. + */ + private int currentIndex; + + public MovingFunction(long samplePeriodMs, long sampleUpdateMs, + int numSignificantBuckets, int numSignificantSamples, + Combine.BinaryCombineLongFn function) { + this.samplePeriodMs = samplePeriodMs; + this.sampleUpdateMs = sampleUpdateMs; + this.numSignificantBuckets = numSignificantBuckets; + this.numSignificantSamples = numSignificantSamples; + this.function = function; + int n = (int) (samplePeriodMs / sampleUpdateMs); + buckets = new long[n]; + Arrays.fill(buckets, function.identity()); + numSamples = new int[n]; + Arrays.fill(numSamples, 0); + currentMsSinceEpoch = -1; + currentIndex = -1; + } + + /** + * Flush stale values. + */ + private void flush(long nowMsSinceEpoch) { + checkArgument(nowMsSinceEpoch >= 0, "Only positive timestamps supported"); + if (currentIndex < 0) { + currentMsSinceEpoch = nowMsSinceEpoch - (nowMsSinceEpoch % sampleUpdateMs); + currentIndex = 0; + } + checkArgument(nowMsSinceEpoch >= currentMsSinceEpoch, "Attempting to move backwards"); + int newBuckets = + Math.min((int) ((nowMsSinceEpoch - currentMsSinceEpoch) / sampleUpdateMs), + buckets.length); + while (newBuckets > 0) { + currentIndex = (currentIndex + 1) % buckets.length; + buckets[currentIndex] = function.identity(); + numSamples[currentIndex] = 0; + newBuckets--; + currentMsSinceEpoch += sampleUpdateMs; + } + } + + /** + * Add {@code value} at {@code nowMsSinceEpoch}. + */ + public void add(long nowMsSinceEpoch, long value) { + flush(nowMsSinceEpoch); + buckets[currentIndex] = function.apply(buckets[currentIndex], value); + numSamples[currentIndex]++; + } + + /** + * Return the minimum/maximum/sum of all retained values within {@link #samplePeriodMs} + * of {@code nowMsSinceEpoch}. + */ + public long get(long nowMsSinceEpoch) { + flush(nowMsSinceEpoch); + long result = function.identity(); + for (int i = 0; i < buckets.length; i++) { + result = function.apply(result, buckets[i]); + } + return result; + } + + /** + * Is the current result 'significant'? Ie is it drawn from enough buckets + * or from enough samples? + */ + public boolean isSignificant() { + int totalSamples = 0; + int activeBuckets = 0; + for (int i = 0; i < buckets.length; i++) { + totalSamples += numSamples[i]; + if (numSamples[i] > 0) { + activeBuckets++; + } + } + return activeBuckets >= numSignificantBuckets || totalSamples >= numSignificantSamples; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClient.java new file mode 100644 index 0000000000..f7fa7832ee --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClient.java @@ -0,0 +1,301 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.api.services.pubsub.Pubsub; +import com.google.api.services.pubsub.Pubsub.Builder; +import com.google.api.services.pubsub.model.AcknowledgeRequest; +import com.google.api.services.pubsub.model.ListSubscriptionsResponse; +import com.google.api.services.pubsub.model.ListTopicsResponse; +import com.google.api.services.pubsub.model.ModifyAckDeadlineRequest; +import com.google.api.services.pubsub.model.PublishRequest; +import com.google.api.services.pubsub.model.PublishResponse; +import com.google.api.services.pubsub.model.PubsubMessage; +import com.google.api.services.pubsub.model.PullRequest; +import com.google.api.services.pubsub.model.PullResponse; +import com.google.api.services.pubsub.model.ReceivedMessage; +import com.google.api.services.pubsub.model.Subscription; +import com.google.api.services.pubsub.model.Topic; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.annotation.Nullable; + +/** + * A Pubsub client using Apiary. + */ +public class PubsubApiaryClient extends PubsubClient { + + private static class PubsubApiaryClientFactory implements PubsubClientFactory { + @Override + public PubsubClient newClient( + @Nullable String timestampLabel, @Nullable String idLabel, DataflowPipelineOptions options) + throws IOException { + Pubsub pubsub = new Builder( + Transport.getTransport(), + Transport.getJsonFactory(), + new ChainingHttpRequestInitializer( + options.getGcpCredential(), + // Do not log 404. It clutters the output and is possibly even required by the caller. + new RetryHttpRequestInitializer(ImmutableList.of(404)))) + .setRootUrl(options.getPubsubRootUrl()) + .setApplicationName(options.getAppName()) + .setGoogleClientRequestInitializer(options.getGoogleApiTrace()) + .build(); + return new PubsubApiaryClient(timestampLabel, idLabel, pubsub); + } + + @Override + public String getKind() { + return "Apiary"; + } + } + + /** + * Factory for creating Pubsub clients using Apiary transport. + */ + public static final PubsubClientFactory FACTORY = new PubsubApiaryClientFactory(); + + /** + * Label to use for custom timestamps, or {@literal null} if should use Pubsub publish time + * instead. + */ + @Nullable + private final String timestampLabel; + + /** + * Label to use for custom ids, or {@literal null} if should use Pubsub provided ids. + */ + @Nullable + private final String idLabel; + + /** + * Underlying Apiary client. + */ + private Pubsub pubsub; + + @VisibleForTesting + PubsubApiaryClient( + @Nullable String timestampLabel, + @Nullable String idLabel, + Pubsub pubsub) { + this.timestampLabel = timestampLabel; + this.idLabel = idLabel; + this.pubsub = pubsub; + } + + @Override + public void close() { + // Nothing to close. + } + + @Override + public int publish(TopicPath topic, List outgoingMessages) + throws IOException { + List pubsubMessages = new ArrayList<>(outgoingMessages.size()); + for (OutgoingMessage outgoingMessage : outgoingMessages) { + PubsubMessage pubsubMessage = new PubsubMessage().encodeData(outgoingMessage.elementBytes); + + Map attributes = pubsubMessage.getAttributes(); + if ((timestampLabel != null || idLabel != null) && attributes == null) { + attributes = new TreeMap<>(); + pubsubMessage.setAttributes(attributes); + } + + if (timestampLabel != null) { + attributes.put(timestampLabel, String.valueOf(outgoingMessage.timestampMsSinceEpoch)); + } + + if (idLabel != null && !Strings.isNullOrEmpty(outgoingMessage.recordId)) { + attributes.put(idLabel, outgoingMessage.recordId); + } + + pubsubMessages.add(pubsubMessage); + } + PublishRequest request = new PublishRequest().setMessages(pubsubMessages); + PublishResponse response = pubsub.projects() + .topics() + .publish(topic.getPath(), request) + .execute(); + return response.getMessageIds().size(); + } + + @Override + public List pull( + long requestTimeMsSinceEpoch, + SubscriptionPath subscription, + int batchSize, + boolean returnImmediately) throws IOException { + PullRequest request = new PullRequest() + .setReturnImmediately(returnImmediately) + .setMaxMessages(batchSize); + PullResponse response = pubsub.projects() + .subscriptions() + .pull(subscription.getPath(), request) + .execute(); + if (response.getReceivedMessages() == null || response.getReceivedMessages().size() == 0) { + return ImmutableList.of(); + } + List incomingMessages = new ArrayList<>(response.getReceivedMessages().size()); + for (ReceivedMessage message : response.getReceivedMessages()) { + PubsubMessage pubsubMessage = message.getMessage(); + @Nullable Map attributes = pubsubMessage.getAttributes(); + + // Payload. + byte[] elementBytes = pubsubMessage.decodeData(); + + // Timestamp. + long timestampMsSinceEpoch = + extractTimestamp(timestampLabel, message.getMessage().getPublishTime(), attributes); + + // Ack id. + String ackId = message.getAckId(); + checkState(!Strings.isNullOrEmpty(ackId)); + + // Record id, if any. + @Nullable String recordId = null; + if (idLabel != null && attributes != null) { + recordId = attributes.get(idLabel); + } + if (Strings.isNullOrEmpty(recordId)) { + // Fall back to the Pubsub provided message id. + recordId = pubsubMessage.getMessageId(); + } + + incomingMessages.add(new IncomingMessage(elementBytes, timestampMsSinceEpoch, + requestTimeMsSinceEpoch, ackId, recordId)); + } + + return incomingMessages; + } + + @Override + public void acknowledge(SubscriptionPath subscription, List ackIds) throws IOException { + AcknowledgeRequest request = new AcknowledgeRequest().setAckIds(ackIds); + pubsub.projects() + .subscriptions() + .acknowledge(subscription.getPath(), request) + .execute(); // ignore Empty result. + } + + @Override + public void modifyAckDeadline( + SubscriptionPath subscription, List ackIds, int deadlineSeconds) + throws IOException { + ModifyAckDeadlineRequest request = + new ModifyAckDeadlineRequest().setAckIds(ackIds) + .setAckDeadlineSeconds(deadlineSeconds); + pubsub.projects() + .subscriptions() + .modifyAckDeadline(subscription.getPath(), request) + .execute(); // ignore Empty result. + } + + @Override + public void createTopic(TopicPath topic) throws IOException { + pubsub.projects() + .topics() + .create(topic.getPath(), new Topic()) + .execute(); // ignore Topic result. + } + + @Override + public void deleteTopic(TopicPath topic) throws IOException { + pubsub.projects() + .topics() + .delete(topic.getPath()) + .execute(); // ignore Empty result. + } + + @Override + public List listTopics(ProjectPath project) throws IOException { + ListTopicsResponse response = pubsub.projects() + .topics() + .list(project.getPath()) + .execute(); + if (response.getTopics() == null || response.getTopics().isEmpty()) { + return ImmutableList.of(); + } + List topics = new ArrayList<>(response.getTopics().size()); + for (Topic topic : response.getTopics()) { + topics.add(topicPathFromPath(topic.getName())); + } + return topics; + } + + @Override + public void createSubscription( + TopicPath topic, SubscriptionPath subscription, + int ackDeadlineSeconds) throws IOException { + Subscription request = new Subscription() + .setTopic(topic.getPath()) + .setAckDeadlineSeconds(ackDeadlineSeconds); + pubsub.projects() + .subscriptions() + .create(subscription.getPath(), request) + .execute(); // ignore Subscription result. + } + + @Override + public void deleteSubscription(SubscriptionPath subscription) throws IOException { + pubsub.projects() + .subscriptions() + .delete(subscription.getPath()) + .execute(); // ignore Empty result. + } + + @Override + public List listSubscriptions(ProjectPath project, TopicPath topic) + throws IOException { + ListSubscriptionsResponse response = pubsub.projects() + .subscriptions() + .list(project.getPath()) + .execute(); + if (response.getSubscriptions() == null || response.getSubscriptions().isEmpty()) { + return ImmutableList.of(); + } + List subscriptions = new ArrayList<>(response.getSubscriptions().size()); + for (Subscription subscription : response.getSubscriptions()) { + if (subscription.getTopic().equals(topic.getPath())) { + subscriptions.add(subscriptionPathFromPath(subscription.getName())); + } + } + return subscriptions; + } + + @Override + public int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException { + Subscription response = pubsub.projects().subscriptions().get(subscription.getPath()).execute(); + return response.getAckDeadlineSeconds(); + } + + @Override + public boolean isEOF() { + return false; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java new file mode 100644 index 0000000000..46eaf006c1 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java @@ -0,0 +1,544 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; + +import com.google.api.client.util.DateTime; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.common.base.Objects; +import com.google.common.base.Strings; + +import java.io.Closeable; +import java.io.IOException; +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +import javax.annotation.Nullable; + +/** + * An (abstract) helper class for talking to Pubsub via an underlying transport. + */ +public abstract class PubsubClient implements Closeable { + /** + * Factory for creating clients. + */ + public interface PubsubClientFactory extends Serializable { + /** + * Construct a new Pubsub client. It should be closed via {@link #close} in order + * to ensure tidy cleanup of underlying netty resources (or use the try-with-resources + * construct). Uses {@code options} to derive pubsub endpoints and application credentials. + * If non-{@literal null}, use {@code timestampLabel} and {@code idLabel} to store custom + * timestamps/ids within message metadata. + */ + PubsubClient newClient( + @Nullable String timestampLabel, + @Nullable String idLabel, + DataflowPipelineOptions options) throws IOException; + + /** + * Return the display name for this factory. Eg "Apiary", "gRPC". + */ + String getKind(); + } + + /** + * Return timestamp as ms-since-unix-epoch corresponding to {@code timestamp}. + * Return {@literal null} if no timestamp could be found. Throw {@link IllegalArgumentException} + * if timestamp cannot be recognized. + */ + @Nullable + private static Long asMsSinceEpoch(@Nullable String timestamp) { + if (Strings.isNullOrEmpty(timestamp)) { + return null; + } + try { + // Try parsing as milliseconds since epoch. Note there is no way to parse a + // string in RFC 3339 format here. + // Expected IllegalArgumentException if parsing fails; we use that to fall back + // to RFC 3339. + return Long.parseLong(timestamp); + } catch (IllegalArgumentException e1) { + // Try parsing as RFC3339 string. DateTime.parseRfc3339 will throw an + // IllegalArgumentException if parsing fails, and the caller should handle. + return DateTime.parseRfc3339(timestamp).getValue(); + } + } + + /** + * Return the timestamp (in ms since unix epoch) to use for a Pubsub message with {@code + * attributes} and {@code pubsubTimestamp}. + *

          If {@code timestampLabel} is non-{@literal null} then the message attributes must contain + * that label, and the value of that label will be taken as the timestamp. + * Otherwise the timestamp will be taken from the Pubsub publish timestamp {@code + * pubsubTimestamp}. Throw {@link IllegalArgumentException} if the timestamp cannot be + * recognized as a ms-since-unix-epoch or RFC3339 time. + * + * @throws IllegalArgumentException + */ + protected static long extractTimestamp( + @Nullable String timestampLabel, + @Nullable String pubsubTimestamp, + @Nullable Map attributes) { + Long timestampMsSinceEpoch; + if (Strings.isNullOrEmpty(timestampLabel)) { + timestampMsSinceEpoch = asMsSinceEpoch(pubsubTimestamp); + checkArgument(timestampMsSinceEpoch != null, + "Cannot interpret PubSub publish timestamp: %s", + pubsubTimestamp); + } else { + String value = attributes == null ? null : attributes.get(timestampLabel); + checkArgument(value != null, + "PubSub message is missing a value for timestamp label %s", + timestampLabel); + timestampMsSinceEpoch = asMsSinceEpoch(value); + checkArgument(timestampMsSinceEpoch != null, + "Cannot interpret value of label %s as timestamp: %s", + timestampLabel, value); + } + return timestampMsSinceEpoch; + } + + /** + * Path representing a cloud project id. + */ + public static class ProjectPath implements Serializable { + private final String path; + + ProjectPath(String path) { + this.path = path; + } + + public String getPath() { + return path; + } + + public String getId() { + String[] splits = path.split("/"); + checkState(splits.length == 1, "Malformed project path %s", path); + return splits[1]; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + ProjectPath that = (ProjectPath) o; + + return path.equals(that.path); + + } + + @Override + public int hashCode() { + return path.hashCode(); + } + + @Override + public String toString() { + return path; + } + } + + public static ProjectPath projectPathFromPath(String path) { + return new ProjectPath(path); + } + + public static ProjectPath projectPathFromId(String projectId) { + return new ProjectPath(String.format("projects/%s", projectId)); + } + + /** + * Path representing a Pubsub subscription. + */ + public static class SubscriptionPath implements Serializable { + private final String path; + + SubscriptionPath(String path) { + this.path = path; + } + + public String getPath() { + return path; + } + + public String getName() { + String[] splits = path.split("/"); + checkState(splits.length == 4, "Malformed subscription path %s", path); + return splits[3]; + } + + public String getV1Beta1Path() { + String[] splits = path.split("/"); + checkState(splits.length == 4, "Malformed subscription path %s", path); + return String.format("/subscriptions/%s/%s", splits[1], splits[3]); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SubscriptionPath that = (SubscriptionPath) o; + return path.equals(that.path); + } + + @Override + public int hashCode() { + return path.hashCode(); + } + + @Override + public String toString() { + return path; + } + } + + public static SubscriptionPath subscriptionPathFromPath(String path) { + return new SubscriptionPath(path); + } + + public static SubscriptionPath subscriptionPathFromName( + String projectId, String subscriptionName) { + return new SubscriptionPath(String.format("projects/%s/subscriptions/%s", + projectId, subscriptionName)); + } + + /** + * Path representing a Pubsub topic. + */ + public static class TopicPath implements Serializable { + private final String path; + + TopicPath(String path) { + this.path = path; + } + + public String getPath() { + return path; + } + + public String getName() { + String[] splits = path.split("/"); + checkState(splits.length == 4, "Malformed topic path %s", path); + return splits[3]; + } + + public String getV1Beta1Path() { + String[] splits = path.split("/"); + checkState(splits.length == 4, "Malformed topic path %s", path); + return String.format("/topics/%s/%s", splits[1], splits[3]); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TopicPath topicPath = (TopicPath) o; + return path.equals(topicPath.path); + } + + @Override + public int hashCode() { + return path.hashCode(); + } + + @Override + public String toString() { + return path; + } + } + + public static TopicPath topicPathFromPath(String path) { + return new TopicPath(path); + } + + public static TopicPath topicPathFromName(String projectId, String topicName) { + return new TopicPath(String.format("projects/%s/topics/%s", projectId, topicName)); + } + + /** + * A message to be sent to Pubsub. + *

          NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. + * Java serialization is never used for non-test clients. + */ + public static class OutgoingMessage implements Serializable { + /** + * Underlying (encoded) element. + */ + public final byte[] elementBytes; + + /** + * Timestamp for element (ms since epoch). + */ + public final long timestampMsSinceEpoch; + + /** + * If using an id label, the record id to associate with this record's metadata so the receiver + * can reject duplicates. Otherwise {@literal null}. + */ + @Nullable + public final String recordId; + + public OutgoingMessage( + byte[] elementBytes, long timestampMsSinceEpoch, @Nullable String recordId) { + this.elementBytes = elementBytes; + this.timestampMsSinceEpoch = timestampMsSinceEpoch; + this.recordId = recordId; + } + + @Override + public String toString() { + return String.format("OutgoingMessage(%db, %dms)", + elementBytes.length, timestampMsSinceEpoch); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + OutgoingMessage that = (OutgoingMessage) o; + + return timestampMsSinceEpoch == that.timestampMsSinceEpoch + && Arrays.equals(elementBytes, that.elementBytes) + && Objects.equal(recordId, that.recordId); + } + + @Override + public int hashCode() { + return Objects.hashCode(Arrays.hashCode(elementBytes), timestampMsSinceEpoch, recordId); + } + } + + /** + * A message received from Pubsub. + *

          NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. + * Java serialization is never used for non-test clients. + */ + public static class IncomingMessage implements Serializable { + /** + * Underlying (encoded) element. + */ + public final byte[] elementBytes; + + /** + * Timestamp for element (ms since epoch). Either Pubsub's processing time, + * or the custom timestamp associated with the message. + */ + public final long timestampMsSinceEpoch; + + /** + * Timestamp (in system time) at which we requested the message (ms since epoch). + */ + public final long requestTimeMsSinceEpoch; + + /** + * Id to pass back to Pubsub to acknowledge receipt of this message. + */ + public final String ackId; + + /** + * Id to pass to the runner to distinguish this message from all others. + */ + public final String recordId; + + public IncomingMessage( + byte[] elementBytes, + long timestampMsSinceEpoch, + long requestTimeMsSinceEpoch, + String ackId, + String recordId) { + this.elementBytes = elementBytes; + this.timestampMsSinceEpoch = timestampMsSinceEpoch; + this.requestTimeMsSinceEpoch = requestTimeMsSinceEpoch; + this.ackId = ackId; + this.recordId = recordId; + } + + public IncomingMessage withRequestTime(long requestTimeMsSinceEpoch) { + return new IncomingMessage(elementBytes, timestampMsSinceEpoch, requestTimeMsSinceEpoch, + ackId, recordId); + } + + @Override + public String toString() { + return String.format("IncomingMessage(%db, %dms)", + elementBytes.length, timestampMsSinceEpoch); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + IncomingMessage that = (IncomingMessage) o; + + return timestampMsSinceEpoch == that.timestampMsSinceEpoch + && requestTimeMsSinceEpoch == that.requestTimeMsSinceEpoch + && ackId.equals(that.ackId) + && recordId.equals(that.recordId) + && Arrays.equals(elementBytes, that.elementBytes); + } + + @Override + public int hashCode() { + return Objects.hashCode(Arrays.hashCode(elementBytes), timestampMsSinceEpoch, + requestTimeMsSinceEpoch, + ackId, recordId); + } + } + + /** + * Publish {@code outgoingMessages} to Pubsub {@code topic}. Return number of messages + * published. + * + * @throws IOException + */ + public abstract int publish(TopicPath topic, List outgoingMessages) + throws IOException; + + /** + * Request the next batch of up to {@code batchSize} messages from {@code subscription}. + * Return the received messages, or empty collection if none were available. Does not + * wait for messages to arrive if {@code returnImmediately} is {@literal true}. + * Returned messages will record their request time as {@code requestTimeMsSinceEpoch}. + * + * @throws IOException + */ + public abstract List pull( + long requestTimeMsSinceEpoch, + SubscriptionPath subscription, + int batchSize, + boolean returnImmediately) + throws IOException; + + /** + * Acknowldege messages from {@code subscription} with {@code ackIds}. + * + * @throws IOException + */ + public abstract void acknowledge(SubscriptionPath subscription, List ackIds) + throws IOException; + + /** + * Modify the ack deadline for messages from {@code subscription} with {@code ackIds} to + * be {@code deadlineSeconds} from now. + * + * @throws IOException + */ + public abstract void modifyAckDeadline( + SubscriptionPath subscription, List ackIds, + int deadlineSeconds) throws IOException; + + /** + * Create {@code topic}. + * + * @throws IOException + */ + public abstract void createTopic(TopicPath topic) throws IOException; + + /* + * Delete {@code topic}. + * + * @throws IOException + */ + public abstract void deleteTopic(TopicPath topic) throws IOException; + + /** + * Return a list of topics for {@code project}. + * + * @throws IOException + */ + public abstract List listTopics(ProjectPath project) throws IOException; + + /** + * Create {@code subscription} to {@code topic}. + * + * @throws IOException + */ + public abstract void createSubscription( + TopicPath topic, SubscriptionPath subscription, int ackDeadlineSeconds) throws IOException; + + /** + * Create a random subscription for {@code topic}. Return the {@link SubscriptionPath}. It + * is the responsibility of the caller to later delete the subscription. + * + * @throws IOException + */ + public SubscriptionPath createRandomSubscription( + ProjectPath project, TopicPath topic, int ackDeadlineSeconds) throws IOException { + // Create a randomized subscription derived from the topic name. + String subscriptionName = topic.getName() + "_beam_" + ThreadLocalRandom.current().nextLong(); + SubscriptionPath subscription = + PubsubClient.subscriptionPathFromName(project.getId(), subscriptionName); + createSubscription(topic, subscription, ackDeadlineSeconds); + return subscription; + } + + /** + * Delete {@code subscription}. + * + * @throws IOException + */ + public abstract void deleteSubscription(SubscriptionPath subscription) throws IOException; + + /** + * Return a list of subscriptions for {@code topic} in {@code project}. + * + * @throws IOException + */ + public abstract List listSubscriptions(ProjectPath project, TopicPath topic) + throws IOException; + + /** + * Return the ack deadline, in seconds, for {@code subscription}. + * + * @throws IOException + */ + public abstract int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException; + + /** + * Return {@literal true} if {@link #pull} will always return empty list. Actual clients + * will return {@literal false}. Test clients may return {@literal true} to signal that all + * expected messages have been pulled and the test may complete. + */ + public abstract boolean isEOF(); +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java new file mode 100644 index 0000000000..05ebfa3883 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java @@ -0,0 +1,444 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.PublisherGrpc; +import com.google.pubsub.v1.PublisherGrpc.PublisherBlockingStub; +import com.google.pubsub.v1.PubsubMessage; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.ReceivedMessage; +import com.google.pubsub.v1.SubscriberGrpc; +import com.google.pubsub.v1.SubscriberGrpc.SubscriberBlockingStub; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.Topic; + +import io.grpc.Channel; +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import io.grpc.auth.ClientAuthInterceptor; +import io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.NegotiationType; +import io.grpc.netty.NettyChannelBuilder; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import javax.annotation.Nullable; + +/** + * A helper class for talking to Pubsub via grpc. + * + *

          CAUTION: Currently uses the application default credentials and does not respect any + * credentials-related arguments in {@link DataflowPipelineOptions}. + */ +public class PubsubGrpcClient extends PubsubClient { + private static final String PUBSUB_ADDRESS = "pubsub.googleapis.com"; + private static final int PUBSUB_PORT = 443; + // Will be needed when credentials are correctly constructed and scoped. + @SuppressWarnings("unused") + private static final List PUBSUB_SCOPES = + Collections.singletonList("https://www.googleapis.com/auth/pubsub"); + private static final int LIST_BATCH_SIZE = 1000; + + private static final int DEFAULT_TIMEOUT_S = 15; + + private static class PubsubGrpcClientFactory implements PubsubClientFactory { + @Override + public PubsubClient newClient( + @Nullable String timestampLabel, @Nullable String idLabel, DataflowPipelineOptions options) + throws IOException { + ManagedChannel channel = NettyChannelBuilder + .forAddress(PUBSUB_ADDRESS, PUBSUB_PORT) + .negotiationType(NegotiationType.TLS) + .sslContext(GrpcSslContexts.forClient().ciphers(null).build()) + .build(); + // TODO: GcpOptions needs to support building com.google.auth.oauth2.Credentials from the + // various command line options. It currently only supports the older + // com.google.api.client.auth.oauth2.Credentials. + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); + return new PubsubGrpcClient(timestampLabel, + idLabel, + DEFAULT_TIMEOUT_S, + channel, + credentials, + null /* publisher stub */, + null /* subscriber stub */); + } + + @Override + public String getKind() { + return "Grpc"; + } + } + + /** + * Factory for creating Pubsub clients using gRCP transport. + */ + public static final PubsubClientFactory FACTORY = new PubsubGrpcClientFactory(); + + /** + * Timeout for grpc calls (in s). + */ + private final int timeoutSec; + + /** + * Underlying netty channel, or {@literal null} if closed. + */ + @Nullable + private ManagedChannel publisherChannel; + + /** + * Credentials determined from options and environment. + */ + private final GoogleCredentials credentials; + + /** + * Label to use for custom timestamps, or {@literal null} if should use Pubsub publish time + * instead. + */ + @Nullable + private final String timestampLabel; + + /** + * Label to use for custom ids, or {@literal null} if should use Pubsub provided ids. + */ + @Nullable + private final String idLabel; + + + /** + * Cached stubs, or null if not cached. + */ + @Nullable + private PublisherGrpc.PublisherBlockingStub cachedPublisherStub; + private SubscriberGrpc.SubscriberBlockingStub cachedSubscriberStub; + + @VisibleForTesting + PubsubGrpcClient( + @Nullable String timestampLabel, + @Nullable String idLabel, + int timeoutSec, + ManagedChannel publisherChannel, + GoogleCredentials credentials, + PublisherGrpc.PublisherBlockingStub cachedPublisherStub, + SubscriberGrpc.SubscriberBlockingStub cachedSubscriberStub) { + this.timestampLabel = timestampLabel; + this.idLabel = idLabel; + this.timeoutSec = timeoutSec; + this.publisherChannel = publisherChannel; + this.credentials = credentials; + this.cachedPublisherStub = cachedPublisherStub; + this.cachedSubscriberStub = cachedSubscriberStub; + } + + /** + * Gracefully close the underlying netty channel. + */ + @Override + public void close() { + if (publisherChannel == null) { + // Already closed. + return; + } + // Can gc the underlying stubs. + cachedPublisherStub = null; + cachedSubscriberStub = null; + // Mark the client as having been closed before going further + // in case we have an exception from the channel. + ManagedChannel publisherChannel = this.publisherChannel; + this.publisherChannel = null; + // Gracefully shutdown the channel. + publisherChannel.shutdown(); + if (timeoutSec > 0) { + try { + publisherChannel.awaitTermination(timeoutSec, TimeUnit.SECONDS); + } catch (InterruptedException e) { + // Ignore. + Thread.currentThread().interrupt(); + } + } + } + + /** + * Return channel with interceptor for returning credentials. + */ + private Channel newChannel() throws IOException { + checkState(publisherChannel != null, "PubsubGrpcClient has been closed"); + ClientAuthInterceptor interceptor = + new ClientAuthInterceptor(credentials, Executors.newSingleThreadExecutor()); + return ClientInterceptors.intercept(publisherChannel, interceptor); + } + + /** + * Return a stub for making a publish request with a timeout. + */ + private PublisherBlockingStub publisherStub() throws IOException { + if (cachedPublisherStub == null) { + cachedPublisherStub = PublisherGrpc.newBlockingStub(newChannel()); + } + if (timeoutSec > 0) { + return cachedPublisherStub.withDeadlineAfter(timeoutSec, TimeUnit.SECONDS); + } else { + return cachedPublisherStub; + } + } + + /** + * Return a stub for making a subscribe request with a timeout. + */ + private SubscriberBlockingStub subscriberStub() throws IOException { + if (cachedSubscriberStub == null) { + cachedSubscriberStub = SubscriberGrpc.newBlockingStub(newChannel()); + } + if (timeoutSec > 0) { + return cachedSubscriberStub.withDeadlineAfter(timeoutSec, TimeUnit.SECONDS); + } else { + return cachedSubscriberStub; + } + } + + @Override + public int publish(TopicPath topic, List outgoingMessages) + throws IOException { + PublishRequest.Builder request = PublishRequest.newBuilder() + .setTopic(topic.getPath()); + for (OutgoingMessage outgoingMessage : outgoingMessages) { + PubsubMessage.Builder message = + PubsubMessage.newBuilder() + .setData(ByteString.copyFrom(outgoingMessage.elementBytes)); + + if (timestampLabel != null) { + message.getMutableAttributes() + .put(timestampLabel, String.valueOf(outgoingMessage.timestampMsSinceEpoch)); + } + + if (idLabel != null && !Strings.isNullOrEmpty(outgoingMessage.recordId)) { + message.getMutableAttributes().put(idLabel, outgoingMessage.recordId); + } + + request.addMessages(message); + } + + PublishResponse response = publisherStub().publish(request.build()); + return response.getMessageIdsCount(); + } + + @Override + public List pull( + long requestTimeMsSinceEpoch, + SubscriptionPath subscription, + int batchSize, + boolean returnImmediately) throws IOException { + PullRequest request = PullRequest.newBuilder() + .setSubscription(subscription.getPath()) + .setReturnImmediately(returnImmediately) + .setMaxMessages(batchSize) + .build(); + PullResponse response = subscriberStub().pull(request); + if (response.getReceivedMessagesCount() == 0) { + return ImmutableList.of(); + } + List incomingMessages = new ArrayList<>(response.getReceivedMessagesCount()); + for (ReceivedMessage message : response.getReceivedMessagesList()) { + PubsubMessage pubsubMessage = message.getMessage(); + @Nullable Map attributes = pubsubMessage.getAttributes(); + + // Payload. + byte[] elementBytes = pubsubMessage.getData().toByteArray(); + + // Timestamp. + String pubsubTimestampString = null; + Timestamp timestampProto = pubsubMessage.getPublishTime(); + if (timestampProto != null) { + pubsubTimestampString = String.valueOf(timestampProto.getSeconds() + + timestampProto.getNanos() / 1000L); + } + long timestampMsSinceEpoch = + extractTimestamp(timestampLabel, pubsubTimestampString, attributes); + + // Ack id. + String ackId = message.getAckId(); + checkState(!Strings.isNullOrEmpty(ackId)); + + // Record id, if any. + @Nullable String recordId = null; + if (idLabel != null && attributes != null) { + recordId = attributes.get(idLabel); + } + if (Strings.isNullOrEmpty(recordId)) { + // Fall back to the Pubsub provided message id. + recordId = pubsubMessage.getMessageId(); + } + + incomingMessages.add(new IncomingMessage(elementBytes, timestampMsSinceEpoch, + requestTimeMsSinceEpoch, ackId, recordId)); + } + return incomingMessages; + } + + @Override + public void acknowledge(SubscriptionPath subscription, List ackIds) + throws IOException { + AcknowledgeRequest request = AcknowledgeRequest.newBuilder() + .setSubscription(subscription.getPath()) + .addAllAckIds(ackIds) + .build(); + subscriberStub().acknowledge(request); // ignore Empty result. + } + + @Override + public void modifyAckDeadline( + SubscriptionPath subscription, List ackIds, int deadlineSeconds) + throws IOException { + ModifyAckDeadlineRequest request = + ModifyAckDeadlineRequest.newBuilder() + .setSubscription(subscription.getPath()) + .addAllAckIds(ackIds) + .setAckDeadlineSeconds(deadlineSeconds) + .build(); + subscriberStub().modifyAckDeadline(request); // ignore Empty result. + } + + @Override + public void createTopic(TopicPath topic) throws IOException { + Topic request = Topic.newBuilder() + .setName(topic.getPath()) + .build(); + publisherStub().createTopic(request); // ignore Topic result. + } + + @Override + public void deleteTopic(TopicPath topic) throws IOException { + DeleteTopicRequest request = DeleteTopicRequest.newBuilder() + .setTopic(topic.getPath()) + .build(); + publisherStub().deleteTopic(request); // ignore Empty result. + } + + @Override + public List listTopics(ProjectPath project) throws IOException { + ListTopicsRequest.Builder request = + ListTopicsRequest.newBuilder() + .setProject(project.getPath()) + .setPageSize(LIST_BATCH_SIZE); + ListTopicsResponse response = publisherStub().listTopics(request.build()); + if (response.getTopicsCount() == 0) { + return ImmutableList.of(); + } + List topics = new ArrayList<>(response.getTopicsCount()); + while (true) { + for (Topic topic : response.getTopicsList()) { + topics.add(topicPathFromPath(topic.getName())); + } + if (response.getNextPageToken().isEmpty()) { + break; + } + request.setPageToken(response.getNextPageToken()); + response = publisherStub().listTopics(request.build()); + } + return topics; + } + + @Override + public void createSubscription( + TopicPath topic, SubscriptionPath subscription, + int ackDeadlineSeconds) throws IOException { + Subscription request = Subscription.newBuilder() + .setTopic(topic.getPath()) + .setName(subscription.getPath()) + .setAckDeadlineSeconds(ackDeadlineSeconds) + .build(); + subscriberStub().createSubscription(request); // ignore Subscription result. + } + + @Override + public void deleteSubscription(SubscriptionPath subscription) throws IOException { + DeleteSubscriptionRequest request = + DeleteSubscriptionRequest.newBuilder() + .setSubscription(subscription.getPath()) + .build(); + subscriberStub().deleteSubscription(request); // ignore Empty result. + } + + @Override + public List listSubscriptions(ProjectPath project, TopicPath topic) + throws IOException { + ListSubscriptionsRequest.Builder request = + ListSubscriptionsRequest.newBuilder() + .setProject(project.getPath()) + .setPageSize(LIST_BATCH_SIZE); + ListSubscriptionsResponse response = subscriberStub().listSubscriptions(request.build()); + if (response.getSubscriptionsCount() == 0) { + return ImmutableList.of(); + } + List subscriptions = new ArrayList<>(response.getSubscriptionsCount()); + while (true) { + for (Subscription subscription : response.getSubscriptionsList()) { + if (subscription.getTopic().equals(topic.getPath())) { + subscriptions.add(subscriptionPathFromPath(subscription.getName())); + } + } + if (response.getNextPageToken().isEmpty()) { + break; + } + request.setPageToken(response.getNextPageToken()); + response = subscriberStub().listSubscriptions(request.build()); + } + return subscriptions; + } + + @Override + public int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException { + GetSubscriptionRequest request = + GetSubscriptionRequest.newBuilder() + .setSubscription(subscription.getPath()) + .build(); + Subscription response = subscriberStub().getSubscription(request); + return response.getAckDeadlineSeconds(); + } + + @Override + public boolean isEOF() { + return false; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java new file mode 100644 index 0000000000..df8c1a72e6 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java @@ -0,0 +1,403 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.api.client.util.Clock; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; + +/** + * A (partial) implementation of {@link PubsubClient} for use by unit tests. Only suitable for + * testing {@link #publish}, {@link #pull}, {@link #acknowledge} and {@link #modifyAckDeadline} + * methods. Relies on statics to mimic the Pubsub service, though we try to hide that. + */ +public class PubsubTestClient extends PubsubClient { + /** + * Mimic the state of the simulated Pubsub 'service'. + * + * Note that the {@link PubsubTestClientFactory} is serialized/deserialized even when running + * test pipelines. Meanwhile it is valid for multiple {@link PubsubTestClient}s to be created + * from the same client factory and run in parallel. Thus we can't enforce aliasing of the + * following data structures over all clients and must resort to a static. + */ + private static class State { + /** + * True if has been primed for a test but not yet validated. + */ + boolean isActive; + + /** + * Publish mode only: Only publish calls for this topic are allowed. + */ + @Nullable + TopicPath expectedTopic; + + /** + * Publish mode only: Messages yet to seen in a {@link #publish} call. + */ + @Nullable + Set remainingExpectedOutgoingMessages; + + /** + * Publish mode only: Messages which should throw when first sent to simulate transient publish + * failure. + */ + @Nullable + Set remainingFailingOutgoingMessages; + + /** + * Pull mode only: Clock from which to get current time. + */ + @Nullable + Clock clock; + + /** + * Pull mode only: Only pull calls for this subscription are allowed. + */ + @Nullable + SubscriptionPath expectedSubscription; + + /** + * Pull mode only: Timeout to simulate. + */ + int ackTimeoutSec; + + /** + * Pull mode only: Messages waiting to be received by a {@link #pull} call. + */ + @Nullable + List remainingPendingIncomingMessages; + + /** + * Pull mode only: Messages which have been returned from a {@link #pull} call and + * not yet ACKed by an {@link #acknowledge} call. + */ + @Nullable + Map pendingAckIncomingMessages; + + /** + * Pull mode only: When above messages are due to have their ACK deadlines expire. + */ + @Nullable + Map ackDeadline; + } + + private static final State STATE = new State(); + + /** Closing the factory will validate all expected messages were processed. */ + public interface PubsubTestClientFactory extends PubsubClientFactory, Closeable { + } + + /** + * Return a factory for testing publishers. Only one factory may be in-flight at a time. + * The factory must be closed when the test is complete, at which point final validation will + * occur. + */ + public static PubsubTestClientFactory createFactoryForPublish( + final TopicPath expectedTopic, + final Iterable expectedOutgoingMessages, + final Iterable failingOutgoingMessages) { + synchronized (STATE) { + checkState(!STATE.isActive, "Test still in flight"); + STATE.expectedTopic = expectedTopic; + STATE.remainingExpectedOutgoingMessages = Sets.newHashSet(expectedOutgoingMessages); + STATE.remainingFailingOutgoingMessages = Sets.newHashSet(failingOutgoingMessages); + STATE.isActive = true; + } + return new PubsubTestClientFactory() { + @Override + public PubsubClient newClient( + @Nullable String timestampLabel, @Nullable String idLabel, + DataflowPipelineOptions options) + throws IOException { + return new PubsubTestClient(); + } + + @Override + public String getKind() { + return "PublishTest"; + } + + @Override + public void close() { + synchronized (STATE) { + checkState(STATE.isActive, "No test still in flight"); + checkState(STATE.remainingExpectedOutgoingMessages.isEmpty(), + "Still waiting for %s messages to be published", + STATE.remainingExpectedOutgoingMessages.size()); + STATE.isActive = false; + STATE.remainingExpectedOutgoingMessages = null; + } + } + }; + } + + /** + * Return a factory for testing subscribers. Only one factory may be in-flight at a time. + * The factory must be closed when the test in complete + */ + public static PubsubTestClientFactory createFactoryForPull( + final Clock clock, + final SubscriptionPath expectedSubscription, + final int ackTimeoutSec, + final Iterable expectedIncomingMessages) { + synchronized (STATE) { + checkState(!STATE.isActive, "Test still in flight"); + STATE.clock = clock; + STATE.expectedSubscription = expectedSubscription; + STATE.ackTimeoutSec = ackTimeoutSec; + STATE.remainingPendingIncomingMessages = Lists.newArrayList(expectedIncomingMessages); + STATE.pendingAckIncomingMessages = new HashMap<>(); + STATE.ackDeadline = new HashMap<>(); + STATE.isActive = true; + } + return new PubsubTestClientFactory() { + @Override + public PubsubClient newClient( + @Nullable String timestampLabel, @Nullable String idLabel, + DataflowPipelineOptions options) + throws IOException { + return new PubsubTestClient(); + } + + @Override + public String getKind() { + return "PullTest"; + } + + @Override + public void close() { + synchronized (STATE) { + checkState(STATE.isActive, "No test still in flight"); + checkState(STATE.remainingPendingIncomingMessages.isEmpty(), + "Still waiting for %s messages to be pulled", + STATE.remainingPendingIncomingMessages.size()); + checkState(STATE.pendingAckIncomingMessages.isEmpty(), + "Still waiting for %s messages to be ACKed", + STATE.pendingAckIncomingMessages.size()); + checkState(STATE.ackDeadline.isEmpty(), + "Still waiting for %s messages to be ACKed", + STATE.ackDeadline.size()); + STATE.isActive = false; + STATE.remainingPendingIncomingMessages = null; + STATE.pendingAckIncomingMessages = null; + STATE.ackDeadline = null; + } + } + }; + } + + /** + * Return true if in pull mode. + */ + private boolean inPullMode() { + checkState(STATE.isActive, "No test is active"); + return STATE.expectedSubscription != null; + } + + /** + * Return true if in publish mode. + */ + private boolean inPublishMode() { + checkState(STATE.isActive, "No test is active"); + return STATE.expectedTopic != null; + } + + /** + * For subscription mode only: + * Track progression of time according to the {@link Clock} passed . This will simulate Pubsub + * expiring + * outstanding ACKs. + */ + public void advance() { + synchronized (STATE) { + checkState(inPullMode(), "Can only advance in pull mode"); + // Any messages who's ACKs timed out are available for re-pulling. + Iterator> deadlineItr = STATE.ackDeadline.entrySet().iterator(); + while (deadlineItr.hasNext()) { + Map.Entry entry = deadlineItr.next(); + if (entry.getValue() <= STATE.clock.currentTimeMillis()) { + STATE.remainingPendingIncomingMessages.add( + STATE.pendingAckIncomingMessages.remove(entry.getKey())); + deadlineItr.remove(); + } + } + } + } + + @Override + public void close() { + } + + @Override + public int publish( + TopicPath topic, List outgoingMessages) throws IOException { + synchronized (STATE) { + checkState(inPublishMode(), "Can only publish in publish mode"); + checkState(topic.equals(STATE.expectedTopic), "Topic %s does not match expected %s", topic, + STATE.expectedTopic); + for (OutgoingMessage outgoingMessage : outgoingMessages) { + if (STATE.remainingFailingOutgoingMessages.remove(outgoingMessage)) { + throw new RuntimeException("Simulating failure for " + outgoingMessage); + } + checkState(STATE.remainingExpectedOutgoingMessages.remove(outgoingMessage), + "Unexpected outgoing message %s", outgoingMessage); + } + return outgoingMessages.size(); + } + } + + @Override + public List pull( + long requestTimeMsSinceEpoch, SubscriptionPath subscription, int batchSize, + boolean returnImmediately) throws IOException { + synchronized (STATE) { + checkState(inPullMode(), "Can only pull in pull mode"); + long now = STATE.clock.currentTimeMillis(); + checkState(requestTimeMsSinceEpoch == now, + "Simulated time %s does not match request time %s", now, requestTimeMsSinceEpoch); + checkState(subscription.equals(STATE.expectedSubscription), + "Subscription %s does not match expected %s", subscription, + STATE.expectedSubscription); + checkState(returnImmediately, "Pull only supported if returning immediately"); + + List incomingMessages = new ArrayList<>(); + Iterator pendItr = STATE.remainingPendingIncomingMessages.iterator(); + while (pendItr.hasNext()) { + IncomingMessage incomingMessage = pendItr.next(); + pendItr.remove(); + IncomingMessage incomingMessageWithRequestTime = + incomingMessage.withRequestTime(requestTimeMsSinceEpoch); + incomingMessages.add(incomingMessageWithRequestTime); + STATE.pendingAckIncomingMessages.put(incomingMessageWithRequestTime.ackId, + incomingMessageWithRequestTime); + STATE.ackDeadline.put(incomingMessageWithRequestTime.ackId, + requestTimeMsSinceEpoch + STATE.ackTimeoutSec * 1000); + if (incomingMessages.size() >= batchSize) { + break; + } + } + return incomingMessages; + } + } + + @Override + public void acknowledge( + SubscriptionPath subscription, + List ackIds) throws IOException { + synchronized (STATE) { + checkState(inPullMode(), "Can only acknowledge in pull mode"); + checkState(subscription.equals(STATE.expectedSubscription), + "Subscription %s does not match expected %s", subscription, + STATE.expectedSubscription); + + for (String ackId : ackIds) { + checkState(STATE.ackDeadline.remove(ackId) != null, + "No message with ACK id %s is waiting for an ACK", ackId); + checkState(STATE.pendingAckIncomingMessages.remove(ackId) != null, + "No message with ACK id %s is waiting for an ACK", ackId); + } + } + } + + @Override + public void modifyAckDeadline( + SubscriptionPath subscription, List ackIds, int deadlineSeconds) throws IOException { + synchronized (STATE) { + checkState(inPullMode(), "Can only modify ack deadline in pull mode"); + checkState(subscription.equals(STATE.expectedSubscription), + "Subscription %s does not match expected %s", subscription, + STATE.expectedSubscription); + + for (String ackId : ackIds) { + if (deadlineSeconds > 0) { + checkState(STATE.ackDeadline.remove(ackId) != null, + "No message with ACK id %s is waiting for an ACK", ackId); + checkState(STATE.pendingAckIncomingMessages.containsKey(ackId), + "No message with ACK id %s is waiting for an ACK", ackId); + STATE.ackDeadline.put(ackId, STATE.clock.currentTimeMillis() + deadlineSeconds * 1000); + } else { + checkState(STATE.ackDeadline.remove(ackId) != null, + "No message with ACK id %s is waiting for an ACK", ackId); + IncomingMessage message = STATE.pendingAckIncomingMessages.remove(ackId); + checkState(message != null, "No message with ACK id %s is waiting for an ACK", ackId); + STATE.remainingPendingIncomingMessages.add(message); + } + } + } + } + + @Override + public void createTopic(TopicPath topic) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void deleteTopic(TopicPath topic) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public List listTopics(ProjectPath project) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void createSubscription( + TopicPath topic, SubscriptionPath subscription, int ackDeadlineSeconds) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void deleteSubscription(SubscriptionPath subscription) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public List listSubscriptions( + ProjectPath project, TopicPath topic) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException { + synchronized (STATE) { + return STATE.ackTimeoutSec; + } + } + + @Override + public boolean isEOF() { + synchronized (STATE) { + checkState(inPullMode(), "Can only check EOF in pull mode"); + return STATE.remainingPendingIncomingMessages.isEmpty(); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java index d792753524..75a93b3589 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java @@ -112,7 +112,11 @@ private static ApiComponents apiComponentsFromUrl(String urlString) { * *

          Note: this client's endpoint is not modified by the * {@link DataflowPipelineDebugOptions#getApiRootUrl()} option. + * + * @deprecated Use an appropriate + * {@link com.google.cloud.dataflow.sdk.util.PubsubClient.PubsubClientFactory} */ + @Deprecated public static Pubsub.Builder newPubsubClient(DataflowPipelineOptions options) { return new Pubsub.Builder(getTransport(), getJsonFactory(), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java index dfe5da3457..bbba56187d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java @@ -22,26 +22,19 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -import com.google.api.client.testing.http.FixedClock; -import com.google.api.client.util.Clock; -import com.google.api.services.pubsub.model.PubsubMessage; import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; import org.joda.time.Duration; -import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.HashMap; import java.util.Set; -import javax.annotation.Nullable; - /** * Tests for PubsubIO Read and Write transforms. */ @@ -92,154 +85,6 @@ public void testTopicValidationTooLong() throws Exception { .toString()); } - /** - * Helper function that creates a {@link PubsubMessage} with the given timestamp registered as - * an attribute with the specified label. - * - *

          If {@code label} is {@code null}, then the attributes are {@code null}. - * - *

          Else, if {@code timestamp} is {@code null}, then attributes are present but have no key for - * the label. - */ - private static PubsubMessage messageWithTimestamp( - @Nullable String label, @Nullable String timestamp) { - PubsubMessage message = new PubsubMessage(); - if (label == null) { - message.setAttributes(null); - return message; - } - - message.setAttributes(new HashMap()); - - if (timestamp == null) { - return message; - } - - message.getAttributes().put(label, timestamp); - return message; - } - - /** - * Helper function that parses the given string to a timestamp through the PubSubIO plumbing. - */ - private static Instant parseTimestamp(@Nullable String timestamp) { - PubsubMessage message = messageWithTimestamp("mylabel", timestamp); - return PubsubIO.assignMessageTimestamp(message, "mylabel", Clock.SYSTEM); - } - - @Test - public void noTimestampLabelReturnsNow() { - final long time = 987654321L; - Instant timestamp = PubsubIO.assignMessageTimestamp( - messageWithTimestamp(null, null), null, new FixedClock(time)); - - assertEquals(new Instant(time), timestamp); - } - - @Test - public void timestampLabelWithNullAttributesThrowsError() { - PubsubMessage message = messageWithTimestamp(null, null); - thrown.expect(RuntimeException.class); - thrown.expectMessage("PubSub message is missing a timestamp in label: myLabel"); - - PubsubIO.assignMessageTimestamp(message, "myLabel", Clock.SYSTEM); - } - - @Test - public void timestampLabelSetWithMissingAttributeThrowsError() { - PubsubMessage message = messageWithTimestamp("notMyLabel", "ignored"); - thrown.expect(RuntimeException.class); - thrown.expectMessage("PubSub message is missing a timestamp in label: myLabel"); - - PubsubIO.assignMessageTimestamp(message, "myLabel", Clock.SYSTEM); - } - - @Test - public void timestampLabelParsesMillisecondsSinceEpoch() { - Long millis = 1446162101123L; - assertEquals(new Instant(millis), parseTimestamp(millis.toString())); - } - - @Test - public void timestampLabelParsesRfc3339Seconds() { - String rfc3339 = "2015-10-29T23:41:41Z"; - assertEquals(Instant.parse(rfc3339), parseTimestamp(rfc3339)); - } - - @Test - public void timestampLabelParsesRfc3339Tenths() { - String rfc3339tenths = "2015-10-29T23:41:41.1Z"; - assertEquals(Instant.parse(rfc3339tenths), parseTimestamp(rfc3339tenths)); - } - - @Test - public void timestampLabelParsesRfc3339Hundredths() { - String rfc3339hundredths = "2015-10-29T23:41:41.12Z"; - assertEquals(Instant.parse(rfc3339hundredths), parseTimestamp(rfc3339hundredths)); - } - - @Test - public void timestampLabelParsesRfc3339Millis() { - String rfc3339millis = "2015-10-29T23:41:41.123Z"; - assertEquals(Instant.parse(rfc3339millis), parseTimestamp(rfc3339millis)); - } - - @Test - public void timestampLabelParsesRfc3339Micros() { - String rfc3339micros = "2015-10-29T23:41:41.123456Z"; - assertEquals(Instant.parse(rfc3339micros), parseTimestamp(rfc3339micros)); - // Note: micros part 456/1000 is dropped. - assertEquals(Instant.parse("2015-10-29T23:41:41.123Z"), parseTimestamp(rfc3339micros)); - } - - @Test - public void timestampLabelParsesRfc3339MicrosRounding() { - String rfc3339micros = "2015-10-29T23:41:41.123999Z"; - assertEquals(Instant.parse(rfc3339micros), parseTimestamp(rfc3339micros)); - // Note: micros part 999/1000 is dropped, not rounded up. - assertEquals(Instant.parse("2015-10-29T23:41:41.123Z"), parseTimestamp(rfc3339micros)); - } - - @Test - public void timestampLabelWithInvalidFormatThrowsError() { - thrown.expect(NumberFormatException.class); - parseTimestamp("not-a-timestamp"); - } - - @Test - public void timestampLabelWithInvalidFormat2ThrowsError() { - thrown.expect(NumberFormatException.class); - parseTimestamp("null"); - } - - @Test - public void timestampLabelWithInvalidFormat3ThrowsError() { - thrown.expect(NumberFormatException.class); - parseTimestamp("2015-10"); - } - - @Test - public void timestampLabelParsesRfc3339WithSmallYear() { - // Google and JodaTime agree on dates after 1582-10-15, when the Gregorian Calendar was adopted - // This is therefore a "small year" until this difference is reconciled. - String rfc3339SmallYear = "1582-10-15T01:23:45.123Z"; - assertEquals(Instant.parse(rfc3339SmallYear), parseTimestamp(rfc3339SmallYear)); - } - - @Test - public void timestampLabelParsesRfc3339WithLargeYear() { - // Year 9999 in range. - String rfc3339LargeYear = "9999-10-29T23:41:41.123999Z"; - assertEquals(Instant.parse(rfc3339LargeYear), parseTimestamp(rfc3339LargeYear)); - } - - @Test - public void timestampLabelRfc3339WithTooLargeYearThrowsError() { - thrown.expect(NumberFormatException.class); - // Year 10000 out of range. - parseTimestamp("10000-10-29T23:41:41.123999Z"); - } - @Test public void testReadDisplayData() { String topic = "projects/project/topics/topic"; @@ -292,7 +137,8 @@ public void testPrimitiveWriteDisplayData() { @Test public void testPrimitiveReadDisplayData() { DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - PubsubIO.Read.Bound read = PubsubIO.Read.topic("projects/project/topics/topic"); + PubsubIO.Read.Bound read = PubsubIO.Read.topic("projects/project/topics/topic") + .maxNumRecords(1); Set displayData = evaluator.displayDataForPrimitiveTransforms(read); assertThat("PubsubIO.Read should include the topic in its primitive display data", diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java new file mode 100644 index 0000000000..ef95a643f9 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io; + +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSink.RecordIdMethod; +import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.util.PubsubClient; +import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; +import com.google.cloud.dataflow.sdk.util.PubsubTestClient; +import com.google.cloud.dataflow.sdk.util.PubsubTestClient.PubsubTestClientFactory; + +import com.google.common.collect.ImmutableList; +import com.google.common.hash.Hashing; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Test PubsubUnboundedSink. + */ +@RunWith(JUnit4.class) +public class PubsubUnboundedSinkTest { + private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); + private static final String DATA = "testData"; + private static final long TIMESTAMP = 1234L; + private static final String TIMESTAMP_LABEL = "timestamp"; + private static final String ID_LABEL = "id"; + private static final int NUM_SHARDS = 10; + + private static class Stamp extends DoFn { + @Override + public void processElement(ProcessContext c) { + c.outputWithTimestamp(c.element(), new Instant(TIMESTAMP)); + } + } + + private String getRecordId(String data) { + return Hashing.murmur3_128().hashBytes(data.getBytes()).toString(); + } + + @Test + public void saneCoder() throws Exception { + OutgoingMessage message = new OutgoingMessage(DATA.getBytes(), TIMESTAMP, getRecordId(DATA)); + CoderProperties.coderDecodeEncodeEqual(PubsubUnboundedSink.CODER, message); + CoderProperties.coderSerializable(PubsubUnboundedSink.CODER); + } + + @Test + public void sendOneMessage() throws IOException { + List outgoing = + ImmutableList.of(new OutgoingMessage(DATA.getBytes(), TIMESTAMP, getRecordId(DATA))); + int batchSize = 1; + int batchBytes = 1; + try (PubsubTestClientFactory factory = + PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, + ImmutableList.of())) { + PubsubUnboundedSink sink = + new PubsubUnboundedSink<>(factory, TOPIC, StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, + NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), + RecordIdMethod.DETERMINISTIC); + TestPipeline p = TestPipeline.create(); + p.apply(Create.of(ImmutableList.of(DATA))) + .apply(ParDo.of(new Stamp())) + .apply(sink); + p.run(); + } + // The PubsubTestClientFactory will assert fail on close if the actual published + // message does not match the expected publish message. + } + + @Test + public void sendMoreThanOneBatchByNumMessages() throws IOException { + List outgoing = new ArrayList<>(); + List data = new ArrayList<>(); + int batchSize = 2; + int batchBytes = 1000; + for (int i = 0; i < batchSize * 10; i++) { + String str = String.valueOf(i); + outgoing.add(new OutgoingMessage(str.getBytes(), TIMESTAMP, getRecordId(str))); + data.add(str); + } + try (PubsubTestClientFactory factory = + PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, + ImmutableList.of())) { + PubsubUnboundedSink sink = + new PubsubUnboundedSink<>(factory, TOPIC, StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, + NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), + RecordIdMethod.DETERMINISTIC); + TestPipeline p = TestPipeline.create(); + p.apply(Create.of(data)) + .apply(ParDo.of(new Stamp())) + .apply(sink); + p.run(); + } + // The PubsubTestClientFactory will assert fail on close if the actual published + // message does not match the expected publish message. + } + + @Test + public void sendMoreThanOneBatchByByteSize() throws IOException { + List outgoing = new ArrayList<>(); + List data = new ArrayList<>(); + int batchSize = 100; + int batchBytes = 10; + int n = 0; + while (n < batchBytes * 10) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < batchBytes; i++) { + sb.append(String.valueOf(n)); + } + String str = sb.toString(); + outgoing.add(new OutgoingMessage(str.getBytes(), TIMESTAMP, getRecordId(str))); + data.add(str); + n += str.length(); + } + try (PubsubTestClientFactory factory = + PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, + ImmutableList.of())) { + PubsubUnboundedSink sink = + new PubsubUnboundedSink<>(factory, TOPIC, StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, + NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), + RecordIdMethod.DETERMINISTIC); + TestPipeline p = TestPipeline.create(); + p.apply(Create.of(data)) + .apply(ParDo.of(new Stamp())) + .apply(sink); + p.run(); + } + // The PubsubTestClientFactory will assert fail on close if the actual published + // message does not match the expected publish message. + } + + // TODO: We would like to test that failed Pubsub publish calls cause the already assigned + // (and random) record ids to be reused. However that can't be done without the test runnner + // supporting retrying bundles. +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java new file mode 100644 index 0000000000..a0b05a5357 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java @@ -0,0 +1,323 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io; + +import static junit.framework.TestCase.assertFalse; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import com.google.api.client.util.Clock; + +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubCheckpoint; +import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubReader; +import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubSource; +import com.google.cloud.dataflow.sdk.testing.CoderProperties; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.PubsubClient; +import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubTestClient; +import com.google.cloud.dataflow.sdk.util.PubsubTestClient.PubsubTestClientFactory; + +import com.google.common.collect.ImmutableList; + +import org.joda.time.Instant; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Test PubsubUnboundedSource. + */ +@RunWith(JUnit4.class) +public class PubsubUnboundedSourceTest { + private static final SubscriptionPath SUBSCRIPTION = + PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); + private static final String DATA = "testData"; + private static final long TIMESTAMP = 1234L; + private static final long REQ_TIME = 6373L; + private static final String TIMESTAMP_LABEL = "timestamp"; + private static final String ID_LABEL = "id"; + private static final String ACK_ID = "testAckId"; + private static final String RECORD_ID = "testRecordId"; + private static final int ACK_TIMEOUT_S = 60; + + private AtomicLong now; + private Clock clock; + private PubsubTestClientFactory factory; + private PubsubSource primSource; + + private void setupOneMessage(Iterable incoming) { + now = new AtomicLong(REQ_TIME); + clock = new Clock() { + @Override + public long currentTimeMillis() { + return now.get(); + } + }; + factory = PubsubTestClient.createFactoryForPull(clock, SUBSCRIPTION, ACK_TIMEOUT_S, incoming); + PubsubUnboundedSource source = + new PubsubUnboundedSource<>(clock, factory, null, null, SUBSCRIPTION, StringUtf8Coder.of(), + TIMESTAMP_LABEL, ID_LABEL); + primSource = new PubsubSource<>(source); + } + + private void setupOneMessage() { + setupOneMessage(ImmutableList.of( + new IncomingMessage(DATA.getBytes(), TIMESTAMP, 0, ACK_ID, RECORD_ID))); + } + + @After + public void after() throws IOException { + factory.close(); + now = null; + clock = null; + primSource = null; + factory = null; + } + + @Test + public void checkpointCoderIsSane() throws Exception { + setupOneMessage(ImmutableList.of()); + CoderProperties.coderSerializable(primSource.getCheckpointMarkCoder()); + // Since we only serialize/deserialize the 'notYetReadIds', and we don't want to make + // equals on checkpoints ignore those fields, we'll test serialization and deserialization + // of checkpoints in multipleReaders below. + } + + @Test + public void readOneMessage() throws IOException { + setupOneMessage(); + TestPipeline p = TestPipeline.create(); + PubsubReader reader = primSource.createReader(p.getOptions(), null); + PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); + // Read one message. + assertTrue(reader.start()); + assertEquals(DATA, reader.getCurrent()); + assertFalse(reader.advance()); + // ACK the message. + PubsubCheckpoint checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + reader.close(); + } + + @Test + public void timeoutAckAndRereadOneMessage() throws IOException { + setupOneMessage(); + TestPipeline p = TestPipeline.create(); + PubsubReader reader = primSource.createReader(p.getOptions(), null); + PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); + assertTrue(reader.start()); + assertEquals(DATA, reader.getCurrent()); + // Let the ACK deadline for the above expire. + now.addAndGet(65 * 1000); + pubsubClient.advance(); + // We'll now receive the same message again. + assertTrue(reader.advance()); + assertEquals(DATA, reader.getCurrent()); + assertFalse(reader.advance()); + // Now ACK the message. + PubsubCheckpoint checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + reader.close(); + } + + @Test + public void extendAck() throws IOException { + setupOneMessage(); + TestPipeline p = TestPipeline.create(); + PubsubReader reader = primSource.createReader(p.getOptions(), null); + PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); + // Pull the first message but don't take a checkpoint for it. + assertTrue(reader.start()); + assertEquals(DATA, reader.getCurrent()); + // Extend the ack + now.addAndGet(55 * 1000); + pubsubClient.advance(); + assertFalse(reader.advance()); + // Extend the ack again + now.addAndGet(25 * 1000); + pubsubClient.advance(); + assertFalse(reader.advance()); + // Now ACK the message. + PubsubCheckpoint checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + reader.close(); + } + + @Test + public void timeoutAckExtensions() throws IOException { + setupOneMessage(); + TestPipeline p = TestPipeline.create(); + PubsubReader reader = primSource.createReader(p.getOptions(), null); + PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); + // Pull the first message but don't take a checkpoint for it. + assertTrue(reader.start()); + assertEquals(DATA, reader.getCurrent()); + // Extend the ack. + now.addAndGet(55 * 1000); + pubsubClient.advance(); + assertFalse(reader.advance()); + // Let the ack expire. + for (int i = 0; i < 3; i++) { + now.addAndGet(25 * 1000); + pubsubClient.advance(); + assertFalse(reader.advance()); + } + // Wait for resend. + now.addAndGet(25 * 1000); + pubsubClient.advance(); + // Reread the same message. + assertTrue(reader.advance()); + assertEquals(DATA, reader.getCurrent()); + // Now ACK the message. + PubsubCheckpoint checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + reader.close(); + } + + @Test + public void multipleReaders() throws IOException { + List incoming = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + String data = String.format("data_%d", i); + String ackid = String.format("ackid_%d", i); + incoming.add(new IncomingMessage(data.getBytes(), TIMESTAMP, 0, ackid, RECORD_ID)); + } + setupOneMessage(incoming); + TestPipeline p = TestPipeline.create(); + PubsubReader reader = primSource.createReader(p.getOptions(), null); + PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); + // Consume two messages, only read one. + assertTrue(reader.start()); + assertEquals("data_0", reader.getCurrent()); + + // Grab checkpoint. + PubsubCheckpoint checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + assertEquals(1, checkpoint.notYetReadIds.size()); + assertEquals("ackid_1", checkpoint.notYetReadIds.get(0)); + + // Read second message. + assertTrue(reader.advance()); + assertEquals("data_1", reader.getCurrent()); + + // Restore from checkpoint. + byte[] checkpointBytes = + CoderUtils.encodeToByteArray(primSource.getCheckpointMarkCoder(), checkpoint); + checkpoint = CoderUtils.decodeFromByteArray(primSource.getCheckpointMarkCoder(), + checkpointBytes); + assertEquals(1, checkpoint.notYetReadIds.size()); + assertEquals("ackid_1", checkpoint.notYetReadIds.get(0)); + + // Re-read second message. + reader = primSource.createReader(p.getOptions(), checkpoint); + assertTrue(reader.start()); + assertEquals("data_1", reader.getCurrent()); + + // We are done. + assertFalse(reader.advance()); + + // ACK final message. + checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + reader.close(); + } + + private long messageNumToTimestamp(int messageNum) { + return TIMESTAMP + messageNum * 100; + } + + @Test + public void readManyMessages() throws IOException { + Map dataToMessageNum = new HashMap<>(); + + final int m = 97; + final int n = 10000; + List incoming = new ArrayList<>(); + for (int i = 0; i < n; i++) { + // Make the messages timestamps slightly out of order. + int messageNum = ((i / m) * m) + (m - 1) - (i % m); + String data = String.format("data_%d", messageNum); + dataToMessageNum.put(data, messageNum); + String recid = String.format("recordid_%d", messageNum); + String ackId = String.format("ackid_%d", messageNum); + incoming.add(new IncomingMessage(data.getBytes(), messageNumToTimestamp(messageNum), 0, + ackId, recid)); + } + setupOneMessage(incoming); + + TestPipeline p = TestPipeline.create(); + PubsubReader reader = primSource.createReader(p.getOptions(), null); + PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); + + for (int i = 0; i < n; i++) { + if (i == 0) { + assertTrue(reader.start()); + } else { + assertTrue(reader.advance()); + } + // We'll checkpoint and ack within the 2min limit. + now.addAndGet(30); + pubsubClient.advance(); + String data = reader.getCurrent(); + Integer messageNum = dataToMessageNum.remove(data); + // No duplicate messages. + assertNotNull(messageNum); + // Preserve timestamp. + assertEquals(new Instant(messageNumToTimestamp(messageNum)), reader.getCurrentTimestamp()); + // Preserve record id. + String recid = String.format("recordid_%d", messageNum); + assertArrayEquals(recid.getBytes(), reader.getCurrentRecordId()); + + if (i % 1000 == 999) { + // Estimated watermark can never get ahead of actual outstanding messages. + long watermark = reader.getWatermark().getMillis(); + long minOutstandingTimestamp = Long.MAX_VALUE; + for (Integer outstandingMessageNum : dataToMessageNum.values()) { + minOutstandingTimestamp = + Math.min(minOutstandingTimestamp, messageNumToTimestamp(outstandingMessageNum)); + } + assertThat(watermark, lessThanOrEqualTo(minOutstandingTimestamp)); + // Ack messages, but only every other finalization. + PubsubCheckpoint checkpoint = reader.getCheckpointMark(); + if (i % 2000 == 1999) { + checkpoint.finalizeCheckpoint(); + } + } + } + // We are done. + assertFalse(reader.advance()); + // We saw each message exactly once. + assertTrue(dataToMessageNum.isEmpty()); + reader.close(); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java new file mode 100644 index 0000000000..130b0bd39b --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.transforms.Combine; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests {@link BucketingFunction}. + */ +@RunWith(JUnit4.class) +public class BucketingFunctionTest { + + private static final long BUCKET_WIDTH = 10; + private static final int SIGNIFICANT_BUCKETS = 2; + private static final int SIGNIFICANT_SAMPLES = 10; + + private static final Combine.BinaryCombineLongFn SUM = + new Combine.BinaryCombineLongFn() { + @Override + public long apply(long left, long right) { + return left + right; + } + + @Override + public long identity() { + return 0; + } + }; + + private BucketingFunction newFunc() { + return new + BucketingFunction(BUCKET_WIDTH, SIGNIFICANT_BUCKETS, + SIGNIFICANT_SAMPLES, SUM); + } + + @Test + public void significantSamples() { + BucketingFunction f = newFunc(); + assertFalse(f.isSignificant()); + for (int i = 0; i < SIGNIFICANT_SAMPLES - 1; i++) { + f.add(0, 0); + assertFalse(f.isSignificant()); + } + f.add(0, 0); + assertTrue(f.isSignificant()); + } + + @Test + public void significantBuckets() { + BucketingFunction f = newFunc(); + assertFalse(f.isSignificant()); + f.add(0, 0); + assertFalse(f.isSignificant()); + f.add(BUCKET_WIDTH, 0); + assertTrue(f.isSignificant()); + } + + @Test + public void sum() { + BucketingFunction f = newFunc(); + for (int i = 0; i < 100; i++) { + f.add(i, i); + assertEquals(((i + 1) * i) / 2, f.get()); + } + } + + @Test + public void movingSum() { + BucketingFunction f = newFunc(); + int lost = 0; + for (int i = 0; i < 200; i++) { + f.add(i, 1); + if (i >= 100) { + f.remove(i - 100); + if (i % BUCKET_WIDTH == BUCKET_WIDTH - 1) { + lost += BUCKET_WIDTH; + } + } + assertEquals(i + 1 - lost, f.get()); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java new file mode 100644 index 0000000000..998d2ba0dc --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.transforms.Combine; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests {@link MovingFunction}. + */ +@RunWith(JUnit4.class) +public class MovingFunctionTest { + + private static final long SAMPLE_PERIOD = 100; + private static final long SAMPLE_UPDATE = 10; + private static final int SIGNIFICANT_BUCKETS = 2; + private static final int SIGNIFICANT_SAMPLES = 10; + + private static final Combine.BinaryCombineLongFn SUM = + new Combine.BinaryCombineLongFn() { + @Override + public long apply(long left, long right) { + return left + right; + } + + @Override + public long identity() { + return 0; + } + }; + + private MovingFunction newFunc() { + return new + MovingFunction(SAMPLE_PERIOD, SAMPLE_UPDATE, SIGNIFICANT_BUCKETS, + SIGNIFICANT_SAMPLES, SUM); + + } + + @Test + public void significantSamples() { + MovingFunction f = newFunc(); + assertFalse(f.isSignificant()); + for (int i = 0; i < SIGNIFICANT_SAMPLES - 1; i++) { + f.add(0, 0); + assertFalse(f.isSignificant()); + } + f.add(0, 0); + assertTrue(f.isSignificant()); + } + + @Test + public void significantBuckets() { + MovingFunction f = newFunc(); + assertFalse(f.isSignificant()); + f.add(0, 0); + assertFalse(f.isSignificant()); + f.add(SAMPLE_UPDATE, 0); + assertTrue(f.isSignificant()); + } + + @Test + public void sum() { + MovingFunction f = newFunc(); + for (int i = 0; i < SAMPLE_PERIOD; i++) { + f.add(i, i); + assertEquals(((i + 1) * i) / 2, f.get(i)); + } + } + + @Test + public void movingSum() { + MovingFunction f = newFunc(); + int lost = 0; + for (int i = 0; i < SAMPLE_PERIOD * 2; i++) { + f.add(i , 1); + if (i >= SAMPLE_PERIOD) { + if (i % SAMPLE_UPDATE == 0) { + lost += SAMPLE_UPDATE; + } + } + assertEquals(i + 1 - lost, f.get(i)); + } + } + + @Test + public void jumpingSum() { + MovingFunction f = newFunc(); + f.add(0, 1); + f.add(SAMPLE_PERIOD - 1, 1); + assertEquals(2, f.get(SAMPLE_PERIOD - 1)); + assertEquals(1, f.get(SAMPLE_PERIOD + 3 * SAMPLE_UPDATE)); + assertEquals(0, f.get(SAMPLE_PERIOD * 2)); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClientTest.java new file mode 100644 index 0000000000..f329347684 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClientTest.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.junit.Assert.assertEquals; + +import com.google.api.services.pubsub.Pubsub; +import com.google.api.services.pubsub.model.PublishRequest; +import com.google.api.services.pubsub.model.PublishResponse; +import com.google.api.services.pubsub.model.PubsubMessage; +import com.google.api.services.pubsub.model.PullRequest; +import com.google.api.services.pubsub.model.PullResponse; +import com.google.api.services.pubsub.model.ReceivedMessage; + +import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import java.io.IOException; +import java.util.List; + +/** + * Tests for PubsubApiaryClient. + */ +public class PubsubApiaryClientTest { + private Pubsub mockPubsub; + private PubsubClient client; + + private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); + private static final SubscriptionPath SUBSCRIPTION = + PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); + private static final long REQ_TIME = 1234L; + private static final long PUB_TIME = 3456L; + private static final long MESSAGE_TIME = 6789L; + private static final String TIMESTAMP_LABEL = "timestamp"; + private static final String ID_LABEL = "id"; + private static final String MESSAGE_ID = "testMessageId"; + private static final String DATA = "testData"; + private static final String RECORD_ID = "testRecordId"; + private static final String ACK_ID = "testAckId"; + + @Before + public void setup() throws IOException { + mockPubsub = Mockito.mock(Pubsub.class, Mockito.RETURNS_DEEP_STUBS); + client = new PubsubApiaryClient(TIMESTAMP_LABEL, ID_LABEL, mockPubsub); + } + + @After + public void teardown() throws IOException { + client.close(); + client = null; + mockPubsub = null; + } + + @Test + public void pullOneMessage() throws IOException { + String expectedSubscription = SUBSCRIPTION.getPath(); + PullRequest expectedRequest = + new PullRequest().setReturnImmediately(true).setMaxMessages(10); + PubsubMessage expectedPubsubMessage = new PubsubMessage() + .setMessageId(MESSAGE_ID) + .encodeData(DATA.getBytes()) + .setPublishTime(String.valueOf(PUB_TIME)) + .setAttributes( + ImmutableMap.of(TIMESTAMP_LABEL, String.valueOf(MESSAGE_TIME), + ID_LABEL, RECORD_ID)); + ReceivedMessage expectedReceivedMessage = + new ReceivedMessage().setMessage(expectedPubsubMessage) + .setAckId(ACK_ID); + PullResponse expectedResponse = + new PullResponse().setReceivedMessages(ImmutableList.of(expectedReceivedMessage)); + Mockito.when(mockPubsub.projects() + .subscriptions() + .pull(expectedSubscription, expectedRequest) + .execute()) + .thenReturn(expectedResponse); + List acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true); + assertEquals(1, acutalMessages.size()); + IncomingMessage actualMessage = acutalMessages.get(0); + assertEquals(ACK_ID, actualMessage.ackId); + assertEquals(DATA, new String(actualMessage.elementBytes)); + assertEquals(RECORD_ID, actualMessage.recordId); + assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch); + assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch); + } + + @Test + public void publishOneMessage() throws IOException { + String expectedTopic = TOPIC.getPath(); + PubsubMessage expectedPubsubMessage = new PubsubMessage() + .encodeData(DATA.getBytes()) + .setAttributes( + ImmutableMap.of(TIMESTAMP_LABEL, String.valueOf(MESSAGE_TIME), + ID_LABEL, RECORD_ID)); + PublishRequest expectedRequest = new PublishRequest() + .setMessages(ImmutableList.of(expectedPubsubMessage)); + PublishResponse expectedResponse = new PublishResponse() + .setMessageIds(ImmutableList.of(MESSAGE_ID)); + Mockito.when(mockPubsub.projects() + .topics() + .publish(expectedTopic, expectedRequest) + .execute()) + .thenReturn(expectedResponse); + OutgoingMessage actualMessage = new OutgoingMessage(DATA.getBytes(), MESSAGE_TIME, RECORD_ID); + int n = client.publish(TOPIC, ImmutableList.of(actualMessage)); + assertEquals(1, n); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java new file mode 100644 index 0000000000..44ed022f36 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java @@ -0,0 +1,187 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.junit.Assert.assertEquals; + +import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; + +import com.google.common.collect.ImmutableMap; + +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Map; + +/** + * Tests for helper classes and methods in PubsubClient. + */ +public class PubsubClientTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + // + // Timestamp handling + // + + private long parse(String timestamp) { + Map map = ImmutableMap.of("myLabel", timestamp); + return PubsubClient.extractTimestamp("myLabel", null, map); + } + + private void roundTripRfc339(String timestamp) { + assertEquals(Instant.parse(timestamp).getMillis(), parse(timestamp)); + } + + private void truncatedRfc339(String timestamp, String truncatedTimestmap) { + assertEquals(Instant.parse(truncatedTimestmap).getMillis(), parse(timestamp)); + } + + @Test + public void noTimestampLabelReturnsPubsubPublish() { + final long time = 987654321L; + long timestamp = PubsubClient.extractTimestamp(null, String.valueOf(time), null); + assertEquals(time, timestamp); + } + + @Test + public void noTimestampLabelAndInvalidPubsubPublishThrowsError() { + thrown.expect(NumberFormatException.class); + PubsubClient.extractTimestamp(null, "not-a-date", null); + } + + @Test + public void timestampLabelWithNullAttributesThrowsError() { + thrown.expect(RuntimeException.class); + thrown.expectMessage("PubSub message is missing a value for timestamp label myLabel"); + PubsubClient.extractTimestamp("myLabel", null, null); + } + + @Test + public void timestampLabelSetWithMissingAttributeThrowsError() { + thrown.expect(RuntimeException.class); + thrown.expectMessage("PubSub message is missing a value for timestamp label myLabel"); + Map map = ImmutableMap.of("otherLabel", "whatever"); + PubsubClient.extractTimestamp("myLabel", null, map); + } + + @Test + public void timestampLabelParsesMillisecondsSinceEpoch() { + long time = 1446162101123L; + Map map = ImmutableMap.of("myLabel", String.valueOf(time)); + long timestamp = PubsubClient.extractTimestamp("myLabel", null, map); + assertEquals(time, timestamp); + } + + @Test + public void timestampLabelParsesRfc3339Seconds() { + roundTripRfc339("2015-10-29T23:41:41Z"); + } + + @Test + public void timestampLabelParsesRfc3339Tenths() { + roundTripRfc339("2015-10-29T23:41:41.1Z"); + } + + @Test + public void timestampLabelParsesRfc3339Hundredths() { + roundTripRfc339("2015-10-29T23:41:41.12Z"); + } + + @Test + public void timestampLabelParsesRfc3339Millis() { + roundTripRfc339("2015-10-29T23:41:41.123Z"); + } + + @Test + public void timestampLabelParsesRfc3339Micros() { + // Note: micros part 456/1000 is dropped. + truncatedRfc339("2015-10-29T23:41:41.123456Z", "2015-10-29T23:41:41.123Z"); + } + + @Test + public void timestampLabelParsesRfc3339MicrosRounding() { + // Note: micros part 999/1000 is dropped, not rounded up. + truncatedRfc339("2015-10-29T23:41:41.123999Z", "2015-10-29T23:41:41.123Z"); + } + + @Test + public void timestampLabelWithInvalidFormatThrowsError() { + thrown.expect(NumberFormatException.class); + parse("not-a-timestamp"); + } + + @Test + public void timestampLabelWithInvalidFormat2ThrowsError() { + thrown.expect(NumberFormatException.class); + parse("null"); + } + + @Test + public void timestampLabelWithInvalidFormat3ThrowsError() { + thrown.expect(NumberFormatException.class); + parse("2015-10"); + } + + @Test + public void timestampLabelParsesRfc3339WithSmallYear() { + // Google and JodaTime agree on dates after 1582-10-15, when the Gregorian Calendar was adopted + // This is therefore a "small year" until this difference is reconciled. + roundTripRfc339("1582-10-15T01:23:45.123Z"); + } + + @Test + public void timestampLabelParsesRfc3339WithLargeYear() { + // Year 9999 in range. + roundTripRfc339("9999-10-29T23:41:41.123999Z"); + } + + @Test + public void timestampLabelRfc3339WithTooLargeYearThrowsError() { + thrown.expect(NumberFormatException.class); + // Year 10000 out of range. + parse("10000-10-29T23:41:41.123999Z"); + } + + // + // Paths + // + + @Test + public void projectPathFromIdWellFormed() { + ProjectPath path = PubsubClient.projectPathFromId("test"); + assertEquals("projects/test", path.getPath()); + } + + @Test + public void subscriptionPathFromNameWellFormed() { + SubscriptionPath path = PubsubClient.subscriptionPathFromName("test", "something"); + assertEquals("projects/test/subscriptions/something", path.getPath()); + assertEquals("/subscriptions/test/something", path.getV1Beta1Path()); + } + + @Test + public void topicPathFromNameWellFormed() { + TopicPath path = PubsubClient.topicPathFromName("test", "something"); + assertEquals("projects/test/topics/something", path.getPath()); + assertEquals("/topics/test/something", path.getV1Beta1Path()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java new file mode 100644 index 0000000000..3ca2f8586d --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java @@ -0,0 +1,167 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.junit.Assert.assertEquals; + +import com.google.auth.oauth2.GoogleCredentials; + +import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.PublisherGrpc; +import com.google.pubsub.v1.PubsubMessage; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.ReceivedMessage; +import com.google.pubsub.v1.SubscriberGrpc; + +import io.grpc.ManagedChannel; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import java.io.IOException; +import java.util.List; + +/** + * Tests for PubsubGrpcClient. + */ +public class PubsubGrpcClientTest { + private ManagedChannel mockChannel; + private GoogleCredentials mockCredentials; + private PublisherGrpc.PublisherBlockingStub mockPublisherStub; + private SubscriberGrpc.SubscriberBlockingStub mockSubscriberStub; + + private PubsubClient client; + + private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); + private static final SubscriptionPath SUBSCRIPTION = + PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); + private static final long REQ_TIME = 1234L; + private static final long PUB_TIME = 3456L; + private static final long MESSAGE_TIME = 6789L; + private static final String TIMESTAMP_LABEL = "timestamp"; + private static final String ID_LABEL = "id"; + private static final String MESSAGE_ID = "testMessageId"; + private static final String DATA = "testData"; + private static final String RECORD_ID = "testRecordId"; + private static final String ACK_ID = "testAckId"; + + @Before + public void setup() throws IOException { + mockChannel = Mockito.mock(ManagedChannel.class); + mockCredentials = Mockito.mock(GoogleCredentials.class); + mockPublisherStub = + Mockito.mock(PublisherGrpc.PublisherBlockingStub.class, Mockito.RETURNS_DEEP_STUBS); + mockSubscriberStub = + Mockito.mock(SubscriberGrpc.SubscriberBlockingStub.class, Mockito.RETURNS_DEEP_STUBS); + client = new PubsubGrpcClient(TIMESTAMP_LABEL, ID_LABEL, 0, mockChannel, + mockCredentials, mockPublisherStub, mockSubscriberStub); + } + + @After + public void teardown() throws IOException { + client.close(); + client = null; + mockChannel = null; + mockCredentials = null; + mockPublisherStub = null; + mockSubscriberStub = null; + } + + @Test + public void pullOneMessage() throws IOException { + String expectedSubscription = SUBSCRIPTION.getPath(); + PullRequest expectedRequest = + PullRequest.newBuilder() + .setSubscription(expectedSubscription) + .setReturnImmediately(true) + .setMaxMessages(10) + .build(); + Timestamp timestamp = Timestamp.newBuilder() + .setSeconds(PUB_TIME / 1000) + .setNanos((int) (PUB_TIME % 1000) * 1000) + .build(); + PubsubMessage expectedPubsubMessage = + PubsubMessage.newBuilder() + .setMessageId(MESSAGE_ID) + .setData( + ByteString.copyFrom(DATA.getBytes())) + .setPublishTime(timestamp) + .putAllAttributes( + ImmutableMap.of(TIMESTAMP_LABEL, + String.valueOf(MESSAGE_TIME), + ID_LABEL, RECORD_ID)) + .build(); + ReceivedMessage expectedReceivedMessage = + ReceivedMessage.newBuilder() + .setMessage(expectedPubsubMessage) + .setAckId(ACK_ID) + .build(); + PullResponse expectedResponse = + PullResponse.newBuilder() + .addAllReceivedMessages(ImmutableList.of(expectedReceivedMessage)) + .build(); + Mockito.when(mockSubscriberStub.pull(expectedRequest)) + .thenReturn(expectedResponse); + List acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true); + assertEquals(1, acutalMessages.size()); + IncomingMessage actualMessage = acutalMessages.get(0); + assertEquals(ACK_ID, actualMessage.ackId); + assertEquals(DATA, new String(actualMessage.elementBytes)); + assertEquals(RECORD_ID, actualMessage.recordId); + assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch); + assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch); + } + + @Test + public void publishOneMessage() throws IOException { + String expectedTopic = TOPIC.getPath(); + PubsubMessage expectedPubsubMessage = + PubsubMessage.newBuilder() + .setData(ByteString.copyFrom(DATA.getBytes())) + .putAllAttributes( + ImmutableMap.of(TIMESTAMP_LABEL, String.valueOf(MESSAGE_TIME), + ID_LABEL, RECORD_ID)) + .build(); + PublishRequest expectedRequest = + PublishRequest.newBuilder() + .setTopic(expectedTopic) + .addAllMessages( + ImmutableList.of(expectedPubsubMessage)) + .build(); + PublishResponse expectedResponse = + PublishResponse.newBuilder() + .addAllMessageIds(ImmutableList.of(MESSAGE_ID)) + .build(); + Mockito.when(mockPublisherStub.publish(expectedRequest)) + .thenReturn(expectedResponse); + OutgoingMessage actualMessage = new OutgoingMessage(DATA.getBytes(), MESSAGE_TIME, RECORD_ID); + int n = client.publish(TOPIC, ImmutableList.of(actualMessage)); + assertEquals(1, n); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java new file mode 100644 index 0000000000..82e03dc804 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.junit.Assert.assertEquals; + +import com.google.api.client.util.Clock; + +import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; +import com.google.cloud.dataflow.sdk.util.PubsubTestClient.PubsubTestClientFactory; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import org.junit.Test; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Tests for PubsubTestClient. + */ +public class PubsubTestClientTest { + private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); + private static final SubscriptionPath SUBSCRIPTION = + PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); + private static final long REQ_TIME = 1234L; + private static final long MESSAGE_TIME = 6789L; + private static final String MESSAGE_ID = "testMessageId"; + private static final String DATA = "testData"; + private static final String ACK_ID = "testAckId"; + private static final int ACK_TIMEOUT_S = 60; + + @Test + public void pullOneMessage() throws IOException { + final AtomicLong now = new AtomicLong(); + Clock clock = new Clock() { + @Override + public long currentTimeMillis() { + return now.get(); + } + }; + IncomingMessage expectedIncomingMessage = + new IncomingMessage(DATA.getBytes(), MESSAGE_TIME, REQ_TIME, ACK_ID, MESSAGE_ID); + try (PubsubTestClientFactory factory = + PubsubTestClient.createFactoryForPull(clock, SUBSCRIPTION, ACK_TIMEOUT_S, + Lists.newArrayList(expectedIncomingMessage))) { + try (PubsubTestClient client = (PubsubTestClient) factory.newClient(null, null, null)) { + now.set(REQ_TIME); + client.advance(); + List incomingMessages = client.pull(now.get(), SUBSCRIPTION, 1, true); + assertEquals(1, incomingMessages.size()); + assertEquals(expectedIncomingMessage, incomingMessages.get(0)); + // Timeout on ACK. + now.addAndGet((ACK_TIMEOUT_S + 10) * 1000); + client.advance(); + incomingMessages = client.pull(now.get(), SUBSCRIPTION, 1, true); + assertEquals(1, incomingMessages.size()); + assertEquals(expectedIncomingMessage.withRequestTime(now.get()), incomingMessages.get(0)); + now.addAndGet(10 * 1000); + client.advance(); + // Extend ack + client.modifyAckDeadline(SUBSCRIPTION, ImmutableList.of(ACK_ID), 20); + // Timeout on extended ACK + now.addAndGet(30 * 1000); + client.advance(); + incomingMessages = client.pull(now.get(), SUBSCRIPTION, 1, true); + assertEquals(1, incomingMessages.size()); + assertEquals(expectedIncomingMessage.withRequestTime(now.get()), incomingMessages.get(0)); + // Extend ack + client.modifyAckDeadline(SUBSCRIPTION, ImmutableList.of(ACK_ID), 20); + // Ack + now.addAndGet(15 * 1000); + client.advance(); + client.acknowledge(SUBSCRIPTION, ImmutableList.of(ACK_ID)); + } + } + } + + @Test + public void publishOneMessage() throws IOException { + OutgoingMessage expectedOutgoingMessage = + new OutgoingMessage(DATA.getBytes(), MESSAGE_TIME, MESSAGE_ID); + try (PubsubTestClientFactory factory = + PubsubTestClient.createFactoryForPublish( + TOPIC, + Sets.newHashSet(expectedOutgoingMessage), + ImmutableList.of())) { + try (PubsubTestClient client = (PubsubTestClient) factory.newClient(null, null, null)) { + client.publish(TOPIC, ImmutableList.of(expectedOutgoingMessage)); + } + } + } +} From 2e21aa4a79512d2057b812fbd03b386063d1a6c3 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 20 May 2016 13:43:10 -0700 Subject: [PATCH 425/751] Remove CustomSourcesTest The paths tested by this test are exercised in existing tests marked RunnableOnService, which have real sources. --- .../runners/dataflow/CustomSourcesTest.java | 273 ------------------ 1 file changed, 273 deletions(-) delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java deleted file mode 100644 index e09251b6a9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSourcesTest.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Sample; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Preconditions; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for {@link CustomSources}. - */ -@RunWith(JUnit4.class) -public class CustomSourcesTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Rule public ExpectedLogs logged = ExpectedLogs.none(CustomSources.class); - - static class TestIO { - public static Read fromRange(int from, int to) { - return new Read(from, to, false); - } - - static class Read extends BoundedSource { - final int from; - final int to; - final boolean produceTimestamps; - - Read(int from, int to, boolean produceTimestamps) { - this.from = from; - this.to = to; - this.produceTimestamps = produceTimestamps; - } - - public Read withTimestampsMillis() { - return new Read(from, to, true); - } - - @Override - public List splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) - throws Exception { - List res = new ArrayList<>(); - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - float step = 1.0f * (to - from) / dataflowOptions.getNumWorkers(); - for (int i = 0; i < dataflowOptions.getNumWorkers(); ++i) { - res.add(new Read( - Math.round(from + i * step), Math.round(from + (i + 1) * step), - produceTimestamps)); - } - return res; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return 8 * (to - from); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return true; - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return new RangeReader(this); - } - - @Override - public void validate() {} - - @Override - public String toString() { - return "[" + from + ", " + to + ")"; - } - - @Override - public Coder getDefaultOutputCoder() { - return BigEndianIntegerCoder.of(); - } - - private static class RangeReader extends BoundedReader { - // To verify that BasicSerializableSourceFormat calls our methods according to protocol. - enum State { - UNSTARTED, - STARTED, - FINISHED - } - private Read source; - private int current = -1; - private State state = State.UNSTARTED; - - public RangeReader(Read source) { - this.source = source; - } - - @Override - public boolean start() throws IOException { - Preconditions.checkState(state == State.UNSTARTED); - state = State.STARTED; - current = source.from; - return (current < source.to); - } - - @Override - public boolean advance() throws IOException { - Preconditions.checkState(state == State.STARTED); - if (current == source.to - 1) { - state = State.FINISHED; - return false; - } - current++; - return true; - } - - @Override - public Integer getCurrent() { - Preconditions.checkState(state == State.STARTED); - return current; - } - - @Override - public Instant getCurrentTimestamp() { - return source.produceTimestamps - ? new Instant(current /* as millis */) : BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - @Override - public void close() throws IOException { - Preconditions.checkState(state == State.STARTED || state == State.FINISHED); - state = State.FINISHED; - } - - @Override - public Read getCurrentSource() { - return source; - } - - @Override - public Read splitAtFraction(double fraction) { - int proposedIndex = (int) (source.from + fraction * (source.to - source.from)); - if (proposedIndex <= current) { - return null; - } - Read primary = new Read(source.from, proposedIndex, source.produceTimestamps); - Read residual = new Read(proposedIndex, source.to, source.produceTimestamps); - this.source = primary; - return residual; - } - - @Override - public Double getFractionConsumed() { - return (current == -1) - ? 0.0 - : (1.0 * (1 + current - source.from) / (source.to - source.from)); - } - } - } - } - - @Test - public void testDirectPipelineWithoutTimestamps() throws Exception { - Pipeline p = TestPipeline.create(); - PCollection sum = p - .apply(Read.from(TestIO.fromRange(10, 20))) - .apply(Sum.integersGlobally()) - .apply(Sample.any(1)); - - DataflowAssert.thatSingleton(sum).isEqualTo(145); - p.run(); - } - - @Test - public void testDirectPipelineWithTimestamps() throws Exception { - Pipeline p = TestPipeline.create(); - PCollection sums = - p.apply(Read.from(TestIO.fromRange(10, 20).withTimestampsMillis())) - .apply(Window.into(FixedWindows.of(Duration.millis(3)))) - .apply(Sum.integersGlobally().withoutDefaults()); - // Should group into [10 11] [12 13 14] [15 16 17] [18 19]. - DataflowAssert.that(sums).containsInAnyOrder(21, 37, 39, 48); - p.run(); - } - - @Test - public void testRangeProgressAndSplitAtFraction() throws Exception { - // Show basic usage of getFractionConsumed and splitAtFraction. - // This test only tests TestIO itself, not BasicSerializableSourceFormat. - - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - TestIO.Read source = TestIO.fromRange(10, 20); - try (BoundedSource.BoundedReader reader = source.createReader(options)) { - assertEquals(0, reader.getFractionConsumed().intValue()); - assertTrue(reader.start()); - assertEquals(0.1, reader.getFractionConsumed(), 1e-6); - assertTrue(reader.advance()); - assertEquals(0.2, reader.getFractionConsumed(), 1e-6); - // Already past 0.0 and 0.1. - assertNull(reader.splitAtFraction(0.0)); - assertNull(reader.splitAtFraction(0.1)); - - { - TestIO.Read residual = (TestIO.Read) reader.splitAtFraction(0.5); - assertNotNull(residual); - TestIO.Read primary = (TestIO.Read) reader.getCurrentSource(); - assertThat(readFromSource(primary, options), contains(10, 11, 12, 13, 14)); - assertThat(readFromSource(residual, options), contains(15, 16, 17, 18, 19)); - } - - // Range is now [10, 15) and we are at 12. - { - TestIO.Read residual = (TestIO.Read) reader.splitAtFraction(0.8); // give up 14. - assertNotNull(residual); - TestIO.Read primary = (TestIO.Read) reader.getCurrentSource(); - assertThat(readFromSource(primary, options), contains(10, 11, 12, 13)); - assertThat(readFromSource(residual, options), contains(14)); - } - - assertTrue(reader.advance()); - assertEquals(12, reader.getCurrent().intValue()); - assertTrue(reader.advance()); - assertEquals(13, reader.getCurrent().intValue()); - assertFalse(reader.advance()); - } - } -} From ce2ba6fe3bd2e0ebf8da352e1dbabd531afdec28 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 19 May 2016 09:17:37 -0700 Subject: [PATCH 426/751] Fix bug in PipelineOptions DisplayData serialization PipelineOptions has been improved to generate display data to be consumed by a runner and used for display. However, there was a bug in the ProxyInvocationHandler implementation of PipelineOptions display data which was causing NullPointerExceptions when generated display data from PipelineOptions previously deserialized from JSON. This change also makes our error handling for display data exceptions consistent across the Dataflow runner: exceptions thrown during display data population will propogate out and cause the pipeline to fail. This is consistent with other user code which may throw exceptions at pipeline construction time. (cherry picked from commit 1e669c44c9d2448b55f5bdba3dcff1831b2cd8b4) --- .../sdk/options/ProxyInvocationHandler.java | 4 +- .../runners/DataflowPipelineTranslator.java | 49 +--------- .../sdk/transforms/display/DisplayData.java | 14 ++- .../options/ProxyInvocationHandlerTest.java | 6 +- .../DataflowPipelineTranslatorTest.java | 64 ------------- .../transforms/display/DisplayDataTest.java | 93 +++++++++++++------ 6 files changed, 84 insertions(+), 146 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index 170db0b1f7..f353ab3af0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -351,6 +351,7 @@ private void populateDisplayData(DisplayData.Builder builder) { } Object value = getValueFromJson(jsonOption.getKey(), spec.getGetterMethod()); + value = value == null ? "" : value; DisplayData.Type type = DisplayData.inferType(value); if (type != null) { builder.add(DisplayData.item(jsonOption.getKey(), type, value) @@ -588,7 +589,8 @@ public void serialize(PipelineOptions value, JsonGenerator jgen, SerializerProvi jgen.writeObject(serializableOptions); List> serializedDisplayData = Lists.newArrayList(); - for (DisplayData.Item item : DisplayData.from(value).items()) { + DisplayData displayData = DisplayData.from(value); + for (DisplayData.Item item : displayData.items()) { @SuppressWarnings("unchecked") Map serializedItem = MAPPER.convertValue(item, Map.class); serializedDisplayData.add(serializedItem); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 28392a48da..aa9f182f19 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -86,8 +86,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -728,18 +726,7 @@ private void addOutput(String name, PValue value, Coder valueCoder) { } private void addDisplayData(String stepName, HasDisplayData hasDisplayData) { - DisplayData displayData; - try { - displayData = DisplayData.from(hasDisplayData); - } catch (Exception e) { - String msg = String.format("Exception thrown while collecting display data for step: %s. " - + "Display data will be not be available for this step.", stepName); - DisplayDataException displayDataException = new DisplayDataException(msg, e); - LOG.warn(msg, displayDataException); - - displayData = displayDataException.asDisplayData(); - } - + DisplayData displayData = DisplayData.from(hasDisplayData); List> list = MAPPER.convertValue(displayData, List.class); addList(getProperties(), PropertyNames.DISPLAY_DATA, list); } @@ -1097,38 +1084,4 @@ private static void translateOutputs( context.addOutput(tag.getId(), output); } } - - /** - * Wraps exceptions thrown while collecting {@link DisplayData} for the Dataflow pipeline runner. - */ - static class DisplayDataException extends Exception implements HasDisplayData { - public DisplayDataException(String message, Throwable cause) { - super(checkNotNull(message), checkNotNull(cause)); - } - - /** - * Retrieve a display data representation of the exception, which can be submitted to - * the service in place of the actual display data. - */ - public DisplayData asDisplayData() { - return DisplayData.from(this); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - Throwable cause = getCause(); - builder - .add(DisplayData.item("exceptionMessage", getMessage())) - .add(DisplayData.item("exceptionType", cause.getClass())) - .add(DisplayData.item("exceptionCause", cause.getMessage())) - .add(DisplayData.item("stackTrace", stackTraceToString())); - } - - private String stackTraceToString() { - StringWriter stringWriter = new StringWriter(); - PrintWriter printWriter = new PrintWriter(stringWriter); - printStackTrace(printWriter); - return stringWriter.toString(); - } - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 05485e4f7a..07a0ae84fe 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -69,10 +69,6 @@ public static DisplayData none() { * Collect the {@link DisplayData} from a component. This will traverse all subcomponents * specified via {@link Builder#include} in the given component. Data in this component will be in * a namespace derived from the component. - * - *

          Pipeline runners should call this method in order to collect display data. While it should - * be safe to call {@code DisplayData.from} on any component which implements it, runners should - * be resilient to exceptions thrown while collecting display data. */ public static DisplayData from(HasDisplayData component) { checkNotNull(component, "component argument cannot be null"); @@ -655,7 +651,15 @@ public Builder include(HasDisplayData subComponent, String namespace) { if (newComponent) { String prevNs = this.latestNs; this.latestNs = namespace; - subComponent.populateDisplayData(this); + + try { + subComponent.populateDisplayData(this); + } catch (Throwable e) { + String msg = String.format("Error while populating display data for component: %s", + namespace); + throw new RuntimeException(msg, e); + } + this.latestNs = prevNs; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java index 017bcf37e5..a77b329616 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java @@ -862,12 +862,16 @@ public void testDisplayDataIncludesExplicitlySetDefaults() { } @Test - public void testDisplayDataNullValuesConvertedToEmptyString() { + public void testDisplayDataNullValuesConvertedToEmptyString() throws Exception { FooOptions options = PipelineOptionsFactory.as(FooOptions.class); options.setFoo(null); DisplayData data = DisplayData.from(options); assertThat(data, hasDisplayItem("foo", "")); + + FooOptions deserializedOptions = serializeDeserialize(FooOptions.class, options); + DisplayData deserializedData = DisplayData.from(deserializedOptions); + assertThat(deserializedData, hasDisplayItem("foo", "")); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index d28bcdf815..9b2218340c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -22,9 +22,7 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -52,7 +50,6 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -77,7 +74,6 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -103,9 +99,7 @@ */ @RunWith(JUnit4.class) public class DataflowPipelineTranslatorTest implements Serializable { - @Rule public transient ExpectedException thrown = ExpectedException.none(); - @Rule public transient ExpectedLogs logs = ExpectedLogs.none(DataflowPipelineTranslator.class); // A Custom Mockito matcher for an initial Job that checks that all // expected fields are set. @@ -914,62 +908,4 @@ public void populateDisplayData(DisplayData.Builder builder) { assertEquals(expectedFn1DisplayData, ImmutableSet.copyOf(fn1displayData)); assertEquals(expectedFn2DisplayData, ImmutableSet.copyOf(fn2displayData)); } - - @Test - public void testCapturesDisplayDataExceptions() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setRunner(DataflowPipelineRunner.class); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - Pipeline pipeline = Pipeline.create(options); - - final RuntimeException displayDataException = new RuntimeException("foobar"); - pipeline - .apply(Create.of(1, 2, 3)) - .apply(ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - throw displayDataException; - } - })); - - Job job = translator.translate( - pipeline, - (DataflowPipelineRunner) pipeline.getRunner(), - Collections.emptyList()).getJob(); - - String expectedMessage = "Display data will be not be available for this step"; - logs.verifyWarn(expectedMessage); - - List steps = job.getSteps(); - assertEquals("Job should have 2 steps", 2, steps.size()); - - @SuppressWarnings("unchecked") - Iterable> displayData = (Collection>) steps.get(1) - .getProperties().get("display_data"); - - String namespace = DataflowPipelineTranslator.DisplayDataException.class.getName(); - Assert.assertThat(displayData, Matchers.>hasItem(allOf( - hasEntry("namespace", namespace), - hasEntry("key", "exceptionType"), - hasEntry("value", RuntimeException.class.getName())))); - - Assert.assertThat(displayData, Matchers.>hasItem(allOf( - hasEntry("namespace", namespace), - hasEntry("key", "exceptionMessage"), - hasEntry(is("value"), Matchers.containsString(expectedMessage))))); - - Assert.assertThat(displayData, Matchers.>hasItem(allOf( - hasEntry("namespace", namespace), - hasEntry("key", "exceptionCause"), - hasEntry("value", "foobar")))); - - Assert.assertThat(displayData, Matchers.>hasItem(allOf( - hasEntry("namespace", namespace), - hasEntry("key", "stackTrace")))); - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index 4adbb33fb6..1114c91a3a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -29,6 +29,7 @@ import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; @@ -38,11 +39,6 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; @@ -53,9 +49,9 @@ import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.testing.EqualsTester; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; - import org.hamcrest.CustomTypeSafeMatcher; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; @@ -66,7 +62,6 @@ import org.joda.time.format.ISODateTimeFormat; import org.junit.Rule; import org.junit.Test; -import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -83,6 +78,7 @@ @RunWith(JUnit4.class) public class DisplayDataTest implements Serializable { @Rule public transient ExpectedException thrown = ExpectedException.none(); + private static final DateTimeFormatter ISO_FORMATTER = ISODateTimeFormat.dateTime(); private static final ObjectMapper MAPPER = new ObjectMapper(); @@ -410,7 +406,7 @@ public void populateDisplayData(Builder builder) { @Test public void testNullNamespaceOverride() { - thrown.expect(NullPointerException.class); + thrown.expectCause(isA(NullPointerException.class)); DisplayData.from(new HasDisplayData() { @Override @@ -513,7 +509,7 @@ public void populateDisplayData(DisplayData.Builder builder) { @Test public void testDuplicateKeyThrowsException() { - thrown.expect(IllegalArgumentException.class); + thrown.expectCause(isA(IllegalArgumentException.class)); DisplayData.from( new HasDisplayData() { @Override @@ -749,7 +745,7 @@ public void populateDisplayData(Builder builder) { } }; - thrown.expect(ClassCastException.class); + thrown.expectCause(isA(ClassCastException.class)); DisplayData.from(component); } @@ -835,7 +831,7 @@ public void testFromNull() { @Test public void testIncludeNull() { - thrown.expect(NullPointerException.class); + thrown.expectCause(isA(NullPointerException.class)); DisplayData.from( new HasDisplayData() { @Override @@ -853,7 +849,7 @@ public void populateDisplayData(Builder builder) { } }; - thrown.expect(NullPointerException.class); + thrown.expectCause(isA(NullPointerException.class)); DisplayData.from(new HasDisplayData() { @Override public void populateDisplayData(Builder builder) { @@ -864,7 +860,7 @@ public void populateDisplayData(Builder builder) { @Test public void testNullKey() { - thrown.expect(NullPointerException.class); + thrown.expectCause(isA(NullPointerException.class)); DisplayData.from( new HasDisplayData() { @Override @@ -965,23 +961,66 @@ public void populateDisplayData(Builder builder) { } /** - * Validate that all runners are resilient to exceptions thrown while retrieving display data. + * Verify that {@link DisplayData.Builder} can recover from exceptions thrown in user code. + * This is not used within the Beam SDK since we want all code to produce valid DisplayData. + * This test just ensures it is possible to write custom code that does recover. */ @Test - @Category(RunnableOnService.class) - public void testRunnersResilientToDisplayDataExceptions() { - Pipeline p = TestPipeline.create(); - PCollection pCol = p - .apply(Create.of(1, 2, 3)) - .apply(new IdentityTransform() { - @Override - public void populateDisplayData(Builder builder) { - throw new RuntimeException("bug!"); - } - }); + public void testCanRecoverFromBuildException() { + final HasDisplayData safeComponent = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.add(DisplayData.item("a", "a")); + } + }; + + final HasDisplayData failingComponent = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + throw new RuntimeException("oh noes!"); + } + }; - DataflowAssert.that(pCol).containsInAnyOrder(1, 2, 3); - p.run(); + DisplayData displayData = DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder + .add(DisplayData.item("b", "b")) + .add(DisplayData.item("c", "c")); + + try { + builder.include(failingComponent); + fail("Expected exception not thrown"); + } catch (RuntimeException e) { + // Expected + } + + builder + .include(safeComponent) + .add(DisplayData.item("d", "d")); + } + }); + + assertThat(displayData, hasDisplayItem("a")); + assertThat(displayData, hasDisplayItem("b")); + assertThat(displayData, hasDisplayItem("c")); + assertThat(displayData, hasDisplayItem("d")); + } + + @Test + public void testExceptionMessage() { + final RuntimeException cause = new RuntimeException("oh noes!"); + HasDisplayData component = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + throw cause; + } + }; + + thrown.expectMessage(component.getClass().getName()); + thrown.expectCause(is(cause)); + + DisplayData.from(component); } private static class IdentityTransform extends PTransform, PCollection> { From 230fe208cf5f8c15550d914ab5b6e8e409ca7c07 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Fri, 20 May 2016 17:32:30 -0700 Subject: [PATCH 427/751] BoundedReader: add getSplitPoints{Consumed,Remaining} (#257) * BoundedReader: add getParallelism{Consumed,Remaining} And implement it for common sources * OffsetBasedReader: test limited parallelism signals * AvroSource: rewrite to support remaining parallelism *) Make the start of a block match Avro's definition: the first byte after the previous sync marker. This enables detecting the last block in the file. *) This change enables us to unify currentOffset and currentBlockOffset, as all records are emitted at the start of the block that contains them. *) Simplify block header reading to have fewer object allocations and buffers using a direct reader and a (allocated once only) CountingInputStream to measure the size of that header. *) Add tests for consumed and remaining parallelism *) Let BlockBasedSource detect the end of the file in remaining parallelism. *) Verify in more places that the correct number of bytes is read from the input Avro file. * CompressedSource: add tests of parallelism and progress *) empty file *) non-empty compressed file *) non-empty not-compressed file * TextIO: implement and test parallelism *) empty file *) non-empty file * CountingSource: test limited parallelism * CompressedSource: implement currentOffset based on bytes decompressed This is not a very good offset because it is an upper bound, but it is likely better than not reporting any progress at all. --- .../contrib/hadoop/HadoopFileSource.java | 12 ++ .../cloud/dataflow/sdk/io/AvroSource.java | 166 ++++++++++++------ .../dataflow/sdk/io/BlockBasedSource.java | 26 +-- .../cloud/dataflow/sdk/io/BoundedSource.java | 145 ++++++++++++++- .../dataflow/sdk/io/CompressedSource.java | 132 ++++++++++++-- .../cloud/dataflow/sdk/io/CountingSource.java | 5 + .../cloud/dataflow/sdk/io/DatastoreIO.java | 13 ++ .../dataflow/sdk/io/FileBasedSource.java | 2 +- .../dataflow/sdk/io/OffsetBasedSource.java | 49 +++++- .../google/cloud/dataflow/sdk/io/TextIO.java | 20 ++- .../sdk/io/range/OffsetRangeTracker.java | 109 ++++++++++-- .../cloud/dataflow/sdk/io/AvroSourceTest.java | 85 +++++++++ .../dataflow/sdk/io/CompressedSourceTest.java | 106 ++++++++++- .../dataflow/sdk/io/CountingSourceTest.java | 30 ++++ .../dataflow/sdk/io/FileBasedSourceTest.java | 2 +- .../sdk/io/OffsetBasedSourceTest.java | 70 +++++++- .../cloud/dataflow/sdk/io/TextIOTest.java | 113 ++++++++++++ .../sdk/io/range/OffsetRangeTrackerTest.java | 1 - 18 files changed, 969 insertions(+), 117 deletions(-) diff --git a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java index f24c3b7bd8..dad4575061 100644 --- a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java +++ b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java @@ -281,6 +281,7 @@ static class HadoopFileReader extends BoundedSource.BoundedReader private Configuration conf; private RecordReader currentReader; private KV currentPair; + private volatile boolean done = false; /** * Create a {@code HadoopFileReader} based on a file or a file pattern specification. @@ -355,6 +356,7 @@ public boolean advance() throws IOException { } // either no next split or all readers were empty currentPair = null; + done = true; return false; } } catch (InterruptedException e) { @@ -431,6 +433,16 @@ private Double getProgress() { } } + @Override + public final long getSplitPointsRemaining() { + if (done) { + return 0; + } + // This source does not currently support dynamic work rebalancing, so remaining + // parallelism is always 1. + return 1; + } + @Override public BoundedSource> splitAtFraction(double fraction) { // Not yet supported. To implement this, the sizes of the splits should be used to diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java index 297663e96f..a27dcb4fde 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; @@ -38,18 +40,24 @@ import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.snappy.SnappyCompressorInputStream; import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; +import org.apache.commons.compress.utils.CountingInputStream; import java.io.ByteArrayInputStream; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; +import java.nio.channels.SeekableByteChannel; +import java.util.Arrays; import java.util.Collection; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; +import javax.annotation.concurrent.GuardedBy; + // CHECKSTYLE.OFF: JavadocStyle /** * A {@link FileBasedSource} for reading Avro files. @@ -437,10 +445,6 @@ public double getFractionOfBlockConsumed() { * the total number of records in the block and the block's size in bytes, followed by the * block's (optionally-encoded) records. Each block is terminated by a 16-bit sync marker. * - *

          Here, we consider the sync marker that precedes a block to be its offset, as this allows - * a reader that begins reading at that offset to detect the sync marker and the beginning of - * the block. - * * @param The type of records contained in the block. */ @Experimental(Experimental.Kind.SOURCE_SINK) @@ -448,24 +452,25 @@ public static class AvroReader extends BlockBasedReader { // The current block. private AvroBlock currentBlock; - // Offset of the block. + // A lock used to synchronize block offsets for getRemainingParallelism + private final Object progressLock = new Object(); + + // Offset of the current block. + @GuardedBy("progressLock") private long currentBlockOffset = 0; // Size of the current block. + @GuardedBy("progressLock") private long currentBlockSizeBytes = 0; - // Current offset within the stream. - private long currentOffset = 0; - // Stream used to read from the underlying file. - // A pushback stream is used to restore bytes buffered during seeking/decoding. + // A pushback stream is used to restore bytes buffered during seeking. private PushbackInputStream stream; + // Counts the number of bytes read. Used only to tell how many bytes are taken up in + // a block's variable-length header. + private CountingInputStream countStream; - // Small buffer for reading encoded values from the stream. - // The maximum size of an encoded long is 10 bytes, and this buffer will be used to read two. - private final byte[] readBuffer = new byte[20]; - - // Decoder to decode binary-encoded values from the buffer. + // Caches the Avro DirectBinaryDecoder used to decode binary-encoded values from the buffer. private BinaryDecoder decoder; /** @@ -480,51 +485,67 @@ public synchronized AvroSource getCurrentSource() { return (AvroSource) super.getCurrentSource(); } + // Precondition: the stream is positioned after the sync marker in the current (about to be + // previous) block. currentBlockSize equals the size of the current block, or zero if this + // reader was just started. + // + // Postcondition: same as above, but for the new current (formerly next) block. @Override public boolean readNextBlock() throws IOException { - // The next block in the file is after the first sync marker that can be read starting from - // the current offset. First, we seek past the next sync marker, if it exists. After a sync - // marker is the start of a block. A block begins with the number of records contained in - // the block, encoded as a long, followed by the size of the block in bytes, encoded as a - // long. The currentOffset after this method should be last byte after this block, and the - // currentBlockOffset should be the start of the sync marker before this block. - - // Seek to the next sync marker, if one exists. - currentOffset += advancePastNextSyncMarker(stream, getCurrentSource().getSyncMarker()); - - // The offset of the current block includes its preceding sync marker. - currentBlockOffset = currentOffset - getCurrentSource().getSyncMarker().length; - - // Read a small buffer to parse the block header. - // We cannot use a BinaryDecoder to do this directly from the stream because a BinaryDecoder - // internally buffers data and we only want to read as many bytes from the stream as the size - // of the header. Though BinaryDecoder#InputStream returns an input stream that is aware of - // its internal buffering, we would have to re-wrap this input stream to seek for the next - // block in the file. - int read = stream.read(readBuffer); - // We reached the last sync marker in the file. - if (read <= 0) { + long startOfNextBlock = currentBlockOffset + currentBlockSizeBytes; + + // Before reading the variable-sized block header, record the current number of bytes read. + long preHeaderCount = countStream.getBytesRead(); + decoder = DecoderFactory.get().directBinaryDecoder(countStream, decoder); + long numRecords; + try { + numRecords = decoder.readLong(); + } catch (EOFException e) { + // Expected for the last block, at which the start position is the EOF. The way to detect + // stream ending is to try reading from it. return false; } - decoder = DecoderFactory.get().binaryDecoder(readBuffer, decoder); - long numRecords = decoder.readLong(); long blockSize = decoder.readLong(); - // The decoder buffers data internally, but since we know the size of the stream the - // decoder has constructed from the readBuffer, the number of bytes available in the - // input stream is equal to the number of unconsumed bytes. - int headerSize = readBuffer.length - decoder.inputStream().available(); - stream.unread(readBuffer, headerSize, read - headerSize); + // Mark header size as the change in the number of bytes read. + long headerSize = countStream.getBytesRead() - preHeaderCount; // Create the current block by reading blockSize bytes. Block sizes permitted by the Avro // specification are [32, 2^30], so this narrowing is ok. byte[] data = new byte[(int) blockSize]; - stream.read(data); + int read = stream.read(data); + checkState(blockSize == read, "Only %s/%s bytes in the block were read", read, blockSize); currentBlock = new AvroBlock<>(data, numRecords, getCurrentSource()); - currentBlockSizeBytes = blockSize; - // Update current offset with the number of bytes we read to get the next block. - currentOffset += headerSize + blockSize; + // Read the end of this block, which MUST be a sync marker for correctness. + byte[] syncMarker = getCurrentSource().getSyncMarker(); + byte[] readSyncMarker = new byte[syncMarker.length]; + long syncMarkerOffset = startOfNextBlock + headerSize + blockSize; + long bytesRead = stream.read(readSyncMarker); + checkState( + bytesRead == syncMarker.length, + "When trying to read a sync marker at position %s, only able to read %s/%s bytes", + syncMarkerOffset, + bytesRead, + syncMarker.length); + if (!Arrays.equals(syncMarker, readSyncMarker)) { + throw new IllegalStateException( + String.format( + "Expected the bytes [%d,%d) in file %s to be a sync marker, but found %s", + syncMarkerOffset, + syncMarkerOffset + syncMarker.length, + getCurrentSource().getFileOrPatternSpec(), + Arrays.toString(readSyncMarker) + )); + } + + // Atomically update both the position and offset of the new block. + synchronized (progressLock) { + currentBlockOffset = startOfNextBlock; + // Total block size includes the header, block content, and trailing sync marker. + currentBlockSizeBytes = headerSize + blockSize + syncMarker.length; + } + return true; } @@ -535,32 +556,65 @@ public AvroBlock getCurrentBlock() { @Override public long getCurrentBlockOffset() { - return currentBlockOffset; + synchronized (progressLock) { + return currentBlockOffset; + } } @Override public long getCurrentBlockSize() { - return currentBlockSizeBytes; + synchronized (progressLock) { + return currentBlockSizeBytes; + } + } + + @Override + public long getSplitPointsRemaining() { + if (isDone()) { + return 0; + } + synchronized (progressLock) { + if (currentBlockOffset + currentBlockSizeBytes >= getCurrentSource().getEndOffset()) { + // This block is known to be the last block in the range. + return 1; + } + } + return super.getSplitPointsRemaining(); } /** * Creates a {@link PushbackInputStream} that has a large enough pushback buffer to be able - * to push back the syncBuffer and the readBuffer. + * to push back the syncBuffer. */ private PushbackInputStream createStream(ReadableByteChannel channel) { return new PushbackInputStream( Channels.newInputStream(channel), - getCurrentSource().getSyncMarker().length + readBuffer.length); + getCurrentSource().getSyncMarker().length); } - /** - * Starts reading from the provided channel. Assumes that the channel is already seeked to - * the source's start offset. - */ + // Postcondition: the stream is positioned at the beginning of the first block after the start + // of the current source, and currentBlockOffset is that position. Additionally, + // currentBlockSizeBytes will be set to 0 indicating that the previous block was empty. @Override protected void startReading(ReadableByteChannel channel) throws IOException { + long startOffset = getCurrentSource().getStartOffset(); + byte[] syncMarker = getCurrentSource().getSyncMarker(); + long syncMarkerLength = syncMarker.length; + + if (startOffset != 0) { + // Rewind order to find the sync marker ending the previous block. + long position = Math.max(0, startOffset - syncMarkerLength); + ((SeekableByteChannel) channel).position(position); + startOffset = position; + } + + // Satisfy the post condition. stream = createStream(channel); - currentOffset = getCurrentSource().getStartOffset(); + countStream = new CountingInputStream(stream); + synchronized (progressLock) { + currentBlockOffset = startOffset + advancePastNextSyncMarker(stream, syncMarker); + currentBlockSizeBytes = 0; + } } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java index f4a9c7db07..9fb9f8aac9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java @@ -205,28 +205,32 @@ protected final boolean readNextRecord() throws IOException { } @Override + @Nullable public Double getFractionConsumed() { - if (getCurrentSource().getEndOffset() == Long.MAX_VALUE) { - return null; - } - Block currentBlock = getCurrentBlock(); - if (currentBlock == null) { - // There is no current block (i.e., the read has not yet begun). + if (!isStarted()) { return 0.0; } + if (isDone()) { + return 1.0; + } + FileBasedSource source = getCurrentSource(); + if (source.getEndOffset() == Long.MAX_VALUE) { + // Unknown end offset, so we cannot tell. + return null; + } + long currentBlockOffset = getCurrentBlockOffset(); - long startOffset = getCurrentSource().getStartOffset(); - long endOffset = getCurrentSource().getEndOffset(); + long startOffset = source.getStartOffset(); + long endOffset = source.getEndOffset(); double fractionAtBlockStart = ((double) (currentBlockOffset - startOffset)) / (endOffset - startOffset); double fractionAtBlockEnd = ((double) (currentBlockOffset + getCurrentBlockSize() - startOffset) / (endOffset - startOffset)); + double blockFraction = getCurrentBlock().getFractionOfBlockConsumed(); return Math.min( 1.0, - fractionAtBlockStart - + currentBlock.getFractionOfBlockConsumed() - * (fractionAtBlockEnd - fractionAtBlockStart)); + fractionAtBlockStart + blockFraction * (fractionAtBlockEnd - fractionAtBlockStart)); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java index be3a415cff..170b56beb1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java @@ -17,6 +17,8 @@ package com.google.cloud.dataflow.sdk.io; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; +import com.google.cloud.dataflow.sdk.io.range.RangeTracker; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; @@ -26,6 +28,8 @@ import java.util.List; import java.util.NoSuchElementException; +import javax.annotation.Nullable; + /** * A {@link Source} that reads a finite amount of input and, because of that, supports * some additional operations. @@ -36,9 +40,16 @@ *

        • Size estimation: {@link #getEstimatedSizeBytes}; *
        • Telling whether or not this source produces key/value pairs in sorted order: * {@link #producesSortedKeys}; - *
        • The reader ({@link BoundedReader}) supports progress estimation - * ({@link BoundedReader#getFractionConsumed}) and dynamic splitting - * ({@link BoundedReader#splitAtFraction}). + *
        • The accompanying {@link BoundedReader reader} has additional functionality to enable runners + * to dynamically adapt based on runtime conditions. + *
            + *
          • Progress estimation ({@link BoundedReader#getFractionConsumed}) + *
          • Tracking of parallelism, to determine whether the current source can be split + * ({@link BoundedReader#getSplitPointsConsumed()} and + * {@link BoundedReader#getSplitPointsRemaining()}). + *
          • Dynamic splitting of the current source ({@link BoundedReader#splitAtFraction}). + *
          + *
        • * * *

          To use this class for supporting your custom input type, derive your class @@ -81,14 +92,14 @@ public abstract List> splitIntoBundles( * *

          Thread safety

          * All methods will be run from the same thread except {@link #splitAtFraction}, - * {@link #getFractionConsumed} and {@link #getCurrentSource}, which can be called concurrently + * {@link #getFractionConsumed}, {@link #getCurrentSource}, {@link #getSplitPointsConsumed()}, + * and {@link #getSplitPointsRemaining()}, all of which can be called concurrently * from a different thread. There will not be multiple concurrent calls to - * {@link #splitAtFraction} but there can be for {@link #getFractionConsumed} if - * {@link #splitAtFraction} is implemented. + * {@link #splitAtFraction}. * - *

          If the source does not implement {@link #splitAtFraction}, you do not need to worry about - * thread safety. If implemented, it must be safe to call {@link #splitAtFraction} and - * {@link #getFractionConsumed} concurrently with other methods. + *

          It must be safe to call {@link #splitAtFraction}, {@link #getFractionConsumed}, + * {@link #getCurrentSource}, {@link #getSplitPointsConsumed()}, and + * {@link #getSplitPointsRemaining()} concurrently with other methods. * *

          Additionally, a successful {@link #splitAtFraction} call must, by definition, cause * {@link #getCurrentSource} to start returning a different value. @@ -128,10 +139,125 @@ public abstract static class BoundedReader extends Source.Reader { * methods (including itself), and it is therefore critical for it to be implemented * in a thread-safe way. */ + @Nullable public Double getFractionConsumed() { return null; } + /** + * A constant to use as the return value for {@link #getSplitPointsConsumed()} or + * {@link #getSplitPointsRemaining()} when the exact value is unknown. + */ + public static final long SPLIT_POINTS_UNKNOWN = -1; + + /** + * Returns the total amount of parallelism in the consumed (returned and processed) range of + * this reader's current {@link BoundedSource} (as would be returned by + * {@link #getCurrentSource}). This corresponds to all split point records (see + * {@link RangeTracker}) returned by this reader, excluding the last split point + * returned if the reader is not finished. + * + *

          Consider the following examples: (1) An input that can be read in parallel down to the + * individual records, such as {@link CountingSource#upTo}, is called "perfectly splittable". + * (2) a "block-compressed" file format such as {@link AvroIO}, in which a block of records has + * to be read as a whole, but different blocks can be read in parallel. (3) An "unsplittable" + * input such as a cursor in a database. + * + *

            + *
          • Any {@link BoundedReader reader} that is unstarted (aka, has never had a call to + * {@link #start}) has a consumed parallelism of 0. This condition holds independent of whether + * the input is splittable. + *
          • Any {@link BoundedReader reader} that has only returned its first element (aka, + * has never had a call to {@link #advance}) has a consumed parallelism of 0: the first element + * is the current element and is still being processed. This condition holds independent of + * whether the input is splittable. + *
          • For an empty reader (in which the call to {@link #start} returned false), the + * consumed parallelism is 0. This condition holds independent of whether the input is + * splittable. + *
          • For a non-empty, finished reader (in which the call to {@link #start} returned true and + * a call to {@link #advance} has returned false), the value returned must be at least 1 + * and should equal the total parallelism in the source. + *
          • For example (1): After returning record #30 (starting at 1) out of 50 in a perfectly + * splittable 50-record input, this value should be 29. When finished, the consumed parallelism + * should be 50. + *
          • For example (2): In a block-compressed value consisting of 5 blocks, the value should + * stay at 0 until the first record of the second block is returned; stay at 1 until the first + * record of the third block is returned, etc. Only once the end-of-file is reached then the + * fifth block has been consumed and the value should stay at 5. + *
          • For example (3): For any non-empty unsplittable input, the consumed parallelism is 0 + * until the reader is finished (because the last call to {@link #advance} returned false, at + * which point it becomes 1. + *
          + * + *

          A reader that is implemented using a {@link RangeTracker} is encouraged to use the + * range tracker's ability to count split points to implement this method. See + * {@link OffsetBasedSource.OffsetBasedReader} and {@link OffsetRangeTracker} for an example. + * + *

          Defaults to {@link #SPLIT_POINTS_UNKNOWN}. Any value less than 0 will be interpreted + * as unknown. + * + *

          Thread safety

          + * See the javadoc on {@link BoundedReader} for information about thread safety. + * + * @see #getSplitPointsRemaining() + */ + public long getSplitPointsConsumed() { + return SPLIT_POINTS_UNKNOWN; + } + + /** + * Returns the total amount of parallelism in the unprocessed part of this reader's current + * {@link BoundedSource} (as would be returned by {@link #getCurrentSource}). This corresponds + * to all unprocessed split point records (see {@link RangeTracker}), including the last + * split point returned, in the remainder part of the source. + * + *

          This function should be implemented only in addition to + * {@link #getSplitPointsConsumed()} and only if an exact value can be + * returned. + * + *

          Consider the following examples: (1) An input that can be read in parallel down to the + * individual records, such as {@link CountingSource#upTo}, is called "perfectly splittable". + * (2) a "block-compressed" file format such as {@link AvroIO}, in which a block of records has + * to be read as a whole, but different blocks can be read in parallel. (3) An "unsplittable" + * input such as a cursor in a database. + * + *

          Assume for examples (1) and (2) that the number of records or blocks remaining is known: + * + *

            + *
          • Any {@link BoundedReader reader} for which the last call to {@link #start} or + * {@link #advance} has returned true should should not return 0, because this reader itself + * represents parallelism at least 1. This condition holds independent of whether the input is + * splittable. + *
          • A finished reader (for which {@link #start} or {@link #advance}) has returned false + * should return a value of 0. This condition holds independent of whether the input is + * splittable. + *
          • For example 1: After returning record #30 (starting at 1) out of 50 in a perfectly + * splittable 50-record input, this value should be 21 (20 remaining + 1 current) if the total + * number of records is known. + *
          • For example 2: After returning a record in block 3 in a block-compressed file + * consisting of 5 blocks, this value should be 3 (since blocks 4 and 5 can be processed in + * parallel by new readers produced via dynamic work rebalancing, while the current reader + * continues processing block 3) if the total number of blocks is known. + *
          • For example (3): a reader for any non-empty unsplittable input, should return 1 until + * it is finished, at which point it should return 0. + *
          • For any reader: After returning the last split point in a file (e.g., the last record + * in example (1), the first record in the last block for example (2), or the first record in + * the file for example (3), this value should be 1: apart from the current task, no additional + * remainder can be split off. + *
          + * + *

          Defaults to {@link #SPLIT_POINTS_UNKNOWN}. Any value less than 0 will be interpreted as + * unknown. + * + *

          Thread safety

          + * See the javadoc on {@link BoundedReader} for information about thread safety. + * + * @see #getSplitPointsConsumed() + */ + public long getSplitPointsRemaining() { + return SPLIT_POINTS_UNKNOWN; + } + /** * Returns a {@code Source} describing the same input that this {@code Reader} currently reads * (including items already read). @@ -262,6 +388,7 @@ public Double getFractionConsumed() { * *

          By default, returns null to indicate that splitting is not possible. */ + @Nullable public BoundedSource splitAtFraction(double fraction) { return null; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index be57eed11b..71fd124bc8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -30,11 +30,14 @@ import java.io.IOException; import java.io.PushbackInputStream; import java.io.Serializable; +import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.NoSuchElementException; import java.util.zip.GZIPInputStream; +import javax.annotation.concurrent.GuardedBy; + /** * A Source that reads from compressed files. A {@code CompressedSources} wraps a delegate * {@link FileBasedSource} that is able to read the decompressed file format. @@ -359,7 +362,12 @@ public static class CompressedReader extends FileBasedReader { private final FileBasedReader readerDelegate; private final CompressedSource source; + private final boolean splittable; + private final Object progressLock = new Object(); + @GuardedBy("progressLock") private int numRecordsRead; + @GuardedBy("progressLock") + private CountingChannel channel; /** * Create a {@code CompressedReader} from a {@code CompressedSource} and delegate reader. @@ -367,6 +375,13 @@ public static class CompressedReader extends FileBasedReader { public CompressedReader(CompressedSource source, FileBasedReader readerDelegate) { super(source); this.source = source; + boolean splittable; + try { + splittable = source.isSplittable(); + } catch (Exception e) { + throw new RuntimeException("Unable to tell whether source " + source + " is splittable", e); + } + this.splittable = splittable; this.readerDelegate = readerDelegate; } @@ -378,18 +393,78 @@ public T getCurrent() throws NoSuchElementException { return readerDelegate.getCurrent(); } + @Override + public final long getSplitPointsConsumed() { + if (splittable) { + return readerDelegate.getSplitPointsConsumed(); + } else { + synchronized (progressLock) { + return (isDone() && numRecordsRead > 0) ? 1 : 0; + } + } + } + + @Override + public final long getSplitPointsRemaining() { + if (splittable) { + return readerDelegate.getSplitPointsRemaining(); + } else { + return isDone() ? 0 : 1; + } + } + /** * Returns true only for the first record; compressed sources cannot be split. */ @Override protected final boolean isAtSplitPoint() { - // We have to return true for the first record, but not for the state before reading it, - // and not for the state after reading any other record. Hence == rather than >= or <=. - // This is required because FileBasedReader is intended for readers that can read a range - // of offsets in a file and where the range can be split in parts. CompressedReader, - // however, is a degenerate case because it cannot be split, but it has to satisfy the - // semantics of offsets and split points anyway. - return numRecordsRead == 1; + if (splittable) { + return readerDelegate.isAtSplitPoint(); + } else { + // We have to return true for the first record, but not for the state before reading it, + // and not for the state after reading any other record. Hence == rather than >= or <=. + // This is required because FileBasedReader is intended for readers that can read a range + // of offsets in a file and where the range can be split in parts. CompressedReader, + // however, is a degenerate case because it cannot be split, but it has to satisfy the + // semantics of offsets and split points anyway. + synchronized (progressLock) { + return numRecordsRead == 1; + } + } + } + + private static class CountingChannel implements ReadableByteChannel { + long count; + private final ReadableByteChannel inner; + + public CountingChannel(ReadableByteChannel inner, long count) { + this.inner = inner; + this.count = count; + } + + public long getCount() { + return count; + } + + @Override + public int read(ByteBuffer dst) throws IOException { + int bytes = inner.read(dst); + if (bytes > 0) { + // Avoid the -1 from EOF. + count += bytes; + } + return bytes; + } + + @Override + public boolean isOpen() { + return inner.isOpen(); + } + + @Override + public void close() throws IOException { + inner.close(); + } } /** @@ -398,6 +473,16 @@ protected final boolean isAtSplitPoint() { */ @Override protected final void startReading(ReadableByteChannel channel) throws IOException { + if (splittable) { + // No-op. We will always delegate to the inner reader, so this.channel and this.progressLock + // will never be used. + } else { + synchronized (progressLock) { + this.channel = new CountingChannel(channel, getCurrentSource().getStartOffset()); + channel = this.channel; + } + } + if (source.getChannelFactory() instanceof FileNameBasedDecompressingChannelFactory) { FileNameBasedDecompressingChannelFactory channelFactory = (FileNameBasedDecompressingChannelFactory) source.getChannelFactory(); @@ -418,16 +503,37 @@ protected final boolean readNextRecord() throws IOException { if (!readerDelegate.readNextRecord()) { return false; } - ++numRecordsRead; + synchronized (progressLock) { + ++numRecordsRead; + } return true; } - /** - * Returns the delegate reader's current offset in the decompressed input. - */ + // Splittable: simply delegates to the inner reader. + // + // Unsplittable: returns the offset in the input stream that has been read by the input. + // these positions are likely to be coarse-grained (in the event of buffering) and + // over-estimates (because they reflect the number of bytes read to produce an element, not its + // start) but both of these provide better data than e.g., reporting the start of the file. @Override - protected final long getCurrentOffset() { - return readerDelegate.getCurrentOffset(); + protected final long getCurrentOffset() throws NoSuchElementException { + if (splittable) { + return readerDelegate.getCurrentOffset(); + } else { + synchronized (progressLock) { + if (numRecordsRead <= 1) { + // Since the first record is at a split point, it should start at the beginning of the + // file. This avoids the bad case where the decompressor read the entire file, which + // would cause the file to be treated as empty when returning channel.getCount() as it + // is outside the valid range. + return 0; + } + if (channel == null) { + throw new NoSuchElementException(); + } + return channel.getCount(); + } + } } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java index 412f3a7ec9..8cca7e2179 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java @@ -197,6 +197,11 @@ protected long getCurrentOffset() throws NoSuchElementException { return current; } + @Override + public synchronized long getSplitPointsRemaining() { + return Math.max(0, getCurrentSource().getEndOffset() - current); + } + @Override public synchronized BoundedCountingSource getCurrentSource() { return (BoundedCountingSource) super.getCurrentSource(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java index 9bd54944cb..7bf763cc28 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java @@ -875,6 +875,8 @@ public static class DatastoreReader extends BoundedSource.BoundedReader */ private int userLimit; + private volatile boolean done = false; + private Entity currentEntity; /** @@ -894,6 +896,16 @@ public Entity getCurrent() { return currentEntity; } + @Override + public final long getSplitPointsConsumed() { + return done ? 1 : 0; + } + + @Override + public final long getSplitPointsRemaining() { + return done ? 0 : 1; + } + @Override public boolean start() throws IOException { return advance(); @@ -911,6 +923,7 @@ public boolean advance() throws IOException { if (entities == null || !entities.hasNext()) { currentEntity = null; + done = true; return false; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java index 7ce2b73dff..78659122de 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java @@ -473,7 +473,7 @@ public FileBasedReader(FileBasedSource source) { } @Override - public FileBasedSource getCurrentSource() { + public synchronized FileBasedSource getCurrentSource() { return (FileBasedSource) super.getCurrentSource(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java index d9f3ffcd92..8818974712 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java @@ -176,7 +176,7 @@ public long getBytesPerOffset() { * *

          As an example in which {@link OffsetBasedSource} is used to implement a file source, suppose * that this source was constructed with an {@code endOffset} of {@link Long#MAX_VALUE} to - * indicate that a file should be read to the end. Then {@link #getMaxEndOffset} should determine + * indicate that a file should be read to the end. Then this function should determine * the actual, exact size of the file in bytes and return it. */ public abstract long getMaxEndOffset(PipelineOptions options) throws Exception; @@ -226,9 +226,22 @@ public void populateDisplayData(DisplayData.Builder builder) { */ public abstract static class OffsetBasedReader extends BoundedReader { private static final Logger LOG = LoggerFactory.getLogger(OffsetBasedReader.class); - private OffsetBasedSource source; + /** + * Returns true if the last call to {@link #start} or {@link #advance} returned false. + */ + public final boolean isDone() { + return rangeTracker.isDone(); + } + + /** + * Returns true if there has been a call to {@link #start}. + */ + public final boolean isStarted() { + return rangeTracker.isStarted(); + } + /** The {@link OffsetRangeTracker} managing the range and current position of the source. */ private final OffsetRangeTracker rangeTracker; @@ -262,12 +275,14 @@ protected boolean isAtSplitPoint() throws NoSuchElementException { @Override public final boolean start() throws IOException { - return startImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint(), getCurrentOffset()); + return startImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint(), getCurrentOffset()) + || rangeTracker.markDone(); } @Override public final boolean advance() throws IOException { - return advanceImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint(), getCurrentOffset()); + return advanceImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint(), getCurrentOffset()) + || rangeTracker.markDone(); } /** @@ -310,6 +325,32 @@ public Double getFractionConsumed() { return rangeTracker.getFractionConsumed(); } + @Override + public long getSplitPointsConsumed() { + return rangeTracker.getSplitPointsProcessed(); + } + + @Override + public long getSplitPointsRemaining() { + if (isDone()) { + return 0; + } else if (!isStarted()) { + // Note that even if the current source does not allow splitting, we don't know that + // it's non-empty so we return UNKNOWN instead of 1. + return BoundedReader.SPLIT_POINTS_UNKNOWN; + } else if (!getCurrentSource().allowsDynamicSplitting()) { + // Started (so non-empty) and unsplittable, so only the current task. + return 1; + } else if (getCurrentOffset() >= rangeTracker.getStopPosition() - 1) { + // If this is true, the next element is outside the range. Note that even getCurrentOffset() + // might be larger than the stop position when the current record is not a split point. + return 1; + } else { + // Use the default. + return super.getSplitPointsRemaining(); + } + } + @Override public final synchronized OffsetBasedSource splitAtFraction(double fraction) { if (!getCurrentSource().allowsDynamicSplitting()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 5089993437..bb894faf8c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -817,9 +817,10 @@ static class TextBasedReader extends FileBasedReader { private ByteString buffer; private int startOfSeparatorInBuffer; private int endOfSeparatorInBuffer; - private long startOfNextRecord; - private boolean eof; - private boolean elementIsPresent; + private long startOfRecord; + private volatile long startOfNextRecord; + private volatile boolean eof; + private volatile boolean elementIsPresent; private T currentValue; private ReadableByteChannel inChannel; @@ -834,7 +835,15 @@ protected long getCurrentOffset() throws NoSuchElementException { if (!elementIsPresent) { throw new NoSuchElementException(); } - return startOfNextRecord; + return startOfRecord; + } + + @Override + public long getSplitPointsRemaining() { + if (isStarted() && startOfNextRecord >= getCurrentSource().getEndOffset()) { + return isDone() ? 0 : 1; + } + return super.getSplitPointsRemaining(); } @Override @@ -912,7 +921,7 @@ private void findSeparatorBounds() throws IOException { @Override protected boolean readNextRecord() throws IOException { - startOfNextRecord += endOfSeparatorInBuffer; + startOfRecord = startOfNextRecord; findSeparatorBounds(); // If we have reached EOF file and consumed all of the buffer then we know @@ -923,6 +932,7 @@ protected boolean readNextRecord() throws IOException { } decodeCurrentElement(); + startOfNextRecord = startOfRecord + endOfSeparatorInBuffer; return true; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java index b237217496..20183c5240 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java @@ -16,6 +16,10 @@ package com.google.cloud.dataflow.sdk.io.range; +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; + import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -31,6 +35,8 @@ public class OffsetRangeTracker implements RangeTracker { private long stopOffset; private long lastRecordStart = -1L; private long offsetOfLastSplitPoint = -1L; + private long splitPointsSeen = 0L; + private boolean done = false; /** * Offset corresponding to infinity. This can only be used as the upper-bound of a range, and @@ -48,6 +54,15 @@ public OffsetRangeTracker(long startOffset, long stopOffset) { this.stopOffset = stopOffset; } + public synchronized boolean isStarted() { + // done => started: handles the case when the reader was empty. + return (offsetOfLastSplitPoint != -1) || done; + } + + public synchronized boolean isDone() { + return done; + } + @Override public synchronized Long getStartPosition() { return startOffset; @@ -64,10 +79,18 @@ public boolean tryReturnRecordAt(boolean isAtSplitPoint, Long recordStart) { } public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, long recordStart) { - if (lastRecordStart == -1 && !isAtSplitPoint) { + if (!isStarted() && !isAtSplitPoint) { throw new IllegalStateException( String.format("The first record [starting at %d] must be at a split point", recordStart)); } + if (recordStart < startOffset) { + throw new IllegalStateException( + String.format( + "Trying to return record [starting at %d] which is before the start offset [%d]", + recordStart, + startOffset)); + + } if (recordStart < lastRecordStart) { throw new IllegalStateException( String.format( @@ -76,8 +99,11 @@ public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, long recor recordStart, lastRecordStart)); } + + lastRecordStart = recordStart; + if (isAtSplitPoint) { - if (offsetOfLastSplitPoint != -1L && recordStart == offsetOfLastSplitPoint) { + if (recordStart == offsetOfLastSplitPoint) { throw new IllegalStateException( String.format( "Record at a split point has same offset as the previous split point: " @@ -85,12 +111,13 @@ public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, long recor offsetOfLastSplitPoint, recordStart)); } if (recordStart >= stopOffset) { + done = true; return false; } offsetOfLastSplitPoint = recordStart; + ++splitPointsSeen; } - lastRecordStart = recordStart; return true; } @@ -104,7 +131,7 @@ public synchronized boolean trySplitAtPosition(long splitOffset) { LOG.debug("Refusing to split {} at {}: stop position unspecified", this, splitOffset); return false; } - if (lastRecordStart == -1) { + if (!isStarted()) { LOG.debug("Refusing to split {} at {}: unstarted", this, splitOffset); return false; } @@ -142,17 +169,72 @@ public synchronized long getPositionForFractionConsumed(double fraction) { @Override public synchronized double getFractionConsumed() { - if (stopOffset == OFFSET_INFINITY) { + if (!isStarted()) { return 0.0; - } - if (lastRecordStart == -1) { + } else if (isDone()) { + return 1.0; + } else if (stopOffset == OFFSET_INFINITY) { return 0.0; + } else if (lastRecordStart >= stopOffset) { + return 1.0; + } else { + // E.g., when reading [3, 6) and lastRecordStart is 4, that means we consumed 3,4 of 3,4,5 + // which is (4 - 3 + 1) / (6 - 3) = 67%. + // Also, clamp to at most 1.0 because the last consumed position can extend past the + // stop position. + return Math.min(1.0, 1.0 * (lastRecordStart - startOffset + 1) / (stopOffset - startOffset)); } - // E.g., when reading [3, 6) and lastRecordStart is 4, that means we consumed 3,4 of 3,4,5 - // which is (4 - 3 + 1) / (6 - 3) = 67%. - // Also, clamp to at most 1.0 because the last consumed position can extend past the - // stop position. - return Math.min(1.0, 1.0 * (lastRecordStart - startOffset + 1) / (stopOffset - startOffset)); + } + + /** + * Returns the total number of split points that have been processed. + * + *

          A split point at a particular offset has been seen if there has been a corresponding call + * to {@link #tryReturnRecordAt(boolean, long)} with {@code isAtSplitPoint} true. It has been + * processed if there has been a subsequent call to + * {@link #tryReturnRecordAt(boolean, long)} with {@code isAtSplitPoint} true and at a larger + * offset. + * + *

          Note that for correctness when implementing {@link BoundedReader#getSplitPointsConsumed()}, + * if a reader finishes before {@link #tryReturnRecordAt(boolean, long)} returns false, + * the reader should add an additional call to {@link #markDone()}. This will indicate that + * processing for the last seen split point has been finished. + * + * @see com.google.cloud.dataflow.sdk.io.OffsetBasedSource for a {@link BoundedReader} + * implemented using {@link OffsetRangeTracker}. + */ + public synchronized long getSplitPointsProcessed() { + if (!isStarted()) { + return 0; + } else if (isDone()) { + return splitPointsSeen; + } else { + // There is a current split point, and it has not finished processing. + checkState( + splitPointsSeen > 0, + "A started rangeTracker should have seen > 0 split points (is %s)", + splitPointsSeen); + return splitPointsSeen - 1; + } + } + + + /** + * Marks this range tracker as being done. Specifically, this will mark the current split point, + * if one exists, as being finished. + * + *

          Always returns false, so that it can be used in an implementation of + * {@link BoundedReader#start()} or {@link BoundedReader#advance()} as follows: + * + *

           {@code
          +   * public boolean start() {
          +   *   return startImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint, position)
          +   *       || rangeTracker.markDone();
          +   * }} 
          + */ + public synchronized boolean markDone() { + done = true; + return false; } @Override @@ -176,7 +258,10 @@ public synchronized String toString() { @VisibleForTesting OffsetRangeTracker copy() { OffsetRangeTracker res = new OffsetRangeTracker(startOffset, stopOffset); + res.offsetOfLastSplitPoint = this.offsetOfLastSplitPoint; res.lastRecordStart = this.lastRecordStart; + res.done = this.done; + res.splitPointsSeen = this.splitPointsSeen; return res; } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java index e2c4299fe5..4298c5774d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java @@ -20,6 +20,7 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -27,6 +28,8 @@ import com.google.cloud.dataflow.sdk.coders.DefaultCoder; import com.google.cloud.dataflow.sdk.io.AvroSource.AvroReader; import com.google.cloud.dataflow.sdk.io.AvroSource.AvroReader.Seeker; +import com.google.cloud.dataflow.sdk.io.BlockBasedSource.BlockBasedReader; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; @@ -42,6 +45,7 @@ import org.apache.avro.reflect.AvroDefault; import org.apache.avro.reflect.Nullable; import org.apache.avro.reflect.ReflectData; +import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -55,6 +59,7 @@ import java.io.IOException; import java.io.PushbackInputStream; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; @@ -195,6 +200,86 @@ public void testGetProgressFromUnstartedReader() throws Exception { } } + @Test + public void testProgress() throws Exception { + // 5 records, 2 per block. + List records = createFixedRecords(5); + String filename = generateTestFile("tmp.avro", records, SyncBehavior.SYNC_REGULAR, 2, + AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); + + AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); + try (BoundedSource.BoundedReader readerOrig = source.createReader(null)) { + assertThat(readerOrig, Matchers.instanceOf(BlockBasedReader.class)); + BlockBasedReader reader = (BlockBasedReader) readerOrig; + + // Before starting + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // First 2 records are in the same block. + assertTrue(reader.start()); + assertTrue(reader.isAtSplitPoint()); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + // continued + assertTrue(reader.advance()); + assertFalse(reader.isAtSplitPoint()); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Second block -> parallelism consumed becomes 1. + assertTrue(reader.advance()); + assertTrue(reader.isAtSplitPoint()); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + // continued + assertTrue(reader.advance()); + assertFalse(reader.isAtSplitPoint()); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Third and final block -> parallelism consumed becomes 2, remaining becomes 1. + assertTrue(reader.advance()); + assertTrue(reader.isAtSplitPoint()); + assertEquals(2, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + + // Done + assertFalse(reader.advance()); + assertEquals(3, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + } + } + + @Test + public void testProgressEmptySource() throws Exception { + // 0 records, 20 per block. + List records = Collections.emptyList(); + String filename = generateTestFile("tmp.avro", records, SyncBehavior.SYNC_REGULAR, 2, + AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); + + AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); + try (BoundedSource.BoundedReader readerOrig = source.createReader(null)) { + assertThat(readerOrig, Matchers.instanceOf(BlockBasedReader.class)); + BlockBasedReader reader = (BlockBasedReader) readerOrig; + + // before starting + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // confirm empty + assertFalse(reader.start()); + + // after reading empty source + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + } + } + @Test public void testGetCurrentFromUnstartedReader() throws Exception { List records = createFixedRecords(DEFAULT_RECORD_COUNT); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index 57a0f8aec3..702d93cba5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -21,6 +21,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -28,8 +30,11 @@ import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; +import com.google.cloud.dataflow.sdk.io.CompressedSource.CompressedReader; import com.google.cloud.dataflow.sdk.io.CompressedSource.CompressionMode; import com.google.cloud.dataflow.sdk.io.CompressedSource.DecompressingChannelFactory; +import com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; @@ -460,11 +465,12 @@ public Coder getDefaultOutputCoder() { private static class ByteReader extends FileBasedReader { ByteBuffer buff = ByteBuffer.allocate(1); Byte current; - long offset = -1; + long offset; ReadableByteChannel channel; public ByteReader(ByteSource source) { super(source); + offset = source.getStartOffset() - 1; } @Override @@ -499,4 +505,102 @@ protected long getCurrentOffset() { } } } + + @Test + public void testEmptyGzipProgress() throws IOException { + File tmpFile = tmpFolder.newFile("empty.gz"); + String filename = tmpFile.toPath().toString(); + writeFile(tmpFile, new byte[0], CompressionMode.GZIP); + + PipelineOptions options = PipelineOptionsFactory.create(); + CompressedSource source = CompressedSource.from(new ByteSource(filename, 1)); + try (BoundedReader readerOrig = source.createReader(options)) { + assertThat(readerOrig, instanceOf(CompressedReader.class)); + CompressedReader reader = (CompressedReader) readerOrig; + // before starting + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + + // confirm empty + assertFalse(reader.start()); + + // after reading empty source + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + + @Test + public void testGzipProgress() throws IOException { + int numRecords = 3; + File tmpFile = tmpFolder.newFile("nonempty.gz"); + String filename = tmpFile.toPath().toString(); + writeFile(tmpFile, new byte[numRecords], CompressionMode.GZIP); + + PipelineOptions options = PipelineOptionsFactory.create(); + CompressedSource source = CompressedSource.from(new ByteSource(filename, 1)); + try (BoundedReader readerOrig = source.createReader(options)) { + assertThat(readerOrig, instanceOf(CompressedReader.class)); + CompressedReader reader = (CompressedReader) readerOrig; + // before starting + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + + // confirm has three records + for (int i = 0; i < numRecords; ++i) { + if (i == 0) { + assertTrue(reader.start()); + } else { + assertTrue(reader.advance()); + } + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + } + assertFalse(reader.advance()); + + // after reading empty source + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + + @Test + public void testSplittableProgress() throws IOException { + File tmpFile = tmpFolder.newFile("nonempty.txt"); + String filename = tmpFile.toPath().toString(); + Files.write(new byte[2], tmpFile); + + PipelineOptions options = PipelineOptionsFactory.create(); + CompressedSource source = CompressedSource.from(new ByteSource(filename, 1)); + try (BoundedReader readerOrig = source.createReader(options)) { + assertThat(readerOrig, not(instanceOf(CompressedReader.class))); + assertThat(readerOrig, instanceOf(FileBasedReader.class)); + FileBasedReader reader = (FileBasedReader) readerOrig; + + // Check preconditions before starting + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // First record: none consumed, unknown remaining. + assertTrue(reader.start()); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Second record: 1 consumed, know that we're on the last record. + assertTrue(reader.advance()); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + + // Confirm empty and check post-conditions + assertFalse(reader.advance()); + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(2, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java index cc9db7978f..cc01cc8576 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java @@ -20,8 +20,10 @@ import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.CountingSource.CounterMark; import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -43,6 +45,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.IOException; import java.util.List; /** @@ -109,6 +112,33 @@ public void testBoundedSourceSplits() throws Exception { p.run(); } + @Test + public void testProgress() throws IOException { + final int numRecords = 5; + @SuppressWarnings("deprecation") // testing CountingSource + BoundedSource source = CountingSource.upTo(numRecords); + try (BoundedReader reader = source.createReader(PipelineOptionsFactory.create())) { + // Check preconditions before starting. Note that CountingReader can always give an accurate + // remaining parallelism. + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(numRecords, reader.getSplitPointsRemaining()); + + assertTrue(reader.start()); + int i = 0; + do { + assertEquals(i, reader.getSplitPointsConsumed()); + assertEquals(numRecords - i, reader.getSplitPointsRemaining()); + ++i; + } while (reader.advance()); + + assertEquals(numRecords, i); // exactly numRecords calls to advance() + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(numRecords, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + @Test @Category(RunnableOnService.class) public void testUnboundedSource() { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java index 7cf4398393..33a9212034 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java @@ -441,7 +441,7 @@ public void testFractionConsumedWhenReadingFilepattern() throws IOException { assertTrue(fractionConsumed > lastFractionConsumed); lastFractionConsumed = fractionConsumed; } - assertTrue(reader.getFractionConsumed() < 1.0); + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java index bdbd00ecb3..07f0d80099 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java @@ -24,6 +24,8 @@ import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; +import com.google.cloud.dataflow.sdk.io.OffsetBasedSource.OffsetBasedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; @@ -82,13 +84,12 @@ public long getMaxEndOffset(PipelineOptions options) { } @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { + public OffsetBasedReader createReader(PipelineOptions options) throws IOException { return new CoarseRangeReader(this); } } - private static class CoarseRangeReader - extends OffsetBasedSource.OffsetBasedReader { + private static class CoarseRangeReader extends OffsetBasedReader { private long current = -1; private long granularity; @@ -234,6 +235,69 @@ public void testReadingGranularityAndFractionConsumed() throws IOException { } } + @Test + public void testProgress() throws IOException { + PipelineOptions options = PipelineOptionsFactory.create(); + CoarseRangeSource source = new CoarseRangeSource(13, 17, 1, 2); + try (OffsetBasedReader reader = source.createReader(options)) { + // Unstarted reader + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Start and produce the element 14 since granularity is 2. + assertTrue(reader.start()); + assertTrue(reader.isAtSplitPoint()); + assertEquals(14, reader.getCurrent().intValue()); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + // Advance and produce the element 15, not a split point. + assertTrue(reader.advance()); + assertEquals(15, reader.getCurrent().intValue()); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Advance and produce the element 16, is a split point. Since the next offset (17) is + // outside the range [13, 17), remaining parallelism should become 1 from UNKNOWN. + assertTrue(reader.advance()); + assertTrue(reader.isAtSplitPoint()); + assertEquals(16, reader.getCurrent().intValue()); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); // The next offset is outside the range. + // Advance and produce the element 17, not a split point. + assertTrue(reader.advance()); + assertEquals(17, reader.getCurrent().intValue()); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + + // Advance and reach the end of the reader. + assertFalse(reader.advance()); + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(2, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + + @Test + public void testProgressEmptySource() throws IOException { + PipelineOptions options = PipelineOptionsFactory.create(); + CoarseRangeSource source = new CoarseRangeSource(13, 17, 1, 100); + try (OffsetBasedReader reader = source.createReader(options)) { + // before starting + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // confirm empty + assertFalse(reader.start()); + + // after reading empty source + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + @Test public void testSplitAtFraction() throws IOException { PipelineOptions options = PipelineOptionsFactory.create(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 1d2fa06e96..90306a921b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -28,6 +28,7 @@ import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -36,6 +37,7 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.TextIO.CompressionType; import com.google.cloud.dataflow.sdk.io.TextIO.TextSource; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; @@ -531,6 +533,117 @@ public void testTextIOGetName() { "ReadMyFile [TextIO.Read]", TextIO.Read.named("ReadMyFile").from("somefile").toString()); } + @Test + public void testProgressEmptyFile() throws IOException { + try (BoundedReader reader = + prepareSource(new byte[0]).createReader(PipelineOptionsFactory.create())) { + // Check preconditions before starting. + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Assert empty + assertFalse(reader.start()); + + // Check postconditions after finishing + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + + @Test + public void testProgressTextFile() throws IOException { + String file = "line1\nline2\nline3"; + try (BoundedReader reader = + prepareSource(file.getBytes()).createReader(PipelineOptionsFactory.create())) { + // Check preconditions before starting + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Line 1 + assertTrue(reader.start()); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Line 2 + assertTrue(reader.advance()); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Line 3 + assertTrue(reader.advance()); + assertEquals(2, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + + // Check postconditions after finishing + assertFalse(reader.advance()); + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(3, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + + @Test + public void testProgressAfterSplitting() throws IOException { + String file = "line1\nline2\nline3"; + BoundedSource source = prepareSource(file.getBytes()); + BoundedSource remainder; + + // Create the remainder, verifying properties pre- and post-splitting. + try (BoundedReader readerOrig = source.createReader(PipelineOptionsFactory.create())) { + // Preconditions. + assertEquals(0.0, readerOrig.getFractionConsumed(), 1e-6); + assertEquals(0, readerOrig.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, readerOrig.getSplitPointsRemaining()); + + // First record, before splitting. + assertTrue(readerOrig.start()); + assertEquals(0, readerOrig.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, readerOrig.getSplitPointsRemaining()); + + // Split. 0.1 is in line1, so should now be able to detect last record. + remainder = readerOrig.splitAtFraction(0.1); + System.err.println(readerOrig.getCurrentSource()); + assertNotNull(remainder); + + // First record, after splitting. + assertEquals(0, readerOrig.getSplitPointsConsumed()); + assertEquals(1, readerOrig.getSplitPointsRemaining()); + + // Finish and postconditions. + assertFalse(readerOrig.advance()); + assertEquals(1.0, readerOrig.getFractionConsumed(), 1e-6); + assertEquals(1, readerOrig.getSplitPointsConsumed()); + assertEquals(0, readerOrig.getSplitPointsRemaining()); + } + + // Check the properties of the remainder. + try (BoundedReader reader = remainder.createReader(PipelineOptionsFactory.create())) { + // Preconditions. + assertEquals(0.0, reader.getFractionConsumed(), 1e-6); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // First record should be line 2. + assertTrue(reader.start()); + assertEquals(0, reader.getSplitPointsConsumed()); + assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); + + // Second record is line 3 + assertTrue(reader.advance()); + assertEquals(1, reader.getSplitPointsConsumed()); + assertEquals(1, reader.getSplitPointsRemaining()); + + // Check postconditions after finishing + assertFalse(reader.advance()); + assertEquals(1.0, reader.getFractionConsumed(), 1e-6); + assertEquals(2, reader.getSplitPointsConsumed()); + assertEquals(0, reader.getSplitPointsRemaining()); + } + } + @Test public void testReadEmptyLines() throws Exception { runTestReadWithData("\n\n\n".getBytes(StandardCharsets.UTF_8), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java index b1f1070ba0..cc0a3c2047 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java @@ -103,7 +103,6 @@ public void testSplitAtOffset() throws Exception { assertFalse(tracker.tryReturnRecordAt(true, 150)); assertFalse(tracker.tryReturnRecordAt(true, 151)); // Should accept non-splitpoint records starting after stop offset. - assertTrue(tracker.tryReturnRecordAt(false, 135)); assertTrue(tracker.tryReturnRecordAt(false, 152)); assertTrue(tracker.tryReturnRecordAt(false, 160)); assertFalse(tracker.tryReturnRecordAt(true, 171)); From bbbb1d168630a628af7e4ae82b797b6b46874cb7 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Mon, 23 May 2016 12:31:20 -0700 Subject: [PATCH 428/751] PubsubIO: make translation to Dataflow service compatible --- sdk/pom.xml | 2 +- .../cloud/dataflow/sdk/io/PubsubIO.java | 13 +- .../dataflow/sdk/io/PubsubUnboundedSink.java | 7 +- .../sdk/runners/DataflowPipelineRunner.java | 115 ++++++++---------- .../dataflow/sdk/util/MovingFunction.java | 8 +- .../cloud/dataflow/sdk/util/PubsubClient.java | 2 +- ...piaryClient.java => PubsubJsonClient.java} | 31 +++-- .../sdk/io/PubsubUnboundedSourceTest.java | 2 - .../sdk/util/BucketingFunctionTest.java | 3 +- .../dataflow/sdk/util/MovingFunctionTest.java | 3 +- .../dataflow/sdk/util/PubsubClientTest.java | 3 + .../sdk/util/PubsubGrpcClientTest.java | 4 + ...entTest.java => PubsubJsonClientTest.java} | 13 +- .../sdk/util/PubsubTestClientTest.java | 3 + 14 files changed, 103 insertions(+), 106 deletions(-) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/util/{PubsubApiaryClient.java => PubsubJsonClient.java} (91%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/util/{PubsubApiaryClientTest.java => PubsubJsonClientTest.java} (94%) diff --git a/sdk/pom.xml b/sdk/pom.xml index a2ef06ebb8..f7b836a156 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -496,7 +496,7 @@ grpc-pubsub-v1 ${pubsubgrpc.version} - com.google.guava diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java index 965db829c0..48114e61c1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java @@ -31,13 +31,13 @@ import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.PubsubApiaryClient; import com.google.cloud.dataflow.sdk.util.PubsubClient; import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; +import com.google.cloud.dataflow.sdk.util.PubsubJsonClient; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; @@ -70,7 +70,7 @@ public class PubsubIO { private static final Logger LOG = LoggerFactory.getLogger(PubsubIO.class); /** Factory for creating pubsub client to manage transport. */ - private static final PubsubClient.PubsubClientFactory FACTORY = PubsubApiaryClient.FACTORY; + private static final PubsubClient.PubsubClientFactory FACTORY = PubsubJsonClient.FACTORY; /** The default {@link Coder} used to translate to/from Cloud Pub/Sub messages. */ public static final Coder DEFAULT_PUBSUB_CODER = StringUtf8Coder.of(); @@ -645,7 +645,8 @@ public PCollection apply(PInput input) { if (boundedOutput) { return input.getPipeline().begin() .apply(Create.of((Void) null)).setCoder(VoidCoder.of()) - .apply(ParDo.of(new PubsubBoundedReader())).setCoder(coder); + .apply(ParDo.of(new PubsubReader())) + .setCoder(coder); } else { @Nullable ProjectPath projectPath = topic == null ? null : PubsubClient.projectPathFromId(topic.project); @@ -724,7 +725,7 @@ public Duration getMaxReadTime() { * *

          Public so can be suppressed by runners. */ - public class PubsubBoundedReader extends DoFn { + public class PubsubReader extends DoFn { private static final int DEFAULT_PULL_SIZE = 100; private static final int ACK_TIMEOUT_SEC = 60; @@ -981,7 +982,7 @@ public PDone apply(PCollection input) { } switch (input.isBounded()) { case BOUNDED: - input.apply(ParDo.of(new PubsubBoundedWriter())); + input.apply(ParDo.of(new PubsubWriter())); return PDone.in(input.getPipeline()); case UNBOUNDED: return input.apply(new PubsubUnboundedSink( @@ -1030,7 +1031,7 @@ public Coder getCoder() { * *

          Public so can be suppressed by runners. */ - public class PubsubBoundedWriter extends DoFn { + public class PubsubWriter extends DoFn { private static final int MAX_PUBLISH_BATCH_SIZE = 100; private transient List output; private transient PubsubClient pubsubClient; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java index 98fc29ba6e..359af380d2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java @@ -55,8 +55,6 @@ import com.google.common.hash.Hashing; import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; @@ -87,8 +85,6 @@ *

          NOTE: This is not the implementation used when running on the Google Cloud Dataflow service. */ public class PubsubUnboundedSink extends PTransform, PDone> { - private static final Logger LOG = LoggerFactory.getLogger(PubsubUnboundedSink.class); - /** * Default maximum number of messages per publish. */ @@ -247,9 +243,8 @@ private static class WriterFn */ private void publishBatch(List messages, int bytes) throws IOException { - long nowMsSinceEpoch = System.currentTimeMillis(); int n = pubsubClient.publish(topic, messages); - checkState(n == messages.size(), "Attempted to publish %d messages but %d were successful", + checkState(n == messages.size(), "Attempted to publish %s messages but %s were successful", messages.size(), n); batchCounter.addValue(1L); elementCounter.addValue((long) messages.size()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 61429b24b2..bfb0d338c3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -59,6 +59,8 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.FileBasedSink; import com.google.cloud.dataflow.sdk.io.PubsubIO; +import com.google.cloud.dataflow.sdk.io.PubsubIO.Read.Bound.PubsubReader; +import com.google.cloud.dataflow.sdk.io.PubsubIO.Write.Bound.PubsubWriter; import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSink; import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource; import com.google.cloud.dataflow.sdk.io.Read; @@ -118,7 +120,6 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; import com.google.cloud.dataflow.sdk.util.WindowingStrategy; import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PCollectionList; @@ -362,15 +363,11 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(Window.Bound.class, AssignWindows.class); // In streaming mode must use either the custom Pubsub unbounded source/sink or // defer to Windmill's built-in implementation. - builder.put(PubsubIO.Read.Bound.PubsubBoundedReader.class, UnsupportedIO.class); - builder.put(PubsubIO.Write.Bound.PubsubBoundedWriter.class, UnsupportedIO.class); - if (options.getExperiments() == null - || !options.getExperiments().contains("enable_custom_pubsub_source")) { - builder.put(PubsubUnboundedSource.class, StreamingPubsubIORead.class); - } + builder.put(PubsubReader.class, UnsupportedIO.class); + builder.put(PubsubWriter.class, UnsupportedIO.class); if (options.getExperiments() == null || !options.getExperiments().contains("enable_custom_pubsub_sink")) { - builder.put(PubsubUnboundedSink.class, StreamingPubsubIOWrite.class); + builder.put(PubsubIO.Write.Bound.class, StreamingPubsubIOWrite.class); } } else { builder.put(Read.Unbounded.class, UnsupportedIO.class); @@ -421,10 +418,19 @@ public OutputT apply( OutputT outputT = (OutputT) PCollection.createPrimitiveOutputInternal( pc.getPipeline(), transform instanceof GroupByKey - ? ((GroupByKey) transform).updateWindowingStrategy(pc.getWindowingStrategy()) - : pc.getWindowingStrategy(), + ? ((GroupByKey) transform).updateWindowingStrategy(pc.getWindowingStrategy()) + : pc.getWindowingStrategy(), pc.isBounded()); return outputT; + } else if (PubsubIO.Read.Bound.class.equals(transform.getClass()) + && options.isStreaming() + && (options.getExperiments() == null + || !options.getExperiments().contains("enable_custom_pubsub_source"))) { + // casting to wildcard + @SuppressWarnings("unchecked") + OutputT pubsub = (OutputT) applyPubsubStreamingRead((PubsubIO.Read.Bound) transform, + input); + return pubsub; } else if (Window.Bound.class.equals(transform.getClass())) { /* * TODO: make this the generic way overrides are applied (using super.apply() rather than @@ -460,6 +466,16 @@ public OutputT apply( } } + private PCollection + applyPubsubStreamingRead(PubsubIO.Read.Bound initialTransform, PInput input) { + // types are matched at compile time + @SuppressWarnings("unchecked") + PubsubIO.Read.Bound transform = (PubsubIO.Read.Bound) initialTransform; + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED) + .setCoder(transform.getCoder()); + } + private PCollection applyWindow( Window.Bound intitialTransform, PCollection initialInput) { // types are matched at compile time @@ -2555,79 +2571,46 @@ protected String getKindString() { // PubsubIO translations // ================================================================================ - /** - * Suppress application of {@link PubsubUnboundedSource#apply} in streaming mode so that we - * can instead defer to Windmill's implementation. - */ - private static class StreamingPubsubIORead extends PTransform> { - private final PubsubUnboundedSource transform; - - /** - * Builds an instance of this class from the overridden transform. - */ - public StreamingPubsubIORead( - DataflowPipelineRunner runner, PubsubUnboundedSource transform) { - this.transform = transform; - } - - PubsubUnboundedSource getOverriddenTransform() { - return transform; - } - - @Override - public PCollection apply(PBegin input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED) - .setCoder(transform.getElementCoder()); - } - - @Override - protected String getKindString() { - return "StreamingPubsubIORead"; - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - StreamingPubsubIORead.class, new StreamingPubsubIOReadTranslator()); - } + static { + DataflowPipelineTranslator.registerTransformTranslator( + PubsubIO.Read.Bound.class, new StreamingPubsubIOReadTranslator()); } /** - * Rewrite {@link StreamingPubsubIORead} to the appropriate internal node. + * Rewrite {@link PubsubIO.Read.Bound} to the appropriate internal node. */ private static class StreamingPubsubIOReadTranslator implements - TransformTranslator { + TransformTranslator { @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void translate( - StreamingPubsubIORead transform, + PubsubIO.Read.Bound transform, TranslationContext context) { translateTyped(transform, context); } private void translateTyped( - StreamingPubsubIORead transform, + PubsubIO.Read.Bound transform, TranslationContext context) { Preconditions.checkState(context.getPipelineOptions().isStreaming(), "StreamingPubsubIORead is only for streaming pipelines."); - PubsubUnboundedSource overriddenTransform = transform.getOverriddenTransform(); context.addStep(transform, "ParallelRead"); context.addInput(PropertyNames.FORMAT, "pubsub"); - if (overriddenTransform.getTopic() != null) { + if (transform.getTopic() != null) { context.addInput(PropertyNames.PUBSUB_TOPIC, - overriddenTransform.getTopic().getV1Beta1Path()); + transform.getTopic().asV1Beta1Path()); } - if (overriddenTransform.getSubscription() != null) { + if (transform.getSubscription() != null) { context.addInput( PropertyNames.PUBSUB_SUBSCRIPTION, - overriddenTransform.getSubscription().getV1Beta1Path()); + transform.getSubscription().asV1Beta1Path()); } - if (overriddenTransform.getTimestampLabel() != null) { + if (transform.getTimestampLabel() != null) { context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, - overriddenTransform.getTimestampLabel()); + transform.getTimestampLabel()); } - if (overriddenTransform.getIdLabel() != null) { - context.addInput(PropertyNames.PUBSUB_ID_LABEL, overriddenTransform.getIdLabel()); + if (transform.getIdLabel() != null) { + context.addInput(PropertyNames.PUBSUB_ID_LABEL, transform.getIdLabel()); } context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); } @@ -2638,17 +2621,17 @@ private void translateTyped( * can instead defer to Windmill's implementation. */ private static class StreamingPubsubIOWrite extends PTransform, PDone> { - private final PubsubUnboundedSink transform; + private final PubsubIO.Write.Bound transform; /** * Builds an instance of this class from the overridden transform. */ public StreamingPubsubIOWrite( - DataflowPipelineRunner runner, PubsubUnboundedSink transform) { + DataflowPipelineRunner runner, PubsubIO.Write.Bound transform) { this.transform = transform; } - PubsubUnboundedSink getOverriddenTransform() { + PubsubIO.Write.Bound getOverriddenTransform() { return transform; } @@ -2687,10 +2670,10 @@ private void translateTyped( TranslationContext context) { Preconditions.checkState(context.getPipelineOptions().isStreaming(), "StreamingPubsubIOWrite is only for streaming pipelines."); - PubsubUnboundedSink overriddenTransform = transform.getOverriddenTransform(); + PubsubIO.Write.Bound overriddenTransform = transform.getOverriddenTransform(); context.addStep(transform, "ParallelWrite"); context.addInput(PropertyNames.FORMAT, "pubsub"); - context.addInput(PropertyNames.PUBSUB_TOPIC, overriddenTransform.getTopic().getV1Beta1Path()); + context.addInput(PropertyNames.PUBSUB_TOPIC, overriddenTransform.getTopic().asV1Beta1Path()); if (overriddenTransform.getTimestampLabel() != null) { context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, overriddenTransform.getTimestampLabel()); @@ -2699,7 +2682,7 @@ private void translateTyped( context.addInput(PropertyNames.PUBSUB_ID_LABEL, overriddenTransform.getIdLabel()); } context.addEncodingInput( - WindowedValue.getValueOnlyCoder(overriddenTransform.getElementCoder())); + WindowedValue.getValueOnlyCoder(overriddenTransform.getCoder())); context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); } } @@ -3317,7 +3300,7 @@ public UnsupportedIO(DataflowPipelineRunner runner, TextIO.Write.Bound transf */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() public UnsupportedIO(DataflowPipelineRunner runner, - PubsubIO.Read.Bound.PubsubBoundedReader doFn) { + PubsubReader doFn) { this.doFn = doFn; } @@ -3326,7 +3309,7 @@ public UnsupportedIO(DataflowPipelineRunner runner, */ @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() public UnsupportedIO(DataflowPipelineRunner runner, - PubsubIO.Write.Bound.PubsubBoundedWriter doFn) { + PubsubWriter doFn) { this.doFn = doFn; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java index 04ec8db6d3..73386e12c5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java @@ -27,11 +27,6 @@ * {@link #sampleUpdateMs}. */ public class MovingFunction { - /** - * How far back to retain samples, in ms. - */ - private final long samplePeriodMs; - /** * How frequently to update the moving function, in ms. */ @@ -75,7 +70,6 @@ public class MovingFunction { public MovingFunction(long samplePeriodMs, long sampleUpdateMs, int numSignificantBuckets, int numSignificantSamples, Combine.BinaryCombineLongFn function) { - this.samplePeriodMs = samplePeriodMs; this.sampleUpdateMs = sampleUpdateMs; this.numSignificantBuckets = numSignificantBuckets; this.numSignificantSamples = numSignificantSamples; @@ -121,7 +115,7 @@ public void add(long nowMsSinceEpoch, long value) { } /** - * Return the minimum/maximum/sum of all retained values within {@link #samplePeriodMs} + * Return the minimum/maximum/sum of all retained values within samplePeriodMs * of {@code nowMsSinceEpoch}. */ public long get(long nowMsSinceEpoch) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java index 46eaf006c1..73b06d7b5a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java @@ -54,7 +54,7 @@ PubsubClient newClient( DataflowPipelineOptions options) throws IOException; /** - * Return the display name for this factory. Eg "Apiary", "gRPC". + * Return the display name for this factory. Eg "Json", "gRPC". */ String getKind(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClient.java similarity index 91% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClient.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClient.java index f7fa7832ee..c8ac8f5126 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClient.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClient.java @@ -18,6 +18,8 @@ import static com.google.common.base.Preconditions.checkState; +import com.google.api.client.auth.oauth2.Credential; +import com.google.api.client.http.HttpRequestInitializer; import com.google.api.services.pubsub.Pubsub; import com.google.api.services.pubsub.Pubsub.Builder; import com.google.api.services.pubsub.model.AcknowledgeRequest; @@ -47,11 +49,20 @@ import javax.annotation.Nullable; /** - * A Pubsub client using Apiary. + * A Pubsub client using JSON. */ -public class PubsubApiaryClient extends PubsubClient { +public class PubsubJsonClient extends PubsubClient { + + private static class PubsubJsonClientFactory implements PubsubClientFactory { + private static HttpRequestInitializer chainHttpRequestInitializer( + Credential credential, HttpRequestInitializer httpRequestInitializer) { + if (credential == null) { + return httpRequestInitializer; + } else { + return new ChainingHttpRequestInitializer(credential, httpRequestInitializer); + } + } - private static class PubsubApiaryClientFactory implements PubsubClientFactory { @Override public PubsubClient newClient( @Nullable String timestampLabel, @Nullable String idLabel, DataflowPipelineOptions options) @@ -59,7 +70,7 @@ public PubsubClient newClient( Pubsub pubsub = new Builder( Transport.getTransport(), Transport.getJsonFactory(), - new ChainingHttpRequestInitializer( + chainHttpRequestInitializer( options.getGcpCredential(), // Do not log 404. It clutters the output and is possibly even required by the caller. new RetryHttpRequestInitializer(ImmutableList.of(404)))) @@ -67,19 +78,19 @@ public PubsubClient newClient( .setApplicationName(options.getAppName()) .setGoogleClientRequestInitializer(options.getGoogleApiTrace()) .build(); - return new PubsubApiaryClient(timestampLabel, idLabel, pubsub); + return new PubsubJsonClient(timestampLabel, idLabel, pubsub); } @Override public String getKind() { - return "Apiary"; + return "Json"; } } /** - * Factory for creating Pubsub clients using Apiary transport. + * Factory for creating Pubsub clients using JSON transport. */ - public static final PubsubClientFactory FACTORY = new PubsubApiaryClientFactory(); + public static final PubsubClientFactory FACTORY = new PubsubJsonClientFactory(); /** * Label to use for custom timestamps, or {@literal null} if should use Pubsub publish time @@ -95,12 +106,12 @@ public String getKind() { private final String idLabel; /** - * Underlying Apiary client. + * Underlying JSON transport. */ private Pubsub pubsub; @VisibleForTesting - PubsubApiaryClient( + PubsubJsonClient( @Nullable String timestampLabel, @Nullable String idLabel, Pubsub pubsub) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java index a0b05a5357..0788347726 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java @@ -118,7 +118,6 @@ public void readOneMessage() throws IOException { setupOneMessage(); TestPipeline p = TestPipeline.create(); PubsubReader reader = primSource.createReader(p.getOptions(), null); - PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); // Read one message. assertTrue(reader.start()); assertEquals(DATA, reader.getCurrent()); @@ -215,7 +214,6 @@ public void multipleReaders() throws IOException { setupOneMessage(incoming); TestPipeline p = TestPipeline.create(); PubsubReader reader = primSource.createReader(p.getOptions(), null); - PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); // Consume two messages, only read one. assertTrue(reader.start()); assertEquals("data_0", reader.getCurrent()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java index 130b0bd39b..394dcbf349 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java @@ -16,10 +16,11 @@ package com.google.cloud.dataflow.sdk.util; -import com.google.cloud.dataflow.sdk.transforms.Combine; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.transforms.Combine; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java index 998d2ba0dc..9303d66d03 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java @@ -16,10 +16,11 @@ package com.google.cloud.dataflow.sdk.util; -import com.google.cloud.dataflow.sdk.transforms.Combine; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.transforms.Combine; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java index 44ed022f36..880dd9fb71 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java @@ -28,12 +28,15 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.util.Map; /** * Tests for helper classes and methods in PubsubClient. */ +@RunWith(JUnit4.class) public class PubsubClientTest { @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java index 3ca2f8586d..cdb2d91d10 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java @@ -39,9 +39,12 @@ import com.google.pubsub.v1.SubscriberGrpc; import io.grpc.ManagedChannel; + import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.mockito.Mockito; import java.io.IOException; @@ -50,6 +53,7 @@ /** * Tests for PubsubGrpcClient. */ +@RunWith(JUnit4.class) public class PubsubGrpcClientTest { private ManagedChannel mockChannel; private GoogleCredentials mockCredentials; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClientTest.java similarity index 94% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClientTest.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClientTest.java index f329347684..c3dd452d43 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubApiaryClientTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClientTest.java @@ -37,15 +37,18 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.mockito.Mockito; import java.io.IOException; import java.util.List; /** - * Tests for PubsubApiaryClient. + * Tests for PubsubJsonClient. */ -public class PubsubApiaryClientTest { +@RunWith(JUnit4.class) +public class PubsubJsonClientTest { private Pubsub mockPubsub; private PubsubClient client; @@ -65,7 +68,7 @@ public class PubsubApiaryClientTest { @Before public void setup() throws IOException { mockPubsub = Mockito.mock(Pubsub.class, Mockito.RETURNS_DEEP_STUBS); - client = new PubsubApiaryClient(TIMESTAMP_LABEL, ID_LABEL, mockPubsub); + client = new PubsubJsonClient(TIMESTAMP_LABEL, ID_LABEL, mockPubsub); } @After @@ -92,7 +95,7 @@ public void pullOneMessage() throws IOException { .setAckId(ACK_ID); PullResponse expectedResponse = new PullResponse().setReceivedMessages(ImmutableList.of(expectedReceivedMessage)); - Mockito.when(mockPubsub.projects() + Mockito.when((Object) mockPubsub.projects() .subscriptions() .pull(expectedSubscription, expectedRequest) .execute()) @@ -119,7 +122,7 @@ public void publishOneMessage() throws IOException { .setMessages(ImmutableList.of(expectedPubsubMessage)); PublishResponse expectedResponse = new PublishResponse() .setMessageIds(ImmutableList.of(MESSAGE_ID)); - Mockito.when(mockPubsub.projects() + Mockito.when((Object) mockPubsub.projects() .topics() .publish(expectedTopic, expectedRequest) .execute()) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java index 82e03dc804..1ba1b29cd4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java @@ -31,6 +31,8 @@ import com.google.common.collect.Sets; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.util.List; @@ -39,6 +41,7 @@ /** * Tests for PubsubTestClient. */ +@RunWith(JUnit4.class) public class PubsubTestClientTest { private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); private static final SubscriptionPath SUBSCRIPTION = From 266321c3b4f203b66f0e2e44e51b4a8a5fa69d3a Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 23 May 2016 12:57:26 -0700 Subject: [PATCH 429/751] AvroSource: synchronization fix --- .../java/com/google/cloud/dataflow/sdk/io/AvroSource.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java index a27dcb4fde..ea3d1c9ee6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java @@ -492,7 +492,10 @@ public synchronized AvroSource getCurrentSource() { // Postcondition: same as above, but for the new current (formerly next) block. @Override public boolean readNextBlock() throws IOException { - long startOfNextBlock = currentBlockOffset + currentBlockSizeBytes; + long startOfNextBlock; + synchronized (progressLock) { + startOfNextBlock = currentBlockOffset + currentBlockSizeBytes; + } // Before reading the variable-sized block header, record the current number of bytes read. long preHeaderCount = countStream.getBytesRead(); From 42a132942a86c6408913a22d0da9a61593d8c5cd Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 23 May 2016 12:59:02 -0700 Subject: [PATCH 430/751] HadoopFileSource: whitespace fix --- .../google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java index dad4575061..afe6c337b5 100644 --- a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java +++ b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java @@ -356,7 +356,7 @@ public boolean advance() throws IOException { } // either no next split or all readers were empty currentPair = null; - done = true; + done = true; return false; } } catch (InterruptedException e) { From 740752d917dee235fac4c04e8b4ae134606532fe Mon Sep 17 00:00:00 2001 From: Kenn Knowles Date: Mon, 23 May 2016 15:09:50 -0700 Subject: [PATCH 431/751] Change-detector test for PubsubIO translation (#284) * Add change-detector test for PubsubIO These tests were written against the v1.5.1 tag, so ensure that subsequent releases do not deviate from the translation there. * Pre-emptive merge conflict avoidance --- .../DataflowPipelineTranslatorTest.java | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 9b2218340c..a65bc0a077 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -45,6 +45,8 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.PubsubIO; +import com.google.cloud.dataflow.sdk.io.PubsubIO.PubsubTopic; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; @@ -747,6 +749,84 @@ public void testToIterableTranslation() throws Exception { assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); } + @Test + public void testPubsubIOReadTranslation() throws Exception { + // A "change detector" test that makes sure the translation of PubsubIO.Read + // does not change in bad ways during refactor + String project = "fakeproject"; + String topicName = "faketopic"; + PubsubTopic topic = + PubsubTopic.fromPath(String.format("projects/%s/topics/%s", project, topicName)); + + DataflowPipelineOptions options = buildPipelineOptions(); + options.setStreaming(true); + DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); + + DataflowPipeline pipeline = DataflowPipeline.create(options); + pipeline.apply(PubsubIO.Read.topic(topic.asPath())); + Job job = + translator + .translate(pipeline, pipeline.getRunner(), Collections.emptyList()) + .getJob(); + + List steps = job.getSteps(); + assertEquals(1, steps.size()); + + Step pubsubStep = steps.get(0); + + // Ensure the core translation does not change; if we get this far, then the right translator + // was invoked, so we don't try to combinatorially test every combination of configuration + // options. That would be for the unit tests of that translator. + assertEquals("ParallelRead", pubsubStep.getKind()); + assertEquals("pubsub", Structs.getString(pubsubStep.getProperties(), PropertyNames.FORMAT)); + assertEquals( + topic.asV1Beta1Path(), + Structs.getString(pubsubStep.getProperties(), PropertyNames.PUBSUB_TOPIC)); + assertEquals( + "PubsubIO.Read", Structs.getString(pubsubStep.getProperties(), PropertyNames.USER_NAME)); + } + + @Test + public void testPubsubIOWriteTranslation() throws Exception { + // A "change detector" test that makes sure the translation of PubsubIO.Read + // does not change in bad ways during refactor + String project = "fakeproject"; + String topicName = "faketopic"; + PubsubTopic topic = + PubsubTopic.fromPath(String.format("projects/%s/topics/%s", project, topicName)); + + DataflowPipelineOptions options = buildPipelineOptions(); + options.setStreaming(true); + DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); + + DataflowPipeline pipeline = DataflowPipeline.create(options); + pipeline.apply(Create.of("hello", "goodbye")) + .apply(PubsubIO.Write.topic(topic.asPath())); + Job job = + translator + .translate(pipeline, pipeline.getRunner(), Collections.emptyList()) + .getJob(); + + // There are 6 steps from the Create and 1 from the PubsubIO.Write + List steps = job.getSteps(); + assertEquals(7, steps.size()); + + Step prepStep = steps.get(5); + Step writeStep = steps.get(6); + + // Ensure the core translation does not change; if we get this far, then the right translator + // was invoked, so we don't try to combinatorially test every combination of configuration + // options. That would be for the unit tests of that translator. + assertEquals("ParallelWrite", writeStep.getKind()); + assertEquals("pubsub", Structs.getString(writeStep.getProperties(), PropertyNames.FORMAT)); + assertEquals( + topic.asV1Beta1Path(), + Structs.getString(writeStep.getProperties(), PropertyNames.PUBSUB_TOPIC)); + assertEquals( + "PubsubIO.Write/StreamingPubsubIOWrite", + Structs.getString(writeStep.getProperties(), PropertyNames.USER_NAME)); + } + @Test public void testToSingletonTranslationWithIsmSideInput() throws Exception { // A "change detector" test that makes sure the translation From 23221a892bbc668f6d2efd968f4129d1916e779e Mon Sep 17 00:00:00 2001 From: peihe Date: Mon, 23 May 2016 20:02:14 -0700 Subject: [PATCH 432/751] Backport PR from Beam: "define executingProject, and use it for creating BigQuery jobs" (#282) * Backport PR from Beam: "define executingProject, and use it for creating BigQuery jobs" * Verify in unit test that BigQuery executing project is used. * BigQueryIOTest: using a valid project name CamelCase is not valid GCP project name --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 73 ++++++++++--------- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 55 ++++++++++---- 2 files changed, 77 insertions(+), 51 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 813ccae48c..78f4529fd7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -557,34 +557,23 @@ public PCollection apply(PInput input) { String.format("Failed to resolve extract destination directory in %s", tempLocation)); } + final String executingProject = bqOptions.getProject(); if (!Strings.isNullOrEmpty(query)) { - String projectId = bqOptions.getProject(); String queryTempDatasetId = "temp_dataset_" + uuid; String queryTempTableId = "temp_table_" + uuid; TableReference queryTempTableRef = new TableReference() - .setProjectId(projectId) + .setProjectId(executingProject) .setDatasetId(queryTempDatasetId) .setTableId(queryTempTableId); - String jsonQueryTempTable; - try { - jsonQueryTempTable = JSON_FACTORY.toString(queryTempTableRef); - } catch (IOException e) { - throw new RuntimeException("Cannot initialize table to JSON strings.", e); - } source = BigQueryQuerySource.create( - jobIdToken, query, jsonQueryTempTable, flattenResults, + jobIdToken, query, queryTempTableRef, flattenResults, extractDestinationDir, bqServices); } else { - String jsonTable; - try { - jsonTable = JSON_FACTORY.toString(getTableWithDefaultProject(bqOptions)); - } catch (IOException e) { - throw new RuntimeException("Cannot initialize table to JSON strings.", e); - } + TableReference inputTable = getTableWithDefaultProject(bqOptions); source = BigQueryTableSource.create( - jobIdToken, jsonTable, extractDestinationDir, bqServices); + jobIdToken, inputTable, extractDestinationDir, bqServices, executingProject); } PassThroughThenCleanup.CleanupOperation cleanupOperation = new PassThroughThenCleanup.CleanupOperation() { @@ -593,7 +582,7 @@ void cleanup(PipelineOptions options) throws Exception { BigQueryOptions bqOptions = options.as(BigQueryOptions.class); JobReference jobRef = new JobReference() - .setProjectId(bqOptions.getProject()) + .setProjectId(executingProject) .setJobId(getExtractJobId(jobIdToken)); Job extractJob = bqServices.getJobService(bqOptions).pollJob( jobRef, CLEANUP_JOB_POLL_MAX_RETRIES); @@ -757,10 +746,12 @@ static class BigQueryTableSource extends BigQuerySourceBase { static BigQueryTableSource create( String jobIdToken, - String jsonTable, + TableReference table, String extractDestinationDir, - BigQueryServices bqServices) { - return new BigQueryTableSource(jobIdToken, jsonTable, extractDestinationDir, bqServices); + BigQueryServices bqServices, + String executingProject) { + return new BigQueryTableSource( + jobIdToken, table, extractDestinationDir, bqServices, executingProject); } private final String jsonTable; @@ -768,11 +759,12 @@ static BigQueryTableSource create( private BigQueryTableSource( String jobIdToken, - String jsonTable, + TableReference table, String extractDestinationDir, - BigQueryServices bqServices) { - super(jobIdToken, extractDestinationDir, bqServices); - this.jsonTable = checkNotNull(jsonTable, "jsonTable"); + BigQueryServices bqServices, + String executingProject) { + super(jobIdToken, extractDestinationDir, bqServices, executingProject); + this.jsonTable = toJsonString(checkNotNull(table, "table")); this.tableSizeBytes = new AtomicReference<>(); } @@ -822,12 +814,12 @@ static class BigQueryQuerySource extends BigQuerySourceBase { static BigQueryQuerySource create( String jobIdToken, String query, - String jsonQueryTempTable, + TableReference queryTempTableRef, Boolean flattenResults, String extractDestinationDir, BigQueryServices bqServices) { return new BigQueryQuerySource( - jobIdToken, query, jsonQueryTempTable, flattenResults, extractDestinationDir, bqServices); + jobIdToken, query, queryTempTableRef, flattenResults, extractDestinationDir, bqServices); } private final String query; @@ -838,13 +830,14 @@ static BigQueryQuerySource create( private BigQueryQuerySource( String jobIdToken, String query, - String jsonQueryTempTable, + TableReference queryTempTableRef, Boolean flattenResults, String extractDestinationDir, BigQueryServices bqServices) { - super(jobIdToken, extractDestinationDir, bqServices); + super(jobIdToken, extractDestinationDir, bqServices, + checkNotNull(queryTempTableRef, "queryTempTableRef").getProjectId()); this.query = checkNotNull(query, "query"); - this.jsonQueryTempTable = checkNotNull(jsonQueryTempTable, "jsonQueryTempTable"); + this.jsonQueryTempTable = toJsonString(queryTempTableRef); this.flattenResults = checkNotNull(flattenResults, "flattenResults"); this.dryRunJobStats = new AtomicReference<>(); } @@ -859,7 +852,7 @@ public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { public BoundedReader createReader(PipelineOptions options) throws IOException { BigQueryOptions bqOptions = options.as(BigQueryOptions.class); return new BigQueryReader(this, bqServices.getReaderFromQuery( - bqOptions, query, bqOptions.getProject(), flattenResults)); + bqOptions, query, executingProject, flattenResults)); } @Override @@ -885,7 +878,12 @@ protected TableReference getTableToExtract(BigQueryOptions bqOptions) // 3. Execute the query. String queryJobId = jobIdToken + "-query"; executeQuery( - queryJobId, query, tableToExtract, flattenResults, bqServices.getJobService(bqOptions)); + executingProject, + queryJobId, + query, + tableToExtract, + flattenResults, + bqServices.getJobService(bqOptions)); return tableToExtract; } @@ -910,22 +908,22 @@ public void populateDisplayData(DisplayData.Builder builder) { private synchronized JobStatistics dryRunQueryIfNeeded(BigQueryOptions bqOptions) throws InterruptedException, IOException { if (dryRunJobStats.get() == null) { - String projectId = bqOptions.getProject(); JobStatistics jobStats = - bqServices.getJobService(bqOptions).dryRunQuery(projectId, query); + bqServices.getJobService(bqOptions).dryRunQuery(executingProject, query); dryRunJobStats.compareAndSet(null, jobStats); } return dryRunJobStats.get(); } private static void executeQuery( + String executingProject, String jobId, String query, TableReference destinationTable, boolean flattenResults, JobService jobService) throws IOException, InterruptedException { JobReference jobRef = new JobReference() - .setProjectId(destinationTable.getProjectId()) + .setProjectId(executingProject) .setJobId(jobId); JobConfigurationQuery queryConfig = new JobConfigurationQuery(); queryConfig @@ -976,14 +974,17 @@ private abstract static class BigQuerySourceBase extends BoundedSource protected final String jobIdToken; protected final String extractDestinationDir; protected final BigQueryServices bqServices; + protected final String executingProject; private BigQuerySourceBase( String jobIdToken, String extractDestinationDir, - BigQueryServices bqServices) { + BigQueryServices bqServices, + String executingProject) { this.jobIdToken = checkNotNull(jobIdToken, "jobIdToken"); this.extractDestinationDir = checkNotNull(extractDestinationDir, "extractDestinationDir"); this.bqServices = checkNotNull(bqServices, "bqServices"); + this.executingProject = checkNotNull(executingProject, "executingProject"); } @Override @@ -1027,7 +1028,7 @@ private List executeExtract( String jobId, TableReference table, JobService jobService) throws InterruptedException, IOException { JobReference jobRef = new JobReference() - .setProjectId(table.getProjectId()) + .setProjectId(executingProject) .setJobId(jobId); String destinationUri = getExtractDestinationUri(extractDestinationDir); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index f7530e99e0..f34124767d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -19,6 +19,7 @@ import static com.google.cloud.dataflow.sdk.io.BigQueryIO.fromJsonString; import static com.google.cloud.dataflow.sdk.io.BigQueryIO.toJsonString; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.common.base.Preconditions.checkArgument; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertEquals; @@ -29,6 +30,7 @@ import static org.mockito.Mockito.when; import com.google.api.client.util.Data; +import com.google.api.client.util.Strings; import com.google.api.services.bigquery.model.ErrorProto; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfigurationExtract; @@ -208,6 +210,7 @@ private static class FakeJobService implements JobService, Serializable { private Object[] startJobReturns; private Object[] pollJobReturns; + private String executingProject; // Both counts will be reset back to zeros after serialization. // This is a work around for DoFn's verifyUnmodified check. private transient int startJobCallsCount; @@ -241,27 +244,42 @@ public FakeJobService pollJobReturns(Object... pollJobReturns) { return this; } + /** + * Verifies executing project. + */ + public FakeJobService verifyExecutingProject(String executingProject) { + this.executingProject = executingProject; + return this; + } + @Override public void startLoadJob(JobReference jobRef, JobConfigurationLoad loadConfig) throws InterruptedException, IOException { - startJob(); + startJob(jobRef); } @Override public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) throws InterruptedException, IOException { - startJob(); + startJob(jobRef); } @Override public void startQueryJob(JobReference jobRef, JobConfigurationQuery query) throws IOException, InterruptedException { - startJob(); + startJob(jobRef); } @Override public Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException { + if (!Strings.isNullOrEmpty(executingProject)) { + checkArgument( + jobRef.getProjectId().equals(executingProject), + "Project id: %s is not equal to executing project: %s", + jobRef.getProjectId(), executingProject); + } + if (pollJobStatusCallsCount < pollJobReturns.length) { Object ret = pollJobReturns[pollJobStatusCallsCount++]; if (ret instanceof Job) { @@ -279,7 +297,14 @@ public Job pollJob(JobReference jobRef, int maxAttempts) } } - private void startJob() throws IOException, InterruptedException { + private void startJob(JobReference jobRef) throws IOException, InterruptedException { + if (!Strings.isNullOrEmpty(executingProject)) { + checkArgument( + jobRef.getProjectId().equals(executingProject), + "Project id: %s is not equal to executing project: %s", + jobRef.getProjectId(), executingProject); + } + if (startJobCallsCount < startJobReturns.length) { Object ret = startJobReturns[startJobCallsCount++]; if (ret instanceof IOException) { @@ -482,7 +507,8 @@ public void testReadFromTable() { FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() .withJobService(new FakeJobService() .startJobReturns("done", "done") - .pollJobReturns(Status.UNKNOWN)) + .pollJobReturns(Status.UNKNOWN) + .verifyExecutingProject(bqOptions.getProject())) .readerReturns( toJsonString(new TableRow().set("name", "a").set("number", 1)), toJsonString(new TableRow().set("name", "b").set("number", 2)), @@ -490,7 +516,7 @@ public void testReadFromTable() { Pipeline p = TestPipeline.create(bqOptions); PCollection output = p - .apply(BigQueryIO.Read.from("foo.com:project:somedataset.sometable") + .apply(BigQueryIO.Read.from("non-executing-project:somedataset.sometable") .withTestServices(fakeBqServices) .withoutValidation()) .apply(ParDo.of(new DoFn() { @@ -927,10 +953,10 @@ public void testBigQueryTableSourceThroughJsonAPI() throws Exception { toJsonString(new TableRow().set("name", "c").set("number", "3"))); String jobIdToken = "testJobIdToken"; - String jsonTable = toJsonString(BigQueryIO.parseTableSpec("project.data_set.table_name")); + TableReference table = BigQueryIO.parseTableSpec("project:data_set.table_name"); String extractDestinationDir = "mock://tempLocation"; - BoundedSource bqSource = - BigQueryTableSource.create(jobIdToken, jsonTable, extractDestinationDir, fakeBqServices); + BoundedSource bqSource = BigQueryTableSource.create( + jobIdToken, table, extractDestinationDir, fakeBqServices, "project"); List expected = ImmutableList.of( new TableRow().set("name", "a").set("number", "1"), @@ -964,10 +990,10 @@ public void testBigQueryTableSourceInitSplit() throws Exception { toJsonString(new TableRow().set("name", "c").set("number", "3"))); String jobIdToken = "testJobIdToken"; - String jsonTable = toJsonString(BigQueryIO.parseTableSpec("project.data_set.table_name")); + TableReference table = BigQueryIO.parseTableSpec("project:data_set.table_name"); String extractDestinationDir = "mock://tempLocation"; - BoundedSource bqSource = - BigQueryTableSource.create(jobIdToken, jsonTable, extractDestinationDir, fakeBqServices); + BoundedSource bqSource = BigQueryTableSource.create( + jobIdToken, table, extractDestinationDir, fakeBqServices, "project"); List expected = ImmutableList.of( new TableRow().set("name", "a").set("number", "1"), @@ -1030,10 +1056,9 @@ public void testBigQueryQuerySourceInitSplit() throws Exception { String jobIdToken = "testJobIdToken"; String extractDestinationDir = "mock://tempLocation"; - TableReference destinationTable = BigQueryIO.parseTableSpec("project.data_set.table_name"); - String jsonDestinationTable = toJsonString(destinationTable); + TableReference destinationTable = BigQueryIO.parseTableSpec("project:data_set.table_name"); BoundedSource bqSource = BigQueryQuerySource.create( - jobIdToken, "query", jsonDestinationTable, true /* flattenResults */, + jobIdToken, "query", destinationTable, true /* flattenResults */, extractDestinationDir, fakeBqServices); List expected = ImmutableList.of( From 0722f0c7ee9b1c6b8203b7c050ce32b2db3e55e4 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 25 May 2016 11:37:26 -0700 Subject: [PATCH 433/751] Backport: Evaluate display data from InProcessPipelineRunner (#286) * Evaluate display data from InProcessPipelineRunner Display data can be added to any PTransform to be used for display from any runner. Runners are not required to consume display data, and currently many don't. This changes InProcessRunner to consumer display data (and then discard it) in order to validate that display data is properly implemented on transforms within a pipeline. Exceptions thrown within HasDisplayData implementations will cause Pipeline.run() to fail. (cherry picked from commit ac98c4a01f7e4b2bba3e99271b66e141e7555de8) --- .../sdk/options/ProxyInvocationHandler.java | 7 +- .../inprocess/DisplayDataValidator.java | 71 +++++++++++++++++++ .../inprocess/InProcessPipelineRunner.java | 2 + .../sdk/transforms/display/DisplayData.java | 14 +++- .../InProcessPipelineRunnerTest.java | 64 +++++++++++++++++ .../transforms/display/DisplayDataTest.java | 19 +++++ 6 files changed, 173 insertions(+), 4 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index f353ab3af0..e865a226e4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -84,7 +84,7 @@ * {@link PipelineOptions#as(Class)}. */ @ThreadSafe -class ProxyInvocationHandler implements InvocationHandler { +class ProxyInvocationHandler implements InvocationHandler, HasDisplayData { private static final ObjectMapper MAPPER = new ObjectMapper(); /** * No two instances of this class are considered equivalent hence we generate a random hash code @@ -141,7 +141,8 @@ public Object invoke(Object proxy, Method method, Object[] args) { && args[0] instanceof DisplayData.Builder) { @SuppressWarnings("unchecked") DisplayData.Builder builder = (DisplayData.Builder) args[0]; - populateDisplayData(builder); + // Explicitly set display data namespace so thrown exceptions will have sensible type. + builder.include(this, PipelineOptions.class); return Void.TYPE; } String methodName = method.getName(); @@ -302,7 +303,7 @@ public int hashCode() { * Populate display data. See {@link HasDisplayData#populateDisplayData}. All explicitly set * pipeline options will be added as display data. */ - private void populateDisplayData(DisplayData.Builder builder) { + public void populateDisplayData(DisplayData.Builder builder) { Set optionSpecs = PipelineOptionsReflector.getOptionSpecs(knownInterfaces); Multimap optionsMap = buildOptionNameToSpecMap(optionSpecs); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java new file mode 100644 index 0000000000..a0d9b86fb9 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; +import com.google.cloud.dataflow.sdk.values.PValue; + +/** + * Validate correct implementation of {@link DisplayData} by evaluating + * {@link HasDisplayData#populateDisplayData(DisplayData.Builder)} during pipeline construction. + */ +class DisplayDataValidator { + // Do not instantiate + private DisplayDataValidator() {} + + static void validatePipeline(Pipeline pipeline) { + validateOptions(pipeline); + validateTransforms(pipeline); + } + + private static void validateOptions(Pipeline pipeline) { + evaluateDisplayData(pipeline.getOptions()); + } + + private static void validateTransforms(Pipeline pipeline) { + pipeline.traverseTopologically(Visitor.INSTANCE); + } + + private static void evaluateDisplayData(HasDisplayData component) { + DisplayData.from(component); + } + + private static class Visitor implements Pipeline.PipelineVisitor { + private static final Visitor INSTANCE = new Visitor(); + + @Override + public void enterCompositeTransform(TransformTreeNode node) { + if (!node.isRootNode()) { + evaluateDisplayData(node.getTransform()); + } + } + + @Override + public void visitTransform(TransformTreeNode node) { + evaluateDisplayData(node.getTransform()); + } + + @Override + public void leaveCompositeTransform(TransformTreeNode node) {} + + @Override + public void visitValue(PValue value, TransformTreeNode producer) {} + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 5a97167325..30631f3121 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -223,6 +223,8 @@ public InProcessPipelineResult run(Pipeline pipeline) { GroupByKey.class, InProcessGroupByKeyOnly.class)); pipeline.traverseTopologically(keyedPValueVisitor); + DisplayDataValidator.validatePipeline(pipeline); + InProcessEvaluationContext context = InProcessEvaluationContext.create( getPipelineOptions(), diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 07a0ae84fe..9588aaadbe 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -654,10 +654,13 @@ public Builder include(HasDisplayData subComponent, String namespace) { try { subComponent.populateDisplayData(this); + } catch (PopulateDisplayDataException e) { + // Don't re-wrap exceptions recursively. + throw e; } catch (Throwable e) { String msg = String.format("Error while populating display data for component: %s", namespace); - throw new RuntimeException(msg, e); + throw new PopulateDisplayDataException(msg, e); } this.latestNs = prevNs; @@ -666,6 +669,15 @@ public Builder include(HasDisplayData subComponent, String namespace) { return this; } + /** + * Marker exception class for exceptions encountered while populating display data. + */ + private class PopulateDisplayDataException extends RuntimeException { + PopulateDisplayDataException(String message, Throwable cause) { + super(message, cause); + } + } + @Override public Builder add(Item item) { checkNotNull(item, "Input display item cannot be null"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java index adb64cd625..38cc62daef 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static org.hamcrest.Matchers.is; + import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; @@ -22,12 +24,19 @@ import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.MapElements; +import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Rule; import org.junit.Test; +import org.junit.internal.matchers.ThrowableMessageMatcher; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -38,6 +47,8 @@ */ @RunWith(JUnit4.class) public class InProcessPipelineRunnerTest implements Serializable { + @Rule public transient ExpectedException thrown = ExpectedException.none(); + @Test public void wordCountShouldSucceed() throws Throwable { Pipeline p = getPipeline(); @@ -66,6 +77,59 @@ public String apply(KV input) { result.awaitCompletion(); } + @Test + public void transformDisplayDataExceptionShouldFail() { + DoFn brokenDoFn = new DoFn() { + @Override + public void processElement(ProcessContext c) throws Exception {} + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + throw new RuntimeException("oh noes!"); + } + }; + + Pipeline p = getPipeline(); + p + .apply(Create.of(1, 2, 3)) + .apply(ParDo.of(brokenDoFn)); + + thrown.expectMessage(brokenDoFn.getClass().getName()); + thrown.expectCause(ThrowableMessageMatcher.hasMessage(is("oh noes!"))); + p.run(); + } + + @Test + public void pipelineOptionsDisplayDataExceptionShouldFail() { + Object brokenValueType = new Object() { + @JsonValue + public int getValue () { + return 42; + } + + @Override + public String toString() { + throw new RuntimeException("oh noes!!"); + } + }; + + Pipeline p = getPipeline(); + p.getOptions().as(ObjectPipelineOptions.class).setValue(brokenValueType); + + p.apply(Create.of(1, 2, 3)); + + thrown.expectMessage(PipelineOptions.class.getName()); + thrown.expectCause(ThrowableMessageMatcher.hasMessage(is("oh noes!!"))); + p.run(); + } + + /** {@link PipelineOptions} to inject broken object type. */ + public interface ObjectPipelineOptions extends PipelineOptions { + Object getValue(); + void setValue(Object value); + } + + private Pipeline getPipeline() { PipelineOptions opts = PipelineOptionsFactory.create(); opts.setRunner(InProcessPipelineRunner.class); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index 1114c91a3a..039e33da3d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -1023,6 +1023,25 @@ public void populateDisplayData(Builder builder) { DisplayData.from(component); } + @Test + public void testExceptionsNotWrappedRecursively() { + final RuntimeException cause = new RuntimeException("oh noes!"); + HasDisplayData component = new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + builder.include(new HasDisplayData() { + @Override + public void populateDisplayData(Builder builder) { + throw cause; + } + }); + } + }; + + thrown.expectCause(is(cause)); + DisplayData.from(component); + } + private static class IdentityTransform extends PTransform, PCollection> { @Override public PCollection apply(PCollection input) { From a20cd6787428d8dc306e0371f2466406f1b896e4 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Wed, 25 May 2016 14:08:03 -0700 Subject: [PATCH 434/751] Clear PubsubUnboundedSource checkpoint state which is not needed for restore. Allows same checkpoint object to be passed to new reader without a serialize/deserialize step. --- .../google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java index 6c60877811..6910824287 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java @@ -232,7 +232,7 @@ public long identity() { static class PubsubCheckpoint implements UnboundedSource.CheckpointMark { /** * If the checkpoint is for persisting: the reader who's snapshotted state we are persisting. - * If the checkpoint is for restoring: initially {@literal null}, then explicitly set. + * If the checkpoint is for restoring: {@literal null}. * Not persisted in durable checkpoint. * CAUTION: Between a checkpoint being taken and {@link #finalizeCheckpoint()} being called * the 'true' active reader may have changed. @@ -247,7 +247,7 @@ static class PubsubCheckpoint implements UnboundedSource.CheckpointMark { * Not persisted in durable checkpoint. */ @Nullable - private final List safeToAckIds; + private List safeToAckIds; /** * If the checkpoint is for persisting: The ACK ids of messages which have been received @@ -298,6 +298,8 @@ public void finalizeCheckpoint() throws IOException { } finally { checkState(reader.numInFlightCheckpoints.decrementAndGet() >= 0, "Miscounted in-flight checkpoints"); + reader = null; + safeToAckIds = null; } } From 794ac5e26b44f264e130ae44c880e910b7059a12 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Tue, 24 May 2016 10:16:49 -0700 Subject: [PATCH 435/751] Backport https://github.com/apache/incubator-beam/pull/380 --- .../dataflow/sdk/util/ActiveWindowSet.java | 109 +++---- .../sdk/util/MergingActiveWindowSet.java | 296 +++++------------- .../sdk/util/NonMergingActiveWindowSet.java | 18 +- .../dataflow/sdk/util/ReduceFnRunner.java | 189 ++++++----- .../sdk/util/MergingActiveWindowSetTest.java | 223 +++++++++---- .../dataflow/sdk/util/TriggerTester.java | 26 +- 6 files changed, 417 insertions(+), 444 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java index 55ebaed849..f93b81dcf1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java @@ -19,47 +19,44 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.common.annotations.VisibleForTesting; + import java.util.Collection; import java.util.Set; -import javax.annotation.Nullable; - /** - * Track which active windows have their state associated with merged-away windows. + * Track which windows are active, and the state address window(s) under which their + * state is stored. Also help with the multi-step process of merging windows and their associated + * state. + * + *

          When windows are merged we must also merge their state. For example, we may need to + * concatenate buffered elements, sum a count of elements, or find a new minimum timestamp. + * If we start with two windows {@code Wa} and {@code Wb} and later discover they should be + * merged into window {@code Wab} then, naively, we must copy and merge the states of {@code Wa} + * and {@code Wab} into {@code Wab}. * - * When windows are merged we must track which state previously associated with the merged windows - * must now be associated with the result window. Some of that state may be combined eagerly when - * the windows are merged. The rest is combined lazily when the final state is actually - * required when emitting a pane. We keep track of this using an {@link ActiveWindowSet}. + *

          However, the common case for merging windows is for a new window to be merged into an + * existing window. Thus, if {@code Wa} is the existing window and {@code Wb} the new window it + * is more efficient to leave the state for {@code Wa} where it is, and simply redirect {@code + * Wab} to it. In this case we say {@code Wab} has a state address window of {@code Wa}. * - *

          An {@link ActiveWindowSet} considers a window to be in one of the following states: + *

          Even if windows {@code Wa} and {@code Wb} already have state, it can still be more efficient + * to append the state of {@code Wb} onto {@code Wa} rather than copy the state from {@code Wa} + * and {@code Wb} into {@code Wab}. * + *

          We use the following terminology for windows: *

            - *
          1. NEW: The initial state for a window on an incoming element; we do not yet know - * if it should be merged into an ACTIVE window, or whether it is already present as an - * ACTIVE window, since we have not yet called - * {@link WindowFn#mergeWindows}.
          2. - *
          3. ACTIVE: A window that has state associated with it and has not itself been merged - * away. The window may have one or more state address windows under which its - * non-empty state is stored. A state value for an ACTIVE window must be derived by reading - * the state in all of its state address windows.
          4. - *
          5. EPHEMERAL: A NEW window that has been merged into an ACTIVE window before any state - * has been associated with that window. Thus the window is neither ACTIVE nor MERGED. These - * windows are not persistently represented since if they reappear the merge function should - * again redirect them to an ACTIVE window. EPHEMERAL windows are an optimization for - * the common case of in-order events and {@link Sessions session window} by never associating - * state with windows that are created and immediately merged away.
          6. - *
          7. MERGED: An ACTIVE window has been merged into another ACTIVE window after it had - * state associated with it. The window will thus appear as a state address window for exactly - * one ACTIVE window.
          8. - *
          9. EXPIRED: The window has expired and may have been garbage collected. No new elements - * (even late elements) will ever be assigned to that window. These windows are not explicitly - * represented anywhere; it is expected that the user of {@link ActiveWindowSet} will store - * no state associated with the window.
          10. + *
          11. ACTIVE: A window that has state associated with it and has not itself been merged + * away. The window may have one (or more) state address windows under which its + * non-empty state is stored. A state value for an ACTIVE window must be derived by reading + * the state in (all of) its state address windows. Note that only pre 1.4 pipelines + * use multiple state address windows per active window. From 1.4 onwards we eagerly merge + * window state into a single state address window. + *
          12. NEW: The initial state for a window of an incoming element which is not + * already ACTIVE. We have not yet called {@link WindowFn#mergeWindows}, and so don't yet know + * whether the window will be be merged into another NEW or ACTIVE window, or will + * become an ACTIVE window in its own right. *
          * - *

          - * *

          If no windows will ever be merged we can use the trivial implementation {@link * NonMergingActiveWindowSet}. Otherwise, the actual implementation of this data structure is in * {@link MergingActiveWindowSet}. @@ -74,27 +71,25 @@ public interface MergeCallback { /** * Called when windows are about to be merged, but before any {@link #onMerge} callback * has been made. + * + * @param toBeMerged the windows about to be merged. + * @param mergeResult the result window, either a member of {@code toBeMerged} or new. */ - void prefetchOnMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) - throws Exception; + void prefetchOnMerge(Collection toBeMerged, W mergeResult) throws Exception; /** * Called when windows are about to be merged, after all {@link #prefetchOnMerge} calls * have been made, but before the active window set has been updated to reflect the merge. * - * @param toBeMerged the windows about to be merged. - * @param activeToBeMerged the subset of {@code toBeMerged} corresponding to windows which - * are currently ACTIVE (and about to be merged). The remaining windows have been deemed - * EPHEMERAL, and thus have no state associated with them. + * @param toBeMerged the windows about to be merged. * @param mergeResult the result window, either a member of {@code toBeMerged} or new. */ - void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) - throws Exception; + void onMerge(Collection toBeMerged, W mergeResult) throws Exception; } /** - * Remove EPHEMERAL windows and remaining NEW windows since we only need to know about them - * while processing new elements. + * Remove any remaining NEW windows since they were not promoted to being ACTIVE + * by {@link #ensureWindowIsActive} and we don't need to record anything about them. */ void cleanupTemporaryWindows(); @@ -104,42 +99,40 @@ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeRe void persist(); /** - * Return the ACTIVE window into which {@code window} has been merged. - * Return {@code window} itself if it is ACTIVE. Return null if {@code window} has not - * yet been seen. + * Return (a view of) the set of currently ACTIVE and NEW windows. */ - @Nullable - W mergeResultWindow(W window); + Set getActiveAndNewWindows(); /** - * Return (a view of) the set of currently ACTIVE windows. + * Return {@code true} if {@code window} is ACTIVE. */ - Set getActiveWindows(); + boolean isActive(W window); /** - * Return {@code true} if {@code window} is ACTIVE. + * Return {@code true} if {@code window} is ACTIVE or NEW. */ - boolean isActive(W window); + boolean isActiveOrNew(W window); /** * Called when an incoming element indicates it is a member of {@code window}, but before we * have started processing that element. If {@code window} is not already known to be ACTIVE, - * MERGED or EPHEMERAL then add it as NEW. + * then add it as NEW. */ void ensureWindowExists(W window); /** * Called when a NEW or ACTIVE window is now known to be ACTIVE. - * Ensure that if it is NEW then it becomes ACTIVE (with itself as its only state address window). + * Ensure that if it is NEW then it becomes ACTIVE (with itself as its only state address + * window). */ void ensureWindowIsActive(W window); /** - * If {@code window} is not already known to be ACTIVE, MERGED or EPHEMERAL then add it - * as ACTIVE. + * If {@code window} is not already known to be ACTIVE then add it as ACTIVE. + * For testing only. */ @VisibleForTesting - void addActive(W window); + void addActiveForTesting(W window); /** * Remove {@code window} from the set. @@ -148,9 +141,9 @@ void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeRe /** * Invoke {@link WindowFn#mergeWindows} on the {@code WindowFn} associated with this window set, - * merging as many of the active windows as possible. {@code mergeCallback} will be invoked for - * each group of windows that are merged. After this no NEW windows will remain, all merge - * result windows will be ACTIVE, and all windows which have been merged away will not be ACTIVE. + * merging as many of the NEW and ACTIVE windows as possible. {@code mergeCallback} will be + * invoked for each group of windows that are merged. After this all merge result windows will + * be ACTIVE, and all windows which have been merged away will be neither ACTIVE nor NEW. */ void merge(MergeCallback mergeCallback) throws Exception; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java index ae50facd03..4b0036ed1b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java @@ -27,6 +27,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collection; @@ -36,70 +37,30 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; /** * An {@link ActiveWindowSet} for merging {@link WindowFn} implementations. - * - *

          The underlying notion of {@link MergingActiveWindowSet} is that of representing equivalence - * classes of merged windows as a mapping from the merged "super-window" to a set of - * state address windows in which some state has been persisted. The mapping need not - * contain EPHEMERAL windows, because they are created and merged without any persistent state. - * Each window must be a state address window for at most one window, so the mapping is - * invertible. - * - *

          The states of a non-expired window are treated as follows: - * - *

            - *
          • NEW: a NEW has an empty set of associated state address windows.
          • - *
          • ACTIVE: an ACTIVE window will be associated with some nonempty set of state - * address windows. If the window has not merged, this will necessarily be the singleton set - * containing just itself, but it is not required that an ACTIVE window be amongst its - * state address windows.
          • - *
          • MERGED: a MERGED window will be in the set of associated windows for some - * other window - that window is retrieved via {@link #representative} (this reverse - * association is implemented in O(1) time).
          • - *
          • EPHEMERAL: EPHEMERAL windows are not persisted but are tracked transiently; - * an EPHEMERAL window must be registered with this {@link ActiveWindowSet} by a call - * to {@link #recordMerge} prior to any request for a {@link #representative}.
          • - *
          - * - *

          To illustrate why an ACTIVE window need not be amongst its own state address windows, - * consider two active windows W1 and W2 that are merged to form W12. Further writes may be - * applied to either of W1 or W2, since a read of W12 implies reading both of W12 and merging - * their results. Hence W12 need not have state directly associated with it. */ public class MergingActiveWindowSet implements ActiveWindowSet { private final WindowFn windowFn; - /** - * Map ACTIVE and NEW windows to their state address windows. Persisted. - */ - private final Map> activeWindowToStateAddressWindows; /** - * As above, but only for EPHEMERAL windows. Does not need to be persisted. - */ - private final Map> activeWindowToEphemeralWindows; - - /** - * A map from window to the ACTIVE window it has been merged into. Does not need to be persisted. - *

          + * Map ACTIVE and NEW windows to their state address windows. Persisted. *

            - *
          • Key window may be ACTIVE, MERGED or EPHEMERAL. - *
          • ACTIVE windows map to themselves. - *
          • If W1 maps to W2 then W2 is in {@link #activeWindowToStateAddressWindows}. - *
          • If W1 = W2 then W1 is ACTIVE. If W1 is in the state address window set for W2 then W1 is - * MERGED. Otherwise W1 is EPHEMERAL. + *
          • A NEW window has the empty set as its value. + *
          • An ACTIVE window has its (typically singleton) set of state address windows as + * its value. *
          */ - private final Map windowToActiveWindow; + private final Map> activeWindowToStateAddressWindows; /** * Deep clone of {@link #activeWindowToStateAddressWindows} as of last commit. - *

          - *

          Used to avoid writing to state if no changes have been made during the work unit. + * Used to avoid writing to state if no changes have been made during the work unit. */ private final Map> originalActiveWindowToStateAddressWindows; @@ -111,42 +72,32 @@ public class MergingActiveWindowSet implements ActiveWi public MergingActiveWindowSet(WindowFn windowFn, StateInternals state) { this.windowFn = windowFn; - StateTag>>> mergeTreeAddr = + StateTag>>> tag = StateTags.makeSystemTagInternal(StateTags.value( "tree", MapCoder.of(windowFn.windowCoder(), SetCoder.of(windowFn.windowCoder())))); - valueState = state.state(StateNamespaces.global(), mergeTreeAddr); - // Little use trying to prefetch this state since the ReduceFnRunner is stymied until it is - // available. + valueState = state.state(StateNamespaces.global(), tag); + // Little use trying to prefetch this state since the ReduceFnRunner + // is stymied until it is available. activeWindowToStateAddressWindows = emptyIfNull(valueState.read()); - activeWindowToEphemeralWindows = new HashMap<>(); originalActiveWindowToStateAddressWindows = deepCopy(activeWindowToStateAddressWindows); - windowToActiveWindow = invert(activeWindowToStateAddressWindows); } @Override public void cleanupTemporaryWindows() { - // All NEW windows can be forgotten. - Iterator>> iter = - activeWindowToStateAddressWindows.entrySet().iterator(); + // All NEW windows can be forgotten since they must have ended up being merged into + // some other ACTIVE window. + Iterator>> iter = activeWindowToStateAddressWindows.entrySet().iterator(); while (iter.hasNext()) { Map.Entry> entry = iter.next(); if (entry.getValue().isEmpty()) { - windowToActiveWindow.remove(entry.getKey()); iter.remove(); } } - - // All EPHEMERAL windows can be forgotten. - for (Map.Entry> entry : activeWindowToEphemeralWindows.entrySet()) { - for (W ephemeral : entry.getValue()) { - windowToActiveWindow.remove(ephemeral); - } - } - activeWindowToEphemeralWindows.clear(); } @Override public void persist() { + checkInvariants(); if (activeWindowToStateAddressWindows.isEmpty()) { // Force all persistent state to disappear. valueState.clear(); @@ -156,42 +107,32 @@ public void persist() { // No change. return; } - // All NEW windows must have been accounted for. - for (Map.Entry> entry : activeWindowToStateAddressWindows.entrySet()) { - Preconditions.checkState( - !entry.getValue().isEmpty(), "Cannot persist NEW window %s", entry.getKey()); - } - // Should be no EPHEMERAL windows. - Preconditions.checkState( - activeWindowToEphemeralWindows.isEmpty(), "Unexpected EPHEMERAL windows before persist"); - valueState.write(activeWindowToStateAddressWindows); // No need to update originalActiveWindowToStateAddressWindows since this object is about to // become garbage. } @Override - @Nullable - public W mergeResultWindow(W window) { - return windowToActiveWindow.get(window); + public Set getActiveAndNewWindows() { + return activeWindowToStateAddressWindows.keySet(); } @Override - public Set getActiveWindows() { - return activeWindowToStateAddressWindows.keySet(); + public boolean isActive(W window) { + Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); + return stateAddressWindows != null && !stateAddressWindows.isEmpty(); } @Override - public boolean isActive(W window) { + public boolean isActiveOrNew(W window) { return activeWindowToStateAddressWindows.containsKey(window); } @Override public void ensureWindowExists(W window) { - if (!windowToActiveWindow.containsKey(window)) { - Preconditions.checkState(!activeWindowToStateAddressWindows.containsKey(window)); + if (!activeWindowToStateAddressWindows.containsKey(window)) { + // Add window as NEW. activeWindowToStateAddressWindows.put(window, new LinkedHashSet()); - windowToActiveWindow.put(window, window); } } @@ -199,48 +140,40 @@ public void ensureWindowExists(W window) { public void ensureWindowIsActive(W window) { Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); Preconditions.checkState(stateAddressWindows != null, - "Cannot ensure window %s is active since it is neither ACTIVE nor NEW", - window); + "Cannot ensure window %s is active since it is neither ACTIVE nor NEW", + window); if (stateAddressWindows.isEmpty()) { - // Window was NEW, make it ACTIVE. - Preconditions.checkState(windowToActiveWindow.containsKey(window) - && windowToActiveWindow.get(window).equals(window)); + // Window was NEW, make it ACTIVE with itself as its state address window. stateAddressWindows.add(window); } } @Override @VisibleForTesting - public void addActive(W window) { - if (!windowToActiveWindow.containsKey(window)) { + public void addActiveForTesting(W window) { + if (!activeWindowToStateAddressWindows.containsKey(window)) { + // Make window ACTIVE with itself as its state address window. Set stateAddressWindows = new LinkedHashSet<>(); stateAddressWindows.add(window); activeWindowToStateAddressWindows.put(window, stateAddressWindows); - windowToActiveWindow.put(window, window); + } + } + + @VisibleForTesting + public void addActiveForTesting(W window, Iterable stateAddressWindows) { + if (!activeWindowToStateAddressWindows.containsKey(window)) { + activeWindowToStateAddressWindows.put(window, Sets.newLinkedHashSet(stateAddressWindows)); } } @Override public void remove(W window) { - Set stateAddressWindows = activeWindowToStateAddressWindows.remove(window); - if (stateAddressWindows != null) { - for (W stateAddressWindow : stateAddressWindows) { - windowToActiveWindow.remove(stateAddressWindow); - } - } - Set ephemeralWindows = activeWindowToEphemeralWindows.remove(window); - if (ephemeralWindows != null) { - for (W ephemeralWindow : ephemeralWindows) { - windowToActiveWindow.remove(ephemeralWindow); - } - } - windowToActiveWindow.remove(window); + activeWindowToStateAddressWindows.remove(window); } private class MergeContextImpl extends WindowFn.MergeContext { private MergeCallback mergeCallback; private final List> allToBeMerged; - private final List> allActiveToBeMerged; private final List allMergeResults; private final Set seen; @@ -248,7 +181,6 @@ public MergeContextImpl(MergeCallback mergeCallback) { windowFn.super(); this.mergeCallback = mergeCallback; allToBeMerged = new ArrayList<>(); - allActiveToBeMerged = new ArrayList<>(); allMergeResults = new ArrayList<>(); seen = new HashSet<>(); } @@ -264,12 +196,11 @@ public void merge(Collection toBeMerged, W mergeResult) throws Exception { Preconditions.checkNotNull(toBeMerged); Preconditions.checkNotNull(mergeResult); List copyOfToBeMerged = new ArrayList<>(toBeMerged.size()); - List activeToBeMerged = new ArrayList<>(toBeMerged.size()); boolean includesMergeResult = false; for (W window : toBeMerged) { Preconditions.checkNotNull(window); Preconditions.checkState( - isActive(window), "Expecting merge window %s to be active", window); + isActiveOrNew(window), "Expecting merge window %s to be ACTIVE or NEW", window); if (window.equals(mergeResult)) { includesMergeResult = true; } @@ -277,31 +208,24 @@ public void merge(Collection toBeMerged, W mergeResult) throws Exception { Preconditions.checkState( notDup, "Expecting merge window %s to appear in at most one merge set", window); copyOfToBeMerged.add(window); - if (!activeWindowToStateAddressWindows.get(window).isEmpty()) { - activeToBeMerged.add(window); - } } if (!includesMergeResult) { Preconditions.checkState( - !isActive(mergeResult), "Expecting result window %s to be new", mergeResult); + !isActive(mergeResult), "Expecting result window %s to be NEW", mergeResult); } allToBeMerged.add(copyOfToBeMerged); - allActiveToBeMerged.add(activeToBeMerged); allMergeResults.add(mergeResult); } public void recordMerges() throws Exception { for (int i = 0; i < allToBeMerged.size(); i++) { - mergeCallback.prefetchOnMerge( - allToBeMerged.get(i), allActiveToBeMerged.get(i), allMergeResults.get(i)); + mergeCallback.prefetchOnMerge(allToBeMerged.get(i), allMergeResults.get(i)); } for (int i = 0; i < allToBeMerged.size(); i++) { - mergeCallback.onMerge( - allToBeMerged.get(i), allActiveToBeMerged.get(i), allMergeResults.get(i)); + mergeCallback.onMerge(allToBeMerged.get(i), allMergeResults.get(i)); recordMerge(allToBeMerged.get(i), allMergeResults.get(i)); } allToBeMerged.clear(); - allActiveToBeMerged.clear(); allMergeResults.clear(); seen.clear(); } @@ -317,7 +241,6 @@ public void merge(MergeCallback mergeCallback) throws Exception { // Actually do the merging and invoke the callbacks. context.recordMerges(); - } /** @@ -327,6 +250,11 @@ public void merge(MergeCallback mergeCallback) throws Exception { * the active window set. */ private void recordMerge(Collection toBeMerged, W mergeResult) throws Exception { + // Note that mergedWriteStateAddress must predict the result of writeStateAddress + // after the corresponding merge has been applied. + // Thus we must ensure the first state address window in the merged result here is + // deterministic. + // Thus we use a linked hash set. Set newStateAddressWindows = new LinkedHashSet<>(); Set existingStateAddressWindows = activeWindowToStateAddressWindows.get(mergeResult); if (existingStateAddressWindows != null) { @@ -334,70 +262,35 @@ private void recordMerge(Collection toBeMerged, W mergeResult) throws Excepti newStateAddressWindows.addAll(existingStateAddressWindows); } - Set newEphemeralWindows = new HashSet<>(); - Set existingEphemeralWindows = activeWindowToEphemeralWindows.get(mergeResult); - if (existingEphemeralWindows != null) { - // Preserve all the existing EPHEMERAL windows for meregResult. - newEphemeralWindows.addAll(existingEphemeralWindows); - } - for (W other : toBeMerged) { Set otherStateAddressWindows = activeWindowToStateAddressWindows.get(other); - Preconditions.checkState(otherStateAddressWindows != null, "Window %s is not ACTIVE", other); + Preconditions.checkState(otherStateAddressWindows != null, + "Window %s is not ACTIVE or NEW", other); for (W otherStateAddressWindow : otherStateAddressWindows) { // Since otherTarget equiv other AND other equiv mergeResult // THEN otherTarget equiv mergeResult. newStateAddressWindows.add(otherStateAddressWindow); - windowToActiveWindow.put(otherStateAddressWindow, mergeResult); } activeWindowToStateAddressWindows.remove(other); - Set otherEphemeralWindows = activeWindowToEphemeralWindows.get(other); - if (otherEphemeralWindows != null) { - for (W otherEphemeral : otherEphemeralWindows) { - // Since otherEphemeral equiv other AND other equiv mergeResult - // THEN otherEphemeral equiv mergeResult. - newEphemeralWindows.add(otherEphemeral); - windowToActiveWindow.put(otherEphemeral, mergeResult); - } - } - activeWindowToEphemeralWindows.remove(other); - // Now other equiv mergeResult. - if (otherStateAddressWindows.contains(other)) { - // Other was ACTIVE and is now known to be MERGED. - } else if (otherStateAddressWindows.isEmpty()) { - // Other was NEW thus has no state. It is now EPHEMERAL. - newEphemeralWindows.add(other); - } else if (other.equals(mergeResult)) { - // Other was ACTIVE, was never used to store elements, but is still ACTIVE. - // Leave it as active. - } else { - // Other was ACTIVE, was never used to store element, as is no longer considered ACTIVE. - // It is now EPHEMERAL. - newEphemeralWindows.add(other); - } - windowToActiveWindow.put(other, mergeResult); } if (newStateAddressWindows.isEmpty()) { // If stateAddressWindows is empty then toBeMerged must have only contained EPHEMERAL windows. - // Promote mergeResult to be active now. + // Promote mergeResult to be ACTIVE now. newStateAddressWindows.add(mergeResult); } - windowToActiveWindow.put(mergeResult, mergeResult); activeWindowToStateAddressWindows.put(mergeResult, newStateAddressWindows); - if (!newEphemeralWindows.isEmpty()) { - activeWindowToEphemeralWindows.put(mergeResult, newEphemeralWindows); - } merged(mergeResult); } @Override public void merged(W window) { + // Take just the first state address window. Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); Preconditions.checkState(stateAddressWindows != null, "Window %s is not ACTIVE", window); W first = Iterables.getFirst(stateAddressWindows, null); @@ -407,8 +300,7 @@ public void merged(W window) { /** * Return the state address windows for ACTIVE {@code window} from which all state associated - * should - * be read and merged. + * should be read and merged. */ @Override public Set readStateAddresses(W window) { @@ -451,36 +343,14 @@ public void checkInvariants() { for (Map.Entry> entry : activeWindowToStateAddressWindows.entrySet()) { W active = entry.getKey(); Preconditions.checkState(!entry.getValue().isEmpty(), - "Unexpected empty state address window set for ACTIVE window %s", - active); + "Unexpected empty state address window set for ACTIVE window %s", + active); for (W stateAddressWindow : entry.getValue()) { Preconditions.checkState(knownStateAddressWindows.add(stateAddressWindow), - "%s is in more than one state address window set", - stateAddressWindow); - Preconditions.checkState(active.equals(windowToActiveWindow.get(stateAddressWindow)), - "%s should have %s as its ACTIVE window", stateAddressWindow, - active); - } - } - for (Map.Entry> entry : activeWindowToEphemeralWindows.entrySet()) { - W active = entry.getKey(); - Preconditions.checkState(activeWindowToStateAddressWindows.containsKey(active), - "%s must be ACTIVE window", active); - Preconditions.checkState( - !entry.getValue().isEmpty(), "Unexpected empty EPHEMERAL set for %s", active); - for (W ephemeralWindow : entry.getValue()) { - Preconditions.checkState(knownStateAddressWindows.add(ephemeralWindow), - "%s is EPHEMERAL/state address of more than one ACTIVE window", - ephemeralWindow); - Preconditions.checkState(active.equals(windowToActiveWindow.get(ephemeralWindow)), - "%s should have %s as its ACTIVE window", ephemeralWindow, active); + "%s is in more than one state address window set", + stateAddressWindow); } } - for (Map.Entry entry : windowToActiveWindow.entrySet()) { - Preconditions.checkState(activeWindowToStateAddressWindows.containsKey(entry.getValue()), - "%s should be ACTIVE since mergeResultWindow for %s", - entry.getValue(), entry.getKey()); - } } @Override @@ -499,23 +369,9 @@ public String toString() { sb.append(active); sb.append(":\n"); for (W stateAddressWindow : stateAddressWindows) { - if (stateAddressWindow.equals(active)) { - sb.append(" ACTIVE "); - } else { - sb.append(" MERGED "); - } + sb.append(" "); sb.append(stateAddressWindow); sb.append("\n"); - W active2 = windowToActiveWindow.get(stateAddressWindow); - Preconditions.checkState(active2.equals(active)); - } - Set ephemeralWindows = activeWindowToEphemeralWindows.get(active); - if (ephemeralWindows != null) { - for (W ephemeralWindow : ephemeralWindows) { - sb.append(" EPHEMERAL "); - sb.append(ephemeralWindow); - sb.append('\n'); - } } } } @@ -523,10 +379,26 @@ public String toString() { return sb.toString(); } - // ====================================================================== + @Override + public boolean equals(Object o) { + if (!(o instanceof MergingActiveWindowSet)) { + return false; + } + + @SuppressWarnings("unchecked") + MergingActiveWindowSet other = (MergingActiveWindowSet) o; + + return activeWindowToStateAddressWindows.equals(other.activeWindowToStateAddressWindows); + } + + @Override + public int hashCode() { + return Objects.hashCode(activeWindowToStateAddressWindows); + } /** - * Replace null {@code multimap} with empty map, and replace null entries in {@code multimap} with + * Replace null {@code multimap} with empty map, and replace null entries in {@code multimap} + * with * empty sets. */ private static Map> emptyIfNull(@Nullable Map> multimap) { @@ -552,22 +424,4 @@ private static Map> deepCopy(Map> multimap) { } return newMultimap; } - - /** - * Return inversion of {@code multimap}, which must be invertible. - */ - private static Map invert(Map> multimap) { - Map result = new HashMap<>(); - for (Map.Entry> entry : multimap.entrySet()) { - W active = entry.getKey(); - for (W target : entry.getValue()) { - W previous = result.put(target, active); - Preconditions.checkState( - previous == null, - "Multimap is not invertible: Window %s has both %s and %s as representatives", - target, previous, active); - } - } - return result; - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java index 6fddc5d604..544c1149b6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java @@ -24,7 +24,8 @@ import java.util.Set; /** - * Implementation of {@link ActiveWindowSet} used with {@link WindowFn WindowFns} that don't support + * Implementation of {@link ActiveWindowSet} used with {@link WindowFn WindowFns} that don't + * support * merging. * * @param the types of windows being managed @@ -37,13 +38,7 @@ public void cleanupTemporaryWindows() {} public void persist() {} @Override - public W mergeResultWindow(W window) { - // Always represented by itself. - return window; - } - - @Override - public Set getActiveWindows() { + public Set getActiveAndNewWindows() { // Only supported when merging. throw new java.lang.UnsupportedOperationException(); } @@ -54,6 +49,11 @@ public boolean isActive(W window) { return true; } + @Override + public boolean isActiveOrNew(W window) { + return true; + } + @Override public void ensureWindowExists(W window) {} @@ -62,7 +62,7 @@ public void ensureWindowIsActive(W window) {} @Override @VisibleForTesting - public void addActive(W window) {} + public void addActiveForTesting(W window) {} @Override public void remove(W window) {} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 106b356cb8..26ec194262 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; @@ -36,6 +37,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; import org.joda.time.Duration; import org.joda.time.Instant; @@ -43,8 +45,10 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import javax.annotation.Nullable; @@ -57,21 +61,21 @@ * the triggering logic. The {@code ReduceFnRunner}s responsibilities are: * *

            - *
          • Tracking the windows that are active (have buffered data) as elements arrive and - * triggers are fired. - *
          • Holding the watermark based on the timestamps of elements in a pane and releasing it - * when the trigger fires. - *
          • Calling the appropriate callbacks on {@link ReduceFn} based on trigger execution, timer - * firings, etc, and providing appropriate contexts to the {@link ReduceFn} for actions - * such as output. - *
          • Scheduling garbage collection of state associated with a specific window, and making that - * happen when the appropriate timer fires. + *
          • Tracking the windows that are active (have buffered data) as elements arrive and + * triggers are fired. + *
          • Holding the watermark based on the timestamps of elements in a pane and releasing it + * when the trigger fires. + *
          • Calling the appropriate callbacks on {@link ReduceFn} based on trigger execution, timer + * firings, etc, and providing appropriate contexts to the {@link ReduceFn} for actions + * such as output. + *
          • Scheduling garbage collection of state associated with a specific window, and making that + * happen when the appropriate timer fires. *
          * - * @param The type of key being processed. - * @param The type of values associated with the key. + * @param The type of key being processed. + * @param The type of values associated with the key. * @param The output type that will be produced for each key. - * @param The type of windows this operates on. + * @param The type of windows this operates on. */ public class ReduceFnRunner { @@ -79,14 +83,14 @@ public class ReduceFnRunner { * The {@link ReduceFnRunner} depends on most aspects of the {@link WindowingStrategy}. * *
            - *
          • It runs the trigger from the {@link WindowingStrategy}.
          • - *
          • It merges windows according to the {@link WindowingStrategy}.
          • - *
          • It chooses how to track active windows and clear out expired windows - * according to the {@link WindowingStrategy}, based on the allowed lateness and - * whether windows can merge.
          • - *
          • It decides whether to emit empty final panes according to whether the - * {@link WindowingStrategy} requires it.
          • - *
          • It uses discarding or accumulation mode according to the {@link WindowingStrategy}.
          • + *
          • It runs the trigger from the {@link WindowingStrategy}.
          • + *
          • It merges windows according to the {@link WindowingStrategy}.
          • + *
          • It chooses how to track active windows and clear out expired windows + * according to the {@link WindowingStrategy}, based on the allowed lateness and + * whether windows can merge.
          • + *
          • It decides whether to emit empty final panes according to whether the + * {@link WindowingStrategy} requires it.
          • + *
          • It uses discarding or accumulation mode according to the {@link WindowingStrategy}.
          • *
          */ private final WindowingStrategy windowingStrategy; @@ -99,11 +103,8 @@ public class ReduceFnRunner { private final K key; - private final OnMergeCallback onMergeCallback = new OnMergeCallback(); - /** - * Track which windows are still active and which 'state address' windows contain state - * for a merged window. + * Track which windows are still active and the 'state address' windows which hold their state. * *
            *
          • State: Global map for all active windows for this computation and key. @@ -247,7 +248,7 @@ boolean isFinished(W window) { @VisibleForTesting boolean hasNoActiveWindows() { - return activeWindows.getActiveWindows().isEmpty(); + return activeWindows.getActiveAndNewWindows().isEmpty(); } /** @@ -256,34 +257,34 @@ boolean hasNoActiveWindows() { * *

            The general strategy is: *

              - *
            1. Use {@link WindowedValue#getWindows} (itself determined using - * {@link WindowFn#assignWindows}) to determine which windows each element belongs to. Some - * of those windows will already have state associated with them. The rest are considered - * NEW. - *
            2. Use {@link WindowFn#mergeWindows} to attempt to merge currently ACTIVE and NEW windows. - * Each NEW window will become either ACTIVE, MERGED, or EPHEMERAL. (See {@link - * ActiveWindowSet} for definitions of these terms.) - *
            3. If at all possible, eagerly substitute EPHEMERAL windows with their ACTIVE state address - * windows before any state is associated with the EPHEMERAL window. In the common case that - * windows for new elements are merged into existing ACTIVE windows then no additional - * storage or merging overhead will be incurred. - *
            4. Otherwise, keep track of the state address windows for ACTIVE windows so that their - * states can be merged on-demand when a pane fires. - *
            5. Process the element for each of the windows it's windows have been merged into according - * to {@link ActiveWindowSet}. Processing may require running triggers, setting timers, - * setting holds, and invoking {@link ReduceFn#onTrigger}. + *
            6. Use {@link WindowedValue#getWindows} (itself determined using + * {@link WindowFn#assignWindows}) to determine which windows each element belongs to. Some + * of those windows will already have state associated with them. The rest are considered + * NEW. + *
            7. Use {@link WindowFn#mergeWindows} to attempt to merge currently ACTIVE and NEW windows. + * Each NEW window will become either ACTIVE or be discardedL. + * (See {@link ActiveWindowSet} for definitions of these terms.) + *
            8. If at all possible, eagerly substitute NEW windows with their ACTIVE state address + * windows before any state is associated with the NEW window. In the common case that + * windows for new elements are merged into existing ACTIVE windows then no additional + * storage or merging overhead will be incurred. + *
            9. Otherwise, keep track of the state address windows for ACTIVE windows so that their + * states can be merged on-demand when a pane fires. + *
            10. Process the element for each of the windows it's windows have been merged into according + * to {@link ActiveWindowSet}. Processing may require running triggers, setting timers, + * setting holds, and invoking {@link ReduceFn#onTrigger}. *
            */ public void processElements(Iterable> values) throws Exception { // If an incoming element introduces a new window, attempt to merge it into an existing - // window eagerly. The outcome is stored in the ActiveWindowSet. - collectAndMergeWindows(values); + // window eagerly. + Map windowToMergeResult = collectAndMergeWindows(values); Set windowsToConsider = new HashSet<>(); // Process each element, using the updated activeWindows determined by collectAndMergeWindows. for (WindowedValue value : values) { - windowsToConsider.addAll(processElement(value)); + windowsToConsider.addAll(processElement(windowToMergeResult, value)); } // Trigger output from any window for which the trigger is ready @@ -299,8 +300,6 @@ public void processElements(Iterable> values) throws Excep // We're all done with merging and emitting elements so can compress the activeWindow state. // Any windows which are still NEW must have come in on a new element which was then discarded // due to the window's trigger being closed. We can thus delete them. - // Any windows which are EPHEMERAL must have come in on a new element but been merged away - // into some other ACTIVE window. We can thus also delete them. activeWindows.cleanupTemporaryWindows(); } @@ -309,12 +308,15 @@ public void persist() { } /** - * Extract the windows associated with the values, and invoke merge. + * Extract the windows associated with the values, and invoke merge. Return a map + * from windows to the merge result window. If a window is not in the domain of + * the result map then it did not get merged into a different window. */ - private void collectAndMergeWindows(Iterable> values) throws Exception { + private Map collectAndMergeWindows(Iterable> values) + throws Exception { // No-op if no merging can take place if (windowingStrategy.getWindowFn().isNonMerging()) { - return; + return ImmutableMap.of(); } // Collect the windows from all elements (except those which are too late) and @@ -325,7 +327,10 @@ private void collectAndMergeWindows(Iterable> values) thro W window = (W) untypedWindow; // For backwards compat with pre 1.4 only. - + // We may still have ACTIVE windows with multiple state addresses, representing + // a window who's state has not yet been eagerly merged. + // We'll go ahead and merge that state now so that we don't have to worry about + // this legacy case anywhere else. if (activeWindows.isActive(window)) { Set stateAddressWindows = activeWindows.readStateAddresses(window); if (stateAddressWindows.size() > 1) { @@ -339,19 +344,41 @@ private void collectAndMergeWindows(Iterable> values) thro } } - // Add this window as NEW if it is not currently ACTIVE or MERGED. + // Add this window as NEW if it is not currently ACTIVE. // If we had already seen this window and closed its trigger, then the - // window will not be ACTIVE or MERGED. It will then be added as NEW here, + // window will not be currently ACTIVE. It will then be added as NEW here, // and fall into the merging logic as usual. activeWindows.ensureWindowExists(window); } } // Merge all of the active windows and retain a mapping from source windows to result windows. - mergeActiveWindows(); + Map windowToMergeResult = new HashMap<>(); + activeWindows.merge(new OnMergeCallback(windowToMergeResult)); + return windowToMergeResult; } private class OnMergeCallback implements ActiveWindowSet.MergeCallback { + private final Map windowToMergeResult; + + OnMergeCallback(Map windowToMergeResult) { + this.windowToMergeResult = windowToMergeResult; + } + + /** + * Return the subset of {@code windows} which are currently ACTIVE. We only need to worry + * about merging state from ACTIVE windows. NEW windows by definition have no existing state. + */ + private List activeWindows(Iterable windows) { + List active = new ArrayList<>(); + for (W window : windows) { + if (activeWindows.isActive(window)) { + active.add(window); + } + } + return active; + } + /** * Called from the active window set to indicate {@code toBeMerged} (of which only * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) will later @@ -359,7 +386,8 @@ private class OnMergeCallback implements ActiveWindowSet.MergeCallback { */ @Override public void prefetchOnMerge( - Collection toBeMerged, Collection activeToBeMerged, W mergeResult) throws Exception { + Collection toBeMerged, W mergeResult) throws Exception { + List activeToBeMerged = activeWindows(toBeMerged); ReduceFn.OnMergeContext directMergeContext = contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); ReduceFn.OnMergeContext renamedMergeContext = @@ -378,9 +406,14 @@ public void prefetchOnMerge( * to be merged into {@code mergeResult}. */ @Override - public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) - throws Exception { + public void onMerge(Collection toBeMerged, W mergeResult) throws Exception { + // Remember we have merged these windows. + for (W window : toBeMerged) { + windowToMergeResult.put(window, mergeResult); + } + // At this point activeWindows has NOT incorporated the results of the merge. + List activeToBeMerged = activeWindows(toBeMerged); ReduceFn.OnMergeContext directMergeContext = contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); ReduceFn.OnMergeContext renamedMergeContext = @@ -404,7 +437,7 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W // Not merged away. continue; } - // Cleanup flavor A: Currently ACTIVE window is about to become MERGED. + // Cleanup flavor A: Currently ACTIVE window is about to be merged away. // Clear any state not already cleared by the onMerge calls above. WindowTracing.debug("ReduceFnRunner.onMerge: Merging {} into {}", active, mergeResult); ReduceFn.Context directClearContext = @@ -421,17 +454,14 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W } } - private void mergeActiveWindows() throws Exception { - activeWindows.merge(onMergeCallback); - } - /** * Process an element. - * @param value the value being processed * + * @param value the value being processed * @return the set of windows in which the element was actually processed */ - private Collection processElement(WindowedValue value) throws Exception { + private Collection processElement(Map windowToMergeResult, WindowedValue value) + throws Exception { // Redirect element windows to the ACTIVE windows they have been merged into. // The compressed representation (value, {window1, window2, ...}) actually represents // distinct elements (value, window1), (value, window2), ... @@ -441,12 +471,11 @@ private Collection processElement(WindowedValue value) throws Excepti for (BoundedWindow untypedWindow : value.getWindows()) { @SuppressWarnings("unchecked") W window = (W) untypedWindow; - - ReduceFn.Context directContext = - contextFactory.base(window, StateStyle.DIRECT); - W active = activeWindows.mergeResultWindow(window); - Preconditions.checkState(active != null, "Window %s has no mergeResultWindow", window); - windows.add(active); + W mergeResult = windowToMergeResult.get(window); + if (mergeResult == null) { + mergeResult = window; + } + windows.add(mergeResult); } // Prefetch in each of the windows if we're going to need to process triggers @@ -540,10 +569,10 @@ public void onTimer(TimerData timer) throws Exception { // - If the window function does not support windowing then all windows will be considered // active. // So we must take conjunction of activeWindows and triggerRunner state. - boolean windowIsActive = + boolean windowIsActiveAndOpen = activeWindows.isActive(window) && !triggerRunner.isClosed(directContext.state()); - if (!windowIsActive) { + if (!windowIsActiveAndOpen) { WindowTracing.debug( "ReduceFnRunner.onTimer: Note that timer {} is for non-ACTIVE window {}", timer, window); } @@ -564,7 +593,7 @@ public void onTimer(TimerData timer) throws Exception { key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - if (windowIsActive) { + if (windowIsActiveAndOpen) { // We need to call onTrigger to emit the final pane if required. // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, // and the watermark has passed the end of the window. @@ -573,14 +602,14 @@ public void onTimer(TimerData timer) throws Exception { // Cleanup flavor B: Clear all the remaining state for this window since we'll never // see elements for it again. - clearAllState(directContext, renamedContext, windowIsActive); + clearAllState(directContext, renamedContext, windowIsActiveAndOpen); } else { WindowTracing.debug( "ReduceFnRunner.onTimer: Triggering for key:{}; window:{} at {} with " + "inputWatermark:{}; outputWatermark:{}", key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - if (windowIsActive) { + if (windowIsActiveAndOpen) { emitIfAppropriate(directContext, renamedContext); } @@ -621,9 +650,9 @@ public void onTimer(TimerData timer) throws Exception { private void clearAllState( ReduceFn.Context directContext, ReduceFn.Context renamedContext, - boolean windowIsActive) - throws Exception { - if (windowIsActive) { + boolean windowIsActiveAndOpen) + throws Exception { + if (windowIsActiveAndOpen) { // Since both the window is in the active window set AND the trigger was not yet closed, // it is possible we still have state. reduceFn.clearState(renamedContext); @@ -645,10 +674,8 @@ private void clearAllState( } } paneInfoTracker.clear(directContext.state()); - if (activeWindows.isActive(directContext.window())) { - // Don't need to track address state windows anymore. - activeWindows.remove(directContext.window()); - } + // Don't need to track address state windows anymore. + activeWindows.remove(directContext.window()); // We'll never need to test for the trigger being closed again. triggerRunner.clearFinished(directContext.state()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java index 16287bde83..adebf2967b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.util; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -37,6 +38,9 @@ import org.junit.runners.JUnit4; import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Test NonMergingActiveWindowSet. @@ -46,12 +50,17 @@ public class MergingActiveWindowSetTest { private Sessions windowFn; private StateInternals state; private MergingActiveWindowSet set; + private ActiveWindowSet.MergeCallback callback; @Before - public void before() { + public void setup() { windowFn = Sessions.withGapDuration(Duration.millis(10)); state = InMemoryStateInternals.forKey("dummyKey"); set = new MergingActiveWindowSet<>(windowFn, state); + @SuppressWarnings("unchecked") + ActiveWindowSet.MergeCallback + callback = mock(ActiveWindowSet.MergeCallback.class); + this.callback = callback; } @After @@ -61,47 +70,78 @@ public void after() { windowFn = null; } - private void add(final long instant) { - System.out.println("ADD " + instant); - final Object element = new Long(instant); - Sessions.AssignContext context = windowFn.new AssignContext() { - @Override - public Object element() { - return element; - } + private void add(long... instants) { + for (final long instant : instants) { + System.out.println("ADD " + instant); + Sessions.AssignContext context = windowFn.new AssignContext() { + @Override + public Object element() { + return (Object) instant; + } - @Override - public Instant timestamp() { - return new Instant(instant); - } + @Override + public Instant timestamp() { + return new Instant(instant); + } - @Override - public Collection windows() { - return ImmutableList.of(); - } - }; + @Override + public Collection windows() { + return ImmutableList.of(); + } + }; - for (IntervalWindow window : windowFn.assignWindows(context)) { - set.ensureWindowExists(window); + for (IntervalWindow window : windowFn.assignWindows(context)) { + set.ensureWindowExists(window); + } } } - private void merge(ActiveWindowSet.MergeCallback callback) throws Exception { - System.out.println("MERGE"); + private Map merge( + List toBeMerged, + IntervalWindow mergeResult) throws Exception { + IntervalWindow predictedPostMergeWriteStateAddress = + set.mergedWriteStateAddress(toBeMerged, mergeResult); + + System.out.println("BEFORE MERGE"); + System.out.println(set); + Map map = new HashMap<>(); + for (IntervalWindow window : toBeMerged) { + System.out.println("WILL MERGE " + window + " INTO " + mergeResult); + map.put(window, mergeResult); + } + System.out.println("AFTER MERGE"); set.merge(callback); - for (IntervalWindow window : set.getActiveWindows()) { - set.ensureWindowIsActive(window); + verify(callback).onMerge(toBeMerged, mergeResult); + System.out.println(set); + + assertEquals(predictedPostMergeWriteStateAddress, set.writeStateAddress(mergeResult)); + + return map; + } + + private void activate(Map map, long... instants) { + for (long instant : instants) { + IntervalWindow window = window(instant, 10); + IntervalWindow active = map.get(window); + if (active == null) { + active = window; + } + System.out.println("ACTIVATE " + active); + set.ensureWindowIsActive(active); } set.checkInvariants(); - System.out.println(set); } - private void pruneAndPersist() { - System.out.println("PRUNE"); + private void cleanup() { + System.out.println("CLEANUP"); set.cleanupTemporaryWindows(); set.checkInvariants(); System.out.println(set); set.persist(); + MergingActiveWindowSet reloaded = + new MergingActiveWindowSet<>(windowFn, state); + reloaded.checkInvariants(); + assertEquals(set, reloaded); } private IntervalWindow window(long start, long size) { @@ -109,70 +149,115 @@ private IntervalWindow window(long start, long size) { } @Test - public void test() throws Exception { - @SuppressWarnings("unchecked") - ActiveWindowSet.MergeCallback callback = - mock(ActiveWindowSet.MergeCallback.class); - + public void testLifecycle() throws Exception { + // Step 1: New elements show up, introducing NEW windows which are partially merged. // NEW 1+10 // NEW 2+10 // NEW 15+10 // => // ACTIVE 1+11 (target 1+11) - // EPHEMERAL 1+10 -> 1+11 - // EPHEMERAL 2+10 -> 1+11 // ACTIVE 15+10 (target 15+10) - add(1); - add(2); - add(15); - merge(callback); - verify(callback).onMerge(ImmutableList.of(window(1, 10), window(2, 10)), - ImmutableList.of(), window(1, 11)); - assertEquals(ImmutableSet.of(window(1, 11), window(15, 10)), set.getActiveWindows()); - assertEquals(window(1, 11), set.mergeResultWindow(window(1, 10))); - assertEquals(window(1, 11), set.mergeResultWindow(window(2, 10))); - assertEquals(window(1, 11), set.mergeResultWindow(window(1, 11))); - assertEquals(window(15, 10), set.mergeResultWindow(window(15, 10))); + add(1, 2, 15); + assertEquals(ImmutableSet.of(window(1, 10), window(2, 10), window(15, 10)), + set.getActiveAndNewWindows()); + Map map = + merge(ImmutableList.of(window(1, 10), window(2, 10)), + window(1, 11)); + activate(map, 1, 2, 15); + assertEquals(ImmutableSet.of(window(1, 11), window(15, 10)), set.getActiveAndNewWindows()); assertEquals( - ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 11))); + ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 11))); assertEquals( - ImmutableSet.of(window(15, 10)), set.readStateAddresses(window(15, 10))); + ImmutableSet.of(window(15, 10)), set.readStateAddresses(window(15, 10))); + cleanup(); + // Step 2: Another element, merged into an existing ACTIVE window. // NEW 3+10 // => // ACTIVE 1+12 (target 1+11) - // EPHEMERAL 3+10 -> 1+12 // ACTIVE 15+10 (target 15+10) add(3); - merge(callback); - verify(callback).onMerge(ImmutableList.of(window(1, 11), window(3, 10)), - ImmutableList.of(window(1, 11)), window(1, 12)); - assertEquals(ImmutableSet.of(window(1, 12), window(15, 10)), set.getActiveWindows()); - assertEquals(window(1, 12), set.mergeResultWindow(window(3, 10))); + assertEquals(ImmutableSet.of(window(3, 10), window(1, 11), window(15, 10)), + set.getActiveAndNewWindows()); + map = merge(ImmutableList.of(window(1, 11), window(3, 10)), + window(1, 12)); + activate(map, 3); + assertEquals(ImmutableSet.of(window(1, 12), window(15, 10)), set.getActiveAndNewWindows()); + assertEquals( + ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 12))); + assertEquals( + ImmutableSet.of(window(15, 10)), set.readStateAddresses(window(15, 10))); + cleanup(); + // Step 3: Another element, causing two ACTIVE windows to be merged. // NEW 8+10 // => - // ACTIVE 1+24 (target 1+11, 15+10) - // MERGED 1+11 -> 1+24 - // MERGED 15+10 -> 1+24 - // EPHEMERAL 1+12 -> 1+24 + // ACTIVE 1+24 (target 1+11) add(8); - merge(callback); - verify(callback).onMerge(ImmutableList.of(window(1, 12), window(8, 10), window(15, 10)), - ImmutableList.of(window(1, 12), window(15, 10)), window(1, 24)); - assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveWindows()); - assertEquals(window(1, 24), set.mergeResultWindow(window(1, 12))); - assertEquals(window(1, 24), set.mergeResultWindow(window(1, 11))); - assertEquals(window(1, 24), set.mergeResultWindow(window(15, 10))); + assertEquals(ImmutableSet.of(window(8, 10), window(1, 12), window(15, 10)), + set.getActiveAndNewWindows()); + map = merge(ImmutableList.of(window(1, 12), window(8, 10), window(15, 10)), + window(1, 24)); + activate(map, 8); + assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveAndNewWindows()); + assertEquals( + ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 24))); + cleanup(); + // Step 4: Another element, merged into an existing ACTIVE window. // NEW 9+10 // => - // ACTIVE 1+24 (target 1+11, 15+10) + // ACTIVE 1+24 (target 1+11) add(9); - merge(callback); - verify(callback).onMerge(ImmutableList.of(window(1, 24), window(9, 10)), - ImmutableList.of(window(1, 24)), window(1, 24)); + assertEquals(ImmutableSet.of(window(9, 10), window(1, 24)), set.getActiveAndNewWindows()); + map = merge(ImmutableList.of(window(1, 24), window(9, 10)), + window(1, 24)); + activate(map, 9); + assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveAndNewWindows()); + assertEquals( + ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 24))); + cleanup(); + + // Step 5: Another element reusing earlier window, merged into an existing ACTIVE window. + // NEW 1+10 + // => + // ACTIVE 1+24 (target 1+11) + add(1); + assertEquals(ImmutableSet.of(window(1, 10), window(1, 24)), set.getActiveAndNewWindows()); + map = merge(ImmutableList.of(window(1, 10), window(1, 24)), + window(1, 24)); + activate(map, 1); + assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveAndNewWindows()); + assertEquals( + ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 24))); + cleanup(); + + // Step 6: Window is closed. + set.remove(window(1, 24)); + cleanup(); + assertTrue(set.getActiveAndNewWindows().isEmpty()); + } + + @Test + public void testLegacyState() { + // Pre 1.4 we merged window state lazily. + // Simulate loading an active window set with multiple state address windows. + set.addActiveForTesting(window(1, 12), + ImmutableList.of(window(1, 10), window(2, 10), window(3, 10))); + + + // Make sure we can detect and repair the state. + assertTrue(set.isActive(window(1, 12))); + assertEquals(ImmutableSet.of(window(1, 10), window(2, 10), window(3, 10)), + set.readStateAddresses(window(1, 12))); + assertEquals(window(1, 10), + set.mergedWriteStateAddress( + ImmutableList.of(window(1, 10), window(2, 10), window(3, 10)), + window(1, 12))); + set.merged(window(1, 12)); + cleanup(); - pruneAndPersist(); + // For then on we are back to the eager case. + assertEquals(ImmutableSet.of(window(1, 10)), set.readStateAddresses(window(1, 12))); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java index ba1bf5e5e0..a9d4087cb0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java @@ -48,6 +48,7 @@ import org.joda.time.Duration; import org.joda.time.Instant; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; @@ -102,6 +103,7 @@ public SimpleTriggerTester withAllowedLateness(Duration allowedLateness) thro private final TriggerContextFactory contextFactory; private final WindowFn windowFn; private final ActiveWindowSet activeWindows; + private final Map windowToMergeResult; /** * An {@link ExecutableTrigger} built from the {@link Trigger} or {@link TriggerBuilder} @@ -153,6 +155,7 @@ protected TriggerTester(WindowingStrategy windowingStrategy) throws E windowFn.isNonMerging() ? new NonMergingActiveWindowSet() : new MergingActiveWindowSet(windowFn, stateInternals); + this.windowToMergeResult = new HashMap<>(); this.contextFactory = new TriggerContextFactory<>(windowingStrategy, stateInternals, activeWindows); @@ -243,7 +246,7 @@ public final void injectElements(Collection> values) th windowFn, value, timestamp, Arrays.asList(GlobalWindow.INSTANCE))); for (W window : assignedWindows) { - activeWindows.addActive(window); + activeWindows.addActiveForTesting(window); // Today, triggers assume onTimer firing at the watermark time, whether or not they // explicitly set the timer themselves. So this tester must set it. @@ -261,7 +264,7 @@ public final void injectElements(Collection> values) th for (BoundedWindow untypedWindow : windowedValue.getWindows()) { // SDK is responsible for type safety @SuppressWarnings("unchecked") - W window = activeWindows.mergeResultWindow((W) untypedWindow); + W window = mergeResult((W) untypedWindow); Trigger.OnElementContext context = contextFactory.createOnElementContext(window, new TestTimers(windowNamespace(window)), windowedValue.getTimestamp(), @@ -310,14 +313,20 @@ public void setSubTriggerFinishedForWindow(int subTriggerIndex, W window, boolea * since it is just to test the trigger's {@code OnMerge} method. */ public final void mergeWindows() throws Exception { + windowToMergeResult.clear(); activeWindows.merge(new MergeCallback() { @Override - public void prefetchOnMerge(Collection toBeMerged, Collection activeToBeMerged, - W mergeResult) throws Exception {} + public void prefetchOnMerge(Collection toBeMerged, W mergeResult) throws Exception {} @Override - public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W mergeResult) - throws Exception { + public void onMerge(Collection toBeMerged, W mergeResult) throws Exception { + List activeToBeMerged = new ArrayList(); + for (W window : toBeMerged) { + windowToMergeResult.put(window, mergeResult); + if (activeWindows.isActive(window)) { + activeToBeMerged.add(window); + } + } Map mergingFinishedSets = Maps.newHashMapWithExpectedSize(activeToBeMerged.size()); for (W oldWindow : activeToBeMerged) { @@ -332,6 +341,11 @@ public void onMerge(Collection toBeMerged, Collection activeToBeMerged, W }); } + public W mergeResult(W window) { + W result = windowToMergeResult.get(window); + return result == null ? window : result; + } + private FinishedTriggers getFinishedSet(W window) { FinishedTriggers finishedSet = finishedSets.get(window); if (finishedSet == null) { From 91999bdc8e51a51bdd271862e23c6dc33f777bc1 Mon Sep 17 00:00:00 2001 From: Mark Shields Date: Tue, 31 May 2016 15:38:58 -0700 Subject: [PATCH 436/751] Backport BEAM pull/391 for BEAM-122 and BEAM-311 (#289) * Backpoint BEAM pull/391 * Dan and Ben's comments * Ben's comments --- .../dataflow/sdk/util/ReduceFnRunner.java | 107 ++++++--- .../dataflow/sdk/util/WatermarkHold.java | 227 +++++++++++------- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 177 +++++++++++++- 3 files changed, 398 insertions(+), 113 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 26ec194262..007a1baa7f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -21,6 +21,7 @@ import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; @@ -577,14 +578,17 @@ public void onTimer(TimerData timer) throws Exception { "ReduceFnRunner.onTimer: Note that timer {} is for non-ACTIVE window {}", timer, window); } - // If this is an end-of-window timer then, we need to set a GC timer + // If this is an end-of-window timer then we may need to set a garbage collection timer + // if allowed lateness is non-zero. boolean isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() - && timer.getTimestamp().equals(window.maxTimestamp()); + && timer.getTimestamp().equals(window.maxTimestamp()); // If this is a garbage collection timer then we should trigger and garbage collect the window. - Instant cleanupTime = window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()); - boolean isGarbageCollection = - TimeDomain.EVENT_TIME == timer.getDomain() && timer.getTimestamp().equals(cleanupTime); + // We'll consider any timer at or after the end-of-window time to be a signal to garbage + // collect. + Instant cleanupTime = garbageCollectionTime(window); + boolean isGarbageCollection = TimeDomain.EVENT_TIME == timer.getDomain() + && !timer.getTimestamp().isBefore(cleanupTime); if (isGarbageCollection) { WindowTracing.debug( @@ -597,7 +601,10 @@ public void onTimer(TimerData timer) throws Exception { // We need to call onTrigger to emit the final pane if required. // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, // and the watermark has passed the end of the window. - onTrigger(directContext, renamedContext, true/* isFinished */, isEndOfWindow); + @Nullable Instant newHold = + onTrigger(directContext, renamedContext, true/* isFinished */, isEndOfWindow); + Preconditions.checkState(newHold == null, + "Hold placed at %s despite isFinished being true.", newHold); } // Cleanup flavor B: Clear all the remaining state for this window since we'll never @@ -623,7 +630,7 @@ public void onTimer(TimerData timer) throws Exception { // timer. (If getAllowedLateness is zero then the timer event will be considered a // cleanup event and handled by the above). // Note we must do this even if the trigger is finished so that we are sure to cleanup - // any final trigger tombstones. + // any final trigger finished bits. Preconditions.checkState( windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO), "Unexpected zero getAllowedLateness"); @@ -632,6 +639,8 @@ public void onTimer(TimerData timer) throws Exception { + "inputWatermark:{}; outputWatermark:{}", key, directContext.window(), cleanupTime, timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); + Preconditions.checkState(!cleanupTime.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), + "Cleanup time %s is beyond end-of-time", cleanupTime); directContext.timers().setTimer(cleanupTime, TimeDomain.EVENT_TIME); } } @@ -643,7 +652,8 @@ public void onTimer(TimerData timer) throws Exception { * beyond allowed lateness. * This is a superset of the clearing done by {@link #emitIfAppropriate} below since: *
              - *
            1. We can clear the trigger state tombstone since we'll never need to ask about it again. + *
            2. We can clear the trigger finished bits since we'll never need to ask if the trigger is + * closed again. *
            3. We can clear any remaining garbage collection hold. *
            */ @@ -658,12 +668,30 @@ private void clearAllState( reduceFn.clearState(renamedContext); watermarkHold.clearHolds(renamedContext); nonEmptyPanes.clearPane(renamedContext.state()); + // These calls work irrespective of whether the window is active or not, but + // are unnecessary if the window is not active. triggerRunner.clearState( directContext.window(), directContext.timers(), directContext.state()); + paneInfoTracker.clear(directContext.state()); } else { - // Needed only for backwards compatibility over UPDATE. - // Clear any end-of-window or garbage collection holds keyed by the current window. - // Only needed if: + // If !windowIsActiveAndOpen then !activeWindows.isActive (1) or triggerRunner.isClosed (2). + // For (1), if !activeWindows.isActive then the window must be merging and has been + // explicitly removed by emitIfAppropriate. But in that case the trigger must have fired + // and been closed, so this case reduces to (2). + // For (2), if triggerRunner.isClosed then the trigger was fired and entered the + // closed state. In that case emitIfAppropriate will have cleared all state in + // reduceFn, triggerRunner (except for finished bits), paneInfoTracker and activeWindows. + // We also know nonEmptyPanes must have been unconditionally cleared by the trigger. + // Since the trigger fired the existing watermark holds must have been cleared, and since + // the trigger closed no new end of window or garbage collection hold will have been + // placed by WatermarkHold.extractAndRelease. + // Thus all the state clearing above is unnecessary. + // + // But(!) for backwards compatibility we must allow a pipeline to be updated from + // an sdk version <= 1.3. In that case it is possible we have an end-of-window or + // garbage collection hold keyed by the current window (reached via directContext) rather + // than the state address window (reached via renamedContext). + // However this can only happen if: // - We have merging windows. // - We are DISCARDING_FIRED_PANES. // - A pane has fired. @@ -673,7 +701,7 @@ private void clearAllState( watermarkHold.clearHolds(directContext); } } - paneInfoTracker.clear(directContext.state()); + // Don't need to track address state windows anymore. activeWindows.remove(directContext.window()); // We'll never need to test for the trigger being closed again. @@ -758,8 +786,11 @@ private boolean needToEmit(boolean isEmpty, boolean isFinished, PaneInfo.Timing /** * Run the {@link ReduceFn#onTrigger} method and produce any necessary output. + * + * @return output watermark hold added, or {@literal null} if none. */ - private void onTrigger( + @Nullable + private Instant onTrigger( final ReduceFn.Context directContext, ReduceFn.Context renamedContext, boolean isFinished, boolean isEndOfWindow) @@ -795,8 +826,7 @@ private void onTrigger( if (newHold.isAfter(directContext.window().maxTimestamp())) { // The hold must be for garbage collection, which can't have happened yet. Preconditions.checkState( - newHold.isEqual( - directContext.window().maxTimestamp().plus(windowingStrategy.getAllowedLateness())), + newHold.isEqual(garbageCollectionTime(directContext.window())), "new hold %s should be at garbage collection for window %s plus %s", newHold, directContext.window(), @@ -838,6 +868,8 @@ public void output(OutputT toOutput) { reduceFn.onTrigger(renamedTriggerContext); } + + return newHold; } /** @@ -861,39 +893,56 @@ private Instant scheduleEndOfWindowOrGarbageCollectionTimer( ReduceFn.Context directContext) { Instant inputWM = timerInternals.currentInputWatermarkTime(); Instant endOfWindow = directContext.window().maxTimestamp(); - Instant fireTime; String which; + Instant timer; if (endOfWindow.isBefore(inputWM)) { - fireTime = endOfWindow.plus(windowingStrategy.getAllowedLateness()); + timer = garbageCollectionTime(directContext.window()); which = "garbage collection"; } else { - fireTime = endOfWindow; + timer = endOfWindow; which = "end-of-window"; } WindowTracing.trace( "ReduceFnRunner.scheduleEndOfWindowOrGarbageCollectionTimer: Scheduling {} timer at {} for " - + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", + + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", which, - fireTime, + timer, key, directContext.window(), inputWM, timerInternals.currentOutputWatermarkTime()); - directContext.timers().setTimer(fireTime, TimeDomain.EVENT_TIME); - return fireTime; + Preconditions.checkState(!timer.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), + "Timer %s is beyond end-of-time", timer); + directContext.timers().setTimer(timer, TimeDomain.EVENT_TIME); + return timer; } - private void cancelEndOfWindowAndGarbageCollectionTimers(ReduceFn.Context context) { + private void cancelEndOfWindowAndGarbageCollectionTimers( + ReduceFn.Context directContext) { WindowTracing.debug( "ReduceFnRunner.cancelEndOfWindowAndGarbageCollectionTimers: Deleting timers for " + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", - key, context.window(), timerInternals.currentInputWatermarkTime(), + key, directContext.window(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - Instant timer = context.window().maxTimestamp(); - context.timers().deleteTimer(timer, TimeDomain.EVENT_TIME); - if (windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO)) { - timer = timer.plus(windowingStrategy.getAllowedLateness()); - context.timers().deleteTimer(timer, TimeDomain.EVENT_TIME); + Instant eow = directContext.window().maxTimestamp(); + directContext.timers().deleteTimer(eow, TimeDomain.EVENT_TIME); + Instant gc = garbageCollectionTime(directContext.window()); + if (gc.isAfter(eow)) { + directContext.timers().deleteTimer(eow, TimeDomain.EVENT_TIME); + } + } + + /** + * Return when {@code window} should be garbage collected. If the window is the GlobalWindow, + * that will be the end of the window. Otherwise, add the allowed lateness to the end of + * the window. + */ + private Instant garbageCollectionTime(W window) { + Instant maxTimestamp = window.maxTimestamp(); + if (maxTimestamp.isBefore(GlobalWindow.INSTANCE.maxTimestamp())) { + return maxTimestamp.plus(windowingStrategy.getAllowedLateness()); + } else { + return maxTimestamp; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index 7f814c457a..a4739f194e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; import com.google.cloud.dataflow.sdk.util.state.ReadableState; @@ -56,8 +57,8 @@ class WatermarkHold implements Serializable { * used for elements. */ public static - StateTag> watermarkHoldTagForOutputTimeFn( - OutputTimeFn outputTimeFn) { + StateTag> watermarkHoldTagForOutputTimeFn( + OutputTimeFn outputTimeFn) { return StateTags.>makeSystemTagInternal( StateTags.watermarkStateInternal("hold", outputTimeFn)); } @@ -84,9 +85,11 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind } /** - * Add a hold to prevent the output watermark progressing beyond the (possibly adjusted) timestamp + * Add a hold to prevent the output watermark progressing beyond the (possibly adjusted) + * timestamp * of the element in {@code context}. We allow the actual hold time to be shifted later by - * {@link OutputTimeFn#assignOutputTime}, but no further than the end of the window. The hold will + * {@link OutputTimeFn#assignOutputTime}, but no further than the end of the window. The hold + * will * remain until cleared by {@link #extractAndRelease}. Return the timestamp at which the hold * was placed, or {@literal null} if no hold was placed. * @@ -190,7 +193,7 @@ public WatermarkHold(TimerInternals timerInternals, WindowingStrategy wind public Instant addHolds(ReduceFn.ProcessValueContext context) { Instant hold = addElementHold(context); if (hold == null) { - hold = addEndOfWindowOrGarbageCollectionHolds(context); + hold = addEndOfWindowOrGarbageCollectionHolds(context, false/*paneIsEmpty*/); } return hold; } @@ -201,23 +204,31 @@ public Instant addHolds(ReduceFn.ProcessValueContext context) { */ private Instant shift(Instant timestamp, W window) { Instant shifted = windowingStrategy.getOutputTimeFn().assignOutputTime(timestamp, window); - if (shifted.isBefore(timestamp)) { - throw new IllegalStateException( - String.format("OutputTimeFn moved element from %s to earlier time %s for window %s", - timestamp, shifted, window)); - } - if (!timestamp.isAfter(window.maxTimestamp()) && shifted.isAfter(window.maxTimestamp())) { - throw new IllegalStateException( - String.format("OutputTimeFn moved element from %s to %s which is beyond end of window %s", - timestamp, shifted, window)); - } + Preconditions.checkState(!shifted.isBefore(timestamp), + "OutputTimeFn moved element from %s to earlier time %s for window %s", + timestamp, shifted, window); + Preconditions.checkState(timestamp.isAfter(window.maxTimestamp()) + || !shifted.isAfter(window.maxTimestamp()), + "OutputTimeFn moved element from %s to %s which is beyond end of " + + "window %s", + timestamp, shifted, window); return shifted; } /** - * Add an element hold if possible. Return instant at which hold was added, or {@literal null} - * if no hold was added. + * Attempt to add an 'element hold'. Return the {@link Instant} at which the hold was + * added (ie the element timestamp plus any forward shift requested by the + * {@link WindowingStrategy#getOutputTimeFn}), or {@literal null} if no hold was added. + * The hold is only added if both: + *
              + *
            1. The backend will be able to respect it. In other words the output watermark cannot + * be ahead of the proposed hold time. + *
            2. A timer will be set (by {@link ReduceFnRunner}) to clear the hold by the end of the + * window. In other words the input watermark cannot be ahead of the end of the window. + *
            + * The hold ensures the pane which incorporates the element is will not be considered late by + * any downstream computation when it is eventually emitted. */ @Nullable private Instant addElementHold(ReduceFn.ProcessValueContext context) { @@ -229,11 +240,6 @@ private Instant addElementHold(ReduceFn.ProcessValueContext context) Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); - // Only add the hold if we can be sure: - // - the backend will be able to respect it - // (ie the hold is at or ahead of the output watermark), AND - // - a timer will be set to clear it by the end of window - // (ie the end of window is at or ahead of the input watermark). String which; boolean tooLate; // TODO: These case labels could be tightened. @@ -247,11 +253,13 @@ private Instant addElementHold(ReduceFn.ProcessValueContext context) } else { which = "on time"; tooLate = false; + Preconditions.checkState(!elementHold.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), + "Element hold %s is beyond end-of-time", elementHold); context.state().access(elementHoldTag).add(elementHold); } WindowTracing.trace( "WatermarkHold.addHolds: element hold at {} is {} for " - + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", elementHold, which, context.key(), context.window(), inputWM, outputWM); @@ -261,87 +269,136 @@ private Instant addElementHold(ReduceFn.ProcessValueContext context) /** * Add an end-of-window hold or, if too late for that, a garbage collection hold (if required). * Return the {@link Instant} at which hold was added, or {@literal null} if no hold was added. - * - *

            The end-of-window hold guarantees that an empty {@code ON_TIME} pane can be given - * a timestamp which will not be considered beyond allowed lateness by any downstream computation. */ @Nullable - private Instant addEndOfWindowOrGarbageCollectionHolds(ReduceFn.Context context) { - Instant hold = addEndOfWindowHold(context); + private Instant addEndOfWindowOrGarbageCollectionHolds( + ReduceFn.Context context, boolean paneIsEmpty) { + Instant hold = addEndOfWindowHold(context, paneIsEmpty); if (hold == null) { - hold = addGarbageCollectionHold(context); + hold = addGarbageCollectionHold(context, paneIsEmpty); } return hold; } /** - * Add an end-of-window hold. Return the {@link Instant} at which hold was added, - * or {@literal null} if no hold was added. + * Attempt to add an 'end-of-window hold'. Return the {@link Instant} at which the hold was added + * (ie the end of window time), or {@literal null} if no end of window hold is possible and we + * should fallback to a garbage collection hold. + * + *

            We only add the hold if we can be sure a timer will be set (by {@link ReduceFnRunner}) + * to clear it. In other words, the input watermark cannot be ahead of the end of window time. * - *

            The end-of-window hold guarantees that any empty {@code ON_TIME} pane can be given - * a timestamp which will not be considered beyond allowed lateness by any downstream computation. + *

            An end-of-window hold is added in two situations: + *

              + *
            1. An incoming element came in behind the output watermark (so we are too late for placing + * the usual element hold), but it may still be possible to include the element in an + * {@link Timing#ON_TIME} pane. We place the end of window hold to ensure that pane will + * not be considered late by any downstream computation. + *
            2. We guarantee an {@link Timing#ON_TIME} pane will be emitted for all windows which saw at + * least one element, even if that {@link Timing#ON_TIME} pane is empty. Thus when elements in + * a pane are processed due to a fired trigger we must set both an end of window timer and an end + * of window hold. Again, the hold ensures the {@link Timing#ON_TIME} pane will not be considered + * late by any downstream computation. + *
            */ @Nullable - private Instant addEndOfWindowHold(ReduceFn.Context context) { - // Only add an end-of-window hold if we can be sure a timer will be set to clear it - // by the end of window (ie the end of window is at or ahead of the input watermark). + private Instant addEndOfWindowHold(ReduceFn.Context context, boolean paneIsEmpty) { Instant outputWM = timerInternals.currentOutputWatermarkTime(); Instant inputWM = timerInternals.currentInputWatermarkTime(); - - String which; - boolean tooLate; Instant eowHold = context.window().maxTimestamp(); + if (eowHold.isBefore(inputWM)) { - which = "too late for end-of-window timer"; - tooLate = true; - } else { - which = "on time"; - tooLate = false; - Preconditions.checkState(outputWM == null || !eowHold.isBefore(outputWM), - "End-of-window hold %s cannot be before output watermark %s", eowHold, outputWM); - context.state().access(EXTRA_HOLD_TAG).add(eowHold); + WindowTracing.trace( + "WatermarkHold.addEndOfWindowHold: end-of-window hold at {} is too late for " + + "end-of-window timer for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + eowHold, context.key(), context.window(), inputWM, outputWM); + return null; } - WindowTracing.trace( - "WatermarkHold.addEndOfWindowHold: end-of-window hold at {} is {} for " - + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - eowHold, which, context.key(), context.window(), inputWM, - outputWM); - return tooLate ? null : eowHold; + Preconditions.checkState(outputWM == null || !eowHold.isBefore(outputWM), + "End-of-window hold %s cannot be before output watermark %s", + eowHold, outputWM); + Preconditions.checkState(!eowHold.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), + "End-of-window hold %s is beyond end-of-time", eowHold); + // If paneIsEmpty then this hold is just for empty ON_TIME panes, so we want to keep + // the hold away from the combining function in elementHoldTag. + // However if !paneIsEmpty then it could make sense to use the elementHoldTag here. + // Alas, onMerge is forced to add an end of window or garbage collection hold without + // knowing whether an element hold is already in place (stopping to check is too expensive). + // This it would end up adding an element hold at the end of the window which could + // upset the elementHoldTag combining function. + context.state().access(EXTRA_HOLD_TAG).add(eowHold); + WindowTracing.trace( + "WatermarkHold.addEndOfWindowHold: end-of-window hold at {} is on time for " + + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + eowHold, context.key(), context.window(), inputWM, outputWM); + return eowHold; } /** - * Add a garbage collection hold, if required. Return the {@link Instant} at which hold was added, + * Attempt to add a 'garbage collection hold' if it is required. Return the {@link Instant} at + * which the hold was added (ie the end of window time plus allowed lateness), * or {@literal null} if no hold was added. * - *

            The garbage collection hold gurantees that any empty final pane can be given - * a timestamp which will not be considered beyond allowed lateness by any downstream - * computation. If we are sure no empty final panes can be emitted then there's no need - * for an additional hold. + *

            We only add the hold if it is distinct from what would be added by + * {@link #addEndOfWindowHold}. In other words, {@link WindowingStrategy#getAllowedLateness} + * must be non-zero. + * + *

            A garbage collection hold is added in two situations: + *

              + *
            1. An incoming element came in behind the output watermark, and was too late for placing + * the usual element hold or an end of window hold. Place the garbage collection hold so that + * we can guarantee when the pane is finally triggered its output will not be dropped due to + * excessive lateness by any downstream computation. + *
            2. The {@link WindowingStrategy#getClosingBehavior()} is + * {@link ClosingBehavior#FIRE_ALWAYS}, and thus we guarantee a final pane will be emitted + * for all windows which saw at least one element. Again, the garbage collection hold guarantees + * that any empty final pane can be given a timestamp which will not be considered beyond + * allowed lateness by any downstream computation. + *
            + * + *

            We use {@code paneIsEmpty} to distinguish cases 1 and 2. */ @Nullable - private Instant addGarbageCollectionHold(ReduceFn.Context context) { - // Only add a garbage collection hold if we may need to emit an empty pane - // at garbage collection time, and garbage collection time is strictly after the - // end of window. (All non-empty panes will have holds at their output - // time derived from their incoming elements and no additional hold is required.) - if (context.windowingStrategy().getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS - && windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO)) { - Instant gcHold = context.window().maxTimestamp().plus(windowingStrategy.getAllowedLateness()); - Instant outputWM = timerInternals.currentOutputWatermarkTime(); - Instant inputWM = timerInternals.currentInputWatermarkTime(); + private Instant addGarbageCollectionHold( + ReduceFn.Context context, boolean paneIsEmpty) { + Instant outputWM = timerInternals.currentOutputWatermarkTime(); + Instant inputWM = timerInternals.currentInputWatermarkTime(); + Instant eow = context.window().maxTimestamp(); + Instant gcHold = eow.plus(windowingStrategy.getAllowedLateness()); + if (!windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO)) { WindowTracing.trace( - "WatermarkHold.addGarbageCollectionHold: garbage collection at {} hold for " - + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + "WatermarkHold.addGarbageCollectionHold: garbage collection hold at {} is unnecessary " + + "since no allowed lateness for key:{}; window:{}; inputWatermark:{}; " + + "outputWatermark:{}", gcHold, context.key(), context.window(), inputWM, outputWM); - Preconditions.checkState(!gcHold.isBefore(inputWM), - "Garbage collection hold %s cannot be before input watermark %s", gcHold, inputWM); - context.state().access(EXTRA_HOLD_TAG).add(gcHold); - return gcHold; - } else { return null; } + + if (paneIsEmpty && context.windowingStrategy().getClosingBehavior() + == ClosingBehavior.FIRE_IF_NON_EMPTY) { + WindowTracing.trace( + "WatermarkHold.addGarbageCollectionHold: garbage collection hold at {} is unnecessary " + + "since empty pane and FIRE_IF_NON_EMPTY for key:{}; window:{}; inputWatermark:{}; " + + "outputWatermark:{}", + gcHold, context.key(), context.window(), inputWM, outputWM); + return null; + } + + Preconditions.checkState(!gcHold.isBefore(inputWM), + "Garbage collection hold %s cannot be before input watermark %s", + gcHold, inputWM); + Preconditions.checkState(!gcHold.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), + "Garbage collection hold %s is beyond end-of-time", gcHold); + // Same EXTRA_HOLD_TAG vs elementHoldTag discussion as in addEndOfWindowHold above. + context.state().access(EXTRA_HOLD_TAG).add(gcHold); + + WindowTracing.trace( + "WatermarkHold.addGarbageCollectionHold: garbage collection hold at {} is on time for " + + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + gcHold, context.key(), context.window(), inputWM, outputWM); + return gcHold; } /** @@ -357,17 +414,19 @@ public void prefetchOnMerge(MergingStateAccessor state) { * watermark hold, then earlier holds may be released. */ public void onMerge(ReduceFn.OnMergeContext context) { - WindowTracing.debug("onMerge: for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + WindowTracing.debug("WatermarkHold.onMerge: for key:{}; window:{}; inputWatermark:{}; " + + "outputWatermark:{}", context.key(), context.window(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); StateMerging.mergeWatermarks(context.state(), elementHoldTag, context.window()); // If we had a cheap way to determine if we have an element hold then we could // avoid adding an unnecessary end-of-window or garbage collection hold. // Simply reading the above merged watermark would impose an additional read for the - // common case that the active window has just one undelying state address window and - // the hold depends on the min of the elemest timestamps. + // common case that the active window has just one underlying state address window and + // the hold depends on the min of the element timestamps. + // At least one merged window must be non-empty for the merge to have been triggered. StateMerging.clear(context.state(), EXTRA_HOLD_TAG); - addEndOfWindowOrGarbageCollectionHolds(context); + addEndOfWindowOrGarbageCollectionHolds(context, false /*paneIsEmpty*/); } /** @@ -375,7 +434,8 @@ public void onMerge(ReduceFn.OnMergeContext context) { */ public static class OldAndNewHolds { public final Instant oldHold; - @Nullable public final Instant newHold; + @Nullable + public final Instant newHold; public OldAndNewHolds(Instant oldHold, @Nullable Instant newHold) { this.oldHold = oldHold; @@ -395,7 +455,8 @@ public OldAndNewHolds(Instant oldHold, @Nullable Instant newHold) { public ReadableState extractAndRelease( final ReduceFn.Context context, final boolean isFinished) { WindowTracing.debug( - "extractAndRelease: for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", + "WatermarkHold.extractAndRelease: for key:{}; window:{}; inputWatermark:{}; " + + "outputWatermark:{}", context.key(), context.window(), timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); final WatermarkHoldState elementHoldState = context.state().access(elementHoldTag); @@ -429,7 +490,7 @@ public OldAndNewHolds read() { // the hold was for garbage collection, take the end of window as the result. WindowTracing.debug( "WatermarkHold.extractAndRelease.read: clipping from {} to end of window " - + "for key:{}; window:{}", + + "for key:{}; window:{}", oldHold, context.key(), context.window()); oldHold = context.window().maxTimestamp(); } @@ -444,7 +505,7 @@ public OldAndNewHolds read() { if (!isFinished) { // Only need to leave behind an end-of-window or garbage collection hold // if future elements will be processed. - newHold = addEndOfWindowOrGarbageCollectionHolds(context); + newHold = addEndOfWindowOrGarbageCollectionHolds(context, true /*paneIsEmpty*/); } return new OldAndNewHolds(oldHold, newHold); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index 73b35b66f5..16ffea24f9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -46,7 +46,10 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; import com.google.cloud.dataflow.sdk.transforms.windowing.Repeatedly; @@ -58,6 +61,7 @@ import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; import org.joda.time.Duration; import org.joda.time.Instant; @@ -258,6 +262,7 @@ public void testOnElementCombiningWithContext() throws Exception { .of(FixedWindows.of(Duration.millis(10))) .withTrigger(mockTrigger) .withMode(AccumulationMode.DISCARDING_FIRED_PANES) + .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) .withAllowedLateness(Duration.millis(100)); TestOptions options = PipelineOptionsFactory.as(TestOptions.class); @@ -504,6 +509,7 @@ public void testPaneInfoAllStatesAfterWatermark() throws Exception { AfterWatermark.pastEndOfWindow()))) .withMode(AccumulationMode.DISCARDING_FIRED_PANES) .withAllowedLateness(Duration.millis(100)) + .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); tester.advanceInputWatermark(new Instant(0)); @@ -548,7 +554,34 @@ public void testPaneInfoAllStatesAfterWatermark() throws Exception { } @Test - public void testPaneInfoAllStatesAfterWatermarkAccumulating() throws Exception { + public void noEmptyPanesFinalIfNonEmpty() throws Exception { + ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( + WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) + .withTrigger(Repeatedly.forever(AfterFirst.of( + AfterPane.elementCountAtLeast(2), + AfterWatermark.pastEndOfWindow()))) + .withMode(AccumulationMode.ACCUMULATING_FIRED_PANES) + .withAllowedLateness(Duration.millis(100)) + .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) + .withClosingBehavior(ClosingBehavior.FIRE_IF_NON_EMPTY)); + + tester.advanceInputWatermark(new Instant(0)); + tester.injectElements( + TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(2, new Instant(2))); + tester.advanceInputWatermark(new Instant(20)); + tester.advanceInputWatermark(new Instant(250)); + + List>> output = tester.extractOutput(); + assertThat(output, contains( + // Trigger with 2 elements + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10), + // Trigger for the empty on time pane + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); + } + + @Test + public void noEmptyPanesFinalAlways() throws Exception { ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) .withTrigger(Repeatedly.forever(AfterFirst.of( @@ -556,6 +589,36 @@ public void testPaneInfoAllStatesAfterWatermarkAccumulating() throws Exception { AfterWatermark.pastEndOfWindow()))) .withMode(AccumulationMode.ACCUMULATING_FIRED_PANES) .withAllowedLateness(Duration.millis(100)) + .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) + .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); + + tester.advanceInputWatermark(new Instant(0)); + tester.injectElements( + TimestampedValue.of(1, new Instant(1)), + TimestampedValue.of(2, new Instant(2))); + tester.advanceInputWatermark(new Instant(20)); + tester.advanceInputWatermark(new Instant(250)); + + List>> output = tester.extractOutput(); + assertThat(output, contains( + // Trigger with 2 elements + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10), + // Trigger for the empty on time pane + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10), + // Trigger for the final pane + WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); + } + + @Test + public void testPaneInfoAllStatesAfterWatermarkAccumulating() throws Exception { + ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( + WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) + .withTrigger(Repeatedly.forever(AfterFirst.of( + AfterPane.elementCountAtLeast(2), + AfterWatermark.pastEndOfWindow()))) + .withMode(AccumulationMode.ACCUMULATING_FIRED_PANES) + .withAllowedLateness(Duration.millis(100)) + .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); tester.advanceInputWatermark(new Instant(0)); @@ -777,6 +840,7 @@ public void testMergingWithReusedWindow() throws Exception { // Another element in the same session window. // Should be discarded with 'window closed'. tester.injectElements(TimestampedValue.of(1, new Instant(1))); // in [1, 11), gc at 21. + // And nothing should be left in the active window state. assertTrue(tester.hasNoActiveWindows()); @@ -1140,6 +1204,117 @@ public void testProcessingTime() throws Exception { WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 3, 2))); } + /** + * We should fire a non-empty ON_TIME pane in the GlobalWindow when the watermark moves to + * end-of-time. + */ + @Test + public void fireNonEmptyOnDrainInGlobalWindow() throws Exception { + ReduceFnTester, GlobalWindow> tester = + ReduceFnTester.nonCombining( + WindowingStrategy.of(new GlobalWindows()) + .withTrigger(Repeatedly.forever( + AfterPane.elementCountAtLeast(3))) + .withMode(AccumulationMode.DISCARDING_FIRED_PANES)); + + tester.advanceInputWatermark(new Instant(0)); + + final int n = 20; + for (int i = 0; i < n; i++) { + tester.injectElements(TimestampedValue.of(i, new Instant(i))); + } + + List>> output = tester.extractOutput(); + assertEquals(n / 3, output.size()); + for (int i = 0; i < output.size(); i++) { + assertEquals(Timing.EARLY, output.get(i).getPane().getTiming()); + assertEquals(i, output.get(i).getPane().getIndex()); + assertEquals(3, Iterables.size(output.get(i).getValue())); + } + + tester.advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE); + + output = tester.extractOutput(); + assertEquals(1, output.size()); + assertEquals(Timing.ON_TIME, output.get(0).getPane().getTiming()); + assertEquals(n / 3, output.get(0).getPane().getIndex()); + assertEquals(n - ((n / 3) * 3), Iterables.size(output.get(0).getValue())); + } + + /** + * We should fire an empty ON_TIME pane in the GlobalWindow when the watermark moves to + * end-of-time. + */ + @Test + public void fireEmptyOnDrainInGlobalWindowIfRequested() throws Exception { + ReduceFnTester, GlobalWindow> tester = + ReduceFnTester.nonCombining( + WindowingStrategy.of(new GlobalWindows()) + .withTrigger(Repeatedly.forever( + AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(new Duration(3)))) + .withMode(AccumulationMode.DISCARDING_FIRED_PANES)); + + final int n = 20; + for (int i = 0; i < n; i++) { + tester.advanceProcessingTime(new Instant(i)); + tester.injectElements(TimestampedValue.of(i, new Instant(i))); + } + tester.advanceProcessingTime(new Instant(n + 4)); + List>> output = tester.extractOutput(); + assertEquals((n + 3) / 4, output.size()); + for (int i = 0; i < output.size(); i++) { + assertEquals(Timing.EARLY, output.get(i).getPane().getTiming()); + assertEquals(i, output.get(i).getPane().getIndex()); + assertEquals(4, Iterables.size(output.get(i).getValue())); + } + + tester.advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE); + + output = tester.extractOutput(); + assertEquals(1, output.size()); + assertEquals(Timing.ON_TIME, output.get(0).getPane().getTiming()); + assertEquals((n + 3) / 4, output.get(0).getPane().getIndex()); + assertEquals(0, Iterables.size(output.get(0).getValue())); + } + + /** + * Late elements should still have a garbage collection hold set so that they + * can make a late pane rather than be dropped due to lateness. + */ + @Test + public void setGarbageCollectionHoldOnLateElements() throws Exception { + ReduceFnTester, IntervalWindow> tester = + ReduceFnTester.nonCombining( + FixedWindows.of(Duration.millis(10)), + AfterWatermark.pastEndOfWindow() + .withLateFirings(AfterPane.elementCountAtLeast(2)), + AccumulationMode.DISCARDING_FIRED_PANES, + Duration.millis(100), + ClosingBehavior.FIRE_IF_NON_EMPTY); + + tester.advanceInputWatermark(new Instant(0)); + tester.advanceOutputWatermark(new Instant(0)); + tester.injectElements(TimestampedValue.of(1, new Instant(1))); + + // Fire ON_TIME pane @ 9 with 1 + + tester.advanceInputWatermark(new Instant(109)); + tester.advanceOutputWatermark(new Instant(109)); + tester.injectElements(TimestampedValue.of(2, new Instant(2))); + // We should have set a garbage collection hold for the final pane. + Instant hold = tester.getWatermarkHold(); + assertEquals(new Instant(109), hold); + + tester.advanceInputWatermark(new Instant(110)); + tester.advanceOutputWatermark(new Instant(110)); + + // Fire final LATE pane @ 9 with 2 + + List>> output = tester.extractOutput(); + assertEquals(2, output.size()); + } + private static class SumAndVerifyContextFn extends CombineFnWithContext { private final PCollectionView view; From 8de49f76cbcea5ef4652b1c30833bda3f7e521e2 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Wed, 1 Jun 2016 20:50:41 -0700 Subject: [PATCH 437/751] Use Structural Value keys instead of User Values (#291) * Use Structural Value keys instead of User Values This fixes problems with lookup by basing entirely on structural equality. --- .../sdk/runners/inprocess/BundleFactory.java | 4 +- .../ExecutorServiceParallelExecutor.java | 8 +- .../inprocess/GroupByKeyEvaluatorFactory.java | 6 +- .../ImmutabilityCheckingBundleFactory.java | 4 +- .../inprocess/InMemoryWatermarkManager.java | 70 +++++++------- .../inprocess/InProcessBundleFactory.java | 25 +++-- .../inprocess/InProcessEvaluationContext.java | 10 +- .../inprocess/InProcessExecutionContext.java | 4 +- .../inprocess/InProcessPipelineRunner.java | 7 +- .../sdk/runners/inprocess/StepAndKey.java | 8 +- .../sdk/runners/inprocess/StructuralKey.java | 74 +++++++++++++++ .../GroupByKeyEvaluatorFactoryTest.java | 27 ++++-- ...ImmutabilityCheckingBundleFactoryTest.java | 13 ++- .../InMemoryWatermarkManagerTest.java | 95 +++++++++++-------- .../inprocess/InProcessBundleFactoryTest.java | 54 ++++++----- .../InProcessEvaluationContextTest.java | 52 ++++++---- .../InProcessPipelineRunnerTest.java | 59 ++++++++++++ .../InProcessTimerInternalsTest.java | 3 +- .../ParDoInProcessEvaluatorTest.java | 2 +- .../ParDoMultiEvaluatorFactoryTest.java | 29 +++--- .../ParDoSingleEvaluatorFactoryTest.java | 35 ++++--- .../runners/inprocess/StructuralKeyTest.java | 79 +++++++++++++++ 22 files changed, 471 insertions(+), 197 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java index 84403afc8a..f2852957c5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java @@ -42,7 +42,7 @@ public interface BundleFactory { * {@link InProcessGroupByKeyOnly} {@link PTransform PTransforms}. Elements added to the bundle * belong to the {@code output} {@link PCollection}. */ - public UncommittedBundle createKeyedBundle( - CommittedBundle input, Object key, PCollection output); + public UncommittedBundle createKeyedBundle( + CommittedBundle input, StructuralKey key, PCollection output); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index 3d15e45413..b5ae114be3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -393,17 +393,19 @@ public void run() { private boolean fireTimers() throws Exception { try { boolean firedTimers = false; - for (Map.Entry, Map> transformTimers : + for (Map.Entry< + AppliedPTransform, Map, FiredTimers>> transformTimers : evaluationContext.extractFiredTimers().entrySet()) { AppliedPTransform transform = transformTimers.getKey(); - for (Map.Entry keyTimers : transformTimers.getValue().entrySet()) { + for (Map.Entry, FiredTimers> keyTimers : + transformTimers.getValue().entrySet()) { for (TimeDomain domain : TimeDomain.values()) { Collection delivery = keyTimers.getValue().getTimers(domain); if (delivery.isEmpty()) { continue; } KeyedWorkItem work = - KeyedWorkItems.timersWorkItem(keyTimers.getKey(), delivery); + KeyedWorkItems.timersWorkItem(keyTimers.getKey().getKey(), delivery); @SuppressWarnings({"unchecked", "rawtypes"}) CommittedBundle bundle = evaluationContext diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java index f71d2ee745..2dacf665ae 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java @@ -145,8 +145,10 @@ public InProcessTransformResult finishBundle() { K key = groupedEntry.getKey().key; KeyedWorkItem groupedKv = KeyedWorkItems.elementsWorkItem(key, groupedEntry.getValue()); - UncommittedBundle> bundle = - evaluationContext.createKeyedBundle(inputBundle, key, application.getOutput()); + UncommittedBundle> bundle = evaluationContext.createKeyedBundle( + inputBundle, + StructuralKey.of(key, keyCoder), + application.getOutput()); bundle.add(WindowedValue.valueInGlobalWindow(groupedKv)); resultBuilder.addOutput(bundle); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java index 56fde7577b..4f7b73c9de 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java @@ -69,8 +69,8 @@ public UncommittedBundle createBundle(CommittedBundle input, PCollecti } @Override - public UncommittedBundle createKeyedBundle( - CommittedBundle input, Object key, PCollection output) { + public UncommittedBundle createKeyedBundle( + CommittedBundle input, StructuralKey key, PCollection output) { return new ImmutabilityEnforcingBundle<>(underlying.createKeyedBundle(input, key, output)); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 992c13f5ab..0f804491ef 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -204,7 +204,7 @@ public static WatermarkUpdate fromTimestamps(Instant oldTime, Instant currentTim private static class AppliedPTransformInputWatermark implements Watermark { private final Collection inputWatermarks; private final SortedMultiset> pendingElements; - private final Map> objectTimers; + private final Map, NavigableSet> objectTimers; private AtomicReference currentWatermark; @@ -283,7 +283,7 @@ private synchronized void updateTimers(TimerUpdate update) { // We don't keep references to timers that have been fired and delivered via #getFiredTimers() } - private synchronized Map> extractFiredEventTimeTimers() { + private synchronized Map, List> extractFiredEventTimeTimers() { return extractFiredTimers(currentWatermark.get(), objectTimers); } @@ -381,8 +381,8 @@ public synchronized String toString() { private static class SynchronizedProcessingTimeInputWatermark implements Watermark { private final Collection inputWms; private final Collection> pendingBundles; - private final Map> processingTimers; - private final Map> synchronizedProcessingTimers; + private final Map, NavigableSet> processingTimers; + private final Map, NavigableSet> synchronizedProcessingTimers; private final PriorityQueue pendingTimers; @@ -487,9 +487,9 @@ private synchronized void updateTimers(TimerUpdate update) { } } - private synchronized Map> extractFiredDomainTimers( + private synchronized Map, List> extractFiredDomainTimers( TimeDomain domain, Instant firingTime) { - Map> firedTimers; + Map, List> firedTimers; switch (domain) { case PROCESSING_TIME: firedTimers = extractFiredTimers(firingTime, processingTimers); @@ -506,13 +506,14 @@ private synchronized Map> extractFiredDomainTimers( + " and gave a non-processing time domain " + domain); } - for (Map.Entry> firedTimer : firedTimers.entrySet()) { + for (Map.Entry, ? extends Collection> firedTimer : + firedTimers.entrySet()) { pendingTimers.addAll(firedTimer.getValue()); } return firedTimers; } - private Map> timerMap(Object key) { + private Map> timerMap(StructuralKey key) { NavigableSet processingQueue = processingTimers.get(key); if (processingQueue == null) { processingQueue = new TreeSet<>(); @@ -644,11 +645,12 @@ public Iterable> apply(WindowedValue input) { * * The result collection retains ordering of timers (from earliest to latest). */ - private static Map> extractFiredTimers( - Instant latestTime, Map> objectTimers) { - Map> result = new HashMap<>(); - Set emptyKeys = new HashSet<>(); - for (Map.Entry> pendingTimers : objectTimers.entrySet()) { + private static Map, List> extractFiredTimers( + Instant latestTime, Map, NavigableSet> objectTimers) { + Map, List> result = new HashMap<>(); + Set> emptyKeys = new HashSet<>(); + for (Map.Entry, NavigableSet> pendingTimers : + objectTimers.entrySet()) { NavigableSet timers = pendingTimers.getValue(); if (!timers.isEmpty() && timers.first().getTimestamp().isBefore(latestTime)) { ArrayList keyFiredTimers = new ArrayList<>(); @@ -920,11 +922,12 @@ private void refreshWatermarks(AppliedPTransform toRefresh) { * Returns a map of each {@link PTransform} that has pending timers to those timers. All of the * pending timers will be removed from this {@link InMemoryWatermarkManager}. */ - public Map, Map> extractFiredTimers() { - Map, Map> allTimers = new HashMap<>(); + public Map, Map, FiredTimers>> extractFiredTimers() { + Map, Map, FiredTimers>> allTimers = new HashMap<>(); for (Map.Entry, TransformWatermarks> watermarksEntry : transformToWatermarks.entrySet()) { - Map keyFiredTimers = watermarksEntry.getValue().extractFiredTimers(); + Map, FiredTimers> keyFiredTimers = + watermarksEntry.getValue().extractFiredTimers(); if (!keyFiredTimers.isEmpty()) { allTimers.put(watermarksEntry.getKey(), keyFiredTimers); } @@ -1127,10 +1130,11 @@ private Iterable> elementsFromBundle(CommittedBundle< return FluentIterable.from(bundle.getElements()).transformAndConcat(EXPLODE_WINDOWS_FN); } - private Map extractFiredTimers() { - Map> eventTimeTimers = inputWatermark.extractFiredEventTimeTimers(); - Map> processingTimers; - Map> synchronizedTimers; + private Map, FiredTimers> extractFiredTimers() { + Map, List> eventTimeTimers = + inputWatermark.extractFiredEventTimeTimers(); + Map, List> processingTimers; + Map, List> synchronizedTimers; if (inputWatermark.get().equals(BoundedWindow.TIMESTAMP_MAX_VALUE)) { processingTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( TimeDomain.PROCESSING_TIME, BoundedWindow.TIMESTAMP_MAX_VALUE); @@ -1142,11 +1146,11 @@ private Map extractFiredTimers() { synchronizedTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( TimeDomain.SYNCHRONIZED_PROCESSING_TIME, getSynchronizedProcessingInputTime()); } - Map>> groupedTimers = new HashMap<>(); + Map, Map>> groupedTimers = new HashMap<>(); groupFiredTimers(groupedTimers, eventTimeTimers, processingTimers, synchronizedTimers); - Map keyFiredTimers = new HashMap<>(); - for (Map.Entry>> firedTimers : + Map, FiredTimers> keyFiredTimers = new HashMap<>(); + for (Map.Entry, Map>> firedTimers : groupedTimers.entrySet()) { keyFiredTimers.put(firedTimers.getKey(), new FiredTimers(firedTimers.getValue())); } @@ -1155,10 +1159,10 @@ private Map extractFiredTimers() { @SafeVarargs private final void groupFiredTimers( - Map>> groupedToMutate, - Map>... timersToGroup) { - for (Map> subGroup : timersToGroup) { - for (Map.Entry> newTimers : subGroup.entrySet()) { + Map, Map>> groupedToMutate, + Map, List>... timersToGroup) { + for (Map, List> subGroup : timersToGroup) { + for (Map.Entry, List> newTimers : subGroup.entrySet()) { Map> grouped = groupedToMutate.get(newTimers.getKey()); if (grouped == null) { grouped = new HashMap<>(); @@ -1193,7 +1197,7 @@ public String toString() { * the input to the executed step. */ public static class TimerUpdate { - private final Object key; + private final StructuralKey key; private final Iterable completedTimers; private final Iterable setTimers; @@ -1214,7 +1218,7 @@ public static TimerUpdate empty() { * Creates a new {@link TimerUpdate} builder with the provided completed timers that needs the * set and deleted timers to be added to it. */ - public static TimerUpdateBuilder builder(Object key) { + public static TimerUpdateBuilder builder(StructuralKey key) { return new TimerUpdateBuilder(key); } @@ -1222,12 +1226,12 @@ public static TimerUpdateBuilder builder(Object key) { * A {@link TimerUpdate} builder that needs to be provided with set timers and deleted timers. */ public static final class TimerUpdateBuilder { - private final Object key; + private final StructuralKey key; private final Collection completedTimers; private final Collection setTimers; private final Collection deletedTimers; - private TimerUpdateBuilder(Object key) { + private TimerUpdateBuilder(StructuralKey key) { this.key = key; this.completedTimers = new HashSet<>(); this.setTimers = new HashSet<>(); @@ -1277,7 +1281,7 @@ public TimerUpdate build() { } private TimerUpdate( - Object key, + StructuralKey key, Iterable completedTimers, Iterable setTimers, Iterable deletedTimers) { @@ -1288,7 +1292,7 @@ private TimerUpdate( } @VisibleForTesting - Object getKey() { + StructuralKey getKey() { return key; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java index 73a18dbf33..d6f7cb4f61 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java @@ -17,6 +17,7 @@ import static com.google.common.base.Preconditions.checkState; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.util.WindowedValue; @@ -26,8 +27,6 @@ import org.joda.time.Instant; -import javax.annotation.Nullable; - /** * A factory that produces bundles that perform no additional validation. */ @@ -40,7 +39,7 @@ private InProcessBundleFactory() {} @Override public UncommittedBundle createRootBundle(PCollection output) { - return InProcessBundle.create(output, null); + return InProcessBundle.create(output, StructuralKey.of(null, VoidCoder.of())); } @Override @@ -49,8 +48,8 @@ public UncommittedBundle createBundle(CommittedBundle input, PCollecti } @Override - public UncommittedBundle createKeyedBundle( - CommittedBundle input, @Nullable Object key, PCollection output) { + public UncommittedBundle createKeyedBundle( + CommittedBundle input, StructuralKey key, PCollection output) { return InProcessBundle.create(output, key); } @@ -59,18 +58,18 @@ public UncommittedBundle createKeyedBundle( */ private static final class InProcessBundle implements UncommittedBundle { private final PCollection pcollection; - @Nullable private final Object key; + private final StructuralKey key; private boolean committed = false; private ImmutableList.Builder> elements; /** * Create a new {@link InProcessBundle} for the specified {@link PCollection}. */ - public static InProcessBundle create(PCollection pcollection, @Nullable Object key) { - return new InProcessBundle(pcollection, key); + public static InProcessBundle create(PCollection pcollection, StructuralKey key) { + return new InProcessBundle<>(pcollection, key); } - private InProcessBundle(PCollection pcollection, Object key) { + private InProcessBundle(PCollection pcollection, StructuralKey key) { this.pcollection = pcollection; this.key = key; this.elements = ImmutableList.builder(); @@ -105,7 +104,7 @@ public CommittedBundle commit(final Instant synchronizedCompletionTime) { private static class CommittedInProcessBundle implements CommittedBundle { public CommittedInProcessBundle( PCollection pcollection, - Object key, + StructuralKey key, Iterable> committedElements, Instant synchronizedCompletionTime) { this.pcollection = pcollection; @@ -115,13 +114,13 @@ public CommittedInProcessBundle( } private final PCollection pcollection; - private final Object key; + /** The structural value key of the Bundle, as specified by the coder that created it. */ + private final StructuralKey key; private final Iterable> committedElements; private final Instant synchronizedCompletionTime; @Override - @Nullable - public Object getKey() { + public StructuralKey getKey() { return key; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index ac4399c59b..b2ad161337 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -230,8 +230,8 @@ public UncommittedBundle createBundle(CommittedBundle input, PCollecti * Create a {@link UncommittedBundle} with the specified keys at the specified step. For use by * {@link InProcessGroupByKeyOnly} {@link PTransform PTransforms}. */ - public UncommittedBundle createKeyedBundle( - CommittedBundle input, Object key, PCollection output) { + public UncommittedBundle createKeyedBundle( + CommittedBundle input, StructuralKey key, PCollection output) { return bundleFactory.createKeyedBundle(input, key, output); } @@ -299,7 +299,7 @@ public InProcessPipelineOptions getPipelineOptions() { * Get an {@link ExecutionContext} for the provided {@link AppliedPTransform} and key. */ public InProcessExecutionContext getExecutionContext( - AppliedPTransform application, Object key) { + AppliedPTransform application, StructuralKey key) { StepAndKey stepAndKey = StepAndKey.of(application, key); return new InProcessExecutionContext( options.getClock(), @@ -368,9 +368,9 @@ void forceRefresh() { *

            This is a destructive operation. Timers will only appear in the result of this method once * for each time they are set. */ - public Map, Map> extractFiredTimers() { + public Map, Map, FiredTimers>> extractFiredTimers() { forceRefresh(); - Map, Map> fired = + Map, Map, FiredTimers>> fired = watermarkManager.extractFiredTimers(); return fired; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java index 43cd9eb573..31557d35fa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java @@ -32,11 +32,11 @@ class InProcessExecutionContext extends BaseExecutionContext { private final Clock clock; - private final Object key; + private final StructuralKey key; private final CopyOnAccessInMemoryStateInternals existingState; private final TransformWatermarks watermarks; - public InProcessExecutionContext(Clock clock, Object key, + public InProcessExecutionContext(Clock clock, StructuralKey key, CopyOnAccessInMemoryStateInternals existingState, TransformWatermarks watermarks) { this.clock = clock; this.key = key; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 30631f3121..1a3fd1e3cc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -60,8 +60,6 @@ import java.util.Map; import java.util.concurrent.ExecutorService; -import javax.annotation.Nullable; - /** * An In-Memory implementation of the Dataflow Programming Model. Supports Unbounded * {@link PCollection PCollections}. @@ -131,11 +129,10 @@ public static interface CommittedBundle { PCollection getPCollection(); /** - * Returns the (possibly null) key that was output in the most recent {@link GroupByKey} in the + * Returns the key that was output in the most recent {@link GroupByKey} in the * execution of this bundle. */ - @Nullable - Object getKey(); + StructuralKey getKey(); /** * Returns an {@link Iterable} containing all of the elements that have been added to this diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java index 15955724eb..feba98f001 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java @@ -26,16 +26,16 @@ */ final class StepAndKey { private final AppliedPTransform step; - private final Object key; + private final StructuralKey key; /** * Create a new {@link StepAndKey} with the provided step and key. */ - public static StepAndKey of(AppliedPTransform step, Object key) { + public static StepAndKey of(AppliedPTransform step, StructuralKey key) { return new StepAndKey(step, key); } - private StepAndKey(AppliedPTransform step, Object key) { + private StepAndKey(AppliedPTransform step, StructuralKey key) { this.step = step; this.key = key; } @@ -44,7 +44,7 @@ private StepAndKey(AppliedPTransform step, Object key) { public String toString() { return MoreObjects.toStringHelper(StepAndKey.class) .add("step", step.getFullName()) - .add("key", key) + .add("key", key.getKey()) .toString(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java new file mode 100644 index 0000000000..a1fe07e4d9 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.util.CoderUtils; + +/** + * A (Key, Coder) pair that uses the structural value of the key (as provided by + * {@link Coder#structuralValue(Object)}) to perform equality and hashing. + */ +class StructuralKey { + /** + * Create a new Structural Key of the provided key that can be encoded by the provided coder. + */ + public static StructuralKey of(K key, Coder coder) { + try { + return new StructuralKey<>(coder, key); + } catch (Exception e) { + throw new IllegalArgumentException( + "Could not encode a key with its provided coder " + coder.getClass().getSimpleName(), e); + } + } + + private final Coder coder; + private final Object structuralValue; + private final byte[] encoded; + + private StructuralKey(Coder coder, K key) throws Exception { + this.coder = coder; + this.structuralValue = coder.structuralValue(key); + this.encoded = CoderUtils.encodeToByteArray(coder, key); + } + + public K getKey() { + try { + return CoderUtils.decodeFromByteArray(coder, encoded); + } catch (CoderException e) { + throw new IllegalArgumentException( + "Could not decode Key with coder of type " + coder.getClass().getSimpleName()); + } + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (other instanceof StructuralKey) { + StructuralKey that = (StructuralKey) other; + return structuralValue.equals(that.structuralValue); + } + return false; + } + + @Override + public int hashCode() { + return structuralValue.hashCode(); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java index deb2a64e78..5e8654be5b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java @@ -22,6 +22,7 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -69,17 +70,27 @@ public void testInMemoryEvaluator() throws Exception { CommittedBundle>> inputBundle = bundleFactory.createRootBundle(kvs).commit(Instant.now()); InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - + StructuralKey fooKey = StructuralKey.of("foo", StringUtf8Coder.of()); UncommittedBundle> fooBundle = - bundleFactory.createKeyedBundle(null, "foo", groupedKvs); + bundleFactory.createKeyedBundle(null, fooKey, groupedKvs); + + StructuralKey barKey = StructuralKey.of("bar", StringUtf8Coder.of()); UncommittedBundle> barBundle = - bundleFactory.createKeyedBundle(null, "bar", groupedKvs); - UncommittedBundle> bazBundle = - bundleFactory.createKeyedBundle(null, "baz", groupedKvs); + bundleFactory.createKeyedBundle(null, barKey, groupedKvs); - when(evaluationContext.createKeyedBundle(inputBundle, "foo", groupedKvs)).thenReturn(fooBundle); - when(evaluationContext.createKeyedBundle(inputBundle, "bar", groupedKvs)).thenReturn(barBundle); - when(evaluationContext.createKeyedBundle(inputBundle, "baz", groupedKvs)).thenReturn(bazBundle); + StructuralKey bazKey = StructuralKey.of("baz", StringUtf8Coder.of()); + UncommittedBundle> bazBundle = + bundleFactory.createKeyedBundle(null, bazKey, groupedKvs); + + when(evaluationContext.createKeyedBundle(inputBundle, + fooKey, + groupedKvs)).thenReturn(fooBundle); + when(evaluationContext.createKeyedBundle(inputBundle, + barKey, + groupedKvs)).thenReturn(barBundle); + when(evaluationContext.createKeyedBundle(inputBundle, + bazKey, + groupedKvs)).thenReturn(bazBundle); // The input to a GroupByKey is assumed to be a KvCoder @SuppressWarnings("unchecked") diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java index 7d29061335..b21a6b11e6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -73,7 +74,9 @@ public void noMutationRootBundleSucceeds() { @Test public void noMutationKeyedBundleSucceeds() { CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle keyed = factory.createKeyedBundle(root, "mykey", transformed); + UncommittedBundle keyed = factory.createKeyedBundle(root, + StructuralKey.of("mykey", StringUtf8Coder.of()), + transformed); WindowedValue windowedArray = WindowedValue.of( @@ -119,7 +122,9 @@ public void mutationBeforeAddRootBundleSucceeds() { @Test public void mutationBeforeAddKeyedBundleSucceeds() { CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle keyed = factory.createKeyedBundle(root, "mykey", transformed); + UncommittedBundle keyed = factory.createKeyedBundle(root, + StructuralKey.of("mykey", StringUtf8Coder.of()), + transformed); byte[] array = new byte[] {4, 8, 12}; array[0] = Byte.MAX_VALUE; @@ -170,7 +175,9 @@ public void mutationAfterAddRootBundleThrows() { @Test public void mutationAfterAddKeyedBundleThrows() { CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle keyed = factory.createKeyedBundle(root, "mykey", transformed); + UncommittedBundle keyed = factory.createKeyedBundle(root, + StructuralKey.of("mykey", StringUtf8Coder.of()), + transformed); byte[] array = new byte[] {4, 8, 12}; WindowedValue windowedArray = diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index 83e33d9cb7..f9f5c99d71 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -23,6 +23,9 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; @@ -394,16 +397,18 @@ public void updateWatermarkWithWatermarkHolds() { */ @Test public void updateWatermarkWithKeyedWatermarkHolds() { - CommittedBundle firstKeyBundle = - bundleFactory.createKeyedBundle(null, "Odd", createdInts) - .add(WindowedValue.timestampedValueInGlobalWindow(1, new Instant(1_000_000L))) - .add(WindowedValue.timestampedValueInGlobalWindow(3, new Instant(-1000L))) - .commit(clock.now()); + CommittedBundle firstKeyBundle = bundleFactory.createKeyedBundle(null, + StructuralKey.of("Odd", StringUtf8Coder.of()), + createdInts) + .add(WindowedValue.timestampedValueInGlobalWindow(1, new Instant(1_000_000L))) + .add(WindowedValue.timestampedValueInGlobalWindow(3, new Instant(-1000L))) + .commit(clock.now()); - CommittedBundle secondKeyBundle = - bundleFactory.createKeyedBundle(null, "Even", createdInts) - .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) - .commit(clock.now()); + CommittedBundle secondKeyBundle = bundleFactory.createKeyedBundle(null, + StructuralKey.of("Even", StringUtf8Coder.of()), + createdInts) + .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) + .commit(clock.now()); manager.updateWatermarks(null, TimerUpdate.empty(), @@ -432,8 +437,9 @@ public void updateWatermarkWithKeyedWatermarkHolds() { not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); - CommittedBundle fauxFirstKeyTimerBundle = - bundleFactory.createKeyedBundle(null, "Odd", createdInts).commit(clock.now()); + CommittedBundle fauxFirstKeyTimerBundle = bundleFactory.createKeyedBundle(null, + StructuralKey.of("Odd", StringUtf8Coder.of()), + createdInts).commit(clock.now()); manager.updateWatermarks(fauxFirstKeyTimerBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), @@ -444,8 +450,9 @@ public void updateWatermarkWithKeyedWatermarkHolds() { assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(1234L))); - CommittedBundle fauxSecondKeyTimerBundle = - bundleFactory.createKeyedBundle(null, "Even", createdInts).commit(clock.now()); + CommittedBundle fauxSecondKeyTimerBundle = bundleFactory.createKeyedBundle(null, + StructuralKey.of("Even", StringUtf8Coder.of()), + createdInts).commit(clock.now()); manager.updateWatermarks(fauxSecondKeyTimerBundle, TimerUpdate.empty(), result(filtered.getProducingTransformInternal(), @@ -843,13 +850,14 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { Instant initialFilteredWm = filteredWms.getSynchronizedProcessingOutputTime(); Instant initialFilteredDoubledWm = filteredDoubledWms.getSynchronizedProcessingOutputTime(); + StructuralKey key = StructuralKey.of("key", StringUtf8Coder.of()); CommittedBundle filteredBundle = multiWindowedBundle(filtered, 2, 8); TimerData pastTimer = TimerData.of(StateNamespaces.global(), new Instant(250L), TimeDomain.PROCESSING_TIME); TimerData futureTimer = TimerData.of(StateNamespaces.global(), new Instant(4096L), TimeDomain.PROCESSING_TIME); TimerUpdate timers = - TimerUpdate.builder("key").setTimer(pastTimer).setTimer(futureTimer).build(); + TimerUpdate.builder(key).setTimer(pastTimer).setTimer(futureTimer).build(); manager.updateWatermarks(createdBundle, timers, result(filtered.getProducingTransformInternal(), @@ -869,11 +877,11 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(earlierThan(initialFilteredDoubledWm))); - Map, Map> firedTimers = + Map, Map, FiredTimers>> firedTimers = manager.extractFiredTimers(); assertThat( firedTimers.get(filtered.getProducingTransformInternal()) - .get("key") + .get(key) .getTimers(TimeDomain.PROCESSING_TIME), contains(pastTimer)); // Our timer has fired, but has not been completed, so it holds our synchronized processing WM @@ -882,14 +890,14 @@ public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { CommittedBundle filteredTimerBundle = bundleFactory - .createKeyedBundle(null, "key", filtered) + .createKeyedBundle(null, key, filtered) .commit(BoundedWindow.TIMESTAMP_MAX_VALUE); CommittedBundle filteredTimerResult = - bundleFactory.createKeyedBundle(null, "key", filteredTimesTwo) + bundleFactory.createKeyedBundle(null, key, filteredTimesTwo) .commit(filteredWms.getSynchronizedProcessingOutputTime()); // Complete the processing time timer manager.updateWatermarks(filteredTimerBundle, - TimerUpdate.builder("key") + TimerUpdate.builder(key) .withCompletedTimers(Collections.singleton(pastTimer)).build(), result(filtered.getProducingTransformInternal(), filteredTimerBundle.withElements(Collections.>emptyList()), @@ -985,7 +993,9 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( TimerData upstreamProcessingTimer = TimerData.of(StateNamespaces.global(), upstreamHold, TimeDomain.PROCESSING_TIME); manager.updateWatermarks(created, - TimerUpdate.builder("key").setTimer(upstreamProcessingTimer).build(), + TimerUpdate.builder(StructuralKey.of("key", StringUtf8Coder.of())) + .setTimer(upstreamProcessingTimer) + .build(), result(filtered.getProducingTransformInternal(), created.withElements(Collections.>emptyList()), Collections.>singleton(filteredBundle)), @@ -1006,7 +1016,7 @@ public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers( CommittedBundle otherCreated = multiWindowedBundle(createdInts, 4, 8, 12); manager.updateWatermarks(otherCreated, - TimerUpdate.builder("key") + TimerUpdate.builder(StructuralKey.of("key", StringUtf8Coder.of())) .withCompletedTimers(Collections.singleton(upstreamProcessingTimer)).build(), result(filtered.getProducingTransformInternal(), otherCreated.withElements(Collections.>emptyList()), @@ -1029,8 +1039,9 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { new Instant(29_919_235L)); Instant upstreamHold = new Instant(2048L); - CommittedBundle filteredBundle = - bundleFactory.createKeyedBundle(created, "key", filtered).commit(upstreamHold); + CommittedBundle filteredBundle = bundleFactory.createKeyedBundle(created, + StructuralKey.of("key", StringUtf8Coder.of()), + filtered).commit(upstreamHold); manager.updateWatermarks( created, TimerUpdate.empty(), @@ -1050,7 +1061,7 @@ public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { @Test public void extractFiredTimersReturnsFiredEventTimeTimers() { - Map, Map> initialTimers = + Map, Map, FiredTimers>> initialTimers = manager.extractFiredTimers(); // Watermarks haven't advanced assertThat(initialTimers.entrySet(), emptyIterable()); @@ -1071,7 +1082,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { TimerData.of(StateNamespaces.global(), new Instant(5000L), TimeDomain.EVENT_TIME); TimerData lastTimer = TimerData.of(StateNamespaces.global(), new Instant(10000L), TimeDomain.EVENT_TIME); - Object key = new Object(); + StructuralKey key = StructuralKey.of(new byte[] {1, 4, 9}, ByteArrayCoder.of()); TimerUpdate update = TimerUpdate.builder(key) .setTimer(earliestTimer) @@ -1087,11 +1098,11 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { new Instant(1000L)); manager.refreshAll(); - Map, Map> firstTransformFiredTimers = + Map, Map, FiredTimers>> firstTransformFiredTimers = manager.extractFiredTimers(); assertThat( firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map firstFilteredTimers = + Map, FiredTimers> firstFilteredTimers = firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); assertThat(firstFilteredTimers.get(key), not(nullValue())); FiredTimers firstFired = firstFilteredTimers.get(key); @@ -1104,11 +1115,11 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { Collections.>emptyList()), new Instant(50_000L)); manager.refreshAll(); - Map, Map> secondTransformFiredTimers = + Map, Map, FiredTimers>> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map secondFilteredTimers = + Map, FiredTimers> secondFilteredTimers = secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); assertThat(secondFilteredTimers.get(key), not(nullValue())); FiredTimers secondFired = secondFilteredTimers.get(key); @@ -1118,7 +1129,7 @@ public void extractFiredTimersReturnsFiredEventTimeTimers() { @Test public void extractFiredTimersReturnsFiredProcessingTimeTimers() { - Map, Map> initialTimers = + Map, Map, FiredTimers>> initialTimers = manager.extractFiredTimers(); // Watermarks haven't advanced assertThat(initialTimers.entrySet(), emptyIterable()); @@ -1138,7 +1149,7 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { TimerData.of(StateNamespaces.global(), new Instant(5000L), TimeDomain.PROCESSING_TIME); TimerData lastTimer = TimerData.of(StateNamespaces.global(), new Instant(10000L), TimeDomain.PROCESSING_TIME); - Object key = new Object(); + StructuralKey key = StructuralKey.of(-12L, VarLongCoder.of()); TimerUpdate update = TimerUpdate.builder(key) .setTimer(lastTimer) @@ -1155,11 +1166,11 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { new Instant(1000L)); manager.refreshAll(); - Map, Map> firstTransformFiredTimers = + Map, Map, FiredTimers>> firstTransformFiredTimers = manager.extractFiredTimers(); assertThat( firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map firstFilteredTimers = + Map, FiredTimers> firstFilteredTimers = firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); assertThat(firstFilteredTimers.get(key), not(nullValue())); FiredTimers firstFired = firstFilteredTimers.get(key); @@ -1173,11 +1184,11 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { Collections.>emptyList()), new Instant(50_000L)); manager.refreshAll(); - Map, Map> secondTransformFiredTimers = + Map, Map, FiredTimers>> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map secondFilteredTimers = + Map, FiredTimers> secondFilteredTimers = secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); assertThat(secondFilteredTimers.get(key), not(nullValue())); FiredTimers secondFired = secondFilteredTimers.get(key); @@ -1187,7 +1198,7 @@ public void extractFiredTimersReturnsFiredProcessingTimeTimers() { @Test public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { - Map, Map> initialTimers = + Map, Map, FiredTimers>> initialTimers = manager.extractFiredTimers(); // Watermarks haven't advanced assertThat(initialTimers.entrySet(), emptyIterable()); @@ -1207,7 +1218,7 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { StateNamespaces.global(), new Instant(5000L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); TimerData lastTimer = TimerData.of( StateNamespaces.global(), new Instant(10000L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - Object key = new Object(); + StructuralKey key = StructuralKey.of(new byte[] {2, -2, 22}, ByteArrayCoder.of()); TimerUpdate update = TimerUpdate.builder(key) .setTimer(lastTimer) @@ -1224,11 +1235,11 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { new Instant(1000L)); manager.refreshAll(); - Map, Map> firstTransformFiredTimers = + Map, Map, FiredTimers>> firstTransformFiredTimers = manager.extractFiredTimers(); assertThat( firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map firstFilteredTimers = + Map, FiredTimers> firstFilteredTimers = firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); assertThat(firstFilteredTimers.get(key), not(nullValue())); FiredTimers firstFired = firstFilteredTimers.get(key); @@ -1243,11 +1254,11 @@ public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { Collections.>emptyList()), new Instant(50_000L)); manager.refreshAll(); - Map, Map> secondTransformFiredTimers = + Map, Map, FiredTimers>> secondTransformFiredTimers = manager.extractFiredTimers(); assertThat( secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map secondFilteredTimers = + Map, FiredTimers> secondFilteredTimers = secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); assertThat(secondFilteredTimers.get(key), not(nullValue())); FiredTimers secondFired = secondFilteredTimers.get(key); @@ -1268,7 +1279,7 @@ public void timerUpdateBuilderBuildAddsAllAddedTimers() { TimerData.of(StateNamespaces.global(), new Instant(2048L), TimeDomain.EVENT_TIME); TimerUpdate update = - TimerUpdate.builder("foo") + TimerUpdate.builder(StructuralKey.of("foo", StringUtf8Coder.of())) .withCompletedTimers(ImmutableList.of(completedOne, completedTwo)) .setTimer(set) .deletedTimer(deleted) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java index a88f6b3ddc..4cc5a37aa7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java @@ -17,9 +17,13 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; @@ -66,34 +70,38 @@ public void setup() { } @Test - public void createRootBundleShouldCreateWithNullKey() { + public void createRootBundleShouldCreateWithEmptyKey() { PCollection pcollection = TestPipeline.create().apply(Create.of(1)); UncommittedBundle inFlightBundle = bundleFactory.createRootBundle(pcollection); CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - assertThat(bundle.getKey(), nullValue()); + assertThat(bundle.getKey(), + Matchers.>equalTo(StructuralKey.of(null, VoidCoder.of()))); } - private void createKeyedBundle(Object key) { + private void createKeyedBundle(Coder coder, T key) throws Exception { PCollection pcollection = TestPipeline.create().apply(Create.of(1)); + StructuralKey skey = StructuralKey.of(key, coder); UncommittedBundle inFlightBundle = - bundleFactory.createKeyedBundle(null, key, pcollection); + bundleFactory.createKeyedBundle(null, skey, pcollection); CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - assertThat(bundle.getKey(), equalTo(key)); + assertThat(bundle.getKey(), equalTo(skey)); } @Test - public void keyedWithNullKeyShouldCreateKeyedBundle() { - createKeyedBundle(null); + public void keyedWithNullKeyShouldCreateKeyedBundle() throws Exception { + createKeyedBundle(VoidCoder.of(), null); } @Test - public void keyedWithKeyShouldCreateKeyedBundle() { - createKeyedBundle(new Object()); + public void keyedWithKeyShouldCreateKeyedBundle() throws Exception { + createKeyedBundle(StringUtf8Coder.of(), "foo"); + createKeyedBundle(VarIntCoder.of(), 1234); + createKeyedBundle(ByteArrayCoder.of(), new byte[] {0, 2, 4, 99}); } private CommittedBundle @@ -151,7 +159,7 @@ public void withElementsShouldReturnIndependentBundle() { assertThat(withed.getElements(), containsInAnyOrder(firstReplacement, secondReplacement)); assertThat(committed.getElements(), containsInAnyOrder(firstValue, secondValue)); - assertThat(withed.getKey(), equalTo(committed.getKey())); + assertThat(withed.getKey(), Matchers.>equalTo(committed.getKey())); assertThat(withed.getPCollection(), equalTo(committed.getPCollection())); assertThat( withed.getSynchronizedProcessingOutputWatermark(), @@ -200,21 +208,21 @@ public void createBundleUnkeyedResultUnkeyed() { @Test public void createBundleKeyedResultPropagatesKey() { CommittedBundle> newBundle = - bundleFactory - .createBundle( - bundleFactory.createKeyedBundle(null, "foo", created).commit(Instant.now()), - downstream) - .commit(Instant.now()); - assertThat(newBundle.getKey(), Matchers.equalTo("foo")); + bundleFactory.createBundle( + bundleFactory.createKeyedBundle( + null, + StructuralKey.of("foo", StringUtf8Coder.of()), + created).commit(Instant.now()), + downstream).commit(Instant.now()); + assertThat(newBundle.getKey().getKey(), Matchers.equalTo("foo")); } @Test public void createKeyedBundleKeyed() { - CommittedBundle> keyedBundle = - bundleFactory - .createKeyedBundle( - bundleFactory.createRootBundle(created).commit(Instant.now()), "foo", downstream) - .commit(Instant.now()); - assertThat(keyedBundle.getKey(), Matchers.equalTo("foo")); + CommittedBundle> keyedBundle = bundleFactory.createKeyedBundle( + bundleFactory.createRootBundle(created).commit(Instant.now()), + StructuralKey.of("foo", StringUtf8Coder.of()), + downstream).commit(Instant.now()); + assertThat(keyedBundle.getKey().getKey(), Matchers.equalTo("foo")); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index c23f3955db..21b325df99 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -23,6 +23,8 @@ import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.io.CountingInput; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; @@ -156,16 +158,16 @@ public void writeToViewWriterThenReadReads() { @Test public void getExecutionContextSameStepSameKeyState() { InProcessExecutionContext fooContext = - context.getExecutionContext(created.getProducingTransformInternal(), "foo"); + context.getExecutionContext(created.getProducingTransformInternal(), + StructuralKey.of("foo", StringUtf8Coder.of())); StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); InProcessStepContext stepContext = fooContext.getOrCreateStepContext("s1", "s1", null); stepContext.stateInternals().state(StateNamespaces.global(), intBag).add(1); - context.handleResult( - InProcessBundleFactory.create() - .createKeyedBundle(null, "foo", created) + context.handleResult(InProcessBundleFactory.create() + .createKeyedBundle(null, StructuralKey.of("foo", StringUtf8Coder.of()), created) .commit(Instant.now()), ImmutableList.of(), StepTransformResult.withoutHold(created.getProducingTransformInternal()) @@ -173,7 +175,8 @@ public void getExecutionContextSameStepSameKeyState() { .build()); InProcessExecutionContext secondFooContext = - context.getExecutionContext(created.getProducingTransformInternal(), "foo"); + context.getExecutionContext(created.getProducingTransformInternal(), + StructuralKey.of("foo", StringUtf8Coder.of())); assertThat( secondFooContext .getOrCreateStepContext("s1", "s1", null) @@ -187,7 +190,8 @@ public void getExecutionContextSameStepSameKeyState() { @Test public void getExecutionContextDifferentKeysIndependentState() { InProcessExecutionContext fooContext = - context.getExecutionContext(created.getProducingTransformInternal(), "foo"); + context.getExecutionContext(created.getProducingTransformInternal(), + StructuralKey.of("foo", StringUtf8Coder.of())); StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); @@ -198,7 +202,8 @@ public void getExecutionContextDifferentKeysIndependentState() { .add(1); InProcessExecutionContext barContext = - context.getExecutionContext(created.getProducingTransformInternal(), "bar"); + context.getExecutionContext(created.getProducingTransformInternal(), + StructuralKey.of("bar", StringUtf8Coder.of())); assertThat(barContext, not(equalTo(fooContext))); assertThat( barContext @@ -211,7 +216,7 @@ public void getExecutionContextDifferentKeysIndependentState() { @Test public void getExecutionContextDifferentStepsIndependentState() { - String myKey = "foo"; + StructuralKey myKey = StructuralKey.of("foo", StringUtf8Coder.of()); InProcessExecutionContext fooContext = context.getExecutionContext(created.getProducingTransformInternal(), myKey); @@ -266,7 +271,7 @@ public void handleResultMergesCounters() { @Test public void handleResultStoresState() { - String myKey = "foo"; + StructuralKey myKey = StructuralKey.of("foo".getBytes(), ByteArrayCoder.of()); InProcessExecutionContext fooContext = context.getExecutionContext(downstream.getProducingTransformInternal(), myKey); @@ -356,7 +361,7 @@ public void extractFiredTimersExtractsTimers() { .build(); context.handleResult(null, ImmutableList.of(), holdResult); - String key = "foo"; + StructuralKey key = StructuralKey.of("foo".length(), VarIntCoder.of()); TimerData toFire = TimerData.of(StateNamespaces.global(), new Instant(100L), TimeDomain.EVENT_TIME); InProcessTransformResult timerResult = @@ -380,11 +385,12 @@ public void extractFiredTimersExtractsTimers() { // Should cause the downstream timer to fire context.handleResult(null, ImmutableList.of(), advanceResult); - Map, Map> fired = context.extractFiredTimers(); + Map, Map, FiredTimers>> fired = + context.extractFiredTimers(); assertThat( fired, Matchers.>hasKey(downstream.getProducingTransformInternal())); - Map downstreamFired = + Map, FiredTimers> downstreamFired = fired.get(downstream.getProducingTransformInternal()); assertThat(downstreamFired, Matchers.hasKey(key)); @@ -399,23 +405,27 @@ public void extractFiredTimersExtractsTimers() { @Test public void createBundleKeyedResultPropagatesKey() { + StructuralKey key = StructuralKey.of("foo", StringUtf8Coder.of()); CommittedBundle> newBundle = context .createBundle( - bundleFactory.createKeyedBundle(null, "foo", created).commit(Instant.now()), - downstream) - .commit(Instant.now()); - assertThat(newBundle.getKey(), Matchers.equalTo("foo")); + bundleFactory.createKeyedBundle( + null, key, + created).commit(Instant.now()), + downstream).commit(Instant.now()); + assertThat(newBundle.getKey(), Matchers.>equalTo(key)); } @Test public void createKeyedBundleKeyed() { + StructuralKey key = StructuralKey.of("foo", StringUtf8Coder.of()); CommittedBundle> keyedBundle = - context - .createKeyedBundle( - bundleFactory.createRootBundle(created).commit(Instant.now()), "foo", downstream) - .commit(Instant.now()); - assertThat(keyedBundle.getKey(), Matchers.equalTo("foo")); + context.createKeyedBundle( + bundleFactory.createRootBundle(created).commit(Instant.now()), + key, + downstream).commit(Instant.now()); + assertThat(keyedBundle.getKey(), + Matchers.>equalTo(key)); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java index 38cc62daef..c415a2b918 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java @@ -16,8 +16,11 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.is; +import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessPipelineResult; @@ -25,14 +28,21 @@ import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.MapElements; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.collect.ImmutableMap; import com.fasterxml.jackson.annotation.JsonValue; + import org.junit.Rule; import org.junit.Test; import org.junit.internal.matchers.ThrowableMessageMatcher; @@ -41,6 +51,7 @@ import org.junit.runners.JUnit4; import java.io.Serializable; +import java.util.Map; /** * Tests for basic {@link InProcessPipelineRunner} functionality. @@ -77,6 +88,54 @@ public String apply(KV input) { result.awaitCompletion(); } + @Test(timeout = 5000L) + public void byteArrayCountShouldSucceed() { + Pipeline p = getPipeline(); + + SerializableFunction getBytes = new SerializableFunction() { + @Override + public byte[] apply(Integer input) { + try { + return CoderUtils.encodeToByteArray(VarIntCoder.of(), input); + } catch (CoderException e) { + fail("Unexpected Coder Exception " + e); + throw new AssertionError("Unreachable"); + } + } + }; + TypeDescriptor td = new TypeDescriptor() { + }; + PCollection foos = + p.apply(Create.of(1, 1, 1, 2, 2, 3)).apply(MapElements.via(getBytes).withOutputType(td)); + PCollection msync = + p.apply(Create.of(1, -2, -8, -16)).apply(MapElements.via(getBytes).withOutputType(td)); + PCollection bytes = + PCollectionList.of(foos).and(msync).apply(Flatten.pCollections()); + PCollection> counts = bytes.apply(Count.perElement()); + PCollection> countsBackToString = + counts.apply(MapElements.via(new SimpleFunction, KV>() { + @Override + public KV apply(KV input) { + try { + return KV.of(CoderUtils.decodeFromByteArray(VarIntCoder.of(), input.getKey()), + input.getValue()); + } catch (CoderException e) { + fail("Unexpected Coder Exception " + e); + throw new AssertionError("Unreachable"); + } + } + })); + + Map expected = ImmutableMap.builder().put(1, 4L) + .put(2, 2L) + .put(3, 1L) + .put(-2, 1L) + .put(-8, 1L) + .put(-16, 1L) + .build(); + DataflowAssert.thatMap(countsBackToString).isEqualTo(expected); + } + @Test public void transformDisplayDataExceptionShouldFail() { DoFn brokenDoFn = new DoFn() { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java index 435a5ba9e3..eeaa4c12a5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; @@ -53,7 +54,7 @@ public void setup() { MockitoAnnotations.initMocks(this); clock = MockClock.fromInstant(new Instant(0)); - timerUpdateBuilder = TimerUpdate.builder(1234); + timerUpdateBuilder = TimerUpdate.builder(StructuralKey.of(1234, VarIntCoder.of())); internals = InProcessTimerInternals.create(clock, watermarks, timerUpdateBuilder); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java index 828b749794..5cf65c1f43 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java @@ -151,7 +151,7 @@ private ParDoInProcessEvaluator createEvaluator( when(stepContext.getTimerUpdate()).thenReturn(TimerUpdate.empty()); when( evaluationContext.getExecutionContext( - Mockito.any(AppliedPTransform.class), Mockito.any(Object.class))) + Mockito.any(AppliedPTransform.class), Mockito.any(StructuralKey.class))) .thenReturn(executionContext); when(evaluationContext.createCounterSet()).thenReturn(new CounterSet()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java index 50a7ed9180..8ba3045034 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java @@ -112,8 +112,8 @@ public void processElement(ProcessContext c) { InProcessExecutionContext executionContext = new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) - .thenReturn(executionContext); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), + inputBundle.getKey())).thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -197,8 +197,8 @@ public void processElement(ProcessContext c) { InProcessExecutionContext executionContext = new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) - .thenReturn(executionContext); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), + inputBundle.getKey())).thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -285,10 +285,12 @@ public void processElement(ProcessContext c) { when(evaluationContext.createBundle(inputBundle, elementOutput)) .thenReturn(elementOutputBundle); - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, "myKey", null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) - .thenReturn(executionContext); + InProcessExecutionContext executionContext = new InProcessExecutionContext(null, + StructuralKey.of("myKey", StringUtf8Coder.of()), + null, + null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), + inputBundle.getKey())).thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -395,10 +397,11 @@ public void processElement(ProcessContext c) { when(evaluationContext.createBundle(inputBundle, elementOutput)) .thenReturn(elementOutputBundle); - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, "myKey", null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) - .thenReturn(executionContext); + InProcessExecutionContext executionContext = new InProcessExecutionContext(null, + StructuralKey.of("myKey", StringUtf8Coder.of()), + null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), + inputBundle.getKey())).thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -417,7 +420,7 @@ public void processElement(ProcessContext c) { assertThat( result.getTimerUpdate(), equalTo( - TimerUpdate.builder("myKey") + TimerUpdate.builder(StructuralKey.of("myKey", StringUtf8Coder.of())) .setTimer(addedTimer) .setTimer(addedTimer) .setTimer(addedTimer) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java index 8cec0ba609..9aa41692b8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java @@ -88,8 +88,8 @@ public void processElement(ProcessContext c) { when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); InProcessExecutionContext executionContext = new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), null)) - .thenReturn(executionContext); + when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), + inputBundle.getKey())).thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -140,8 +140,8 @@ public void processElement(ProcessContext c) { when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); InProcessExecutionContext executionContext = new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), null)) - .thenReturn(executionContext); + when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), + inputBundle.getKey())).thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -202,9 +202,11 @@ public void processElement(ProcessContext c) { when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, "myKey", null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) + InProcessExecutionContext executionContext = new InProcessExecutionContext(null, + StructuralKey.of("myKey", StringUtf8Coder.of()), + null, null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), + inputBundle.getKey())) .thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -290,6 +292,7 @@ public void processElement(ProcessContext c) { }); PCollection> mainOutput = input.apply(pardo); + StructuralKey key = StructuralKey.of("myKey", StringUtf8Coder.of()); CommittedBundle inputBundle = bundleFactory.createRootBundle(input).commit(Instant.now()); @@ -299,9 +302,12 @@ public void processElement(ProcessContext c) { when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, "myKey", null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), null)) + InProcessExecutionContext executionContext = new InProcessExecutionContext(null, + key, + null, + null); + when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), + inputBundle.getKey())) .thenReturn(executionContext); CounterSet counters = new CounterSet(); when(evaluationContext.createCounterSet()).thenReturn(counters); @@ -314,10 +320,11 @@ public void processElement(ProcessContext c) { evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getTimerUpdate(), - equalTo( - TimerUpdate.builder("myKey").setTimer(addedTimer).deletedTimer(deletedTimer).build())); + assertThat(result.getTimerUpdate(), + equalTo(TimerUpdate.builder(StructuralKey.of("myKey", StringUtf8Coder.of())) + .setTimer(addedTimer) + .deletedTimer(deletedTimer) + .build())); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java new file mode 100644 index 0000000000..d0e995f6ff --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.theInstance; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link StructuralKey}. + */ +@RunWith(JUnit4.class) +public class StructuralKeyTest { + @Test + public void getKeyEqualToOldKey() { + assertThat(StructuralKey.of(1234, VarIntCoder.of()).getKey(), equalTo(1234)); + assertThat(StructuralKey.of("foobar", StringUtf8Coder.of()).getKey(), equalTo("foobar")); + assertArrayEquals(StructuralKey.of(new byte[] {2, 9, -22}, ByteArrayCoder.of()).getKey(), + new byte[] {2, 9, -22}); + } + + @Test + public void getKeyNotSameInstance() { + byte[] original = new byte[] {1, 4, 9, 127, -22}; + StructuralKey key = StructuralKey.of(original, ByteArrayCoder.of()); + + assertThat(key.getKey(), not(theInstance(original))); + } + + @Test + public void objectEqualsTrueKeyEquals() { + StructuralKey original = StructuralKey.of(1234, VarIntCoder.of()); + assertThat(StructuralKey.of(1234, VarIntCoder.of()), equalTo(original)); + } + + @Test + public void objectsNotEqualEncodingsEqualEquals() { + byte[] original = new byte[] {1, 4, 9, 127, -22}; + StructuralKey key = StructuralKey.of(original, ByteArrayCoder.of()); + + StructuralKey otherKey = + StructuralKey.of(new byte[] {1, 4, 9, 127, -22}, ByteArrayCoder.of()); + assertThat(key, equalTo(otherKey)); + } + + @Test + public void notEqualEncodingsEqual() { + byte[] original = new byte[] {1, 4, 9, 127, -22}; + StructuralKey key = StructuralKey.of(original, ByteArrayCoder.of()); + + StructuralKey otherKey = + StructuralKey.of(new byte[] {9, -128, 22}, ByteArrayCoder.of()); + assertThat(key, not(equalTo(otherKey))); + } +} From 5fc3a642508636eec60d1dd29c78b0fb91b2f1ca Mon Sep 17 00:00:00 2001 From: dhalperi Date: Thu, 2 Jun 2016 21:31:23 -0700 Subject: [PATCH 438/751] Version management ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=123937555 --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index bfb0d338c3..f9b2ce86dd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -220,9 +220,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.5.1"; + = "dataflow.gcr.io/v1beta3/java-batch:1.6.0"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.5.1"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.6.0"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 25275f6339507ec53d07750e4d7ac0bb975a97f1 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 3 Jun 2016 11:02:14 -0700 Subject: [PATCH 439/751] Remove byteArrayCount timeout --- .../sdk/runners/inprocess/InProcessPipelineRunnerTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java index c415a2b918..5da61ba217 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java @@ -88,7 +88,6 @@ public String apply(KV input) { result.awaitCompletion(); } - @Test(timeout = 5000L) public void byteArrayCountShouldSucceed() { Pipeline p = getPipeline(); From dc42fce7458f15dd26d2d5fe487532914a6066db Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 3 Jun 2016 17:02:24 -0700 Subject: [PATCH 440/751] InProcessRunner: add Javadoc and cleanup what gets generated * Reduce visibility of InProcessRunner implementation * Generate Javadoc for the InProcessRunner --- sdk/pom.xml | 2 +- .../cloud/dataflow/sdk/runners/inprocess/BundleFactory.java | 2 +- .../sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java | 2 +- .../sdk/runners/inprocess/InMemoryWatermarkManager.java | 2 +- .../sdk/runners/inprocess/InProcessBundleOutputManager.java | 2 +- .../dataflow/sdk/runners/inprocess/InProcessTimerInternals.java | 2 +- .../sdk/runners/inprocess/InProcessTransformResult.java | 2 +- .../dataflow/sdk/runners/inprocess/StepTransformResult.java | 2 +- .../dataflow/sdk/runners/inprocess/TransformEvaluator.java | 2 +- .../sdk/runners/inprocess/TransformEvaluatorFactory.java | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index f7b836a156..e412db1f7f 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -261,7 +261,7 @@ ../javadoc/overview.html com.google.cloud.dataflow.sdk - -exclude com.google.cloud.dataflow.sdk.runners.worker:com.google.cloud.dataflow.sdk.runners.dataflow:com.google.cloud.dataflow.sdk.util:com.google.cloud.dataflow.sdk.runners.inprocess ${dataflow.javadoc_opts} + -exclude com.google.cloud.dataflow.sdk.runners.worker:com.google.cloud.dataflow.sdk.runners.dataflow:com.google.cloud.dataflow.sdk.util ${dataflow.javadoc_opts} false true ]]> diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java index f2852957c5..fa62fb3844 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java @@ -24,7 +24,7 @@ /** * A factory that creates {@link UncommittedBundle UncommittedBundles}. */ -public interface BundleFactory { +interface BundleFactory { /** * Create an {@link UncommittedBundle} from an empty input. Elements added to the bundle belong to * the {@code output} {@link PCollection}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java index 65a342b64e..42704b162b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java @@ -39,7 +39,7 @@ * {@link Pipeline}. This is used to schedule consuming {@link PTransform PTransforms} to consume * input after the upstream transform has produced and committed output. */ -public class ConsumerTrackingPipelineVisitor implements PipelineVisitor { +class ConsumerTrackingPipelineVisitor implements PipelineVisitor { private Map>> valueToConsumers = new HashMap<>(); private Collection> rootTransforms = new ArrayList<>(); private Collection> views = new ArrayList<>(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 0f804491ef..a35544af28 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -122,7 +122,7 @@ * Watermark_PCollection = Watermark_Out_ProducingPTransform * */ -public class InMemoryWatermarkManager { +class InMemoryWatermarkManager { /** * The watermark of some {@link Pipeline} element, usually a {@link PTransform} or a * {@link PCollection}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java index 406e2d4638..bd8f3f72b4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java @@ -27,7 +27,7 @@ * An {@link OutputManager} that outputs to {@link CommittedBundle Bundles} used by the * {@link InProcessPipelineRunner}. */ -public class InProcessBundleOutputManager implements OutputManager { +class InProcessBundleOutputManager implements OutputManager { private final Map, UncommittedBundle> bundles; public static InProcessBundleOutputManager create( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java index 1d075c54c2..72f8b4621b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java @@ -27,7 +27,7 @@ /** * An implementation of {@link TimerInternals} where all relevant data exists in memory. */ -public class InProcessTimerInternals implements TimerInternals { +class InProcessTimerInternals implements TimerInternals { private final Clock processingTimeClock; private final TransformWatermarks watermarks; private final TimerUpdateBuilder timerUpdateBuilder; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java index add53387b7..2180c00483 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -31,7 +31,7 @@ /** * The result of evaluating an {@link AppliedPTransform} with a {@link TransformEvaluator}. */ -public interface InProcessTransformResult { +interface InProcessTransformResult { /** * Returns the {@link AppliedPTransform} that produced this result. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java index b520c0666b..dba6923c00 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java @@ -36,7 +36,7 @@ /** * An immutable {@link InProcessTransformResult}. */ -public class StepTransformResult implements InProcessTransformResult { +class StepTransformResult implements InProcessTransformResult { private final AppliedPTransform transform; private final Iterable> bundles; private final Iterable> unprocessedElements; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java index 270557d55c..be54ec20ee 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java @@ -24,7 +24,7 @@ * * @param the type of elements that will be passed to {@link #processElement} */ -public interface TransformEvaluator { +interface TransformEvaluator { /** * Process an element in the input {@link CommittedBundle}. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java index b0eb19e57e..a91337f28e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java @@ -26,7 +26,7 @@ * A factory for creating instances of {@link TransformEvaluator} for the application of a * {@link PTransform}. */ -public interface TransformEvaluatorFactory { +interface TransformEvaluatorFactory { /** * Create a new {@link TransformEvaluator} for the application of the {@link PTransform}. * From a310e8201d8829bc3caff39d9a937d572d4d2cf8 Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Mon, 6 Jun 2016 13:07:35 -0700 Subject: [PATCH 441/751] Fix validation in PubsubIO --- .../cloud/dataflow/sdk/util/PubsubClient.java | 54 +++++++++++-------- 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java index 73b06d7b5a..2b24dd9891 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java @@ -120,20 +120,27 @@ protected static long extractTimestamp( * Path representing a cloud project id. */ public static class ProjectPath implements Serializable { - private final String path; + private final String projectId; + /** + * Creates a {@link ProjectPath} from a {@link String} representation, which + * must be of the form {@code "projects/" + projectId}. + */ ProjectPath(String path) { - this.path = path; + String[] splits = path.split("/"); + checkArgument( + splits.length == 2 && splits[0].equals("projects"), + "Malformed project path \"%s\": must be of the form \"projects/\" + ", + path); + this.projectId = splits[1]; } public String getPath() { - return path; + return String.format("projects/%s", projectId); } public String getId() { - String[] splits = path.split("/"); - checkState(splits.length == 1, "Malformed project path %s", path); - return splits[1]; + return projectId; } @Override @@ -147,18 +154,17 @@ public boolean equals(Object o) { ProjectPath that = (ProjectPath) o; - return path.equals(that.path); - + return projectId.equals(that.projectId); } @Override public int hashCode() { - return path.hashCode(); + return projectId.hashCode(); } @Override public String toString() { - return path; + return getPath(); } } @@ -174,26 +180,29 @@ public static ProjectPath projectPathFromId(String projectId) { * Path representing a Pubsub subscription. */ public static class SubscriptionPath implements Serializable { - private final String path; + private final String projectId; + private final String subscriptionName; SubscriptionPath(String path) { - this.path = path; + String[] splits = path.split("/"); + checkState( + splits.length == 4 && splits[0].equals("projects") && splits[2].equals("subscriptions"), + "Malformed subscription path %s: " + + "must be of the form \"projects/\" + + \"subscriptions\"", path); + this.projectId = splits[1]; + this.subscriptionName = splits[3]; } public String getPath() { - return path; + return String.format("projects/%s/subscriptions/%s", projectId, subscriptionName); } public String getName() { - String[] splits = path.split("/"); - checkState(splits.length == 4, "Malformed subscription path %s", path); - return splits[3]; + return subscriptionName; } public String getV1Beta1Path() { - String[] splits = path.split("/"); - checkState(splits.length == 4, "Malformed subscription path %s", path); - return String.format("/subscriptions/%s/%s", splits[1], splits[3]); + return String.format("/subscriptions/%s/%s", projectId, subscriptionName); } @Override @@ -205,17 +214,18 @@ public boolean equals(Object o) { return false; } SubscriptionPath that = (SubscriptionPath) o; - return path.equals(that.path); + return this.subscriptionName.equals(that.subscriptionName) + && this.projectId.equals(that.projectId); } @Override public int hashCode() { - return path.hashCode(); + return Objects.hashCode(projectId, subscriptionName); } @Override public String toString() { - return path; + return getPath(); } } From cafc48146a1e1f4d1403106735138481a529560a Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 6 Jun 2016 17:47:46 -0700 Subject: [PATCH 442/751] DataflowPipelineRunner: increment API version Preparation for 1.6.0 release ----Release Notes---- ----Internal Notes---- --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f9b2ce86dd..ec75cd5377 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -215,7 +215,7 @@ public class DataflowPipelineRunner extends PipelineRunner private DataflowPipelineRunnerHooks hooks; // Environment version information. - private static final String ENVIRONMENT_MAJOR_VERSION = "4"; + private static final String ENVIRONMENT_MAJOR_VERSION = "5"; // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. From e0e56e0911e18ad08c5f9ed245c76849503ab7c7 Mon Sep 17 00:00:00 2001 From: elibixby Date: Tue, 7 Jun 2016 16:58:56 -0700 Subject: [PATCH 443/751] Unbounded Firebase Source, and associated DoFns (#69) * Initial commit First working commit prepare to add licenses Cleared Checkstyle Moved all logging to testers Added failfast behavior option to FirebaseSource Expand error message for erased type variables in CoderRegistry ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104912339 Do not overwrite TypeDescriptor of PCollection in PCollectionTuple The previous behavior was added based on an assumption that a TupleTag indexing into a PCollectionTuple would probably have better type information than was already present on a PCollection. This assumption is unwarranted if the PCollection received a particular TypeDescriptor prior to being added to a PCollectionTuple. In particular, MapElements sets a specific type descriptor which is overwritten when the PCollection is put into a PCollectionTuple during evaluation by the DirectPipelineRunner. The assumption is also not needed -- the affected use case is that of a multi-output ParDo, where the outputs are primitives, and these follow a separate code path. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104930665 FlatMapElements: javadoc fixes - two broken tags missing } - one broken link to refactored java8 function ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104933857 Use MapElements in WordCount example ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104998220 Fix comment regarding condition for AfterAll finishing ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105007693 Test simple Combine with Java 8 lambdas and method references Combine, as written, accepts the functional interface SerializableFunction. This change adds Java 8 tests to verify that this invocation operates correctly when provided an anonymous lambda function or method reference. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105008164 BigQueryTableRowIterator: make getF/getV work correctly BigQuery's recommended API is that users should use the getF and getV commands to read data from TableRows, but we have been breaking that API and supporting a Map interface instead. Switch to make the code support both interfaces, with the eventual goal of deprecating the Map version. Includes a little bit of cleanup to internal function names and arguments. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105022905 Hide the CloudDebuggerOptions ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105068420 Avoid deserializing and calling start/finishBundle on empty bundles Often in streaming mode small bundles arrive and get buffered by the GroupAlsoByWindowsFn. In this case it's wasteful to deserialize and initialize all subsequent DoFns. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105073190 Write: move from transforms to io package And leave behind a deprecated subclass for backwards compatibility. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105076144 Fixes a shutdown race in ReadOperation Prevents ReadOperation from calling requestDynamicSplit() on a closed reader, by closing the reader only after the operation is marked finished. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105078926 Enable dynamic work rebalancing when reading from intermediate data ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105083061 Add tests using Java 8 method references Filter, FlatMapElements, and MapElements should work with first-class functions however they are created. Previously, they were tested with lambda. Now they are also tested with method references. (They do work.) ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105084851 Add DataflowProfilingOptions ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105085000 Merge before processing elements This means that when a trigger fires we don't need to merge, which greatly simplifies the implementation. It also means that the number of intermediate (partially merged) windows is significantly reduced (dependent on the number of calls to processElements rather than the number of individual elements). Persist windows when running tests that involve merging. This is more representative of how actual bundles are processed by GroupAlsoByWindows. Remove the delayed commit of the finished set. With pre-merging this is no longer necessary. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105085413 Add a pipeline option to GcsOptions for user-specified buffer size The default settings for opening IO Channels to Google Cloud Storage use 64 MB buffers per connection, which can lead to out-of-memory issues when running a pipeline with several GCS connections. See GitHub issue #62. Add a GcsOptions pipeline option so that users can override these sizes as needed. Also clean up the tests. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105087013 Fix typo in error message Observed in https://github.com/GoogleCloudPlatform/DataflowJavaSDK/issues/65 (scroll right on the text box). ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105206603 WorkerDiskType option: document and add reference URL The format of the string expected by this option is set by GCE and is non-obvious. Provide an example and a link for more information. Fixes #68 ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105223902 Stop sampling after StateSampler.close() Implemented by serializing all the scheduled task runs and introducing a cancellation flag. Fixes a race condition where a scheduled sampling could still happen after cancellatino. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105226569 Add size-based file rotation to java logger The logger will now automatically write logs to a new file when the size exceeds a configurable limit (default 1 GB). This mechanism - which is similar to glog - is intended to work in combination with a purger that removes old files. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105228034 Fix a BigQuery output issue in DirectPipelineRunner getOrCreateTable() was called for each output element, and it introduces unnecessary BigQuery APIs call and duplicated messages. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105328508 Miscellaneous cleanup ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105338462 Refactored logging to use deterministic events Fixed DoFn Pipelining Finished Pipeline Fix Moved to two Firebases for test Cleaning a firebase to allow for duplicate events turned out to be too difficult for a number of test cases. It's fine to use two different demo Firebases for test event generation though, as events should be Firebase repo agnostic (Pipeline's can use tags and tranform names to label events with their originating pipeline in the case they want to use multiple Firebases) Updated tests Added a test for Child Changed events. Updated ChildAddedTest to depend on DoFirebasePush and fixed bug this revealed in DoFirebasePush All tests to green * Removed FirebaseErrors after discussion with puf@ firebase errors should not be passed down the pipeline * Tests now share a single demo firebase rather than using disposable firebases. Cleanup has been fixed with the exception of a detected error in DataflowJavaSDK * Log elements to PTranform. Changes from PR review * Added readme * Update README.md Typo * Made tests green again, style + polish fixes * Add Firebase contrib module ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104912339 Do not overwrite TypeDescriptor of PCollection in PCollectionTuple The previous behavior was added based on an assumption that a TupleTag indexing into a PCollectionTuple would probably have better type information than was already present on a PCollection. This assumption is unwarranted if the PCollection received a particular TypeDescriptor prior to being added to a PCollectionTuple. In particular, MapElements sets a specific type descriptor which is overwritten when the PCollection is put into a PCollectionTuple during evaluation by the DirectPipelineRunner. The assumption is also not needed -- the affected use case is that of a multi-output ParDo, where the outputs are primitives, and these follow a separate code path. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104930665 FlatMapElements: javadoc fixes - two broken tags missing } - one broken link to refactored java8 function ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104933857 Use MapElements in WordCount example ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=104998220 Fix comment regarding condition for AfterAll finishing ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105007693 Test simple Combine with Java 8 lambdas and method references Combine, as written, accepts the functional interface SerializableFunction. This change adds Java 8 tests to verify that this invocation operates correctly when provided an anonymous lambda function or method reference. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105008164 BigQueryTableRowIterator: make getF/getV work correctly BigQuery's recommended API is that users should use the getF and getV commands to read data from TableRows, but we have been breaking that API and supporting a Map interface instead. Switch to make the code support both interfaces, with the eventual goal of deprecating the Map version. Includes a little bit of cleanup to internal function names and arguments. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105022905 Hide the CloudDebuggerOptions ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105068420 Avoid deserializing and calling start/finishBundle on empty bundles Often in streaming mode small bundles arrive and get buffered by the GroupAlsoByWindowsFn. In this case it's wasteful to deserialize and initialize all subsequent DoFns. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105073190 Write: move from transforms to io package And leave behind a deprecated subclass for backwards compatibility. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105076144 Fixes a shutdown race in ReadOperation Prevents ReadOperation from calling requestDynamicSplit() on a closed reader, by closing the reader only after the operation is marked finished. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105078926 Enable dynamic work rebalancing when reading from intermediate data ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105083061 Add tests using Java 8 method references Filter, FlatMapElements, and MapElements should work with first-class functions however they are created. Previously, they were tested with lambda. Now they are also tested with method references. (They do work.) ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105084851 Add DataflowProfilingOptions ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105085000 Merge before processing elements This means that when a trigger fires we don't need to merge, which greatly simplifies the implementation. It also means that the number of intermediate (partially merged) windows is significantly reduced (dependent on the number of calls to processElements rather than the number of individual elements). Persist windows when running tests that involve merging. This is more representative of how actual bundles are processed by GroupAlsoByWindows. Remove the delayed commit of the finished set. With pre-merging this is no longer necessary. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105085413 Add a pipeline option to GcsOptions for user-specified buffer size The default settings for opening IO Channels to Google Cloud Storage use 64 MB buffers per connection, which can lead to out-of-memory issues when running a pipeline with several GCS connections. See GitHub issue #62. Add a GcsOptions pipeline option so that users can override these sizes as needed. Also clean up the tests. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105087013 Fix typo in error message Observed in https://github.com/GoogleCloudPlatform/DataflowJavaSDK/issues/65 (scroll right on the text box). ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105206603 WorkerDiskType option: document and add reference URL The format of the string expected by this option is set by GCE and is non-obvious. Provide an example and a link for more information. Fixes #68 ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105223902 Stop sampling after StateSampler.close() Implemented by serializing all the scheduled task runs and introducing a cancellation flag. Fixes a race condition where a scheduled sampling could still happen after cancellatino. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105226569 Add size-based file rotation to java logger The logger will now automatically write logs to a new file when the size exceeds a configurable limit (default 1 GB). This mechanism - which is similar to glog - is intended to work in combination with a purger that removes old files. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105228034 Fix a BigQuery output issue in DirectPipelineRunner getOrCreateTable() was called for each output element, and it introduces unnecessary BigQuery APIs call and duplicated messages. ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105328508 Miscellaneous cleanup ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=105338462 Refactored logging to use deterministic events Fixed DoFn Pipelining Finished Pipeline Fix Moved to two Firebases for test Cleaning a firebase to allow for duplicate events turned out to be too difficult for a number of test cases. It's fine to use two different demo Firebases for test event generation though, as events should be Firebase repo agnostic (Pipeline's can use tags and tranform names to label events with their originating pipeline in the case they want to use multiple Firebases) Updated tests Added a test for Child Changed events. Updated ChildAddedTest to depend on DoFirebasePush and fixed bug this revealed in DoFirebasePush All tests to green * Removed FirebaseErrors after discussion with puf@ firebase errors should not be passed down the pipeline * Tests now share a single demo firebase rather than using disposable firebases. Cleanup has been fixed with the exception of a detected error in DataflowJavaSDK * firebase pom: fix checkstyle config * firebase: fix a few import-related checkstyle issues * firebase: promote slf4j dependency to compile-time It's required by LogElements transform * Fixed tests and style * Package and style updates * More Package and style updates --- contrib/firebaseio/AUTHORS.md | 1 + contrib/firebaseio/README.md | 15 + contrib/firebaseio/pom.xml | 115 +++++ .../firebase/contrib/JacksonCoder.java | 152 +++++++ .../contrib/firebase/contrib/LogElements.java | 76 ++++ .../contrib/firebase/events/ChildAdded.java | 45 ++ .../contrib/firebase/events/ChildChanged.java | 43 ++ .../contrib/firebase/events/ChildMoved.java | 40 ++ .../contrib/firebase/events/ChildRemoved.java | 41 ++ .../firebase/events/FirebaseChildEvent.java | 53 +++ .../firebase/events/FirebaseEvent.java | 75 ++++ .../contrib/firebase/events/ValueChanged.java | 44 ++ .../contrib/firebase/io/DoFirebasePush.java | 52 +++ .../contrib/firebase/io/DoFirebaseSet.java | 43 ++ .../contrib/firebase/io/DoFirebaseUpdate.java | 45 ++ .../contrib/firebase/io/FirebaseDoFn.java | 96 +++++ .../contrib/firebase/io/FirebaseSource.java | 406 ++++++++++++++++++ .../firebase/utils/FirebaseAuthenticator.java | 34 ++ .../firebase/utils/FirebaseCheckpoint.java | 125 ++++++ .../utils/FirebaseCheckpointCoder.java | 104 +++++ .../utils/FirebaseEmptyAuthenticator.java | 33 ++ .../firebase/utils/FirebaseEventCoder.java | 105 +++++ .../utils/FirebasePasswordAuthenticator.java | 59 +++ .../contrib/firebase/utils/Record.java | 48 +++ .../firebase/io/BaseFirebaseSourceTest.java | 181 ++++++++ .../contrib/firebase/io/ChildAddedTest.java | 58 +++ .../contrib/firebase/io/ChildChangedTest.java | 43 ++ .../contrib/firebase/io/ChildMovedTest.java | 70 +++ .../contrib/firebase/io/ChildRemovedTest.java | 60 +++ .../io/DoFirebaseSetWithPriority.java | 51 +++ .../firebase/io/FirebaseChildTest.java | 86 ++++ .../firebase/io/FirebaseValueTest.java | 103 +++++ .../src/test/resources/testdata.json | 302 +++++++++++++ 33 files changed, 2804 insertions(+) create mode 100644 contrib/firebaseio/AUTHORS.md create mode 100644 contrib/firebaseio/README.md create mode 100644 contrib/firebaseio/pom.xml create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java create mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java create mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java create mode 100644 contrib/firebaseio/src/test/resources/testdata.json diff --git a/contrib/firebaseio/AUTHORS.md b/contrib/firebaseio/AUTHORS.md new file mode 100644 index 0000000000..ac5722ea5b --- /dev/null +++ b/contrib/firebaseio/AUTHORS.md @@ -0,0 +1 @@ +elibixby [@ github, google, gmail ] diff --git a/contrib/firebaseio/README.md b/contrib/firebaseio/README.md new file mode 100644 index 0000000000..776b3d54fc --- /dev/null +++ b/contrib/firebaseio/README.md @@ -0,0 +1,15 @@ +## FirebaseIO for Dataflow + +This library includes two components for communicating with [Firebase](https://www.firebase.com/) from Dataflow: + +* `FirebaseSource` an `UnboundedSource` which can watch a Firebase ref for events and attempts (but does not guarantee) to deliver those events in order to the Dataflow pipeline. The source will unmarshal `DataSnapshot`s generated by these events into the paramaterized type specified by your `FirebaseSource`, which can be any object serializable by Jackson. + +* Various `FirebaseDoFn` which can be used to write data to a firebase: + * `DoFirebasePush` will attach unique and time-ordered strings as keys to objects recieved from the pipeline. + * `DoFirebaseSet` will overriding data at the key's location with the specified `Object` + * `DoFirebaseUpdate` will update the tree at the ref with the given `Map` + + +These utilities also use various `FirebaseEvents` to wrap your unmarshalled data in a Jackson Serializable POJO, which retains event type information. So for example you could filter a pipeline on `ChildAdded` events, where your original `DataSnapshot` was unmarshalled into a Jackson Serializable POJO of type `T`. + +The library uses the firebase JVM client library and as such takes advantage of Web sockets for data transfer. However this means that writing to Firebase will use one websocket per shard, so if you plan to fan out your writes, make sure to limit the parallelism with `PTransform#withMaxParallelism` to avoid capping out your available connections. diff --git a/contrib/firebaseio/pom.xml b/contrib/firebaseio/pom.xml new file mode 100644 index 0000000000..3d27ca4b0a --- /dev/null +++ b/contrib/firebaseio/pom.xml @@ -0,0 +1,115 @@ + + + + 4.0.0 + + com.google.cloud.dataflow + google-cloud-dataflow-java-contrib-firebaseio + FirebaseIO + Unbounded Source, and DoFns to read and write to Firebase from Dataflow + 0.0.2-SNAPSHOT + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + UTF-8 + [1.2.0, 2.0.0) + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.12 + + + com.puppycrawl.tools + checkstyle + 6.6 + + + + ../../checkstyle.xml + true + true + true + + + + validate + + check + + + + + + + + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-all + ${google-cloud-dataflow-version} + + + + com.google.guava + guava + 18.0 + + + + com.firebase + firebase-client-jvm + 2.4.0 + + + + org.slf4j + slf4j-api + 1.7.15 + + + + org.slf4j + slf4j-simple + 1.7.15 + + + + + org.hamcrest + hamcrest-all + 1.3 + test + + + + junit + junit + 4.12 + test + + + + diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java new file mode 100644 index 0000000000..61a862922d --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java @@ -0,0 +1,152 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.contrib; + +import static com.google.cloud.dataflow.sdk.util.Structs.addString; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.util.Collections; +import java.util.List; + +/** + * Encodes objects using {@link ObjectReader} and {@link ObjectWriter}. + */ +public class JacksonCoder extends StandardCoder { + + private static final long serialVersionUID = -754345287170755870L; + + private static final ObjectMapper MAPPER = new ObjectMapper() + .enableDefaultTyping(DefaultTyping.NON_FINAL) + .enable(DeserializationFeature.WRAP_EXCEPTIONS) + .enable(SerializationFeature.WRAP_EXCEPTIONS) + .disable(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS) + .enable(SerializationFeature.WRITE_NULL_MAP_VALUES) + .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false) + .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); + + // Threadsafe as per http://wiki.fasterxml.com/JacksonBestPracticesPerformance + private final ObjectWriter writer; + private final ObjectReader reader; + + protected final Class type; + + public static JacksonCoder of(TypeDescriptor type) { + @SuppressWarnings("unchecked") + Class clazz = (Class) type.getRawType(); + return of(clazz); + } + + /** + * JacksonCoder will encode any type that can be serialized/deserialized by Jackson. + * This can be achieved by using either Jackson annotations (as seen in this library), or + * implementing @see + * custom serializers. + * @param clazz Type to encode + * @return A JacksonCoder parameterized with type {@code clazz} + */ + public static JacksonCoder of(Class clazz){ + return new JacksonCoder<>(clazz); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @JsonCreator + public static JacksonCoder of( + @JsonProperty("type") String classType) throws ClassNotFoundException { + return new JacksonCoder(Class.forName(classType)); + } + + protected JacksonCoder(Class clazz){ + this.type = clazz; + writer = MAPPER.writer(); + reader = MAPPER.readerFor(type); + } + + @Override + public void encode(T value, OutputStream outStream, Context context) + throws IOException { + writer.writeValue(outStream, value); + } + + @Override + public T decode(InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) + throws IOException { + return reader.readValue(inStream); + } + + @Override + public List> getCoderArguments() { + return Collections.emptyList(); + } + + @Override + public void verifyDeterministic() throws NonDeterministicException{ + throw new Coder.NonDeterministicException(this, "JSON is not a deterministic encoding"); + } + + public Class getType(){ + return this.type; + } + + protected Object writeReplace() { + // When serialized by Java, instances of AvroCoder should be replaced by + // a SerializedJacksonCoderProxy. + return new SerializedJacksonCoderProxy<>(type); + } + + @Override + public CloudObject asCloudObject() { + CloudObject result = super.asCloudObject(); + addString(result, "type", type.getName()); + return result; + } + + /** + * Proxy to use in place of serializing the JacksonCoder. This allows the fields + * to remain final. + */ + protected static class SerializedJacksonCoderProxy implements Serializable { + protected final Class type; + + public SerializedJacksonCoderProxy(Class type) { + this.type = type; + } + + private Object readResolve() { + // When deserialized, instances of this object should be replaced by + // constructing an JacksonCoder. + return new JacksonCoder<>(type); + } + } +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java new file mode 100644 index 0000000000..4afe30afbc --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java @@ -0,0 +1,76 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.contrib; + +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; + +import org.slf4j.event.Level; +import org.slf4j.event.LoggingEvent; +import org.slf4j.event.SubstituteLoggingEvent; +import org.slf4j.impl.SimpleLogger; +import org.slf4j.impl.SimpleLoggerFactory; + +/** + * Logs a {@link PCollection} to a logger for the specified {@link Class}. + */ +public class LogElements extends PTransform, PDone> { + + private final Level level; + private final String className; + + public LogElements(Class clazz, Level level){ + this.className = clazz.getName(); + this.level = level; + } + + @Override + public PDone apply(PCollection input){ + input.apply(ParDo.of(new LoggingDoFn(this.className, this.level))); + return PDone.in(input.getPipeline()); + } + + /** + * Given a PCollection of {@link LoggingEvent}s, log them to a simple logger (uses System.err). + */ + public static class LoggingDoFn extends DoFn{ + + private final String className; + private final Level level; + private transient SimpleLogger logger; + + public LoggingDoFn(String className, Level level){ + this.className = className; + this.level = level; + } + + @Override + public void startBundle(Context c) throws Exception { + logger = (SimpleLogger) new SimpleLoggerFactory().getLogger(this.className); + } + + @Override + public void processElement(DoFn.ProcessContext c) throws Exception { + SubstituteLoggingEvent event = new SubstituteLoggingEvent(); + event.setMessage(c.element().toString()); + event.setLevel(this.level); + logger.log(event); + } + } +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java new file mode 100644 index 0000000000..a880126108 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; + +import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.firebase.client.ChildEventListener; +import com.firebase.client.DataSnapshot; + + +/** + * Created by {@link ChildEventListener#onChildRemoved } triggered in {@link FirebaseSource}. + * @param type that {@link DataSnapshot} is parsed as. + */ +public class ChildAdded extends FirebaseChildEvent { + + @JsonCreator + public ChildAdded( + @JsonProperty("key") String key, + @JsonProperty("data") T data, + @JsonProperty("previousChildName") String previousChildName) { + super(key, data, previousChildName); + } + + public ChildAdded(DataSnapshot snapshot, String previousChildName){ + super(snapshot, previousChildName); + } + + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java new file mode 100644 index 0000000000..c152639bd0 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; + +import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.firebase.client.ChildEventListener; +import com.firebase.client.DataSnapshot; + +/** + * Created by {@link ChildEventListener#onChildRemoved } triggered in {@link FirebaseSource}. + * @param + */ +public class ChildChanged extends FirebaseChildEvent { + + @JsonCreator + public ChildChanged( + @JsonProperty("key") String key, + @JsonProperty("data") T data, + @JsonProperty("previousChildName") String previousChildName) { + super(key, data, previousChildName); + } + + public ChildChanged(DataSnapshot snapshot, String previousChildName){ + super(snapshot, previousChildName); + } + + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java new file mode 100644 index 0000000000..c0193f76fa --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.firebase.client.DataSnapshot; + +/** + * TODO: Insert description here. (generated by elibixby) + * @param type that {@link DataSnapshot} is parsed as. + */ +public class ChildMoved extends FirebaseChildEvent { + + @JsonCreator + public ChildMoved( + @JsonProperty("key") String key, + @JsonProperty("data") T data, + @JsonProperty("previousChildName") String previousChildName) { + super(key, data, previousChildName); + } + + public ChildMoved(DataSnapshot snapshot, String previousChildName){ + super(snapshot, previousChildName); + } + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java new file mode 100644 index 0000000000..97e1e38204 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; + +import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.firebase.client.ChildEventListener; +import com.firebase.client.DataSnapshot; + +/** + * Created by {@link ChildEventListener#onChildRemoved } triggered in {@link FirebaseSource}. + * @param type that {@link DataSnapshot} is parsed as. + */ +public class ChildRemoved extends FirebaseEvent { + + @JsonCreator + public ChildRemoved( + @JsonProperty("key") String key, + @JsonProperty("data") T data) { + super(key, data); + } + + public ChildRemoved(DataSnapshot snapshot){ + super(snapshot); + } + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java new file mode 100644 index 0000000000..e985478553 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; + +import com.firebase.client.DataSnapshot; + +import java.util.Objects; + +/** + * TODO: Super class for events which come with a {@code previousChildName}. + * @param type that {@link DataSnapshot} is parsed as. + */ +public class FirebaseChildEvent extends FirebaseEvent { + + public final String previousChildName; + + protected FirebaseChildEvent(String key, T data, String previousChildName) { + super(key, data); + this.previousChildName = previousChildName; + } + + protected FirebaseChildEvent(DataSnapshot snapshot, String previousChildName) { + super(snapshot); + this.previousChildName = previousChildName; + } + + @Override + public int hashCode(){ + return Objects.hash(previousChildName, super.hashCode()); + } + + @Override + public boolean equals(Object e){ + if (this.getClass().isInstance(e)){ + FirebaseChildEvent other = (FirebaseChildEvent) e; + return Objects.equals(this.previousChildName, other.previousChildName) && super.equals(e); + } + return false; + } +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java new file mode 100644 index 0000000000..276252cd2d --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; +import com.fasterxml.jackson.databind.SerializationFeature; + +import com.firebase.client.DataSnapshot; +import com.firebase.client.GenericTypeIndicator; + +import java.util.Objects; + +/** + * Supertype for all {@link FirebaseEvent}s. + * @param type that {@link DataSnapshot} is parsed as. +**/ +public class FirebaseEvent{ + + private static ObjectMapper mapper = new ObjectMapper() + .enableDefaultTyping(DefaultTyping.NON_FINAL) + .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + + public final String key; + public final T data; + + protected FirebaseEvent(String key, T data){ + this.key = key; + this.data = data; + } + + protected FirebaseEvent(DataSnapshot snapshot){ + this(snapshot.getKey(), snapshot.getValue(new GenericTypeIndicator(){})); + } + + @Override + public int hashCode(){ + return Objects.hash(key, data); + } + + /** + * Does a deep equality check by delegating to {@code T.equals()}. + */ + @Override + public boolean equals(Object e){ + if (this.getClass().isInstance(e)){ + FirebaseEvent other = (FirebaseEvent) e; + return Objects.equals(this.key, other.key) && Objects.equals(this.data, other.data); + } + return false; + } + + @Override + public String toString(){ + try { + return mapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + return e.toString(); + } + } +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java new file mode 100644 index 0000000000..3c29a96c7e --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; + +import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.firebase.client.DataSnapshot; +import com.firebase.client.ValueEventListener; + + + +/** + * Created by {@link ValueEventListener#onDataChange } triggered in {@link FirebaseSource}. + * @param type that {@link DataSnapshot} is parsed as. + */ +public class ValueChanged extends FirebaseEvent { + + @JsonCreator + public ValueChanged( + @JsonProperty("key") String key, + @JsonProperty("data") T data) { + super(key, data); + } + + public ValueChanged(DataSnapshot snapshot){ + super(snapshot); + } + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java new file mode 100644 index 0000000000..52e0bf5b63 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.values.KV; + +import com.firebase.client.Firebase; + + + +/** + * Creates a unique String ID using {@link Firebase#push()} and outputs an + * {@link com.google.cloud.dataflow.sdk.values.KV} with the String as a key. + */ +public class DoFirebasePush extends FirebaseDoFn> { + + private static final long serialVersionUID = -2377431649046447957L; + + public DoFirebasePush(String url, FirebaseAuthenticator auther) { + super(url, auther); + } + + @Override + public void processElement(DoFn>.ProcessContext context) { + context.output(KV.of(root.push().getKey(), context.element())); + } + + + @Override + public void asyncProcessElement(DoFn>.ProcessContext context, + FirebaseDoFn>.FirebaseListener listener) { + //Call is synchronous, this will not be called + } + +} + + diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java new file mode 100644 index 0000000000..55d0fe2302 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.values.KV; +import com.firebase.client.Firebase; + +/** + * Sets a value using {@link Firebase#setValue(Object)} where the {@code String} key is the + * path to the child to set the value on. Set a path as {@code null} to remove a value. + */ +public class DoFirebaseSet extends FirebaseDoFn, Void> { + + private static final long serialVersionUID = -4587959210797506754L; + + public DoFirebaseSet(String url, FirebaseAuthenticator auther) { + super(url, auther); + } + + @Override + public void asyncProcessElement(DoFn, Void>.ProcessContext context, + FirebaseDoFn, Void>.FirebaseListener listener) { + root.child(context.element().getKey()) + .setValue(context.element().getValue(), listener); + } +} + + diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java new file mode 100644 index 0000000000..973aabca70 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; + +import com.firebase.client.Firebase; + +import java.util.Map; + +/** + * Updates the element at the specified url, using {@link Firebase#updateChildren(Map)}. + */ +public class DoFirebaseUpdate extends FirebaseDoFn, Void> { + + private static final long serialVersionUID = 937268867072092459L; + + + public DoFirebaseUpdate(String url, FirebaseAuthenticator auther) { + super(url, auther); + } + + @Override + public void asyncProcessElement(DoFn, Void>.ProcessContext context, + FirebaseDoFn, Void>.FirebaseListener listener) { + root.updateChildren(context.element(), listener); + } + +} + + diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java new file mode 100644 index 0000000000..20eeef3c42 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; + +import com.google.cloud.dataflow.sdk.transforms.DoFn; + +import com.firebase.client.Firebase; +import com.firebase.client.Firebase.CompletionListener; +import com.firebase.client.FirebaseError; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Abstract superclass for DoFns that need a {@link Firebase} ref. + * This class allows concurrent writes to a Firebase within a bundle and blocks once all writes in + * the bundle are complete, by sharing a single lock across the bundle + * (via the {@code FirebaseListener} class) + */ +public abstract class FirebaseDoFn extends DoFn { + + private static final long serialVersionUID = 2668706582381990870L; + + final String url; + final FirebaseAuthenticator auther; + + transient Firebase root; + private transient Semaphore lock; + + /** + * Releases a permit on the {@link Semaphore} when + * {@link CompletionListener#onComplete(FirebaseError, Firebase)} is called. + */ + protected class FirebaseListener implements CompletionListener{ + @Override + public void onComplete(FirebaseError err, Firebase arg1) { + lock.release(); + if (err != null){ + throw err.toException(); + } + } + } + + /** + * @param url Fully qualified address to the Firebase ref which this DoFn uses. + * @param auther Used to authenticate to Firebase + */ + public FirebaseDoFn(String url, FirebaseAuthenticator auther){ + this.url = url; + this.auther = auther; + } + + @Override + public void startBundle(Context c) throws Exception { + root = new Firebase(this.url); + auther.authenticate(root); + //No need to throttle, that will be taken care of by bundle size + lock = new Semaphore(Integer.MAX_VALUE); + } + + /** + * @param context ProcessContext from the Pipeline + * @param listener Used to indicate when the asynchronous operation is complete + */ + public abstract void asyncProcessElement( + DoFn.ProcessContext context, + FirebaseListener listener); + + @Override + public void processElement(DoFn.ProcessContext context) + throws InterruptedException{ + lock.acquire(); + this.asyncProcessElement(context, new FirebaseListener()); + } + + @Override + public void finishBundle(Context c) throws InterruptedException{ + //Wait "forever" + lock.tryAcquire(Integer.MAX_VALUE, Long.MAX_VALUE, TimeUnit.DAYS); + } +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java new file mode 100644 index 0000000000..887d0adf7e --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java @@ -0,0 +1,406 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.events.ChildAdded; +import com.google.cloud.dataflow.contrib.firebase.events.ChildChanged; +import com.google.cloud.dataflow.contrib.firebase.events.ChildMoved; +import com.google.cloud.dataflow.contrib.firebase.events.ChildRemoved; +import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; +import com.google.cloud.dataflow.contrib.firebase.events.ValueChanged; + +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseCheckpoint; +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseCheckpointCoder; +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseEventCoder; +import com.google.cloud.dataflow.contrib.firebase.utils.Record; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; + +import com.google.common.base.Preconditions; + +import com.fasterxml.jackson.databind.ObjectWriter; +import com.firebase.client.AuthData; +import com.firebase.client.ChildEventListener; +import com.firebase.client.DataSnapshot; +import com.firebase.client.Firebase; +import com.firebase.client.Firebase.CompletionListener; +import com.firebase.client.FirebaseError; +import com.firebase.client.FirebaseException; +import com.firebase.client.Query; +import com.firebase.client.ServerValue; +import com.firebase.client.ValueEventListener; + +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.CountDownLatch; + + + +import javax.annotation.Nullable; + + + + +/** + * Reads events from a {@code Query} and outputs them as {@link FirebaseEvent}s. + * @param Type of object to deserialize {@link DataSnapshot}s into. E.g. {@link java.util.Map} + */ +public class FirebaseSource + extends UnboundedSource, FirebaseCheckpoint> { + + private static final long serialVersionUID = 5926529400127617094L; + + /** + * Uses {@link FirebaseCheckpoint} to build a priority queue based on event time, + * for events triggered by listeners specified in {@link FirebaseSource} construction. + **/ + public class FirebaseReader extends UnboundedReader>{ + + private final FirebaseSource source; + private final MessageDigest digest; + private final Firebase timestampRef; + private final FirebaseCheckpoint checkpoint; + private final Firebase ref; + private ValueEventListener valueListener; + private ChildEventListener childListener; + private FirebaseError error = null; + + FirebaseReader( + FirebaseSource source, + FirebaseCheckpoint checkpoint) { + this.source = source; + try { + this.digest = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + if (checkpoint == null){ + this.checkpoint = new FirebaseCheckpoint<>(); + } else { + this.checkpoint = checkpoint.reset(); + } + this.ref = this.source.getRef(); + this.valueListener = makeValueListener(); + this.childListener = makeChildListener(); + this.timestampRef = this.ref.getRoot().child( + Integer.toHexString(this.hashCode()) + Long.toHexString(System.currentTimeMillis())); + } + + private ValueEventListener makeValueListener() { + return new ValueEventListener(){ + + @Override + public void onCancelled(FirebaseError err) { + error = err; + } + + @Override + public void onDataChange(DataSnapshot snapshot) { + wrapEventWithInstant(new ValueChanged( + snapshot)); + } + }; + } + + private ChildEventListener makeChildListener() { + return new ChildEventListener(){ + @Override + public void onCancelled(FirebaseError err) { + error = err; + } + + @Override + public void onChildAdded(DataSnapshot snapshot, String previousChildName) { + wrapEventWithInstant(new ChildAdded( + snapshot, + previousChildName)); + } + + @Override + public void onChildChanged(DataSnapshot snapshot, String previousChildName) { + wrapEventWithInstant(new ChildChanged( + snapshot, + previousChildName)); + } + + @Override + public void onChildMoved(DataSnapshot snapshot, String previousChildName) { + wrapEventWithInstant(new ChildMoved( + snapshot, + previousChildName)); + } + + @Override + public void onChildRemoved(DataSnapshot snapshot) { + wrapEventWithInstant(new ChildRemoved( + snapshot)); + } + }; + } + + /** + * On receiving an event, {@link FirebaseReader} sets the {@link ServerValue#TIMESTAMP} + * in the Firebase which will be populated with the current server time. This will trigger + * a value change event, which can be used to retrieve a timestamp. Effectively this method + * delegates dealing with clock drift between shards to the Firebase servers. Since events are + * always processed in order by a single client, timestamps will be in the order events were + * recieved. + * @param event {@link FirebaseEvent} to wrap + */ + private void wrapEventWithInstant(final FirebaseEvent event){ + timestampRef.setValue(ServerValue.TIMESTAMP, new CompletionListener(){ + @Override + public void onComplete(FirebaseError err, Firebase ref) { + if (err != null){ + error = err; + } + ref.addListenerForSingleValueEvent(new ValueEventListener(){ + @Override + public void onCancelled(FirebaseError err) { + error = err; + } + @Override + public void onDataChange(DataSnapshot timestamp) { + checkpoint.put(new Record<>( + new Instant(timestamp.getValue(Long.class)), + event)); + } + }); + } + }); + } + + @Override + public boolean advance() throws IOException { + if (error == null){ + return this.checkpoint.advance(); + } + throw error.toException(); + } + + @Override + public CheckpointMark getCheckpointMark() { + return checkpoint; + } + + @Override + public byte[] getCurrentRecordId() throws NoSuchElementException { + return digest.digest( + ByteBuffer.allocate(12).putInt( + this.checkpoint.read().data.hashCode()).putLong( + this.checkpoint.read().timestamp.getMillis()).array()); + } + + @Override + public UnboundedSource, ?> getCurrentSource() { + return this.source; + } + + @Override + public Instant getWatermark() { + return this.checkpoint.minTimestamp(); + } + + @Override + public boolean start() throws IOException { + try { + this.source.auther.authenticate(this.ref); + } catch (Exception e) { + throw new IOException(e); + } + if (this.source.listenForChildEvents){ + this.childListener = this.ref.addChildEventListener(this.childListener); + } + if (this.source.listenForValueEvents){ + this.valueListener = this.ref.addValueEventListener(this.valueListener); + } + return this.advance(); + } + + @Override + public void close() throws IOException { + if (this.source.listenForChildEvents) { + this.ref.removeEventListener(this.childListener); + } + if (this.source.listenForValueEvents){ + this.ref.removeEventListener(this.valueListener); + } + final CountDownLatch lock = new CountDownLatch(1); + timestampRef.removeValue(new CompletionListener(){ + + @Override + public void onComplete(FirebaseError err, Firebase arg1) { + lock.countDown(); + if (err != null){ + throw err.toException(); + } + } + }); + try { + lock.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException(); + } + } + + /** + * @see com.google.cloud.dataflow.sdk.io.Source.Reader#getCurrent() + **/ + @Override + public FirebaseEvent getCurrent() throws NoSuchElementException { + if (this.checkpoint.read() == null){ + throw new NoSuchElementException(); + } + return this.checkpoint.read().data; + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + if (this.checkpoint.read() == null){ + throw new NoSuchElementException(); + } + return this.checkpoint.read().timestamp; + } + } + + private final String queryString; + private final FirebaseAuthenticator auther; + private final boolean listenForChildEvents; + private final boolean listenForValueEvents; + private final Class clazz; + private final Logger logger = LoggerFactory.getLogger(FirebaseSource.class); + + /** + * @see FirebaseSource#of(Class, FirebaseAuthenticator, Query) + * @return A FirebaseSource that uses only a {@link ChildEventListener} + */ + public static FirebaseSource childListenerOf( + Class clazz, + FirebaseAuthenticator auther, + Query query){ + return new FirebaseSource<>(clazz, auther, query, true, false); + } + + /** + * @see FirebaseSource#of(Class, FirebaseAuthenticator, Query) + * @return A FirebaseSource that uses only a {@link ValueEventListener} + */ + public static FirebaseSource valueListenerOf( + Class clazz, + FirebaseAuthenticator auther, + Query query){ + return new FirebaseSource<>(clazz, auther, query, false, true); + } + + /** + * @param clazz determines the type of data the {@link DataSnapshot}s received from Firebase + * servers will be unmarshalled into, and serialized and deserialized. Any POJO which is + * serializable as a JSON Object by an {@link ObjectWriter} will work. + * @param auther Used to authenticate to Firebase + * @param query The {@link Query} which will create events passed on to the pipeline. + * @return A FirebaseSource that uses both a {@link ChildEventListener} and a + * {@link ValueEventListener} + */ + public static FirebaseSource of( + Class clazz, + FirebaseAuthenticator auther, + Query query){ + return new FirebaseSource<>(clazz, auther, query, true, true); + } + + /** + * @param clazz Class Reference for the type to deserialize {@link DataSnapshot}s into. + * @param auther Authenticator + * @param query Any {@link Query} reference. + * @param listenForChildEvents Adds a {@link ChildEventListener} during runtime + * @param listenForValueEvents Adds a {@link ValueEventListener} during runtime + */ + protected FirebaseSource( + Class clazz, + FirebaseAuthenticator auther, + Query query, + boolean listenForChildEvents, + boolean listenForValueEvents){ + if (query.toString().equals(query.getRef().getRoot().toString())){ + throw new IllegalArgumentException("Cannot use a reference to the root of a Firebase " + + "repository. Since FirebaseSource uses a ref at the root of the repository to store" + + "timestamps, this will result in an endless event loop, which will livelock your" + + "pipeline."); + } + this.clazz = clazz; + this.auther = auther; + this.queryString = query.getRef().toString(); + this.listenForChildEvents = listenForChildEvents; + this.listenForValueEvents = listenForValueEvents; + } + + protected Firebase getRef(){ + return new Firebase(this.queryString); + } + + @SuppressWarnings("unchecked") + @Override + public List, FirebaseCheckpoint>> + generateInitialSplits( + int numSplits, PipelineOptions arg1) throws Exception { + return Collections.singletonList(this); + } + + @Override + public Coder> getDefaultOutputCoder() { + return FirebaseEventCoder.of(new TypeDescriptor>(){}, this.clazz); + } + + @Override + public void validate() { + AuthData result; + try { + result = auther.authenticate(this.getRef()); + } catch (FirebaseException e) { + throw new RuntimeException("Authenticator failed to authenticate", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Thread interrupted while waiting for authentication to complete", e); + } + Preconditions.checkNotNull(result, "If result is null, authenticators is "); + } + + @Override + public UnboundedReader> createReader( + PipelineOptions arg0, @Nullable FirebaseCheckpoint arg1) { + return new FirebaseReader(this, arg1); + } + + @Override + public Coder> getCheckpointMarkCoder() { + return FirebaseCheckpointCoder.of(new TypeDescriptor>(){}, this.clazz); + } + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java new file mode 100644 index 0000000000..c7e49f02cf --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; +import com.firebase.client.AuthData; +import com.firebase.client.Firebase; +import com.firebase.client.FirebaseException; + +import java.io.Serializable; + +/** + * Wrapper for the many {@link Firebase} auth methods. + */ +public abstract class FirebaseAuthenticator implements Serializable { + + private static final long serialVersionUID = 2795829710483502835L; + + public abstract AuthData authenticate(Firebase firebase) + throws FirebaseException, InterruptedException; + + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java new file mode 100644 index 0000000000..8259a1f1fc --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; + +import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource.FirebaseReader; +import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.joda.time.Instant; + +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.PriorityBlockingQueue; + +import javax.annotation.Nullable; + +/** + * Maintains a {@link PriorityBlockingQueue} to store the {@link Record}s created by + * {@link FirebaseReader}, on error these records are replayed on the new Reader to prevent + * dataloss. + * @param + */ +public class FirebaseCheckpoint implements CheckpointMark { + + //Oldest on top + private PriorityBlockingQueue> unread; + private LinkedBlockingQueue> read; + + private Record cur; + + @JsonCreator + public FirebaseCheckpoint( + @JsonProperty("read") Record[] read, + @JsonProperty("unread") Record[] unread, + @JsonProperty("cur") Record cur){ + this.read = new LinkedBlockingQueue<>(read.length); + this.read.addAll(Arrays.asList(read)); + this.unread = new PriorityBlockingQueue<>(unread.length); + this.unread.addAll(Arrays.asList(unread)); + this.cur = cur; + } + + public FirebaseCheckpoint(){ + this.unread = new PriorityBlockingQueue<>(); + this.read = new LinkedBlockingQueue<>(); + } + + @Override + public void finalizeCheckpoint() throws IOException { + this.read = new LinkedBlockingQueue<>(); + } + + public Instant minTimestamp(){ + @Nullable Record next = unread.peek(); + // NOTE: records compare using their timestamps + if (next == null || cur.compareTo(next) < 0) { + return cur.timestamp; + } else { + return next.timestamp; + } + } + + public FirebaseCheckpoint reset(){ + unread.addAll(read); + try { + this.finalizeCheckpoint(); + } catch (IOException e) { + e.printStackTrace(); + } + return this; + } + + public void put(Record e){ + unread.put(e); + } + + public Record read(){ + return this.cur; + } + + public boolean advance(){ + if (cur != null){ + read.add(cur); + } + cur = unread.poll(); + return cur != null; + } + + /** + * For {@link FirebaseCheckpointCoder}. + */ + @SuppressWarnings("unchecked") + public Record[] getRead(){ + return this.read.toArray(new Record[read.size()]); + } + + /** + * For {@link FirebaseCheckpointCoder}. + */ + @SuppressWarnings("unchecked") + public Record[] getUnread(){ + return this.unread.toArray(new Record[unread.size()]); + } + + public Record getCur(){ + return this.cur; + } + + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java new file mode 100644 index 0000000000..fda469c96c --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java @@ -0,0 +1,104 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; + +import static com.google.cloud.dataflow.sdk.util.Structs.addString; +import com.google.cloud.dataflow.contrib.firebase.contrib.JacksonCoder; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + + + +/** + * @see JacksonCoder + * Subclassed to allow parameterized type to behave property + * @param Type of {@link Record} encoded by {@link FirebaseCheckpoint} + */ +public class FirebaseCheckpointCoder extends JacksonCoder> { + private final Class subType; + + @SuppressWarnings("unchecked") + public FirebaseCheckpointCoder(TypeDescriptor> type, Class subType) { + this((Class>) type.getRawType(), subType); + } + + public FirebaseCheckpointCoder(Class> type, Class subType) { + super(type); + this.subType = subType; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @JsonCreator + public static FirebaseCheckpointCoder of( + @JsonProperty("type") String classType, + @JsonProperty("subType") String subClassType) throws ClassNotFoundException { + return new FirebaseCheckpointCoder(Class.forName(classType), Class.forName(subClassType)); + } + + public static FirebaseCheckpointCoder of( + TypeDescriptor> type, + Class subType) { + return new FirebaseCheckpointCoder(type, subType); + } + + @Override + protected Object writeReplace() { + // When serialized by Java, instances of FirebaseCheckpointCoder should be replaced by + // a SerializedAvroCoderProxy. + return new FirebaseJacksonCoderProxy<>(type, subType); + } + + @Override + public CloudObject asCloudObject() { + CloudObject result = super.asCloudObject(); + addString(result, "subType", subType.getName()); + return result; + } + + public Class getSubType(){ + return this.subType; + } + + + /** + * Serialization proxy to allow fields to be final. + * @param Type of {@link Record} encoded by {@link FirebaseCheckpoint} + */ + protected static class FirebaseJacksonCoderProxy + extends SerializedJacksonCoderProxy>{ + + private final Class subType; + + /** + * @param type + */ + public FirebaseJacksonCoderProxy(Class> type, Class subType) { + super(type); + this.subType = subType; + } + + private Object readResolve() { + // When deserialized, instances of this object should be replaced by + // constructing a FirebaseJacksonCoder. + return new FirebaseCheckpointCoder(this.type, this.subType); + } + + } + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java new file mode 100644 index 0000000000..f078fe55e5 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; + +import com.firebase.client.AuthData; +import com.firebase.client.Firebase; +import com.firebase.client.FirebaseException; + +/** + * Dummy authenticator for test instances of {@link Firebase}. + */ +public class FirebaseEmptyAuthenticator extends FirebaseAuthenticator { + + private static final long serialVersionUID = 7664558699766082532L; + + @Override + public AuthData authenticate(Firebase firebase) throws FirebaseException { + return new AuthData(null, 0, null, null, null, null); + } +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java new file mode 100644 index 0000000000..aad2cd7396 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; + +import static com.google.cloud.dataflow.sdk.util.Structs.addString; + +import com.google.cloud.dataflow.contrib.firebase.contrib.JacksonCoder; +import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; +import com.google.cloud.dataflow.sdk.util.CloudObject; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + + +/** + * Coder for {@link FirebaseEvent}. Subclasses {@link JacksonCoder} so that parameterized types + * behave properly. + */ +public class FirebaseEventCoder extends JacksonCoder> { + + private final Class subType; + + @SuppressWarnings("unchecked") + public FirebaseEventCoder(TypeDescriptor> type, Class subType) { + this((Class>) type.getRawType(), subType); + } + + public FirebaseEventCoder(Class> type, Class subType) { + super(type); + this.subType = subType; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @JsonCreator + public static FirebaseEventCoder of( + @JsonProperty("type") String classType, + @JsonProperty("subType") String subClassType) throws ClassNotFoundException { + return new FirebaseEventCoder(Class.forName(classType), Class.forName(subClassType)); + } + + public static FirebaseEventCoder of( + TypeDescriptor> type, + Class subType) { + return new FirebaseEventCoder(type, subType); + } + + @Override + protected Object writeReplace() { + // When serialized by Java, instances of FirebaseEventCoder should be replaced by + // a SerializedAvroCoderProxy. + return new FirebaseJacksonCoderProxy<>(type, subType); + } + + @Override + public CloudObject asCloudObject() { + CloudObject result = super.asCloudObject(); + addString(result, "subType", subType.getName()); + return result; + } + + public Class getSubType(){ + return this.subType; + } + + /** + * Proxy to allow internal fields to be final. + * @param @see FirebaseEvent + */ + protected static class FirebaseJacksonCoderProxy + extends SerializedJacksonCoderProxy>{ + + private final Class subType; + + /** + * @param type + */ + public FirebaseJacksonCoderProxy(Class> type, Class subType) { + super(type); + this.subType = subType; + } + + private Object readResolve() { + // When deserialized, instances of this object should be replaced by + // constructing an AvroCoder. + return new FirebaseEventCoder(this.type, this.subType); + } + + } + + +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java new file mode 100644 index 0000000000..f5850331e1 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; + +import com.firebase.client.AuthData; +import com.firebase.client.Firebase; +import com.firebase.client.Firebase.AuthResultHandler; +import com.firebase.client.FirebaseError; +import com.firebase.client.FirebaseException; + +import java.util.concurrent.CountDownLatch; + +/** + * Wrapper for {@link Firebase#authWithPassword(String, String, AuthResultHandler)}. + */ +public class FirebasePasswordAuthenticator extends FirebaseAuthenticator { + + private static final long serialVersionUID = -3274906800271012577L; + private final String email; + private final String password; + private transient AuthData result; + + public FirebasePasswordAuthenticator(String email, String password){ + this.email = email; + this.password = password; + } + + @Override + public AuthData authenticate(Firebase firebase) throws FirebaseException, InterruptedException { + final CountDownLatch done = new CountDownLatch(1); + firebase.authWithPassword(this.email, this.password, new AuthResultHandler() { + @Override + public void onAuthenticationError(FirebaseError err) { + done.countDown(); + throw err.toException(); + } + @Override + public void onAuthenticated(AuthData arg0) { + result = arg0; + done.countDown(); + } + }); + done.await(); + return result; + } +} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java new file mode 100644 index 0000000000..b8e57b2327 --- /dev/null +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; + +import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.joda.time.Instant; + + + +/** + * Wrapper for a {@link FirebaseEvent} and a {@link Instant}. + * @param @see FirebaseDataEvent + */ +public class Record implements Comparable>{ + + public final Instant timestamp; + public final FirebaseEvent data; + + @JsonCreator + public Record( + @JsonProperty("timestamp") Instant timestamp, + @JsonProperty("event") FirebaseEvent event){ + this.timestamp = timestamp; + this.data = event; + } + + @Override + public int compareTo(Record o) { + return this.timestamp.compareTo(o.timestamp); + } +} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java new file mode 100644 index 0000000000..0c96e657a0 --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java @@ -0,0 +1,181 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.contrib.LogElements; +import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseEmptyAuthenticator; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.values.PCollection; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.firebase.client.ChildEventListener; +import com.firebase.client.Firebase; +import com.firebase.client.Firebase.CompletionListener; +import com.firebase.client.FirebaseError; +import com.firebase.client.ValueEventListener; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.event.Level; + +import java.io.IOException; +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + + + +/** + * Archetype for comparing events produced by through {@link FirebaseSource} with events surfaced + * by the unmodified {@link ChildEventListener} and {@link ValueEventListener}. + **/ +@RunWith(JUnit4.class) +public abstract class BaseFirebaseSourceTest { + + /** + * Logs all the added entries! + **/ + private class LoggingArrayList extends ArrayList { + private Logger logger; + + LoggingArrayList(Logger logger){ + this.logger = logger; + } + + @Override + public boolean add(T e){ + logger.info(e.toString()); + return super.add(e); + } + + } + + FirebaseAuthenticator auther = new FirebaseEmptyAuthenticator(); + private Throwable err; + Firebase testRef; + + static final Logger LOGGER = LoggerFactory.getLogger(BaseFirebaseSourceTest.class); + + private final LoggingArrayList> expected = + new LoggingArrayList<>(LOGGER); + + @Before + public void setUp() throws IOException, InterruptedException { + + testRef = new Firebase("https://dataflowio.firebaseio-demo.com") + .child(Integer.toHexString(this.hashCode()) + + Long.toHexString(System.currentTimeMillis())); + + cleanFirebase(testRef); + + prepareData(new ObjectMapper().>>readValue( + ClassLoader.getSystemResourceAsStream("testdata.json"), + new TypeReference>() {})); + + } + + @After + public void teardown() throws InterruptedException{ + cleanFirebase(testRef); + } + + private Thread getPipelineThread(final Pipeline p){ + Thread t = new Thread(new Runnable(){ + @Override + public void run() { + LOGGER.info(p.run().getState().toString()); + } + }); + t.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){ + @Override + public void uncaughtException(Thread t, Throwable e) { + err = e; + } + }); + return t; + } + + private void cleanFirebase(Firebase f) throws InterruptedException{ + final CountDownLatch lock = new CountDownLatch(1); + f.removeValue(new CompletionListener(){ + @Override + public void onComplete(FirebaseError arg0, Firebase arg1) { + lock.countDown(); + } + }); + lock.await(); + } + + public abstract void prepareData(List> testData); + + public abstract void triggerEvents(Firebase f); + + public abstract void addListener(Firebase f, final Collection> events); + + public abstract void removeListener(Firebase f); + + public abstract FirebaseSource makeSource(FirebaseAuthenticator auther, + Firebase f); + + @Test + public void matchEvents() throws Throwable{ + + //Generate expected events + addListener(testRef, expected); + triggerEvents(testRef); + cleanFirebase(testRef); + removeListener(testRef); + LOGGER.info("At most " + expected.size() + " elements to look for in pipeline"); + + + FirebaseSource source = makeSource(auther, testRef); + + TestPipeline p = TestPipeline.create(); + + PCollection> events = p + .apply(Read.from(source).withMaxNumRecords(expected.size())); + + events.apply(new LogElements>(FirebaseChildTest.class, Level.INFO)); + + DataflowAssert.that(events).containsInAnyOrder(expected); + + //Test pipeline against expected events; + Thread t = getPipelineThread(p); + t.start(); + Thread.sleep(1500); + triggerEvents(testRef); + cleanFirebase(testRef); + t.join(); + if (err != null){ + throw err; + } + } + +} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java new file mode 100644 index 0000000000..4fd74079d7 --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.events.ChildAdded; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; +import com.google.cloud.dataflow.sdk.values.KV; + +import com.firebase.client.Firebase; + +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.List; +import java.util.Map; + + + + +/** + * Triggers {@link ChildAdded} events. + */ +@RunWith(JUnit4.class) +public class ChildAddedTest extends FirebaseChildTest { + + private KV[] usableData; + + @Override + public void triggerEvents(Firebase f) { + DoFnTester.of(new DoFirebaseSet(f.toString(), auther)).processBatch(usableData); + } + + @SuppressWarnings("unchecked") + @Override + public void prepareData(List> testData) { + Object[] entries = testData.toArray(); + + List> withKeys = DoFnTester.of( + new DoFirebasePush(testRef.toString(), + auther)) + .processBatch(entries); + + usableData = withKeys.toArray(new KV[withKeys.size()]); + } +} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java new file mode 100644 index 0000000000..ce6d5dacae --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; + +import com.firebase.client.Firebase; + +import java.util.List; +import java.util.Map; + +/** + * TODO: Insert description here. (generated by elibixby) + */ +public class ChildChangedTest extends FirebaseChildTest { + + Map[] usableData; + + @SuppressWarnings("unchecked") + @Override + public void prepareData(List> testData) { + usableData = testData.toArray(new Map[testData.size()]); + } + + @Override + public void triggerEvents(Firebase f) { + DoFnTester.of(new DoFirebaseUpdate(f.toString(), auther)).processBatch(usableData); + } + +} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java new file mode 100644 index 0000000000..ce0d799af7 --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; +import com.google.cloud.dataflow.sdk.values.KV; + +import com.firebase.client.Firebase; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * TODO: Insert description here. (generated by elibixby) + */ +public class ChildMovedTest extends FirebaseChildTest { + + private KV>[] withPriority; + private KV>[] shuffle; + + @Override + public void triggerEvents(Firebase f) { + @SuppressWarnings("deprecation") + DoFnTester>, Void> setWithPriority = + DoFnTester.of(new DoFirebaseSetWithPriority(f.toString(), auther)); + + setWithPriority.processBatch(withPriority); + setWithPriority.processBatch(shuffle); + + } + + @SuppressWarnings("unchecked") + @Override + public void prepareData(List> testData) { + Set> entrySet = testData.get(0).entrySet(); + + withPriority = new KV[entrySet.size()]; + shuffle = new KV[entrySet.size()]; + + int i = 0; + for (Entry entry : entrySet){ + withPriority[i] = KV.of( + entry.getKey(), + KV.of( + entry.getValue(), + String.valueOf(i))); + shuffle[i] = KV.of( + entry.getKey(), + KV.of( + entry.getValue(), + String.valueOf((i + 1) % entrySet.size()))); + i++; + } + } +} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java new file mode 100644 index 0000000000..04f61f2a91 --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.events.ChildRemoved; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; +import com.google.cloud.dataflow.sdk.values.KV; + +import com.firebase.client.Firebase; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Triggers {@link ChildRemoved} events by adding a large number of data and removing it. + */ +public class ChildRemovedTest extends FirebaseChildTest { + + private KV[] someData; + private KV[] nulls; + + @SuppressWarnings("unchecked") + @Override + public void prepareData(List> testData) { + Set> entrySet = testData.get(0).entrySet(); + + nulls = new KV[entrySet.size()]; + someData = new KV[entrySet.size()]; + int i = 0; + for (Entry entry : entrySet){ + LOGGER.info(entry.getKey()); + nulls[i] = KV.of(entry.getKey(), null); + someData[i] = KV.of(entry.getKey(), entry.getValue()); + i++; + } + } + + @Override + public void triggerEvents(Firebase f) { + DoFnTester, Void> setter = DoFnTester.of( + new DoFirebaseSet(f.toString(), auther)); + setter.processBatch(someData); + setter.processBatch(nulls); + } +} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java new file mode 100644 index 0000000000..d3996910b4 --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.values.KV; + +import com.firebase.client.Firebase; + +/** + * Uses {@link Firebase#setValue(Object, Object)} to set an object with a priority. + * This is a bad pattern, and only used to trigger ChildMovedTest. Users should prefer + * {@link Firebase#orderByKey()} to {@link Firebase#orderByPriority()} and as such have no need + * to set priority. + */ +@Deprecated +class DoFirebaseSetWithPriority extends + FirebaseDoFn>, Void> { + + private static final long serialVersionUID = 1321447767620652932L; + + DoFirebaseSetWithPriority(String url, FirebaseAuthenticator auther) { + super(url, auther); + } + + @Override + public void asyncProcessElement( + DoFn>, Void>.ProcessContext context, + FirebaseDoFn>, Void>.FirebaseListener listener) { + root.child(context.element().getKey()) + .setValue( + context.element().getValue().getKey(), + context.element().getValue().getValue(), + listener); + } +} + diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java new file mode 100644 index 0000000000..e8a5409a48 --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.events.ChildAdded; +import com.google.cloud.dataflow.contrib.firebase.events.ChildChanged; +import com.google.cloud.dataflow.contrib.firebase.events.ChildMoved; +import com.google.cloud.dataflow.contrib.firebase.events.ChildRemoved; +import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; + +import com.fasterxml.jackson.databind.JsonNode; +import com.firebase.client.ChildEventListener; +import com.firebase.client.DataSnapshot; +import com.firebase.client.Firebase; +import com.firebase.client.FirebaseError; + +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Collection; + +/** + * Parent test for all tests which trigger events in a {@link ChildEventListener}. + **/ +@RunWith(JUnit4.class) +public abstract class FirebaseChildTest extends BaseFirebaseSourceTest { + + ChildEventListener listener; + + @Override + public void addListener(Firebase f, final Collection> events) { + listener = f.addChildEventListener(new ChildEventListener(){ + + @Override + public void onCancelled(FirebaseError err) { } + + @Override + public void onChildAdded(DataSnapshot data, String previousChildName) { + events.add(new ChildAdded(data, previousChildName)); + } + + @Override + public void onChildChanged(DataSnapshot data, String previousChildName) { + events.add(new ChildChanged(data, previousChildName)); + } + + @Override + public void onChildMoved(DataSnapshot data, String previousChildName) { + events.add(new ChildMoved(data, previousChildName)); + } + + @Override + public void onChildRemoved(DataSnapshot data) { + events.add(new ChildRemoved(data)); + } + }); + } + + @Override + public void removeListener(Firebase f) { + f.removeEventListener(listener); + } + + @Override + public FirebaseSource makeSource( + FirebaseAuthenticator auther, + Firebase f) { + return FirebaseSource.childListenerOf(JsonNode.class, auther, f); + + } + +} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java new file mode 100644 index 0000000000..757df2bfbc --- /dev/null +++ b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java @@ -0,0 +1,103 @@ +/** + * Copyright (c) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; + +import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; +import com.google.cloud.dataflow.contrib.firebase.events.ValueChanged; +import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.firebase.client.DataSnapshot; +import com.firebase.client.Firebase; +import com.firebase.client.FirebaseError; +import com.firebase.client.ValueEventListener; + +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + + + +/** + * Triggers value changes. + * Potentially flakey since it relies on spacing out value changes to avoid events being + * globbed by Firebase Client Library + */ +@RunWith(JUnit4.class) +public class FirebaseValueTest extends BaseFirebaseSourceTest { + + ValueEventListener listener; + List> someData; + + @SuppressWarnings("unchecked") + @Override + public void prepareData(List> testData) { + someData = testData; + try { + LOGGER.info(new ObjectMapper().writeValueAsString(someData)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("unchecked") + @Override + public void triggerEvents(Firebase f) { + DoFnTester, Void> updater = DoFnTester.of( + new DoFirebaseUpdate(f.toString(), auther)); + for (Map data : someData){ + updater.processBatch(data); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + @Override + public void addListener(Firebase f, final Collection> events) { + listener = f.addValueEventListener(new ValueEventListener(){ + + @Override + public void onCancelled(FirebaseError err) { } + + @Override + public void onDataChange(DataSnapshot data) { + events.add(new ValueChanged(data)); + } + }); + } + + @Override + public void removeListener(Firebase f) { + f.removeEventListener(listener); + } + + @Override + public FirebaseSource makeSource( + FirebaseAuthenticator auther, + Firebase f) { + return FirebaseSource.valueListenerOf(JsonNode.class, auther, f); + } + +} diff --git a/contrib/firebaseio/src/test/resources/testdata.json b/contrib/firebaseio/src/test/resources/testdata.json new file mode 100644 index 0000000000..34b5153fab --- /dev/null +++ b/contrib/firebaseio/src/test/resources/testdata.json @@ -0,0 +1,302 @@ +[ + { + "_id": "55e61a3012dc397360c371f2", + "index": 0, + "guid": "012118a4-5f74-460d-83f9-acfa91fb1bc3", + "isActive": false, + "balance": "$2,685.88", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "blue", + "name": { + "first": "Carrillo", + "last": "Cantrell" + }, + "company": "ENVIRE", + "email": "carrillo.cantrell@envire.me", + "phone": "+1 (923) 418-3207", + "address": "153 Nassau Street, Choctaw, Tennessee, 3970", + "about": "Ullamco labore eiusmod fugiat non culpa reprehenderit qui incididunt deserunt nisi minim sit voluptate excepteur. Esse sunt sunt cillum voluptate ea. Incididunt non anim aliquip qui Lorem aute veniam ad cupidatat.", + "registered": "Tuesday, March 17, 2015 10:20 AM", + "latitude": "-36.557494", + "longitude": "164.76669", + "tags": [ + "mollit", + "occaecat", + "et", + "non", + "est", + "deserunt", + "esse", + "custom_tag" + ], + "range": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + "friends": [ + { + "id": 0, + "name": "Virginia Watkins" + }, + { + "id": 1, + "name": "Duffy Hancock" + }, + { + "id": 2, + "name": "Kelsey Hill" + } + ], + "greeting": "Hello, Carrillo! You have 9 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "55e61a30a83a40606944bf81", + "index": 1, + "guid": "989508d7-8545-481f-b13d-d14e92e718cd", + "isActive": false, + "balance": "$3,122.94", + "picture": "http://placehold.it/32x32", + "age": 25, + "eyeColor": "blue", + "name": { + "first": "Priscilla", + "last": "Adkins" + }, + "company": "ZILLACON", + "email": "priscilla.adkins@zillacon.org", + "phone": "+1 (818) 547-3211", + "address": "137 Grant Avenue, Riverton, Rhode Island, 2077", + "about": "Irure sit ad occaecat et minim eu. Deserunt deserunt et enim fugiat. Ex commodo aliquip ad ipsum do aliquip sunt consectetur culpa dolore commodo. Reprehenderit aute amet aliquip enim esse magna do. Est nostrud amet voluptate magna est elit qui occaecat ea qui eu est sint. Aute exercitation sunt nostrud tempor cupidatat mollit culpa nulla labore.", + "registered": "Sunday, May 17, 2015 4:29 AM", + "latitude": "27.772689", + "longitude": "-46.103999", + "tags": [ + "mollit", + "occaecat", + "et", + "non", + "est", + "deserunt", + "esse", + "custom_tag" + ], + "range": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + "friends": [ + { + "id": 0, + "name": "Virginia Watkins" + }, + { + "id": 1, + "name": "Duffy Hancock" + }, + { + "id": 2, + "name": "Kelsey Hill" + } + ], + "greeting": "Hello, Priscilla! You have 5 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "55e61a3099c1283f4d6dd2ba", + "index": 2, + "guid": "4afb20cd-a10f-4aff-9433-6f91c70ad371", + "isActive": true, + "balance": "$1,120.38", + "picture": "http://placehold.it/32x32", + "age": 27, + "eyeColor": "blue", + "name": { + "first": "Kirk", + "last": "Clarke" + }, + "company": "ENERFORCE", + "email": "kirk.clarke@enerforce.us", + "phone": "+1 (862) 592-3458", + "address": "242 Euclid Avenue, Ronco, North Dakota, 4513", + "about": "Dolor elit ad excepteur labore do sint nisi voluptate Lorem et qui pariatur veniam sit. Amet in in eiusmod exercitation culpa quis enim fugiat sit. Duis magna ex laborum irure. Cillum culpa est mollit id enim do deserunt in officia. Elit mollit elit sit enim elit non.", + "registered": "Thursday, July 30, 2015 2:27 PM", + "latitude": "52.963677", + "longitude": "-48.650757", + "tags": [ + "mollit", + "occaecat", + "et", + "non", + "est", + "deserunt", + "esse", + "custom_tag" + ], + "range": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + "friends": [ + { + "id": 0, + "name": "Virginia Watkins" + }, + { + "id": 1, + "name": "Duffy Hancock" + }, + { + "id": 2, + "name": "Kelsey Hill" + } + ], + "greeting": "Hello, Kirk! You have 9 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "55e61a30c7cc81267cba07b1", + "index": 3, + "guid": "287199ca-5e64-4a25-b900-f23fee037d49", + "isActive": true, + "balance": "$3,579.20", + "picture": "http://placehold.it/32x32", + "age": 20, + "eyeColor": "green", + "name": { + "first": "Lillie", + "last": "Glenn" + }, + "company": "VISUALIX", + "email": "lillie.glenn@visualix.info", + "phone": "+1 (844) 476-3891", + "address": "127 Kingston Avenue, Roderfield, Arizona, 5033", + "about": "Officia tempor eu in voluptate. Ipsum nisi ut irure aliqua laborum excepteur cillum. Cillum ea eiusmod duis tempor quis ut. Est aute ipsum mollit consectetur exercitation fugiat pariatur minim.", + "registered": "Monday, June 23, 2014 7:10 AM", + "latitude": "39.351941", + "longitude": "-147.015315", + "tags": [ + "mollit", + "occaecat", + "et", + "non", + "est", + "deserunt", + "esse", + "custom_tag" + ], + "range": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + "friends": [ + { + "id": 0, + "name": "Virginia Watkins" + }, + { + "id": 1, + "name": "Duffy Hancock" + }, + { + "id": 2, + "name": "Kelsey Hill" + } + ], + "greeting": "Hello, Lillie! You have 6 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "55e61a30fc1bed5d41139b57", + "index": 4, + "guid": "4ae2f0d8-4648-4f9c-a0ae-8866c2ff07cb", + "isActive": true, + "balance": "$1,868.85", + "picture": "http://placehold.it/32x32", + "age": 30, + "eyeColor": "green", + "name": { + "first": "Hudson", + "last": "Blevins" + }, + "company": "DOGNOSIS", + "email": "hudson.blevins@dognosis.net", + "phone": "+1 (808) 407-3340", + "address": "554 Portland Avenue, Abrams, Illinois, 6182", + "about": "Pariatur elit tempor ut officia minim aliquip anim sint mollit. Nostrud fugiat exercitation irure veniam reprehenderit ad in consequat quis ea nisi. Eiusmod nisi nostrud consectetur nulla eiusmod ipsum excepteur do irure consectetur culpa velit fugiat. Nostrud sit ullamco nostrud eu exercitation labore. Quis magna laboris et consequat. Sit fugiat nisi amet sint culpa ullamco.", + "registered": "Friday, December 5, 2014 5:28 AM", + "latitude": "0.694342", + "longitude": "104.825617", + "tags": [ + "mollit", + "occaecat", + "et", + "non", + "est", + "deserunt", + "esse", + "custom_tag" + ], + "range": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + "friends": [ + { + "id": 0, + "name": "Virginia Watkins" + }, + { + "id": 1, + "name": "Duffy Hancock" + }, + { + "id": 2, + "name": "Kelsey Hill" + } + ], + "greeting": "Hello, Hudson! You have 8 unread messages.", + "favoriteFruit": "strawberry" + } +] \ No newline at end of file From 3dac5e5e042b5434a9173288bb3e3d9a48ff5cc0 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 7 Jun 2016 18:05:59 -0700 Subject: [PATCH 444/751] Use a DirectExecutor for Watermark Callbacks This fixes a resource leak where the executor service is not properly shut down with the rest of the InProcessPipelineRunner. --- .../runners/inprocess/InProcessEvaluationContext.java | 4 ++-- .../runners/inprocess/WatermarkCallbackExecutor.java | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index b2ad161337..1d3f168657 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -43,13 +43,13 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; +import com.google.common.util.concurrent.MoreExecutors; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Executors; import javax.annotation.Nullable; @@ -127,7 +127,7 @@ private InProcessEvaluationContext( this.applicationStateInternals = new ConcurrentHashMap<>(); this.mergedCounters = new CounterSet(); - this.callbackExecutor = WatermarkCallbackExecutor.create(Executors.newSingleThreadExecutor()); + this.callbackExecutor = WatermarkCallbackExecutor.create(MoreExecutors.directExecutor()); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java index e240544d17..a331f5c12b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java @@ -26,7 +26,7 @@ import java.util.PriorityQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executor; /** * Executes callbacks that occur based on the progression of the watermark per-step. @@ -48,15 +48,15 @@ class WatermarkCallbackExecutor { /** * Create a new {@link WatermarkCallbackExecutor}. */ - public static WatermarkCallbackExecutor create(ExecutorService executor) { + public static WatermarkCallbackExecutor create(Executor executor) { return new WatermarkCallbackExecutor(executor); } private final ConcurrentMap, PriorityQueue> callbacks; - private final ExecutorService executor; + private final Executor executor; - private WatermarkCallbackExecutor(ExecutorService executor) { + private WatermarkCallbackExecutor(Executor executor) { this.callbacks = new ConcurrentHashMap<>(); this.executor = executor; } @@ -98,7 +98,7 @@ public void fireForWatermark(AppliedPTransform step, Instant watermark) } synchronized (callbackQueue) { while (!callbackQueue.isEmpty() && callbackQueue.peek().shouldFire(watermark)) { - executor.submit(callbackQueue.poll().getCallback()); + executor.execute(callbackQueue.poll().getCallback()); } } } From 8348001317a20c2e96fabaf53b8fa584d91e4aed Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 6 Jun 2016 13:30:12 -0700 Subject: [PATCH 445/751] Version management: update to 1.7.0-SNAPSHOT ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=124171144 --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index c15f73f688..a476c3ff91 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 4e999083b0..7f6dfbc046 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 0aa71c49f9..828f6f5c1d 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index cbc1cdcd12..0f594b7182 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index e412db1f7f..eb5f27339e 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT com.google.cloud.dataflow From f59379d9051bf854bdfe47c8b950da4b6a9fdf53 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 9 Jun 2016 08:46:37 -0700 Subject: [PATCH 446/751] Disable exec-maven-plugin cleanupDaemonThreads exec-maven-plugin has a bad interaction with DataflowPipelineRunner when waiting on daemon threads. When running example pipelines, Maven will emit a warning saying background threads are alive after being aborted. This looks to users like an error while there's actually no harm to it. Disabling cleanupDaemonThreads suppresses this warning. (cherry picked from commit 70ba4f0dd63d564205b58d0ba4e5215f6802f8c9) --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 0f594b7182..c97feebedf 100644 --- a/pom.xml +++ b/pom.xml @@ -174,6 +174,7 @@ + false java.util.logging.config.file From 79e9b3164b14fc83ac25f7b88737050c6a1b327c Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Sun, 12 Jun 2016 12:05:57 -0700 Subject: [PATCH 447/751] Version management: restore 1.6.0-SNAPSHOT for 1.6.0 release Revert "Version management: update to 1.7.0-SNAPSHOT" --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index a476c3ff91..c15f73f688 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.6.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 7f6dfbc046..4e999083b0 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 828f6f5c1d..0aa71c49f9 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index c97feebedf..763cf77cee 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.7.0-SNAPSHOT + 1.6.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index eb5f27339e..e412db1f7f 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.6.0-SNAPSHOT com.google.cloud.dataflow From f82fe56272cf640c72f02d589c705436cac74d40 Mon Sep 17 00:00:00 2001 From: dhalperi Date: Mon, 6 Jun 2016 13:30:12 -0700 Subject: [PATCH 448/751] Version management: update to 1.7.0-SNAPSHOT First commit after v1.6.0 release --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index c15f73f688..a476c3ff91 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 4e999083b0..7f6dfbc046 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 0aa71c49f9..828f6f5c1d 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index 763cf77cee..c97feebedf 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index e412db1f7f..eb5f27339e 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.6.0-SNAPSHOT + 1.7.0-SNAPSHOT com.google.cloud.dataflow From f241d587fd73cb8ffe7dc6df4f08d1b68465a4ef Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Fri, 10 Jun 2016 12:52:43 -0700 Subject: [PATCH 449/751] Port cleanupDaemonThreads fix to archetype module (cherry picked from commit 51030829ef53001eb7db608fd56bcf1b4bea4249) --- .../src/main/resources/archetype-resources/pom.xml | 13 +++++++++++++ .../src/main/resources/archetype-resources/pom.xml | 13 +++++++++++++ .../test/resources/projects/basic/reference/pom.xml | 13 +++++++++++++ 3 files changed, 39 insertions(+) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 060c02a207..486a82b602 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -87,6 +87,19 @@ + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + false + + + + diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index bb679a00b4..ab2bcf9a70 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -19,6 +19,19 @@ + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + false + + + + diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index d8c563d07f..b94fb39e12 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -19,6 +19,19 @@ + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + false + + + + From a7690a023ceba34893ac2e100f71b7380dd77532 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 13 Jun 2016 17:34:58 -0700 Subject: [PATCH 450/751] CompressedSourceTest: simplify We should use random.nextBytes(buff) instead of making the array in a loop. The code we now point to is the same as the for loop, so the test continues to pass. --- .../google/cloud/dataflow/sdk/io/CompressedSourceTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index 702d93cba5..e6769315fc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -368,9 +368,7 @@ private byte[] generateInput(int size) { // Arbitrary but fixed seed Random random = new Random(285930); byte[] buff = new byte[size]; - for (int i = 0; i < size; i++) { - buff[i] = (byte) (random.nextInt() % Byte.MAX_VALUE); - } + random.nextBytes(buff); return buff; } From 444609f80c928dafabe2daf412f52b72d3c9ab7b Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 13 Jun 2016 17:48:02 -0700 Subject: [PATCH 451/751] Make example AddTimestampFn range deterministic (#303) The timestamps added in the WindowedWordCount example are currently based on when the bundles are executed, which makes the min/max bounds non-deterministic. This change makes the range based on the construction time. (cherry picked from commit 335202a033ced6f30f1b0e5df9da047241abc750) --- .../cloud/dataflow/examples/WindowedWordCount.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java index 2adac55627..5a4841e3f0 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java @@ -122,13 +122,18 @@ public class WindowedWordCount { * 2-hour period. */ static class AddTimestampFn extends DoFn { - private static final long RAND_RANGE = 7200000; // 2 hours in ms + private static final Duration RAND_RANGE = Duration.standardHours(2); + private final Instant minTimestamp; + + AddTimestampFn() { + this.minTimestamp = new Instant(System.currentTimeMillis()); + } @Override public void processElement(ProcessContext c) { // Generate a timestamp that falls somewhere in the past two hours. - long randomTimestamp = System.currentTimeMillis() - - (int) (Math.random() * RAND_RANGE); + long randMillis = (long) (Math.random() * RAND_RANGE.getMillis()); + Instant randomTimestamp = minTimestamp.plus(randMillis); /** * Concept #2: Set the data element with that timestamp. */ From 5c69a4b50c6e3106c9d689327376dbb8c50cee64 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 15 Jun 2016 13:48:11 -0700 Subject: [PATCH 452/751] Backport: Package javadoc for org.apache.beam.sdk.transforms.display (#306) * Package javadoc for org.apache.beam.sdk.transforms.display (cherry picked from commit 2e0836e730c52c0ef7137f67495f43bb4ec2b06a) --- .../sdk/transforms/display/package-info.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java new file mode 100644 index 0000000000..d3e624006f --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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. + */ + +/** + * Defines {@link com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData} for annotating + * components which provide + * {@link com.google.cloud.dataflow.sdk.transforms.display.DisplayData display data} used within UIs + * and diagnostic tools. + * + * @see com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData + */ +package com.google.cloud.dataflow.sdk.transforms.display; From 8bd5f555d2854a5fb4895045b10f85626ab4405b Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 17 Jun 2016 15:55:49 -0700 Subject: [PATCH 453/751] Shutdown the InProcessPipelineRunner after Terminating Abnormally (#311) Ensure that the executor service is shutdown, and the monitor is not rescheduled, after an exception is thrown. --- .../ExecutorServiceParallelExecutor.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index b5ae114be3..ca7880160e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -343,6 +343,8 @@ private class MonitorRunnable implements Runnable { evaluationContext.getPipelineOptions().getAppName(), ExecutorServiceParallelExecutor.class.getSimpleName()); + private boolean exceptionThrown = false; + @Override public void run() { String oldName = Thread.currentThread().getName(); @@ -358,6 +360,7 @@ public void run() { scheduleConsumers(update); } else if (update.getException().isPresent()) { visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); + exceptionThrown = true; } if (System.nanoTime() - updatesStart > maxTimeProcessingUpdatesNanos) { break; @@ -426,15 +429,17 @@ private boolean fireTimers() throws Exception { } private boolean shouldShutdown() { - if (evaluationContext.isDone()) { - LOG.debug("Pipeline is finished. Shutting down. {}"); - while (!visibleUpdates.offer(VisibleExecutorUpdate.finished())) { - visibleUpdates.poll(); + boolean shouldShutdown = exceptionThrown || evaluationContext.isDone(); + if (shouldShutdown) { + if (evaluationContext.isDone()) { + LOG.debug("Pipeline is finished. Shutting down. {}"); + while (!visibleUpdates.offer(VisibleExecutorUpdate.finished())) { + visibleUpdates.poll(); + } + executorService.shutdown(); } - executorService.shutdown(); - return true; } - return false; + return shouldShutdown; } /** From 3a38bf8299747b78a3f316d43410aa6fc7015414 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 17 Jun 2016 15:57:33 -0700 Subject: [PATCH 454/751] Return from awaitCompletion if Already Done (#310) This ensures that a call to ExecutorService#awaitCompletion returns immediately if there are no visible updates and the executor has completed. If the executor is in this state, no additional visible updates will be published and the call will hang. This sequence generally will not happen, as calls via InProcessPipelineResult return if the state is already terminal, but this ensures that parallel calls to awaitCompletion do not hang one calling thread. --- .../inprocess/ExecutorServiceParallelExecutor.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index ca7880160e..27f728d55f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -197,11 +197,16 @@ private void scheduleConsumers(ExecutorUpdate update) { public void awaitCompletion() throws Throwable { VisibleExecutorUpdate update; do { - update = visibleUpdates.take(); - if (update.throwable.isPresent()) { + // Get an update; don't block forever if another thread has handled it + update = visibleUpdates.poll(2L, TimeUnit.SECONDS); + if (update == null && executorService.isShutdown()) { + // there are no updates to process and no updates will ever be published because the + // executor is shutdown + return; + } else if (update != null && update.throwable.isPresent()) { throw update.throwable.get(); } - } while (!update.isDone()); + } while (update == null || !update.isDone()); executorService.shutdown(); } From 98571508d3e82e4599d906d5bb9c8b77b714717f Mon Sep 17 00:00:00 2001 From: millsd Date: Tue, 14 Jun 2016 12:37:44 -0700 Subject: [PATCH 455/751] Upgrade the version of the Dataflow API ----Release Notes---- [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=124869544 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c97feebedf..aeb7bb3506 100644 --- a/pom.xml +++ b/pom.xml @@ -72,7 +72,7 @@ 0.0.2 0.2.3 v2-rev8-1.22.0 - v1b3-rev26-1.22.0 + v1b3-rev28-1.22.0 0.5.160222 v1beta2-rev1-4.0.0 1.22.0 From 312feba6fcce0c89ac87f004d1f31045b673243b Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 24 Jun 2016 21:32:11 -0700 Subject: [PATCH 456/751] Reuse UnboundedReaders in the InProcessRunner (#312) Reuse up to a point, and then discard the reader to exercise resume from checkpoint. --- .../UnboundedReadEvaluatorFactory.java | 145 ++++++++++++++---- .../UnboundedReadEvaluatorFactoryTest.java | 55 +++++-- 2 files changed, 158 insertions(+), 42 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index a0b62b353f..e212021f2a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -19,13 +19,17 @@ import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.annotations.VisibleForTesting; + +import org.joda.time.Instant; import java.io.IOException; import java.util.Queue; @@ -40,6 +44,10 @@ * for the {@link Unbounded Read.Unbounded} primitive {@link PTransform}. */ class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { + // Resume from a checkpoint every nth invocation, to ensure close-and-resume is exercised + @VisibleForTesting + static final int MAX_READER_REUSE_COUNT = 20; + /* * An evaluator for a Source is stateful, to ensure the CheckpointMark is properly persisted. * Evaluators are cached here to ensure that the checkpoint mark is appropriately reused @@ -51,7 +59,7 @@ class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { * an arbitrary Queue implementation does not, so the concrete type is used explicitly. */ private final ConcurrentMap< - EvaluatorKey, ConcurrentLinkedQueue>> + EvaluatorKey, ConcurrentLinkedQueue>> sourceEvaluators = new ConcurrentHashMap<>(); @SuppressWarnings({"unchecked", "rawtypes"}) @@ -76,29 +84,33 @@ private TransformEvaluator getTransformEvaluator( * already done so. */ @SuppressWarnings("unchecked") - private Queue> getTransformEvaluatorQueue( + private + Queue> getTransformEvaluatorQueue( final AppliedPTransform, Unbounded> transform, final InProcessEvaluationContext evaluationContext) { // Key by the application and the context the evaluation is occurring in (which call to // Pipeline#run). EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); @SuppressWarnings("unchecked") - ConcurrentLinkedQueue> evaluatorQueue = - (ConcurrentLinkedQueue>) sourceEvaluators.get(key); + ConcurrentLinkedQueue> evaluatorQueue = + (ConcurrentLinkedQueue>) + sourceEvaluators.get(key); if (evaluatorQueue == null) { evaluatorQueue = new ConcurrentLinkedQueue<>(); if (sourceEvaluators.putIfAbsent(key, evaluatorQueue) == null) { // If no queue existed in the evaluators, add an evaluator to initialize the evaluator // factory for this transform - UnboundedSource source = transform.getTransform().getSource(); - UnboundedReadEvaluator evaluator = - new UnboundedReadEvaluator( + UnboundedSource source = + (UnboundedSource) transform.getTransform().getSource(); + UnboundedReadEvaluator evaluator = + new UnboundedReadEvaluator<>( transform, evaluationContext, source, evaluatorQueue); evaluatorQueue.offer(evaluator); } else { // otherwise return the existing Queue that arrived before us evaluatorQueue = - (ConcurrentLinkedQueue>) sourceEvaluators.get(key); + (ConcurrentLinkedQueue>) + sourceEvaluators.get(key); } } return evaluatorQueue; @@ -114,27 +126,38 @@ private Queue> getTransformEvaluatorQu * checkpoint, and constructs its reader from the current checkpoint in each call to * {@link #finishBundle()}. */ - private static class UnboundedReadEvaluator implements TransformEvaluator { + private static class UnboundedReadEvaluator + implements TransformEvaluator { private static final int ARBITRARY_MAX_ELEMENTS = 10; + private final AppliedPTransform, Unbounded> transform; private final InProcessEvaluationContext evaluationContext; - private final ConcurrentLinkedQueue> evaluatorQueue; + private final ConcurrentLinkedQueue> + evaluatorQueue; /** * The source being read from by this {@link UnboundedReadEvaluator}. This may not be the same * source as derived from {@link #transform} due to splitting. */ - private final UnboundedSource source; - private CheckpointMark checkpointMark; + private final UnboundedSource source; + private UnboundedReader currentReader; + private CheckpointMarkT checkpointMark; + + /** + * The count of bundles output from this {@link UnboundedReadEvaluator}. Used to exercise + * {@link UnboundedReader#close()}. + */ + private int outputBundles = 0; public UnboundedReadEvaluator( AppliedPTransform, Unbounded> transform, InProcessEvaluationContext evaluationContext, - UnboundedSource source, - ConcurrentLinkedQueue> evaluatorQueue) { + UnboundedSource source, + ConcurrentLinkedQueue> evaluatorQueue) { this.transform = transform; this.evaluationContext = evaluationContext; this.evaluatorQueue = evaluatorQueue; this.source = source; + this.currentReader = null; this.checkpointMark = null; } @@ -144,36 +167,92 @@ public void processElement(WindowedValue element) {} @Override public InProcessTransformResult finishBundle() throws IOException { UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); - try (UnboundedReader reader = - createReader(source, evaluationContext.getPipelineOptions());) { - int numElements = 0; - if (reader.start()) { + try { + boolean elementAvailable = startReader(); + + Instant watermark = currentReader.getWatermark(); + if (elementAvailable) { + int numElements = 0; do { - output.add( - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp())); + output.add(WindowedValue.timestampedValueInGlobalWindow(currentReader.getCurrent(), + currentReader.getCurrentTimestamp())); numElements++; - } while (numElements < ARBITRARY_MAX_ELEMENTS && reader.advance()); + } while (numElements < ARBITRARY_MAX_ELEMENTS && currentReader.advance()); + watermark = currentReader.getWatermark(); + // Only take a checkpoint if we did any work + finishRead(); } - checkpointMark = reader.getCheckpointMark(); - checkpointMark.finalizeCheckpoint(); // TODO: When exercising create initial splits, make this the minimum watermark across all // existing readers StepTransformResult result = - StepTransformResult.withHold(transform, reader.getWatermark()) - .addOutput(output) - .build(); + StepTransformResult.withHold(transform, watermark).addOutput(output).build(); evaluatorQueue.offer(this); return result; + } catch (IOException e) { + closeReader(); + throw e; + } + } + + private boolean startReader() throws IOException { + if (currentReader == null) { + if (checkpointMark != null) { + checkpointMark.finalizeCheckpoint(); + } + currentReader = source.createReader(evaluationContext.getPipelineOptions(), checkpointMark); + checkpointMark = null; + return currentReader.start(); + } else { + return currentReader.advance(); } } - private UnboundedReader createReader( - UnboundedSource source, PipelineOptions options) { + /** + * Checkpoint the current reader, finalize the previous checkpoint, and update the state of this + * evaluator. + */ + private void finishRead() throws IOException { + final CheckpointMark oldMark = checkpointMark; @SuppressWarnings("unchecked") - CheckpointMarkT mark = (CheckpointMarkT) checkpointMark; - return source.createReader(options, mark); + final CheckpointMarkT mark = (CheckpointMarkT) currentReader.getCheckpointMark(); + checkpointMark = mark; + if (oldMark != null) { + oldMark.finalizeCheckpoint(); + } + + // If the watermark is the max value, this source may not be invoked again. Finalize after + // committing the output. + if (!currentReader.getWatermark().isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE)) { + evaluationContext.scheduleAfterOutputWouldBeProduced(transform.getOutput(), + GlobalWindow.INSTANCE, + transform.getOutput().getWindowingStrategy(), + new Runnable() { + public void run() { + try { + mark.finalizeCheckpoint(); + } catch (IOException e) { + throw new RuntimeException( + "Couldn't finalize checkpoint after the end of the Global Window", + e); + } + } + }); + } + // Sometimes resume from a checkpoint even if it's not required + + if (outputBundles >= MAX_READER_REUSE_COUNT) { + closeReader(); + outputBundles = 0; + } else { + outputBundles++; + } + } + + private void closeReader() throws IOException { + if (currentReader != null) { + currentReader.close(); + currentReader = null; + } } } } - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java index d96e9e9f21..752069b391 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.nullValue; @@ -41,7 +40,11 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; + +import com.google.common.collect.ContiguousSet; +import com.google.common.collect.DiscreteDomain; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Range; import org.hamcrest.Matchers; import org.joda.time.DateTime; @@ -133,7 +136,29 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleSequentialCalls() t } @Test - public void evaluatorClosesReader() throws Exception { + public void evaluatorClosesReaderAfterOutputCount() throws Exception { + ContiguousSet elems = ContiguousSet.create( + Range.closed(0L, 20L * UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT), + DiscreteDomain.longs()); + TestUnboundedSource source = + new TestUnboundedSource<>(BigEndianLongCoder.of(), elems.toArray(new Long[0])); + + TestPipeline p = TestPipeline.create(); + PCollection pcollection = p.apply(Read.from(source)); + AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + + UncommittedBundle output = bundleFactory.createRootBundle(pcollection); + when(context.createRootBundle(pcollection)).thenReturn(output); + + for (int i = 0; i < UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT + 1; i++) { + TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); + evaluator.finishBundle(); + } + assertThat(TestUnboundedSource.readerClosedCount, equalTo(1)); + } + + @Test + public void evaluatorReusesReaderBeforeCount() throws Exception { TestUnboundedSource source = new TestUnboundedSource<>(BigEndianLongCoder.of(), 1L, 2L, 3L); @@ -148,11 +173,18 @@ public void evaluatorClosesReader() throws Exception { evaluator.finishBundle(); CommittedBundle committed = output.commit(Instant.now()); assertThat(ImmutableList.copyOf(committed.getElements()), hasSize(3)); - assertThat(TestUnboundedSource.readerClosedCount, equalTo(1)); + assertThat(TestUnboundedSource.readerClosedCount, equalTo(0)); + assertThat(TestUnboundedSource.readerAdvancedCount, equalTo(4)); + + evaluator = factory.forApplication(sourceTransform, null, context); + evaluator.finishBundle(); + assertThat(TestUnboundedSource.readerClosedCount, equalTo(0)); + // Tried to advance again, even with no elements + assertThat(TestUnboundedSource.readerAdvancedCount, equalTo(5)); } @Test - public void evaluatorNoElementsClosesReader() throws Exception { + public void evaluatorNoElementsReusesReaderAlways() throws Exception { TestUnboundedSource source = new TestUnboundedSource<>(BigEndianLongCoder.of()); TestPipeline p = TestPipeline.create(); @@ -162,11 +194,13 @@ public void evaluatorNoElementsClosesReader() throws Exception { UncommittedBundle output = bundleFactory.createRootBundle(pcollection); when(context.createRootBundle(pcollection)).thenReturn(output); - TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); - evaluator.finishBundle(); - CommittedBundle committed = output.commit(Instant.now()); - assertThat(committed.getElements(), emptyIterable()); - assertThat(TestUnboundedSource.readerClosedCount, equalTo(1)); + for (int i = 0; i < 2 * UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT; i++) { + TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); + evaluator.finishBundle(); + } + assertThat(TestUnboundedSource.readerClosedCount, equalTo(0)); + assertThat(TestUnboundedSource.readerAdvancedCount, + equalTo(2 * UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT)); } // TODO: Once the source is split into multiple sources before evaluating, this test will have to @@ -212,10 +246,12 @@ public Instant apply(Long input) { private static class TestUnboundedSource extends UnboundedSource { static int readerClosedCount; + static int readerAdvancedCount; private final Coder coder; private final List elems; public TestUnboundedSource(Coder coder, T... elems) { + readerAdvancedCount = 0; readerClosedCount = 0; this.coder = coder; this.elems = Arrays.asList(elems); @@ -263,6 +299,7 @@ public boolean start() throws IOException { @Override public boolean advance() throws IOException { + readerAdvancedCount++; if (index + 1 < elems.size()) { index++; return true; From 2d612a1eb3f60bc372314cbcf865cd538a22ca81 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Fri, 24 Jun 2016 23:33:51 -0500 Subject: [PATCH 457/751] Backport: Fix NullPointerException in AfterWatermark display data (#307) * Fix NullPointerException in AfterWatermark display data Window transforms register display data for the associated trigger function by calling its .toString() method. The AfterWatermark trigger .toString() method was not properly handling cases where there is no late firings registered. (cherry picked from commit e7f2f582afd48bf5e2aacb3a36471377cb927018) * fixup! Fix reference to Never.ever() --- .../sdk/transforms/windowing/AfterWatermark.java | 14 +++++++++----- .../transforms/windowing/AfterWatermarkTest.java | 9 +++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index 77c422a414..4f66b92b07 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -30,6 +30,8 @@ import java.util.List; import java.util.Objects; +import javax.annotation.Nullable; + /** *

            {@code AfterWatermark} triggers fire based on progress of the system watermark. This time is a * lower-bound, sometimes heuristically established, on event times that have been fully processed @@ -144,6 +146,7 @@ private static class AfterWatermarkEarlyAndLate private static final int LATE_INDEX = 1; private final OnceTrigger earlyTrigger; + @Nullable private final OnceTrigger lateTrigger; @SuppressWarnings("unchecked") @@ -264,7 +267,6 @@ public void onFire(Trigger.TriggerContext context) throws Exception { public String toString() { StringBuilder builder = new StringBuilder(TO_STRING); - Trigger earlyTrigger = subTriggers.get(EARLY_INDEX); if (!(earlyTrigger instanceof NeverTrigger)) { builder .append(".withEarlyFirings(") @@ -272,10 +274,12 @@ public String toString() { .append(")"); } - builder - .append(".withLateFirings(") - .append(subTriggers.get(LATE_INDEX)) - .append(")"); + if (lateTrigger != null && !(lateTrigger instanceof NeverTrigger)) { + builder + .append(".withLateFirings(") + .append(lateTrigger) + .append(")"); + } return builder.toString(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java index e1a14c7cdf..cca90db4c8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java @@ -343,6 +343,15 @@ public void testFromEndOfWindowToString() { assertEquals("AfterWatermark.pastEndOfWindow()", trigger.toString()); } + @Test + public void testEarlyFiringsToString() { + Trigger trigger = AfterWatermark.pastEndOfWindow() + .withEarlyFirings(StubTrigger.named("t1")) + .buildTrigger(); + + assertEquals("AfterWatermark.pastEndOfWindow().withEarlyFirings(t1)", trigger.toString()); + } + @Test public void testLateFiringsToString() { Trigger trigger = AfterWatermark.pastEndOfWindow() From c42c3330b07d725aa152a8a32e4c197bf74ce711 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 24 Jun 2016 21:35:52 -0700 Subject: [PATCH 458/751] Add inprocess package-info (#305) --- .../sdk/runners/inprocess/package-info.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java new file mode 100644 index 0000000000..a68325935c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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. + */ + +/** + * Defines the {@link com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner}, + * which executes both Bounded and Unbounded {@code Pipelines} on the local machine. + * + *

            See {@link com.google.cloud.dataflow.sdk.runners} for more information about Pipeline Runners. + */ +package com.google.cloud.dataflow.sdk.runners.inprocess; From 2b0e6964a9774de49f90f12ead919fa4a8361a72 Mon Sep 17 00:00:00 2001 From: joshualitt Date: Tue, 28 Jun 2016 13:01:02 -0700 Subject: [PATCH 459/751] Update dataflow version in pom.xml to maven latest (#316) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index aeb7bb3506..192c81a288 100644 --- a/pom.xml +++ b/pom.xml @@ -72,7 +72,7 @@ 0.0.2 0.2.3 v2-rev8-1.22.0 - v1b3-rev28-1.22.0 + v1b3-rev30-1.22.0 0.5.160222 v1beta2-rev1-4.0.0 1.22.0 From 590e90b2442cda65ba4c1f2ac8b0a67747c69999 Mon Sep 17 00:00:00 2001 From: peihe Date: Tue, 28 Jun 2016 13:47:39 -0700 Subject: [PATCH 460/751] Backport from Beam: Increase the MESSAGES_POLLING_ATTEMPTS for slow backend starts (#318) This is backport from: https://github.com/apache/incubator-beam/pull/549 --- .../google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java index 6cf25154e8..d3f688e332 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java @@ -99,7 +99,7 @@ public class DataflowPipelineJob implements PipelineResult { /** * The amount of polling attempts for job status and messages information. */ - static final int MESSAGES_POLLING_ATTEMPTS = 10; + static final int MESSAGES_POLLING_ATTEMPTS = 12; static final int STATUS_POLLING_ATTEMPTS = 5; /** From 74f08eacea64f872cd95932e2e7f372862d929d3 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 29 Feb 2016 13:48:09 -0800 Subject: [PATCH 461/751] Add UnboundedCountingInput#withRate The rate controls the speed at which UnboundedCountingInput outputs elements. This is an aggregate rate across all instances of the source, and thus elements will not necessarily be output "smoothly", or within the first period. The aggregate rate, however, will be approximately equal to the provided rate. Add package-private CountingSource#createUnbounded() to expose the UnboundedCountingSource type. Make UnboundedCountingSource package-private. --- .../cloud/dataflow/sdk/io/CountingInput.java | 42 +++++++- .../cloud/dataflow/sdk/io/CountingSource.java | 99 +++++++++++++++++-- .../dataflow/sdk/io/CountingInputTest.java | 24 ++++- .../dataflow/sdk/io/CountingSourceTest.java | 73 ++++++++++++++ 4 files changed, 224 insertions(+), 14 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java index 91e3f13113..c743146e10 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java @@ -90,7 +90,11 @@ public static BoundedCountingInput upTo(long numElements) { */ public static UnboundedCountingInput unbounded() { return new UnboundedCountingInput( - new NowTimestampFn(), Optional.absent(), Optional.absent()); + new NowTimestampFn(), + 1L /* Elements per period */, + Duration.ZERO /* Period length */, + Optional.absent() /* Maximum number of records */, + Optional.absent() /* Maximum read duration */); } /** @@ -133,14 +137,20 @@ public void populateDisplayData(DisplayData.Builder builder) { */ public static class UnboundedCountingInput extends PTransform> { private final SerializableFunction timestampFn; + private final long elementsPerPeriod; + private final Duration period; private final Optional maxNumRecords; private final Optional maxReadTime; private UnboundedCountingInput( SerializableFunction timestampFn, + long elementsPerPeriod, + Duration period, Optional maxNumRecords, Optional maxReadTime) { this.timestampFn = timestampFn; + this.elementsPerPeriod = elementsPerPeriod; + this.period = period; this.maxNumRecords = maxNumRecords; this.maxReadTime = maxReadTime; } @@ -152,7 +162,8 @@ private UnboundedCountingInput( *

            Note that the timestamps produced by {@code timestampFn} may not decrease. */ public UnboundedCountingInput withTimestampFn(SerializableFunction timestampFn) { - return new UnboundedCountingInput(timestampFn, maxNumRecords, maxReadTime); + return new UnboundedCountingInput( + timestampFn, elementsPerPeriod, period, maxNumRecords, maxReadTime); } /** @@ -165,7 +176,23 @@ public UnboundedCountingInput withTimestampFn(SerializableFunction 0, "MaxRecords must be a positive (nonzero) value. Got %s", maxRecords); - return new UnboundedCountingInput(timestampFn, Optional.of(maxRecords), maxReadTime); + return new UnboundedCountingInput( + timestampFn, elementsPerPeriod, period, Optional.of(maxRecords), maxReadTime); + } + + /** + * Returns an {@link UnboundedCountingInput} like this one, but with output production limited + * to an aggregate rate of no more than the number of elements per the period length. + * + *

            Note that when there are multiple splits, each split outputs independently. This may lead + * to elements not being produced evenly across time, though the aggregate rate will still + * approach the specified rate. + * + *

            A duration of {@link Duration#ZERO} will produce output as fast as possible. + */ + public UnboundedCountingInput withRate(long numElements, Duration periodLength) { + return new UnboundedCountingInput( + timestampFn, numElements, periodLength, maxNumRecords, maxReadTime); } /** @@ -177,13 +204,18 @@ public UnboundedCountingInput withMaxNumRecords(long maxRecords) { */ public UnboundedCountingInput withMaxReadTime(Duration readTime) { checkNotNull(readTime, "ReadTime cannot be null"); - return new UnboundedCountingInput(timestampFn, maxNumRecords, Optional.of(readTime)); + return new UnboundedCountingInput( + timestampFn, elementsPerPeriod, period, maxNumRecords, Optional.of(readTime)); } @SuppressWarnings("deprecation") @Override public PCollection apply(PBegin begin) { - Unbounded read = Read.from(CountingSource.unboundedWithTimestampFn(timestampFn)); + Unbounded read = + Read.from( + CountingSource.createUnbounded() + .withTimestampFn(timestampFn) + .withRate(elementsPerPeriod, period)); if (!maxNumRecords.isPresent() && !maxReadTime.isPresent()) { return begin.apply(read); } else if (maxNumRecords.isPresent() && !maxReadTime.isPresent()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java index 8cca7e2179..20568441ed 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.io; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -29,6 +30,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.collect.ImmutableList; +import org.joda.time.Duration; import org.joda.time.Instant; import java.io.IOException; @@ -81,6 +83,14 @@ public static BoundedSource upTo(long numElements) { return new BoundedCountingSource(0, numElements); } + /** + * Create a new {@link UnboundedCountingSource}. + */ + // package-private to return a typed UnboundedCountingSource rather than the UnboundedSource type. + static UnboundedCountingSource createUnbounded() { + return new UnboundedCountingSource(0, 1, 1L, Duration.ZERO, new NowTimestampFn()); + } + /** * Creates an {@link UnboundedSource} that will produce numbers starting from {@code 0} up to * {@link Long#MAX_VALUE}. @@ -113,7 +123,7 @@ public static UnboundedSource unbounded() { @Deprecated public static UnboundedSource unboundedWithTimestampFn( SerializableFunction timestampFn) { - return new UnboundedCountingSource(0, 1, timestampFn); + return new UnboundedCountingSource(0, 1, 1L, Duration.ZERO, timestampFn); } ///////////////////////////////////////////////////////////////////////////////////////////// @@ -231,11 +241,15 @@ public void close() throws IOException {} /** * An implementation of {@link CountingSource} that produces an unbounded {@link PCollection}. */ - private static class UnboundedCountingSource extends UnboundedSource { + static class UnboundedCountingSource extends UnboundedSource { /** The first number (>= 0) generated by this {@link UnboundedCountingSource}. */ private final long start; /** The interval between numbers generated by this {@link UnboundedCountingSource}. */ private final long stride; + /** The number of elements to produce each period. */ + private final long elementsPerPeriod; + /** The time between producing numbers from this {@link UnboundedCountingSource}. */ + private final Duration period; /** The function used to produce timestamps for the generated elements. */ private final SerializableFunction timestampFn; @@ -248,13 +262,45 @@ private static class UnboundedCountingSource extends UnboundedSourceNote that the timestamps produced by {@code timestampFn} may not decrease. */ - public UnboundedCountingSource( - long start, long stride, SerializableFunction timestampFn) { + private UnboundedCountingSource( + long start, + long stride, + long elementsPerPeriod, + Duration period, + SerializableFunction timestampFn) { this.start = start; this.stride = stride; + checkArgument( + elementsPerPeriod > 0L, + "Must produce at least one element per period, got %s", + elementsPerPeriod); + this.elementsPerPeriod = elementsPerPeriod; + checkArgument( + period.getMillis() >= 0L, "Must have a non-negative period length, got %s", period); + this.period = period; this.timestampFn = timestampFn; } + /** + * Returns an {@link UnboundedCountingSource} like this one with the specified period. Elements + * will be produced with an interval between them equal to the period. + */ + public UnboundedCountingSource withRate(long elementsPerPeriod, Duration period) { + return new UnboundedCountingSource(start, stride, elementsPerPeriod, period, timestampFn); + } + + /** + * Returns an {@link UnboundedCountingSource} like this one where the timestamp of output + * elements are supplied by the specified function. + * + *

            Note that timestamps produced by {@code timestampFn} may not decrease. + */ + public UnboundedCountingSource withTimestampFn( + SerializableFunction timestampFn) { + checkNotNull(timestampFn); + return new UnboundedCountingSource(start, stride, elementsPerPeriod, period, timestampFn); + } + /** * Splits an unbounded source {@code desiredNumSplits} ways by giving each split every * {@code desiredNumSplits}th element that this {@link UnboundedCountingSource} @@ -275,7 +321,9 @@ public List> generat for (int i = 0; i < desiredNumSplits; ++i) { // Starts offset by the original stride. Using Javadoc example, this generates starts of // 0, 2, and 4. - splits.add(new UnboundedCountingSource(start + i * stride, newStride, timestampFn)); + splits.add( + new UnboundedCountingSource( + start + i * stride, newStride, elementsPerPeriod, period, timestampFn)); } return splits.build(); } @@ -309,6 +357,7 @@ private static class UnboundedCountingReader extends UnboundedReader { private UnboundedCountingSource source; private long current; private Instant currentTimestamp; + private Instant firstStarted; public UnboundedCountingReader(UnboundedCountingSource source, CounterMark mark) { this.source = source; @@ -318,11 +367,15 @@ public UnboundedCountingReader(UnboundedCountingSource source, CounterMark mark) this.current = source.start - source.stride; } else { this.current = mark.getLastEmitted(); + this.firstStarted = mark.getStartTime(); } } @Override public boolean start() throws IOException { + if (firstStarted == null) { + this.firstStarted = Instant.now(); + } return advance(); } @@ -332,11 +385,25 @@ public boolean advance() throws IOException { if (Long.MAX_VALUE - source.stride < current) { return false; } - current += source.stride; + long nextValue = current + source.stride; + if (expectedValue() < nextValue) { + return false; + } + current = nextValue; currentTimestamp = source.timestampFn.apply(current); return true; } + private long expectedValue() { + if (source.period.getMillis() == 0L) { + return Long.MAX_VALUE; + } + double periodsElapsed = + (Instant.now().getMillis() - firstStarted.getMillis()) + / (double) source.period.getMillis(); + return (long) (source.elementsPerPeriod * periodsElapsed); + } + @Override public Instant getWatermark() { return source.timestampFn.apply(current); @@ -344,7 +411,7 @@ public Instant getWatermark() { @Override public CounterMark getCheckpointMark() { - return new CounterMark(current); + return new CounterMark(current, firstStarted); } @Override @@ -364,6 +431,12 @@ public Instant getCurrentTimestamp() throws NoSuchElementException { @Override public void close() throws IOException {} + + @Override + public long getSplitBacklogBytes() { + long expected = expectedValue(); + return Math.max(0L, 8 * (expected - current) / source.stride); + } } /** @@ -374,12 +447,14 @@ public void close() throws IOException {} public static class CounterMark implements UnboundedSource.CheckpointMark { /** The last value emitted. */ private final long lastEmitted; + private final Instant startTime; /** * Creates a checkpoint mark reflecting the last emitted value. */ - public CounterMark(long lastEmitted) { + public CounterMark(long lastEmitted, Instant startTime) { this.lastEmitted = lastEmitted; + this.startTime = startTime; } /** @@ -389,11 +464,19 @@ public long getLastEmitted() { return lastEmitted; } + /** + * Returns the time the reader was started. + */ + public Instant getStartTime() { + return startTime; + } + ///////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") // For AvroCoder private CounterMark() { this.lastEmitted = 0L; + this.startTime = Instant.now(); } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java index d06688a29c..529536e7a5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java @@ -19,7 +19,8 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.CountingInput.UnboundedCountingInput; @@ -96,6 +97,27 @@ public void testUnboundedInput() { p.run(); } + @Test + public void testUnboundedInputRate() { + Pipeline p = TestPipeline.create(); + long numElements = 5000; + + long elemsPerPeriod = 10L; + Duration periodLength = Duration.millis(8); + PCollection input = + p.apply( + CountingInput.unbounded() + .withRate(elemsPerPeriod, periodLength) + .withMaxNumRecords(numElements)); + + addCountingAsserts(input, numElements); + long expectedRuntimeMillis = (periodLength.getMillis() * numElements) / elemsPerPeriod; + Instant startTime = Instant.now(); + p.run(); + Instant endTime = Instant.now(); + assertThat(endTime.isAfter(startTime.plus(expectedRuntimeMillis)), is(true)); + } + private static class ElementValueDiff extends DoFn { @Override public void processElement(ProcessContext c) throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java index cc01cc8576..3051535d5d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java @@ -16,12 +16,16 @@ package com.google.cloud.dataflow.sdk.io; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.CountingSource.CounterMark; +import com.google.cloud.dataflow.sdk.io.CountingSource.UnboundedCountingSource; import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; @@ -39,6 +43,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionList; +import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -179,6 +184,40 @@ public void testUnboundedSourceTimestamps() { p.run(); } + @Test + public void testUnboundedSourceWithRate() { + Pipeline p = TestPipeline.create(); + + Duration period = Duration.millis(5); + long numElements = 1000L; + + PCollection input = + p.apply( + Read.from( + CountingSource.createUnbounded() + .withTimestampFn(new ValueAsTimestampFn()) + .withRate(1, period)) + .withMaxNumRecords(numElements)); + addCountingAsserts(input, numElements); + + PCollection diffs = + input + .apply("TimestampDiff", ParDo.of(new ElementValueDiff())) + .apply("RemoveDuplicateTimestamps", RemoveDuplicates.create()); + // This assert also confirms that diffs only has one unique value. + DataflowAssert.thatSingleton(diffs).isEqualTo(0L); + + Instant started = Instant.now(); + p.run(); + Instant finished = Instant.now(); + Duration expectedDuration = period.multipliedBy((int) numElements); + assertThat( + started + .plus(expectedDuration) + .isBefore(finished), + is(true)); + } + @Test @Category(RunnableOnService.class) public void testUnboundedSourceSplits() throws Exception { @@ -204,6 +243,40 @@ public void testUnboundedSourceSplits() throws Exception { p.run(); } + @Test + public void testUnboundedSourceRateSplits() throws Exception { + Pipeline p = TestPipeline.create(); + int elementsPerPeriod = 10; + Duration period = Duration.millis(5); + + long numElements = 1000; + int numSplits = 10; + + UnboundedCountingSource initial = + CountingSource.createUnbounded().withRate(elementsPerPeriod, period); + List> splits = + initial.generateInitialSplits(numSplits, p.getOptions()); + assertEquals("Expected exact splitting", numSplits, splits.size()); + + long elementsPerSplit = numElements / numSplits; + assertEquals("Expected even splits", numElements, elementsPerSplit * numSplits); + PCollectionList pcollections = PCollectionList.empty(p); + for (int i = 0; i < splits.size(); ++i) { + pcollections = + pcollections.and( + p.apply("split" + i, Read.from(splits.get(i)).withMaxNumRecords(elementsPerSplit))); + } + PCollection input = pcollections.apply(Flatten.pCollections()); + + addCountingAsserts(input, numElements); + Instant startTime = Instant.now(); + p.run(); + Instant endTime = Instant.now(); + // 500 ms if the readers are all initialized in parallel; 5000 ms if they are evaluated serially + long expectedMinimumMillis = (numElements * period.getMillis()) / elementsPerPeriod; + assertThat(expectedMinimumMillis, lessThan(endTime.getMillis() - startTime.getMillis())); + } + /** * A timestamp function that uses the given value as the timestamp. Because the input values will * not wrap, this function is non-decreasing and meets the timestamp function criteria laid out From 84584dcba30651ef41c6f040ce8fd8182e617d67 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 29 Jun 2016 15:38:08 -0500 Subject: [PATCH 462/751] Fix AutoComplete example streaming configuration (#308) (cherry picked from commit e60e3e6de85a022d4669333c544b0b86145d0d55) --- .../cloud/dataflow/examples/complete/AutoComplete.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java index f897338889..4c6c9f82e5 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java @@ -38,6 +38,7 @@ import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.options.Validation; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -415,6 +416,7 @@ public void processElement(ProcessContext c) { */ private static interface Options extends ExamplePubsubTopicOptions, ExampleBigQueryTableOptions { @Description("Input text file") + @Validation.Required String getInputFile(); void setInputFile(String value); @@ -499,7 +501,9 @@ public static void main(String[] args) throws IOException { .to(tableRef) .withSchema(FormatForBigquery.getSchema()) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); + .withWriteDisposition(options.isStreaming() + ? BigQueryIO.Write.WriteDisposition.WRITE_APPEND + : BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); } // Run the pipeline. From a82c15816bced7caf54822f22a3131a88cd70924 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Wed, 29 Jun 2016 14:09:35 -0700 Subject: [PATCH 463/751] Configure the Surefire Argline in Travis (#320) --- .travis.yml | 6 +++--- pom.xml | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 096e5ad42a..2f5ed182c5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,11 +18,11 @@ matrix: env: MAVEN_OVERRIDE="" # On Linux, run with specific JDKs only. - os: linux - env: CUSTOM_JDK="oraclejdk8" MAVEN_OVERRIDE="-DforkCount=0" + env: CUSTOM_JDK="oraclejdk8" MAVEN_OVERRIDE="-Ddataflow.surefire_argline='-Xmx512m'" - os: linux - env: CUSTOM_JDK="oraclejdk7" MAVEN_OVERRIDE="-DforkCount=0" + env: CUSTOM_JDK="oraclejdk7" MAVEN_OVERRIDE="-Ddataflow.surefire_argline='-Xmx512m'" - os: linux - env: CUSTOM_JDK="openjdk7" MAVEN_OVERRIDE="-DforkCount=0" + env: CUSTOM_JDK="openjdk7" MAVEN_OVERRIDE="-Ddataflow.surefire_argline='-Xmx512m'" before_install: - if [ "$TRAVIS_OS_NAME" == "osx" ]; then export JAVA_HOME=$(/usr/libexec/java_home); fi diff --git a/pom.xml b/pom.xml index 192c81a288..1133b4e46d 100644 --- a/pom.xml +++ b/pom.xml @@ -65,6 +65,7 @@ UTF-8 + 1.7.7 @@ -233,6 +234,7 @@ false false true + ${dataflow.surefire_argline} From 9b12258222721c113833606753ae92ef89e6decf Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 30 Jun 2016 17:42:35 -0700 Subject: [PATCH 464/751] Backport: Make IdentityWindowFn and NeverTrigger available (#315) * Make IdentityWindowFn and NeverTrigger available This will be used as part of the new PAssert IdentityWindowFn remains package-private to restrict usage. (cherry picked from commit c9a1efae25455af1e47675938e296c716ec0fa0f) * fixup! Checkstyle validation --- .../transforms/windowing/AfterWatermark.java | 43 +------ .../sdk/transforms/windowing/Never.java | 73 ++++++++++++ .../dataflow/sdk/util/IdentityWindowFn.java | 109 ++++++++++++++++++ .../cloud/dataflow/sdk/util/Reshuffle.java | 79 ++----------- .../sdk/transforms/windowing/NeverTest.java | 54 +++++++++ 5 files changed, 247 insertions(+), 111 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index 4f66b92b07..5d6e179417 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -100,43 +100,6 @@ public interface AfterWatermarkLate extends TriggerBuil TriggerBuilder withEarlyFirings(OnceTrigger earlyTrigger); } - /** - * A trigger which never fires. Used for the "early" trigger when only a late trigger was - * specified. - */ - static class NeverTrigger extends OnceTrigger { - - protected NeverTrigger() { - super(null); - } - - @Override - public void onElement(OnElementContext c) throws Exception { } - - @Override - public void onMerge(OnMergeContext c) throws Exception { } - - @Override - protected Trigger getContinuationTrigger(List> continuationTriggers) { - return this; - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return false; - } - - @Override - protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { - throw new UnsupportedOperationException( - String.format("%s should never fire", getClass().getSimpleName())); - } - } private static class AfterWatermarkEarlyAndLate extends Trigger @@ -267,14 +230,14 @@ public void onFire(Trigger.TriggerContext context) throws Exception { public String toString() { StringBuilder builder = new StringBuilder(TO_STRING); - if (!(earlyTrigger instanceof NeverTrigger)) { + if (!(earlyTrigger instanceof Never.NeverTrigger)) { builder .append(".withEarlyFirings(") .append(earlyTrigger) .append(")"); } - if (lateTrigger != null && !(lateTrigger instanceof NeverTrigger)) { + if (lateTrigger != null && !(lateTrigger instanceof Never.NeverTrigger)) { builder .append(".withLateFirings(") .append(lateTrigger) @@ -352,7 +315,7 @@ public AfterWatermarkEarly withEarlyFirings(OnceTrigger earlyFirings) { public AfterWatermarkLate withLateFirings(OnceTrigger lateFirings) { Preconditions.checkNotNull(lateFirings, "Must specify the trigger to use for late firings"); - return new AfterWatermarkEarlyAndLate(new NeverTrigger(), lateFirings); + return new AfterWatermarkEarlyAndLate(Never.ever(), lateFirings); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java new file mode 100644 index 0000000000..9fa8498220 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; + +import org.joda.time.Instant; + +import java.util.List; + +/** + * A trigger which never fires. + * + *

            + * Using this trigger will only produce output when the watermark passes the end of the + * {@link BoundedWindow window} plus the {@link Window#withAllowedLateness() allowed + * lateness}. + */ +public final class Never { + /** + * Returns a trigger which never fires. Output will be produced from the using {@link GroupByKey} + * when the {@link BoundedWindow} closes. + */ + public static Trigger.OnceTrigger ever() { + // NeverTrigger ignores all inputs and is Window-type independent. + return new NeverTrigger(); + } + + static class NeverTrigger extends Trigger.OnceTrigger { + protected NeverTrigger() { + super(null); + } + + @Override + public void onElement(OnElementContext c) {} + + @Override + public void onMerge(OnMergeContext c) {} + + @Override + protected Trigger getContinuationTrigger(List> continuationTriggers) { + return this; + } + + @Override + public Instant getWatermarkThatGuaranteesFiring(BoundedWindow window) { + return BoundedWindow.TIMESTAMP_MAX_VALUE; + } + + @Override + public boolean shouldFire(Trigger.TriggerContext context) { + return false; + } + + @Override + protected void onOnlyFiring(Trigger.TriggerContext context) { + throw new UnsupportedOperationException( + String.format("%s should never fire", getClass().getSimpleName())); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java new file mode 100644 index 0000000000..757b0963c8 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.NonMergingWindowFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import org.joda.time.Instant; + +import java.util.Collection; + +/** + * A {@link WindowFn} that leaves all associations between elements and windows unchanged. + * + *

            This {@link WindowFn} is applied when elements must be passed through a {@link GroupByKey}, + * but should maintain their existing {@link Window} assignments. Because windows may have been + * merged, the earlier {@link WindowFn} may not appropriately maintain the existing window + * assignments. For example, if the earlier {@link WindowFn} merges windows, after a + * {@link GroupByKey} the {@link WindowingStrategy} uses {@link InvalidWindows}, and no further + * {@link GroupByKey} can be applied without applying a new {@link WindowFn}. This {@link WindowFn} + * allows existing window assignments to be maintained across a single group by key, at which point + * the earlier {@link WindowingStrategy} should be restored. + * + *

            This {@link WindowFn} is an internal implementation detail of sdk-provided utilities, and + * should not be used by {@link Pipeline} writers. + */ +class IdentityWindowFn extends NonMergingWindowFn { + + /** + * The coder of the type of windows of the input {@link PCollection}. This is not an arbitrary + * {@link BoundedWindow} {@link Coder}, but is safe to use for all windows assigned by this + * transform, as it should be the same coder used by the {@link WindowFn} that initially assigned + * these windows. + */ + private final Coder coder; + private final boolean assignsToSingleWindow; + + public IdentityWindowFn(Coder coder, boolean assignsToSingleWindow) { + // Safe because it is only used privately here. + // At every point where a window is returned or accepted, it has been provided + // by priorWindowFn, so it is of the expected type. + @SuppressWarnings("unchecked") + Coder windowCoder = (Coder) coder; + this.coder = windowCoder; + this.assignsToSingleWindow = assignsToSingleWindow; + } + + @Override + public Collection assignWindows(WindowFn.AssignContext c) + throws Exception { + // The windows are provided by priorWindowFn, which also provides the coder for them + @SuppressWarnings("unchecked") + Collection priorWindows = (Collection) c.windows(); + return priorWindows; + } + + @Override + public boolean isCompatible(WindowFn other) { + throw new UnsupportedOperationException( + String.format( + "%s.isCompatible() should never be called." + + " It is a private implementation detail of sdk utilities." + + " This message indicates a bug in the Beam SDK.", + getClass().getCanonicalName())); + } + + @Override + public Coder windowCoder() { + // Safe because the previous WindowFn provides both the windows and the coder. + // The Coder is _not_ actually a coder for an arbitrary BoundedWindow. + return coder; + } + + @Override + public boolean assignsToSingleWindow() { + return assignsToSingleWindow; + } + + @Override + public BoundedWindow getSideInputWindow(BoundedWindow window) { + throw new UnsupportedOperationException( + String.format( + "%s.getSideInputWindow() should never be called." + + " It is a private implementation detail of sdk utilities." + + " This message indicates a bug in the Beam SDK.", + getClass().getCanonicalName())); + } + + @Deprecated + @Override + public Instant getOutputTime(Instant inputTimestamp, BoundedWindow window) { + return inputTimestamp; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java index 367db2dc5b..040801d308 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java @@ -15,22 +15,16 @@ */ package com.google.cloud.dataflow.sdk.util; -import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.NonMergingWindowFn; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.Collection; /** * A {@link PTransform} that returns a {@link PCollection} equivalent to its input but operationally @@ -60,11 +54,14 @@ public PCollection> apply(PCollection> input) { // If the input has already had its windows merged, then the GBK that performed the merge // will have set originalStrategy.getWindowFn() to InvalidWindows, causing the GBK contained // here to fail. Instead, we install a valid WindowFn that leaves all windows unchanged. - Window.Bound> rewindow = Window - .>into(new PassThroughWindowFn<>(originalStrategy.getWindowFn())) - .triggering(new ReshuffleTrigger<>()) - .discardingFiredPanes() - .withAllowedLateness(Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis())); + Window.Bound> rewindow = + Window.>into( + new IdentityWindowFn<>( + originalStrategy.getWindowFn().windowCoder(), + originalStrategy.getWindowFn().assignsToSingleWindow())) + .triggering(new ReshuffleTrigger<>()) + .discardingFiredPanes() + .withAllowedLateness(Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis())); return input.apply(rewindow) .apply(GroupByKey.create()) @@ -82,64 +79,4 @@ public void processElement(ProcessContext c) { } })); } - - /** - * A {@link WindowFn} that leaves all associations between elements and windows unchanged. - * - *

            In order to implement all the abstract methods of {@link WindowFn}, this requires the - * prior {@link WindowFn}, to which all auxiliary functionality is delegated. - */ - private static class PassThroughWindowFn extends NonMergingWindowFn { - - /** The WindowFn prior to this. Used for its windowCoder, etc. */ - private final WindowFn priorWindowFn; - - public PassThroughWindowFn(WindowFn priorWindowFn) { - // Safe because it is only used privately here. - // At every point where a window is returned or accepted, it has been provided - // by priorWindowFn, so it is of the type expected. - @SuppressWarnings("unchecked") - WindowFn internalWindowFn = (WindowFn) priorWindowFn; - this.priorWindowFn = internalWindowFn; - } - - @Override - public Collection assignWindows(WindowFn.AssignContext c) - throws Exception { - // The windows are provided by priorWindowFn, which also provides the coder for them - @SuppressWarnings("unchecked") - Collection priorWindows = (Collection) c.windows(); - return priorWindows; - } - - @Override - public boolean isCompatible(WindowFn other) { - throw new UnsupportedOperationException( - String.format("%s.isCompatible() should never be called." - + " It is a private implementation detail of Reshuffle." - + " This message indicates a bug in the Dataflow SDK.", - getClass().getCanonicalName())); - } - - @Override - public Coder windowCoder() { - // Safe because priorWindowFn provides the windows also. - // The Coder is _not_ actually a coder for an arbitrary BoundedWindow. - return priorWindowFn.windowCoder(); - } - - @Override - public BoundedWindow getSideInputWindow(BoundedWindow window) { - throw new UnsupportedOperationException( - String.format("%s.getSideInputWindow() should never be called." - + " It is a private implementation detail of Reshuffle." - + " This message indicates a bug in the Dataflow SDK.", - getClass().getCanonicalName())); - } - - @Override - public Instant getOutputTime(Instant inputTimestamp, BoundedWindow window) { - return inputTimestamp; - } - } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java new file mode 100644 index 0000000000..02bcff9fe0 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.util.TriggerTester; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link Never}. + */ +@RunWith(JUnit4.class) +public class NeverTest { + private TriggerTester.SimpleTriggerTester triggerTester; + + @Before + public void setup() throws Exception { + triggerTester = + TriggerTester.forTrigger( + Never.ever(), FixedWindows.of(Duration.standardMinutes(5))); + } + + @Test + public void falseAfterEndOfWindow() throws Exception { + triggerTester.injectElements(TimestampedValue.of(1, new Instant(1))); + IntervalWindow window = + new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardMinutes(5))); + assertThat(triggerTester.shouldFire(window), is(false)); + triggerTester.advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE); + assertThat(triggerTester.shouldFire(window), is(false)); + } +} From c22ebdb524a01bc3ead577428c02c18eb8384091 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Fri, 1 Jul 2016 20:02:11 -0700 Subject: [PATCH 465/751] Modified range tracker to use first response seen as start key (#322) --- .../dataflow/sdk/io/bigtable/BigtableIO.java | 5 +- .../sdk/io/range/ByteKeyRangeTracker.java | 8 ++ .../sdk/io/bigtable/BigtableIOTest.java | 2 - .../sdk/io/range/ByteKeyRangeTrackerTest.java | 84 +++++++++++++------ 4 files changed, 70 insertions(+), 29 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index bf66c6c52a..05e1563d97 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -809,9 +809,10 @@ public final Double getFractionConsumed() { public final synchronized BigtableSource splitAtFraction(double fraction) { ByteKey splitKey; try { - splitKey = source.getRange().interpolateKey(fraction); + splitKey = rangeTracker.getRange().interpolateKey(fraction); } catch (IllegalArgumentException e) { - logger.info("%s: Failed to interpolate key for fraction %s.", source.getRange(), fraction); + logger.info( + "%s: Failed to interpolate key for fraction %s.", rangeTracker.getRange(), fraction); return null; } logger.debug( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java index f6796cc5af..9c1c571f2a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java @@ -47,11 +47,19 @@ public synchronized ByteKey getStopPosition() { return range.getEndKey(); } + /** Returns the current range. */ + public synchronized ByteKeyRange getRange() { + return range; + } + @Override public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, ByteKey recordStart) { if (isAtSplitPoint && !range.containsKey(recordStart)) { return false; } + if (position == null) { + range = range.withStartKey(recordStart); + } position = recordStart; return true; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java index ebe53c90b3..064101f0b7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -62,7 +62,6 @@ import org.hamcrest.Matchers; import org.junit.Before; -import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -291,7 +290,6 @@ public boolean apply(@Nullable Row input) { *

            Because this test runs so slowly, it is disabled by default. Re-run when changing the * {@link BigtableIO.Read} implementation. */ - @Ignore("Slow. Rerun when changing the implementation.") @Test public void testReadingSplitAtFractionExhaustive() throws Exception { final String table = "TEST-FEW-ROWS-SPLIT-EXHAUSTIVE-TABLE"; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java index 234e6e9d95..0200b565d9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java @@ -26,66 +26,100 @@ /** Tests for {@link ByteKeyRangeTracker}. */ @RunWith(JUnit4.class) public class ByteKeyRangeTrackerTest { - private static final ByteKey START_KEY = ByteKey.of(0x12); - private static final ByteKey MIDDLE_KEY = ByteKey.of(0x23); + private static final ByteKey INITIAL_START_KEY = ByteKey.of(0x12); + private static final ByteKey INITIAL_MIDDLE_KEY = ByteKey.of(0x23); + private static final ByteKey NEW_START_KEY = ByteKey.of(0x14); + private static final ByteKey NEW_MIDDLE_KEY = ByteKey.of(0x24); private static final ByteKey BEFORE_END_KEY = ByteKey.of(0x33); private static final ByteKey END_KEY = ByteKey.of(0x34); - private static final double RANGE_SIZE = 0x34 - 0x12; - private static final ByteKeyRange RANGE = ByteKeyRange.of(START_KEY, END_KEY); + private static final double INITIAL_RANGE_SIZE = 0x34 - 0x12; + private static final ByteKeyRange INITIAL_RANGE = ByteKeyRange.of(INITIAL_START_KEY, END_KEY); + private static final double NEW_RANGE_SIZE = 0x34 - 0x14; + private static final ByteKeyRange NEW_RANGE = ByteKeyRange.of(NEW_START_KEY, END_KEY); /** Tests for {@link ByteKeyRangeTracker#toString}. */ @Test public void testToString() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); - String expected = String.format("ByteKeyRangeTracker{range=%s, position=null}", RANGE); + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); + String expected = String.format("ByteKeyRangeTracker{range=%s, position=null}", INITIAL_RANGE); assertEquals(expected, tracker.toString()); - tracker.tryReturnRecordAt(true, MIDDLE_KEY); - expected = String.format("ByteKeyRangeTracker{range=%s, position=%s}", RANGE, MIDDLE_KEY); + tracker.tryReturnRecordAt(true, INITIAL_START_KEY); + tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY); + expected = + String.format("ByteKeyRangeTracker{range=%s, position=%s}", INITIAL_RANGE, + INITIAL_MIDDLE_KEY); + assertEquals(expected, tracker.toString()); + } + + /** Tests for updating the start key to the first record returned. */ + @Test + public void testUpdateStartKey() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); + + tracker.tryReturnRecordAt(true, NEW_START_KEY); + String expected = + String.format("ByteKeyRangeTracker{range=%s, position=%s}", NEW_RANGE, NEW_START_KEY); assertEquals(expected, tracker.toString()); } /** Tests for {@link ByteKeyRangeTracker#of}. */ @Test public void testBuilding() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - assertEquals(START_KEY, tracker.getStartPosition()); + assertEquals(INITIAL_START_KEY, tracker.getStartPosition()); assertEquals(END_KEY, tracker.getStopPosition()); } /** Tests for {@link ByteKeyRangeTracker#getFractionConsumed()}. */ @Test public void testGetFractionConsumed() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); double delta = 0.00001; assertEquals(0.0, tracker.getFractionConsumed(), delta); - tracker.tryReturnRecordAt(true, START_KEY); + tracker.tryReturnRecordAt(true, INITIAL_START_KEY); + assertEquals(0.0, tracker.getFractionConsumed(), delta); + + tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY); + assertEquals(0.5, tracker.getFractionConsumed(), delta); + + tracker.tryReturnRecordAt(true, BEFORE_END_KEY); + assertEquals(1 - 1 / INITIAL_RANGE_SIZE, tracker.getFractionConsumed(), delta); + } + + /** Tests for {@link ByteKeyRangeTracker#getFractionConsumed()} with updated start key. */ + @Test + public void testGetFractionConsumedUpdateStartKey() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); + double delta = 0.00001; + + tracker.tryReturnRecordAt(true, NEW_START_KEY); assertEquals(0.0, tracker.getFractionConsumed(), delta); - tracker.tryReturnRecordAt(true, MIDDLE_KEY); + tracker.tryReturnRecordAt(true, NEW_MIDDLE_KEY); assertEquals(0.5, tracker.getFractionConsumed(), delta); tracker.tryReturnRecordAt(true, BEFORE_END_KEY); - assertEquals(1 - 1 / RANGE_SIZE, tracker.getFractionConsumed(), delta); + assertEquals(1 - 1 / NEW_RANGE_SIZE, tracker.getFractionConsumed(), delta); } /** Tests for {@link ByteKeyRangeTracker#tryReturnRecordAt}. */ @Test public void testTryReturnRecordAt() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); // Should be able to emit at the same key twice, should that happen. // Should be able to emit within range (in order, but system guarantees won't try out of order). // Should not be able to emit past end of range. - assertTrue(tracker.tryReturnRecordAt(true, START_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, START_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); assertTrue(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); @@ -97,13 +131,13 @@ public void testTryReturnRecordAt() { /** Tests for {@link ByteKeyRangeTracker#trySplitAtPosition}. */ @Test public void testSplitAtPosition() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(RANGE); + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); // Unstarted, should not split. - assertFalse(tracker.trySplitAtPosition(MIDDLE_KEY)); + assertFalse(tracker.trySplitAtPosition(INITIAL_MIDDLE_KEY)); // Start it, split it before the end. - assertTrue(tracker.tryReturnRecordAt(true, START_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); assertTrue(tracker.trySplitAtPosition(BEFORE_END_KEY)); assertEquals(BEFORE_END_KEY, tracker.getStopPosition()); @@ -111,8 +145,8 @@ public void testSplitAtPosition() { assertFalse(tracker.trySplitAtPosition(END_KEY)); // Should not be able to split after emitting. - assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); - assertFalse(tracker.trySplitAtPosition(MIDDLE_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, MIDDLE_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); + assertFalse(tracker.trySplitAtPosition(INITIAL_MIDDLE_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); } } From d827645423dd18ac8bee0d4bb2b2402301d65223 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Fri, 1 Jul 2016 20:02:59 -0700 Subject: [PATCH 466/751] Update OffsetRangeTracker progress tracking and start offset (#323) --- .../sdk/io/range/OffsetRangeTracker.java | 13 ++- .../sdk/io/OffsetBasedSourceTest.java | 5 +- .../sdk/io/bigtable/BigtableIOTest.java | 3 - .../sdk/io/range/OffsetRangeTrackerTest.java | 91 +++++++++++++++---- 4 files changed, 82 insertions(+), 30 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java index 20183c5240..71ba908ff1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java @@ -31,7 +31,7 @@ public class OffsetRangeTracker implements RangeTracker { private static final Logger LOG = LoggerFactory.getLogger(OffsetRangeTracker.class); - private final long startOffset; + private long startOffset; private long stopOffset; private long lastRecordStart = -1L; private long offsetOfLastSplitPoint = -1L; @@ -100,6 +100,9 @@ public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, long recor lastRecordStart)); } + if (lastRecordStart == -1) { + startOffset = recordStart; + } lastRecordStart = recordStart; if (isAtSplitPoint) { @@ -164,7 +167,7 @@ public synchronized long getPositionForFractionConsumed(double fraction) { throw new IllegalArgumentException( "getPositionForFractionConsumed is not applicable to an unbounded range: " + this); } - return (long) Math.ceil(startOffset + fraction * (stopOffset - startOffset)); + return (long) Math.floor(startOffset + fraction * (stopOffset - startOffset)); } @Override @@ -178,11 +181,11 @@ public synchronized double getFractionConsumed() { } else if (lastRecordStart >= stopOffset) { return 1.0; } else { - // E.g., when reading [3, 6) and lastRecordStart is 4, that means we consumed 3,4 of 3,4,5 - // which is (4 - 3 + 1) / (6 - 3) = 67%. + // E.g., when reading [3, 6) and lastRecordStart is 4, that means we consumed 3 of 3,4,5 + // which is (4 - 3) / (6 - 3) = 33%. // Also, clamp to at most 1.0 because the last consumed position can extend past the // stop position. - return Math.min(1.0, 1.0 * (lastRecordStart - startOffset + 1) / (stopOffset - startOffset)); + return Math.min(1.0, 1.0 * (lastRecordStart - startOffset) / (stopOffset - startOffset)); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java index 07f0d80099..1b3f8f3744 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java @@ -215,13 +215,14 @@ public void testReadingGranularityAndFractionConsumed() throws IOException { assertEquals(0.0, reader.getFractionConsumed(), 1e-6); assertTrue(reader.start()); - do { + items.add(reader.getCurrent()); + while (reader.advance()) { Double fraction = reader.getFractionConsumed(); assertNotNull(fraction); assertTrue(fraction.toString(), fraction > 0.0); assertTrue(fraction.toString(), fraction <= 1.0); items.add(reader.getCurrent()); - } while (reader.advance()); + } assertEquals(1.0, reader.getFractionConsumed(), 1e-6); assertEquals(20, items.size()); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java index 064101f0b7..27c9d8703f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -286,9 +286,6 @@ public boolean apply(@Nullable Row input) { /** * Tests dynamic work rebalancing exhaustively. - * - *

            Because this test runs so slowly, it is disabled by default. Re-run when changing the - * {@link BigtableIO.Read} implementation. */ @Test public void testReadingSplitAtFractionExhaustive() throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java index cc0a3c2047..acf14f23e1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java @@ -34,6 +34,17 @@ public class OffsetRangeTrackerTest { @Rule public final ExpectedException expected = ExpectedException.none(); + @Test + public void testUpdateStartOffset() throws Exception { + OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); + assertEquals(100, tracker.getStartPosition().longValue()); + // Update start offset to first record returned + assertTrue(tracker.tryReturnRecordAt(true, 150)); + assertEquals(150, tracker.getStartPosition().longValue()); + assertTrue(tracker.tryReturnRecordAt(true, 180)); + assertEquals(150, tracker.getStartPosition().longValue()); + } + @Test public void testTryReturnRecordSimpleSparse() throws Exception { OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); @@ -112,28 +123,48 @@ public void testSplitAtOffset() throws Exception { public void testGetPositionForFractionDense() throws Exception { // Represents positions 3, 4, 5. OffsetRangeTracker tracker = new OffsetRangeTracker(3, 6); - // [3, 3) represents 0.0 of [3, 6) + // [3, 3) represents from [0, 1/3) fraction of [3, 6) assertEquals(3, tracker.getPositionForFractionConsumed(0.0)); - // [3, 4) represents up to 1/3 of [3, 6) - assertEquals(4, tracker.getPositionForFractionConsumed(1.0 / 6)); - assertEquals(4, tracker.getPositionForFractionConsumed(0.333)); - // [3, 5) represents up to 2/3 of [3, 6) - assertEquals(5, tracker.getPositionForFractionConsumed(0.334)); - assertEquals(5, tracker.getPositionForFractionConsumed(0.666)); - // any fraction consumed over 2/3 means the whole [3, 6) has been consumed. - assertEquals(6, tracker.getPositionForFractionConsumed(0.667)); + assertEquals(3, tracker.getPositionForFractionConsumed(1.0 / 6)); + assertEquals(3, tracker.getPositionForFractionConsumed(0.333)); + // [3, 4) represents from [0, 2/3) fraction of [3, 6) + assertEquals(4, tracker.getPositionForFractionConsumed(0.334)); + assertEquals(4, tracker.getPositionForFractionConsumed(0.666)); + // [3, 5) represents from [0, 1) fraction of [3, 6) + assertEquals(5, tracker.getPositionForFractionConsumed(0.667)); + assertEquals(5, tracker.getPositionForFractionConsumed(0.999)); + // The whole [3, 6) is consumed for fraction 1 + assertEquals(6, tracker.getPositionForFractionConsumed(1.0)); + } + + @Test + public void testGetPositionForFractionDenseUpdateStartOffset() throws Exception { + // Represents positions 3, 4, 5. + OffsetRangeTracker tracker = new OffsetRangeTracker(3, 6); + // [3, 3) represents from [0, 1/3) fraction of [3, 6) + assertEquals(3, tracker.getPositionForFractionConsumed(0.333)); + // Update start offset to 4 + assertTrue(tracker.tryReturnRecordAt(true, 4)); + // [4, 4) represents from [0, 1/2) fraction of [4, 6) + assertEquals(4, tracker.getPositionForFractionConsumed(0.0)); + assertEquals(4, tracker.getPositionForFractionConsumed(0.499)); + // [4, 5) represents from [0, 1) fraction of [4, 6) + assertEquals(5, tracker.getPositionForFractionConsumed(0.5)); + assertEquals(5, tracker.getPositionForFractionConsumed(0.999)); + // The whole [4, 6) is consumed for fraction 1 + assertEquals(6, tracker.getPositionForFractionConsumed(1.0)); } @Test public void testGetFractionConsumedDense() throws Exception { OffsetRangeTracker tracker = new OffsetRangeTracker(3, 6); - assertEquals(0, tracker.getFractionConsumed(), 1e-6); + assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); assertTrue(tracker.tryReturnRecordAt(true, 3)); - assertEquals(1.0 / 3, tracker.getFractionConsumed(), 1e-6); + assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); assertTrue(tracker.tryReturnRecordAt(true, 4)); - assertEquals(2.0 / 3, tracker.getFractionConsumed(), 1e-6); + assertEquals(1.0 / 3, tracker.getFractionConsumed(), 1e-6); assertTrue(tracker.tryReturnRecordAt(true, 5)); - assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); + assertEquals(2.0 / 3, tracker.getFractionConsumed(), 1e-6); assertTrue(tracker.tryReturnRecordAt(false /* non-split-point */, 6)); assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); assertTrue(tracker.tryReturnRecordAt(false /* non-split-point */, 7)); @@ -144,14 +175,33 @@ public void testGetFractionConsumedDense() throws Exception { @Test public void testGetFractionConsumedSparse() throws Exception { OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - assertEquals(0, tracker.getFractionConsumed(), 1e-6); + assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); + assertTrue(tracker.tryReturnRecordAt(true, 100)); + assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); assertTrue(tracker.tryReturnRecordAt(true, 110)); - // Consumed positions through 110 = total 11 positions of 100. - assertEquals(0.11, tracker.getFractionConsumed(), 1e-6); + // Consumed positions through 109 = total 10 positions of 100. + assertEquals(0.1, tracker.getFractionConsumed(), 1e-6); + assertTrue(tracker.tryReturnRecordAt(true, 150)); + assertEquals(0.5, tracker.getFractionConsumed(), 1e-6); + assertTrue(tracker.tryReturnRecordAt(true, 195)); + assertEquals(0.95, tracker.getFractionConsumed(), 1e-6); + assertFalse(tracker.tryReturnRecordAt(true, 200)); + assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); + } + + @Test + public void testGetFractionConsumedUpdateStartOffset() throws Exception { + OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); assertTrue(tracker.tryReturnRecordAt(true, 150)); - assertEquals(0.51, tracker.getFractionConsumed(), 1e-6); + assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); + assertTrue(tracker.tryReturnRecordAt(true, 160)); + assertEquals(0.2, tracker.getFractionConsumed(), 1e-6); + assertTrue(tracker.tryReturnRecordAt(true, 180)); + assertEquals(0.6, tracker.getFractionConsumed(), 1e-6); assertTrue(tracker.tryReturnRecordAt(true, 195)); - assertEquals(0.96, tracker.getFractionConsumed(), 1e-6); + assertEquals(0.9, tracker.getFractionConsumed(), 1e-6); + assertFalse(tracker.tryReturnRecordAt(true, 200)); + assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); } @Test @@ -171,15 +221,16 @@ public void testEverythingWithUnboundedRange() throws Exception { @Test public void testTryReturnFirstRecordNotSplitPoint() throws Exception { + OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); expected.expect(IllegalStateException.class); - new OffsetRangeTracker(100, 200).tryReturnRecordAt(false, 120); + tracker.tryReturnRecordAt(false, 120); } @Test public void testTryReturnRecordNonMonotonic() throws Exception { OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - expected.expect(IllegalStateException.class); tracker.tryReturnRecordAt(true, 120); + expected.expect(IllegalStateException.class); tracker.tryReturnRecordAt(true, 110); } } From e02090187cf1c8d6cf600cbb032c7c79e0c2d482 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Thu, 9 Jun 2016 14:17:14 -0700 Subject: [PATCH 467/751] Added getSplitPointsConsumed() to ByteKeyRangeTracker --- .../sdk/io/range/ByteKeyRangeTracker.java | 63 ++++++++++++++++++- .../sdk/io/range/ByteKeyRangeTrackerTest.java | 58 ++++++++++++++++- 2 files changed, 118 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java index 9c1c571f2a..ca97e4fd1c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java @@ -17,6 +17,9 @@ package com.google.cloud.dataflow.sdk.io.range; import static com.google.common.base.MoreObjects.toStringHelper; +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,6 +40,10 @@ public static ByteKeyRangeTracker of(ByteKeyRange range) { return new ByteKeyRangeTracker(range); } + public synchronized boolean isDone() { + return done; + } + @Override public synchronized ByteKey getStartPosition() { return range.getStartKey(); @@ -54,13 +61,28 @@ public synchronized ByteKeyRange getRange() { @Override public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, ByteKey recordStart) { - if (isAtSplitPoint && !range.containsKey(recordStart)) { + if (done) { return false; } + + checkState(!(position == null && !isAtSplitPoint), "The first record must be at a split point"); + checkState(!(recordStart.compareTo(range.getStartKey()) < 0), + "Trying to return record which is before the start key"); + checkState(!(position != null && recordStart.compareTo(position) < 0), + "Trying to return record which is before the last-returned record"); + if (position == null) { range = range.withStartKey(recordStart); } position = recordStart; + + if (isAtSplitPoint) { + if (!range.containsKey(recordStart)) { + done = true; + return false; + } + ++splitPointsSeen; + } return true; } @@ -106,13 +128,50 @@ public synchronized double getFractionConsumed() { return range.estimateFractionForKey(position); } + public synchronized long getSplitPointsConsumed() { + if (position == null) { + return 0; + } else if (isDone()) { + return splitPointsSeen; + } else { + // There is a current split point, and it has not finished processing. + checkState( + splitPointsSeen > 0, + "A started rangeTracker should have seen > 0 split points (is %s)", + splitPointsSeen); + return splitPointsSeen - 1; + } + } + /////////////////////////////////////////////////////////////////////////////// private ByteKeyRange range; @Nullable private ByteKey position; + private long splitPointsSeen; + private boolean done; private ByteKeyRangeTracker(ByteKeyRange range) { this.range = range; - this.position = null; + position = null; + splitPointsSeen = 0L; + done = false; + } + + /** + * Marks this range tracker as being done. Specifically, this will mark the current split point, + * if one exists, as being finished. + * + *

            Always returns false, so that it can be used in an implementation of + * {@link BoundedReader#start()} or {@link BoundedReader#advance()} as follows: + * + *

             {@code
            +   * public boolean start() {
            +   *   return startImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint, position)
            +   *       || rangeTracker.markDone();
            +   * }} 
            + */ + public synchronized boolean markDone() { + done = true; + return false; } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java index 0200b565d9..076debe09c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java @@ -19,14 +19,18 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link ByteKeyRangeTracker}. */ @RunWith(JUnit4.class) public class ByteKeyRangeTrackerTest { + private static final ByteKey BEFORE_START_KEY = ByteKey.of(0x11); private static final ByteKey INITIAL_START_KEY = ByteKey.of(0x12); + private static final ByteKey AFTER_START_KEY = ByteKey.of(0x13); private static final ByteKey INITIAL_MIDDLE_KEY = ByteKey.of(0x23); private static final ByteKey NEW_START_KEY = ByteKey.of(0x14); private static final ByteKey NEW_MIDDLE_KEY = ByteKey.of(0x24); @@ -37,6 +41,8 @@ public class ByteKeyRangeTrackerTest { private static final double NEW_RANGE_SIZE = 0x34 - 0x14; private static final ByteKeyRange NEW_RANGE = ByteKeyRange.of(NEW_START_KEY, END_KEY); + @Rule public final ExpectedException expected = ExpectedException.none(); + /** Tests for {@link ByteKeyRangeTracker#toString}. */ @Test public void testToString() { @@ -125,7 +131,30 @@ public void testTryReturnRecordAt() { assertFalse(tracker.tryReturnRecordAt(true, END_KEY)); // after end - assertTrue(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); // still succeeds + assertFalse(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); // false because done + } + + @Test + public void testTryReturnFirstRecordNotSplitPoint() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); + expected.expect(IllegalStateException.class); + tracker.tryReturnRecordAt(false, INITIAL_START_KEY); + } + + @Test + public void testTryReturnBeforeStartKey() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); + expected.expect(IllegalStateException.class); + tracker.tryReturnRecordAt(true, BEFORE_START_KEY); + } + + @Test + public void testTryReturnBeforeLastReturnedRecord() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); + expected.expect(IllegalStateException.class); + tracker.tryReturnRecordAt(true, AFTER_START_KEY); } /** Tests for {@link ByteKeyRangeTracker#trySplitAtPosition}. */ @@ -149,4 +178,31 @@ public void testSplitAtPosition() { assertFalse(tracker.trySplitAtPosition(INITIAL_MIDDLE_KEY)); assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); } + + /** Tests for {@link ByteKeyRangeTracker#getSplitPointsConsumed()}. */ + @Test + public void testGetSplitPointsConsumed() { + ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); + assertEquals(0, tracker.getSplitPointsConsumed()); + + // Started, 0 split points consumed + assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); + assertEquals(0, tracker.getSplitPointsConsumed()); + + // Processing new split point, 1 split point consumed + assertTrue(tracker.tryReturnRecordAt(true, AFTER_START_KEY)); + assertEquals(1, tracker.getSplitPointsConsumed()); + + // Processing new non-split point, 1 split point consumed + assertTrue(tracker.tryReturnRecordAt(false, INITIAL_MIDDLE_KEY)); + assertEquals(1, tracker.getSplitPointsConsumed()); + + // Processing new split point, 2 split points consumed + assertTrue(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); + assertEquals(2, tracker.getSplitPointsConsumed()); + + // Mark tracker as done, 3 split points consumed + tracker.markDone(); + assertEquals(3, tracker.getSplitPointsConsumed()); + } } From 7b00b68120725e1ae220b06a9457dc83ef3b4ee9 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Fri, 1 Jul 2016 20:09:41 -0700 Subject: [PATCH 468/751] Expose getSplitPointsConsumed() in BigtableIO (#325) Implement getSplitPointsConsumed() in BigtableIO --- .../dataflow/sdk/io/bigtable/BigtableIO.java | 11 +++++-- .../sdk/io/bigtable/BigtableIOTest.java | 32 ++++++++++++++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index 05e1563d97..58cbf11eae 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -763,7 +763,8 @@ public boolean start() throws IOException { reader = service.createReader(getCurrentSource()); boolean hasRecord = reader.start() - && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())); + && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())) + || rangeTracker.markDone(); if (hasRecord) { ++recordsReturned; } @@ -779,7 +780,8 @@ public synchronized BigtableSource getCurrentSource() { public boolean advance() throws IOException { boolean hasRecord = reader.advance() - && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())); + && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())) + || rangeTracker.markDone(); if (hasRecord) { ++recordsReturned; } @@ -805,6 +807,11 @@ public final Double getFractionConsumed() { return rangeTracker.getFractionConsumed(); } + @Override + public final long getSplitPointsConsumed() { + return rangeTracker.getSplitPointsConsumed(); + } + @Override public final synchronized BigtableSource splitAtFraction(double fraction) { ByteKey splitKey; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java index 27c9d8703f..ef2381e543 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -23,7 +23,6 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verifyNotNull; - import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -40,6 +39,7 @@ import com.google.cloud.bigtable.config.BigtableOptions; import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; import com.google.cloud.dataflow.sdk.io.range.ByteKey; import com.google.cloud.dataflow.sdk.io.range.ByteKeyRange; @@ -487,6 +487,36 @@ public void testWritingDisplayData() { assertThat(displayData, hasDisplayItem("tableId", "fooTable")); } + @Test + public void testGetSplitPointsConsumed() throws Exception { + final String table = "TEST-TABLE"; + final int numRows = 100; + int splitPointsConsumed = 0; + + makeTableData(table, numRows); + + BigtableSource source = + new BigtableSource(service, table, null, ByteKeyRange.ALL_KEYS, null); + + BoundedReader reader = source.createReader(TestPipeline.testingPipelineOptions()); + + reader.start(); + // Started, 0 split points consumed + assertEquals("splitPointsConsumed starting", + splitPointsConsumed, reader.getSplitPointsConsumed()); + + // Split points consumed increases for each row read + while (reader.advance()) { + assertEquals("splitPointsConsumed advancing", + ++splitPointsConsumed, reader.getSplitPointsConsumed()); + } + + // Reader marked as done, 100 split points consumed + assertEquals("splitPointsConsumed done", numRows, reader.getSplitPointsConsumed()); + + reader.close(); + } + //////////////////////////////////////////////////////////////////////////////////////////// private static final String COLUMN_FAMILY_NAME = "family"; private static final ByteString COLUMN_NAME = ByteString.copyFromUtf8("column"); From 564ee5c3daa41e94363967d6b4e7418f53f7cbda Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Sat, 2 Jul 2016 02:18:07 -0700 Subject: [PATCH 469/751] AvroSource: use a 64K buffer size for Snappy codec commons-compress defaults to a 32K buffer size for Snappy. However, Avro uses xerial.snappy to write, which has a 64K buffer size. When the buffer size is too small, decoding data from Snappy can cause an EOF exception rather than finishing data. This fixes BEAM-422. --- .../google/cloud/dataflow/sdk/io/AvroSource.java | 2 +- .../cloud/dataflow/sdk/io/AvroSourceTest.java | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java index ea3d1c9ee6..1e3f47df76 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java @@ -393,7 +393,7 @@ private static InputStream decodeAsInputStream(byte[] data, String codec) throws ByteArrayInputStream byteStream = new ByteArrayInputStream(data); switch (codec) { case DataFileConstants.SNAPPY_CODEC: - return new SnappyCompressorInputStream(byteStream); + return new SnappyCompressorInputStream(byteStream, 1 << 16 /* Avro uses 64KB blocks. */); case DataFileConstants.DEFLATE_CODEC: // nowrap == true: Do not expect ZLIB header or checksum, as Avro does not write them. Inflater inflater = new Inflater(true); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java index 4298c5774d..e8be07f85b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java @@ -132,10 +132,17 @@ private String generateTestFile(String filename, List elems, SyncBehavior @Test public void testReadWithDifferentCodecs() throws Exception { // Test reading files generated using all codecs. - String codecs[] = {DataFileConstants.NULL_CODEC, DataFileConstants.BZIP2_CODEC, - DataFileConstants.DEFLATE_CODEC, DataFileConstants.SNAPPY_CODEC, - DataFileConstants.XZ_CODEC}; - List expected = createRandomRecords(DEFAULT_RECORD_COUNT); + String codecs[] = { + DataFileConstants.NULL_CODEC, + DataFileConstants.BZIP2_CODEC, + DataFileConstants.DEFLATE_CODEC, + DataFileConstants.SNAPPY_CODEC, + DataFileConstants.XZ_CODEC, + }; + // As Avro's default block size is 64KB, write 64K records to ensure at least one full block. + // We could make this smaller than 64K assuming each record is at least B bytes, but then the + // test could silently stop testing the failure condition from BEAM-422. + List expected = createRandomRecords(1 << 16); for (String codec : codecs) { String filename = generateTestFile( From ce2e5c009bc5bb6be01b63d7be088087138d5d91 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Thu, 7 Jul 2016 21:43:42 -0700 Subject: [PATCH 470/751] Update to bigtable-client-core-0.3.0 and use bulk writes (#326) Generally more stable, plus bulk writes bring 5x write throughput in batch jobs by more efficiently using the network. --- pom.xml | 3 +- sdk/pom.xml | 4 +- .../dataflow/sdk/io/bigtable/BigtableIO.java | 65 ++++++++++++++++++- .../sdk/io/bigtable/BigtableServiceImpl.java | 31 ++++----- .../sdk/io/bigtable/BigtableIOTest.java | 63 ++++++++++++++++++ 5 files changed, 142 insertions(+), 24 deletions(-) diff --git a/pom.xml b/pom.xml index 1133b4e46d..d50c62ccf8 100644 --- a/pom.xml +++ b/pom.xml @@ -71,12 +71,13 @@ 1.7.7 v2-rev295-1.22.0 0.0.2 - 0.2.3 + 0.3.0 v2-rev8-1.22.0 v1b3-rev30-1.22.0 0.5.160222 v1beta2-rev1-4.0.0 1.22.0 + 0.13.1 19.0 1.3 2.7.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index eb5f27339e..51827187e9 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -482,13 +482,13 @@ io.grpc grpc-all - 0.12.0 + ${grpc.version} io.netty netty-handler - 4.1.0.Beta8 + 4.1.0.CR1 diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index 58cbf11eae..c583bd97a9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -25,6 +25,7 @@ import com.google.bigtable.v1.RowFilter; import com.google.bigtable.v1.SampleRowKeysResponse; import com.google.cloud.bigtable.config.BigtableOptions; +import com.google.cloud.bigtable.config.RetryOptions; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; @@ -52,6 +53,8 @@ import com.google.protobuf.ByteString; import com.google.protobuf.Empty; +import io.grpc.Status; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -201,8 +204,23 @@ public Read withBigtableOptions(BigtableOptions options) { public Read withBigtableOptions(BigtableOptions.Builder optionsBuilder) { checkNotNull(optionsBuilder, "optionsBuilder"); // TODO: is there a better way to clone a Builder? Want it to be immune from user changes. - BigtableOptions.Builder clonedBuilder = optionsBuilder.build().toBuilder(); + BigtableOptions options = optionsBuilder.build(); + RetryOptions retryOptions = options.getRetryOptions(); + + // Set data channel count to one because there is only 1 scanner in this session + // Use retryOptionsToBuilder because absent in Bigtable library + // TODO: replace with RetryOptions.toBuilder() when added to Bigtable library + // Set batch size because of bug (incorrect initialization) in Bigtable library + // TODO: remove setRetryOptions when fixed in Bigtable library + BigtableOptions.Builder clonedBuilder = options.toBuilder() + .setDataChannelCount(1) + .setRetryOptions( + retryOptionsToBuilder(retryOptions) + .setStreamingBatchSize(Math.min(retryOptions.getStreamingBatchSize(), + retryOptions.getStreamingBufferSize() / 2)) + .build()); BigtableOptions optionsWithAgent = clonedBuilder.setUserAgent(getUserAgent()).build(); + return new Read(optionsWithAgent, tableId, filter, bigtableService); } @@ -385,7 +403,24 @@ public Write withBigtableOptions(BigtableOptions options) { public Write withBigtableOptions(BigtableOptions.Builder optionsBuilder) { checkNotNull(optionsBuilder, "optionsBuilder"); // TODO: is there a better way to clone a Builder? Want it to be immune from user changes. - BigtableOptions.Builder clonedBuilder = optionsBuilder.build().toBuilder(); + BigtableOptions options = optionsBuilder.build(); + RetryOptions retryOptions = options.getRetryOptions(); + + // Set useBulkApi to true for enabling bulk writes + // Use retryOptionsToBuilder because absent in Bigtable library + // TODO: replace with RetryOptions.toBuilder() when added to Bigtable library + // Set batch size because of bug (incorrect initialization) in Bigtable library + // TODO: remove setRetryOptions when fixed in Bigtable library + BigtableOptions.Builder clonedBuilder = options.toBuilder() + .setBulkOptions( + options.getBulkOptions().toBuilder() + .setUseBulkApi(true) + .build()) + .setRetryOptions( + retryOptionsToBuilder(retryOptions) + .setStreamingBatchSize(Math.min(retryOptions.getStreamingBatchSize(), + retryOptions.getStreamingBufferSize() / 2)) + .build()); BigtableOptions optionsWithAgent = clonedBuilder.setUserAgent(getUserAgent()).build(); return new Write(optionsWithAgent, tableId, bigtableService); } @@ -1022,6 +1057,30 @@ private static String getUserAgent() { info.getName(), info.getVersion(), javaVersion, - "0.2.3" /* TODO get Bigtable client version directly from jar. */); + "0.3.0" /* TODO get Bigtable client version directly from jar. */); + } + + /** + * A helper function to convert a RetryOptions into a RetryOptions.Builder. + */ + private static RetryOptions.Builder retryOptionsToBuilder(RetryOptions options) { + RetryOptions.Builder builder = new RetryOptions.Builder(); + builder.setEnableRetries(options.enableRetries()); + builder.setInitialBackoffMillis(options.getInitialBackoffMillis()); + builder.setBackoffMultiplier(options.getBackoffMultiplier()); + builder.setMaxElapsedBackoffMillis(options.getMaxElaspedBackoffMillis()); + builder.setStreamingBufferSize(options.getStreamingBufferSize()); + builder.setStreamingBatchSize(options.getStreamingBatchSize()); + builder.setReadPartialRowTimeoutMillis(options.getReadPartialRowTimeoutMillis()); + builder.setMaxScanTimeoutRetries(options.getMaxScanTimeoutRetries()); + builder.setAllowRetriesWithoutTimestamp(options.allowRetriesWithoutTimestamp()); + + for (Status.Code code : Status.Code.values()) { + if (options.isRetryable(code)) { + builder.addStatusToRetryOn(code); + } + } + + return builder; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java index 5ab85827ec..bfdf1cd909 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java @@ -25,8 +25,9 @@ import com.google.bigtable.v1.SampleRowKeysResponse; import com.google.cloud.bigtable.config.BigtableOptions; import com.google.cloud.bigtable.grpc.BigtableSession; +import com.google.cloud.bigtable.grpc.BigtableTableName; import com.google.cloud.bigtable.grpc.async.AsyncExecutor; -import com.google.cloud.bigtable.grpc.async.HeapSizeManager; +import com.google.cloud.bigtable.grpc.async.BulkMutation; import com.google.cloud.bigtable.grpc.scanner.ResultScanner; import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; import com.google.cloud.dataflow.sdk.values.KV; @@ -62,7 +63,7 @@ public BigtableServiceImpl(BigtableOptions options) { @Override public BigtableWriterImpl openForWriting(String tableId) throws IOException { BigtableSession session = new BigtableSession(options); - String tableName = options.getClusterName().toTableNameStr(tableId); + BigtableTableName tableName = options.getClusterName().toTableName(tableId); return new BigtableWriterImpl(session, tableName); } @@ -167,24 +168,23 @@ public Row getCurrentRow() throws NoSuchElementException { private static class BigtableWriterImpl implements Writer { private BigtableSession session; private AsyncExecutor executor; + private BulkMutation bulkMutation; private final MutateRowRequest.Builder partialBuilder; - public BigtableWriterImpl(BigtableSession session, String tableName) { + public BigtableWriterImpl(BigtableSession session, BigtableTableName tableName) { this.session = session; - this.executor = - new AsyncExecutor( - session.getDataClient(), - new HeapSizeManager( - AsyncExecutor.ASYNC_MUTATOR_MAX_MEMORY_DEFAULT, - AsyncExecutor.MAX_INFLIGHT_RPCS_DEFAULT)); - - partialBuilder = MutateRowRequest.newBuilder().setTableName(tableName); + executor = session.createAsyncExecutor(); + bulkMutation = session.createBulkMutation(tableName, executor); + + partialBuilder = MutateRowRequest.newBuilder().setTableName(tableName.toString()); } @Override public void close() throws IOException { try { - if (executor != null) { + if (bulkMutation != null) { + bulkMutation.flush(); + bulkMutation = null; executor.flush(); executor = null; } @@ -205,12 +205,7 @@ public ListenableFuture writeRecord(KV> re .setRowKey(record.getKey()) .addAllMutations(record.getValue()) .build(); - try { - return executor.mutateRowAsync(r); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException("Write interrupted", e); - } + return bulkMutation.add(r); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java index ef2381e543..cc9a97dfd0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -37,6 +37,8 @@ import com.google.bigtable.v1.RowFilter; import com.google.bigtable.v1.SampleRowKeysResponse; import com.google.cloud.bigtable.config.BigtableOptions; +import com.google.cloud.bigtable.config.BulkOptions; +import com.google.cloud.bigtable.config.RetryOptions; import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; @@ -517,6 +519,67 @@ public void testGetSplitPointsConsumed() throws Exception { reader.close(); } + @Test + public void testReadWithBigTableOptionsSetsRetryOptions() { + final int initialBackoffMillis = -1; + + BigtableOptions.Builder optionsBuilder = BIGTABLE_OPTIONS.toBuilder(); + + RetryOptions.Builder retryOptionsBuilder = new RetryOptions.Builder(); + retryOptionsBuilder.setInitialBackoffMillis(initialBackoffMillis); + + optionsBuilder.setRetryOptions(retryOptionsBuilder.build()); + + BigtableIO.Read read = + BigtableIO.read().withBigtableOptions(optionsBuilder.build()); + + BigtableOptions options = read.getBigtableOptions(); + assertEquals(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE, + options.getRetryOptions().getStreamingBatchSize()); + assertEquals(initialBackoffMillis, options.getRetryOptions().getInitialBackoffMillis()); + + assertThat(options.getRetryOptions(), + Matchers.equalTo(retryOptionsBuilder + .setStreamingBatchSize(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE) + .build())); + } + + @Test + public void testWriteWithBigTableOptionsSetsBulkOptionsAndRetryOptions() { + final int maxInflightRpcs = 1; + final int initialBackoffMillis = -1; + + BigtableOptions.Builder optionsBuilder = BIGTABLE_OPTIONS.toBuilder(); + + BulkOptions.Builder bulkOptionsBuilder = new BulkOptions.Builder(); + bulkOptionsBuilder.setMaxInflightRpcs(maxInflightRpcs); + + RetryOptions.Builder retryOptionsBuilder = new RetryOptions.Builder(); + retryOptionsBuilder.setInitialBackoffMillis(initialBackoffMillis); + + optionsBuilder.setBulkOptions(bulkOptionsBuilder.build()) + .setRetryOptions(retryOptionsBuilder.build()); + + BigtableIO.Write write = + BigtableIO.write().withBigtableOptions(optionsBuilder.build()); + + BigtableOptions options = write.getBigtableOptions(); + assertEquals(true, options.getBulkOptions().useBulkApi()); + assertEquals(maxInflightRpcs, options.getBulkOptions().getMaxInflightRpcs()); + assertEquals(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE, + options.getRetryOptions().getStreamingBatchSize()); + assertEquals(initialBackoffMillis, options.getRetryOptions().getInitialBackoffMillis()); + + assertThat(options.getBulkOptions(), + Matchers.equalTo(bulkOptionsBuilder + .setUseBulkApi(true) + .build())); + assertThat(options.getRetryOptions(), + Matchers.equalTo(retryOptionsBuilder + .setStreamingBatchSize(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE) + .build())); + } + //////////////////////////////////////////////////////////////////////////////////////////// private static final String COLUMN_FAMILY_NAME = "family"; private static final ByteString COLUMN_NAME = ByteString.copyFromUtf8("column"); From 77b4b7b480253ee0433f4ceb626966055fa6df0b Mon Sep 17 00:00:00 2001 From: peihe Date: Mon, 11 Jul 2016 09:26:08 -0700 Subject: [PATCH 471/751] Backport from Beam: Use UnboundedReadFromBoundedSource in dataflow runner (#333) --- .../sdk/runners/DataflowPipelineRunner.java | 35 +- ...ataflowUnboundedReadFromBoundedSource.java | 539 ++++++++++++++++++ .../runners/DataflowPipelineRunnerTest.java | 30 - ...lowUnboundedReadFromBoundedSourceTest.java | 372 ++++++++++++ 4 files changed, 942 insertions(+), 34 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index ec75cd5377..7a1a99c5df 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -57,6 +57,7 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; import com.google.cloud.dataflow.sdk.io.BigQueryIO; +import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.FileBasedSink; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.PubsubIO.Read.Bound.PubsubReader; @@ -79,6 +80,7 @@ import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; +import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource; import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; @@ -354,11 +356,8 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(View.AsIterable.class, StreamingViewAsIterable.class); builder.put(Write.Bound.class, StreamingWrite.class); builder.put(Read.Unbounded.class, StreamingUnboundedRead.class); - builder.put(Read.Bounded.class, UnsupportedIO.class); - builder.put(AvroIO.Read.Bound.class, UnsupportedIO.class); + builder.put(Read.Bounded.class, StreamingBoundedRead.class); builder.put(AvroIO.Write.Bound.class, UnsupportedIO.class); - builder.put(BigQueryIO.Read.Bound.class, UnsupportedIO.class); - builder.put(TextIO.Read.Bound.class, UnsupportedIO.class); builder.put(TextIO.Write.Bound.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); // In streaming mode must use either the custom Pubsub unbounded source/sink or @@ -2805,6 +2804,34 @@ public void processElement(ProcessContext c) { } } + /** + * Specialized implementation for + * {@link com.google.cloud.dataflow.sdk.io.Read.Bounded Read.Bounded} for the + * Dataflow runner in streaming mode. + */ + private static class StreamingBoundedRead extends PTransform> { + private final BoundedSource source; + + /** Builds an instance of this class from the overridden transform. */ + @SuppressWarnings("unused") // used via reflection in DataflowRunner#apply() + public StreamingBoundedRead(DataflowPipelineRunner runner, Read.Bounded transform) { + this.source = transform.getSource(); + } + + @Override + protected Coder getDefaultOutputCoder() { + return source.getDefaultOutputCoder(); + } + + @Override + public final PCollection apply(PInput input) { + source.validate(); + + return Pipeline.applyTransform(input, new DataflowUnboundedReadFromBoundedSource<>(source)) + .setIsBoundedInternal(IsBounded.BOUNDED); + } + } + /** * Specialized implementation for * {@link com.google.cloud.dataflow.sdk.transforms.Create.Values Create.Values} for the diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java new file mode 100644 index 0000000000..81aceebb2f --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java @@ -0,0 +1,539 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; + +import static com.google.cloud.dataflow.sdk.util.StringUtils.approximateSimpleName; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.ListCoder; +import com.google.cloud.dataflow.sdk.coders.NullableCoder; +import com.google.cloud.dataflow.sdk.coders.SerializableCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import javax.annotation.Nullable; + +/** + * {@link PTransform} that converts a {@link BoundedSource} as an {@link UnboundedSource}. + * + *

            {@link BoundedSource} is read directly without calling {@link BoundedSource#splitIntoBundles}, + * and element timestamps are propagated. While any elements remain, the watermark is the beginning + * of time {@link BoundedWindow#TIMESTAMP_MIN_VALUE}, and after all elements have been produced + * the watermark goes to the end of time {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. + * + *

            Checkpoints are created by calling {@link BoundedReader#splitAtFraction} on inner + * {@link BoundedSource}. + * Sources that cannot be split are read entirely into memory, so this transform does not work well + * with large, unsplittable sources. + * + *

            This transform is intended to be used by a runner during pipeline translation to convert + * a Read.Bounded into a Read.Unbounded. + */ +public class DataflowUnboundedReadFromBoundedSource extends PTransform> { + + private static final Logger LOG = + LoggerFactory.getLogger(DataflowUnboundedReadFromBoundedSource.class); + + private final BoundedSource source; + + /** + * Constructs a {@link PTransform} that performs an unbounded read from a {@link BoundedSource}. + */ + public DataflowUnboundedReadFromBoundedSource(BoundedSource source) { + this.source = source; + } + + @Override + public PCollection apply(PInput input) { + return input.getPipeline().apply( + Read.from(new BoundedToUnboundedSourceAdapter<>(source))); + } + + @Override + protected Coder getDefaultOutputCoder() { + return source.getDefaultOutputCoder(); + } + + @Override + public String getKindString() { + return "Read(" + approximateSimpleName(source.getClass()) + ")"; + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + // We explicitly do not register base-class data, instead we use the delegate inner source. + builder + .add(DisplayData.item("source", source.getClass())) + .include(source); + } + + /** + * A {@code BoundedSource} to {@code UnboundedSource} adapter. + */ + @VisibleForTesting + public static class BoundedToUnboundedSourceAdapter + extends UnboundedSource> { + + private BoundedSource boundedSource; + + public BoundedToUnboundedSourceAdapter(BoundedSource boundedSource) { + this.boundedSource = boundedSource; + } + + @Override + public void validate() { + boundedSource.validate(); + } + + @Override + public List> generateInitialSplits( + int desiredNumSplits, PipelineOptions options) throws Exception { + try { + long desiredBundleSize = boundedSource.getEstimatedSizeBytes(options) / desiredNumSplits; + if (desiredBundleSize <= 0) { + LOG.warn("BoundedSource {} cannot estimate its size, skips the initial splits.", + boundedSource); + return ImmutableList.of(this); + } + List> splits + = boundedSource.splitIntoBundles(desiredBundleSize, options); + if (splits == null) { + LOG.warn("BoundedSource cannot split {}, skips the initial splits.", boundedSource); + return ImmutableList.of(this); + } + return Lists.transform( + splits, + new Function, BoundedToUnboundedSourceAdapter>() { + @Override + public BoundedToUnboundedSourceAdapter apply(BoundedSource input) { + return new BoundedToUnboundedSourceAdapter<>(input); + }}); + } catch (Exception e) { + LOG.warn("Exception while splitting {}, skips the initial splits.", boundedSource, e); + return ImmutableList.of(this); + } + } + + @Override + public Reader createReader(PipelineOptions options, Checkpoint checkpoint) { + if (checkpoint == null) { + return new Reader(null /* residualElements */, boundedSource, options); + } else { + return new Reader(checkpoint.residualElements, checkpoint.residualSource, options); + } + } + + @Override + public Coder getDefaultOutputCoder() { + return boundedSource.getDefaultOutputCoder(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Coder> getCheckpointMarkCoder() { + return new CheckpointCoder<>(boundedSource.getDefaultOutputCoder()); + } + + @VisibleForTesting + static class Checkpoint implements UnboundedSource.CheckpointMark { + @Nullable private final List> residualElements; + @Nullable private final BoundedSource residualSource; + + public Checkpoint( + @Nullable List> residualElements, + @Nullable BoundedSource residualSource) { + this.residualElements = residualElements; + this.residualSource = residualSource; + } + + @Override + public void finalizeCheckpoint() {} + + @VisibleForTesting + @Nullable List> getResidualElements() { + return residualElements; + } + + @VisibleForTesting + @Nullable BoundedSource getResidualSource() { + return residualSource; + } + } + + @VisibleForTesting + static class CheckpointCoder extends StandardCoder> { + + @JsonCreator + public static CheckpointCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) + List> components) { + checkArgument(components.size() == 1, + "Expecting 1 components, got %s", components.size()); + return new CheckpointCoder<>(components.get(0)); + } + + // The coder for a list of residual elements and their timestamps + private final Coder>> elemsCoder; + // The coder from the BoundedReader for coding each element + private final Coder elemCoder; + // The nullable and serializable coder for the BoundedSource. + @SuppressWarnings("rawtypes") + private final Coder sourceCoder; + + CheckpointCoder(Coder elemCoder) { + this.elemsCoder = NullableCoder.of( + ListCoder.of(TimestampedValue.TimestampedValueCoder.of(elemCoder))); + this.elemCoder = elemCoder; + this.sourceCoder = NullableCoder.of(SerializableCoder.of(BoundedSource.class)); + } + + @Override + public void encode(Checkpoint value, OutputStream outStream, Context context) + throws CoderException, IOException { + Context nested = context.nested(); + elemsCoder.encode(value.residualElements, outStream, nested); + sourceCoder.encode(value.residualSource, outStream, nested); + } + + @SuppressWarnings("unchecked") + @Override + public Checkpoint decode(InputStream inStream, Context context) + throws CoderException, IOException { + Context nested = context.nested(); + return new Checkpoint<>( + elemsCoder.decode(inStream, nested), + sourceCoder.decode(inStream, nested)); + } + + @Override + public List> getCoderArguments() { + return Arrays.>asList(elemCoder); + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + throw new NonDeterministicException(this, + "CheckpointCoder uses Java Serialization, which may be non-deterministic."); + } + } + + /** + * An {@code UnboundedReader} that wraps a {@code BoundedSource} into + * {@link ResidualElements} and {@link ResidualSource}. + * + *

            In the initial state, {@link ResidualElements} is null and {@link ResidualSource} contains + * the {@code BoundedSource}. After the first checkpoint, the {@code BoundedSource} will + * be split into {@link ResidualElements} and {@link ResidualSource}. + */ + @VisibleForTesting + class Reader extends UnboundedReader { + private ResidualElements residualElements; + @Nullable private ResidualSource residualSource; + private final PipelineOptions options; + private boolean done; + + Reader( + @Nullable List> residualElementsList, + @Nullable BoundedSource residualSource, + PipelineOptions options) { + init(residualElementsList, residualSource, options); + this.options = checkNotNull(options, "options"); + this.done = false; + } + + private void init( + @Nullable List> residualElementsList, + @Nullable BoundedSource residualSource, + PipelineOptions options) { + this.residualElements = residualElementsList == null + ? new ResidualElements(Collections.>emptyList()) + : new ResidualElements(residualElementsList); + this.residualSource = + residualSource == null ? null : new ResidualSource(residualSource, options); + } + + @Override + public boolean start() throws IOException { + return advance(); + } + + @Override + public boolean advance() throws IOException { + if (residualElements.advance()) { + return true; + } else if (residualSource != null && residualSource.advance()) { + return true; + } else { + done = true; + return false; + } + } + + @Override + public void close() throws IOException { + if (residualSource != null) { + residualSource.close(); + } + } + + @Override + public T getCurrent() throws NoSuchElementException { + if (residualElements.hasCurrent()) { + return residualElements.getCurrent(); + } else if (residualSource != null) { + return residualSource.getCurrent(); + } else { + throw new NoSuchElementException(); + } + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + if (residualElements.hasCurrent()) { + return residualElements.getCurrentTimestamp(); + } else if (residualSource != null) { + return residualSource.getCurrentTimestamp(); + } else { + throw new NoSuchElementException(); + } + } + + @Override + public Instant getWatermark() { + return done ? BoundedWindow.TIMESTAMP_MAX_VALUE : BoundedWindow.TIMESTAMP_MIN_VALUE; + } + + /** + * {@inheritDoc} + * + *

            If only part of the {@link ResidualElements} is consumed, the new + * checkpoint will contain the remaining elements in {@link ResidualElements} and + * the {@link ResidualSource}. + * + *

            If all {@link ResidualElements} and part of the + * {@link ResidualSource} are consumed, the new checkpoint is done by splitting + * {@link ResidualSource} into new {@link ResidualElements} and {@link ResidualSource}. + * {@link ResidualSource} is the source split from the current source, + * and {@link ResidualElements} contains rest elements from the current source after + * the splitting. For unsplittable source, it will put all remaining elements into + * the {@link ResidualElements}. + */ + @Override + public Checkpoint getCheckpointMark() { + Checkpoint newCheckpoint; + if (!residualElements.done()) { + // Part of residualElements are consumed. + // Checkpoints the remaining elements and residualSource. + newCheckpoint = new Checkpoint<>( + residualElements.getRestElements(), + residualSource == null ? null : residualSource.getSource()); + } else if (residualSource != null) { + newCheckpoint = residualSource.getCheckpointMark(); + } else { + newCheckpoint = new Checkpoint<>(null /* residualElements */, null /* residualSource */); + } + // Re-initialize since the residualElements and the residualSource might be + // consumed or split by checkpointing. + init(newCheckpoint.residualElements, newCheckpoint.residualSource, options); + return newCheckpoint; + } + + @Override + public BoundedToUnboundedSourceAdapter getCurrentSource() { + return BoundedToUnboundedSourceAdapter.this; + } + } + + private class ResidualElements { + private final List> elementsList; + @Nullable private Iterator> elementsIterator; + @Nullable private TimestampedValue currentT; + private boolean hasCurrent; + private boolean done; + + ResidualElements(List> residualElementsList) { + this.elementsList = checkNotNull(residualElementsList, "residualElementsList"); + this.elementsIterator = null; + this.currentT = null; + this.hasCurrent = false; + this.done = false; + } + + public boolean advance() { + if (elementsIterator == null) { + elementsIterator = elementsList.iterator(); + } + if (elementsIterator.hasNext()) { + currentT = elementsIterator.next(); + hasCurrent = true; + return true; + } else { + done = true; + hasCurrent = false; + return false; + } + } + + boolean hasCurrent() { + return hasCurrent; + } + + boolean done() { + return done; + } + + TimestampedValue getCurrentTimestampedValue() { + if (!hasCurrent) { + throw new NoSuchElementException(); + } + return currentT; + } + + T getCurrent() { + return getCurrentTimestampedValue().getValue(); + } + + Instant getCurrentTimestamp() { + return getCurrentTimestampedValue().getTimestamp(); + } + + List> getRestElements() { + if (elementsIterator == null) { + return elementsList; + } else { + List> newResidualElements = Lists.newArrayList(); + while (elementsIterator.hasNext()) { + newResidualElements.add(elementsIterator.next()); + } + return newResidualElements; + } + } + } + + private class ResidualSource { + private BoundedSource residualSource; + private PipelineOptions options; + @Nullable private BoundedReader reader; + private boolean closed; + + public ResidualSource(BoundedSource residualSource, PipelineOptions options) { + this.residualSource = checkNotNull(residualSource, "residualSource"); + this.options = checkNotNull(options, "options"); + this.reader = null; + this.closed = false; + } + + private boolean advance() throws IOException { + if (reader == null && !closed) { + reader = residualSource.createReader(options); + return reader.start(); + } else { + return reader.advance(); + } + } + + T getCurrent() throws NoSuchElementException { + if (reader == null) { + throw new NoSuchElementException(); + } + return reader.getCurrent(); + } + + Instant getCurrentTimestamp() throws NoSuchElementException { + if (reader == null) { + throw new NoSuchElementException(); + } + return reader.getCurrentTimestamp(); + } + + void close() throws IOException { + if (reader != null) { + reader.close(); + reader = null; + } + closed = true; + } + + BoundedSource getSource() { + return residualSource; + } + + Checkpoint getCheckpointMark() { + if (reader == null) { + // Reader hasn't started, checkpoint the residualSource. + return new Checkpoint<>(null /* residualElements */, residualSource); + } else { + // Part of residualSource are consumed. + // Splits the residualSource and tracks the new residualElements in current source. + BoundedSource residualSplit = null; + Double fractionConsumed = reader.getFractionConsumed(); + if (fractionConsumed != null && 0 <= fractionConsumed && fractionConsumed <= 1) { + double fractionRest = 1 - fractionConsumed; + int splitAttempts = 8; + for (int i = 0; i < 8 && residualSplit == null; ++i) { + double fractionToSplit = fractionConsumed + fractionRest * i / splitAttempts; + residualSplit = reader.splitAtFraction(fractionToSplit); + } + } + List> newResidualElements = Lists.newArrayList(); + try { + while (advance()) { + newResidualElements.add( + TimestampedValue.of(reader.getCurrent(), reader.getCurrentTimestamp())); + } + } catch (IOException e) { + throw new RuntimeException("Failed to read elements from the bounded reader.", e); + } + return new Checkpoint<>(newResidualElements, residualSplit); + } + } + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 8a10db93ca..199d2d09c4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -46,8 +46,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.AvroSource; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; @@ -893,34 +891,6 @@ private void testUnsupportedSource(PTransform source, String name, bo p.run(); } - @Test - public void testBoundedSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource( - AvroSource.readFromFileWithClass("foo", String.class), "Read.Bounded", true); - } - - @Test - public void testBigQueryIOSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource( - BigQueryIO.Read.from("project:bar.baz").withoutValidation(), "BigQueryIO.Read", true); - } - - @Test - public void testAvroIOSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource( - AvroIO.Read.from("foo"), "AvroIO.Read", true); - } - - @Test - public void testTextIOSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource(TextIO.Read.from("foo"), "TextIO.Read", true); - } - - @Test - public void testReadBoundedSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource(Read.from(AvroSource.from("/tmp/test")), "Read.Bounded", true); - } - @Test public void testReadUnboundedUnsupportedInBatch() throws Exception { testUnsupportedSource(Read.from(new TestCountingSource(1)), "Read.Unbounded", false); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java new file mode 100644 index 0000000000..7c39ab03ce --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java @@ -0,0 +1,372 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.SerializableCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.CountingSource; +import com.google.cloud.dataflow.sdk.io.FileBasedSource; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource.BoundedToUnboundedSourceAdapter; +import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource.BoundedToUnboundedSourceAdapter.Checkpoint; +import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource.BoundedToUnboundedSourceAdapter.CheckpointCoder; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.RunnableOnService; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.Max; +import com.google.cloud.dataflow.sdk.transforms.Min; +import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ReadableByteChannel; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Random; + +/** + * Unit tests for {@link DataflowUnboundedReadFromBoundedSource}. + */ +@RunWith(JUnit4.class) +public class DataflowUnboundedReadFromBoundedSourceTest { + + @Rule + public TemporaryFolder tmpFolder = new TemporaryFolder(); + + @Rule + public transient ExpectedException thrown = ExpectedException.none(); + + @Test + public void testCheckpointCoderNulls() throws Exception { + CheckpointCoder coder = new CheckpointCoder<>(StringUtf8Coder.of()); + Checkpoint emptyCheckpoint = new Checkpoint<>(null, null); + Checkpoint decodedEmptyCheckpoint = CoderUtils.decodeFromByteArray( + coder, + CoderUtils.encodeToByteArray(coder, emptyCheckpoint)); + assertNull(decodedEmptyCheckpoint.getResidualElements()); + assertNull(decodedEmptyCheckpoint.getResidualSource()); + } + + @Test + @Category(RunnableOnService.class) + public void testBoundedToUnboundedSourceAdapter() throws Exception { + long numElements = 100; + BoundedSource boundedSource = CountingSource.upTo(numElements); + UnboundedSource> unboundedSource = + new BoundedToUnboundedSourceAdapter<>(boundedSource); + + Pipeline p = TestPipeline.create(); + + PCollection output = + p.apply(Read.from(unboundedSource).withMaxNumRecords(numElements)); + + // Count == numElements + DataflowAssert + .thatSingleton(output.apply("Count", Count.globally())) + .isEqualTo(numElements); + // Unique count == numElements + DataflowAssert + .thatSingleton(output.apply(RemoveDuplicates.create()) + .apply("UniqueCount", Count.globally())) + .isEqualTo(numElements); + // Min == 0 + DataflowAssert + .thatSingleton(output.apply("Min", Min.globally())) + .isEqualTo(0L); + // Max == numElements-1 + DataflowAssert + .thatSingleton(output.apply("Max", Max.globally())) + .isEqualTo(numElements - 1); + p.run(); + } + + @Test + public void testCountingSourceToUnboundedCheckpoint() throws Exception { + long numElements = 100; + BoundedSource countingSource = CountingSource.upTo(numElements); + List expected = Lists.newArrayList(); + for (long i = 0; i < numElements; ++i) { + expected.add(i); + } + testBoundedToUnboundedSourceAdapterCheckpoint(countingSource, expected); + } + + @Test + public void testUnsplittableSourceToUnboundedCheckpoint() throws Exception { + String baseName = "test-input"; + File compressedFile = tmpFolder.newFile(baseName + ".gz"); + byte[] input = generateInput(100); + writeFile(compressedFile, input); + + BoundedSource source = new UnsplittableSource(compressedFile.getPath(), 1); + List expected = Lists.newArrayList(); + for (byte i : input) { + expected.add(i); + } + testBoundedToUnboundedSourceAdapterCheckpoint(source, expected); + } + + private void testBoundedToUnboundedSourceAdapterCheckpoint( + BoundedSource boundedSource, + List expectedElements) throws Exception { + BoundedToUnboundedSourceAdapter unboundedSource = + new BoundedToUnboundedSourceAdapter<>(boundedSource); + + PipelineOptions options = PipelineOptionsFactory.create(); + BoundedToUnboundedSourceAdapter.Reader reader = + unboundedSource.createReader(options, null); + + List actual = Lists.newArrayList(); + for (boolean hasNext = reader.start(); hasNext; hasNext = reader.advance()) { + actual.add(reader.getCurrent()); + // checkpoint every 9 elements + if (actual.size() % 9 == 0) { + Checkpoint checkpoint = reader.getCheckpointMark(); + checkpoint.finalizeCheckpoint(); + } + } + Checkpoint checkpointDone = reader.getCheckpointMark(); + assertTrue(checkpointDone.getResidualElements() == null + || checkpointDone.getResidualElements().isEmpty()); + + assertEquals(expectedElements.size(), actual.size()); + assertEquals(Sets.newHashSet(expectedElements), Sets.newHashSet(actual)); + } + + @Test + public void testCountingSourceToUnboundedCheckpointRestart() throws Exception { + long numElements = 100; + BoundedSource countingSource = CountingSource.upTo(numElements); + List expected = Lists.newArrayList(); + for (long i = 0; i < numElements; ++i) { + expected.add(i); + } + testBoundedToUnboundedSourceAdapterCheckpointRestart(countingSource, expected); + } + + @Test + public void testUnsplittableSourceToUnboundedCheckpointRestart() throws Exception { + String baseName = "test-input"; + File compressedFile = tmpFolder.newFile(baseName + ".gz"); + byte[] input = generateInput(1000); + writeFile(compressedFile, input); + + BoundedSource source = new UnsplittableSource(compressedFile.getPath(), 1); + List expected = Lists.newArrayList(); + for (byte i : input) { + expected.add(i); + } + testBoundedToUnboundedSourceAdapterCheckpointRestart(source, expected); + } + + private void testBoundedToUnboundedSourceAdapterCheckpointRestart( + BoundedSource boundedSource, + List expectedElements) throws Exception { + BoundedToUnboundedSourceAdapter unboundedSource = + new BoundedToUnboundedSourceAdapter<>(boundedSource); + + PipelineOptions options = PipelineOptionsFactory.create(); + BoundedToUnboundedSourceAdapter.Reader reader = + unboundedSource.createReader(options, null); + + List actual = Lists.newArrayList(); + for (boolean hasNext = reader.start(); hasNext;) { + actual.add(reader.getCurrent()); + // checkpoint every 9 elements + if (actual.size() % 9 == 0) { + Checkpoint checkpoint = reader.getCheckpointMark(); + Coder> checkpointCoder = unboundedSource.getCheckpointMarkCoder(); + Checkpoint decodedCheckpoint = CoderUtils.decodeFromByteArray( + checkpointCoder, + CoderUtils.encodeToByteArray(checkpointCoder, checkpoint)); + reader.close(); + checkpoint.finalizeCheckpoint(); + + BoundedToUnboundedSourceAdapter.Reader restarted = + unboundedSource.createReader(options, decodedCheckpoint); + reader = restarted; + hasNext = reader.start(); + } else { + hasNext = reader.advance(); + } + } + Checkpoint checkpointDone = reader.getCheckpointMark(); + assertTrue(checkpointDone.getResidualElements() == null + || checkpointDone.getResidualElements().isEmpty()); + + assertEquals(expectedElements.size(), actual.size()); + assertEquals(Sets.newHashSet(expectedElements), Sets.newHashSet(actual)); + } + + @Test + public void testReadBeforeStart() throws Exception { + thrown.expect(NoSuchElementException.class); + + BoundedSource countingSource = CountingSource.upTo(100); + BoundedToUnboundedSourceAdapter unboundedSource = + new BoundedToUnboundedSourceAdapter<>(countingSource); + PipelineOptions options = PipelineOptionsFactory.create(); + + unboundedSource.createReader(options, null).getCurrent(); + } + + @Test + public void testReadFromCheckpointBeforeStart() throws Exception { + thrown.expect(NoSuchElementException.class); + + BoundedSource countingSource = CountingSource.upTo(100); + BoundedToUnboundedSourceAdapter unboundedSource = + new BoundedToUnboundedSourceAdapter<>(countingSource); + PipelineOptions options = PipelineOptionsFactory.create(); + + List> elements = + ImmutableList.of(TimestampedValue.of(1L, new Instant(1L))); + Checkpoint checkpoint = new Checkpoint<>(elements, countingSource); + unboundedSource.createReader(options, checkpoint).getCurrent(); + } + + /** + * Generate byte array of given size. + */ + private static byte[] generateInput(int size) { + // Arbitrary but fixed seed + Random random = new Random(285930); + byte[] buff = new byte[size]; + random.nextBytes(buff); + return buff; + } + + /** + * Writes a single output file. + */ + private static void writeFile(File file, byte[] input) throws IOException { + try (OutputStream os = new FileOutputStream(file)) { + os.write(input); + } + } + + /** + * Unsplittable source for use in tests. + */ + private static class UnsplittableSource extends FileBasedSource { + public UnsplittableSource(String fileOrPatternSpec, long minBundleSize) { + super(fileOrPatternSpec, minBundleSize); + } + + public UnsplittableSource( + String fileName, long minBundleSize, long startOffset, long endOffset) { + super(fileName, minBundleSize, startOffset, endOffset); + } + + @Override + protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { + return new UnsplittableSource(fileName, getMinBundleSize(), start, end); + } + + @Override + protected FileBasedReader createSingleFileReader(PipelineOptions options) { + return new UnsplittableReader(this); + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return false; + } + + @Override + public boolean allowsDynamicSplitting() { + return false; + } + + @Override + public Coder getDefaultOutputCoder() { + return SerializableCoder.of(Byte.class); + } + + private static class UnsplittableReader extends FileBasedReader { + ByteBuffer buff = ByteBuffer.allocate(1); + Byte current; + long offset; + ReadableByteChannel channel; + + public UnsplittableReader(UnsplittableSource source) { + super(source); + offset = source.getStartOffset() - 1; + } + + @Override + public Byte getCurrent() throws NoSuchElementException { + return current; + } + + @Override + protected boolean isAtSplitPoint() { + return true; + } + + @Override + protected void startReading(ReadableByteChannel channel) throws IOException { + this.channel = channel; + } + + @Override + protected boolean readNextRecord() throws IOException { + buff.clear(); + if (channel.read(buff) != 1) { + return false; + } + current = new Byte(buff.get(0)); + offset += 1; + return true; + } + + @Override + protected long getCurrentOffset() { + return offset; + } + } + } +} From f3b030b26ffe027d7b18c7120ab15d26e9ab8c77 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Mon, 11 Jul 2016 09:40:12 -0700 Subject: [PATCH 472/751] Changed JUnitMatchers to Matchers (#335) --- .../google/cloud/dataflow/sdk/transforms/DoFnTester.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java index 544766433c..6cc904f5a2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java @@ -63,12 +63,10 @@ * // Process a batch containing a single input element: * Input testInput = ...; * List testOutputs = fnTester.processBatch(testInput); - * Assert.assertThat(testOutputs, - * JUnitMatchers.hasItems(...)); + * Assert.assertThat(testOutputs, Matchers.hasItems(...)); * * // Process a bigger batch: - * Assert.assertThat(fnTester.processBatch(i1, i2, ...), - * JUnitMatchers.hasItems(...)); + * Assert.assertThat(fnTester.processBatch(i1, i2, ...), Matchers.hasItems(...)); * } * * @param the type of the {@code DoFn}'s (main) input elements From 07795e4f24b93bf94182cf664e93ebdf29c29f1e Mon Sep 17 00:00:00 2001 From: Kurt Alfred Kluever Date: Mon, 11 Jul 2016 12:42:32 -0400 Subject: [PATCH 473/751] Use HashBasedTable.create() instead of Tables.newCustomTable() (#336) * Use HashBasedTable.create() instead of Tables.newCustomTable() * Update StateTable.java --- .../cloud/dataflow/sdk/util/state/StateTable.java | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java index edd1dae279..9e15e35197 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java @@ -16,11 +16,9 @@ package com.google.cloud.dataflow.sdk.util.state; import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; -import com.google.common.base.Supplier; +import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; -import com.google.common.collect.Tables; -import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -30,13 +28,7 @@ public abstract class StateTable { private final Table, State> stateTable = - Tables.newCustomTable(new HashMap, State>>(), - new Supplier, State>>() { - @Override - public Map, State> get() { - return new HashMap<>(); - } - }); + HashBasedTable.create(); /** * Gets the {@link State} in the specified {@link StateNamespace} with the specified {@link From 088f6f13a93a4ea93e821406b9b7535676d67fa7 Mon Sep 17 00:00:00 2001 From: peihe Date: Tue, 12 Jul 2016 23:12:31 -0700 Subject: [PATCH 474/751] BigQueryIO: User friendly message for tempLocation * User friendly message for tempLocation. Closes #313 Temporary location is needed for BigQueryIO, in case of cloud based runners at least one of `staging` or `temp` locations is required, for location runners such requirement is not enforced thus it is possible to end up with nasty NPE - see #313. Provide more user friendly exception, with suggestion to set `temp` location. * Create PipelineOptions in each tests to avoid mutating bqOptions --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 16 +++++++ .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 47 +++++++++++++------ 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 78f4529fd7..6ce7c36fa5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -492,6 +492,22 @@ public void validate(PInput input) { if (validate) { BigQueryOptions bqOptions = input.getPipeline().getOptions().as(BigQueryOptions.class); + String tempLocation = bqOptions.getTempLocation(); + checkArgument( + !Strings.isNullOrEmpty(tempLocation), + "BigQueryIO.Read needs a GCS temp location to store temp files."); + if (testBigQueryServices == null) { + try { + GcsPath.fromUri(tempLocation); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + String.format( + "BigQuery temp location expected a valid 'gs://' path, but was given '%s'", + tempLocation), + e); + } + } + TableReference table = getTableWithDefaultProject(bqOptions); if (table == null && query == null) { throw new IllegalStateException( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index f34124767d..0a39100b7d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -334,8 +334,6 @@ public JobStatistics dryRunQuery(String projectId, String query) @Mock private transient IOChannelFactory mockIOChannelFactory; @Mock private transient DatasetService mockDatasetService; - private transient BigQueryOptions bqOptions; - private void checkReadTableObject( BigQueryIO.Read.Bound bound, String project, String dataset, String table) { checkReadTableObjectWithValidate(bound, project, dataset, table, true); @@ -384,11 +382,7 @@ private void checkWriteObjectWithValidate( } @Before - public void setUp() throws IOException { - bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); - + public void setUp() { MockitoAnnotations.initMocks(this); } @@ -444,10 +438,11 @@ public void testBuildSourceWithTableReference() { @Test public void testValidateReadSetsDefaultProject() { - BigQueryOptions options = PipelineOptionsFactory.as(BigQueryOptions.class); - options.setProject("someproject"); + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation("gs://testbucket/testdir"); - Pipeline p = Pipeline.create(options); + Pipeline p = Pipeline.create(bqOptions); TableReference tableRef = new TableReference(); tableRef.setDatasetId("somedataset"); @@ -464,7 +459,11 @@ public void testValidateReadSetsDefaultProject() { @Test @Category(RunnableOnService.class) public void testBuildSourceWithoutTableOrQuery() { - Pipeline p = TestPipeline.create(); + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation("gs://testbucket/testdir"); + + Pipeline p = TestPipeline.create(bqOptions); thrown.expect(IllegalStateException.class); thrown.expectMessage( "Invalid BigQuery read operation, either table reference or query has to be set"); @@ -475,7 +474,11 @@ public void testBuildSourceWithoutTableOrQuery() { @Test @Category(RunnableOnService.class) public void testBuildSourceWithTableAndQuery() { - Pipeline p = TestPipeline.create(); + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation("gs://testbucket/testdir"); + + Pipeline p = TestPipeline.create(bqOptions); thrown.expect(IllegalStateException.class); thrown.expectMessage( "Invalid BigQuery read operation. Specifies both a query and a table, only one of these" @@ -490,7 +493,11 @@ public void testBuildSourceWithTableAndQuery() { @Test @Category(RunnableOnService.class) public void testBuildSourceWithTableAndFlatten() { - Pipeline p = TestPipeline.create(); + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation("gs://testbucket/testdir"); + + Pipeline p = TestPipeline.create(bqOptions); thrown.expect(IllegalStateException.class); thrown.expectMessage( "Invalid BigQuery read operation. Specifies a" @@ -503,7 +510,11 @@ public void testBuildSourceWithTableAndFlatten() { } @Test - public void testReadFromTable() { + public void testReadFromTable() throws IOException { + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() .withJobService(new FakeJobService() .startJobReturns("done", "done") @@ -534,6 +545,10 @@ public void processElement(ProcessContext c) throws Exception { @Test public void testCustomSink() throws Exception { + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() .withJobService(new FakeJobService() .startJobReturns("done", "done", "done") @@ -567,6 +582,10 @@ public boolean accept(File pathname) { @Test public void testCustomSinkUnknown() throws Exception { + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() .withJobService(new FakeJobService() .startJobReturns("done", "done") From 0410aafe3485d35e629f20883999888940e967d2 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Wed, 13 Jul 2016 11:09:11 -0700 Subject: [PATCH 475/751] Add v1beta3 version of datastore Source/Sink. (#328) * Add v1beta3 version of datastore Source/Sink. * Deprecate old DatastoreIO classes * getProject to getDataset --- examples/pom.xml | 12 + .../examples/complete/AutoComplete.java | 159 +-- .../examples/cookbook/DatastoreWordCount.java | 50 +- pom.xml | 2 + sdk/pom.xml | 12 + .../dataflow/sdk/coders/EntityCoder.java | 3 + .../cloud/dataflow/sdk/io/DatastoreIO.java | 4 + .../sdk/io/datastore/DatastoreIO.java | 40 + .../dataflow/sdk/io/datastore/V1Beta3.java | 991 ++++++++++++++++++ .../sdk/io/datastore/package-info.java | 22 + .../cloud/dataflow/sdk/util/ApiSurface.java | 3 + .../sdk/coders/protobuf/ProtobufUtilTest.java | 7 +- .../sdk/io/datastore/V1Beta3Test.java | 582 ++++++++++ 13 files changed, 1779 insertions(+), 108 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java diff --git a/examples/pom.xml b/examples/pom.xml index a476c3ff91..d247168935 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -459,6 +459,18 @@ + + com.google.cloud.datastore + datastore-v1beta3-proto-client + ${datastore.client.version} + + + + com.google.cloud.datastore + datastore-v1beta3-protos + ${datastore.proto.version} + + com.google.guava guava diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java index 4c6c9f82e5..6e50fe1047 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java @@ -16,14 +16,12 @@ package com.google.cloud.dataflow.examples.complete; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; + import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; -import com.google.api.services.datastore.DatastoreV1.Entity; -import com.google.api.services.datastore.DatastoreV1.Key; -import com.google.api.services.datastore.DatastoreV1.Value; -import com.google.api.services.datastore.client.DatastoreHelper; import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions; import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicOptions; @@ -32,9 +30,9 @@ import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.DefaultCoder; import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.DatastoreIO; import com.google.cloud.dataflow.sdk.io.PubsubIO; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreIO; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; @@ -60,12 +58,18 @@ import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; +import com.google.datastore.v1beta3.Entity; +import com.google.datastore.v1beta3.Key; +import com.google.datastore.v1beta3.Value; +import com.google.datastore.v1beta3.client.DatastoreHelper; import org.joda.time.Duration; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -121,26 +125,26 @@ public static ComputeTopCompletions top(int candidatesPerPrefix, boolean recursi @Override public PCollection>> apply(PCollection input) { PCollection candidates = input - // First count how often each token appears. - .apply(new Count.PerElement()) - - // Map the KV outputs of Count into our own CompletionCandiate class. - .apply(ParDo.named("CreateCompletionCandidates").of( - new DoFn, CompletionCandidate>() { - @Override - public void processElement(ProcessContext c) { - c.output(new CompletionCandidate(c.element().getKey(), c.element().getValue())); - } - })); + // First count how often each token appears. + .apply(new Count.PerElement()) + + // Map the KV outputs of Count into our own CompletionCandiate class. + .apply(ParDo.named("CreateCompletionCandidates").of( + new DoFn, CompletionCandidate>() { + @Override + public void processElement(ProcessContext c) { + c.output(new CompletionCandidate(c.element().getKey(), c.element().getValue())); + } + })); // Compute the top via either a flat or recursive algorithm. if (recursive) { return candidates - .apply(new ComputeTopRecursive(candidatesPerPrefix, 1)) - .apply(Flatten.>>pCollections()); + .apply(new ComputeTopRecursive(candidatesPerPrefix, 1)) + .apply(Flatten.>>pCollections()); } else { return candidates - .apply(new ComputeTopFlat(candidatesPerPrefix, 1)); + .apply(new ComputeTopFlat(candidatesPerPrefix, 1)); } } } @@ -150,7 +154,7 @@ public void processElement(ProcessContext c) { */ private static class ComputeTopFlat extends PTransform, - PCollection>>> { + PCollection>>> { private final int candidatesPerPrefix; private final int minPrefix; @@ -163,12 +167,12 @@ public ComputeTopFlat(int candidatesPerPrefix, int minPrefix) { public PCollection>> apply( PCollection input) { return input - // For each completion candidate, map it to all prefixes. - .apply(ParDo.of(new AllPrefixes(minPrefix))) + // For each completion candidate, map it to all prefixes. + .apply(ParDo.of(new AllPrefixes(minPrefix))) - // Find and return the top candiates for each prefix. - .apply(Top.largestPerKey(candidatesPerPrefix) - .withHotKeyFanout(new HotKeyFanout())); + // Find and return the top candiates for each prefix. + .apply(Top.largestPerKey(candidatesPerPrefix) + .withHotKeyFanout(new HotKeyFanout())); } private static class HotKeyFanout implements SerializableFunction { @@ -188,7 +192,7 @@ public Integer apply(String input) { */ private static class ComputeTopRecursive extends PTransform, - PCollectionList>>> { + PCollectionList>>> { private final int candidatesPerPrefix; private final int minPrefix; @@ -216,42 +220,42 @@ public void processElement(ProcessContext c) { @Override public PCollectionList>> apply( - PCollection input) { - if (minPrefix > 10) { - // Base case, partitioning to return the output in the expected format. - return input + PCollection input) { + if (minPrefix > 10) { + // Base case, partitioning to return the output in the expected format. + return input .apply(new ComputeTopFlat(candidatesPerPrefix, minPrefix)) .apply(Partition.of(2, new KeySizePartitionFn())); - } else { - // If a candidate is in the top N for prefix a...b, it must also be in the top - // N for a...bX for every X, which is typlically a much smaller set to consider. - // First, compute the top candidate for prefixes of size at least minPrefix + 1. - PCollectionList>> larger = input + } else { + // If a candidate is in the top N for prefix a...b, it must also be in the top + // N for a...bX for every X, which is typlically a much smaller set to consider. + // First, compute the top candidate for prefixes of size at least minPrefix + 1. + PCollectionList>> larger = input .apply(new ComputeTopRecursive(candidatesPerPrefix, minPrefix + 1)); - // Consider the top candidates for each prefix of length minPrefix + 1... - PCollection>> small = + // Consider the top candidates for each prefix of length minPrefix + 1... + PCollection>> small = PCollectionList - .of(larger.get(1).apply(ParDo.of(new FlattenTops()))) - // ...together with those (previously excluded) candidates of length - // exactly minPrefix... - .and(input.apply(Filter.byPredicate( - new SerializableFunction() { - @Override - public Boolean apply(CompletionCandidate c) { - return c.getValue().length() == minPrefix; - } - }))) - .apply("FlattenSmall", Flatten.pCollections()) - // ...set the key to be the minPrefix-length prefix... - .apply(ParDo.of(new AllPrefixes(minPrefix, minPrefix))) - // ...and (re)apply the Top operator to all of them together. - .apply(Top.largestPerKey(candidatesPerPrefix)); - - PCollection>> flattenLarger = larger - .apply("FlattenLarge", Flatten.>>pCollections()); - - return PCollectionList.of(flattenLarger).and(small); - } + .of(larger.get(1).apply(ParDo.of(new FlattenTops()))) + // ...together with those (previously excluded) candidates of length + // exactly minPrefix... + .and(input.apply(Filter.byPredicate( + new SerializableFunction() { + @Override + public Boolean apply(CompletionCandidate c) { + return c.getValue().length() == minPrefix; + } + }))) + .apply("FlattenSmall", Flatten.pCollections()) + // ...set the key to be the minPrefix-length prefix... + .apply(ParDo.of(new AllPrefixes(minPrefix, minPrefix))) + // ...and (re)apply the Top operator to all of them together. + .apply(Top.largestPerKey(candidatesPerPrefix)); + + PCollection>> flattenLarger = larger + .apply("FlattenLarge", Flatten.>>pCollections()); + + return PCollectionList.of(flattenLarger).and(small); + } } } @@ -270,7 +274,7 @@ public AllPrefixes(int minPrefix, int maxPrefix) { this.maxPrefix = maxPrefix; } @Override - public void processElement(ProcessContext c) { + public void processElement(ProcessContext c) { String word = c.element().value; for (int i = minPrefix; i <= Math.min(word.length(), maxPrefix); i++) { c.output(KV.of(word.substring(0, i), c.element())); @@ -353,12 +357,12 @@ public void processElement(ProcessContext c) { List completions = new ArrayList<>(); for (CompletionCandidate cc : c.element().getValue()) { completions.add(new TableRow() - .set("count", cc.getCount()) - .set("tag", cc.getValue())); + .set("count", cc.getCount()) + .set("tag", cc.getValue())); } TableRow row = new TableRow() - .set("prefix", c.element().getKey()) - .set("tags", completions); + .set("prefix", c.element().getKey()) + .set("tags", completions); c.output(row); } @@ -395,16 +399,15 @@ public void processElement(ProcessContext c) { entityBuilder.setKey(key); List candidates = new ArrayList<>(); + Map properties = new HashMap<>(); for (CompletionCandidate tag : c.element().getValue()) { Entity.Builder tagEntity = Entity.newBuilder(); - tagEntity.addProperty( - DatastoreHelper.makeProperty("tag", DatastoreHelper.makeValue(tag.value))); - tagEntity.addProperty( - DatastoreHelper.makeProperty("count", DatastoreHelper.makeValue(tag.count))); - candidates.add(DatastoreHelper.makeValue(tagEntity).setIndexed(false).build()); + properties.put("tag", makeValue(tag.value).build()); + properties.put("count", makeValue(tag.count).build()); + candidates.add(makeValue(tagEntity).build()); } - entityBuilder.addProperty( - DatastoreHelper.makeProperty("candidates", DatastoreHelper.makeValue(candidates))); + properties.put("candidates", makeValue(candidates).build()); + entityBuilder.putAllProperties(properties); c.output(entityBuilder.build()); } } @@ -425,7 +428,7 @@ private static interface Options extends ExamplePubsubTopicOptions, ExampleBigQu Boolean getRecursive(); void setRecursive(Boolean value); - @Description("Dataset entity kind") + @Description("Datastore entity kind") @Default.String("autocomplete-demo") String getKind(); void setKind(String value); @@ -476,16 +479,16 @@ public static void main(String[] args) throws IOException { // Create the pipeline. Pipeline p = Pipeline.create(options); PCollection>> toWrite = p - .apply(readSource) - .apply(ParDo.of(new ExtractHashtags())) - .apply(Window.into(windowFn)) - .apply(ComputeTopCompletions.top(10, options.getRecursive())); + .apply(readSource) + .apply(ParDo.of(new ExtractHashtags())) + .apply(Window.into(windowFn)) + .apply(ComputeTopCompletions.top(10, options.getRecursive())); if (options.getOutputToDatastore()) { toWrite - .apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind()))) - .apply(DatastoreIO.writeTo(MoreObjects.firstNonNull( - options.getOutputDataset(), options.getProject()))); + .apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind()))) + .apply(DatastoreIO.v1beta3().write().withProjectId(MoreObjects.firstNonNull( + options.getOutputDataset(), options.getProject()))); } if (options.getOutputToBigQuery()) { dataflowUtils.setupBigQueryTable(); diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java index eaf1e2053d..2f72f48d6e 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java @@ -16,23 +16,16 @@ package com.google.cloud.dataflow.examples.cookbook; -import static com.google.api.services.datastore.client.DatastoreHelper.getPropertyMap; -import static com.google.api.services.datastore.client.DatastoreHelper.getString; -import static com.google.api.services.datastore.client.DatastoreHelper.makeFilter; -import static com.google.api.services.datastore.client.DatastoreHelper.makeKey; -import static com.google.api.services.datastore.client.DatastoreHelper.makeValue; +import static com.google.datastore.v1beta3.client.DatastoreHelper.getString; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; -import com.google.api.services.datastore.DatastoreV1.Entity; -import com.google.api.services.datastore.DatastoreV1.Key; -import com.google.api.services.datastore.DatastoreV1.Property; -import com.google.api.services.datastore.DatastoreV1.PropertyFilter; -import com.google.api.services.datastore.DatastoreV1.Query; -import com.google.api.services.datastore.DatastoreV1.Value; import com.google.cloud.dataflow.examples.WordCount; import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.DatastoreIO; -import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreIO; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptions; @@ -41,6 +34,11 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.MapElements; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.datastore.v1beta3.Entity; +import com.google.datastore.v1beta3.Key; +import com.google.datastore.v1beta3.PropertyFilter; +import com.google.datastore.v1beta3.Query; +import com.google.datastore.v1beta3.Value; import java.util.Map; import java.util.UUID; @@ -87,7 +85,7 @@ public class DatastoreWordCount { static class GetContentFn extends DoFn { @Override public void processElement(ProcessContext c) { - Map props = getPropertyMap(c.element()); + Map props = c.element().getProperties(); Value value = props.get("content"); if (value != null) { c.output(getString(value)); @@ -104,7 +102,7 @@ public void processElement(ProcessContext c) { static Key makeAncestorKey(@Nullable String namespace, String kind) { Key.Builder keyBuilder = makeKey(kind, "root"); if (namespace != null) { - keyBuilder.getPartitionIdBuilder().setNamespace(namespace); + keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace); } return keyBuilder.build(); } @@ -134,12 +132,11 @@ public Entity makeEntity(String content) { // we must set the namespace on keyBuilder. TODO: Once partitionId inheritance is added, // we can simplify this code. if (namespace != null) { - keyBuilder.getPartitionIdBuilder().setNamespace(namespace); + keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace); } entityBuilder.setKey(keyBuilder.build()); - entityBuilder.addProperty(Property.newBuilder().setName("content") - .setValue(Value.newBuilder().setStringValue(content))); + entityBuilder.getProperties().put("content", makeValue(content).build()); return entityBuilder.build(); } @@ -165,6 +162,7 @@ public static interface Options extends PipelineOptions { String getOutput(); void setOutput(String value); + // Note: This maps to Project ID for v1beta3 version of datastore @Description("Dataset ID to read from datastore") @Validation.Required String getDataset(); @@ -194,12 +192,12 @@ public static interface Options extends PipelineOptions { * text input. Forces use of DirectPipelineRunner for local execution mode. */ public static void writeDataToDatastore(Options options) { - Pipeline p = Pipeline.create(options); - p.apply(TextIO.Read.named("ReadLines").from(options.getInput())) - .apply(ParDo.of(new CreateEntityFn(options.getNamespace(), options.getKind()))) - .apply(DatastoreIO.writeTo(options.getDataset())); + Pipeline p = Pipeline.create(options); + p.apply(TextIO.Read.named("ReadLines").from(options.getInput())) + .apply(ParDo.of(new CreateEntityFn(options.getNamespace(), options.getKind()))) + .apply(DatastoreIO.v1beta3().write().withProjectId(options.getDataset())); - p.run(); + p.run(); } /** @@ -228,13 +226,13 @@ public static void readDataFromDatastore(Options options) { Query query = makeAncestorKindQuery(options); // For Datastore sources, the read namespace can be set on the entire query. - DatastoreIO.Source source = DatastoreIO.source() - .withDataset(options.getDataset()) + V1Beta3.Read read = DatastoreIO.v1beta3().read() + .withProjectId(options.getDataset()) .withQuery(query) .withNamespace(options.getNamespace()); Pipeline p = Pipeline.create(options); - p.apply("ReadShakespeareFromDatastore", Read.from(source)) + p.apply("ReadShakespeareFromDatastore", read) .apply("StringifyEntity", ParDo.of(new GetContentFn())) .apply("CountWords", new WordCount.CountWords()) .apply("PrintWordCount", MapElements.via(new WordCount.FormatAsTextFn())) diff --git a/pom.xml b/pom.xml index d50c62ccf8..eeb4ed6370 100644 --- a/pom.xml +++ b/pom.xml @@ -76,6 +76,8 @@ v1b3-rev30-1.22.0 0.5.160222 v1beta2-rev1-4.0.0 + 1.0.0-beta.2 + 1.0.0-beta 1.22.0 0.13.1 19.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index 51827187e9..a4f158f931 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -751,6 +751,18 @@ 1.4.5 + + com.google.cloud.datastore + datastore-v1beta3-proto-client + ${datastore.client.version} + + + + com.google.cloud.datastore + datastore-v1beta3-protos + ${datastore.proto.version} + + com.google.cloud.bigdataoss util diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java index 3ae857f065..73df010300 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java @@ -26,7 +26,10 @@ /** * A {@link Coder} for {@link Entity} objects based on their encoded Protocol Buffer form. + * + * @deprecated use {@link com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder} instead. */ +@Deprecated public class EntityCoder extends AtomicCoder { @JsonCreator diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java index 7bf763cc28..f112f0e3b2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java @@ -173,7 +173,11 @@ * for security and permission related information specific to Datastore. * * @see com.google.cloud.dataflow.sdk.runners.PipelineRunner + * + * @deprecated replaced by {@link com.google.cloud.dataflow.sdk.io.datastore.DatastoreIO} */ + +@Deprecated @Experimental(Experimental.Kind.SOURCE_SINK) public class DatastoreIO { public static final String DEFAULT_HOST = "https://www.googleapis.com"; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java new file mode 100644 index 0000000000..f402dcbfc3 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.datastore; + +import com.google.cloud.dataflow.sdk.annotations.Experimental; + +/** + *

            {@link DatastoreIO} provides an API for reading from and writing to + * Google Cloud Datastore over different + * versions of the Datastore Client libraries. + * + *

            To use the v1beta3 version see {@link V1Beta3}. + */ +@Experimental(Experimental.Kind.SOURCE_SINK) +public class DatastoreIO { + + private DatastoreIO() {} + + /** + * Returns a {@link V1Beta3} that provides an API for accessing Datastore through v1beta3 version + * of Datastore Client library. + */ + public static V1Beta3 v1beta3() { + return new V1Beta3(); + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java new file mode 100644 index 0000000000..10c093745d --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java @@ -0,0 +1,991 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.datastore; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Verify.verify; +import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; +import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; +import static com.google.datastore.v1beta3.QueryResultBatch.MoreResultsType.NOT_FINISHED; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeAndFilter; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeUpsert; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; + +import com.google.api.client.auth.oauth2.Credential; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.BackOffUtils; +import com.google.api.client.util.Sleeper; +import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.SerializableCoder; +import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.Sink; +import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; +import com.google.cloud.dataflow.sdk.io.Sink.Writer; +import com.google.cloud.dataflow.sdk.options.GcpOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; +import com.google.cloud.dataflow.sdk.values.PBegin; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; +import com.google.common.primitives.Ints; +import com.google.datastore.v1beta3.CommitRequest; +import com.google.datastore.v1beta3.Entity; +import com.google.datastore.v1beta3.EntityResult; +import com.google.datastore.v1beta3.Key; +import com.google.datastore.v1beta3.Key.PathElement; +import com.google.datastore.v1beta3.PartitionId; +import com.google.datastore.v1beta3.Query; +import com.google.datastore.v1beta3.QueryResultBatch; +import com.google.datastore.v1beta3.RunQueryRequest; +import com.google.datastore.v1beta3.RunQueryResponse; +import com.google.datastore.v1beta3.client.Datastore; +import com.google.datastore.v1beta3.client.DatastoreException; +import com.google.datastore.v1beta3.client.DatastoreFactory; +import com.google.datastore.v1beta3.client.DatastoreHelper; +import com.google.datastore.v1beta3.client.DatastoreOptions; +import com.google.datastore.v1beta3.client.QuerySplitter; +import com.google.protobuf.Int32Value; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import javax.annotation.Nullable; + +/** + *

            {@link V1Beta3} provides an API to Read and Write {@link PCollection PCollections} of + * Google Cloud Datastore version v1beta3 + * {@link Entity} objects. + * + *

            This API currently requires an authentication workaround. To use {@link V1Beta3}, users + * must use the {@code gcloud} command line tool to get credentials for Datastore: + *

            + * $ gcloud auth login
            + * 
            + * + *

            To read a {@link PCollection} from a query to Datastore, use {@link V1Beta3#read} and + * its methods {@link V1Beta3.Read#withProjectId} and {@link V1Beta3.Read#withQuery} to + * specify the project to query and the query to read from. You can optionally provide a namespace + * to query within using {@link V1Beta3.Read#withNamespace}. + * + *

            For example: + * + *

             {@code
            + * // Read a query from Datastore
            + * PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
            + * Query query = ...;
            + * String projectId = "...";
            + *
            + * Pipeline p = Pipeline.create(options);
            + * PCollection entities = p.apply(
            + *     DatastoreIO.v1beta3().read()
            + *         .withProjectId(projectId)
            + *         .withQuery(query));
            + * } 
            + * + *

            Note: Normally, a Cloud Dataflow job will read from Cloud Datastore in parallel across + * many workers. However, when the {@link Query} is configured with a limit using + * {@link com.google.datastore.v1beta3.Query.Builder#setLimit(Int32Value)}, then + * all returned results will be read by a single Dataflow worker in order to ensure correct data. + * + *

            To write a {@link PCollection} to a Datastore, use {@link V1Beta3#write}, + * specifying the Cloud Datastore project to write to: + * + *

             {@code
            + * PCollection entities = ...;
            + * entities.apply(DatastoreIO.v1beta3().write().withProjectId(projectId));
            + * p.run();
            + * } 
            + * + *

            {@link Entity Entities} in the {@code PCollection} to be written must have complete + * {@link Key Keys}. Complete {@code Keys} specify the {@code name} and {@code id} of the + * {@code Entity}, where incomplete {@code Keys} do not. A {@code namespace} other than + * {@code projectId} default may be used by specifying it in the {@code Entity} {@code Keys}. + * + *

            {@code
            + * Key.Builder keyBuilder = DatastoreHelper.makeKey(...);
            + * keyBuilder.getPartitionIdBuilder().setNamespace(namespace);
            + * }
            + * + *

            {@code Entities} will be committed as upsert (update or insert) mutations. Please read + * Entities, Properties, and + * Keys for more information about {@code Entity} keys. + * + *

            Permissions

            + * Permission requirements depend on the {@code PipelineRunner} that is used to execute the + * Dataflow job. Please refer to the documentation of corresponding {@code PipelineRunner}s for + * more details. + * + *

            Please see Cloud Datastore Sign Up + * for security and permission related information specific to Datastore. + * + * @see com.google.cloud.dataflow.sdk.runners.PipelineRunner + */ +@Experimental(Experimental.Kind.SOURCE_SINK) +public class V1Beta3 { + + // A package-private constructor to prevent direct instantiation from outside of this package + V1Beta3() {} + + /** + * Datastore has a limit of 500 mutations per batch operation, so we flush + * changes to Datastore every 500 entities. + */ + private static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; + + /** + * Returns an empty {@link V1Beta3.Read} builder. Configure the source {@code projectId}, + * {@code query}, and optionally {@code namespace} using {@link V1Beta3.Read#withProjectId}, + * {@link V1Beta3.Read#withQuery}, and {@link V1Beta3.Read#withNamespace}. + */ + public V1Beta3.Read read() { + return new V1Beta3.Read(null, null, null); + } + + /** + * A {@link PTransform} that reads the result rows of a Datastore query as {@code Entity} + * objects. + * + * @see DatastoreIO + */ + public static class Read extends PTransform> { + @Nullable + private final String projectId; + + @Nullable + private final Query query; + + @Nullable + private final String namespace; + + /** + * Note that only {@code namespace} is really {@code @Nullable}. The other parameters may be + * {@code null} as a matter of build order, but if they are {@code null} at instantiation time, + * an error will be thrown. + */ + private Read(@Nullable String projectId, @Nullable Query query, @Nullable String namespace) { + this.projectId = projectId; + this.query = query; + this.namespace = namespace; + } + + /** + * Returns a new {@link V1Beta3.Read} that reads from the Datastore for the specified project. + */ + public V1Beta3.Read withProjectId(String projectId) { + checkNotNull(projectId, "projectId"); + return new V1Beta3.Read(projectId, query, namespace); + } + + /** + * Returns a new {@link V1Beta3.Read} that reads the results of the specified query. + * + *

            Note: Normally, {@code DatastoreIO} will read from Cloud Datastore in parallel + * across many workers. However, when the {@link Query} is configured with a limit using + * {@link Query.Builder#setLimit}, then all results will be read by a single worker in order + * to ensure correct results. + */ + public V1Beta3.Read withQuery(Query query) { + checkNotNull(query, "query"); + checkArgument(!query.hasLimit() || query.getLimit().getValue() > 0, + "Invalid query limit %s: must be positive", query.getLimit().getValue()); + return new V1Beta3.Read(projectId, query, namespace); + } + + /** + * Returns a new {@link V1Beta3.Read} that reads from the given namespace. + */ + public V1Beta3.Read withNamespace(String namespace) { + return new V1Beta3.Read(projectId, query, namespace); + } + + @Nullable + public Query getQuery() { + return query; + } + + @Nullable + public String getProjectId() { + return projectId; + } + + @Nullable + public String getNamespace() { + return namespace; + } + + @Override + public PCollection apply(PBegin input) { + return input.apply(com.google.cloud.dataflow.sdk.io.Read.from(getSource())); + } + + @Override + public void validate(PBegin input) { + checkNotNull(projectId, "projectId"); + checkNotNull(query, "query"); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull(DisplayData.item("projectId", projectId) + .withLabel("ProjectId")) + .addIfNotNull(DisplayData.item("namespace", namespace) + .withLabel("Namespace")) + .addIfNotNull(DisplayData.item("query", query.toString()) + .withLabel("Query")); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(getClass()) + .add("projectId", projectId) + .add("query", query) + .add("namespace", namespace) + .toString(); + } + + @VisibleForTesting + DatastoreSource getSource() { + return new DatastoreSource(projectId, query, namespace); + } + } + + /** + * Returns an empty {@link V1Beta3.Write} builder. Configure the destination + * {@code projectId} using {@link V1Beta3.Write#withProjectId}. + */ + public Write write() { + return new Write(null); + } + + /** + * A {@link PTransform} that writes {@link Entity} objects to Cloud Datastore. + * + * @see DatastoreIO + */ + public static class Write extends PTransform, PDone> { + @Nullable + private final String projectId; + + /** + * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if + * it is {@code null} at instantiation time, an error will be thrown. + */ + public Write(@Nullable String projectId) { + this.projectId = projectId; + } + + /** + * Returns a new {@link Write} that writes to the Cloud Datastore for the specified project. + */ + public Write withProjectId(String projectId) { + checkNotNull(projectId, "projectId"); + return new Write(projectId); + } + + @Override + public PDone apply(PCollection input) { + return input.apply( + com.google.cloud.dataflow.sdk.io.Write.to(new DatastoreSink(projectId))); + } + + @Override + public void validate(PCollection input) { + checkNotNull(projectId, "projectId"); + } + + @Nullable + public String getProjectId() { + return projectId; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(getClass()) + .add("projectId", projectId) + .toString(); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull(DisplayData.item("projectId", projectId) + .withLabel("Output Project")); + } + } + + /** + * A {@link com.google.cloud.dataflow.sdk.io.Source} that reads data from Datastore. + */ + static class DatastoreSource extends BoundedSource { + + @Override + public Coder getDefaultOutputCoder() { + return ProtoCoder.of(Entity.class); + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) { + return false; + } + + @Override + public List splitIntoBundles(long desiredBundleSizeBytes, + PipelineOptions options) throws Exception { + // Users may request a limit on the number of results. We can currently support this by + // simply disabling parallel reads and using only a single split. + if (query.hasLimit()) { + return ImmutableList.of(this); + } + + long numSplits; + try { + numSplits = Math.round(((double) getEstimatedSizeBytes(options)) / desiredBundleSizeBytes); + } catch (Exception e) { + // Fallback in case estimated size is unavailable. TODO: fix this, it's horrible. + numSplits = 12; + } + + // If the desiredBundleSize or number of workers results in 1 split, simply return + // a source that reads from the original query. + if (numSplits <= 1) { + return ImmutableList.of(this); + } + + List datastoreSplits; + try { + datastoreSplits = getSplitQueries(Ints.checkedCast(numSplits), options); + } catch (IllegalArgumentException | DatastoreException e) { + LOG.warn("Unable to parallelize the given query: {}", query, e); + return ImmutableList.of(this); + } + + ImmutableList.Builder splits = ImmutableList.builder(); + for (Query splitQuery : datastoreSplits) { + splits.add(new DatastoreSource(projectId, splitQuery, namespace)); + } + return splits.build(); + } + + @Override + public BoundedReader createReader(PipelineOptions pipelineOptions) throws IOException { + return new DatastoreReader(this, getDatastore(pipelineOptions)); + } + + @Override + public void validate() { + checkNotNull(query, "query"); + checkNotNull(projectId, "projectId"); + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + // Datastore provides no way to get a good estimate of how large the result of a query + // will be. As a rough approximation, we attempt to fetch the statistics of the whole + // entity kind being queried, using the __Stat_Kind__ system table, assuming exactly 1 kind + // is specified in the query. + // + // See https://cloud.google.com/datastore/docs/concepts/stats + if (mockEstimateSizeBytes != null) { + return mockEstimateSizeBytes; + } + + Datastore datastore = getDatastore(options); + if (query.getKindCount() != 1) { + throw new UnsupportedOperationException( + "Can only estimate size for queries specifying exactly 1 kind."); + } + String ourKind = query.getKind(0).getName(); + long latestTimestamp = queryLatestStatisticsTimestamp(datastore); + Query.Builder query = Query.newBuilder(); + if (namespace == null) { + query.addKindBuilder().setName("__Stat_Kind__"); + } else { + query.addKindBuilder().setName("__Ns_Stat_Kind__"); + } + query.setFilter(makeAndFilter( + makeFilter("kind_name", EQUAL, makeValue(ourKind)).build(), + makeFilter("timestamp", EQUAL, makeValue(latestTimestamp)).build())); + RunQueryRequest request = makeRequest(query.build()); + + long now = System.currentTimeMillis(); + RunQueryResponse response = datastore.runQuery(request); + LOG.info("Query for per-kind statistics took {}ms", System.currentTimeMillis() - now); + + QueryResultBatch batch = response.getBatch(); + if (batch.getEntityResultsCount() == 0) { + throw new NoSuchElementException( + "Datastore statistics for kind " + ourKind + " unavailable"); + } + Entity entity = batch.getEntityResults(0).getEntity(); + return entity.getProperties().get("entity_bytes").getIntegerValue(); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull(DisplayData.item("projectId", projectId) + .withLabel("ProjectId")) + .addIfNotNull(DisplayData.item("namespace", namespace) + .withLabel("Namespace")) + .addIfNotNull(DisplayData.item("query", query.toString()) + .withLabel("Query")); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(getClass()) + .add("projectId", projectId) + .add("query", query) + .add("namespace", namespace) + .toString(); + } + + private static final Logger LOG = LoggerFactory.getLogger(DatastoreSource.class); + private final String projectId; + private final Query query; + @Nullable + private final String namespace; + + /** For testing only. TODO: This could be much cleaner with dependency injection. */ + @Nullable + private QuerySplitter mockSplitter; + @Nullable + private Long mockEstimateSizeBytes; + + DatastoreSource(String projectId, Query query, @Nullable String namespace) { + this.projectId = projectId; + this.query = query; + this.namespace = namespace; + } + + /** + * A helper function to get the split queries, taking into account the optional + * {@code namespace} and whether there is a mock splitter. + */ + private List getSplitQueries(int numSplits, PipelineOptions options) + throws DatastoreException { + // If namespace is set, include it in the split request so splits are calculated accordingly. + PartitionId.Builder partitionBuilder = PartitionId.newBuilder(); + if (namespace != null) { + partitionBuilder.setNamespaceId(namespace); + } + + if (mockSplitter != null) { + // For testing. + return mockSplitter.getSplits(query, partitionBuilder.build(), numSplits, null); + } + + return DatastoreHelper.getQuerySplitter().getSplits( + query, partitionBuilder.build(), numSplits, getDatastore(options)); + } + + /** + * Builds a {@link RunQueryRequest} from the {@code query}, using the properties set on this + * {@code DatastoreSource}. For example, sets the {@code namespace} for the request. + */ + private RunQueryRequest makeRequest(Query query) { + RunQueryRequest.Builder requestBuilder = RunQueryRequest.newBuilder().setQuery(query); + if (namespace != null) { + requestBuilder.getPartitionIdBuilder().setNamespaceId(namespace); + } + return requestBuilder.build(); + } + + /** + * Datastore system tables with statistics are periodically updated. This method fetches + * the latest timestamp of statistics update using the {@code __Stat_Total__} table. + */ + private long queryLatestStatisticsTimestamp(Datastore datastore) throws DatastoreException { + Query.Builder query = Query.newBuilder(); + query.addKindBuilder().setName("__Stat_Total__"); + query.addOrder(makeOrder("timestamp", DESCENDING)); + query.setLimit(Int32Value.newBuilder().setValue(1)); + RunQueryRequest request = makeRequest(query.build()); + + long now = System.currentTimeMillis(); + RunQueryResponse response = datastore.runQuery(request); + LOG.info("Query for latest stats timestamp of project {} took {}ms", projectId, + System.currentTimeMillis() - now); + QueryResultBatch batch = response.getBatch(); + if (batch.getEntityResultsCount() == 0) { + throw new NoSuchElementException( + "Datastore total statistics for project " + projectId + " unavailable"); + } + Entity entity = batch.getEntityResults(0).getEntity(); + return entity.getProperties().get("timestamp").getTimestampValue().getNanos(); + } + + private Datastore getDatastore(PipelineOptions pipelineOptions) { + DatastoreOptions.Builder builder = + new DatastoreOptions.Builder() + .projectId(projectId) + .initializer( + new RetryHttpRequestInitializer() + ); + + Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); + if (credential != null) { + builder.credential(credential); + } + return DatastoreFactory.get().create(builder.build()); + } + + /** For testing only. */ + DatastoreSource withMockSplitter(QuerySplitter splitter) { + DatastoreSource res = new DatastoreSource(projectId, query, namespace); + res.mockSplitter = splitter; + res.mockEstimateSizeBytes = mockEstimateSizeBytes; + return res; + } + + /** For testing only. */ + DatastoreSource withMockEstimateSizeBytes(Long estimateSizeBytes) { + DatastoreSource res = new DatastoreSource(projectId, query, namespace); + res.mockSplitter = mockSplitter; + res.mockEstimateSizeBytes = estimateSizeBytes; + return res; + } + + @VisibleForTesting + Query getQuery() { + return query; + } + } + + /** + * A {@link DatastoreSource.Reader} over the records from a query of the datastore. + * + *

            Timestamped records are currently not supported. + * All records implicitly have the timestamp of {@code BoundedWindow.TIMESTAMP_MIN_VALUE}. + */ + @VisibleForTesting + static class DatastoreReader extends BoundedSource.BoundedReader { + private final DatastoreSource source; + + /** + * Datastore to read from. + */ + private final Datastore datastore; + + /** + * True if more results may be available. + */ + private boolean moreResults; + + /** + * Iterator over records. + */ + private java.util.Iterator entities; + + /** + * Current batch of query results. + */ + private QueryResultBatch currentBatch; + + /** + * Maximum number of results to request per query. + * + *

            Must be set, or it may result in an I/O error when querying + * Cloud Datastore. + */ + private static final int QUERY_BATCH_LIMIT = 500; + + /** + * Remaining user-requested limit on the number of sources to return. If the user did not set a + * limit, then this variable will always have the value {@link Integer#MAX_VALUE} and will never + * be decremented. + */ + private int userLimit; + + private volatile boolean done = false; + + private Entity currentEntity; + + /** + * Returns a DatastoreReader with DatastoreSource and Datastore object set. + * + * @param datastore a datastore connection to use. + */ + public DatastoreReader(DatastoreSource source, Datastore datastore) { + this.source = source; + this.datastore = datastore; + // If the user set a limit on the query, remember it. Otherwise pin to MAX_VALUE. + userLimit = source.query.hasLimit() + ? source.query.getLimit().getValue() : Integer.MAX_VALUE; + } + + @Override + public Entity getCurrent() { + return currentEntity; + } + + @Override + public final long getSplitPointsConsumed() { + return done ? 1 : 0; + } + + @Override + public final long getSplitPointsRemaining() { + return done ? 0 : 1; + } + + @Override + public boolean start() throws IOException { + return advance(); + } + + @Override + public boolean advance() throws IOException { + if (entities == null || (!entities.hasNext() && moreResults)) { + try { + entities = getIteratorAndMoveCursor(); + } catch (DatastoreException e) { + throw new IOException(e); + } + } + + if (entities == null || !entities.hasNext()) { + currentEntity = null; + done = true; + return false; + } + + currentEntity = entities.next().getEntity(); + return true; + } + + @Override + public void close() throws IOException { + // Nothing + } + + @Override + public DatastoreSource getCurrentSource() { + return source; + } + + @Override + public DatastoreSource splitAtFraction(double fraction) { + // Not supported. + return null; + } + + @Override + public Double getFractionConsumed() { + // Not supported. + return null; + } + + /** + * Returns an iterator over the next batch of records for the query + * and updates the cursor to get the next batch as needed. + * Query has specified limit and offset from InputSplit. + */ + private Iterator getIteratorAndMoveCursor() throws DatastoreException { + Query.Builder query = source.query.toBuilder().clone(); + query.setLimit(Int32Value.newBuilder().setValue(Math.min(userLimit, QUERY_BATCH_LIMIT))); + if (currentBatch != null && !currentBatch.getEndCursor().isEmpty()) { + query.setStartCursor(currentBatch.getEndCursor()); + } + + RunQueryRequest request = source.makeRequest(query.build()); + RunQueryResponse response = datastore.runQuery(request); + + currentBatch = response.getBatch(); + + // MORE_RESULTS_AFTER_LIMIT is not implemented yet: + // https://groups.google.com/forum/#!topic/gcd-discuss/iNs6M1jA2Vw, so + // use result count to determine if more results might exist. + int numFetch = currentBatch.getEntityResultsCount(); + if (source.query.hasLimit()) { + verify(userLimit >= numFetch, + "Expected userLimit %s >= numFetch %s, because query limit %s should be <= userLimit", + userLimit, numFetch, query.getLimit()); + userLimit -= numFetch; + } + moreResults = + // User-limit does not exist (so userLimit == MAX_VALUE) and/or has not been satisfied. + (userLimit > 0) + // All indications from the API are that there are/may be more results. + && ((numFetch == QUERY_BATCH_LIMIT) + || (currentBatch.getMoreResults() == NOT_FINISHED)); + + // May receive a batch of 0 results if the number of records is a multiple + // of the request limit. + if (numFetch == 0) { + return null; + } + + return currentBatch.getEntityResultsList().iterator(); + } + } + + /** + * A {@link Sink} that writes data to Datastore. + */ + static class DatastoreSink extends Sink { + final String projectId; + + public DatastoreSink(String projectId) { + this.projectId = projectId; + } + + @Override + public void validate(PipelineOptions options) { + checkNotNull(projectId, "projectId"); + } + + @Override + public DatastoreWriteOperation createWriteOperation(PipelineOptions options) { + return new DatastoreWriteOperation(this); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull(DisplayData.item("projectId", projectId) + .withLabel("Output Project")); + } + } + + /** + * A {@link WriteOperation} that will manage a parallel write to a Datastore sink. + */ + private static class DatastoreWriteOperation + extends WriteOperation { + private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriteOperation.class); + + private final DatastoreSink sink; + + public DatastoreWriteOperation(DatastoreSink sink) { + this.sink = sink; + } + + @Override + public Coder getWriterResultCoder() { + return SerializableCoder.of(DatastoreWriteResult.class); + } + + @Override + public void initialize(PipelineOptions options) throws Exception {} + + /** + * Finalizes the write. Logs the number of entities written to the Datastore. + */ + @Override + public void finalize(Iterable writerResults, PipelineOptions options) + throws Exception { + long totalEntities = 0; + for (DatastoreWriteResult result : writerResults) { + totalEntities += result.entitiesWritten; + } + LOG.info("Wrote {} elements.", totalEntities); + } + + @Override + public DatastoreWriter createWriter(PipelineOptions options) throws Exception { + DatastoreOptions.Builder builder = + new DatastoreOptions.Builder() + .projectId(sink.projectId) + .initializer(new RetryHttpRequestInitializer()); + Credential credential = options.as(GcpOptions.class).getGcpCredential(); + if (credential != null) { + builder.credential(credential); + } + Datastore datastore = DatastoreFactory.get().create(builder.build()); + + return new DatastoreWriter(this, datastore); + } + + @Override + public DatastoreSink getSink() { + return sink; + } + } + + /** + * {@link Writer} that writes entities to a Datastore Sink. Entities are written in batches, + * where the maximum batch size is {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. Entities + * are committed as upsert mutations (either update if the key already exists, or insert if it is + * a new key). If an entity does not have a complete key (i.e., it has no name or id), the bundle + * will fail. + * + *

            See + * Datastore: Entities, Properties, and Keys for information about entity keys and upsert + * mutations. + * + *

            Commits are non-transactional. If a commit fails because of a conflict over an entity + * group, the commit will be retried (up to {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT} + * times). + * + *

            Visible for testing purposes. + */ + @VisibleForTesting + static class DatastoreWriter extends Writer { + private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriter.class); + private final DatastoreWriteOperation writeOp; + private final Datastore datastore; + private long totalWritten = 0; + + // Visible for testing. + final List entities = new ArrayList<>(); + + /** + * Since a bundle is written in batches, we should retry the commit of a batch in order to + * prevent transient errors from causing the bundle to fail. + */ + private static final int MAX_RETRIES = 5; + + /** + * Initial backoff time for exponential backoff for retry attempts. + */ + private static final int INITIAL_BACKOFF_MILLIS = 5000; + + /** + * Returns true if a Datastore key is complete. A key is complete if its last element + * has either an id or a name. + */ + static boolean isValidKey(Key key) { + List elementList = key.getPathList(); + if (elementList.isEmpty()) { + return false; + } + PathElement lastElement = elementList.get(elementList.size() - 1); + return (lastElement.getId() != 0 || !lastElement.getName().isEmpty()); + } + + DatastoreWriter(DatastoreWriteOperation writeOp, Datastore datastore) { + this.writeOp = writeOp; + this.datastore = datastore; + } + + @Override + public void open(String uId) throws Exception {} + + /** + * Writes an entity to the Datastore. Writes are batched, up to {@link + * V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. If an entity does not have a complete key, an + * {@link IllegalArgumentException} will be thrown. + */ + @Override + public void write(Entity value) throws Exception { + // Verify that the entity to write has a complete key. + if (!isValidKey(value.getKey())) { + throw new IllegalArgumentException( + "Entities to be written to the Datastore must have complete keys"); + } + + entities.add(value); + + if (entities.size() >= V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT) { + flushBatch(); + } + } + + /** + * Flushes any pending batch writes and returns a DatastoreWriteResult. + */ + @Override + public DatastoreWriteResult close() throws Exception { + if (entities.size() > 0) { + flushBatch(); + } + return new DatastoreWriteResult(totalWritten); + } + + @Override + public DatastoreWriteOperation getWriteOperation() { + return writeOp; + } + + /** + * Writes a batch of entities to the Datastore. + * + *

            If a commit fails, it will be retried (up to {@link DatastoreWriter#MAX_RETRIES} + * times). All entities in the batch will be committed again, even if the commit was partially + * successful. If the retry limit is exceeded, the last exception from the Datastore will be + * thrown. + * + * @throws DatastoreException if the commit fails or IOException or InterruptedException if + * backing off between retries fails. + */ + private void flushBatch() throws DatastoreException, IOException, InterruptedException { + LOG.debug("Writing batch of {} entities", entities.size()); + Sleeper sleeper = Sleeper.DEFAULT; + BackOff backoff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_MILLIS); + + while (true) { + // Batch upsert entities. + try { + CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); + for (Entity entity: entities) { + commitRequest.addMutations(makeUpsert(entity)); + } + commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); + datastore.commit(commitRequest.build()); + // Break if the commit threw no exception. + break; + } catch (DatastoreException exception) { + // Only log the code and message for potentially-transient errors. The entire exception + // will be propagated upon the last retry. + LOG.error("Error writing to the Datastore ({}): {}", exception.getCode(), + exception.getMessage()); + if (!BackOffUtils.next(sleeper, backoff)) { + LOG.error("Aborting after {} retries.", MAX_RETRIES); + throw exception; + } + } + } + totalWritten += entities.size(); + LOG.debug("Successfully wrote {} entities", entities.size()); + entities.clear(); + } + } + + private static class DatastoreWriteResult implements Serializable { + final long entitiesWritten; + + public DatastoreWriteResult(long recordsWritten) { + this.entitiesWritten = recordsWritten; + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java new file mode 100644 index 0000000000..18f547f594 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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. + */ + +/** + *

            Provides an API for reading from and writing to + * Google Cloud Datastore over different + * versions of the Datastore Client libraries. + */ +package com.google.cloud.dataflow.sdk.io.datastore; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java index 7a9c87733b..23940f50d9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java @@ -620,7 +620,10 @@ public static ApiSurface getSdkApiSurface() throws IOException { .pruningPrefix("com.google.bigtable.v1") .pruningPrefix("com.google.cloud.bigtable.config") .pruningPrefix("com.google.cloud.bigtable.grpc.Bigtable*Name") + .pruningPrefix("com.google.datastore") .pruningPrefix("com.google.protobuf") + .pruningPrefix("com.google.rpc") + .pruningPrefix("com.google.type") .pruningPrefix("org.joda.time") .pruningPrefix("org.apache.avro") .pruningPrefix("org.junit") diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java index f2192e62e6..f6693f0fc8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java @@ -22,7 +22,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; -import com.google.api.services.datastore.DatastoreV1.Entity; import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages; import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; @@ -149,9 +148,9 @@ public void testDurationIsNotProto2() { } @Test - public void testEntityIsDeterministic() throws NonDeterministicException { - // Cloud Datastore's Entities can be encoded deterministically. - verifyDeterministic(ProtoCoder.of(Entity.class)); + public void testDurationIsDeterministic() throws NonDeterministicException { + // Duration can be encoded deterministically. + verifyDeterministic(ProtoCoder.of(Duration.class)); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java new file mode 100644 index 0000000000..0f9733eda5 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java @@ -0,0 +1,582 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.io.datastore; + +import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreReader; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreSource; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreWriter; +import com.google.cloud.dataflow.sdk.options.GcpOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.util.TestCredential; +import com.google.common.collect.Lists; +import com.google.datastore.v1beta3.Entity; +import com.google.datastore.v1beta3.EntityResult; +import com.google.datastore.v1beta3.Key; +import com.google.datastore.v1beta3.KindExpression; +import com.google.datastore.v1beta3.PartitionId; +import com.google.datastore.v1beta3.PropertyFilter; +import com.google.datastore.v1beta3.Query; +import com.google.datastore.v1beta3.QueryResultBatch; +import com.google.datastore.v1beta3.RunQueryRequest; +import com.google.datastore.v1beta3.RunQueryResponse; +import com.google.datastore.v1beta3.Value; +import com.google.datastore.v1beta3.client.Datastore; +import com.google.datastore.v1beta3.client.DatastoreHelper; +import com.google.datastore.v1beta3.client.QuerySplitter; +import com.google.protobuf.Int32Value; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; + +/** + * Tests for {@link V1Beta3}. + */ +@RunWith(JUnit4.class) +public class V1Beta3Test { + private static final String PROJECT_ID = "testProject"; + private static final String NAMESPACE = "testNamespace"; + private static final String KIND = "testKind"; + private static final Query QUERY; + static { + Query.Builder q = Query.newBuilder(); + q.addKindBuilder().setName(KIND); + QUERY = q.build(); + } + private V1Beta3.Read initialRead; + + @Mock + Datastore mockDatastore; + + @Rule + public final ExpectedException thrown = ExpectedException.none(); + + @Rule public final ExpectedLogs logged = ExpectedLogs.none(DatastoreSource.class); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + initialRead = DatastoreIO.v1beta3().read() + .withProjectId(PROJECT_ID).withQuery(QUERY).withNamespace(NAMESPACE); + } + + /** + * Helper function to create a test {@code DataflowPipelineOptions}. + */ + static final GcpOptions testPipelineOptions() { + GcpOptions options = PipelineOptionsFactory.as(GcpOptions.class); + options.setGcpCredential(new TestCredential()); + return options; + } + + @Test + public void testBuildRead() throws Exception { + V1Beta3.Read read = DatastoreIO.v1beta3().read() + .withProjectId(PROJECT_ID).withQuery(QUERY).withNamespace(NAMESPACE); + assertEquals(QUERY, read.getQuery()); + assertEquals(PROJECT_ID, read.getProjectId()); + assertEquals(NAMESPACE, read.getNamespace()); + } + + /** + * {@link #testBuildRead} but constructed in a different order. + */ + @Test + public void testBuildReadAlt() throws Exception { + V1Beta3.Read read = DatastoreIO.v1beta3().read() + .withProjectId(PROJECT_ID).withNamespace(NAMESPACE).withQuery(QUERY); + assertEquals(QUERY, read.getQuery()); + assertEquals(PROJECT_ID, read.getProjectId()); + assertEquals(NAMESPACE, read.getNamespace()); + } + + @Test + public void testReadValidationFailsProject() throws Exception { + V1Beta3.Read read = DatastoreIO.v1beta3().read().withQuery(QUERY); + thrown.expect(NullPointerException.class); + thrown.expectMessage("project"); + read.validate(null); + } + + @Test + public void testReadValidationFailsQuery() throws Exception { + V1Beta3.Read read = DatastoreIO.v1beta3().read().withProjectId(PROJECT_ID); + thrown.expect(NullPointerException.class); + thrown.expectMessage("query"); + read.validate(null); + } + + @Test + public void testReadValidationFailsQueryLimitZero() throws Exception { + Query invalidLimit = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(0)).build(); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Invalid query limit 0: must be positive"); + + DatastoreIO.v1beta3().read().withQuery(invalidLimit); + } + + @Test + public void testReadValidationFailsQueryLimitNegative() throws Exception { + Query invalidLimit = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(-5)).build(); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Invalid query limit -5: must be positive"); + + DatastoreIO.v1beta3().read().withQuery(invalidLimit); + } + + @Test + public void testReadValidationSucceedsNamespace() throws Exception { + V1Beta3.Read read = DatastoreIO.v1beta3().read().withProjectId(PROJECT_ID).withQuery(QUERY); + /* Should succeed, as a null namespace is fine. */ + read.validate(null); + } + + @Test + public void testReadDisplayData() { + V1Beta3.Read read = DatastoreIO.v1beta3().read() + .withProjectId(PROJECT_ID) + .withQuery(QUERY) + .withNamespace(NAMESPACE); + + DisplayData displayData = DisplayData.from(read); + + assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); + assertThat(displayData, hasDisplayItem("query", QUERY.toString())); + assertThat(displayData, hasDisplayItem("namespace", NAMESPACE)); + } + + @Test + public void testWriteDoesNotAllowNullProject() throws Exception { + thrown.expect(NullPointerException.class); + thrown.expectMessage("projectId"); + + DatastoreIO.v1beta3().write().withProjectId(null); + } + + @Test + public void testWriteValidationFailsWithNoProject() throws Exception { + V1Beta3.Write write = DatastoreIO.v1beta3().write(); + + thrown.expect(NullPointerException.class); + thrown.expectMessage("projectId"); + + write.validate(null); + } + + @Test + public void testSinkValidationSucceedsWithProject() throws Exception { + V1Beta3.Write write = DatastoreIO.v1beta3().write().withProjectId(PROJECT_ID); + write.validate(null); + } + + @Test + public void testWriteDisplayData() { + V1Beta3.Write write = DatastoreIO.v1beta3().write() + .withProjectId(PROJECT_ID); + + DisplayData displayData = DisplayData.from(write); + + assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); + } + + @Test + public void testQuerySplitBasic() throws Exception { + KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); + Query query = Query.newBuilder().addKind(mykind).build(); + + List mockSplits = new ArrayList<>(); + for (int i = 0; i < 8; ++i) { + mockSplits.add( + Query.newBuilder() + .addKind(mykind) + .setFilter( + DatastoreHelper.makeFilter("foo", PropertyFilter.Operator.EQUAL, + Value.newBuilder().setIntegerValue(i).build())) + .build()); + } + + QuerySplitter splitter = mock(QuerySplitter.class); + /* No namespace */ + PartitionId partition = PartitionId.newBuilder().build(); + when(splitter.getSplits(any(Query.class), eq(partition), eq(8), any(Datastore.class))) + .thenReturn(mockSplits); + + DatastoreSource io = initialRead + .withNamespace(null) + .withQuery(query) + .getSource() + .withMockSplitter(splitter) + .withMockEstimateSizeBytes(8 * 1024L); + + List bundles = io.splitIntoBundles(1024, testPipelineOptions()); + assertEquals(8, bundles.size()); + for (int i = 0; i < 8; ++i) { + DatastoreSource bundle = bundles.get(i); + Query bundleQuery = bundle.getQuery(); + assertEquals("mykind", bundleQuery.getKind(0).getName()); + assertEquals(i, bundleQuery.getFilter().getPropertyFilter().getValue().getIntegerValue()); + } + } + + /** + * Verifies that when namespace is set in the source, the split request includes the namespace. + */ + @Test + public void testSourceWithNamespace() throws Exception { + QuerySplitter splitter = mock(QuerySplitter.class); + DatastoreSource io = initialRead + .getSource() + .withMockSplitter(splitter) + .withMockEstimateSizeBytes(8 * 1024L); + + io.splitIntoBundles(1024, testPipelineOptions()); + + PartitionId partition = PartitionId.newBuilder().setNamespaceId(NAMESPACE).build(); + verify(splitter).getSplits(eq(QUERY), eq(partition), eq(8), any(Datastore.class)); + verifyNoMoreInteractions(splitter); + } + + @Test + public void testQuerySplitWithZeroSize() throws Exception { + KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); + Query query = Query.newBuilder().addKind(mykind).build(); + + List mockSplits = Lists.newArrayList( + Query.newBuilder() + .addKind(mykind) + .build()); + + QuerySplitter splitter = mock(QuerySplitter.class); + when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class))) + .thenReturn(mockSplits); + + DatastoreSource io = initialRead + .withQuery(query) + .getSource() + .withMockSplitter(splitter) + .withMockEstimateSizeBytes(0L); + + List bundles = io.splitIntoBundles(1024, testPipelineOptions()); + assertEquals(1, bundles.size()); + verify(splitter, never()) + .getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class)); + DatastoreSource bundle = bundles.get(0); + Query bundleQuery = bundle.getQuery(); + assertEquals("mykind", bundleQuery.getKind(0).getName()); + assertFalse(bundleQuery.hasFilter()); + } + + /** + * Tests that a query with a user-provided limit field does not split, and does not even + * interact with a query splitter. + */ + @Test + public void testQueryDoesNotSplitWithLimitSet() throws Exception { + // Minimal query with a limit + Query query = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(5)).build(); + + // Mock query splitter, should not be invoked. + QuerySplitter splitter = mock(QuerySplitter.class); + when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(2), any(Datastore.class))) + .thenThrow(new AssertionError("Splitter should not be invoked")); + + List bundles = + initialRead + .withQuery(query) + .getSource() + .withMockSplitter(splitter) + .splitIntoBundles(1024, testPipelineOptions()); + + assertEquals(1, bundles.size()); + assertEquals(query, bundles.get(0).getQuery()); + verifyNoMoreInteractions(splitter); + } + + /** + * Tests that when {@link QuerySplitter} cannot split a query, {@link V1Beta3} falls back to + * a single split. + */ + @Test + public void testQuerySplitterThrows() throws Exception { + // Mock query splitter that throws IllegalArgumentException + IllegalArgumentException exception = + new IllegalArgumentException("query not supported by splitter"); + QuerySplitter splitter = mock(QuerySplitter.class); + when( + splitter.getSplits( + any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class))) + .thenThrow(exception); + + Query query = Query.newBuilder().addKind(KindExpression.newBuilder().setName("myKind")).build(); + List bundles = + initialRead + .withQuery(query) + .getSource() + .withMockSplitter(splitter) + .withMockEstimateSizeBytes(10240L) + .splitIntoBundles(1024, testPipelineOptions()); + + assertEquals(1, bundles.size()); + assertEquals(query, bundles.get(0).getQuery()); + verify(splitter, times(1)) + .getSplits( + any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class)); + logged.verifyWarn("Unable to parallelize the given query", exception); + } + + @Test + public void testQuerySplitSizeUnavailable() throws Exception { + KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); + Query query = Query.newBuilder().addKind(mykind).build(); + + List mockSplits = Lists.newArrayList(Query.newBuilder().addKind(mykind).build()); + + QuerySplitter splitter = mock(QuerySplitter.class); + when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(12), any(Datastore.class))) + .thenReturn(mockSplits); + + DatastoreSource io = initialRead + .withQuery(query) + .getSource() + .withMockSplitter(splitter) + .withMockEstimateSizeBytes(8 * 1024L); + + DatastoreSource spiedIo = spy(io); + when(spiedIo.getEstimatedSizeBytes(any(PipelineOptions.class))) + .thenThrow(new NoSuchElementException()); + + List bundles = spiedIo.splitIntoBundles(1024, testPipelineOptions()); + assertEquals(1, bundles.size()); + verify(splitter, never()) + .getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class)); + DatastoreSource bundle = bundles.get(0); + Query bundleQuery = bundle.getQuery(); + assertEquals("mykind", bundleQuery.getKind(0).getName()); + assertFalse(bundleQuery.hasFilter()); + } + + /** + * Test building a Write using builder methods. + */ + @Test + public void testBuildWrite() throws Exception { + V1Beta3.Write write = DatastoreIO.v1beta3().write().withProjectId(PROJECT_ID); + assertEquals(PROJECT_ID, write.getProjectId()); + } + + /** + * Test the detection of complete and incomplete keys. + */ + @Test + public void testHasNameOrId() { + Key key; + // Complete with name, no ancestor + key = makeKey("bird", "finch").build(); + assertTrue(DatastoreWriter.isValidKey(key)); + + // Complete with id, no ancestor + key = makeKey("bird", 123).build(); + assertTrue(DatastoreWriter.isValidKey(key)); + + // Incomplete, no ancestor + key = makeKey("bird").build(); + assertFalse(DatastoreWriter.isValidKey(key)); + + // Complete with name and ancestor + key = makeKey("bird", "owl").build(); + key = makeKey(key, "bird", "horned").build(); + assertTrue(DatastoreWriter.isValidKey(key)); + + // Complete with id and ancestor + key = makeKey("bird", "owl").build(); + key = makeKey(key, "bird", 123).build(); + assertTrue(DatastoreWriter.isValidKey(key)); + + // Incomplete with ancestor + key = makeKey("bird", "owl").build(); + key = makeKey(key, "bird").build(); + assertFalse(DatastoreWriter.isValidKey(key)); + + key = makeKey().build(); + assertFalse(DatastoreWriter.isValidKey(key)); + } + + /** + * Test that entities with incomplete keys cannot be updated. + */ + @Test + public void testAddEntitiesWithIncompleteKeys() throws Exception { + Key key = makeKey("bird").build(); + Entity entity = Entity.newBuilder().setKey(key).build(); + DatastoreWriter writer = new DatastoreWriter(null, mockDatastore); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Entities to be written to the Datastore must have complete keys"); + + writer.write(entity); + } + + /** + * Test that entities are added to the batch to update. + */ + @Test + public void testAddingEntities() throws Exception { + List expected = Lists.newArrayList( + Entity.newBuilder().setKey(makeKey("bird", "jay").build()).build(), + Entity.newBuilder().setKey(makeKey("bird", "condor").build()).build(), + Entity.newBuilder().setKey(makeKey("bird", "robin").build()).build()); + + List allEntities = Lists.newArrayList(expected); + Collections.shuffle(allEntities); + + DatastoreWriter writer = new DatastoreWriter(null, mockDatastore); + writer.open("test_id"); + for (Entity entity : allEntities) { + writer.write(entity); + } + + assertEquals(expected.size(), writer.entities.size()); + assertThat(writer.entities, containsInAnyOrder(expected.toArray())); + } + + /** Datastore batch API limit in number of records per query. */ + private static final int DATASTORE_QUERY_BATCH_LIMIT = 500; + + /** + * A helper function that creates mock {@link Entity} results in response to a query. Always + * indicates that more results are available, unless the batch is limited to fewer than + * {@link #DATASTORE_QUERY_BATCH_LIMIT} results. + */ + private static RunQueryResponse mockResponseForQuery(Query q) { + // Every query V1Beta3 sends should have a limit. + assertTrue(q.hasLimit()); + + // The limit should be in the range [1, DATASTORE_QUERY_BATCH_LIMIT] + int limit = q.getLimit().getValue(); + assertThat(limit, greaterThanOrEqualTo(1)); + assertThat(limit, lessThanOrEqualTo(DATASTORE_QUERY_BATCH_LIMIT)); + + // Create the requested number of entities. + List entities = new ArrayList<>(limit); + for (int i = 0; i < limit; ++i) { + entities.add( + EntityResult.newBuilder() + .setEntity(Entity.newBuilder().setKey(makeKey("key" + i, i + 1))) + .build()); + } + + // Fill out the other parameters on the returned result batch. + RunQueryResponse.Builder ret = RunQueryResponse.newBuilder(); + ret.getBatchBuilder() + .addAllEntityResults(entities) + .setEntityResultType(EntityResult.ResultType.FULL) + .setMoreResults( + limit == DATASTORE_QUERY_BATCH_LIMIT + ? QueryResultBatch.MoreResultsType.NOT_FINISHED + : QueryResultBatch.MoreResultsType.NO_MORE_RESULTS); + + return ret.build(); + } + + /** Helper function to run a test reading from a limited-result query. */ + private void runQueryLimitReadTest(int numEntities) throws Exception { + // An empty query to read entities. + Query query = Query.newBuilder().setLimit( + Int32Value.newBuilder().setValue(numEntities)).build(); + V1Beta3.Read read = DatastoreIO.v1beta3().read().withQuery(query).withProjectId("mockProject"); + + // Use mockResponseForQuery to generate results. + when(mockDatastore.runQuery(any(RunQueryRequest.class))) + .thenAnswer( + new Answer() { + @Override + public RunQueryResponse answer(InvocationOnMock invocation) throws Throwable { + Query q = ((RunQueryRequest) invocation.getArguments()[0]).getQuery(); + return mockResponseForQuery(q); + } + }); + + // Actually instantiate the reader. + DatastoreReader reader = new DatastoreReader(read.getSource(), mockDatastore); + + // Simply count the number of results returned by the reader. + assertTrue(reader.start()); + int resultCount = 1; + while (reader.advance()) { + resultCount++; + } + reader.close(); + + // Validate the number of results. + assertEquals(numEntities, resultCount); + } + + /** Tests reading with a query limit less than one batch. */ + @Test + public void testReadingWithLimitOneBatch() throws Exception { + runQueryLimitReadTest(5); + } + + /** Tests reading with a query limit more than one batch, and not a multiple. */ + @Test + public void testReadingWithLimitMultipleBatches() throws Exception { + runQueryLimitReadTest(DATASTORE_QUERY_BATCH_LIMIT + 5); + } + + /** Tests reading several batches, using an exact multiple of batch size results. */ + @Test + public void testReadingWithLimitMultipleBatchesExactMultiple() throws Exception { + runQueryLimitReadTest(5 * DATASTORE_QUERY_BATCH_LIMIT); + } +} + From ea37f6fcba7e9234be22e1fa304a6df6a37af1c4 Mon Sep 17 00:00:00 2001 From: Ben Chambers Date: Wed, 13 Jul 2016 12:59:35 -0700 Subject: [PATCH 476/751] Refactor StateSampler with parameterized schedule (#334) * Refactor StateSampler with parameterized schedule Encapsulate the logic to using SheduledExecutorService inside the current default scheduler. * fixup! Review comments * Minor tweaks --- .../sdk/util/common/worker/StateSampler.java | 182 ++++++++++++------ 1 file changed, 118 insertions(+), 64 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java index 00d3b3b904..2e4c1f5a70 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java @@ -16,18 +16,22 @@ package com.google.cloud.dataflow.sdk.util.common.worker; +import com.google.api.client.util.NanoClock; import com.google.cloud.dataflow.sdk.util.common.Counter; import com.google.cloud.dataflow.sdk.util.common.CounterSet; +import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.Closeable; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; @@ -41,6 +45,94 @@ @ThreadSafe public class StateSampler implements AutoCloseable { + /** + * An interface for scheduling state sampling. + */ + public static interface SampleScheduler { + Closeable scheduleSampling(StateSampler sampler); + } + + /** + * An implementation of {@link SampleScheduler} using a scheduled executor service and two + * callbacks per sample. The sampling uses "stratified sampling" -- in every bucket of + * samplingPeriodMs we choose a random point to sample. This prevents pathological behavior in + * case some states happen to occur at a similar period. + * + *

            The current implementation uses a fixed-rate timer with a period samplingPeriodMs as a + * trampoline to a one-shot random timer which fires with a random delay within + * samplingPeriodMs. + */ + @VisibleForTesting + static final class DefaultScheduler implements SampleScheduler { + private static final int NUM_EXECUTOR_THREADS = 16; + private static final ScheduledExecutorService EXECUTOR_SERVICE = + Executors.newScheduledThreadPool(NUM_EXECUTOR_THREADS, + new ThreadFactoryBuilder().setDaemon(true).build()); + + private final long samplingPeriodMs; + + @VisibleForTesting + DefaultScheduler(long samplingPeriodMs) { + this.samplingPeriodMs = samplingPeriodMs; + } + + @Override + public Closeable scheduleSampling(final StateSampler sampler) { + return new Closeable() { + private ScheduledFuture invocationFuture = null; + private ScheduledFuture invocationTriggerFuture = EXECUTOR_SERVICE.scheduleAtFixedRate( + new Runnable() { + @Override + public void run() { + long delay = ThreadLocalRandom.current().nextInt((int) samplingPeriodMs); + synchronized (this) { + if (invocationFuture != null) { + invocationFuture.cancel(false); + } + invocationFuture = EXECUTOR_SERVICE.schedule( + new Runnable() { + @Override + public void run() { + sampler.run(); + } + }, + delay, + TimeUnit.MILLISECONDS); + } + } + }, + 0, + samplingPeriodMs, + TimeUnit.MILLISECONDS); + + @Override + public void close() throws IOException { + synchronized (this) { + if (invocationTriggerFuture != null) { + invocationTriggerFuture.cancel(false); + invocationTriggerFuture = null; + } + if (invocationFuture != null) { + invocationFuture.cancel(false); + invocationFuture = null; + } + } + } + }; + } + } + + public static final SampleScheduler NOOP_SCHEDULER = new SampleScheduler() { + @Override + public Closeable scheduleSampling(StateSampler sampler) { + return new Closeable() { + @Override + public void close() throws IOException { + } + }; + } + }; + /** Different kinds of states. */ public enum StateKind { /** IO, user code, etc. */ @@ -82,20 +174,10 @@ public enum StateKind { */ private long stateTimestampNs = 0; - /** Using a fixed number of timers for all StateSampler objects. */ - private static final int NUM_EXECUTOR_THREADS = 16; - - private static final ScheduledExecutorService executorService = - Executors.newScheduledThreadPool(NUM_EXECUTOR_THREADS, - new ThreadFactoryBuilder().setDaemon(true).build()); - - private Random rand = new Random(); - private List callbacks = new ArrayList<>(); - private ScheduledFuture invocationTriggerFuture = null; - - private ScheduledFuture invocationFuture = null; + private final Closeable sampleSchedule; + private final NanoClock nanoClock; /** * Constructs a new {@link StateSampler} that can be used to obtain @@ -105,15 +187,18 @@ public enum StateKind { * @param prefix the prefix of the counter names for the states * @param counterSetMutator the {@link CounterSet.AddCounterMutator} * used to create a counter for each distinct state - * @param samplingPeriodMs the sampling period in milliseconds + * @param scheduler the sample scheduler to use */ public StateSampler(String prefix, CounterSet.AddCounterMutator counterSetMutator, - final long samplingPeriodMs) { + SampleScheduler scheduler, + NanoClock nanoClock) { this.prefix = prefix; this.counterSetMutator = counterSetMutator; - currentState = DO_NOT_SAMPLE; - scheduleSampling(samplingPeriodMs); + this.nanoClock = nanoClock; + this.currentState = DO_NOT_SAMPLE; + this.sampleSchedule = scheduler.scheduleSampling(this); + this.stateTimestampNs = nanoClock.nanoTime(); } /** @@ -124,56 +209,30 @@ public StateSampler(String prefix, * @param prefix the prefix of the counter names for the states * @param counterSetMutator the {@link CounterSet.AddCounterMutator} * used to create a counter for each distinct state + * @param samplingPeriodMs the sampling period in milliseconds */ public StateSampler(String prefix, - CounterSet.AddCounterMutator counterSetMutator) { - this(prefix, counterSetMutator, DEFAULT_SAMPLING_PERIOD_MS); + CounterSet.AddCounterMutator counterSetMutator, + final long samplingPeriodMs) { + this(prefix, counterSetMutator, new DefaultScheduler(samplingPeriodMs), NanoClock.SYSTEM); } /** - * Called by the constructor to schedule sampling at the given period. + * Constructs a new {@link StateSampler} that can be used to obtain + * an approximate breakdown of the time spent by an execution + * context in various states, as a fraction of the total time. * - *

            Should not be overridden by sub-classes unless they want to change - * or disable the automatic sampling of state. + * @param prefix the prefix of the counter names for the states + * @param counterSetMutator the {@link CounterSet.AddCounterMutator} + * used to create a counter for each distinct state */ - protected void scheduleSampling(final long samplingPeriodMs) { - // Here "stratified sampling" is used, which makes sure that there's 1 uniformly chosen sampled - // point in every bucket of samplingPeriodMs, to prevent pathological behavior in case some - // states happen to occur at a similar period. - // The current implementation uses a fixed-rate timer with a period samplingPeriodMs as a - // trampoline to a one-shot random timer which fires with a random delay within - // samplingPeriodMs. - stateTimestampNs = System.nanoTime(); - invocationTriggerFuture = - executorService.scheduleAtFixedRate( - new Runnable() { - @Override - public void run() { - long delay = rand.nextInt((int) samplingPeriodMs); - synchronized (StateSampler.this) { - if (invocationFuture != null) { - invocationFuture.cancel(false); - } - invocationFuture = - executorService.schedule( - new Runnable() { - @Override - public void run() { - StateSampler.this.run(); - } - }, - delay, - TimeUnit.MILLISECONDS); - } - } - }, - 0, - samplingPeriodMs, - TimeUnit.MILLISECONDS); + public StateSampler(String prefix, + CounterSet.AddCounterMutator counterSetMutator) { + this(prefix, counterSetMutator, DEFAULT_SAMPLING_PERIOD_MS); } public synchronized void run() { - long startTimestampNs = System.nanoTime(); + long startTimestampNs = nanoClock.nanoTime(); int state = currentState; if (state != DO_NOT_SAMPLE) { StateKind kind = null; @@ -189,14 +248,9 @@ public synchronized void run() { } @Override - public synchronized void close() { + public synchronized void close() throws IOException { currentState = DO_NOT_SAMPLE; - if (invocationTriggerFuture != null) { - invocationTriggerFuture.cancel(false); - } - if (invocationFuture != null) { - invocationFuture.cancel(false); - } + sampleSchedule.close(); } /** From 4da482540bbada2d3e411744c3d96f20f7233d35 Mon Sep 17 00:00:00 2001 From: lukecwik Date: Wed, 13 Jul 2016 18:00:43 -0400 Subject: [PATCH 477/751] Remove reference to non-existent class. (#338) --- .../java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java index fcfe1d8f2f..c51f70d5f5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java @@ -45,7 +45,6 @@ public class ApiSurfaceTest { @Test public void testOurApiSurface() throws Exception { ApiSurface checkedApiSurface = ApiSurface.getSdkApiSurface() - .pruningClassName("com.google.cloud.dataflow.sdk.runners.worker.StateFetcher") .pruningClassName("com.google.cloud.dataflow.sdk.util.common.ReflectHelpers") .pruningClassName("com.google.cloud.dataflow.sdk.DataflowMatchers") .pruningClassName("com.google.cloud.dataflow.sdk.TestUtils") From 933bda87fbc5eb95331c9a0e0d4a24e9d4e5fd2d Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Thu, 14 Jul 2016 08:27:58 -0700 Subject: [PATCH 478/751] Release Info: fix official name of SDK (#339) --- .../com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java index 39b30054f1..538ab960d9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java @@ -47,7 +47,7 @@ public static DataflowReleaseInfo getReleaseInfo() { return LazyInit.INSTANCE; } - @Key private String name = "Google Cloud Dataflow Java SDK"; + @Key private String name = "Google Cloud Dataflow SDK for Java"; @Key private String version = "Unknown"; /** Provides the SDK name. */ From 88148b4074156b5cc62de8f77ad322951e677440 Mon Sep 17 00:00:00 2001 From: Ryan Culbertson Date: Fri, 15 Jul 2016 20:14:57 -0400 Subject: [PATCH 479/751] Clarify RequiresWindowAccess error message (#332) An error message is printed when a DoFn needs access to the window but does not implement RequiresWindowAccess. This PR changes to the error message to print the interface name instead of just "RequiresWindow", which makes it more clear which interface the user should use. --- .../java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index 37aacb0688..5cd3350e80 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -434,7 +434,7 @@ public T sideInput(PCollectionView view) { public BoundedWindow window() { if (!(fn instanceof RequiresWindowAccess)) { throw new UnsupportedOperationException( - "window() is only available in the context of a DoFn marked as RequiresWindow."); + "window() is only available in the context of a DoFn marked as RequiresWindowAccess."); } return Iterables.getOnlyElement(windows()); } From 6c8d879a1168ca0bebc4caf4faef6b1119134021 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Mon, 18 Jul 2016 16:07:20 -0700 Subject: [PATCH 480/751] Modified Javadoc to reflect Values (#340) --- .../java/com/google/cloud/dataflow/sdk/transforms/Values.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java index d84bc779ec..c9026e969c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java @@ -26,7 +26,7 @@ *

            Example of use: *

             {@code
              * PCollection> wordCounts = ...;
            - * PCollection counts = wordCounts.apply(Values.create());
            + * PCollection counts = wordCounts.apply(Values.create());
              * } 
            * *

            Each output element has the same timestamp and is in the same windows From 002aa6183416d9dd81f989060825637a4376b835 Mon Sep 17 00:00:00 2001 From: Ben Chambers Date: Mon, 18 Jul 2016 16:27:15 -0700 Subject: [PATCH 481/751] Start sampling *after* initialization (#341) --- .../cloud/dataflow/sdk/util/common/worker/StateSampler.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java index 2e4c1f5a70..613c9406ba 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java @@ -197,8 +197,12 @@ public StateSampler(String prefix, this.counterSetMutator = counterSetMutator; this.nanoClock = nanoClock; this.currentState = DO_NOT_SAMPLE; - this.sampleSchedule = scheduler.scheduleSampling(this); this.stateTimestampNs = nanoClock.nanoTime(); + + // Schedule sampling. It should be assumed that as soon as this call + // is made, sampling may happen. Therefore, it should be the final + // step of initialization. + this.sampleSchedule = scheduler.scheduleSampling(this); } /** From ae26ceb929f417854b396fbe878fcca922706f8b Mon Sep 17 00:00:00 2001 From: bchambers Date: Thu, 21 Jul 2016 10:30:34 -0700 Subject: [PATCH 482/751] Switch StateSampler to Closeable --- .../sdk/util/common/worker/StateSampler.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java index 613c9406ba..125e398663 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java @@ -43,7 +43,7 @@ * regular intervals, with adjustment for scheduling delay. */ @ThreadSafe -public class StateSampler implements AutoCloseable { +public class StateSampler implements Closeable { /** * An interface for scheduling state sampling. @@ -359,7 +359,7 @@ public int setState(String name, StateKind kind) { } /** - * Returns an AutoCloseable {@link ScopedState} that will perform a + * Returns an {@link Closeable} {@link ScopedState} that will perform a * state transition to the given state, and will automatically reset * the state to the prior state upon closing. * @@ -390,9 +390,10 @@ public String getPrefix() { * *

            Thread-safe. */ - public class ScopedState implements AutoCloseable { - private StateSampler sampler; - private int previousState; + public class ScopedState implements Closeable { + private final StateSampler sampler; + private final int previousState; + private boolean closed = false; private ScopedState(StateSampler sampler, int previousState) { this.sampler = sampler; @@ -401,7 +402,10 @@ private ScopedState(StateSampler sampler, int previousState) { @Override public void close() { - sampler.setState(previousState); + if (!closed) { + closed = true; + sampler.setState(previousState); + } } } From e910b4da5e20988068c237a35eab2cc38f594ac6 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 21 Jul 2016 23:30:09 -0700 Subject: [PATCH 483/751] sdk-all: do not repackage BulkOptions Also part of Bigtable public API surface --- sdk/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/pom.xml b/sdk/pom.xml index a4f158f931..4d1d4aa156 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -370,6 +370,7 @@ com.google.cloud.dataflow.sdk.repackaged.com.google.cloud.bigtable com.google.cloud.bigtable.config.BigtableOptions* + com.google.cloud.bigtable.config.BulkOptions* com.google.cloud.bigtable.config.CredentialOptions* com.google.cloud.bigtable.config.RetryOptions* com.google.cloud.bigtable.grpc.BigtableClusterName From 411c84b80736128949e98217775e6503ddf70c53 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 26 Jul 2016 11:41:11 -0700 Subject: [PATCH 484/751] Add KafkaIO to Contrib (#345) Add KafkaIO to Contrib KafkaIO is an Unbounded source for reading from Apache Kafka. Backports KafkaIO from Apache Beam. See apache/incubator-beam 7b175dff8303b24cb92702db5b5a1a4691435bb1 --- .travis.yml | 2 + contrib/kafka/pom.xml | 173 ++ .../contrib/kafka/KafkaCheckpointMark.java | 74 + .../cloud/dataflow/contrib/kafka/KafkaIO.java | 1612 +++++++++++++++++ .../dataflow/contrib/kafka/KafkaRecord.java | 80 + .../contrib/kafka/KafkaRecordCoder.java | 122 ++ .../dataflow/contrib/kafka/package-info.java | 20 + .../dataflow/contrib/kafka/KafkaIOTest.java | 674 +++++++ 8 files changed, 2757 insertions(+) create mode 100644 contrib/kafka/pom.xml create mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java create mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java create mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java create mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java create mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java create mode 100644 contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java diff --git a/.travis.yml b/.travis.yml index 2f5ed182c5..51926a3d8c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,7 +30,9 @@ before_install: install: - travis_retry mvn install clean -U -DskipTests=true + - travis_retry mvn -f contrib/kafka/pom.xml install clean -U -DskipTests=true script: - travis_retry mvn $MAVEN_OVERRIDE install -U + - travis_retry mvn -f contrib/kafka/pom.xml $MAVEN_OVERRIDE install -U - travis_retry travis/test_wordcount.sh diff --git a/contrib/kafka/pom.xml b/contrib/kafka/pom.xml new file mode 100644 index 0000000000..f47ed574f9 --- /dev/null +++ b/contrib/kafka/pom.xml @@ -0,0 +1,173 @@ + + + + 4.0.0 + + jar + + com.google.cloud.dataflow + google-cloud-dataflow-java-contrib-kafka + Google Cloud Dataflow Kafka IO Library + Library to read Kafka topics. + 0.1.0-SNAPSHOT + + + [1.6.0, 2.0.0) + 0.9.0.1 + + 19.0 + 1.3 + 2.7.0 + 2.4 + 4.11 + 1.7.14 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.12 + + + com.puppycrawl.tools + checkstyle + 6.6 + + + + ../../checkstyle.xml + true + true + true + + + + + check + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + true + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + + attach-sources + compile + + jar + + + + attach-test-sources + test-compile + + test-jar + + + + + + + + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-all + ${dataflow.version} + + + + org.apache.kafka + kafka-clients + ${kafka.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + joda-time + joda-time + ${joda.version} + + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + + com.google.guava + guava + ${guava.version} + + + + + org.hamcrest + hamcrest-all + test + ${hamcrest.version} + + + + junit + junit + test + ${junit.version} + + + + org.slf4j + slf4j-jdk14 + test + ${slf4j.version} + + + diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java new file mode 100644 index 0000000000..a9231de6e0 --- /dev/null +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.kafka; + +import com.google.cloud.dataflow.sdk.coders.DefaultCoder; +import com.google.cloud.dataflow.sdk.coders.SerializableCoder; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; + +import org.apache.kafka.common.TopicPartition; + +import java.io.IOException; +import java.io.Serializable; +import java.util.List; + +/** + * Checkpoint for an unbounded KafkaIO.Read. Consists of Kafka topic name, partition id, and the + * latest offset consumed so far. + */ +@DefaultCoder(SerializableCoder.class) +public class KafkaCheckpointMark implements UnboundedSource.CheckpointMark, Serializable { + + private final List partitions; + + public KafkaCheckpointMark(List partitions) { + this.partitions = partitions; + } + + public List getPartitions() { + return partitions; + } + + @Override + public void finalizeCheckpoint() throws IOException { + /* nothing to do */ + + // We might want to support committing offset in Kafka for better resume point when the job + // is restarted (checkpoint is not available for job restarts). + } + + /** + * A tuple to hold topic, partition, and offset that comprise the checkpoint for a single + * partition. + */ + public static class PartitionMark implements Serializable { + private final TopicPartition topicPartition; + private final long offset; + + public PartitionMark(TopicPartition topicPartition, long offset) { + this.topicPartition = topicPartition; + this.offset = offset; + } + + public TopicPartition getTopicPartition() { + return topicPartition; + } + + public long getOffset() { + return offset; + } + } +} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java new file mode 100644 index 0000000000..a18062da56 --- /dev/null +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java @@ -0,0 +1,1612 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.kafka; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark.PartitionMark; +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.SerializableCoder; +import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.io.Read.Unbounded; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; +import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.ExposedByteArrayInputStream; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PBegin; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; +import com.google.common.base.Joiner; +import com.google.common.base.Optional; +import com.google.common.collect.ComparisonChain; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import com.google.common.io.Closeables; + +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.Callback; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.apache.kafka.common.PartitionInfo; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.errors.WakeupException; +import org.apache.kafka.common.serialization.ByteArrayDeserializer; +import org.apache.kafka.common.serialization.Serializer; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.annotation.Nullable; + +/** + * An unbounded source and a sink for Kafka topics. Kafka + * version 0.9 and above are supported. + * + *

            Reading from Kafka topics

            + * + *

            KafkaIO source returns unbounded collection of Kafka records as {@code + * PCollection>}. A {@link KafkaRecord} includes basic metadata like + * topic-partition and offset, along with key and value associated with a Kafka record. + * + *

            Although most applications consumer single topic, the source can be configured to consume + * multiple topics or even a specific set of {@link TopicPartition}s. + * + *

            To configure a Kafka source, you must specify at the minimum Kafka bootstrapServers + * and one or more topics to consume. The following example illustrates various options for + * configuring the source : + * + *

            {@code
            + *
            + *  pipeline
            + *    .apply(KafkaIO.read()
            + *       .withBootstrapServers("broker_1:9092,broker_2:9092")
            + *       .withTopics(ImmutableList.of("topic_a", "topic_b"))
            + *       // above two are required configuration. returns PCollection
            + *
            + *       // rest of the settings are optional :
            + *
            + *       // set a Coder for Key and Value (note the change to return type)
            + *       .withKeyCoder(BigEndianLongCoder.of()) // PCollection
            + *       .withValueCoder(StringUtf8Coder.of())  // PCollection
            + *
            + *       // you can further customize KafkaConsumer used to read the records by adding more
            + *       // settings for ConsumerConfig. e.g :
            + *       .updateConsumerProperties(ImmutableMap.of("receive.buffer.bytes", 1024 * 1024))
            + *
            + *       // custom function for calculating record timestamp (default is processing time)
            + *       .withTimestampFn(new MyTypestampFunction())
            + *
            + *       // custom function for watermark (default is record timestamp)
            + *       .withWatermarkFn(new MyWatermarkFunction())
            + *
            + *       // finally, if you don't need Kafka metadata, you can drop it
            + *       .withoutMetadata() // PCollection>
            + *    )
            + *    .apply(Values.create()) // PCollection
            + *     ...
            + * }
            + * + *

            Partition Assignment and Checkpointing

            The Kafka partitions are evenly distributed among + * splits (workers). Dataflow checkpointing is fully supported and each split can resume from + * previous checkpoint. See {@link UnboundedKafkaSource#generateInitialSplits(int, PipelineOptions)} + * for more details on splits and checkpoint support. + * + *

            When the pipeline starts for the first time without any checkpoint, the source starts + * consuming from the latest offsets. You can override this behavior to consume from the + * beginning by setting appropriate appropriate properties in {@link ConsumerConfig}, through {@link + * Read#updateConsumerProperties(Map)}. + * + *

            Writing to Kafka

            + * + * KafkaIO sink supports writing key-value pairs to a Kafka topic. Users can also write just the + * values. To configure a Kafka sink, you must specify at the minimum Kafka + * bootstrapServers and the topic to write to. The following example illustrates various + * options for configuring the sink: + * + *
            {@code
            + *
            + *  PCollection> kvColl = ...;
            + *  kvColl.apply(KafkaIO.write()
            + *       .withBootstrapServers("broker_1:9092,broker_2:9092")
            + *       .withTopic("results")
            + *
            + *       // set Coder for Key and Value
            + *       .withKeyCoder(BigEndianLongCoder.of())
            + *       .withValueCoder(StringUtf8Coder.of())
            + *
            + *       // you can further customize KafkaProducer used to write the records by adding more
            + *       // settings for ProducerConfig. e.g, to enable compression :
            + *       .updateProducerProperties(ImmutableMap.of("compression.type", "gzip"))
            + *    );
            + * }
            + * + * Often you might want to write just values without any keys to Kafka. Use {@code values()} to + * write records with default empty(null) key: + * + *
            {@code
            + *  PCollection strings = ...;
            + *  strings.apply(KafkaIO.write()
            + *      .withBootstrapServers("broker_1:9092,broker_2:9092")
            + *      .withTopic("results")
            + *      .withValueCoder(StringUtf8Coder.of()) // just need coder for value
            + *      .values() // writes values to Kafka with default key
            + *    );
            + * }
            + * + *

            Advanced Kafka Configuration

            KafakIO allows setting most of the properties in {@link + * ConsumerConfig} for source or in {@link ProducerConfig} for sink. E.g. if you would like to + * enable offset auto commit (for external monitoring or other purposes), you can set + * "group.id", "enable.auto.commit", etc. + */ +public class KafkaIO { + + /** + * Creates an uninitialized {@link Read} {@link PTransform}. Before use, basic Kafka configuration + * should set with {@link Read#withBootstrapServers(String)} and {@link Read#withTopics(List)}. + * Other optional settings include key and value coders, custom timestamp and watermark + * functions. + */ + public static Read read() { + return new Read( + new ArrayList(), + new ArrayList(), + ByteArrayCoder.of(), + ByteArrayCoder.of(), + Read.KAFKA_9_CONSUMER_FACTORY_FN, + Read.DEFAULT_CONSUMER_PROPERTIES, + Long.MAX_VALUE, + null); + } + + /** + * Creates an uninitialized {@link Write} {@link PTransform}. Before use, Kafka configuration + * should be set with {@link Write#withBootstrapServers(String)} and {@link Write#withTopic} along + * with {@link Coder}s for (optional) key and values. + */ + public static Write write() { + return new Write( + null, ByteArrayCoder.of(), ByteArrayCoder.of(), TypedWrite.DEFAULT_PRODUCER_PROPERTIES); + } + + ///////////////////////// Read Support \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + + /** + * A {@link PTransform} to read from Kafka topics. See {@link KafkaIO} for more information on + * usage and configuration. + */ + public static class Read extends TypedRead { + + /** + * Returns a new {@link Read} with Kafka consumer pointing to {@code bootstrapServers}. + */ + public Read withBootstrapServers(String bootstrapServers) { + return updateConsumerProperties( + ImmutableMap.of( + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers)); + } + + /** + * Returns a new {@link Read} that reads from the topics. All the partitions are from each of + * the topics is read. See {@link UnboundedKafkaSource#generateInitialSplits(int, + * PipelineOptions)} for description of how the partitions are distributed among the splits. + */ + public Read withTopics(List topics) { + checkState(topicPartitions.isEmpty(), "Only topics or topicPartitions can be set, not both"); + + return new Read( + ImmutableList.copyOf(topics), + topicPartitions, + keyCoder, + valueCoder, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * Returns a new {@link Read} that reads from the partitions. This allows reading only a subset + * of partitions for one or more topics when (if ever) needed. See {@link + * UnboundedKafkaSource#generateInitialSplits(int, PipelineOptions)} for description of how the + * partitions are distributed among the splits. + */ + public Read withTopicPartitions(List topicPartitions) { + checkState(topics.isEmpty(), "Only topics or topicPartitions can be set, not both"); + + return new Read( + topics, + ImmutableList.copyOf(topicPartitions), + keyCoder, + valueCoder, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * Returns a new {@link Read} with {@link Coder} for key bytes. + */ + public Read withKeyCoder(Coder keyCoder) { + return new Read( + topics, + topicPartitions, + keyCoder, + valueCoder, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * Returns a new {@link Read} with {@link Coder} for value bytes. + */ + public Read withValueCoder(Coder valueCoder) { + return new Read( + topics, + topicPartitions, + keyCoder, + valueCoder, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * A factory to create Kafka {@link Consumer} from consumer configuration. This is useful for + * supporting another version of Kafka consumer. Default is {@link KafkaConsumer}. + */ + public Read withConsumerFactoryFn( + SerializableFunction, Consumer> consumerFactoryFn) { + return new Read( + topics, + topicPartitions, + keyCoder, + valueCoder, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * Update consumer configuration with new properties. + */ + public Read updateConsumerProperties(Map configUpdates) { + + Map config = + updateKafkaProperties(consumerConfig, IGNORED_CONSUMER_PROPERTIES, configUpdates); + + return new Read( + topics, + topicPartitions, + keyCoder, + valueCoder, + consumerFactoryFn, + config, + maxNumRecords, + maxReadTime); + } + + /** + * Similar to {@link com.google.cloud.dataflow.sdk.io.Read.Unbounded#withMaxNumRecords(long)}. + * Mainly used for tests and demo applications. + */ + public Read withMaxNumRecords(long maxNumRecords) { + return new Read( + topics, + topicPartitions, + keyCoder, + valueCoder, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + null); + } + + /** + * Similar to {@link com.google.cloud.dataflow.sdk.io.Read.Unbounded#withMaxReadTime(Duration)}. + * Mainly used for tests and demo applications. + */ + public Read withMaxReadTime(Duration maxReadTime) { + return new Read( + topics, + topicPartitions, + keyCoder, + valueCoder, + consumerFactoryFn, + consumerConfig, + Long.MAX_VALUE, + maxReadTime); + } + + /////////////////////////////////////////////////////////////////////////////////////// + + private Read( + List topics, + List topicPartitions, + Coder keyCoder, + Coder valueCoder, + SerializableFunction, Consumer> consumerFactoryFn, + Map consumerConfig, + long maxNumRecords, + @Nullable Duration maxReadTime) { + + super( + topics, + topicPartitions, + keyCoder, + valueCoder, + null, + null, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * A set of properties that are not required or don't make sense for our consumer. + */ + private static final Map IGNORED_CONSUMER_PROPERTIES = + ImmutableMap.of( + ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, + "Set keyCoder instead", + ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, + "Set valueCoder instead" + // "group.id", "enable.auto.commit", "auto.commit.interval.ms" : + // lets allow these, applications can have better resume point for restarts. + ); + + // set config defaults + private static final Map DEFAULT_CONSUMER_PROPERTIES = + ImmutableMap.of( + ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, + ByteArrayDeserializer.class.getName(), + ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, + ByteArrayDeserializer.class.getName(), + + // Use large receive buffer. Once KAFKA-3135 is fixed, this _may_ not be required. + // with default value of of 32K, It takes multiple seconds between successful polls. + // All the consumer work is done inside poll(), with smaller send buffer size, it + // takes many polls before a 1MB chunk from the server is fully read. In my testing + // about half of the time select() inside kafka consumer waited for 20-30ms, though + // the server had lots of data in tcp send buffers on its side. Compared to default, + // this setting increased throughput increased by many fold (3-4x). + ConsumerConfig.RECEIVE_BUFFER_CONFIG, + 512 * 1024, + + // default to latest offset when we are not resuming. + ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, + "latest", + // disable auto commit of offsets. we don't require group_id. could be enabled by user. + ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, + false); + + // default Kafka 0.9 Consumer supplier. + private static final SerializableFunction, Consumer> + KAFKA_9_CONSUMER_FACTORY_FN = + new SerializableFunction, Consumer>() { + public Consumer apply(Map config) { + return new KafkaConsumer<>(config); + } + }; + } + + /** + * A {@link PTransform} to read from Kafka topics. See {@link KafkaIO} for more information on + * usage and configuration. + */ + public static class TypedRead extends PTransform>> { + + /** + * A function to assign a timestamp to a record. Default is processing timestamp. + */ + public TypedRead withTimestampFn2( + SerializableFunction, Instant> timestampFn) { + checkNotNull(timestampFn); + return new TypedRead( + topics, + topicPartitions, + keyCoder, + valueCoder, + timestampFn, + watermarkFn, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * A function to calculate watermark after a record. Default is last record timestamp + * + * @see #withTimestampFn(SerializableFunction) + */ + public TypedRead withWatermarkFn2( + SerializableFunction, Instant> watermarkFn) { + checkNotNull(watermarkFn); + return new TypedRead( + topics, + topicPartitions, + keyCoder, + valueCoder, + timestampFn, + watermarkFn, + consumerFactoryFn, + consumerConfig, + maxNumRecords, + maxReadTime); + } + + /** + * A function to assign a timestamp to a record. Default is processing timestamp. + */ + public TypedRead withTimestampFn(SerializableFunction, Instant> timestampFn) { + checkNotNull(timestampFn); + return withTimestampFn2(unwrapKafkaAndThen(timestampFn)); + } + + /** + * A function to calculate watermark after a record. Default is last record timestamp + * + * @see #withTimestampFn(SerializableFunction) + */ + public TypedRead withWatermarkFn(SerializableFunction, Instant> watermarkFn) { + checkNotNull(watermarkFn); + return withWatermarkFn2(unwrapKafkaAndThen(watermarkFn)); + } + + /** + * Returns a {@link PTransform} for PCollection of {@link KV}, dropping Kafka metatdata. + */ + public PTransform>> withoutMetadata() { + return new TypedWithoutMetadata(this); + } + + @Override + public PCollection> apply(PBegin input) { + // Handles unbounded source to bounded conversion if maxNumRecords or maxReadTime is set. + Unbounded> unbounded = + com.google.cloud.dataflow.sdk.io.Read.from(makeSource()); + + PTransform>> transform = unbounded; + + if (maxNumRecords < Long.MAX_VALUE) { + transform = unbounded.withMaxNumRecords(maxNumRecords); + } else if (maxReadTime != null) { + transform = unbounded.withMaxReadTime(maxReadTime); + } + + return input.getPipeline().apply(transform); + } + + //////////////////////////////////////////////////////////////////////////////////////// + + protected final List topics; + protected final List topicPartitions; // mutually exclusive with topics + protected final Coder keyCoder; + protected final Coder valueCoder; + @Nullable protected final SerializableFunction, Instant> timestampFn; + @Nullable protected final SerializableFunction, Instant> watermarkFn; + protected final SerializableFunction, Consumer> + consumerFactoryFn; + protected final Map consumerConfig; + protected final long maxNumRecords; // bounded read, mainly for testing + protected final Duration maxReadTime; // bounded read, mainly for testing + + private TypedRead( + List topics, + List topicPartitions, + Coder keyCoder, + Coder valueCoder, + @Nullable SerializableFunction, Instant> timestampFn, + @Nullable SerializableFunction, Instant> watermarkFn, + SerializableFunction, Consumer> consumerFactoryFn, + Map consumerConfig, + long maxNumRecords, + @Nullable Duration maxReadTime) { + super("KafkaIO.Read"); + + this.topics = topics; + this.topicPartitions = topicPartitions; + this.keyCoder = keyCoder; + this.valueCoder = valueCoder; + this.timestampFn = timestampFn; + this.watermarkFn = watermarkFn; + this.consumerFactoryFn = consumerFactoryFn; + this.consumerConfig = consumerConfig; + this.maxNumRecords = maxNumRecords; + this.maxReadTime = maxReadTime; + } + + /** + * Creates an {@link UnboundedSource, ?>} with the configuration in {@link + * TypedRead}. Primary use case is unit tests, should not be used in an application. + */ + @VisibleForTesting + UnboundedSource, com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> + makeSource() { + return new UnboundedKafkaSource( + -1, + topics, + topicPartitions, + keyCoder, + valueCoder, + timestampFn, + Optional.fromNullable(watermarkFn), + consumerFactoryFn, + consumerConfig); + } + + // utility method to convert KafkRecord to user KV before applying user functions + private static + SerializableFunction, OutT> unwrapKafkaAndThen( + final SerializableFunction, OutT> fn) { + return new SerializableFunction, OutT>() { + public OutT apply(KafkaRecord record) { + return fn.apply(record.getKV()); + } + }; + } + } + + /** + * A {@link PTransform} to read from Kafka topics. Similar to {@link KafkaIO.TypedRead}, but + * removes Kafka metatdata and returns a {@link PCollection} of {@link KV}. See {@link KafkaIO} + * for more information on usage and configuration of reader. + */ + public static class TypedWithoutMetadata extends PTransform>> { + + private final TypedRead typedRead; + + TypedWithoutMetadata(TypedRead read) { + super("KafkaIO.Read"); + this.typedRead = read; + } + + @Override + public PCollection> apply(PBegin begin) { + return typedRead + .apply(begin) + .apply( + "Remove Kafka Metadata", + ParDo.of( + new DoFn, KV>() { + @Override + public void processElement(ProcessContext ctx) { + ctx.output(ctx.element().getKV()); + } + })); + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + + private static final Logger LOG = LoggerFactory.getLogger(KafkaIO.class); + + /** + * Returns a new config map which is merge of current config and updates. Verifies the updates do + * not includes ignored properties. + */ + private static Map updateKafkaProperties( + Map currentConfig, + Map ignoredProperties, + Map updates) { + + for (String key : updates.keySet()) { + checkArgument( + !ignoredProperties.containsKey(key), + "No need to configure '%s'. %s", + key, + ignoredProperties.get(key)); + } + + Map config = new HashMap<>(currentConfig); + config.putAll(updates); + + return config; + } + + private static class NowTimestampFn implements SerializableFunction { + @Override + public Instant apply(T input) { + return Instant.now(); + } + } + + /** Static class, prevent instantiation. */ + private KafkaIO() {} + + private static class UnboundedKafkaSource + extends UnboundedSource< + KafkaRecord, com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> { + + private final int id; // split id, mainly for debugging + private final List topics; + private final List assignedPartitions; + private final Coder keyCoder; + private final Coder valueCoder; + private final SerializableFunction, Instant> timestampFn; + // would it be a good idea to pass currentTimestamp to watermarkFn? + private final Optional, Instant>> watermarkFn; + private SerializableFunction, Consumer> consumerFactoryFn; + private final Map consumerConfig; + + public UnboundedKafkaSource( + int id, + List topics, + List assignedPartitions, + Coder keyCoder, + Coder valueCoder, + @Nullable SerializableFunction, Instant> timestampFn, + Optional, Instant>> watermarkFn, + SerializableFunction, Consumer> consumerFactoryFn, + Map consumerConfig) { + + this.id = id; + this.assignedPartitions = assignedPartitions; + this.topics = topics; + this.keyCoder = keyCoder; + this.valueCoder = valueCoder; + this.timestampFn = + (timestampFn == null ? new NowTimestampFn>() : timestampFn); + this.watermarkFn = watermarkFn; + this.consumerFactoryFn = consumerFactoryFn; + this.consumerConfig = consumerConfig; + } + + /** + * The partitions are evenly distributed among the splits. The number of splits returned is + * {@code min(desiredNumSplits, totalNumPartitions)}, though better not to depend on the exact + * count. + * + *

            It is important to assign the partitions deterministically so that we can support + * resuming a split from last checkpoint. The Kafka partitions are sorted by {@code } and then assigned to splits in round-robin order. + */ + @Override + public List> generateInitialSplits( + int desiredNumSplits, PipelineOptions options) throws Exception { + + List partitions = new ArrayList<>(assignedPartitions); + + // (a) fetch partitions for each topic + // (b) sort by + // (c) round-robin assign the partitions to splits + + if (partitions.isEmpty()) { + try (Consumer consumer = consumerFactoryFn.apply(consumerConfig)) { + for (String topic : topics) { + for (PartitionInfo p : consumer.partitionsFor(topic)) { + partitions.add(new TopicPartition(p.topic(), p.partition())); + } + } + } + } + + Collections.sort( + partitions, + new Comparator() { + public int compare(TopicPartition tp1, TopicPartition tp2) { + return ComparisonChain.start() + .compare(tp1.topic(), tp2.topic()) + .compare(tp1.partition(), tp2.partition()) + .result(); + } + }); + + checkArgument(desiredNumSplits > 0); + checkState( + partitions.size() > 0, + "Could not find any partitions. Please check Kafka configuration and topic names"); + + int numSplits = Math.min(desiredNumSplits, partitions.size()); + List> assignments = new ArrayList<>(numSplits); + + for (int i = 0; i < numSplits; i++) { + assignments.add(new ArrayList()); + } + for (int i = 0; i < partitions.size(); i++) { + assignments.get(i % numSplits).add(partitions.get(i)); + } + + List> result = new ArrayList<>(numSplits); + + for (int i = 0; i < numSplits; i++) { + List assignedToSplit = assignments.get(i); + + LOG.info( + "Partitions assigned to split {} (total {}): {}", + i, + assignedToSplit.size(), + Joiner.on(",").join(assignedToSplit)); + + result.add( + new UnboundedKafkaSource( + i, + this.topics, + assignedToSplit, + this.keyCoder, + this.valueCoder, + this.timestampFn, + this.watermarkFn, + this.consumerFactoryFn, + this.consumerConfig)); + } + + return result; + } + + @Override + public UnboundedKafkaReader createReader( + PipelineOptions options, + com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark checkpointMark) { + if (assignedPartitions.isEmpty()) { + LOG.warn("Looks like generateSplits() is not called. Generate single split."); + try { + return new UnboundedKafkaReader( + generateInitialSplits(1, options).get(0), checkpointMark); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return new UnboundedKafkaReader(this, checkpointMark); + } + + @Override + public Coder + getCheckpointMarkCoder() { + return SerializableCoder.of( + com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark.class); + } + + @Override + public boolean requiresDeduping() { + // Kafka records are ordered with in partitions. In addition checkpoint guarantees + // records are not consumed twice. + return false; + } + + @Override + public void validate() { + checkNotNull( + consumerConfig.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG), + "Kafka bootstrap servers should be set"); + checkArgument( + topics.size() > 0 || assignedPartitions.size() > 0, + "Kafka topics or topic_partitions are required"); + } + + @Override + public Coder> getDefaultOutputCoder() { + return KafkaRecordCoder.of(keyCoder, valueCoder); + } + } + + private static class UnboundedKafkaReader extends UnboundedReader> { + + private final UnboundedKafkaSource source; + private final String name; + private Consumer consumer; + private final List partitionStates; + private KafkaRecord curRecord; + private Instant curTimestamp; + private Iterator curBatch = Collections.emptyIterator(); + + private static final Duration KAFKA_POLL_TIMEOUT = Duration.millis(1000); + // how long to wait for new records from kafka consumer inside start() + private static final Duration START_NEW_RECORDS_POLL_TIMEOUT = Duration.standardSeconds(5); + // how long to wait for new records from kafka consumer inside advance() + private static final Duration NEW_RECORDS_POLL_TIMEOUT = Duration.millis(10); + + // Use a separate thread to read Kafka messages. Kafka Consumer does all its work including + // network I/O inside poll(). Polling only inside #advance(), especially with a small timeout + // like 100 milliseconds does not work well. This along with large receive buffer for + // consumer achieved best throughput in tests (see `defaultConsumerProperties`). + private final ExecutorService consumerPollThread = Executors.newSingleThreadExecutor(); + private final SynchronousQueue> availableRecordsQueue = + new SynchronousQueue<>(); + private AtomicBoolean closed = new AtomicBoolean(false); + + // Backlog support : + // Kafka consumer does not have an API to fetch latest offset for topic. We need to seekToEnd() + // then look at position(). Use another consumer to do this so that the primary consumer does + // not need to be interrupted. The latest offsets are fetched periodically on another thread. + // This is still a hack. There could be unintended side effects, e.g. if user enabled offset + // auto commit in consumer config, this could interfere with the primary consumer (we will + // handle this particular problem). We might have to make this optional. + private Consumer offsetConsumer; + private final ScheduledExecutorService offsetFetcherThread = + Executors.newSingleThreadScheduledExecutor(); + private static final int OFFSET_UPDATE_INTERVAL_SECONDS = 5; + + /** watermark before any records have been read. */ + private static Instant initialWatermark = new Instant(Long.MIN_VALUE); + + public String toString() { + return name; + } + + // maintains state of each assigned partition (buffered records, consumed offset, etc) + private static class PartitionState { + private final TopicPartition topicPartition; + private long consumedOffset; + private long latestOffset; + private Iterator> recordIter = Collections.emptyIterator(); + + // simple moving average for size of each record in bytes + private double avgRecordSize = 0; + private static final int movingAvgWindow = 1000; // very roughly avg of last 1000 elements + + PartitionState(TopicPartition partition, long offset) { + this.topicPartition = partition; + this.consumedOffset = offset; + this.latestOffset = -1; + } + + // update consumedOffset and avgRecordSize + void recordConsumed(long offset, int size) { + consumedOffset = offset; + + // this is always updated from single thread. probably not worth making it an AtomicDouble + if (avgRecordSize <= 0) { + avgRecordSize = size; + } else { + // initially, first record heavily contributes to average. + avgRecordSize += ((size - avgRecordSize) / movingAvgWindow); + } + } + + synchronized void setLatestOffset(long latestOffset) { + this.latestOffset = latestOffset; + } + + synchronized long approxBacklogInBytes() { + // Note that is an an estimate of uncompressed backlog. + // Messages on Kafka might be comressed. + if (latestOffset < 0 || consumedOffset < 0) { + return UnboundedReader.BACKLOG_UNKNOWN; + } + if (latestOffset <= consumedOffset || consumedOffset < 0) { + return 0; + } + return (long) ((latestOffset - consumedOffset - 1) * avgRecordSize); + } + } + + public UnboundedKafkaReader( + UnboundedKafkaSource source, + @Nullable com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark checkpointMark) { + + this.source = source; + this.name = "Reader-" + source.id; + + partitionStates = + ImmutableList.copyOf( + Lists.transform( + source.assignedPartitions, + new Function() { + public PartitionState apply(TopicPartition tp) { + return new PartitionState(tp, -1L); + } + })); + + if (checkpointMark != null) { + // a) verify that assigned and check-pointed partitions match exactly + // b) set consumed offsets + + checkState( + checkpointMark.getPartitions().size() == source.assignedPartitions.size(), + "checkPointMark and assignedPartitions should match"); + // we could consider allowing a mismatch, though it is not expected in current Dataflow + + for (int i = 0; i < source.assignedPartitions.size(); i++) { + PartitionMark ckptMark = checkpointMark.getPartitions().get(i); + TopicPartition assigned = source.assignedPartitions.get(i); + + checkState( + ckptMark.getTopicPartition().equals(assigned), + "checkpointed partition %s and assigned partition %s don't match", + ckptMark.getTopicPartition(), + assigned); + + partitionStates.get(i).consumedOffset = ckptMark.getOffset(); + } + } + } + + private void consumerPollLoop() { + // Read in a loop and enqueue the batch of records, if any, to availableRecordsQueue + while (!closed.get()) { + try { + ConsumerRecords records = consumer.poll(KAFKA_POLL_TIMEOUT.getMillis()); + if (!records.isEmpty() && !closed.get()) { + availableRecordsQueue.put(records); // blocks until dequeued. + } + } catch (InterruptedException e) { + LOG.warn("{}: consumer thread is interrupted", this, e); // not expected + break; + } catch (WakeupException e) { + break; + } + } + + LOG.info("{}: Returning from consumer pool loop", this); + } + + private void nextBatch(Duration timeout) { + curBatch = Collections.emptyIterator(); + + ConsumerRecords records; + try { + records = availableRecordsQueue.poll(timeout.getMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOG.warn("{}: Unexpected", this, e); + return; + } + + if (records == null) { + return; + } + + List nonEmpty = new LinkedList<>(); + + for (PartitionState p : partitionStates) { + p.recordIter = records.records(p.topicPartition).iterator(); + if (p.recordIter.hasNext()) { + nonEmpty.add(p); + } + } + + // cycle through the partitions in order to interleave records from each. + curBatch = Iterators.cycle(nonEmpty); + } + + @Override + public boolean start() throws IOException { + consumer = source.consumerFactoryFn.apply(source.consumerConfig); + consumer.assign(source.assignedPartitions); + + // seek to consumedOffset + 1 if it is set + for (PartitionState p : partitionStates) { + if (p.consumedOffset >= 0) { + LOG.info("{}: resuming {} at {}", name, p.topicPartition, p.consumedOffset + 1); + consumer.seek(p.topicPartition, p.consumedOffset + 1); + } else { + LOG.info("{}: resuming {} at default offset", name, p.topicPartition); + } + } + + // start consumer read loop. + // Note that consumer is not thread safe, should not accessed out side consumerPollLoop() + consumerPollThread.submit( + new Runnable() { + public void run() { + consumerPollLoop(); + } + }); + + // offsetConsumer setup : + + Object groupId = source.consumerConfig.get(ConsumerConfig.GROUP_ID_CONFIG); + // override group_id and disable auto_commit so that it does not interfere with main consumer + String offsetGroupId = + String.format( + "%s_offset_consumer_%d_%s", + name, + (new Random()).nextInt(Integer.MAX_VALUE), + (groupId == null ? "none" : groupId)); + Map offsetConsumerConfig = new HashMap<>(source.consumerConfig); + offsetConsumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, offsetGroupId); + offsetConsumerConfig.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); + + offsetConsumer = source.consumerFactoryFn.apply(offsetConsumerConfig); + offsetConsumer.assign(source.assignedPartitions); + + offsetFetcherThread.scheduleAtFixedRate( + new Runnable() { + public void run() { + updateLatestOffsets(); + } + }, + 0, + OFFSET_UPDATE_INTERVAL_SECONDS, + TimeUnit.SECONDS); + + // Wait for longer than normal when fetching a batch to improve chances a record is available + // when start() returns. + nextBatch(START_NEW_RECORDS_POLL_TIMEOUT); + return advance(); + } + + @Override + public boolean advance() throws IOException { + /* Read first record (if any). we need to loop here because : + * - (a) some records initially need to be skipped if they are before consumedOffset + * - (b) if curBatch is empty, we want to fetch next batch and then advance. + * - (c) curBatch is an iterator of iterators. we interleave the records from each. + * curBatch.next() might return an empty iterator. + */ + while (true) { + if (curBatch.hasNext()) { + PartitionState pState = curBatch.next(); + + if (!pState.recordIter.hasNext()) { // -- (c) + pState.recordIter = Collections.emptyIterator(); // drop ref + curBatch.remove(); + continue; + } + + ConsumerRecord rawRecord = pState.recordIter.next(); + long consumed = pState.consumedOffset; + long offset = rawRecord.offset(); + + if (consumed >= 0 && offset <= consumed) { // -- (a) + // this can happen when compression is enabled in Kafka (seems to be fixed in 0.10) + // should we check if the offset is way off from consumedOffset (say > 1M)? + LOG.warn( + "{}: ignoring already consumed offset {} for {}", + this, + offset, + pState.topicPartition); + continue; + } + + // sanity check + if (consumed >= 0 && (offset - consumed) != 1) { + LOG.warn( + "{}: gap in offsets for {} after {}. {} records missing.", + this, + pState.topicPartition, + consumed, + offset - consumed - 1); + } + + if (curRecord == null) { + LOG.info("{}: first record offset {}", name, offset); + } + + curRecord = null; // user coders below might throw. + + // apply user coders. might want to allow skipping records that fail to decode. + // TODO: wrap exceptions from coders to make explicit to users + KafkaRecord record = + new KafkaRecord( + rawRecord.topic(), + rawRecord.partition(), + rawRecord.offset(), + decode(rawRecord.key(), source.keyCoder), + decode(rawRecord.value(), source.valueCoder)); + + curTimestamp = source.timestampFn.apply(record); + curRecord = record; + + int recordSize = + (rawRecord.key() == null ? 0 : rawRecord.key().length) + + (rawRecord.value() == null ? 0 : rawRecord.value().length); + pState.recordConsumed(offset, recordSize); + return true; + + } else { // -- (b) + nextBatch(NEW_RECORDS_POLL_TIMEOUT); + + if (!curBatch.hasNext()) { + return false; + } + } + } + } + + private static byte[] nullBytes = new byte[0]; + + private static T decode(byte[] bytes, Coder coder) throws IOException { + // If 'bytes' is null, use byte[0]. It is common for key in Kakfa record to be null. + // This makes it impossible for user to distinguish between zero length byte and null. + // Alternately, we could have a ByteArrayCoder that handles nulls, and use that for default + // coder. + byte[] toDecode = bytes == null ? nullBytes : bytes; + return coder.decode(new ExposedByteArrayInputStream(toDecode), Coder.Context.OUTER); + } + + // update latest offset for each partition. + // called from offsetFetcher thread + private void updateLatestOffsets() { + for (PartitionState p : partitionStates) { + try { + offsetConsumer.seekToEnd(p.topicPartition); + long offset = offsetConsumer.position(p.topicPartition); + p.setLatestOffset(offset); + } catch (Exception e) { + LOG.warn("{}: exception while fetching latest offsets. ignored.", this, e); + p.setLatestOffset(-1L); // reset + } + + LOG.debug( + "{}: latest offset update for {} : {} (consumed offset {}, avg record size {})", + this, + p.topicPartition, + p.latestOffset, + p.consumedOffset, + p.avgRecordSize); + } + + LOG.debug("{}: backlog {}", this, getSplitBacklogBytes()); + } + + @Override + public Instant getWatermark() { + if (curRecord == null) { + LOG.warn("{}: getWatermark() : no records have been read yet.", name); + return initialWatermark; + } + + return source.watermarkFn.isPresent() + ? source.watermarkFn.get().apply(curRecord) + : curTimestamp; + } + + @Override + public CheckpointMark getCheckpointMark() { + return new KafkaCheckpointMark( + ImmutableList.copyOf( + // avoid lazy (consumedOffset can change) + Lists.transform( + partitionStates, + new Function() { + public PartitionMark apply(PartitionState p) { + return new PartitionMark(p.topicPartition, p.consumedOffset); + } + }))); + } + + @Override + public UnboundedSource, ?> getCurrentSource() { + return source; + } + + @Override + public KafkaRecord getCurrent() throws NoSuchElementException { + // should we delay updating consumed offset till this point? Mostly not required. + return curRecord; + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + return curTimestamp; + } + + @Override + public long getSplitBacklogBytes() { + long backlogBytes = 0; + + for (PartitionState p : partitionStates) { + long pBacklog = p.approxBacklogInBytes(); + if (pBacklog == UnboundedReader.BACKLOG_UNKNOWN) { + return UnboundedReader.BACKLOG_UNKNOWN; + } + backlogBytes += pBacklog; + } + + return backlogBytes; + } + + @Override + public void close() throws IOException { + closed.set(true); + consumerPollThread.shutdown(); + offsetFetcherThread.shutdown(); + + boolean isShutdown = false; + + // Wait for threads to shutdown. Trying this a loop to handle a tiny race where poll thread + // might block to enqueue right after availableRecordsQueue.poll() below. + while (!isShutdown) { + + consumer.wakeup(); + offsetConsumer.wakeup(); + availableRecordsQueue.poll(); // drain unread batch, this unblocks consumer thread. + try { + isShutdown = + consumerPollThread.awaitTermination(10, TimeUnit.SECONDS) + && offsetFetcherThread.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); // not expected + } + + if (!isShutdown) { + LOG.warn("An internal thread is taking a long time to shutdown. will retry."); + } + } + + Closeables.close(offsetConsumer, true); + Closeables.close(consumer, true); + } + } + + //////////////////////// Sink Support \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + + /** + * A {@link PTransform} to write to a Kafka topic. See {@link KafkaIO} for more information on + * usage and configuration. + */ + public static class Write extends TypedWrite { + + /** + * Returns a new {@link Write} transform with Kafka producer pointing to {@code + * bootstrapServers}. + */ + public Write withBootstrapServers(String bootstrapServers) { + return updateProducerProperties( + ImmutableMap.of( + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers)); + } + + /** + * Returns a new {@link Write} transform that write to given topic. + */ + public Write withTopic(String topic) { + return new Write(topic, keyCoder, valueCoder, producerConfig); + } + + /** + * Returns a new {@link Write} with {@link Coder} for serializing key (if any) to bytes. A key + * is optional while writing to Kafka. Note when a key is set, its hash is used to determine + * partition in Kafka (see {@link ProducerRecord} for more details). + */ + public Write withKeyCoder(Coder keyCoder) { + return new Write(topic, keyCoder, valueCoder, producerConfig); + } + + /** + * Returns a new {@link Write} with {@link Coder} for serializing value to bytes. + */ + public Write withValueCoder(Coder valueCoder) { + return new Write(topic, keyCoder, valueCoder, producerConfig); + } + + public Write updateProducerProperties(Map configUpdates) { + Map config = + updateKafkaProperties( + producerConfig, TypedWrite.IGNORED_PRODUCER_PROPERTIES, configUpdates); + return new Write(topic, keyCoder, valueCoder, config); + } + + private Write( + String topic, Coder keyCoder, Coder valueCoder, Map producerConfig) { + super( + topic, + keyCoder, + valueCoder, + producerConfig, + Optional., Producer>>absent()); + } + } + + /** + * A {@link PTransform} to write to a Kafka topic. See {@link KafkaIO} for more information on + * usage and configuration. + */ + public static class TypedWrite extends PTransform>, PDone> { + + /** + * Returns a new {@link Write} with a custom function to create Kafka producer. Primarily used + * for tests. Default is {@link KafkaProducer} + */ + public TypedWrite withProducerFactoryFn( + SerializableFunction, Producer> producerFactoryFn) { + return new TypedWrite( + topic, keyCoder, valueCoder, producerConfig, Optional.of(producerFactoryFn)); + } + + /** + * Returns a new transform that writes just the values to Kafka. This is useful for writing + * collections of values rather thank {@link KV}s. + */ + @SuppressWarnings("unchecked") + public PTransform, PDone> values() { + return new KafkaValueWrite((TypedWrite) this); + // Any way to avoid casting here to TypedWrite? We can't create + // new TypedWrite without casting producerFactoryFn. + } + + @Override + public PDone apply(PCollection> input) { + input.apply( + ParDo.of( + new KafkaWriter( + topic, keyCoder, valueCoder, producerConfig, producerFactoryFnOpt))); + return PDone.in(input.getPipeline()); + } + + @Override + public void validate(PCollection> input) { + checkNotNull( + producerConfig.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG), + "Kafka bootstrap servers should be set"); + checkNotNull(topic, "Kafka topic should be set"); + } + + ////////////////////////////////////////////////////////////////////////////////////////// + + protected final String topic; + protected final Coder keyCoder; + protected final Coder valueCoder; + protected final Optional, Producer>> + producerFactoryFnOpt; + protected final Map producerConfig; + + protected TypedWrite( + String topic, + Coder keyCoder, + Coder valueCoder, + Map producerConfig, + Optional, Producer>> producerFactoryFnOpt) { + + this.topic = topic; + this.keyCoder = keyCoder; + this.valueCoder = valueCoder; + this.producerConfig = producerConfig; + this.producerFactoryFnOpt = producerFactoryFnOpt; + } + + // set config defaults + private static final Map DEFAULT_PRODUCER_PROPERTIES = + ImmutableMap.of( + ProducerConfig.RETRIES_CONFIG, + 3, + ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, + CoderBasedKafkaSerializer.class, + ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, + CoderBasedKafkaSerializer.class); + + /** + * A set of properties that are not required or don't make sense for our consumer. + */ + private static final Map IGNORED_PRODUCER_PROPERTIES = + ImmutableMap.of( + ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, + "Set keyCoder instead", + ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, + "Set valueCoder instead", + configForKeySerializer(), + "Reserved for internal serializer", + configForValueSerializer(), + "Reserved for internal serializer"); + } + + /** + * Same as {@link Write Write<K, V>} without a Key. Null is used for key as it is the + * convention is Kafka when there is no key specified. Majority of Kafka writers don't specify a + * key. + */ + private static class KafkaValueWrite extends PTransform, PDone> { + + private final TypedWrite kvWriteTransform; + + private KafkaValueWrite(TypedWrite kvWriteTransform) { + this.kvWriteTransform = kvWriteTransform; + } + + @Override + public PDone apply(PCollection input) { + return input + .apply( + "Kafka values with default key", + ParDo.of( + new DoFn>() { + @Override + public void processElement(ProcessContext ctx) throws Exception { + ctx.output(KV.of(null, ctx.element())); + } + })) + .setCoder(KvCoder.of(VoidCoder.of(), kvWriteTransform.valueCoder)) + .apply(kvWriteTransform); + } + } + + private static class KafkaWriter extends DoFn, Void> { + + @Override + public void startBundle(Context c) throws Exception { + // Producer initialization is fairly costly. Move this to future initialization api to avoid + // creating a producer for each bundle. + if (producer == null) { + if (producerFactoryFnOpt.isPresent()) { + producer = producerFactoryFnOpt.get().apply(producerConfig); + } else { + producer = new KafkaProducer(producerConfig); + } + } + } + + @Override + public void processElement(ProcessContext ctx) throws Exception { + checkForFailures(); + + KV kv = ctx.element(); + producer.send( + new ProducerRecord(topic, kv.getKey(), kv.getValue()), new SendCallback()); + } + + @Override + public void finishBundle(Context c) throws Exception { + producer.flush(); + producer.close(); + producer = null; + checkForFailures(); + } + + /////////////////////////////////////////////////////////////////////////////////// + + private final String topic; + private final Map producerConfig; + private final Optional, Producer>> + producerFactoryFnOpt; + + private transient Producer producer = null; + //private transient Callback sendCallback = new SendCallback(); + // first exception and number of failures since last invocation of checkForFailures(): + private transient Exception sendException = null; + private transient long numSendFailures = 0; + + KafkaWriter( + String topic, + Coder keyCoder, + Coder valueCoder, + Map producerConfig, + Optional, Producer>> producerFactoryFnOpt) { + + this.topic = topic; + this.producerFactoryFnOpt = producerFactoryFnOpt; + + // Set custom kafka serializers. We can not serialize user objects then pass the bytes to + // producer. The key and value objects are used in kafka Partitioner interface. + // This does not matter for default partitioner in Kafka as it uses just the serialized + // key bytes to pick a partition. But are making sure user's custom partitioner would work + // as expected. + + this.producerConfig = new HashMap<>(producerConfig); + this.producerConfig.put(configForKeySerializer(), keyCoder); + this.producerConfig.put(configForValueSerializer(), valueCoder); + } + + private synchronized void checkForFailures() throws IOException { + if (numSendFailures == 0) { + return; + } + + String msg = + String.format( + "KafkaWriter : failed to send %d records (since last report)", numSendFailures); + + Exception e = sendException; + sendException = null; + numSendFailures = 0; + + LOG.warn(msg); + throw new IOException(msg, e); + } + + private class SendCallback implements Callback { + @Override + public void onCompletion(RecordMetadata metadata, Exception exception) { + if (exception == null) { + return; + } + + synchronized (KafkaWriter.this) { + if (sendException == null) { + sendException = exception; + } + numSendFailures++; + } + // don't log exception stacktrace here, exception will be propagated up. + LOG.warn("KafkaWriter send failed : '{}'", exception.getMessage()); + } + } + } + + /** + * Implements Kafka's {@link Serializer} with a {@link Coder}. The coder is stored as serialized + * value in producer configuration map. + */ + public static class CoderBasedKafkaSerializer implements Serializer { + + @SuppressWarnings("unchecked") + @Override + public void configure(Map configs, boolean isKey) { + String configKey = isKey ? configForKeySerializer() : configForValueSerializer(); + coder = (Coder) configs.get(configKey); + checkNotNull(coder, "could not instantiate coder for Kafka serialization"); + } + + @Override + public byte[] serialize(String topic, @Nullable T data) { + if (data == null) { + return null; // common for keys to be null + } + + try { + return CoderUtils.encodeToByteArray(coder, data); + } catch (CoderException e) { + throw new RuntimeException(e); + } + } + + @Override + public void close() {} + + private Coder coder = null; + private static final String CONFIG_FORMAT = + "com.google.cloud.dataflow.coder.based.kafka.%s.serializer"; + } + + private static String configForKeySerializer() { + return String.format(CoderBasedKafkaSerializer.CONFIG_FORMAT, "key"); + } + + private static String configForValueSerializer() { + return String.format(CoderBasedKafkaSerializer.CONFIG_FORMAT, "value"); + } +} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java new file mode 100644 index 0000000000..7373c2d6e5 --- /dev/null +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.kafka; + +import com.google.cloud.dataflow.sdk.values.KV; + +import java.io.Serializable; +import java.util.Arrays; + +/** + * KafkaRecord contains key and value of the record as well as metadata for the record (topic name, + * partition id, and offset). + */ +public class KafkaRecord implements Serializable { + + private final String topic; + private final int partition; + private final long offset; + private final KV kv; + + public KafkaRecord(String topic, int partition, long offset, K key, V value) { + this(topic, partition, offset, KV.of(key, value)); + } + + public KafkaRecord(String topic, int partition, long offset, KV kv) { + + this.topic = topic; + this.partition = partition; + this.offset = offset; + this.kv = kv; + } + + public String getTopic() { + return topic; + } + + public int getPartition() { + return partition; + } + + public long getOffset() { + return offset; + } + + public KV getKV() { + return kv; + } + + @Override + public int hashCode() { + return Arrays.deepHashCode(new Object[] {topic, partition, offset, kv}); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof KafkaRecord) { + @SuppressWarnings("unchecked") + KafkaRecord other = (KafkaRecord) obj; + return topic.equals(other.topic) + && partition == other.partition + && offset == other.offset + && kv.equals(other.kv); + } else { + return false; + } + } +} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java new file mode 100644 index 0000000000..ed29c13342 --- /dev/null +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.kafka; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.values.KV; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; + +/** + * {@link Coder} for {@link KafkaRecord}. + */ +public class KafkaRecordCoder extends StandardCoder> { + + private static final StringUtf8Coder stringCoder = StringUtf8Coder.of(); + private static final VarLongCoder longCoder = VarLongCoder.of(); + private static final VarIntCoder intCoder = VarIntCoder.of(); + + private final KvCoder kvCoder; + + @JsonCreator + public static KafkaRecordCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { + KvCoder kvCoder = KvCoder.of(components); + return of(kvCoder.getKeyCoder(), kvCoder.getValueCoder()); + } + + public static KafkaRecordCoder of(Coder keyCoder, Coder valueCoder) { + return new KafkaRecordCoder(keyCoder, valueCoder); + } + + public KafkaRecordCoder(Coder keyCoder, Coder valueCoder) { + this.kvCoder = KvCoder.of(keyCoder, valueCoder); + } + + @Override + public void encode( + com.google.cloud.dataflow.contrib.kafka.KafkaRecord value, + OutputStream outStream, + Context context) + throws CoderException, IOException { + Context nested = context.nested(); + stringCoder.encode(value.getTopic(), outStream, nested); + intCoder.encode(value.getPartition(), outStream, nested); + longCoder.encode(value.getOffset(), outStream, nested); + kvCoder.encode(value.getKV(), outStream, nested); + } + + @Override + public com.google.cloud.dataflow.contrib.kafka.KafkaRecord decode( + InputStream inStream, Context context) throws CoderException, IOException { + Context nested = context.nested(); + return new com.google.cloud.dataflow.contrib.kafka.KafkaRecord( + stringCoder.decode(inStream, nested), + intCoder.decode(inStream, nested), + longCoder.decode(inStream, nested), + kvCoder.decode(inStream, nested)); + } + + @Override + public List> getCoderArguments() { + return kvCoder.getCoderArguments(); + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + kvCoder.verifyDeterministic(); + } + + @Override + public boolean isRegisterByteSizeObserverCheap( + com.google.cloud.dataflow.contrib.kafka.KafkaRecord value, Context context) { + return kvCoder.isRegisterByteSizeObserverCheap(value.getKV(), context); + //TODO : do we have to implement getEncodedSize()? + } + + @SuppressWarnings("unchecked") + @Override + public Object structuralValue(com.google.cloud.dataflow.contrib.kafka.KafkaRecord value) + throws Exception { + if (consistentWithEquals()) { + return value; + } else { + return new com.google.cloud.dataflow.contrib.kafka.KafkaRecord( + value.getTopic(), + value.getPartition(), + value.getOffset(), + (KV) kvCoder.structuralValue(value.getKV())); + } + } + + @Override + public boolean consistentWithEquals() { + return kvCoder.consistentWithEquals(); + } +} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java new file mode 100644 index 0000000000..48746c1908 --- /dev/null +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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. + */ + +/** + * Transforms for reading and writing from Apache Kafka. + */ +package com.google.cloud.dataflow.contrib.kafka; diff --git a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java new file mode 100644 index 0000000000..af8d674831 --- /dev/null +++ b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java @@ -0,0 +1,674 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.kafka; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; +import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; +import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; +import com.google.cloud.dataflow.sdk.io.Read; +import com.google.cloud.dataflow.sdk.io.UnboundedSource; +import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.Max; +import com.google.cloud.dataflow.sdk.transforms.Min; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.Values; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.PartitionInfo; +import org.apache.kafka.common.TopicPartition; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.annotation.Nullable; + +/** + * Tests of {@link KafkaIO}. + */ +@RunWith(JUnit4.class) +public class KafkaIOTest { + /* + * The tests below borrow code and structure from CountingSourceTest. In addition verifies + * the reader interleaves the records from multiple partitions. + * + * Other tests to consider : + * - test KafkaRecordCoder + */ + + @Rule public ExpectedException thrown = ExpectedException.none(); + + // Update mock consumer with records distributed among the given topics, each with given number + // of partitions. Records are assigned in round-robin order among the partitions. + private static MockConsumer mkMockConsumer( + List topics, int partitionsPerTopic, int numElements) { + + final List partitions = new ArrayList<>(); + final Map>> records = new HashMap<>(); + Map> partitionMap = new HashMap<>(); + + for (String topic : topics) { + List partIds = new ArrayList<>(partitionsPerTopic); + for (int i = 0; i < partitionsPerTopic; i++) { + partitions.add(new TopicPartition(topic, i)); + partIds.add(new PartitionInfo(topic, i, null, null, null)); + } + partitionMap.put(topic, partIds); + } + + int numPartitions = partitions.size(); + long[] offsets = new long[numPartitions]; + + for (int i = 0; i < numElements; i++) { + int pIdx = i % numPartitions; + TopicPartition tp = partitions.get(pIdx); + + if (!records.containsKey(tp)) { + records.put(tp, new ArrayList>()); + } + records + .get(tp) + .add( + new ConsumerRecord( + tp.topic(), + tp.partition(), + offsets[pIdx]++, + ByteBuffer.wrap(new byte[8]).putInt(i).array(), + // key is 4 byte record id + ByteBuffer.wrap(new byte[8]).putLong(i).array())); // value is 8 byte record id + } + + MockConsumer consumer = + new MockConsumer(OffsetResetStrategy.EARLIEST) { + // override assign() to add records that belong to the assigned partitions. + public void assign(List assigned) { + super.assign(assigned); + for (TopicPartition tp : assigned) { + for (ConsumerRecord r : records.get(tp)) { + addRecord(r); + } + updateBeginningOffsets(ImmutableMap.of(tp, 0L)); + updateEndOffsets(ImmutableMap.of(tp, (long) records.get(tp).size())); + seek(tp, 0); + } + } + }; + + for (String topic : topics) { + consumer.updatePartitions(topic, partitionMap.get(topic)); + } + + return consumer; + } + + private static class ConsumerFactoryFn + implements SerializableFunction, Consumer> { + private final List topics; + private final int partitionsPerTopic; + private final int numElements; + + public ConsumerFactoryFn(List topics, int partitionsPerTopic, int numElements) { + this.topics = topics; + this.partitionsPerTopic = partitionsPerTopic; + this.numElements = numElements; + } + + public Consumer apply(Map config) { + return mkMockConsumer(topics, partitionsPerTopic, numElements); + } + } + + /** + * Creates a consumer with two topics, with 5 partitions each. numElements are (round-robin) + * assigned all the 10 partitions. + */ + private static KafkaIO.TypedRead mkKafkaReadTransform( + int numElements, @Nullable SerializableFunction, Instant> timestampFn) { + + List topics = ImmutableList.of("topic_a", "topic_b"); + + com.google.cloud.dataflow.contrib.kafka.KafkaIO.Read reader = + com.google.cloud.dataflow.contrib.kafka.KafkaIO.read() + .withBootstrapServers("none") + .withTopics(topics) + .withConsumerFactoryFn(new ConsumerFactoryFn(topics, 10, numElements)) // 20 partitions + .withKeyCoder(BigEndianIntegerCoder.of()) + .withValueCoder(BigEndianLongCoder.of()) + .withMaxNumRecords(numElements); + + if (timestampFn != null) { + return reader.withTimestampFn(timestampFn); + } else { + return reader; + } + } + + private static class AssertMultipleOf implements SerializableFunction, Void> { + private final int num; + + public AssertMultipleOf(int num) { + this.num = num; + } + + @Override + public Void apply(Iterable values) { + for (Long v : values) { + assertEquals(0, v % num); + } + return null; + } + } + + public static void addCountingAsserts(PCollection input, long numElements) { + // Count == numElements + DataflowAssert.thatSingleton(input.apply("Count", Count.globally())) + .isEqualTo(numElements); + // Unique count == numElements + DataflowAssert.thatSingleton( + input + .apply(RemoveDuplicates.create()) + .apply("UniqueCount", Count.globally())) + .isEqualTo(numElements); + // Min == 0 + DataflowAssert.thatSingleton(input.apply("Min", Min.globally())).isEqualTo(0L); + // Max == numElements-1 + DataflowAssert.thatSingleton(input.apply("Max", Max.globally())) + .isEqualTo(numElements - 1); + } + + @Test + public void testUnboundedSource() { + Pipeline p = TestPipeline.create(); + int numElements = 1000; + + PCollection input = + p + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(Values.create()); + + addCountingAsserts(input, numElements); + p.run(); + } + + @Test + public void testUnboundedSourceWithExplicitPartitions() { + Pipeline p = TestPipeline.create(); + int numElements = 1000; + + List topics = ImmutableList.of("test"); + + com.google.cloud.dataflow.contrib.kafka.KafkaIO.TypedRead reader = + com.google.cloud.dataflow.contrib.kafka.KafkaIO.read() + .withBootstrapServers("none") + .withTopicPartitions(ImmutableList.of(new TopicPartition("test", 5))) + .withConsumerFactoryFn(new ConsumerFactoryFn(topics, 10, numElements)) // 10 partitions + .withValueCoder(BigEndianLongCoder.of()) + .withMaxNumRecords(numElements / 10); + + PCollection input = p.apply(reader.withoutMetadata()).apply(Values.create()); + + // assert that every element is a multiple of 5. + DataflowAssert.that(input).satisfies(new AssertMultipleOf(5)); + + DataflowAssert.thatSingleton(input.apply(Count.globally())).isEqualTo(numElements / 10L); + + p.run(); + } + + private static class ElementValueDiff extends DoFn { + @Override + public void processElement(ProcessContext c) throws Exception { + c.output(c.element() - c.timestamp().getMillis()); + } + } + + @Test + public void testUnboundedSourceTimestamps() { + Pipeline p = TestPipeline.create(); + int numElements = 1000; + + PCollection input = + p + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(Values.create()); + + addCountingAsserts(input, numElements); + + PCollection diffs = + input + .apply("TimestampDiff", ParDo.of(new ElementValueDiff())) + .apply("RemoveDuplicateTimestamps", RemoveDuplicates.create()); + // This assert also confirms that diffs only has one unique value. + DataflowAssert.thatSingleton(diffs).isEqualTo(0L); + + p.run(); + } + + private static class RemoveKafkaMetadata + extends DoFn, KV> { + @Override + public void processElement(ProcessContext ctx) throws Exception { + ctx.output(ctx.element().getKV()); + } + } + + @Test + public void testUnboundedSourceSplits() throws Exception { + Pipeline p = TestPipeline.create(); + int numElements = 1000; + int numSplits = 10; + + UnboundedSource, ?> initial = + mkKafkaReadTransform(numElements, null).makeSource(); + List< + ? extends + UnboundedSource< + com.google.cloud.dataflow.contrib.kafka.KafkaRecord, ?>> + splits = initial.generateInitialSplits(numSplits, p.getOptions()); + assertEquals("Expected exact splitting", numSplits, splits.size()); + + long elementsPerSplit = numElements / numSplits; + assertEquals("Expected even splits", numElements, elementsPerSplit * numSplits); + PCollectionList pcollections = PCollectionList.empty(p); + for (int i = 0; i < splits.size(); ++i) { + pcollections = + pcollections.and( + p + .apply("split" + i, Read.from(splits.get(i)).withMaxNumRecords(elementsPerSplit)) + .apply("Remove Metadata " + i, ParDo.of(new RemoveKafkaMetadata())) + .apply("collection " + i, Values.create())); + } + PCollection input = pcollections.apply(Flatten.pCollections()); + + addCountingAsserts(input, numElements); + p.run(); + } + + /** + * A timestamp function that uses the given value as the timestamp. + */ + private static class ValueAsTimestampFn + implements SerializableFunction, Instant> { + @Override + public Instant apply(KV input) { + return new Instant(input.getValue()); + } + } + + // Kafka records are read in a separate thread inside the reader. As a result advance() might not + // read any records even from the mock consumer, especially for the first record. + // This is a helper method to loop until we read a record. + private static void advanceOnce(UnboundedReader reader) throws IOException { + while (!reader.advance()) { + // very rarely will there be more than one attempts. + // in case of a bug we might end up looping forever, and test will fail with a timeout. + } + } + + @Test + public void testUnboundedSourceCheckpointMark() throws Exception { + int numElements = 85; // 85 to make sure some partitions have more records than other. + + // create a single split: + UnboundedSource< + com.google.cloud.dataflow.contrib.kafka.KafkaRecord, + com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> + source = + mkKafkaReadTransform(numElements, new ValueAsTimestampFn()) + .makeSource() + .generateInitialSplits(1, PipelineOptionsFactory.fromArgs(new String[0]).create()) + .get(0); + + UnboundedReader> reader = + source.createReader(null, null); + final int numToSkip = 3; + + // advance numToSkip elements + if (!reader.start()) { + advanceOnce(reader); + } + + for (long l = 0; l < numToSkip - 1; ++l) { + advanceOnce(reader); + } + + // Confirm that we get the expected element in sequence before checkpointing. + assertEquals(numToSkip - 1, (long) reader.getCurrent().getKV().getValue()); + assertEquals(numToSkip - 1, reader.getCurrentTimestamp().getMillis()); + + // Checkpoint and restart, and confirm that the source continues correctly. + com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark mark = + CoderUtils.clone( + source.getCheckpointMarkCoder(), + (com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark) + reader.getCheckpointMark()); + reader = source.createReader(null, mark); + + // Confirm that we get the next elements in sequence. + // This also confirms that Reader interleaves records from each partitions by the reader. + + if (!reader.start()) { + advanceOnce(reader); + } + + for (int i = numToSkip; i < numElements; i++) { + assertEquals(i, (long) reader.getCurrent().getKV().getValue()); + assertEquals(i, reader.getCurrentTimestamp().getMillis()); + if ((i + 1) < numElements) { + advanceOnce(reader); + } + } + } + + @Test + public void testSink() throws Exception { + // Simply read from kafka source and write to kafka sink. Then verify the records + // are correctly published to mock kafka producer. + + int numElements = 1000; + + synchronized (MOCK_PRODUCER_LOCK) { + MOCK_PRODUCER.clear(); + + ProducerSendCompletionThread completionThread = new ProducerSendCompletionThread().start(); + + Pipeline pipeline = TestPipeline.create(); + String topic = "test"; + + pipeline + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply( + com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() + .withBootstrapServers("none") + .withTopic(topic) + .withKeyCoder(BigEndianIntegerCoder.of()) + .withValueCoder(BigEndianLongCoder.of()) + .withProducerFactoryFn(new ProducerFactoryFn())); + + pipeline.run(); + + completionThread.shutdown(); + + verifyProducerRecords(topic, numElements, false); + } + } + + @Test + public void testValuesSink() throws Exception { + // similar to testSink(), but use values()' interface. + + int numElements = 1000; + + synchronized (MOCK_PRODUCER_LOCK) { + MOCK_PRODUCER.clear(); + + ProducerSendCompletionThread completionThread = new ProducerSendCompletionThread().start(); + + Pipeline pipeline = TestPipeline.create(); + String topic = "test"; + + pipeline + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(Values.create()) // there are no keys + .apply( + com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() + .withBootstrapServers("none") + .withTopic(topic) + .withKeyCoder(BigEndianIntegerCoder.of()) + .withValueCoder(BigEndianLongCoder.of()) + .withProducerFactoryFn(new ProducerFactoryFn()) + .values()); + + pipeline.run(); + + completionThread.shutdown(); + + verifyProducerRecords(topic, numElements, true); + } + } + + @Test + public void testSinkWithSendErrors() throws Throwable { + // similar to testSink(), except that up to 10 of the send calls to producer will fail + // asynchronously. + + // TODO: Ideally we want the pipeline to run to completion by retrying bundles that fail. + // We limit the number of errors injected to 10 below. This would reflect a real streaming + // pipeline. But I am sure how to achieve that. For now expect an exception: + + thrown.expect(InjectedErrorException.class); + thrown.expectMessage("Injected Error #1"); + + int numElements = 1000; + + synchronized (MOCK_PRODUCER_LOCK) { + MOCK_PRODUCER.clear(); + + Pipeline pipeline = TestPipeline.create(); + String topic = "test"; + + ProducerSendCompletionThread completionThreadWithErrors = + new ProducerSendCompletionThread(10, 100).start(); + + pipeline + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply( + com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() + .withBootstrapServers("none") + .withTopic(topic) + .withKeyCoder(BigEndianIntegerCoder.of()) + .withValueCoder(BigEndianLongCoder.of()) + .withProducerFactoryFn(new ProducerFactoryFn())); + + try { + pipeline.run(); + } catch (PipelineExecutionException e) { + // throwing inner exception helps assert that first exception is thrown from the Sink + throw e.getCause().getCause(); + } finally { + completionThreadWithErrors.shutdown(); + } + } + } + + private static void verifyProducerRecords(String topic, int numElements, boolean keyIsAbsent) { + + // verify that appropriate messages are written to kafka + List> sent = MOCK_PRODUCER.history(); + + // sort by values + Collections.sort( + sent, + new Comparator>() { + @Override + public int compare(ProducerRecord o1, ProducerRecord o2) { + return Long.compare(o1.value(), o2.value()); + } + }); + + for (int i = 0; i < numElements; i++) { + ProducerRecord record = sent.get(i); + assertEquals(topic, record.topic()); + if (keyIsAbsent) { + assertNull(record.key()); + } else { + assertEquals(i, record.key().intValue()); + } + assertEquals(i, record.value().longValue()); + } + } + + /** + * Singleton MockProudcer. Using a singleton here since we need access to the object to fetch the + * actual records published to the producer. This prohibits running the tests using the producer + * in parallel, but there are only one or two tests. + */ + private static final MockProducer MOCK_PRODUCER = + new MockProducer( + false, + // disable synchronous completion of send. see ProducerSendCompletionThread below. + new com.google.cloud.dataflow.contrib.kafka.KafkaIO.CoderBasedKafkaSerializer(), + new com.google.cloud.dataflow.contrib.kafka.KafkaIO.CoderBasedKafkaSerializer()) { + + // override flush() so that it does not complete all the waiting sends, giving a chance to + // ProducerCompletionThread to inject errors. + + @Override + public void flush() { + while (completeNext()) { + // there are some uncompleted records. let the completion thread handle them. + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + } + } + }; + + // use a separate object serialize tests using MOCK_PRODUCER so that we don't interfere + // with Kafka MockProducer locking itself. + private static final Object MOCK_PRODUCER_LOCK = new Object(); + + private static class ProducerFactoryFn + implements SerializableFunction, Producer> { + + @Override + public Producer apply(Map config) { + return MOCK_PRODUCER; + } + } + + private static class InjectedErrorException extends RuntimeException { + public InjectedErrorException(String message) { + super(message); + } + } + + /** + * We start MockProducer with auto-completion disabled. That implies a record is not marked sent + * until #completeNext() is called on it. This class starts a thread to asynchronously 'complete' + * the the sends. During completion, we can also make those requests fail. This error injection is + * used in one of the tests. + */ + private static class ProducerSendCompletionThread { + + private final int maxErrors; + private final int errorFrequency; + private final AtomicBoolean done = new AtomicBoolean(false); + private final ExecutorService injectorThread; + private int numCompletions = 0; + + ProducerSendCompletionThread() { + // complete everything successfully + this(0, 0); + } + + ProducerSendCompletionThread(final int maxErrors, final int errorFrequency) { + this.maxErrors = maxErrors; + this.errorFrequency = errorFrequency; + injectorThread = Executors.newSingleThreadExecutor(); + } + + ProducerSendCompletionThread start() { + injectorThread.submit( + new Runnable() { + @Override + public void run() { + int errorsInjected = 0; + + while (!done.get()) { + boolean successful; + + if (errorsInjected < maxErrors && ((numCompletions + 1) % errorFrequency) == 0) { + successful = + MOCK_PRODUCER.errorNext( + new InjectedErrorException("Injected Error #" + (errorsInjected + 1))); + + if (successful) { + errorsInjected++; + } + } else { + successful = MOCK_PRODUCER.completeNext(); + } + + if (successful) { + numCompletions++; + } else { + // wait a bit since there are no unsent records + try { + Thread.sleep(1); + } catch (InterruptedException e) { + } + } + } + } + }); + + return this; + } + + void shutdown() { + done.set(true); + injectorThread.shutdown(); + try { + assertTrue(injectorThread.awaitTermination(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + } + } +} From 82ab660c95c9337fe24efe824c8000f320deb55e Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Mon, 1 Aug 2016 22:41:05 -0700 Subject: [PATCH 485/751] Added Bigtable Read DisplayData (#349) --- .../dataflow/sdk/io/bigtable/BigtableIO.java | 13 ++++++++++ .../sdk/io/bigtable/BigtableIOTest.java | 25 +++++++++++++++++++ .../display/DisplayDataEvaluator.java | 23 +++++++++++++++++ 3 files changed, 61 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index c583bd97a9..bd4b3fd5e5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -723,6 +723,19 @@ public void validate() { checkArgument(!tableId.isEmpty(), "tableId cannot be empty"); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder.add(DisplayData.item("tableId", tableId) + .withLabel("Table ID")); + + if (filter != null) { + builder.add(DisplayData.item("rowFilter", filter.toString()) + .withLabel("Table Row Filter")); + } + } + @Override public Coder getDefaultOutputCoder() { return ProtoCoder.of(Row.class); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java index cc9a97dfd0..26cb64afb9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java @@ -50,6 +50,7 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; @@ -79,6 +80,7 @@ import java.util.List; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; @@ -423,6 +425,29 @@ public void testReadingDisplayData() { assertThat(displayData, hasDisplayItem("bigtableOptions")); } + @Test + public void testReadingPrimitiveDisplayData() throws IOException, InterruptedException { + final String table = "fooTable"; + service.createTable(table); + + RowFilter rowFilter = RowFilter.newBuilder() + .setRowKeyRegexFilter(ByteString.copyFromUtf8("foo.*")) + .build(); + + DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(); + BigtableIO.Read read = BigtableIO.read() + .withBigtableOptions(BIGTABLE_OPTIONS) + .withTableId(table) + .withRowFilter(rowFilter) + .withBigtableService(service); + + Set displayData = evaluator.displayDataForPrimitiveSourceTransforms(read); + assertThat("BigtableIO.Read should include the table id in its primitive display data", + displayData, Matchers.hasItem(hasDisplayItem("tableId"))); + assertThat("BigtableIO.Read should include the row filter, if it exists, in its primitive " + + "display data", displayData, Matchers.hasItem(hasDisplayItem("rowFilter"))); + } + /** Tests that a record gets written to the service and messages are logged. */ @Test public void testWriting() throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java index 1da3cc8868..24e98d0ac4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.POutput; import com.google.cloud.dataflow.sdk.values.PValue; @@ -96,6 +97,28 @@ public Set displayDataForPrimitiveTransforms( return visitor.getPrimitivesDisplayData(); } + /** + * Traverse the specified source {@link PTransform}, collecting {@link DisplayData} registered + * on the inner primitive {@link PTransform PTransforms}. + * + * @param root The source root {@link PTransform} to traverse + * @return the set of {@link DisplayData} for primitive source {@link PTransform PTransforms}. + */ + public Set displayDataForPrimitiveSourceTransforms( + final PTransform root) { + Pipeline pipeline = Pipeline.create(options); + pipeline + .apply(root); + + return displayDataForPipeline(pipeline, root); + } + + private static Set displayDataForPipeline(Pipeline pipeline, PTransform root) { + PrimitiveDisplayDataPTransformVisitor visitor = new PrimitiveDisplayDataPTransformVisitor(root); + pipeline.traverseTopologically(visitor); + return visitor.getPrimitivesDisplayData(); + } + /** * Visits {@link PTransform PTransforms} in a pipeline, and collects {@link DisplayData} for * each primitive transform under a given composite root. From 508be16b16d4cf981a593530235fc37b4ecb6837 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Tue, 2 Aug 2016 12:53:31 -0700 Subject: [PATCH 486/751] Add option to disable cloning DoFn in DoFnTester --- .../dataflow/sdk/transforms/DoFnTester.java | 43 +++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java index 6cc904f5a2..d4bbcc5e3d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java @@ -155,6 +155,29 @@ public void setSideOutputTags(TupleTagList sideOutputTags) { resetState(); } + + /** + * Whether or not a {@link DoFnTester} should clone the {@link DoFn} under test. + */ + public enum CloningBehavior { + CLONE, + DO_NOT_CLONE; + } + + /** + * Instruct this {@link DoFnTester} whether or not to clone the {@link DoFn} under test. + */ + public void setCloningBehavior(CloningBehavior newValue) { + this.cloningBehavior = newValue; + } + + /** + * Indicates whether this {@link DoFnTester} will clone the {@link DoFn} under test. + */ + public CloningBehavior getCloningBehavior() { + return cloningBehavior; + } + /** * A convenience operation that first calls {@link #startBundle}, * then calls {@link #processElement} on each of the input elements, then @@ -434,6 +457,13 @@ enum State { private Map, Iterable>> sideInputs = new HashMap<>(); + /** + * Whether to clone the original {@link DoFn} or just use it as-is. + * + *

            Worker-side {@link DoFn DoFns} may not be serializable, and are not required to be. + */ + private CloningBehavior cloningBehavior = CloningBehavior.CLONE; + /** The output tags used by the DoFn under test. */ TupleTag mainOutputTag = new TupleTag<>(); List> sideOutputTags = new ArrayList<>(); @@ -468,10 +498,15 @@ void resetState() { @SuppressWarnings("unchecked") void initializeState() { - fn = (DoFn) - SerializableUtils.deserializeFromByteArray( - SerializableUtils.serializeToByteArray(origFn), - origFn.toString()); + if (cloningBehavior.equals(CloningBehavior.DO_NOT_CLONE)) { + fn = origFn; + } else { + fn = (DoFn) + SerializableUtils.deserializeFromByteArray( + SerializableUtils.serializeToByteArray(origFn), + origFn.toString()); + } + counterSet = new CounterSet(); PTuple runnerSideInputs = PTuple.empty(); for (Map.Entry, Iterable>> entry From c2d00d302252cf9eca177508315bbc1532a80c00 Mon Sep 17 00:00:00 2001 From: Dan McGrath Date: Fri, 5 Aug 2016 10:17:54 -0600 Subject: [PATCH 487/751] Minor nit on Datastore capitalization (#355) Prevents localization issues where the product name is translated by mistake to a local language. --- .../java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java index 73df010300..9dd81f3547 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java @@ -78,7 +78,7 @@ protected long getEncodedElementByteSize(Entity value, Context context) * {@inheritDoc} * * @throws NonDeterministicException always. - * A datastore kind can hold arbitrary {@link Object} instances, which + * A Datastore kind can hold arbitrary {@link Object} instances, which * makes the encoding non-deterministic. */ @Override From 870e1b47ced76221de7b45d50dfdee338d17e393 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Fri, 5 Aug 2016 13:33:59 -0700 Subject: [PATCH 488/751] Compressed source fixes and tests (#357) * CompressedSource: CompressedReader is never splittable The only way it's safe to split a compressed file is if the file is not compressed. This can only happen when the source itself is splittable, and that in turn will result in the inner source's reader being returned. A CompressedReader will only be created in the event that the file is NOT splittable. So remove all the logic handling splittable compressed readers, and instead go with the logic when we know/assume the file is compressed. * TextIO: test compression with larger files It is important for correctness that we test with large files because otherwise the compressed file may be larger than the uncompressed file, which could mask bugs * TextIOTest: flesh out more * TextIOTest: add large uncompressed file --- .../dataflow/sdk/io/CompressedSource.java | 80 +++---- .../dataflow/sdk/io/CompressedSourceTest.java | 52 ++++- .../cloud/dataflow/sdk/io/TextIOTest.java | 195 +++++++++++++++--- 3 files changed, 241 insertions(+), 86 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index 71fd124bc8..2592afee55 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -290,7 +290,7 @@ protected final boolean isSplittable() throws Exception { (FileNameBasedDecompressingChannelFactory) channelFactory; return !fileNameBasedChannelFactory.isCompressed(getFileOrPatternSpec()); } - return true; + return false; } /** @@ -362,7 +362,6 @@ public static class CompressedReader extends FileBasedReader { private final FileBasedReader readerDelegate; private final CompressedSource source; - private final boolean splittable; private final Object progressLock = new Object(); @GuardedBy("progressLock") private int numRecordsRead; @@ -375,13 +374,6 @@ public static class CompressedReader extends FileBasedReader { public CompressedReader(CompressedSource source, FileBasedReader readerDelegate) { super(source); this.source = source; - boolean splittable; - try { - splittable = source.isSplittable(); - } catch (Exception e) { - throw new RuntimeException("Unable to tell whether source " + source + " is splittable", e); - } - this.splittable = splittable; this.readerDelegate = readerDelegate; } @@ -395,22 +387,14 @@ public T getCurrent() throws NoSuchElementException { @Override public final long getSplitPointsConsumed() { - if (splittable) { - return readerDelegate.getSplitPointsConsumed(); - } else { - synchronized (progressLock) { - return (isDone() && numRecordsRead > 0) ? 1 : 0; - } + synchronized (progressLock) { + return (isDone() && numRecordsRead > 0) ? 1 : 0; } } @Override public final long getSplitPointsRemaining() { - if (splittable) { - return readerDelegate.getSplitPointsRemaining(); - } else { - return isDone() ? 0 : 1; - } + return isDone() ? 0 : 1; } /** @@ -418,18 +402,14 @@ public final long getSplitPointsRemaining() { */ @Override protected final boolean isAtSplitPoint() { - if (splittable) { - return readerDelegate.isAtSplitPoint(); - } else { - // We have to return true for the first record, but not for the state before reading it, - // and not for the state after reading any other record. Hence == rather than >= or <=. - // This is required because FileBasedReader is intended for readers that can read a range - // of offsets in a file and where the range can be split in parts. CompressedReader, - // however, is a degenerate case because it cannot be split, but it has to satisfy the - // semantics of offsets and split points anyway. - synchronized (progressLock) { - return numRecordsRead == 1; - } + // We have to return true for the first record, but not for the state before reading it, + // and not for the state after reading any other record. Hence == rather than >= or <=. + // This is required because FileBasedReader is intended for readers that can read a range + // of offsets in a file and where the range can be split in parts. CompressedReader, + // however, is a degenerate case because it cannot be split, but it has to satisfy the + // semantics of offsets and split points anyway. + synchronized (progressLock) { + return numRecordsRead == 1; } } @@ -473,14 +453,9 @@ public void close() throws IOException { */ @Override protected final void startReading(ReadableByteChannel channel) throws IOException { - if (splittable) { - // No-op. We will always delegate to the inner reader, so this.channel and this.progressLock - // will never be used. - } else { - synchronized (progressLock) { - this.channel = new CountingChannel(channel, getCurrentSource().getStartOffset()); - channel = this.channel; - } + synchronized (progressLock) { + this.channel = new CountingChannel(channel, getCurrentSource().getStartOffset()); + channel = this.channel; } if (source.getChannelFactory() instanceof FileNameBasedDecompressingChannelFactory) { @@ -509,30 +484,21 @@ protected final boolean readNextRecord() throws IOException { return true; } - // Splittable: simply delegates to the inner reader. - // // Unsplittable: returns the offset in the input stream that has been read by the input. // these positions are likely to be coarse-grained (in the event of buffering) and // over-estimates (because they reflect the number of bytes read to produce an element, not its // start) but both of these provide better data than e.g., reporting the start of the file. @Override protected final long getCurrentOffset() throws NoSuchElementException { - if (splittable) { - return readerDelegate.getCurrentOffset(); - } else { - synchronized (progressLock) { - if (numRecordsRead <= 1) { - // Since the first record is at a split point, it should start at the beginning of the - // file. This avoids the bad case where the decompressor read the entire file, which - // would cause the file to be treated as empty when returning channel.getCount() as it - // is outside the valid range. - return 0; - } - if (channel == null) { - throw new NoSuchElementException(); - } - return channel.getCount(); + synchronized (progressLock) { + if (numRecordsRead <= 1) { + // Since the first record is at a split point, it should start at the beginning of the + // file. This avoids the bad case where the decompressor read the entire file, which + // would cause the file to be treated as empty when returning channel.getCount() as it + // is outside the valid range. + return 0; } + return channel.getCount(); } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java index e6769315fc..9f4f3cf246 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java @@ -92,6 +92,56 @@ public void testReadGzip() throws Exception { runReadTest(input, CompressionMode.GZIP); } + /** + * Test splittability of files in AUTO mode. + */ + @Test + public void testAutoSplittable() throws Exception { + CompressedSource source; + + // GZip files are not splittable + source = CompressedSource.from(new ByteSource("input.gz", 1)); + assertFalse(source.isSplittable()); + source = CompressedSource.from(new ByteSource("input.GZ", 1)); + assertFalse(source.isSplittable()); + + // BZ2 files are not splittable + source = CompressedSource.from(new ByteSource("input.bz2", 1)); + assertFalse(source.isSplittable()); + source = CompressedSource.from(new ByteSource("input.BZ2", 1)); + assertFalse(source.isSplittable()); + + // Other extensions are assumed to be splittable. + source = CompressedSource.from(new ByteSource("input.txt", 1)); + assertTrue(source.isSplittable()); + source = CompressedSource.from(new ByteSource("input.csv", 1)); + assertTrue(source.isSplittable()); + } + + /** + * Test splittability of files in GZIP mode -- none should be splittable. + */ + @Test + public void testGzipSplittable() throws Exception { + CompressedSource source; + + // GZip files are not splittable + source = CompressedSource.from(new ByteSource("input.gz", 1)) + .withDecompression(CompressionMode.GZIP); + assertFalse(source.isSplittable()); + source = CompressedSource.from(new ByteSource("input.GZ", 1)) + .withDecompression(CompressionMode.GZIP); + assertFalse(source.isSplittable()); + + // Other extensions are also not splittable. + source = CompressedSource.from(new ByteSource("input.txt", 1)) + .withDecompression(CompressionMode.GZIP); + assertFalse(source.isSplittable()); + source = CompressedSource.from(new ByteSource("input.csv", 1)) + .withDecompression(CompressionMode.GZIP); + assertFalse(source.isSplittable()); + } + /** * Test reading nonempty input with bzip2. */ @@ -492,7 +542,7 @@ protected boolean readNextRecord() throws IOException { if (channel.read(buff) != 1) { return false; } - current = new Byte(buff.get(0)); + current = buff.get(0); offset += 1; return true; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 90306a921b..53295b0e56 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -24,6 +24,7 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; @@ -60,6 +61,7 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.common.collect.ImmutableList; +import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -75,6 +77,7 @@ import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; +import java.io.OutputStream; import java.io.PrintStream; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; @@ -473,52 +476,188 @@ public void testCompressionTypeIsSet() throws Exception { assertEquals(CompressionType.GZIP, read.getCompressionType()); } - @Test - public void testCompressedRead() throws Exception { - String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; - File tmpFile = tmpFolder.newFile(); - String filename = tmpFile.getPath(); - - List expected = new ArrayList<>(); - try (PrintStream writer = - new PrintStream(new GZIPOutputStream(new FileOutputStream(tmpFile)))) { + /** + * Helper that writes the given lines (adding a newline in between) to a stream, then closes the + * stream. + */ + private static void writeToStreamAndClose(String[] lines, OutputStream outputStream) { + try (PrintStream writer = new PrintStream(outputStream)) { for (String line : lines) { writer.println(line); - expected.add(line); } } + } + /** + * Helper method that runs TextIO.Read.from(filename).withCompressionType(compressionType) + * and asserts that the results match the given expected output. + */ + private static void assertReadingCompressedFileMatchesExpected( + String filename, CompressionType compressionType, String[] expected) { Pipeline p = TestPipeline.create(); - TextIO.Read.Bound read = - TextIO.Read.from(filename).withCompressionType(CompressionType.GZIP); + TextIO.Read.from(filename).withCompressionType(compressionType); PCollection output = p.apply(read); DataflowAssert.that(output).containsInAnyOrder(expected); p.run(); } + /** Helper to make an array of compressible strings. Returns ["word"+i] for i in range(0,n). */ + private static String[] makeLines(int n) { + String[] ret = new String[n]; + for (int i = 0; i < n; ++i) { + ret[i] = "word" + i; + } + return ret; + } + + /** Tests reading from a small, gzipped file with no .gz extension but GZIP compression set. */ @Test - public void testGZIPReadWhenUncompressed() throws Exception { - String[] lines = {"Meritorious condor", "Obnoxious duck"}; - File tmpFile = tmpFolder.newFile(); + public void testSmallCompressedGzipReadNoExtension() throws Exception { + String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; + File tmpFile = tmpFolder.newFile(); // no GZ extension String filename = tmpFile.getPath(); - List expected = new ArrayList<>(); - try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) { - for (String line : lines) { - writer.println(line); - expected.add(line); - } - } + writeToStreamAndClose(lines, new GZIPOutputStream(new FileOutputStream(tmpFile))); + assertReadingCompressedFileMatchesExpected(filename, CompressionType.GZIP, lines); + } - Pipeline p = TestPipeline.create(); - TextIO.Read.Bound read = - TextIO.Read.from(filename).withCompressionType(CompressionType.GZIP); - PCollection output = p.apply(read); + /** + * Tests reading from a small, gzipped file with .gz extension and AUTO or GZIP compression set. + */ + @Test + public void testSmallCompressedGzipRead() throws Exception { + String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; + File tmpFile = tmpFolder.newFile("small_gzip.gz"); + String filename = tmpFile.getPath(); - DataflowAssert.that(output).containsInAnyOrder(expected); - p.run(); + writeToStreamAndClose(lines, new GZIPOutputStream(new FileOutputStream(tmpFile))); + // Should work in AUTO mode. + assertReadingCompressedFileMatchesExpected(filename, CompressionType.AUTO, lines); + // Should work in GZIP mode. + assertReadingCompressedFileMatchesExpected(filename, CompressionType.GZIP, lines); + } + + /** + * Tests reading from a small, uncompressed file with .gz extension. + * This must work in AUTO or GZIP modes. This is needed because some network file systems / HTTP + * clients will transparently decompress gzipped content. + */ + @Test + public void testSmallCompressedGzipReadActuallyUncompressed() throws Exception { + String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; + File tmpFile = tmpFolder.newFile("not_really_gzipped.gz"); // GZ file extension lies + String filename = tmpFile.getPath(); + + writeToStreamAndClose(lines, new FileOutputStream(tmpFile)); + // Should work with GZIP compression set. + assertReadingCompressedFileMatchesExpected(filename, CompressionType.GZIP, lines); + // Should also work with AUTO mode set. + assertReadingCompressedFileMatchesExpected(filename, CompressionType.AUTO, lines); + } + + /** Tests reading from a small, bzip2ed file with no .bz2 extension but BZIP2 compression set. */ + @Test + public void testSmallCompressedBzip2ReadNoExtension() throws Exception { + String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; + File tmpFile = tmpFolder.newFile(); // no BZ2 extension + String filename = tmpFile.getPath(); + + writeToStreamAndClose(lines, new BZip2CompressorOutputStream(new FileOutputStream(tmpFile))); + assertReadingCompressedFileMatchesExpected(filename, CompressionType.BZIP2, lines); + } + + /** + * Tests reading from a small, bzip2ed file with .bz2 extension and AUTO or BZIP2 compression set. + */ + @Test + public void testSmallCompressedBzipRead() throws Exception { + String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; + File tmpFile = tmpFolder.newFile("small_bzip2.bz2"); + String filename = tmpFile.getPath(); + + writeToStreamAndClose(lines, new BZip2CompressorOutputStream(new FileOutputStream(tmpFile))); + // Should work in AUTO mode. + assertReadingCompressedFileMatchesExpected(filename, CompressionType.AUTO, lines); + // Should work in BZIP2 mode. + assertReadingCompressedFileMatchesExpected(filename, CompressionType.BZIP2, lines); + } + + /** + * Tests reading from a large, bzip2ed file with .bz2 extension and AUTO or BZIP2 compression set. + * It is important to test a large compressible file because using only small files may mask bugs + * from range tracking that can only occur if the file compression ratio is high -- small + * compressed files are usually as big as the uncompressed ones or bigger. + */ + @Test + public void testLargeCompressedBzipRead() throws Exception { + String[] lines = makeLines(5000); + File bz2File = tmpFolder.newFile("large_bzip2.bz2"); + String bz2Filename = bz2File.getPath(); + + writeToStreamAndClose(lines, new BZip2CompressorOutputStream(new FileOutputStream(bz2File))); + // Should work in AUTO mode. + assertReadingCompressedFileMatchesExpected(bz2Filename, CompressionType.AUTO, lines); + // Should work in BZIP2 mode. + assertReadingCompressedFileMatchesExpected(bz2Filename, CompressionType.BZIP2, lines); + + // Confirm that the compressed file is smaller than the uncompressed file. + File txtFile = tmpFolder.newFile("large_bzip2.txt"); + writeToStreamAndClose(lines, new FileOutputStream(txtFile)); + assertThat(Files.size(txtFile.toPath()), greaterThan(Files.size(bz2File.toPath()))); + } + + /** + * Tests reading from a large, gzipped file with .gz extension and AUTO or GZIP compression set. + * It is important to test a large compressible file because using only small files may mask bugs + * from range tracking that can only occur if the file compression ratio is high -- small + * compressed files are usually as big as the uncompressed ones or bigger. + */ + @Test + public void testLargeCompressedGzipRead() throws Exception { + String[] lines = makeLines(5000); + File gzFile = tmpFolder.newFile("large_gzip.gz"); + String gzFilename = gzFile.getPath(); + + writeToStreamAndClose(lines, new GZIPOutputStream(new FileOutputStream(gzFile))); + // Should work in AUTO mode. + assertReadingCompressedFileMatchesExpected(gzFilename, CompressionType.AUTO, lines); + // Should work in BZIP2 mode. + assertReadingCompressedFileMatchesExpected(gzFilename, CompressionType.GZIP, lines); + + // Confirm that the compressed file is smaller than the uncompressed file. + File txtFile = tmpFolder.newFile("large_gzip.txt"); + writeToStreamAndClose(lines, new FileOutputStream(txtFile)); + assertThat(Files.size(txtFile.toPath()), greaterThan(Files.size(gzFile.toPath()))); + } + + /** + * Tests reading from a large, uncompressed file. + */ + @Test + public void testLargeUncompressedReadTxt() throws Exception { + String[] lines = makeLines(5000); + File txtFile = tmpFolder.newFile("large_file.txt"); + String txtFilename = txtFile.getPath(); + + writeToStreamAndClose(lines, new FileOutputStream(txtFile)); + // Should work in AUTO mode. + assertReadingCompressedFileMatchesExpected(txtFilename, CompressionType.AUTO, lines); + } + + /** + * Tests reading from a large, uncompressed file with a weird file extension. + */ + @Test + public void testLargeUncompressedReadWeirdExtension() throws Exception { + String[] lines = makeLines(5000); + File txtFile = tmpFolder.newFile("large_file.bin.data.foo"); + String txtFilename = txtFile.getPath(); + + writeToStreamAndClose(lines, new FileOutputStream(txtFile)); + // Should work in AUTO mode. + assertReadingCompressedFileMatchesExpected(txtFilename, CompressionType.AUTO, lines); } @Test From a0a15a79088003cbe2646bd469d626de04f8ced3 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Mon, 8 Aug 2016 11:23:50 -0700 Subject: [PATCH 489/751] Version management: update to worker container version 1.6.1 (#359) --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 7a1a99c5df..341afbe075 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -222,9 +222,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.6.0"; + = "dataflow.gcr.io/v1beta3/java-batch:1.6.1"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.6.0"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.6.1"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 1f1e98b8e2e384fbdea8df191947fd4deab81e32 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 8 Aug 2016 15:27:48 -0700 Subject: [PATCH 490/751] Use EqualsTester in ProxyInvocationHandlerTest (#358) This tests the equality groups instead of manual assertions, including same-reference equality. --- .../options/ProxyInvocationHandlerTest.java | 34 ++++--------------- 1 file changed, 7 insertions(+), 27 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java index a77b329616..89cdcc0fd0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java @@ -21,8 +21,6 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; - -import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; @@ -30,6 +28,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; @@ -37,6 +36,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; +import com.google.common.testing.EqualsTester; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -215,37 +215,17 @@ public void testAnnotationDefaults() throws Exception { } @Test - public void testEquals() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy = handler.as(Simple.class); - JLSDefaults sameAsProxy = proxy.as(JLSDefaults.class); - ProxyInvocationHandler handler2 = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy2 = handler2.as(Simple.class); - JLSDefaults sameAsProxy2 = proxy2.as(JLSDefaults.class); - assertTrue(handler.equals(proxy)); - assertTrue(proxy.equals(proxy)); - assertTrue(proxy.equals(sameAsProxy)); - assertFalse(handler.equals(handler2)); - assertFalse(proxy.equals(proxy2)); - assertFalse(proxy.equals(sameAsProxy2)); - } - - @Test - public void testHashCode() throws Exception { + public void testEqualsAndHashCode() throws Exception { ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); Simple proxy = handler.as(Simple.class); JLSDefaults sameAsProxy = proxy.as(JLSDefaults.class); - ProxyInvocationHandler handler2 = new ProxyInvocationHandler(Maps.newHashMap()); Simple proxy2 = handler2.as(Simple.class); JLSDefaults sameAsProxy2 = proxy2.as(JLSDefaults.class); - - // Hashcode comparisons below depend on random numbers, so could fail if seed changes. - assertTrue(handler.hashCode() == proxy.hashCode()); - assertTrue(proxy.hashCode() == sameAsProxy.hashCode()); - assertFalse(handler.hashCode() == handler2.hashCode()); - assertFalse(proxy.hashCode() == proxy2.hashCode()); - assertFalse(proxy.hashCode() == sameAsProxy2.hashCode()); + new EqualsTester() + .addEqualityGroup(handler, proxy, sameAsProxy) + .addEqualityGroup(handler2, proxy2, sameAsProxy2) + .testEquals(); } @Test From 16ee7d8b98a7bd934af1f3f1b8f8ad26ef075e78 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Wed, 10 Aug 2016 10:38:14 -0700 Subject: [PATCH 491/751] Use Datastore AncestorKey for AutoComplete example (#354) * Use Datastore AncestorKey for AutoComplete example * Remove unused import * Add ancestor key --- .../examples/complete/AutoComplete.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java index 6e50fe1047..6ff9139e7d 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.examples.complete; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; import com.google.api.services.bigquery.model.TableFieldSchema; @@ -61,7 +62,6 @@ import com.google.datastore.v1beta3.Entity; import com.google.datastore.v1beta3.Key; import com.google.datastore.v1beta3.Value; -import com.google.datastore.v1beta3.client.DatastoreHelper; import org.joda.time.Duration; @@ -384,18 +384,24 @@ static TableSchema getSchema() { /** * Takes as input a the top candidates per prefix, and emits an entity * suitable for writing to Datastore. + * + *

            Note: We use ancestor keys for strong consistency. See the Cloud Datastore documentation on + * + * Structuring Data for Strong Consistency */ static class FormatForDatastore extends DoFn>, Entity> { private String kind; + private String ancestorKey; - public FormatForDatastore(String kind) { + public FormatForDatastore(String kind, String ancestorKey) { this.kind = kind; + this.ancestorKey = ancestorKey; } @Override public void processElement(ProcessContext c) { Entity.Builder entityBuilder = Entity.newBuilder(); - Key key = DatastoreHelper.makeKey(kind, c.element().getKey()).build(); + Key key = makeKey(makeKey(kind, ancestorKey).build(), kind, c.element().getKey()).build(); entityBuilder.setKey(key); List candidates = new ArrayList<>(); @@ -446,6 +452,11 @@ private static interface Options extends ExamplePubsubTopicOptions, ExampleBigQu @Description("Datastore output dataset ID, defaults to project ID") String getOutputDataset(); void setOutputDataset(String value); + + @Description("Datastore ancestor key") + @Default.String("root") + String getDatastoreAncestorKey(); + void setDatastoreAncestorKey(String value); } public static void main(String[] args) throws IOException { @@ -486,7 +497,8 @@ public static void main(String[] args) throws IOException { if (options.getOutputToDatastore()) { toWrite - .apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind()))) + .apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind(), + options.getDatastoreAncestorKey()))) .apply(DatastoreIO.v1beta3().write().withProjectId(MoreObjects.firstNonNull( options.getOutputDataset(), options.getProject()))); } From 3452e6b1be5e81a90228000b43a2c313e108b031 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Wed, 10 Aug 2016 22:19:54 -0700 Subject: [PATCH 492/751] Datastore Read as a composite PTransform (#352) --- .../dataflow/sdk/io/datastore/V1Beta3.java | 819 +++++++++--------- .../sdk/io/datastore/V1Beta3Test.java | 458 +++++----- 2 files changed, 613 insertions(+), 664 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java index 10c093745d..06b11eeb3d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java @@ -22,7 +22,6 @@ import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; import static com.google.datastore.v1beta3.QueryResultBatch.MoreResultsType.NOT_FINISHED; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeAndFilter; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeUpsert; @@ -35,24 +34,29 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.Sink; import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; import com.google.cloud.dataflow.sdk.io.Sink.Writer; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.Values; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; -import com.google.common.primitives.Ints; import com.google.datastore.v1beta3.CommitRequest; import com.google.datastore.v1beta3.Entity; import com.google.datastore.v1beta3.EntityResult; @@ -77,7 +81,6 @@ import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; @@ -97,7 +100,8 @@ *

            To read a {@link PCollection} from a query to Datastore, use {@link V1Beta3#read} and * its methods {@link V1Beta3.Read#withProjectId} and {@link V1Beta3.Read#withQuery} to * specify the project to query and the query to read from. You can optionally provide a namespace - * to query within using {@link V1Beta3.Read#withNamespace}. + * to query within using {@link V1Beta3.Read#withNamespace}. You could also optionally specify + * how many splits you want for the query using {@link V1Beta3.Read#withNumQuerySplits}. * *

            For example: * @@ -155,7 +159,7 @@ @Experimental(Experimental.Kind.SOURCE_SINK) public class V1Beta3 { - // A package-private constructor to prevent direct instantiation from outside of this package + // A package-private constructor to prevent direct instantiation from outside of this package V1Beta3() {} /** @@ -166,11 +170,12 @@ public class V1Beta3 { /** * Returns an empty {@link V1Beta3.Read} builder. Configure the source {@code projectId}, - * {@code query}, and optionally {@code namespace} using {@link V1Beta3.Read#withProjectId}, - * {@link V1Beta3.Read#withQuery}, and {@link V1Beta3.Read#withNamespace}. + * {@code query}, and optionally {@code namespace} and {@code numQuerySplits} using + * {@link V1Beta3.Read#withProjectId}, {@link V1Beta3.Read#withQuery}, + * {@link V1Beta3.Read#withNamespace}, {@link V1Beta3.Read#withNumQuerySplits}. */ public V1Beta3.Read read() { - return new V1Beta3.Read(null, null, null); + return new V1Beta3.Read(null, null, null, 0); } /** @@ -180,6 +185,24 @@ public V1Beta3.Read read() { * @see DatastoreIO */ public static class Read extends PTransform> { + private static final Logger LOG = LoggerFactory.getLogger(Read.class); + + /** An upper bound on the number of splits for a query. */ + public static final int NUM_QUERY_SPLITS_MAX = 50000; + + /** A lower bound on the number of splits for a query. */ + static final int NUM_QUERY_SPLITS_MIN = 12; + + /** Default bundle size of 64MB. */ + static final long DEFAULT_BUNDLE_SIZE_BYTES = 64 * 1024 * 1024; + + /** + * Maximum number of results to request per query. + * + *

            Must be set, or it may result in an I/O error when querying Cloud Datastore. + */ + static final int QUERY_BATCH_LIMIT = 500; + @Nullable private final String projectId; @@ -189,15 +212,100 @@ public static class Read extends PTransform> { @Nullable private final String namespace; + private final int numQuerySplits; + + /** + * Computes the number of splits to be performed on the given query by querying the estimated + * size from Datastore. + */ + static int getEstimatedNumSplits(Datastore datastore, Query query, @Nullable String namespace) { + int numSplits; + try { + long estimatedSizeBytes = getEstimatedSizeBytes(datastore, query, namespace); + numSplits = (int) Math.min(NUM_QUERY_SPLITS_MAX, + Math.round(((double) estimatedSizeBytes) / DEFAULT_BUNDLE_SIZE_BYTES)); + } catch (Exception e) { + LOG.warn("Failed the fetch estimatedSizeBytes for query: {}", query, e); + // Fallback in case estimated size is unavailable. + numSplits = NUM_QUERY_SPLITS_MIN; + } + return Math.max(numSplits, NUM_QUERY_SPLITS_MIN); + } + + /** + * Get the estimated size of the data returned by the given query. + * + *

            Datastore provides no way to get a good estimate of how large the result of a query + * entity kind being queried, using the __Stat_Kind__ system table, assuming exactly 1 kind + * is specified in the query. + * + *

            See https://cloud.google.com/datastore/docs/concepts/stats. + */ + static long getEstimatedSizeBytes(Datastore datastore, Query query, @Nullable String namespace) + throws DatastoreException { + String ourKind = query.getKind(0).getName(); + Query.Builder queryBuilder = Query.newBuilder(); + if (namespace == null) { + queryBuilder.addKindBuilder().setName("__Stat_Kind__"); + } else { + queryBuilder.addKindBuilder().setName("__Ns_Stat_Kind__"); + } + queryBuilder.setFilter(makeFilter("kind_name", EQUAL, makeValue(ourKind).build())); + + // Get the latest statistics + queryBuilder.addOrder(makeOrder("timestamp", DESCENDING)); + queryBuilder.setLimit(Int32Value.newBuilder().setValue(1)); + + RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); + + long now = System.currentTimeMillis(); + RunQueryResponse response = datastore.runQuery(request); + LOG.debug("Query for per-kind statistics took {}ms", System.currentTimeMillis() - now); + + QueryResultBatch batch = response.getBatch(); + if (batch.getEntityResultsCount() == 0) { + throw new NoSuchElementException( + "Datastore statistics for kind " + ourKind + " unavailable"); + } + Entity entity = batch.getEntityResults(0).getEntity(); + return entity.getProperties().get("entity_bytes").getIntegerValue(); + } + + /** Builds a {@link RunQueryRequest} from the {@code query} and {@code namespace}. */ + static RunQueryRequest makeRequest(Query query, @Nullable String namespace) { + RunQueryRequest.Builder requestBuilder = RunQueryRequest.newBuilder().setQuery(query); + if (namespace != null) { + requestBuilder.getPartitionIdBuilder().setNamespaceId(namespace); + } + return requestBuilder.build(); + } + + /** + * A helper function to get the split queries, taking into account the optional + * {@code namespace}. + */ + private static List splitQuery(Query query, @Nullable String namespace, + Datastore datastore, QuerySplitter querySplitter, int numSplits) throws DatastoreException { + // If namespace is set, include it in the split request so splits are calculated accordingly. + PartitionId.Builder partitionBuilder = PartitionId.newBuilder(); + if (namespace != null) { + partitionBuilder.setNamespaceId(namespace); + } + + return querySplitter.getSplits(query, partitionBuilder.build(), numSplits, datastore); + } + /** * Note that only {@code namespace} is really {@code @Nullable}. The other parameters may be * {@code null} as a matter of build order, but if they are {@code null} at instantiation time, * an error will be thrown. */ - private Read(@Nullable String projectId, @Nullable Query query, @Nullable String namespace) { + private Read(@Nullable String projectId, @Nullable Query query, @Nullable String namespace, + int numQuerySplits) { this.projectId = projectId; this.query = query; this.namespace = namespace; + this.numQuerySplits = numQuerySplits; } /** @@ -205,7 +313,7 @@ private Read(@Nullable String projectId, @Nullable Query query, @Nullable String */ public V1Beta3.Read withProjectId(String projectId) { checkNotNull(projectId, "projectId"); - return new V1Beta3.Read(projectId, query, namespace); + return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); } /** @@ -220,14 +328,35 @@ public V1Beta3.Read withQuery(Query query) { checkNotNull(query, "query"); checkArgument(!query.hasLimit() || query.getLimit().getValue() > 0, "Invalid query limit %s: must be positive", query.getLimit().getValue()); - return new V1Beta3.Read(projectId, query, namespace); + return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); } /** * Returns a new {@link V1Beta3.Read} that reads from the given namespace. */ public V1Beta3.Read withNamespace(String namespace) { - return new V1Beta3.Read(projectId, query, namespace); + return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); + } + + /** + * Returns a new {@link V1Beta3.Read} that reads by splitting the given {@code query} into + * {@code numQuerySplits}. + * + *

            The semantics for the query splitting is defined below: + *

              + *
            • Any value less than or equal to 0 will be ignored, and the number of splits will be + * chosen dynamically at runtime based on the query data size. + *
            • Any value greater than {@link Read#NUM_QUERY_SPLITS_MAX} will be capped at + * {@code NUM_QUERY_SPLITS_MAX}. + *
            • If the {@code query} has a user limit set, then {@code numQuerySplits} will be + * ignored and no split will be performed. + *
            • Under certain cases Cloud Datastore is unable to split query to the requested number of + * splits. In such cases we just use whatever the Datastore returns. + *
            + */ + public V1Beta3.Read withNumQuerySplits(int numQuerySplits) { + return new V1Beta3.Read(projectId, query, namespace, + Math.min(Math.max(numQuerySplits, 0), NUM_QUERY_SPLITS_MAX)); } @Nullable @@ -245,9 +374,45 @@ public String getNamespace() { return namespace; } + + /** + * {@inheritDoc} + */ @Override public PCollection apply(PBegin input) { - return input.apply(com.google.cloud.dataflow.sdk.io.Read.from(getSource())); + V1Beta3Options v1Beta3Options = V1Beta3Options.from(getProjectId(), getQuery(), + getNamespace()); + + /* + * This composite transform involves the following steps: + * 1. Create a singleton of the user provided {@code query} and apply a {@link ParDo} that + * splits the query into {@code numQuerySplits} and assign each split query a unique + * {@code Integer} as the key. The resulting output is of the type + * {@code PCollection>}. + * + * If the value of {@code numQuerySplits} is less than or equal to 0, then the number of + * splits will be computed dynamically based on the size of the data for the {@code query}. + * + * 2. The resulting {@code PCollection} is sharded using a {@link GroupByKey} operation. The + * queries are extracted from they {@code KV>} and flattened to + * output a {@code PCollection}. + * + * 3. In the third step, a {@code ParDo} reads entities for each query and outputs + * a {@code PCollection}. + */ + PCollection> queries = input + .apply(Create.of(query)) + .apply(ParDo.of(new SplitQueryFn(v1Beta3Options, numQuerySplits))); + + PCollection shardedQueries = queries + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(Flatten.iterables()); + + PCollection entities = shardedQueries + .apply(ParDo.of(new ReadFn(v1Beta3Options))); + + return entities; } @Override @@ -277,482 +442,294 @@ public String toString() { .toString(); } - @VisibleForTesting - DatastoreSource getSource() { - return new DatastoreSource(projectId, query, namespace); - } - } - - /** - * Returns an empty {@link V1Beta3.Write} builder. Configure the destination - * {@code projectId} using {@link V1Beta3.Write#withProjectId}. - */ - public Write write() { - return new Write(null); - } - - /** - * A {@link PTransform} that writes {@link Entity} objects to Cloud Datastore. - * - * @see DatastoreIO - */ - public static class Write extends PTransform, PDone> { - @Nullable - private final String projectId; - - /** - * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if - * it is {@code null} at instantiation time, an error will be thrown. - */ - public Write(@Nullable String projectId) { - this.projectId = projectId; - } - /** - * Returns a new {@link Write} that writes to the Cloud Datastore for the specified project. + * A class for v1beta3 Datastore related options. */ - public Write withProjectId(String projectId) { - checkNotNull(projectId, "projectId"); - return new Write(projectId); - } - - @Override - public PDone apply(PCollection input) { - return input.apply( - com.google.cloud.dataflow.sdk.io.Write.to(new DatastoreSink(projectId))); - } - - @Override - public void validate(PCollection input) { - checkNotNull(projectId, "projectId"); - } - - @Nullable - public String getProjectId() { - return projectId; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("projectId", projectId) - .toString(); - } + @VisibleForTesting + static class V1Beta3Options implements Serializable { + private final Query query; + private final String projectId; + @Nullable + private final String namespace; + + private V1Beta3Options(String projectId, Query query, @Nullable String namespace) { + this.projectId = checkNotNull(projectId, "projectId"); + this.query = checkNotNull(query, "query"); + this.namespace = namespace; + } - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("projectId", projectId) - .withLabel("Output Project")); - } - } + public static V1Beta3Options from(String projectId, Query query, @Nullable String namespace) { + return new V1Beta3Options(projectId, query, namespace); + } - /** - * A {@link com.google.cloud.dataflow.sdk.io.Source} that reads data from Datastore. - */ - static class DatastoreSource extends BoundedSource { + public Query getQuery() { + return query; + } - @Override - public Coder getDefaultOutputCoder() { - return ProtoCoder.of(Entity.class); - } + public String getProjectId() { + return projectId; + } - @Override - public boolean producesSortedKeys(PipelineOptions options) { - return false; + @Nullable + public String getNamespace() { + return namespace; + } } - @Override - public List splitIntoBundles(long desiredBundleSizeBytes, - PipelineOptions options) throws Exception { - // Users may request a limit on the number of results. We can currently support this by - // simply disabling parallel reads and using only a single split. - if (query.hasLimit()) { - return ImmutableList.of(this); + /** + * A {@link DoFn} that splits a given query into multiple sub-queries, assigns them unique keys + * and outputs them as {@link KV}. + */ + @VisibleForTesting + static class SplitQueryFn extends DoFn> { + private final V1Beta3Options options; + // number of splits to make for a given query + private final int numSplits; + + private final V1Beta3DatastoreFactory datastoreFactory; + // Datastore client + private transient Datastore datastore; + // Query splitter + private transient QuerySplitter querySplitter; + + public SplitQueryFn(V1Beta3Options options, int numSplits) { + this(options, numSplits, new V1Beta3DatastoreFactory()); } - long numSplits; - try { - numSplits = Math.round(((double) getEstimatedSizeBytes(options)) / desiredBundleSizeBytes); - } catch (Exception e) { - // Fallback in case estimated size is unavailable. TODO: fix this, it's horrible. - numSplits = 12; + @VisibleForTesting + SplitQueryFn(V1Beta3Options options, int numSplits, + V1Beta3DatastoreFactory datastoreFactory) { + this.options = options; + this.numSplits = numSplits; + this.datastoreFactory = datastoreFactory; } - // If the desiredBundleSize or number of workers results in 1 split, simply return - // a source that reads from the original query. - if (numSplits <= 1) { - return ImmutableList.of(this); + @Override + public void startBundle(Context c) throws Exception { + datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), options.projectId); + querySplitter = datastoreFactory.getQuerySplitter(); } - List datastoreSplits; - try { - datastoreSplits = getSplitQueries(Ints.checkedCast(numSplits), options); - } catch (IllegalArgumentException | DatastoreException e) { - LOG.warn("Unable to parallelize the given query: {}", query, e); - return ImmutableList.of(this); - } + @Override + public void processElement(ProcessContext c) throws Exception { + int key = 1; + Query query = c.element(); - ImmutableList.Builder splits = ImmutableList.builder(); - for (Query splitQuery : datastoreSplits) { - splits.add(new DatastoreSource(projectId, splitQuery, namespace)); - } - return splits.build(); - } + // If query has a user set limit, then do not split. + if (query.hasLimit()) { + c.output(KV.of(key, query)); + return; + } - @Override - public BoundedReader createReader(PipelineOptions pipelineOptions) throws IOException { - return new DatastoreReader(this, getDatastore(pipelineOptions)); - } + int estimatedNumSplits; + // Compute the estimated numSplits if numSplits is not specified by the user. + if (numSplits <= 0) { + estimatedNumSplits = getEstimatedNumSplits(datastore, query, options.getNamespace()); + } else { + estimatedNumSplits = numSplits; + } - @Override - public void validate() { - checkNotNull(query, "query"); - checkNotNull(projectId, "projectId"); - } + List querySplits; + try { + querySplits = splitQuery(query, options.getNamespace(), datastore, querySplitter, + estimatedNumSplits); + } catch (Exception e) { + LOG.warn("Unable to parallelize the given query: {}", query, e); + querySplits = ImmutableList.of(query); + } - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - // Datastore provides no way to get a good estimate of how large the result of a query - // will be. As a rough approximation, we attempt to fetch the statistics of the whole - // entity kind being queried, using the __Stat_Kind__ system table, assuming exactly 1 kind - // is specified in the query. - // - // See https://cloud.google.com/datastore/docs/concepts/stats - if (mockEstimateSizeBytes != null) { - return mockEstimateSizeBytes; + // assign unique keys to query splits. + for (Query subquery : querySplits) { + c.output(KV.of(key++, subquery)); + } } - Datastore datastore = getDatastore(options); - if (query.getKindCount() != 1) { - throw new UnsupportedOperationException( - "Can only estimate size for queries specifying exactly 1 kind."); + @Override + public void populateDisplayData(Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull(DisplayData.item("projectId", options.getProjectId()) + .withLabel("ProjectId")) + .addIfNotNull(DisplayData.item("namespace", options.getNamespace()) + .withLabel("Namespace")) + .addIfNotNull(DisplayData.item("query", options.getQuery().toString()) + .withLabel("Query")); } - String ourKind = query.getKind(0).getName(); - long latestTimestamp = queryLatestStatisticsTimestamp(datastore); - Query.Builder query = Query.newBuilder(); - if (namespace == null) { - query.addKindBuilder().setName("__Stat_Kind__"); - } else { - query.addKindBuilder().setName("__Ns_Stat_Kind__"); + } + + /** + * A {@link DoFn} that reads entities from Datastore for each query. + */ + @VisibleForTesting + static class ReadFn extends DoFn { + private final V1Beta3Options options; + private final V1Beta3DatastoreFactory datastoreFactory; + // Datastore client + private transient Datastore datastore; + + public ReadFn(V1Beta3Options options) { + this(options, new V1Beta3DatastoreFactory()); } - query.setFilter(makeAndFilter( - makeFilter("kind_name", EQUAL, makeValue(ourKind)).build(), - makeFilter("timestamp", EQUAL, makeValue(latestTimestamp)).build())); - RunQueryRequest request = makeRequest(query.build()); - long now = System.currentTimeMillis(); - RunQueryResponse response = datastore.runQuery(request); - LOG.info("Query for per-kind statistics took {}ms", System.currentTimeMillis() - now); + @VisibleForTesting + ReadFn(V1Beta3Options options, V1Beta3DatastoreFactory datastoreFactory) { + this.options = options; + this.datastoreFactory = datastoreFactory; + } - QueryResultBatch batch = response.getBatch(); - if (batch.getEntityResultsCount() == 0) { - throw new NoSuchElementException( - "Datastore statistics for kind " + ourKind + " unavailable"); + @Override + public void startBundle(Context c) throws Exception { + datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), options.getProjectId()); } - Entity entity = batch.getEntityResults(0).getEntity(); - return entity.getProperties().get("entity_bytes").getIntegerValue(); - } - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("projectId", projectId) - .withLabel("ProjectId")) - .addIfNotNull(DisplayData.item("namespace", namespace) - .withLabel("Namespace")) - .addIfNotNull(DisplayData.item("query", query.toString()) - .withLabel("Query")); - } + /** Read and output entities for the given query. */ + @Override + public void processElement(ProcessContext context) throws Exception { + Query query = context.element(); + String namespace = options.getNamespace(); + int userLimit = query.hasLimit() + ? query.getLimit().getValue() : Integer.MAX_VALUE; - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("projectId", projectId) - .add("query", query) - .add("namespace", namespace) - .toString(); - } + boolean moreResults = true; + QueryResultBatch currentBatch = null; - private static final Logger LOG = LoggerFactory.getLogger(DatastoreSource.class); - private final String projectId; - private final Query query; - @Nullable - private final String namespace; + while (moreResults) { + Query.Builder queryBuilder = query.toBuilder().clone(); + queryBuilder.setLimit(Int32Value.newBuilder().setValue( + Math.min(userLimit, QUERY_BATCH_LIMIT))); - /** For testing only. TODO: This could be much cleaner with dependency injection. */ - @Nullable - private QuerySplitter mockSplitter; - @Nullable - private Long mockEstimateSizeBytes; + if (currentBatch != null && !currentBatch.getEndCursor().isEmpty()) { + queryBuilder.setStartCursor(currentBatch.getEndCursor()); + } - DatastoreSource(String projectId, Query query, @Nullable String namespace) { - this.projectId = projectId; - this.query = query; - this.namespace = namespace; - } + RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); + RunQueryResponse response = datastore.runQuery(request); - /** - * A helper function to get the split queries, taking into account the optional - * {@code namespace} and whether there is a mock splitter. - */ - private List getSplitQueries(int numSplits, PipelineOptions options) - throws DatastoreException { - // If namespace is set, include it in the split request so splits are calculated accordingly. - PartitionId.Builder partitionBuilder = PartitionId.newBuilder(); - if (namespace != null) { - partitionBuilder.setNamespaceId(namespace); - } + currentBatch = response.getBatch(); - if (mockSplitter != null) { - // For testing. - return mockSplitter.getSplits(query, partitionBuilder.build(), numSplits, null); - } + // MORE_RESULTS_AFTER_LIMIT is not implemented yet: + // https://groups.google.com/forum/#!topic/gcd-discuss/iNs6M1jA2Vw, so + // use result count to determine if more results might exist. + int numFetch = currentBatch.getEntityResultsCount(); + if (query.hasLimit()) { + verify(userLimit >= numFetch, + "Expected userLimit %s >= numFetch %s, because query limit %s must be <= userLimit", + userLimit, numFetch, query.getLimit()); + userLimit -= numFetch; + } - return DatastoreHelper.getQuerySplitter().getSplits( - query, partitionBuilder.build(), numSplits, getDatastore(options)); - } + // output all the entities from the current batch. + for (EntityResult entityResult : currentBatch.getEntityResultsList()) { + context.output(entityResult.getEntity()); + } - /** - * Builds a {@link RunQueryRequest} from the {@code query}, using the properties set on this - * {@code DatastoreSource}. For example, sets the {@code namespace} for the request. - */ - private RunQueryRequest makeRequest(Query query) { - RunQueryRequest.Builder requestBuilder = RunQueryRequest.newBuilder().setQuery(query); - if (namespace != null) { - requestBuilder.getPartitionIdBuilder().setNamespaceId(namespace); + // Check if we have more entities to be read. + moreResults = + // User-limit does not exist (so userLimit == MAX_VALUE) and/or has not been satisfied + (userLimit > 0) + // All indications from the API are that there are/may be more results. + && ((numFetch == QUERY_BATCH_LIMIT) + || (currentBatch.getMoreResults() == NOT_FINISHED)); + } } - return requestBuilder.build(); } /** - * Datastore system tables with statistics are periodically updated. This method fetches - * the latest timestamp of statistics update using the {@code __Stat_Total__} table. + * A wrapper factory class for Datastore singleton classes {@link DatastoreFactory} and + * {@link QuerySplitter} + * + *

            {@link DatastoreFactory} and {@link QuerySplitter} are not java serializable, hence + * wrapping them under this class, which implements {@link Serializable}. */ - private long queryLatestStatisticsTimestamp(Datastore datastore) throws DatastoreException { - Query.Builder query = Query.newBuilder(); - query.addKindBuilder().setName("__Stat_Total__"); - query.addOrder(makeOrder("timestamp", DESCENDING)); - query.setLimit(Int32Value.newBuilder().setValue(1)); - RunQueryRequest request = makeRequest(query.build()); + @VisibleForTesting + static class V1Beta3DatastoreFactory implements Serializable { + + /** Builds a Datastore client for the given pipeline options and project. */ + public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { + DatastoreOptions.Builder builder = + new DatastoreOptions.Builder() + .projectId(projectId) + .initializer( + new RetryHttpRequestInitializer() + ); + + Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); + if (credential != null) { + builder.credential(credential); + } - long now = System.currentTimeMillis(); - RunQueryResponse response = datastore.runQuery(request); - LOG.info("Query for latest stats timestamp of project {} took {}ms", projectId, - System.currentTimeMillis() - now); - QueryResultBatch batch = response.getBatch(); - if (batch.getEntityResultsCount() == 0) { - throw new NoSuchElementException( - "Datastore total statistics for project " + projectId + " unavailable"); + return DatastoreFactory.get().create(builder.build()); } - Entity entity = batch.getEntityResults(0).getEntity(); - return entity.getProperties().get("timestamp").getTimestampValue().getNanos(); - } - - private Datastore getDatastore(PipelineOptions pipelineOptions) { - DatastoreOptions.Builder builder = - new DatastoreOptions.Builder() - .projectId(projectId) - .initializer( - new RetryHttpRequestInitializer() - ); - Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); - if (credential != null) { - builder.credential(credential); + /** Builds a Datastore {@link QuerySplitter}. */ + public QuerySplitter getQuerySplitter() { + return DatastoreHelper.getQuerySplitter(); } - return DatastoreFactory.get().create(builder.build()); - } - - /** For testing only. */ - DatastoreSource withMockSplitter(QuerySplitter splitter) { - DatastoreSource res = new DatastoreSource(projectId, query, namespace); - res.mockSplitter = splitter; - res.mockEstimateSizeBytes = mockEstimateSizeBytes; - return res; - } - - /** For testing only. */ - DatastoreSource withMockEstimateSizeBytes(Long estimateSizeBytes) { - DatastoreSource res = new DatastoreSource(projectId, query, namespace); - res.mockSplitter = mockSplitter; - res.mockEstimateSizeBytes = estimateSizeBytes; - return res; } + } - @VisibleForTesting - Query getQuery() { - return query; - } + /** + * Returns an empty {@link V1Beta3.Write} builder. Configure the destination + * {@code projectId} using {@link V1Beta3.Write#withProjectId}. + */ + public Write write() { + return new Write(null); } /** - * A {@link DatastoreSource.Reader} over the records from a query of the datastore. + * A {@link PTransform} that writes {@link Entity} objects to Cloud Datastore. * - *

            Timestamped records are currently not supported. - * All records implicitly have the timestamp of {@code BoundedWindow.TIMESTAMP_MIN_VALUE}. + * @see DatastoreIO */ - @VisibleForTesting - static class DatastoreReader extends BoundedSource.BoundedReader { - private final DatastoreSource source; - - /** - * Datastore to read from. - */ - private final Datastore datastore; - - /** - * True if more results may be available. - */ - private boolean moreResults; - - /** - * Iterator over records. - */ - private java.util.Iterator entities; - - /** - * Current batch of query results. - */ - private QueryResultBatch currentBatch; - - /** - * Maximum number of results to request per query. - * - *

            Must be set, or it may result in an I/O error when querying - * Cloud Datastore. - */ - private static final int QUERY_BATCH_LIMIT = 500; + public static class Write extends PTransform, PDone> { + @Nullable + private final String projectId; /** - * Remaining user-requested limit on the number of sources to return. If the user did not set a - * limit, then this variable will always have the value {@link Integer#MAX_VALUE} and will never - * be decremented. + * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if + * it is {@code null} at instantiation time, an error will be thrown. */ - private int userLimit; - - private volatile boolean done = false; - - private Entity currentEntity; + public Write(@Nullable String projectId) { + this.projectId = projectId; + } /** - * Returns a DatastoreReader with DatastoreSource and Datastore object set. - * - * @param datastore a datastore connection to use. + * Returns a new {@link Write} that writes to the Cloud Datastore for the specified project. */ - public DatastoreReader(DatastoreSource source, Datastore datastore) { - this.source = source; - this.datastore = datastore; - // If the user set a limit on the query, remember it. Otherwise pin to MAX_VALUE. - userLimit = source.query.hasLimit() - ? source.query.getLimit().getValue() : Integer.MAX_VALUE; - } - - @Override - public Entity getCurrent() { - return currentEntity; - } - - @Override - public final long getSplitPointsConsumed() { - return done ? 1 : 0; - } - - @Override - public final long getSplitPointsRemaining() { - return done ? 0 : 1; - } - - @Override - public boolean start() throws IOException { - return advance(); + public Write withProjectId(String projectId) { + checkNotNull(projectId, "projectId"); + return new Write(projectId); } @Override - public boolean advance() throws IOException { - if (entities == null || (!entities.hasNext() && moreResults)) { - try { - entities = getIteratorAndMoveCursor(); - } catch (DatastoreException e) { - throw new IOException(e); - } - } - - if (entities == null || !entities.hasNext()) { - currentEntity = null; - done = true; - return false; - } - - currentEntity = entities.next().getEntity(); - return true; + public PDone apply(PCollection input) { + return input.apply( + com.google.cloud.dataflow.sdk.io.Write.to(new DatastoreSink(projectId))); } @Override - public void close() throws IOException { - // Nothing + public void validate(PCollection input) { + checkNotNull(projectId, "projectId"); } - @Override - public DatastoreSource getCurrentSource() { - return source; + @Nullable + public String getProjectId() { + return projectId; } @Override - public DatastoreSource splitAtFraction(double fraction) { - // Not supported. - return null; + public String toString() { + return MoreObjects.toStringHelper(getClass()) + .add("projectId", projectId) + .toString(); } @Override - public Double getFractionConsumed() { - // Not supported. - return null; - } - - /** - * Returns an iterator over the next batch of records for the query - * and updates the cursor to get the next batch as needed. - * Query has specified limit and offset from InputSplit. - */ - private Iterator getIteratorAndMoveCursor() throws DatastoreException { - Query.Builder query = source.query.toBuilder().clone(); - query.setLimit(Int32Value.newBuilder().setValue(Math.min(userLimit, QUERY_BATCH_LIMIT))); - if (currentBatch != null && !currentBatch.getEndCursor().isEmpty()) { - query.setStartCursor(currentBatch.getEndCursor()); - } - - RunQueryRequest request = source.makeRequest(query.build()); - RunQueryResponse response = datastore.runQuery(request); - - currentBatch = response.getBatch(); - - // MORE_RESULTS_AFTER_LIMIT is not implemented yet: - // https://groups.google.com/forum/#!topic/gcd-discuss/iNs6M1jA2Vw, so - // use result count to determine if more results might exist. - int numFetch = currentBatch.getEntityResultsCount(); - if (source.query.hasLimit()) { - verify(userLimit >= numFetch, - "Expected userLimit %s >= numFetch %s, because query limit %s should be <= userLimit", - userLimit, numFetch, query.getLimit()); - userLimit -= numFetch; - } - moreResults = - // User-limit does not exist (so userLimit == MAX_VALUE) and/or has not been satisfied. - (userLimit > 0) - // All indications from the API are that there are/may be more results. - && ((numFetch == QUERY_BATCH_LIMIT) - || (currentBatch.getMoreResults() == NOT_FINISHED)); - - // May receive a batch of 0 results if the number of records is a multiple - // of the request limit. - if (numFetch == 0) { - return null; - } - - return currentBatch.getEntityResultsList().iterator(); + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull(DisplayData.item("projectId", projectId) + .withLabel("Output Project")); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java index 0f9733eda5..7f668565e7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java @@ -16,9 +16,18 @@ package com.google.cloud.dataflow.sdk.io.datastore; +import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.DEFAULT_BUNDLE_SIZE_BYTES; +import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.QUERY_BATCH_LIMIT; +import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.getEstimatedSizeBytes; +import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.makeRequest; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; +import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; +import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; @@ -28,37 +37,32 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreReader; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreSource; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreWriter; -import com.google.cloud.dataflow.sdk.options.GcpOptions; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.ReadFn; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.SplitQueryFn; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.V1Beta3DatastoreFactory; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.V1Beta3Options; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester.CloningBehavior; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.TestCredential; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.collect.Lists; import com.google.datastore.v1beta3.Entity; import com.google.datastore.v1beta3.EntityResult; import com.google.datastore.v1beta3.Key; -import com.google.datastore.v1beta3.KindExpression; import com.google.datastore.v1beta3.PartitionId; -import com.google.datastore.v1beta3.PropertyFilter; import com.google.datastore.v1beta3.Query; import com.google.datastore.v1beta3.QueryResultBatch; import com.google.datastore.v1beta3.RunQueryRequest; import com.google.datastore.v1beta3.RunQueryResponse; -import com.google.datastore.v1beta3.Value; import com.google.datastore.v1beta3.client.Datastore; -import com.google.datastore.v1beta3.client.DatastoreHelper; import com.google.datastore.v1beta3.client.QuerySplitter; import com.google.protobuf.Int32Value; @@ -75,8 +79,10 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; import java.util.List; -import java.util.NoSuchElementException; +import java.util.Set; /** * Tests for {@link V1Beta3}. @@ -87,36 +93,36 @@ public class V1Beta3Test { private static final String NAMESPACE = "testNamespace"; private static final String KIND = "testKind"; private static final Query QUERY; + private static final V1Beta3Options v1Beta3Options; static { Query.Builder q = Query.newBuilder(); q.addKindBuilder().setName(KIND); QUERY = q.build(); + v1Beta3Options = V1Beta3Options.from(PROJECT_ID, QUERY, NAMESPACE); } private V1Beta3.Read initialRead; @Mock Datastore mockDatastore; + @Mock + QuerySplitter mockQuerySplitter; + @Mock + V1Beta3DatastoreFactory mockDatastoreFactory; @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final ExpectedLogs logged = ExpectedLogs.none(DatastoreSource.class); - @Before public void setUp() { MockitoAnnotations.initMocks(this); initialRead = DatastoreIO.v1beta3().read() .withProjectId(PROJECT_ID).withQuery(QUERY).withNamespace(NAMESPACE); - } - /** - * Helper function to create a test {@code DataflowPipelineOptions}. - */ - static final GcpOptions testPipelineOptions() { - GcpOptions options = PipelineOptionsFactory.as(GcpOptions.class); - options.setGcpCredential(new TestCredential()); - return options; + when(mockDatastoreFactory.getDatastore(any(PipelineOptions.class), any(String.class))) + .thenReturn(mockDatastore); + when(mockDatastoreFactory.getQuerySplitter()) + .thenReturn(mockQuerySplitter); } @Test @@ -229,182 +235,6 @@ public void testWriteDisplayData() { assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); } - @Test - public void testQuerySplitBasic() throws Exception { - KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); - Query query = Query.newBuilder().addKind(mykind).build(); - - List mockSplits = new ArrayList<>(); - for (int i = 0; i < 8; ++i) { - mockSplits.add( - Query.newBuilder() - .addKind(mykind) - .setFilter( - DatastoreHelper.makeFilter("foo", PropertyFilter.Operator.EQUAL, - Value.newBuilder().setIntegerValue(i).build())) - .build()); - } - - QuerySplitter splitter = mock(QuerySplitter.class); - /* No namespace */ - PartitionId partition = PartitionId.newBuilder().build(); - when(splitter.getSplits(any(Query.class), eq(partition), eq(8), any(Datastore.class))) - .thenReturn(mockSplits); - - DatastoreSource io = initialRead - .withNamespace(null) - .withQuery(query) - .getSource() - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(8 * 1024L); - - List bundles = io.splitIntoBundles(1024, testPipelineOptions()); - assertEquals(8, bundles.size()); - for (int i = 0; i < 8; ++i) { - DatastoreSource bundle = bundles.get(i); - Query bundleQuery = bundle.getQuery(); - assertEquals("mykind", bundleQuery.getKind(0).getName()); - assertEquals(i, bundleQuery.getFilter().getPropertyFilter().getValue().getIntegerValue()); - } - } - - /** - * Verifies that when namespace is set in the source, the split request includes the namespace. - */ - @Test - public void testSourceWithNamespace() throws Exception { - QuerySplitter splitter = mock(QuerySplitter.class); - DatastoreSource io = initialRead - .getSource() - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(8 * 1024L); - - io.splitIntoBundles(1024, testPipelineOptions()); - - PartitionId partition = PartitionId.newBuilder().setNamespaceId(NAMESPACE).build(); - verify(splitter).getSplits(eq(QUERY), eq(partition), eq(8), any(Datastore.class)); - verifyNoMoreInteractions(splitter); - } - - @Test - public void testQuerySplitWithZeroSize() throws Exception { - KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); - Query query = Query.newBuilder().addKind(mykind).build(); - - List mockSplits = Lists.newArrayList( - Query.newBuilder() - .addKind(mykind) - .build()); - - QuerySplitter splitter = mock(QuerySplitter.class); - when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class))) - .thenReturn(mockSplits); - - DatastoreSource io = initialRead - .withQuery(query) - .getSource() - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(0L); - - List bundles = io.splitIntoBundles(1024, testPipelineOptions()); - assertEquals(1, bundles.size()); - verify(splitter, never()) - .getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class)); - DatastoreSource bundle = bundles.get(0); - Query bundleQuery = bundle.getQuery(); - assertEquals("mykind", bundleQuery.getKind(0).getName()); - assertFalse(bundleQuery.hasFilter()); - } - - /** - * Tests that a query with a user-provided limit field does not split, and does not even - * interact with a query splitter. - */ - @Test - public void testQueryDoesNotSplitWithLimitSet() throws Exception { - // Minimal query with a limit - Query query = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(5)).build(); - - // Mock query splitter, should not be invoked. - QuerySplitter splitter = mock(QuerySplitter.class); - when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(2), any(Datastore.class))) - .thenThrow(new AssertionError("Splitter should not be invoked")); - - List bundles = - initialRead - .withQuery(query) - .getSource() - .withMockSplitter(splitter) - .splitIntoBundles(1024, testPipelineOptions()); - - assertEquals(1, bundles.size()); - assertEquals(query, bundles.get(0).getQuery()); - verifyNoMoreInteractions(splitter); - } - - /** - * Tests that when {@link QuerySplitter} cannot split a query, {@link V1Beta3} falls back to - * a single split. - */ - @Test - public void testQuerySplitterThrows() throws Exception { - // Mock query splitter that throws IllegalArgumentException - IllegalArgumentException exception = - new IllegalArgumentException("query not supported by splitter"); - QuerySplitter splitter = mock(QuerySplitter.class); - when( - splitter.getSplits( - any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class))) - .thenThrow(exception); - - Query query = Query.newBuilder().addKind(KindExpression.newBuilder().setName("myKind")).build(); - List bundles = - initialRead - .withQuery(query) - .getSource() - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(10240L) - .splitIntoBundles(1024, testPipelineOptions()); - - assertEquals(1, bundles.size()); - assertEquals(query, bundles.get(0).getQuery()); - verify(splitter, times(1)) - .getSplits( - any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class)); - logged.verifyWarn("Unable to parallelize the given query", exception); - } - - @Test - public void testQuerySplitSizeUnavailable() throws Exception { - KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); - Query query = Query.newBuilder().addKind(mykind).build(); - - List mockSplits = Lists.newArrayList(Query.newBuilder().addKind(mykind).build()); - - QuerySplitter splitter = mock(QuerySplitter.class); - when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(12), any(Datastore.class))) - .thenReturn(mockSplits); - - DatastoreSource io = initialRead - .withQuery(query) - .getSource() - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(8 * 1024L); - - DatastoreSource spiedIo = spy(io); - when(spiedIo.getEstimatedSizeBytes(any(PipelineOptions.class))) - .thenThrow(new NoSuchElementException()); - - List bundles = spiedIo.splitIntoBundles(1024, testPipelineOptions()); - assertEquals(1, bundles.size()); - verify(splitter, never()) - .getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class)); - DatastoreSource bundle = bundles.get(0); - Query bundleQuery = bundle.getQuery(); - assertEquals("mykind", bundleQuery.getKind(0).getName()); - assertFalse(bundleQuery.hasFilter()); - } - /** * Test building a Write using builder methods. */ @@ -489,22 +319,146 @@ public void testAddingEntities() throws Exception { assertThat(writer.entities, containsInAnyOrder(expected.toArray())); } - /** Datastore batch API limit in number of records per query. */ - private static final int DATASTORE_QUERY_BATCH_LIMIT = 500; + /** + * Tests {@link V1Beta3.Read#getEstimatedSizeBytes} to fetch and return estimated size for a + * query. + */ + @Test + public void testEstimatedSizeBytes() throws Exception { + long entityBytes = 100L; + // Per Kind statistics request and response + RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE), NAMESPACE); + RunQueryResponse statResponse = makeStatKindResponse(entityBytes); + + when(mockDatastore.runQuery(statRequest)) + .thenReturn(statResponse); + + assertEquals(entityBytes, getEstimatedSizeBytes(mockDatastore, QUERY, NAMESPACE)); + verify(mockDatastore, times(1)).runQuery(statRequest); + } + + /** + * Tests {@link SplitQueryFn} when number of query splits is specified. + */ + @Test + public void testSplitQueryFnWithNumSplits() throws Exception { + int numSplits = 100; + when(mockQuerySplitter.getSplits( + eq(QUERY), any(PartitionId.class), eq(numSplits), any(Datastore.class))) + .thenReturn(splitQuery(QUERY, numSplits)); + + SplitQueryFn splitQueryFn = new SplitQueryFn(v1Beta3Options, numSplits, mockDatastoreFactory); + DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); + /** + * Although Datastore client is marked transient in {@link SplitQueryFn}, when injected through + * mock factory using a when clause for unit testing purposes, it is not serializable + * because it doesn't have a no-arg constructor. Thus disabling the cloning to prevent the + * doFn from being serialized. + */ + doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); + List> queries = doFnTester.processBatch(QUERY); + + assertEquals(queries.size(), numSplits); + verifyUniqueKeys(queries); + verify(mockQuerySplitter, times(1)).getSplits( + eq(QUERY), any(PartitionId.class), eq(numSplits), any(Datastore.class)); + verifyZeroInteractions(mockDatastore); + } + + /** + * Tests {@link SplitQueryFn} when no query splits is specified. + */ + @Test + public void testSplitQueryFnWithoutNumSplits() throws Exception { + // Force SplitQueryFn to compute the number of query splits + int numSplits = 0; + int expectedNumSplits = 20; + long entityBytes = expectedNumSplits * DEFAULT_BUNDLE_SIZE_BYTES; + + // Per Kind statistics request and response + RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE), NAMESPACE); + RunQueryResponse statResponse = makeStatKindResponse(entityBytes); + + when(mockDatastore.runQuery(statRequest)) + .thenReturn(statResponse); + when(mockQuerySplitter.getSplits( + eq(QUERY), any(PartitionId.class), eq(expectedNumSplits), any(Datastore.class))) + .thenReturn(splitQuery(QUERY, expectedNumSplits)); + + SplitQueryFn splitQueryFn = new SplitQueryFn(v1Beta3Options, numSplits, mockDatastoreFactory); + DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); + doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); + List> queries = doFnTester.processBatch(QUERY); + + assertEquals(queries.size(), expectedNumSplits); + verifyUniqueKeys(queries); + verify(mockQuerySplitter, times(1)).getSplits( + eq(QUERY), any(PartitionId.class), eq(expectedNumSplits), any(Datastore.class)); + verify(mockDatastore, times(1)).runQuery(statRequest); + } + + /** + * Tests {@link V1Beta3.Read.SplitQueryFn} when the query has a user specified limit. + */ + @Test + public void testSplitQueryFnWithQueryLimit() throws Exception { + Query queryWithLimit = QUERY.toBuilder().clone() + .setLimit(Int32Value.newBuilder().setValue(1)) + .build(); + + SplitQueryFn splitQueryFn = new SplitQueryFn(v1Beta3Options, 10, mockDatastoreFactory); + DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); + doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); + List> queries = doFnTester.processBatch(queryWithLimit); + + assertEquals(queries.size(), 1); + verifyUniqueKeys(queries); + verifyNoMoreInteractions(mockDatastore); + verifyNoMoreInteractions(mockQuerySplitter); + } + + /** Tests {@link ReadFn} with a query limit less than one batch. */ + @Test + public void testReadFnWithOneBatch() throws Exception { + readFnTest(5); + } + + /** Tests {@link ReadFn} with a query limit more than one batch, and not a multiple. */ + @Test + public void testReadFnWithMultipleBatches() throws Exception { + readFnTest(QUERY_BATCH_LIMIT + 5); + } + + /** Tests {@link ReadFn} for several batches, using an exact multiple of batch size results. */ + @Test + public void testReadFnWithBatchesExactMultiple() throws Exception { + readFnTest(5 * QUERY_BATCH_LIMIT); + } + + /** Helper Methods */ + + /** A helper function that verifies if all the queries have unique keys. */ + private void verifyUniqueKeys(List> queries) { + Set keys = new HashSet<>(); + for (KV kv: queries) { + keys.add(kv.getKey()); + } + assertEquals(keys.size(), queries.size()); + } /** * A helper function that creates mock {@link Entity} results in response to a query. Always * indicates that more results are available, unless the batch is limited to fewer than - * {@link #DATASTORE_QUERY_BATCH_LIMIT} results. + * {@link V1Beta3.Read#QUERY_BATCH_LIMIT} results. */ private static RunQueryResponse mockResponseForQuery(Query q) { // Every query V1Beta3 sends should have a limit. assertTrue(q.hasLimit()); - // The limit should be in the range [1, DATASTORE_QUERY_BATCH_LIMIT] + // The limit should be in the range [1, QUERY_BATCH_LIMIT] int limit = q.getLimit().getValue(); assertThat(limit, greaterThanOrEqualTo(1)); - assertThat(limit, lessThanOrEqualTo(DATASTORE_QUERY_BATCH_LIMIT)); + assertThat(limit, lessThanOrEqualTo(QUERY_BATCH_LIMIT)); // Create the requested number of entities. List entities = new ArrayList<>(limit); @@ -521,62 +475,80 @@ private static RunQueryResponse mockResponseForQuery(Query q) { .addAllEntityResults(entities) .setEntityResultType(EntityResult.ResultType.FULL) .setMoreResults( - limit == DATASTORE_QUERY_BATCH_LIMIT + limit == QUERY_BATCH_LIMIT ? QueryResultBatch.MoreResultsType.NOT_FINISHED : QueryResultBatch.MoreResultsType.NO_MORE_RESULTS); return ret.build(); } - /** Helper function to run a test reading from a limited-result query. */ - private void runQueryLimitReadTest(int numEntities) throws Exception { + /** Helper function to run a test reading from a {@link ReadFn}. */ + private void readFnTest(int numEntities) throws Exception { // An empty query to read entities. Query query = Query.newBuilder().setLimit( Int32Value.newBuilder().setValue(numEntities)).build(); - V1Beta3.Read read = DatastoreIO.v1beta3().read().withQuery(query).withProjectId("mockProject"); // Use mockResponseForQuery to generate results. when(mockDatastore.runQuery(any(RunQueryRequest.class))) - .thenAnswer( - new Answer() { - @Override - public RunQueryResponse answer(InvocationOnMock invocation) throws Throwable { - Query q = ((RunQueryRequest) invocation.getArguments()[0]).getQuery(); - return mockResponseForQuery(q); - } - }); - - // Actually instantiate the reader. - DatastoreReader reader = new DatastoreReader(read.getSource(), mockDatastore); - - // Simply count the number of results returned by the reader. - assertTrue(reader.start()); - int resultCount = 1; - while (reader.advance()) { - resultCount++; - } - reader.close(); - + .thenAnswer(new Answer() { + @Override + public RunQueryResponse answer(InvocationOnMock invocationOnMock) throws Throwable { + Query q = ((RunQueryRequest) invocationOnMock.getArguments()[0]).getQuery(); + return mockResponseForQuery(q); + } + }); + + ReadFn readFn = new ReadFn(v1Beta3Options, mockDatastoreFactory); + DoFnTester doFnTester = DoFnTester.of(readFn); + /** + * Although Datastore client is marked transient in {@link ReadFn}, when injected through + * mock factory using a when clause for unit testing purposes, it is not serializable + * because it doesn't have a no-arg constructor. Thus disabling the cloning to prevent the + * test object from being serialized. + */ + doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); + List entities = doFnTester.processBatch(query); + + int expectedNumCallsToRunQuery = (int) Math.ceil((double) numEntities / QUERY_BATCH_LIMIT); + verify(mockDatastore, times(expectedNumCallsToRunQuery)).runQuery(any(RunQueryRequest.class)); // Validate the number of results. - assertEquals(numEntities, resultCount); + assertEquals(numEntities, entities.size()); } - /** Tests reading with a query limit less than one batch. */ - @Test - public void testReadingWithLimitOneBatch() throws Exception { - runQueryLimitReadTest(5); + /** Builds a per-kind statistics response with the given entity size. */ + private static RunQueryResponse makeStatKindResponse(long entitySizeInBytes) { + RunQueryResponse.Builder timestampResponse = RunQueryResponse.newBuilder(); + Entity.Builder entity = Entity.newBuilder(); + entity.setKey(makeKey("dummyKind", "dummyId")); + entity.getMutableProperties().put("entity_bytes", makeValue(entitySizeInBytes).build()); + EntityResult.Builder entityResult = EntityResult.newBuilder(); + entityResult.setEntity(entity); + QueryResultBatch.Builder batch = QueryResultBatch.newBuilder(); + batch.addEntityResults(entityResult); + timestampResponse.setBatch(batch); + return timestampResponse.build(); } - /** Tests reading with a query limit more than one batch, and not a multiple. */ - @Test - public void testReadingWithLimitMultipleBatches() throws Exception { - runQueryLimitReadTest(DATASTORE_QUERY_BATCH_LIMIT + 5); + /** Builds a per-kind statistics query for the given timestamp and namespace. */ + private static Query makeStatKindQuery(String namespace) { + Query.Builder statQuery = Query.newBuilder(); + if (namespace == null) { + statQuery.addKindBuilder().setName("__Stat_Kind__"); + } else { + statQuery.addKindBuilder().setName("__Ns_Stat_Kind__"); + } + statQuery.setFilter(makeFilter("kind_name", EQUAL, makeValue(KIND)).build()); + statQuery.addOrder(makeOrder("timestamp", DESCENDING)); + statQuery.setLimit(Int32Value.newBuilder().setValue(1)); + return statQuery.build(); } - /** Tests reading several batches, using an exact multiple of batch size results. */ - @Test - public void testReadingWithLimitMultipleBatchesExactMultiple() throws Exception { - runQueryLimitReadTest(5 * DATASTORE_QUERY_BATCH_LIMIT); + /** Generate dummy query splits. */ + private List splitQuery(Query query, int numSplits) { + List queries = new LinkedList<>(); + for (int i = 0; i < numSplits; i++) { + queries.add(query.toBuilder().clone().build()); + } + return queries; } } - From 436b7a2567017108374ec901f389a1ffd77cde73 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Wed, 15 Jun 2016 14:41:09 -0700 Subject: [PATCH 493/751] Deduplicate Unbounded Reads This ensures that sources that produce duplicate elements that are marked as requiresDeduplication are handled by the DirectRunner. --- .../inprocess/UnboundedReadDeduplicator.java | 97 +++++++++++++ .../UnboundedReadEvaluatorFactory.java | 17 ++- .../UnboundedReadDeduplicatorTest.java | 132 ++++++++++++++++++ .../UnboundedReadEvaluatorFactoryTest.java | 50 ++++++- 4 files changed, 292 insertions(+), 4 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java new file mode 100644 index 0000000000..98ef0f54cd --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; + +import org.joda.time.Duration; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Provides methods to determine if a record is a duplicate within the evaluation of a + * {@link Unbounded} {@link PTransform}. + */ +interface UnboundedReadDeduplicator { + /** + * Returns true if the record with the provided ID should be output, and false if it should not + * be because it is a duplicate. + */ + boolean shouldOutput(byte[] recordId); + + /** + * An {@link UnboundedReadDeduplicator} that always returns true. For use with sources do not + * require deduplication. + */ + class NeverDeduplicator implements UnboundedReadDeduplicator { + /** + * Create a new {@link NeverDeduplicator}. + */ + public static UnboundedReadDeduplicator create() { + return new NeverDeduplicator(); + } + + @Override + public boolean shouldOutput(byte[] recordId) { + return true; + } + } + + + /** + * An {@link UnboundedReadDeduplicator} that returns true if the record ID has not been seen + * within 10 minutes. + */ + class CachedIdDeduplicator implements UnboundedReadDeduplicator { + private static final ByteArrayCoder RECORD_ID_CODER = ByteArrayCoder.of(); + private static final long MAX_RETENTION_SINCE_ACCESS = + Duration.standardMinutes(10L).getMillis(); + + private final LoadingCache, AtomicBoolean> ids; + + /** + * Create a new {@link CachedIdDeduplicator}. + */ + public static UnboundedReadDeduplicator create() { + return new CachedIdDeduplicator(); + } + + private CachedIdDeduplicator() { + ids = CacheBuilder.newBuilder() + .expireAfterAccess(MAX_RETENTION_SINCE_ACCESS, TimeUnit.MILLISECONDS) + .maximumSize(100_000L) + .build(new TrueBooleanLoader()); + } + + @Override + public boolean shouldOutput(byte[] recordId) { + return ids.getUnchecked(StructuralKey.of(recordId, RECORD_ID_CODER)).getAndSet(false); + } + + private static class TrueBooleanLoader + extends CacheLoader, AtomicBoolean> { + @Override + public AtomicBoolean load(StructuralKey key) throws Exception { + return new AtomicBoolean(true); + } + } + } + +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index e212021f2a..0b4a807aa2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -102,9 +102,15 @@ Queue> getTransformEvaluatorQue // factory for this transform UnboundedSource source = (UnboundedSource) transform.getTransform().getSource(); + UnboundedReadDeduplicator deduplicator; + if (source.requiresDeduping()) { + deduplicator = UnboundedReadDeduplicator.CachedIdDeduplicator.create(); + } else { + deduplicator = UnboundedReadDeduplicator.NeverDeduplicator.create(); + } UnboundedReadEvaluator evaluator = new UnboundedReadEvaluator<>( - transform, evaluationContext, source, evaluatorQueue); + transform, evaluationContext, source, deduplicator, evaluatorQueue); evaluatorQueue.offer(evaluator); } else { // otherwise return the existing Queue that arrived before us @@ -139,6 +145,7 @@ private static class UnboundedReadEvaluator source; + private final UnboundedReadDeduplicator deduplicator; private UnboundedReader currentReader; private CheckpointMarkT checkpointMark; @@ -152,12 +159,14 @@ public UnboundedReadEvaluator( AppliedPTransform, Unbounded> transform, InProcessEvaluationContext evaluationContext, UnboundedSource source, + UnboundedReadDeduplicator deduplicator, ConcurrentLinkedQueue> evaluatorQueue) { this.transform = transform; this.evaluationContext = evaluationContext; this.evaluatorQueue = evaluatorQueue; this.source = source; this.currentReader = null; + this.deduplicator = deduplicator; this.checkpointMark = null; } @@ -174,8 +183,10 @@ public InProcessTransformResult finishBundle() throws IOException { if (elementAvailable) { int numElements = 0; do { - output.add(WindowedValue.timestampedValueInGlobalWindow(currentReader.getCurrent(), - currentReader.getCurrentTimestamp())); + if (deduplicator.shouldOutput(currentReader.getCurrentRecordId())) { + output.add(WindowedValue.timestampedValueInGlobalWindow(currentReader.getCurrent(), + currentReader.getCurrentTimestamp())); + } numElements++; } while (numElements < ARBITRARY_MAX_ELEMENTS && currentReader.advance()); watermark = currentReader.getWatermark(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java new file mode 100644 index 0000000000..8685920151 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.runners.inprocess.UnboundedReadDeduplicator.CachedIdDeduplicator; +import com.google.cloud.dataflow.sdk.runners.inprocess.UnboundedReadDeduplicator.NeverDeduplicator; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Tests for {@link UnboundedReadDeduplicator}. + */ +@RunWith(JUnit4.class) +public class UnboundedReadDeduplicatorTest { + @Test + public void neverDeduplicatorAlwaysTrue() { + byte[] id = new byte[] {-1, 2, 4, 22}; + UnboundedReadDeduplicator dedupper = NeverDeduplicator.create(); + + assertThat(dedupper.shouldOutput(id), is(true)); + assertThat(dedupper.shouldOutput(id), is(true)); + } + + @Test + public void cachedIdDeduplicatorTrueForFirstIdThenFalse() { + byte[] id = new byte[] {-1, 2, 4, 22}; + UnboundedReadDeduplicator dedupper = CachedIdDeduplicator.create(); + + assertThat(dedupper.shouldOutput(id), is(true)); + assertThat(dedupper.shouldOutput(id), is(false)); + } + + @Test + public void cachedIdDeduplicatorMultithreaded() throws InterruptedException { + byte[] id = new byte[] {-1, 2, 4, 22}; + UnboundedReadDeduplicator dedupper = CachedIdDeduplicator.create(); + final CountDownLatch startSignal = new CountDownLatch(1); + int numThreads = 1000; + final CountDownLatch readyLatch = new CountDownLatch(numThreads); + final CountDownLatch finishLine = new CountDownLatch(numThreads); + + ExecutorService executor = Executors.newCachedThreadPool(); + AtomicInteger successCount = new AtomicInteger(); + AtomicInteger failureCount = new AtomicInteger(); + for (int i = 0; i < numThreads; i++) { + executor.submit(new TryOutputIdRunnable(dedupper, + id, + successCount, + failureCount, + readyLatch, + startSignal, + finishLine)); + } + + readyLatch.await(); + startSignal.countDown(); + finishLine.await(10L, TimeUnit.SECONDS); + executor.shutdownNow(); + + assertThat(successCount.get(), equalTo(1)); + assertThat(failureCount.get(), equalTo(numThreads - 1)); + } + + private static class TryOutputIdRunnable implements Runnable { + private final UnboundedReadDeduplicator deduplicator; + private final byte[] id; + private final AtomicInteger successCount; + private final AtomicInteger failureCount; + private final CountDownLatch readyLatch; + private final CountDownLatch startSignal; + private final CountDownLatch finishLine; + + public TryOutputIdRunnable( + UnboundedReadDeduplicator dedupper, + byte[] id, + AtomicInteger successCount, + AtomicInteger failureCount, + CountDownLatch readyLatch, + CountDownLatch startSignal, + CountDownLatch finishLine) { + this.deduplicator = dedupper; + this.id = id; + this.successCount = successCount; + this.failureCount = failureCount; + this.readyLatch = readyLatch; + this.startSignal = startSignal; + this.finishLine = finishLine; + } + + @Override + public void run() { + readyLatch.countDown(); + try { + startSignal.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + if (deduplicator.shouldOutput(id)) { + successCount.incrementAndGet(); + } else { + failureCount.incrementAndGet(); + } + finishLine.countDown(); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java index 752069b391..84a7ca2b0b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java @@ -38,6 +38,7 @@ import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -135,6 +136,38 @@ public void unboundedSourceInMemoryTransformEvaluatorMultipleSequentialCalls() t tgw(15L), tgw(13L), tgw(10L))); } + @Test + public void unboundedSourceWithDuplicatesMultipleCalls() throws Exception { + Long[] outputs = new Long[20]; + for (long i = 0L; i < 20L; i++) { + outputs[(int) i] = i % 5L; + } + TestUnboundedSource source = + new TestUnboundedSource<>(BigEndianLongCoder.of(), outputs); + source.dedupes = true; + + TestPipeline p = TestPipeline.create(); + PCollection pcollection = p.apply(Read.from(source)); + AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); + + UncommittedBundle output = bundleFactory.createRootBundle(pcollection); + when(context.createRootBundle(pcollection)).thenReturn(output); + TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); + + evaluator.finishBundle(); + assertThat( + output.commit(Instant.now()).getElements(), + containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(3L), tgw(0L))); + + UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); + when(context.createRootBundle(longs)).thenReturn(secondOutput); + TransformEvaluator secondEvaluator = factory.forApplication(sourceTransform, null, context); + secondEvaluator.finishBundle(); + assertThat( + secondOutput.commit(Instant.now()).getElements(), + Matchers.>emptyIterable()); + } + @Test public void evaluatorClosesReaderAfterOutputCount() throws Exception { ContiguousSet elems = ContiguousSet.create( @@ -249,6 +282,7 @@ private static class TestUnboundedSource extends UnboundedSource coder; private final List elems; + private boolean dedupes = false; public TestUnboundedSource(Coder coder, T... elems) { readerAdvancedCount = 0; @@ -275,6 +309,11 @@ public Coder getCheckpointMarkCoder() { return new TestCheckpointMark.Coder(); } + @Override + public boolean requiresDeduping() { + return dedupes; + } + @Override public void validate() {} @@ -330,7 +369,16 @@ public T getCurrent() throws NoSuchElementException { @Override public Instant getCurrentTimestamp() throws NoSuchElementException { - return Instant.now(); + return new Instant(index); + } + + @Override + public byte[] getCurrentRecordId() { + try { + return CoderUtils.encodeToByteArray(coder, getCurrent()); + } catch (CoderException e) { + throw new RuntimeException(e); + } } @Override From 60fa23d91fb315f056e7ed15c5d6885a8af76dca Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 12 Aug 2016 09:54:17 -0700 Subject: [PATCH 494/751] Remove unneccessary method in ReadEvaluatorFactories The getTransformEvaluator() method's only call is poll on the result of getTransformEvaluatorQueue (which is only ever called by getTransformEvaluator). Instead, move the construction to getTransformEvaluator and call poll on the result. --- .../BoundedReadEvaluatorFactory.java | 16 +++++---------- .../UnboundedReadEvaluatorFactory.java | 20 ++++++------------- 2 files changed, 11 insertions(+), 25 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java index 26f1f88399..b6b657f94f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java @@ -58,21 +58,15 @@ public TransformEvaluator forApplication( return getTransformEvaluator((AppliedPTransform) application, evaluationContext); } - private TransformEvaluator getTransformEvaluator( - final AppliedPTransform, Bounded> transform, - final InProcessEvaluationContext evaluationContext) { - return getTransformEvaluatorQueue(transform, evaluationContext).poll(); - } - /** - * Get the queue of {@link TransformEvaluator TransformEvaluators} that produce elements for the - * provided application of {@link Bounded Read.Bounded}, initializing it if required. + * Get a {@link TransformEvaluator} that produce elements for the provided application of + * {@link Bounded Read.Bounded}, initializing the queue of evaluators if required. * *

            This method is thread-safe, and will only produce new evaluators if no other invocation has * already done so. */ @SuppressWarnings("unchecked") - private Queue> getTransformEvaluatorQueue( + private BoundedReadEvaluator getTransformEvaluator( final AppliedPTransform, Bounded> transform, final InProcessEvaluationContext evaluationContext) { // Key by the application and the context the evaluation is occurring in (which call to @@ -94,7 +88,7 @@ private Queue> getTransformEvaluatorQueu evaluatorQueue = (Queue>) sourceEvaluators.get(key); } } - return evaluatorQueue; + return evaluatorQueue.poll(); } /** @@ -130,7 +124,7 @@ public void processElement(WindowedValue element) {} @Override public InProcessTransformResult finishBundle() throws IOException { try (final BoundedReader reader = - source.createReader(evaluationContext.getPipelineOptions());) { + source.createReader(evaluationContext.getPipelineOptions())) { boolean contentsRemaining = reader.start(); UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java index e212021f2a..59baaeb097 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java @@ -32,7 +32,6 @@ import org.joda.time.Instant; import java.io.IOException; -import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; @@ -70,24 +69,17 @@ public TransformEvaluator forApplication(AppliedPTransform TransformEvaluator getTransformEvaluator( - final AppliedPTransform, Unbounded> transform, - final InProcessEvaluationContext evaluationContext) { - return getTransformEvaluatorQueue(transform, evaluationContext).poll(); - } - /** - * Get the queue of {@link TransformEvaluator TransformEvaluators} that produce elements for the - * provided application of {@link Unbounded Read.Unbounded}, initializing it if required. + * Get a {@link TransformEvaluator} that produce elements for the provided application of + * {@link Unbounded Read.Unbounded}, initializing the queue of evaluators if required. * *

            This method is thread-safe, and will only produce new evaluators if no other invocation has * already done so. */ - @SuppressWarnings("unchecked") private - Queue> getTransformEvaluatorQueue( - final AppliedPTransform, Unbounded> transform, - final InProcessEvaluationContext evaluationContext) { + TransformEvaluator getTransformEvaluator( + final AppliedPTransform, Unbounded> transform, + final InProcessEvaluationContext evaluationContext) { // Key by the application and the context the evaluation is occurring in (which call to // Pipeline#run). EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); @@ -113,7 +105,7 @@ Queue> getTransformEvaluatorQue sourceEvaluators.get(key); } } - return evaluatorQueue; + return evaluatorQueue.poll(); } /** From 2b6ef825f6a484080912529cb90824d028ecd3e1 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 12 Aug 2016 10:11:30 -0700 Subject: [PATCH 495/751] Remove References to Instant#now in the DirectRunner The DirectRunner should use exclusively the configured clock to determine the processing time. --- .../inprocess/ExecutorServiceParallelExecutor.java | 3 +-- .../inprocess/InProcessEvaluationContext.java | 13 ++++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index 27f728d55f..a37190c543 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -36,7 +36,6 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -420,7 +419,7 @@ private boolean fireTimers() throws Exception { .createKeyedBundle( null, keyTimers.getKey(), (PCollection) transform.getInput()) .add(WindowedValue.valueInEmptyWindows(work)) - .commit(Instant.now()); + .commit(evaluationContext.now()); scheduleConsumption(transform, bundle, new TimerCompletionCallback(delivery)); firedTimers = true; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 1d3f168657..6ca375865d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -45,6 +45,8 @@ import com.google.common.collect.Iterables; import com.google.common.util.concurrent.MoreExecutors; +import org.joda.time.Instant; + import java.util.Collection; import java.util.List; import java.util.Map; @@ -77,6 +79,7 @@ class InProcessEvaluationContext { /** The options that were used to create this {@link Pipeline}. */ private final InProcessPipelineOptions options; + private final Clock clock; private final BundleFactory bundleFactory; /** The current processing time and event time watermarks and timers. */ @@ -112,6 +115,7 @@ private InProcessEvaluationContext( Map, String> stepNames, Collection> views) { this.options = checkNotNull(options); + this.clock = options.getClock(); this.bundleFactory = checkNotNull(bundleFactory); checkNotNull(rootTransforms); checkNotNull(valueToConsumers); @@ -120,8 +124,7 @@ private InProcessEvaluationContext( this.stepNames = stepNames; this.watermarkManager = - InMemoryWatermarkManager.create( - NanosOffsetClock.create(), rootTransforms, valueToConsumers); + InMemoryWatermarkManager.create(clock, rootTransforms, valueToConsumers); this.sideInputContainer = InProcessSideInputContainer.create(this, views); this.applicationStateInternals = new ConcurrentHashMap<>(); @@ -302,7 +305,7 @@ public InProcessExecutionContext getExecutionContext( AppliedPTransform application, StructuralKey key) { StepAndKey stepAndKey = StepAndKey.of(application, key); return new InProcessExecutionContext( - options.getClock(), + clock, key, (CopyOnAccessInMemoryStateInternals) applicationStateInternals.get(stepAndKey), watermarkManager.getWatermarks(application)); @@ -421,4 +424,8 @@ public boolean isDone() { } return true; } + + public Instant now() { + return clock.now(); + } } From 44a277b459a9bb1c1215862b2092f0483c86462d Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 12 Aug 2016 10:16:04 -0700 Subject: [PATCH 496/751] Add DirectRunner Reuse Test Two calls to run using the Direct Runner should be independent and succeed independently. --- .../InProcessPipelineRunnerTest.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java index 5da61ba217..7fcdee9028 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java @@ -15,7 +15,9 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.Pipeline; @@ -52,6 +54,7 @@ import java.io.Serializable; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; /** * Tests for basic {@link InProcessPipelineRunner} functionality. @@ -88,6 +91,50 @@ public String apply(KV input) { result.awaitCompletion(); } + private static AtomicInteger changed; + @Test + public void reusePipelineSucceeds() throws Throwable { + Pipeline p = getPipeline(); + + changed = new AtomicInteger(0); + + PCollection> counts = + p.apply(Create.of("foo", "bar", "foo", "baz", "bar", "foo")) + .apply(MapElements.via(new SimpleFunction() { + @Override + public String apply(String input) { + return input; + } + })) + .apply(Count.perElement()); + PCollection countStrs = + counts.apply(MapElements.via(new SimpleFunction, String>() { + @Override + public String apply(KV input) { + String str = String.format("%s: %s", input.getKey(), input.getValue()); + return str; + } + })); + + counts.apply(ParDo.of(new DoFn, Void>() { + @Override + public void processElement(ProcessContext c) throws Exception { + changed.getAndIncrement(); + } + })); + + DataflowAssert.that(countStrs).containsInAnyOrder("baz: 1", "bar: 2", "foo: 3"); + + InProcessPipelineResult result = ((InProcessPipelineResult) p.run()); + result.awaitCompletion(); + + InProcessPipelineResult otherResult = ((InProcessPipelineResult) p.run()); + otherResult.awaitCompletion(); + + assertThat("Each element should have been processed twice", changed.get(), equalTo(6)); + } + + @Test public void byteArrayCountShouldSucceed() { Pipeline p = getPipeline(); From fae7eb9dc082bf3707fd9a0718402dc43a9a70df Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 12 Aug 2016 10:16:34 -0700 Subject: [PATCH 497/751] Remove unneccssary Assignment in TransformExecutor --- .../cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java index 3657688058..4430158b42 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -115,7 +115,7 @@ public void run() { processElements(evaluator, enforcements); - InProcessTransformResult result = finishBundle(evaluator, enforcements); + finishBundle(evaluator, enforcements); } catch (Throwable t) { onComplete.handleThrowable(inputBundle, t); if (t instanceof RuntimeException) { From 65b885a54f31ff3f1b0a40cba205460a9ad84a5f Mon Sep 17 00:00:00 2001 From: David Rieber Date: Tue, 9 Aug 2016 14:05:25 -0700 Subject: [PATCH 498/751] Do not add DataDisks to windmill service jobs. --- .../dataflow/sdk/runners/DataflowPipelineTranslator.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index aa9f182f19..22be3add11 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -429,7 +429,9 @@ public Job translate(List packages) { workerPool.setPackages(packages); workerPool.setNumWorkers(options.getNumWorkers()); - if (options.isStreaming()) { + if (options.isStreaming() + && (options.getExperiments() == null + || !options.getExperiments().contains("enable_windmill_service"))) { // Use separate data disk for streaming. Disk disk = new Disk(); disk.setDiskType(options.getWorkerDiskType()); From 449291dad77d2f0ecf1d146b97cf09459d5ec913 Mon Sep 17 00:00:00 2001 From: mariusz89016 Date: Sun, 14 Aug 2016 00:35:19 +0200 Subject: [PATCH 499/751] [BEAM-432] Corrected BigQueryIO javadoc --- .../main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 6ce7c36fa5..48d32075e2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -173,7 +173,7 @@ *
            {@code
              * PCollection shakespeare = pipeline.apply(
              *     BigQueryIO.Read.named("Read")
            - *                    .fromQuery("SELECT year, mean_temp FROM samples.weather_stations"));
            + *                    .fromQuery("SELECT year, mean_temp FROM [samples.weather_stations]"));
              * }
            * *

            When creating a BigQuery input transform, users should provide either a query or a table. From 6d1789fb1434a4a080da4cd0e0d772131625872b Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 15 Aug 2016 15:44:00 -0700 Subject: [PATCH 500/751] Exclude guava-testlib from shading relocation Previously, guava-testlib guava-testlib was being relocated as part of the shading process, but test-scope dependencies aren't bundled in the uber-jar. As a result, the output JAR was unusable without recreating the same shading rules in a consuming project. --- sdk/pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/pom.xml b/sdk/pom.xml index 4d1d4aa156..2ea15a3b41 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -359,6 +359,9 @@ the second relocation. --> com.google.common + + com.google.common.**.testing + com.google.cloud.dataflow.sdk.repackaged.com.google.common From e7356dbec6f299290e3ca4660592f7210f0ede9f Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 15 Aug 2016 16:38:07 -0700 Subject: [PATCH 501/751] fixup! Add comments about guava-testlib package relocation --- sdk/pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/pom.xml b/sdk/pom.xml index 2ea15a3b41..4e62def6b2 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -360,6 +360,7 @@ com.google.common + com.google.common.**.testing com.google.cloud.dataflow.sdk.repackaged.com.google.common @@ -781,6 +782,8 @@ + com.google.guava guava-testlib ${guava.version} From 1e039153466931eac7c5e482bb2618e4ecf6afc6 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 15 Aug 2016 16:45:11 -0700 Subject: [PATCH 502/751] fixup! grammar --- sdk/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index 4e62def6b2..c4a6f3e61e 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -782,7 +782,7 @@ - com.google.guava guava-testlib From d1a28f3df730ec4cf47503751d7524e192c5338c Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 26 Jul 2016 09:38:13 -0700 Subject: [PATCH 503/751] Use AutoValue for StepTransformResult --- .../inprocess/StepTransformResult.java | 77 ++++--------------- 1 file changed, 16 insertions(+), 61 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java index dba6923c00..22f30ac70c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java @@ -15,8 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import static com.google.common.base.Preconditions.checkNotNull; - +import com.google.auto.value.AutoValue; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -24,7 +23,6 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; -import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import org.joda.time.Instant; @@ -36,67 +34,30 @@ /** * An immutable {@link InProcessTransformResult}. */ -class StepTransformResult implements InProcessTransformResult { - private final AppliedPTransform transform; - private final Iterable> bundles; - private final Iterable> unprocessedElements; - @Nullable private final CopyOnAccessInMemoryStateInternals state; - private final TimerUpdate timerUpdate; - @Nullable private final CounterSet counters; - private final Instant watermarkHold; - - private StepTransformResult( - AppliedPTransform transform, - Iterable> outputBundles, - Iterable> unprocessedElements, - CopyOnAccessInMemoryStateInternals state, - TimerUpdate timerUpdate, - CounterSet counters, - Instant watermarkHold) { - this.transform = checkNotNull(transform); - this.bundles = checkNotNull(outputBundles); - this.unprocessedElements = checkNotNull(unprocessedElements); - this.state = state; - this.timerUpdate = checkNotNull(timerUpdate); - this.counters = counters; - this.watermarkHold = checkNotNull(watermarkHold); - } - +@AutoValue +public abstract class StepTransformResult implements InProcessTransformResult { @Override - public Iterable> getOutputBundles() { - return bundles; - } + public abstract AppliedPTransform getTransform(); @Override - public Iterable> getUnprocessedElements() { - return unprocessedElements; - } + public abstract Iterable> getOutputBundles(); @Override - public CounterSet getCounters() { - return counters; - } + public abstract Iterable> getUnprocessedElements(); @Override - public AppliedPTransform getTransform() { - return transform; - } + @Nullable + public abstract CounterSet getCounters(); @Override - public Instant getWatermarkHold() { - return watermarkHold; - } + public abstract Instant getWatermarkHold(); @Nullable @Override - public CopyOnAccessInMemoryStateInternals getState() { - return state; - } + public abstract CopyOnAccessInMemoryStateInternals getState(); @Override - public TimerUpdate getTimerUpdate() { - return timerUpdate; - } + public abstract TimerUpdate getTimerUpdate(); public static Builder withHold(AppliedPTransform transform, Instant watermarkHold) { return new Builder(transform, watermarkHold); @@ -106,13 +67,6 @@ public static Builder withoutHold(AppliedPTransform transform) { return new Builder(transform, BoundedWindow.TIMESTAMP_MAX_VALUE); } - @Override - public String toString() { - return MoreObjects.toStringHelper(StepTransformResult.class) - .add("transform", transform) - .toString(); - } - /** * A builder for creating instances of {@link StepTransformResult}. */ @@ -134,14 +88,14 @@ private Builder(AppliedPTransform transform, Instant watermarkHold) { } public StepTransformResult build() { - return new StepTransformResult( + return new AutoValue_StepTransformResult( transform, bundlesBuilder.build(), unprocessedElementsBuilder.build(), - state, - timerUpdate, counters, - watermarkHold); + watermarkHold, + state, + timerUpdate); } public Builder withCounters(CounterSet counters) { @@ -177,3 +131,4 @@ public Builder addOutput(Collection> outputBundles) { } } } + From f7e62c813f6f39bd2b703fa00807ab9e92c832a2 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 22 Jul 2016 13:47:19 -0700 Subject: [PATCH 504/751] Apply ExecutorUpdates in two Phases This removes the need for an explicit break by ensuring that work added by the monitor will not complete and add more work for the monitor to complete. --- .../ExecutorServiceParallelExecutor.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index a37190c543..b25b2db616 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -39,6 +39,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; @@ -354,11 +355,15 @@ public void run() { String oldName = Thread.currentThread().getName(); Thread.currentThread().setName(runnableName); try { - ExecutorUpdate update = allUpdates.poll(); - int numUpdates = 0; - // pull all of the pending work off of the queue - long updatesStart = System.nanoTime(); - while (update != null) { + Collection updates = new ArrayList<>(); + // Pull all available updates off of the queue before adding additional work. This ensures + // both loops terminate. + ExecutorUpdate pendingUpdate = allUpdates.poll(); + while (pendingUpdate != null) { + updates.add(pendingUpdate); + pendingUpdate = allUpdates.poll(); + } + for (ExecutorUpdate update : updates) { LOG.debug("Executor Update: {}", update); if (update.getBundle().isPresent()) { scheduleConsumers(update); @@ -366,11 +371,6 @@ public void run() { visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); exceptionThrown = true; } - if (System.nanoTime() - updatesStart > maxTimeProcessingUpdatesNanos) { - break; - } else { - update = allUpdates.poll(); - } } boolean timersFired = fireTimers(); addWorkIfNecessary(timersFired); From 1cd3ffd56034231a18cf4f27a1b8cac2279d77da Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Tue, 16 Aug 2016 13:11:16 -0700 Subject: [PATCH 505/751] ByteKeyRangeTracker: synchronize toString It's the only unsynchronized function, and it could potentially produce bad data. --- .../google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java index ca97e4fd1c..5f3ea71314 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java @@ -175,7 +175,7 @@ public synchronized boolean markDone() { } @Override - public String toString() { + public synchronized String toString() { return toStringHelper(ByteKeyRangeTracker.class) .add("range", range) .add("position", position) From 65540ba84af8761beb6b62191cb661f7f91eb22f Mon Sep 17 00:00:00 2001 From: reuvenlax Date: Tue, 16 Aug 2016 18:28:44 -0700 Subject: [PATCH 506/751] Update CounterSet.java to be threadsafe Some runners want to query CounterSet from a different thread than the one that mutates it. This requires thread safety. --- .../com/google/cloud/dataflow/sdk/util/common/CounterSet.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java index 9e9638ff33..5d659672f2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java @@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkArgument; import java.util.AbstractSet; -import java.util.HashMap; import java.util.Iterator; +import java.util.concurrent.ConcurrentHashMap; /** * A CounterSet maintains a set of {@link Counter}s. @@ -30,7 +30,7 @@ public class CounterSet extends AbstractSet> { /** Registered counters. */ - private final HashMap> counters = new HashMap<>(); + private final ConcurrentHashMap> counters = new ConcurrentHashMap<>(); private final AddCounterMutator addCounterMutator = new AddCounterMutator(); From 9b532ff81430a80fa83e6eba7973e1900f9a7a42 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 17 Aug 2016 08:53:54 -0700 Subject: [PATCH 507/751] Fix repackaging exclude pattern for guava-testlib --- sdk/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/pom.xml b/sdk/pom.xml index c4a6f3e61e..c08fee77e8 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -361,7 +361,7 @@ com.google.common - com.google.common.**.testing + com.google.common.**.testing.* com.google.cloud.dataflow.sdk.repackaged.com.google.common @@ -783,7 +783,7 @@ + also relocated by excluding com.google.common.**.testing.* --> com.google.guava guava-testlib ${guava.version} From 92d23ba0d95b3c5845e8f37c351290846f29def8 Mon Sep 17 00:00:00 2001 From: peihe Date: Wed, 17 Aug 2016 09:46:03 -0700 Subject: [PATCH 508/751] Merge pr 331, with some fixups (#351) * Check for existence of job before polling. Closes #330. In case of local runners, export job does not exists, check if job exists before polling for result. This will prevent unnecessary exceptions, polling in local mode. * Merge PR-331, and fixups. * address feedback --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 9 +-- .../dataflow/sdk/util/BigQueryServices.java | 7 +++ .../sdk/util/BigQueryServicesImpl.java | 45 +++++++++++++++ .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 42 +++++++++++++- .../sdk/util/BigQueryServicesImplTest.java | 56 +++++++++++++++++++ 5 files changed, 152 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 48d32075e2..1ee2f0297c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -395,10 +395,6 @@ public static class Bound extends PTransform> { "Validation of query \"%1$s\" failed. If the query depends on an earlier stage of the" + " pipeline, This validation can be disabled using #withoutValidation."; - // The maximum number of retries to poll a BigQuery job in the cleanup phase. - // We expect the jobs have already DONE, and don't need a high max retires. - private static final int CLEANUP_JOB_POLL_MAX_RETRIES = 10; - private Bound() { this( null /* name */, @@ -600,8 +596,9 @@ void cleanup(PipelineOptions options) throws Exception { JobReference jobRef = new JobReference() .setProjectId(executingProject) .setJobId(getExtractJobId(jobIdToken)); - Job extractJob = bqServices.getJobService(bqOptions).pollJob( - jobRef, CLEANUP_JOB_POLL_MAX_RETRIES); + + Job extractJob = bqServices.getJobService(bqOptions) + .getJob(jobRef); Collection extractFiles = null; if (extractJob != null) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java index 2fc93fe355..060e7ff7bf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -93,6 +93,13 @@ Job pollJob(JobReference jobRef, int maxAttempts) */ JobStatistics dryRunQuery(String projectId, String query) throws InterruptedException, IOException; + + /** + * Gets the specified {@link Job} by the given {@link JobReference}. + * + * Returns null if the job is not found. + */ + Job getJob(JobReference jobRef) throws IOException, InterruptedException; } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index e438747785..2c50aea756 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -244,6 +244,51 @@ public JobStatistics dryRunQuery(String projectId, String query) Sleeper.DEFAULT, backoff).getStatistics(); } + + /** + * {@inheritDoc} + * + *

            Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds max RPC retries. + */ + @Override + public Job getJob(JobReference jobRef) throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + return getJob(jobRef, Sleeper.DEFAULT, backoff); + } + + @VisibleForTesting + public Job getJob(JobReference jobRef, Sleeper sleeper, BackOff backoff) + throws IOException, InterruptedException { + String jobId = jobRef.getJobId(); + Exception lastException; + do { + try { + return client.jobs().get(jobRef.getProjectId(), jobId).execute(); + } catch (GoogleJsonResponseException e) { + if (errorExtractor.itemNotFound(e)) { + LOG.info("No BigQuery job with job id {} found.", jobId); + return null; + } + LOG.warn( + "Ignoring the error encountered while trying to query the BigQuery job {}", + jobId, e); + lastException = e; + } catch (IOException e) { + LOG.warn( + "Ignoring the error encountered while trying to query the BigQuery job {}", + jobId, e); + lastException = e; + } + } while (nextBackOff(sleeper, backoff)); + throw new IOException( + String.format( + "Unable to find BigQuery job: %s, aborting after %d retries.", + jobRef, MAX_RPC_ATTEMPTS), + lastException); + } } @VisibleForTesting diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 0a39100b7d..f0281efc92 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -210,17 +210,21 @@ private static class FakeJobService implements JobService, Serializable { private Object[] startJobReturns; private Object[] pollJobReturns; + private Object[] getJobReturns; private String executingProject; // Both counts will be reset back to zeros after serialization. // This is a work around for DoFn's verifyUnmodified check. private transient int startJobCallsCount; private transient int pollJobStatusCallsCount; + private transient int getJobCallsCount; public FakeJobService() { this.startJobReturns = new Object[0]; this.pollJobReturns = new Object[0]; + this.getJobReturns = new Object[0]; this.startJobCallsCount = 0; this.pollJobStatusCallsCount = 0; + this.getJobCallsCount = 0; } /** @@ -234,6 +238,16 @@ public FakeJobService startJobReturns(Object... startJobReturns) { return this; } + /** + * Sets the return values to mock {@link JobService#getJob}. + * + *

            Throws if the {@link Object} is a {@link InterruptedException}, returns otherwise. + */ + public FakeJobService getJobReturns(Object... getJobReturns) { + this.getJobReturns = getJobReturns; + return this; + } + /** * Sets the return values to mock {@link JobService#pollJob}. * @@ -325,6 +339,32 @@ public JobStatistics dryRunQuery(String projectId, String query) throws InterruptedException, IOException { throw new UnsupportedOperationException(); } + + @Override + public Job getJob(JobReference jobRef) throws InterruptedException { + if (!Strings.isNullOrEmpty(executingProject)) { + checkArgument( + jobRef.getProjectId().equals(executingProject), + "Project id: %s is not equal to executing project: %s", + jobRef.getProjectId(), executingProject); + } + + if (getJobCallsCount < getJobReturns.length) { + Object ret = getJobReturns[getJobCallsCount++]; + if (ret == null) { + return null; + } else if (ret instanceof Job) { + return (Job) ret; + } else if (ret instanceof InterruptedException) { + throw (InterruptedException) ret; + } else { + throw new RuntimeException("Unexpected return type: " + ret.getClass()); + } + } else { + throw new RuntimeException( + "Exceeded expected number of calls: " + getJobReturns.length); + } + } } @Rule public transient ExpectedException thrown = ExpectedException.none(); @@ -518,7 +558,7 @@ public void testReadFromTable() throws IOException { FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() .withJobService(new FakeJobService() .startJobReturns("done", "done") - .pollJobReturns(Status.UNKNOWN) + .getJobReturns((Job) null) .verifyExecutingProject(bqOptions.getProject())) .readerReturns( toJsonString(new TableRow().set("name", "a").set("number", 1)), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java index d9de2ab5b0..ec6f6ba37a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java @@ -258,6 +258,62 @@ public void testPollJobUnknown() throws IOException, InterruptedException { verify(response, times(1)).getContentType(); } + @Test + public void testGetJobSucceeds() throws Exception { + Job testJob = new Job(); + testJob.setStatus(new JobStatus()); + + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(200); + when(response.getContent()).thenReturn(toStream(testJob)); + + BigQueryServicesImpl.JobServiceImpl jobService = + new BigQueryServicesImpl.JobServiceImpl(bigquery); + JobReference jobRef = new JobReference() + .setProjectId("projectId") + .setJobId("jobId"); + Job job = jobService.getJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + + assertEquals(testJob, job); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + @Test + public void testGetJobNotFound() throws Exception { + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(404); + + BigQueryServicesImpl.JobServiceImpl jobService = + new BigQueryServicesImpl.JobServiceImpl(bigquery); + JobReference jobRef = new JobReference() + .setProjectId("projectId") + .setJobId("jobId"); + Job job = jobService.getJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); + + assertEquals(null, job); + verify(response, times(1)).getStatusCode(); + verify(response, times(1)).getContent(); + verify(response, times(1)).getContentType(); + } + + @Test + public void testGetJobThrows() throws Exception { + when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); + when(response.getStatusCode()).thenReturn(401); + + BigQueryServicesImpl.JobServiceImpl jobService = + new BigQueryServicesImpl.JobServiceImpl(bigquery); + JobReference jobRef = new JobReference() + .setProjectId("projectId") + .setJobId("jobId"); + thrown.expect(IOException.class); + thrown.expectMessage(String.format("Unable to find BigQuery job: %s", jobRef)); + + jobService.getJob(jobRef, Sleeper.DEFAULT, BackOff.STOP_BACKOFF); + } + @Test public void testExecuteWithRetries() throws IOException, InterruptedException { Table testTable = new Table(); From b3f3ab7c0d2a4b96860d516f05054e0bfc5f8d72 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 20 Jun 2016 09:40:31 -0700 Subject: [PATCH 509/751] Make JAXBCoder Thread Safe JAXB Marshaller and Unmarshaller are not thread safe, but coders are required to be. Create context only once, and create Marshaller and Unmarshaller locally on-demand. --- .../cloud/dataflow/sdk/coders/JAXBCoder.java | 28 +++++--- .../dataflow/sdk/coders/JAXBCoderTest.java | 69 ++++++++++++++++++- 2 files changed, 85 insertions(+), 12 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java index 2b0190b5f3..9e0c9c4b47 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java @@ -40,8 +40,7 @@ public class JAXBCoder extends AtomicCoder { private final Class jaxbClass; - private transient Marshaller jaxbMarshaller = null; - private transient Unmarshaller jaxbUnmarshaller = null; + private transient JAXBContext jaxbContext; public Class getJAXBClass() { return jaxbClass; @@ -64,10 +63,9 @@ public static JAXBCoder of(Class jaxbClass) { public void encode(T value, OutputStream outStream, Context context) throws CoderException, IOException { try { - if (jaxbMarshaller == null) { - JAXBContext jaxbContext = JAXBContext.newInstance(jaxbClass); - jaxbMarshaller = jaxbContext.createMarshaller(); - } + JAXBContext jaxbContext = getContext(); + // TODO: Consider caching in a ThreadLocal if this impacts performance + Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.marshal(value, new FilterOutputStream(outStream) { // JAXB closes the underyling stream so we must filter out those calls. @@ -83,10 +81,9 @@ public void close() throws IOException { @Override public T decode(InputStream inStream, Context context) throws CoderException, IOException { try { - if (jaxbUnmarshaller == null) { - JAXBContext jaxbContext = JAXBContext.newInstance(jaxbClass); - jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - } + JAXBContext jaxbContext = getContext(); + // TODO: Consider caching in a ThreadLocal if this impacts performance + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); @SuppressWarnings("unchecked") T obj = (T) jaxbUnmarshaller.unmarshal(new FilterInputStream(inStream) { @@ -101,6 +98,17 @@ public void close() throws IOException { } } + private final JAXBContext getContext() throws JAXBException { + if (jaxbContext == null) { + synchronized (this) { + if (jaxbContext == null) { + jaxbContext = JAXBContext.newInstance(jaxbClass); + } + } + } + return jaxbContext; + } + @Override public String getEncodingId() { return getJAXBClass().getName(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java index 7e1effff5d..56b91680f5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java @@ -16,13 +16,23 @@ package com.google.cloud.dataflow.sdk.coders; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import com.google.cloud.dataflow.sdk.testing.CoderProperties; import com.google.cloud.dataflow.sdk.util.CoderUtils; -import org.junit.Assert; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; + import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + import javax.xml.bind.annotation.XmlRootElement; /** Unit tests for {@link JAXBCoder}. */ @@ -82,7 +92,62 @@ public void testEncodeDecode() throws Exception { JAXBCoder coder = JAXBCoder.of(TestType.class); byte[] encoded = CoderUtils.encodeToByteArray(coder, new TestType("abc", 9999)); - Assert.assertEquals(new TestType("abc", 9999), CoderUtils.decodeFromByteArray(coder, encoded)); + assertEquals(new TestType("abc", 9999), CoderUtils.decodeFromByteArray(coder, encoded)); + } + + @Test + public void testEncodeDecodeAfterClone() throws Exception { + JAXBCoder coder = SerializableUtils.clone(JAXBCoder.of(TestType.class)); + + byte[] encoded = CoderUtils.encodeToByteArray(coder, new TestType("abc", 9999)); + assertEquals(new TestType("abc", 9999), CoderUtils.decodeFromByteArray(coder, encoded)); + } + + @Test + public void testEncodeDecodeMultithreaded() throws Throwable { + final JAXBCoder coder = JAXBCoder.of(TestType.class); + int numThreads = 1000; + + final CountDownLatch ready = new CountDownLatch(numThreads); + final CountDownLatch start = new CountDownLatch(1); + final CountDownLatch done = new CountDownLatch(numThreads); + + final AtomicReference thrown = new AtomicReference<>(); + + Executor executor = Executors.newCachedThreadPool(); + for (int i = 0; i < numThreads; i++) { + final TestType elem = new TestType("abc", i); + final int index = i; + executor.execute( + new Runnable() { + @Override + public void run() { + ready.countDown(); + try { + start.await(); + } catch (InterruptedException e) { + } + + try { + byte[] encoded = CoderUtils.encodeToByteArray(coder, elem); + assertEquals( + new TestType("abc", index), CoderUtils.decodeFromByteArray(coder, encoded)); + } catch (Throwable e) { + thrown.compareAndSet(null, e); + } + done.countDown(); + } + }); + } + ready.await(); + start.countDown(); + + if (!done.await(10L, TimeUnit.SECONDS)) { + fail("Should be able to clone " + numThreads + " elements in 10 seconds"); + } + if (thrown.get() != null) { + throw thrown.get(); + } } @Test From 39e57d6ceb58e68a62f9965318bf446bd8d0c330 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 17 Aug 2016 11:58:26 -0700 Subject: [PATCH 510/751] Import Strings utilities from guava instead of google.api.client (#378) --- .../java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index f0281efc92..e91dd6afa6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -30,7 +30,6 @@ import static org.mockito.Mockito.when; import com.google.api.client.util.Data; -import com.google.api.client.util.Strings; import com.google.api.services.bigquery.model.ErrorProto; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfigurationExtract; @@ -83,6 +82,7 @@ import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; From b462b6056ea4e16f21d874e17d7fe8bc380b5bbf Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 12 Aug 2016 10:21:43 -0700 Subject: [PATCH 511/751] Make TimerData#compareTo consistent with equals Timers are equal if the domain, timestamp, and namespace are equal. Compare these values in compareTo. The ordering of TimerData that are not in the same namespace or domain is arbitrary. --- .../dataflow/sdk/util/TimerInternals.java | 17 ++++++- .../dataflow/sdk/util/TimerInternalsTest.java | 47 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java index b26e6e87b0..a3eb3671c0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java @@ -28,6 +28,7 @@ import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; +import com.google.common.collect.ComparisonChain; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -204,9 +205,23 @@ public String toString() { .toString(); } + /** + * {@inheritDoc}. + * + *

            The ordering of {@link TimerData} that are not in the same namespace or domain is + * arbitrary. + */ @Override public int compareTo(TimerData o) { - return Long.compare(timestamp.getMillis(), o.getTimestamp().getMillis()); + ComparisonChain chain = ComparisonChain.start() + .compare(timestamp.getMillis(), o.getTimestamp().getMillis()) + .compare(domain, o.domain); + if (chain.result() == 0) { + // Computing the string key may be expensive, so only do so if it is meaningful in this + // comparison. + chain = chain.compare(namespace.stringKey(), o.namespace.stringKey()); + } + return chain.result(); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java index 68aecf0b53..797237f763 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java @@ -15,12 +15,18 @@ */ package com.google.cloud.dataflow.sdk.util; +import static org.hamcrest.Matchers.comparesEqualTo; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.testing.CoderProperties; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerDataCoder; +import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; import org.joda.time.Instant; @@ -48,5 +54,46 @@ public void testTimerDataCoder() throws Exception { windowCoder, new IntervalWindow(new Instant(0), new Instant(100))), new Instant(99), TimeDomain.PROCESSING_TIME)); } + + @Test + public void testCompareTo() { + Instant firstTimestamp = new Instant(100); + Instant secondTimestamp = new Instant(200); + IntervalWindow firstWindow = new IntervalWindow(new Instant(0), firstTimestamp); + IntervalWindow secondWindow = new IntervalWindow(firstTimestamp, secondTimestamp); + Coder windowCoder = IntervalWindow.getCoder(); + + StateNamespace firstWindowNs = StateNamespaces.window(windowCoder, firstWindow); + StateNamespace secondWindowNs = StateNamespaces.window(windowCoder, secondWindow); + + TimerData firstEventTime = TimerData.of(firstWindowNs, firstTimestamp, TimeDomain.EVENT_TIME); + TimerData secondEventTime = TimerData.of(firstWindowNs, secondTimestamp, TimeDomain.EVENT_TIME); + TimerData thirdEventTime = TimerData.of(secondWindowNs, secondTimestamp, TimeDomain.EVENT_TIME); + + TimerData firstProcTime = + TimerData.of(firstWindowNs, firstTimestamp, TimeDomain.PROCESSING_TIME); + TimerData secondProcTime = + TimerData.of(firstWindowNs, secondTimestamp, TimeDomain.PROCESSING_TIME); + TimerData thirdProcTime = + TimerData.of(secondWindowNs, secondTimestamp, TimeDomain.PROCESSING_TIME); + + assertThat(firstEventTime, + comparesEqualTo(TimerData.of(firstWindowNs, firstTimestamp, TimeDomain.EVENT_TIME))); + assertThat(firstEventTime, lessThan(secondEventTime)); + assertThat(secondEventTime, lessThan(thirdEventTime)); + assertThat(firstEventTime, lessThan(thirdEventTime)); + + assertThat(secondProcTime, + comparesEqualTo(TimerData.of(firstWindowNs, secondTimestamp, TimeDomain.PROCESSING_TIME))); + assertThat(firstProcTime, lessThan(secondProcTime)); + assertThat(secondProcTime, lessThan(thirdProcTime)); + assertThat(firstProcTime, lessThan(thirdProcTime)); + + assertThat(firstEventTime, not(comparesEqualTo(firstProcTime))); + assertThat(firstProcTime, + not(comparesEqualTo(TimerData.of(firstWindowNs, + firstTimestamp, + TimeDomain.SYNCHRONIZED_PROCESSING_TIME)))); + } } From 4d0004a639f4c769b2a9214843e1c45ebaf442f6 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 12 Aug 2016 11:09:37 -0700 Subject: [PATCH 512/751] Make GroupAlsoByWindowsProperties order-independent Use matchers and containsInAnyOrder. GroupAlsoByWindows does not need to output windows in a specific order. --- .../util/GroupAlsoByWindowsProperties.java | 191 ++++++++---------- 1 file changed, 82 insertions(+), 109 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java index ce06299d61..e2ae389b4b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java @@ -39,6 +39,9 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; import org.joda.time.Duration; import org.joda.time.Instant; @@ -118,17 +121,9 @@ public static void groupsElementsIntoFixedWindows( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item0.getTimestamp(), equalTo(new Instant(1))); - assertThat(item0.getWindows(), contains(window(0, 10))); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v3")); - assertThat(item1.getTimestamp(), equalTo(new Instant(13))); - assertThat(item1.getWindows(), - contains(window(10, 20))); + assertThat(result, containsInAnyOrder( + gabwResult(window(0, 10), new Instant(1), "v1", "v2"), + gabwResult(window(10, 20), new Instant(13), "v3"))); } /** @@ -158,24 +153,10 @@ public static void groupsElementsIntoSlidingWindows( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(3)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), contains("v1")); - assertThat(item0.getTimestamp(), equalTo(new Instant(5))); - assertThat(item0.getWindows(), - contains(window(-10, 10))); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item1.getTimestamp(), equalTo(new Instant(10))); - assertThat(item1.getWindows(), - contains(window(0, 20))); - - WindowedValue>> item2 = result.get(2); - assertThat(item2.getValue().getValue(), contains("v2")); - assertThat(item2.getTimestamp(), equalTo(new Instant(20))); - assertThat(item2.getWindows(), - contains(window(10, 30))); + assertThat(result, containsInAnyOrder( + gabwResult(window(-10, 10), new Instant(5), "v1"), + gabwResult(window(0, 20), new Instant(10), "v1", "v2"), + gabwResult(window(10, 30), new Instant(20), "v2"))); } /** @@ -266,18 +247,9 @@ public static void groupsIntoOverlappingNonmergingWindows( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v3")); - assertThat(item0.getTimestamp(), equalTo(new Instant(1))); - assertThat(item0.getWindows(), - contains(window(0, 5))); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v2")); - assertThat(item1.getTimestamp(), equalTo(new Instant(4))); - assertThat(item1.getWindows(), - contains(window(1, 5))); + assertThat(result, + containsInAnyOrder(gabwResult(window(0, 5), new Instant(1), "v1", "v3"), + gabwResult(window(1, 5), new Instant(4), "v2"))); } /** @@ -309,18 +281,9 @@ public static void groupsElementsInMergedSessions( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item0.getTimestamp(), equalTo(new Instant(0))); - assertThat(item0.getWindows(), - contains(window(0, 15))); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v3")); - assertThat(item1.getTimestamp(), equalTo(new Instant(15))); - assertThat(item1.getWindows(), - contains(window(15, 25))); + assertThat(result, containsInAnyOrder( + gabwResult(window(0, 15), new Instant(0), "v1", "v2"), + gabwResult(window(15, 25), new Instant(15), "v3"))); } /** @@ -402,18 +365,9 @@ public static void groupsElementsIntoFixedWindowsWithEndOfWindowTimestamp( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item0.getTimestamp(), equalTo(window(0, 10).maxTimestamp())); - assertThat(item0.getTimestamp(), - equalTo(Iterables.getOnlyElement(item0.getWindows()).maxTimestamp())); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v3")); - assertThat(item1.getTimestamp(), equalTo(window(10, 20).maxTimestamp())); - assertThat(item1.getTimestamp(), - equalTo(Iterables.getOnlyElement(item1.getWindows()).maxTimestamp())); + assertThat(result, containsInAnyOrder( + gabwResult(window(0, 10), window(0, 10).maxTimestamp(), "v1", "v2"), + gabwResult(window(10, 20), window(10, 20).maxTimestamp(), "v3"))); } /** @@ -451,16 +405,9 @@ public boolean dependsOnlyOnEarliestInputTimestamp() { WindowedValue.of("v3", new Instant(13), Arrays.asList(window(10, 20)), PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item0.getWindows(), contains(window(0, 10))); - assertThat(item0.getTimestamp(), equalTo(new Instant(2))); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v3")); - assertThat(item1.getWindows(), contains(window(10, 20))); - assertThat(item1.getTimestamp(), equalTo(new Instant(14))); + assertThat(result, containsInAnyOrder( + gabwResult(window(0, 10), new Instant(2), "v1", "v2"), + gabwResult(window(10, 20), new Instant(14), "v3"))); } /** @@ -495,16 +442,9 @@ public static void groupsElementsIntoFixedWindowsWithLatestTimestamp( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item0.getWindows(), contains(window(0, 10))); - assertThat(item0.getTimestamp(), equalTo(new Instant(2))); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v3")); - assertThat(item1.getWindows(), contains(window(10, 20))); - assertThat(item1.getTimestamp(), equalTo(new Instant(13))); + assertThat(result, containsInAnyOrder( + gabwResult(window(0, 10), new Instant(2), "v1", "v2"), + gabwResult(window(10, 20), new Instant(13), "v3"))); } /** @@ -538,18 +478,9 @@ public static void groupsElementsInMergedSessionsWithEndOfWindowTimestamp( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item0.getWindows(), contains(window(0, 15))); - assertThat(item0.getTimestamp(), - equalTo(Iterables.getOnlyElement(item0.getWindows()).maxTimestamp())); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v3")); - assertThat(item1.getWindows(), contains(window(15, 25))); - assertThat(item1.getTimestamp(), - equalTo(Iterables.getOnlyElement(item1.getWindows()).maxTimestamp())); + assertThat(result, containsInAnyOrder( + gabwResult(window(0, 15), window(0, 15).maxTimestamp(), "v1", "v2"), + gabwResult(window(15, 25), window(15, 25).maxTimestamp(), "v3"))); } /** @@ -583,16 +514,9 @@ public static void groupsElementsInMergedSessionsWithLatestTimestamp( PaneInfo.NO_FIRING)); assertThat(result.size(), equalTo(2)); - - WindowedValue>> item0 = result.get(0); - assertThat(item0.getValue().getValue(), containsInAnyOrder("v1", "v2")); - assertThat(item0.getWindows(), contains(window(0, 15))); - assertThat(item0.getTimestamp(), equalTo(new Instant(5))); - - WindowedValue>> item1 = result.get(1); - assertThat(item1.getValue().getValue(), contains("v3")); - assertThat(item1.getWindows(), contains(window(15, 25))); - assertThat(item1.getTimestamp(), equalTo(new Instant(15))); + assertThat(result, containsInAnyOrder( + gabwResult(window(0, 15), new Instant(5), "v1", "v2"), + gabwResult(window(15, 25), new Instant(15), "v3"))); } /** @@ -629,13 +553,21 @@ public static void combinesElementsPerSessionWithEndOfWindowTimestamp( assertThat(result.size(), equalTo(2)); - WindowedValue> item0 = result.get(0); + // TODO: Rewrite to use matchers rather than order-based inspection + WindowedValue> item0; + WindowedValue> item1; + if (result.get(0).getWindows().iterator().next().equals(window(0, 15))) { + item0 = result.get(0); + item1 = result.get(1); + } else { + item0 = result.get(1); + item1 = result.get(0); + } assertThat(item0.getValue().getValue(), equalTo(combineFn.apply(ImmutableList.of(1L, 2L)))); assertThat(item0.getWindows(), contains(window(0, 15))); assertThat(item0.getTimestamp(), equalTo(Iterables.getOnlyElement(item0.getWindows()).maxTimestamp())); - WindowedValue> item1 = result.get(1); assertThat(item1.getValue().getValue(), equalTo(combineFn.apply(ImmutableList.of(4L)))); assertThat(item1.getWindows(), contains(window(15, 25))); assertThat(item1.getTimestamp(), @@ -715,4 +647,45 @@ private static BoundedWindow window(long start, long end) { return new IntervalWindow(new Instant(start), new Instant(end)); } + private static Matcher>>> gabwResult( + BoundedWindow window, + Instant timestamp, + T... values) { + return new GroupAlsoByWindowResultMatcher<>(values, new BoundedWindow[] {window}, timestamp); + } + + private static class GroupAlsoByWindowResultMatcher + extends BaseMatcher>>> { + + private final T[] values; + private final BoundedWindow[] windows; + private final Instant timestamp; + + private GroupAlsoByWindowResultMatcher(T[] values, BoundedWindow[] windows, Instant timestamp) { + this.values = values; + this.windows = windows; + this.timestamp = timestamp; + } + + @Override + public boolean matches(Object item) { + if (item instanceof WindowedValue && ((WindowedValue) item).getValue() instanceof KV) { + WindowedValue>> that = (WindowedValue>>) item; + return containsInAnyOrder(values).matches(that.getValue().getValue()) + && timestamp.equals(that.getTimestamp()) + && containsInAnyOrder(windows).matches(that.getWindows()); + } + return false; + } + + @Override + public void describeTo(Description description) { + description.appendText("A Windowed Value containing values ") + .appendValueList("[", ", ", "]", values) + .appendText(" in windows ") + .appendValueList("[", ", ", "]", windows) + .appendText(" with timestamp ") + .appendValue(timestamp); + } + } } From b9b2c7486fd96e8194792394484e9e54fb9ba002 Mon Sep 17 00:00:00 2001 From: Pei He Date: Wed, 17 Aug 2016 15:55:35 -0700 Subject: [PATCH 513/751] Backport Beam PR-828 Set Gcs upload buffer size to 1M in DataflowRunner streaming mode --- .../sdk/runners/DataflowPipelineRunner.java | 7 ++++ .../runners/DataflowPipelineRunnerTest.java | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 341afbe075..d536fd7045 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -133,6 +133,7 @@ import com.google.cloud.dataflow.sdk.values.PValue; import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.cloud.dataflow.sdk.values.TupleTagList; +import com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; @@ -229,6 +230,9 @@ public class DataflowPipelineRunner extends PipelineRunner // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; + @VisibleForTesting + static final int GCS_UPLOAD_BUFFER_SIZE_BYTES_DEFAULT = 1 * 1024 * 1024; + private final Set> pcollectionsRequiringIndexedFormat; /** @@ -334,6 +338,9 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { + "' invalid. Please make sure the value is non-negative."); } + if (dataflowOptions.isStreaming() && dataflowOptions.getGcsUploadBufferSizeBytes() == null) { + dataflowOptions.setGcsUploadBufferSizeBytes(GCS_UPLOAD_BUFFER_SIZE_BYTES_DEFAULT); + } return new DataflowPipelineRunner(dataflowOptions); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 199d2d09c4..41019cc5fe 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -735,6 +735,43 @@ public void testValidJobName() throws IOException { } } + @Test + public void testGcsUploadBufferSizeIsUnsetForBatchWhenDefault() throws IOException { + DataflowPipelineOptions batchOptions = buildPipelineOptions(); + batchOptions.setRunner(DataflowPipelineRunner.class); + Pipeline.create(batchOptions); + assertNull(batchOptions.getGcsUploadBufferSizeBytes()); + } + + @Test + public void testGcsUploadBufferSizeIsSetForStreamingWhenDefault() throws IOException { + DataflowPipelineOptions streamingOptions = buildPipelineOptions(); + streamingOptions.setStreaming(true); + streamingOptions.setRunner(DataflowPipelineRunner.class); + Pipeline.create(streamingOptions); + assertEquals( + DataflowPipelineRunner.GCS_UPLOAD_BUFFER_SIZE_BYTES_DEFAULT, + streamingOptions.getGcsUploadBufferSizeBytes().intValue()); + } + + @Test + public void testGcsUploadBufferSizeUnchangedWhenNotDefault() throws IOException { + int gcsUploadBufferSizeBytes = 12345678; + DataflowPipelineOptions batchOptions = buildPipelineOptions(); + batchOptions.setGcsUploadBufferSizeBytes(gcsUploadBufferSizeBytes); + batchOptions.setRunner(DataflowPipelineRunner.class); + Pipeline.create(batchOptions); + assertEquals(gcsUploadBufferSizeBytes, batchOptions.getGcsUploadBufferSizeBytes().intValue()); + + DataflowPipelineOptions streamingOptions = buildPipelineOptions(); + streamingOptions.setStreaming(true); + streamingOptions.setGcsUploadBufferSizeBytes(gcsUploadBufferSizeBytes); + streamingOptions.setRunner(DataflowPipelineRunner.class); + Pipeline.create(streamingOptions); + assertEquals( + gcsUploadBufferSizeBytes, streamingOptions.getGcsUploadBufferSizeBytes().intValue()); + } + /** * A fake PTransform for testing. */ From a4afc9e6e40003f012756a02b8d66f8f57b2ba24 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Wed, 17 Aug 2016 16:10:01 -0700 Subject: [PATCH 514/751] Add GatherAllPanes PTransform (#366) This PTransform Reifies and gathers all panes produced for each window, outputting a single pane per window at the time the window is Garbage Collected. For use in DataflowAssert, to match over the final contents of each window. --- .../dataflow/sdk/util/GatherAllPanes.java | 72 ++++++++++ .../dataflow/sdk/util/GatherAllPanesTest.java | 129 ++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java new file mode 100644 index 0000000000..1d675e3487 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey.ReifyTimestampsAndWindows; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.Values; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.windowing.Never; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; + +/** + * Gathers all panes of each window into exactly one output. + * + *

            Note that this will delay the output of a window until the garbage collection time (when the + * watermark passes the end of the window plus allowed lateness) even if the upstream triggers + * closed the window earlier. + */ +public class GatherAllPanes + extends PTransform, PCollection>>> { + /** + * Gathers all panes of each window into a single output element. + * + *

            This will gather all output panes into a single element, which causes them to be colocated + * on a single worker. As a result, this is only suitable for {@link PCollection PCollections} + * where all of the output elements for each pane fit in memory, such as in tests. + */ + public static GatherAllPanes globally() { + return new GatherAllPanes<>(); + } + + private GatherAllPanes() {} + + @Override + public PCollection>> apply(PCollection input) { + WindowFn originalWindowFn = input.getWindowingStrategy().getWindowFn(); + + return input + .apply(WithKeys.of(0).withKeyType(new TypeDescriptor() {})) + .apply(new ReifyTimestampsAndWindows()) + .apply( + Window.into( + new IdentityWindowFn>>( + originalWindowFn.windowCoder(), originalWindowFn.assignsToSingleWindow())) + .triggering(Never.ever()) + .withAllowedLateness(input.getWindowingStrategy().getAllowedLateness()) + .discardingFiredPanes()) + // all values have the same key so they all appear as a single output element + .apply(GroupByKey.>create()) + .apply(Values.>>create()) + .setWindowingStrategyInternal(input.getWindowingStrategy()); + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java new file mode 100644 index 0000000000..37bf04d469 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.junit.Assert.fail; + +import com.google.cloud.dataflow.sdk.io.CountingInput; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.Values; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.WithTimestamps; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; +import com.google.common.collect.Iterables; + +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.Serializable; + +/** + * Tests for {@link GatherAllPanes}. + */ +@RunWith(JUnit4.class) +public class GatherAllPanesTest implements Serializable { + @Test + public void singlePaneSingleReifiedPane() { + TestPipeline p = TestPipeline.create(); + PCollection>>> accumulatedPanes = + p.apply(CountingInput.upTo(20000)) + .apply( + WithTimestamps.of( + new SerializableFunction() { + @Override + public Instant apply(Long input) { + return new Instant(input * 10); + } + })) + .apply( + Window.into(FixedWindows.of(Duration.standardMinutes(1))) + .triggering(AfterWatermark.pastEndOfWindow()) + .withAllowedLateness(Duration.ZERO) + .discardingFiredPanes()) + .apply(WithKeys.of((Void) null).withKeyType(new TypeDescriptor() {})) + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(GatherAllPanes.>globally()); + + DataflowAssert.that(accumulatedPanes) + .satisfies( + new SerializableFunction>>>, Void>() { + @Override + public Void apply(Iterable>>> input) { + for (Iterable>> windowedInput : input) { + if (Iterables.size(windowedInput) > 1) { + fail("Expected all windows to have exactly one pane, got " + windowedInput); + return null; + } + } + return null; + } + }); + } + + @Test + public void multiplePanesMultipleReifiedPane() { + TestPipeline p = TestPipeline.create(); + + PCollection>>> accumulatedPanes = + p.apply(CountingInput.upTo(20000)) + .apply( + WithTimestamps.of( + new SerializableFunction() { + @Override + public Instant apply(Long input) { + return new Instant(input * 10); + } + })) + .apply( + Window.into(FixedWindows.of(Duration.standardMinutes(1))) + .triggering( + AfterWatermark.pastEndOfWindow() + .withEarlyFirings(AfterPane.elementCountAtLeast(1))) + .withAllowedLateness(Duration.ZERO) + .discardingFiredPanes()) + .apply(WithKeys.of((Void) null).withKeyType(new TypeDescriptor() {})) + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(GatherAllPanes.>globally()); + + DataflowAssert.that(accumulatedPanes) + .satisfies( + new SerializableFunction>>>, Void>() { + @Override + public Void apply(Iterable>>> input) { + for (Iterable>> windowedInput : input) { + if (Iterables.size(windowedInput) > 1) { + return null; + } + } + fail("Expected at least one window to have multiple panes"); + return null; + } + }); + } +} From be76da63581135b3380457a49e5ce1887b226772 Mon Sep 17 00:00:00 2001 From: Pei He Date: Wed, 17 Aug 2016 16:28:39 -0700 Subject: [PATCH 515/751] fix unused import --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index d536fd7045..f2030e5f38 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -133,7 +133,6 @@ import com.google.cloud.dataflow.sdk.values.PValue; import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; From 2eb66a7d1bcbf0c670f54faca73cf9aa329ac2e8 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Thu, 18 Aug 2016 14:48:18 -0400 Subject: [PATCH 516/751] Add configuration flag for Private IPs (#374) * Add ValueProvider * Delete ValueProvider.java * Update pom.xml * Update DataflowPipelineWorkerPoolOptions.java * Update DataflowPipelineTranslator.java * Update DataflowPipelineWorkerPoolOptions.java --- pom.xml | 2 +- .../options/DataflowPipelineWorkerPoolOptions.java | 14 ++++++++++++++ .../sdk/runners/DataflowPipelineTranslator.java | 7 +++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index eeb4ed6370..2ece510d42 100644 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,7 @@ 0.0.2 0.3.0 v2-rev8-1.22.0 - v1b3-rev30-1.22.0 + v1b3-rev36-1.22.0 0.5.160222 v1beta2-rev1-4.0.0 1.0.0-beta.2 diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java index cc96e802f1..6200cb4ae6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java @@ -23,6 +23,8 @@ import java.util.List; +import javax.annotation.Nullable; + /** * Options that are used to configure the Dataflow pipeline worker pool. */ @@ -254,4 +256,16 @@ public String getTeardownPolicyName() { + "https://cloud.google.com/compute/docs/reference/latest/diskTypes") String getWorkerDiskType(); void setWorkerDiskType(String value); + + /** + * Specifies whether worker pools should be started with public IP addresses. + * + *

            WARNING: This feature is experimental. You must be whitelisted to use it. + */ + @Description("Specifies whether worker pools should be started with public IP addresses. WARNING:" + + "This feature is experimental. You must be whitelisted to use it.") + @Experimental + @JsonIgnore + @Nullable Boolean getUsePublicIps(); + void setUsePublicIps(@Nullable Boolean value); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java index 22be3add11..775c5efefc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java @@ -426,6 +426,13 @@ public Job translate(List packages) { workerPool.setMachineType(options.getWorkerMachineType()); } + if (options.getUsePublicIps() != null) { + if (options.getUsePublicIps()) { + workerPool.setIpConfiguration("WORKER_IP_PUBLIC"); + } else { + workerPool.setIpConfiguration("WORKER_IP_PRIVATE"); + } + } workerPool.setPackages(packages); workerPool.setNumWorkers(options.getNumWorkers()); From a818586002aedcbe9107c6c81560d4afa2b071fd Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Fri, 19 Aug 2016 07:31:10 -0700 Subject: [PATCH 517/751] DatastoreIO Sink as ParDo (#383) --- .../dataflow/sdk/io/datastore/V1Beta3.java | 274 ++++++------------ .../sdk/io/datastore/V1Beta3Test.java | 91 ++++-- 2 files changed, 147 insertions(+), 218 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java index 06b11eeb3d..32fd1a2061 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java @@ -32,11 +32,6 @@ import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.Sleeper; import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.io.Sink; -import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; -import com.google.cloud.dataflow.sdk.io.Sink.Writer; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -166,7 +161,8 @@ public class V1Beta3 { * Datastore has a limit of 500 mutations per batch operation, so we flush * changes to Datastore every 500 entities. */ - private static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; + @VisibleForTesting + static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; /** * Returns an empty {@link V1Beta3.Read} builder. Configure the source {@code projectId}, @@ -633,39 +629,6 @@ public void processElement(ProcessContext context) throws Exception { } } } - - /** - * A wrapper factory class for Datastore singleton classes {@link DatastoreFactory} and - * {@link QuerySplitter} - * - *

            {@link DatastoreFactory} and {@link QuerySplitter} are not java serializable, hence - * wrapping them under this class, which implements {@link Serializable}. - */ - @VisibleForTesting - static class V1Beta3DatastoreFactory implements Serializable { - - /** Builds a Datastore client for the given pipeline options and project. */ - public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { - DatastoreOptions.Builder builder = - new DatastoreOptions.Builder() - .projectId(projectId) - .initializer( - new RetryHttpRequestInitializer() - ); - - Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); - if (credential != null) { - builder.credential(credential); - } - - return DatastoreFactory.get().create(builder.build()); - } - - /** Builds a Datastore {@link QuerySplitter}. */ - public QuerySplitter getQuerySplitter() { - return DatastoreHelper.getQuerySplitter(); - } - } } /** @@ -703,8 +666,8 @@ public Write withProjectId(String projectId) { @Override public PDone apply(PCollection input) { - return input.apply( - com.google.cloud.dataflow.sdk.io.Write.to(new DatastoreSink(projectId))); + input.apply(ParDo.of(new DatastoreWriterFn(projectId))); + return PDone.in(input.getPipeline()); } @Override @@ -734,117 +697,28 @@ public void populateDisplayData(DisplayData.Builder builder) { } /** - * A {@link Sink} that writes data to Datastore. - */ - static class DatastoreSink extends Sink { - final String projectId; - - public DatastoreSink(String projectId) { - this.projectId = projectId; - } - - @Override - public void validate(PipelineOptions options) { - checkNotNull(projectId, "projectId"); - } - - @Override - public DatastoreWriteOperation createWriteOperation(PipelineOptions options) { - return new DatastoreWriteOperation(this); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("projectId", projectId) - .withLabel("Output Project")); - } - } - - /** - * A {@link WriteOperation} that will manage a parallel write to a Datastore sink. - */ - private static class DatastoreWriteOperation - extends WriteOperation { - private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriteOperation.class); - - private final DatastoreSink sink; - - public DatastoreWriteOperation(DatastoreSink sink) { - this.sink = sink; - } - - @Override - public Coder getWriterResultCoder() { - return SerializableCoder.of(DatastoreWriteResult.class); - } - - @Override - public void initialize(PipelineOptions options) throws Exception {} - - /** - * Finalizes the write. Logs the number of entities written to the Datastore. - */ - @Override - public void finalize(Iterable writerResults, PipelineOptions options) - throws Exception { - long totalEntities = 0; - for (DatastoreWriteResult result : writerResults) { - totalEntities += result.entitiesWritten; - } - LOG.info("Wrote {} elements.", totalEntities); - } - - @Override - public DatastoreWriter createWriter(PipelineOptions options) throws Exception { - DatastoreOptions.Builder builder = - new DatastoreOptions.Builder() - .projectId(sink.projectId) - .initializer(new RetryHttpRequestInitializer()); - Credential credential = options.as(GcpOptions.class).getGcpCredential(); - if (credential != null) { - builder.credential(credential); - } - Datastore datastore = DatastoreFactory.get().create(builder.build()); - - return new DatastoreWriter(this, datastore); - } - - @Override - public DatastoreSink getSink() { - return sink; - } - } - - /** - * {@link Writer} that writes entities to a Datastore Sink. Entities are written in batches, - * where the maximum batch size is {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. Entities - * are committed as upsert mutations (either update if the key already exists, or insert if it is - * a new key). If an entity does not have a complete key (i.e., it has no name or id), the bundle - * will fail. + * A {@link DoFn} that writes {@link Entity} objects to Cloud Datastore. Entities are written in + * batches, where the maximum batch size is {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. + * Entities are committed as upsert mutations (either update if the key already exists, or + * insert if it is a new key). If an entity does not have a complete key (i.e., it has no name + * or id), the bundle will fail. * *

            See - * Datastore: Entities, Properties, and Keys for information about entity keys and upsert - * mutations. + * href="https://cloud.google.com/datastore/docs/concepts/entities"> + * Datastore: Entities, Properties, and Keys for information about entity keys and entities. * *

            Commits are non-transactional. If a commit fails because of a conflict over an entity * group, the commit will be retried (up to {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT} * times). - * - *

            Visible for testing purposes. */ @VisibleForTesting - static class DatastoreWriter extends Writer { - private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriter.class); - private final DatastoreWriteOperation writeOp; - private final Datastore datastore; - private long totalWritten = 0; - - // Visible for testing. - final List entities = new ArrayList<>(); - + static class DatastoreWriterFn extends DoFn { + private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriterFn.class); + private final String projectId; + private transient Datastore datastore; + private final V1Beta3DatastoreFactory datastoreFactory; + // Current batch of entities to be written. + private final List entities = new ArrayList<>(); /** * Since a bundle is written in batches, we should retry the commit of a batch in order to * prevent transient errors from causing the bundle to fail. @@ -856,68 +730,47 @@ static class DatastoreWriter extends Writer { */ private static final int INITIAL_BACKOFF_MILLIS = 5000; - /** - * Returns true if a Datastore key is complete. A key is complete if its last element - * has either an id or a name. - */ - static boolean isValidKey(Key key) { - List elementList = key.getPathList(); - if (elementList.isEmpty()) { - return false; - } - PathElement lastElement = elementList.get(elementList.size() - 1); - return (lastElement.getId() != 0 || !lastElement.getName().isEmpty()); + public DatastoreWriterFn(String projectId) { + this(projectId, new V1Beta3DatastoreFactory()); } - DatastoreWriter(DatastoreWriteOperation writeOp, Datastore datastore) { - this.writeOp = writeOp; - this.datastore = datastore; + @VisibleForTesting + DatastoreWriterFn(String projectId, V1Beta3DatastoreFactory datastoreFactory) { + this.projectId = checkNotNull(projectId, "projectId"); + this.datastoreFactory = datastoreFactory; } @Override - public void open(String uId) throws Exception {} + public void startBundle(Context c) { + datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), projectId); + } - /** - * Writes an entity to the Datastore. Writes are batched, up to {@link - * V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. If an entity does not have a complete key, an - * {@link IllegalArgumentException} will be thrown. - */ @Override - public void write(Entity value) throws Exception { + public void processElement(ProcessContext c) throws Exception { // Verify that the entity to write has a complete key. - if (!isValidKey(value.getKey())) { + if (!isValidKey(c.element().getKey())) { throw new IllegalArgumentException( "Entities to be written to the Datastore must have complete keys"); } - entities.add(value); - + entities.add(c.element()); if (entities.size() >= V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT) { flushBatch(); } } - /** - * Flushes any pending batch writes and returns a DatastoreWriteResult. - */ @Override - public DatastoreWriteResult close() throws Exception { + public void finishBundle(Context c) throws Exception { if (entities.size() > 0) { flushBatch(); } - return new DatastoreWriteResult(totalWritten); - } - - @Override - public DatastoreWriteOperation getWriteOperation() { - return writeOp; } /** - * Writes a batch of entities to the Datastore. + * Writes a batch of entities to Cloud Datastore. * - *

            If a commit fails, it will be retried (up to {@link DatastoreWriter#MAX_RETRIES} - * times). All entities in the batch will be committed again, even if the commit was partially + *

            If a commit fails, it will be retried (up to {@link DatastoreWriterFn#MAX_RETRIES} + * times). All entities in the batch will be committed again, even if the commit was partially * successful. If the retry limit is exceeded, the last exception from the Datastore will be * thrown. * @@ -951,17 +804,66 @@ private void flushBatch() throws DatastoreException, IOException, InterruptedExc } } } - totalWritten += entities.size(); LOG.debug("Successfully wrote {} entities", entities.size()); entities.clear(); } + + @Override + public void populateDisplayData(Builder builder) { + super.populateDisplayData(builder); + builder + .addIfNotNull(DisplayData.item("projectId", projectId) + .withLabel("Output Project")); + } + } + + /** + * Returns true if a Datastore key is complete. A key is complete if its last element + * has either an id or a name. + */ + static boolean isValidKey(Key key) { + List elementList = key.getPathList(); + if (elementList.isEmpty()) { + return false; + } + PathElement lastElement = elementList.get(elementList.size() - 1); + return (lastElement.getId() != 0 || !lastElement.getName().isEmpty()); } - private static class DatastoreWriteResult implements Serializable { - final long entitiesWritten; + /** + * A wrapper factory class for Datastore singleton classes {@link DatastoreFactory} and + * {@link QuerySplitter} + * + *

            {@link DatastoreFactory} and {@link QuerySplitter} are not java serializable, hence + * wrapping them under this class, which implements {@link Serializable}. + */ + @VisibleForTesting + static class V1Beta3DatastoreFactory implements Serializable { - public DatastoreWriteResult(long recordsWritten) { - this.entitiesWritten = recordsWritten; + /** + * Builds a Datastore client for the given pipeline options and project. + */ + public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { + DatastoreOptions.Builder builder = + new DatastoreOptions.Builder() + .projectId(projectId) + .initializer( + new RetryHttpRequestInitializer() + ); + + Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); + if (credential != null) { + builder.credential(credential); + } + + return DatastoreFactory.get().create(builder.build()); + } + + /** + * Builds a Datastore {@link QuerySplitter}. + */ + public QuerySplitter getQuerySplitter() { + return DatastoreHelper.getQuerySplitter(); } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java index 7f668565e7..b0f97ab63a 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.io.datastore; +import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT; import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.DEFAULT_BUNDLE_SIZE_BYTES; import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.QUERY_BATCH_LIMIT; import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.getEstimatedSizeBytes; @@ -25,10 +26,9 @@ import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; - import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeUpsert; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; -import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.Assert.assertEquals; @@ -43,17 +43,18 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreWriter; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreWriterFn; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.ReadFn; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.SplitQueryFn; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.V1Beta3DatastoreFactory; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.V1Beta3Options; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.V1Beta3DatastoreFactory; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.DoFnTester; import com.google.cloud.dataflow.sdk.transforms.DoFnTester.CloningBehavior; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.Lists; +import com.google.datastore.v1beta3.CommitRequest; import com.google.datastore.v1beta3.Entity; import com.google.datastore.v1beta3.EntityResult; import com.google.datastore.v1beta3.Key; @@ -78,7 +79,6 @@ import org.mockito.stubbing.Answer; import java.util.ArrayList; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; @@ -252,33 +252,33 @@ public void testHasNameOrId() { Key key; // Complete with name, no ancestor key = makeKey("bird", "finch").build(); - assertTrue(DatastoreWriter.isValidKey(key)); + assertTrue(V1Beta3.isValidKey(key)); // Complete with id, no ancestor key = makeKey("bird", 123).build(); - assertTrue(DatastoreWriter.isValidKey(key)); + assertTrue(V1Beta3.isValidKey(key)); // Incomplete, no ancestor key = makeKey("bird").build(); - assertFalse(DatastoreWriter.isValidKey(key)); + assertFalse(V1Beta3.isValidKey(key)); // Complete with name and ancestor key = makeKey("bird", "owl").build(); key = makeKey(key, "bird", "horned").build(); - assertTrue(DatastoreWriter.isValidKey(key)); + assertTrue(V1Beta3.isValidKey(key)); // Complete with id and ancestor key = makeKey("bird", "owl").build(); key = makeKey(key, "bird", 123).build(); - assertTrue(DatastoreWriter.isValidKey(key)); + assertTrue(V1Beta3.isValidKey(key)); // Incomplete with ancestor key = makeKey("bird", "owl").build(); key = makeKey(key, "bird").build(); - assertFalse(DatastoreWriter.isValidKey(key)); + assertFalse(V1Beta3.isValidKey(key)); key = makeKey().build(); - assertFalse(DatastoreWriter.isValidKey(key)); + assertFalse(V1Beta3.isValidKey(key)); } /** @@ -288,35 +288,62 @@ public void testHasNameOrId() { public void testAddEntitiesWithIncompleteKeys() throws Exception { Key key = makeKey("bird").build(); Entity entity = Entity.newBuilder().setKey(key).build(); - DatastoreWriter writer = new DatastoreWriter(null, mockDatastore); + DatastoreWriterFn writer = new DatastoreWriterFn(PROJECT_ID, mockDatastoreFactory); + DoFnTester doFnTester = DoFnTester.of(writer); + doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); - thrown.expect(IllegalArgumentException.class); + thrown.expect(UserCodeException.class); thrown.expectMessage("Entities to be written to the Datastore must have complete keys"); - writer.write(entity); + doFnTester.processBatch(entity); + } + + /** Tests {@link DatastoreWriterFn} with entities less than one batch. */ + @Test + public void testDatatoreWriterFnWithOneBatch() throws Exception { + datastoreWriterFnTest(100); + } + + /** Tests {@link DatastoreWriterFn} with entities of more than one batches, but not a multiple. */ + @Test + public void testDatatoreWriterFnWithMultipleBatches() throws Exception { + datastoreWriterFnTest(DATASTORE_BATCH_UPDATE_LIMIT * 3 + 100); } /** - * Test that entities are added to the batch to update. + * Tests {@link DatastoreWriterFn} with entities of several batches, using an exact multiple of + * write batch size. */ @Test - public void testAddingEntities() throws Exception { - List expected = Lists.newArrayList( - Entity.newBuilder().setKey(makeKey("bird", "jay").build()).build(), - Entity.newBuilder().setKey(makeKey("bird", "condor").build()).build(), - Entity.newBuilder().setKey(makeKey("bird", "robin").build()).build()); - - List allEntities = Lists.newArrayList(expected); - Collections.shuffle(allEntities); - - DatastoreWriter writer = new DatastoreWriter(null, mockDatastore); - writer.open("test_id"); - for (Entity entity : allEntities) { - writer.write(entity); + public void testDatatoreWriterFnWithBatchesExactMultiple() throws Exception { + datastoreWriterFnTest(DATASTORE_BATCH_UPDATE_LIMIT * 2); + } + + // A helper method to test DatastoreWriterFn for various batch sizes. + private void datastoreWriterFnTest(int numEntities) throws Exception { + // Create the requested number of mutations. + List entities = new ArrayList<>(numEntities); + for (int i = 0; i < numEntities; ++i) { + entities.add(Entity.newBuilder().setKey(makeKey("key" + i, i + 1)).build()); } - assertEquals(expected.size(), writer.entities.size()); - assertThat(writer.entities, containsInAnyOrder(expected.toArray())); + DatastoreWriterFn datastoreWriter = new DatastoreWriterFn(PROJECT_ID, mockDatastoreFactory); + DoFnTester doFnTester = DoFnTester.of(datastoreWriter); + doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); + doFnTester.processBatch(entities); + + int start = 0; + while (start < numEntities) { + int end = Math.min(numEntities, start + DATASTORE_BATCH_UPDATE_LIMIT); + CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); + commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); + for (Entity entity: entities.subList(start, end)) { + commitRequest.addMutations(makeUpsert(entity)); + } + // Verify all the batch requests were made with the expected entities. + verify(mockDatastore, times(1)).commit(commitRequest.build()); + start = end; + } } /** From 9a0e82913ee26703a6736fdacc179d7e334d41c5 Mon Sep 17 00:00:00 2001 From: reuvenlax Date: Fri, 19 Aug 2016 09:32:33 -0700 Subject: [PATCH 518/751] Remove unneeded synchronization on CounterSet (#381) Now that CounterSet.java is fully threadsafe, all of its synchronized methods simply add lock contention. Remove synchronized everywhere, and replace explicit implementation of addOrReuse with threadsafe calls to ConcurrentHashMap.putIfAbsent. --- .../dataflow/sdk/util/common/CounterSet.java | 33 +++++++------------ 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java index 5d659672f2..3c862e6c88 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java @@ -72,22 +72,17 @@ public void addNewCounter(Counter counter) { * @throws IllegalArgumentException if a counter with the same * name but an incompatible kind had already been added */ - public synchronized Counter addOrReuseCounter(Counter counter) { - Counter oldCounter = counters.get(counter.getName()); - if (oldCounter == null) { - // A new counter. - counters.put(counter.getName(), counter); - return counter; - } - if (counter.isCompatibleWith(oldCounter)) { + public Counter addOrReuseCounter(Counter counter) { + Counter oldCounter = counters.putIfAbsent(counter.getName(), counter); + if (oldCounter != null) { + checkArgument(counter.isCompatibleWith(oldCounter), + "Counter %s duplicates incompatible counter %s in %s", counter, oldCounter, this); // Return the counter to reuse. @SuppressWarnings("unchecked") Counter compatibleCounter = (Counter) oldCounter; return compatibleCounter; } - throw new IllegalArgumentException( - "Counter " + counter + " duplicates incompatible counter " - + oldCounter + " in " + this); + return counter; } /** @@ -105,33 +100,29 @@ public boolean addCounter(Counter counter) { * Returns the Counter with the given name in this CounterSet; * returns null if no such Counter exists. */ - public synchronized Counter getExistingCounter(String name) { + public Counter getExistingCounter(String name) { return counters.get(name); } @Override - public synchronized Iterator> iterator() { + public Iterator> iterator() { return counters.values().iterator(); } @Override - public synchronized int size() { + public int size() { return counters.size(); } @Override - public synchronized boolean add(Counter e) { + public boolean add(Counter e) { if (null == e) { return false; } - if (counters.containsKey(e.getName())) { - return false; - } - counters.put(e.getName(), e); - return true; + return counters.putIfAbsent(e.getName(), e) == null; } - public synchronized void merge(CounterSet that) { + public void merge(CounterSet that) { for (Counter theirCounter : that) { Counter myCounter = counters.get(theirCounter.getName()); if (myCounter != null) { From cca2b9985ce64c87ada35b67a5c2c49460e229dd Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 19 Aug 2016 10:22:49 -0700 Subject: [PATCH 519/751] Mark JAXBContext as Volatile in JAXBCoder This corrects the double-checked locking and lazy intialization --- .../java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java index 9e0c9c4b47..fb4e5bdcdf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java @@ -40,7 +40,7 @@ public class JAXBCoder extends AtomicCoder { private final Class jaxbClass; - private transient JAXBContext jaxbContext; + private transient volatile JAXBContext jaxbContext; public Class getJAXBClass() { return jaxbClass; From 9648029b8e94155d989b23c140dfd6a4897517f2 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 12 Aug 2016 15:14:52 -0700 Subject: [PATCH 520/751] Use an Explicit Coder in XML source test If an XML record is encoded without having access to the remainder of the stream it will throw an exception when being decoded. --- .../cloud/dataflow/sdk/io/XmlSourceTest.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java index 198d3857dc..cfc5b23d49 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java @@ -18,7 +18,6 @@ import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionFails; import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; @@ -27,6 +26,8 @@ import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.AvroCoder; +import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.io.Source.Reader; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; @@ -36,6 +37,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.collect.ImmutableList; +import org.apache.avro.reflect.ReflectData; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Rule; @@ -227,6 +229,11 @@ public String toString() { } } + // Use a non-XML coder as JAXBCoder is not suitable for use as an intermediate coder, as it + // requires the entire stream to behave correctly. + private Coder trainCoder = + AvroCoder.of(Train.class, ReflectData.AllowNull.get().getSchema(Train.class)); + private List generateRandomTrainList(int size) { String[] names = {"Thomas", "Henry", "Gordon", "Emily", "Toby", "Percy", "Mavis", "Edward", "Bertie", "Harold", "Hiro", "Terence", "Salty", "Trevor"}; @@ -576,7 +583,8 @@ public void testReadXMLSmallDataflow() throws IOException { .withRecordClass(Train.class) .withMinBundleSize(1024); - PCollection output = p.apply(Read.from(source).named("ReadFileData")); + PCollection output = + p.apply(Read.from(source).named("ReadFileData")).setCoder(trainCoder); List expectedResults = ImmutableList.of(new Train("Thomas", 1, "blue", null), new Train("Henry", 3, "green", null), @@ -665,7 +673,8 @@ public void testReadXMLLargeDataflow() throws IOException { .withRecordElement("train") .withRecordClass(Train.class) .withMinBundleSize(1024); - PCollection output = p.apply(Read.from(source).named("ReadFileData")); + PCollection output = + p.apply(Read.from(source).named("ReadFileData")).setCoder(trainCoder); DataflowAssert.that(output).containsInAnyOrder(trains); p.run(); @@ -812,7 +821,8 @@ public void testReadXMLFilePattern() throws IOException { .withRecordElement("train") .withRecordClass(Train.class) .withMinBundleSize(1024); - PCollection output = p.apply(Read.from(source).named("ReadFileData")); + PCollection output = p.apply(Read.from(source).named("ReadFileData")) + .setCoder(trainCoder); List expectedResults = new ArrayList<>(); expectedResults.addAll(trains1); From e37d3f3171d2807430efc0417982e4b139a4acfb Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Wed, 8 Jun 2016 16:22:34 -0700 Subject: [PATCH 521/751] Fix TriggerExampleTest --- .../examples/cookbook/TriggerExampleTest.java | 69 ++++++++++++------- 1 file changed, 45 insertions(+), 24 deletions(-) diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java index 209ea521bd..75cd0cf03a 100644 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java +++ b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java @@ -32,6 +32,8 @@ import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.common.base.Joiner; +import com.google.common.collect.Lists; import org.joda.time.Duration; import org.joda.time.Instant; @@ -42,7 +44,9 @@ import org.junit.runners.JUnit4; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.Map; /** * Unit Tests for {@link TriggerExample}. @@ -53,9 +57,9 @@ public class TriggerExampleTest { private static final String[] INPUT = - {"01/01/2010 00:00:00,1108302,94,E,ML,36,100,29,0.0065,66,9,1,0.001,74.8,1,9,3,0.0028,71,1,9," - + "12,0.0099,67.4,1,9,13,0.0121,99.0,1,,,,,0,,,,,0,,,,,0,,,,,0", "01/01/2010 00:00:00," - + "1100333,5,N,FR,9,0,39,,,9,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,"}; + {"01/01/2010 00:00:00,1108302,94,E,ML,36,100,29,0.0065,66,9,1,0.001,74.8,1,9,3,0.0028,71,1,9," + + "12,0.0099,67.4,1,9,13,0.0121,99.0,1,,,,,0,,,,,0,,,,,0,,,,,0", "01/01/2010 00:00:00," + + "1100333,5,N,FR,9,0,39,,,9,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,"}; private static final List> TIME_STAMPED_INPUT = Arrays.asList( TimestampedValue.of("01/01/2010 00:00:00,1108302,5,W,ML,36,100,30,0.0065,66,9,1,0.001," @@ -68,24 +72,30 @@ public class TriggerExampleTest { + "0.001,74.8,1,9,3,0.0028,71,1,9,12,0.0099,97.4,1,9,13,0.0121,50.0,1,,,,,0,,,,,0" + ",,,,,0,,,,,0", new Instant(1))); - private static final TableRow OUT_ROW_1 = new TableRow() - .set("trigger_type", "default") - .set("freeway", "5").set("total_flow", 30) - .set("number_of_records", 1) - .set("isFirst", true).set("isLast", true) - .set("timing", "ON_TIME") - .set("window", "[1970-01-01T00:01:00.000Z..1970-01-01T00:02:00.000Z)"); - - private static final TableRow OUT_ROW_2 = new TableRow() - .set("trigger_type", "default") - .set("freeway", "110").set("total_flow", 90) - .set("number_of_records", 2) - .set("isFirst", true).set("isLast", true) - .set("timing", "ON_TIME") - .set("window", "[1970-01-01T00:00:00.000Z..1970-01-01T00:01:00.000Z)"); + private static final TableRow OUT_ROW_1 = + new TableRow() + .set("trigger_type", "default") + .set("freeway", "5") + .set("total_flow", 30) + .set("number_of_records", 1) + .set("isFirst", true) + .set("isLast", true) + .set("timing", "ON_TIME") + .set("window", "[1970-01-01T00:01:00.000Z..1970-01-01T00:02:00.000Z)"); + + private static final TableRow OUT_ROW_2 = + new TableRow() + .set("trigger_type", "default") + .set("freeway", "110") + .set("total_flow", 90) + .set("number_of_records", 2) + .set("isFirst", true) + .set("isLast", true) + .set("timing", "ON_TIME") + .set("window", "[1970-01-01T00:00:00.000Z..1970-01-01T00:01:00.000Z)"); @Test - public void testExtractTotalFlow() { + public void testExtractTotalFlow() throws Exception { DoFnTester> extractFlowInfow = DoFnTester .of(new ExtractFlowInfo()); @@ -110,15 +120,26 @@ public void testTotalFlow () { .apply(Window.>into(FixedWindows.of(Duration.standardMinutes(1)))) .apply(new TotalFlow("default")); - PCollection results = totalFlow.apply(ParDo.of(new FormatResults())); + PCollection results = totalFlow.apply(ParDo.of(new FormatResults())); - - DataflowAssert.that(results).containsInAnyOrder(OUT_ROW_1, OUT_ROW_2); + DataflowAssert.that(results) + .containsInAnyOrder(canonicalFormat(OUT_ROW_1), canonicalFormat(OUT_ROW_2)); pipeline.run(); } - static class FormatResults extends DoFn { + // Sort the fields and toString() the values, since TableRow has a bit of a dynamically + // typed API and equals()/hashCode() are not appropriate for matching in tests + static String canonicalFormat(TableRow row) { + List entries = Lists.newArrayListWithCapacity(row.size()); + for (Map.Entry entry : row.entrySet()) { + entries.add(entry.getKey() + ":" + entry.getValue()); + } + Collections.sort(entries); + return Joiner.on(",").join(entries); + } + + static class FormatResults extends DoFn { @Override public void processElement(ProcessContext c) throws Exception { TableRow element = c.element(); @@ -131,7 +152,7 @@ public void processElement(ProcessContext c) throws Exception { .set("isLast", element.get("isLast")) .set("timing", element.get("timing")) .set("window", element.get("window")); - c.output(row); + c.output(canonicalFormat(row)); } } } From f02e2c338a57727a84d69eb9273ebcce6ba12ec6 Mon Sep 17 00:00:00 2001 From: Pei He Date: Fri, 19 Aug 2016 14:58:30 -0700 Subject: [PATCH 522/751] Backport Beam PR-835 Fix NPE in BigQueryIO.TransformingReader when it contains an unsplittable reader. --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 12 +- .../dataflow/sdk/testing/SourceTestUtils.java | 130 ++++++++++++++++++ .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 31 +++++ .../sdk/testing/SourceTestUtilsTest.java | 64 +++++++++ 4 files changed, 231 insertions(+), 6 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 1ee2f0297c..e7ced589a2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1146,9 +1146,9 @@ static class TransformingSource extends BoundedSource { BoundedSource boundedSource, SerializableFunction function, Coder outputCoder) { - this.boundedSource = boundedSource; - this.function = function; - this.outputCoder = outputCoder; + this.boundedSource = checkNotNull(boundedSource, "boundedSource"); + this.function = checkNotNull(function, "function"); + this.outputCoder = checkNotNull(outputCoder, "outputCoder"); } @Override @@ -1193,7 +1193,7 @@ private class TransformingReader extends BoundedReader { private final BoundedReader boundedReader; private TransformingReader(BoundedReader boundedReader) { - this.boundedReader = boundedReader; + this.boundedReader = checkNotNull(boundedReader, "boundedReader"); } @Override @@ -1224,8 +1224,8 @@ public void close() throws IOException { @Override public synchronized BoundedSource splitAtFraction(double fraction) { - return new TransformingSource<>( - boundedReader.splitAtFraction(fraction), function, outputCoder); + BoundedSource split = boundedReader.splitAtFraction(fraction); + return split == null ? null : new TransformingSource<>(split, function, outputCoder); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java index df92332c86..0b7fb3ea8c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.sdk.testing; +import static com.google.common.base.Preconditions.checkNotNull; + import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; @@ -28,8 +30,11 @@ import com.google.cloud.dataflow.sdk.io.BoundedSource; import com.google.cloud.dataflow.sdk.io.Source; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.collect.ImmutableList; +import org.joda.time.Instant; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,6 +42,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -44,6 +50,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; +import javax.annotation.Nullable; + /** * Helper functions and test harnesses for checking correctness of {@link Source} * implementations. @@ -672,4 +680,126 @@ public KV, BoundedSource> call() throws Exception { numItemsToReadBeforeSplitting, fraction, options); return (res.numResidualItems > 0); } + + /** + * Returns an equivalent unsplittable {@code BoundedSource}. + * + *

            It forwards most methods to the given {@code boundedSource}, except: + *

              + *
            1. {@link BoundedSource#splitIntoBundles} rejects initial splitting + * by returning itself in a list. + *
            2. {@link BoundedReader#splitAtFraction} rejects dynamic splitting by returning null. + *
            + */ + public static BoundedSource toUnsplittableSource(BoundedSource boundedSource) { + return new UnsplittableSource<>(boundedSource); + } + + private static class UnsplittableSource extends BoundedSource { + + private final BoundedSource boundedSource; + + private UnsplittableSource(BoundedSource boundedSource) { + this.boundedSource = checkNotNull(boundedSource, "boundedSource"); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + this.boundedSource.populateDisplayData(builder); + } + + @Override + public List> splitIntoBundles( + long desiredBundleSizeBytes, PipelineOptions options) throws Exception { + return ImmutableList.of(this); + } + + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + return boundedSource.getEstimatedSizeBytes(options); + } + + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return boundedSource.producesSortedKeys(options); + } + + @Override + public BoundedReader createReader(PipelineOptions options) throws IOException { + return new UnsplittableReader<>(boundedSource, boundedSource.createReader(options)); + } + + @Override + public void validate() { + boundedSource.validate(); + } + + @Override + public Coder getDefaultOutputCoder() { + return boundedSource.getDefaultOutputCoder(); + } + + private static class UnsplittableReader extends BoundedReader { + + private final BoundedSource boundedSource; + private final BoundedReader boundedReader; + + private UnsplittableReader(BoundedSource boundedSource, BoundedReader boundedReader) { + this.boundedSource = checkNotNull(boundedSource, "boundedSource"); + this.boundedReader = checkNotNull(boundedReader, "boundedReader"); + } + + @Override + public BoundedSource getCurrentSource() { + return boundedSource; + } + + @Override + public boolean start() throws IOException { + return boundedReader.start(); + } + + @Override + public boolean advance() throws IOException { + return boundedReader.advance(); + } + + @Override + public T getCurrent() throws NoSuchElementException { + return boundedReader.getCurrent(); + } + + @Override + public void close() throws IOException { + boundedReader.close(); + } + + @Override + @Nullable + public BoundedSource splitAtFraction(double fraction) { + return null; + } + + @Override + @Nullable + public Double getFractionConsumed() { + return boundedReader.getFractionConsumed(); + } + + @Override + public long getSplitPointsConsumed() { + return boundedReader.getSplitPointsConsumed(); + } + + @Override + public long getSplitPointsRemaining() { + return boundedReader.getSplitPointsRemaining(); + } + + @Override + public Instant getCurrentTimestamp() throws NoSuchElementException { + return boundedReader.getCurrentTimestamp(); + } + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index e91dd6afa6..2ca6f43e61 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -1201,6 +1201,37 @@ public String apply(Long input) { stringSource, stringSource.splitIntoBundles(100, options), options); } + @Test + public void testTransformingSourceUnsplittable() throws Exception { + int numElements = 10000; + @SuppressWarnings("deprecation") + BoundedSource longSource = + SourceTestUtils.toUnsplittableSource(CountingSource.upTo(numElements)); + SerializableFunction toStringFn = + new SerializableFunction() { + @Override + public String apply(Long input) { + return input.toString(); + } + }; + BoundedSource stringSource = + new TransformingSource<>(longSource, toStringFn, StringUtf8Coder.of()); + + List expected = Lists.newArrayList(); + for (int i = 0; i < numElements; i++) { + expected.add(String.valueOf(i)); + } + + PipelineOptions options = PipelineOptionsFactory.create(); + Assert.assertThat( + SourceTestUtils.readFromSource(stringSource, options), CoreMatchers.is(expected)); + SourceTestUtils.assertSplitAtFractionBehavior( + stringSource, 100, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); + + SourceTestUtils.assertSourcesEqualReferenceSource( + stringSource, stringSource.splitIntoBundles(100, options), options); + } + @Test @Category(RunnableOnService.class) public void testPassThroughThenCleanup() throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java new file mode 100644 index 0000000000..d88e8347a9 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java @@ -0,0 +1,64 @@ + +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.google.cloud.dataflow.sdk.io.BoundedSource; +import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; +import com.google.cloud.dataflow.sdk.io.CountingSource; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.common.collect.Sets; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.List; +import java.util.Set; + +/** + * Tests for {@link SourceTestUtils}. + */ +@RunWith(JUnit4.class) +public class SourceTestUtilsTest { + + @Test + public void testToUnsplittableSource() throws Exception { + PipelineOptions options = PipelineOptionsFactory.create(); + BoundedSource baseSource = CountingSource.upTo(100); + BoundedSource unsplittableSource = SourceTestUtils.toUnsplittableSource(baseSource); + List splits = unsplittableSource.splitIntoBundles(1, options); + assertEquals(splits.size(), 1); + assertEquals(splits.get(0), unsplittableSource); + + BoundedReader unsplittableReader = unsplittableSource.createReader(options); + assertEquals(0, unsplittableReader.getFractionConsumed(), 1e-15); + + Set expected = Sets.newHashSet(SourceTestUtils.readFromSource(baseSource, options)); + Set actual = Sets.newHashSet(); + actual.addAll(SourceTestUtils.readNItemsFromUnstartedReader(unsplittableReader, 40)); + assertNull(unsplittableReader.splitAtFraction(0.5)); + actual.addAll(SourceTestUtils.readRemainingFromReader(unsplittableReader, true /* started */)); + assertEquals(1, unsplittableReader.getFractionConsumed(), 1e-15); + + assertEquals(100, actual.size()); + assertEquals(Sets.newHashSet(expected), Sets.newHashSet(actual)); + } +} From 149c87fe7e60953689de69d6231b4fdfd3d7ec85 Mon Sep 17 00:00:00 2001 From: Ian Zhou Date: Fri, 19 Aug 2016 16:46:22 -0700 Subject: [PATCH 523/751] BigQueryIO update sink to shard into multiple write jobs (#362) * [BEAM-383] Modified BigQueryIO to write based on number of files and file sizes * BigQueryIO update sink to shard into multiple write jobs * Added unit tests and error handling in removeTemporaryTables * Minor changes * Javadoc fix * Checkstyle * Fixed javadoc change --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 605 +++++++++++++----- .../dataflow/sdk/util/BigQueryServices.java | 9 +- .../sdk/util/BigQueryServicesImpl.java | 82 ++- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 345 +++++++++- 4 files changed, 840 insertions(+), 201 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index e7ced589a2..6263c0b64a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -29,6 +29,7 @@ import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobConfigurationTableCopy; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobStatus; @@ -36,6 +37,7 @@ import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; +import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.AtomicCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.Coder.Context; @@ -46,8 +48,6 @@ import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; @@ -55,6 +55,7 @@ import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; @@ -62,6 +63,9 @@ import com.google.cloud.dataflow.sdk.transforms.View; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.AvroUtils; import com.google.cloud.dataflow.sdk.util.BigQueryServices; @@ -70,6 +74,9 @@ import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl; import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; +import com.google.cloud.dataflow.sdk.util.FileIOChannelFactory; +import com.google.cloud.dataflow.sdk.util.GcsIOChannelFactory; +import com.google.cloud.dataflow.sdk.util.GcsUtil; import com.google.cloud.dataflow.sdk.util.GcsUtil.GcsUtilFactory; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; @@ -94,6 +101,7 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; +import com.google.common.io.CountingOutputStream; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -111,6 +119,8 @@ import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -389,7 +399,7 @@ public static class Bound extends PTransform> { @Nullable final String query; final boolean validate; @Nullable final Boolean flattenResults; - @Nullable final BigQueryServices testBigQueryServices; + @Nullable BigQueryServices testBigQueryServices; private static final String QUERY_VALIDATION_FAILURE_ERROR = "Validation of query \"%1$s\" failed. If the query depends on an earlier stage of the" @@ -689,11 +699,10 @@ public Boolean getFlattenResults() { } private BigQueryServices getBigQueryServices() { - if (testBigQueryServices != null) { - return testBigQueryServices; - } else { - return new BigQueryServicesImpl(); + if (testBigQueryServices == null) { + testBigQueryServices = new BigQueryServicesImpl(); } + return testBigQueryServices; } } @@ -1451,6 +1460,19 @@ public static Bound withoutValidation() { * {@link PCollection} of {@link TableRow TableRows} to a BigQuery table. */ public static class Bound extends PTransform, PDone> { + // Maximum number of files in a single partition. + static final int MAX_NUM_FILES = 10000; + + // Maximum number of bytes in a single partition. + static final long MAX_SIZE_BYTES = 3 * (1L << 40); + + // The maximum number of retry jobs. + static final int MAX_RETRY_JOBS = 3; + + // The maximum number of retries to poll the status of a job. + // It sets to {@code Integer.MAX_VALUE} to block until the BigQuery job finishes. + static final int LOAD_JOB_POLL_MAX_RETRIES = Integer.MAX_VALUE; + @Nullable final String jsonTableRef; @Nullable final SerializableFunction tableRefFunction; @@ -1721,7 +1743,9 @@ public void validate(PCollection input) { @Override public PDone apply(PCollection input) { - BigQueryOptions options = input.getPipeline().getOptions().as(BigQueryOptions.class); + Pipeline p = input.getPipeline(); + BigQueryOptions options = p.getOptions().as(BigQueryOptions.class); + BigQueryServices bqServices = getBigQueryServices(); // In a streaming job, or when a tablespec function is defined, we use StreamWithDeDup // and BigQuery's streaming import API. @@ -1733,13 +1757,13 @@ public PDone apply(PCollection input) { if (Strings.isNullOrEmpty(table.getProjectId())) { table.setProjectId(options.getProject()); } - String jobIdToken = randomUUIDString(); + String jobIdToken = "beam_job_" + randomUUIDString(); String tempLocation = options.getTempLocation(); String tempFilePrefix; try { IOChannelFactory factory = IOChannelUtils.getFactory(tempLocation); tempFilePrefix = factory.resolve( - factory.resolve(tempLocation, "BigQuerySinkTemp"), + factory.resolve(tempLocation, "BigQueryWriteTemp"), jobIdToken); } catch (IOException e) { throw new RuntimeException( @@ -1747,17 +1771,120 @@ public PDone apply(PCollection input) { e); } - BigQueryServices bqServices = getBigQueryServices(); - return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( - new BigQuerySink( + PCollection singleton = p.apply("Create", Create.of(tempFilePrefix)); + + PCollection inputInGlobalWindow = + input.apply( + Window.into(new GlobalWindows()) + .triggering(DefaultTrigger.of()) + .discardingFiredPanes()); + + PCollection> results = inputInGlobalWindow + .apply("WriteBundles", + ParDo.of(new WriteBundles(tempFilePrefix))); + + TupleTag>> multiPartitionsTag = + new TupleTag>>("multiPartitionsTag") {}; + TupleTag>> singlePartitionTag = + new TupleTag>>("singlePartitionTag") {}; + + PCollectionView>> resultsView = results + .apply("ResultsView", View.>asIterable()); + PCollectionTuple partitions = singleton.apply(ParDo + .of(new WritePartition( + resultsView, + multiPartitionsTag, + singlePartitionTag)) + .withSideInputs(resultsView) + .withOutputTags(multiPartitionsTag, TupleTagList.of(singlePartitionTag))); + + // Write multiple partitions to separate temporary tables + PCollection tempTables = partitions.get(multiPartitionsTag) + .apply("MultiPartitionsGroupByKey", GroupByKey.>create()) + .apply("MultiPartitionsWriteTables", ParDo.of(new WriteTables( + false, + bqServices, jobIdToken, - table, + tempFilePrefix, + toJsonString(table), jsonSchema, - getWriteDisposition(), - getCreateDisposition(), + WriteDisposition.WRITE_EMPTY, + CreateDisposition.CREATE_IF_NEEDED))); + + PCollectionView> tempTablesView = tempTables + .apply("TempTablesView", View.asIterable()); + singleton.apply(ParDo + .of(new WriteRename( + bqServices, + jobIdToken, + toJsonString(table), + writeDisposition, + createDisposition, + tempTablesView)) + .withSideInputs(tempTablesView)); + + // Write single partition to final table + partitions.get(singlePartitionTag) + .apply("SinglePartitionGroupByKey", GroupByKey.>create()) + .apply("SinglePartitionWriteTables", ParDo.of(new WriteTables( + true, + bqServices, + jobIdToken, tempFilePrefix, - input.getCoder(), - bqServices))); + toJsonString(table), + jsonSchema, + writeDisposition, + createDisposition))); + + return PDone.in(input.getPipeline()); + } + + private class WriteBundles extends DoFn> { + private TableRowWriter writer = null; + private final String tempFilePrefix; + + WriteBundles(String tempFilePrefix) { + this.tempFilePrefix = tempFilePrefix; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + if (writer == null) { + writer = new TableRowWriter(tempFilePrefix); + writer.open(UUID.randomUUID().toString()); + LOG.debug("Done opening writer {}", writer); + } + try { + writer.write(c.element()); + } catch (Exception e) { + // Discard write result and close the write. + try { + writer.close(); + // The writer does not need to be reset, as this OldDoFn cannot be reused. + } catch (Exception closeException) { + // Do not mask the exception that caused the write to fail. + e.addSuppressed(closeException); + } + throw e; + } + } + + @Override + public void finishBundle(Context c) throws Exception { + if (writer != null) { + c.output(writer.close()); + writer = null; + } + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder + .addIfNotNull(DisplayData.item("tempFilePrefix", tempFilePrefix) + .withLabel("Temporary File Prefix")); + } } @Override @@ -1816,200 +1943,374 @@ public boolean getValidate() { } private BigQueryServices getBigQueryServices() { - if (testBigQueryServices != null) { - return testBigQueryServices; - } else { - return new BigQueryServicesImpl(); + if (testBigQueryServices == null) { + testBigQueryServices = new BigQueryServicesImpl(); } + return testBigQueryServices; } } - /** Disallow construction of utility class. */ - private Write() {} - } - - /** - * {@link BigQuerySink} is implemented as a {@link FileBasedSink}. - * - *

            It uses BigQuery load job to import files into BigQuery. - */ - static class BigQuerySink extends FileBasedSink { - private final String jobIdToken; - @Nullable private final String jsonTable; - @Nullable private final String jsonSchema; - private final WriteDisposition writeDisposition; - private final CreateDisposition createDisposition; - private final Coder coder; - private final BigQueryServices bqServices; - - public BigQuerySink( - String jobIdToken, - @Nullable TableReference table, - @Nullable String jsonSchema, - WriteDisposition writeDisposition, - CreateDisposition createDisposition, - String tempFile, - Coder coder, - BigQueryServices bqServices) { - super(tempFile, ".json"); - this.jobIdToken = checkNotNull(jobIdToken, "jobIdToken"); - if (table == null) { - this.jsonTable = null; - } else { - checkArgument(!Strings.isNullOrEmpty(table.getProjectId()), - "Table %s should have a project specified", table); - this.jsonTable = toJsonString(table); - } - this.jsonSchema = jsonSchema; - this.writeDisposition = checkNotNull(writeDisposition, "writeDisposition"); - this.createDisposition = checkNotNull(createDisposition, "createDisposition"); - this.coder = checkNotNull(coder, "coder"); - this.bqServices = checkNotNull(bqServices, "bqServices"); - } - - @Override - public FileBasedSink.FileBasedWriteOperation createWriteOperation( - PipelineOptions options) { - return new BigQueryWriteOperation(this); - } + static class TableRowWriter { + private static final Coder CODER = TableRowJsonCoder.of(); + private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); + private final String tempFilePrefix; + private String id; + private String fileName; + private WritableByteChannel channel; + protected String mimeType = MimeTypes.TEXT; + private CountingOutputStream out; + + TableRowWriter(String basename) { + this.tempFilePrefix = basename; + } + + public final void open(String uId) throws Exception { + id = uId; + fileName = tempFilePrefix + id; + LOG.debug("Opening {}.", fileName); + channel = IOChannelUtils.create(fileName, mimeType); + try { + out = new CountingOutputStream(Channels.newOutputStream(channel)); + LOG.debug("Writing header to {}.", fileName); + } catch (Exception e) { + try { + LOG.error("Writing header to {} failed, closing channel.", fileName); + channel.close(); + } catch (IOException closeException) { + LOG.error("Closing channel for {} failed", fileName); + } + throw e; + } + LOG.debug("Starting write of bundle {} to {}.", this.id, fileName); + } - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); + public void write(TableRow value) throws Exception { + CODER.encode(value, out, Context.OUTER); + out.write(NEWLINE); + } - builder - .addIfNotNull(DisplayData.item("schema", jsonSchema) - .withLabel("Table Schema")) - .addIfNotNull(DisplayData.item("tableSpec", jsonTable) - .withLabel("Table Specification")); + public final KV close() throws IOException { + channel.close(); + return KV.of(fileName, out.getCount()); + } } - private static class BigQueryWriteOperation extends FileBasedWriteOperation { - // The maximum number of retry load jobs. - private static final int MAX_RETRY_LOAD_JOBS = 3; + /** + * Partitions temporary files based on number of files and file sizes. + */ + static class WritePartition extends DoFn>> { + private final PCollectionView>> resultsView; + private TupleTag>> multiPartitionsTag; + private TupleTag>> singlePartitionTag; - // The maximum number of retries to poll the status of a load job. - // It sets to {@code Integer.MAX_VALUE} to block until the BigQuery job finishes. - private static final int LOAD_JOB_POLL_MAX_RETRIES = Integer.MAX_VALUE; + public WritePartition( + PCollectionView>> resultsView, + TupleTag>> multiPartitionsTag, + TupleTag>> singlePartitionTag) { + this.resultsView = resultsView; + this.multiPartitionsTag = multiPartitionsTag; + this.singlePartitionTag = singlePartitionTag; + } - private final BigQuerySink bigQuerySink; + @Override + public void processElement(ProcessContext c) throws Exception { + List> results = Lists.newArrayList(c.sideInput(resultsView)); + if (results.isEmpty()) { + TableRowWriter writer = new TableRowWriter(c.element()); + writer.open(UUID.randomUUID().toString()); + results.add(writer.close()); + } - private BigQueryWriteOperation(BigQuerySink sink) { - super(checkNotNull(sink, "sink")); - this.bigQuerySink = sink; + long partitionId = 0; + int currNumFiles = 0; + long currSizeBytes = 0; + List currResults = Lists.newArrayList(); + for (int i = 0; i < results.size(); ++i) { + KV fileResult = results.get(i); + if (currNumFiles + 1 > Bound.MAX_NUM_FILES + || currSizeBytes + fileResult.getValue() > Bound.MAX_SIZE_BYTES) { + c.sideOutput(multiPartitionsTag, KV.of(++partitionId, currResults)); + currResults = Lists.newArrayList(); + currNumFiles = 0; + currSizeBytes = 0; + } + ++currNumFiles; + currSizeBytes += fileResult.getValue(); + currResults.add(fileResult.getKey()); + } + if (partitionId == 0) { + c.sideOutput(singlePartitionTag, KV.of(++partitionId, currResults)); + } else { + c.sideOutput(multiPartitionsTag, KV.of(++partitionId, currResults)); + } } @Override - public FileBasedWriter createWriter(PipelineOptions options) throws Exception { - return new TableRowWriter(this, bigQuerySink.coder); + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + } + } + + /** + * Writes partitions to BigQuery tables. + */ + static class WriteTables extends DoFn>>, String> { + private final boolean singlePartition; + private final BigQueryServices bqServices; + private final String jobIdToken; + private final String tempFilePrefix; + private final String jsonTableRef; + private final String jsonSchema; + private final WriteDisposition writeDisposition; + private final CreateDisposition createDisposition; + + public WriteTables( + boolean singlePartition, + BigQueryServices bqServices, + String jobIdToken, + String tempFilePrefix, + String jsonTableRef, + String jsonSchema, + WriteDisposition writeDisposition, + CreateDisposition createDisposition) { + this.singlePartition = singlePartition; + this.bqServices = bqServices; + this.jobIdToken = jobIdToken; + this.tempFilePrefix = tempFilePrefix; + this.jsonTableRef = jsonTableRef; + this.jsonSchema = jsonSchema; + this.writeDisposition = writeDisposition; + this.createDisposition = createDisposition; } @Override - public void finalize(Iterable writerResults, PipelineOptions options) - throws IOException, InterruptedException { - try { - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - List tempFiles = Lists.newArrayList(); - for (FileResult result : writerResults) { - tempFiles.add(result.getFilename()); - } - if (!tempFiles.isEmpty()) { - load( - bigQuerySink.bqServices.getJobService(bqOptions), - bigQuerySink.jobIdToken, - fromJsonString(bigQuerySink.jsonTable, TableReference.class), - tempFiles, - fromJsonString(bigQuerySink.jsonSchema, TableSchema.class), - bigQuerySink.writeDisposition, - bigQuerySink.createDisposition); - } - } finally { - removeTemporaryFiles(options); + public void processElement(ProcessContext c) throws Exception { + List partition = Lists.newArrayList(c.element().getValue()).get(0); + String jobIdPrefix = String.format(jobIdToken + "_%05d", c.element().getKey()); + TableReference ref = fromJsonString(jsonTableRef, TableReference.class); + if (!singlePartition) { + ref.setTableId(jobIdPrefix); } + + load( + bqServices.getJobService(c.getPipelineOptions().as(BigQueryOptions.class)), + jobIdPrefix, + ref, + fromJsonString(jsonSchema, TableSchema.class), + partition, + writeDisposition, + createDisposition); + c.output(toJsonString(ref)); + + removeTemporaryFiles(c.getPipelineOptions(), tempFilePrefix, partition); } - /** - * Import files into BigQuery with load jobs. - * - *

            Returns if files are successfully loaded into BigQuery. - * Throws a RuntimeException if: - * 1. The status of one load job is UNKNOWN. This is to avoid duplicating data. - * 2. It exceeds {@code MAX_RETRY_LOAD_JOBS}. - * - *

            If a load job failed, it will try another load job with a different job id. - */ private void load( JobService jobService, String jobIdPrefix, TableReference ref, - List gcsUris, @Nullable TableSchema schema, + List gcsUris, WriteDisposition writeDisposition, CreateDisposition createDisposition) throws InterruptedException, IOException { JobConfigurationLoad loadConfig = new JobConfigurationLoad() - .setSourceUris(gcsUris) .setDestinationTable(ref) .setSchema(schema) + .setSourceUris(gcsUris) .setWriteDisposition(writeDisposition.name()) .setCreateDisposition(createDisposition.name()) .setSourceFormat("NEWLINE_DELIMITED_JSON"); - boolean retrying = false; String projectId = ref.getProjectId(); - for (int i = 0; i < MAX_RETRY_LOAD_JOBS; ++i) { + for (int i = 0; i < Bound.MAX_RETRY_JOBS; ++i) { String jobId = jobIdPrefix + "-" + i; - if (retrying) { - LOG.info("Previous load jobs failed, retrying."); - } - LOG.info("Starting BigQuery load job: {}", jobId); + LOG.info("Starting BigQuery load job {}: try {}/{}", jobId, i, Bound.MAX_RETRY_JOBS); JobReference jobRef = new JobReference() .setProjectId(projectId) .setJobId(jobId); jobService.startLoadJob(jobRef, loadConfig); Status jobStatus = - parseStatus(jobService.pollJob(jobRef, LOAD_JOB_POLL_MAX_RETRIES)); + parseStatus(jobService.pollJob(jobRef, Bound.LOAD_JOB_POLL_MAX_RETRIES)); switch (jobStatus) { case SUCCEEDED: return; case UNKNOWN: - throw new RuntimeException("Failed to poll the load job status."); + throw new RuntimeException("Failed to poll the load job status of job " + jobId); case FAILED: LOG.info("BigQuery load job failed: {}", jobId); - retrying = true; continue; default: - throw new IllegalStateException("Unexpected job status: " + jobStatus); + throw new IllegalStateException(String.format("Unexpected job status: %s of job %s", + jobStatus, jobId)); } } - throw new RuntimeException( - "Failed to create the load job, reached max retries: " + MAX_RETRY_LOAD_JOBS); + throw new RuntimeException(String.format("Failed to create the load job %s, reached max " + + "retries: %d", jobIdPrefix, Bound.MAX_RETRY_JOBS)); + } + + static void removeTemporaryFiles( + PipelineOptions options, + String tempFilePrefix, + Collection files) + throws IOException { + IOChannelFactory factory = IOChannelUtils.getFactory(tempFilePrefix); + if (factory instanceof GcsIOChannelFactory) { + GcsUtil gcsUtil = new GcsUtil.GcsUtilFactory().create(options); + gcsUtil.remove(files); + } else if (factory instanceof FileIOChannelFactory) { + for (String filename : files) { + LOG.debug("Removing file {}", filename); + boolean exists = Files.deleteIfExists(Paths.get(filename)); + if (!exists) { + LOG.debug("{} does not exist.", filename); + } + } + } else { + throw new IOException("Unrecognized file system."); + } } - } - private static class TableRowWriter extends FileBasedWriter { - private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); - private final Coder coder; - private OutputStream out; + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); - public TableRowWriter( - FileBasedWriteOperation writeOperation, Coder coder) { - super(writeOperation); - this.mimeType = MimeTypes.TEXT; - this.coder = coder; + builder + .addIfNotNull(DisplayData.item("jobIdToken", jobIdToken) + .withLabel("Job ID Token")) + .addIfNotNull(DisplayData.item("tempFilePrefix", tempFilePrefix) + .withLabel("Temporary File Prefix")) + .addIfNotNull(DisplayData.item("jsonTableRef", jsonTableRef) + .withLabel("Table Reference")) + .addIfNotNull(DisplayData.item("jsonSchema", jsonSchema) + .withLabel("Table Schema")); + } + } + + /** + * Copies temporary tables to destination table. + */ + static class WriteRename extends DoFn { + private final BigQueryServices bqServices; + private final String jobIdToken; + private final String jsonTableRef; + private final WriteDisposition writeDisposition; + private final CreateDisposition createDisposition; + private final PCollectionView> tempTablesView; + + public WriteRename( + BigQueryServices bqServices, + String jobIdToken, + String jsonTableRef, + WriteDisposition writeDisposition, + CreateDisposition createDisposition, + PCollectionView> tempTablesView) { + this.bqServices = bqServices; + this.jobIdToken = jobIdToken; + this.jsonTableRef = jsonTableRef; + this.writeDisposition = writeDisposition; + this.createDisposition = createDisposition; + this.tempTablesView = tempTablesView; } @Override - protected void prepareWrite(WritableByteChannel channel) throws Exception { - out = Channels.newOutputStream(channel); + public void processElement(ProcessContext c) throws Exception { + List tempTablesJson = Lists.newArrayList(c.sideInput(tempTablesView)); + + // Do not copy if no temp tables are provided + if (tempTablesJson.size() == 0) { + return; + } + + List tempTables = Lists.newArrayList(); + for (String table : tempTablesJson) { + tempTables.add(fromJsonString(table, TableReference.class)); + } + copy( + bqServices.getJobService(c.getPipelineOptions().as(BigQueryOptions.class)), + jobIdToken, + fromJsonString(jsonTableRef, TableReference.class), + tempTables, + writeDisposition, + createDisposition); + + DatasetService tableService = + bqServices.getDatasetService(c.getPipelineOptions().as(BigQueryOptions.class)); + removeTemporaryTables(tableService, tempTables); + } + + private void copy( + JobService jobService, + String jobIdPrefix, + TableReference ref, + List tempTables, + WriteDisposition writeDisposition, + CreateDisposition createDisposition) throws InterruptedException, IOException { + JobConfigurationTableCopy copyConfig = new JobConfigurationTableCopy() + .setSourceTables(tempTables) + .setDestinationTable(ref) + .setWriteDisposition(writeDisposition.name()) + .setCreateDisposition(createDisposition.name()); + + String projectId = ref.getProjectId(); + for (int i = 0; i < Bound.MAX_RETRY_JOBS; ++i) { + String jobId = jobIdPrefix + "-" + i; + LOG.info("Starting BigQuery copy job {}: try {}/{}", jobId, i, Bound.MAX_RETRY_JOBS); + JobReference jobRef = new JobReference() + .setProjectId(projectId) + .setJobId(jobId); + jobService.startCopyJob(jobRef, copyConfig); + Status jobStatus = + parseStatus(jobService.pollJob(jobRef, Bound.LOAD_JOB_POLL_MAX_RETRIES)); + switch (jobStatus) { + case SUCCEEDED: + return; + case UNKNOWN: + throw new RuntimeException("Failed to poll the copy job status of job " + jobId); + case FAILED: + LOG.info("BigQuery copy job failed: {}", jobId); + continue; + default: + throw new IllegalStateException(String.format("Unexpected job status: %s of job %s", + jobStatus, jobId)); + } + } + throw new RuntimeException(String.format("Failed to create the copy job %s, reached max " + + "retries: %d", jobIdPrefix, Bound.MAX_RETRY_JOBS)); + } + + static void removeTemporaryTables(DatasetService tableService, + List tempTables) throws Exception { + for (TableReference tableRef : tempTables) { + try { + LOG.debug("Deleting table {}", toJsonString(tableRef)); + tableService.deleteTable( + tableRef.getProjectId(), + tableRef.getDatasetId(), + tableRef.getTableId()); + } catch (Exception e) { + LOG.warn("Failed to delete the table {}", toJsonString(tableRef), e); + } + } } @Override - public void write(TableRow value) throws Exception { - // Use Context.OUTER to encode and NEWLINE as the delimeter. - coder.encode(value, out, Context.OUTER); - out.write(NEWLINE); + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + + builder + .addIfNotNull(DisplayData.item("jobIdToken", jobIdToken) + .withLabel("Job ID Token")) + .addIfNotNull(DisplayData.item("jsonTableRef", jsonTableRef) + .withLabel("Table Reference")) + .add(DisplayData.item("writeDisposition", writeDisposition.toString()) + .withLabel("Write Disposition")) + .add(DisplayData.item("createDisposition", createDisposition.toString()) + .withLabel("Create Disposition")); } } + + /** Disallow construction of utility class. */ + private Write() {} } private static void verifyDatasetPresence(BigQueryOptions options, TableReference table) { @@ -2137,8 +2438,8 @@ public TableReference getOrCreateTable(BigQueryOptions options, String tableSpec TableSchema tableSchema = JSON_FACTORY.fromString(jsonTableSchema, TableSchema.class); Bigquery client = Transport.newBigQueryClient(options).build(); BigQueryTableInserter inserter = new BigQueryTableInserter(client); - inserter.getOrCreateTable(tableReference, WriteDisposition.WRITE_APPEND, - CreateDisposition.CREATE_IF_NEEDED, tableSchema); + inserter.getOrCreateTable(tableReference, Write.WriteDisposition.WRITE_APPEND, + Write.CreateDisposition.CREATE_IF_NEEDED, tableSchema); createdTables.add(tableSpec); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java index 060e7ff7bf..904608e3a0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -20,6 +20,7 @@ import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobConfigurationTableCopy; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.Table; @@ -80,6 +81,12 @@ void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) void startQueryJob(JobReference jobRef, JobConfigurationQuery query) throws IOException, InterruptedException; + /** + * Start a BigQuery copy job. + */ + void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) + throws IOException, InterruptedException; + /** * Waits for the job is Done, and returns the job. * @@ -105,7 +112,7 @@ JobStatistics dryRunQuery(String projectId, String query) /** * An interface to get, create and delete Cloud BigQuery datasets and tables. */ - public interface DatasetService { + interface DatasetService { /** * Gets the specified {@link Table} resource by table ID. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index 2c50aea756..79ad00f0cb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -28,10 +28,12 @@ import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobConfigurationTableCopy; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableDataList; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; @@ -104,9 +106,9 @@ private JobServiceImpl(BigQueryOptions options) { /** * {@inheritDoc} * - *

            the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC . + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. */ @Override public void startLoadJob( @@ -122,9 +124,9 @@ public void startLoadJob( /** * {@inheritDoc} * - *

            the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC . + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. */ @Override public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) @@ -140,9 +142,9 @@ public void startExtractJob(JobReference jobRef, JobConfigurationExtract extract /** * {@inheritDoc} * - *

            the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC . + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. */ @Override public void startQueryJob(JobReference jobRef, JobConfigurationQuery queryConfig) @@ -155,6 +157,24 @@ public void startQueryJob(JobReference jobRef, JobConfigurationQuery queryConfig startJob(job, errorExtractor, client); } + /** + * {@inheritDoc} + * + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + */ + @Override + public void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) + throws IOException, InterruptedException { + Job job = new Job() + .setJobReference(jobRef) + .setConfiguration( + new JobConfiguration().setCopy(copyConfig)); + + startJob(job, errorExtractor, client); + } + private static void startJob(Job job, ApiErrorExtractor errorExtractor, Bigquery client) throws IOException, InterruptedException { @@ -310,9 +330,9 @@ private DatasetServiceImpl(BigQueryOptions bqOptions) { /** * {@inheritDoc} * - *

            the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC . + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. */ @Override public Table getTable(String projectId, String datasetId, String tableId) @@ -331,9 +351,9 @@ public Table getTable(String projectId, String datasetId, String tableId) /** * {@inheritDoc} * - *

            the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC . + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. */ @Override public void deleteTable(String projectId, String datasetId, String tableId) @@ -349,12 +369,46 @@ public void deleteTable(String projectId, String datasetId, String tableId) backoff); } + public boolean isTableEmpty(String projectId, String datasetId, String tableId) + throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + TableDataList dataList = executeWithRetries( + client.tabledata().list(projectId, datasetId, tableId), + String.format( + "Unable to list table data: %s, aborting after %d retries.", + tableId, MAX_RPC_ATTEMPTS), + Sleeper.DEFAULT, + backoff); + return dataList.getRows() == null || dataList.getRows().isEmpty(); + } + + /** + * {@inheritDoc} + * + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + * + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + */ + public Dataset getDataset(String projectId, String datasetId) + throws IOException, InterruptedException { + BackOff backoff = + new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + return executeWithRetries( + client.datasets().get(projectId, datasetId), + String.format( + "Unable to get dataset: %s, aborting after %d retries.", + datasetId, MAX_RPC_ATTEMPTS), + Sleeper.DEFAULT, + backoff); + } + /** * {@inheritDoc} * - *

            the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC . + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. */ @Override public void createDataset( @@ -410,9 +464,9 @@ void createDataset( /** * {@inheritDoc} * - *

            the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * - * @throws IOException if it exceeds max RPC . + * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. */ @Override public void deleteDataset(String projectId, String datasetId) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 2ca6f43e61..c2e5ffb64f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -20,13 +20,15 @@ import static com.google.cloud.dataflow.sdk.io.BigQueryIO.toJsonString; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.common.base.Preconditions.checkArgument; - import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import com.google.api.client.util.Data; @@ -35,6 +37,7 @@ import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; +import com.google.api.services.bigquery.model.JobConfigurationTableCopy; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobStatistics2; @@ -47,8 +50,10 @@ import com.google.api.services.bigquery.model.TableSchema; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryQuerySource; import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryTableSource; import com.google.cloud.dataflow.sdk.io.BigQueryIO.PassThroughThenCleanup; @@ -56,7 +61,11 @@ import com.google.cloud.dataflow.sdk.io.BigQueryIO.Status; import com.google.cloud.dataflow.sdk.io.BigQueryIO.TransformingSource; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.TableRowWriter; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WritePartition; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteRename; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteTables; import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; @@ -69,6 +78,7 @@ import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; @@ -81,7 +91,12 @@ import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.cloud.dataflow.sdk.util.PCollectionViews; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.TupleTag; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -106,6 +121,9 @@ import java.io.FileFilter; import java.io.IOException; import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; @@ -284,6 +302,12 @@ public void startQueryJob(JobReference jobRef, JobConfigurationQuery query) startJob(jobRef); } + @Override + public void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) + throws IOException, InterruptedException { + startJob(jobRef); + } + @Override public Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException { @@ -370,9 +394,10 @@ public Job getJob(JobReference jobRef) throws InterruptedException { @Rule public transient ExpectedException thrown = ExpectedException.none(); @Rule public transient ExpectedLogs logged = ExpectedLogs.none(BigQueryIO.class); @Rule public transient TemporaryFolder testFolder = new TemporaryFolder(); - @Mock public transient BigQueryServices.JobService mockJobService; + @Mock(extraInterfaces = Serializable.class) + public transient BigQueryServices.JobService mockJobService; @Mock private transient IOChannelFactory mockIOChannelFactory; - @Mock private transient DatasetService mockDatasetService; + @Mock(extraInterfaces = Serializable.class) private transient DatasetService mockDatasetService; private void checkReadTableObject( BigQueryIO.Read.Bound bound, String project, String dataset, String table) { @@ -584,7 +609,7 @@ public void processElement(ProcessContext c) throws Exception { } @Test - public void testCustomSink() throws Exception { + public void testWrite() throws Exception { BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); bqOptions.setProject("defaultProject"); bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); @@ -611,17 +636,17 @@ public void testCustomSink() throws Exception { p.run(); logged.verifyInfo("Starting BigQuery load job"); - logged.verifyInfo("Previous load jobs failed, retrying."); + logged.verifyInfo("BigQuery load job failed"); + logged.verifyInfo("try 0/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + logged.verifyInfo("try 1/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + logged.verifyInfo("try 2/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + logged.verifyNotLogged("try 3/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); File tempDir = new File(bqOptions.getTempLocation()); - assertEquals(0, tempDir.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isFile(); - }}).length); + testNumFiles(tempDir, 0); } @Test - public void testCustomSinkUnknown() throws Exception { + public void testWriteUnknown() throws Exception { BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); bqOptions.setProject("defaultProject"); bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); @@ -643,15 +668,11 @@ public void testCustomSinkUnknown() throws Exception { .withoutValidation()); thrown.expect(RuntimeException.class); - thrown.expectMessage("Failed to poll the load job status."); + thrown.expectMessage("Failed to poll the load job status"); p.run(); File tempDir = new File(bqOptions.getTempLocation()); - assertEquals(0, tempDir.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isFile(); - }}).length); + testNumFiles(tempDir, 0); } @Test @@ -697,7 +718,7 @@ public void testQuerySourcePrimitiveDisplayData() { } @Test - public void testBuildSink() { + public void testBuildWrite() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("foo.com:project:somedataset.sometable"); checkWriteObject( @@ -706,7 +727,7 @@ public void testBuildSink() { } @Test - public void testBuildSinkwithoutValidation() { + public void testBuildWritewithoutValidation() { // This test just checks that using withoutValidation will not trigger object // construction errors. BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") @@ -717,7 +738,7 @@ public void testBuildSinkwithoutValidation() { } @Test - public void testBuildSinkDefaultProject() { + public void testBuildWriteDefaultProject() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("somedataset.sometable"); checkWriteObject( @@ -726,7 +747,7 @@ public void testBuildSinkDefaultProject() { } @Test - public void testBuildSinkWithTableReference() { + public void testBuildWriteWithTableReference() { TableReference table = new TableReference() .setProjectId("foo.com:project") .setDatasetId("somedataset") @@ -740,7 +761,7 @@ public void testBuildSinkWithTableReference() { @Test @Category(RunnableOnService.class) - public void testBuildSinkWithoutTable() { + public void testBuildWriteWithoutTable() { Pipeline p = TestPipeline.create(); thrown.expect(IllegalStateException.class); thrown.expectMessage("must set the table reference"); @@ -749,7 +770,7 @@ public void testBuildSinkWithoutTable() { } @Test - public void testBuildSinkWithSchema() { + public void testBuildWriteWithSchema() { TableSchema schema = new TableSchema(); BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("foo.com:project:somedataset.sometable").withSchema(schema); @@ -759,7 +780,7 @@ public void testBuildSinkWithSchema() { } @Test - public void testBuildSinkWithCreateDispositionNever() { + public void testBuildWriteWithCreateDispositionNever() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("foo.com:project:somedataset.sometable") .withCreateDisposition(CreateDisposition.CREATE_NEVER); @@ -769,7 +790,7 @@ public void testBuildSinkWithCreateDispositionNever() { } @Test - public void testBuildSinkWithCreateDispositionIfNeeded() { + public void testBuildWriteWithCreateDispositionIfNeeded() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("foo.com:project:somedataset.sometable") .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED); @@ -779,7 +800,7 @@ public void testBuildSinkWithCreateDispositionIfNeeded() { } @Test - public void testBuildSinkWithWriteDispositionTruncate() { + public void testBuildWriteWithWriteDispositionTruncate() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("foo.com:project:somedataset.sometable") .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE); @@ -789,7 +810,7 @@ public void testBuildSinkWithWriteDispositionTruncate() { } @Test - public void testBuildSinkWithWriteDispositionAppend() { + public void testBuildWriteWithWriteDispositionAppend() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("foo.com:project:somedataset.sometable") .withWriteDisposition(WriteDisposition.WRITE_APPEND); @@ -799,7 +820,7 @@ public void testBuildSinkWithWriteDispositionAppend() { } @Test - public void testBuildSinkWithWriteDispositionEmpty() { + public void testBuildWriteWithWriteDispositionEmpty() { BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") .to("foo.com:project:somedataset.sometable") .withWriteDisposition(WriteDisposition.WRITE_EMPTY); @@ -809,7 +830,7 @@ public void testBuildSinkWithWriteDispositionEmpty() { } @Test - public void testBuildSinkDisplayData() { + public void testBuildWriteDisplayData() { String tableSpec = "project:dataset.table"; TableSchema schema = new TableSchema().set("col1", "type1").set("col2", "type2"); @@ -832,20 +853,20 @@ public void testBuildSinkDisplayData() { } @Test - public void testBatchSinkPrimitiveDisplayData() { + public void testBatchWritePrimitiveDisplayData() { DataflowPipelineOptions options = DataflowDisplayDataEvaluator.getDefaultOptions(); options.setStreaming(false); - testSinkPrimitiveDisplayData(options); + testWritePrimitiveDisplayData(options); } @Test - public void testStreamingSinkPrimitiveDisplayData() { + public void testStreamingWritePrimitiveDisplayData() { DataflowPipelineOptions options = DataflowDisplayDataEvaluator.getDefaultOptions(); options.setStreaming(true); - testSinkPrimitiveDisplayData(options); + testWritePrimitiveDisplayData(options); } - private void testSinkPrimitiveDisplayData(DataflowPipelineOptions options) { + private void testWritePrimitiveDisplayData(DataflowPipelineOptions options) { DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(options); BigQueryIO.Write.Bound write = BigQueryIO.Write @@ -1266,4 +1287,260 @@ void cleanup(PipelineOptions options) throws Exception { p.run(); } + + @Test + public void testWritePartitionEmptyData() throws Exception { + long numFiles = 0; + long fileSize = 0; + + // An empty file is created for no input data. One partition is needed. + long expectedNumPartitions = 1; + testWritePartition(numFiles, fileSize, expectedNumPartitions); + } + + @Test + public void testWritePartitionSinglePartition() throws Exception { + long numFiles = BigQueryIO.Write.Bound.MAX_NUM_FILES; + long fileSize = 1; + + // One partition is needed. + long expectedNumPartitions = 1; + testWritePartition(numFiles, fileSize, expectedNumPartitions); + } + + @Test + public void testWritePartitionManyFiles() throws Exception { + long numFiles = BigQueryIO.Write.Bound.MAX_NUM_FILES * 3; + long fileSize = 1; + + // One partition is needed for each group of BigQueryWrite.MAX_NUM_FILES files. + long expectedNumPartitions = 3; + testWritePartition(numFiles, fileSize, expectedNumPartitions); + } + + @Test + public void testWritePartitionLargeFileSize() throws Exception { + long numFiles = 10; + long fileSize = BigQueryIO.Write.Bound.MAX_SIZE_BYTES / 3; + + // One partition is needed for each group of three files. + long expectedNumPartitions = 4; + testWritePartition(numFiles, fileSize, expectedNumPartitions); + } + + private void testWritePartition(long numFiles, long fileSize, long expectedNumPartitions) + throws Exception { + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); + + List expectedPartitionIds = Lists.newArrayList(); + for (long i = 1; i <= expectedNumPartitions; ++i) { + expectedPartitionIds.add(i); + } + + List> files = Lists.newArrayList(); + List fileNames = Lists.newArrayList(); + for (int i = 0; i < numFiles; ++i) { + String fileName = String.format("files%05d", i); + fileNames.add(fileName); + files.add(KV.of(fileName, fileSize)); + } + + TupleTag>> multiPartitionsTag = + new TupleTag>>("multiPartitionsTag") {}; + TupleTag>> singlePartitionTag = + new TupleTag>>("singlePartitionTag") {}; + + PCollectionView>> filesView = PCollectionViews.iterableView( + TestPipeline.create(), + WindowingStrategy.globalDefault(), + KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); + + WritePartition writePartition = + new WritePartition(filesView, multiPartitionsTag, singlePartitionTag); + + DoFnTester>> tester = DoFnTester.of(writePartition); + tester.setSideInputInGlobalWindow(filesView, files); + tester.processElement(bqOptions.getTempLocation()); + + List>> partitions; + if (expectedNumPartitions > 1) { + partitions = tester.takeSideOutputElements(multiPartitionsTag); + } else { + partitions = tester.takeSideOutputElements(singlePartitionTag); + } + List partitionIds = Lists.newArrayList(); + List partitionFileNames = Lists.newArrayList(); + for (KV> partition : partitions) { + partitionIds.add(partition.getKey()); + for (String name : partition.getValue()) { + partitionFileNames.add(name); + } + } + + assertEquals(expectedPartitionIds, partitionIds); + if (numFiles == 0) { + assertThat(partitionFileNames, Matchers.hasSize(1)); + assertTrue(Files.exists(Paths.get(partitionFileNames.get(0)))); + assertThat(Files.readAllBytes(Paths.get(partitionFileNames.get(0))).length, + Matchers.equalTo(0)); + } else { + assertEquals(fileNames, partitionFileNames); + } + } + + @Test + public void testWriteTables() throws Exception { + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .withJobService(new FakeJobService() + .startJobReturns("done", "done", "done", "done") + .pollJobReturns(Status.FAILED, Status.SUCCEEDED, Status.SUCCEEDED, Status.SUCCEEDED)); + + long numPartitions = 3; + long numFilesPerPartition = 10; + String jobIdToken = "jobIdToken"; + String tempFilePrefix = "tempFilePrefix"; + String jsonTable = "{}"; + String jsonSchema = "{}"; + List expectedTempTables = Lists.newArrayList(); + + List>>> partitions = Lists.newArrayList(); + for (long i = 0; i < numPartitions; ++i) { + List filesPerPartition = Lists.newArrayList(); + for (int j = 0; j < numFilesPerPartition; ++j) { + filesPerPartition.add(String.format("files%05d", j)); + } + partitions.add(KV.of(i, (Iterable>) Collections.singleton(filesPerPartition))); + expectedTempTables.add(String.format("{\"tableId\":\"%s_%05d\"}", jobIdToken, i)); + } + + WriteTables writeTables = new WriteTables( + false, + fakeBqServices, + jobIdToken, + tempFilePrefix, + jsonTable, + jsonSchema, + WriteDisposition.WRITE_EMPTY, + CreateDisposition.CREATE_IF_NEEDED); + + DoFnTester>>, String> tester = DoFnTester.of(writeTables); + for (KV>> partition : partitions) { + tester.processElement(partition); + } + + List tempTables = tester.takeOutputElements(); + + logged.verifyInfo("Starting BigQuery load job"); + logged.verifyInfo("BigQuery load job failed"); + logged.verifyInfo("try 0/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + logged.verifyInfo("try 1/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + logged.verifyNotLogged("try 2/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + + assertEquals(expectedTempTables, tempTables); + } + + @Test + public void testRemoveTemporaryFiles() throws Exception { + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("defaultProject"); + bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); + + int numFiles = 10; + List fileNames = Lists.newArrayList(); + String tempFilePrefix = bqOptions.getTempLocation() + "/"; + TableRowWriter writer = new TableRowWriter(tempFilePrefix); + for (int i = 0; i < numFiles; ++i) { + String fileName = String.format("files%05d", i); + writer.open(fileName); + fileNames.add(writer.close().getKey()); + } + fileNames.add(tempFilePrefix + String.format("files%05d", numFiles)); + + File tempDir = new File(bqOptions.getTempLocation()); + testNumFiles(tempDir, 10); + + WriteTables.removeTemporaryFiles(bqOptions, tempFilePrefix, fileNames); + + testNumFiles(tempDir, 0); + + for (String fileName : fileNames) { + logged.verifyDebug("Removing file " + fileName); + } + logged.verifyDebug(fileNames.get(numFiles) + " does not exist."); + } + + @Test + public void testWriteRename() throws Exception { + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .withJobService(new FakeJobService() + .startJobReturns("done", "done") + .pollJobReturns(Status.FAILED, Status.SUCCEEDED)) + .withDatasetService(mockDatasetService); + + long numTempTables = 3; + String jobIdToken = "jobIdToken"; + String jsonTable = "{}"; + List tempTables = Lists.newArrayList(); + for (long i = 0; i < numTempTables; ++i) { + tempTables.add(String.format("{\"tableId\":\"%s_%05d\"}", jobIdToken, i)); + } + + PCollectionView> tempTablesView = PCollectionViews.iterableView( + TestPipeline.create(), + WindowingStrategy.globalDefault(), + StringUtf8Coder.of()); + + WriteRename writeRename = new WriteRename( + fakeBqServices, + jobIdToken, + jsonTable, + WriteDisposition.WRITE_EMPTY, + CreateDisposition.CREATE_IF_NEEDED, + tempTablesView); + + DoFnTester tester = DoFnTester.of(writeRename); + tester.setSideInputInGlobalWindow(tempTablesView, tempTables); + tester.processElement(null); + + logged.verifyInfo("Starting BigQuery copy job"); + logged.verifyInfo("BigQuery copy job failed"); + logged.verifyInfo("try 0/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + logged.verifyInfo("try 1/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + logged.verifyNotLogged("try 2/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); + } + + @Test + public void testRemoveTemporaryTables() throws Exception { + String projectId = "someproject"; + String datasetId = "somedataset"; + List tables = Lists.newArrayList("table1", "table2", "table3"); + List tableRefs = Lists.newArrayList( + BigQueryIO.parseTableSpec(String.format("%s:%s.%s", projectId, datasetId, tables.get(0))), + BigQueryIO.parseTableSpec(String.format("%s:%s.%s", projectId, datasetId, tables.get(1))), + BigQueryIO.parseTableSpec(String.format("%s:%s.%s", projectId, datasetId, tables.get(2)))); + + doThrow(new IOException("Unable to delete table")) + .when(mockDatasetService).deleteTable(projectId, datasetId, tables.get(0)); + doNothing().when(mockDatasetService).deleteTable(projectId, datasetId, tables.get(1)); + doNothing().when(mockDatasetService).deleteTable(projectId, datasetId, tables.get(2)); + + WriteRename.removeTemporaryTables(mockDatasetService, tableRefs); + + for (TableReference ref : tableRefs) { + logged.verifyDebug("Deleting table " + toJsonString(ref)); + } + logged.verifyWarn("Failed to delete the table " + toJsonString(tableRefs.get(0))); + logged.verifyNotLogged("Failed to delete the table " + toJsonString(tableRefs.get(1))); + logged.verifyNotLogged("Failed to delete the table " + toJsonString(tableRefs.get(2))); + } + + private static void testNumFiles(File tempDir, int expectedNumFiles) { + assertEquals(expectedNumFiles, tempDir.listFiles(new FileFilter() { + @Override + public boolean accept(File pathname) { + return pathname.isFile(); + }}).length); + } } From 94b679e01eeda90ec515e7215b62762470ba2df9 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 14 Jun 2016 14:03:41 -0700 Subject: [PATCH 524/751] Write: add support for setting a fixed number of shards And remove special support in Dataflow and Direct runners for it. --- .../google/cloud/dataflow/sdk/io/AvroIO.java | 12 +- .../google/cloud/dataflow/sdk/io/TextIO.java | 13 +- .../google/cloud/dataflow/sdk/io/Write.java | 304 ++++++++++++++---- .../sdk/runners/DataflowPipelineRunner.java | 259 +-------------- .../inprocess/AvroIOShardedWriteFactory.java | 74 ----- .../inprocess/InProcessPipelineRunner.java | 4 - .../inprocess/ShardControlledWrite.java | 79 ----- .../inprocess/TextIOShardedWriteFactory.java | 76 ----- .../cloud/dataflow/sdk/io/WriteTest.java | 141 +++++++- .../AvroIOShardedWriteFactoryTest.java | 110 ------- .../TextIOShardedWriteFactoryTest.java | 110 ------- 11 files changed, 386 insertions(+), 796 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java index 0ef2e07d85..bca7a80a5e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java @@ -680,14 +680,14 @@ public PDone apply(PCollection input) { throw new IllegalStateException("need to set the schema of an AvroIO.Write transform"); } - // Note that custom sinks currently do not expose sharding controls. - // Thus pipeline runner writers need to individually add support internally to - // apply user requested sharding limits. - return input.apply( - "Write", + com.google.cloud.dataflow.sdk.io.Write.Bound write = com.google.cloud.dataflow.sdk.io.Write.to( new AvroSink<>( - filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema)))); + filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema))); + if (getNumShards() > 0) { + write = write.withNumShards(getNumShards()); + } + return input.apply("Write", write); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index bb894faf8c..92934a91c9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -639,12 +639,13 @@ public PDone apply(PCollection input) { "need to set the filename prefix of a TextIO.Write transform"); } - // Note that custom sinks currently do not expose sharding controls. - // Thus pipeline runner writers need to individually add support internally to - // apply user requested sharding limits. - return input.apply("Write", com.google.cloud.dataflow.sdk.io.Write.to( - new TextSink<>( - filenamePrefix, filenameSuffix, shardTemplate, coder))); + com.google.cloud.dataflow.sdk.io.Write.Bound write = + com.google.cloud.dataflow.sdk.io.Write.to( + new TextSink<>(filenamePrefix, filenameSuffix, shardTemplate, coder)); + if (getNumShards() > 0) { + write = write.withNumShards(getNumShards()); + } + return input.apply("Write", write); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java index 62d0cf639a..8c537944fa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java @@ -11,9 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.client.util.Lists; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -23,12 +25,17 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; @@ -36,40 +43,60 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; /** * A {@link PTransform} that writes to a {@link Sink}. A write begins with a sequential global * initialization of a sink, followed by a parallel write, and ends with a sequential finalization - * of the write. The output of a write is {@link PDone}. In the case of an empty PCollection, only - * the global initialization and finalization will be performed. + * of the write. The output of a write is {@link PDone}. + * + *

            By default, every bundle in the input {@link PCollection} will be processed by a + * {@link WriteOperation}, so the number of outputs will vary based on runner behavior, though at + * least 1 output will always be produced. The exact parallelism of the write stage can be + * controlled using {@link Write.Bound#withNumShards}, typically used to control how many files are + * produced or to globally limit the number of workers connecting to an external service. However, + * this option can often hurt performance: it adds an additional {@link GroupByKey} to the pipeline. + * + *

            {@code Write} re-windows the data into the global window, so it is typically not well suited + * to use in streaming pipelines. * - *

            Currently, only batch workflows can contain Write transforms. + *

            Example usage with runner-controlled sharding: * - *

            Example usage: + *

            {@code p.apply(Write.to(new MySink(...)));}
            + + *

            Example usage with a fixed number of shards: * - *

            {@code p.apply(Write.to(new MySink(...)));} + *

            {@code p.apply(Write.to(new MySink(...)).withNumShards(3));}
            */ @Experimental(Experimental.Kind.SOURCE_SINK) public class Write { private static final Logger LOG = LoggerFactory.getLogger(Write.class); /** - * Creates a Write transform that writes to the given Sink. + * Creates a {@link Write} transform that writes to the given {@link Sink}, letting the runner + * control how many different shards are produced. */ public static Bound to(Sink sink) { - return new Bound<>(sink); + checkNotNull(sink, "sink"); + return new Bound<>(sink, 0 /* runner-controlled sharding */); } /** - * A {@link PTransform} that writes to a {@link Sink}. See {@link Write} and {@link Sink} for - * documentation about writing to Sinks. + * A {@link PTransform} that writes to a {@link Sink}. See the class-level Javadoc for more + * information. + * + * @see Write + * @see Sink */ public static class Bound extends PTransform, PDone> { private final Sink sink; + private int numShards; - private Bound(Sink sink) { + private Bound(Sink sink, int numShards) { this.sink = sink; + this.numShards = numShards; } @Override @@ -83,9 +110,20 @@ public PDone apply(PCollection input) { public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder - .add(DisplayData.item("sink", sink.getClass()) - .withLabel("Write Sink")) - .include(sink); + .add(DisplayData.item("sink", sink.getClass()).withLabel("Write Sink")) + .include(sink) + .addIfNotDefault( + DisplayData.item("numShards", getNumShards()).withLabel("Fixed Number of Shards"), + 0); + } + + /** + * Returns the number of shards that will be produced in the output. + * + * @see Write for more information + */ + public int getNumShards() { + return numShards; } /** @@ -95,6 +133,153 @@ public Sink getSink() { return sink; } + /** + * Returns a new {@link Write.Bound} that will write to the current {@link Sink} using the + * specified number of shards. + * + *

            This option should be used sparingly as it can hurt performance. See {@link Write} for + * more information. + * + *

            A value less than or equal to 0 will be equivalent to the default behavior of + * runner-controlled sharding. + */ + public Bound withNumShards(int numShards) { + return new Bound<>(sink, Math.max(numShards, 0)); + } + + /** + * Writes all the elements in a bundle using a {@link Writer} produced by the + * {@link WriteOperation} associated with the {@link Sink}. + */ + private class WriteBundles extends DoFn { + // Writer that will write the records in this bundle. Lazily + // initialized in processElement. + private Writer writer = null; + private final PCollectionView> writeOperationView; + + WriteBundles(PCollectionView> writeOperationView) { + this.writeOperationView = writeOperationView; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + // Lazily initialize the Writer + if (writer == null) { + WriteOperation writeOperation = c.sideInput(writeOperationView); + LOG.info("Opening writer for write operation {}", writeOperation); + writer = writeOperation.createWriter(c.getPipelineOptions()); + writer.open(UUID.randomUUID().toString()); + LOG.debug("Done opening writer {} for operation {}", writer, writeOperationView); + } + try { + writer.write(c.element()); + } catch (Exception e) { + // Discard write result and close the write. + try { + writer.close(); + // The writer does not need to be reset, as this DoFn cannot be reused. + } catch (Exception closeException) { + if (closeException instanceof InterruptedException) { + // Do not silently ignore interrupted state. + Thread.currentThread().interrupt(); + } + // Do not mask the exception that caused the write to fail. + e.addSuppressed(closeException); + } + throw e; + } + } + + @Override + public void finishBundle(Context c) throws Exception { + if (writer != null) { + WriteT result = writer.close(); + c.output(result); + // Reset state in case of reuse. + writer = null; + } + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Write.Bound.this.populateDisplayData(builder); + } + } + + /** + * Like {@link WriteBundles}, but where the elements for each shard have been collected into + * a single iterable. + * + * @see WriteBundles + */ + private class WriteShardedBundles extends DoFn>, WriteT> { + private final PCollectionView> writeOperationView; + + WriteShardedBundles(PCollectionView> writeOperationView) { + this.writeOperationView = writeOperationView; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + // In a sharded write, single input element represents one shard. We can open and close + // the writer in each call to processElement. + WriteOperation writeOperation = c.sideInput(writeOperationView); + LOG.info("Opening writer for write operation {}", writeOperation); + Writer writer = writeOperation.createWriter(c.getPipelineOptions()); + writer.open(UUID.randomUUID().toString()); + LOG.debug("Done opening writer {} for operation {}", writer, writeOperationView); + + try { + for (T t : c.element().getValue()) { + writer.write(t); + } + } catch (Exception e) { + try { + writer.close(); + } catch (Exception closeException) { + if (closeException instanceof InterruptedException) { + // Do not silently ignore interrupted state. + Thread.currentThread().interrupt(); + } + // Do not mask the exception that caused the write to fail. + e.addSuppressed(closeException); + } + throw e; + } + + // Close the writer; if this throws let the error propagate. + WriteT result = writer.close(); + c.output(result); + } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Write.Bound.this.populateDisplayData(builder); + } + } + + private static class ApplyShardingKey implements SerializableFunction { + private final int numShards; + private int shardNumber; + + ApplyShardingKey(int numShards) { + this.numShards = numShards; + shardNumber = -1; + } + + @Override + public Integer apply(T input) { + if (shardNumber == -1) { + // We want to desynchronize the first record sharding key for each instance of + // ApplyShardingKey, so records in a small PCollection will be statistically balanced. + shardNumber = ThreadLocalRandom.current().nextInt(numShards); + } else { + shardNumber = (shardNumber + 1) % numShards; + } + return shardNumber; + } + } + /** * A write is performed as sequence of three {@link ParDo}'s. * @@ -138,7 +323,7 @@ private PDone createWrite( // A singleton collection of the WriteOperation, to be used as input to a ParDo to initialize // the sink. PCollection> operationCollection = - p.apply(Create.>of(writeOperation).withCoder(operationCoder)); + p.apply(Create.of(writeOperation).withCoder(operationCoder)); // Initialize the resource in a do-once ParDo on the WriteOperation. operationCollection = operationCollection @@ -161,54 +346,32 @@ public void processElement(ProcessContext c) throws Exception { final PCollectionView> writeOperationView = operationCollection.apply(View.>asSingleton()); + // Re-window the data into the global window and remove any existing triggers. + PCollection inputInGlobalWindow = + input.apply( + Window.into(new GlobalWindows()) + .triggering(DefaultTrigger.of()) + .discardingFiredPanes()); + // Perform the per-bundle writes as a ParDo on the input PCollection (with the WriteOperation // as a side input) and collect the results of the writes in a PCollection. // There is a dependency between this ParDo and the first (the WriteOperation PCollection // as a side input), so this will happen after the initial ParDo. - PCollection results = input - .apply(Window.into(new GlobalWindows())) - .apply("WriteBundles", ParDo.of(new DoFn() { - // Writer that will write the records in this bundle. Lazily - // initialized in processElement. - private Writer writer = null; - - @Override - public void processElement(ProcessContext c) throws Exception { - // Lazily initialize the Writer - if (writer == null) { - WriteOperation writeOperation = c.sideInput(writeOperationView); - LOG.info("Opening writer for write operation {}", writeOperation); - writer = writeOperation.createWriter(c.getPipelineOptions()); - writer.open(UUID.randomUUID().toString()); - LOG.debug("Done opening writer {} for operation {}", writer, writeOperationView); - } - try { - writer.write(c.element()); - } catch (Exception e) { - // Discard write result and close the write. - try { - writer.close(); - } catch (Exception closeException) { - // Do not mask the exception that caused the write to fail. - } - throw e; - } - } - - @Override - public void finishBundle(Context c) throws Exception { - if (writer != null) { - WriteT result = writer.close(); - c.output(result); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - Write.Bound.this.populateDisplayData(builder); - } - }).withSideInputs(writeOperationView)) - .setCoder(writeOperation.getWriterResultCoder()); + PCollection results; + if (getNumShards() <= 0) { + results = inputInGlobalWindow + .apply("WriteBundles", + ParDo.of(new WriteBundles<>(writeOperationView)) + .withSideInputs(writeOperationView)); + } else { + results = inputInGlobalWindow + .apply("ApplyShardLabel", WithKeys.of(new ApplyShardingKey(getNumShards()))) + .apply("GroupIntoShards", GroupByKey.create()) + .apply("WriteShardedBundles", + ParDo.of(new WriteShardedBundles<>(writeOperationView)) + .withSideInputs(writeOperationView)); + } + results.setCoder(writeOperation.getWriterResultCoder()); final PCollectionView> resultsView = results.apply(View.asIterable()); @@ -224,9 +387,26 @@ public void populateDisplayData(DisplayData.Builder builder) { @Override public void processElement(ProcessContext c) throws Exception { WriteOperation writeOperation = c.element(); - LOG.info("Finalizing write operation {}", writeOperation); - Iterable results = c.sideInput(resultsView); - LOG.debug("Side input initialized to finalize write operation {}", writeOperation); + LOG.info("Finalizing write operation {}.", writeOperation); + List results = Lists.newArrayList(c.sideInput(resultsView)); + LOG.debug("Side input initialized to finalize write operation {}.", writeOperation); + + // We must always output at least 1 shard, and honor user-specified numShards if set. + int minShardsNeeded = Math.max(1, getNumShards()); + int extraShardsNeeded = minShardsNeeded - results.size(); + if (extraShardsNeeded > 0) { + LOG.info( + "Creating {} empty output shards in addition to {} written for a total of {}.", + extraShardsNeeded, results.size(), minShardsNeeded); + for (int i = 0; i < extraShardsNeeded; ++i) { + Writer writer = writeOperation.createWriter(c.getPipelineOptions()); + writer.open(UUID.randomUUID().toString()); + WriteT emptyWrite = writer.close(); + results.add(emptyWrite); + } + LOG.debug("Done creating extra shards."); + } + writeOperation.finalize(results, c.getPipelineOptions()); LOG.debug("Done finalizing write operation {}", writeOperation); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f2030e5f38..1df6fa0380 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -39,7 +39,6 @@ import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; import com.google.cloud.dataflow.sdk.PipelineResult.State; import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -65,7 +64,6 @@ import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSink; import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource; import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.io.Write; @@ -102,7 +100,6 @@ import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; @@ -181,6 +178,7 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; + import javax.annotation.Nullable; /** @@ -378,8 +376,6 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(Read.Unbounded.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); builder.put(Write.Bound.class, BatchWrite.class); - builder.put(AvroIO.Write.Bound.class, BatchAvroIOWrite.class); - builder.put(TextIO.Write.Bound.class, BatchTextIOWrite.class); // In batch mode must use the custom Pubsub bounded source/sink. builder.put(PubsubUnboundedSource.class, UnsupportedIO.class); builder.put(PubsubUnboundedSink.class, UnsupportedIO.class); @@ -2074,52 +2070,6 @@ public Iterable apply(Iterable> input) { } } - /** - * A {@link PTransform} that uses shuffle to create a fusion break. This allows pushing - * parallelism limits such as sharding controls further down the pipeline. - */ - private static class ReshardForWrite extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection input) { - return input - // TODO: This would need to be adapted to write per-window shards. - .apply( - Window.into(new GlobalWindows()) - .triggering(DefaultTrigger.of()) - .discardingFiredPanes()) - .apply( - "RandomKey", - ParDo.of( - new DoFn>() { - transient long counter, step; - - @Override - public void startBundle(Context c) { - counter = (long) (Math.random() * Long.MAX_VALUE); - step = 1 + 2 * (long) (Math.random() * Long.MAX_VALUE); - } - - @Override - public void processElement(ProcessContext c) { - counter += step; - c.output(KV.of(counter, c.element())); - } - })) - .apply(GroupByKey.create()) - .apply( - "Ungroup", - ParDo.of( - new DoFn>, T>() { - @Override - public void processElement(ProcessContext c) { - for (T item : c.element().getValue()) { - c.output(item); - } - } - })); - } - } - /** * Specialized implementation which overrides * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} to provide Google @@ -2341,213 +2291,6 @@ private void translateWriteHelper( } } - /** - * Specialized implementation which overrides - * {@link com.google.cloud.dataflow.sdk.io.TextIO.Write.Bound TextIO.Write.Bound} with - * a native sink instead of a custom sink as workaround until custom sinks - * have support for sharding controls. - */ - private static class BatchTextIOWrite extends PTransform, PDone> { - private final TextIO.Write.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchTextIOWrite(DataflowPipelineRunner runner, TextIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - if (transform.getNumShards() > 0) { - return input - .apply(new ReshardForWrite()) - .apply(new BatchTextIONativeWrite<>(transform)); - } else { - return transform.apply(input); - } - } - } - - /** - * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way - * to provide the native definition of the Text sink. - */ - private static class BatchTextIONativeWrite extends PTransform, PDone> { - private final TextIO.Write.Bound transform; - public BatchTextIONativeWrite(TextIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - return PDone.in(input.getPipeline()); - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - BatchTextIONativeWrite.class, new BatchTextIONativeWriteTranslator()); - } - } - - /** - * TextIO.Write.Bound support code for the Dataflow backend when applying parallelism limits - * through user requested sharding limits. - */ - private static class BatchTextIONativeWriteTranslator - implements TransformTranslator> { - @SuppressWarnings("unchecked") - @Override - public void translate(@SuppressWarnings("rawtypes") BatchTextIONativeWrite transform, - TranslationContext context) { - translateWriteHelper(transform, transform.transform, context); - } - - private void translateWriteHelper( - BatchTextIONativeWrite transform, - TextIO.Write.Bound originalTransform, - TranslationContext context) { - // Note that the original transform can not be used during add step/add input - // and is only passed in to get properties from it. - - checkState(originalTransform.getNumShards() > 0, - "Native TextSink is expected to only be used when sharding controls are required."); - - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (originalTransform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(originalTransform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + originalTransform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - // TODO: How do we want to specify format and - // format-specific properties? - context.addInput(PropertyNames.FORMAT, "text"); - context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, - originalTransform.getShardNameTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); - context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); - context.addEncodingInput( - WindowedValue.getValueOnlyCoder(originalTransform.getCoder())); - - } - } - - /** - * Specialized implementation which overrides - * {@link com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound AvroIO.Write.Bound} with - * a native sink instead of a custom sink as workaround until custom sinks - * have support for sharding controls. - */ - private static class BatchAvroIOWrite extends PTransform, PDone> { - private final AvroIO.Write.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchAvroIOWrite(DataflowPipelineRunner runner, AvroIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - if (transform.getNumShards() > 0) { - return input - .apply(new ReshardForWrite()) - .apply(new BatchAvroIONativeWrite<>(transform)); - } else { - return transform.apply(input); - } - } - } - - /** - * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way - * to provide the native definition of the Avro sink. - */ - private static class BatchAvroIONativeWrite extends PTransform, PDone> { - private final AvroIO.Write.Bound transform; - public BatchAvroIONativeWrite(AvroIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - return PDone.in(input.getPipeline()); - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - BatchAvroIONativeWrite.class, new BatchAvroIONativeWriteTranslator()); - } - } - - /** - * AvroIO.Write.Bound support code for the Dataflow backend when applying parallelism limits - * through user requested sharding limits. - */ - private static class BatchAvroIONativeWriteTranslator - implements TransformTranslator> { - @SuppressWarnings("unchecked") - @Override - public void translate(@SuppressWarnings("rawtypes") BatchAvroIONativeWrite transform, - TranslationContext context) { - translateWriteHelper(transform, transform.transform, context); - } - - private void translateWriteHelper( - BatchAvroIONativeWrite transform, - AvroIO.Write.Bound originalTransform, - TranslationContext context) { - // Note that the original transform can not be used during add step/add input - // and is only passed in to get properties from it. - - checkState(originalTransform.getNumShards() > 0, - "Native AvroSink is expected to only be used when sharding controls are required."); - - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - - // TODO: drop this check when server supports alternative templates. - switch (originalTransform.getShardTemplate()) { - case ShardNameTemplate.INDEX_OF_MAX: - break; // supported by server - case "": - // Empty shard template allowed - forces single output. - Preconditions.checkArgument(originalTransform.getNumShards() <= 1, - "Num shards must be <= 1 when using an empty sharding template"); - break; - default: - throw new UnsupportedOperationException("Shard template " - + originalTransform.getShardTemplate() - + " not yet supported by Dataflow service"); - } - - context.addInput(PropertyNames.FORMAT, "avro"); - context.addInput(PropertyNames.FILENAME_PREFIX, originalTransform.getFilenamePrefix()); - context.addInput(PropertyNames.SHARD_NAME_TEMPLATE, originalTransform.getShardTemplate()); - context.addInput(PropertyNames.FILENAME_SUFFIX, originalTransform.getFilenameSuffix()); - context.addInput(PropertyNames.VALIDATE_SINK, originalTransform.needsValidation()); - context.addInput(PropertyNames.NUM_SHARDS, (long) originalTransform.getNumShards()); - context.addEncodingInput( - WindowedValue.getValueOnlyCoder( - AvroCoder.of(originalTransform.getType(), originalTransform.getSchema()))); - } - } - /** * Specialized (non-)implementation for * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java deleted file mode 100644 index de7ab1c046..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactory.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; - -class AvroIOShardedWriteFactory implements PTransformOverrideFactory { - @Override - public PTransform override( - PTransform transform) { - if (transform instanceof AvroIO.Write.Bound) { - @SuppressWarnings("unchecked") - AvroIO.Write.Bound originalWrite = (AvroIO.Write.Bound) transform; - if (originalWrite.getNumShards() > 1 - || (originalWrite.getNumShards() == 1 - && !"".equals(originalWrite.getShardNameTemplate()))) { - @SuppressWarnings("unchecked") - PTransform override = - (PTransform) new AvroIOShardedWrite(originalWrite); - return override; - } - } - return transform; - } - - private class AvroIOShardedWrite extends ShardControlledWrite { - private final AvroIO.Write.Bound initial; - - private AvroIOShardedWrite(AvroIO.Write.Bound initial) { - this.initial = initial; - } - - @Override - int getNumShards() { - return initial.getNumShards(); - } - - @Override - PTransform, PDone> getSingleShardTransform(int shardNum) { - String shardName = - IOChannelUtils.constructName( - initial.getFilenamePrefix(), - initial.getShardNameTemplate(), - initial.getFilenameSuffix(), - shardNum, - getNumShards()); - return initial.withoutSharding().to(shardName).withSuffix(""); - } - - @Override - protected PTransform, PDone> delegate() { - return initial; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 1a3fd1e3cc..9f0aea11e6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -19,8 +19,6 @@ import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; import com.google.cloud.dataflow.sdk.PipelineResult; import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.AggregatorPipelineExtractor; import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; @@ -80,8 +78,6 @@ public class InProcessPipelineRunner .put(Create.Values.class, new InProcessCreateOverrideFactory()) .put(GroupByKey.class, new InProcessGroupByKeyOverrideFactory()) .put(CreatePCollectionView.class, new InProcessViewOverrideFactory()) - .put(AvroIO.Write.Bound.class, new AvroIOShardedWriteFactory()) - .put(TextIO.Write.Bound.class, new TextIOShardedWriteFactory()) .build(); /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java deleted file mode 100644 index 47edb51f17..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ShardControlledWrite.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.Partition; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PDone; - -import java.util.concurrent.ThreadLocalRandom; - -/** - * A write that explicitly controls its number of output shards. - */ -abstract class ShardControlledWrite - extends ForwardingPTransform, PDone> { - @Override - public PDone apply(PCollection input) { - int numShards = getNumShards(); - checkArgument( - numShards >= 1, - "%s should only be applied if the output has a controlled number of shards (> 1); got %s", - getClass().getSimpleName(), - getNumShards()); - PCollectionList shards = - input.apply( - "PartitionInto" + numShards + "Shards", - Partition.of(getNumShards(), new RandomSeedPartitionFn())); - for (int i = 0; i < shards.size(); i++) { - PCollection shard = shards.get(i); - PTransform, PDone> writeShard = getSingleShardTransform(i); - shard.apply(String.format("%s(Shard:%s)", writeShard.getName(), i), writeShard); - } - return PDone.in(input.getPipeline()); - } - - /** - * Returns the number of shards this {@link PTransform} should write to. - */ - abstract int getNumShards(); - - /** - * Returns a {@link PTransform} that performs a write to the shard with the specified shard - * number. - * - *

            This method will be called n times, where n is the value of {@link #getNumShards()}, for - * shard numbers {@code [0...n)}. - */ - abstract PTransform, PDone> getSingleShardTransform(int shardNum); - - private static class RandomSeedPartitionFn implements Partition.PartitionFn { - int nextPartition = -1; - @Override - public int partitionFor(T elem, int numPartitions) { - if (nextPartition < 0) { - nextPartition = ThreadLocalRandom.current().nextInt(numPartitions); - } - nextPartition++; - nextPartition %= numPartitions; - return nextPartition; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java deleted file mode 100644 index b4e0f9b04c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactory.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.TextIO.Write.Bound; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; - -class TextIOShardedWriteFactory implements PTransformOverrideFactory { - - @Override - public PTransform override( - PTransform transform) { - if (transform instanceof TextIO.Write.Bound) { - @SuppressWarnings("unchecked") - TextIO.Write.Bound originalWrite = (TextIO.Write.Bound) transform; - if (originalWrite.getNumShards() > 1 - || (originalWrite.getNumShards() == 1 - && !"".equals(originalWrite.getShardNameTemplate()))) { - @SuppressWarnings("unchecked") - PTransform override = - (PTransform) new TextIOShardedWrite(originalWrite); - return override; - } - } - return transform; - } - - private static class TextIOShardedWrite extends ShardControlledWrite { - private final TextIO.Write.Bound initial; - - private TextIOShardedWrite(Bound initial) { - this.initial = initial; - } - - @Override - int getNumShards() { - return initial.getNumShards(); - } - - @Override - PTransform, PDone> getSingleShardTransform(int shardNum) { - String shardName = - IOChannelUtils.constructName( - initial.getFilenamePrefix(), - initial.getShardTemplate(), - initial.getFilenameSuffix(), - shardNum, - getNumShards()); - return TextIO.Write.withCoder(initial.getCoder()).to(shardName).withoutSharding(); - } - - @Override - protected PTransform, PDone> delegate() { - return initial; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java index d28b1adf93..58025aa100 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java @@ -11,7 +11,6 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package com.google.cloud.dataflow.sdk.io; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; @@ -20,6 +19,7 @@ import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -48,7 +48,9 @@ import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; +import com.google.common.base.Optional; +import org.hamcrest.Matchers; import org.joda.time.Duration; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,12 +59,14 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicInteger; /** * Tests for the Write PTransform. @@ -71,6 +75,10 @@ public class WriteTest { // Static store that can be accessed within the writer private static List sinkContents = new ArrayList<>(); + // Static count of output shards + private static AtomicInteger numShards = new AtomicInteger(0); + // Static counts of the number of records per shard. + private static List recordsPerShard = new ArrayList<>(); private static final MapElements IDENTITY_MAP = MapElements.via(new SimpleFunction() { @@ -122,6 +130,67 @@ public void testWrite() { runWrite(inputs, IDENTITY_MAP); } + /** + * Test that Write with an empty input still produces one shard. + */ + @Test + public void testEmptyWrite() { + runWrite(Collections.emptyList(), IDENTITY_MAP); + // Note we did not request a sharded write, so runWrite will not validate the number of shards. + assertEquals(1, numShards.intValue()); + } + + /** + * Test that Write with a configured number of shards produces the desired number of shards even + * when there are many elements. + */ + @Test + public void testShardedWrite() { + runShardedWrite( + Arrays.asList("one", "two", "three", "four", "five", "six"), + IDENTITY_MAP, + Optional.of(1)); + } + + /** + * Test that Write with a configured number of shards produces the desired number of shards even + * when there are too few elements. + */ + @Test + public void testExpandShardedWrite() { + runShardedWrite( + Arrays.asList("one", "two", "three", "four", "five", "six"), + IDENTITY_MAP, + Optional.of(20)); + } + + /** + * Tests that a Write can balance many elements. + */ + @Test + public void testShardedWriteBalanced() { + int numElements = 1000; + List inputs = new ArrayList<>(numElements); + for (int i = 0; i < numElements; ++i) { + inputs.add(String.format("elt%04d", i)); + } + + runShardedWrite( + inputs, + new WindowAndReshuffle<>( + Window.into(Sessions.withGapDuration(Duration.millis(1)))), + Optional.of(10)); + + // Check that both the min and max number of results per shard are close to the expected. + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + for (Integer i : recordsPerShard) { + min = Math.min(min, i); + max = Math.max(max, i); + } + assertThat((double) min, Matchers.greaterThanOrEqualTo(max * 0.9)); + } + /** * Test a Write transform with an empty PCollection. */ @@ -139,7 +208,7 @@ public void testWriteWindowed() { List inputs = Arrays.asList("Critical canary", "Apprehensive eagle", "Intimidating pigeon", "Pedantic gull", "Frisky finch"); runWrite( - inputs, new WindowAndReshuffle(Window.into(FixedWindows.of(Duration.millis(2))))); + inputs, new WindowAndReshuffle<>(Window.into(FixedWindows.of(Duration.millis(2))))); } /** @@ -152,7 +221,22 @@ public void testWriteWithSessions() { runWrite( inputs, - new WindowAndReshuffle(Window.into(Sessions.withGapDuration(Duration.millis(1))))); + new WindowAndReshuffle<>( + Window.into(Sessions.withGapDuration(Duration.millis(1))))); + } + + @Test + public void testBuildWrite() { + Sink sink = new TestSink() {}; + Write.Bound write = Write.to(sink).withNumShards(3); + assertEquals(3, write.getNumShards()); + assertThat(write.getSink(), is(sink)); + + Write.Bound write2 = write.withNumShards(7); + assertEquals(7, write2.getNumShards()); + assertThat(write2.getSink(), is(sink)); + // original unchanged + assertEquals(3, write.getNumShards()); } @Test @@ -170,7 +254,20 @@ public void populateDisplayData(DisplayData.Builder builder) { assertThat(displayData, includesDisplayDataFrom(sink)); } - + @Test + public void testShardedDisplayData() { + TestSink sink = new TestSink() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item("foo", "bar")); + } + }; + Write.Bound write = Write.to(sink).withNumShards(1); + DisplayData displayData = DisplayData.from(write); + assertThat(displayData, hasDisplayItem("sink", sink.getClass())); + assertThat(displayData, includesDisplayDataFrom(sink)); + assertThat(displayData, hasDisplayItem("numShards", 1)); + } /** * Performs a Write transform and verifies the Write transform calls the appropriate methods on @@ -179,6 +276,18 @@ public void populateDisplayData(DisplayData.Builder builder) { */ private static void runWrite( List inputs, PTransform, PCollection> transform) { + runShardedWrite(inputs, transform, Optional.absent()); + } + + /** + * Performs a Write transform with the desired number of shards. Verifies the Write transform + * calls the appropriate methods on a test sink in the correct order, as well as verifies that + * the elements of a PCollection are written to the sink. If numConfiguredShards is not null, also + * verifies that the output number of shards is correct. + */ + private static void runShardedWrite( + List inputs, PTransform, PCollection> transform, + Optional numConfiguredShards) { // Flag to validate that the pipeline options are passed to the Sink String[] args = {"--testFlag=test_value"}; PipelineOptions options = PipelineOptionsFactory.fromArgs(args).as(WriteOptions.class); @@ -186,6 +295,10 @@ private static void runWrite( // Clear the sink's contents. sinkContents.clear(); + // Reset the number of shards produced. + numShards.set(0); + // Reset the number of records in each shard. + recordsPerShard.clear(); // Prepare timestamps for the elements. List timestamps = new ArrayList<>(); @@ -194,13 +307,21 @@ private static void runWrite( } TestSink sink = new TestSink(); + Write.Bound write = Write.to(sink); + if (numConfiguredShards.isPresent()) { + write = write.withNumShards(numConfiguredShards.get()); + } p.apply(Create.timestamped(inputs, timestamps).withCoder(StringUtf8Coder.of())) .apply(transform) - .apply(Write.to(sink)); + .apply(write); p.run(); assertThat(sinkContents, containsInAnyOrder(inputs.toArray())); assertTrue(sink.hasCorrectState()); + if (numConfiguredShards.isPresent()) { + assertEquals(numConfiguredShards.get().intValue(), numShards.intValue()); + assertEquals(numConfiguredShards.get().intValue(), recordsPerShard.size()); + } } // Test sink and associated write operation and writer. TestSink, TestWriteOperation, and @@ -237,10 +358,7 @@ private boolean hasCorrectState() { */ @Override public boolean equals(Object other) { - if (!(other instanceof TestSink)) { - return false; - } - return true; + return (other instanceof TestSink); } @Override @@ -305,6 +423,7 @@ public void finalize(Iterable bundleResults, PipelineOptions o idSet.add(result.uId); // Add the elements that were written to the sink's contents. sinkContents.addAll(result.elementsWritten); + recordsPerShard.add(result.elementsWritten.size()); } // Each result came from a unique id. assertEquals(resultCount, idSet.size()); @@ -389,6 +508,7 @@ public TestSinkWriteOperation getWriteOperation() { @Override public void open(String uId) throws Exception { + numShards.incrementAndGet(); this.uId = uId; assertEquals(State.INITIAL, state); state = State.OPENED; @@ -412,10 +532,9 @@ public TestWriterResult close() throws Exception { /** * Options for test, exposed for PipelineOptionsFactory. */ - public static interface WriteOptions extends TestPipelineOptions { + public interface WriteOptions extends TestPipelineOptions { @Description("Test flag and value") String getTestFlag(); - void setTestFlag(String value); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java deleted file mode 100644 index 0caaff10f7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/AvroIOShardedWriteFactoryTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.theInstance; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.AvroIOTest; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; - -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; - -/** - * Tests for {@link AvroIOShardedWriteFactory}. - */ -@RunWith(JUnit4.class) -public class AvroIOShardedWriteFactoryTest { - - @Rule public TemporaryFolder tmp = new TemporaryFolder(); - private AvroIOShardedWriteFactory factory; - - @Before - public void setup() { - factory = new AvroIOShardedWriteFactory(); - } - - @Test - public void originalWithoutShardingReturnsOriginal() throws Exception { - File file = tmp.newFile("foo"); - PTransform, PDone> original = - AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()).withoutSharding(); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, theInstance(original)); - } - - @Test - public void originalShardingNotSpecifiedReturnsOriginal() throws Exception { - File file = tmp.newFile("foo"); - PTransform, PDone> original = - AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, theInstance(original)); - } - - @Test - public void originalShardedToOneReturnsExplicitlySharded() throws Exception { - File file = tmp.newFile("foo"); - AvroIO.Write.Bound original = - AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()).withNumShards(1); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, not(Matchers., PDone>>equalTo(original))); - - TestPipeline p = TestPipeline.create(); - String[] elems = new String[] {"foo", "bar", "baz"}; - p.apply(Create.of(elems)).apply(overridden); - - file.delete(); - - p.run(); - AvroIOTest.assertTestOutputs(elems, 1, file.getAbsolutePath(), original.getShardNameTemplate()); - } - - @Test - public void originalShardedToManyReturnsExplicitlySharded() throws Exception { - File file = tmp.newFile("foo"); - AvroIO.Write.Bound original = - AvroIO.Write.withSchema(String.class).to(file.getAbsolutePath()).withNumShards(3); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, not(Matchers., PDone>>equalTo(original))); - - TestPipeline p = TestPipeline.create(); - String[] elems = new String[] {"foo", "bar", "baz", "spam", "ham", "eggs"}; - p.apply(Create.of(elems)).apply(overridden); - - file.delete(); - p.run(); - AvroIOTest.assertTestOutputs(elems, 3, file.getAbsolutePath(), original.getShardNameTemplate()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java deleted file mode 100644 index f0d67ab95b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TextIOShardedWriteFactoryTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.theInstance; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.TextIOTest; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; - -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; - -/** - * Tests for {@link TextIOShardedWriteFactory}. - */ -@RunWith(JUnit4.class) -public class TextIOShardedWriteFactoryTest { - @Rule public TemporaryFolder tmp = new TemporaryFolder(); - private TextIOShardedWriteFactory factory; - - @Before - public void setup() { - factory = new TextIOShardedWriteFactory(); - } - - @Test - public void originalWithoutShardingReturnsOriginal() throws Exception { - File file = tmp.newFile("foo"); - PTransform, PDone> original = - TextIO.Write.to(file.getAbsolutePath()).withoutSharding(); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, theInstance(original)); - } - - @Test - public void originalShardingNotSpecifiedReturnsOriginal() throws Exception { - File file = tmp.newFile("foo"); - PTransform, PDone> original = TextIO.Write.to(file.getAbsolutePath()); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, theInstance(original)); - } - - @Test - public void originalShardedToOneReturnsExplicitlySharded() throws Exception { - File file = tmp.newFile("foo"); - TextIO.Write.Bound original = - TextIO.Write.to(file.getAbsolutePath()).withNumShards(1); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, not(Matchers., PDone>>equalTo(original))); - - TestPipeline p = TestPipeline.create(); - String[] elems = new String[] {"foo", "bar", "baz"}; - p.apply(Create.of(elems)).apply(overridden); - - file.delete(); - - p.run(); - TextIOTest.assertOutputFiles( - elems, StringUtf8Coder.of(), 1, tmp, "foo", original.getShardNameTemplate()); - } - - @Test - public void originalShardedToManyReturnsExplicitlySharded() throws Exception { - File file = tmp.newFile("foo"); - TextIO.Write.Bound original = TextIO.Write.to(file.getAbsolutePath()).withNumShards(3); - PTransform, PDone> overridden = factory.override(original); - - assertThat(overridden, not(Matchers., PDone>>equalTo(original))); - - TestPipeline p = TestPipeline.create(); - String[] elems = new String[] {"foo", "bar", "baz", "spam", "ham", "eggs"}; - p.apply(Create.of(elems)).apply(overridden); - - file.delete(); - p.run(); - TextIOTest.assertOutputFiles( - elems, StringUtf8Coder.of(), 3, tmp, "foo", original.getShardNameTemplate()); - } -} From a6008272a4274f951aef9a4027958a370d097f27 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 21 Jun 2016 10:44:43 -0700 Subject: [PATCH 525/751] Add StaticWindows This is a windowFn that ignores the input and always assigns to the same input. It returns the provided window as the side input window if and only if that window is present within its set of windows. --- .../dataflow/sdk/testing/StaticWindows.java | 115 ++++++++++++++++++ .../dataflow/sdk/testing/WindowSupplier.java | 80 ++++++++++++ .../sdk/testing/StaticWindowsTest.java | 91 ++++++++++++++ .../sdk/testing/WindowSupplierTest.java | 86 +++++++++++++ 4 files changed, 372 insertions(+) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java new file mode 100644 index 0000000000..88f2db9a94 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.NonMergingWindowFn; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; + +import org.joda.time.Instant; + +import java.util.Collection; +import java.util.Collections; +import java.util.Objects; + +/** + * A {@link WindowFn} that assigns all elements to a static collection of + * {@link BoundedWindow BoundedWindows}. Side inputs windowed into static windows only support + * main input windows in the provided collection of windows. + */ +final class StaticWindows extends NonMergingWindowFn { + private final Supplier> windows; + private final Coder coder; + + private final boolean onlyExisting; + + private StaticWindows( + Supplier> windows, + Coder coder, + boolean onlyExisting) { + this.windows = windows; + this.coder = coder; + this.onlyExisting = onlyExisting; + } + + public static StaticWindows of(Coder coder, Iterable windows) { + checkArgument(!Iterables.isEmpty(windows), "Input windows to StaticWindows may not be empty"); + @SuppressWarnings("unchecked") + StaticWindows windowFn = + new StaticWindows( + WindowSupplier.of((Coder) coder, (Iterable) windows), + (Coder) coder, + false); + return windowFn; + } + + public static StaticWindows of(Coder coder, W window) { + return of(coder, Collections.singleton(window)); + } + + public StaticWindows intoOnlyExisting() { + return new StaticWindows(windows, coder, true); + } + + public Collection getWindows() { + return windows.get(); + } + + @Override + public Collection assignWindows(AssignContext c) throws Exception { + if (onlyExisting) { + checkArgument( + windows.get().containsAll(c.windows()), + "Tried to assign windows to an element that is not already windowed into a provided " + + "window when onlyExisting is set to true"); + return ImmutableList.copyOf(c.windows()); + } else { + return getWindows(); + } + } + + @Override + public boolean isCompatible(WindowFn other) { + if (!(other instanceof StaticWindows)) { + return false; + } + StaticWindows that = (StaticWindows) other; + return Objects.equals(this.windows.get(), that.windows.get()); + } + + @Override + public Coder windowCoder() { + return coder; + } + + @Override + public BoundedWindow getSideInputWindow(BoundedWindow window) { + checkArgument(windows.get().contains(window), + "StaticWindows only supports side input windows for main input windows that it contains"); + return window; + } + + @Override + public Instant getOutputTime(Instant inputTimestamp, BoundedWindow window) { + return inputTimestamp; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java new file mode 100644 index 0000000000..5a76447fdc --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.io.Serializable; +import java.util.Collection; + +/** + * A {@link Supplier} that returns a static set of {@link BoundedWindow BoundedWindows}. The + * supplier is {@link Serializable}, and handles encoding and decoding the windows with a + * {@link Coder} provided for the windows. + */ +final class WindowSupplier implements Supplier>, Serializable { + private final Coder coder; + private final Collection encodedWindows; + + private transient Collection windows; + + public static WindowSupplier of(Coder coder, Iterable windows) { + ImmutableSet.Builder windowsBuilder = ImmutableSet.builder(); + for (W window : windows) { + try { + windowsBuilder.add(CoderUtils.encodeToByteArray(coder, window)); + } catch (CoderException e) { + throw new IllegalArgumentException( + "Could not encode provided windows with the provided window coder", e); + } + } + return new WindowSupplier(coder, windowsBuilder.build()); + } + + private WindowSupplier(Coder coder, Collection encodedWindows) { + this.coder = coder; + this.encodedWindows = encodedWindows; + } + + @Override + public Collection get() { + if (windows == null) { + decodeWindows(); + } + return windows; + } + + private synchronized void decodeWindows() { + if (windows == null) { + ImmutableList.Builder windowsBuilder = ImmutableList.builder(); + for (byte[] encoded : encodedWindows) { + try { + windowsBuilder.add(CoderUtils.decodeFromByteArray(coder, encoded)); + } catch (CoderException e) { + throw new IllegalArgumentException( + "Could not decode provided windows with the provided window coder", e); + } + } + this.windows = windowsBuilder.build(); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java new file mode 100644 index 0000000000..9e79f08504 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link StaticWindows}. + */ +@RunWith(JUnit4.class) +public class StaticWindowsTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private final IntervalWindow first = new IntervalWindow(new Instant(0), new Instant(100_000L)); + private final IntervalWindow second = + new IntervalWindow(new Instant(1_000_000L), GlobalWindow.INSTANCE.maxTimestamp()); + + @Test + public void singleWindowSucceeds() throws Exception { + WindowFn fn = StaticWindows.of(IntervalWindow.getCoder(), first); + assertThat(WindowFnTestUtils.assignedWindows(fn, 100L), + Matchers.contains(first)); + assertThat(WindowFnTestUtils.assignedWindows(fn, -100L), + Matchers.contains(first)); + } + + @Test + public void multipleWindowsSucceeds() throws Exception { + WindowFn fn = + StaticWindows.of(IntervalWindow.getCoder(), ImmutableList.of(first, second)); + assertThat(WindowFnTestUtils.assignedWindows(fn, 100L), + Matchers.containsInAnyOrder(first, second)); + assertThat(WindowFnTestUtils.assignedWindows(fn, 1_000_000_000L), + Matchers.containsInAnyOrder(first, second)); + assertThat(WindowFnTestUtils.assignedWindows(fn, -100L), + Matchers.containsInAnyOrder(first, second)); + } + + @Test + public void getSideInputWindowIdentity() { + WindowFn fn = + StaticWindows.of(IntervalWindow.getCoder(), ImmutableList.of(first, second)); + + assertThat(fn.getSideInputWindow(first), Matchers.equalTo(first)); + assertThat(fn.getSideInputWindow(second), Matchers.equalTo(second)); + } + + @Test + public void getSideInputWindowNotPresent() { + WindowFn fn = + StaticWindows.of(IntervalWindow.getCoder(), ImmutableList.of(second)); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("contains"); + fn.getSideInputWindow(first); + } + + @Test + public void emptyIterableThrows() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("may not be empty"); + StaticWindows.of(GlobalWindow.Coder.INSTANCE, ImmutableList.of()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java new file mode 100644 index 0000000000..26e67ae1bf --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.coders.AtomicCoder; +import com.google.cloud.dataflow.sdk.coders.CoderException; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.common.collect.ImmutableList; + +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Collections; + +/** + * Tests for {@link WindowSupplier}. + */ +public class WindowSupplierTest { + private final IntervalWindow window = new IntervalWindow(new Instant(0L), new Instant(100L)); + private final IntervalWindow otherWindow = + new IntervalWindow(new Instant(-100L), new Instant(100L)); + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Test + public void getReturnsProvidedWindows() { + assertThat( + WindowSupplier.of(IntervalWindow.getCoder(), ImmutableList.of(window, otherWindow)).get(), + Matchers.containsInAnyOrder(otherWindow, window)); + } + + @Test + public void getAfterSerialization() { + WindowSupplier supplier = + WindowSupplier.of(IntervalWindow.getCoder(), ImmutableList.of(window, otherWindow)); + assertThat( + SerializableUtils.clone(supplier).get(), + Matchers.containsInAnyOrder(otherWindow, window)); + } + + @Test + public void unencodableWindowFails() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Could not encode"); + WindowSupplier.of( + new FailingCoder(), + Collections.singleton(window)); + } + + private static class FailingCoder extends AtomicCoder { + @Override + public void encode( + BoundedWindow value, OutputStream outStream, Context context) + throws CoderException, IOException { + throw new CoderException("Test Enccode Exception"); + } + + @Override + public BoundedWindow decode( + InputStream inStream, Context context) throws CoderException, IOException { + throw new CoderException("Test Decode Exception"); + } + } +} From 3ba47a148725064781c464de0148f3ba0f935c0a Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Wed, 8 Jun 2016 15:07:52 -0700 Subject: [PATCH 526/751] Base DataflowAssert on GBK instead of side inputs GroupByKey is a bit more fundamental and most backends will be able to group by key in the global window very quickly. So switching the primitive used to gather all the contents of a PCollection for assertions should make it a bit easier to get early feedback during runner development. --- .../dataflow/sdk/testing/DataflowAssert.java | 933 +++++++++++------- .../testing/TestDataflowPipelineRunner.java | 3 +- .../sdk/testing/DataflowAssertTest.java | 26 - 3 files changed, 580 insertions(+), 382 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java index 6c9643cc3c..07e4044ddd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.testing; +import static com.google.common.base.Preconditions.checkState; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; @@ -27,51 +28,53 @@ import com.google.cloud.dataflow.sdk.coders.IterableCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.options.StreamingOptions; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.View; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Never; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.base.Optional; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.List; import java.util.Map; import java.util.NoSuchElementException; /** - * An assertion on the contents of a {@link PCollection} - * incorporated into the pipeline. Such an assertion - * can be checked no matter what kind of {@link PipelineRunner} is - * used. + * An assertion on the contents of a {@link PCollection} incorporated into the pipeline. Such an + * assertion can be checked no matter what kind of {@link PipelineRunner} is used. * *

            Note that the {@code DataflowAssert} call must precede the call * to {@link Pipeline#run}. * - *

            Examples of use: - *

            {@code
            + * 

            Examples of use:

            {@code
              * Pipeline p = TestPipeline.create();
              * ...
              * PCollection output =
            @@ -101,34 +104,139 @@ public class DataflowAssert {
             
               private static int assertCount = 0;
             
            +  private static String nextAssertionName() {
            +    return "DataflowAssert$" + (assertCount++);
            +  }
            +
               // Do not instantiate.
               private DataflowAssert() {}
             
               /**
            -   * Constructs an {@link IterableAssert} for the elements of the provided
            -   * {@link PCollection}.
            +   * Builder interface for assertions applicable to iterables and PCollection contents.
            +   */
            +  public interface IterableAssert {
            +    /**
            +     * Sets the coder of the actual {@link PCollection}.
            +     *
            +     * @return the same {@link IterableAssert} builder for further assertions
            +     * @deprecated instead call {@link PCollection#setCoder(Coder)} on the actual
            +     * {@link PCollection} directly.
            +     */
            +    @Deprecated
            +    IterableAssert setCoder(Coder coderOrNull);
            +
            +    /**
            +     * Returns the coder of the actual {@link PCollection}.
            +     *
            +     * @deprecated instead call {@link PCollection#getCoder()} on the actual {@link PCollection}
            +     * directly
            +     */
            +    @Deprecated
            +    Coder getCoder();
            +
            +    /**
            +     * Asserts that the iterable in question contains the provided elements.
            +     *
            +     * @return the same {@link IterableAssert} builder for further assertions
            +     */
            +    IterableAssert containsInAnyOrder(T... expectedElements);
            +
            +    /**
            +     * Asserts that the iterable in question contains the provided elements.
            +     *
            +     * @return the same {@link IterableAssert} builder for further assertions
            +     */
            +    IterableAssert containsInAnyOrder(Iterable expectedElements);
            +
            +    /**
            +     * Asserts that the iterable in question is empty.
            +     *
            +     * @return the same {@link IterableAssert} builder for further assertions
            +     */
            +    IterableAssert empty();
            +
            +    /**
            +     * Applies the provided checking function (presumably containing assertions) to the
            +     * iterable in question.
            +     *
            +     * @return the same {@link IterableAssert} builder for further assertions
            +     */
            +    IterableAssert satisfies(SerializableFunction, Void> checkerFn);
            +  }
            +
            +  /**
            +   * Builder interface for assertions applicable to a single value.
            +   */
            +  public interface SingletonAssert {
            +    /**
            +     * Sets the coder of the actual {@link PCollection}.
            +     *
            +     * @return the same {@link IterableAssert} builder for further assertions
            +     * @deprecated instead call {@link PCollection#setCoder(Coder)} on the actual
            +     * {@link PCollection} directly.
            +     */
            +    @Deprecated
            +    SingletonAssert setCoder(Coder coderOrNull);
            +
            +    /**
            +     * Returns the coder of the actual {@link PCollection}.
            +     *
            +     * @deprecated instead call {@link PCollection#getCoder()} on the actual {@link PCollection}
            +     * directly
            +     */
            +    @Deprecated
            +    Coder getCoder();
            +
            +    /**
            +     * Asserts that the value in question is equal to the provided value, according to
            +     * {@link Object#equals}.
            +     *
            +     * @return the same {@link SingletonAssert} builder for further assertions
            +     */
            +    SingletonAssert isEqualTo(T expected);
            +
            +    /**
            +     * Asserts that the value in question is equal to the provided value, according to
            +     * {@link Object#equals}.
            +     *
            +     * @deprecated instead use {@link #isEqualTo(Object)}
            +     * @return the same {@link SingletonAssert} builder for further assertions
            +     */
            +    @Deprecated
            +    SingletonAssert is(T expected);
            +
            +    /**
            +     * Asserts that the value in question is not equal to the provided value, according
            +     * to {@link Object#equals}.
            +     *
            +     * @return the same {@link SingletonAssert} builder for further assertions
            +     */
            +    SingletonAssert notEqualTo(T notExpected);
            +
            +    /**
            +     * Applies the provided checking function (presumably containing assertions) to the
            +     * value in question.
            +     *
            +     * @return the same {@link SingletonAssert} builder for further assertions
            +     */
            +    SingletonAssert satisfies(SerializableFunction checkerFn);
            +  }
            +
            +  /**
            +   * Constructs an {@link IterableAssert} for the elements of the provided {@link PCollection}.
                */
               public static  IterableAssert that(PCollection actual) {
            -    return new IterableAssert<>(
            -        new CreateActual>(actual, View.asIterable()),
            -         actual.getPipeline())
            -         .setCoder(actual.getCoder());
            +    return new PCollectionContentsAssert<>(actual);
               }
             
               /**
            -   * Constructs an {@link IterableAssert} for the value of the provided
            -   * {@link PCollection} which must contain a single {@code Iterable}
            -   * value.
            +   * Constructs an {@link IterableAssert} for the value of the provided {@link PCollection} which
            +   * must contain a single {@code Iterable} value.
                */
            -  public static  IterableAssert
            -      thatSingletonIterable(PCollection> actual) {
            +  public static  IterableAssert thatSingletonIterable(
            +      PCollection> actual) {
             
            -    List> maybeElementCoder = actual.getCoder().getCoderArguments();
            -    Coder tCoder;
                 try {
            -      @SuppressWarnings("unchecked")
            -      Coder tCoderTmp = (Coder) Iterables.getOnlyElement(maybeElementCoder);
            -      tCoder = tCoderTmp;
                 } catch (NoSuchElementException | IllegalArgumentException exc) {
                   throw new IllegalArgumentException(
                     "DataflowAssert.thatSingletonIterable requires a PCollection>"
            @@ -139,19 +247,16 @@ public static  IterableAssert that(PCollection actual) {
                 @SuppressWarnings("unchecked") // Safe covariant cast
                 PCollection> actualIterables = (PCollection>) actual;
             
            -    return new IterableAssert<>(
            -        new CreateActual, Iterable>(
            -            actualIterables, View.>asSingleton()),
            -        actual.getPipeline())
            -        .setCoder(tCoder);
            +    return new PCollectionSingletonIterableAssert<>(actualIterables);
               }
             
               /**
            -   * Constructs an {@link IterableAssert} for the value of the provided
            -   * {@code PCollectionView PCollectionView>}.
            +   * Constructs an {@link IterableAssert} for the value of the provided {@link PCollectionView}.
                */
            +  @Deprecated
               public static  IterableAssert thatIterable(PCollectionView> actual) {
            -    return new IterableAssert<>(new PreExisting>(actual), actual.getPipeline());
            +    // TODO Before PR complete. Required for backwards compatibility purposes.
            +    return null;
               }
             
               /**
            @@ -159,93 +264,109 @@ public static  IterableAssert thatIterable(PCollectionView> ac
                * {@code PCollection PCollection}, which must be a singleton.
                */
               public static  SingletonAssert thatSingleton(PCollection actual) {
            -    return new SingletonAssert<>(
            -        new CreateActual(actual, View.asSingleton()), actual.getPipeline())
            -        .setCoder(actual.getCoder());
            +    return new PCollectionViewAssert<>(actual, View.asSingleton(), actual.getCoder());
               }
             
               /**
                * Constructs a {@link SingletonAssert} for the value of the provided {@link PCollection}.
                *
            -   * 

            Note that the actual value must be coded by a {@link KvCoder}, - * not just any {@code Coder}. + *

            Note that the actual value must be coded by a {@link KvCoder}, not just any + * {@code Coder}. */ - public static SingletonAssert>> - thatMultimap(PCollection> actual) { + public static SingletonAssert>> thatMultimap( + PCollection> actual) { @SuppressWarnings("unchecked") KvCoder kvCoder = (KvCoder) actual.getCoder(); - - return new SingletonAssert<>( - new CreateActual<>(actual, View.asMultimap()), actual.getPipeline()) - .setCoder(MapCoder.of(kvCoder.getKeyCoder(), IterableCoder.of(kvCoder.getValueCoder()))); + return new PCollectionViewAssert<>( + actual, + View.asMultimap(), + MapCoder.of(kvCoder.getKeyCoder(), IterableCoder.of(kvCoder.getValueCoder()))); } /** - * Constructs a {@link SingletonAssert} for the value of the provided {@link PCollection}, - * which must have at most one value per key. + * Constructs a {@link SingletonAssert} for the value of the provided {@link PCollection}, which + * must have at most one value per key. * - *

            Note that the actual value must be coded by a {@link KvCoder}, - * not just any {@code Coder}. + *

            Note that the actual value must be coded by a {@link KvCoder}, not just any + * {@code Coder}. */ public static SingletonAssert> thatMap(PCollection> actual) { @SuppressWarnings("unchecked") KvCoder kvCoder = (KvCoder) actual.getCoder(); - - return new SingletonAssert<>( - new CreateActual<>(actual, View.asMap()), actual.getPipeline()) - .setCoder(MapCoder.of(kvCoder.getKeyCoder(), kvCoder.getValueCoder())); + return new PCollectionViewAssert<>( + actual, View.asMap(), MapCoder.of(kvCoder.getKeyCoder(), kvCoder.getValueCoder())); } //////////////////////////////////////////////////////////// /** - * An assertion about the contents of a {@link PCollectionView} yielding an {@code Iterable}. + * An {@link IterableAssert} about the contents of a {@link PCollection}. This does not require + * the runner to support side inputs. */ - public static class IterableAssert implements Serializable { - private final Pipeline pipeline; - private final PTransform>> createActual; - private Optional> coder; + private static class PCollectionContentsAssert implements IterableAssert { + private final PCollection actual; - protected IterableAssert( - PTransform>> createActual, Pipeline pipeline) { - this.createActual = createActual; - this.pipeline = pipeline; - this.coder = Optional.absent(); + public PCollectionContentsAssert(PCollection actual) { + this.actual = actual; + } + + @Override + public IterableAssert setCoder(Coder coderOrNull) { + if (coderOrNull != null) { + actual.setCoder(coderOrNull); + } + return this; + } + + @Override + public Coder getCoder() { + return actual.getCoder(); } /** - * Sets the coder to use for elements of type {@code T}, as needed for internal purposes. + * Checks that the {@code Iterable} contains the expected elements, in any order. * *

            Returns this {@code IterableAssert}. */ - public IterableAssert setCoder(Coder coderOrNull) { - this.coder = Optional.fromNullable(coderOrNull); - return this; + @Override + @SafeVarargs + public final PCollectionContentsAssert containsInAnyOrder(T... expectedElements) { + return containsInAnyOrder(Arrays.asList(expectedElements)); } /** - * Gets the coder, which may yet be absent. + * Checks that the {@code Iterable} contains the expected elements, in any order. + * + *

            Returns this {@code IterableAssert}. */ - public Coder getCoder() { - if (coder.isPresent()) { - return coder.get(); - } else { - throw new IllegalStateException( - "Attempting to access the coder of an IterableAssert" - + " that has not been set yet."); - } + @Override + public PCollectionContentsAssert containsInAnyOrder(Iterable expectedElements) { + return satisfies(new AssertContainsInAnyOrderRelation(), expectedElements); + } + + @Override + public PCollectionContentsAssert empty() { + containsInAnyOrder(Collections.emptyList()); + return this; + } + + @Override + public PCollectionContentsAssert satisfies( + SerializableFunction, Void> checkerFn) { + actual.apply(nextAssertionName(), new GroupThenAssert<>(checkerFn)); + return this; } /** - * Applies a {@link SerializableFunction} to check the elements of the {@code Iterable}. + * Checks that the {@code Iterable} contains elements that match the provided matchers, in any + * order. * *

            Returns this {@code IterableAssert}. */ - public IterableAssert satisfies(SerializableFunction, Void> checkerFn) { - pipeline.apply( - "DataflowAssert$" + (assertCount++), - new OneSideInputAssert>(createActual, checkerFn)); - return this; + @SafeVarargs + final PCollectionContentsAssert containsInAnyOrder( + SerializableMatcher... elementMatchers) { + return satisfies(SerializableMatchers.containsInAnyOrder(elementMatchers)); } /** @@ -253,16 +374,11 @@ public IterableAssert satisfies(SerializableFunction, Void> check * *

            Returns this {@code IterableAssert}. */ - public IterableAssert satisfies( - AssertRelation, Iterable> relation, - final Iterable expectedElements) { - pipeline.apply( - "DataflowAssert$" + (assertCount++), - new TwoSideInputAssert, Iterable>(createActual, - new CreateExpected>(expectedElements, coder, View.asIterable()), - relation)); - - return this; + private PCollectionContentsAssert satisfies( + AssertRelation, Iterable> relation, Iterable expectedElements) { + return satisfies( + new CheckRelationAgainstExpected>( + relation, expectedElements, IterableCoder.of(actual.getCoder()))); } /** @@ -270,17 +386,14 @@ public IterableAssert satisfies( * *

            Returns this {@code IterableAssert}. */ - IterableAssert satisfies(final SerializableMatcher> matcher) { + PCollectionContentsAssert satisfies( + final SerializableMatcher> matcher) { // Safe covariant cast. Could be elided by changing a lot of this file to use // more flexible bounds. @SuppressWarnings({"rawtypes", "unchecked"}) SerializableFunction, Void> checkerFn = - (SerializableFunction) new MatcherCheckerFn<>(matcher); - pipeline.apply( - "DataflowAssert$" + (assertCount++), - new OneSideInputAssert>( - createActual, - checkerFn)); + (SerializableFunction) new MatcherCheckerFn<>(matcher); + actual.apply("DataflowAssert$" + (assertCount++), new GroupThenAssert<>(checkerFn)); return this; } @@ -298,15 +411,6 @@ public Void apply(T actual) { } } - /** - * Checks that the {@code Iterable} is empty. - * - *

            Returns this {@code IterableAssert}. - */ - public IterableAssert empty() { - return satisfies(new AssertContainsInAnyOrderRelation(), Collections.emptyList()); - } - /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on DataflowAssert objects. @@ -330,169 +434,155 @@ public int hashCode() { throw new UnsupportedOperationException( String.format("%s.hashCode() is not supported.", IterableAssert.class.getSimpleName())); } + } - /** - * Checks that the {@code Iterable} contains the expected elements, in any - * order. - * - *

            Returns this {@code IterableAssert}. - */ - public IterableAssert containsInAnyOrder(Iterable expectedElements) { - return satisfies(new AssertContainsInAnyOrderRelation(), expectedElements); + /** + * An {@link IterableAssert} for an iterable that is the sole element of a {@link PCollection}. + * This does not require the runner to support side inputs. + */ + private static class PCollectionSingletonIterableAssert implements IterableAssert { + private final PCollection> actual; + private final Coder elementCoder; + + public PCollectionSingletonIterableAssert(PCollection> actual) { + this.actual = actual; + + @SuppressWarnings("unchecked") + Coder typedCoder = (Coder) actual.getCoder().getCoderArguments().get(0); + this.elementCoder = typedCoder; } - /** - * Checks that the {@code Iterable} contains the expected elements, in any - * order. - * - *

            Returns this {@code IterableAssert}. - */ - @SafeVarargs - public final IterableAssert containsInAnyOrder(T... expectedElements) { - return satisfies( - new AssertContainsInAnyOrderRelation(), - Arrays.asList(expectedElements)); + @Override + public IterableAssert setCoder(Coder coderOrNull) { + return this; } - /** - * Checks that the {@code Iterable} contains elements that match the provided matchers, - * in any order. - * - *

            Returns this {@code IterableAssert}. - */ + @Override + public Coder getCoder() { + return elementCoder; + } + + @Override @SafeVarargs - final IterableAssert containsInAnyOrder( - SerializableMatcher... elementMatchers) { - return satisfies(SerializableMatchers.containsInAnyOrder(elementMatchers)); + public final PCollectionSingletonIterableAssert containsInAnyOrder(T... expectedElements) { + return containsInAnyOrder(Arrays.asList(expectedElements)); + } + + @Override + public PCollectionSingletonIterableAssert empty() { + return containsInAnyOrder(Collections.emptyList()); + } + + @Override + public PCollectionSingletonIterableAssert containsInAnyOrder(Iterable expectedElements) { + return satisfies(new AssertContainsInAnyOrderRelation(), expectedElements); + } + + @Override + public PCollectionSingletonIterableAssert satisfies( + SerializableFunction, Void> checkerFn) { + actual.apply("DataflowAssert$" + (assertCount++), + new GroupThenAssertForSingleton<>(checkerFn)); + return this; + } + + private PCollectionSingletonIterableAssert satisfies( + AssertRelation, Iterable> relation, Iterable expectedElements) { + return satisfies( + new CheckRelationAgainstExpected>( + relation, expectedElements, IterableCoder.of(elementCoder))); } } /** - * An assertion about the single value of type {@code T} - * associated with a {@link PCollectionView}. + * An assertion about the contents of a {@link PCollection} when it is viewed as a single value + * of type {@code ViewT}. This requires side input support from the runner. */ - public static class SingletonAssert implements Serializable { - private final Pipeline pipeline; - private final CreateActual createActual; - private Optional> coder; - - protected SingletonAssert( - CreateActual createActual, Pipeline pipeline) { - this.pipeline = pipeline; - this.createActual = createActual; - this.coder = Optional.absent(); + private static class PCollectionViewAssert implements SingletonAssert { + private final PCollection actual; + private final PTransform, PCollectionView> view; + private final Coder coder; + + protected PCollectionViewAssert( + PCollection actual, + PTransform, PCollectionView> view, + Coder coder) { + this.actual = actual; + this.view = view; + this.coder = coder; } - /** - * Always throws an {@link UnsupportedOperationException}: users are probably looking for - * {@link #isEqualTo}. - */ - @Deprecated @Override - public boolean equals(Object o) { - throw new UnsupportedOperationException( - String.format( - "tests for Java equality of the %s object, not the PCollection in question. " - + "Call a test method, such as isEqualTo.", - getClass().getSimpleName())); + public SingletonAssert setCoder(Coder coderOrNull) { + return this; } - /** - * @throws UnsupportedOperationException always. - * @deprecated {@link Object#hashCode()} is not supported on DataflowAssert objects. - */ - @Deprecated @Override - public int hashCode() { - throw new UnsupportedOperationException( - String.format("%s.hashCode() is not supported.", SingletonAssert.class.getSimpleName())); + public Coder getCoder() { + return coder; } - /** - * Sets the coder to use for elements of type {@code T}, as needed - * for internal purposes. - * - *

            Returns this {@code IterableAssert}. - */ - public SingletonAssert setCoder(Coder coderOrNull) { - this.coder = Optional.fromNullable(coderOrNull); - return this; + @Override + public PCollectionViewAssert isEqualTo(ViewT expectedValue) { + return satisfies(new AssertIsEqualToRelation(), expectedValue); } - /** - * Gets the coder, which may yet be absent. - */ - public Coder getCoder() { - if (coder.isPresent()) { - return coder.get(); - } else { - throw new IllegalStateException( - "Attempting to access the coder of an IterableAssert that has not been set yet."); - } + @Override + public SingletonAssert is(ViewT expected) { + return isEqualTo(expected); } - /** - * Applies a {@link SerializableFunction} to check the value of this - * {@code SingletonAssert}'s view. - * - *

            Returns this {@code SingletonAssert}. - */ - public SingletonAssert satisfies(SerializableFunction checkerFn) { - pipeline.apply( - "DataflowAssert$" + (assertCount++), - new OneSideInputAssert(createActual, checkerFn)); - return this; + @Override + public PCollectionViewAssert notEqualTo(ViewT expectedValue) { + return satisfies(new AssertNotEqualToRelation(), expectedValue); } - /** - * Applies an {@link AssertRelation} to check the provided relation against the - * value of this assert and the provided expected value. - * - *

            Returns this {@code SingletonAssert}. - */ - public SingletonAssert satisfies( - AssertRelation relation, - final T expectedValue) { - pipeline.apply( - "DataflowAssert$" + (assertCount++), - new TwoSideInputAssert(createActual, - new CreateExpected(Arrays.asList(expectedValue), coder, View.asSingleton()), - relation)); - + @Override + public PCollectionViewAssert satisfies( + SerializableFunction checkerFn) { + actual + .getPipeline() + .apply( + "DataflowAssert$" + (assertCount++), + new OneSideInputAssert(CreateActual.from(actual, view), checkerFn)); return this; } /** - * Checks that the value of this {@code SingletonAssert}'s view is equal - * to the expected value. + * Applies an {@link AssertRelation} to check the provided relation against the value of this + * assert and the provided expected value. * *

            Returns this {@code SingletonAssert}. */ - public SingletonAssert isEqualTo(T expectedValue) { - return satisfies(new AssertIsEqualToRelation(), expectedValue); + private PCollectionViewAssert satisfies( + AssertRelation relation, final ViewT expectedValue) { + return satisfies(new CheckRelationAgainstExpected(relation, expectedValue, coder)); } /** - * Checks that the value of this {@code SingletonAssert}'s view is not equal - * to the expected value. - * - *

            Returns this {@code SingletonAssert}. + * Always throws an {@link UnsupportedOperationException}: users are probably looking for + * {@link #isEqualTo}. */ - public SingletonAssert notEqualTo(T expectedValue) { - return satisfies(new AssertNotEqualToRelation(), expectedValue); + @Deprecated + @Override + public boolean equals(Object o) { + throw new UnsupportedOperationException( + String.format( + "tests for Java equality of the %s object, not the PCollection in question. " + + "Call a test method, such as isEqualTo.", + getClass().getSimpleName())); } /** - * Checks that the value of this {@code SingletonAssert}'s view is equal to - * the expected value. - * - * @deprecated replaced by {@link #isEqualTo} + * @throws UnsupportedOperationException always. + * @deprecated {@link Object#hashCode()} is not supported on {@link DataflowAssert} objects. */ @Deprecated - public SingletonAssert is(T expectedValue) { - return isEqualTo(expectedValue); + @Override + public int hashCode() { + throw new UnsupportedOperationException( + String.format("%s.hashCode() is not supported.", SingletonAssert.class.getSimpleName())); } - } //////////////////////////////////////////////////////////////////////// @@ -503,8 +593,13 @@ private static class CreateActual private final transient PCollection actual; private final transient PTransform, PCollectionView> actualView; - private CreateActual(PCollection actual, - PTransform, PCollectionView> actualView) { + public static CreateActual from( + PCollection actual, PTransform, PCollectionView> actualView) { + return new CreateActual<>(actual, actualView); + } + + private CreateActual( + PCollection actual, PTransform, PCollectionView> actualView) { this.actual = actual; this.actualView = actualView; } @@ -514,73 +609,198 @@ public PCollectionView apply(PBegin input) { final Coder coder = actual.getCoder(); return actual .apply(Window.into(new GlobalWindows())) - .apply(ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext context) throws CoderException { - context.output(CoderUtils.clone(coder, context.element())); - } - })) + .apply( + ParDo.of( + new DoFn() { + @Override + public void processElement(ProcessContext context) throws CoderException { + context.output(CoderUtils.clone(coder, context.element())); + } + })) .apply(actualView); } } - private static class CreateExpected - extends PTransform> { - - private final Iterable elements; - private final Optional> coder; - private final transient PTransform, PCollectionView> view; + /** + * A partially applied {@link AssertRelation}, where one value is provided along with a coder to + * serialize/deserialize them. + */ + private static class CheckRelationAgainstExpected implements SerializableFunction { + private final AssertRelation relation; + private final byte[] encodedExpected; + private final Coder coder; - private CreateExpected(Iterable elements, Optional> coder, - PTransform, PCollectionView> view) { - this.elements = elements; + public CheckRelationAgainstExpected(AssertRelation relation, T expected, Coder coder) { + this.relation = relation; this.coder = coder; - this.view = view; + + try { + this.encodedExpected = CoderUtils.encodeToByteArray(coder, expected); + } catch (IOException coderException) { + throw new RuntimeException(coderException); + } } @Override - public PCollectionView apply(PBegin input) { - Create.Values createTransform = Create.of(elements); - if (coder.isPresent()) { - createTransform = createTransform.withCoder(coder.get()); + public Void apply(T actual) { + try { + T expected = CoderUtils.decodeFromByteArray(coder, encodedExpected); + return relation.assertFor(expected).apply(actual); + } catch (IOException coderException) { + throw new RuntimeException(coderException); } - return input.apply(createTransform).apply(view); } } - private static class PreExisting extends PTransform> { + /** + * A transform that gathers the contents of a {@link PCollection} into a single main input + * iterable in the global window. This requires a runner to support {@link GroupByKey} in the + * global window, but not side inputs or other windowing or triggers. + * + *

            If the {@link PCollection} is empty, this transform returns a {@link PCollection} containing + * a single empty iterable, even though in practice most runners will not produce any element. + */ + private static class GroupGlobally extends PTransform, PCollection>> + implements Serializable { + + public GroupGlobally() {} + + @Override + public PCollection> apply(PCollection input) { + + final int contentsKey = 0; + final int dummyKey = 1; + final int combinedKey = 42; + + // Group the contents by key. If it is empty, this PCollection will be empty, too. + // Then key it again with a dummy key. + Bound> trigger = + Window.>triggering(Never.ever()).discardingFiredPanes(); + PCollection>>> doubleKeyedGroupedInput = + input + .apply("GloballyWindow", Window.into(new GlobalWindows())) + .apply("ContentsWithKeys", WithKeys.of(contentsKey)) + .apply("NeverTriggerContents", trigger) + .apply("ContentsGBK", GroupByKey.create()) + .apply( + "DoubleKeyContents", WithKeys.>>of(combinedKey)); + + // Create another non-empty PCollection that is keyed with a distinct dummy key + PCollection>>> doubleKeyedDummy = + input + .getPipeline() + .apply( + Create.of( + KV.of( + combinedKey, + KV.of(dummyKey, (Iterable) Collections.emptyList()))) + .withCoder(doubleKeyedGroupedInput.getCoder())) + .setWindowingStrategyInternal(doubleKeyedGroupedInput.getWindowingStrategy()); + + // Flatten them together and group by the combined key to get a single element + PCollection>>>> dummyAndContents = + PCollectionList.>>>of(doubleKeyedGroupedInput) + .and(doubleKeyedDummy) + .apply( + "FlattenDummyAndContents", + Flatten.>>>pCollections()) + .apply( + "GroupDummyAndContents", GroupByKey.>>create()); + + // Extract the contents if they exist else empty contents. + return dummyAndContents + .apply( + "GetContents", + ParDo.of( + new DoFn>>>, Iterable>() { + @Override + public void processElement(ProcessContext ctx) { + Iterable>> groupedDummyAndContents = + ctx.element().getValue(); + + if (Iterables.size(groupedDummyAndContents) == 1) { + // Only the dummy value, so just output empty + ctx.output(Collections.emptyList()); + } else { + checkState( + Iterables.size(groupedDummyAndContents) == 2, + "Internal error: DataflowAssert grouped contents with a" + + " dummy value resulted in more than 2 groupings: %s", + groupedDummyAndContents); + + if (Iterables.get(groupedDummyAndContents, 0).getKey() == contentsKey) { + // The first iterable in the group holds the real contents + ctx.output(Iterables.get(groupedDummyAndContents, 0).getValue()); + } else { + // The second iterable holds the real contents + ctx.output(Iterables.get(groupedDummyAndContents, 1).getValue()); + } + } + } + })); + } + } + + /** + * A transform that applies an assertion-checking function over iterables of {@code ActualT} to + * the entirety of the contents of its input. + */ + public static class GroupThenAssert extends PTransform, PDone> + implements Serializable { + private final SerializableFunction, Void> checkerFn; + + private GroupThenAssert(SerializableFunction, Void> checkerFn) { + this.checkerFn = checkerFn; + } + + @Override + public PDone apply(PCollection input) { + input + .apply("GroupGlobally", new GroupGlobally()) + .apply("RunChecks", ParDo.of(new GroupedValuesCheckerDoFn<>(checkerFn))); - private final PCollectionView view; + return PDone.in(input.getPipeline()); + } + } - private PreExisting(PCollectionView view) { - this.view = view; + /** + * A transform that applies an assertion-checking function to a single iterable contained as the + * sole element of a {@link PCollection}. + */ + public static class GroupThenAssertForSingleton + extends PTransform>, PDone> implements Serializable { + private final SerializableFunction, Void> checkerFn; + + private GroupThenAssertForSingleton(SerializableFunction, Void> checkerFn) { + this.checkerFn = checkerFn; } @Override - public PCollectionView apply(PBegin input) { - return view; + public PDone apply(PCollection> input) { + input + .apply("GroupGlobally", new GroupGlobally>()) + .apply("RunChecks", ParDo.of(new SingletonCheckerDoFn<>(checkerFn))); + + return PDone.in(input.getPipeline()); } } /** - * An assertion checker that takes a single - * {@link PCollectionView PCollectionView<ActualT>} - * and an assertion over {@code ActualT}, and checks it within a dataflow - * pipeline. + * An assertion checker that takes a single {@link PCollectionView + * PCollectionView<ActualT>} and an assertion over {@code ActualT}, and checks it within a + * Beam pipeline. * - *

            Note that the entire assertion must be serializable. If - * you need to make assertions involving multiple inputs - * that are each not serializable, use TwoSideInputAssert. + *

            Note that the entire assertion must be serializable. * - *

            This is generally useful for assertion functions that - * are serializable but whose underlying data may not have a coder. + *

            This is generally useful for assertion functions that are serializable but whose underlying + * data may not have a coder. */ - static class OneSideInputAssert - extends PTransform implements Serializable { + public static class OneSideInputAssert extends PTransform + implements Serializable { private final transient PTransform> createActual; private final SerializableFunction checkerFn; - public OneSideInputAssert( + private OneSideInputAssert( PTransform> createActual, SerializableFunction checkerFn) { this.createActual = createActual; @@ -592,19 +812,24 @@ public PDone apply(PBegin input) { final PCollectionView actual = input.apply("CreateActual", createActual); input - .apply(Create.of((Void) null).withCoder(VoidCoder.of())) - .apply(ParDo.named("RunChecks").withSideInputs(actual) - .of(new CheckerDoFn<>(checkerFn, actual))); + .apply(Create.of(0).withCoder(VarIntCoder.of())) + .apply( + ParDo.named("RunChecks") + .withSideInputs(actual) + .of(new SideInputCheckerDoFn<>(checkerFn, actual))); return PDone.in(input.getPipeline()); } } /** - * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of - * a {@link PCollectionView}, and adjusts counters and thrown exceptions for use in testing. + * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of a + * {@link PCollectionView}, and adjusts counters and thrown exceptions for use in testing. + * + *

            The input is ignored, but is {@link Integer} to be usable on runners that do not support + * null values. */ - private static class CheckerDoFn extends DoFn { + private static class SideInputCheckerDoFn extends DoFn { private final SerializableFunction checkerFn; private final Aggregator success = createAggregator(SUCCESS_COUNTER, new Sum.SumIntegerFn()); @@ -612,9 +837,8 @@ private static class CheckerDoFn extends DoFn { createAggregator(FAILURE_COUNTER, new Sum.SumIntegerFn()); private final PCollectionView actual; - private CheckerDoFn( - SerializableFunction checkerFn, - PCollectionView actual) { + private SideInputCheckerDoFn( + SerializableFunction checkerFn, PCollectionView actual) { this.checkerFn = checkerFn; this.actual = actual; } @@ -623,12 +847,9 @@ private CheckerDoFn( public void processElement(ProcessContext c) { try { ActualT actualContents = c.sideInput(actual); - checkerFn.apply(actualContents); - success.addValue(1); + doChecks(actualContents, checkerFn, success, failure); } catch (Throwable t) { - LOG.error("DataflowAssert failed expectations.", t); - failure.addValue(1); - // TODO: allow for metrics to propagate on failure when running a streaming pipeline + // Suppress exception in streaming if (!c.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { throw t; } @@ -637,84 +858,89 @@ public void processElement(ProcessContext c) { } /** - * An assertion checker that takes a {@link PCollectionView PCollectionView<ActualT>}, - * a {@link PCollectionView PCollectionView<ExpectedT>}, a relation - * over {@code A} and {@code B}, and checks that the relation holds - * within a dataflow pipeline. + * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of + * the single iterable element of the input {@link PCollection} and adjusts counters and + * thrown exceptions for use in testing. * - *

            This is useful when either/both of {@code A} and {@code B} - * are not serializable, but have coders (provided - * by the underlying {@link PCollection}s). + *

            The singleton property is presumed, not enforced. */ - static class TwoSideInputAssert - extends PTransform implements Serializable { - - private final transient PTransform> createActual; - private final transient PTransform> createExpected; - private final AssertRelation relation; + private static class GroupedValuesCheckerDoFn extends DoFn { + private final SerializableFunction checkerFn; + private final Aggregator success = + createAggregator(SUCCESS_COUNTER, new Sum.SumIntegerFn()); + private final Aggregator failure = + createAggregator(FAILURE_COUNTER, new Sum.SumIntegerFn()); - protected TwoSideInputAssert( - PTransform> createActual, - PTransform> createExpected, - AssertRelation relation) { - this.createActual = createActual; - this.createExpected = createExpected; - this.relation = relation; + private GroupedValuesCheckerDoFn(SerializableFunction checkerFn) { + this.checkerFn = checkerFn; } @Override - public PDone apply(PBegin input) { - final PCollectionView actual = input.apply("CreateActual", createActual); - final PCollectionView expected = input.apply("CreateExpected", createExpected); + public void processElement(ProcessContext c) { + try { + doChecks(c.element(), checkerFn, success, failure); + } catch (Throwable t) { + // Suppress exception in streaming + if (!c.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { + throw t; + } + } + } + } - input - .apply(Create.of((Void) null).withCoder(VoidCoder.of())) - .apply(ParDo.named("RunChecks").withSideInputs(actual, expected) - .of(new CheckerDoFn<>(relation, actual, expected))); + /** + * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of + * the single item contained within the single iterable on input and + * adjusts counters and thrown exceptions for use in testing. + * + *

            The singleton property of the input {@link PCollection} is presumed, not enforced. However, + * each input element must be a singleton iterable, or this will fail. + */ + private static class SingletonCheckerDoFn extends DoFn, Void> { + private final SerializableFunction checkerFn; + private final Aggregator success = + createAggregator(SUCCESS_COUNTER, new Sum.SumIntegerFn()); + private final Aggregator failure = + createAggregator(FAILURE_COUNTER, new Sum.SumIntegerFn()); - return PDone.in(input.getPipeline()); + private SingletonCheckerDoFn(SerializableFunction checkerFn) { + this.checkerFn = checkerFn; } - private static class CheckerDoFn extends DoFn { - private final Aggregator success = - createAggregator(SUCCESS_COUNTER, new Sum.SumIntegerFn()); - private final Aggregator failure = - createAggregator(FAILURE_COUNTER, new Sum.SumIntegerFn()); - private final AssertRelation relation; - private final PCollectionView actual; - private final PCollectionView expected; - - private CheckerDoFn(AssertRelation relation, - PCollectionView actual, PCollectionView expected) { - this.relation = relation; - this.actual = actual; - this.expected = expected; - } - - @Override - public void processElement(ProcessContext c) { - try { - ActualT actualContents = c.sideInput(actual); - ExpectedT expectedContents = c.sideInput(expected); - relation.assertFor(expectedContents).apply(actualContents); - success.addValue(1); - } catch (Throwable t) { - LOG.error("DataflowAssert failed expectations.", t); - failure.addValue(1); - // TODO: allow for metrics to propagate on failure when running a streaming pipeline - if (!c.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { - throw t; - } + @Override + public void processElement(ProcessContext c) { + try { + ActualT actualContents = Iterables.getOnlyElement(c.element()); + doChecks(actualContents, checkerFn, success, failure); + } catch (Throwable t) { + // Suppress exception in streaming + if (!c.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { + throw t; } } } } + private static void doChecks( + ActualT actualContents, + SerializableFunction checkerFn, + Aggregator successAggregator, + Aggregator failureAggregator) { + try { + checkerFn.apply(actualContents); + successAggregator.addValue(1); + } catch (Throwable t) { + LOG.error("DataflowAssert failed expectations.", t); + failureAggregator.addValue(1); + throw t; + } + } + ///////////////////////////////////////////////////////////////////////////// /** - * A {@link SerializableFunction} that verifies that an actual value is equal to an - * expected value. + * A {@link SerializableFunction} that verifies that an actual value is equal to an expected + * value. */ private static class AssertIsEqualTo implements SerializableFunction { private T expected; @@ -731,8 +957,8 @@ public Void apply(T actual) { } /** - * A {@link SerializableFunction} that verifies that an actual value is not equal to an - * expected value. + * A {@link SerializableFunction} that verifies that an actual value is not equal to an expected + * value. */ private static class AssertNotEqualTo implements SerializableFunction { private T expected; @@ -749,8 +975,8 @@ public Void apply(T actual) { } /** - * A {@link SerializableFunction} that verifies that an {@code Iterable} contains - * expected items in any order. + * A {@link SerializableFunction} that verifies that an {@code Iterable} contains expected items + * in any order. */ private static class AssertContainsInAnyOrder implements SerializableFunction, Void> { @@ -780,10 +1006,9 @@ public Void apply(Iterable actual) { //////////////////////////////////////////////////////////// /** - * A binary predicate between types {@code Actual} and {@code Expected}. - * Implemented as a method {@code assertFor(Expected)} which returns - * a {@code SerializableFunction} - * that should verify the assertion.. + * A binary predicate between types {@code Actual} and {@code Expected}. Implemented as a method + * {@code assertFor(Expected)} which returns a {@code SerializableFunction} that + * should verify the assertion.. */ private static interface AssertRelation extends Serializable { public SerializableFunction assertFor(ExpectedT input); @@ -792,8 +1017,7 @@ private static interface AssertRelation extends Serializable /** * An {@link AssertRelation} implementing the binary predicate that two objects are equal. */ - private static class AssertIsEqualToRelation - implements AssertRelation { + private static class AssertIsEqualToRelation implements AssertRelation { @Override public SerializableFunction assertFor(T expected) { return new AssertIsEqualTo(expected); @@ -803,8 +1027,7 @@ public SerializableFunction assertFor(T expected) { /** * An {@link AssertRelation} implementing the binary predicate that two objects are not equal. */ - private static class AssertNotEqualToRelation - implements AssertRelation { + private static class AssertNotEqualToRelation implements AssertRelation { @Override public SerializableFunction assertFor(T expected) { return new AssertNotEqualTo(expected); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java index 9424f0422f..118ba2f822 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java @@ -158,7 +158,8 @@ public void process(List messages) { public OutputT apply( PTransform transform, InputT input) { if (transform instanceof DataflowAssert.OneSideInputAssert - || transform instanceof DataflowAssert.TwoSideInputAssert) { + || transform instanceof DataflowAssert.GroupThenAssert + || transform instanceof DataflowAssert.GroupThenAssertForSingleton) { expectedNumberOfAssertions += 1; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java index 0380bb6be8..074f3479f2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java @@ -16,8 +16,6 @@ package com.google.cloud.dataflow.sdk.testing; -import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.anything; -import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.not; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -154,30 +152,6 @@ public Void apply(Iterable contents) { pipeline.run(); } - /** - * Basic test of succeeding {@link DataflowAssert} using a {@link SerializableMatcher}. - */ - @Test - @Category(RunnableOnService.class) - public void testBasicMatcherSuccess() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(42)); - DataflowAssert.that(pcollection).containsInAnyOrder(anything()); - pipeline.run(); - } - - /** - * Basic test of failing {@link DataflowAssert} using a {@link SerializableMatcher}. - */ - @Test - @Category(RunnableOnService.class) - public void testBasicMatcherFailure() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(42)); - DataflowAssert.that(pcollection).containsInAnyOrder(not(anything())); - runExpectingAssertionFailure(pipeline); - } - /** * Test that we throw an error at pipeline construction time when the user mistakenly uses * {@code DataflowAssert.thatSingleton().equals()} instead of the test method {@code .isEqualTo}. From 7db6b83d447d56fb6622766d3ff43f3b2dc16c60 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 20 Jun 2016 14:38:11 -0700 Subject: [PATCH 527/751] Use GatherAllPanes in PAssert Instead of explicitly grouping by key, gather all the panes across the input window. --- .../dataflow/sdk/testing/DataflowAssert.java | 370 ++++++++++++++---- .../sdk/testing/DataflowAssertTest.java | 114 ++++++ 2 files changed, 415 insertions(+), 69 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java index 07e4044ddd..da6a4bf381 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java @@ -34,19 +34,25 @@ import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.Values; import com.google.cloud.dataflow.sdk.transforms.View; import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Never; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.util.GatherAllPanes; +import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PBegin; import com.google.cloud.dataflow.sdk.values.PCollection; @@ -61,9 +67,11 @@ import java.io.IOException; import java.io.Serializable; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.NoSuchElementException; @@ -133,6 +141,14 @@ public interface IterableAssert { */ @Deprecated Coder getCoder(); + /** + * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only + * run on the provided window. + * + * @return a new {@link IterableAssert} like this one but with the assertion only applied to the + * specified window. + */ + IterableAssert inWindow(BoundedWindow window); /** * Asserts that the iterable in question contains the provided elements. @@ -187,6 +203,15 @@ public interface SingletonAssert { @Deprecated Coder getCoder(); + /** + * Creates a new {@link SingletonAssert} like this one, but with the assertion restricted to + * only run on the provided window. + * + * @return a new {@link SingletonAssert} like this one but with the assertion only applied to + * the specified window. + */ + SingletonAssert inWindow(BoundedWindow window); + /** * Asserts that the value in question is equal to the provided value, according to * {@link Object#equals}. @@ -305,9 +330,23 @@ public static SingletonAssert> thatMap(PCollection> ac */ private static class PCollectionContentsAssert implements IterableAssert { private final PCollection actual; + private final AssertionWindows rewindowingStrategy; public PCollectionContentsAssert(PCollection actual) { + this(actual, IntoGlobalWindow.of()); + } + + public PCollectionContentsAssert(PCollection actual, AssertionWindows rewindowingStrategy) { this.actual = actual; + this.rewindowingStrategy = rewindowingStrategy; + } + + @Override + public PCollectionContentsAssert inWindow(BoundedWindow window) { + @SuppressWarnings({"unchecked", "rawtypes"}) + Coder windowCoder = + (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(); + return new PCollectionContentsAssert<>(actual, IntoStaticWindows.of(windowCoder, window)); } @Override @@ -353,7 +392,7 @@ public PCollectionContentsAssert empty() { @Override public PCollectionContentsAssert satisfies( SerializableFunction, Void> checkerFn) { - actual.apply(nextAssertionName(), new GroupThenAssert<>(checkerFn)); + actual.apply(nextAssertionName(), new GroupThenAssert<>(checkerFn, rewindowingStrategy)); return this; } @@ -393,7 +432,8 @@ PCollectionContentsAssert satisfies( @SuppressWarnings({"rawtypes", "unchecked"}) SerializableFunction, Void> checkerFn = (SerializableFunction) new MatcherCheckerFn<>(matcher); - actual.apply("DataflowAssert$" + (assertCount++), new GroupThenAssert<>(checkerFn)); + actual.apply("DataflowAssert$" + (assertCount++), + new GroupThenAssert<>(checkerFn, rewindowingStrategy)); return this; } @@ -443,13 +483,30 @@ public int hashCode() { private static class PCollectionSingletonIterableAssert implements IterableAssert { private final PCollection> actual; private final Coder elementCoder; + private final AssertionWindows rewindowingStrategy; public PCollectionSingletonIterableAssert(PCollection> actual) { + this(actual, IntoGlobalWindow.>of()); + } + + public PCollectionSingletonIterableAssert( + PCollection> actual, AssertionWindows rewindowingStrategy) { this.actual = actual; @SuppressWarnings("unchecked") Coder typedCoder = (Coder) actual.getCoder().getCoderArguments().get(0); this.elementCoder = typedCoder; + + this.rewindowingStrategy = rewindowingStrategy; + } + + @Override + public PCollectionSingletonIterableAssert inWindow(BoundedWindow window) { + @SuppressWarnings({"unchecked", "rawtypes"}) + Coder windowCoder = + (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(); + return new PCollectionSingletonIterableAssert<>( + actual, IntoStaticWindows.>of(windowCoder, window)); } @Override @@ -481,8 +538,9 @@ public PCollectionSingletonIterableAssert containsInAnyOrder(Iterable expe @Override public PCollectionSingletonIterableAssert satisfies( SerializableFunction, Void> checkerFn) { - actual.apply("DataflowAssert$" + (assertCount++), - new GroupThenAssertForSingleton<>(checkerFn)); + actual.apply( + "DataflowAssert$" + (assertCount++), + new GroupThenAssertForSingleton<>(checkerFn, rewindowingStrategy)); return this; } @@ -501,14 +559,24 @@ private PCollectionSingletonIterableAssert satisfies( private static class PCollectionViewAssert implements SingletonAssert { private final PCollection actual; private final PTransform, PCollectionView> view; + private final AssertionWindows rewindowActuals; private final Coder coder; protected PCollectionViewAssert( PCollection actual, PTransform, PCollectionView> view, Coder coder) { + this(actual, view, IntoGlobalWindow.of(), coder); + } + + private PCollectionViewAssert( + PCollection actual, + PTransform, PCollectionView> view, + AssertionWindows rewindowActuals, + Coder coder) { this.actual = actual; this.view = view; + this.rewindowActuals = rewindowActuals; this.coder = coder; } @@ -522,6 +590,15 @@ public Coder getCoder() { return coder; } + public PCollectionViewAssert inWindow(BoundedWindow window) { + return new PCollectionViewAssert<>( + actual, + view, + IntoStaticWindows.of( + (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(), window), + coder); + } + @Override public PCollectionViewAssert isEqualTo(ViewT expectedValue) { return satisfies(new AssertIsEqualToRelation(), expectedValue); @@ -544,7 +621,10 @@ public PCollectionViewAssert satisfies( .getPipeline() .apply( "DataflowAssert$" + (assertCount++), - new OneSideInputAssert(CreateActual.from(actual, view), checkerFn)); + new OneSideInputAssert( + CreateActual.from(actual, rewindowActuals, view), + rewindowActuals.windowDummy(), + checkerFn)); return this; } @@ -591,16 +671,22 @@ private static class CreateActual extends PTransform> { private final transient PCollection actual; + private final transient AssertionWindows rewindowActuals; private final transient PTransform, PCollectionView> actualView; public static CreateActual from( - PCollection actual, PTransform, PCollectionView> actualView) { - return new CreateActual<>(actual, actualView); + PCollection actual, + AssertionWindows rewindowActuals, + PTransform, PCollectionView> actualView) { + return new CreateActual<>(actual, rewindowActuals, actualView); } private CreateActual( - PCollection actual, PTransform, PCollectionView> actualView) { + PCollection actual, + AssertionWindows rewindowActuals, + PTransform, PCollectionView> actualView) { this.actual = actual; + this.rewindowActuals = rewindowActuals; this.actualView = actualView; } @@ -608,7 +694,8 @@ private CreateActual( public PCollectionView apply(PBegin input) { final Coder coder = actual.getCoder(); return actual - .apply(Window.into(new GlobalWindows())) + .apply("FilterActuals", rewindowActuals.prepareActuals()) + .apply("RewindowActuals", rewindowActuals.windowActuals()) .apply( ParDo.of( new DoFn() { @@ -660,84 +747,83 @@ public Void apply(T actual) { *

            If the {@link PCollection} is empty, this transform returns a {@link PCollection} containing * a single empty iterable, even though in practice most runners will not produce any element. */ - private static class GroupGlobally extends PTransform, PCollection>> + private static class GroupGlobally + extends PTransform, PCollection>>> implements Serializable { + private final AssertionWindows rewindowingStrategy; - public GroupGlobally() {} + public GroupGlobally(AssertionWindows rewindowingStrategy) { + this.rewindowingStrategy = rewindowingStrategy; + } @Override - public PCollection> apply(PCollection input) { - - final int contentsKey = 0; - final int dummyKey = 1; + public PCollection>> apply(PCollection input) { final int combinedKey = 42; + // Remove the triggering on both + PTransform< + PCollection>>>, + PCollection>>>> + removeTriggering = + Window.>>>triggering(Never.ever()) + .discardingFiredPanes() + .withAllowedLateness(input.getWindowingStrategy().getAllowedLateness()); // Group the contents by key. If it is empty, this PCollection will be empty, too. // Then key it again with a dummy key. - Bound> trigger = - Window.>triggering(Never.ever()).discardingFiredPanes(); - PCollection>>> doubleKeyedGroupedInput = + PCollection>>> groupedContents = + // TODO: Split the filtering from the rewindowing, and apply filtering before the Gather + // if the grouping of extra records input - .apply("GloballyWindow", Window.into(new GlobalWindows())) - .apply("ContentsWithKeys", WithKeys.of(contentsKey)) - .apply("NeverTriggerContents", trigger) - .apply("ContentsGBK", GroupByKey.create()) + .apply(rewindowingStrategy.prepareActuals()) + .apply("GatherAllOutputs", GatherAllPanes.globally()) .apply( - "DoubleKeyContents", WithKeys.>>of(combinedKey)); + "RewindowActuals", + rewindowingStrategy.>>windowActuals()) + .apply("KeyForDummy", WithKeys.>>of(combinedKey)) + .apply("RemoveActualsTriggering", removeTriggering); // Create another non-empty PCollection that is keyed with a distinct dummy key - PCollection>>> doubleKeyedDummy = + PCollection>>> keyedDummy = input .getPipeline() .apply( Create.of( KV.of( combinedKey, - KV.of(dummyKey, (Iterable) Collections.emptyList()))) - .withCoder(doubleKeyedGroupedInput.getCoder())) - .setWindowingStrategyInternal(doubleKeyedGroupedInput.getWindowingStrategy()); + (Iterable>) + Collections.>emptyList())) + .withCoder(groupedContents.getCoder())) + .apply( + "WindowIntoDummy", + rewindowingStrategy.>>>windowDummy()) + .apply("RemoveDummyTriggering", removeTriggering); // Flatten them together and group by the combined key to get a single element - PCollection>>>> dummyAndContents = - PCollectionList.>>>of(doubleKeyedGroupedInput) - .and(doubleKeyedDummy) + Bound>>> trigger = + Window.>>>triggering(Never.ever()) + .withAllowedLateness(input.getWindowingStrategy().getAllowedLateness()) + .discardingFiredPanes(); + PCollection>>>> dummyAndContents = + PCollectionList.of(groupedContents) + .and(keyedDummy) .apply( "FlattenDummyAndContents", - Flatten.>>>pCollections()) + Flatten.>>>pCollections()) + .apply("NeverTrigger", trigger) .apply( - "GroupDummyAndContents", GroupByKey.>>create()); + "GroupDummyAndContents", + GroupByKey.>>create()); - // Extract the contents if they exist else empty contents. return dummyAndContents - .apply( - "GetContents", - ParDo.of( - new DoFn>>>, Iterable>() { - @Override - public void processElement(ProcessContext ctx) { - Iterable>> groupedDummyAndContents = - ctx.element().getValue(); - - if (Iterables.size(groupedDummyAndContents) == 1) { - // Only the dummy value, so just output empty - ctx.output(Collections.emptyList()); - } else { - checkState( - Iterables.size(groupedDummyAndContents) == 2, - "Internal error: DataflowAssert grouped contents with a" - + " dummy value resulted in more than 2 groupings: %s", - groupedDummyAndContents); - - if (Iterables.get(groupedDummyAndContents, 0).getKey() == contentsKey) { - // The first iterable in the group holds the real contents - ctx.output(Iterables.get(groupedDummyAndContents, 0).getValue()); - } else { - // The second iterable holds the real contents - ctx.output(Iterables.get(groupedDummyAndContents, 1).getValue()); - } - } - } - })); + .apply(Values.>>>create()) + .apply(ParDo.of(new ConcatFn>())); + } + } + + private static final class ConcatFn extends DoFn>, Iterable> { + @Override + public void processElement(ProcessContext c) throws Exception { + c.output(Iterables.concat(c.element())); } } @@ -748,15 +834,20 @@ public void processElement(ProcessContext ctx) { public static class GroupThenAssert extends PTransform, PDone> implements Serializable { private final SerializableFunction, Void> checkerFn; + private final AssertionWindows rewindowingStrategy; - private GroupThenAssert(SerializableFunction, Void> checkerFn) { + private GroupThenAssert( + SerializableFunction, Void> checkerFn, AssertionWindows rewindowingStrategy) { this.checkerFn = checkerFn; + this.rewindowingStrategy = rewindowingStrategy; } @Override public PDone apply(PCollection input) { input - .apply("GroupGlobally", new GroupGlobally()) + .apply("GroupGlobally", new GroupGlobally(rewindowingStrategy)) + .apply("GetOnlyPane", ParDo.of(new ExtractOnlyPane())) + .setCoder(IterableCoder.of(input.getCoder())) .apply("RunChecks", ParDo.of(new GroupedValuesCheckerDoFn<>(checkerFn))); return PDone.in(input.getPipeline()); @@ -770,15 +861,20 @@ public PDone apply(PCollection input) { public static class GroupThenAssertForSingleton extends PTransform>, PDone> implements Serializable { private final SerializableFunction, Void> checkerFn; + private final AssertionWindows rewindowingStrategy; - private GroupThenAssertForSingleton(SerializableFunction, Void> checkerFn) { + private GroupThenAssertForSingleton( + SerializableFunction, Void> checkerFn, AssertionWindows rewindowingStrategy) { this.checkerFn = checkerFn; + this.rewindowingStrategy = rewindowingStrategy; } @Override public PDone apply(PCollection> input) { input - .apply("GroupGlobally", new GroupGlobally>()) + .apply("GroupGlobally", new GroupGlobally>(rewindowingStrategy)) + .apply("GetOnlyPane", ParDo.of(new ExtractOnlyPane>())) + .setCoder(IterableCoder.of(input.getCoder())) .apply("RunChecks", ParDo.of(new SingletonCheckerDoFn<>(checkerFn))); return PDone.in(input.getPipeline()); @@ -798,12 +894,15 @@ public PDone apply(PCollection> input) { public static class OneSideInputAssert extends PTransform implements Serializable { private final transient PTransform> createActual; + private final transient PTransform, PCollection> windowToken; private final SerializableFunction checkerFn; private OneSideInputAssert( PTransform> createActual, + PTransform, PCollection> windowToken, SerializableFunction checkerFn) { this.createActual = createActual; + this.windowToken = windowToken; this.checkerFn = checkerFn; } @@ -813,10 +912,10 @@ public PDone apply(PBegin input) { input .apply(Create.of(0).withCoder(VarIntCoder.of())) + .apply("WindowToken", windowToken) .apply( - ParDo.named("RunChecks") - .withSideInputs(actual) - .of(new SideInputCheckerDoFn<>(checkerFn, actual))); + "RunChecks", + ParDo.withSideInputs(actual).of(new SideInputCheckerDoFn<>(checkerFn, actual))); return PDone.in(input.getPipeline()); } @@ -857,6 +956,23 @@ public void processElement(ProcessContext c) { } } + private static class ExtractOnlyPane extends DoFn>, Iterable> { + @Override + public void processElement(ProcessContext c) throws Exception { + List outputs = new ArrayList<>(); + for (WindowedValue value : c.element()) { + checkState( + value.getPane().isFirst() && value.getPane().isLast(), + "Expected elements to be produced by a trigger that fires at most once, but got" + + "a value in a pane that is %s. Actual Pane Info: %s", + value.getPane().isFirst() ? "not the last pane" : "not the first pane", + value.getPane()); + outputs.add(value.getValue()); + } + c.output(outputs); + } + } + /** * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of * the single iterable element of the input {@link PCollection} and adjusts counters and @@ -1045,4 +1161,120 @@ public SerializableFunction, Void> assertFor(Iterable expectedEle return new AssertContainsInAnyOrder(expectedElements); } } + + //////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * A strategy for filtering and rewindowing the actual and dummy {@link PCollection PCollections} + * within a {@link DataflowAssert}. + * + *

            This must ensure that the windowing strategies of the output of {@link #windowActuals()} and + * {@link #windowDummy()} are compatible (and can be {@link Flatten Flattened}). + * + *

            The {@link PCollection} produced by {@link #prepareActuals()} will be a parent (though not + * a direct parent) of the transform provided to {@link #windowActuals()}. + */ + private interface AssertionWindows { + /** + * Returns a transform that assigns the dummy element into the appropriate + * {@link BoundedWindow windows}. + */ + PTransform, PCollection> windowDummy(); + + /** + * Returns a transform that filters and reassigns windows of the actual elements if necessary. + */ + PTransform, PCollection> prepareActuals(); + + /** + * Returns a transform that assigns the actual elements into the appropriate + * {@link BoundedWindow windows}. Will be called after {@link #prepareActuals()}. + */ + PTransform, PCollection> windowActuals(); + } + + /** + * An {@link AssertionWindows} which assigns all elements to the {@link GlobalWindow}. + */ + private static class IntoGlobalWindow implements AssertionWindows, Serializable { + public static AssertionWindows of() { + return new IntoGlobalWindow(); + } + + private PTransform, PCollection> window() { + return Window.into(new GlobalWindows()); + } + + @Override + public PTransform, PCollection> windowDummy() { + return window(); + } + + /** + * Rewindows all input elements into the {@link GlobalWindow}. This ensures that the result + * PCollection will contain all of the elements of the PCollection when the window is not + * specified. + */ + @Override + public PTransform, PCollection> prepareActuals() { + return window(); + } + + @Override + public PTransform, PCollection> windowActuals() { + return window(); + } + } + + private static class IntoStaticWindows implements AssertionWindows { + private final StaticWindows windowFn; + + public static AssertionWindows of(Coder windowCoder, BoundedWindow window) { + return new IntoStaticWindows(StaticWindows.of(windowCoder, window)); + } + + private IntoStaticWindows(StaticWindows windowFn) { + this.windowFn = windowFn; + } + + @Override + public PTransform, PCollection> windowDummy() { + return Window.into(windowFn); + } + + @Override + public PTransform, PCollection> prepareActuals() { + return new FilterWindows<>(windowFn); + } + + @Override + public PTransform, PCollection> windowActuals() { + return Window.into(windowFn.intoOnlyExisting()); + } + } + + /** + * A DoFn that filters elements based on their presence in a static collection of windows. + */ + private static final class FilterWindows extends PTransform, PCollection> { + private final StaticWindows windows; + + public FilterWindows(StaticWindows windows) { + this.windows = windows; + } + + @Override + public PCollection apply(PCollection input) { + return input.apply("FilterWindows", ParDo.of(new Fn())); + } + + private class Fn extends DoFn implements RequiresWindowAccess { + @Override + public void processElement(ProcessContext c) throws Exception { + if (windows.getWindows().contains(c.window())) { + c.output(c.element()); + } + } + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java index 074f3479f2..7b019de214 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.testing; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -28,11 +29,20 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.common.collect.Iterables; import com.fasterxml.jackson.annotation.JsonCreator; +import org.joda.time.Duration; +import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -152,6 +162,45 @@ public Void apply(Iterable contents) { pipeline.run(); } + /** + * A {@link DataflowAssert} about the contents of a {@link PCollection} + * is allows to be verified by an arbitrary {@link SerializableFunction}, + * though. + */ + @Test + @Category(RunnableOnService.class) + public void testWindowedSerializablePredicate() throws Exception { + Pipeline pipeline = TestPipeline.create(); + + PCollection pcollection = pipeline + .apply(Create.timestamped( + TimestampedValue.of(new NotSerializableObject(), new Instant(250L)), + TimestampedValue.of(new NotSerializableObject(), new Instant(500L))) + .withCoder(NotSerializableObjectCoder.of())) + .apply(Window.into(FixedWindows.of(Duration.millis(300L)))); + + DataflowAssert.that(pcollection) + .inWindow(new IntervalWindow(new Instant(0L), new Instant(300L))) + .satisfies(new SerializableFunction, Void>() { + @Override + public Void apply(Iterable contents) { + assertThat(Iterables.isEmpty(contents), is(false)); + return null; // no problem! + } + }); + DataflowAssert.that(pcollection) + .inWindow(new IntervalWindow(new Instant(300L), new Instant(600L))) + .satisfies(new SerializableFunction, Void>() { + @Override + public Void apply(Iterable contents) { + assertThat(Iterables.isEmpty(contents), is(false)); + return null; // no problem! + } + }); + + pipeline.run(); + } + /** * Test that we throw an error at pipeline construction time when the user mistakenly uses * {@code DataflowAssert.thatSingleton().equals()} instead of the test method {@code .isEqualTo}. @@ -224,6 +273,26 @@ public void testIsEqualTo() throws Exception { pipeline.run(); } + /** + * Basic test for {@code isEqualTo}. + */ + @Test + @Category(RunnableOnService.class) + public void testWindowedIsEqualTo() throws Exception { + Pipeline pipeline = TestPipeline.create(); + PCollection pcollection = + pipeline.apply(Create.timestamped(TimestampedValue.of(43, new Instant(250L)), + TimestampedValue.of(22, new Instant(-250L)))) + .apply(Window.into(FixedWindows.of(Duration.millis(500L)))); + DataflowAssert.thatSingleton(pcollection) + .inWindow(new IntervalWindow(new Instant(0L), new Instant(500L))) + .isEqualTo(43); + DataflowAssert.thatSingleton(pcollection) + .inWindow(new IntervalWindow(new Instant(-500L), new Instant(0L))) + .isEqualTo(22); + pipeline.run(); + } + /** * Basic test for {@code notEqualTo}. */ @@ -248,6 +317,51 @@ public void testContainsInAnyOrder() throws Exception { pipeline.run(); } + /** + * Tests that {@code containsInAnyOrder} is actually order-independent. + */ + @Test + @Category(RunnableOnService.class) + public void testGlobalWindowContainsInAnyOrder() throws Exception { + Pipeline pipeline = TestPipeline.create(); + PCollection pcollection = pipeline.apply(Create.of(1, 2, 3, 4)); + DataflowAssert.that(pcollection).inWindow(GlobalWindow.INSTANCE).containsInAnyOrder(2, 1, 4, 3); + pipeline.run(); + } + + /** + * Tests that windowed {@code containsInAnyOrder} is actually order-independent. + */ + @Test + @Category(RunnableOnService.class) + public void testWindowedContainsInAnyOrder() throws Exception { + Pipeline pipeline = TestPipeline.create(); + PCollection pcollection = + pipeline.apply(Create.timestamped(TimestampedValue.of(1, new Instant(100L)), + TimestampedValue.of(2, new Instant(200L)), + TimestampedValue.of(3, new Instant(300L)), + TimestampedValue.of(4, new Instant(400L)))) + .apply(Window.into(SlidingWindows.of(Duration.millis(200L)) + .every(Duration.millis(100L)) + .withOffset(Duration.millis(50L)))); + + DataflowAssert.that(pcollection) + .inWindow(new IntervalWindow(new Instant(-50L), new Instant(150L))).containsInAnyOrder(1); + DataflowAssert.that(pcollection) + .inWindow(new IntervalWindow(new Instant(50L), new Instant(250L))) + .containsInAnyOrder(2, 1); + DataflowAssert.that(pcollection) + .inWindow(new IntervalWindow(new Instant(150L), new Instant(350L))) + .containsInAnyOrder(2, 3); + DataflowAssert.that(pcollection) + .inWindow(new IntervalWindow(new Instant(250L), new Instant(450L))) + .containsInAnyOrder(4, 3); + DataflowAssert.that(pcollection) + .inWindow(new IntervalWindow(new Instant(350L), new Instant(550L))) + .containsInAnyOrder(4); + pipeline.run(); + } + /** * Tests that {@code containsInAnyOrder} fails when and how it should. */ From 463028f98b178f7979b1902963cb5746abfc2dbe Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 20 Jun 2016 14:38:11 -0700 Subject: [PATCH 528/751] Add Pane matchers to PAssert This allows PCollections that have upstream triggers that fire multiple times to assert the contents of panes with specific timings, rather than restricting the trigger to fire only once. --- .../dataflow/sdk/testing/DataflowAssert.java | 221 +++++++++--- .../dataflow/sdk/testing/PaneExtractors.java | 139 ++++++++ .../sdk/testing/DataflowAssertTest.java | 4 +- .../sdk/testing/PaneExtractorsTest.java | 321 ++++++++++++++++++ 4 files changed, 644 insertions(+), 41 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java index da6a4bf381..b0e4630852 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java @@ -16,7 +16,6 @@ package com.google.cloud.dataflow.sdk.testing; -import static com.google.common.base.Preconditions.checkState; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; @@ -37,9 +36,11 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.MapElements; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.Values; import com.google.cloud.dataflow.sdk.transforms.View; @@ -62,16 +63,15 @@ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.List; import java.util.Map; import java.util.NoSuchElementException; @@ -145,11 +145,50 @@ public interface IterableAssert { * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only * run on the provided window. * + *

            The assertion will concatenate all panes present in the provided window if the + * {@link Trigger} produces multiple panes. If the windowing strategy accumulates fired panes + * and triggers fire multple times, consider using instead {@link #inFinalPane(BoundedWindow)} + * or {@link #inOnTimePane(BoundedWindow)}. + * * @return a new {@link IterableAssert} like this one but with the assertion only applied to the * specified window. */ IterableAssert inWindow(BoundedWindow window); + /** + * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only + * run on the provided window, running the checker only on the final pane for each key. + * + *

            If the input {@link WindowingStrategy} does not always produce final panes, the assertion + * may be executed over an empty input even if the trigger has fired previously. To ensure that + * a final pane is always produced, set the {@link ClosingBehavior} of the windowing strategy + * (via {@link Window.Bound#withAllowedLateness(Duration, ClosingBehavior)} setting + * {@link ClosingBehavior} to {@link ClosingBehavior#FIRE_ALWAYS}). + * + * @return a new {@link IterableAssert} like this one but with the assertion only applied to the + * specified window. + */ + IterableAssert inFinalPane(BoundedWindow window); + + /** + * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only + * run on the provided window. + * + * @return a new {@link IterableAssert} like this one but with the assertion only applied to the + * specified window. + */ + IterableAssert inOnTimePane(BoundedWindow window); + + /** + * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only + * run on the provided window across all panes that were not produced by the arrival of late + * data. + * + * @return a new {@link IterableAssert} like this one but with the assertion only applied to the + * specified window. + */ + IterableAssert inCombinedNonLatePanes(BoundedWindow window); + /** * Asserts that the iterable in question contains the provided elements. * @@ -207,10 +246,38 @@ public interface SingletonAssert { * Creates a new {@link SingletonAssert} like this one, but with the assertion restricted to * only run on the provided window. * + *

            The assertion will expect outputs to be produced to the provided window exactly once. If + * the upstream {@link Trigger} may produce output multiple times, consider instead using + * {@link #inFinalPane(BoundedWindow)} or {@link #inOnTimePane(BoundedWindow)}. + * + * @return a new {@link SingletonAssert} like this one but with the assertion only applied to + * the specified window. + */ + SingletonAssert inOnlyPane(BoundedWindow window); + + /** + * Creates a new {@link SingletonAssert} like this one, but with the assertion restricted to + * only run on the provided window, running the checker only on the final pane for each key. + * + *

            If the input {@link WindowingStrategy} does not always produce final panes, the assertion + * may be executed over an empty input even if the trigger has fired previously. To ensure that + * a final pane is always produced, set the {@link ClosingBehavior} of the windowing strategy + * (via {@link Window.Bound#withAllowedLateness(Duration, ClosingBehavior)} setting + * {@link ClosingBehavior} to {@link ClosingBehavior#FIRE_ALWAYS}). + * + * @return a new {@link SingletonAssert} like this one but with the assertion only applied to + * the specified window. + */ + SingletonAssert inFinalPane(BoundedWindow window); + + /** + * Creates a new {@link SingletonAssert} like this one, but with the assertion restricted to + * only run on the provided window, running the checker only on the on-time pane for each key. + * * @return a new {@link SingletonAssert} like this one but with the assertion only applied to * the specified window. */ - SingletonAssert inWindow(BoundedWindow window); + SingletonAssert inOnTimePane(BoundedWindow window); /** * Asserts that the value in question is equal to the provided value, according to @@ -331,22 +398,49 @@ public static SingletonAssert> thatMap(PCollection> ac private static class PCollectionContentsAssert implements IterableAssert { private final PCollection actual; private final AssertionWindows rewindowingStrategy; + private final SimpleFunction>, Iterable> paneExtractor; public PCollectionContentsAssert(PCollection actual) { - this(actual, IntoGlobalWindow.of()); + this(actual, IntoGlobalWindow.of(), PaneExtractors.onlyPane()); } - public PCollectionContentsAssert(PCollection actual, AssertionWindows rewindowingStrategy) { + public PCollectionContentsAssert( + PCollection actual, + AssertionWindows rewindowingStrategy, + SimpleFunction>, Iterable> paneExtractor) { this.actual = actual; this.rewindowingStrategy = rewindowingStrategy; + this.paneExtractor = paneExtractor; } @Override public PCollectionContentsAssert inWindow(BoundedWindow window) { + return withPane(window, PaneExtractors.allPanes()); + } + + @Override + public PCollectionContentsAssert inFinalPane(BoundedWindow window) { + return withPane(window, PaneExtractors.finalPane()); + } + + @Override + public PCollectionContentsAssert inOnTimePane(BoundedWindow window) { + return withPane(window, PaneExtractors.onTimePane()); + } + + @Override + public PCollectionContentsAssert inCombinedNonLatePanes(BoundedWindow window) { + return withPane(window, PaneExtractors.nonLatePanes()); + } + + private PCollectionContentsAssert withPane( + BoundedWindow window, + SimpleFunction>, Iterable> paneExtractor) { @SuppressWarnings({"unchecked", "rawtypes"}) Coder windowCoder = (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(); - return new PCollectionContentsAssert<>(actual, IntoStaticWindows.of(windowCoder, window)); + return new PCollectionContentsAssert<>( + actual, IntoStaticWindows.of(windowCoder, window), paneExtractor); } @Override @@ -392,7 +486,9 @@ public PCollectionContentsAssert empty() { @Override public PCollectionContentsAssert satisfies( SerializableFunction, Void> checkerFn) { - actual.apply(nextAssertionName(), new GroupThenAssert<>(checkerFn, rewindowingStrategy)); + actual.apply( + nextAssertionName(), + new GroupThenAssert<>(checkerFn, rewindowingStrategy, paneExtractor)); return this; } @@ -432,8 +528,9 @@ PCollectionContentsAssert satisfies( @SuppressWarnings({"rawtypes", "unchecked"}) SerializableFunction, Void> checkerFn = (SerializableFunction) new MatcherCheckerFn<>(matcher); - actual.apply("DataflowAssert$" + (assertCount++), - new GroupThenAssert<>(checkerFn, rewindowingStrategy)); + actual.apply( + "DataflowAssert$" + (assertCount++), + new GroupThenAssert<>(checkerFn, rewindowingStrategy, paneExtractor)); return this; } @@ -484,13 +581,17 @@ private static class PCollectionSingletonIterableAssert implements IterableAs private final PCollection> actual; private final Coder elementCoder; private final AssertionWindows rewindowingStrategy; + private final SimpleFunction>>, Iterable>> + paneExtractor; public PCollectionSingletonIterableAssert(PCollection> actual) { - this(actual, IntoGlobalWindow.>of()); + this(actual, IntoGlobalWindow.>of(), PaneExtractors.>onlyPane()); } public PCollectionSingletonIterableAssert( - PCollection> actual, AssertionWindows rewindowingStrategy) { + PCollection> actual, + AssertionWindows rewindowingStrategy, + SimpleFunction>>, Iterable>> paneExtractor) { this.actual = actual; @SuppressWarnings("unchecked") @@ -498,15 +599,37 @@ public PCollectionSingletonIterableAssert( this.elementCoder = typedCoder; this.rewindowingStrategy = rewindowingStrategy; + this.paneExtractor = paneExtractor; } @Override public PCollectionSingletonIterableAssert inWindow(BoundedWindow window) { + return withPanes(window, PaneExtractors.>allPanes()); + } + + @Override + public PCollectionSingletonIterableAssert inFinalPane(BoundedWindow window) { + return withPanes(window, PaneExtractors.>finalPane()); + } + + @Override + public PCollectionSingletonIterableAssert inOnTimePane(BoundedWindow window) { + return withPanes(window, PaneExtractors.>onTimePane()); + } + + @Override + public PCollectionSingletonIterableAssert inCombinedNonLatePanes(BoundedWindow window) { + return withPanes(window, PaneExtractors.>nonLatePanes()); + } + + private PCollectionSingletonIterableAssert withPanes( + BoundedWindow window, + SimpleFunction>>, Iterable>> paneExtractor) { @SuppressWarnings({"unchecked", "rawtypes"}) Coder windowCoder = (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(); return new PCollectionSingletonIterableAssert<>( - actual, IntoStaticWindows.>of(windowCoder, window)); + actual, IntoStaticWindows.>of(windowCoder, window), paneExtractor); } @Override @@ -540,7 +663,7 @@ public PCollectionSingletonIterableAssert satisfies( SerializableFunction, Void> checkerFn) { actual.apply( "DataflowAssert$" + (assertCount++), - new GroupThenAssertForSingleton<>(checkerFn, rewindowingStrategy)); + new GroupThenAssertForSingleton<>(checkerFn, rewindowingStrategy, paneExtractor)); return this; } @@ -560,23 +683,26 @@ private static class PCollectionViewAssert implements SingletonAss private final PCollection actual; private final PTransform, PCollectionView> view; private final AssertionWindows rewindowActuals; + private final SimpleFunction>, Iterable> paneExtractor; private final Coder coder; protected PCollectionViewAssert( PCollection actual, PTransform, PCollectionView> view, Coder coder) { - this(actual, view, IntoGlobalWindow.of(), coder); + this(actual, view, IntoGlobalWindow.of(), PaneExtractors.onlyPane(), coder); } private PCollectionViewAssert( PCollection actual, PTransform, PCollectionView> view, AssertionWindows rewindowActuals, + SimpleFunction>, Iterable> paneExtractor, Coder coder) { this.actual = actual; this.view = view; this.rewindowActuals = rewindowActuals; + this.paneExtractor = paneExtractor; this.coder = coder; } @@ -590,12 +716,29 @@ public Coder getCoder() { return coder; } - public PCollectionViewAssert inWindow(BoundedWindow window) { + public PCollectionViewAssert inOnlyPane(BoundedWindow window) { + return inPane(window, PaneExtractors.onlyPane()); + } + + @Override + public PCollectionViewAssert inFinalPane(BoundedWindow window) { + return inPane(window, PaneExtractors.finalPane()); + } + + @Override + public PCollectionViewAssert inOnTimePane(BoundedWindow window) { + return inPane(window, PaneExtractors.onTimePane()); + } + + private PCollectionViewAssert inPane( + BoundedWindow window, + SimpleFunction>, Iterable> paneExtractor) { return new PCollectionViewAssert<>( actual, view, IntoStaticWindows.of( (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(), window), + paneExtractor, coder); } @@ -622,7 +765,7 @@ public PCollectionViewAssert satisfies( .apply( "DataflowAssert$" + (assertCount++), new OneSideInputAssert( - CreateActual.from(actual, rewindowActuals, view), + CreateActual.from(actual, rewindowActuals, paneExtractor, view), rewindowActuals.windowDummy(), checkerFn)); return this; @@ -672,21 +815,25 @@ private static class CreateActual private final transient PCollection actual; private final transient AssertionWindows rewindowActuals; + private final transient SimpleFunction>, Iterable> extractPane; private final transient PTransform, PCollectionView> actualView; public static CreateActual from( PCollection actual, AssertionWindows rewindowActuals, + SimpleFunction>, Iterable> extractPane, PTransform, PCollectionView> actualView) { - return new CreateActual<>(actual, rewindowActuals, actualView); + return new CreateActual<>(actual, rewindowActuals, extractPane, actualView); } private CreateActual( PCollection actual, AssertionWindows rewindowActuals, + SimpleFunction>, Iterable> extractPane, PTransform, PCollectionView> actualView) { this.actual = actual; this.rewindowActuals = rewindowActuals; + this.extractPane = extractPane; this.actualView = actualView; } @@ -695,6 +842,10 @@ public PCollectionView apply(PBegin input) { final Coder coder = actual.getCoder(); return actual .apply("FilterActuals", rewindowActuals.prepareActuals()) + .apply("GatherPanes", GatherAllPanes.globally()) + .apply("ExtractPane", MapElements.via(extractPane)) + .setCoder(IterableCoder.of(actual.getCoder())) + .apply(Flatten.iterables()) .apply("RewindowActuals", rewindowActuals.windowActuals()) .apply( ParDo.of( @@ -835,18 +986,22 @@ public static class GroupThenAssert extends PTransform, PDone> implements Serializable { private final SerializableFunction, Void> checkerFn; private final AssertionWindows rewindowingStrategy; + private final SimpleFunction>, Iterable> paneExtractor; private GroupThenAssert( - SerializableFunction, Void> checkerFn, AssertionWindows rewindowingStrategy) { + SerializableFunction, Void> checkerFn, + AssertionWindows rewindowingStrategy, + SimpleFunction>, Iterable> paneExtractor) { this.checkerFn = checkerFn; this.rewindowingStrategy = rewindowingStrategy; + this.paneExtractor = paneExtractor; } @Override public PDone apply(PCollection input) { input .apply("GroupGlobally", new GroupGlobally(rewindowingStrategy)) - .apply("GetOnlyPane", ParDo.of(new ExtractOnlyPane())) + .apply("GetPane", MapElements.via(paneExtractor)) .setCoder(IterableCoder.of(input.getCoder())) .apply("RunChecks", ParDo.of(new GroupedValuesCheckerDoFn<>(checkerFn))); @@ -862,18 +1017,23 @@ public static class GroupThenAssertForSingleton extends PTransform>, PDone> implements Serializable { private final SerializableFunction, Void> checkerFn; private final AssertionWindows rewindowingStrategy; + private final SimpleFunction>>, Iterable>> + paneExtractor; private GroupThenAssertForSingleton( - SerializableFunction, Void> checkerFn, AssertionWindows rewindowingStrategy) { + SerializableFunction, Void> checkerFn, + AssertionWindows rewindowingStrategy, + SimpleFunction>>, Iterable>> paneExtractor) { this.checkerFn = checkerFn; this.rewindowingStrategy = rewindowingStrategy; + this.paneExtractor = paneExtractor; } @Override public PDone apply(PCollection> input) { input .apply("GroupGlobally", new GroupGlobally>(rewindowingStrategy)) - .apply("GetOnlyPane", ParDo.of(new ExtractOnlyPane>())) + .apply("GetPane", MapElements.via(paneExtractor)) .setCoder(IterableCoder.of(input.getCoder())) .apply("RunChecks", ParDo.of(new SingletonCheckerDoFn<>(checkerFn))); @@ -956,23 +1116,6 @@ public void processElement(ProcessContext c) { } } - private static class ExtractOnlyPane extends DoFn>, Iterable> { - @Override - public void processElement(ProcessContext c) throws Exception { - List outputs = new ArrayList<>(); - for (WindowedValue value : c.element()) { - checkState( - value.getPane().isFirst() && value.getPane().isLast(), - "Expected elements to be produced by a trigger that fires at most once, but got" - + "a value in a pane that is %s. Actual Pane Info: %s", - value.getPane().isFirst() ? "not the last pane" : "not the first pane", - value.getPane()); - outputs.add(value.getValue()); - } - c.output(outputs); - } - } - /** * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of * the single iterable element of the input {@link PCollection} and adjusts counters and diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java new file mode 100644 index 0000000000..94f6505a6c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TypeDescriptor; + +import java.util.ArrayList; +import java.util.List; + +/** + * {@link PTransform PTransforms} which take an {@link Iterable} of {@link WindowedValue + * WindowedValues} and outputs an {@link Iterable} of all values in the specified pane, dropping the + * {@link WindowedValue} metadata. + * + *

            Although all of the method signatures return SimpleFunction, users should ensure to set the + * coder of any output {@link PCollection}, as appropriate {@link TypeDescriptor TypeDescriptors} + * cannot be obtained when the extractor is created. + */ +final class PaneExtractors { + private PaneExtractors() { + } + + static SimpleFunction>, Iterable> onlyPane() { + return new ExtractOnlyPane<>(); + } + + static SimpleFunction>, Iterable> onTimePane() { + return new ExtractOnTimePane<>(); + } + + static SimpleFunction>, Iterable> finalPane() { + return new ExtractFinalPane<>(); + } + + static SimpleFunction>, Iterable> nonLatePanes() { + return new ExtractNonLatePanes<>(); + } + + static SimpleFunction>, Iterable> allPanes() { + return new ExtractAllPanes<>(); + } + + private static class ExtractOnlyPane + extends SimpleFunction>, Iterable> { + @Override + public Iterable apply(Iterable> input) { + List outputs = new ArrayList<>(); + for (WindowedValue value : input) { + checkState(value.getPane().isFirst() && value.getPane().isLast(), + "Expected elements to be produced by a trigger that fires at most once, but got" + + "a value in a pane that is %s. Actual Pane Info: %s", + value.getPane().isFirst() ? "not the last pane" : "not the first pane", + value.getPane()); + outputs.add(value.getValue()); + } + return outputs; + } + } + + + private static class ExtractOnTimePane + extends SimpleFunction>, Iterable> { + @Override + public Iterable apply(Iterable> input) { + List outputs = new ArrayList<>(); + for (WindowedValue value : input) { + if (value.getPane().getTiming().equals(Timing.ON_TIME)) { + outputs.add(value.getValue()); + } + } + return outputs; + } + } + + + private static class ExtractFinalPane + extends SimpleFunction>, Iterable> { + @Override + public Iterable apply(Iterable> input) { + List outputs = new ArrayList<>(); + for (WindowedValue value : input) { + if (value.getPane().isLast()) { + outputs.add(value.getValue()); + } + } + return outputs; + } + } + + + private static class ExtractAllPanes + extends SimpleFunction>, Iterable> { + @Override + public Iterable apply(Iterable> input) { + List outputs = new ArrayList<>(); + for (WindowedValue value : input) { + outputs.add(value.getValue()); + } + return outputs; + } + } + + + private static class ExtractNonLatePanes + extends SimpleFunction>, Iterable> { + @Override + public Iterable apply(Iterable> input) { + List outputs = new ArrayList<>(); + for (WindowedValue value : input) { + if (value.getPane().getTiming() != PaneInfo.Timing.LATE) { + outputs.add(value.getValue()); + } + } + return outputs; + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java index 7b019de214..4802f99f32 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java @@ -285,10 +285,10 @@ public void testWindowedIsEqualTo() throws Exception { TimestampedValue.of(22, new Instant(-250L)))) .apply(Window.into(FixedWindows.of(Duration.millis(500L)))); DataflowAssert.thatSingleton(pcollection) - .inWindow(new IntervalWindow(new Instant(0L), new Instant(500L))) + .inOnlyPane(new IntervalWindow(new Instant(0L), new Instant(500L))) .isEqualTo(43); DataflowAssert.thatSingleton(pcollection) - .inWindow(new IntervalWindow(new Instant(-500L), new Instant(0L))) + .inOnlyPane(new IntervalWindow(new Instant(-500L), new Instant(0L))) .isEqualTo(22); pipeline.run(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java new file mode 100644 index 0000000000..4fb3848df8 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java @@ -0,0 +1,321 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; +import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.common.collect.ImmutableList; + +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link PaneExtractors}. + */ +@RunWith(JUnit4.class) +public class PaneExtractorsTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Test + public void onlyPaneNoFiring() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.onlyPane(); + Iterable> noFiring = + ImmutableList.of( + WindowedValue.valueInGlobalWindow(9), WindowedValue.valueInEmptyWindows(19)); + assertThat(extractor.apply(noFiring), containsInAnyOrder(9, 19)); + } + + @Test + public void onlyPaneOnlyOneFiring() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.onlyPane(); + Iterable> onlyFiring = + ImmutableList.of( + WindowedValue.of( + 2, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), + WindowedValue.of( + 1, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + assertThat(extractor.apply(onlyFiring), containsInAnyOrder(2, 1)); + } + + @Test + public void onlyPaneMultiplePanesFails() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.onlyPane(); + Iterable> multipleFiring = + ImmutableList.of( + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY)), + WindowedValue.of( + 2, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 1, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L))); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage("trigger that fires at most once"); + extractor.apply(multipleFiring); + } + + @Test + public void onTimePane() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.onTimePane(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 2, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L))); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4)); + } + + @Test + public void onTimePaneOnlyEarlyAndLate() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.onTimePane(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 2, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 1, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY))); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4)); + } + + @Test + public void finalPane() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.finalPane(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, true, Timing.LATE, 2L, 1L)), + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 1, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY))); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(8)); + } + + @Test + public void finalPaneNoExplicitFinalEmpty() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.finalPane(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 1, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY))); + + assertThat(extractor.apply(onlyOnTime), emptyIterable()); + } + + @Test + public void nonLatePanesSingleOnTime() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.nonLatePanes(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), + WindowedValue.of( + 4, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), + WindowedValue.of( + 2, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4, 8)); + } + + @Test + public void nonLatePanesSingleEarly() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.nonLatePanes(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY)), + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY))); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(4, 8)); + } + + @Test + public void allPanesSingleLate() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.nonLatePanes(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.LATE, 0L, 0L))); + + assertThat(extractor.apply(onlyOnTime), emptyIterable()); + } + + @Test + public void nonLatePanesMultiplePanes() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.nonLatePanes(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), + WindowedValue.of(7, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING), + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 1, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY))); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(4, 1, 7)); + } + + @Test + public void allPanesSinglePane() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.allPanes(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), + WindowedValue.of( + 4, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), + WindowedValue.of( + 2, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING)); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4, 8)); + } + + @Test + public void allPanesMultiplePanes() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.allPanes(); + Iterable> onlyOnTime = + ImmutableList.of( + WindowedValue.of( + 8, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), + WindowedValue.of( + 4, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), + WindowedValue.of( + 1, + new Instant(0L), + GlobalWindow.INSTANCE, + PaneInfo.createPane(true, false, Timing.EARLY))); + + assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(4, 8, 1)); + } + + @Test + public void allPanesEmpty() { + SerializableFunction>, Iterable> extractor = + PaneExtractors.allPanes(); + Iterable> noPanes = ImmutableList.of(); + + assertThat(extractor.apply(noPanes), emptyIterable()); + } +} From e3eeac0639528ba3ed60a17d797d9abfcf9573e7 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 19 Aug 2016 16:08:00 -0700 Subject: [PATCH 529/751] Reimplement DataflowAssert#thatIterable Required for backwards compatibility reasons. This implementation is deprecated in favor of DataflowAssert#that, DataflowAssert#thatSingletonIterable, and DataflowAssert#thatSingleton, all of which are equally capable but more powerful. --- .../dataflow/sdk/testing/DataflowAssert.java | 137 +++++++++++++++++- .../sdk/testing/DataflowAssertTest.java | 13 ++ 2 files changed, 148 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java index b0e4630852..ea0f79de0a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java @@ -22,6 +22,7 @@ import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import com.google.cloud.dataflow.sdk.coders.IterableCoder; @@ -60,6 +61,8 @@ import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.base.Optional; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -344,11 +347,13 @@ public static IterableAssert thatSingletonIterable( /** * Constructs an {@link IterableAssert} for the value of the provided {@link PCollectionView}. + * + * @deprecated use {@link #thatSingletonIterable(PCollection)}, + * {@link #thatSingleton(PCollection)} or {@link #that(PCollection)} instead. */ @Deprecated public static IterableAssert thatIterable(PCollectionView> actual) { - // TODO Before PR complete. Required for backwards compatibility purposes. - return null; + return new PCollectionViewIterableAssert(actual); } /** @@ -675,6 +680,134 @@ private PCollectionSingletonIterableAssert satisfies( } } + private static class PCollectionViewIterableAssert implements IterableAssert { + private final PCollectionView> actual; + private Optional> valueCoder; + + private PCollectionViewIterableAssert( + PCollectionView> actual) { + this.actual = actual; + valueCoder = Optional.absent(); + } + + @Override + public IterableAssert setCoder(Coder coderOrNull) { + valueCoder = Optional.fromNullable(coderOrNull); + return this; + } + + @Override + public Coder getCoder() { + if (valueCoder.isPresent()) { + return valueCoder.get(); + } else { + throw new IllegalArgumentException("Blah"); + } + } + + @Override + public IterableAssert inWindow(BoundedWindow window) { + throw new UnsupportedOperationException( + "IterableAssert of an PCollectionView does not support windowed assertions"); + } + + @Override + public IterableAssert inFinalPane(BoundedWindow window) { + // TODO: Can maybe be supported? + throw new UnsupportedOperationException( + "IterableAssert of an PCollectionView does not support windowed assertions"); + } + + @Override + public IterableAssert inOnTimePane(BoundedWindow window) { + throw new UnsupportedOperationException( + "IterableAssert of an PCollectionView does not support windowed assertions"); + } + + @Override + public IterableAssert inCombinedNonLatePanes(BoundedWindow window) { + throw new UnsupportedOperationException( + "IterableAssert of an PCollectionView does not support windowed assertions"); + } + + @Override + public IterableAssert containsInAnyOrder(T... expectedElements) { + return containsInAnyOrder(ImmutableList.copyOf(expectedElements)); + } + + @Override + public IterableAssert containsInAnyOrder(Iterable expectedElements) { + return satisfies(new AssertContainsInAnyOrderRelation(), expectedElements); + } + + private IterableAssert satisfies( + AssertRelation, Iterable> relation, + Iterable expectedElements) { + Coder elemCoder; + if (valueCoder.isPresent()) { + elemCoder = valueCoder.get(); + } else { + try { + elemCoder = + Create.of(expectedElements).getDefaultOutputCoder(actual.getPipeline().begin()); + } catch (CannotProvideCoderException e) { + throw new IllegalArgumentException( + "Attempted to infer the Coder of an IterableAssert, but no Coder was explicitly set " + + "and no coder could be inferred", e); + } + } + return satisfies(new CheckRelationAgainstExpected>( + relation, expectedElements, IterableCoder.of(elemCoder))); + } + + @Override + public IterableAssert empty() { + return containsInAnyOrder(); + } + + @Override + public IterableAssert satisfies(SerializableFunction, Void> checkerFn) { + PTransform>> identity = + new PTransform>>() { + @Override + public PCollectionView> apply(PBegin input) { + return actual; + } + }; + actual.getPipeline() + .apply(nextAssertionName(), + new OneSideInputAssert<>( + identity, + Window.into(new GlobalWindows()), + checkerFn)); + return this; + } + + /** + * @throws UnsupportedOperationException always + * @deprecated {@link Object#equals(Object)} is not supported on DataflowAssert objects. + * If you meant to test object equality, use a variant of {@link #containsInAnyOrder} + * instead. + */ + @Deprecated + @Override + public boolean equals(Object o) { + throw new UnsupportedOperationException( + "If you meant to test object equality, use .containsInAnyOrder instead."); + } + + /** + * @throws UnsupportedOperationException always. + * @deprecated {@link Object#hashCode()} is not supported on DataflowAssert objects. + */ + @Deprecated + @Override + public int hashCode() { + throw new UnsupportedOperationException( + String.format("%s.hashCode() is not supported.", IterableAssert.class.getSimpleName())); + } + } + /** * An assertion about the contents of a {@link PCollection} when it is viewed as a single value * of type {@code ViewT}. This requires side input support from the runner. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java index 4802f99f32..c055d2d819 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java @@ -29,6 +29,7 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.View; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; @@ -36,6 +37,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.collect.Iterables; @@ -201,6 +203,17 @@ public Void apply(Iterable contents) { pipeline.run(); } + @Test + @SuppressWarnings("deprecation") + public void testContainsInAnyOrderIterableView() { + Pipeline p = TestPipeline.create(); + PCollectionView> iterableView = + p.apply(Create.of(1, 2, 3, 4)).apply(View.asIterable()); + + DataflowAssert.thatIterable(iterableView).containsInAnyOrder(4, 3, 2, 1); + p.run(); + } + /** * Test that we throw an error at pipeline construction time when the user mistakenly uses * {@code DataflowAssert.thatSingleton().equals()} instead of the test method {@code .isEqualTo}. From 4775bcb8f4455267d0c6cee8e08b4826a209cb3f Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Mon, 22 Aug 2016 14:18:29 -0700 Subject: [PATCH 530/751] BoundedReader: update the range last of all (#390) Reorders the code in some splitAtFraction calls so that the rangeTracker update is the last thing (besides assignment) in the function. This avoids a potential issue if creating the primary or residual sources happens to throw an exception. --- .../com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java | 6 +++--- .../google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java index 8818974712..415be15a22 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java @@ -366,13 +366,13 @@ public final synchronized OffsetBasedSource splitAtFraction(double fraction) LOG.debug( "Proposing to split OffsetBasedReader {} at fraction {} (offset {})", rangeTracker, fraction, splitOffset); - if (!rangeTracker.trySplitAtPosition(splitOffset)) { - return null; - } long start = source.getStartOffset(); long end = source.getEndOffset(); OffsetBasedSource primary = source.createSourceForSubrange(start, splitOffset); OffsetBasedSource residual = source.createSourceForSubrange(splitOffset, end); + if (!rangeTracker.trySplitAtPosition(splitOffset)) { + return null; + } this.source = primary; return residual; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index bd4b3fd5e5..e1a46e0584 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -872,11 +872,11 @@ public final synchronized BigtableSource splitAtFraction(double fraction) { } logger.debug( "Proposing to split {} at fraction {} (key {})", rangeTracker, fraction, splitKey); + BigtableSource primary = source.withEndKey(splitKey); + BigtableSource residual = source.withStartKey(splitKey); if (!rangeTracker.trySplitAtPosition(splitKey)) { return null; } - BigtableSource primary = source.withEndKey(splitKey); - BigtableSource residual = source.withStartKey(splitKey); this.source = primary; return residual; } From e7ec5f7d3f0634c3d3139e6fbba763b30cca97ea Mon Sep 17 00:00:00 2001 From: sammcveety Date: Mon, 22 Aug 2016 17:41:02 -0400 Subject: [PATCH 531/751] Add template runner (#346) * Add ValueProvider * Update DataflowPipelineRunner.java * Update DataflowPipelineRunnerHooks.java * Update DataflowPipelineRunnerHooks.java * Create TemplatingDataflowPipelineRunner.java * Add test.' * update * add test * Fix messages * Remove ValueProvider * Fix formatting. * Remove dupe * Fix typo * Fix style errors. * Fix style errors. * Fix things * fixes * Update TemplatingDataflowPipelineRunnerTest.java * Do not return null, return a useless Job instead. * Update TemplatingDataflowPipelineRunner.java * Update TemplatingDataflowPipelineRunner.java --- .../sdk/runners/DataflowPipelineRunner.java | 46 ++++-- .../runners/DataflowPipelineRunnerHooks.java | 10 ++ .../TemplatingDataflowPipelineRunner.java | 154 ++++++++++++++++++ .../TemplatingDataflowPipelineRunnerTest.java | 137 ++++++++++++++++ 4 files changed, 336 insertions(+), 11 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f2030e5f38..3f8b1ed3f7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -110,6 +110,7 @@ import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; import com.google.cloud.dataflow.sdk.util.InstanceBuilder; +import com.google.cloud.dataflow.sdk.util.MimeTypes; import com.google.cloud.dataflow.sdk.util.MonitoringUtil; import com.google.cloud.dataflow.sdk.util.PCollectionViews; import com.google.cloud.dataflow.sdk.util.PathValidator; @@ -159,7 +160,6 @@ import org.slf4j.LoggerFactory; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -168,6 +168,8 @@ import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -607,16 +609,10 @@ public DataflowPipelineJob run(Pipeline pipeline) { } if (!Strings.isNullOrEmpty(options.getDataflowJobFile())) { - try (PrintWriter printWriter = new PrintWriter( - new File(options.getDataflowJobFile()))) { - String workSpecJson = DataflowPipelineTranslator.jobToString(newJob); - printWriter.print(workSpecJson); - LOG.info("Printed workflow specification to {}", options.getDataflowJobFile()); - } catch (IllegalStateException ex) { - LOG.warn("Cannot translate workflow spec to json for debug."); - } catch (FileNotFoundException ex) { - LOG.warn("Cannot create workflow spec output file."); - } + runJobFileHooks(newJob); + } + if (hooks != null && !hooks.shouldActuallyRunJob()) { + return null; } String jobIdToUpdate = null; @@ -751,6 +747,34 @@ public void leaveCompositeTransform(TransformTreeNode node) { } } + private void runJobFileHooks(Job newJob) { + try { + WritableByteChannel writer = + IOChannelUtils.create(options.getDataflowJobFile(), MimeTypes.TEXT); + PrintWriter printWriter = new PrintWriter(Channels.newOutputStream(writer)); + String workSpecJson = DataflowPipelineTranslator.jobToString(newJob); + printWriter.print(workSpecJson); + printWriter.flush(); + printWriter.close(); + LOG.info("Printed job specification to {}", options.getDataflowJobFile()); + } catch (IllegalStateException ex) { + String error = "Cannot translate workflow spec to JSON."; + if (hooks != null && hooks.failOnJobFileWriteFailure()) { + throw new RuntimeException(error, ex); + } else { + LOG.warn(error, ex); + } + } catch (IOException ex) { + String error = + String.format("Cannot create output file at {}", options.getDataflowJobFile()); + if (hooks != null && hooks.failOnJobFileWriteFailure()) { + throw new RuntimeException(error, ex); + } else { + LOG.warn(error, ex); + } + } + } + /** * Returns true if the passed in {@link PCollection} needs to be materialiazed using * an indexed format. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java index b9a02935de..982f631da6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java @@ -34,4 +34,14 @@ public class DataflowPipelineRunnerHooks { * to change the environment with which their job executes on the service. */ public void modifyEnvironmentBeforeSubmission(Environment environment) {} + + /** Allows the user to specify whether the job should actually be executed. */ + public boolean shouldActuallyRunJob() { + return true; + } + + /** Specifies whether the runner should fail if it fails to write to a job file. */ + public boolean failOnJobFileWriteFailure() { + return false; + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java new file mode 100644 index 0000000000..d01507be92 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.api.services.dataflow.Dataflow; +import com.google.auto.service.AutoService; +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.MonitoringUtil; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.TimeUnit; + +/** + * A {@link PipelineRunner} that's like {@link DataflowPipelineRunner} but only stores a template of + * a job. + * + *

            Requires that {@link getDataflowJobFile} is set. + */ +public class TemplatingDataflowPipelineRunner extends PipelineRunner { + private static final Logger LOG = LoggerFactory.getLogger(TemplatingDataflowPipelineRunner.class); + + private final DataflowPipelineRunner dataflowPipelineRunner; + private final PipelineOptions options; + + protected TemplatingDataflowPipelineRunner(DataflowPipelineRunner internalRunner, + PipelineOptions options) { + this.dataflowPipelineRunner = internalRunner; + this.options = options; + } + + private static class TemplateHooks extends DataflowPipelineRunnerHooks { + @Override + public boolean shouldActuallyRunJob() { + return false; + } + + @Override + public boolean failOnJobFileWriteFailure() { + return true; + } + } + + /** Constructs a runner from the provided options. */ + public static TemplatingDataflowPipelineRunner fromOptions(PipelineOptions options) { + DataflowPipelineDebugOptions dataflowOptions = + PipelineOptionsValidator.validate(DataflowPipelineDebugOptions.class, options); + DataflowPipelineRunner dataflowPipelineRunner = + DataflowPipelineRunner.fromOptions(dataflowOptions); + checkArgument(!Strings.isNullOrEmpty(dataflowOptions.getDataflowJobFile()), + "--dataflowJobFile must be present to create a template."); + + return new TemplatingDataflowPipelineRunner(dataflowPipelineRunner, options); + } + + private static class TemplateJob extends DataflowPipelineJob { + private static final String ERROR = + "The result of template creation should not be used."; + + TemplateJob() { + super(null, null, null, null); + } + + @Override + public String getJobId() { + throw new UnsupportedOperationException(ERROR); + } + + @Override + public String getProjectId() { + throw new UnsupportedOperationException(ERROR); + } + + @Override + public DataflowPipelineJob getReplacedByJob() { + throw new UnsupportedOperationException(ERROR); + } + + @Override + public Dataflow getDataflowClient() { + throw new UnsupportedOperationException(ERROR); + } + + @Override + public State waitToFinish( + long timeToWait, + TimeUnit timeUnit, + MonitoringUtil.JobMessagesHandler messageHandler) { + throw new UnsupportedOperationException(ERROR); + } + + @Override + public void cancel() { + throw new UnsupportedOperationException(ERROR); + } + + @Override + public State getState() { + throw new UnsupportedOperationException(ERROR); + } + } + + @Override + public DataflowPipelineJob run(Pipeline p) { + dataflowPipelineRunner.setHooks(new TemplateHooks()); + final DataflowPipelineJob job = dataflowPipelineRunner.run(p); + LOG.info("Template successfully created."); + return new TemplateJob(); + } + + @Override + public OutputT apply( + PTransform transform, InputT input) { + // We delegate graph building to the inner runner. + return dataflowPipelineRunner.apply(transform, input); + } + + @Override + public String toString() { + return "TemplatingDataflowPipelineRunner"; + } + + /** Register the {@link TemplatingDataflowPipelineRunner}. */ + @AutoService(PipelineRunnerRegistrar.class) + public static class Runner implements PipelineRunnerRegistrar { + @Override + public Iterable>> getPipelineRunners() { + return ImmutableList + .>>of(TemplatingDataflowPipelineRunner.class); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java new file mode 100644 index 0000000000..bc9c00946e --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; +import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.util.NoopPathValidator; +import com.google.cloud.dataflow.sdk.util.TestCredential; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.File; + +/** + * Tests for TemplatingDataflowPipelineRunner. + */ +@RunWith(JUnit4.class) +public class TemplatingDataflowPipelineRunnerTest { + + @Mock private DataflowPipelineJob mockJob; + @Mock private DataflowPipelineRunner mockRunner; + + @Rule + public ExpectedLogs expectedLogs = ExpectedLogs.none(TemplatingDataflowPipelineRunner.class); + + @Rule + public ExpectedException expectedThrown = ExpectedException.none(); + + @Rule + public final TemporaryFolder tmpDir = new TemporaryFolder(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(mockJob.getProjectId()).thenReturn("project"); + when(mockJob.getJobId()).thenReturn("job"); + when(mockRunner.run(isA(Pipeline.class))).thenReturn(mockJob); + } + + /** + * Tests that the {@link TemplatingDataflowPipelineRunner} returns normally when the runner is + * successfully run. + */ + @Test + public void testLoggedCompletion() throws Exception { + File existingFile = tmpDir.newFile(); + TestDataflowPipelineOptions options = + PipelineOptionsFactory.as(TestDataflowPipelineOptions.class); + options.setProject(mockJob.getProjectId()); + options.setDataflowJobFile(existingFile.getPath()); + TemplatingDataflowPipelineRunner runner = + new TemplatingDataflowPipelineRunner(mockRunner, options); + runner.run(DirectPipeline.createForTest()); + expectedLogs.verifyInfo("Template successfully created"); + } + + + /** + * Tests that the {@link TemplatingDataflowPipelineRunner} returns normally when the runner is + * successfully run. + */ + @Test + public void testFullCompletion() throws Exception { + File existingFile = tmpDir.newFile(); + DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setJobName("TestJobName"); + options.setGcpCredential(new TestCredential()); + options.setPathValidatorClass(NoopPathValidator.class); + options.setProject("test-project"); + options.setDataflowJobFile(existingFile.getPath()); + options.setTempLocation(tmpDir.getRoot().getPath()); + TemplatingDataflowPipelineRunner runner = + TemplatingDataflowPipelineRunner.fromOptions(options); + runner.run(DirectPipeline.createForTest()); + } + + /** + * Tests that the {@link TemplatingDataflowPipelineRunner} throws the appropriate exception when + * an output file is not writable. + */ + @Test + public void testLoggedErrorForFile() throws Exception { + DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setJobName("TestJobName"); + options.setDataflowJobFile("//bad/path"); + options.setProject("test-project"); + options.setTempLocation(tmpDir.getRoot().getPath()); + options.setGcpCredential(new TestCredential()); + options.setPathValidatorClass(NoopPathValidator.class); + TemplatingDataflowPipelineRunner runner = + TemplatingDataflowPipelineRunner.fromOptions(options); + + expectedThrown.expectMessage("Cannot create output file at"); + expectedThrown.expect(RuntimeException.class); + runner.run(DirectPipeline.createForTest()); + } + + @Test + public void testToString() { + DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setJobName("TestJobName"); + options.setDataflowJobFile("foo"); + options.setProject("test-project"); + options.setTempLocation("gs://test/temp/location"); + options.setGcpCredential(new TestCredential()); + options.setPathValidatorClass(NoopPathValidator.class); + assertEquals("TemplatingDataflowPipelineRunner", + TemplatingDataflowPipelineRunner.fromOptions(options).toString()); + } +} From ee25e238e65fc71b5db7ba0dace4b45d19dbf07a Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Mon, 22 Aug 2016 14:42:33 -0700 Subject: [PATCH 532/751] Run rejected BigQueryTableInserter tasks in the calling thread Otherwise, even temporary bursts of data will cause failures as the thread pool's queue is saturated. --- .../cloud/dataflow/sdk/util/BigQueryTableInserter.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java index 7b749a164e..aa992c52f6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java @@ -80,8 +80,12 @@ public class BigQueryTableInserter { private final TableReference defaultRef; private final long maxRowsPerBatch; - private static final ExecutorService executor = MoreExecutors.getExitingExecutorService( - (ThreadPoolExecutor) Executors.newFixedThreadPool(100), 10, TimeUnit.SECONDS); + private static final ExecutorService executor; + static { + ThreadPoolExecutor tempExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(100); + tempExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + executor = MoreExecutors.getExitingExecutorService(tempExecutor, 10, TimeUnit.SECONDS); + } /** * Constructs a new row inserter. From 5e513737282e0ae253f44cd10f987a380d89d182 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Mon, 22 Aug 2016 19:12:11 -0700 Subject: [PATCH 533/751] Datastore Sink support for writing Mutations. (#395) --- .../dataflow/sdk/io/datastore/V1Beta3.java | 253 ++++++++++++++---- .../sdk/io/datastore/V1Beta3Test.java | 211 ++++++++++++--- 2 files changed, 378 insertions(+), 86 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java index 32fd1a2061..f3109ae18a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java @@ -22,6 +22,7 @@ import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; import static com.google.datastore.v1beta3.QueryResultBatch.MoreResultsType.NOT_FINISHED; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeDelete; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeUpsert; @@ -38,8 +39,10 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.Flatten; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.MapElements; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; import com.google.cloud.dataflow.sdk.transforms.Values; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; @@ -57,6 +60,7 @@ import com.google.datastore.v1beta3.EntityResult; import com.google.datastore.v1beta3.Key; import com.google.datastore.v1beta3.Key.PathElement; +import com.google.datastore.v1beta3.Mutation; import com.google.datastore.v1beta3.PartitionId; import com.google.datastore.v1beta3.Query; import com.google.datastore.v1beta3.QueryResultBatch; @@ -82,7 +86,7 @@ import javax.annotation.Nullable; /** - *

            {@link V1Beta3} provides an API to Read and Write {@link PCollection PCollections} of + *

            {@link V1Beta3} provides an API to Read, Write and Delete {@link PCollection PCollections} of * Google Cloud Datastore version v1beta3 * {@link Entity} objects. * @@ -127,7 +131,25 @@ * p.run(); * }

            * - *

            {@link Entity Entities} in the {@code PCollection} to be written must have complete + *

            To delete a {@link PCollection} of {@link Entity Entities} from Datastore, use + * {@link V1Beta3#deleteEntity()}, specifying the Cloud Datastore project to write to: + * + *

             {@code
            + * PCollection entities = ...;
            + * entities.apply(DatastoreIO.v1beta3().deleteEntity().withProjectId(projectId));
            + * p.run();
            + * } 
            + * + *

            To delete entities associated with a {@link PCollection} of {@link Key Keys} from Datastore, + * use {@link V1Beta3#deleteKey}, specifying the Cloud Datastore project to write to: + * + *

             {@code
            + * PCollection entities = ...;
            + * entities.apply(DatastoreIO.v1beta3().deleteKey().withProjectId(projectId));
            + * p.run();
            + * } 
            + * + *

            {@link Entity Entities} in the {@code PCollection} to be written or deleted must have complete * {@link Key Keys}. Complete {@code Keys} specify the {@code name} and {@code id} of the * {@code Entity}, where incomplete {@code Keys} do not. A {@code namespace} other than * {@code projectId} default may be used by specifying it in the {@code Entity} {@code Keys}. @@ -137,9 +159,9 @@ * keyBuilder.getPartitionIdBuilder().setNamespace(namespace); * }

            * - *

            {@code Entities} will be committed as upsert (update or insert) mutations. Please read - * Entities, Properties, and - * Keys for more information about {@code Entity} keys. + *

            {@code Entities} will be committed as upsert (update or insert) or delete mutations. Please + * read Entities, Properties, + * and Keys for more information about {@code Entity} keys. * *

            Permissions

            * Permission requirements depend on the {@code PipelineRunner} that is used to execute the @@ -639,21 +661,34 @@ public Write write() { return new Write(null); } + /** + * Returns an empty {@link DeleteEntity} builder. Configure the destination + * {@code projectId} using {@link DeleteEntity#withProjectId}. + */ + public DeleteEntity deleteEntity() { + return new DeleteEntity(null); + } + + /** + * Returns an empty {@link DeleteKey} builder. Configure the destination + * {@code projectId} using {@link DeleteKey#withProjectId}. + */ + public DeleteKey deleteKey() { + return new DeleteKey(null); + } + /** * A {@link PTransform} that writes {@link Entity} objects to Cloud Datastore. * * @see DatastoreIO */ - public static class Write extends PTransform, PDone> { - @Nullable - private final String projectId; - + public static class Write extends Mutate { /** * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if * it is {@code null} at instantiation time, an error will be thrown. */ - public Write(@Nullable String projectId) { - this.projectId = projectId; + Write(@Nullable String projectId) { + super(projectId, new UpsertFn()); } /** @@ -663,27 +698,99 @@ public Write withProjectId(String projectId) { checkNotNull(projectId, "projectId"); return new Write(projectId); } + } - @Override - public PDone apply(PCollection input) { - input.apply(ParDo.of(new DatastoreWriterFn(projectId))); - return PDone.in(input.getPipeline()); + /** + * A {@link PTransform} that deletes {@link Entity Entities} from Cloud Datastore. + * + * @see DatastoreIO + */ + public static class DeleteEntity extends Mutate { + /** + * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if + * it is {@code null} at instantiation time, an error will be thrown. + */ + DeleteEntity(@Nullable String projectId) { + super(projectId, new DeleteEntityFn()); } - @Override - public void validate(PCollection input) { + /** + * Returns a new {@link DeleteEntity} that deletes entities from the Cloud Datastore for the + * specified project. + */ + public DeleteEntity withProjectId(String projectId) { + checkNotNull(projectId, "projectId"); + return new DeleteEntity(projectId); + } + } + + /** + * A {@link PTransform} that deletes {@link Entity Entities} associated with the given + * {@link Key Keys} from Cloud Datastore. + * + * @see DatastoreIO + */ + public static class DeleteKey extends Mutate { + /** + * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if + * it is {@code null} at instantiation time, an error will be thrown. + */ + DeleteKey(@Nullable String projectId) { + super(projectId, new DeleteKeyFn()); + } + + /** + * Returns a new {@link DeleteKey} that deletes entities from the Cloud Datastore for the + * specified project. + */ + public DeleteKey withProjectId(String projectId) { checkNotNull(projectId, "projectId"); + return new DeleteKey(projectId); } + } + /** + * A {@link PTransform} that writes mutations to Cloud Datastore. + * + *

            It requires a {@link DoFn} that tranforms an object of type {@code T} to a {@link Mutation}. + * {@code T} is usually either an {@link Entity} or a {@link Key} + * Note: Only idempotent Cloud Datastore mutation operations (upsert and delete) should + * be used by the {@code DoFn} provided, as the commits are retried when failures occur. + */ + private abstract static class Mutate extends PTransform, PDone> { @Nullable - public String getProjectId() { - return projectId; + private final String projectId; + /** A function that transforms each {@code T} into a mutation. */ + private final SimpleFunction mutationFn; + + /** + * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if + * it is {@code null} at instantiation time, an error will be thrown. + */ + Mutate(@Nullable String projectId, SimpleFunction mutationFn) { + this.projectId = projectId; + this.mutationFn = checkNotNull(mutationFn); + } + + @Override + public PDone apply(PCollection input) { + input.apply("Convert to Mutation", MapElements.via(mutationFn)) + .apply("Write Mutation to Datastore", ParDo.of(new DatastoreWriterFn(projectId))); + + return PDone.in(input.getPipeline()); + } + + @Override + public void validate(PCollection input) { + checkNotNull(projectId, "projectId"); + checkNotNull(mutationFn, "mutationFn"); } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("projectId", projectId) + .add("mutationFn", mutationFn.getClass().getName()) .toString(); } @@ -692,33 +799,38 @@ public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder .addIfNotNull(DisplayData.item("projectId", projectId) - .withLabel("Output Project")); + .withLabel("Output Project")) + .add(DisplayData.item("mutationFn", mutationFn.getClass()) + .withLabel("Datastore Mutation Function")); + } + + public String getProjectId() { + return projectId; } } /** - * A {@link DoFn} that writes {@link Entity} objects to Cloud Datastore. Entities are written in + * {@link DoFn} that writes {@link Mutation}s to Cloud Datastore. Mutations are written in * batches, where the maximum batch size is {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. - * Entities are committed as upsert mutations (either update if the key already exists, or - * insert if it is a new key). If an entity does not have a complete key (i.e., it has no name - * or id), the bundle will fail. * *

            See - * Datastore: Entities, Properties, and Keys for information about entity keys and entities. + * Datastore: Entities, Properties, and Keys for information about entity keys and mutations. * *

            Commits are non-transactional. If a commit fails because of a conflict over an entity * group, the commit will be retried (up to {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT} - * times). + * times). This means that the mutation operation should be idempotent. Thus, the writer should + * only be used for {code upsert} and {@code delete} mutation operations, as these are the only + * two Cloud Datastore mutations that are idempotent. */ @VisibleForTesting - static class DatastoreWriterFn extends DoFn { + static class DatastoreWriterFn extends DoFn { private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriterFn.class); private final String projectId; private transient Datastore datastore; private final V1Beta3DatastoreFactory datastoreFactory; - // Current batch of entities to be written. - private final List entities = new ArrayList<>(); + // Current batch of mutations to be written. + private final List mutations = new ArrayList<>(); /** * Since a bundle is written in batches, we should retry the commit of a batch in order to * prevent transient errors from causing the bundle to fail. @@ -730,7 +842,7 @@ static class DatastoreWriterFn extends DoFn { */ private static final int INITIAL_BACKOFF_MILLIS = 5000; - public DatastoreWriterFn(String projectId) { + DatastoreWriterFn(String projectId) { this(projectId, new V1Beta3DatastoreFactory()); } @@ -747,30 +859,24 @@ public void startBundle(Context c) { @Override public void processElement(ProcessContext c) throws Exception { - // Verify that the entity to write has a complete key. - if (!isValidKey(c.element().getKey())) { - throw new IllegalArgumentException( - "Entities to be written to the Datastore must have complete keys"); - } - - entities.add(c.element()); - if (entities.size() >= V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT) { + mutations.add(c.element()); + if (mutations.size() >= V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT) { flushBatch(); } } @Override public void finishBundle(Context c) throws Exception { - if (entities.size() > 0) { + if (mutations.size() > 0) { flushBatch(); } } /** - * Writes a batch of entities to Cloud Datastore. + * Writes a batch of mutations to Cloud Datastore. * *

            If a commit fails, it will be retried (up to {@link DatastoreWriterFn#MAX_RETRIES} - * times). All entities in the batch will be committed again, even if the commit was partially + * times). All mutations in the batch will be committed again, even if the commit was partially * successful. If the retry limit is exceeded, the last exception from the Datastore will be * thrown. * @@ -778,7 +884,7 @@ public void finishBundle(Context c) throws Exception { * backing off between retries fails. */ private void flushBatch() throws DatastoreException, IOException, InterruptedException { - LOG.debug("Writing batch of {} entities", entities.size()); + LOG.debug("Writing batch of {} mutations", mutations.size()); Sleeper sleeper = Sleeper.DEFAULT; BackOff backoff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_MILLIS); @@ -786,9 +892,7 @@ private void flushBatch() throws DatastoreException, IOException, InterruptedExc // Batch upsert entities. try { CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); - for (Entity entity: entities) { - commitRequest.addMutations(makeUpsert(entity)); - } + commitRequest.addAllMutations(mutations); commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); datastore.commit(commitRequest.build()); // Break if the commit threw no exception. @@ -804,8 +908,8 @@ private void flushBatch() throws DatastoreException, IOException, InterruptedExc } } } - LOG.debug("Successfully wrote {} entities", entities.size()); - entities.clear(); + LOG.debug("Successfully wrote {} mutations", mutations.size()); + mutations.clear(); } @Override @@ -818,7 +922,7 @@ public void populateDisplayData(Builder builder) { } /** - * Returns true if a Datastore key is complete. A key is complete if its last element + * Returns true if a Datastore key is complete. A key is complete if its last element * has either an id or a name. */ static boolean isValidKey(Key key) { @@ -830,6 +934,51 @@ static boolean isValidKey(Key key) { return (lastElement.getId() != 0 || !lastElement.getName().isEmpty()); } + /** + * A function that constructs an upsert {@link Mutation} from an {@link Entity}. + */ + @VisibleForTesting + static class UpsertFn extends SimpleFunction { + @Override + public Mutation apply(Entity entity) { + // Verify that the entity to write has a complete key. + checkArgument(isValidKey(entity.getKey()), + "Entities to be written to the Datastore must have complete keys:\n%s", entity); + + return makeUpsert(entity).build(); + } + } + + /** + * A function that constructs a delete {@link Mutation} from an {@link Entity}. + */ + @VisibleForTesting + static class DeleteEntityFn extends SimpleFunction { + @Override + public Mutation apply(Entity entity) { + // Verify that the entity to delete has a complete key. + checkArgument(isValidKey(entity.getKey()), + "Entities to be deleted from the Datastore must have complete keys:\n%s", entity); + + return makeDelete(entity.getKey()).build(); + } + } + + /** + * A function that constructs a delete {@link Mutation} from a {@link Key}. + */ + @VisibleForTesting + static class DeleteKeyFn extends SimpleFunction { + @Override + public Mutation apply(Key key) { + // Verify that the entity to delete has a complete key. + checkArgument(isValidKey(key), + "Keys to be deleted from the Datastore must be complete:\n%s", key); + + return makeDelete(key).build(); + } + } + /** * A wrapper factory class for Datastore singleton classes {@link DatastoreFactory} and * {@link QuerySplitter} @@ -840,9 +989,7 @@ static boolean isValidKey(Key key) { @VisibleForTesting static class V1Beta3DatastoreFactory implements Serializable { - /** - * Builds a Datastore client for the given pipeline options and project. - */ + /** Builds a Datastore client for the given pipeline options and project. */ public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { DatastoreOptions.Builder builder = new DatastoreOptions.Builder() @@ -859,9 +1006,7 @@ public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) return DatastoreFactory.get().create(builder.build()); } - /** - * Builds a Datastore {@link QuerySplitter}. - */ + /** Builds a Datastore {@link QuerySplitter}. */ public QuerySplitter getQuerySplitter() { return DatastoreHelper.getQuerySplitter(); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java index b0f97ab63a..8387be6721 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java @@ -21,9 +21,11 @@ import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.QUERY_BATCH_LIMIT; import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.getEstimatedSizeBytes; import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.makeRequest; +import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.isValidKey; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; +import static com.google.datastore.v1beta3.client.DatastoreHelper.makeDelete; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; @@ -44,20 +46,26 @@ import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreWriterFn; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteEntity; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteEntityFn; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteKey; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteKeyFn; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.ReadFn; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.SplitQueryFn; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.V1Beta3Options; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.UpsertFn; import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.V1Beta3DatastoreFactory; +import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Write; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.DoFnTester; import com.google.cloud.dataflow.sdk.transforms.DoFnTester.CloningBehavior; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.UserCodeException; import com.google.cloud.dataflow.sdk.values.KV; import com.google.datastore.v1beta3.CommitRequest; import com.google.datastore.v1beta3.Entity; import com.google.datastore.v1beta3.EntityResult; import com.google.datastore.v1beta3.Key; +import com.google.datastore.v1beta3.Mutation; import com.google.datastore.v1beta3.PartitionId; import com.google.datastore.v1beta3.Query; import com.google.datastore.v1beta3.QueryResultBatch; @@ -182,14 +190,14 @@ public void testReadValidationFailsQueryLimitNegative() throws Exception { @Test public void testReadValidationSucceedsNamespace() throws Exception { - V1Beta3.Read read = DatastoreIO.v1beta3().read().withProjectId(PROJECT_ID).withQuery(QUERY); + V1Beta3.Read read = DatastoreIO.v1beta3().read().withProjectId(PROJECT_ID).withQuery(QUERY); /* Should succeed, as a null namespace is fine. */ read.validate(null); } @Test public void testReadDisplayData() { - V1Beta3.Read read = DatastoreIO.v1beta3().read() + V1Beta3.Read read = DatastoreIO.v1beta3().read() .withProjectId(PROJECT_ID) .withQuery(QUERY) .withNamespace(NAMESPACE); @@ -211,7 +219,7 @@ public void testWriteDoesNotAllowNullProject() throws Exception { @Test public void testWriteValidationFailsWithNoProject() throws Exception { - V1Beta3.Write write = DatastoreIO.v1beta3().write(); + Write write = DatastoreIO.v1beta3().write(); thrown.expect(NullPointerException.class); thrown.expectMessage("projectId"); @@ -220,19 +228,88 @@ public void testWriteValidationFailsWithNoProject() throws Exception { } @Test - public void testSinkValidationSucceedsWithProject() throws Exception { - V1Beta3.Write write = DatastoreIO.v1beta3().write().withProjectId(PROJECT_ID); + public void testWriteValidationSucceedsWithProject() throws Exception { + Write write = DatastoreIO.v1beta3().write().withProjectId(PROJECT_ID); write.validate(null); } @Test public void testWriteDisplayData() { - V1Beta3.Write write = DatastoreIO.v1beta3().write() + Write write = DatastoreIO.v1beta3().write() .withProjectId(PROJECT_ID); DisplayData displayData = DisplayData.from(write); assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); + assertThat(displayData, hasDisplayItem("mutationFn", UpsertFn.class)); + } + + @Test + public void testDeleteEntityDoesNotAllowNullProject() throws Exception { + thrown.expect(NullPointerException.class); + thrown.expectMessage("projectId"); + + DatastoreIO.v1beta3().deleteEntity().withProjectId(null); + } + + @Test + public void testDeleteEntityValidationFailsWithNoProject() throws Exception { + DeleteEntity deleteEntity = DatastoreIO.v1beta3().deleteEntity(); + + thrown.expect(NullPointerException.class); + thrown.expectMessage("projectId"); + + deleteEntity.validate(null); + } + + @Test + public void testDeleteEntityValidationSucceedsWithProject() throws Exception { + DeleteEntity deleteEntity = DatastoreIO.v1beta3().deleteEntity().withProjectId(PROJECT_ID); + deleteEntity.validate(null); + } + + @Test + public void testDeleteEntityDisplayData() { + DeleteEntity deleteEntity = DatastoreIO.v1beta3().deleteEntity().withProjectId(PROJECT_ID); + + DisplayData displayData = DisplayData.from(deleteEntity); + + assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); + assertThat(displayData, hasDisplayItem("mutationFn", DeleteEntityFn.class)); + } + + @Test + public void testDeleteKeyDoesNotAllowNullProject() throws Exception { + thrown.expect(NullPointerException.class); + thrown.expectMessage("projectId"); + + DatastoreIO.v1beta3().deleteKey().withProjectId(null); + } + + @Test + public void testDeleteKeyValidationFailsWithNoProject() throws Exception { + DeleteKey deleteKey = DatastoreIO.v1beta3().deleteKey(); + + thrown.expect(NullPointerException.class); + thrown.expectMessage("projectId"); + + deleteKey.validate(null); + } + + @Test + public void testDeleteKeyValidationSucceedsWithProject() throws Exception { + DeleteKey deleteKey = DatastoreIO.v1beta3().deleteKey().withProjectId(PROJECT_ID); + deleteKey.validate(null); + } + + @Test + public void testDeleteKeyDisplayData() { + DeleteKey deleteKey = DatastoreIO.v1beta3().deleteKey().withProjectId(PROJECT_ID); + + DisplayData displayData = DisplayData.from(deleteKey); + + assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); + assertThat(displayData, hasDisplayItem("mutationFn", DeleteKeyFn.class)); } /** @@ -252,33 +329,33 @@ public void testHasNameOrId() { Key key; // Complete with name, no ancestor key = makeKey("bird", "finch").build(); - assertTrue(V1Beta3.isValidKey(key)); + assertTrue(isValidKey(key)); // Complete with id, no ancestor key = makeKey("bird", 123).build(); - assertTrue(V1Beta3.isValidKey(key)); + assertTrue(isValidKey(key)); // Incomplete, no ancestor key = makeKey("bird").build(); - assertFalse(V1Beta3.isValidKey(key)); + assertFalse(isValidKey(key)); // Complete with name and ancestor key = makeKey("bird", "owl").build(); key = makeKey(key, "bird", "horned").build(); - assertTrue(V1Beta3.isValidKey(key)); + assertTrue(isValidKey(key)); // Complete with id and ancestor key = makeKey("bird", "owl").build(); key = makeKey(key, "bird", 123).build(); - assertTrue(V1Beta3.isValidKey(key)); + assertTrue(isValidKey(key)); // Incomplete with ancestor key = makeKey("bird", "owl").build(); key = makeKey(key, "bird").build(); - assertFalse(V1Beta3.isValidKey(key)); + assertFalse(isValidKey(key)); key = makeKey().build(); - assertFalse(V1Beta3.isValidKey(key)); + assertFalse(isValidKey(key)); } /** @@ -288,14 +365,86 @@ public void testHasNameOrId() { public void testAddEntitiesWithIncompleteKeys() throws Exception { Key key = makeKey("bird").build(); Entity entity = Entity.newBuilder().setKey(key).build(); - DatastoreWriterFn writer = new DatastoreWriterFn(PROJECT_ID, mockDatastoreFactory); - DoFnTester doFnTester = DoFnTester.of(writer); - doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); + UpsertFn upsertFn = new UpsertFn(); - thrown.expect(UserCodeException.class); + thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Entities to be written to the Datastore must have complete keys"); - doFnTester.processBatch(entity); + upsertFn.apply(entity); + } + + @Test + /** + * Test that entities with valid keys are transformed to upsert mutations. + */ + public void testAddEntities() throws Exception { + Key key = makeKey("bird", "finch").build(); + Entity entity = Entity.newBuilder().setKey(key).build(); + UpsertFn upsertFn = new UpsertFn(); + + Mutation exceptedMutation = makeUpsert(entity).build(); + assertEquals(upsertFn.apply(entity), exceptedMutation); + } + + /** + * Test that entities with incomplete keys cannot be deleted. + */ + @Test + public void testDeleteEntitiesWithIncompleteKeys() throws Exception { + Key key = makeKey("bird").build(); + Entity entity = Entity.newBuilder().setKey(key).build(); + DeleteEntityFn deleteEntityFn = new DeleteEntityFn(); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Entities to be deleted from the Datastore must have complete keys"); + + deleteEntityFn.apply(entity); + } + + /** + * Test that entities with valid keys are transformed to delete mutations. + */ + @Test + public void testDeleteEntities() throws Exception { + Key key = makeKey("bird", "finch").build(); + Entity entity = Entity.newBuilder().setKey(key).build(); + DeleteEntityFn deleteEntityFn = new DeleteEntityFn(); + + Mutation exceptedMutation = makeDelete(entity.getKey()).build(); + assertEquals(deleteEntityFn.apply(entity), exceptedMutation); + } + + /** + * Test that incomplete keys cannot be deleted. + */ + @Test + public void testDeleteIncompleteKeys() throws Exception { + Key key = makeKey("bird").build(); + DeleteKeyFn deleteKeyFn = new DeleteKeyFn(); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Keys to be deleted from the Datastore must be complete"); + + deleteKeyFn.apply(key); + } + + /** + * Test that valid keys are transformed to delete mutations. + */ + @Test + public void testDeleteKeys() throws Exception { + Key key = makeKey("bird", "finch").build(); + DeleteKeyFn deleteKeyFn = new DeleteKeyFn(); + + Mutation exceptedMutation = makeDelete(key).build(); + assertEquals(deleteKeyFn.apply(key), exceptedMutation); + } + + @Test + public void testDatastoreWriteFnDisplayData() { + DatastoreWriterFn datastoreWriter = new DatastoreWriterFn(PROJECT_ID); + DisplayData displayData = DisplayData.from(datastoreWriter); + assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); } /** Tests {@link DatastoreWriterFn} with entities less than one batch. */ @@ -320,32 +469,30 @@ public void testDatatoreWriterFnWithBatchesExactMultiple() throws Exception { } // A helper method to test DatastoreWriterFn for various batch sizes. - private void datastoreWriterFnTest(int numEntities) throws Exception { + private void datastoreWriterFnTest(int numMutations) throws Exception { // Create the requested number of mutations. - List entities = new ArrayList<>(numEntities); - for (int i = 0; i < numEntities; ++i) { - entities.add(Entity.newBuilder().setKey(makeKey("key" + i, i + 1)).build()); + List mutations = new ArrayList<>(numMutations); + for (int i = 0; i < numMutations; ++i) { + mutations.add( + makeUpsert(Entity.newBuilder().setKey(makeKey("key" + i, i + 1)).build()).build()); } DatastoreWriterFn datastoreWriter = new DatastoreWriterFn(PROJECT_ID, mockDatastoreFactory); - DoFnTester doFnTester = DoFnTester.of(datastoreWriter); + DoFnTester doFnTester = DoFnTester.of(datastoreWriter); doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); - doFnTester.processBatch(entities); + doFnTester.processBatch(mutations); int start = 0; - while (start < numEntities) { - int end = Math.min(numEntities, start + DATASTORE_BATCH_UPDATE_LIMIT); + while (start < numMutations) { + int end = Math.min(numMutations, start + DATASTORE_BATCH_UPDATE_LIMIT); CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); - for (Entity entity: entities.subList(start, end)) { - commitRequest.addMutations(makeUpsert(entity)); - } - // Verify all the batch requests were made with the expected entities. + commitRequest.addAllMutations(mutations.subList(start, end)); + // Verify all the batch requests were made with the expected mutations. verify(mockDatastore, times(1)).commit(commitRequest.build()); start = end; } } - /** * Tests {@link V1Beta3.Read#getEstimatedSizeBytes} to fetch and return estimated size for a * query. From ae204e10a790777702f2e9216477ebf28849c927 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Sun, 14 Aug 2016 23:08:21 -0700 Subject: [PATCH 534/751] FileBasedSink: improve parallelism in GCS copy/remove --- .../cloud/dataflow/sdk/util/GcsUtil.java | 247 ++++++++---------- .../cloud/dataflow/sdk/util/GcsUtilTest.java | 69 +++++ 2 files changed, 182 insertions(+), 134 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java index 9572a7de63..dba7b49f80 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java @@ -16,16 +16,16 @@ package com.google.cloud.dataflow.sdk.util; +import static com.google.common.base.Preconditions.checkArgument; + import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpHeaders; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.util.BackOff; import com.google.api.client.util.Sleeper; import com.google.api.services.storage.Storage; -import com.google.api.services.storage.StorageRequest; import com.google.api.services.storage.model.Objects; import com.google.api.services.storage.model.StorageObject; import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; @@ -43,6 +43,11 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,12 +60,16 @@ import java.util.Collections; import java.util.LinkedList; import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; -import javax.annotation.concurrent.NotThreadSafe; /** * Provides operations on GCS. @@ -106,7 +115,11 @@ public GcsUtil create(PipelineOptions options) { /** * Maximum number of requests permitted in a GCS batch request. */ - private static final int MAX_REQUESTS_PER_BATCH = 1000; + private static final int MAX_REQUESTS_PER_BATCH = 100; + /** + * Maximum number of concurrent batches of requests executing on GCS. + */ + private static final int MAX_CONCURRENT_BATCHES = 256; ///////////////////////////////////////////////////////////////////////////// @@ -121,7 +134,6 @@ public GcsUtil create(PipelineOptions options) { // Exposed for testing. final ExecutorService executorService; - private final BatchHelper batchHelper; /** * Returns true if the given GCS pattern is supported otherwise fails with an * exception. @@ -141,8 +153,6 @@ private GcsUtil( this.storageClient = storageClient; this.uploadBufferSizeBytes = uploadBufferSizeBytes; this.executorService = executorService; - this.batchHelper = new BatchHelper( - storageClient.getRequestFactory().getInitializer(), storageClient, MAX_REQUESTS_PER_BATCH); } // Use this only for testing purposes. @@ -156,7 +166,7 @@ protected void setStorageClient(Storage storageClient) { * exists. */ public List expand(GcsPath gcsPattern) throws IOException { - Preconditions.checkArgument(isGcsPatternSupported(gcsPattern.getObject())); + checkArgument(isGcsPatternSupported(gcsPattern.getObject())); Matcher m = GLOB_PREFIX.matcher(gcsPattern.getObject()); Pattern p = null; String prefix = null; @@ -368,154 +378,123 @@ public boolean shouldRetry(IOException e) { } } + private static void executeBatches(List batches) throws IOException { + ListeningExecutorService executor = MoreExecutors.listeningDecorator( + MoreExecutors.getExitingExecutorService( + new ThreadPoolExecutor(MAX_CONCURRENT_BATCHES, MAX_CONCURRENT_BATCHES, + 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue()))); + + List> futures = new LinkedList<>(); + for (final BatchRequest batch : batches) { + futures.add(executor.submit(new Callable() { + public Void call() throws IOException { + batch.execute(); + return null; + } + })); + } + + try { + Futures.allAsList(futures).get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted while executing batch GCS request", e); + } catch (ExecutionException e) { + throw new IOException("Error executing batch GCS request", e); + } finally { + executor.shutdown(); + } + } + public void copy(List srcFilenames, List destFilenames) throws IOException { - Preconditions.checkArgument( + executeBatches(makeCopyBatches(srcFilenames, destFilenames)); + } + + List makeCopyBatches(List srcFilenames, List destFilenames) + throws IOException { + checkArgument( srcFilenames.size() == destFilenames.size(), "Number of source files %s must equal number of destination files %s", srcFilenames.size(), destFilenames.size()); + + List batches = new LinkedList<>(); + BatchRequest batch = storageClient.batch(); for (int i = 0; i < srcFilenames.size(); i++) { final GcsPath sourcePath = GcsPath.fromUri(srcFilenames.get(i)); final GcsPath destPath = GcsPath.fromUri(destFilenames.get(i)); - LOG.debug("Copying {} to {}", sourcePath, destPath); - Storage.Objects.Copy copyObject = storageClient.objects().copy(sourcePath.getBucket(), - sourcePath.getObject(), destPath.getBucket(), destPath.getObject(), null); - batchHelper.queue(copyObject, new JsonBatchCallback() { - @Override - public void onSuccess(StorageObject obj, HttpHeaders responseHeaders) { - LOG.debug("Successfully copied {} to {}", sourcePath, destPath); - } - - @Override - public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { - // Do nothing on item not found. - if (!errorExtractor.itemNotFound(e)) { - throw new IOException(e.toString()); - } - LOG.debug("{} does not exist.", sourcePath); - } - }); + enqueueCopy(sourcePath, destPath, batch); + if (batch.size() >= MAX_REQUESTS_PER_BATCH) { + batches.add(batch); + batch = storageClient.batch(); + } } - batchHelper.flush(); - } - - public void remove(Collection filenames) throws IOException { - for (String filename : filenames) { - final GcsPath path = GcsPath.fromUri(filename); - LOG.debug("Removing: " + path); - Storage.Objects.Delete deleteObject = - storageClient.objects().delete(path.getBucket(), path.getObject()); - batchHelper.queue(deleteObject, new JsonBatchCallback() { - @Override - public void onSuccess(Void obj, HttpHeaders responseHeaders) throws IOException { - LOG.debug("Successfully removed {}", path); - } - - @Override - public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { - // Do nothing on item not found. - if (!errorExtractor.itemNotFound(e)) { - throw new IOException(e.toString()); - } - LOG.debug("{} does not exist.", path); - } - }); + if (batch.size() > 0) { + batches.add(batch); } - batchHelper.flush(); + return batches; } - /** - * BatchHelper abstracts out the logic for the maximum requests per batch for GCS. - * - *

            Copy of - * https://github.com/GoogleCloudPlatform/bigdata-interop/blob/master/gcs/src/main/java/com/google/cloud/hadoop/gcsio/BatchHelper.java - * - *

            Copied to prevent Dataflow from depending on the Hadoop-related dependencies that are not - * used in Dataflow. Hadoop-related dependencies will be removed from the Google Cloud Storage - * Connector (https://cloud.google.com/hadoop/google-cloud-storage-connector) so that this project - * and others may use the connector without introducing unnecessary dependencies. - * - *

            This class is not thread-safe; create a new BatchHelper instance per single-threaded logical - * grouping of requests. - */ - @NotThreadSafe - private static class BatchHelper { - /** - * Callback that causes a single StorageRequest to be added to the BatchRequest. - */ - protected static interface QueueRequestCallback { - void enqueue() throws IOException; + List makeRemoveBatches(Collection filenames) throws IOException { + List batches = new LinkedList<>(); + for (List filesToDelete : + Lists.partition(Lists.newArrayList(filenames), MAX_REQUESTS_PER_BATCH)) { + BatchRequest batch = storageClient.batch(); + for (String file : filesToDelete) { + enqueueDelete(GcsPath.fromUri(file), batch); + } + batches.add(batch); } + return batches; + } - private final List pendingBatchEntries; - private final BatchRequest batch; - - // Number of requests that can be queued into a single actual HTTP request - // before a sub-batch is sent. - private final long maxRequestsPerBatch; - - // Flag that indicates whether there is an in-progress flush. - private boolean flushing = false; + public void remove(Collection filenames) throws IOException { + executeBatches(makeRemoveBatches(filenames)); + } - /** - * Primary constructor, generally accessed only via the inner Factory class. - */ - public BatchHelper( - HttpRequestInitializer requestInitializer, Storage gcs, long maxRequestsPerBatch) { - this.pendingBatchEntries = new LinkedList<>(); - this.batch = gcs.batch(requestInitializer); - this.maxRequestsPerBatch = maxRequestsPerBatch; - } + private void enqueueCopy(final GcsPath from, final GcsPath to, BatchRequest batch) + throws IOException { + Storage.Objects.Copy copyRequest = storageClient.objects() + .copy(from.getBucket(), from.getObject(), to.getBucket(), to.getObject(), null); + copyRequest.queue(batch, new JsonBatchCallback() { + @Override + public void onSuccess(StorageObject obj, HttpHeaders responseHeaders) { + LOG.debug("Successfully copied {} to {}", from, to); + } - /** - * Adds an additional request to the batch, and possibly flushes the current contents of the - * batch if {@code maxRequestsPerBatch} has been reached. - */ - public void queue(final StorageRequest req, final JsonBatchCallback callback) - throws IOException { - QueueRequestCallback queueCallback = new QueueRequestCallback() { - @Override - public void enqueue() throws IOException { - req.queue(batch, callback); + @Override + public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { + if (errorExtractor.itemNotFound(e)) { + // Do nothing on item not found. + LOG.debug("{} does not exist, assuming this is a retry after deletion.", from); + return; } - }; - pendingBatchEntries.add(queueCallback); - - flushIfPossibleAndRequired(); - } - - // Flush our buffer if we have more pending entries than maxRequestsPerBatch - private void flushIfPossibleAndRequired() throws IOException { - if (pendingBatchEntries.size() > maxRequestsPerBatch) { - flushIfPossible(); + throw new IOException( + String.format("Error trying to copy %s to %s: %s", from, to, e)); } - } + }); + } - // Flush our buffer if we are not already in a flush operation and we have data to flush. - private void flushIfPossible() throws IOException { - if (!flushing && pendingBatchEntries.size() > 0) { - flushing = true; - try { - while (batch.size() < maxRequestsPerBatch && pendingBatchEntries.size() > 0) { - QueueRequestCallback head = pendingBatchEntries.remove(0); - head.enqueue(); - } + private void enqueueDelete(final GcsPath file, BatchRequest batch) throws IOException { + Storage.Objects.Delete deleteRequest = storageClient.objects() + .delete(file.getBucket(), file.getObject()); + deleteRequest.queue(batch, new JsonBatchCallback() { + @Override + public void onSuccess(Void obj, HttpHeaders responseHeaders) { + LOG.debug("Successfully deleted {}", file); + } - batch.execute(); - } finally { - flushing = false; + @Override + public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { + if (errorExtractor.itemNotFound(e)) { + // Do nothing on item not found. + LOG.debug("{} does not exist.", file); + return; } + throw new IOException(String.format("Error trying to delete %s: %s", file, e)); } - } - - - /** - * Sends any currently remaining requests in the batch; should be called at the end of any - * series of batched requests to ensure everything has been sent. - */ - public void flush() throws IOException { - flushIfPossible(); - } + }); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java index a1a97684d5..230a63b80f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java @@ -17,6 +17,8 @@ package com.google.cloud.dataflow.sdk.util; import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -26,6 +28,7 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; +import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequest; @@ -486,4 +489,70 @@ public LowLevelHttpRequest buildRequest(String method, String url) throws IOExce HttpResponse response = request.execute(); return GoogleJsonResponseException.from(jsonFactory, response); } + + private static List makeStrings(String s, int n) { + ImmutableList.Builder ret = ImmutableList.builder(); + for (int i = 0; i < n; ++i) { + ret.add(String.format("gs://bucket/%s%d", s, i)); + } + return ret.build(); + } + + private static int sumBatchSizes(List batches) { + int ret = 0; + for (BatchRequest b : batches) { + ret += b.size(); + assertThat(b.size(), greaterThan(0)); + } + return ret; + } + + @Test + public void testMakeCopyBatches() throws IOException { + GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil(); + + // Small number of files fits in 1 batch + List batches = gcsUtil.makeCopyBatches(makeStrings("s", 3), makeStrings("d", 3)); + assertThat(batches.size(), equalTo(1)); + assertThat(sumBatchSizes(batches), equalTo(3)); + + // 1 batch of files fits in 1 batch + batches = gcsUtil.makeCopyBatches(makeStrings("s", 100), makeStrings("d", 100)); + assertThat(batches.size(), equalTo(1)); + assertThat(sumBatchSizes(batches), equalTo(100)); + + // A little more than 5 batches of files fits in 6 batches + batches = gcsUtil.makeCopyBatches(makeStrings("s", 501), makeStrings("d", 501)); + assertThat(batches.size(), equalTo(6)); + assertThat(sumBatchSizes(batches), equalTo(501)); + } + + @Test + public void testInvalidCopyBatches() throws IOException { + GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil(); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Number of source files 3"); + + gcsUtil.makeCopyBatches(makeStrings("s", 3), makeStrings("d", 1)); + } + + @Test + public void testMakeRemoveBatches() throws IOException { + GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil(); + + // Small number of files fits in 1 batch + List batches = gcsUtil.makeRemoveBatches(makeStrings("s", 3)); + assertThat(batches.size(), equalTo(1)); + assertThat(sumBatchSizes(batches), equalTo(3)); + + // 1 batch of files fits in 1 batch + batches = gcsUtil.makeRemoveBatches(makeStrings("s", 100)); + assertThat(batches.size(), equalTo(1)); + assertThat(sumBatchSizes(batches), equalTo(100)); + + // A little more than 5 batches of files fits in 6 batches + batches = gcsUtil.makeRemoveBatches(makeStrings("s", 501)); + assertThat(batches.size(), equalTo(6)); + assertThat(sumBatchSizes(batches), equalTo(501)); + } } From 1c930da049cc846fe7e07ab3485032229e6b2023 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Tue, 23 Aug 2016 20:39:40 -0700 Subject: [PATCH 535/751] WindowSupplierTest: add missing @RunWith (#398) --- .../google/cloud/dataflow/sdk/testing/WindowSupplierTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java index 26e67ae1bf..1ffb2310e1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java @@ -29,6 +29,8 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.io.InputStream; @@ -38,6 +40,7 @@ /** * Tests for {@link WindowSupplier}. */ +@RunWith(JUnit4.class) public class WindowSupplierTest { private final IntervalWindow window = new IntervalWindow(new Instant(0L), new Instant(100L)); private final IntervalWindow otherWindow = From 2dd0fabf16ec06869f0c591e4156e07ed958f22b Mon Sep 17 00:00:00 2001 From: peihe Date: Wed, 24 Aug 2016 13:15:26 -0700 Subject: [PATCH 536/751] Enable TextIO.Write in DataflowPipelineRunner for streaming (#394) --- .../main/java/com/google/cloud/dataflow/sdk/io/Write.java | 8 +++++++- .../dataflow/sdk/runners/DataflowPipelineRunner.java | 2 -- .../dataflow/sdk/runners/DataflowPipelineRunnerTest.java | 5 ----- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java index 8c537944fa..5881951996 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java @@ -13,9 +13,9 @@ */ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.client.util.Lists; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -37,8 +37,10 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -101,6 +103,10 @@ private Bound(Sink sink, int numShards) { @Override public PDone apply(PCollection input) { + checkArgument(IsBounded.BOUNDED == input.isBounded(), + "%s can only be applied to a Bounded PCollection", + Write.class.getSimpleName()); + PipelineOptions options = input.getPipeline().getOptions(); sink.validate(options); return createWrite(input, sink.createWriteOperation(options)); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index ced100d854..f88790dfc5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -360,11 +360,9 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(View.AsSingleton.class, StreamingViewAsSingleton.class); builder.put(View.AsList.class, StreamingViewAsList.class); builder.put(View.AsIterable.class, StreamingViewAsIterable.class); - builder.put(Write.Bound.class, StreamingWrite.class); builder.put(Read.Unbounded.class, StreamingUnboundedRead.class); builder.put(Read.Bounded.class, StreamingBoundedRead.class); builder.put(AvroIO.Write.Bound.class, UnsupportedIO.class); - builder.put(TextIO.Write.Bound.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); // In streaming mode must use either the custom Pubsub unbounded source/sink or // defer to Windmill's built-in implementation. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 41019cc5fe..1dac6c4cf2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -950,11 +950,6 @@ public void testAvroIOSinkUnsupportedInStreaming() throws Exception { testUnsupportedSink(AvroIO.Write.to("foo").withSchema(String.class), "AvroIO.Write", true); } - @Test - public void testTextIOSinkUnsupportedInStreaming() throws Exception { - testUnsupportedSink(TextIO.Write.to("foo"), "TextIO.Write", true); - } - @Test public void testBatchViewAsSingletonToIsmRecord() throws Exception { DoFnTester>>>, From 2039cdb6cfb0acd9121ddc3ea9c53c519b705ef7 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Wed, 24 Aug 2016 13:28:25 -0700 Subject: [PATCH 537/751] DatastoreIO v1beta3 to v1 version (#397) --- examples/pom.xml | 4 +- .../examples/complete/AutoComplete.java | 12 +- .../examples/cookbook/DatastoreWordCount.java | 24 +-- pom.xml | 4 +- sdk/pom.xml | 4 +- .../sdk/io/datastore/DatastoreIO.java | 8 +- .../{V1Beta3.java => DatastoreV1.java} | 175 +++++++++--------- ...{V1Beta3Test.java => DatastoreV1Test.java} | 147 +++++++-------- 8 files changed, 190 insertions(+), 188 deletions(-) rename sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/{V1Beta3.java => DatastoreV1.java} (85%) rename sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/{V1Beta3Test.java => DatastoreV1Test.java} (81%) diff --git a/examples/pom.xml b/examples/pom.xml index d247168935..b6876b61eb 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -461,13 +461,13 @@ com.google.cloud.datastore - datastore-v1beta3-proto-client + datastore-v1-proto-client ${datastore.client.version} com.google.cloud.datastore - datastore-v1beta3-protos + datastore-v1-protos ${datastore.proto.version} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java index 6ff9139e7d..e30e6ca56d 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java @@ -16,8 +16,8 @@ package com.google.cloud.dataflow.examples.complete; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; +import static com.google.datastore.v1.client.DatastoreHelper.makeKey; +import static com.google.datastore.v1.client.DatastoreHelper.makeValue; import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableReference; @@ -59,9 +59,9 @@ import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -import com.google.datastore.v1beta3.Entity; -import com.google.datastore.v1beta3.Key; -import com.google.datastore.v1beta3.Value; +import com.google.datastore.v1.Entity; +import com.google.datastore.v1.Key; +import com.google.datastore.v1.Value; import org.joda.time.Duration; @@ -499,7 +499,7 @@ public static void main(String[] args) throws IOException { toWrite .apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind(), options.getDatastoreAncestorKey()))) - .apply(DatastoreIO.v1beta3().write().withProjectId(MoreObjects.firstNonNull( + .apply(DatastoreIO.v1().write().withProjectId(MoreObjects.firstNonNull( options.getOutputDataset(), options.getProject()))); } if (options.getOutputToBigQuery()) { diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java index 2f72f48d6e..cf1f7b1b2b 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java @@ -16,16 +16,16 @@ package com.google.cloud.dataflow.examples.cookbook; -import static com.google.datastore.v1beta3.client.DatastoreHelper.getString; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; +import static com.google.datastore.v1.client.DatastoreHelper.getString; +import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; +import static com.google.datastore.v1.client.DatastoreHelper.makeKey; +import static com.google.datastore.v1.client.DatastoreHelper.makeValue; import com.google.cloud.dataflow.examples.WordCount; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.io.datastore.DatastoreIO; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.PipelineOptions; @@ -34,11 +34,11 @@ import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.MapElements; import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.datastore.v1beta3.Entity; -import com.google.datastore.v1beta3.Key; -import com.google.datastore.v1beta3.PropertyFilter; -import com.google.datastore.v1beta3.Query; -import com.google.datastore.v1beta3.Value; +import com.google.datastore.v1.Entity; +import com.google.datastore.v1.Key; +import com.google.datastore.v1.PropertyFilter; +import com.google.datastore.v1.Query; +import com.google.datastore.v1.Value; import java.util.Map; import java.util.UUID; @@ -195,7 +195,7 @@ public static void writeDataToDatastore(Options options) { Pipeline p = Pipeline.create(options); p.apply(TextIO.Read.named("ReadLines").from(options.getInput())) .apply(ParDo.of(new CreateEntityFn(options.getNamespace(), options.getKind()))) - .apply(DatastoreIO.v1beta3().write().withProjectId(options.getDataset())); + .apply(DatastoreIO.v1().write().withProjectId(options.getDataset())); p.run(); } @@ -226,7 +226,7 @@ public static void readDataFromDatastore(Options options) { Query query = makeAncestorKindQuery(options); // For Datastore sources, the read namespace can be set on the entire query. - V1Beta3.Read read = DatastoreIO.v1beta3().read() + DatastoreV1.Read read = DatastoreIO.v1().read() .withProjectId(options.getDataset()) .withQuery(query) .withNamespace(options.getNamespace()); diff --git a/pom.xml b/pom.xml index 2ece510d42..9009eccd76 100644 --- a/pom.xml +++ b/pom.xml @@ -76,8 +76,8 @@ v1b3-rev36-1.22.0 0.5.160222 v1beta2-rev1-4.0.0 - 1.0.0-beta.2 - 1.0.0-beta + 1.1.0 + 1.0.1 1.22.0 0.13.1 19.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index c08fee77e8..d9c4727601 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -758,13 +758,13 @@ com.google.cloud.datastore - datastore-v1beta3-proto-client + datastore-v1-proto-client ${datastore.client.version} com.google.cloud.datastore - datastore-v1beta3-protos + datastore-v1-protos ${datastore.proto.version} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java index f402dcbfc3..6dde7488e1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java @@ -23,7 +23,7 @@ * Google Cloud Datastore over different * versions of the Datastore Client libraries. * - *

            To use the v1beta3 version see {@link V1Beta3}. + *

            To use the v1 version see {@link DatastoreV1}. */ @Experimental(Experimental.Kind.SOURCE_SINK) public class DatastoreIO { @@ -31,10 +31,10 @@ public class DatastoreIO { private DatastoreIO() {} /** - * Returns a {@link V1Beta3} that provides an API for accessing Datastore through v1beta3 version + * Returns a {@link DatastoreV1} that provides an API for accessing Datastore through v1 version * of Datastore Client library. */ - public static V1Beta3 v1beta3() { - return new V1Beta3(); + public static DatastoreV1 v1() { + return new DatastoreV1(); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java similarity index 85% rename from sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java rename to sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java index f3109ae18a..a146c2d78f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java @@ -19,14 +19,14 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; -import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; -import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; -import static com.google.datastore.v1beta3.QueryResultBatch.MoreResultsType.NOT_FINISHED; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeDelete; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeUpsert; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; +import static com.google.datastore.v1.PropertyFilter.Operator.EQUAL; +import static com.google.datastore.v1.PropertyOrder.Direction.DESCENDING; +import static com.google.datastore.v1.QueryResultBatch.MoreResultsType.NOT_FINISHED; +import static com.google.datastore.v1.client.DatastoreHelper.makeDelete; +import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; +import static com.google.datastore.v1.client.DatastoreHelper.makeOrder; +import static com.google.datastore.v1.client.DatastoreHelper.makeUpsert; +import static com.google.datastore.v1.client.DatastoreHelper.makeValue; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.util.BackOff; @@ -55,23 +55,23 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; -import com.google.datastore.v1beta3.CommitRequest; -import com.google.datastore.v1beta3.Entity; -import com.google.datastore.v1beta3.EntityResult; -import com.google.datastore.v1beta3.Key; -import com.google.datastore.v1beta3.Key.PathElement; -import com.google.datastore.v1beta3.Mutation; -import com.google.datastore.v1beta3.PartitionId; -import com.google.datastore.v1beta3.Query; -import com.google.datastore.v1beta3.QueryResultBatch; -import com.google.datastore.v1beta3.RunQueryRequest; -import com.google.datastore.v1beta3.RunQueryResponse; -import com.google.datastore.v1beta3.client.Datastore; -import com.google.datastore.v1beta3.client.DatastoreException; -import com.google.datastore.v1beta3.client.DatastoreFactory; -import com.google.datastore.v1beta3.client.DatastoreHelper; -import com.google.datastore.v1beta3.client.DatastoreOptions; -import com.google.datastore.v1beta3.client.QuerySplitter; +import com.google.datastore.v1.CommitRequest; +import com.google.datastore.v1.Entity; +import com.google.datastore.v1.EntityResult; +import com.google.datastore.v1.Key; +import com.google.datastore.v1.Key.PathElement; +import com.google.datastore.v1.Mutation; +import com.google.datastore.v1.PartitionId; +import com.google.datastore.v1.Query; +import com.google.datastore.v1.QueryResultBatch; +import com.google.datastore.v1.RunQueryRequest; +import com.google.datastore.v1.RunQueryResponse; +import com.google.datastore.v1.client.Datastore; +import com.google.datastore.v1.client.DatastoreException; +import com.google.datastore.v1.client.DatastoreFactory; +import com.google.datastore.v1.client.DatastoreHelper; +import com.google.datastore.v1.client.DatastoreOptions; +import com.google.datastore.v1.client.QuerySplitter; import com.google.protobuf.Int32Value; import org.slf4j.Logger; @@ -86,21 +86,21 @@ import javax.annotation.Nullable; /** - *

            {@link V1Beta3} provides an API to Read, Write and Delete {@link PCollection PCollections} of - * Google Cloud Datastore version v1beta3 + *

            {@link DatastoreV1} provides an API to Read, Write and Delete {@link PCollection PCollections} + * of Google Cloud Datastore version v1 * {@link Entity} objects. * - *

            This API currently requires an authentication workaround. To use {@link V1Beta3}, users + *

            This API currently requires an authentication workaround. To use {@link DatastoreV1}, users * must use the {@code gcloud} command line tool to get credentials for Datastore: *

              * $ gcloud auth login
              * 
            * - *

            To read a {@link PCollection} from a query to Datastore, use {@link V1Beta3#read} and - * its methods {@link V1Beta3.Read#withProjectId} and {@link V1Beta3.Read#withQuery} to + *

            To read a {@link PCollection} from a query to Datastore, use {@link DatastoreV1#read} and + * its methods {@link DatastoreV1.Read#withProjectId} and {@link DatastoreV1.Read#withQuery} to * specify the project to query and the query to read from. You can optionally provide a namespace - * to query within using {@link V1Beta3.Read#withNamespace}. You could also optionally specify - * how many splits you want for the query using {@link V1Beta3.Read#withNumQuerySplits}. + * to query within using {@link DatastoreV1.Read#withNamespace}. You could also optionally specify + * how many splits you want for the query using {@link DatastoreV1.Read#withNumQuerySplits}. * *

            For example: * @@ -112,40 +112,40 @@ * * Pipeline p = Pipeline.create(options); * PCollection entities = p.apply( - * DatastoreIO.v1beta3().read() + * DatastoreIO.v1().read() * .withProjectId(projectId) * .withQuery(query)); * } * *

            Note: Normally, a Cloud Dataflow job will read from Cloud Datastore in parallel across * many workers. However, when the {@link Query} is configured with a limit using - * {@link com.google.datastore.v1beta3.Query.Builder#setLimit(Int32Value)}, then + * {@link com.google.datastore.v1.Query.Builder#setLimit(Int32Value)}, then * all returned results will be read by a single Dataflow worker in order to ensure correct data. * - *

            To write a {@link PCollection} to a Datastore, use {@link V1Beta3#write}, + *

            To write a {@link PCollection} to a Datastore, use {@link DatastoreV1#write}, * specifying the Cloud Datastore project to write to: * *

             {@code
              * PCollection entities = ...;
            - * entities.apply(DatastoreIO.v1beta3().write().withProjectId(projectId));
            + * entities.apply(DatastoreIO.v1().write().withProjectId(projectId));
              * p.run();
              * } 
            * *

            To delete a {@link PCollection} of {@link Entity Entities} from Datastore, use - * {@link V1Beta3#deleteEntity()}, specifying the Cloud Datastore project to write to: + * {@link DatastoreV1#deleteEntity()}, specifying the Cloud Datastore project to write to: * *

             {@code
              * PCollection entities = ...;
            - * entities.apply(DatastoreIO.v1beta3().deleteEntity().withProjectId(projectId));
            + * entities.apply(DatastoreIO.v1().deleteEntity().withProjectId(projectId));
              * p.run();
              * } 
            * *

            To delete entities associated with a {@link PCollection} of {@link Key Keys} from Datastore, - * use {@link V1Beta3#deleteKey}, specifying the Cloud Datastore project to write to: + * use {@link DatastoreV1#deleteKey}, specifying the Cloud Datastore project to write to: * *

             {@code
              * PCollection entities = ...;
            - * entities.apply(DatastoreIO.v1beta3().deleteKey().withProjectId(projectId));
            + * entities.apply(DatastoreIO.v1().deleteKey().withProjectId(projectId));
              * p.run();
              * } 
            * @@ -174,10 +174,10 @@ * @see com.google.cloud.dataflow.sdk.runners.PipelineRunner */ @Experimental(Experimental.Kind.SOURCE_SINK) -public class V1Beta3 { +public class DatastoreV1 { // A package-private constructor to prevent direct instantiation from outside of this package - V1Beta3() {} + DatastoreV1() {} /** * Datastore has a limit of 500 mutations per batch operation, so we flush @@ -187,13 +187,13 @@ public class V1Beta3 { static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; /** - * Returns an empty {@link V1Beta3.Read} builder. Configure the source {@code projectId}, + * Returns an empty {@link DatastoreV1.Read} builder. Configure the source {@code projectId}, * {@code query}, and optionally {@code namespace} and {@code numQuerySplits} using - * {@link V1Beta3.Read#withProjectId}, {@link V1Beta3.Read#withQuery}, - * {@link V1Beta3.Read#withNamespace}, {@link V1Beta3.Read#withNumQuerySplits}. + * {@link DatastoreV1.Read#withProjectId}, {@link DatastoreV1.Read#withQuery}, + * {@link DatastoreV1.Read#withNamespace}, {@link DatastoreV1.Read#withNumQuerySplits}. */ - public V1Beta3.Read read() { - return new V1Beta3.Read(null, null, null, 0); + public DatastoreV1.Read read() { + return new DatastoreV1.Read(null, null, null, 0); } /** @@ -327,37 +327,38 @@ private Read(@Nullable String projectId, @Nullable Query query, @Nullable String } /** - * Returns a new {@link V1Beta3.Read} that reads from the Datastore for the specified project. + * Returns a new {@link DatastoreV1.Read} that reads from the Datastore for the specified + * project. */ - public V1Beta3.Read withProjectId(String projectId) { + public DatastoreV1.Read withProjectId(String projectId) { checkNotNull(projectId, "projectId"); - return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); + return new DatastoreV1.Read(projectId, query, namespace, numQuerySplits); } /** - * Returns a new {@link V1Beta3.Read} that reads the results of the specified query. + * Returns a new {@link DatastoreV1.Read} that reads the results of the specified query. * *

            Note: Normally, {@code DatastoreIO} will read from Cloud Datastore in parallel * across many workers. However, when the {@link Query} is configured with a limit using * {@link Query.Builder#setLimit}, then all results will be read by a single worker in order * to ensure correct results. */ - public V1Beta3.Read withQuery(Query query) { + public DatastoreV1.Read withQuery(Query query) { checkNotNull(query, "query"); checkArgument(!query.hasLimit() || query.getLimit().getValue() > 0, "Invalid query limit %s: must be positive", query.getLimit().getValue()); - return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); + return new DatastoreV1.Read(projectId, query, namespace, numQuerySplits); } /** - * Returns a new {@link V1Beta3.Read} that reads from the given namespace. + * Returns a new {@link DatastoreV1.Read} that reads from the given namespace. */ - public V1Beta3.Read withNamespace(String namespace) { - return new V1Beta3.Read(projectId, query, namespace, numQuerySplits); + public DatastoreV1.Read withNamespace(String namespace) { + return new DatastoreV1.Read(projectId, query, namespace, numQuerySplits); } /** - * Returns a new {@link V1Beta3.Read} that reads by splitting the given {@code query} into + * Returns a new {@link DatastoreV1.Read} that reads by splitting the given {@code query} into * {@code numQuerySplits}. * *

            The semantics for the query splitting is defined below: @@ -372,8 +373,8 @@ public V1Beta3.Read withNamespace(String namespace) { * splits. In such cases we just use whatever the Datastore returns. * */ - public V1Beta3.Read withNumQuerySplits(int numQuerySplits) { - return new V1Beta3.Read(projectId, query, namespace, + public DatastoreV1.Read withNumQuerySplits(int numQuerySplits) { + return new DatastoreV1.Read(projectId, query, namespace, Math.min(Math.max(numQuerySplits, 0), NUM_QUERY_SPLITS_MAX)); } @@ -398,7 +399,7 @@ public String getNamespace() { */ @Override public PCollection apply(PBegin input) { - V1Beta3Options v1Beta3Options = V1Beta3Options.from(getProjectId(), getQuery(), + V1Options v1Options = V1Options.from(getProjectId(), getQuery(), getNamespace()); /* @@ -420,7 +421,7 @@ public PCollection apply(PBegin input) { */ PCollection> queries = input .apply(Create.of(query)) - .apply(ParDo.of(new SplitQueryFn(v1Beta3Options, numQuerySplits))); + .apply(ParDo.of(new SplitQueryFn(v1Options, numQuerySplits))); PCollection shardedQueries = queries .apply(GroupByKey.create()) @@ -428,7 +429,7 @@ public PCollection apply(PBegin input) { .apply(Flatten.iterables()); PCollection entities = shardedQueries - .apply(ParDo.of(new ReadFn(v1Beta3Options))); + .apply(ParDo.of(new ReadFn(v1Options))); return entities; } @@ -461,23 +462,23 @@ public String toString() { } /** - * A class for v1beta3 Datastore related options. + * A class for v1 Datastore related options. */ @VisibleForTesting - static class V1Beta3Options implements Serializable { + static class V1Options implements Serializable { private final Query query; private final String projectId; @Nullable private final String namespace; - private V1Beta3Options(String projectId, Query query, @Nullable String namespace) { + private V1Options(String projectId, Query query, @Nullable String namespace) { this.projectId = checkNotNull(projectId, "projectId"); this.query = checkNotNull(query, "query"); this.namespace = namespace; } - public static V1Beta3Options from(String projectId, Query query, @Nullable String namespace) { - return new V1Beta3Options(projectId, query, namespace); + public static V1Options from(String projectId, Query query, @Nullable String namespace) { + return new V1Options(projectId, query, namespace); } public Query getQuery() { @@ -500,23 +501,23 @@ public String getNamespace() { */ @VisibleForTesting static class SplitQueryFn extends DoFn> { - private final V1Beta3Options options; + private final V1Options options; // number of splits to make for a given query private final int numSplits; - private final V1Beta3DatastoreFactory datastoreFactory; + private final V1DatastoreFactory datastoreFactory; // Datastore client private transient Datastore datastore; // Query splitter private transient QuerySplitter querySplitter; - public SplitQueryFn(V1Beta3Options options, int numSplits) { - this(options, numSplits, new V1Beta3DatastoreFactory()); + public SplitQueryFn(V1Options options, int numSplits) { + this(options, numSplits, new V1DatastoreFactory()); } @VisibleForTesting - SplitQueryFn(V1Beta3Options options, int numSplits, - V1Beta3DatastoreFactory datastoreFactory) { + SplitQueryFn(V1Options options, int numSplits, + V1DatastoreFactory datastoreFactory) { this.options = options; this.numSplits = numSplits; this.datastoreFactory = datastoreFactory; @@ -580,17 +581,17 @@ public void populateDisplayData(Builder builder) { */ @VisibleForTesting static class ReadFn extends DoFn { - private final V1Beta3Options options; - private final V1Beta3DatastoreFactory datastoreFactory; + private final V1Options options; + private final V1DatastoreFactory datastoreFactory; // Datastore client private transient Datastore datastore; - public ReadFn(V1Beta3Options options) { - this(options, new V1Beta3DatastoreFactory()); + public ReadFn(V1Options options) { + this(options, new V1DatastoreFactory()); } @VisibleForTesting - ReadFn(V1Beta3Options options, V1Beta3DatastoreFactory datastoreFactory) { + ReadFn(V1Options options, V1DatastoreFactory datastoreFactory) { this.options = options; this.datastoreFactory = datastoreFactory; } @@ -654,8 +655,8 @@ public void processElement(ProcessContext context) throws Exception { } /** - * Returns an empty {@link V1Beta3.Write} builder. Configure the destination - * {@code projectId} using {@link V1Beta3.Write#withProjectId}. + * Returns an empty {@link DatastoreV1.Write} builder. Configure the destination + * {@code projectId} using {@link DatastoreV1.Write#withProjectId}. */ public Write write() { return new Write(null); @@ -811,14 +812,14 @@ public String getProjectId() { /** * {@link DoFn} that writes {@link Mutation}s to Cloud Datastore. Mutations are written in - * batches, where the maximum batch size is {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT}. + * batches, where the maximum batch size is {@link DatastoreV1#DATASTORE_BATCH_UPDATE_LIMIT}. * *

            See * Datastore: Entities, Properties, and Keys for information about entity keys and mutations. * *

            Commits are non-transactional. If a commit fails because of a conflict over an entity - * group, the commit will be retried (up to {@link V1Beta3#DATASTORE_BATCH_UPDATE_LIMIT} + * group, the commit will be retried (up to {@link DatastoreV1#DATASTORE_BATCH_UPDATE_LIMIT} * times). This means that the mutation operation should be idempotent. Thus, the writer should * only be used for {code upsert} and {@code delete} mutation operations, as these are the only * two Cloud Datastore mutations that are idempotent. @@ -828,7 +829,7 @@ static class DatastoreWriterFn extends DoFn { private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriterFn.class); private final String projectId; private transient Datastore datastore; - private final V1Beta3DatastoreFactory datastoreFactory; + private final V1DatastoreFactory datastoreFactory; // Current batch of mutations to be written. private final List mutations = new ArrayList<>(); /** @@ -843,11 +844,11 @@ static class DatastoreWriterFn extends DoFn { private static final int INITIAL_BACKOFF_MILLIS = 5000; DatastoreWriterFn(String projectId) { - this(projectId, new V1Beta3DatastoreFactory()); + this(projectId, new V1DatastoreFactory()); } @VisibleForTesting - DatastoreWriterFn(String projectId, V1Beta3DatastoreFactory datastoreFactory) { + DatastoreWriterFn(String projectId, V1DatastoreFactory datastoreFactory) { this.projectId = checkNotNull(projectId, "projectId"); this.datastoreFactory = datastoreFactory; } @@ -860,7 +861,7 @@ public void startBundle(Context c) { @Override public void processElement(ProcessContext c) throws Exception { mutations.add(c.element()); - if (mutations.size() >= V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT) { + if (mutations.size() >= DatastoreV1.DATASTORE_BATCH_UPDATE_LIMIT) { flushBatch(); } } @@ -987,7 +988,7 @@ public Mutation apply(Key key) { * wrapping them under this class, which implements {@link Serializable}. */ @VisibleForTesting - static class V1Beta3DatastoreFactory implements Serializable { + static class V1DatastoreFactory implements Serializable { /** Builds a Datastore client for the given pipeline options and project. */ public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java similarity index 81% rename from sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java rename to sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java index 8387be6721..62001b8d62 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/V1Beta3Test.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java @@ -16,21 +16,21 @@ package com.google.cloud.dataflow.sdk.io.datastore; -import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DATASTORE_BATCH_UPDATE_LIMIT; -import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.DEFAULT_BUNDLE_SIZE_BYTES; -import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.QUERY_BATCH_LIMIT; -import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.getEstimatedSizeBytes; -import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.makeRequest; -import static com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.isValidKey; +import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DATASTORE_BATCH_UPDATE_LIMIT; +import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.DEFAULT_BUNDLE_SIZE_BYTES; +import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.QUERY_BATCH_LIMIT; +import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.getEstimatedSizeBytes; +import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.makeRequest; +import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.isValidKey; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.datastore.v1beta3.PropertyFilter.Operator.EQUAL; -import static com.google.datastore.v1beta3.PropertyOrder.Direction.DESCENDING; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeDelete; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeOrder; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeUpsert; -import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue; +import static com.google.datastore.v1.PropertyFilter.Operator.EQUAL; +import static com.google.datastore.v1.PropertyOrder.Direction.DESCENDING; +import static com.google.datastore.v1.client.DatastoreHelper.makeDelete; +import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; +import static com.google.datastore.v1.client.DatastoreHelper.makeKey; +import static com.google.datastore.v1.client.DatastoreHelper.makeOrder; +import static com.google.datastore.v1.client.DatastoreHelper.makeUpsert; +import static com.google.datastore.v1.client.DatastoreHelper.makeValue; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.Assert.assertEquals; @@ -45,34 +45,35 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DatastoreWriterFn; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteEntity; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteEntityFn; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteKey; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.DeleteKeyFn; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.ReadFn; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.SplitQueryFn; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Read.V1Beta3Options; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.UpsertFn; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.V1Beta3DatastoreFactory; -import com.google.cloud.dataflow.sdk.io.datastore.V1Beta3.Write; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DatastoreWriterFn; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteEntity; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteEntityFn; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteKey; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteKeyFn; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.ReadFn; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.SplitQueryFn; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.V1Options; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.UpsertFn; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.V1DatastoreFactory; +import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Write; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.DoFnTester; import com.google.cloud.dataflow.sdk.transforms.DoFnTester.CloningBehavior; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; -import com.google.datastore.v1beta3.CommitRequest; -import com.google.datastore.v1beta3.Entity; -import com.google.datastore.v1beta3.EntityResult; -import com.google.datastore.v1beta3.Key; -import com.google.datastore.v1beta3.Mutation; -import com.google.datastore.v1beta3.PartitionId; -import com.google.datastore.v1beta3.Query; -import com.google.datastore.v1beta3.QueryResultBatch; -import com.google.datastore.v1beta3.RunQueryRequest; -import com.google.datastore.v1beta3.RunQueryResponse; -import com.google.datastore.v1beta3.client.Datastore; -import com.google.datastore.v1beta3.client.QuerySplitter; +import com.google.datastore.v1.CommitRequest; +import com.google.datastore.v1.Entity; +import com.google.datastore.v1.EntityResult; +import com.google.datastore.v1.Key; +import com.google.datastore.v1.Mutation; +import com.google.datastore.v1.PartitionId; +import com.google.datastore.v1.Query; +import com.google.datastore.v1.QueryResultBatch; +import com.google.datastore.v1.RunQueryRequest; +import com.google.datastore.v1.RunQueryResponse; +import com.google.datastore.v1.client.Datastore; +import com.google.datastore.v1.client.QuerySplitter; import com.google.protobuf.Int32Value; import org.junit.Before; @@ -93,29 +94,29 @@ import java.util.Set; /** - * Tests for {@link V1Beta3}. + * Tests for {@link DatastoreV1}. */ @RunWith(JUnit4.class) -public class V1Beta3Test { +public class DatastoreV1Test { private static final String PROJECT_ID = "testProject"; private static final String NAMESPACE = "testNamespace"; private static final String KIND = "testKind"; private static final Query QUERY; - private static final V1Beta3Options v1Beta3Options; + private static final V1Options v1Options; static { Query.Builder q = Query.newBuilder(); q.addKindBuilder().setName(KIND); QUERY = q.build(); - v1Beta3Options = V1Beta3Options.from(PROJECT_ID, QUERY, NAMESPACE); + v1Options = V1Options.from(PROJECT_ID, QUERY, NAMESPACE); } - private V1Beta3.Read initialRead; + private DatastoreV1.Read initialRead; @Mock Datastore mockDatastore; @Mock QuerySplitter mockQuerySplitter; @Mock - V1Beta3DatastoreFactory mockDatastoreFactory; + V1DatastoreFactory mockDatastoreFactory; @Rule public final ExpectedException thrown = ExpectedException.none(); @@ -124,7 +125,7 @@ public class V1Beta3Test { public void setUp() { MockitoAnnotations.initMocks(this); - initialRead = DatastoreIO.v1beta3().read() + initialRead = DatastoreIO.v1().read() .withProjectId(PROJECT_ID).withQuery(QUERY).withNamespace(NAMESPACE); when(mockDatastoreFactory.getDatastore(any(PipelineOptions.class), any(String.class))) @@ -135,7 +136,7 @@ public void setUp() { @Test public void testBuildRead() throws Exception { - V1Beta3.Read read = DatastoreIO.v1beta3().read() + Read read = DatastoreIO.v1().read() .withProjectId(PROJECT_ID).withQuery(QUERY).withNamespace(NAMESPACE); assertEquals(QUERY, read.getQuery()); assertEquals(PROJECT_ID, read.getProjectId()); @@ -147,7 +148,7 @@ public void testBuildRead() throws Exception { */ @Test public void testBuildReadAlt() throws Exception { - V1Beta3.Read read = DatastoreIO.v1beta3().read() + Read read = DatastoreIO.v1().read() .withProjectId(PROJECT_ID).withNamespace(NAMESPACE).withQuery(QUERY); assertEquals(QUERY, read.getQuery()); assertEquals(PROJECT_ID, read.getProjectId()); @@ -156,7 +157,7 @@ public void testBuildReadAlt() throws Exception { @Test public void testReadValidationFailsProject() throws Exception { - V1Beta3.Read read = DatastoreIO.v1beta3().read().withQuery(QUERY); + Read read = DatastoreIO.v1().read().withQuery(QUERY); thrown.expect(NullPointerException.class); thrown.expectMessage("project"); read.validate(null); @@ -164,7 +165,7 @@ public void testReadValidationFailsProject() throws Exception { @Test public void testReadValidationFailsQuery() throws Exception { - V1Beta3.Read read = DatastoreIO.v1beta3().read().withProjectId(PROJECT_ID); + Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID); thrown.expect(NullPointerException.class); thrown.expectMessage("query"); read.validate(null); @@ -176,7 +177,7 @@ public void testReadValidationFailsQueryLimitZero() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Invalid query limit 0: must be positive"); - DatastoreIO.v1beta3().read().withQuery(invalidLimit); + DatastoreIO.v1().read().withQuery(invalidLimit); } @Test @@ -185,19 +186,19 @@ public void testReadValidationFailsQueryLimitNegative() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Invalid query limit -5: must be positive"); - DatastoreIO.v1beta3().read().withQuery(invalidLimit); + DatastoreIO.v1().read().withQuery(invalidLimit); } @Test public void testReadValidationSucceedsNamespace() throws Exception { - V1Beta3.Read read = DatastoreIO.v1beta3().read().withProjectId(PROJECT_ID).withQuery(QUERY); + DatastoreV1.Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID).withQuery(QUERY); /* Should succeed, as a null namespace is fine. */ read.validate(null); } @Test public void testReadDisplayData() { - V1Beta3.Read read = DatastoreIO.v1beta3().read() + DatastoreV1.Read read = DatastoreIO.v1().read() .withProjectId(PROJECT_ID) .withQuery(QUERY) .withNamespace(NAMESPACE); @@ -214,12 +215,12 @@ public void testWriteDoesNotAllowNullProject() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("projectId"); - DatastoreIO.v1beta3().write().withProjectId(null); + DatastoreIO.v1().write().withProjectId(null); } @Test public void testWriteValidationFailsWithNoProject() throws Exception { - Write write = DatastoreIO.v1beta3().write(); + Write write = DatastoreIO.v1().write(); thrown.expect(NullPointerException.class); thrown.expectMessage("projectId"); @@ -229,13 +230,13 @@ public void testWriteValidationFailsWithNoProject() throws Exception { @Test public void testWriteValidationSucceedsWithProject() throws Exception { - Write write = DatastoreIO.v1beta3().write().withProjectId(PROJECT_ID); + Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); write.validate(null); } @Test public void testWriteDisplayData() { - Write write = DatastoreIO.v1beta3().write() + Write write = DatastoreIO.v1().write() .withProjectId(PROJECT_ID); DisplayData displayData = DisplayData.from(write); @@ -249,12 +250,12 @@ public void testDeleteEntityDoesNotAllowNullProject() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("projectId"); - DatastoreIO.v1beta3().deleteEntity().withProjectId(null); + DatastoreIO.v1().deleteEntity().withProjectId(null); } @Test public void testDeleteEntityValidationFailsWithNoProject() throws Exception { - DeleteEntity deleteEntity = DatastoreIO.v1beta3().deleteEntity(); + DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity(); thrown.expect(NullPointerException.class); thrown.expectMessage("projectId"); @@ -264,13 +265,13 @@ public void testDeleteEntityValidationFailsWithNoProject() throws Exception { @Test public void testDeleteEntityValidationSucceedsWithProject() throws Exception { - DeleteEntity deleteEntity = DatastoreIO.v1beta3().deleteEntity().withProjectId(PROJECT_ID); + DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity().withProjectId(PROJECT_ID); deleteEntity.validate(null); } @Test public void testDeleteEntityDisplayData() { - DeleteEntity deleteEntity = DatastoreIO.v1beta3().deleteEntity().withProjectId(PROJECT_ID); + DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity().withProjectId(PROJECT_ID); DisplayData displayData = DisplayData.from(deleteEntity); @@ -283,12 +284,12 @@ public void testDeleteKeyDoesNotAllowNullProject() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("projectId"); - DatastoreIO.v1beta3().deleteKey().withProjectId(null); + DatastoreIO.v1().deleteKey().withProjectId(null); } @Test public void testDeleteKeyValidationFailsWithNoProject() throws Exception { - DeleteKey deleteKey = DatastoreIO.v1beta3().deleteKey(); + DeleteKey deleteKey = DatastoreIO.v1().deleteKey(); thrown.expect(NullPointerException.class); thrown.expectMessage("projectId"); @@ -298,13 +299,13 @@ public void testDeleteKeyValidationFailsWithNoProject() throws Exception { @Test public void testDeleteKeyValidationSucceedsWithProject() throws Exception { - DeleteKey deleteKey = DatastoreIO.v1beta3().deleteKey().withProjectId(PROJECT_ID); + DeleteKey deleteKey = DatastoreIO.v1().deleteKey().withProjectId(PROJECT_ID); deleteKey.validate(null); } @Test public void testDeleteKeyDisplayData() { - DeleteKey deleteKey = DatastoreIO.v1beta3().deleteKey().withProjectId(PROJECT_ID); + DeleteKey deleteKey = DatastoreIO.v1().deleteKey().withProjectId(PROJECT_ID); DisplayData displayData = DisplayData.from(deleteKey); @@ -317,7 +318,7 @@ public void testDeleteKeyDisplayData() { */ @Test public void testBuildWrite() throws Exception { - V1Beta3.Write write = DatastoreIO.v1beta3().write().withProjectId(PROJECT_ID); + DatastoreV1.Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); assertEquals(PROJECT_ID, write.getProjectId()); } @@ -494,7 +495,7 @@ private void datastoreWriterFnTest(int numMutations) throws Exception { } } /** - * Tests {@link V1Beta3.Read#getEstimatedSizeBytes} to fetch and return estimated size for a + * Tests {@link DatastoreV1.Read#getEstimatedSizeBytes} to fetch and return estimated size for a * query. */ @Test @@ -521,7 +522,7 @@ public void testSplitQueryFnWithNumSplits() throws Exception { eq(QUERY), any(PartitionId.class), eq(numSplits), any(Datastore.class))) .thenReturn(splitQuery(QUERY, numSplits)); - SplitQueryFn splitQueryFn = new SplitQueryFn(v1Beta3Options, numSplits, mockDatastoreFactory); + SplitQueryFn splitQueryFn = new SplitQueryFn(v1Options, numSplits, mockDatastoreFactory); DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); /** * Although Datastore client is marked transient in {@link SplitQueryFn}, when injected through @@ -559,7 +560,7 @@ public void testSplitQueryFnWithoutNumSplits() throws Exception { eq(QUERY), any(PartitionId.class), eq(expectedNumSplits), any(Datastore.class))) .thenReturn(splitQuery(QUERY, expectedNumSplits)); - SplitQueryFn splitQueryFn = new SplitQueryFn(v1Beta3Options, numSplits, mockDatastoreFactory); + SplitQueryFn splitQueryFn = new SplitQueryFn(v1Options, numSplits, mockDatastoreFactory); DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); List> queries = doFnTester.processBatch(QUERY); @@ -572,7 +573,7 @@ public void testSplitQueryFnWithoutNumSplits() throws Exception { } /** - * Tests {@link V1Beta3.Read.SplitQueryFn} when the query has a user specified limit. + * Tests {@link DatastoreV1.Read.SplitQueryFn} when the query has a user specified limit. */ @Test public void testSplitQueryFnWithQueryLimit() throws Exception { @@ -580,7 +581,7 @@ public void testSplitQueryFnWithQueryLimit() throws Exception { .setLimit(Int32Value.newBuilder().setValue(1)) .build(); - SplitQueryFn splitQueryFn = new SplitQueryFn(v1Beta3Options, 10, mockDatastoreFactory); + SplitQueryFn splitQueryFn = new SplitQueryFn(v1Options, 10, mockDatastoreFactory); DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); List> queries = doFnTester.processBatch(queryWithLimit); @@ -623,10 +624,10 @@ private void verifyUniqueKeys(List> queries) { /** * A helper function that creates mock {@link Entity} results in response to a query. Always * indicates that more results are available, unless the batch is limited to fewer than - * {@link V1Beta3.Read#QUERY_BATCH_LIMIT} results. + * {@link DatastoreV1.Read#QUERY_BATCH_LIMIT} results. */ private static RunQueryResponse mockResponseForQuery(Query q) { - // Every query V1Beta3 sends should have a limit. + // Every query DatastoreV1 sends should have a limit. assertTrue(q.hasLimit()); // The limit should be in the range [1, QUERY_BATCH_LIMIT] @@ -672,7 +673,7 @@ public RunQueryResponse answer(InvocationOnMock invocationOnMock) throws Throwab } }); - ReadFn readFn = new ReadFn(v1Beta3Options, mockDatastoreFactory); + ReadFn readFn = new ReadFn(v1Options, mockDatastoreFactory); DoFnTester doFnTester = DoFnTester.of(readFn); /** * Although Datastore client is marked transient in {@link ReadFn}, when injected through From b79bb74d1f846629e8da8c24b8a5f9d77c4c8f37 Mon Sep 17 00:00:00 2001 From: lukecwik Date: Wed, 24 Aug 2016 13:30:10 -0700 Subject: [PATCH 538/751] Fix TestPipeline javadoc to correspond with current implementation. (#399) --- .../dataflow/sdk/testing/TestPipeline.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java index a05a7785d9..620ff0055c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java @@ -41,16 +41,23 @@ * configured to run locally or against the live service. * *

            It is recommended to tag hand-selected tests for this purpose using the - * RunnableOnService Category annotation, as each test run against the service - * will spin up and tear down a single VM. + * {@code @RunnableOnService} category annotation, and use a category aware + * test executor such as JUnit. Each test run against the service will spin + * up and tear down VMs. * - *

            In order to run tests on the dataflow pipeline service, the following + *

            In order to run tests on Google Cloud Dataflow, the following * conditions must be met: *

              - *
            • runIntegrationTestOnService System property must be set to true. - *
            • System property "projectName" must be set to your Cloud project. - *
            • System property "temp_gcs_directory" must be set to a valid GCS bucket. - *
            • Jars containing the SDK and test classes must be added to the test classpath. + *
            • System property {@code runIntegrationTestOnService} must be set to true.
            • + *
            • System property {@code dataflowOptions} must contain a JSON delimited list + * of pipeline options with all options that the Google Cloud Dataflow service requires. + * For example: + *
              {@code [
              + *     "--project=mygcpproject",
              + *     "--stagingLocation=gs://mygcsbucket/path"
              + *     ]}
              + * Note that the set of pipeline options required can also be test specific.
            • + *
            • Jars containing the SDK and test classes must be available on the classpath.
            • *
            * *

            Use {@link DataflowAssert} for tests, as it integrates with this test From 91df685dda50fff934b00fcf2dbb04028badd49e Mon Sep 17 00:00:00 2001 From: bchambers Date: Thu, 25 Aug 2016 10:47:37 -0700 Subject: [PATCH 539/751] Synchronize on the StateSampler in all cases. --- .../cloud/dataflow/sdk/util/common/worker/StateSampler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java index 125e398663..bb8a1589fb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java @@ -85,7 +85,7 @@ public Closeable scheduleSampling(final StateSampler sampler) { @Override public void run() { long delay = ThreadLocalRandom.current().nextInt((int) samplingPeriodMs); - synchronized (this) { + synchronized (sampler) { if (invocationFuture != null) { invocationFuture.cancel(false); } @@ -107,7 +107,7 @@ public void run() { @Override public void close() throws IOException { - synchronized (this) { + synchronized (sampler) { if (invocationTriggerFuture != null) { invocationTriggerFuture.cancel(false); invocationTriggerFuture = null; From f8f4701190cae18347523a336e0427d489da2bf3 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 26 Aug 2016 13:57:16 -0700 Subject: [PATCH 540/751] Dynamically choose number of shards in the InProcessPipelineRunner (#400) * Add Additional Exists check to FileIOChannelFactory#create This ensures that if the folder did not exist when first checked, but did by the time mkdirs was executed (and thus mkdirs returned false) the create will not fail. * Dynamically choose number of shards in the InProcessPipelineRunner Add a Write Override Factory that limits the number of shards if unspecified. This ensures that we will not write an output file per-key due to bundling. Do so by obtaining a count of the elements and obtaining the number of shards based on the number of outputs. --- .../inprocess/InProcessPipelineRunner.java | 4 +- .../inprocess/WriteWithShardingFactory.java | 134 ++++++++ .../sdk/util/FileIOChannelFactory.java | 3 +- .../cloud/dataflow/sdk/io/TextIOTest.java | 18 +- .../cloud/dataflow/sdk/io/WriteTest.java | 3 +- .../WriteWithShardingFactoryTest.java | 288 ++++++++++++++++++ 6 files changed, 441 insertions(+), 9 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 9f0aea11e6..0a23961ffa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -19,6 +19,7 @@ import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; import com.google.cloud.dataflow.sdk.PipelineResult; import com.google.cloud.dataflow.sdk.annotations.Experimental; +import com.google.cloud.dataflow.sdk.io.Write; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.runners.AggregatorPipelineExtractor; import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; @@ -50,9 +51,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; - import org.joda.time.Instant; - import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -78,6 +77,7 @@ public class InProcessPipelineRunner .put(Create.Values.class, new InProcessCreateOverrideFactory()) .put(GroupByKey.class, new InProcessGroupByKeyOverrideFactory()) .put(CreatePCollectionView.class, new InProcessViewOverrideFactory()) + .put(Write.Bound.class, new WriteWithShardingFactory()) .build(); /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java new file mode 100644 index 0000000000..6de64603f8 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.io.Write; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.Values; +import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; +import com.google.common.annotations.VisibleForTesting; +import org.joda.time.Duration; +import java.util.concurrent.ThreadLocalRandom; + +/** + * A {@link PTransformOverrideFactory} that overrides {@link Write} {@link PTransform PTransforms} + * with an unspecified number of shards with a write with a specified number of shards. The number + * of shards is the log base 10 of the number of input records, with up to 2 additional shards. + */ +class WriteWithShardingFactory implements PTransformOverrideFactory { + static final int MAX_RANDOM_EXTRA_SHARDS = 3; + + @Override + public PTransform override( + PTransform transform) { + if (transform instanceof Write.Bound) { + Write.Bound that = (Write.Bound) transform; + if (that.getNumShards() == 0) { + return (PTransform) new DynamicallyReshardedWrite(that); + } + } + return transform; + } + + private static class DynamicallyReshardedWrite extends PTransform, PDone> { + private final transient Write.Bound original; + + private DynamicallyReshardedWrite(Write.Bound original) { + this.original = original; + } + + @Override + public PDone apply(PCollection input) { + PCollection records = input.apply("RewindowInputs", + Window.into(new GlobalWindows()).triggering(DefaultTrigger.of()) + .withAllowedLateness(Duration.ZERO) + .discardingFiredPanes()); + final PCollectionView numRecords = records.apply(Count.globally().asSingletonView()); + PCollection resharded = + records + .apply( + "ApplySharding", + ParDo.withSideInputs(numRecords) + .of( + new KeyBasedOnCountFn( + numRecords, + ThreadLocalRandom.current().nextInt(MAX_RANDOM_EXTRA_SHARDS)))) + .apply("GroupIntoShards", GroupByKey.create()) + .apply("DropShardingKeys", Values.>create()) + .apply("FlattenShardIterables", Flatten.iterables()); + // This is an inverted application to apply the expansion of the original Write PTransform + // without adding a new Write Transform Node, which would be overwritten the same way, leading + // to an infinite recursion. We cannot modify the number of shards, because that is determined + // at runtime. + return original.apply(resharded); + } + } + + @VisibleForTesting + static class KeyBasedOnCountFn extends DoFn> { + @VisibleForTesting + static final int MIN_SHARDS_FOR_LOG = 3; + + private final PCollectionView numRecords; + private final int randomExtraShards; + private int currentShard; + private int maxShards; + + KeyBasedOnCountFn(PCollectionView numRecords, int extraShards) { + this.numRecords = numRecords; + this.randomExtraShards = extraShards; + } + + @Override + public void processElement(ProcessContext c) throws Exception { + if (maxShards == 0L) { + maxShards = calculateShards(c.sideInput(numRecords)); + currentShard = ThreadLocalRandom.current().nextInt(maxShards); + } + int shard = currentShard; + currentShard = (currentShard + 1) % maxShards; + c.output(KV.of(shard, c.element())); + } + + private int calculateShards(long totalRecords) { + checkArgument( + totalRecords > 0, + "KeyBasedOnCountFn cannot be invoked on an element if there are no elements"); + if (totalRecords < MIN_SHARDS_FOR_LOG + randomExtraShards) { + return (int) totalRecords; + } + // 100mil records before >7 output files + int floorLogRecs = Double.valueOf(Math.log10(totalRecords)).intValue(); + int shards = Math.max(floorLogRecs, MIN_SHARDS_FOR_LOG) + randomExtraShards; + return shards; + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java index 77d0b830cb..443c5e240f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java @@ -107,7 +107,8 @@ public WritableByteChannel create(String spec, String mimeType) File file = new File(spec); if (file.getAbsoluteFile().getParentFile() != null && !file.getAbsoluteFile().getParentFile().exists() - && !file.getAbsoluteFile().getParentFile().mkdirs()) { + && !file.getAbsoluteFile().getParentFile().mkdirs() + && !file.getAbsoluteFile().getParentFile().exists()) { throw new IOException("Unable to create parent directories for '" + spec + "'"); } return Channels.newChannel( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 53295b0e56..b3a43f67e5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -269,11 +269,19 @@ public static void assertOutputFiles( String shardNameTemplate) throws Exception { List expectedFiles = new ArrayList<>(); - for (int i = 0; i < numShards; i++) { - expectedFiles.add( - new File( - rootLocation.getRoot(), - IOChannelUtils.constructName(outputName, shardNameTemplate, "", i, numShards))); + if (numShards == 0) { + String pattern = + IOChannelUtils.resolve(rootLocation.getRoot().getAbsolutePath(), outputName + "*"); + for (String expected : IOChannelUtils.getFactory(pattern).match(pattern)) { + expectedFiles.add(new File(expected)); + } + } else { + for (int i = 0; i < numShards; i++) { + expectedFiles.add( + new File( + rootLocation.getRoot(), + IOChannelUtils.constructName(outputName, shardNameTemplate, "", i, numShards))); + } } List actual = new ArrayList<>(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java index 58025aa100..9023ad0387 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java @@ -19,6 +19,7 @@ import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -137,7 +138,7 @@ public void testWrite() { public void testEmptyWrite() { runWrite(Collections.emptyList(), IDENTITY_MAP); // Note we did not request a sharded write, so runWrite will not validate the number of shards. - assertEquals(1, numShards.intValue()); + assertThat(numShards.intValue(), greaterThan(0)); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java new file mode 100644 index 0000000000..2e84ca31d3 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java @@ -0,0 +1,288 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.io.Sink; +import com.google.cloud.dataflow.sdk.io.TextIO; +import com.google.cloud.dataflow.sdk.io.Write; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.inprocess.WriteWithShardingFactory.KeyBasedOnCountFn; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.DoFnTester; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.util.IOChannelUtils; +import com.google.cloud.dataflow.sdk.util.PCollectionViews; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollectionView; +import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.base.Function; +import com.google.common.collect.Iterables; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import java.io.File; +import java.io.FileReader; +import java.io.Reader; +import java.nio.CharBuffer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +/** + * Tests for {@link WriteWithShardingFactory}. + */ +public class WriteWithShardingFactoryTest { + public static final int INPUT_SIZE = 10000; + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + private WriteWithShardingFactory factory = new WriteWithShardingFactory(); + + @Test + public void dynamicallyReshardedWrite() throws Exception { + List strs = new ArrayList<>(INPUT_SIZE); + for (int i = 0; i < INPUT_SIZE; i++) { + strs.add(UUID.randomUUID().toString()); + } + Collections.shuffle(strs); + + String fileName = "resharded_write"; + String outputPath = tmp.getRoot().getAbsolutePath(); + String targetLocation = IOChannelUtils.resolve(outputPath, fileName); + PipelineOptions testOptions = TestPipeline.testingPipelineOptions(); + testOptions.setRunner(InProcessPipelineRunner.class); + Pipeline p = Pipeline.create(testOptions); + // TextIO is implemented in terms of the Write PTransform. When sharding is not specified, + // resharding should be automatically applied + p.apply(Create.of(strs)).apply(TextIO.Write.to(targetLocation)); + + p.run(); + + Collection files = IOChannelUtils.getFactory(outputPath).match(targetLocation + "*"); + List actuals = new ArrayList<>(strs.size()); + for (String file : files) { + CharBuffer buf = CharBuffer.allocate((int) new File(file).length()); + try (Reader reader = new FileReader(file)) { + reader.read(buf); + buf.flip(); + } + + String[] readStrs = buf.toString().split("\n"); + for (String read : readStrs) { + if (read.length() > 0) { + actuals.add(read); + } + } + } + + assertThat(actuals, containsInAnyOrder(strs.toArray())); + assertThat( + files, + hasSize( + allOf( + greaterThan(1), + lessThan( + (int) + (Math.log10(INPUT_SIZE) + + WriteWithShardingFactory.MAX_RANDOM_EXTRA_SHARDS))))); + } + + @Test + public void withShardingSpecifiesOriginalTransform() { + PTransform, PDone> original = Write.to(new TestSink()).withNumShards(3); + + assertThat(factory.override(original), equalTo(original)); + } + + @Test + public void withNonWriteReturnsOriginalTransform() { + PTransform, PDone> original = + new PTransform, PDone>() { + @Override + public PDone apply(PCollection input) { + return PDone.in(input.getPipeline()); + } + }; + + assertThat(factory.override(original), equalTo(original)); + } + + @Test + public void withNoShardingSpecifiedReturnsNewTransform() { + PTransform, PDone> original = Write.to(new TestSink()); + assertThat(factory.override(original), not(equalTo(original))); + } + + @Test + public void keyBasedOnCountFnWithOneElement() throws Exception { + PCollectionView elementCountView = + PCollectionViews.singletonView( + TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); + KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); + DoFnTester> fnTester = DoFnTester.of(fn); + + fnTester.setSideInput(elementCountView, + Collections.>singleton(WindowedValue.valueInGlobalWindow(1L))); + + List> outputs = fnTester.processBatch("foo", "bar", "bazbar"); + assertThat( + outputs, containsInAnyOrder(KV.of(0, "foo"), KV.of(0, "bar"), KV.of(0, "bazbar"))); + } + + @Test + public void keyBasedOnCountFnWithTwoElements() throws Exception { + PCollectionView elementCountView = + PCollectionViews.singletonView( + TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); + KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); + DoFnTester> fnTester = DoFnTester.of(fn); + + fnTester.setSideInput(elementCountView, + Collections.>singleton(WindowedValue.valueInGlobalWindow(2L))); + + List> outputs = fnTester.processBatch("foo", "bar"); + assertThat( + outputs, + anyOf( + containsInAnyOrder(KV.of(0, "foo"), KV.of(1, "bar")), + containsInAnyOrder(KV.of(1, "foo"), KV.of(0, "bar")))); + } + + @Test + public void keyBasedOnCountFnFewElementsThreeShards() throws Exception { + PCollectionView elementCountView = + PCollectionViews.singletonView( + TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); + KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); + DoFnTester> fnTester = DoFnTester.of(fn); + + fnTester.setSideInput(elementCountView, + Collections.>singleton(WindowedValue.valueInGlobalWindow(100L))); + + List> outputs = + fnTester.processBatch("foo", "bar", "baz", "foobar", "foobaz", "barbaz"); + assertThat( + Iterables.transform( + outputs, + new Function, Integer>() { + @Override + public Integer apply(KV input) { + return input.getKey(); + } + }), + containsInAnyOrder(0, 0, 1, 1, 2, 2)); + } + + @Test + public void keyBasedOnCountFnManyElements() throws Exception { + PCollectionView elementCountView = + PCollectionViews.singletonView( + TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); + KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); + DoFnTester> fnTester = DoFnTester.of(fn); + + double count = Math.pow(10, 10); + fnTester.setSideInput(elementCountView, + Collections.>singleton(WindowedValue.valueInGlobalWindow((long) count))); + + List strings = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + strings.add(Long.toHexString(ThreadLocalRandom.current().nextLong())); + } + List> kvs = fnTester.processBatch(strings); + long maxKey = -1L; + for (KV kv : kvs) { + maxKey = Math.max(maxKey, kv.getKey()); + } + assertThat(maxKey, equalTo(9L)); + } + + @Test + public void keyBasedOnCountFnFewElementsExtraShards() throws Exception { + PCollectionView elementCountView = + PCollectionViews.singletonView( + TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); + KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 10); + DoFnTester> fnTester = DoFnTester.of(fn); + + long countValue = (long) KeyBasedOnCountFn.MIN_SHARDS_FOR_LOG + 3; + fnTester.setSideInput(elementCountView, + Collections.>singleton(WindowedValue.valueInGlobalWindow(countValue))); + + List strings = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + strings.add(Long.toHexString(ThreadLocalRandom.current().nextLong())); + } + List> kvs = fnTester.processBatch(strings); + long maxKey = -1L; + for (KV kv : kvs) { + maxKey = Math.max(maxKey, kv.getKey()); + } + // 0 to n-1 shard ids. + assertThat(maxKey, equalTo(countValue - 1)); + } + + @Test + public void keyBasedOnCountFnManyElementsExtraShards() throws Exception { + PCollectionView elementCountView = + PCollectionViews.singletonView( + TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); + KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 3); + DoFnTester> fnTester = DoFnTester.of(fn); + + double count = Math.pow(10, 10); + fnTester.setSideInput(elementCountView, + Collections.>singleton(WindowedValue.valueInGlobalWindow((long) count))); + + List strings = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + strings.add(Long.toHexString(ThreadLocalRandom.current().nextLong())); + } + List> kvs = fnTester.processBatch(strings); + long maxKey = -1L; + for (KV kv : kvs) { + maxKey = Math.max(maxKey, kv.getKey()); + } + assertThat(maxKey, equalTo(12L)); + } + + private static class TestSink extends Sink { + @Override + public void validate(PipelineOptions options) {} + + @Override + public WriteOperation createWriteOperation(PipelineOptions options) { + throw new IllegalArgumentException("Should not be used"); + } + } +} From 9c34b031a4de6e36f7fdf8584e15efa6382c66d4 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Fri, 26 Aug 2016 13:57:34 -0700 Subject: [PATCH 541/751] BigQueryIO.Write: raise size limit to 11 TiB (#401) BigQuery has changed their total size quota to 12 TiB. https://cloud.google.com/bigquery/quota-policy#import --- .../java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 6263c0b64a..fefc84e8be 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1463,8 +1463,8 @@ public static class Bound extends PTransform, PDone> { // Maximum number of files in a single partition. static final int MAX_NUM_FILES = 10000; - // Maximum number of bytes in a single partition. - static final long MAX_SIZE_BYTES = 3 * (1L << 40); + // Maximum number of bytes in a single partition -- 11 TiB just under BQ's 12 TiB limit. + static final long MAX_SIZE_BYTES = 11 * (1L << 40); // The maximum number of retry jobs. static final int MAX_RETRY_JOBS = 3; From ad841a1bbb98a09ce50d02bc09d779537912dd37 Mon Sep 17 00:00:00 2001 From: joshualitt Date: Fri, 26 Aug 2016 15:07:39 -0700 Subject: [PATCH 542/751] Add structured name support to dataflow worker (#371) --- .../dataflow/sdk/util/common/Counter.java | 129 +++++++++++++++--- .../dataflow/sdk/util/common/CounterSet.java | 56 +++++++- .../dataflow/sdk/util/common/NameContext.java | 43 ++++++ .../sdk/util/common/CounterSetTest.java | 122 ++++++++++++++++- .../dataflow/sdk/util/common/CounterTest.java | 15 +- 5 files changed, 337 insertions(+), 28 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java index a33e06bd05..7f40dfcb20 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java @@ -20,9 +20,12 @@ import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.OR; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import com.google.auto.value.AutoValue; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.MoreObjects; import com.google.common.util.concurrent.AtomicDouble; import java.util.Objects; @@ -114,6 +117,14 @@ public static enum AggregationKind { * @throws IllegalArgumentException if the aggregation kind is not supported */ public static Counter ints(String name, AggregationKind kind) { + return new IntegerCounter(Name.withoutStructure(name), kind); + } + + /** + * Like {@link #ints(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a + * string. + */ + public static Counter ints(Counter.Name name, AggregationKind kind) { return new IntegerCounter(name, kind); } @@ -129,6 +140,14 @@ public static Counter ints(String name, AggregationKind kind) { * @throws IllegalArgumentException if the aggregation kind is not supported */ public static Counter longs(String name, AggregationKind kind) { + return new LongCounter(Name.withoutStructure(name), kind); + } + + /** + * Like {@link #longs(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a + * string. + */ + public static Counter longs(Counter.Name name, AggregationKind kind) { return new LongCounter(name, kind); } @@ -144,6 +163,14 @@ public static Counter longs(String name, AggregationKind kind) { * @throws IllegalArgumentException if the aggregation kind is not supported */ public static Counter doubles(String name, AggregationKind kind) { + return new DoubleCounter(Name.withoutStructure(name), kind); + } + + /** + * Like {@link #doubles(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a + * string. + */ + public static Counter doubles(Counter.Name name, AggregationKind kind) { return new DoubleCounter(name, kind); } @@ -158,6 +185,14 @@ public static Counter doubles(String name, AggregationKind kind) { * @throws IllegalArgumentException if the aggregation kind is not supported */ public static Counter booleans(String name, AggregationKind kind) { + return new BooleanCounter(Name.withoutStructure(name), kind); + } + + /** + * Like {@link #booleans(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a + * string. + */ + public static Counter booleans(Counter.Name name, AggregationKind kind) { return new BooleanCounter(name, kind); } @@ -173,9 +208,17 @@ public static Counter booleans(String name, AggregationKind kind) { */ @SuppressWarnings("unused") private static Counter strings(String name, AggregationKind kind) { - return new StringCounter(name, kind); + return new StringCounter(Name.withoutStructure(name), kind); } + /** + * Like {@link #strings(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a + * string. + */ + @SuppressWarnings("unused") + private static Counter strings(Counter.Name name, AggregationKind kind) { + return new StringCounter(name, kind); + } ////////////////////////////////////////////////////////////////////////////// @@ -218,7 +261,12 @@ private static Counter strings(String name, AggregationKind kind) { * Returns the counter's name. */ public String getName() { - return name; + return this.name.counterName(); + } + + /** Returns a Name object which uniquely identifies this counter. */ + public Name getUniqueName() { + return this.name; } /** @@ -342,28 +390,26 @@ protected void setDirty() { */ @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(getName()); - sb.append(":"); - sb.append(getKind()); - sb.append("("); + String valueString; switch (kind) { case SUM: case MAX: case MIN: case AND: case OR: - sb.append(getAggregate()); + valueString = getAggregate().toString(); break; case MEAN: - sb.append(getMean()); + valueString = getMean().toString(); break; default: throw illegalArgumentException(); } - sb.append(")"); - - return sb.toString(); + return MoreObjects.toStringHelper(this) + .add("Name", name) + .add("Kind", getKind()) + .add("Value", valueString) + .toString(); } @Override @@ -418,17 +464,58 @@ public boolean isCompatibleWith(Counter that) { ////////////////////////////////////////////////////////////////////////////// - /** The name of this counter. */ - protected final String name; - /** The kind of aggregation function to apply to this counter. */ protected final AggregationKind kind; /** The commit state of this counter. **/ protected final AtomicReference commitState; + /** + * {@link Counter.Name} is the full unique name of the counter. Counters must have + * at least a name, and optionally may be associated with a {@code systemName}, an + * {@code originalName}, or both. All of these names together define a counter uniquely. + */ + @AutoValue + public abstract static class Name { + /** Create a {@link Counter.Name} with the {@code originalName} from a {@link NameContext}. */ + public static Name withOriginalName(String name, NameContext context) { + return new AutoValue_Counter_Name(name, null, + checkNotNull(context.originalName(), "Expected original name in context %s", context)); + } + + /** Create a {@link Counter.Name} with the {@code systemName} from a {@link NameContext}. */ + public static Name withSystemName(String name, NameContext context) { + return new AutoValue_Counter_Name(name, + checkNotNull(context.systemName(), "Expected system name in context %s", context), + null); + } + + /** Create a {@link Counter.Name} without a {@link NameContext}. */ + public static Name withoutStructure(String name) { + return new AutoValue_Counter_Name(name, null, null); + } + + /** Returns the non-unique {@code counterName}. */ + public abstract String counterName(); + + /** Returns an optional {@code contextSystemName}. */ + @Nullable public abstract String contextSystemName(); + + /** Returns an optional {@code contextOriginalName}. */ + @Nullable public abstract String contextOriginalName(); + } + + /** The name of this counter. */ + protected final Name name; + protected Counter(String name, AggregationKind kind) { - this.name = name; + this.name = Name.withoutStructure(name); + this.kind = kind; + this.commitState = new AtomicReference<>(CommitState.COMMITTED); + } + + protected Counter(Name name, AggregationKind kind) { + this.name = checkNotNull(name); this.kind = kind; this.commitState = new AtomicReference<>(CommitState.COMMITTED); } @@ -445,7 +532,7 @@ private static class LongCounter extends Counter { private final AtomicReference deltaMean; /** Initializes a new {@link Counter} for {@link Long} values. */ - private LongCounter(String name, AggregationKind kind) { + private LongCounter(Counter.Name name, AggregationKind kind) { super(name, kind); switch (kind) { case MEAN: @@ -657,7 +744,7 @@ private static class DoubleCounter extends Counter { AtomicReference deltaMean; /** Initializes a new {@link Counter} for {@link Double} values. */ - private DoubleCounter(String name, AggregationKind kind) { + private DoubleCounter(Counter.Name name, AggregationKind kind) { super(name, kind); switch (kind) { case MEAN: @@ -867,7 +954,7 @@ private static class BooleanCounter extends Counter { private final AtomicBoolean deltaAggregate; /** Initializes a new {@link Counter} for {@link Boolean} values. */ - private BooleanCounter(String name, AggregationKind kind) { + private BooleanCounter(Counter.Name name, AggregationKind kind) { super(name, kind); aggregate = new AtomicBoolean(); deltaAggregate = new AtomicBoolean(); @@ -952,7 +1039,7 @@ public Counter merge(Counter that) { */ private static class StringCounter extends Counter { /** Initializes a new {@link Counter} for {@link String} values. */ - private StringCounter(String name, AggregationKind kind) { + private StringCounter(Counter.Name name, AggregationKind kind) { super(name, kind); // TODO: Support MIN, MAX of Strings. throw illegalArgumentException(); @@ -1036,7 +1123,7 @@ private static class IntegerCounter extends Counter { private final AtomicReference deltaMean; /** Initializes a new {@link Counter} for {@link Integer} values. */ - private IntegerCounter(String name, AggregationKind kind) { + private IntegerCounter(Counter.Name name, AggregationKind kind) { super(name, kind); switch (kind) { case MEAN: diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java index 3c862e6c88..0e89693319 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.util.common; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.AbstractSet; import java.util.Iterator; @@ -30,7 +31,7 @@ public class CounterSet extends AbstractSet> { /** Registered counters. */ - private final ConcurrentHashMap> counters = new ConcurrentHashMap<>(); + private final ConcurrentHashMap> counters = new ConcurrentHashMap<>(); private final AddCounterMutator addCounterMutator = new AddCounterMutator(); @@ -51,6 +52,15 @@ public AddCounterMutator getAddCounterMutator() { return addCounterMutator; } + /** + * Returns an object that supports adding additional counters into + * this {@link CounterSet} with the supplied {@link NameContext}. + */ + public AddCounterMutator getAddCounterMutator(NameContext context) { + AddCounterMutator addCounterWithContextMutator = new AddCounterMutator(context); + return addCounterWithContextMutator; + } + /** * Adds a new counter, throwing an exception if a counter of the * same name already exists. @@ -73,7 +83,7 @@ public void addNewCounter(Counter counter) { * name but an incompatible kind had already been added */ public Counter addOrReuseCounter(Counter counter) { - Counter oldCounter = counters.putIfAbsent(counter.getName(), counter); + Counter oldCounter = counters.putIfAbsent(counter.getUniqueName(), counter); if (oldCounter != null) { checkArgument(counter.isCompatibleWith(oldCounter), "Counter %s duplicates incompatible counter %s in %s", counter, oldCounter, this); @@ -96,12 +106,21 @@ public boolean addCounter(Counter counter) { return add(counter); } + /** + * Returns the {@link Counter} with the given {@link Counter.Name} in this {@link CounterSet}; + * returns null if no such {@link Counter} exists. + */ + public synchronized Counter getExistingCounter(Counter.Name name) { + return counters.get(name); + } + /** * Returns the Counter with the given name in this CounterSet; * returns null if no such Counter exists. */ public Counter getExistingCounter(String name) { - return counters.get(name); + Counter.Name unstructuredName = Counter.Name.withoutStructure(name); + return counters.get(unstructuredName); } @Override @@ -119,12 +138,12 @@ public boolean add(Counter e) { if (null == e) { return false; } - return counters.putIfAbsent(e.getName(), e) == null; + return counters.putIfAbsent(e.getUniqueName(), e) == null; } public void merge(CounterSet that) { for (Counter theirCounter : that) { - Counter myCounter = counters.get(theirCounter.getName()); + Counter myCounter = counters.get(theirCounter.getUniqueName()); if (myCounter != null) { mergeCounters(myCounter, theirCounter); } else { @@ -151,6 +170,26 @@ private void mergeCounters(Counter mine, Counter theirCounter) { * public methods of the CounterSet. */ public class AddCounterMutator { + + /** + * The {@link NameContext} to add counters into, optional. + */ + private final NameContext context; + + /** + * Constructor which takes a {@link NameContext}. + */ + public AddCounterMutator(NameContext context) { + this.context = checkNotNull(context); + } + + /** + * Default Constructor has no context associated. + */ + public AddCounterMutator() { + this.context = null; + } + /** * Adds the given Counter into the enclosing CounterSet. * @@ -164,5 +203,12 @@ public class AddCounterMutator { public Counter addCounter(Counter counter) { return addOrReuseCounter(counter); } + + /** + * Returns the {@link NameContext} associated with this mutator, if any. + */ + public NameContext getNameContext() { + return this.context; + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java new file mode 100644 index 0000000000..2e35c2f93c --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util.common; + +import com.google.auto.value.AutoValue; + +/** + * The {@link NameContext} represents the context in which a counter is reported. Specifically, + * it may be associated with a specific original step name and associated system name. + */ +@AutoValue +public abstract class NameContext { + /** Create a {@link NameContext} with both an {@code originalName} and {@code systemName}. */ + public static NameContext create(String originalName, String systemName) { + return new AutoValue_NameContext(originalName, systemName); + } + + /** + * Returns the {@code systemName} associated with this {@link NameContext}. + * This name represents the system determined name for this instruction. */ + public abstract String systemName(); + + /** + * Returns the {@code originalName} associated with this {@link NameContext}. + * This name is the name of the step in the original workflow graph which + * caused this instruction to be generated. + */ + public abstract String originalName(); +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java index 55ed714ad7..397743637e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java @@ -18,11 +18,15 @@ import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; @@ -39,6 +43,8 @@ public class CounterSetTest { private CounterSet set; + private static final String counterName = "counter-name"; + @Rule public ExpectedException thrown = ExpectedException.none(); @@ -222,4 +228,118 @@ public void testAddCounterMutatorAddMultipleCounters() { assertThat(set, containsInAnyOrder(c1, c2)); } + @Test + public void testNullCounterBeforeAdd() { + // getting a nonexistent counter returns null, then after add a value is + // returned + assertThat(set.getExistingCounter(counterName), is(nullValue())); + Counter counterAddCheck = Counter.ints(counterName, SUM); + set.addNewCounter(counterAddCheck); + assertThat(set.getExistingCounter(counterName), is(notNullValue())); + } + + @Test + public void testAddDuplicate() { + // adding an already existing counter using addNewCounter throws an exception + Counter counterAddCheck = Counter.ints(counterName, SUM); + set.addNewCounter(counterAddCheck); + thrown.expect(IllegalArgumentException.class); + set.addNewCounter(counterAddCheck); + assertThat(set.getExistingCounter(counterName), is(notNullValue())); + } + + /** + * CounterSet mutators with different contexts should not conflict with one another. + * The below tests creates a few counter mutators, some with and without an associated + * NameContext, and verify the counters added through the mutators are as + * expected. + */ + @Test + public void testMutatorsDoNotConflict() { + NameContext context = NameContext.create("original_name", "optimized_name"); + Counter.Name structuredName = + Counter.Name.withOriginalName(counterName, context); + + // Create an unstructured counter with a value + Counter counterUnstructured = Counter.ints(counterName, SUM); + set.addNewCounter(counterUnstructured); + counterUnstructured.addValue(10); + + // create a counter with the same name, but a different context and value + CounterSet.AddCounterMutator adder = set.getAddCounterMutator(context); + @SuppressWarnings("unchecked") + Counter counterStructured = Counter.ints(structuredName, SUM); + adder.addCounter(counterStructured); + counterStructured.addValue(-10); + + // now read back both counters and check values + @SuppressWarnings("unchecked") + Counter counterUnstructuredToo = + (Counter) set.getExistingCounter(counterName); + + @SuppressWarnings("unchecked") + Counter counterStructuredToo = + (Counter) set.getExistingCounter(structuredName); + assertThat(counterUnstructuredToo.getAggregate(), is(10)); + assertThat(counterStructuredToo.getAggregate(), is(-10)); + + // grab a regular mutator, first check that adding an existing counter simply reuses + adder = set.getAddCounterMutator(); + int size = set.size(); + counterUnstructuredToo = adder.addCounter(counterUnstructuredToo); + assertThat(set.size(), is(size)); + assertThat(counterUnstructuredToo.getAggregate(), is(10)); + + // This counter should still be unstructured, ie the two mutators should not interfere with one + // another + Counter.Name unstructured = counterUnstructuredToo.getUniqueName(); + assertThat(unstructured.counterName(), is(notNullValue())); + assertThat(unstructured.contextSystemName(), is(nullValue())); + assertThat(unstructured.contextOriginalName(), is(nullValue())); + } + + /** + * Adding counters to a CounterSet via mutator should be equivalent to + * directly adding counters to a CounterSet. + */ + @Test + public void testMutatorsAndConstructorAreEquivalent() { + // First a regular counterset created with an array of counters + CounterSet cs1 = + new CounterSet( + Counter.longs("counter-1", SUM).resetToValue(0L), + Counter.longs("counter-2", SUM).resetToValue(0L)); + + // Now add via counter mutator + CounterSet cs2 = new CounterSet(); + CounterSet.AddCounterMutator adder = cs2.getAddCounterMutator(); + adder.addCounter(Counter.longs("counter-1", SUM).resetToValue(0L)); + adder.addCounter(Counter.longs("counter-2", SUM).resetToValue(0L)); + assertEquals(cs1, cs2); + + // Now add unstructured counters with a counter mutator + CounterSet cs3 = new CounterSet(); + NameContext context = NameContext.create("original_name", "optimized_name"); + adder = cs3.getAddCounterMutator(context); + Counter c1 = Counter.longs("counter-1", SUM).resetToValue(0L); + Counter c2 = Counter.longs("counter-2", SUM).resetToValue(0L); + adder.addCounter(c1); + adder.addCounter(c2); + assertEquals(cs3, cs2); + + // now try two cases with structured names + c1 = Counter.longs( + Counter.Name.withOriginalName( + "counter-1", context), SUM).resetToValue(0L); + c2 = Counter.longs( + Counter.Name.withOriginalName( + "counter-2", context), SUM).resetToValue(0L); + cs1 = new CounterSet(c1, c2); + + cs2 = new CounterSet(); + adder = cs2.getAddCounterMutator(context); + adder.addCounter(c1); + adder.addCounter(c2); + assertEquals(cs1, cs2); + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java index b47050b52c..e913f1a969 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java @@ -23,6 +23,10 @@ import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MIN; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.OR; import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -92,8 +96,17 @@ public void testCompatibility() { assertTrue( Counter.longs("c", SUM).resetToValue(666L).isCompatibleWith( Counter.longs("c", SUM).resetToValue(42L))); - } + // now a structured counter should not be compatible + final String counterName = "counter-name"; + Counter counter1 = Counter.ints(counterName, SUM); + NameContext context = NameContext.create("original_name", "optimized_name"); + + Counter counterStructured = Counter.ints( + Counter.Name.withOriginalName(counterName, context), SUM); + assertThat(counter1.isCompatibleWith(counterStructured), is(false)); + assertThat(counterStructured.isCompatibleWith(counter1), is(false)); + } private void assertOK(long total, long delta, Counter c) { assertEquals(total, c.getAggregate().longValue()); From 513738a9eac89ab5258e9846d3af8079df116015 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 30 Aug 2016 09:46:05 -0700 Subject: [PATCH 543/751] Use Quiescence to Drive the DirectRunner (#408) * Add handleEmpty to CompletionCallback This is invoked when a Transform Executor has no work to do. Usually this is due to reinvocation of a Source. * Add ProducedOutput method to TransformResult This can communicate that a PTransform that produced no outputs still should cause pending work to be evaluated. PCollectionViews modifiy the state of the evaluator and can cause formerly blocked PTransforms to be able to progress. * Use the State of the Executor to drive progress Add the concept of Quiescence to ExecutorServiceParallelExecutor. If the executor is Quiescent, it should interrogate root nodes for additional work. If not, runs of the monitor should update the state as appropriate. --- .../runners/inprocess/CommittedResult.java | 23 ++- .../runners/inprocess/CompletionCallback.java | 8 + .../ExecutorServiceParallelExecutor.java | 163 +++++++++++------- .../inprocess/InProcessEvaluationContext.java | 14 +- .../inprocess/InProcessTransformResult.java | 10 +- .../inprocess/StepTransformResult.java | 19 +- .../runners/inprocess/TransformExecutor.java | 1 + .../inprocess/ViewEvaluatorFactory.java | 9 +- .../inprocess/CommittedResultTest.java | 28 +-- .../InMemoryWatermarkManagerTest.java | 14 +- .../inprocess/StepTransformResultTest.java | 88 ++++++++++ .../inprocess/TransformExecutorTest.java | 35 +++- 12 files changed, 321 insertions(+), 91 deletions(-) create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java index 7b9cfbcf8e..2e4dfe6ab9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java @@ -15,10 +15,13 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; + import com.google.auto.value.AutoValue; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import java.util.Set; + import javax.annotation.Nullable; /** @@ -45,12 +48,28 @@ abstract class CommittedResult { */ public abstract Iterable> getOutputs(); + /** + * Returns if the transform that produced this result produced outputs. + * + *

            Transforms that produce output via modifying the state of the runner (e.g. + * {@link CreatePCollectionView}) should explicitly set this to true. If {@link #getOutputs()} + * returns a nonempty iterable, this will also return true. + */ + public abstract Set getProducedOutputTypes(); + public static CommittedResult create( InProcessTransformResult original, CommittedBundle unprocessedElements, - Iterable> outputs) { + Iterable> outputs, + Set producedOutputs) { return new AutoValue_CommittedResult(original.getTransform(), unprocessedElements, - outputs); + outputs, + producedOutputs); + } + + enum OutputType { + PCOLLECTION_VIEW, + BUNDLE } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java index 6940421b93..a4495d395d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; /** * A callback for completing a bundle of input. @@ -27,6 +28,13 @@ interface CompletionCallback { CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result); + /** + * Handle an input bundle that did not require processing. + * + *

            This occurs when a Source has no splits that can currently produce outputs. + */ + void handleEmpty(AppliedPTransform transform); + /** * Handle a result that terminated abnormally due to the provided {@link Throwable}. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index b25b2db616..4855af6496 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -50,6 +50,8 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; @@ -81,6 +83,18 @@ final class ExecutorServiceParallelExecutor implements InProcessExecutor { private Collection> rootNodes; + private final AtomicReference state = + new AtomicReference<>(ExecutorState.QUIESCENT); + + /** + * Measures the number of {@link TransformExecutor TransformExecutors} that have been scheduled + * but not yet completed. + * + *

            Before a {@link TransformExecutor} is scheduled, this value is incremented. All methods in + * {@link CompletionCallback} decrement this value. + */ + private final AtomicLong outstandingWork = new AtomicLong(); + public static ExecutorServiceParallelExecutor create( ExecutorService executorService, Map>> valueToConsumers, @@ -118,7 +132,8 @@ private ExecutorServiceParallelExecutor( this.visibleUpdates = new ArrayBlockingQueue<>(20); parallelExecutorService = TransformExecutorServices.parallel(executorService); - defaultCompletionCallback = new DefaultCompletionCallback(); + defaultCompletionCallback = + new TimerIterableCompletionCallback(Collections.emptyList()); } private CacheLoader @@ -179,6 +194,7 @@ private void evaluateBundle( transform, onComplete, transformExecutor); + outstandingWork.incrementAndGet(); transformExecutor.schedule(callable); } @@ -213,18 +229,19 @@ public void awaitCompletion() throws Throwable { /** * The base implementation of {@link CompletionCallback} that provides implementations for * {@link #handleResult(CommittedBundle, InProcessTransformResult)} and - * {@link #handleThrowable(CommittedBundle, Throwable)}, given an implementation of - * {@link #getCommittedResult(CommittedBundle, InProcessTransformResult)}. + * {@link #handleThrowable(CommittedBundle, Throwable)}. */ - private abstract class CompletionCallbackBase implements CompletionCallback { - protected abstract CommittedResult getCommittedResult( - CommittedBundle inputBundle, - InProcessTransformResult result); + private class TimerIterableCompletionCallback implements CompletionCallback { + private final Iterable timers; + + protected TimerIterableCompletionCallback(Iterable timers) { + this.timers = timers; + } @Override public final CommittedResult handleResult( CommittedBundle inputBundle, InProcessTransformResult result) { - CommittedResult committedResult = getCommittedResult(inputBundle, result); + CommittedResult committedResult = evaluationContext.handleResult(inputBundle, timers, result); for (CommittedBundle outputBundle : committedResult.getOutputs()) { allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle, valueToConsumers.get(outputBundle.getPCollection()))); @@ -234,50 +251,24 @@ public final CommittedResult handleResult( allUpdates.offer(ExecutorUpdate.fromBundle(unprocessedInputs, Collections.>singleton(committedResult.getTransform()))); } + if (!committedResult.getProducedOutputTypes().isEmpty()) { + state.set(ExecutorState.ACTIVE); + } + outstandingWork.decrementAndGet(); return committedResult; } @Override - public final void handleThrowable(CommittedBundle inputBundle, Throwable t) { - allUpdates.offer(ExecutorUpdate.fromThrowable(t)); + public void handleEmpty(AppliedPTransform transform) { + outstandingWork.decrementAndGet(); } - } - /** - * The default {@link CompletionCallback}. The default completion callback is used to complete - * transform evaluations that are triggered due to the arrival of elements from an upstream - * transform, or for a source transform. - */ - private class DefaultCompletionCallback extends CompletionCallbackBase { @Override - public CommittedResult getCommittedResult( - CommittedBundle inputBundle, InProcessTransformResult result) { - return evaluationContext.handleResult(inputBundle, - Collections.emptyList(), - result); - } - } - - /** - * A {@link CompletionCallback} where the completed bundle was produced to deliver some collection - * of {@link TimerData timers}. When the evaluator completes successfully, reports all of the - * timers used to create the input to the {@link InProcessEvaluationContext evaluation context} - * as part of the result. - */ - private class TimerCompletionCallback extends CompletionCallbackBase { - private final Iterable timers; - - private TimerCompletionCallback(Iterable timers) { - this.timers = timers; - } - - @Override - public CommittedResult getCommittedResult( - CommittedBundle inputBundle, InProcessTransformResult result) { - return evaluationContext.handleResult(inputBundle, timers, result); + public final void handleThrowable(CommittedBundle inputBundle, Throwable t) { + allUpdates.offer(ExecutorUpdate.fromThrowable(t)); + outstandingWork.decrementAndGet(); } } - /** * An internal status update on the state of the executor. * @@ -355,6 +346,20 @@ public void run() { String oldName = Thread.currentThread().getName(); Thread.currentThread().setName(runnableName); try { + boolean noWorkOutstanding = outstandingWork.get() == 0L; + ExecutorState startingState = state.get(); + if (startingState == ExecutorState.ACTIVE) { + // The remainder of this call will add all available work to the Executor, and there will + // be no new work available + state.compareAndSet(ExecutorState.ACTIVE, ExecutorState.PROCESSING); + } else if (startingState == ExecutorState.PROCESSING && noWorkOutstanding) { + // The executor has consumed all new work and no new work was added + state.compareAndSet(ExecutorState.PROCESSING, ExecutorState.QUIESCING); + } else if (startingState == ExecutorState.QUIESCING && noWorkOutstanding) { + // The executor re-ran all blocked work and nothing could make progress. + state.compareAndSet(ExecutorState.QUIESCING, ExecutorState.QUIESCENT); + } + fireTimers(); Collection updates = new ArrayList<>(); // Pull all available updates off of the queue before adding additional work. This ensures // both loops terminate. @@ -366,14 +371,18 @@ public void run() { for (ExecutorUpdate update : updates) { LOG.debug("Executor Update: {}", update); if (update.getBundle().isPresent()) { - scheduleConsumers(update); + if (ExecutorState.ACTIVE == startingState || (ExecutorState.PROCESSING == startingState + && noWorkOutstanding)) { + scheduleConsumers(update); + } else { + allUpdates.offer(update); + } } else if (update.getException().isPresent()) { visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); exceptionThrown = true; } } - boolean timersFired = fireTimers(); - addWorkIfNecessary(timersFired); + addWorkIfNecessary(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.error("Monitor died due to being interrupted"); @@ -397,9 +406,8 @@ public void run() { /** * Fires any available timers. Returns true if at least one timer was fired. */ - private boolean fireTimers() throws Exception { + private void fireTimers() throws Exception { try { - boolean firedTimers = false; for (Map.Entry< AppliedPTransform, Map, FiredTimers>> transformTimers : evaluationContext.extractFiredTimers().entrySet()) { @@ -420,12 +428,11 @@ private boolean fireTimers() throws Exception { null, keyTimers.getKey(), (PCollection) transform.getInput()) .add(WindowedValue.valueInEmptyWindows(work)) .commit(evaluationContext.now()); - scheduleConsumption(transform, bundle, new TimerCompletionCallback(delivery)); - firedTimers = true; + state.set(ExecutorState.ACTIVE); + scheduleConsumption(transform, bundle, new TimerIterableCompletionCallback(delivery)); } } } - return firedTimers; } catch (Exception e) { LOG.error("Internal Error while delivering timers", e); throw e; @@ -451,18 +458,56 @@ private boolean shouldShutdown() { * add more work from root nodes that may have additional work. This ensures that if a pipeline * has elements available from the root nodes it will add those elements when necessary. */ - private void addWorkIfNecessary(boolean firedTimers) { + private void addWorkIfNecessary() { // If any timers have fired, they will add more work; We don't need to add more - if (firedTimers) { - return; - } - // All current TransformExecutors are blocked; add more work from the roots. - for (AppliedPTransform root : rootNodes) { - if (!evaluationContext.isDone(root)) { - scheduleConsumption(root, null, defaultCompletionCallback); + if (state.get() == ExecutorState.QUIESCENT) { + // All current TransformExecutors are blocked; add more work from the roots. + for (AppliedPTransform root : rootNodes) { + if (!evaluationContext.isDone(root)) { + scheduleConsumption(root, null, defaultCompletionCallback); + state.set(ExecutorState.ACTIVE); + } } } } } + + + /** + * The state of the executor. The state of the executor determines the behavior of the + * {@link MonitorRunnable} when it runs. + */ + private enum ExecutorState { + /** + * Output has been produced since the last time the monitor ran. Work exists that has not yet + * been evaluated, and all pending, including potentially blocked work, should be evaluated. + * + *

            The executor becomes active whenever a timer fires, a {@link PCollectionView} is updated, + * or output is produced by the evaluation of a {@link TransformExecutor}. + */ + ACTIVE, + /** + * The Executor does not have any unevaluated work available to it, but work is in progress. + * Work should not be added until the Executor becomes active or no work is outstanding. + * + *

            If all outstanding work completes without the executor becoming {@code ACTIVE}, the + * Executor enters state {@code QUIESCING}. Previously evaluated work must be reevaluated, in + * case a side input has made progress. + */ + PROCESSING, + /** + * All outstanding work is work that may be blocked on a side input. When there is no + * outstanding work, the executor becomes {@code QUIESCENT}. + */ + QUIESCING, + /** + * All elements are either buffered in state or are blocked on a side input. There are no + * timers that are permitted to fire but have not. There is no outstanding work. + * + *

            The pipeline will not make progress without the progression of watermarks, the progression + * of processing time, or the addition of elements. + */ + QUIESCENT + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 6ca375865d..9e5a8b190f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; @@ -44,15 +45,13 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.MoreExecutors; - import org.joda.time.Instant; - import java.util.Collection; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; - import javax.annotation.Nullable; /** @@ -155,11 +154,18 @@ public CommittedResult handleResult( Iterable> committedBundles = commitBundles(result.getOutputBundles()); // Update watermarks and timers + EnumSet outputTypes = EnumSet.copyOf(result.getOutputTypes()); + if (Iterables.isEmpty(committedBundles)) { + outputTypes.remove(OutputType.BUNDLE); + } else { + outputTypes.add(OutputType.BUNDLE); + } CommittedResult committedResult = CommittedResult.create(result, completedBundle == null ? null : completedBundle.withElements((Iterable) result.getUnprocessedElements()), - committedBundles); + committedBundles, + outputTypes); watermarkManager.updateWatermarks( completedBundle, result.getTimerUpdate().withCompletedTimers(completedTimers), diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java index 2180c00483..fcd37a09a1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -15,6 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -23,9 +24,8 @@ import com.google.cloud.dataflow.sdk.util.WindowedValue; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; - import org.joda.time.Instant; - +import java.util.Set; import javax.annotation.Nullable; /** @@ -79,4 +79,10 @@ interface InProcessTransformResult { *

            If this evaluation did not add or remove any timers, returns an empty TimerUpdate. */ TimerUpdate getTimerUpdate(); + + /** + * Returns the types of output produced by this {@link PTransform}. This may not include + * {@link OutputType#BUNDLE}, as empty bundles may be dropped when the transform is committed. + */ + Set getOutputTypes(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java index 22f30ac70c..da6d658870 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.runners.inprocess; import com.google.auto.value.AutoValue; +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -24,11 +25,10 @@ import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; import com.google.common.collect.ImmutableList; - import org.joda.time.Instant; - import java.util.Collection; - +import java.util.EnumSet; +import java.util.Set; import javax.annotation.Nullable; /** @@ -59,6 +59,9 @@ public abstract class StepTransformResult implements InProcessTransformResult { @Override public abstract TimerUpdate getTimerUpdate(); + @Override + public abstract Set getOutputTypes(); + public static Builder withHold(AppliedPTransform transform, Instant watermarkHold) { return new Builder(transform, watermarkHold); } @@ -77,12 +80,14 @@ public static class Builder { private CopyOnAccessInMemoryStateInternals state; private TimerUpdate timerUpdate; private CounterSet counters; + private final Set producedOutputs; private final Instant watermarkHold; private Builder(AppliedPTransform transform, Instant watermarkHold) { this.transform = transform; this.watermarkHold = watermarkHold; this.bundlesBuilder = ImmutableList.builder(); + this.producedOutputs = EnumSet.noneOf(OutputType.class); this.unprocessedElementsBuilder = ImmutableList.builder(); this.timerUpdate = TimerUpdate.builder(null).build(); } @@ -95,7 +100,8 @@ public StepTransformResult build() { counters, watermarkHold, state, - timerUpdate); + timerUpdate, + producedOutputs); } public Builder withCounters(CounterSet counters) { @@ -129,6 +135,11 @@ public Builder addOutput(Collection> outputBundles) { bundlesBuilder.addAll(outputBundles); return this; } + + public Builder withAdditionalOutput(OutputType producedAdditionalOutput) { + producedOutputs.add(producedAdditionalOutput); + return this; + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java index 4430158b42..bc20af13fe 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java @@ -109,6 +109,7 @@ public void run() { TransformEvaluator evaluator = evaluatorFactory.forApplication(transform, inputBundle, evaluationContext); if (evaluator == null) { + onComplete.handleEmpty(transform); // Nothing to do return; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java index abdd61185b..e2aabc25de 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java @@ -17,6 +17,7 @@ import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; @@ -29,7 +30,6 @@ import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; - import java.util.ArrayList; import java.util.List; @@ -76,7 +76,12 @@ public void processElement(WindowedValue> element) { @Override public InProcessTransformResult finishBundle() { writer.add(elements); - return StepTransformResult.withoutHold(application).build(); + StepTransformResult.Builder resultBuilder = StepTransformResult.withoutHold(application); + if (!elements.isEmpty()) { + resultBuilder = resultBuilder.withAdditionalOutput(OutputType.PCOLLECTION_VIEW); + } + return resultBuilder + .build(); } }; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java index 28beaf2fcc..2242c67c20 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java @@ -18,6 +18,7 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -28,15 +29,14 @@ import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; import com.google.common.collect.ImmutableList; - import org.hamcrest.Matchers; import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; - import java.io.Serializable; import java.util.Collections; +import java.util.EnumSet; import java.util.List; /** @@ -54,9 +54,11 @@ public class CommittedResultTest implements Serializable { @Test public void getTransformExtractsFromResult() { CommittedResult result = - CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + CommittedResult.create( + StepTransformResult.withoutHold(transform).build(), bundleFactory.createRootBundle(created).commit(Instant.now()), - Collections.>emptyList()); + Collections.>emptyList(), + EnumSet.noneOf(OutputType.class)); assertThat(result.getTransform(), Matchers.>equalTo(transform)); } @@ -68,9 +70,11 @@ public void getUncommittedElementsEqualInput() { .add(WindowedValue.valueInGlobalWindow(2)) .commit(Instant.now()); CommittedResult result = - CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + CommittedResult.create( + StepTransformResult.withoutHold(transform).build(), bundle, - Collections.>emptyList()); + Collections.>emptyList(), + EnumSet.noneOf(OutputType.class)); assertThat(result.getUnprocessedInputs(), Matchers.>equalTo(bundle)); @@ -79,9 +83,11 @@ public void getUncommittedElementsEqualInput() { @Test public void getUncommittedElementsNull() { CommittedResult result = - CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + CommittedResult.create( + StepTransformResult.withoutHold(transform).build(), null, - Collections.>emptyList()); + Collections.>emptyList(), + EnumSet.noneOf(OutputType.class)); assertThat(result.getUnprocessedInputs(), nullValue()); } @@ -96,9 +102,11 @@ public void getOutputsEqualInput() { WindowingStrategy.globalDefault(), PCollection.IsBounded.UNBOUNDED)).commit(Instant.now())); CommittedResult result = - CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + CommittedResult.create( + StepTransformResult.withoutHold(transform).build(), bundleFactory.createRootBundle(created).commit(Instant.now()), - outputs); + outputs, + EnumSet.of(OutputType.BUNDLE, OutputType.PCOLLECTION_VIEW)); assertThat(result.getOutputs(), Matchers.containsInAnyOrder(outputs.toArray())); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java index f9f5c99d71..87ab63021d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java @@ -26,6 +26,7 @@ import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; @@ -54,7 +55,7 @@ import com.google.cloud.dataflow.sdk.values.PValue; import com.google.cloud.dataflow.sdk.values.TimestampedValue; import com.google.common.collect.ImmutableList; - +import com.google.common.collect.Iterables; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; @@ -64,13 +65,12 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; - import java.io.Serializable; import java.util.Collection; import java.util.Collections; +import java.util.EnumSet; import java.util.HashMap; import java.util.Map; - import javax.annotation.Nullable; /** @@ -1418,8 +1418,12 @@ private final CommittedResult result( AppliedPTransform transform, @Nullable CommittedBundle unprocessedBundle, Iterable> bundles) { - return CommittedResult.create(StepTransformResult.withoutHold(transform).build(), + return CommittedResult.create( + StepTransformResult.withoutHold(transform).build(), unprocessedBundle, - bundles); + bundles, + Iterables.isEmpty(bundles) + ? EnumSet.noneOf(OutputType.class) + : EnumSet.of(OutputType.BUNDLE)); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java new file mode 100644 index 0000000000..2cfaa17859 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2015 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.values.PCollection; +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link StepTransformResult}. + */ +@RunWith(JUnit4.class) +public class StepTransformResultTest { + private AppliedPTransform transform; + private BundleFactory bundleFactory; + private PCollection pc; + + @Before + public void setup() { + TestPipeline p = TestPipeline.create(); + pc = p.apply(Create.of(1, 2, 3)); + transform = pc.getProducingTransformInternal(); + + bundleFactory = InProcessBundleFactory.create(); + } + + @Test + public void producedBundlesProducedOutputs() { + UncommittedBundle bundle = bundleFactory.createRootBundle(pc); + InProcessTransformResult result = StepTransformResult.withoutHold(transform).addOutput(bundle) + .build(); + + assertThat(result.getOutputBundles(), + Matchers.>containsInAnyOrder(bundle)); + } + + @Test + public void withAdditionalOutputProducedOutputs() { + InProcessTransformResult result = StepTransformResult.withoutHold(transform) + .withAdditionalOutput(OutputType.PCOLLECTION_VIEW) + .build(); + + assertThat(result.getOutputTypes(), containsInAnyOrder(OutputType.PCOLLECTION_VIEW)); + } + + @Test + public void producedBundlesAndAdditionalOutputProducedOutputs() { + InProcessTransformResult result = StepTransformResult.withoutHold(transform) + .addOutput(bundleFactory.createRootBundle(pc)) + .withAdditionalOutput(OutputType.PCOLLECTION_VIEW) + .build(); + + assertThat(result.getOutputTypes(), hasItem(OutputType.PCOLLECTION_VIEW)); + } + + @Test + public void noBundlesNoAdditionalOutputProducedOutputsFalse() { + InProcessTransformResult result = StepTransformResult.withoutHold(transform).build(); + + assertThat(result.getOutputTypes(), emptyIterable()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java index e61707c416..68e2d24cc7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java @@ -26,6 +26,7 @@ import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; +import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -37,7 +38,6 @@ import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.util.concurrent.MoreExecutors; - import org.hamcrest.Matchers; import org.joda.time.Instant; import org.junit.Before; @@ -48,16 +48,17 @@ import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.EnumSet; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; + /** * Tests for {@link TransformExecutor}. */ @@ -130,6 +131,26 @@ public InProcessTransformResult finishBundle() throws Exception { assertThat(completionCallback.handledThrowable, is(nullValue())); } + @Test + public void nullTransformEvaluatorTerminates() throws Exception { + when(registry.forApplication(created.getProducingTransformInternal(), + null, + evaluationContext)).thenReturn(null); + + TransformExecutor executor = TransformExecutor.create(registry, + Collections.emptyList(), + evaluationContext, + null, + created.getProducingTransformInternal(), + completionCallback, + transformEvaluationState); + executor.run(); + + assertThat(completionCallback.handledResult, is(nullValue())); + assertThat(completionCallback.handledEmpty, equalTo(true)); + assertThat(completionCallback.handledThrowable, is(nullValue())); + } + @Test public void inputBundleProcessesEachElementFinishesAndCompletes() throws Exception { final InProcessTransformResult result = @@ -468,6 +489,7 @@ public InProcessTransformResult finishBundle() throws Exception { private static class RegisteringCompletionCallback implements CompletionCallback { private InProcessTransformResult handledResult = null; + private boolean handledEmpty = false; private Throwable handledThrowable = null; private final CountDownLatch onMethod; @@ -489,7 +511,14 @@ public CommittedResult handleResult( inputBundle == null ? null : inputBundle.withElements(unprocessedElements); return CommittedResult.create(result, unprocessedBundle, - Collections.>emptyList()); + Collections.>emptyList(), + EnumSet.noneOf(OutputType.class)); + } + + @Override + public void handleEmpty(AppliedPTransform transform) { + handledEmpty = true; + onMethod.countDown(); } @Override From 76979db1338969267a648cde0115052e17a420c6 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Thu, 1 Sep 2016 16:56:45 -0700 Subject: [PATCH 544/751] Add the TestStream Primitive (#410) * Add inEarlyPanesInGlobalWindow as a DataflowAssert Extractor This is for use in asserting the contents of speculative panes in the global window. * Add TestStream to the Testing package This is a source suitable for use with tests that have interesting triggering behavior. It is an Unbounded source that emits elements in bundles, and advances the watermark and processing time appropriately. Implement TestStream in the InProcessPipelineRunner --- .../inprocess/InMemoryWatermarkManager.java | 22 +- .../inprocess/InProcessEvaluationContext.java | 10 +- .../inprocess/InProcessPipelineOptions.java | 18 +- .../inprocess/InProcessPipelineRunner.java | 74 +++- .../runners/inprocess/KeyedResourcePool.java | 45 +++ .../inprocess/LockedKeyedResourcePool.java | 93 +++++ .../runners/inprocess/NanosOffsetClock.java | 14 - .../inprocess/TestStreamEvaluatorFactory.java | 217 ++++++++++ .../inprocess/TransformEvaluatorRegistry.java | 13 +- .../inprocess/WriteWithShardingFactory.java | 2 +- .../dataflow/sdk/testing/DataflowAssert.java | 31 +- .../dataflow/sdk/testing/PaneExtractors.java | 18 + .../dataflow/sdk/testing/TestStream.java | 366 +++++++++++++++++ .../InProcessEvaluationContextTest.java | 1 + .../LockedKeyedResourcePoolTest.java | 161 ++++++++ .../TestStreamEvaluatorFactoryTest.java | 213 ++++++++++ .../dataflow/sdk/testing/TestStreamTest.java | 379 ++++++++++++++++++ 17 files changed, 1623 insertions(+), 54 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index a35544af28..eec8256767 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -39,9 +39,7 @@ import com.google.common.collect.Ordering; import com.google.common.collect.SortedMultiset; import com.google.common.collect.TreeMultiset; - import org.joda.time.Instant; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -57,7 +55,6 @@ import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; - import javax.annotation.Nullable; /** @@ -1133,19 +1130,12 @@ private Iterable> elementsFromBundle(CommittedBundle< private Map, FiredTimers> extractFiredTimers() { Map, List> eventTimeTimers = inputWatermark.extractFiredEventTimeTimers(); - Map, List> processingTimers; - Map, List> synchronizedTimers; - if (inputWatermark.get().equals(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - processingTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( - TimeDomain.PROCESSING_TIME, BoundedWindow.TIMESTAMP_MAX_VALUE); - synchronizedTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( - TimeDomain.PROCESSING_TIME, BoundedWindow.TIMESTAMP_MAX_VALUE); - } else { - processingTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( - TimeDomain.PROCESSING_TIME, clock.now()); - synchronizedTimers = synchronizedProcessingInputWatermark.extractFiredDomainTimers( - TimeDomain.SYNCHRONIZED_PROCESSING_TIME, getSynchronizedProcessingInputTime()); - } + Map, List> processingTimers = + synchronizedProcessingInputWatermark.extractFiredDomainTimers(TimeDomain.PROCESSING_TIME, + clock.now()); + Map, List> synchronizedTimers = + synchronizedProcessingInputWatermark.extractFiredDomainTimers( + TimeDomain.SYNCHRONIZED_PROCESSING_TIME, getSynchronizedProcessingInputTime()); Map, Map>> groupedTimers = new HashMap<>(); groupFiredTimers(groupedTimers, eventTimeTimers, processingTimers, synchronizedTimers); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index 9e5a8b190f..b9bea5b2f4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -97,24 +97,26 @@ class InProcessEvaluationContext { public static InProcessEvaluationContext create( InProcessPipelineOptions options, + Clock clock, BundleFactory bundleFactory, Collection> rootTransforms, Map>> valueToConsumers, Map, String> stepNames, Collection> views) { return new InProcessEvaluationContext( - options, bundleFactory, rootTransforms, valueToConsumers, stepNames, views); + options, clock, bundleFactory, rootTransforms, valueToConsumers, stepNames, views); } private InProcessEvaluationContext( InProcessPipelineOptions options, + Clock clock, BundleFactory bundleFactory, Collection> rootTransforms, Map>> valueToConsumers, Map, String> stepNames, Collection> views) { this.options = checkNotNull(options); - this.clock = options.getClock(); + this.clock = clock; this.bundleFactory = checkNotNull(bundleFactory); checkNotNull(rootTransforms); checkNotNull(valueToConsumers); @@ -434,4 +436,8 @@ public boolean isDone() { public Instant now() { return clock.now(); } + + Clock getClock() { + return clock; + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java index e904ec46ce..b2894871ce 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java @@ -15,17 +15,13 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.Hidden; import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.Validation.Required; import com.google.cloud.dataflow.sdk.transforms.PTransform; - import com.fasterxml.jackson.annotation.JsonIgnore; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -37,17 +33,14 @@ public interface InProcessPipelineOptions extends PipelineOptions, ApplicationNa * Gets the {@link ExecutorServiceFactory} to use to create instances of {@link ExecutorService} * to execute {@link PTransform PTransforms}. * - *

            Note that {@link ExecutorService ExecutorServices} returned by the factory must ensure that - * it cannot enter a state in which it will not schedule additional pending work unless currently - * scheduled work completes, as this may cause the {@link Pipeline} to cease processing. - * *

            Defaults to a {@link FixedThreadPoolExecutorServiceFactory}, which produces instances of * {@link Executors#newCachedThreadPool()}. + * + * @deprecated the runner manages its own {@link ExecutorService} as an implementation detail */ + @Deprecated @JsonIgnore - @Required @Hidden - @Default.InstanceFactory(FixedThreadPoolExecutorServiceFactory.class) ExecutorServiceFactory getExecutorServiceFactory(); void setExecutorServiceFactory(ExecutorServiceFactory executorService); @@ -55,10 +48,11 @@ public interface InProcessPipelineOptions extends PipelineOptions, ApplicationNa /** * Gets the {@link Clock} used by this pipeline. The clock is used in place of accessing the * system time when time values are required by the evaluator. + * + * @deprecated the runner manages its own {@link Clock} as an implementation detail */ - @Default.InstanceFactory(NanosOffsetClock.Factory.class) + @Deprecated @JsonIgnore - @Required @Hidden @Description( "The processing time source used by the pipeline. When the current time is " diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index 0a23961ffa..775f083205 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -28,7 +28,9 @@ import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOverrideFactory; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessCreate.InProcessCreateOverrideFactory; +import com.google.cloud.dataflow.sdk.runners.inprocess.TestStreamEvaluatorFactory.InProcessTestStreamFactory; import com.google.cloud.dataflow.sdk.runners.inprocess.ViewEvaluatorFactory.InProcessViewOverrideFactory; +import com.google.cloud.dataflow.sdk.testing.TestStream; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -48,6 +50,8 @@ import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; import com.google.cloud.dataflow.sdk.values.PValue; +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -56,6 +60,7 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; /** * An In-Memory implementation of the Dataflow Programming Model. Supports Unbounded @@ -77,6 +82,7 @@ public class InProcessPipelineRunner .put(Create.Values.class, new InProcessCreateOverrideFactory()) .put(GroupByKey.class, new InProcessGroupByKeyOverrideFactory()) .put(CreatePCollectionView.class, new InProcessViewOverrideFactory()) + .put(TestStream.class, new InProcessTestStreamFactory()) .put(Write.Bound.class, new WriteWithShardingFactory()) .build(); @@ -173,6 +179,8 @@ public static interface PCollectionViewWriter { //////////////////////////////////////////////////////////////////////////////////////////////// private final InProcessPipelineOptions options; + private Supplier executorServiceSupplier; + private Supplier clockSupplier; public static InProcessPipelineRunner fromOptions(PipelineOptions options) { return new InProcessPipelineRunner(options.as(InProcessPipelineOptions.class)); @@ -180,6 +188,17 @@ public static InProcessPipelineRunner fromOptions(PipelineOptions options) { private InProcessPipelineRunner(InProcessPipelineOptions options) { this.options = options; + if (options.getExecutorServiceFactory() == null) { + executorServiceSupplier = new FixedThreadPoolSupplier(); + } else { + executorServiceSupplier = + new ExecutorServiceFactorySupplier(options.getExecutorServiceFactory()); + } + if (options.getClock() == null) { + clockSupplier = new NanosOffsetClockSupplier(); + } else { + clockSupplier = Suppliers.ofInstance(options.getClock()); + } } /** @@ -189,6 +208,14 @@ public InProcessPipelineOptions getPipelineOptions() { return options; } + Supplier getClockSupplier() { + return clockSupplier; + } + + void setClockSupplier(Supplier supplier) { + this.clockSupplier = supplier; + } + @Override public OutputT apply( PTransform transform, InputT input) { @@ -221,6 +248,7 @@ public InProcessPipelineResult run(Pipeline pipeline) { InProcessEvaluationContext context = InProcessEvaluationContext.create( getPipelineOptions(), + clockSupplier.get(), createBundleFactory(getPipelineOptions()), consumerTrackingVisitor.getRootTransforms(), consumerTrackingVisitor.getValueToConsumers(), @@ -228,14 +256,15 @@ public InProcessPipelineResult run(Pipeline pipeline) { consumerTrackingVisitor.getViews()); // independent executor service for each run - ExecutorService executorService = - context.getPipelineOptions().getExecutorServiceFactory().create(); + ExecutorService executorService = executorServiceSupplier.get(); + + TransformEvaluatorRegistry registry = TransformEvaluatorRegistry.defaultRegistry(); InProcessExecutor executor = ExecutorServiceParallelExecutor.create( executorService, consumerTrackingVisitor.getValueToConsumers(), keyedPValueVisitor.getKeyedPValues(), - TransformEvaluatorRegistry.defaultRegistry(), + registry, defaultModelEnforcements(options), context); executor.start(consumerTrackingVisitor.getRootTransforms()); @@ -361,4 +390,43 @@ public State awaitCompletion() throws Throwable { return state; } } + + /** + * A {@link Supplier} that creates a {@link ExecutorService} based on + * {@link Executors#newFixedThreadPool(int)}. + */ + private static class FixedThreadPoolSupplier implements Supplier { + @Override + public ExecutorService get() { + return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + } + } + + + /** + * A {@link Supplier} that wraps an {@link ExecutorServiceFactory}. + */ + private static class ExecutorServiceFactorySupplier implements Supplier { + private final ExecutorServiceFactory executorServiceFactory; + + public ExecutorServiceFactorySupplier( + ExecutorServiceFactory executorServiceFactory) { + this.executorServiceFactory = executorServiceFactory; + } + + @Override + public ExecutorService get() { + return executorServiceFactory.create(); + } + } + + /** + * A {@link Supplier} that creates a {@link NanosOffsetClock}. + */ + private static class NanosOffsetClockSupplier implements Supplier { + @Override + public Clock get() { + return NanosOffsetClock.create(); + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java new file mode 100644 index 0000000000..ee41f42276 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import com.google.common.base.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +/** + * A pool of resources associated with specific keys. Implementations enforce specific use patterns, + * such as limiting the the number of outstanding elements available per key. + */ +interface KeyedResourcePool { + /** + * Tries to acquire a value for the provided key, loading it via the provided loader if necessary. + * + *

            If the returned {@link Optional} contains a value, the caller obtains ownership of that + * value. The value should be released back to this {@link KeyedResourcePool} after the + * caller no longer has use of it using {@link #release(Object, Object)}. + * + *

            The provided {@link Callable} must not return null; it may either return a non-null + * value or throw an exception. + */ + Optional tryAcquire(K key, Callable loader) throws ExecutionException; + + /** + * Release the provided value, relinquishing ownership of it. Future calls to + * {@link #tryAcquire(Object, Callable)} may return the released value. + */ + void release(K key, V value); +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java new file mode 100644 index 0000000000..8757183e06 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import com.google.common.base.Optional; +import com.google.common.util.concurrent.ExecutionError; +import com.google.common.util.concurrent.UncheckedExecutionException; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutionException; + +/** + * A {@link KeyedResourcePool} which is limited to at most one outstanding instance at a time for + * each key. + */ +class LockedKeyedResourcePool implements KeyedResourcePool { + /** + * A map from each key to an {@link Optional} of the associated value. At most one value is stored + * per key, and it is obtained by at most one thread at a time. + * + *

            For each key in this map: + * + *

              + *
            • If there is no associated value, then no value has been stored yet. + *
            • If the value is {@code Optional.absent()} then the value is currently in use. + *
            • If the value is {@code Optional.present()} then the contained value is available for use. + *
            + */ + public static LockedKeyedResourcePool create() { + return new LockedKeyedResourcePool<>(); + } + + private final ConcurrentMap> cache; + + private LockedKeyedResourcePool() { + cache = new ConcurrentHashMap<>(); + } + + @Override + public Optional tryAcquire(K key, Callable loader) throws ExecutionException { + Optional value = cache.replace(key, Optional.absent()); + if (value == null) { + // No value already existed, so populate the cache with the value returned by the loader + cache.putIfAbsent(key, Optional.of(load(loader))); + // Some other thread may obtain the result after the putIfAbsent, so retry acquisition + value = cache.replace(key, Optional.absent()); + } + return value; + } + + private V load(Callable loader) throws ExecutionException { + try { + return loader.call(); + } catch (Error t) { + throw new ExecutionError(t); + } catch (RuntimeException e) { + throw new UncheckedExecutionException(e); + } catch (Exception e) { + throw new ExecutionException(e); + } + } + + @Override + public void release(K key, V value) { + Optional replaced = cache.replace(key, Optional.of(value)); + checkNotNull(replaced, "Tried to release before a value was acquired"); + checkState( + !replaced.isPresent(), + "Released a value to a %s where there is already a value present for key %s (%s). " + + "At most one value may be present at a time.", + LockedKeyedResourcePool.class.getSimpleName(), + key, + replaced); + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java index 958e26d6ee..ce95b541f6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java @@ -15,11 +15,7 @@ */ package com.google.cloud.dataflow.sdk.runners.inprocess; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - import org.joda.time.Instant; - import java.util.concurrent.TimeUnit; /** @@ -44,15 +40,5 @@ public Instant now() { baseMillis + (TimeUnit.MILLISECONDS.convert( System.nanoTime() - nanosAtBaseMillis, TimeUnit.NANOSECONDS))); } - - /** - * Creates instances of {@link NanosOffsetClock}. - */ - public static class Factory implements DefaultValueFactory { - @Override - public Clock create(PipelineOptions options) { - return new NanosOffsetClock(); - } - } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java new file mode 100644 index 0000000000..52e4e19e2e --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java @@ -0,0 +1,217 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestStream; +import com.google.cloud.dataflow.sdk.testing.TestStream.ElementEvent; +import com.google.cloud.dataflow.sdk.testing.TestStream.Event; +import com.google.cloud.dataflow.sdk.testing.TestStream.EventType; +import com.google.cloud.dataflow.sdk.testing.TestStream.ProcessingTimeEvent; +import com.google.cloud.dataflow.sdk.testing.TestStream.WatermarkEvent; +import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.util.WindowingStrategy; +import com.google.cloud.dataflow.sdk.values.PBegin; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; +import com.google.cloud.dataflow.sdk.values.PInput; +import com.google.cloud.dataflow.sdk.values.POutput; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.common.base.Supplier; +import org.joda.time.Duration; +import org.joda.time.Instant; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicReference; +import javax.annotation.Nullable; + +/** The {@link TransformEvaluatorFactory} for the {@link TestStream} primitive. */ +class TestStreamEvaluatorFactory implements TransformEvaluatorFactory { + private final KeyedResourcePool, Evaluator> evaluators = + LockedKeyedResourcePool.create(); + + @Nullable + @Override + public TransformEvaluator forApplication( + AppliedPTransform application, + @Nullable CommittedBundle inputBundle, + InProcessEvaluationContext evaluationContext) + throws Exception { + return createEvaluator((AppliedPTransform) application, evaluationContext); + } + + /** + * Returns the evaluator for the provided application of {@link TestStream}, or null if it is + * already in use. + * + *

            The documented behavior of {@link TestStream} requires the output of one event to travel + * completely through the pipeline before any additional event, so additional instances that have + * a separate collection of events cannot be created. + */ + private TransformEvaluator createEvaluator( + AppliedPTransform, TestStream> application, + InProcessEvaluationContext evaluationContext) + throws ExecutionException { + return evaluators + .tryAcquire(application, new CreateEvaluator<>(application, evaluationContext, evaluators)) + .orNull(); + } + + private static class Evaluator implements TransformEvaluator { + private final AppliedPTransform, TestStream> application; + private final InProcessEvaluationContext context; + private final KeyedResourcePool, Evaluator> cache; + private final List> events; + private int index; + private Instant currentWatermark; + + private Evaluator( + AppliedPTransform, TestStream> application, + InProcessEvaluationContext context, + KeyedResourcePool, Evaluator> cache) { + this.application = application; + this.context = context; + this.cache = cache; + this.events = application.getTransform().getEvents(); + index = 0; + currentWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE; + } + + @Override + public void processElement(WindowedValue element) throws Exception {} + + @Override + public InProcessTransformResult finishBundle() throws Exception { + try { + if (index >= events.size()) { + return StepTransformResult.withoutHold(application).build(); + } + Event event = events.get(index); + if (event.getType().equals(EventType.WATERMARK)) { + currentWatermark = ((WatermarkEvent) event).getWatermark(); + } + StepTransformResult.Builder result = + StepTransformResult.withHold(application, currentWatermark); + if (event.getType().equals(EventType.ELEMENT)) { + UncommittedBundle bundle = context.createRootBundle(application.getOutput()); + for (TimestampedValue elem : ((ElementEvent) event).getElements()) { + bundle.add( + WindowedValue.timestampedValueInGlobalWindow(elem.getValue(), elem.getTimestamp())); + } + result.addOutput(bundle); + } + if (event.getType().equals(EventType.PROCESSING_TIME)) { + ((TestClock) context.getClock()) + .advance(((ProcessingTimeEvent) event).getProcessingTimeAdvance()); + } + index++; + return result.build(); + } finally { + cache.release(application, this); + } + } + } + + private static class TestClock implements Clock { + private final AtomicReference currentTime = + new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); + + public void advance(Duration amount) { + Instant now = currentTime.get(); + currentTime.compareAndSet(now, now.plus(amount)); + } + + @Override + public Instant now() { + return currentTime.get(); + } + } + + private static class TestClockSupplier implements Supplier { + @Override + public Clock get() { + return new TestClock(); + } + } + + static class InProcessTestStreamFactory implements PTransformOverrideFactory { + @Override + public PTransform override( + PTransform transform) { + if (transform instanceof TestStream) { + return (PTransform) + new DirectTestStream((TestStream) transform); + } + return transform; + } + + private static class DirectTestStream extends PTransform> { + private final TestStream original; + + private DirectTestStream(TestStream transform) { + this.original = transform; + } + + @Override + public PCollection apply(PBegin input) { + PipelineRunner runner = input.getPipeline().getRunner(); + checkState( + runner instanceof InProcessPipelineRunner, + "%s can only be used when running with the %s", + getClass().getSimpleName(), + InProcessPipelineRunner.class.getSimpleName()); + input.getPipeline() + .getOptions() + .as(InProcessPipelineOptions.class) + .setShutdownUnboundedProducersWithMaxWatermark(true); + ((InProcessPipelineRunner) runner).setClockSupplier(new TestClockSupplier()); + return PCollection.createPrimitiveOutputInternal( + input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED) + .setCoder(original.getValueCoder()); + } + } + } + + private static class CreateEvaluator implements Callable> { + private final AppliedPTransform, TestStream> application; + private final InProcessEvaluationContext evaluationContext; + private final KeyedResourcePool, Evaluator> evaluators; + + public CreateEvaluator( + AppliedPTransform, TestStream> application, + InProcessEvaluationContext evaluationContext, + KeyedResourcePool, Evaluator> evaluators) { + this.application = application; + this.evaluationContext = evaluationContext; + this.evaluators = evaluators; + } + + @Override + public Evaluator call() throws Exception { + return new Evaluator<>(application, evaluationContext, evaluators); + } + } +} + diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java index 9dd9c9115d..cbcf3ba77b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java @@ -17,15 +17,14 @@ import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; +import com.google.cloud.dataflow.sdk.testing.TestStream; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.common.collect.ImmutableMap; - import java.util.Map; - import javax.annotation.Nullable; /** @@ -47,6 +46,7 @@ public static TransformEvaluatorRegistry defaultRegistry() { .put(FlattenPCollectionList.class, new FlattenEvaluatorFactory()) .put(ViewEvaluatorFactory.WriteView.class, new ViewEvaluatorFactory()) .put(Window.Bound.class, new WindowEvaluatorFactory()) + .put(TestStream.class, new TestStreamEvaluatorFactory()) .build(); return new TransformEvaluatorRegistry(primitives); } @@ -71,4 +71,13 @@ public TransformEvaluator forApplication( TransformEvaluatorFactory factory = factories.get(application.getTransform().getClass()); return factory.forApplication(application, inputBundle, evaluationContext); } + + /** + * A factory to create Transform Evaluator Registries. + */ + public static class Factory { + public TransformEvaluatorRegistry create() { + return TransformEvaluatorRegistry.defaultRegistry(); + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java index 6de64603f8..6d1d71d0ad 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java @@ -58,7 +58,7 @@ public PTransform extends PTransform, PDone> { + private static class DynamicallyReshardedWrite extends PTransform, PDone> { private final transient Write.Bound original; private DynamicallyReshardedWrite(Write.Bound original) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java index ea0f79de0a..3290417b9b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java @@ -192,6 +192,13 @@ public interface IterableAssert { */ IterableAssert inCombinedNonLatePanes(BoundedWindow window); + /** + * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only + * run on panes in the {@link GlobalWindow} that were emitted before the {@link GlobalWindow} + * closed. These panes have {@link Timing#EARLY}. + */ + IterableAssert inEarlyGlobalWindowPanes(); + /** * Asserts that the iterable in question contains the provided elements. * @@ -438,6 +445,11 @@ public PCollectionContentsAssert inCombinedNonLatePanes(BoundedWindow window) return withPane(window, PaneExtractors.nonLatePanes()); } + @Override + public IterableAssert inEarlyGlobalWindowPanes() { + return withPane(GlobalWindow.INSTANCE, PaneExtractors.earlyPanes()); + } + private PCollectionContentsAssert withPane( BoundedWindow window, SimpleFunction>, Iterable> paneExtractor) { @@ -627,6 +639,11 @@ public PCollectionSingletonIterableAssert inCombinedNonLatePanes(BoundedWindo return withPanes(window, PaneExtractors.>nonLatePanes()); } + @Override + public IterableAssert inEarlyGlobalWindowPanes() { + return withPanes(GlobalWindow.INSTANCE, PaneExtractors.>earlyPanes()); + } + private PCollectionSingletonIterableAssert withPanes( BoundedWindow window, SimpleFunction>>, Iterable>> paneExtractor) { @@ -708,26 +725,32 @@ public Coder getCoder() { @Override public IterableAssert inWindow(BoundedWindow window) { throw new UnsupportedOperationException( - "IterableAssert of an PCollectionView does not support windowed assertions"); + "IterableAssert of a PCollectionView does not support windowed assertions"); } @Override public IterableAssert inFinalPane(BoundedWindow window) { // TODO: Can maybe be supported? throw new UnsupportedOperationException( - "IterableAssert of an PCollectionView does not support windowed assertions"); + "IterableAssert of a PCollectionView does not support windowed assertions"); } @Override public IterableAssert inOnTimePane(BoundedWindow window) { throw new UnsupportedOperationException( - "IterableAssert of an PCollectionView does not support windowed assertions"); + "IterableAssert of a PCollectionView does not support windowed assertions"); } @Override public IterableAssert inCombinedNonLatePanes(BoundedWindow window) { throw new UnsupportedOperationException( - "IterableAssert of an PCollectionView does not support windowed assertions"); + "IterableAssert of a PCollectionView does not support windowed assertions"); + } + + @Override + public IterableAssert inEarlyGlobalWindowPanes() { + throw new UnsupportedOperationException( + "IterableAssert of a PCollectionView does not support windowed assertions"); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java index 94f6505a6c..700f035315 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java @@ -58,6 +58,10 @@ static SimpleFunction>, Iterable> nonLatePanes( return new ExtractNonLatePanes<>(); } + static SimpleFunction>, Iterable> earlyPanes() { + return new ExtractEarlyPanes<>(); + } + static SimpleFunction>, Iterable> allPanes() { return new ExtractAllPanes<>(); } @@ -136,4 +140,18 @@ public Iterable apply(Iterable> input) { return outputs; } } + + private static class ExtractEarlyPanes + extends SimpleFunction>, Iterable> { + @Override + public Iterable apply(Iterable> input) { + List outputs = new ArrayList<>(); + for (WindowedValue value : input) { + if (value.getPane().getTiming() == PaneInfo.Timing.EARLY) { + outputs.add(value.getValue()); + } + } + return outputs; + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java new file mode 100644 index 0000000000..03c7e4389f --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java @@ -0,0 +1,366 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.auto.value.AutoValue; +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.DurationCoder; +import com.google.cloud.dataflow.sdk.coders.InstantCoder; +import com.google.cloud.dataflow.sdk.coders.IterableCoder; +import com.google.cloud.dataflow.sdk.coders.StandardCoder; +import com.google.cloud.dataflow.sdk.runners.PipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.PropertyNames; +import com.google.cloud.dataflow.sdk.util.VarInt; +import com.google.cloud.dataflow.sdk.values.PBegin; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.cloud.dataflow.sdk.values.TimestampedValue.TimestampedValueCoder; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableList; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.joda.time.ReadableDuration; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Collections; +import java.util.List; + +/** + * A testing input that generates an unbounded {@link PCollection} of elements, advancing the + * watermark and processing time as elements are emitted. After all of the specified elements are + * emitted, ceases to produce output. + * + *

            Each call to a {@link TestStream.Builder} method will only be reflected in the state of the + * {@link Pipeline} after each method before it has completed and no more progress can be made by + * the {@link Pipeline}. A {@link PipelineRunner} must ensure that no more progress can be made in + * the {@link Pipeline} before advancing the state of the {@link TestStream}. + */ +public final class TestStream extends PTransform> { + private final List> events; + private final Coder coder; + + /** + * Create a new {@link TestStream.Builder} with no elements and watermark equal to {@link + * BoundedWindow#TIMESTAMP_MIN_VALUE}. + */ + public static Builder create(Coder coder) { + return new Builder<>(coder); + } + + private TestStream(Coder coder, List> events) { + this.coder = coder; + this.events = checkNotNull(events); + } + + /** + * An incomplete {@link TestStream}. Elements added to this builder will be produced in sequence + * when the pipeline created by the {@link TestStream} is run. + */ + public static class Builder { + private final Coder coder; + private final ImmutableList> events; + private final Instant currentWatermark; + + private Builder(Coder coder) { + this(coder, ImmutableList.>of(), BoundedWindow.TIMESTAMP_MIN_VALUE); + } + + private Builder(Coder coder, ImmutableList> events, Instant currentWatermark) { + this.coder = coder; + this.events = events; + this.currentWatermark = currentWatermark; + } + + /** + * Adds the specified elements to the source with timestamp equal to the current watermark. + * + * @return A {@link TestStream.Builder} like this one that will emit the provided elements + * after all earlier events have completed. + */ + @SafeVarargs + public final Builder addElements(T first, T... rest) { + TimestampedValue firstElement = TimestampedValue.of(first, currentWatermark); + @SuppressWarnings("unchecked") + TimestampedValue[] remainingElements = new TimestampedValue[rest.length]; + for (int i = 0; i < rest.length; i++) { + remainingElements[i] = TimestampedValue.of(rest[i], currentWatermark); + } + return addElements(firstElement, remainingElements); + } + + /** + * Adds the specified elements to the source with the provided timestamps. + * + * @return A {@link TestStream.Builder} like this one that will emit the provided elements + * after all earlier events have completed. + */ + @SafeVarargs + public final Builder addElements( + TimestampedValue first, TimestampedValue... rest) { + checkArgument( + first.getTimestamp().isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE), + "Elements must have timestamps before %s. Got: %s", + BoundedWindow.TIMESTAMP_MAX_VALUE, + first.getTimestamp()); + for (TimestampedValue element : rest) { + checkArgument( + element.getTimestamp().isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE), + "Elements must have timestamps before %s. Got: %s", + BoundedWindow.TIMESTAMP_MAX_VALUE, + element.getTimestamp()); + } + ImmutableList> newEvents = + ImmutableList.>builder() + .addAll(events) + .add(ElementEvent.add(first, rest)) + .build(); + return new Builder(coder, newEvents, currentWatermark); + } + + /** + * Advance the watermark of this source to the specified instant. + * + *

            The watermark must advance monotonically and cannot advance to {@link + * BoundedWindow#TIMESTAMP_MAX_VALUE} or beyond. + * + * @return A {@link TestStream.Builder} like this one that will advance the watermark to the + * specified point after all earlier events have completed. + */ + public Builder advanceWatermarkTo(Instant newWatermark) { + checkArgument( + newWatermark.isAfter(currentWatermark), "The watermark must monotonically advance"); + checkArgument( + newWatermark.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE), + "The Watermark cannot progress beyond the maximum. Got: %s. Maximum: %s", + newWatermark, + BoundedWindow.TIMESTAMP_MAX_VALUE); + ImmutableList> newEvents = ImmutableList.>builder() + .addAll(events) + .add(WatermarkEvent.advanceTo(newWatermark)) + .build(); + return new Builder(coder, newEvents, newWatermark); + } + + /** + * Advance the processing time by the specified amount. + * + * @return A {@link TestStream.Builder} like this one that will advance the processing time by + * the specified amount after all earlier events have completed. + */ + public Builder advanceProcessingTime(Duration amount) { + checkArgument( + amount.getMillis() > 0, + "Must advance the processing time by a positive amount. Got: ", + amount); + ImmutableList> newEvents = + ImmutableList.>builder() + .addAll(events) + .add(ProcessingTimeEvent.advanceBy(amount)) + .build(); + return new Builder(coder, newEvents, currentWatermark); + } + + /** + * Advance the watermark to infinity, completing this {@link TestStream}. Future calls to the + * same builder will not affect the returned {@link TestStream}. + */ + public TestStream advanceWatermarkToInfinity() { + ImmutableList> newEvents = + ImmutableList.>builder() + .addAll(events) + .add(WatermarkEvent.advanceTo(BoundedWindow.TIMESTAMP_MAX_VALUE)) + .build(); + return new TestStream<>(coder, newEvents); + } + } + + /** + * An event in a {@link TestStream}. A marker interface for all events that happen while + * evaluating a {@link TestStream}. + */ + public interface Event { + EventType getType(); + } + + /** + * The types of {@link Event} that are supported by {@link TestStream}. + */ + public enum EventType { + ELEMENT, + WATERMARK, + PROCESSING_TIME + } + + /** An {@link Event} that produces elements. */ + @AutoValue + public abstract static class ElementEvent implements Event { + public abstract Iterable> getElements(); + + @SafeVarargs + static Event add(TimestampedValue element, TimestampedValue... elements) { + return add(ImmutableList.>builder().add(element).add(elements).build()); + } + + static Event add(Iterable> elements) { + return new AutoValue_TestStream_ElementEvent<>(EventType.ELEMENT, elements); + } + } + + /** An {@link Event} that advances the watermark. */ + @AutoValue + public abstract static class WatermarkEvent implements Event { + public abstract Instant getWatermark(); + + static Event advanceTo(Instant newWatermark) { + return new AutoValue_TestStream_WatermarkEvent<>(EventType.WATERMARK, newWatermark); + } + } + + /** An {@link Event} that advances the processing time clock. */ + @AutoValue + public abstract static class ProcessingTimeEvent implements Event { + public abstract Duration getProcessingTimeAdvance(); + + static Event advanceBy(Duration amount) { + return new AutoValue_TestStream_ProcessingTimeEvent<>(EventType.PROCESSING_TIME, amount); + } + } + + @Override + public PCollection apply(PBegin input) { + throw new IllegalStateException( + String.format( + "Pipeline Runner %s does not support %s", + input.getPipeline().getRunner().getClass().getSimpleName(), + getClass().getSimpleName())); + } + + public Coder getValueCoder() { + return coder; + } + + /** + * Returns a coder suitable for encoding {@link TestStream.Event}. + */ + public Coder> getEventCoder() { + return EventCoder.of(coder); + } + + /** + * Returns the sequence of {@link Event Events} in this {@link TestStream}. + * + *

            For use by {@link PipelineRunner} authors. + */ + public List> getEvents() { + return events; + } + + /** + * A {@link Coder} that encodes and decodes {@link TestStream.Event Events}. + * + * @param the type of elements in {@link ElementEvent ElementEvents} encoded and decoded by + * this {@link EventCoder} + */ + @VisibleForTesting + static final class EventCoder extends StandardCoder> { + private static final Coder DURATION_CODER = DurationCoder.of(); + private static final Coder INSTANT_CODER = InstantCoder.of(); + private final Coder valueCoder; + private final Coder>> elementCoder; + + public static EventCoder of(Coder valueCoder) { + return new EventCoder<>(valueCoder); + } + + @JsonCreator + public static EventCoder of( + @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { + checkArgument( + components.size() == 1, + "Was expecting exactly one component coder, got %s", + components.size()); + return new EventCoder<>((Coder) components.get(0)); + } + + private EventCoder(Coder valueCoder) { + this.valueCoder = valueCoder; + this.elementCoder = IterableCoder.of(TimestampedValueCoder.of(valueCoder)); + } + + @Override + public void encode( + Event value, OutputStream outStream, Context context) + throws IOException { + VarInt.encode(value.getType().ordinal(), outStream); + switch (value.getType()) { + case ELEMENT: + Iterable> elems = ((ElementEvent) value).getElements(); + elementCoder.encode(elems, outStream, context); + break; + case WATERMARK: + Instant ts = ((WatermarkEvent) value).getWatermark(); + INSTANT_CODER.encode(ts, outStream, context); + break; + case PROCESSING_TIME: + Duration processingAdvance = ((ProcessingTimeEvent) value).getProcessingTimeAdvance(); + DURATION_CODER.encode(processingAdvance, outStream, context); + break; + default: + throw new AssertionError("Unreachable: Unsupported Event Type " + value.getType()); + } + } + + @Override + public Event decode( + InputStream inStream, Context context) throws IOException { + EventType eventType = EventType.values()[VarInt.decodeInt(inStream)]; + switch (eventType) { + case ELEMENT: + Iterable> elements = elementCoder.decode(inStream, context); + return ElementEvent.add(elements); + case WATERMARK: + return WatermarkEvent.advanceTo(INSTANT_CODER.decode(inStream, context)); + case PROCESSING_TIME: + return ProcessingTimeEvent.advanceBy( + DURATION_CODER.decode(inStream, context).toDuration()); + default: + throw new AssertionError("Unreachable: Unsupported Event Type " + eventType); + } + } + + @Override + public List> getCoderArguments() { + return Collections.singletonList(valueCoder); + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + elementCoder.verifyDeterministic(); + DURATION_CODER.verifyDeterministic(); + INSTANT_CODER.verifyDeterministic(); + } + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java index 21b325df99..21e45ffec5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java @@ -116,6 +116,7 @@ public void setup() { context = InProcessEvaluationContext.create( runner.getPipelineOptions(), + NanosOffsetClock.create(), InProcessBundleFactory.create(), rootTransforms, valueToConsumers, diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java new file mode 100644 index 0000000000..7e650b48aa --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import com.google.common.base.Optional; +import com.google.common.util.concurrent.ExecutionError; +import com.google.common.util.concurrent.UncheckedExecutionException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +/** + * Tests for {@link LockedKeyedResourcePool}. + */ +@RunWith(JUnit4.class) +public class LockedKeyedResourcePoolTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + private LockedKeyedResourcePool cache = + LockedKeyedResourcePool.create(); + + @Test + public void acquireReleaseAcquireLastLoadedOrReleased() throws ExecutionException { + Optional returned = cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + return 3; + } + }); + assertThat(returned.get(), equalTo(3)); + + cache.release("foo", 4); + Optional reacquired = cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + return 5; + } + }); + assertThat(reacquired.get(), equalTo(4)); + } + + @Test + public void acquireReleaseReleaseThrows() throws ExecutionException { + Optional returned = cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + return 3; + } + }); + assertThat(returned.get(), equalTo(3)); + + cache.release("foo", 4); + thrown.expect(IllegalStateException.class); + thrown.expectMessage("already a value present"); + thrown.expectMessage("At most one"); + cache.release("foo", 4); + } + + @Test + public void releaseBeforeAcquireThrows() { + thrown.expect(NullPointerException.class); + thrown.expectMessage("before a value was acquired"); + cache.release("bar", 3); + } + + @Test + public void multipleAcquireWithoutReleaseAbsent() throws ExecutionException { + Optional returned = cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + return 3; + } + }); + Optional secondReturned = cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + return 3; + } + }); + assertThat(secondReturned.isPresent(), is(false)); + } + + @Test + public void acquireMultipleKeysSucceeds() throws ExecutionException { + Optional returned = cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + return 3; + } + }); + Optional secondReturned = cache.tryAcquire("bar", new Callable() { + @Override + public Integer call() throws Exception { + return 4; + } + }); + + assertThat(returned.get(), equalTo(3)); + assertThat(secondReturned.get(), equalTo(4)); + } + + @Test + public void acquireThrowsExceptionWrapped() throws ExecutionException { + final Exception cause = new Exception("checkedException"); + thrown.expect(ExecutionException.class); + thrown.expectCause(equalTo(cause)); + cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + throw cause; + } + }); + } + + @Test + public void acquireThrowsRuntimeExceptionWrapped() throws ExecutionException { + final RuntimeException cause = new RuntimeException("UncheckedException"); + thrown.expect(UncheckedExecutionException.class); + thrown.expectCause(equalTo(cause)); + cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + throw cause; + } + }); + } + + @Test + public void acquireThrowsErrorWrapped() throws ExecutionException { + final Error cause = new Error("Error"); + thrown.expect(ExecutionError.class); + thrown.expectCause(equalTo(cause)); + cache.tryAcquire("foo", new Callable() { + @Override + public Integer call() throws Exception { + throw cause; + } + }); + } +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java new file mode 100644 index 0000000000..40b548d893 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.testing.TestStream; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.util.WindowedValue; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.collect.Iterables; +import org.hamcrest.Matchers; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link TestStreamEvaluatorFactory}. */ +@RunWith(JUnit4.class) +public class TestStreamEvaluatorFactoryTest { + private TestStreamEvaluatorFactory factory = new TestStreamEvaluatorFactory(); + private BundleFactory bundleFactory = InProcessBundleFactory.create(); + + /** Demonstrates that returned evaluators produce elements in sequence. */ + @Test + public void producesElementsInSequence() throws Exception { + Pipeline p = getPipeline(); + PCollection streamVals = + p.apply( + TestStream.create(VarIntCoder.of()) + .addElements(1, 2, 3) + .addElements(4, 5, 6) + .advanceWatermarkToInfinity()); + + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + when(context.createRootBundle(streamVals)) + .thenReturn( + bundleFactory.createRootBundle(streamVals), bundleFactory.createRootBundle(streamVals)); + + TransformEvaluator firstEvaluator = + factory.forApplication(streamVals.getProducingTransformInternal(), null, context); + InProcessTransformResult firstResult = firstEvaluator.finishBundle(); + + TransformEvaluator secondEvaluator = + factory.forApplication(streamVals.getProducingTransformInternal(), null, context); + InProcessTransformResult secondResult = secondEvaluator.finishBundle(); + + TransformEvaluator thirdEvaluator = + factory.forApplication(streamVals.getProducingTransformInternal(), null, context); + InProcessTransformResult thirdResult = thirdEvaluator.finishBundle(); + + assertThat( + Iterables.getOnlyElement(firstResult.getOutputBundles()) + .commit(Instant.now()) + .getElements(), + Matchers.>containsInAnyOrder( + WindowedValue.valueInGlobalWindow(1), + WindowedValue.valueInGlobalWindow(2), + WindowedValue.valueInGlobalWindow(3))); + assertThat(firstResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + + assertThat( + Iterables.getOnlyElement(secondResult.getOutputBundles()) + .commit(Instant.now()) + .getElements(), + Matchers.>containsInAnyOrder( + WindowedValue.valueInGlobalWindow(4), + WindowedValue.valueInGlobalWindow(5), + WindowedValue.valueInGlobalWindow(6))); + assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + + assertThat(Iterables.isEmpty(thirdResult.getOutputBundles()), is(true)); + assertThat(thirdResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); + } + + /** Demonstrates that at most one evaluator for an application is available at a time. */ + @Test + public void onlyOneEvaluatorAtATime() throws Exception { + Pipeline p = getPipeline(); + PCollection streamVals = + p.apply( + TestStream.create(VarIntCoder.of()).addElements(4, 5, 6).advanceWatermarkToInfinity()); + + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + TransformEvaluator firstEvaluator = + factory.forApplication(streamVals.getProducingTransformInternal(), null, context); + + // create a second evaluator before the first is finished. The evaluator should not be available + TransformEvaluator secondEvaluator = + factory.forApplication(streamVals.getProducingTransformInternal(), null, context); + assertThat(secondEvaluator, is(nullValue())); + } + + /** + * Demonstrates that multiple applications of the same {@link TestStream} produce separate + * evaluators. + */ + @Test + public void multipleApplicationsMultipleEvaluators() throws Exception { + Pipeline p = getPipeline(); + TestStream stream = + TestStream.create(VarIntCoder.of()).addElements(2).advanceWatermarkToInfinity(); + PCollection firstVals = p.apply("Stream One", stream); + PCollection secondVals = p.apply("Stream A", stream); + + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + when(context.createRootBundle(firstVals)).thenReturn(bundleFactory.createRootBundle(firstVals)); + when(context.createRootBundle(secondVals)) + .thenReturn(bundleFactory.createRootBundle(secondVals)); + + TransformEvaluator firstEvaluator = + factory.forApplication(firstVals.getProducingTransformInternal(), null, context); + // The two evaluators can exist independently + TransformEvaluator secondEvaluator = + factory.forApplication(secondVals.getProducingTransformInternal(), null, context); + + InProcessTransformResult firstResult = firstEvaluator.finishBundle(); + InProcessTransformResult secondResult = secondEvaluator.finishBundle(); + + assertThat( + Iterables.getOnlyElement(firstResult.getOutputBundles()) + .commit(Instant.now()) + .getElements(), + Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow(2))); + assertThat(firstResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + + // They both produce equal results, and don't interfere with each other + assertThat( + Iterables.getOnlyElement(secondResult.getOutputBundles()) + .commit(Instant.now()) + .getElements(), + Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow(2))); + assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + } + + /** + * Demonstrates that multiple applications of different {@link TestStream} produce independent + * evaluators. + */ + @Test + public void multipleStreamsMultipleEvaluators() throws Exception { + Pipeline p = getPipeline(); + PCollection firstVals = + p.apply( + "Stream One", + TestStream.create(VarIntCoder.of()).addElements(2).advanceWatermarkToInfinity()); + PCollection secondVals = + p.apply( + "Stream A", + TestStream.create(StringUtf8Coder.of()) + .addElements("Two") + .advanceWatermarkToInfinity()); + + InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); + when(context.createRootBundle(firstVals)).thenReturn(bundleFactory.createRootBundle(firstVals)); + when(context.createRootBundle(secondVals)) + .thenReturn(bundleFactory.createRootBundle(secondVals)); + + TransformEvaluator firstEvaluator = + factory.forApplication(firstVals.getProducingTransformInternal(), null, context); + // The two evaluators can exist independently + TransformEvaluator secondEvaluator = + factory.forApplication(secondVals.getProducingTransformInternal(), null, context); + + InProcessTransformResult firstResult = firstEvaluator.finishBundle(); + InProcessTransformResult secondResult = secondEvaluator.finishBundle(); + + assertThat( + Iterables.getOnlyElement(firstResult.getOutputBundles()) + .commit(Instant.now()) + .getElements(), + Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow(2))); + assertThat(firstResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + + assertThat( + Iterables.getOnlyElement(secondResult.getOutputBundles()) + .commit(Instant.now()) + .getElements(), + Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow("Two"))); + assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); + } + + private Pipeline getPipeline() { + PipelineOptions options = PipelineOptionsFactory.create(); + options.setRunner(InProcessPipelineRunner.class); + return Pipeline.create(options); + } + +} + diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java new file mode 100644 index 0000000000..c894317208 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java @@ -0,0 +1,379 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.testing; + +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; +import com.google.cloud.dataflow.sdk.coders.VarIntCoder; +import com.google.cloud.dataflow.sdk.coders.VarLongCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.testing.TestStream.Builder; +import com.google.cloud.dataflow.sdk.transforms.Count; +import com.google.cloud.dataflow.sdk.transforms.Flatten; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.Sum; +import com.google.cloud.dataflow.sdk.transforms.Values; +import com.google.cloud.dataflow.sdk.transforms.WithKeys; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; +import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; +import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.Never; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window; +import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import java.io.Serializable; + +/** Tests for {@link TestStream}. */ +@RunWith(JUnit4.class) +public class TestStreamTest implements Serializable { + @Rule public transient ExpectedException thrown = ExpectedException.none(); + + @Test + public void testLateDataAccumulating() { + Instant instant = new Instant(0); + TestStream source = + TestStream.create(VarIntCoder.of()) + .addElements( + TimestampedValue.of(1, instant), + TimestampedValue.of(2, instant), + TimestampedValue.of(3, instant)) + .advanceWatermarkTo(instant.plus(Duration.standardMinutes(6))) + // These elements are late but within the allowed lateness + .addElements(TimestampedValue.of(4, instant), TimestampedValue.of(5, instant)) + .advanceWatermarkTo(instant.plus(Duration.standardMinutes(20))) + // These elements are droppably late + .addElements( + TimestampedValue.of(-1, instant), + TimestampedValue.of(-2, instant), + TimestampedValue.of(-3, instant)) + .advanceWatermarkToInfinity(); + + Pipeline p = getPipeline(); + PCollection windowed = + p.apply(source) + .apply( + Window.into(FixedWindows.of(Duration.standardMinutes(5))) + .triggering( + AfterWatermark.pastEndOfWindow() + .withEarlyFirings( + AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(2))) + .withLateFirings(AfterPane.elementCountAtLeast(1))) + .accumulatingFiredPanes() + .withAllowedLateness(Duration.standardMinutes(5), ClosingBehavior.FIRE_ALWAYS)); + PCollection triggered = + windowed + .apply(WithKeys.of(1)) + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(Flatten.iterables()); + PCollection count = windowed.apply(Count.globally().withoutDefaults()); + PCollection sum = windowed.apply(Sum.integersGlobally().withoutDefaults()); + + IntervalWindow window = new IntervalWindow(instant, instant.plus(Duration.standardMinutes(5L))); + DataflowAssert.that(triggered).inFinalPane(window).containsInAnyOrder(1, 2, 3, 4, 5); + DataflowAssert.that(triggered).inOnTimePane(window).containsInAnyOrder(1, 2, 3); + DataflowAssert.that(count) + .inWindow(window) + .satisfies( + new SerializableFunction, Void>() { + @Override + public Void apply(Iterable input) { + for (Long count : input) { + assertThat(count, allOf(greaterThanOrEqualTo(3L), lessThanOrEqualTo(5L))); + } + return null; + } + }); + DataflowAssert.that(sum) + .inWindow(window) + .satisfies( + new SerializableFunction, Void>() { + @Override + public Void apply(Iterable input) { + for (Integer sum : input) { + assertThat(sum, allOf(greaterThanOrEqualTo(6), lessThanOrEqualTo(15))); + } + return null; + } + }); + + p.run(); + } + + @Test + public void testProcessingTimeTrigger() { + TestStream source = + TestStream.create(VarLongCoder.of()) + .addElements( + TimestampedValue.of(1L, new Instant(1000L)), + TimestampedValue.of(2L, new Instant(2000L))) + .advanceProcessingTime(Duration.standardMinutes(12)) + .addElements(TimestampedValue.of(3L, new Instant(3000L))) + .advanceProcessingTime(Duration.standardMinutes(6)) + .advanceWatermarkToInfinity(); + + Pipeline p = getPipeline(); + PCollection sum = + p.apply(source) + .apply( + Window.triggering( + AfterWatermark.pastEndOfWindow() + .withEarlyFirings( + AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(Duration.standardMinutes(5)))) + .accumulatingFiredPanes() + .withAllowedLateness(Duration.ZERO)) + .apply(Sum.longsGlobally()); + + DataflowAssert.that(sum).inEarlyGlobalWindowPanes().containsInAnyOrder(3L, 6L); + + p.run(); + } + + /** + * A test that demonstrates that a Trigger in discarding mode fires multiple times, and elements + * that have been produced in a pane are not produced in future panes. + */ + @Test + public void testDiscardingMode() { + TestStream stream = + TestStream.create(StringUtf8Coder.of()) + .advanceWatermarkTo(new Instant(0)) + .addElements( + TimestampedValue.of("firstPane", new Instant(100)), + TimestampedValue.of("alsoFirstPane", new Instant(200))) + .addElements(TimestampedValue.of("onTimePane", new Instant(500))) + .advanceWatermarkTo(new Instant(1001L)) + .addElements( + TimestampedValue.of("finalLatePane", new Instant(750)), + TimestampedValue.of("alsoFinalLatePane", new Instant(250))) + .advanceWatermarkToInfinity(); + + Pipeline p = getPipeline(); + FixedWindows windowFn = FixedWindows.of(Duration.millis(1000L)); + Duration allowedLateness = Duration.millis(5000L); + PCollection values = + p.apply(stream) + .apply( + Window.into(windowFn) + .triggering( + AfterWatermark.pastEndOfWindow() + .withEarlyFirings(AfterPane.elementCountAtLeast(2)) + .withLateFirings(Never.ever())) + .discardingFiredPanes() + .withAllowedLateness(allowedLateness)) + .apply(WithKeys.of(1)) + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(Flatten.iterables()); + + IntervalWindow window = windowFn.assignWindow(new Instant(100)); + DataflowAssert.that(values) + .inWindow(window) + .containsInAnyOrder( + "firstPane", "alsoFirstPane", "onTimePane", "finalLatePane", "alsoFinalLatePane"); + DataflowAssert.that(values) + .inCombinedNonLatePanes(window) + .containsInAnyOrder("firstPane", "alsoFirstPane", "onTimePane"); + DataflowAssert.that(values).inOnTimePane(window).containsInAnyOrder("onTimePane"); + DataflowAssert.that(values) + .inFinalPane(window) + .containsInAnyOrder("finalLatePane", "alsoFinalLatePane"); + + p.run(); + } + + @Test + public void testFirstElementLate() { + Instant lateElementTimestamp = new Instant(-1_000_000); + TestStream stream = + TestStream.create(StringUtf8Coder.of()) + .advanceWatermarkTo(new Instant(-1)) + .addElements(TimestampedValue.of("late", lateElementTimestamp)) + .addElements(TimestampedValue.of("onTime", new Instant(100))) + .advanceWatermarkToInfinity(); + + Pipeline p = getPipeline(); + FixedWindows windowFn = FixedWindows.of(Duration.millis(1000L)); + Duration allowedLateness = Duration.millis(5000L); + PCollection values = + p.apply(stream) + .apply( + Window.into(windowFn) + .triggering(DefaultTrigger.of()) + .discardingFiredPanes() + .withAllowedLateness(allowedLateness)) + .apply(WithKeys.of(1)) + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(Flatten.iterables()); + + DataflowAssert.that(values).inWindow(windowFn.assignWindow(lateElementTimestamp)).empty(); + DataflowAssert.that(values) + .inWindow(windowFn.assignWindow(new Instant(100))) + .containsInAnyOrder("onTime"); + + p.run(); + } + + @Test + public void testElementsAtAlmostPositiveInfinity() { + Instant endOfGlobalWindow = GlobalWindow.INSTANCE.maxTimestamp(); + TestStream stream = + TestStream.create(StringUtf8Coder.of()) + .addElements( + TimestampedValue.of("foo", endOfGlobalWindow), + TimestampedValue.of("bar", endOfGlobalWindow)) + .advanceWatermarkToInfinity(); + + Pipeline p = getPipeline(); + FixedWindows windows = FixedWindows.of(Duration.standardHours(6)); + PCollection windowedValues = + p.apply(stream) + .apply(Window.into(windows)) + .apply(WithKeys.of(1)) + .apply(GroupByKey.create()) + .apply(Values.>create()) + .apply(Flatten.iterables()); + + DataflowAssert.that(windowedValues) + .inWindow(windows.assignWindow(GlobalWindow.INSTANCE.maxTimestamp())) + .containsInAnyOrder("foo", "bar"); + p.run(); + } + + @Test + public void testMultipleStreams() { + Pipeline p = getPipeline(); + + TestStream stream = + TestStream.create(StringUtf8Coder.of()) + .addElements("foo", "bar") + .advanceWatermarkToInfinity(); + + TestStream other = + TestStream.create(VarIntCoder.of()).addElements(1, 2, 3, 4).advanceWatermarkToInfinity(); + + PCollection createStrings = + p.apply("CreateStrings", stream) + .apply( + "WindowStrings", + Window.triggering(AfterPane.elementCountAtLeast(2)) + .withAllowedLateness(Duration.ZERO) + .accumulatingFiredPanes()); + DataflowAssert.that(createStrings).containsInAnyOrder("foo", "bar"); + PCollection createInts = + p.apply("CreateInts", other) + .apply( + "WindowInts", + Window.triggering(AfterPane.elementCountAtLeast(4)) + .withAllowedLateness(Duration.ZERO) + .accumulatingFiredPanes()); + DataflowAssert.that(createInts).containsInAnyOrder(1, 2, 3, 4); + + p.run(); + } + + @Test + public void testElementAtPositiveInfinityThrows() { + Builder stream = + TestStream.create(VarIntCoder.of()) + .addElements(TimestampedValue.of(-1, BoundedWindow.TIMESTAMP_MAX_VALUE.minus(1L))); + thrown.expect(IllegalArgumentException.class); + stream.addElements(TimestampedValue.of(1, BoundedWindow.TIMESTAMP_MAX_VALUE)); + } + + @Test + public void testAdvanceWatermarkNonMonotonicThrows() { + Builder stream = + TestStream.create(VarIntCoder.of()).advanceWatermarkTo(new Instant(-1L)); + thrown.expect(IllegalArgumentException.class); + stream.advanceWatermarkTo(new Instant(-100L)); + } + + @Test + public void testAdvanceWatermarkEqualToPositiveInfinityThrows() { + Builder stream = + TestStream.create(VarIntCoder.of()) + .advanceWatermarkTo(BoundedWindow.TIMESTAMP_MAX_VALUE.minus(1L)); + thrown.expect(IllegalArgumentException.class); + stream.advanceWatermarkTo(BoundedWindow.TIMESTAMP_MAX_VALUE); + } + + private Pipeline getPipeline() { + PipelineOptions options = TestPipeline.testingPipelineOptions(); + options.setRunner(InProcessPipelineRunner.class); + return TestPipeline.fromOptions(options); + } + + @Test + public void testUnsupportedRunnerThrows() { + PipelineOptions opts = PipelineOptionsFactory.create(); + opts.setRunner(DirectPipelineRunner.class); + + Pipeline p = Pipeline.create(opts); + + thrown.expect(IllegalStateException.class); + thrown.expectMessage("DirectPipelineRunner"); + thrown.expectMessage("does not support TestStream"); + thrown.expectMessage(TestStream.class.getSimpleName()); + thrown.expectMessage(DirectPipelineRunner.class.getSimpleName()); + p.apply(TestStream.create(VarIntCoder.of()).advanceWatermarkToInfinity()); + } + + @Test + public void testEncodeDecode() throws Exception { + TestStream.Event elems = + TestStream.ElementEvent.add( + TimestampedValue.of(1, new Instant()), + TimestampedValue.of(-10, new Instant()), + TimestampedValue.of(Integer.MAX_VALUE, new Instant())); + TestStream.Event wm = TestStream.WatermarkEvent.advanceTo(new Instant(100)); + TestStream.Event procTime = + TestStream.ProcessingTimeEvent.advanceBy(Duration.millis(90548)); + + TestStream.EventCoder coder = TestStream.EventCoder.of(VarIntCoder.of()); + + CoderProperties.coderSerializable(coder); + CoderProperties.coderDecodeEncodeEqual(coder, elems); + CoderProperties.coderDecodeEncodeEqual(coder, wm); + CoderProperties.coderDecodeEncodeEqual(coder, procTime); + } +} From 2228e242975f2225667eaa5e384d714fe366e4c4 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Thu, 1 Sep 2016 17:04:02 -0700 Subject: [PATCH 545/751] DatastoreIO statistics query fixes (#406) * DatastoreIO statistics query fixes * Clean up extra spaces * Use composite filter for stats query --- .../sdk/io/datastore/DatastoreV1.java | 45 ++++++++-- .../sdk/io/datastore/DatastoreV1Test.java | 85 ++++++++++++++----- 2 files changed, 104 insertions(+), 26 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java index a146c2d78f..b2ad01e672 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java @@ -22,6 +22,7 @@ import static com.google.datastore.v1.PropertyFilter.Operator.EQUAL; import static com.google.datastore.v1.PropertyOrder.Direction.DESCENDING; import static com.google.datastore.v1.QueryResultBatch.MoreResultsType.NOT_FINISHED; +import static com.google.datastore.v1.client.DatastoreHelper.makeAndFilter; import static com.google.datastore.v1.client.DatastoreHelper.makeDelete; import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1.client.DatastoreHelper.makeOrder; @@ -240,6 +241,7 @@ static int getEstimatedNumSplits(Datastore datastore, Query query, @Nullable Str int numSplits; try { long estimatedSizeBytes = getEstimatedSizeBytes(datastore, query, namespace); + LOG.info("Estimated size bytes for the query is: {}", estimatedSizeBytes); numSplits = (int) Math.min(NUM_QUERY_SPLITS_MAX, Math.round(((double) estimatedSizeBytes) / DEFAULT_BUNDLE_SIZE_BYTES)); } catch (Exception e) { @@ -250,6 +252,33 @@ static int getEstimatedNumSplits(Datastore datastore, Query query, @Nullable Str return Math.max(numSplits, NUM_QUERY_SPLITS_MIN); } + /** + * Datastore system tables with statistics are periodically updated. This method fetches + * the latest timestamp (in microseconds) of statistics update using the {@code __Stat_Total__} + * table. + */ + private static long queryLatestStatisticsTimestamp(Datastore datastore, + @Nullable String namespace) throws DatastoreException { + Query.Builder query = Query.newBuilder(); + if (namespace == null) { + query.addKindBuilder().setName("__Stat_Total__"); + } else { + query.addKindBuilder().setName("__Stat_Ns_Total__"); + } + query.addOrder(makeOrder("timestamp", DESCENDING)); + query.setLimit(Int32Value.newBuilder().setValue(1)); + RunQueryRequest request = makeRequest(query.build(), namespace); + + RunQueryResponse response = datastore.runQuery(request); + QueryResultBatch batch = response.getBatch(); + if (batch.getEntityResultsCount() == 0) { + throw new NoSuchElementException( + "Datastore total statistics unavailable"); + } + Entity entity = batch.getEntityResults(0).getEntity(); + return entity.getProperties().get("timestamp").getTimestampValue().getSeconds() * 1000000; + } + /** * Get the estimated size of the data returned by the given query. * @@ -262,17 +291,18 @@ static int getEstimatedNumSplits(Datastore datastore, Query query, @Nullable Str static long getEstimatedSizeBytes(Datastore datastore, Query query, @Nullable String namespace) throws DatastoreException { String ourKind = query.getKind(0).getName(); + long latestTimestamp = queryLatestStatisticsTimestamp(datastore, namespace); + LOG.info("Latest stats timestamp for kind {} is {}", ourKind, latestTimestamp); + Query.Builder queryBuilder = Query.newBuilder(); if (namespace == null) { queryBuilder.addKindBuilder().setName("__Stat_Kind__"); } else { - queryBuilder.addKindBuilder().setName("__Ns_Stat_Kind__"); + queryBuilder.addKindBuilder().setName("__Stat_Ns_Kind__"); } - queryBuilder.setFilter(makeFilter("kind_name", EQUAL, makeValue(ourKind).build())); - - // Get the latest statistics - queryBuilder.addOrder(makeOrder("timestamp", DESCENDING)); - queryBuilder.setLimit(Int32Value.newBuilder().setValue(1)); + queryBuilder.setFilter(makeAndFilter( + makeFilter("kind_name", EQUAL, makeValue(ourKind).build()).build(), + makeFilter("timestamp", EQUAL, makeValue(latestTimestamp).build()).build())); RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); @@ -548,6 +578,7 @@ public void processElement(ProcessContext c) throws Exception { estimatedNumSplits = numSplits; } + LOG.info("Splitting the query into {} splits", estimatedNumSplits); List querySplits; try { querySplits = splitQuery(query, options.getNamespace(), datastore, querySplitter, @@ -868,7 +899,7 @@ public void processElement(ProcessContext c) throws Exception { @Override public void finishBundle(Context c) throws Exception { - if (mutations.size() > 0) { + if (!mutations.isEmpty()) { flushBatch(); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java index 62001b8d62..e99ebe0ca6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java @@ -25,6 +25,7 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static com.google.datastore.v1.PropertyFilter.Operator.EQUAL; import static com.google.datastore.v1.PropertyOrder.Direction.DESCENDING; +import static com.google.datastore.v1.client.DatastoreHelper.makeAndFilter; import static com.google.datastore.v1.client.DatastoreHelper.makeDelete; import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; import static com.google.datastore.v1.client.DatastoreHelper.makeKey; @@ -88,6 +89,7 @@ import org.mockito.stubbing.Answer; import java.util.ArrayList; +import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; @@ -109,7 +111,7 @@ public class DatastoreV1Test { QUERY = q.build(); v1Options = V1Options.from(PROJECT_ID, QUERY, NAMESPACE); } - private DatastoreV1.Read initialRead; + private Read initialRead; @Mock Datastore mockDatastore; @@ -148,7 +150,7 @@ public void testBuildRead() throws Exception { */ @Test public void testBuildReadAlt() throws Exception { - Read read = DatastoreIO.v1().read() + Read read = DatastoreIO.v1().read() .withProjectId(PROJECT_ID).withNamespace(NAMESPACE).withQuery(QUERY); assertEquals(QUERY, read.getQuery()); assertEquals(PROJECT_ID, read.getProjectId()); @@ -157,7 +159,7 @@ public void testBuildReadAlt() throws Exception { @Test public void testReadValidationFailsProject() throws Exception { - Read read = DatastoreIO.v1().read().withQuery(QUERY); + Read read = DatastoreIO.v1().read().withQuery(QUERY); thrown.expect(NullPointerException.class); thrown.expectMessage("project"); read.validate(null); @@ -165,7 +167,7 @@ public void testReadValidationFailsProject() throws Exception { @Test public void testReadValidationFailsQuery() throws Exception { - Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID); + Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID); thrown.expect(NullPointerException.class); thrown.expectMessage("query"); read.validate(null); @@ -191,14 +193,14 @@ public void testReadValidationFailsQueryLimitNegative() throws Exception { @Test public void testReadValidationSucceedsNamespace() throws Exception { - DatastoreV1.Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID).withQuery(QUERY); + Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID).withQuery(QUERY); /* Should succeed, as a null namespace is fine. */ read.validate(null); } @Test public void testReadDisplayData() { - DatastoreV1.Read read = DatastoreIO.v1().read() + Read read = DatastoreIO.v1().read() .withProjectId(PROJECT_ID) .withQuery(QUERY) .withNamespace(NAMESPACE); @@ -236,8 +238,7 @@ public void testWriteValidationSucceedsWithProject() throws Exception { @Test public void testWriteDisplayData() { - Write write = DatastoreIO.v1().write() - .withProjectId(PROJECT_ID); + Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); DisplayData displayData = DisplayData.from(write); @@ -271,7 +272,7 @@ public void testDeleteEntityValidationSucceedsWithProject() throws Exception { @Test public void testDeleteEntityDisplayData() { - DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity().withProjectId(PROJECT_ID); + DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity().withProjectId(PROJECT_ID); DisplayData displayData = DisplayData.from(deleteEntity); @@ -305,7 +306,7 @@ public void testDeleteKeyValidationSucceedsWithProject() throws Exception { @Test public void testDeleteKeyDisplayData() { - DeleteKey deleteKey = DatastoreIO.v1().deleteKey().withProjectId(PROJECT_ID); + DeleteKey deleteKey = DatastoreIO.v1().deleteKey().withProjectId(PROJECT_ID); DisplayData displayData = DisplayData.from(deleteKey); @@ -318,7 +319,7 @@ public void testDeleteKeyDisplayData() { */ @Test public void testBuildWrite() throws Exception { - DatastoreV1.Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); + DatastoreV1.Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); assertEquals(PROJECT_ID, write.getProjectId()); } @@ -494,6 +495,7 @@ private void datastoreWriterFnTest(int numMutations) throws Exception { start = end; } } + /** * Tests {@link DatastoreV1.Read#getEstimatedSizeBytes} to fetch and return estimated size for a * query. @@ -501,14 +503,23 @@ private void datastoreWriterFnTest(int numMutations) throws Exception { @Test public void testEstimatedSizeBytes() throws Exception { long entityBytes = 100L; + // In seconds + long timestamp = 1234L; + + RunQueryRequest latestTimestampRequest = makeRequest(makeLatestTimestampQuery(NAMESPACE), + NAMESPACE); + RunQueryResponse latestTimestampResponse = makeLatestTimestampResponse(timestamp); // Per Kind statistics request and response - RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE), NAMESPACE); + RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE, timestamp), NAMESPACE); RunQueryResponse statResponse = makeStatKindResponse(entityBytes); + when(mockDatastore.runQuery(latestTimestampRequest)) + .thenReturn(latestTimestampResponse); when(mockDatastore.runQuery(statRequest)) .thenReturn(statResponse); assertEquals(entityBytes, getEstimatedSizeBytes(mockDatastore, QUERY, NAMESPACE)); + verify(mockDatastore, times(1)).runQuery(latestTimestampRequest); verify(mockDatastore, times(1)).runQuery(statRequest); } @@ -549,11 +560,19 @@ public void testSplitQueryFnWithoutNumSplits() throws Exception { int numSplits = 0; int expectedNumSplits = 20; long entityBytes = expectedNumSplits * DEFAULT_BUNDLE_SIZE_BYTES; + // In seconds + long timestamp = 1234L; + + RunQueryRequest latestTimestampRequest = makeRequest(makeLatestTimestampQuery(NAMESPACE), + NAMESPACE); + RunQueryResponse latestTimestampResponse = makeLatestTimestampResponse(timestamp); // Per Kind statistics request and response - RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE), NAMESPACE); + RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE, timestamp), NAMESPACE); RunQueryResponse statResponse = makeStatKindResponse(entityBytes); + when(mockDatastore.runQuery(latestTimestampRequest)) + .thenReturn(latestTimestampResponse); when(mockDatastore.runQuery(statRequest)) .thenReturn(statResponse); when(mockQuerySplitter.getSplits( @@ -569,6 +588,7 @@ public void testSplitQueryFnWithoutNumSplits() throws Exception { verifyUniqueKeys(queries); verify(mockQuerySplitter, times(1)).getSplits( eq(QUERY), any(PartitionId.class), eq(expectedNumSplits), any(Datastore.class)); + verify(mockDatastore, times(1)).runQuery(latestTimestampRequest); verify(mockDatastore, times(1)).runQuery(statRequest); } @@ -692,7 +712,7 @@ public RunQueryResponse answer(InvocationOnMock invocationOnMock) throws Throwab /** Builds a per-kind statistics response with the given entity size. */ private static RunQueryResponse makeStatKindResponse(long entitySizeInBytes) { - RunQueryResponse.Builder timestampResponse = RunQueryResponse.newBuilder(); + RunQueryResponse.Builder statKindResponse = RunQueryResponse.newBuilder(); Entity.Builder entity = Entity.newBuilder(); entity.setKey(makeKey("dummyKind", "dummyId")); entity.getMutableProperties().put("entity_bytes", makeValue(entitySizeInBytes).build()); @@ -700,24 +720,51 @@ private static RunQueryResponse makeStatKindResponse(long entitySizeInBytes) { entityResult.setEntity(entity); QueryResultBatch.Builder batch = QueryResultBatch.newBuilder(); batch.addEntityResults(entityResult); + statKindResponse.setBatch(batch); + return statKindResponse.build(); + } + + /** Builds a response of the given timestamp. */ + private static RunQueryResponse makeLatestTimestampResponse(long timestamp) { + RunQueryResponse.Builder timestampResponse = RunQueryResponse.newBuilder(); + Entity.Builder entity = Entity.newBuilder(); + entity.setKey(makeKey("dummyKind", "dummyId")); + entity.getMutableProperties().put("timestamp", makeValue(new Date(timestamp * 1000)).build()); + EntityResult.Builder entityResult = EntityResult.newBuilder(); + entityResult.setEntity(entity); + QueryResultBatch.Builder batch = QueryResultBatch.newBuilder(); + batch.addEntityResults(entityResult); timestampResponse.setBatch(batch); return timestampResponse.build(); } /** Builds a per-kind statistics query for the given timestamp and namespace. */ - private static Query makeStatKindQuery(String namespace) { + private static Query makeStatKindQuery(String namespace, long timestamp) { Query.Builder statQuery = Query.newBuilder(); if (namespace == null) { statQuery.addKindBuilder().setName("__Stat_Kind__"); } else { - statQuery.addKindBuilder().setName("__Ns_Stat_Kind__"); + statQuery.addKindBuilder().setName("__Stat_Ns_Kind__"); } - statQuery.setFilter(makeFilter("kind_name", EQUAL, makeValue(KIND)).build()); - statQuery.addOrder(makeOrder("timestamp", DESCENDING)); - statQuery.setLimit(Int32Value.newBuilder().setValue(1)); + statQuery.setFilter(makeAndFilter( + makeFilter("kind_name", EQUAL, makeValue(KIND)).build(), + makeFilter("timestamp", EQUAL, makeValue(timestamp * 1000000L)).build())); return statQuery.build(); } + /** Builds a latest timestamp statistics query. */ + private static Query makeLatestTimestampQuery(String namespace) { + Query.Builder timestampQuery = Query.newBuilder(); + if (namespace == null) { + timestampQuery.addKindBuilder().setName("__Stat_Total__"); + } else { + timestampQuery.addKindBuilder().setName("__Stat_Ns_Total__"); + } + timestampQuery.addOrder(makeOrder("timestamp", DESCENDING)); + timestampQuery.setLimit(Int32Value.newBuilder().setValue(1)); + return timestampQuery.build(); + } + /** Generate dummy query splits. */ private List splitQuery(Query query, int numSplits) { List queries = new LinkedList<>(); From 252f571e759c5cfa391de8262b11c5fcd2a732d9 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 5 Aug 2016 14:20:56 -0700 Subject: [PATCH 546/751] Add LeaderBoardTest This test exercises the PTransforms that make up the LeaderBoard example. This includes speculative and late trigger firings to produce team and individual scores on a global and fixed window basis. Refactor LeaderBoard to expose the team and user score calculations as composite PTransforms to enable this testing. --- .../examples/complete/game/LeaderBoard.java | 123 ++++-- .../complete/game/LeaderBoardTest.java | 367 ++++++++++++++++++ 2 files changed, 448 insertions(+), 42 deletions(-) create mode 100644 examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java index 4185376868..694259d279 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java @@ -28,6 +28,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.options.Validation; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; +import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; @@ -38,17 +39,16 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.Window; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; - +import com.google.common.annotations.VisibleForTesting; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.joda.time.Instant; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - /** * This class is the third in a series of four pipelines that tell a story in a 'gaming' domain, * following {@link UserScore} and {@link HourlyTeamScore}. Concepts include: processing unbounded @@ -69,7 +69,7 @@ * here we're using an unbounded data source, which lets us provide speculative results, and allows * handling of late data, at much lower latency. We can use the early/speculative results to keep a * 'leaderboard' updated in near-realtime. Our handling of late data lets us generate correct - * results, e.g. for 'team prizes'. We're now outputing window results as they're + * results, e.g. for 'team prizes'. We're now outputting window results as they're * calculated, giving us much lower latency than with the previous batch examples. * *

            Run {@link injector.Injector} to generate pubsub data for this pipeline. The Injector @@ -186,52 +186,91 @@ public static void main(String[] args) throws Exception { .apply(PubsubIO.Read.timestampLabel(TIMESTAMP_ATTRIBUTE).topic(options.getTopic())) .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())); - // [START DocInclude_WindowAndTrigger] - // Extract team/score pairs from the event stream, using hour-long windows by default. - gameEvents - .apply(Window.named("LeaderboardTeamFixedWindows") - .into(FixedWindows.of( - Duration.standardMinutes(options.getTeamWindowDuration()))) - // We will get early (speculative) results as well as cumulative - // processing of late data. - .triggering( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(FIVE_MINUTES)) - .withLateFirings(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(TEN_MINUTES))) - .withAllowedLateness(Duration.standardMinutes(options.getAllowedLateness())) - .accumulatingFiredPanes()) - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")) + gameEvents.apply("CalculateTeamScores", + new CalculateTeamScores( + Duration.standardMinutes(options.getTeamWindowDuration()), + Duration.standardMinutes(options.getAllowedLateness()))) // Write the results to BigQuery. .apply("WriteTeamScoreSums", new WriteWindowedToBigQuery>( options.getTableName() + "_team", configureWindowedTableWrite())); - // [END DocInclude_WindowAndTrigger] - - // [START DocInclude_ProcTimeTrigger] - // Extract user/score pairs from the event stream using processing time, via global windowing. - // Get periodic updates on all users' running scores. gameEvents - .apply(Window.named("LeaderboardUserGlobalWindow") - .into(new GlobalWindows()) - // Get periodic results every ten minutes. - .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(TEN_MINUTES))) - .accumulatingFiredPanes() - .withAllowedLateness(Duration.standardMinutes(options.getAllowedLateness()))) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")) + .apply( + "CalculateUserScores", + new CalculateUserScores(Duration.standardMinutes(options.getAllowedLateness()))) // Write the results to BigQuery. - .apply("WriteUserScoreSums", - new WriteToBigQuery>( - options.getTableName() + "_user", configureGlobalWindowBigQueryWrite())); - // [END DocInclude_ProcTimeTrigger] + .apply( + "WriteUserScoreSums", + new WriteToBigQuery>( + options.getTableName() + "_user", configureGlobalWindowBigQueryWrite())); // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the // command line. PipelineResult result = pipeline.run(); dataflowUtils.waitToFinish(result); } + + /** + * Calculates scores for each team within the configured window duration. + */ + // [START DocInclude_WindowAndTrigger] + // Extract team/score pairs from the event stream, using hour-long windows by default. + @VisibleForTesting + static class CalculateTeamScores + extends PTransform, PCollection>> { + private final Duration teamWindowDuration; + private final Duration allowedLateness; + + CalculateTeamScores(Duration teamWindowDuration, Duration allowedLateness) { + this.teamWindowDuration = teamWindowDuration; + this.allowedLateness = allowedLateness; + } + + @Override + public PCollection> apply(PCollection infos) { + return infos.apply("LeaderboardTeamFixedWindows", + Window.into(FixedWindows.of(teamWindowDuration)) + // We will get early (speculative) results as well as cumulative + // processing of late data. + .triggering(AfterWatermark.pastEndOfWindow() + .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(FIVE_MINUTES)) + .withLateFirings(AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(TEN_MINUTES))) + .withAllowedLateness(allowedLateness) + .accumulatingFiredPanes()) + // Extract and sum teamname/score pairs from the event data. + .apply("ExtractTeamScore", new ExtractAndSumScore("team")); + } + } + // [END DocInclude_WindowAndTrigger] + + // [START DocInclude_ProcTimeTrigger] + /** + * Extract user/score pairs from the event stream using processing time, via global windowing. + * Get periodic updates on all users' running scores. + */ + @VisibleForTesting + static class CalculateUserScores + extends PTransform, PCollection>> { + private final Duration allowedLateness; + + CalculateUserScores(Duration allowedLateness) { + this.allowedLateness = allowedLateness; + } + + @Override + public PCollection> apply(PCollection input) { + return input.apply("LeaderboardUserGlobalWindow", + Window.into(new GlobalWindows()) + // Get periodic results every ten minutes. + .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(TEN_MINUTES))) + .accumulatingFiredPanes() + .withAllowedLateness(allowedLateness)) + // Extract and sum username/score pairs from the event data. + .apply("ExtractUserScore", new ExtractAndSumScore("user")); + } + } + // [END DocInclude_ProcTimeTrigger] } diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java new file mode 100644 index 0000000000..5561a4c69b --- /dev/null +++ b/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java @@ -0,0 +1,367 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.examples.complete.game; + +import static org.hamcrest.Matchers.hasItem; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.examples.complete.game.LeaderBoard.CalculateTeamScores; +import com.google.cloud.dataflow.examples.complete.game.LeaderBoard.CalculateUserScores; +import com.google.cloud.dataflow.examples.complete.game.UserScore.GameActionInfo; +import com.google.cloud.dataflow.sdk.coders.AvroCoder; +import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.testing.TestStream; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.cloud.dataflow.sdk.values.TimestampedValue; +import com.google.common.collect.ImmutableMap; +import java.io.Serializable; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link LeaderBoard}. + */ +@RunWith(JUnit4.class) +public class LeaderBoardTest implements Serializable { + private static final Duration ALLOWED_LATENESS = Duration.standardHours(1); + private static final Duration TEAM_WINDOW_DURATION = Duration.standardMinutes(20); + private Instant baseTime = new Instant(0); + + /** + * Some example users, on two separate teams. + */ + private enum TestUser { + RED_ONE("scarlet", "red"), RED_TWO("burgundy", "red"), + BLUE_ONE("navy", "blue"), BLUE_TWO("sky", "blue"); + + private final String userName; + private final String teamName; + + TestUser(String userName, String teamName) { + this.userName = userName; + this.teamName = teamName; + } + + public String getUser() { + return userName; + } + + public String getTeam() { + return teamName; + } + } + + /** + * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive + * on time (ahead of the watermark). + */ + @Test + public void testTeamScoresOnTime() { + TestPipeline p = getPipeline(); + + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + // Start at the epoch + .advanceWatermarkTo(baseTime) + // add some elements ahead of the watermark + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1)), + event(TestUser.RED_TWO, 3, Duration.standardSeconds(22)), + event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(3))) + // The watermark advances slightly, but not past the end of the window + .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) + // Add some more on time elements + .addElements(event(TestUser.RED_ONE, 1, Duration.standardMinutes(4)), + event(TestUser.BLUE_ONE, 2, Duration.standardSeconds(270))) + // The window should close and emit an ON_TIME pane + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + DataflowAssert.that(teamScores) + .inOnTimePane(new IntervalWindow(baseTime, TEAM_WINDOW_DURATION)) + .containsInAnyOrder(KV.of(blueTeam, 12), KV.of(redTeam, 4)); + + p.run(); + } + + /** + * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive + * on time, and the processing time advances far enough for speculative panes. + */ + @Test + public void testTeamScoresSpeculative() { + TestPipeline p = getPipeline(); + + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + // Start at the epoch + .advanceWatermarkTo(baseTime) + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1))) + // Some time passes within the runner, which causes a speculative pane containing the blue + // team's score to be emitted + .advanceProcessingTime(Duration.standardMinutes(10)) + .addElements(event(TestUser.RED_TWO, 5, Duration.standardMinutes(3))) + // Some additional time passes and we get a speculative pane for the red team + .advanceProcessingTime(Duration.standardMinutes(12)) + .addElements(event(TestUser.BLUE_TWO, 3, Duration.standardSeconds(22))) + // More time passes and a speculative pane containing a refined value for the blue pane is + // emitted + .advanceProcessingTime(Duration.standardMinutes(10)) + // Some more events occur + .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(4)), + event(TestUser.BLUE_TWO, 2, Duration.standardMinutes(2))) + // The window closes and we get an ON_TIME pane that contains all of the updates + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + IntervalWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + // The window contains speculative panes alongside the on-time pane + DataflowAssert.that(teamScores) + .inWindow(window) + .containsInAnyOrder(KV.of(blueTeam, 10) /* The on-time blue pane */, + KV.of(redTeam, 9) /* The on-time red pane */, + KV.of(blueTeam, 5) /* The first blue speculative pane */, + KV.of(blueTeam, 8) /* The second blue speculative pane */, + KV.of(redTeam, 5) /* The red speculative pane */); + DataflowAssert.that(teamScores) + .inOnTimePane(window) + .containsInAnyOrder(KV.of(blueTeam, 10), KV.of(redTeam, 9)); + + p.run(); + } + + /** + * A test where elements arrive behind the watermark (late data), but before the end of the + * window. These elements are emitted on time. + */ + @Test + public void testTeamScoresUnobservablyLate() { + TestPipeline p = getPipeline(); + + BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + .advanceWatermarkTo(baseTime) + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8)), + event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) + .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).minus(Duration.standardMinutes(1))) + // These events are late, but the window hasn't closed yet, so the elements are in the + // on-time pane + .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), + event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), + event(TestUser.BLUE_TWO, 2, Duration.standardSeconds(90)), + event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) + .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) + .advanceWatermarkToInfinity(); + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + // The On Time pane contains the late elements that arrived before the end of the window + DataflowAssert.that(teamScores) + .inOnTimePane(window) + .containsInAnyOrder(KV.of(redTeam, 14), KV.of(blueTeam, 13)); + + p.run(); + } + + /** + * A test where elements arrive behind the watermark (late data) after the watermark passes the + * end of the window, but before the maximum allowed lateness. These elements are emitted in a + * late pane. + */ + @Test + public void testTeamScoresObservablyLate() { + TestPipeline p = getPipeline(); + + Instant firstWindowCloses = baseTime.plus(ALLOWED_LATENESS).plus(TEAM_WINDOW_DURATION); + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + .advanceWatermarkTo(baseTime) + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8))) + .advanceProcessingTime(Duration.standardMinutes(10)) + .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) + .addElements(event(TestUser.RED_ONE, 3, Duration.standardMinutes(1)), + event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) + .advanceWatermarkTo(firstWindowCloses.minus(Duration.standardMinutes(1))) + // These events are late but should still appear in a late pane + .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), + event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), + event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) + // A late refinement is emitted due to the advance in processing time, but the window has + // not yet closed because the watermark has not advanced + .advanceProcessingTime(Duration.standardMinutes(12)) + // These elements should appear in the final pane + .addElements(event(TestUser.RED_TWO, 9, Duration.standardMinutes(1)), + event(TestUser.RED_TWO, 1, Duration.standardMinutes(3))) + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + DataflowAssert.that(teamScores) + .inWindow(window) + .satisfies((SerializableFunction>, Void>) input -> { + // The final sums need not exist in the same pane, but must appear in the output + // PCollection + assertThat(input, hasItem(KV.of(blueTeam, 11))); + assertThat(input, hasItem(KV.of(redTeam, 27))); + return null; + }); + DataflowAssert.thatMap(teamScores) + // The closing behavior of CalculateTeamScores precludes an inFinalPane matcher + .inOnTimePane(window) + .isEqualTo(ImmutableMap.builder().put(redTeam, 7) + .put(blueTeam, 11) + .build()); + + // No final pane is emitted for the blue team, as all of their updates have been taken into + // account in earlier panes + DataflowAssert.that(teamScores).inFinalPane(window).containsInAnyOrder(KV.of(redTeam, 27)); + + p.run(); + } + + /** + * A test where elements arrive beyond the maximum allowed lateness. These elements are dropped + * within {@link CalculateTeamScores} and do not impact the final result. + */ + @Test + public void testTeamScoresDroppablyLate() { + TestPipeline p = getPipeline(); + + BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + TestStream infos = TestStream.create(AvroCoder.of(GameActionInfo.class)) + .addElements(event(TestUser.BLUE_ONE, 12, Duration.ZERO), + event(TestUser.RED_ONE, 3, Duration.ZERO)) + .advanceWatermarkTo(window.maxTimestamp()) + .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_TWO, 3, Duration.ZERO), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) + // Move the watermark past the end of the allowed lateness plus the end of the window + .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS) + .plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) + // These elements within the expired window are droppably late, and will not appear in the + // output + .addElements( + event(TestUser.BLUE_TWO, 3, TEAM_WINDOW_DURATION.minus(Duration.standardSeconds(5))), + event(TestUser.RED_ONE, 7, Duration.standardMinutes(4))) + .advanceWatermarkToInfinity(); + PCollection> teamScores = p.apply(infos) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + // Only one on-time pane and no late panes should be emitted + DataflowAssert.that(teamScores) + .inWindow(window) + .containsInAnyOrder(KV.of(redTeam, 7), KV.of(blueTeam, 18)); + // No elements are added before the watermark passes the end of the window plus the allowed + // lateness, so no refinement should be emitted + DataflowAssert.that(teamScores).inFinalPane(window).empty(); + } + + /** + * A test where elements arrive both on-time and late in {@link CalculateUserScores}, which emits + * output into the {@link GlobalWindow}. All elements that arrive should be taken into account, + * even if they arrive later than the maximum allowed lateness. + */ + @Test + public void testUserScore() { + TestPipeline p = getPipeline(); + + TestStream infos = + TestStream.create(AvroCoder.of(GameActionInfo.class)) + .addElements( + event(TestUser.BLUE_ONE, 12, Duration.ZERO), + event(TestUser.RED_ONE, 3, Duration.ZERO)) + .advanceProcessingTime(Duration.standardMinutes(7)) + .addElements( + event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_TWO, 3, Duration.ZERO), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) + .advanceProcessingTime(Duration.standardMinutes(5)) + .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS).plus(Duration.standardHours(12))) + // Late elements are always observable within the global window - they arrive before + // the window closes, so they will appear in a pane, even if they arrive after the + // allowed lateness, and are taken into account alongside on-time elements + .addElements( + event(TestUser.RED_ONE, 3, Duration.standardMinutes(7)), + event(TestUser.RED_ONE, 2, (ALLOWED_LATENESS).plus(Duration.standardHours(13)))) + .advanceProcessingTime(Duration.standardMinutes(6)) + .addElements(event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(12))) + .advanceProcessingTime(Duration.standardMinutes(20)) + .advanceWatermarkToInfinity(); + + PCollection> userScores = + p.apply(infos).apply(new CalculateUserScores(ALLOWED_LATENESS)); + + // User scores are emitted in speculative panes in the Global Window - this matcher choice + // ensures that panes emitted by the watermark advancing to positive infinity are not included, + // as that will not occur outside of tests + DataflowAssert.that(userScores) + .inEarlyGlobalWindowPanes() + .containsInAnyOrder(KV.of(TestUser.BLUE_ONE.getUser(), 15), + KV.of(TestUser.RED_ONE.getUser(), 7), + KV.of(TestUser.RED_ONE.getUser(), 12), + KV.of(TestUser.BLUE_TWO.getUser(), 3), + KV.of(TestUser.BLUE_TWO.getUser(), 8)); + + p.run(); + } + + private TestPipeline getPipeline() { + PipelineOptions options = TestPipeline.testingPipelineOptions(); + options.setRunner(InProcessPipelineRunner.class); + return TestPipeline.fromOptions(options); + } + + private TimestampedValue event( + TestUser user, + int score, + Duration baseTimeOffset) { + return TimestampedValue.of(new GameActionInfo(user.getUser(), + user.getTeam(), + score, + baseTime.plus(baseTimeOffset).getMillis()), baseTime.plus(baseTimeOffset)); + } +} From bafe563b166c70f995b4b30692dcfe0e96610e41 Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Fri, 2 Sep 2016 09:55:16 -0700 Subject: [PATCH 547/751] Cloud Datastore naming clean-up (#414) --- .../examples/complete/AutoComplete.java | 12 ++--- .../examples/cookbook/DatastoreWordCount.java | 16 +++--- .../sdk/io/datastore/DatastoreIO.java | 6 +-- .../sdk/io/datastore/DatastoreV1.java | 50 +++++++++---------- .../sdk/io/datastore/package-info.java | 2 +- .../sdk/io/datastore/DatastoreV1Test.java | 6 +-- 6 files changed, 46 insertions(+), 46 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java index e30e6ca56d..d99924e2a8 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java @@ -99,7 +99,7 @@ * --streaming * } * - *

            This will update the datastore every 10 seconds based on the last + *

            This will update the Cloud Datastore every 10 seconds based on the last * 30 minutes of data received. */ public class AutoComplete { @@ -383,7 +383,7 @@ static TableSchema getSchema() { /** * Takes as input a the top candidates per prefix, and emits an entity - * suitable for writing to Datastore. + * suitable for writing to Cloud Datastore. * *

            Note: We use ancestor keys for strong consistency. See the Cloud Datastore documentation on * @@ -434,7 +434,7 @@ private static interface Options extends ExamplePubsubTopicOptions, ExampleBigQu Boolean getRecursive(); void setRecursive(Boolean value); - @Description("Datastore entity kind") + @Description("Cloud Datastore entity kind") @Default.String("autocomplete-demo") String getKind(); void setKind(String value); @@ -444,16 +444,16 @@ private static interface Options extends ExamplePubsubTopicOptions, ExampleBigQu Boolean getOutputToBigQuery(); void setOutputToBigQuery(Boolean value); - @Description("Whether output to Datastore") + @Description("Whether output to Cloud Datastore") @Default.Boolean(false) Boolean getOutputToDatastore(); void setOutputToDatastore(Boolean value); - @Description("Datastore output dataset ID, defaults to project ID") + @Description("Cloud Datastore output dataset ID, defaults to project ID") String getOutputDataset(); void setOutputDataset(String value); - @Description("Datastore ancestor key") + @Description("Cloud Datastore ancestor key") @Default.String("root") String getDatastoreAncestorKey(); void setDatastoreAncestorKey(String value); diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java index cf1f7b1b2b..6c4936ee14 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java @@ -48,11 +48,11 @@ /** * A WordCount example using DatastoreIO. * - *

            This example shows how to use DatastoreIO to read from Datastore and + *

            This example shows how to use DatastoreIO to read from Cloud Datastore and * write the results to Cloud Storage. Note that this example will write - * data to Datastore, which may incur charge for Datastore operations. + * data to Cloud Datastore, which may incur charge for Cloud Datastore operations. * - *

            To run this example, users need to use gcloud to get credential for Datastore: + *

            To run this example, users need to use gcloud to get credential for Cloud Datastore: *

            {@code
              * $ gcloud auth login
              * }
            @@ -152,7 +152,7 @@ public void processElement(ProcessContext c) { *

            Inherits standard configuration options. */ public static interface Options extends PipelineOptions { - @Description("Path of the file to read from and store to Datastore") + @Description("Path of the file to read from and store to Cloud Datastore") @Default.String("gs://dataflow-samples/shakespeare/kinglear.txt") String getInput(); void setInput(String value); @@ -163,12 +163,12 @@ public static interface Options extends PipelineOptions { void setOutput(String value); // Note: This maps to Project ID for v1beta3 version of datastore - @Description("Dataset ID to read from datastore") + @Description("Dataset ID to read from Cloud Datastore") @Validation.Required String getDataset(); void setDataset(String value); - @Description("Dataset entity kind") + @Description("Cloud Datastore Entity Kind") @Default.String("shakespeare-demo") String getKind(); void setKind(String value); @@ -189,7 +189,7 @@ public static interface Options extends PipelineOptions { /** * An example that creates a pipeline to populate DatastoreIO from a - * text input. Forces use of DirectPipelineRunner for local execution mode. + * text input. Forces use of DirectPipelineRunner for local execution mode. */ public static void writeDataToDatastore(Options options) { Pipeline p = Pipeline.create(options); @@ -220,7 +220,7 @@ static Query makeAncestorKindQuery(Options options) { } /** - * An example that creates a pipeline to do DatastoreIO.Read from Datastore. + * An example that creates a pipeline to do DatastoreIO.Read from Cloud Datastore. */ public static void readDataFromDatastore(Options options) { Query query = makeAncestorKindQuery(options); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java index 6dde7488e1..2ac1797155 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java @@ -21,7 +21,7 @@ /** *

            {@link DatastoreIO} provides an API for reading from and writing to * Google Cloud Datastore over different - * versions of the Datastore Client libraries. + * versions of the Cloud Datastore Client libraries. * *

            To use the v1 version see {@link DatastoreV1}. */ @@ -31,8 +31,8 @@ public class DatastoreIO { private DatastoreIO() {} /** - * Returns a {@link DatastoreV1} that provides an API for accessing Datastore through v1 version - * of Datastore Client library. + * Returns a {@link DatastoreV1} that provides an API for accessing Cloud Datastore through v1 + * version of Cloud Datastore Client library. */ public static DatastoreV1 v1() { return new DatastoreV1(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java index b2ad01e672..83fd2d54ad 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java @@ -92,13 +92,13 @@ * {@link Entity} objects. * *

            This API currently requires an authentication workaround. To use {@link DatastoreV1}, users - * must use the {@code gcloud} command line tool to get credentials for Datastore: + * must use the {@code gcloud} command line tool to get credentials for Cloud Datastore: *

              * $ gcloud auth login
              * 
            * - *

            To read a {@link PCollection} from a query to Datastore, use {@link DatastoreV1#read} and - * its methods {@link DatastoreV1.Read#withProjectId} and {@link DatastoreV1.Read#withQuery} to + *

            To read a {@link PCollection} from a query to Cloud Datastore, use {@link DatastoreV1#read} + * and its methods {@link DatastoreV1.Read#withProjectId} and {@link DatastoreV1.Read#withQuery} to * specify the project to query and the query to read from. You can optionally provide a namespace * to query within using {@link DatastoreV1.Read#withNamespace}. You could also optionally specify * how many splits you want for the query using {@link DatastoreV1.Read#withNumQuerySplits}. @@ -123,7 +123,7 @@ * {@link com.google.datastore.v1.Query.Builder#setLimit(Int32Value)}, then * all returned results will be read by a single Dataflow worker in order to ensure correct data. * - *

            To write a {@link PCollection} to a Datastore, use {@link DatastoreV1#write}, + *

            To write a {@link PCollection} to a Cloud Datastore, use {@link DatastoreV1#write}, * specifying the Cloud Datastore project to write to: * *

             {@code
            @@ -132,7 +132,7 @@
              * p.run();
              * } 
            * - *

            To delete a {@link PCollection} of {@link Entity Entities} from Datastore, use + *

            To delete a {@link PCollection} of {@link Entity Entities} from Cloud Datastore, use * {@link DatastoreV1#deleteEntity()}, specifying the Cloud Datastore project to write to: * *

             {@code
            @@ -141,8 +141,8 @@
              * p.run();
              * } 
            * - *

            To delete entities associated with a {@link PCollection} of {@link Key Keys} from Datastore, - * use {@link DatastoreV1#deleteKey}, specifying the Cloud Datastore project to write to: + *

            To delete entities associated with a {@link PCollection} of {@link Key Keys} from Cloud + * Datastore, use {@link DatastoreV1#deleteKey}, specifying the Cloud Datastore project to write to: * *

             {@code
              * PCollection entities = ...;
            @@ -170,7 +170,7 @@
              * more details.
              *
              * 

            Please see Cloud Datastore Sign Up - * for security and permission related information specific to Datastore. + * for security and permission related information specific to Cloud Datastore. * * @see com.google.cloud.dataflow.sdk.runners.PipelineRunner */ @@ -182,7 +182,7 @@ public class DatastoreV1 { /** * Datastore has a limit of 500 mutations per batch operation, so we flush - * changes to Datastore every 500 entities. + * changes to Cloud Datastore every 500 entities. */ @VisibleForTesting static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; @@ -198,7 +198,7 @@ public DatastoreV1.Read read() { } /** - * A {@link PTransform} that reads the result rows of a Datastore query as {@code Entity} + * A {@link PTransform} that reads the result rows of a Cloud atastore query as {@code Entity} * objects. * * @see DatastoreIO @@ -235,7 +235,7 @@ public static class Read extends PTransform> { /** * Computes the number of splits to be performed on the given query by querying the estimated - * size from Datastore. + * size from Cloud Datastore. */ static int getEstimatedNumSplits(Datastore datastore, Query query, @Nullable String namespace) { int numSplits; @@ -282,7 +282,7 @@ private static long queryLatestStatisticsTimestamp(Datastore datastore, /** * Get the estimated size of the data returned by the given query. * - *

            Datastore provides no way to get a good estimate of how large the result of a query + *

            Cloud Datastore provides no way to get a good estimate of how large the result of a query * entity kind being queried, using the __Stat_Kind__ system table, assuming exactly 1 kind * is specified in the query. * @@ -313,7 +313,7 @@ static long getEstimatedSizeBytes(Datastore datastore, Query query, @Nullable St QueryResultBatch batch = response.getBatch(); if (batch.getEntityResultsCount() == 0) { throw new NoSuchElementException( - "Datastore statistics for kind " + ourKind + " unavailable"); + "Cloud Datastore statistics for kind " + ourKind + " unavailable"); } Entity entity = batch.getEntityResults(0).getEntity(); return entity.getProperties().get("entity_bytes").getIntegerValue(); @@ -357,7 +357,7 @@ private Read(@Nullable String projectId, @Nullable Query query, @Nullable String } /** - * Returns a new {@link DatastoreV1.Read} that reads from the Datastore for the specified + * Returns a new {@link DatastoreV1.Read} that reads from the Cloud Datastore for the specified * project. */ public DatastoreV1.Read withProjectId(String projectId) { @@ -492,7 +492,7 @@ public String toString() { } /** - * A class for v1 Datastore related options. + * A class for v1 Cloud Datastore related options. */ @VisibleForTesting static class V1Options implements Serializable { @@ -608,7 +608,7 @@ public void populateDisplayData(Builder builder) { } /** - * A {@link DoFn} that reads entities from Datastore for each query. + * A {@link DoFn} that reads entities from Cloud Datastore for each query. */ @VisibleForTesting static class ReadFn extends DoFn { @@ -909,8 +909,8 @@ public void finishBundle(Context c) throws Exception { * *

            If a commit fails, it will be retried (up to {@link DatastoreWriterFn#MAX_RETRIES} * times). All mutations in the batch will be committed again, even if the commit was partially - * successful. If the retry limit is exceeded, the last exception from the Datastore will be - * thrown. + * successful. If the retry limit is exceeded, the last exception from the Cloud Datastore will + * be thrown. * * @throws DatastoreException if the commit fails or IOException or InterruptedException if * backing off between retries fails. @@ -954,7 +954,7 @@ public void populateDisplayData(Builder builder) { } /** - * Returns true if a Datastore key is complete. A key is complete if its last element + * Returns true if a Cloud Datastore key is complete. A key is complete if its last element * has either an id or a name. */ static boolean isValidKey(Key key) { @@ -975,7 +975,7 @@ static class UpsertFn extends SimpleFunction { public Mutation apply(Entity entity) { // Verify that the entity to write has a complete key. checkArgument(isValidKey(entity.getKey()), - "Entities to be written to the Datastore must have complete keys:\n%s", entity); + "Entities to be written to the Cloud Datastore must have complete keys:\n%s", entity); return makeUpsert(entity).build(); } @@ -990,7 +990,7 @@ static class DeleteEntityFn extends SimpleFunction { public Mutation apply(Entity entity) { // Verify that the entity to delete has a complete key. checkArgument(isValidKey(entity.getKey()), - "Entities to be deleted from the Datastore must have complete keys:\n%s", entity); + "Entities to be deleted from the Cloud Datastore must have complete keys:\n%s", entity); return makeDelete(entity.getKey()).build(); } @@ -1005,14 +1005,14 @@ static class DeleteKeyFn extends SimpleFunction { public Mutation apply(Key key) { // Verify that the entity to delete has a complete key. checkArgument(isValidKey(key), - "Keys to be deleted from the Datastore must be complete:\n%s", key); + "Keys to be deleted from the Cloud Datastore must be complete:\n%s", key); return makeDelete(key).build(); } } /** - * A wrapper factory class for Datastore singleton classes {@link DatastoreFactory} and + * A wrapper factory class for Cloud Datastore singleton classes {@link DatastoreFactory} and * {@link QuerySplitter} * *

            {@link DatastoreFactory} and {@link QuerySplitter} are not java serializable, hence @@ -1021,7 +1021,7 @@ public Mutation apply(Key key) { @VisibleForTesting static class V1DatastoreFactory implements Serializable { - /** Builds a Datastore client for the given pipeline options and project. */ + /** Builds a Cloud Datastore client for the given pipeline options and project. */ public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { DatastoreOptions.Builder builder = new DatastoreOptions.Builder() @@ -1038,7 +1038,7 @@ public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) return DatastoreFactory.get().create(builder.build()); } - /** Builds a Datastore {@link QuerySplitter}. */ + /** Builds a Cloud Datastore {@link QuerySplitter}. */ public QuerySplitter getQuerySplitter() { return DatastoreHelper.getQuerySplitter(); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java index 18f547f594..d6eb213145 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java @@ -17,6 +17,6 @@ /** *

            Provides an API for reading from and writing to * Google Cloud Datastore over different - * versions of the Datastore Client libraries. + * versions of the Cloud Datastore Client libraries. */ package com.google.cloud.dataflow.sdk.io.datastore; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java index e99ebe0ca6..917f87a1ef 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java @@ -370,7 +370,7 @@ public void testAddEntitiesWithIncompleteKeys() throws Exception { UpsertFn upsertFn = new UpsertFn(); thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Entities to be written to the Datastore must have complete keys"); + thrown.expectMessage("Entities to be written to the Cloud Datastore must have complete keys"); upsertFn.apply(entity); } @@ -398,7 +398,7 @@ public void testDeleteEntitiesWithIncompleteKeys() throws Exception { DeleteEntityFn deleteEntityFn = new DeleteEntityFn(); thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Entities to be deleted from the Datastore must have complete keys"); + thrown.expectMessage("Entities to be deleted from the Cloud Datastore must have complete keys"); deleteEntityFn.apply(entity); } @@ -425,7 +425,7 @@ public void testDeleteIncompleteKeys() throws Exception { DeleteKeyFn deleteKeyFn = new DeleteKeyFn(); thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Keys to be deleted from the Datastore must be complete"); + thrown.expectMessage("Keys to be deleted from the Cloud Datastore must be complete"); deleteKeyFn.apply(key); } From 35dd9af8d3518907368f62854c64adfd62b03cbf Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Fri, 2 Sep 2016 14:15:23 -0700 Subject: [PATCH 548/751] Add Missing RunWith to WriteWithShardingFactoryTest (#415) --- .../sdk/runners/inprocess/WriteWithShardingFactoryTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java index 2e84ca31d3..96fa6bffcb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java @@ -49,6 +49,8 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.File; import java.io.FileReader; import java.io.Reader; @@ -63,6 +65,7 @@ /** * Tests for {@link WriteWithShardingFactory}. */ +@RunWith(JUnit4.class) public class WriteWithShardingFactoryTest { public static final int INPUT_SIZE = 10000; @Rule public TemporaryFolder tmp = new TemporaryFolder(); From f64056982b41afceb6ffe9279b62af523eb88511 Mon Sep 17 00:00:00 2001 From: peihe Date: Sun, 4 Sep 2016 13:59:51 -0700 Subject: [PATCH 549/751] Create the temp dataset in the same location as the queried table in BigQueryTableRowIterator (#411) * Create the temp dataset in the same location as the queried table in BigQueryTableRowIterator * address feedback * address feedback * fix failed tests --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 23 ++-- .../sdk/util/BigQueryTableRowIterator.java | 106 ++++++++++++------ .../util/BigQueryTableRowIteratorTest.java | 56 +++++---- 3 files changed, 111 insertions(+), 74 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index fefc84e8be..2d5c8cc824 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -549,13 +549,13 @@ private static void dryRunQuery(BigQueryOptions options, String query) { request.setQuery(query); request.setDryRun(true); + String queryValidationErrorMsg = String.format(QUERY_VALIDATION_FAILURE_ERROR, query); try { BigQueryTableRowIterator.executeWithBackOff( - client.jobs().query(options.getProject(), request), QUERY_VALIDATION_FAILURE_ERROR, - query); + client.jobs().query(options.getProject(), request), + queryValidationErrorMsg); } catch (Exception e) { - throw new IllegalArgumentException( - String.format(QUERY_VALIDATION_FAILURE_ERROR, query), e); + throw new IllegalArgumentException(queryValidationErrorMsg, e); } } @@ -2314,17 +2314,17 @@ private Write() {} } private static void verifyDatasetPresence(BigQueryOptions options, TableReference table) { + String resourceNotFoundMsg = + String.format(RESOURCE_NOT_FOUND_ERROR, "dataset", BigQueryIO.toTableSpec(table)); try { Bigquery client = Transport.newBigQueryClient(options).build(); BigQueryTableRowIterator.executeWithBackOff( client.datasets().get(table.getProjectId(), table.getDatasetId()), - RESOURCE_NOT_FOUND_ERROR, "dataset", BigQueryIO.toTableSpec(table)); + resourceNotFoundMsg); } catch (Exception e) { ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); if ((e instanceof IOException) && errorExtractor.itemNotFound((IOException) e)) { - throw new IllegalArgumentException( - String.format(RESOURCE_NOT_FOUND_ERROR, "dataset", BigQueryIO.toTableSpec(table)), - e); + throw new IllegalArgumentException(resourceNotFoundMsg, e); } else { throw new RuntimeException( String.format(UNABLE_TO_CONFIRM_PRESENCE_OF_RESOURCE_ERROR, "dataset", @@ -2335,16 +2335,17 @@ private static void verifyDatasetPresence(BigQueryOptions options, TableReferenc } private static void verifyTablePresence(BigQueryOptions options, TableReference table) { + String resourceNotFoundMsg = + String.format(RESOURCE_NOT_FOUND_ERROR, "table", BigQueryIO.toTableSpec(table)); try { Bigquery client = Transport.newBigQueryClient(options).build(); BigQueryTableRowIterator.executeWithBackOff( client.tables().get(table.getProjectId(), table.getDatasetId(), table.getTableId()), - RESOURCE_NOT_FOUND_ERROR, "table", BigQueryIO.toTableSpec(table)); + resourceNotFoundMsg); } catch (Exception e) { ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); if ((e instanceof IOException) && errorExtractor.itemNotFound((IOException) e)) { - throw new IllegalArgumentException( - String.format(RESOURCE_NOT_FOUND_ERROR, "table", BigQueryIO.toTableSpec(table)), e); + throw new IllegalArgumentException(resourceNotFoundMsg, e); } else { throw new RuntimeException( String.format(UNABLE_TO_CONFIRM_PRESENCE_OF_RESOURCE_ERROR, "table", diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 75b3bb9271..e1b7079347 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -27,7 +27,6 @@ import com.google.api.client.util.Data; import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.Bigquery.Jobs.Insert; import com.google.api.services.bigquery.model.Dataset; import com.google.api.services.bigquery.model.DatasetReference; import com.google.api.services.bigquery.model.ErrorProto; @@ -35,6 +34,7 @@ import com.google.api.services.bigquery.model.JobConfiguration; import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableCell; @@ -138,16 +138,7 @@ public void open() throws IOException, InterruptedException { ref = executeQueryAndWaitForCompletion(); } // Get table schema. - Bigquery.Tables.Get get = - client.tables().get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - - Table table = - executeWithBackOff( - get, - "Error opening BigQuery table %s of dataset %s : {}", - ref.getTableId(), - ref.getDatasetId()); - schema = table.getSchema(); + schema = getTable(ref).getSchema(); } public boolean advance() throws IOException, InterruptedException { @@ -172,9 +163,10 @@ public boolean advance() throws IOException, InterruptedException { TableDataList result = executeWithBackOff( list, - "Error reading from BigQuery table %s of dataset %s : {}", - ref.getTableId(), - ref.getDatasetId()); + String.format( + "Error reading from BigQuery table %s of dataset %s.", + ref.getTableId(), + ref.getDatasetId())); pageToken = result.getPageToken(); iteratorOverCurrentBatch = @@ -331,19 +323,34 @@ private TableRow getTypedTableRow(List fields, Map T executeWithBackOff(AbstractGoogleClientRequest client, String error, + Object... errorArgs) throws IOException, InterruptedException { + return executeWithBackOff(client, String.format(error, errorArgs)); + } + // Execute a BQ request with exponential backoff and return the result. // client - BQ request to be executed // error - Formatted message to log if when a request fails. Takes exception message as a // formatter parameter. - public static T executeWithBackOff(AbstractGoogleClientRequest client, String error, - Object... errorArgs) throws IOException, InterruptedException { + public static T executeWithBackOff(AbstractGoogleClientRequest client, String error) + throws IOException, InterruptedException { Sleeper sleeper = Sleeper.DEFAULT; BackOff backOff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_TIME.getMillis()); @@ -435,11 +474,12 @@ public static T executeWithBackOff(AbstractGoogleClientRequest client, St result = client.execute(); break; } catch (IOException e) { - LOG.error(String.format(error, errorArgs), e.getMessage()); + LOG.error("{}", error, e); if (!BackOffUtils.next(sleeper, backOff)) { - LOG.error( - String.format(error, errorArgs), "Failing after retrying " + MAX_RETRIES + " times."); - throw e; + String errorMessage = String.format( + "%s Failing to execute job after %d attempts.", error, MAX_RETRIES + 1); + LOG.error("{}", errorMessage, e); + throw new IOException(errorMessage, e); } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java index b82e62595c..cecbcb70fb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -31,11 +31,12 @@ import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.ErrorProto; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfiguration; import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.api.services.bigquery.model.JobReference; +import com.google.api.services.bigquery.model.JobStatistics; +import com.google.api.services.bigquery.model.JobStatistics2; import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableCell; @@ -44,6 +45,7 @@ import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; +import com.google.common.collect.ImmutableList; import org.junit.After; import org.junit.Before; @@ -126,6 +128,11 @@ private static Table tableWithBasicSchema() { new TableFieldSchema().setName("answer").setType("INTEGER")))); } + private static Table tableWithLocation() { + return new Table() + .setLocation("EU"); + } + private TableRow rawRow(Object... args) { List cells = new LinkedList<>(); for (Object a : args) { @@ -145,8 +152,11 @@ private TableDataList rawDataList(TableRow... rows) { @Test public void testReadFromQuery() throws IOException, InterruptedException { // Mock job inserting. + Job dryRunJob = new Job().setStatistics( + new JobStatistics().setQuery(new JobStatistics2().setReferencedTables( + ImmutableList.of(new TableReference())))); Job insertedJob = new Job().setJobReference(new JobReference()); - when(mockJobsInsert.execute()).thenReturn(insertedJob); + when(mockJobsInsert.execute()).thenReturn(dryRunJob, insertedJob); // Mock job polling. JobStatus status = new JobStatus().setState("DONE"); @@ -161,7 +171,7 @@ public void testReadFromQuery() throws IOException, InterruptedException { when(mockJobsGet.execute()).thenReturn(getJob); // Mock table schema fetch. - when(mockTablesGet.execute()).thenReturn(tableWithBasicSchema()); + when(mockTablesGet.execute()).thenReturn(tableWithLocation(), tableWithBasicSchema()); // Mock table data fetch. when(mockTabledataList.execute()).thenReturn(rawDataList(rawRow("Arthur", 42))); @@ -189,15 +199,15 @@ public void testReadFromQuery() throws IOException, InterruptedException { verify(mockDatasets).delete(anyString(), anyString()); verify(mockDatasetsDelete).execute(); // Job inserted to run the query, polled once. - verify(mockClient, times(2)).jobs(); - verify(mockJobs).insert(anyString(), any(Job.class)); - verify(mockJobsInsert).execute(); + verify(mockClient, times(3)).jobs(); + verify(mockJobs, times(2)).insert(anyString(), any(Job.class)); + verify(mockJobsInsert, times(2)).execute(); verify(mockJobs).get(anyString(), anyString()); verify(mockJobsGet).execute(); // Temp table get after query finish, deleted after reading. - verify(mockClient, times(2)).tables(); - verify(mockTables).get("project", "dataset", "table"); - verify(mockTablesGet).execute(); + verify(mockClient, times(3)).tables(); + verify(mockTables, times(2)).get(anyString(), anyString(), anyString()); + verify(mockTablesGet, times(2)).execute(); verify(mockTables).delete(anyString(), anyString(), anyString()); verify(mockTablesDelete).execute(); // Table data read. @@ -213,43 +223,29 @@ public void testReadFromQuery() throws IOException, InterruptedException { */ @Test public void testQueryFailed() throws IOException { - // Job can be created. - JobReference ref = new JobReference(); - Job insertedJob = new Job().setJobReference(ref); - when(mockJobsInsert.execute()).thenReturn(insertedJob); - // Job state polled with an error. String errorReason = "bad query"; - JobStatus status = - new JobStatus().setState("DONE").setErrorResult(new ErrorProto().setMessage(errorReason)); - Job getJob = new Job().setJobReference(ref).setStatus(status); - when(mockJobsGet.execute()).thenReturn(getJob); + Exception exception = new IOException(errorReason); + when(mockJobsInsert.execute()).thenThrow(exception, exception, exception, exception); String query = "NOT A QUERY"; try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null)) { + try { iterator.open(); fail(); } catch (Exception expected) { // Verify message explains cause and reports the query. - assertThat(expected.getMessage(), containsString("failed")); - assertThat(expected.getMessage(), containsString(errorReason)); + assertThat(expected.getMessage(), containsString("Error")); assertThat(expected.getMessage(), containsString(query)); + assertThat(expected.getCause().getMessage(), containsString(errorReason)); } } - // Temp dataset created and then later deleted. - verify(mockClient, times(2)).datasets(); - verify(mockDatasets).insert(anyString(), any(Dataset.class)); - verify(mockDatasetsInsert).execute(); - verify(mockDatasets).delete(anyString(), anyString()); - verify(mockDatasetsDelete).execute(); // Job inserted to run the query, then polled once. - verify(mockClient, times(2)).jobs(); + verify(mockClient, times(1)).jobs(); verify(mockJobs).insert(anyString(), any(Job.class)); - verify(mockJobsInsert).execute(); - verify(mockJobs).get(anyString(), anyString()); - verify(mockJobsGet).execute(); + verify(mockJobsInsert, times(3)).execute(); } } From 94d57207924ed8650cf3c97fccb2a45f27bcc6a3 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Tue, 6 Sep 2016 15:20:39 -0700 Subject: [PATCH 550/751] FluentBackoff: a replacement for a variety of custom backoff implementations (#417) We have 3 different backoff classes, which don't really have that much different functionality. Add a single, flexible backoff implementation that can be used to replace all three classes. Additionally, this new backoff actually supports more functionality than any of the other three did -- you can limit retries, cap the exponential growth of an individual backoff, and cap the cumulative time spent in backoff; prior implementations did not allow all 3. This also makes the parameters self-obvious (Duration, not number-that-is-also-millis) where appropriate. This initial PR should have no functional changes. * Implement FluentBackoff * Replace other custom BackOff implementations with FluentBackoff --- .../examples/common/DataflowExampleUtils.java | 9 +- .../cloud/dataflow/sdk/io/BigQueryIO.java | 19 +- .../io/BoundedReadFromUnboundedSource.java | 8 +- .../cloud/dataflow/sdk/io/DatastoreIO.java | 13 +- .../sdk/io/datastore/DatastoreV1.java | 26 +- .../sdk/runners/DataflowPipelineJob.java | 81 ++++--- ...temptAndTimeBoundedExponentialBackOff.java | 3 + .../AttemptBoundedExponentialBackOff.java | 3 + .../sdk/util/BigQueryServicesImpl.java | 119 +++++---- .../sdk/util/BigQueryTableInserter.java | 24 +- .../sdk/util/BigQueryTableRowIterator.java | 3 +- .../dataflow/sdk/util/FluentBackoff.java | 227 ++++++++++++++++++ .../cloud/dataflow/sdk/util/GcsUtil.java | 18 +- .../IntervalBoundedExponentialBackOff.java | 1 + .../cloud/dataflow/sdk/util/PackageUtil.java | 30 ++- .../sdk/runners/DataflowPipelineJobTest.java | 41 ++-- ...tAndTimeBoundedExponentialBackOffTest.java | 1 + .../AttemptBoundedExponentialBackOffTest.java | 1 + .../sdk/util/BigQueryServicesImplTest.java | 15 +- .../dataflow/sdk/util/FluentBackoffTest.java | 226 +++++++++++++++++ .../cloud/dataflow/sdk/util/GcsUtilTest.java | 10 +- 21 files changed, 694 insertions(+), 184 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java index b53f146226..523044138f 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java @@ -41,7 +41,7 @@ import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.IntraBundleParallelization; import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.FluentBackoff; import com.google.cloud.dataflow.sdk.util.MonitoringUtil; import com.google.cloud.dataflow.sdk.util.Transport; import com.google.cloud.dataflow.sdk.values.PBegin; @@ -51,6 +51,8 @@ import com.google.common.collect.Sets; import com.google.common.util.concurrent.Uninterruptibles; +import org.joda.time.Duration; + import java.io.IOException; import java.util.Collection; import java.util.List; @@ -59,6 +61,7 @@ import javax.servlet.http.HttpServletResponse; + /** * The utility class that sets up and tears down external resources, starts the Google Cloud Pub/Sub * injector, and cancels the streaming and the injector pipelines once the program terminates. @@ -95,7 +98,9 @@ public DataflowExampleUtils(DataflowPipelineOptions options, boolean isUnbounded */ public void setup() throws IOException { Sleeper sleeper = Sleeper.DEFAULT; - BackOff backOff = new AttemptBoundedExponentialBackOff(3, 200); + BackOff backOff = + FluentBackoff.DEFAULT + .withMaxRetries(3).withInitialBackoff(Duration.millis(200)).backoff(); Throwable lastException = null; try { do { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 2d5c8cc824..c56de7bd20 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -21,9 +21,6 @@ import static com.google.common.base.Preconditions.checkState; import com.google.api.client.json.JsonFactory; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfigurationExtract; @@ -66,7 +63,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.AvroUtils; import com.google.cloud.dataflow.sdk.util.BigQueryServices; import com.google.cloud.dataflow.sdk.util.BigQueryServices.DatasetService; @@ -107,6 +103,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.avro.generic.GenericRecord; +import org.joda.time.Duration; import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -133,7 +130,6 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -984,14 +980,14 @@ private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOE * ... */ private abstract static class BigQuerySourceBase extends BoundedSource { - // The maximum number of attempts to verify temp files. - private static final int MAX_FILES_VERIFY_ATTEMPTS = 10; + // The maximum number of retries to verify temp files. + private static final int MAX_FILES_VERIFY_RETRIES = 9; // The maximum number of retries to poll a BigQuery job. protected static final int JOB_POLL_MAX_RETRIES = Integer.MAX_VALUE; // The initial backoff for verifying temp files. - private static final long INITIAL_FILES_VERIFY_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); + private static final Duration INITIAL_FILES_VERIFY_BACKOFF = Duration.standardSeconds(1); protected final String jobIdToken; protected final String extractDestinationDir; @@ -1090,14 +1086,7 @@ public TableRow apply(GenericRecord input) { }}; List> avroSources = Lists.newArrayList(); - BackOff backoff = new AttemptBoundedExponentialBackOff( - MAX_FILES_VERIFY_ATTEMPTS, INITIAL_FILES_VERIFY_BACKOFF_MILLIS); for (String fileName : files) { - while (BackOffUtils.next(Sleeper.DEFAULT, backoff)) { - if (IOChannelUtils.getFactory(fileName).getSizeBytes(fileName) != -1) { - break; - } - } avroSources.add(new TransformingSource<>( AvroSource.from(fileName), function, getDefaultOutputCoder())); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java index 8388f1a39a..88ecbee3d7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java @@ -26,7 +26,7 @@ import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.IntervalBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.FluentBackoff; import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PInput; @@ -51,6 +51,10 @@ class BoundedReadFromUnboundedSource extends PTransform source; private final long maxNumRecords; private final Duration maxReadTime; + private static final FluentBackoff BACKOFF_FACTORY = + FluentBackoff.DEFAULT + .withInitialBackoff(Duration.millis(10)) + .withMaxBackoff(Duration.standardSeconds(10)); /** * Returns a new {@link BoundedReadFromUnboundedSource} that reads a bounded amount @@ -239,7 +243,7 @@ public boolean advance() throws IOException { private boolean advanceWithBackoff() throws IOException { // Try reading from the source with exponential backoff - BackOff backoff = new IntervalBoundedExponentialBackOff(10000, 10); + BackOff backoff = BACKOFF_FACTORY.backoff(); long nextSleep = backoff.nextBackOffMillis(); while (nextSleep != BackOff.STOP) { if (endTime != null && Instant.now().isAfter(endTime)) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java index f112f0e3b2..d50de15d91 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java @@ -57,7 +57,7 @@ import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.FluentBackoff; import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.base.MoreObjects; @@ -65,6 +65,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -719,11 +720,9 @@ static class DatastoreWriter extends Writer { * prevent transient errors from causing the bundle to fail. */ private static final int MAX_RETRIES = 5; - - /** - * Initial backoff time for exponential backoff for retry attempts. - */ - private static final int INITIAL_BACKOFF_MILLIS = 5000; + private static final FluentBackoff BUNDLE_WRITE_BACKOFF = + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RETRIES).withInitialBackoff(Duration.standardSeconds(5)); /** * Returns true if a Datastore key is complete. A key is complete if its last element @@ -797,7 +796,7 @@ public DatastoreWriteOperation getWriteOperation() { private void flushBatch() throws DatastoreException, IOException, InterruptedException { LOG.debug("Writing batch of {} entities", entities.size()); Sleeper sleeper = Sleeper.DEFAULT; - BackOff backoff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_MILLIS); + BackOff backoff = BUNDLE_WRITE_BACKOFF.backoff(); while (true) { // Batch upsert entities. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java index 83fd2d54ad..3af3932978 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java @@ -47,7 +47,7 @@ import com.google.cloud.dataflow.sdk.transforms.Values; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.FluentBackoff; import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PBegin; @@ -75,6 +75,7 @@ import com.google.datastore.v1.client.QuerySplitter; import com.google.protobuf.Int32Value; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -863,16 +864,11 @@ static class DatastoreWriterFn extends DoFn { private final V1DatastoreFactory datastoreFactory; // Current batch of mutations to be written. private final List mutations = new ArrayList<>(); - /** - * Since a bundle is written in batches, we should retry the commit of a batch in order to - * prevent transient errors from causing the bundle to fail. - */ - private static final int MAX_RETRIES = 5; - /** - * Initial backoff time for exponential backoff for retry attempts. - */ - private static final int INITIAL_BACKOFF_MILLIS = 5000; + private static final int MAX_RETRIES = 5; + private static final FluentBackoff BUNDLE_WRITE_BACKOFF = + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RETRIES).withInitialBackoff(Duration.standardSeconds(5)); DatastoreWriterFn(String projectId) { this(projectId, new V1DatastoreFactory()); @@ -907,10 +903,10 @@ public void finishBundle(Context c) throws Exception { /** * Writes a batch of mutations to Cloud Datastore. * - *

            If a commit fails, it will be retried (up to {@link DatastoreWriterFn#MAX_RETRIES} - * times). All mutations in the batch will be committed again, even if the commit was partially - * successful. If the retry limit is exceeded, the last exception from the Cloud Datastore will - * be thrown. + *

            If a commit fails, it will be retried up to {@link #MAX_RETRIES} times. All + * mutations in the batch will be committed again, even if the commit was partially + * successful. If the retry limit is exceeded, the last exception from Cloud Datastore will be + * thrown. * * @throws DatastoreException if the commit fails or IOException or InterruptedException if * backing off between retries fails. @@ -918,7 +914,7 @@ public void finishBundle(Context c) throws Exception { private void flushBatch() throws DatastoreException, IOException, InterruptedException { LOG.debug("Writing batch of {} mutations", mutations.size()); Sleeper sleeper = Sleeper.DEFAULT; - BackOff backoff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_MILLIS); + BackOff backoff = BUNDLE_WRITE_BACKOFF.backoff(); while (true) { // Batch upsert entities. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java index d3f688e332..c2aa39774b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java @@ -31,12 +31,12 @@ import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowMetricUpdateExtractor; import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.util.AttemptAndTimeBoundedExponentialBackOff; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; +import com.google.cloud.dataflow.sdk.util.FluentBackoff; import com.google.cloud.dataflow.sdk.util.MapAggregatorValues; import com.google.cloud.dataflow.sdk.util.MonitoringUtil; import com.google.common.annotations.VisibleForTesting; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -93,14 +93,27 @@ public class DataflowPipelineJob implements PipelineResult { /** * The polling interval for job status and messages information. */ - static final long MESSAGES_POLLING_INTERVAL = TimeUnit.SECONDS.toMillis(2); - static final long STATUS_POLLING_INTERVAL = TimeUnit.SECONDS.toMillis(2); + static final Duration MESSAGES_POLLING_INTERVAL = Duration.standardSeconds(2); + static final Duration STATUS_POLLING_INTERVAL = Duration.standardSeconds(2); + + static final double DEFAULT_BACKOFF_EXPONENT = 1.5; /** - * The amount of polling attempts for job status and messages information. + * The amount of polling retries for job status and messages information. */ - static final int MESSAGES_POLLING_ATTEMPTS = 12; - static final int STATUS_POLLING_ATTEMPTS = 5; + static final int MESSAGES_POLLING_RETRIES = 11; + static final int STATUS_POLLING_RETRIES = 4; + + private static final FluentBackoff MESSAGES_BACKOFF_FACTORY = + FluentBackoff.DEFAULT + .withInitialBackoff(MESSAGES_POLLING_INTERVAL) + .withMaxRetries(MESSAGES_POLLING_RETRIES) + .withExponent(DEFAULT_BACKOFF_EXPONENT); + protected static final FluentBackoff STATUS_BACKOFF_FACTORY = + FluentBackoff.DEFAULT + .withInitialBackoff(STATUS_POLLING_INTERVAL) + .withMaxRetries(STATUS_POLLING_RETRIES) + .withExponent(DEFAULT_BACKOFF_EXPONENT); /** * Constructs the job. @@ -174,15 +187,15 @@ public State waitToFinish( TimeUnit timeUnit, MonitoringUtil.JobMessagesHandler messageHandler) throws IOException, InterruptedException { - return waitToFinish(timeToWait, timeUnit, messageHandler, Sleeper.DEFAULT, NanoClock.SYSTEM); + Duration duration = Duration.millis(timeUnit.toMillis(timeToWait)); + return waitToFinish(duration, messageHandler, Sleeper.DEFAULT, NanoClock.SYSTEM); } /** * Wait for the job to finish and return the final status. * - * @param timeToWait The time to wait in units timeUnit for the job to finish. + * @param duration The total time to wait for the job to finish. * Provide a value less than 1 ms for an infinite wait. - * @param timeUnit The unit of time for timeToWait. * @param messageHandler If non null this handler will be invoked for each * batch of messages received. * @param sleeper A sleeper to use to sleep between attempts. @@ -196,8 +209,7 @@ public State waitToFinish( @Nullable @VisibleForTesting State waitToFinish( - long timeToWait, - TimeUnit timeUnit, + Duration duration, MonitoringUtil.JobMessagesHandler messageHandler, Sleeper sleeper, NanoClock nanoClock) @@ -205,21 +217,23 @@ State waitToFinish( MonitoringUtil monitor = new MonitoringUtil(projectId, dataflowClient); long lastTimestamp = 0; - BackOff backoff = - timeUnit.toMillis(timeToWait) > 0 - ? new AttemptAndTimeBoundedExponentialBackOff( - MESSAGES_POLLING_ATTEMPTS, - MESSAGES_POLLING_INTERVAL, - timeUnit.toMillis(timeToWait), - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ATTEMPTS, - nanoClock) - : new AttemptBoundedExponentialBackOff( - MESSAGES_POLLING_ATTEMPTS, MESSAGES_POLLING_INTERVAL); + BackOff backoff; + if (!duration.isLongerThan(Duration.ZERO)) { + backoff = MESSAGES_BACKOFF_FACTORY.backoff(); + } else { + backoff = MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(duration).backoff(); + } + + // This function tracks the cumulative time from the *first request* to enforce the wall-clock + // limit. Any backoff instance could, at best, track the the time since the first attempt at a + // given request. Thus, we need to track the cumulative time ourselves. + long startNanos = nanoClock.nanoTime(); + State state; do { // Get the state of the job before listing messages. This ensures we always fetch job // messages after the job finishes to ensure we have all them. - state = getStateWithRetries(1, sleeper); + state = getStateWithRetries(STATUS_BACKOFF_FACTORY.withMaxRetries(0).backoff(), sleeper); boolean hasError = state == State.UNKNOWN; if (messageHandler != null && !hasError) { @@ -241,7 +255,16 @@ State waitToFinish( } if (!hasError) { + // Reset the backoff. backoff.reset(); + // If duration is set, update the new cumulative sleep time to be the remaining + // part of the total input sleep duration. + if (duration.isLongerThan(Duration.ZERO)) { + long nanosConsumed = nanoClock.nanoTime() - startNanos; + Duration consumed = Duration.millis((nanosConsumed + 999999) / 1000000); + backoff = + MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(duration.minus(consumed)).backoff(); + } // Check if the job is done. if (state.isTerminal()) { return state; @@ -272,7 +295,7 @@ public State getState() { return terminalState; } - return getStateWithRetries(STATUS_POLLING_ATTEMPTS, Sleeper.DEFAULT); + return getStateWithRetries(STATUS_BACKOFF_FACTORY.backoff(), Sleeper.DEFAULT); } /** @@ -284,7 +307,7 @@ public State getState() { * @return The state of the job or State.UNKNOWN in case of failure. */ @VisibleForTesting - State getStateWithRetries(int attempts, Sleeper sleeper) { + State getStateWithRetries(BackOff attempts, Sleeper sleeper) { if (terminalState != null) { return terminalState; } @@ -303,17 +326,13 @@ State getStateWithRetries(int attempts, Sleeper sleeper) { * Attempts to get the underlying {@link Job}. Uses exponential backoff on failure up to the * maximum number of passed in attempts. * - * @param attempts The amount of attempts to make. + * @param backoff the {@link BackOff} used to control retries. * @param sleeper Object used to do the sleeps between attempts. * @return The underlying {@link Job} object. * @throws IOException When the maximum number of retries is exhausted, the last exception is * thrown. */ - @VisibleForTesting - Job getJobWithRetries(int attempts, Sleeper sleeper) throws IOException { - AttemptBoundedExponentialBackOff backoff = - new AttemptBoundedExponentialBackOff(attempts, STATUS_POLLING_INTERVAL); - + private Job getJobWithRetries(BackOff backoff, Sleeper sleeper) throws IOException { // Retry loop ends in return or throw while (true) { try { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java index e94d414fc0..10793bd7c1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java @@ -31,7 +31,10 @@ * constructor. * *

            Implementation is not thread-safe. + * + * @deprecated prefer {@link FluentBackoff} */ +@Deprecated public class AttemptAndTimeBoundedExponentialBackOff extends AttemptBoundedExponentialBackOff { private long endTimeMillis; private long maximumTotalWaitTimeMillis; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java index 613316ea0e..f7df6f7725 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java @@ -41,7 +41,10 @@ *

            * *

            Implementation is not thread-safe. + * + * @deprecated prefer {@link FluentBackoff} */ +@Deprecated public class AttemptBoundedExponentialBackOff implements BackOff { public static final double DEFAULT_MULTIPLIER = 1.5; public static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index 79ad00f0cb..d1054db271 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -40,12 +40,12 @@ import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.NoSuchElementException; -import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; @@ -57,14 +57,14 @@ public class BigQueryServicesImpl implements BigQueryServices { private static final Logger LOG = LoggerFactory.getLogger(BigQueryServicesImpl.class); - // The maximum number of attempts to execute a BigQuery RPC. - private static final int MAX_RPC_ATTEMPTS = 10; + // The maximum number of retries to execute a BigQuery RPC. + private static final int MAX_RPC_RETRIES = 9; // The initial backoff for executing a BigQuery RPC. - private static final long INITIAL_RPC_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); + private static final Duration INITIAL_RPC_BACKOFF = Duration.standardSeconds(1); // The initial backoff for polling the status of a BigQuery job. - private static final long INITIAL_JOB_STATUS_POLL_BACKOFF_MILLIS = TimeUnit.SECONDS.toMillis(1); + private static final Duration INITIAL_JOB_STATUS_POLL_BACKOFF = Duration.standardSeconds(1); @Override public JobService getJobService(BigQueryOptions options) { @@ -106,9 +106,9 @@ private JobServiceImpl(BigQueryOptions options) { /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startLoadJob( @@ -124,9 +124,9 @@ public void startLoadJob( /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) @@ -142,9 +142,9 @@ public void startExtractJob(JobReference jobRef, JobConfigurationExtract extract /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startQueryJob(JobReference jobRef, JobConfigurationQuery queryConfig) @@ -160,9 +160,9 @@ public void startQueryJob(JobReference jobRef, JobConfigurationQuery queryConfig /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) @@ -179,7 +179,8 @@ private static void startJob(Job job, ApiErrorExtractor errorExtractor, Bigquery client) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); startJob(job, errorExtractor, client, Sleeper.DEFAULT, backoff); } @@ -212,15 +213,17 @@ static void startJob( throw new IOException( String.format( "Unable to insert job: %s, aborting after %d .", - jobRef.getJobId(), MAX_RPC_ATTEMPTS), + jobRef.getJobId(), MAX_RPC_RETRIES), lastException); } @Override public Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException { - BackOff backoff = new AttemptBoundedExponentialBackOff( - maxAttempts, INITIAL_JOB_STATUS_POLL_BACKOFF_MILLIS); + BackOff backoff = + FluentBackoff.DEFAULT + .withMaxRetries(maxAttempts).withInitialBackoff(INITIAL_JOB_STATUS_POLL_BACKOFF) + .backoff(); return pollJob(jobRef, Sleeper.DEFAULT, backoff); } @@ -255,12 +258,13 @@ public JobStatistics dryRunQuery(String projectId, String query) .setQuery(query)) .setDryRun(true)); BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return executeWithRetries( client.jobs().insert(projectId, job), String.format( "Unable to dry run query: %s, aborting after %d retries.", - query, MAX_RPC_ATTEMPTS), + query, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff).getStatistics(); } @@ -275,7 +279,9 @@ public JobStatistics dryRunQuery(String projectId, String query) @Override public Job getJob(JobReference jobRef) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_JOB_STATUS_POLL_BACKOFF) + .backoff(); return getJob(jobRef, Sleeper.DEFAULT, backoff); } @@ -306,13 +312,28 @@ public Job getJob(JobReference jobRef, Sleeper sleeper, BackOff backoff) throw new IOException( String.format( "Unable to find BigQuery job: %s, aborting after %d retries.", - jobRef, MAX_RPC_ATTEMPTS), + jobRef, MAX_RPC_RETRIES), lastException); } } @VisibleForTesting static class DatasetServiceImpl implements DatasetService { + // Approximate amount of table data to upload per InsertAll request. + private static final long UPLOAD_BATCH_SIZE_BYTES = 64 * 1024; + + // The maximum number of rows to upload per InsertAll request. + private static final long MAX_ROWS_PER_BATCH = 500; + + private static final FluentBackoff INSERT_BACKOFF_FACTORY = + FluentBackoff.DEFAULT.withInitialBackoff(Duration.millis(200)).withMaxRetries(5); + + // A backoff for rate limit exceeded errors. Retries forever. + private static final FluentBackoff DEFAULT_BACKOFF_FACTORY = + FluentBackoff.DEFAULT + .withInitialBackoff(Duration.standardSeconds(1)) + .withMaxBackoff(Duration.standardMinutes(2)); + private final ApiErrorExtractor errorExtractor; private final Bigquery client; @@ -330,20 +351,21 @@ private DatasetServiceImpl(BigQueryOptions bqOptions) { /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public Table getTable(String projectId, String datasetId, String tableId) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return executeWithRetries( client.tables().get(projectId, datasetId, tableId), String.format( "Unable to get table: %s, aborting after %d retries.", - tableId, MAX_RPC_ATTEMPTS), + tableId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff); } @@ -351,20 +373,21 @@ public Table getTable(String projectId, String datasetId, String tableId) /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void deleteTable(String projectId, String datasetId, String tableId) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); executeWithRetries( client.tables().delete(projectId, datasetId, tableId), String.format( "Unable to delete table: %s, aborting after %d retries.", - tableId, MAX_RPC_ATTEMPTS), + tableId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff); } @@ -372,12 +395,13 @@ public void deleteTable(String projectId, String datasetId, String tableId) public boolean isTableEmpty(String projectId, String datasetId, String tableId) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); TableDataList dataList = executeWithRetries( client.tabledata().list(projectId, datasetId, tableId), String.format( "Unable to list table data: %s, aborting after %d retries.", - tableId, MAX_RPC_ATTEMPTS), + tableId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff); return dataList.getRows() == null || dataList.getRows().isEmpty(); @@ -386,19 +410,20 @@ public boolean isTableEmpty(String projectId, String datasetId, String tableId) /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ public Dataset getDataset(String projectId, String datasetId) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return executeWithRetries( client.datasets().get(projectId, datasetId), String.format( "Unable to get dataset: %s, aborting after %d retries.", - datasetId, MAX_RPC_ATTEMPTS), + datasetId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff); } @@ -406,21 +431,21 @@ public Dataset getDataset(String projectId, String datasetId) /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void createDataset( String projectId, String datasetId, String location, String description) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); createDataset(projectId, datasetId, location, description, Sleeper.DEFAULT, backoff); } - @VisibleForTesting - void createDataset( + private void createDataset( String projectId, String datasetId, String location, @@ -457,34 +482,35 @@ void createDataset( throw new IOException( String.format( "Unable to create dataset: %s, aborting after %d .", - datasetId, MAX_RPC_ATTEMPTS), + datasetId, MAX_RPC_RETRIES), lastException); } /** * {@inheritDoc} * - *

            Tries executing the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. + *

            Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * - * @throws IOException if it exceeds {@code MAX_RPC_ATTEMPTS} attempts. + * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void deleteDataset(String projectId, String datasetId) throws IOException, InterruptedException { BackOff backoff = - new AttemptBoundedExponentialBackOff(MAX_RPC_ATTEMPTS, INITIAL_RPC_BACKOFF_MILLIS); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); executeWithRetries( client.datasets().delete(projectId, datasetId), String.format( "Unable to delete table: %s, aborting after %d retries.", - datasetId, MAX_RPC_ATTEMPTS), + datasetId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff); } } private static class BigQueryJsonReaderImpl implements BigQueryJsonReader { - BigQueryTableRowIterator iterator; + private BigQueryTableRowIterator iterator; private BigQueryJsonReaderImpl(BigQueryTableRowIterator iterator) { this.iterator = iterator; @@ -562,7 +588,6 @@ static T executeWithRetries( /** * Identical to {@link BackOffUtils#next} but without checked IOException. - * @throws InterruptedException */ private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { try { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java index aa992c52f6..f16118a4c1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java @@ -37,6 +37,7 @@ import com.google.common.base.Preconditions; import com.google.common.util.concurrent.MoreExecutors; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,11 +67,9 @@ public class BigQueryTableInserter { // The maximum number of rows to upload per InsertAll request. private static final long MAX_ROWS_PER_BATCH = 500; - // The maximum number of times to retry inserting rows into BigQuery. - private static final int MAX_INSERT_ATTEMPTS = 5; - - // The initial backoff after a failure inserting rows into BigQuery. - private static final long INITIAL_INSERT_BACKOFF_INTERVAL_MS = 200L; + // Backoff for inserting rows to BigQuery. + private static final FluentBackoff INSERT_BACKOFF_FACTORY = + FluentBackoff.DEFAULT.withInitialBackoff(Duration.millis(200)).withMaxRetries(5); // Backoff time bounds for rate limit exceeded errors. private static final long INITIAL_RATE_LIMIT_EXCEEDED_BACKOFF_MS = TimeUnit.SECONDS.toMillis(1); @@ -150,7 +149,7 @@ public void insertAll(List rowList) throws IOException { /** * Insert all rows from the given list using specified insertIds if not null. * - * @deprecated replaced by {@link #insertAll(TableReference, List, List)} + * @deprecated replaced by {@link #insertAll(TableReference, List, List, Aggregator)} */ @Deprecated public void insertAll(List rowList, @@ -178,9 +177,7 @@ public void insertAll(TableReference ref, List rowList, + "as many elements as rowList"); } - AttemptBoundedExponentialBackOff backoff = new AttemptBoundedExponentialBackOff( - MAX_INSERT_ATTEMPTS, - INITIAL_INSERT_BACKOFF_INTERVAL_MS); + BackOff backoff = INSERT_BACKOFF_FACTORY.backoff(); List allErrors = new ArrayList<>(); // These lists contain the rows to publish. Initially the contain the entire list. If there are @@ -280,7 +277,12 @@ public List call() throws IOException { throw new RuntimeException(e.getCause()); } - if (!allErrors.isEmpty() && !backoff.atMaxAttempts()) { + if (allErrors.isEmpty()) { + break; + } + + long nextBackoffMillis = backoff.nextBackOffMillis(); + if (nextBackoffMillis == BackOff.STOP) { try { Thread.sleep(backoff.nextBackOffMillis()); } catch (InterruptedException e) { @@ -291,8 +293,6 @@ public List call() throws IOException { rowsToPublish = retryRows; idsToPublish = retryIds; allErrors.clear(); - } else { - break; } } if (!allErrors.isEmpty()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index e1b7079347..b450a8eabf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -466,7 +466,8 @@ public static T executeWithBackOff(AbstractGoogleClientRequest client, St throws IOException, InterruptedException { Sleeper sleeper = Sleeper.DEFAULT; BackOff backOff = - new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_TIME.getMillis()); + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RETRIES).withInitialBackoff(INITIAL_BACKOFF_TIME).backoff(); T result = null; while (true) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java new file mode 100644 index 0000000000..cae3e6a3da --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java @@ -0,0 +1,227 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.api.client.util.BackOff; +import com.google.common.base.MoreObjects; +import org.joda.time.Duration; + +/** + * A fluent builder for {@link BackOff} objects that allows customization of the retry algorithm. + * + * @see #DEFAULT for the default configuration parameters. + */ +public final class FluentBackoff { + + private static final double DEFAULT_EXPONENT = 1.5; + private static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5; + private static final Duration DEFAULT_MIN_BACKOFF = Duration.standardSeconds(1); + private static final Duration DEFAULT_MAX_BACKOFF = Duration.standardDays(1000); + private static final int DEFAULT_MAX_RETRIES = Integer.MAX_VALUE; + private static final Duration DEFAULT_MAX_CUM_BACKOFF = Duration.standardDays(1000); + + private final double exponent; + private final Duration initialBackoff; + private final Duration maxBackoff; + private final Duration maxCumulativeBackoff; + private final int maxRetries; + + /** + * By default the {@link BackOff} created by this builder will use exponential backoff (base + * exponent 1.5) with an initial backoff of 1 second. These parameters can be overridden with + * {@link #withExponent(double)} and {@link #withInitialBackoff(Duration)}, + * respectively, and the maximum backoff after exponential increase can be capped using {@link + * FluentBackoff#withMaxBackoff(Duration)}. + * + *

            The default {@link BackOff} does not limit the number of retries. To limit the backoff, the + * maximum total number of retries can be set using {@link #withMaxRetries(int)}. The + * total time spent in backoff can be time-bounded as well by configuring {@link + * #withMaxCumulativeBackoff(Duration)}. If either of these limits are reached, calls + * to {@link BackOff#nextBackOffMillis()} will return {@link BackOff#STOP} to signal that no more + * retries should continue. + */ + public static final FluentBackoff DEFAULT = new FluentBackoff( + DEFAULT_EXPONENT, + DEFAULT_MIN_BACKOFF, DEFAULT_MAX_BACKOFF, DEFAULT_MAX_CUM_BACKOFF, + DEFAULT_MAX_RETRIES); + + /** + * Instantiates a {@link BackOff} that will obey the current configuration. + * + * @see FluentBackoff + */ + public BackOff backoff() { + return new BackoffImpl(this); + } + + /** + * Returns a copy of this {@link FluentBackoff} that instead uses the specified exponent to + * control the exponential growth of delay. + * + *

            Does not modify this object. + * + * @see FluentBackoff + */ + public FluentBackoff withExponent(double exponent) { + checkArgument(exponent > 0, "exponent %s must be greater than 0", exponent); + return new FluentBackoff( + exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); + } + + /** + * Returns a copy of this {@link FluentBackoff} that instead uses the specified initial backoff + * duration. + * + *

            Does not modify this object. + * + * @see FluentBackoff + */ + public FluentBackoff withInitialBackoff(Duration initialBackoff) { + checkArgument( + initialBackoff.isLongerThan(Duration.ZERO), + "initialBackoff %s must be at least 1 millisecond", + initialBackoff); + return new FluentBackoff( + exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); + } + + /** + * Returns a copy of this {@link FluentBackoff} that limits the maximum backoff of an individual + * attempt to the specified duration. + * + *

            Does not modify this object. + * + * @see FluentBackoff + */ + public FluentBackoff withMaxBackoff(Duration maxBackoff) { + checkArgument( + maxBackoff.getMillis() > 0, + "maxBackoff %s must be at least 1 millisecond", + maxBackoff); + return new FluentBackoff( + exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); + } + + /** + * Returns a copy of this {@link FluentBackoff} that limits the total time spent in backoff + * returned across all calls to {@link BackOff#nextBackOffMillis()}. + * + *

            Does not modify this object. + * + * @see FluentBackoff + */ + public FluentBackoff withMaxCumulativeBackoff(Duration maxCumulativeBackoff) { + checkArgument(maxCumulativeBackoff.isLongerThan(Duration.ZERO), + "maxCumulativeBackoff %s must be at least 1 millisecond", maxCumulativeBackoff); + return new FluentBackoff( + exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); + } + + /** + * Returns a copy of this {@link FluentBackoff} that limits the total number of retries, aka + * the total number of calls to {@link BackOff#nextBackOffMillis()} before returning + * {@link BackOff#STOP}. + * + *

            Does not modify this object. + * + * @see FluentBackoff + */ + public FluentBackoff withMaxRetries(int maxRetries) { + checkArgument(maxRetries >= 0, "maxRetries %s cannot be negative", maxRetries); + return new FluentBackoff( + exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); + } + + public String toString() { + return MoreObjects.toStringHelper(FluentBackoff.class) + .add("exponent", exponent) + .add("initialBackoff", initialBackoff) + .add("maxBackoff", maxBackoff) + .add("maxRetries", maxRetries) + .add("maxCumulativeBackoff", maxCumulativeBackoff) + .toString(); + } + + private static class BackoffImpl implements BackOff { + + // Customization of this backoff. + private final FluentBackoff backoffConfig; + // Current state + private Duration currentCumulativeBackoff; + private int currentRetry; + + @Override + public void reset() { + currentRetry = 0; + currentCumulativeBackoff = Duration.ZERO; + } + + @Override + public long nextBackOffMillis() { + // Maximum number of retries reached. + if (currentRetry >= backoffConfig.maxRetries) { + return BackOff.STOP; + } + // Maximum cumulative backoff reached. + if (currentCumulativeBackoff.compareTo(backoffConfig.maxCumulativeBackoff) >= 0) { + return BackOff.STOP; + } + + double currentIntervalMillis = + Math.min( + backoffConfig.initialBackoff.getMillis() + * Math.pow(backoffConfig.exponent, currentRetry), + backoffConfig.maxBackoff.getMillis()); + double randomOffset = + (Math.random() * 2 - 1) * DEFAULT_RANDOMIZATION_FACTOR * currentIntervalMillis; + long nextBackoffMillis = Math.round(currentIntervalMillis + randomOffset); + // Cap to limit on cumulative backoff + Duration remainingCumulative = + backoffConfig.maxCumulativeBackoff.minus(currentCumulativeBackoff); + nextBackoffMillis = Math.min(nextBackoffMillis, remainingCumulative.getMillis()); + + // Update state and return backoff. + currentCumulativeBackoff = currentCumulativeBackoff.plus(nextBackoffMillis); + currentRetry += 1; + return nextBackoffMillis; + } + + private BackoffImpl(FluentBackoff backoffConfig) { + this.backoffConfig = backoffConfig; + this.reset(); + } + + public String toString() { + return MoreObjects.toStringHelper(BackoffImpl.class) + .add("backoffConfig", backoffConfig) + .add("currentRetry", currentRetry) + .add("currentCumulativeBackoff", currentCumulativeBackoff) + .toString(); + } + } + + private FluentBackoff( + double exponent, Duration initialBackoff, Duration maxBackoff, Duration maxCumulativeBackoff, + int maxRetries) { + this.exponent = exponent; + this.initialBackoff = initialBackoff; + this.maxBackoff = maxBackoff; + this.maxRetries = maxRetries; + this.maxCumulativeBackoff = maxCumulativeBackoff; + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java index dba7b49f80..e3a807e7c6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java @@ -49,6 +49,7 @@ import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -121,6 +122,9 @@ public GcsUtil create(PipelineOptions options) { */ private static final int MAX_CONCURRENT_BATCHES = 256; + private static final FluentBackoff BACKOFF_FACTORY = + FluentBackoff.DEFAULT.withMaxRetries(3).withInitialBackoff(Duration.millis(200)); + ///////////////////////////////////////////////////////////////////////////// /** Client for the GCS API. */ @@ -179,7 +183,7 @@ public List expand(GcsPath gcsPattern) throws IOException { // the request has strong global consistency. ResilientOperation.retry( ResilientOperation.getGoogleRequestCallable(getObject), - new AttemptBoundedExponentialBackOff(3, 200), + BACKOFF_FACTORY.backoff(), RetryDeterminer.SOCKET_ERRORS, IOException.class); return ImmutableList.of(gcsPattern); @@ -218,7 +222,7 @@ public List expand(GcsPath gcsPattern) throws IOException { try { objects = ResilientOperation.retry( ResilientOperation.getGoogleRequestCallable(listObject), - new AttemptBoundedExponentialBackOff(3, 200), + BACKOFF_FACTORY.backoff(), RetryDeterminer.SOCKET_ERRORS, IOException.class); } catch (Exception e) { @@ -259,7 +263,10 @@ Integer getUploadBufferSizeBytes() { * if the resource does not exist. */ public long fileSize(GcsPath path) throws IOException { - return fileSize(path, new AttemptBoundedExponentialBackOff(4, 200), Sleeper.DEFAULT); + return fileSize( + path, + BACKOFF_FACTORY.backoff(), + Sleeper.DEFAULT); } /** @@ -337,7 +344,10 @@ public WritableByteChannel create(GcsPath path, * be accessible otherwise the permissions exception will be propagated. */ public boolean bucketExists(GcsPath path) throws IOException { - return bucketExists(path, new AttemptBoundedExponentialBackOff(4, 200), Sleeper.DEFAULT); + return bucketExists( + path, + BACKOFF_FACTORY.backoff(), + Sleeper.DEFAULT); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java index 5e73ad8fe8..d7a246d695 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java @@ -46,6 +46,7 @@ * *

            Implementation is not thread-safe. */ +@Deprecated public class IntervalBoundedExponentialBackOff implements BackOff { public static final double DEFAULT_MULTIPLIER = 1.5; public static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java index 8b2d56f133..d5f0e3f099 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java @@ -13,10 +13,9 @@ * License for the specific language governing permissions and limitations under * the License. */ - package com.google.cloud.dataflow.sdk.util; -import com.google.api.client.util.BackOffUtils; +import com.google.api.client.util.BackOff; import com.google.api.client.util.Sleeper; import com.google.api.services.dataflow.model.DataflowPackage; import com.google.cloud.hadoop.util.ApiErrorExtractor; @@ -28,6 +27,7 @@ import com.fasterxml.jackson.core.Base64Variants; +import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,11 +52,15 @@ public class PackageUtil { /** * The initial interval to use between package staging attempts. */ - private static final long INITIAL_BACKOFF_INTERVAL_MS = 5000L; + private static final Duration INITIAL_BACKOFF_INTERVAL = Duration.standardSeconds(5); /** - * The maximum number of attempts when staging a file. + * The maximum number of retries when staging a file. */ - private static final int MAX_ATTEMPTS = 5; + private static final int MAX_RETRIES = 4; + + private static final FluentBackoff BACKOFF_FACTORY = + FluentBackoff.DEFAULT + .withMaxRetries(MAX_RETRIES).withInitialBackoff(INITIAL_BACKOFF_INTERVAL); /** * Translates exceptions from API calls. @@ -197,9 +201,7 @@ static List stageClasspathElements( } // Upload file, retrying on failure. - AttemptBoundedExponentialBackOff backoff = new AttemptBoundedExponentialBackOff( - MAX_ATTEMPTS, - INITIAL_BACKOFF_INTERVAL_MS); + BackOff backoff = BACKOFF_FACTORY.backoff(); while (true) { try { LOG.debug("Uploading classpath element {} to {}", classpathElement, target); @@ -217,15 +219,17 @@ static List stageClasspathElements( + "'gcloud auth login'.", classpathElement, target); LOG.error(errorMessage); throw new IOException(errorMessage, e); - } else if (!backoff.atMaxAttempts()) { - LOG.warn("Upload attempt failed, sleeping before retrying staging of classpath: {}", - classpathElement, e); - BackOffUtils.next(retrySleeper, backoff); - } else { + } + long sleep = backoff.nextBackOffMillis(); + if (sleep == BackOff.STOP) { // Rethrow last error, to be included as a cause in the catch below. LOG.error("Upload failed, will NOT retry staging of classpath: {}", classpathElement, e); throw e; + } else { + LOG.warn("Upload attempt failed, sleeping before retrying staging of classpath: {}", + classpathElement, e); + retrySleeper.sleep(sleep); } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java index 261cecb962..cc364ce34f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java @@ -46,7 +46,6 @@ import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.util.AttemptBoundedExponentialBackOff; import com.google.cloud.dataflow.sdk.util.MonitoringUtil; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.cloud.dataflow.sdk.values.POutput; @@ -54,6 +53,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSetMultimap; +import org.joda.time.Duration; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -101,22 +101,21 @@ public void setup() { * AttemptBoundedExponentialBackOff given the number of retries and * an initial polling interval. * - * @param pollingIntervalMillis The initial polling interval given. - * @param attempts The number of attempts made + * @param pollingInterval The initial polling interval given. + * @param retries The number of retries made * @param timeSleptMillis The amount of time slept by the clock. This is checked * against the valid interval. */ - void checkValidInterval(long pollingIntervalMillis, int attempts, long timeSleptMillis) { + private void checkValidInterval(Duration pollingInterval, int retries, long timeSleptMillis) { long highSum = 0; long lowSum = 0; - for (int i = 1; i < attempts; i++) { + for (int i = 0; i < retries; i++) { double currentInterval = - pollingIntervalMillis - * Math.pow(AttemptBoundedExponentialBackOff.DEFAULT_MULTIPLIER, i - 1); - double offset = - AttemptBoundedExponentialBackOff.DEFAULT_RANDOMIZATION_FACTOR * currentInterval; - highSum += Math.round(currentInterval + offset); - lowSum += Math.round(currentInterval - offset); + pollingInterval.getMillis() + * Math.pow(DataflowPipelineJob.DEFAULT_BACKOFF_EXPONENT, i); + double randomOffset = 0.5 * currentInterval; + highSum += Math.round(currentInterval + randomOffset); + lowSum += Math.round(currentInterval - randomOffset); } assertThat(timeSleptMillis, allOf(greaterThanOrEqualTo(lowSum), lessThanOrEqualTo(highSum))); } @@ -143,7 +142,7 @@ public void testWaitToFinishMessagesFail() throws Exception { DataflowPipelineJob job = new DataflowPipelineJob( PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - State state = job.waitToFinish(5, TimeUnit.MINUTES, jobHandler, fastClock, fastClock); + State state = job.waitToFinish(Duration.standardMinutes(5), jobHandler, fastClock, fastClock); assertEquals(null, state); } @@ -161,7 +160,7 @@ public State mockWaitToFinishInState(State state) throws Exception { DataflowPipelineJob job = new DataflowPipelineJob( PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - return job.waitToFinish(1, TimeUnit.MINUTES, null, fastClock, fastClock); + return job.waitToFinish(Duration.standardMinutes(1), null, fastClock, fastClock); } /** @@ -213,11 +212,11 @@ public void testWaitToFinishFail() throws Exception { PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); long startTime = fastClock.nanoTime(); - State state = job.waitToFinish(5, TimeUnit.MINUTES, null, fastClock, fastClock); + State state = job.waitToFinish(Duration.standardMinutes(5), null, fastClock, fastClock); assertEquals(null, state); long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime); checkValidInterval(DataflowPipelineJob.MESSAGES_POLLING_INTERVAL, - DataflowPipelineJob.MESSAGES_POLLING_ATTEMPTS, timeDiff); + DataflowPipelineJob.MESSAGES_POLLING_RETRIES, timeDiff); } @Test @@ -232,11 +231,11 @@ public void testWaitToFinishTimeFail() throws Exception { DataflowPipelineJob job = new DataflowPipelineJob( PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); long startTime = fastClock.nanoTime(); - State state = job.waitToFinish(4, TimeUnit.MILLISECONDS, null, fastClock, fastClock); + State state = job.waitToFinish(Duration.millis(4), null, fastClock, fastClock); assertEquals(null, state); long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime); - // Should only sleep for the 4 ms remaining. - assertEquals(timeDiff, 4L); + // Should only have slept for the 4 ms allowed. + assertEquals(4L, timeDiff); } @Test @@ -257,7 +256,7 @@ public void testGetStateReturnsServiceState() throws Exception { assertEquals( State.RUNNING, - job.getStateWithRetries(DataflowPipelineJob.STATUS_POLLING_ATTEMPTS, fastClock)); + job.getStateWithRetries(DataflowPipelineJob.STATUS_BACKOFF_FACTORY.backoff(), fastClock)); } @Test @@ -275,10 +274,10 @@ public void testGetStateWithExceptionReturnsUnknown() throws Exception { long startTime = fastClock.nanoTime(); assertEquals( State.UNKNOWN, - job.getStateWithRetries(DataflowPipelineJob.STATUS_POLLING_ATTEMPTS, fastClock)); + job.getStateWithRetries(DataflowPipelineJob.STATUS_BACKOFF_FACTORY.backoff(), fastClock)); long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime); checkValidInterval(DataflowPipelineJob.STATUS_POLLING_INTERVAL, - DataflowPipelineJob.STATUS_POLLING_ATTEMPTS, timeDiff); + DataflowPipelineJob.STATUS_POLLING_RETRIES, timeDiff); } @Test diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java index 1d1f27f61b..e200ee9a72 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java @@ -35,6 +35,7 @@ /** Unit tests for {@link AttemptAndTimeBoundedExponentialBackOff}. */ @RunWith(JUnit4.class) +@SuppressWarnings("deprecation") // tests a deprecated clas public class AttemptAndTimeBoundedExponentialBackOffTest { @Rule public ExpectedException exception = ExpectedException.none(); @Rule public FastNanoClockAndSleeper fastClock = new FastNanoClockAndSleeper(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java index 6f86e61b8a..b4897dc4df 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java @@ -35,6 +35,7 @@ /** Unit tests for {@link AttemptBoundedExponentialBackOff}. */ @RunWith(JUnit4.class) +@SuppressWarnings("deprecation") // tests a deprecated class public class AttemptBoundedExponentialBackOffTest { @Rule public ExpectedException exception = ExpectedException.none(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java index ec6f6ba37a..df6632be76 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java @@ -112,9 +112,8 @@ public void testStartLoadJobSucceeds() throws IOException, InterruptedException loadConfig.setDestinationTable(ref); Sleeper sleeper = new FastNanoClockAndSleeper(); - BackOff backoff = new AttemptBoundedExponentialBackOff( - 5 /* attempts */, 1000 /* initialIntervalMillis */); - JobServiceImpl.startJob(testJob, new ApiErrorExtractor(), bigquery, sleeper, backoff); + JobServiceImpl.startJob( + testJob, new ApiErrorExtractor(), bigquery, sleeper, FluentBackoff.DEFAULT.backoff()); verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); @@ -141,9 +140,8 @@ public void testStartLoadJobSucceedsAlreadyExists() throws IOException, Interrup loadConfig.setDestinationTable(ref); Sleeper sleeper = new FastNanoClockAndSleeper(); - BackOff backoff = new AttemptBoundedExponentialBackOff( - 5 /* attempts */, 1000 /* initialIntervalMillis */); - JobServiceImpl.startJob(testJob, new ApiErrorExtractor(), bigquery, sleeper, backoff); + JobServiceImpl.startJob( + testJob, new ApiErrorExtractor(), bigquery, sleeper, FluentBackoff.DEFAULT.backoff()); verify(response, times(1)).getStatusCode(); verify(response, times(1)).getContent(); @@ -174,9 +172,8 @@ public void testStartLoadJobRetry() throws IOException, InterruptedException { loadConfig.setDestinationTable(ref); Sleeper sleeper = new FastNanoClockAndSleeper(); - BackOff backoff = new AttemptBoundedExponentialBackOff( - 5 /* attempts */, 1000 /* initialIntervalMillis */); - JobServiceImpl.startJob(testJob, new ApiErrorExtractor(), bigquery, sleeper, backoff); + JobServiceImpl.startJob( + testJob, new ApiErrorExtractor(), bigquery, sleeper, FluentBackoff.DEFAULT.backoff()); verify(response, times(2)).getStatusCode(); verify(response, times(2)).getContent(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java new file mode 100644 index 0000000000..a251387aae --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java @@ -0,0 +1,226 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.util; + +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import com.google.api.client.util.BackOff; + +import org.joda.time.Duration; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; + +/** + * Tests for {@link FluentBackoff}. + */ +@RunWith(JUnit4.class) +public class FluentBackoffTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + private final FluentBackoff defaultBackoff = FluentBackoff.DEFAULT; + + @Test + public void testInvalidExponent() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("exponent -2.0 must be greater than 0"); + defaultBackoff.withExponent(-2.0); + } + + @Test + public void testInvalidInitialBackoff() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("initialBackoff PT0S must be at least 1 millisecond"); + defaultBackoff.withInitialBackoff(Duration.ZERO); + } + + @Test + public void testInvalidMaxBackoff() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("maxBackoff PT0S must be at least 1 millisecond"); + defaultBackoff.withMaxBackoff(Duration.ZERO); + } + + @Test + public void testInvalidMaxRetries() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("maxRetries -1 cannot be negative"); + defaultBackoff.withMaxRetries(-1); + } + + @Test + public void testInvalidCumulativeBackoff() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("maxCumulativeBackoff PT-0.002S must be at least 1 millisecond"); + defaultBackoff.withMaxCumulativeBackoff(Duration.millis(-2)); + } + + /** + * Tests with bounded interval, custom exponent, and unlimited retries. + */ + @Test + public void testBoundedIntervalWithReset() throws Exception { + BackOff backOff = + FluentBackoff.DEFAULT + .withInitialBackoff(Duration.millis(500)) + .withMaxBackoff(Duration.standardSeconds(1)).backoff(); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(374L), lessThan(1126L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), + lessThanOrEqualTo(1500L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), + lessThanOrEqualTo(1500L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), + lessThanOrEqualTo(1500L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), + lessThanOrEqualTo(1500L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), + lessThanOrEqualTo(1500L))); + + // Reset, should go back to short times. + backOff.reset(); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(374L), lessThan(1126L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), + lessThanOrEqualTo(1500L))); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), + lessThanOrEqualTo(1500L))); + + } + + /** + * Tests with bounded interval, custom exponent, limited retries, and a reset. + */ + @Test + public void testMaxRetriesWithReset() throws Exception { + BackOff backOff = + FluentBackoff.DEFAULT + .withInitialBackoff(Duration.millis(500)) + .withMaxRetries(1) + .backoff(); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); + assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); + assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); + assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); + assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); + + backOff.reset(); + assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); + assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); + } + + private static long countMaximumBackoff(BackOff backOff) throws IOException { + long cumulativeBackoffMillis = 0; + long currentBackoffMillis = backOff.nextBackOffMillis(); + while (currentBackoffMillis != BackOff.STOP) { + cumulativeBackoffMillis += currentBackoffMillis; + currentBackoffMillis = backOff.nextBackOffMillis(); + } + return cumulativeBackoffMillis; + } + + /** + * Tests with bounded interval, custom exponent, limited cumulative time, and a reset. + */ + @Test + public void testBoundedIntervalAndCumTimeWithReset() throws Exception { + BackOff backOff = + FluentBackoff.DEFAULT + .withInitialBackoff(Duration.millis(500)) + .withMaxBackoff(Duration.standardSeconds(1)) + .withMaxCumulativeBackoff(Duration.standardMinutes(1)).backoff(); + + assertThat(countMaximumBackoff(backOff), equalTo(Duration.standardMinutes(1).getMillis())); + + backOff.reset(); + assertThat(countMaximumBackoff(backOff), equalTo(Duration.standardMinutes(1).getMillis())); + // sanity check: should get 0 if we don't reset + assertThat(countMaximumBackoff(backOff), equalTo(0L)); + + backOff.reset(); + assertThat(countMaximumBackoff(backOff), equalTo(Duration.standardMinutes(1).getMillis())); + } + + /** + * Tests with bounded interval, custom exponent, limited cumulative time and retries. + */ + @Test + public void testBoundedIntervalAndCumTimeAndRetriesWithReset() throws Exception { + BackOff backOff = + FluentBackoff.DEFAULT + .withInitialBackoff(Duration.millis(500)) + .withMaxBackoff(Duration.standardSeconds(1)) + .withMaxCumulativeBackoff(Duration.standardMinutes(1)) + .backoff(); + + long cumulativeBackoffMillis = 0; + long currentBackoffMillis = backOff.nextBackOffMillis(); + while (currentBackoffMillis != BackOff.STOP) { + cumulativeBackoffMillis += currentBackoffMillis; + currentBackoffMillis = backOff.nextBackOffMillis(); + } + assertThat(cumulativeBackoffMillis, equalTo(Duration.standardMinutes(1).getMillis())); + } + + @Test + public void testFluentBackoffToString() throws IOException { + FluentBackoff config = FluentBackoff.DEFAULT + .withExponent(3.4) + .withMaxRetries(4) + .withInitialBackoff(Duration.standardSeconds(3)) + .withMaxBackoff(Duration.standardHours(1)) + .withMaxCumulativeBackoff(Duration.standardDays(1)); + + assertEquals( + "FluentBackoff{exponent=3.4, initialBackoff=PT3S, maxBackoff=PT3600S," + + " maxRetries=4, maxCumulativeBackoff=PT86400S}", + config.toString()); + } + @Test + public void testBackoffImplToString() throws IOException { + FluentBackoff config = FluentBackoff.DEFAULT + .withExponent(3.4) + .withMaxRetries(4) + .withInitialBackoff(Duration.standardSeconds(3)) + .withMaxBackoff(Duration.standardHours(1)) + .withMaxCumulativeBackoff(Duration.standardDays(1)); + BackOff backOff = config.backoff(); + + assertEquals( + "BackoffImpl{backoffConfig=" + config.toString() + "," + + " currentRetry=0, currentCumulativeBackoff=PT0S}", + backOff.toString()); + + // backoff once, ignoring result + backOff.nextBackOffMillis(); + + // currentRetry is exact, we can test it. + assertThat(backOff.toString(), containsString("currentRetry=1")); + // currentCumulativeBackoff is not exact; we cannot even check that it's non-zero (randomness). + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java index 230a63b80f..e49c52b9a0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java @@ -364,7 +364,7 @@ public void testRetryFileSize() throws IOException { Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); - BackOff mockBackOff = new AttemptBoundedExponentialBackOff(3, 200); + BackOff mockBackOff = FluentBackoff.DEFAULT.withMaxRetries(2).backoff(); when(mockStorage.objects()).thenReturn(mockStorageObjects); when(mockStorageObjects.get("testbucket", "testobject")).thenReturn(mockStorageGet); @@ -375,7 +375,7 @@ public void testRetryFileSize() throws IOException { assertEquals(1000, gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject"), mockBackOff, new FastNanoClockAndSleeper())); - assertEquals(mockBackOff.nextBackOffMillis(), BackOff.STOP); + assertEquals(BackOff.STOP, mockBackOff.nextBackOffMillis()); } @Test @@ -389,7 +389,7 @@ public void testBucketExists() throws IOException { Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); - BackOff mockBackOff = new AttemptBoundedExponentialBackOff(3, 200); + BackOff mockBackOff = FluentBackoff.DEFAULT.backoff(); when(mockStorage.buckets()).thenReturn(mockStorageObjects); when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet); @@ -412,7 +412,7 @@ public void testBucketDoesNotExistBecauseOfAccessError() throws IOException { Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); - BackOff mockBackOff = new AttemptBoundedExponentialBackOff(3, 200); + BackOff mockBackOff = FluentBackoff.DEFAULT.backoff(); GoogleJsonResponseException expectedException = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Waves hand mysteriously", "These aren't the buckets your looking for"); @@ -437,7 +437,7 @@ public void testBucketDoesNotExist() throws IOException { Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); - BackOff mockBackOff = new AttemptBoundedExponentialBackOff(3, 200); + BackOff mockBackOff = FluentBackoff.DEFAULT.backoff(); when(mockStorage.buckets()).thenReturn(mockStorageObjects); when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet); From 5b818508dba7abd2ccf8d8aaa24a822baa15e4a4 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Tue, 6 Sep 2016 18:03:31 -0700 Subject: [PATCH 551/751] BigQueryTableRowIteratorTest: fix bug that resulted from merge conflict (#419) --- .../cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java index cecbcb70fb..4f30b1cf88 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -246,6 +246,6 @@ public void testQueryFailed() throws IOException { // Job inserted to run the query, then polled once. verify(mockClient, times(1)).jobs(); verify(mockJobs).insert(anyString(), any(Job.class)); - verify(mockJobsInsert, times(3)).execute(); + verify(mockJobsInsert, times(4)).execute(); } } From 2fd5ba4bdc8edf0e202cac2a09cc5bbef69c7d7c Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Tue, 6 Sep 2016 19:53:06 -0700 Subject: [PATCH 552/751] BigQuery: limit max job polling time to 1 minute (#418) Before the backoff would grow unboundedly, so we could in principle wait 1.5x to 2x the actual job time. For long running jobs this is hours. Now, we just back off at most 1 minute between checking the job state. Note there should be no danger of QPS overload here because we should have very few concurrent outstanding jobs --- .../cloud/dataflow/sdk/util/BigQueryServicesImpl.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index d1054db271..d3b5d44dc4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -218,11 +218,12 @@ static void startJob( } @Override - public Job pollJob(JobReference jobRef, int maxAttempts) - throws InterruptedException { + public Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException { BackOff backoff = FluentBackoff.DEFAULT - .withMaxRetries(maxAttempts).withInitialBackoff(INITIAL_JOB_STATUS_POLL_BACKOFF) + .withMaxRetries(maxAttempts) + .withInitialBackoff(INITIAL_JOB_STATUS_POLL_BACKOFF) + .withMaxBackoff(Duration.standardMinutes(1)) .backoff(); return pollJob(jobRef, Sleeper.DEFAULT, backoff); } From c4094b13b3ccb71366bb518a908c4ba828a4adbb Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Wed, 7 Sep 2016 11:23:26 -0700 Subject: [PATCH 553/751] BigQueryTableRowIterator: support queries that reference no tables (#420) * BigQueryTableRowIterator: support queries that reference no tables The new code in https://github.com/GoogleCloudPlatform/DataflowJavaSDK/pull/411 did not adequately handle the case in which a query does not reference any tables, which could result in a NullPointerException. * fixup! BigQueryTableRowIterator: support queries that refernece no tables --- .../sdk/util/BigQueryTableRowIterator.java | 13 ++-- .../util/BigQueryTableRowIteratorTest.java | 69 +++++++++++++++++++ 2 files changed, 76 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index b450a8eabf..bbf26217dc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -392,12 +392,13 @@ private TableReference executeQueryAndWaitForCompletion() client.jobs().insert(projectId, dryRunJob), String.format("Error when trying to dry run query %s.", query)).getStatistics(); - TableReference sourceTable = jobStats.getQuery() - .getReferencedTables() - .get(0); - - Table table = getTable(sourceTable); - String location = table.getLocation(); + // Default to US if the query does not read any tables. + String location = "US"; + @Nullable List tables = jobStats.getQuery().getReferencedTables(); + if (tables != null && !tables.isEmpty()) { + Table table = getTable(tables.get(0)); + location = table.getLocation(); + } // Create a temporary dataset to store results. // Starting dataset name with an "_" so that it is hidden. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java index 4f30b1cf88..f70ec4856b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -216,6 +216,75 @@ public void testReadFromQuery() throws IOException, InterruptedException { verify(mockTabledataList).execute(); } + /** + * Verifies that queries that reference no data can be read. + */ + @Test + public void testReadFromQueryNoTables() throws IOException, InterruptedException { + // Mock job inserting. + Job dryRunJob = new Job().setStatistics( + new JobStatistics().setQuery(new JobStatistics2())); + Job insertedJob = new Job().setJobReference(new JobReference()); + when(mockJobsInsert.execute()).thenReturn(dryRunJob, insertedJob); + + // Mock job polling. + JobStatus status = new JobStatus().setState("DONE"); + TableReference tableRef = + new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); + JobConfigurationQuery queryConfig = new JobConfigurationQuery().setDestinationTable(tableRef); + Job getJob = + new Job() + .setJobReference(new JobReference()) + .setStatus(status) + .setConfiguration(new JobConfiguration().setQuery(queryConfig)); + when(mockJobsGet.execute()).thenReturn(getJob); + + // Mock table schema fetch. + when(mockTablesGet.execute()).thenReturn(tableWithBasicSchema()); + + // Mock table data fetch. + when(mockTabledataList.execute()).thenReturn(rawDataList(rawRow("Arthur", 42))); + + // Run query and verify + String query = "SELECT \"Arthur\" as name, 42 as count"; + try (BigQueryTableRowIterator iterator = + BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null)) { + iterator.open(); + assertTrue(iterator.advance()); + TableRow row = iterator.getCurrent(); + + assertTrue(row.containsKey("name")); + assertTrue(row.containsKey("answer")); + assertEquals("Arthur", row.get("name")); + assertEquals(42, row.get("answer")); + + assertFalse(iterator.advance()); + } + + // Temp dataset created and later deleted. + verify(mockClient, times(2)).datasets(); + verify(mockDatasets).insert(anyString(), any(Dataset.class)); + verify(mockDatasetsInsert).execute(); + verify(mockDatasets).delete(anyString(), anyString()); + verify(mockDatasetsDelete).execute(); + // Job inserted to run the query, polled once. + verify(mockClient, times(3)).jobs(); + verify(mockJobs, times(2)).insert(anyString(), any(Job.class)); + verify(mockJobsInsert, times(2)).execute(); + verify(mockJobs).get(anyString(), anyString()); + verify(mockJobsGet).execute(); + // Temp table get after query finish, deleted after reading. + verify(mockClient, times(2)).tables(); + verify(mockTables, times(1)).get(anyString(), anyString(), anyString()); + verify(mockTablesGet, times(1)).execute(); + verify(mockTables).delete(anyString(), anyString(), anyString()); + verify(mockTablesDelete).execute(); + // Table data read. + verify(mockClient).tabledata(); + verify(mockTabledata).list("project", "dataset", "table"); + verify(mockTabledataList).execute(); + } + /** * Verifies that when the query fails, the user gets a useful exception and the temporary dataset * is cleaned up. Also verifies that the temporary table (which is never created) is not From 0146f95bc7b8341e5fee9ab49467a64c678c65cc Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Wed, 7 Sep 2016 16:19:19 -0700 Subject: [PATCH 554/751] Backport https://github.com/apache/incubator-beam/pull/918 to Dataflow SDK --- .../google/cloud/dataflow/sdk/io/TextIO.java | 152 +++++++++++++++--- .../cloud/dataflow/sdk/io/TextIOTest.java | 99 +++++++++++- 2 files changed, 226 insertions(+), 25 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 92934a91c9..a9f20c1106 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -471,7 +471,31 @@ public static Bound withoutValidation() { return new Bound<>(DEFAULT_TEXT_CODER).withoutValidation(); } - // TODO: appendingNewlines, header, footer, etc. + /** + * Returns a transform for writing to text files that adds a header string to the files + * it writes. + * + *

            A {@code null} value will clear any previously configured header. + * + * @param header the string to be added as file header + */ + public static Bound withHeader(String header) { + return new Bound<>(DEFAULT_TEXT_CODER).withHeader(header); + } + + /** + * Returns a transform for writing to text files that adds a footer string to the files + * it writes. + * + *

            A {@code null} value will clear any previously configured footer. + * + * @param footer the string to be added as file footer + */ + public static Bound withFooter(String footer) { + return new Bound<>(DEFAULT_TEXT_CODER).withFooter(footer); + } + + // TODO: appendingNewlines, etc. /** * A PTransform that writes a bounded PCollection to a text file (or @@ -488,6 +512,12 @@ public static class Bound extends PTransform, PDone> { /** The suffix of each file written, combined with prefix and shardTemplate. */ private final String filenameSuffix; + /** An optional header to add to each file. */ + private final String header; + + /** An optional footer to add to each file. */ + private final String footer; + /** The Coder to use to decode each line. */ private final Coder coder; @@ -501,12 +531,15 @@ public static class Bound extends PTransform, PDone> { private final boolean validate; Bound(Coder coder) { - this(null, null, "", coder, 0, DEFAULT_SHARD_TEMPLATE, true); + this(null, null, "", null, null, coder, 0, DEFAULT_SHARD_TEMPLATE, true); } - private Bound(String name, String filenamePrefix, String filenameSuffix, Coder coder, - int numShards, String shardTemplate, boolean validate) { + private Bound(String name, String filenamePrefix, String filenameSuffix, String header, + String footer, Coder coder, int numShards, String shardTemplate, + boolean validate) { super(name); + this.header = header; + this.footer = footer; this.coder = coder; this.filenamePrefix = filenamePrefix; this.filenameSuffix = filenameSuffix; @@ -522,7 +555,7 @@ private Bound(String name, String filenamePrefix, String filenameSuffix, CoderDoes not modify this object. */ public Bound named(String name) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, validate); } @@ -536,7 +569,7 @@ public Bound named(String name) { */ public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, validate); } @@ -550,7 +583,7 @@ public Bound to(String filenamePrefix) { */ public Bound withSuffix(String nameExtension) { validateOutputComponent(nameExtension); - return new Bound<>(name, filenamePrefix, nameExtension, coder, numShards, + return new Bound<>(name, filenamePrefix, nameExtension, header, footer, coder, numShards, shardTemplate, validate); } @@ -570,7 +603,7 @@ public Bound withSuffix(String nameExtension) { */ public Bound withNumShards(int numShards) { Preconditions.checkArgument(numShards >= 0); - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, validate); } @@ -583,7 +616,7 @@ public Bound withNumShards(int numShards) { * @see ShardNameTemplate */ public Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, validate); } @@ -601,7 +634,8 @@ public Bound withShardNameTemplate(String shardTemplate) { *

            Does not modify this object. */ public Bound withoutSharding() { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, 1, "", validate); + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, 1, + "", validate); } /** @@ -613,10 +647,40 @@ public Bound withoutSharding() { * @param the type of the elements of the input {@link PCollection} */ public Bound withCoder(Coder coder) { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, validate); } + /** + * Returns a transform for writing to text files that adds a header string to the files + * it writes. + * + *

            A {@code null} value will clear any previously configured header. + * + *

            Does not modify this object. + * + * @param header the string to be added as file header + */ + public Bound withHeader(String header) { + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, + shardTemplate, false); + } + + /** + * Returns a transform for writing to text files that adds a footer string to the files + * it writes. + * + *

            A {@code null} value will clear any previously configured footer. + * + *

            Does not modify this object. + * + * @param footer the string to be added as file footer + */ + public Bound withFooter(String footer) { + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, + shardTemplate, false); + } + /** * Returns a transform for writing to text files that's like this one but * that has GCS output path validation on pipeline creation disabled. @@ -628,7 +692,7 @@ public Bound withCoder(Coder coder) { *

            Does not modify this object. */ public Bound withoutValidation() { - return new Bound<>(name, filenamePrefix, filenameSuffix, coder, numShards, + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, false); } @@ -641,7 +705,8 @@ public PDone apply(PCollection input) { com.google.cloud.dataflow.sdk.io.Write.Bound write = com.google.cloud.dataflow.sdk.io.Write.to( - new TextSink<>(filenamePrefix, filenameSuffix, shardTemplate, coder)); + new TextSink<>(filenamePrefix, filenameSuffix, header, footer, shardTemplate, + coder)); if (getNumShards() > 0) { write = write.withNumShards(getNumShards()); } @@ -663,7 +728,11 @@ public void populateDisplayData(DisplayData.Builder builder) { .addIfNotDefault(DisplayData.item("validation", validate) .withLabel("Validation Enabled"), true) .addIfNotDefault(DisplayData.item("numShards", numShards) - .withLabel("Maximum Output Shards"), 0); + .withLabel("Maximum Output Shards"), 0) + .addIfNotNull(DisplayData.item("fileHeader", header) + .withLabel("File Header")) + .addIfNotNull(DisplayData.item("fileFooter", footer) + .withLabel("File Footer")); } /** @@ -698,6 +767,14 @@ public Coder getCoder() { return coder; } + public String getHeader() { + return header; + } + + public String getFooter() { + return footer; + } + public boolean needsValidation() { return validate; } @@ -976,17 +1053,22 @@ private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOExcep @VisibleForTesting static class TextSink extends FileBasedSink { private final Coder coder; + private final String header; + private final String footer; @VisibleForTesting TextSink( - String baseOutputFilename, String extension, String fileNameTemplate, Coder coder) { + String baseOutputFilename, String extension, String header, String footer, + String fileNameTemplate, Coder coder) { super(baseOutputFilename, extension, fileNameTemplate); this.coder = coder; + this.header = header; + this.footer = footer; } @Override public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { - return new TextWriteOperation<>(this, coder); + return new TextWriteOperation<>(this, coder, header, footer); } /** @@ -995,15 +1077,19 @@ public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOpt */ private static class TextWriteOperation extends FileBasedWriteOperation { private final Coder coder; + private final String header; + private final String footer; - private TextWriteOperation(TextSink sink, Coder coder) { + private TextWriteOperation(TextSink sink, Coder coder, String header, String footer) { super(sink); this.coder = coder; + this.header = header; + this.footer = footer; } @Override public FileBasedWriter createWriter(PipelineOptions options) throws Exception { - return new TextWriter<>(this, coder); + return new TextWriter<>(this, coder, header, footer); } } @@ -1014,19 +1100,49 @@ public FileBasedWriter createWriter(PipelineOptions options) throws Exception private static class TextWriter extends FileBasedWriter { private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); private final Coder coder; + private final String header; + private final String footer; private OutputStream out; public TextWriter(FileBasedWriteOperation writeOperation, Coder coder) { + this(writeOperation, coder, null, null); + } + + public TextWriter(FileBasedWriteOperation writeOperation, Coder coder, String header) { + this(writeOperation, coder, header, null); + } + + public TextWriter(FileBasedWriteOperation writeOperation, Coder coder, String header, + String footer) { super(writeOperation); + this.header = header; + this.footer = footer; this.mimeType = MimeTypes.TEXT; this.coder = coder; } + private void writeLine(String line) throws IOException { + if (line != null) { + out.write(line.getBytes(StandardCharsets.UTF_8)); + out.write(NEWLINE); + } + } + @Override protected void prepareWrite(WritableByteChannel channel) throws Exception { out = Channels.newOutputStream(channel); } + @Override + protected void writeHeader() throws Exception { + writeLine(header); + } + + @Override + protected void writeFooter() throws Exception { + writeLine(footer); + } + @Override public void write(T value) throws Exception { coder.encode(value, out, Context.OUTER); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index b3a43f67e5..aec4da0790 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -59,7 +59,12 @@ import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PDone; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.junit.Rule; @@ -86,9 +91,11 @@ import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.zip.GZIPOutputStream; +import javax.annotation.Nullable; /** * Tests for TextIO Read and Write transforms. @@ -96,6 +103,9 @@ @RunWith(JUnit4.class) @SuppressWarnings("unchecked") public class TextIOTest { + private static final String MY_HEADER = "myHeader"; + private static final String MY_FOOTER = "myFooter"; + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -228,10 +238,19 @@ public void testReadDisplayData() { } void runTestWrite(T[] elems, Coder coder) throws Exception { - runTestWrite(elems, coder, 1); + runTestWrite(elems, null, null, coder, 1); } void runTestWrite(T[] elems, Coder coder, int numShards) throws Exception { + runTestWrite(elems, null, null, coder, numShards); + } + + void runTestWrite(T[] elems, Coder coder, String header, String footer) throws Exception { + runTestWrite(elems, header, footer, coder, 1); + } + + void runTestWrite(T[] elems, String header, String footer, Coder coder, int numShards) + throws Exception { String outputName = "file.txt"; String baseFilename = tmpFolder.newFile(outputName).getPath(); @@ -252,16 +271,20 @@ void runTestWrite(T[] elems, Coder coder, int numShards) throws Exception } else { write = write.withNumShards(numShards).withShardNameTemplate(ShardNameTemplate.INDEX_OF_MAX); } + write = write.withHeader(header).withFooter(footer); input.apply(write); p.run(); - assertOutputFiles(elems, coder, numShards, tmpFolder, outputName, write.getShardNameTemplate()); + assertOutputFiles(elems, header, footer, coder, numShards, tmpFolder, outputName, + write.getShardNameTemplate()); } public static void assertOutputFiles( T[] elems, + final String header, + final String footer, Coder coder, int numShards, TemporaryFolder rootLocation, @@ -284,28 +307,71 @@ public static void assertOutputFiles( } } - List actual = new ArrayList<>(); + List> actual = new ArrayList<>(); for (File tmpFile : expectedFiles) { try (BufferedReader reader = new BufferedReader(new FileReader(tmpFile))) { + List currentFile = Lists.newArrayList(); for (;;) { String line = reader.readLine(); if (line == null) { break; } - actual.add(line); + currentFile.add(line); } + actual.add(currentFile); } } - String[] expected = new String[elems.length]; + LinkedList expectedElements = Lists.newLinkedList(); for (int i = 0; i < elems.length; i++) { T elem = elems[i]; byte[] encodedElem = CoderUtils.encodeToByteArray(coder, elem); String line = new String(encodedElem); - expected[i] = line; + expectedElements.add(line); } - assertThat(actual, containsInAnyOrder(expected)); + ArrayList actualElements = + Lists.newArrayList( + Iterables.concat( + FluentIterable + .from(actual) + .transform(removeHeaderAndFooter(header, footer)) + .toList())); + + assertThat(actualElements, containsInAnyOrder(expectedElements.toArray())); + + assertTrue(Iterables.all(actual, haveProperHeaderAndFooter(header, footer))); + } + + private static Function, List> removeHeaderAndFooter(final String header, + final String footer) { + return new Function, List>() { + @Nullable + @Override + public List apply(List lines) { + ArrayList newLines = Lists.newArrayList(lines); + if (header != null) { + newLines.remove(0); + } + if (footer != null) { + int last = newLines.size() - 1; + newLines.remove(last); + } + return newLines; + } + }; + } + + private static Predicate> haveProperHeaderAndFooter(final String header, + final String footer) { + return new Predicate>() { + @Override + public boolean apply(List fileLines) { + int last = fileLines.size() - 1; + return (header == null || fileLines.get(0).equals(header)) + && (footer == null || fileLines.get(last).equals(footer)); + } + }; } @Test @@ -354,6 +420,21 @@ public void testShardedWrite() throws Exception { runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), 5); } + @Test + public void testWriteWithHeader() throws Exception { + runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), MY_HEADER, null); + } + + @Test + public void testWriteWithFooter() throws Exception { + runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), null, MY_FOOTER); + } + + @Test + public void testWriteWithHeaderAndFooter() throws Exception { + runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), MY_HEADER, MY_FOOTER); + } + @Test public void testWriteDisplayData() { TextIO.Write.Bound write = TextIO.Write @@ -361,12 +442,16 @@ public void testWriteDisplayData() { .withSuffix("bar") .withShardNameTemplate("-SS-of-NN-") .withNumShards(100) + .withFooter("myFooter") + .withHeader("myHeader") .withoutValidation(); DisplayData displayData = DisplayData.from(write); assertThat(displayData, hasDisplayItem("filePrefix", "foo")); assertThat(displayData, hasDisplayItem("fileSuffix", "bar")); + assertThat(displayData, hasDisplayItem("fileHeader", "myHeader")); + assertThat(displayData, hasDisplayItem("fileFooter", "myFooter")); assertThat(displayData, hasDisplayItem("shardNameTemplate", "-SS-of-NN-")); assertThat(displayData, hasDisplayItem("numShards", 100)); assertThat(displayData, hasDisplayItem("validation", false)); From a61d459cd72340fe2d4d9b05983210e6b3bc3699 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Wed, 7 Sep 2016 16:57:26 -0700 Subject: [PATCH 555/751] Catch an underflow issue in DataflowPipelineJob's backoff code (#422) * DataflowPipelineJob: better tracking of cumulative sleep time * Test overflow correctly * fixup --- .../sdk/runners/DataflowPipelineJob.java | 26 +++++++---- .../sdk/runners/DataflowPipelineJobTest.java | 46 +++++++++++++++++++ 2 files changed, 63 insertions(+), 9 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java index c2aa39774b..4a68755565 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java @@ -255,19 +255,27 @@ State waitToFinish( } if (!hasError) { - // Reset the backoff. + // We can stop if the job is done. + if (state.isTerminal()) { + return state; + } + + // The job is not done, so we must keep polling. backoff.reset(); - // If duration is set, update the new cumulative sleep time to be the remaining - // part of the total input sleep duration. + + // If a total duration for all backoff has been set, update the new cumulative sleep time to + // be the remaining total backoff duration, stopping if we have already exceeded the + // allotted time. if (duration.isLongerThan(Duration.ZERO)) { long nanosConsumed = nanoClock.nanoTime() - startNanos; Duration consumed = Duration.millis((nanosConsumed + 999999) / 1000000); - backoff = - MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(duration.minus(consumed)).backoff(); - } - // Check if the job is done. - if (state.isTerminal()) { - return state; + Duration remaining = duration.minus(consumed); + if (remaining.isLongerThan(Duration.ZERO)) { + backoff = MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(remaining).backoff(); + } else { + // If there is no time remaining, don't bother backing off. + backoff = BackOff.STOP_BACKOFF; + } } } } while(BackOffUtils.next(sleeper, backoff)); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java index cc364ce34f..1d6ccc66ab 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java @@ -30,6 +30,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.api.client.util.NanoClock; +import com.google.api.client.util.Sleeper; import com.google.api.services.dataflow.Dataflow; import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Get; import com.google.api.services.dataflow.Dataflow.Projects.Jobs.GetMetrics; @@ -66,6 +68,7 @@ import java.io.IOException; import java.math.BigDecimal; import java.net.SocketTimeoutException; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; /** @@ -238,6 +241,30 @@ public void testWaitToFinishTimeFail() throws Exception { assertEquals(4L, timeDiff); } + @Test + public void testCumulativeTimeOverflow() throws Exception { + Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); + + Job statusResponse = new Job(); + statusResponse.setCurrentState("JOB_STATE_RUNNING"); + when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); + when(statusRequest.execute()).thenReturn(statusResponse); + + DataflowAggregatorTransforms dataflowAggregatorTransforms = + mock(DataflowAggregatorTransforms.class); + + FastNanoClockAndFuzzySleeper clock = new FastNanoClockAndFuzzySleeper(); + + DataflowPipelineJob job = new DataflowPipelineJob( + PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); + long startTime = clock.nanoTime(); + State state = job.waitToFinish(Duration.millis(4), null, clock, clock); + assertEquals(null, state); + long timeDiff = TimeUnit.NANOSECONDS.toMillis(clock.nanoTime() - startTime); + // Should only have slept for the 4 ms allowed. + assertThat(timeDiff, lessThanOrEqualTo(4L)); + } + @Test public void testGetStateReturnsServiceState() throws Exception { Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); @@ -599,4 +626,23 @@ public String getName() { String fullName, PTransform transform) { return AppliedPTransform.of(fullName, mock(PInput.class), mock(POutput.class), transform); } + + + private static class FastNanoClockAndFuzzySleeper implements NanoClock, Sleeper { + private long fastNanoTime; + + public FastNanoClockAndFuzzySleeper() { + fastNanoTime = NanoClock.SYSTEM.nanoTime(); + } + + @Override + public long nanoTime() { + return fastNanoTime; + } + + @Override + public void sleep(long millis) throws InterruptedException { + fastNanoTime += millis * 1000000L + ThreadLocalRandom.current().nextInt(500000); + } + } } From e4f4e785e3d922d9f8b3e989ed1435d79e9dae73 Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Wed, 7 Sep 2016 13:45:37 -0700 Subject: [PATCH 556/751] Add simple overload for WindowMatcher.isWindowedValue --- .../java/com/google/cloud/dataflow/sdk/WindowMatchers.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java index 9d7cfc8694..97b3756d3e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java @@ -46,6 +46,11 @@ public static Matcher> isWindowedValue( return new WindowedValueMatcher<>(valueMatcher, timestampMatcher, Matchers.anything()); } + public static Matcher> isWindowedValue( + Matcher valueMatcher) { + return new WindowedValueMatcher<>(valueMatcher, Matchers.anything(), Matchers.anything()); + } + public static Matcher> isSingleWindowedValue( T value, long timestamp, long windowStart, long windowEnd) { return WindowMatchers.isSingleWindowedValue( From 5696b86295973c5d5409d3ec3b0bcf4d97eb66b9 Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Wed, 7 Sep 2016 13:53:09 -0700 Subject: [PATCH 557/751] Add test for ReduceFnRunner GC time overflow --- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index 16ffea24f9..f3d841e322 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -17,6 +17,8 @@ package com.google.cloud.dataflow.sdk.util; import static com.google.cloud.dataflow.sdk.WindowMatchers.isSingleWindowedValue; +import static com.google.cloud.dataflow.sdk.WindowMatchers.isWindowedValue; + import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; @@ -49,6 +51,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; +import com.google.cloud.dataflow.sdk.transforms.windowing.Never; import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; @@ -57,6 +60,7 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; +import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.cloud.dataflow.sdk.values.TimestampedValue; @@ -76,6 +80,7 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -226,6 +231,70 @@ public void testOnElementCombiningDiscarding() throws Exception { tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); } + /** + * Tests that the garbage collection time for a fixed window does not overflow the end of time. + */ + @Test + public void testFixedWindowEndOfTimeGarbageCollection() throws Exception { + + Duration allowedLateness = Duration.standardDays(365); + Duration windowSize = Duration.millis(10); + WindowFn windowFn = FixedWindows.of(windowSize); + + // This timestamp falls into a window where the end of the window is before the end of the + // global window - the "end of time" - yet its expiration time is after. + final Instant elementTimestamp = + GlobalWindow.INSTANCE.maxTimestamp().minus(allowedLateness).plus(1); + + IntervalWindow window = Iterables.getOnlyElement( + windowFn.assignWindows( + windowFn.new AssignContext() { + @Override + public Object element() { + throw new UnsupportedOperationException(); + } + @Override + public Instant timestamp() { + return elementTimestamp; + } + + @Override + public Collection windows() { + throw new UnsupportedOperationException(); + } + })); + + assertTrue( + window.maxTimestamp().isBefore(GlobalWindow.INSTANCE.maxTimestamp())); + assertTrue( + window.maxTimestamp().plus(allowedLateness).isAfter(GlobalWindow.INSTANCE.maxTimestamp())); + + // Test basic execution of a trigger using a non-combining window set and accumulating mode. + ReduceFnTester tester = + ReduceFnTester.combining( + windowFn, + AfterWatermark.pastEndOfWindow().withLateFirings(Never.ever()).buildTrigger(), + AccumulationMode.DISCARDING_FIRED_PANES, + new Sum.SumIntegerFn().asKeyedFn(), + VarIntCoder.of(), + allowedLateness); + + tester.injectElements(TimestampedValue.of(13, elementTimestamp)); + + // Should fire ON_TIME pane and there will be a checkState that the cleanup time + // is prior to timestamp max value + tester.advanceInputWatermark(window.maxTimestamp()); + + // Nothing in the ON_TIME pane (not governed by triggers, but by ReduceFnRunner) + assertThat(tester.extractOutput(), emptyIterable()); + + tester.injectElements(TimestampedValue.of(42, elementTimestamp)); + + // Now the final pane should fire, demonstrating that the GC time was truncated + tester.advanceInputWatermark(GlobalWindow.INSTANCE.maxTimestamp()); + assertThat(tester.extractOutput(), contains(isWindowedValue(equalTo(55)))); + } + @Test public void testOnElementCombiningAccumulating() throws Exception { // Test basic execution of a trigger using a non-combining window set and accumulating mode. From 2dd5fdb33f503276bebdf98a0d5953b616c6152d Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Wed, 7 Sep 2016 13:53:49 -0700 Subject: [PATCH 558/751] Fix overflow in ReduceFnRunner garbage collection times --- .../dataflow/sdk/util/ReduceFnRunner.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 007a1baa7f..34042a359b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -933,16 +933,21 @@ private void cancelEndOfWindowAndGarbageCollectionTimers( } /** - * Return when {@code window} should be garbage collected. If the window is the GlobalWindow, - * that will be the end of the window. Otherwise, add the allowed lateness to the end of - * the window. + * Return when {@code window} should be garbage collected. If the window's expiration time is on + * or after the end of the global window, it will be truncated to the end of the global window. */ private Instant garbageCollectionTime(W window) { - Instant maxTimestamp = window.maxTimestamp(); - if (maxTimestamp.isBefore(GlobalWindow.INSTANCE.maxTimestamp())) { - return maxTimestamp.plus(windowingStrategy.getAllowedLateness()); + + // If the end of the window + allowed lateness is beyond the "end of time" aka the end of the + // global window, then we truncate it. The conditional is phrased like it is because the + // addition of EOW + allowed lateness might even overflow the maximum allowed Instant + if (GlobalWindow.INSTANCE + .maxTimestamp() + .minus(windowingStrategy.getAllowedLateness()) + .isBefore(window.maxTimestamp())) { + return GlobalWindow.INSTANCE.maxTimestamp(); } else { - return maxTimestamp; + return window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()); } } From 871e96a57169b82de6ff5ce65dfca55b499d64c5 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Wed, 7 Sep 2016 16:46:30 -0700 Subject: [PATCH 559/751] fixup types in ReduceFnRunnerTest --- .../com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java index f3d841e322..af154afb51 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java @@ -273,7 +273,8 @@ public Collection windows() { ReduceFnTester tester = ReduceFnTester.combining( windowFn, - AfterWatermark.pastEndOfWindow().withLateFirings(Never.ever()).buildTrigger(), + AfterWatermark.pastEndOfWindow() + .withLateFirings(Never.ever()).buildTrigger(), AccumulationMode.DISCARDING_FIRED_PANES, new Sum.SumIntegerFn().asKeyedFn(), VarIntCoder.of(), From 391f44af4ee1c2e25b6a0a9050f2a13d15620e12 Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Thu, 8 Sep 2016 10:44:11 -0700 Subject: [PATCH 560/751] Backport Apache Beam PR/934 --- .../google/cloud/dataflow/sdk/io/TextIO.java | 89 +++++++++---------- .../cloud/dataflow/sdk/io/TextIOTest.java | 7 +- 2 files changed, 46 insertions(+), 50 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index a9f20c1106..13b552abd7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -36,7 +36,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.protobuf.ByteString; - import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; @@ -47,7 +46,6 @@ import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import java.util.regex.Pattern; - import javax.annotation.Nullable; /** @@ -313,20 +311,20 @@ public PCollection apply(PInput input) { switch(compressionType) { case UNCOMPRESSED: read = com.google.cloud.dataflow.sdk.io.Read.from( - new TextSource(filepattern, coder)); + new TextSource<>(filepattern, coder)); break; case AUTO: read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource(filepattern, coder))); + CompressedSource.from(new TextSource<>(filepattern, coder))); break; case BZIP2: read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource(filepattern, coder)) + CompressedSource.from(new TextSource<>(filepattern, coder)) .withDecompression(CompressedSource.CompressionMode.BZIP2)); break; case GZIP: read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource(filepattern, coder)) + CompressedSource.from(new TextSource<>(filepattern, coder)) .withDecompression(CompressedSource.CompressionMode.GZIP)); break; default: @@ -473,25 +471,25 @@ public static Bound withoutValidation() { /** * Returns a transform for writing to text files that adds a header string to the files - * it writes. + * it writes. Note that a newline character will be added after the header. * *

            A {@code null} value will clear any previously configured header. * * @param header the string to be added as file header */ - public static Bound withHeader(String header) { + public static Bound withHeader(@Nullable String header) { return new Bound<>(DEFAULT_TEXT_CODER).withHeader(header); } /** * Returns a transform for writing to text files that adds a footer string to the files - * it writes. + * it writes. Note that a newline character will be added after the header. * *

            A {@code null} value will clear any previously configured footer. * * @param footer the string to be added as file footer */ - public static Bound withFooter(String footer) { + public static Bound withFooter(@Nullable String footer) { return new Bound<>(DEFAULT_TEXT_CODER).withFooter(footer); } @@ -513,10 +511,10 @@ public static class Bound extends PTransform, PDone> { private final String filenameSuffix; /** An optional header to add to each file. */ - private final String header; + @Nullable private final String header; /** An optional footer to add to each file. */ - private final String footer; + @Nullable private final String footer; /** The Coder to use to decode each line. */ private final Coder coder; @@ -534,9 +532,9 @@ public static class Bound extends PTransform, PDone> { this(null, null, "", null, null, coder, 0, DEFAULT_SHARD_TEMPLATE, true); } - private Bound(String name, String filenamePrefix, String filenameSuffix, String header, - String footer, Coder coder, int numShards, String shardTemplate, - boolean validate) { + private Bound(String name, String filenamePrefix, String filenameSuffix, + @Nullable String header, @Nullable String footer, Coder coder, int numShards, + String shardTemplate, boolean validate) { super(name); this.header = header; this.footer = footer; @@ -653,7 +651,7 @@ public Bound withCoder(Coder coder) { /** * Returns a transform for writing to text files that adds a header string to the files - * it writes. + * it writes. Note that a newline character will be added after the header. * *

            A {@code null} value will clear any previously configured header. * @@ -661,14 +659,14 @@ public Bound withCoder(Coder coder) { * * @param header the string to be added as file header */ - public Bound withHeader(String header) { + public Bound withHeader(@Nullable String header) { return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, false); } /** * Returns a transform for writing to text files that adds a footer string to the files - * it writes. + * it writes. Note that a newline character will be added after the header. * *

            A {@code null} value will clear any previously configured footer. * @@ -676,7 +674,7 @@ public Bound withHeader(String header) { * * @param footer the string to be added as file footer */ - public Bound withFooter(String footer) { + public Bound withFooter(@Nullable String footer) { return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, false); } @@ -767,10 +765,12 @@ public Coder getCoder() { return coder; } + @Nullable public String getHeader() { return header; } + @Nullable public String getFooter() { return footer; } @@ -835,7 +835,7 @@ private static void validateOutputComponent(String partialFilePattern) { private TextIO() {} /** - * A {@link FileBasedSource} which can decode records delimited by new line characters. + * A {@link FileBasedSource} which can decode records delimited by newline characters. * *

            This source splits the data into records using {@code UTF-8} {@code \n}, {@code \r}, or * {@code \r\n} as the delimiter. This source is not strict and supports decoding the last record @@ -883,7 +883,7 @@ public Coder getDefaultOutputCoder() { /** * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader FileBasedReader} - * which can decode records delimited by new line characters. + * which can decode records delimited by newline characters. * * See {@link TextSource} for further details. */ @@ -1046,19 +1046,20 @@ private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOExcep } /** - * A {@link FileBasedSink} for text files. Produces text files with the new line separator + * A {@link FileBasedSink} for text files. Produces text files with the newline separator * {@code '\n'} represented in {@code UTF-8} format as the record separator. * Each record (including the last) is terminated. */ @VisibleForTesting static class TextSink extends FileBasedSink { private final Coder coder; - private final String header; - private final String footer; + @Nullable private final String header; + @Nullable private final String footer; @VisibleForTesting TextSink( - String baseOutputFilename, String extension, String header, String footer, + String baseOutputFilename, String extension, + @Nullable String header, @Nullable String footer, String fileNameTemplate, Coder coder) { super(baseOutputFilename, extension, fileNameTemplate); this.coder = coder; @@ -1077,10 +1078,11 @@ public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOpt */ private static class TextWriteOperation extends FileBasedWriteOperation { private final Coder coder; - private final String header; - private final String footer; + @Nullable private final String header; + @Nullable private final String footer; - private TextWriteOperation(TextSink sink, Coder coder, String header, String footer) { + private TextWriteOperation(TextSink sink, Coder coder, + @Nullable String header, @Nullable String footer) { super(sink); this.coder = coder; this.header = header; @@ -1100,20 +1102,12 @@ public FileBasedWriter createWriter(PipelineOptions options) throws Exception private static class TextWriter extends FileBasedWriter { private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); private final Coder coder; - private final String header; - private final String footer; + @Nullable private final String header; + @Nullable private final String footer; private OutputStream out; - public TextWriter(FileBasedWriteOperation writeOperation, Coder coder) { - this(writeOperation, coder, null, null); - } - - public TextWriter(FileBasedWriteOperation writeOperation, Coder coder, String header) { - this(writeOperation, coder, header, null); - } - - public TextWriter(FileBasedWriteOperation writeOperation, Coder coder, String header, - String footer) { + public TextWriter(FileBasedWriteOperation writeOperation, Coder coder, + @Nullable String header, @Nullable String footer) { super(writeOperation); this.header = header; this.footer = footer; @@ -1121,9 +1115,12 @@ public TextWriter(FileBasedWriteOperation writeOperation, Coder coder, Str this.coder = coder; } - private void writeLine(String line) throws IOException { - if (line != null) { - out.write(line.getBytes(StandardCharsets.UTF_8)); + /** + * Writes {@code value} followed by a newline if {@code value} is not null. + */ + private void writeIfNotNull(@Nullable String value) throws IOException { + if (value != null) { + out.write(value.getBytes(StandardCharsets.UTF_8)); out.write(NEWLINE); } } @@ -1133,14 +1130,14 @@ protected void prepareWrite(WritableByteChannel channel) throws Exception { out = Channels.newOutputStream(channel); } - @Override + @Override protected void writeHeader() throws Exception { - writeLine(header); + writeIfNotNull(header); } @Override protected void writeFooter() throws Exception { - writeLine(footer); + writeIfNotNull(footer); } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index aec4da0790..0ba2582a94 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -91,7 +91,6 @@ import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; -import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.zip.GZIPOutputStream; @@ -310,7 +309,7 @@ public static void assertOutputFiles( List> actual = new ArrayList<>(); for (File tmpFile : expectedFiles) { try (BufferedReader reader = new BufferedReader(new FileReader(tmpFile))) { - List currentFile = Lists.newArrayList(); + List currentFile = new ArrayList<>(); for (;;) { String line = reader.readLine(); if (line == null) { @@ -322,7 +321,7 @@ public static void assertOutputFiles( } } - LinkedList expectedElements = Lists.newLinkedList(); + List expectedElements = new ArrayList<>(elems.length); for (int i = 0; i < elems.length; i++) { T elem = elems[i]; byte[] encodedElem = CoderUtils.encodeToByteArray(coder, elem); @@ -330,7 +329,7 @@ public static void assertOutputFiles( expectedElements.add(line); } - ArrayList actualElements = + List actualElements = Lists.newArrayList( Iterables.concat( FluentIterable From c06ad869f941833fadb30157aa02050692473cba Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Thu, 8 Sep 2016 10:47:11 -0700 Subject: [PATCH 561/751] !fixup Undo IDE auto save rule. --- .../java/com/google/cloud/dataflow/sdk/io/TextIO.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 13b552abd7..1444ed4ffa 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -311,20 +311,20 @@ public PCollection apply(PInput input) { switch(compressionType) { case UNCOMPRESSED: read = com.google.cloud.dataflow.sdk.io.Read.from( - new TextSource<>(filepattern, coder)); + new TextSource(filepattern, coder)); break; case AUTO: read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource<>(filepattern, coder))); + CompressedSource.from(new TextSource(filepattern, coder))); break; case BZIP2: read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource<>(filepattern, coder)) + CompressedSource.from(new TextSource(filepattern, coder)) .withDecompression(CompressedSource.CompressionMode.BZIP2)); break; case GZIP: read = com.google.cloud.dataflow.sdk.io.Read.from( - CompressedSource.from(new TextSource<>(filepattern, coder)) + CompressedSource.from(new TextSource(filepattern, coder)) .withDecompression(CompressedSource.CompressionMode.GZIP)); break; default: From 57db85721dcd59e409a93a99f771369992730b1b Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Thu, 8 Sep 2016 13:32:39 -0700 Subject: [PATCH 562/751] !fixup Whitespace --- sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 1444ed4ffa..0fbac40bdb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -1132,7 +1132,7 @@ protected void prepareWrite(WritableByteChannel channel) throws Exception { @Override protected void writeHeader() throws Exception { - writeIfNotNull(header); + writeIfNotNull(header); } @Override From 88e68fec016dffaa42ed6d8523f2c346fb861c0d Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 8 Sep 2016 15:54:08 -0700 Subject: [PATCH 563/751] Upgrade the worker container version --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f88790dfc5..d54927dddd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -222,9 +222,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.6.1"; + = "dataflow.gcr.io/v1beta3/java-batch:1.7.0"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.6.1"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.7.0"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 261fdf92cea4eb0f7be7e3e93c58abc8dc44836e Mon Sep 17 00:00:00 2001 From: Pei He Date: Thu, 8 Sep 2016 18:16:14 -0700 Subject: [PATCH 564/751] add flag to control whether to enable streaming unbounded read --- .../sdk/runners/DataflowPipelineRunner.java | 10 ++++++- .../runners/DataflowPipelineRunnerTest.java | 29 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index f88790dfc5..81f4fc5b9f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -361,7 +361,15 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(View.AsList.class, StreamingViewAsList.class); builder.put(View.AsIterable.class, StreamingViewAsIterable.class); builder.put(Read.Unbounded.class, StreamingUnboundedRead.class); - builder.put(Read.Bounded.class, StreamingBoundedRead.class); + if (options.getExperiments() == null + || !options.getExperiments().contains("enable_streaming_bounded_read")) { + builder.put(Read.Bounded.class, UnsupportedIO.class); + builder.put(AvroIO.Read.Bound.class, UnsupportedIO.class); + builder.put(BigQueryIO.Read.Bound.class, UnsupportedIO.class); + builder.put(TextIO.Read.Bound.class, UnsupportedIO.class); + } else { + builder.put(Read.Bounded.class, StreamingBoundedRead.class); + } builder.put(AvroIO.Write.Bound.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); // In streaming mode must use either the custom Pubsub unbounded source/sink or diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 1dac6c4cf2..7ad99dbef7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -46,6 +46,8 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; +import com.google.cloud.dataflow.sdk.io.AvroSource; +import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; @@ -928,6 +930,33 @@ private void testUnsupportedSource(PTransform source, String name, bo p.run(); } + @Test + public void testBoundedSourceUnsupportedInStreaming() throws Exception { + testUnsupportedSource( + AvroSource.readFromFileWithClass("foo", String.class), "Read.Bounded", true); + } + + @Test + public void testBigQueryIOSourceUnsupportedInStreaming() throws Exception { + testUnsupportedSource( + BigQueryIO.Read.from("project:bar.baz").withoutValidation(), "BigQueryIO.Read", true); + } + + @Test + public void testAvroIOSourceUnsupportedInStreaming() throws Exception { + testUnsupportedSource(AvroIO.Read.from("foo"), "AvroIO.Read", true); + } + + @Test + public void testTextIOSourceUnsupportedInStreaming() throws Exception { + testUnsupportedSource(TextIO.Read.from("foo"), "TextIO.Read", true); + } + + @Test + public void testReadBoundedSourceUnsupportedInStreaming() throws Exception { + testUnsupportedSource(Read.from(AvroSource.from("/tmp/test")), "Read.Bounded", true); + } + @Test public void testReadUnboundedUnsupportedInBatch() throws Exception { testUnsupportedSource(Read.from(new TestCountingSource(1)), "Read.Unbounded", false); From bf6fed38ecab7d9d603d2e06113221bd31f4a355 Mon Sep 17 00:00:00 2001 From: Pei He Date: Fri, 9 Sep 2016 12:38:37 -0700 Subject: [PATCH 565/751] Revert PR-427 to re-enable streaming bounded read --- .../sdk/runners/DataflowPipelineRunner.java | 10 +------ .../runners/DataflowPipelineRunnerTest.java | 29 ------------------- 2 files changed, 1 insertion(+), 38 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index d77fc863dc..d54927dddd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -361,15 +361,7 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { builder.put(View.AsList.class, StreamingViewAsList.class); builder.put(View.AsIterable.class, StreamingViewAsIterable.class); builder.put(Read.Unbounded.class, StreamingUnboundedRead.class); - if (options.getExperiments() == null - || !options.getExperiments().contains("enable_streaming_bounded_read")) { - builder.put(Read.Bounded.class, UnsupportedIO.class); - builder.put(AvroIO.Read.Bound.class, UnsupportedIO.class); - builder.put(BigQueryIO.Read.Bound.class, UnsupportedIO.class); - builder.put(TextIO.Read.Bound.class, UnsupportedIO.class); - } else { - builder.put(Read.Bounded.class, StreamingBoundedRead.class); - } + builder.put(Read.Bounded.class, StreamingBoundedRead.class); builder.put(AvroIO.Write.Bound.class, UnsupportedIO.class); builder.put(Window.Bound.class, AssignWindows.class); // In streaming mode must use either the custom Pubsub unbounded source/sink or diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 7ad99dbef7..1dac6c4cf2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -46,8 +46,6 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.AvroSource; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; @@ -930,33 +928,6 @@ private void testUnsupportedSource(PTransform source, String name, bo p.run(); } - @Test - public void testBoundedSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource( - AvroSource.readFromFileWithClass("foo", String.class), "Read.Bounded", true); - } - - @Test - public void testBigQueryIOSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource( - BigQueryIO.Read.from("project:bar.baz").withoutValidation(), "BigQueryIO.Read", true); - } - - @Test - public void testAvroIOSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource(AvroIO.Read.from("foo"), "AvroIO.Read", true); - } - - @Test - public void testTextIOSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource(TextIO.Read.from("foo"), "TextIO.Read", true); - } - - @Test - public void testReadBoundedSourceUnsupportedInStreaming() throws Exception { - testUnsupportedSource(Read.from(AvroSource.from("/tmp/test")), "Read.Bounded", true); - } - @Test public void testReadUnboundedUnsupportedInBatch() throws Exception { testUnsupportedSource(Read.from(new TestCountingSource(1)), "Read.Unbounded", false); From 111a26af7b9235aaf583e8d0161f754e581bc9a3 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Mon, 12 Sep 2016 09:50:43 -0700 Subject: [PATCH 566/751] Remove timeout in JAXBCoderTest The infrastructure should kill the test if the await does not return. --- .../cloud/dataflow/sdk/coders/JAXBCoderTest.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java index 56b91680f5..e75c69c79c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java @@ -17,7 +17,6 @@ package com.google.cloud.dataflow.sdk.coders; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import com.google.cloud.dataflow.sdk.testing.CoderProperties; import com.google.cloud.dataflow.sdk.util.CoderUtils; @@ -30,7 +29,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.xml.bind.annotation.XmlRootElement; @@ -106,7 +104,7 @@ public void testEncodeDecodeAfterClone() throws Exception { @Test public void testEncodeDecodeMultithreaded() throws Throwable { final JAXBCoder coder = JAXBCoder.of(TestType.class); - int numThreads = 1000; + int numThreads = 100; final CountDownLatch ready = new CountDownLatch(numThreads); final CountDownLatch start = new CountDownLatch(1); @@ -142,11 +140,11 @@ public void run() { ready.await(); start.countDown(); - if (!done.await(10L, TimeUnit.SECONDS)) { - fail("Should be able to clone " + numThreads + " elements in 10 seconds"); - } - if (thrown.get() != null) { - throw thrown.get(); + done.await(); + Throwable actuallyThrown = thrown.get(); + + if (actuallyThrown != null) { + throw actuallyThrown; } } From 5a19c99b2f76f49c8c19a54ac976db7b381d63f4 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 12 Sep 2016 19:02:14 -0700 Subject: [PATCH 567/751] SDK: suppress expected deprecation warnings --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 2 ++ .../com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java | 1 + .../java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java | 1 + .../com/google/cloud/dataflow/sdk/io/CountingSourceTest.java | 1 + .../java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java | 1 + .../cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java | 2 ++ .../sdk/util/IntervalBoundedExponentialBackOffTest.java | 1 + 7 files changed, 9 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index d54927dddd..bec4f134f9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -2359,6 +2359,7 @@ public void translate( translateTyped(transform, context); } + @SuppressWarnings("deprecation") // uses internal deprecated code deliberately. private void translateTyped( PubsubIO.Read.Bound transform, TranslationContext context) { @@ -2435,6 +2436,7 @@ public void translate( translateTyped(transform, context); } + @SuppressWarnings("deprecation") // uses internal deprecated code deliberately. private void translateTyped( StreamingPubsubIOWrite transform, TranslationContext context) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java index 8ced1dc9d0..8c047d3418 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java @@ -37,6 +37,7 @@ * Test case for {@link EntityCoder}. */ @RunWith(JUnit4.class) +@SuppressWarnings("deprecation") // test of deprecated code. public class EntityCoderTest { private static final Coder TEST_CODER = EntityCoder.of(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java index e8be07f85b..44fa680921 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java @@ -95,6 +95,7 @@ private String generateTestFile(String filename, List elems, SyncBehavior String path = tmpFile.toString(); FileOutputStream os = new FileOutputStream(tmpFile); + @SuppressWarnings("deprecation") // test uses internal AvroCoder code. DatumWriter datumWriter = coder.createDatumWriter(); try (DataFileWriter writer = new DataFileWriter<>(datumWriter)) { writer.setCodec(CodecFactory.fromString(codec)); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java index 3051535d5d..3cce395cc6 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java @@ -57,6 +57,7 @@ * Tests of {@link CountingSource}. */ @RunWith(JUnit4.class) +@SuppressWarnings("deprecation") // test of deprecated code. public class CountingSourceTest { public static void addCountingAsserts(PCollection input, long numElements) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java index f1ae3cc70f..46c053757f 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java @@ -91,6 +91,7 @@ * Tests for {@link DatastoreIO}. */ @RunWith(JUnit4.class) +@SuppressWarnings("deprecation") // test of deprecated code. public class DatastoreIOTest { private static final String HOST = "testHost"; private static final String DATASET = "testDataset"; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java index 6524e144f8..8d09844d6d 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java @@ -160,6 +160,7 @@ public void testTextIOWriteWithLimitedNumberOfShards() throws Exception { } @Test + @SuppressWarnings("deprecation") // test uses internal AvroCoder features. public void testAvroIOWriteWithDefaultShardingStrategy() throws Exception { String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "output"); Pipeline p = DirectPipeline.createForTest(); @@ -181,6 +182,7 @@ public void testAvroIOWriteWithDefaultShardingStrategy() throws Exception { } @Test + @SuppressWarnings("deprecation") // test uses internal AvroCoder features. public void testAvroIOWriteWithLimitedNumberOfShards() throws Exception { final int numShards = 3; String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "shardedOutput"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java index 8ad7aa6592..3853705b7c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java @@ -32,6 +32,7 @@ /** Unit tests for {@link IntervalBoundedExponentialBackOff}. */ @RunWith(JUnit4.class) +@SuppressWarnings("deprecation") // test of deprecated code. public class IntervalBoundedExponentialBackOffTest { @Rule public ExpectedException exception = ExpectedException.none(); From b4c8dec24610fedab84ba03504dee7dd37a61a83 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 13 Sep 2016 12:04:49 -0700 Subject: [PATCH 568/751] Version management: update development to version 1.8.0-SNAPSHOT --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index b6876b61eb..d93a81c36f 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.8.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 7f6dfbc046..2bea58b4e1 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.8.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 828f6f5c1d..c42cd5a244 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.8.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index 9009eccd76..b4635e86ba 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.7.0-SNAPSHOT + 1.8.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index d9c4727601..b3302bc1d2 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.7.0-SNAPSHOT + 1.8.0-SNAPSHOT com.google.cloud.dataflow From 657ce1ff85caf44f7cf16d67b973055657980c2e Mon Sep 17 00:00:00 2001 From: pjesa Date: Mon, 19 Sep 2016 09:36:49 -0700 Subject: [PATCH 569/751] Deprecate TeardownPolicy for Dataflow service We are moving towards supporting only TEARDOWN_ALWAYS. --- .../sdk/options/DataflowPipelineWorkerPoolOptions.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java index 6200cb4ae6..b0d30957ad 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java @@ -189,7 +189,10 @@ public String create(PipelineOptions options) { /** * The policy for tearing down the workers spun up by the service. + * @deprecated + * Dataflow Service will only support TEARDOWN_ALWAYS policy in the future. */ + @Deprecated public enum TeardownPolicy { /** * All VMs created for a Dataflow job are deleted when the job finishes, regardless of whether From a9d586bbdf21791165e0dd24bf201757d7a1290a Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Mon, 19 Sep 2016 16:54:28 -0700 Subject: [PATCH 570/751] checkstyle: prohibit API client repackaged Guava (#430) Apparently the IllegalImport check only blocks packages, so we had to move to Regexp to get individual classes. --- checkstyle.xml | 8 ++++++++ .../src/main/java/DebuggingWordCount.java | 2 +- .../com/google/cloud/dataflow/sdk/util/CloudObject.java | 2 +- .../google/cloud/dataflow/sdk/util/OutputReference.java | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 920da8823c..4d387f82dc 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -133,6 +133,14 @@ page at http://checkstyle.sourceforge.net/config.html --> + + + + + diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java index 299e3b7fe2..d0fe12611c 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java @@ -151,7 +151,7 @@ public void processElement(ProcessContext c) { } } } - + /** * Options supported by {@link DebuggingWordCount}. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java index 8c704bf6d9..26645aa773 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java @@ -16,7 +16,7 @@ package com.google.cloud.dataflow.sdk.util; -import static com.google.api.client.util.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Key; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java index 096c996528..baa505b923 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java @@ -16,7 +16,7 @@ package com.google.cloud.dataflow.sdk.util; -import static com.google.api.client.util.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Key; From 8b87f47d2e047767c426308510782fe227f5df6d Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 20 Sep 2016 09:18:19 -0700 Subject: [PATCH 571/751] Add Flatten with Duplicate Inputs Test This test demonstrates that if a Flatten.PCollections transform has the same PCollectionList in its input multiple times, it will duplicate the input PCollection for each time it occurs within the list. --- .../dataflow/sdk/transforms/FlattenTest.java | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java index 0c9d3315db..069ee72fad 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java @@ -40,7 +40,7 @@ import com.google.cloud.dataflow.sdk.values.PCollectionList; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.common.collect.ImmutableSet; - +import com.google.common.collect.Iterables; import org.joda.time.Duration; import org.junit.Assert; import org.junit.Rule; @@ -49,7 +49,6 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; - import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; @@ -115,6 +114,26 @@ public void testFlattenPCollectionListEmpty() { p.run(); } + @Test + @Category(RunnableOnService.class) + public void testFlattenInputMultipleCopies() { + Pipeline p = TestPipeline.create(); + + PCollection lines = p.apply("mkLines", Create.of(LINES)); + PCollection lines2 = p.apply("mkOtherLines", Create.of(LINES2)); + + PCollection flattened = PCollectionList.of(lines) + .and(lines2) + .and(lines) + .and(lines) + .apply(Flatten.pCollections()); + + DataflowAssert.that(flattened) + .containsInAnyOrder(Iterables.concat(LINES, LINES, LINES, LINES2)); + + p.run(); + } + @Test @Category(RunnableOnService.class) public void testEmptyFlattenAsSideInput() { From 8b1eafac3da9682e4c689459c79ef47d89384eb5 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Wed, 21 Sep 2016 10:27:28 -0700 Subject: [PATCH 572/751] checkstyle.xml: blacklist imports of two shaded dependencies (#437) --- checkstyle.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/checkstyle.xml b/checkstyle.xml index 4d387f82dc..64ea8635e9 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -130,7 +130,7 @@ page at http://checkstyle.sourceforge.net/config.html --> - + + + + + + + diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java index 887d0adf7e..2ffff2bdf7 100644 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java +++ b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.contrib.firebase.io; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.contrib.firebase.events.ChildAdded; import com.google.cloud.dataflow.contrib.firebase.events.ChildChanged; import com.google.cloud.dataflow.contrib.firebase.events.ChildMoved; @@ -33,8 +35,6 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Preconditions; - import com.fasterxml.jackson.databind.ObjectWriter; import com.firebase.client.AuthData; import com.firebase.client.ChildEventListener; @@ -389,7 +389,7 @@ public void validate() { Thread.currentThread().interrupt(); throw new RuntimeException("Thread interrupted while waiting for authentication to complete", e); } - Preconditions.checkNotNull(result, "If result is null, authenticators is "); + checkNotNull(result, "If result is null, authenticators is "); } @Override diff --git a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java index afe6c337b5..e8981d2d6a 100644 --- a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java +++ b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java @@ -16,6 +16,9 @@ package com.google.cloud.dataflow.contrib.hadoop; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; @@ -24,7 +27,6 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.values.KV; import com.google.common.base.Function; -import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; @@ -164,14 +166,10 @@ public Class getValueClass() { @Override public void validate() { - Preconditions.checkNotNull(filepattern, - "need to set the filepattern of a HadoopFileSource"); - Preconditions.checkNotNull(formatClass, - "need to set the format class of a HadoopFileSource"); - Preconditions.checkNotNull(keyClass, - "need to set the key class of a HadoopFileSource"); - Preconditions.checkNotNull(valueClass, - "need to set the value class of a HadoopFileSource"); + checkNotNull(filepattern, "need to set the filepattern of a HadoopFileSource"); + checkNotNull(formatClass, "need to set the format class of a HadoopFileSource"); + checkNotNull(keyClass, "need to set the key class of a HadoopFileSource"); + checkNotNull(valueClass, "need to set the value class of a HadoopFileSource"); } @Override @@ -466,8 +464,7 @@ public SerializableSplit() { } public SerializableSplit(InputSplit split) { - Preconditions.checkArgument(split instanceof Writable, "Split is not writable: " - + split); + checkArgument(split instanceof Writable, "Split is not writable: %s", split); this.split = split; } diff --git a/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java b/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java index 81d8a7f9af..465a1ebc6a 100644 --- a/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java +++ b/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java @@ -16,6 +16,8 @@ package com.google.cloud.dataflow.contrib.joinlibrary; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.ParDo; @@ -25,7 +27,6 @@ import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Preconditions; /** * Utility class with different versions of joins. All methods join two collections of @@ -45,8 +46,8 @@ public class Join { */ public static PCollection>> innerJoin( final PCollection> leftCollection, final PCollection> rightCollection) { - Preconditions.checkNotNull(leftCollection); - Preconditions.checkNotNull(rightCollection); + checkNotNull(leftCollection); + checkNotNull(rightCollection); final TupleTag v1Tuple = new TupleTag<>(); final TupleTag v2Tuple = new TupleTag<>(); @@ -93,9 +94,9 @@ public static PCollection>> leftOuterJoin( final PCollection> leftCollection, final PCollection> rightCollection, final V2 nullValue) { - Preconditions.checkNotNull(leftCollection); - Preconditions.checkNotNull(rightCollection); - Preconditions.checkNotNull(nullValue); + checkNotNull(leftCollection); + checkNotNull(rightCollection); + checkNotNull(nullValue); final TupleTag v1Tuple = new TupleTag<>(); final TupleTag v2Tuple = new TupleTag<>(); @@ -146,9 +147,9 @@ public static PCollection>> rightOuterJoin( final PCollection> leftCollection, final PCollection> rightCollection, final V1 nullValue) { - Preconditions.checkNotNull(leftCollection); - Preconditions.checkNotNull(rightCollection); - Preconditions.checkNotNull(nullValue); + checkNotNull(leftCollection); + checkNotNull(rightCollection); + checkNotNull(nullValue); final TupleTag v1Tuple = new TupleTag<>(); final TupleTag v2Tuple = new TupleTag<>(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index 3041b95547..24590f55fd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -16,17 +16,17 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.cloud.dataflow.sdk.annotations.Experimental; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; - import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; - import java.io.IOException; import java.io.PushbackInputStream; import java.io.Serializable; @@ -35,7 +35,6 @@ import java.nio.channels.ReadableByteChannel; import java.util.NoSuchElementException; import java.util.zip.GZIPInputStream; - import javax.annotation.concurrent.GuardedBy; /** @@ -253,7 +252,7 @@ private CompressedSource(FileBasedSource sourceDelegate, this.sourceDelegate = sourceDelegate; this.channelFactory = channelFactory; try { - Preconditions.checkArgument( + checkArgument( isSplittable() || startOffset == 0, "CompressedSources must start reading at offset 0. Requested offset: " + startOffset); } catch (Exception e) { @@ -268,9 +267,9 @@ private CompressedSource(FileBasedSource sourceDelegate, @Override public void validate() { super.validate(); - Preconditions.checkNotNull(sourceDelegate); + checkNotNull(sourceDelegate); sourceDelegate.validate(); - Preconditions.checkNotNull(channelFactory); + checkNotNull(channelFactory); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java index 78659122de..5e47eeaa62 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java @@ -14,22 +14,22 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; + import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; - import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import java.io.IOException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SeekableByteChannel; @@ -133,18 +133,18 @@ public final Mode getMode() { @Override public final FileBasedSource createSourceForSubrange(long start, long end) { - Preconditions.checkArgument(mode != Mode.FILEPATTERN, + checkArgument(mode != Mode.FILEPATTERN, "Cannot split a file pattern based source based on positions"); - Preconditions.checkArgument(start >= getStartOffset(), "Start offset value " + start + checkArgument(start >= getStartOffset(), "Start offset value " + start + " of the subrange cannot be smaller than the start offset value " + getStartOffset() + " of the parent source"); - Preconditions.checkArgument(end <= getEndOffset(), "End offset value " + end + checkArgument(end <= getEndOffset(), "End offset value " + end + " of the subrange cannot be larger than the end offset value " + getEndOffset() + " of the parent source"); FileBasedSource source = createForSubrangeOfFile(fileOrPatternSpec, start, end); if (start > 0 || end != Long.MAX_VALUE) { - Preconditions.checkArgument(source.getMode() == Mode.SINGLE_FILE_OR_SUBRANGE, + checkArgument(source.getMode() == Mode.SINGLE_FILE_OR_SUBRANGE, "Source created for the range [" + start + "," + end + ")" + " must be a subrange source"); } @@ -386,10 +386,10 @@ public void validate() { super.validate(); switch (mode) { case FILEPATTERN: - Preconditions.checkArgument(getStartOffset() == 0, + checkArgument(getStartOffset() == 0, "FileBasedSource is based on a file pattern or a full single file " + "but the starting offset proposed " + getStartOffset() + " is not zero"); - Preconditions.checkArgument(getEndOffset() == Long.MAX_VALUE, + checkArgument(getEndOffset() == Long.MAX_VALUE, "FileBasedSource is based on a file pattern or a full single file " + "but the ending offset proposed " + getEndOffset() + " is not Long.MAX_VALUE"); break; @@ -468,7 +468,7 @@ public abstract static class FileBasedReader extends OffsetBasedReader { */ public FileBasedReader(FileBasedSource source) { super(source); - Preconditions.checkArgument(source.getMode() != Mode.FILEPATTERN, + checkArgument(source.getMode() != Mode.FILEPATTERN, "FileBasedReader does not support reading file patterns"); } @@ -488,10 +488,10 @@ protected final boolean startImpl() throws IOException { seekChannel.position(source.getStartOffset()); } else { // Channel is not seekable. Must not be a subrange. - Preconditions.checkArgument(source.mode != Mode.SINGLE_FILE_OR_SUBRANGE, + checkArgument(source.mode != Mode.SINGLE_FILE_OR_SUBRANGE, "Subrange-based sources must only be defined for file types that support seekable " + " read channels"); - Preconditions.checkArgument(source.getStartOffset() == 0, "Start offset " + checkArgument(source.getStartOffset() == 0, "Start offset " + source.getStartOffset() + " is not zero but channel for reading the file is not seekable."); } @@ -574,7 +574,7 @@ public boolean start() throws IOException { @Override public boolean advance() throws IOException { - Preconditions.checkState(currentReader != null, "Call start() before advance()"); + checkState(currentReader != null, "Call start() before advance()"); if (currentReader.advance()) { return true; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 492dcad24c..f48b968bc3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -16,6 +16,7 @@ package com.google.cloud.dataflow.sdk.io; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -34,9 +35,7 @@ import com.google.cloud.dataflow.sdk.values.PDone; import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; import com.google.protobuf.ByteString; - import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; @@ -47,7 +46,6 @@ import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import java.util.regex.Pattern; - import javax.annotation.Nullable; /** @@ -598,7 +596,7 @@ public Bound withSuffix(String nameExtension) { * @see ShardNameTemplate */ public Bound withNumShards(int numShards) { - Preconditions.checkArgument(numShards >= 0); + checkArgument(numShards >= 0); return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, validate); } @@ -821,7 +819,7 @@ public boolean matches(String filename) { private static final Pattern SHARD_OUTPUT_PATTERN = Pattern.compile("@([0-9]+|\\*)"); private static void validateOutputComponent(String partialFilePattern) { - Preconditions.checkArgument( + checkArgument( !SHARD_OUTPUT_PATTERN.matcher(partialFilePattern).find(), "Output name components are not allowed to contain @* or @N patterns: " + partialFilePattern); From ac1d97b3bb8233bbc8dcec4dfc6a268529acad77 Mon Sep 17 00:00:00 2001 From: peihe Date: Fri, 30 Sep 2016 08:14:44 -0700 Subject: [PATCH 595/751] Let BigQuery to pick default location if the query does not read any tables. (#456) --- .../dataflow/sdk/util/BigQueryTableRowIterator.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index dfdb26981a..552c60464b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -356,14 +356,16 @@ private Table getTable(TableReference ref) throws IOException, InterruptedExcept } // Create a new BigQuery dataset - private void createDataset(String datasetId, String location) + private void createDataset(String datasetId, @Nullable String location) throws IOException, InterruptedException { Dataset dataset = new Dataset(); DatasetReference reference = new DatasetReference(); reference.setProjectId(projectId); reference.setDatasetId(datasetId); dataset.setDatasetReference(reference); - dataset.setLocation(location); + if (location != null) { + dataset.setLocation(location); + } executeWithBackOff( client.datasets().insert(projectId, dataset), @@ -411,8 +413,8 @@ private TableReference executeQueryAndWaitForCompletion() client.jobs().insert(projectId, dryRunJob), String.format("Error when trying to dry run query %s.", query)).getStatistics(); - // Default to US if the query does not read any tables. - String location = "US"; + // Let BigQuery to pick default location if the query does not read any tables. + String location = null; @Nullable List tables = jobStats.getQuery().getReferencedTables(); if (tables != null && !tables.isEmpty()) { Table table = getTable(tables.get(0)); From 1303cb72b4ce2b821b30cac8869da45dc44a49fc Mon Sep 17 00:00:00 2001 From: Pei He Date: Fri, 30 Sep 2016 12:54:27 -0700 Subject: [PATCH 596/751] Forward port fixups in Beam PR-1032 --- .../sdk/util/BigQueryTableRowIterator.java | 17 +++++++-------- .../util/BigQueryTableRowIteratorTest.java | 21 ++++++++++++++----- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 552c60464b..8f4ff793dc 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -177,13 +177,11 @@ public boolean advance() throws IOException, InterruptedException { list.setPageToken(pageToken); } - TableDataList result = - executeWithBackOff( - list, - String.format( - "Error reading from BigQuery table %s of dataset %s.", - ref.getTableId(), - ref.getDatasetId())); + TableDataList result = executeWithBackOff( + list, + String.format( + "Error reading from BigQuery table %s of dataset %s.", + ref.getTableId(), ref.getDatasetId())); pageToken = result.getPageToken(); iteratorOverCurrentBatch = @@ -370,7 +368,7 @@ private void createDataset(String datasetId, @Nullable String location) executeWithBackOff( client.datasets().insert(projectId, dataset), String.format( - "Error when trying to create the temporary dataset %s in project %s", + "Error when trying to create the temporary dataset %s in project %s.", datasetId, projectId)); } @@ -407,7 +405,7 @@ private TableReference executeQueryAndWaitForCompletion() Job dryRunJob = new Job() .setConfiguration(new JobConfiguration() .setQuery(new JobConfigurationQuery() - .setQuery(query)) + .setQuery(query)) .setDryRun(true)); JobStatistics jobStats = executeWithBackOff( client.jobs().insert(projectId, dryRunJob), @@ -508,7 +506,6 @@ public static T executeWithBackOff(AbstractGoogleClientRequest client, St } } } - return result; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java index 4516d5d977..d6ac5b36ba 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -133,6 +133,17 @@ private static Table tableWithBasicSchema() { new TableFieldSchema().setName("anniversary_time").setType("TIME")))); } + private static Table noTableQuerySchema() { + return new Table() + .setSchema( + new TableSchema() + .setFields( + Arrays.asList( + new TableFieldSchema().setName("name").setType("STRING"), + new TableFieldSchema().setName("count").setType("INTEGER"), + new TableFieldSchema().setName("photo").setType("BYTES")))); + } + private static Table tableWithLocation() { return new Table() .setLocation("EU"); @@ -206,6 +217,7 @@ public void testReadFromQuery() throws IOException, InterruptedException { assertEquals("2000-01-01", row.get("anniversary_date")); assertEquals("2000-01-01 00:00:00.000005", row.get("anniversary_datetime")); assertEquals("00:00:00.000005", row.get("anniversary_time")); + assertFalse(iterator.advance()); } @@ -257,14 +269,13 @@ public void testReadFromQueryNoTables() throws IOException, InterruptedException when(mockJobsGet.execute()).thenReturn(getJob); // Mock table schema fetch. - when(mockTablesGet.execute()).thenReturn(tableWithBasicSchema()); + when(mockTablesGet.execute()).thenReturn(noTableQuerySchema()); byte[] photoBytes = "photograph".getBytes(); String photoBytesEncoded = BaseEncoding.base64().encode(photoBytes); // Mock table data fetch. when(mockTabledataList.execute()).thenReturn( - rawDataList(rawRow("Arthur", 42, photoBytesEncoded, - "2000-01-01", "2000-01-01 00:00:00.000005", "00:00:00.000005"))); + rawDataList(rawRow("Arthur", 42, photoBytesEncoded))); // Run query and verify String query = String.format( @@ -277,10 +288,10 @@ public void testReadFromQueryNoTables() throws IOException, InterruptedException TableRow row = iterator.getCurrent(); assertTrue(row.containsKey("name")); - assertTrue(row.containsKey("answer")); + assertTrue(row.containsKey("count")); assertTrue(row.containsKey("photo")); assertEquals("Arthur", row.get("name")); - assertEquals(42, row.get("answer")); + assertEquals(42, row.get("count")); assertEquals(photoBytesEncoded, row.get("photo")); assertFalse(iterator.advance()); From 6c0fc49394abd4a42b225ad71771fba368ee4a8a Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 30 Sep 2016 15:51:30 -0700 Subject: [PATCH 597/751] Version management: use 1.8.0 worker container --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 03c8cba75d..176f972ea3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -221,9 +221,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.7.0"; + = "dataflow.gcr.io/v1beta3/java-batch:1.8.0"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.7.0"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.8.0"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 0ea71364834857478b827a5e86666a816486f02c Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 7 Jul 2016 13:49:30 -0700 Subject: [PATCH 598/751] Backport DisplayDataEvaluator#getDefaultOptions() (cherry picked from commit 9e0b1b423ef722cdfbec0bde89d85faa760bf322) --- .../sdk/transforms/display/DisplayDataEvaluator.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java index 24e98d0ac4..15cea27bbc 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java @@ -40,10 +40,11 @@ public class DisplayDataEvaluator { private final PipelineOptions options; /** - * Create a new {@link DisplayDataEvaluator} using {@link TestPipeline#testingPipelineOptions()}. + * Create a new {@link DisplayDataEvaluator} using options returned from + * {@link #getDefaultOptions()}. */ public static DisplayDataEvaluator create() { - return create(TestPipeline.testingPipelineOptions()); + return create(getDefaultOptions()); } /** @@ -53,6 +54,13 @@ public static DisplayDataEvaluator create(PipelineOptions pipelineOptions) { return new DisplayDataEvaluator(pipelineOptions); } + /** + * The default {@link PipelineOptions} which will be used by {@link #create()}. + */ + public static PipelineOptions getDefaultOptions() { + return TestPipeline.testingPipelineOptions(); + } + private DisplayDataEvaluator(PipelineOptions options) { this.options = options; } From 3edf047fcc5ac4a4f8a97381b7c6bae5b56aae72 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 3 Oct 2016 09:41:15 -0700 Subject: [PATCH 599/751] Handle anonymous classes in DataflowUnboundedReadFromBoundedSource.getKind() Correctly implement display data for DataflowRunner Read transforms The DataflowRunner will replace usages of the Read transform with interally-wrapped implementations for streaming and bounded cases. We were not properly passing display data between these usages. Set transform names in DisplayDataEvaluator If a transform name is unset, a runner may infer the name from the class simple name, which fails with anonymous classes. In order to be more generically useful, we set transform names within the DisplayDataEvaluator. (cherry-picked from 3e7c396a09965ad688fc9b584c57cb1807360391) --- .../io/BoundedReadFromUnboundedSource.java | 6 ++ .../sdk/runners/DataflowPipelineRunner.java | 7 +++ ...ataflowUnboundedReadFromBoundedSource.java | 16 +++++- .../cloud/dataflow/sdk/io/ReadTest.java | 56 ++++++++++++++++++- ...lowUnboundedReadFromBoundedSourceTest.java | 47 ++++++++++++++++ .../display/DisplayDataEvaluator.java | 6 +- 6 files changed, 132 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java index 88ecbee3d7..9712e8fb92 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java @@ -202,6 +202,12 @@ public BoundedReader> createReader(PipelineOptions options) return new Reader(source.createReader(options, null)); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item("source", source.getClass())); + builder.include(source); + } + private class Reader extends BoundedReader> { private long recordsRead = 0L; private Instant endTime = Instant.now().plus(maxReadTime); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 176f972ea3..54f261f644 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -2522,6 +2522,13 @@ protected Coder> getDefaultOutputCoder() { return ValueWithRecordId.ValueWithRecordIdCoder.of(source.getDefaultOutputCoder()); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder.add(DisplayData.item("source", source.getClass())); + builder.include(source); + } + public UnboundedSource getSource() { return source; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java index 81aceebb2f..6cfaad13eb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java @@ -103,7 +103,14 @@ protected Coder getDefaultOutputCoder() { @Override public String getKindString() { - return "Read(" + approximateSimpleName(source.getClass()) + ")"; + String sourceName; + if (source.getClass().isAnonymousClass()) { + sourceName = "AnonymousSource"; + } else { + sourceName = approximateSimpleName(source.getClass()); + } + + return "Read(" + sourceName + ")"; } @Override @@ -181,6 +188,13 @@ public Coder> getCheckpointMarkCoder() { return new CheckpointCoder<>(boundedSource.getDefaultOutputCoder()); } + @Override + public void populateDisplayData(DisplayData.Builder builder) { + super.populateDisplayData(builder); + builder.add(DisplayData.item("source", boundedSource.getClass())); + builder.include(boundedSource); + } + @VisibleForTesting static class Checkpoint implements UnboundedSource.CheckpointMark { @Nullable private final List> residualElements; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java index 25afc07f00..6939ad4b14 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java @@ -20,15 +20,21 @@ import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.StreamingOptions; +import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; import org.joda.time.Duration; import org.junit.Rule; import org.junit.Test; +import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -36,6 +42,7 @@ import java.io.IOException; import java.io.Serializable; import java.util.List; +import java.util.Set; import javax.annotation.Nullable; /** @@ -100,6 +107,51 @@ public void populateDisplayData(DisplayData.Builder builder) { assertThat(unboundedDisplayData, hasDisplayItem("maxReadTime", maxReadTime)); } + @Test + @Category(RunnableOnService.class) + public void testBoundedPrimitiveDisplayData() { + testPrimitiveDisplayData(/* isStreaming: */ false); + } + + @Test + @Category(RunnableOnService.class) + public void testStreamingPrimitiveDisplayData() { + testPrimitiveDisplayData(/* isStreaming: */ true); + } + + private void testPrimitiveDisplayData(boolean isStreaming) { + PipelineOptions options = DisplayDataEvaluator.getDefaultOptions(); + options.as(StreamingOptions.class).setStreaming(isStreaming); + DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(options); + + SerializableBoundedSource boundedSource = new SerializableBoundedSource() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item("foo", "bar")); + } + }; + SerializableUnboundedSource unboundedSource = new SerializableUnboundedSource() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item("foo", "bar")); + } + }; + + Read.Bounded bounded = Read.from(boundedSource); + BoundedReadFromUnboundedSource unbounded = Read.from(unboundedSource) + .withMaxNumRecords(1234); + + Set boundedDisplayData = evaluator + .displayDataForPrimitiveSourceTransforms(bounded); + assertThat(boundedDisplayData, hasItem(hasDisplayItem("source", boundedSource.getClass()))); + assertThat(boundedDisplayData, hasItem(includesDisplayDataFrom(boundedSource))); + + Set unboundedDisplayData = evaluator + .displayDataForPrimitiveSourceTransforms(unbounded); + assertThat(unboundedDisplayData, hasItem(hasDisplayItem("source"))); + assertThat(unboundedDisplayData, hasItem(includesDisplayDataFrom(unboundedSource))); + } + private abstract static class CustomBoundedSource extends BoundedSource { @Override public List> splitIntoBundles( @@ -127,7 +179,7 @@ public void validate() {} @Override public Coder getDefaultOutputCoder() { - return null; + return StringUtf8Coder.of(); } } @@ -163,7 +215,7 @@ public void validate() {} @Override public Coder getDefaultOutputCoder() { - return null; + return StringUtf8Coder.of(); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java index 7c39ab03ce..c144ca8ab9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java @@ -268,6 +268,53 @@ public void testReadFromCheckpointBeforeStart() throws Exception { unboundedSource.createReader(options, checkpoint).getCurrent(); } + @Test + public void testKind() { + DataflowUnboundedReadFromBoundedSource read = new + DataflowUnboundedReadFromBoundedSource<>(new NoopNamedSource()); + + assertEquals("Read(NoopNamedSource)", read.getKindString()); + } + + @Test + public void testKindAnonymousSource() { + NoopNamedSource anonSource = new NoopNamedSource() {}; + DataflowUnboundedReadFromBoundedSource read = new + DataflowUnboundedReadFromBoundedSource<>(anonSource); + + assertEquals("Read(AnonymousSource)", read.getKindString()); + } + + /** Source implementation only useful for its identity. */ + static class NoopNamedSource extends BoundedSource { + @Override + public List> splitIntoBundles(long desiredBundleSizeBytes, + PipelineOptions options) throws Exception { + return null; + } + @Override + public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { + return 0; + } + @Override + public boolean producesSortedKeys(PipelineOptions options) throws Exception { + return false; + } + @Override + public BoundedReader createReader( + PipelineOptions options) throws IOException { + return null; + } + @Override + public void validate() { + + } + @Override + public Coder getDefaultOutputCoder() { + return null; + } + } + /** * Generate byte array of given size. */ diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java index 15cea27bbc..82a06afb87 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java @@ -97,8 +97,8 @@ public Set displayDataForPrimitiveTransforms( Pipeline pipeline = Pipeline.create(options); pipeline - .apply(input) - .apply(root); + .apply("Input", input) + .apply("Transform", root); PrimitiveDisplayDataPTransformVisitor visitor = new PrimitiveDisplayDataPTransformVisitor(root); pipeline.traverseTopologically(visitor); @@ -116,7 +116,7 @@ public Set displayDataForPrimitiveSourceTransforms( final PTransform root) { Pipeline pipeline = Pipeline.create(options); pipeline - .apply(root); + .apply("SourceTransform", root); return displayDataForPipeline(pipeline, root); } From 0786791cae6fb4e1c99c763d74070fd29b019d3d Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Fri, 30 Sep 2016 10:05:00 -0700 Subject: [PATCH 600/751] Backport PipelineOptions display data array values PipelineOptions generates display data for arbitrary option types using #toString(). For array types, this gives an message like [Ljava.lang.String;@fc25934b]. Instead, we detect array types and use Arrays.deepString to build a string based on array values. (cherry picked from commit bed5000a0f19312736e74725d186d16a504e5031) --- .../sdk/options/ProxyInvocationHandler.java | 23 +++++++++++++++++-- .../options/ProxyInvocationHandlerTest.java | 23 +++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index 535e043ef5..9c6c7b9f0c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -331,7 +331,7 @@ public void populateDisplayData(DisplayData.Builder builder) { builder.add(DisplayData.item(option.getKey(), type, value) .withNamespace(pipelineInterface)); } else { - builder.add(DisplayData.item(option.getKey(), value.toString()) + builder.add(DisplayData.item(option.getKey(), displayDataString(value)) .withNamespace(pipelineInterface)); } } @@ -360,7 +360,7 @@ public void populateDisplayData(DisplayData.Builder builder) { builder.add(DisplayData.item(jsonOption.getKey(), type, value) .withNamespace(spec.getDefiningInterface())); } else { - builder.add(DisplayData.item(jsonOption.getKey(), value.toString()) + builder.add(DisplayData.item(jsonOption.getKey(), displayDataString(value)) .withNamespace(spec.getDefiningInterface())); } } @@ -368,6 +368,25 @@ public void populateDisplayData(DisplayData.Builder builder) { } } + /** + * {@link Object#toString()} wrapper to extract display data values for various types. + */ + private String displayDataString(Object value) { + checkNotNull(value, "value cannot be null"); + if (!value.getClass().isArray()) { + return value.toString(); + } + if (!value.getClass().getComponentType().isPrimitive()) { + return Arrays.deepToString((Object[]) value); + } + + // At this point, we have some type of primitive array. Arrays.deepToString(..) requires an + // Object array, but will unwrap nested primitive arrays. + String wrapped = Arrays.deepToString(new Object[]{value}); + return wrapped.substring(1, wrapped.length() - 1); + } + + /** * Marker interface used when the original {@link PipelineOptions} interface is not known at * runtime. This can occur if {@link PipelineOptions} are deserialized from JSON. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java index 89cdcc0fd0..685e0f23e5 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java @@ -854,6 +854,29 @@ public void testDisplayDataNullValuesConvertedToEmptyString() throws Exception { assertThat(deserializedData, hasDisplayItem("foo", "")); } + @Test + public void testDisplayDataArrayValue() throws Exception { + ArrayOptions options = PipelineOptionsFactory.as(ArrayOptions.class); + options.setDeepArray(new String[][] {new String[] {"a", "b"}, new String[] {"c"}}); + options.setDeepPrimitiveArray(new int[][] {new int[] {1, 2}, new int[] {3}}); + + DisplayData data = DisplayData.from(options); + assertThat(data, hasDisplayItem("deepArray", "[[a, b], [c]]")); + assertThat(data, hasDisplayItem("deepPrimitiveArray", "[[1, 2], [3]]")); + + ArrayOptions deserializedOptions = serializeDeserialize(ArrayOptions.class, options); + DisplayData deserializedData = DisplayData.from(deserializedOptions); + assertThat(deserializedData, hasDisplayItem("deepPrimitiveArray", "[[1, 2], [3]]")); + } + + private interface ArrayOptions extends PipelineOptions { + String[][] getDeepArray(); + void setDeepArray(String[][] value); + + int[][] getDeepPrimitiveArray(); + void setDeepPrimitiveArray(int[][] value); + } + @Test public void testDisplayDataJsonSerialization() throws IOException { FooOptions options = PipelineOptionsFactory.as(FooOptions.class); From 073519f666da025f232c5f114a28606611ec0a1e Mon Sep 17 00:00:00 2001 From: Pei He Date: Mon, 3 Oct 2016 21:32:04 -0700 Subject: [PATCH 601/751] BigQueryIO: rename testBigQueryServices to bigQueryServices --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 59 +++++++++---------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 900fec64fd..a14933570b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -396,7 +396,7 @@ public static class Bound extends PTransform> { final boolean validate; @Nullable final Boolean flattenResults; @Nullable final Boolean useLegacySql; - @Nullable BigQueryServices testBigQueryServices; + @Nullable BigQueryServices bigQueryServices; private static final String QUERY_VALIDATION_FAILURE_ERROR = "Validation of query \"%1$s\" failed. If the query depends on an earlier stage of the" @@ -410,20 +410,20 @@ private Bound() { true /* validate */, null /* flattenResults */, null /* useLegacySql */, - null /* testBigQueryServices */); + null /* bigQueryServices */); } private Bound( String name, @Nullable String query, @Nullable String jsonTableRef, boolean validate, @Nullable Boolean flattenResults, @Nullable Boolean useLegacySql, - @Nullable BigQueryServices testBigQueryServices) { + @Nullable BigQueryServices bigQueryServices) { super(name); this.jsonTableRef = jsonTableRef; this.query = query; this.validate = validate; this.flattenResults = flattenResults; this.useLegacySql = useLegacySql; - this.testBigQueryServices = testBigQueryServices; + this.bigQueryServices = bigQueryServices; } /** @@ -434,7 +434,7 @@ private Bound( public Bound named(String name) { return new Bound( name, query, jsonTableRef, validate, flattenResults, useLegacySql, - testBigQueryServices); + bigQueryServices); } /** @@ -455,7 +455,7 @@ public Bound from(String tableSpec) { public Bound from(TableReference table) { return new Bound( name, query, toJsonString(table), validate, flattenResults, useLegacySql, - testBigQueryServices); + bigQueryServices); } /** @@ -475,7 +475,7 @@ public Bound fromQuery(String query) { return new Bound(name, query, jsonTableRef, validate, MoreObjects.firstNonNull(flattenResults, Boolean.TRUE), MoreObjects.firstNonNull(useLegacySql, Boolean.TRUE), - testBigQueryServices); + bigQueryServices); } /** @@ -484,7 +484,7 @@ public Bound fromQuery(String query) { public Bound withoutValidation() { return new Bound( name, query, jsonTableRef, false /* validate */, flattenResults, useLegacySql, - testBigQueryServices); + bigQueryServices); } /** @@ -497,7 +497,7 @@ public Bound withoutValidation() { public Bound withoutResultFlattening() { return new Bound( name, query, jsonTableRef, validate, false /* flattenResults */, useLegacySql, - testBigQueryServices); + bigQueryServices); } /** @@ -509,7 +509,7 @@ public Bound withoutResultFlattening() { public Bound usingStandardSql() { return new Bound( name, query, jsonTableRef, validate, flattenResults, false /* useLegacySql */, - testBigQueryServices); + bigQueryServices); } @VisibleForTesting @@ -533,7 +533,7 @@ public void validate(PInput input) { checkArgument( !Strings.isNullOrEmpty(tempLocation), "BigQueryIO.Read needs a GCS temp location to store temp files."); - if (testBigQueryServices == null) { + if (bigQueryServices == null) { try { GcsPath.fromUri(tempLocation); } catch (IllegalArgumentException e) { @@ -744,10 +744,10 @@ public Boolean getUseLegacySql() { } private BigQueryServices getBigQueryServices() { - if (testBigQueryServices == null) { - testBigQueryServices = new BigQueryServicesImpl(); + if (bigQueryServices == null) { + bigQueryServices = new BigQueryServicesImpl(); } - return testBigQueryServices; + return bigQueryServices; } } @@ -1542,8 +1542,7 @@ public static class Bound extends PTransform, PDone> { // An option to indicate if table validation is desired. Default is true. final boolean validate; - // A fake or mock BigQueryServices for tests. - @Nullable private BigQueryServices testBigQueryServices; + @Nullable private BigQueryServices bigQueryServices; private static class TranslateTableSpecFunction implements SerializableFunction { @@ -1574,14 +1573,14 @@ public Bound() { CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY, true /* validate */, - null /* testBigQueryServices */); + null /* bigQueryServices */); } private Bound(String name, @Nullable String jsonTableRef, @Nullable SerializableFunction tableRefFunction, @Nullable String jsonSchema, CreateDisposition createDisposition, WriteDisposition writeDisposition, boolean validate, - @Nullable BigQueryServices testBigQueryServices) { + @Nullable BigQueryServices bigQueryServices) { super(name); this.jsonTableRef = jsonTableRef; this.tableRefFunction = tableRefFunction; @@ -1589,7 +1588,7 @@ private Bound(String name, @Nullable String jsonTableRef, this.createDisposition = checkNotNull(createDisposition, "createDisposition"); this.writeDisposition = checkNotNull(writeDisposition, "writeDisposition"); this.validate = validate; - this.testBigQueryServices = testBigQueryServices; + this.bigQueryServices = bigQueryServices; } /** @@ -1599,7 +1598,7 @@ private Bound(String name, @Nullable String jsonTableRef, */ public Bound named(String name) { return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, testBigQueryServices); + writeDisposition, validate, bigQueryServices); } /** @@ -1619,7 +1618,7 @@ public Bound to(String tableSpec) { */ public Bound to(TableReference table) { return new Bound(name, toJsonString(table), tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, testBigQueryServices); + writeDisposition, validate, bigQueryServices); } /** @@ -1648,7 +1647,7 @@ public Bound to( public Bound toTableReference( SerializableFunction tableRefFunction) { return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, testBigQueryServices); + writeDisposition, validate, bigQueryServices); } /** @@ -1659,7 +1658,7 @@ public Bound toTableReference( */ public Bound withSchema(TableSchema schema) { return new Bound(name, jsonTableRef, tableRefFunction, toJsonString(schema), - createDisposition, writeDisposition, validate, testBigQueryServices); + createDisposition, writeDisposition, validate, bigQueryServices); } /** @@ -1669,7 +1668,7 @@ public Bound withSchema(TableSchema schema) { */ public Bound withCreateDisposition(CreateDisposition createDisposition) { return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, testBigQueryServices); + writeDisposition, validate, bigQueryServices); } /** @@ -1679,7 +1678,7 @@ public Bound withCreateDisposition(CreateDisposition createDisposition) { */ public Bound withWriteDisposition(WriteDisposition writeDisposition) { return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, testBigQueryServices); + writeDisposition, validate, bigQueryServices); } /** @@ -1689,7 +1688,7 @@ public Bound withWriteDisposition(WriteDisposition writeDisposition) { */ public Bound withoutValidation() { return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, false, testBigQueryServices); + writeDisposition, false, bigQueryServices); } @VisibleForTesting @@ -1778,7 +1777,7 @@ public void validate(PCollection input) { checkArgument( !Strings.isNullOrEmpty(tempLocation), "BigQueryIO.Write needs a GCS temp location to store temp files."); - if (testBigQueryServices == null) { + if (bigQueryServices == null) { try { GcsPath.fromUri(tempLocation); } catch (IllegalArgumentException e) { @@ -1994,10 +1993,10 @@ public boolean getValidate() { } private BigQueryServices getBigQueryServices() { - if (testBigQueryServices == null) { - testBigQueryServices = new BigQueryServicesImpl(); + if (bigQueryServices == null) { + bigQueryServices = new BigQueryServicesImpl(); } - return testBigQueryServices; + return bigQueryServices; } } From ed51e7fc52763bdef6d2d1fd515467157b10ebef Mon Sep 17 00:00:00 2001 From: Pei He Date: Mon, 3 Oct 2016 21:36:16 -0700 Subject: [PATCH 602/751] BigQueryIO: use getTableWithDefaultProject() to reduce duplicated code --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index a14933570b..a8091d3fe7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -692,13 +692,13 @@ public void populateDisplayData(DisplayData.Builder builder) { } /** - * Returns the table to write, or {@code null} if reading from a query instead. + * Returns the table to read, or {@code null} if reading from a query instead. * - *

            If the table's project is not specified, use the default one. + *

            If the table's project is not specified, use the executing project. */ @Nullable private TableReference getTableWithDefaultProject(BigQueryOptions bqOptions) { TableReference table = getTable(); - if (table != null && table.getProjectId() == null) { + if (table != null && Strings.isNullOrEmpty(table.getProjectId())) { // If user does not specify a project we assume the table to be located in // the default project. table.setProjectId(bqOptions.getProject()); @@ -709,6 +709,7 @@ public void populateDisplayData(DisplayData.Builder builder) { /** * Returns the table to read, or {@code null} if reading from a query instead. */ + @Nullable public TableReference getTable() { return fromJsonString(jsonTableRef, TableReference.class); } @@ -1739,13 +1740,7 @@ public void validate(PCollection input) { // The user specified a table. if (jsonTableRef != null && validate) { - TableReference table = getTable(); - - // If user does not specify a project we assume the table to be located in the project - // configured in BigQueryOptions. - if (Strings.isNullOrEmpty(table.getProjectId())) { - table.setProjectId(options.getProject()); - } + TableReference table = getTableWithDefaultProject(options); // Check for destination table presence and emptiness for early failure notification. // Note that a presence check can fail when the table or dataset is created by an earlier @@ -1803,10 +1798,8 @@ public PDone apply(PCollection input) { return input.apply(new StreamWithDeDup(getTable(), tableRefFunction, getSchema())); } - TableReference table = fromJsonString(jsonTableRef, TableReference.class); - if (Strings.isNullOrEmpty(table.getProjectId())) { - table.setProjectId(options.getProject()); - } + TableReference table = getTableWithDefaultProject(options); + String jobIdToken = "beam_job_" + randomUUIDString(); String tempLocation = options.getTempLocation(); String tempFilePrefix; @@ -1981,6 +1974,21 @@ public TableSchema getSchema() { return fromJsonString(jsonSchema, TableSchema.class); } + /** + * Returns the table to write, or {@code null} if writing with {@code tableRefFunction}. + * + *

            If the table's project is not specified, use the executing project. + */ + @Nullable private TableReference getTableWithDefaultProject(BigQueryOptions bqOptions) { + TableReference table = getTable(); + if (table != null && Strings.isNullOrEmpty(table.getProjectId())) { + // If user does not specify a project we assume the table to be located in + // the default project. + table.setProjectId(bqOptions.getProject()); + } + return table; + } + /** Returns the table reference, or {@code null}. */ @Nullable public TableReference getTable() { From 57ffaba9b2a81da1defecc11fa386dd5ee95ff43 Mon Sep 17 00:00:00 2001 From: Pei He Date: Mon, 3 Oct 2016 21:45:17 -0700 Subject: [PATCH 603/751] BigQueryIO: port trivial fixes from Beam version. --- .../google/cloud/dataflow/sdk/io/BigQueryIO.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index a8091d3fe7..61b66e0a98 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -165,7 +165,7 @@ *

            To read from a BigQuery table, apply a {@link BigQueryIO.Read} transformation. * This produces a {@link PCollection} of {@link TableRow TableRows} as output: *

            {@code
            - * PCollection shakespeare = pipeline.apply(
            + * PCollection weatherData = pipeline.apply(
              *     BigQueryIO.Read.named("Read")
              *                    .from("clouddataflow-readonly:samples.weather_stations"));
              * }
            @@ -177,7 +177,7 @@ * input transform. * *
            {@code
            - * PCollection shakespeare = pipeline.apply(
            + * PCollection meanTemperatureData = pipeline.apply(
              *     BigQueryIO.Read.named("Read")
              *                    .fromQuery("SELECT year, mean_temp FROM [samples.weather_stations]"));
              * }
            @@ -888,14 +888,19 @@ static BigQueryQuerySource create( String extractDestinationDir, BigQueryServices bqServices) { return new BigQueryQuerySource( - jobIdToken, query, queryTempTableRef, flattenResults, useLegacySql, extractDestinationDir, + jobIdToken, + query, + queryTempTableRef, + flattenResults, + useLegacySql, + extractDestinationDir, bqServices); } private final String query; private final String jsonQueryTempTable; private final Boolean flattenResults; - private final boolean useLegacySql; + private final Boolean useLegacySql; private transient AtomicReference dryRunJobStats; private BigQueryQuerySource( @@ -1013,7 +1018,6 @@ private void executeQuery( if (parseStatus(job) != Status.SUCCEEDED) { throw new IOException("Query job failed: " + jobId); } - return; } private JobConfigurationQuery createBasicQueryConfig() { From 7e31709c1a60e58a4d60f1a5908fa64290e215a8 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 20 Sep 2016 09:55:47 -0700 Subject: [PATCH 604/751] Use encoded Elements in the DirectPipelineRunner --- .../cloud/dataflow/sdk/runners/DirectPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java index 8a38bd9dd7..13c461e99e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java @@ -937,8 +937,8 @@ public void setPCollectionWindowedValue( public void setPCollectionValuesWithMetadata( PCollection pc, List> elements) { LOG.debug("Setting {} = {}", pc, elements); - ensurePCollectionEncodable(pc, elements); - setPValue(pc, elements); + List> encoded = ensurePCollectionEncodable(pc, elements); + setPValue(pc, encoded); } @Override From d05ac79420d4b7ded552d23f66fcb91d263209ce Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 4 Oct 2016 16:49:49 -0700 Subject: [PATCH 605/751] Version management Begin version 1.9.0 of the Dataflow SDK for Java --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index d93a81c36f..c04affddde 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.8.0-SNAPSHOT + 1.9.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 2bea58b4e1..e26a7602fd 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.8.0-SNAPSHOT + 1.9.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index c42cd5a244..22eeb7fb41 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.8.0-SNAPSHOT + 1.9.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index b4635e86ba..8e11698cbe 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.8.0-SNAPSHOT + 1.9.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index b3302bc1d2..78b04e0912 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.8.0-SNAPSHOT + 1.9.0-SNAPSHOT com.google.cloud.dataflow From e524c3279fa0b6e9511e0cd9dbcbef4ddb57358f Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 5 Oct 2016 13:59:34 -0700 Subject: [PATCH 606/751] fixup! Remove extra line --- .../cloud/dataflow/sdk/options/ProxyInvocationHandler.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index 9c6c7b9f0c..5070a52569 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -386,7 +386,6 @@ private String displayDataString(Object value) { return wrapped.substring(1, wrapped.length() - 1); } - /** * Marker interface used when the original {@link PipelineOptions} interface is not known at * runtime. This can occur if {@link PipelineOptions} are deserialized from JSON. From c6256dfa91eca0d674eb9ec8b7d3904c6e85d83e Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 5 Oct 2016 16:23:48 -0700 Subject: [PATCH 607/751] fixup! Add missing populateDisplayData to Combine.GroupedValue --- .../com/google/cloud/dataflow/sdk/transforms/Combine.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java index 444244fa37..3243d2a708 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java @@ -2293,6 +2293,11 @@ public void processElement(ProcessContext c) { c.output(KV.of(key, combineFnRunner.apply(key, c.element().getValue(), c))); } + + @Override + public void populateDisplayData(DisplayData.Builder builder) { + Combine.GroupedValues.this.populateDisplayData(builder); + } }).withSideInputs(sideInputs)); try { From da5fc7fad3122d35e4f0e25fa75557377204b837 Mon Sep 17 00:00:00 2001 From: Pei He Date: Thu, 6 Oct 2016 16:51:13 -0700 Subject: [PATCH 608/751] BigQueryServicesImpl: fix the typo of the backoff constant. --- .../google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index 9e642ffff3..1a37e01375 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -281,8 +281,7 @@ public JobStatistics dryRunQuery(String projectId, JobConfigurationQuery queryCo public Job getJob(JobReference jobRef) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_JOB_STATUS_POLL_BACKOFF) - .backoff(); + .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return getJob(jobRef, Sleeper.DEFAULT, backoff); } From f5e0badedd942ac7d5d3458b908ec6df4d6094b0 Mon Sep 17 00:00:00 2001 From: Thomas Groh Date: Tue, 4 Oct 2016 14:08:34 -0700 Subject: [PATCH 609/751] Reduce the read time in BoundedReadFromUnboundedSourceTest We only wish to demonsrate that we read "some elements" in the test. Do so in 20ms rather than 200ms. --- .../dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java index 1dc11d3793..3aef499305 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java @@ -17,7 +17,6 @@ package com.google.cloud.dataflow.sdk.io; import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -33,13 +32,11 @@ import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; - import org.joda.time.Duration; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; - import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; @@ -132,7 +129,7 @@ private void test(boolean dedup, boolean timeBound) throws Exception { } PCollection> output = timeBound - ? p.apply(Read.from(source).withMaxReadTime(Duration.millis(200))) + ? p.apply(Read.from(source).withMaxReadTime(Duration.millis(20))) : p.apply(Read.from(source).withMaxNumRecords(NUM_RECORDS)); // Because some of the NUM_RECORDS elements read are dupes, the final output From 2e65b439dafc277cac7aad3387bb42d23889264f Mon Sep 17 00:00:00 2001 From: Rafal Wojdyla Date: Mon, 17 Oct 2016 16:42:14 -0400 Subject: [PATCH 610/751] Alpha subcommand is deprecated use beta --- .../com/google/cloud/dataflow/sdk/util/MonitoringUtil.java | 2 +- .../google/cloud/dataflow/sdk/util/MonitoringUtilTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java index d45018798d..7eb3c4aa84 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java @@ -45,7 +45,7 @@ */ public final class MonitoringUtil { - private static final String GCLOUD_DATAFLOW_PREFIX = "gcloud alpha dataflow"; + private static final String GCLOUD_DATAFLOW_PREFIX = "gcloud beta dataflow"; private static final String ENDPOINT_OVERRIDE_ENV_VAR = "CLOUDSDK_API_ENDPOINT_OVERRIDES_DATAFLOW"; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java index c94450d6d2..e1458f76b7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java @@ -126,7 +126,7 @@ public void testDontOverrideEndpointWithDefaultApi() { options.setProject(PROJECT_ID); options.setGcpCredential(new TestCredential()); String cancelCommand = MonitoringUtil.getGcloudCancelCommand(options, JOB_ID); - assertEquals("gcloud alpha dataflow jobs --project=someProject cancel 1234", cancelCommand); + assertEquals("gcloud beta dataflow jobs --project=someProject cancel 1234", cancelCommand); } @Test @@ -140,7 +140,7 @@ public void testOverridesEndpointWithStagedDataflowEndpoint() { String cancelCommand = MonitoringUtil.getGcloudCancelCommand(options, JOB_ID); assertEquals( "CLOUDSDK_API_ENDPOINT_OVERRIDES_DATAFLOW=https://dataflow.googleapis.com/v0neverExisted/ " - + "gcloud alpha dataflow jobs --project=someProject cancel 1234", + + "gcloud beta dataflow jobs --project=someProject cancel 1234", cancelCommand); } } From c8a648b282202cc02db17ad2d93b67054173aac2 Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Tue, 18 Oct 2016 13:22:59 -0700 Subject: [PATCH 611/751] Backport Apache Beam PR #1109 https://github.com/apache/incubator-beam/pull/1109 --- .../cloud/dataflow/sdk/io/AvroSource.java | 97 ++++++++++++++++--- .../cloud/dataflow/sdk/io/AvroSourceTest.java | 43 ++++++++ 2 files changed, 125 insertions(+), 15 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java index a872df2d90..cbecba92be 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java @@ -27,6 +27,7 @@ import com.google.cloud.dataflow.sdk.util.AvroUtils; import com.google.cloud.dataflow.sdk.util.AvroUtils.AvroMetadata; import com.google.cloud.dataflow.sdk.values.PCollection; +import com.google.common.annotations.VisibleForTesting; import org.apache.avro.Schema; import org.apache.avro.file.CodecFactory; @@ -47,6 +48,8 @@ import java.io.EOFException; import java.io.IOException; import java.io.InputStream; +import java.io.InvalidObjectException; +import java.io.ObjectStreamException; import java.io.PushbackInputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; @@ -54,6 +57,8 @@ import java.nio.channels.SeekableByteChannel; import java.util.Arrays; import java.util.Collection; +import java.util.Map; +import java.util.WeakHashMap; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; @@ -165,7 +170,7 @@ public class AvroSource extends BlockBasedSource { * to read records of the given type from a file pattern. */ public static Read.Bounded readFromFileWithClass(String filePattern, Class clazz) { - return Read.from(new AvroSource(filePattern, DEFAULT_MIN_BUNDLE_SIZE, + return Read.from(new AvroSource<>(filePattern, DEFAULT_MIN_BUNDLE_SIZE, ReflectData.get().getSchema(clazz).toString(), clazz, null, null)); } @@ -219,14 +224,14 @@ public AvroSource withSchema(Class clazz) { *

            Does not modify this object. */ public AvroSource withMinBundleSize(long minBundleSize) { - return new AvroSource( + return new AvroSource<>( getFileOrPatternSpec(), minBundleSize, readSchemaString, type, codec, syncMarker); } private AvroSource(String fileNameOrPattern, long minBundleSize, String schema, Class type, String codec, byte[] syncMarker) { super(fileNameOrPattern, minBundleSize); - this.readSchemaString = schema; + this.readSchemaString = internSchemaString(schema); this.codec = codec; this.syncMarker = syncMarker; this.type = type; @@ -236,11 +241,11 @@ private AvroSource(String fileNameOrPattern, long minBundleSize, String schema, private AvroSource(String fileName, long minBundleSize, long startOffset, long endOffset, String schema, Class type, String codec, byte[] syncMarker, String fileSchema) { super(fileName, minBundleSize, startOffset, endOffset); - this.readSchemaString = schema; + this.readSchemaString = internSchemaString(schema); this.codec = codec; this.syncMarker = syncMarker; this.type = type; - this.fileSchemaString = fileSchema; + this.fileSchemaString = internSchemaString(fileSchema); } @Override @@ -278,13 +283,18 @@ public BlockBasedSource createForSubrangeOfFile(String fileName, long start, readSchemaString = metadata.getSchemaString(); } } - return new AvroSource(fileName, getMinBundleSize(), start, end, readSchemaString, type, + // Note that if the fileSchemaString is equivalent to the readSchemaString, "intern"ing + // the string will occur within the constructor and return the same reference as the + // readSchemaString. This allows for Java to have an efficient serialization since it + // will only encode the schema once while just storing pointers to the encoded version + // within this source. + return new AvroSource<>(fileName, getMinBundleSize(), start, end, readSchemaString, type, codec, syncMarker, fileSchemaString); } @Override protected BlockBasedReader createSingleFileReader(PipelineOptions options) { - return new AvroReader(this); + return new AvroReader<>(this); } @Override @@ -295,8 +305,7 @@ public boolean producesSortedKeys(PipelineOptions options) throws Exception { @Override public AvroCoder getDefaultOutputCoder() { if (coder == null) { - Schema.Parser parser = new Schema.Parser(); - coder = AvroCoder.of(type, parser.parse(readSchemaString)); + coder = AvroCoder.of(type, internOrParseSchemaString(readSchemaString)); } return coder; } @@ -305,28 +314,28 @@ public String getSchema() { return readSchemaString; } - private Schema getReadSchema() { + @VisibleForTesting + Schema getReadSchema() { if (readSchemaString == null) { return null; } // If the schema has not been parsed, parse it. if (readSchema == null) { - Schema.Parser parser = new Schema.Parser(); - readSchema = parser.parse(readSchemaString); + readSchema = internOrParseSchemaString(readSchemaString); } return readSchema; } - private Schema getFileSchema() { + @VisibleForTesting + Schema getFileSchema() { if (fileSchemaString == null) { return null; } // If the schema has not been parsed, parse it. if (fileSchema == null) { - Schema.Parser parser = new Schema.Parser(); - fileSchema = parser.parse(fileSchemaString); + fileSchema = internOrParseSchemaString(fileSchemaString); } return fileSchema; } @@ -351,6 +360,64 @@ private DatumReader createDatumReader() { } } + // A logical reference cache used to store schemas and schema strings to allow us to + // "intern" values and reduce the number of copies of equivalent objects. + private static final Map schemaLogicalReferenceCache = new WeakHashMap<>(); + private static final Map schemaStringLogicalReferenceCache = new WeakHashMap<>(); + + // We avoid String.intern() because depending on the JVM, these may be added to the PermGenSpace + // which we want to avoid otherwise we could run out of PermGenSpace. + private static synchronized String internSchemaString(String schema) { + String internSchema = schemaStringLogicalReferenceCache.get(schema); + if (internSchema != null) { + return internSchema; + } + schemaStringLogicalReferenceCache.put(schema, schema); + return schema; + } + + private static synchronized Schema internOrParseSchemaString(String schemaString) { + Schema schema = schemaLogicalReferenceCache.get(schemaString); + if (schema != null) { + return schema; + } + Schema.Parser parser = new Schema.Parser(); + schema = parser.parse(schemaString); + schemaLogicalReferenceCache.put(schemaString, schema); + return schema; + } + + // Reading the object from Java serialization typically does not go through the constructor, + // we use readResolve to replace the constructed instance with one which uses the constructor + // allowing us to intern any schemas. + @SuppressWarnings("unused") + private Object readResolve() throws ObjectStreamException { + switch (getMode()) { + case SINGLE_FILE_OR_SUBRANGE: + return new AvroSource<>( + getFileOrPatternSpec(), + getMinBundleSize(), + getStartOffset(), + getEndOffset(), + readSchemaString, + type, + codec, + syncMarker, + fileSchemaString); + case FILEPATTERN: + return new AvroSource<>( + getFileOrPatternSpec(), + getMinBundleSize(), + readSchemaString, + type, + codec, + syncMarker); + default: + throw new InvalidObjectException( + String.format("Unknown mode %s for AvroSource %s", getMode(), this)); + } + } + /** * A {@link BlockBasedSource.Block} of Avro records. * diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java index 44fa680921..5141320e19 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java @@ -21,6 +21,8 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -34,6 +36,8 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.util.AvroUtils; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; import com.google.common.base.MoreObjects; import org.apache.avro.Schema; @@ -427,6 +431,45 @@ public void testSchemaUpdate() throws Exception { assertThat(actual, containsInAnyOrder(expected.toArray())); } + @Test + public void testSchemaStringIsInterned() throws Exception { + List birds = createRandomRecords(100); + String filename = generateTestFile("tmp.avro", birds, SyncBehavior.SYNC_DEFAULT, 0, + AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); + String schemaA = AvroUtils.readMetadataFromFile(filename).getSchemaString(); + String schemaB = AvroUtils.readMetadataFromFile(filename).getSchemaString(); + assertNotSame(schemaA, schemaB); + + AvroSource sourceA = AvroSource.from(filename).withSchema(schemaA); + AvroSource sourceB = AvroSource.from(filename).withSchema(schemaB); + assertSame(sourceA.getSchema(), sourceB.getSchema()); + + // Ensure that deserialization still goes through interning + AvroSource sourceC = SerializableUtils.clone(sourceB); + assertSame(sourceA.getSchema(), sourceC.getSchema()); + } + + @Test + public void testSchemaIsInterned() throws Exception { + List birds = createRandomRecords(100); + String filename = generateTestFile("tmp.avro", birds, SyncBehavior.SYNC_DEFAULT, 0, + AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); + String schemaA = AvroUtils.readMetadataFromFile(filename).getSchemaString(); + String schemaB = AvroUtils.readMetadataFromFile(filename).getSchemaString(); + assertNotSame(schemaA, schemaB); + + AvroSource sourceA = (AvroSource) AvroSource.from(filename) + .withSchema(schemaA).createForSubrangeOfFile(filename, 0L, 0L); + AvroSource sourceB = (AvroSource) AvroSource.from(filename) + .withSchema(schemaB).createForSubrangeOfFile(filename, 0L, 0L); + assertSame(sourceA.getReadSchema(), sourceA.getFileSchema()); + assertSame(sourceA.getReadSchema(), sourceB.getReadSchema()); + assertSame(sourceA.getReadSchema(), sourceB.getFileSchema()); + + // Schemas are transient and not serialized thus we don't need to worry about interning + // after deserialization. + } + private void assertEqualsWithGeneric(List expected, List actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { From 173c70d32eb37db0bd99a231fba2ffe416a3266b Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Mon, 24 Oct 2016 13:38:00 -0700 Subject: [PATCH 612/751] Update checkstyle version to match apache/beam-incubating --- contrib/firebaseio/pom.xml | 5 +++-- contrib/hadoop/pom.xml | 5 +++-- contrib/join-library/pom.xml | 1 + contrib/kafka/pom.xml | 5 +++-- examples/pom.xml | 5 +++-- sdk/pom.xml | 6 +++--- suppressions.xml | 31 +++++++++++++++++++++++++++++++ 7 files changed, 47 insertions(+), 11 deletions(-) create mode 100644 suppressions.xml diff --git a/contrib/firebaseio/pom.xml b/contrib/firebaseio/pom.xml index 3d27ca4b0a..b50ef89167 100644 --- a/contrib/firebaseio/pom.xml +++ b/contrib/firebaseio/pom.xml @@ -39,16 +39,17 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.12 + 2.17 com.puppycrawl.tools checkstyle - 6.6 + 6.19 ../../checkstyle.xml + ../../suppressions.xml true true true diff --git a/contrib/hadoop/pom.xml b/contrib/hadoop/pom.xml index 8e5a207d12..0659e3ebaa 100644 --- a/contrib/hadoop/pom.xml +++ b/contrib/hadoop/pom.xml @@ -54,16 +54,17 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.12 + 2.17 com.puppycrawl.tools checkstyle - 6.6 + 6.19 ../../checkstyle.xml + ../../suppressions.xml true true true diff --git a/contrib/join-library/pom.xml b/contrib/join-library/pom.xml index df39545dac..f15ef9794c 100644 --- a/contrib/join-library/pom.xml +++ b/contrib/join-library/pom.xml @@ -71,6 +71,7 @@ 2.17 ../../checkstyle.xml + ../../suppressions.xml true true true diff --git a/contrib/kafka/pom.xml b/contrib/kafka/pom.xml index f47ed574f9..735b38cd8e 100644 --- a/contrib/kafka/pom.xml +++ b/contrib/kafka/pom.xml @@ -54,16 +54,17 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.12 + 2.17 com.puppycrawl.tools checkstyle - 6.6 + 6.19 ../../checkstyle.xml + ../../suppressions.xml true true true diff --git a/examples/pom.xml b/examples/pom.xml index c04affddde..6c1deb0b75 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -188,16 +188,17 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.12 + 2.17 com.puppycrawl.tools checkstyle - 6.6 + 6.19 ../checkstyle.xml + ../suppressions.xml true true true diff --git a/sdk/pom.xml b/sdk/pom.xml index 78b04e0912..d23ca15c10 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -186,21 +186,21 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.12 + 2.17 com.puppycrawl.tools checkstyle - 6.6 + 6.19 ../checkstyle.xml + ../suppressions.xml true true false true - ${project.build.directory}/generated-test-sources/** diff --git a/suppressions.xml b/suppressions.xml new file mode 100644 index 0000000000..4c9649a62a --- /dev/null +++ b/suppressions.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + From 13f6aa6276677bc68e5b3ddaad43c9069049d864 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Thu, 20 Oct 2016 13:57:18 -0700 Subject: [PATCH 613/751] Add checkstyle RedundantModifier check and fix offending classes Add METHOD_DEF to checkstyle RedundantModifier validation Add INTERFACE_DEF to checkstyle RedundantModifier validation Add doc comment for new checkstyle RedundantModifier check --- checkstyle.xml | 7 +++ .../dataflow/examples/DebuggingWordCount.java | 2 +- .../dataflow/examples/WindowedWordCount.java | 2 +- .../cloud/dataflow/examples/WordCount.java | 4 +- .../common/ExampleBigQueryTableOptions.java | 2 +- ...mplePubsubTopicAndSubscriptionOptions.java | 2 +- .../common/ExamplePubsubTopicOptions.java | 2 +- .../examples/complete/AutoComplete.java | 2 +- .../dataflow/examples/complete/TfIdf.java | 2 +- .../complete/TopWikipediaSessions.java | 2 +- .../examples/cookbook/BigQueryTornadoes.java | 2 +- .../cookbook/CombinePerKeyExamples.java | 2 +- .../examples/cookbook/DatastoreWordCount.java | 2 +- .../examples/cookbook/DeDupExample.java | 4 +- .../examples/cookbook/FilterExamples.java | 2 +- .../examples/cookbook/JoinExamples.java | 2 +- .../examples/cookbook/MaxPerKeyExamples.java | 2 +- .../examples/complete/game/GameStats.java | 17 ++++--- .../complete/game/HourlyTeamScore.java | 8 ++-- .../examples/complete/game/LeaderBoard.java | 15 +++--- .../examples/complete/game/UserScore.java | 2 +- .../complete/game/injector/Injector.java | 4 +- .../examples/complete/game/GameStatsTest.java | 18 -------- .../complete/game/HourlyTeamScoreTest.java | 10 ---- .../complete/game/LeaderBoardTest.java | 2 +- .../examples/complete/game/UserScoreTest.java | 2 - .../google/cloud/dataflow/sdk/Pipeline.java | 8 ++-- .../cloud/dataflow/sdk/PipelineResult.java | 2 +- .../sdk/annotations/Experimental.java | 4 +- .../coders/CannotProvideCoderException.java | 2 +- .../cloud/dataflow/sdk/coders/Coder.java | 26 +++++------ .../dataflow/sdk/coders/CoderFactory.java | 4 +- .../dataflow/sdk/coders/CoderProvider.java | 2 +- .../dataflow/sdk/coders/DelegateCoder.java | 4 +- .../cloud/dataflow/sdk/coders/JAXBCoder.java | 2 +- .../dataflow/sdk/io/CompressedSource.java | 6 +-- .../cloud/dataflow/sdk/io/FileBasedSink.java | 6 +-- .../google/cloud/dataflow/sdk/io/TextIO.java | 4 +- .../BlockingDataflowPipelineOptions.java | 2 +- .../options/DataflowPipelineDebugOptions.java | 6 +-- .../sdk/options/DataflowPipelineOptions.java | 2 +- .../DataflowPipelineWorkerPoolOptions.java | 8 ++-- .../sdk/options/DataflowProfilingOptions.java | 2 +- .../options/DataflowWorkerLoggingOptions.java | 4 +- .../dataflow/sdk/options/GcpOptions.java | 6 +-- .../dataflow/sdk/options/GcsOptions.java | 2 +- .../sdk/options/GoogleApiDebugOptions.java | 2 +- .../dataflow/sdk/options/PipelineOptions.java | 2 +- .../runners/DataflowPipelineTranslator.java | 28 +++++------ .../sdk/runners/DirectPipelineRunner.java | 4 +- .../sdk/runners/PipelineRunnerRegistrar.java | 2 +- .../sdk/runners/inprocess/BundleFactory.java | 6 +-- .../inprocess/InMemoryWatermarkManager.java | 4 +- .../inprocess/InProcessPipelineRunner.java | 6 +-- .../dataflow/sdk/testing/DataflowAssert.java | 4 +- .../dataflow/sdk/transforms/Combine.java | 8 ++-- .../sdk/transforms/CombineFnBase.java | 17 ++++--- .../cloud/dataflow/sdk/transforms/DoFn.java | 2 +- .../dataflow/sdk/transforms/Partition.java | 2 +- .../sdk/transforms/SerializableFunction.java | 2 +- .../sdk/transforms/windowing/PaneInfo.java | 2 +- .../sdk/transforms/windowing/Trigger.java | 6 +-- .../sdk/transforms/windowing/WindowFn.java | 2 +- ...temptAndTimeBoundedExponentialBackOff.java | 2 +- .../dataflow/sdk/util/BigQueryServices.java | 8 ++-- .../dataflow/sdk/util/CredentialFactory.java | 2 +- .../cloud/dataflow/sdk/util/DoFnRunner.java | 6 +-- .../cloud/dataflow/sdk/util/DoFnRunners.java | 2 +- .../dataflow/sdk/util/FinishedTriggers.java | 8 ++-- .../dataflow/sdk/util/IOChannelFactory.java | 2 +- .../dataflow/sdk/util/PathValidator.java | 6 +-- .../sdk/util/PerKeyCombineFnRunner.java | 26 +++++------ .../sdk/util/ReduceFnContextFactory.java | 2 +- .../cloud/dataflow/sdk/util/Stager.java | 2 +- .../dataflow/sdk/util/TimerInternals.java | 4 +- .../cloud/dataflow/sdk/util/Timers.java | 10 ++-- .../dataflow/sdk/util/common/Counter.java | 4 +- .../common/ElementByteSizeObservable.java | 5 +- .../dataflow/sdk/util/common/Reiterable.java | 2 +- .../dataflow/sdk/util/common/Reiterator.java | 2 +- .../sdk/util/common/worker/StateSampler.java | 6 +-- .../CopyOnAccessInMemoryStateInternals.java | 2 +- .../dataflow/sdk/util/state/StateContext.java | 6 +-- .../dataflow/sdk/values/PCollectionView.java | 8 ++-- .../cloud/dataflow/sdk/values/PInput.java | 6 +-- .../cloud/dataflow/sdk/values/POutput.java | 8 ++-- .../cloud/dataflow/sdk/values/PValue.java | 4 +- .../dataflow/sdk/coders/AvroCoderTest.java | 4 +- .../options/PipelineOptionsFactoryTest.java | 46 +++++++++---------- .../sdk/options/PipelineOptionsTest.java | 6 +-- .../options/PipelineOptionsValidatorTest.java | 18 ++++---- .../options/ProxyInvocationHandlerTest.java | 36 +++++++-------- .../InMemoryWatermarkManagerTest.java | 2 +- .../sdk/testing/DataflowJUnitTestRunner.java | 2 +- .../sdk/testing/PCollectionViewTesting.java | 2 +- .../dataflow/sdk/util/ApiSurfaceTest.java | 22 ++++----- .../PipelineOptionsFactoryJava8Test.java | 8 ++-- 97 files changed, 293 insertions(+), 308 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index ba03fd4676..e6f4f2af87 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -133,6 +133,13 @@ page at http://checkstyle.sourceforge.net/config.html --> + + + + + + + 4.0.0 + + com.google.cloud.dataflow + google-cloud-dataflow-java-contrib-sorter + Google Cloud Dataflow Sorter Library + Library to sort data from within Dataflow pipelines. + 0.0.1-SNAPSHOT + jar + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + UTF-8 + [1.2.0,2.0.0) + 2.7.1 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.17 + + + com.puppycrawl.tools + checkstyle + 6.19 + + + + ../../checkstyle.xml + true + true + true + + + + + check + + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + + attach-sources + compile + + jar + + + + attach-test-sources + test-compile + + test-jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + Google Cloud Dataflow Sorter Contrib + Google Cloud Dataflow Sorter Contrib + + com.google.cloud.dataflow.contrib.sorter + false + ]]> + + + + https://cloud.google.com/dataflow/java-sdk/JavaDoc/ + ${basedir}/../../javadoc/dataflow-sdk-docs + + + http://docs.guava-libraries.googlecode.com/git-history/release18/javadoc/ + ${basedir}/../../javadoc/guava-docs + + + + + + + jar + + package + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + bundle-and-repackage + package + + shade + + + true + + + org.apache.hadoop:hadoop-mapreduce-client-core + org.apache.hadoop:hadoop-common + com.google.guava:guava + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + org.apache.hadoop + com.google.cloud.dataflow.repackaged.org.apache.hadoop + + + com.google.common + com.google.cloud.dataflow.repackaged.com.google.common + + + com.google.thirdparty + com.google.cloud.dataflow.repackaged.com.google.thirdparty + + + + + + + + + + + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-all + ${google-cloud-dataflow-version} + + + + org.apache.hadoop + hadoop-mapreduce-client-core + ${hadoop.version} + + + + org.apache.hadoop + hadoop-common + ${hadoop.version} + + + + com.google.guava + guava + 19.0 + + + + + org.hamcrest + hamcrest-all + 1.3 + test + + + + org.mockito + mockito-all + 1.10.19 + test + + + + junit + junit + 4.11 + test + + + diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java new file mode 100644 index 0000000000..1108eef2ad --- /dev/null +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.cloud.dataflow.sdk.values.KV; +import java.io.IOException; +import java.io.Serializable; + +/** + * {@link Sorter} that will use in memory sorting until the values can't fit into memory and will + * then fall back to external sorting. + */ +public class BufferedExternalSorter implements Sorter { + /** Contains configuration for the sorter. */ + public static class Options implements Serializable { + private String tempLocation = "/tmp"; + private int memoryMB = 100; + + /** Sets the path to a temporary location where the sorter writes intermediate files. */ + public void setTempLocation(String tempLocation) { + checkArgument( + !tempLocation.startsWith("gs://"), + "BufferedExternalSorter does not support GCS temporary location"); + + this.tempLocation = tempLocation; + } + + /** Returns the configured temporary location. */ + public String getTempLocation() { + return tempLocation; + } + + /** + * Sets the size of the memory buffer in megabytes. This controls both the buffer for initial in + * memory sorting and the buffer used when external sorting. Must be greater than zero. + */ + public void setMemoryMB(int memoryMB) { + checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); + this.memoryMB = memoryMB; + } + + /** Returns the configured size of the memory buffer. */ + public int getMemoryMB() { + return memoryMB; + } + } + + private ExternalSorter externalSorter; + private InMemorySorter inMemorySorter; + + boolean inMemorySorterFull; + + BufferedExternalSorter(ExternalSorter externalSorter, InMemorySorter inMemorySorter) { + this.externalSorter = externalSorter; + this.inMemorySorter = inMemorySorter; + } + + public static BufferedExternalSorter create(Options options) { + ExternalSorter.Options externalSorterOptions = new ExternalSorter.Options(); + externalSorterOptions.setMemoryMB(options.getMemoryMB()); + externalSorterOptions.setTempLocation(options.getTempLocation()); + + InMemorySorter.Options inMemorySorterOptions = new InMemorySorter.Options(); + inMemorySorterOptions.setMemoryMB(options.getMemoryMB()); + + return new BufferedExternalSorter( + ExternalSorter.create(externalSorterOptions), InMemorySorter.create(inMemorySorterOptions)); + } + + @Override + public void add(KV record) throws IOException { + if (!inMemorySorterFull) { + if (inMemorySorter.addIfRoom(record)) { + return; + } else { + // Flushing contents of in memory sorter to external sorter so we can rely on external + // from here on out + inMemorySorterFull = true; + transferToExternalSorter(); + } + } + + // In memory sorter is full, so put in external sorter instead + externalSorter.add(record); + } + + /** + * Transfers all of the records loaded so far into the in memory sorter over to the external + * sorter. + */ + private void transferToExternalSorter() throws IOException { + for (KV record : inMemorySorter.sort()) { + externalSorter.add(record); + } + // Allow in memory sorter and its contents to be garbage collected + inMemorySorter = null; + } + + @Override + public Iterable> sort() throws IOException { + if (!inMemorySorterFull) { + return inMemorySorter.sort(); + } else { + return externalSorter.sort(); + } + } +} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java new file mode 100644 index 0000000000..8965b41926 --- /dev/null +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.values.KV; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.BytesWritable; +import org.apache.hadoop.io.SequenceFile; +import org.apache.hadoop.io.SequenceFile.CompressionType; +import org.apache.hadoop.io.SequenceFile.Sorter.RawKeyValueIterator; +import org.apache.hadoop.io.SequenceFile.Writer; +import org.apache.hadoop.mapred.JobConf; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.Serializable; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.UUID; + +/** Does an external sort of the provided values using Hadoop's {@link SequenceFile}. */ +class ExternalSorter implements Sorter { + private Options options; + + /** Whether {@link #sort()} was already called. */ + private boolean sortCalled = false; + + /** SequenceFile Writer for writing all input data to a file. */ + private Writer writer; + + /** Sorter used to sort the input file. */ + private SequenceFile.Sorter sorter; + + /** Temporary directory for input and intermediate files. */ + private Path tempDir; + + /** The list of input files to be sorted. */ + private Path[] paths; + + private boolean initialized = false; + + /** {@link Options} contains configuration of the sorter. */ + public static class Options implements Serializable { + private String tempLocation = "/tmp"; + private int memoryMB = 100; + + /** Sets the path to a temporary location where the sorter writes intermediate files. */ + public void setTempLocation(String tempLocation) { + if (tempLocation.startsWith("gs://")) { + throw new IllegalArgumentException("Sorter doesn't support GCS temporary location."); + } + + this.tempLocation = tempLocation; + } + + /** Returns the configured temporary location. */ + public String getTempLocation() { + return tempLocation; + } + + /** Sets the size of the memory buffer in megabytes. */ + public void setMemoryMB(int memoryMB) { + checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); + this.memoryMB = memoryMB; + } + + /** Returns the configured size of the memory buffer. */ + public int getMemoryMB() { + return memoryMB; + } + } + + /** Returns a {@link Sorter} configured with the given {@link Options}. */ + public static ExternalSorter create(Options options) { + return new ExternalSorter(options); + } + + @Override + public void add(KV record) throws IOException { + checkState(!sortCalled, "Records can only be added before sort()"); + + initHadoopSorter(); + + BytesWritable key = new BytesWritable(record.getKey()); + BytesWritable value = new BytesWritable(record.getValue()); + + writer.append(key, value); + } + + @Override + public Iterable> sort() throws IOException { + checkState(!sortCalled, "sort() can only be called once."); + sortCalled = true; + + initHadoopSorter(); + + writer.close(); + + return new SortedRecordsIterable(); + } + + private ExternalSorter(Options options) { + this.options = options; + } + + /** + * Initializes the hadoop sorter. Does some local file system setup, and is somewhat expensive + * (~20 ms on local machine). Only executed when necessary. + */ + private void initHadoopSorter() throws IOException { + if (!initialized) { + tempDir = new Path(options.getTempLocation(), "tmp" + UUID.randomUUID().toString()); + paths = new Path[] {new Path(tempDir, "test.seq")}; + + JobConf conf = new JobConf(); + writer = + SequenceFile.createWriter( + conf, + Writer.valueClass(BytesWritable.class), + Writer.keyClass(BytesWritable.class), + Writer.file(paths[0]), + Writer.compression(CompressionType.NONE)); + + FileSystem fs = FileSystem.getLocal(conf); + sorter = + new SequenceFile.Sorter( + fs, new BytesWritable.Comparator(), BytesWritable.class, BytesWritable.class, conf); + sorter.setMemory(options.getMemoryMB() * 1024 * 1024); + + initialized = true; + } + } + + /** An {@link Iterable} producing the iterators over sorted data. */ + private class SortedRecordsIterable implements Iterable> { + @Override + public Iterator> iterator() { + return new SortedRecordsIterator(); + } + } + + /** An {@link Iterator} producing the sorted data. */ + private class SortedRecordsIterator implements Iterator> { + private RawKeyValueIterator iterator; + + /** Next {@link KV} to return from {@link #next()}. */ + private KV nextKV = null; + + SortedRecordsIterator() { + try { + this.iterator = sorter.sortAndIterate(paths, tempDir, false); + } catch (IOException e) { + throw new RuntimeException(e); + } + + nextKV = KV.of(null, null); // A dummy value that will be overwritten by next(). + next(); + } + + @Override + public boolean hasNext() { + return nextKV != null; + } + + @Override + public KV next() { + if (nextKV == null) { + throw new NoSuchElementException(); + } + + KV current = nextKV; + + try { + if (iterator.next()) { + // Parse key from DataOutputBuffer. + ByteArrayInputStream keyStream = new ByteArrayInputStream(iterator.getKey().getData()); + BytesWritable key = new BytesWritable(); + key.readFields(new DataInputStream(keyStream)); + + // Parse value from ValueBytes. + ByteArrayOutputStream valOutStream = new ByteArrayOutputStream(); + iterator.getValue().writeUncompressedBytes(new DataOutputStream(valOutStream)); + ByteArrayInputStream valInStream = new ByteArrayInputStream(valOutStream.toByteArray()); + BytesWritable value = new BytesWritable(); + value.readFields(new DataInputStream(valInStream)); + + nextKV = KV.of(key.copyBytes(), value.copyBytes()); + } else { + nextKV = null; + } + } catch (IOException e) { + throw new RuntimeException(e); + } + + return current; + } + + @Override + public void remove() { + throw new UnsupportedOperationException("Iterator does not support remove"); + } + } +} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java new file mode 100644 index 0000000000..e62fca4057 --- /dev/null +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; + +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.primitives.UnsignedBytes; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; + +/** + * Sorts {@code } pairs in memory. Based on the configured size of the memory buffer, + * will reject additional pairs. + */ +class InMemorySorter implements Sorter { + /** {@code Options} contains configuration of the sorter. */ + public static class Options implements Serializable { + private int memoryMB = 100; + + /** Sets the size of the memory buffer in megabytes. */ + public void setMemoryMB(int memoryMB) { + checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); + this.memoryMB = memoryMB; + } + + /** Returns the configured size of the memory buffer. */ + public int getMemoryMB() { + return memoryMB; + } + } + + /** The comparator to use to sort the records by key. */ + private static final Comparator COMPARATOR = UnsignedBytes.lexicographicalComparator(); + + /** How many bytes per word in the running JVM. Assumes 64 bit/8 bytes if unknown. */ + private static final int NUM_BYTES_PER_WORD = getNumBytesPerWord(); + + /** + * Estimate of memory overhead per KV record in bytes not including memory associated with keys + * and values. + * + *

              + *
            • Object reference within {@link ArrayList} (1 word), + *
            • A {@link KV} (2 words), + *
            • Two byte arrays (2 words for array lengths), + *
            • Per-object overhead (JVM-specific, guessing 2 words * 3 objects) + *
            + */ + private static final int RECORD_MEMORY_OVERHEAD_ESTIMATE = 11 * NUM_BYTES_PER_WORD; + + /** Maximum size of the buffer in bytes. */ + private int maxBufferSize; + + /** Current number of stored bytes. Including estimated overhead bytes. */ + private int numBytes; + + /** Whether sort has been called. */ + private boolean sortCalled; + + /** The stored records to be sorted. */ + private ArrayList> records = new ArrayList>(); + + /** Private constructor. */ + private InMemorySorter(Options options) { + maxBufferSize = options.getMemoryMB() * 1024 * 1024; + } + + /** Create a new sorter from provided options. */ + public static InMemorySorter create(Options options) { + return new InMemorySorter(options); + } + + @Override + public void add(KV record) { + checkState(addIfRoom(record), "No space remaining for in memory sorting"); + } + + /** Adds the record is there is room and returns true. Otherwise returns false. */ + public boolean addIfRoom(KV record) { + checkState(!sortCalled, "Records can only be added before sort()"); + + int recordBytes = estimateRecordBytes(record); + if (roomInBuffer(numBytes + recordBytes, records.size() + 1)) { + records.add(record); + numBytes += recordBytes; + return true; + } else { + return false; + } + } + + @Override + public Iterable> sort() { + checkState(!sortCalled, "sort() can only be called once."); + + sortCalled = true; + + Comparator> kvComparator = + new Comparator>() { + + @Override + public int compare(KV o1, KV o2) { + return COMPARATOR.compare(o1.getKey(), o2.getKey()); + } + }; + Collections.sort(records, kvComparator); + return Collections.unmodifiableList(records); + } + + /** + * Estimate the number of additional bytes required to store this record. Including the key, the + * value and any overhead for objects and references. + */ + private int estimateRecordBytes(KV record) { + return RECORD_MEMORY_OVERHEAD_ESTIMATE + record.getKey().length + record.getValue().length; + } + + /** + * Check whether we have room to store the provided total number of bytes and total number of + * records. + */ + private boolean roomInBuffer(int numBytes, int numRecords) { + // Collections.sort may allocate up to n/2 extra object references. + // Also, ArrayList grows by a factor of 1.5x, so there might be up to n/2 null object + // references in the backing array. + // And finally, in Java 7, Collections.sort performs a defensive copy to an array in case the + // input list is a LinkedList. + // So assume we need an additional overhead of two words per record in the worst case + return (numBytes + (numRecords * NUM_BYTES_PER_WORD * 2)) < maxBufferSize; + } + + /** + * Returns the number of bytes in a word according to the JVM. Defaults to 8 for 64 bit if answer + * unknown. + */ + private static int getNumBytesPerWord() { + String bitsPerWord = System.getProperty("sun.arch.data.model"); + + try { + return Integer.parseInt(bitsPerWord) / 8; + } catch (Exception e) { + // Can't determine whether 32 or 64 bit, so assume 64 + return 8; + } + } +} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/SortValues.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/SortValues.java new file mode 100644 index 0000000000..32c393277c --- /dev/null +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/SortValues.java @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import com.google.cloud.dataflow.sdk.coders.Coder; +import com.google.cloud.dataflow.sdk.coders.IterableCoder; +import com.google.cloud.dataflow.sdk.coders.KvCoder; +import com.google.cloud.dataflow.sdk.transforms.DoFn; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.PTransform; +import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.util.CoderUtils; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import java.io.IOException; +import java.util.Iterator; + +/** + * {@code SortValues} takes a {@code PCollection>>>} with elements consisting of a primary key and iterables + * over {@code } pairs, and returns a {@code PCollection>>} of the same elements but with values sorted by a secondary + * key. + * + *

            This transform ignores the primary key, there is no guarantee of any relationship between + * elements with different primary keys. The primary key is explicit here only because this + * transform is typically used on a result of a {@link GroupByKey} transform. + * + *

            This transform sorts by lexicographic comparison of the byte representations of the secondary + * keys and may write secondary key-value pairs to disk. In order to retrieve the byte + * representations it requires the input PCollection to use a {@link KvCoder} for its input, an + * {@link IterableCoder} for its input values and a {@link KvCoder} for its secondary key-value + * pairs. + */ +public class SortValues + extends PTransform< + PCollection>>>, + PCollection>>>> { + + private BufferedExternalSorter.Options sorterOptions; + + private SortValues(BufferedExternalSorter.Options sorterOptions) { + this.sorterOptions = sorterOptions; + } + + /** + * Returns a {@code SortValues} {@link PTransform}. + * + * @param the type of the primary keys of the input and output {@code PCollection}s + * @param the type of the secondary (sort) keys of the input and output {@code + * PCollection}s + * @param the type of the values of the input and output {@code PCollection}s + */ + public static + SortValues create( + BufferedExternalSorter.Options sorterOptions) { + return new SortValues<>(sorterOptions); + } + + @Override + public PCollection>>> apply( + PCollection>>> input) { + return input.apply( + ParDo.of( + new SortValuesDoFn( + sorterOptions, + getSecondaryKeyCoder(input.getCoder()), + getValueCoder(input.getCoder())))); + } + + @Override + protected Coder>>> getDefaultOutputCoder( + PCollection>>> input) { + return input.getCoder(); + } + + /** Retrieves the {@link Coder} for the secondary key-value pairs. */ + @SuppressWarnings("unchecked") + private static + KvCoder getSecondaryKeyValueCoder( + Coder>>> inputCoder) { + if (!(inputCoder instanceof KvCoder)) { + throw new IllegalStateException("SortValues requires its input to use KvCoder"); + } + @SuppressWarnings("unchecked") + KvCoder>> kvCoder = + (KvCoder>>) (inputCoder); + + if (!(kvCoder.getValueCoder() instanceof IterableCoder)) { + throw new IllegalStateException( + "SortValues requires the values be encoded with IterableCoder"); + } + IterableCoder> iterableCoder = + (IterableCoder>) (kvCoder.getValueCoder()); + + if (!(iterableCoder.getElemCoder() instanceof KvCoder)) { + throw new IllegalStateException( + "SortValues requires the secondary key-value pairs to use KvCoder"); + } + return (KvCoder) (iterableCoder.getElemCoder()); + } + + /** Retrieves the {@link Coder} for the secondary keys. */ + private static Coder getSecondaryKeyCoder( + Coder>>> inputCoder) { + return getSecondaryKeyValueCoder(inputCoder).getKeyCoder(); + } + + /** Returns the {@code Coder} of the values associated with the secondary keys. */ + private static Coder getValueCoder( + Coder>>> inputCoder) { + return getSecondaryKeyValueCoder(inputCoder).getValueCoder(); + } + + private static class SortValuesDoFn + extends DoFn< + KV>>, + KV>>> { + private final BufferedExternalSorter.Options sorterOptions; + private final Coder keyCoder; + private final Coder valueCoder; + + SortValuesDoFn( + BufferedExternalSorter.Options sorterOptions, + Coder keyCoder, + Coder valueCoder) { + this.sorterOptions = sorterOptions; + this.keyCoder = keyCoder; + this.valueCoder = valueCoder; + } + + @Override + public void processElement(ProcessContext c) { + Iterable> records = c.element().getValue(); + + try { + Sorter sorter = BufferedExternalSorter.create(sorterOptions); + for (KV record : records) { + sorter.add( + KV.of( + CoderUtils.encodeToByteArray(keyCoder, record.getKey()), + CoderUtils.encodeToByteArray(valueCoder, record.getValue()))); + } + + c.output( + KV.of( + c.element().getKey(), + (Iterable>) (new DecodingIterable(sorter.sort())))); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private class DecodingIterable implements Iterable> { + Iterable> iterable; + + DecodingIterable(Iterable> iterable) { + this.iterable = iterable; + } + + @Override + public Iterator> iterator() { + return new DecodingIterator(iterable.iterator()); + } + } + + private class DecodingIterator implements Iterator> { + Iterator> iterator; + + DecodingIterator(Iterator> iterator) { + this.iterator = iterator; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public KV next() { + KV next = iterator.next(); + try { + return KV.of( + CoderUtils.decodeFromByteArray(keyCoder, next.getKey()), + CoderUtils.decodeFromByteArray(valueCoder, next.getValue())); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException("Iterator does not support remove"); + } + } + } +} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/Sorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/Sorter.java new file mode 100644 index 0000000000..b28b28314c --- /dev/null +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/Sorter.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import com.google.cloud.dataflow.sdk.values.KV; +import java.io.IOException; + +/** + * Interface for classes which can sort {@code } pairs by the key. + * + *

            Records must first be added by calling {@link #add(KV)}. Then {@link #sort()} can be called at + * most once. + * + *

            TODO: Support custom comparison functions. + */ +interface Sorter { + + /** + * Adds a given record to the sorter. + * + *

            Records can only be added before calling {@link #sort()}. + */ + void add(KV record) throws IOException; + + /** + * Sorts the added elements and returns an {@link Iterable} over the sorted elements. + * + *

            Can be called at most once. + */ + Iterable> sort() throws IOException; +} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/package-info.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/package-info.java new file mode 100644 index 0000000000..9a06e84b5b --- /dev/null +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/package-info.java @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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. + */ + +/** + * Utility for performing local sort of potentially large sets of values. Will sort in memory and + * spill to disk for external sorting if necessary. + */ +package com.google.cloud.dataflow.contrib.sorter; diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java new file mode 100644 index 0000000000..954642a833 --- /dev/null +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.cloud.dataflow.contrib.sorter.SorterTestUtils.SorterGenerator; +import com.google.cloud.dataflow.sdk.values.KV; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Arrays; + +/** Tests for {@link BufferedExternalSorter}. */ +@RunWith(JUnit4.class) +public class BufferedExternalSorterTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + @SuppressWarnings("unchecked") + @Test + public void testNoFallback() throws Exception { + ExternalSorter mockExternalSorter = mock(ExternalSorter.class); + InMemorySorter mockInMemorySorter = mock(InMemorySorter.class); + BufferedExternalSorter testSorter = + new BufferedExternalSorter(mockExternalSorter, mockInMemorySorter); + + KV[] kvs = + new KV[] { + KV.of(new byte[] {0}, new byte[] {}), + KV.of(new byte[] {0, 1}, new byte[] {}), + KV.of(new byte[] {1}, new byte[] {}) + }; + + when(mockInMemorySorter.addIfRoom(kvs[0])).thenReturn(true); + when(mockInMemorySorter.addIfRoom(kvs[1])).thenReturn(true); + when(mockInMemorySorter.addIfRoom(kvs[2])).thenReturn(true); + when(mockInMemorySorter.sort()).thenReturn(Arrays.asList(kvs[0], kvs[1], kvs[2])); + + testSorter.add(kvs[0]); + testSorter.add(kvs[1]); + testSorter.add(kvs[2]); + + assertEquals(Arrays.asList(kvs[0], kvs[1], kvs[2]), testSorter.sort()); + + // Verify external sorter was never called + verify(mockExternalSorter, never()).add(any(KV.class)); + verify(mockExternalSorter, never()).sort(); + } + + @Test + public void testFallback() throws Exception { + ExternalSorter mockExternalSorter = mock(ExternalSorter.class); + InMemorySorter mockInMemorySorter = mock(InMemorySorter.class); + BufferedExternalSorter testSorter = + new BufferedExternalSorter(mockExternalSorter, mockInMemorySorter); + + @SuppressWarnings("unchecked") + KV[] kvs = + new KV[] { + KV.of(new byte[] {0}, new byte[] {}), + KV.of(new byte[] {0, 1}, new byte[] {}), + KV.of(new byte[] {1}, new byte[] {}) + }; + + when(mockInMemorySorter.addIfRoom(kvs[0])).thenReturn(true); + when(mockInMemorySorter.addIfRoom(kvs[1])).thenReturn(true); + when(mockInMemorySorter.addIfRoom(kvs[2])).thenReturn(false); + when(mockInMemorySorter.sort()).thenReturn(Arrays.asList(kvs[0], kvs[1])); + when(mockExternalSorter.sort()).thenReturn(Arrays.asList(kvs[0], kvs[1], kvs[2])); + + testSorter.add(kvs[0]); + testSorter.add(kvs[1]); + testSorter.add(kvs[2]); + + assertEquals(Arrays.asList(kvs[0], kvs[1], kvs[2]), testSorter.sort()); + + verify(mockExternalSorter, times(1)).add(kvs[0]); + verify(mockExternalSorter, times(1)).add(kvs[1]); + verify(mockExternalSorter, times(1)).add(kvs[2]); + } + + @Test + public void testEmpty() throws Exception { + SorterTestUtils.testEmpty(BufferedExternalSorter.create(new BufferedExternalSorter.Options())); + } + + @Test + public void testSingleElement() throws Exception { + SorterTestUtils.testSingleElement( + BufferedExternalSorter.create(new BufferedExternalSorter.Options())); + } + + @Test + public void testEmptyKeyValueElement() throws Exception { + SorterTestUtils.testEmptyKeyValueElement( + BufferedExternalSorter.create(new BufferedExternalSorter.Options())); + } + + @Test + public void testMultipleIterations() throws Exception { + SorterTestUtils.testMultipleIterations( + BufferedExternalSorter.create(new BufferedExternalSorter.Options())); + } + + @Test + public void testManySortersFewRecords() throws Exception { + SorterTestUtils.testRandom( + new SorterGenerator() { + @Override + public Sorter generateSorter() throws Exception { + return BufferedExternalSorter.create(new BufferedExternalSorter.Options()); + } + }, + 1000000, + 10); + } + + @Test + public void testOneSorterManyRecords() throws Exception { + SorterTestUtils.testRandom( + new SorterGenerator() { + @Override + public Sorter generateSorter() throws Exception { + return BufferedExternalSorter.create(new BufferedExternalSorter.Options()); + } + }, + 1, + 1000000); + } + + @Test + public void testAddAfterSort() throws Exception { + SorterTestUtils.testAddAfterSort( + BufferedExternalSorter.create(new BufferedExternalSorter.Options()), thrown); + fail(); + } + + @Test + public void testSortTwice() throws Exception { + SorterTestUtils.testSortTwice( + BufferedExternalSorter.create(new BufferedExternalSorter.Options()), thrown); + fail(); + } + + @Test + public void testNegativeMemory() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be greater than zero"); + BufferedExternalSorter.Options options = new BufferedExternalSorter.Options(); + options.setMemoryMB(-1); + } +} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java new file mode 100644 index 0000000000..150ffbd633 --- /dev/null +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static org.junit.Assert.fail; + +import com.google.cloud.dataflow.contrib.sorter.SorterTestUtils.SorterGenerator; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Sorter. */ +@RunWith(JUnit4.class) +public class ExternalSorterTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testEmpty() throws Exception { + SorterTestUtils.testEmpty(ExternalSorter.create(new ExternalSorter.Options())); + } + + @Test + public void testSingleElement() throws Exception { + SorterTestUtils.testSingleElement(ExternalSorter.create(new ExternalSorter.Options())); + } + + @Test + public void testEmptyKeyValueElement() throws Exception { + SorterTestUtils.testEmptyKeyValueElement(ExternalSorter.create(new ExternalSorter.Options())); + } + + @Test + public void testMultipleIterations() throws Exception { + SorterTestUtils.testMultipleIterations(ExternalSorter.create(new ExternalSorter.Options())); + } + + @Test + public void testRandom() throws Exception { + SorterTestUtils.testRandom( + new SorterGenerator() { + @Override + public Sorter generateSorter() throws Exception { + return ExternalSorter.create(new ExternalSorter.Options()); + } + }, + 1, + 1000000); + } + + @Test + public void testAddAfterSort() throws Exception { + SorterTestUtils.testAddAfterSort(ExternalSorter.create(new ExternalSorter.Options()), thrown); + fail(); + } + + @Test + public void testSortTwice() throws Exception { + SorterTestUtils.testSortTwice(ExternalSorter.create(new ExternalSorter.Options()), thrown); + fail(); + } + + @Test + public void testNegativeMemory() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be greater than zero"); + ExternalSorter.Options options = new ExternalSorter.Options(); + options.setMemoryMB(-1); + } +} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java new file mode 100644 index 0000000000..1c4e43fc1c --- /dev/null +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.fail; + +import com.google.cloud.dataflow.contrib.sorter.SorterTestUtils.SorterGenerator; +import com.google.cloud.dataflow.sdk.values.KV; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link InMemorySorter}. */ +@RunWith(JUnit4.class) +public class InMemorySorterTest { + @Rule public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testEmpty() throws Exception { + SorterTestUtils.testEmpty(InMemorySorter.create(new InMemorySorter.Options())); + } + + @Test + public void testSingleElement() throws Exception { + SorterTestUtils.testSingleElement(InMemorySorter.create(new InMemorySorter.Options())); + } + + @Test + public void testEmptyKeyValueElement() throws Exception { + SorterTestUtils.testEmptyKeyValueElement(InMemorySorter.create(new InMemorySorter.Options())); + } + + @Test + public void testMultipleIterations() throws Exception { + SorterTestUtils.testMultipleIterations(InMemorySorter.create(new InMemorySorter.Options())); + } + + @Test + public void testManySorters() throws Exception { + SorterTestUtils.testRandom( + new SorterGenerator() { + @Override + public Sorter generateSorter() throws Exception { + return InMemorySorter.create(new InMemorySorter.Options()); + } + }, + 1000000, + 10); + } + + @Test + public void testAddAfterSort() throws Exception { + SorterTestUtils.testAddAfterSort(InMemorySorter.create(new InMemorySorter.Options()), thrown); + fail(); + } + + @Test + public void testSortTwice() throws Exception { + SorterTestUtils.testSortTwice(InMemorySorter.create(new InMemorySorter.Options()), thrown); + fail(); + } + + /** + * Verify an exception is thrown when the in memory sorter runs out of space. + * + * @throws Exception + */ + @Test + public void testOutOfSpace() throws Exception { + thrown.expect(IllegalStateException.class); + thrown.expectMessage(is("No space remaining for in memory sorting")); + SorterTestUtils.testRandom( + new SorterGenerator() { + @Override + public Sorter generateSorter() throws Exception { + InMemorySorter.Options options = new InMemorySorter.Options(); + options.setMemoryMB(1); + return InMemorySorter.create(options); + } + }, + 1, + 10000000); + } + + @Test + public void testAddIfRoom() throws Exception { + InMemorySorter.Options options = new InMemorySorter.Options(); + options.setMemoryMB(1); + InMemorySorter sorter = InMemorySorter.create(options); + + // Should be a few kb less than what the total buffer supports + KV bigRecord = KV.of(new byte[1024 * 500], new byte[1024 * 500]); + + // First add should succeed, second add should fail due to insufficient room + Assert.assertTrue(sorter.addIfRoom(bigRecord)); + Assert.assertFalse(sorter.addIfRoom(bigRecord)); + } + + @Test + public void testAddIfRoomOverhead() throws Exception { + InMemorySorter.Options options = new InMemorySorter.Options(); + options.setMemoryMB(1); + InMemorySorter sorter = InMemorySorter.create(options); + + // No bytes within record, should still run out of room due to memory overhead of record + KV tinyRecord = KV.of(new byte[0], new byte[0]); + + // Verify we can't insert one million records into this one megabyte buffer + boolean stillRoom = true; + for (int i = 0; (i < 1000000) && stillRoom; i++) { + stillRoom = sorter.addIfRoom(tinyRecord); + } + + Assert.assertFalse(stillRoom); + } + + @Test + public void testNegativeMemory() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be greater than zero"); + InMemorySorter.Options options = new InMemorySorter.Options(); + options.setMemoryMB(-1); + } +} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java new file mode 100644 index 0000000000..dd46ae1528 --- /dev/null +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import com.google.cloud.dataflow.sdk.Pipeline; +import com.google.cloud.dataflow.sdk.testing.DataflowAssert; +import com.google.cloud.dataflow.sdk.testing.TestPipeline; +import com.google.cloud.dataflow.sdk.transforms.Create; +import com.google.cloud.dataflow.sdk.transforms.GroupByKey; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.cloud.dataflow.sdk.values.PCollection; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Arrays; + +/** Tests for {@link SortValues} transform. */ +@RunWith(JUnit4.class) +public class SortValuesTest { + + @Test + public void testSecondaryKeySorting() throws Exception { + Pipeline p = TestPipeline.create(); + + // Create a PCollection of > pairs. + PCollection>> input = + p.apply( + Create.of( + Arrays.asList( + KV.of("key1", KV.of("secondaryKey2", 20)), + KV.of("key2", KV.of("secondaryKey2", 200)), + KV.of("key1", KV.of("secondaryKey3", 30)), + KV.of("key1", KV.of("secondaryKey1", 10)), + KV.of("key2", KV.of("secondaryKey1", 100))))); + + // Group by Key, bringing pairs for the same Key together. + PCollection>>> grouped = + input.apply(GroupByKey.>create()); + + // For every Key, sort the iterable of pairs by SecondaryKey. + PCollection>>> groupedAndSorted = + grouped.apply( + SortValues.create(new BufferedExternalSorter.Options())); + + DataflowAssert.that(groupedAndSorted) + .satisfies(new AssertThatHasExpectedContentsForTestSecondaryKeySorting()); + + p.run(); + } + + static class AssertThatHasExpectedContentsForTestSecondaryKeySorting + implements SerializableFunction>>>, Void> { + @SuppressWarnings("unchecked") + @Override + public Void apply(Iterable>>> actual) { + assertThat( + actual, + containsInAnyOrder( + KvMatcher.isKv( + is("key1"), + contains( + KvMatcher.isKv(is("secondaryKey1"), is(10)), + KvMatcher.isKv(is("secondaryKey2"), is(20)), + KvMatcher.isKv(is("secondaryKey3"), is(30)))), + KvMatcher.isKv( + is("key2"), + contains( + KvMatcher.isKv(is("secondaryKey1"), is(100)), + KvMatcher.isKv(is("secondaryKey2"), is(200)))))); + return null; + } + } + + /** Matcher for KVs. Forked from Beam's com.google.cloud.dataflow/sdk/TestUtils.java */ + public static class KvMatcher extends TypeSafeMatcher> { + final Matcher keyMatcher; + final Matcher valueMatcher; + + public static KvMatcher isKv(Matcher keyMatcher, Matcher valueMatcher) { + return new KvMatcher<>(keyMatcher, valueMatcher); + } + + public KvMatcher(Matcher keyMatcher, Matcher valueMatcher) { + this.keyMatcher = keyMatcher; + this.valueMatcher = valueMatcher; + } + + @Override + public boolean matchesSafely(KV kv) { + return keyMatcher.matches(kv.getKey()) && valueMatcher.matches(kv.getValue()); + } + + @Override + public void describeTo(Description description) { + description + .appendText("a KV(") + .appendValue(keyMatcher) + .appendText(", ") + .appendValue(valueMatcher) + .appendText(")"); + } + } +} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SorterTestUtils.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SorterTestUtils.java new file mode 100644 index 0000000000..9aff1f0c11 --- /dev/null +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SorterTestUtils.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.contrib.sorter; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.emptyIterable; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.values.KV; +import com.google.common.primitives.UnsignedBytes; +import org.junit.rules.ExpectedException; + +import java.util.Random; + +/** A set of basic tests for {@link Sorter}s. */ +public class SorterTestUtils { + + public static void testEmpty(Sorter sorter) throws Exception { + assertThat(sorter.sort(), is(emptyIterable())); + } + + @SuppressWarnings("unchecked") + public static void testSingleElement(Sorter sorter) throws Exception { + KV kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2}); + sorter.add(kv); + assertThat(sorter.sort(), contains(kv)); + } + + @SuppressWarnings("unchecked") + public static void testEmptyKeyValueElement(Sorter sorter) throws Exception { + KV kv = KV.of(new byte[] {}, new byte[] {}); + sorter.add(kv); + assertThat(sorter.sort(), contains(kv)); + } + + @SuppressWarnings("unchecked") + public static void testMultipleIterations(Sorter sorter) throws Exception { + KV[] kvs = + new KV[] { + KV.of(new byte[] {0}, new byte[] {}), + KV.of(new byte[] {0, 1}, new byte[] {}), + KV.of(new byte[] {1}, new byte[] {}) + }; + sorter.add(kvs[1]); + sorter.add(kvs[2]); + sorter.add(kvs[0]); + Iterable> sorted = sorter.sort(); + assertThat(sorted, contains(kvs[0], kvs[1], kvs[2])); + // Iterate second time. + assertThat(sorted, contains(kvs[0], kvs[1], kvs[2])); + } + + /** Class that generates a new sorter. Used when performance testing multiple sorter creation. */ + interface SorterGenerator { + Sorter generateSorter() throws Exception; + } + + /** + * Generates random records and executes a test with the provided number of sorters and number of + * records per sorter. + */ + public static void testRandom( + SorterGenerator sorterGenerator, int numSorters, int numRecordsPerSorter) throws Exception { + long start = System.currentTimeMillis(); + for (int i = 0; i < numSorters; ++i) { + Sorter sorter = sorterGenerator.generateSorter(); + Random rnd = new Random(0L); + for (int j = 0; j < numRecordsPerSorter; ++j) { + byte[] key = new byte[8]; + byte[] value = new byte[8]; + rnd.nextBytes(key); + rnd.nextBytes(value); + sorter.add(KV.of(key, value)); + } + + byte[] prevKey = null; + for (KV record : sorter.sort()) { + assertTrue( + prevKey == null + || UnsignedBytes.lexicographicalComparator().compare(prevKey, record.getKey()) < 0); + prevKey = record.getKey(); + } + } + long end = System.currentTimeMillis(); + System.out.println( + "Took " + + (end - start) + + "ms for " + + numRecordsPerSorter * numSorters * 1000.0 / (end - start) + + " records/s"); + } + + /** Tests trying to call add after calling sort. Should throw an exception. */ + public static void testAddAfterSort(Sorter sorter, ExpectedException thrown) throws Exception { + thrown.expect(IllegalStateException.class); + thrown.expectMessage(is("Records can only be added before sort()")); + KV kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2}); + sorter.add(kv); + sorter.sort(); + sorter.add(kv); + } + + /** Tests trying to calling sort twice. Should throw an exception. */ + public static void testSortTwice(Sorter sorter, ExpectedException thrown) throws Exception { + thrown.expect(IllegalStateException.class); + thrown.expectMessage(is("sort() can only be called once.")); + KV kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2}); + sorter.add(kv); + sorter.sort(); + sorter.sort(); + } +} From 9e2759166573026d889860bb99f0ec06497f314c Mon Sep 17 00:00:00 2001 From: Mitch Shanklin Date: Thu, 3 Nov 2016 18:01:50 -0700 Subject: [PATCH 620/751] Response to PR comments from davorbonaci@ --- contrib/sorter/AUTHORS.md | 5 ----- contrib/sorter/README.md | 2 +- .../google/cloud/dataflow/contrib/sorter/SortValuesTest.java | 2 +- 3 files changed, 2 insertions(+), 7 deletions(-) delete mode 100644 contrib/sorter/AUTHORS.md diff --git a/contrib/sorter/AUTHORS.md b/contrib/sorter/AUTHORS.md deleted file mode 100644 index cb0be27052..0000000000 --- a/contrib/sorter/AUTHORS.md +++ /dev/null @@ -1,5 +0,0 @@ -# Authors of 'sorter' module - -The following is the official list of authors for copyright purposes of this community-contributed module. - - Google Inc. diff --git a/contrib/sorter/README.md b/contrib/sorter/README.md index 65dfc7f68a..29f45b8900 100644 --- a/contrib/sorter/README.md +++ b/contrib/sorter/README.md @@ -2,7 +2,7 @@ This module provides the SortValues transform, which takes a `PCollection>>>` and produces a `PCollection>>>` where, for each primary key `K` the paired `Iterable>` has been sorted by the byte encoding of secondary key (`K2`). It will efficiently and scalably sort the iterables, even if they are large (do not fit in memory). ##Caveats -* This transform performs value-only sorting; the iterable accompanying each key is sorted, but *there is no relationship between different keys*, as Beam does not support any defined relationship between different elements in a PCollection. +* This transform performs value-only sorting; the iterable accompanying each key is sorted, but *there is no relationship between different keys*, as Dataflow does not support any defined relationship between different elements in a PCollection. * Each `Iterable>` is sorted on a single worker using local memory and disk. This means that `SortValues` may be a performance and/or scalability bottleneck when used in different pipelines. For example, users are discouraged from using `SortValues` on a `PCollection` of a single element to globally sort a large `PCollection`. ##Options diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java index dd46ae1528..bb7273bad6 100644 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java @@ -95,7 +95,7 @@ public Void apply(Iterable>>> actual) { } } - /** Matcher for KVs. Forked from Beam's com.google.cloud.dataflow/sdk/TestUtils.java */ + /** Matcher for KVs. Forked from com.google.cloud.dataflow/sdk/TestUtils.java */ public static class KvMatcher extends TypeSafeMatcher> { final Matcher keyMatcher; final Matcher valueMatcher; From 5b8e5f8198c6a180fa4f4e0c15fc36b2f9bc76a8 Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Fri, 4 Nov 2016 15:33:02 -0700 Subject: [PATCH 621/751] Update maven compiler plugin to 3.1 to match sdk. --- contrib/kafka/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/kafka/pom.xml b/contrib/kafka/pom.xml index 735b38cd8e..4beecd7ba5 100644 --- a/contrib/kafka/pom.xml +++ b/contrib/kafka/pom.xml @@ -44,7 +44,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.2 + 3.1 1.7 1.7 From b404763415ab29b006f1675fd4f5286768380da7 Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Wed, 9 Nov 2016 11:38:20 -0800 Subject: [PATCH 622/751] Backport Apache Beam PR #1322 https://github.com/apache/incubator-beam/commit/752a8da377d8bb17a61826bd7e00bd3798c23881 --- .../java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java index 91efb43f35..c5aa029531 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java @@ -680,7 +680,7 @@ private void checkArray(String context, TypeDescriptor type, Schema schema) { } else { // If it was an unknown type encoded as an array, be conservative and assume // that we don't know anything about the order. - reportError(context, "encoding %s as an ARRAY was unexpected"); + reportError(context, "encoding %s as an ARRAY was unexpected", type); return; } From fdbb51f03c7ab6e4ecd5f07286937ef850f52ff5 Mon Sep 17 00:00:00 2001 From: Eugene Kirpichov Date: Mon, 14 Nov 2016 11:42:40 -0800 Subject: [PATCH 623/751] FileBasedSink removes temp files from successful bundles This is a weaker but backward-compatible version of respective Beam changes: https://github.com/apache/incubator-beam/pull/1050 https://github.com/apache/incubator-beam/pull/1278 --- .../cloud/dataflow/sdk/io/FileBasedSink.java | 34 ++++++++++++++++--- .../dataflow/sdk/io/FileBasedSinkTest.java | 14 +++++--- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index 4ed6c7216e..87102e1bac 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -44,7 +44,9 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; /** * Abstract {@link Sink} for file-based output. An implementation of FileBasedSink writes file-based @@ -312,7 +314,7 @@ public void finalize(Iterable writerResults, PipelineOptions options // Optionally remove temporary files. if (temporaryFileRetention == TemporaryFileRetention.REMOVE) { - removeTemporaryFiles(options); + removeTemporaryFiles(files, options); } } @@ -369,22 +371,44 @@ protected final List generateDestinationFilenames(int numFiles) { return destFilenames; } + /** + * Use {@link #removeTemporaryFiles(Collection, PipelineOptions)} instead. + */ + @Deprecated + protected final void removeTemporaryFiles(PipelineOptions options) throws IOException { + removeTemporaryFiles(Collections.emptyList(), options); + } + /** * Removes temporary output files. Uses the temporary filename to find files to remove. * + *

            Additionally, to partially mitigate the effects of filesystems with eventually-consistent + * directory matching APIs, takes a list of files that are known to exist - i.e. removes the + * union of the known files and files that the filesystem says exist in the directory. + * + *

            Assumes that, if globbing had been strongly consistent, it would have matched all + * of knownFiles - i.e. on a strongly consistent filesystem, knownFiles can be ignored. + * *

            Can be called from subclasses that override {@link FileBasedWriteOperation#finalize}. * Note:If finalize is overridden and does not rename or otherwise finalize * temporary files, this method will remove them. */ - protected final void removeTemporaryFiles(PipelineOptions options) throws IOException { + protected final void removeTemporaryFiles( + Collection knownFiles, PipelineOptions options) throws IOException { String pattern = buildTemporaryFilename(baseTemporaryFilename, "*"); LOG.debug("Finding temporary bundle output files matching {}.", pattern); FileOperations fileOperations = FileOperationsFactory.getFileOperations(pattern, options); IOChannelFactory factory = IOChannelUtils.getFactory(pattern); Collection matches = factory.match(pattern); - LOG.debug("{} temporary files matched {}", matches.size(), pattern); - LOG.debug("Removing {} files.", matches.size()); - fileOperations.remove(matches); + Set allMatches = new HashSet<>(matches); + allMatches.addAll(knownFiles); + LOG.debug( + "Removing {} temporary files matching {} ({} matched glob, {} additional known files)", + allMatches.size(), + pattern, + matches.size(), + allMatches.size() - matches.size()); + fileOperations.remove(allMatches); } /** diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java index da23f3a562..fc81db8958 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java @@ -248,22 +248,28 @@ private void testRemoveTemporaryFiles(int numFiles, String baseTemporaryFilename PipelineOptions options = PipelineOptionsFactory.create(); SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation(baseTemporaryFilename); - List temporaryFiles = new ArrayList<>(); + List temporaryFiles = new ArrayList<>(); List outputFiles = new ArrayList<>(); for (int i = 0; i < numFiles; i++) { File tmpFile = tmpFolder.newFile( FileBasedWriteOperation.buildTemporaryFilename(baseTemporaryFilename, "" + i)); - temporaryFiles.add(tmpFile); + temporaryFiles.add(tmpFile.getAbsolutePath()); File outputFile = tmpFolder.newFile(baseOutputFilename + i); outputFiles.add(outputFile); } - writeOp.removeTemporaryFiles(options); + File extraFile = new File(tmpFolder.newFolder("extra"), "foo"); + assertTrue(extraFile.createNewFile()); + + temporaryFiles.add(extraFile.getAbsolutePath()); + + writeOp.removeTemporaryFiles(temporaryFiles, options); for (int i = 0; i < numFiles; i++) { - assertFalse(temporaryFiles.get(i).exists()); + assertFalse(new File(temporaryFiles.get(i)).exists()); assertTrue(outputFiles.get(i).exists()); } + assertFalse(extraFile.exists()); } /** From 5305b351c6cae36e1ee47d47ac11a2f8731b1b71 Mon Sep 17 00:00:00 2001 From: Daniel Mills Date: Mon, 28 Nov 2016 14:16:20 -0800 Subject: [PATCH 624/751] Use a retrying Dataflow Client for DataflowPipelineJob --- .../dataflow/sdk/runners/DataflowPipelineRunner.java | 2 +- .../com/google/cloud/dataflow/sdk/util/Transport.java | 11 ----------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 8099f0955e..7dc0e9295b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -625,7 +625,7 @@ public DataflowPipelineJob run(Pipeline pipeline) { // regularly and need not be retried automatically. DataflowPipelineJob dataflowPipelineJob = new DataflowPipelineJob(options.getProject(), jobResult.getId(), - Transport.newRawDataflowClient(options).build(), aggregatorTransforms); + Transport.newDataflowClient(options).build(), aggregatorTransforms); // If the service returned client request id, the SDK needs to compare it // with the original id generated in the request, if they are not the same diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java index 15fe286339..f2de47e390 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java @@ -157,17 +157,6 @@ public static Clouddebugger.Builder newClouddebuggerClient(DataflowPipelineOptio .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); } - /** - * Returns a Dataflow client that does not automatically retry failed - * requests. - */ - public static Dataflow.Builder - newRawDataflowClient(DataflowPipelineOptions options) { - return newDataflowClient(options) - .setHttpRequestInitializer(options.getGcpCredential()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - /** * Returns a Cloud Storage client builder. * From 7100ddb5ec0c68e01f3ca96997613c2c4282995f Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Thu, 1 Dec 2016 11:06:24 -0800 Subject: [PATCH 625/751] Suppress spurious rebuilds due to missing package-info.class --- pom.xml | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/pom.xml b/pom.xml index 2297b2a4ef..cdcb9a8095 100644 --- a/pom.xml +++ b/pom.xml @@ -92,6 +92,9 @@ 3.1.4 v1-rev71-1.22.0 4.4.1 + + -Xpkginfo:always + nothing pom @@ -112,6 +115,49 @@ -Xdoclint:-missing + + + java7-packageinfo + + 1.7 + + + + -Xpkginfo:legacy + **/package-info.java + + + + + maven-compiler-plugin + + + + compile-package-info + + compile + + compile + + + -Xpkginfo:always + + + **/package-info.java + + + + + + + + @@ -145,6 +191,23 @@ false + + + default-compile + + compile + + compile + + + ${compiler.default.pkginfo.flag} + + + ${compiler.default.exclude} + + + + From 6d580cb7a936811117a85da79d60b1ec09a1accc Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Thu, 1 Dec 2016 12:58:12 -0800 Subject: [PATCH 626/751] KafkaIO should return one split for each of partition. This is the actual unit of parallelism for Kafka topic. desiredNumSplits that Dataflow passes to a custom source is not very low when maxNumWorkers is set, it asks for just one split for each of the workers. This limits use of CPU cores on the workers essentially making autoscaling use more resources without improving peformance. This includes a hack to force single split in many unit tests since DirectPipelineRunner and InProcessPipelineRunner don't seem to read from more than one split. --- .../cloud/dataflow/contrib/kafka/KafkaIO.java | 52 +++++++++--------- .../dataflow/contrib/kafka/KafkaIOTest.java | 54 +++++++++++-------- 2 files changed, 59 insertions(+), 47 deletions(-) diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java index a18062da56..0d83ee45bb 100644 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java @@ -44,7 +44,6 @@ import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; @@ -731,7 +730,6 @@ public List> generateInitialSplits( // (a) fetch partitions for each topic // (b) sort by - // (c) round-robin assign the partitions to splits if (partitions.isEmpty()) { try (Consumer consumer = consumerFactoryFn.apply(consumerConfig)) { @@ -754,43 +752,45 @@ public int compare(TopicPartition tp1, TopicPartition tp2) { } }); - checkArgument(desiredNumSplits > 0); checkState( partitions.size() > 0, "Could not find any partitions. Please check Kafka configuration and topic names"); - int numSplits = Math.min(desiredNumSplits, partitions.size()); - List> assignments = new ArrayList<>(numSplits); - - for (int i = 0; i < numSplits; i++) { - assignments.add(new ArrayList()); - } - for (int i = 0; i < partitions.size(); i++) { - assignments.get(i % numSplits).add(partitions.get(i)); - } - - List> result = new ArrayList<>(numSplits); - - for (int i = 0; i < numSplits; i++) { - List assignedToSplit = assignments.get(i); - - LOG.info( - "Partitions assigned to split {} (total {}): {}", - i, - assignedToSplit.size(), - Joiner.on(",").join(assignedToSplit)); + List> result = new ArrayList<>(partitions.size()); + if (Boolean.TRUE.equals(consumerConfig.get("force.single.split.for.dastaflow.tests"))) { + // Work around/hack for Direct/InProcess runner in Dataflow not supporting multiple splits. + LOG.info("Reading all the partitions in single split"); result.add( - new UnboundedKafkaSource( - i, + new UnboundedKafkaSource<>( + 0, this.topics, - assignedToSplit, + partitions, this.keyCoder, this.valueCoder, this.timestampFn, this.watermarkFn, this.consumerFactoryFn, this.consumerConfig)); + } else { + // one split for each partition. + for (int i = 0; i < partitions.size(); i++) { + TopicPartition partition = partitions.get(i); + + LOG.info("Partition assigned to split {} : {}", i, partition); + + result.add( + new UnboundedKafkaSource<>( + i, + this.topics, + ImmutableList.of(partition), + this.keyCoder, + this.valueCoder, + this.timestampFn, + this.watermarkFn, + this.consumerFactoryFn, + this.consumerConfig)); + } } return result; diff --git a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java index af8d674831..aeae6cdb4d 100644 --- a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java +++ b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java @@ -126,7 +126,7 @@ private static MockConsumer mkMockConsumer( tp.topic(), tp.partition(), offsets[pIdx]++, - ByteBuffer.wrap(new byte[8]).putInt(i).array(), + ByteBuffer.wrap(new byte[4]).putInt(i).array(), // key is 4 byte record id ByteBuffer.wrap(new byte[8]).putLong(i).array())); // value is 8 byte record id } @@ -172,11 +172,12 @@ public Consumer apply(Map config) { } /** - * Creates a consumer with two topics, with 5 partitions each. numElements are (round-robin) - * assigned all the 10 partitions. + * Creates a consumer with two topics, with 10 partitions each. numElements are (round-robin) + * assigned all the 20 partitions. */ private static KafkaIO.TypedRead mkKafkaReadTransform( - int numElements, @Nullable SerializableFunction, Instant> timestampFn) { + int numElements, boolean forceSingleSplit, + @Nullable SerializableFunction, Instant> timestampFn) { List topics = ImmutableList.of("topic_a", "topic_b"); @@ -189,6 +190,11 @@ private static KafkaIO.TypedRead mkKafkaReadTransform( .withValueCoder(BigEndianLongCoder.of()) .withMaxNumRecords(numElements); + if (forceSingleSplit) { + reader = reader.updateConsumerProperties( + ImmutableMap.of("force.single.split.for.dataflow.tests", true)); + } + if (timestampFn != null) { return reader.withTimestampFn(timestampFn); } else { @@ -232,11 +238,13 @@ public static void addCountingAsserts(PCollection input, long numElements) @Test public void testUnboundedSource() { Pipeline p = TestPipeline.create(); + int numElements = 1000; PCollection input = p - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, true, + new ValueAsTimestampFn()).withoutMetadata()) .apply(Values.create()); addCountingAsserts(input, numElements); @@ -282,7 +290,8 @@ public void testUnboundedSourceTimestamps() { PCollection input = p - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, true, + new ValueAsTimestampFn()).withoutMetadata()) .apply(Values.create()); addCountingAsserts(input, numElements); @@ -309,16 +318,16 @@ public void processElement(ProcessContext ctx) throws Exception { public void testUnboundedSourceSplits() throws Exception { Pipeline p = TestPipeline.create(); int numElements = 1000; - int numSplits = 10; + int numSplits = 20; + // create source with 20 partitions. UnboundedSource, ?> initial = - mkKafkaReadTransform(numElements, null).makeSource(); - List< - ? extends - UnboundedSource< - com.google.cloud.dataflow.contrib.kafka.KafkaRecord, ?>> - splits = initial.generateInitialSplits(numSplits, p.getOptions()); - assertEquals("Expected exact splitting", numSplits, splits.size()); + mkKafkaReadTransform(numElements, false, null).makeSource(); + + List, ?>> splits = + initial.generateInitialSplits(1, p.getOptions()); + + assertEquals("KafkaIO should ignore desiredNumSplits", numSplits, splits.size()); long elementsPerSplit = numElements / numSplits; assertEquals("Expected even splits", numElements, elementsPerSplit * numSplits); @@ -362,14 +371,14 @@ private static void advanceOnce(UnboundedReader reader) throws IOException { public void testUnboundedSourceCheckpointMark() throws Exception { int numElements = 85; // 85 to make sure some partitions have more records than other. - // create a single split: + // take the first split. UnboundedSource< com.google.cloud.dataflow.contrib.kafka.KafkaRecord, com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> source = - mkKafkaReadTransform(numElements, new ValueAsTimestampFn()) + mkKafkaReadTransform(numElements, true, new ValueAsTimestampFn()) .makeSource() - .generateInitialSplits(1, PipelineOptionsFactory.fromArgs(new String[0]).create()) + .generateInitialSplits(5, PipelineOptionsFactory.fromArgs(new String[0]).create()) .get(0); UnboundedReader> reader = @@ -429,7 +438,8 @@ public void testSink() throws Exception { String topic = "test"; pipeline - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, true, + new ValueAsTimestampFn()).withoutMetadata()) .apply( com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() .withBootstrapServers("none") @@ -461,7 +471,8 @@ public void testValuesSink() throws Exception { String topic = "test"; pipeline - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, true, + new ValueAsTimestampFn()).withoutMetadata()) .apply(Values.create()) // there are no keys .apply( com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() @@ -487,7 +498,7 @@ public void testSinkWithSendErrors() throws Throwable { // TODO: Ideally we want the pipeline to run to completion by retrying bundles that fail. // We limit the number of errors injected to 10 below. This would reflect a real streaming - // pipeline. But I am sure how to achieve that. For now expect an exception: + // pipeline. But I am not sure how to achieve that. For now expect an exception: thrown.expect(InjectedErrorException.class); thrown.expectMessage("Injected Error #1"); @@ -504,7 +515,8 @@ public void testSinkWithSendErrors() throws Throwable { new ProducerSendCompletionThread(10, 100).start(); pipeline - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, true, + new ValueAsTimestampFn()).withoutMetadata()) .apply( com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() .withBootstrapServers("none") From cdd5f5fca9f08dbf211f0303d81510f473167401 Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Thu, 1 Dec 2016 15:01:16 -0800 Subject: [PATCH 627/751] Based on Thomas comment. DirectPipelineRunner does not call getInitialSplits(). Rather than forcing single split through a special config, force it when it invoked from within KafkaIO itself. --- .../cloud/dataflow/contrib/kafka/KafkaIO.java | 51 ++++++++++--------- .../dataflow/contrib/kafka/KafkaIOTest.java | 39 +++++--------- 2 files changed, 38 insertions(+), 52 deletions(-) diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java index 0d83ee45bb..f5422d33d6 100644 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java @@ -756,41 +756,41 @@ public int compare(TopicPartition tp1, TopicPartition tp2) { partitions.size() > 0, "Could not find any partitions. Please check Kafka configuration and topic names"); + if (desiredNumSplits < 0) { + // special case for DirectPipelineRunner (used in tests) in Dataflow. Return single split. + return ImmutableList.of( + new UnboundedKafkaSource<>( + 0, + this.topics, + partitions, + this.keyCoder, + this.valueCoder, + this.timestampFn, + this.watermarkFn, + this.consumerFactoryFn, + this.consumerConfig) + ); + } + List> result = new ArrayList<>(partitions.size()); - if (Boolean.TRUE.equals(consumerConfig.get("force.single.split.for.dastaflow.tests"))) { - // Work around/hack for Direct/InProcess runner in Dataflow not supporting multiple splits. - LOG.info("Reading all the partitions in single split"); + // one split for each partition. + for (int i = 0; i < partitions.size(); i++) { + TopicPartition partition = partitions.get(i); + + LOG.info("Partition assigned to split {} : {}", i, partition); + result.add( new UnboundedKafkaSource<>( - 0, + i, this.topics, - partitions, + ImmutableList.of(partition), this.keyCoder, this.valueCoder, this.timestampFn, this.watermarkFn, this.consumerFactoryFn, this.consumerConfig)); - } else { - // one split for each partition. - for (int i = 0; i < partitions.size(); i++) { - TopicPartition partition = partitions.get(i); - - LOG.info("Partition assigned to split {} : {}", i, partition); - - result.add( - new UnboundedKafkaSource<>( - i, - this.topics, - ImmutableList.of(partition), - this.keyCoder, - this.valueCoder, - this.timestampFn, - this.watermarkFn, - this.consumerFactoryFn, - this.consumerConfig)); - } } return result; @@ -803,8 +803,9 @@ public UnboundedKafkaReader createReader( if (assignedPartitions.isEmpty()) { LOG.warn("Looks like generateSplits() is not called. Generate single split."); try { + return new UnboundedKafkaReader( - generateInitialSplits(1, options).get(0), checkpointMark); + generateInitialSplits(-1, options).get(0), checkpointMark); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java index aeae6cdb4d..7cfa8a0e94 100644 --- a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java +++ b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java @@ -126,7 +126,7 @@ private static MockConsumer mkMockConsumer( tp.topic(), tp.partition(), offsets[pIdx]++, - ByteBuffer.wrap(new byte[4]).putInt(i).array(), + ByteBuffer.wrap(new byte[8]).putInt(i).array(), // key is 4 byte record id ByteBuffer.wrap(new byte[8]).putLong(i).array())); // value is 8 byte record id } @@ -176,8 +176,7 @@ public Consumer apply(Map config) { * assigned all the 20 partitions. */ private static KafkaIO.TypedRead mkKafkaReadTransform( - int numElements, boolean forceSingleSplit, - @Nullable SerializableFunction, Instant> timestampFn) { + int numElements, @Nullable SerializableFunction, Instant> timestampFn) { List topics = ImmutableList.of("topic_a", "topic_b"); @@ -190,11 +189,6 @@ private static KafkaIO.TypedRead mkKafkaReadTransform( .withValueCoder(BigEndianLongCoder.of()) .withMaxNumRecords(numElements); - if (forceSingleSplit) { - reader = reader.updateConsumerProperties( - ImmutableMap.of("force.single.split.for.dataflow.tests", true)); - } - if (timestampFn != null) { return reader.withTimestampFn(timestampFn); } else { @@ -238,13 +232,11 @@ public static void addCountingAsserts(PCollection input, long numElements) @Test public void testUnboundedSource() { Pipeline p = TestPipeline.create(); - int numElements = 1000; PCollection input = p - .apply(mkKafkaReadTransform(numElements, true, - new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) .apply(Values.create()); addCountingAsserts(input, numElements); @@ -290,8 +282,7 @@ public void testUnboundedSourceTimestamps() { PCollection input = p - .apply(mkKafkaReadTransform(numElements, true, - new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) .apply(Values.create()); addCountingAsserts(input, numElements); @@ -320,13 +311,10 @@ public void testUnboundedSourceSplits() throws Exception { int numElements = 1000; int numSplits = 20; - // create source with 20 partitions. UnboundedSource, ?> initial = - mkKafkaReadTransform(numElements, false, null).makeSource(); - + mkKafkaReadTransform(numElements, null).makeSource(); List, ?>> splits = initial.generateInitialSplits(1, p.getOptions()); - assertEquals("KafkaIO should ignore desiredNumSplits", numSplits, splits.size()); long elementsPerSplit = numElements / numSplits; @@ -371,14 +359,14 @@ private static void advanceOnce(UnboundedReader reader) throws IOException { public void testUnboundedSourceCheckpointMark() throws Exception { int numElements = 85; // 85 to make sure some partitions have more records than other. - // take the first split. + // create a single split: UnboundedSource< com.google.cloud.dataflow.contrib.kafka.KafkaRecord, com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> source = - mkKafkaReadTransform(numElements, true, new ValueAsTimestampFn()) + mkKafkaReadTransform(numElements, new ValueAsTimestampFn()) .makeSource() - .generateInitialSplits(5, PipelineOptionsFactory.fromArgs(new String[0]).create()) + .generateInitialSplits(-1, PipelineOptionsFactory.fromArgs(new String[0]).create()) .get(0); UnboundedReader> reader = @@ -438,8 +426,7 @@ public void testSink() throws Exception { String topic = "test"; pipeline - .apply(mkKafkaReadTransform(numElements, true, - new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) .apply( com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() .withBootstrapServers("none") @@ -471,8 +458,7 @@ public void testValuesSink() throws Exception { String topic = "test"; pipeline - .apply(mkKafkaReadTransform(numElements, true, - new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) .apply(Values.create()) // there are no keys .apply( com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() @@ -498,7 +484,7 @@ public void testSinkWithSendErrors() throws Throwable { // TODO: Ideally we want the pipeline to run to completion by retrying bundles that fail. // We limit the number of errors injected to 10 below. This would reflect a real streaming - // pipeline. But I am not sure how to achieve that. For now expect an exception: + // pipeline. But I am sure how to achieve that. For now expect an exception: thrown.expect(InjectedErrorException.class); thrown.expectMessage("Injected Error #1"); @@ -515,8 +501,7 @@ public void testSinkWithSendErrors() throws Throwable { new ProducerSendCompletionThread(10, 100).start(); pipeline - .apply(mkKafkaReadTransform(numElements, true, - new ValueAsTimestampFn()).withoutMetadata()) + .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) .apply( com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() .withBootstrapServers("none") From 75eb7943521b61589073adaee72a65451a14961b Mon Sep 17 00:00:00 2001 From: Sam Whittle Date: Tue, 6 Dec 2016 15:32:17 -0800 Subject: [PATCH 628/751] Improve ReduceFnRunner prefetching Add prefetch* methods for prefetching state matching existing methods. Prefetch triggers in processElements. Replace onTimer with batched onTimers method to allow prefetching across timers. --- .../sdk/util/BatchTimerInternals.java | 22 +- .../GroupAlsoByWindowViaWindowSetDoFn.java | 6 +- .../dataflow/sdk/util/PaneInfoTracker.java | 4 + .../sdk/util/ReduceFnContextFactory.java | 9 +- .../dataflow/sdk/util/ReduceFnRunner.java | 490 +++++++++++------- .../dataflow/sdk/util/TriggerRunner.java | 15 +- .../dataflow/sdk/util/WatermarkHold.java | 5 + .../sdk/util/BatchTimerInternalsTest.java | 55 +- .../dataflow/sdk/util/ReduceFnTester.java | 28 +- 9 files changed, 407 insertions(+), 227 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java index dc41f7db3b..ca34165927 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java @@ -23,6 +23,7 @@ import org.joda.time.Instant; +import java.util.ArrayList; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Set; @@ -124,16 +125,19 @@ private void advance(ReduceFnRunner runner, Instant newTime, TimeDom PriorityQueue timers = queue(domain); boolean shouldFire = false; - do { - TimerData timer = timers.peek(); - // Timers fire if the new time is ahead of the timer - shouldFire = timer != null && newTime.isAfter(timer.getTimestamp()); - if (shouldFire) { - // Remove before firing, so that if the trigger adds another identical + while (true) { + ArrayList firedTimers = new ArrayList(); + while (!timers.isEmpty() && newTime.isAfter(timers.peek().getTimestamp())) { + // Remove before firing, so that if the callback adds another identical // timer we don't remove it. - timers.remove(); - runner.onTimer(timer); + TimerData timer = timers.remove(); + existingTimers.remove(timer); + firedTimers.add(timer); } - } while (shouldFire); + if (firedTimers.isEmpty()) { + break; + } + runner.onTimers(firedTimers); + } } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java index 89a4fcb720..5110ff199f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java @@ -20,7 +20,6 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.util.DoFnRunner.ReduceFnExecutor; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.values.KV; @@ -81,9 +80,7 @@ public void processElement(ProcessContext c) throws Exception { c.getPipelineOptions()); reduceFnRunner.processElements(element.elementsIterable()); - for (TimerData timer : element.timersIterable()) { - reduceFnRunner.onTimer(timer); - } + reduceFnRunner.onTimers(element.timersIterable()); reduceFnRunner.persist(); } @@ -101,4 +98,3 @@ public Aggregator getDroppedDueToLatenessAggregator() { return droppedDueToLateness; } } - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java index 0cc6a048c9..934917bb1e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java @@ -51,6 +51,10 @@ public void clear(StateAccessor state) { state.access(PANE_INFO_TAG).clear(); } + public void prefetchPaneInfo(ReduceFn.Context context) { + context.state().access(PaneInfoTracker.PANE_INFO_TAG).readLater(); + } + /** * Return a ({@link ReadableState} for) the pane info appropriate for {@code context}. The pane * info includes the timing for the pane, who's calculation is quite subtle. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java index dc97c58a28..06ae2e6593 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java @@ -24,7 +24,6 @@ import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateAccessor; import com.google.cloud.dataflow.sdk.util.state.StateContext; @@ -99,7 +98,7 @@ public ReduceFn.ProcessValueContext forValue( } public ReduceFn.OnTriggerContext forTrigger(W window, - ReadableState pane, StateStyle style, OnTriggerCallbacks callbacks) { + PaneInfo pane, StateStyle style, OnTriggerCallbacks callbacks) { return new OnTriggerContextImpl(stateAccessor(window, style), pane, callbacks); } @@ -371,11 +370,11 @@ public Timers timers() { private class OnTriggerContextImpl extends ReduceFn.OnTriggerContext { private final StateAccessorImpl state; - private final ReadableState pane; + private final PaneInfo pane; private final OnTriggerCallbacks callbacks; private final TimersImpl timers; - private OnTriggerContextImpl(StateAccessorImpl state, ReadableState pane, + private OnTriggerContextImpl(StateAccessorImpl state, PaneInfo pane, OnTriggerCallbacks callbacks) { reduceFn.super(); this.state = state; @@ -406,7 +405,7 @@ public StateAccessor state() { @Override public PaneInfo paneInfo() { - return pane.read(); + return pane; } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java index 9322efcbc1..500d755083 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java @@ -34,13 +34,14 @@ import com.google.cloud.dataflow.sdk.util.ReduceFnContextFactory.StateStyle; import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.ReadableState; import com.google.cloud.dataflow.sdk.util.state.StateInternals; import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowNamespace; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMap; +import com.google.common.base.Function; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; import org.joda.time.Duration; import org.joda.time.Instant; @@ -50,6 +51,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -254,6 +256,32 @@ boolean hasNoActiveWindows() { return activeWindows.getActiveAndNewWindows().isEmpty(); } + private Set openWindows(Collection windows) { + Set result = new HashSet<>(); + for (W window : windows) { + ReduceFn.Context directContext = contextFactory.base( + window, StateStyle.DIRECT); + if (!triggerRunner.isClosed(directContext.state())) { + result.add(window); + } + } + return result; + } + + private Collection windowsThatShouldFire(Set windows) throws Exception { + Collection result = new ArrayList<>(); + // Filter out timers that didn't trigger. + for (W window : windows) { + ReduceFn.Context directContext = + contextFactory.base(window, StateStyle.DIRECT); + if (triggerRunner.shouldFire( + directContext.window(), directContext.timers(), directContext.state())) { + result.add(window); + } + } + return result; + } + /** * Incorporate {@code values} into the underlying reduce function, and manage holds, timers, * triggers, and window merging. @@ -279,25 +307,54 @@ boolean hasNoActiveWindows() { * */ public void processElements(Iterable> values) throws Exception { + if (!values.iterator().hasNext()) { + return; + } + + // Determine all the windows for elements. + Set windows = collectWindows(values); // If an incoming element introduces a new window, attempt to merge it into an existing // window eagerly. - Map windowToMergeResult = collectAndMergeWindows(values); + Map windowToMergeResult = mergeWindows(windows); + if (!windowToMergeResult.isEmpty()) { + // Update windows by removing all windows that were merged away and adding + // the windows they were merged to. We add after completing all the + // removals to avoid removing a window that was also added. + List addedWindows = new ArrayList<>(windowToMergeResult.size()); + for (Map.Entry entry : windowToMergeResult.entrySet()) { + windows.remove(entry.getKey()); + addedWindows.add(entry.getValue()); + } + windows.addAll(addedWindows); + } - Set windowsToConsider = new HashSet<>(); + prefetchWindowsForValues(windows); - // Process each element, using the updated activeWindows determined by collectAndMergeWindows. + // All windows that are open before element processing may need to fire. + Set windowsToConsider = openWindows(windows); + + // Process each element, using the updated activeWindows determined by mergeWindows. for (WindowedValue value : values) { - windowsToConsider.addAll(processElement(windowToMergeResult, value)); + processElement(windowToMergeResult, value); } - // Trigger output from any window for which the trigger is ready + // Now that we've processed the elements, see if any of the windows need to fire. + // Prefetch state necessary to determine if the triggers should fire. for (W mergedWindow : windowsToConsider) { - ReduceFn.Context directContext = - contextFactory.base(mergedWindow, StateStyle.DIRECT); - ReduceFn.Context renamedContext = - contextFactory.base(mergedWindow, StateStyle.RENAMED); - triggerRunner.prefetchShouldFire(mergedWindow, directContext.state()); - emitIfAppropriate(directContext, renamedContext); + triggerRunner.prefetchShouldFire( + mergedWindow, contextFactory.base(mergedWindow, StateStyle.DIRECT).state()); + } + // Filter to windows that are firing. + Collection windowsToFire = windowsThatShouldFire(windowsToConsider); + // Prefetch windows that are firing. + for (W window : windowsToFire) { + prefetchEmit(contextFactory.base(window, StateStyle.DIRECT), + contextFactory.base(window, StateStyle.RENAMED)); + } + // Trigger output from firing windows. + for (W window : windowsToFire) { + emit(contextFactory.base(window, StateStyle.DIRECT), + contextFactory.base(window, StateStyle.RENAMED)); } // We're all done with merging and emitting elements so can compress the activeWindow state. @@ -311,52 +368,61 @@ public void persist() { } /** - * Extract the windows associated with the values, and invoke merge. Return a map - * from windows to the merge result window. If a window is not in the domain of - * the result map then it did not get merged into a different window. + * Extract the windows associated with the values. */ - private Map collectAndMergeWindows(Iterable> values) - throws Exception { - // No-op if no merging can take place + private Set collectWindows(Iterable> values) throws Exception { + Set windows = new HashSet<>(); + for (WindowedValue value : values) { + for (BoundedWindow untypedWindow : value.getWindows()) { + @SuppressWarnings("unchecked") + W window = (W) untypedWindow; + windows.add(window); + } + } + return windows; + } + + /** + * Invoke merge for the given windows and return a map from windows to the + * merge result window. Windows that were not merged are not present in the + * map. + */ + private Map mergeWindows(Set windows) throws Exception { if (windowingStrategy.getWindowFn().isNonMerging()) { - return ImmutableMap.of(); + // Return an empty map, indicating that every window is not merged. + return Collections.emptyMap(); } + Map windowToMergeResult = new HashMap<>(); // Collect the windows from all elements (except those which are too late) and // make sure they are already in the active window set or are added as NEW windows. - for (WindowedValue value : values) { - for (BoundedWindow untypedWindow : value.getWindows()) { - @SuppressWarnings("unchecked") - W window = (W) untypedWindow; - - // For backwards compat with pre 1.4 only. - // We may still have ACTIVE windows with multiple state addresses, representing - // a window who's state has not yet been eagerly merged. - // We'll go ahead and merge that state now so that we don't have to worry about - // this legacy case anywhere else. - if (activeWindows.isActive(window)) { - Set stateAddressWindows = activeWindows.readStateAddresses(window); - if (stateAddressWindows.size() > 1) { - // This is a legacy window who's state has not been eagerly merged. - // Do that now. - ReduceFn.OnMergeContext premergeContext = - contextFactory.forPremerge(window); - reduceFn.onMerge(premergeContext); - watermarkHold.onMerge(premergeContext); - activeWindows.merged(window); - } + for (W window : windows) { + // For backwards compat with pre 1.4 only. + // We may still have ACTIVE windows with multiple state addresses, representing + // a window who's state has not yet been eagerly merged. + // We'll go ahead and merge that state now so that we don't have to worry about + // this legacy case anywhere else. + if (activeWindows.isActive(window)) { + Set stateAddressWindows = activeWindows.readStateAddresses(window); + if (stateAddressWindows.size() > 1) { + // This is a legacy window who's state has not been eagerly merged. + // Do that now. + ReduceFn.OnMergeContext premergeContext = + contextFactory.forPremerge(window); + reduceFn.onMerge(premergeContext); + watermarkHold.onMerge(premergeContext); + activeWindows.merged(window); } - - // Add this window as NEW if it is not currently ACTIVE. - // If we had already seen this window and closed its trigger, then the - // window will not be currently ACTIVE. It will then be added as NEW here, - // and fall into the merging logic as usual. - activeWindows.ensureWindowExists(window); } + + // Add this window as NEW if it is not currently ACTIVE. + // If we had already seen this window and closed its trigger, then the + // window will not be currently ACTIVE. It will then be added as NEW here, + // and fall into the merging logic as usual. + activeWindows.ensureWindowExists(window); } // Merge all of the active windows and retain a mapping from source windows to result windows. - Map windowToMergeResult = new HashMap<>(); activeWindows.merge(new OnMergeCallback(windowToMergeResult)); return windowToMergeResult; } @@ -458,38 +524,50 @@ public void onMerge(Collection toBeMerged, W mergeResult) throws Exception { } /** - * Process an element. - * - * @param value the value being processed - * @return the set of windows in which the element was actually processed + * Redirect element windows to the ACTIVE windows they have been merged into. + * The compressed representation (value, {window1, window2, ...}) actually represents + * distinct elements (value, window1), (value, window2), ... + * so if window1 and window2 merge, the resulting window will contain both copies + * of the value. */ - private Collection processElement(Map windowToMergeResult, WindowedValue value) - throws Exception { - // Redirect element windows to the ACTIVE windows they have been merged into. - // The compressed representation (value, {window1, window2, ...}) actually represents - // distinct elements (value, window1), (value, window2), ... - // so if window1 and window2 merge, the resulting window will contain both copies - // of the value. - Collection windows = new ArrayList<>(); - for (BoundedWindow untypedWindow : value.getWindows()) { - @SuppressWarnings("unchecked") - W window = (W) untypedWindow; - W mergeResult = windowToMergeResult.get(window); - if (mergeResult == null) { - mergeResult = window; - } - windows.add(mergeResult); - } + private ImmutableSet toMergedWindows(final Map windowToMergeResult, + final Collection windows) { + return ImmutableSet.copyOf( + FluentIterable.from(windows).transform( + new Function() { + @Override + public W apply(BoundedWindow untypedWindow) { + @SuppressWarnings("unchecked") + W window = (W) untypedWindow; + W mergedWindow = windowToMergeResult.get(window); + // If the element is not present in the map, the window is unmerged. + return (mergedWindow == null) ? window : mergedWindow; + } + } + )); + } + private void prefetchWindowsForValues(Collection windows) { // Prefetch in each of the windows if we're going to need to process triggers for (W window : windows) { - ReduceFn.ProcessValueContext directContext = contextFactory.forValue( - window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); + ReduceFn.Context directContext = contextFactory.base( + window, StateStyle.DIRECT); triggerRunner.prefetchForValue(window, directContext.state()); } + } + + /** + * Process an element. + * + * @param windowToMergeResult map of windows to merged windows. If a window is + * not present it is unmerged. + * @param value the value being processed + */ + private void processElement(Map windowToMergeResult, WindowedValue value) + throws Exception { + ImmutableSet windows = toMergedWindows(windowToMergeResult, value.getWindows()); // Process the element for each (mergeResultWindow, not closed) window it belongs to. - List triggerableWindows = new ArrayList<>(windows.size()); for (W window : windows) { ReduceFn.ProcessValueContext directContext = contextFactory.forValue( window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); @@ -504,7 +582,6 @@ private Collection processElement(Map windowToMergeResult, WindowedValu continue; } - triggerableWindows.add(window); activeWindows.ensureWindowIsActive(window); ReduceFn.ProcessValueContext renamedContext = contextFactory.forValue( window, value.getValue(), value.getTimestamp(), StateStyle.RENAMED); @@ -548,102 +625,152 @@ private Collection processElement(Map windowToMergeResult, WindowedValu // cannot take a trigger state from firing to non-firing. // (We don't actually assert this since it is too slow.) } - - return triggerableWindows; } /** - * Called when an end-of-window, garbage collection, or trigger-specific timer fires. + * Enriches TimerData with state necessary for processing a timer as well as + * common queries about a timer. */ - public void onTimer(TimerData timer) throws Exception { - // Which window is the timer for? - checkArgument(timer.getNamespace() instanceof WindowNamespace, - "Expected timer to be in WindowNamespace, but was in %s", timer.getNamespace()); - @SuppressWarnings("unchecked") - WindowNamespace windowNamespace = (WindowNamespace) timer.getNamespace(); - W window = windowNamespace.getWindow(); - ReduceFn.Context directContext = - contextFactory.base(window, StateStyle.DIRECT); - ReduceFn.Context renamedContext = - contextFactory.base(window, StateStyle.RENAMED); + private class EnrichedTimerData { + public final Instant timestamp; + public final ReduceFn.Context directContext; + public final ReduceFn.Context renamedContext; + // If this is an end-of-window timer then we may need to set a garbage collection timer + // if allowed lateness is non-zero. + public final boolean isEndOfWindow; + // If this is a garbage collection timer then we should trigger and + // garbage collect the window. We'll consider any timer at or after the + // end-of-window time to be a signal to garbage collect. + public final boolean isGarbageCollection; + + EnrichedTimerData( + TimerData timer, + ReduceFn.Context directContext, + ReduceFn.Context renamedContext) { + this.timestamp = timer.getTimestamp(); + this.directContext = directContext; + this.renamedContext = renamedContext; + W window = directContext.window(); + this.isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() + && timer.getTimestamp().equals(window.maxTimestamp()); + Instant cleanupTime = garbageCollectionTime(window); + this.isGarbageCollection = !timer.getTimestamp().isBefore(cleanupTime); + } // Has this window had its trigger finish? // - The trigger may implement isClosed as constant false. // - If the window function does not support windowing then all windows will be considered // active. // So we must take conjunction of activeWindows and triggerRunner state. - boolean windowIsActiveAndOpen = - activeWindows.isActive(window) && !triggerRunner.isClosed(directContext.state()); + public boolean windowIsActiveAndOpen() { + return activeWindows.isActive(directContext.window()) + && !triggerRunner.isClosed(directContext.state()); + } + } - if (!windowIsActiveAndOpen) { - WindowTracing.debug( - "ReduceFnRunner.onTimer: Note that timer {} is for non-ACTIVE window {}", timer, window); + public void onTimers(Iterable timers) throws Exception { + if (!timers.iterator().hasNext()) { + return; } - // If this is an end-of-window timer then we may need to set a garbage collection timer - // if allowed lateness is non-zero. - boolean isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() - && timer.getTimestamp().equals(window.maxTimestamp()); - - // If this is a garbage collection timer then we should trigger and garbage collect the window. - // We'll consider any timer at or after the end-of-window time to be a signal to garbage - // collect. - Instant cleanupTime = garbageCollectionTime(window); - boolean isGarbageCollection = TimeDomain.EVENT_TIME == timer.getDomain() - && !timer.getTimestamp().isBefore(cleanupTime); - - if (isGarbageCollection) { - WindowTracing.debug( - "ReduceFnRunner.onTimer: Cleaning up for key:{}; window:{} at {} with " - + "inputWatermark:{}; outputWatermark:{}", - key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - - if (windowIsActiveAndOpen) { - // We need to call onTrigger to emit the final pane if required. - // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, - // and the watermark has passed the end of the window. - @Nullable Instant newHold = - onTrigger(directContext, renamedContext, true/* isFinished */, isEndOfWindow); - checkState(newHold == null, - "Hold placed at %s despite isFinished being true.", newHold); + // Create a reusable context for each timer and begin prefetching necessary + // state. + List enrichedTimers = new LinkedList(); + for (TimerData timer : timers) { + checkArgument(timer.getNamespace() instanceof WindowNamespace, + "Expected timer to be in WindowNamespace, but was in %s", timer.getNamespace()); + @SuppressWarnings("unchecked") + WindowNamespace windowNamespace = (WindowNamespace) timer.getNamespace(); + W window = windowNamespace.getWindow(); + ReduceFn.Context directContext = + contextFactory.base(window, StateStyle.DIRECT); + ReduceFn.Context renamedContext = + contextFactory.base(window, StateStyle.RENAMED); + EnrichedTimerData enrichedTimer = new EnrichedTimerData(timer, directContext, renamedContext); + enrichedTimers.add(enrichedTimer); + + // Perform prefetching of state to determine if the trigger should fire. + if (enrichedTimer.isGarbageCollection) { + triggerRunner.prefetchIsClosed(directContext.state()); + } else { + triggerRunner.prefetchShouldFire(directContext.window(), directContext.state()); } + } - // Cleanup flavor B: Clear all the remaining state for this window since we'll never - // see elements for it again. - clearAllState(directContext, renamedContext, windowIsActiveAndOpen); - } else { - WindowTracing.debug( - "ReduceFnRunner.onTimer: Triggering for key:{}; window:{} at {} with " - + "inputWatermark:{}; outputWatermark:{}", - key, window, timer.getTimestamp(), timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - if (windowIsActiveAndOpen) { - emitIfAppropriate(directContext, renamedContext); + // For those windows that are active and open, prefetch the triggering or emitting state. + for (EnrichedTimerData timer : enrichedTimers) { + if (timer.windowIsActiveAndOpen()) { + ReduceFn.Context directContext = timer.directContext; + if (timer.isGarbageCollection) { + prefetchOnTrigger(directContext, timer.renamedContext); + } else if (triggerRunner.shouldFire( + directContext.window(), directContext.timers(), directContext.state())) { + prefetchEmit(directContext, timer.renamedContext); + } } + } - if (isEndOfWindow) { - // If the window strategy trigger includes a watermark trigger then at this point - // there should be no data holds, either because we'd already cleared them on an - // earlier onTrigger, or because we just cleared them on the above emitIfAppropriate. - // We could assert this but it is very expensive. - - // Since we are processing an on-time firing we should schedule the garbage collection - // timer. (If getAllowedLateness is zero then the timer event will be considered a - // cleanup event and handled by the above). - // Note we must do this even if the trigger is finished so that we are sure to cleanup - // any final trigger finished bits. - checkState( - windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO), - "Unexpected zero getAllowedLateness"); - WindowTracing.debug( - "ReduceFnRunner.onTimer: Scheduling cleanup timer for key:{}; window:{} at {} with " - + "inputWatermark:{}; outputWatermark:{}", - key, directContext.window(), cleanupTime, timerInternals.currentInputWatermarkTime(), + // Perform processing now that everything is prefetched. + for (EnrichedTimerData timer : enrichedTimers) { + ReduceFn.Context directContext = timer.directContext; + ReduceFn.Context renamedContext = timer.renamedContext; + + if (timer.isGarbageCollection) { + WindowTracing.debug("ReduceFnRunner.onTimer: Cleaning up for key:{}; window:{} at {} with " + + "inputWatermark:{}; outputWatermark:{}", + key, directContext.window(), timer.timestamp, + timerInternals.currentInputWatermarkTime(), timerInternals.currentOutputWatermarkTime()); - checkState(!cleanupTime.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), - "Cleanup time %s is beyond end-of-time", cleanupTime); - directContext.timers().setTimer(cleanupTime, TimeDomain.EVENT_TIME); + + boolean windowIsActiveAndOpen = timer.windowIsActiveAndOpen(); + if (windowIsActiveAndOpen) { + // We need to call onTrigger to emit the final pane if required. + // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, + // and the watermark has passed the end of the window. + @Nullable + Instant newHold = onTrigger( + directContext, renamedContext, true /* isFinished */, timer.isEndOfWindow); + checkState(newHold == null, "Hold placed at %s despite isFinished being true.", newHold); + } + + // Cleanup flavor B: Clear all the remaining state for this window since we'll never + // see elements for it again. + clearAllState(directContext, renamedContext, windowIsActiveAndOpen); + } else { + WindowTracing.debug("ReduceFnRunner.onTimer: Triggering for key:{}; window:{} at {} with " + + "inputWatermark:{}; outputWatermark:{}", + key, directContext.window(), timer.timestamp, + timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + if (timer.windowIsActiveAndOpen() + && triggerRunner.shouldFire( + directContext.window(), directContext.timers(), directContext.state())) { + emit(directContext, renamedContext); + } + + if (timer.isEndOfWindow) { + // If the window strategy trigger includes a watermark trigger then at this point + // there should be no data holds, either because we'd already cleared them on an + // earlier onTrigger, or because we just cleared them on the above emit. + // We could assert this but it is very expensive. + + // Since we are processing an on-time firing we should schedule the garbage collection + // timer. (If getAllowedLateness is zero then the timer event will be considered a + // cleanup event and handled by the above). + // Note we must do this even if the trigger is finished so that we are sure to cleanup + // any final trigger finished bits. + checkState(windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO), + "Unexpected zero getAllowedLateness"); + Instant cleanupTime = garbageCollectionTime(directContext.window()); + WindowTracing.debug( + "ReduceFnRunner.onTimer: Scheduling cleanup timer for key:{}; window:{} at {} with " + + "inputWatermark:{}; outputWatermark:{}", + key, directContext.window(), cleanupTime, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + checkState(!cleanupTime.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), + "Cleanup time %s is beyond end-of-time", cleanupTime); + directContext.timers().setTimer(cleanupTime, TimeDomain.EVENT_TIME); + } } } } @@ -652,7 +779,7 @@ public void onTimer(TimerData timer) throws Exception { * Clear all the state associated with {@code context}'s window. * Should only be invoked if we know all future elements for this window will be considered * beyond allowed lateness. - * This is a superset of the clearing done by {@link #emitIfAppropriate} below since: + * This is a superset of the clearing done by {@link #emit} below since: *

              *
            1. We can clear the trigger finished bits since we'll never need to ask if the trigger is * closed again. @@ -678,10 +805,10 @@ private void clearAllState( } else { // If !windowIsActiveAndOpen then !activeWindows.isActive (1) or triggerRunner.isClosed (2). // For (1), if !activeWindows.isActive then the window must be merging and has been - // explicitly removed by emitIfAppropriate. But in that case the trigger must have fired + // explicitly removed by emit. But in that case the trigger must have fired // and been closed, so this case reduces to (2). // For (2), if triggerRunner.isClosed then the trigger was fired and entered the - // closed state. In that case emitIfAppropriate will have cleared all state in + // closed state. In that case emit will have cleared all state in // reduceFn, triggerRunner (except for finished bits), paneInfoTracker and activeWindows. // We also know nonEmptyPanes must have been unconditionally cleared by the trigger. // Since the trigger fired the existing watermark holds must have been cleared, and since @@ -723,17 +850,23 @@ private boolean shouldDiscardAfterFiring(boolean isFinished) { return false; } + private void prefetchEmit(ReduceFn.Context directContext, + ReduceFn.Context renamedContext) { + triggerRunner.prefetchShouldFire(directContext.window(), directContext.state()); + triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); + triggerRunner.prefetchIsClosed(directContext.state()); + prefetchOnTrigger(directContext, renamedContext); + } + /** - * Possibly emit a pane if a trigger is ready to fire or timers require it, and cleanup state. + * Emit if a trigger is ready to fire or timers require it, and cleanup state. */ - private void emitIfAppropriate(ReduceFn.Context directContext, + private void emit( + ReduceFn.Context directContext, ReduceFn.Context renamedContext) throws Exception { - if (!triggerRunner.shouldFire( - directContext.window(), directContext.timers(), directContext.state())) { - // Ignore unless trigger is ready to fire - return; - } + checkState(triggerRunner.shouldFire( + directContext.window(), directContext.timers(), directContext.state())); // Inform the trigger of the transition to see if it is finished triggerRunner.onFire(directContext.window(), directContext.timers(), directContext.state()); @@ -768,7 +901,7 @@ private void emitIfAppropriate(ReduceFn.Context directCon } /** - * Do we need to emit a pane? + * Do we need to emit? */ private boolean needToEmit(boolean isEmpty, boolean isFinished, PaneInfo.Timing timing) { if (!isEmpty) { @@ -786,6 +919,15 @@ private boolean needToEmit(boolean isEmpty, boolean isFinished, PaneInfo.Timing return false; } + private void prefetchOnTrigger( + final ReduceFn.Context directContext, + ReduceFn.Context renamedContext) { + paneInfoTracker.prefetchPaneInfo(directContext); + watermarkHold.prefetchExtract(renamedContext); + nonEmptyPanes.isEmpty(renamedContext.state()).readLater(); + reduceFn.prefetchOnTrigger(directContext.state()); + } + /** * Run the {@link ReduceFn#onTrigger} method and produce any necessary output. * @@ -799,25 +941,17 @@ private Instant onTrigger( throws Exception { Instant inputWM = timerInternals.currentInputWatermarkTime(); - // Prefetch necessary states - ReadableState outputTimestampFuture = - watermarkHold.extractAndRelease(renamedContext, isFinished).readLater(); - ReadableState paneFuture = - paneInfoTracker.getNextPaneInfo(directContext, isFinished).readLater(); - ReadableState isEmptyFuture = - nonEmptyPanes.isEmpty(renamedContext.state()).readLater(); - - reduceFn.prefetchOnTrigger(directContext.state()); - triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); - // Calculate the pane info. - final PaneInfo pane = paneFuture.read(); - // Extract the window hold, and as a side effect clear it. + final PaneInfo pane = paneInfoTracker.getNextPaneInfo(directContext, isFinished).read(); - WatermarkHold.OldAndNewHolds pair = outputTimestampFuture.read(); + // Extract the window hold, and as a side effect clear it. + final WatermarkHold.OldAndNewHolds pair = + watermarkHold.extractAndRelease(renamedContext, isFinished).read(); final Instant outputTimestamp = pair.oldHold; @Nullable Instant newHold = pair.newHold; + final boolean isEmpty = nonEmptyPanes.isEmpty(renamedContext.state()).read(); + if (newHold != null) { // We can't be finished yet. checkState( @@ -849,11 +983,11 @@ private Instant onTrigger( } // Only emit a pane if it has data or empty panes are observable. - if (needToEmit(isEmptyFuture.read(), isFinished, pane.getTiming())) { + if (needToEmit(isEmpty, isFinished, pane.getTiming())) { // Run reduceFn.onTrigger method. final List windows = Collections.singletonList(directContext.window()); ReduceFn.OnTriggerContext renamedTriggerContext = - contextFactory.forTrigger(directContext.window(), paneFuture, StateStyle.RENAMED, + contextFactory.forTrigger(directContext.window(), pane, StateStyle.RENAMED, new OnTriggerCallbacks() { @Override public void output(OutputT toOutput) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java index e59a1c20d7..672d846bb6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java @@ -90,30 +90,31 @@ private void clearFinishedBits(ValueState state) { } state.clear(); } + /** Return true if the trigger is closed in the window corresponding to the specified state. */ public boolean isClosed(StateAccessor state) { return readFinishedBits(state.access(FINISHED_BITS_TAG)).isFinished(rootTrigger); } - public void prefetchForValue(W window, StateAccessor state) { + public void prefetchIsClosed(StateAccessor state) { if (isFinishedSetNeeded()) { state.access(FINISHED_BITS_TAG).readLater(); } + } + + public void prefetchForValue(W window, StateAccessor state) { + prefetchIsClosed(state); rootTrigger.getSpec().prefetchOnElement( contextFactory.createStateAccessor(window, rootTrigger)); } public void prefetchOnFire(W window, StateAccessor state) { - if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).readLater(); - } + prefetchIsClosed(state); rootTrigger.getSpec().prefetchOnFire(contextFactory.createStateAccessor(window, rootTrigger)); } public void prefetchShouldFire(W window, StateAccessor state) { - if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).readLater(); - } + prefetchIsClosed(state); rootTrigger.getSpec().prefetchShouldFire( contextFactory.createStateAccessor(window, rootTrigger)); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java index f23e5eb9e5..06de70fe5f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java @@ -443,6 +443,11 @@ public OldAndNewHolds(Instant oldHold, @Nullable Instant newHold) { } } + public void prefetchExtract(final ReduceFn.Context context) { + context.state().access(elementHoldTag).readLater(); + context.state().access(EXTRA_HOLD_TAG).readLater(); + } + /** * Return (a future for) the earliest hold for {@code context}. Clear all the holds after * reading, but add/restore an end-of-window or garbage collection hold if required. diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java index 25d07d62d7..3228c544bf 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java @@ -15,6 +15,8 @@ */ package com.google.cloud.dataflow.sdk.util; +import static org.mockito.Matchers.argThat; + import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateNamespaceForTest; @@ -24,10 +26,15 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * Tests for {@link BatchTimerInternals}. */ @@ -44,6 +51,37 @@ public void setUp() { MockitoAnnotations.initMocks(this); } + private static class TimersAre extends ArgumentMatcher> { + final List expectedTimers; + TimersAre(List timers) { + expectedTimers = timers; + } + + @Override + public boolean matches(Object actual) { + if (actual == null || !(actual instanceof Iterable)) { + return false; + } + @SuppressWarnings("unchecked") + Iterable timers = (Iterable) actual; + + List actualTimers = new ArrayList(); + for (TimerData timer : timers) { + actualTimers.add(timer); + } + return expectedTimers.equals(actualTimers); + } + + @Override + public String toString() { + return "ordered timers " + expectedTimers.toString(); + } + } + + private static TimersAre timersAre(TimerData... timers) { + return new TimersAre(Arrays.asList(timers)); + } + @Test public void testFiringTimers() throws Exception { BatchTimerInternals underTest = new BatchTimerInternals(new Instant(0)); @@ -54,7 +92,7 @@ public void testFiringTimers() throws Exception { underTest.setTimer(processingTime2); underTest.advanceProcessingTime(mockRunner, new Instant(20)); - Mockito.verify(mockRunner).onTimer(processingTime1); + Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime1))); Mockito.verifyNoMoreInteractions(mockRunner); // Advancing just a little shouldn't refire @@ -63,13 +101,13 @@ public void testFiringTimers() throws Exception { // Adding the timer and advancing a little should refire underTest.setTimer(processingTime1); - Mockito.verify(mockRunner).onTimer(processingTime1); underTest.advanceProcessingTime(mockRunner, new Instant(21)); + Mockito.verify(mockRunner, Mockito.times(2)).onTimers(argThat(timersAre(processingTime1))); Mockito.verifyNoMoreInteractions(mockRunner); // And advancing the rest of the way should still have the other timer underTest.advanceProcessingTime(mockRunner, new Instant(30)); - Mockito.verify(mockRunner).onTimer(processingTime2); + Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime2))); Mockito.verifyNoMoreInteractions(mockRunner); } @@ -87,13 +125,11 @@ public void testTimerOrdering() throws Exception { underTest.setTimer(watermarkTime2); underTest.advanceInputWatermark(mockRunner, new Instant(30)); - Mockito.verify(mockRunner).onTimer(watermarkTime1); - Mockito.verify(mockRunner).onTimer(watermarkTime2); + Mockito.verify(mockRunner).onTimers(argThat(timersAre(watermarkTime1, watermarkTime2))); Mockito.verifyNoMoreInteractions(mockRunner); underTest.advanceProcessingTime(mockRunner, new Instant(30)); - Mockito.verify(mockRunner).onTimer(processingTime1); - Mockito.verify(mockRunner).onTimer(processingTime2); + Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime1, processingTime2))); Mockito.verifyNoMoreInteractions(mockRunner); } @@ -107,10 +143,9 @@ public void testDeduplicate() throws Exception { underTest.setTimer(processingTime); underTest.setTimer(processingTime); underTest.advanceProcessingTime(mockRunner, new Instant(20)); + Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime))); underTest.advanceInputWatermark(mockRunner, new Instant(20)); - - Mockito.verify(mockRunner).onTimer(processingTime); - Mockito.verify(mockRunner).onTimer(watermarkTime); + Mockito.verify(mockRunner).onTimers(argThat(timersAre(watermarkTime))); Mockito.verifyNoMoreInteractions(mockRunner); } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java index e7da19f4d4..f206a4cfb9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java @@ -418,8 +418,10 @@ public WindowedValue apply(TimestampedValue input) { public void fireTimer(W window, Instant timestamp, TimeDomain domain) throws Exception { ReduceFnRunner runner = createRunner(); - runner.onTimer( + ArrayList timers = new ArrayList(1); + timers.add( TimerData.of(StateNamespaces.window(windowFn.windowCoder(), window), timestamp, domain)); + runner.onTimers(timers); runner.persist(); } @@ -760,20 +762,20 @@ private void advanceAndFire( PriorityQueue queue = queue(domain); boolean shouldFire = false; - do { - TimerData timer = queue.peek(); - // Timers fire when the current time progresses past the timer time. - shouldFire = timer != null && currentTime.isAfter(timer.getTimestamp()); - if (shouldFire) { - WindowTracing.trace( - "TestTimerInternals.advanceAndFire: firing {} at {}", timer, currentTime); - // Remove before firing, so that if the trigger adds another identical + while (true) { + ArrayList firedTimers = new ArrayList(); + while (!queue.isEmpty() && currentTime.isAfter(queue.peek().getTimestamp())) { + // Remove before firing, so that if the callback adds another identical // timer we don't remove it. - queue.remove(); - - runner.onTimer(timer); + TimerData timer = queue.remove(); + existingTimers.remove(timer); + firedTimers.add(timer); + } + if (firedTimers.isEmpty()) { + break; } - } while (shouldFire); + runner.onTimers(firedTimers); + } } } } From 1531683b4b33a8ca962ebc6dde4e3ce68fd6e0cc Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Thu, 8 Dec 2016 15:13:13 -0800 Subject: [PATCH 629/751] Simplify diff by handling single split & split per partition cases existing code. --- .../cloud/dataflow/contrib/kafka/KafkaIO.java | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java index f5422d33d6..d7e1c60feb 100644 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java @@ -44,6 +44,7 @@ import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; +import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; @@ -730,6 +731,7 @@ public List> generateInitialSplits( // (a) fetch partitions for each topic // (b) sort by + // (c) round-robin assign the partitions to splits if (partitions.isEmpty()) { try (Consumer consumer = consumerFactoryFn.apply(consumerConfig)) { @@ -756,35 +758,33 @@ public int compare(TopicPartition tp1, TopicPartition tp2) { partitions.size() > 0, "Could not find any partitions. Please check Kafka configuration and topic names"); - if (desiredNumSplits < 0) { - // special case for DirectPipelineRunner (used in tests) in Dataflow. Return single split. - return ImmutableList.of( - new UnboundedKafkaSource<>( - 0, - this.topics, - partitions, - this.keyCoder, - this.valueCoder, - this.timestampFn, - this.watermarkFn, - this.consumerFactoryFn, - this.consumerConfig) - ); + // one split per partition, except when desiredNumSplits is -1, which is a special case + // for DirectDataflowRunner that requires single split. + int numSplits = desiredNumSplits == -1 ? 1 : partitions.size(); + List> assignments = new ArrayList<>(numSplits); + + for (int i = 0; i < numSplits; i++) { + assignments.add(new ArrayList()); + } + for (int i = 0; i < partitions.size(); i++) { + assignments.get(i % numSplits).add(partitions.get(i)); } - List> result = new ArrayList<>(partitions.size()); + List> result = new ArrayList<>(numSplits); - // one split for each partition. - for (int i = 0; i < partitions.size(); i++) { - TopicPartition partition = partitions.get(i); + for (int i = 0; i < numSplits; i++) { + List assignedToSplit = assignments.get(i); - LOG.info("Partition assigned to split {} : {}", i, partition); + LOG.info( + "Partitions assigned to split {} : {}", + i, + Joiner.on(",").join(assignedToSplit)); result.add( - new UnboundedKafkaSource<>( + new UnboundedKafkaSource( i, this.topics, - ImmutableList.of(partition), + assignedToSplit, this.keyCoder, this.valueCoder, this.timestampFn, @@ -803,7 +803,6 @@ public UnboundedKafkaReader createReader( if (assignedPartitions.isEmpty()) { LOG.warn("Looks like generateSplits() is not called. Generate single split."); try { - return new UnboundedKafkaReader( generateInitialSplits(-1, options).get(0), checkpointMark); } catch (Exception e) { From 10e9a08108763446728567ba4a37b6d6516b46bf Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Thu, 8 Dec 2016 16:00:34 -0800 Subject: [PATCH 630/751] review comments. Remove special handling of single partition in generateInitialSplits. --- .../cloud/dataflow/contrib/kafka/KafkaIO.java | 67 +++++++++---------- .../dataflow/contrib/kafka/KafkaIOTest.java | 4 +- 2 files changed, 34 insertions(+), 37 deletions(-) diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java index d7e1c60feb..5176d6e898 100644 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java @@ -44,7 +44,6 @@ import com.google.cloud.dataflow.sdk.values.PInput; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; @@ -714,24 +713,12 @@ public UnboundedKafkaSource( this.consumerConfig = consumerConfig; } - /** - * The partitions are evenly distributed among the splits. The number of splits returned is - * {@code min(desiredNumSplits, totalNumPartitions)}, though better not to depend on the exact - * count. - * - *

              It is important to assign the partitions deterministically so that we can support - * resuming a split from last checkpoint. The Kafka partitions are sorted by {@code } and then assigned to splits in round-robin order. - */ - @Override - public List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception { + private List fetchKafkaPartitions() { List partitions = new ArrayList<>(assignedPartitions); // (a) fetch partitions for each topic // (b) sort by - // (c) round-robin assign the partitions to splits if (partitions.isEmpty()) { try (Consumer consumer = consumerFactoryFn.apply(consumerConfig)) { @@ -758,33 +745,35 @@ public int compare(TopicPartition tp1, TopicPartition tp2) { partitions.size() > 0, "Could not find any partitions. Please check Kafka configuration and topic names"); - // one split per partition, except when desiredNumSplits is -1, which is a special case - // for DirectDataflowRunner that requires single split. - int numSplits = desiredNumSplits == -1 ? 1 : partitions.size(); - List> assignments = new ArrayList<>(numSplits); + return partitions; + } - for (int i = 0; i < numSplits; i++) { - assignments.add(new ArrayList()); - } - for (int i = 0; i < partitions.size(); i++) { - assignments.get(i % numSplits).add(partitions.get(i)); - } + /** + * Returns one split for each of the Kafka partitions. + * + *

              It is important to sort the partitions deterministically so that we can support + * resuming a split from last checkpoint. The Kafka partitions are sorted by {@code }. + */ + @Override + public List> generateInitialSplits( + int desiredNumSplits, PipelineOptions options) throws Exception { + + List partitions = fetchKafkaPartitions(); - List> result = new ArrayList<>(numSplits); + List> result = new ArrayList<>(partitions.size()); - for (int i = 0; i < numSplits; i++) { - List assignedToSplit = assignments.get(i); + // one split for each partition. + for (int i = 0; i < partitions.size(); i++) { + TopicPartition partition = partitions.get(i); - LOG.info( - "Partitions assigned to split {} : {}", - i, - Joiner.on(",").join(assignedToSplit)); + LOG.info("Partition assigned to split {} : {}", i, partition); result.add( - new UnboundedKafkaSource( + new UnboundedKafkaSource<>( i, this.topics, - assignedToSplit, + ImmutableList.of(partition), this.keyCoder, this.valueCoder, this.timestampFn, @@ -804,7 +793,17 @@ public UnboundedKafkaReader createReader( LOG.warn("Looks like generateSplits() is not called. Generate single split."); try { return new UnboundedKafkaReader( - generateInitialSplits(-1, options).get(0), checkpointMark); + new UnboundedKafkaSource<>( + 0, + this.topics, + fetchKafkaPartitions(), + this.keyCoder, + this.valueCoder, + this.timestampFn, + this.watermarkFn, + this.consumerFactoryFn, + this.consumerConfig), + checkpointMark); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java index 7cfa8a0e94..710f74ed92 100644 --- a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java +++ b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java @@ -365,9 +365,7 @@ public void testUnboundedSourceCheckpointMark() throws Exception { com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> source = mkKafkaReadTransform(numElements, new ValueAsTimestampFn()) - .makeSource() - .generateInitialSplits(-1, PipelineOptionsFactory.fromArgs(new String[0]).create()) - .get(0); + .makeSource(); UnboundedReader> reader = source.createReader(null, null); From 1485c4d47cad125f7c18c9ca05a888d1f8211f3c Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Thu, 8 Dec 2016 16:07:31 -0800 Subject: [PATCH 631/751] fix indentation --- .../cloud/dataflow/contrib/kafka/KafkaIO.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java index 5176d6e898..47335bdbc9 100644 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java @@ -794,15 +794,15 @@ public UnboundedKafkaReader createReader( try { return new UnboundedKafkaReader( new UnboundedKafkaSource<>( - 0, - this.topics, - fetchKafkaPartitions(), - this.keyCoder, - this.valueCoder, - this.timestampFn, - this.watermarkFn, - this.consumerFactoryFn, - this.consumerConfig), + 0, + this.topics, + fetchKafkaPartitions(), + this.keyCoder, + this.valueCoder, + this.timestampFn, + this.watermarkFn, + this.consumerFactoryFn, + this.consumerConfig), checkpointMark); } catch (Exception e) { throw new RuntimeException(e); From 668a3e2f36f6722c792bc3606a27d6d23ca751c0 Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Thu, 8 Dec 2016 17:16:30 -0800 Subject: [PATCH 632/751] fix unused import --- .../com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java index 710f74ed92..19d4336a5b 100644 --- a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java +++ b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java @@ -26,7 +26,6 @@ import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.UnboundedSource; import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Count; From 3a6dde76be043fcdc30a5e19168080cff6cda9e9 Mon Sep 17 00:00:00 2001 From: Sam Whittle Date: Fri, 9 Dec 2016 11:16:01 -0800 Subject: [PATCH 633/751] Only increase counters in LateDroppingDoFnRunner once, even if iterated multiple times. --- .../sdk/util/LateDataDroppingDoFnRunner.java | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java index 3dfa06474e..721953a644 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java @@ -112,20 +112,30 @@ public WindowedValue apply(BoundedWindow window) { }); }}); + Iterable> concatElements = Iterables.concat(windowsExpandedElements); + + // Bump the counter separately since we don't want multiple iterations to + // increase it multiple times. + for (WindowedValue input : concatElements) { + BoundedWindow window = Iterables.getOnlyElement(input.getWindows()); + if (canDropDueToExpiredWindow(window)) { + // The element is too late for this window. + droppedDueToLateness.addValue(1L); + WindowTracing.debug( + "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " + + "since too far behind inputWatermark:{}; outputWatermark:{}", + input.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), + timerInternals.currentOutputWatermarkTime()); + } + } + Iterable> nonLateElements = Iterables.filter( - Iterables.concat(windowsExpandedElements), + concatElements, new Predicate>() { @Override public boolean apply(WindowedValue input) { BoundedWindow window = Iterables.getOnlyElement(input.getWindows()); if (canDropDueToExpiredWindow(window)) { - // The element is too late for this window. - droppedDueToLateness.addValue(1L); - WindowTracing.debug( - "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since too far behind inputWatermark:{}; outputWatermark:{}", - input.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); return false; } else { return true; From 9b96b97b6eaf8f0b4d280144fdebbe55b82384f8 Mon Sep 17 00:00:00 2001 From: Sam Whittle Date: Fri, 9 Dec 2016 12:39:49 -0800 Subject: [PATCH 634/751] Improve LateDataDroppingDoFnRunner to include reiteration. --- .../dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java index c951d4c9a1..b654b31b1c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java @@ -77,6 +77,9 @@ public void testLateDataFilter() throws Exception { createDatum(18, 18L)); assertThat(expected, containsInAnyOrder(Iterables.toArray(actual, WindowedValue.class))); assertEquals(1, droppedDueToLateness.sum); + // Ensure that reiterating returns the same results and doesn't increment the counter again. + assertThat(expected, containsInAnyOrder(Iterables.toArray(actual, WindowedValue.class))); + assertEquals(1, droppedDueToLateness.sum); } private WindowedValue createDatum(T element, long timestampMillis) { @@ -112,4 +115,3 @@ public String getName() { } } } - From 678fb7a590e66f3db3de278af5bc4c0ed437d48a Mon Sep 17 00:00:00 2001 From: dhalperi Date: Fri, 9 Dec 2016 01:17:53 -0800 Subject: [PATCH 635/751] DataflowPipelineRunner: preparation for 1.8.1 release [] ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=141532913 --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index fd6c1ea608..0b50706f1c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -216,14 +216,14 @@ public class DataflowPipelineRunner extends PipelineRunner private DataflowPipelineRunnerHooks hooks; // Environment version information. - private static final String ENVIRONMENT_MAJOR_VERSION = "5"; + private static final String ENVIRONMENT_MAJOR_VERSION = "6"; // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.8.0"; + = "dataflow.gcr.io/v1beta3/java-batch:1.8.1"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.8.0"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.8.1"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 8a7f299aa946e92e8a0e0cb897d36491218a28ee Mon Sep 17 00:00:00 2001 From: Ben Chambers Date: Mon, 12 Dec 2016 09:30:50 -0800 Subject: [PATCH 636/751] Add saveProfilesToGcs option; deprecate enableProfilingAgent (#497) Add saveProfilesToGcs option to DataflowProfilingOptions This option (if present) is verified to be a writeable GCS path during pipeline submission. --- .../sdk/options/DataflowProfilingOptions.java | 10 +- .../sdk/runners/DataflowPipelineRunner.java | 8 + .../runners/DataflowPipelineRunnerTest.java | 225 ++++++++++-------- .../DataflowPipelineTranslatorTest.java | 36 ++- 4 files changed, 164 insertions(+), 115 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java index 75dde19ea1..bd1fbff285 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java @@ -27,11 +27,17 @@ @Hidden public interface DataflowProfilingOptions { - @Description("Whether to periodically dump profiling information to local disk.\n" - + "WARNING: Enabling this option may fill local disk with profiling information.") + @Description( + "This option is deprecated and ignored. Using --saveProfilesToGcs= is preferred.") boolean getEnableProfilingAgent(); void setEnableProfilingAgent(boolean enabled); + @Description( + "When set to a non-empty value, enables recording profiles and saving them to GCS.\n" + + "Profiles will continue until the pipeline is stopped or updated without this option.\n") + String getSaveProfilesToGcs(); + void setSaveProfilesToGcs(String gcsPath); + @Description( "[INTERNAL] Additional configuration for the profiling agent. Not typically necessary.") @Hidden diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 0b50706f1c..318d0abd20 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -275,6 +275,14 @@ public static DataflowPipelineRunner fromOptions(PipelineOptions options) { if (dataflowOptions.getTempLocation() != null) { validator.validateOutputFilePrefixSupported(dataflowOptions.getTempLocation()); } + if (!Strings.isNullOrEmpty(dataflowOptions.getSaveProfilesToGcs())) { + validator.validateOutputFilePrefixSupported(dataflowOptions.getSaveProfilesToGcs()); + } + if (dataflowOptions.getEnableProfilingAgent()) { + LOG.error("--enableProfilingAgent is no longer supported, and will be ignored. " + + "Use --saveProfilesToGcs instead."); + } + if (Strings.isNullOrEmpty(dataflowOptions.getTempLocation())) { dataflowOptions.setTempLocation(dataflowOptions.getStagingLocation()); } else if (Strings.isNullOrEmpty(dataflowOptions.getStagingLocation())) { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 1dac6c4cf2..24cb9eca69 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -32,7 +32,9 @@ import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.api.services.dataflow.Dataflow; @@ -94,6 +96,7 @@ import org.hamcrest.Matchers; import org.hamcrest.TypeSafeMatcher; import org.joda.time.Instant; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.internal.matchers.ThrowableMessageMatcher; @@ -129,12 +132,44 @@ public class DataflowPipelineRunnerTest { private static final String PROJECT_ID = "some-project"; + public static final String VALID_GS_SPAM_HAM_EGGS = "gs://spam/ham/eggs"; + public static final String VALID_SOMEBUCKET_SOME_PATH = "gs://somebucket/some/path"; + public static final String VALID_BUCKET_OBJECT = "gs://bucket/object"; @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); + private GcsUtil mockGcsUtil; + private Dataflow.Projects.Jobs mockJobs; + + @Before + public void setUp() throws IOException { + this.mockGcsUtil = mock(GcsUtil.class); + this.mockJobs = mock(Dataflow.Projects.Jobs.class); + when(mockGcsUtil.create(any(GcsPath.class), anyString())) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + + when(mockGcsUtil.isGcsPatternSupported(anyString())).thenReturn(true); + when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); + when(mockGcsUtil.bucketExists(GcsPath.fromUri(VALID_GS_SPAM_HAM_EGGS))).thenReturn(true); + when(mockGcsUtil.bucketExists(GcsPath.fromUri(VALID_SOMEBUCKET_SOME_PATH))).thenReturn(true); + when(mockGcsUtil.bucketExists(GcsPath.fromUri(VALID_BUCKET_OBJECT))).thenReturn(true); + } + // Asserts that the given Job has all expected fields set. private static void assertValidJob(Job job) { assertNull(job.getId()); @@ -146,25 +181,22 @@ private DataflowPipeline buildDataflowPipeline(DataflowPipelineOptions options) options.setStableUniqueNames(CheckEnabled.ERROR); DataflowPipeline p = DataflowPipeline.create(options); - p.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/object")) - .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/object")); + p.apply(TextIO.Read.named("ReadMyFile").from(VALID_BUCKET_OBJECT)) + .apply(TextIO.Write.named("WriteMyFile").to(VALID_BUCKET_OBJECT)); return p; } - private static Dataflow buildMockDataflow( - final ArgumentCaptor jobCaptor) throws IOException { + private Dataflow buildMockDataflow() throws IOException { Dataflow mockDataflowClient = mock(Dataflow.class); Dataflow.Projects mockProjects = mock(Dataflow.Projects.class); - Dataflow.Projects.Jobs mockJobs = mock(Dataflow.Projects.Jobs.class); Dataflow.Projects.Jobs.Create mockRequest = mock(Dataflow.Projects.Jobs.Create.class); Dataflow.Projects.Jobs.List mockList = mock(Dataflow.Projects.Jobs.List.class); when(mockDataflowClient.projects()).thenReturn(mockProjects); when(mockProjects.jobs()).thenReturn(mockJobs); - when(mockJobs.create(eq(PROJECT_ID), jobCaptor.capture())) - .thenReturn(mockRequest); + when(mockJobs.create(eq(PROJECT_ID), isA(Job.class))).thenReturn(mockRequest); when(mockJobs.list(eq(PROJECT_ID))).thenReturn(mockList); when(mockList.setPageToken(anyString())).thenReturn(mockList); when(mockList.execute()) @@ -183,43 +215,14 @@ private static Dataflow buildMockDataflow( return mockDataflowClient; } - private GcsUtil buildMockGcsUtil(boolean bucketExists) throws IOException { - GcsUtil mockGcsUtil = mock(GcsUtil.class); - when(mockGcsUtil.create(any(GcsPath.class), anyString())) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); - - when(mockGcsUtil.isGcsPatternSupported(anyString())).thenReturn(true); - when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); - when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(bucketExists); - return mockGcsUtil; - } - private DataflowPipelineOptions buildPipelineOptions() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - return buildPipelineOptions(jobCaptor); - } - - private DataflowPipelineOptions buildPipelineOptions( - ArgumentCaptor jobCaptor) throws IOException { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); options.setProject(PROJECT_ID); - options.setTempLocation("gs://somebucket/some/path"); + options.setTempLocation(VALID_SOMEBUCKET_SOME_PATH); // Set FILES_PROPERTY to empty to prevent a default value calculated from classpath. options.setFilesToStage(new LinkedList()); - options.setDataflowClient(buildMockDataflow(jobCaptor)); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + options.setDataflowClient(buildMockDataflow()); + options.setGcsUtil(mockGcsUtil); options.setGcpCredential(new TestCredential()); return options; } @@ -227,8 +230,7 @@ private DataflowPipelineOptions buildPipelineOptions( @Test public void testFromOptionsWithUppercaseConvertsToLowercase() throws Exception { String mixedCase = "ThisJobNameHasMixedCase"; - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); + DataflowPipelineOptions options = buildPipelineOptions(); options.setJobName(mixedCase); DataflowPipelineRunner runner = DataflowPipelineRunner.fromOptions(options); @@ -237,12 +239,13 @@ public void testFromOptionsWithUppercaseConvertsToLowercase() throws Exception { @Test public void testRun() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); + DataflowPipelineOptions options = buildPipelineOptions(); DataflowPipeline p = buildDataflowPipeline(options); DataflowPipelineJob job = p.run(); assertEquals("newid", job.getJobId()); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); assertValidJob(jobCaptor.getValue()); } @@ -273,14 +276,15 @@ public void testRunReturnDifferentRequestId() throws IOException { @Test public void testUpdate() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); + DataflowPipelineOptions options = buildPipelineOptions(); options.setUpdate(true); options.setJobName("oldJobName"); DataflowPipeline p = buildDataflowPipeline(options); DataflowPipelineJob job = p.run(); assertEquals("newid", job.getJobId()); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); assertValidJob(jobCaptor.getValue()); } @@ -334,8 +338,7 @@ protected boolean matchesSafely(DataflowJobAlreadyUpdatedException item) { public void testRunWithFiles() throws IOException { // Test that the function DataflowPipelineRunner.stageFiles works as // expected. - GcsUtil mockGcsUtil = buildMockGcsUtil(true /* bucket exists */); - final String gcsStaging = "gs://somebucket/some/path"; + final String gcsStaging = VALID_SOMEBUCKET_SOME_PATH; final String gcsTemp = "gs://somebucket/some/temp/path"; final String cloudDataflowDataset = "somedataset"; @@ -347,8 +350,8 @@ public void testRunWithFiles() throws IOException { String overridePackageName = "alias.txt"; - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setGcsUtil(mockGcsUtil); options.setFilesToStage(ImmutableList.of( temp1.getAbsolutePath(), overridePackageName + "=" + temp2.getAbsolutePath())); @@ -357,15 +360,17 @@ public void testRunWithFiles() throws IOException { options.setTempDatasetId(cloudDataflowDataset); options.setProject(PROJECT_ID); options.setJobName("job"); - options.setDataflowClient(buildMockDataflow(jobCaptor)); - options.setGcsUtil(mockGcsUtil); + options.setDataflowClient(buildMockDataflow()); options.setGcpCredential(new TestCredential()); + when(mockGcsUtil.bucketExists(GcsPath.fromUri(gcsTemp))).thenReturn(true); DataflowPipeline p = buildDataflowPipeline(options); DataflowPipelineJob job = p.run(); assertEquals("newid", job.getJobId()); + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); Job workflowJob = jobCaptor.getValue(); assertValidJob(workflowJob); @@ -442,11 +447,12 @@ public void testGcsStagingLocationInitialization() throws Exception { // Set temp location (required), and check that staging location is set. DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setGcsUtil(mockGcsUtil); options.setTempLocation(gcsTemp); options.setProject(PROJECT_ID); options.setGcpCredential(new TestCredential()); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + when(mockGcsUtil.bucketExists(GcsPath.fromUri(gcsTemp))).thenReturn(true); DataflowPipelineRunner.fromOptions(options); assertNotNull(options.getStagingLocation()); @@ -454,9 +460,7 @@ public void testGcsStagingLocationInitialization() throws Exception { @Test public void testNonGcsFilePathInReadFailure() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); + Pipeline p = buildDataflowPipeline(buildPipelineOptions()); p.apply(TextIO.Read.named("ReadMyNonGcsFile").from(tmpFolder.newFile().getPath())); thrown.expectCause(Matchers.allOf( @@ -464,13 +468,12 @@ public void testNonGcsFilePathInReadFailure() throws IOException { ThrowableMessageMatcher.hasMessage( containsString("expected a valid 'gs://' path but was given")))); p.run(); - assertValidJob(jobCaptor.getValue()); } @Test public void testNonGcsFilePathInWriteFailure() throws IOException { Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); + PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from(VALID_BUCKET_OBJECT)); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); @@ -479,9 +482,7 @@ public void testNonGcsFilePathInWriteFailure() throws IOException { @Test public void testMultiSlashGcsFileReadPath() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - Pipeline p = buildDataflowPipeline(buildPipelineOptions(jobCaptor)); + Pipeline p = buildDataflowPipeline(buildPipelineOptions()); p.apply(TextIO.Read.named("ReadInvalidGcsFile") .from("gs://bucket/tmp//file")); @@ -489,13 +490,16 @@ public void testMultiSlashGcsFileReadPath() throws IOException { instanceOf(IllegalArgumentException.class), ThrowableMessageMatcher.hasMessage(containsString("consecutive slashes")))); p.run(); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); assertValidJob(jobCaptor.getValue()); } @Test public void testMultiSlashGcsFileWritePath() throws IOException { Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from("gs://bucket/object")); + PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from(VALID_BUCKET_OBJECT)); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("consecutive slashes"); @@ -504,14 +508,15 @@ public void testMultiSlashGcsFileWritePath() throws IOException { @Test public void testInvalidTempLocation() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); + DataflowPipelineOptions options = buildPipelineOptions(); options.setTempLocation("file://temp/location"); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); DataflowPipelineRunner.fromOptions(options); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); assertValidJob(jobCaptor.getValue()); } @@ -535,34 +540,67 @@ public void testInvalidStagingLocation() throws IOException { } @Test - public void testNonExistentTempLocation() throws IOException { - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + public void testInvalidProfileLocation() throws IOException { + DataflowPipelineOptions options = buildPipelineOptions(); + options.setSaveProfilesToGcs("file://my/staging/location"); + try { + DataflowPipelineRunner.fromOptions(options); + fail("fromOptions should have failed"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("expected a valid 'gs://' path but was given")); + } - GcsUtil mockGcsUtil = buildMockGcsUtil(false /* bucket exists */); - DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); - options.setGcsUtil(mockGcsUtil); + options.setSaveProfilesToGcs("my/staging/location"); + try { + DataflowPipelineRunner.fromOptions(options); + fail("fromOptions should have failed"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("expected a valid 'gs://' path but was given")); + } + } + + @Test + public void testNonExistentTempLocation() throws IOException { + DataflowPipelineOptions options = buildPipelineOptions(); options.setTempLocation("gs://non-existent-bucket/location"); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(containsString( "Output path does not exist or is not writeable: gs://non-existent-bucket/location")); DataflowPipelineRunner.fromOptions(options); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); assertValidJob(jobCaptor.getValue()); } @Test public void testNonExistentStagingLocation() throws IOException { + DataflowPipelineOptions options = buildPipelineOptions(); + options.setStagingLocation("gs://non-existent-bucket/location"); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(containsString( + "Output path does not exist or is not writeable: gs://non-existent-bucket/location")); + DataflowPipelineRunner.fromOptions(options); + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); + assertValidJob(jobCaptor.getValue()); + } - GcsUtil mockGcsUtil = buildMockGcsUtil(false /* bucket exists */); - DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); - options.setGcsUtil(mockGcsUtil); - options.setStagingLocation("gs://non-existent-bucket/location"); + @Test + public void testNonExistentProfileLocation() throws IOException { + DataflowPipelineOptions options = buildPipelineOptions(); + options.setSaveProfilesToGcs("gs://non-existent-bucket/location"); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(containsString( "Output path does not exist or is not writeable: gs://non-existent-bucket/location")); DataflowPipelineRunner.fromOptions(options); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); + verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); assertValidJob(jobCaptor.getValue()); } @@ -587,9 +625,9 @@ public void testProjectId() throws IOException { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); options.setRunner(DataflowPipelineRunner.class); options.setProject("foo-12345"); + options.setGcsUtil(mockGcsUtil); - options.setStagingLocation("gs://spam/ham/eggs"); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); options.setGcpCredential(new TestCredential()); DataflowPipelineRunner.fromOptions(options); @@ -598,11 +636,11 @@ public void testProjectId() throws IOException { @Test public void testProjectPrefix() throws IOException { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setGcsUtil(mockGcsUtil); options.setRunner(DataflowPipelineRunner.class); options.setProject("google.com:some-project-12345"); - options.setStagingLocation("gs://spam/ham/eggs"); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); options.setGcpCredential(new TestCredential()); DataflowPipelineRunner.fromOptions(options); @@ -611,11 +649,11 @@ public void testProjectPrefix() throws IOException { @Test public void testProjectNumber() throws IOException { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setGcsUtil(mockGcsUtil); options.setRunner(DataflowPipelineRunner.class); options.setProject("12345"); - options.setStagingLocation("gs://spam/ham/eggs"); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Project ID"); @@ -627,11 +665,12 @@ public void testProjectNumber() throws IOException { @Test public void testProjectDescription() throws IOException { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setGcsUtil(mockGcsUtil); + options.setGcsUtil(mockGcsUtil); options.setRunner(DataflowPipelineRunner.class); options.setProject("some project"); - options.setStagingLocation("gs://spam/ham/eggs"); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Project ID"); @@ -645,10 +684,9 @@ public void testInvalidNumberOfWorkerHarnessThreads() throws IOException { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); options.setRunner(DataflowPipelineRunner.class); options.setProject("foo-12345"); + options.setGcsUtil(mockGcsUtil); - options.setStagingLocation("gs://spam/ham/eggs"); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); - + options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); options.as(DataflowPipelineDebugOptions.class).setNumberOfWorkerHarnessThreads(-1); thrown.expect(IllegalArgumentException.class); @@ -673,11 +711,12 @@ public void testNoStagingLocationAndNoTempLocationFails() { @Test public void testStagingLocationAndNoTempLocationSucceeds() throws Exception { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setGcsUtil(mockGcsUtil); options.setRunner(DataflowPipelineRunner.class); options.setGcpCredential(new TestCredential()); options.setProject("foo-project"); - options.setStagingLocation("gs://spam/ham/eggs"); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); + DataflowPipelineRunner.fromOptions(options); } @@ -685,11 +724,11 @@ public void testStagingLocationAndNoTempLocationSucceeds() throws Exception { @Test public void testTempLocationAndNoStagingLocationSucceeds() throws Exception { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); + options.setGcsUtil(mockGcsUtil); options.setRunner(DataflowPipelineRunner.class); options.setGcpCredential(new TestCredential()); options.setProject("foo-project"); - options.setTempLocation("gs://spam/ham/eggs"); - options.setGcsUtil(buildMockGcsUtil(true /* bucket exists */)); + options.setTempLocation(VALID_GS_SPAM_HAM_EGGS);; DataflowPipelineRunner.fromOptions(options); } @@ -795,10 +834,7 @@ protected Coder getDefaultOutputCoder(PCollection input) { @Test public void testTransformTranslatorMissing() throws IOException { - // Test that we throw if we don't provide a translation. - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - - DataflowPipelineOptions options = buildPipelineOptions(jobCaptor); + DataflowPipelineOptions options = buildPipelineOptions(); DataflowPipeline p = DataflowPipeline.create(options); p.apply(Create.of(Arrays.asList(1, 2, 3))) @@ -808,13 +844,14 @@ public void testTransformTranslatorMissing() throws IOException { thrown.expectMessage(Matchers.containsString("no translator registered")); DataflowPipelineTranslator.fromOptions(options) .translate(p, p.getRunner(), Collections.emptyList()); - assertValidJob(jobCaptor.getValue()); } @Test public void testTransformTranslator() throws IOException { // Test that we can provide a custom translation DataflowPipelineOptions options = buildPipelineOptions(); + when(mockGcsUtil.bucketExists(GcsPath.fromUri("gs://somebucket/some/path/staging"))) + .thenReturn(true); DataflowPipeline p = DataflowPipeline.create(options); TestTransform transform = new TestTransform(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index a65bc0a077..0c4b1e37b2 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -19,9 +19,9 @@ import static com.google.cloud.dataflow.sdk.util.Structs.addObject; import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; import static com.google.cloud.dataflow.sdk.util.Structs.getString; - import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; @@ -60,6 +60,7 @@ import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.View; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; +import com.google.cloud.dataflow.sdk.util.DataflowPathValidator; import com.google.cloud.dataflow.sdk.util.GcsUtil; import com.google.cloud.dataflow.sdk.util.OutputReference; import com.google.cloud.dataflow.sdk.util.PropertyNames; @@ -91,7 +92,6 @@ import java.io.Serializable; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -184,25 +184,23 @@ public void testSettingOfSdkPipelineOptions() throws IOException { .translate(p, p.getRunner(), Collections.emptyList()) .getJob(); - // Note that the contents of this materialized map may be changed by the act of reading an - // option, which will cause the default to get materialized whereas it would otherwise be - // left absent. It is permissible to simply alter this test to reflect current behavior. - Map settings = new HashMap<>(); - settings.put("appName", "DataflowPipelineTranslatorTest"); - settings.put("project", "some-project"); - settings.put("pathValidatorClass", "com.google.cloud.dataflow.sdk.util.DataflowPathValidator"); - settings.put("runner", "com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner"); - settings.put("jobName", "some-job-name"); - settings.put("tempLocation", "gs://somebucket/some/path"); - settings.put("stagingLocation", "gs://somebucket/some/path/staging"); - settings.put("stableUniqueNames", "WARNING"); - settings.put("streaming", false); - settings.put("numberOfWorkerHarnessThreads", 0); - settings.put("experiments", null); - Map sdkPipelineOptions = job.getEnvironment().getSdkPipelineOptions(); assertThat(sdkPipelineOptions, hasKey("options")); - assertEquals(settings, sdkPipelineOptions.get("options")); + Map optionsMap = (Map) sdkPipelineOptions.get("options"); + + assertThat(optionsMap, hasEntry("appName", (Object) "DataflowPipelineTranslatorTest")); + assertThat(optionsMap, hasEntry("project", (Object) "some-project")); + assertThat(optionsMap, + hasEntry("pathValidatorClass", (Object) DataflowPathValidator.class.getName())); + assertThat(optionsMap, + hasEntry("runner", (Object) DataflowPipelineRunner.class.getName())); + assertThat(optionsMap, hasEntry("jobName", (Object) "some-job-name")); + assertThat(optionsMap, hasEntry("tempLocation", (Object) "gs://somebucket/some/path")); + assertThat(optionsMap, + hasEntry("stagingLocation", (Object) "gs://somebucket/some/path/staging")); + assertThat(optionsMap, hasEntry("stableUniqueNames", (Object) "WARNING")); + assertThat(optionsMap, hasEntry("streaming", (Object) false)); + assertThat(optionsMap, hasEntry("numberOfWorkerHarnessThreads", (Object) 0)); } @Test From 7053cf5541922e438edfc7709e3f17e7fca78db6 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 13 Dec 2016 07:49:19 -0800 Subject: [PATCH 637/751] checkstyle: improve Javadoc checking This is a spiritual backport of https://github.com/apache/incubator-beam/pull/1060 Same checkstyle.xml changes, very similar fixes but recreated because of code divergence --- checkstyle.xml | 3 ++ .../examples/cookbook/TriggerExample.java | 30 +++++++++---------- .../examples/complete/game/GameStats.java | 8 ++--- .../complete/game/HourlyTeamScore.java | 6 ++-- .../examples/complete/game/LeaderBoard.java | 10 +++---- .../examples/complete/game/UserScore.java | 8 ++--- .../complete/game/injector/Injector.java | 10 +++---- .../src/main/java/DebuggingWordCount.java | 2 +- .../src/main/java/WindowedWordCount.java | 2 +- .../src/main/java/WordCount.java | 4 +-- .../java/common/DataflowExampleUtils.java | 2 +- .../common/ExampleBigQueryTableOptions.java | 2 +- .../common/ExamplePubsubTopicOptions.java | 2 +- .../cloud/dataflow/sdk/io/AvroSource.java | 1 + .../cloud/dataflow/sdk/io/BigQueryIO.java | 5 ++++ .../cloud/dataflow/sdk/io/BoundedSource.java | 14 ++++++--- .../cloud/dataflow/sdk/io/DatastoreIO.java | 2 +- .../cloud/dataflow/sdk/io/FileBasedSink.java | 1 + .../dataflow/sdk/io/OffsetBasedSource.java | 2 ++ .../cloud/dataflow/sdk/io/PubsubIO.java | 1 + .../google/cloud/dataflow/sdk/io/Sink.java | 3 ++ .../google/cloud/dataflow/sdk/io/TextIO.java | 11 +++---- .../google/cloud/dataflow/sdk/io/Write.java | 2 +- .../sdk/io/datastore/DatastoreIO.java | 2 +- .../sdk/io/datastore/DatastoreV1.java | 2 +- .../dataflow/sdk/io/range/RangeTracker.java | 2 ++ .../options/DataflowPipelineDebugOptions.java | 3 +- .../dataflow/sdk/options/PipelineOptions.java | 6 ++-- .../sdk/options/PipelineOptionsReflector.java | 2 +- .../sdk/options/ProxyInvocationHandler.java | 4 +-- .../sdk/runners/dataflow/AssignWindows.java | 6 ++-- .../sdk/runners/inprocess/EvaluatorKey.java | 4 +-- .../ExecutorServiceParallelExecutor.java | 2 +- .../inprocess/InMemoryWatermarkManager.java | 4 +-- .../runners/inprocess/InProcessCreate.java | 4 +-- .../inprocess/InProcessEvaluationContext.java | 2 +- .../inprocess/InProcessExecutionContext.java | 4 +-- .../inprocess/InProcessPipelineRunner.java | 13 ++++---- .../inprocess/InProcessTransformResult.java | 4 +-- .../runners/inprocess/TransformEvaluator.java | 2 +- .../inprocess/ViewEvaluatorFactory.java | 4 +-- .../sdk/runners/worker/IsmFormat.java | 6 ++-- .../sdk/testing/SerializableMatchers.java | 5 ++-- .../dataflow/sdk/testing/SourceTestUtils.java | 3 +- .../sdk/transforms/ApproximateQuantiles.java | 2 +- .../dataflow/sdk/transforms/Combine.java | 6 ++-- .../dataflow/sdk/transforms/CombineFns.java | 12 +++----- .../sdk/transforms/CombineWithContext.java | 4 +-- .../cloud/dataflow/sdk/transforms/DoFn.java | 2 +- .../dataflow/sdk/transforms/PTransform.java | 8 ++--- .../cloud/dataflow/sdk/transforms/ParDo.java | 2 +- .../sdk/transforms/RemoveDuplicates.java | 7 +++-- .../dataflow/sdk/transforms/WithKeys.java | 2 +- .../sdk/transforms/display/DisplayData.java | 8 ++--- .../transforms/windowing/AfterWatermark.java | 4 +-- .../sdk/transforms/windowing/Never.java | 5 ++-- .../sdk/transforms/windowing/PaneInfo.java | 4 +-- .../sdk/transforms/windowing/Window.java | 2 +- .../cloud/dataflow/sdk/util/AvroUtils.java | 2 +- .../sdk/util/BaseExecutionContext.java | 9 +++--- .../dataflow/sdk/util/BigQueryServices.java | 2 +- .../cloud/dataflow/sdk/util/DoFnRunner.java | 2 +- .../dataflow/sdk/util/DoFnRunnerBase.java | 2 +- .../util/ExposedByteArrayOutputStream.java | 1 + .../sdk/util/PerKeyCombineFnRunners.java | 4 +-- .../cloud/dataflow/sdk/util/PubsubClient.java | 3 ++ .../dataflow/sdk/util/PubsubTestClient.java | 2 +- .../dataflow/sdk/util/RandomAccessData.java | 8 ++--- .../dataflow/sdk/util/TimerInternals.java | 2 +- .../dataflow/sdk/util/common/Counter.java | 4 +-- .../cloud/dataflow/sdk/values/PInput.java | 2 +- .../sdk/testing/SystemNanoTimeSleeper.java | 2 +- 72 files changed, 176 insertions(+), 152 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index e6f4f2af87..3d99556795 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -180,6 +180,9 @@ page at http://checkstyle.sourceforge.net/config.html --> + + + diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java index ce5e08e7d2..b40d2b6f6e 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java @@ -66,11 +66,11 @@ * data into {@link Window windows} to be processed, and demonstrates using various kinds of {@link * Trigger triggers} to control when the results for each window are emitted. * - *

              This example uses a portion of real traffic data from San Diego freeways. It contains + *

              This example uses a portion of real traffic data from San Diego freeways. It contains * readings from sensor stations set up along each freeway. Each sensor reading includes a * calculation of the 'total flow' across all lanes in that freeway direction. * - *

              Concepts: + *

              Concepts: *

                *   1. The default triggering behavior
                *   2. Late data with the default trigger
              @@ -78,14 +78,14 @@
                *   4. Combining late data and speculative estimates
                * 
              * - *

              Before running this example, it will be useful to familiarize yourself with Dataflow triggers + *

              Before running this example, it will be useful to familiarize yourself with Dataflow triggers * and understand the concept of 'late data', * See: * https://cloud.google.com/dataflow/model/triggers and * * https://cloud.google.com/dataflow/model/windowing#Advanced * - *

              The example pipeline reads data from a Pub/Sub topic. By default, running the example will + *

              The example pipeline reads data from a Pub/Sub topic. By default, running the example will * also run an auxiliary pipeline to inject data from the default {@code --input} file to the * {@code --pubsubTopic}. The auxiliary pipeline puts a timestamp on the injected data so that the * example pipeline can operate on event time (rather than arrival time). The auxiliary @@ -94,24 +94,24 @@ * choosing or set {@code --input=""} which will disable the automatic Pub/Sub injection, and allow * you to use a separate tool to publish to the given topic. * - *

              The example is configured to use the default Pub/Sub topic and the default BigQuery table + *

              The example is configured to use the default Pub/Sub topic and the default BigQuery table * from the example common package (there are no defaults for a general Dataflow pipeline). * You can override them by using the {@code --pubsubTopic}, {@code --bigQueryDataset}, and * {@code --bigQueryTable} options. If the Pub/Sub topic or the BigQuery table do not exist, * the example will try to create them. * - *

              The pipeline outputs its results to a BigQuery table. + *

              The pipeline outputs its results to a BigQuery table. * Here are some queries you can use to see interesting results: * Replace {@code } in the query below with the name of the BigQuery table. * Replace {@code } in the query below with the window interval. * - *

              To see the results of the default trigger, + *

              To see the results of the default trigger, * Note: When you start up your pipeline, you'll initially see results from 'late' data. Wait after * the window duration, until the first pane of non-late data has been emitted, to see more * interesting results. * {@code SELECT * FROM enter_table_name WHERE trigger_type = "default" ORDER BY window DESC} * - *

              To see the late data i.e. dropped by the default trigger, + *

              To see the late data i.e. dropped by the default trigger, * {@code SELECT * FROM WHERE trigger_type = "withAllowedLateness" and * (timing = "LATE" or timing = "ON_TIME") and freeway = "5" ORDER BY window DESC, processing_time} * @@ -120,23 +120,23 @@ * (trigger_type = "withAllowedLateness" or trigger_type = "sequential") and freeway = "5" ORDER BY * window DESC, processing_time} * - *

              To see speculative results every minute, + *

              To see speculative results every minute, * {@code SELECT * FROM WHERE trigger_type = "speculative" and freeway = "5" * ORDER BY window DESC, processing_time} * - *

              To see speculative results every five minutes after the end of the window + *

              To see speculative results every five minutes after the end of the window * {@code SELECT * FROM WHERE trigger_type = "sequential" and timing != "EARLY" * and freeway = "5" ORDER BY window DESC, processing_time} * - *

              To see the first and the last pane for a freeway in a window for all the trigger types, + *

              To see the first and the last pane for a freeway in a window for all the trigger types, * {@code SELECT * FROM WHERE (isFirst = true or isLast = true) ORDER BY window} * - *

              To reduce the number of results for each query we can add additional where clauses. + *

              To reduce the number of results for each query we can add additional where clauses. * For examples, To see the results of the default trigger, * {@code SELECT * FROM WHERE trigger_type = "default" AND freeway = "5" AND * window = ""} * - *

              The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C) + *

              The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C) * and then exits. */ @@ -170,13 +170,13 @@ public class TriggerExample { * 5 | 60 | 10:27:20 | 10:27:25 * 5 | 60 | 10:29:00 | 11:11:00 * - *

              Dataflow tracks a watermark which records up to what point in event time the data is + *

              Dataflow tracks a watermark which records up to what point in event time the data is * complete. For the purposes of the example, we'll assume the watermark is approximately 15m * behind the current processing time. In practice, the actual value would vary over time based * on the systems knowledge of the current PubSub delay and contents of the backlog (data * that has not yet been processed). * - *

              If the watermark is 15m behind, then the window [10:00:00, 10:30:00) (in event time) would + *

              If the watermark is 15m behind, then the window [10:00:00, 10:30:00) (in event time) would * close at 10:44:59, when the watermark passes 10:30:00. */ static class CalculateTotalFlow diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java index cc77997bef..63b875af02 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java @@ -65,21 +65,21 @@ * New concepts: session windows and finding session duration; use of both * singleton and non-singleton side inputs. * - *

              This pipeline builds on the {@link LeaderBoard} functionality, and adds some "business + *

              This pipeline builds on the {@link LeaderBoard} functionality, and adds some "business * intelligence" analysis: abuse detection and usage patterns. The pipeline derives the Mean user * score sum for a window, and uses that information to identify likely spammers/robots. (The robots * have a higher click rate than the human users). The 'robot' users are then filtered out when * calculating the team scores. * - *

              Additionally, user sessions are tracked: that is, we find bursts of user activity using + *

              Additionally, user sessions are tracked: that is, we find bursts of user activity using * session windows. Then, the mean session duration information is recorded in the context of * subsequent fixed windowing. (This could be used to tell us what games are giving us greater * user retention). * - *

              Run {@link injector.Injector} to generate pubsub data for this pipeline. The Injector + *

              Run {@link injector.Injector} to generate pubsub data for this pipeline. The Injector * documentation provides more detail. * - *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration + *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration * like this: *

              {@code
                *   --project=YOUR_PROJECT_ID
              diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java
              index ff9b247b01..82904c2f18 100644
              --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java
              +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java
              @@ -46,7 +46,7 @@
                * domain, following {@link UserScore}. In addition to the concepts introduced in {@link UserScore},
                * new concepts include: windowing and element timestamps; use of {@code Filter.byPredicate()}.
                *
              - * 

              This pipeline processes data collected from gaming events in batch, building on {@link + *

              This pipeline processes data collected from gaming events in batch, building on {@link * UserScore} but using fixed windows. It calculates the sum of scores per team, for each window, * optionally allowing specification of two timestamps before and after which data is filtered out. * This allows a model where late data collected after the intended analysis window can be included, @@ -55,7 +55,7 @@ * {@link UserScore} pipeline. However, our batch processing is high-latency, in that we don't get * results from plays at the beginning of the batch's time period until the batch is processed. * - *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration + *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration * like this: *

              {@code
                *   --project=YOUR_PROJECT_ID
              @@ -66,7 +66,7 @@
                * 
              * where the BigQuery dataset you specify must already exist. * - *

              Optionally include {@code --input} to specify the batch input file path. + *

              Optionally include {@code --input} to specify the batch input file path. * To indicate a time after which the data should be filtered out, include the * {@code --stopMin} arg. E.g., {@code --stopMin=2015-10-18-23-59} indicates that any data * timestamped after 23:59 PST on 2015-10-18 should not be included in the analysis. diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java index f332a2da10..ae1491d136 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java @@ -57,26 +57,26 @@ * early/speculative results; using .accumulatingFiredPanes() to do cumulative processing of late- * arriving data. * - *

              This pipeline processes an unbounded stream of 'game events'. The calculation of the team + *

              This pipeline processes an unbounded stream of 'game events'. The calculation of the team * scores uses fixed windowing based on event time (the time of the game play event), not * processing time (the time that an event is processed by the pipeline). The pipeline calculates * the sum of scores per team, for each window. By default, the team scores are calculated using * one-hour windows. * - *

              In contrast-- to demo another windowing option-- the user scores are calculated using a + *

              In contrast-- to demo another windowing option-- the user scores are calculated using a * global window, which periodically (every ten minutes) emits cumulative user score sums. * - *

              In contrast to the previous pipelines in the series, which used static, finite input data, + *

              In contrast to the previous pipelines in the series, which used static, finite input data, * here we're using an unbounded data source, which lets us provide speculative results, and allows * handling of late data, at much lower latency. We can use the early/speculative results to keep a * 'leaderboard' updated in near-realtime. Our handling of late data lets us generate correct * results, e.g. for 'team prizes'. We're now outputting window results as they're * calculated, giving us much lower latency than with the previous batch examples. * - *

              Run {@link injector.Injector} to generate pubsub data for this pipeline. The Injector + *

              Run {@link injector.Injector} to generate pubsub data for this pipeline. The Injector * documentation provides more detail on how to do this. * - *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration + *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration * like this: *

              {@code
                *   --project=YOUR_PROJECT_ID
              diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java
              index ae4f8f5d06..f0215cf8aa 100644
              --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java
              +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java
              @@ -49,15 +49,15 @@
                * BigQuery; using standalone DoFns; use of the sum by key transform; examples of
                * Java 8 lambda syntax.
                *
              - * 

              In this gaming scenario, many users play, as members of different teams, over the course of a + *

              In this gaming scenario, many users play, as members of different teams, over the course of a * day, and their actions are logged for processing. Some of the logged game events may be late- * arriving, if users play on mobile devices and go transiently offline for a period. * - *

              This pipeline does batch processing of data collected from gaming events. It calculates the + *

              This pipeline does batch processing of data collected from gaming events. It calculates the * sum of scores per user, over an entire batch of gaming data (collected, say, for each day). The * batch processing will not include any late data that arrives after the day's cutoff point. * - *

              To execute this pipeline using the Dataflow service and static example input data, specify + *

              To execute this pipeline using the Dataflow service and static example input data, specify * the pipeline configuration like this: *

              {@code
                *   --project=YOUR_PROJECT_ID
              @@ -68,7 +68,7 @@
                * 
              * where the BigQuery dataset you specify must already exist. * - *

              Optionally include the --input argument to specify a batch input file. + *

              Optionally include the --input argument to specify a batch input file. * See the --input default value for example batch data file, or use {@link injector.Injector} to * generate your own batch data. */ diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java index 6d7b901544..39584f403a 100644 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java +++ b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java @@ -41,22 +41,22 @@ * This is a generator that simulates usage data from a mobile game, and either publishes the data * to a pubsub topic or writes it to a file. * - *

              The general model used by the generator is the following. There is a set of teams with team + *

              The general model used by the generator is the following. There is a set of teams with team * members. Each member is scoring points for their team. After some period, a team will dissolve * and a new one will be created in its place. There is also a set of 'Robots', or spammer users. * They hop from team to team. The robots are set to have a higher 'click rate' (generate more * events) than the regular team members. * - *

              Each generated line of data has the following form: + *

              Each generated line of data has the following form: * username,teamname,score,timestamp_in_ms,readable_time * e.g.: * user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 * - *

              The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if + *

              The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if * specified. It takes the following arguments: * {@code Injector project-name (topic-name|none) (filename|none)}. * - *

              To run the Injector in the mode where it publishes to PubSub, you will need to authenticate + *

              To run the Injector in the mode where it publishes to PubSub, you will need to authenticate * locally using project-based service account credentials to avoid running over PubSub * quota. * See https://developers.google.com/identity/protocols/application-default-credentials @@ -75,7 +75,7 @@ *

              * The pubsub topic will be created if it does not exist. * - *

              To run the injector in write-to-file-mode, set the topic name to "none" and specify the + *

              To run the injector in write-to-file-mode, set the topic name to "none" and specify the * filename: *

              {@code
                * Injector  none 
              diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java
              index d0fe12611c..0d5afdef12 100644
              --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java
              +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java
              @@ -158,7 +158,7 @@ public void processElement(ProcessContext c) {
                  * 

              Inherits standard configuration options and all options defined in * {@link WordCount.WordCountOptions}. */ - public static interface WordCountOptions extends WordCount.WordCountOptions { + public interface WordCountOptions extends WordCount.WordCountOptions { @Description("Regex filter pattern to use in DebuggingWordCount. " + "Only words matching this pattern will be counted.") diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java index 29921e235f..48b54069c4 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java @@ -178,7 +178,7 @@ private static TableReference getTableReference(Options options) { * table and the PubSub topic, as well as the {@link WordCount.WordCountOptions} support for * specification of the input file. */ - public static interface Options + public interface Options extends WordCount.WordCountOptions, DataflowExampleUtils.DataflowExampleUtilsOptions { @Description("Fixed window duration, in minutes") @Default.Integer(WINDOW_SIZE) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java index 150b60d2d2..c787585e25 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -158,7 +158,7 @@ public PCollection> apply(PCollection lines) { * *

              Inherits standard configuration options. */ - public static interface WordCountOptions extends PipelineOptions { + public interface WordCountOptions extends PipelineOptions { @Description("Path of the file to read from") @Default.String("gs://dataflow-samples/shakespeare/kinglear.txt") String getInputFile(); @@ -172,7 +172,7 @@ public static interface WordCountOptions extends PipelineOptions { /** * Returns "gs://${YOUR_STAGING_DIRECTORY}/counts.txt" as the default destination. */ - public static class OutputFactory implements DefaultValueFactory { + class OutputFactory implements DefaultValueFactory { @Override public String create(PipelineOptions options) { DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java index ccf1f9e8b9..e663224db9 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java @@ -67,7 +67,7 @@ public class DataflowExampleUtils { /** * Define an interface that supports the PubSub and BigQuery example options. */ - public static interface DataflowExampleUtilsOptions + public interface DataflowExampleUtilsOptions extends DataflowExampleOptions, ExamplePubsubTopicOptions, ExampleBigQueryTableOptions { } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java index bef5bfdd83..45546b1717 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java @@ -43,7 +43,7 @@ public interface ExampleBigQueryTableOptions extends DataflowPipelineOptions { /** * Returns the job name as the default BigQuery table name. */ - static class BigQueryTableFactory implements DefaultValueFactory { + class BigQueryTableFactory implements DefaultValueFactory { @Override public String create(PipelineOptions options) { return options.as(DataflowPipelineOptions.class).getJobName() diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java index 525de69cdd..f217821f1c 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java @@ -37,7 +37,7 @@ public interface ExamplePubsubTopicOptions extends DataflowPipelineOptions { /** * Returns a default Pub/Sub topic based on the project and the job names. */ - static class PubsubTopicFactory implements DefaultValueFactory { + class PubsubTopicFactory implements DefaultValueFactory { @Override public String create(PipelineOptions options) { DataflowPipelineOptions dataflowPipelineOptions = diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java index cbecba92be..f9f07a2311 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java @@ -122,6 +122,7 @@ * }

              * *

              Permissions

              + * *

              Permission requirements depend on the {@link PipelineRunner} that is used to execute the * Dataflow job. Please refer to the documentation of corresponding {@link PipelineRunner}s for * more details. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 61b66e0a98..8c120c4439 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -141,6 +141,7 @@ * BigQuery tables. * *

              Table References

              + * *

              A fully-qualified BigQuery table name consists of three components: *

                *
              • {@code projectId}: the Cloud project id (defaults to @@ -162,6 +163,7 @@ *
              * *

              Reading

              + * *

              To read from a BigQuery table, apply a {@link BigQueryIO.Read} transformation. * This produces a {@link PCollection} of {@link TableRow TableRows} as output: *

              {@code
              @@ -186,6 +188,7 @@
                * Pipeline construction will fail with a validation error if neither or both are specified.
                *
                * 

              Writing

              + * *

              To write to a BigQuery table, apply a {@link BigQueryIO.Write} transformation. * This consumes a {@link PCollection} of {@link TableRow TableRows} as input. *

              {@code
              @@ -209,6 +212,7 @@
                * dispositions are not supported in streaming mode.
                *
                * 

              Sharding BigQuery output tables

              + * *

              A common use case is to dynamically generate BigQuery table names based on * the current window. To support this, * {@link BigQueryIO.Write#to(SerializableFunction)} @@ -234,6 +238,7 @@ *

              Per-window tables are not yet supported in batch mode. * *

              Permissions

              + * *

              Permission requirements depend on the {@link PipelineRunner} that is used to execute the * Dataflow job. Please refer to the documentation of corresponding {@link PipelineRunner}s for * more details. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java index 170b56beb1..fd1a85656a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java @@ -87,11 +87,13 @@ public abstract List> splitIntoBundles( * operations, such as progress estimation and dynamic work rebalancing. * *

              Boundedness

              + * *

              Once {@link #start} or {@link #advance} has returned false, neither will be called * again on this object. * *

              Thread safety

              - * All methods will be run from the same thread except {@link #splitAtFraction}, + * + *

              All methods will be run from the same thread except {@link #splitAtFraction}, * {@link #getFractionConsumed}, {@link #getCurrentSource}, {@link #getSplitPointsConsumed()}, * and {@link #getSplitPointsRemaining()}, all of which can be called concurrently * from a different thread. There will not be multiple concurrent calls to @@ -108,7 +110,8 @@ public abstract List> splitIntoBundles( * {@link #getCurrentSource} which do not change between {@link #splitAtFraction} calls. * *

              Implementing {@link #splitAtFraction}

              - * In the course of dynamic work rebalancing, the method {@link #splitAtFraction} + * + *

              In the course of dynamic work rebalancing, the method {@link #splitAtFraction} * may be called concurrently with {@link #advance} or {@link #start}. It is critical that * their interaction is implemented in a thread-safe way, otherwise data loss is possible. * @@ -263,14 +266,17 @@ public long getSplitPointsRemaining() { * (including items already read). * *

              Usage

              + * *

              Reader subclasses can use this method for convenience to access unchanging properties of * the source being read. Alternatively, they can cache these properties in the constructor. + * *

              The framework will call this method in the course of dynamic work rebalancing, e.g. after * a successful {@link BoundedSource.BoundedReader#splitAtFraction} call. * *

              Mutability and thread safety

              - * Remember that {@link Source} objects must always be immutable. However, the return value of - * this function may be affected by dynamic work rebalancing, happening asynchronously via + * + *

              Remember that {@link Source} objects must always be immutable. However, the return value + * of this function may be affected by dynamic work rebalancing, happening asynchronously via * {@link BoundedSource.BoundedReader#splitAtFraction}, meaning it can return a different * {@link Source} object. However, the returned object itself will still itself be immutable. * Callers must take care not to rely on properties of the returned source that may be diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java index 004db8f88c..162453cd48 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java @@ -78,7 +78,7 @@ import javax.annotation.Nullable; /** - *

              {@link DatastoreIO} provides an API to Read and Write {@link PCollection PCollections} of + * {@link DatastoreIO} provides an API to Read and Write {@link PCollection PCollections} of * Google Cloud Datastore * {@link Entity} objects. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index 87102e1bac..976bc86269 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -185,6 +185,7 @@ private static String getFileExtension(String usersExtension) { * {@link FileBasedSink#fileNamingTemplate}. * *

              Temporary Bundle File Handling:

              + * *

              {@link FileBasedSink.FileBasedWriteOperation#temporaryFileRetention} controls the behavior * for managing temporary files. By default, temporary files will be removed. Subclasses can * provide a different value to the constructor. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java index 267b88fa53..170c7dd342 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java @@ -258,7 +258,9 @@ public OffsetBasedReader(OffsetBasedSource source) { * Returns the starting offset of the {@link Source.Reader#getCurrent current record}, * which has been read by the last successful {@link Source.Reader#start} or * {@link Source.Reader#advance} call. + * *

              If no such call has been made yet, the return value is unspecified. + * *

              See {@link RangeTracker} for description of offset semantics. */ protected abstract long getCurrentOffset() throws NoSuchElementException; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java index 48114e61c1..875e25bcd8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java @@ -62,6 +62,7 @@ * and consume unbounded {@link PCollection PCollections}. * *

              Permissions

              + * *

              Permission requirements depend on the {@link PipelineRunner} that is used to execute the * Dataflow job. Please refer to the documentation of corresponding * {@link PipelineRunner PipelineRunners} for more details. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java index c7bb68beb1..af244d933a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java @@ -69,6 +69,7 @@ * * *

              WriteOperation

              + * *

              {@link WriteOperation#initialize} and {@link WriteOperation#finalize} are conceptually called * once: at the beginning and end of a Write transform. However, implementors must ensure that these * methods are idempotent, as they may be called multiple times on different machines in the case of @@ -89,6 +90,7 @@ * these mutations will not be visible in finalize). * *

              Bundle Ids:

              + * *

              In order to ensure fault-tolerance, a bundle may be executed multiple times (e.g., in the * event of failure/retry or for redundancy). However, exactly one of these executions will have its * result passed to the WriteOperation's finalize method. Each call to {@link Writer#open} is passed @@ -108,6 +110,7 @@ * of output file names that it can then merge or rename using some bundle naming scheme. * *

              Writer Results:

              + * *

              {@link WriteOperation}s and {@link Writer}s must agree on a writer result type that will be * returned by a Writer after it writes a bundle. This type can be a client-defined object or an * existing type; {@link WriteOperation#getWriterResultCoder} should return a {@link Coder} for the diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 40a71132c1..124152e6f2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -109,6 +109,7 @@ * }

              * *

              Permissions

              + * *

              When run using the {@link DirectPipelineRunner}, your pipeline can read and write text files * on your local drive and remote text files on Google Cloud Storage that you have access to using * your {@code gcloud} credentials. When running in the Dataflow service using @@ -249,7 +250,7 @@ public Bound from(String filepattern) { /** * Returns a new transform for reading from text files that's like this one but - * that uses the given {@link Coder Coder} to decode each of the + * that uses the given {@link Coder} to decode each of the * lines of the file into a value of type {@code X}. * *

              Does not modify this object. @@ -634,8 +635,8 @@ public Bound withoutSharding() { /** * Returns a transform for writing to text files that's like this one - * but that uses the given {@link Coder Coder} to encode each of - * the elements of the input {@link PCollection PCollection} into an + * but that uses the given {@link Coder} to encode each of + * the elements of the input {@link PCollection} into an * output text line. Does not modify this object. * * @param the type of the elements of the input {@link PCollection} @@ -881,7 +882,7 @@ public Coder getDefaultOutputCoder() { * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader FileBasedReader} * which can decode records delimited by newline characters. * - * See {@link TextSource} for further details. + *

              See {@link TextSource} for further details. */ @VisibleForTesting static class TextBasedReader extends FileBasedReader { @@ -1013,7 +1014,7 @@ protected boolean readNextRecord() throws IOException { /** * Decodes the current element updating the buffer to only contain the unconsumed bytes. * - * This invalidates the currently stored {@code startOfSeparatorInBuffer} and + *

              This invalidates the currently stored {@code startOfSeparatorInBuffer} and * {@code endOfSeparatorInBuffer}. */ private void decodeCurrentElement() throws IOException { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java index 5881951996..3aec6fff22 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java @@ -67,7 +67,7 @@ *

              Example usage with runner-controlled sharding: * *

              {@code p.apply(Write.to(new MySink(...)));}
              - + * *

              Example usage with a fixed number of shards: * *

              {@code p.apply(Write.to(new MySink(...)).withNumShards(3));}
              diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java index 2ac1797155..403036e4f3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java @@ -19,7 +19,7 @@ import com.google.cloud.dataflow.sdk.annotations.Experimental; /** - *

              {@link DatastoreIO} provides an API for reading from and writing to + * {@link DatastoreIO} provides an API for reading from and writing to * Google Cloud Datastore over different * versions of the Cloud Datastore Client libraries. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java index 3af3932978..3cb7a6b4d5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java @@ -88,7 +88,7 @@ import javax.annotation.Nullable; /** - *

              {@link DatastoreV1} provides an API to Read, Write and Delete {@link PCollection PCollections} + * {@link DatastoreV1} provides an API to Read, Write and Delete {@link PCollection PCollections} * of Google Cloud Datastore version v1 * {@link Entity} objects. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java index 84359f1aa1..cd67b85548 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java @@ -185,12 +185,14 @@ public interface RangeTracker { /** * Atomically determines whether a record at the given position can be returned and updates * internal state. In particular: + * *

                *
              • If {@code isAtSplitPoint} is {@code true}, and {@code recordStart} is outside the current * range, returns {@code false}; *
              • Otherwise, updates the last-consumed position to {@code recordStart} and returns * {@code true}. *
              + * *

              This method MUST be called on all split point records. It may be called on every record. */ boolean tryReturnRecordAt(boolean isAtSplitPoint, PositionT recordStart); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java index 202003e275..12f8d40037 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java @@ -228,8 +228,7 @@ public Dataflow create(PipelineOptions options) { * thrashing or out of memory. The location of the heap file will either be echoed back * to the user, or the user will be given the opportunity to download the heap file. * - *

              - * CAUTION: Heap dumps can of comparable size to the default boot disk. Consider increasing + *

              CAUTION: Heap dumps can of comparable size to the default boot disk. Consider increasing * the boot disk size before setting this flag to true. */ @Description("If {@literal true}, save a heap dump before killing a thread or process " diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java index 701fe47976..f9c26f6136 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java @@ -91,7 +91,7 @@ * *

              Defining Your Own PipelineOptions

              * - * Defining your own {@link PipelineOptions} is the way for you to make configuration + *

              Defining your own {@link PipelineOptions} is the way for you to make configuration * options available for both local execution and execution via a {@link PipelineRunner}. * By having PipelineOptionsFactory as your command-line interpreter, you will provide * a standardized way for users to interact with your application via the command-line. @@ -115,7 +115,7 @@ * *

              Restrictions

              * - * Since PipelineOptions can be "cast" to multiple types dynamically using + *

              Since PipelineOptions can be "cast" to multiple types dynamically using * {@link PipelineOptions#as(Class)}, a property must conform to the following set of restrictions: *

                *
              • Any property with the same name must have the same return type for all derived @@ -156,7 +156,7 @@ * *

                Registration Of PipelineOptions

                * - * Registration of {@link PipelineOptions} by an application guarantees that the + *

                Registration of {@link PipelineOptions} by an application guarantees that the * {@link PipelineOptions} is composable during execution of their {@link Pipeline} and * meets the restrictions listed above or will fail during registration. Registration * also lists the registered {@link PipelineOptions} when {@code --help} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java index 094590a322..77cf91592f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java @@ -67,7 +67,7 @@ static Set getOptionSpecs(Class o /** * Retrieve metadata for the full set of pipeline options visible within the type hierarchy * closure of the set of input interfaces. An option is "visible" if: - *

                + * *

                  *
                • The option is defined within the interface hierarchy closure of the input * {@link PipelineOptions}.
                • diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index 5070a52569..8ea2a3a49d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -237,7 +237,7 @@ public boolean equals(Object obj) { * Backing implementation for {@link PipelineOptions#as(Class)}. * * @param iface The interface that the returned object needs to implement. - * @return An object that implements the interface . + * @return An object that implements the interface {@code }. */ synchronized T as(Class iface) { checkNotNull(iface); @@ -389,7 +389,7 @@ private String displayDataString(Object value) { /** * Marker interface used when the original {@link PipelineOptions} interface is not known at * runtime. This can occur if {@link PipelineOptions} are deserialized from JSON. - *

                  + * *

                  Pipeline authors can ensure {@link PipelineOptions} type information is available at * runtime by registering their {@link PipelineOptions options} interfaces. See the "Registration" * section of {@link PipelineOptions} documentation. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java index 093783de85..846de43bb6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java @@ -28,14 +28,14 @@ * A primitive {@link PTransform} that implements the {@link Window#into(WindowFn)} * {@link PTransform}. * - * For an application of {@link Window#into(WindowFn)} that changes the {@link WindowFn}, applies + *

                  For an application of {@link Window#into(WindowFn)} that changes the {@link WindowFn}, applies * a primitive {@link PTransform} in the Dataflow service. * - * For an application of {@link Window#into(WindowFn)} that does not change the {@link WindowFn}, + *

                  For an application of {@link Window#into(WindowFn)} that does not change the {@link WindowFn}, * applies an identity {@link ParDo} and sets the windowing strategy of the output * {@link PCollection}. * - * For internal use only. + *

                  For internal use only. * * @param the type of input element */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java index 307bc5cdb5..f6aafcc1b3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java @@ -22,8 +22,8 @@ /** * A (Transform, Pipeline Execution) key for stateful evaluators. * - * Source evaluators are stateful to ensure data is not read multiple times. Evaluators are cached - * to ensure that the reader is not restarted if the evaluator is retriggered. An + *

                  Source evaluators are stateful to ensure data is not read multiple times. Evaluators are + * cached to ensure that the reader is not restarted if the evaluator is retriggered. An * {@link EvaluatorKey} is used to ensure that multiple Pipelines can be executed without sharing * the same evaluators. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java index 4855af6496..88c93f795c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java @@ -272,7 +272,7 @@ public final void handleThrowable(CommittedBundle inputBundle, Throwable t) { /** * An internal status update on the state of the executor. * - * Used to signal when the executor should be shut down (due to an exception). + *

                  Used to signal when the executor should be shut down (due to an exception). */ @AutoValue abstract static class ExecutorUpdate { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java index 80dbd9917a..9d145e8c09 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java @@ -167,7 +167,7 @@ public boolean isAdvanced() { /** * Returns the {@link WatermarkUpdate} that is a result of combining the two watermark updates. * - * If either of the input {@link WatermarkUpdate WatermarkUpdates} were advanced, the result + *

                  If either of the input {@link WatermarkUpdate WatermarkUpdates} were advanced, the result * {@link WatermarkUpdate} has been advanced. */ public WatermarkUpdate union(WatermarkUpdate that) { @@ -640,7 +640,7 @@ public Iterable> apply(WindowedValue input) { * latestTime argument and put in in the result with the same key, then remove all of the keys * which have no more pending timers. * - * The result collection retains ordering of timers (from earliest to latest). + *

                  The result collection retains ordering of timers (from earliest to latest). */ private static Map, List> extractFiredTimers( Instant latestTime, Map, NavigableSet> objectTimers) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java index 48ef560f88..802851a8db 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java @@ -44,8 +44,8 @@ * An in-process implementation of the {@link Values Create.Values} {@link PTransform}, implemented * using a {@link BoundedSource}. * - * The coder is inferred via the {@link Values#getDefaultOutputCoder(PInput)} method on the original - * transform. + *

                  The coder is inferred via the {@link Values#getDefaultOutputCoder(PInput)} method on the + * original transform. */ class InProcessCreate extends ForwardingPTransform> { private final Create.Values original; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java index b9bea5b2f4..7669f4ba97 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java @@ -351,7 +351,7 @@ public ReadyCheckingSideInputReader createSideInputReader( * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent * of all other {@link CounterSet CounterSets} created by this call. * - * The {@link InProcessEvaluationContext} is responsible for unifying the counters present in + *

                  The {@link InProcessEvaluationContext} is responsible for unifying the counters present in * all created {@link CounterSet CounterSets} when the transforms that call this method * complete. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java index 31557d35fa..46894cdaf5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java @@ -26,8 +26,8 @@ /** * Execution Context for the {@link InProcessPipelineRunner}. * - * This implementation is not thread safe. A new {@link InProcessExecutionContext} must be created - * for each thread that requires it. + *

                  This implementation is not thread safe. A new {@link InProcessExecutionContext} must be + * created for each thread that requires it. */ class InProcessExecutionContext extends BaseExecutionContext { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java index c51a2a027b..9f19c588ef 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java @@ -157,11 +157,10 @@ public interface CommittedBundle { * Return a new {@link CommittedBundle} that is like this one, except calls to * {@link #getElements()} will return the provided elements. This bundle is unchanged. * - *

                  - * The value of the {@link #getSynchronizedProcessingOutputWatermark() synchronized processing - * output watermark} of the returned {@link CommittedBundle} is equal to the value returned from - * the current bundle. This is used to ensure a {@link PTransform} that could not complete - * processing on input elements properly holds the synchronized processing time to the + *

                  The value of the {@link #getSynchronizedProcessingOutputWatermark() synchronized + * processing output watermark} of the returned {@link CommittedBundle} is equal to the value + * returned from the current bundle. This is used to ensure a {@link PTransform} that could not + * complete processing on input elements properly holds the synchronized processing time to the * appropriate value. */ CommittedBundle withElements(Iterable> elements); @@ -315,7 +314,7 @@ private BundleFactory createBundleFactory(InProcessPipelineOptions pipelineOptio /** * The result of running a {@link Pipeline} with the {@link InProcessPipelineRunner}. * - * Throws {@link UnsupportedOperationException} for all methods. + *

                  Throws {@link UnsupportedOperationException} for all methods. */ public static class InProcessPipelineResult implements PipelineResult { private final InProcessExecutor executor; @@ -372,7 +371,7 @@ public AggregatorValues getAggregatorValues(Aggregator aggregator) * {@link InProcessPipelineOptions#isShutdownUnboundedProducersWithMaxWatermark()} set to false, * this method will never return. * - * See also {@link InProcessExecutor#awaitCompletion()}. + *

                  See also {@link InProcessExecutor#awaitCompletion()}. */ public State awaitCompletion() throws Throwable { if (!state.isTerminal()) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java index fcd37a09a1..996d51b6b1 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java @@ -58,7 +58,7 @@ interface InProcessTransformResult { /** * Returns the Watermark Hold for the transform at the time this result was produced. * - * If the transform does not set any watermark hold, returns + *

                  If the transform does not set any watermark hold, returns * {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. */ Instant getWatermarkHold(); @@ -66,7 +66,7 @@ interface InProcessTransformResult { /** * Returns the State used by the transform. * - * If this evaluation did not access state, this may return null. + *

                  If this evaluation did not access state, this may return null. */ @Nullable CopyOnAccessInMemoryStateInternals getState(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java index be54ec20ee..f4e9d028f7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java @@ -35,7 +35,7 @@ interface TransformEvaluator { /** * Finish processing the bundle of this {@link TransformEvaluator}. * - * After {@link #finishBundle()} is called, the {@link TransformEvaluator} will not be reused, + *

                  After {@link #finishBundle()} is called, the {@link TransformEvaluator} will not be reused, * and no more elements will be processed. * * @return an {@link InProcessTransformResult} containing the results of this bundle evaluation. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java index e2aabc25de..9b296dbdc7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java @@ -130,8 +130,8 @@ protected PTransform, PCollectionView> delegate() { /** * An in-process implementation of the {@link CreatePCollectionView} primitive. * - * This implementation requires the input {@link PCollection} to be an iterable, which is provided - * to {@link PCollectionView#fromIterableInternal(Iterable)}. + *

                  This implementation requires the input {@link PCollection} to be an iterable, which is + * provided to {@link PCollectionView#fromIterableInternal(Iterable)}. */ public static final class WriteView extends PTransform>, PCollectionView> { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java index 289a77beb1..b2a3fd592f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java @@ -331,7 +331,7 @@ int getNumberOfShardKeyCoders(List keyComponents) { /** * Computes the shard id for the given key component(s). * - * The shard keys are encoded into their byte representations and hashed using the + *

                  The shard keys are encoded into their byte representations and hashed using the * * 32-bit murmur3 algorithm, x86 variant (little-endian variant), * using {@code 1225801234} as the seed value. We ensure that shard ids for @@ -344,7 +344,7 @@ public int hash(List keyComponents) { /** * Computes the shard id for the given key component(s). * - * Mutates {@code keyBytes} such that when returned, contains the encoded + *

                  Mutates {@code keyBytes} such that when returned, contains the encoded * version of the key components. */ int encodeAndHash(List keyComponents, RandomAccessData keyBytesToMutate) { @@ -684,7 +684,7 @@ public int hashCode() { /** * A coder for {@link IsmShard}s. * - * The shard descriptor is encoded as: + *

                  The shard descriptor is encoded as: *

                    *
                  • id (variable length integer encoding)
                  • *
                  • blockOffset (variable length long encoding)
                  • diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java index da5171e21f..85b1d5b072 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java @@ -1046,14 +1046,13 @@ public String toString() { * the {@link Matcher} returned by {@link SerializableSupplier#get() get()} when it is invoked * during matching (which may occur on another machine, such as a Dataflow worker). * - * + *
                    {@code
                        * return fromSupplier(new SerializableSupplier>() {
                    -   *   *     @Override
                        *     public Matcher get() {
                        *       return new MyMatcherForT();
                        *     }
                        * });
                    -   * 
                    +   * }
                    */ public static SerializableMatcher fromSupplier( SerializableSupplier> supplier) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java index 0b7fb3ea8c..8dbc600b8f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java @@ -287,7 +287,8 @@ public SplitAtFractionResult(int numPrimaryItems, int numResidualItems) { * Asserts that the {@code source}'s reader either fails to {@code splitAtFraction(fraction)} * after reading {@code numItemsToReadBeforeSplit} items, or succeeds in a way that is * consistent according to {@link #assertSplitAtFractionSucceedsAndConsistent}. - *

                    Returns SplitAtFractionResult. + * + *

                    Returns SplitAtFractionResult. */ public static SplitAtFractionResult assertSplitAtFractionBehavior( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java index 75ec7a8e1d..a995431b7a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java @@ -208,7 +208,7 @@ PTransform, PCollection>> globally(int numQuantiles) { *

              * *

              The default error bound is {@code 1 / N}, though in practice - * the accuracy tends to be much better.

              See + * the accuracy tends to be much better. See * {@link #create(int, Comparator, long, double)} for * more information about the meaning of {@code epsilon}, and * {@link #withEpsilon} for a convenient way to adjust it. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java index a1d124ca78..bd1ccf977f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java @@ -672,7 +672,7 @@ public void verifyDeterministic() throws NonDeterministicException { * An abstract subclass of {@link CombineFn} for implementing combiners that are more * easily and efficiently expressed as binary operations on ints * - *

              It uses {@code int[0]} as the mutable accumulator. + *

              It uses {@code int[0]} as the mutable accumulator. */ public abstract static class BinaryCombineIntegerFn extends CombineFn { @@ -754,7 +754,7 @@ public Counter getCounter(String name) { * An abstract subclass of {@link CombineFn} for implementing combiners that are more * easily and efficiently expressed as binary operations on longs. * - *

              It uses {@code long[0]} as the mutable accumulator. + *

              It uses {@code long[0]} as the mutable accumulator. */ public abstract static class BinaryCombineLongFn extends CombineFn { /** @@ -834,7 +834,7 @@ public Counter getCounter(String name) { * An abstract subclass of {@link CombineFn} for implementing combiners that are more * easily and efficiently expressed as binary operations on doubles. * - *

              It uses {@code double[0]} as the mutable accumulator. + *

              It uses {@code double[0]} as the mutable accumulator. */ public abstract static class BinaryCombineDoubleFn extends CombineFn { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java index 44004660d9..b9ee5aeeeb 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java @@ -66,7 +66,7 @@ public class CombineFns { *

              The same {@link TupleTag} cannot be used in a composition multiple times. * *

              Example: - *

              { @code
              +   * 
              {@code
                  * PCollection> latencies = ...;
                  *
                  * TupleTag maxLatencyTag = new TupleTag();
              @@ -74,7 +74,6 @@ public class CombineFns {
                  *
                  * SimpleFunction identityFn =
                  *     new SimpleFunction() {
              -   *       @Override
                  *       public Integer apply(Integer input) {
                  *           return input;
                  *       }};
              @@ -87,7 +86,6 @@ public class CombineFns {
                  * PCollection finalResultCollection = maxAndMean
                  *     .apply(ParDo.of(
                  *         new DoFn, T>() {
              -   *           @Override
                  *           public void processElement(ProcessContext c) throws Exception {
                  *             KV e = c.element();
                  *             Integer maxLatency = e.getValue().get(maxLatencyTag);
              @@ -96,7 +94,7 @@ public class CombineFns {
                  *             c.output(...some T...);
                  *           }
                  *         }));
              -   * } 
              + * }
              */ public static ComposeKeyedCombineFnBuilder composeKeyed() { return new ComposeKeyedCombineFnBuilder(); @@ -109,7 +107,7 @@ public static ComposeKeyedCombineFnBuilder composeKeyed() { *

              The same {@link TupleTag} cannot be used in a composition multiple times. * *

              Example: - *

              { @code
              +   * 
              {@code
                  * PCollection globalLatencies = ...;
                  *
                  * TupleTag maxLatencyTag = new TupleTag();
              @@ -117,7 +115,6 @@ public static ComposeKeyedCombineFnBuilder composeKeyed() {
                  *
                  * SimpleFunction identityFn =
                  *     new SimpleFunction() {
              -   *       @Override
                  *       public Integer apply(Integer input) {
                  *           return input;
                  *       }};
              @@ -130,7 +127,6 @@ public static ComposeKeyedCombineFnBuilder composeKeyed() {
                  * PCollection finalResultCollection = maxAndMean
                  *     .apply(ParDo.of(
                  *         new DoFn() {
              -   *           @Override
                  *           public void processElement(ProcessContext c) throws Exception {
                  *             CoCombineResult e = c.element();
                  *             Integer maxLatency = e.get(maxLatencyTag);
              @@ -139,7 +135,7 @@ public static ComposeKeyedCombineFnBuilder composeKeyed() {
                  *             c.output(...some T...);
                  *           }
                  *         }));
              -   * } 
              + * }
              */ public static ComposeCombineFnBuilder compose() { return new ComposeCombineFnBuilder(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java index e9f29fccb4..d7439b1fc5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java @@ -63,7 +63,7 @@ public interface RequiresContextInternal {} * A combine function that has access to {@code PipelineOptions} and side inputs through * {@code CombineWithContext.Context}. * - * See the equivalent {@link CombineFn} for details about combine functions. + *

              See the equivalent {@link CombineFn} for details about combine functions. */ public abstract static class CombineFnWithContext extends CombineFnBase.AbstractGlobalCombineFn @@ -180,7 +180,7 @@ public void populateDisplayData(DisplayData.Builder builder) { * A keyed combine function that has access to {@code PipelineOptions} and side inputs through * {@code CombineWithContext.Context}. * - * See the equivalent {@link KeyedCombineFn} for details about keyed combine functions. + *

              See the equivalent {@link KeyedCombineFn} for details about keyed combine functions. */ public abstract static class KeyedCombineFnWithContext extends CombineFnBase.AbstractPerKeyCombineFn diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java index fffe769995..c9dc9f433a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java @@ -298,7 +298,7 @@ public abstract class ProcessContext extends Context { * timestamps can only be shifted forward to future. For infinite * skew, return {@code Duration.millis(Long.MAX_VALUE)}. * - *

              Note that producing an element whose timestamp is less than the + *

              Note that producing an element whose timestamp is less than the * current timestamp may result in late data, i.e. returning a non-zero * value here does not impact watermark calculations used for firing * windows. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java index 8499bcb141..38e0312857 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java @@ -287,9 +287,9 @@ protected Coder getDefaultOutputCoder() throws CannotProvideCoderException { * Returns the default {@code Coder} to use for the output of this * single-output {@code PTransform} when applied to the given input. * - * @throws CannotProvideCoderException if none can be inferred. - * *

              By default, always throws. + * + * @throws CannotProvideCoderException if none can be inferred. */ protected Coder getDefaultOutputCoder(@SuppressWarnings("unused") InputT input) throws CannotProvideCoderException { @@ -300,9 +300,9 @@ protected Coder getDefaultOutputCoder(@SuppressWarnings("unused") InputT inpu * Returns the default {@code Coder} to use for the given output of * this single-output {@code PTransform} when applied to the given input. * - * @throws CannotProvideCoderException if none can be inferred. - * *

              By default, always throws. + * + * @throws CannotProvideCoderException if none can be inferred. */ public Coder getDefaultOutputCoder( InputT input, @SuppressWarnings("unused") TypedPValue output) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java index 29bfb7f549..2134de6474 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java @@ -101,7 +101,7 @@ * If this method is not overridden, this call may be optimized away.

            2. *
            * - * Each of the calls to any of the {@link DoFn DoFn's} processing + *

            Each of the calls to any of the {@link DoFn DoFn's} processing * methods can produce zero or more output elements. All of the * of output elements from all of the {@link DoFn} instances * are included in the output {@link PCollection}. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java index 8913138abb..4388c2d5b8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java @@ -105,7 +105,7 @@ public Void apply(Iterable iter) { * A {@link RemoveDuplicates} {@link PTransform} that uses a {@link SerializableFunction} to * obtain a representative value for each input element. * - * Construct via {@link RemoveDuplicates#withRepresentativeValueFn(SerializableFunction)}. + *

            Construct via {@link RemoveDuplicates#withRepresentativeValueFn(SerializableFunction)}. * * @param the type of input and output element * @param the type of representative values used to dedup @@ -143,8 +143,9 @@ public T apply(T left, T right) { * Return a {@code WithRepresentativeValues} {@link PTransform} that is like this one, but with * the specified output type descriptor. * - * Required for use of {@link RemoveDuplicates#withRepresentativeValueFn(SerializableFunction)} - * in Java 8 with a lambda as the fn. + *

            Required for use of + * {@link RemoveDuplicates#withRepresentativeValueFn(SerializableFunction)} in Java 8 with a + * lambda as the fn. * * @param type a {@link TypeDescriptor} describing the representative type of this * {@code WithRepresentativeValues} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java index c06795c703..4c1ce7f073 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java @@ -98,7 +98,7 @@ private WithKeys(SerializableFunction fn, Class keyClass) { /** * Return a {@link WithKeys} that is like this one with the specified key type descriptor. * - * For use with lambdas in Java 8, either this method must be called with an appropriate type + *

            For use with lambdas in Java 8, either this method must be called with an appropriate type * descriptor or {@link PCollection#setCoder(Coder)} must be called on the output * {@link PCollection}. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 0dadedf7ea..599245f911 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -164,7 +164,7 @@ public interface Builder { * } * * - * Using {@code include(subcomponent)} will associate each of the registered items with the + *

            Using {@code include(subcomponent)} will associate each of the registered items with the * namespace of the {@code subcomponent} being registered. To register display data in the * current namespace, such as from a base class implementation, use * {@code subcomponent.populateDisplayData(builder)} instead. @@ -233,7 +233,7 @@ public String getNamespace() { /** * The key for the display item. Each display item is created with a key and value - * via {@link DisplayData#item). + * via {@link DisplayData#item}. */ @JsonGetter("key") public String getKey() { @@ -269,8 +269,8 @@ public Object getValue() { * value. For example, the {@link #getValue() value} for {@link Type#JAVA_CLASS} items contains * the full class name with package, while the short value contains just the class name. * - * A {@link #getValue() value} will be provided for each display item, and some types may also - * provide a short-value. If a short value is provided, display data consumers may + *

            A {@link #getValue() value} will be provided for each display item, and some types may + * also provide a short-value. If a short value is provided, display data consumers may * choose to display it instead of or in addition to the {@link #getValue() value}. */ @JsonGetter("shortValue") diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index 6ffa85c6bd..5fd8554c90 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -32,7 +32,7 @@ import javax.annotation.Nullable; /** - *

            {@code AfterWatermark} triggers fire based on progress of the system watermark. This time is a + * {@code AfterWatermark} triggers fire based on progress of the system watermark. This time is a * lower-bound, sometimes heuristically established, on event times that have been fully processed * by the pipeline. * @@ -56,7 +56,7 @@ * *

            The watermark is the clock that defines {@link TimeDomain#EVENT_TIME}. * - * Additionaly firings before or after the watermark can be requested by calling + *

            Additionaly firings before or after the watermark can be requested by calling * {@code AfterWatermark.pastEndOfWindow.withEarlyFirings(OnceTrigger)} or * {@code AfterWatermark.pastEndOfWindow.withEarlyFirings(OnceTrigger)}. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java index 9fa8498220..12a3cc707c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java @@ -23,9 +23,8 @@ /** * A trigger which never fires. * - *

            - * Using this trigger will only produce output when the watermark passes the end of the - * {@link BoundedWindow window} plus the {@link Window#withAllowedLateness() allowed + *

            Using this trigger will only produce output when the watermark passes the end of the + * {@link BoundedWindow window} plus the {@link Window#withAllowedLateness allowed * lateness}. */ public final class Never { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java index 0fdf590a87..3cb556852f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java @@ -94,7 +94,7 @@ public final class PaneInfo { * And a {@code LATE} pane cannot contain locally on-time elements. * * - * However, note that: + *

            However, note that: *

              *
            1. An {@code ON_TIME} pane may contain locally late elements. It may even contain only * locally late elements. Provided a locally late element finds its way into an {@code ON_TIME} @@ -256,7 +256,7 @@ public long getIndex() { /** * The zero-based index of this trigger firing among non-speculative panes. * - *

              This will return 0 for the first non-{@link Timing#EARLY} timer firing, 1 for the next one, + *

              This will return 0 for the first non-{@link Timing#EARLY} timer firing, 1 for the next one, * etc. * *

              Always -1 for speculative data. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java index 60b9e5d904..70ed44c71d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java @@ -42,7 +42,7 @@ * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey GroupByKeys}, * including one within composite transforms, will group by the combination of * keys and windows. - + * *

              See {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey} * for more information about how grouping with windows works. * diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java index 15acc8899d..35c11f6c88 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java @@ -193,7 +193,7 @@ static String formatTimestamp(String timestamp) { /** * Utility function to convert from an Avro {@link GenericRecord} to a BigQuery {@link TableRow}. * - * See + *

              See * "Avro format" for more information. */ public static TableRow convertGenericRecordToTableRow(GenericRecord record, TableSchema schema) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java index 6a0ccf3531..19ba8d6256 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java @@ -38,16 +38,17 @@ *

              BaseExecutionContext is generic to allow implementing subclasses to return a concrete subclass * of {@link StepContext} from {@link #getOrCreateStepContext(String, String, StateSampler)} and * {@link #getAllStepContexts()} without forcing each subclass to override the method, e.g. - *

              - * @Override
              + *
              + * 
              {@code
              + * {@literal @}Override
                * StreamingModeExecutionContext.StepContext getOrCreateStepContext(...) {
                *   return (StreamingModeExecutionContext.StepContext) super.getOrCreateStepContext(...);
                * }
              - * 
              + * }
              * *

              When a subclass of {@code BaseExecutionContext} has been downcast, the return types of * {@link #createStepContext(String, String, StateSampler)}, - * {@link #getOrCreateStepContext(String, String, StateSampler}, and {@link #getAllStepContexts()} + * {@link #getOrCreateStepContext(String, String, StateSampler)}, and {@link #getAllStepContexts()} * will be appropriately specialized. */ public abstract class BaseExecutionContext diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java index b13feeade5..ec96009494 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -105,7 +105,7 @@ JobStatistics dryRunQuery(String projectId, JobConfigurationQuery queryConfig) /** * Gets the specified {@link Job} by the given {@link JobReference}. * - * Returns null if the job is not found. + *

              Returns null if the job is not found. */ Job getJob(JobReference jobRef) throws IOException, InterruptedException; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java index 81ccbf1fe8..e0ce0ae097 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java @@ -47,7 +47,7 @@ public interface ReduceFnExecutor { /** * Gets this object as a {@link DoFn}. * - * Most implementors of this interface are expected to be {@link DoFn} instances, and will + *

              Most implementors of this interface are expected to be {@link DoFn} instances, and will * return themselves. */ DoFn, KV> asDoFn(); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java index 51237a03b8..0c2465161e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java @@ -56,7 +56,7 @@ /** * A base implementation of {@link DoFnRunner}. * - *

              Sub-classes should override {@link #invokeProcessElement}. + *

              Sub-classes should override {@link #invokeProcessElement}. */ public abstract class DoFnRunnerBase implements DoFnRunner { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java index d8e4d50714..8bb931ae21 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java @@ -56,6 +56,7 @@ private void fallback() { * Write {@code b} to the stream and take the ownership of {@code b}. * If the stream is empty, {@code b} itself will be used as the content of the stream and * no content copy will be involved. + * *

              Note: After passing any byte array to this method, it must not be modified again. * * @throws IOException diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java index 6606c5451f..a11b275a4f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java @@ -49,7 +49,7 @@ public class PerKeyCombineFnRunners { /** * An implementation of {@link PerKeyCombineFnRunner} with {@link KeyedCombineFn}. * - * It forwards functions calls to the {@link KeyedCombineFn}. + *

              It forwards functions calls to the {@link KeyedCombineFn}. */ private static class KeyedCombineFnRunner implements PerKeyCombineFnRunner { @@ -145,7 +145,7 @@ public AccumT compact(K key, AccumT accumulator, PipelineOptions options, /** * An implementation of {@link PerKeyCombineFnRunner} with {@link KeyedCombineFnWithContext}. * - * It forwards functions calls to the {@link KeyedCombineFnWithContext}. + *

              It forwards functions calls to the {@link KeyedCombineFnWithContext}. */ private static class KeyedCombineFnWithContextRunner implements PerKeyCombineFnRunner { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java index 2b24dd9891..e544bde333 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java @@ -85,6 +85,7 @@ private static Long asMsSinceEpoch(@Nullable String timestamp) { /** * Return the timestamp (in ms since unix epoch) to use for a Pubsub message with {@code * attributes} and {@code pubsubTimestamp}. + * *

              If {@code timestampLabel} is non-{@literal null} then the message attributes must contain * that label, and the value of that label will be taken as the timestamp. * Otherwise the timestamp will be taken from the Pubsub publish timestamp {@code @@ -298,6 +299,7 @@ public static TopicPath topicPathFromName(String projectId, String topicName) { /** * A message to be sent to Pubsub. + * *

              NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. * Java serialization is never used for non-test clients. */ @@ -356,6 +358,7 @@ public int hashCode() { /** * A message received from Pubsub. + * *

              NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. * Java serialization is never used for non-test clients. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java index df8c1a72e6..c3a5a4e959 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java @@ -42,7 +42,7 @@ public class PubsubTestClient extends PubsubClient { /** * Mimic the state of the simulated Pubsub 'service'. * - * Note that the {@link PubsubTestClientFactory} is serialized/deserialized even when running + *

              Note that the {@link PubsubTestClientFactory} is serialized/deserialized even when running * test pipelines. Meanwhile it is valid for multiple {@link PubsubTestClient}s to be created * from the same client factory and run in parallel. Thus we can't enforce aliasing of the * following data structures over all clients and must resort to a static. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java index 6c96c8e703..359e40ff64 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java @@ -44,8 +44,8 @@ * also provides random access to bytes stored within. This wrapper allows users to finely * control the number of byte copies that occur. * - * Anything stored within the in-memory buffer from offset {@link #size()} is considered temporary - * unused storage. + *

              Anything stored within the in-memory buffer from offset {@link #size()} is considered + * temporary unused storage. */ @NotThreadSafe public class RandomAccessData { @@ -54,7 +54,7 @@ public class RandomAccessData { * This follows the same encoding scheme as {@link ByteArrayCoder}. * This coder is deterministic and consistent with equals. * - * This coder does not support encoding positive infinity. + *

              This coder does not support encoding positive infinity. */ public static class RandomAccessDataCoder extends AtomicCoder { private static final RandomAccessDataCoder INSTANCE = new RandomAccessDataCoder(); @@ -192,7 +192,7 @@ public int commonPrefixLength(RandomAccessData o1, RandomAccessData o2) { * is strictly greater than this. Note that if this is empty or is all 0xFF then * a token value of positive infinity is returned. * - * The {@link UnsignedLexicographicalComparator} supports comparing {@link RandomAccessData} + *

              The {@link UnsignedLexicographicalComparator} supports comparing {@link RandomAccessData} * with support for positive infinitiy. */ public RandomAccessData increment() throws IOException { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java index 8cbd393da6..57518b1ac3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java @@ -111,7 +111,7 @@ public interface TimerInternals { *

            2. However will never be behind the global input watermark for any following computation. *
            * - *

            In pictures: + *

            In pictures: *

                *  |              |       |       |       |
                *  |              |   D   |   C   |   B   |   A
            diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java
            index 5dda81189e..0b73d382b0 100644
            --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java
            +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java
            @@ -364,11 +364,11 @@ public boolean committing() {
               /**
                * Changes the counter from {@code CommitState.COMMITTING} to {@code CommitState.COMMITTED}.
                *
            -   * @return true if successful.
            -   *
                * 

            False return indicates that the counter was updated while the committing is pending. * That counter update might or might not has been committed. The {@code commitState} has to * stay in {@code CommitState.DIRTY}. + * + * @return true if successful. */ public boolean committed() { return commitState.compareAndSet(CommitState.COMMITTING, CommitState.COMMITTED); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java index c3805c7e49..77afe9d378 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java @@ -46,7 +46,7 @@ public interface PInput { Collection expand(); /** - *

            After building, finalizes this {@code PInput} to make it ready for + * After building, finalizes this {@code PInput} to make it ready for * being used as an input to a {@link com.google.cloud.dataflow.sdk.transforms.PTransform}. * *

            Automatically invoked whenever {@code apply()} is invoked on diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java index d8507f79b0..4a727bc7a7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java @@ -28,7 +28,7 @@ * href="https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks"> * article goes into further detail about this issue. * - * This {@link Sleeper} uses {@link System#nanoTime} + *

            This {@link Sleeper} uses {@link System#nanoTime} * as the timing source and {@link LockSupport#parkNanos} as the wait method. * Note that usage of this sleeper may impact performance because * of the relatively more expensive methods being invoked when compared to From 66f664ce8fadd5765d98912101be60d605c4680f Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 13 Dec 2016 08:13:47 -0800 Subject: [PATCH 638/751] Kafka contrib: checkstyle fixes --- .../google/cloud/dataflow/contrib/kafka/KafkaIO.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java index 47335bdbc9..67d523a1ac 100644 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java +++ b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java @@ -106,7 +106,7 @@ *

            Although most applications consumer single topic, the source can be configured to consume * multiple topics or even a specific set of {@link TopicPartition}s. * - *

            To configure a Kafka source, you must specify at the minimum Kafka bootstrapServers + *

            To configure a Kafka source, you must specify at the minimum Kafka bootstrapServers * and one or more topics to consume. The following example illustrates various options for * configuring the source : * @@ -153,7 +153,7 @@ * *

            Writing to Kafka

            * - * KafkaIO sink supports writing key-value pairs to a Kafka topic. Users can also write just the + *

            KafkaIO sink supports writing key-value pairs to a Kafka topic. Users can also write just the * values. To configure a Kafka sink, you must specify at the minimum Kafka * bootstrapServers and the topic to write to. The following example illustrates various * options for configuring the sink: @@ -175,7 +175,7 @@ * ); * }

            * - * Often you might want to write just values without any keys to Kafka. Use {@code values()} to + *

            Often you might want to write just values without any keys to Kafka. Use {@code values()} to * write records with default empty(null) key: * *

            {@code
            @@ -578,7 +578,7 @@ private TypedRead(
                 }
             
                 /**
            -     * Creates an {@link UnboundedSource, ?>} with the configuration in {@link
            +     * Creates an {@link UnboundedSource} with the configuration in {@link
                  * TypedRead}. Primary use case is unit tests, should not be used in an application.
                  */
                 @VisibleForTesting
            @@ -751,7 +751,7 @@ public int compare(TopicPartition tp1, TopicPartition tp2) {
                 /**
                  * Returns one split for each of the Kafka partitions.
                  *
            -     * 

            It is important to sort the partitions deterministically so that we can support + *

            It is important to sort the partitions deterministically so that we can support * resuming a split from last checkpoint. The Kafka partitions are sorted by {@code }. */ From 2dd04b07b500bd6412f3a7461be65d3d5e921229 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Tue, 13 Dec 2016 09:07:14 -0800 Subject: [PATCH 639/751] Backport ValueProvider from [BEAM-551] (#492) * Create ValueProvider.java * Create ValueProviderUtils.java * Create ValueProviderTest.java * Create ValueProviderUtilsTest.java * More fixes * Fix space * Add DisplayData support for ValueProvider * Add more PRs * Fix checkstyle * Fix diff * Fix diff * Fixups --- .../dataflow/sdk/options/PipelineOptions.java | 32 +- .../sdk/options/PipelineOptionsFactory.java | 109 +++--- .../sdk/options/ProxyInvocationHandler.java | 125 +++++-- .../dataflow/sdk/options/ValueProvider.java | 319 ++++++++++++++++++ .../sdk/options/ValueProviderUtils.java | 58 ++++ .../sdk/transforms/display/DisplayData.java | 22 ++ .../cloud/dataflow/sdk/util/ApiSurface.java | 5 +- .../options/PipelineOptionsFactoryTest.java | 110 +++++- .../sdk/options/PipelineOptionsTest.java | 24 +- .../options/ProxyInvocationHandlerTest.java | 16 +- .../sdk/options/ValueProviderTest.java | 292 ++++++++++++++++ .../sdk/options/ValueProviderUtilsTest.java | 77 +++++ .../transforms/display/DisplayDataTest.java | 87 +++++ 13 files changed, 1189 insertions(+), 87 deletions(-) create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java create mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java index 701fe47976..e88be766ce 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java @@ -33,8 +33,9 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.lang.reflect.Proxy; +import java.util.Map; import java.util.ServiceLoader; - +import java.util.concurrent.atomic.AtomicLong; import javax.annotation.concurrent.ThreadSafe; /** @@ -261,4 +262,33 @@ enum CheckEnabled { @Description("A pipeline level default location for storing temporary files.") String getTempLocation(); void setTempLocation(String value); + + /** + * Returns a map of properties which correspond to {@link RuntimeValueProvider}, + * keyed by the property name. The value is a map containing type and default + * information. + */ + Map> outputRuntimeOptions(); + + /** + * Provides a unique ID for this {@link PipelineOptions} object, assigned at graph + * construction time. + */ + @Hidden + @Default.InstanceFactory(AtomicLongFactory.class) + Long getOptionsId(); + void setOptionsId(Long id); + + /** + * {@link DefaultValueFactory} which supplies an ID that is guaranteed to be unique + * within the given process. + */ + class AtomicLongFactory implements DefaultValueFactory { + private static final AtomicLong NEXT_ID = new AtomicLong(0); + + @Override + public Long create(PipelineOptions options) { + return NEXT_ID.getAndIncrement(); + } + } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java index cca4cc7f6f..160e27af23 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java @@ -30,8 +30,8 @@ import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; +import com.google.common.base.Predicates; import com.google.common.base.Strings; -import com.google.common.collect.Collections2; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; @@ -64,7 +64,9 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -894,21 +896,18 @@ public static DataflowWorkerHarnessOptions createFromSystemProperties() throws I * resolved. */ private static List getPropertyDescriptors( - Class beanClass) - throws IntrospectionException { - // The sorting is important to make this method stable. - SortedSet methods = Sets.newTreeSet(MethodComparator.INSTANCE); - methods.addAll( - Collections2.filter(Arrays.asList(beanClass.getMethods()), NOT_SYNTHETIC_PREDICATE)); + Set methods, Class beanClass) + throws IntrospectionException { SortedMap propertyNamesToGetters = new TreeMap<>(); for (Map.Entry entry : - PipelineOptionsReflector.getPropertyNamesToGetters(methods).entries()) { + PipelineOptionsReflector.getPropertyNamesToGetters(methods).entries()) { propertyNamesToGetters.put(entry.getKey(), entry.getValue()); } List descriptors = Lists.newArrayList(); List mismatches = new ArrayList<>(); + Set usedDescriptors = Sets.newHashSet(); /* * Add all the getter/setter pairs to the list of descriptors removing the getter once * it has been paired up. @@ -925,9 +924,9 @@ private static List getPropertyDescriptors( // Validate that the getter and setter property types are the same. if (getterMethod != null) { - Class getterPropertyType = getterMethod.getReturnType(); - Class setterPropertyType = method.getParameterTypes()[0]; - if (getterPropertyType != setterPropertyType) { + Type getterPropertyType = getterMethod.getGenericReturnType(); + Type setterPropertyType = method.getGenericParameterTypes()[0]; + if (!getterPropertyType.equals(setterPropertyType)) { TypeMismatch mismatch = new TypeMismatch(); mismatch.propertyName = propertyName; mismatch.getterPropertyType = getterPropertyType; @@ -936,9 +935,14 @@ private static List getPropertyDescriptors( continue; } } - - descriptors.add(new PropertyDescriptor( - propertyName, getterMethod, method)); + // Properties can appear multiple times with subclasses, and we don't + // want to add a bad entry if we have already added a good one (with both + // getter and setter). + if (!usedDescriptors.contains(propertyName)) { + descriptors.add(new PropertyDescriptor( + propertyName, getterMethod, method)); + usedDescriptors.add(propertyName); + } } throwForTypeMismatches(mismatches); @@ -952,8 +956,8 @@ private static List getPropertyDescriptors( private static class TypeMismatch { private String propertyName; - private Class getterPropertyType; - private Class setterPropertyType; + private Type getterPropertyType; + private Type setterPropertyType; } private static void throwForTypeMismatches(List mismatches) { @@ -963,8 +967,8 @@ private static void throwForTypeMismatches(List mismatches) { "Type mismatch between getter and setter methods for property [%s]. " + "Getter is of type [%s] whereas setter is of type [%s].", mismatch.propertyName, - mismatch.getterPropertyType.getName(), - mismatch.setterPropertyType.getName())); + mismatch.getterPropertyType, + mismatch.setterPropertyType)); } else if (mismatches.size() > 1) { StringBuilder builder = new StringBuilder( String.format("Type mismatches between getters and setters detected:")); @@ -972,8 +976,8 @@ private static void throwForTypeMismatches(List mismatches) { builder.append(String.format( "%n - Property [%s]: Getter is of type [%s] whereas setter is of type [%s].", mismatch.propertyName, - mismatch.getterPropertyType.getName(), - mismatch.setterPropertyType.getName())); + mismatch.getterPropertyType.toString(), + mismatch.setterPropertyType.toString())); } throw new IllegalArgumentException(builder.toString()); } @@ -1028,14 +1032,13 @@ private static List validateClass(Class validateClass(Class allInterfaceMethods = + SortedSet allInterfaceMethods = FluentIterable.from( ReflectHelpers.getClosureOfMethodsOnInterfaces( validatedPipelineOptionsInterfaces)) @@ -1081,7 +1084,7 @@ private static List validateClass(Class descriptors = getPropertyDescriptors(klass); + List descriptors = getPropertyDescriptors(allInterfaceMethods, iface); List incompletelyIgnoredGetters = new ArrayList<>(); List ignoredSetters = new ArrayList<>(); @@ -1155,13 +1158,25 @@ private static List validateClass(Class knownMethods = Sets.newHashSet(); + for (Method method : methods) { + knownMethods.add(method.getName()); + } // Verify that no additional methods are on an interface that aren't a bean property. + // Because methods can have multiple declarations, we do a name-based comparison + // here to prevent false positives. SortedSet unknownMethods = new TreeSet<>(MethodComparator.INSTANCE); unknownMethods.addAll( Sets.filter( - Sets.difference(Sets.newHashSet(klass.getMethods()), methods), - NOT_SYNTHETIC_PREDICATE)); + Sets.difference(Sets.newHashSet(iface.getMethods()), methods), + Predicates.and(NOT_SYNTHETIC_PREDICATE, + new Predicate() { + @Override + public boolean apply(Method input) { + return !knownMethods.contains(input.getName()); + } + }))); checkArgument(unknownMethods.isEmpty(), "Methods %s on [%s] do not conform to being bean properties.", FluentIterable.from(unknownMethods).transform(ReflectHelpers.METHOD_FORMATTER), @@ -1455,7 +1470,7 @@ public boolean apply(@Nullable String input) { } Method method = propertyNamesToGetters.get(entry.getKey()); - // Only allow empty argument values for String, String Array, and Collection. + // Only allow empty argument values for String, String Array, and Collection. Class returnType = method.getReturnType(); JavaType type = MAPPER.getTypeFactory().constructType(method.getGenericReturnType()); if ("runner".equals(entry.getKey())) { @@ -1481,8 +1496,12 @@ public boolean apply(@Nullable String input) { } } } else if ((returnType.isArray() && (SIMPLE_TYPES.contains(returnType.getComponentType()) - || returnType.getComponentType().isEnum())) - || Collection.class.isAssignableFrom(returnType)) { + || returnType.getComponentType().isEnum())) + || Collection.class.isAssignableFrom(returnType) + || (returnType.equals(ValueProvider.class) + && MAPPER.getTypeFactory().constructType( + ((ParameterizedType) method.getGenericReturnType()) + .getActualTypeArguments()[0]).isCollectionLikeType())) { // Split any strings with "," List values = FluentIterable.from(entry.getValue()) .transformAndConcat(new Function>() { @@ -1492,25 +1511,31 @@ public Iterable apply(String input) { } }).toList(); - if (returnType.isArray() && !returnType.getComponentType().equals(String.class)) { + if (returnType.isArray() && !returnType.getComponentType().equals(String.class) + || Collection.class.isAssignableFrom(returnType) + || returnType.equals(ValueProvider.class)) { for (String value : values) { checkArgument(!value.isEmpty(), - "Empty argument value is only allowed for String, String Array, and Collection," - + " but received: " + returnType); + "Empty argument value is only allowed for String, String Array, " + + "and Collections of Strings, but received: %s", + method.getGenericReturnType()); } } convertedOptions.put(entry.getKey(), MAPPER.convertValue(values, type)); - } else if (SIMPLE_TYPES.contains(returnType) || returnType.isEnum()) { + } else if (SIMPLE_TYPES.contains(returnType) || returnType.isEnum() + || returnType.equals(ValueProvider.class)) { String value = Iterables.getOnlyElement(entry.getValue()); checkArgument(returnType.equals(String.class) || !value.isEmpty(), - "Empty argument value is only allowed for String, String Array, and Collection," - + " but received: " + returnType); + "Empty argument value is only allowed for String, String Array, " + + "and Collections of Strings, but received: %s", + method.getGenericReturnType()); convertedOptions.put(entry.getKey(), MAPPER.convertValue(value, type)); } else { String value = Iterables.getOnlyElement(entry.getValue()); checkArgument(returnType.equals(String.class) || !value.isEmpty(), - "Empty argument value is only allowed for String, String Array, and Collection," - + " but received: " + returnType); + "Empty argument value is only allowed for String, String Array, " + + "and Collections of Strings, but received: %s", + method.getGenericReturnType()); try { convertedOptions.put(entry.getKey(), MAPPER.readValue(value, type)); } catch (IOException e) { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java index 5070a52569..7a36b3d249 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java @@ -21,6 +21,8 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.JsonIgnorePredicate; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.Registration; +import com.google.cloud.dataflow.sdk.options.ValueProvider.RuntimeValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; import com.google.cloud.dataflow.sdk.util.InstanceBuilder; @@ -55,6 +57,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.Arrays; @@ -131,6 +134,8 @@ public Object invoke(Object proxy, Method method, Object[] args) { return equals(args[0]); } else if (args == null && "hashCode".equals(method.getName())) { return hashCode(); + } else if (args == null && "outputRuntimeOptions".equals(method.getName())) { + return outputRuntimeOptions((PipelineOptions) proxy); } else if (args != null && "as".equals(method.getName()) && args[0] instanceof Class) { @SuppressWarnings("unchecked") Class clazz = (Class) args[0]; @@ -241,7 +246,7 @@ public boolean equals(Object obj) { */ synchronized T as(Class iface) { checkNotNull(iface); - checkArgument(iface.isInterface()); + checkArgument(iface.isInterface(), "Not an interface: %s", iface); if (!interfaceToProxyCache.containsKey(iface)) { Registration registration = PipelineOptionsFactory.validateWellFormed(iface, knownInterfaces); @@ -301,6 +306,29 @@ public int hashCode() { return hashCode; } + /** + * Returns a map of properties which correspond to {@link RuntimeValueProvider}. + */ + public Map> outputRuntimeOptions(PipelineOptions options) { + Set optionSpecs = PipelineOptionsReflector.getOptionSpecs(knownInterfaces); + Map> properties = Maps.newHashMap(); + + for (PipelineOptionSpec spec : optionSpecs) { + if (spec.getGetterMethod().getReturnType().equals(ValueProvider.class)) { + Object vp = invoke(options, spec.getGetterMethod(), null); + if (((ValueProvider) vp).isAccessible()) { + continue; + } + Map property = Maps.newHashMap(); + property.put("type", + ((ParameterizedType) spec.getGetterMethod() + .getGenericReturnType()).getActualTypeArguments()[0]); + properties.put(spec.getName(), property); + } + } + return properties; + } + /** * Populate display data. See {@link HasDisplayData#populateDisplayData}. All explicitly set * pipeline options will be added as display data. @@ -507,36 +535,37 @@ private Object getValueFromJson(String propertyName, Method method) { */ @SuppressWarnings({"unchecked", "rawtypes"}) private Object getDefault(PipelineOptions proxy, Method method) { + if (method.getReturnType().equals(RuntimeValueProvider.class)) { + throw new RuntimeException(String.format( + "Method %s should not have return type " + + "RuntimeValueProvider, use ValueProvider instead.", method.getName())); + } + if (method.getReturnType().equals(StaticValueProvider.class)) { + throw new RuntimeException(String.format( + "Method %s should not have return type " + + "StaticValueProvider, use ValueProvider instead.", method.getName())); + } + @Nullable Object defaultObject = null; for (Annotation annotation : method.getAnnotations()) { - if (annotation instanceof Default.Class) { - return ((Default.Class) annotation).value(); - } else if (annotation instanceof Default.String) { - return ((Default.String) annotation).value(); - } else if (annotation instanceof Default.Boolean) { - return ((Default.Boolean) annotation).value(); - } else if (annotation instanceof Default.Character) { - return ((Default.Character) annotation).value(); - } else if (annotation instanceof Default.Byte) { - return ((Default.Byte) annotation).value(); - } else if (annotation instanceof Default.Short) { - return ((Default.Short) annotation).value(); - } else if (annotation instanceof Default.Integer) { - return ((Default.Integer) annotation).value(); - } else if (annotation instanceof Default.Long) { - return ((Default.Long) annotation).value(); - } else if (annotation instanceof Default.Float) { - return ((Default.Float) annotation).value(); - } else if (annotation instanceof Default.Double) { - return ((Default.Double) annotation).value(); - } else if (annotation instanceof Default.Enum) { - return Enum.valueOf((Class) method.getReturnType(), - ((Default.Enum) annotation).value()); - } else if (annotation instanceof Default.InstanceFactory) { - return InstanceBuilder.ofType(((Default.InstanceFactory) annotation).value()) - .build() - .create(proxy); + defaultObject = returnDefaultHelper(annotation, proxy, method); + if (defaultObject != null) { + break; } } + if (method.getReturnType().equals(ValueProvider.class)) { + String propertyName = gettersToPropertyNames.get(method.getName()); + return defaultObject == null + ? new RuntimeValueProvider( + method.getName(), propertyName, + (Class) method.getDeclaringClass(), + proxy.getOptionsId()) + : new RuntimeValueProvider( + method.getName(), propertyName, + (Class) method.getDeclaringClass(), + defaultObject, proxy.getOptionsId()); + } else if (defaultObject != null) { + return defaultObject; + } /* * We need to make sure that we return something appropriate for the return type. Thus we return @@ -545,6 +574,43 @@ private Object getDefault(PipelineOptions proxy, Method method) { return Defaults.defaultValue(method.getReturnType()); } + /** + * Helper method to return standard Default cases. + */ + @Nullable + private Object returnDefaultHelper( + Annotation annotation, PipelineOptions proxy, Method method) { + if (annotation instanceof Default.Class) { + return ((Default.Class) annotation).value(); + } else if (annotation instanceof Default.String) { + return ((Default.String) annotation).value(); + } else if (annotation instanceof Default.Boolean) { + return ((Default.Boolean) annotation).value(); + } else if (annotation instanceof Default.Character) { + return ((Default.Character) annotation).value(); + } else if (annotation instanceof Default.Byte) { + return ((Default.Byte) annotation).value(); + } else if (annotation instanceof Default.Short) { + return ((Default.Short) annotation).value(); + } else if (annotation instanceof Default.Integer) { + return ((Default.Integer) annotation).value(); + } else if (annotation instanceof Default.Long) { + return ((Default.Long) annotation).value(); + } else if (annotation instanceof Default.Float) { + return ((Default.Float) annotation).value(); + } else if (annotation instanceof Default.Double) { + return ((Default.Double) annotation).value(); + } else if (annotation instanceof Default.Enum) { + return Enum.valueOf((Class) method.getReturnType(), + ((Default.Enum) annotation).value()); + } else if (annotation instanceof Default.InstanceFactory) { + return InstanceBuilder.ofType(((Default.InstanceFactory) annotation).value()) + .build() + .create(proxy); + } + return null; + } + /** * Returns a map from the getters method name to the name of the property based upon the passed in * {@link PropertyDescriptor}s property descriptors. @@ -695,7 +761,8 @@ public PipelineOptions deserialize(JsonParser jp, DeserializationContext ctxt) } PipelineOptions options = new ProxyInvocationHandler(Maps.newHashMap(), fields) - .as(PipelineOptions.class); + .as(PipelineOptions.class); + ValueProvider.RuntimeValueProvider.setRuntimeOptions(options); return options; } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java new file mode 100644 index 0000000000..24a6a0666b --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java @@ -0,0 +1,319 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.common.base.MoreObjects; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; + +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Nullable; + +/** + * {@link ValueProvider} is an interface which abstracts the notion of + * fetching a value that may or may not be currently available. This can be + * used to parameterize transforms that only read values in at runtime, for + * example. + */ +@JsonSerialize(using = ValueProvider.Serializer.class) +@JsonDeserialize(using = ValueProvider.Deserializer.class) +public interface ValueProvider extends Serializable { + /** + * Return the value wrapped by this {@link ValueProvider}. + */ + T get(); + + /** + * Whether the contents of this {@link ValueProvider} is available to + * routines that run at graph construction time. + */ + boolean isAccessible(); + + /** + * {@link StaticValueProvider} is an implementation of {@link ValueProvider} that + * allows for a static value to be provided. + */ + class StaticValueProvider implements ValueProvider, Serializable { + @Nullable + private final T value; + + StaticValueProvider(@Nullable T value) { + this.value = value; + } + + /** + * Creates a {@link StaticValueProvider} that wraps the provided value. + */ + public static StaticValueProvider of(T value) { + StaticValueProvider factory = new StaticValueProvider<>(value); + return factory; + } + + @Override + public T get() { + return value; + } + + @Override + public boolean isAccessible() { + return true; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("value", value) + .toString(); + } + } + + /** + * {@link NestedValueProvider} is an implementation of {@link ValueProvider} that + * allows for wrapping another {@link ValueProvider} object. + */ + class NestedValueProvider implements ValueProvider, Serializable { + + private final ValueProvider value; + private final SerializableFunction translator; + + NestedValueProvider(ValueProvider value, SerializableFunction translator) { + this.value = checkNotNull(value); + this.translator = checkNotNull(translator); + } + + /** + * Creates a {@link NestedValueProvider} that wraps the provided value. + */ + public static NestedValueProvider of( + ValueProvider value, SerializableFunction translator) { + NestedValueProvider factory = new NestedValueProvider(value, translator); + return factory; + } + + @Override + public T get() { + return translator.apply(value.get()); + } + + @Override + public boolean isAccessible() { + return value.isAccessible(); + } + + /** + * Return the property name associated with this provider. + */ + public String propertyName() { + if (value instanceof RuntimeValueProvider) { + return ((RuntimeValueProvider) value).propertyName(); + } else if (value instanceof NestedValueProvider) { + return ((NestedValueProvider) value).propertyName(); + } else { + throw new RuntimeException("Only a RuntimeValueProvider or a NestedValueProvider can supply" + + " a property name."); + } + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("value", value) + .toString(); + } + } + + /** + * {@link RuntimeValueProvider} is an implementation of {@link ValueProvider} that + * allows for a value to be provided at execution time rather than at graph + * construction time. + * + *

            To enforce this contract, if there is no default, users must only call + * {@link #get()} at execution time (after a call to + * {@link com.google.cloud.dataflow.sdk.Pipeline#run}), + * which will provide the value of {@code optionsMap}. + */ + class RuntimeValueProvider implements ValueProvider, Serializable { + private static ConcurrentHashMap optionsMap = + new ConcurrentHashMap<>(); + + private final Class klass; + private final String methodName; + private final String propertyName; + @Nullable + private final T defaultValue; + private final Long optionsId; + + /** + * Creates a {@link RuntimeValueProvider} that will query the provided + * {@code optionsId} for a value. + */ + RuntimeValueProvider(String methodName, String propertyName, + Class klass, Long optionsId) { + this.methodName = methodName; + this.propertyName = propertyName; + this.klass = klass; + this.defaultValue = null; + this.optionsId = optionsId; + } + + /** + * Creates a {@link RuntimeValueProvider} that will query the provided + * {@code optionsId} for a value, or use the default if no value is available. + */ + RuntimeValueProvider(String methodName, String propertyName, + Class klass, + T defaultValue, Long optionsId) { + this.methodName = methodName; + this.propertyName = propertyName; + this.klass = klass; + this.defaultValue = defaultValue; + this.optionsId = optionsId; + } + + /** + * Once set, all {@code RuntimeValueProviders} will return {@code true} + * from {@code isAccessible()}. By default, the value is set when + * deserializing {@link PipelineOptions}. + */ + static void setRuntimeOptions(PipelineOptions runtimeOptions) { + optionsMap.put(runtimeOptions.getOptionsId(), runtimeOptions); + } + + @Override + public T get() { + PipelineOptions options = optionsMap.get(optionsId); + if (options == null) { + throw new RuntimeException("Not called from a runtime context."); + } + try { + Method method = klass.getMethod(methodName); + PipelineOptions methodOptions = options.as(klass); + InvocationHandler handler = Proxy.getInvocationHandler(methodOptions); + ValueProvider result = + (ValueProvider) handler.invoke(methodOptions, method, null); + // Two cases: If we have deserialized a new value from JSON, it will + // be wrapped in a StaticValueProvider, which we can provide here. If + // not, there was no JSON value, and we return the default, whether or + // not it is null. + if (result instanceof StaticValueProvider) { + return result.get(); + } + return defaultValue; + } catch (Throwable e) { + throw new RuntimeException("Unable to load runtime value.", e); + } + } + + @Override + public boolean isAccessible() { + PipelineOptions options = optionsMap.get(optionsId); + return options != null; + } + + /** + * Returns the property name that corresponds to this provider. + */ + public String propertyName() { + return propertyName; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("propertyName", propertyName) + .add("default", defaultValue) + .add("value", isAccessible() ? get() : null) + .toString(); + } + } + + /** + * Serializer for {@link ValueProvider}. + */ + class Serializer extends JsonSerializer> { + @Override + public void serialize(ValueProvider value, JsonGenerator jgen, + SerializerProvider provider) throws IOException { + if (value.isAccessible()) { + jgen.writeObject(value.get()); + } else { + jgen.writeNull(); + } + } + } + + /** + * Deserializer for {@link ValueProvider}, which handles type marshalling. + */ + class Deserializer extends JsonDeserializer> + implements ContextualDeserializer { + + private final JavaType innerType; + + // A 0-arg constructor is required by the compiler. + Deserializer() { + this.innerType = null; + } + + Deserializer(JavaType innerType) { + this.innerType = innerType; + } + + @Override + public JsonDeserializer createContextual(DeserializationContext ctxt, + BeanProperty property) + throws JsonMappingException { + checkNotNull(ctxt, "Null DeserializationContext."); + JavaType type = checkNotNull(ctxt.getContextualType(), "Invalid type: %s", getClass()); + JavaType[] params = type.findTypeParameters(ValueProvider.class); + if (params.length != 1) { + throw new RuntimeException( + "Unable to derive type for ValueProvider: " + type.toString()); + } + JavaType param = params[0]; + return new Deserializer(param); + } + + @Override + public ValueProvider deserialize(JsonParser jp, DeserializationContext ctxt) + throws IOException, JsonProcessingException { + JsonDeserializer dser = ctxt.findRootValueDeserializer( + checkNotNull(innerType, "Invalid %s: innerType is null. Serialization error?", getClass())); + Object o = dser.deserialize(jp, ctxt); + return StaticValueProvider.of(o); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java new file mode 100644 index 0000000000..8b628e8484 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.io.IOException; +import java.util.Map; + +/** + * Utilities for working with the {@link ValueProvider} interface. + */ +public class ValueProviderUtils { + private ValueProviderUtils() {} + + /** + * Given {@code serializedOptions} as a JSON-serialized {@link PipelineOptions}, updates + * the values according to the provided values in {@code runtimeValues}. + */ + public static String updateSerializedOptions( + String serializedOptions, Map runtimeValues) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode root, options; + try { + root = mapper.readValue(serializedOptions, ObjectNode.class); + options = (ObjectNode) root.get("options"); + checkNotNull(options, "Unable to locate 'options' in %s", serializedOptions); + } catch (IOException e) { + throw new RuntimeException( + String.format("Unable to parse %s", serializedOptions), e); + } + + for (Map.Entry entry : runtimeValues.entrySet()) { + options.put(entry.getKey(), entry.getValue()); + } + try { + return mapper.writeValueAsString(root); + } catch (IOException e) { + throw new RuntimeException("Unable to parse re-serialize options", e); + } + } +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java index 0dadedf7ea..788ad7e205 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java @@ -19,6 +19,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import com.google.cloud.dataflow.sdk.options.ValueProvider; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; @@ -729,6 +730,27 @@ public static Item item(String key, @Nullable String value) { return item(key, Type.STRING, value); } + /** + * Create a display item for the specified key and {@link ValueProvider}. + */ + public static Item item(String key, ValueProvider value) { + if (value == null) { + return item(key, Type.STRING, null); + } + if (value.isAccessible()) { + Object got = value.get(); + if (got == null) { + return item(key, Type.STRING, null); + } + Type type = inferType(got); + if (type == null) { + throw new RuntimeException(String.format("Unknown value type: %s", got)); + } + return item(key, type, got); + } + return item(key, Type.STRING, value.toString()); + } + /** * Create a display item for the specified key and integer value. */ diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java index 23940f50d9..c711093f3b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java @@ -627,7 +627,10 @@ public static ApiSurface getSdkApiSurface() throws IOException { .pruningPrefix("org.joda.time") .pruningPrefix("org.apache.avro") .pruningPrefix("org.junit") - .pruningPrefix("com.fasterxml.jackson.annotation"); + .pruningPrefix("com.fasterxml.jackson.annotation") + .pruningPrefix("com.fasterxml.jackson.core") + .pruningPrefix("com.fasterxml.jackson.databind") + .pruningPrefix("com.fasterxml.jackson.deser"); } public static void main(String[] args) throws Exception { diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java index ce8cb93b3f..7b1cfc6217 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java @@ -236,7 +236,7 @@ public void testMultiGetterSetterTypeMismatchThrows() { expectedException.expectMessage("Property [value]: Getter is of type " + "[boolean] whereas setter is of type [int]."); expectedException.expectMessage("Property [other]: Getter is of type [long] " - + "whereas setter is of type [java.lang.String]."); + + "whereas setter is of type [class java.lang.String]."); PipelineOptionsFactory.as(MultiGetterSetterTypeMismatch.class); } @@ -520,7 +520,8 @@ public void testEmptyValueNotAllowed() { "--byte="}; expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collection"); + "Empty argument value is only allowed for String, String Array, and Collections" + + " of Strings"); PipelineOptionsFactory.fromArgs(args).as(Primitives.class); } @@ -728,7 +729,8 @@ public void testEmptyInStringArraysWithCommaList() { public void testEmptyInNonStringArrays() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collection"); + "Empty argument value is only allowed for String, String Array, and Collections" + + " of Strings"); String[] args = new String[] { "--boolean=true", @@ -742,7 +744,8 @@ public void testEmptyInNonStringArrays() { public void testEmptyInNonStringArraysWithCommaList() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collection"); + "Empty argument value is only allowed for String, String Array, and Collections" + + " of Strings"); String[] args = new String[] { "--int=1,,9"}; @@ -769,16 +772,57 @@ public void testOutOfOrderArrays() { public interface Lists extends PipelineOptions { List getString(); void setString(List value); + List getInteger(); + void setInteger(List value); + List getList(); + void setList(List value); } @Test - public void testList() { - String[] args = + public void testListRawDefaultsToString() { + String[] manyArgs = + new String[] {"--list=stringValue1", "--list=stringValue2", "--list=stringValue3"}; + + Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); + assertEquals(ImmutableList.of("stringValue1", "stringValue2", "stringValue3"), + options.getList()); + } + + @Test + public void testListString() { + String[] manyArgs = new String[] {"--string=stringValue1", "--string=stringValue2", "--string=stringValue3"}; + String[] oneArg = new String[] {"--string=stringValue1"}; - Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); + Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); assertEquals(ImmutableList.of("stringValue1", "stringValue2", "stringValue3"), options.getString()); + + options = PipelineOptionsFactory.fromArgs(oneArg).as(Lists.class); + assertEquals(ImmutableList.of("stringValue1"), options.getString()); + } + + @Test + public void testListInt() { + String[] manyArgs = + new String[] {"--integer=1", "--integer=2", "--integer=3"}; + String[] manyArgsShort = + new String[] {"--integer=1,2,3"}; + String[] oneArg = new String[] {"--integer=1"}; + String[] missingArg = new String[] {"--integer="}; + + Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); + assertEquals(ImmutableList.of(1, 2, 3), options.getInteger()); + options = PipelineOptionsFactory.fromArgs(manyArgsShort).as(Lists.class); + assertEquals(ImmutableList.of(1, 2, 3), options.getInteger()); + options = PipelineOptionsFactory.fromArgs(oneArg).as(Lists.class); + assertEquals(ImmutableList.of(1), options.getInteger()); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage( + "Empty argument value is only allowed for String, String Array, and Collections of Strings," + + " but received: java.util.List"); + options = PipelineOptionsFactory.fromArgs(missingArg).as(Lists.class); } @Test @@ -826,6 +870,58 @@ public void testSetASingularAttributeUsingAListIsIgnoredWithoutStrictParsing() { expectedLogs.verifyWarn("Strict parsing is disabled, ignoring option"); } + /** A test interface containing all supported List return types. */ + public interface Maps extends PipelineOptions { + Map getMap(); + void setMap(Map value); + + Map> getNestedMap(); + void setNestedMap(Map> value); + } + + @Test + public void testMapIntInt() { + String[] manyArgsShort = + new String[] {"--map={\"1\":1,\"2\":2}"}; + String[] oneArg = new String[] {"--map={\"1\":1}"}; + String[] missingArg = new String[] {"--map="}; + + Maps options = PipelineOptionsFactory.fromArgs(manyArgsShort).as(Maps.class); + assertEquals(ImmutableMap.of(1, 1, 2, 2), options.getMap()); + options = PipelineOptionsFactory.fromArgs(oneArg).as(Maps.class); + assertEquals(ImmutableMap.of(1, 1), options.getMap()); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage( + "Empty argument value is only allowed for String, String Array, and " + + "Collections of Strings, but received: java.util.Map"); + options = PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); + } + + @Test + public void testNestedMap() { + String[] manyArgsShort = + new String[] {"--nestedMap={\"1\":{\"1\":1},\"2\":{\"2\":2}}"}; + String[] oneArg = new String[] {"--nestedMap={\"1\":{\"1\":1}}"}; + String[] missingArg = new String[] {"--nestedMap="}; + + Maps options = PipelineOptionsFactory.fromArgs(manyArgsShort).as(Maps.class); + assertEquals(ImmutableMap.of(1, ImmutableMap.of(1, 1), + 2, ImmutableMap.of(2, 2)), + options.getNestedMap()); + options = PipelineOptionsFactory.fromArgs(oneArg).as(Maps.class); + assertEquals(ImmutableMap.of(1, ImmutableMap.of(1, 1)), + options.getNestedMap()); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage( + "Empty argument value is only allowed for String, String Array, and Collections of " + + "Strings, but received: java.util.Map>"); + options = PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); + } + @Test public void testSettingRunner() { String[] args = new String[] {"--runner=BlockingDataflowPipelineRunner"}; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java index 5293e83bab..f430687ee3 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java @@ -24,6 +24,7 @@ import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @@ -38,6 +39,7 @@ import java.io.IOException; import java.util.List; +import java.util.Map; import java.util.Set; /** Unit tests for {@link PipelineOptions}. */ @@ -122,5 +124,25 @@ public void testCloneAsConflicted() throws Exception { expectedException.expectMessage("incompatible return types"); options.cloneAs(ConflictedTestOptions.class); } -} + private interface ValueProviderOptions extends PipelineOptions { + ValueProvider getBool(); + void setBool(ValueProvider value); + + ValueProvider getString(); + void setString(ValueProvider value); + + String getNotAValueProvider(); + void setNotAValueProvider(String value); + } + + @Test + public void testOutputRuntimeOptions() { + ValueProviderOptions options = + PipelineOptionsFactory.fromArgs( + new String[]{"--string=baz"}).as(ValueProviderOptions.class); + Map expected = ImmutableMap.of( + "bool", ImmutableMap.of("type", Boolean.class)); + assertEquals(expected, options.outputRuntimeOptions()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java index 30a8346731..50183184f7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java @@ -245,12 +245,14 @@ public void testToString() throws Exception { public void testToStringAfterDeserializationContainsJsonEntries() throws Exception { ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); Simple proxy = handler.as(Simple.class); + Long optionsId = proxy.getOptionsId(); proxy.setString("stringValue"); DefaultAnnotations proxy2 = proxy.as(DefaultAnnotations.class); proxy2.setLong(57L); - assertEquals("Current Settings:\n" - + " long: 57\n" - + " string: \"stringValue\"\n", + assertEquals(String.format("Current Settings:\n" + + " long: 57\n" + + " optionsId: %d\n" + + " string: \"stringValue\"\n", optionsId), serializeDeserialize(PipelineOptions.class, proxy2).toString()); } @@ -258,14 +260,16 @@ public void testToStringAfterDeserializationContainsJsonEntries() throws Excepti public void testToStringAfterDeserializationContainsOverriddenEntries() throws Exception { ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); Simple proxy = handler.as(Simple.class); + Long optionsId = proxy.getOptionsId(); proxy.setString("stringValue"); DefaultAnnotations proxy2 = proxy.as(DefaultAnnotations.class); proxy2.setLong(57L); Simple deserializedOptions = serializeDeserialize(Simple.class, proxy2); deserializedOptions.setString("overriddenValue"); - assertEquals("Current Settings:\n" - + " long: 57\n" - + " string: overriddenValue\n", + assertEquals(String.format("Current Settings:\n" + + " long: 57\n" + + " optionsId: %d\n" + + " string: overriddenValue\n", optionsId), deserializedOptions.toString()); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java new file mode 100644 index 0000000000..2f593ede1f --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java @@ -0,0 +1,292 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.RuntimeValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; +import com.google.cloud.dataflow.sdk.util.SerializableUtils; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.List; + +/** Tests for {@link ValueProvider}. */ +@RunWith(JUnit4.class) +public class ValueProviderTest { + @Rule public ExpectedException expectedException = ExpectedException.none(); + + /** A test interface. */ + public interface TestOptions extends PipelineOptions { + @Default.String("bar") + ValueProvider getBar(); + void setBar(ValueProvider bar); + + ValueProvider getFoo(); + void setFoo(ValueProvider foo); + + ValueProvider> getList(); + void setList(ValueProvider> list); + } + + @Test + public void testCommandLineNoDefault() { + TestOptions options = PipelineOptionsFactory.fromArgs( + new String[]{"--foo=baz"}).as(TestOptions.class); + ValueProvider provider = options.getFoo(); + assertEquals("baz", provider.get()); + assertTrue(provider.isAccessible()); + } + + @Test + public void testListValueProvider() { + TestOptions options = PipelineOptionsFactory.fromArgs( + new String[]{"--list=1,2,3"}).as(TestOptions.class); + ValueProvider> provider = options.getList(); + assertEquals(ImmutableList.of(1, 2, 3), provider.get()); + assertTrue(provider.isAccessible()); + } + + @Test + public void testCommandLineWithDefault() { + TestOptions options = PipelineOptionsFactory.fromArgs( + new String[]{"--bar=baz"}).as(TestOptions.class); + ValueProvider provider = options.getBar(); + assertEquals("baz", provider.get()); + assertTrue(provider.isAccessible()); + } + + @Test + public void testStaticValueProvider() { + ValueProvider provider = StaticValueProvider.of("foo"); + assertEquals("foo", provider.get()); + assertTrue(provider.isAccessible()); + assertEquals("StaticValueProvider{value=foo}", provider.toString()); + } + + @Test + public void testNoDefaultRuntimeProvider() { + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + ValueProvider provider = options.getFoo(); + assertFalse(provider.isAccessible()); + + expectedException.expect(RuntimeException.class); + expectedException.expectMessage("Not called from a runtime context"); + provider.get(); + } + + @Test + public void testRuntimePropertyName() { + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + ValueProvider provider = options.getFoo(); + assertEquals("foo", ((RuntimeValueProvider) provider).propertyName()); + assertEquals( + "RuntimeValueProvider{propertyName=foo, default=null, value=null}", + provider.toString()); + } + + @Test + public void testDefaultRuntimeProvider() { + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + ValueProvider provider = options.getBar(); + assertFalse(provider.isAccessible()); + } + + @Test + public void testNoDefaultRuntimeProviderWithOverride() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + TestOptions runtime = mapper.readValue( + "{ \"options\": { \"foo\": \"quux\" }}", PipelineOptions.class) + .as(TestOptions.class); + + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + runtime.setOptionsId(options.getOptionsId()); + RuntimeValueProvider.setRuntimeOptions(runtime); + + ValueProvider provider = options.getFoo(); + assertTrue(provider.isAccessible()); + assertEquals("quux", provider.get()); + } + + @Test + public void testDefaultRuntimeProviderWithOverride() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + TestOptions runtime = mapper.readValue( + "{ \"options\": { \"bar\": \"quux\" }}", PipelineOptions.class) + .as(TestOptions.class); + + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + runtime.setOptionsId(options.getOptionsId()); + RuntimeValueProvider.setRuntimeOptions(runtime); + + ValueProvider provider = options.getBar(); + assertTrue(provider.isAccessible()); + assertEquals("quux", provider.get()); + } + + @Test + public void testDefaultRuntimeProviderWithoutOverride() throws Exception { + TestOptions runtime = PipelineOptionsFactory.as(TestOptions.class); + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + runtime.setOptionsId(options.getOptionsId()); + RuntimeValueProvider.setRuntimeOptions(runtime); + + ValueProvider provider = options.getBar(); + assertTrue(provider.isAccessible()); + assertEquals("bar", provider.get()); + } + + /** A test interface. */ + public interface BadOptionsRuntime extends PipelineOptions { + RuntimeValueProvider getBar(); + void setBar(RuntimeValueProvider bar); + } + + @Test + public void testOptionReturnTypeRuntime() { + BadOptionsRuntime options = PipelineOptionsFactory.as(BadOptionsRuntime.class); + expectedException.expect(RuntimeException.class); + expectedException.expectMessage( + "Method getBar should not have return type " + + "RuntimeValueProvider, use ValueProvider instead."); + RuntimeValueProvider provider = options.getBar(); + } + + /** A test interface. */ + public interface BadOptionsStatic extends PipelineOptions { + StaticValueProvider getBar(); + void setBar(StaticValueProvider bar); + } + + @Test + public void testOptionReturnTypeStatic() { + BadOptionsStatic options = PipelineOptionsFactory.as(BadOptionsStatic.class); + expectedException.expect(RuntimeException.class); + expectedException.expectMessage( + "Method getBar should not have return type " + + "StaticValueProvider, use ValueProvider instead."); + StaticValueProvider provider = options.getBar(); + } + + @Test + public void testSerializeDeserializeNoArg() throws Exception { + TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); + assertFalse(submitOptions.getFoo().isAccessible()); + ObjectMapper mapper = new ObjectMapper(); + String serializedOptions = mapper.writeValueAsString(submitOptions); + + String runnerString = ValueProviderUtils.updateSerializedOptions( + serializedOptions, ImmutableMap.of("foo", "quux")); + TestOptions runtime = mapper.readValue(runnerString, PipelineOptions.class) + .as(TestOptions.class); + + ValueProvider vp = runtime.getFoo(); + assertTrue(vp.isAccessible()); + assertEquals("quux", vp.get()); + assertEquals(vp.getClass(), StaticValueProvider.class); + } + + @Test + public void testSerializeDeserializeWithArg() throws Exception { + TestOptions submitOptions = PipelineOptionsFactory.fromArgs( + new String[]{"--foo=baz"}).as(TestOptions.class); + assertEquals("baz", submitOptions.getFoo().get()); + assertTrue(submitOptions.getFoo().isAccessible()); + ObjectMapper mapper = new ObjectMapper(); + String serializedOptions = mapper.writeValueAsString(submitOptions); + + String runnerString = ValueProviderUtils.updateSerializedOptions( + serializedOptions, ImmutableMap.of("foo", "quux")); + TestOptions runtime = mapper.readValue(runnerString, PipelineOptions.class) + .as(TestOptions.class); + + ValueProvider vp = runtime.getFoo(); + assertTrue(vp.isAccessible()); + assertEquals("quux", vp.get()); + } + + @Test + public void testNestedValueProviderStatic() throws Exception { + ValueProvider svp = StaticValueProvider.of("foo"); + ValueProvider nvp = NestedValueProvider.of( + svp, new SerializableFunction() { + @Override + public String apply(String from) { + return from + "bar"; + } + }); + assertTrue(nvp.isAccessible()); + assertEquals("foobar", nvp.get()); + assertEquals( + "NestedValueProvider{value=StaticValueProvider{value=foo}}", + nvp.toString()); + } + + @Test + public void testNestedValueProviderRuntime() throws Exception { + TestOptions options = PipelineOptionsFactory.as(TestOptions.class); + ValueProvider rvp = options.getBar(); + ValueProvider nvp = NestedValueProvider.of( + rvp, new SerializableFunction() { + @Override + public String apply(String from) { + return from + "bar"; + } + }); + ValueProvider doubleNvp = NestedValueProvider.of( + nvp, new SerializableFunction() { + @Override + public String apply(String from) { + return from; + } + }); + assertEquals("bar", ((NestedValueProvider) nvp).propertyName()); + assertEquals("bar", ((NestedValueProvider) doubleNvp).propertyName()); + assertFalse(nvp.isAccessible()); + expectedException.expect(RuntimeException.class); + expectedException.expectMessage("Not called from a runtime context"); + nvp.get(); + } + + private static class NonSerializable {} + + private static class NonSerializableTranslator + implements SerializableFunction { + @Override + public NonSerializable apply(String from) { + return new NonSerializable(); + } + } + + @Test + public void testNestedValueProviderSerialize() throws Exception { + ValueProvider nvp = NestedValueProvider.of( + StaticValueProvider.of("foo"), new NonSerializableTranslator()); + SerializableUtils.ensureSerializable(nvp); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java new file mode 100644 index 0000000000..6c92649b28 --- /dev/null +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2016 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk.options; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.google.common.collect.ImmutableMap; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link ValueProviderUtils}. */ +@RunWith(JUnit4.class) +public class ValueProviderUtilsTest { + /** A test interface. */ + public interface TestOptions extends PipelineOptions { + String getString(); + void setString(String value); + + String getOtherString(); + void setOtherString(String value); + } + + @Test + public void testUpdateSerialize() throws Exception { + TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); + ObjectMapper mapper = new ObjectMapper(); + String serializedOptions = mapper.writeValueAsString(submitOptions); + String updatedOptions = ValueProviderUtils.updateSerializedOptions( + serializedOptions, ImmutableMap.of("string", "bar")); + TestOptions runtime = mapper.readValue(updatedOptions, PipelineOptions.class) + .as(TestOptions.class); + assertEquals("bar", runtime.getString()); + } + + @Test + public void testUpdateSerializeExistingValue() throws Exception { + TestOptions submitOptions = PipelineOptionsFactory.fromArgs( + new String[]{"--string=baz", "--otherString=quux"}).as(TestOptions.class); + ObjectMapper mapper = new ObjectMapper(); + String serializedOptions = mapper.writeValueAsString(submitOptions); + String updatedOptions = ValueProviderUtils.updateSerializedOptions( + serializedOptions, ImmutableMap.of("string", "bar")); + TestOptions runtime = mapper.readValue(updatedOptions, PipelineOptions.class) + .as(TestOptions.class); + assertEquals("bar", runtime.getString()); + assertEquals("quux", runtime.getOtherString()); + } + + @Test + public void testUpdateSerializeEmptyUpdate() throws Exception { + TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); + ObjectMapper mapper = new ObjectMapper(); + String serializedOptions = mapper.writeValueAsString(submitOptions); + String updatedOptions = ValueProviderUtils.updateSerializedOptions( + serializedOptions, ImmutableMap.of()); + TestOptions runtime = mapper.readValue(updatedOptions, PipelineOptions.class) + .as(TestOptions.class); + assertNull(runtime.getString()); + } +} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java index 039e33da3d..d1601996a1 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java @@ -39,6 +39,8 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; @@ -159,6 +161,89 @@ public void populateDisplayData(DisplayData.Builder builder) { assertThat(data, hasDisplayItem("foo", "bar")); } + @Test + public void testStaticValueProviderDate() { + final Instant value = Instant.now(); + DisplayData data = + DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item( + "foo", StaticValueProvider.of(value))); + } + }); + @SuppressWarnings("unchecked") + DisplayData.Item item = (DisplayData.Item) data.items().toArray()[0]; + + @SuppressWarnings("unchecked") + Matcher> matchesAllOf = Matchers.allOf( + hasKey("foo"), + hasType(DisplayData.Type.TIMESTAMP), + hasValue(ISO_FORMATTER.print(value))); + + assertThat(item, matchesAllOf); + } + + @Test + public void testStaticValueProviderString() { + DisplayData data = + DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item( + "foo", StaticValueProvider.of("bar"))); + } + }); + + assertThat(data.items(), hasSize(1)); + assertThat(data, hasDisplayItem("foo", "bar")); + } + + @Test + public void testStaticValueProviderInt() { + DisplayData data = + DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item( + "foo", StaticValueProvider.of(1))); + } + }); + + assertThat(data.items(), hasSize(1)); + assertThat(data, hasDisplayItem("foo", 1)); + } + + @Test + public void testInaccessibleValueProvider() { + DisplayData data = + DisplayData.from(new HasDisplayData() { + @Override + public void populateDisplayData(DisplayData.Builder builder) { + builder.add(DisplayData.item( + "foo", new ValueProvider() { + @Override + public boolean isAccessible() { + return false; + } + + @Override + public String get() { + return "bar"; + } + + @Override + public String toString() { + return "toString"; + } + })); + } + }); + + assertThat(data.items(), hasSize(1)); + assertThat(data, hasDisplayItem("foo", "toString")); + } + @Test public void testAsMap() { DisplayData data = @@ -288,6 +373,8 @@ public void testAddIfNotNull() { public void populateDisplayData(Builder builder) { builder .addIfNotNull(DisplayData.item("nullString", (String) null)) + .addIfNotNull(DisplayData.item("nullVPString", (ValueProvider) null)) + .addIfNotNull(DisplayData.item("nullierVPString", StaticValueProvider.of(null))) .addIfNotNull(DisplayData.item("notNullString", "foo")) .addIfNotNull(DisplayData.item("nullLong", (Long) null)) .addIfNotNull(DisplayData.item("notNullLong", 1234L)) From c737a68d6b2445c4f25f23975e6e0f6f722a109c Mon Sep 17 00:00:00 2001 From: sammcveety Date: Tue, 13 Dec 2016 12:34:55 -0800 Subject: [PATCH 640/751] Backport TextIO ValueProvider changes [BEAM-551] (#499) * Initial backport * Initial backport * Initial backport * Fixups * Fixups --- .../dataflow/sdk/io/CompressedSource.java | 2 +- .../cloud/dataflow/sdk/io/FileBasedSink.java | 46 ++++++++++--- .../dataflow/sdk/io/FileBasedSource.java | 61 ++++++++++++----- .../google/cloud/dataflow/sdk/io/TextIO.java | 65 +++++++++++++++---- .../google/cloud/dataflow/sdk/io/XmlSink.java | 4 +- .../sdk/runners/DataflowPipelineRunner.java | 7 +- .../sdk/runners/dataflow/ReadTranslator.java | 12 ++-- .../cloud/dataflow/sdk/io/TextIOTest.java | 19 ++++++ .../cloud/dataflow/sdk/io/XmlSinkTest.java | 10 +-- .../runners/DataflowPipelineRunnerTest.java | 20 ++++++ .../DataflowPipelineTranslatorTest.java | 29 +++++++++ 11 files changed, 223 insertions(+), 52 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java index f0651022b7..2f2d82e823 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java @@ -236,7 +236,7 @@ public CompressedSource withDecompression(DecompressingChannelFactory channel */ private CompressedSource( FileBasedSource sourceDelegate, DecompressingChannelFactory channelFactory) { - super(sourceDelegate.getFileOrPatternSpec(), Long.MAX_VALUE); + super(sourceDelegate.getFileOrPatternSpecProvider(), Long.MAX_VALUE); this.sourceDelegate = sourceDelegate; this.channelFactory = channelFactory; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java index 87102e1bac..428d843dae 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java @@ -22,6 +22,8 @@ import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.SerializableCoder; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.FileIOChannelFactory; import com.google.cloud.dataflow.sdk.util.GcsIOChannelFactory; @@ -71,7 +73,7 @@ public abstract class FileBasedSink extends Sink { /** * Base filename for final output files. */ - protected final String baseOutputFilename; + protected final ValueProvider baseOutputFilename; /** * The extension to be used for the final output files. @@ -88,7 +90,7 @@ public abstract class FileBasedSink extends Sink { * Construct a FileBasedSink with the given base output filename and extension. */ public FileBasedSink(String baseOutputFilename, String extension) { - this(baseOutputFilename, extension, ShardNameTemplate.INDEX_OF_MAX); + this(StaticValueProvider.of(baseOutputFilename), extension, ShardNameTemplate.INDEX_OF_MAX); } /** @@ -98,6 +100,17 @@ public FileBasedSink(String baseOutputFilename, String extension) { *

            See {@link ShardNameTemplate} for a description of file naming templates. */ public FileBasedSink(String baseOutputFilename, String extension, String fileNamingTemplate) { + this(StaticValueProvider.of(baseOutputFilename), extension, fileNamingTemplate); + } + + /** + * Construct a FileBasedSink with the given base output filename, extension, and file naming + * template. + * + *

            See {@link ShardNameTemplate} for a description of file naming templates. + */ + public FileBasedSink(ValueProvider baseOutputFilename, + String extension, String fileNamingTemplate) { this.baseOutputFilename = baseOutputFilename; this.extension = extension; this.fileNamingTemplate = fileNamingTemplate; @@ -107,6 +120,13 @@ public FileBasedSink(String baseOutputFilename, String extension, String fileNam * Returns the base output filename for this file based sink. */ public String getBaseOutputFilename() { + return baseOutputFilename.get(); + } + + /** + * Returns the base output filename for this file based sink. + */ + public ValueProvider getBaseOutputFilenameProvider() { return baseOutputFilename; } @@ -130,7 +150,9 @@ public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); String fileNamePattern = String.format("%s%s%s", - baseOutputFilename, fileNamingTemplate, getFileExtension(extension)); + baseOutputFilename.isAccessible() + ? baseOutputFilename.get() : baseOutputFilename.toString(), + fileNamingTemplate, getFileExtension(extension)); builder.add(DisplayData.item("fileNamePattern", fileNamePattern) .withLabel("File Name Pattern")); } @@ -220,7 +242,7 @@ public enum TemporaryFileRetention { /** * Base filename used for temporary output files. Default is the baseOutputFilename. */ - protected final String baseTemporaryFilename; + protected final ValueProvider baseTemporaryFilename; /** * Name separator for temporary files. Temporary files will be named @@ -243,7 +265,7 @@ protected static final String buildTemporaryFilename(String prefix, String suffi * @param sink the FileBasedSink that will be used to configure this write operation. */ public FileBasedWriteOperation(FileBasedSink sink) { - this(sink, sink.baseOutputFilename); + this(sink, sink.getBaseOutputFilenameProvider(), TemporaryFileRetention.REMOVE); } /** @@ -253,7 +275,7 @@ public FileBasedWriteOperation(FileBasedSink sink) { * @param baseTemporaryFilename the base filename to be used for temporary output files. */ public FileBasedWriteOperation(FileBasedSink sink, String baseTemporaryFilename) { - this(sink, baseTemporaryFilename, TemporaryFileRetention.REMOVE); + this(sink, StaticValueProvider.of(baseTemporaryFilename), TemporaryFileRetention.REMOVE); } /** @@ -265,6 +287,12 @@ public FileBasedWriteOperation(FileBasedSink sink, String baseTemporaryFilena */ public FileBasedWriteOperation(FileBasedSink sink, String baseTemporaryFilename, TemporaryFileRetention temporaryFileRetention) { + this(sink, StaticValueProvider.of(baseTemporaryFilename), temporaryFileRetention); + } + + private FileBasedWriteOperation(FileBasedSink sink, + ValueProvider baseTemporaryFilename, + TemporaryFileRetention temporaryFileRetention) { this.sink = sink; this.baseTemporaryFilename = baseTemporaryFilename; this.temporaryFileRetention = temporaryFileRetention; @@ -360,7 +388,7 @@ protected final List copyToOutputFiles(List filenames, PipelineO protected final List generateDestinationFilenames(int numFiles) { List destFilenames = new ArrayList<>(); String extension = getSink().extension; - String baseOutputFilename = getSink().baseOutputFilename; + String baseOutputFilename = getSink().baseOutputFilename.get(); String fileNamingTemplate = getSink().fileNamingTemplate; String suffix = getFileExtension(extension); @@ -395,7 +423,7 @@ protected final void removeTemporaryFiles(PipelineOptions options) throws IOExce */ protected final void removeTemporaryFiles( Collection knownFiles, PipelineOptions options) throws IOException { - String pattern = buildTemporaryFilename(baseTemporaryFilename, "*"); + String pattern = buildTemporaryFilename(baseTemporaryFilename.get(), "*"); LOG.debug("Finding temporary bundle output files matching {}.", pattern); FileOperations fileOperations = FileOperationsFactory.getFileOperations(pattern, options); IOChannelFactory factory = IOChannelUtils.getFactory(pattern); @@ -508,7 +536,7 @@ protected void writeFooter() throws Exception {} public final void open(String uId) throws Exception { this.id = uId; filename = FileBasedWriteOperation.buildTemporaryFilename( - getWriteOperation().baseTemporaryFilename, uId); + getWriteOperation().baseTemporaryFilename.get(), uId); LOG.debug("Opening {}.", filename); channel = IOChannelUtils.create(filename, mimeType); try { diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java index 5e47eeaa62..ea67a9e22c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java @@ -18,6 +18,8 @@ import static com.google.common.base.Preconditions.checkState; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.util.IOChannelFactory; import com.google.cloud.dataflow.sdk.util.IOChannelUtils; @@ -73,7 +75,7 @@ public abstract class FileBasedSource extends OffsetBasedSource { // Package-private for testing. static final int THREAD_POOL_SIZE = 128; - private final String fileOrPatternSpec; + private final ValueProvider fileOrPatternSpec; private final Mode mode; /** @@ -95,6 +97,16 @@ public enum Mode { * @param minBundleSize minimum bundle size in bytes. */ public FileBasedSource(String fileOrPatternSpec, long minBundleSize) { + this(StaticValueProvider.of(fileOrPatternSpec), minBundleSize); + } + + + /** + * Create a {@code FileBaseSource} based on a file or a file pattern specification. + * Same as the {@code String} constructor, but accepting a {@link ValueProvider} + * to allow for runtime configuration of the source. + */ + public FileBasedSource(ValueProvider fileOrPatternSpec, long minBundleSize) { super(0, Long.MAX_VALUE, minBundleSize); mode = Mode.FILEPATTERN; this.fileOrPatternSpec = fileOrPatternSpec; @@ -120,10 +132,14 @@ public FileBasedSource(String fileName, long minBundleSize, long startOffset, long endOffset) { super(startOffset, endOffset, minBundleSize); mode = Mode.SINGLE_FILE_OR_SUBRANGE; - this.fileOrPatternSpec = fileName; + this.fileOrPatternSpec = StaticValueProvider.of(fileName); } public final String getFileOrPatternSpec() { + return fileOrPatternSpec.get(); + } + + public final ValueProvider getFileOrPatternSpecProvider() { return fileOrPatternSpec; } @@ -142,7 +158,9 @@ public final FileBasedSource createSourceForSubrange(long start, long end) { + " of the subrange cannot be larger than the end offset value " + getEndOffset() + " of the parent source"); - FileBasedSource source = createForSubrangeOfFile(fileOrPatternSpec, start, end); + checkState(fileOrPatternSpec.isAccessible(), + "Subrange creation should only happen at execution time."); + FileBasedSource source = createForSubrangeOfFile(fileOrPatternSpec.get(), start, end); if (start > 0 || end != Long.MAX_VALUE) { checkArgument(source.getMode() == Mode.SINGLE_FILE_OR_SUBRANGE, "Source created for the range [" + start + "," + end + ")" @@ -180,19 +198,21 @@ public final long getEstimatedSizeBytes(PipelineOptions options) throws Exceptio // we perform the size estimation of files and file patterns using the interface provided by // IOChannelFactory. - IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec); if (mode == Mode.FILEPATTERN) { + checkState(fileOrPatternSpec.isAccessible(), + "Size estimation should be done at execution time."); + IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec.get()); // TODO Implement a more efficient parallel/batch size estimation mechanism for file patterns. long startTime = System.currentTimeMillis(); long totalSize = 0; - Collection inputs = factory.match(fileOrPatternSpec); + Collection inputs = factory.match(fileOrPatternSpec.get()); if (inputs.size() <= MAX_NUMBER_OF_FILES_FOR_AN_EXACT_STAT) { totalSize = getExactTotalSizeOfFiles(inputs, factory); - LOG.debug("Size estimation of all files of pattern " + fileOrPatternSpec + " took " + LOG.debug("Size estimation of all files of pattern " + fileOrPatternSpec.get() + " took " + (System.currentTimeMillis() - startTime) + " ms"); } else { totalSize = getEstimatedSizeOfFilesBySampling(inputs, factory); - LOG.debug("Size estimation of pattern " + fileOrPatternSpec + " by sampling took " + LOG.debug("Size estimation of pattern " + fileOrPatternSpec.get() + " by sampling took " + (System.currentTimeMillis() - startTime) + " ms"); } return totalSize; @@ -261,7 +281,7 @@ private static long getEstimatedSizeOfFilesBySampling( @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); - builder.add(DisplayData.item("filePattern", getFileOrPatternSpec()) + builder.add(DisplayData.item("filePattern", getFileOrPatternSpecProvider()) .withLabel("File Pattern")); } @@ -294,7 +314,9 @@ public final List> splitIntoBundles( ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(THREAD_POOL_SIZE)); try { - for (final String file : FileBasedSource.expandFilePattern(fileOrPatternSpec)) { + checkState(fileOrPatternSpec.isAccessible(), + "Bundle splitting should only happen at execution time."); + for (final String file : FileBasedSource.expandFilePattern(fileOrPatternSpec.get())) { futures.add(createFutureForFileSplit(file, desiredBundleSizeBytes, options, service)); } List> splitResults = @@ -334,8 +356,10 @@ protected boolean isSplittable() throws Exception { // We split a file-based source into subranges only if the file is efficiently seekable. // If a file is not efficiently seekable it would be highly inefficient to create and read a // source based on a subrange of that file. - IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec); - return factory.isReadSeekEfficient(fileOrPatternSpec); + checkState(fileOrPatternSpec.isAccessible(), + "isSplittable should only be called at runtime."); + IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec.get()); + return factory.isReadSeekEfficient(fileOrPatternSpec.get()); } @Override @@ -345,7 +369,7 @@ public final BoundedReader createReader(PipelineOptions options) throws IOExc if (mode == Mode.FILEPATTERN) { long startTime = System.currentTimeMillis(); - Collection files = FileBasedSource.expandFilePattern(fileOrPatternSpec); + Collection files = FileBasedSource.expandFilePattern(fileOrPatternSpec.get()); List> fileReaders = new ArrayList<>(); for (String fileName : files) { long endOffset; @@ -373,9 +397,9 @@ public final BoundedReader createReader(PipelineOptions options) throws IOExc public String toString() { switch (mode) { case FILEPATTERN: - return fileOrPatternSpec; + return fileOrPatternSpec.toString(); case SINGLE_FILE_OR_SUBRANGE: - return fileOrPatternSpec + " range " + super.toString(); + return fileOrPatternSpec.toString() + " range " + super.toString(); default: throw new IllegalStateException("Unexpected mode: " + mode); } @@ -407,8 +431,8 @@ public final long getMaxEndOffset(PipelineOptions options) throws Exception { throw new IllegalArgumentException("Cannot determine the exact end offset of a file pattern"); } if (getEndOffset() == Long.MAX_VALUE) { - IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec); - return factory.getSizeBytes(fileOrPatternSpec); + IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec.get()); + return factory.getSizeBytes(fileOrPatternSpec.get()); } else { return getEndOffset(); } @@ -480,8 +504,9 @@ public synchronized FileBasedSource getCurrentSource() { @Override protected final boolean startImpl() throws IOException { FileBasedSource source = getCurrentSource(); - IOChannelFactory factory = IOChannelUtils.getFactory(source.getFileOrPatternSpec()); - this.channel = factory.open(source.getFileOrPatternSpec()); + IOChannelFactory factory = IOChannelUtils.getFactory( + source.getFileOrPatternSpecProvider().get()); + this.channel = factory.open(source.getFileOrPatternSpecProvider().get()); if (channel instanceof SeekableByteChannel) { SeekableByteChannel seekChannel = (SeekableByteChannel) channel; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java index 40a71132c1..216c07fdcd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java @@ -17,6 +17,7 @@ package com.google.cloud.dataflow.sdk.io; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.cloud.dataflow.sdk.coders.Coder; @@ -25,6 +26,8 @@ import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.io.Read.Bounded; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.transforms.PTransform; @@ -148,6 +151,13 @@ public static Bound from(String filepattern) { return new Bound<>(DEFAULT_TEXT_CODER).from(filepattern); } + /** + * Same as {@code from(filepattern)}, but accepting a {@link ValueProvider}. + */ + public static Bound from(ValueProvider filepattern) { + return new Bound<>(DEFAULT_TEXT_CODER).from(filepattern); + } + /** * Returns a transform for reading text files that uses the given * {@code Coder} to decode each of the lines of the file into a @@ -201,7 +211,7 @@ public static Bound withCompressionType(TextIO.CompressionType compressi */ public static class Bound extends PTransform> { /** The filepattern to read from. */ - @Nullable private final String filepattern; + @Nullable private final ValueProvider filepattern; /** The Coder to use to decode each line. */ private final Coder coder; @@ -216,8 +226,8 @@ public static class Bound extends PTransform> { this(null, null, coder, true, TextIO.CompressionType.AUTO); } - private Bound(String name, String filepattern, Coder coder, boolean validate, - TextIO.CompressionType compressionType) { + private Bound(@Nullable String name, @Nullable ValueProvider filepattern, + Coder coder, boolean validate, TextIO.CompressionType compressionType) { super(name); this.coder = coder; this.filepattern = filepattern; @@ -244,6 +254,16 @@ public Bound named(String name) { */ public Bound from(String filepattern) { + checkNotNull(filepattern, "Filepattern cannot be empty."); + return new Bound<>(name, StaticValueProvider.of(filepattern), coder, validate, + compressionType); + } + + /** + * Same as {@code from(filepattern)}, but accepting a {@link ValueProvider}. + */ + public Bound from(ValueProvider filepattern) { + checkNotNull(filepattern, "Filepattern cannot be empty."); return new Bound<>(name, filepattern, coder, validate, compressionType); } @@ -295,14 +315,16 @@ public PCollection apply(PInput input) { } if (validate) { + checkState(filepattern.isAccessible(), + "Cannot validate with a filepattern provided at runtime."); try { checkState( - !IOChannelUtils.getFactory(filepattern).match(filepattern).isEmpty(), + !IOChannelUtils.getFactory(filepattern.get()).match(filepattern.get()).isEmpty(), "Unable to find any files matching %s", filepattern); } catch (IOException e) { throw new IllegalStateException( - String.format("Failed to validate %s", filepattern), e); + String.format("Failed to validate %s", filepattern.get()), e); } } @@ -352,7 +374,7 @@ protected Coder getDefaultOutputCoder() { } public String getFilepattern() { - return filepattern; + return filepattern.get(); } public boolean needsValidation() { @@ -399,6 +421,13 @@ public static Bound to(String prefix) { return new Bound<>(DEFAULT_TEXT_CODER).to(prefix); } + /** + * Like {@link #to(String)}, but with a {@link ValueProvider}. + */ + public static Bound to(ValueProvider prefix) { + return new Bound<>(DEFAULT_TEXT_CODER).to(prefix); + } + /** * Returns a transform for writing to text files that appends the specified suffix * to the created files. @@ -502,7 +531,7 @@ public static class Bound extends PTransform, PDone> { private static final String DEFAULT_SHARD_TEMPLATE = ShardNameTemplate.INDEX_OF_MAX; /** The prefix of each file written, combined with suffix and shardTemplate. */ - @Nullable private final String filenamePrefix; + @Nullable private final ValueProvider filenamePrefix; /** The suffix of each file written, combined with prefix and shardTemplate. */ private final String filenameSuffix; @@ -528,7 +557,7 @@ public static class Bound extends PTransform, PDone> { this(null, null, "", null, null, coder, 0, DEFAULT_SHARD_TEMPLATE, true); } - private Bound(String name, String filenamePrefix, String filenameSuffix, + private Bound(String name, ValueProvider filenamePrefix, String filenameSuffix, @Nullable String header, @Nullable String footer, Coder coder, int numShards, String shardTemplate, boolean validate) { super(name); @@ -563,7 +592,15 @@ public Bound named(String name) { */ public Bound to(String filenamePrefix) { validateOutputComponent(filenamePrefix); - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, + return new Bound<>(name, StaticValueProvider.of(filenamePrefix), filenameSuffix, + header, footer, coder, numShards, shardTemplate, validate); + } + + /** + * Like {@link #to(String)}, but with a {@link ValueProvider}. + */ + public Bound to(ValueProvider filenamePrefix) { + return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, shardTemplate, validate); } @@ -742,7 +779,7 @@ protected Coder getDefaultOutputCoder() { } public String getFilenamePrefix() { - return filenamePrefix; + return filenamePrefix.get(); } public String getShardTemplate() { @@ -852,6 +889,12 @@ static class TextSource extends FileBasedSource { this.coder = coder; } + @VisibleForTesting + TextSource(ValueProvider fileSpec, Coder coder) { + super(fileSpec, 1L); + this.coder = coder; + } + private TextSource(String fileName, long start, long end, Coder coder) { super(fileName, 1L, start, end); this.coder = coder; @@ -1054,7 +1097,7 @@ static class TextSink extends FileBasedSink { @VisibleForTesting TextSink( - String baseOutputFilename, String extension, + ValueProvider baseOutputFilename, String extension, @Nullable String header, @Nullable String footer, String fileNameTemplate, Coder coder) { super(baseOutputFilename, extension, fileNameTemplate); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java index 104611ef94..720ef555b2 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java @@ -177,7 +177,7 @@ private Bound(Class classToBind, String rootElementName, String baseOutputFil *

            The specified class must be able to be used to create a JAXB context. */ public Bound ofRecordClass(Class classToBind) { - return new Bound<>(classToBind, rootElementName, baseOutputFilename); + return new Bound<>(classToBind, rootElementName, baseOutputFilename.get()); } /** @@ -195,7 +195,7 @@ public Bound toFilenamePrefix(String baseOutputFilename) { * supplied name. */ public Bound withRootElement(String rootElementName) { - return new Bound<>(classToBind, rootElementName, baseOutputFilename); + return new Bound<>(classToBind, rootElementName, baseOutputFilename.get()); } /** diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index 318d0abd20..c1a7b88414 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -2120,8 +2120,11 @@ public BatchWrite(DataflowPipelineRunner runner, Write.Bound transform) { public PDone apply(PCollection input) { if (transform.getSink() instanceof FileBasedSink) { FileBasedSink sink = (FileBasedSink) transform.getSink(); - PathValidator validator = runner.options.getPathValidator(); - validator.validateOutputFilePrefixSupported(sink.getBaseOutputFilename()); + if (sink.getBaseOutputFilenameProvider().isAccessible()) { + PathValidator validator = runner.options.getPathValidator(); + validator.validateOutputFilePrefixSupported( + sink.getBaseOutputFilenameProvider().get()); + } } return transform.apply(input); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java index f110e84adc..1111d786c3 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java @@ -24,6 +24,7 @@ import com.google.cloud.dataflow.sdk.io.FileBasedSource; import com.google.cloud.dataflow.sdk.io.Read; import com.google.cloud.dataflow.sdk.io.Source; +import com.google.cloud.dataflow.sdk.options.ValueProvider; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; @@ -50,10 +51,13 @@ public static void translateReadHelper(Source source, // TODO: Move this validation out of translation once IOChannelUtils is portable // and can be reconstructed on the worker. if (source instanceof FileBasedSource) { - String filePatternOrSpec = ((FileBasedSource) source).getFileOrPatternSpec(); - context.getPipelineOptions() - .getPathValidator() - .validateInputFilePatternSupported(filePatternOrSpec); + ValueProvider filePatternOrSpec = + ((FileBasedSource) source).getFileOrPatternSpecProvider(); + if (filePatternOrSpec.isAccessible()) { + context.getPipelineOptions() + .getPathValidator() + .validateInputFilePatternSupported(filePatternOrSpec.get()); + } } context.addStep(transform, "ParallelRead"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java index 1d65d1ce2d..063760681e 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java @@ -50,6 +50,7 @@ import com.google.cloud.dataflow.sdk.io.TextIO.TextSource; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.options.ValueProvider; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; @@ -622,6 +623,24 @@ public void testBadWildcardRecursive() throws Exception { pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); } + /** Options for testing. */ + public interface RuntimeTestOptions extends PipelineOptions { + ValueProvider getInput(); + void setInput(ValueProvider value); + + ValueProvider getOutput(); + void setOutput(ValueProvider value); + } + + @Test + public void testRuntimeOptionsNotCalledInApply() throws Exception { + Pipeline pipeline = TestPipeline.create(); + RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); + pipeline + .apply(TextIO.Read.from(options.getInput()).withoutValidation()) + .apply(TextIO.Write.to(options.getOutput()).withoutValidation()); + } + @Test public void testReadWithoutValidationFlag() throws Exception { TextIO.Read.Bound read = TextIO.Read.from("gs://bucket/foo*/baz"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java index 22c1b59f45..9cf1ad1245 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java @@ -93,7 +93,7 @@ public void testBuildXmlSink() { .withRootElement(testRootElement); assertEquals(testClass, sink.classToBind); assertEquals(testRootElement, sink.rootElementName); - assertEquals(testFilePrefix, sink.baseOutputFilename); + assertEquals(testFilePrefix, sink.baseOutputFilename.get()); } /** @@ -105,7 +105,7 @@ public void testBuildXmlSinkDirect() { XmlSink.writeOf(Bird.class, testRootElement, testFilePrefix); assertEquals(testClass, sink.classToBind); assertEquals(testRootElement, sink.rootElementName); - assertEquals(testFilePrefix, sink.baseOutputFilename); + assertEquals(testFilePrefix, sink.baseOutputFilename.get()); } /** @@ -142,10 +142,10 @@ public void testCreateWriteOperations() { XmlSink.writeOf(testClass, testRootElement, testFilePrefix); XmlWriteOperation writeOp = sink.createWriteOperation(options); assertEquals(testClass, writeOp.getSink().classToBind); - assertEquals(testFilePrefix, writeOp.getSink().baseOutputFilename); + assertEquals(testFilePrefix, writeOp.getSink().baseOutputFilename.get()); assertEquals(testRootElement, writeOp.getSink().rootElementName); assertEquals(XmlSink.XML_EXTENSION, writeOp.getSink().extension); - assertEquals(testFilePrefix, writeOp.baseTemporaryFilename); + assertEquals(testFilePrefix, writeOp.baseTemporaryFilename.get()); } /** @@ -158,7 +158,7 @@ public void testCreateWriter() throws Exception { XmlSink.writeOf(testClass, testRootElement, testFilePrefix) .createWriteOperation(options); XmlWriter writer = writeOp.createWriter(options); - assertEquals(testFilePrefix, writer.getWriteOperation().baseTemporaryFilename); + assertEquals(testFilePrefix, writer.getWriteOperation().baseTemporaryFilename.get()); assertEquals(testRootElement, writer.getWriteOperation().getSink().rootElementName); assertNotNull(writer.marshaller); } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java index 24cb9eca69..ffcc688165 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java @@ -55,6 +55,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.options.ValueProvider; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsList; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMap; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMultimap; @@ -249,6 +250,25 @@ public void testRun() throws IOException { assertValidJob(jobCaptor.getValue()); } + /** Options for testing. */ + public interface RuntimeTestOptions extends PipelineOptions { + ValueProvider getInput(); + void setInput(ValueProvider value); + + ValueProvider getOutput(); + void setOutput(ValueProvider value); + } + + @Test + public void testTextIOWithRuntimeParameters() throws IOException { + DataflowPipelineOptions dataflowOptions = buildPipelineOptions(); + RuntimeTestOptions options = dataflowOptions.as(RuntimeTestOptions.class); + Pipeline p = buildDataflowPipeline(dataflowOptions); + p + .apply(TextIO.Read.from(options.getInput()).withoutValidation()) + .apply(TextIO.Write.to(options.getOutput()).withoutValidation()); + } + @Test public void testRunReturnDifferentRequestId() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java index 0c4b1e37b2..78d905d160 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java @@ -51,6 +51,7 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.options.ValueProvider; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; import com.google.cloud.dataflow.sdk.transforms.Count; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -203,6 +204,34 @@ public void testSettingOfSdkPipelineOptions() throws IOException { assertThat(optionsMap, hasEntry("numberOfWorkerHarnessThreads", (Object) 0)); } + private static class TestValueProvider implements ValueProvider, Serializable { + @Override + public boolean isAccessible() { + return false; + } + + @Override + public String get() { + throw new RuntimeException("Should not be called."); + } + } + + @Test + public void testInaccessibleProvider() throws Exception { + DataflowPipelineOptions options = buildPipelineOptions(); + options.setRunner(DataflowPipelineRunner.class); + Pipeline pipeline = Pipeline.create(options); + DataflowPipelineTranslator t = DataflowPipelineTranslator.fromOptions(options); + + pipeline.apply(TextIO.Read.from(new TestValueProvider()).withoutValidation()); + + // Check that translation does not fail. + t.translate( + pipeline, + (DataflowPipelineRunner) pipeline.getRunner(), + Collections.emptyList()); + } + @Test public void testNetworkConfig() throws IOException { final String testNetwork = "test-network"; From 61709c6bfd0d7a515beb420db43eeb70f068fb13 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Tue, 13 Dec 2016 15:07:38 -0800 Subject: [PATCH 641/751] Templated jobs should use custom IO for BigQuery (#496) * Templated jobs should use custom IO for BigQuery * Fix assignment --- .../sdk/runners/TemplatingDataflowPipelineRunner.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java index d01507be92..f7c3274bd9 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java @@ -31,6 +31,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.TimeUnit; /** @@ -67,6 +69,13 @@ public boolean failOnJobFileWriteFailure() { public static TemplatingDataflowPipelineRunner fromOptions(PipelineOptions options) { DataflowPipelineDebugOptions dataflowOptions = PipelineOptionsValidator.validate(DataflowPipelineDebugOptions.class, options); + List experiments = dataflowOptions.getExperiments(); + if (experiments == null) { + experiments = new ArrayList<>(); + dataflowOptions.setExperiments(experiments); + } + experiments.add("enable_custom_bigquery_source"); + experiments.add("enable_custom_bigquery_sink"); DataflowPipelineRunner dataflowPipelineRunner = DataflowPipelineRunner.fromOptions(dataflowOptions); checkArgument(!Strings.isNullOrEmpty(dataflowOptions.getDataflowJobFile()), From f6b287fdee46e522aa4883c0436b43387ca0ed38 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Tue, 13 Dec 2016 15:56:51 -0800 Subject: [PATCH 642/751] Backport apache/incubator-beam#1238 (#500) * Backport https://github.com/apache/incubator-beam/pull/1238 * Fixups --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 207 ++++++++++++++---- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 40 ++-- 2 files changed, 185 insertions(+), 62 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 8c120c4439..a0ccb78564 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -48,6 +48,9 @@ import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.dataflow.sdk.options.GcpOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -333,6 +336,38 @@ public static String toTableSpec(TableReference ref) { return sb.toString(); } + private static class JsonTableRefToTableRef + implements SerializableFunction { + @Override + public TableReference apply(String from) { + return fromJsonString(from, TableReference.class); + } + } + + private static class TableRefToJson + implements SerializableFunction { + @Override + public String apply(TableReference from) { + return toJsonString(from); + } + } + + private static class TableRefToProjectId + implements SerializableFunction { + @Override + public String apply(TableReference from) { + return from.getProjectId(); + } + } + + private static class TableSpecToTableRef + implements SerializableFunction { + @Override + public TableReference apply(String from) { + return parseTableSpec(from); + } + } + /** * A {@link PTransform} that reads from a BigQuery table and returns a * {@link PCollection} of {@link TableRow TableRows} containing each of the rows of the table. @@ -367,6 +402,13 @@ public static Bound named(String name) { * {@code "[dataset_id].[table_id]"} for tables within the current project. */ public static Bound from(String tableSpec) { + return new Bound().from(StaticValueProvider.of(tableSpec)); + } + + /** + * Same as {@code from(String)}, but with a {@link ValueProvider}. + */ + public static Bound from(ValueProvider tableSpec) { return new Bound().from(tableSpec); } @@ -374,6 +416,13 @@ public static Bound from(String tableSpec) { * Reads results received after executing the given query. */ public static Bound fromQuery(String query) { + return new Bound().fromQuery(StaticValueProvider.of(query)); + } + + /** + * Same as {@code from(String)}, but with a {@link ValueProvider}. + */ + public static Bound fromQuery(ValueProvider query) { return new Bound().fromQuery(query); } @@ -396,8 +445,8 @@ public static Bound withoutValidation() { * {@link PCollection} of {@link TableRow TableRows}. */ public static class Bound extends PTransform> { - @Nullable final String jsonTableRef; - @Nullable final String query; + @Nullable final ValueProvider jsonTableRef; + @Nullable final ValueProvider query; final boolean validate; @Nullable final Boolean flattenResults; @Nullable final Boolean useLegacySql; @@ -419,7 +468,8 @@ private Bound() { } private Bound( - String name, @Nullable String query, @Nullable String jsonTableRef, boolean validate, + String name, @Nullable ValueProvider query, + @Nullable ValueProvider jsonTableRef, boolean validate, @Nullable Boolean flattenResults, @Nullable Boolean useLegacySql, @Nullable BigQueryServices bigQueryServices) { super(name); @@ -449,7 +499,23 @@ public Bound named(String name) { *

            Does not modify this object. */ public Bound from(String tableSpec) { - return from(parseTableSpec(tableSpec)); + return from(StaticValueProvider.of(tableSpec)); + } + + /** + * Returns a copy of this transform that reads from the specified table. Refer to + * {@link #parseTableSpec(String)} for the specification format. + * + *

            Does not modify this object. + */ + public Bound from(ValueProvider tableSpec) { + return new Bound( + name, query, + NestedValueProvider.of( + NestedValueProvider.of( + tableSpec, new TableSpecToTableRef()), + new TableRefToJson()), + validate, flattenResults, useLegacySql, bigQueryServices); } /** @@ -458,9 +524,7 @@ public Bound from(String tableSpec) { *

            Does not modify this object. */ public Bound from(TableReference table) { - return new Bound( - name, query, toJsonString(table), validate, flattenResults, useLegacySql, - bigQueryServices); + return from(StaticValueProvider.of(toTableSpec(table))); } /** @@ -477,6 +541,13 @@ name, query, toJsonString(table), validate, flattenResults, useLegacySql, * Standard SQL dialect, use {@link BigQueryIO.Read.Bound#usingStandardSql}. */ public Bound fromQuery(String query) { + return fromQuery(StaticValueProvider.of(query)); + } + + /** + * Like {@link #fromQuery(String)}, but from a {@link ValueProvider}. + */ + public Bound fromQuery(ValueProvider query) { return new Bound(name, query, jsonTableRef, validate, MoreObjects.firstNonNull(flattenResults, Boolean.TRUE), MoreObjects.firstNonNull(useLegacySql, Boolean.TRUE), @@ -550,7 +621,7 @@ public void validate(PInput input) { } } - TableReference table = getTableWithDefaultProject(bqOptions); + ValueProvider table = getTableWithDefaultProject(bqOptions); checkState( table == null || query == null, @@ -569,14 +640,15 @@ public void validate(PInput input) { "Invalid BigQueryIO.Read: Specifies a table with a SQL dialect" + " preference, which only applies to queries"); + checkState(table.isAccessible(), "Cannot call validate if table is dynamically set."); // Check for source table presence for early failure notification. - - verifyDatasetPresence(bqOptions, table); - verifyTablePresence(bqOptions, table); + verifyDatasetPresence(bqOptions, table.get()); + verifyTablePresence(bqOptions, table.get()); } else /* query != null */ { + checkState(query.isAccessible(), "Cannot call validate if query is dynamically set."); checkState(flattenResults != null, "flattenResults should not be null if query is set"); checkState(useLegacySql != null, "useLegacySql should not be null if query is set"); - dryRunQuery(bqOptions, query, useLegacySql); + dryRunQuery(bqOptions, query.get(), useLegacySql); } } @@ -619,7 +691,7 @@ public PCollection apply(PInput input) { } final String executingProject = bqOptions.getProject(); - if (!Strings.isNullOrEmpty(query)) { + if (query != null && (!query.isAccessible() || !Strings.isNullOrEmpty(query.get()))) { String queryTempDatasetId = "temp_dataset_" + uuid; String queryTempTableId = "temp_table_" + uuid; @@ -629,12 +701,15 @@ public PCollection apply(PInput input) { .setTableId(queryTempTableId); source = BigQueryQuerySource.create( - jobIdToken, query, queryTempTableRef, flattenResults, useLegacySql, - extractDestinationDir, bqServices); + jobIdToken, query, NestedValueProvider.of( + StaticValueProvider.of( + toJsonString(queryTempTableRef)), new JsonTableRefToTableRef()), + flattenResults, useLegacySql, extractDestinationDir, bqServices); } else { - TableReference inputTable = getTableWithDefaultProject(bqOptions); + ValueProvider inputTable = getTableWithDefaultProject(bqOptions); source = BigQueryTableSource.create( - jobIdToken, inputTable, extractDestinationDir, bqServices, executingProject); + jobIdToken, inputTable, extractDestinationDir, bqServices, + StaticValueProvider.of(executingProject)); } PassThroughThenCleanup.CleanupOperation cleanupOperation = new PassThroughThenCleanup.CleanupOperation() { @@ -701,28 +776,59 @@ public void populateDisplayData(DisplayData.Builder builder) { * *

            If the table's project is not specified, use the executing project. */ - @Nullable private TableReference getTableWithDefaultProject(BigQueryOptions bqOptions) { - TableReference table = getTable(); - if (table != null && Strings.isNullOrEmpty(table.getProjectId())) { + @Nullable private ValueProvider getTableWithDefaultProject( + BigQueryOptions bqOptions) { + ValueProvider table = getTableProvider(); + if (table == null) { + return table; + } + if (!table.isAccessible()) { + LOG.info("Using a dynamic value for table input. This must contain a project" + + " in the table reference: {}", table); + return table; + } + if (Strings.isNullOrEmpty(table.get().getProjectId())) { // If user does not specify a project we assume the table to be located in // the default project. - table.setProjectId(bqOptions.getProject()); + TableReference ref = table.get(); + ref.setProjectId(bqOptions.getProject()); + return NestedValueProvider.of(StaticValueProvider.of( + toJsonString(ref)), new JsonTableRefToTableRef()); } return table; } + /** + * Returns the table to read, or {@code null} if reading from a query instead. + */ + @Nullable + public ValueProvider getTableProvider() { + return jsonTableRef == null + ? null : NestedValueProvider.of(jsonTableRef, new JsonTableRefToTableRef()); + } + /** * Returns the table to read, or {@code null} if reading from a query instead. */ @Nullable public TableReference getTable() { - return fromJsonString(jsonTableRef, TableReference.class); + ValueProvider provider = getTableProvider(); + return provider == null ? null : provider.get(); } /** * Returns the query to be read, or {@code null} if reading from a table instead. */ + @Nullable public String getQuery() { + return query == null ? null : query.get(); + } + + /** + * Returns the query to be read, or {@code null} if reading from a table instead. + */ + @Nullable + public ValueProvider getQueryProvider() { return query; } @@ -819,44 +925,46 @@ static class BigQueryTableSource extends BigQuerySourceBase { static BigQueryTableSource create( String jobIdToken, - TableReference table, + ValueProvider table, String extractDestinationDir, BigQueryServices bqServices, - String executingProject) { + ValueProvider executingProject) { return new BigQueryTableSource( jobIdToken, table, extractDestinationDir, bqServices, executingProject); } - private final String jsonTable; + private final ValueProvider jsonTable; private final AtomicReference tableSizeBytes; private BigQueryTableSource( String jobIdToken, - TableReference table, + ValueProvider table, String extractDestinationDir, BigQueryServices bqServices, - String executingProject) { + ValueProvider executingProject) { super(jobIdToken, extractDestinationDir, bqServices, executingProject); - this.jsonTable = toJsonString(checkNotNull(table, "table")); + this.jsonTable = NestedValueProvider.of(checkNotNull(table, "table"), new TableRefToJson()); this.tableSizeBytes = new AtomicReference<>(); } @Override protected TableReference getTableToExtract(BigQueryOptions bqOptions) throws IOException { - return JSON_FACTORY.fromString(jsonTable, TableReference.class); + checkState(jsonTable.isAccessible()); + return JSON_FACTORY.fromString(jsonTable.get(), TableReference.class); } @Override public BoundedReader createReader(PipelineOptions options) throws IOException { BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - TableReference tableRef = JSON_FACTORY.fromString(jsonTable, TableReference.class); + checkState(jsonTable.isAccessible()); + TableReference tableRef = JSON_FACTORY.fromString(jsonTable.get(), TableReference.class); return new BigQueryReader(this, bqServices.getReaderFromTable(bqOptions, tableRef)); } @Override public synchronized long getEstimatedSizeBytes(PipelineOptions options) throws Exception { if (tableSizeBytes.get() == null) { - TableReference table = JSON_FACTORY.fromString(jsonTable, TableReference.class); + TableReference table = JSON_FACTORY.fromString(jsonTable.get(), TableReference.class); Long numBytes = bqServices.getDatasetService(options.as(BigQueryOptions.class)) .getTable(table.getProjectId(), table.getDatasetId(), table.getTableId()) @@ -886,8 +994,8 @@ static class BigQueryQuerySource extends BigQuerySourceBase { static BigQueryQuerySource create( String jobIdToken, - String query, - TableReference queryTempTableRef, + ValueProvider query, + ValueProvider queryTempTableRef, Boolean flattenResults, Boolean useLegacySql, String extractDestinationDir, @@ -902,24 +1010,26 @@ static BigQueryQuerySource create( bqServices); } - private final String query; - private final String jsonQueryTempTable; + private final ValueProvider query; + private final ValueProvider jsonQueryTempTable; private final Boolean flattenResults; private final Boolean useLegacySql; private transient AtomicReference dryRunJobStats; private BigQueryQuerySource( String jobIdToken, - String query, - TableReference queryTempTableRef, + ValueProvider query, + ValueProvider queryTempTableRef, Boolean flattenResults, Boolean useLegacySql, String extractDestinationDir, BigQueryServices bqServices) { super(jobIdToken, extractDestinationDir, bqServices, - checkNotNull(queryTempTableRef, "queryTempTableRef").getProjectId()); + NestedValueProvider.of( + checkNotNull(queryTempTableRef, "queryTempTableRef"), new TableRefToProjectId())); this.query = checkNotNull(query, "query"); - this.jsonQueryTempTable = toJsonString(queryTempTableRef); + this.jsonQueryTempTable = NestedValueProvider.of( + queryTempTableRef, new TableRefToJson()); this.flattenResults = checkNotNull(flattenResults, "flattenResults"); this.useLegacySql = checkNotNull(useLegacySql, "useLegacySql"); this.dryRunJobStats = new AtomicReference<>(); @@ -935,7 +1045,7 @@ public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { public BoundedReader createReader(PipelineOptions options) throws IOException { BigQueryOptions bqOptions = options.as(BigQueryOptions.class); return new BigQueryReader(this, bqServices.getReaderFromQuery( - bqOptions, query, executingProject, flattenResults, useLegacySql)); + bqOptions, query.get(), executingProject.get(), flattenResults, useLegacySql)); } @Override @@ -956,7 +1066,7 @@ protected TableReference getTableToExtract(BigQueryOptions bqOptions) // 2. Create the temporary dataset in the query location. TableReference tableToExtract = - JSON_FACTORY.fromString(jsonQueryTempTable, TableReference.class); + JSON_FACTORY.fromString(jsonQueryTempTable.get(), TableReference.class); tableService.createDataset( tableToExtract.getProjectId(), tableToExtract.getDatasetId(), @@ -966,7 +1076,7 @@ protected TableReference getTableToExtract(BigQueryOptions bqOptions) // 3. Execute the query. String queryJobId = jobIdToken + "-query"; executeQuery( - executingProject, + executingProject.get(), queryJobId, tableToExtract, bqServices.getJobService(bqOptions)); @@ -975,8 +1085,9 @@ protected TableReference getTableToExtract(BigQueryOptions bqOptions) @Override protected void cleanupTempResource(BigQueryOptions bqOptions) throws Exception { + checkState(jsonQueryTempTable.isAccessible()); TableReference tableToRemove = - JSON_FACTORY.fromString(jsonQueryTempTable, TableReference.class); + JSON_FACTORY.fromString(jsonQueryTempTable.get(), TableReference.class); DatasetService tableService = bqServices.getDatasetService(bqOptions); tableService.deleteTable( @@ -996,7 +1107,7 @@ private synchronized JobStatistics dryRunQueryIfNeeded(BigQueryOptions bqOptions throws InterruptedException, IOException { if (dryRunJobStats.get() == null) { JobStatistics jobStats = bqServices.getJobService(bqOptions).dryRunQuery( - executingProject, createBasicQueryConfig()); + executingProject.get(), createBasicQueryConfig()); dryRunJobStats.compareAndSet(null, jobStats); } return dryRunJobStats.get(); @@ -1027,7 +1138,7 @@ private void executeQuery( private JobConfigurationQuery createBasicQueryConfig() { return new JobConfigurationQuery() - .setQuery(query) + .setQuery(query.get()) .setFlattenResults(flattenResults) .setUseLegacySql(useLegacySql); } @@ -1064,13 +1175,13 @@ private abstract static class BigQuerySourceBase extends BoundedSource protected final String jobIdToken; protected final String extractDestinationDir; protected final BigQueryServices bqServices; - protected final String executingProject; + protected final ValueProvider executingProject; private BigQuerySourceBase( String jobIdToken, String extractDestinationDir, BigQueryServices bqServices, - String executingProject) { + ValueProvider executingProject) { this.jobIdToken = checkNotNull(jobIdToken, "jobIdToken"); this.extractDestinationDir = checkNotNull(extractDestinationDir, "extractDestinationDir"); this.bqServices = checkNotNull(bqServices, "bqServices"); @@ -1118,7 +1229,7 @@ private List executeExtract( String jobId, TableReference table, JobService jobService) throws InterruptedException, IOException { JobReference jobRef = new JobReference() - .setProjectId(executingProject) + .setProjectId(executingProject.get()) .setJobId(jobId); String destinationUri = getExtractDestinationUri(extractDestinationDir); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index f651d8bca9..d6796fe598 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -70,6 +70,7 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; @@ -423,7 +424,7 @@ private void checkReadTableObjectWithValidate( private void checkReadQueryObjectWithValidate( BigQueryIO.Read.Bound bound, String query, boolean validate) { assertNull(bound.getTable()); - assertEquals(query, bound.query); + assertEquals(query, bound.getQuery()); assertEquals(validate, bound.getValidate()); } @@ -505,22 +506,29 @@ public void testBuildSourceWithTableReference() { @Test public void testValidateReadSetsDefaultProject() { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); + String projectId = "someproject"; + String datasetId = "somedataset"; + String tableId = "sometable"; + BigQueryOptions bqOptions = TestPipeline.testingPipelineOptions().as(BigQueryOptions.class); + bqOptions.setProject(projectId); bqOptions.setTempLocation("gs://testbucket/testdir"); - Pipeline p = Pipeline.create(bqOptions); + FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() + .withJobService(new FakeJobService()) + .withDatasetService(mockDatasetService); + + Pipeline p = TestPipeline.create(bqOptions); TableReference tableRef = new TableReference(); - tableRef.setDatasetId("somedataset"); - tableRef.setTableId("sometable"); + tableRef.setDatasetId(datasetId); + tableRef.setTableId(tableId); thrown.expect(RuntimeException.class); // Message will be one of following depending on the execution environment. - thrown.expectMessage( - Matchers.either(Matchers.containsString("Unable to confirm BigQuery dataset presence")) - .or(Matchers.containsString("BigQuery dataset not found for table"))); - p.apply(BigQueryIO.Read.named("ReadMyTable").from(tableRef)); + thrown.expectMessage(Matchers.containsString( + "Unable to confirm BigQuery dataset presence for table")); + p.apply(BigQueryIO.Read.from(tableRef) + .withTestServices(fakeBqServices)); } @Test @@ -1058,7 +1066,8 @@ public void testBigQueryTableSourceThroughJsonAPI() throws Exception { TableReference table = BigQueryIO.parseTableSpec("project:data_set.table_name"); String extractDestinationDir = "mock://tempLocation"; BoundedSource bqSource = BigQueryTableSource.create( - jobIdToken, table, extractDestinationDir, fakeBqServices, "project"); + jobIdToken, StaticValueProvider.of(table), extractDestinationDir, fakeBqServices, + StaticValueProvider.of("project")); List expected = ImmutableList.of( new TableRow().set("name", "a").set("number", "1"), @@ -1095,7 +1104,8 @@ public void testBigQueryTableSourceInitSplit() throws Exception { TableReference table = BigQueryIO.parseTableSpec("project:data_set.table_name"); String extractDestinationDir = "mock://tempLocation"; BoundedSource bqSource = BigQueryTableSource.create( - jobIdToken, table, extractDestinationDir, fakeBqServices, "project"); + jobIdToken, StaticValueProvider.of(table), extractDestinationDir, fakeBqServices, + StaticValueProvider.of("project")); List expected = ImmutableList.of( new TableRow().set("name", "a").set("number", "1"), @@ -1160,7 +1170,8 @@ public void testBigQueryQuerySourceInitSplit() throws Exception { String extractDestinationDir = "mock://tempLocation"; TableReference destinationTable = BigQueryIO.parseTableSpec("project:data_set.table_name"); BoundedSource bqSource = BigQueryQuerySource.create( - jobIdToken, "query", destinationTable, true /* flattenResults */, true /* useLegacySql */, + jobIdToken, StaticValueProvider.of("query"), StaticValueProvider.of(destinationTable), + true /* flattenResults */, true /* useLegacySql */, extractDestinationDir, fakeBqServices); List expected = ImmutableList.of( @@ -1251,7 +1262,8 @@ public void testBigQueryNoTableQuerySourceInitSplit() throws Exception { String extractDestinationDir = "mock://tempLocation"; TableReference destinationTable = BigQueryIO.parseTableSpec("project:data_set.table_name"); BoundedSource bqSource = BigQueryQuerySource.create( - jobIdToken, "query", destinationTable, true /* flattenResults */, true /* useLegacySql */, + jobIdToken, StaticValueProvider.of("query"), StaticValueProvider.of(destinationTable), + true /* flattenResults */, true /* useLegacySql */, extractDestinationDir, fakeBqServices); List expected = ImmutableList.of( From 03bf9b7de04f53c8c307d5e9d8da2a735fe65fb8 Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Tue, 13 Dec 2016 16:59:32 -0800 Subject: [PATCH 643/751] Increase KafkaIO version to 0.2.0 Recent PR #491 changes how KafkaIO splits. This makes it incompatible with Dataflow update across these two versions. --- contrib/kafka/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/kafka/pom.xml b/contrib/kafka/pom.xml index 4beecd7ba5..29f64d5577 100644 --- a/contrib/kafka/pom.xml +++ b/contrib/kafka/pom.xml @@ -25,7 +25,7 @@ google-cloud-dataflow-java-contrib-kafka Google Cloud Dataflow Kafka IO Library Library to read Kafka topics. - 0.1.0-SNAPSHOT + 0.2.0-SNAPSHOT [1.6.0, 2.0.0) From bdbe05ec68e45a3082022649b8b5d68d6a56bfa9 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Wed, 14 Dec 2016 13:14:12 -0800 Subject: [PATCH 644/751] PubsubIO: support ValueProvider for read and write Backport https://github.com/apache/incubator-beam/pull/1230 (#501) Update PubsubUnboundedSink.java Update PubsubUnboundedSource.java Update PubsubIOTest.java Update PubsubUnboundedSinkTest.java Update PubsubUnboundedSourceTest.java Fixups Fixups * Fixups --- .../cloud/dataflow/sdk/io/PubsubIO.java | 179 +++++++++++++++--- .../dataflow/sdk/io/PubsubUnboundedSink.java | 25 ++- .../sdk/io/PubsubUnboundedSource.java | 58 ++++-- .../cloud/dataflow/sdk/io/PubsubIOTest.java | 27 ++- .../sdk/io/PubsubUnboundedSinkTest.java | 20 +- .../sdk/io/PubsubUnboundedSourceTest.java | 6 +- 6 files changed, 248 insertions(+), 67 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java index 875e25bcd8..55dd24f6b7 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java @@ -22,12 +22,16 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; import com.google.cloud.dataflow.sdk.runners.PipelineRunner; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.PTransform; import com.google.cloud.dataflow.sdk.transforms.ParDo; +import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; import com.google.cloud.dataflow.sdk.util.CoderUtils; @@ -137,7 +141,7 @@ private static void validatePubsubName(String name) { * Populate common {@link DisplayData} between Pubsub source and sink. */ private static void populateCommonDisplayData(DisplayData.Builder builder, - String timestampLabel, String idLabel, PubsubTopic topic) { + String timestampLabel, String idLabel, ValueProvider topic) { builder .addIfNotNull(DisplayData.item("timestampLabel", timestampLabel) .withLabel("Timestamp Label Attribute")) @@ -145,7 +149,9 @@ private static void populateCommonDisplayData(DisplayData.Builder builder, .withLabel("ID Label Attribute")); if (topic != null) { - builder.add(DisplayData.item("topic", topic.asPath()) + String topicString = topic.isAccessible() ? topic.get().asPath() + : topic.toString(); + builder.add(DisplayData.item("topic", topicString) .withLabel("Pubsub Topic")); } } @@ -255,6 +261,61 @@ public String asPath() { } } + /** + * Used to build a {@link ValueProvider} for {@link PubsubSubscription}. + */ + private static class SubscriptionTranslator + implements SerializableFunction { + @Override + public PubsubSubscription apply(String from) { + return PubsubSubscription.fromPath(from); + } + } + + /** + * Used to build a {@link ValueProvider} for {@link SubscriptionPath}. + */ + private static class SubscriptionPathTranslator + implements SerializableFunction { + @Override + public SubscriptionPath apply(PubsubSubscription from) { + return PubsubClient.subscriptionPathFromName(from.project, from.subscription); + } + } + + /** + * Used to build a {@link ValueProvider} for {@link PubsubTopic}. + */ + private static class TopicTranslator + implements SerializableFunction { + @Override + public PubsubTopic apply(String from) { + return PubsubTopic.fromPath(from); + } + } + + /** + * Used to build a {@link ValueProvider} for {@link TopicPath}. + */ + private static class TopicPathTranslator + implements SerializableFunction { + @Override + public TopicPath apply(PubsubTopic from) { + return PubsubClient.topicPathFromName(from.project, from.topic); + } + } + + /** + * Used to build a {@link ValueProvider} for {@link ProjectPath}. + */ + private static class ProjectPathTranslator + implements SerializableFunction { + @Override + public ProjectPath apply(PubsubTopic from) { + return PubsubClient.projectPathFromId(from.project); + } + } + /** * Class representing a Cloud Pub/Sub Topic. */ @@ -378,6 +439,13 @@ public static Bound named(String name) { return new Bound<>(DEFAULT_PUBSUB_CODER).named(name); } + /** + * Like {@code topic()} but with a {@link ValueProvider}. + */ + public static Bound topic(ValueProvider topic) { + return new Bound<>(DEFAULT_PUBSUB_CODER).topic(topic); + } + /** * Creates and returns a transform for reading from a Cloud Pub/Sub topic. Mutually exclusive * with {@link #subscription(String)}. @@ -390,7 +458,7 @@ public static Bound named(String name) { * Dataflow. */ public static Bound topic(String topic) { - return new Bound<>(DEFAULT_PUBSUB_CODER).topic(topic); + return new Bound<>(DEFAULT_PUBSUB_CODER).topic(StaticValueProvider.of(topic)); } /** @@ -401,6 +469,13 @@ public static Bound topic(String topic) { * of the {@code subscription} string. */ public static Bound subscription(String subscription) { + return new Bound<>(DEFAULT_PUBSUB_CODER).subscription(StaticValueProvider.of(subscription)); + } + + /** + * Like {@code topic()} but with a {@link ValueProvider}. + */ + public static Bound subscription(ValueProvider subscription) { return new Bound<>(DEFAULT_PUBSUB_CODER).subscription(subscription); } @@ -494,10 +569,10 @@ public static Bound maxReadTime(Duration maxReadTime) { */ public static class Bound extends PTransform> { /** The Cloud Pub/Sub topic to read from. */ - @Nullable private final PubsubTopic topic; + @Nullable private final ValueProvider topic; /** The Cloud Pub/Sub subscription to read from. */ - @Nullable private final PubsubSubscription subscription; + @Nullable private final ValueProvider subscription; /** The name of the message attribute to read timestamps from. */ @Nullable private final String timestampLabel; @@ -518,9 +593,9 @@ private Bound(Coder coder) { this(null, null, null, null, coder, null, 0, null); } - private Bound(String name, PubsubSubscription subscription, PubsubTopic topic, - String timestampLabel, Coder coder, String idLabel, int maxNumRecords, - Duration maxReadTime) { + private Bound(String name, ValueProvider subscription, + ValueProvider topic, String timestampLabel, Coder coder, + String idLabel, int maxNumRecords, Duration maxReadTime) { super(name); this.subscription = subscription; this.topic = topic; @@ -555,8 +630,20 @@ public Bound named(String name) { *

            Does not modify this object. */ public Bound subscription(String subscription) { - return new Bound<>(name, PubsubSubscription.fromPath(subscription), topic, timestampLabel, - coder, idLabel, maxNumRecords, maxReadTime); + return subscription(StaticValueProvider.of(subscription)); + } + + /** + * Like {@code subscription()} but with a {@link ValueProvider}. + */ + public Bound subscription(ValueProvider subscription) { + if (subscription.isAccessible()) { + // Validate. + PubsubSubscription.fromPath(subscription.get()); + } + return new Bound<>(name, + NestedValueProvider.of(subscription, new SubscriptionTranslator()), + topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); } /** @@ -568,8 +655,20 @@ public Bound subscription(String subscription) { *

            Does not modify this object. */ public Bound topic(String topic) { - return new Bound<>(name, subscription, PubsubTopic.fromPath(topic), timestampLabel, coder, - idLabel, maxNumRecords, maxReadTime); + return topic(StaticValueProvider.of(topic)); + } + + /** + * Like {@code topic()} but with a {@link ValueProvider}. + */ + public Bound topic(ValueProvider topic) { + if (topic.isAccessible()) { + // Validate. + PubsubTopic.fromPath(topic.get()); + } + return new Bound<>(name, subscription, + NestedValueProvider.of(topic, new TopicTranslator()), + timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); } /** @@ -649,15 +748,14 @@ public PCollection apply(PInput input) { .apply(ParDo.of(new PubsubReader())) .setCoder(coder); } else { - @Nullable ProjectPath projectPath = - topic == null ? null : PubsubClient.projectPathFromId(topic.project); - @Nullable TopicPath topicPath = - topic == null ? null : PubsubClient.topicPathFromName(topic.project, topic.topic); - @Nullable SubscriptionPath subscriptionPath = + @Nullable ValueProvider projectPath = + topic == null ? null : NestedValueProvider.of(topic, new ProjectPathTranslator()); + @Nullable ValueProvider topicPath = + topic == null ? null : NestedValueProvider.of(topic, new TopicPathTranslator()); + @Nullable ValueProvider subscriptionPath = subscription == null ? null - : PubsubClient.subscriptionPathFromName( - subscription.project, subscription.subscription); + : NestedValueProvider.of(subscription, new SubscriptionPathTranslator()); return input.getPipeline().begin() .apply(new PubsubUnboundedSource( FACTORY, projectPath, topicPath, subscriptionPath, @@ -667,7 +765,6 @@ public PCollection apply(PInput input) { @Override public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); populateCommonDisplayData(builder, timestampLabel, idLabel, topic); builder @@ -677,8 +774,10 @@ public void populateDisplayData(DisplayData.Builder builder) { .withLabel("Maximum Read Records"), 0); if (subscription != null) { - builder.add(DisplayData.item("subscription", subscription.asPath()) - .withLabel("Pubsub Subscription")); + String subscriptionString = subscription.isAccessible() + ? subscription.get().asPath() : subscription.toString(); + builder.add(DisplayData.item("subscription", subscriptionString) + .withLabel("Pubsub Subscription")); } } @@ -688,10 +787,18 @@ protected Coder getDefaultOutputCoder() { } public PubsubTopic getTopic() { + return topic == null ? null : topic.get(); + } + + public ValueProvider getTopicProvider() { return topic; } public PubsubSubscription getSubscription() { + return subscription == null ? null : subscription.get(); + } + + public ValueProvider getSubscriptionProvider() { return subscription; } @@ -848,6 +955,13 @@ public static Bound named(String name) { * {@code topic} string. */ public static Bound topic(String topic) { + return new Bound<>(DEFAULT_PUBSUB_CODER).topic(StaticValueProvider.of(topic)); + } + + /** + * Like {@code topic()} but with a {@link ValueProvider}. + */ + public static Bound topic(ValueProvider topic) { return new Bound<>(DEFAULT_PUBSUB_CODER).topic(topic); } @@ -897,7 +1011,7 @@ public static Bound withCoder(Coder coder) { */ public static class Bound extends PTransform, PDone> { /** The Cloud Pub/Sub topic to publish to. */ - @Nullable private final PubsubTopic topic; + @Nullable private final ValueProvider topic; /** The name of the message attribute to publish message timestamps in. */ @Nullable private final String timestampLabel; /** The name of the message attribute to publish unique message IDs in. */ @@ -909,7 +1023,8 @@ private Bound(Coder coder) { } private Bound( - String name, PubsubTopic topic, String timestampLabel, String idLabel, Coder coder) { + String name, ValueProvider topic, String timestampLabel, + String idLabel, Coder coder) { super(name); this.topic = topic; this.timestampLabel = timestampLabel; @@ -937,7 +1052,15 @@ public Bound named(String name) { *

            Does not modify this object. */ public Bound topic(String topic) { - return new Bound<>(name, PubsubTopic.fromPath(topic), timestampLabel, idLabel, coder); + return topic(StaticValueProvider.of(topic)); + } + + /** + * Like {@code topic()} but with a {@link ValueProvider}. + */ + public Bound topic(ValueProvider topic) { + return new Bound<>(name, NestedValueProvider.of(topic, new TopicTranslator()), + timestampLabel, idLabel, coder); } /** @@ -988,7 +1111,7 @@ public PDone apply(PCollection input) { case UNBOUNDED: return input.apply(new PubsubUnboundedSink( FACTORY, - PubsubClient.topicPathFromName(topic.project, topic.topic), + NestedValueProvider.of(topic, new TopicPathTranslator()), coder, timestampLabel, idLabel, @@ -1009,6 +1132,10 @@ protected Coder getDefaultOutputCoder() { } public PubsubTopic getTopic() { + return topic.get(); + } + + public ValueProvider getTopicProvider() { return topic; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java index 359af380d2..26ffb9e11b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java @@ -28,6 +28,7 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.coders.VarIntCoder; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.GroupByKey; @@ -207,7 +208,7 @@ public void populateDisplayData(Builder builder) { private static class WriterFn extends DoFn>, Void> { private final PubsubClientFactory pubsubFactory; - private final TopicPath topic; + private final ValueProvider topic; private final String timestampLabel; private final String idLabel; private final int publishBatchSize; @@ -227,8 +228,8 @@ private static class WriterFn createAggregator("bytes", new Sum.SumLongFn()); WriterFn( - PubsubClientFactory pubsubFactory, TopicPath topic, String timestampLabel, - String idLabel, int publishBatchSize, int publishBatchBytes) { + PubsubClientFactory pubsubFactory, ValueProvider topic, + String timestampLabel, String idLabel, int publishBatchSize, int publishBatchBytes) { this.pubsubFactory = pubsubFactory; this.topic = topic; this.timestampLabel = timestampLabel; @@ -243,7 +244,7 @@ private static class WriterFn */ private void publishBatch(List messages, int bytes) throws IOException { - int n = pubsubClient.publish(topic, messages); + int n = pubsubClient.publish(topic.get(), messages); checkState(n == messages.size(), "Attempted to publish %s messages but %s were successful", messages.size(), n); batchCounter.addValue(1L); @@ -293,7 +294,11 @@ public void finishBundle(Context c) throws Exception { @Override public void populateDisplayData(Builder builder) { super.populateDisplayData(builder); - builder.add(DisplayData.item("topic", topic.getPath())); + String topicString = + topic == null ? null + : topic.isAccessible() ? topic.get().getPath() + : topic.toString(); + builder.add(DisplayData.item("topic", topicString)); builder.add(DisplayData.item("transport", pubsubFactory.getKind())); builder.addIfNotNull(DisplayData.item("timestampLabel", timestampLabel)); builder.addIfNotNull(DisplayData.item("idLabel", idLabel)); @@ -312,7 +317,7 @@ public void populateDisplayData(Builder builder) { /** * Pubsub topic to publish to. */ - private final TopicPath topic; + private final ValueProvider topic; /** * Coder for elements. It is the responsibility of the underlying Pubsub transport to @@ -366,7 +371,7 @@ public void populateDisplayData(Builder builder) { @VisibleForTesting PubsubUnboundedSink( PubsubClientFactory pubsubFactory, - TopicPath topic, + ValueProvider topic, Coder elementCoder, String timestampLabel, String idLabel, @@ -389,7 +394,7 @@ public void populateDisplayData(Builder builder) { public PubsubUnboundedSink( PubsubClientFactory pubsubFactory, - TopicPath topic, + ValueProvider topic, Coder elementCoder, String timestampLabel, String idLabel, @@ -400,6 +405,10 @@ public PubsubUnboundedSink( } public TopicPath getTopic() { + return topic.get(); + } + + public ValueProvider getTopicProvider() { return topic; } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java index 6910824287..575fe39771 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java @@ -29,6 +29,7 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -608,7 +609,7 @@ PubsubClient getPubsubClient() { * CAUTION: Retains {@code ackIds}. */ void ackBatch(List ackIds) throws IOException { - pubsubClient.acknowledge(outer.outer.subscription, ackIds); + pubsubClient.acknowledge(outer.outer.subscription.get(), ackIds); ackedIds.add(ackIds); } @@ -618,7 +619,7 @@ void ackBatch(List ackIds) throws IOException { * with the given {@code ockIds}. Does not retain {@code ackIds}. */ public void nackBatch(long nowMsSinceEpoch, List ackIds) throws IOException { - pubsubClient.modifyAckDeadline(outer.outer.subscription, ackIds, 0); + pubsubClient.modifyAckDeadline(outer.outer.subscription.get(), ackIds, 0); numNacked.add(nowMsSinceEpoch, ackIds.size()); } @@ -629,7 +630,7 @@ public void nackBatch(long nowMsSinceEpoch, List ackIds) throws IOExcept */ private void extendBatch(long nowMsSinceEpoch, List ackIds) throws IOException { int extensionSec = (ackTimeoutMs * ACK_EXTENSION_PCT) / (100 * 1000); - pubsubClient.modifyAckDeadline(outer.outer.subscription, ackIds, extensionSec); + pubsubClient.modifyAckDeadline(outer.outer.subscription.get(), ackIds, extensionSec); numExtendedDeadlines.add(nowMsSinceEpoch, ackIds.size()); } @@ -765,7 +766,7 @@ private void pull() throws IOException { // BLOCKs until received. Collection receivedMessages = pubsubClient.pull(requestTimeMsSinceEpoch, - outer.outer.subscription, + outer.outer.subscription.get(), PULL_BATCH_SIZE, true); if (receivedMessages.isEmpty()) { // Nothing available yet. Try again later. @@ -871,7 +872,7 @@ private void stats() { @Override public boolean start() throws IOException { // Determine the ack timeout. - ackTimeoutMs = pubsubClient.ackDeadlineSeconds(outer.outer.subscription) * 1000; + ackTimeoutMs = pubsubClient.ackDeadlineSeconds(outer.outer.subscription.get()) * 1000; return advance(); } @@ -1111,7 +1112,7 @@ private static class StatsFn extends DoFn { createAggregator("elements", new Sum.SumLongFn()); private final PubsubClientFactory pubsubFactory; - private final SubscriptionPath subscription; + private final ValueProvider subscription; @Nullable private final String timestampLabel; @Nullable @@ -1119,7 +1120,7 @@ private static class StatsFn extends DoFn { public StatsFn( PubsubClientFactory pubsubFactory, - SubscriptionPath subscription, + ValueProvider subscription, @Nullable String timestampLabel, @Nullable @@ -1139,7 +1140,11 @@ public void processElement(ProcessContext c) throws Exception { @Override public void populateDisplayData(Builder builder) { super.populateDisplayData(builder); - builder.add(DisplayData.item("subscription", subscription.getPath())); + String subscriptionString = + subscription == null ? null + : subscription.isAccessible() ? subscription.get().getPath() + : subscription.toString(); + builder.add(DisplayData.item("subscription", subscriptionString)); builder.add(DisplayData.item("transport", pubsubFactory.getKind())); builder.addIfNotNull(DisplayData.item("timestampLabel", timestampLabel)); builder.addIfNotNull(DisplayData.item("idLabel", idLabel)); @@ -1165,14 +1170,14 @@ public void populateDisplayData(Builder builder) { * Project under which to create a subscription if only the {@link #topic} was given. */ @Nullable - private final ProjectPath project; + private final ValueProvider project; /** * Topic to read from. If {@literal null}, then {@link #subscription} must be given. * Otherwise {@link #subscription} must be null. */ @Nullable - private final TopicPath topic; + private final ValueProvider topic; /** * Subscription to read from. If {@literal null} then {@link #topic} must be given. @@ -1183,7 +1188,7 @@ public void populateDisplayData(Builder builder) { * subscription is never deleted. */ @Nullable - private SubscriptionPath subscription; + private ValueProvider subscription; /** * Coder for elements. Elements are effectively double-encoded: first to a byte array @@ -1210,9 +1215,9 @@ public void populateDisplayData(Builder builder) { PubsubUnboundedSource( Clock clock, PubsubClientFactory pubsubFactory, - @Nullable ProjectPath project, - @Nullable TopicPath topic, - @Nullable SubscriptionPath subscription, + @Nullable ValueProvider project, + @Nullable ValueProvider topic, + @Nullable ValueProvider subscription, Coder elementCoder, @Nullable String timestampLabel, @Nullable String idLabel) { @@ -1235,9 +1240,9 @@ public void populateDisplayData(Builder builder) { */ public PubsubUnboundedSource( PubsubClientFactory pubsubFactory, - @Nullable ProjectPath project, - @Nullable TopicPath topic, - @Nullable SubscriptionPath subscription, + @Nullable ValueProvider project, + @Nullable ValueProvider topic, + @Nullable ValueProvider subscription, Coder elementCoder, @Nullable String timestampLabel, @Nullable String idLabel) { @@ -1250,16 +1255,26 @@ public Coder getElementCoder() { @Nullable public ProjectPath getProject() { - return project; + return project == null ? null : project.get(); } @Nullable public TopicPath getTopic() { + return topic == null ? null : topic.get(); + } + + @Nullable + public ValueProvider getTopicProvider() { return topic; } @Nullable public SubscriptionPath getSubscription() { + return subscription == null ? null : subscription.get(); + } + + @Nullable + public ValueProvider getSubscriptionProvider() { return subscription; } @@ -1282,8 +1297,11 @@ public PCollection apply(PBegin input) { input.getPipeline() .getOptions() .as(DataflowPipelineOptions.class))) { - subscription = - pubsubClient.createRandomSubscription(project, topic, DEAULT_ACK_TIMEOUT_SEC); + checkState(project.isAccessible(), "createRandomSubscription must be called at runtime."); + checkState(topic.isAccessible(), "createRandomSubscription must be called at runtime."); + SubscriptionPath subscriptionPath = + pubsubClient.createRandomSubscription( + project.get(), topic.get(), DEAULT_ACK_TIMEOUT_SEC); LOG.warn("Created subscription {} to topic {}." + " Note this subscription WILL NOT be deleted when the pipeline terminates", subscription, topic); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java index bbba56187d..fbb563e4d7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java @@ -20,8 +20,11 @@ import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; @@ -91,8 +94,8 @@ public void testReadDisplayData() { String subscription = "projects/project/subscriptions/subscription"; Duration maxReadTime = Duration.standardMinutes(5); PubsubIO.Read.Bound read = PubsubIO.Read - .topic(topic) - .subscription(subscription) + .topic(StaticValueProvider.of(topic)) + .subscription(StaticValueProvider.of(subscription)) .timestampLabel("myTimestamp") .idLabel("myId") .maxNumRecords(1234) @@ -134,6 +137,26 @@ public void testPrimitiveWriteDisplayData() { displayData, hasItem(hasDisplayItem("topic"))); } + @Test + public void testNullTopic() { + String subscription = "projects/project/subscriptions/subscription"; + PubsubIO.Read.Bound read = PubsubIO.Read + .subscription(StaticValueProvider.of(subscription)); + assertNull(read.getTopic()); + assertNotNull(read.getSubscription()); + assertNotNull(DisplayData.from(read)); + } + + @Test + public void testNullSubscription() { + String topic = "projects/project/topics/topic"; + PubsubIO.Read.Bound read = PubsubIO.Read + .topic(StaticValueProvider.of(topic)); + assertNotNull(read.getTopic()); + assertNull(read.getSubscription()); + assertNotNull(DisplayData.from(read)); + } + @Test public void testPrimitiveReadDisplayData() { DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java index ef95a643f9..287f07e52c 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java @@ -18,6 +18,7 @@ import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSink.RecordIdMethod; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.testing.CoderProperties; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; @@ -82,9 +83,9 @@ public void sendOneMessage() throws IOException { PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, ImmutableList.of())) { PubsubUnboundedSink sink = - new PubsubUnboundedSink<>(factory, TOPIC, StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, - NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), - RecordIdMethod.DETERMINISTIC); + new PubsubUnboundedSink<>(factory, StaticValueProvider.of(TOPIC), StringUtf8Coder.of(), + TIMESTAMP_LABEL, ID_LABEL, NUM_SHARDS, batchSize, batchBytes, + Duration.standardSeconds(2), RecordIdMethod.DETERMINISTIC); TestPipeline p = TestPipeline.create(); p.apply(Create.of(ImmutableList.of(DATA))) .apply(ParDo.of(new Stamp())) @@ -110,9 +111,9 @@ public void sendMoreThanOneBatchByNumMessages() throws IOException { PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, ImmutableList.of())) { PubsubUnboundedSink sink = - new PubsubUnboundedSink<>(factory, TOPIC, StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, - NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), - RecordIdMethod.DETERMINISTIC); + new PubsubUnboundedSink<>(factory, StaticValueProvider.of(TOPIC), StringUtf8Coder.of(), + TIMESTAMP_LABEL, ID_LABEL, NUM_SHARDS, batchSize, batchBytes, + Duration.standardSeconds(2), RecordIdMethod.DETERMINISTIC); TestPipeline p = TestPipeline.create(); p.apply(Create.of(data)) .apply(ParDo.of(new Stamp())) @@ -144,9 +145,10 @@ public void sendMoreThanOneBatchByByteSize() throws IOException { PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, ImmutableList.of())) { PubsubUnboundedSink sink = - new PubsubUnboundedSink<>(factory, TOPIC, StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, - NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), - RecordIdMethod.DETERMINISTIC); + new PubsubUnboundedSink<>(factory, StaticValueProvider.of(TOPIC), + StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, + NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), + RecordIdMethod.DETERMINISTIC); TestPipeline p = TestPipeline.create(); p.apply(Create.of(data)) .apply(ParDo.of(new Stamp())) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java index 0788347726..f7e4f863de 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java @@ -30,6 +30,7 @@ import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubCheckpoint; import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubReader; import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubSource; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.testing.CoderProperties; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.util.CoderUtils; @@ -85,8 +86,9 @@ public long currentTimeMillis() { }; factory = PubsubTestClient.createFactoryForPull(clock, SUBSCRIPTION, ACK_TIMEOUT_S, incoming); PubsubUnboundedSource source = - new PubsubUnboundedSource<>(clock, factory, null, null, SUBSCRIPTION, StringUtf8Coder.of(), - TIMESTAMP_LABEL, ID_LABEL); + new PubsubUnboundedSource<>( + clock, factory, null, null, StaticValueProvider.of(SUBSCRIPTION), + StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL); primSource = new PubsubSource<>(source); } From e4e0e664ccc6f02c10a2a6455cfe6395318c46e1 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Wed, 14 Dec 2016 14:29:03 -0800 Subject: [PATCH 645/751] DataflowRunner: add support for Dataflow-PubSubIO with ValueProviders Backport https://github.com/apache/incubator-beam/pull/1504 (#503) --- .../sdk/runners/DataflowPipelineRunner.java | 37 +++++++++++++++---- .../dataflow/sdk/util/PropertyNames.java | 2 + 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index c1a7b88414..c350b038bf 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -73,6 +73,7 @@ import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; import com.google.cloud.dataflow.sdk.options.StreamingOptions; +import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.JobSpecification; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; @@ -2379,14 +2380,27 @@ private void translateTyped( "StreamingPubsubIORead is only for streaming pipelines."); context.addStep(transform, "ParallelRead"); context.addInput(PropertyNames.FORMAT, "pubsub"); - if (transform.getTopic() != null) { - context.addInput(PropertyNames.PUBSUB_TOPIC, - transform.getTopic().asV1Beta1Path()); + if (transform.getTopicProvider() != null) { + if (transform.getTopicProvider().isAccessible()) { + context.addInput( + PropertyNames.PUBSUB_TOPIC, transform.getTopic().asV1Beta1Path()); + } else { + context.addInput( + PropertyNames.PUBSUB_TOPIC_OVERRIDE, + ((NestedValueProvider) transform.getTopicProvider()).propertyName()); + } } - if (transform.getSubscription() != null) { - context.addInput( - PropertyNames.PUBSUB_SUBSCRIPTION, - transform.getSubscription().asV1Beta1Path()); + if (transform.getSubscriptionProvider() != null) { + if (transform.getSubscriptionProvider().isAccessible()) { + context.addInput( + PropertyNames.PUBSUB_SUBSCRIPTION, + transform.getSubscription().asV1Beta1Path()); + } else { + context.addInput( + PropertyNames.PUBSUB_SUBSCRIPTION_OVERRIDE, + ((NestedValueProvider) transform.getSubscriptionProvider()) + .propertyName()); + } } if (transform.getTimestampLabel() != null) { context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, @@ -2457,7 +2471,14 @@ private void translateTyped( PubsubIO.Write.Bound overriddenTransform = transform.getOverriddenTransform(); context.addStep(transform, "ParallelWrite"); context.addInput(PropertyNames.FORMAT, "pubsub"); - context.addInput(PropertyNames.PUBSUB_TOPIC, overriddenTransform.getTopic().asV1Beta1Path()); + if (overriddenTransform.getTopicProvider().isAccessible()) { + context.addInput( + PropertyNames.PUBSUB_TOPIC, overriddenTransform.getTopic().asV1Beta1Path()); + } else { + context.addInput( + PropertyNames.PUBSUB_TOPIC_OVERRIDE, + ((NestedValueProvider) overriddenTransform.getTopicProvider()).propertyName()); + } if (overriddenTransform.getTimestampLabel() != null) { context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, overriddenTransform.getTimestampLabel()); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java index 75c21e6e66..5771fa44e4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java @@ -83,8 +83,10 @@ public class PropertyNames { public static final String PHASE = "phase"; public static final String PUBSUB_ID_LABEL = "pubsub_id_label"; public static final String PUBSUB_SUBSCRIPTION = "pubsub_subscription"; + public static final String PUBSUB_SUBSCRIPTION_OVERRIDE = "pubsub_subscription_runtime_override"; public static final String PUBSUB_TIMESTAMP_LABEL = "pubsub_timestamp_label"; public static final String PUBSUB_TOPIC = "pubsub_topic"; + public static final String PUBSUB_TOPIC_OVERRIDE = "pubsub_topic_runtime_override"; public static final String SCALAR_FIELD_NAME = "value"; public static final String SERIALIZED_FN = "serialized_fn"; public static final String SHARD_NAME_TEMPLATE = "shard_template"; From 2d17f3abd123f17d76aa0c615dba839785978b45 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Wed, 14 Dec 2016 16:46:30 -0800 Subject: [PATCH 646/751] BigQueryIO support for ValueProvider * Update BigQueryIO.java * Update BigQueryIO.java * Update BigQueryIO.java * Update BigQueryIOTest.java * Fixups * Fixups * Fixups * Fixups --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 204 +++++++++++++----- .../sdk/runners/DataflowPipelineRunner.java | 2 +- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 74 ++++++- 3 files changed, 217 insertions(+), 63 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index a0ccb78564..1db12bb15f 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -336,6 +336,23 @@ public static String toTableSpec(TableReference ref) { return sb.toString(); } + @VisibleForTesting + static class JsonSchemaToTableSchema + implements SerializableFunction { + @Override + public TableSchema apply(String from) { + return fromJsonString(from, TableSchema.class); + } + } + + private static class TableSchemaToJsonSchema + implements SerializableFunction { + @Override + public String apply(TableSchema from) { + return toJsonString(from); + } + } + private static class JsonTableRefToTableRef implements SerializableFunction { @Override @@ -344,6 +361,14 @@ public TableReference apply(String from) { } } + private static class TableRefToTableSpec + implements SerializableFunction { + @Override + public String apply(TableReference from) { + return toTableSpec(from); + } + } + private static class TableRefToJson implements SerializableFunction { @Override @@ -368,6 +393,15 @@ public TableReference apply(String from) { } } + @Nullable + private static ValueProvider displayTable( + @Nullable ValueProvider table) { + if (table == null) { + return null; + } + return NestedValueProvider.of(table, new TableRefToTableSpec()); + } + /** * A {@link PTransform} that reads from a BigQuery table and returns a * {@link PCollection} of {@link TableRow TableRows} containing each of the rows of the table. @@ -699,11 +733,11 @@ public PCollection apply(PInput input) { .setProjectId(executingProject) .setDatasetId(queryTempDatasetId) .setTableId(queryTempTableId); + String jsonTableRef = toJsonString(queryTempTableRef); source = BigQueryQuerySource.create( jobIdToken, query, NestedValueProvider.of( - StaticValueProvider.of( - toJsonString(queryTempTableRef)), new JsonTableRefToTableRef()), + StaticValueProvider.of(jsonTableRef), new JsonTableRefToTableRef()), flattenResults, useLegacySql, extractDestinationDir, bqServices); } else { ValueProvider inputTable = getTableWithDefaultProject(bqOptions); @@ -752,14 +786,9 @@ protected Coder getDefaultOutputCoder() { @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); - TableReference table = getTable(); - - if (table != null) { - builder.add(DisplayData.item("table", toTableSpec(table)) - .withLabel("Table")); - } - builder + .addIfNotNull(DisplayData.item("table", displayTable(getTableProvider())) + .withLabel("Table")) .addIfNotNull(DisplayData.item("query", query) .withLabel("Query")) .addIfNotNull(DisplayData.item("flattenResults", flattenResults) @@ -790,10 +819,10 @@ public void populateDisplayData(DisplayData.Builder builder) { if (Strings.isNullOrEmpty(table.get().getProjectId())) { // If user does not specify a project we assume the table to be located in // the default project. - TableReference ref = table.get(); - ref.setProjectId(bqOptions.getProject()); + TableReference tableRef = table.get(); + tableRef.setProjectId(bqOptions.getProject()); return NestedValueProvider.of(StaticValueProvider.of( - toJsonString(ref)), new JsonTableRefToTableRef()); + toJsonString(tableRef)), new JsonTableRefToTableRef()); } return table; } @@ -1567,6 +1596,11 @@ public static Bound to(String tableSpec) { return new Bound().to(tableSpec); } + /** Creates a write transformation for the given table. */ + public static Bound to(ValueProvider tableSpec) { + return new Bound().to(tableSpec); + } + /** Creates a write transformation for the given table. */ public static Bound to(TableReference table) { return new Bound().to(table); @@ -1610,6 +1644,13 @@ public static Bound withSchema(TableSchema schema) { return new Bound().withSchema(schema); } + /** + * Like {@link #withSchema(TableSchema)}, but with a {@link ValueProvider}. + */ + public static Bound withSchema(ValueProvider schema) { + return new Bound().withSchema(schema); + } + /** Creates a write transformation with the specified options for creating the table. */ public static Bound withCreateDisposition(CreateDisposition disposition) { return new Bound().withCreateDisposition(disposition); @@ -1645,12 +1686,12 @@ public static class Bound extends PTransform, PDone> { // It sets to {@code Integer.MAX_VALUE} to block until the BigQuery job finishes. static final int LOAD_JOB_POLL_MAX_RETRIES = Integer.MAX_VALUE; - @Nullable final String jsonTableRef; + @Nullable final ValueProvider jsonTableRef; @Nullable final SerializableFunction tableRefFunction; // Table schema. The schema is required only if the table does not exist. - @Nullable final String jsonSchema; + @Nullable final ValueProvider jsonSchema; // Options for creating the table. Valid values are CREATE_IF_NEEDED and // CREATE_NEVER. @@ -1697,9 +1738,9 @@ public Bound() { null /* bigQueryServices */); } - private Bound(String name, @Nullable String jsonTableRef, + private Bound(String name, @Nullable ValueProvider jsonTableRef, @Nullable SerializableFunction tableRefFunction, - @Nullable String jsonSchema, + @Nullable ValueProvider jsonSchema, CreateDisposition createDisposition, WriteDisposition writeDisposition, boolean validate, @Nullable BigQueryServices bigQueryServices) { super(name); @@ -1729,7 +1770,8 @@ public Bound named(String name) { *

            Does not modify this object. */ public Bound to(String tableSpec) { - return to(parseTableSpec(tableSpec)); + return toTableRef(NestedValueProvider.of( + StaticValueProvider.of(tableSpec), new TableSpecToTableRef())); } /** @@ -1738,8 +1780,7 @@ public Bound to(String tableSpec) { *

            Does not modify this object. */ public Bound to(TableReference table) { - return new Bound(name, toJsonString(table), tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, bigQueryServices); + return to(StaticValueProvider.of(toTableSpec(table))); } /** @@ -1756,6 +1797,28 @@ public Bound to( return toTableReference(new TranslateTableSpecFunction(tableSpecFunction)); } + /** + * Returns a copy of this write transformation, but writing to the specified table. Refer to + * {@link #parseTableSpec(String)} for the specification format. + * + *

            Does not modify this object. + */ + public Bound to(ValueProvider tableSpec) { + return toTableRef(NestedValueProvider.of(tableSpec, new TableSpecToTableRef())); + } + + /** + * Returns a copy of this write transformation, but writing to the specified table. + * + *

            Does not modify this object. + */ + private Bound toTableRef(ValueProvider table) { + return new Bound(name, + NestedValueProvider.of(table, new TableRefToJson()), + tableRefFunction, jsonSchema, createDisposition, + writeDisposition, validate, bigQueryServices); + } + /** * Returns a copy of this write transformation, but using the specified function to determine * which table to write to for each window. @@ -1778,7 +1841,17 @@ public Bound toTableReference( *

            Does not modify this object. */ public Bound withSchema(TableSchema schema) { - return new Bound(name, jsonTableRef, tableRefFunction, toJsonString(schema), + return new Bound(name, jsonTableRef, tableRefFunction, + StaticValueProvider.of(toJsonString(schema)), + createDisposition, writeDisposition, validate, bigQueryServices); + } + + /** + * Like {@link #withSchema(TableSchema)}, but with a {@link ValueProvider}. + */ + public Bound withSchema(ValueProvider schema) { + return new Bound(name, jsonTableRef, tableRefFunction, + NestedValueProvider.of(schema, new TableSchemaToJsonSchema()), createDisposition, writeDisposition, validate, bigQueryServices); } @@ -1860,7 +1933,7 @@ public void validate(PCollection input) { // The user specified a table. if (jsonTableRef != null && validate) { - TableReference table = getTableWithDefaultProject(options); + TableReference table = getTableWithDefaultProject(options).get(); // Check for destination table presence and emptiness for early failure notification. // Note that a presence check can fail when the table or dataset is created by an earlier @@ -1915,10 +1988,12 @@ public PDone apply(PCollection input) { // In a streaming job, or when a tablespec function is defined, we use StreamWithDeDup // and BigQuery's streaming import API. if (options.isStreaming() || tableRefFunction != null) { - return input.apply(new StreamWithDeDup(getTable(), tableRefFunction, getSchema())); + return input.apply(new StreamWithDeDup(getTable(), tableRefFunction, + NestedValueProvider.of(jsonSchema, new JsonSchemaToTableSchema()))); + } - TableReference table = getTableWithDefaultProject(options); + ValueProvider table = getTableWithDefaultProject(options); String jobIdToken = "beam_job_" + randomUUIDString(); String tempLocation = options.getTempLocation(); @@ -1969,7 +2044,7 @@ public PDone apply(PCollection input) { bqServices, jobIdToken, tempFilePrefix, - toJsonString(table), + NestedValueProvider.of(table, new TableRefToJson()), jsonSchema, WriteDisposition.WRITE_EMPTY, CreateDisposition.CREATE_IF_NEEDED))); @@ -1980,7 +2055,7 @@ public PDone apply(PCollection input) { .of(new WriteRename( bqServices, jobIdToken, - toJsonString(table), + NestedValueProvider.of(table, new TableRefToJson()), writeDisposition, createDisposition, tempTablesView)) @@ -1994,7 +2069,7 @@ public PDone apply(PCollection input) { bqServices, jobIdToken, tempFilePrefix, - toJsonString(table), + NestedValueProvider.of(table, new TableRefToJson()), jsonSchema, writeDisposition, createDisposition))); @@ -2091,7 +2166,8 @@ public WriteDisposition getWriteDisposition() { /** Returns the table schema. */ public TableSchema getSchema() { - return fromJsonString(jsonSchema, TableSchema.class); + return fromJsonString( + jsonSchema == null ? null : jsonSchema.get(), TableSchema.class); } /** @@ -2099,20 +2175,32 @@ public TableSchema getSchema() { * *

            If the table's project is not specified, use the executing project. */ - @Nullable private TableReference getTableWithDefaultProject(BigQueryOptions bqOptions) { - TableReference table = getTable(); - if (table != null && Strings.isNullOrEmpty(table.getProjectId())) { + @Nullable private ValueProvider getTableWithDefaultProject( + BigQueryOptions bqOptions) { + ValueProvider table = getTable(); + if (table == null) { + return table; + } + if (!table.isAccessible()) { + LOG.info("Using a dynamic value for table input. This must contain a project" + + " in the table reference: {}", table); + return table; + } + if (Strings.isNullOrEmpty(table.get().getProjectId())) { // If user does not specify a project we assume the table to be located in // the default project. - table.setProjectId(bqOptions.getProject()); + TableReference tableRef = table.get(); + tableRef.setProjectId(bqOptions.getProject()); + return NestedValueProvider.of(StaticValueProvider.of( + toJsonString(tableRef)), new JsonTableRefToTableRef()); } return table; } /** Returns the table reference, or {@code null}. */ @Nullable - public TableReference getTable() { - return fromJsonString(jsonTableRef, TableReference.class); + public ValueProvider getTable() { + return NestedValueProvider.of(jsonTableRef, new JsonTableRefToTableRef()); } /** Returns {@code true} if table validation is enabled. */ @@ -2237,8 +2325,8 @@ static class WriteTables extends DoFn>>, String> private final BigQueryServices bqServices; private final String jobIdToken; private final String tempFilePrefix; - private final String jsonTableRef; - private final String jsonSchema; + private final ValueProvider jsonTableRef; + private final ValueProvider jsonSchema; private final WriteDisposition writeDisposition; private final CreateDisposition createDisposition; @@ -2247,8 +2335,8 @@ public WriteTables( BigQueryServices bqServices, String jobIdToken, String tempFilePrefix, - String jsonTableRef, - String jsonSchema, + ValueProvider jsonTableRef, + ValueProvider jsonSchema, WriteDisposition writeDisposition, CreateDisposition createDisposition) { this.singlePartition = singlePartition; @@ -2265,7 +2353,7 @@ public WriteTables( public void processElement(ProcessContext c) throws Exception { List partition = Lists.newArrayList(c.element().getValue()).get(0); String jobIdPrefix = String.format(jobIdToken + "_%05d", c.element().getKey()); - TableReference ref = fromJsonString(jsonTableRef, TableReference.class); + TableReference ref = fromJsonString(jsonTableRef.get(), TableReference.class); if (!singlePartition) { ref.setTableId(jobIdPrefix); } @@ -2274,7 +2362,8 @@ public void processElement(ProcessContext c) throws Exception { bqServices.getJobService(c.getPipelineOptions().as(BigQueryOptions.class)), jobIdPrefix, ref, - fromJsonString(jsonSchema, TableSchema.class), + fromJsonString( + jsonSchema == null ? null : jsonSchema.get(), TableSchema.class), partition, writeDisposition, createDisposition); @@ -2370,7 +2459,7 @@ public void populateDisplayData(DisplayData.Builder builder) { static class WriteRename extends DoFn { private final BigQueryServices bqServices; private final String jobIdToken; - private final String jsonTableRef; + private final ValueProvider jsonTableRef; private final WriteDisposition writeDisposition; private final CreateDisposition createDisposition; private final PCollectionView> tempTablesView; @@ -2378,7 +2467,7 @@ static class WriteRename extends DoFn { public WriteRename( BigQueryServices bqServices, String jobIdToken, - String jsonTableRef, + ValueProvider jsonTableRef, WriteDisposition writeDisposition, CreateDisposition createDisposition, PCollectionView> tempTablesView) { @@ -2406,7 +2495,7 @@ public void processElement(ProcessContext c) throws Exception { copy( bqServices.getJobService(c.getPipelineOptions().as(BigQueryOptions.class)), jobIdToken, - fromJsonString(jsonTableRef, TableReference.class), + fromJsonString(jsonTableRef.get(), TableReference.class), tempTables, writeDisposition, createDisposition); @@ -2542,7 +2631,7 @@ private static void verifyTablePresence(BigQueryOptions options, TableReference private static class StreamingWriteFn extends DoFn, TableRowInfo>, Void> { /** TableSchema in JSON. Use String to make the class Serializable. */ - private final String jsonTableSchema; + private final ValueProvider jsonTableSchema; /** JsonTableRows to accumulate BigQuery rows in order to batch writes. */ private transient Map> tableRows; @@ -2560,8 +2649,9 @@ private static class StreamingWriteFn createAggregator("ByteCount", new Sum.SumLongFn()); /** Constructor. */ - StreamingWriteFn(TableSchema schema) { - jsonTableSchema = toJsonString(schema); + StreamingWriteFn(ValueProvider schema) { + this.jsonTableSchema = + NestedValueProvider.of(schema, new TableSchemaToJsonSchema()); } /** Prepares a target BigQuery table. */ @@ -2614,7 +2704,8 @@ public TableReference getOrCreateTable(BigQueryOptions options, String tableSpec // check again. This check isn't needed for correctness, but we add it to prevent // every thread from attempting a create and overwhelming our BigQuery quota. if (!createdTables.contains(tableSpec)) { - TableSchema tableSchema = JSON_FACTORY.fromString(jsonTableSchema, TableSchema.class); + TableSchema tableSchema = JSON_FACTORY.fromString( + jsonTableSchema.get(), TableSchema.class); Bigquery client = Transport.newBigQueryClient(options).build(); BigQueryTableInserter inserter = new BigQueryTableInserter(client); inserter.getOrCreateTable(tableReference, Write.WriteDisposition.WRITE_APPEND, @@ -2770,7 +2861,7 @@ private static class TagWithUniqueIdsAndTable extends DoFn, TableRowInfo>> implements DoFn.RequiresWindowAccess { /** TableSpec to write to. */ - private final String tableSpec; + private final ValueProvider tableSpec; /** User function mapping windows to {@link TableReference} in JSON. */ private final SerializableFunction tableRefFunction; @@ -2778,15 +2869,16 @@ private static class TagWithUniqueIdsAndTable private transient String randomUUID; private transient long sequenceNo = 0L; - TagWithUniqueIdsAndTable(BigQueryOptions options, TableReference table, + TagWithUniqueIdsAndTable(BigQueryOptions options, + ValueProvider table, SerializableFunction tableRefFunction) { checkArgument(table == null ^ tableRefFunction == null, "Exactly one of table or tableRefFunction should be set"); if (table != null) { - if (table.getProjectId() == null) { - table.setProjectId(options.as(BigQueryOptions.class).getProject()); + if (table.isAccessible() && table.get().getProjectId() == null) { + table.get().setProjectId(options.as(BigQueryOptions.class).getProject()); } - this.tableSpec = toTableSpec(table); + this.tableSpec = NestedValueProvider.of(table, new TableRefToTableSpec()); } else { tableSpec = null; } @@ -2825,7 +2917,7 @@ public void populateDisplayData(DisplayData.Builder builder) { private String tableSpecFromWindow(BigQueryOptions options, BoundedWindow window) { if (tableSpec != null) { - return tableSpec; + return tableSpec.get(); } else { TableReference table = tableRefFunction.apply(window); if (table.getProjectId() == null) { @@ -2843,14 +2935,14 @@ private String tableSpecFromWindow(BigQueryOptions options, BoundedWindow window * it leverages BigQuery best effort de-dup mechanism. */ private static class StreamWithDeDup extends PTransform, PDone> { - private final transient TableReference tableReference; + private final transient ValueProvider tableReference; private final SerializableFunction tableRefFunction; - private final transient TableSchema tableSchema; + private final transient ValueProvider tableSchema; /** Constructor. */ - StreamWithDeDup(TableReference tableReference, + StreamWithDeDup(ValueProvider tableReference, SerializableFunction tableRefFunction, - TableSchema tableSchema) { + ValueProvider tableSchema) { this.tableReference = tableReference; this.tableRefFunction = tableRefFunction; this.tableSchema = tableSchema; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index c350b038bf..d5b40a52b8 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -2293,7 +2293,7 @@ private void translateWriteHelper( "BigQueryIO is specified to use streaming write in batch mode."); } - TableReference table = originalTransform.getTable(); + TableReference table = originalTransform.getTable().get(); // Actual translation. context.addStep(transform, "ParallelWrite"); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index d6796fe598..b9d79adace 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -56,6 +56,7 @@ import com.google.cloud.dataflow.sdk.coders.VarLongCoder; import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryQuerySource; import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryTableSource; +import com.google.cloud.dataflow.sdk.io.BigQueryIO.JsonSchemaToTableSchema; import com.google.cloud.dataflow.sdk.io.BigQueryIO.PassThroughThenCleanup; import com.google.cloud.dataflow.sdk.io.BigQueryIO.PassThroughThenCleanup.CleanupOperation; import com.google.cloud.dataflow.sdk.io.BigQueryIO.Status; @@ -70,6 +71,8 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; +import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.testing.DataflowAssert; import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; @@ -440,9 +443,9 @@ private void checkWriteObjectWithValidate( BigQueryIO.Write.Bound bound, String project, String dataset, String table, TableSchema schema, CreateDisposition createDisposition, WriteDisposition writeDisposition, boolean validate) { - assertEquals(project, bound.getTable().getProjectId()); - assertEquals(dataset, bound.getTable().getDatasetId()); - assertEquals(table, bound.getTable().getTableId()); + assertEquals(project, bound.getTable().get().getProjectId()); + assertEquals(dataset, bound.getTable().get().getDatasetId()); + assertEquals(table, bound.getTable().get().getTableId()); assertEquals(schema, bound.getSchema()); assertEquals(createDisposition, bound.createDisposition); assertEquals(writeDisposition, bound.writeDisposition); @@ -1542,8 +1545,8 @@ public void testWriteTables() throws Exception { fakeBqServices, jobIdToken, tempFilePrefix, - jsonTable, - jsonSchema, + StaticValueProvider.of(jsonTable), + StaticValueProvider.of(jsonSchema), WriteDisposition.WRITE_EMPTY, CreateDisposition.CREATE_IF_NEEDED); @@ -1617,7 +1620,7 @@ public void testWriteRename() throws Exception { WriteRename writeRename = new WriteRename( fakeBqServices, jobIdToken, - jsonTable, + StaticValueProvider.of(jsonTable), WriteDisposition.WRITE_EMPTY, CreateDisposition.CREATE_IF_NEEDED, tempTablesView); @@ -1658,6 +1661,65 @@ public void testRemoveTemporaryTables() throws Exception { logged.verifyNotLogged("Failed to delete the table " + toJsonString(tableRefs.get(2))); } + /** Test options. **/ + public interface RuntimeTestOptions extends PipelineOptions { + ValueProvider getInputTable(); + void setInputTable(ValueProvider value); + + ValueProvider getInputQuery(); + void setInputQuery(ValueProvider value); + + ValueProvider getOutputTable(); + void setOutputTable(ValueProvider value); + + ValueProvider getOutputSchema(); + void setOutputSchema(ValueProvider value); + } + + @Test + public void testRuntimeOptionsNotCalledInApplyInputTable() { + RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + bqOptions.setTempLocation("gs://testbucket/testdir"); + Pipeline pipeline = TestPipeline.create(options); + BigQueryIO.Read.Bound read = BigQueryIO.Read.from( + options.getInputTable()).withoutValidation(); + pipeline.apply(read); + // Test that this doesn't throw. + DisplayData.from(read); + } + + @Test + public void testRuntimeOptionsNotCalledInApplyInputQuery() { + RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + bqOptions.setTempLocation("gs://testbucket/testdir"); + Pipeline pipeline = TestPipeline.create(options); + BigQueryIO.Read.Bound read = BigQueryIO.Read.fromQuery( + options.getInputQuery()).withoutValidation(); + pipeline.apply(read); + // Test that this doesn't throw. + DisplayData.from(read); + } + + @Test + public void testRuntimeOptionsNotCalledInApplyOutput() { + RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + bqOptions.setTempLocation("gs://testbucket/testdir"); + Pipeline pipeline = TestPipeline.create(options); + BigQueryIO.Write.Bound write = BigQueryIO.Write + .to(options.getOutputTable()) + .withSchema(NestedValueProvider.of( + options.getOutputSchema(), new JsonSchemaToTableSchema())) + .withoutValidation(); + pipeline + .apply(Create.of()) + .apply(write); + // Test that this doesn't throw. + DisplayData.from(write); + } + private static void testNumFiles(File tempDir, int expectedNumFiles) { assertEquals(expectedNumFiles, tempDir.listFiles(new FileFilter() { @Override From 929ac382ffd8d2ebaa884c8a70245e2eeced1bb0 Mon Sep 17 00:00:00 2001 From: Scott Wegner Date: Wed, 14 Dec 2016 16:48:58 -0800 Subject: [PATCH 647/751] Fail to split in FileBasedSource if filePattern expands to empty. (#509) Typically, input file patterns are validated during Pipeline construction, but standard Read transforms include an option to disable validation. This is generally useful but can lead to cases where a Pipeline executes successfully with empty inputs. This changes the behavior to fail execution on empty file-based inputs even when validation is disabled. (cherry picked from commit 9fc9d66212bf26087622ad6e042db982d5232c55) --- .../cloud/dataflow/sdk/io/FileBasedSource.java | 6 +++++- .../cloud/dataflow/sdk/io/FileBasedSourceTest.java | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java index ea67a9e22c..4fb996ffa0 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java @@ -316,7 +316,11 @@ public final List> splitIntoBundles( try { checkState(fileOrPatternSpec.isAccessible(), "Bundle splitting should only happen at execution time."); - for (final String file : FileBasedSource.expandFilePattern(fileOrPatternSpec.get())) { + Collection expandedFiles = + FileBasedSource.expandFilePattern(fileOrPatternSpec.get()); + checkArgument(!expandedFiles.isEmpty(), + "Unable to find any files matching %s", fileOrPatternSpec.get()); + for (final String file : expandedFiles) { futures.add(createFutureForFileSplit(file, desiredBundleSizeBytes, options, service)); } List> splitResults = diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java index 33a9212034..508e41a9b7 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java @@ -42,6 +42,7 @@ import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -70,6 +71,7 @@ public class FileBasedSourceTest { Random random = new Random(0L); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); + @Rule public ExpectedException thrown = ExpectedException.none(); /** * If {@code splitHeader} is null, this is just a simple line-based reader. Otherwise, the file is @@ -414,6 +416,16 @@ public void testSplittingUsingFullThreadPool() throws Exception { assertEquals(numFiles, splits.size()); } + @Test + public void testSplittingFailsOnEmptyFileExpansion() throws Exception { + PipelineOptions options = PipelineOptionsFactory.create(); + String missingFilePath = tempFolder.newFolder().getAbsolutePath() + "/missing.txt"; + TestFileBasedSource source = new TestFileBasedSource(missingFilePath, Long.MAX_VALUE, null); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(String.format("Unable to find any files matching %s", missingFilePath)); + source.splitIntoBundles(1234, options); + } + @Test public void testFractionConsumedWhenReadingFilepattern() throws IOException { List data1 = createStringDataset(3, 1000); From 68b4f5ce69b271d677dc3b9dbacc6bffa08cf5ed Mon Sep 17 00:00:00 2001 From: Vikas Kedigehalli Date: Wed, 14 Dec 2016 18:59:33 -0800 Subject: [PATCH 648/751] Allow empty string value for ValueProvider types. (#506) Backport of apache/incubator-beam#1580 --- .../sdk/options/PipelineOptionsFactory.java | 113 ++++++--- .../options/PipelineOptionsFactoryTest.java | 222 +++++++++++++++--- 2 files changed, 279 insertions(+), 56 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java index 160e27af23..54e4d87a7d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java @@ -64,7 +64,6 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.ArrayList; @@ -1495,13 +1494,7 @@ public boolean apply(@Nullable String input) { throw new IllegalArgumentException(msg, e); } } - } else if ((returnType.isArray() && (SIMPLE_TYPES.contains(returnType.getComponentType()) - || returnType.getComponentType().isEnum())) - || Collection.class.isAssignableFrom(returnType) - || (returnType.equals(ValueProvider.class) - && MAPPER.getTypeFactory().constructType( - ((ParameterizedType) method.getGenericReturnType()) - .getActualTypeArguments()[0]).isCollectionLikeType())) { + } else if (isCollectionOrArrayOfAllowedTypes(returnType, type)) { // Split any strings with "," List values = FluentIterable.from(entry.getValue()) .transformAndConcat(new Function>() { @@ -1509,33 +1502,23 @@ public boolean apply(@Nullable String input) { public Iterable apply(String input) { return Arrays.asList(input.split(",")); } - }).toList(); - - if (returnType.isArray() && !returnType.getComponentType().equals(String.class) - || Collection.class.isAssignableFrom(returnType) - || returnType.equals(ValueProvider.class)) { - for (String value : values) { - checkArgument(!value.isEmpty(), - "Empty argument value is only allowed for String, String Array, " - + "and Collections of Strings, but received: %s", - method.getGenericReturnType()); - } + }).toList(); + + if (values.contains("")) { + checkEmptyStringAllowed(returnType, type, method.getGenericReturnType().toString()); } convertedOptions.put(entry.getKey(), MAPPER.convertValue(values, type)); - } else if (SIMPLE_TYPES.contains(returnType) || returnType.isEnum() - || returnType.equals(ValueProvider.class)) { + } else if (isSimpleType(returnType, type)) { String value = Iterables.getOnlyElement(entry.getValue()); - checkArgument(returnType.equals(String.class) || !value.isEmpty(), - "Empty argument value is only allowed for String, String Array, " - + "and Collections of Strings, but received: %s", - method.getGenericReturnType()); + if (value.isEmpty()) { + checkEmptyStringAllowed(returnType, type, method.getGenericReturnType().toString()); + } convertedOptions.put(entry.getKey(), MAPPER.convertValue(value, type)); } else { String value = Iterables.getOnlyElement(entry.getValue()); - checkArgument(returnType.equals(String.class) || !value.isEmpty(), - "Empty argument value is only allowed for String, String Array, " - + "and Collections of Strings, but received: %s", - method.getGenericReturnType()); + if (value.isEmpty()) { + checkEmptyStringAllowed(returnType, type, method.getGenericReturnType().toString()); + } try { convertedOptions.put(entry.getKey(), MAPPER.readValue(value, type)); } catch (IOException e) { @@ -1553,4 +1536,76 @@ public Iterable apply(String input) { } return convertedOptions; } + + /** + * Returns true if the given type is one of {@code SIMPLE_TYPES} or an enum, or if the given type + * is a {@link ValueProvider ValueProvider<T>} and {@code T} is one of {@code SIMPLE_TYPES} + * or an enum. + */ + private static boolean isSimpleType(Class type, JavaType genericType) { + Class unwrappedType = type.equals(ValueProvider.class) + ? genericType.containedType(0).getRawClass() : type; + return SIMPLE_TYPES.contains(unwrappedType) || unwrappedType.isEnum(); + } + + /** + * Returns true if the given type is an array or {@link Collection} of {@code SIMPLE_TYPES} or + * enums, or if the given type is a {@link ValueProvider ValueProvider<T>} and {@code T} is + * one of an array or {@link Collection} of {@code SIMPLE_TYPES} or enums. + */ + private static boolean isCollectionOrArrayOfAllowedTypes(Class type, JavaType genericType) { + JavaType containerType = type.equals(ValueProvider.class) + ? genericType.containedType(0) : genericType; + + // Check if it is an array of simple types or enum. + if (containerType.getRawClass().isArray() + && (SIMPLE_TYPES.contains(containerType.getRawClass().getComponentType()) + || containerType.getRawClass().getComponentType().isEnum())) { + return true; + } + // Check if it is Collection of simple types or enum. + if (Collection.class.isAssignableFrom(containerType.getRawClass())) { + JavaType innerType = containerType.containedType(0); + // Note that raw types are allowed, hence the null check. + if (innerType == null || SIMPLE_TYPES.contains(innerType.getRawClass()) + || innerType.getRawClass().isEnum()) { + return true; + } + } + return false; + } + + /** + * Ensures that empty string value is allowed for a given type. + * + *

            Empty strings are only allowed for {@link String}, {@link String String[]}, + * {@link Collection Collection<String>}, or {@link ValueProvider ValueProvider<T>} + * and {@code T} is of type {@link String}, {@link String String[]}, + * {@link Collection Collection<String>}. + * + * @param type class object for the type under check. + * @param genericType complete type information for the type under check. + * @param genericTypeName a string representation of the complete type information. + */ + private static void checkEmptyStringAllowed(Class type, JavaType genericType, + String genericTypeName) { + JavaType unwrappedType = type.equals(ValueProvider.class) + ? genericType.containedType(0) : genericType; + + Class containedType = unwrappedType.getRawClass(); + if (unwrappedType.getRawClass().isArray()) { + containedType = unwrappedType.getRawClass().getComponentType(); + } else if (Collection.class.isAssignableFrom(unwrappedType.getRawClass())) { + JavaType innerType = unwrappedType.containedType(0); + // Note that raw types are allowed, hence the null check. + containedType = innerType == null ? String.class : innerType.getRawClass(); + } + if (!containedType.equals(String.class)) { + String msg = String.format("Empty argument value is only allowed for String, String Array, " + + "Collections of Strings or any of these types in a parameterized ValueProvider, " + + "but received: %s", + genericTypeName); + throw new IllegalArgumentException(msg); + } + } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java index 7b1cfc6217..c0ddac59a4 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java @@ -519,9 +519,7 @@ public void testEmptyValueNotAllowed() { String[] args = new String[] { "--byte="}; expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collections" - + " of Strings"); + expectedException.expectMessage(emptyStringErrorMessage()); PipelineOptionsFactory.fromArgs(args).as(Primitives.class); } @@ -556,6 +554,12 @@ public interface Objects extends PipelineOptions { void setClassValue(Class value); TestEnum getEnum(); void setEnum(TestEnum value); + ValueProvider getStringValue(); + void setStringValue(ValueProvider value); + ValueProvider getLongValue(); + void setLongValue(ValueProvider value); + ValueProvider getEnumValue(); + void setEnumValue(ValueProvider value); } @Test @@ -572,7 +576,10 @@ public void testObjects() { "--string=stringValue", "--emptyString=", "--classValue=" + PipelineOptionsFactoryTest.class.getName(), - "--enum=" + TestEnum.Value}; + "--enum=" + TestEnum.Value, + "--stringValue=beam", + "--longValue=12389049585840", + "--enumValue=" + TestEnum.Value}; Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); assertTrue(options.getBoolean()); @@ -587,6 +594,41 @@ public void testObjects() { assertTrue(options.getEmptyString().isEmpty()); assertEquals(PipelineOptionsFactoryTest.class, options.getClassValue()); assertEquals(TestEnum.Value, options.getEnum()); + assertEquals("beam", options.getStringValue().get()); + assertEquals(Long.valueOf(12389049585840L), options.getLongValue().get()); + assertEquals(TestEnum.Value, options.getEnumValue().get()); + } + + @Test + public void testStringValueProvider() { + String[] args = new String[] {"--stringValue=beam"}; + String[] emptyArgs = new String[] { "--stringValue="}; + Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); + assertEquals("beam", options.getStringValue().get()); + options = PipelineOptionsFactory.fromArgs(emptyArgs).as(Objects.class); + assertEquals("", options.getStringValue().get()); + } + + @Test + public void testLongValueProvider() { + String[] args = new String[] {"--longValue=12345678762"}; + String[] emptyArgs = new String[] {"--longValue="}; + Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); + assertEquals(Long.valueOf(12345678762L), options.getLongValue().get()); + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(emptyStringErrorMessage()); + PipelineOptionsFactory.fromArgs(emptyArgs).as(Objects.class); + } + + @Test + public void testEnumValueProvider() { + String[] args = new String[] {"--enumValue=" + TestEnum.Value}; + String[] emptyArgs = new String[] {"--enumValue="}; + Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); + assertEquals(TestEnum.Value, options.getEnumValue().get()); + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(emptyStringErrorMessage()); + PipelineOptionsFactory.fromArgs(emptyArgs).as(Objects.class); } /** A test class for verifying JSON -> Object conversion. */ @@ -606,17 +648,23 @@ interface ComplexTypes extends PipelineOptions { ComplexType getObject(); void setObject(ComplexType value); + + ValueProvider getObjectValue(); + void setObjectValue(ValueProvider value); } @Test public void testComplexTypes() { String[] args = new String[] { "--map={\"key\":\"value\",\"key2\":\"value2\"}", - "--object={\"key\":\"value\",\"key2\":\"value2\"}"}; + "--object={\"key\":\"value\",\"key2\":\"value2\"}", + "--objectValue={\"key\":\"value\",\"key2\":\"value2\"}"}; ComplexTypes options = PipelineOptionsFactory.fromArgs(args).as(ComplexTypes.class); assertEquals(ImmutableMap.of("key", "value", "key2", "value2"), options.getMap()); assertEquals("value", options.getObject().value); assertEquals("value2", options.getObject().value2); + assertEquals("value", options.getObjectValue().get().value); + assertEquals("value2", options.getObjectValue().get().value2); } @Test @@ -649,6 +697,12 @@ public interface Arrays extends PipelineOptions { void setClassValue(Class[] value); TestEnum[] getEnum(); void setEnum(TestEnum[] value); + ValueProvider getStringValue(); + void setStringValue(ValueProvider value); + ValueProvider getLongValue(); + void setLongValue(ValueProvider value); + ValueProvider getEnumValue(); + void setEnumValue(ValueProvider value); } @Test @@ -682,7 +736,13 @@ public void testArrays() { "--classValue=" + PipelineOptionsFactory.class.getName(), "--classValue=" + PipelineOptionsFactoryTest.class.getName(), "--enum=" + TestEnum.Value, - "--enum=" + TestEnum.Value2}; + "--enum=" + TestEnum.Value2, + "--stringValue=abc", + "--stringValue=beam", + "--longValue=123890123890", + "--longValue=123890123891", + "--enumValue=" + TestEnum.Value, + "--enumValue=" + TestEnum.Value2}; Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); boolean[] bools = options.getBoolean(); @@ -699,6 +759,10 @@ public void testArrays() { PipelineOptionsFactoryTest.class}, options.getClassValue()); assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, options.getEnum()); + assertArrayEquals(new String[] {"abc", "beam"}, options.getStringValue().get()); + assertArrayEquals(new Long[] {123890123890L, 123890123891L}, options.getLongValue().get()); + assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, + options.getEnumValue().get()); } @Test @@ -728,9 +792,7 @@ public void testEmptyInStringArraysWithCommaList() { @Test public void testEmptyInNonStringArrays() { expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collections" - + " of Strings"); + expectedException.expectMessage(emptyStringErrorMessage()); String[] args = new String[] { "--boolean=true", @@ -743,15 +805,57 @@ public void testEmptyInNonStringArrays() { @Test public void testEmptyInNonStringArraysWithCommaList() { expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collections" - + " of Strings"); + expectedException.expectMessage(emptyStringErrorMessage()); String[] args = new String[] { "--int=1,,9"}; PipelineOptionsFactory.fromArgs(args).as(Arrays.class); } + @Test + public void testStringArrayValueProvider() { + String[] args = new String[] {"--stringValue=abc", "--stringValue=xyz"}; + String[] commaArgs = new String[]{"--stringValue=abc,xyz"}; + String[] emptyArgs = new String[] { "--stringValue=", "--stringValue="}; + Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); + assertArrayEquals(new String[]{"abc", "xyz"}, options.getStringValue().get()); + options = PipelineOptionsFactory.fromArgs(commaArgs).as(Arrays.class); + assertArrayEquals(new String[]{"abc", "xyz"}, options.getStringValue().get()); + options = PipelineOptionsFactory.fromArgs(emptyArgs).as(Arrays.class); + assertArrayEquals(new String[]{"", ""}, options.getStringValue().get()); + } + + @Test + public void testLongArrayValueProvider() { + String[] args = new String[] {"--longValue=12345678762", "--longValue=12345678763"}; + String[] commaArgs = new String[] {"--longValue=12345678762,12345678763"}; + String[] emptyArgs = new String[] {"--longValue=", "--longValue="}; + Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); + assertArrayEquals(new Long[] {12345678762L, 12345678763L}, options.getLongValue().get()); + options = PipelineOptionsFactory.fromArgs(commaArgs).as(Arrays.class); + assertArrayEquals(new Long[] {12345678762L, 12345678763L}, options.getLongValue().get()); + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(emptyStringErrorMessage()); + PipelineOptionsFactory.fromArgs(emptyArgs).as(Arrays.class); + } + + @Test + public void testEnumArrayValueProvider() { + String[] args = new String[] {"--enumValue=" + TestEnum.Value, + "--enumValue=" + TestEnum.Value2}; + String[] commaArgs = new String[] {"--enumValue=" + TestEnum.Value + "," + TestEnum.Value2}; + String[] emptyArgs = new String[] {"--enumValue="}; + Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); + assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, + options.getEnumValue().get()); + options = PipelineOptionsFactory.fromArgs(commaArgs).as(Arrays.class); + assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, + options.getEnumValue().get()); + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(emptyStringErrorMessage()); + PipelineOptionsFactory.fromArgs(emptyArgs).as(Arrays.class); + } + @Test public void testOutOfOrderArrays() { String[] args = new String[] { @@ -776,16 +880,27 @@ public interface Lists extends PipelineOptions { void setInteger(List value); List getList(); void setList(List value); + ValueProvider> getStringValue(); + void setStringValue(ValueProvider> value); + ValueProvider> getLongValue(); + void setLongValue(ValueProvider> value); + ValueProvider> getEnumValue(); + void setEnumValue(ValueProvider> value); } @Test public void testListRawDefaultsToString() { String[] manyArgs = new String[] {"--list=stringValue1", "--list=stringValue2", "--list=stringValue3"}; + String[] manyArgsWithEmptyString = + new String[] {"--list=stringValue1", "--list=", "--list=stringValue3"}; Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); assertEquals(ImmutableList.of("stringValue1", "stringValue2", "stringValue3"), options.getList()); + options = PipelineOptionsFactory.fromArgs(manyArgsWithEmptyString).as(Lists.class); + assertEquals(ImmutableList.of("stringValue1", "", "stringValue3"), + options.getList()); } @Test @@ -793,13 +908,15 @@ public void testListString() { String[] manyArgs = new String[] {"--string=stringValue1", "--string=stringValue2", "--string=stringValue3"}; String[] oneArg = new String[] {"--string=stringValue1"}; + String[] emptyArg = new String[] {"--string="}; Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); assertEquals(ImmutableList.of("stringValue1", "stringValue2", "stringValue3"), options.getString()); - options = PipelineOptionsFactory.fromArgs(oneArg).as(Lists.class); assertEquals(ImmutableList.of("stringValue1"), options.getString()); + options = PipelineOptionsFactory.fromArgs(emptyArg).as(Lists.class); + assertEquals(ImmutableList.of(""), options.getString()); } @Test @@ -819,10 +936,8 @@ public void testListInt() { assertEquals(ImmutableList.of(1), options.getInteger()); expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collections of Strings," - + " but received: java.util.List"); - options = PipelineOptionsFactory.fromArgs(missingArg).as(Lists.class); + expectedException.expectMessage(emptyStringErrorMessage("java.util.List")); + PipelineOptionsFactory.fromArgs(missingArg).as(Lists.class); } @Test @@ -851,6 +966,49 @@ public void testMixedShorthandAndLongStyleList() { options.getChar()); } + + @Test + public void testStringListValueProvider() { + String[] args = new String[] {"--stringValue=abc", "--stringValue=xyz"}; + String[] commaArgs = new String[]{"--stringValue=abc,xyz"}; + String[] emptyArgs = new String[] { "--stringValue=", "--stringValue="}; + Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); + assertEquals(ImmutableList.of("abc", "xyz"), options.getStringValue().get()); + options = PipelineOptionsFactory.fromArgs(commaArgs).as(Lists.class); + assertEquals(ImmutableList.of("abc", "xyz"), options.getStringValue().get()); + options = PipelineOptionsFactory.fromArgs(emptyArgs).as(Lists.class); + assertEquals(ImmutableList.of("", ""), options.getStringValue().get()); + } + + @Test + public void testLongListValueProvider() { + String[] args = new String[] {"--longValue=12345678762", "--longValue=12345678763"}; + String[] commaArgs = new String[] {"--longValue=12345678762,12345678763"}; + String[] emptyArgs = new String[] {"--longValue=", "--longValue="}; + Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); + assertEquals(ImmutableList.of(12345678762L, 12345678763L), options.getLongValue().get()); + options = PipelineOptionsFactory.fromArgs(commaArgs).as(Lists.class); + assertEquals(ImmutableList.of(12345678762L, 12345678763L), options.getLongValue().get()); + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(emptyStringErrorMessage()); + PipelineOptionsFactory.fromArgs(emptyArgs).as(Lists.class); + } + + @Test + public void testEnumListValueProvider() { + String[] args = new String[] {"--enumValue=" + TestEnum.Value, + "--enumValue=" + TestEnum.Value2}; + String[] commaArgs = new String[] {"--enumValue=" + TestEnum.Value + "," + TestEnum.Value2}; + String[] emptyArgs = new String[] {"--enumValue="}; + Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); + assertEquals(ImmutableList.of(TestEnum.Value, TestEnum.Value2), options.getEnumValue().get()); + options = PipelineOptionsFactory.fromArgs(commaArgs).as(Lists.class); + assertEquals(ImmutableList.of(TestEnum.Value, TestEnum.Value2), options.getEnumValue().get()); + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(emptyStringErrorMessage()); + PipelineOptionsFactory.fromArgs(emptyArgs).as(Lists.class); + } + @Test public void testSetASingularAttributeUsingAListThrowsAnError() { String[] args = new String[] { @@ -892,11 +1050,9 @@ public void testMapIntInt() { assertEquals(ImmutableMap.of(1, 1), options.getMap()); expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and " - + "Collections of Strings, but received: java.util.Map"); - options = PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); + expectedException.expectMessage(emptyStringErrorMessage( + "java.util.Map")); + PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); } @Test @@ -915,11 +1071,9 @@ public void testNestedMap() { options.getNestedMap()); expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Empty argument value is only allowed for String, String Array, and Collections of " - + "Strings, but received: java.util.Map>"); - options = PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); + expectedException.expectMessage(emptyStringErrorMessage( + "java.util.Map>")); + PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); } @Test @@ -1247,4 +1401,18 @@ public void run() { thread.join(); assertEquals(cl, classLoader[0]); } + + private String emptyStringErrorMessage() { + return emptyStringErrorMessage(null); + } + + private String emptyStringErrorMessage(String type) { + String msg = "Empty argument value is only allowed for String, String Array, " + + "Collections of Strings or any of these types in a parameterized ValueProvider"; + if (type != null) { + return String.format("%s, but received: %s", msg, type); + } else { + return msg; + } + } } From a9145ca48ccb598892e24d1b1bb3d918c8a3b442 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Thu, 15 Dec 2016 11:49:19 -0800 Subject: [PATCH 649/751] Fix handling of streaming BQ table --- .../main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 1db12bb15f..2f9bc20f8e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -2200,7 +2200,8 @@ public TableSchema getSchema() { /** Returns the table reference, or {@code null}. */ @Nullable public ValueProvider getTable() { - return NestedValueProvider.of(jsonTableRef, new JsonTableRefToTableRef()); + return jsonTableRef == null + ? null : NestedValueProvider.of(jsonTableRef, new JsonTableRefToTableRef()); } /** Returns {@code true} if table validation is enabled. */ From 13259dd9cfa3d7bf9fac2a83710d8a82184b4fb9 Mon Sep 17 00:00:00 2001 From: sammcveety Date: Thu, 15 Dec 2016 17:26:33 -0800 Subject: [PATCH 650/751] BigQueryIO: Fix error when project is not provided (#512) --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 19 +++++++++++++++---- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 2f9bc20f8e..ace18eff5e 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -385,7 +385,8 @@ public String apply(TableReference from) { } } - private static class TableSpecToTableRef + @VisibleForTesting + static class TableSpecToTableRef implements SerializableFunction { @Override public TableReference apply(String from) { @@ -2858,7 +2859,8 @@ private static class TableRowInfo { * a randomUUID is generated only once per bucket of data. The actual unique * id is created by concatenating this randomUUID with a sequential number. */ - private static class TagWithUniqueIdsAndTable + @VisibleForTesting + static class TagWithUniqueIdsAndTable extends DoFn, TableRowInfo>> implements DoFn.RequiresWindowAccess { /** TableSpec to write to. */ @@ -2876,8 +2878,12 @@ private static class TagWithUniqueIdsAndTable checkArgument(table == null ^ tableRefFunction == null, "Exactly one of table or tableRefFunction should be set"); if (table != null) { - if (table.isAccessible() && table.get().getProjectId() == null) { - table.get().setProjectId(options.as(BigQueryOptions.class).getProject()); + if (table.isAccessible() && Strings.isNullOrEmpty(table.get().getProjectId())) { + TableReference tableRef = table.get() + .setProjectId(options.as(BigQueryOptions.class).getProject()); + table = NestedValueProvider.of( + StaticValueProvider.of(toJsonString(tableRef)), + new JsonTableRefToTableRef()); } this.tableSpec = NestedValueProvider.of(table, new TableRefToTableSpec()); } else { @@ -2916,6 +2922,11 @@ public void populateDisplayData(DisplayData.Builder builder) { } } + @VisibleForTesting + ValueProvider getTableSpec() { + return tableSpec; + } + private String tableSpecFromWindow(BigQueryOptions options, BoundedWindow window) { if (tableSpec != null) { return tableSpec.get(); diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index b9d79adace..0f2064eb69 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -1720,6 +1721,19 @@ public void testRuntimeOptionsNotCalledInApplyOutput() { DisplayData.from(write); } + @Test + public void testTagWithUniqueIdsAndTableProjectNotNullWithNvp() { + BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); + bqOptions.setProject("project"); + BigQueryIO.TagWithUniqueIdsAndTable tag = + new BigQueryIO.TagWithUniqueIdsAndTable( + bqOptions, NestedValueProvider.of( + StaticValueProvider.of("data_set.table_name"), + new BigQueryIO.TableSpecToTableRef()), null); + TableReference table = BigQueryIO.parseTableSpec(tag.getTableSpec().get()); + assertNotNull(table.getProjectId()); + } + private static void testNumFiles(File tempDir, int expectedNumFiles) { assertEquals(expectedNumFiles, tempDir.listFiles(new FileFilter() { @Override From 8981893e799607bba87b4640d9f58ff63cb6a39e Mon Sep 17 00:00:00 2001 From: Mitch Shanklin Date: Fri, 16 Dec 2016 09:17:39 -0800 Subject: [PATCH 651/751] Some minor changes and fixes for sorter module (#508) Backport apache/incubator-beam#1327 Includes: * Limit max memory for ExternalSorter and BufferedExternalSorter to 2047 MB to prevent int overflow within Hadoop's sorting library * Fix int overflow for large memory values in InMemorySorter * Add note about estimated disk use to README.MD * Fix to make Hadoop's sorting library put all temp files under the specified directory * Have Hadoop clean up the temp directory on exit * Stop shading hadoop dependencies. Some context: ** The existing shading is broken (modules that depend on this one cannot use it successfully). ** Hadoop's use of reflection in several instances makes shading the dependency "in a good way" nearly impossible. It requires a couple of rather brittle hacks, and, for clients that depend on certain conflicting versions of hadoop these hacks can mean it doesn't meet its intended goal of preventing conflicts anyway. ** From what I can tell, there's no good way to shade this to make it universally usable, so leaving it unshaded seems like a reasonable default. ** Without shading Hadoop, this module can be successfully used from Beam's wordcount example (which actually does have pre-existing hadoop dependencies already). --- contrib/sorter/README.md | 2 +- contrib/sorter/pom.xml | 8 ++---- .../sorter/BufferedExternalSorter.java | 6 ++++- .../contrib/sorter/ExternalSorter.java | 15 ++++++++++- .../contrib/sorter/InMemorySorter.java | 26 +++++++++---------- .../sorter/BufferedExternalSorterTest.java | 16 ++++++++++++ .../contrib/sorter/ExternalSorterTest.java | 16 ++++++++++++ .../contrib/sorter/InMemorySorterTest.java | 8 ++++++ 8 files changed, 75 insertions(+), 22 deletions(-) diff --git a/contrib/sorter/README.md b/contrib/sorter/README.md index 29f45b8900..1f6c3a5d93 100644 --- a/contrib/sorter/README.md +++ b/contrib/sorter/README.md @@ -3,7 +3,7 @@ This module provides the SortValues transform, which takes a `PCollection>` is sorted on a single worker using local memory and disk. This means that `SortValues` may be a performance and/or scalability bottleneck when used in different pipelines. For example, users are discouraged from using `SortValues` on a `PCollection` of a single element to globally sort a large `PCollection`. +* Each `Iterable>` is sorted on a single worker using local memory and disk. This means that `SortValues` may be a performance and/or scalability bottleneck when used in different pipelines. For example, users are discouraged from using `SortValues` on a `PCollection` of a single element to globally sort a large `PCollection`. A (rough) estimate of the number of bytes of disk space utilized if sorting spills to disk is `numRecords * (numSecondaryKeyBytesPerRecord + numValueBytesPerRecord + 16) * 3`. ##Options * The user can customize the temporary location used if sorting requires spilling to disk and the maximum amount of memory to use by creating a custom instance of `BufferedExternalSorter.Options` to pass into `SortValues.create`. diff --git a/contrib/sorter/pom.xml b/contrib/sorter/pom.xml index 08ac2d9aa0..d9ffb65bd9 100644 --- a/contrib/sorter/pom.xml +++ b/contrib/sorter/pom.xml @@ -150,8 +150,6 @@ true - org.apache.hadoop:hadoop-mapreduce-client-core - org.apache.hadoop:hadoop-common com.google.guava:guava @@ -166,10 +164,6 @@ - - org.apache.hadoop - com.google.cloud.dataflow.repackaged.org.apache.hadoop - com.google.common com.google.cloud.dataflow.repackaged.com.google.common @@ -198,12 +192,14 @@ org.apache.hadoop hadoop-mapreduce-client-core ${hadoop.version} + provided org.apache.hadoop hadoop-common ${hadoop.version} + provided diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java index 1108eef2ad..d717f79ed7 100644 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java @@ -48,10 +48,14 @@ public String getTempLocation() { /** * Sets the size of the memory buffer in megabytes. This controls both the buffer for initial in - * memory sorting and the buffer used when external sorting. Must be greater than zero. + * memory sorting and the buffer used when external sorting. Must be greater than zero and less + * than 2048. */ public void setMemoryMB(int memoryMB) { checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); + // Hadoop's external sort stores the number of available memory bytes in an int, this prevents + // overflow + checkArgument(memoryMB < 2048, "memoryMB must be less than 2048"); this.memoryMB = memoryMB; } diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java index 8965b41926..80937ec9e3 100644 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java @@ -79,9 +79,15 @@ public String getTempLocation() { return tempLocation; } - /** Sets the size of the memory buffer in megabytes. */ + /** + * Sets the size of the memory buffer in megabytes. Must be greater than zero and less than + * 2048. + */ public void setMemoryMB(int memoryMB) { checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); + // Hadoop's external sort stores the number of available memory bytes in an int, this prevents + // integer overflow + checkArgument(memoryMB < 2048, "memoryMB must be less than 2048"); this.memoryMB = memoryMB; } @@ -134,6 +140,9 @@ private void initHadoopSorter() throws IOException { paths = new Path[] {new Path(tempDir, "test.seq")}; JobConf conf = new JobConf(); + // Sets directory for intermediate files created during merge of merge sort + conf.set("io.seqfile.local.dir", tempDir.toUri().getPath()); + writer = SequenceFile.createWriter( conf, @@ -143,6 +152,10 @@ private void initHadoopSorter() throws IOException { Writer.compression(CompressionType.NONE)); FileSystem fs = FileSystem.getLocal(conf); + // Directory has to exist for Hadoop to recognize it as deletable on exit + fs.mkdirs(tempDir); + fs.deleteOnExit(tempDir); + sorter = new SequenceFile.Sorter( fs, new BytesWritable.Comparator(), BytesWritable.class, BytesWritable.class, conf); diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java index e62fca4057..ac1b520f4e 100644 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java +++ b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java @@ -33,16 +33,16 @@ class InMemorySorter implements Sorter { /** {@code Options} contains configuration of the sorter. */ public static class Options implements Serializable { - private int memoryMB = 100; + private long memoryMB = 100; /** Sets the size of the memory buffer in megabytes. */ - public void setMemoryMB(int memoryMB) { + public void setMemoryMB(long memoryMB) { checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); this.memoryMB = memoryMB; } /** Returns the configured size of the memory buffer. */ - public int getMemoryMB() { + public long getMemoryMB() { return memoryMB; } } @@ -51,7 +51,7 @@ public int getMemoryMB() { private static final Comparator COMPARATOR = UnsignedBytes.lexicographicalComparator(); /** How many bytes per word in the running JVM. Assumes 64 bit/8 bytes if unknown. */ - private static final int NUM_BYTES_PER_WORD = getNumBytesPerWord(); + private static final long NUM_BYTES_PER_WORD = getNumBytesPerWord(); /** * Estimate of memory overhead per KV record in bytes not including memory associated with keys @@ -64,13 +64,13 @@ public int getMemoryMB() { *

          • Per-object overhead (JVM-specific, guessing 2 words * 3 objects) * */ - private static final int RECORD_MEMORY_OVERHEAD_ESTIMATE = 11 * NUM_BYTES_PER_WORD; + private static final long RECORD_MEMORY_OVERHEAD_ESTIMATE = 11 * NUM_BYTES_PER_WORD; /** Maximum size of the buffer in bytes. */ - private int maxBufferSize; + private long maxBufferSize; /** Current number of stored bytes. Including estimated overhead bytes. */ - private int numBytes; + private long numBytes; /** Whether sort has been called. */ private boolean sortCalled; @@ -80,7 +80,7 @@ public int getMemoryMB() { /** Private constructor. */ private InMemorySorter(Options options) { - maxBufferSize = options.getMemoryMB() * 1024 * 1024; + maxBufferSize = options.getMemoryMB() * 1024L * 1024L; } /** Create a new sorter from provided options. */ @@ -97,7 +97,7 @@ public void add(KV record) { public boolean addIfRoom(KV record) { checkState(!sortCalled, "Records can only be added before sort()"); - int recordBytes = estimateRecordBytes(record); + long recordBytes = estimateRecordBytes(record); if (roomInBuffer(numBytes + recordBytes, records.size() + 1)) { records.add(record); numBytes += recordBytes; @@ -129,7 +129,7 @@ public int compare(KV o1, KV o2) { * Estimate the number of additional bytes required to store this record. Including the key, the * value and any overhead for objects and references. */ - private int estimateRecordBytes(KV record) { + private long estimateRecordBytes(KV record) { return RECORD_MEMORY_OVERHEAD_ESTIMATE + record.getKey().length + record.getValue().length; } @@ -137,7 +137,7 @@ private int estimateRecordBytes(KV record) { * Check whether we have room to store the provided total number of bytes and total number of * records. */ - private boolean roomInBuffer(int numBytes, int numRecords) { + private boolean roomInBuffer(long numBytes, long numRecords) { // Collections.sort may allocate up to n/2 extra object references. // Also, ArrayList grows by a factor of 1.5x, so there might be up to n/2 null object // references in the backing array. @@ -151,11 +151,11 @@ private boolean roomInBuffer(int numBytes, int numRecords) { * Returns the number of bytes in a word according to the JVM. Defaults to 8 for 64 bit if answer * unknown. */ - private static int getNumBytesPerWord() { + private static long getNumBytesPerWord() { String bitsPerWord = System.getProperty("sun.arch.data.model"); try { - return Integer.parseInt(bitsPerWord) / 8; + return Long.parseLong(bitsPerWord) / 8; } catch (Exception e) { // Can't determine whether 32 or 64 bit, so assume 64 return 8; diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java index 954642a833..f43663c60b 100644 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java @@ -173,4 +173,20 @@ public void testNegativeMemory() throws Exception { BufferedExternalSorter.Options options = new BufferedExternalSorter.Options(); options.setMemoryMB(-1); } + + @Test + public void testZeroMemory() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be greater than zero"); + BufferedExternalSorter.Options options = new BufferedExternalSorter.Options(); + options.setMemoryMB(0); + } + + @Test + public void testMemoryTooLarge() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be less than 2048"); + BufferedExternalSorter.Options options = new BufferedExternalSorter.Options(); + options.setMemoryMB(2048); + } } diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java index 150ffbd633..6db3437379 100644 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java @@ -82,4 +82,20 @@ public void testNegativeMemory() throws Exception { ExternalSorter.Options options = new ExternalSorter.Options(); options.setMemoryMB(-1); } + + @Test + public void testZeroMemory() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be greater than zero"); + ExternalSorter.Options options = new ExternalSorter.Options(); + options.setMemoryMB(0); + } + + @Test + public void testMemoryTooLarge() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be less than 2048"); + ExternalSorter.Options options = new ExternalSorter.Options(); + options.setMemoryMB(2048); + } } diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java index 1c4e43fc1c..2865dfe203 100644 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java +++ b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java @@ -139,4 +139,12 @@ public void testNegativeMemory() throws Exception { InMemorySorter.Options options = new InMemorySorter.Options(); options.setMemoryMB(-1); } + + @Test + public void testZeroMemory() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("memoryMB must be greater than zero"); + InMemorySorter.Options options = new InMemorySorter.Options(); + options.setMemoryMB(0); + } } From 24b403e2d607f123d4dca1deb1ce1a390e4022e0 Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Fri, 16 Dec 2016 12:46:48 -0800 Subject: [PATCH 652/751] Remove outdated autoscaling language (#513) * TopWikipediaSessions: remove outdated autoscaling language * DataflowPipelineWorkerPoolOptions --- .../dataflow/examples/complete/TopWikipediaSessions.java | 9 --------- .../sdk/options/DataflowPipelineWorkerPoolOptions.java | 6 ++---- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java index 23c72cab7a..1f2be1f0b1 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java +++ b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java @@ -68,15 +68,6 @@ * *

            The default input is {@code gs://dataflow-samples/wikipedia_edits/*.json} and can be * overridden with {@code --input}. - * - *

            The input for this example is large enough that it's a good place to enable (experimental) - * autoscaling: - *

            {@code
            - *   --autoscalingAlgorithm=BASIC
            - *   --maxNumWorkers=20
            - * }
            - * 
            - * This will automatically scale the number of workers up over time until the job completes. */ public class TopWikipediaSessions { private static final String EXPORTED_WIKI_TABLE = "gs://dataflow-samples/wikipedia_edits/*.json"; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java index 6279724abc..23612442b5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java @@ -45,7 +45,6 @@ public interface DataflowPipelineWorkerPoolOptions extends PipelineOptions { /** * Type of autoscaling algorithm to use. */ - @Experimental(Experimental.Kind.AUTOSCALING) enum AutoscalingAlgorithmType { /** Use numWorkers machines. Do not autoscale the worker pool. */ NONE("AUTOSCALING_ALGORITHM_NONE"), @@ -69,7 +68,7 @@ public String getAlgorithm() { } /** - * [Experimental] The autoscaling algorithm to use for the workerpool. + * The autoscaling algorithm to use for the workerpool. * *
              *
            • NONE: does not change the size of the worker pool.
            • @@ -78,12 +77,11 @@ public String getAlgorithm() { * *
            */ - @Description("[Experimental] The autoscaling algorithm to use for the workerpool. " + @Description("The autoscaling algorithm to use for the workerpool. " + "NONE: does not change the size of the worker pool. " + "BASIC (deprecated): autoscale the worker pool size up to maxNumWorkers until the job " + "completes. " + "THROUGHPUT_BASED: autoscale the workerpool based on throughput (up to maxNumWorkers).") - @Experimental(Experimental.Kind.AUTOSCALING) AutoscalingAlgorithmType getAutoscalingAlgorithm(); void setAutoscalingAlgorithm(AutoscalingAlgorithmType value); From 31426ada0349f96deb529ef065a9e9e340f31f1c Mon Sep 17 00:00:00 2001 From: sammcveety Date: Fri, 16 Dec 2016 12:49:58 -0800 Subject: [PATCH 653/751] Regression test for pull/511 (#514) --- .../com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 0f2064eb69..a5bddec315 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -1734,6 +1734,13 @@ public void testTagWithUniqueIdsAndTableProjectNotNullWithNvp() { assertNotNull(table.getProjectId()); } + @Test + public void testWriteHandlesNullTable() { + BigQueryIO.Write.Bound write = BigQueryIO.Write + .withoutValidation(); + assertNull(write.getTable()); + } + private static void testNumFiles(File tempDir, int expectedNumFiles) { assertEquals(expectedNumFiles, tempDir.listFiles(new FileFilter() { @Override From 0623407a1047f93295dae1ece811b2d6458ba041 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 16 Dec 2016 14:09:27 -0800 Subject: [PATCH 654/751] Version management: prep for 1.9.0 release --- .../cloud/dataflow/sdk/runners/DataflowPipelineRunner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java index d5b40a52b8..f4cdba516b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java @@ -222,9 +222,9 @@ public class DataflowPipelineRunner extends PipelineRunner // Default Docker container images that execute Dataflow worker harness, residing in Google // Container Registry, separately for Batch and Streaming. public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.8.1"; + = "dataflow.gcr.io/v1beta3/java-batch:1.9.0"; public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.8.1"; + = "dataflow.gcr.io/v1beta3/java-streaming:1.9.0"; // The limit of CreateJob request size. private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; From 2c9bbcc5f90feaf387bf4041bb311b5b5f178710 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 16 Dec 2016 16:34:57 -0800 Subject: [PATCH 655/751] View: javadoc fixes to asMap --- .../java/com/google/cloud/dataflow/sdk/transforms/View.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java index e2c4487ae5..ce2a3afe1b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java @@ -191,9 +191,9 @@ public static AsIterable asIterable() { /** * Returns a {@link View.AsMap} transform that takes a - * {@link PCollection PCollection<KV<K V>>} as + * {@link PCollection PCollection<KV<K, V>>} as * input and produces a {@link PCollectionView} mapping each window to - * a {@link Map Map>K, V>}. It is required that each key of the input be + * a {@link Map Map<K, V>}. It is required that each key of the input be * associated with a single value, per window. If this is not the case, precede this * view with {@code Combine.perKey}, as in the example below, or alternatively * use {@link View#asMultimap()}. From 5f4301f63f007b8aaf868191a138ea4306666e6c Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Wed, 21 Dec 2016 18:51:24 -0800 Subject: [PATCH 656/751] Version management: begin development on the 1.10 release --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 6c1deb0b75..2c652305e4 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.9.0-SNAPSHOT + 1.10.0-SNAPSHOT com.google.cloud.dataflow diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index e26a7602fd..081b852824 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.9.0-SNAPSHOT + 1.10.0-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 22eeb7fb41..e40c1955d9 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.9.0-SNAPSHOT + 1.10.0-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index cdcb9a8095..5810ee7239 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ http://cloud.google.com/dataflow 2013 - 1.9.0-SNAPSHOT + 1.10.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index d23ca15c10..82ffe3ac9e 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -22,7 +22,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 1.9.0-SNAPSHOT + 1.10.0-SNAPSHOT com.google.cloud.dataflow From 161cacee1bba31b4f04b4800a3c606c3a54d40c8 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 14:32:30 -0800 Subject: [PATCH 657/751] Update pom.xml files for the 2.0.0-beta1 version --- checkstyle.xml | 2 +- examples/pom.xml | 501 +------------------------- pom.xml | 458 ++++++++++-------------- sdk/pom.xml | 907 +---------------------------------------------- 4 files changed, 220 insertions(+), 1648 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 3d99556795..66d1379c4e 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -130,7 +130,7 @@ page at http://checkstyle.sourceforge.net/config.html --> - + diff --git a/examples/pom.xml b/examples/pom.xml index 2c652305e4..ec5277c800 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -1,6 +1,6 @@ - - org.codehaus.mojo - build-helper-maven-plugin - - - add-java8-main-source - initialize - - add-source - - - - ${project.basedir}/src/main/java8 - - - - - - add-java8-test-source - initialize - - add-test-source - - - - ${project.basedir}/src/test/java8 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - - default-testCompile - test-compile - - testCompile - - - 1.7 - 1.7 - - - **/*Java8Test.java - **/game/**/*.java - - - - - - - java8-test-compile - test-compile - - testCompile - - - 1.8 - 1.8 - - - **/*Java8Test.java - **/game/**/*.java - - - - - - - default-compile - compile - - compile - - - 1.7 - 1.7 - - - **/*Java8*.java - **/game/**/*.java - - - - - - - java8-compile - compile - - compile - - - 1.8 - 1.8 - - - **/*Java8*.java - **/game/**/*.java - - - - - - - - - - - - - - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-dependency-plugin - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.puppycrawl.tools - checkstyle - 6.19 - - - - ../checkstyle.xml - ../suppressions.xml - true - true - true - false - - - - - check - - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - compile - - jar - - - - attach-test-sources - test-compile - - test-jar - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - Google Cloud Dataflow Examples - Google Cloud Dataflow Examples - - com.google.cloud.dataflow.examples - -exclude com.google.cloud.dataflow.sdk.runners.worker:com.google.cloud.dataflow.sdk.runners.dataflow:com.google.cloud.dataflow.sdk.util ${dataflow.javadoc_opts} - false - true - ]]> - - - - - https://cloud.google.com/dataflow/java-sdk/JavaDoc/ - ${basedir}/../javadoc/dataflow-sdk-docs - - - - https://developers.google.com/api-client-library/java/google-api-java-client/reference/1.20.0/ - ${basedir}/../javadoc/apiclient-docs - - - http://avro.apache.org/docs/1.7.7/api/java/ - ${basedir}/../javadoc/avro-docs - - - https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/java/latest/ - ${basedir}/../javadoc/bq-docs - - - https://cloud.google.com/datastore/docs/apis/javadoc/ - ${basedir}/../javadoc/datastore-docs - - - http://docs.guava-libraries.googlecode.com/git-history/release18/javadoc/ - ${basedir}/../javadoc/guava-docs - - - http://fasterxml.github.io/jackson-annotations/javadoc/2.7/ - ${basedir}/../javadoc/jackson-annotations-docs - - - http://fasterxml.github.io/jackson-databind/javadoc/2.7/ - ${basedir}/../javadoc/jackson-databind-docs - - - http://www.joda.org/joda-time/apidocs - ${basedir}/../javadoc/joda-docs - - - https://developers.google.com/api-client-library/java/google-oauth-java-client/reference/1.20.0/ - ${basedir}/../javadoc/oauth-docs - - - - - - - jar - - package - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4.1 - - - package - - shade - - - ${project.artifactId}-bundled-${project.version} - - - *:* - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - default-jar - - jar - - - - default-test-jar - - test-jar - - - - - - - - org.jacoco - jacoco-maven-plugin - - - - com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - ${project.version} - - - - com.google.api-client - google-api-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-dataflow - ${dataflow.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-bigquery - ${bigquery.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.http-client - google-http-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - org.apache.avro - avro - ${avro.version} - - - - com.google.apis - google-api-services-datastore-protobuf - ${datastore.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-pubsub - ${pubsub.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.cloud.datastore - datastore-v1-proto-client - ${datastore.client.version} - - - - com.google.cloud.datastore - datastore-v1-protos - ${datastore.proto.version} - - - - com.google.guava - guava - ${guava.version} - - - - com.google.code.findbugs - jsr305 - ${jsr305.version} - - - - joda-time - joda-time - ${joda.version} - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - runtime - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - junit - junit - ${junit.version} + org.apache.beam + beam-examples-java - org.mockito - mockito-all - 1.10.19 - test + org.apache.beam + beam-examples-java8 diff --git a/pom.xml b/pom.xml index 5810ee7239..c6225324ee 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ - 1.7.7 - v2-rev295-1.22.0 - 0.0.2 - 0.3.0 - v2-rev8-1.22.0 - v1b3-rev43-1.22.0 - 0.5.160222 - v1beta2-rev1-4.0.0 - 1.1.0 - 1.0.1 - 1.22.0 - 0.13.1 - 19.0 - 1.3 - 2.7.0 - 2.4 - 3.0.1 - 4.11 - 3.0.0-beta-1 - v1-rev10-1.22.0 - 1.7.14 - 3.1.4 - v1-rev71-1.22.0 - 4.4.1 - - -Xpkginfo:always - nothing + ${maven.build.timestamp} + yyyy-MM-dd HH:mm + + 0.4.0 pom @@ -105,107 +89,56 @@ maven-archetypes/examples - - - doclint-java8-disable - - [1.8,) - - - -Xdoclint:-missing - - - - - java7-packageinfo - - 1.7 - - - - -Xpkginfo:legacy - **/package-info.java - - - - - maven-compiler-plugin - - - - compile-package-info - - compile - - compile - - - -Xpkginfo:always - - - **/package-info.java - - - - - - - - - - + org.apache.maven.plugins + maven-clean-plugin + 3.0.0 + + + + org.apache.maven.plugins maven-compiler-plugin - 3.1 + 3.6.0 1.7 1.7 -Xlint:all -Werror - -Xlint:-options - - -Xlint:-cast - -Xlint:-deprecation - -Xlint:-processing - -Xlint:-rawtypes - -Xlint:-serial - -Xlint:-try - -Xlint:-unchecked - -Xlint:-varargs - - - true - - false + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.17 + + + com.puppycrawl.tools + checkstyle + 6.19 + + + + checkstyle.xml + suppressions.xml + true + true + true + true - default-compile + verify - compile + check - compile - - - ${compiler.default.pkginfo.flag} - - - ${compiler.default.exclude} - - @@ -213,195 +146,194 @@ org.apache.maven.plugins maven-jar-plugin - 2.5 + 3.0.2 + + true + + + + default-jar + + jar + + + + default-test-jar + + test-jar + + + org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - - - org.codehaus.mojo - versions-maven-plugin - 2.1 - - - - org.codehaus.mojo - exec-maven-plugin - 1.4.0 + maven-source-plugin + 3.0.1 - verify + attach-sources + compile - java + jar + + + + attach-test-sources + test-compile + + test-jar - - false - - - java.util.logging.config.file - logging.properties - - - - - org.jacoco - jacoco-maven-plugin - 0.7.5.201505241946 + org.apache.maven.plugins + maven-dependency-plugin + 3.0.0 - prepare-agent + analyze-only - file - true + true - - report - prepare-package - - report - - - - - **/AutoValue_*.class - - org.apache.maven.plugins maven-surefire-plugin - 2.18.1 - - ${testParallelValue} - 4 - - ${project.build.directory}/${project.artifactId}-${project.version}.jar - ${project.build.directory}/${project.artifactId}-${project.version}-tests.jar - - ${testGroups} - - ${runIntegrationTestOnService} - ${dataflowProjectName} - - false - false - true - ${dataflow.surefire_argline} - + 2.19.1 + + + + org.apache.maven.plugins + maven-archetype-plugin + 2.4 - org.apache.maven.surefire - surefire-junit47 - 2.18.1 + org.apache.maven.shared + maven-invoker + 2.2 + + + + default-integration-test + install + + integration-test + + + true + + + - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.avro - avro-maven-plugin - ${avro.version} - - schema - - - - - false - - - - - - org.apache.maven.plugins - maven-jar-plugin - [2.5,) - - jar - test-jar - - - - - - - - - org.jacoco - jacoco-maven-plugin - [0.7.5,) - - report - prepare-agent - - - - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.10 + maven-release-plugin + 2.5.3 - true + true + true + deploy org.codehaus.mojo - build-helper-maven-plugin - 1.10 + exec-maven-plugin + 1.5.0 + + false + - - - org.codehaus.mojo - versions-maven-plugin - 2.1 - - - - dependency-updates-report - plugin-updates-report - - - + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + + org.apache.maven.plugins + maven-dependency-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + org.apache.maven.plugins + maven-checkstyle-plugin - + + + + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-all + ${project.version} + + + + org.apache.beam + beam-sdks-java-core + ${beam.version} + + + + org.apache.beam + beam-sdks-java-io-google-cloud-platform + ${beam.version} + + + + org.apache.beam + beam-runners-direct-java + ${beam.version} + + + + org.apache.beam + beam-runners-google-cloud-dataflow-java + ${beam.version} + + + + org.apache.beam + beam-examples-java + ${beam.version} + + + + org.apache.beam + beam-examples-java8 + ${beam.version} + + + diff --git a/sdk/pom.xml b/sdk/pom.xml index 82ffe3ac9e..b6f5ecc572 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -1,6 +1,6 @@ - - org.codehaus.mojo - build-helper-maven-plugin - - - add-java8-test-source - initialize - - add-test-source - - - - ${project.basedir}/src/test/java8 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - default-testCompile - test-compile - - testCompile - - - 1.7 - 1.7 - - - **/*Java8Test.java - - - - - - java8-testCompile - test-compile - - testCompile - - - 1.8 - 1.8 - - **/*Java8Test.java - - - - - - - - - - @@ -134,812 +40,27 @@ true - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - - - InProcessPipelineRunnerTests - integration-test - - test - - - com.google.cloud.dataflow.sdk.testing.RunnableOnService - none - true - - false - - [ - "--runner=InProcessPipelineRunner" - ] - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - analyze-only - - true - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.puppycrawl.tools - checkstyle - 6.19 - - - - ../checkstyle.xml - ../suppressions.xml - true - true - false - true - - - - - check - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - default-jar - - jar - - - - default-test-jar - - test-jar - - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - compile - - jar - - - - attach-test-sources - test-compile - - test-jar - - - - - - - org.apache.maven.plugins maven-javadoc-plugin - - Google Cloud Dataflow SDK ${project.version} API - Google Cloud Dataflow SDK for Java, version ${project.version} - ../javadoc/overview.html - - com.google.cloud.dataflow.sdk - -exclude com.google.cloud.dataflow.sdk.runners.worker:com.google.cloud.dataflow.sdk.runners.dataflow:com.google.cloud.dataflow.sdk.util ${dataflow.javadoc_opts} - false - true - ]]> - - - - https://developers.google.com/api-client-library/java/google-api-java-client/reference/1.20.0/ - ${basedir}/../javadoc/apiclient-docs - - - http://avro.apache.org/docs/1.7.7/api/java/ - ${basedir}/../javadoc/avro-docs - - - https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/java/latest/ - ${basedir}/../javadoc/bq-docs - - - https://cloud.google.com/datastore/docs/apis/javadoc/ - ${basedir}/../javadoc/datastore-docs - - - http://docs.guava-libraries.googlecode.com/git-history/release19/javadoc/ - ${basedir}/../javadoc/guava-docs - - - http://hamcrest.org/JavaHamcrest/javadoc/1.3/ - ${basedir}/../javadoc/hamcrest-docs - - - http://fasterxml.github.io/jackson-annotations/javadoc/2.7/ - ${basedir}/../javadoc/jackson-annotations-docs - - - http://fasterxml.github.io/jackson-databind/javadoc/2.7/ - ${basedir}/../javadoc/jackson-databind-docs - - - http://www.joda.org/joda-time/apidocs - ${basedir}/../javadoc/joda-docs - - - http://junit.sourceforge.net/javadoc/ - ${basedir}/../javadoc/junit-docs - - - https://developers.google.com/api-client-library/java/google-oauth-java-client/reference/1.20.0/ - ${basedir}/../javadoc/oauth-docs - - - - - - - jar - - package - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4.1 - - - - bundle-and-repackage - package - - shade - - - true - - - com.google.cloud.bigtable:bigtable-client-core - com.google.guava:guava - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - com.google.common - - - com.google.common.**.testing.* - - com.google.cloud.dataflow.sdk.repackaged.com.google.common - - - com.google.thirdparty - com.google.cloud.dataflow.sdk.repackaged.com.google.thirdparty - - - com.google.cloud.bigtable - com.google.cloud.dataflow.sdk.repackaged.com.google.cloud.bigtable - - com.google.cloud.bigtable.config.BigtableOptions* - com.google.cloud.bigtable.config.BulkOptions* - com.google.cloud.bigtable.config.CredentialOptions* - com.google.cloud.bigtable.config.RetryOptions* - com.google.cloud.bigtable.grpc.BigtableClusterName - com.google.cloud.bigtable.grpc.BigtableTableName - - - - - - - - - bundle-rest-without-repackaging - package - - shade - - - true - ${project.artifactId}-bundled-${project.version} - - - com.google.cloud.bigtable:bigtable-client-core - com.google.guava:guava - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - - org.jacoco - jacoco-maven-plugin - - - - - org.apache.avro - avro-maven-plugin - ${avro.version} - - - schemas - generate-test-sources - - schema - - - ${project.basedir}/src/test/ - ${project.build.directory}/generated-test-sources/java - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.9.1 - - - add-test-source - generate-test-sources - - add-test-source - - - - ${project.build.directory}/generated-test-sources/java - - - - - - - com.google.apis - google-api-services-dataflow - ${dataflow.version} - - - - com.google.guava - guava-jdk5 - - - - - - io.grpc - grpc-all - ${grpc.version} - - - - io.netty - netty-handler - 4.1.0.CR1 - - - - com.google.api.grpc - grpc-pubsub-v1 - ${pubsubgrpc.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.auth - google-auth-library-oauth2-http - 0.4.0 - - - - com.google.guava - guava-jdk5 - - - - - - com.google.cloud.bigtable - bigtable-protos - ${bigtable.version} - - - - com.google.cloud.bigtable - bigtable-client-core - ${bigtable.version} - - - - com.google.api-client - google-api-client - ${google-clients.version} - - - com.google.guava - guava-jdk5 - - - - - - - com.google.api-client - google-api-client-java6 - ${google-clients.version} - runtime - - - - - com.google.api-client - google-api-client-jackson2 - ${google-clients.version} - runtime - - - - com.google.apis - google-api-services-bigquery - ${bigquery.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-clouddebugger - ${clouddebugger.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-pubsub - ${pubsub.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-storage - ${storage.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.http-client - google-http-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - - com.google.http-client - google-http-client-jackson - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - org.codehaus.jackson - jackson-core-asl - - - runtime - - - - com.google.http-client - google-http-client-jackson2 - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.http-client - google-http-client-protobuf - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - runtime - - - - com.google.oauth-client - google-oauth-client-java6 - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.oauth-client - google-oauth-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-datastore-protobuf - ${datastore.version} - - - - com.google.guava - guava-jdk5 - - - - com.google.http-client - google-http-client - - - com.google.api-client - google-api-client - - - com.google.oauth-client - google-oauth-client - - - com.google.http-client - google-http-client-jackson - - - com.google.http-client - google-http-client-protobuf - - - - - - com.google.cloud.bigdataoss - gcsio - 1.4.5 - - - - com.google.cloud.datastore - datastore-v1-proto-client - ${datastore.client.version} - - - - com.google.cloud.datastore - datastore-v1-protos - ${datastore.proto.version} - - - - com.google.cloud.bigdataoss - util - 1.4.5 - - - - com.google.guava - guava - - ${guava.version} - - - - - com.google.guava - guava-testlib - ${guava.version} - test - - - - com.google.protobuf - protobuf-java - ${protobuf.version} - - - - com.google.code.findbugs - jsr305 - ${jsr305.version} - - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.apache.avro - avro - ${avro.version} - - - - org.xerial.snappy - snappy-java - 1.1.2.1 - - - - org.apache.commons - commons-compress - 1.9 - - - - joda-time - joda-time - ${joda.version} - - - - - org.codehaus.woodstox - stax2-api - ${stax2.version} - true - - - - org.codehaus.woodstox - woodstox-core-asl - ${woodstox.version} - runtime - true - - - - javax.xml.stream - stax-api - - - - - - - org.tukaani - xz - 1.5 - runtime - true - - - - - com.google.auto.service - auto-service - 1.0-rc2 - true - - - com.google.auto.value - auto-value - 1.1 - provided - - - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - provided - - - - junit - junit - ${junit.version} - provided + org.apache.beam + beam-sdks-java-core - org.slf4j - slf4j-jdk14 - ${slf4j.version} - test + org.apache.beam + beam-sdks-java-io-google-cloud-platform - org.mockito - mockito-all - 1.10.19 - test + org.apache.beam + beam-runners-direct-java - com.google.cloud.dataflow - google-cloud-dataflow-java-proto-library-all - 0.5.160304 - test + org.apache.beam + beam-runners-google-cloud-dataflow-java From e6017a83adcea1dc992c7175df749aa6d3c1c7e6 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 14:52:53 -0800 Subject: [PATCH 658/751] Remove all SDK source files They are now brought by the dependency on Apache Beam. --- .../google/cloud/dataflow/sdk/Pipeline.java | 503 --- .../cloud/dataflow/sdk/PipelineResult.java | 95 - .../sdk/annotations/Experimental.java | 80 - .../sdk/annotations/package-info.java | 20 - .../dataflow/sdk/coders/AtomicCoder.java | 51 - .../cloud/dataflow/sdk/coders/AvroCoder.java | 714 ---- .../sdk/coders/BigEndianIntegerCoder.java | 99 - .../sdk/coders/BigEndianLongCoder.java | 99 - .../dataflow/sdk/coders/ByteArrayCoder.java | 138 - .../cloud/dataflow/sdk/coders/ByteCoder.java | 111 - .../dataflow/sdk/coders/ByteStringCoder.java | 106 - .../coders/CannotProvideCoderException.java | 95 - .../cloud/dataflow/sdk/coders/Coder.java | 298 -- .../dataflow/sdk/coders/CoderException.java | 36 - .../dataflow/sdk/coders/CoderFactories.java | 274 -- .../dataflow/sdk/coders/CoderFactory.java | 43 - .../dataflow/sdk/coders/CoderProvider.java | 33 - .../dataflow/sdk/coders/CoderProviders.java | 164 - .../dataflow/sdk/coders/CoderRegistry.java | 844 ----- .../dataflow/sdk/coders/CollectionCoder.java | 73 - .../dataflow/sdk/coders/CustomCoder.java | 137 - .../dataflow/sdk/coders/DefaultCoder.java | 66 - .../dataflow/sdk/coders/DelegateCoder.java | 164 - .../coders/DeterministicStandardCoder.java | 38 - .../dataflow/sdk/coders/DoubleCoder.java | 113 - .../dataflow/sdk/coders/DurationCoder.java | 97 - .../dataflow/sdk/coders/EntityCoder.java | 89 - .../dataflow/sdk/coders/InstantCoder.java | 113 - .../dataflow/sdk/coders/IterableCoder.java | 77 - .../sdk/coders/IterableLikeCoder.java | 277 -- .../cloud/dataflow/sdk/coders/JAXBCoder.java | 143 - .../cloud/dataflow/sdk/coders/KvCoder.java | 161 - .../dataflow/sdk/coders/KvCoderBase.java | 61 - .../cloud/dataflow/sdk/coders/ListCoder.java | 77 - .../cloud/dataflow/sdk/coders/MapCoder.java | 160 - .../dataflow/sdk/coders/MapCoderBase.java | 54 - .../dataflow/sdk/coders/NullableCoder.java | 175 - .../dataflow/sdk/coders/Proto2Coder.java | 361 -- .../sdk/coders/SerializableCoder.java | 183 - .../cloud/dataflow/sdk/coders/SetCoder.java | 94 - .../dataflow/sdk/coders/StandardCoder.java | 229 -- .../sdk/coders/StringDelegateCoder.java | 86 - .../dataflow/sdk/coders/StringUtf8Coder.java | 139 - .../sdk/coders/StructuralByteArray.java | 56 - .../sdk/coders/TableRowJsonCoder.java | 82 - .../sdk/coders/TextualIntegerCoder.java | 69 - .../dataflow/sdk/coders/VarIntCoder.java | 97 - .../dataflow/sdk/coders/VarLongCoder.java | 96 - .../cloud/dataflow/sdk/coders/VoidCoder.java | 76 - .../dataflow/sdk/coders/package-info.java | 44 - .../sdk/coders/protobuf/ProtoCoder.java | 404 -- .../sdk/coders/protobuf/ProtobufUtil.java | 171 - .../sdk/coders/protobuf/package-info.java | 23 - .../google/cloud/dataflow/sdk/io/AvroIO.java | 845 ----- .../cloud/dataflow/sdk/io/AvroSource.java | 771 ---- .../cloud/dataflow/sdk/io/BigQueryIO.java | 3076 ---------------- .../dataflow/sdk/io/BlockBasedSource.java | 241 -- .../io/BoundedReadFromUnboundedSource.java | 294 -- .../cloud/dataflow/sdk/io/BoundedSource.java | 410 --- .../dataflow/sdk/io/CompressedSource.java | 509 --- .../cloud/dataflow/sdk/io/CountingInput.java | 249 -- .../cloud/dataflow/sdk/io/CountingSource.java | 485 --- .../cloud/dataflow/sdk/io/DatastoreIO.java | 1000 ----- .../cloud/dataflow/sdk/io/FileBasedSink.java | 720 ---- .../dataflow/sdk/io/FileBasedSource.java | 684 ---- .../dataflow/sdk/io/OffsetBasedSource.java | 383 -- .../cloud/dataflow/sdk/io/PubsubIO.java | 1218 ------ .../dataflow/sdk/io/PubsubUnboundedSink.java | 449 --- .../sdk/io/PubsubUnboundedSource.java | 1320 ------- .../google/cloud/dataflow/sdk/io/Read.java | 272 -- .../dataflow/sdk/io/ShardNameTemplate.java | 75 - .../google/cloud/dataflow/sdk/io/Sink.java | 266 -- .../google/cloud/dataflow/sdk/io/Source.java | 204 -- .../google/cloud/dataflow/sdk/io/TextIO.java | 1190 ------ .../dataflow/sdk/io/UnboundedSource.java | 253 -- .../google/cloud/dataflow/sdk/io/Write.java | 423 --- .../google/cloud/dataflow/sdk/io/XmlSink.java | 322 -- .../cloud/dataflow/sdk/io/XmlSource.java | 555 --- .../dataflow/sdk/io/bigtable/BigtableIO.java | 1133 ------ .../sdk/io/bigtable/BigtableService.java | 108 - .../sdk/io/bigtable/BigtableServiceImpl.java | 236 -- .../sdk/io/bigtable/package-info.java | 22 - .../sdk/io/datastore/DatastoreIO.java | 40 - .../sdk/io/datastore/DatastoreV1.java | 1043 ------ .../sdk/io/datastore/package-info.java | 22 - .../cloud/dataflow/sdk/io/package-info.java | 37 - .../cloud/dataflow/sdk/io/range/ByteKey.java | 173 - .../dataflow/sdk/io/range/ByteKeyRange.java | 376 -- .../sdk/io/range/ByteKeyRangeTracker.java | 184 - .../sdk/io/range/OffsetRangeTracker.java | 270 -- .../dataflow/sdk/io/range/RangeTracker.java | 222 -- .../dataflow/sdk/io/range/package-info.java | 23 - .../sdk/options/ApplicationNameOptions.java | 33 - .../dataflow/sdk/options/BigQueryOptions.java | 31 - .../BlockingDataflowPipelineOptions.java | 49 - .../sdk/options/CloudDebuggerOptions.java | 51 - .../options/DataflowPipelineDebugOptions.java | 270 -- .../sdk/options/DataflowPipelineOptions.java | 137 - .../DataflowPipelineWorkerPoolOptions.java | 272 -- .../sdk/options/DataflowProfilingOptions.java | 52 - .../options/DataflowWorkerHarnessOptions.java | 50 - .../options/DataflowWorkerLoggingOptions.java | 153 - .../cloud/dataflow/sdk/options/Default.java | 153 - .../sdk/options/DefaultValueFactory.java | 38 - .../dataflow/sdk/options/Description.java | 35 - .../sdk/options/DirectPipelineOptions.java | 75 - .../dataflow/sdk/options/GcpOptions.java | 291 -- .../dataflow/sdk/options/GcsOptions.java | 113 - .../sdk/options/GoogleApiDebugOptions.java | 87 - .../cloud/dataflow/sdk/options/Hidden.java | 33 - .../sdk/options/PipelineOptionSpec.java | 54 - .../dataflow/sdk/options/PipelineOptions.java | 294 -- .../sdk/options/PipelineOptionsFactory.java | 1611 -------- .../sdk/options/PipelineOptionsReflector.java | 110 - .../sdk/options/PipelineOptionsRegistrar.java | 36 - .../sdk/options/PipelineOptionsValidator.java | 104 - .../sdk/options/ProxyInvocationHandler.java | 769 ---- .../sdk/options/StreamingOptions.java | 30 - .../dataflow/sdk/options/Validation.java | 46 - .../dataflow/sdk/options/ValueProvider.java | 319 -- .../sdk/options/ValueProviderUtils.java | 58 - .../dataflow/sdk/options/package-info.java | 25 - .../cloud/dataflow/sdk/package-info.java | 33 - .../runners/AggregatorPipelineExtractor.java | 97 - .../runners/AggregatorRetrievalException.java | 32 - .../sdk/runners/AggregatorValues.java | 52 - .../BlockingDataflowPipelineRunner.java | 184 - .../DataflowJobAlreadyExistsException.java | 34 - .../DataflowJobAlreadyUpdatedException.java | 33 - .../DataflowJobCancelledException.java | 38 - .../sdk/runners/DataflowJobException.java | 40 - .../DataflowJobExecutionException.java | 34 - .../runners/DataflowJobUpdatedException.java | 51 - .../sdk/runners/DataflowPipeline.java | 59 - .../sdk/runners/DataflowPipelineJob.java | 418 --- .../runners/DataflowPipelineRegistrar.java | 58 - .../sdk/runners/DataflowPipelineRunner.java | 3251 ----------------- .../runners/DataflowPipelineRunnerHooks.java | 47 - .../runners/DataflowPipelineTranslator.java | 1102 ------ .../sdk/runners/DataflowServiceException.java | 32 - .../dataflow/sdk/runners/DirectPipeline.java | 55 - .../sdk/runners/DirectPipelineRegistrar.java | 53 - .../sdk/runners/DirectPipelineRunner.java | 1155 ------ .../dataflow/sdk/runners/PipelineRunner.java | 77 - .../sdk/runners/PipelineRunnerRegistrar.java | 40 - .../sdk/runners/RecordingPipelineVisitor.java | 54 - .../TemplatingDataflowPipelineRunner.java | 163 - .../sdk/runners/TransformHierarchy.java | 105 - .../sdk/runners/TransformTreeNode.java | 254 -- .../sdk/runners/dataflow/AssignWindows.java | 88 - .../sdk/runners/dataflow/CustomSources.java | 118 - .../DataflowAggregatorTransforms.java | 79 - .../DataflowMetricUpdateExtractor.java | 110 - ...ataflowUnboundedReadFromBoundedSource.java | 553 --- .../sdk/runners/dataflow/ReadTranslator.java | 107 - .../sdk/runners/dataflow/package-info.java | 20 - .../inprocess/AbstractModelEnforcement.java | 36 - .../BoundedReadEvaluatorFactory.java | 143 - .../sdk/runners/inprocess/BundleFactory.java | 48 - .../dataflow/sdk/runners/inprocess/Clock.java | 29 - .../runners/inprocess/CommittedResult.java | 75 - .../runners/inprocess/CompletionCallback.java | 42 - .../ConsumerTrackingPipelineVisitor.java | 173 - .../inprocess/DisplayDataValidator.java | 71 - .../inprocess/EmptyTransformEvaluator.java | 49 - .../EncodabilityEnforcementFactory.java | 68 - .../sdk/runners/inprocess/EvaluatorKey.java | 55 - .../inprocess/ExecutorServiceFactory.java | 32 - .../ExecutorServiceParallelExecutor.java | 513 --- ...FixedThreadPoolExecutorServiceFactory.java | 43 - .../inprocess/FlattenEvaluatorFactory.java | 81 - .../inprocess/ForwardingPTransform.java | 60 - .../inprocess/GroupByKeyEvaluatorFactory.java | 274 -- .../ImmutabilityCheckingBundleFactory.java | 127 - .../ImmutabilityEnforcementFactory.java | 101 - .../inprocess/InMemoryWatermarkManager.java | 1407 ------- .../inprocess/InProcessBundleFactory.java | 159 - .../InProcessBundleOutputManager.java | 50 - .../runners/inprocess/InProcessCreate.java | 233 -- .../inprocess/InProcessEvaluationContext.java | 443 --- .../inprocess/InProcessExecutionContext.java | 106 - .../runners/inprocess/InProcessExecutor.java | 46 - .../inprocess/InProcessPipelineOptions.java | 93 - .../inprocess/InProcessPipelineRunner.java | 431 --- .../runners/inprocess/InProcessRegistrar.java | 52 - .../InProcessSideInputContainer.java | 274 -- .../inprocess/InProcessTimerInternals.java | 83 - .../inprocess/InProcessTransformResult.java | 88 - .../inprocess/KeyedPValueTrackingVisitor.java | 95 - .../runners/inprocess/KeyedResourcePool.java | 45 - .../inprocess/LockedKeyedResourcePool.java | 93 - .../runners/inprocess/ModelEnforcement.java | 61 - .../inprocess/ModelEnforcementFactory.java | 28 - .../runners/inprocess/NanosOffsetClock.java | 44 - .../inprocess/PTransformOverrideFactory.java | 31 - .../inprocess/ParDoInProcessEvaluator.java | 184 - .../inprocess/ParDoMultiEvaluatorFactory.java | 62 - .../ParDoSingleEvaluatorFactory.java | 60 - .../PassthroughTransformEvaluator.java | 47 - .../sdk/runners/inprocess/StepAndKey.java | 68 - .../inprocess/StepTransformResult.java | 145 - .../sdk/runners/inprocess/StructuralKey.java | 74 - .../inprocess/TestStreamEvaluatorFactory.java | 217 -- .../runners/inprocess/TransformEvaluator.java | 45 - .../inprocess/TransformEvaluatorFactory.java | 47 - .../inprocess/TransformEvaluatorRegistry.java | 83 - .../runners/inprocess/TransformExecutor.java | 179 - .../inprocess/TransformExecutorService.java | 34 - .../inprocess/TransformExecutorServices.java | 140 - .../inprocess/UnboundedReadDeduplicator.java | 97 - .../UnboundedReadEvaluatorFactory.java | 261 -- .../inprocess/ViewEvaluatorFactory.java | 149 - .../inprocess/WatermarkCallbackExecutor.java | 142 - .../inprocess/WindowEvaluatorFactory.java | 129 - .../inprocess/WriteWithShardingFactory.java | 134 - .../sdk/runners/inprocess/package-info.java | 23 - .../dataflow/sdk/runners/package-info.java | 33 - .../sdk/runners/worker/IsmFormat.java | 945 ----- .../sdk/runners/worker/package-info.java | 24 - .../dataflow/sdk/testing/CoderProperties.java | 349 -- .../dataflow/sdk/testing/DataflowAssert.java | 1579 -------- .../dataflow/sdk/testing/PaneExtractors.java | 157 - .../sdk/testing/RunnableOnService.java | 30 - .../sdk/testing/SerializableMatcher.java | 36 - .../sdk/testing/SerializableMatchers.java | 1179 ------ .../dataflow/sdk/testing/SourceTestUtils.java | 806 ---- .../dataflow/sdk/testing/StaticWindows.java | 115 - .../testing/TestDataflowPipelineOptions.java | 26 - .../testing/TestDataflowPipelineRunner.java | 221 -- .../dataflow/sdk/testing/TestPipeline.java | 200 - .../dataflow/sdk/testing/TestStream.java | 366 -- .../sdk/testing/WindowFnTestUtils.java | 325 -- .../dataflow/sdk/testing/WindowSupplier.java | 80 - .../dataflow/sdk/testing/package-info.java | 21 - .../dataflow/sdk/transforms/Aggregator.java | 78 - .../sdk/transforms/AggregatorRetriever.java | 36 - .../sdk/transforms/AppliedPTransform.java | 100 - .../sdk/transforms/ApproximateQuantiles.java | 778 ---- .../sdk/transforms/ApproximateUnique.java | 467 --- .../dataflow/sdk/transforms/Combine.java | 2367 ------------ .../sdk/transforms/CombineFnBase.java | 305 -- .../dataflow/sdk/transforms/CombineFns.java | 1166 ------ .../sdk/transforms/CombineWithContext.java | 284 -- .../cloud/dataflow/sdk/transforms/Count.java | 135 - .../cloud/dataflow/sdk/transforms/Create.java | 427 --- .../cloud/dataflow/sdk/transforms/DoFn.java | 563 --- .../sdk/transforms/DoFnReflector.java | 672 ---- .../dataflow/sdk/transforms/DoFnTester.java | 528 --- .../sdk/transforms/DoFnWithContext.java | 428 --- .../cloud/dataflow/sdk/transforms/Filter.java | 266 -- .../sdk/transforms/FlatMapElements.java | 145 - .../dataflow/sdk/transforms/Flatten.java | 219 -- .../dataflow/sdk/transforms/GroupByKey.java | 585 --- .../IntraBundleParallelization.java | 360 -- .../cloud/dataflow/sdk/transforms/Keys.java | 68 - .../cloud/dataflow/sdk/transforms/KvSwap.java | 73 - .../dataflow/sdk/transforms/MapElements.java | 125 - .../cloud/dataflow/sdk/transforms/Max.java | 263 -- .../cloud/dataflow/sdk/transforms/Mean.java | 202 - .../cloud/dataflow/sdk/transforms/Min.java | 263 -- .../dataflow/sdk/transforms/PTransform.java | 324 -- .../cloud/dataflow/sdk/transforms/ParDo.java | 1358 ------- .../dataflow/sdk/transforms/Partition.java | 190 - .../sdk/transforms/RemoveDuplicates.java | 159 - .../cloud/dataflow/sdk/transforms/Sample.java | 265 -- .../transforms/SerializableComparator.java | 28 - .../sdk/transforms/SerializableFunction.java | 31 - .../sdk/transforms/SimpleFunction.java | 54 - .../cloud/dataflow/sdk/transforms/Sum.java | 188 - .../cloud/dataflow/sdk/transforms/Top.java | 569 --- .../cloud/dataflow/sdk/transforms/Values.java | 68 - .../cloud/dataflow/sdk/transforms/View.java | 470 --- .../dataflow/sdk/transforms/WithKeys.java | 140 - .../sdk/transforms/WithTimestamps.java | 129 - .../cloud/dataflow/sdk/transforms/Write.java | 27 - .../sdk/transforms/display/DisplayData.java | 826 ----- .../transforms/display/HasDisplayData.java | 66 - .../sdk/transforms/display/package-info.java | 25 - .../sdk/transforms/join/CoGbkResult.java | 462 --- .../transforms/join/CoGbkResultSchema.java | 134 - .../sdk/transforms/join/CoGroupByKey.java | 211 -- .../join/KeyedPCollectionTuple.java | 247 -- .../sdk/transforms/join/RawUnionValue.java | 51 - .../sdk/transforms/join/UnionCoder.java | 147 - .../sdk/transforms/join/package-info.java | 21 - .../dataflow/sdk/transforms/package-info.java | 43 - .../sdk/transforms/windowing/AfterAll.java | 128 - .../windowing/AfterDelayFromFirstElement.java | 331 -- .../sdk/transforms/windowing/AfterEach.java | 145 - .../sdk/transforms/windowing/AfterFirst.java | 130 - .../sdk/transforms/windowing/AfterPane.java | 145 - .../windowing/AfterProcessingTime.java | 104 - .../AfterSynchronizedProcessingTime.java | 75 - .../transforms/windowing/AfterWatermark.java | 383 -- .../transforms/windowing/BoundedWindow.java | 46 - .../transforms/windowing/CalendarWindows.java | 390 -- .../transforms/windowing/DefaultTrigger.java | 95 - .../transforms/windowing/FixedWindows.java | 127 - .../transforms/windowing/GlobalWindow.java | 68 - .../transforms/windowing/GlobalWindows.java | 63 - .../transforms/windowing/IntervalWindow.java | 201 - .../transforms/windowing/InvalidWindows.java | 87 - .../MergeOverlappingIntervalWindows.java | 86 - .../sdk/transforms/windowing/Never.java | 72 - .../windowing/NonMergingWindowFn.java | 35 - .../windowing/OrFinallyTrigger.java | 105 - .../transforms/windowing/OutputTimeFn.java | 319 -- .../transforms/windowing/OutputTimeFns.java | 168 - .../sdk/transforms/windowing/PaneInfo.java | 385 -- .../windowing/PartitioningWindowFn.java | 61 - .../sdk/transforms/windowing/Repeatedly.java | 105 - .../sdk/transforms/windowing/Sessions.java | 120 - .../transforms/windowing/SlidingWindows.java | 227 -- .../sdk/transforms/windowing/Trigger.java | 544 --- .../transforms/windowing/TriggerBuilder.java | 29 - .../sdk/transforms/windowing/Window.java | 701 ---- .../sdk/transforms/windowing/WindowFn.java | 233 -- .../transforms/windowing/package-info.java | 49 - .../dataflow/sdk/util/ActiveWindowSet.java | 173 - .../cloud/dataflow/sdk/util/ApiSurface.java | 648 ---- .../sdk/util/AppEngineEnvironment.java | 61 - .../dataflow/sdk/util/AppliedCombineFn.java | 130 - .../dataflow/sdk/util/AssignWindowsDoFn.java | 67 - ...temptAndTimeBoundedExponentialBackOff.java | 172 - .../AttemptBoundedExponentialBackOff.java | 86 - .../cloud/dataflow/sdk/util/AvroUtils.java | 361 -- .../sdk/util/BaseExecutionContext.java | 156 - .../sdk/util/BatchTimerInternals.java | 143 - .../dataflow/sdk/util/BigQueryServices.java | 178 - .../sdk/util/BigQueryServicesImpl.java | 604 --- .../sdk/util/BigQueryTableInserter.java | 472 --- .../sdk/util/BigQueryTableRowIterator.java | 533 --- .../cloud/dataflow/sdk/util/BitSetCoder.java | 59 - .../dataflow/sdk/util/BucketingFunction.java | 151 - .../BufferedElementCountingOutputStream.java | 184 - .../dataflow/sdk/util/CloudKnownType.java | 138 - .../cloud/dataflow/sdk/util/CloudObject.java | 184 - .../cloud/dataflow/sdk/util/CoderUtils.java | 327 -- .../sdk/util/CombineContextFactory.java | 107 - .../dataflow/sdk/util/CombineFnUtil.java | 164 - .../dataflow/sdk/util/CounterAggregator.java | 96 - .../dataflow/sdk/util/CredentialFactory.java | 29 - .../cloud/dataflow/sdk/util/Credentials.java | 193 - .../sdk/util/DataflowPathValidator.java | 98 - .../sdk/util/DataflowReleaseInfo.java | 87 - .../sdk/util/DirectModeExecutionContext.java | 130 - .../sdk/util/DirectSideInputReader.java | 73 - .../cloud/dataflow/sdk/util/DoFnInfo.java | 67 - .../cloud/dataflow/sdk/util/DoFnRunner.java | 60 - .../dataflow/sdk/util/DoFnRunnerBase.java | 558 --- .../cloud/dataflow/sdk/util/DoFnRunners.java | 140 - .../dataflow/sdk/util/ExecutableTrigger.java | 161 - .../dataflow/sdk/util/ExecutionContext.java | 102 - .../sdk/util/ExposedByteArrayInputStream.java | 51 - .../util/ExposedByteArrayOutputStream.java | 116 - .../sdk/util/FileIOChannelFactory.java | 136 - .../dataflow/sdk/util/FinishedTriggers.java | 42 - .../sdk/util/FinishedTriggersBitSet.java | 68 - .../sdk/util/FinishedTriggersSet.java | 74 - .../dataflow/sdk/util/FluentBackoff.java | 227 -- .../dataflow/sdk/util/GatherAllPanes.java | 72 - .../sdk/util/GcpCredentialFactory.java | 45 - .../sdk/util/GcsIOChannelFactory.java | 86 - .../cloud/dataflow/sdk/util/GcsStager.java | 54 - .../cloud/dataflow/sdk/util/GcsUtil.java | 564 --- .../GroupAlsoByWindowViaWindowSetDoFn.java | 100 - .../sdk/util/GroupAlsoByWindowsDoFn.java | 58 - ...GroupAlsoByWindowsViaOutputBufferDoFn.java | 98 - .../dataflow/sdk/util/IOChannelFactory.java | 101 - .../dataflow/sdk/util/IOChannelUtils.java | 204 -- .../dataflow/sdk/util/IdentityWindowFn.java | 109 - .../sdk/util/IllegalMutationException.java | 52 - .../dataflow/sdk/util/InstanceBuilder.java | 270 -- .../IntervalBoundedExponentialBackOff.java | 93 - .../dataflow/sdk/util/KeyedWorkItem.java | 41 - .../dataflow/sdk/util/KeyedWorkItemCoder.java | 120 - .../dataflow/sdk/util/KeyedWorkItems.java | 120 - .../sdk/util/LateDataDroppingDoFnRunner.java | 154 - .../sdk/util/MapAggregatorValues.java | 48 - .../sdk/util/MergingActiveWindowSet.java | 429 --- .../cloud/dataflow/sdk/util/MimeTypes.java | 23 - .../dataflow/sdk/util/MonitoringUtil.java | 233 -- .../dataflow/sdk/util/MovingFunction.java | 145 - .../dataflow/sdk/util/MutationDetector.java | 31 - .../dataflow/sdk/util/MutationDetectors.java | 181 - .../dataflow/sdk/util/NonEmptyPanes.java | 148 - .../sdk/util/NonMergingActiveWindowSet.java | 90 - .../sdk/util/NoopCredentialFactory.java | 38 - .../dataflow/sdk/util/NoopPathValidator.java | 48 - .../sdk/util/NullSideInputReader.java | 61 - .../dataflow/sdk/util/OutputReference.java | 42 - .../sdk/util/PCollectionViewWindow.java | 67 - .../dataflow/sdk/util/PCollectionViews.java | 426 --- .../cloud/dataflow/sdk/util/PTuple.java | 160 - .../cloud/dataflow/sdk/util/PackageUtil.java | 331 -- .../dataflow/sdk/util/PaneInfoTracker.java | 155 - .../dataflow/sdk/util/PathValidator.java | 47 - .../sdk/util/PerKeyCombineFnRunner.java | 147 - .../sdk/util/PerKeyCombineFnRunners.java | 257 -- .../dataflow/sdk/util/PropertyNames.java | 110 - .../cloud/dataflow/sdk/util/PubsubClient.java | 557 --- .../dataflow/sdk/util/PubsubGrpcClient.java | 444 --- .../dataflow/sdk/util/PubsubJsonClient.java | 312 -- .../dataflow/sdk/util/PubsubTestClient.java | 403 -- .../sdk/util/PushbackSideInputDoFnRunner.java | 112 - .../dataflow/sdk/util/RandomAccessData.java | 352 -- .../util/ReadyCheckingSideInputReader.java | 31 - .../cloud/dataflow/sdk/util/ReduceFn.java | 128 - .../sdk/util/ReduceFnContextFactory.java | 493 --- .../dataflow/sdk/util/ReduceFnRunner.java | 1118 ------ .../util/ReifyTimestampAndWindowsDoFn.java | 46 - .../cloud/dataflow/sdk/util/Reshuffle.java | 82 - .../dataflow/sdk/util/ReshuffleTrigger.java | 66 - .../sdk/util/RetryHttpRequestInitializer.java | 250 -- .../dataflow/sdk/util/SerializableUtils.java | 159 - .../cloud/dataflow/sdk/util/Serializer.java | 145 - .../sdk/util/ShardingWritableByteChannel.java | 118 - .../dataflow/sdk/util/SideInputReader.java | 48 - .../dataflow/sdk/util/SimpleDoFnRunner.java | 55 - .../cloud/dataflow/sdk/util/Stager.java | 29 - .../cloud/dataflow/sdk/util/StreamUtils.java | 68 - .../cloud/dataflow/sdk/util/StringUtils.java | 244 -- .../cloud/dataflow/sdk/util/Structs.java | 384 -- .../dataflow/sdk/util/SystemDoFnInternal.java | 37 - .../dataflow/sdk/util/SystemReduceFn.java | 133 - .../dataflow/sdk/util/TestCredential.java | 51 - .../cloud/dataflow/sdk/util/TimeDomain.java | 41 - .../cloud/dataflow/sdk/util/TimeUtil.java | 164 - .../dataflow/sdk/util/TimerInternals.java | 283 -- .../cloud/dataflow/sdk/util/Timers.java | 59 - .../cloud/dataflow/sdk/util/Transport.java | 198 - .../sdk/util/TriggerContextFactory.java | 521 --- .../dataflow/sdk/util/TriggerRunner.java | 232 -- .../dataflow/sdk/util/UnownedInputStream.java | 76 - .../sdk/util/UnownedOutputStream.java | 56 - .../sdk/util/UploadIdResponseInterceptor.java | 61 - .../dataflow/sdk/util/UserCodeException.java | 98 - .../dataflow/sdk/util/ValueWithRecordId.java | 154 - .../cloud/dataflow/sdk/util/Values.java | 88 - .../cloud/dataflow/sdk/util/VarInt.java | 115 - .../dataflow/sdk/util/WatermarkHold.java | 540 --- .../cloud/dataflow/sdk/util/Weighted.java | 27 - .../dataflow/sdk/util/WeightedValue.java | 45 - .../dataflow/sdk/util/WindowTracing.java | 36 - .../dataflow/sdk/util/WindowedValue.java | 732 ---- .../dataflow/sdk/util/WindowingInternals.java | 82 - .../dataflow/sdk/util/WindowingStrategy.java | 268 -- .../cloud/dataflow/sdk/util/ZipFiles.java | 294 -- .../dataflow/sdk/util/common/Counter.java | 1338 ------- .../sdk/util/common/CounterProvider.java | 26 - .../dataflow/sdk/util/common/CounterSet.java | 214 -- .../common/ElementByteSizeObservable.java | 40 - .../ElementByteSizeObservableIterable.java | 63 - .../ElementByteSizeObservableIterator.java | 36 - .../util/common/ElementByteSizeObserver.java | 92 - .../dataflow/sdk/util/common/NameContext.java | 43 - .../sdk/util/common/PeekingReiterator.java | 98 - .../sdk/util/common/ReflectHelpers.java | 211 -- .../dataflow/sdk/util/common/Reiterable.java | 27 - .../dataflow/sdk/util/common/Reiterator.java | 39 - .../sdk/util/common/package-info.java | 18 - .../sdk/util/common/worker/StateSampler.java | 427 --- .../sdk/util/common/worker/package-info.java | 18 - .../dataflow/sdk/util/gcsfs/GcsPath.java | 619 ---- .../dataflow/sdk/util/gcsfs/package-info.java | 18 - .../cloud/dataflow/sdk/util/package-info.java | 18 - .../util/state/AccumulatorCombiningState.java | 51 - .../dataflow/sdk/util/state/BagState.java | 26 - .../sdk/util/state/CombiningState.java | 40 - .../CopyOnAccessInMemoryStateInternals.java | 454 --- .../util/state/InMemoryStateInternals.java | 414 --- .../sdk/util/state/MergingStateAccessor.java | 40 - .../sdk/util/state/ReadableState.java | 53 - .../cloud/dataflow/sdk/util/state/State.java | 30 - .../sdk/util/state/StateAccessor.java | 36 - .../dataflow/sdk/util/state/StateContext.java | 41 - .../sdk/util/state/StateContexts.java | 107 - .../sdk/util/state/StateInternals.java | 55 - .../dataflow/sdk/util/state/StateMerging.java | 255 -- .../sdk/util/state/StateNamespace.java | 54 - .../sdk/util/state/StateNamespaceForTest.java | 63 - .../sdk/util/state/StateNamespaces.java | 277 -- .../dataflow/sdk/util/state/StateTable.java | 81 - .../dataflow/sdk/util/state/StateTag.java | 96 - .../dataflow/sdk/util/state/StateTags.java | 579 --- .../dataflow/sdk/util/state/ValueState.java | 35 - .../sdk/util/state/WatermarkHoldState.java | 42 - .../google/cloud/dataflow/sdk/values/KV.java | 130 - .../cloud/dataflow/sdk/values/PBegin.java | 87 - .../dataflow/sdk/values/PCollection.java | 250 -- .../dataflow/sdk/values/PCollectionList.java | 238 -- .../dataflow/sdk/values/PCollectionTuple.java | 264 -- .../dataflow/sdk/values/PCollectionView.java | 64 - .../cloud/dataflow/sdk/values/PDone.java | 47 - .../cloud/dataflow/sdk/values/PInput.java | 56 - .../cloud/dataflow/sdk/values/POutput.java | 76 - .../dataflow/sdk/values/POutputValueBase.java | 102 - .../cloud/dataflow/sdk/values/PValue.java | 38 - .../cloud/dataflow/sdk/values/PValueBase.java | 155 - .../dataflow/sdk/values/TimestampedValue.java | 155 - .../cloud/dataflow/sdk/values/TupleTag.java | 196 - .../dataflow/sdk/values/TupleTagList.java | 148 - .../dataflow/sdk/values/TypeDescriptor.java | 351 -- .../dataflow/sdk/values/TypedPValue.java | 197 - .../dataflow/sdk/values/package-info.java | 52 - sdk/src/main/proto/README.md | 27 - .../proto/proto2_coder_test_messages.proto | 51 - .../cloud/dataflow/sdk/DataflowMatchers.java | 65 - .../cloud/dataflow/sdk/PipelineTest.java | 296 -- .../google/cloud/dataflow/sdk/TestUtils.java | 213 -- .../cloud/dataflow/sdk/WindowMatchers.java | 142 - .../dataflow/sdk/coders/AvroCoderTest.java | 754 ---- .../sdk/coders/BigEndianIntegerCoderTest.java | 90 - .../sdk/coders/BigEndianLongCoderTest.java | 94 - .../sdk/coders/ByteArrayCoderTest.java | 144 - .../dataflow/sdk/coders/ByteCoderTest.java | 91 - .../sdk/coders/ByteStringCoderTest.java | 121 - .../sdk/coders/CoderFactoriesTest.java | 100 - .../sdk/coders/CoderProvidersTest.java | 71 - .../sdk/coders/CoderRegistryTest.java | 521 --- .../cloud/dataflow/sdk/coders/CoderTest.java | 78 - .../sdk/coders/CollectionCoderTest.java | 93 - .../dataflow/sdk/coders/CustomCoderTest.java | 135 - .../dataflow/sdk/coders/DefaultCoderTest.java | 128 - .../sdk/coders/DelegateCoderTest.java | 141 - .../dataflow/sdk/coders/DoubleCoderTest.java | 96 - .../sdk/coders/DurationCoderTest.java | 86 - .../dataflow/sdk/coders/EntityCoderTest.java | 109 - .../dataflow/sdk/coders/InstantCoderTest.java | 116 - .../sdk/coders/IterableCoderTest.java | 109 - .../dataflow/sdk/coders/JAXBCoderTest.java | 162 - .../dataflow/sdk/coders/KvCoderTest.java | 118 - .../dataflow/sdk/coders/ListCoderTest.java | 134 - .../dataflow/sdk/coders/MapCoderTest.java | 106 - .../sdk/coders/NullableCoderTest.java | 132 - .../sdk/coders/PrintBase64Encodings.java | 81 - .../dataflow/sdk/coders/Proto2CoderTest.java | 145 - .../sdk/coders/SerializableCoderTest.java | 222 -- .../dataflow/sdk/coders/SetCoderTest.java | 86 - .../sdk/coders/StandardCoderTest.java | 176 - .../sdk/coders/StringDelegateCoderTest.java | 72 - .../sdk/coders/StringUtf8CoderTest.java | 80 - .../sdk/coders/StructuralByteArrayTest.java | 39 - .../sdk/coders/TableRowJsonCoderTest.java | 86 - .../sdk/coders/TextualIntegerCoderTest.java | 90 - .../dataflow/sdk/coders/VarIntCoderTest.java | 91 - .../dataflow/sdk/coders/VarLongCoderTest.java | 94 - .../sdk/coders/protobuf/ProtoCoderTest.java | 182 - .../sdk/coders/protobuf/ProtobufUtilTest.java | 194 - .../sdk/io/AvroIOGeneratedClassTest.java | 374 -- .../cloud/dataflow/sdk/io/AvroIOTest.java | 322 -- .../cloud/dataflow/sdk/io/AvroSourceTest.java | 843 ----- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 1751 --------- .../BoundedReadFromUnboundedSourceTest.java | 141 - .../dataflow/sdk/io/CompressedSourceTest.java | 654 ---- .../dataflow/sdk/io/CountingInputTest.java | 184 - .../dataflow/sdk/io/CountingSourceTest.java | 320 -- .../dataflow/sdk/io/DatastoreIOTest.java | 693 ---- .../dataflow/sdk/io/FileBasedSinkTest.java | 518 --- .../dataflow/sdk/io/FileBasedSourceTest.java | 926 ----- .../sdk/io/OffsetBasedSourceTest.java | 343 -- .../cloud/dataflow/sdk/io/PubsubIOTest.java | 170 - .../sdk/io/PubsubUnboundedSinkTest.java | 165 - .../sdk/io/PubsubUnboundedSourceTest.java | 323 -- .../cloud/dataflow/sdk/io/ReadTest.java | 235 -- .../cloud/dataflow/sdk/io/TextIOTest.java | 1092 ------ .../cloud/dataflow/sdk/io/WriteTest.java | 541 --- .../cloud/dataflow/sdk/io/XmlSinkTest.java | 252 -- .../cloud/dataflow/sdk/io/XmlSourceTest.java | 854 ----- .../sdk/io/bigtable/BigtableIOTest.java | 895 ----- .../sdk/io/datastore/DatastoreV1Test.java | 776 ---- .../ByteKeyRangeEstimateFractionTest.java | 69 - .../range/ByteKeyRangeInterpolateKeyTest.java | 73 - .../sdk/io/range/ByteKeyRangeTest.java | 396 -- .../sdk/io/range/ByteKeyRangeTrackerTest.java | 208 -- .../dataflow/sdk/io/range/ByteKeyTest.java | 178 - .../sdk/io/range/OffsetRangeTrackerTest.java | 236 -- .../google/cloud/dataflow/sdk/io/user.avsc | 10 - .../DataflowPipelineDebugOptionsTest.java | 40 - .../options/DataflowPipelineOptionsTest.java | 91 - .../options/DataflowProfilingOptionsTest.java | 47 - .../DataflowWorkerLoggingOptionsTest.java | 73 - .../dataflow/sdk/options/GcpOptionsTest.java | 123 - .../options/GoogleApiDebugOptionsTest.java | 147 - .../options/PipelineOptionsFactoryTest.java | 1418 ------- .../options/PipelineOptionsReflectorTest.java | 225 -- .../sdk/options/PipelineOptionsTest.java | 148 - .../options/PipelineOptionsValidatorTest.java | 310 -- .../options/ProxyInvocationHandlerTest.java | 973 ----- .../sdk/options/ValueProviderTest.java | 292 -- .../sdk/options/ValueProviderUtilsTest.java | 77 - .../AggregatorPipelineExtractorTest.java | 228 -- .../BlockingDataflowPipelineRunnerTest.java | 301 -- .../sdk/runners/DataflowPipelineJobTest.java | 648 ---- .../DataflowPipelineRegistrarTest.java | 72 - .../runners/DataflowPipelineRunnerTest.java | 1483 -------- .../sdk/runners/DataflowPipelineTest.java | 44 - .../DataflowPipelineTranslatorTest.java | 1018 ------ .../runners/DirectPipelineRegistrarTest.java | 69 - .../sdk/runners/DirectPipelineRunnerTest.java | 212 -- .../sdk/runners/DirectPipelineTest.java | 34 - .../sdk/runners/PipelineRunnerTest.java | 82 - .../TemplatingDataflowPipelineRunnerTest.java | 137 - .../sdk/runners/TransformTreeTest.java | 194 - ...lowUnboundedReadFromBoundedSourceTest.java | 419 --- .../runners/dataflow/TestCountingSource.java | 256 -- .../dataflow/TestCountingSourceTest.java | 72 - .../BoundedReadEvaluatorFactoryTest.java | 278 -- .../inprocess/CommittedResultTest.java | 113 - .../ConsumerTrackingPipelineVisitorTest.java | 270 -- .../EncodabilityEnforcementFactoryTest.java | 264 -- .../FlattenEvaluatorFactoryTest.java | 139 - .../inprocess/ForwardingPTransformTest.java | 110 - .../GroupByKeyEvaluatorFactoryTest.java | 191 - ...ImmutabilityCheckingBundleFactoryTest.java | 225 -- .../ImmutabilityEnforcementFactoryTest.java | 127 - .../InMemoryWatermarkManagerTest.java | 1429 -------- .../inprocess/InProcessBundleFactoryTest.java | 228 -- .../inprocess/InProcessCreateTest.java | 229 -- .../InProcessEvaluationContextTest.java | 543 --- .../InProcessPipelineRegistrarTest.java | 71 - .../InProcessPipelineRunnerTest.java | 246 -- .../InProcessSideInputContainerTest.java | 517 --- .../InProcessTimerInternalsTest.java | 132 - .../KeyedPValueTrackingVisitorTest.java | 189 - .../LockedKeyedResourcePoolTest.java | 161 - .../sdk/runners/inprocess/MockClock.java | 60 - .../ParDoInProcessEvaluatorTest.java | 211 -- .../ParDoMultiEvaluatorFactoryTest.java | 432 --- .../ParDoSingleEvaluatorFactoryTest.java | 330 -- .../inprocess/StepTransformResultTest.java | 88 - .../runners/inprocess/StructuralKeyTest.java | 79 - .../TestStreamEvaluatorFactoryTest.java | 213 -- .../TransformExecutorServicesTest.java | 100 - .../inprocess/TransformExecutorTest.java | 565 --- .../UnboundedReadDeduplicatorTest.java | 132 - .../UnboundedReadEvaluatorFactoryTest.java | 411 --- .../inprocess/ViewEvaluatorFactoryTest.java | 99 - .../WatermarkCallbackExecutorTest.java | 128 - .../inprocess/WindowEvaluatorFactoryTest.java | 219 -- .../WriteWithShardingFactoryTest.java | 291 -- .../sdk/testing/CoderPropertiesTest.java | 214 -- .../sdk/testing/DataflowAssertTest.java | 429 --- .../sdk/testing/DataflowJUnitTestRunner.java | 129 - .../dataflow/sdk/testing/ExpectedLogs.java | 306 -- .../sdk/testing/ExpectedLogsTest.java | 153 - .../sdk/testing/FastNanoClockAndSleeper.java | 47 - .../testing/FastNanoClockAndSleeperTest.java | 47 - .../sdk/testing/PCollectionViewTesting.java | 295 -- .../sdk/testing/PaneExtractorsTest.java | 321 -- .../sdk/testing/ResetDateTimeProvider.java | 41 - .../testing/ResetDateTimeProviderTest.java | 55 - .../sdk/testing/RestoreSystemProperties.java | 49 - .../testing/RestoreSystemPropertiesTest.java | 50 - .../sdk/testing/SerializableMatchersTest.java | 165 - .../sdk/testing/SourceTestUtilsTest.java | 64 - .../sdk/testing/StaticWindowsTest.java | 91 - .../sdk/testing/SystemNanoTimeSleeper.java | 68 - .../testing/SystemNanoTimeSleeperTest.java | 53 - .../TestDataflowPipelineRunnerTest.java | 317 -- .../sdk/testing/TestPipelineTest.java | 93 - .../dataflow/sdk/testing/TestStreamTest.java | 379 -- .../sdk/testing/WindowSupplierTest.java | 89 - .../transforms/ApproximateQuantilesTest.java | 313 -- .../sdk/transforms/ApproximateUniqueTest.java | 308 -- .../sdk/transforms/CombineFnsTest.java | 480 --- .../dataflow/sdk/transforms/CombineTest.java | 1195 ------ .../dataflow/sdk/transforms/CountTest.java | 121 - .../dataflow/sdk/transforms/CreateTest.java | 240 -- .../sdk/transforms/DoFnContextTest.java | 68 - .../DoFnDelegatingAggregatorTest.java | 143 - .../sdk/transforms/DoFnReflectorTest.java | 493 --- .../dataflow/sdk/transforms/DoFnTest.java | 201 - .../sdk/transforms/DoFnTesterTest.java | 253 -- .../sdk/transforms/DoFnWithContextTest.java | 231 -- .../dataflow/sdk/transforms/FilterTest.java | 180 - .../sdk/transforms/FlatMapElementsTest.java | 124 - .../dataflow/sdk/transforms/FlattenTest.java | 388 -- .../sdk/transforms/GroupByKeyTest.java | 454 --- .../IntraBundleParallelizationTest.java | 278 -- .../dataflow/sdk/transforms/KeysTest.java | 83 - .../dataflow/sdk/transforms/KvSwapTest.java | 91 - .../sdk/transforms/MapElementsTest.java | 187 - .../dataflow/sdk/transforms/MaxTest.java | 78 - .../dataflow/sdk/transforms/MeanTest.java | 72 - .../dataflow/sdk/transforms/MinTest.java | 79 - .../dataflow/sdk/transforms/NoOpDoFn.java | 143 - .../sdk/transforms/PTransformTest.java | 41 - .../dataflow/sdk/transforms/ParDoTest.java | 1592 -------- .../sdk/transforms/PartitionTest.java | 153 - .../sdk/transforms/RemoveDuplicatesTest.java | 131 - .../dataflow/sdk/transforms/SampleTest.java | 274 -- .../sdk/transforms/SimpleStatsFnsTest.java | 129 - .../dataflow/sdk/transforms/SumTest.java | 66 - .../dataflow/sdk/transforms/TopTest.java | 273 -- .../dataflow/sdk/transforms/ValuesTest.java | 93 - .../dataflow/sdk/transforms/ViewTest.java | 1549 -------- .../dataflow/sdk/transforms/WithKeysTest.java | 127 - .../sdk/transforms/WithTimestampsTest.java | 209 -- .../display/DataflowDisplayDataEvaluator.java | 69 - .../display/DisplayDataEvaluator.java | 173 - .../display/DisplayDataEvaluatorTest.java | 94 - .../display/DisplayDataMatchers.java | 361 -- .../display/DisplayDataMatchersTest.java | 155 - .../transforms/display/DisplayDataTest.java | 1218 ------ .../transforms/join/CoGbkResultCoderTest.java | 85 - .../sdk/transforms/join/CoGbkResultTest.java | 124 - .../sdk/transforms/join/CoGroupByKeyTest.java | 507 --- .../sdk/transforms/join/UnionCoderTest.java | 48 - .../transforms/windowing/AfterAllTest.java | 156 - .../transforms/windowing/AfterEachTest.java | 132 - .../transforms/windowing/AfterFirstTest.java | 181 - .../transforms/windowing/AfterPaneTest.java | 132 - .../windowing/AfterProcessingTimeTest.java | 188 - .../AfterSynchronizedProcessingTimeTest.java | 121 - .../windowing/AfterWatermarkTest.java | 374 -- .../windowing/CalendarWindowsTest.java | 292 -- .../windowing/DefaultTriggerTest.java | 176 - .../windowing/FixedWindowsTest.java | 139 - .../windowing/IntervalWindowTest.java | 94 - .../sdk/transforms/windowing/NeverTest.java | 54 - .../windowing/OrFinallyTriggerTest.java | 215 -- .../transforms/windowing/PaneInfoTest.java | 75 - .../transforms/windowing/RepeatedlyTest.java | 224 -- .../transforms/windowing/SessionsTest.java | 166 - .../windowing/SlidingWindowsTest.java | 214 -- .../sdk/transforms/windowing/StubTrigger.java | 70 - .../sdk/transforms/windowing/TriggerTest.java | 117 - .../sdk/transforms/windowing/WindowTest.java | 288 -- .../transforms/windowing/WindowingTest.java | 244 -- .../dataflow/sdk/util/ApiSurfaceTest.java | 186 - ...tAndTimeBoundedExponentialBackOffTest.java | 213 -- .../AttemptBoundedExponentialBackOffTest.java | 86 - .../dataflow/sdk/util/AvroUtilsTest.java | 249 -- .../sdk/util/BatchTimerInternalsTest.java | 151 - .../sdk/util/BigQueryServicesImplTest.java | 353 -- .../sdk/util/BigQueryTableInserterTest.java | 389 -- .../util/BigQueryTableRowIteratorTest.java | 356 -- .../dataflow/sdk/util/BigQueryUtilTest.java | 479 --- .../sdk/util/BucketingFunctionTest.java | 103 - ...fferedElementCountingOutputStreamTest.java | 205 -- .../dataflow/sdk/util/CoderUtilsTest.java | 229 -- .../dataflow/sdk/util/CombineFnUtilTest.java | 62 - .../sdk/util/CounterAggregatorTest.java | 253 -- .../sdk/util/DataflowPathValidatorTest.java | 92 - .../sdk/util/ExecutableTriggerTest.java | 130 - .../util/ExposedByteArrayInputStreamTest.java | 78 - .../ExposedByteArrayOutputStreamTest.java | 245 -- .../sdk/util/FileIOChannelFactoryTest.java | 226 -- .../sdk/util/FinishedTriggersBitSetTest.java | 54 - .../sdk/util/FinishedTriggersProperties.java | 109 - .../sdk/util/FinishedTriggersSetTest.java | 60 - .../dataflow/sdk/util/FluentBackoffTest.java | 226 -- .../dataflow/sdk/util/GatherAllPanesTest.java | 129 - .../sdk/util/GcsIOChannelFactoryTest.java | 43 - .../cloud/dataflow/sdk/util/GcsUtilTest.java | 558 --- .../util/GroupAlsoByWindowsProperties.java | 691 ---- ...pAlsoByWindowsViaOutputBufferDoFnTest.java | 111 - .../dataflow/sdk/util/IOChannelUtilsTest.java | 94 - .../sdk/util/IdentitySideInputWindowFn.java | 52 - .../sdk/util/InstanceBuilderTest.java | 115 - ...IntervalBoundedExponentialBackOffTest.java | 100 - .../sdk/util/KeyedWorkItemCoderTest.java | 61 - .../util/LateDataDroppingDoFnRunnerTest.java | 117 - .../sdk/util/MergingActiveWindowSetTest.java | 263 -- .../dataflow/sdk/util/MonitoringUtilTest.java | 146 - .../dataflow/sdk/util/MovingFunctionTest.java | 114 - .../sdk/util/MutationDetectorsTest.java | 148 - .../cloud/dataflow/sdk/util/PTupleTest.java | 40 - .../dataflow/sdk/util/PackageUtilTest.java | 482 --- .../dataflow/sdk/util/PubsubClientTest.java | 190 - .../sdk/util/PubsubGrpcClientTest.java | 171 - .../sdk/util/PubsubJsonClientTest.java | 134 - .../sdk/util/PubsubTestClientTest.java | 116 - .../util/PushbackSideInputDoFnRunnerTest.java | 231 -- .../sdk/util/RandomAccessDataTest.java | 205 -- .../dataflow/sdk/util/ReduceFnRunnerTest.java | 1450 -------- .../dataflow/sdk/util/ReduceFnTester.java | 781 ---- .../dataflow/sdk/util/ReshuffleTest.java | 208 -- .../sdk/util/ReshuffleTriggerTest.java | 66 - .../util/RetryHttpRequestInitializerTest.java | 296 -- .../sdk/util/SerializableUtilsTest.java | 165 - .../dataflow/sdk/util/SerializerTest.java | 162 - .../sdk/util/SimpleDoFnRunnerTest.java | 86 - .../dataflow/sdk/util/StreamUtilsTest.java | 71 - .../dataflow/sdk/util/StringUtilsTest.java | 145 - .../cloud/dataflow/sdk/util/StructsTest.java | 206 -- .../cloud/dataflow/sdk/util/TimeUtilTest.java | 73 - .../dataflow/sdk/util/TimerInternalsTest.java | 99 - .../dataflow/sdk/util/TriggerTester.java | 596 --- .../sdk/util/UnownedInputStreamTest.java | 76 - .../sdk/util/UnownedOutputStreamTest.java | 57 - .../util/UploadIdResponseInterceptorTest.java | 99 - .../sdk/util/UserCodeExceptionTest.java | 182 - .../cloud/dataflow/sdk/util/VarIntTest.java | 277 -- .../dataflow/sdk/util/WindowedValueTest.java | 109 - .../cloud/dataflow/sdk/util/ZipFilesTest.java | 311 -- .../sdk/util/common/CounterSetTest.java | 345 -- .../dataflow/sdk/util/common/CounterTest.java | 747 ---- .../sdk/util/common/CounterTestUtils.java | 56 - .../sdk/util/common/ReflectHelpersTest.java | 126 - .../dataflow/sdk/util/gcsfs/GcsPathTest.java | 333 -- ...opyOnAccessInMemoryStateInternalsTest.java | 553 --- .../state/InMemoryStateInternalsTest.java | 348 -- .../sdk/util/state/StateNamespacesTest.java | 129 - .../dataflow/sdk/util/state/StateTagTest.java | 173 - .../cloud/dataflow/sdk/values/KVTest.java | 112 - .../sdk/values/PCollectionListTest.java | 47 - .../sdk/values/PCollectionTupleTest.java | 93 - .../cloud/dataflow/sdk/values/PDoneTest.java | 102 - .../dataflow/sdk/values/TupleTagTest.java | 87 - .../sdk/values/TypeDescriptorTest.java | 193 - .../dataflow/sdk/values/TypedPValueTest.java | 164 - .../PipelineOptionsFactoryJava8Test.java | 90 - .../sdk/transforms/CombineJava8Test.java | 175 - .../sdk/transforms/FilterJava8Test.java | 118 - .../transforms/FlatMapElementsJava8Test.java | 84 - .../sdk/transforms/MapElementsJava8Test.java | 77 - .../sdk/transforms/PartitionJava8Test.java | 74 - .../transforms/RemoveDuplicatesJava8Test.java | 99 - .../sdk/transforms/WithKeysJava8Test.java | 74 - .../transforms/WithTimestampsJava8Test.java | 66 - 822 files changed, 189124 deletions(-) delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/Pipeline.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/PipelineResult.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AtomicCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CannotProvideCoderException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactories.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProvider.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProviders.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CollectionCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CustomCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DefaultCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DelegateCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DeterministicStandardCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DoubleCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DurationCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/InstantCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableLikeCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ListCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/NullableCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SerializableCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SetCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringUtf8Coder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarIntCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarLongCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/ShardNameTemplate.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/UnboundedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ApplicationNameOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BigQueryOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BlockingDataflowPipelineOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerHarnessOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Default.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DefaultValueFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Description.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DirectPipelineOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcpOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcsOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Hidden.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsRegistrar.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/StreamingOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Validation.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/options/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorRetrievalException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorValues.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyExistsException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyUpdatedException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobCancelledException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobExecutionException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobUpdatedException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipeline.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrar.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowServiceException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipeline.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrar.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerRegistrar.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/RecordingPipelineVisitor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformHierarchy.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformTreeNode.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowAggregatorTransforms.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/Clock.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EmptyTransformEvaluator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FixedThreadPoolExecutorServiceFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/CoderProperties.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/RunnableOnService.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatcher.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineOptions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowFnTestUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Aggregator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AggregatorRetriever.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AppliedPTransform.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Create.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Flatten.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Keys.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/KvSwap.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Mean.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableComparator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableFunction.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sum.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithTimestamps.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Write.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultSchema.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKey.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/KeyedPCollectionTuple.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/RawUnionValue.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/BoundedWindow.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindow.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindow.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/InvalidWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/MergeOverlappingIntervalWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/NonMergingWindowFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFns.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PartitioningWindowFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerBuilder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppEngineEnvironment.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppliedCombineFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AssignWindowsDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BitSetCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStream.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudKnownType.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CounterAggregator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CredentialFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Credentials.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectSideInputReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnInfo.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStream.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcpCredentialFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsStager.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IllegalMutationException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/InstanceBuilder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItem.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MapAggregatorValues.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MimeTypes.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetector.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopCredentialFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopPathValidator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NullSideInputReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PTuple.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PathValidator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClient.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReifyTimestampAndWindowsDoFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializer.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Serializer.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ShardingWritableByteChannel.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SideInputReader.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Stager.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StreamUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StringUtils.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemDoFnInternal.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TestCredential.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeUtil.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedInputStream.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStream.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ValueWithRecordId.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Values.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/VarInt.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Weighted.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedValue.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowTracing.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingStrategy.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ZipFiles.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterProvider.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservable.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterable.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObserver.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/PeekingReiterator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpers.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterable.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterator.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPath.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/package-info.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/AccumulatorCombiningState.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningState.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateAccessor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ReadableState.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateAccessor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespace.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaceForTest.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaces.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkHoldState.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/KV.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PBegin.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollection.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionList.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionTuple.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionView.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PDone.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutput.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutputValueBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValue.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValueBase.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TimestampedValue.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTag.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTagList.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypedPValue.java delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/values/package-info.java delete mode 100644 sdk/src/main/proto/README.md delete mode 100644 sdk/src/main/proto/proto2_coder_test_messages.proto delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/DataflowMatchers.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/TestUtils.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderFactoriesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderProvidersTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CollectionCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CustomCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DefaultCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DelegateCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DoubleCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DurationCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/InstantCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/IterableCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/KvCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ListCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/MapCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/NullableCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/PrintBase64Encodings.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SerializableCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SetCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StandardCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringUtf8CoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarIntCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarLongCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/io/user.avsc delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GcpOptionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrarTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrarTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/MockClock.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowJUnitTestRunner.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogs.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeper.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeperTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PCollectionViewTesting.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProvider.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProviderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemPropertiesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchersTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeperTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CountTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CreateTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnContextTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnDelegatingAggregatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflectorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTesterTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KeysTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KvSwapTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/NoOpDoFn.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SimpleStatsFnsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ValuesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithKeysTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithTimestampsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DataflowDisplayDataEvaluator.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKeyTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindowTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfoTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStreamTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CoderUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidatorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStreamTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStreamTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactoryTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOChannelUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/InstanceBuilderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MutationDetectorsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PTupleTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PackageUtilTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClientTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializableUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StreamUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StringUtilsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimeUtilTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedInputStreamTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStreamTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/VarIntTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpersTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPathTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateNamespacesTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/values/KVTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionListTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionTupleTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PDoneTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TupleTagTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java delete mode 100644 sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypedPValueTest.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FilterJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/MapElementsJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/PartitionJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithKeysJava8Test.java delete mode 100644 sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithTimestampsJava8Test.java diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/Pipeline.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/Pipeline.java deleted file mode 100644 index 2cd5695455..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/Pipeline.java +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.TransformHierarchy; -import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * A {@link Pipeline} manages a directed acyclic graph of {@link PTransform PTransforms}, and the - * {@link PCollection PCollections} that the {@link PTransform}s consume and produce. - * - *

            A {@link Pipeline} is initialized with a {@link PipelineRunner} that will later - * execute the {@link Pipeline}. - * - *

            {@link Pipeline Pipelines} are independent, so they can be constructed and executed - * concurrently. - * - *

            Each {@link Pipeline} is self-contained and isolated from any other - * {@link Pipeline}. The {@link PValue PValues} that are inputs and outputs of each of a - * {@link Pipeline Pipeline's} {@link PTransform PTransforms} are also owned by that - * {@link Pipeline}. A {@link PValue} owned by one {@link Pipeline} can be read only by - * {@link PTransform PTransforms} also owned by that {@link Pipeline}. - * - *

            Here is a typical example of use: - *

             {@code
            - * // Start by defining the options for the pipeline.
            - * PipelineOptions options = PipelineOptionsFactory.create();
            - * // Then create the pipeline. The runner is determined by the options.
            - * Pipeline p = Pipeline.create(options);
            - *
            - * // A root PTransform, like TextIO.Read or Create, gets added
            - * // to the Pipeline by being applied:
            - * PCollection lines =
            - *     p.apply(TextIO.Read.from("gs://bucket/dir/file*.txt"));
            - *
            - * // A Pipeline can have multiple root transforms:
            - * PCollection moreLines =
            - *     p.apply(TextIO.Read.from("gs://bucket/other/dir/file*.txt"));
            - * PCollection yetMoreLines =
            - *     p.apply(Create.of("yet", "more", "lines").withCoder(StringUtf8Coder.of()));
            - *
            - * // Further PTransforms can be applied, in an arbitrary (acyclic) graph.
            - * // Subsequent PTransforms (and intermediate PCollections etc.) are
            - * // implicitly part of the same Pipeline.
            - * PCollection allLines =
            - *     PCollectionList.of(lines).and(moreLines).and(yetMoreLines)
            - *     .apply(new Flatten());
            - * PCollection> wordCounts =
            - *     allLines
            - *     .apply(ParDo.of(new ExtractWords()))
            - *     .apply(new Count());
            - * PCollection formattedWordCounts =
            - *     wordCounts.apply(ParDo.of(new FormatCounts()));
            - * formattedWordCounts.apply(TextIO.Write.to("gs://bucket/dir/counts.txt"));
            - *
            - * // PTransforms aren't executed when they're applied, rather they're
            - * // just added to the Pipeline.  Once the whole Pipeline of PTransforms
            - * // is constructed, the Pipeline's PTransforms can be run using a
            - * // PipelineRunner.  The default PipelineRunner executes the Pipeline
            - * // directly, sequentially, in this one process, which is useful for
            - * // unit tests and simple experiments:
            - * p.run();
            - *
            - * } 
            - */ -public class Pipeline { - private static final Logger LOG = LoggerFactory.getLogger(Pipeline.class); - - /** - * Thrown during execution of a {@link Pipeline}, whenever user code within that - * {@link Pipeline} throws an exception. - * - *

            The original exception thrown by user code may be retrieved via {@link #getCause}. - */ - public static class PipelineExecutionException extends RuntimeException { - /** - * Wraps {@code cause} into a {@link PipelineExecutionException}. - */ - public PipelineExecutionException(Throwable cause) { - super(cause); - } - } - - ///////////////////////////////////////////////////////////////////////////// - // Public operations. - - /** - * Constructs a pipeline from the provided options. - * - * @return The newly created pipeline. - */ - public static Pipeline create(PipelineOptions options) { - Pipeline pipeline = new Pipeline(PipelineRunner.fromOptions(options), options); - LOG.debug("Creating {}", pipeline); - return pipeline; - } - - /** - * Returns a {@link PBegin} owned by this Pipeline. This is useful - * as the input of a root PTransform such as {@link Read} or - * {@link Create}. - */ - public PBegin begin() { - return PBegin.in(this); - } - - /** - * Like {@link #apply(String, PTransform)} but the transform node in the {@link Pipeline} - * graph will be named according to {@link PTransform#getName}. - * - * @see #apply(String, PTransform) - */ - public OutputT apply( - PTransform root) { - return begin().apply(root); - } - - /** - * Adds a root {@link PTransform}, such as {@link Read} or {@link Create}, - * to this {@link Pipeline}. - * - *

            The node in the {@link Pipeline} graph will use the provided {@code name}. - * This name is used in various places, including the monitoring UI, logging, - * and to stably identify this node in the {@link Pipeline} graph upon update. - * - *

            Alias for {@code begin().apply(name, root)}. - */ - public OutputT apply( - String name, PTransform root) { - return begin().apply(name, root); - } - - /** - * Runs the {@link Pipeline} using its {@link PipelineRunner}. - */ - public PipelineResult run() { - LOG.debug("Running {} via {}", this, runner); - try { - return runner.run(this); - } catch (UserCodeException e) { - // This serves to replace the stack with one that ends here and - // is caused by the caught UserCodeException, thereby splicing - // out all the stack frames in between the PipelineRunner itself - // and where the worker calls into the user's code. - throw new PipelineExecutionException(e.getCause()); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - // Below here are operations that aren't normally called by users. - - /** - * Returns the {@link CoderRegistry} that this {@link Pipeline} uses. - */ - public CoderRegistry getCoderRegistry() { - if (coderRegistry == null) { - coderRegistry = new CoderRegistry(); - coderRegistry.registerStandardCoders(); - } - return coderRegistry; - } - - /** - * Sets the {@link CoderRegistry} that this {@link Pipeline} uses. - */ - public void setCoderRegistry(CoderRegistry coderRegistry) { - this.coderRegistry = coderRegistry; - } - - /** - * A {@link PipelineVisitor} can be passed into - * {@link Pipeline#traverseTopologically} to be called for each of the - * transforms and values in the {@link Pipeline}. - */ - public interface PipelineVisitor { - /** - * Called for each composite transform after all topological predecessors have been visited - * but before any of its component transforms. - */ - void enterCompositeTransform(TransformTreeNode node); - - /** - * Called for each composite transform after all of its component transforms and their outputs - * have been visited. - */ - void leaveCompositeTransform(TransformTreeNode node); - - /** - * Called for each primitive transform after all of its topological predecessors - * and inputs have been visited. - */ - void visitTransform(TransformTreeNode node); - - /** - * Called for each value after the transform that produced the value has been - * visited. - */ - void visitValue(PValue value, TransformTreeNode producer); - } - - /** - * Invokes the {@link PipelineVisitor PipelineVisitor's} - * {@link PipelineVisitor#visitTransform} and - * {@link PipelineVisitor#visitValue} operations on each of this - * {@link Pipeline Pipeline's} transform and value nodes, in forward - * topological order. - * - *

            Traversal of the {@link Pipeline} causes {@link PTransform PTransforms} and - * {@link PValue PValues} owned by the {@link Pipeline} to be marked as finished, - * at which point they may no longer be modified. - * - *

            Typically invoked by {@link PipelineRunner} subclasses. - */ - public void traverseTopologically(PipelineVisitor visitor) { - Set visitedValues = new HashSet<>(); - // Visit all the transforms, which should implicitly visit all the values. - transforms.visit(visitor, visitedValues); - if (!visitedValues.containsAll(values)) { - throw new RuntimeException( - "internal error: should have visited all the values " - + "after visiting all the transforms"); - } - } - - /** - * Like {@link #applyTransform(String, PInput, PTransform)} but defaulting to the name - * provided by the {@link PTransform}. - */ - public static - OutputT applyTransform(InputT input, - PTransform transform) { - return input.getPipeline().applyInternal(transform.getName(), input, transform); - } - - /** - * Applies the given {@code PTransform} to this input {@code InputT} and returns - * its {@code OutputT}. This uses {@code name} to identify this specific application - * of the transform. This name is used in various places, including the monitoring UI, - * logging, and to stably identify this application node in the {@link Pipeline} graph during - * update. - * - *

            Each {@link PInput} subclass that provides an {@code apply} method should delegate to - * this method to ensure proper registration with the {@link PipelineRunner}. - */ - public static - OutputT applyTransform(String name, InputT input, - PTransform transform) { - return input.getPipeline().applyInternal(name, input, transform); - } - - ///////////////////////////////////////////////////////////////////////////// - // Below here are internal operations, never called by users. - - private final PipelineRunner runner; - private final PipelineOptions options; - private final TransformHierarchy transforms = new TransformHierarchy(); - private Collection values = new ArrayList<>(); - private Set usedFullNames = new HashSet<>(); - private CoderRegistry coderRegistry; - private Multimap, AppliedPTransform> transformApplicationsForTesting = - HashMultimap.create(); - - /** - * @deprecated replaced by {@link #Pipeline(PipelineRunner, PipelineOptions)} - */ - @Deprecated - protected Pipeline(PipelineRunner runner) { - this(runner, PipelineOptionsFactory.create()); - } - - protected Pipeline(PipelineRunner runner, PipelineOptions options) { - this.runner = runner; - this.options = options; - } - - @Override - public String toString() { - return "Pipeline#" + hashCode(); - } - - /** - * Applies a {@link PTransform} to the given {@link PInput}. - * - * @see Pipeline#apply - */ - private - OutputT applyInternal(String name, InputT input, - PTransform transform) { - input.finishSpecifying(); - - TransformTreeNode parent = transforms.getCurrent(); - String namePrefix = parent.getFullName(); - String fullName = uniquifyInternal(namePrefix, name); - - boolean nameIsUnique = fullName.equals(buildName(namePrefix, name)); - - if (!nameIsUnique) { - switch (getOptions().getStableUniqueNames()) { - case OFF: - break; - case WARNING: - LOG.warn("Transform {} does not have a stable unique name. " - + "This will prevent updating of pipelines.", fullName); - break; - case ERROR: - throw new IllegalStateException( - "Transform " + fullName + " does not have a stable unique name. " - + "This will prevent updating of pipelines."); - default: - throw new IllegalArgumentException( - "Unrecognized value for stable unique names: " + getOptions().getStableUniqueNames()); - } - } - - TransformTreeNode child = - new TransformTreeNode(parent, transform, fullName, input); - parent.addComposite(child); - - transforms.addInput(child, input); - - LOG.debug("Adding {} to {}", transform, this); - try { - transforms.pushNode(child); - transform.validate(input); - OutputT output = runner.apply(transform, input); - transforms.setOutput(child, output); - - AppliedPTransform applied = AppliedPTransform.of( - child.getFullName(), input, output, transform); - transformApplicationsForTesting.put(transform, applied); - // recordAsOutput is a NOOP if already called; - output.recordAsOutput(applied); - verifyOutputState(output, child); - return output; - } finally { - transforms.popNode(); - } - } - - /** - * Returns all producing transforms for the {@link PValue PValues} contained - * in {@code output}. - */ - private List> getProducingTransforms(POutput output) { - List> producingTransforms = new ArrayList<>(); - for (PValue value : output.expand()) { - AppliedPTransform transform = value.getProducingTransformInternal(); - if (transform != null) { - producingTransforms.add(transform); - } - } - return producingTransforms; - } - - /** - * Verifies that the output of a {@link PTransform} is correctly configured in its - * {@link TransformTreeNode} in the {@link Pipeline} graph. - * - *

            A non-composite {@link PTransform} must have all - * of its outputs registered as produced by that {@link PTransform}. - * - *

            A composite {@link PTransform} must have all of its outputs - * registered as produced by the contained primitive {@link PTransform PTransforms}. - * They have each had the above check performed already, when - * they were applied, so the only possible failure state is - * that the composite {@link PTransform} has returned a primitive output. - */ - private void verifyOutputState(POutput output, TransformTreeNode node) { - if (!node.isCompositeNode()) { - PTransform thisTransform = node.getTransform(); - List> producingTransforms = getProducingTransforms(output); - for (AppliedPTransform producingTransform : producingTransforms) { - // Using != because object identity indicates that the transforms - // are the same node in the pipeline - if (thisTransform != producingTransform.getTransform()) { - throw new IllegalArgumentException("Output of non-composite transform " - + thisTransform + " is registered as being produced by" - + " a different transform: " + producingTransform); - } - } - } else { - PTransform thisTransform = node.getTransform(); - List> producingTransforms = getProducingTransforms(output); - for (AppliedPTransform producingTransform : producingTransforms) { - // Using == because object identity indicates that the transforms - // are the same node in the pipeline - if (thisTransform == producingTransform.getTransform()) { - throw new IllegalStateException("Output of composite transform " - + thisTransform + " is registered as being produced by it," - + " but the output of every composite transform should be" - + " produced by a primitive transform contained therein."); - } - } - } - } - - /** - * Returns the configured {@link PipelineRunner}. - */ - public PipelineRunner getRunner() { - return runner; - } - - /** - * Returns the configured {@link PipelineOptions}. - */ - public PipelineOptions getOptions() { - return options; - } - - /** - * @deprecated this method is no longer compatible with the design of {@link Pipeline}, - * as {@link PTransform PTransforms} can be applied multiple times, with different names - * each time. - */ - @Deprecated - public String getFullNameForTesting(PTransform transform) { - Collection> uses = - transformApplicationsForTesting.get(transform); - checkState(uses.size() > 0, "Unknown transform: " + transform); - checkState(uses.size() <= 1, "Transform used multiple times: " + transform); - return Iterables.getOnlyElement(uses).getFullName(); - } - - /** - * Returns a unique name for a transform with the given prefix (from - * enclosing transforms) and initial name. - * - *

            For internal use only. - */ - private String uniquifyInternal(String namePrefix, String origName) { - String name = origName; - int suffixNum = 2; - while (true) { - String candidate = buildName(namePrefix, name); - if (usedFullNames.add(candidate)) { - return candidate; - } - // A duplicate! Retry. - name = origName + suffixNum++; - } - } - - /** - * Builds a name from a "/"-delimited prefix and a name. - */ - private String buildName(String namePrefix, String name) { - return namePrefix.isEmpty() ? name : namePrefix + "/" + name; - } - - /** - * Adds the given {@link PValue} to this {@link Pipeline}. - * - *

            For internal use only. - */ - public void addValueInternal(PValue value) { - this.values.add(value); - LOG.debug("Adding {} to {}", value, this); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/PipelineResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/PipelineResult.java deleted file mode 100644 index 68c7bf58f9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/PipelineResult.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; -import com.google.cloud.dataflow.sdk.runners.AggregatorValues; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; - -/** - * Result of {@link Pipeline#run()}. - */ -public interface PipelineResult { - - /** - * Retrieves the current state of the pipeline execution. - * - * @return the {@link State} representing the state of this pipeline. - */ - State getState(); - - /** - * Retrieves the current value of the provided {@link Aggregator}. - * - * @param aggregator the {@link Aggregator} to retrieve values for. - * @return the current values of the {@link Aggregator}, - * which may be empty if there are no values yet. - * @throws AggregatorRetrievalException if the {@link Aggregator} values could not be retrieved. - */ - AggregatorValues getAggregatorValues(Aggregator aggregator) - throws AggregatorRetrievalException; - - // TODO: method to retrieve error messages. - - /** Named constants for common values for the job state. */ - enum State { - - /** The job state could not be obtained or was not specified. */ - UNKNOWN(false, false), - - /** The job has been paused, or has not yet started. */ - STOPPED(false, false), - - /** The job is currently running. */ - RUNNING(false, false), - - /** The job has successfully completed. */ - DONE(true, false), - - /** The job has failed. */ - FAILED(true, false), - - /** The job has been explicitly cancelled. */ - CANCELLED(true, false), - - /** The job has been updated. */ - UPDATED(true, true); - - private final boolean terminal; - - private final boolean hasReplacement; - - private State(boolean terminal, boolean hasReplacement) { - this.terminal = terminal; - this.hasReplacement = hasReplacement; - } - - /** - * @return {@code true} if the job state can no longer complete work. - */ - public final boolean isTerminal() { - return terminal; - } - - /** - * @return {@code true} if this job state indicates that a replacement job exists. - */ - public final boolean hasReplacementJob() { - return hasReplacement; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java deleted file mode 100644 index cb8bfd6e76..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/Experimental.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Signifies that a public API (public class, method or field) is subject to - * incompatible changes, or even removal, in a future release. An API bearing - * this annotation is exempt from any compatibility guarantees made by its - * containing library. Note that the presence of this annotation implies nothing - * about the quality or performance of the API in question, only the fact that - * it is not "API-frozen." - * - *

            It is generally safe for applications to depend on experimental - * APIs, at the cost of some extra work during upgrades. However, it is - * generally inadvisable for libraries (which get included on users' - * class paths, outside the library developers' control) to do so. - */ -@Retention(RetentionPolicy.CLASS) -@Target({ - ElementType.ANNOTATION_TYPE, - ElementType.CONSTRUCTOR, - ElementType.FIELD, - ElementType.METHOD, - ElementType.TYPE}) -@Documented -public @interface Experimental { - Kind value() default Kind.UNSPECIFIED; - - /** - * An enumeration of various kinds of experimental APIs. - */ - enum Kind { - /** Generic group of experimental APIs. This is the default value. */ - UNSPECIFIED, - - /** Sources and sinks related experimental APIs. */ - SOURCE_SINK, - - /** Auto-scaling related experimental APIs. */ - AUTOSCALING, - - /** Trigger-related experimental APIs. */ - TRIGGER, - - /** Aggregator-related experimental APIs. */ - AGGREGATOR, - - /** Experimental APIs for Coder binary format identifiers. */ - CODER_ENCODING_ID, - - /** State-related experimental APIs. */ - STATE, - - /** Timer-related experimental APIs. */ - TIMERS, - - /** Experimental APIs related to customizing the output time for computed values. */ - OUTPUT_TIME - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/package-info.java deleted file mode 100644 index 6c224a6a8e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/annotations/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines annotations used across the SDK. - */ -package com.google.cloud.dataflow.sdk.annotations; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AtomicCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AtomicCoder.java deleted file mode 100644 index c4951b4004..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AtomicCoder.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import java.util.Collections; -import java.util.List; - -/** - * A {@link Coder} that has no component {@link Coder Coders} or other state. - * - *

            Note that, unless the behavior is overridden, atomic coders are presumed to be deterministic - * and all instances are considered equal. - * - * @param the type of the values being transcoded - */ -public abstract class AtomicCoder extends DeterministicStandardCoder { - protected AtomicCoder() { } - - @Override - public List> getCoderArguments() { - return null; - } - - /** - * Returns a list of values contained in the provided example - * value, one per type parameter. If there are no type parameters, - * returns an empty list. - * - *

            Because {@link AtomicCoder} has no components, always returns an empty list. - * - * @param exampleValue unused, but part of the latent interface expected by - * {@link CoderFactories#fromStaticMethods} - */ - public static List getInstanceComponents(T exampleValue) { - return Collections.emptyList(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java deleted file mode 100644 index c5aa029531..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java +++ /dev/null @@ -1,714 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericDatumReader; -import org.apache.avro.generic.GenericDatumWriter; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.generic.IndexedRecord; -import org.apache.avro.io.BinaryDecoder; -import org.apache.avro.io.BinaryEncoder; -import org.apache.avro.io.DatumReader; -import org.apache.avro.io.DatumWriter; -import org.apache.avro.io.DecoderFactory; -import org.apache.avro.io.EncoderFactory; -import org.apache.avro.reflect.AvroEncode; -import org.apache.avro.reflect.AvroName; -import org.apache.avro.reflect.AvroSchema; -import org.apache.avro.reflect.ReflectData; -import org.apache.avro.reflect.ReflectDatumReader; -import org.apache.avro.reflect.ReflectDatumWriter; -import org.apache.avro.reflect.Union; -import org.apache.avro.specific.SpecificData; -import org.apache.avro.util.ClassUtils; -import org.apache.avro.util.Utf8; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; - -import javax.annotation.Nullable; - -/** - * A {@link Coder} using Avro binary format. - * - *

            Each instance of {@code AvroCoder} encapsulates an Avro schema for objects of type - * {@code T}. - * - *

            The Avro schema may be provided explicitly via {@link AvroCoder#of(Class, Schema)} or - * omitted via {@link AvroCoder#of(Class)}, in which case it will be inferred - * using Avro's {@link org.apache.avro.reflect.ReflectData}. - * - *

            For complete details about schema generation and how it can be controlled please see - * the {@link org.apache.avro.reflect} package. - * Only concrete classes with a no-argument constructor can be mapped to Avro records. - * All inherited fields that are not static or transient are included. Fields are not permitted to - * be null unless annotated by {@link Nullable} or a {@link Union} schema - * containing {@code "null"}. - * - *

            To use, specify the {@code Coder} type on a PCollection: - *

            - * {@code
            - * PCollection records =
            - *     input.apply(...)
            - *          .setCoder(AvroCoder.of(MyCustomElement.class);
            - * }
            - * 
            - * - *

            or annotate the element class using {@code @DefaultCoder}. - *

            
            - * {@literal @}DefaultCoder(AvroCoder.class)
            - * public class MyCustomElement {
            - *   ...
            - * }
            - * 
            - * - *

            The implementation attempts to determine if the Avro encoding of the given type will satisfy - * the criteria of {@link Coder#verifyDeterministic} by inspecting both the type and the - * Schema provided or generated by Avro. Only coders that are deterministic can be used in - * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey} operations. - * - * @param the type of elements handled by this coder - */ -public class AvroCoder extends StandardCoder { - - /** - * Returns an {@code AvroCoder} instance for the provided element type. - * @param the element type - */ - public static AvroCoder of(TypeDescriptor type) { - @SuppressWarnings("unchecked") - Class clazz = (Class) type.getRawType(); - return of(clazz); - } - - /** - * Returns an {@code AvroCoder} instance for the provided element class. - * @param the element type - */ - public static AvroCoder of(Class clazz) { - return new AvroCoder<>(clazz, ReflectData.get().getSchema(clazz)); - } - - /** - * Returns an {@code AvroCoder} instance for the Avro schema. The implicit - * type is GenericRecord. - */ - public static AvroCoder of(Schema schema) { - return new AvroCoder<>(GenericRecord.class, schema); - } - - /** - * Returns an {@code AvroCoder} instance for the provided element type - * using the provided Avro schema. - * - *

            If the type argument is GenericRecord, the schema may be arbitrary. - * Otherwise, the schema must correspond to the type provided. - * - * @param the element type - */ - public static AvroCoder of(Class type, Schema schema) { - return new AvroCoder<>(type, schema); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @JsonCreator - public static AvroCoder of( - @JsonProperty("type") String classType, - @JsonProperty("schema") String schema) throws ClassNotFoundException { - Schema.Parser parser = new Schema.Parser(); - return new AvroCoder(Class.forName(classType), parser.parse(schema)); - } - - public static final CoderProvider PROVIDER = new CoderProvider() { - @Override - public Coder getCoder(TypeDescriptor typeDescriptor) { - // This is a downcast from `? super T` to T. However, because - // it comes from a TypeDescriptor, the class object itself - // is the same so the supertype in question shares the same - // generated AvroCoder schema. - @SuppressWarnings("unchecked") - Class rawType = (Class) typeDescriptor.getRawType(); - return AvroCoder.of(rawType); - } - }; - - private final Class type; - private final Schema schema; - - private final List nonDeterministicReasons; - - // Factories allocated by .get() are thread-safe and immutable. - private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); - private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); - // Cache the old encoder/decoder and let the factories reuse them when possible. To be threadsafe, - // these are ThreadLocal. This code does not need to be re-entrant as AvroCoder does not use - // an inner coder. - private final ThreadLocal decoder; - private final ThreadLocal encoder; - private final ThreadLocal> writer; - private final ThreadLocal> reader; - - protected AvroCoder(Class type, Schema schema) { - this.type = type; - this.schema = schema; - - nonDeterministicReasons = new AvroDeterminismChecker().check(TypeDescriptor.of(type), schema); - - // Decoder and Encoder start off null for each thread. They are allocated and potentially - // reused inside encode/decode. - this.decoder = new ThreadLocal<>(); - this.encoder = new ThreadLocal<>(); - - // Reader and writer are allocated once per thread and are "final" for thread-local Coder - // instance. - this.reader = new ThreadLocal>() { - @Override - public DatumReader initialValue() { - return createDatumReader(); - } - }; - this.writer = new ThreadLocal>() { - @Override - public DatumWriter initialValue() { - return createDatumWriter(); - } - }; - } - - /** - * The encoding identifier is designed to support evolution as per the design of Avro - * In order to use this class effectively, carefully read the Avro - * documentation at - * Schema Resolution - * to ensure that the old and new schema match. - * - *

            In particular, this encoding identifier is guaranteed to be the same for {@code AvroCoder} - * instances of the same principal class, and otherwise distinct. The schema is not included - * in the identifier. - * - *

            When modifying a class to be encoded as Avro, here are some guidelines; see the above link - * for greater detail. - * - *

              - *
            • Avoid changing field names. - *
            • Never remove a required field. - *
            • Only add optional fields, with sensible defaults. - *
            • When changing the type of a field, consult the Avro documentation to ensure the new and - * old types are interchangeable. - *
            - * - *

            Code consuming this message class should be prepared to support all versions of - * the class until it is certain that no remaining serialized instances exist. - * - *

            If backwards incompatible changes must be made, the best recourse is to change the name - * of your class. - */ - @Override - public String getEncodingId() { - return type.getName(); - } - - /** - * Returns the type this coder encodes/decodes. - */ - public Class getType() { - return type; - } - - private Object writeReplace() { - // When serialized by Java, instances of AvroCoder should be replaced by - // a SerializedAvroCoderProxy. - return new SerializedAvroCoderProxy<>(type, schema.toString()); - } - - @Override - public void encode(T value, OutputStream outStream, Context context) throws IOException { - // Get a BinaryEncoder instance from the ThreadLocal cache and attempt to reuse it. - BinaryEncoder encoderInstance = ENCODER_FACTORY.directBinaryEncoder(outStream, encoder.get()); - // Save the potentially-new instance for reuse later. - encoder.set(encoderInstance); - writer.get().write(value, encoderInstance); - // Direct binary encoder does not buffer any data and need not be flushed. - } - - @Override - public T decode(InputStream inStream, Context context) throws IOException { - // Get a BinaryDecoder instance from the ThreadLocal cache and attempt to reuse it. - BinaryDecoder decoderInstance = DECODER_FACTORY.directBinaryDecoder(inStream, decoder.get()); - // Save the potentially-new instance for later. - decoder.set(decoderInstance); - return reader.get().read(null, decoderInstance); - } - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addString(result, "type", type.getName()); - addString(result, "schema", schema.toString()); - return result; - } - - /** - * @throws NonDeterministicException when the type may not be deterministically - * encoded using the given {@link Schema}, the {@code directBinaryEncoder}, and the - * {@link ReflectDatumWriter} or {@link GenericDatumWriter}. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - if (!nonDeterministicReasons.isEmpty()) { - throw new NonDeterministicException(this, nonDeterministicReasons); - } - } - - /** - * Returns a new {@link DatumReader} that can be used to read from an Avro file directly. Assumes - * the schema used to read is the same as the schema that was used when writing. - * - * @deprecated For {@code AvroCoder} internal use only. - */ - // TODO: once we can remove this deprecated function, inline in constructor. - @Deprecated - public DatumReader createDatumReader() { - if (type.equals(GenericRecord.class)) { - return new GenericDatumReader<>(schema); - } else { - return new ReflectDatumReader<>(schema); - } - } - - /** - * Returns a new {@link DatumWriter} that can be used to write to an Avro file directly. - * - * @deprecated For {@code AvroCoder} internal use only. - */ - // TODO: once we can remove this deprecated function, inline in constructor. - @Deprecated - public DatumWriter createDatumWriter() { - if (type.equals(GenericRecord.class)) { - return new GenericDatumWriter<>(schema); - } else { - return new ReflectDatumWriter<>(schema); - } - } - - /** - * Returns the schema used by this coder. - */ - public Schema getSchema() { - return schema; - } - - /** - * Proxy to use in place of serializing the {@link AvroCoder}. This allows the fields - * to remain final. - */ - private static class SerializedAvroCoderProxy implements Serializable { - private final Class type; - private final String schemaStr; - - public SerializedAvroCoderProxy(Class type, String schemaStr) { - this.type = type; - this.schemaStr = schemaStr; - } - - private Object readResolve() { - // When deserialized, instances of this object should be replaced by - // constructing an AvroCoder. - Schema.Parser parser = new Schema.Parser(); - return new AvroCoder(type, parser.parse(schemaStr)); - } - } - - /** - * Helper class encapsulating the various pieces of state maintained by the - * recursive walk used for checking if the encoding will be deterministic. - */ - private static class AvroDeterminismChecker { - - // Reasons that the original type are not deterministic. This accumulates - // the actual output. - private List reasons = new ArrayList<>(); - - // Types that are currently "open". Used to make sure we don't have any - // recursive types. Note that we assume that all occurrences of a given type - // are equal, rather than tracking pairs of type + schema. - private Set> activeTypes = new HashSet<>(); - - // Similarly to how we record active types, we record the schemas we visit - // to make sure we don't encounter recursive fields. - private Set activeSchemas = new HashSet<>(); - - /** - * Report an error in the current context. - */ - private void reportError(String context, String fmt, Object... args) { - String message = String.format(fmt, args); - reasons.add(context + ": " + message); - } - - /** - * Classes that are serialized by Avro as a String include - *

              - *
            • Subtypes of CharSequence (including String, Avro's mutable Utf8, etc.) - *
            • Several predefined classes (BigDecimal, BigInteger, URI, URL) - *
            • Classes annotated with @Stringable (uses their #toString() and a String constructor) - *
            - * - *

            Rather than determine which of these cases are deterministic, we list some classes - * that definitely are, and treat any others as non-deterministic. - */ - private static final Set> DETERMINISTIC_STRINGABLE_CLASSES = new HashSet<>(); - static { - // CharSequences: - DETERMINISTIC_STRINGABLE_CLASSES.add(String.class); - DETERMINISTIC_STRINGABLE_CLASSES.add(Utf8.class); - - // Explicitly Stringable: - DETERMINISTIC_STRINGABLE_CLASSES.add(java.math.BigDecimal.class); - DETERMINISTIC_STRINGABLE_CLASSES.add(java.math.BigInteger.class); - DETERMINISTIC_STRINGABLE_CLASSES.add(java.net.URI.class); - DETERMINISTIC_STRINGABLE_CLASSES.add(java.net.URL.class); - - // Classes annotated with @Stringable: - } - - /** - * Return true if the given type token is a subtype of *any* of the listed parents. - */ - private static boolean isSubtypeOf(TypeDescriptor type, Class... parents) { - for (Class parent : parents) { - if (type.isSubtypeOf(TypeDescriptor.of(parent))) { - return true; - } - } - return false; - } - - protected AvroDeterminismChecker() {} - - // The entry point for the check. Should not be recursively called. - public List check(TypeDescriptor type, Schema schema) { - recurse(type.getRawType().getName(), type, schema); - return reasons; - } - - // This is the method that should be recursively called. It sets up the path - // and visited types correctly. - private void recurse(String context, TypeDescriptor type, Schema schema) { - if (type.getRawType().isAnnotationPresent(AvroSchema.class)) { - reportError(context, "Custom schemas are not supported -- remove @AvroSchema."); - return; - } - - if (!activeTypes.add(type)) { - reportError(context, "%s appears recursively", type); - return; - } - - // If the the record isn't a true class, but rather a GenericRecord, SpecificRecord, etc. - // with a specified schema, then we need to make the decision based on the generated - // implementations. - if (isSubtypeOf(type, IndexedRecord.class)) { - checkIndexedRecord(context, schema, null); - } else { - doCheck(context, type, schema); - } - - activeTypes.remove(type); - } - - private void doCheck(String context, TypeDescriptor type, Schema schema) { - switch (schema.getType()) { - case ARRAY: - checkArray(context, type, schema); - break; - case ENUM: - // Enums should be deterministic, since they depend only on the ordinal. - break; - case FIXED: - // Depending on the implementation of GenericFixed, we don't know how - // the given field will be encoded. So, we assume that it isn't - // deterministic. - reportError(context, "FIXED encodings are not guaranteed to be deterministic"); - break; - case MAP: - checkMap(context, type, schema); - break; - case RECORD: - checkRecord(type, schema); - break; - case UNION: - checkUnion(context, type, schema); - break; - case STRING: - checkString(context, type); - break; - case BOOLEAN: - case BYTES: - case DOUBLE: - case INT: - case FLOAT: - case LONG: - case NULL: - // For types that Avro encodes using one of the above primitives, we assume they are - // deterministic. - break; - default: - // In any other case (eg., new types added to Avro) we cautiously return - // false. - reportError(context, "Unknown schema type %s may be non-deterministic", schema.getType()); - break; - } - } - - private void checkString(String context, TypeDescriptor type) { - // For types that are encoded as strings, we need to make sure they're in an approved - // whitelist. For other types that are annotated @Stringable, Avro will just use the - // #toString() methods, which has no guarantees of determinism. - if (!DETERMINISTIC_STRINGABLE_CLASSES.contains(type.getRawType())) { - reportError(context, "%s may not have deterministic #toString()", type); - } - } - - private static final Schema AVRO_NULL_SCHEMA = Schema.create(Schema.Type.NULL); - - private void checkUnion(String context, TypeDescriptor type, Schema schema) { - final List unionTypes = schema.getTypes(); - - if (!type.getRawType().isAnnotationPresent(Union.class)) { - // First check for @Nullable field, which shows up as a union of field type and null. - if (unionTypes.size() == 2 && unionTypes.contains(AVRO_NULL_SCHEMA)) { - // Find the Schema that is not NULL and recursively check that it is deterministic. - Schema nullableFieldSchema = unionTypes.get(0).equals(AVRO_NULL_SCHEMA) - ? unionTypes.get(1) : unionTypes.get(0); - doCheck(context, type, nullableFieldSchema); - return; - } - - // Otherwise report a schema error. - reportError(context, "Expected type %s to have @Union annotation", type); - return; - } - - // Errors associated with this union will use the base class as their context. - String baseClassContext = type.getRawType().getName(); - - // For a union, we need to make sure that each possible instantiation is deterministic. - for (Schema concrete : unionTypes) { - @SuppressWarnings("unchecked") - TypeDescriptor unionType = TypeDescriptor.of(ReflectData.get().getClass(concrete)); - - recurse(baseClassContext, unionType, concrete); - } - } - - private void checkRecord(TypeDescriptor type, Schema schema) { - // For a record, we want to make sure that all the fields are deterministic. - Class clazz = type.getRawType(); - for (org.apache.avro.Schema.Field fieldSchema : schema.getFields()) { - Field field = getField(clazz, fieldSchema.name()); - String fieldContext = field.getDeclaringClass().getName() + "#" + field.getName(); - - if (field.isAnnotationPresent(AvroEncode.class)) { - reportError(fieldContext, - "Custom encoders may be non-deterministic -- remove @AvroEncode"); - continue; - } - - if (!IndexedRecord.class.isAssignableFrom(field.getType()) - && field.isAnnotationPresent(AvroSchema.class)) { - // TODO: We should be able to support custom schemas on POJO fields, but we shouldn't - // need to, so we just allow it in the case of IndexedRecords. - reportError(fieldContext, - "Custom schemas are only supported for subtypes of IndexedRecord."); - continue; - } - - TypeDescriptor fieldType = type.resolveType(field.getGenericType()); - recurse(fieldContext, fieldType, fieldSchema.schema()); - } - } - - private void checkIndexedRecord(String context, Schema schema, - @Nullable String specificClassStr) { - - if (!activeSchemas.add(schema)) { - reportError(context, "%s appears recursively", schema.getName()); - return; - } - - switch (schema.getType()) { - case ARRAY: - // Generic Records use GenericData.Array to implement arrays, which is - // essentially an ArrayList, and therefore ordering is deterministic. - // The array is thus deterministic if the elements are deterministic. - checkIndexedRecord(context, schema.getElementType(), null); - break; - case ENUM: - // Enums are deterministic because they encode as a single integer. - break; - case FIXED: - // In the case of GenericRecords, FIXED is deterministic because it - // encodes/decodes as a Byte[]. - break; - case MAP: - reportError(context, - "GenericRecord and SpecificRecords use a HashMap to represent MAPs," - + " so it is non-deterministic"); - break; - case RECORD: - for (org.apache.avro.Schema.Field field : schema.getFields()) { - checkIndexedRecord( - schema.getName() + "." + field.name(), - field.schema(), - field.getProp(SpecificData.CLASS_PROP)); - } - break; - case STRING: - // GenericDatumWriter#findStringClass will use a CharSequence or a String - // for each string, so it is deterministic. - - // SpecificCompiler#getStringType will use java.lang.String, org.apache.avro.util.Utf8, - // or java.lang.CharSequence, unless SpecificData.CLASS_PROP overrides that. - if (specificClassStr != null) { - Class specificClass; - try { - specificClass = ClassUtils.forName(specificClassStr); - if (!DETERMINISTIC_STRINGABLE_CLASSES.contains(specificClass)) { - reportError(context, "Specific class %s is not known to be deterministic", - specificClassStr); - } - } catch (ClassNotFoundException e) { - reportError(context, "Specific class %s is not known to be deterministic", - specificClassStr); - } - } - break; - case UNION: - for (org.apache.avro.Schema subschema : schema.getTypes()) { - checkIndexedRecord(subschema.getName(), subschema, null); - } - break; - case BOOLEAN: - case BYTES: - case DOUBLE: - case INT: - case FLOAT: - case LONG: - case NULL: - // For types that Avro encodes using one of the above primitives, we assume they are - // deterministic. - break; - default: - reportError(context, "Unknown schema type %s may be non-deterministic", schema.getType()); - break; - } - - activeSchemas.remove(schema); - } - - private void checkMap(String context, TypeDescriptor type, Schema schema) { - if (!isSubtypeOf(type, SortedMap.class)) { - reportError(context, "%s may not be deterministically ordered", type); - } - - // Avro (currently) asserts that all keys are strings. - // In case that changes, we double check that the key was a string: - Class keyType = type.resolveType(Map.class.getTypeParameters()[0]).getRawType(); - if (!String.class.equals(keyType)) { - reportError(context, "map keys should be Strings, but was %s", keyType); - } - - recurse(context, - type.resolveType(Map.class.getTypeParameters()[1]), - schema.getValueType()); - } - - private void checkArray(String context, TypeDescriptor type, Schema schema) { - TypeDescriptor elementType = null; - if (type.isArray()) { - // The type is an array (with ordering)-> deterministic iff the element is deterministic. - elementType = type.getComponentType(); - } else if (isSubtypeOf(type, Collection.class)) { - if (isSubtypeOf(type, List.class, SortedSet.class)) { - // Ordered collection -> deterministic iff the element is deterministic - elementType = type.resolveType(Collection.class.getTypeParameters()[0]); - } else { - // Not an ordered collection -> not deterministic - reportError(context, "%s may not be deterministically ordered", type); - return; - } - } else { - // If it was an unknown type encoded as an array, be conservative and assume - // that we don't know anything about the order. - reportError(context, "encoding %s as an ARRAY was unexpected", type); - return; - } - - // If we get here, it's either a deterministically-ordered Collection, or - // an array. Either way, the type is deterministic iff the element type is - // deterministic. - recurse(context, elementType, schema.getElementType()); - } - - /** - * Extract a field from a class. We need to look at the declared fields so that we can - * see private fields. We may need to walk up to the parent to get classes from the parent. - */ - private static Field getField(Class clazz, String name) { - while (clazz != null) { - for (Field field : clazz.getDeclaredFields()) { - AvroName avroName = field.getAnnotation(AvroName.class); - if (avroName != null && name.equals(avroName.value())) { - return field; - } else if (avroName == null && name.equals(field.getName())) { - return field; - } - } - clazz = clazz.getSuperclass(); - } - - throw new IllegalArgumentException( - "Unable to get field " + name + " from class " + clazz); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoder.java deleted file mode 100644 index 24f6a45433..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoder.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UTFDataFormatException; - -/** - * A {@link BigEndianIntegerCoder} encodes {@link Integer Integers} in 4 bytes, big-endian. - */ -public class BigEndianIntegerCoder extends AtomicCoder { - - @JsonCreator - public static BigEndianIntegerCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final BigEndianIntegerCoder INSTANCE = new BigEndianIntegerCoder(); - - private BigEndianIntegerCoder() {} - - @Override - public void encode(Integer value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Integer"); - } - new DataOutputStream(outStream).writeInt(value); - } - - @Override - public Integer decode(InputStream inStream, Context context) - throws IOException, CoderException { - try { - return new DataInputStream(inStream).readInt(); - } catch (EOFException | UTFDataFormatException exn) { - // These exceptions correspond to decoding problems, so change - // what kind of exception they're branded as. - throw new CoderException(exn); - } - } - - /** - * {@inheritDoc} - * - * @return {@code true}. This coder is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}, because {@link #getEncodedElementByteSize} runs in constant time. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Integer value, Context context) { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code 4}, the size in bytes of an integer's big endian encoding. - */ - @Override - protected long getEncodedElementByteSize(Integer value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null Integer"); - } - return 4; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoder.java deleted file mode 100644 index 4196608b54..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoder.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UTFDataFormatException; - -/** - * A {@link BigEndianLongCoder} encodes {@link Long}s in 8 bytes, big-endian. - */ -public class BigEndianLongCoder extends AtomicCoder { - - @JsonCreator - public static BigEndianLongCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final BigEndianLongCoder INSTANCE = new BigEndianLongCoder(); - - private BigEndianLongCoder() {} - - @Override - public void encode(Long value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Long"); - } - new DataOutputStream(outStream).writeLong(value); - } - - @Override - public Long decode(InputStream inStream, Context context) - throws IOException, CoderException { - try { - return new DataInputStream(inStream).readLong(); - } catch (EOFException | UTFDataFormatException exn) { - // These exceptions correspond to decoding problems, so change - // what kind of exception they're branded as. - throw new CoderException(exn); - } - } - - /** - * {@inheritDoc} - * - * @return {@code true}. This coder is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}, since {@link #getEncodedElementByteSize} returns a constant. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Long value, Context context) { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code 8}, the byte size of a big-endian encoded {@code Long}. - */ - @Override - protected long getEncodedElementByteSize(Long value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null Long"); - } - return 8; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java deleted file mode 100644 index 1e555c67bf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoder.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.ExposedByteArrayOutputStream; -import com.google.cloud.dataflow.sdk.util.StreamUtils; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.common.io.ByteStreams; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} for {@code byte[]}. - * - *

            The encoding format is as follows: - *

              - *
            • If in a non-nested context (the {@code byte[]} is the only value in the stream), the - * bytes are read/written directly.
            • - *
            • If in a nested context, the bytes are prefixed with the length of the array, - * encoded via a {@link VarIntCoder}.
            • - *
            - */ -public class ByteArrayCoder extends AtomicCoder { - - @JsonCreator - public static ByteArrayCoder of() { - return INSTANCE; - } - - - ///////////////////////////////////////////////////////////////////////////// - - private static final ByteArrayCoder INSTANCE = new ByteArrayCoder(); - - private ByteArrayCoder() {} - - @Override - public void encode(byte[] value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null byte[]"); - } - if (!context.isWholeStream) { - VarInt.encode(value.length, outStream); - outStream.write(value); - } else { - outStream.write(value); - } - } - - /** - * Encodes the provided {@code value} with the identical encoding to {@link #encode}, but with - * optimizations that take ownership of the value. - * - *

            Once passed to this method, {@code value} should never be observed or mutated again. - */ - public void encodeAndOwn(byte[] value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (!context.isWholeStream) { - VarInt.encode(value.length, outStream); - outStream.write(value); - } else { - if (outStream instanceof ExposedByteArrayOutputStream) { - ((ExposedByteArrayOutputStream) outStream).writeAndOwn(value); - } else { - outStream.write(value); - } - } - } - - @Override - public byte[] decode(InputStream inStream, Context context) - throws IOException, CoderException { - if (context.isWholeStream) { - return StreamUtils.getBytes(inStream); - } else { - int length = VarInt.decodeInt(inStream); - if (length < 0) { - throw new IOException("invalid length " + length); - } - byte[] value = new byte[length]; - ByteStreams.readFully(inStream, value); - return value; - } - } - - /** - * {@inheritDoc} - * - * @return objects that are equal if the two arrays contain the same bytes. - */ - @Override - public Object structuralValue(byte[] value) { - return new StructuralByteArray(value); - } - - /** - * {@inheritDoc} - * - * @return {@code true} since {@link #getEncodedElementByteSize} runs in - * constant time using the {@code length} of the provided array. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(byte[] value, Context context) { - return true; - } - - @Override - protected long getEncodedElementByteSize(byte[] value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null byte[]"); - } - long size = 0; - if (!context.isWholeStream) { - size += VarInt.getLength(value.length); - } - return size + value.length; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteCoder.java deleted file mode 100644 index 9f17497d8d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteCoder.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UTFDataFormatException; - -/** - * A {@link ByteCoder} encodes {@link Byte} values in 1 byte using Java serialization. - */ -public class ByteCoder extends AtomicCoder { - - @JsonCreator - public static ByteCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final ByteCoder INSTANCE = new ByteCoder(); - - private ByteCoder() {} - - @Override - public void encode(Byte value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Byte"); - } - outStream.write(value.byteValue()); - } - - @Override - public Byte decode(InputStream inStream, Context context) - throws IOException, CoderException { - try { - // value will be between 0-255, -1 for EOF - int value = inStream.read(); - if (value == -1) { - throw new EOFException("EOF encountered decoding 1 byte from input stream"); - } - return (byte) value; - } catch (EOFException | UTFDataFormatException exn) { - // These exceptions correspond to decoding problems, so change - // what kind of exception they're branded as. - throw new CoderException(exn); - } - } - - /** - * {@inheritDoc} - * - * {@link ByteCoder} will never throw a {@link Coder.NonDeterministicException}; bytes can always - * be encoded deterministically. - */ - @Override - public void verifyDeterministic() {} - - /** - * {@inheritDoc} - * - * @return {@code true}. This coder is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link ByteCoder#getEncodedElementByteSize} returns a constant. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Byte value, Context context) { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code 1}, the byte size of a {@link Byte} encoded using Java serialization. - */ - @Override - protected long getEncodedElementByteSize(Byte value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot estimate size for unsupported null value"); - } - return 1; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java deleted file mode 100644 index b7c1a3cd0a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoder.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.common.io.ByteStreams; -import com.google.protobuf.ByteString; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} for {@link ByteString} objects based on their encoded Protocol Buffer form. - * - *

            When this code is used in a nested {@link Coder.Context}, the serialized {@link ByteString} - * objects are first delimited by their size. - */ -public class ByteStringCoder extends AtomicCoder { - - @JsonCreator - public static ByteStringCoder of() { - return INSTANCE; - } - - /***************************/ - - private static final ByteStringCoder INSTANCE = new ByteStringCoder(); - - private ByteStringCoder() {} - - @Override - public void encode(ByteString value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null ByteString"); - } - - if (!context.isWholeStream) { - // ByteString is not delimited, so write its size before its contents. - VarInt.encode(value.size(), outStream); - } - value.writeTo(outStream); - } - - @Override - public ByteString decode(InputStream inStream, Context context) throws IOException { - if (context.isWholeStream) { - return ByteString.readFrom(inStream); - } - - int size = VarInt.decodeInt(inStream); - // ByteString reads to the end of the input stream, so give it a limited stream of exactly - // the right length. Also set its chunk size so that the ByteString will contain exactly - // one chunk. - return ByteString.readFrom(ByteStreams.limit(inStream, size), size); - } - - @Override - protected long getEncodedElementByteSize(ByteString value, Context context) throws Exception { - int size = value.size(); - - if (context.isWholeStream) { - return size; - } - return VarInt.getLength(size) + size; - } - - /** - * {@inheritDoc} - * - *

            Returns true; the encoded output of two invocations of {@link ByteStringCoder} in the same - * {@link Coder.Context} will be identical if and only if the original {@link ByteString} objects - * are equal according to {@link Object#equals}. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - *

            Returns true. {@link ByteString#size} returns the size of an array and a {@link VarInt}. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(ByteString value, Context context) { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CannotProvideCoderException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CannotProvideCoderException.java deleted file mode 100644 index 00979e7936..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CannotProvideCoderException.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -/** - * The exception thrown when a {@link CoderProvider} cannot - * provide a {@link Coder} that has been requested. - */ -public class CannotProvideCoderException extends Exception { - private final ReasonCode reason; - - public CannotProvideCoderException(String message) { - this(message, ReasonCode.UNKNOWN); - } - - public CannotProvideCoderException(String message, ReasonCode reason) { - super(message); - this.reason = reason; - } - - public CannotProvideCoderException(String message, Throwable cause) { - this(message, cause, ReasonCode.UNKNOWN); - } - - public CannotProvideCoderException(String message, Throwable cause, ReasonCode reason) { - super(message, cause); - this.reason = reason; - } - - public CannotProvideCoderException(Throwable cause) { - this(cause, ReasonCode.UNKNOWN); - } - - public CannotProvideCoderException(Throwable cause, ReasonCode reason) { - super(cause); - this.reason = reason; - } - - /** - * @return the reason that Coder inference failed. - */ - public ReasonCode getReason() { - return reason; - } - - /** - * Returns the inner-most {@link CannotProvideCoderException} when they are deeply nested. - * - *

            For example, if a coder for {@code List>} cannot be provided because - * there is no known coder for {@code Whatsit}, the root cause of the exception should be a - * CannotProvideCoderException with details pertinent to {@code Whatsit}, suppressing the - * intermediate layers. - */ - public Throwable getRootCause() { - Throwable cause = getCause(); - if (cause == null) { - return this; - } else if (!(cause instanceof CannotProvideCoderException)) { - return cause; - } else { - return ((CannotProvideCoderException) cause).getRootCause(); - } - } - - /** - * Indicates the reason that {@link Coder} inference failed. - */ - public enum ReasonCode { - /** - * The reason a coder could not be provided is unknown or does have an established - * {@link ReasonCode}. - */ - UNKNOWN, - - /** - * The reason a coder could not be provided is type erasure, for example when requesting - * coder inference for a {@code List} where {@code T} is unknown. - */ - TYPE_ERASURE - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java deleted file mode 100644 index edbc26e770..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Coder.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.common.base.Joiner; -import com.google.common.base.MoreObjects; -import com.google.common.base.Objects; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A {@link Coder Coder<T>} defines how to encode and decode values of type {@code T} into - * byte streams. - * - *

            {@link Coder} instances are serialized during job creation and deserialized - * before use, via JSON serialization. See {@link SerializableCoder} for an example of a - * {@link Coder} that adds a custom field to - * the {@link Coder} serialization. It provides a constructor annotated with - * {@link com.fasterxml.jackson.annotation.JsonCreator}, which is a factory method used when - * deserializing a {@link Coder} instance. - * - *

            {@link Coder} classes for compound types are often composed from coder classes for types - * contains therein. The composition of {@link Coder} instances into a coder for the compound - * class is the subject of the {@link CoderFactory} type, which enables automatic generic - * composition of {@link Coder} classes within the {@link CoderRegistry}. With particular - * static methods on a compound {@link Coder} class, a {@link CoderFactory} can be automatically - * inferred. See {@link KvCoder} for an example of a simple compound {@link Coder} that supports - * automatic composition in the {@link CoderRegistry}. - * - *

            The binary format of a {@link Coder} is identified by {@link #getEncodingId()}; be sure to - * understand the requirements for evolving coder formats. - * - *

            All methods of a {@link Coder} are required to be thread safe. - * - * @param the type of the values being transcoded - */ -public interface Coder extends Serializable { - /** The context in which encoding or decoding is being done. */ - class Context { - /** - * The outer context: the value being encoded or decoded takes - * up the remainder of the record/stream contents. - */ - public static final Context OUTER = new Context(true); - - /** - * The nested context: the value being encoded or decoded is - * (potentially) a part of a larger record/stream contents, and - * may have other parts encoded or decoded after it. - */ - public static final Context NESTED = new Context(false); - - /** - * Whether the encoded or decoded value fills the remainder of the - * output or input (resp.) record/stream contents. If so, then - * the size of the decoded value can be determined from the - * remaining size of the record/stream contents, and so explicit - * lengths aren't required. - */ - public final boolean isWholeStream; - - public Context(boolean isWholeStream) { - this.isWholeStream = isWholeStream; - } - - public Context nested() { - return NESTED; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Context)) { - return false; - } - return Objects.equal(isWholeStream, ((Context) obj).isWholeStream); - } - - @Override - public int hashCode() { - return Objects.hashCode(isWholeStream); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(Context.class) - .addValue(isWholeStream ? "OUTER" : "NESTED").toString(); - } - } - - /** - * Encodes the given value of type {@code T} onto the given output stream - * in the given context. - * - * @throws IOException if writing to the {@code OutputStream} fails - * for some reason - * @throws CoderException if the value could not be encoded for some reason - */ - void encode(T value, OutputStream outStream, Context context) - throws CoderException, IOException; - - /** - * Decodes a value of type {@code T} from the given input stream in - * the given context. Returns the decoded value. - * - * @throws IOException if reading from the {@code InputStream} fails - * for some reason - * @throws CoderException if the value could not be decoded for some reason - */ - T decode(InputStream inStream, Context context) - throws CoderException, IOException; - - /** - * If this is a {@code Coder} for a parameterized type, returns the - * list of {@code Coder}s being used for each of the parameters, or - * returns {@code null} if this cannot be done or this is not a - * parameterized type. - */ - List> getCoderArguments(); - - /** - * Returns the {@link CloudObject} that represents this {@code Coder}. - */ - CloudObject asCloudObject(); - - /** - * Throw {@link NonDeterministicException} if the coding is not deterministic. - * - *

            In order for a {@code Coder} to be considered deterministic, - * the following must be true: - *

              - *
            • two values that compare as equal (via {@code Object.equals()} - * or {@code Comparable.compareTo()}, if supported) have the same - * encoding. - *
            • the {@code Coder} always produces a canonical encoding, which is the - * same for an instance of an object even if produced on different - * computers at different times. - *
            - * - * @throws Coder.NonDeterministicException if this coder is not deterministic. - */ - void verifyDeterministic() throws Coder.NonDeterministicException; - - /** - * Returns {@code true} if this {@link Coder} is injective with respect to {@link Objects#equals}. - * - *

            Whenever the encoded bytes of two values are equal, then the original values are equal - * according to {@code Objects.equals()}. Note that this is well-defined for {@code null}. - * - *

            This condition is most notably false for arrays. More generally, this condition is false - * whenever {@code equals()} compares object identity, rather than performing a - * semantic/structural comparison. - */ - boolean consistentWithEquals(); - - /** - * Returns an object with an {@code Object.equals()} method that represents structural equality - * on the argument. - * - *

            For any two values {@code x} and {@code y} of type {@code T}, if their encoded bytes are the - * same, then it must be the case that {@code structuralValue(x).equals(@code structuralValue(y)}. - * - *

            Most notably: - *

              - *
            • The structural value for an array coder should perform a structural comparison of the - * contents of the arrays, rather than the default behavior of comparing according to object - * identity. - *
            • The structural value for a coder accepting {@code null} should be a proper object with - * an {@code equals()} method, even if the input value is {@code null}. - *
            - * - *

            See also {@link #consistentWithEquals()}. - */ - Object structuralValue(T value) throws Exception; - - /** - * Returns whether {@link #registerByteSizeObserver} cheap enough to - * call for every element, that is, if this {@code Coder} can - * calculate the byte size of the element to be coded in roughly - * constant time (or lazily). - * - *

            Not intended to be called by user code, but instead by - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} - * implementations. - */ - boolean isRegisterByteSizeObserverCheap(T value, Context context); - - /** - * Notifies the {@code ElementByteSizeObserver} about the byte size - * of the encoded value using this {@code Coder}. - * - *

            Not intended to be called by user code, but instead by - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} - * implementations. - */ - void registerByteSizeObserver( - T value, ElementByteSizeObserver observer, Context context) - throws Exception; - - /** - * An identifier for the binary format written by {@link #encode}. - * - *

            This value, along with the fully qualified class name, forms an identifier for the - * binary format of this coder. Whenever this value changes, the new encoding is considered - * incompatible with the prior format: It is presumed that the prior version of the coder will - * be unable to correctly read the new format and the new version of the coder will be unable to - * correctly read the old format. - * - *

            If the format is changed in a backwards-compatible way (the Coder can still accept data from - * the prior format), such as by adding optional fields to a Protocol Buffer or Avro definition, - * and you want Dataflow to understand that the new coder is compatible with the prior coder, - * this value must remain unchanged. It is then the responsibility of {@link #decode} to correctly - * read data from the prior format. - */ - @Experimental(Kind.CODER_ENCODING_ID) - String getEncodingId(); - - /** - * A collection of encodings supported by {@link #decode} in addition to the encoding - * from {@link #getEncodingId()} (which is assumed supported). - * - *

            This information is not currently used for any purpose. It is descriptive only, - * and this method is subject to change. - * - * @see #getEncodingId() - */ - @Experimental(Kind.CODER_ENCODING_ID) - Collection getAllowedEncodings(); - - /** - * Exception thrown by {@link Coder#verifyDeterministic()} if the encoding is - * not deterministic, including details of why the encoding is not deterministic. - */ - class NonDeterministicException extends Throwable { - private Coder coder; - private List reasons; - - public NonDeterministicException( - Coder coder, String reason, @Nullable NonDeterministicException e) { - this(coder, Arrays.asList(reason), e); - } - - public NonDeterministicException(Coder coder, String reason) { - this(coder, Arrays.asList(reason), null); - } - - public NonDeterministicException(Coder coder, List reasons) { - this(coder, reasons, null); - } - - public NonDeterministicException( - Coder coder, - List reasons, - @Nullable NonDeterministicException cause) { - super(cause); - checkArgument(reasons.size() > 0, "Reasons must not be empty."); - this.reasons = reasons; - this.coder = coder; - } - - public Iterable getReasons() { - return reasons; - } - - @Override - public String getMessage() { - return String.format("%s is not deterministic because:\n %s", - coder, Joiner.on("\n ").join(reasons)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderException.java deleted file mode 100644 index 8ff8571e5c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import java.io.IOException; - -/** - * An {@link Exception} thrown if there is a problem encoding or decoding a value. - */ -public class CoderException extends IOException { - public CoderException(String message) { - super(message); - } - - public CoderException(String message, Throwable cause) { - super(message, cause); - } - - public CoderException(Throwable cause) { - super(cause); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactories.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactories.java deleted file mode 100644 index 01a5eabfc6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactories.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Static utility methods for creating and working with {@link Coder}s. - */ -public final class CoderFactories { - private CoderFactories() { } // Static utility class - - /** - * Creates a {@link CoderFactory} built from particular static methods of a class that - * implements {@link Coder}. - * - *

            The class must have the following static methods: - * - *

              - *
            • {@code - * public static Coder of(Coder argCoder1, Coder argCoder2, ...) - * } - *
            • {@code - * public static List getInstanceComponents(T exampleValue); - * } - * - * - *

              The {@code of(...)} method will be used to construct a - * {@code Coder} from component {@link Coder}s. - * It must accept one {@link Coder} argument for each - * generic type parameter of {@code T}. If {@code T} takes no generic - * type parameters, then the {@code of()} factory method should take - * no arguments. - * - *

              The {@code getInstanceComponents} method will be used to - * decompose a value during the {@link Coder} inference process, - * to automatically choose coders for the components. - * - *

              Note that the class {@code T} to be coded may be a - * not-yet-specialized generic class. - * For a generic class {@code MyClass} and an actual type parameter - * {@code Foo}, the {@link CoderFactoryFromStaticMethods} will - * accept any {@code Coder} and produce a {@code Coder>}. - * - *

              For example, the {@link CoderFactory} returned by - * {@code fromStaticMethods(ListCoder.class)} - * will produce a {@code Coder>} for any {@code Coder Coder}. - */ - public static CoderFactory fromStaticMethods(Class clazz) { - return new CoderFactoryFromStaticMethods(clazz); - } - - /** - * Creates a {@link CoderFactory} that always returns the - * given coder. - * - *

              The {@code getInstanceComponents} method of this - * {@link CoderFactory} always returns an empty list. - */ - public static CoderFactory forCoder(Coder coder) { - return new CoderFactoryForCoder<>(coder); - } - - /** - * See {@link #fromStaticMethods} for a detailed description - * of the characteristics of this {@link CoderFactory}. - */ - private static class CoderFactoryFromStaticMethods implements CoderFactory { - - @Override - @SuppressWarnings("rawtypes") - public Coder create(List> componentCoders) { - try { - return (Coder) factoryMethod.invoke( - null /* static */, componentCoders.toArray()); - } catch (IllegalAccessException - | IllegalArgumentException - | InvocationTargetException - | NullPointerException - | ExceptionInInitializerError exn) { - throw new IllegalStateException( - "error when invoking Coder factory method " + factoryMethod, - exn); - } - } - - @Override - public List getInstanceComponents(Object value) { - try { - @SuppressWarnings("unchecked") - List components = (List) getComponentsMethod.invoke( - null /* static */, value); - return components; - } catch (IllegalAccessException - | IllegalArgumentException - | InvocationTargetException - | NullPointerException - | ExceptionInInitializerError exn) { - throw new IllegalStateException( - "error when invoking Coder getComponents method " + getComponentsMethod, - exn); - } - } - - //////////////////////////////////////////////////////////////////////////////// - - // Method to create a coder given component coders - // For a Coder class of kind * -> * -> ... n times ... -> * - // this has type Coder -> Coder -> ... n times ... -> Coder - private Method factoryMethod; - - // Method to decompose a value of type T into its parts. - // For a Coder class of kind * -> * -> ... n times ... -> * - // this has type T -> List - // where the list has n elements. - private Method getComponentsMethod; - - /** - * Returns a CoderFactory that invokes the given static factory method - * to create the Coder. - */ - private CoderFactoryFromStaticMethods(Class coderClazz) { - this.factoryMethod = getFactoryMethod(coderClazz); - this.getComponentsMethod = getInstanceComponentsMethod(coderClazz); - } - - /** - * Returns the static {@code of} constructor method on {@code coderClazz} - * if it exists. It is assumed to have one {@link Coder} parameter for - * each type parameter of {@code coderClazz}. - */ - private Method getFactoryMethod(Class coderClazz) { - Method factoryMethodCandidate; - - // Find the static factory method of coderClazz named 'of' with - // the appropriate number of type parameters. - int numTypeParameters = coderClazz.getTypeParameters().length; - Class[] factoryMethodArgTypes = new Class[numTypeParameters]; - Arrays.fill(factoryMethodArgTypes, Coder.class); - try { - factoryMethodCandidate = - coderClazz.getDeclaredMethod("of", factoryMethodArgTypes); - } catch (NoSuchMethodException | SecurityException exn) { - throw new IllegalArgumentException( - "cannot register Coder " + coderClazz + ": " - + "does not have an accessible method named 'of' with " - + numTypeParameters + " arguments of Coder type", - exn); - } - if (!Modifier.isStatic(factoryMethodCandidate.getModifiers())) { - throw new IllegalArgumentException( - "cannot register Coder " + coderClazz + ": " - + "method named 'of' with " + numTypeParameters - + " arguments of Coder type is not static"); - } - if (!coderClazz.isAssignableFrom(factoryMethodCandidate.getReturnType())) { - throw new IllegalArgumentException( - "cannot register Coder " + coderClazz + ": " - + "method named 'of' with " + numTypeParameters - + " arguments of Coder type does not return a " + coderClazz); - } - try { - if (!factoryMethodCandidate.isAccessible()) { - factoryMethodCandidate.setAccessible(true); - } - } catch (SecurityException exn) { - throw new IllegalArgumentException( - "cannot register Coder " + coderClazz + ": " - + "method named 'of' with " + numTypeParameters - + " arguments of Coder type is not accessible", - exn); - } - - return factoryMethodCandidate; - } - - /** - * Finds the static method on {@code coderType} to use - * to decompose a value of type {@code T} into components, - * each corresponding to an argument of the {@code of} - * method. - */ - private Method getInstanceComponentsMethod(Class coderClazz) { - TypeDescriptor coderType = TypeDescriptor.of(coderClazz); - TypeDescriptor argumentType = getCodedType(coderType); - - // getInstanceComponents may be implemented in a superclass, - // so we search them all for an applicable method. We do not - // try to be clever about finding the best overload. It may - // be in a generic superclass, erased to accept an Object. - // However, subtypes are listed before supertypes (it is a - // topological ordering) so probably the best one will be chosen - // if there are more than one (which should be rare) - for (TypeDescriptor supertype : coderType.getClasses()) { - for (Method method : supertype.getRawType().getDeclaredMethods()) { - if (method.getName().equals("getInstanceComponents")) { - TypeDescriptor formalArgumentType = supertype.getArgumentTypes(method).get(0); - if (formalArgumentType.getRawType().isAssignableFrom(argumentType.getRawType())) { - return method; - } - } - } - } - - throw new IllegalArgumentException( - "cannot create a CoderFactory from " + coderType + ": " - + "does not have an accessible method " - + "'getInstanceComponents'"); - } - - /** - * If {@code coderType} is a subclass of {@link Coder} for a specific - * type {@code T}, returns {@code T.class}. Otherwise, raises IllegalArgumentException. - */ - private TypeDescriptor getCodedType(TypeDescriptor coderType) { - for (TypeDescriptor ifaceType : coderType.getInterfaces()) { - if (ifaceType.getRawType().equals(Coder.class)) { - ParameterizedType coderIface = (ParameterizedType) ifaceType.getType(); - @SuppressWarnings("unchecked") - TypeDescriptor token = - (TypeDescriptor) TypeDescriptor.of(coderIface.getActualTypeArguments()[0]); - return token; - } - } - throw new IllegalArgumentException( - "cannot build CoderFactory from class " + coderType - + ": does not implement Coder for any T."); - } - } - - /** - * See {@link #forCoder} for a detailed description of this - * {@link CoderFactory}. - */ - private static class CoderFactoryForCoder implements CoderFactory { - private Coder coder; - - public CoderFactoryForCoder(Coder coder) { - this.coder = coder; - } - - @Override - public Coder create(List> componentCoders) { - return this.coder; - } - - @Override - public List getInstanceComponents(Object value) { - return Collections.emptyList(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactory.java deleted file mode 100644 index 962fcaff3c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import java.util.List; - -/** - * A {@link CoderFactory} creates coders and decomposes values. - * It may operate on a parameterized type, such as {@link List}, - * in which case the {@link #create} method accepts a list of - * coders to use for the type parameters. - */ -public interface CoderFactory { - - /** - * Returns a {@code Coder}, given argument coder to use for - * values of a particular type, given the Coders for each of - * the type's generic parameter types. - */ - Coder create(List> componentCoders); - - /** - * Returns a list of objects contained in {@code value}, one per - * type argument, or {@code null} if none can be determined. - * The list of returned objects should be the same size as the - * list of coders required by {@link #create}. - */ - List getInstanceComponents(Object value); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProvider.java deleted file mode 100644 index 8eaaa5af5b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -/** - * A {@link CoderProvider} may create a {@link Coder} for - * any concrete class. - */ -public interface CoderProvider { - - /** - * Provides a coder for a given class, if possible. - * - * @throws CannotProvideCoderException if no coder can be provided - */ - Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProviders.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProviders.java deleted file mode 100644 index 8b0aedd2b4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderProviders.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import java.lang.reflect.InvocationTargetException; -import java.util.List; - -/** - * Static utility methods for working with {@link CoderProvider CoderProviders}. - */ -public final class CoderProviders { - - // Static utility class - private CoderProviders() { } - - /** - * Creates a {@link CoderProvider} built from particular static methods of a class that - * implements {@link Coder}. The requirements for this method are precisely the requirements - * for a {@link Coder} class to be usable with {@link DefaultCoder} annotations. - * - *

              The class must have the following static method: - * - *

              {@code
              -   * public static Coder of(TypeDescriptor type)
              -   * }
              -   * 
              - */ - public static CoderProvider fromStaticMethods(Class clazz) { - return new CoderProviderFromStaticMethods(clazz); - } - - - /** - * Returns a {@link CoderProvider} that consults each of the provider {@code coderProviders} - * and returns the first {@link Coder} provided. - * - *

              Note that the order in which the providers are listed matters: While the set of types - * handled will be the union of those handled by all of the providers in the list, the actual - * {@link Coder} provided by the first successful provider may differ, and may have inferior - * properties. For example, not all {@link Coder Coders} are deterministic, handle {@code null} - * values, or have comparable performance. - */ - public static CoderProvider firstOf(CoderProvider... coderProviders) { - return new FirstOf(ImmutableList.copyOf(coderProviders)); - } - - /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * @see #firstOf - */ - private static class FirstOf implements CoderProvider { - - private Iterable providers; - - public FirstOf(Iterable providers) { - this.providers = providers; - } - - @Override - public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { - List messages = Lists.newArrayList(); - for (CoderProvider provider : providers) { - try { - return provider.getCoder(type); - } catch (CannotProvideCoderException exc) { - messages.add(String.format("%s could not provide a Coder for type %s: %s", - provider, type, exc.getMessage())); - } - } - throw new CannotProvideCoderException( - String.format("Cannot provide coder for type %s: %s.", - type, Joiner.on("; ").join(messages))); - } - } - - private static class CoderProviderFromStaticMethods implements CoderProvider { - - /** If true, then clazz has {@code of(TypeDescriptor)}. If false, {@code of(Class)}. */ - private final boolean takesTypeDescriptor; - private final Class clazz; - - public CoderProviderFromStaticMethods(Class clazz) { - // Note that the second condition supports older classes, which only needed to provide - // of(Class), not of(TypeDescriptor). Our own classes have updated to accept a - // TypeDescriptor. Hence the error message points only to the current specification, - // not both acceptable conditions. - checkArgument(classTakesTypeDescriptor(clazz) || classTakesClass(clazz), - "Class " + clazz.getCanonicalName() - + " is missing required static method of(TypeDescriptor)."); - - this.takesTypeDescriptor = classTakesTypeDescriptor(clazz); - this.clazz = clazz; - } - - @Override - public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { - try { - if (takesTypeDescriptor) { - @SuppressWarnings("unchecked") - Coder result = InstanceBuilder.ofType(Coder.class) - .fromClass(clazz) - .fromFactoryMethod("of") - .withArg(TypeDescriptor.class, type) - .build(); - return result; - } else { - @SuppressWarnings("unchecked") - Coder result = InstanceBuilder.ofType(Coder.class) - .fromClass(clazz) - .fromFactoryMethod("of") - .withArg(Class.class, type.getRawType()) - .build(); - return result; - } - } catch (RuntimeException exc) { - if (exc.getCause() instanceof InvocationTargetException) { - throw new CannotProvideCoderException(exc.getCause().getCause()); - } - throw exc; - } - } - - private boolean classTakesTypeDescriptor(Class clazz) { - try { - clazz.getDeclaredMethod("of", TypeDescriptor.class); - return true; - } catch (NoSuchMethodException | SecurityException exc) { - return false; - } - } - - private boolean classTakesClass(Class clazz) { - try { - clazz.getDeclaredMethod("of", Class.class); - return true; - } catch (NoSuchMethodException | SecurityException exc) { - return false; - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java deleted file mode 100644 index 9325711c2d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CoderRegistry.java +++ /dev/null @@ -1,844 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException.ReasonCode; -import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.protobuf.ByteString; - -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * A {@link CoderRegistry} allows registering the default {@link Coder} to use for a Java class, - * and looking up and instantiating the default {@link Coder} for a Java type. - * - *

              {@link CoderRegistry} uses the following mechanisms to determine a default {@link Coder} for a - * Java class, in order of precedence: - *

                - *
              1. Registration: - *
                  - *
                • A {@link CoderFactory} can be registered to handle a particular class via - * {@link #registerCoder(Class, CoderFactory)}.
                • - *
                • A {@link Coder} class with the static methods to satisfy - * {@link CoderFactories#fromStaticMethods} can be registered via - * {@link #registerCoder(Class, Class)}.
                • - *
                • Built-in types are registered via - * {@link #registerStandardCoders()}.
                • - *
                - *
              2. Annotations: {@link DefaultCoder} can be used to annotate a type with - * the default {@code Coder} type. The {@link Coder} class must satisfy the requirements - * of {@link CoderProviders#fromStaticMethods}. - *
              3. Fallback: A fallback {@link CoderProvider} is used to attempt to provide a {@link Coder} - * for any type. By default, this is {@link SerializableCoder#PROVIDER}, which can provide - * a {@link Coder} for any type that is serializable via Java serialization. The fallback - * {@link CoderProvider} can be get and set via {@link #getFallbackCoderProvider()} - * and {@link #setFallbackCoderProvider}. Multiple fallbacks can be chained together using - * {@link CoderProviders#firstOf}. - *
              - */ -public class CoderRegistry implements CoderProvider { - - private static final Logger LOG = LoggerFactory.getLogger(CoderRegistry.class); - - public CoderRegistry() { - setFallbackCoderProvider( - CoderProviders.firstOf(ProtoCoder.coderProvider(), SerializableCoder.PROVIDER)); - } - - /** - * Registers standard Coders with this CoderRegistry. - */ - public void registerStandardCoders() { - registerCoder(Byte.class, ByteCoder.class); - registerCoder(ByteString.class, ByteStringCoder.class); - registerCoder(Double.class, DoubleCoder.class); - registerCoder(Instant.class, InstantCoder.class); - registerCoder(Integer.class, VarIntCoder.class); - registerCoder(Iterable.class, IterableCoder.class); - registerCoder(KV.class, KvCoder.class); - registerCoder(List.class, ListCoder.class); - registerCoder(Long.class, VarLongCoder.class); - registerCoder(Map.class, MapCoder.class); - registerCoder(Set.class, SetCoder.class); - registerCoder(String.class, StringUtf8Coder.class); - registerCoder(TableRow.class, TableRowJsonCoder.class); - registerCoder(TimestampedValue.class, TimestampedValue.TimestampedValueCoder.class); - registerCoder(Void.class, VoidCoder.class); - registerCoder(byte[].class, ByteArrayCoder.class); - } - - /** - * Registers {@code coderClazz} as the default {@link Coder} class to handle encoding and - * decoding instances of {@code clazz}, overriding prior registrations if any exist. - * - *

              Supposing {@code T} is the static type corresponding to the {@code clazz}, then - * {@code coderClazz} should have a static factory method with the following signature: - * - *

               {@code
              -   * public static Coder of(Coder argCoder1, Coder argCoder2, ...)
              -   * } 
              - * - *

              This method will be called to create instances of {@code Coder} for values of type - * {@code T}, passing Coders for each of the generic type parameters of {@code T}. If {@code T} - * takes no generic type parameters, then the {@code of()} factory method should have no - * arguments. - * - *

              If {@code T} is a parameterized type, then it should additionally have a method with the - * following signature: - * - *

               {@code
              -   * public static List getInstanceComponents(T exampleValue);
              -   * } 
              -   *
              -   * 

              This method will be called to decompose a value during the {@link Coder} inference process, - * to automatically choose {@link Coder Coders} for the components. - * - * @param clazz the class of objects to be encoded - * @param coderClazz a class with static factory methods to provide {@link Coder Coders} - */ - public void registerCoder(Class clazz, Class coderClazz) { - registerCoder(clazz, CoderFactories.fromStaticMethods(coderClazz)); - } - - /** - * Registers {@code coderFactory} as the default {@link CoderFactory} to produce {@code Coder} - * instances to decode and encode instances of {@code clazz}. This will override prior - * registrations if any exist. - */ - public void registerCoder(Class clazz, CoderFactory coderFactory) { - coderFactoryMap.put(clazz, coderFactory); - } - - /** - * Register the provided {@link Coder} for encoding all values of the specified {@code Class}. - * This will override prior registrations if any exist. - * - *

              Not for use with generic rawtypes. Instead, register a {@link CoderFactory} via - * {@link #registerCoder(Class, CoderFactory)} or ensure your {@code Coder} class has the - * appropriate static methods and register it directly via {@link #registerCoder(Class, Class)}. - */ - public void registerCoder(Class rawClazz, Coder coder) { - checkArgument( - rawClazz.getTypeParameters().length == 0, - "CoderRegistry.registerCoder(Class, Coder) may not be used " - + "with unspecialized generic classes"); - - CoderFactory factory = CoderFactories.forCoder(coder); - registerCoder(rawClazz, factory); - } - - /** - * Returns the {@link Coder} to use by default for values of the given type. - * - * @throws CannotProvideCoderException if there is no default Coder. - */ - public Coder getDefaultCoder(TypeDescriptor typeDescriptor) - throws CannotProvideCoderException { - return getDefaultCoder(typeDescriptor, Collections.>emptyMap()); - } - - /** - * See {@link #getDefaultCoder(TypeDescriptor)}. - */ - @Override - public Coder getCoder(TypeDescriptor typeDescriptor) - throws CannotProvideCoderException { - return getDefaultCoder(typeDescriptor); - } - - /** - * Returns the {@link Coder} to use by default for values of the given type, where the given input - * type uses the given {@link Coder}. - * - * @throws CannotProvideCoderException if there is no default Coder. - */ - public Coder getDefaultCoder( - TypeDescriptor typeDescriptor, - TypeDescriptor inputTypeDescriptor, - Coder inputCoder) - throws CannotProvideCoderException { - return getDefaultCoder( - typeDescriptor, getTypeToCoderBindings(inputTypeDescriptor.getType(), inputCoder)); - } - - /** - * Returns the {@link Coder} to use on elements produced by this function, given the {@link Coder} - * used for its input elements. - */ - public Coder getDefaultOutputCoder( - SerializableFunction fn, Coder inputCoder) - throws CannotProvideCoderException { - - ParameterizedType fnType = (ParameterizedType) - TypeDescriptor.of(fn.getClass()).getSupertype(SerializableFunction.class).getType(); - - return getDefaultCoder( - fn.getClass(), - SerializableFunction.class, - ImmutableMap.of(fnType.getActualTypeArguments()[0], inputCoder), - SerializableFunction.class.getTypeParameters()[1]); - } - - /** - * Returns the {@link Coder} to use for the specified type parameter specialization of the - * subclass, given {@link Coder Coders} to use for all other type parameters (if any). - * - * @throws CannotProvideCoderException if there is no default Coder. - */ - public Coder getDefaultCoder( - Class subClass, - Class baseClass, - Map> knownCoders, - TypeVariable param) - throws CannotProvideCoderException { - - Map> inferredCoders = getDefaultCoders(subClass, baseClass, knownCoders); - - @SuppressWarnings("unchecked") - Coder paramCoderOrNull = (Coder) inferredCoders.get(param); - if (paramCoderOrNull != null) { - return paramCoderOrNull; - } else { - throw new CannotProvideCoderException( - "Cannot infer coder for type parameter " + param.getName()); - } - } - - /** - * Returns the {@link Coder} to use for the provided example value, if it can be determined. - * - * @throws CannotProvideCoderException if there is no default {@link Coder} or - * more than one {@link Coder} matches - */ - public Coder getDefaultCoder(T exampleValue) throws CannotProvideCoderException { - Class clazz = exampleValue == null ? Void.class : exampleValue.getClass(); - - if (clazz.getTypeParameters().length == 0) { - // Trust that getDefaultCoder returns a valid - // Coder for non-generic clazz. - @SuppressWarnings("unchecked") - Coder coder = (Coder) getDefaultCoder(clazz); - return coder; - } else { - CoderFactory factory = getDefaultCoderFactory(clazz); - - List components = factory.getInstanceComponents(exampleValue); - if (components == null) { - throw new CannotProvideCoderException(String.format( - "Cannot provide coder based on value with class %s: The registered CoderFactory with " - + "class %s failed to decompose the value, which is required in order to provide " - + "Coders for the components.", - clazz.getCanonicalName(), factory.getClass().getCanonicalName())); - } - - // componentcoders = components.map(this.getDefaultCoder) - List> componentCoders = new ArrayList<>(); - for (Object component : components) { - try { - Coder componentCoder = getDefaultCoder(component); - componentCoders.add(componentCoder); - } catch (CannotProvideCoderException exc) { - throw new CannotProvideCoderException( - String.format("Cannot provide coder based on value with class %s", - clazz.getCanonicalName()), - exc); - } - } - - // Trust that factory.create maps from valid component Coders - // to a valid Coder. - @SuppressWarnings("unchecked") - Coder coder = (Coder) factory.create(componentCoders); - return coder; - } - } - - /** - * Returns the {@link Coder} to use by default for values of the given class. The following three - * sources for a {@link Coder} will be attempted, in order: - * - *
                - *
              1. A {@link Coder} class registered explicitly via a call to {@link #registerCoder}, - *
              2. A {@link DefaultCoder} annotation on the class, - *
              3. This registry's fallback {@link CoderProvider}, which may be able to generate a - * {@link Coder} for an arbitrary class. - *
              - * - * @throws CannotProvideCoderException if a {@link Coder} cannot be provided - */ - public Coder getDefaultCoder(Class clazz) throws CannotProvideCoderException { - - CannotProvideCoderException factoryException; - try { - CoderFactory coderFactory = getDefaultCoderFactory(clazz); - LOG.debug("Default coder for {} found by factory", clazz); - @SuppressWarnings("unchecked") - Coder coder = (Coder) coderFactory.create(Collections.>emptyList()); - return coder; - } catch (CannotProvideCoderException exc) { - factoryException = exc; - } - - CannotProvideCoderException annotationException; - try { - return getDefaultCoderFromAnnotation(clazz); - } catch (CannotProvideCoderException exc) { - annotationException = exc; - } - - CannotProvideCoderException fallbackException; - if (getFallbackCoderProvider() != null) { - try { - return getFallbackCoderProvider().getCoder(TypeDescriptor.of(clazz)); - } catch (CannotProvideCoderException exc) { - fallbackException = exc; - } - } else { - fallbackException = new CannotProvideCoderException("no fallback CoderProvider configured"); - } - - // Build up the error message and list of causes. - StringBuilder messageBuilder = new StringBuilder() - .append("Unable to provide a default Coder for ").append(clazz.getCanonicalName()) - .append(". Correct one of the following root causes:"); - - messageBuilder - .append("\n Building a Coder using a registered CoderFactory failed: ") - .append(factoryException.getMessage()); - - messageBuilder - .append("\n Building a Coder from the @DefaultCoder annotation failed: ") - .append(annotationException.getMessage()); - - messageBuilder - .append("\n Building a Coder from the fallback CoderProvider failed: ") - .append(fallbackException.getMessage()); - - throw new CannotProvideCoderException(messageBuilder.toString()); - } - - /** - * Sets the fallback {@link CoderProvider} for this registry. If no other method succeeds in - * providing a {@code Coder} for a type {@code T}, then the registry will attempt to create - * a {@link Coder} using this {@link CoderProvider}. - * - *

              By default, this is set to {@link SerializableCoder#PROVIDER}. - * - *

              See {@link #getFallbackCoderProvider}. - */ - public void setFallbackCoderProvider(CoderProvider coderProvider) { - fallbackCoderProvider = coderProvider; - } - - /** - * Returns the fallback {@link CoderProvider} for this registry. - * - *

              See {@link #setFallbackCoderProvider}. - */ - public CoderProvider getFallbackCoderProvider() { - return fallbackCoderProvider; - } - - /** - * Returns a {@code Map} from each of {@code baseClass}'s type parameters to the {@link Coder} to - * use by default for it, in the context of {@code subClass}'s specialization of - * {@code baseClass}. - * - *

              If no {@link Coder} can be inferred for a particular type parameter, then that type variable - * will be absent from the returned {@code Map}. - * - *

              For example, if {@code baseClass} is {@code Map.class}, where {@code Map} has type - * parameters {@code K} and {@code V}, and {@code subClass} extends {@code Map} - * then the result will map the type variable {@code K} to a {@code Coder} and the - * type variable {@code V} to a {@code Coder}. - * - *

              The {@code knownCoders} parameter can be used to provide known {@link Coder Coders} for any - * of the parameters; these will be used to infer the others. - * - *

              Note that inference is attempted for every type variable. For a type - * {@code MyType} inference will be attempted for all of {@code One}, - * {@code Two}, {@code Three}, even if the requester only wants a {@link Coder} for {@code Two}. - * - *

              For this reason {@code getDefaultCoders} (plural) does not throw an exception if a - * {@link Coder} for a particular type variable cannot be inferred, but merely omits the entry - * from the returned {@code Map}. It is the responsibility of the caller (usually - * {@link #getDefaultCoder} to extract the desired coder or throw a - * {@link CannotProvideCoderException} when appropriate. - * - * @param subClass the concrete type whose specializations are being inferred - * @param baseClass the base type, a parameterized class - * @param knownCoders a map corresponding to the set of known {@link Coder Coders} indexed by - * parameter name - * - * @deprecated this method is not part of the public interface and will be made private - */ - @Deprecated - public Map> getDefaultCoders( - Class subClass, - Class baseClass, - Map> knownCoders) { - TypeVariable>[] typeParams = baseClass.getTypeParameters(); - Coder[] knownCodersArray = new Coder[typeParams.length]; - for (int i = 0; i < typeParams.length; i++) { - knownCodersArray[i] = knownCoders.get(typeParams[i]); - } - Coder[] resultArray = getDefaultCoders( - subClass, baseClass, knownCodersArray); - Map> result = new HashMap<>(); - for (int i = 0; i < typeParams.length; i++) { - if (resultArray[i] != null) { - result.put(typeParams[i], resultArray[i]); - } - } - return result; - } - - /** - * Returns an array listing, for each of {@code baseClass}'s type parameters, the {@link Coder} to - * use by default for it, in the context of {@code subClass}'s specialization of - * {@code baseClass}. - * - *

              If a {@link Coder} cannot be inferred for a type variable, its slot in the resulting array - * will be {@code null}. - * - *

              For example, if {@code baseClass} is {@code Map.class}, where {@code Map} has type - * parameters {@code K} and {@code V} in that order, and {@code subClass} extends - * {@code Map} then the result will contain a {@code Coder} and a - * {@code Coder}, in that order. - * - *

              The {@code knownCoders} parameter can be used to provide known {@link Coder Coders} for any - * of the type parameters. These will be used to infer the others. If non-null, the length of this - * array must match the number of type parameters of {@code baseClass}, and simply be filled with - * {@code null} values for each type parameters without a known {@link Coder}. - * - *

              Note that inference is attempted for every type variable. For a type - * {@code MyType} inference will will be attempted for all of {@code One}, - * {@code Two}, {@code Three}, even if the requester only wants a {@link Coder} for {@code Two}. - * - *

              For this reason {@code getDefaultCoders} (plural) does not throw an exception if a - * {@link Coder} for a particular type variable cannot be inferred. Instead, it results in a - * {@code null} in the array. It is the responsibility of the caller (usually - * {@link #getDefaultCoder} to extract the desired coder or throw a - * {@link CannotProvideCoderException} when appropriate. - * - * @param subClass the concrete type whose specializations are being inferred - * @param baseClass the base type, a parameterized class - * @param knownCoders an array corresponding to the set of base class type parameters. Each entry - * can be either a {@link Coder} (in which case it will be used for inference) or - * {@code null} (in which case it will be inferred). May be {@code null} to indicate the - * entire set of parameters should be inferred. - * @throws IllegalArgumentException if baseClass doesn't have type parameters or if the length of - * {@code knownCoders} is not equal to the number of type parameters of {@code baseClass}. - */ - private Coder[] getDefaultCoders( - Class subClass, - Class baseClass, - @Nullable Coder[] knownCoders) { - Type type = TypeDescriptor.of(subClass).getSupertype(baseClass).getType(); - if (!(type instanceof ParameterizedType)) { - throw new IllegalArgumentException(type + " is not a ParameterizedType"); - } - ParameterizedType parameterizedType = (ParameterizedType) type; - Type[] typeArgs = parameterizedType.getActualTypeArguments(); - if (knownCoders == null) { - knownCoders = new Coder[typeArgs.length]; - } else if (typeArgs.length != knownCoders.length) { - throw new IllegalArgumentException( - String.format("Class %s has %d parameters, but %d coders are requested.", - baseClass.getCanonicalName(), typeArgs.length, knownCoders.length)); - } - - Map> context = new HashMap<>(); - for (int i = 0; i < knownCoders.length; i++) { - if (knownCoders[i] != null) { - try { - verifyCompatible(knownCoders[i], typeArgs[i]); - } catch (IncompatibleCoderException exn) { - throw new IllegalArgumentException( - String.format("Provided coders for type arguments of %s contain incompatibilities:" - + " Cannot encode elements of type %s with coder %s", - baseClass, - typeArgs[i], knownCoders[i]), - exn); - } - context.putAll(getTypeToCoderBindings(typeArgs[i], knownCoders[i])); - } - } - - Coder[] result = new Coder[typeArgs.length]; - for (int i = 0; i < knownCoders.length; i++) { - if (knownCoders[i] != null) { - result[i] = knownCoders[i]; - } else { - try { - result[i] = getDefaultCoder(typeArgs[i], context); - } catch (CannotProvideCoderException exc) { - result[i] = null; - } - } - } - return result; - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Thrown when a {@link Coder} cannot possibly encode a type, yet has been proposed as a - * {@link Coder} for that type. - */ - @VisibleForTesting static class IncompatibleCoderException extends RuntimeException { - private Coder coder; - private Type type; - - public IncompatibleCoderException(String message, Coder coder, Type type) { - super(message); - this.coder = coder; - this.type = type; - } - - public IncompatibleCoderException(String message, Coder coder, Type type, Throwable cause) { - super(message, cause); - this.coder = coder; - this.type = type; - } - - public Coder getCoder() { - return coder; - } - - public Type getType() { - return type; - } - } - - /** - * Returns {@code true} if the given {@link Coder} can possibly encode elements - * of the given type. - */ - @VisibleForTesting static , CandidateT> - void verifyCompatible(CoderT coder, Type candidateType) throws IncompatibleCoderException { - - // Various representations of the coder's class - @SuppressWarnings("unchecked") - Class coderClass = (Class) coder.getClass(); - TypeDescriptor coderDescriptor = TypeDescriptor.of(coderClass); - - // Various representations of the actual coded type - @SuppressWarnings("unchecked") - TypeDescriptor codedDescriptor = CoderUtils.getCodedType(coderDescriptor); - @SuppressWarnings("unchecked") - Class codedClass = (Class) codedDescriptor.getRawType(); - Type codedType = codedDescriptor.getType(); - - // Various representations of the candidate type - @SuppressWarnings("unchecked") - TypeDescriptor candidateDescriptor = - (TypeDescriptor) TypeDescriptor.of(candidateType); - @SuppressWarnings("unchecked") - Class candidateClass = (Class) candidateDescriptor.getRawType(); - - // If coder has type Coder where the actual value of T is lost - // to erasure, then we cannot rule it out. - if (candidateType instanceof TypeVariable) { - return; - } - - // If the raw types are not compatible, we can certainly rule out - // coder compatibility - if (!codedClass.isAssignableFrom(candidateClass)) { - throw new IncompatibleCoderException( - String.format("Cannot encode elements of type %s with coder %s because the" - + " coded type %s is not assignable from %s", - candidateType, coder, codedClass, candidateType), - coder, candidateType); - } - // we have established that this is a covariant upcast... though - // coders are invariant, we are just checking one direction - @SuppressWarnings("unchecked") - TypeDescriptor candidateOkDescriptor = (TypeDescriptor) candidateDescriptor; - - // If the coded type is a parameterized type where any of the actual - // type parameters are not compatible, then the whole thing is certainly not - // compatible. - if ((codedType instanceof ParameterizedType) && !isNullOrEmpty(coder.getCoderArguments())) { - ParameterizedType parameterizedSupertype = ((ParameterizedType) - candidateOkDescriptor.getSupertype(codedClass).getType()); - Type[] typeArguments = parameterizedSupertype.getActualTypeArguments(); - List> typeArgumentCoders = coder.getCoderArguments(); - if (typeArguments.length < typeArgumentCoders.size()) { - throw new IncompatibleCoderException( - String.format("Cannot encode elements of type %s with coder %s:" - + " the generic supertype %s has %s type parameters, which is less than the" - + " number of coder arguments %s has (%s).", - candidateOkDescriptor, coder, - parameterizedSupertype, typeArguments.length, - coder, typeArgumentCoders.size()), - coder, candidateOkDescriptor.getType()); - } - for (int i = 0; i < typeArgumentCoders.size(); i++) { - try { - verifyCompatible( - typeArgumentCoders.get(i), - candidateDescriptor.resolveType(typeArguments[i]).getType()); - } catch (IncompatibleCoderException exn) { - throw new IncompatibleCoderException( - String.format("Cannot encode elements of type %s with coder %s" - + " because some component coder is incompatible", - candidateType, coder), - coder, candidateType, exn); - } - } - } - } - - private static boolean isNullOrEmpty(Collection c) { - return c == null || c.size() == 0; - } - - /** - * The map of classes to the CoderFactories to use to create their - * default Coders. - */ - private Map, CoderFactory> coderFactoryMap = new HashMap<>(); - - /** - * A provider of coders for types where no coder is registered. - */ - private CoderProvider fallbackCoderProvider; - - /** - * Returns the {@link CoderFactory} to use to create default {@link Coder Coders} for instances of - * the given class, or {@code null} if there is no default {@link CoderFactory} registered. - */ - private CoderFactory getDefaultCoderFactory(Class clazz) throws CannotProvideCoderException { - CoderFactory coderFactoryOrNull = coderFactoryMap.get(clazz); - if (coderFactoryOrNull != null) { - return coderFactoryOrNull; - } else { - throw new CannotProvideCoderException( - String.format("Cannot provide coder based on value with class %s: No CoderFactory has " - + "been registered for the class.", clazz.getCanonicalName())); - } - } - - /** - * Returns the {@link Coder} returned according to the {@link CoderProvider} from any - * {@link DefaultCoder} annotation on the given class. - */ - private Coder getDefaultCoderFromAnnotation(Class clazz) - throws CannotProvideCoderException { - DefaultCoder defaultAnnotation = clazz.getAnnotation(DefaultCoder.class); - if (defaultAnnotation == null) { - throw new CannotProvideCoderException( - String.format("Class %s does not have a @DefaultCoder annotation.", - clazz.getCanonicalName())); - } - - LOG.debug("DefaultCoder annotation found for {} with value {}", - clazz, defaultAnnotation.value()); - CoderProvider coderProvider = CoderProviders.fromStaticMethods(defaultAnnotation.value()); - return coderProvider.getCoder(TypeDescriptor.of(clazz)); - } - - /** - * Returns the {@link Coder} to use by default for values of the given type, - * in a context where the given types use the given coders. - * - * @throws CannotProvideCoderException if a coder cannot be provided - */ - private Coder getDefaultCoder( - TypeDescriptor typeDescriptor, - Map> typeCoderBindings) - throws CannotProvideCoderException { - - Coder defaultCoder = getDefaultCoder(typeDescriptor.getType(), typeCoderBindings); - LOG.debug("Default coder for {}: {}", typeDescriptor, defaultCoder); - @SuppressWarnings("unchecked") - Coder result = (Coder) defaultCoder; - return result; - } - - /** - * Returns the {@link Coder} to use by default for values of the given type, - * in a context where the given types use the given coders. - * - * @throws CannotProvideCoderException if a coder cannot be provided - */ - private Coder getDefaultCoder(Type type, Map> typeCoderBindings) - throws CannotProvideCoderException { - Coder coder = typeCoderBindings.get(type); - if (coder != null) { - return coder; - } - if (type instanceof Class) { - Class clazz = (Class) type; - return getDefaultCoder(clazz); - } else if (type instanceof ParameterizedType) { - return getDefaultCoder((ParameterizedType) type, typeCoderBindings); - } else if (type instanceof TypeVariable || type instanceof WildcardType) { - // No default coder for an unknown generic type. - throw new CannotProvideCoderException( - String.format("Cannot provide a coder for type variable %s" - + " (declared by %s) because the actual type is unknown due to erasure.", - type, - ((TypeVariable) type).getGenericDeclaration()), - ReasonCode.TYPE_ERASURE); - } else { - throw new RuntimeException( - "Internal error: unexpected kind of Type: " + type); - } - } - - /** - * Returns the {@link Coder} to use by default for values of the given - * parameterized type, in a context where the given types use the - * given {@link Coder Coders}. - * - * @throws CannotProvideCoderException if no coder can be provided - */ - private Coder getDefaultCoder( - ParameterizedType type, - Map> typeCoderBindings) - throws CannotProvideCoderException { - - CannotProvideCoderException factoryException; - try { - return getDefaultCoderFromFactory(type, typeCoderBindings); - } catch (CannotProvideCoderException exc) { - factoryException = exc; - } - - CannotProvideCoderException annotationException; - try { - Class rawClazz = (Class) type.getRawType(); - return getDefaultCoderFromAnnotation(rawClazz); - } catch (CannotProvideCoderException exc) { - annotationException = exc; - } - - // Build up the error message and list of causes. - StringBuilder messageBuilder = new StringBuilder() - .append("Unable to provide a default Coder for ").append(type) - .append(". Correct one of the following root causes:"); - - messageBuilder - .append("\n Building a Coder using a registered CoderFactory failed: ") - .append(factoryException.getMessage()); - - messageBuilder - .append("\n Building a Coder from the @DefaultCoder annotation failed: ") - .append(annotationException.getMessage()); - - throw new CannotProvideCoderException(messageBuilder.toString()); - } - - private Coder getDefaultCoderFromFactory( - ParameterizedType type, - Map> typeCoderBindings) - throws CannotProvideCoderException { - Class rawClazz = (Class) type.getRawType(); - CoderFactory coderFactory = getDefaultCoderFactory(rawClazz); - List> typeArgumentCoders = new ArrayList<>(); - for (Type typeArgument : type.getActualTypeArguments()) { - try { - Coder typeArgumentCoder = getDefaultCoder(typeArgument, - typeCoderBindings); - typeArgumentCoders.add(typeArgumentCoder); - } catch (CannotProvideCoderException exc) { - throw new CannotProvideCoderException( - String.format("Cannot provide coder for parameterized type %s: %s", - type, - exc.getMessage()), - exc); - } - } - return coderFactory.create(typeArgumentCoders); - } - - /** - * Returns an immutable {@code Map} from each of the type variables - * embedded in the given type to the corresponding types - * in the given {@link Coder}. - */ - private Map> getTypeToCoderBindings(Type type, Coder coder) { - if (type instanceof TypeVariable || type instanceof Class) { - return ImmutableMap.>of(type, coder); - } else if (type instanceof ParameterizedType) { - return getTypeToCoderBindings((ParameterizedType) type, coder); - } else { - return ImmutableMap.of(); - } - } - - /** - * Returns an immutable {@code Map} from the type arguments of the parameterized type to their - * corresponding {@link Coder Coders}, and so on recursively for their type parameters. - * - *

              This method is simply a specialization to break out the most - * elaborate case of {@link #getTypeToCoderBindings(Type, Coder)}. - */ - private Map> getTypeToCoderBindings(ParameterizedType type, Coder coder) { - List typeArguments = Arrays.asList(type.getActualTypeArguments()); - List> coderArguments = coder.getCoderArguments(); - - if ((coderArguments == null) || (typeArguments.size() != coderArguments.size())) { - return ImmutableMap.of(); - } else { - Map> typeToCoder = Maps.newHashMap(); - - typeToCoder.put(type, coder); - - for (int i = 0; i < typeArguments.size(); i++) { - Type typeArgument = typeArguments.get(i); - Coder coderArgument = coderArguments.get(i); - typeToCoder.putAll(getTypeToCoderBindings(typeArgument, coderArgument)); - } - - return ImmutableMap.>builder().putAll(typeToCoder).build(); - } - - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CollectionCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CollectionCoder.java deleted file mode 100644 index acaf120830..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CollectionCoder.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.Collection; -import java.util.List; - -/** - * A {@link CollectionCoder} encodes {@link Collection Collections} in the format - * of {@link IterableLikeCoder}. - */ -public class CollectionCoder extends IterableLikeCoder> { - - public static CollectionCoder of(Coder elemCoder) { - return new CollectionCoder<>(elemCoder); - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal operations below here. - - /** - * {@inheritDoc} - * - * @return the decoded elements directly, since {@link List} is a subtype of - * {@link Collection}. - */ - @Override - protected final Collection decodeToIterable(List decodedElements) { - return decodedElements; - } - - @JsonCreator - public static CollectionCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List components) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return of((Coder) components.get(0)); - } - - /** - * Returns the first element in this collection if it is non-empty, - * otherwise returns {@code null}. - */ - public static List getInstanceComponents( - Collection exampleValue) { - return getInstanceComponentsHelper(exampleValue); - } - - protected CollectionCoder(Coder elemCoder) { - super(elemCoder, "Collection"); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CustomCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CustomCoder.java deleted file mode 100644 index b34ef8cf6d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/CustomCoder.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.common.collect.Lists; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; -import java.util.Collection; - -/** - * An abstract base class for writing a {@link Coder} class that encodes itself via Java - * serialization. - * - *

              To complete an implementation, subclasses must implement {@link Coder#encode} - * and {@link Coder#decode} methods. Anonymous subclasses must furthermore override - * {@link #getEncodingId}. - * - *

              Not to be confused with {@link SerializableCoder} that encodes objects that implement the - * {@link Serializable} interface. - * - * @param the type of elements handled by this coder - */ -public abstract class CustomCoder extends AtomicCoder - implements Serializable { - @JsonCreator - public static CustomCoder of( - // N.B. typeId is a required parameter here, since a field named "@type" - // is presented to the deserializer as an input. - // - // If this method did not consume the field, Jackson2 would observe an - // unconsumed field and a returned value of a derived type. So Jackson2 - // would attempt to update the returned value with the unconsumed field - // data, The standard JsonDeserializer does not implement a mechanism for - // updating constructed values, so it would throw an exception, causing - // deserialization to fail. - @JsonProperty(value = "@type", required = false) String typeId, - @JsonProperty(value = "encoding_id", required = false) String encodingId, - @JsonProperty("type") String type, - @JsonProperty("serialized_coder") String serializedCoder) { - return (CustomCoder) SerializableUtils.deserializeFromByteArray( - StringUtils.jsonStringToByteArray(serializedCoder), - type); - } - - /** - * {@inheritDoc} - * - * @return A thin {@link CloudObject} wrapping of the Java serialization of {@code this}. - */ - @Override - public CloudObject asCloudObject() { - // N.B. We use the CustomCoder class, not the derived class, since during - // deserialization we will be using the CustomCoder's static factory method - // to construct an instance of the derived class. - CloudObject result = CloudObject.forClass(CustomCoder.class); - addString(result, "type", getClass().getName()); - addString(result, "serialized_coder", - StringUtils.byteArrayToJsonString( - SerializableUtils.serializeToByteArray(this))); - - String encodingId = getEncodingId(); - checkNotNull(encodingId, "Coder.getEncodingId() must not return null."); - if (!encodingId.isEmpty()) { - addString(result, PropertyNames.ENCODING_ID, encodingId); - } - - Collection allowedEncodings = getAllowedEncodings(); - if (!allowedEncodings.isEmpty()) { - addStringList(result, PropertyNames.ALLOWED_ENCODINGS, Lists.newArrayList(allowedEncodings)); - } - - return result; - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException a {@link CustomCoder} is presumed - * nondeterministic. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "CustomCoder implementations must override verifyDeterministic," - + " or they are presumed nondeterministic."); - } - - /** - * {@inheritDoc} - * - * @return The canonical class name for this coder. For stable data formats that are independent - * of class name, it is recommended to override this method. - * - * @throws UnsupportedOperationException when an anonymous class is used, since they do not have - * a stable canonical class name. - */ - @Override - public String getEncodingId() { - if (getClass().isAnonymousClass()) { - throw new UnsupportedOperationException( - String.format("Anonymous CustomCoder subclass %s must override getEncodingId()." - + " Otherwise, convert to a named class and getEncodingId() will be automatically" - + " generated from the fully qualified class name.", - getClass())); - } - return getClass().getCanonicalName(); - } - - // This coder inherits isRegisterByteSizeObserverCheap, - // getEncodedElementByteSize and registerByteSizeObserver - // from StandardCoder. Override if we can do better. -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DefaultCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DefaultCoder.java deleted file mode 100644 index 110579b64c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DefaultCoder.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.values.PCollection; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The {@link DefaultCoder} annotation - * specifies a default {@link Coder} class to handle encoding and decoding - * instances of the annotated class. - * - *

              The specified {@link Coder} must satisfy the requirements of - * {@link CoderProviders#fromStaticMethods}. Two classes provided by the SDK that - * are intended for use with this annotation include {@link SerializableCoder} - * and {@link AvroCoder}. - * - *

              To configure the use of Java serialization as the default - * for a class, annotate the class to use - * {@link SerializableCoder} as follows: - * - *

              {@literal @}DefaultCoder(SerializableCoder.class)
              - * public class MyCustomDataType implements Serializable {
              - *   // ...
              - * }
              - * - *

              Similarly, to configure the use of - * {@link AvroCoder} as the default: - *

              {@literal @}DefaultCoder(AvroCoder.class)
              - * public class MyCustomDataType {
              - *   public MyCustomDataType() {}  // Avro requires an empty constructor.
              - *   // ...
              - * }
              - * - *

              Coders specified explicitly via - * {@link PCollection#setCoder} - * take precedence, followed by Coders registered at runtime via - * {@link CoderRegistry#registerCoder}. See {@link CoderRegistry} for a more detailed discussion - * of the precedence rules. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@SuppressWarnings("rawtypes") -public @interface DefaultCoder { - Class value(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DelegateCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DelegateCoder.java deleted file mode 100644 index c1b58f7870..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DelegateCoder.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.Collection; -import java.util.List; - -/** - * A {@code DelegateCoder} wraps a {@link Coder} for {@code IntermediateT} and - * encodes/decodes values of type {@code T} by converting - * to/from {@code IntermediateT} and then encoding/decoding using the underlying - * {@code Coder}. - * - *

              The conversions from {@code T} to {@code IntermediateT} and vice versa - * must be supplied as {@link CodingFunction}, a serializable - * function that may throw any {@code Exception}. If a thrown - * exception is an instance of {@link CoderException} or - * {@link IOException}, it will be re-thrown, otherwise it will be wrapped as - * a {@link CoderException}. - * - * @param The type of objects coded by this Coder. - * @param The type of objects a {@code T} will be converted to for coding. - */ -public class DelegateCoder extends CustomCoder { - /** - * A {@link DelegateCoder.CodingFunction CodingFunction<InputT, OutputT>} is a serializable - * function from {@code InputT} to {@code OutputT} that may throw any {@link Exception}. - */ - public interface CodingFunction extends Serializable { - OutputT apply(InputT input) throws Exception; - } - - public static DelegateCoder of(Coder coder, - CodingFunction toFn, - CodingFunction fromFn) { - return new DelegateCoder(coder, toFn, fromFn); - } - - @Override - public void encode(T value, OutputStream outStream, Context context) - throws CoderException, IOException { - coder.encode(applyAndWrapExceptions(toFn, value), outStream, context); - } - - @Override - public T decode(InputStream inStream, Context context) throws CoderException, IOException { - return applyAndWrapExceptions(fromFn, coder.decode(inStream, context)); - } - - /** - * Returns the coder used to encode/decode the intermediate values produced/consumed by the - * coding functions of this {@code DelegateCoder}. - */ - public Coder getCoder() { - return coder; - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException when the underlying coder's {@code verifyDeterministic()} - * throws a {@link Coder.NonDeterministicException}. For this to be safe, the - * intermediate {@code CodingFunction} must also be deterministic. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - coder.verifyDeterministic(); - } - - /** - * {@inheritDoc} - * - * @return a structural for a value of type {@code T} obtained by first converting to - * {@code IntermediateT} and then obtaining a structural value according to the underlying - * coder. - */ - @Override - public Object structuralValue(T value) throws Exception { - return coder.structuralValue(toFn.apply(value)); - } - - @Override - public String toString() { - return "DelegateCoder(" + coder + ")"; - } - - /** - * {@inheritDoc} - * - * @return a {@link String} composed from the underlying coder class name and its encoding id. - * Note that this omits any description of the coding functions. These should be modified - * with care. - */ - @Override - public String getEncodingId() { - return delegateEncodingId(coder.getClass(), coder.getEncodingId()); - } - - /** - * {@inheritDoc} - * - * @return allowed encodings which are composed from the underlying coder class and its allowed - * encoding ids. Note that this omits any description of the coding functions. These - * should be modified with care. - */ - @Override - public Collection getAllowedEncodings() { - List allowedEncodings = Lists.newArrayList(); - for (String allowedEncoding : coder.getAllowedEncodings()) { - allowedEncodings.add(delegateEncodingId(coder.getClass(), allowedEncoding)); - } - return allowedEncodings; - } - - private String delegateEncodingId(Class delegateClass, String encodingId) { - return String.format("%s:%s", delegateClass.getName(), encodingId); - } - - ///////////////////////////////////////////////////////////////////////////// - - private OutputT applyAndWrapExceptions( - CodingFunction fn, - InputT input) throws CoderException, IOException { - try { - return fn.apply(input); - } catch (IOException exc) { - throw exc; - } catch (Exception exc) { - throw new CoderException(exc); - } - } - - private final Coder coder; - private final CodingFunction toFn; - private final CodingFunction fromFn; - - protected DelegateCoder(Coder coder, - CodingFunction toFn, - CodingFunction fromFn) { - this.coder = coder; - this.fromFn = fromFn; - this.toFn = toFn; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DeterministicStandardCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DeterministicStandardCoder.java deleted file mode 100644 index 0e0018afd4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DeterministicStandardCoder.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -/** - * A {@link DeterministicStandardCoder} is a {@link StandardCoder} that is - * deterministic, in the sense that for objects considered equal - * according to {@link Object#equals(Object)}, the encoded bytes are - * also equal. - * - * @param the type of the values being transcoded - */ -public abstract class DeterministicStandardCoder extends StandardCoder { - protected DeterministicStandardCoder() {} - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException never, unless overridden. A - * {@link DeterministicStandardCoder} is presumed deterministic. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DoubleCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DoubleCoder.java deleted file mode 100644 index 68d58df102..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DoubleCoder.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UTFDataFormatException; - -/** - * A {@link DoubleCoder} encodes {@link Double} values in 8 bytes using Java serialization. - */ -public class DoubleCoder extends AtomicCoder { - - @JsonCreator - public static DoubleCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final DoubleCoder INSTANCE = new DoubleCoder(); - - private DoubleCoder() {} - - @Override - public void encode(Double value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Double"); - } - new DataOutputStream(outStream).writeDouble(value); - } - - @Override - public Double decode(InputStream inStream, Context context) - throws IOException, CoderException { - try { - return new DataInputStream(inStream).readDouble(); - } catch (EOFException | UTFDataFormatException exn) { - // These exceptions correspond to decoding problems, so change - // what kind of exception they're branded as. - throw new CoderException(exn); - } - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException always. - * Floating-point operations are not guaranteed to be deterministic, even - * if the storage format might be, so floating point representations are not - * recommended for use in operations that require deterministic inputs. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "Floating point encodings are not guaranteed to be deterministic."); - } - - /** - * {@inheritDoc} - * - * @return {@code true}. This coder is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link DoubleCoder#getEncodedElementByteSize} returns a constant. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Double value, Context context) { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code 8}, the byte size of a {@link Double} encoded using Java serialization. - */ - @Override - protected long getEncodedElementByteSize(Double value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null Double"); - } - return 8; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DurationCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DurationCoder.java deleted file mode 100644 index 25527f05df..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/DurationCoder.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import org.joda.time.Duration; -import org.joda.time.ReadableDuration; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} that encodes a joda {@link Duration} as a {@link Long} using the format of - * {@link VarLongCoder}. - */ -public class DurationCoder extends AtomicCoder { - - @JsonCreator - public static DurationCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final DurationCoder INSTANCE = new DurationCoder(); - - private final VarLongCoder longCoder = VarLongCoder.of(); - - private DurationCoder() {} - - private Long toLong(ReadableDuration value) { - return value.getMillis(); - } - - private ReadableDuration fromLong(Long decoded) { - return Duration.millis(decoded); - } - - @Override - public void encode(ReadableDuration value, OutputStream outStream, Context context) - throws CoderException, IOException { - if (value == null) { - throw new CoderException("cannot encode a null ReadableDuration"); - } - longCoder.encode(toLong(value), outStream, context); - } - - @Override - public ReadableDuration decode(InputStream inStream, Context context) - throws CoderException, IOException { - return fromLong(longCoder.decode(inStream, context)); - } - - /** - * {@inheritDoc} - * - * @return {@code true}. This coder is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}, because it is cheap to ascertain the byte size of a long. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(ReadableDuration value, Context context) { - return longCoder.isRegisterByteSizeObserverCheap(toLong(value), context); - } - - @Override - public void registerByteSizeObserver( - ReadableDuration value, ElementByteSizeObserver observer, Context context) throws Exception { - longCoder.registerByteSizeObserver(toLong(value), observer, context); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java deleted file mode 100644 index 9dd81f3547..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/EntityCoder.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.api.services.datastore.DatastoreV1.Entity; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} for {@link Entity} objects based on their encoded Protocol Buffer form. - * - * @deprecated use {@link com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder} instead. - */ -@Deprecated -public class EntityCoder extends AtomicCoder { - - @JsonCreator - public static EntityCoder of() { - return INSTANCE; - } - - /***************************/ - - private static final EntityCoder INSTANCE = new EntityCoder(); - - private EntityCoder() {} - - @Override - public void encode(Entity value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Entity"); - } - - // Since Entity implements com.google.protobuf.MessageLite, - // we could directly use writeTo to write to a OutputStream object - outStream.write(java.nio.ByteBuffer.allocate(4).putInt(value.getSerializedSize()).array()); - value.writeTo(outStream); - outStream.flush(); - } - - @Override - public Entity decode(InputStream inStream, Context context) - throws IOException { - byte[] entitySize = new byte[4]; - inStream.read(entitySize, 0, 4); - int size = java.nio.ByteBuffer.wrap(entitySize).getInt(); - byte[] data = new byte[size]; - inStream.read(data, 0, size); - return Entity.parseFrom(data); - } - - @Override - protected long getEncodedElementByteSize(Entity value, Context context) - throws Exception { - return value.getSerializedSize(); - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException always. - * A Datastore kind can hold arbitrary {@link Object} instances, which - * makes the encoding non-deterministic. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "Datastore encodings can hold arbitrary Object instances"); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/InstantCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/InstantCoder.java deleted file mode 100644 index 99b58ce419..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/InstantCoder.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.common.base.Converter; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} for joda {@link Instant} that encodes it as a big endian {@link Long} - * shifted such that lexicographic ordering of the bytes corresponds to chronological order. - */ -public class InstantCoder extends AtomicCoder { - - @JsonCreator - public static InstantCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final InstantCoder INSTANCE = new InstantCoder(); - - private final BigEndianLongCoder longCoder = BigEndianLongCoder.of(); - - private InstantCoder() {} - - /** - * Converts {@link Instant} to a {@code Long} representing its millis-since-epoch, - * but shifted so that the byte representation of negative values are lexicographically - * ordered before the byte representation of positive values. - * - *

              This deliberately utilizes the well-defined overflow for {@code Long} values. - * See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2 - */ - private static final Converter ORDER_PRESERVING_CONVERTER = - new Converter() { - - @Override - protected Long doForward(Instant instant) { - return instant.getMillis() - Long.MIN_VALUE; - } - - @Override - protected Instant doBackward(Long shiftedMillis) { - return new Instant(shiftedMillis + Long.MIN_VALUE); - } - }; - - @Override - public void encode(Instant value, OutputStream outStream, Context context) - throws CoderException, IOException { - if (value == null) { - throw new CoderException("cannot encode a null Instant"); - } - longCoder.encode(ORDER_PRESERVING_CONVERTER.convert(value), outStream, context); - } - - @Override - public Instant decode(InputStream inStream, Context context) - throws CoderException, IOException { - return ORDER_PRESERVING_CONVERTER.reverse().convert(longCoder.decode(inStream, context)); - } - - /** - * {@inheritDoc} - * - * @return {@code true}. This coder is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. The byte size for a big endian long is a constant. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Instant value, Context context) { - return longCoder.isRegisterByteSizeObserverCheap( - ORDER_PRESERVING_CONVERTER.convert(value), context); - } - - @Override - public void registerByteSizeObserver( - Instant value, ElementByteSizeObserver observer, Context context) throws Exception { - longCoder.registerByteSizeObserver( - ORDER_PRESERVING_CONVERTER.convert(value), observer, context); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableCoder.java deleted file mode 100644 index 51f24a8d53..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableCoder.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -/** - * An {@link IterableCoder} encodes any {@link Iterable} in the format - * of {@link IterableLikeCoder}. - * - * @param the type of the elements of the iterables being transcoded - */ -public class IterableCoder extends IterableLikeCoder> { - - public static IterableCoder of(Coder elemCoder) { - return new IterableCoder<>(elemCoder); - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal operations below here. - - @Override - protected final Iterable decodeToIterable(List decodedElements) { - return decodedElements; - } - - @JsonCreator - public static IterableCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return of(components.get(0)); - } - - /** - * Returns the first element in this iterable if it is non-empty, - * otherwise returns {@code null}. - */ - public static List getInstanceComponents( - Iterable exampleValue) { - return getInstanceComponentsHelper(exampleValue); - } - - protected IterableCoder(Coder elemCoder) { - super(elemCoder, "Iterable"); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addBoolean(result, PropertyNames.IS_STREAM_LIKE, true); - return result; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableLikeCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableLikeCoder.java deleted file mode 100644 index 3c80c4805e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/IterableLikeCoder.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.BufferedElementCountingOutputStream; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObservableIterable; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Observable; -import java.util.Observer; - -/** - * An abstract base class with functionality for assembling a - * {@link Coder} for a class that implements {@code Iterable}. - * - *

              To complete a subclass, implement the {@link #decodeToIterable} method. This superclass - * will decode the elements in the input stream into a {@link List} and then pass them to that - * method to be converted into the appropriate iterable type. Note that this means the input - * iterables must fit into memory. - * - *

              The format of this coder is as follows: - * - *

                - *
              • If the input {@link Iterable} has a known and finite size, then the size is written to the - * output stream in big endian format, followed by all of the encoded elements.
              • - *
              • If the input {@link Iterable} is not known to have a finite size, then each element - * of the input is preceded by {@code true} encoded as a byte (indicating "more data") - * followed by the encoded element, and terminated by {@code false} encoded as a byte.
              • - *
              - * - * @param the type of the elements of the {@code Iterable}s being transcoded - * @param the type of the Iterables being transcoded - */ -public abstract class IterableLikeCoder> - extends StandardCoder { - public Coder getElemCoder() { - return elementCoder; - } - - /** - * Builds an instance of {@code IterableT}, this coder's associated {@link Iterable}-like - * subtype, from a list of decoded elements. - */ - protected abstract IterableT decodeToIterable(List decodedElements); - - ///////////////////////////////////////////////////////////////////////////// - // Internal operations below here. - - private final Coder elementCoder; - private final String iterableName; - - /** - * Returns the first element in the iterable-like {@code exampleValue} if it is non-empty, - * otherwise returns {@code null}. - */ - protected static > - List getInstanceComponentsHelper(IterableT exampleValue) { - for (T value : exampleValue) { - return Arrays.asList(value); - } - return null; - } - - protected IterableLikeCoder(Coder elementCoder, String iterableName) { - checkArgument(elementCoder != null, "element Coder for IterableLikeCoder must not be null"); - checkArgument(iterableName != null, "iterable name for IterableLikeCoder must not be null"); - this.elementCoder = elementCoder; - this.iterableName = iterableName; - } - - @Override - public void encode( - IterableT iterable, OutputStream outStream, Context context) - throws IOException, CoderException { - if (iterable == null) { - throw new CoderException("cannot encode a null " + iterableName); - } - Context nestedContext = context.nested(); - DataOutputStream dataOutStream = new DataOutputStream(outStream); - if (iterable instanceof Collection) { - // We can know the size of the Iterable. Use an encoding with a - // leading size field, followed by that many elements. - Collection collection = (Collection) iterable; - dataOutStream.writeInt(collection.size()); - for (T elem : collection) { - elementCoder.encode(elem, dataOutStream, nestedContext); - } - } else { - // We don't know the size without traversing it so use a fixed size buffer - // and encode as many elements as possible into it before outputting the size followed - // by the elements. - dataOutStream.writeInt(-1); - BufferedElementCountingOutputStream countingOutputStream = - new BufferedElementCountingOutputStream(dataOutStream); - for (T elem : iterable) { - countingOutputStream.markElementStart(); - elementCoder.encode(elem, countingOutputStream, nestedContext); - } - countingOutputStream.finish(); - } - // Make sure all our output gets pushed to the underlying outStream. - dataOutStream.flush(); - } - - @Override - public IterableT decode(InputStream inStream, Context context) - throws IOException, CoderException { - Context nestedContext = context.nested(); - DataInputStream dataInStream = new DataInputStream(inStream); - int size = dataInStream.readInt(); - if (size >= 0) { - List elements = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - elements.add(elementCoder.decode(dataInStream, nestedContext)); - } - return decodeToIterable(elements); - } else { - List elements = new ArrayList<>(); - long count; - // We don't know the size a priori. Check if we're done with - // each block of elements. - while ((count = VarInt.decodeLong(dataInStream)) > 0) { - while (count > 0) { - elements.add(elementCoder.decode(dataInStream, nestedContext)); - count -= 1; - } - } - return decodeToIterable(elements); - } - } - - @Override - public List> getCoderArguments() { - return Arrays.asList(elementCoder); - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException always. - * Encoding is not deterministic for the general {@link Iterable} case, as it depends - * upon the type of iterable. This may allow two objects to compare as equal - * while the encoding differs. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "IterableLikeCoder can not guarantee deterministic ordering."); - } - - /** - * {@inheritDoc} - * - * @return {@code true} if the iterable is of a known class that supports lazy counting - * of byte size, since that requires minimal extra computation. - */ - @Override - public boolean isRegisterByteSizeObserverCheap( - IterableT iterable, Context context) { - return iterable instanceof ElementByteSizeObservableIterable; - } - - @Override - public void registerByteSizeObserver( - IterableT iterable, ElementByteSizeObserver observer, Context context) - throws Exception { - if (iterable == null) { - throw new CoderException("cannot encode a null Iterable"); - } - Context nestedContext = context.nested(); - - if (iterable instanceof ElementByteSizeObservableIterable) { - observer.setLazy(); - ElementByteSizeObservableIterable observableIterable = - (ElementByteSizeObservableIterable) iterable; - observableIterable.addObserver( - new IteratorObserver(observer, iterable instanceof Collection)); - } else { - if (iterable instanceof Collection) { - // We can know the size of the Iterable. Use an encoding with a - // leading size field, followed by that many elements. - Collection collection = (Collection) iterable; - observer.update(4L); - for (T elem : collection) { - elementCoder.registerByteSizeObserver(elem, observer, nestedContext); - } - } else { - // TODO: Update to use an accurate count depending on size and count, currently we - // are under estimating the size by up to 10 bytes per block of data since we are - // not encoding the count prefix which occurs at most once per 64k of data and is upto - // 10 bytes long. Since we include the total count we can upper bound the underestimate - // to be 10 / 65536 ~= 0.0153% of the actual size. - observer.update(4L); - long count = 0; - for (T elem : iterable) { - count += 1; - elementCoder.registerByteSizeObserver(elem, observer, nestedContext); - } - if (count > 0) { - // Update the length based upon the number of counted elements, this helps - // eliminate the case where all the elements are encoded in the first block and - // it is quite short (e.g. Long.MAX_VALUE nulls encoded with VoidCoder). - observer.update(VarInt.getLength(count)); - } - // Update with the terminator byte. - observer.update(1L); - } - } - } - - /** - * An observer that gets notified when an observable iterator - * returns a new value. This observer just notifies an outerObserver - * about this event. Additionally, the outerObserver is notified - * about additional separators that are transparently added by this - * coder. - */ - private class IteratorObserver implements Observer { - private final ElementByteSizeObserver outerObserver; - private final boolean countable; - - public IteratorObserver(ElementByteSizeObserver outerObserver, - boolean countable) { - this.outerObserver = outerObserver; - this.countable = countable; - - if (countable) { - // Additional 4 bytes are due to size. - outerObserver.update(4L); - } else { - // Additional 5 bytes are due to size = -1 (4 bytes) and - // hasNext = false (1 byte). - outerObserver.update(5L); - } - } - - @Override - public void update(Observable obs, Object obj) { - if (!(obj instanceof Long)) { - throw new AssertionError("unexpected parameter object"); - } - - if (countable) { - outerObserver.update(obs, obj); - } else { - // Additional 1 byte is due to hasNext = true flag. - outerObserver.update(obs, 1 + (long) obj); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java deleted file mode 100644 index 2aa8b234ef..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/JAXBCoder.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.Structs; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.FilterInputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; - -/** - * A coder for JAXB annotated objects. This coder uses JAXB marshalling/unmarshalling mechanisms - * to encode/decode the objects. Users must provide the {@code Class} of the JAXB annotated object. - * - * @param type of JAXB annotated objects that will be serialized. - */ -public class JAXBCoder extends AtomicCoder { - - private final Class jaxbClass; - private transient volatile JAXBContext jaxbContext; - - public Class getJAXBClass() { - return jaxbClass; - } - - private JAXBCoder(Class jaxbClass) { - this.jaxbClass = jaxbClass; - } - - /** - * Create a coder for a given type of JAXB annotated objects. - * - * @param jaxbClass the {@code Class} of the JAXB annotated objects. - */ - public static JAXBCoder of(Class jaxbClass) { - return new JAXBCoder<>(jaxbClass); - } - - @Override - public void encode(T value, OutputStream outStream, Context context) - throws CoderException, IOException { - try { - JAXBContext jaxbContext = getContext(); - // TODO: Consider caching in a ThreadLocal if this impacts performance - Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); - - jaxbMarshaller.marshal(value, new FilterOutputStream(outStream) { - // JAXB closes the underyling stream so we must filter out those calls. - @Override - public void close() throws IOException { - } - }); - } catch (JAXBException e) { - throw new CoderException(e); - } - } - - @Override - public T decode(InputStream inStream, Context context) throws CoderException, IOException { - try { - JAXBContext jaxbContext = getContext(); - // TODO: Consider caching in a ThreadLocal if this impacts performance - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - - @SuppressWarnings("unchecked") - T obj = (T) jaxbUnmarshaller.unmarshal(new FilterInputStream(inStream) { - // JAXB closes the underyling stream so we must filter out those calls. - @Override - public void close() throws IOException { - } - }); - return obj; - } catch (JAXBException e) { - throw new CoderException(e); - } - } - - private JAXBContext getContext() throws JAXBException { - if (jaxbContext == null) { - synchronized (this) { - if (jaxbContext == null) { - jaxbContext = JAXBContext.newInstance(jaxbClass); - } - } - } - return jaxbContext; - } - - @Override - public String getEncodingId() { - return getJAXBClass().getName(); - } - - //////////////////////////////////////////////////////////////////////////////////// - // JSON Serialization details below - - private static final String JAXB_CLASS = "jaxb_class"; - - /** - * Constructor for JSON deserialization only. - */ - @JsonCreator - public static JAXBCoder of( - @JsonProperty(JAXB_CLASS) String jaxbClassName) { - try { - @SuppressWarnings("unchecked") - Class jaxbClass = (Class) Class.forName(jaxbClassName); - return of(jaxbClass); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException(e); - } - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - Structs.addString(result, JAXB_CLASS, jaxbClass.getName()); - return result; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoder.java deleted file mode 100644 index 61854ca48e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoder.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.values.KV; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; - -/** - * A {@code KvCoder} encodes {@link KV}s. - * - * @param the type of the keys of the KVs being transcoded - * @param the type of the values of the KVs being transcoded - */ -public class KvCoder extends KvCoderBase> { - public static KvCoder of(Coder keyCoder, - Coder valueCoder) { - return new KvCoder<>(keyCoder, valueCoder); - } - - @JsonCreator - public static KvCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 2, "Expecting 2 components, got " + components.size()); - return of(components.get(0), components.get(1)); - } - - public static List getInstanceComponents( - KV exampleValue) { - return Arrays.asList( - exampleValue.getKey(), - exampleValue.getValue()); - } - - public Coder getKeyCoder() { - return keyCoder; - } - - public Coder getValueCoder() { - return valueCoder; - } - - ///////////////////////////////////////////////////////////////////////////// - - private final Coder keyCoder; - private final Coder valueCoder; - - private KvCoder(Coder keyCoder, Coder valueCoder) { - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; - } - - @Override - public void encode(KV kv, OutputStream outStream, Context context) - throws IOException, CoderException { - if (kv == null) { - throw new CoderException("cannot encode a null KV"); - } - Context nestedContext = context.nested(); - keyCoder.encode(kv.getKey(), outStream, nestedContext); - valueCoder.encode(kv.getValue(), outStream, nestedContext); - } - - @Override - public KV decode(InputStream inStream, Context context) - throws IOException, CoderException { - Context nestedContext = context.nested(); - K key = keyCoder.decode(inStream, nestedContext); - V value = valueCoder.decode(inStream, nestedContext); - return KV.of(key, value); - } - - @Override - public List> getCoderArguments() { - return Arrays.asList(keyCoder, valueCoder); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic("Key coder must be deterministic", getKeyCoder()); - verifyDeterministic("Value coder must be deterministic", getValueCoder()); - } - - @Override - public boolean consistentWithEquals() { - return keyCoder.consistentWithEquals() && valueCoder.consistentWithEquals(); - } - - @Override - public Object structuralValue(KV kv) throws Exception { - if (consistentWithEquals()) { - return kv; - } else { - return KV.of(getKeyCoder().structuralValue(kv.getKey()), - getValueCoder().structuralValue(kv.getValue())); - } - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addBoolean(result, PropertyNames.IS_PAIR_LIKE, true); - return result; - } - - /** - * Returns whether both keyCoder and valueCoder are considered not expensive. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(KV kv, Context context) { - return keyCoder.isRegisterByteSizeObserverCheap(kv.getKey(), - context.nested()) - && valueCoder.isRegisterByteSizeObserverCheap(kv.getValue(), - context.nested()); - } - - /** - * Notifies ElementByteSizeObserver about the byte size of the - * encoded value using this coder. - */ - @Override - public void registerByteSizeObserver( - KV kv, ElementByteSizeObserver observer, Context context) - throws Exception { - if (kv == null) { - throw new CoderException("cannot encode a null KV"); - } - keyCoder.registerByteSizeObserver( - kv.getKey(), observer, context.nested()); - valueCoder.registerByteSizeObserver( - kv.getValue(), observer, context.nested()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java deleted file mode 100644 index 4a12ee0d96..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/KvCoderBase.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -/** - * A abstract base class for KvCoder. Works around a Jackson2 bug tickled when building - * {@link KvCoder} directly (as of this writing, Jackson2 walks off the end of - * an array when it tries to deserialize a class with multiple generic type - * parameters). This class should be removed when possible. - * - * @param the type of values being transcoded - */ -@Deprecated -public abstract class KvCoderBase extends StandardCoder { - /** - * A constructor used only for decoding from JSON. - * - * @param typeId present in the JSON encoding, but unused - * @param isPairLike present in the JSON encoding, but unused - */ - @Deprecated - @JsonCreator - public static KvCoderBase of( - // N.B. typeId is a required parameter here, since a field named "@type" - // is presented to the deserializer as an input. - // - // If this method did not consume the field, Jackson2 would observe an - // unconsumed field and a returned value of a derived type. So Jackson2 - // would attempt to update the returned value with the unconsumed field - // data. The standard JsonDeserializer does not implement a mechanism for - // updating constructed values, so it would throw an exception, causing - // deserialization to fail. - @JsonProperty(value = "@type", required = false) String typeId, - @JsonProperty(value = PropertyNames.IS_PAIR_LIKE, required = false) boolean isPairLike, - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { - return KvCoder.of(components); - } - - protected KvCoderBase() {} -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ListCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ListCoder.java deleted file mode 100644 index ff3387bdbc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/ListCoder.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -/** - * A {@link Coder} for {@link List}, using the format of {@link IterableLikeCoder}. - * - * @param the type of the elements of the Lists being transcoded - */ -public class ListCoder extends IterableLikeCoder> { - - public static ListCoder of(Coder elemCoder) { - return new ListCoder<>(elemCoder); - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal operations below here. - - @Override - protected final List decodeToIterable(List decodedElements) { - return decodedElements; - } - - @JsonCreator - public static ListCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return of((Coder) components.get(0)); - } - - /** - * Returns the first element in this list if it is non-empty, - * otherwise returns {@code null}. - */ - public static List getInstanceComponents(List exampleValue) { - return getInstanceComponentsHelper(exampleValue); - } - - protected ListCoder(Coder elemCoder) { - super(elemCoder, "List"); - } - - /** - * List sizes are always known, so ListIterable may be deterministic while - * the general IterableLikeCoder is not. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "ListCoder.elemCoder must be deterministic", getElemCoder()); - } - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoder.java deleted file mode 100644 index 897ee81938..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoder.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.common.collect.Maps; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * A {@link Coder} for {@link Map Maps} that encodes them according to provided - * coders for keys and values. - * - * @param the type of the keys of the KVs being transcoded - * @param the type of the values of the KVs being transcoded - */ -public class MapCoder extends MapCoderBase> { - /** - * Produces a MapCoder with the given keyCoder and valueCoder. - */ - public static MapCoder of( - Coder keyCoder, - Coder valueCoder) { - return new MapCoder<>(keyCoder, valueCoder); - } - - @JsonCreator - public static MapCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 2, "Expecting 2 components, got " + components.size()); - return of((Coder) components.get(0), (Coder) components.get(1)); - } - - /** - * Returns the key and value for an arbitrary element of this map, - * if it is non-empty, otherwise returns {@code null}. - */ - public static List getInstanceComponents( - Map exampleValue) { - for (Map.Entry entry : exampleValue.entrySet()) { - return Arrays.asList(entry.getKey(), entry.getValue()); - } - return null; - } - - public Coder getKeyCoder() { - return keyCoder; - } - - public Coder getValueCoder() { - return valueCoder; - } - - ///////////////////////////////////////////////////////////////////////////// - - Coder keyCoder; - Coder valueCoder; - - MapCoder(Coder keyCoder, Coder valueCoder) { - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; - } - - @Override - public void encode( - Map map, - OutputStream outStream, - Context context) - throws IOException, CoderException { - if (map == null) { - throw new CoderException("cannot encode a null Map"); - } - DataOutputStream dataOutStream = new DataOutputStream(outStream); - dataOutStream.writeInt(map.size()); - for (Entry entry : map.entrySet()) { - keyCoder.encode(entry.getKey(), outStream, context.nested()); - valueCoder.encode(entry.getValue(), outStream, context.nested()); - } - dataOutStream.flush(); - } - - @Override - public Map decode(InputStream inStream, Context context) - throws IOException, CoderException { - DataInputStream dataInStream = new DataInputStream(inStream); - int size = dataInStream.readInt(); - Map retval = Maps.newHashMapWithExpectedSize(size); - for (int i = 0; i < size; ++i) { - K key = keyCoder.decode(inStream, context.nested()); - V value = valueCoder.decode(inStream, context.nested()); - retval.put(key, value); - } - return retval; - } - - /** - * {@inheritDoc} - * - * @return a {@link List} containing the key coder at index 0 at the and value coder at index 1. - */ - @Override - public List> getCoderArguments() { - return Arrays.asList(keyCoder, valueCoder); - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException always. Not all maps have a deterministic encoding. - * For example, {@code HashMap} comparison does not depend on element order, so - * two {@code HashMap} instances may be equal but produce different encodings. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "Ordering of entries in a Map may be non-deterministic."); - } - - @Override - public void registerByteSizeObserver( - Map map, ElementByteSizeObserver observer, Context context) - throws Exception { - observer.update(4L); - for (Entry entry : map.entrySet()) { - keyCoder.registerByteSizeObserver( - entry.getKey(), observer, context.nested()); - valueCoder.registerByteSizeObserver( - entry.getValue(), observer, context.nested()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java deleted file mode 100644 index d32406c50d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/MapCoderBase.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -/** - * A abstract base class for MapCoder. Works around a Jackson2 bug tickled when building - * {@link MapCoder} directly (as of this writing, Jackson2 walks off the end of - * an array when it tries to deserialize a class with multiple generic type - * parameters). This should be removed in favor of a better workaround. - * @param the type of values being transcoded - */ -@Deprecated -public abstract class MapCoderBase extends StandardCoder { - @Deprecated - @JsonCreator - public static MapCoderBase of( - // N.B. typeId is a required parameter here, since a field named "@type" - // is presented to the deserializer as an input. - // - // If this method did not consume the field, Jackson2 would observe an - // unconsumed field and a returned value of a derived type. So Jackson2 - // would attempt to update the returned value with the unconsumed field - // data, The standard JsonDeserializer does not implement a mechanism for - // updating constructed values, so it would throw an exception, causing - // deserialization to fail. - @JsonProperty(value = "@type", required = false) String typeId, - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - return MapCoder.of(components); - } - - protected MapCoderBase() {} -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/NullableCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/NullableCoder.java deleted file mode 100644 index 39a5e09533..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/NullableCoder.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A {@link NullableCoder} encodes nullable values of type {@code T} using a nested - * {@code Coder} that does not tolerate {@code null} values. {@link NullableCoder} uses - * exactly 1 byte per entry to indicate whether the value is {@code null}, then adds the encoding - * of the inner coder for non-null values. - * - * @param the type of the values being transcoded - */ -public class NullableCoder extends StandardCoder { - public static NullableCoder of(Coder valueCoder) { - return new NullableCoder<>(valueCoder); - } - - @JsonCreator - public static NullableCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 components, got " + components.size()); - return of(components.get(0)); - } - - ///////////////////////////////////////////////////////////////////////////// - - private final Coder valueCoder; - private static final int ENCODE_NULL = 0; - private static final int ENCODE_PRESENT = 1; - - private NullableCoder(Coder valueCoder) { - this.valueCoder = valueCoder; - } - - @Override - public void encode(@Nullable T value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - outStream.write(ENCODE_NULL); - } else { - outStream.write(ENCODE_PRESENT); - valueCoder.encode(value, outStream, context.nested()); - } - } - - @Override - @Nullable - public T decode(InputStream inStream, Context context) throws IOException, CoderException { - int b = inStream.read(); - if (b == ENCODE_NULL) { - return null; - } else if (b != ENCODE_PRESENT) { - throw new CoderException(String.format( - "NullableCoder expects either a byte valued %s (null) or %s (present), got %s", - ENCODE_NULL, ENCODE_PRESENT, b)); - } - return valueCoder.decode(inStream, context.nested()); - } - - @Override - public List> getCoderArguments() { - return ImmutableList.of(valueCoder); - } - - /** - * {@code NullableCoder} is deterministic if the nested {@code Coder} is. - * - * {@inheritDoc} - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic("Value coder must be deterministic", valueCoder); - } - - /** - * {@code NullableCoder} is consistent with equals if the nested {@code Coder} is. - * - * {@inheritDoc} - */ - @Override - public boolean consistentWithEquals() { - return valueCoder.consistentWithEquals(); - } - - @Override - public Object structuralValue(@Nullable T value) throws Exception { - if (value == null) { - return Optional.absent(); - } - return Optional.of(valueCoder.structuralValue(value)); - } - - /** - * Overridden to short-circuit the default {@code StandardCoder} behavior of encoding and - * counting the bytes. The size is known (1 byte) when {@code value} is {@code null}, otherwise - * the size is 1 byte plus the size of nested {@code Coder}'s encoding of {@code value}. - * - * {@inheritDoc} - */ - @Override - public void registerByteSizeObserver( - @Nullable T value, ElementByteSizeObserver observer, Context context) throws Exception { - observer.update(1); - if (value != null) { - valueCoder.registerByteSizeObserver(value, observer, context.nested()); - } - } - - /** - * Overridden to short-circuit the default {@code StandardCoder} behavior of encoding and - * counting the bytes. The size is known (1 byte) when {@code value} is {@code null}, otherwise - * the size is 1 byte plus the size of nested {@code Coder}'s encoding of {@code value}. - * - * {@inheritDoc} - */ - @Override - protected long getEncodedElementByteSize(@Nullable T value, Context context) throws Exception { - if (value == null) { - return 1; - } - - if (valueCoder instanceof StandardCoder) { - // If valueCoder is a StandardCoder then we can ask it directly for the encoded size of - // the value, adding 1 byte to count the null indicator. - return 1 + ((StandardCoder) valueCoder) - .getEncodedElementByteSize(value, context.nested()); - } - - // If value is not a StandardCoder then fall back to the default StandardCoder behavior - // of encoding and counting the bytes. The encoding will include the null indicator byte. - return super.getEncodedElementByteSize(value, context); - } - - /** - * {@code NullableCoder} is cheap if {@code valueCoder} is cheap. - * - * {@inheritDoc} - */ - @Override - public boolean isRegisterByteSizeObserverCheap(@Nullable T value, Context context) { - return valueCoder.isRegisterByteSizeObserverCheap(value, context.nested()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java deleted file mode 100644 index ef91ba96e8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/Proto2Coder.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.Structs; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.protobuf.ExtensionRegistry; -import com.google.protobuf.Message; -import com.google.protobuf.Parser; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import javax.annotation.Nullable; - -/** - * A {@link Coder} using Google Protocol Buffers 2 binary format. - * - *

              To learn more about Protocol Buffers, visit: - * https://developers.google.com/protocol-buffers - * - *

              To use, specify the {@link Coder} type on a PCollection containing Protocol Buffers messages. - * - *

              - * {@code
              - * PCollection records =
              - *     input.apply(...)
              - *          .setCoder(Proto2Coder.of(MyProto.Message.class));
              - * }
              - * 
              - * - *

              Custom message extensions are also supported, but the coder must be made - * aware of them explicitly: - * - *

              - * {@code
              - * PCollection records =
              - *     input.apply(...)
              - *          .setCoder(Proto2Coder.of(MyProto.Message.class)
              - *              .addExtensionsFrom(MyProto.class));
              - * }
              - * 
              - * - * @param the type of elements handled by this coder, must extend {@code Message} - * @deprecated Use {@link ProtoCoder}. - */ -@Deprecated -public class Proto2Coder extends AtomicCoder { - - /** The class of Protobuf message to be encoded. */ - private final Class protoMessageClass; - - /** - * All extension host classes included in this Proto2Coder. The extensions from - * these classes will be included in the {@link ExtensionRegistry} used during - * encoding and decoding. - */ - private final List> extensionHostClasses; - - private Proto2Coder(Class protoMessageClass, List> extensionHostClasses) { - this.protoMessageClass = protoMessageClass; - this.extensionHostClasses = extensionHostClasses; - } - - private static final CoderProvider PROVIDER = - new CoderProvider() { - @Override - public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { - if (type.isSubtypeOf(new TypeDescriptor() {})) { - @SuppressWarnings("unchecked") - TypeDescriptor messageType = - (TypeDescriptor) type; - @SuppressWarnings("unchecked") - Coder coder = (Coder) Proto2Coder.of(messageType); - return coder; - } else { - throw new CannotProvideCoderException( - String.format( - "Cannot provide Proto2Coder because %s " - + "is not a subclass of protocol buffer Messsage", - type)); - } - } - }; - - public static CoderProvider coderProvider() { - return PROVIDER; - } - - /** - * Returns a {@code Proto2Coder} for the given Protobuf message class. - */ - public static Proto2Coder of(Class protoMessageClass) { - return new Proto2Coder(protoMessageClass, Collections.>emptyList()); - } - - /** - * Returns a {@code Proto2Coder} for the given Protobuf message class. - */ - public static Proto2Coder of(TypeDescriptor protoMessageType) { - @SuppressWarnings("unchecked") - Class protoMessageClass = (Class) protoMessageType.getRawType(); - return of(protoMessageClass); - } - - /** - * Produces a {@code Proto2Coder} like this one, but with the extensions from - * the given classes registered. - * - * @param moreExtensionHosts an iterable of classes that define a static - * method {@code registerAllExtensions(ExtensionRegistry)} - */ - public Proto2Coder withExtensionsFrom(Iterable> moreExtensionHosts) { - for (Class extensionHost : moreExtensionHosts) { - // Attempt to access the required method, to make sure it's present. - try { - Method registerAllExtensions = - extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class); - checkArgument( - Modifier.isStatic(registerAllExtensions.getModifiers()), - "Method registerAllExtensions() must be static for use with Proto2Coder"); - } catch (NoSuchMethodException | SecurityException e) { - throw new IllegalArgumentException(e); - } - } - - return new Proto2Coder( - protoMessageClass, - new ImmutableList.Builder>() - .addAll(extensionHostClasses) - .addAll(moreExtensionHosts) - .build()); - } - - /** - * See {@link #withExtensionsFrom(Iterable)}. - */ - public Proto2Coder withExtensionsFrom(Class... extensionHosts) { - return withExtensionsFrom(ImmutableList.copyOf(extensionHosts)); - } - - /** - * Adds custom Protobuf extensions to the coder. Returns {@code this} - * for method chaining. - * - * @param extensionHosts must be a class that defines a static - * method name {@code registerAllExtensions} - * @deprecated use {@link #withExtensionsFrom} - */ - @Deprecated - public Proto2Coder addExtensionsFrom(Class... extensionHosts) { - return addExtensionsFrom(ImmutableList.copyOf(extensionHosts)); - } - - /** - * Adds custom Protobuf extensions to the coder. Returns {@code this} - * for method chaining. - * - * @param extensionHosts must be a class that defines a static - * method name {@code registerAllExtensions} - * @deprecated use {@link #withExtensionsFrom} - */ - @Deprecated - public Proto2Coder addExtensionsFrom(Iterable> extensionHosts) { - for (Class extensionHost : extensionHosts) { - try { - // Attempt to access the declared method, to make sure it's present. - extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(e); - } - extensionHostClasses.add(extensionHost); - } - // The memoized extension registry needs to be recomputed because we have mutated this object. - synchronized (this) { - memoizedExtensionRegistry = null; - getExtensionRegistry(); - } - return this; - } - - @Override - public void encode(T value, OutputStream outStream, Context context) throws IOException { - if (value == null) { - throw new CoderException("cannot encode a null " + protoMessageClass.getSimpleName()); - } - if (context.isWholeStream) { - value.writeTo(outStream); - } else { - value.writeDelimitedTo(outStream); - } - } - - @Override - public T decode(InputStream inStream, Context context) throws IOException { - if (context.isWholeStream) { - return getParser().parseFrom(inStream, getExtensionRegistry()); - } else { - return getParser().parseDelimitedFrom(inStream, getExtensionRegistry()); - } - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof Proto2Coder)) { - return false; - } - Proto2Coder otherCoder = (Proto2Coder) other; - return protoMessageClass.equals(otherCoder.protoMessageClass) - && Sets.newHashSet(extensionHostClasses) - .equals(Sets.newHashSet(otherCoder.extensionHostClasses)); - } - - @Override - public int hashCode() { - return Objects.hash(protoMessageClass, extensionHostClasses); - } - - /** - * The encoding identifier is designed to support evolution as per the design of Protocol - * Buffers. In order to use this class effectively, carefully follow the advice in the Protocol - * Buffers documentation at - * Updating - * A Message Type. - * - *

              In particular, the encoding identifier is guaranteed to be the same for {@code Proto2Coder} - * instances of the same principal message class, and otherwise distinct. Loaded extensions do not - * affect the id, nor does it encode the full schema. - * - *

              When modifying a message class, here are the broadest guidelines; see the above link - * for greater detail. - * - *

                - *
              • Do not change the numeric tags for any fields. - *
              • Never remove a required field. - *
              • Only add optional or repeated fields, with sensible defaults. - *
              • When changing the type of a field, consult the Protocol Buffers documentation to ensure - * the new and old types are interchangeable. - *
              - * - *

              Code consuming this message class should be prepared to support all versions of - * the class until it is certain that no remaining serialized instances exist. - * - *

              If backwards incompatible changes must be made, the best recourse is to change the name - * of your Protocol Buffers message class. - */ - @Override - public String getEncodingId() { - return protoMessageClass.getName(); - } - - private transient Parser memoizedParser; - - private Parser getParser() { - if (memoizedParser == null) { - try { - @SuppressWarnings("unchecked") - T protoMessageInstance = (T) protoMessageClass.getMethod("getDefaultInstance").invoke(null); - @SuppressWarnings("unchecked") - Parser tParser = (Parser) protoMessageInstance.getParserForType(); - memoizedParser = tParser; - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IllegalArgumentException(e); - } - } - return memoizedParser; - } - - private transient ExtensionRegistry memoizedExtensionRegistry; - - private synchronized ExtensionRegistry getExtensionRegistry() { - if (memoizedExtensionRegistry == null) { - ExtensionRegistry registry = ExtensionRegistry.newInstance(); - for (Class extensionHost : extensionHostClasses) { - try { - extensionHost - .getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class) - .invoke(null, registry); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IllegalStateException(e); - } - } - memoizedExtensionRegistry = registry.getUnmodifiable(); - } - return memoizedExtensionRegistry; - } - - //////////////////////////////////////////////////////////////////////////////////// - // JSON Serialization details below - - private static final String PROTO_MESSAGE_CLASS = "proto_message_class"; - private static final String PROTO_EXTENSION_HOSTS = "proto_extension_hosts"; - - /** - * Constructor for JSON deserialization only. - */ - @JsonCreator - public static Proto2Coder of( - @JsonProperty(PROTO_MESSAGE_CLASS) String protoMessageClassName, - @Nullable @JsonProperty(PROTO_EXTENSION_HOSTS) List extensionHostClassNames) { - - try { - @SuppressWarnings("unchecked") - Class protoMessageClass = (Class) Class.forName(protoMessageClassName); - List> extensionHostClasses = Lists.newArrayList(); - if (extensionHostClassNames != null) { - for (String extensionHostClassName : extensionHostClassNames) { - extensionHostClasses.add(Class.forName(extensionHostClassName)); - } - } - return of(protoMessageClass).withExtensionsFrom(extensionHostClasses); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException(e); - } - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - Structs.addString(result, PROTO_MESSAGE_CLASS, protoMessageClass.getName()); - List extensionHostClassNames = Lists.newArrayList(); - for (Class clazz : extensionHostClasses) { - extensionHostClassNames.add(CloudObject.forString(clazz.getName())); - } - Structs.addList(result, PROTO_EXTENSION_HOSTS, extensionHostClassNames); - return result; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SerializableCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SerializableCoder.java deleted file mode 100644 index 593c9f0f80..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SerializableCoder.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamClass; -import java.io.OutputStream; -import java.io.Serializable; - -/** - * A {@link Coder} for Java classes that implement {@link Serializable}. - * - *

              To use, specify the coder type on a PCollection: - *

              - * {@code
              - *   PCollection records =
              - *       foo.apply(...).setCoder(SerializableCoder.of(MyRecord.class));
              - * }
              - * 
              - * - *

              {@link SerializableCoder} does not guarantee a deterministic encoding, as Java - * serialization may produce different binary encodings for two equivalent - * objects. - * - * @param the type of elements handled by this coder - */ -public class SerializableCoder extends AtomicCoder { - - /** - * Returns a {@link SerializableCoder} instance for the provided element type. - * @param the element type - */ - public static SerializableCoder of(TypeDescriptor type) { - @SuppressWarnings("unchecked") - Class clazz = (Class) type.getRawType(); - return of(clazz); - } - - /** - * Returns a {@link SerializableCoder} instance for the provided element class. - * @param the element type - */ - public static SerializableCoder of(Class clazz) { - return new SerializableCoder<>(clazz); - } - - @JsonCreator - @SuppressWarnings("unchecked") - public static SerializableCoder of(@JsonProperty("type") String classType) - throws ClassNotFoundException { - Class clazz = Class.forName(classType); - if (!Serializable.class.isAssignableFrom(clazz)) { - throw new ClassNotFoundException( - "Class " + classType + " does not implement Serializable"); - } - return of((Class) clazz); - } - - /** - * A {@link CoderProvider} that constructs a {@link SerializableCoder} - * for any class that implements serializable. - */ - public static final CoderProvider PROVIDER = new CoderProvider() { - @Override - public Coder getCoder(TypeDescriptor typeDescriptor) - throws CannotProvideCoderException { - Class clazz = typeDescriptor.getRawType(); - if (Serializable.class.isAssignableFrom(clazz)) { - @SuppressWarnings("unchecked") - Class serializableClazz = - (Class) clazz; - @SuppressWarnings("unchecked") - Coder coder = (Coder) SerializableCoder.of(serializableClazz); - return coder; - } else { - throw new CannotProvideCoderException( - "Cannot provide SerializableCoder because " + typeDescriptor - + " does not implement Serializable"); - } - } - }; - - - private final Class type; - - protected SerializableCoder(Class type) { - this.type = type; - } - - public Class getRecordType() { - return type; - } - - @Override - public void encode(T value, OutputStream outStream, Context context) - throws IOException, CoderException { - try { - ObjectOutputStream oos = new ObjectOutputStream(outStream); - oos.writeObject(value); - oos.flush(); - } catch (IOException exn) { - throw new CoderException("unable to serialize record " + value, exn); - } - } - - @Override - public T decode(InputStream inStream, Context context) - throws IOException, CoderException { - try { - ObjectInputStream ois = new ObjectInputStream(inStream); - return type.cast(ois.readObject()); - } catch (ClassNotFoundException e) { - throw new CoderException("unable to deserialize record", e); - } - } - - @Override - public String getEncodingId() { - return String.format("%s:%s", - type.getName(), - ObjectStreamClass.lookup(type).getSerialVersionUID()); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - result.put("type", type.getName()); - return result; - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException always. Java serialization is not - * deterministic with respect to {@link Object#equals} for all types. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "Java Serialization may be non-deterministic."); - } - - @Override - public boolean equals(Object other) { - if (getClass() != other.getClass()) { - return false; - } - return type == ((SerializableCoder) other).type; - } - - @Override - public int hashCode() { - return type.hashCode(); - } - - // This coder inherits isRegisterByteSizeObserverCheap, - // getEncodedElementByteSize and registerByteSizeObserver - // from StandardCoder. Looks like we cannot do much better - // in this case. -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SetCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SetCoder.java deleted file mode 100644 index 1445885f2c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/SetCoder.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * A {@link SetCoder} encodes any {@link Set} using the format of {@link IterableLikeCoder}. The - * elements may not be in a deterministic order, depending on the {@code Set} implementation. - * - * @param the type of the elements of the set - */ -public class SetCoder extends IterableLikeCoder> { - - /** - * Produces a {@link SetCoder} with the given {@code elementCoder}. - */ - public static SetCoder of(Coder elementCoder) { - return new SetCoder<>(elementCoder); - } - - /** - * Dynamically typed constructor for JSON deserialization. - */ - @JsonCreator - public static SetCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List components) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return of((Coder) components.get(0)); - } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException always. Sets are not ordered, but - * they are encoded in the order of an arbitrary iteration. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "Ordering of elements in a set may be non-deterministic."); - } - - /** - * Returns the first element in this set if it is non-empty, - * otherwise returns {@code null}. - */ - public static List getInstanceComponents( - Set exampleValue) { - return getInstanceComponentsHelper(exampleValue); - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal operations below here. - - /** - * {@inheritDoc} - * - * @return A new {@link Set} built from the elements in the {@link List} decoded by - * {@link IterableLikeCoder}. - */ - @Override - protected final Set decodeToIterable(List decodedElements) { - return new HashSet<>(decodedElements); - } - - protected SetCoder(Coder elemCoder) { - super(elemCoder, "Set"); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java deleted file mode 100644 index faa98619ec..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StandardCoder.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.cloud.dataflow.sdk.util.Structs.addList; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.common.collect.Lists; -import com.google.common.io.ByteStreams; -import com.google.common.io.CountingOutputStream; - -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** - * An abstract base class to implement a {@link Coder} that defines equality, hashing, and printing - * via the class name and recursively using {@link #getComponents}. - * - *

              To extend {@link StandardCoder}, override the following methods as appropriate: - * - *

                - *
              • {@link #getComponents}: the default implementation returns {@link #getCoderArguments}.
              • - *
              • {@link #getEncodedElementByteSize} and - * {@link #isRegisterByteSizeObserverCheap}: the - * default implementation encodes values to bytes and counts the bytes, which is considered - * expensive.
              • - *
              • {@link #getEncodingId} and {@link #getAllowedEncodings}: by default, the encoding id - * is the empty string, so only the canonical name of the subclass will be used for - * compatibility checks, and no other encoding ids are allowed.
              • - *
              - */ -public abstract class StandardCoder implements Coder { - protected StandardCoder() {} - - @Override - public String getEncodingId() { - return ""; - } - - @Override - public Collection getAllowedEncodings() { - return Collections.emptyList(); - } - - /** - * Returns the list of {@link Coder Coders} that are components of this {@link Coder}. - */ - public List> getComponents() { - List> coderArguments = getCoderArguments(); - if (coderArguments == null) { - return Collections.emptyList(); - } else { - return coderArguments; - } - } - - /** - * {@inheritDoc} - * - * @return {@code true} if the two {@link StandardCoder} instances have the - * same class and equal components. - */ - @Override - public boolean equals(Object o) { - if (o == null || this.getClass() != o.getClass()) { - return false; - } - StandardCoder that = (StandardCoder) o; - return this.getComponents().equals(that.getComponents()); - } - - @Override - public int hashCode() { - return getClass().hashCode() * 31 + getComponents().hashCode(); - } - - @Override - public String toString() { - String s = getClass().getName(); - s = s.substring(s.lastIndexOf('.') + 1); - List> componentCoders = getComponents(); - if (!componentCoders.isEmpty()) { - s += "("; - boolean first = true; - for (Coder componentCoder : componentCoders) { - if (first) { - first = false; - } else { - s += ", "; - } - s += componentCoder.toString(); - } - s += ")"; - } - return s; - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = CloudObject.forClass(getClass()); - - List> components = getComponents(); - if (!components.isEmpty()) { - List cloudComponents = new ArrayList<>(components.size()); - for (Coder coder : components) { - cloudComponents.add(coder.asCloudObject()); - } - addList(result, PropertyNames.COMPONENT_ENCODINGS, cloudComponents); - } - - String encodingId = getEncodingId(); - checkNotNull(encodingId, "Coder.getEncodingId() must not return null."); - if (!encodingId.isEmpty()) { - addString(result, PropertyNames.ENCODING_ID, encodingId); - } - - Collection allowedEncodings = getAllowedEncodings(); - if (!allowedEncodings.isEmpty()) { - addStringList(result, PropertyNames.ALLOWED_ENCODINGS, Lists.newArrayList(allowedEncodings)); - } - - return result; - } - - /** - * {@inheritDoc} - * - * @return {@code false} unless it is overridden. {@link StandardCoder#registerByteSizeObserver} - * invokes {@link #getEncodedElementByteSize} which requires re-encoding an element - * unless it is overridden. This is considered expensive. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(T value, Context context) { - return false; - } - - /** - * Returns the size in bytes of the encoded value using this coder. - */ - protected long getEncodedElementByteSize(T value, Context context) - throws Exception { - try { - CountingOutputStream os = new CountingOutputStream(ByteStreams.nullOutputStream()); - encode(value, os, context); - return os.getCount(); - } catch (Exception exn) { - throw new IllegalArgumentException( - "Unable to encode element '" + value + "' with coder '" + this + "'.", exn); - } - } - - /** - * {@inheritDoc} - * - *

              For {@link StandardCoder} subclasses, this notifies {@code observer} about the byte size - * of the encoded value using this coder as returned by {@link #getEncodedElementByteSize}. - */ - @Override - public void registerByteSizeObserver( - T value, ElementByteSizeObserver observer, Context context) - throws Exception { - observer.update(getEncodedElementByteSize(value, context)); - } - - protected void verifyDeterministic(String message, Iterable> coders) - throws NonDeterministicException { - for (Coder coder : coders) { - try { - coder.verifyDeterministic(); - } catch (NonDeterministicException e) { - throw new NonDeterministicException(this, message, e); - } - } - } - - protected void verifyDeterministic(String message, Coder... coders) - throws NonDeterministicException { - verifyDeterministic(message, Arrays.asList(coders)); - } - - /** - * {@inheritDoc} - * - * @return {@code false} for {@link StandardCoder} unless overridden. - */ - @Override - public boolean consistentWithEquals() { - return false; - } - - @Override - public Object structuralValue(T value) throws Exception { - if (value != null && consistentWithEquals()) { - return value; - } else { - try { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - encode(value, os, Context.OUTER); - return new StructuralByteArray(os.toByteArray()); - } catch (Exception exn) { - throw new IllegalArgumentException( - "Unable to encode element '" + value + "' with coder '" + this + "'.", exn); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java deleted file mode 100644 index 1fc1247226..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoder.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; - -import java.lang.reflect.InvocationTargetException; - -/** - * A {@link Coder} that wraps a {@code Coder} - * and encodes/decodes values via string representations. - * - *

              To decode, the input byte stream is decoded to - * a {@link String}, and this is passed to the single-argument - * constructor for {@code T}. - * - *

              To encode, the input value is converted via {@code toString()}, - * and this string is encoded. - * - *

              In order for this to operate correctly for a class {@code Clazz}, - * it must be the case for any instance {@code x} that - * {@code x.equals(new Clazz(x.toString()))}. - * - *

              This method of encoding is not designed for ease of evolution of {@code Clazz}; - * it should only be used in cases where the class is stable or the encoding is not - * important. If evolution of the class is important, see {@link ProtoCoder}, {@link AvroCoder}, - * or {@link JAXBCoder}. - * - * @param The type of objects coded. - */ -public class StringDelegateCoder extends DelegateCoder { - public static StringDelegateCoder of(Class clazz) { - return new StringDelegateCoder(clazz); - } - - @Override - public String toString() { - return "StringDelegateCoder(" + clazz + ")"; - } - - private final Class clazz; - - protected StringDelegateCoder(final Class clazz) { - super(StringUtf8Coder.of(), - new CodingFunction() { - @Override - public String apply(T input) { - return input.toString(); - } - }, - new CodingFunction() { - @Override - public T apply(String input) throws - NoSuchMethodException, - InstantiationException, - IllegalAccessException, - InvocationTargetException { - return clazz.getConstructor(String.class).newInstance(input); - } - }); - - this.clazz = clazz; - } - - /** - * The encoding id is the fully qualified name of the encoded/decoded class. - */ - @Override - public String getEncodingId() { - return clazz.getName(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringUtf8Coder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringUtf8Coder.java deleted file mode 100644 index 179840c3c4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StringUtf8Coder.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.ExposedByteArrayOutputStream; -import com.google.cloud.dataflow.sdk.util.StreamUtils; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.common.base.Utf8; -import com.google.common.io.ByteStreams; -import com.google.common.io.CountingOutputStream; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UTFDataFormatException; -import java.nio.charset.StandardCharsets; - -/** - * A {@link Coder} that encodes {@link String Strings} in UTF-8 encoding. - * If in a nested context, prefixes the string with an integer length field, - * encoded via a {@link VarIntCoder}. - */ -public class StringUtf8Coder extends AtomicCoder { - - @JsonCreator - public static StringUtf8Coder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final StringUtf8Coder INSTANCE = new StringUtf8Coder(); - - private static void writeString(String value, DataOutputStream dos) - throws IOException { - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - VarInt.encode(bytes.length, dos); - dos.write(bytes); - } - - private static String readString(DataInputStream dis) throws IOException { - int len = VarInt.decodeInt(dis); - if (len < 0) { - throw new CoderException("Invalid encoded string length: " + len); - } - byte[] bytes = new byte[len]; - dis.readFully(bytes); - return new String(bytes, StandardCharsets.UTF_8); - } - - private StringUtf8Coder() {} - - @Override - public void encode(String value, OutputStream outStream, Context context) - throws IOException { - if (value == null) { - throw new CoderException("cannot encode a null String"); - } - if (context.isWholeStream) { - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - if (outStream instanceof ExposedByteArrayOutputStream) { - ((ExposedByteArrayOutputStream) outStream).writeAndOwn(bytes); - } else { - outStream.write(bytes); - } - } else { - writeString(value, new DataOutputStream(outStream)); - } - } - - @Override - public String decode(InputStream inStream, Context context) - throws IOException { - if (context.isWholeStream) { - byte[] bytes = StreamUtils.getBytes(inStream); - return new String(bytes, StandardCharsets.UTF_8); - } else { - try { - return readString(new DataInputStream(inStream)); - } catch (EOFException | UTFDataFormatException exn) { - // These exceptions correspond to decoding problems, so change - // what kind of exception they're branded as. - throw new CoderException(exn); - } - } - } - - /** - * {@inheritDoc} - * - * @return {@code true}. This coder is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return the byte size of the UTF-8 encoding of the a string or, in a nested context, - * the byte size of the encoding plus the encoded length prefix. - */ - @Override - protected long getEncodedElementByteSize(String value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null String"); - } - if (context.isWholeStream) { - return Utf8.encodedLength(value); - } else { - CountingOutputStream countingStream = - new CountingOutputStream(ByteStreams.nullOutputStream()); - DataOutputStream stream = new DataOutputStream(countingStream); - writeString(value, stream); - return countingStream.getCount(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java deleted file mode 100644 index ea18eb971a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArray.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.api.client.util.Base64.encodeBase64String; - -import java.util.Arrays; - -/** - * A wrapper around a byte[] that uses structural, value-based - * equality rather than byte[]'s normal object identity. - */ -public class StructuralByteArray { - byte[] value; - - public StructuralByteArray(byte[] value) { - this.value = value; - } - - public byte[] getValue() { - return value; - } - - @Override - public boolean equals(Object o) { - if (o instanceof StructuralByteArray) { - StructuralByteArray that = (StructuralByteArray) o; - return Arrays.equals(this.value, that.value); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Arrays.hashCode(value); - } - - @Override - public String toString() { - return "base64:" + encodeBase64String(value); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoder.java deleted file mode 100644 index bed88b080f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoder.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.api.services.bigquery.model.TableRow; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} that encodes BigQuery {@link TableRow} objects in their native JSON format. - */ -public class TableRowJsonCoder extends AtomicCoder { - - @JsonCreator - public static TableRowJsonCoder of() { - return INSTANCE; - } - - @Override - public void encode(TableRow value, OutputStream outStream, Context context) - throws IOException { - String strValue = MAPPER.writeValueAsString(value); - StringUtf8Coder.of().encode(strValue, outStream, context); - } - - @Override - public TableRow decode(InputStream inStream, Context context) - throws IOException { - String strValue = StringUtf8Coder.of().decode(inStream, context); - return MAPPER.readValue(strValue, TableRow.class); - } - - @Override - protected long getEncodedElementByteSize(TableRow value, Context context) - throws Exception { - String strValue = MAPPER.writeValueAsString(value); - return StringUtf8Coder.of().getEncodedElementByteSize(strValue, context); - } - - ///////////////////////////////////////////////////////////////////////////// - - // FAIL_ON_EMPTY_BEANS is disabled in order to handle null values in - // TableRow. - private static final ObjectMapper MAPPER = - new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); - - private static final TableRowJsonCoder INSTANCE = new TableRowJsonCoder(); - - private TableRowJsonCoder() { } - - /** - * {@inheritDoc} - * - * @throws NonDeterministicException always. A {@link TableRow} can hold arbitrary - * {@link Object} instances, which makes the encoding non-deterministic. - */ - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "TableCell can hold arbitrary instances, which may be non-deterministic."); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoder.java deleted file mode 100644 index 9250c683f8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} that encodes {@code Integer Integers} as the ASCII bytes of - * their textual, decimal, representation. - */ -public class TextualIntegerCoder extends AtomicCoder { - - @JsonCreator - public static TextualIntegerCoder of() { - return new TextualIntegerCoder(); - } - - ///////////////////////////////////////////////////////////////////////////// - - protected TextualIntegerCoder() {} - - @Override - public void encode(Integer value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Integer"); - } - String textualValue = value.toString(); - StringUtf8Coder.of().encode(textualValue, outStream, context); - } - - @Override - public Integer decode(InputStream inStream, Context context) - throws IOException, CoderException { - String textualValue = StringUtf8Coder.of().decode(inStream, context); - try { - return Integer.valueOf(textualValue); - } catch (NumberFormatException exn) { - throw new CoderException("error when decoding a textual integer", exn); - } - } - - @Override - protected long getEncodedElementByteSize(Integer value, Context context) throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null Integer"); - } - String textualValue = value.toString(); - return StringUtf8Coder.of().getEncodedElementByteSize(textualValue, context); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarIntCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarIntCoder.java deleted file mode 100644 index 18ec250381..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarIntCoder.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.VarInt; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UTFDataFormatException; - -/** - * A {@link Coder} that encodes {@link Integer Integers} using between 1 and 5 bytes. Negative - * numbers always take 5 bytes, so {@link BigEndianIntegerCoder} may be preferable for - * integers that are known to often be large or negative. - */ -public class VarIntCoder extends AtomicCoder { - - @JsonCreator - public static VarIntCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final VarIntCoder INSTANCE = - new VarIntCoder(); - - private VarIntCoder() {} - - @Override - public void encode(Integer value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Integer"); - } - VarInt.encode(value.intValue(), outStream); - } - - @Override - public Integer decode(InputStream inStream, Context context) - throws IOException, CoderException { - try { - return VarInt.decodeInt(inStream); - } catch (EOFException | UTFDataFormatException exn) { - // These exceptions correspond to decoding problems, so change - // what kind of exception they're branded as. - throw new CoderException(exn); - } - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link VarIntCoder} is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link #getEncodedElementByteSize} is cheap. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Integer value, Context context) { - return true; - } - - @Override - protected long getEncodedElementByteSize(Integer value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null Integer"); - } - return VarInt.getLength(value.longValue()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarLongCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarLongCoder.java deleted file mode 100644 index 520245e497..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VarLongCoder.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.VarInt; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UTFDataFormatException; - -/** - * A {@link Coder} that encodes {@link Long Longs} using between 1 and 10 bytes. Negative - * numbers always take 10 bytes, so {@link BigEndianLongCoder} may be preferable for - * longs that are known to often be large or negative. - */ -public class VarLongCoder extends AtomicCoder { - - @JsonCreator - public static VarLongCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final VarLongCoder INSTANCE = new VarLongCoder(); - - private VarLongCoder() {} - - @Override - public void encode(Long value, OutputStream outStream, Context context) - throws IOException, CoderException { - if (value == null) { - throw new CoderException("cannot encode a null Long"); - } - VarInt.encode(value.longValue(), outStream); - } - - @Override - public Long decode(InputStream inStream, Context context) - throws IOException, CoderException { - try { - return VarInt.decodeLong(inStream); - } catch (EOFException | UTFDataFormatException exn) { - // These exceptions correspond to decoding problems, so change - // what kind of exception they're branded as. - throw new CoderException(exn); - } - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link VarLongCoder} is injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link #getEncodedElementByteSize} is cheap. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Long value, Context context) { - return true; - } - - @Override - protected long getEncodedElementByteSize(Long value, Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null Long"); - } - return VarInt.getLength(value.longValue()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java deleted file mode 100644 index 0de606b789..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link Coder} for {@link Void}. Uses zero bytes per {@link Void}. - */ -public class VoidCoder extends AtomicCoder { - - @JsonCreator - public static VoidCoder of() { - return INSTANCE; - } - - ///////////////////////////////////////////////////////////////////////////// - - private static final VoidCoder INSTANCE = new VoidCoder(); - - private VoidCoder() {} - - @Override - public void encode(Void value, OutputStream outStream, Context context) { - // Nothing to write! - } - - @Override - public Void decode(InputStream inStream, Context context) { - // Nothing to read! - return null; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link VoidCoder} is (vacuously) injective. - */ - @Override - public boolean consistentWithEquals() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. {@link VoidCoder#getEncodedElementByteSize} runs in constant time. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(Void value, Context context) { - return true; - } - - @Override - protected long getEncodedElementByteSize(Void value, Context context) - throws Exception { - return 0; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java deleted file mode 100644 index fdf931f4a8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines {@link com.google.cloud.dataflow.sdk.coders.Coder Coders} - * to specify how data is encoded to and decoded from byte strings. - * - *

              During execution of a Pipeline, elements in a - * {@link com.google.cloud.dataflow.sdk.values.PCollection} - * may need to be encoded into byte strings. - * This happens both at the beginning and end of a pipeline when data is read from and written to - * persistent storage and also during execution of a pipeline when elements are communicated between - * machines. - * - *

              Exactly when PCollection elements are encoded during execution depends on which - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} is being used and how that runner - * chooses to execute the pipeline. As such, Dataflow requires that all PCollections have an - * appropriate Coder in case it becomes necessary. In many cases, the Coder can be inferred from - * the available Java type - * information and the Pipeline's {@link com.google.cloud.dataflow.sdk.coders.CoderRegistry}. It - * can be specified per PCollection via - * {@link com.google.cloud.dataflow.sdk.values.PCollection#setCoder(Coder)} or per type using the - * {@link com.google.cloud.dataflow.sdk.coders.DefaultCoder} annotation. - * - *

              This package provides a number of coders for common types like {@code Integer}, - * {@code String}, and {@code List}, as well as coders like - * {@link com.google.cloud.dataflow.sdk.coders.AvroCoder} that can be used to encode many custom - * types. - * - */ -package com.google.cloud.dataflow.sdk.coders; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java deleted file mode 100644 index 111c24dc19..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderProvider; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.Structs; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.protobuf.ExtensionRegistry; -import com.google.protobuf.Message; -import com.google.protobuf.Parser; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.annotation.Nullable; - -/** - * A {@link Coder} using Google Protocol Buffers binary format. {@link ProtoCoder} supports both - * Protocol Buffers syntax versions 2 and 3. - * - *

              To learn more about Protocol Buffers, visit: - * https://developers.google.com/protocol-buffers - * - *

              {@link ProtoCoder} is registered in the global {@link CoderRegistry} as the default - * {@link Coder} for any {@link Message} object. Custom message extensions are also supported, but - * these extensions must be registered for a particular {@link ProtoCoder} instance and that - * instance must be registered on the {@link PCollection} that needs the extensions: - * - *

              {@code
              - * import MyProtoFile;
              - * import MyProtoFile.MyMessage;
              - *
              - * Coder coder = ProtoCoder.of(MyMessage.class).withExtensionsFrom(MyProtoFile.class);
              - * PCollection records =  input.apply(...).setCoder(coder);
              - * }
              - * - *

              Versioning

              - * - *

              {@link ProtoCoder} supports both versions 2 and 3 of the Protocol Buffers syntax. However, - * the Java runtime version of the google.com.protobuf library must match exactly the - * version of protoc that was used to produce the JAR files containing the compiled - * .proto messages. - * - *

              For more information, see the - * Protocol Buffers documentation. - * - *

              {@link ProtoCoder} and Determinism

              - * - *

              In general, Protocol Buffers messages can be encoded deterministically within a single - * pipeline as long as: - * - *

                - *
              • The encoded messages (and any transitively linked messages) do not use map - * fields.
              • - *
              • Every Java VM that encodes or decodes the messages use the same runtime version of the - * Protocol Buffers library and the same compiled .proto file JAR.
              • - *
              - * - *

              {@link ProtoCoder} and Encoding Stability

              - * - *

              When changing Protocol Buffers messages, follow the rules in the Protocol Buffers language - * guides for - * {@code proto2} - * and - * {@code proto3} - * syntaxes, depending on your message type. Following these guidelines will ensure that the - * old encoded data can be read by new versions of the code. - * - *

              Generally, any change to the message type, registered extensions, runtime library, or - * compiled proto JARs may change the encoding. Thus even if both the original and updated messages - * can be encoded deterministically within a single job, these deterministic encodings may not be - * the same across jobs. - * - * @param the Protocol Buffers {@link Message} handled by this {@link Coder}. - */ -public class ProtoCoder extends AtomicCoder { - - /** - * A {@link CoderProvider} that returns a {@link ProtoCoder} with an empty - * {@link ExtensionRegistry}. - */ - public static CoderProvider coderProvider() { - return PROVIDER; - } - - /** - * Returns a {@link ProtoCoder} for the given Protocol Buffers {@link Message}. - */ - public static ProtoCoder of(Class protoMessageClass) { - return new ProtoCoder(protoMessageClass, ImmutableSet.>of()); - } - - /** - * Returns a {@link ProtoCoder} for the Protocol Buffers {@link Message} indicated by the given - * {@link TypeDescriptor}. - */ - public static ProtoCoder of(TypeDescriptor protoMessageType) { - @SuppressWarnings("unchecked") - Class protoMessageClass = (Class) protoMessageType.getRawType(); - return of(protoMessageClass); - } - - /** - * Returns a {@link ProtoCoder} like this one, but with the extensions from the given classes - * registered. - * - *

              Each of the extension host classes must be an class automatically generated by the - * Protocol Buffers compiler, {@code protoc}, that contains messages. - * - *

              Does not modify this object. - */ - public ProtoCoder withExtensionsFrom(Iterable> moreExtensionHosts) { - for (Class extensionHost : moreExtensionHosts) { - // Attempt to access the required method, to make sure it's present. - try { - Method registerAllExtensions = - extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class); - checkArgument( - Modifier.isStatic(registerAllExtensions.getModifiers()), - "Method registerAllExtensions() must be static"); - } catch (NoSuchMethodException | SecurityException e) { - throw new IllegalArgumentException( - String.format("Unable to register extensions for %s", extensionHost.getCanonicalName()), - e); - } - } - - return new ProtoCoder( - protoMessageClass, - new ImmutableSet.Builder>() - .addAll(extensionHostClasses) - .addAll(moreExtensionHosts) - .build()); - } - - /** - * See {@link #withExtensionsFrom(Iterable)}. - * - *

              Does not modify this object. - */ - public ProtoCoder withExtensionsFrom(Class... moreExtensionHosts) { - return withExtensionsFrom(Arrays.asList(moreExtensionHosts)); - } - - @Override - public void encode(T value, OutputStream outStream, Context context) throws IOException { - if (value == null) { - throw new CoderException("cannot encode a null " + protoMessageClass.getSimpleName()); - } - if (context.isWholeStream) { - value.writeTo(outStream); - } else { - value.writeDelimitedTo(outStream); - } - } - - @Override - public T decode(InputStream inStream, Context context) throws IOException { - if (context.isWholeStream) { - return getParser().parseFrom(inStream, getExtensionRegistry()); - } else { - return getParser().parseDelimitedFrom(inStream, getExtensionRegistry()); - } - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof ProtoCoder)) { - return false; - } - ProtoCoder otherCoder = (ProtoCoder) other; - return protoMessageClass.equals(otherCoder.protoMessageClass) - && Sets.newHashSet(extensionHostClasses) - .equals(Sets.newHashSet(otherCoder.extensionHostClasses)); - } - - @Override - public int hashCode() { - return Objects.hash(protoMessageClass, extensionHostClasses); - } - - /** - * The encoding identifier is designed to support evolution as per the design of Protocol - * Buffers. In order to use this class effectively, carefully follow the advice in the Protocol - * Buffers documentation at - * Updating - * A Message Type. - * - *

              In particular, the encoding identifier is guaranteed to be the same for {@link ProtoCoder} - * instances of the same principal message class, with the same registered extension host classes, - * and otherwise distinct. Note that the encoding ID does not encode any version of the message - * or extensions, nor does it include the message schema. - * - *

              When modifying a message class, here are the broadest guidelines; see the above link - * for greater detail. - * - *

                - *
              • Do not change the numeric tags for any fields. - *
              • Never remove a required field. - *
              • Only add optional or repeated fields, with sensible defaults. - *
              • When changing the type of a field, consult the Protocol Buffers documentation to ensure - * the new and old types are interchangeable. - *
              - * - *

              Code consuming this message class should be prepared to support all versions of - * the class until it is certain that no remaining serialized instances exist. - * - *

              If backwards incompatible changes must be made, the best recourse is to change the name - * of your Protocol Buffers message class. - */ - @Override - public String getEncodingId() { - return protoMessageClass.getName() + getSortedExtensionClasses().toString(); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - ProtobufUtil.verifyDeterministic(this); - } - - /** - * Returns the Protocol Buffers {@link Message} type this {@link ProtoCoder} supports. - */ - public Class getMessageType() { - return protoMessageClass; - } - - /** - * Returns the {@link ExtensionRegistry} listing all known Protocol Buffers extension messages - * to {@code T} registered with this {@link ProtoCoder}. - */ - public ExtensionRegistry getExtensionRegistry() { - if (memoizedExtensionRegistry == null) { - ExtensionRegistry registry = ExtensionRegistry.newInstance(); - for (Class extensionHost : extensionHostClasses) { - try { - extensionHost - .getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class) - .invoke(null, registry); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IllegalStateException(e); - } - } - memoizedExtensionRegistry = registry.getUnmodifiable(); - } - return memoizedExtensionRegistry; - } - - //////////////////////////////////////////////////////////////////////////////////// - // Private implementation details below. - - /** The {@link Message} type to be coded. */ - private final Class protoMessageClass; - - /** - * All extension host classes included in this {@link ProtoCoder}. The extensions from these - * classes will be included in the {@link ExtensionRegistry} used during encoding and decoding. - */ - private final Set> extensionHostClasses; - - // Constants used to serialize and deserialize - private static final String PROTO_MESSAGE_CLASS = "proto_message_class"; - private static final String PROTO_EXTENSION_HOSTS = "proto_extension_hosts"; - - // Transient fields that are lazy initialized and then memoized. - private transient ExtensionRegistry memoizedExtensionRegistry; - private transient Parser memoizedParser; - - /** Private constructor. */ - private ProtoCoder(Class protoMessageClass, Set> extensionHostClasses) { - this.protoMessageClass = protoMessageClass; - this.extensionHostClasses = extensionHostClasses; - } - - /** - * @deprecated For JSON deserialization only. - */ - @JsonCreator - @Deprecated - public static ProtoCoder of( - @JsonProperty(PROTO_MESSAGE_CLASS) String protoMessageClassName, - @Nullable @JsonProperty(PROTO_EXTENSION_HOSTS) List extensionHostClassNames) { - - try { - @SuppressWarnings("unchecked") - Class protoMessageClass = (Class) Class.forName(protoMessageClassName); - List> extensionHostClasses = Lists.newArrayList(); - if (extensionHostClassNames != null) { - for (String extensionHostClassName : extensionHostClassNames) { - extensionHostClasses.add(Class.forName(extensionHostClassName)); - } - } - return of(protoMessageClass).withExtensionsFrom(extensionHostClasses); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException(e); - } - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - Structs.addString(result, PROTO_MESSAGE_CLASS, protoMessageClass.getName()); - List extensionHostClassNames = Lists.newArrayList(); - for (String className : getSortedExtensionClasses()) { - extensionHostClassNames.add(CloudObject.forString(className)); - } - Structs.addList(result, PROTO_EXTENSION_HOSTS, extensionHostClassNames); - return result; - } - - /** Get the memoized {@link Parser}, possibly initializing it lazily. */ - private Parser getParser() { - if (memoizedParser == null) { - try { - @SuppressWarnings("unchecked") - T protoMessageInstance = (T) protoMessageClass.getMethod("getDefaultInstance").invoke(null); - @SuppressWarnings("unchecked") - Parser tParser = (Parser) protoMessageInstance.getParserForType(); - memoizedParser = tParser; - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IllegalArgumentException(e); - } - } - return memoizedParser; - } - - /** - * The implementation of the {@link CoderProvider} for this {@link ProtoCoder} returned by - * {@link #coderProvider()}. - */ - private static final CoderProvider PROVIDER = - new CoderProvider() { - @Override - public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { - if (!type.isSubtypeOf(new TypeDescriptor() {})) { - throw new CannotProvideCoderException( - String.format( - "Cannot provide %s because %s is not a subclass of %s", - ProtoCoder.class.getSimpleName(), - type, - Message.class.getName())); - } - - @SuppressWarnings("unchecked") - TypeDescriptor messageType = (TypeDescriptor) type; - try { - @SuppressWarnings("unchecked") - Coder coder = (Coder) ProtoCoder.of(messageType); - return coder; - } catch (IllegalArgumentException e) { - throw new CannotProvideCoderException(e); - } - } - }; - - private SortedSet getSortedExtensionClasses() { - SortedSet ret = new TreeSet<>(); - for (Class clazz : extensionHostClasses) { - ret.add(clazz.getName()); - } - return ret; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java deleted file mode 100644 index 597b1de843..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Descriptors.FileDescriptor.Syntax; -import com.google.protobuf.Descriptors.GenericDescriptor; -import com.google.protobuf.ExtensionRegistry; -import com.google.protobuf.ExtensionRegistry.ExtensionInfo; -import com.google.protobuf.Message; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashSet; -import java.util.Set; - -/** - * Utility functions for reflecting and analyzing Protocol Buffers classes. - * - *

              Used by {@link ProtoCoder}, but in a separate file for testing and isolation. - */ -class ProtobufUtil { - /** - * Returns the {@link Descriptor} for the given Protocol Buffers {@link Message}. - * - * @throws IllegalArgumentException if there is an error in Java reflection. - */ - static Descriptor getDescriptorForClass(Class clazz) { - try { - return (Descriptor) clazz.getMethod("getDescriptor").invoke(null); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * Returns the {@link Descriptor} for the given Protocol Buffers {@link Message} as well as - * every class it can include transitively. - * - * @throws IllegalArgumentException if there is an error in Java reflection. - */ - static Set getRecursiveDescriptorsForClass( - Class clazz, ExtensionRegistry registry) { - Descriptor root = getDescriptorForClass(clazz); - Set descriptors = new HashSet<>(); - recursivelyAddDescriptors(root, descriptors, registry); - return descriptors; - } - - /** - * Recursively walks the given {@link Message} class and verifies that every field or message - * linked in uses the Protocol Buffers proto2 syntax. - */ - static void checkProto2Syntax(Class clazz, ExtensionRegistry registry) { - for (GenericDescriptor d : getRecursiveDescriptorsForClass(clazz, registry)) { - Syntax s = d.getFile().getSyntax(); - checkArgument( - s == Syntax.PROTO2, - "Message %s or one of its dependencies does not use proto2 syntax: %s in file %s", - clazz.getName(), - d.getFullName(), - d.getFile().getName()); - } - } - - /** - * Recursively checks whether the specified class uses any Protocol Buffers fields that cannot - * be deterministically encoded. - * - * @throws NonDeterministicException if the object cannot be encoded deterministically. - */ - static void verifyDeterministic(ProtoCoder coder) throws NonDeterministicException { - Class message = coder.getMessageType(); - ExtensionRegistry registry = coder.getExtensionRegistry(); - Set descriptors = getRecursiveDescriptorsForClass(message, registry); - for (Descriptor d : descriptors) { - for (FieldDescriptor fd : d.getFields()) { - // If there is a transitively reachable Protocol Buffers map field, then this object cannot - // be encoded deterministically. - if (fd.isMapField()) { - String reason = - String.format( - "Protocol Buffers message %s transitively includes Map field %s (from file %s)." - + " Maps cannot be deterministically encoded.", - message.getName(), - fd.getFullName(), - fd.getFile().getFullName()); - throw new NonDeterministicException(coder, reason); - } - } - } - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Disable construction of utility class - private ProtobufUtil() {} - - private static void recursivelyAddDescriptors( - Descriptor message, Set descriptors, ExtensionRegistry registry) { - if (descriptors.contains(message)) { - return; - } - descriptors.add(message); - - for (FieldDescriptor f : message.getFields()) { - recursivelyAddDescriptors(f, descriptors, registry); - } - for (FieldDescriptor f : message.getExtensions()) { - recursivelyAddDescriptors(f, descriptors, registry); - } - for (ExtensionInfo info : - registry.getAllImmutableExtensionsByExtendedType(message.getFullName())) { - recursivelyAddDescriptors(info.descriptor, descriptors, registry); - } - for (ExtensionInfo info : - registry.getAllMutableExtensionsByExtendedType(message.getFullName())) { - recursivelyAddDescriptors(info.descriptor, descriptors, registry); - } - } - - private static void recursivelyAddDescriptors( - FieldDescriptor field, Set descriptors, ExtensionRegistry registry) { - switch (field.getType()) { - case BOOL: - case BYTES: - case DOUBLE: - case ENUM: - case FIXED32: - case FIXED64: - case FLOAT: - case INT32: - case INT64: - case SFIXED32: - case SFIXED64: - case SINT32: - case SINT64: - case STRING: - case UINT32: - case UINT64: - // Primitive types do not transitively access anything else. - break; - - case GROUP: - case MESSAGE: - // Recursively adds all the fields from this nested Message. - recursivelyAddDescriptors(field.getMessageType(), descriptors, registry); - break; - - default: - throw new UnsupportedOperationException( - "Unexpected Protocol Buffers field type: " + field.getType()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java deleted file mode 100644 index b5bcf18eda..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines a {@link com.google.cloud.dataflow.sdk.coders.Coder} - * for Protocol Buffers messages, {@code ProtoCoder}. - * - * @see com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder - */ -package com.google.cloud.dataflow.sdk.coders.protobuf; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java deleted file mode 100644 index bd8ac53c6e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java +++ /dev/null @@ -1,845 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.annotations.VisibleForTesting; - -import org.apache.avro.Schema; -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.reflect.ReflectData; - -import java.io.IOException; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; - -/** - * {@link PTransform}s for reading and writing Avro files. - * - *

              To read a {@link PCollection} from one or more Avro files, use - * {@link AvroIO.Read}, specifying {@link AvroIO.Read#from} to specify - * the path of the file(s) to read from (e.g., a local filename or - * filename pattern if running locally, or a Google Cloud Storage - * filename or filename pattern of the form - * {@code "gs:///"}), and optionally - * {@link AvroIO.Read#named} to specify the name of the pipeline step. - * - *

              It is required to specify {@link AvroIO.Read#withSchema}. To - * read specific records, such as Avro-generated classes, provide an - * Avro-generated class type. To read {@link GenericRecord GenericRecords}, provide either - * a {@link Schema} object or an Avro schema in a JSON-encoded string form. - * An exception will be thrown if a record doesn't match the specified - * schema. - * - *

              For example: - *

               {@code
              - * Pipeline p = ...;
              - *
              - * // A simple Read of a local file (only runs locally):
              - * PCollection records =
              - *     p.apply(AvroIO.Read.from("/path/to/file.avro")
              - *                        .withSchema(AvroAutoGenClass.class));
              - *
              - * // A Read from a GCS file (runs locally and via the Google Cloud
              - * // Dataflow service):
              - * Schema schema = new Schema.Parser().parse(new File("schema.avsc"));
              - * PCollection records =
              - *     p.apply(AvroIO.Read.named("ReadFromAvro")
              - *                        .from("gs://my_bucket/path/to/records-*.avro")
              - *                        .withSchema(schema));
              - * } 
              - * - *

              To write a {@link PCollection} to one or more Avro files, use - * {@link AvroIO.Write}, specifying {@link AvroIO.Write#to} to specify - * the path of the file to write to (e.g., a local filename or sharded - * filename pattern if running locally, or a Google Cloud Storage - * filename or sharded filename pattern of the form - * {@code "gs:///"}), and optionally - * {@link AvroIO.Write#named} to specify the name of the pipeline step. - * - *

              It is required to specify {@link AvroIO.Write#withSchema}. To - * write specific records, such as Avro-generated classes, provide an - * Avro-generated class type. To write {@link GenericRecord GenericRecords}, provide either - * a {@link Schema} object or a schema in a JSON-encoded string form. - * An exception will be thrown if a record doesn't match the specified - * schema. - * - *

              For example: - *

               {@code
              - * // A simple Write to a local file (only runs locally):
              - * PCollection records = ...;
              - * records.apply(AvroIO.Write.to("/path/to/file.avro")
              - *                           .withSchema(AvroAutoGenClass.class));
              - *
              - * // A Write to a sharded GCS file (runs locally and via the Google Cloud
              - * // Dataflow service):
              - * Schema schema = new Schema.Parser().parse(new File("schema.avsc"));
              - * PCollection records = ...;
              - * records.apply(AvroIO.Write.named("WriteToAvro")
              - *                           .to("gs://my_bucket/path/to/numbers")
              - *                           .withSchema(schema)
              - *                           .withSuffix(".avro"));
              - * } 
              - * - *

              Permissions

              - * Permission requirements depend on the {@link PipelineRunner} that is used to execute the - * Dataflow job. Please refer to the documentation of corresponding {@link PipelineRunner}s for - * more details. - */ -public class AvroIO { - /** - * A root {@link PTransform} that reads from an Avro file (or multiple Avro - * files matching a pattern) and returns a {@link PCollection} containing - * the decoding of each record. - */ - public static class Read { - /** - * Returns a {@link PTransform} with the given step name. - */ - public static Bound named(String name) { - return new Bound<>(GenericRecord.class).named(name); - } - - /** - * Returns a {@link PTransform} that reads from the file(s) - * with the given name or pattern. This can be a local filename - * or filename pattern (if running locally), or a Google Cloud - * Storage filename or filename pattern of the form - * {@code "gs:///"} (if running locally or via - * the Google Cloud Dataflow service). Standard - * Java - * Filesystem glob patterns ("*", "?", "[..]") are supported. - */ - public static Bound from(String filepattern) { - return new Bound<>(GenericRecord.class).from(filepattern); - } - - /** - * Returns a {@link PTransform} that reads Avro file(s) - * containing records whose type is the specified Avro-generated class. - * - * @param the type of the decoded elements, and the elements - * of the resulting {@link PCollection} - */ - public static Bound withSchema(Class type) { - return new Bound<>(type).withSchema(type); - } - - /** - * Returns a {@link PTransform} that reads Avro file(s) - * containing records of the specified schema. - */ - public static Bound withSchema(Schema schema) { - return new Bound<>(GenericRecord.class).withSchema(schema); - } - - /** - * Returns a {@link PTransform} that reads Avro file(s) - * containing records of the specified schema in a JSON-encoded - * string form. - */ - public static Bound withSchema(String schema) { - return withSchema((new Schema.Parser()).parse(schema)); - } - - /** - * Returns a {@link PTransform} that reads Avro file(s) - * that has GCS path validation on pipeline creation disabled. - * - *

              This can be useful in the case where the GCS input location does - * not exist at the pipeline creation time, but is expected to be available - * at execution time. - */ - public static Bound withoutValidation() { - return new Bound<>(GenericRecord.class).withoutValidation(); - } - - /** - * A {@link PTransform} that reads from an Avro file (or multiple Avro - * files matching a pattern) and returns a bounded {@link PCollection} containing - * the decoding of each record. - * - * @param the type of each of the elements of the resulting - * PCollection - */ - public static class Bound extends PTransform> { - /** The filepattern to read from. */ - @Nullable - final String filepattern; - /** The class type of the records. */ - final Class type; - /** The schema of the input file. */ - @Nullable - final Schema schema; - /** An option to indicate if input validation is desired. Default is true. */ - final boolean validate; - - Bound(Class type) { - this(null, null, type, null, true); - } - - Bound(String name, String filepattern, Class type, Schema schema, boolean validate) { - super(name); - this.filepattern = filepattern; - this.type = type; - this.schema = schema; - this.validate = validate; - } - - /** - * Returns a new {@link PTransform} that's like this one but - * with the given step name. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound<>(name, filepattern, type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that reads from the file(s) with the given name or pattern. - * (See {@link AvroIO.Read#from} for a description of - * filepatterns.) - * - *

              Does not modify this object. - */ - public Bound from(String filepattern) { - return new Bound<>(name, filepattern, type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that reads Avro file(s) containing records whose type is the - * specified Avro-generated class. - * - *

              Does not modify this object. - * - * @param the type of the decoded elements and the elements of - * the resulting PCollection - */ - public Bound withSchema(Class type) { - return new Bound<>(name, filepattern, type, ReflectData.get().getSchema(type), validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that reads Avro file(s) containing records of the specified schema. - * - *

              Does not modify this object. - */ - public Bound withSchema(Schema schema) { - return new Bound<>(name, filepattern, GenericRecord.class, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that reads Avro file(s) containing records of the specified schema - * in a JSON-encoded string form. - * - *

              Does not modify this object. - */ - public Bound withSchema(String schema) { - return withSchema((new Schema.Parser()).parse(schema)); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that has GCS input path validation on pipeline creation disabled. - * - *

              Does not modify this object. - * - *

              This can be useful in the case where the GCS input location does - * not exist at the pipeline creation time, but is expected to be - * available at execution time. - */ - public Bound withoutValidation() { - return new Bound<>(name, filepattern, type, schema, false); - } - - @Override - public PCollection apply(PInput input) { - if (filepattern == null) { - throw new IllegalStateException( - "need to set the filepattern of an AvroIO.Read transform"); - } - if (schema == null) { - throw new IllegalStateException("need to set the schema of an AvroIO.Read transform"); - } - if (validate) { - try { - checkState( - !IOChannelUtils.getFactory(filepattern).match(filepattern).isEmpty(), - "Unable to find any files matching %s", - filepattern); - } catch (IOException e) { - throw new IllegalStateException( - String.format("Failed to validate %s", filepattern), e); - } - } - - @SuppressWarnings("unchecked") - Bounded read = - type == GenericRecord.class - ? (Bounded) com.google.cloud.dataflow.sdk.io.Read.from( - AvroSource.from(filepattern).withSchema(schema)) - : com.google.cloud.dataflow.sdk.io.Read.from( - AvroSource.from(filepattern).withSchema(type)); - - PCollection pcol = input.getPipeline().apply("Read", read); - // Honor the default output coder that would have been used by this PTransform. - pcol.setCoder(getDefaultOutputCoder()); - return pcol; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("filePattern", filepattern) - .withLabel("Input File Pattern")) - .addIfNotDefault(DisplayData.item("validation", validate) - .withLabel("Validation Enabled"), true); - } - - @Override - protected Coder getDefaultOutputCoder() { - return AvroCoder.of(type, schema); - } - - public String getFilepattern() { - return filepattern; - } - - public Schema getSchema() { - return schema; - } - - public boolean needsValidation() { - return validate; - } - } - - /** Disallow construction of utility class. */ - private Read() {} - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A root {@link PTransform} that writes a {@link PCollection} to an Avro file (or - * multiple Avro files matching a sharding pattern). - */ - public static class Write { - /** - * Returns a {@link PTransform} with the given step name. - */ - public static Bound named(String name) { - return new Bound<>(GenericRecord.class).named(name); - } - - /** - * Returns a {@link PTransform} that writes to the file(s) - * with the given prefix. This can be a local filename - * (if running locally), or a Google Cloud Storage filename of - * the form {@code "gs:///"} - * (if running locally or via the Google Cloud Dataflow service). - * - *

              The files written will begin with this prefix, followed by - * a shard identifier (see {@link Bound#withNumShards}, and end - * in a common extension, if given by {@link Bound#withSuffix}. - */ - public static Bound to(String prefix) { - return new Bound<>(GenericRecord.class).to(prefix); - } - - /** - * Returns a {@link PTransform} that writes to the file(s) with the - * given filename suffix. - */ - public static Bound withSuffix(String filenameSuffix) { - return new Bound<>(GenericRecord.class).withSuffix(filenameSuffix); - } - - /** - * Returns a {@link PTransform} that uses the provided shard count. - * - *

              Constraining the number of shards is likely to reduce - * the performance of a pipeline. Setting this value is not recommended - * unless you require a specific number of output files. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - */ - public static Bound withNumShards(int numShards) { - return new Bound<>(GenericRecord.class).withNumShards(numShards); - } - - /** - * Returns a {@link PTransform} that uses the given shard name - * template. - * - *

              See {@link ShardNameTemplate} for a description of shard templates. - */ - public static Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>(GenericRecord.class).withShardNameTemplate(shardTemplate); - } - - /** - * Returns a {@link PTransform} that forces a single file as - * output. - * - *

              Constraining the number of shards is likely to reduce - * the performance of a pipeline. Setting this value is not recommended - * unless you require a specific number of output files. - */ - public static Bound withoutSharding() { - return new Bound<>(GenericRecord.class).withoutSharding(); - } - - /** - * Returns a {@link PTransform} that writes Avro file(s) - * containing records whose type is the specified Avro-generated class. - * - * @param the type of the elements of the input PCollection - */ - public static Bound withSchema(Class type) { - return new Bound<>(type).withSchema(type); - } - - /** - * Returns a {@link PTransform} that writes Avro file(s) - * containing records of the specified schema. - */ - public static Bound withSchema(Schema schema) { - return new Bound<>(GenericRecord.class).withSchema(schema); - } - - /** - * Returns a {@link PTransform} that writes Avro file(s) - * containing records of the specified schema in a JSON-encoded - * string form. - */ - public static Bound withSchema(String schema) { - return withSchema((new Schema.Parser()).parse(schema)); - } - - /** - * Returns a {@link PTransform} that writes Avro file(s) that has GCS path validation on - * pipeline creation disabled. - * - *

              This can be useful in the case where the GCS output location does - * not exist at the pipeline creation time, but is expected to be available - * at execution time. - */ - public static Bound withoutValidation() { - return new Bound<>(GenericRecord.class).withoutValidation(); - } - - /** - * A {@link PTransform} that writes a bounded {@link PCollection} to an Avro file (or - * multiple Avro files matching a sharding pattern). - * - * @param the type of each of the elements of the input PCollection - */ - public static class Bound extends PTransform, PDone> { - private static final String DEFAULT_SHARD_TEMPLATE = ShardNameTemplate.INDEX_OF_MAX; - - /** The filename to write to. */ - @Nullable - final String filenamePrefix; - /** Suffix to use for each filename. */ - final String filenameSuffix; - /** Requested number of shards. 0 for automatic. */ - final int numShards; - /** Shard template string. */ - final String shardTemplate; - /** The class type of the records. */ - final Class type; - /** The schema of the output file. */ - @Nullable - final Schema schema; - /** An option to indicate if output validation is desired. Default is true. */ - final boolean validate; - - Bound(Class type) { - this(null, null, "", 0, DEFAULT_SHARD_TEMPLATE, type, null, true); - } - - Bound( - String name, - String filenamePrefix, - String filenameSuffix, - int numShards, - String shardTemplate, - Class type, - Schema schema, - boolean validate) { - super(name); - this.filenamePrefix = filenamePrefix; - this.filenameSuffix = filenameSuffix; - this.numShards = numShards; - this.shardTemplate = shardTemplate; - this.type = type; - this.schema = schema; - this.validate = validate; - } - - /** - * Returns a new {@link PTransform} that's like this one but - * with the given step name. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that writes to the file(s) with the given filename prefix. - * - *

              See {@link AvroIO.Write#to(String)} for more information - * about filenames. - * - *

              Does not modify this object. - */ - public Bound to(String filenamePrefix) { - validateOutputComponent(filenamePrefix); - return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that writes to the file(s) with the given filename suffix. - * - *

              See {@link ShardNameTemplate} for a description of shard templates. - * - *

              Does not modify this object. - */ - public Bound withSuffix(String filenameSuffix) { - validateOutputComponent(filenameSuffix); - return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that uses the provided shard count. - * - *

              Constraining the number of shards is likely to reduce - * the performance of a pipeline. Setting this value is not recommended - * unless you require a specific number of output files. - * - *

              Does not modify this object. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - * @see ShardNameTemplate - */ - public Bound withNumShards(int numShards) { - checkArgument(numShards >= 0); - return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that uses the given shard name template. - * - *

              Does not modify this object. - * - * @see ShardNameTemplate - */ - public Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that forces a single file as output. - * - *

              This is a shortcut for - * {@code .withNumShards(1).withShardNameTemplate("")} - * - *

              Does not modify this object. - */ - public Bound withoutSharding() { - return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", type, schema, validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that writes to Avro file(s) containing records whose type is the - * specified Avro-generated class. - * - *

              Does not modify this object. - * - * @param the type of the elements of the input PCollection - */ - public Bound withSchema(Class type) { - return new Bound<>( - name, - filenamePrefix, - filenameSuffix, - numShards, - shardTemplate, - type, - ReflectData.get().getSchema(type), - validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that writes to Avro file(s) containing records of the specified - * schema. - * - *

              Does not modify this object. - */ - public Bound withSchema(Schema schema) { - return new Bound<>( - name, - filenamePrefix, - filenameSuffix, - numShards, - shardTemplate, - GenericRecord.class, - schema, - validate); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that writes to Avro file(s) containing records of the specified - * schema in a JSON-encoded string form. - * - *

              Does not modify this object. - */ - public Bound withSchema(String schema) { - return withSchema((new Schema.Parser()).parse(schema)); - } - - /** - * Returns a new {@link PTransform} that's like this one but - * that has GCS output path validation on pipeline creation disabled. - * - *

              Does not modify this object. - * - *

              This can be useful in the case where the GCS output location does - * not exist at the pipeline creation time, but is expected to be - * available at execution time. - */ - public Bound withoutValidation() { - return new Bound<>( - name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, false); - } - - @Override - public PDone apply(PCollection input) { - if (filenamePrefix == null) { - throw new IllegalStateException( - "need to set the filename prefix of an AvroIO.Write transform"); - } - if (schema == null) { - throw new IllegalStateException("need to set the schema of an AvroIO.Write transform"); - } - - com.google.cloud.dataflow.sdk.io.Write.Bound write = - com.google.cloud.dataflow.sdk.io.Write.to( - new AvroSink<>( - filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema))); - if (getNumShards() > 0) { - write = write.withNumShards(getNumShards()); - } - return input.apply("Write", write); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("schema", type) - .withLabel("Record Schema")) - .addIfNotNull(DisplayData.item("filePrefix", filenamePrefix) - .withLabel("Output File Prefix")) - .addIfNotDefault(DisplayData.item("shardNameTemplate", shardTemplate) - .withLabel("Output Shard Name Template"), - DEFAULT_SHARD_TEMPLATE) - .addIfNotDefault(DisplayData.item("fileSuffix", filenameSuffix) - .withLabel("Output File Suffix"), - "") - .addIfNotDefault(DisplayData.item("numShards", numShards) - .withLabel("Maximum Output Shards"), - 0) - .addIfNotDefault(DisplayData.item("validation", validate) - .withLabel("Validation Enabled"), - true); - } - - /** - * Returns the current shard name template string. - */ - public String getShardNameTemplate() { - return shardTemplate; - } - - @Override - protected Coder getDefaultOutputCoder() { - return VoidCoder.of(); - } - - public String getFilenamePrefix() { - return filenamePrefix; - } - - public String getShardTemplate() { - return shardTemplate; - } - - public int getNumShards() { - return numShards; - } - - public String getFilenameSuffix() { - return filenameSuffix; - } - - public Class getType() { - return type; - } - - public Schema getSchema() { - return schema; - } - - public boolean needsValidation() { - return validate; - } - } - - /** Disallow construction of utility class. */ - private Write() {} - } - - // Pattern which matches old-style shard output patterns, which are now - // disallowed. - private static final Pattern SHARD_OUTPUT_PATTERN = Pattern.compile("@([0-9]+|\\*)"); - - private static void validateOutputComponent(String partialFilePattern) { - checkArgument( - !SHARD_OUTPUT_PATTERN.matcher(partialFilePattern).find(), - "Output name components are not allowed to contain @* or @N patterns: " - + partialFilePattern); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** Disallow construction of utility class. */ - private AvroIO() {} - - /** - * A {@link FileBasedSink} for Avro files. - */ - @VisibleForTesting - static class AvroSink extends FileBasedSink { - private final AvroCoder coder; - - @VisibleForTesting - AvroSink( - String baseOutputFilename, String extension, String fileNameTemplate, AvroCoder coder) { - super(baseOutputFilename, extension, fileNameTemplate); - this.coder = coder; - } - - @Override - public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { - return new AvroWriteOperation<>(this, coder); - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation - * FileBasedWriteOperation} for Avro files. - */ - private static class AvroWriteOperation extends FileBasedWriteOperation { - private final AvroCoder coder; - - private AvroWriteOperation(AvroSink sink, AvroCoder coder) { - super(sink); - this.coder = coder; - } - - @Override - public FileBasedWriter createWriter(PipelineOptions options) throws Exception { - return new AvroWriter<>(this, coder); - } - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} - * for Avro files. - */ - private static class AvroWriter extends FileBasedWriter { - private final AvroCoder coder; - private DataFileWriter dataFileWriter; - - public AvroWriter(FileBasedWriteOperation writeOperation, AvroCoder coder) { - super(writeOperation); - this.mimeType = MimeTypes.BINARY; - this.coder = coder; - } - - @SuppressWarnings("deprecation") // uses internal test functionality. - @Override - protected void prepareWrite(WritableByteChannel channel) throws Exception { - dataFileWriter = new DataFileWriter<>(coder.createDatumWriter()); - dataFileWriter.create(coder.getSchema(), Channels.newOutputStream(channel)); - } - - @Override - public void write(T value) throws Exception { - dataFileWriter.append(value); - } - - @Override - protected void writeFooter() throws Exception { - dataFileWriter.flush(); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java deleted file mode 100644 index f9f07a2311..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java +++ /dev/null @@ -1,771 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.util.AvroUtils; -import com.google.cloud.dataflow.sdk.util.AvroUtils.AvroMetadata; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.annotations.VisibleForTesting; - -import org.apache.avro.Schema; -import org.apache.avro.file.CodecFactory; -import org.apache.avro.file.DataFileConstants; -import org.apache.avro.generic.GenericDatumReader; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.BinaryDecoder; -import org.apache.avro.io.DatumReader; -import org.apache.avro.io.DecoderFactory; -import org.apache.avro.reflect.ReflectData; -import org.apache.avro.reflect.ReflectDatumReader; -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; -import org.apache.commons.compress.compressors.snappy.SnappyCompressorInputStream; -import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; -import org.apache.commons.compress.utils.CountingInputStream; - -import java.io.ByteArrayInputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InvalidObjectException; -import java.io.ObjectStreamException; -import java.io.PushbackInputStream; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SeekableByteChannel; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - -import javax.annotation.concurrent.GuardedBy; - -// CHECKSTYLE.OFF: JavadocStyle -/** - * A {@link FileBasedSource} for reading Avro files. - * - *

              To read a {@link PCollection} of objects from one or more Avro files, use - * {@link AvroSource#from} to specify the path(s) of the files to read. The {@link AvroSource} that - * is returned will read objects of type {@link GenericRecord} with the schema(s) that were written - * at file creation. To further configure the {@link AvroSource} to read with a user-defined schema, - * or to return records of a type other than {@link GenericRecord}, use - * {@link AvroSource#withSchema(Schema)} (using an Avro {@link Schema}), - * {@link AvroSource#withSchema(String)} (using a JSON schema), or - * {@link AvroSource#withSchema(Class)} (to return objects of the Avro-generated class specified). - * - *

              An {@link AvroSource} can be read from using the {@link Read} transform. For example: - * - *

              - * {@code
              - * AvroSource source = AvroSource.from(file.toPath()).withSchema(MyType.class);
              - * PCollection records = Read.from(mySource);
              - * }
              - * 
              - * - *

              The {@link AvroSource#readFromFileWithClass(String, Class)} method is a convenience method - * that returns a read transform. For example: - * - *

              - * {@code
              - * PCollection records = AvroSource.readFromFileWithClass(file.toPath(), MyType.class));
              - * }
              - * 
              - * - *

              This class's implementation is based on the Avro 1.7.7 specification and implements - * parsing of some parts of Avro Object Container Files. The rationale for doing so is that the Avro - * API does not provide efficient ways of computing the precise offsets of blocks within a file, - * which is necessary to support dynamic work rebalancing. However, whenever it is possible to use - * the Avro API in a way that supports maintaining precise offsets, this class uses the Avro API. - * - *

              Avro Object Container files store records in blocks. Each block contains a collection of - * records. Blocks may be encoded (e.g., with bzip2, deflate, snappy, etc.). Blocks are delineated - * from one another by a 16-byte sync marker. - * - *

              An {@link AvroSource} for a subrange of a single file contains records in the blocks such that - * the start offset of the block is greater than or equal to the start offset of the source and less - * than the end offset of the source. - * - *

              To use XZ-encoded Avro files, please include an explicit dependency on {@code xz-1.5.jar}, - * which has been marked as optional in the Maven {@code sdk/pom.xml} for Google Cloud Dataflow: - * - *

              {@code
              - * 
              - *   org.tukaani
              - *   xz
              - *   1.5
              - * 
              - * }
              - * - *

              Permissions

              - * - *

              Permission requirements depend on the {@link PipelineRunner} that is used to execute the - * Dataflow job. Please refer to the documentation of corresponding {@link PipelineRunner}s for - * more details. - * - * @param The type of records to be read from the source. - */ -// CHECKSTYLE.ON: JavadocStyle -@Experimental(Experimental.Kind.SOURCE_SINK) -public class AvroSource extends BlockBasedSource { - // Default minimum bundle size (chosen as two default-size Avro blocks to attempt to - // ensure that every source has at least one block of records). - // The default sync interval is 64k. - static final long DEFAULT_MIN_BUNDLE_SIZE = 2 * DataFileConstants.DEFAULT_SYNC_INTERVAL; - - // The JSON schema used to encode records. - private final String readSchemaString; - - // The JSON schema that was used to write the source Avro file (may differ from the schema we will - // use to read from it). - private final String fileSchemaString; - - // The type of the records contained in the file. - private final Class type; - - // The following metadata fields are not user-configurable. They are extracted from the object - // container file header upon subsource creation. - - // The codec used to encode the blocks in the Avro file. String value drawn from those in - // https://avro.apache.org/docs/1.7.7/api/java/org/apache/avro/file/CodecFactory.html - private final String codec; - - // The object container file's 16-byte sync marker. - private final byte[] syncMarker; - - // Default output coder, lazily initialized. - private transient AvroCoder coder = null; - - // Schema of the file, lazily initialized. - private transient Schema fileSchema; - - // Schema used to encode records, lazily initialized. - private transient Schema readSchema; - - /** - * Creates a {@link Read} transform that will read from an {@link AvroSource} that is configured - * to read records of the given type from a file pattern. - */ - public static Read.Bounded readFromFileWithClass(String filePattern, Class clazz) { - return Read.from(new AvroSource<>(filePattern, DEFAULT_MIN_BUNDLE_SIZE, - ReflectData.get().getSchema(clazz).toString(), clazz, null, null)); - } - - /** - * Creates an {@link AvroSource} that reads from the given file name or pattern ("glob"). The - * returned source can be further configured by calling {@link #withSchema} to return a type other - * than {@link GenericRecord}. - */ - public static AvroSource from(String fileNameOrPattern) { - return new AvroSource<>( - fileNameOrPattern, DEFAULT_MIN_BUNDLE_SIZE, null, GenericRecord.class, null, null); - } - - /** - * Returns an {@link AvroSource} that's like this one but reads files containing records that - * conform to the given schema. - * - *

              Does not modify this object. - */ - public AvroSource withSchema(String schema) { - return new AvroSource<>( - getFileOrPatternSpec(), getMinBundleSize(), schema, GenericRecord.class, codec, syncMarker); - } - - /** - * Returns an {@link AvroSource} that's like this one but reads files containing records that - * conform to the given schema. - * - *

              Does not modify this object. - */ - public AvroSource withSchema(Schema schema) { - return new AvroSource<>(getFileOrPatternSpec(), getMinBundleSize(), schema.toString(), - GenericRecord.class, codec, syncMarker); - } - - /** - * Returns an {@link AvroSource} that's like this one but reads files containing records of the - * type of the given class. - * - *

              Does not modify this object. - */ - public AvroSource withSchema(Class clazz) { - return new AvroSource(getFileOrPatternSpec(), getMinBundleSize(), - ReflectData.get().getSchema(clazz).toString(), clazz, codec, syncMarker); - } - - /** - * Returns an {@link AvroSource} that's like this one but uses the supplied minimum bundle size. - * Refer to {@link OffsetBasedSource} for a description of {@code minBundleSize} and its use. - * - *

              Does not modify this object. - */ - public AvroSource withMinBundleSize(long minBundleSize) { - return new AvroSource<>( - getFileOrPatternSpec(), minBundleSize, readSchemaString, type, codec, syncMarker); - } - - private AvroSource(String fileNameOrPattern, long minBundleSize, String schema, Class type, - String codec, byte[] syncMarker) { - super(fileNameOrPattern, minBundleSize); - this.readSchemaString = internSchemaString(schema); - this.codec = codec; - this.syncMarker = syncMarker; - this.type = type; - this.fileSchemaString = null; - } - - private AvroSource(String fileName, long minBundleSize, long startOffset, long endOffset, - String schema, Class type, String codec, byte[] syncMarker, String fileSchema) { - super(fileName, minBundleSize, startOffset, endOffset); - this.readSchemaString = internSchemaString(schema); - this.codec = codec; - this.syncMarker = syncMarker; - this.type = type; - this.fileSchemaString = internSchemaString(fileSchema); - } - - @Override - public void validate() { - // AvroSource objects do not need to be configured with more than a file pattern. Overridden to - // make this explicit. - super.validate(); - } - - @Override - public BlockBasedSource createForSubrangeOfFile(String fileName, long start, long end) { - byte[] syncMarker = this.syncMarker; - String codec = this.codec; - String readSchemaString = this.readSchemaString; - String fileSchemaString = this.fileSchemaString; - // codec and syncMarker are initially null when the source is created, as they differ - // across input files and must be read from the file. Here, when we are creating a source - // for a subrange of a file, we can initialize these values. When the resulting AvroSource - // is further split, they do not need to be read again. - if (codec == null || syncMarker == null || fileSchemaString == null) { - AvroMetadata metadata; - try { - Collection files = FileBasedSource.expandFilePattern(fileName); - checkArgument(files.size() <= 1, "More than 1 file matched %s"); - metadata = AvroUtils.readMetadataFromFile(fileName); - } catch (IOException e) { - throw new RuntimeException("Error reading metadata from file " + fileName, e); - } - codec = metadata.getCodec(); - syncMarker = metadata.getSyncMarker(); - fileSchemaString = metadata.getSchemaString(); - // If the source was created with a null schema, use the schema that we read from the file's - // metadata. - if (readSchemaString == null) { - readSchemaString = metadata.getSchemaString(); - } - } - // Note that if the fileSchemaString is equivalent to the readSchemaString, "intern"ing - // the string will occur within the constructor and return the same reference as the - // readSchemaString. This allows for Java to have an efficient serialization since it - // will only encode the schema once while just storing pointers to the encoded version - // within this source. - return new AvroSource<>(fileName, getMinBundleSize(), start, end, readSchemaString, type, - codec, syncMarker, fileSchemaString); - } - - @Override - protected BlockBasedReader createSingleFileReader(PipelineOptions options) { - return new AvroReader<>(this); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public AvroCoder getDefaultOutputCoder() { - if (coder == null) { - coder = AvroCoder.of(type, internOrParseSchemaString(readSchemaString)); - } - return coder; - } - - public String getSchema() { - return readSchemaString; - } - - @VisibleForTesting - Schema getReadSchema() { - if (readSchemaString == null) { - return null; - } - - // If the schema has not been parsed, parse it. - if (readSchema == null) { - readSchema = internOrParseSchemaString(readSchemaString); - } - return readSchema; - } - - @VisibleForTesting - Schema getFileSchema() { - if (fileSchemaString == null) { - return null; - } - - // If the schema has not been parsed, parse it. - if (fileSchema == null) { - fileSchema = internOrParseSchemaString(fileSchemaString); - } - return fileSchema; - } - - private byte[] getSyncMarker() { - return syncMarker; - } - - private String getCodec() { - return codec; - } - - private DatumReader createDatumReader() { - Schema readSchema = getReadSchema(); - Schema fileSchema = getFileSchema(); - checkNotNull(readSchema, "No read schema has been initialized for source %s", this); - checkNotNull(fileSchema, "No file schema has been initialized for source %s", this); - if (type == GenericRecord.class) { - return new GenericDatumReader<>(fileSchema, readSchema); - } else { - return new ReflectDatumReader<>(fileSchema, readSchema); - } - } - - // A logical reference cache used to store schemas and schema strings to allow us to - // "intern" values and reduce the number of copies of equivalent objects. - private static final Map schemaLogicalReferenceCache = new WeakHashMap<>(); - private static final Map schemaStringLogicalReferenceCache = new WeakHashMap<>(); - - // We avoid String.intern() because depending on the JVM, these may be added to the PermGenSpace - // which we want to avoid otherwise we could run out of PermGenSpace. - private static synchronized String internSchemaString(String schema) { - String internSchema = schemaStringLogicalReferenceCache.get(schema); - if (internSchema != null) { - return internSchema; - } - schemaStringLogicalReferenceCache.put(schema, schema); - return schema; - } - - private static synchronized Schema internOrParseSchemaString(String schemaString) { - Schema schema = schemaLogicalReferenceCache.get(schemaString); - if (schema != null) { - return schema; - } - Schema.Parser parser = new Schema.Parser(); - schema = parser.parse(schemaString); - schemaLogicalReferenceCache.put(schemaString, schema); - return schema; - } - - // Reading the object from Java serialization typically does not go through the constructor, - // we use readResolve to replace the constructed instance with one which uses the constructor - // allowing us to intern any schemas. - @SuppressWarnings("unused") - private Object readResolve() throws ObjectStreamException { - switch (getMode()) { - case SINGLE_FILE_OR_SUBRANGE: - return new AvroSource<>( - getFileOrPatternSpec(), - getMinBundleSize(), - getStartOffset(), - getEndOffset(), - readSchemaString, - type, - codec, - syncMarker, - fileSchemaString); - case FILEPATTERN: - return new AvroSource<>( - getFileOrPatternSpec(), - getMinBundleSize(), - readSchemaString, - type, - codec, - syncMarker); - default: - throw new InvalidObjectException( - String.format("Unknown mode %s for AvroSource %s", getMode(), this)); - } - } - - /** - * A {@link BlockBasedSource.Block} of Avro records. - * - * @param The type of records stored in the block. - */ - @Experimental(Experimental.Kind.SOURCE_SINK) - static class AvroBlock extends Block { - // The number of records in the block. - private final long numRecords; - - // The current record in the block. - private T currentRecord; - - // The index of the current record in the block. - private long currentRecordIndex = 0; - - // A DatumReader to read records from the block. - private final DatumReader reader; - - // A BinaryDecoder used by the reader to decode records. - private final BinaryDecoder decoder; - - /** - * Decodes a byte array as an InputStream. The byte array may be compressed using some - * codec. Reads from the returned stream will result in decompressed bytes. - * - *

              This supports the same codecs as Avro's {@link CodecFactory}, namely those defined in - * {@link DataFileConstants}. - * - *

                - *
              • "snappy" : Google's Snappy compression - *
              • "deflate" : deflate compression - *
              • "bzip2" : Bzip2 compression - *
              • "xz" : xz compression - *
              • "null" (the string, not the value): Uncompressed data - *
              - */ - private static InputStream decodeAsInputStream(byte[] data, String codec) throws IOException { - ByteArrayInputStream byteStream = new ByteArrayInputStream(data); - switch (codec) { - case DataFileConstants.SNAPPY_CODEC: - return new SnappyCompressorInputStream(byteStream, 1 << 16 /* Avro uses 64KB blocks. */); - case DataFileConstants.DEFLATE_CODEC: - // nowrap == true: Do not expect ZLIB header or checksum, as Avro does not write them. - Inflater inflater = new Inflater(true); - return new InflaterInputStream(byteStream, inflater); - case DataFileConstants.XZ_CODEC: - return new XZCompressorInputStream(byteStream); - case DataFileConstants.BZIP2_CODEC: - return new BZip2CompressorInputStream(byteStream); - case DataFileConstants.NULL_CODEC: - return byteStream; - default: - throw new IllegalArgumentException("Unsupported codec: " + codec); - } - } - - AvroBlock(byte[] data, long numRecords, AvroSource source) throws IOException { - this.numRecords = numRecords; - this.reader = source.createDatumReader(); - this.decoder = - DecoderFactory.get().binaryDecoder(decodeAsInputStream(data, source.getCodec()), null); - } - - @Override - public T getCurrentRecord() { - return currentRecord; - } - - @Override - public boolean readNextRecord() throws IOException { - if (currentRecordIndex >= numRecords) { - return false; - } - currentRecord = reader.read(null, decoder); - currentRecordIndex++; - return true; - } - - @Override - public double getFractionOfBlockConsumed() { - return ((double) currentRecordIndex) / numRecords; - } - } - - /** - * A {@link BlockBasedSource.BlockBasedReader} for reading blocks from Avro files. - * - *

              An Avro Object Container File consists of a header followed by a 16-bit sync marker - * and then a sequence of blocks, where each block begins with two encoded longs representing - * the total number of records in the block and the block's size in bytes, followed by the - * block's (optionally-encoded) records. Each block is terminated by a 16-bit sync marker. - * - * @param The type of records contained in the block. - */ - @Experimental(Experimental.Kind.SOURCE_SINK) - public static class AvroReader extends BlockBasedReader { - // The current block. - private AvroBlock currentBlock; - - // A lock used to synchronize block offsets for getRemainingParallelism - private final Object progressLock = new Object(); - - // Offset of the current block. - @GuardedBy("progressLock") - private long currentBlockOffset = 0; - - // Size of the current block. - @GuardedBy("progressLock") - private long currentBlockSizeBytes = 0; - - // Stream used to read from the underlying file. - // A pushback stream is used to restore bytes buffered during seeking. - private PushbackInputStream stream; - // Counts the number of bytes read. Used only to tell how many bytes are taken up in - // a block's variable-length header. - private CountingInputStream countStream; - - // Caches the Avro DirectBinaryDecoder used to decode binary-encoded values from the buffer. - private BinaryDecoder decoder; - - /** - * Reads Avro records of type {@code T} from the specified source. - */ - public AvroReader(AvroSource source) { - super(source); - } - - @Override - public synchronized AvroSource getCurrentSource() { - return (AvroSource) super.getCurrentSource(); - } - - // Precondition: the stream is positioned after the sync marker in the current (about to be - // previous) block. currentBlockSize equals the size of the current block, or zero if this - // reader was just started. - // - // Postcondition: same as above, but for the new current (formerly next) block. - @Override - public boolean readNextBlock() throws IOException { - long startOfNextBlock; - synchronized (progressLock) { - startOfNextBlock = currentBlockOffset + currentBlockSizeBytes; - } - - // Before reading the variable-sized block header, record the current number of bytes read. - long preHeaderCount = countStream.getBytesRead(); - decoder = DecoderFactory.get().directBinaryDecoder(countStream, decoder); - long numRecords; - try { - numRecords = decoder.readLong(); - } catch (EOFException e) { - // Expected for the last block, at which the start position is the EOF. The way to detect - // stream ending is to try reading from it. - return false; - } - long blockSize = decoder.readLong(); - - // Mark header size as the change in the number of bytes read. - long headerSize = countStream.getBytesRead() - preHeaderCount; - - // Create the current block by reading blockSize bytes. Block sizes permitted by the Avro - // specification are [32, 2^30], so this narrowing is ok. - byte[] data = new byte[(int) blockSize]; - int read = stream.read(data); - checkState(blockSize == read, "Only %s/%s bytes in the block were read", read, blockSize); - currentBlock = new AvroBlock<>(data, numRecords, getCurrentSource()); - - // Read the end of this block, which MUST be a sync marker for correctness. - byte[] syncMarker = getCurrentSource().getSyncMarker(); - byte[] readSyncMarker = new byte[syncMarker.length]; - long syncMarkerOffset = startOfNextBlock + headerSize + blockSize; - long bytesRead = stream.read(readSyncMarker); - checkState( - bytesRead == syncMarker.length, - "When trying to read a sync marker at position %s, only able to read %s/%s bytes", - syncMarkerOffset, - bytesRead, - syncMarker.length); - if (!Arrays.equals(syncMarker, readSyncMarker)) { - throw new IllegalStateException( - String.format( - "Expected the bytes [%d,%d) in file %s to be a sync marker, but found %s", - syncMarkerOffset, - syncMarkerOffset + syncMarker.length, - getCurrentSource().getFileOrPatternSpec(), - Arrays.toString(readSyncMarker) - )); - } - - // Atomically update both the position and offset of the new block. - synchronized (progressLock) { - currentBlockOffset = startOfNextBlock; - // Total block size includes the header, block content, and trailing sync marker. - currentBlockSizeBytes = headerSize + blockSize + syncMarker.length; - } - - return true; - } - - @Override - public AvroBlock getCurrentBlock() { - return currentBlock; - } - - @Override - public long getCurrentBlockOffset() { - synchronized (progressLock) { - return currentBlockOffset; - } - } - - @Override - public long getCurrentBlockSize() { - synchronized (progressLock) { - return currentBlockSizeBytes; - } - } - - @Override - public long getSplitPointsRemaining() { - if (isDone()) { - return 0; - } - synchronized (progressLock) { - if (currentBlockOffset + currentBlockSizeBytes >= getCurrentSource().getEndOffset()) { - // This block is known to be the last block in the range. - return 1; - } - } - return super.getSplitPointsRemaining(); - } - - /** - * Creates a {@link PushbackInputStream} that has a large enough pushback buffer to be able - * to push back the syncBuffer. - */ - private PushbackInputStream createStream(ReadableByteChannel channel) { - return new PushbackInputStream( - Channels.newInputStream(channel), - getCurrentSource().getSyncMarker().length); - } - - // Postcondition: the stream is positioned at the beginning of the first block after the start - // of the current source, and currentBlockOffset is that position. Additionally, - // currentBlockSizeBytes will be set to 0 indicating that the previous block was empty. - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - long startOffset = getCurrentSource().getStartOffset(); - byte[] syncMarker = getCurrentSource().getSyncMarker(); - long syncMarkerLength = syncMarker.length; - - if (startOffset != 0) { - // Rewind order to find the sync marker ending the previous block. - long position = Math.max(0, startOffset - syncMarkerLength); - ((SeekableByteChannel) channel).position(position); - startOffset = position; - } - - // Satisfy the post condition. - stream = createStream(channel); - countStream = new CountingInputStream(stream); - synchronized (progressLock) { - currentBlockOffset = startOffset + advancePastNextSyncMarker(stream, syncMarker); - currentBlockSizeBytes = 0; - } - } - - /** - * Advances to the first byte after the next occurrence of the sync marker in the - * stream when reading from the current offset. Returns the number of bytes consumed - * from the stream. Note that this method requires a PushbackInputStream with a buffer - * at least as big as the marker it is seeking for. - */ - static long advancePastNextSyncMarker(PushbackInputStream stream, byte[] syncMarker) - throws IOException { - Seeker seeker = new Seeker(syncMarker); - byte[] syncBuffer = new byte[syncMarker.length]; - long totalBytesConsumed = 0; - // Seek until either a sync marker is found or we reach the end of the file. - int mark = -1; // Position of the last byte in the sync marker. - int read; // Number of bytes read. - do { - read = stream.read(syncBuffer); - if (read >= 0) { - mark = seeker.find(syncBuffer, read); - // Update the currentOffset with the number of bytes read. - totalBytesConsumed += read; - } - } while (mark < 0 && read > 0); - - // If the sync marker was found, unread block data and update the current offsets. - if (mark >= 0) { - // The current offset after this call should be just past the sync marker, so we should - // unread the remaining buffer contents and update the currentOffset accordingly. - stream.unread(syncBuffer, mark + 1, read - (mark + 1)); - totalBytesConsumed = totalBytesConsumed - (read - (mark + 1)); - } - return totalBytesConsumed; - } - - /** - * A {@link Seeker} looks for a given marker within a byte buffer. Uses naive string matching - * with a sliding window, as sync markers are small and random. - */ - static class Seeker { - // The marker to search for. - private byte[] marker; - - // Buffer used for the sliding window. - private byte[] searchBuffer; - - // Number of bytes available to be matched in the buffer. - private int available = 0; - - /** - * Create a {@link Seeker} that looks for the given marker. - */ - public Seeker(byte[] marker) { - this.marker = marker; - this.searchBuffer = new byte[marker.length]; - } - - /** - * Find the marker in the byte buffer. Returns the index of the end of the marker in the - * buffer. If the marker is not found, returns -1. - * - *

              State is maintained between calls. If the marker was partially matched, a subsequent - * call to find will resume matching the marker. - * - * @param buffer - * @return the index of the end of the marker within the buffer, or -1 if the buffer was not - * found. - */ - public int find(byte[] buffer, int length) { - for (int i = 0; i < length; i++) { - System.arraycopy(searchBuffer, 1, searchBuffer, 0, searchBuffer.length - 1); - searchBuffer[searchBuffer.length - 1] = buffer[i]; - available = Math.min(available + 1, searchBuffer.length); - if (ByteBuffer.wrap(searchBuffer, searchBuffer.length - available, available) - .equals(ByteBuffer.wrap(marker))) { - available = 0; - return i; - } - } - return -1; - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java deleted file mode 100644 index ace18eff5e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ /dev/null @@ -1,3076 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.client.json.JsonFactory; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.Job; -import com.google.api.services.bigquery.model.JobConfigurationExtract; -import com.google.api.services.bigquery.model.JobConfigurationLoad; -import com.google.api.services.bigquery.model.JobConfigurationQuery; -import com.google.api.services.bigquery.model.JobConfigurationTableCopy; -import com.google.api.services.bigquery.model.JobReference; -import com.google.api.services.bigquery.model.JobStatistics; -import com.google.api.services.bigquery.model.JobStatus; -import com.google.api.services.bigquery.model.QueryRequest; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.AvroUtils; -import com.google.cloud.dataflow.sdk.util.BigQueryServices; -import com.google.cloud.dataflow.sdk.util.BigQueryServices.DatasetService; -import com.google.cloud.dataflow.sdk.util.BigQueryServices.JobService; -import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl; -import com.google.cloud.dataflow.sdk.util.BigQueryTableInserter; -import com.google.cloud.dataflow.sdk.util.BigQueryTableRowIterator; -import com.google.cloud.dataflow.sdk.util.FileIOChannelFactory; -import com.google.cloud.dataflow.sdk.util.GcsIOChannelFactory; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.GcsUtil.GcsUtilFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.Reshuffle; -import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.cloud.hadoop.util.ApiErrorExtractor; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.io.CountingOutputStream; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.apache.avro.generic.GenericRecord; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.atomic.AtomicReference; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; - -/** - * {@link PTransform}s for reading and writing - * BigQuery tables. - * - *

              Table References

              - * - *

              A fully-qualified BigQuery table name consists of three components: - *

                - *
              • {@code projectId}: the Cloud project id (defaults to - * {@link GcpOptions#getProject()}). - *
              • {@code datasetId}: the BigQuery dataset id, unique within a project. - *
              • {@code tableId}: a table id, unique within a dataset. - *
              - * - *

              BigQuery table references are stored as a {@link TableReference}, which comes - * from the - * BigQuery Java Client API. - * Tables can be referred to as Strings, with or without the {@code projectId}. - * A helper function is provided ({@link BigQueryIO#parseTableSpec(String)}) - * that parses the following string forms into a {@link TableReference}: - * - *

                - *
              • [{@code project_id}]:[{@code dataset_id}].[{@code table_id}] - *
              • [{@code dataset_id}].[{@code table_id}] - *
              - * - *

              Reading

              - * - *

              To read from a BigQuery table, apply a {@link BigQueryIO.Read} transformation. - * This produces a {@link PCollection} of {@link TableRow TableRows} as output: - *

              {@code
              - * PCollection weatherData = pipeline.apply(
              - *     BigQueryIO.Read.named("Read")
              - *                    .from("clouddataflow-readonly:samples.weather_stations"));
              - * }
              - * - *

              See {@link TableRow} for more information on the {@link TableRow} object. - * - *

              Users may provide a query to read from rather than reading all of a BigQuery table. If - * specified, the result obtained by executing the specified query will be used as the data of the - * input transform. - * - *

              {@code
              - * PCollection meanTemperatureData = pipeline.apply(
              - *     BigQueryIO.Read.named("Read")
              - *                    .fromQuery("SELECT year, mean_temp FROM [samples.weather_stations]"));
              - * }
              - * - *

              When creating a BigQuery input transform, users should provide either a query or a table. - * Pipeline construction will fail with a validation error if neither or both are specified. - * - *

              Writing

              - * - *

              To write to a BigQuery table, apply a {@link BigQueryIO.Write} transformation. - * This consumes a {@link PCollection} of {@link TableRow TableRows} as input. - *

              {@code
              - * PCollection quotes = ...
              - *
              - * List fields = new ArrayList<>();
              - * fields.add(new TableFieldSchema().setName("source").setType("STRING"));
              - * fields.add(new TableFieldSchema().setName("quote").setType("STRING"));
              - * TableSchema schema = new TableSchema().setFields(fields);
              - *
              - * quotes.apply(BigQueryIO.Write
              - *     .named("Write")
              - *     .to("my-project:output.output_table")
              - *     .withSchema(schema)
              - *     .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE));
              - * }
              - * - *

              See {@link BigQueryIO.Write} for details on how to specify if a write should - * append to an existing table, replace the table, or verify that the table is - * empty. Note that the dataset being written to must already exist. Write - * dispositions are not supported in streaming mode. - * - *

              Sharding BigQuery output tables

              - * - *

              A common use case is to dynamically generate BigQuery table names based on - * the current window. To support this, - * {@link BigQueryIO.Write#to(SerializableFunction)} - * accepts a function mapping the current window to a tablespec. For example, - * here's code that outputs daily tables to BigQuery: - *

              {@code
              - * PCollection quotes = ...
              - * quotes.apply(Window.into(CalendarWindows.days(1)))
              - *       .apply(BigQueryIO.Write
              - *         .named("Write")
              - *         .withSchema(schema)
              - *         .to(new SerializableFunction() {
              - *           public String apply(BoundedWindow window) {
              - *             // The cast below is safe because CalendarWindows.days(1) produces IntervalWindows.
              - *             String dayString = DateTimeFormat.forPattern("yyyy_MM_dd")
              - *                  .withZone(DateTimeZone.UTC)
              - *                  .print(((IntervalWindow) window).start());
              - *             return "my-project:output.output_table_" + dayString;
              - *           }
              - *         }));
              - * }
              - * - *

              Per-window tables are not yet supported in batch mode. - * - *

              Permissions

              - * - *

              Permission requirements depend on the {@link PipelineRunner} that is used to execute the - * Dataflow job. Please refer to the documentation of corresponding {@link PipelineRunner}s for - * more details. - * - *

              Please see BigQuery Access Control - * for security and permission related information specific to BigQuery. - */ -public class BigQueryIO { - private static final Logger LOG = LoggerFactory.getLogger(BigQueryIO.class); - - /** - * Singleton instance of the JSON factory used to read and write JSON - * formatted rows. - */ - private static final JsonFactory JSON_FACTORY = Transport.getJsonFactory(); - - /** - * Project IDs must contain 6-63 lowercase letters, digits, or dashes. - * IDs must start with a letter and may not end with a dash. - * This regex isn't exact - this allows for patterns that would be rejected by - * the service, but this is sufficient for basic parsing of table references. - */ - private static final String PROJECT_ID_REGEXP = "[a-z][-a-z0-9:.]{4,61}[a-z0-9]"; - - /** - * Regular expression that matches Dataset IDs. - */ - private static final String DATASET_REGEXP = "[-\\w.]{1,1024}"; - - /** - * Regular expression that matches Table IDs. - */ - private static final String TABLE_REGEXP = "[-\\w$@]{1,1024}"; - - /** - * Matches table specifications in the form {@code "[project_id]:[dataset_id].[table_id]"} or - * {@code "[dataset_id].[table_id]"}. - */ - private static final String DATASET_TABLE_REGEXP = - String.format("((?%s):)?(?%s)\\.(?%s)", PROJECT_ID_REGEXP, - DATASET_REGEXP, TABLE_REGEXP); - - private static final Pattern TABLE_SPEC = Pattern.compile(DATASET_TABLE_REGEXP); - - @Deprecated // unused. - public static final String SET_PROJECT_FROM_OPTIONS_WARNING = - "No project specified for BigQuery table \"%1$s.%2$s\". Assuming it is in \"%3$s\". If the" - + " table is in a different project please specify it as a part of the BigQuery table" - + " definition."; - - private static final String RESOURCE_NOT_FOUND_ERROR = - "BigQuery %1$s not found for table \"%2$s\" . Please create the %1$s before pipeline" - + " execution. If the %1$s is created by an earlier stage of the pipeline, this" - + " validation can be disabled using #withoutValidation."; - - private static final String UNABLE_TO_CONFIRM_PRESENCE_OF_RESOURCE_ERROR = - "Unable to confirm BigQuery %1$s presence for table \"%2$s\". If the %1$s is created by" - + " an earlier stage of the pipeline, this validation can be disabled using" - + " #withoutValidation."; - - /** - * Parse a table specification in the form - * {@code "[project_id]:[dataset_id].[table_id]"} or {@code "[dataset_id].[table_id]"}. - * - *

              If the project id is omitted, the default project id is used. - */ - public static TableReference parseTableSpec(String tableSpec) { - Matcher match = TABLE_SPEC.matcher(tableSpec); - if (!match.matches()) { - throw new IllegalArgumentException( - "Table reference is not in [project_id]:[dataset_id].[table_id] " - + "format: " + tableSpec); - } - - TableReference ref = new TableReference(); - ref.setProjectId(match.group("PROJECT")); - - return ref.setDatasetId(match.group("DATASET")).setTableId(match.group("TABLE")); - } - - /** - * Returns a canonical string representation of the {@link TableReference}. - */ - public static String toTableSpec(TableReference ref) { - StringBuilder sb = new StringBuilder(); - if (ref.getProjectId() != null) { - sb.append(ref.getProjectId()); - sb.append(":"); - } - - sb.append(ref.getDatasetId()).append('.').append(ref.getTableId()); - return sb.toString(); - } - - @VisibleForTesting - static class JsonSchemaToTableSchema - implements SerializableFunction { - @Override - public TableSchema apply(String from) { - return fromJsonString(from, TableSchema.class); - } - } - - private static class TableSchemaToJsonSchema - implements SerializableFunction { - @Override - public String apply(TableSchema from) { - return toJsonString(from); - } - } - - private static class JsonTableRefToTableRef - implements SerializableFunction { - @Override - public TableReference apply(String from) { - return fromJsonString(from, TableReference.class); - } - } - - private static class TableRefToTableSpec - implements SerializableFunction { - @Override - public String apply(TableReference from) { - return toTableSpec(from); - } - } - - private static class TableRefToJson - implements SerializableFunction { - @Override - public String apply(TableReference from) { - return toJsonString(from); - } - } - - private static class TableRefToProjectId - implements SerializableFunction { - @Override - public String apply(TableReference from) { - return from.getProjectId(); - } - } - - @VisibleForTesting - static class TableSpecToTableRef - implements SerializableFunction { - @Override - public TableReference apply(String from) { - return parseTableSpec(from); - } - } - - @Nullable - private static ValueProvider displayTable( - @Nullable ValueProvider table) { - if (table == null) { - return null; - } - return NestedValueProvider.of(table, new TableRefToTableSpec()); - } - - /** - * A {@link PTransform} that reads from a BigQuery table and returns a - * {@link PCollection} of {@link TableRow TableRows} containing each of the rows of the table. - * - *

              Each {@link TableRow} contains values indexed by column name. Here is a - * sample processing function that processes a "line" column from rows: - *

              {@code
              -   * static class ExtractWordsFn extends DoFn {
              -   *   public void processElement(ProcessContext c) {
              -   *     // Get the "line" field of the TableRow object, split it into words, and emit them.
              -   *     TableRow row = c.element();
              -   *     String[] words = row.get("line").toString().split("[^a-zA-Z']+");
              -   *     for (String word : words) {
              -   *       if (!word.isEmpty()) {
              -   *         c.output(word);
              -   *       }
              -   *     }
              -   *   }
              -   * }}
              - */ - public static class Read { - /** - * Returns a {@link Read.Bound} with the given name. The BigQuery table or query to be read - * from has not yet been configured. - */ - public static Bound named(String name) { - return new Bound().named(name); - } - - /** - * Reads a BigQuery table specified as {@code "[project_id]:[dataset_id].[table_id]"} or - * {@code "[dataset_id].[table_id]"} for tables within the current project. - */ - public static Bound from(String tableSpec) { - return new Bound().from(StaticValueProvider.of(tableSpec)); - } - - /** - * Same as {@code from(String)}, but with a {@link ValueProvider}. - */ - public static Bound from(ValueProvider tableSpec) { - return new Bound().from(tableSpec); - } - - /** - * Reads results received after executing the given query. - */ - public static Bound fromQuery(String query) { - return new Bound().fromQuery(StaticValueProvider.of(query)); - } - - /** - * Same as {@code from(String)}, but with a {@link ValueProvider}. - */ - public static Bound fromQuery(ValueProvider query) { - return new Bound().fromQuery(query); - } - - /** - * Reads a BigQuery table specified as a {@link TableReference} object. - */ - public static Bound from(TableReference table) { - return new Bound().from(table); - } - - /** - * Disables BigQuery table validation, which is enabled by default. - */ - public static Bound withoutValidation() { - return new Bound().withoutValidation(); - } - - /** - * A {@link PTransform} that reads from a BigQuery table and returns a bounded - * {@link PCollection} of {@link TableRow TableRows}. - */ - public static class Bound extends PTransform> { - @Nullable final ValueProvider jsonTableRef; - @Nullable final ValueProvider query; - final boolean validate; - @Nullable final Boolean flattenResults; - @Nullable final Boolean useLegacySql; - @Nullable BigQueryServices bigQueryServices; - - private static final String QUERY_VALIDATION_FAILURE_ERROR = - "Validation of query \"%1$s\" failed. If the query depends on an earlier stage of the" - + " pipeline, This validation can be disabled using #withoutValidation."; - - private Bound() { - this( - null /* name */, - null /* query */, - null /* jsonTableRef */, - true /* validate */, - null /* flattenResults */, - null /* useLegacySql */, - null /* bigQueryServices */); - } - - private Bound( - String name, @Nullable ValueProvider query, - @Nullable ValueProvider jsonTableRef, boolean validate, - @Nullable Boolean flattenResults, @Nullable Boolean useLegacySql, - @Nullable BigQueryServices bigQueryServices) { - super(name); - this.jsonTableRef = jsonTableRef; - this.query = query; - this.validate = validate; - this.flattenResults = flattenResults; - this.useLegacySql = useLegacySql; - this.bigQueryServices = bigQueryServices; - } - - /** - * Returns a copy of this transform using the name associated with this transformation. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound( - name, query, jsonTableRef, validate, flattenResults, useLegacySql, - bigQueryServices); - } - - /** - * Returns a copy of this transform that reads from the specified table. Refer to - * {@link #parseTableSpec(String)} for the specification format. - * - *

              Does not modify this object. - */ - public Bound from(String tableSpec) { - return from(StaticValueProvider.of(tableSpec)); - } - - /** - * Returns a copy of this transform that reads from the specified table. Refer to - * {@link #parseTableSpec(String)} for the specification format. - * - *

              Does not modify this object. - */ - public Bound from(ValueProvider tableSpec) { - return new Bound( - name, query, - NestedValueProvider.of( - NestedValueProvider.of( - tableSpec, new TableSpecToTableRef()), - new TableRefToJson()), - validate, flattenResults, useLegacySql, bigQueryServices); - } - - /** - * Returns a copy of this transform that reads from the specified table. - * - *

              Does not modify this object. - */ - public Bound from(TableReference table) { - return from(StaticValueProvider.of(toTableSpec(table))); - } - - /** - * Returns a copy of this transform that reads the results of the specified query. - * - *

              Does not modify this object. - * - *

              By default, the query results will be flattened -- see - * "flattenResults" in the - * Jobs documentation for more information. To disable flattening, use - * {@link BigQueryIO.Read.Bound#withoutResultFlattening}. - * - *

              By default, the query will use BigQuery's legacy SQL dialect. To use the BigQuery - * Standard SQL dialect, use {@link BigQueryIO.Read.Bound#usingStandardSql}. - */ - public Bound fromQuery(String query) { - return fromQuery(StaticValueProvider.of(query)); - } - - /** - * Like {@link #fromQuery(String)}, but from a {@link ValueProvider}. - */ - public Bound fromQuery(ValueProvider query) { - return new Bound(name, query, jsonTableRef, validate, - MoreObjects.firstNonNull(flattenResults, Boolean.TRUE), - MoreObjects.firstNonNull(useLegacySql, Boolean.TRUE), - bigQueryServices); - } - - /** - * Disable table validation. - */ - public Bound withoutValidation() { - return new Bound( - name, query, jsonTableRef, false /* validate */, flattenResults, useLegacySql, - bigQueryServices); - } - - /** - * Disable - * flattening of query results. - * - *

              Only valid when a query is used ({@link #fromQuery}). Setting this option when reading - * from a table will cause an error during validation. - */ - public Bound withoutResultFlattening() { - return new Bound( - name, query, jsonTableRef, validate, false /* flattenResults */, useLegacySql, - bigQueryServices); - } - - /** - * Enables BigQuery's Standard SQL dialect when reading from a query. - * - *

              Only valid when a query is used ({@link #fromQuery}). Setting this option when reading - * from a table will cause an error during validation. - */ - public Bound usingStandardSql() { - return new Bound( - name, query, jsonTableRef, validate, flattenResults, false /* useLegacySql */, - bigQueryServices); - } - - @VisibleForTesting - Bound withTestServices(BigQueryServices testServices) { - return new Bound( - name, query, jsonTableRef, validate, flattenResults, useLegacySql, testServices); - } - - @Override - public void validate(PInput input) { - if (!validate) { - // Note that a table or query check can fail if the table or dataset are created by - // earlier stages of the pipeline or if a query depends on earlier stages of a pipeline. - // For these cases the withoutValidation method can be used to disable the check. - return; - } - - BigQueryOptions bqOptions = input.getPipeline().getOptions().as(BigQueryOptions.class); - - String tempLocation = bqOptions.getTempLocation(); - checkArgument( - !Strings.isNullOrEmpty(tempLocation), - "BigQueryIO.Read needs a GCS temp location to store temp files."); - if (bigQueryServices == null) { - try { - GcsPath.fromUri(tempLocation); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException( - String.format( - "BigQuery temp location expected a valid 'gs://' path, but was given '%s'", - tempLocation), - e); - } - } - - ValueProvider table = getTableWithDefaultProject(bqOptions); - - checkState( - table == null || query == null, - "Invalid BigQueryIO.Read: table reference and query may not both be set"); - checkState( - table != null || query != null, - "Invalid BigQueryIO.Read: one of table reference and query must be set"); - - if (table != null) { - checkState( - flattenResults == null, - "Invalid BigQueryIO.Read: Specifies a table with a result flattening" - + " preference, which only applies to queries"); - checkState( - useLegacySql == null, - "Invalid BigQueryIO.Read: Specifies a table with a SQL dialect" - + " preference, which only applies to queries"); - - checkState(table.isAccessible(), "Cannot call validate if table is dynamically set."); - // Check for source table presence for early failure notification. - verifyDatasetPresence(bqOptions, table.get()); - verifyTablePresence(bqOptions, table.get()); - } else /* query != null */ { - checkState(query.isAccessible(), "Cannot call validate if query is dynamically set."); - checkState(flattenResults != null, "flattenResults should not be null if query is set"); - checkState(useLegacySql != null, "useLegacySql should not be null if query is set"); - dryRunQuery(bqOptions, query.get(), useLegacySql); - } - } - - private static void dryRunQuery( - BigQueryOptions options, String query, boolean useLegacySql) { - Bigquery client = Transport.newBigQueryClient(options).build(); - QueryRequest request = new QueryRequest(); - request.setQuery(query); - request.setDryRun(true); - request.setUseLegacySql(useLegacySql); - - String queryValidationErrorMsg = String.format(QUERY_VALIDATION_FAILURE_ERROR, query); - try { - BigQueryTableRowIterator.executeWithBackOff( - client.jobs().query(options.getProject(), request), - queryValidationErrorMsg); - } catch (Exception e) { - throw new IllegalArgumentException(queryValidationErrorMsg, e); - } - } - - @Override - public PCollection apply(PInput input) { - String uuid = randomUUIDString(); - final String jobIdToken = "beam_job_" + uuid; - - BigQueryOptions bqOptions = input.getPipeline().getOptions().as(BigQueryOptions.class); - - BoundedSource source; - final BigQueryServices bqServices = getBigQueryServices(); - - final String extractDestinationDir; - String tempLocation = bqOptions.getTempLocation(); - try { - IOChannelFactory factory = IOChannelUtils.getFactory(tempLocation); - extractDestinationDir = factory.resolve(tempLocation, uuid); - } catch (IOException e) { - throw new RuntimeException( - String.format("Failed to resolve extract destination directory in %s", tempLocation)); - } - - final String executingProject = bqOptions.getProject(); - if (query != null && (!query.isAccessible() || !Strings.isNullOrEmpty(query.get()))) { - String queryTempDatasetId = "temp_dataset_" + uuid; - String queryTempTableId = "temp_table_" + uuid; - - TableReference queryTempTableRef = new TableReference() - .setProjectId(executingProject) - .setDatasetId(queryTempDatasetId) - .setTableId(queryTempTableId); - String jsonTableRef = toJsonString(queryTempTableRef); - - source = BigQueryQuerySource.create( - jobIdToken, query, NestedValueProvider.of( - StaticValueProvider.of(jsonTableRef), new JsonTableRefToTableRef()), - flattenResults, useLegacySql, extractDestinationDir, bqServices); - } else { - ValueProvider inputTable = getTableWithDefaultProject(bqOptions); - source = BigQueryTableSource.create( - jobIdToken, inputTable, extractDestinationDir, bqServices, - StaticValueProvider.of(executingProject)); - } - PassThroughThenCleanup.CleanupOperation cleanupOperation = - new PassThroughThenCleanup.CleanupOperation() { - @Override - void cleanup(PipelineOptions options) throws Exception { - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - - JobReference jobRef = new JobReference() - .setProjectId(executingProject) - .setJobId(getExtractJobId(jobIdToken)); - - Job extractJob = bqServices.getJobService(bqOptions) - .getJob(jobRef); - - Collection extractFiles = null; - if (extractJob != null) { - extractFiles = getExtractFilePaths(extractDestinationDir, extractJob); - } else { - IOChannelFactory factory = IOChannelUtils.getFactory(extractDestinationDir); - Collection dirMatch = factory.match(extractDestinationDir); - if (!dirMatch.isEmpty()) { - extractFiles = factory.match(factory.resolve(extractDestinationDir, "*")); - } - } - if (extractFiles != null && !extractFiles.isEmpty()) { - new GcsUtilFactory().create(options).remove(extractFiles); - } - }}; - return input.getPipeline() - .apply(com.google.cloud.dataflow.sdk.io.Read.from(source)) - .setCoder(getDefaultOutputCoder()) - .apply(new PassThroughThenCleanup(cleanupOperation)); - } - - @Override - protected Coder getDefaultOutputCoder() { - return TableRowJsonCoder.of(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("table", displayTable(getTableProvider())) - .withLabel("Table")) - .addIfNotNull(DisplayData.item("query", query) - .withLabel("Query")) - .addIfNotNull(DisplayData.item("flattenResults", flattenResults) - .withLabel("Flatten Query Results")) - .addIfNotNull(DisplayData.item("useLegacySql", useLegacySql) - .withLabel("Use Legacy SQL Dialect")) - .addIfNotDefault(DisplayData.item("validation", validate) - .withLabel("Validation Enabled"), - true); - } - - /** - * Returns the table to read, or {@code null} if reading from a query instead. - * - *

              If the table's project is not specified, use the executing project. - */ - @Nullable private ValueProvider getTableWithDefaultProject( - BigQueryOptions bqOptions) { - ValueProvider table = getTableProvider(); - if (table == null) { - return table; - } - if (!table.isAccessible()) { - LOG.info("Using a dynamic value for table input. This must contain a project" - + " in the table reference: {}", table); - return table; - } - if (Strings.isNullOrEmpty(table.get().getProjectId())) { - // If user does not specify a project we assume the table to be located in - // the default project. - TableReference tableRef = table.get(); - tableRef.setProjectId(bqOptions.getProject()); - return NestedValueProvider.of(StaticValueProvider.of( - toJsonString(tableRef)), new JsonTableRefToTableRef()); - } - return table; - } - - /** - * Returns the table to read, or {@code null} if reading from a query instead. - */ - @Nullable - public ValueProvider getTableProvider() { - return jsonTableRef == null - ? null : NestedValueProvider.of(jsonTableRef, new JsonTableRefToTableRef()); - } - - /** - * Returns the table to read, or {@code null} if reading from a query instead. - */ - @Nullable - public TableReference getTable() { - ValueProvider provider = getTableProvider(); - return provider == null ? null : provider.get(); - } - - /** - * Returns the query to be read, or {@code null} if reading from a table instead. - */ - @Nullable - public String getQuery() { - return query == null ? null : query.get(); - } - - /** - * Returns the query to be read, or {@code null} if reading from a table instead. - */ - @Nullable - public ValueProvider getQueryProvider() { - return query; - } - - /** - * Returns true if table validation is enabled. - */ - public boolean getValidate() { - return validate; - } - - /** - * Returns true/false if result flattening is enabled/disabled, or null if not applicable. - */ - public Boolean getFlattenResults() { - return flattenResults; - } - - /** - * Returns true (false) if the query will (will not) use BigQuery's legacy SQL mode, or null - * if not applicable. - */ - @Nullable - public Boolean getUseLegacySql() { - return useLegacySql; - } - - private BigQueryServices getBigQueryServices() { - if (bigQueryServices == null) { - bigQueryServices = new BigQueryServicesImpl(); - } - return bigQueryServices; - } - } - - /** Disallow construction of utility class. */ - private Read() {} - } - - /** - * A {@link PTransform} that invokes {@link CleanupOperation} after the input {@link PCollection} - * has been processed. - */ - @VisibleForTesting - static class PassThroughThenCleanup extends PTransform, PCollection> { - - private CleanupOperation cleanupOperation; - - PassThroughThenCleanup(CleanupOperation cleanupOperation) { - this.cleanupOperation = cleanupOperation; - } - - @Override - public PCollection apply(PCollection input) { - TupleTag mainOutput = new TupleTag<>(); - TupleTag cleanupSignal = new TupleTag<>(); - PCollectionTuple outputs = input.apply(ParDo.of(new IdentityFn()) - .withOutputTags(mainOutput, TupleTagList.of(cleanupSignal))); - - PCollectionView cleanupSignalView = outputs.get(cleanupSignal) - .setCoder(VoidCoder.of()) - .apply(View.asSingleton().withDefaultValue(null)); - - input.getPipeline() - .apply("Create(CleanupOperation)", Create.of(cleanupOperation)) - .apply("Cleanup", ParDo.of( - new DoFn() { - @Override - public void processElement(ProcessContext c) - throws Exception { - c.element().cleanup(c.getPipelineOptions()); - } - }).withSideInputs(cleanupSignalView)); - - return outputs.get(mainOutput); - } - - private static class IdentityFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element()); - } - } - - abstract static class CleanupOperation implements Serializable { - abstract void cleanup(PipelineOptions options) throws Exception; - } - } - - /** - * A {@link BigQuerySourceBase} for reading BigQuery tables. - */ - @VisibleForTesting - static class BigQueryTableSource extends BigQuerySourceBase { - - static BigQueryTableSource create( - String jobIdToken, - ValueProvider table, - String extractDestinationDir, - BigQueryServices bqServices, - ValueProvider executingProject) { - return new BigQueryTableSource( - jobIdToken, table, extractDestinationDir, bqServices, executingProject); - } - - private final ValueProvider jsonTable; - private final AtomicReference tableSizeBytes; - - private BigQueryTableSource( - String jobIdToken, - ValueProvider table, - String extractDestinationDir, - BigQueryServices bqServices, - ValueProvider executingProject) { - super(jobIdToken, extractDestinationDir, bqServices, executingProject); - this.jsonTable = NestedValueProvider.of(checkNotNull(table, "table"), new TableRefToJson()); - this.tableSizeBytes = new AtomicReference<>(); - } - - @Override - protected TableReference getTableToExtract(BigQueryOptions bqOptions) throws IOException { - checkState(jsonTable.isAccessible()); - return JSON_FACTORY.fromString(jsonTable.get(), TableReference.class); - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - checkState(jsonTable.isAccessible()); - TableReference tableRef = JSON_FACTORY.fromString(jsonTable.get(), TableReference.class); - return new BigQueryReader(this, bqServices.getReaderFromTable(bqOptions, tableRef)); - } - - @Override - public synchronized long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - if (tableSizeBytes.get() == null) { - TableReference table = JSON_FACTORY.fromString(jsonTable.get(), TableReference.class); - - Long numBytes = bqServices.getDatasetService(options.as(BigQueryOptions.class)) - .getTable(table.getProjectId(), table.getDatasetId(), table.getTableId()) - .getNumBytes(); - tableSizeBytes.compareAndSet(null, numBytes); - } - return tableSizeBytes.get(); - } - - @Override - protected void cleanupTempResource(BigQueryOptions bqOptions) throws Exception { - // Do nothing. - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("table", jsonTable)); - } - } - - /** - * A {@link BigQuerySourceBase} for querying BigQuery tables. - */ - @VisibleForTesting - static class BigQueryQuerySource extends BigQuerySourceBase { - - static BigQueryQuerySource create( - String jobIdToken, - ValueProvider query, - ValueProvider queryTempTableRef, - Boolean flattenResults, - Boolean useLegacySql, - String extractDestinationDir, - BigQueryServices bqServices) { - return new BigQueryQuerySource( - jobIdToken, - query, - queryTempTableRef, - flattenResults, - useLegacySql, - extractDestinationDir, - bqServices); - } - - private final ValueProvider query; - private final ValueProvider jsonQueryTempTable; - private final Boolean flattenResults; - private final Boolean useLegacySql; - private transient AtomicReference dryRunJobStats; - - private BigQueryQuerySource( - String jobIdToken, - ValueProvider query, - ValueProvider queryTempTableRef, - Boolean flattenResults, - Boolean useLegacySql, - String extractDestinationDir, - BigQueryServices bqServices) { - super(jobIdToken, extractDestinationDir, bqServices, - NestedValueProvider.of( - checkNotNull(queryTempTableRef, "queryTempTableRef"), new TableRefToProjectId())); - this.query = checkNotNull(query, "query"); - this.jsonQueryTempTable = NestedValueProvider.of( - queryTempTableRef, new TableRefToJson()); - this.flattenResults = checkNotNull(flattenResults, "flattenResults"); - this.useLegacySql = checkNotNull(useLegacySql, "useLegacySql"); - this.dryRunJobStats = new AtomicReference<>(); - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - return dryRunQueryIfNeeded(bqOptions).getTotalBytesProcessed(); - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - return new BigQueryReader(this, bqServices.getReaderFromQuery( - bqOptions, query.get(), executingProject.get(), flattenResults, useLegacySql)); - } - - @Override - protected TableReference getTableToExtract(BigQueryOptions bqOptions) - throws IOException, InterruptedException { - // 1. Find the location of the query. - String location = null; - List referencedTables = - dryRunQueryIfNeeded(bqOptions).getQuery().getReferencedTables(); - DatasetService tableService = bqServices.getDatasetService(bqOptions); - if (referencedTables != null && !referencedTables.isEmpty()) { - TableReference queryTable = referencedTables.get(0); - location = tableService.getTable( - queryTable.getProjectId(), - queryTable.getDatasetId(), - queryTable.getTableId()).getLocation(); - } - - // 2. Create the temporary dataset in the query location. - TableReference tableToExtract = - JSON_FACTORY.fromString(jsonQueryTempTable.get(), TableReference.class); - tableService.createDataset( - tableToExtract.getProjectId(), - tableToExtract.getDatasetId(), - location, - "Dataset for BigQuery query job temporary table"); - - // 3. Execute the query. - String queryJobId = jobIdToken + "-query"; - executeQuery( - executingProject.get(), - queryJobId, - tableToExtract, - bqServices.getJobService(bqOptions)); - return tableToExtract; - } - - @Override - protected void cleanupTempResource(BigQueryOptions bqOptions) throws Exception { - checkState(jsonQueryTempTable.isAccessible()); - TableReference tableToRemove = - JSON_FACTORY.fromString(jsonQueryTempTable.get(), TableReference.class); - - DatasetService tableService = bqServices.getDatasetService(bqOptions); - tableService.deleteTable( - tableToRemove.getProjectId(), - tableToRemove.getDatasetId(), - tableToRemove.getTableId()); - tableService.deleteDataset(tableToRemove.getProjectId(), tableToRemove.getDatasetId()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("query", query)); - } - - private synchronized JobStatistics dryRunQueryIfNeeded(BigQueryOptions bqOptions) - throws InterruptedException, IOException { - if (dryRunJobStats.get() == null) { - JobStatistics jobStats = bqServices.getJobService(bqOptions).dryRunQuery( - executingProject.get(), createBasicQueryConfig()); - dryRunJobStats.compareAndSet(null, jobStats); - } - return dryRunJobStats.get(); - } - - private void executeQuery( - String executingProject, - String jobId, - TableReference destinationTable, - JobService jobService) throws IOException, InterruptedException { - JobReference jobRef = new JobReference() - .setProjectId(executingProject) - .setJobId(jobId); - - JobConfigurationQuery queryConfig = createBasicQueryConfig() - .setAllowLargeResults(true) - .setCreateDisposition("CREATE_IF_NEEDED") - .setDestinationTable(destinationTable) - .setPriority("BATCH") - .setWriteDisposition("WRITE_EMPTY"); - - jobService.startQueryJob(jobRef, queryConfig); - Job job = jobService.pollJob(jobRef, JOB_POLL_MAX_RETRIES); - if (parseStatus(job) != Status.SUCCEEDED) { - throw new IOException("Query job failed: " + jobId); - } - } - - private JobConfigurationQuery createBasicQueryConfig() { - return new JobConfigurationQuery() - .setQuery(query.get()) - .setFlattenResults(flattenResults) - .setUseLegacySql(useLegacySql); - } - - private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException { - in.defaultReadObject(); - dryRunJobStats = new AtomicReference<>(); - } - } - - /** - * An abstract {@link BoundedSource} to read a table from BigQuery. - * - *

              This source uses a BigQuery export job to take a snapshot of the table on GCS, and then - * reads in parallel from each produced file. It is implemented by {@link BigQueryTableSource}, - * and {@link BigQueryQuerySource}, depending on the configuration of the read. - * Specifically, - *

                - *
              • {@link BigQueryTableSource} is for reading BigQuery tables
              • - *
              • {@link BigQueryQuerySource} is for querying BigQuery tables
              • - *
              - * ... - */ - private abstract static class BigQuerySourceBase extends BoundedSource { - // The maximum number of retries to verify temp files. - private static final int MAX_FILES_VERIFY_RETRIES = 9; - - // The maximum number of retries to poll a BigQuery job. - protected static final int JOB_POLL_MAX_RETRIES = Integer.MAX_VALUE; - - // The initial backoff for verifying temp files. - private static final Duration INITIAL_FILES_VERIFY_BACKOFF = Duration.standardSeconds(1); - - protected final String jobIdToken; - protected final String extractDestinationDir; - protected final BigQueryServices bqServices; - protected final ValueProvider executingProject; - - private BigQuerySourceBase( - String jobIdToken, - String extractDestinationDir, - BigQueryServices bqServices, - ValueProvider executingProject) { - this.jobIdToken = checkNotNull(jobIdToken, "jobIdToken"); - this.extractDestinationDir = checkNotNull(extractDestinationDir, "extractDestinationDir"); - this.bqServices = checkNotNull(bqServices, "bqServices"); - this.executingProject = checkNotNull(executingProject, "executingProject"); - } - - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - TableReference tableToExtract = getTableToExtract(bqOptions); - JobService jobService = bqServices.getJobService(bqOptions); - String extractJobId = getExtractJobId(jobIdToken); - List tempFiles = executeExtract(extractJobId, tableToExtract, jobService); - - TableSchema tableSchema = bqServices.getDatasetService(bqOptions).getTable( - tableToExtract.getProjectId(), - tableToExtract.getDatasetId(), - tableToExtract.getTableId()).getSchema(); - - cleanupTempResource(bqOptions); - return createSources(tempFiles, tableSchema); - } - - protected abstract TableReference getTableToExtract(BigQueryOptions bqOptions) throws Exception; - - protected abstract void cleanupTempResource(BigQueryOptions bqOptions) throws Exception; - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public void validate() { - // Do nothing, validation is done in BigQuery.Read. - } - - @Override - public Coder getDefaultOutputCoder() { - return TableRowJsonCoder.of(); - } - - private List executeExtract( - String jobId, TableReference table, JobService jobService) - throws InterruptedException, IOException { - JobReference jobRef = new JobReference() - .setProjectId(executingProject.get()) - .setJobId(jobId); - - String destinationUri = getExtractDestinationUri(extractDestinationDir); - JobConfigurationExtract extract = new JobConfigurationExtract() - .setSourceTable(table) - .setDestinationFormat("AVRO") - .setDestinationUris(ImmutableList.of(destinationUri)); - - LOG.info("Starting BigQuery extract job: {}", jobId); - jobService.startExtractJob(jobRef, extract); - Job extractJob = - jobService.pollJob(jobRef, JOB_POLL_MAX_RETRIES); - if (parseStatus(extractJob) != Status.SUCCEEDED) { - throw new IOException(String.format( - "Extract job %s failed, status: %s", - extractJob.getJobReference().getJobId(), extractJob.getStatus())); - } - - List tempFiles = getExtractFilePaths(extractDestinationDir, extractJob); - return ImmutableList.copyOf(tempFiles); - } - - private List> createSources( - List files, TableSchema tableSchema) throws IOException, InterruptedException { - final String jsonSchema = JSON_FACTORY.toString(tableSchema); - - SerializableFunction function = - new SerializableFunction() { - @Override - public TableRow apply(GenericRecord input) { - try { - return AvroUtils.convertGenericRecordToTableRow( - input, JSON_FACTORY.fromString(jsonSchema, TableSchema.class)); - } catch (IOException e) { - throw new RuntimeException("Failed to convert GenericRecord to TableRow", e); - } - }}; - - List> avroSources = Lists.newArrayList(); - for (String fileName : files) { - avroSources.add(new TransformingSource<>( - AvroSource.from(fileName), function, getDefaultOutputCoder())); - } - return ImmutableList.copyOf(avroSources); - } - - protected static class BigQueryReader extends BoundedSource.BoundedReader { - private final BigQuerySourceBase source; - private final BigQueryServices.BigQueryJsonReader reader; - - private BigQueryReader( - BigQuerySourceBase source, BigQueryServices.BigQueryJsonReader reader) { - this.source = source; - this.reader = reader; - } - - @Override - public BoundedSource getCurrentSource() { - return source; - } - - @Override - public boolean start() throws IOException { - return reader.start(); - } - - @Override - public boolean advance() throws IOException { - return reader.advance(); - } - - @Override - public TableRow getCurrent() throws NoSuchElementException { - return reader.getCurrent(); - } - - @Override - public void close() throws IOException { - reader.close(); - } - } - } - - /** - * A {@link BoundedSource} that reads from {@code BoundedSource} - * and transforms elements to type {@code V}. - */ - @VisibleForTesting - static class TransformingSource extends BoundedSource { - private final BoundedSource boundedSource; - private final SerializableFunction function; - private final Coder outputCoder; - - TransformingSource( - BoundedSource boundedSource, - SerializableFunction function, - Coder outputCoder) { - this.boundedSource = checkNotNull(boundedSource, "boundedSource"); - this.function = checkNotNull(function, "function"); - this.outputCoder = checkNotNull(outputCoder, "outputCoder"); - } - - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - return Lists.transform( - boundedSource.splitIntoBundles(desiredBundleSizeBytes, options), - new Function, BoundedSource>() { - @Override - public BoundedSource apply(BoundedSource input) { - return new TransformingSource<>(input, function, outputCoder); - } - }); - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return boundedSource.getEstimatedSizeBytes(options); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return boundedSource.producesSortedKeys(options); - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return new TransformingReader(boundedSource.createReader(options)); - } - - @Override - public void validate() { - boundedSource.validate(); - } - - @Override - public Coder getDefaultOutputCoder() { - return outputCoder; - } - - private class TransformingReader extends BoundedReader { - private final BoundedReader boundedReader; - - private TransformingReader(BoundedReader boundedReader) { - this.boundedReader = checkNotNull(boundedReader, "boundedReader"); - } - - @Override - public synchronized BoundedSource getCurrentSource() { - return new TransformingSource<>(boundedReader.getCurrentSource(), function, outputCoder); - } - - @Override - public boolean start() throws IOException { - return boundedReader.start(); - } - - @Override - public boolean advance() throws IOException { - return boundedReader.advance(); - } - - @Override - public V getCurrent() throws NoSuchElementException { - T current = boundedReader.getCurrent(); - return function.apply(current); - } - - @Override - public void close() throws IOException { - boundedReader.close(); - } - - @Override - public synchronized BoundedSource splitAtFraction(double fraction) { - BoundedSource split = boundedReader.splitAtFraction(fraction); - return split == null ? null : new TransformingSource<>(split, function, outputCoder); - } - - @Override - public Double getFractionConsumed() { - return boundedReader.getFractionConsumed(); - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - return boundedReader.getCurrentTimestamp(); - } - } - } - - private static String getExtractJobId(String jobIdToken) { - return jobIdToken + "-extract"; - } - - private static String getExtractDestinationUri(String extractDestinationDir) { - return String.format("%s/%s", extractDestinationDir, "*.avro"); - } - - private static List getExtractFilePaths(String extractDestinationDir, Job extractJob) - throws IOException { - JobStatistics jobStats = extractJob.getStatistics(); - List counts = jobStats.getExtract().getDestinationUriFileCounts(); - if (counts.size() != 1) { - String errorMessage = (counts.size() == 0 - ? "No destination uri file count received." - : String.format("More than one destination uri file count received. First two are %s, %s", - counts.get(0), counts.get(1))); - throw new RuntimeException(errorMessage); - } - long filesCount = counts.get(0); - - ImmutableList.Builder paths = ImmutableList.builder(); - IOChannelFactory factory = IOChannelUtils.getFactory(extractDestinationDir); - for (long i = 0; i < filesCount; ++i) { - String filePath = - factory.resolve(extractDestinationDir, String.format("%012d%s", i, ".avro")); - paths.add(filePath); - } - return paths.build(); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@link PTransform} that writes a {@link PCollection} containing {@link TableRow TableRows} - * to a BigQuery table. - * - *

              In BigQuery, each table has an encosing dataset. The dataset being written must already - * exist. - * - *

              By default, tables will be created if they do not exist, which corresponds to a - * {@link CreateDisposition#CREATE_IF_NEEDED} disposition that matches the default of BigQuery's - * Jobs API. A schema must be provided (via {@link BigQueryIO.Write#withSchema(TableSchema)}), - * or else the transform may fail at runtime with an {@link IllegalArgumentException}. - * - *

              By default, writes require an empty table, which corresponds to - * a {@link WriteDisposition#WRITE_EMPTY} disposition that matches the - * default of BigQuery's Jobs API. - * - *

              Here is a sample transform that produces TableRow values containing - * "word" and "count" columns: - *

              {@code
              -   * static class FormatCountsFn extends DoFn, TableRow> {
              -   *   public void processElement(ProcessContext c) {
              -   *     TableRow row = new TableRow()
              -   *         .set("word", c.element().getKey())
              -   *         .set("count", c.element().getValue().intValue());
              -   *     c.output(row);
              -   *   }
              -   * }}
              - */ - public static class Write { - /** - * An enumeration type for the BigQuery create disposition strings. - * - * @see - * configuration.query.createDisposition in the BigQuery Jobs API - */ - public enum CreateDisposition { - /** - * Specifics that tables should not be created. - * - *

              If the output table does not exist, the write fails. - */ - CREATE_NEVER, - - /** - * Specifies that tables should be created if needed. This is the default - * behavior. - * - *

              Requires that a table schema is provided via {@link BigQueryIO.Write#withSchema}. - * This precondition is checked before starting a job. The schema is - * not required to match an existing table's schema. - * - *

              When this transformation is executed, if the output table does not - * exist, the table is created from the provided schema. Note that even if - * the table exists, it may be recreated if necessary when paired with a - * {@link WriteDisposition#WRITE_TRUNCATE}. - */ - CREATE_IF_NEEDED - } - - /** - * An enumeration type for the BigQuery write disposition strings. - * - * @see - * configuration.query.writeDisposition in the BigQuery Jobs API - */ - public enum WriteDisposition { - /** - * Specifies that write should replace a table. - * - *

              The replacement may occur in multiple steps - for instance by first - * removing the existing table, then creating a replacement, then filling - * it in. This is not an atomic operation, and external programs may - * see the table in any of these intermediate steps. - */ - WRITE_TRUNCATE, - - /** - * Specifies that rows may be appended to an existing table. - */ - WRITE_APPEND, - - /** - * Specifies that the output table must be empty. This is the default - * behavior. - * - *

              If the output table is not empty, the write fails at runtime. - * - *

              This check may occur long before data is written, and does not - * guarantee exclusive access to the table. If two programs are run - * concurrently, each specifying the same output table and - * a {@link WriteDisposition} of {@link WriteDisposition#WRITE_EMPTY}, it is possible - * for both to succeed. - */ - WRITE_EMPTY - } - - /** - * Creates a write transformation with the given transform name. The BigQuery table to be - * written has not yet been configured. - */ - public static Bound named(String name) { - return new Bound().named(name); - } - - /** - * Creates a write transformation for the given table specification. - * - *

              Refer to {@link #parseTableSpec(String)} for the specification format. - */ - public static Bound to(String tableSpec) { - return new Bound().to(tableSpec); - } - - /** Creates a write transformation for the given table. */ - public static Bound to(ValueProvider tableSpec) { - return new Bound().to(tableSpec); - } - - /** Creates a write transformation for the given table. */ - public static Bound to(TableReference table) { - return new Bound().to(table); - } - - /** - * Creates a write transformation from a function that maps windows to table specifications. - * Each time a new window is encountered, this function will be called and the resulting table - * will be created. Records within that window will be written to the associated table. - * - *

              See {@link #parseTableSpec(String)} for the format that {@code tableSpecFunction} should - * return. - * - *

              {@code tableSpecFunction} should be deterministic. When given the same window, it should - * always return the same table specification. - */ - public static Bound to(SerializableFunction tableSpecFunction) { - return new Bound().to(tableSpecFunction); - } - - /** - * Creates a write transformation from a function that maps windows to {@link TableReference} - * objects. - * - *

              {@code tableRefFunction} should be deterministic. When given the same window, it should - * always return the same table reference. - */ - public static Bound toTableReference( - SerializableFunction tableRefFunction) { - return new Bound().toTableReference(tableRefFunction); - } - - /** - * Creates a write transformation with the specified schema to use in table creation. - * - *

              The schema is required only if writing to a table that does not already - * exist, and {@link CreateDisposition} is set to - * {@link CreateDisposition#CREATE_IF_NEEDED}. - */ - public static Bound withSchema(TableSchema schema) { - return new Bound().withSchema(schema); - } - - /** - * Like {@link #withSchema(TableSchema)}, but with a {@link ValueProvider}. - */ - public static Bound withSchema(ValueProvider schema) { - return new Bound().withSchema(schema); - } - - /** Creates a write transformation with the specified options for creating the table. */ - public static Bound withCreateDisposition(CreateDisposition disposition) { - return new Bound().withCreateDisposition(disposition); - } - - /** Creates a write transformation with the specified options for writing to the table. */ - public static Bound withWriteDisposition(WriteDisposition disposition) { - return new Bound().withWriteDisposition(disposition); - } - - /** - * Creates a write transformation with BigQuery table validation disabled. - */ - public static Bound withoutValidation() { - return new Bound().withoutValidation(); - } - - /** - * A {@link PTransform} that can write either a bounded or unbounded - * {@link PCollection} of {@link TableRow TableRows} to a BigQuery table. - */ - public static class Bound extends PTransform, PDone> { - // Maximum number of files in a single partition. - static final int MAX_NUM_FILES = 10000; - - // Maximum number of bytes in a single partition -- 11 TiB just under BQ's 12 TiB limit. - static final long MAX_SIZE_BYTES = 11 * (1L << 40); - - // The maximum number of retry jobs. - static final int MAX_RETRY_JOBS = 3; - - // The maximum number of retries to poll the status of a job. - // It sets to {@code Integer.MAX_VALUE} to block until the BigQuery job finishes. - static final int LOAD_JOB_POLL_MAX_RETRIES = Integer.MAX_VALUE; - - @Nullable final ValueProvider jsonTableRef; - - @Nullable final SerializableFunction tableRefFunction; - - // Table schema. The schema is required only if the table does not exist. - @Nullable final ValueProvider jsonSchema; - - // Options for creating the table. Valid values are CREATE_IF_NEEDED and - // CREATE_NEVER. - final CreateDisposition createDisposition; - - // Options for writing to the table. Valid values are WRITE_TRUNCATE, - // WRITE_APPEND and WRITE_EMPTY. - final WriteDisposition writeDisposition; - - // An option to indicate if table validation is desired. Default is true. - final boolean validate; - - @Nullable private BigQueryServices bigQueryServices; - - private static class TranslateTableSpecFunction implements - SerializableFunction { - private SerializableFunction tableSpecFunction; - - TranslateTableSpecFunction(SerializableFunction tableSpecFunction) { - this.tableSpecFunction = tableSpecFunction; - } - - @Override - public TableReference apply(BoundedWindow value) { - return parseTableSpec(tableSpecFunction.apply(value)); - } - } - - /** - * @deprecated Should be private. Instead, use one of the factory methods in - * {@link BigQueryIO.Write}, such as {@link BigQueryIO.Write#to(String)}, to create an - * instance of this class. - */ - @Deprecated - public Bound() { - this( - null /* name */, - null /* jsonTableRef */, - null /* tableRefFunction */, - null /* jsonSchema */, - CreateDisposition.CREATE_IF_NEEDED, - WriteDisposition.WRITE_EMPTY, - true /* validate */, - null /* bigQueryServices */); - } - - private Bound(String name, @Nullable ValueProvider jsonTableRef, - @Nullable SerializableFunction tableRefFunction, - @Nullable ValueProvider jsonSchema, - CreateDisposition createDisposition, WriteDisposition writeDisposition, boolean validate, - @Nullable BigQueryServices bigQueryServices) { - super(name); - this.jsonTableRef = jsonTableRef; - this.tableRefFunction = tableRefFunction; - this.jsonSchema = jsonSchema; - this.createDisposition = checkNotNull(createDisposition, "createDisposition"); - this.writeDisposition = checkNotNull(writeDisposition, "writeDisposition"); - this.validate = validate; - this.bigQueryServices = bigQueryServices; - } - - /** - * Returns a copy of this write transformation, but with the specified transform name. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, bigQueryServices); - } - - /** - * Returns a copy of this write transformation, but writing to the specified table. Refer to - * {@link #parseTableSpec(String)} for the specification format. - * - *

              Does not modify this object. - */ - public Bound to(String tableSpec) { - return toTableRef(NestedValueProvider.of( - StaticValueProvider.of(tableSpec), new TableSpecToTableRef())); - } - - /** - * Returns a copy of this write transformation, but writing to the specified table. - * - *

              Does not modify this object. - */ - public Bound to(TableReference table) { - return to(StaticValueProvider.of(toTableSpec(table))); - } - - /** - * Returns a copy of this write transformation, but using the specified function to determine - * which table to write to for each window. - * - *

              Does not modify this object. - * - *

              {@code tableSpecFunction} should be deterministic. When given the same window, it - * should always return the same table specification. - */ - public Bound to( - SerializableFunction tableSpecFunction) { - return toTableReference(new TranslateTableSpecFunction(tableSpecFunction)); - } - - /** - * Returns a copy of this write transformation, but writing to the specified table. Refer to - * {@link #parseTableSpec(String)} for the specification format. - * - *

              Does not modify this object. - */ - public Bound to(ValueProvider tableSpec) { - return toTableRef(NestedValueProvider.of(tableSpec, new TableSpecToTableRef())); - } - - /** - * Returns a copy of this write transformation, but writing to the specified table. - * - *

              Does not modify this object. - */ - private Bound toTableRef(ValueProvider table) { - return new Bound(name, - NestedValueProvider.of(table, new TableRefToJson()), - tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, bigQueryServices); - } - - /** - * Returns a copy of this write transformation, but using the specified function to determine - * which table to write to for each window. - * - *

              Does not modify this object. - * - *

              {@code tableRefFunction} should be deterministic. When given the same window, it should - * always return the same table reference. - */ - public Bound toTableReference( - SerializableFunction tableRefFunction) { - return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, bigQueryServices); - } - - /** - * Returns a copy of this write transformation, but using the specified schema for rows - * to be written. - * - *

              Does not modify this object. - */ - public Bound withSchema(TableSchema schema) { - return new Bound(name, jsonTableRef, tableRefFunction, - StaticValueProvider.of(toJsonString(schema)), - createDisposition, writeDisposition, validate, bigQueryServices); - } - - /** - * Like {@link #withSchema(TableSchema)}, but with a {@link ValueProvider}. - */ - public Bound withSchema(ValueProvider schema) { - return new Bound(name, jsonTableRef, tableRefFunction, - NestedValueProvider.of(schema, new TableSchemaToJsonSchema()), - createDisposition, writeDisposition, validate, bigQueryServices); - } - - /** - * Returns a copy of this write transformation, but using the specified create disposition. - * - *

              Does not modify this object. - */ - public Bound withCreateDisposition(CreateDisposition createDisposition) { - return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, bigQueryServices); - } - - /** - * Returns a copy of this write transformation, but using the specified write disposition. - * - *

              Does not modify this object. - */ - public Bound withWriteDisposition(WriteDisposition writeDisposition) { - return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, bigQueryServices); - } - - /** - * Returns a copy of this write transformation, but without BigQuery table validation. - * - *

              Does not modify this object. - */ - public Bound withoutValidation() { - return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, false, bigQueryServices); - } - - @VisibleForTesting - Bound withTestServices(BigQueryServices testServices) { - return new Bound(name, jsonTableRef, tableRefFunction, jsonSchema, createDisposition, - writeDisposition, validate, testServices); - } - - private static void verifyTableEmpty( - BigQueryOptions options, - TableReference table) { - try { - Bigquery client = Transport.newBigQueryClient(options).build(); - BigQueryTableInserter inserter = new BigQueryTableInserter(client); - if (!inserter.isEmpty(table)) { - throw new IllegalArgumentException( - "BigQuery table is not empty: " + BigQueryIO.toTableSpec(table)); - } - } catch (IOException e) { - ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); - if (errorExtractor.itemNotFound(e)) { - // Nothing to do. If the table does not exist, it is considered empty. - } else { - throw new RuntimeException( - "unable to confirm BigQuery table emptiness for table " - + BigQueryIO.toTableSpec(table), e); - } - } - } - - @Override - public void validate(PCollection input) { - BigQueryOptions options = input.getPipeline().getOptions().as(BigQueryOptions.class); - - // Exactly one of the table and table reference can be configured. - checkState( - jsonTableRef != null || tableRefFunction != null, - "must set the table reference of a BigQueryIO.Write transform"); - checkState( - jsonTableRef == null || tableRefFunction == null, - "Cannot set both a table reference and a table function for a BigQueryIO.Write" - + " transform"); - - // Require a schema if creating one or more tables. - checkArgument( - createDisposition != CreateDisposition.CREATE_IF_NEEDED || jsonSchema != null, - "CreateDisposition is CREATE_IF_NEEDED, however no schema was provided."); - - // The user specified a table. - if (jsonTableRef != null && validate) { - TableReference table = getTableWithDefaultProject(options).get(); - - // Check for destination table presence and emptiness for early failure notification. - // Note that a presence check can fail when the table or dataset is created by an earlier - // stage of the pipeline. For these cases the #withoutValidation method can be used to - // disable the check. - verifyDatasetPresence(options, table); - if (getCreateDisposition() == BigQueryIO.Write.CreateDisposition.CREATE_NEVER) { - verifyTablePresence(options, table); - } - if (getWriteDisposition() == BigQueryIO.Write.WriteDisposition.WRITE_EMPTY) { - verifyTableEmpty(options, table); - } - } - - if (options.isStreaming() || tableRefFunction != null) { - // We will use BigQuery's streaming write API -- validate supported dispositions. - checkArgument( - createDisposition != CreateDisposition.CREATE_NEVER, - "CreateDisposition.CREATE_NEVER is not supported for an unbounded PCollection or when" - + " using a tablespec function."); - - checkArgument( - writeDisposition != WriteDisposition.WRITE_TRUNCATE, - "WriteDisposition.WRITE_TRUNCATE is not supported for an unbounded PCollection or" - + " when using a tablespec function."); - } else { - // We will use a BigQuery load job -- validate the temp location. - String tempLocation = options.getTempLocation(); - checkArgument( - !Strings.isNullOrEmpty(tempLocation), - "BigQueryIO.Write needs a GCS temp location to store temp files."); - if (bigQueryServices == null) { - try { - GcsPath.fromUri(tempLocation); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException( - String.format( - "BigQuery temp location expected a valid 'gs://' path, but was given '%s'", - tempLocation), - e); - } - } - } - } - - @Override - public PDone apply(PCollection input) { - Pipeline p = input.getPipeline(); - BigQueryOptions options = p.getOptions().as(BigQueryOptions.class); - BigQueryServices bqServices = getBigQueryServices(); - - // In a streaming job, or when a tablespec function is defined, we use StreamWithDeDup - // and BigQuery's streaming import API. - if (options.isStreaming() || tableRefFunction != null) { - return input.apply(new StreamWithDeDup(getTable(), tableRefFunction, - NestedValueProvider.of(jsonSchema, new JsonSchemaToTableSchema()))); - - } - - ValueProvider table = getTableWithDefaultProject(options); - - String jobIdToken = "beam_job_" + randomUUIDString(); - String tempLocation = options.getTempLocation(); - String tempFilePrefix; - try { - IOChannelFactory factory = IOChannelUtils.getFactory(tempLocation); - tempFilePrefix = factory.resolve( - factory.resolve(tempLocation, "BigQueryWriteTemp"), - jobIdToken); - } catch (IOException e) { - throw new RuntimeException( - String.format("Failed to resolve BigQuery temp location in %s", tempLocation), - e); - } - - PCollection singleton = p.apply("Create", Create.of(tempFilePrefix)); - - PCollection inputInGlobalWindow = - input.apply( - Window.into(new GlobalWindows()) - .triggering(DefaultTrigger.of()) - .discardingFiredPanes()); - - PCollection> results = inputInGlobalWindow - .apply("WriteBundles", - ParDo.of(new WriteBundles(tempFilePrefix))); - - TupleTag>> multiPartitionsTag = - new TupleTag>>("multiPartitionsTag") {}; - TupleTag>> singlePartitionTag = - new TupleTag>>("singlePartitionTag") {}; - - PCollectionView>> resultsView = results - .apply("ResultsView", View.>asIterable()); - PCollectionTuple partitions = singleton.apply(ParDo - .of(new WritePartition( - resultsView, - multiPartitionsTag, - singlePartitionTag)) - .withSideInputs(resultsView) - .withOutputTags(multiPartitionsTag, TupleTagList.of(singlePartitionTag))); - - // Write multiple partitions to separate temporary tables - PCollection tempTables = partitions.get(multiPartitionsTag) - .apply("MultiPartitionsGroupByKey", GroupByKey.>create()) - .apply("MultiPartitionsWriteTables", ParDo.of(new WriteTables( - false, - bqServices, - jobIdToken, - tempFilePrefix, - NestedValueProvider.of(table, new TableRefToJson()), - jsonSchema, - WriteDisposition.WRITE_EMPTY, - CreateDisposition.CREATE_IF_NEEDED))); - - PCollectionView> tempTablesView = tempTables - .apply("TempTablesView", View.asIterable()); - singleton.apply(ParDo - .of(new WriteRename( - bqServices, - jobIdToken, - NestedValueProvider.of(table, new TableRefToJson()), - writeDisposition, - createDisposition, - tempTablesView)) - .withSideInputs(tempTablesView)); - - // Write single partition to final table - partitions.get(singlePartitionTag) - .apply("SinglePartitionGroupByKey", GroupByKey.>create()) - .apply("SinglePartitionWriteTables", ParDo.of(new WriteTables( - true, - bqServices, - jobIdToken, - tempFilePrefix, - NestedValueProvider.of(table, new TableRefToJson()), - jsonSchema, - writeDisposition, - createDisposition))); - - return PDone.in(input.getPipeline()); - } - - private class WriteBundles extends DoFn> { - private TableRowWriter writer = null; - private final String tempFilePrefix; - - WriteBundles(String tempFilePrefix) { - this.tempFilePrefix = tempFilePrefix; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - if (writer == null) { - writer = new TableRowWriter(tempFilePrefix); - writer.open(UUID.randomUUID().toString()); - LOG.debug("Done opening writer {}", writer); - } - try { - writer.write(c.element()); - } catch (Exception e) { - // Discard write result and close the write. - try { - writer.close(); - // The writer does not need to be reset, as this OldDoFn cannot be reused. - } catch (Exception closeException) { - // Do not mask the exception that caused the write to fail. - e.addSuppressed(closeException); - } - throw e; - } - } - - @Override - public void finishBundle(Context c) throws Exception { - if (writer != null) { - c.output(writer.close()); - writer = null; - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .addIfNotNull(DisplayData.item("tempFilePrefix", tempFilePrefix) - .withLabel("Temporary File Prefix")); - } - } - - @Override - protected Coder getDefaultOutputCoder() { - return VoidCoder.of(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .addIfNotNull(DisplayData.item("table", jsonTableRef) - .withLabel("Table Reference")) - .addIfNotNull(DisplayData.item("schema", jsonSchema) - .withLabel("Table Schema")); - - if (tableRefFunction != null) { - builder.add(DisplayData.item("tableFn", tableRefFunction.getClass()) - .withLabel("Table Reference Function")); - } - - builder - .add(DisplayData.item("createDisposition", createDisposition.toString()) - .withLabel("Table CreateDisposition")) - .add(DisplayData.item("writeDisposition", writeDisposition.toString()) - .withLabel("Table WriteDisposition")) - .addIfNotDefault(DisplayData.item("validation", validate) - .withLabel("Validation Enabled"), true); - } - - /** Returns the create disposition. */ - public CreateDisposition getCreateDisposition() { - return createDisposition; - } - - /** Returns the write disposition. */ - public WriteDisposition getWriteDisposition() { - return writeDisposition; - } - - /** Returns the table schema. */ - public TableSchema getSchema() { - return fromJsonString( - jsonSchema == null ? null : jsonSchema.get(), TableSchema.class); - } - - /** - * Returns the table to write, or {@code null} if writing with {@code tableRefFunction}. - * - *

              If the table's project is not specified, use the executing project. - */ - @Nullable private ValueProvider getTableWithDefaultProject( - BigQueryOptions bqOptions) { - ValueProvider table = getTable(); - if (table == null) { - return table; - } - if (!table.isAccessible()) { - LOG.info("Using a dynamic value for table input. This must contain a project" - + " in the table reference: {}", table); - return table; - } - if (Strings.isNullOrEmpty(table.get().getProjectId())) { - // If user does not specify a project we assume the table to be located in - // the default project. - TableReference tableRef = table.get(); - tableRef.setProjectId(bqOptions.getProject()); - return NestedValueProvider.of(StaticValueProvider.of( - toJsonString(tableRef)), new JsonTableRefToTableRef()); - } - return table; - } - - /** Returns the table reference, or {@code null}. */ - @Nullable - public ValueProvider getTable() { - return jsonTableRef == null - ? null : NestedValueProvider.of(jsonTableRef, new JsonTableRefToTableRef()); - } - - /** Returns {@code true} if table validation is enabled. */ - public boolean getValidate() { - return validate; - } - - private BigQueryServices getBigQueryServices() { - if (bigQueryServices == null) { - bigQueryServices = new BigQueryServicesImpl(); - } - return bigQueryServices; - } - } - - static class TableRowWriter { - private static final Coder CODER = TableRowJsonCoder.of(); - private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); - private final String tempFilePrefix; - private String id; - private String fileName; - private WritableByteChannel channel; - protected String mimeType = MimeTypes.TEXT; - private CountingOutputStream out; - - TableRowWriter(String basename) { - this.tempFilePrefix = basename; - } - - public final void open(String uId) throws Exception { - id = uId; - fileName = tempFilePrefix + id; - LOG.debug("Opening {}.", fileName); - channel = IOChannelUtils.create(fileName, mimeType); - try { - out = new CountingOutputStream(Channels.newOutputStream(channel)); - LOG.debug("Writing header to {}.", fileName); - } catch (Exception e) { - try { - LOG.error("Writing header to {} failed, closing channel.", fileName); - channel.close(); - } catch (IOException closeException) { - LOG.error("Closing channel for {} failed", fileName); - } - throw e; - } - LOG.debug("Starting write of bundle {} to {}.", this.id, fileName); - } - - public void write(TableRow value) throws Exception { - CODER.encode(value, out, Context.OUTER); - out.write(NEWLINE); - } - - public final KV close() throws IOException { - channel.close(); - return KV.of(fileName, out.getCount()); - } - } - - /** - * Partitions temporary files based on number of files and file sizes. - */ - static class WritePartition extends DoFn>> { - private final PCollectionView>> resultsView; - private TupleTag>> multiPartitionsTag; - private TupleTag>> singlePartitionTag; - - public WritePartition( - PCollectionView>> resultsView, - TupleTag>> multiPartitionsTag, - TupleTag>> singlePartitionTag) { - this.resultsView = resultsView; - this.multiPartitionsTag = multiPartitionsTag; - this.singlePartitionTag = singlePartitionTag; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - List> results = Lists.newArrayList(c.sideInput(resultsView)); - if (results.isEmpty()) { - TableRowWriter writer = new TableRowWriter(c.element()); - writer.open(UUID.randomUUID().toString()); - results.add(writer.close()); - } - - long partitionId = 0; - int currNumFiles = 0; - long currSizeBytes = 0; - List currResults = Lists.newArrayList(); - for (int i = 0; i < results.size(); ++i) { - KV fileResult = results.get(i); - if (currNumFiles + 1 > Bound.MAX_NUM_FILES - || currSizeBytes + fileResult.getValue() > Bound.MAX_SIZE_BYTES) { - c.sideOutput(multiPartitionsTag, KV.of(++partitionId, currResults)); - currResults = Lists.newArrayList(); - currNumFiles = 0; - currSizeBytes = 0; - } - ++currNumFiles; - currSizeBytes += fileResult.getValue(); - currResults.add(fileResult.getKey()); - } - if (partitionId == 0) { - c.sideOutput(singlePartitionTag, KV.of(++partitionId, currResults)); - } else { - c.sideOutput(multiPartitionsTag, KV.of(++partitionId, currResults)); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - } - } - - /** - * Writes partitions to BigQuery tables. - */ - static class WriteTables extends DoFn>>, String> { - private final boolean singlePartition; - private final BigQueryServices bqServices; - private final String jobIdToken; - private final String tempFilePrefix; - private final ValueProvider jsonTableRef; - private final ValueProvider jsonSchema; - private final WriteDisposition writeDisposition; - private final CreateDisposition createDisposition; - - public WriteTables( - boolean singlePartition, - BigQueryServices bqServices, - String jobIdToken, - String tempFilePrefix, - ValueProvider jsonTableRef, - ValueProvider jsonSchema, - WriteDisposition writeDisposition, - CreateDisposition createDisposition) { - this.singlePartition = singlePartition; - this.bqServices = bqServices; - this.jobIdToken = jobIdToken; - this.tempFilePrefix = tempFilePrefix; - this.jsonTableRef = jsonTableRef; - this.jsonSchema = jsonSchema; - this.writeDisposition = writeDisposition; - this.createDisposition = createDisposition; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - List partition = Lists.newArrayList(c.element().getValue()).get(0); - String jobIdPrefix = String.format(jobIdToken + "_%05d", c.element().getKey()); - TableReference ref = fromJsonString(jsonTableRef.get(), TableReference.class); - if (!singlePartition) { - ref.setTableId(jobIdPrefix); - } - - load( - bqServices.getJobService(c.getPipelineOptions().as(BigQueryOptions.class)), - jobIdPrefix, - ref, - fromJsonString( - jsonSchema == null ? null : jsonSchema.get(), TableSchema.class), - partition, - writeDisposition, - createDisposition); - c.output(toJsonString(ref)); - - removeTemporaryFiles(c.getPipelineOptions(), tempFilePrefix, partition); - } - - private void load( - JobService jobService, - String jobIdPrefix, - TableReference ref, - @Nullable TableSchema schema, - List gcsUris, - WriteDisposition writeDisposition, - CreateDisposition createDisposition) throws InterruptedException, IOException { - JobConfigurationLoad loadConfig = new JobConfigurationLoad() - .setDestinationTable(ref) - .setSchema(schema) - .setSourceUris(gcsUris) - .setWriteDisposition(writeDisposition.name()) - .setCreateDisposition(createDisposition.name()) - .setSourceFormat("NEWLINE_DELIMITED_JSON"); - - String projectId = ref.getProjectId(); - for (int i = 0; i < Bound.MAX_RETRY_JOBS; ++i) { - String jobId = jobIdPrefix + "-" + i; - LOG.info("Starting BigQuery load job {}: try {}/{}", jobId, i, Bound.MAX_RETRY_JOBS); - JobReference jobRef = new JobReference() - .setProjectId(projectId) - .setJobId(jobId); - jobService.startLoadJob(jobRef, loadConfig); - Status jobStatus = - parseStatus(jobService.pollJob(jobRef, Bound.LOAD_JOB_POLL_MAX_RETRIES)); - switch (jobStatus) { - case SUCCEEDED: - return; - case UNKNOWN: - throw new RuntimeException("Failed to poll the load job status of job " + jobId); - case FAILED: - LOG.info("BigQuery load job failed: {}", jobId); - continue; - default: - throw new IllegalStateException(String.format("Unexpected job status: %s of job %s", - jobStatus, jobId)); - } - } - throw new RuntimeException(String.format("Failed to create the load job %s, reached max " - + "retries: %d", jobIdPrefix, Bound.MAX_RETRY_JOBS)); - } - - static void removeTemporaryFiles( - PipelineOptions options, - String tempFilePrefix, - Collection files) - throws IOException { - IOChannelFactory factory = IOChannelUtils.getFactory(tempFilePrefix); - if (factory instanceof GcsIOChannelFactory) { - GcsUtil gcsUtil = new GcsUtil.GcsUtilFactory().create(options); - gcsUtil.remove(files); - } else if (factory instanceof FileIOChannelFactory) { - for (String filename : files) { - LOG.debug("Removing file {}", filename); - boolean exists = Files.deleteIfExists(Paths.get(filename)); - if (!exists) { - LOG.debug("{} does not exist.", filename); - } - } - } else { - throw new IOException("Unrecognized file system."); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .addIfNotNull(DisplayData.item("jobIdToken", jobIdToken) - .withLabel("Job ID Token")) - .addIfNotNull(DisplayData.item("tempFilePrefix", tempFilePrefix) - .withLabel("Temporary File Prefix")) - .addIfNotNull(DisplayData.item("jsonTableRef", jsonTableRef) - .withLabel("Table Reference")) - .addIfNotNull(DisplayData.item("jsonSchema", jsonSchema) - .withLabel("Table Schema")); - } - } - - /** - * Copies temporary tables to destination table. - */ - static class WriteRename extends DoFn { - private final BigQueryServices bqServices; - private final String jobIdToken; - private final ValueProvider jsonTableRef; - private final WriteDisposition writeDisposition; - private final CreateDisposition createDisposition; - private final PCollectionView> tempTablesView; - - public WriteRename( - BigQueryServices bqServices, - String jobIdToken, - ValueProvider jsonTableRef, - WriteDisposition writeDisposition, - CreateDisposition createDisposition, - PCollectionView> tempTablesView) { - this.bqServices = bqServices; - this.jobIdToken = jobIdToken; - this.jsonTableRef = jsonTableRef; - this.writeDisposition = writeDisposition; - this.createDisposition = createDisposition; - this.tempTablesView = tempTablesView; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - List tempTablesJson = Lists.newArrayList(c.sideInput(tempTablesView)); - - // Do not copy if no temp tables are provided - if (tempTablesJson.size() == 0) { - return; - } - - List tempTables = Lists.newArrayList(); - for (String table : tempTablesJson) { - tempTables.add(fromJsonString(table, TableReference.class)); - } - copy( - bqServices.getJobService(c.getPipelineOptions().as(BigQueryOptions.class)), - jobIdToken, - fromJsonString(jsonTableRef.get(), TableReference.class), - tempTables, - writeDisposition, - createDisposition); - - DatasetService tableService = - bqServices.getDatasetService(c.getPipelineOptions().as(BigQueryOptions.class)); - removeTemporaryTables(tableService, tempTables); - } - - private void copy( - JobService jobService, - String jobIdPrefix, - TableReference ref, - List tempTables, - WriteDisposition writeDisposition, - CreateDisposition createDisposition) throws InterruptedException, IOException { - JobConfigurationTableCopy copyConfig = new JobConfigurationTableCopy() - .setSourceTables(tempTables) - .setDestinationTable(ref) - .setWriteDisposition(writeDisposition.name()) - .setCreateDisposition(createDisposition.name()); - - String projectId = ref.getProjectId(); - for (int i = 0; i < Bound.MAX_RETRY_JOBS; ++i) { - String jobId = jobIdPrefix + "-" + i; - LOG.info("Starting BigQuery copy job {}: try {}/{}", jobId, i, Bound.MAX_RETRY_JOBS); - JobReference jobRef = new JobReference() - .setProjectId(projectId) - .setJobId(jobId); - jobService.startCopyJob(jobRef, copyConfig); - Status jobStatus = - parseStatus(jobService.pollJob(jobRef, Bound.LOAD_JOB_POLL_MAX_RETRIES)); - switch (jobStatus) { - case SUCCEEDED: - return; - case UNKNOWN: - throw new RuntimeException("Failed to poll the copy job status of job " + jobId); - case FAILED: - LOG.info("BigQuery copy job failed: {}", jobId); - continue; - default: - throw new IllegalStateException(String.format("Unexpected job status: %s of job %s", - jobStatus, jobId)); - } - } - throw new RuntimeException(String.format("Failed to create the copy job %s, reached max " - + "retries: %d", jobIdPrefix, Bound.MAX_RETRY_JOBS)); - } - - static void removeTemporaryTables(DatasetService tableService, - List tempTables) throws Exception { - for (TableReference tableRef : tempTables) { - try { - LOG.debug("Deleting table {}", toJsonString(tableRef)); - tableService.deleteTable( - tableRef.getProjectId(), - tableRef.getDatasetId(), - tableRef.getTableId()); - } catch (Exception e) { - LOG.warn("Failed to delete the table {}", toJsonString(tableRef), e); - } - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .addIfNotNull(DisplayData.item("jobIdToken", jobIdToken) - .withLabel("Job ID Token")) - .addIfNotNull(DisplayData.item("jsonTableRef", jsonTableRef) - .withLabel("Table Reference")) - .add(DisplayData.item("writeDisposition", writeDisposition.toString()) - .withLabel("Write Disposition")) - .add(DisplayData.item("createDisposition", createDisposition.toString()) - .withLabel("Create Disposition")); - } - } - - /** Disallow construction of utility class. */ - private Write() {} - } - - private static void verifyDatasetPresence(BigQueryOptions options, TableReference table) { - String resourceNotFoundMsg = - String.format(RESOURCE_NOT_FOUND_ERROR, "dataset", BigQueryIO.toTableSpec(table)); - try { - Bigquery client = Transport.newBigQueryClient(options).build(); - BigQueryTableRowIterator.executeWithBackOff( - client.datasets().get(table.getProjectId(), table.getDatasetId()), - resourceNotFoundMsg); - } catch (Exception e) { - ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); - if ((e instanceof IOException) && errorExtractor.itemNotFound((IOException) e)) { - throw new IllegalArgumentException(resourceNotFoundMsg, e); - } else { - throw new RuntimeException( - String.format(UNABLE_TO_CONFIRM_PRESENCE_OF_RESOURCE_ERROR, "dataset", - BigQueryIO.toTableSpec(table)), - e); - } - } - } - - private static void verifyTablePresence(BigQueryOptions options, TableReference table) { - String resourceNotFoundMsg = - String.format(RESOURCE_NOT_FOUND_ERROR, "table", BigQueryIO.toTableSpec(table)); - try { - Bigquery client = Transport.newBigQueryClient(options).build(); - BigQueryTableRowIterator.executeWithBackOff( - client.tables().get(table.getProjectId(), table.getDatasetId(), table.getTableId()), - resourceNotFoundMsg); - } catch (Exception e) { - ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); - if ((e instanceof IOException) && errorExtractor.itemNotFound((IOException) e)) { - throw new IllegalArgumentException(resourceNotFoundMsg, e); - } else { - throw new RuntimeException( - String.format(UNABLE_TO_CONFIRM_PRESENCE_OF_RESOURCE_ERROR, "table", - BigQueryIO.toTableSpec(table)), - e); - } - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Implementation of DoFn to perform streaming BigQuery write. - */ - @SystemDoFnInternal - private static class StreamingWriteFn - extends DoFn, TableRowInfo>, Void> { - /** TableSchema in JSON. Use String to make the class Serializable. */ - private final ValueProvider jsonTableSchema; - - /** JsonTableRows to accumulate BigQuery rows in order to batch writes. */ - private transient Map> tableRows; - - /** The list of unique ids for each BigQuery table row. */ - private transient Map> uniqueIdsForTableRows; - - /** The list of tables created so far, so we don't try the creation - each time. */ - private static Set createdTables = - Collections.newSetFromMap(new ConcurrentHashMap()); - - /** Tracks bytes written, exposed as "ByteCount" Counter. */ - private Aggregator byteCountAggregator = - createAggregator("ByteCount", new Sum.SumLongFn()); - - /** Constructor. */ - StreamingWriteFn(ValueProvider schema) { - this.jsonTableSchema = - NestedValueProvider.of(schema, new TableSchemaToJsonSchema()); - } - - /** Prepares a target BigQuery table. */ - @Override - public void startBundle(Context context) { - tableRows = new HashMap<>(); - uniqueIdsForTableRows = new HashMap<>(); - } - - /** Accumulates the input into JsonTableRows and uniqueIdsForTableRows. */ - @Override - public void processElement(ProcessContext context) { - String tableSpec = context.element().getKey().getKey(); - List rows = getOrCreateMapListValue(tableRows, tableSpec); - List uniqueIds = getOrCreateMapListValue(uniqueIdsForTableRows, tableSpec); - - rows.add(context.element().getValue().tableRow); - uniqueIds.add(context.element().getValue().uniqueId); - } - - /** Writes the accumulated rows into BigQuery with streaming API. */ - @Override - public void finishBundle(Context context) throws Exception { - BigQueryOptions options = context.getPipelineOptions().as(BigQueryOptions.class); - Bigquery client = Transport.newBigQueryClient(options).build(); - - for (String tableSpec : tableRows.keySet()) { - TableReference tableReference = getOrCreateTable(options, tableSpec); - flushRows(client, tableReference, tableRows.get(tableSpec), - uniqueIdsForTableRows.get(tableSpec)); - } - tableRows.clear(); - uniqueIdsForTableRows.clear(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder.addIfNotNull(DisplayData.item("schema", jsonTableSchema) - .withLabel("Table Schema")); - } - - public TableReference getOrCreateTable(BigQueryOptions options, String tableSpec) - throws IOException { - TableReference tableReference = parseTableSpec(tableSpec); - if (!createdTables.contains(tableSpec)) { - synchronized (createdTables) { - // Another thread may have succeeded in creating the table in the meanwhile, so - // check again. This check isn't needed for correctness, but we add it to prevent - // every thread from attempting a create and overwhelming our BigQuery quota. - if (!createdTables.contains(tableSpec)) { - TableSchema tableSchema = JSON_FACTORY.fromString( - jsonTableSchema.get(), TableSchema.class); - Bigquery client = Transport.newBigQueryClient(options).build(); - BigQueryTableInserter inserter = new BigQueryTableInserter(client); - inserter.getOrCreateTable(tableReference, Write.WriteDisposition.WRITE_APPEND, - Write.CreateDisposition.CREATE_IF_NEEDED, tableSchema); - createdTables.add(tableSpec); - } - } - } - return tableReference; - } - - /** Writes the accumulated rows into BigQuery with streaming API. */ - private void flushRows(Bigquery client, TableReference tableReference, - List tableRows, List uniqueIds) { - if (!tableRows.isEmpty()) { - try { - BigQueryTableInserter inserter = new BigQueryTableInserter(client); - inserter.insertAll(tableReference, tableRows, uniqueIds, byteCountAggregator); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - } - - private static class ShardedKey { - private final K key; - private final int shardNumber; - - public static ShardedKey of(K key, int shardNumber) { - return new ShardedKey(key, shardNumber); - } - - private ShardedKey(K key, int shardNumber) { - this.key = key; - this.shardNumber = shardNumber; - } - - public K getKey() { - return key; - } - - public int getShardNumber() { - return shardNumber; - } - } - - /** - * A {@link Coder} for {@link ShardedKey}, using a wrapped key {@link Coder}. - */ - private static class ShardedKeyCoder - extends StandardCoder> { - public static ShardedKeyCoder of(Coder keyCoder) { - return new ShardedKeyCoder<>(keyCoder); - } - - @JsonCreator - public static ShardedKeyCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 component, got %s", components.size()); - return of(components.get(0)); - } - - protected ShardedKeyCoder(Coder keyCoder) { - this.keyCoder = keyCoder; - this.shardNumberCoder = VarIntCoder.of(); - } - - @Override - public List> getCoderArguments() { - return Arrays.asList(keyCoder); - } - - @Override - public void encode(ShardedKey key, OutputStream outStream, Context context) - throws IOException { - keyCoder.encode(key.getKey(), outStream, context.nested()); - shardNumberCoder.encode(key.getShardNumber(), outStream, context); - } - - @Override - public ShardedKey decode(InputStream inStream, Context context) - throws IOException { - return new ShardedKey( - keyCoder.decode(inStream, context.nested()), - shardNumberCoder.decode(inStream, context)); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - keyCoder.verifyDeterministic(); - } - - Coder keyCoder; - VarIntCoder shardNumberCoder; - } - - private static class TableRowInfoCoder extends AtomicCoder { - private static final TableRowInfoCoder INSTANCE = new TableRowInfoCoder(); - - @JsonCreator - public static TableRowInfoCoder of() { - return INSTANCE; - } - - @Override - public void encode(TableRowInfo value, OutputStream outStream, Context context) - throws IOException { - if (value == null) { - throw new CoderException("cannot encode a null value"); - } - tableRowCoder.encode(value.tableRow, outStream, context.nested()); - idCoder.encode(value.uniqueId, outStream, context.nested()); - } - - @Override - public TableRowInfo decode(InputStream inStream, Context context) - throws IOException { - return new TableRowInfo( - tableRowCoder.decode(inStream, context.nested()), - idCoder.decode(inStream, context.nested())); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, "TableRows are not deterministic."); - } - - TableRowJsonCoder tableRowCoder = TableRowJsonCoder.of(); - StringUtf8Coder idCoder = StringUtf8Coder.of(); - } - - private static class TableRowInfo { - TableRowInfo(TableRow tableRow, String uniqueId) { - this.tableRow = tableRow; - this.uniqueId = uniqueId; - } - - final TableRow tableRow; - final String uniqueId; - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Fn that tags each table row with a unique id and destination table. - * To avoid calling UUID.randomUUID() for each element, which can be costly, - * a randomUUID is generated only once per bucket of data. The actual unique - * id is created by concatenating this randomUUID with a sequential number. - */ - @VisibleForTesting - static class TagWithUniqueIdsAndTable - extends DoFn, TableRowInfo>> - implements DoFn.RequiresWindowAccess { - /** TableSpec to write to. */ - private final ValueProvider tableSpec; - - /** User function mapping windows to {@link TableReference} in JSON. */ - private final SerializableFunction tableRefFunction; - - private transient String randomUUID; - private transient long sequenceNo = 0L; - - TagWithUniqueIdsAndTable(BigQueryOptions options, - ValueProvider table, - SerializableFunction tableRefFunction) { - checkArgument(table == null ^ tableRefFunction == null, - "Exactly one of table or tableRefFunction should be set"); - if (table != null) { - if (table.isAccessible() && Strings.isNullOrEmpty(table.get().getProjectId())) { - TableReference tableRef = table.get() - .setProjectId(options.as(BigQueryOptions.class).getProject()); - table = NestedValueProvider.of( - StaticValueProvider.of(toJsonString(tableRef)), - new JsonTableRefToTableRef()); - } - this.tableSpec = NestedValueProvider.of(table, new TableRefToTableSpec()); - } else { - tableSpec = null; - } - this.tableRefFunction = tableRefFunction; - } - - - @Override - public void startBundle(Context context) { - randomUUID = UUID.randomUUID().toString(); - } - - /** Tag the input with a unique id. */ - @Override - public void processElement(ProcessContext context) throws IOException { - String uniqueId = randomUUID + sequenceNo++; - ThreadLocalRandom randomGenerator = ThreadLocalRandom.current(); - String tableSpec = tableSpecFromWindow( - context.getPipelineOptions().as(BigQueryOptions.class), context.window()); - // We output on keys 0-50 to ensure that there's enough batching for - // BigQuery. - context.output(KV.of(ShardedKey.of(tableSpec, randomGenerator.nextInt(0, 50)), - new TableRowInfo(context.element(), uniqueId))); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder.addIfNotNull(DisplayData.item("table", tableSpec)); - if (tableRefFunction != null) { - builder.add(DisplayData.item("tableFn", tableRefFunction.getClass()) - .withLabel("Table Reference Function")); - } - } - - @VisibleForTesting - ValueProvider getTableSpec() { - return tableSpec; - } - - private String tableSpecFromWindow(BigQueryOptions options, BoundedWindow window) { - if (tableSpec != null) { - return tableSpec.get(); - } else { - TableReference table = tableRefFunction.apply(window); - if (table.getProjectId() == null) { - table.setProjectId(options.getProject()); - } - return toTableSpec(table); - } - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * PTransform that performs streaming BigQuery write. To increase consistency, - * it leverages BigQuery best effort de-dup mechanism. - */ - private static class StreamWithDeDup extends PTransform, PDone> { - private final transient ValueProvider tableReference; - private final SerializableFunction tableRefFunction; - private final transient ValueProvider tableSchema; - - /** Constructor. */ - StreamWithDeDup(ValueProvider tableReference, - SerializableFunction tableRefFunction, - ValueProvider tableSchema) { - this.tableReference = tableReference; - this.tableRefFunction = tableRefFunction; - this.tableSchema = tableSchema; - } - - @Override - protected Coder getDefaultOutputCoder() { - return VoidCoder.of(); - } - - @Override - public PDone apply(PCollection input) { - // A naive implementation would be to simply stream data directly to BigQuery. - // However, this could occasionally lead to duplicated data, e.g., when - // a VM that runs this code is restarted and the code is re-run. - - // The above risk is mitigated in this implementation by relying on - // BigQuery built-in best effort de-dup mechanism. - - // To use this mechanism, each input TableRow is tagged with a generated - // unique id, which is then passed to BigQuery and used to ignore duplicates. - - PCollection, TableRowInfo>> tagged = input.apply(ParDo.of( - new TagWithUniqueIdsAndTable(input.getPipeline().getOptions().as(BigQueryOptions.class), - tableReference, tableRefFunction))); - - // To prevent having the same TableRow processed more than once with regenerated - // different unique ids, this implementation relies on "checkpointing", which is - // achieved as a side effect of having StreamingWriteFn immediately follow a GBK, - // performed by Reshuffle. - tagged - .setCoder(KvCoder.of(ShardedKeyCoder.of(StringUtf8Coder.of()), TableRowInfoCoder.of())) - .apply(Reshuffle., TableRowInfo>of()) - .apply(ParDo.of(new StreamingWriteFn(tableSchema))); - - // Note that the implementation to return PDone here breaks the - // implicit assumption about the job execution order. If a user - // implements a PTransform that takes PDone returned here as its - // input, the transform may not necessarily be executed after - // the BigQueryIO.Write. - - return PDone.in(input.getPipeline()); - } - } - - /** - * Status of a BigQuery job or request. - */ - enum Status { - SUCCEEDED, - FAILED, - UNKNOWN, - } - - private static Status parseStatus(@Nullable Job job) { - if (job == null) { - return Status.UNKNOWN; - } - JobStatus status = job.getStatus(); - if (status.getErrorResult() != null) { - return Status.FAILED; - } else if (status.getErrors() != null && !status.getErrors().isEmpty()) { - return Status.FAILED; - } else { - return Status.SUCCEEDED; - } - } - - @VisibleForTesting - static String toJsonString(Object item) { - if (item == null) { - return null; - } - try { - return JSON_FACTORY.toString(item); - } catch (IOException e) { - throw new RuntimeException( - String.format("Cannot serialize %s to a JSON string.", item.getClass().getSimpleName()), - e); - } - } - - @VisibleForTesting - static T fromJsonString(String json, Class clazz) { - if (json == null) { - return null; - } - try { - return JSON_FACTORY.fromString(json, clazz); - } catch (IOException e) { - throw new RuntimeException( - String.format("Cannot deserialize %s from a JSON string: %s.", clazz, json), - e); - } - } - - /** - * Returns a randomUUID string. - * - *

              {@code '-'} is removed because BigQuery doesn't allow it in dataset id. - */ - private static String randomUUIDString() { - return UUID.randomUUID().toString().replaceAll("-", ""); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** Disallow construction of utility class. */ - private BigQueryIO() {} - - private static List getOrCreateMapListValue(Map> map, K key) { - List value = map.get(key); - if (value == null) { - value = new ArrayList<>(); - map.put(key, value); - } - return value; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java deleted file mode 100644 index 9fb9f8aac9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -import java.io.IOException; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A {@code BlockBasedSource} is a {@link FileBasedSource} where a file consists of blocks of - * records. - * - *

              {@code BlockBasedSource} should be derived from when a file format does not support efficient - * seeking to a record in the file, but can support efficient seeking to a block. Alternatively, - * records in the file cannot be offset-addressed, but blocks can (it is not possible to say - * that record {code i} starts at offset {@code m}, but it is possible to say that block {@code j} - * starts at offset {@code n}). - * - *

              The records that will be read from a {@code BlockBasedSource} that corresponds to a subrange - * of a file {@code [startOffset, endOffset)} are those records such that the record is contained in - * a block that starts at offset {@code i}, where {@code i >= startOffset} and - * {@code i < endOffset}. In other words, a record will be read from the source if its first byte is - * contained in a block that begins within the range described by the source. - * - *

              This entails that it is possible to determine the start offsets of all blocks in a file. - * - *

              Progress reporting for reading from a {@code BlockBasedSource} is inaccurate. A {@link - * BlockBasedReader} reports its current offset as {@code (offset of current block) + (current block - * size) * (fraction of block consumed)}. However, only the offset of the current block is required - * to be accurately reported by subclass implementations. As such, in the worst case, the current - * offset is only updated at block boundaries. - * - *

              {@code BlockBasedSource} supports dynamic splitting. However, because records in a {@code - * BlockBasedSource} are not required to have offsets and progress reporting is inaccurate, {@code - * BlockBasedReader} only supports splitting at block boundaries. - * In other words, {@link BlockBasedReader#atSplitPoint} returns true iff the current record is the - * first record in a block. See {@link FileBasedSource.FileBasedReader} for discussion about split - * points. - * - * @param The type of records to be read from the source. - */ -@Experimental(Experimental.Kind.SOURCE_SINK) -public abstract class BlockBasedSource extends FileBasedSource { - /** - * Creates a {@code BlockBasedSource} based on a file name or pattern. Subclasses must call this - * constructor when creating a {@code BlockBasedSource} for a file pattern. See - * {@link FileBasedSource} for more information. - */ - public BlockBasedSource(String fileOrPatternSpec, long minBundleSize) { - super(fileOrPatternSpec, minBundleSize); - } - - /** - * Creates a {@code BlockBasedSource} for a single file. Subclasses must call this constructor - * when implementing {@link BlockBasedSource#createForSubrangeOfFile}. See documentation in - * {@link FileBasedSource}. - */ - public BlockBasedSource(String fileName, long minBundleSize, long startOffset, long endOffset) { - super(fileName, minBundleSize, startOffset, endOffset); - } - - /** - * Creates a {@code BlockBasedSource} for the specified range in a single file. - */ - @Override - protected abstract BlockBasedSource createForSubrangeOfFile( - String fileName, long start, long end); - - /** - * Creates a {@code BlockBasedReader}. - */ - @Override - protected abstract BlockBasedReader createSingleFileReader(PipelineOptions options); - - /** - * A {@code Block} represents a block of records that can be read. - */ - @Experimental(Experimental.Kind.SOURCE_SINK) - protected abstract static class Block { - /** - * Returns the current record. - */ - public abstract T getCurrentRecord(); - - /** - * Reads the next record from the block and returns true iff one exists. - */ - public abstract boolean readNextRecord() throws IOException; - - /** - * Returns the fraction of the block already consumed, if possible, as a value in - * {@code [0, 1]}. It should not include the current record. Successive results from this method - * must be monotonically increasing. - * - *

              If it is not possible to compute the fraction of the block consumed this method may - * return zero. For example, when the total number of records in the block is unknown. - */ - public abstract double getFractionOfBlockConsumed(); - } - - /** - * A {@code Reader} that reads records from a {@link BlockBasedSource}. If the source is a - * subrange of a file, the blocks that will be read by this reader are those such that the first - * byte of the block is within the range {@code [start, end)}. - */ - @Experimental(Experimental.Kind.SOURCE_SINK) - protected abstract static class BlockBasedReader extends FileBasedReader { - private boolean atSplitPoint; - - protected BlockBasedReader(BlockBasedSource source) { - super(source); - } - - /** - * Read the next block from the input. - */ - public abstract boolean readNextBlock() throws IOException; - - /** - * Returns the current block (the block that was read by the last successful call to - * {@link BlockBasedReader#readNextBlock}). May return null initially, or if no block has been - * successfully read. - */ - @Nullable - public abstract Block getCurrentBlock(); - - /** - * Returns the size of the current block in bytes as it is represented in the underlying file, - * if possible. This method may return {@code 0} if the size of the current block is unknown. - * - *

              The size returned by this method must be such that for two successive blocks A and B, - * {@code offset(A) + size(A) <= offset(B)}. If this is not satisfied, the progress reported - * by the {@code BlockBasedReader} will be non-monotonic and will interfere with the quality - * (but not correctness) of dynamic work rebalancing. - * - *

              This method and {@link Block#getFractionOfBlockConsumed} are used to provide an estimate - * of progress within a block ({@code getCurrentBlock().getFractionOfBlockConsumed() * - * getCurrentBlockSize()}). It is acceptable for the result of this computation to be {@code 0}, - * but progress estimation will be inaccurate. - */ - public abstract long getCurrentBlockSize(); - - /** - * Returns the largest offset such that starting to read from that offset includes the current - * block. - */ - public abstract long getCurrentBlockOffset(); - - @Override - public final T getCurrent() throws NoSuchElementException { - Block currentBlock = getCurrentBlock(); - if (currentBlock == null) { - throw new NoSuchElementException( - "No block has been successfully read from " + getCurrentSource()); - } - return currentBlock.getCurrentRecord(); - } - - /** - * Returns true if the reader is at a split point. A {@code BlockBasedReader} is at a split - * point if the current record is the first record in a block. In other words, split points - * are block boundaries. - */ - @Override - protected boolean isAtSplitPoint() { - return atSplitPoint; - } - - /** - * Reads the next record from the {@link #getCurrentBlock() current block} if - * possible. Will call {@link #readNextBlock()} to advance to the next block if not. - * - *

              The first record read from a block is treated as a split point. - */ - @Override - protected final boolean readNextRecord() throws IOException { - atSplitPoint = false; - - while (getCurrentBlock() == null || !getCurrentBlock().readNextRecord()) { - if (!readNextBlock()) { - return false; - } - // The first record in a block is a split point. - atSplitPoint = true; - } - return true; - } - - @Override - @Nullable - public Double getFractionConsumed() { - if (!isStarted()) { - return 0.0; - } - if (isDone()) { - return 1.0; - } - FileBasedSource source = getCurrentSource(); - if (source.getEndOffset() == Long.MAX_VALUE) { - // Unknown end offset, so we cannot tell. - return null; - } - - long currentBlockOffset = getCurrentBlockOffset(); - long startOffset = source.getStartOffset(); - long endOffset = source.getEndOffset(); - double fractionAtBlockStart = - ((double) (currentBlockOffset - startOffset)) / (endOffset - startOffset); - double fractionAtBlockEnd = - ((double) (currentBlockOffset + getCurrentBlockSize() - startOffset) - / (endOffset - startOffset)); - double blockFraction = getCurrentBlock().getFractionOfBlockConsumed(); - return Math.min( - 1.0, - fractionAtBlockStart + blockFraction * (fractionAtBlockEnd - fractionAtBlockStart)); - } - - @Override - protected long getCurrentOffset() { - return getCurrentBlockOffset(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java deleted file mode 100644 index 9712e8fb92..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSource.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.util.StringUtils.approximateSimpleName; - -import com.google.api.client.util.BackOff; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.FluentBackoff; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.util.concurrent.Uninterruptibles; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.TimeUnit; - -/** - * {@link PTransform} that reads a bounded amount of data from an {@link UnboundedSource}, - * specified as one or both of a maximum number of elements or a maximum period of time to read. - * - *

              Created by {@link Read}. - */ -class BoundedReadFromUnboundedSource extends PTransform> { - private final UnboundedSource source; - private final long maxNumRecords; - private final Duration maxReadTime; - private static final FluentBackoff BACKOFF_FACTORY = - FluentBackoff.DEFAULT - .withInitialBackoff(Duration.millis(10)) - .withMaxBackoff(Duration.standardSeconds(10)); - - /** - * Returns a new {@link BoundedReadFromUnboundedSource} that reads a bounded amount - * of data from the given {@link UnboundedSource}. The bound is specified as a number - * of records to read. - * - *

              This may take a long time to execute if the splits of this source are slow to read - * records. - */ - public BoundedReadFromUnboundedSource withMaxNumRecords(long maxNumRecords) { - return new BoundedReadFromUnboundedSource(source, maxNumRecords, maxReadTime); - } - - /** - * Returns a new {@link BoundedReadFromUnboundedSource} that reads a bounded amount - * of data from the given {@link UnboundedSource}. The bound is specified as an amount - * of time to read for. Each split of the source will read for this much time. - */ - public BoundedReadFromUnboundedSource withMaxReadTime(Duration maxReadTime) { - return new BoundedReadFromUnboundedSource(source, maxNumRecords, maxReadTime); - } - - BoundedReadFromUnboundedSource( - UnboundedSource source, long maxNumRecords, Duration maxReadTime) { - this.source = source; - this.maxNumRecords = maxNumRecords; - this.maxReadTime = maxReadTime; - } - - @Override - public PCollection apply(PInput input) { - PCollection> read = Pipeline.applyTransform(input, - Read.from(new UnboundedToBoundedSourceAdapter<>(source, maxNumRecords, maxReadTime))); - if (source.requiresDeduping()) { - read = read.apply(RemoveDuplicates.withRepresentativeValueFn( - new SerializableFunction, byte[]>() { - @Override - public byte[] apply(ValueWithRecordId input) { - return input.getId(); - } - })); - } - return read.apply(ValueWithRecordId.stripIds()); - } - - @Override - protected Coder getDefaultOutputCoder() { - return source.getDefaultOutputCoder(); - } - - @Override - public String getKindString() { - return "Read(" + approximateSimpleName(source.getClass()) + ")"; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - // We explicitly do not register base-class data, instead we use the delegate inner source. - builder - .add(DisplayData.item("source", source.getClass()) - .withLabel("Read Source")) - .addIfNotDefault(DisplayData.item("maxRecords", maxNumRecords) - .withLabel("Maximum Read Records"), Long.MAX_VALUE) - .addIfNotNull(DisplayData.item("maxReadTime", maxReadTime) - .withLabel("Maximum Read Time")) - .include(source); - } - - private static class UnboundedToBoundedSourceAdapter - extends BoundedSource> { - private final UnboundedSource source; - private final long maxNumRecords; - private final Duration maxReadTime; - - private UnboundedToBoundedSourceAdapter( - UnboundedSource source, long maxNumRecords, Duration maxReadTime) { - this.source = source; - this.maxNumRecords = maxNumRecords; - this.maxReadTime = maxReadTime; - } - - /** - * Divide the given number of records into {@code numSplits} approximately - * equal parts that sum to {@code numRecords}. - */ - private static long[] splitNumRecords(long numRecords, int numSplits) { - long[] splitNumRecords = new long[numSplits]; - for (int i = 0; i < numSplits; i++) { - splitNumRecords[i] = numRecords / numSplits; - } - for (int i = 0; i < numRecords % numSplits; i++) { - splitNumRecords[i] = splitNumRecords[i] + 1; - } - return splitNumRecords; - } - - /** - * Pick a number of initial splits based on the number of records expected to be processed. - */ - private static int numInitialSplits(long numRecords) { - final int maxSplits = 100; - final long recordsPerSplit = 10000; - return (int) Math.min(maxSplits, numRecords / recordsPerSplit + 1); - } - - @Override - public List>> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - List> result = new ArrayList<>(); - int numInitialSplits = numInitialSplits(maxNumRecords); - List> splits = - source.generateInitialSplits(numInitialSplits, options); - int numSplits = splits.size(); - long[] numRecords = splitNumRecords(maxNumRecords, numSplits); - for (int i = 0; i < numSplits; i++) { - result.add( - new UnboundedToBoundedSourceAdapter(splits.get(i), numRecords[i], maxReadTime)); - } - return result; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) { - // No way to estimate bytes, so returning 0. - return 0L; - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) { - return false; - } - - @Override - public Coder> getDefaultOutputCoder() { - return ValueWithRecordId.ValueWithRecordIdCoder.of(source.getDefaultOutputCoder()); - } - - @Override - public void validate() { - source.validate(); - } - - @Override - public BoundedReader> createReader(PipelineOptions options) { - return new Reader(source.createReader(options, null)); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("source", source.getClass())); - builder.include(source); - } - - private class Reader extends BoundedReader> { - private long recordsRead = 0L; - private Instant endTime = Instant.now().plus(maxReadTime); - private UnboundedSource.UnboundedReader reader; - - private Reader(UnboundedSource.UnboundedReader reader) { - this.recordsRead = 0L; - if (maxReadTime != null) { - this.endTime = Instant.now().plus(maxReadTime); - } else { - this.endTime = null; - } - this.reader = reader; - } - - @Override - public boolean start() throws IOException { - if (maxNumRecords <= 0 || (maxReadTime != null && maxReadTime.getMillis() == 0)) { - return false; - } - - recordsRead++; - if (reader.start()) { - return true; - } else { - return advanceWithBackoff(); - } - } - - @Override - public boolean advance() throws IOException { - if (recordsRead >= maxNumRecords) { - finalizeCheckpoint(); - return false; - } - recordsRead++; - return advanceWithBackoff(); - } - - private boolean advanceWithBackoff() throws IOException { - // Try reading from the source with exponential backoff - BackOff backoff = BACKOFF_FACTORY.backoff(); - long nextSleep = backoff.nextBackOffMillis(); - while (nextSleep != BackOff.STOP) { - if (endTime != null && Instant.now().isAfter(endTime)) { - finalizeCheckpoint(); - return false; - } - if (reader.advance()) { - return true; - } - Uninterruptibles.sleepUninterruptibly(nextSleep, TimeUnit.MILLISECONDS); - nextSleep = backoff.nextBackOffMillis(); - } - finalizeCheckpoint(); - return false; - } - - private void finalizeCheckpoint() throws IOException { - reader.getCheckpointMark().finalizeCheckpoint(); - } - - @Override - public ValueWithRecordId getCurrent() throws NoSuchElementException { - return new ValueWithRecordId<>(reader.getCurrent(), reader.getCurrentRecordId()); - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - return reader.getCurrentTimestamp(); - } - - @Override - public void close() throws IOException { - reader.close(); - } - - @Override - public BoundedSource> getCurrentSource() { - return UnboundedToBoundedSourceAdapter.this; - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java deleted file mode 100644 index fd1a85656a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BoundedSource.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; -import com.google.cloud.dataflow.sdk.io.range.RangeTracker; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A {@link Source} that reads a finite amount of input and, because of that, supports - * some additional operations. - * - *

              The operations are: - *

                - *
              • Splitting into bundles of given size: {@link #splitIntoBundles}; - *
              • Size estimation: {@link #getEstimatedSizeBytes}; - *
              • Telling whether or not this source produces key/value pairs in sorted order: - * {@link #producesSortedKeys}; - *
              • The accompanying {@link BoundedReader reader} has additional functionality to enable runners - * to dynamically adapt based on runtime conditions. - *
                  - *
                • Progress estimation ({@link BoundedReader#getFractionConsumed}) - *
                • Tracking of parallelism, to determine whether the current source can be split - * ({@link BoundedReader#getSplitPointsConsumed()} and - * {@link BoundedReader#getSplitPointsRemaining()}). - *
                • Dynamic splitting of the current source ({@link BoundedReader#splitAtFraction}). - *
                - *
              • - *
              - * - *

              To use this class for supporting your custom input type, derive your class - * class from it, and override the abstract methods. For an example, see {@link DatastoreIO}. - * - * @param Type of records read by the source. - */ -public abstract class BoundedSource extends Source { - /** - * Splits the source into bundles of approximately {@code desiredBundleSizeBytes}. - */ - public abstract List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception; - - /** - * An estimate of the total size (in bytes) of the data that would be read from this source. - * This estimate is in terms of external storage size, before any decompression or other - * processing done by the reader. - */ - public abstract long getEstimatedSizeBytes(PipelineOptions options) throws Exception; - - /** - * Whether this source is known to produce key/value pairs sorted by lexicographic order on - * the bytes of the encoded key. - */ - public abstract boolean producesSortedKeys(PipelineOptions options) throws Exception; - - /** - * Returns a new {@link BoundedReader} that reads from this source. - */ - public abstract BoundedReader createReader(PipelineOptions options) throws IOException; - - /** - * A {@code Reader} that reads a bounded amount of input and supports some additional - * operations, such as progress estimation and dynamic work rebalancing. - * - *

              Boundedness

              - * - *

              Once {@link #start} or {@link #advance} has returned false, neither will be called - * again on this object. - * - *

              Thread safety

              - * - *

              All methods will be run from the same thread except {@link #splitAtFraction}, - * {@link #getFractionConsumed}, {@link #getCurrentSource}, {@link #getSplitPointsConsumed()}, - * and {@link #getSplitPointsRemaining()}, all of which can be called concurrently - * from a different thread. There will not be multiple concurrent calls to - * {@link #splitAtFraction}. - * - *

              It must be safe to call {@link #splitAtFraction}, {@link #getFractionConsumed}, - * {@link #getCurrentSource}, {@link #getSplitPointsConsumed()}, and - * {@link #getSplitPointsRemaining()} concurrently with other methods. - * - *

              Additionally, a successful {@link #splitAtFraction} call must, by definition, cause - * {@link #getCurrentSource} to start returning a different value. - * Callers of {@link #getCurrentSource} need to be aware of the possibility that the returned - * value can change at any time, and must only access the properties of the source returned by - * {@link #getCurrentSource} which do not change between {@link #splitAtFraction} calls. - * - *

              Implementing {@link #splitAtFraction}

              - * - *

              In the course of dynamic work rebalancing, the method {@link #splitAtFraction} - * may be called concurrently with {@link #advance} or {@link #start}. It is critical that - * their interaction is implemented in a thread-safe way, otherwise data loss is possible. - * - *

              Sources which support dynamic work rebalancing should use - * {@link com.google.cloud.dataflow.sdk.io.range.RangeTracker} to manage the (source-specific) - * range of positions that is being split. If your source supports dynamic work rebalancing, - * please use that class to implement it if possible; if not possible, please contact the team - * at dataflow-feedback@google.com. - */ - @Experimental(Experimental.Kind.SOURCE_SINK) - public abstract static class BoundedReader extends Source.Reader { - /** - * Returns a value in [0, 1] representing approximately what fraction of the - * {@link #getCurrentSource current source} this reader has read so far, or {@code null} if such - * an estimate is not available. - * - *

              It is recommended that this method should satisfy the following properties: - *

                - *
              • Should return 0 before the {@link #start} call. - *
              • Should return 1 after a {@link #start} or {@link #advance} call that returns false. - *
              • The returned values should be non-decreasing (though they don't have to be unique). - *
              - * - *

              By default, returns null to indicate that this cannot be estimated. - * - *

              Thread safety
              - * If {@link #splitAtFraction} is implemented, this method can be called concurrently to other - * methods (including itself), and it is therefore critical for it to be implemented - * in a thread-safe way. - */ - @Nullable - public Double getFractionConsumed() { - return null; - } - - /** - * A constant to use as the return value for {@link #getSplitPointsConsumed()} or - * {@link #getSplitPointsRemaining()} when the exact value is unknown. - */ - public static final long SPLIT_POINTS_UNKNOWN = -1; - - /** - * Returns the total amount of parallelism in the consumed (returned and processed) range of - * this reader's current {@link BoundedSource} (as would be returned by - * {@link #getCurrentSource}). This corresponds to all split point records (see - * {@link RangeTracker}) returned by this reader, excluding the last split point - * returned if the reader is not finished. - * - *

              Consider the following examples: (1) An input that can be read in parallel down to the - * individual records, such as {@link CountingSource#upTo}, is called "perfectly splittable". - * (2) a "block-compressed" file format such as {@link AvroIO}, in which a block of records has - * to be read as a whole, but different blocks can be read in parallel. (3) An "unsplittable" - * input such as a cursor in a database. - * - *

                - *
              • Any {@link BoundedReader reader} that is unstarted (aka, has never had a call to - * {@link #start}) has a consumed parallelism of 0. This condition holds independent of whether - * the input is splittable. - *
              • Any {@link BoundedReader reader} that has only returned its first element (aka, - * has never had a call to {@link #advance}) has a consumed parallelism of 0: the first element - * is the current element and is still being processed. This condition holds independent of - * whether the input is splittable. - *
              • For an empty reader (in which the call to {@link #start} returned false), the - * consumed parallelism is 0. This condition holds independent of whether the input is - * splittable. - *
              • For a non-empty, finished reader (in which the call to {@link #start} returned true and - * a call to {@link #advance} has returned false), the value returned must be at least 1 - * and should equal the total parallelism in the source. - *
              • For example (1): After returning record #30 (starting at 1) out of 50 in a perfectly - * splittable 50-record input, this value should be 29. When finished, the consumed parallelism - * should be 50. - *
              • For example (2): In a block-compressed value consisting of 5 blocks, the value should - * stay at 0 until the first record of the second block is returned; stay at 1 until the first - * record of the third block is returned, etc. Only once the end-of-file is reached then the - * fifth block has been consumed and the value should stay at 5. - *
              • For example (3): For any non-empty unsplittable input, the consumed parallelism is 0 - * until the reader is finished (because the last call to {@link #advance} returned false, at - * which point it becomes 1. - *
              - * - *

              A reader that is implemented using a {@link RangeTracker} is encouraged to use the - * range tracker's ability to count split points to implement this method. See - * {@link OffsetBasedSource.OffsetBasedReader} and {@link OffsetRangeTracker} for an example. - * - *

              Defaults to {@link #SPLIT_POINTS_UNKNOWN}. Any value less than 0 will be interpreted - * as unknown. - * - *

              Thread safety

              - * See the javadoc on {@link BoundedReader} for information about thread safety. - * - * @see #getSplitPointsRemaining() - */ - public long getSplitPointsConsumed() { - return SPLIT_POINTS_UNKNOWN; - } - - /** - * Returns the total amount of parallelism in the unprocessed part of this reader's current - * {@link BoundedSource} (as would be returned by {@link #getCurrentSource}). This corresponds - * to all unprocessed split point records (see {@link RangeTracker}), including the last - * split point returned, in the remainder part of the source. - * - *

              This function should be implemented only in addition to - * {@link #getSplitPointsConsumed()} and only if an exact value can be - * returned. - * - *

              Consider the following examples: (1) An input that can be read in parallel down to the - * individual records, such as {@link CountingSource#upTo}, is called "perfectly splittable". - * (2) a "block-compressed" file format such as {@link AvroIO}, in which a block of records has - * to be read as a whole, but different blocks can be read in parallel. (3) An "unsplittable" - * input such as a cursor in a database. - * - *

              Assume for examples (1) and (2) that the number of records or blocks remaining is known: - * - *

                - *
              • Any {@link BoundedReader reader} for which the last call to {@link #start} or - * {@link #advance} has returned true should should not return 0, because this reader itself - * represents parallelism at least 1. This condition holds independent of whether the input is - * splittable. - *
              • A finished reader (for which {@link #start} or {@link #advance}) has returned false - * should return a value of 0. This condition holds independent of whether the input is - * splittable. - *
              • For example 1: After returning record #30 (starting at 1) out of 50 in a perfectly - * splittable 50-record input, this value should be 21 (20 remaining + 1 current) if the total - * number of records is known. - *
              • For example 2: After returning a record in block 3 in a block-compressed file - * consisting of 5 blocks, this value should be 3 (since blocks 4 and 5 can be processed in - * parallel by new readers produced via dynamic work rebalancing, while the current reader - * continues processing block 3) if the total number of blocks is known. - *
              • For example (3): a reader for any non-empty unsplittable input, should return 1 until - * it is finished, at which point it should return 0. - *
              • For any reader: After returning the last split point in a file (e.g., the last record - * in example (1), the first record in the last block for example (2), or the first record in - * the file for example (3), this value should be 1: apart from the current task, no additional - * remainder can be split off. - *
              - * - *

              Defaults to {@link #SPLIT_POINTS_UNKNOWN}. Any value less than 0 will be interpreted as - * unknown. - * - *

              Thread safety

              - * See the javadoc on {@link BoundedReader} for information about thread safety. - * - * @see #getSplitPointsConsumed() - */ - public long getSplitPointsRemaining() { - return SPLIT_POINTS_UNKNOWN; - } - - /** - * Returns a {@code Source} describing the same input that this {@code Reader} currently reads - * (including items already read). - * - *

              Usage

              - * - *

              Reader subclasses can use this method for convenience to access unchanging properties of - * the source being read. Alternatively, they can cache these properties in the constructor. - * - *

              The framework will call this method in the course of dynamic work rebalancing, e.g. after - * a successful {@link BoundedSource.BoundedReader#splitAtFraction} call. - * - *

              Mutability and thread safety

              - * - *

              Remember that {@link Source} objects must always be immutable. However, the return value - * of this function may be affected by dynamic work rebalancing, happening asynchronously via - * {@link BoundedSource.BoundedReader#splitAtFraction}, meaning it can return a different - * {@link Source} object. However, the returned object itself will still itself be immutable. - * Callers must take care not to rely on properties of the returned source that may be - * asynchronously changed as a result of this process (e.g. do not cache an end offset when - * reading a file). - * - *

              Implementation

              - * For convenience, subclasses should usually return the most concrete subclass of - * {@link Source} possible. - * In practice, the implementation of this method should nearly always be one of the following: - *
                - *
              • Source that inherits from a base class that already implements - * {@link #getCurrentSource}: delegate to base class. In this case, it is almost always - * an error for the subclass to maintain its own copy of the source. - *
                {@code
                -     *   public FooReader(FooSource source) {
                -     *     super(source);
                -     *   }
                -     *
                -     *   public FooSource getCurrentSource() {
                -     *     return (FooSource)super.getCurrentSource();
                -     *   }
                -     * }
                - *
              • Source that does not support dynamic work rebalancing: return a private final variable. - *
                {@code
                -     *   private final FooSource source;
                -     *
                -     *   public FooReader(FooSource source) {
                -     *     this.source = source;
                -     *   }
                -     *
                -     *   public FooSource getCurrentSource() {
                -     *     return source;
                -     *   }
                -     * }
                - *
              • {@link BoundedSource.BoundedReader} that explicitly supports dynamic work rebalancing: - * maintain a variable pointing to an immutable source object, and protect it with - * synchronization. - *
                {@code
                -     *   private FooSource source;
                -     *
                -     *   public FooReader(FooSource source) {
                -     *     this.source = source;
                -     *   }
                -     *
                -     *   public synchronized FooSource getCurrentSource() {
                -     *     return source;
                -     *   }
                -     *
                -     *   public synchronized FooSource splitAtFraction(double fraction) {
                -     *     ...
                -     *     FooSource primary = ...;
                -     *     FooSource residual = ...;
                -     *     this.source = primary;
                -     *     return residual;
                -     *   }
                -     * }
                - *
              - */ - @Override - public abstract BoundedSource getCurrentSource(); - - /** - * Tells the reader to narrow the range of the input it's going to read and give up - * the remainder, so that the new range would contain approximately the given - * fraction of the amount of data in the current range. - * - *

              Returns a {@code BoundedSource} representing the remainder. - * - *

              Detailed description
              - * Assuming the following sequence of calls: - *
              {@code
              -     *   BoundedSource initial = reader.getCurrentSource();
              -     *   BoundedSource residual = reader.splitAtFraction(fraction);
              -     *   BoundedSource primary = reader.getCurrentSource();
              -     * }
              - *
                - *
              • The "primary" and "residual" sources, when read, should together cover the same - * set of records as "initial". - *
              • The current reader should continue to be in a valid state, and continuing to read - * from it should, together with the records it already read, yield the same records - * as would have been read by "primary". - *
              • The amount of data read by "primary" should ideally represent approximately - * the given fraction of the amount of data read by "initial". - *
              - * For example, a reader that reads a range of offsets [A, B) in a file might implement - * this method by truncating the current range to [A, A + fraction*(B-A)) and returning - * a Source representing the range [A + fraction*(B-A), B). - * - *

              This method should return {@code null} if the split cannot be performed for this fraction - * while satisfying the semantics above. E.g., a reader that reads a range of offsets - * in a file should return {@code null} if it is already past the position in its range - * corresponding to the given fraction. In this case, the method MUST have no effect - * (the reader must behave as if the method hadn't been called at all). - * - *

              Statefulness
              - * Since this method (if successful) affects the reader's source, in subsequent invocations - * "fraction" should be interpreted relative to the new current source. - * - *
              Thread safety and blocking
              - * This method will be called concurrently to other methods (however there will not be multiple - * concurrent invocations of this method itself), and it is critical for it to be implemented - * in a thread-safe way (otherwise data loss is possible). - * - *

              It is also very important that this method always completes quickly. In particular, - * it should not perform or wait on any blocking operations such as I/O, RPCs etc. Violating - * this requirement may stall completion of the work item or even cause it to fail. - * - *

              It is incorrect to make both this method and {@link #start}/{@link #advance} - * {@code synchronized}, because those methods can perform blocking operations, and then - * this method would have to wait for those calls to complete. - * - *

              {@link com.google.cloud.dataflow.sdk.io.range.RangeTracker} makes it easy to implement - * this method safely and correctly. - * - *

              By default, returns null to indicate that splitting is not possible. - */ - @Nullable - public BoundedSource splitAtFraction(double fraction) { - return null; - } - - /** - * By default, returns the minimum possible timestamp. - */ - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - return BoundedWindow.TIMESTAMP_MIN_VALUE; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java deleted file mode 100644 index 2f2d82e823..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CompressedSource.java +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.common.io.ByteStreams; -import com.google.common.primitives.Ints; -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; -import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; -import java.io.IOException; -import java.io.PushbackInputStream; -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.util.NoSuchElementException; -import java.util.zip.GZIPInputStream; -import javax.annotation.concurrent.GuardedBy; - -/** - * A Source that reads from compressed files. A {@code CompressedSources} wraps a delegate - * {@link FileBasedSource} that is able to read the decompressed file format. - * - *

              For example, use the following to read from a gzip-compressed XML file: - * - *

               {@code
              - * XmlSource mySource = XmlSource.from(...);
              - * PCollection collection = p.apply(Read.from(CompressedSource
              - *     .from(mySource)
              - *     .withDecompression(CompressedSource.CompressionMode.GZIP)));
              - * } 
              - * - *

              Supported compression algorithms are {@link CompressionMode#GZIP} and - * {@link CompressionMode#BZIP2}. User-defined compression types are supported by implementing - * {@link DecompressingChannelFactory}. - * - *

              By default, the compression algorithm is selected from those supported in - * {@link CompressionMode} based on the file name provided to the source, namely - * {@code ".bz2"} indicates {@link CompressionMode#BZIP2} and {@code ".gz"} indicates - * {@link CompressionMode#GZIP}. If the file name does not match any of the supported - * algorithms, it is assumed to be uncompressed data. - * - * @param The type to read from the compressed file. - */ -@Experimental(Experimental.Kind.SOURCE_SINK) -public class CompressedSource extends FileBasedSource { - /** - * Factory interface for creating channels that decompress the content of an underlying channel. - */ - public interface DecompressingChannelFactory extends Serializable { - /** - * Given a channel, create a channel that decompresses the content read from the channel. - * @throws IOException - */ - ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) - throws IOException; - } - - /** - * Factory interface for creating channels that decompress the content of an underlying channel, - * based on both the channel and the file name. - */ - private interface FileNameBasedDecompressingChannelFactory - extends DecompressingChannelFactory { - /** - * Given a channel, create a channel that decompresses the content read from the channel. - * @throws IOException - */ - ReadableByteChannel createDecompressingChannel(String fileName, ReadableByteChannel channel) - throws IOException; - - /** - * Given a file name, returns true if the file name matches any supported compression - * scheme. - */ - boolean isCompressed(String fileName); - } - - /** - * Default compression types supported by the {@code CompressedSource}. - */ - public enum CompressionMode implements DecompressingChannelFactory { - /** - * Reads a byte channel assuming it is compressed with gzip. - */ - GZIP { - @Override - public boolean matches(String fileName) { - return fileName.toLowerCase().endsWith(".gz"); - } - - @Override - public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) - throws IOException { - // Determine if the input stream is gzipped. The input stream returned from the - // GCS connector may already be decompressed; GCS does this based on the - // content-encoding property. - PushbackInputStream stream = new PushbackInputStream(Channels.newInputStream(channel), 2); - byte[] headerBytes = new byte[2]; - int bytesRead = ByteStreams.read( - stream /* source */, headerBytes /* dest */, 0 /* offset */, 2 /* len */); - stream.unread(headerBytes, 0, bytesRead); - if (bytesRead >= 2) { - byte zero = 0x00; - int header = Ints.fromBytes(zero, zero, headerBytes[1], headerBytes[0]); - if (header == GZIPInputStream.GZIP_MAGIC) { - return Channels.newChannel(new GzipCompressorInputStream(stream, true)); - } - } - return Channels.newChannel(stream); - } - }, - - /** - * Reads a byte channel assuming it is compressed with bzip2. - */ - BZIP2 { - @Override - public boolean matches(String fileName) { - return fileName.toLowerCase().endsWith(".bz2"); - } - - @Override - public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) - throws IOException { - return Channels.newChannel( - new BZip2CompressorInputStream(Channels.newInputStream(channel))); - } - }; - - /** - * Returns {@code true} if the given file name implies that the contents are compressed - * according to the compression embodied by this factory. - */ - public abstract boolean matches(String fileName); - - @Override - public abstract ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) - throws IOException; - } - - /** - * Reads a byte channel detecting compression according to the file name. If the filename - * is not any other known {@link CompressionMode}, it is presumed to be uncompressed. - */ - private static class DecompressAccordingToFilename - implements FileNameBasedDecompressingChannelFactory { - - @Override - public ReadableByteChannel createDecompressingChannel( - String fileName, ReadableByteChannel channel) throws IOException { - for (CompressionMode type : CompressionMode.values()) { - if (type.matches(fileName)) { - return type.createDecompressingChannel(channel); - } - } - // Uncompressed - return channel; - } - - @Override - public ReadableByteChannel createDecompressingChannel(ReadableByteChannel channel) { - throw new UnsupportedOperationException( - String.format("%s does not support createDecompressingChannel(%s) but only" - + " createDecompressingChannel(%s,%s)", - getClass().getSimpleName(), - String.class.getSimpleName(), - ReadableByteChannel.class.getSimpleName(), - ReadableByteChannel.class.getSimpleName())); - } - - @Override - public boolean isCompressed(String fileName) { - for (CompressionMode type : CompressionMode.values()) { - if (type.matches(fileName)) { - return true; - } - } - return false; - } - } - - private final FileBasedSource sourceDelegate; - private final DecompressingChannelFactory channelFactory; - - /** - * Creates a {@link Read} transform that reads from that reads from the underlying - * {@link FileBasedSource} {@code sourceDelegate} after decompressing it with a {@link - * DecompressingChannelFactory}. - */ - public static Read.Bounded readFromSource( - FileBasedSource sourceDelegate, DecompressingChannelFactory channelFactory) { - return Read.from(new CompressedSource<>(sourceDelegate, channelFactory)); - } - - /** - * Creates a {@code CompressedSource} from an underlying {@code FileBasedSource}. The type - * of compression used will be based on the file name extension unless explicitly - * configured via {@link CompressedSource#withDecompression}. - */ - public static CompressedSource from(FileBasedSource sourceDelegate) { - return new CompressedSource<>(sourceDelegate, new DecompressAccordingToFilename()); - } - - /** - * Return a {@code CompressedSource} that is like this one but will decompress its underlying file - * with the given {@link DecompressingChannelFactory}. - */ - public CompressedSource withDecompression(DecompressingChannelFactory channelFactory) { - return new CompressedSource<>(this.sourceDelegate, channelFactory); - } - - /** - * Creates a {@code CompressedSource} from a delegate file based source and a decompressing - * channel factory. - */ - private CompressedSource( - FileBasedSource sourceDelegate, DecompressingChannelFactory channelFactory) { - super(sourceDelegate.getFileOrPatternSpecProvider(), Long.MAX_VALUE); - this.sourceDelegate = sourceDelegate; - this.channelFactory = channelFactory; - } - - /** - * Creates a {@code CompressedSource} for an individual file. Used by {@link - * CompressedSource#createForSubrangeOfFile}. - */ - private CompressedSource(FileBasedSource sourceDelegate, - DecompressingChannelFactory channelFactory, String filePatternOrSpec, long minBundleSize, - long startOffset, long endOffset) { - super(filePatternOrSpec, minBundleSize, startOffset, endOffset); - this.sourceDelegate = sourceDelegate; - this.channelFactory = channelFactory; - try { - checkArgument( - isSplittable() || startOffset == 0, - "CompressedSources must start reading at offset 0. Requested offset: " + startOffset); - } catch (Exception e) { - throw new RuntimeException( - "Error checking whether source " + sourceDelegate + " is splittable"); - } - } - - /** - * Validates that the delegate source is a valid source and that the channel factory is not null. - */ - @Override - public void validate() { - super.validate(); - checkNotNull(sourceDelegate); - sourceDelegate.validate(); - checkNotNull(channelFactory); - } - - /** - * Creates a {@code CompressedSource} for a subrange of a file. Called by superclass to create a - * source for a single file. - */ - @Override - protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { - return new CompressedSource<>(sourceDelegate.createForSubrangeOfFile(fileName, start, end), - channelFactory, fileName, sourceDelegate.getMinBundleSize(), start, end); - } - - /** - * Determines whether a single file represented by this source is splittable. Returns true - * if we are using the default decompression factory and and it determines - * from the requested file name that the file is not compressed. - */ - @Override - protected final boolean isSplittable() throws Exception { - if (channelFactory instanceof FileNameBasedDecompressingChannelFactory) { - FileNameBasedDecompressingChannelFactory fileNameBasedChannelFactory = - (FileNameBasedDecompressingChannelFactory) channelFactory; - return !fileNameBasedChannelFactory.isCompressed(getFileOrPatternSpec()); - } - return false; - } - - /** - * Creates a {@code FileBasedReader} to read a single file. - * - *

              Uses the delegate source to create a single file reader for the delegate source. - * Utilizes the default decompression channel factory to not wrap the source reader - * if the file name does not represent a compressed file allowing for splitting of - * the source. - */ - @Override - protected final FileBasedReader createSingleFileReader(PipelineOptions options) { - if (channelFactory instanceof FileNameBasedDecompressingChannelFactory) { - FileNameBasedDecompressingChannelFactory fileNameBasedChannelFactory = - (FileNameBasedDecompressingChannelFactory) channelFactory; - if (!fileNameBasedChannelFactory.isCompressed(getFileOrPatternSpec())) { - return sourceDelegate.createSingleFileReader(options); - } - } - return new CompressedReader( - this, sourceDelegate.createSingleFileReader(options)); - } - - /** - * Returns whether the delegate source produces sorted keys. - */ - @Override - public final boolean producesSortedKeys(PipelineOptions options) throws Exception { - return sourceDelegate.producesSortedKeys(options); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - // We explicitly do not register base-class data, instead we use the delegate inner source. - builder - .include(sourceDelegate) - .add(DisplayData.item("source", sourceDelegate.getClass()) - .withLabel("Read Source")); - - if (channelFactory instanceof Enum) { - // GZIP and BZIP are implemented as enums; Enum classes are anonymous, so use the .name() - // value instead - builder.add(DisplayData.item("compressionMode", ((Enum) channelFactory).name()) - .withLabel("Compression Mode")); - } else { - builder.add(DisplayData.item("compressionMode", channelFactory.getClass()) - .withLabel("Compression Mode")); - } - } - - /** - * Returns the delegate source's default output coder. - */ - @Override - public final Coder getDefaultOutputCoder() { - return sourceDelegate.getDefaultOutputCoder(); - } - - public final DecompressingChannelFactory getChannelFactory() { - return channelFactory; - } - - /** - * Reader for a {@link CompressedSource}. Decompresses its input and uses a delegate - * reader to read elements from the decompressed input. - * @param The type of records read from the source. - */ - public static class CompressedReader extends FileBasedReader { - - private final FileBasedReader readerDelegate; - private final CompressedSource source; - private final Object progressLock = new Object(); - @GuardedBy("progressLock") - private int numRecordsRead; - @GuardedBy("progressLock") - private CountingChannel channel; - - /** - * Create a {@code CompressedReader} from a {@code CompressedSource} and delegate reader. - */ - public CompressedReader(CompressedSource source, FileBasedReader readerDelegate) { - super(source); - this.source = source; - this.readerDelegate = readerDelegate; - } - - /** - * Gets the current record from the delegate reader. - */ - @Override - public T getCurrent() throws NoSuchElementException { - return readerDelegate.getCurrent(); - } - - @Override - public final long getSplitPointsConsumed() { - synchronized (progressLock) { - return (isDone() && numRecordsRead > 0) ? 1 : 0; - } - } - - @Override - public final long getSplitPointsRemaining() { - return isDone() ? 0 : 1; - } - - /** - * Returns true only for the first record; compressed sources cannot be split. - */ - @Override - protected final boolean isAtSplitPoint() { - // We have to return true for the first record, but not for the state before reading it, - // and not for the state after reading any other record. Hence == rather than >= or <=. - // This is required because FileBasedReader is intended for readers that can read a range - // of offsets in a file and where the range can be split in parts. CompressedReader, - // however, is a degenerate case because it cannot be split, but it has to satisfy the - // semantics of offsets and split points anyway. - synchronized (progressLock) { - return numRecordsRead == 1; - } - } - - private static class CountingChannel implements ReadableByteChannel { - long count; - private final ReadableByteChannel inner; - - public CountingChannel(ReadableByteChannel inner, long count) { - this.inner = inner; - this.count = count; - } - - public long getCount() { - return count; - } - - @Override - public int read(ByteBuffer dst) throws IOException { - int bytes = inner.read(dst); - if (bytes > 0) { - // Avoid the -1 from EOF. - count += bytes; - } - return bytes; - } - - @Override - public boolean isOpen() { - return inner.isOpen(); - } - - @Override - public void close() throws IOException { - inner.close(); - } - } - - /** - * Creates a decompressing channel from the input channel and passes it to its delegate reader's - * {@link FileBasedReader#startReading(ReadableByteChannel)}. - */ - @Override - protected final void startReading(ReadableByteChannel channel) throws IOException { - synchronized (progressLock) { - this.channel = new CountingChannel(channel, getCurrentSource().getStartOffset()); - channel = this.channel; - } - - if (source.getChannelFactory() instanceof FileNameBasedDecompressingChannelFactory) { - FileNameBasedDecompressingChannelFactory channelFactory = - (FileNameBasedDecompressingChannelFactory) source.getChannelFactory(); - readerDelegate.startReading(channelFactory.createDecompressingChannel( - getCurrentSource().getFileOrPatternSpec(), - channel)); - } else { - readerDelegate.startReading(source.getChannelFactory().createDecompressingChannel( - channel)); - } - } - - /** - * Reads the next record via the delegate reader. - */ - @Override - protected final boolean readNextRecord() throws IOException { - if (!readerDelegate.readNextRecord()) { - return false; - } - synchronized (progressLock) { - ++numRecordsRead; - } - return true; - } - - // Unsplittable: returns the offset in the input stream that has been read by the input. - // these positions are likely to be coarse-grained (in the event of buffering) and - // over-estimates (because they reflect the number of bytes read to produce an element, not its - // start) but both of these provide better data than e.g., reporting the start of the file. - @Override - protected final long getCurrentOffset() throws NoSuchElementException { - synchronized (progressLock) { - if (numRecordsRead <= 1) { - // Since the first record is at a split point, it should start at the beginning of the - // file. This avoids the bad case where the decompressor read the entire file, which - // would cause the file to be treated as empty when returning channel.getCount() as it - // is outside the valid range. - return 0; - } - return channel.getCount(); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java deleted file mode 100644 index c743146e10..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingInput.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.io.CountingSource.NowTimestampFn; -import com.google.cloud.dataflow.sdk.io.Read.Unbounded; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.common.base.Optional; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -/** - * A {@link PTransform} that produces longs. When used to produce a - * {@link IsBounded#BOUNDED bounded} {@link PCollection}, {@link CountingInput} starts at {@code 0} - * and counts up to a specified maximum. When used to produce an - * {@link IsBounded#UNBOUNDED unbounded} {@link PCollection}, it counts up to {@link Long#MAX_VALUE} - * and then never produces more output. (In practice, this limit should never be reached.) - * - *

              The bounded {@link CountingInput} is implemented based on {@link OffsetBasedSource} and - * {@link OffsetBasedSource.OffsetBasedReader}, so it performs efficient initial splitting and it - * supports dynamic work rebalancing. - * - *

              To produce a bounded {@code PCollection}, use {@link CountingInput#upTo(long)}: - * - *

              {@code
              - * Pipeline p = ...
              - * PTransform> producer = CountingInput.upTo(1000);
              - * PCollection bounded = p.apply(producer);
              - * }
              - * - *

              To produce an unbounded {@code PCollection}, use {@link CountingInput#unbounded()}, - * calling {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to provide values - * with timestamps other than {@link Instant#now}. - * - *

              {@code
              - * Pipeline p = ...
              - *
              - * // To create an unbounded producer that uses processing time as the element timestamp.
              - * PCollection unbounded = p.apply(CountingInput.unbounded());
              - * // Or, to create an unbounded source that uses a provided function to set the element timestamp.
              - * PCollection unboundedWithTimestamps =
              - *     p.apply(CountingInput.unbounded().withTimestampFn(someFn));
              - * }
              - */ -public class CountingInput { - /** - * Creates a {@link BoundedCountingInput} that will produce the specified number of elements, - * from {@code 0} to {@code numElements - 1}. - */ - public static BoundedCountingInput upTo(long numElements) { - checkArgument(numElements > 0, "numElements (%s) must be greater than 0", numElements); - return new BoundedCountingInput(numElements); - } - - /** - * Creates an {@link UnboundedCountingInput} that will produce numbers starting from {@code 0} up - * to {@link Long#MAX_VALUE}. - * - *

              After {@link Long#MAX_VALUE}, the transform never produces more output. (In practice, this - * limit should never be reached.) - * - *

              Elements in the resulting {@link PCollection PCollection<Long>} will by default have - * timestamps corresponding to processing time at element generation, provided by - * {@link Instant#now}. Use the transform returned by - * {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to control the output - * timestamps. - */ - public static UnboundedCountingInput unbounded() { - return new UnboundedCountingInput( - new NowTimestampFn(), - 1L /* Elements per period */, - Duration.ZERO /* Period length */, - Optional.absent() /* Maximum number of records */, - Optional.absent() /* Maximum read duration */); - } - - /** - * A {@link PTransform} that will produce a specified number of {@link Long Longs} starting from - * 0. - */ - public static class BoundedCountingInput extends PTransform> { - private final long numElements; - - private BoundedCountingInput(long numElements) { - this.numElements = numElements; - } - - @SuppressWarnings("deprecation") - @Override - public PCollection apply(PBegin begin) { - return begin.apply(Read.from(CountingSource.upTo(numElements))); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("upTo", numElements) - .withLabel("Count Up To")); - } - } - - /** - * A {@link PTransform} that will produce numbers starting from {@code 0} up to - * {@link Long#MAX_VALUE}. - * - *

              After {@link Long#MAX_VALUE}, the transform never produces more output. (In practice, this - * limit should never be reached.) - * - *

              Elements in the resulting {@link PCollection PCollection<Long>} will by default have - * timestamps corresponding to processing time at element generation, provided by - * {@link Instant#now}. Use the transform returned by - * {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to control the output - * timestamps. - */ - public static class UnboundedCountingInput extends PTransform> { - private final SerializableFunction timestampFn; - private final long elementsPerPeriod; - private final Duration period; - private final Optional maxNumRecords; - private final Optional maxReadTime; - - private UnboundedCountingInput( - SerializableFunction timestampFn, - long elementsPerPeriod, - Duration period, - Optional maxNumRecords, - Optional maxReadTime) { - this.timestampFn = timestampFn; - this.elementsPerPeriod = elementsPerPeriod; - this.period = period; - this.maxNumRecords = maxNumRecords; - this.maxReadTime = maxReadTime; - } - - /** - * Returns an {@link UnboundedCountingInput} like this one, but where output elements have the - * timestamp specified by the timestampFn. - * - *

              Note that the timestamps produced by {@code timestampFn} may not decrease. - */ - public UnboundedCountingInput withTimestampFn(SerializableFunction timestampFn) { - return new UnboundedCountingInput( - timestampFn, elementsPerPeriod, period, maxNumRecords, maxReadTime); - } - - /** - * Returns an {@link UnboundedCountingInput} like this one, but that will read at most the - * specified number of elements. - * - *

              A bounded amount of elements will be produced by the result transform, and the result - * {@link PCollection} will be {@link IsBounded#BOUNDED bounded}. - */ - public UnboundedCountingInput withMaxNumRecords(long maxRecords) { - checkArgument( - maxRecords > 0, "MaxRecords must be a positive (nonzero) value. Got %s", maxRecords); - return new UnboundedCountingInput( - timestampFn, elementsPerPeriod, period, Optional.of(maxRecords), maxReadTime); - } - - /** - * Returns an {@link UnboundedCountingInput} like this one, but with output production limited - * to an aggregate rate of no more than the number of elements per the period length. - * - *

              Note that when there are multiple splits, each split outputs independently. This may lead - * to elements not being produced evenly across time, though the aggregate rate will still - * approach the specified rate. - * - *

              A duration of {@link Duration#ZERO} will produce output as fast as possible. - */ - public UnboundedCountingInput withRate(long numElements, Duration periodLength) { - return new UnboundedCountingInput( - timestampFn, numElements, periodLength, maxNumRecords, maxReadTime); - } - - /** - * Returns an {@link UnboundedCountingInput} like this one, but that will read for at most the - * specified amount of time. - * - *

              A bounded amount of elements will be produced by the result transform, and the result - * {@link PCollection} will be {@link IsBounded#BOUNDED bounded}. - */ - public UnboundedCountingInput withMaxReadTime(Duration readTime) { - checkNotNull(readTime, "ReadTime cannot be null"); - return new UnboundedCountingInput( - timestampFn, elementsPerPeriod, period, maxNumRecords, Optional.of(readTime)); - } - - @SuppressWarnings("deprecation") - @Override - public PCollection apply(PBegin begin) { - Unbounded read = - Read.from( - CountingSource.createUnbounded() - .withTimestampFn(timestampFn) - .withRate(elementsPerPeriod, period)); - if (!maxNumRecords.isPresent() && !maxReadTime.isPresent()) { - return begin.apply(read); - } else if (maxNumRecords.isPresent() && !maxReadTime.isPresent()) { - return begin.apply(read.withMaxNumRecords(maxNumRecords.get())); - } else if (!maxNumRecords.isPresent() && maxReadTime.isPresent()) { - return begin.apply(read.withMaxReadTime(maxReadTime.get())); - } else { - return begin.apply( - read.withMaxReadTime(maxReadTime.get()).withMaxNumRecords(maxNumRecords.get())); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder.add(DisplayData.item("timestampFn", timestampFn.getClass()) - .withLabel("Timestamp Function")); - - if (maxReadTime.isPresent()) { - builder.add(DisplayData.item("maxReadTime", maxReadTime.get()) - .withLabel("Maximum Read Time")); - } - - if (maxNumRecords.isPresent()) { - builder.add(DisplayData.item("maxRecords", maxNumRecords.get()) - .withLabel("Maximum Read Records")); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java deleted file mode 100644 index 20568441ed..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/CountingSource.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.io.CountingInput.UnboundedCountingInput; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * A source that produces longs. When used as a {@link BoundedSource}, {@link CountingSource} - * starts at {@code 0} and counts up to a specified maximum. When used as an - * {@link UnboundedSource}, it counts up to {@link Long#MAX_VALUE} and then never produces more - * output. (In practice, this limit should never be reached.) - * - *

              The bounded {@link CountingSource} is implemented based on {@link OffsetBasedSource} and - * {@link OffsetBasedSource.OffsetBasedReader}, so it performs efficient initial splitting and it - * supports dynamic work rebalancing. - * - *

              To produce a bounded {@code PCollection}, use {@link CountingSource#upTo(long)}: - * - *

              {@code
              - * Pipeline p = ...
              - * PTransform> producer = CountingInput.upTo(1000);
              - * PCollection bounded = p.apply(producer);
              - * }
              - * - *

              To produce an unbounded {@code PCollection}, use {@link CountingInput#unbounded()}, - * calling {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} to provide values - * with timestamps other than {@link Instant#now}. - * - *

              {@code
              - * Pipeline p = ...
              - *
              - * // To create an unbounded PCollection that uses processing time as the element timestamp.
              - * PCollection unbounded = p.apply(CountingInput.unbounded());
              - * // Or, to create an unbounded source that uses a provided function to set the element timestamp.
              - * PCollection unboundedWithTimestamps =
              - *     p.apply(CountingInput.unbounded().withTimestampFn(someFn));
              - *
              - * }
              - */ -public class CountingSource { - /** - * Creates a {@link BoundedSource} that will produce the specified number of elements, - * from {@code 0} to {@code numElements - 1}. - * - * @deprecated use {@link CountingInput#upTo(long)} instead - */ - @Deprecated - public static BoundedSource upTo(long numElements) { - checkArgument(numElements > 0, "numElements (%s) must be greater than 0", numElements); - return new BoundedCountingSource(0, numElements); - } - - /** - * Create a new {@link UnboundedCountingSource}. - */ - // package-private to return a typed UnboundedCountingSource rather than the UnboundedSource type. - static UnboundedCountingSource createUnbounded() { - return new UnboundedCountingSource(0, 1, 1L, Duration.ZERO, new NowTimestampFn()); - } - - /** - * Creates an {@link UnboundedSource} that will produce numbers starting from {@code 0} up to - * {@link Long#MAX_VALUE}. - * - *

              After {@link Long#MAX_VALUE}, the source never produces more output. (In practice, this - * limit should never be reached.) - * - *

              Elements in the resulting {@link PCollection PCollection<Long>} will have timestamps - * corresponding to processing time at element generation, provided by {@link Instant#now}. - * - * @deprecated use {@link CountingInput#unbounded()} instead - */ - @Deprecated - public static UnboundedSource unbounded() { - return unboundedWithTimestampFn(new NowTimestampFn()); - } - - /** - * Creates an {@link UnboundedSource} that will produce numbers starting from {@code 0} up to - * {@link Long#MAX_VALUE}, with element timestamps supplied by the specified function. - * - *

              After {@link Long#MAX_VALUE}, the source never produces more output. (In practice, this - * limit should never be reached.) - * - *

              Note that the timestamps produced by {@code timestampFn} may not decrease. - * - * @deprecated use {@link CountingInput#unbounded()} and call - * {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)} instead - */ - @Deprecated - public static UnboundedSource unboundedWithTimestampFn( - SerializableFunction timestampFn) { - return new UnboundedCountingSource(0, 1, 1L, Duration.ZERO, timestampFn); - } - - ///////////////////////////////////////////////////////////////////////////////////////////// - - /** Prevent instantiation. */ - private CountingSource() {} - - /** - * A function that returns {@link Instant#now} as the timestamp for each generated element. - */ - static class NowTimestampFn implements SerializableFunction { - @Override - public Instant apply(Long input) { - return Instant.now(); - } - } - - /** - * An implementation of {@link CountingSource} that produces a bounded {@link PCollection}. - * It is implemented on top of {@link OffsetBasedSource} (with associated reader - * {@link BoundedCountingReader}) and performs efficient initial splitting and supports dynamic - * work rebalancing. - */ - private static class BoundedCountingSource extends OffsetBasedSource { - /** - * Creates a {@link BoundedCountingSource} that generates the numbers in the specified - * {@code [start, end)} range. - */ - public BoundedCountingSource(long start, long end) { - super(start, end, 1 /* can be split every 1 offset */); - } - - //////////////////////////////////////////////////////////////////////////////////////////// - - @Override - public long getBytesPerOffset() { - return 8; - } - - @Override - public long getMaxEndOffset(PipelineOptions options) throws Exception { - return getEndOffset(); - } - - @Override - public OffsetBasedSource createSourceForSubrange(long start, long end) { - return new BoundedCountingSource(start, end); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return true; - } - - @Override - public com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader createReader( - PipelineOptions options) throws IOException { - return new BoundedCountingReader(this); - } - - @Override - public Coder getDefaultOutputCoder() { - return VarLongCoder.of(); - } - } - - /** - * The reader associated with {@link BoundedCountingSource}. - * - * @see BoundedCountingSource - */ - private static class BoundedCountingReader extends OffsetBasedSource.OffsetBasedReader { - private long current; - - public BoundedCountingReader(OffsetBasedSource source) { - super(source); - } - - @Override - protected long getCurrentOffset() throws NoSuchElementException { - return current; - } - - @Override - public synchronized long getSplitPointsRemaining() { - return Math.max(0, getCurrentSource().getEndOffset() - current); - } - - @Override - public synchronized BoundedCountingSource getCurrentSource() { - return (BoundedCountingSource) super.getCurrentSource(); - } - - @Override - public Long getCurrent() throws NoSuchElementException { - return current; - } - - @Override - protected boolean startImpl() throws IOException { - current = getCurrentSource().getStartOffset(); - return true; - } - - @Override - protected boolean advanceImpl() throws IOException { - current++; - return true; - } - - @Override - public void close() throws IOException {} - } - - /** - * An implementation of {@link CountingSource} that produces an unbounded {@link PCollection}. - */ - static class UnboundedCountingSource extends UnboundedSource { - /** The first number (>= 0) generated by this {@link UnboundedCountingSource}. */ - private final long start; - /** The interval between numbers generated by this {@link UnboundedCountingSource}. */ - private final long stride; - /** The number of elements to produce each period. */ - private final long elementsPerPeriod; - /** The time between producing numbers from this {@link UnboundedCountingSource}. */ - private final Duration period; - /** The function used to produce timestamps for the generated elements. */ - private final SerializableFunction timestampFn; - - /** - * Creates an {@link UnboundedSource} that will produce numbers starting from {@code 0} up to - * {@link Long#MAX_VALUE}, with element timestamps supplied by the specified function. - * - *

              After {@link Long#MAX_VALUE}, the source never produces more output. (In practice, this - * limit should never be reached.) - * - *

              Note that the timestamps produced by {@code timestampFn} may not decrease. - */ - private UnboundedCountingSource( - long start, - long stride, - long elementsPerPeriod, - Duration period, - SerializableFunction timestampFn) { - this.start = start; - this.stride = stride; - checkArgument( - elementsPerPeriod > 0L, - "Must produce at least one element per period, got %s", - elementsPerPeriod); - this.elementsPerPeriod = elementsPerPeriod; - checkArgument( - period.getMillis() >= 0L, "Must have a non-negative period length, got %s", period); - this.period = period; - this.timestampFn = timestampFn; - } - - /** - * Returns an {@link UnboundedCountingSource} like this one with the specified period. Elements - * will be produced with an interval between them equal to the period. - */ - public UnboundedCountingSource withRate(long elementsPerPeriod, Duration period) { - return new UnboundedCountingSource(start, stride, elementsPerPeriod, period, timestampFn); - } - - /** - * Returns an {@link UnboundedCountingSource} like this one where the timestamp of output - * elements are supplied by the specified function. - * - *

              Note that timestamps produced by {@code timestampFn} may not decrease. - */ - public UnboundedCountingSource withTimestampFn( - SerializableFunction timestampFn) { - checkNotNull(timestampFn); - return new UnboundedCountingSource(start, stride, elementsPerPeriod, period, timestampFn); - } - - /** - * Splits an unbounded source {@code desiredNumSplits} ways by giving each split every - * {@code desiredNumSplits}th element that this {@link UnboundedCountingSource} - * produces. - * - *

              E.g., if a source produces all even numbers {@code [0, 2, 4, 6, 8, ...)} and we want to - * split into 3 new sources, then the new sources will produce numbers that are 6 apart and - * are offset at the start by the original stride: {@code [0, 6, 12, ...)}, - * {@code [2, 8, 14, ...)}, and {@code [4, 10, 16, ...)}. - */ - @Override - public List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception { - // Using Javadoc example, stride 2 with 3 splits becomes stride 6. - long newStride = stride * desiredNumSplits; - - ImmutableList.Builder splits = ImmutableList.builder(); - for (int i = 0; i < desiredNumSplits; ++i) { - // Starts offset by the original stride. Using Javadoc example, this generates starts of - // 0, 2, and 4. - splits.add( - new UnboundedCountingSource( - start + i * stride, newStride, elementsPerPeriod, period, timestampFn)); - } - return splits.build(); - } - - @Override - public UnboundedReader createReader( - PipelineOptions options, CounterMark checkpointMark) { - return new UnboundedCountingReader(this, checkpointMark); - } - - @Override - public Coder getCheckpointMarkCoder() { - return AvroCoder.of(CountingSource.CounterMark.class); - } - - @Override - public void validate() {} - - @Override - public Coder getDefaultOutputCoder() { - return VarLongCoder.of(); - } - } - - /** - * The reader associated with {@link UnboundedCountingSource}. - * - * @see UnboundedCountingSource - */ - private static class UnboundedCountingReader extends UnboundedReader { - private UnboundedCountingSource source; - private long current; - private Instant currentTimestamp; - private Instant firstStarted; - - public UnboundedCountingReader(UnboundedCountingSource source, CounterMark mark) { - this.source = source; - if (mark == null) { - // Because we have not emitted an element yet, and start() calls advance, we need to - // "un-advance" so that start() produces the correct output. - this.current = source.start - source.stride; - } else { - this.current = mark.getLastEmitted(); - this.firstStarted = mark.getStartTime(); - } - } - - @Override - public boolean start() throws IOException { - if (firstStarted == null) { - this.firstStarted = Instant.now(); - } - return advance(); - } - - @Override - public boolean advance() throws IOException { - // Overflow-safe check that (current + source.stride) <= LONG.MAX_VALUE. Else, stop producing. - if (Long.MAX_VALUE - source.stride < current) { - return false; - } - long nextValue = current + source.stride; - if (expectedValue() < nextValue) { - return false; - } - current = nextValue; - currentTimestamp = source.timestampFn.apply(current); - return true; - } - - private long expectedValue() { - if (source.period.getMillis() == 0L) { - return Long.MAX_VALUE; - } - double periodsElapsed = - (Instant.now().getMillis() - firstStarted.getMillis()) - / (double) source.period.getMillis(); - return (long) (source.elementsPerPeriod * periodsElapsed); - } - - @Override - public Instant getWatermark() { - return source.timestampFn.apply(current); - } - - @Override - public CounterMark getCheckpointMark() { - return new CounterMark(current, firstStarted); - } - - @Override - public UnboundedSource getCurrentSource() { - return source; - } - - @Override - public Long getCurrent() throws NoSuchElementException { - return current; - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - return currentTimestamp; - } - - @Override - public void close() throws IOException {} - - @Override - public long getSplitBacklogBytes() { - long expected = expectedValue(); - return Math.max(0L, 8 * (expected - current) / source.stride); - } - } - - /** - * The checkpoint for an unbounded {@link CountingSource} is simply the last value produced. The - * associated source object encapsulates the information needed to produce the next value. - */ - @DefaultCoder(AvroCoder.class) - public static class CounterMark implements UnboundedSource.CheckpointMark { - /** The last value emitted. */ - private final long lastEmitted; - private final Instant startTime; - - /** - * Creates a checkpoint mark reflecting the last emitted value. - */ - public CounterMark(long lastEmitted, Instant startTime) { - this.lastEmitted = lastEmitted; - this.startTime = startTime; - } - - /** - * Returns the last value emitted by the reader. - */ - public long getLastEmitted() { - return lastEmitted; - } - - /** - * Returns the time the reader was started. - */ - public Instant getStartTime() { - return startTime; - } - - ///////////////////////////////////////////////////////////////////////////////////// - - @SuppressWarnings("unused") // For AvroCoder - private CounterMark() { - this.lastEmitted = 0L; - this.startTime = Instant.now(); - } - - @Override - public void finalizeCheckpoint() throws IOException {} - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java deleted file mode 100644 index 162453cd48..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/DatastoreIO.java +++ /dev/null @@ -1,1000 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.api.services.datastore.DatastoreV1.PropertyFilter.Operator.EQUAL; -import static com.google.api.services.datastore.DatastoreV1.PropertyOrder.Direction.DESCENDING; -import static com.google.api.services.datastore.DatastoreV1.QueryResultBatch.MoreResultsType.NOT_FINISHED; -import static com.google.api.services.datastore.client.DatastoreHelper.getPropertyMap; -import static com.google.api.services.datastore.client.DatastoreHelper.makeFilter; -import static com.google.api.services.datastore.client.DatastoreHelper.makeOrder; -import static com.google.api.services.datastore.client.DatastoreHelper.makeValue; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Verify.verify; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.Sleeper; -import com.google.api.services.datastore.DatastoreV1.CommitRequest; -import com.google.api.services.datastore.DatastoreV1.Entity; -import com.google.api.services.datastore.DatastoreV1.EntityResult; -import com.google.api.services.datastore.DatastoreV1.Key; -import com.google.api.services.datastore.DatastoreV1.Key.PathElement; -import com.google.api.services.datastore.DatastoreV1.PartitionId; -import com.google.api.services.datastore.DatastoreV1.Query; -import com.google.api.services.datastore.DatastoreV1.QueryResultBatch; -import com.google.api.services.datastore.DatastoreV1.RunQueryRequest; -import com.google.api.services.datastore.DatastoreV1.RunQueryResponse; -import com.google.api.services.datastore.client.Datastore; -import com.google.api.services.datastore.client.DatastoreException; -import com.google.api.services.datastore.client.DatastoreFactory; -import com.google.api.services.datastore.client.DatastoreHelper; -import com.google.api.services.datastore.client.DatastoreOptions; -import com.google.api.services.datastore.client.QuerySplitter; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.EntityCoder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; -import com.google.cloud.dataflow.sdk.io.Sink.Writer; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.FluentBackoff; -import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; -import com.google.common.primitives.Ints; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * {@link DatastoreIO} provides an API to Read and Write {@link PCollection PCollections} of - * Google Cloud Datastore - * {@link Entity} objects. - * - *

              Google Cloud Datastore is a fully managed NoSQL data storage service. - * An {@code Entity} is an object in Datastore, analogous to a row in traditional - * database table. - * - *

              This API currently requires an authentication workaround. To use {@link DatastoreIO}, users - * must use the {@code gcloud} command line tool to get credentials for Datastore: - *

              - * $ gcloud auth login
              - * 
              - * - *

              To read a {@link PCollection} from a query to Datastore, use {@link DatastoreIO#source} and - * its methods {@link DatastoreIO.Source#withDataset} and {@link DatastoreIO.Source#withQuery} to - * specify the dataset to query and the query to read from. You can optionally provide a namespace - * to query within using {@link DatastoreIO.Source#withNamespace} or a Datastore host using - * {@link DatastoreIO.Source#withHost}. - * - *

              For example: - * - *

               {@code
              - * // Read a query from Datastore
              - * PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
              - * Query query = ...;
              - * String dataset = "...";
              - *
              - * Pipeline p = Pipeline.create(options);
              - * PCollection entities = p.apply(
              - *     Read.from(DatastoreIO.source()
              - *         .withDataset(datasetId)
              - *         .withQuery(query)
              - *         .withHost(host)));
              - * } 
              - * - *

              or: - * - *

               {@code
              - * // Read a query from Datastore using the default namespace and host
              - * PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
              - * Query query = ...;
              - * String dataset = "...";
              - *
              - * Pipeline p = Pipeline.create(options);
              - * PCollection entities = p.apply(DatastoreIO.readFrom(datasetId, query));
              - * p.run();
              - * } 
              - * - *

              Note: Normally, a Cloud Dataflow job will read from Cloud Datastore in parallel across - * many workers. However, when the {@link Query} is configured with a limit using - * {@link com.google.api.services.datastore.DatastoreV1.Query.Builder#setLimit(int)}, then - * all returned results will be read by a single Dataflow worker in order to ensure correct data. - * - *

              To write a {@link PCollection} to a Datastore, use {@link DatastoreIO#writeTo}, - * specifying the datastore to write to: - * - *

               {@code
              - * PCollection entities = ...;
              - * entities.apply(DatastoreIO.writeTo(dataset));
              - * p.run();
              - * } 
              - * - *

              To optionally change the host that is used to write to the Datastore, use {@link - * DatastoreIO#sink} to build a {@link DatastoreIO.Sink} and write to it using the {@link Write} - * transform: - * - *

               {@code
              - * PCollection entities = ...;
              - * entities.apply(Write.to(DatastoreIO.sink().withDataset(dataset).withHost(host)));
              - * } 
              - * - *

              {@link Entity Entities} in the {@code PCollection} to be written must have complete - * {@link Key Keys}. Complete {@code Keys} specify the {@code name} and {@code id} of the - * {@code Entity}, where incomplete {@code Keys} do not. A {@code namespace} other than the - * project default may be written to by specifying it in the {@code Entity} {@code Keys}. - * - *

              {@code
              - * Key.Builder keyBuilder = DatastoreHelper.makeKey(...);
              - * keyBuilder.getPartitionIdBuilder().setNamespace(namespace);
              - * }
              - * - *

              {@code Entities} will be committed as upsert (update or insert) mutations. Please read - * Entities, Properties, and - * Keys for more information about {@code Entity} keys. - * - *

              Permissions

              - * Permission requirements depend on the {@code PipelineRunner} that is used to execute the - * Dataflow job. Please refer to the documentation of corresponding {@code PipelineRunner}s for - * more details. - * - *

              Please see Cloud Datastore Sign Up - * for security and permission related information specific to Datastore. - * - * @see com.google.cloud.dataflow.sdk.runners.PipelineRunner - * - * @deprecated replaced by {@link com.google.cloud.dataflow.sdk.io.datastore.DatastoreIO} - */ - -@Deprecated -@Experimental(Experimental.Kind.SOURCE_SINK) -public class DatastoreIO { - public static final String DEFAULT_HOST = "https://www.googleapis.com"; - - /** - * Datastore has a limit of 500 mutations per batch operation, so we flush - * changes to Datastore every 500 entities. - */ - public static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; - - /** - * Returns an empty {@link DatastoreIO.Source} builder with the default {@code host}. - * Configure the {@code dataset}, {@code query}, and {@code namespace} using - * {@link DatastoreIO.Source#withDataset}, {@link DatastoreIO.Source#withQuery}, - * and {@link DatastoreIO.Source#withNamespace}. - * - * @deprecated the name and return type do not match. Use {@link #source()}. - */ - @Deprecated - public static Source read() { - return source(); - } - - /** - * Returns an empty {@link DatastoreIO.Source} builder with the default {@code host}. - * Configure the {@code dataset}, {@code query}, and {@code namespace} using - * {@link DatastoreIO.Source#withDataset}, {@link DatastoreIO.Source#withQuery}, - * and {@link DatastoreIO.Source#withNamespace}. - * - *

              The resulting {@link Source} object can be passed to {@link Read} to create a - * {@code PTransform} that will read from Datastore. - */ - public static Source source() { - return new Source(DEFAULT_HOST, null, null, null); - } - - /** - * Returns a {@code PTransform} that reads Datastore entities from the query - * against the given dataset. - */ - public static Read.Bounded readFrom(String datasetId, Query query) { - return Read.from(new Source(DEFAULT_HOST, datasetId, query, null)); - } - - /** - * Returns a {@code PTransform} that reads Datastore entities from the query - * against the given dataset and host. - * - * @deprecated prefer {@link #source()} with {@link Source#withHost}, {@link Source#withDataset}, - * {@link Source#withQuery}s. - */ - @Deprecated - public static Read.Bounded readFrom(String host, String datasetId, Query query) { - return Read.from(new Source(host, datasetId, query, null)); - } - - /** - * A {@link Source} that reads the result rows of a Datastore query as {@code Entity} objects. - */ - public static class Source extends BoundedSource { - public String getHost() { - return host; - } - - public String getDataset() { - return datasetId; - } - - public Query getQuery() { - return query; - } - - @Nullable - public String getNamespace() { - return namespace; - } - - public Source withDataset(String datasetId) { - checkNotNull(datasetId, "datasetId"); - return new Source(host, datasetId, query, namespace); - } - - /** - * Returns a new {@link Source} that reads the results of the specified query. - * - *

              Does not modify this object. - * - *

              Note: Normally, a Cloud Dataflow job will read from Cloud Datastore in parallel - * across many workers. However, when the {@link Query} is configured with a limit using - * {@link com.google.api.services.datastore.DatastoreV1.Query.Builder#setLimit(int)}, then all - * returned results will be read by a single Dataflow worker in order to ensure correct data. - */ - public Source withQuery(Query query) { - checkNotNull(query, "query"); - checkArgument(!query.hasLimit() || query.getLimit() > 0, - "Invalid query limit %s: must be positive", query.getLimit()); - return new Source(host, datasetId, query, namespace); - } - - public Source withHost(String host) { - checkNotNull(host, "host"); - return new Source(host, datasetId, query, namespace); - } - - public Source withNamespace(@Nullable String namespace) { - return new Source(host, datasetId, query, namespace); - } - - @Override - public Coder getDefaultOutputCoder() { - return EntityCoder.of(); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) { - // TODO: Perhaps this can be implemented by inspecting the query. - return false; - } - - @Override - public List splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) - throws Exception { - // Users may request a limit on the number of results. We can currently support this by - // simply disabling parallel reads and using only a single split. - if (query.hasLimit()) { - return ImmutableList.of(this); - } - - long numSplits; - try { - numSplits = Math.round(((double) getEstimatedSizeBytes(options)) / desiredBundleSizeBytes); - } catch (Exception e) { - // Fallback in case estimated size is unavailable. TODO: fix this, it's horrible. - - // 1. Try Dataflow's numWorkers, which will be 0 for other workers. - DataflowPipelineWorkerPoolOptions poolOptions = - options.as(DataflowPipelineWorkerPoolOptions.class); - if (poolOptions.getNumWorkers() > 0) { - LOG.warn("Estimated size of unavailable, using the number of workers {}", - poolOptions.getNumWorkers(), e); - numSplits = poolOptions.getNumWorkers(); - } else { - // 2. Default to 12 in the unknown case. - numSplits = 12; - } - } - - // If the desiredBundleSize or number of workers results in 1 split, simply return - // a source that reads from the original query. - if (numSplits <= 1) { - return ImmutableList.of(this); - } - - List datastoreSplits; - try { - datastoreSplits = getSplitQueries(Ints.checkedCast(numSplits), options); - } catch (IllegalArgumentException | DatastoreException e) { - LOG.warn("Unable to parallelize the given query: {}", query, e); - return ImmutableList.of(this); - } - - ImmutableList.Builder splits = ImmutableList.builder(); - for (Query splitQuery : datastoreSplits) { - splits.add(new Source(host, datasetId, splitQuery, namespace)); - } - return splits.build(); - } - - @Override - public BoundedReader createReader(PipelineOptions pipelineOptions) throws IOException { - return new DatastoreReader(this, getDatastore(pipelineOptions)); - } - - @Override - public void validate() { - checkNotNull(host, "host"); - checkNotNull(query, "query"); - checkNotNull(datasetId, "datasetId"); - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - // Datastore provides no way to get a good estimate of how large the result of a query - // will be. As a rough approximation, we attempt to fetch the statistics of the whole - // entity kind being queried, using the __Stat_Kind__ system table, assuming exactly 1 kind - // is specified in the query. - // - // See https://cloud.google.com/datastore/docs/concepts/stats - if (mockEstimateSizeBytes != null) { - return mockEstimateSizeBytes; - } - - Datastore datastore = getDatastore(options); - if (query.getKindCount() != 1) { - throw new UnsupportedOperationException( - "Can only estimate size for queries specifying exactly 1 kind."); - } - String ourKind = query.getKind(0).getName(); - long latestTimestamp = queryLatestStatisticsTimestamp(datastore); - Query.Builder query = Query.newBuilder(); - if (namespace == null) { - query.addKindBuilder().setName("__Stat_Kind__"); - } else { - query.addKindBuilder().setName("__Ns_Stat_Kind__"); - } - query.setFilter(makeFilter( - makeFilter("kind_name", EQUAL, makeValue(ourKind)).build(), - makeFilter("timestamp", EQUAL, makeValue(latestTimestamp)).build())); - RunQueryRequest request = makeRequest(query.build()); - - long now = System.currentTimeMillis(); - RunQueryResponse response = datastore.runQuery(request); - LOG.info("Query for per-kind statistics took {}ms", System.currentTimeMillis() - now); - - QueryResultBatch batch = response.getBatch(); - if (batch.getEntityResultCount() == 0) { - throw new NoSuchElementException( - "Datastore statistics for kind " + ourKind + " unavailable"); - } - Entity entity = batch.getEntityResult(0).getEntity(); - return getPropertyMap(entity).get("entity_bytes").getIntegerValue(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotDefault(DisplayData.item("host", host) - .withLabel("Datastore Service"), DEFAULT_HOST) - .addIfNotNull(DisplayData.item("dataset", datasetId) - .withLabel("Input Dataset")) - .addIfNotNull(DisplayData.item("namespace", namespace) - .withLabel("App Engine Namespace")); - - if (query != null) { - builder.add(DisplayData.item("query", query.toString()) - .withLabel("Query")); - } - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("host", host) - .add("dataset", datasetId) - .add("query", query) - .add("namespace", namespace) - .toString(); - } - - /////////////////////////////////////////////////////////////////////////////////////////// - - private static final Logger LOG = LoggerFactory.getLogger(Source.class); - private final String host; - /** Not really nullable, but it may be {@code null} for in-progress {@code Source}s. */ - @Nullable - private final String datasetId; - /** Not really nullable, but it may be {@code null} for in-progress {@code Source}s. */ - @Nullable - private final Query query; - @Nullable - private final String namespace; - - /** For testing only. TODO: This could be much cleaner with dependency injection. */ - @Nullable - private QuerySplitter mockSplitter; - @Nullable - private Long mockEstimateSizeBytes; - - /** - * Note that only {@code namespace} is really {@code @Nullable}. The other parameters may be - * {@code null} as a matter of build order, but if they are {@code null} at instantiation time, - * an error will be thrown. - */ - private Source( - String host, @Nullable String datasetId, @Nullable Query query, - @Nullable String namespace) { - this.host = checkNotNull(host, "host"); - this.datasetId = datasetId; - this.query = query; - this.namespace = namespace; - } - - /** - * A helper function to get the split queries, taking into account the optional - * {@code namespace} and whether there is a mock splitter. - */ - private List getSplitQueries(int numSplits, PipelineOptions options) - throws DatastoreException { - // If namespace is set, include it in the split request so splits are calculated accordingly. - PartitionId.Builder partitionBuilder = PartitionId.newBuilder(); - if (namespace != null) { - partitionBuilder.setNamespace(namespace); - } - - if (mockSplitter != null) { - // For testing. - return mockSplitter.getSplits(query, partitionBuilder.build(), numSplits, null); - } - - return DatastoreHelper.getQuerySplitter().getSplits( - query, partitionBuilder.build(), numSplits, getDatastore(options)); - } - - /** - * Builds a {@link RunQueryRequest} from the {@code query}, using the properties set on this - * {@code Source}. For example, sets the {@code namespace} for the request. - */ - private RunQueryRequest makeRequest(Query query) { - RunQueryRequest.Builder requestBuilder = RunQueryRequest.newBuilder().setQuery(query); - if (namespace != null) { - requestBuilder.getPartitionIdBuilder().setNamespace(namespace); - } - return requestBuilder.build(); - } - - /** - * Datastore system tables with statistics are periodically updated. This method fetches - * the latest timestamp of statistics update using the {@code __Stat_Total__} table. - */ - private long queryLatestStatisticsTimestamp(Datastore datastore) throws DatastoreException { - Query.Builder query = Query.newBuilder(); - query.addKindBuilder().setName("__Stat_Total__"); - query.addOrder(makeOrder("timestamp", DESCENDING)); - query.setLimit(1); - RunQueryRequest request = makeRequest(query.build()); - - long now = System.currentTimeMillis(); - RunQueryResponse response = datastore.runQuery(request); - LOG.info("Query for latest stats timestamp of dataset {} took {}ms", datasetId, - System.currentTimeMillis() - now); - QueryResultBatch batch = response.getBatch(); - if (batch.getEntityResultCount() == 0) { - throw new NoSuchElementException( - "Datastore total statistics for dataset " + datasetId + " unavailable"); - } - Entity entity = batch.getEntityResult(0).getEntity(); - return getPropertyMap(entity).get("timestamp").getTimestampMicrosecondsValue(); - } - - private Datastore getDatastore(PipelineOptions pipelineOptions) { - DatastoreOptions.Builder builder = - new DatastoreOptions.Builder().host(host).dataset(datasetId).initializer( - new RetryHttpRequestInitializer()); - - Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); - if (credential != null) { - builder.credential(credential); - } - return DatastoreFactory.get().create(builder.build()); - } - - /** For testing only. */ - Source withMockSplitter(QuerySplitter splitter) { - Source res = new Source(host, datasetId, query, namespace); - res.mockSplitter = splitter; - res.mockEstimateSizeBytes = mockEstimateSizeBytes; - return res; - } - - /** For testing only. */ - Source withMockEstimateSizeBytes(Long estimateSizeBytes) { - Source res = new Source(host, datasetId, query, namespace); - res.mockSplitter = mockSplitter; - res.mockEstimateSizeBytes = estimateSizeBytes; - return res; - } - } - - ///////////////////// Write Class ///////////////////////////////// - - /** - * Returns a new {@link DatastoreIO.Sink} builder using the default host. - * You need to further configure it using {@link DatastoreIO.Sink#withDataset}, and optionally - * {@link DatastoreIO.Sink#withHost} before using it in a {@link Write} transform. - * - *

              For example: {@code p.apply(Write.to(DatastoreIO.sink().withDataset(dataset)));} - */ - public static Sink sink() { - return new Sink(DEFAULT_HOST, null); - } - - /** - * Returns a new {@link Write} transform that will write to a {@link Sink}. - * - *

              For example: {@code p.apply(DatastoreIO.writeTo(dataset));} - */ - public static Write.Bound writeTo(String datasetId) { - return Write.to(sink().withDataset(datasetId)); - } - - /** - * A {@link Sink} that writes a {@link PCollection} containing - * {@link Entity Entities} to a Datastore kind. - * - */ - public static class Sink extends com.google.cloud.dataflow.sdk.io.Sink { - final String host; - final String datasetId; - - /** - * Returns a {@link Sink} that is like this one, but will write to the specified dataset. - */ - public Sink withDataset(String datasetId) { - checkNotNull(datasetId, "datasetId"); - return new Sink(host, datasetId); - } - - /** - * Returns a {@link Sink} that is like this one, but will use the given host. If not specified, - * the {@link DatastoreIO#DEFAULT_HOST default host} will be used. - */ - public Sink withHost(String host) { - checkNotNull(host, "host"); - return new Sink(host, datasetId); - } - - /** - * Constructs a Sink with given host and dataset. - */ - protected Sink(String host, String datasetId) { - this.host = checkNotNull(host, "host"); - this.datasetId = datasetId; - } - - /** - * Ensures the host and dataset are set. - */ - @Override - public void validate(PipelineOptions options) { - checkNotNull( - host, "Host is a required parameter. Please use withHost to set the host."); - checkNotNull( - datasetId, - "Dataset ID is a required parameter. Please use withDataset to to set the datasetId."); - } - - @Override - public DatastoreWriteOperation createWriteOperation(PipelineOptions options) { - return new DatastoreWriteOperation(this); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotDefault(DisplayData.item("host", host) - .withLabel("Datastore Service"), DEFAULT_HOST) - .addIfNotNull(DisplayData.item("dataset", datasetId) - .withLabel("Output Dataset")); - } - } - - /** - * A {@link WriteOperation} that will manage a parallel write to a Datastore sink. - */ - private static class DatastoreWriteOperation - extends WriteOperation { - private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriteOperation.class); - - private final DatastoreIO.Sink sink; - - public DatastoreWriteOperation(DatastoreIO.Sink sink) { - this.sink = sink; - } - - @Override - public Coder getWriterResultCoder() { - return SerializableCoder.of(DatastoreWriteResult.class); - } - - @Override - public void initialize(PipelineOptions options) throws Exception {} - - /** - * Finalizes the write. Logs the number of entities written to the Datastore. - */ - @Override - public void finalize(Iterable writerResults, PipelineOptions options) - throws Exception { - long totalEntities = 0; - for (DatastoreWriteResult result : writerResults) { - totalEntities += result.entitiesWritten; - } - LOG.info("Wrote {} elements.", totalEntities); - } - - @Override - public DatastoreWriter createWriter(PipelineOptions options) throws Exception { - DatastoreOptions.Builder builder = - new DatastoreOptions.Builder() - .host(sink.host) - .dataset(sink.datasetId) - .initializer(new RetryHttpRequestInitializer()); - Credential credential = options.as(GcpOptions.class).getGcpCredential(); - if (credential != null) { - builder.credential(credential); - } - Datastore datastore = DatastoreFactory.get().create(builder.build()); - - return new DatastoreWriter(this, datastore); - } - - @Override - public DatastoreIO.Sink getSink() { - return sink; - } - } - - /** - * {@link Writer} that writes entities to a Datastore Sink. Entities are written in batches, - * where the maximum batch size is {@link DatastoreIO#DATASTORE_BATCH_UPDATE_LIMIT}. Entities - * are committed as upsert mutations (either update if the key already exists, or insert if it is - * a new key). If an entity does not have a complete key (i.e., it has no name or id), the bundle - * will fail. - * - *

              See - * Datastore: Entities, Properties, and Keys for information about entity keys and upsert - * mutations. - * - *

              Commits are non-transactional. If a commit fails because of a conflict over an entity - * group, the commit will be retried (up to {@link DatastoreIO#DATASTORE_BATCH_UPDATE_LIMIT} - * times). - * - *

              Visible for testing purposes. - */ - static class DatastoreWriter extends Writer { - private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriter.class); - private final DatastoreWriteOperation writeOp; - private final Datastore datastore; - private long totalWritten = 0; - - // Visible for testing. - final List entities = new ArrayList<>(); - - /** - * Since a bundle is written in batches, we should retry the commit of a batch in order to - * prevent transient errors from causing the bundle to fail. - */ - private static final int MAX_RETRIES = 5; - private static final FluentBackoff BUNDLE_WRITE_BACKOFF = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RETRIES).withInitialBackoff(Duration.standardSeconds(5)); - - /** - * Returns true if a Datastore key is complete. A key is complete if its last element - * has either an id or a name. - */ - static boolean isValidKey(Key key) { - List elementList = key.getPathElementList(); - if (elementList.isEmpty()) { - return false; - } - PathElement lastElement = elementList.get(elementList.size() - 1); - return (lastElement.hasId() || lastElement.hasName()); - } - - // Visible for testing - DatastoreWriter(DatastoreWriteOperation writeOp, Datastore datastore) { - this.writeOp = writeOp; - this.datastore = datastore; - } - - @Override - public void open(String uId) throws Exception {} - - /** - * Writes an entity to the Datastore. Writes are batched, up to {@link - * DatastoreIO#DATASTORE_BATCH_UPDATE_LIMIT}. If an entity does not have a complete key, an - * {@link IllegalArgumentException} will be thrown. - */ - @Override - public void write(Entity value) throws Exception { - // Verify that the entity to write has a complete key. - if (!isValidKey(value.getKey())) { - throw new IllegalArgumentException( - "Entities to be written to the Datastore must have complete keys"); - } - - entities.add(value); - - if (entities.size() >= DatastoreIO.DATASTORE_BATCH_UPDATE_LIMIT) { - flushBatch(); - } - } - - /** - * Flushes any pending batch writes and returns a DatastoreWriteResult. - */ - @Override - public DatastoreWriteResult close() throws Exception { - if (entities.size() > 0) { - flushBatch(); - } - return new DatastoreWriteResult(totalWritten); - } - - @Override - public DatastoreWriteOperation getWriteOperation() { - return writeOp; - } - - /** - * Writes a batch of entities to the Datastore. - * - *

              If a commit fails, it will be retried (up to {@link DatastoreWriter#MAX_RETRIES} - * times). All entities in the batch will be committed again, even if the commit was partially - * successful. If the retry limit is exceeded, the last exception from the Datastore will be - * thrown. - * - * @throws DatastoreException if the commit fails or IOException or InterruptedException if - * backing off between retries fails. - */ - private void flushBatch() throws DatastoreException, IOException, InterruptedException { - LOG.debug("Writing batch of {} entities", entities.size()); - Sleeper sleeper = Sleeper.DEFAULT; - BackOff backoff = BUNDLE_WRITE_BACKOFF.backoff(); - - while (true) { - // Batch upsert entities. - try { - CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); - commitRequest.getMutationBuilder().addAllUpsert(entities); - commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); - datastore.commit(commitRequest.build()); - - // Break if the commit threw no exception. - break; - - } catch (DatastoreException exception) { - // Only log the code and message for potentially-transient errors. The entire exception - // will be propagated upon the last retry. - LOG.error("Error writing to the Datastore ({}): {}", exception.getCode(), - exception.getMessage()); - if (!BackOffUtils.next(sleeper, backoff)) { - LOG.error("Aborting after {} retries.", MAX_RETRIES); - throw exception; - } - } - } - totalWritten += entities.size(); - LOG.debug("Successfully wrote {} entities", entities.size()); - entities.clear(); - } - } - - private static class DatastoreWriteResult implements Serializable { - final long entitiesWritten; - - public DatastoreWriteResult(long recordsWritten) { - this.entitiesWritten = recordsWritten; - } - } - - /** - * A {@link Source.Reader} over the records from a query of the datastore. - * - *

              Timestamped records are currently not supported. - * All records implicitly have the timestamp of {@code BoundedWindow.TIMESTAMP_MIN_VALUE}. - */ - public static class DatastoreReader extends BoundedSource.BoundedReader { - private final Source source; - - /** - * Datastore to read from. - */ - private final Datastore datastore; - - /** - * True if more results may be available. - */ - private boolean moreResults; - - /** - * Iterator over records. - */ - private java.util.Iterator entities; - - /** - * Current batch of query results. - */ - private QueryResultBatch currentBatch; - - /** - * Maximum number of results to request per query. - * - *

              Must be set, or it may result in an I/O error when querying - * Cloud Datastore. - */ - private static final int QUERY_BATCH_LIMIT = 500; - - /** - * Remaining user-requested limit on the number of sources to return. If the user did not set a - * limit, then this variable will always have the value {@link Integer#MAX_VALUE} and will never - * be decremented. - */ - private int userLimit; - - private volatile boolean done = false; - - private Entity currentEntity; - - /** - * Returns a DatastoreReader with Source and Datastore object set. - * - * @param datastore a datastore connection to use. - */ - public DatastoreReader(Source source, Datastore datastore) { - this.source = source; - this.datastore = datastore; - // If the user set a limit on the query, remember it. Otherwise pin to MAX_VALUE. - userLimit = source.query.hasLimit() ? source.query.getLimit() : Integer.MAX_VALUE; - } - - @Override - public Entity getCurrent() { - return currentEntity; - } - - @Override - public final long getSplitPointsConsumed() { - return done ? 1 : 0; - } - - @Override - public final long getSplitPointsRemaining() { - return done ? 0 : 1; - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - if (entities == null || (!entities.hasNext() && moreResults)) { - try { - entities = getIteratorAndMoveCursor(); - } catch (DatastoreException e) { - throw new IOException(e); - } - } - - if (entities == null || !entities.hasNext()) { - currentEntity = null; - done = true; - return false; - } - - currentEntity = entities.next().getEntity(); - return true; - } - - @Override - public void close() throws IOException { - // Nothing - } - - @Override - public DatastoreIO.Source getCurrentSource() { - return source; - } - - @Override - public DatastoreIO.Source splitAtFraction(double fraction) { - // Not supported. - return null; - } - - @Override - public Double getFractionConsumed() { - // Not supported. - return null; - } - - /** - * Returns an iterator over the next batch of records for the query - * and updates the cursor to get the next batch as needed. - * Query has specified limit and offset from InputSplit. - */ - private Iterator getIteratorAndMoveCursor() throws DatastoreException { - Query.Builder query = source.query.toBuilder().clone(); - query.setLimit(Math.min(userLimit, QUERY_BATCH_LIMIT)); - if (currentBatch != null && currentBatch.hasEndCursor()) { - query.setStartCursor(currentBatch.getEndCursor()); - } - - RunQueryRequest request = source.makeRequest(query.build()); - RunQueryResponse response = datastore.runQuery(request); - - currentBatch = response.getBatch(); - - // MORE_RESULTS_AFTER_LIMIT is not implemented yet: - // https://groups.google.com/forum/#!topic/gcd-discuss/iNs6M1jA2Vw, so - // use result count to determine if more results might exist. - int numFetch = currentBatch.getEntityResultCount(); - if (source.query.hasLimit()) { - verify(userLimit >= numFetch, - "Expected userLimit %s >= numFetch %s, because query limit %s should be <= userLimit", - userLimit, numFetch, query.getLimit()); - userLimit -= numFetch; - } - moreResults = - // User-limit does not exist (so userLimit == MAX_VALUE) and/or has not been satisfied. - (userLimit > 0) - // All indications from the API are that there are/may be more results. - && ((numFetch == QUERY_BATCH_LIMIT) || (currentBatch.getMoreResults() == NOT_FINISHED)); - - // May receive a batch of 0 results if the number of records is a multiple - // of the request limit. - if (numFetch == 0) { - return null; - } - - return currentBatch.getEntityResultList().iterator(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java deleted file mode 100644 index c644a8adfa..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSink.java +++ /dev/null @@ -1,720 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.FileIOChannelFactory; -import com.google.cloud.dataflow.sdk.util.GcsIOChannelFactory; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.GcsUtil.GcsUtilFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.Serializable; -import java.nio.channels.WritableByteChannel; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Abstract {@link Sink} for file-based output. An implementation of FileBasedSink writes file-based - * output and defines the format of output files (how values are written, headers/footers, MIME - * type, etc.). - * - *

              At pipeline construction time, the methods of FileBasedSink are called to validate the sink - * and to create a {@link Sink.WriteOperation} that manages the process of writing to the sink. - * - *

              The process of writing to file-based sink is as follows: - *

                - *
              1. An optional subclass-defined initialization, - *
              2. a parallel write of bundles to temporary files, and finally, - *
              3. these temporary files are renamed with final output filenames. - *
              - * - *

              Supported file systems are those registered with {@link IOChannelUtils}. - * - * @param the type of values written to the sink. - */ -public abstract class FileBasedSink extends Sink { - /** - * Base filename for final output files. - */ - protected final ValueProvider baseOutputFilename; - - /** - * The extension to be used for the final output files. - */ - protected final String extension; - - /** - * Naming template for output files. See {@link ShardNameTemplate} for a description of - * possible naming templates. Default is {@link ShardNameTemplate#INDEX_OF_MAX}. - */ - protected final String fileNamingTemplate; - - /** - * Construct a FileBasedSink with the given base output filename and extension. - */ - public FileBasedSink(String baseOutputFilename, String extension) { - this(StaticValueProvider.of(baseOutputFilename), extension, ShardNameTemplate.INDEX_OF_MAX); - } - - /** - * Construct a FileBasedSink with the given base output filename, extension, and file naming - * template. - * - *

              See {@link ShardNameTemplate} for a description of file naming templates. - */ - public FileBasedSink(String baseOutputFilename, String extension, String fileNamingTemplate) { - this(StaticValueProvider.of(baseOutputFilename), extension, fileNamingTemplate); - } - - /** - * Construct a FileBasedSink with the given base output filename, extension, and file naming - * template. - * - *

              See {@link ShardNameTemplate} for a description of file naming templates. - */ - public FileBasedSink(ValueProvider baseOutputFilename, - String extension, String fileNamingTemplate) { - this.baseOutputFilename = baseOutputFilename; - this.extension = extension; - this.fileNamingTemplate = fileNamingTemplate; - } - - /** - * Returns the base output filename for this file based sink. - */ - public String getBaseOutputFilename() { - return baseOutputFilename.get(); - } - - /** - * Returns the base output filename for this file based sink. - */ - public ValueProvider getBaseOutputFilenameProvider() { - return baseOutputFilename; - } - - /** - * Perform pipeline-construction-time validation. The default implementation is a no-op. - * Subclasses should override to ensure the sink is valid and can be written to. It is recommended - * to use {@link com.google.common.base.Preconditions} in the implementation of this method. - */ - @Override - public void validate(PipelineOptions options) {} - - /** - * Return a subclass of {@link FileBasedSink.FileBasedWriteOperation} that will manage the write - * to the sink. - */ - @Override - public abstract FileBasedWriteOperation createWriteOperation(PipelineOptions options); - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - String fileNamePattern = String.format("%s%s%s", - baseOutputFilename.isAccessible() - ? baseOutputFilename.get() : baseOutputFilename.toString(), - fileNamingTemplate, getFileExtension(extension)); - builder.add(DisplayData.item("fileNamePattern", fileNamePattern) - .withLabel("File Name Pattern")); - } - - /** - * Returns the file extension to be used. If the user did not request a file - * extension then this method returns the empty string. Otherwise this method - * adds a {@code "."} to the beginning of the users extension if one is not present. - */ - private static String getFileExtension(String usersExtension) { - if (usersExtension == null || usersExtension.isEmpty()) { - return ""; - } - if (usersExtension.startsWith(".")) { - return usersExtension; - } - return "." + usersExtension; - } - - /** - * Abstract {@link Sink.WriteOperation} that manages the process of writing to a - * {@link FileBasedSink}. - * - *

              The primary responsibilities of the FileBasedWriteOperation is the management of output - * files. During a write, {@link FileBasedSink.FileBasedWriter}s write bundles to temporary file - * locations. After the bundles have been written, - *

                - *
              1. {@link FileBasedSink.FileBasedWriteOperation#finalize} is given a list of the temporary - * files containing the output bundles. - *
              2. During finalize, these temporary files are copied to final output locations and named - * according to a file naming template. - *
              3. Finally, any temporary files that were created during the write are removed. - *
              - * - *

              Subclass implementations of FileBasedWriteOperation must implement - * {@link FileBasedSink.FileBasedWriteOperation#createWriter} to return a concrete - * FileBasedSinkWriter. - * - *

              Temporary and Output File Naming:

              During the write, bundles are written to temporary - * files using the baseTemporaryFilename that can be provided via the constructor of - * FileBasedWriteOperation. These temporary files will be named - * {@code {baseTemporaryFilename}-temp-{bundleId}}, where bundleId is the unique id of the bundle. - * For example, if baseTemporaryFilename is "gs://my-bucket/my_temp_output", the output for a - * bundle with bundle id 15723 will be "gs://my-bucket/my_temp_output-temp-15723". - * - *

              Final output files are written to baseOutputFilename with the format - * {@code {baseOutputFilename}-0000i-of-0000n.{extension}} where n is the total number of bundles - * written and extension is the file extension. Both baseOutputFilename and extension are required - * constructor arguments. - * - *

              Subclass implementations can change the file naming template by supplying a value for - * {@link FileBasedSink#fileNamingTemplate}. - * - *

              Temporary Bundle File Handling:

              - * - *

              {@link FileBasedSink.FileBasedWriteOperation#temporaryFileRetention} controls the behavior - * for managing temporary files. By default, temporary files will be removed. Subclasses can - * provide a different value to the constructor. - * - *

              Note that in the case of permanent failure of a bundle's write, no clean up of temporary - * files will occur. - * - *

              If there are no elements in the PCollection being written, no output will be generated. - * - * @param the type of values written to the sink. - */ - public abstract static class FileBasedWriteOperation extends WriteOperation { - private static final Logger LOG = LoggerFactory.getLogger(FileBasedWriteOperation.class); - - /** - * Options for handling of temporary output files. - */ - public enum TemporaryFileRetention { - KEEP, - REMOVE; - } - - /** - * The Sink that this WriteOperation will write to. - */ - protected final FileBasedSink sink; - - /** - * Option to keep or remove temporary output files. - */ - protected final TemporaryFileRetention temporaryFileRetention; - - /** - * Base filename used for temporary output files. Default is the baseOutputFilename. - */ - protected final ValueProvider baseTemporaryFilename; - - /** - * Name separator for temporary files. Temporary files will be named - * {@code {baseTemporaryFilename}-temp-{bundleId}}. - */ - protected static final String TEMPORARY_FILENAME_SEPARATOR = "-temp-"; - - /** - * Build a temporary filename using the temporary filename separator with the given prefix and - * suffix. - */ - protected static final String buildTemporaryFilename(String prefix, String suffix) { - return prefix + FileBasedWriteOperation.TEMPORARY_FILENAME_SEPARATOR + suffix; - } - - /** - * Construct a FileBasedWriteOperation using the same base filename for both temporary and - * output files. - * - * @param sink the FileBasedSink that will be used to configure this write operation. - */ - public FileBasedWriteOperation(FileBasedSink sink) { - this(sink, sink.getBaseOutputFilenameProvider(), TemporaryFileRetention.REMOVE); - } - - /** - * Construct a FileBasedWriteOperation. - * - * @param sink the FileBasedSink that will be used to configure this write operation. - * @param baseTemporaryFilename the base filename to be used for temporary output files. - */ - public FileBasedWriteOperation(FileBasedSink sink, String baseTemporaryFilename) { - this(sink, StaticValueProvider.of(baseTemporaryFilename), TemporaryFileRetention.REMOVE); - } - - /** - * Create a new FileBasedWriteOperation. - * - * @param sink the FileBasedSink that will be used to configure this write operation. - * @param baseTemporaryFilename the base filename to be used for temporary output files. - * @param temporaryFileRetention defines how temporary files are handled. - */ - public FileBasedWriteOperation(FileBasedSink sink, String baseTemporaryFilename, - TemporaryFileRetention temporaryFileRetention) { - this(sink, StaticValueProvider.of(baseTemporaryFilename), temporaryFileRetention); - } - - private FileBasedWriteOperation(FileBasedSink sink, - ValueProvider baseTemporaryFilename, - TemporaryFileRetention temporaryFileRetention) { - this.sink = sink; - this.baseTemporaryFilename = baseTemporaryFilename; - this.temporaryFileRetention = temporaryFileRetention; - } - - /** - * Clients must implement to return a subclass of {@link FileBasedSink.FileBasedWriter}. This - * method must satisfy the restrictions placed on implementations of - * {@link Sink.WriteOperation#createWriter}. Namely, it must not mutate the state of the object. - */ - @Override - public abstract FileBasedWriter createWriter(PipelineOptions options) throws Exception; - - /** - * Initialization of the sink. Default implementation is a no-op. May be overridden by subclass - * implementations to perform initialization of the sink at pipeline runtime. This method must - * be idempotent and is subject to the same implementation restrictions as - * {@link Sink.WriteOperation#initialize}. - */ - @Override - public void initialize(PipelineOptions options) throws Exception {} - - /** - * Finalizes writing by copying temporary output files to their final location and optionally - * removing temporary files. - * - *

              Finalization may be overridden by subclass implementations to perform customized - * finalization (e.g., initiating some operation on output bundles, merging them, etc.). - * {@code writerResults} contains the filenames of written bundles. - * - *

              If subclasses override this method, they must guarantee that its implementation is - * idempotent, as it may be executed multiple times in the case of failure or for redundancy. It - * is a best practice to attempt to try to make this method atomic. - * - * @param writerResults the results of writes (FileResult). - */ - @Override - public void finalize(Iterable writerResults, PipelineOptions options) - throws Exception { - // Collect names of temporary files and rename them. - List files = new ArrayList<>(); - for (FileResult result : writerResults) { - LOG.debug("Temporary bundle output file {} will be copied.", result.getFilename()); - files.add(result.getFilename()); - } - copyToOutputFiles(files, options); - - // Optionally remove temporary files. - if (temporaryFileRetention == TemporaryFileRetention.REMOVE) { - removeTemporaryFiles(files, options); - } - } - - /** - * Copy temporary files to final output filenames using the file naming template. - * - *

              Can be called from subclasses that override {@link FileBasedWriteOperation#finalize}. - * - *

              Files will be named according to the file naming template. The order of the output files - * will be the same as the sorted order of the input filenames. In other words, if the input - * filenames are ["C", "A", "B"], baseOutputFilename is "file", the extension is ".txt", and - * the fileNamingTemplate is "-SSS-of-NNN", the contents of A will be copied to - * file-000-of-003.txt, the contents of B will be copied to file-001-of-003.txt, etc. - * - * @param filenames the filenames of temporary files. - * @return a list containing the names of final output files. - */ - protected final List copyToOutputFiles(List filenames, PipelineOptions options) - throws IOException { - int numFiles = filenames.size(); - List srcFilenames = new ArrayList<>(); - List destFilenames = generateDestinationFilenames(numFiles); - - // Sort files for copying. - srcFilenames.addAll(filenames); - Collections.sort(srcFilenames); - - if (numFiles > 0) { - LOG.debug("Copying {} files.", numFiles); - FileOperations fileOperations = - FileOperationsFactory.getFileOperations(destFilenames.get(0), options); - fileOperations.copy(srcFilenames, destFilenames); - } else { - LOG.info("No output files to write."); - } - - return destFilenames; - } - - /** - * Generate output bundle filenames. - */ - protected final List generateDestinationFilenames(int numFiles) { - List destFilenames = new ArrayList<>(); - String extension = getSink().extension; - String baseOutputFilename = getSink().baseOutputFilename.get(); - String fileNamingTemplate = getSink().fileNamingTemplate; - - String suffix = getFileExtension(extension); - for (int i = 0; i < numFiles; i++) { - destFilenames.add(IOChannelUtils.constructName( - baseOutputFilename, fileNamingTemplate, suffix, i, numFiles)); - } - return destFilenames; - } - - /** - * Use {@link #removeTemporaryFiles(Collection, PipelineOptions)} instead. - */ - @Deprecated - protected final void removeTemporaryFiles(PipelineOptions options) throws IOException { - removeTemporaryFiles(Collections.emptyList(), options); - } - - /** - * Removes temporary output files. Uses the temporary filename to find files to remove. - * - *

              Additionally, to partially mitigate the effects of filesystems with eventually-consistent - * directory matching APIs, takes a list of files that are known to exist - i.e. removes the - * union of the known files and files that the filesystem says exist in the directory. - * - *

              Assumes that, if globbing had been strongly consistent, it would have matched all - * of knownFiles - i.e. on a strongly consistent filesystem, knownFiles can be ignored. - * - *

              Can be called from subclasses that override {@link FileBasedWriteOperation#finalize}. - * Note:If finalize is overridden and does not rename or otherwise finalize - * temporary files, this method will remove them. - */ - protected final void removeTemporaryFiles( - Collection knownFiles, PipelineOptions options) throws IOException { - String pattern = buildTemporaryFilename(baseTemporaryFilename.get(), "*"); - LOG.debug("Finding temporary bundle output files matching {}.", pattern); - FileOperations fileOperations = FileOperationsFactory.getFileOperations(pattern, options); - IOChannelFactory factory = IOChannelUtils.getFactory(pattern); - Collection matches = factory.match(pattern); - Set allMatches = new HashSet<>(matches); - allMatches.addAll(knownFiles); - LOG.debug( - "Removing {} temporary files matching {} ({} matched glob, {} additional known files)", - allMatches.size(), - pattern, - matches.size(), - allMatches.size() - matches.size()); - fileOperations.remove(allMatches); - } - - /** - * Provides a coder for {@link FileBasedSink.FileResult}. - */ - @Override - public Coder getWriterResultCoder() { - return SerializableCoder.of(FileResult.class); - } - - /** - * Returns the FileBasedSink for this write operation. - */ - @Override - public FileBasedSink getSink() { - return sink; - } - } - - /** - * Abstract {@link Sink.Writer} that writes a bundle to a {@link FileBasedSink}. Subclass - * implementations provide a method that can write a single value to a {@link WritableByteChannel} - * ({@link Sink.Writer#write}). - * - *

              Subclass implementations may also override methods that write headers and footers before and - * after the values in a bundle, respectively, as well as provide a MIME type for the output - * channel. - * - *

              Multiple FileBasedWriter instances may be created on the same worker, and therefore any - * access to static members or methods should be thread safe. - * - * @param the type of values to write. - */ - public abstract static class FileBasedWriter extends Writer { - private static final Logger LOG = LoggerFactory.getLogger(FileBasedWriter.class); - - final FileBasedWriteOperation writeOperation; - - /** - * Unique id for this output bundle. - */ - private String id; - - /** - * The filename of the output bundle. Equal to the - * {@link FileBasedSink.FileBasedWriteOperation#TEMPORARY_FILENAME_SEPARATOR} and id appended to - * the baseName. - */ - private String filename; - - /** - * The channel to write to. - */ - private WritableByteChannel channel; - - /** - * The MIME type used in the creation of the output channel (if the file system supports it). - * - *

              GCS, for example, supports writing files with Content-Type metadata. - * - *

              May be overridden. Default is {@link MimeTypes#TEXT}. See {@link MimeTypes} for other - * options. - */ - protected String mimeType = MimeTypes.TEXT; - - /** - * Construct a new FileBasedWriter with a base filename. - */ - public FileBasedWriter(FileBasedWriteOperation writeOperation) { - checkNotNull(writeOperation); - this.writeOperation = writeOperation; - } - - /** - * Called with the channel that a subclass will write its header, footer, and values to. - * Subclasses should either keep a reference to the channel provided or create and keep a - * reference to an appropriate object that they will use to write to it. - * - *

              Called before any subsequent calls to writeHeader, writeFooter, and write. - */ - protected abstract void prepareWrite(WritableByteChannel channel) throws Exception; - - /** - * Writes header at the beginning of output files. Nothing by default; subclasses may override. - */ - protected void writeHeader() throws Exception {} - - /** - * Writes footer at the end of output files. Nothing by default; subclasses may override. - */ - protected void writeFooter() throws Exception {} - - /** - * Opens the channel. - */ - @Override - public final void open(String uId) throws Exception { - this.id = uId; - filename = FileBasedWriteOperation.buildTemporaryFilename( - getWriteOperation().baseTemporaryFilename.get(), uId); - LOG.debug("Opening {}.", filename); - channel = IOChannelUtils.create(filename, mimeType); - try { - prepareWrite(channel); - LOG.debug("Writing header to {}.", filename); - writeHeader(); - } catch (Exception e) { - // The caller shouldn't have to close() this Writer if it fails to open(), so close the - // channel if prepareWrite() or writeHeader() fails. - try { - LOG.error("Writing header to {} failed, closing channel.", filename); - channel.close(); - } catch (IOException closeException) { - // Log exception and mask it. - LOG.error("Closing channel for {} failed: {}", filename, closeException.getMessage()); - } - // Throw the exception that caused the write to fail. - throw e; - } - LOG.debug("Starting write of bundle {} to {}.", this.id, filename); - } - - /** - * Closes the channel and return the bundle result. - */ - @Override - public final FileResult close() throws Exception { - try (WritableByteChannel theChannel = channel) { - LOG.debug("Writing footer to {}.", filename); - writeFooter(); - } - FileResult result = new FileResult(filename); - LOG.debug("Result for bundle {}: {}", this.id, filename); - return result; - } - - /** - * Return the FileBasedWriteOperation that this Writer belongs to. - */ - @Override - public FileBasedWriteOperation getWriteOperation() { - return writeOperation; - } - } - - /** - * Result of a single bundle write. Contains the filename of the bundle. - */ - public static final class FileResult implements Serializable { - private final String filename; - - public FileResult(String filename) { - this.filename = filename; - } - - public String getFilename() { - return filename; - } - } - - // File system operations - // Warning: These class are purposefully private and will be replaced by more robust file I/O - // utilities. Not for use outside FileBasedSink. - - /** - * Factory for FileOperations. - */ - private static class FileOperationsFactory { - /** - * Return a FileOperations implementation based on which IOChannel would be used to write to a - * location specification (not necessarily a filename, as it may contain wildcards). - * - *

              Only supports File and GCS locations (currently, the only factories registered with - * IOChannelUtils). For other locations, an exception is thrown. - */ - public static FileOperations getFileOperations(String spec, PipelineOptions options) - throws IOException { - IOChannelFactory factory = IOChannelUtils.getFactory(spec); - if (factory instanceof GcsIOChannelFactory) { - return new GcsOperations(options); - } else if (factory instanceof FileIOChannelFactory) { - return new LocalFileOperations(); - } else { - throw new IOException("Unrecognized file system."); - } - } - } - - /** - * Copy and Remove operations for files. Operations behave like remove-if-existing and - * copy-if-existing and do not throw exceptions on file not found to enable retries of these - * operations in the case of transient error. - */ - private interface FileOperations { - /** - * Copy a collection of files from one location to another. - * - *

              The number of source filenames must equal the number of destination filenames. - * - * @param srcFilenames the source filenames. - * @param destFilenames the destination filenames. - */ - void copy(List srcFilenames, List destFilenames) throws IOException; - - /** - * Remove a collection of files. - */ - void remove(Collection filenames) throws IOException; - } - - /** - * GCS file system operations. - */ - private static class GcsOperations implements FileOperations { - private final GcsUtil gcsUtil; - - public GcsOperations(PipelineOptions options) { - gcsUtil = new GcsUtilFactory().create(options); - } - - @Override - public void copy(List srcFilenames, List destFilenames) throws IOException { - gcsUtil.copy(srcFilenames, destFilenames); - } - - @Override - public void remove(Collection filenames) throws IOException { - gcsUtil.remove(filenames); - } - } - - /** - * File systems supported by {@link Files}. - */ - private static class LocalFileOperations implements FileOperations { - private static final Logger LOG = LoggerFactory.getLogger(LocalFileOperations.class); - - @Override - public void copy(List srcFilenames, List destFilenames) throws IOException { - checkArgument( - srcFilenames.size() == destFilenames.size(), - "Number of source files %s must equal number of destination files %s", - srcFilenames.size(), - destFilenames.size()); - int numFiles = srcFilenames.size(); - for (int i = 0; i < numFiles; i++) { - String src = srcFilenames.get(i); - String dst = destFilenames.get(i); - LOG.debug("Copying {} to {}", src, dst); - copyOne(src, dst); - } - } - - private void copyOne(String source, String destination) throws IOException { - try { - // Copy the source file, replacing the existing destination. - Files.copy(Paths.get(source), Paths.get(destination), StandardCopyOption.REPLACE_EXISTING); - } catch (NoSuchFileException e) { - LOG.debug("{} does not exist.", source); - // Suppress exception if file does not exist. - } - } - - @Override - public void remove(Collection filenames) throws IOException { - for (String filename : filenames) { - LOG.debug("Removing file {}", filename); - removeOne(filename); - } - } - - private void removeOne(String filename) throws IOException { - // Delete the file if it exists. - boolean exists = Files.deleteIfExists(Paths.get(filename)); - if (!exists) { - LOG.debug("{} does not exist.", filename); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java deleted file mode 100644 index 4fb996ffa0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/FileBasedSource.java +++ /dev/null @@ -1,684 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.IOChannelFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SeekableByteChannel; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; - -/** - * A common base class for all file-based {@link Source}s. Extend this class to implement your own - * file-based custom source. - * - *

              A file-based {@code Source} is a {@code Source} backed by a file pattern defined as a Java - * glob, a single file, or a offset range for a single file. See {@link OffsetBasedSource} and - * {@link com.google.cloud.dataflow.sdk.io.range.RangeTracker} for semantics of offset ranges. - * - *

              This source stores a {@code String} that is an {@link IOChannelFactory} specification for a - * file or file pattern. There should be an {@code IOChannelFactory} defined for the file - * specification provided. Please refer to {@link IOChannelUtils} and {@link IOChannelFactory} for - * more information on this. - * - *

              In addition to the methods left abstract from {@code BoundedSource}, subclasses must implement - * methods to create a sub-source and a reader for a range of a single file - - * {@link #createForSubrangeOfFile} and {@link #createSingleFileReader}. Please refer to - * {@link XmlSource} for an example implementation of {@code FileBasedSource}. - * - * @param Type of records represented by the source. - */ -public abstract class FileBasedSource extends OffsetBasedSource { - private static final Logger LOG = LoggerFactory.getLogger(FileBasedSource.class); - private static final float FRACTION_OF_FILES_TO_STAT = 0.01f; - - // Package-private for testing - static final int MAX_NUMBER_OF_FILES_FOR_AN_EXACT_STAT = 100; - - // Size of the thread pool to be used for performing file operations in parallel. - // Package-private for testing. - static final int THREAD_POOL_SIZE = 128; - - private final ValueProvider fileOrPatternSpec; - private final Mode mode; - - /** - * A given {@code FileBasedSource} represents a file resource of one of these types. - */ - public enum Mode { - FILEPATTERN, - SINGLE_FILE_OR_SUBRANGE - } - - /** - * Create a {@code FileBaseSource} based on a file or a file pattern specification. This - * constructor must be used when creating a new {@code FileBasedSource} for a file pattern. - * - *

              See {@link OffsetBasedSource} for a detailed description of {@code minBundleSize}. - * - * @param fileOrPatternSpec {@link IOChannelFactory} specification of file or file pattern - * represented by the {@link FileBasedSource}. - * @param minBundleSize minimum bundle size in bytes. - */ - public FileBasedSource(String fileOrPatternSpec, long minBundleSize) { - this(StaticValueProvider.of(fileOrPatternSpec), minBundleSize); - } - - - /** - * Create a {@code FileBaseSource} based on a file or a file pattern specification. - * Same as the {@code String} constructor, but accepting a {@link ValueProvider} - * to allow for runtime configuration of the source. - */ - public FileBasedSource(ValueProvider fileOrPatternSpec, long minBundleSize) { - super(0, Long.MAX_VALUE, minBundleSize); - mode = Mode.FILEPATTERN; - this.fileOrPatternSpec = fileOrPatternSpec; - } - - /** - * Create a {@code FileBasedSource} based on a single file. This constructor must be used when - * creating a new {@code FileBasedSource} for a subrange of a single file. - * Additionally, this constructor must be used to create new {@code FileBasedSource}s when - * subclasses implement the method {@link #createForSubrangeOfFile}. - * - *

              See {@link OffsetBasedSource} for detailed descriptions of {@code minBundleSize}, - * {@code startOffset}, and {@code endOffset}. - * - * @param fileName {@link IOChannelFactory} specification of the file represented by the - * {@link FileBasedSource}. - * @param minBundleSize minimum bundle size in bytes. - * @param startOffset starting byte offset. - * @param endOffset ending byte offset. If the specified value {@code >= #getMaxEndOffset()} it - * implies {@code #getMaxEndOffSet()}. - */ - public FileBasedSource(String fileName, long minBundleSize, - long startOffset, long endOffset) { - super(startOffset, endOffset, minBundleSize); - mode = Mode.SINGLE_FILE_OR_SUBRANGE; - this.fileOrPatternSpec = StaticValueProvider.of(fileName); - } - - public final String getFileOrPatternSpec() { - return fileOrPatternSpec.get(); - } - - public final ValueProvider getFileOrPatternSpecProvider() { - return fileOrPatternSpec; - } - - public final Mode getMode() { - return mode; - } - - @Override - public final FileBasedSource createSourceForSubrange(long start, long end) { - checkArgument(mode != Mode.FILEPATTERN, - "Cannot split a file pattern based source based on positions"); - checkArgument(start >= getStartOffset(), "Start offset value " + start - + " of the subrange cannot be smaller than the start offset value " + getStartOffset() - + " of the parent source"); - checkArgument(end <= getEndOffset(), "End offset value " + end - + " of the subrange cannot be larger than the end offset value " + getEndOffset() - + " of the parent source"); - - checkState(fileOrPatternSpec.isAccessible(), - "Subrange creation should only happen at execution time."); - FileBasedSource source = createForSubrangeOfFile(fileOrPatternSpec.get(), start, end); - if (start > 0 || end != Long.MAX_VALUE) { - checkArgument(source.getMode() == Mode.SINGLE_FILE_OR_SUBRANGE, - "Source created for the range [" + start + "," + end + ")" - + " must be a subrange source"); - } - return source; - } - - /** - * Creates and returns a new {@code FileBasedSource} of the same type as the current - * {@code FileBasedSource} backed by a given file and an offset range. When current source is - * being split, this method is used to generate new sub-sources. When creating the source - * subclasses must call the constructor {@link #FileBasedSource(String, long, long, long)} of - * {@code FileBasedSource} with corresponding parameter values passed here. - * - * @param fileName file backing the new {@code FileBasedSource}. - * @param start starting byte offset of the new {@code FileBasedSource}. - * @param end ending byte offset of the new {@code FileBasedSource}. May be Long.MAX_VALUE, - * in which case it will be inferred using {@link #getMaxEndOffset}. - */ - protected abstract FileBasedSource createForSubrangeOfFile( - String fileName, long start, long end); - - /** - * Creates and returns an instance of a {@code FileBasedReader} implementation for the current - * source assuming the source represents a single file. File patterns will be handled by - * {@code FileBasedSource} implementation automatically. - */ - protected abstract FileBasedReader createSingleFileReader( - PipelineOptions options); - - @Override - public final long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - // This implementation of method getEstimatedSizeBytes is provided to simplify subclasses. Here - // we perform the size estimation of files and file patterns using the interface provided by - // IOChannelFactory. - - if (mode == Mode.FILEPATTERN) { - checkState(fileOrPatternSpec.isAccessible(), - "Size estimation should be done at execution time."); - IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec.get()); - // TODO Implement a more efficient parallel/batch size estimation mechanism for file patterns. - long startTime = System.currentTimeMillis(); - long totalSize = 0; - Collection inputs = factory.match(fileOrPatternSpec.get()); - if (inputs.size() <= MAX_NUMBER_OF_FILES_FOR_AN_EXACT_STAT) { - totalSize = getExactTotalSizeOfFiles(inputs, factory); - LOG.debug("Size estimation of all files of pattern " + fileOrPatternSpec.get() + " took " - + (System.currentTimeMillis() - startTime) + " ms"); - } else { - totalSize = getEstimatedSizeOfFilesBySampling(inputs, factory); - LOG.debug("Size estimation of pattern " + fileOrPatternSpec.get() + " by sampling took " - + (System.currentTimeMillis() - startTime) + " ms"); - } - return totalSize; - } else { - long start = getStartOffset(); - long end = Math.min(getEndOffset(), getMaxEndOffset(options)); - return end - start; - } - } - - // Get the exact total size of the given set of files. - // Invokes multiple requests for size estimation in parallel using a thread pool. - // TODO: replace this with bulk request API when it is available. Will require updates - // to IOChannelFactory interface. - private static long getExactTotalSizeOfFiles( - Collection files, IOChannelFactory ioChannelFactory) throws Exception { - List> futures = new ArrayList<>(); - ListeningExecutorService service = - MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(THREAD_POOL_SIZE)); - long totalSize = 0; - try { - for (String file : files) { - futures.add(createFutureForSizeEstimation(file, ioChannelFactory, service)); - } - - for (Long val : Futures.allAsList(futures).get()) { - totalSize += val; - } - - return totalSize; - } finally { - service.shutdown(); - } - } - - private static ListenableFuture createFutureForSizeEstimation( - final String file, - final IOChannelFactory ioChannelFactory, - ListeningExecutorService service) { - return service.submit( - new Callable() { - @Override - public Long call() throws Exception { - return ioChannelFactory.getSizeBytes(file); - } - }); - } - - // Estimate the total size of the given set of files through sampling and extrapolation. - // Currently we use uniform sampling which requires a linear sampling size for a reasonable - // estimate. - // TODO: Implement a more efficient sampling mechanism. - private static long getEstimatedSizeOfFilesBySampling( - Collection files, IOChannelFactory ioChannelFactory) throws Exception { - int sampleSize = (int) (FRACTION_OF_FILES_TO_STAT * files.size()); - sampleSize = Math.max(MAX_NUMBER_OF_FILES_FOR_AN_EXACT_STAT, sampleSize); - - List selectedFiles = new ArrayList(files); - Collections.shuffle(selectedFiles); - selectedFiles = selectedFiles.subList(0, sampleSize); - - return files.size() * getExactTotalSizeOfFiles(selectedFiles, ioChannelFactory) - / selectedFiles.size(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("filePattern", getFileOrPatternSpecProvider()) - .withLabel("File Pattern")); - } - - private ListenableFuture>> createFutureForFileSplit( - final String file, - final long desiredBundleSizeBytes, - final PipelineOptions options, - ListeningExecutorService service) { - return service.submit(new Callable>>() { - @Override - public List> call() throws Exception { - return createForSubrangeOfFile(file, 0, Long.MAX_VALUE) - .splitIntoBundles(desiredBundleSizeBytes, options); - } - }); - } - - @Override - public final List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - // This implementation of method splitIntoBundles is provided to simplify subclasses. Here we - // split a FileBasedSource based on a file pattern to FileBasedSources based on full single - // files. For files that can be efficiently seeked, we further split FileBasedSources based on - // those files to FileBasedSources based on sub ranges of single files. - - if (mode == Mode.FILEPATTERN) { - long startTime = System.currentTimeMillis(); - List>>> futures = new ArrayList<>(); - - ListeningExecutorService service = - MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(THREAD_POOL_SIZE)); - try { - checkState(fileOrPatternSpec.isAccessible(), - "Bundle splitting should only happen at execution time."); - Collection expandedFiles = - FileBasedSource.expandFilePattern(fileOrPatternSpec.get()); - checkArgument(!expandedFiles.isEmpty(), - "Unable to find any files matching %s", fileOrPatternSpec.get()); - for (final String file : expandedFiles) { - futures.add(createFutureForFileSplit(file, desiredBundleSizeBytes, options, service)); - } - List> splitResults = - ImmutableList.copyOf(Iterables.concat(Futures.allAsList(futures).get())); - LOG.debug( - "Splitting the source based on file pattern " - + fileOrPatternSpec - + " took " - + (System.currentTimeMillis() - startTime) - + " ms"); - return splitResults; - } finally { - service.shutdown(); - } - } else { - if (isSplittable()) { - List> splitResults = new ArrayList<>(); - for (OffsetBasedSource split : super.splitIntoBundles(desiredBundleSizeBytes, options)) { - splitResults.add((FileBasedSource) split); - } - return splitResults; - } else { - LOG.debug("The source for file " + fileOrPatternSpec - + " is not split into sub-range based sources since the file is not seekable"); - return ImmutableList.of(this); - } - } - } - - /** - * Determines whether a file represented by this source is can be split into bundles. - * - *

              By default, a file is splittable if it is on a file system that supports efficient read - * seeking. Subclasses may override to provide different behavior. - */ - protected boolean isSplittable() throws Exception { - // We split a file-based source into subranges only if the file is efficiently seekable. - // If a file is not efficiently seekable it would be highly inefficient to create and read a - // source based on a subrange of that file. - checkState(fileOrPatternSpec.isAccessible(), - "isSplittable should only be called at runtime."); - IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec.get()); - return factory.isReadSeekEfficient(fileOrPatternSpec.get()); - } - - @Override - public final BoundedReader createReader(PipelineOptions options) throws IOException { - // Validate the current source prior to creating a reader for it. - this.validate(); - - if (mode == Mode.FILEPATTERN) { - long startTime = System.currentTimeMillis(); - Collection files = FileBasedSource.expandFilePattern(fileOrPatternSpec.get()); - List> fileReaders = new ArrayList<>(); - for (String fileName : files) { - long endOffset; - try { - endOffset = IOChannelUtils.getFactory(fileName).getSizeBytes(fileName); - } catch (IOException e) { - LOG.warn("Failed to get size of " + fileName, e); - endOffset = Long.MAX_VALUE; - } - fileReaders.add( - createForSubrangeOfFile(fileName, 0, endOffset).createSingleFileReader(options)); - } - LOG.debug("Creating a reader for file pattern " + fileOrPatternSpec + " took " - + (System.currentTimeMillis() - startTime) + " ms"); - if (fileReaders.size() == 1) { - return fileReaders.get(0); - } - return new FilePatternReader(this, fileReaders); - } else { - return createSingleFileReader(options); - } - } - - @Override - public String toString() { - switch (mode) { - case FILEPATTERN: - return fileOrPatternSpec.toString(); - case SINGLE_FILE_OR_SUBRANGE: - return fileOrPatternSpec.toString() + " range " + super.toString(); - default: - throw new IllegalStateException("Unexpected mode: " + mode); - } - } - - @Override - public void validate() { - super.validate(); - switch (mode) { - case FILEPATTERN: - checkArgument(getStartOffset() == 0, - "FileBasedSource is based on a file pattern or a full single file " - + "but the starting offset proposed " + getStartOffset() + " is not zero"); - checkArgument(getEndOffset() == Long.MAX_VALUE, - "FileBasedSource is based on a file pattern or a full single file " - + "but the ending offset proposed " + getEndOffset() + " is not Long.MAX_VALUE"); - break; - case SINGLE_FILE_OR_SUBRANGE: - // Nothing more to validate. - break; - default: - throw new IllegalStateException("Unknown mode: " + mode); - } - } - - @Override - public final long getMaxEndOffset(PipelineOptions options) throws Exception { - if (mode == Mode.FILEPATTERN) { - throw new IllegalArgumentException("Cannot determine the exact end offset of a file pattern"); - } - if (getEndOffset() == Long.MAX_VALUE) { - IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec.get()); - return factory.getSizeBytes(fileOrPatternSpec.get()); - } else { - return getEndOffset(); - } - } - - protected static final Collection expandFilePattern(String fileOrPatternSpec) - throws IOException { - IOChannelFactory factory = IOChannelUtils.getFactory(fileOrPatternSpec); - Collection matches = factory.match(fileOrPatternSpec); - LOG.info("Matched {} files for pattern {}", matches.size(), fileOrPatternSpec); - return matches; - } - - /** - * A {@link Source.Reader reader} that implements code common to readers of - * {@code FileBasedSource}s. - * - *

              Seekability

              - * - *

              This reader uses a {@link ReadableByteChannel} created for the file represented by the - * corresponding source to efficiently move to the correct starting position defined in the - * source. Subclasses of this reader should implement {@link #startReading} to get access to this - * channel. If the source corresponding to the reader is for a subrange of a file the - * {@code ReadableByteChannel} provided is guaranteed to be an instance of the type - * {@link SeekableByteChannel}, which may be used by subclass to traverse back in the channel to - * determine the correct starting position. - * - *

              Reading Records

              - * - *

              Sequential reading is implemented using {@link #readNextRecord}. - * - *

              Then {@code FileBasedReader} implements "reading a range [A, B)" in the following way. - *

                - *
              1. {@link #start} opens the file - *
              2. {@link #start} seeks the {@code SeekableByteChannel} to A (reading offset ranges for - * non-seekable files is not supported) and calls {@code startReading()} - *
              3. {@link #start} calls {@link #advance} once, which, via {@link #readNextRecord}, - * locates the first record which is at a split point AND its offset is at or after A. - * If this record is at or after B, {@link #advance} returns false and reading is finished. - *
              4. if the previous advance call returned {@code true} sequential reading starts and - * {@code advance()} will be called repeatedly - *
              - * {@code advance()} calls {@code readNextRecord()} on the subclass, and stops (returns false) if - * the new record is at a split point AND the offset of the new record is at or after B. - * - *

              Thread Safety

              - * - *

              Since this class implements {@link Source.Reader} it guarantees thread safety. Abstract - * methods defined here will not be accessed by more than one thread concurrently. - */ - public abstract static class FileBasedReader extends OffsetBasedReader { - private ReadableByteChannel channel = null; - - /** - * Subclasses should not perform IO operations at the constructor. All IO operations should be - * delayed until the {@link #startReading} method is invoked. - */ - public FileBasedReader(FileBasedSource source) { - super(source); - checkArgument(source.getMode() != Mode.FILEPATTERN, - "FileBasedReader does not support reading file patterns"); - } - - @Override - public synchronized FileBasedSource getCurrentSource() { - return (FileBasedSource) super.getCurrentSource(); - } - - @Override - protected final boolean startImpl() throws IOException { - FileBasedSource source = getCurrentSource(); - IOChannelFactory factory = IOChannelUtils.getFactory( - source.getFileOrPatternSpecProvider().get()); - this.channel = factory.open(source.getFileOrPatternSpecProvider().get()); - - if (channel instanceof SeekableByteChannel) { - SeekableByteChannel seekChannel = (SeekableByteChannel) channel; - seekChannel.position(source.getStartOffset()); - } else { - // Channel is not seekable. Must not be a subrange. - checkArgument(source.mode != Mode.SINGLE_FILE_OR_SUBRANGE, - "Subrange-based sources must only be defined for file types that support seekable " - + " read channels"); - checkArgument(source.getStartOffset() == 0, "Start offset " - + source.getStartOffset() - + " is not zero but channel for reading the file is not seekable."); - } - - startReading(channel); - - // Advance once to load the first record. - return advanceImpl(); - } - - @Override - protected final boolean advanceImpl() throws IOException { - return readNextRecord(); - } - - /** - * Closes any {@link ReadableByteChannel} created for the current reader. This implementation is - * idempotent. Any {@code close()} method introduced by a subclass must be idempotent and must - * call the {@code close()} method in the {@code FileBasedReader}. - */ - @Override - public void close() throws IOException { - if (channel != null) { - channel.close(); - } - } - - /** - * Performs any initialization of the subclass of {@code FileBasedReader} that involves IO - * operations. Will only be invoked once and before that invocation the base class will seek the - * channel to the source's starting offset. - * - *

              Provided {@link ReadableByteChannel} is for the file represented by the source of this - * reader. Subclass may use the {@code channel} to build a higher level IO abstraction, e.g., a - * BufferedReader or an XML parser. - * - *

              If the corresponding source is for a subrange of a file, {@code channel} is guaranteed to - * be an instance of the type {@link SeekableByteChannel}. - * - *

              After this method is invoked the base class will not be reading data from the channel or - * adjusting the position of the channel. But the base class is responsible for properly closing - * the channel. - * - * @param channel a byte channel representing the file backing the reader. - */ - protected abstract void startReading(ReadableByteChannel channel) throws IOException; - - /** - * Reads the next record from the channel provided by {@link #startReading}. Methods - * {@link #getCurrent}, {@link #getCurrentOffset}, and {@link #isAtSplitPoint()} should return - * the corresponding information about the record read by the last invocation of this method. - * - *

              Note that this method will be called the same way for reading the first record in the - * source (file or offset range in the file) and for reading subsequent records. It is up to the - * subclass to do anything special for locating and reading the first record, if necessary. - * - * @return {@code true} if a record was successfully read, {@code false} if the end of the - * channel was reached before successfully reading a new record. - */ - protected abstract boolean readNextRecord() throws IOException; - } - - // An internal Reader implementation that concatenates a sequence of FileBasedReaders. - private class FilePatternReader extends BoundedReader { - private final FileBasedSource source; - private final List> fileReaders; - final ListIterator> fileReadersIterator; - FileBasedReader currentReader = null; - - public FilePatternReader(FileBasedSource source, List> fileReaders) { - this.source = source; - this.fileReaders = fileReaders; - this.fileReadersIterator = fileReaders.listIterator(); - } - - @Override - public boolean start() throws IOException { - return startNextNonemptyReader(); - } - - @Override - public boolean advance() throws IOException { - checkState(currentReader != null, "Call start() before advance()"); - if (currentReader.advance()) { - return true; - } - return startNextNonemptyReader(); - } - - private boolean startNextNonemptyReader() throws IOException { - while (fileReadersIterator.hasNext()) { - currentReader = fileReadersIterator.next(); - if (currentReader.start()) { - return true; - } - currentReader.close(); - } - return false; - } - - @Override - public T getCurrent() throws NoSuchElementException { - // A NoSuchElement will be thrown by the last FileBasedReader if getCurrent() is called after - // advance() returns false. - return currentReader.getCurrent(); - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - // A NoSuchElement will be thrown by the last FileBasedReader if getCurrentTimestamp() - // is called after advance() returns false. - return currentReader.getCurrentTimestamp(); - } - - @Override - public void close() throws IOException { - // Close all readers that may have not yet been closed. - // If this reader has not been started, currentReader is null. - if (currentReader != null) { - currentReader.close(); - } - while (fileReadersIterator.hasNext()) { - fileReadersIterator.next().close(); - } - } - - @Override - public FileBasedSource getCurrentSource() { - return source; - } - - @Override - public FileBasedSource splitAtFraction(double fraction) { - // Unsupported. TODO: implement. - LOG.debug("Dynamic splitting of FilePatternReader is unsupported."); - return null; - } - - @Override - public Double getFractionConsumed() { - if (currentReader == null) { - return 0.0; - } - if (fileReaders.isEmpty()) { - return 1.0; - } - int index = fileReadersIterator.previousIndex(); - int numReaders = fileReaders.size(); - if (index == numReaders) { - return 1.0; - } - double before = 1.0 * index / numReaders; - double after = 1.0 * (index + 1) / numReaders; - Double fractionOfCurrentReader = currentReader.getFractionConsumed(); - if (fractionOfCurrentReader == null) { - return before; - } - return before + fractionOfCurrentReader * (after - before); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java deleted file mode 100644 index 170c7dd342..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSource.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.io.range.OffsetRangeTracker; -import com.google.cloud.dataflow.sdk.io.range.RangeTracker; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * A {@link BoundedSource} that uses offsets to define starting and ending positions. - * - *

              {@link OffsetBasedSource} is a common base class for all bounded sources where the input can - * be represented as a single range, and an input can be efficiently processed in parallel by - * splitting the range into a set of disjoint ranges whose union is the original range. This class - * should be used for sources that can be cheaply read starting at any given offset. - * {@link OffsetBasedSource} stores the range and implements splitting into bundles. - * - *

              Extend {@link OffsetBasedSource} to implement your own offset-based custom source. - * {@link FileBasedSource}, which is a subclass of this, adds additional functionality useful for - * custom sources that are based on files. If possible implementors should start from - * {@link FileBasedSource} instead of {@link OffsetBasedSource}. - * - *

              Consult {@link RangeTracker} for important semantics common to all sources defined by a range - * of positions of a certain type, including the semantics of split points - * ({@link OffsetBasedReader#isAtSplitPoint}). - * - * @param Type of records represented by the source. - * @see BoundedSource - * @see FileBasedSource - * @see RangeTracker - */ -public abstract class OffsetBasedSource extends BoundedSource { - private final long startOffset; - private final long endOffset; - private final long minBundleSize; - - /** - * @param startOffset starting offset (inclusive) of the source. Must be non-negative. - * - * @param endOffset ending offset (exclusive) of the source. Use {@link Long#MAX_VALUE} to - * indicate that the entire source after {@code startOffset} should be read. Must be - * {@code > startOffset}. - * - * @param minBundleSize minimum bundle size in offset units that should be used when splitting the - * source into sub-sources. This value may not be respected if the total - * range of the source is smaller than the specified {@code minBundleSize}. - * Must be non-negative. - */ - public OffsetBasedSource(long startOffset, long endOffset, long minBundleSize) { - this.startOffset = startOffset; - this.endOffset = endOffset; - this.minBundleSize = minBundleSize; - } - - /** - * Returns the starting offset of the source. - */ - public long getStartOffset() { - return startOffset; - } - - /** - * Returns the specified ending offset of the source. Any returned value greater than or equal to - * {@link #getMaxEndOffset(PipelineOptions)} should be treated as - * {@link #getMaxEndOffset(PipelineOptions)}. - */ - public long getEndOffset() { - return endOffset; - } - - /** - * Returns the minimum bundle size that should be used when splitting the source into sub-sources. - * This value may not be respected if the total range of the source is smaller than the specified - * {@code minBundleSize}. - */ - public long getMinBundleSize() { - return minBundleSize; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - long trueEndOffset = (endOffset == Long.MAX_VALUE) ? getMaxEndOffset(options) : endOffset; - return getBytesPerOffset() * (trueEndOffset - getStartOffset()); - } - - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - // Split the range into bundles based on the desiredBundleSizeBytes. Final bundle is adjusted to - // make sure that we do not end up with a too small bundle at the end. If the desired bundle - // size is smaller than the minBundleSize of the source then minBundleSize will be used instead. - - long desiredBundleSizeOffsetUnits = Math.max( - Math.max(1, desiredBundleSizeBytes / getBytesPerOffset()), - minBundleSize); - - List> subSources = new ArrayList<>(); - long start = startOffset; - long maxEnd = Math.min(endOffset, getMaxEndOffset(options)); - - while (start < maxEnd) { - long end = start + desiredBundleSizeOffsetUnits; - end = Math.min(end, maxEnd); - // Avoid having a too small bundle at the end and ensure that we respect minBundleSize. - long remaining = maxEnd - end; - if ((remaining < desiredBundleSizeOffsetUnits / 4) || (remaining < minBundleSize)) { - end = maxEnd; - } - subSources.add(createSourceForSubrange(start, end)); - - start = end; - } - return subSources; - } - - @Override - public void validate() { - checkArgument( - this.startOffset >= 0, - "Start offset has value %s, must be non-negative", this.startOffset); - checkArgument( - this.endOffset >= 0, - "End offset has value %s, must be non-negative", this.endOffset); - checkArgument( - this.startOffset < this.endOffset, - "Start offset %s must be before end offset %s", - this.startOffset, this.endOffset); - checkArgument( - this.minBundleSize >= 0, - "minBundleSize has value %s, must be non-negative", - this.minBundleSize); - } - - @Override - public String toString() { - return "[" + startOffset + ", " + endOffset + ")"; - } - - /** - * Returns approximately how many bytes of data correspond to a single offset in this source. - * Used for translation between this source's range and methods defined in terms of bytes, such - * as {@link #getEstimatedSizeBytes} and {@link #splitIntoBundles}. - * - *

              Defaults to {@code 1} byte, which is the common case for, e.g., file sources. - */ - public long getBytesPerOffset() { - return 1L; - } - - /** - * Returns the actual ending offset of the current source. The value returned by this function - * will be used to clip the end of the range {@code [startOffset, endOffset)} such that the - * range used is {@code [startOffset, min(endOffset, maxEndOffset))}. - * - *

              As an example in which {@link OffsetBasedSource} is used to implement a file source, suppose - * that this source was constructed with an {@code endOffset} of {@link Long#MAX_VALUE} to - * indicate that a file should be read to the end. Then this function should determine - * the actual, exact size of the file in bytes and return it. - */ - public abstract long getMaxEndOffset(PipelineOptions options) throws Exception; - - /** - * Returns an {@link OffsetBasedSource} for a subrange of the current source. The - * subrange {@code [start, end)} must be within the range {@code [startOffset, endOffset)} of - * the current source, i.e. {@code startOffset <= start < end <= endOffset}. - */ - public abstract OffsetBasedSource createSourceForSubrange(long start, long end); - - /** - * Whether this source should allow dynamic splitting of the offset ranges. - * - *

              True by default. Override this to return false if the source cannot - * support dynamic splitting correctly. If this returns false, - * {@link OffsetBasedSource.OffsetBasedReader#splitAtFraction} will refuse all split requests. - */ - public boolean allowsDynamicSplitting() { - return true; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotDefault(DisplayData.item("minBundleSize", minBundleSize) - .withLabel("Minimum Bundle Size"), 1L) - .addIfNotDefault(DisplayData.item("startOffset", startOffset) - .withLabel("Start Read Offset"), 0L) - .addIfNotDefault(DisplayData.item("endOffset", endOffset) - .withLabel("End Read Offset"), Long.MAX_VALUE); - } - - /** - * A {@link Source.Reader} that implements code common to readers of all - * {@link OffsetBasedSource}s. - * - *

              Subclasses have to implement: - *

                - *
              • The methods {@link #startImpl} and {@link #advanceImpl} for reading the - * first or subsequent records. - *
              • The methods {@link #getCurrent}, {@link #getCurrentOffset}, and optionally - * {@link #isAtSplitPoint} and {@link #getCurrentTimestamp} to access properties of - * the last record successfully read by {@link #startImpl} or {@link #advanceImpl}. - *
              - */ - public abstract static class OffsetBasedReader extends BoundedReader { - private static final Logger LOG = LoggerFactory.getLogger(OffsetBasedReader.class); - private OffsetBasedSource source; - - /** - * Returns true if the last call to {@link #start} or {@link #advance} returned false. - */ - public final boolean isDone() { - return rangeTracker.isDone(); - } - - /** - * Returns true if there has been a call to {@link #start}. - */ - public final boolean isStarted() { - return rangeTracker.isStarted(); - } - - /** The {@link OffsetRangeTracker} managing the range and current position of the source. */ - private final OffsetRangeTracker rangeTracker; - - /** - * @param source the {@link OffsetBasedSource} to be read by the current reader. - */ - public OffsetBasedReader(OffsetBasedSource source) { - this.source = source; - this.rangeTracker = new OffsetRangeTracker(source.getStartOffset(), source.getEndOffset()); - } - - /** - * Returns the starting offset of the {@link Source.Reader#getCurrent current record}, - * which has been read by the last successful {@link Source.Reader#start} or - * {@link Source.Reader#advance} call. - * - *

              If no such call has been made yet, the return value is unspecified. - * - *

              See {@link RangeTracker} for description of offset semantics. - */ - protected abstract long getCurrentOffset() throws NoSuchElementException; - - /** - * Returns whether the current record is at a split point (i.e., whether the current record - * would be the first record to be read by a source with a specified start offset of - * {@link #getCurrentOffset}). - * - *

              See detailed documentation about split points in {@link RangeTracker}. - */ - protected boolean isAtSplitPoint() throws NoSuchElementException { - return true; - } - - @Override - public final boolean start() throws IOException { - return startImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint(), getCurrentOffset()) - || rangeTracker.markDone(); - } - - @Override - public final boolean advance() throws IOException { - return advanceImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint(), getCurrentOffset()) - || rangeTracker.markDone(); - } - - /** - * Initializes the {@link OffsetBasedSource.OffsetBasedReader} and advances to the first record, - * returning {@code true} if there is a record available to be read. This method will be - * invoked exactly once and may perform expensive setup operations that are needed to - * initialize the reader. - * - *

              This function is the {@code OffsetBasedReader} implementation of - * {@link BoundedReader#start}. The key difference is that the implementor can ignore the - * possibility that it should no longer produce the first record, either because it has exceeded - * the original {@code endOffset} assigned to the reader, or because a concurrent call to - * {@link #splitAtFraction} has changed the source to shrink the offset range being read. - * - * @see BoundedReader#start - */ - protected abstract boolean startImpl() throws IOException; - - /** - * Advances to the next record and returns {@code true}, or returns false if there is no next - * record. - * - *

              This function is the {@code OffsetBasedReader} implementation of - * {@link BoundedReader#advance}. The key difference is that the implementor can ignore the - * possibility that it should no longer produce the next record, either because it has exceeded - * the original {@code endOffset} assigned to the reader, or because a concurrent call to - * {@link #splitAtFraction} has changed the source to shrink the offset range being read. - * - * @see BoundedReader#advance - */ - protected abstract boolean advanceImpl() throws IOException; - - @Override - public synchronized OffsetBasedSource getCurrentSource() { - return source; - } - - @Override - public Double getFractionConsumed() { - return rangeTracker.getFractionConsumed(); - } - - @Override - public long getSplitPointsConsumed() { - return rangeTracker.getSplitPointsProcessed(); - } - - @Override - public long getSplitPointsRemaining() { - if (isDone()) { - return 0; - } else if (!isStarted()) { - // Note that even if the current source does not allow splitting, we don't know that - // it's non-empty so we return UNKNOWN instead of 1. - return BoundedReader.SPLIT_POINTS_UNKNOWN; - } else if (!getCurrentSource().allowsDynamicSplitting()) { - // Started (so non-empty) and unsplittable, so only the current task. - return 1; - } else if (getCurrentOffset() >= rangeTracker.getStopPosition() - 1) { - // If this is true, the next element is outside the range. Note that even getCurrentOffset() - // might be larger than the stop position when the current record is not a split point. - return 1; - } else { - // Use the default. - return super.getSplitPointsRemaining(); - } - } - - @Override - public final synchronized OffsetBasedSource splitAtFraction(double fraction) { - if (!getCurrentSource().allowsDynamicSplitting()) { - return null; - } - if (rangeTracker.getStopPosition() == Long.MAX_VALUE) { - LOG.debug( - "Refusing to split unbounded OffsetBasedReader {} at fraction {}", - rangeTracker, fraction); - return null; - } - long splitOffset = rangeTracker.getPositionForFractionConsumed(fraction); - LOG.debug( - "Proposing to split OffsetBasedReader {} at fraction {} (offset {})", - rangeTracker, fraction, splitOffset); - long start = source.getStartOffset(); - long end = source.getEndOffset(); - OffsetBasedSource primary = source.createSourceForSubrange(start, splitOffset); - OffsetBasedSource residual = source.createSourceForSubrange(splitOffset, end); - if (!rangeTracker.trySplitAtPosition(splitOffset)) { - return null; - } - this.source = primary; - return residual; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java deleted file mode 100644 index 55dd24f6b7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubIO.java +++ /dev/null @@ -1,1218 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.PubsubClient; -import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; -import com.google.cloud.dataflow.sdk.util.PubsubJsonClient; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.base.Strings; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; - -/** - * Read and Write {@link PTransform}s for Cloud Pub/Sub streams. These transforms create - * and consume unbounded {@link PCollection PCollections}. - * - *

              Permissions

              - * - *

              Permission requirements depend on the {@link PipelineRunner} that is used to execute the - * Dataflow job. Please refer to the documentation of corresponding - * {@link PipelineRunner PipelineRunners} for more details. - */ -public class PubsubIO { - private static final Logger LOG = LoggerFactory.getLogger(PubsubIO.class); - - /** Factory for creating pubsub client to manage transport. */ - private static final PubsubClient.PubsubClientFactory FACTORY = PubsubJsonClient.FACTORY; - - /** The default {@link Coder} used to translate to/from Cloud Pub/Sub messages. */ - public static final Coder DEFAULT_PUBSUB_CODER = StringUtf8Coder.of(); - - /** - * Project IDs must contain 6-63 lowercase letters, digits, or dashes. - * IDs must start with a letter and may not end with a dash. - * This regex isn't exact - this allows for patterns that would be rejected by - * the service, but this is sufficient for basic parsing of table references. - */ - private static final Pattern PROJECT_ID_REGEXP = - Pattern.compile("[a-z][-a-z0-9:.]{4,61}[a-z0-9]"); - - private static final Pattern SUBSCRIPTION_REGEXP = - Pattern.compile("projects/([^/]+)/subscriptions/(.+)"); - - private static final Pattern TOPIC_REGEXP = Pattern.compile("projects/([^/]+)/topics/(.+)"); - - private static final Pattern V1BETA1_SUBSCRIPTION_REGEXP = - Pattern.compile("/subscriptions/([^/]+)/(.+)"); - - private static final Pattern V1BETA1_TOPIC_REGEXP = Pattern.compile("/topics/([^/]+)/(.+)"); - - private static final Pattern PUBSUB_NAME_REGEXP = Pattern.compile("[a-zA-Z][-._~%+a-zA-Z0-9]+"); - - private static final int PUBSUB_NAME_MIN_LENGTH = 3; - private static final int PUBSUB_NAME_MAX_LENGTH = 255; - - private static final String SUBSCRIPTION_RANDOM_TEST_PREFIX = "_random/"; - private static final String SUBSCRIPTION_STARTING_SIGNAL = "_starting_signal/"; - private static final String TOPIC_DEV_NULL_TEST_NAME = "/topics/dev/null"; - - private static void validateProjectName(String project) { - Matcher match = PROJECT_ID_REGEXP.matcher(project); - if (!match.matches()) { - throw new IllegalArgumentException( - "Illegal project name specified in Pubsub subscription: " + project); - } - } - - private static void validatePubsubName(String name) { - if (name.length() < PUBSUB_NAME_MIN_LENGTH) { - throw new IllegalArgumentException( - "Pubsub object name is shorter than 3 characters: " + name); - } - if (name.length() > PUBSUB_NAME_MAX_LENGTH) { - throw new IllegalArgumentException( - "Pubsub object name is longer than 255 characters: " + name); - } - - if (name.startsWith("goog")) { - throw new IllegalArgumentException("Pubsub object name cannot start with goog: " + name); - } - - Matcher match = PUBSUB_NAME_REGEXP.matcher(name); - if (!match.matches()) { - throw new IllegalArgumentException("Illegal Pubsub object name specified: " + name - + " Please see Javadoc for naming rules."); - } - } - - /** - * Populate common {@link DisplayData} between Pubsub source and sink. - */ - private static void populateCommonDisplayData(DisplayData.Builder builder, - String timestampLabel, String idLabel, ValueProvider topic) { - builder - .addIfNotNull(DisplayData.item("timestampLabel", timestampLabel) - .withLabel("Timestamp Label Attribute")) - .addIfNotNull(DisplayData.item("idLabel", idLabel) - .withLabel("ID Label Attribute")); - - if (topic != null) { - String topicString = topic.isAccessible() ? topic.get().asPath() - : topic.toString(); - builder.add(DisplayData.item("topic", topicString) - .withLabel("Pubsub Topic")); - } - } - - /** - * Class representing a Cloud Pub/Sub Subscription. - */ - public static class PubsubSubscription implements Serializable { - private enum Type { NORMAL, FAKE } - - private final Type type; - private final String project; - private final String subscription; - - private PubsubSubscription(Type type, String project, String subscription) { - this.type = type; - this.project = project; - this.subscription = subscription; - } - - /** - * Creates a class representing a Pub/Sub subscription from the specified subscription path. - * - *

              Cloud Pub/Sub subscription names should be of the form - * {@code projects//subscriptions/}, where {@code } is the name - * of the project the subscription belongs to. The {@code } component must comply - * with the following requirements: - * - *

                - *
              • Can only contain lowercase letters, numbers, dashes ('-'), underscores ('_') and periods - * ('.').
              • - *
              • Must be between 3 and 255 characters.
              • - *
              • Must begin with a letter.
              • - *
              • Must end with a letter or a number.
              • - *
              • Cannot begin with {@code 'goog'} prefix.
              • - *
              - */ - public static PubsubSubscription fromPath(String path) { - if (path.startsWith(SUBSCRIPTION_RANDOM_TEST_PREFIX) - || path.startsWith(SUBSCRIPTION_STARTING_SIGNAL)) { - return new PubsubSubscription(Type.FAKE, "", path); - } - - String projectName, subscriptionName; - - Matcher v1beta1Match = V1BETA1_SUBSCRIPTION_REGEXP.matcher(path); - if (v1beta1Match.matches()) { - LOG.warn("Saw subscription in v1beta1 format. Subscriptions should be in the format " - + "projects//subscriptions/"); - projectName = v1beta1Match.group(1); - subscriptionName = v1beta1Match.group(2); - } else { - Matcher match = SUBSCRIPTION_REGEXP.matcher(path); - if (!match.matches()) { - throw new IllegalArgumentException("Pubsub subscription is not in " - + "projects//subscriptions/ format: " + path); - } - projectName = match.group(1); - subscriptionName = match.group(2); - } - - validateProjectName(projectName); - validatePubsubName(subscriptionName); - return new PubsubSubscription(Type.NORMAL, projectName, subscriptionName); - } - - /** - * Returns the string representation of this subscription as a path used in the Cloud Pub/Sub - * v1beta1 API. - * - * @deprecated the v1beta1 API for Cloud Pub/Sub is deprecated. - */ - @Deprecated - public String asV1Beta1Path() { - if (type == Type.NORMAL) { - return "/subscriptions/" + project + "/" + subscription; - } else { - return subscription; - } - } - - /** - * Returns the string representation of this subscription as a path used in the Cloud Pub/Sub - * v1beta2 API. - * - * @deprecated the v1beta2 API for Cloud Pub/Sub is deprecated. - */ - @Deprecated - public String asV1Beta2Path() { - if (type == Type.NORMAL) { - return "projects/" + project + "/subscriptions/" + subscription; - } else { - return subscription; - } - } - - /** - * Returns the string representation of this subscription as a path used in the Cloud Pub/Sub - * API. - */ - public String asPath() { - if (type == Type.NORMAL) { - return "projects/" + project + "/subscriptions/" + subscription; - } else { - return subscription; - } - } - } - - /** - * Used to build a {@link ValueProvider} for {@link PubsubSubscription}. - */ - private static class SubscriptionTranslator - implements SerializableFunction { - @Override - public PubsubSubscription apply(String from) { - return PubsubSubscription.fromPath(from); - } - } - - /** - * Used to build a {@link ValueProvider} for {@link SubscriptionPath}. - */ - private static class SubscriptionPathTranslator - implements SerializableFunction { - @Override - public SubscriptionPath apply(PubsubSubscription from) { - return PubsubClient.subscriptionPathFromName(from.project, from.subscription); - } - } - - /** - * Used to build a {@link ValueProvider} for {@link PubsubTopic}. - */ - private static class TopicTranslator - implements SerializableFunction { - @Override - public PubsubTopic apply(String from) { - return PubsubTopic.fromPath(from); - } - } - - /** - * Used to build a {@link ValueProvider} for {@link TopicPath}. - */ - private static class TopicPathTranslator - implements SerializableFunction { - @Override - public TopicPath apply(PubsubTopic from) { - return PubsubClient.topicPathFromName(from.project, from.topic); - } - } - - /** - * Used to build a {@link ValueProvider} for {@link ProjectPath}. - */ - private static class ProjectPathTranslator - implements SerializableFunction { - @Override - public ProjectPath apply(PubsubTopic from) { - return PubsubClient.projectPathFromId(from.project); - } - } - - /** - * Class representing a Cloud Pub/Sub Topic. - */ - public static class PubsubTopic implements Serializable { - private enum Type { NORMAL, FAKE } - - private final Type type; - private final String project; - private final String topic; - - private PubsubTopic(Type type, String project, String topic) { - this.type = type; - this.project = project; - this.topic = topic; - } - - /** - * Creates a class representing a Cloud Pub/Sub topic from the specified topic path. - * - *

              Cloud Pub/Sub topic names should be of the form - * {@code /topics//}, where {@code } is the name of - * the publishing project. The {@code } component must comply with - * the following requirements: - * - *

                - *
              • Can only contain lowercase letters, numbers, dashes ('-'), underscores ('_') and periods - * ('.').
              • - *
              • Must be between 3 and 255 characters.
              • - *
              • Must begin with a letter.
              • - *
              • Must end with a letter or a number.
              • - *
              • Cannot begin with 'goog' prefix.
              • - *
              - */ - public static PubsubTopic fromPath(String path) { - if (path.equals(TOPIC_DEV_NULL_TEST_NAME)) { - return new PubsubTopic(Type.FAKE, "", path); - } - - String projectName, topicName; - - Matcher v1beta1Match = V1BETA1_TOPIC_REGEXP.matcher(path); - if (v1beta1Match.matches()) { - LOG.warn("Saw topic in v1beta1 format. Topics should be in the format " - + "projects//topics/"); - projectName = v1beta1Match.group(1); - topicName = v1beta1Match.group(2); - } else { - Matcher match = TOPIC_REGEXP.matcher(path); - if (!match.matches()) { - throw new IllegalArgumentException( - "Pubsub topic is not in projects//topics/ format: " + path); - } - projectName = match.group(1); - topicName = match.group(2); - } - - validateProjectName(projectName); - validatePubsubName(topicName); - return new PubsubTopic(Type.NORMAL, projectName, topicName); - } - - /** - * Returns the string representation of this topic as a path used in the Cloud Pub/Sub - * v1beta1 API. - * - * @deprecated the v1beta1 API for Cloud Pub/Sub is deprecated. - */ - @Deprecated - public String asV1Beta1Path() { - if (type == Type.NORMAL) { - return "/topics/" + project + "/" + topic; - } else { - return topic; - } - } - - /** - * Returns the string representation of this topic as a path used in the Cloud Pub/Sub - * v1beta2 API. - * - * @deprecated the v1beta2 API for Cloud Pub/Sub is deprecated. - */ - @Deprecated - public String asV1Beta2Path() { - if (type == Type.NORMAL) { - return "projects/" + project + "/topics/" + topic; - } else { - return topic; - } - } - - /** - * Returns the string representation of this topic as a path used in the Cloud Pub/Sub - * API. - */ - public String asPath() { - if (type == Type.NORMAL) { - return "projects/" + project + "/topics/" + topic; - } else { - return topic; - } - } - } - - /** - * A {@link PTransform} that continuously reads from a Cloud Pub/Sub stream and - * returns a {@link PCollection} of {@link String Strings} containing the items from - * the stream. - * - *

              When running with a {@link PipelineRunner} that only supports bounded - * {@link PCollection PCollections} (such as {@link DirectPipelineRunner}), - * only a bounded portion of the input Pub/Sub stream can be processed. As such, either - * {@link Bound#maxNumRecords(int)} or {@link Bound#maxReadTime(Duration)} must be set. - */ - public static class Read { - /** - * Creates and returns a transform for reading from Cloud Pub/Sub with the specified transform - * name. - */ - public static Bound named(String name) { - return new Bound<>(DEFAULT_PUBSUB_CODER).named(name); - } - - /** - * Like {@code topic()} but with a {@link ValueProvider}. - */ - public static Bound topic(ValueProvider topic) { - return new Bound<>(DEFAULT_PUBSUB_CODER).topic(topic); - } - - /** - * Creates and returns a transform for reading from a Cloud Pub/Sub topic. Mutually exclusive - * with {@link #subscription(String)}. - * - *

              See {@link PubsubIO.PubsubTopic#fromPath(String)} for more details on the format - * of the {@code topic} string. - * - *

              Dataflow will start reading data published on this topic from the time the pipeline is - * started. Any data published on the topic before the pipeline is started will not be read by - * Dataflow. - */ - public static Bound topic(String topic) { - return new Bound<>(DEFAULT_PUBSUB_CODER).topic(StaticValueProvider.of(topic)); - } - - /** - * Creates and returns a transform for reading from a specific Cloud Pub/Sub subscription. - * Mutually exclusive with {@link #topic(String)}. - * - *

              See {@link PubsubIO.PubsubSubscription#fromPath(String)} for more details on the format - * of the {@code subscription} string. - */ - public static Bound subscription(String subscription) { - return new Bound<>(DEFAULT_PUBSUB_CODER).subscription(StaticValueProvider.of(subscription)); - } - - /** - * Like {@code topic()} but with a {@link ValueProvider}. - */ - public static Bound subscription(ValueProvider subscription) { - return new Bound<>(DEFAULT_PUBSUB_CODER).subscription(subscription); - } - - /** - * Creates and returns a transform reading from Cloud Pub/Sub where record timestamps are - * expected to be provided as Pub/Sub message attributes. The {@code timestampLabel} - * parameter specifies the name of the attribute that contains the timestamp. - * - *

              The timestamp value is expected to be represented in the attribute as either: - * - *

                - *
              • a numerical value representing the number of milliseconds since the Unix epoch. For - * example, if using the Joda time classes, {@link Instant#getMillis()} returns the correct - * value for this attribute. - *
              • a String in RFC 3339 format. For example, {@code 2015-10-29T23:41:41.123Z}. The - * sub-second component of the timestamp is optional, and digits beyond the first three - * (i.e., time units smaller than milliseconds) will be ignored. - *
              - * - *

              If {@code timestampLabel} is not provided, the system will generate record timestamps - * the first time it sees each record. All windowing will be done relative to these timestamps. - * - *

              By default, windows are emitted based on an estimate of when this source is likely - * done producing data for a given timestamp (referred to as the Watermark; see - * {@link AfterWatermark} for more details). Any late data will be handled by the trigger - * specified with the windowing strategy – by default it will be output immediately. - * - *

              Note that the system can guarantee that no late data will ever be seen when it assigns - * timestamps by arrival time (i.e. {@code timestampLabel} is not provided). - * - * @see RFC 3339 - */ - public static Bound timestampLabel(String timestampLabel) { - return new Bound<>(DEFAULT_PUBSUB_CODER).timestampLabel(timestampLabel); - } - - /** - * Creates and returns a transform for reading from Cloud Pub/Sub where unique record - * identifiers are expected to be provided as Pub/Sub message attributes. The {@code idLabel} - * parameter specifies the attribute name. The value of the attribute can be any string - * that uniquely identifies this record. - * - *

              If {@code idLabel} is not provided, Dataflow cannot guarantee that no duplicate data will - * be delivered on the Pub/Sub stream. In this case, deduplication of the stream will be - * strictly best effort. - */ - public static Bound idLabel(String idLabel) { - return new Bound<>(DEFAULT_PUBSUB_CODER).idLabel(idLabel); - } - - /** - * Creates and returns a transform for reading from Cloud Pub/Sub that uses the given - * {@link Coder} to decode Pub/Sub messages into a value of type {@code T}. - * - *

              By default, uses {@link StringUtf8Coder}, which just - * returns the text lines as Java strings. - * - * @param the type of the decoded elements, and the elements - * of the resulting PCollection. - */ - public static Bound withCoder(Coder coder) { - return new Bound<>(coder); - } - - /** - * Creates and returns a transform for reading from Cloud Pub/Sub with a maximum number of - * records that will be read. The transform produces a bounded {@link PCollection}. - * - *

              Either this option or {@link #maxReadTime(Duration)} must be set in order to create a - * bounded source. - */ - public static Bound maxNumRecords(int maxNumRecords) { - return new Bound<>(DEFAULT_PUBSUB_CODER).maxNumRecords(maxNumRecords); - } - - /** - * Creates and returns a transform for reading from Cloud Pub/Sub with a maximum number of - * duration during which records will be read. The transform produces a bounded - * {@link PCollection}. - * - *

              Either this option or {@link #maxNumRecords(int)} must be set in order to create a bounded - * source. - */ - public static Bound maxReadTime(Duration maxReadTime) { - return new Bound<>(DEFAULT_PUBSUB_CODER).maxReadTime(maxReadTime); - } - - /** - * A {@link PTransform} that reads from a Cloud Pub/Sub source and returns - * a unbounded {@link PCollection} containing the items from the stream. - */ - public static class Bound extends PTransform> { - /** The Cloud Pub/Sub topic to read from. */ - @Nullable private final ValueProvider topic; - - /** The Cloud Pub/Sub subscription to read from. */ - @Nullable private final ValueProvider subscription; - - /** The name of the message attribute to read timestamps from. */ - @Nullable private final String timestampLabel; - - /** The name of the message attribute to read unique message IDs from. */ - @Nullable private final String idLabel; - - /** The coder used to decode each record. */ - @Nullable private final Coder coder; - - /** Stop after reading this many records. */ - private final int maxNumRecords; - - /** Stop after reading for this much time. */ - @Nullable private final Duration maxReadTime; - - private Bound(Coder coder) { - this(null, null, null, null, coder, null, 0, null); - } - - private Bound(String name, ValueProvider subscription, - ValueProvider topic, String timestampLabel, Coder coder, - String idLabel, int maxNumRecords, Duration maxReadTime) { - super(name); - this.subscription = subscription; - this.topic = topic; - this.timestampLabel = timestampLabel; - this.coder = coder; - this.idLabel = idLabel; - this.maxNumRecords = maxNumRecords; - this.maxReadTime = maxReadTime; - } - - /** - * Returns a transform that's like this one but with the given step name. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound<>( - name, subscription, topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - /** - * Returns a transform that's like this one but reading from the - * given subscription. - * - *

              See {@link PubsubIO.PubsubSubscription#fromPath(String)} for more details on the format - * of the {@code subscription} string. - * - *

              Multiple readers reading from the same subscription will each receive - * some arbitrary portion of the data. Most likely, separate readers should - * use their own subscriptions. - * - *

              Does not modify this object. - */ - public Bound subscription(String subscription) { - return subscription(StaticValueProvider.of(subscription)); - } - - /** - * Like {@code subscription()} but with a {@link ValueProvider}. - */ - public Bound subscription(ValueProvider subscription) { - if (subscription.isAccessible()) { - // Validate. - PubsubSubscription.fromPath(subscription.get()); - } - return new Bound<>(name, - NestedValueProvider.of(subscription, new SubscriptionTranslator()), - topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - /** - * Returns a transform that's like this one but that reads from the specified topic. - * - *

              See {@link PubsubIO.PubsubTopic#fromPath(String)} for more details on the - * format of the {@code topic} string. - * - *

              Does not modify this object. - */ - public Bound topic(String topic) { - return topic(StaticValueProvider.of(topic)); - } - - /** - * Like {@code topic()} but with a {@link ValueProvider}. - */ - public Bound topic(ValueProvider topic) { - if (topic.isAccessible()) { - // Validate. - PubsubTopic.fromPath(topic.get()); - } - return new Bound<>(name, subscription, - NestedValueProvider.of(topic, new TopicTranslator()), - timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - /** - * Returns a transform that's like this one but that reads message timestamps - * from the given message attribute. See {@link PubsubIO.Read#timestampLabel(String)} for - * more details on the format of the timestamp attribute. - * - *

              Does not modify this object. - */ - public Bound timestampLabel(String timestampLabel) { - return new Bound<>( - name, subscription, topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - /** - * Returns a transform that's like this one but that reads unique message IDs - * from the given message attribute. See {@link PubsubIO.Read#idLabel(String)} for more - * details on the format of the ID attribute. - * - *

              Does not modify this object. - */ - public Bound idLabel(String idLabel) { - return new Bound<>( - name, subscription, topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - /** - * Returns a transform that's like this one but that uses the given - * {@link Coder} to decode each record into a value of type {@code X}. - * - *

              Does not modify this object. - * - * @param the type of the decoded elements, and the - * elements of the resulting PCollection. - */ - public Bound withCoder(Coder coder) { - return new Bound<>( - name, subscription, topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - /** - * Returns a transform that's like this one but will only read up to the specified - * maximum number of records from Cloud Pub/Sub. The transform produces a bounded - * {@link PCollection}. See {@link PubsubIO.Read#maxNumRecords(int)} for more details. - */ - public Bound maxNumRecords(int maxNumRecords) { - return new Bound<>( - name, subscription, topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - /** - * Returns a transform that's like this one but will only read during the specified - * duration from Cloud Pub/Sub. The transform produces a bounded {@link PCollection}. - * See {@link PubsubIO.Read#maxReadTime(Duration)} for more details. - */ - public Bound maxReadTime(Duration maxReadTime) { - return new Bound<>( - name, subscription, topic, timestampLabel, coder, idLabel, maxNumRecords, maxReadTime); - } - - @Override - public PCollection apply(PInput input) { - if (topic == null && subscription == null) { - throw new IllegalStateException("Need to set either the topic or the subscription for " - + "a PubsubIO.Read transform"); - } - if (topic != null && subscription != null) { - throw new IllegalStateException("Can't set both the topic and the subscription for " - + "a PubsubIO.Read transform"); - } - - boolean boundedOutput = getMaxNumRecords() > 0 || getMaxReadTime() != null; - - if (boundedOutput) { - return input.getPipeline().begin() - .apply(Create.of((Void) null)).setCoder(VoidCoder.of()) - .apply(ParDo.of(new PubsubReader())) - .setCoder(coder); - } else { - @Nullable ValueProvider projectPath = - topic == null ? null : NestedValueProvider.of(topic, new ProjectPathTranslator()); - @Nullable ValueProvider topicPath = - topic == null ? null : NestedValueProvider.of(topic, new TopicPathTranslator()); - @Nullable ValueProvider subscriptionPath = - subscription == null - ? null - : NestedValueProvider.of(subscription, new SubscriptionPathTranslator()); - return input.getPipeline().begin() - .apply(new PubsubUnboundedSource( - FACTORY, projectPath, topicPath, subscriptionPath, - coder, timestampLabel, idLabel)); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - populateCommonDisplayData(builder, timestampLabel, idLabel, topic); - - builder - .addIfNotNull(DisplayData.item("maxReadTime", maxReadTime) - .withLabel("Maximum Read Time")) - .addIfNotDefault(DisplayData.item("maxNumRecords", maxNumRecords) - .withLabel("Maximum Read Records"), 0); - - if (subscription != null) { - String subscriptionString = subscription.isAccessible() - ? subscription.get().asPath() : subscription.toString(); - builder.add(DisplayData.item("subscription", subscriptionString) - .withLabel("Pubsub Subscription")); - } - } - - @Override - protected Coder getDefaultOutputCoder() { - return coder; - } - - public PubsubTopic getTopic() { - return topic == null ? null : topic.get(); - } - - public ValueProvider getTopicProvider() { - return topic; - } - - public PubsubSubscription getSubscription() { - return subscription == null ? null : subscription.get(); - } - - public ValueProvider getSubscriptionProvider() { - return subscription; - } - - public String getTimestampLabel() { - return timestampLabel; - } - - public Coder getCoder() { - return coder; - } - - public String getIdLabel() { - return idLabel; - } - - public int getMaxNumRecords() { - return maxNumRecords; - } - - public Duration getMaxReadTime() { - return maxReadTime; - } - - /** - * Default reader when Pubsub subscription has some form of upper bound. - * - *

              TODO: Consider replacing with BoundedReadFromUnboundedSource on top - * of PubsubUnboundedSource. - * - *

              NOTE: This is not the implementation used when running on the Google Cloud Dataflow - * service in streaming mode. - * - *

              Public so can be suppressed by runners. - */ - public class PubsubReader extends DoFn { - private static final int DEFAULT_PULL_SIZE = 100; - private static final int ACK_TIMEOUT_SEC = 60; - - @Override - public void processElement(ProcessContext c) throws IOException { - try (PubsubClient pubsubClient = - FACTORY.newClient(timestampLabel, idLabel, - c.getPipelineOptions().as(DataflowPipelineOptions.class))) { - - PubsubClient.SubscriptionPath subscriptionPath; - if (getSubscription() == null) { - TopicPath topicPath = - PubsubClient.topicPathFromName(getTopic().project, getTopic().topic); - // The subscription will be registered under this pipeline's project if we know it. - // Otherwise we'll fall back to the topic's project. - // Note that they don't need to be the same. - String projectId = - c.getPipelineOptions().as(DataflowPipelineOptions.class).getProject(); - if (Strings.isNullOrEmpty(projectId)) { - projectId = getTopic().project; - } - ProjectPath projectPath = PubsubClient.projectPathFromId(projectId); - try { - subscriptionPath = - pubsubClient.createRandomSubscription(projectPath, topicPath, ACK_TIMEOUT_SEC); - } catch (Exception e) { - throw new RuntimeException("Failed to create subscription: ", e); - } - } else { - subscriptionPath = - PubsubClient.subscriptionPathFromName(getSubscription().project, - getSubscription().subscription); - } - - Instant endTime = (getMaxReadTime() == null) - ? new Instant(Long.MAX_VALUE) : Instant.now().plus(getMaxReadTime()); - - List messages = new ArrayList<>(); - - Throwable finallyBlockException = null; - try { - while ((getMaxNumRecords() == 0 || messages.size() < getMaxNumRecords()) - && Instant.now().isBefore(endTime)) { - int batchSize = DEFAULT_PULL_SIZE; - if (getMaxNumRecords() > 0) { - batchSize = Math.min(batchSize, getMaxNumRecords() - messages.size()); - } - - List batchMessages = - pubsubClient.pull(System.currentTimeMillis(), subscriptionPath, batchSize, - false); - List ackIds = new ArrayList<>(); - for (IncomingMessage message : batchMessages) { - messages.add(message); - ackIds.add(message.ackId); - } - if (ackIds.size() != 0) { - pubsubClient.acknowledge(subscriptionPath, ackIds); - } - } - } catch (IOException e) { - throw new RuntimeException("Unexpected exception while reading from Pubsub: ", e); - } finally { - if (getSubscription() == null) { - try { - pubsubClient.deleteSubscription(subscriptionPath); - } catch (Exception e) { - finallyBlockException = e; - } - } - } - if (finallyBlockException != null) { - throw new RuntimeException("Failed to delete subscription: ", finallyBlockException); - } - - for (IncomingMessage message : messages) { - c.outputWithTimestamp( - CoderUtils.decodeFromByteArray(getCoder(), message.elementBytes), - new Instant(message.timestampMsSinceEpoch)); - } - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Bound.this.populateDisplayData(builder); - } - } - } - - /** Disallow construction of utility class. */ - private Read() {} - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** Disallow construction of utility class. */ - private PubsubIO() {} - - /** - * A {@link PTransform} that continuously writes a - * {@link PCollection} of {@link String Strings} to a Cloud Pub/Sub stream. - */ - // TODO: Support non-String encodings. - public static class Write { - /** - * Creates a transform that writes to Pub/Sub with the given step name. - */ - public static Bound named(String name) { - return new Bound<>(DEFAULT_PUBSUB_CODER).named(name); - } - - /** - * Creates a transform that publishes to the specified topic. - * - *

              See {@link PubsubIO.PubsubTopic#fromPath(String)} for more details on the format of the - * {@code topic} string. - */ - public static Bound topic(String topic) { - return new Bound<>(DEFAULT_PUBSUB_CODER).topic(StaticValueProvider.of(topic)); - } - - /** - * Like {@code topic()} but with a {@link ValueProvider}. - */ - public static Bound topic(ValueProvider topic) { - return new Bound<>(DEFAULT_PUBSUB_CODER).topic(topic); - } - - /** - * Creates a transform that writes to Pub/Sub, adds each record's timestamp to the published - * messages in an attribute with the specified name. The value of the attribute will be a number - * representing the number of milliseconds since the Unix epoch. For example, if using the Joda - * time classes, {@link Instant#Instant(long)} can be used to parse this value. - * - *

              If the output from this sink is being read by another Dataflow source, then - * {@link PubsubIO.Read#timestampLabel(String)} can be used to ensure the other source reads - * these timestamps from the appropriate attribute. - */ - public static Bound timestampLabel(String timestampLabel) { - return new Bound<>(DEFAULT_PUBSUB_CODER).timestampLabel(timestampLabel); - } - - /** - * Creates a transform that writes to Pub/Sub, adding each record's unique identifier to the - * published messages in an attribute with the specified name. The value of the attribute is an - * opaque string. - * - *

              If the the output from this sink is being read by another Dataflow source, then - * {@link PubsubIO.Read#idLabel(String)} can be used to ensure that* the other source reads - * these unique identifiers from the appropriate attribute. - */ - public static Bound idLabel(String idLabel) { - return new Bound<>(DEFAULT_PUBSUB_CODER).idLabel(idLabel); - } - - /** - * Creates a transform that uses the given {@link Coder} to encode each of the - * elements of the input collection into an output message. - * - *

              By default, uses {@link StringUtf8Coder}, which writes input Java strings directly as - * records. - * - * @param the type of the elements of the input PCollection - */ - public static Bound withCoder(Coder coder) { - return new Bound<>(coder); - } - - /** - * A {@link PTransform} that writes an unbounded {@link PCollection} of {@link String Strings} - * to a Cloud Pub/Sub stream. - */ - public static class Bound extends PTransform, PDone> { - /** The Cloud Pub/Sub topic to publish to. */ - @Nullable private final ValueProvider topic; - /** The name of the message attribute to publish message timestamps in. */ - @Nullable private final String timestampLabel; - /** The name of the message attribute to publish unique message IDs in. */ - @Nullable private final String idLabel; - private final Coder coder; - - private Bound(Coder coder) { - this(null, null, null, null, coder); - } - - private Bound( - String name, ValueProvider topic, String timestampLabel, - String idLabel, Coder coder) { - super(name); - this.topic = topic; - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - this.coder = coder; - } - - /** - * Returns a new transform that's like this one but with the specified step - * name. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound<>(name, topic, timestampLabel, idLabel, coder); - } - - /** - * Returns a new transform that's like this one but that writes to the specified - * topic. - * - *

              See {@link PubsubIO.PubsubTopic#fromPath(String)} for more details on the format of the - * {@code topic} string. - * - *

              Does not modify this object. - */ - public Bound topic(String topic) { - return topic(StaticValueProvider.of(topic)); - } - - /** - * Like {@code topic()} but with a {@link ValueProvider}. - */ - public Bound topic(ValueProvider topic) { - return new Bound<>(name, NestedValueProvider.of(topic, new TopicTranslator()), - timestampLabel, idLabel, coder); - } - - /** - * Returns a new transform that's like this one but that publishes record timestamps - * to a message attribute with the specified name. See - * {@link PubsubIO.Write#timestampLabel(String)} for more details. - * - *

              Does not modify this object. - */ - public Bound timestampLabel(String timestampLabel) { - return new Bound<>(name, topic, timestampLabel, idLabel, coder); - } - - /** - * Returns a new transform that's like this one but that publishes unique record IDs - * to a message attribute with the specified name. See {@link PubsubIO.Write#idLabel(String)} - * for more details. - * - *

              Does not modify this object. - */ - public Bound idLabel(String idLabel) { - return new Bound<>(name, topic, timestampLabel, idLabel, coder); - } - - /** - * Returns a new transform that's like this one - * but that uses the given {@link Coder} to encode each of - * the elements of the input {@link PCollection} into an - * output record. - * - *

              Does not modify this object. - * - * @param the type of the elements of the input {@link PCollection} - */ - public Bound withCoder(Coder coder) { - return new Bound<>(name, topic, timestampLabel, idLabel, coder); - } - - @Override - public PDone apply(PCollection input) { - if (topic == null) { - throw new IllegalStateException("need to set the topic of a PubsubIO.Write transform"); - } - switch (input.isBounded()) { - case BOUNDED: - input.apply(ParDo.of(new PubsubWriter())); - return PDone.in(input.getPipeline()); - case UNBOUNDED: - return input.apply(new PubsubUnboundedSink( - FACTORY, - NestedValueProvider.of(topic, new TopicPathTranslator()), - coder, - timestampLabel, - idLabel, - 100 /* numShards */)); - } - throw new RuntimeException(); // cases are exhaustive. - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - populateCommonDisplayData(builder, timestampLabel, idLabel, topic); - } - - @Override - protected Coder getDefaultOutputCoder() { - return VoidCoder.of(); - } - - public PubsubTopic getTopic() { - return topic.get(); - } - - public ValueProvider getTopicProvider() { - return topic; - } - - public String getTimestampLabel() { - return timestampLabel; - } - - public String getIdLabel() { - return idLabel; - } - - public Coder getCoder() { - return coder; - } - - /** - * Writer to Pubsub which batches messages from bounded collections. - * - *

              NOTE: This is not the implementation used when running on the Google Cloud Dataflow - * service in streaming mode. - * - *

              Public so can be suppressed by runners. - */ - public class PubsubWriter extends DoFn { - private static final int MAX_PUBLISH_BATCH_SIZE = 100; - private transient List output; - private transient PubsubClient pubsubClient; - - @Override - public void startBundle(Context c) throws IOException { - this.output = new ArrayList<>(); - // NOTE: idLabel is ignored. - this.pubsubClient = - FACTORY.newClient(timestampLabel, null, - c.getPipelineOptions().as(DataflowPipelineOptions.class)); - } - - @Override - public void processElement(ProcessContext c) throws IOException { - // NOTE: The record id is always null. - OutgoingMessage message = - new OutgoingMessage(CoderUtils.encodeToByteArray(getCoder(), c.element()), - c.timestamp().getMillis(), null); - output.add(message); - - if (output.size() >= MAX_PUBLISH_BATCH_SIZE) { - publish(); - } - } - - @Override - public void finishBundle(Context c) throws IOException { - if (!output.isEmpty()) { - publish(); - } - output = null; - pubsubClient.close(); - pubsubClient = null; - } - - private void publish() throws IOException { - int n = pubsubClient.publish( - PubsubClient.topicPathFromName(getTopic().project, getTopic().topic), - output); - checkState(n == output.size()); - output.clear(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Bound.this.populateDisplayData(builder); - } - } - } - - /** Disallow construction of utility class. */ - private Write() {} - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java deleted file mode 100644 index 26ffb9e11b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSink.java +++ /dev/null @@ -1,449 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CustomCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.NullableCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterFirst; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Repeatedly; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.PubsubClient; -import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.PubsubClientFactory; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.hash.Hashing; - -import org.joda.time.Duration; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; - -import javax.annotation.Nullable; - -/** - * A PTransform which streams messages to Pubsub. - *

                - *
              • The underlying implementation is just a {@link GroupByKey} followed by a {@link ParDo} which - * publishes as a side effect. (In the future we want to design and switch to a custom - * {@code UnboundedSink} implementation so as to gain access to system watermark and - * end-of-pipeline cleanup.) - *
              • We try to send messages in batches while also limiting send latency. - *
              • No stats are logged. Rather some counters are used to keep track of elements and batches. - *
              • Though some background threads are used by the underlying netty system all actual Pubsub - * calls are blocking. We rely on the underlying runner to allow multiple {@link DoFn} instances - * to execute concurrently and hide latency. - *
              • A failed bundle will cause messages to be resent. Thus we rely on the Pubsub consumer - * to dedup messages. - *
              - * - *

              NOTE: This is not the implementation used when running on the Google Cloud Dataflow service. - */ -public class PubsubUnboundedSink extends PTransform, PDone> { - /** - * Default maximum number of messages per publish. - */ - private static final int DEFAULT_PUBLISH_BATCH_SIZE = 1000; - - /** - * Default maximum size of a publish batch, in bytes. - */ - private static final int DEFAULT_PUBLISH_BATCH_BYTES = 400000; - - /** - * Default longest delay between receiving a message and pushing it to Pubsub. - */ - private static final Duration DEFAULT_MAX_LATENCY = Duration.standardSeconds(2); - - /** - * Coder for conveying outgoing messages between internal stages. - */ - private static class OutgoingMessageCoder extends CustomCoder { - private static final NullableCoder RECORD_ID_CODER = - NullableCoder.of(StringUtf8Coder.of()); - - @Override - public void encode( - OutgoingMessage value, OutputStream outStream, Context context) - throws CoderException, IOException { - ByteArrayCoder.of().encode(value.elementBytes, outStream, Context.NESTED); - BigEndianLongCoder.of().encode(value.timestampMsSinceEpoch, outStream, Context.NESTED); - RECORD_ID_CODER.encode(value.recordId, outStream, Context.NESTED); - } - - @Override - public OutgoingMessage decode( - InputStream inStream, Context context) throws CoderException, IOException { - byte[] elementBytes = ByteArrayCoder.of().decode(inStream, Context.NESTED); - long timestampMsSinceEpoch = BigEndianLongCoder.of().decode(inStream, Context.NESTED); - @Nullable String recordId = RECORD_ID_CODER.decode(inStream, Context.NESTED); - return new OutgoingMessage(elementBytes, timestampMsSinceEpoch, recordId); - } - } - - @VisibleForTesting - static final Coder CODER = new OutgoingMessageCoder(); - - // ================================================================================ - // RecordIdMethod - // ================================================================================ - - /** - * Specify how record ids are to be generated. - */ - @VisibleForTesting - enum RecordIdMethod { - /** Leave null. */ - NONE, - /** Generate randomly. */ - RANDOM, - /** Generate deterministically. For testing only. */ - DETERMINISTIC - } - - // ================================================================================ - // ShardFn - // ================================================================================ - - /** - * Convert elements to messages and shard them. - */ - private static class ShardFn extends DoFn> { - private final Aggregator elementCounter = - createAggregator("elements", new Sum.SumLongFn()); - private final Coder elementCoder; - private final int numShards; - private final RecordIdMethod recordIdMethod; - - ShardFn(Coder elementCoder, int numShards, RecordIdMethod recordIdMethod) { - this.elementCoder = elementCoder; - this.numShards = numShards; - this.recordIdMethod = recordIdMethod; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - elementCounter.addValue(1L); - byte[] elementBytes = CoderUtils.encodeToByteArray(elementCoder, c.element()); - long timestampMsSinceEpoch = c.timestamp().getMillis(); - @Nullable String recordId = null; - switch (recordIdMethod) { - case NONE: - break; - case DETERMINISTIC: - recordId = Hashing.murmur3_128().hashBytes(elementBytes).toString(); - break; - case RANDOM: - // Since these elements go through a GroupByKey, any failures while sending to - // Pubsub will be retried without falling back and generating a new record id. - // Thus even though we may send the same message to Pubsub twice, it is guaranteed - // to have the same record id. - recordId = UUID.randomUUID().toString(); - break; - } - c.output(KV.of(ThreadLocalRandom.current().nextInt(numShards), - new OutgoingMessage(elementBytes, timestampMsSinceEpoch, recordId))); - } - - @Override - public void populateDisplayData(Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("numShards", numShards)); - } - } - - // ================================================================================ - // WriterFn - // ================================================================================ - - /** - * Publish messages to Pubsub in batches. - */ - private static class WriterFn - extends DoFn>, Void> { - private final PubsubClientFactory pubsubFactory; - private final ValueProvider topic; - private final String timestampLabel; - private final String idLabel; - private final int publishBatchSize; - private final int publishBatchBytes; - - /** - * Client on which to talk to Pubsub. Null until created by {@link #startBundle}. - */ - @Nullable - private transient PubsubClient pubsubClient; - - private final Aggregator batchCounter = - createAggregator("batches", new Sum.SumLongFn()); - private final Aggregator elementCounter = - createAggregator("elements", new Sum.SumLongFn()); - private final Aggregator byteCounter = - createAggregator("bytes", new Sum.SumLongFn()); - - WriterFn( - PubsubClientFactory pubsubFactory, ValueProvider topic, - String timestampLabel, String idLabel, int publishBatchSize, int publishBatchBytes) { - this.pubsubFactory = pubsubFactory; - this.topic = topic; - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - this.publishBatchSize = publishBatchSize; - this.publishBatchBytes = publishBatchBytes; - } - - /** - * BLOCKING - * Send {@code messages} as a batch to Pubsub. - */ - private void publishBatch(List messages, int bytes) - throws IOException { - int n = pubsubClient.publish(topic.get(), messages); - checkState(n == messages.size(), "Attempted to publish %s messages but %s were successful", - messages.size(), n); - batchCounter.addValue(1L); - elementCounter.addValue((long) messages.size()); - byteCounter.addValue((long) bytes); - } - - @Override - public void startBundle(Context c) throws Exception { - checkState(pubsubClient == null, "startBundle invoked without prior finishBundle"); - pubsubClient = - pubsubFactory.newClient(timestampLabel, idLabel, - c.getPipelineOptions().as(DataflowPipelineOptions.class)); - } - - @Override - public void processElement(ProcessContext c) throws Exception { - List pubsubMessages = new ArrayList<>(publishBatchSize); - int bytes = 0; - for (OutgoingMessage message : c.element().getValue()) { - if (!pubsubMessages.isEmpty() - && bytes + message.elementBytes.length > publishBatchBytes) { - // Break large (in bytes) batches into smaller. - // (We've already broken by batch size using the trigger below, though that may - // run slightly over the actual PUBLISH_BATCH_SIZE. We'll consider that ok since - // the hard limit from Pubsub is by bytes rather than number of messages.) - // BLOCKS until published. - publishBatch(pubsubMessages, bytes); - pubsubMessages.clear(); - bytes = 0; - } - pubsubMessages.add(message); - bytes += message.elementBytes.length; - } - if (!pubsubMessages.isEmpty()) { - // BLOCKS until published. - publishBatch(pubsubMessages, bytes); - } - } - - @Override - public void finishBundle(Context c) throws Exception { - pubsubClient.close(); - pubsubClient = null; - } - - @Override - public void populateDisplayData(Builder builder) { - super.populateDisplayData(builder); - String topicString = - topic == null ? null - : topic.isAccessible() ? topic.get().getPath() - : topic.toString(); - builder.add(DisplayData.item("topic", topicString)); - builder.add(DisplayData.item("transport", pubsubFactory.getKind())); - builder.addIfNotNull(DisplayData.item("timestampLabel", timestampLabel)); - builder.addIfNotNull(DisplayData.item("idLabel", idLabel)); - } - } - - // ================================================================================ - // PubsubUnboundedSink - // ================================================================================ - - /** - * Which factory to use for creating Pubsub transport. - */ - private final PubsubClientFactory pubsubFactory; - - /** - * Pubsub topic to publish to. - */ - private final ValueProvider topic; - - /** - * Coder for elements. It is the responsibility of the underlying Pubsub transport to - * re-encode element bytes if necessary, eg as Base64 strings. - */ - private final Coder elementCoder; - - /** - * Pubsub metadata field holding timestamp of each element, or {@literal null} if should use - * Pubsub message publish timestamp instead. - */ - @Nullable - private final String timestampLabel; - - /** - * Pubsub metadata field holding id for each element, or {@literal null} if need to generate - * a unique id ourselves. - */ - @Nullable - private final String idLabel; - - /** - * Number of 'shards' to use so that latency in Pubsub publish can be hidden. Generally this - * should be a small multiple of the number of available cores. Too smoll a number results - * in too much time lost to blocking Pubsub calls. To large a number results in too many - * single-element batches being sent to Pubsub with high per-batch overhead. - */ - private final int numShards; - - /** - * Maximum number of messages per publish. - */ - private final int publishBatchSize; - - /** - * Maximum size of a publish batch, in bytes. - */ - private final int publishBatchBytes; - - /** - * Longest delay between receiving a message and pushing it to Pubsub. - */ - private final Duration maxLatency; - - /** - * How record ids should be generated for each record (if {@link #idLabel} is non-{@literal - * null}). - */ - private final RecordIdMethod recordIdMethod; - - @VisibleForTesting - PubsubUnboundedSink( - PubsubClientFactory pubsubFactory, - ValueProvider topic, - Coder elementCoder, - String timestampLabel, - String idLabel, - int numShards, - int publishBatchSize, - int publishBatchBytes, - Duration maxLatency, - RecordIdMethod recordIdMethod) { - this.pubsubFactory = pubsubFactory; - this.topic = topic; - this.elementCoder = elementCoder; - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - this.numShards = numShards; - this.publishBatchSize = publishBatchSize; - this.publishBatchBytes = publishBatchBytes; - this.maxLatency = maxLatency; - this.recordIdMethod = idLabel == null ? RecordIdMethod.NONE : recordIdMethod; - } - - public PubsubUnboundedSink( - PubsubClientFactory pubsubFactory, - ValueProvider topic, - Coder elementCoder, - String timestampLabel, - String idLabel, - int numShards) { - this(pubsubFactory, topic, elementCoder, timestampLabel, idLabel, numShards, - DEFAULT_PUBLISH_BATCH_SIZE, DEFAULT_PUBLISH_BATCH_BYTES, DEFAULT_MAX_LATENCY, - RecordIdMethod.RANDOM); - } - - public TopicPath getTopic() { - return topic.get(); - } - - public ValueProvider getTopicProvider() { - return topic; - } - - @Nullable - public String getTimestampLabel() { - return timestampLabel; - } - - @Nullable - public String getIdLabel() { - return idLabel; - } - - public Coder getElementCoder() { - return elementCoder; - } - - @Override - public PDone apply(PCollection input) { - input.apply( - Window.named("PubsubUnboundedSink.Window") - .into(new GlobalWindows()) - .triggering( - Repeatedly.forever( - AfterFirst.of(AfterPane.elementCountAtLeast(publishBatchSize), - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(maxLatency)))) - .discardingFiredPanes()) - .apply(ParDo.named("PubsubUnboundedSink.Shard") - .of(new ShardFn(elementCoder, numShards, recordIdMethod))) - .setCoder(KvCoder.of(VarIntCoder.of(), CODER)) - .apply(GroupByKey.create()) - .apply(ParDo.named("PubsubUnboundedSink.Writer") - .of(new WriterFn(pubsubFactory, topic, timestampLabel, idLabel, - publishBatchSize, publishBatchBytes))); - return PDone.in(input.getPipeline()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java deleted file mode 100644 index 575fe39771..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java +++ /dev/null @@ -1,1320 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.client.util.Clock; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.Sum.SumLongFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.BucketingFunction; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.MovingFunction; -import com.google.cloud.dataflow.sdk.util.PubsubClient; -import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.PubsubClientFactory; -import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Charsets; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.GeneralSecurityException; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Nullable; - -/** - * A PTransform which streams messages from Pubsub. - *

                - *
              • The underlying implementation in an {@link UnboundedSource} which receives messages - * in batches and hands them out one at a time. - *
              • The watermark (either in Pubsub processing time or custom timestamp time) is estimated - * by keeping track of the minimum of the last minutes worth of messages. This assumes Pubsub - * delivers the oldest (in Pubsub processing time) available message at least once a minute, - * and that custom timestamps are 'mostly' monotonic with Pubsub processing time. Unfortunately - * both of those assumptions are fragile. Thus the estimated watermark may get ahead of - * the 'true' watermark and cause some messages to be late. - *
              • Checkpoints are used both to ACK received messages back to Pubsub (so that they may - * be retired on the Pubsub end), and to NACK already consumed messages should a checkpoint - * need to be restored (so that Pubsub will resend those messages promptly). - *
              • The backlog is determined by each reader using the messages which have been pulled from - * Pubsub but not yet consumed downstream. The backlog does not take account of any messages queued - * by Pubsub for the subscription. Unfortunately there is currently no API to determine - * the size of the Pubsub queue's backlog. - *
              • The subscription must already exist. - *
              • The subscription timeout is read whenever a reader is started. However it is not - * checked thereafter despite the timeout being user-changeable on-the-fly. - *
              • We log vital stats every 30 seconds. - *
              • Though some background threads may be used by the underlying transport all Pubsub calls - * are blocking. We rely on the underlying runner to allow multiple - * {@link UnboundedSource.UnboundedReader} instances to execute concurrently and thus hide latency. - *
              - * - *

              NOTE: This is not the implementation used when running on the Google Cloud Dataflow service. - */ -public class PubsubUnboundedSource extends PTransform> { - private static final Logger LOG = LoggerFactory.getLogger(PubsubUnboundedSource.class); - - /** - * Default ACK timeout for created subscriptions. - */ - private static final int DEAULT_ACK_TIMEOUT_SEC = 60; - - /** - * Coder for checkpoints. - */ - private static final PubsubCheckpointCoder CHECKPOINT_CODER = new PubsubCheckpointCoder<>(); - - /** - * Maximum number of messages per pull. - */ - private static final int PULL_BATCH_SIZE = 1000; - - /** - * Maximum number of ACK ids per ACK or ACK extension call. - */ - private static final int ACK_BATCH_SIZE = 2000; - - /** - * Maximum number of messages in flight. - */ - private static final int MAX_IN_FLIGHT = 20000; - - /** - * Timeout for round trip from receiving a message to finally ACKing it back to Pubsub. - */ - private static final Duration PROCESSING_TIMEOUT = Duration.standardSeconds(120); - - /** - * Percentage of ack timeout by which to extend acks when they are near timeout. - */ - private static final int ACK_EXTENSION_PCT = 50; - - /** - * Percentage of ack timeout we should use as a safety margin. We'll try to extend acks - * by this margin before the ack actually expires. - */ - private static final int ACK_SAFETY_PCT = 20; - - /** - * For stats only: How close we can get to an ack deadline before we risk it being already - * considered passed by Pubsub. - */ - private static final Duration ACK_TOO_LATE = Duration.standardSeconds(2); - - /** - * Period of samples to determine watermark and other stats. - */ - private static final Duration SAMPLE_PERIOD = Duration.standardMinutes(1); - - /** - * Period of updates to determine watermark and other stats. - */ - private static final Duration SAMPLE_UPDATE = Duration.standardSeconds(5); - - /** - * Period for logging stats. - */ - private static final Duration LOG_PERIOD = Duration.standardSeconds(30); - - /** - * Minimum number of unread messages required before considering updating watermark. - */ - private static final int MIN_WATERMARK_MESSAGES = 10; - - /** - * Minimum number of SAMPLE_UPDATE periods over which unread messages shoud be spread - * before considering updating watermark. - */ - private static final int MIN_WATERMARK_SPREAD = 2; - - /** - * Additional sharding so that we can hide read message latency. - */ - private static final int SCALE_OUT = 4; - - // TODO: Would prefer to use MinLongFn but it is a BinaryCombineFn rather - // than a BinaryCombineLongFn. [BEAM-285] - private static final Combine.BinaryCombineLongFn MIN = - new Combine.BinaryCombineLongFn() { - @Override - public long apply(long left, long right) { - return Math.min(left, right); - } - - @Override - public long identity() { - return Long.MAX_VALUE; - } - }; - - private static final Combine.BinaryCombineLongFn MAX = - new Combine.BinaryCombineLongFn() { - @Override - public long apply(long left, long right) { - return Math.max(left, right); - } - - @Override - public long identity() { - return Long.MIN_VALUE; - } - }; - - private static final Combine.BinaryCombineLongFn SUM = new SumLongFn(); - - // ================================================================================ - // Checkpoint - // ================================================================================ - - /** - * Which messages have been durably committed and thus can now be ACKed. - * Which messages have been read but not yet committed, in which case they should be NACKed if - * we need to restore. - */ - @VisibleForTesting - static class PubsubCheckpoint implements UnboundedSource.CheckpointMark { - /** - * If the checkpoint is for persisting: the reader who's snapshotted state we are persisting. - * If the checkpoint is for restoring: {@literal null}. - * Not persisted in durable checkpoint. - * CAUTION: Between a checkpoint being taken and {@link #finalizeCheckpoint()} being called - * the 'true' active reader may have changed. - */ - @Nullable - private PubsubReader reader; - - /** - * If the checkpoint is for persisting: The ACK ids of messages which have been passed - * downstream since the last checkpoint. - * If the checkpoint is for restoring: {@literal null}. - * Not persisted in durable checkpoint. - */ - @Nullable - private List safeToAckIds; - - /** - * If the checkpoint is for persisting: The ACK ids of messages which have been received - * from Pubsub but not yet passed downstream at the time of the snapshot. - * If the checkpoint is for restoring: Same, but recovered from durable storage. - */ - @VisibleForTesting - final List notYetReadIds; - - public PubsubCheckpoint( - @Nullable PubsubReader reader, @Nullable List safeToAckIds, - List notYetReadIds) { - this.reader = reader; - this.safeToAckIds = safeToAckIds; - this.notYetReadIds = notYetReadIds; - } - - /** - * BLOCKING - * All messages which have been passed downstream have now been durably committed. - * We can ACK them upstream. - * CAUTION: This may never be called. - */ - @Override - public void finalizeCheckpoint() throws IOException { - checkState(reader != null && safeToAckIds != null, "Cannot finalize a restored checkpoint"); - // Even if the 'true' active reader has changed since the checkpoint was taken we are - // fine: - // - The underlying Pubsub topic will not have changed, so the following ACKs will still - // go to the right place. - // - We'll delete the ACK ids from the readers in-flight state, but that only effects - // flow control and stats, neither of which are relevant anymore. - try { - int n = safeToAckIds.size(); - List batchSafeToAckIds = new ArrayList<>(Math.min(n, ACK_BATCH_SIZE)); - for (String ackId : safeToAckIds) { - batchSafeToAckIds.add(ackId); - if (batchSafeToAckIds.size() >= ACK_BATCH_SIZE) { - reader.ackBatch(batchSafeToAckIds); - n -= batchSafeToAckIds.size(); - // CAUTION: Don't reuse the same list since ackBatch holds on to it. - batchSafeToAckIds = new ArrayList<>(Math.min(n, ACK_BATCH_SIZE)); - } - } - if (!batchSafeToAckIds.isEmpty()) { - reader.ackBatch(batchSafeToAckIds); - } - } finally { - checkState(reader.numInFlightCheckpoints.decrementAndGet() >= 0, - "Miscounted in-flight checkpoints"); - reader = null; - safeToAckIds = null; - } - } - - /** - * Return current time according to {@code reader}. - */ - private static long now(PubsubReader reader) { - if (reader.outer.outer.clock == null) { - return System.currentTimeMillis(); - } else { - return reader.outer.outer.clock.currentTimeMillis(); - } - } - - /** - * BLOCKING - * NACK all messages which have been read from Pubsub but not passed downstream. - * This way Pubsub will send them again promptly. - */ - public void nackAll(PubsubReader reader) throws IOException { - checkState(this.reader == null, "Cannot nackAll on persisting checkpoint"); - List batchYetToAckIds = - new ArrayList<>(Math.min(notYetReadIds.size(), ACK_BATCH_SIZE)); - for (String ackId : notYetReadIds) { - batchYetToAckIds.add(ackId); - if (batchYetToAckIds.size() >= ACK_BATCH_SIZE) { - long nowMsSinceEpoch = now(reader); - reader.nackBatch(nowMsSinceEpoch, batchYetToAckIds); - batchYetToAckIds.clear(); - } - } - if (!batchYetToAckIds.isEmpty()) { - long nowMsSinceEpoch = now(reader); - reader.nackBatch(nowMsSinceEpoch, batchYetToAckIds); - } - } - } - - /** - * The coder for our checkpoints. - */ - private static class PubsubCheckpointCoder extends AtomicCoder> { - private static final Coder> LIST_CODER = ListCoder.of(StringUtf8Coder.of()); - - @Override - public void encode(PubsubCheckpoint value, OutputStream outStream, Context context) - throws IOException { - LIST_CODER.encode(value.notYetReadIds, outStream, context); - } - - @Override - public PubsubCheckpoint decode(InputStream inStream, Context context) throws IOException { - List notYetReadIds = LIST_CODER.decode(inStream, context); - return new PubsubCheckpoint<>(null, null, notYetReadIds); - } - } - - // ================================================================================ - // Reader - // ================================================================================ - - /** - * A reader which keeps track of which messages have been received from Pubsub - * but not yet consumed downstream and/or ACKed back to Pubsub. - */ - @VisibleForTesting - static class PubsubReader extends UnboundedSource.UnboundedReader { - /** - * For access to topic and checkpointCoder. - */ - private final PubsubSource outer; - - /** - * Client on which to talk to Pubsub. Null if closed. - */ - @Nullable - private PubsubClient pubsubClient; - - /** - * Ack timeout, in ms, as set on subscription when we first start reading. Not - * updated thereafter. -1 if not yet determined. - */ - private int ackTimeoutMs; - - /** - * ACK ids of messages we have delivered downstream but not yet ACKed. - */ - private Set safeToAckIds; - - /** - * Messages we have received from Pubsub and not yet delivered downstream. - * We preserve their order. - */ - private final Queue notYetRead; - - private static class InFlightState { - /** - * When request which yielded message was issues. - */ - long requestTimeMsSinceEpoch; - - /** - * When Pubsub will consider this message's ACK to timeout and thus it needs to be - * extended. - */ - long ackDeadlineMsSinceEpoch; - - public InFlightState(long requestTimeMsSinceEpoch, long ackDeadlineMsSinceEpoch) { - this.requestTimeMsSinceEpoch = requestTimeMsSinceEpoch; - this.ackDeadlineMsSinceEpoch = ackDeadlineMsSinceEpoch; - } - } - - /** - * Map from ACK ids of messages we have received from Pubsub but not yet ACKed to their - * in flight state. Ordered from earliest to latest ACK deadline. - */ - private final LinkedHashMap inFlight; - - /** - * Batches of successfully ACKed ids which need to be pruned from the above. - * CAUTION: Accessed by both reader and checkpointing threads. - */ - private final Queue> ackedIds; - - /** - * Byte size of undecoded elements in {@link #notYetRead}. - */ - private long notYetReadBytes; - - /** - * Bucketed map from received time (as system time, ms since epoch) to message - * timestamps (mssince epoch) of all received but not-yet read messages. - * Used to estimate watermark. - */ - private BucketingFunction minUnreadTimestampMsSinceEpoch; - - /** - * Minimum of timestamps (ms since epoch) of all recently read messages. - * Used to estimate watermark. - */ - private MovingFunction minReadTimestampMsSinceEpoch; - - /** - * System time (ms since epoch) we last received a message from Pubsub, or -1 if - * not yet received any messages. - */ - private long lastReceivedMsSinceEpoch; - - /** - * The last reported watermark (ms since epoch), or beginning of time if none yet reported. - */ - private long lastWatermarkMsSinceEpoch; - - /** - * The current message, or {@literal null} if none. - */ - @Nullable - private PubsubClient.IncomingMessage current; - - /** - * Stats only: System time (ms since epoch) we last logs stats, or -1 if never. - */ - private long lastLogTimestampMsSinceEpoch; - - /** - * Stats only: Total number of messages received. - */ - private long numReceived; - - /** - * Stats only: Number of messages which have recently been received. - */ - private MovingFunction numReceivedRecently; - - /** - * Stats only: Number of messages which have recently had their deadline extended. - */ - private MovingFunction numExtendedDeadlines; - - /** - * Stats only: Number of messages which have recenttly had their deadline extended even - * though it may be too late to do so. - */ - private MovingFunction numLateDeadlines; - - - /** - * Stats only: Number of messages which have recently been ACKed. - */ - private MovingFunction numAcked; - - /** - * Stats only: Number of messages which have recently expired (ACKs were extended for too - * long). - */ - private MovingFunction numExpired; - - /** - * Stats only: Number of messages which have recently been NACKed. - */ - private MovingFunction numNacked; - - /** - * Stats only: Number of message bytes which have recently been read by downstream consumer. - */ - private MovingFunction numReadBytes; - - /** - * Stats only: Minimum of timestamp (ms since epoch) of all recently received messages. - * Used to estimate timestamp skew. Does not contribute to watermark estimator. - */ - private MovingFunction minReceivedTimestampMsSinceEpoch; - - /** - * Stats only: Maximum of timestamp (ms since epoch) of all recently received messages. - * Used to estimate timestamp skew. - */ - private MovingFunction maxReceivedTimestampMsSinceEpoch; - - /** - * Stats only: Minimum of recent estimated watermarks (ms since epoch). - */ - private MovingFunction minWatermarkMsSinceEpoch; - - /** - * Stats ony: Maximum of recent estimated watermarks (ms since epoch). - */ - private MovingFunction maxWatermarkMsSinceEpoch; - - /** - * Stats only: Number of messages with timestamps strictly behind the estimated watermark - * at the time they are received. These may be considered 'late' by downstream computations. - */ - private MovingFunction numLateMessages; - - /** - * Stats only: Current number of checkpoints in flight. - * CAUTION: Accessed by both checkpointing and reader threads. - */ - private AtomicInteger numInFlightCheckpoints; - - /** - * Stats only: Maximum number of checkpoints in flight at any time. - */ - private int maxInFlightCheckpoints; - - private static MovingFunction newFun(Combine.BinaryCombineLongFn function) { - return new MovingFunction(SAMPLE_PERIOD.getMillis(), - SAMPLE_UPDATE.getMillis(), - MIN_WATERMARK_SPREAD, - MIN_WATERMARK_MESSAGES, - function); - } - - /** - * Construct a reader. - */ - public PubsubReader(DataflowPipelineOptions options, PubsubSource outer) - throws IOException, GeneralSecurityException { - this.outer = outer; - pubsubClient = - outer.outer.pubsubFactory.newClient(outer.outer.timestampLabel, outer.outer.idLabel, - options); - ackTimeoutMs = -1; - safeToAckIds = new HashSet<>(); - notYetRead = new ArrayDeque<>(); - inFlight = new LinkedHashMap<>(); - ackedIds = new ConcurrentLinkedQueue<>(); - notYetReadBytes = 0; - minUnreadTimestampMsSinceEpoch = new BucketingFunction(SAMPLE_UPDATE.getMillis(), - MIN_WATERMARK_SPREAD, - MIN_WATERMARK_MESSAGES, - MIN); - minReadTimestampMsSinceEpoch = newFun(MIN); - lastReceivedMsSinceEpoch = -1; - lastWatermarkMsSinceEpoch = BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis(); - current = null; - lastLogTimestampMsSinceEpoch = -1; - numReceived = 0L; - numReceivedRecently = newFun(SUM); - numExtendedDeadlines = newFun(SUM); - numLateDeadlines = newFun(SUM); - numAcked = newFun(SUM); - numExpired = newFun(SUM); - numNacked = newFun(SUM); - numReadBytes = newFun(SUM); - minReceivedTimestampMsSinceEpoch = newFun(MIN); - maxReceivedTimestampMsSinceEpoch = newFun(MAX); - minWatermarkMsSinceEpoch = newFun(MIN); - maxWatermarkMsSinceEpoch = newFun(MAX); - numLateMessages = newFun(SUM); - numInFlightCheckpoints = new AtomicInteger(); - maxInFlightCheckpoints = 0; - } - - @VisibleForTesting - PubsubClient getPubsubClient() { - return pubsubClient; - } - - /** - * BLOCKING - * ACK {@code ackIds} back to Pubsub. - * CAUTION: May be invoked from a separate checkpointing thread. - * CAUTION: Retains {@code ackIds}. - */ - void ackBatch(List ackIds) throws IOException { - pubsubClient.acknowledge(outer.outer.subscription.get(), ackIds); - ackedIds.add(ackIds); - } - - /** - * BLOCKING - * NACK (ie request deadline extension of 0) receipt of messages from Pubsub - * with the given {@code ockIds}. Does not retain {@code ackIds}. - */ - public void nackBatch(long nowMsSinceEpoch, List ackIds) throws IOException { - pubsubClient.modifyAckDeadline(outer.outer.subscription.get(), ackIds, 0); - numNacked.add(nowMsSinceEpoch, ackIds.size()); - } - - /** - * BLOCKING - * Extend the processing deadline for messages from Pubsub with the given {@code ackIds}. - * Does not retain {@code ackIds}. - */ - private void extendBatch(long nowMsSinceEpoch, List ackIds) throws IOException { - int extensionSec = (ackTimeoutMs * ACK_EXTENSION_PCT) / (100 * 1000); - pubsubClient.modifyAckDeadline(outer.outer.subscription.get(), ackIds, extensionSec); - numExtendedDeadlines.add(nowMsSinceEpoch, ackIds.size()); - } - - /** - * Return the current time, in ms since epoch. - */ - private long now() { - if (outer.outer.clock == null) { - return System.currentTimeMillis(); - } else { - return outer.outer.clock.currentTimeMillis(); - } - } - - /** - * Messages which have been ACKed (via the checkpoint finalize) are no longer in flight. - * This is only used for flow control and stats. - */ - private void retire() throws IOException { - long nowMsSinceEpoch = now(); - while (true) { - List ackIds = ackedIds.poll(); - if (ackIds == null) { - return; - } - numAcked.add(nowMsSinceEpoch, ackIds.size()); - for (String ackId : ackIds) { - inFlight.remove(ackId); - safeToAckIds.remove(ackId); - } - } - } - - /** - * BLOCKING - * Extend deadline for all messages which need it. - * CAUTION: If extensions can't keep up with wallclock then we'll never return. - */ - private void extend() throws IOException { - while (true) { - long nowMsSinceEpoch = now(); - List assumeExpired = new ArrayList<>(); - List toBeExtended = new ArrayList<>(); - List toBeExpired = new ArrayList<>(); - // Messages will be in increasing deadline order. - for (Map.Entry entry : inFlight.entrySet()) { - if (entry.getValue().ackDeadlineMsSinceEpoch - (ackTimeoutMs * ACK_SAFETY_PCT) / 100 - > nowMsSinceEpoch) { - // All remaining messages don't need their ACKs to be extended. - break; - } - - if (entry.getValue().ackDeadlineMsSinceEpoch - ACK_TOO_LATE.getMillis() - < nowMsSinceEpoch) { - // Pubsub may have already considered this message to have expired. - // If so it will (eventually) be made available on a future pull request. - // If this message ends up being committed then it will be considered a duplicate - // when re-pulled. - assumeExpired.add(entry.getKey()); - continue; - } - - if (entry.getValue().requestTimeMsSinceEpoch + PROCESSING_TIMEOUT.getMillis() - < nowMsSinceEpoch) { - // This message has been in-flight for too long. - // Give up on it, otherwise we risk extending its ACK indefinitely. - toBeExpired.add(entry.getKey()); - continue; - } - - // Extend the ACK for this message. - toBeExtended.add(entry.getKey()); - if (toBeExtended.size() >= ACK_BATCH_SIZE) { - // Enough for one batch. - break; - } - } - - if (assumeExpired.isEmpty() && toBeExtended.isEmpty() && toBeExpired.isEmpty()) { - // Nothing to be done. - return; - } - - if (!assumeExpired.isEmpty()) { - // If we didn't make the ACK deadline assume expired and no longer in flight. - numLateDeadlines.add(nowMsSinceEpoch, assumeExpired.size()); - for (String ackId : assumeExpired) { - inFlight.remove(ackId); - } - } - - if (!toBeExpired.isEmpty()) { - // Expired messages are no longer considered in flight. - numExpired.add(nowMsSinceEpoch, toBeExpired.size()); - for (String ackId : toBeExpired) { - inFlight.remove(ackId); - } - } - - if (!toBeExtended.isEmpty()) { - // Pubsub extends acks from it's notion of current time. - // We'll try to track that on our side, but note the deadlines won't necessarily agree. - long newDeadlineMsSinceEpoch = nowMsSinceEpoch + (ackTimeoutMs * ACK_EXTENSION_PCT) / 100; - for (String ackId : toBeExtended) { - // Maintain increasing ack deadline order. - InFlightState state = inFlight.remove(ackId); - inFlight.put(ackId, - new InFlightState(state.requestTimeMsSinceEpoch, newDeadlineMsSinceEpoch)); - } - // BLOCKs until extended. - extendBatch(nowMsSinceEpoch, toBeExtended); - } - } - } - - /** - * BLOCKING - * Fetch another batch of messages from Pubsub. - */ - private void pull() throws IOException { - if (inFlight.size() >= MAX_IN_FLIGHT) { - // Wait for checkpoint to be finalized before pulling anymore. - // There may be lag while checkpoints are persisted and the finalizeCheckpoint method - // is invoked. By limiting the in-flight messages we can ensure we don't end up consuming - // messages faster than we can checkpoint them. - return; - } - - long requestTimeMsSinceEpoch = now(); - long deadlineMsSinceEpoch = requestTimeMsSinceEpoch + ackTimeoutMs; - - // Pull the next batch. - // BLOCKs until received. - Collection receivedMessages = - pubsubClient.pull(requestTimeMsSinceEpoch, - outer.outer.subscription.get(), - PULL_BATCH_SIZE, true); - if (receivedMessages.isEmpty()) { - // Nothing available yet. Try again later. - return; - } - - lastReceivedMsSinceEpoch = requestTimeMsSinceEpoch; - - // Capture the received messages. - for (PubsubClient.IncomingMessage incomingMessage : receivedMessages) { - notYetRead.add(incomingMessage); - notYetReadBytes += incomingMessage.elementBytes.length; - inFlight.put(incomingMessage.ackId, - new InFlightState(requestTimeMsSinceEpoch, deadlineMsSinceEpoch)); - numReceived++; - numReceivedRecently.add(requestTimeMsSinceEpoch, 1L); - minReceivedTimestampMsSinceEpoch.add(requestTimeMsSinceEpoch, - incomingMessage.timestampMsSinceEpoch); - maxReceivedTimestampMsSinceEpoch.add(requestTimeMsSinceEpoch, - incomingMessage.timestampMsSinceEpoch); - minUnreadTimestampMsSinceEpoch.add(requestTimeMsSinceEpoch, - incomingMessage.timestampMsSinceEpoch); - } - } - - /** - * Log stats if time to do so. - */ - private void stats() { - long nowMsSinceEpoch = now(); - if (lastLogTimestampMsSinceEpoch < 0) { - lastLogTimestampMsSinceEpoch = nowMsSinceEpoch; - return; - } - long deltaMs = nowMsSinceEpoch - lastLogTimestampMsSinceEpoch; - if (deltaMs < LOG_PERIOD.getMillis()) { - return; - } - - String messageSkew = "unknown"; - long minTimestamp = minReceivedTimestampMsSinceEpoch.get(nowMsSinceEpoch); - long maxTimestamp = maxReceivedTimestampMsSinceEpoch.get(nowMsSinceEpoch); - if (minTimestamp < Long.MAX_VALUE && maxTimestamp > Long.MIN_VALUE) { - messageSkew = (maxTimestamp - minTimestamp) + "ms"; - } - - String watermarkSkew = "unknown"; - long minWatermark = minWatermarkMsSinceEpoch.get(nowMsSinceEpoch); - long maxWatermark = maxWatermarkMsSinceEpoch.get(nowMsSinceEpoch); - if (minWatermark < Long.MAX_VALUE && maxWatermark > Long.MIN_VALUE) { - watermarkSkew = (maxWatermark - minWatermark) + "ms"; - } - - String oldestInFlight = "no"; - String oldestAckId = Iterables.getFirst(inFlight.keySet(), null); - if (oldestAckId != null) { - oldestInFlight = - (nowMsSinceEpoch - inFlight.get(oldestAckId).requestTimeMsSinceEpoch) + "ms"; - } - - LOG.info("Pubsub {} has " - + "{} received messages, " - + "{} current unread messages, " - + "{} current unread bytes, " - + "{} current in-flight msgs, " - + "{} oldest in-flight, " - + "{} current in-flight checkpoints, " - + "{} max in-flight checkpoints, " - + "{}B/s recent read, " - + "{} recent received, " - + "{} recent extended, " - + "{} recent late extended, " - + "{} recent ACKed, " - + "{} recent NACKed, " - + "{} recent expired, " - + "{} recent message timestamp skew, " - + "{} recent watermark skew, " - + "{} recent late messages, " - + "{} last reported watermark", - outer.outer.subscription, - numReceived, - notYetRead.size(), - notYetReadBytes, - inFlight.size(), - oldestInFlight, - numInFlightCheckpoints.get(), - maxInFlightCheckpoints, - numReadBytes.get(nowMsSinceEpoch) / (SAMPLE_PERIOD.getMillis() / 1000L), - numReceivedRecently.get(nowMsSinceEpoch), - numExtendedDeadlines.get(nowMsSinceEpoch), - numLateDeadlines.get(nowMsSinceEpoch), - numAcked.get(nowMsSinceEpoch), - numNacked.get(nowMsSinceEpoch), - numExpired.get(nowMsSinceEpoch), - messageSkew, - watermarkSkew, - numLateMessages.get(nowMsSinceEpoch), - new Instant(lastWatermarkMsSinceEpoch)); - - lastLogTimestampMsSinceEpoch = nowMsSinceEpoch; - } - - @Override - public boolean start() throws IOException { - // Determine the ack timeout. - ackTimeoutMs = pubsubClient.ackDeadlineSeconds(outer.outer.subscription.get()) * 1000; - return advance(); - } - - /** - * BLOCKING - * Return {@literal true} if a Pubsub messaage is available, {@literal false} if - * none is available at this time or we are over-subscribed. May BLOCK while extending - * ACKs or fetching available messages. Will not block waiting for messages. - */ - @Override - public boolean advance() throws IOException { - // Emit stats. - stats(); - - if (current != null) { - // Current is consumed. It can no longer contribute to holding back the watermark. - minUnreadTimestampMsSinceEpoch.remove(current.requestTimeMsSinceEpoch); - current = null; - } - - // Retire state associated with ACKed messages. - retire(); - - // Extend all pressing deadlines. - // Will BLOCK until done. - // If the system is pulling messages only to let them sit in a downsteam queue then - // this will have the effect of slowing down the pull rate. - // However, if the system is genuinely taking longer to process each message then - // the work to extend ACKs would be better done in the background. - extend(); - - if (notYetRead.isEmpty()) { - // Pull another batch. - // Will BLOCK until fetch returns, but will not block until a message is available. - pull(); - } - - // Take one message from queue. - current = notYetRead.poll(); - if (current == null) { - // Try again later. - return false; - } - notYetReadBytes -= current.elementBytes.length; - checkState(notYetReadBytes >= 0); - long nowMsSinceEpoch = now(); - numReadBytes.add(nowMsSinceEpoch, current.elementBytes.length); - minReadTimestampMsSinceEpoch.add(nowMsSinceEpoch, current.timestampMsSinceEpoch); - if (current.timestampMsSinceEpoch < lastWatermarkMsSinceEpoch) { - numLateMessages.add(nowMsSinceEpoch, 1L); - } - - // Current message can be considered 'read' and will be persisted by the next - // checkpoint. So it is now safe to ACK back to Pubsub. - safeToAckIds.add(current.ackId); - return true; - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - try { - return CoderUtils.decodeFromByteArray(outer.outer.elementCoder, current.elementBytes); - } catch (CoderException e) { - throw new RuntimeException("Unable to decode element from Pubsub message: ", e); - } - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return new Instant(current.timestampMsSinceEpoch); - } - - @Override - public byte[] getCurrentRecordId() throws NoSuchElementException { - if (current == null) { - throw new NoSuchElementException(); - } - return current.recordId.getBytes(Charsets.UTF_8); - } - - @Override - public void close() throws IOException { - if (pubsubClient != null) { - pubsubClient.close(); - pubsubClient = null; - } - } - - @Override - public PubsubSource getCurrentSource() { - return outer; - } - - @Override - public Instant getWatermark() { - if (pubsubClient.isEOF() && notYetRead.isEmpty()) { - // For testing only: Advance the watermark to the end of time to signal - // the test is complete. - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - // NOTE: We'll allow the watermark to go backwards. The underlying runner is responsible - // for aggregating all reported watermarks and ensuring the aggregate is latched. - // If we attempt to latch locally then it is possible a temporary starvation of one reader - // could cause its estimated watermark to fast forward to current system time. Then when - // the reader resumes its watermark would be unable to resume tracking. - // By letting the underlying runner latch we avoid any problems due to localized starvation. - long nowMsSinceEpoch = now(); - long readMin = minReadTimestampMsSinceEpoch.get(nowMsSinceEpoch); - long unreadMin = minUnreadTimestampMsSinceEpoch.get(); - if (readMin == Long.MAX_VALUE - && unreadMin == Long.MAX_VALUE - && lastReceivedMsSinceEpoch >= 0 - && nowMsSinceEpoch > lastReceivedMsSinceEpoch + SAMPLE_PERIOD.getMillis()) { - // We don't currently have any unread messages pending, we have not had any messages - // read for a while, and we have not received any new messages from Pubsub for a while. - // Advance watermark to current time. - // TODO: Estimate a timestamp lag. - lastWatermarkMsSinceEpoch = nowMsSinceEpoch; - } else if (minReadTimestampMsSinceEpoch.isSignificant() - || minUnreadTimestampMsSinceEpoch.isSignificant()) { - // Take minimum of the timestamps in all unread messages and recently read messages. - lastWatermarkMsSinceEpoch = Math.min(readMin, unreadMin); - } - // else: We're not confident enough to estimate a new watermark. Stick with the old one. - minWatermarkMsSinceEpoch.add(nowMsSinceEpoch, lastWatermarkMsSinceEpoch); - maxWatermarkMsSinceEpoch.add(nowMsSinceEpoch, lastWatermarkMsSinceEpoch); - return new Instant(lastWatermarkMsSinceEpoch); - } - - @Override - public PubsubCheckpoint getCheckpointMark() { - int cur = numInFlightCheckpoints.incrementAndGet(); - maxInFlightCheckpoints = Math.max(maxInFlightCheckpoints, cur); - // It's possible for a checkpoint to be taken but never finalized. - // So we simply copy whatever safeToAckIds we currently have. - // It's possible a later checkpoint will be taken before an earlier one is finalized, - // in which case we'll double ACK messages to Pubsub. However Pubsub is fine with that. - List snapshotSafeToAckIds = Lists.newArrayList(safeToAckIds); - List snapshotNotYetReadIds = new ArrayList<>(notYetRead.size()); - for (PubsubClient.IncomingMessage incomingMessage : notYetRead) { - snapshotNotYetReadIds.add(incomingMessage.ackId); - } - return new PubsubCheckpoint<>(this, snapshotSafeToAckIds, snapshotNotYetReadIds); - } - - @Override - public long getSplitBacklogBytes() { - return notYetReadBytes; - } - } - - // ================================================================================ - // Source - // ================================================================================ - - @VisibleForTesting - static class PubsubSource extends UnboundedSource> { - public final PubsubUnboundedSource outer; - - public PubsubSource(PubsubUnboundedSource outer) { - this.outer = outer; - } - - @Override - public List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception { - List> result = new ArrayList<>(desiredNumSplits); - for (int i = 0; i < desiredNumSplits * SCALE_OUT; i++) { - // Since the source is immutable and Pubsub automatically shards we simply - // replicate ourselves the requested number of times - result.add(this); - } - return result; - } - - @Override - public PubsubReader createReader( - PipelineOptions options, - @Nullable PubsubCheckpoint checkpoint) { - PubsubReader reader; - try { - reader = new PubsubReader<>(options.as(DataflowPipelineOptions.class), this); - } catch (GeneralSecurityException | IOException e) { - throw new RuntimeException("Unable to subscribe to " + outer.subscription + ": ", e); - } - if (checkpoint != null) { - // NACK all messages we may have lost. - try { - // Will BLOCK until NACKed. - checkpoint.nackAll(reader); - } catch (IOException e) { - LOG.error("Pubsub {} cannot have {} lost messages NACKed, ignoring: {}", - outer.subscription, checkpoint.notYetReadIds.size(), e); - } - } - return reader; - } - - @Nullable - @Override - public Coder> getCheckpointMarkCoder() { - @SuppressWarnings("unchecked") PubsubCheckpointCoder typedCoder = - (PubsubCheckpointCoder) CHECKPOINT_CODER; - return typedCoder; - } - - @Override - public Coder getDefaultOutputCoder() { - return outer.elementCoder; - } - - @Override - public void validate() { - // Nothing to validate. - } - - @Override - public boolean requiresDeduping() { - // We cannot prevent re-offering already read messages after a restore from checkpoint. - return true; - } - } - - // ================================================================================ - // StatsFn - // ================================================================================ - - private static class StatsFn extends DoFn { - private final Aggregator elementCounter = - createAggregator("elements", new Sum.SumLongFn()); - - private final PubsubClientFactory pubsubFactory; - private final ValueProvider subscription; - @Nullable - private final String timestampLabel; - @Nullable - private final String idLabel; - - public StatsFn( - PubsubClientFactory pubsubFactory, - ValueProvider subscription, - @Nullable - String timestampLabel, - @Nullable - String idLabel) { - this.pubsubFactory = pubsubFactory; - this.subscription = subscription; - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - elementCounter.addValue(1L); - c.output(c.element()); - } - - @Override - public void populateDisplayData(Builder builder) { - super.populateDisplayData(builder); - String subscriptionString = - subscription == null ? null - : subscription.isAccessible() ? subscription.get().getPath() - : subscription.toString(); - builder.add(DisplayData.item("subscription", subscriptionString)); - builder.add(DisplayData.item("transport", pubsubFactory.getKind())); - builder.addIfNotNull(DisplayData.item("timestampLabel", timestampLabel)); - builder.addIfNotNull(DisplayData.item("idLabel", idLabel)); - } - } - - // ================================================================================ - // PubsubUnboundedSource - // ================================================================================ - - /** - * For testing only: Clock to use for all timekeeping. If {@literal null} use system clock. - */ - @Nullable - private Clock clock; - - /** - * Factory for creating underlying Pubsub transport. - */ - private final PubsubClientFactory pubsubFactory; - - /** - * Project under which to create a subscription if only the {@link #topic} was given. - */ - @Nullable - private final ValueProvider project; - - /** - * Topic to read from. If {@literal null}, then {@link #subscription} must be given. - * Otherwise {@link #subscription} must be null. - */ - @Nullable - private final ValueProvider topic; - - /** - * Subscription to read from. If {@literal null} then {@link #topic} must be given. - * Otherwise {@link #topic} must be null. - * - *

              If no subscription is given a random one will be created when the transorm is - * applied. This field will be update with that subscription's path. The created - * subscription is never deleted. - */ - @Nullable - private ValueProvider subscription; - - /** - * Coder for elements. Elements are effectively double-encoded: first to a byte array - * using this checkpointCoder, then to a base-64 string to conform to Pubsub's payload - * conventions. - */ - private final Coder elementCoder; - - /** - * Pubsub metadata field holding timestamp of each element, or {@literal null} if should use - * Pubsub message publish timestamp instead. - */ - @Nullable - private final String timestampLabel; - - /** - * Pubsub metadata field holding id for each element, or {@literal null} if need to generate - * a unique id ourselves. - */ - @Nullable - private final String idLabel; - - @VisibleForTesting - PubsubUnboundedSource( - Clock clock, - PubsubClientFactory pubsubFactory, - @Nullable ValueProvider project, - @Nullable ValueProvider topic, - @Nullable ValueProvider subscription, - Coder elementCoder, - @Nullable String timestampLabel, - @Nullable String idLabel) { - checkArgument((topic == null) != (subscription == null), - "Exactly one of topic and subscription must be given"); - checkArgument((topic == null) == (project == null), - "Project must be given if topic is given"); - this.clock = clock; - this.pubsubFactory = checkNotNull(pubsubFactory); - this.project = project; - this.topic = topic; - this.subscription = subscription; - this.elementCoder = checkNotNull(elementCoder); - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - } - - /** - * Construct an unbounded source to consume from the Pubsub {@code subscription}. - */ - public PubsubUnboundedSource( - PubsubClientFactory pubsubFactory, - @Nullable ValueProvider project, - @Nullable ValueProvider topic, - @Nullable ValueProvider subscription, - Coder elementCoder, - @Nullable String timestampLabel, - @Nullable String idLabel) { - this(null, pubsubFactory, project, topic, subscription, elementCoder, timestampLabel, idLabel); - } - - public Coder getElementCoder() { - return elementCoder; - } - - @Nullable - public ProjectPath getProject() { - return project == null ? null : project.get(); - } - - @Nullable - public TopicPath getTopic() { - return topic == null ? null : topic.get(); - } - - @Nullable - public ValueProvider getTopicProvider() { - return topic; - } - - @Nullable - public SubscriptionPath getSubscription() { - return subscription == null ? null : subscription.get(); - } - - @Nullable - public ValueProvider getSubscriptionProvider() { - return subscription; - } - - @Nullable - public String getTimestampLabel() { - return timestampLabel; - } - - @Nullable - public String getIdLabel() { - return idLabel; - } - - @Override - public PCollection apply(PBegin input) { - if (subscription == null) { - try { - try (PubsubClient pubsubClient = - pubsubFactory.newClient(timestampLabel, idLabel, - input.getPipeline() - .getOptions() - .as(DataflowPipelineOptions.class))) { - checkState(project.isAccessible(), "createRandomSubscription must be called at runtime."); - checkState(topic.isAccessible(), "createRandomSubscription must be called at runtime."); - SubscriptionPath subscriptionPath = - pubsubClient.createRandomSubscription( - project.get(), topic.get(), DEAULT_ACK_TIMEOUT_SEC); - LOG.warn("Created subscription {} to topic {}." - + " Note this subscription WILL NOT be deleted when the pipeline terminates", - subscription, topic); - } - } catch (Exception e) { - throw new RuntimeException("Failed to create subscription: ", e); - } - } - - return input.getPipeline().begin() - .apply(Read.from(new PubsubSource(this))) - .apply(ParDo.named("PubsubUnboundedSource.Stats") - .of(new StatsFn(pubsubFactory, subscription, - timestampLabel, idLabel))); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java deleted file mode 100644 index ef77a6371f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Read.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.util.StringUtils.approximateSimpleName; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PInput; - -import org.joda.time.Duration; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A {@link PTransform} for reading from a {@link Source}. - * - *

              Usage example: - *

              - * Pipeline p = Pipeline.create();
              - * p.apply(Read.from(new MySource().withFoo("foo").withBar("bar"))
              - *             .named("foobar"));
              - * 
              - */ -public class Read { - /** - * Returns a new {@code Read} {@code PTransform} builder with the given name. - */ - public static Builder named(String name) { - return new Builder(name); - } - - /** - * Returns a new {@code Read.Bounded} {@code PTransform} reading from the given - * {@code BoundedSource}. - */ - public static Bounded from(BoundedSource source) { - return new Bounded<>(null, source); - } - - /** - * Returns a new {@code Read.Unbounded} {@code PTransform} reading from the given - * {@code UnboundedSource}. - */ - public static Unbounded from(UnboundedSource source) { - return new Unbounded<>(null, source); - } - - /** - * Helper class for building {@code Read} transforms. - */ - public static class Builder { - private final String name; - - private Builder(String name) { - this.name = name; - } - - /** - * Returns a new {@code Read.Bounded} {@code PTransform} reading from the given - * {@code BoundedSource}. - */ - public Bounded from(BoundedSource source) { - return new Bounded<>(name, source); - } - - /** - * Returns a new {@code Read.Unbounded} {@code PTransform} reading from the given - * {@code UnboundedSource}. - */ - public Unbounded from(UnboundedSource source) { - return new Unbounded<>(name, source); - } - } - - /** - * {@link PTransform} that reads from a {@link BoundedSource}. - */ - public static class Bounded extends PTransform> { - private final BoundedSource source; - - private Bounded(@Nullable String name, BoundedSource source) { - super(name); - this.source = SerializableUtils.ensureSerializable(source); - } - - /** - * Returns a new {@code Bounded} {@code PTransform} that's like this one but - * has the given name. - * - *

              Does not modify this object. - */ - public Bounded named(String name) { - return new Bounded(name, source); - } - - @Override - protected Coder getDefaultOutputCoder() { - return source.getDefaultOutputCoder(); - } - - @Override - public final PCollection apply(PInput input) { - source.validate(); - - return PCollection.createPrimitiveOutputInternal(input.getPipeline(), - WindowingStrategy.globalDefault(), IsBounded.BOUNDED) - .setCoder(getDefaultOutputCoder()); - } - - /** - * Returns the {@code BoundedSource} used to create this {@code Read} {@code PTransform}. - */ - public BoundedSource getSource() { - return source; - } - - @Override - public String getKindString() { - return "Read(" + approximateSimpleName(source.getClass()) + ")"; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("source", source.getClass()) - .withLabel("Read Source")) - .include(source); - } - - static { - registerDefaultTransformEvaluator(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private static void registerDefaultTransformEvaluator() { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bounded.class, - new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bounded transform, DirectPipelineRunner.EvaluationContext context) { - evaluateReadHelper(transform, context); - } - - private void evaluateReadHelper( - Read.Bounded transform, DirectPipelineRunner.EvaluationContext context) { - try { - List> output = new ArrayList<>(); - BoundedSource source = transform.getSource(); - try (BoundedSource.BoundedReader reader = - source.createReader(context.getPipelineOptions())) { - for (boolean available = reader.start(); - available; - available = reader.advance()) { - output.add( - DirectPipelineRunner.ValueWithMetadata.of( - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp()))); - } - } - context.setPCollectionValuesWithMetadata(context.getOutput(transform), output); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - } - - /** - * {@link PTransform} that reads from a {@link UnboundedSource}. - */ - public static class Unbounded extends PTransform> { - private final UnboundedSource source; - - private Unbounded(@Nullable String name, UnboundedSource source) { - super(name); - this.source = SerializableUtils.ensureSerializable(source); - } - - /** - * Returns a new {@code Unbounded} {@code PTransform} that's like this one but - * has the given name. - * - *

              Does not modify this object. - */ - public Unbounded named(String name) { - return new Unbounded(name, source); - } - - /** - * Returns a new {@link BoundedReadFromUnboundedSource} that reads a bounded amount - * of data from the given {@link UnboundedSource}. The bound is specified as a number - * of records to read. - * - *

              This may take a long time to execute if the splits of this source are slow to read - * records. - */ - public BoundedReadFromUnboundedSource withMaxNumRecords(long maxNumRecords) { - return new BoundedReadFromUnboundedSource(source, maxNumRecords, null); - } - - /** - * Returns a new {@link BoundedReadFromUnboundedSource} that reads a bounded amount - * of data from the given {@link UnboundedSource}. The bound is specified as an amount - * of time to read for. Each split of the source will read for this much time. - */ - public BoundedReadFromUnboundedSource withMaxReadTime(Duration maxReadTime) { - return new BoundedReadFromUnboundedSource(source, Long.MAX_VALUE, maxReadTime); - } - - @Override - protected Coder getDefaultOutputCoder() { - return source.getDefaultOutputCoder(); - } - - @Override - public final PCollection apply(PInput input) { - source.validate(); - - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED); - } - - /** - * Returns the {@code UnboundedSource} used to create this {@code Read} {@code PTransform}. - */ - public UnboundedSource getSource() { - return source; - } - - @Override - public String getKindString() { - return "Read(" + approximateSimpleName(source.getClass()) + ")"; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("source", source.getClass()) - .withLabel("Read Source")) - .include(source); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/ShardNameTemplate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/ShardNameTemplate.java deleted file mode 100644 index 7270012768..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/ShardNameTemplate.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -/** - * Standard shard naming templates. - * - *

              Shard naming templates are strings that may contain placeholders for - * the shard number and shard count. When constructing a filename for a - * particular shard number, the upper-case letters 'S' and 'N' are replaced - * with the 0-padded shard number and shard count respectively. - * - *

              Left-padding of the numbers enables lexicographical sorting of the - * resulting filenames. If the shard number or count are too large for the - * space provided in the template, then the result may no longer sort - * lexicographically. For example, a shard template of "S-of-N", for 200 - * shards, will result in outputs named "0-of-200", ... '10-of-200', - * '100-of-200", etc. - * - *

              Shard numbers start with 0, so the last shard number is the shard count - * minus one. For example, the template "-SSSSS-of-NNNNN" will be - * instantiated as "-00000-of-01000" for the first shard (shard 0) of a - * 1000-way sharded output. - * - *

              A shard name template is typically provided along with a name prefix - * and suffix, which allows constructing complex paths that have embedded - * shard information. For example, outputs in the form - * "gs://bucket/path-01-of-99.txt" could be constructed by providing the - * individual components: - * - *

              {@code
              - *   pipeline.apply(
              - *       TextIO.Write.to("gs://bucket/path")
              - *                   .withShardNameTemplate("-SS-of-NN")
              - *                   .withSuffix(".txt"))
              - * }
              - * - *

              In the example above, you could make parts of the output configurable - * by users without the user having to specify all components of the output - * name. - * - *

              If a shard name template does not contain any repeating 'S', then - * the output shard count must be 1, as otherwise the same filename would be - * generated for multiple shards. - */ -public class ShardNameTemplate { - /** - * Shard name containing the index and max. - * - *

              Eg: [prefix]-00000-of-00100[suffix] and - * [prefix]-00001-of-00100[suffix] - */ - public static final String INDEX_OF_MAX = "-SSSSS-of-NNNNN"; - - /** - * Shard is a file within a directory. - * - *

              Eg: [prefix]/part-00000[suffix] and [prefix]/part-00001[suffix] - */ - public static final String DIRECTORY_CONTAINER = "/part-SSSSS"; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java deleted file mode 100644 index af244d933a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Sink.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import java.io.Serializable; - -/** - * A {@code Sink} represents a resource that can be written to using the {@link Write} transform. - * - *

              A parallel write to a {@code Sink} consists of three phases: - *

                - *
              1. A sequential initialization phase (e.g., creating a temporary output directory, etc.) - *
              2. A parallel write phase where workers write bundles of records - *
              3. A sequential finalization phase (e.g., committing the writes, merging output files, - * etc.) - *
              - * - *

              The {@link Write} transform can be used in a Dataflow pipeline to perform this write. - * Specifically, a Write transform can be applied to a {@link PCollection} {@code p} by: - * - *

              {@code p.apply(Write.to(new MySink()));} - * - *

              Implementing a {@link Sink} and the corresponding write operations requires extending three - * abstract classes: - * - *

                - *
              • {@link Sink}: an immutable logical description of the location/resource to write to. - * Depending on the type of sink, it may contain fields such as the path to an output directory - * on a filesystem, a database table name, etc. Implementors of {@link Sink} must - * implement two methods: {@link Sink#validate} and {@link Sink#createWriteOperation}. - * {@link Sink#validate Validate} is called by the Write transform at pipeline creation, and should - * validate that the Sink can be written to. The createWriteOperation method is also called at - * pipeline creation, and should return a WriteOperation object that defines how to write to the - * Sink. Note that implementations of Sink must be serializable and Sinks must be immutable. - * - *
              • {@link WriteOperation}: The WriteOperation implements the initialization and - * finalization phases of a write. Implementors of {@link WriteOperation} must implement - * corresponding {@link WriteOperation#initialize} and {@link WriteOperation#finalize} methods. A - * WriteOperation must also implement {@link WriteOperation#createWriter} that creates Writers, - * {@link WriteOperation#getWriterResultCoder} that returns a {@link Coder} for the result of a - * parallel write, and a {@link WriteOperation#getSink} that returns the Sink that the write - * operation corresponds to. See below for more information about these methods and restrictions on - * their implementation. - * - *
              • {@link Writer}: A Writer writes a bundle of records. Writer defines four methods: - * {@link Writer#open}, which is called once at the start of writing a bundle; {@link Writer#write}, - * which writes a single record from the bundle; {@link Writer#close}, which is called once at the - * end of writing a bundle; and {@link Writer#getWriteOperation}, which returns the write operation - * that the writer belongs to. - *
              - * - *

              WriteOperation

              - * - *

              {@link WriteOperation#initialize} and {@link WriteOperation#finalize} are conceptually called - * once: at the beginning and end of a Write transform. However, implementors must ensure that these - * methods are idempotent, as they may be called multiple times on different machines in the case of - * failure/retry or for redundancy. - * - *

              The finalize method of WriteOperation is passed an Iterable of a writer result type. This - * writer result type should encode the result of a write and, in most cases, some encoding of the - * unique bundle id. - * - *

              All implementations of {@link WriteOperation} must be serializable. - * - *

              WriteOperation may have mutable state. For instance, {@link WriteOperation#initialize} may - * mutate the object state. These mutations will be visible in {@link WriteOperation#createWriter} - * and {@link WriteOperation#finalize} because the object will be serialized after initialize and - * deserialized before these calls. However, it is not serialized again after createWriter is - * called, as createWriter will be called within workers to create Writers for the bundles that are - * distributed to these workers. Therefore, newWriter should not mutate the WriteOperation state (as - * these mutations will not be visible in finalize). - * - *

              Bundle Ids:

              - * - *

              In order to ensure fault-tolerance, a bundle may be executed multiple times (e.g., in the - * event of failure/retry or for redundancy). However, exactly one of these executions will have its - * result passed to the WriteOperation's finalize method. Each call to {@link Writer#open} is passed - * a unique bundle id when it is called by the Write transform, so even redundant or retried - * bundles will have a unique way of identifying their output. - * - *

              The bundle id should be used to guarantee that a bundle's output is unique. This uniqueness - * guarantee is important; if a bundle is to be output to a file, for example, the name of the file - * must be unique to avoid conflicts with other Writers. The bundle id should be encoded in the - * writer result returned by the Writer and subsequently used by the WriteOperation's finalize - * method to identify the results of successful writes. - * - *

              For example, consider the scenario where a Writer writes files containing serialized records - * and the WriteOperation's finalization step is to merge or rename these output files. In this - * case, a Writer may use its unique id to name its output file (to avoid conflicts) and return the - * name of the file it wrote as its writer result. The WriteOperation will then receive an Iterable - * of output file names that it can then merge or rename using some bundle naming scheme. - * - *

              Writer Results:

              - * - *

              {@link WriteOperation}s and {@link Writer}s must agree on a writer result type that will be - * returned by a Writer after it writes a bundle. This type can be a client-defined object or an - * existing type; {@link WriteOperation#getWriterResultCoder} should return a {@link Coder} for the - * type. - * - *

              A note about thread safety: Any use of static members or methods in Writer should be thread - * safe, as different instances of Writer objects may be created in different threads on the same - * worker. - * - * @param the type that will be written to the Sink. - */ -@Experimental(Experimental.Kind.SOURCE_SINK) -public abstract class Sink implements Serializable, HasDisplayData { - /** - * Ensures that the sink is valid and can be written to before the write operation begins. One - * should use {@link com.google.common.base.Preconditions} to implement this method. - */ - public abstract void validate(PipelineOptions options); - - /** - * Returns an instance of a {@link WriteOperation} that can write to this Sink. - */ - public abstract WriteOperation createWriteOperation(PipelineOptions options); - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(DisplayData.Builder builder) {} - - /** - * A {@link WriteOperation} defines the process of a parallel write of objects to a Sink. - * - *

              The {@code WriteOperation} defines how to perform initialization and finalization of a - * parallel write to a sink as well as how to create a {@link Sink.Writer} object that can write - * a bundle to the sink. - * - *

              Since operations in Dataflow may be run multiple times for redundancy or fault-tolerance, - * the initialization and finalization defined by a WriteOperation must be idempotent. - * - *

              {@code WriteOperation}s may be mutable; a {@code WriteOperation} is serialized after the - * call to {@code initialize} method and deserialized before calls to - * {@code createWriter} and {@code finalized}. However, it is not - * reserialized after {@code createWriter}, so {@code createWriter} should not mutate the - * state of the {@code WriteOperation}. - * - *

              See {@link Sink} for more detailed documentation about the process of writing to a Sink. - * - * @param The type of objects to write - * @param The result of a per-bundle write - */ - public abstract static class WriteOperation implements Serializable { - /** - * Performs initialization before writing to the sink. Called before writing begins. - */ - public abstract void initialize(PipelineOptions options) throws Exception; - - /** - * Given an Iterable of results from bundle writes, performs finalization after writing and - * closes the sink. Called after all bundle writes are complete. - * - *

              The results that are passed to finalize are those returned by bundles that completed - * successfully. Although bundles may have been run multiple times (for fault-tolerance), only - * one writer result will be passed to finalize for each bundle. An implementation of finalize - * should perform clean up of any failed and successfully retried bundles. Note that these - * failed bundles will not have their writer result passed to finalize, so finalize should be - * capable of locating any temporary/partial output written by failed bundles. - * - *

              A best practice is to make finalize atomic. If this is impossible given the semantics - * of the sink, finalize should be idempotent, as it may be called multiple times in the case of - * failure/retry or for redundancy. - * - *

              Note that the iteration order of the writer results is not guaranteed to be consistent if - * finalize is called multiple times. - * - * @param writerResults an Iterable of results from successful bundle writes. - */ - public abstract void finalize(Iterable writerResults, PipelineOptions options) - throws Exception; - - /** - * Creates a new {@link Sink.Writer} to write a bundle of the input to the sink. - * - *

              The bundle id that the writer will use to uniquely identify its output will be passed to - * {@link Writer#open}. - * - *

              Must not mutate the state of the WriteOperation. - */ - public abstract Writer createWriter(PipelineOptions options) throws Exception; - - /** - * Returns the Sink that this write operation writes to. - */ - public abstract Sink getSink(); - - /** - * Returns a coder for the writer result type. - */ - public Coder getWriterResultCoder() { - return null; - } - } - - /** - * A Writer writes a bundle of elements from a PCollection to a sink. {@link Writer#open} is - * called before writing begins and {@link Writer#close} is called after all elements in the - * bundle have been written. {@link Writer#write} writes an element to the sink. - * - *

              Note that any access to static members or methods of a Writer must be thread-safe, as - * multiple instances of a Writer may be instantiated in different threads on the same worker. - * - *

              See {@link Sink} for more detailed documentation about the process of writing to a Sink. - * - * @param The type of object to write - * @param The writer results type (e.g., the bundle's output filename, as String) - */ - public abstract static class Writer { - /** - * Performs bundle initialization. For example, creates a temporary file for writing or - * initializes any state that will be used across calls to {@link Writer#write}. - * - *

              The unique id that is given to open should be used to ensure that the writer's output does - * not interfere with the output of other Writers, as a bundle may be executed many times for - * fault tolerance. See {@link Sink} for more information about bundle ids. - */ - public abstract void open(String uId) throws Exception; - - /** - * Called for each value in the bundle. - */ - public abstract void write(T value) throws Exception; - - /** - * Finishes writing the bundle. Closes any resources used for writing the bundle. - * - *

              Returns a writer result that will be used in the {@link Sink.WriteOperation}'s - * finalization. The result should contain some way to identify the output of this bundle (using - * the bundle id). {@link WriteOperation#finalize} will use the writer result to identify - * successful writes. See {@link Sink} for more information about bundle ids. - * - * @return the writer result - */ - public abstract WriteT close() throws Exception; - - /** - * Returns the write operation this writer belongs to. - */ - public abstract WriteOperation getWriteOperation(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java deleted file mode 100644 index 81d5dfdebc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Source.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.Serializable; -import java.util.NoSuchElementException; - -/** - * Base class for defining input formats and creating a {@code Source} for reading the input. - * - *

              This class is not intended to be subclassed directly. Instead, to define - * a bounded source (a source which produces a finite amount of input), subclass - * {@link BoundedSource}; to define an unbounded source, subclass {@link UnboundedSource}. - * - *

              A {@code Source} passed to a {@code Read} transform must be - * {@code Serializable}. This allows the {@code Source} instance - * created in this "main program" to be sent (in serialized form) to - * remote worker machines and reconstituted for each batch of elements - * of the input {@code PCollection} being processed or for each source splitting - * operation. A {@code Source} can have instance variable state, and - * non-transient instance variable state will be serialized in the main program - * and then deserialized on remote worker machines. - * - *

              {@code Source} classes MUST be effectively immutable. The only acceptable use of - * mutable fields is to cache the results of expensive operations, and such fields MUST be - * marked {@code transient}. - * - *

              {@code Source} objects should override {@link Object#toString}, as it will be - * used in important error and debugging messages. - * - * @param Type of elements read by the source. - */ -@Experimental(Experimental.Kind.SOURCE_SINK) -public abstract class Source implements Serializable, HasDisplayData { - /** - * Checks that this source is valid, before it can be used in a pipeline. - * - *

              It is recommended to use {@link com.google.common.base.Preconditions} for implementing - * this method. - */ - public abstract void validate(); - - /** - * Returns the default {@code Coder} to use for the data read from this source. - */ - public abstract Coder getDefaultOutputCoder(); - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(DisplayData.Builder builder) {} - - /** - * The interface that readers of custom input sources must implement. - * - *

              This interface is deliberately distinct from {@link java.util.Iterator} because - * the current model tends to be easier to program and more efficient in practice - * for iterating over sources such as files, databases etc. (rather than pure collections). - * - *

              Reading data from the {@link Reader} must obey the following access pattern: - *

                - *
              • One call to {@link #start} - *
                • If {@link #start} returned true, any number of calls to {@code getCurrent}* - * methods
                - *
              • Repeatedly, a call to {@link #advance}. This may be called regardless - * of what the previous {@link #start}/{@link #advance} returned. - *
                • If {@link #advance} returned true, any number of calls to {@code getCurrent}* - * methods
                - *
              - * - *

              For example, if the reader is reading a fixed set of data: - *

              -   *   try {
              -   *     for (boolean available = reader.start(); available; available = reader.advance()) {
              -   *       T item = reader.getCurrent();
              -   *       Instant timestamp = reader.getCurrentTimestamp();
              -   *       ...
              -   *     }
              -   *   } finally {
              -   *     reader.close();
              -   *   }
              -   * 
              - * - *

              If the set of data being read is continually growing: - *

              -   *   try {
              -   *     boolean available = reader.start();
              -   *     while (true) {
              -   *       if (available) {
              -   *         T item = reader.getCurrent();
              -   *         Instant timestamp = reader.getCurrentTimestamp();
              -   *         ...
              -   *         resetExponentialBackoff();
              -   *       } else {
              -   *         exponentialBackoff();
              -   *       }
              -   *       available = reader.advance();
              -   *     }
              -   *   } finally {
              -   *     reader.close();
              -   *   }
              -   * 
              - * - *

              Note: this interface is a work-in-progress and may change. - * - *

              All {@code Reader} functions except {@link #getCurrentSource} do not need to be thread-safe; - * they may only be accessed by a single thread at once. However, {@link #getCurrentSource} needs - * to be thread-safe, and other functions should assume that its returned value can change - * asynchronously. - */ - public abstract static class Reader implements AutoCloseable { - /** - * Initializes the reader and advances the reader to the first record. - * - *

              This method should be called exactly once. The invocation should occur prior to calling - * {@link #advance} or {@link #getCurrent}. This method may perform expensive operations that - * are needed to initialize the reader. - * - * @return {@code true} if a record was read, {@code false} if there is no more input available. - */ - public abstract boolean start() throws IOException; - - /** - * Advances the reader to the next valid record. - * - *

              It is an error to call this without having called {@link #start} first. - * - * @return {@code true} if a record was read, {@code false} if there is no more input available. - */ - public abstract boolean advance() throws IOException; - - /** - * Returns the value of the data item that was read by the last {@link #start} or - * {@link #advance} call. The returned value must be effectively immutable and remain valid - * indefinitely. - * - *

              Multiple calls to this method without an intervening call to {@link #advance} should - * return the same result. - * - * @throws java.util.NoSuchElementException if {@link #start} was never called, or if - * the last {@link #start} or {@link #advance} returned {@code false}. - */ - public abstract T getCurrent() throws NoSuchElementException; - - /** - * Returns the timestamp associated with the current data item. - * - *

              If the source does not support timestamps, this should return - * {@code BoundedWindow.TIMESTAMP_MIN_VALUE}. - * - *

              Multiple calls to this method without an intervening call to {@link #advance} should - * return the same result. - * - * @throws NoSuchElementException if the reader is at the beginning of the input and - * {@link #start} or {@link #advance} wasn't called, or if the last {@link #start} or - * {@link #advance} returned {@code false}. - */ - public abstract Instant getCurrentTimestamp() throws NoSuchElementException; - - /** - * Closes the reader. The reader cannot be used after this method is called. - */ - @Override - public abstract void close() throws IOException; - - /** - * Returns a {@code Source} describing the same input that this {@code Reader} currently reads - * (including items already read). - * - *

              Usually, an implementation will simply return the immutable {@link Source} object from - * which the current {@link Reader} was constructed, or delegate to the base class. - * However, when using or implementing this method on a {@link BoundedSource.BoundedReader}, - * special considerations apply, see documentation for - * {@link BoundedSource.BoundedReader#getCurrentSource}. - */ - public abstract Source getCurrentSource(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java deleted file mode 100644 index 2ea29acde0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/TextIO.java +++ /dev/null @@ -1,1190 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.annotations.VisibleForTesting; -import com.google.protobuf.ByteString; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SeekableByteChannel; -import java.nio.channels.WritableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.NoSuchElementException; -import java.util.regex.Pattern; -import javax.annotation.Nullable; - -/** - * {@link PTransform}s for reading and writing text files. - * - *

              To read a {@link PCollection} from one or more text files, use {@link TextIO.Read}. - * You can instantiate a transform using {@link TextIO.Read#from(String)} to specify - * the path of the file(s) to read from (e.g., a local filename or - * filename pattern if running locally, or a Google Cloud Storage - * filename or filename pattern of the form - * {@code "gs:///"}). You may optionally call - * {@link TextIO.Read#named(String)} to specify the name of the pipeline step. - * - *

              By default, {@link TextIO.Read} returns a {@link PCollection} of {@link String Strings}, - * each corresponding to one line of an input UTF-8 text file. To convert directly from the raw - * bytes (split into lines delimited by '\n', '\r', or '\r\n') to another object of type {@code T}, - * supply a {@code Coder} using {@link TextIO.Read#withCoder(Coder)}. - * - *

              See the following examples: - * - *

              {@code
              - * Pipeline p = ...;
              - *
              - * // A simple Read of a local file (only runs locally):
              - * PCollection lines =
              - *     p.apply(TextIO.Read.from("/local/path/to/file.txt"));
              - *
              - * // A fully-specified Read from a GCS file (runs locally and via the
              - * // Google Cloud Dataflow service):
              - * PCollection numbers =
              - *     p.apply(TextIO.Read.named("ReadNumbers")
              - *                        .from("gs://my_bucket/path/to/numbers-*.txt")
              - *                        .withCoder(TextualIntegerCoder.of()));
              - * }
              - * - *

              To write a {@link PCollection} to one or more text files, use - * {@link TextIO.Write}, specifying {@link TextIO.Write#to(String)} to specify - * the path of the file to write to (e.g., a local filename or sharded - * filename pattern if running locally, or a Google Cloud Storage - * filename or sharded filename pattern of the form - * {@code "gs:///"}). You can optionally name the resulting transform using - * {@link TextIO.Write#named(String)}, and you can use {@link TextIO.Write#withCoder(Coder)} - * to specify the Coder to use to encode the Java values into text lines. - * - *

              Any existing files with the same names as generated output files - * will be overwritten. - * - *

              For example: - *

              {@code
              - * // A simple Write to a local file (only runs locally):
              - * PCollection lines = ...;
              - * lines.apply(TextIO.Write.to("/path/to/file.txt"));
              - *
              - * // A fully-specified Write to a sharded GCS file (runs locally and via the
              - * // Google Cloud Dataflow service):
              - * PCollection numbers = ...;
              - * numbers.apply(TextIO.Write.named("WriteNumbers")
              - *                           .to("gs://my_bucket/path/to/numbers")
              - *                           .withSuffix(".txt")
              - *                           .withCoder(TextualIntegerCoder.of()));
              - * }
              - * - *

              Permissions

              - * - *

              When run using the {@link DirectPipelineRunner}, your pipeline can read and write text files - * on your local drive and remote text files on Google Cloud Storage that you have access to using - * your {@code gcloud} credentials. When running in the Dataflow service using - * {@link DataflowPipelineRunner}, the pipeline can only read and write files from GCS. For more - * information about permissions, see the Cloud Dataflow documentation on - * Security and - * Permissions. - */ -public class TextIO { - /** The default coder, which returns each line of the input file as a string. */ - public static final Coder DEFAULT_TEXT_CODER = StringUtf8Coder.of(); - - /** - * A {@link PTransform} that reads from a text file (or multiple text - * files matching a pattern) and returns a {@link PCollection} containing - * the decoding of each of the lines of the text file(s). The - * default decoding just returns each line as a {@link String}, but you may call - * {@link #withCoder(Coder)} to change the return type. - */ - public static class Read { - /** - * Returns a transform for reading text files that uses the given step name. - */ - public static Bound named(String name) { - return new Bound<>(DEFAULT_TEXT_CODER).named(name); - } - - /** - * Returns a transform for reading text files that reads from the file(s) - * with the given filename or filename pattern. This can be a local path (if running locally), - * or a Google Cloud Storage filename or filename pattern of the form - * {@code "gs:///"} (if running locally or via the Google Cloud Dataflow - * service). Standard Java Filesystem glob patterns ("*", "?", "[..]") are supported. - */ - public static Bound from(String filepattern) { - return new Bound<>(DEFAULT_TEXT_CODER).from(filepattern); - } - - /** - * Same as {@code from(filepattern)}, but accepting a {@link ValueProvider}. - */ - public static Bound from(ValueProvider filepattern) { - return new Bound<>(DEFAULT_TEXT_CODER).from(filepattern); - } - - /** - * Returns a transform for reading text files that uses the given - * {@code Coder} to decode each of the lines of the file into a - * value of type {@code T}. - * - *

              By default, uses {@link StringUtf8Coder}, which just - * returns the text lines as Java strings. - * - * @param the type of the decoded elements, and the elements - * of the resulting PCollection - */ - public static Bound withCoder(Coder coder) { - return new Bound<>(coder); - } - - /** - * Returns a transform for reading text files that has GCS path validation on - * pipeline creation disabled. - * - *

              This can be useful in the case where the GCS input does not - * exist at the pipeline creation time, but is expected to be - * available at execution time. - */ - public static Bound withoutValidation() { - return new Bound<>(DEFAULT_TEXT_CODER).withoutValidation(); - } - - /** - * Returns a transform for reading text files that decompresses all input files - * using the specified compression type. - * - *

              If no compression type is specified, the default is {@link TextIO.CompressionType#AUTO}. - * In this mode, the compression type of the file is determined by its extension - * (e.g., {@code *.gz} is gzipped, {@code *.bz2} is bzipped, and all other extensions are - * uncompressed). - */ - public static Bound withCompressionType(TextIO.CompressionType compressionType) { - return new Bound<>(DEFAULT_TEXT_CODER).withCompressionType(compressionType); - } - - // TODO: strippingNewlines, etc. - - /** - * A {@link PTransform} that reads from one or more text files and returns a bounded - * {@link PCollection} containing one element for each line of the input files. - * - * @param the type of each of the elements of the resulting - * {@link PCollection}. By default, each line is returned as a {@link String}, however you - * may use {@link #withCoder(Coder)} to supply a {@code Coder} to produce a - * {@code PCollection} instead. - */ - public static class Bound extends PTransform> { - /** The filepattern to read from. */ - @Nullable private final ValueProvider filepattern; - - /** The Coder to use to decode each line. */ - private final Coder coder; - - /** An option to indicate if input validation is desired. Default is true. */ - private final boolean validate; - - /** Option to indicate the input source's compression type. Default is AUTO. */ - private final TextIO.CompressionType compressionType; - - Bound(Coder coder) { - this(null, null, coder, true, TextIO.CompressionType.AUTO); - } - - private Bound(@Nullable String name, @Nullable ValueProvider filepattern, - Coder coder, boolean validate, TextIO.CompressionType compressionType) { - super(name); - this.coder = coder; - this.filepattern = filepattern; - this.validate = validate; - this.compressionType = compressionType; - } - - /** - * Returns a new transform for reading from text files that's like this one but - * with the given step name. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound<>(name, filepattern, coder, validate, compressionType); - } - - /** - * Returns a new transform for reading from text files that's like this one but - * that reads from the file(s) with the given name or pattern. See {@link TextIO.Read#from} - * for a description of filepatterns. - * - *

              Does not modify this object. - - */ - public Bound from(String filepattern) { - checkNotNull(filepattern, "Filepattern cannot be empty."); - return new Bound<>(name, StaticValueProvider.of(filepattern), coder, validate, - compressionType); - } - - /** - * Same as {@code from(filepattern)}, but accepting a {@link ValueProvider}. - */ - public Bound from(ValueProvider filepattern) { - checkNotNull(filepattern, "Filepattern cannot be empty."); - return new Bound<>(name, filepattern, coder, validate, compressionType); - } - - /** - * Returns a new transform for reading from text files that's like this one but - * that uses the given {@link Coder} to decode each of the - * lines of the file into a value of type {@code X}. - * - *

              Does not modify this object. - * - * @param the type of the decoded elements, and the - * elements of the resulting PCollection - */ - public Bound withCoder(Coder coder) { - return new Bound<>(name, filepattern, coder, validate, compressionType); - } - - /** - * Returns a new transform for reading from text files that's like this one but - * that has GCS path validation on pipeline creation disabled. - * - *

              This can be useful in the case where the GCS input does not - * exist at the pipeline creation time, but is expected to be - * available at execution time. - * - *

              Does not modify this object. - */ - public Bound withoutValidation() { - return new Bound<>(name, filepattern, coder, false, compressionType); - } - - /** - * Returns a new transform for reading from text files that's like this one but - * reads from input sources using the specified compression type. - * - *

              If no compression type is specified, the default is {@link TextIO.CompressionType#AUTO}. - * See {@link TextIO.Read#withCompressionType} for more details. - * - *

              Does not modify this object. - */ - public Bound withCompressionType(TextIO.CompressionType compressionType) { - return new Bound<>(name, filepattern, coder, validate, compressionType); - } - - @Override - public PCollection apply(PInput input) { - if (filepattern == null) { - throw new IllegalStateException("need to set the filepattern of a TextIO.Read transform"); - } - - if (validate) { - checkState(filepattern.isAccessible(), - "Cannot validate with a filepattern provided at runtime."); - try { - checkState( - !IOChannelUtils.getFactory(filepattern.get()).match(filepattern.get()).isEmpty(), - "Unable to find any files matching %s", - filepattern); - } catch (IOException e) { - throw new IllegalStateException( - String.format("Failed to validate %s", filepattern.get()), e); - } - } - - final Bounded read = com.google.cloud.dataflow.sdk.io.Read.from(getSource()); - PCollection pcol = input.getPipeline().apply("Read", read); - // Honor the default output coder that would have been used by this PTransform. - pcol.setCoder(getDefaultOutputCoder()); - return pcol; - } - - // Helper to create a source specific to the requested compression type. - protected FileBasedSource getSource() { - switch (compressionType) { - case UNCOMPRESSED: - return new TextSource(filepattern, coder); - case AUTO: - return CompressedSource.from(new TextSource(filepattern, coder)); - case BZIP2: - return - CompressedSource.from(new TextSource(filepattern, coder)) - .withDecompression(CompressedSource.CompressionMode.BZIP2); - case GZIP: - return - CompressedSource.from(new TextSource(filepattern, coder)) - .withDecompression(CompressedSource.CompressionMode.GZIP); - default: - throw new IllegalArgumentException("Unknown compression type: " + compressionType); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .add(DisplayData.item("compressionType", compressionType.toString()) - .withLabel("Compression Type")) - .addIfNotDefault(DisplayData.item("validation", validate) - .withLabel("Validation Enabled"), true) - .addIfNotNull(DisplayData.item("filePattern", filepattern) - .withLabel("File Pattern")); - } - - @Override - protected Coder getDefaultOutputCoder() { - return coder; - } - - public String getFilepattern() { - return filepattern.get(); - } - - public boolean needsValidation() { - return validate; - } - - public TextIO.CompressionType getCompressionType() { - return compressionType; - } - } - - /** Disallow construction of utility classes. */ - private Read() {} - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@link PTransform} that writes a {@link PCollection} to text file (or - * multiple text files matching a sharding pattern), with each - * element of the input collection encoded into its own line. - */ - public static class Write { - /** - * Returns a transform for writing to text files with the given step name. - */ - public static Bound named(String name) { - return new Bound<>(DEFAULT_TEXT_CODER).named(name); - } - - /** - * Returns a transform for writing to text files that writes to the file(s) - * with the given prefix. This can be a local filename - * (if running locally), or a Google Cloud Storage filename of - * the form {@code "gs:///"} - * (if running locally or via the Google Cloud Dataflow service). - * - *

              The files written will begin with this prefix, followed by - * a shard identifier (see {@link Bound#withNumShards(int)}, and end - * in a common extension, if given by {@link Bound#withSuffix(String)}. - */ - public static Bound to(String prefix) { - return new Bound<>(DEFAULT_TEXT_CODER).to(prefix); - } - - /** - * Like {@link #to(String)}, but with a {@link ValueProvider}. - */ - public static Bound to(ValueProvider prefix) { - return new Bound<>(DEFAULT_TEXT_CODER).to(prefix); - } - - /** - * Returns a transform for writing to text files that appends the specified suffix - * to the created files. - */ - public static Bound withSuffix(String nameExtension) { - return new Bound<>(DEFAULT_TEXT_CODER).withSuffix(nameExtension); - } - - /** - * Returns a transform for writing to text files that uses the provided shard count. - * - *

              Constraining the number of shards is likely to reduce - * the performance of a pipeline. Setting this value is not recommended - * unless you require a specific number of output files. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - */ - public static Bound withNumShards(int numShards) { - return new Bound<>(DEFAULT_TEXT_CODER).withNumShards(numShards); - } - - /** - * Returns a transform for writing to text files that uses the given shard name - * template. - * - *

              See {@link ShardNameTemplate} for a description of shard templates. - */ - public static Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>(DEFAULT_TEXT_CODER).withShardNameTemplate(shardTemplate); - } - - /** - * Returns a transform for writing to text files that forces a single file as - * output. - */ - public static Bound withoutSharding() { - return new Bound<>(DEFAULT_TEXT_CODER).withoutSharding(); - } - - /** - * Returns a transform for writing to text files that uses the given - * {@link Coder} to encode each of the elements of the input - * {@link PCollection} into an output text line. - * - *

              By default, uses {@link StringUtf8Coder}, which writes input - * Java strings directly as output lines. - * - * @param the type of the elements of the input {@link PCollection} - */ - public static Bound withCoder(Coder coder) { - return new Bound<>(coder); - } - - /** - * Returns a transform for writing to text files that has GCS path validation on - * pipeline creation disabled. - * - *

              This can be useful in the case where the GCS output location does - * not exist at the pipeline creation time, but is expected to be available - * at execution time. - */ - public static Bound withoutValidation() { - return new Bound<>(DEFAULT_TEXT_CODER).withoutValidation(); - } - - /** - * Returns a transform for writing to text files that adds a header string to the files - * it writes. Note that a newline character will be added after the header. - * - *

              A {@code null} value will clear any previously configured header. - * - * @param header the string to be added as file header - */ - public static Bound withHeader(@Nullable String header) { - return new Bound<>(DEFAULT_TEXT_CODER).withHeader(header); - } - - /** - * Returns a transform for writing to text files that adds a footer string to the files - * it writes. Note that a newline character will be added after the header. - * - *

              A {@code null} value will clear any previously configured footer. - * - * @param footer the string to be added as file footer - */ - public static Bound withFooter(@Nullable String footer) { - return new Bound<>(DEFAULT_TEXT_CODER).withFooter(footer); - } - - // TODO: appendingNewlines, etc. - - /** - * A PTransform that writes a bounded PCollection to a text file (or - * multiple text files matching a sharding pattern), with each - * PCollection element being encoded into its own line. - * - * @param the type of the elements of the input PCollection - */ - public static class Bound extends PTransform, PDone> { - private static final String DEFAULT_SHARD_TEMPLATE = ShardNameTemplate.INDEX_OF_MAX; - - /** The prefix of each file written, combined with suffix and shardTemplate. */ - @Nullable private final ValueProvider filenamePrefix; - /** The suffix of each file written, combined with prefix and shardTemplate. */ - private final String filenameSuffix; - - /** An optional header to add to each file. */ - @Nullable private final String header; - - /** An optional footer to add to each file. */ - @Nullable private final String footer; - - /** The Coder to use to decode each line. */ - private final Coder coder; - - /** Requested number of shards. 0 for automatic. */ - private final int numShards; - - /** The shard template of each file written, combined with prefix and suffix. */ - private final String shardTemplate; - - /** An option to indicate if output validation is desired. Default is true. */ - private final boolean validate; - - Bound(Coder coder) { - this(null, null, "", null, null, coder, 0, DEFAULT_SHARD_TEMPLATE, true); - } - - private Bound(String name, ValueProvider filenamePrefix, String filenameSuffix, - @Nullable String header, @Nullable String footer, Coder coder, int numShards, - String shardTemplate, boolean validate) { - super(name); - this.header = header; - this.footer = footer; - this.coder = coder; - this.filenamePrefix = filenamePrefix; - this.filenameSuffix = filenameSuffix; - this.numShards = numShards; - this.shardTemplate = shardTemplate; - this.validate = validate; - } - - /** - * Returns a transform for writing to text files that's like this one but - * with the given step name. - * - *

              Does not modify this object. - */ - public Bound named(String name) { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, validate); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that writes to the file(s) with the given filename prefix. - * - *

              See {@link TextIO.Write#to(String) Write.to(String)} for more information. - * - *

              Does not modify this object. - */ - public Bound to(String filenamePrefix) { - validateOutputComponent(filenamePrefix); - return new Bound<>(name, StaticValueProvider.of(filenamePrefix), filenameSuffix, - header, footer, coder, numShards, shardTemplate, validate); - } - - /** - * Like {@link #to(String)}, but with a {@link ValueProvider}. - */ - public Bound to(ValueProvider filenamePrefix) { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, validate); - } - - /** - * Returns a transform for writing to text files that that's like this one but - * that writes to the file(s) with the given filename suffix. - * - *

              Does not modify this object. - * - * @see ShardNameTemplate - */ - public Bound withSuffix(String nameExtension) { - validateOutputComponent(nameExtension); - return new Bound<>(name, filenamePrefix, nameExtension, header, footer, coder, numShards, - shardTemplate, validate); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that uses the provided shard count. - * - *

              Constraining the number of shards is likely to reduce - * the performance of a pipeline. Setting this value is not recommended - * unless you require a specific number of output files. - * - *

              Does not modify this object. - * - * @param numShards the number of shards to use, or 0 to let the system - * decide. - * @see ShardNameTemplate - */ - public Bound withNumShards(int numShards) { - checkArgument(numShards >= 0); - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, validate); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that uses the given shard name template. - * - *

              Does not modify this object. - * - * @see ShardNameTemplate - */ - public Bound withShardNameTemplate(String shardTemplate) { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, validate); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that forces a single file as output. - * - *

              Constraining the number of shards is likely to reduce - * the performance of a pipeline. Using this setting is not recommended - * unless you truly require a single output file. - * - *

              This is a shortcut for - * {@code .withNumShards(1).withShardNameTemplate("")} - * - *

              Does not modify this object. - */ - public Bound withoutSharding() { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, 1, - "", validate); - } - - /** - * Returns a transform for writing to text files that's like this one - * but that uses the given {@link Coder} to encode each of - * the elements of the input {@link PCollection} into an - * output text line. Does not modify this object. - * - * @param the type of the elements of the input {@link PCollection} - */ - public Bound withCoder(Coder coder) { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, validate); - } - - /** - * Returns a transform for writing to text files that adds a header string to the files - * it writes. Note that a newline character will be added after the header. - * - *

              A {@code null} value will clear any previously configured header. - * - *

              Does not modify this object. - * - * @param header the string to be added as file header - */ - public Bound withHeader(@Nullable String header) { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, false); - } - - /** - * Returns a transform for writing to text files that adds a footer string to the files - * it writes. Note that a newline character will be added after the header. - * - *

              A {@code null} value will clear any previously configured footer. - * - *

              Does not modify this object. - * - * @param footer the string to be added as file footer - */ - public Bound withFooter(@Nullable String footer) { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, false); - } - - /** - * Returns a transform for writing to text files that's like this one but - * that has GCS output path validation on pipeline creation disabled. - * - *

              This can be useful in the case where the GCS output location does - * not exist at the pipeline creation time, but is expected to be - * available at execution time. - * - *

              Does not modify this object. - */ - public Bound withoutValidation() { - return new Bound<>(name, filenamePrefix, filenameSuffix, header, footer, coder, numShards, - shardTemplate, false); - } - - @Override - public PDone apply(PCollection input) { - if (filenamePrefix == null) { - throw new IllegalStateException( - "need to set the filename prefix of a TextIO.Write transform"); - } - - com.google.cloud.dataflow.sdk.io.Write.Bound write = - com.google.cloud.dataflow.sdk.io.Write.to( - new TextSink<>(filenamePrefix, filenameSuffix, header, footer, shardTemplate, - coder)); - if (getNumShards() > 0) { - write = write.withNumShards(getNumShards()); - } - return input.apply("Write", write); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .addIfNotNull(DisplayData.item("filePrefix", filenamePrefix) - .withLabel("Output File Prefix")) - .addIfNotDefault(DisplayData.item("fileSuffix", filenameSuffix) - .withLabel("Output Fix Suffix"), "") - .addIfNotDefault(DisplayData.item("shardNameTemplate", shardTemplate) - .withLabel("Output Shard Name Template"), - DEFAULT_SHARD_TEMPLATE) - .addIfNotDefault(DisplayData.item("validation", validate) - .withLabel("Validation Enabled"), true) - .addIfNotDefault(DisplayData.item("numShards", numShards) - .withLabel("Maximum Output Shards"), 0) - .addIfNotNull(DisplayData.item("fileHeader", header) - .withLabel("File Header")) - .addIfNotNull(DisplayData.item("fileFooter", footer) - .withLabel("File Footer")); - } - - /** - * Returns the current shard name template string. - */ - public String getShardNameTemplate() { - return shardTemplate; - } - - @Override - protected Coder getDefaultOutputCoder() { - return VoidCoder.of(); - } - - public String getFilenamePrefix() { - return filenamePrefix.get(); - } - - public String getShardTemplate() { - return shardTemplate; - } - - public int getNumShards() { - return numShards; - } - - public String getFilenameSuffix() { - return filenameSuffix; - } - - public Coder getCoder() { - return coder; - } - - @Nullable - public String getHeader() { - return header; - } - - @Nullable - public String getFooter() { - return footer; - } - - public boolean needsValidation() { - return validate; - } - } - } - - /** - * Possible text file compression types. - */ - public enum CompressionType { - /** - * Automatically determine the compression type based on filename extension. - */ - AUTO(""), - /** - * Uncompressed (i.e., may be split). - */ - UNCOMPRESSED(""), - /** - * GZipped. - */ - GZIP(".gz"), - /** - * BZipped. - */ - BZIP2(".bz2"); - - private String filenameSuffix; - - CompressionType(String suffix) { - this.filenameSuffix = suffix; - } - - /** - * Determine if a given filename matches a compression type based on its extension. - * @param filename the filename to match - * @return true iff the filename ends with the compression type's known extension. - */ - public boolean matches(String filename) { - return filename.toLowerCase().endsWith(filenameSuffix.toLowerCase()); - } - } - - // Pattern which matches old-style shard output patterns, which are now - // disallowed. - private static final Pattern SHARD_OUTPUT_PATTERN = Pattern.compile("@([0-9]+|\\*)"); - - private static void validateOutputComponent(String partialFilePattern) { - checkArgument( - !SHARD_OUTPUT_PATTERN.matcher(partialFilePattern).find(), - "Output name components are not allowed to contain @* or @N patterns: " - + partialFilePattern); - } - - ////////////////////////////////////////////////////////////////////////////// - - /** Disable construction of utility class. */ - private TextIO() {} - - /** - * A {@link FileBasedSource} which can decode records delimited by newline characters. - * - *

              This source splits the data into records using {@code UTF-8} {@code \n}, {@code \r}, or - * {@code \r\n} as the delimiter. This source is not strict and supports decoding the last record - * even if it is not delimited. Finally, no records are decoded if the stream is empty. - * - *

              This source supports reading from any arbitrary byte position within the stream. If the - * starting position is not {@code 0}, then bytes are skipped until the first delimiter is found - * representing the beginning of the first record to be decoded. - */ - @VisibleForTesting - static class TextSource extends FileBasedSource { - /** The Coder to use to decode each line. */ - private final Coder coder; - - @VisibleForTesting - TextSource(String fileSpec, Coder coder) { - super(fileSpec, 1L); - this.coder = coder; - } - - @VisibleForTesting - TextSource(ValueProvider fileSpec, Coder coder) { - super(fileSpec, 1L); - this.coder = coder; - } - - private TextSource(String fileName, long start, long end, Coder coder) { - super(fileName, 1L, start, end); - this.coder = coder; - } - - @Override - protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { - return new TextSource<>(fileName, start, end, coder); - } - - @Override - protected FileBasedReader createSingleFileReader(PipelineOptions options) { - return new TextBasedReader<>(this); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public Coder getDefaultOutputCoder() { - return coder; - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader FileBasedReader} - * which can decode records delimited by newline characters. - * - *

              See {@link TextSource} for further details. - */ - @VisibleForTesting - static class TextBasedReader extends FileBasedReader { - private static final int READ_BUFFER_SIZE = 8192; - private final Coder coder; - private final ByteBuffer readBuffer = ByteBuffer.allocate(READ_BUFFER_SIZE); - private ByteString buffer; - private int startOfSeparatorInBuffer; - private int endOfSeparatorInBuffer; - private long startOfRecord; - private volatile long startOfNextRecord; - private volatile boolean eof; - private volatile boolean elementIsPresent; - private T currentValue; - private ReadableByteChannel inChannel; - - private TextBasedReader(TextSource source) { - super(source); - coder = source.coder; - buffer = ByteString.EMPTY; - } - - @Override - protected long getCurrentOffset() throws NoSuchElementException { - if (!elementIsPresent) { - throw new NoSuchElementException(); - } - return startOfRecord; - } - - @Override - public long getSplitPointsRemaining() { - if (isStarted() && startOfNextRecord >= getCurrentSource().getEndOffset()) { - return isDone() ? 0 : 1; - } - return super.getSplitPointsRemaining(); - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (!elementIsPresent) { - throw new NoSuchElementException(); - } - return currentValue; - } - - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - this.inChannel = channel; - // If the first offset is greater than zero, we need to skip bytes until we see our - // first separator. - if (getCurrentSource().getStartOffset() > 0) { - checkState(channel instanceof SeekableByteChannel, - "%s only supports reading from a SeekableByteChannel when given a start offset" - + " greater than 0.", TextSource.class.getSimpleName()); - long requiredPosition = getCurrentSource().getStartOffset() - 1; - ((SeekableByteChannel) channel).position(requiredPosition); - findSeparatorBounds(); - buffer = buffer.substring(endOfSeparatorInBuffer); - startOfNextRecord = requiredPosition + endOfSeparatorInBuffer; - endOfSeparatorInBuffer = 0; - startOfSeparatorInBuffer = 0; - } - } - - /** - * Locates the start position and end position of the next delimiter. Will - * consume the channel till either EOF or the delimiter bounds are found. - * - *

              This fills the buffer and updates the positions as follows: - *

              {@code
              -       * ------------------------------------------------------
              -       * | element bytes | delimiter bytes | unconsumed bytes |
              -       * ------------------------------------------------------
              -       * 0            start of          end of              buffer
              -       *              separator         separator           size
              -       *              in buffer         in buffer
              -       * }
              - */ - private void findSeparatorBounds() throws IOException { - int bytePositionInBuffer = 0; - while (true) { - if (!tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 1)) { - startOfSeparatorInBuffer = endOfSeparatorInBuffer = bytePositionInBuffer; - break; - } - - byte currentByte = buffer.byteAt(bytePositionInBuffer); - - if (currentByte == '\n') { - startOfSeparatorInBuffer = bytePositionInBuffer; - endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; - break; - } else if (currentByte == '\r') { - startOfSeparatorInBuffer = bytePositionInBuffer; - endOfSeparatorInBuffer = startOfSeparatorInBuffer + 1; - - if (tryToEnsureNumberOfBytesInBuffer(bytePositionInBuffer + 2)) { - currentByte = buffer.byteAt(bytePositionInBuffer + 1); - if (currentByte == '\n') { - endOfSeparatorInBuffer += 1; - } - } - break; - } - - // Move to the next byte in buffer. - bytePositionInBuffer += 1; - } - } - - @Override - protected boolean readNextRecord() throws IOException { - startOfRecord = startOfNextRecord; - findSeparatorBounds(); - - // If we have reached EOF file and consumed all of the buffer then we know - // that there are no more records. - if (eof && buffer.size() == 0) { - elementIsPresent = false; - return false; - } - - decodeCurrentElement(); - startOfNextRecord = startOfRecord + endOfSeparatorInBuffer; - return true; - } - - /** - * Decodes the current element updating the buffer to only contain the unconsumed bytes. - * - *

              This invalidates the currently stored {@code startOfSeparatorInBuffer} and - * {@code endOfSeparatorInBuffer}. - */ - private void decodeCurrentElement() throws IOException { - ByteString dataToDecode = buffer.substring(0, startOfSeparatorInBuffer); - currentValue = coder.decode(dataToDecode.newInput(), Context.OUTER); - elementIsPresent = true; - buffer = buffer.substring(endOfSeparatorInBuffer); - } - - /** - * Returns false if we were unable to ensure the minimum capacity by consuming the channel. - */ - private boolean tryToEnsureNumberOfBytesInBuffer(int minCapacity) throws IOException { - // While we aren't at EOF or haven't fulfilled the minimum buffer capacity, - // attempt to read more bytes. - while (buffer.size() <= minCapacity && !eof) { - eof = inChannel.read(readBuffer) == -1; - readBuffer.flip(); - buffer = buffer.concat(ByteString.copyFrom(readBuffer)); - readBuffer.clear(); - } - // Return true if we were able to honor the minimum buffer capacity request - return buffer.size() >= minCapacity; - } - } - } - - /** - * A {@link FileBasedSink} for text files. Produces text files with the newline separator - * {@code '\n'} represented in {@code UTF-8} format as the record separator. - * Each record (including the last) is terminated. - */ - @VisibleForTesting - static class TextSink extends FileBasedSink { - private final Coder coder; - @Nullable private final String header; - @Nullable private final String footer; - - @VisibleForTesting - TextSink( - ValueProvider baseOutputFilename, String extension, - @Nullable String header, @Nullable String footer, - String fileNameTemplate, Coder coder) { - super(baseOutputFilename, extension, fileNameTemplate); - this.coder = coder; - this.header = header; - this.footer = footer; - } - - @Override - public FileBasedSink.FileBasedWriteOperation createWriteOperation(PipelineOptions options) { - return new TextWriteOperation<>(this, coder, header, footer); - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation - * FileBasedWriteOperation} for text files. - */ - private static class TextWriteOperation extends FileBasedWriteOperation { - private final Coder coder; - @Nullable private final String header; - @Nullable private final String footer; - - private TextWriteOperation(TextSink sink, Coder coder, - @Nullable String header, @Nullable String footer) { - super(sink); - this.coder = coder; - this.header = header; - this.footer = footer; - } - - @Override - public FileBasedWriter createWriter(PipelineOptions options) throws Exception { - return new TextWriter<>(this, coder, header, footer); - } - } - - /** - * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter} - * for text files. - */ - private static class TextWriter extends FileBasedWriter { - private static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); - private final Coder coder; - @Nullable private final String header; - @Nullable private final String footer; - private OutputStream out; - - public TextWriter(FileBasedWriteOperation writeOperation, Coder coder, - @Nullable String header, @Nullable String footer) { - super(writeOperation); - this.header = header; - this.footer = footer; - this.mimeType = MimeTypes.TEXT; - this.coder = coder; - } - - /** - * Writes {@code value} followed by a newline if {@code value} is not null. - */ - private void writeIfNotNull(@Nullable String value) throws IOException { - if (value != null) { - out.write(value.getBytes(StandardCharsets.UTF_8)); - out.write(NEWLINE); - } - } - - @Override - protected void prepareWrite(WritableByteChannel channel) throws Exception { - out = Channels.newOutputStream(channel); - } - - @Override - protected void writeHeader() throws Exception { - writeIfNotNull(header); - } - - @Override - protected void writeFooter() throws Exception { - writeIfNotNull(footer); - } - - @Override - public void write(T value) throws Exception { - coder.encode(value, out, Context.OUTER); - out.write(NEWLINE); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/UnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/UnboundedSource.java deleted file mode 100644 index e585151c89..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/UnboundedSource.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * A {@link Source} that reads an unbounded amount of input and, because of that, supports - * some additional operations such as checkpointing, watermarks, and record ids. - * - *

                - *
              • Checkpointing allows sources to not re-read the same data again in the case of failures. - *
              • Watermarks allow for downstream parts of the pipeline to know up to what point - * in time the data is complete. - *
              • Record ids allow for efficient deduplication of input records; many streaming sources - * do not guarantee that a given record will only be read a single time. - *
              - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} and - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger} for more information on - * timestamps and watermarks. - * - * @param Type of records output by this source. - * @param Type of checkpoint marks used by the readers of this source. - */ -public abstract class UnboundedSource< - OutputT, CheckpointMarkT extends UnboundedSource.CheckpointMark> extends Source { - /** - * Returns a list of {@code UnboundedSource} objects representing the instances of this source - * that should be used when executing the workflow. Each split should return a separate partition - * of the input data. - * - *

              For example, for a source reading from a growing directory of files, each split - * could correspond to a prefix of file names. - * - *

              Some sources are not splittable, such as reading from a single TCP stream. In that - * case, only a single split should be returned. - * - *

              Some data sources automatically partition their data among readers. For these types of - * inputs, {@code n} identical replicas of the top-level source can be returned. - * - *

              The size of the returned list should be as close to {@code desiredNumSplits} - * as possible, but does not have to match exactly. A low number of splits - * will limit the amount of parallelism in the source. - */ - public abstract List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception; - - /** - * Create a new {@link UnboundedReader} to read from this source, resuming from the given - * checkpoint if present. - */ - public abstract UnboundedReader createReader( - PipelineOptions options, @Nullable CheckpointMarkT checkpointMark); - - /** - * Returns a {@link Coder} for encoding and decoding the checkpoints for this source, or - * null if the checkpoints do not need to be durably committed. - */ - @Nullable - public abstract Coder getCheckpointMarkCoder(); - - /** - * Returns whether this source requires explicit deduping. - * - *

              This is needed if the underlying data source can return the same record multiple times, - * such a queuing system with a pull-ack model. Sources where the records read are uniquely - * identified by the persisted state in the CheckpointMark do not need this. - */ - public boolean requiresDeduping() { - return false; - } - - /** - * A marker representing the progress and state of an - * {@link com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader}. - * - *

              For example, this could be offsets in a set of files being read. - */ - public interface CheckpointMark { - /** - * Perform any finalization that needs to happen after a bundle of data read from - * the source has been processed and committed. - * - *

              For example, this could be sending acknowledgement requests to an external - * data source such as Pub/Sub. - * - *

              This may be called from any thread, potentially at the same time as calls to the - * {@code UnboundedReader} that created it. - */ - void finalizeCheckpoint() throws IOException; - } - - /** - * A {@code Reader} that reads an unbounded amount of input. - * - *

              A given {@code UnboundedReader} object will only be accessed by a single thread at once. - */ - @Experimental(Experimental.Kind.SOURCE_SINK) - public abstract static class UnboundedReader extends Source.Reader { - private static final byte[] EMPTY = new byte[0]; - - /** - * Initializes the reader and advances the reader to the first record. - * - *

              This method should be called exactly once. The invocation should occur prior to calling - * {@link #advance} or {@link #getCurrent}. This method may perform expensive operations that - * are needed to initialize the reader. - * - *

              Returns {@code true} if a record was read, {@code false} if there is no more input - * currently available. Future calls to {@link #advance} may return {@code true} once more data - * is available. Regardless of the return value of {@code start}, {@code start} will not be - * called again on the same {@code UnboundedReader} object; it will only be called again when a - * new reader object is constructed for the same source, e.g. on recovery. - */ - @Override - public abstract boolean start() throws IOException; - - /** - * Advances the reader to the next valid record. - * - *

              Returns {@code true} if a record was read, {@code false} if there is no more input - * available. Future calls to {@link #advance} may return {@code true} once more data is - * available. - */ - @Override - public abstract boolean advance() throws IOException; - - /** - * Returns a unique identifier for the current record. This should be the same for each - * instance of the same logical record read from the underlying data source. - * - *

              It is only necessary to override this if {@link #requiresDeduping} has been overridden to - * return true. - * - *

              For example, this could be a hash of the record contents, or a logical ID present in - * the record. If this is generated as a hash of the record contents, it should be at least 16 - * bytes (128 bits) to avoid collisions. - * - *

              This method has the same restrictions on when it can be called as {@link #getCurrent} and - * {@link #getCurrentTimestamp}. - * - * @throws NoSuchElementException if the reader is at the beginning of the input and - * {@link #start} or {@link #advance} wasn't called, or if the last {@link #start} or - * {@link #advance} returned {@code false}. - */ - public byte[] getCurrentRecordId() throws NoSuchElementException { - if (getCurrentSource().requiresDeduping()) { - throw new IllegalStateException( - "getCurrentRecordId() must be overridden if requiresDeduping returns true()"); - } - return EMPTY; - } - - /** - * Returns a timestamp before or at the timestamps of all future elements read by this reader. - * - *

              This can be approximate. If records are read that violate this guarantee, they will be - * considered late, which will affect how they will be processed. See - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} for more information on - * late data and how to handle it. - * - *

              However, this value should be as late as possible. Downstream windows may not be able - * to close until this watermark passes their end. - * - *

              For example, a source may know that the records it reads will be in timestamp order. In - * this case, the watermark can be the timestamp of the last record read. For a - * source that does not have natural timestamps, timestamps can be set to the time of - * reading, in which case the watermark is the current clock time. - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} and - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger} for more - * information on timestamps and watermarks. - * - *

              May be called after {@link #advance} or {@link #start} has returned false, but not before - * {@link #start} has been called. - */ - public abstract Instant getWatermark(); - - /** - * Returns a {@link CheckpointMark} representing the progress of this {@code UnboundedReader}. - * - *

              The elements read up until this is called will be processed together as a bundle. Once - * the result of this processing has been durably committed, - * {@link CheckpointMark#finalizeCheckpoint} will be called on the {@link CheckpointMark} - * object. - * - *

              The returned object should not be modified. - * - *

              May be called after {@link #advance} or {@link #start} has returned false, but not before - * {@link #start} has been called. - */ - public abstract CheckpointMark getCheckpointMark(); - - /** - * Constant representing an unknown amount of backlog. - */ - public static final long BACKLOG_UNKNOWN = -1L; - - /** - * Returns the size of the backlog of unread data in the underlying data source represented by - * this split of this source. - * - *

              One of this or {@link #getTotalBacklogBytes} should be overridden in order to allow the - * runner to scale the amount of resources allocated to the pipeline. - */ - public long getSplitBacklogBytes() { - return BACKLOG_UNKNOWN; - } - - /** - * Returns the size of the backlog of unread data in the underlying data source represented by - * all splits of this source. - * - *

              One of this or {@link #getSplitBacklogBytes} should be overridden in order to allow the - * runner to scale the amount of resources allocated to the pipeline. - */ - public long getTotalBacklogBytes() { - return BACKLOG_UNKNOWN; - } - - /** - * Returns the {@link UnboundedSource} that created this reader. This will not change over the - * life of the reader. - */ - @Override - public abstract UnboundedSource getCurrentSource(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java deleted file mode 100644 index 3aec6fff22..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/Write.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; -import com.google.cloud.dataflow.sdk.io.Sink.Writer; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.collect.Lists; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; - -/** - * A {@link PTransform} that writes to a {@link Sink}. A write begins with a sequential global - * initialization of a sink, followed by a parallel write, and ends with a sequential finalization - * of the write. The output of a write is {@link PDone}. - * - *

              By default, every bundle in the input {@link PCollection} will be processed by a - * {@link WriteOperation}, so the number of outputs will vary based on runner behavior, though at - * least 1 output will always be produced. The exact parallelism of the write stage can be - * controlled using {@link Write.Bound#withNumShards}, typically used to control how many files are - * produced or to globally limit the number of workers connecting to an external service. However, - * this option can often hurt performance: it adds an additional {@link GroupByKey} to the pipeline. - * - *

              {@code Write} re-windows the data into the global window, so it is typically not well suited - * to use in streaming pipelines. - * - *

              Example usage with runner-controlled sharding: - * - *

              {@code p.apply(Write.to(new MySink(...)));}
              - * - *

              Example usage with a fixed number of shards: - * - *

              {@code p.apply(Write.to(new MySink(...)).withNumShards(3));}
              - */ -@Experimental(Experimental.Kind.SOURCE_SINK) -public class Write { - private static final Logger LOG = LoggerFactory.getLogger(Write.class); - - /** - * Creates a {@link Write} transform that writes to the given {@link Sink}, letting the runner - * control how many different shards are produced. - */ - public static Bound to(Sink sink) { - checkNotNull(sink, "sink"); - return new Bound<>(sink, 0 /* runner-controlled sharding */); - } - - /** - * A {@link PTransform} that writes to a {@link Sink}. See the class-level Javadoc for more - * information. - * - * @see Write - * @see Sink - */ - public static class Bound extends PTransform, PDone> { - private final Sink sink; - private int numShards; - - private Bound(Sink sink, int numShards) { - this.sink = sink; - this.numShards = numShards; - } - - @Override - public PDone apply(PCollection input) { - checkArgument(IsBounded.BOUNDED == input.isBounded(), - "%s can only be applied to a Bounded PCollection", - Write.class.getSimpleName()); - - PipelineOptions options = input.getPipeline().getOptions(); - sink.validate(options); - return createWrite(input, sink.createWriteOperation(options)); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("sink", sink.getClass()).withLabel("Write Sink")) - .include(sink) - .addIfNotDefault( - DisplayData.item("numShards", getNumShards()).withLabel("Fixed Number of Shards"), - 0); - } - - /** - * Returns the number of shards that will be produced in the output. - * - * @see Write for more information - */ - public int getNumShards() { - return numShards; - } - - /** - * Returns the {@link Sink} associated with this PTransform. - */ - public Sink getSink() { - return sink; - } - - /** - * Returns a new {@link Write.Bound} that will write to the current {@link Sink} using the - * specified number of shards. - * - *

              This option should be used sparingly as it can hurt performance. See {@link Write} for - * more information. - * - *

              A value less than or equal to 0 will be equivalent to the default behavior of - * runner-controlled sharding. - */ - public Bound withNumShards(int numShards) { - return new Bound<>(sink, Math.max(numShards, 0)); - } - - /** - * Writes all the elements in a bundle using a {@link Writer} produced by the - * {@link WriteOperation} associated with the {@link Sink}. - */ - private class WriteBundles extends DoFn { - // Writer that will write the records in this bundle. Lazily - // initialized in processElement. - private Writer writer = null; - private final PCollectionView> writeOperationView; - - WriteBundles(PCollectionView> writeOperationView) { - this.writeOperationView = writeOperationView; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - // Lazily initialize the Writer - if (writer == null) { - WriteOperation writeOperation = c.sideInput(writeOperationView); - LOG.info("Opening writer for write operation {}", writeOperation); - writer = writeOperation.createWriter(c.getPipelineOptions()); - writer.open(UUID.randomUUID().toString()); - LOG.debug("Done opening writer {} for operation {}", writer, writeOperationView); - } - try { - writer.write(c.element()); - } catch (Exception e) { - // Discard write result and close the write. - try { - writer.close(); - // The writer does not need to be reset, as this DoFn cannot be reused. - } catch (Exception closeException) { - if (closeException instanceof InterruptedException) { - // Do not silently ignore interrupted state. - Thread.currentThread().interrupt(); - } - // Do not mask the exception that caused the write to fail. - e.addSuppressed(closeException); - } - throw e; - } - } - - @Override - public void finishBundle(Context c) throws Exception { - if (writer != null) { - WriteT result = writer.close(); - c.output(result); - // Reset state in case of reuse. - writer = null; - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - Write.Bound.this.populateDisplayData(builder); - } - } - - /** - * Like {@link WriteBundles}, but where the elements for each shard have been collected into - * a single iterable. - * - * @see WriteBundles - */ - private class WriteShardedBundles extends DoFn>, WriteT> { - private final PCollectionView> writeOperationView; - - WriteShardedBundles(PCollectionView> writeOperationView) { - this.writeOperationView = writeOperationView; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - // In a sharded write, single input element represents one shard. We can open and close - // the writer in each call to processElement. - WriteOperation writeOperation = c.sideInput(writeOperationView); - LOG.info("Opening writer for write operation {}", writeOperation); - Writer writer = writeOperation.createWriter(c.getPipelineOptions()); - writer.open(UUID.randomUUID().toString()); - LOG.debug("Done opening writer {} for operation {}", writer, writeOperationView); - - try { - for (T t : c.element().getValue()) { - writer.write(t); - } - } catch (Exception e) { - try { - writer.close(); - } catch (Exception closeException) { - if (closeException instanceof InterruptedException) { - // Do not silently ignore interrupted state. - Thread.currentThread().interrupt(); - } - // Do not mask the exception that caused the write to fail. - e.addSuppressed(closeException); - } - throw e; - } - - // Close the writer; if this throws let the error propagate. - WriteT result = writer.close(); - c.output(result); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - Write.Bound.this.populateDisplayData(builder); - } - } - - private static class ApplyShardingKey implements SerializableFunction { - private final int numShards; - private int shardNumber; - - ApplyShardingKey(int numShards) { - this.numShards = numShards; - shardNumber = -1; - } - - @Override - public Integer apply(T input) { - if (shardNumber == -1) { - // We want to desynchronize the first record sharding key for each instance of - // ApplyShardingKey, so records in a small PCollection will be statistically balanced. - shardNumber = ThreadLocalRandom.current().nextInt(numShards); - } else { - shardNumber = (shardNumber + 1) % numShards; - } - return shardNumber; - } - } - - /** - * A write is performed as sequence of three {@link ParDo}'s. - * - *

              In the first, a do-once ParDo is applied to a singleton PCollection containing the Sink's - * {@link WriteOperation}. In this initialization ParDo, {@link WriteOperation#initialize} is - * called. The output of this ParDo is a singleton PCollection - * containing the WriteOperation. - * - *

              This singleton collection containing the WriteOperation is then used as a side input to a - * ParDo over the PCollection of elements to write. In this bundle-writing phase, - * {@link WriteOperation#createWriter} is called to obtain a {@link Writer}. - * {@link Writer#open} and {@link Writer#close} are called in {@link DoFn#startBundle} and - * {@link DoFn#finishBundle}, respectively, and {@link Writer#write} method is called for every - * element in the bundle. The output of this ParDo is a PCollection of writer result - * objects (see {@link Sink} for a description of writer results)-one for each bundle. - * - *

              The final do-once ParDo uses the singleton collection of the WriteOperation as input and - * the collection of writer results as a side-input. In this ParDo, - * {@link WriteOperation#finalize} is called to finalize the write. - * - *

              If the write of any element in the PCollection fails, {@link Writer#close} will be called - * before the exception that caused the write to fail is propagated and the write result will be - * discarded. - * - *

              Since the {@link WriteOperation} is serialized after the initialization ParDo and - * deserialized in the bundle-writing and finalization phases, any state change to the - * WriteOperation object that occurs during initialization is visible in the latter phases. - * However, the WriteOperation is not serialized after the bundle-writing phase. This is why - * implementations should guarantee that {@link WriteOperation#createWriter} does not mutate - * WriteOperation). - */ - private PDone createWrite( - PCollection input, WriteOperation writeOperation) { - Pipeline p = input.getPipeline(); - - // A coder to use for the WriteOperation. - @SuppressWarnings("unchecked") - Coder> operationCoder = - (Coder>) SerializableCoder.of(writeOperation.getClass()); - - // A singleton collection of the WriteOperation, to be used as input to a ParDo to initialize - // the sink. - PCollection> operationCollection = - p.apply(Create.of(writeOperation).withCoder(operationCoder)); - - // Initialize the resource in a do-once ParDo on the WriteOperation. - operationCollection = operationCollection - .apply("Initialize", ParDo.of( - new DoFn, WriteOperation>() { - @Override - public void processElement(ProcessContext c) throws Exception { - WriteOperation writeOperation = c.element(); - LOG.info("Initializing write operation {}", writeOperation); - writeOperation.initialize(c.getPipelineOptions()); - LOG.debug("Done initializing write operation {}", writeOperation); - // The WriteOperation is also the output of this ParDo, so it can have mutable - // state. - c.output(writeOperation); - } - })) - .setCoder(operationCoder); - - // Create a view of the WriteOperation to be used as a sideInput to the parallel write phase. - final PCollectionView> writeOperationView = - operationCollection.apply(View.>asSingleton()); - - // Re-window the data into the global window and remove any existing triggers. - PCollection inputInGlobalWindow = - input.apply( - Window.into(new GlobalWindows()) - .triggering(DefaultTrigger.of()) - .discardingFiredPanes()); - - // Perform the per-bundle writes as a ParDo on the input PCollection (with the WriteOperation - // as a side input) and collect the results of the writes in a PCollection. - // There is a dependency between this ParDo and the first (the WriteOperation PCollection - // as a side input), so this will happen after the initial ParDo. - PCollection results; - if (getNumShards() <= 0) { - results = inputInGlobalWindow - .apply("WriteBundles", - ParDo.of(new WriteBundles<>(writeOperationView)) - .withSideInputs(writeOperationView)); - } else { - results = inputInGlobalWindow - .apply("ApplyShardLabel", WithKeys.of(new ApplyShardingKey(getNumShards()))) - .apply("GroupIntoShards", GroupByKey.create()) - .apply("WriteShardedBundles", - ParDo.of(new WriteShardedBundles<>(writeOperationView)) - .withSideInputs(writeOperationView)); - } - results.setCoder(writeOperation.getWriterResultCoder()); - - final PCollectionView> resultsView = - results.apply(View.asIterable()); - - // Finalize the write in another do-once ParDo on the singleton collection containing the - // Writer. The results from the per-bundle writes are given as an Iterable side input. - // The WriteOperation's state is the same as after its initialization in the first do-once - // ParDo. There is a dependency between this ParDo and the parallel write (the writer results - // collection as a side input), so it will happen after the parallel write. - @SuppressWarnings("unused") - final PCollection done = operationCollection - .apply("Finalize", ParDo.of(new DoFn, Integer>() { - @Override - public void processElement(ProcessContext c) throws Exception { - WriteOperation writeOperation = c.element(); - LOG.info("Finalizing write operation {}.", writeOperation); - List results = Lists.newArrayList(c.sideInput(resultsView)); - LOG.debug("Side input initialized to finalize write operation {}.", writeOperation); - - // We must always output at least 1 shard, and honor user-specified numShards if set. - int minShardsNeeded = Math.max(1, getNumShards()); - int extraShardsNeeded = minShardsNeeded - results.size(); - if (extraShardsNeeded > 0) { - LOG.info( - "Creating {} empty output shards in addition to {} written for a total of {}.", - extraShardsNeeded, results.size(), minShardsNeeded); - for (int i = 0; i < extraShardsNeeded; ++i) { - Writer writer = writeOperation.createWriter(c.getPipelineOptions()); - writer.open(UUID.randomUUID().toString()); - WriteT emptyWrite = writer.close(); - results.add(emptyWrite); - } - LOG.debug("Done creating extra shards."); - } - - writeOperation.finalize(results, c.getPipelineOptions()); - LOG.debug("Done finalizing write operation {}", writeOperation); - } - }).withSideInputs(resultsView)); - return PDone.in(input.getPipeline()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java deleted file mode 100644 index 720ef555b2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSink.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation; -import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import java.io.OutputStream; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - -// CHECKSTYLE.OFF: JavadocStyle -/** - * A {@link Sink} that outputs records as XML-formatted elements. Writes a {@link PCollection} of - * records from JAXB-annotated classes to a single file location. - * - *

              Given a PCollection containing records of type T that can be marshalled to XML elements, this - * Sink will produce a single file consisting of a single root element that contains all of the - * elements in the PCollection. - * - *

              XML Sinks are created with a base filename to write to, a root element name that will be used - * for the root element of the output files, and a class to bind to an XML element. This class - * will be used in the marshalling of records in an input PCollection to their XML representation - * and must be able to be bound using JAXB annotations (checked at pipeline construction time). - * - *

              XML Sinks can be written to using the {@link Write} transform: - * - *

              - * p.apply(Write.to(
              - *      XmlSink.ofRecordClass(Type.class)
              - *          .withRootElementName(root_element)
              - *          .toFilenamePrefix(output_filename)));
              - * 
              - * - *

              For example, consider the following class with JAXB annotations: - * - *

              - *  {@literal @}XmlRootElement(name = "word_count_result")
              - *  {@literal @}XmlType(propOrder = {"word", "frequency"})
              - *  public class WordFrequency {
              - *    private String word;
              - *    private long frequency;
              - *
              - *    public WordFrequency() { }
              - *
              - *    public WordFrequency(String word, long frequency) {
              - *      this.word = word;
              - *      this.frequency = frequency;
              - *    }
              - *
              - *    public void setWord(String word) {
              - *      this.word = word;
              - *    }
              - *
              - *    public void setFrequency(long frequency) {
              - *      this.frequency = frequency;
              - *    }
              - *
              - *    public long getFrequency() {
              - *      return frequency;
              - *    }
              - *
              - *    public String getWord() {
              - *      return word;
              - *    }
              - *  }
              - * 
              - * - *

              The following will produce XML output with a root element named "words" from a PCollection of - * WordFrequency objects: - *

              - * p.apply(Write.to(
              - *  XmlSink.ofRecordClass(WordFrequency.class)
              - *      .withRootElement("words")
              - *      .toFilenamePrefix(output_file)));
              - * 
              - * - *

              The output of which will look like: - *

              - * {@code
              - * 
              - *
              - *  
              - *    decreased
              - *    1
              - *  
              - *
              - *  
              - *    War
              - *    4
              - *  
              - *
              - *  
              - *    empress'
              - *    14
              - *  
              - *
              - *  
              - *    stoops
              - *    6
              - *  
              - *
              - *  ...
              - * 
              - * }
              - */ -// CHECKSTYLE.ON: JavadocStyle -@SuppressWarnings("checkstyle:javadocstyle") -public class XmlSink { - protected static final String XML_EXTENSION = "xml"; - - /** - * Returns a builder for an XmlSink. You'll need to configure the class to bind, the root - * element name, and the output file prefix with {@link Bound#ofRecordClass}, {@link - * Bound#withRootElement}, and {@link Bound#toFilenamePrefix}, respectively. - */ - public static Bound write() { - return new Bound<>(null, null, null); - } - - /** - * Returns an XmlSink that writes objects as XML entities. - * - *

              Output files will have the name {@literal {baseOutputFilename}-0000i-of-0000n.xml} where n - * is the number of output bundles that the Dataflow service divides the output into. - * - * @param klass the class of the elements to write. - * @param rootElementName the enclosing root element. - * @param baseOutputFilename the output filename prefix. - */ - public static Bound writeOf( - Class klass, String rootElementName, String baseOutputFilename) { - return new Bound<>(klass, rootElementName, baseOutputFilename); - } - - /** - * A {@link FileBasedSink} that writes objects as XML elements. - */ - public static class Bound extends FileBasedSink { - final Class classToBind; - final String rootElementName; - - private Bound(Class classToBind, String rootElementName, String baseOutputFilename) { - super(baseOutputFilename, XML_EXTENSION); - this.classToBind = classToBind; - this.rootElementName = rootElementName; - } - - /** - * Returns an XmlSink that writes objects of the class specified as XML elements. - * - *

              The specified class must be able to be used to create a JAXB context. - */ - public Bound ofRecordClass(Class classToBind) { - return new Bound<>(classToBind, rootElementName, baseOutputFilename.get()); - } - - /** - * Returns an XmlSink that writes to files with the given prefix. - * - *

              Output files will have the name {@literal {filenamePrefix}-0000i-of-0000n.xml} where n is - * the number of output bundles that the Dataflow service divides the output into. - */ - public Bound toFilenamePrefix(String baseOutputFilename) { - return new Bound<>(classToBind, rootElementName, baseOutputFilename); - } - - /** - * Returns an XmlSink that writes XML files with an enclosing root element of the - * supplied name. - */ - public Bound withRootElement(String rootElementName) { - return new Bound<>(classToBind, rootElementName, baseOutputFilename.get()); - } - - /** - * Validates that the root element, class to bind to a JAXB context, and filenamePrefix have - * been set and that the class can be bound in a JAXB context. - */ - @Override - public void validate(PipelineOptions options) { - checkNotNull(classToBind, "Missing a class to bind to a JAXB context."); - checkNotNull(rootElementName, "Missing a root element name."); - checkNotNull(baseOutputFilename, "Missing a filename to write to."); - try { - JAXBContext.newInstance(classToBind); - } catch (JAXBException e) { - throw new RuntimeException("Error binding classes to a JAXB Context.", e); - } - } - - /** - * Creates an {@link XmlWriteOperation}. - */ - @Override - public XmlWriteOperation createWriteOperation(PipelineOptions options) { - return new XmlWriteOperation<>(this); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("rootElement", rootElementName) - .withLabel("XML Root Element")) - .addIfNotNull(DisplayData.item("recordClass", classToBind) - .withLabel("XML Record Class")); - } - } - - /** - * {@link Sink.WriteOperation} for XML {@link Sink}s. - */ - protected static final class XmlWriteOperation extends FileBasedWriteOperation { - public XmlWriteOperation(XmlSink.Bound sink) { - super(sink); - } - - /** - * Creates a {@link XmlWriter} with a marshaller for the type it will write. - */ - @Override - public XmlWriter createWriter(PipelineOptions options) throws Exception { - JAXBContext context; - Marshaller marshaller; - context = JAXBContext.newInstance(getSink().classToBind); - marshaller = context.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); - marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - return new XmlWriter<>(this, marshaller); - } - - /** - * Return the XmlSink.Bound for this write operation. - */ - @Override - public XmlSink.Bound getSink() { - return (XmlSink.Bound) super.getSink(); - } - } - - /** - * A {@link Sink.Writer} that can write objects as XML elements. - */ - protected static final class XmlWriter extends FileBasedWriter { - final Marshaller marshaller; - private OutputStream os = null; - - public XmlWriter(XmlWriteOperation writeOperation, Marshaller marshaller) { - super(writeOperation); - this.marshaller = marshaller; - } - - /** - * Creates the output stream that elements will be written to. - */ - @Override - protected void prepareWrite(WritableByteChannel channel) throws Exception { - os = Channels.newOutputStream(channel); - } - - /** - * Writes the root element opening tag. - */ - @Override - protected void writeHeader() throws Exception { - String rootElementName = getWriteOperation().getSink().rootElementName; - os.write(CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "<" + rootElementName + ">\n")); - } - - /** - * Writes the root element closing tag. - */ - @Override - protected void writeFooter() throws Exception { - String rootElementName = getWriteOperation().getSink().rootElementName; - os.write(CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "\n")); - } - - /** - * Writes a value to the stream. - */ - @Override - public void write(T value) throws Exception { - marshaller.marshal(value, os); - } - - /** - * Return the XmlWriteOperation this write belongs to. - */ - @Override - public XmlWriteOperation getWriteOperation() { - return (XmlWriteOperation) super.getWriteOperation(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java deleted file mode 100644 index c5eb287dd3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/XmlSource.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.JAXBCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.codehaus.stax2.XMLInputFactory2; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.SequenceInputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.NoSuchElementException; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.ValidationEvent; -import javax.xml.bind.ValidationEventHandler; -import javax.xml.stream.FactoryConfigurationError; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -// CHECKSTYLE.OFF: JavadocStyle -/** - * A source that can be used to read XML files. This source reads one or more - * XML files and creates a {@code PCollection} of a given type. An Dataflow read transform can be - * created by passing an {@code XmlSource} object to {@code Read.from()}. Please note the - * example given below. - * - *

              The XML file must be of the following form, where {@code root} and {@code record} are XML - * element names that are defined by the user: - * - *

              - * {@code
              - * 
              - *  ... 
              - *  ... 
              - *  ... 
              - * ...
              - *  ... 
              - * 
              - * }
              - * 
              - * - *

              Basically, the XML document should contain a single root element with an inner list consisting - * entirely of record elements. The records may contain arbitrary XML content; however, that content - * must not contain the start {@code } or end {@code } tags. This - * restriction enables reading from large XML files in parallel from different offsets in the file. - * - *

              Root and/or record elements may additionally contain an arbitrary number of XML attributes. - * Additionally users must provide a class of a JAXB annotated Java type that can be used convert - * records into Java objects and vice versa using JAXB marshalling/unmarshalling mechanisms. Reading - * the source will generate a {@code PCollection} of the given JAXB annotated Java type. - * Optionally users may provide a minimum size of a bundle that should be created for the source. - * - *

              The following example shows how to read from {@link XmlSource} in a Dataflow pipeline: - * - *

              - * {@code
              - * XmlSource source = XmlSource.from(file.toPath().toString())
              - *     .withRootElement("root")
              - *     .withRecordElement("record")
              - *     .withRecordClass(Record.class);
              - * PCollection output = p.apply(Read.from(source));
              - * }
              - * 
              - * - *

              Currently, only XML files that use single-byte characters are supported. Using a file that - * contains multi-byte characters may result in data loss or duplication. - * - *

              To use {@link XmlSource}: - *

                - *
              1. Explicitly declare a dependency on org.codehaus.woodstox:stax2-api
              2. - *
              3. Include a compatible implementation on the classpath at run-time, - * such as org.codehaus.woodstox:woodstox-core-asl
              4. - *
              - * - *

              These dependencies have been declared as optional in Maven sdk/pom.xml file of - * Google Cloud Dataflow. - * - *

              Permissions

              - * Permission requirements depend on the - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner PipelineRunner} that is - * used to execute the Dataflow job. Please refer to the documentation of corresponding - * {@link PipelineRunner PipelineRunners} for more details. - * - * @param Type of the objects that represent the records of the XML file. The - * {@code PCollection} generated by this source will be of this type. - */ -// CHECKSTYLE.ON: JavadocStyle -public class XmlSource extends FileBasedSource { - - private static final String XML_VERSION = "1.1"; - private static final int DEFAULT_MIN_BUNDLE_SIZE = 8 * 1024; - private final String rootElement; - private final String recordElement; - private final Class recordClass; - - /** - * Creates an XmlSource for a single XML file or a set of XML files defined by a Java "glob" file - * pattern. Each XML file should be of the form defined in {@link XmlSource}. - */ - public static XmlSource from(String fileOrPatternSpec) { - return new XmlSource<>(fileOrPatternSpec, DEFAULT_MIN_BUNDLE_SIZE, null, null, null); - } - - /** - * Sets name of the root element of the XML document. This will be used to create a valid starting - * root element when initiating a bundle of records created from an XML document. This is a - * required parameter. - */ - public XmlSource withRootElement(String rootElement) { - return new XmlSource<>( - getFileOrPatternSpec(), getMinBundleSize(), rootElement, recordElement, recordClass); - } - - /** - * Sets name of the record element of the XML document. This will be used to determine offset of - * the first record of a bundle created from the XML document. This is a required parameter. - */ - public XmlSource withRecordElement(String recordElement) { - return new XmlSource<>( - getFileOrPatternSpec(), getMinBundleSize(), rootElement, recordElement, recordClass); - } - - /** - * Sets a JAXB annotated class that can be populated using a record of the provided XML file. This - * will be used when unmarshalling record objects from the XML file. This is a required - * parameter. - */ - public XmlSource withRecordClass(Class recordClass) { - return new XmlSource<>( - getFileOrPatternSpec(), getMinBundleSize(), rootElement, recordElement, recordClass); - } - - /** - * Sets a parameter {@code minBundleSize} for the minimum bundle size of the source. Please refer - * to {@link OffsetBasedSource} for the definition of minBundleSize. This is an optional - * parameter. - */ - public XmlSource withMinBundleSize(long minBundleSize) { - return new XmlSource<>( - getFileOrPatternSpec(), minBundleSize, rootElement, recordElement, recordClass); - } - - private XmlSource(String fileOrPattern, long minBundleSize, String rootElement, - String recordElement, Class recordClass) { - super(fileOrPattern, minBundleSize); - this.rootElement = rootElement; - this.recordElement = recordElement; - this.recordClass = recordClass; - } - - private XmlSource(String fileOrPattern, long minBundleSize, long startOffset, long endOffset, - String rootElement, String recordElement, Class recordClass) { - super(fileOrPattern, minBundleSize, startOffset, endOffset); - this.rootElement = rootElement; - this.recordElement = recordElement; - this.recordClass = recordClass; - } - - @Override - protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { - return new XmlSource( - fileName, getMinBundleSize(), start, end, rootElement, recordElement, recordClass); - } - - @Override - protected FileBasedReader createSingleFileReader(PipelineOptions options) { - return new XMLReader(this); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public void validate() { - super.validate(); - checkNotNull( - rootElement, "rootElement is null. Use builder method withRootElement() to set this."); - checkNotNull( - recordElement, - "recordElement is null. Use builder method withRecordElement() to set this."); - checkNotNull( - recordClass, "recordClass is null. Use builder method withRecordClass() to set this."); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("rootElement", rootElement) - .withLabel("XML Root Element")) - .addIfNotNull(DisplayData.item("recordElement", recordElement) - .withLabel("XML Record Element")) - .addIfNotNull(DisplayData.item("recordClass", recordClass) - .withLabel("XML Record Class")); - } - - @Override - public Coder getDefaultOutputCoder() { - return JAXBCoder.of(recordClass); - } - - public String getRootElement() { - return rootElement; - } - - public String getRecordElement() { - return recordElement; - } - - public Class getRecordClass() { - return recordClass; - } - - /** - * A {@link Source.Reader} for reading JAXB annotated Java objects from an XML file. The XML - * file should be of the form defined at {@link XmlSource}. - * - *

              Timestamped values are currently unsupported - all values implicitly have the timestamp - * of {@code BoundedWindow.TIMESTAMP_MIN_VALUE}. - * - * @param Type of objects that will be read by the reader. - */ - private static class XMLReader extends FileBasedReader { - // The amount of bytes read from the channel to memory when determining the starting offset of - // the first record in a bundle. After matching to starting offset of the first record the - // remaining bytes read to this buffer and the bytes still not read from the channel are used to - // create the XML parser. - private static final int BUF_SIZE = 1024; - - // This should be the maximum number of bytes a character will encode to, for any encoding - // supported by XmlSource. Currently this is set to 4 since UTF-8 characters may be - // four bytes. - private static final int MAX_CHAR_BYTES = 4; - - // In order to support reading starting in the middle of an XML file, we construct an imaginary - // well-formed document (a header and root tag followed by the contents of the input starting at - // the record boundary) and feed it to the parser. Because of this, the offset reported by the - // XML parser is not the same as offset in the original file. They differ by a constant amount: - // offsetInOriginalFile = parser.getLocation().getCharacterOffset() + parserBaseOffset; - // Note that this is true only for files with single-byte characters. - // It appears that, as of writing, there does not exist a Java XML parser capable of correctly - // reporting byte offsets of elements in the presence of multi-byte characters. - private long parserBaseOffset = 0; - private boolean readingStarted = false; - - // If true, the current bundle does not contain any records. - private boolean emptyBundle = false; - - private Unmarshaller jaxbUnmarshaller = null; - private XMLStreamReader parser = null; - - private T currentRecord = null; - - // Byte offset of the current record in the XML file provided when creating the source. - private long currentByteOffset = 0; - - public XMLReader(XmlSource source) { - super(source); - - // Set up a JAXB Unmarshaller that can be used to unmarshall record objects. - try { - JAXBContext jaxbContext = JAXBContext.newInstance(getCurrentSource().recordClass); - jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - - // Throw errors if validation fails. JAXB by default ignores validation errors. - jaxbUnmarshaller.setEventHandler(new ValidationEventHandler() { - @Override - public boolean handleEvent(ValidationEvent event) { - throw new RuntimeException(event.getMessage(), event.getLinkedException()); - } - }); - } catch (JAXBException e) { - throw new RuntimeException(e); - } - } - - @Override - public synchronized XmlSource getCurrentSource() { - return (XmlSource) super.getCurrentSource(); - } - - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - // This method determines the correct starting offset of the first record by reading bytes - // from the ReadableByteChannel. This implementation does not need the channel to be a - // SeekableByteChannel. - // The method tries to determine the first record element in the byte channel. The first - // record must start with the characters "' character - // * '/' character (to support empty records). - // - // After this match this method creates the XML parser for parsing the XML document, - // feeding it a fake document consisting of an XML header and the tag followed - // by the contents of channel starting from tag may be never - // closed. - - // This stores any bytes that should be used prior to the remaining bytes of the channel when - // creating an XML parser object. - ByteArrayOutputStream preambleByteBuffer = new ByteArrayOutputStream(); - // A dummy declaration and root for the document with proper XML version and encoding. Without - // this XML parsing may fail or may produce incorrect results. - - byte[] dummyStartDocumentBytes = - ("" - + "<" + getCurrentSource().rootElement + ">").getBytes(StandardCharsets.UTF_8); - preambleByteBuffer.write(dummyStartDocumentBytes); - // Gets the byte offset (in the input file) of the first record in ReadableByteChannel. This - // method returns the offset and stores any bytes that should be used when creating the XML - // parser in preambleByteBuffer. - long offsetInFileOfRecordElement = - getFirstOccurenceOfRecordElement(channel, preambleByteBuffer); - if (offsetInFileOfRecordElement < 0) { - // Bundle has no records. So marking this bundle as an empty bundle. - emptyBundle = true; - return; - } else { - byte[] preambleBytes = preambleByteBuffer.toByteArray(); - currentByteOffset = offsetInFileOfRecordElement; - setUpXMLParser(channel, preambleBytes); - parserBaseOffset = offsetInFileOfRecordElement - dummyStartDocumentBytes.length; - } - readingStarted = true; - } - - // Gets the first occurrence of the next record within the given ReadableByteChannel. Puts - // any bytes read past the starting offset of the next record back to the preambleByteBuffer. - // If a record is found, returns the starting offset of the record, otherwise - // returns -1. - private long getFirstOccurenceOfRecordElement( - ReadableByteChannel channel, ByteArrayOutputStream preambleByteBuffer) throws IOException { - int byteIndexInRecordElementToMatch = 0; - // Index of the byte in the string " 0) { - buf.flip(); - while (buf.hasRemaining()) { - offsetInFileOfCurrentByte++; - byte b = buf.get(); - boolean reset = false; - if (recordStartBytesMatched) { - // We already matched "..." - // * "..." - // * "' || c == '/') { - fullyMatched = true; - // Add the recordStartBytes and charBytes to preambleByteBuffer since these were - // already read from the channel. - preambleByteBuffer.write(recordStartBytes); - preambleByteBuffer.write(charBytes); - // Also add the rest of the current buffer to preambleByteBuffer. - while (buf.hasRemaining()) { - preambleByteBuffer.write(buf.get()); - } - break outer; - } else { - // Matching was unsuccessful. Reset the buffer to include bytes read for the char. - ByteBuffer newbuf = ByteBuffer.allocate(BUF_SIZE); - newbuf.put(charBytes); - offsetInFileOfCurrentByte -= charBytes.length; - while (buf.hasRemaining()) { - newbuf.put(buf.get()); - } - newbuf.flip(); - buf = newbuf; - - // Ignore everything and try again starting from the current buffer. - reset = true; - } - } else if (b == recordStartBytes[byteIndexInRecordElementToMatch]) { - // Next byte matched. - if (!matchStarted) { - // Match was for the first byte, record the starting offset. - matchStarted = true; - startingOffsetInFileOfCurrentMatch = offsetInFileOfCurrentByte; - } - byteIndexInRecordElementToMatch++; - } else { - // Not a match. Ignore everything and try again starting at current point. - reset = true; - } - if (reset) { - // Clear variables and try to match starting from the next byte. - byteIndexInRecordElementToMatch = 0; - startingOffsetInFileOfCurrentMatch = -1; - matchStarted = false; - recordStartBytesMatched = false; - charBytes = new byte[MAX_CHAR_BYTES]; - charBytesFound = 0; - } - if (byteIndexInRecordElementToMatch == recordStartBytes.length) { - // " jb = jaxbUnmarshaller.unmarshal(parser, getCurrentSource().recordClass); - currentRecord = jb.getValue(); - return true; - } catch (JAXBException | XMLStreamException e) { - throw new IOException(e); - } - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (!readingStarted) { - throw new NoSuchElementException(); - } - return currentRecord; - } - - @Override - protected boolean isAtSplitPoint() { - // Every record is at a split point. - return true; - } - - @Override - protected long getCurrentOffset() { - return currentByteOffset; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java deleted file mode 100644 index 3751d160f5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ /dev/null @@ -1,1133 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.bigtable.v1.Mutation; -import com.google.bigtable.v1.Row; -import com.google.bigtable.v1.RowFilter; -import com.google.bigtable.v1.SampleRowKeysResponse; -import com.google.cloud.bigtable.config.BigtableOptions; -import com.google.cloud.bigtable.config.RetryOptions; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; -import com.google.cloud.dataflow.sdk.io.Sink.Writer; -import com.google.cloud.dataflow.sdk.io.range.ByteKey; -import com.google.cloud.dataflow.sdk.io.range.ByteKeyRange; -import com.google.cloud.dataflow.sdk.io.range.ByteKeyRangeTracker; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.protobuf.ByteString; -import com.google.protobuf.Empty; - -import io.grpc.Status; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.ConcurrentLinkedQueue; - -import javax.annotation.Nullable; - -/** - * A bounded source and sink for Google Cloud Bigtable. - * - *

              For more information, see the online documentation at - * Google Cloud Bigtable. - * - *

              Reading from Cloud Bigtable

              - * - *

              The Bigtable source returns a set of rows from a single table, returning a - * {@code PCollection}. - * - *

              To configure a Cloud Bigtable source, you must supply a table id and a {@link BigtableOptions} - * or builder configured with the project and other information necessary to identify the - * Bigtable cluster. By default, {@link BigtableIO.Read} will read all rows in the table. The row - * range to be read can optionally be restricted using {@link BigtableIO.Read#withKeyRange}, and - * a {@link RowFilter} can be specified using {@link BigtableIO.Read#withRowFilter}. For example: - * - *

              {@code
              - * BigtableOptions.Builder optionsBuilder =
              - *     new BigtableOptions.Builder()
              - *         .setProjectId("project")
              - *         .setClusterId("cluster")
              - *         .setZoneId("zone");
              - *
              - * Pipeline p = ...;
              - *
              - * // Scan the entire table.
              - * p.apply("read",
              - *     BigtableIO.read()
              - *         .withBigtableOptions(optionsBuilder)
              - *         .withTableId("table"));
              - *
              - * // Scan a prefix of the table.
              - * ByteKeyRange keyRange = ...;
              - * p.apply("read",
              - *     BigtableIO.read()
              - *         .withBigtableOptions(optionsBuilder)
              - *         .withTableId("table")
              - *         .withKeyRange(keyRange));
              - *
              - * // Scan a subset of rows that match the specified row filter.
              - * p.apply("filtered read",
              - *     BigtableIO.read()
              - *         .withBigtableOptions(optionsBuilder)
              - *         .withTableId("table")
              - *         .withRowFilter(filter));
              - * }
              - * - *

              Writing to Cloud Bigtable

              - * - *

              The Bigtable sink executes a set of row mutations on a single table. It takes as input a - * {@link PCollection PCollection<KV<ByteString, Iterable<Mutation>>>}, where the - * {@link ByteString} is the key of the row being mutated, and each {@link Mutation} represents an - * idempotent transformation to that row. - * - *

              To configure a Cloud Bigtable sink, you must supply a table id and a {@link BigtableOptions} - * or builder configured with the project and other information necessary to identify the - * Bigtable cluster, for example: - * - *

              {@code
              - * BigtableOptions.Builder optionsBuilder =
              - *     new BigtableOptions.Builder()
              - *         .setProjectId("project")
              - *         .setClusterId("cluster")
              - *         .setZoneId("zone");
              - *
              - * PCollection>> data = ...;
              - *
              - * data.apply("write",
              - *     BigtableIO.write()
              - *         .withBigtableOptions(optionsBuilder)
              - *         .withTableId("table"));
              - * }
              - * - *

              Experimental

              - * - *

              This connector for Cloud Bigtable is considered experimental and may break or receive - * backwards-incompatible changes in future versions of the Cloud Dataflow SDK. Cloud Bigtable is - * in Beta, and thus it may introduce breaking changes in future revisions of its service or APIs. - * - *

              Permissions

              - * - *

              Permission requirements depend on the {@link PipelineRunner} that is used to execute the - * Dataflow job. Please refer to the documentation of corresponding - * {@link PipelineRunner PipelineRunners} for more details. - */ -@Experimental -public class BigtableIO { - private static final Logger logger = LoggerFactory.getLogger(BigtableIO.class); - - /** - * Creates an uninitialized {@link BigtableIO.Read}. Before use, the {@code Read} must be - * initialized with a - * {@link BigtableIO.Read#withBigtableOptions(BigtableOptions) BigtableOptions} that specifies - * the source Cloud Bigtable cluster, and a {@link BigtableIO.Read#withTableId tableId} that - * specifies which table to read. A {@link RowFilter} may also optionally be specified using - * {@link BigtableIO.Read#withRowFilter}. - */ - @Experimental - public static Read read() { - return new Read(null, "", ByteKeyRange.ALL_KEYS, null, null); - } - - /** - * Creates an uninitialized {@link BigtableIO.Write}. Before use, the {@code Write} must be - * initialized with a - * {@link BigtableIO.Write#withBigtableOptions(BigtableOptions) BigtableOptions} that specifies - * the destination Cloud Bigtable cluster, and a {@link BigtableIO.Write#withTableId tableId} that - * specifies which table to write. - */ - @Experimental - public static Write write() { - return new Write(null, "", null); - } - - /** - * A {@link PTransform} that reads from Google Cloud Bigtable. See the class-level Javadoc on - * {@link BigtableIO} for more information. - * - * @see BigtableIO - */ - @Experimental - public static class Read extends PTransform> { - /** - * Returns a new {@link BigtableIO.Read} that will read from the Cloud Bigtable cluster - * indicated by the given options, and using any other specified customizations. - * - *

              Does not modify this object. - */ - public Read withBigtableOptions(BigtableOptions options) { - checkNotNull(options, "options"); - return withBigtableOptions(options.toBuilder()); - } - - /** - * Returns a new {@link BigtableIO.Read} that will read from the Cloud Bigtable cluster - * indicated by the given options, and using any other specified customizations. - * - *

              Clones the given {@link BigtableOptions} builder so that any further changes - * will have no effect on the returned {@link BigtableIO.Read}. - * - *

              Does not modify this object. - */ - public Read withBigtableOptions(BigtableOptions.Builder optionsBuilder) { - checkNotNull(optionsBuilder, "optionsBuilder"); - // TODO: is there a better way to clone a Builder? Want it to be immune from user changes. - BigtableOptions options = optionsBuilder.build(); - RetryOptions retryOptions = options.getRetryOptions(); - - // Set data channel count to one because there is only 1 scanner in this session - // Use retryOptionsToBuilder because absent in Bigtable library - // TODO: replace with RetryOptions.toBuilder() when added to Bigtable library - // Set batch size because of bug (incorrect initialization) in Bigtable library - // TODO: remove setRetryOptions when fixed in Bigtable library - BigtableOptions.Builder clonedBuilder = options.toBuilder() - .setDataChannelCount(1) - .setRetryOptions( - retryOptionsToBuilder(retryOptions) - .setStreamingBatchSize(Math.min(retryOptions.getStreamingBatchSize(), - retryOptions.getStreamingBufferSize() / 2)) - .build()); - BigtableOptions optionsWithAgent = clonedBuilder.setUserAgent(getUserAgent()).build(); - - return new Read(optionsWithAgent, tableId, keyRange, filter, bigtableService); - } - - /** - * Returns a new {@link BigtableIO.Read} that will filter the rows read from Cloud Bigtable - * using the given row filter. - * - *

              Does not modify this object. - */ - public Read withRowFilter(RowFilter filter) { - checkNotNull(filter, "filter"); - return new Read(options, tableId, keyRange, filter, bigtableService); - } - - /** - * Returns a new {@link BigtableIO.Read} that will read only rows in the specified range. - * - *

              Does not modify this object. - */ - public Read withKeyRange(ByteKeyRange keyRange) { - checkNotNull(keyRange, "keyRange"); - return new Read(options, tableId, keyRange, filter, bigtableService); - } - - /** - * Returns a new {@link BigtableIO.Read} that will read from the specified table. - * - *

              Does not modify this object. - */ - public Read withTableId(String tableId) { - checkNotNull(tableId, "tableId"); - return new Read(options, tableId, keyRange, filter, bigtableService); - } - - /** - * Returns the Google Cloud Bigtable cluster being read from, and other parameters. - */ - public BigtableOptions getBigtableOptions() { - return options; - } - - /** - * Returns the range of keys that will be read from the table. By default, returns - * {@link ByteKeyRange#ALL_KEYS} to scan the entire table. - */ - public ByteKeyRange getKeyRange() { - return keyRange; - } - - /** - * Returns the table being read from. - */ - public String getTableId() { - return tableId; - } - - @Override - public PCollection apply(PBegin input) { - BigtableSource source = - new BigtableSource(getBigtableService(), tableId, filter, keyRange, null); - return input.getPipeline().apply(com.google.cloud.dataflow.sdk.io.Read.from(source)); - } - - @Override - public void validate(PBegin input) { - checkArgument(options != null, "BigtableOptions not specified"); - checkArgument(!tableId.isEmpty(), "Table ID not specified"); - try { - checkArgument( - getBigtableService().tableExists(tableId), "Table %s does not exist", tableId); - } catch (IOException e) { - logger.warn("Error checking whether table {} exists; proceeding.", tableId, e); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder.add(DisplayData.item("tableId", tableId) - .withLinkUrl("Table ID")); - - if (options != null) { - builder.add(DisplayData.item("bigtableOptions", options.toString()) - .withLabel("Bigtable Options")); - } - - builder.addIfNotDefault( - DisplayData.item("keyRange", keyRange.toString()), ByteKeyRange.ALL_KEYS.toString()); - - if (filter != null) { - builder.add(DisplayData.item("rowFilter", filter.toString()) - .withLabel("Table Row Filter")); - } - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(Read.class) - .add("options", options) - .add("tableId", tableId) - .add("keyRange", keyRange) - .add("filter", filter) - .toString(); - } - - ///////////////////////////////////////////////////////////////////////////////////////// - /** - * Used to define the Cloud Bigtable cluster and any options for the networking layer. - * Cannot actually be {@code null} at validation time, but may start out {@code null} while - * source is being built. - */ - @Nullable private final BigtableOptions options; - private final String tableId; - private final ByteKeyRange keyRange; - @Nullable private final RowFilter filter; - @Nullable private final BigtableService bigtableService; - - private Read( - @Nullable BigtableOptions options, - String tableId, - ByteKeyRange keyRange, - @Nullable RowFilter filter, - @Nullable BigtableService bigtableService) { - this.options = options; - this.tableId = checkNotNull(tableId, "tableId"); - this.keyRange = checkNotNull(keyRange, "keyRange"); - this.filter = filter; - this.bigtableService = bigtableService; - } - - /** - * Returns a new {@link BigtableIO.Read} that will read using the given Cloud Bigtable - * service implementation. - * - *

              This is used for testing. - * - *

              Does not modify this object. - */ - Read withBigtableService(BigtableService bigtableService) { - checkNotNull(bigtableService, "bigtableService"); - return new Read(options, tableId, keyRange, filter, bigtableService); - } - - /** - * Helper function that either returns the mock Bigtable service supplied by - * {@link #withBigtableService} or creates and returns an implementation that talks to - * {@code Cloud Bigtable}. - */ - private BigtableService getBigtableService() { - if (bigtableService != null) { - return bigtableService; - } - return new BigtableServiceImpl(options); - } - } - - /** - * A {@link PTransform} that writes to Google Cloud Bigtable. See the class-level Javadoc on - * {@link BigtableIO} for more information. - * - * @see BigtableIO - */ - @Experimental - public static class Write - extends PTransform>>, PDone> { - /** - * Used to define the Cloud Bigtable cluster and any options for the networking layer. - * Cannot actually be {@code null} at validation time, but may start out {@code null} while - * source is being built. - */ - @Nullable private final BigtableOptions options; - private final String tableId; - @Nullable private final BigtableService bigtableService; - - private Write( - @Nullable BigtableOptions options, - String tableId, - @Nullable BigtableService bigtableService) { - this.options = options; - this.tableId = checkNotNull(tableId, "tableId"); - this.bigtableService = bigtableService; - } - - /** - * Returns a new {@link BigtableIO.Write} that will write to the Cloud Bigtable cluster - * indicated by the given options, and using any other specified customizations. - * - *

              Does not modify this object. - */ - public Write withBigtableOptions(BigtableOptions options) { - checkNotNull(options, "options"); - return withBigtableOptions(options.toBuilder()); - } - - /** - * Returns a new {@link BigtableIO.Write} that will write to the Cloud Bigtable cluster - * indicated by the given options, and using any other specified customizations. - * - *

              Clones the given {@link BigtableOptions} builder so that any further changes - * will have no effect on the returned {@link BigtableIO.Write}. - * - *

              Does not modify this object. - */ - public Write withBigtableOptions(BigtableOptions.Builder optionsBuilder) { - checkNotNull(optionsBuilder, "optionsBuilder"); - // TODO: is there a better way to clone a Builder? Want it to be immune from user changes. - BigtableOptions options = optionsBuilder.build(); - RetryOptions retryOptions = options.getRetryOptions(); - - // Set useBulkApi to true for enabling bulk writes - // Use retryOptionsToBuilder because absent in Bigtable library - // TODO: replace with RetryOptions.toBuilder() when added to Bigtable library - // Set batch size because of bug (incorrect initialization) in Bigtable library - // TODO: remove setRetryOptions when fixed in Bigtable library - BigtableOptions.Builder clonedBuilder = options.toBuilder() - .setBulkOptions( - options.getBulkOptions().toBuilder() - .setUseBulkApi(true) - .build()) - .setRetryOptions( - retryOptionsToBuilder(retryOptions) - .setStreamingBatchSize(Math.min(retryOptions.getStreamingBatchSize(), - retryOptions.getStreamingBufferSize() / 2)) - .build()); - BigtableOptions optionsWithAgent = clonedBuilder.setUserAgent(getUserAgent()).build(); - return new Write(optionsWithAgent, tableId, bigtableService); - } - - /** - * Returns a new {@link BigtableIO.Write} that will write to the specified table. - * - *

              Does not modify this object. - */ - public Write withTableId(String tableId) { - checkNotNull(tableId, "tableId"); - return new Write(options, tableId, bigtableService); - } - - /** - * Returns the Google Cloud Bigtable cluster being written to, and other parameters. - */ - public BigtableOptions getBigtableOptions() { - return options; - } - - /** - * Returns the table being written to. - */ - public String getTableId() { - return tableId; - } - - @Override - public PDone apply(PCollection>> input) { - Sink sink = new Sink(tableId, getBigtableService()); - return input.apply(com.google.cloud.dataflow.sdk.io.Write.to(sink)); - } - - @Override - public void validate(PCollection>> input) { - checkArgument(options != null, "BigtableOptions not specified"); - checkArgument(!tableId.isEmpty(), "Table ID not specified"); - try { - checkArgument( - getBigtableService().tableExists(tableId), "Table %s does not exist", tableId); - } catch (IOException e) { - logger.warn("Error checking whether table {} exists; proceeding.", tableId, e); - } - } - - /** - * Returns a new {@link BigtableIO.Write} that will write using the given Cloud Bigtable - * service implementation. - * - *

              This is used for testing. - * - *

              Does not modify this object. - */ - Write withBigtableService(BigtableService bigtableService) { - checkNotNull(bigtableService, "bigtableService"); - return new Write(options, tableId, bigtableService); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder.add(DisplayData.item("tableId", tableId) - .withLabel("Table ID")); - - if (options != null) { - builder.add(DisplayData.item("bigtableOptions", options.toString()) - .withLabel("Bigtable Options")); - } - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(Write.class) - .add("options", options) - .add("tableId", tableId) - .toString(); - } - - /** - * Helper function that either returns the mock Bigtable service supplied by - * {@link #withBigtableService} or creates and returns an implementation that talks to - * {@code Cloud Bigtable}. - */ - private BigtableService getBigtableService() { - if (bigtableService != null) { - return bigtableService; - } - return new BigtableServiceImpl(options); - } - } - - ////////////////////////////////////////////////////////////////////////////////////////// - /** Disallow construction of utility class. */ - private BigtableIO() {} - - static class BigtableSource extends BoundedSource { - public BigtableSource( - BigtableService service, - String tableId, - @Nullable RowFilter filter, - ByteKeyRange range, - @Nullable Long estimatedSizeBytes) { - this.service = service; - this.tableId = tableId; - this.filter = filter; - this.range = range; - this.estimatedSizeBytes = estimatedSizeBytes; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(BigtableSource.class) - .add("tableId", tableId) - .add("filter", filter) - .add("range", range) - .add("estimatedSizeBytes", estimatedSizeBytes) - .toString(); - } - - ////// Private state and internal implementation details ////// - private final BigtableService service; - private final String tableId; - @Nullable private final RowFilter filter; - private final ByteKeyRange range; - @Nullable private Long estimatedSizeBytes; - @Nullable private transient List sampleRowKeys; - - protected BigtableSource withStartKey(ByteKey startKey) { - checkNotNull(startKey, "startKey"); - return new BigtableSource( - service, tableId, filter, range.withStartKey(startKey), estimatedSizeBytes); - } - - protected BigtableSource withEndKey(ByteKey endKey) { - checkNotNull(endKey, "endKey"); - return new BigtableSource( - service, tableId, filter, range.withEndKey(endKey), estimatedSizeBytes); - } - - protected BigtableSource withEstimatedSizeBytes(Long estimatedSizeBytes) { - checkNotNull(estimatedSizeBytes, "estimatedSizeBytes"); - return new BigtableSource(service, tableId, filter, range, estimatedSizeBytes); - } - - /** - * Makes an API call to the Cloud Bigtable service that gives information about tablet key - * boundaries and estimated sizes. We can use these samples to ensure that splits are on - * different tablets, and possibly generate sub-splits within tablets. - */ - private List getSampleRowKeys() throws IOException { - return service.getSampleRowKeys(this); - } - - @Override - public List splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - // Update the desiredBundleSizeBytes in order to limit the - // number of splits to maximumNumberOfSplits. - long maximumNumberOfSplits = 4000; - long sizeEstimate = getEstimatedSizeBytes(options); - desiredBundleSizeBytes = - Math.max(sizeEstimate / maximumNumberOfSplits, desiredBundleSizeBytes); - - // Delegate to testable helper. - return splitIntoBundlesBasedOnSamples(desiredBundleSizeBytes, getSampleRowKeys()); - } - - /** Helper that splits this source into bundles based on Cloud Bigtable sampled row keys. */ - private List splitIntoBundlesBasedOnSamples( - long desiredBundleSizeBytes, List sampleRowKeys) { - // There are no regions, or no samples available. Just scan the entire range. - if (sampleRowKeys.isEmpty()) { - logger.info("Not splitting source {} because no sample row keys are available.", this); - return Collections.singletonList(this); - } - - logger.info( - "About to split into bundles of size {} with sampleRowKeys length {} first element {}", - desiredBundleSizeBytes, - sampleRowKeys.size(), - sampleRowKeys.get(0)); - - // Loop through all sampled responses and generate splits from the ones that overlap the - // scan range. The main complication is that we must track the end range of the previous - // sample to generate good ranges. - ByteKey lastEndKey = ByteKey.EMPTY; - long lastOffset = 0; - ImmutableList.Builder splits = ImmutableList.builder(); - for (SampleRowKeysResponse response : sampleRowKeys) { - ByteKey responseEndKey = ByteKey.of(response.getRowKey()); - long responseOffset = response.getOffsetBytes(); - checkState( - responseOffset >= lastOffset, - "Expected response byte offset %s to come after the last offset %s", - responseOffset, - lastOffset); - - if (!range.overlaps(ByteKeyRange.of(lastEndKey, responseEndKey))) { - // This region does not overlap the scan, so skip it. - lastOffset = responseOffset; - lastEndKey = responseEndKey; - continue; - } - - // Calculate the beginning of the split as the larger of startKey and the end of the last - // split. Unspecified start is smallest key so is correctly treated as earliest key. - ByteKey splitStartKey = lastEndKey; - if (splitStartKey.compareTo(range.getStartKey()) < 0) { - splitStartKey = range.getStartKey(); - } - - // Calculate the end of the split as the smaller of endKey and the end of this sample. Note - // that range.containsKey handles the case when range.getEndKey() is empty. - ByteKey splitEndKey = responseEndKey; - if (!range.containsKey(splitEndKey)) { - splitEndKey = range.getEndKey(); - } - - // We know this region overlaps the desired key range, and we know a rough estimate of its - // size. Split the key range into bundle-sized chunks and then add them all as splits. - long sampleSizeBytes = responseOffset - lastOffset; - List subSplits = - splitKeyRangeIntoBundleSizedSubranges( - sampleSizeBytes, - desiredBundleSizeBytes, - ByteKeyRange.of(splitStartKey, splitEndKey)); - splits.addAll(subSplits); - - // Move to the next region. - lastEndKey = responseEndKey; - lastOffset = responseOffset; - } - - // We must add one more region after the end of the samples if both these conditions hold: - // 1. we did not scan to the end yet (lastEndKey is concrete, not 0-length). - // 2. we want to scan to the end (endKey is empty) or farther (lastEndKey < endKey). - if (!lastEndKey.isEmpty() - && (range.getEndKey().isEmpty() || lastEndKey.compareTo(range.getEndKey()) < 0)) { - splits.add(this.withStartKey(lastEndKey).withEndKey(range.getEndKey())); - } - - List ret = splits.build(); - logger.info("Generated {} splits. First split: {}", ret.size(), ret.get(0)); - return ret; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws IOException { - // Delegate to testable helper. - if (estimatedSizeBytes == null) { - estimatedSizeBytes = getEstimatedSizeBytesBasedOnSamples(getSampleRowKeys()); - } - return estimatedSizeBytes; - } - - /** - * Computes the estimated size in bytes based on the total size of all samples that overlap - * the key range this source will scan. - */ - private long getEstimatedSizeBytesBasedOnSamples(List samples) { - long estimatedSizeBytes = 0; - long lastOffset = 0; - ByteKey currentStartKey = ByteKey.EMPTY; - // Compute the total estimated size as the size of each sample that overlaps the scan range. - // TODO: In future, Bigtable service may provide finer grained APIs, e.g., to sample given a - // filter or to sample on a given key range. - for (SampleRowKeysResponse response : samples) { - ByteKey currentEndKey = ByteKey.of(response.getRowKey()); - long currentOffset = response.getOffsetBytes(); - if (!currentStartKey.isEmpty() && currentStartKey.equals(currentEndKey)) { - // Skip an empty region. - lastOffset = currentOffset; - continue; - } else if (range.overlaps(ByteKeyRange.of(currentStartKey, currentEndKey))) { - estimatedSizeBytes += currentOffset - lastOffset; - } - currentStartKey = currentEndKey; - lastOffset = currentOffset; - } - return estimatedSizeBytes; - } - - /** - * Cloud Bigtable returns query results ordered by key. - */ - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return true; - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return new BigtableReader(this, service); - } - - @Override - public void validate() { - checkArgument(!tableId.isEmpty(), "tableId cannot be empty"); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder.add(DisplayData.item("tableId", tableId) - .withLabel("Table ID")); - - if (filter != null) { - builder.add(DisplayData.item("rowFilter", filter.toString()) - .withLabel("Table Row Filter")); - } - } - - @Override - public Coder getDefaultOutputCoder() { - return ProtoCoder.of(Row.class); - } - - /** Helper that splits the specified range in this source into bundles. */ - private List splitKeyRangeIntoBundleSizedSubranges( - long sampleSizeBytes, long desiredBundleSizeBytes, ByteKeyRange range) { - // Catch the trivial cases. Split is small enough already, or this is the last region. - logger.debug( - "Subsplit for sampleSizeBytes {} and desiredBundleSizeBytes {}", - sampleSizeBytes, - desiredBundleSizeBytes); - if (sampleSizeBytes <= desiredBundleSizeBytes) { - return Collections.singletonList( - this.withStartKey(range.getStartKey()).withEndKey(range.getEndKey())); - } - - checkArgument( - sampleSizeBytes > 0, "Sample size %s bytes must be greater than 0.", sampleSizeBytes); - checkArgument( - desiredBundleSizeBytes > 0, - "Desired bundle size %s bytes must be greater than 0.", - desiredBundleSizeBytes); - - int splitCount = (int) Math.ceil(((double) sampleSizeBytes) / (desiredBundleSizeBytes)); - List splitKeys = range.split(splitCount); - ImmutableList.Builder splits = ImmutableList.builder(); - Iterator keys = splitKeys.iterator(); - ByteKey prev = keys.next(); - while (keys.hasNext()) { - ByteKey next = keys.next(); - splits.add( - this - .withStartKey(prev) - .withEndKey(next) - .withEstimatedSizeBytes(sampleSizeBytes / splitCount)); - prev = next; - } - return splits.build(); - } - - public ByteKeyRange getRange() { - return range; - } - - public RowFilter getRowFilter() { - return filter; - } - - public String getTableId() { - return tableId; - } - } - - private static class BigtableReader extends BoundedReader { - // Thread-safety: source is protected via synchronization and is only accessed or modified - // inside a synchronized block (or constructor, which is the same). - private BigtableSource source; - private BigtableService service; - private BigtableService.Reader reader; - private final ByteKeyRangeTracker rangeTracker; - private long recordsReturned; - - public BigtableReader(BigtableSource source, BigtableService service) { - this.source = source; - this.service = service; - rangeTracker = ByteKeyRangeTracker.of(source.getRange()); - } - - @Override - public boolean start() throws IOException { - reader = service.createReader(getCurrentSource()); - boolean hasRecord = - reader.start() - && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())) - || rangeTracker.markDone(); - if (hasRecord) { - ++recordsReturned; - } - return hasRecord; - } - - @Override - public synchronized BigtableSource getCurrentSource() { - return source; - } - - @Override - public boolean advance() throws IOException { - boolean hasRecord = - reader.advance() - && rangeTracker.tryReturnRecordAt(true, ByteKey.of(reader.getCurrentRow().getKey())) - || rangeTracker.markDone(); - if (hasRecord) { - ++recordsReturned; - } - return hasRecord; - } - - @Override - public Row getCurrent() throws NoSuchElementException { - return reader.getCurrentRow(); - } - - @Override - public void close() throws IOException { - logger.info("Closing reader after reading {} records.", recordsReturned); - if (reader != null) { - reader.close(); - reader = null; - } - } - - @Override - public final Double getFractionConsumed() { - return rangeTracker.getFractionConsumed(); - } - - @Override - public final long getSplitPointsConsumed() { - return rangeTracker.getSplitPointsConsumed(); - } - - @Override - public final synchronized BigtableSource splitAtFraction(double fraction) { - ByteKey splitKey; - try { - splitKey = rangeTracker.getRange().interpolateKey(fraction); - } catch (IllegalArgumentException e) { - logger.info( - "%s: Failed to interpolate key for fraction %s.", rangeTracker.getRange(), fraction); - return null; - } - logger.debug( - "Proposing to split {} at fraction {} (key {})", rangeTracker, fraction, splitKey); - BigtableSource primary = source.withEndKey(splitKey); - BigtableSource residual = source.withStartKey(splitKey); - if (!rangeTracker.trySplitAtPosition(splitKey)) { - return null; - } - this.source = primary; - return residual; - } - } - - private static class Sink - extends com.google.cloud.dataflow.sdk.io.Sink>> { - - public Sink(String tableId, BigtableService bigtableService) { - this.tableId = checkNotNull(tableId, "tableId"); - this.bigtableService = checkNotNull(bigtableService, "bigtableService"); - } - - public String getTableId() { - return tableId; - } - - public BigtableService getBigtableService() { - return bigtableService; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(Sink.class) - .add("bigtableService", bigtableService) - .add("tableId", tableId) - .toString(); - } - - /////////////////////////////////////////////////////////////////////////////// - private final String tableId; - private final BigtableService bigtableService; - - @Override - public WriteOperation>, Long> createWriteOperation( - PipelineOptions options) { - return new BigtableWriteOperation(this); - } - - /** Does nothing, as it is redundant with {@link Write#validate}. */ - @Override - public void validate(PipelineOptions options) {} - } - - private static class BigtableWriteOperation - extends WriteOperation>, Long> { - private final Sink sink; - - public BigtableWriteOperation(Sink sink) { - this.sink = sink; - } - - @Override - public Writer>, Long> createWriter(PipelineOptions options) - throws Exception { - return new BigtableWriter(this); - } - - @Override - public void initialize(PipelineOptions options) {} - - @Override - public void finalize(Iterable writerResults, PipelineOptions options) { - long count = 0; - for (Long value : writerResults) { - value += count; - } - logger.debug("Wrote {} elements to BigtableIO.Sink {}", sink); - } - - @Override - public Sink getSink() { - return sink; - } - - @Override - public Coder getWriterResultCoder() { - return VarLongCoder.of(); - } - } - - private static class BigtableWriter extends Writer>, Long> { - private final BigtableWriteOperation writeOperation; - private final Sink sink; - private BigtableService.Writer bigtableWriter; - private long recordsWritten; - private final ConcurrentLinkedQueue failures; - - public BigtableWriter(BigtableWriteOperation writeOperation) { - this.writeOperation = writeOperation; - this.sink = writeOperation.getSink(); - this.failures = new ConcurrentLinkedQueue<>(); - } - - @Override - public void open(String uId) throws Exception { - bigtableWriter = sink.getBigtableService().openForWriting(sink.getTableId()); - recordsWritten = 0; - } - - /** - * If any write has asynchronously failed, fail the bundle with a useful error. - */ - private void checkForFailures() throws IOException { - // Note that this function is never called by multiple threads and is the only place that - // we remove from failures, so this code is safe. - if (failures.isEmpty()) { - return; - } - - StringBuilder logEntry = new StringBuilder(); - int i = 0; - for (; i < 10 && !failures.isEmpty(); ++i) { - BigtableWriteException exc = failures.remove(); - logEntry.append("\n").append(exc.getMessage()); - if (exc.getCause() != null) { - logEntry.append(": ").append(exc.getCause().getMessage()); - } - } - String message = - String.format( - "At least %d errors occurred writing to Bigtable. First %d errors: %s", - i + failures.size(), - i, - logEntry.toString()); - logger.error(message); - throw new IOException(message); - } - - @Override - public void write(KV> rowMutations) throws Exception { - checkForFailures(); - Futures.addCallback( - bigtableWriter.writeRecord(rowMutations), new WriteExceptionCallback(rowMutations)); - ++recordsWritten; - } - - @Override - public Long close() throws Exception { - bigtableWriter.close(); - bigtableWriter = null; - checkForFailures(); - logger.info("Wrote {} records", recordsWritten); - return recordsWritten; - } - - @Override - public WriteOperation>, Long> getWriteOperation() { - return writeOperation; - } - - private class WriteExceptionCallback implements FutureCallback { - private final KV> value; - - public WriteExceptionCallback(KV> value) { - this.value = value; - } - - @Override - public void onFailure(Throwable cause) { - failures.add(new BigtableWriteException(value, cause)); - } - - @Override - public void onSuccess(Empty produced) {} - } - } - - /** - * An exception that puts information about the failed record being written in its message. - */ - static class BigtableWriteException extends IOException { - public BigtableWriteException(KV> record, Throwable cause) { - super( - String.format( - "Error mutating row %s with mutations %s", - record.getKey().toStringUtf8(), - record.getValue()), - cause); - } - } - - /** - * A helper function to produce a Cloud Bigtable user agent string. - */ - private static String getUserAgent() { - String javaVersion = System.getProperty("java.specification.version"); - DataflowReleaseInfo info = DataflowReleaseInfo.getReleaseInfo(); - return String.format( - "%s/%s (%s); %s", - info.getName(), - info.getVersion(), - javaVersion, - "0.3.0" /* TODO get Bigtable client version directly from jar. */); - } - - /** - * A helper function to convert a RetryOptions into a RetryOptions.Builder. - */ - private static RetryOptions.Builder retryOptionsToBuilder(RetryOptions options) { - RetryOptions.Builder builder = new RetryOptions.Builder(); - builder.setEnableRetries(options.enableRetries()); - builder.setInitialBackoffMillis(options.getInitialBackoffMillis()); - builder.setBackoffMultiplier(options.getBackoffMultiplier()); - builder.setMaxElapsedBackoffMillis(options.getMaxElaspedBackoffMillis()); - builder.setStreamingBufferSize(options.getStreamingBufferSize()); - builder.setStreamingBatchSize(options.getStreamingBatchSize()); - builder.setReadPartialRowTimeoutMillis(options.getReadPartialRowTimeoutMillis()); - builder.setMaxScanTimeoutRetries(options.getMaxScanTimeoutRetries()); - builder.setAllowRetriesWithoutTimestamp(options.allowRetriesWithoutTimestamp()); - - for (Status.Code code : Status.Code.values()) { - if (options.isRetryable(code)) { - builder.addStatusToRetryOn(code); - } - } - - return builder; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java deleted file mode 100644 index 85d706cb0a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableService.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; - -import com.google.bigtable.v1.Mutation; -import com.google.bigtable.v1.Row; -import com.google.bigtable.v1.SampleRowKeysResponse; -import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.protobuf.ByteString; -import com.google.protobuf.Empty; - -import java.io.IOException; -import java.io.Serializable; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * An interface for real or fake implementations of Cloud Bigtable. - */ -interface BigtableService extends Serializable { - - /** - * The interface of a class that can write to Cloud Bigtable. - */ - interface Writer { - /** - * Writes a single row transaction to Cloud Bigtable. The key of the {@code record} is the - * row key to be mutated and the iterable of mutations represent the changes to be made to the - * row. - * - * @throws IOException if there is an error submitting the write. - */ - ListenableFuture writeRecord(KV> record) - throws IOException; - - /** - * Closes the writer. - * - * @throws IOException if any writes did not succeed - */ - void close() throws IOException; - } - - /** - * The interface of a class that reads from Cloud Bigtable. - */ - interface Reader { - /** - * Reads the first element (including initialization, such as opening a network connection) and - * returns true if an element was found. - */ - boolean start() throws IOException; - - /** - * Attempts to read the next element, and returns true if an element has been read. - */ - boolean advance() throws IOException; - - /** - * Closes the reader. - * - * @throws IOException if there is an error. - */ - void close() throws IOException; - - /** - * Returns the last row read by a successful start() or advance(), or throws if there is no - * current row because the last such call was unsuccessful. - */ - Row getCurrentRow() throws NoSuchElementException; - } - - /** - * Returns {@code true} if the table with the give name exists. - */ - boolean tableExists(String tableId) throws IOException; - - /** - * Returns a {@link Reader} that will read from the specified source. - */ - Reader createReader(BigtableSource source) throws IOException; - - /** - * Returns a {@link Writer} that will write to the specified table. - */ - Writer openForWriting(String tableId) throws IOException; - - /** - * Returns a set of row keys sampled from the underlying table. These contain information about - * the distribution of keys within the table. - */ - List getSampleRowKeys(BigtableSource source) throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java deleted file mode 100644 index bfdf1cd909..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableServiceImpl.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; - -import com.google.bigtable.admin.table.v1.GetTableRequest; -import com.google.bigtable.v1.MutateRowRequest; -import com.google.bigtable.v1.Mutation; -import com.google.bigtable.v1.ReadRowsRequest; -import com.google.bigtable.v1.Row; -import com.google.bigtable.v1.RowRange; -import com.google.bigtable.v1.SampleRowKeysRequest; -import com.google.bigtable.v1.SampleRowKeysResponse; -import com.google.cloud.bigtable.config.BigtableOptions; -import com.google.cloud.bigtable.grpc.BigtableSession; -import com.google.cloud.bigtable.grpc.BigtableTableName; -import com.google.cloud.bigtable.grpc.async.AsyncExecutor; -import com.google.cloud.bigtable.grpc.async.BulkMutation; -import com.google.cloud.bigtable.grpc.scanner.ResultScanner; -import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.MoreObjects; -import com.google.common.io.Closer; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.protobuf.ByteString; -import com.google.protobuf.Empty; - -import io.grpc.Status.Code; -import io.grpc.StatusRuntimeException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * An implementation of {@link BigtableService} that actually communicates with the Cloud Bigtable - * service. - */ -class BigtableServiceImpl implements BigtableService { - private static final Logger logger = LoggerFactory.getLogger(BigtableService.class); - - public BigtableServiceImpl(BigtableOptions options) { - this.options = options; - } - - private final BigtableOptions options; - - @Override - public BigtableWriterImpl openForWriting(String tableId) throws IOException { - BigtableSession session = new BigtableSession(options); - BigtableTableName tableName = options.getClusterName().toTableName(tableId); - return new BigtableWriterImpl(session, tableName); - } - - @Override - public boolean tableExists(String tableId) throws IOException { - if (!BigtableSession.isAlpnProviderEnabled()) { - logger.info( - "Skipping existence check for table {} (BigtableOptions {}) because ALPN is not" - + " configured.", - tableId, - options); - return true; - } - - try (BigtableSession session = new BigtableSession(options)) { - GetTableRequest getTable = - GetTableRequest.newBuilder() - .setName(options.getClusterName().toTableNameStr(tableId)) - .build(); - session.getTableAdminClient().getTable(getTable); - return true; - } catch (StatusRuntimeException e) { - if (e.getStatus().getCode() == Code.NOT_FOUND) { - return false; - } - String message = - String.format( - "Error checking whether table %s (BigtableOptions %s) exists", tableId, options); - logger.error(message, e); - throw new IOException(message, e); - } - } - - private class BigtableReaderImpl implements Reader { - private BigtableSession session; - private final BigtableSource source; - private ResultScanner results; - private Row currentRow; - - public BigtableReaderImpl(BigtableSession session, BigtableSource source) { - this.session = session; - this.source = source; - } - - @Override - public boolean start() throws IOException { - RowRange range = - RowRange.newBuilder() - .setStartKey(source.getRange().getStartKey().getValue()) - .setEndKey(source.getRange().getEndKey().getValue()) - .build(); - ReadRowsRequest.Builder requestB = - ReadRowsRequest.newBuilder() - .setRowRange(range) - .setTableName(options.getClusterName().toTableNameStr(source.getTableId())); - if (source.getRowFilter() != null) { - requestB.setFilter(source.getRowFilter()); - } - results = session.getDataClient().readRows(requestB.build()); - return advance(); - } - - @Override - public boolean advance() throws IOException { - currentRow = results.next(); - return (currentRow != null); - } - - @Override - public void close() throws IOException { - // Goal: by the end of this function, both results and session are null and closed, - // independent of what errors they throw or prior state. - - if (session == null) { - // Only possible when previously closed, so we know that results is also null. - return; - } - - // Session does not implement Closeable -- it's AutoCloseable. So we can't register it with - // the Closer, but we can use the Closer to simplify the error handling. - try (Closer closer = Closer.create()) { - if (results != null) { - closer.register(results); - results = null; - } - - session.close(); - } finally { - session = null; - } - } - - @Override - public Row getCurrentRow() throws NoSuchElementException { - if (currentRow == null) { - throw new NoSuchElementException(); - } - return currentRow; - } - } - - private static class BigtableWriterImpl implements Writer { - private BigtableSession session; - private AsyncExecutor executor; - private BulkMutation bulkMutation; - private final MutateRowRequest.Builder partialBuilder; - - public BigtableWriterImpl(BigtableSession session, BigtableTableName tableName) { - this.session = session; - executor = session.createAsyncExecutor(); - bulkMutation = session.createBulkMutation(tableName, executor); - - partialBuilder = MutateRowRequest.newBuilder().setTableName(tableName.toString()); - } - - @Override - public void close() throws IOException { - try { - if (bulkMutation != null) { - bulkMutation.flush(); - bulkMutation = null; - executor.flush(); - executor = null; - } - } finally { - if (session != null) { - session.close(); - session = null; - } - } - } - - @Override - public ListenableFuture writeRecord(KV> record) - throws IOException { - MutateRowRequest r = - partialBuilder - .clone() - .setRowKey(record.getKey()) - .addAllMutations(record.getValue()) - .build(); - return bulkMutation.add(r); - } - } - - @Override - public String toString() { - return MoreObjects - .toStringHelper(BigtableServiceImpl.class) - .add("options", options) - .toString(); - } - - @Override - public Reader createReader(BigtableSource source) throws IOException { - BigtableSession session = new BigtableSession(options); - return new BigtableReaderImpl(session, source); - } - - @Override - public List getSampleRowKeys(BigtableSource source) throws IOException { - try (BigtableSession session = new BigtableSession(options)) { - SampleRowKeysRequest request = - SampleRowKeysRequest.newBuilder() - .setTableName(options.getClusterName().toTableNameStr(source.getTableId())) - .build(); - return session.getDataClient().sampleRowKeys(request); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java deleted file mode 100644 index 112a954d71..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines transforms for reading and writing from Google Cloud Bigtable. - * - * @see com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO - */ -package com.google.cloud.dataflow.sdk.io.bigtable; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java deleted file mode 100644 index 403036e4f3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreIO.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.datastore; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; - -/** - * {@link DatastoreIO} provides an API for reading from and writing to - * Google Cloud Datastore over different - * versions of the Cloud Datastore Client libraries. - * - *

              To use the v1 version see {@link DatastoreV1}. - */ -@Experimental(Experimental.Kind.SOURCE_SINK) -public class DatastoreIO { - - private DatastoreIO() {} - - /** - * Returns a {@link DatastoreV1} that provides an API for accessing Cloud Datastore through v1 - * version of Cloud Datastore Client library. - */ - public static DatastoreV1 v1() { - return new DatastoreV1(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java deleted file mode 100644 index 3cb7a6b4d5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1.java +++ /dev/null @@ -1,1043 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.datastore; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Verify.verify; -import static com.google.datastore.v1.PropertyFilter.Operator.EQUAL; -import static com.google.datastore.v1.PropertyOrder.Direction.DESCENDING; -import static com.google.datastore.v1.QueryResultBatch.MoreResultsType.NOT_FINISHED; -import static com.google.datastore.v1.client.DatastoreHelper.makeAndFilter; -import static com.google.datastore.v1.client.DatastoreHelper.makeDelete; -import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; -import static com.google.datastore.v1.client.DatastoreHelper.makeOrder; -import static com.google.datastore.v1.client.DatastoreHelper.makeUpsert; -import static com.google.datastore.v1.client.DatastoreHelper.makeValue; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.Sleeper; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.util.FluentBackoff; -import com.google.cloud.dataflow.sdk.util.RetryHttpRequestInitializer; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; -import com.google.datastore.v1.CommitRequest; -import com.google.datastore.v1.Entity; -import com.google.datastore.v1.EntityResult; -import com.google.datastore.v1.Key; -import com.google.datastore.v1.Key.PathElement; -import com.google.datastore.v1.Mutation; -import com.google.datastore.v1.PartitionId; -import com.google.datastore.v1.Query; -import com.google.datastore.v1.QueryResultBatch; -import com.google.datastore.v1.RunQueryRequest; -import com.google.datastore.v1.RunQueryResponse; -import com.google.datastore.v1.client.Datastore; -import com.google.datastore.v1.client.DatastoreException; -import com.google.datastore.v1.client.DatastoreFactory; -import com.google.datastore.v1.client.DatastoreHelper; -import com.google.datastore.v1.client.DatastoreOptions; -import com.google.datastore.v1.client.QuerySplitter; -import com.google.protobuf.Int32Value; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * {@link DatastoreV1} provides an API to Read, Write and Delete {@link PCollection PCollections} - * of Google Cloud Datastore version v1 - * {@link Entity} objects. - * - *

              This API currently requires an authentication workaround. To use {@link DatastoreV1}, users - * must use the {@code gcloud} command line tool to get credentials for Cloud Datastore: - *

              - * $ gcloud auth login
              - * 
              - * - *

              To read a {@link PCollection} from a query to Cloud Datastore, use {@link DatastoreV1#read} - * and its methods {@link DatastoreV1.Read#withProjectId} and {@link DatastoreV1.Read#withQuery} to - * specify the project to query and the query to read from. You can optionally provide a namespace - * to query within using {@link DatastoreV1.Read#withNamespace}. You could also optionally specify - * how many splits you want for the query using {@link DatastoreV1.Read#withNumQuerySplits}. - * - *

              For example: - * - *

               {@code
              - * // Read a query from Datastore
              - * PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
              - * Query query = ...;
              - * String projectId = "...";
              - *
              - * Pipeline p = Pipeline.create(options);
              - * PCollection entities = p.apply(
              - *     DatastoreIO.v1().read()
              - *         .withProjectId(projectId)
              - *         .withQuery(query));
              - * } 
              - * - *

              Note: Normally, a Cloud Dataflow job will read from Cloud Datastore in parallel across - * many workers. However, when the {@link Query} is configured with a limit using - * {@link com.google.datastore.v1.Query.Builder#setLimit(Int32Value)}, then - * all returned results will be read by a single Dataflow worker in order to ensure correct data. - * - *

              To write a {@link PCollection} to a Cloud Datastore, use {@link DatastoreV1#write}, - * specifying the Cloud Datastore project to write to: - * - *

               {@code
              - * PCollection entities = ...;
              - * entities.apply(DatastoreIO.v1().write().withProjectId(projectId));
              - * p.run();
              - * } 
              - * - *

              To delete a {@link PCollection} of {@link Entity Entities} from Cloud Datastore, use - * {@link DatastoreV1#deleteEntity()}, specifying the Cloud Datastore project to write to: - * - *

               {@code
              - * PCollection entities = ...;
              - * entities.apply(DatastoreIO.v1().deleteEntity().withProjectId(projectId));
              - * p.run();
              - * } 
              - * - *

              To delete entities associated with a {@link PCollection} of {@link Key Keys} from Cloud - * Datastore, use {@link DatastoreV1#deleteKey}, specifying the Cloud Datastore project to write to: - * - *

               {@code
              - * PCollection entities = ...;
              - * entities.apply(DatastoreIO.v1().deleteKey().withProjectId(projectId));
              - * p.run();
              - * } 
              - * - *

              {@link Entity Entities} in the {@code PCollection} to be written or deleted must have complete - * {@link Key Keys}. Complete {@code Keys} specify the {@code name} and {@code id} of the - * {@code Entity}, where incomplete {@code Keys} do not. A {@code namespace} other than - * {@code projectId} default may be used by specifying it in the {@code Entity} {@code Keys}. - * - *

              {@code
              - * Key.Builder keyBuilder = DatastoreHelper.makeKey(...);
              - * keyBuilder.getPartitionIdBuilder().setNamespace(namespace);
              - * }
              - * - *

              {@code Entities} will be committed as upsert (update or insert) or delete mutations. Please - * read Entities, Properties, - * and Keys for more information about {@code Entity} keys. - * - *

              Permissions

              - * Permission requirements depend on the {@code PipelineRunner} that is used to execute the - * Dataflow job. Please refer to the documentation of corresponding {@code PipelineRunner}s for - * more details. - * - *

              Please see Cloud Datastore Sign Up - * for security and permission related information specific to Cloud Datastore. - * - * @see com.google.cloud.dataflow.sdk.runners.PipelineRunner - */ -@Experimental(Experimental.Kind.SOURCE_SINK) -public class DatastoreV1 { - - // A package-private constructor to prevent direct instantiation from outside of this package - DatastoreV1() {} - - /** - * Datastore has a limit of 500 mutations per batch operation, so we flush - * changes to Cloud Datastore every 500 entities. - */ - @VisibleForTesting - static final int DATASTORE_BATCH_UPDATE_LIMIT = 500; - - /** - * Returns an empty {@link DatastoreV1.Read} builder. Configure the source {@code projectId}, - * {@code query}, and optionally {@code namespace} and {@code numQuerySplits} using - * {@link DatastoreV1.Read#withProjectId}, {@link DatastoreV1.Read#withQuery}, - * {@link DatastoreV1.Read#withNamespace}, {@link DatastoreV1.Read#withNumQuerySplits}. - */ - public DatastoreV1.Read read() { - return new DatastoreV1.Read(null, null, null, 0); - } - - /** - * A {@link PTransform} that reads the result rows of a Cloud atastore query as {@code Entity} - * objects. - * - * @see DatastoreIO - */ - public static class Read extends PTransform> { - private static final Logger LOG = LoggerFactory.getLogger(Read.class); - - /** An upper bound on the number of splits for a query. */ - public static final int NUM_QUERY_SPLITS_MAX = 50000; - - /** A lower bound on the number of splits for a query. */ - static final int NUM_QUERY_SPLITS_MIN = 12; - - /** Default bundle size of 64MB. */ - static final long DEFAULT_BUNDLE_SIZE_BYTES = 64 * 1024 * 1024; - - /** - * Maximum number of results to request per query. - * - *

              Must be set, or it may result in an I/O error when querying Cloud Datastore. - */ - static final int QUERY_BATCH_LIMIT = 500; - - @Nullable - private final String projectId; - - @Nullable - private final Query query; - - @Nullable - private final String namespace; - - private final int numQuerySplits; - - /** - * Computes the number of splits to be performed on the given query by querying the estimated - * size from Cloud Datastore. - */ - static int getEstimatedNumSplits(Datastore datastore, Query query, @Nullable String namespace) { - int numSplits; - try { - long estimatedSizeBytes = getEstimatedSizeBytes(datastore, query, namespace); - LOG.info("Estimated size bytes for the query is: {}", estimatedSizeBytes); - numSplits = (int) Math.min(NUM_QUERY_SPLITS_MAX, - Math.round(((double) estimatedSizeBytes) / DEFAULT_BUNDLE_SIZE_BYTES)); - } catch (Exception e) { - LOG.warn("Failed the fetch estimatedSizeBytes for query: {}", query, e); - // Fallback in case estimated size is unavailable. - numSplits = NUM_QUERY_SPLITS_MIN; - } - return Math.max(numSplits, NUM_QUERY_SPLITS_MIN); - } - - /** - * Datastore system tables with statistics are periodically updated. This method fetches - * the latest timestamp (in microseconds) of statistics update using the {@code __Stat_Total__} - * table. - */ - private static long queryLatestStatisticsTimestamp(Datastore datastore, - @Nullable String namespace) throws DatastoreException { - Query.Builder query = Query.newBuilder(); - if (namespace == null) { - query.addKindBuilder().setName("__Stat_Total__"); - } else { - query.addKindBuilder().setName("__Stat_Ns_Total__"); - } - query.addOrder(makeOrder("timestamp", DESCENDING)); - query.setLimit(Int32Value.newBuilder().setValue(1)); - RunQueryRequest request = makeRequest(query.build(), namespace); - - RunQueryResponse response = datastore.runQuery(request); - QueryResultBatch batch = response.getBatch(); - if (batch.getEntityResultsCount() == 0) { - throw new NoSuchElementException( - "Datastore total statistics unavailable"); - } - Entity entity = batch.getEntityResults(0).getEntity(); - return entity.getProperties().get("timestamp").getTimestampValue().getSeconds() * 1000000; - } - - /** - * Get the estimated size of the data returned by the given query. - * - *

              Cloud Datastore provides no way to get a good estimate of how large the result of a query - * entity kind being queried, using the __Stat_Kind__ system table, assuming exactly 1 kind - * is specified in the query. - * - *

              See https://cloud.google.com/datastore/docs/concepts/stats. - */ - static long getEstimatedSizeBytes(Datastore datastore, Query query, @Nullable String namespace) - throws DatastoreException { - String ourKind = query.getKind(0).getName(); - long latestTimestamp = queryLatestStatisticsTimestamp(datastore, namespace); - LOG.info("Latest stats timestamp for kind {} is {}", ourKind, latestTimestamp); - - Query.Builder queryBuilder = Query.newBuilder(); - if (namespace == null) { - queryBuilder.addKindBuilder().setName("__Stat_Kind__"); - } else { - queryBuilder.addKindBuilder().setName("__Stat_Ns_Kind__"); - } - queryBuilder.setFilter(makeAndFilter( - makeFilter("kind_name", EQUAL, makeValue(ourKind).build()).build(), - makeFilter("timestamp", EQUAL, makeValue(latestTimestamp).build()).build())); - - RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); - - long now = System.currentTimeMillis(); - RunQueryResponse response = datastore.runQuery(request); - LOG.debug("Query for per-kind statistics took {}ms", System.currentTimeMillis() - now); - - QueryResultBatch batch = response.getBatch(); - if (batch.getEntityResultsCount() == 0) { - throw new NoSuchElementException( - "Cloud Datastore statistics for kind " + ourKind + " unavailable"); - } - Entity entity = batch.getEntityResults(0).getEntity(); - return entity.getProperties().get("entity_bytes").getIntegerValue(); - } - - /** Builds a {@link RunQueryRequest} from the {@code query} and {@code namespace}. */ - static RunQueryRequest makeRequest(Query query, @Nullable String namespace) { - RunQueryRequest.Builder requestBuilder = RunQueryRequest.newBuilder().setQuery(query); - if (namespace != null) { - requestBuilder.getPartitionIdBuilder().setNamespaceId(namespace); - } - return requestBuilder.build(); - } - - /** - * A helper function to get the split queries, taking into account the optional - * {@code namespace}. - */ - private static List splitQuery(Query query, @Nullable String namespace, - Datastore datastore, QuerySplitter querySplitter, int numSplits) throws DatastoreException { - // If namespace is set, include it in the split request so splits are calculated accordingly. - PartitionId.Builder partitionBuilder = PartitionId.newBuilder(); - if (namespace != null) { - partitionBuilder.setNamespaceId(namespace); - } - - return querySplitter.getSplits(query, partitionBuilder.build(), numSplits, datastore); - } - - /** - * Note that only {@code namespace} is really {@code @Nullable}. The other parameters may be - * {@code null} as a matter of build order, but if they are {@code null} at instantiation time, - * an error will be thrown. - */ - private Read(@Nullable String projectId, @Nullable Query query, @Nullable String namespace, - int numQuerySplits) { - this.projectId = projectId; - this.query = query; - this.namespace = namespace; - this.numQuerySplits = numQuerySplits; - } - - /** - * Returns a new {@link DatastoreV1.Read} that reads from the Cloud Datastore for the specified - * project. - */ - public DatastoreV1.Read withProjectId(String projectId) { - checkNotNull(projectId, "projectId"); - return new DatastoreV1.Read(projectId, query, namespace, numQuerySplits); - } - - /** - * Returns a new {@link DatastoreV1.Read} that reads the results of the specified query. - * - *

              Note: Normally, {@code DatastoreIO} will read from Cloud Datastore in parallel - * across many workers. However, when the {@link Query} is configured with a limit using - * {@link Query.Builder#setLimit}, then all results will be read by a single worker in order - * to ensure correct results. - */ - public DatastoreV1.Read withQuery(Query query) { - checkNotNull(query, "query"); - checkArgument(!query.hasLimit() || query.getLimit().getValue() > 0, - "Invalid query limit %s: must be positive", query.getLimit().getValue()); - return new DatastoreV1.Read(projectId, query, namespace, numQuerySplits); - } - - /** - * Returns a new {@link DatastoreV1.Read} that reads from the given namespace. - */ - public DatastoreV1.Read withNamespace(String namespace) { - return new DatastoreV1.Read(projectId, query, namespace, numQuerySplits); - } - - /** - * Returns a new {@link DatastoreV1.Read} that reads by splitting the given {@code query} into - * {@code numQuerySplits}. - * - *

              The semantics for the query splitting is defined below: - *

                - *
              • Any value less than or equal to 0 will be ignored, and the number of splits will be - * chosen dynamically at runtime based on the query data size. - *
              • Any value greater than {@link Read#NUM_QUERY_SPLITS_MAX} will be capped at - * {@code NUM_QUERY_SPLITS_MAX}. - *
              • If the {@code query} has a user limit set, then {@code numQuerySplits} will be - * ignored and no split will be performed. - *
              • Under certain cases Cloud Datastore is unable to split query to the requested number of - * splits. In such cases we just use whatever the Datastore returns. - *
              - */ - public DatastoreV1.Read withNumQuerySplits(int numQuerySplits) { - return new DatastoreV1.Read(projectId, query, namespace, - Math.min(Math.max(numQuerySplits, 0), NUM_QUERY_SPLITS_MAX)); - } - - @Nullable - public Query getQuery() { - return query; - } - - @Nullable - public String getProjectId() { - return projectId; - } - - @Nullable - public String getNamespace() { - return namespace; - } - - - /** - * {@inheritDoc} - */ - @Override - public PCollection apply(PBegin input) { - V1Options v1Options = V1Options.from(getProjectId(), getQuery(), - getNamespace()); - - /* - * This composite transform involves the following steps: - * 1. Create a singleton of the user provided {@code query} and apply a {@link ParDo} that - * splits the query into {@code numQuerySplits} and assign each split query a unique - * {@code Integer} as the key. The resulting output is of the type - * {@code PCollection>}. - * - * If the value of {@code numQuerySplits} is less than or equal to 0, then the number of - * splits will be computed dynamically based on the size of the data for the {@code query}. - * - * 2. The resulting {@code PCollection} is sharded using a {@link GroupByKey} operation. The - * queries are extracted from they {@code KV>} and flattened to - * output a {@code PCollection}. - * - * 3. In the third step, a {@code ParDo} reads entities for each query and outputs - * a {@code PCollection}. - */ - PCollection> queries = input - .apply(Create.of(query)) - .apply(ParDo.of(new SplitQueryFn(v1Options, numQuerySplits))); - - PCollection shardedQueries = queries - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(Flatten.iterables()); - - PCollection entities = shardedQueries - .apply(ParDo.of(new ReadFn(v1Options))); - - return entities; - } - - @Override - public void validate(PBegin input) { - checkNotNull(projectId, "projectId"); - checkNotNull(query, "query"); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("projectId", projectId) - .withLabel("ProjectId")) - .addIfNotNull(DisplayData.item("namespace", namespace) - .withLabel("Namespace")) - .addIfNotNull(DisplayData.item("query", query.toString()) - .withLabel("Query")); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("projectId", projectId) - .add("query", query) - .add("namespace", namespace) - .toString(); - } - - /** - * A class for v1 Cloud Datastore related options. - */ - @VisibleForTesting - static class V1Options implements Serializable { - private final Query query; - private final String projectId; - @Nullable - private final String namespace; - - private V1Options(String projectId, Query query, @Nullable String namespace) { - this.projectId = checkNotNull(projectId, "projectId"); - this.query = checkNotNull(query, "query"); - this.namespace = namespace; - } - - public static V1Options from(String projectId, Query query, @Nullable String namespace) { - return new V1Options(projectId, query, namespace); - } - - public Query getQuery() { - return query; - } - - public String getProjectId() { - return projectId; - } - - @Nullable - public String getNamespace() { - return namespace; - } - } - - /** - * A {@link DoFn} that splits a given query into multiple sub-queries, assigns them unique keys - * and outputs them as {@link KV}. - */ - @VisibleForTesting - static class SplitQueryFn extends DoFn> { - private final V1Options options; - // number of splits to make for a given query - private final int numSplits; - - private final V1DatastoreFactory datastoreFactory; - // Datastore client - private transient Datastore datastore; - // Query splitter - private transient QuerySplitter querySplitter; - - public SplitQueryFn(V1Options options, int numSplits) { - this(options, numSplits, new V1DatastoreFactory()); - } - - @VisibleForTesting - SplitQueryFn(V1Options options, int numSplits, - V1DatastoreFactory datastoreFactory) { - this.options = options; - this.numSplits = numSplits; - this.datastoreFactory = datastoreFactory; - } - - @Override - public void startBundle(Context c) throws Exception { - datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), options.projectId); - querySplitter = datastoreFactory.getQuerySplitter(); - } - - @Override - public void processElement(ProcessContext c) throws Exception { - int key = 1; - Query query = c.element(); - - // If query has a user set limit, then do not split. - if (query.hasLimit()) { - c.output(KV.of(key, query)); - return; - } - - int estimatedNumSplits; - // Compute the estimated numSplits if numSplits is not specified by the user. - if (numSplits <= 0) { - estimatedNumSplits = getEstimatedNumSplits(datastore, query, options.getNamespace()); - } else { - estimatedNumSplits = numSplits; - } - - LOG.info("Splitting the query into {} splits", estimatedNumSplits); - List querySplits; - try { - querySplits = splitQuery(query, options.getNamespace(), datastore, querySplitter, - estimatedNumSplits); - } catch (Exception e) { - LOG.warn("Unable to parallelize the given query: {}", query, e); - querySplits = ImmutableList.of(query); - } - - // assign unique keys to query splits. - for (Query subquery : querySplits) { - c.output(KV.of(key++, subquery)); - } - } - - @Override - public void populateDisplayData(Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("projectId", options.getProjectId()) - .withLabel("ProjectId")) - .addIfNotNull(DisplayData.item("namespace", options.getNamespace()) - .withLabel("Namespace")) - .addIfNotNull(DisplayData.item("query", options.getQuery().toString()) - .withLabel("Query")); - } - } - - /** - * A {@link DoFn} that reads entities from Cloud Datastore for each query. - */ - @VisibleForTesting - static class ReadFn extends DoFn { - private final V1Options options; - private final V1DatastoreFactory datastoreFactory; - // Datastore client - private transient Datastore datastore; - - public ReadFn(V1Options options) { - this(options, new V1DatastoreFactory()); - } - - @VisibleForTesting - ReadFn(V1Options options, V1DatastoreFactory datastoreFactory) { - this.options = options; - this.datastoreFactory = datastoreFactory; - } - - @Override - public void startBundle(Context c) throws Exception { - datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), options.getProjectId()); - } - - /** Read and output entities for the given query. */ - @Override - public void processElement(ProcessContext context) throws Exception { - Query query = context.element(); - String namespace = options.getNamespace(); - int userLimit = query.hasLimit() - ? query.getLimit().getValue() : Integer.MAX_VALUE; - - boolean moreResults = true; - QueryResultBatch currentBatch = null; - - while (moreResults) { - Query.Builder queryBuilder = query.toBuilder().clone(); - queryBuilder.setLimit(Int32Value.newBuilder().setValue( - Math.min(userLimit, QUERY_BATCH_LIMIT))); - - if (currentBatch != null && !currentBatch.getEndCursor().isEmpty()) { - queryBuilder.setStartCursor(currentBatch.getEndCursor()); - } - - RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); - RunQueryResponse response = datastore.runQuery(request); - - currentBatch = response.getBatch(); - - // MORE_RESULTS_AFTER_LIMIT is not implemented yet: - // https://groups.google.com/forum/#!topic/gcd-discuss/iNs6M1jA2Vw, so - // use result count to determine if more results might exist. - int numFetch = currentBatch.getEntityResultsCount(); - if (query.hasLimit()) { - verify(userLimit >= numFetch, - "Expected userLimit %s >= numFetch %s, because query limit %s must be <= userLimit", - userLimit, numFetch, query.getLimit()); - userLimit -= numFetch; - } - - // output all the entities from the current batch. - for (EntityResult entityResult : currentBatch.getEntityResultsList()) { - context.output(entityResult.getEntity()); - } - - // Check if we have more entities to be read. - moreResults = - // User-limit does not exist (so userLimit == MAX_VALUE) and/or has not been satisfied - (userLimit > 0) - // All indications from the API are that there are/may be more results. - && ((numFetch == QUERY_BATCH_LIMIT) - || (currentBatch.getMoreResults() == NOT_FINISHED)); - } - } - } - } - - /** - * Returns an empty {@link DatastoreV1.Write} builder. Configure the destination - * {@code projectId} using {@link DatastoreV1.Write#withProjectId}. - */ - public Write write() { - return new Write(null); - } - - /** - * Returns an empty {@link DeleteEntity} builder. Configure the destination - * {@code projectId} using {@link DeleteEntity#withProjectId}. - */ - public DeleteEntity deleteEntity() { - return new DeleteEntity(null); - } - - /** - * Returns an empty {@link DeleteKey} builder. Configure the destination - * {@code projectId} using {@link DeleteKey#withProjectId}. - */ - public DeleteKey deleteKey() { - return new DeleteKey(null); - } - - /** - * A {@link PTransform} that writes {@link Entity} objects to Cloud Datastore. - * - * @see DatastoreIO - */ - public static class Write extends Mutate { - /** - * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if - * it is {@code null} at instantiation time, an error will be thrown. - */ - Write(@Nullable String projectId) { - super(projectId, new UpsertFn()); - } - - /** - * Returns a new {@link Write} that writes to the Cloud Datastore for the specified project. - */ - public Write withProjectId(String projectId) { - checkNotNull(projectId, "projectId"); - return new Write(projectId); - } - } - - /** - * A {@link PTransform} that deletes {@link Entity Entities} from Cloud Datastore. - * - * @see DatastoreIO - */ - public static class DeleteEntity extends Mutate { - /** - * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if - * it is {@code null} at instantiation time, an error will be thrown. - */ - DeleteEntity(@Nullable String projectId) { - super(projectId, new DeleteEntityFn()); - } - - /** - * Returns a new {@link DeleteEntity} that deletes entities from the Cloud Datastore for the - * specified project. - */ - public DeleteEntity withProjectId(String projectId) { - checkNotNull(projectId, "projectId"); - return new DeleteEntity(projectId); - } - } - - /** - * A {@link PTransform} that deletes {@link Entity Entities} associated with the given - * {@link Key Keys} from Cloud Datastore. - * - * @see DatastoreIO - */ - public static class DeleteKey extends Mutate { - /** - * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if - * it is {@code null} at instantiation time, an error will be thrown. - */ - DeleteKey(@Nullable String projectId) { - super(projectId, new DeleteKeyFn()); - } - - /** - * Returns a new {@link DeleteKey} that deletes entities from the Cloud Datastore for the - * specified project. - */ - public DeleteKey withProjectId(String projectId) { - checkNotNull(projectId, "projectId"); - return new DeleteKey(projectId); - } - } - - /** - * A {@link PTransform} that writes mutations to Cloud Datastore. - * - *

              It requires a {@link DoFn} that tranforms an object of type {@code T} to a {@link Mutation}. - * {@code T} is usually either an {@link Entity} or a {@link Key} - * Note: Only idempotent Cloud Datastore mutation operations (upsert and delete) should - * be used by the {@code DoFn} provided, as the commits are retried when failures occur. - */ - private abstract static class Mutate extends PTransform, PDone> { - @Nullable - private final String projectId; - /** A function that transforms each {@code T} into a mutation. */ - private final SimpleFunction mutationFn; - - /** - * Note that {@code projectId} is only {@code @Nullable} as a matter of build order, but if - * it is {@code null} at instantiation time, an error will be thrown. - */ - Mutate(@Nullable String projectId, SimpleFunction mutationFn) { - this.projectId = projectId; - this.mutationFn = checkNotNull(mutationFn); - } - - @Override - public PDone apply(PCollection input) { - input.apply("Convert to Mutation", MapElements.via(mutationFn)) - .apply("Write Mutation to Datastore", ParDo.of(new DatastoreWriterFn(projectId))); - - return PDone.in(input.getPipeline()); - } - - @Override - public void validate(PCollection input) { - checkNotNull(projectId, "projectId"); - checkNotNull(mutationFn, "mutationFn"); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("projectId", projectId) - .add("mutationFn", mutationFn.getClass().getName()) - .toString(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("projectId", projectId) - .withLabel("Output Project")) - .add(DisplayData.item("mutationFn", mutationFn.getClass()) - .withLabel("Datastore Mutation Function")); - } - - public String getProjectId() { - return projectId; - } - } - - /** - * {@link DoFn} that writes {@link Mutation}s to Cloud Datastore. Mutations are written in - * batches, where the maximum batch size is {@link DatastoreV1#DATASTORE_BATCH_UPDATE_LIMIT}. - * - *

              See - * Datastore: Entities, Properties, and Keys for information about entity keys and mutations. - * - *

              Commits are non-transactional. If a commit fails because of a conflict over an entity - * group, the commit will be retried (up to {@link DatastoreV1#DATASTORE_BATCH_UPDATE_LIMIT} - * times). This means that the mutation operation should be idempotent. Thus, the writer should - * only be used for {code upsert} and {@code delete} mutation operations, as these are the only - * two Cloud Datastore mutations that are idempotent. - */ - @VisibleForTesting - static class DatastoreWriterFn extends DoFn { - private static final Logger LOG = LoggerFactory.getLogger(DatastoreWriterFn.class); - private final String projectId; - private transient Datastore datastore; - private final V1DatastoreFactory datastoreFactory; - // Current batch of mutations to be written. - private final List mutations = new ArrayList<>(); - - private static final int MAX_RETRIES = 5; - private static final FluentBackoff BUNDLE_WRITE_BACKOFF = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RETRIES).withInitialBackoff(Duration.standardSeconds(5)); - - DatastoreWriterFn(String projectId) { - this(projectId, new V1DatastoreFactory()); - } - - @VisibleForTesting - DatastoreWriterFn(String projectId, V1DatastoreFactory datastoreFactory) { - this.projectId = checkNotNull(projectId, "projectId"); - this.datastoreFactory = datastoreFactory; - } - - @Override - public void startBundle(Context c) { - datastore = datastoreFactory.getDatastore(c.getPipelineOptions(), projectId); - } - - @Override - public void processElement(ProcessContext c) throws Exception { - mutations.add(c.element()); - if (mutations.size() >= DatastoreV1.DATASTORE_BATCH_UPDATE_LIMIT) { - flushBatch(); - } - } - - @Override - public void finishBundle(Context c) throws Exception { - if (!mutations.isEmpty()) { - flushBatch(); - } - } - - /** - * Writes a batch of mutations to Cloud Datastore. - * - *

              If a commit fails, it will be retried up to {@link #MAX_RETRIES} times. All - * mutations in the batch will be committed again, even if the commit was partially - * successful. If the retry limit is exceeded, the last exception from Cloud Datastore will be - * thrown. - * - * @throws DatastoreException if the commit fails or IOException or InterruptedException if - * backing off between retries fails. - */ - private void flushBatch() throws DatastoreException, IOException, InterruptedException { - LOG.debug("Writing batch of {} mutations", mutations.size()); - Sleeper sleeper = Sleeper.DEFAULT; - BackOff backoff = BUNDLE_WRITE_BACKOFF.backoff(); - - while (true) { - // Batch upsert entities. - try { - CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); - commitRequest.addAllMutations(mutations); - commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); - datastore.commit(commitRequest.build()); - // Break if the commit threw no exception. - break; - } catch (DatastoreException exception) { - // Only log the code and message for potentially-transient errors. The entire exception - // will be propagated upon the last retry. - LOG.error("Error writing to the Datastore ({}): {}", exception.getCode(), - exception.getMessage()); - if (!BackOffUtils.next(sleeper, backoff)) { - LOG.error("Aborting after {} retries.", MAX_RETRIES); - throw exception; - } - } - } - LOG.debug("Successfully wrote {} mutations", mutations.size()); - mutations.clear(); - } - - @Override - public void populateDisplayData(Builder builder) { - super.populateDisplayData(builder); - builder - .addIfNotNull(DisplayData.item("projectId", projectId) - .withLabel("Output Project")); - } - } - - /** - * Returns true if a Cloud Datastore key is complete. A key is complete if its last element - * has either an id or a name. - */ - static boolean isValidKey(Key key) { - List elementList = key.getPathList(); - if (elementList.isEmpty()) { - return false; - } - PathElement lastElement = elementList.get(elementList.size() - 1); - return (lastElement.getId() != 0 || !lastElement.getName().isEmpty()); - } - - /** - * A function that constructs an upsert {@link Mutation} from an {@link Entity}. - */ - @VisibleForTesting - static class UpsertFn extends SimpleFunction { - @Override - public Mutation apply(Entity entity) { - // Verify that the entity to write has a complete key. - checkArgument(isValidKey(entity.getKey()), - "Entities to be written to the Cloud Datastore must have complete keys:\n%s", entity); - - return makeUpsert(entity).build(); - } - } - - /** - * A function that constructs a delete {@link Mutation} from an {@link Entity}. - */ - @VisibleForTesting - static class DeleteEntityFn extends SimpleFunction { - @Override - public Mutation apply(Entity entity) { - // Verify that the entity to delete has a complete key. - checkArgument(isValidKey(entity.getKey()), - "Entities to be deleted from the Cloud Datastore must have complete keys:\n%s", entity); - - return makeDelete(entity.getKey()).build(); - } - } - - /** - * A function that constructs a delete {@link Mutation} from a {@link Key}. - */ - @VisibleForTesting - static class DeleteKeyFn extends SimpleFunction { - @Override - public Mutation apply(Key key) { - // Verify that the entity to delete has a complete key. - checkArgument(isValidKey(key), - "Keys to be deleted from the Cloud Datastore must be complete:\n%s", key); - - return makeDelete(key).build(); - } - } - - /** - * A wrapper factory class for Cloud Datastore singleton classes {@link DatastoreFactory} and - * {@link QuerySplitter} - * - *

              {@link DatastoreFactory} and {@link QuerySplitter} are not java serializable, hence - * wrapping them under this class, which implements {@link Serializable}. - */ - @VisibleForTesting - static class V1DatastoreFactory implements Serializable { - - /** Builds a Cloud Datastore client for the given pipeline options and project. */ - public Datastore getDatastore(PipelineOptions pipelineOptions, String projectId) { - DatastoreOptions.Builder builder = - new DatastoreOptions.Builder() - .projectId(projectId) - .initializer( - new RetryHttpRequestInitializer() - ); - - Credential credential = pipelineOptions.as(GcpOptions.class).getGcpCredential(); - if (credential != null) { - builder.credential(credential); - } - - return DatastoreFactory.get().create(builder.build()); - } - - /** Builds a Cloud Datastore {@link QuerySplitter}. */ - public QuerySplitter getQuerySplitter() { - return DatastoreHelper.getQuerySplitter(); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java deleted file mode 100644 index d6eb213145..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/datastore/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - *

              Provides an API for reading from and writing to - * Google Cloud Datastore over different - * versions of the Cloud Datastore Client libraries. - */ -package com.google.cloud.dataflow.sdk.io.datastore; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/package-info.java deleted file mode 100644 index de0bd86094..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/package-info.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines transforms for reading and writing common storage formats, including - * {@link com.google.cloud.dataflow.sdk.io.AvroIO}, - * {@link com.google.cloud.dataflow.sdk.io.BigQueryIO}, and - * {@link com.google.cloud.dataflow.sdk.io.TextIO}. - * - *

              The classes in this package provide {@code Read} transforms that create PCollections - * from existing storage: - *

              {@code
              - * PCollection inputData = pipeline.apply(
              - *     BigQueryIO.Read.named("Read")
              - *                    .from("clouddataflow-readonly:samples.weather_stations");
              - * }
              - * and {@code Write} transforms that persist PCollections to external storage: - *
               {@code
              - * PCollection numbers = ...;
              - * numbers.apply(TextIO.Write.named("WriteNumbers")
              - *                           .to("gs://my_bucket/path/to/numbers"));
              - * } 
              - */ -package com.google.cloud.dataflow.sdk.io; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java deleted file mode 100644 index 30772da793..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.protobuf.ByteString; -import com.google.protobuf.ByteString.ByteIterator; - -import java.io.Serializable; - -/** - * A class representing a key consisting of an array of bytes. Arbitrary-length - * {@code byte[]} keys are typical in key-value stores such as Google Cloud Bigtable. - * - *

              Instances of {@link ByteKey} are immutable. - * - *

              {@link ByteKey} implements {@link Comparable Comparable<ByteKey>} by comparing the - * arrays in lexicographic order. The smallest {@link ByteKey} is a zero-length array; the successor - * to a key is the same key with an additional 0 byte appended; and keys have unbounded size. - * - *

              Note that the empty {@link ByteKey} compares smaller than all other keys, but some systems - * have the semantic that when an empty {@link ByteKey} is used as an upper bound, it represents - * the largest possible key. In these cases, implementors should use {@link #isEmpty} to test - * whether an upper bound key is empty. - */ -public final class ByteKey implements Comparable, Serializable { - /** An empty key. */ - public static final ByteKey EMPTY = ByteKey.of(); - - /** - * Creates a new {@link ByteKey} backed by the specified {@link ByteString}. - */ - public static ByteKey of(ByteString value) { - return new ByteKey(value); - } - - /** - * Creates a new {@link ByteKey} backed by a copy of the specified {@code byte[]}. - * - *

              Makes a copy of the underlying array. - */ - public static ByteKey copyFrom(byte[] bytes) { - return of(ByteString.copyFrom(bytes)); - } - - /** - * Creates a new {@link ByteKey} backed by a copy of the specified {@code int[]}. This method is - * primarily used as a convenience to create a {@link ByteKey} in code without casting down to - * signed Java {@link Byte bytes}: - * - *

              {@code
              -   * ByteKey key = ByteKey.of(0xde, 0xad, 0xbe, 0xef);
              -   * }
              - * - *

              Makes a copy of the input. - */ - public static ByteKey of(int... bytes) { - byte[] ret = new byte[bytes.length]; - for (int i = 0; i < bytes.length; ++i) { - ret[i] = (byte) (bytes[i] & 0xff); - } - return ByteKey.copyFrom(ret); - } - - /** - * Returns an immutable {@link ByteString} representing this {@link ByteKey}. - * - *

              Does not copy. - */ - public ByteString getValue() { - return value; - } - - /** - * Returns a newly-allocated {@code byte[]} representing this {@link ByteKey}. - * - *

              Copies the underlying {@code byte[]}. - */ - public byte[] getBytes() { - return value.toByteArray(); - } - - /** - * Returns {@code true} if the {@code byte[]} backing this {@link ByteKey} is of length 0. - */ - public boolean isEmpty() { - return value.isEmpty(); - } - - /** - * {@link ByteKey} implements {@link Comparable Comparable<ByteKey>} by comparing the - * arrays in lexicographic order. The smallest {@link ByteKey} is a zero-length array; the - * successor to a key is the same key with an additional 0 byte appended; and keys have unbounded - * size. - */ - @Override - public int compareTo(ByteKey other) { - checkNotNull(other, "other"); - ByteIterator thisIt = value.iterator(); - ByteIterator otherIt = other.value.iterator(); - while (thisIt.hasNext() && otherIt.hasNext()) { - // (byte & 0xff) converts [-128,127] bytes to [0,255] ints. - int cmp = (thisIt.nextByte() & 0xff) - (otherIt.nextByte() & 0xff); - if (cmp != 0) { - return cmp; - } - } - // If we get here, the prefix of both arrays is equal up to the shorter array. The array with - // more bytes is larger. - return value.size() - other.value.size(); - } - - //////////////////////////////////////////////////////////////////////////////////// - private final ByteString value; - - private ByteKey(ByteString value) { - this.value = value; - } - - /** Array used as a helper in {@link #toString}. */ - private static final char[] HEX = - new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - - // Prints the key as a string "[deadbeef]". - @Override - public String toString() { - char[] encoded = new char[2 * value.size() + 2]; - encoded[0] = '['; - int cnt = 1; - ByteIterator iterator = value.iterator(); - while (iterator.hasNext()) { - byte b = iterator.nextByte(); - encoded[cnt] = HEX[(b & 0xF0) >>> 4]; - ++cnt; - encoded[cnt] = HEX[b & 0xF]; - ++cnt; - } - encoded[cnt] = ']'; - return new String(encoded); - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof ByteKey)) { - return false; - } - ByteKey other = (ByteKey) o; - return (other.value.size() == value.size()) && this.compareTo(other) == 0; - } - - @Override - public int hashCode() { - return value.hashCode(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java deleted file mode 100644 index 6f58d393f9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRange.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Verify.verify; - -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -/** - * A class representing a range of {@link ByteKey ByteKeys}. - * - *

              Instances of {@link ByteKeyRange} are immutable. - * - *

              A {@link ByteKeyRange} enforces the restriction that its start and end keys must form a valid, - * non-empty range {@code [startKey, endKey)} that is inclusive of the start key and exclusive of - * the end key. - * - *

              When the end key is empty, it is treated as the largest possible key. - * - *

              Interpreting {@link ByteKey} in a {@link ByteKeyRange}

              - * - *

              The primary role of {@link ByteKeyRange} is to provide functionality for - * {@link #estimateFractionForKey(ByteKey)}, {@link #interpolateKey(double)}, and - * {@link #split(int)}, which are used for Google Cloud Dataflow's - * Autoscaling - * and Dynamic Work Rebalancing features. - * - *

              {@link ByteKeyRange} implements these features by treating a {@link ByteKey}'s underlying - * {@code byte[]} as the binary expansion of floating point numbers in the range {@code [0.0, 1.0]}. - * For example, the keys {@code ByteKey.of(0x80)}, {@code ByteKey.of(0xc0)}, and - * {@code ByteKey.of(0xe0)} are interpreted as {@code 0.5}, {@code 0.75}, and {@code 0.875} - * respectively. The empty {@code ByteKey.EMPTY} is interpreted as {@code 0.0} when used as the - * start of a range and {@code 1.0} when used as the end key. - * - *

              Key interpolation, fraction estimation, and range splitting are all interpreted in these - * floating-point semantics. See the respective implementations for further details. Note: - * the underlying implementations of these functions use {@link BigInteger} and {@link BigDecimal}, - * so they can be slow and should not be called in hot loops. Dataflow's dynamic work - * rebalancing will only invoke these functions during periodic control operations, so they are not - * called on the critical path. - * - * @see ByteKey - */ -public final class ByteKeyRange implements Serializable { - private static final Logger logger = LoggerFactory.getLogger(ByteKeyRange.class); - - /** The range of all keys, with empty start and end keys. */ - public static final ByteKeyRange ALL_KEYS = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.EMPTY); - - /** - * Creates a new {@link ByteKeyRange} with the given start and end keys. - * - *

              Note that if {@code endKey} is empty, it is treated as the largest possible key. - * - * @see ByteKeyRange - * - * @throws IllegalArgumentException if {@code endKey} is less than or equal to {@code startKey}, - * unless {@code endKey} is empty indicating the maximum possible {@link ByteKey}. - */ - public static ByteKeyRange of(ByteKey startKey, ByteKey endKey) { - return new ByteKeyRange(startKey, endKey); - } - - /** - * Returns the {@link ByteKey} representing the lower bound of this {@link ByteKeyRange}. - */ - public ByteKey getStartKey() { - return startKey; - } - - /** - * Returns the {@link ByteKey} representing the upper bound of this {@link ByteKeyRange}. - * - *

              Note that if {@code endKey} is empty, it is treated as the largest possible key. - */ - public ByteKey getEndKey() { - return endKey; - } - - /** - * Returns {@code true} if the specified {@link ByteKey} is contained within this range. - */ - public Boolean containsKey(ByteKey key) { - return key.compareTo(startKey) >= 0 && endsAfterKey(key); - } - - /** - * Returns {@code true} if the specified {@link ByteKeyRange} overlaps this range. - */ - public Boolean overlaps(ByteKeyRange other) { - // If each range starts before the other range ends, then they must overlap. - // { [] } -- one range inside the other OR { [ } ] -- partial overlap. - return endsAfterKey(other.startKey) && other.endsAfterKey(startKey); - } - - /** - * Returns a list of up to {@code numSplits + 1} {@link ByteKey ByteKeys} in ascending order, - * where the keys have been interpolated to form roughly equal sub-ranges of this - * {@link ByteKeyRange}, assuming a uniform distribution of keys within this range. - * - *

              The first {@link ByteKey} in the result is guaranteed to be equal to {@link #getStartKey}, - * and the last {@link ByteKey} in the result is guaranteed to be equal to {@link #getEndKey}. - * Thus the resulting list exactly spans the same key range as this {@link ByteKeyRange}. - * - *

              Note that the number of keys returned is not always equal to {@code numSplits + 1}. - * Specifically, if this range is unsplittable (e.g., because the start and end keys are equal - * up to padding by zero bytes), the list returned will only contain the start and end key. - * - * @throws IllegalArgumentException if the specified number of splits is < 1 - * @see ByteKeyRange the ByteKeyRange class Javadoc for more information about split semantics. - */ - public List split(int numSplits) { - checkArgument(numSplits > 0, "numSplits %s must be a positive integer", numSplits); - - try { - ImmutableList.Builder ret = ImmutableList.builder(); - ret.add(startKey); - for (int i = 1; i < numSplits; ++i) { - ret.add(interpolateKey(i / (double) numSplits)); - } - ret.add(endKey); - return ret.build(); - } catch (IllegalStateException e) { - // The range is not splittable -- just return - return ImmutableList.of(startKey, endKey); - } - } - - /** - * Returns the fraction of this range {@code [startKey, endKey)} that is in the interval - * {@code [startKey, key)}. - * - * @throws IllegalArgumentException if {@code key} does not fall within this range - * @see ByteKeyRange the ByteKeyRange class Javadoc for more information about fraction semantics. - */ - public double estimateFractionForKey(ByteKey key) { - checkNotNull(key, "key"); - checkArgument(!key.isEmpty(), "Cannot compute fraction for an empty key"); - checkArgument( - key.compareTo(startKey) >= 0, "Expected key %s >= range start key %s", key, startKey); - - if (key.equals(endKey)) { - return 1.0; - } - checkArgument(containsKey(key), "Cannot compute fraction for %s outside this %s", key, this); - - byte[] startBytes = startKey.getBytes(); - byte[] endBytes = endKey.getBytes(); - byte[] keyBytes = key.getBytes(); - // If the endKey is unspecified, add a leading 1 byte to it and a leading 0 byte to all other - // keys, to get a concrete least upper bound for the desired range. - if (endKey.isEmpty()) { - startBytes = addHeadByte(startBytes, (byte) 0); - endBytes = addHeadByte(endBytes, (byte) 1); - keyBytes = addHeadByte(keyBytes, (byte) 0); - } - - // Pad to the longest of all 3 keys. - int paddedKeyLength = Math.max(Math.max(startBytes.length, endBytes.length), keyBytes.length); - BigInteger rangeStartInt = paddedPositiveInt(startBytes, paddedKeyLength); - BigInteger rangeEndInt = paddedPositiveInt(endBytes, paddedKeyLength); - BigInteger keyInt = paddedPositiveInt(keyBytes, paddedKeyLength); - - // Keys are equal subject to padding by 0. - BigInteger range = rangeEndInt.subtract(rangeStartInt); - if (range.equals(BigInteger.ZERO)) { - logger.warn( - "Using 0.0 as the default fraction for this near-empty range {} where start and end keys" - + " differ only by trailing zeros.", - this); - return 0.0; - } - - // Compute the progress (key-start)/(end-start) scaling by 2^64, dividing (which rounds), - // and then scaling down after the division. This gives ample precision when converted to - // double. - BigInteger progressScaled = keyInt.subtract(rangeStartInt).shiftLeft(64); - return progressScaled.divide(range).doubleValue() / Math.pow(2, 64); - } - - /** - * Returns a {@link ByteKey} {@code key} such that {@code [startKey, key)} represents - * approximately the specified fraction of the range {@code [startKey, endKey)}. The interpolation - * is computed assuming a uniform distribution of keys. - * - *

              For example, given the largest possible range (defined by empty start and end keys), the - * fraction {@code 0.5} will return the {@code ByteKey.of(0x80)}, which will also be returned for - * ranges {@code [0x40, 0xc0)} and {@code [0x6f, 0x91)}. - * - *

              The key returned will never be empty. - * - * @throws IllegalArgumentException if {@code fraction} is outside the range [0, 1) - * @throws IllegalStateException if this range cannot be interpolated - * @see ByteKeyRange the ByteKeyRange class Javadoc for more information about fraction semantics. - */ - public ByteKey interpolateKey(double fraction) { - checkArgument( - fraction >= 0.0 && fraction < 1.0, "Fraction %s must be in the range [0, 1)", fraction); - byte[] startBytes = startKey.getBytes(); - byte[] endBytes = endKey.getBytes(); - // If the endKey is unspecified, add a leading 1 byte to it and a leading 0 byte to all other - // keys, to get a concrete least upper bound for the desired range. - if (endKey.isEmpty()) { - startBytes = addHeadByte(startBytes, (byte) 0); - endBytes = addHeadByte(endBytes, (byte) 1); - } - - // Pad to the longest key. - int paddedKeyLength = Math.max(startBytes.length, endBytes.length); - BigInteger rangeStartInt = paddedPositiveInt(startBytes, paddedKeyLength); - BigInteger rangeEndInt = paddedPositiveInt(endBytes, paddedKeyLength); - - // If the keys are equal subject to padding by 0, we can't interpolate. - BigInteger range = rangeEndInt.subtract(rangeStartInt); - checkState( - !range.equals(BigInteger.ZERO), - "Refusing to interpolate for near-empty %s where start and end keys differ only by trailing" - + " zero bytes.", - this); - - // Add precision so that range is at least 53 (double mantissa length) bits long. This way, we - // can interpolate small ranges finely, e.g., split the range key 3 to key 4 into 1024 parts. - // We add precision to range by adding zero bytes to the end of the keys, aka shifting the - // underlying BigInteger left by a multiple of 8 bits. - int bytesNeeded = ((53 - range.bitLength()) + 7) / 8; - if (bytesNeeded > 0) { - range = range.shiftLeft(bytesNeeded * 8); - rangeStartInt = rangeStartInt.shiftLeft(bytesNeeded * 8); - paddedKeyLength += bytesNeeded; - } - - BigInteger interpolatedOffset = - new BigDecimal(range).multiply(BigDecimal.valueOf(fraction)).toBigInteger(); - - int outputKeyLength = endKey.isEmpty() ? (paddedKeyLength - 1) : paddedKeyLength; - return ByteKey.copyFrom( - fixupHeadZeros(rangeStartInt.add(interpolatedOffset).toByteArray(), outputKeyLength)); - } - - /** - * Returns new {@link ByteKeyRange} like this one, but with the specified start key. - */ - public ByteKeyRange withStartKey(ByteKey startKey) { - return new ByteKeyRange(startKey, endKey); - } - - /** - * Returns new {@link ByteKeyRange} like this one, but with the specified end key. - */ - public ByteKeyRange withEndKey(ByteKey endKey) { - return new ByteKeyRange(startKey, endKey); - } - - //////////////////////////////////////////////////////////////////////////////////// - private final ByteKey startKey; - private final ByteKey endKey; - - private ByteKeyRange(ByteKey startKey, ByteKey endKey) { - this.startKey = checkNotNull(startKey, "startKey"); - this.endKey = checkNotNull(endKey, "endKey"); - checkArgument(endsAfterKey(startKey), "Start %s must be less than end %s", startKey, endKey); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(ByteKeyRange.class) - .add("startKey", startKey) - .add("endKey", endKey) - .toString(); - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof ByteKeyRange)) { - return false; - } - ByteKeyRange other = (ByteKeyRange) o; - return Objects.equals(startKey, other.startKey) && Objects.equals(endKey, other.endKey); - } - - @Override - public int hashCode() { - return Objects.hash(startKey, endKey); - } - - /** - * Returns a copy of the specified array with the specified byte added at the front. - */ - private static byte[] addHeadByte(byte[] array, byte b) { - byte[] ret = new byte[array.length + 1]; - ret[0] = b; - System.arraycopy(array, 0, ret, 1, array.length); - return ret; - } - - /** - * Ensures the array is exactly {@code size} bytes long. Returns the input array if the condition - * is met, otherwise either adds or removes zero bytes from the beginning of {@code array}. - */ - private static byte[] fixupHeadZeros(byte[] array, int size) { - int padding = size - array.length; - if (padding == 0) { - return array; - } - - if (padding < 0) { - // There is one zero byte at the beginning, added by BigInteger to make there be a sign - // bit when converting to bytes. - verify( - padding == -1, - "key %s: expected length %d with exactly one byte of padding, found %d", - ByteKey.copyFrom(array), - size, - -padding); - verify( - (array[0] == 0) && ((array[1] & 0x80) == 0x80), - "key %s: is 1 byte longer than expected, indicating BigInteger padding. Expect first byte" - + " to be zero with set MSB in second byte.", - ByteKey.copyFrom(array)); - return Arrays.copyOfRange(array, 1, array.length); - } - - byte[] ret = new byte[size]; - System.arraycopy(array, 0, ret, padding, array.length); - return ret; - } - - /** - * Returns {@code true} when the specified {@code key} is smaller this range's end key. The only - * semantic change from {@code (key.compareTo(getEndKey()) < 0)} is that the empty end key is - * treated as larger than all possible {@link ByteKey keys}. - */ - boolean endsAfterKey(ByteKey key) { - return endKey.isEmpty() || key.compareTo(endKey) < 0; - } - - /** Builds a BigInteger out of the specified array, padded to the desired byte length. */ - private static BigInteger paddedPositiveInt(byte[] bytes, int length) { - int bytePaddingNeeded = length - bytes.length; - checkArgument( - bytePaddingNeeded >= 0, "Required bytes.length {} < length {}", bytes.length, length); - BigInteger ret = new BigInteger(1, bytes); - return (bytePaddingNeeded == 0) ? ret : ret.shiftLeft(8 * bytePaddingNeeded); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java deleted file mode 100644 index 5f3ea71314..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTracker.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static com.google.common.base.MoreObjects.toStringHelper; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.Nullable; - -/** - * A {@link RangeTracker} for {@link ByteKey ByteKeys} in {@link ByteKeyRange ByteKeyRanges}. - * - * @see ByteKey - * @see ByteKeyRange - */ -public final class ByteKeyRangeTracker implements RangeTracker { - private static final Logger logger = LoggerFactory.getLogger(ByteKeyRangeTracker.class); - - /** Instantiates a new {@link ByteKeyRangeTracker} with the specified range. */ - public static ByteKeyRangeTracker of(ByteKeyRange range) { - return new ByteKeyRangeTracker(range); - } - - public synchronized boolean isDone() { - return done; - } - - @Override - public synchronized ByteKey getStartPosition() { - return range.getStartKey(); - } - - @Override - public synchronized ByteKey getStopPosition() { - return range.getEndKey(); - } - - /** Returns the current range. */ - public synchronized ByteKeyRange getRange() { - return range; - } - - @Override - public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, ByteKey recordStart) { - if (done) { - return false; - } - - checkState(!(position == null && !isAtSplitPoint), "The first record must be at a split point"); - checkState(!(recordStart.compareTo(range.getStartKey()) < 0), - "Trying to return record which is before the start key"); - checkState(!(position != null && recordStart.compareTo(position) < 0), - "Trying to return record which is before the last-returned record"); - - if (position == null) { - range = range.withStartKey(recordStart); - } - position = recordStart; - - if (isAtSplitPoint) { - if (!range.containsKey(recordStart)) { - done = true; - return false; - } - ++splitPointsSeen; - } - return true; - } - - @Override - public synchronized boolean trySplitAtPosition(ByteKey splitPosition) { - // Unstarted. - if (position == null) { - logger.warn( - "{}: Rejecting split request at {} because no records have been returned.", - this, - splitPosition); - return false; - } - - // Started, but not after current position. - if (splitPosition.compareTo(position) <= 0) { - logger.warn( - "{}: Rejecting split request at {} because it is not after current position {}.", - this, - splitPosition, - position); - return false; - } - - // Sanity check. - if (!range.containsKey(splitPosition)) { - logger.warn( - "{}: Rejecting split request at {} because it is not within the range.", - this, - splitPosition); - return false; - } - - range = range.withEndKey(splitPosition); - return true; - } - - @Override - public synchronized double getFractionConsumed() { - if (position == null) { - return 0; - } - return range.estimateFractionForKey(position); - } - - public synchronized long getSplitPointsConsumed() { - if (position == null) { - return 0; - } else if (isDone()) { - return splitPointsSeen; - } else { - // There is a current split point, and it has not finished processing. - checkState( - splitPointsSeen > 0, - "A started rangeTracker should have seen > 0 split points (is %s)", - splitPointsSeen); - return splitPointsSeen - 1; - } - } - - /////////////////////////////////////////////////////////////////////////////// - private ByteKeyRange range; - @Nullable private ByteKey position; - private long splitPointsSeen; - private boolean done; - - private ByteKeyRangeTracker(ByteKeyRange range) { - this.range = range; - position = null; - splitPointsSeen = 0L; - done = false; - } - - /** - * Marks this range tracker as being done. Specifically, this will mark the current split point, - * if one exists, as being finished. - * - *

              Always returns false, so that it can be used in an implementation of - * {@link BoundedReader#start()} or {@link BoundedReader#advance()} as follows: - * - *

               {@code
              -   * public boolean start() {
              -   *   return startImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint, position)
              -   *       || rangeTracker.markDone();
              -   * }} 
              - */ - public synchronized boolean markDone() { - done = true; - return false; - } - - @Override - public synchronized String toString() { - return toStringHelper(ByteKeyRangeTracker.class) - .add("range", range) - .add("position", position) - .toString(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java deleted file mode 100644 index 71ba908ff1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTracker.java +++ /dev/null @@ -1,270 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; - -import com.google.common.annotations.VisibleForTesting; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A {@link RangeTracker} for non-negative positions of type {@code long}. - */ -public class OffsetRangeTracker implements RangeTracker { - private static final Logger LOG = LoggerFactory.getLogger(OffsetRangeTracker.class); - - private long startOffset; - private long stopOffset; - private long lastRecordStart = -1L; - private long offsetOfLastSplitPoint = -1L; - private long splitPointsSeen = 0L; - private boolean done = false; - - /** - * Offset corresponding to infinity. This can only be used as the upper-bound of a range, and - * indicates reading all of the records until the end without specifying exactly what the end is. - * - *

              Infinite ranges cannot be split because it is impossible to estimate progress within them. - */ - public static final long OFFSET_INFINITY = Long.MAX_VALUE; - - /** - * Creates an {@code OffsetRangeTracker} for the specified range. - */ - public OffsetRangeTracker(long startOffset, long stopOffset) { - this.startOffset = startOffset; - this.stopOffset = stopOffset; - } - - public synchronized boolean isStarted() { - // done => started: handles the case when the reader was empty. - return (offsetOfLastSplitPoint != -1) || done; - } - - public synchronized boolean isDone() { - return done; - } - - @Override - public synchronized Long getStartPosition() { - return startOffset; - } - - @Override - public synchronized Long getStopPosition() { - return stopOffset; - } - - @Override - public boolean tryReturnRecordAt(boolean isAtSplitPoint, Long recordStart) { - return tryReturnRecordAt(isAtSplitPoint, recordStart.longValue()); - } - - public synchronized boolean tryReturnRecordAt(boolean isAtSplitPoint, long recordStart) { - if (!isStarted() && !isAtSplitPoint) { - throw new IllegalStateException( - String.format("The first record [starting at %d] must be at a split point", recordStart)); - } - if (recordStart < startOffset) { - throw new IllegalStateException( - String.format( - "Trying to return record [starting at %d] which is before the start offset [%d]", - recordStart, - startOffset)); - - } - if (recordStart < lastRecordStart) { - throw new IllegalStateException( - String.format( - "Trying to return record [starting at %d] " - + "which is before the last-returned record [starting at %d]", - recordStart, - lastRecordStart)); - } - - if (lastRecordStart == -1) { - startOffset = recordStart; - } - lastRecordStart = recordStart; - - if (isAtSplitPoint) { - if (recordStart == offsetOfLastSplitPoint) { - throw new IllegalStateException( - String.format( - "Record at a split point has same offset as the previous split point: " - + "previous split point at %d, current record starts at %d", - offsetOfLastSplitPoint, recordStart)); - } - if (recordStart >= stopOffset) { - done = true; - return false; - } - offsetOfLastSplitPoint = recordStart; - ++splitPointsSeen; - } - - return true; - } - - @Override - public boolean trySplitAtPosition(Long splitOffset) { - return trySplitAtPosition(splitOffset.longValue()); - } - - public synchronized boolean trySplitAtPosition(long splitOffset) { - if (stopOffset == OFFSET_INFINITY) { - LOG.debug("Refusing to split {} at {}: stop position unspecified", this, splitOffset); - return false; - } - if (!isStarted()) { - LOG.debug("Refusing to split {} at {}: unstarted", this, splitOffset); - return false; - } - - // Note: technically it is correct to split at any position after the last returned - // split point, not just the last returned record. - // TODO: Investigate whether in practice this is useful or, rather, confusing. - if (splitOffset <= lastRecordStart) { - LOG.debug( - "Refusing to split {} at {}: already past proposed split position", this, splitOffset); - return false; - } - if (splitOffset < startOffset || splitOffset >= stopOffset) { - LOG.debug( - "Refusing to split {} at {}: proposed split position out of range", this, splitOffset); - return false; - } - LOG.debug("Agreeing to split {} at {}", this, splitOffset); - this.stopOffset = splitOffset; - return true; - } - - /** - * Returns a position {@code P} such that the range {@code [start, P)} represents approximately - * the given fraction of the range {@code [start, end)}. Assumes that the density of records - * in the range is approximately uniform. - */ - public synchronized long getPositionForFractionConsumed(double fraction) { - if (stopOffset == OFFSET_INFINITY) { - throw new IllegalArgumentException( - "getPositionForFractionConsumed is not applicable to an unbounded range: " + this); - } - return (long) Math.floor(startOffset + fraction * (stopOffset - startOffset)); - } - - @Override - public synchronized double getFractionConsumed() { - if (!isStarted()) { - return 0.0; - } else if (isDone()) { - return 1.0; - } else if (stopOffset == OFFSET_INFINITY) { - return 0.0; - } else if (lastRecordStart >= stopOffset) { - return 1.0; - } else { - // E.g., when reading [3, 6) and lastRecordStart is 4, that means we consumed 3 of 3,4,5 - // which is (4 - 3) / (6 - 3) = 33%. - // Also, clamp to at most 1.0 because the last consumed position can extend past the - // stop position. - return Math.min(1.0, 1.0 * (lastRecordStart - startOffset) / (stopOffset - startOffset)); - } - } - - /** - * Returns the total number of split points that have been processed. - * - *

              A split point at a particular offset has been seen if there has been a corresponding call - * to {@link #tryReturnRecordAt(boolean, long)} with {@code isAtSplitPoint} true. It has been - * processed if there has been a subsequent call to - * {@link #tryReturnRecordAt(boolean, long)} with {@code isAtSplitPoint} true and at a larger - * offset. - * - *

              Note that for correctness when implementing {@link BoundedReader#getSplitPointsConsumed()}, - * if a reader finishes before {@link #tryReturnRecordAt(boolean, long)} returns false, - * the reader should add an additional call to {@link #markDone()}. This will indicate that - * processing for the last seen split point has been finished. - * - * @see com.google.cloud.dataflow.sdk.io.OffsetBasedSource for a {@link BoundedReader} - * implemented using {@link OffsetRangeTracker}. - */ - public synchronized long getSplitPointsProcessed() { - if (!isStarted()) { - return 0; - } else if (isDone()) { - return splitPointsSeen; - } else { - // There is a current split point, and it has not finished processing. - checkState( - splitPointsSeen > 0, - "A started rangeTracker should have seen > 0 split points (is %s)", - splitPointsSeen); - return splitPointsSeen - 1; - } - } - - - /** - * Marks this range tracker as being done. Specifically, this will mark the current split point, - * if one exists, as being finished. - * - *

              Always returns false, so that it can be used in an implementation of - * {@link BoundedReader#start()} or {@link BoundedReader#advance()} as follows: - * - *

               {@code
              -   * public boolean start() {
              -   *   return startImpl() && rangeTracker.tryReturnRecordAt(isAtSplitPoint, position)
              -   *       || rangeTracker.markDone();
              -   * }} 
              - */ - public synchronized boolean markDone() { - done = true; - return false; - } - - @Override - public synchronized String toString() { - String stopString = (stopOffset == OFFSET_INFINITY) ? "infinity" : String.valueOf(stopOffset); - if (lastRecordStart >= 0) { - return String.format( - "", - lastRecordStart, - startOffset, - stopString); - } else { - return String.format("", startOffset, stopString); - } - } - - /** - * Returns a copy of this tracker for testing purposes (to simplify testing methods with - * side effects). - */ - @VisibleForTesting - OffsetRangeTracker copy() { - OffsetRangeTracker res = new OffsetRangeTracker(startOffset, stopOffset); - res.offsetOfLastSplitPoint = this.offsetOfLastSplitPoint; - res.lastRecordStart = this.lastRecordStart; - res.done = this.done; - res.splitPointsSeen = this.splitPointsSeen; - return res; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java deleted file mode 100644 index cd67b85548..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/RangeTracker.java +++ /dev/null @@ -1,222 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -/** - * A {@code RangeTracker} is a thread-safe helper object for implementing dynamic work rebalancing - * in position-based {@link com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader} - * subclasses. - * - *

              Usage of the RangeTracker class hierarchy

              - * The abstract {@code RangeTracker} interface should not be used per se - all users should use its - * subclasses directly. We declare it here because all subclasses have roughly the same interface - * and the same properties, to centralize the documentation. Currently we provide one - * implementation - {@link OffsetRangeTracker}. - * - *

              Position-based sources

              - * A position-based source is one where the source can be described by a range of positions of - * an ordered type and the records returned by the reader can be described by positions of the - * same type. - * - *

              In case a record occupies a range of positions in the source, the most important thing about - * the record is the position where it starts. - * - *

              Defining the semantics of positions for a source is entirely up to the source class, however - * the chosen definitions have to obey certain properties in order to make it possible to correctly - * split the source into parts, including dynamic splitting. Two main aspects need to be defined: - *

                - *
              • How to assign starting positions to records. - *
              • Which records should be read by a source with a range {@code [A, B)}. - *
              - * Moreover, reading a range must be efficient, i.e., the performance of reading a range - * should not significantly depend on the location of the range. For example, reading the range - * {@code [A, B)} should not require reading all data before {@code A}. - * - *

              The sections below explain exactly what properties these definitions must satisfy, and - * how to use a {@code RangeTracker} with a properly defined source. - * - *

              Properties of position-based sources

              - * The main requirement for position-based sources is associativity: reading records from - * {@code [A, B)} and records from {@code [B, C)} should give the same records as reading from - * {@code [A, C)}, where {@code A <= B <= C}. This property ensures that no matter how a range - * of positions is split into arbitrarily many sub-ranges, the total set of records described by - * them stays the same. - * - *

              The other important property is how the source's range relates to positions of records in - * the source. In many sources each record can be identified by a unique starting position. - * In this case: - *

                - *
              • All records returned by a source {@code [A, B)} must have starting positions - * in this range. - *
              • All but the last record should end within this range. The last record may or may not - * extend past the end of the range. - *
              • Records should not overlap. - *
              - * Such sources should define "read {@code [A, B)}" as "read from the first record starting at or - * after A, up to but not including the first record starting at or after B". - * - *

              Some examples of such sources include reading lines or CSV from a text file, reading keys and - * values from a BigTable, etc. - * - *

              The concept of split points allows to extend the definitions for dealing with sources - * where some records cannot be identified by a unique starting position. - * - *

              In all cases, all records returned by a source {@code [A, B)} must start at or after - * {@code A}. - * - *

              Split points

              - * - *

              Some sources may have records that are not directly addressable. For example, imagine a file - * format consisting of a sequence of compressed blocks. Each block can be assigned an offset, but - * records within the block cannot be directly addressed without decompressing the block. Let us - * refer to this hypothetical format as CBF (Compressed Blocks Format). - * - *

              Many such formats can still satisfy the associativity property. For example, in CBF, reading - * {@code [A, B)} can mean "read all the records in all blocks whose starting offset is in - * {@code [A, B)}". - * - *

              To support such complex formats, we introduce the notion of split points. We say that - * a record is a split point if there exists a position {@code A} such that the record is the first - * one to be returned when reading the range {@code [A, infinity)}. In CBF, the only split points - * would be the first records in each block. - * - *

              Split points allow us to define the meaning of a record's position and a source's range - * in all cases: - *

                - *
              • For a record that is at a split point, its position is defined to be the largest - * {@code A} such that reading a source with the range {@code [A, infinity)} returns this record; - *
              • Positions of other records are only required to be non-decreasing; - *
              • Reading the source {@code [A, B)} must return records starting from the first split point - * at or after {@code A}, up to but not including the first split point at or after {@code B}. - * In particular, this means that the first record returned by a source MUST always be - * a split point. - *
              • Positions of split points must be unique. - *
              - * As a result, for any decomposition of the full range of the source into position ranges, the - * total set of records will be the full set of records in the source, and each record - * will be read exactly once. - * - *

              Consumed positions

              - * As the source is being read, and records read from it are being passed to the downstream - * transforms in the pipeline, we say that positions in the source are being consumed. - * When a reader has read a record (or promised to a caller that a record will be returned), - * positions up to and including the record's start position are considered consumed. - * - *

              Dynamic splitting can happen only at unconsumed positions. If the reader just - * returned a record at offset 42 in a file, dynamic splitting can happen only at offset 43 or - * beyond, as otherwise that record could be read twice (by the current reader and by a reader - * of the task starting at 43). - * - *

              Example

              - * The following example uses an {@link OffsetRangeTracker} to support dynamically splitting - * a source with integer positions (offsets). - *
               {@code
              - *   class MyReader implements BoundedReader {
              - *     private MySource currentSource;
              - *     private final OffsetRangeTracker tracker = new OffsetRangeTracker();
              - *     ...
              - *     MyReader(MySource source) {
              - *       this.currentSource = source;
              - *       this.tracker = new MyRangeTracker<>(source.getStartOffset(), source.getEndOffset())
              - *     }
              - *     ...
              - *     boolean start() {
              - *       ... (general logic for locating the first record) ...
              - *       if (!tracker.tryReturnRecordAt(true, recordStartOffset)) return false;
              - *       ... (any logic that depends on the record being returned, e.g. counting returned records)
              - *       return true;
              - *     }
              - *     boolean advance() {
              - *       ... (general logic for locating the next record) ...
              - *       if (!tracker.tryReturnRecordAt(isAtSplitPoint, recordStartOffset)) return false;
              - *       ... (any logic that depends on the record being returned, e.g. counting returned records)
              - *       return true;
              - *     }
              - *
              - *     double getFractionConsumed() {
              - *       return tracker.getFractionConsumed();
              - *     }
              - *   }
              - * } 
              - * - *

              Usage with different models of iteration

              - * When using this class to protect a - * {@link com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader}, follow the pattern - * described above. - * - *

              When using this class to protect iteration in the {@code hasNext()/next()} - * model, consider the record consumed when {@code hasNext()} is about to return true, rather than - * when {@code next()} is called, because {@code hasNext()} returning true is promising the caller - * that {@code next()} will have an element to return - so {@link #trySplitAtPosition} must not - * split the range in a way that would make the record promised by {@code hasNext()} belong to - * a different range. - * - *

              Also note that implementations of {@code hasNext()} need to ensure - * that they call {@link #tryReturnRecordAt} only once even if {@code hasNext()} is called - * repeatedly, due to the requirement on uniqueness of split point positions. - * - * @param Type of positions used by the source to define ranges and identify records. - */ -public interface RangeTracker { - /** - * Returns the starting position of the current range, inclusive. - */ - PositionT getStartPosition(); - - /** - * Returns the ending position of the current range, exclusive. - */ - PositionT getStopPosition(); - - /** - * Atomically determines whether a record at the given position can be returned and updates - * internal state. In particular: - * - *

                - *
              • If {@code isAtSplitPoint} is {@code true}, and {@code recordStart} is outside the current - * range, returns {@code false}; - *
              • Otherwise, updates the last-consumed position to {@code recordStart} and returns - * {@code true}. - *
              - * - *

              This method MUST be called on all split point records. It may be called on every record. - */ - boolean tryReturnRecordAt(boolean isAtSplitPoint, PositionT recordStart); - - /** - * Atomically splits the current range [{@link #getStartPosition}, {@link #getStopPosition}) - * into a "primary" part [{@link #getStartPosition}, {@code splitPosition}) - * and a "residual" part [{@code splitPosition}, {@link #getStopPosition}), assuming the current - * last-consumed position is within [{@link #getStartPosition}, splitPosition) - * (i.e., {@code splitPosition} has not been consumed yet). - * - *

              Updates the current range to be the primary and returns {@code true}. This means that - * all further calls on the current object will interpret their arguments relative to the - * primary range. - * - *

              If the split position has already been consumed, or if no {@link #tryReturnRecordAt} call - * was made yet, returns {@code false}. The second condition is to prevent dynamic splitting - * during reader start-up. - */ - boolean trySplitAtPosition(PositionT splitPosition); - - /** - * Returns the approximate fraction of positions in the source that have been consumed by - * successful {@link #tryReturnRecordAt} calls, or 0.0 if no such calls have happened. - */ - double getFractionConsumed(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/package-info.java deleted file mode 100644 index beb77bf0ad..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/range/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Provides thread-safe helpers for implementing dynamic work rebalancing in position-based - * bounded sources. - * - *

              See {@link com.google.cloud.dataflow.sdk.io.range.RangeTracker} to get started. - */ -package com.google.cloud.dataflow.sdk.io.range; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ApplicationNameOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ApplicationNameOptions.java deleted file mode 100644 index 60d62d3754..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ApplicationNameOptions.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -/** - * Options that allow setting the application name. - */ -public interface ApplicationNameOptions extends PipelineOptions { - /** - * Name of application, for display purposes. - * - *

              Defaults to the name of the class that constructs the {@link PipelineOptions} - * via the {@link PipelineOptionsFactory}. - */ - @Description("Name of application for display purposes. Defaults to the name of the class that " - + "constructs the PipelineOptions via the PipelineOptionsFactory.") - String getAppName(); - void setAppName(String value); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BigQueryOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BigQueryOptions.java deleted file mode 100644 index ed4eb24bac..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BigQueryOptions.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -/** - * Properties needed when using BigQuery with the Dataflow SDK. - */ -@Description("Options that are used to configure BigQuery. See " - + "https://cloud.google.com/bigquery/what-is-bigquery for details on BigQuery.") -public interface BigQueryOptions extends ApplicationNameOptions, GcpOptions, - PipelineOptions, StreamingOptions { - @Description("Temporary dataset for BigQuery table operations. " - + "Supported values are \"bigquery.googleapis.com/{dataset}\"") - @Default.String("bigquery.googleapis.com/cloud_dataflow") - String getTempDatasetId(); - void setTempDatasetId(String value); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BlockingDataflowPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BlockingDataflowPipelineOptions.java deleted file mode 100644 index 09c5eb98c0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/BlockingDataflowPipelineOptions.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.io.PrintStream; - -/** - * Options that are used to configure the {@link BlockingDataflowPipelineRunner}. - */ -@Description("Configure options on the BlockingDataflowPipelineRunner.") -public interface BlockingDataflowPipelineOptions extends DataflowPipelineOptions { - /** - * Output stream for job status messages. - */ - @Description("Where messages generated during execution of the Dataflow job will be output.") - @JsonIgnore - @Hidden - @Default.InstanceFactory(StandardOutputFactory.class) - PrintStream getJobMessageOutput(); - void setJobMessageOutput(PrintStream value); - - /** - * Returns a default of {@link System#out}. - */ - class StandardOutputFactory implements DefaultValueFactory { - @Override - public PrintStream create(PipelineOptions options) { - return System.out; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java deleted file mode 100644 index 16acc9cd25..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/CloudDebuggerOptions.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.api.services.clouddebugger.v2.model.Debuggee; -import com.google.cloud.dataflow.sdk.annotations.Experimental; - -import javax.annotation.Nullable; - -/** - * Options for controlling Cloud Debugger. - */ -@Description("[Experimental] Used to configure the Cloud Debugger") -@Experimental -@Hidden -public interface CloudDebuggerOptions { - - /** Whether to enable the Cloud Debugger snapshot agent for the current job. */ - @Description("Whether to enable the Cloud Debugger snapshot agent for the current job.") - boolean getEnableCloudDebugger(); - void setEnableCloudDebugger(boolean enabled); - - /** The Cloud Debugger debuggee to associate with. This should not be set directly. */ - @Description("The Cloud Debugger debuggee to associate with. This should not be set directly.") - @Hidden - @Nullable Debuggee getDebuggee(); - void setDebuggee(Debuggee debuggee); - - /** The maximum cost (as a ratio of CPU time) allowed for evaluating conditional snapshots. */ - @Description( - "The maximum cost (as a ratio of CPU time) allowed for evaluating conditional snapshots. " - + "Should be a double between 0 and 1. " - + "Snapshots will be cancelled if evaluating conditions takes more than this ratio of time.") - @Default.Double(0.01) - double getMaxConditionCost(); - void setMaxConditionCost(double maxConditionCost); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java deleted file mode 100644 index 12f8d40037..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptions.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.api.services.dataflow.Dataflow; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.util.DataflowPathValidator; -import com.google.cloud.dataflow.sdk.util.GcsStager; -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; -import com.google.cloud.dataflow.sdk.util.PathValidator; -import com.google.cloud.dataflow.sdk.util.Stager; -import com.google.cloud.dataflow.sdk.util.Transport; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.List; -import java.util.Map; - -/** - * Internal. Options used to control execution of the Dataflow SDK for - * debugging and testing purposes. - */ -@Description("[Internal] Options used to control execution of the Dataflow SDK for " - + "debugging and testing purposes.") -@Hidden -public interface DataflowPipelineDebugOptions extends PipelineOptions { - - /** - * The list of backend experiments to enable. - * - *

              Dataflow provides a number of experimental features that can be enabled - * with this flag. - * - *

              Please sync with the Dataflow team before enabling any experiments. - */ - @Description("[Experimental] Dataflow provides a number of experimental features that can " - + "be enabled with this flag. Please sync with the Dataflow team before enabling any " - + "experiments.") - @Experimental - List getExperiments(); - void setExperiments(List value); - - /** - * The root URL for the Dataflow API. {@code dataflowEndpoint} can override this value - * if it contains an absolute URL, otherwise {@code apiRootUrl} will be combined with - * {@code dataflowEndpoint} to generate the full URL to communicate with the Dataflow API. - */ - @Description("The root URL for the Dataflow API. dataflowEndpoint can override this " - + "value if it contains an absolute URL, otherwise apiRootUrl will be combined with " - + "dataflowEndpoint to generate the full URL to communicate with the Dataflow API.") - @Default.String(Dataflow.DEFAULT_ROOT_URL) - String getApiRootUrl(); - void setApiRootUrl(String value); - - /** - * Dataflow endpoint to use. - * - *

              Defaults to the current version of the Google Cloud Dataflow - * API, at the time the current SDK version was released. - * - *

              If the string contains "://", then this is treated as a URL, - * otherwise {@link #getApiRootUrl()} is used as the root - * URL. - */ - @Description("The URL for the Dataflow API. If the string contains \"://\", this" - + " will be treated as the entire URL, otherwise will be treated relative to apiRootUrl.") - @Default.String(Dataflow.DEFAULT_SERVICE_PATH) - String getDataflowEndpoint(); - void setDataflowEndpoint(String value); - - /** - * The path to write the translated Dataflow job specification out to - * at job submission time. The Dataflow job specification will be represented in JSON - * format. - */ - @Description("The path to write the translated Dataflow job specification out to " - + "at job submission time. The Dataflow job specification will be represented in JSON " - + "format.") - String getDataflowJobFile(); - void setDataflowJobFile(String value); - - /** - * The class of the validator that should be created and used to validate paths. - * If pathValidator has not been set explicitly, an instance of this class will be - * constructed and used as the path validator. - */ - @Description("The class of the validator that should be created and used to validate paths. " - + "If pathValidator has not been set explicitly, an instance of this class will be " - + "constructed and used as the path validator.") - @Default.Class(DataflowPathValidator.class) - Class getPathValidatorClass(); - void setPathValidatorClass(Class validatorClass); - - /** - * The path validator instance that should be used to validate paths. - * If no path validator has been set explicitly, the default is to use the instance factory that - * constructs a path validator based upon the currently set pathValidatorClass. - */ - @JsonIgnore - @Description("The path validator instance that should be used to validate paths. " - + "If no path validator has been set explicitly, the default is to use the instance factory " - + "that constructs a path validator based upon the currently set pathValidatorClass.") - @Default.InstanceFactory(PathValidatorFactory.class) - PathValidator getPathValidator(); - void setPathValidator(PathValidator validator); - - /** - * The class responsible for staging resources to be accessible by workers - * during job execution. If stager has not been set explicitly, an instance of this class - * will be created and used as the resource stager. - */ - @Description("The class of the stager that should be created and used to stage resources. " - + "If stager has not been set explicitly, an instance of the this class will be created " - + "and used as the resource stager.") - @Default.Class(GcsStager.class) - Class getStagerClass(); - void setStagerClass(Class stagerClass); - - /** - * The resource stager instance that should be used to stage resources. - * If no stager has been set explicitly, the default is to use the instance factory - * that constructs a resource stager based upon the currently set stagerClass. - */ - @JsonIgnore - @Description("The resource stager instance that should be used to stage resources. " - + "If no stager has been set explicitly, the default is to use the instance factory " - + "that constructs a resource stager based upon the currently set stagerClass.") - @Default.InstanceFactory(StagerFactory.class) - Stager getStager(); - void setStager(Stager stager); - - /** - * An instance of the Dataflow client. Defaults to creating a Dataflow client - * using the current set of options. - */ - @JsonIgnore - @Description("An instance of the Dataflow client. Defaults to creating a Dataflow client " - + "using the current set of options.") - @Default.InstanceFactory(DataflowClientFactory.class) - Dataflow getDataflowClient(); - void setDataflowClient(Dataflow value); - - /** Returns the default Dataflow client built from the passed in PipelineOptions. */ - class DataflowClientFactory implements DefaultValueFactory { - @Override - public Dataflow create(PipelineOptions options) { - return Transport.newDataflowClient(options.as(DataflowPipelineOptions.class)).build(); - } - } - - /** - * Root URL for use with the Pubsub API. - */ - @Description("Root URL for use with the Pubsub API") - @Default.String("https://pubsub.googleapis.com") - String getPubsubRootUrl(); - void setPubsubRootUrl(String value); - - /** - * Whether to update the currently running pipeline with the same name as this one. - * - * @deprecated This property is replaced by {@link DataflowPipelineOptions#getUpdate()} - */ - @Deprecated - @Description("If set, replace the existing pipeline with the name specified by --jobName with " - + "this pipeline, preserving state.") - boolean getUpdate(); - @Deprecated - void setUpdate(boolean value); - - /** - * Mapping of old PTranform names to new ones, specified as JSON - * {"oldName":"newName",...}. To mark a transform as deleted, make newName the - * empty string. - */ - @JsonIgnore - @Description( - "Mapping of old PTranform names to new ones, specified as JSON " - + "{\"oldName\":\"newName\",...}. To mark a transform as deleted, make newName the empty " - + "string.") - Map getTransformNameMapping(); - void setTransformNameMapping(Map value); - - /** - * Custom windmill_main binary to use with the streaming runner. - */ - @Description("Custom windmill_main binary to use with the streaming runner") - String getOverrideWindmillBinary(); - void setOverrideWindmillBinary(String value); - - /** - * Custom windmill service endpoint. - */ - @Description("Custom windmill service endpoint.") - String getWindmillServiceEndpoint(); - void setWindmillServiceEndpoint(String value); - - @Description("Port for communicating with a remote windmill service.") - @Default.Integer(443) - int getWindmillServicePort(); - void setWindmillServicePort(int value); - - /** - * Number of threads to use on the Dataflow worker harness. If left unspecified, - * the Dataflow service will compute an appropriate number of threads to use. - */ - @Description("Number of threads to use on the Dataflow worker harness. If left unspecified, " - + "the Dataflow service will compute an appropriate number of threads to use.") - int getNumberOfWorkerHarnessThreads(); - void setNumberOfWorkerHarnessThreads(int value); - - /** - * If {@literal true}, save a heap dump before killing a thread or process which is GC - * thrashing or out of memory. The location of the heap file will either be echoed back - * to the user, or the user will be given the opportunity to download the heap file. - * - *

              CAUTION: Heap dumps can of comparable size to the default boot disk. Consider increasing - * the boot disk size before setting this flag to true. - */ - @Description("If {@literal true}, save a heap dump before killing a thread or process " - + "which is GC thrashing or out of memory.") - boolean getDumpHeapOnOOM(); - void setDumpHeapOnOOM(boolean dumpHeapBeforeExit); - - /** - * Creates a {@link PathValidator} object using the class specified in - * {@link #getPathValidatorClass()}. - */ - class PathValidatorFactory implements DefaultValueFactory { - @Override - public PathValidator create(PipelineOptions options) { - DataflowPipelineDebugOptions debugOptions = options.as(DataflowPipelineDebugOptions.class); - return InstanceBuilder.ofType(PathValidator.class) - .fromClass(debugOptions.getPathValidatorClass()) - .fromFactoryMethod("fromOptions") - .withArg(PipelineOptions.class, options) - .build(); - } - } - - /** - * Creates a {@link Stager} object using the class specified in - * {@link #getStagerClass()}. - */ - class StagerFactory implements DefaultValueFactory { - @Override - public Stager create(PipelineOptions options) { - DataflowPipelineDebugOptions debugOptions = options.as(DataflowPipelineDebugOptions.class); - return InstanceBuilder.ofType(Stager.class) - .fromClass(debugOptions.getStagerClass()) - .fromFactoryMethod("fromOptions") - .withArg(PipelineOptions.class, options) - .build(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java deleted file mode 100644 index baff19e66d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptions.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.runners.DataflowPipeline; -import com.google.common.base.MoreObjects; - -import org.joda.time.DateTimeUtils; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.util.Map; - -/** - * Options that can be used to configure the {@link DataflowPipeline}. - */ -@Description("Options that configure the Dataflow pipeline.") -public interface DataflowPipelineOptions extends - PipelineOptions, GcpOptions, ApplicationNameOptions, DataflowPipelineDebugOptions, - DataflowPipelineWorkerPoolOptions, BigQueryOptions, - GcsOptions, StreamingOptions, CloudDebuggerOptions, DataflowWorkerLoggingOptions, - DataflowProfilingOptions { - - @Description("Project id. Required when running a Dataflow in the cloud. " - + "See https://cloud.google.com/storage/docs/projects for further details.") - @Override - @Validation.Required - @Default.InstanceFactory(DefaultProjectFactory.class) - String getProject(); - @Override - void setProject(String value); - - /** - * GCS path for staging local files, e.g. gs://bucket/object - * - *

              Must be a valid Cloud Storage URL, beginning with the prefix "gs://" - * - *

              At least one of {@link #getTempLocation()} or {@link #getStagingLocation()} must be set. If - * {@link #getTempLocation()} is not set, then the Dataflow pipeline defaults to using - * {@link #getStagingLocation()}. - */ - @Description("GCS path for staging local files, e.g. \"gs://bucket/object\". " - + "Must be a valid Cloud Storage URL, beginning with the prefix \"gs://\". " - + "At least one of stagingLocation or tempLocation must be set. If stagingLocation is unset, " - + "defaults to using tempLocation.") - String getStagingLocation(); - void setStagingLocation(String value); - - /** - * The Dataflow job name is used as an idempotence key within the Dataflow service. - * If there is an existing job that is currently active, another active job with the same - * name will not be able to be created. Defaults to using the ApplicationName-UserName-Date. - */ - @Description("The Dataflow job name is used as an idempotence key within the Dataflow service. " - + "For each running job in the same GCP project, jobs with the same name cannot be created " - + "unless the new job is an explicit update of the previous one. Defaults to using " - + "ApplicationName-UserName-Date. The job name must match the regular expression " - + "'[a-z]([-a-z0-9]{0,38}[a-z0-9])?'. The runner will automatically truncate the name of the " - + "job and convert to lower case.") - @Default.InstanceFactory(JobNameFactory.class) - String getJobName(); - void setJobName(String value); - - /** - * Whether to update the currently running pipeline with the same name as this one. - */ - @Override - @SuppressWarnings("deprecation") // base class member deprecated in favor of this one. - @Description( - "If set, replace the existing pipeline with the name specified by --jobName with " - + "this pipeline, preserving state.") - boolean getUpdate(); - @Override - @SuppressWarnings("deprecation") // base class member deprecated in favor of this one. - void setUpdate(boolean value); - - /** - * Run the job as a specific service account, instead of the default GCE robot. - */ - @Hidden - @Experimental - @Description( - "Run the job as a specific service account, instead of the default GCE robot.") - String getServiceAccount(); - void setServiceAccount(String value); - - /** - * Returns a normalized job name constructed from {@link ApplicationNameOptions#getAppName()}, the - * local system user name (if available), and the current time. The normalization makes sure that - * the job name matches the required pattern of [a-z]([-a-z0-9]*[a-z0-9])? and length limit of 40 - * characters. - * - *

              This job name factory is only able to generate one unique name per second per application - * and user combination. - */ - class JobNameFactory implements DefaultValueFactory { - private static final DateTimeFormatter FORMATTER = - DateTimeFormat.forPattern("MMddHHmmss").withZone(DateTimeZone.UTC); - - @Override - public String create(PipelineOptions options) { - String appName = options.as(ApplicationNameOptions.class).getAppName(); - String normalizedAppName = appName == null || appName.length() == 0 ? "dataflow" - : appName.toLowerCase() - .replaceAll("[^a-z0-9]", "0") - .replaceAll("^[^a-z]", "a"); - String userName = MoreObjects.firstNonNull(System.getProperty("user.name"), ""); - String normalizedUserName = userName.toLowerCase() - .replaceAll("[^a-z0-9]", "0"); - String datePart = FORMATTER.print(DateTimeUtils.currentTimeMillis()); - return normalizedAppName + "-" + normalizedUserName + "-" + datePart; - } - } - - /** - * Labels that will be applied to the billing records for this job. - */ - @Description("Labels that will be applied to the billing records for this job.") - Map getLabels(); - void setLabels(Map labels); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java deleted file mode 100644 index 23612442b5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineWorkerPoolOptions.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Options that are used to configure the Dataflow pipeline worker pool. - */ -@Description("Options that are used to configure the Dataflow pipeline worker pool.") -public interface DataflowPipelineWorkerPoolOptions extends PipelineOptions { - /** - * Number of workers to use when executing the Dataflow job. Note that selection of an autoscaling - * algorithm other then {@code NONE} will affect the size of the worker pool. If left unspecified, - * the Dataflow service will determine the number of workers. - */ - @Description("Number of workers to use when executing the Dataflow job. Note that " - + "selection of an autoscaling algorithm other then \"NONE\" will affect the " - + "size of the worker pool. If left unspecified, the Dataflow service will " - + "determine the number of workers.") - int getNumWorkers(); - void setNumWorkers(int value); - - /** - * Type of autoscaling algorithm to use. - */ - enum AutoscalingAlgorithmType { - /** Use numWorkers machines. Do not autoscale the worker pool. */ - NONE("AUTOSCALING_ALGORITHM_NONE"), - - @Deprecated - BASIC("AUTOSCALING_ALGORITHM_BASIC"), - - /** Autoscale the workerpool based on throughput (up to maxNumWorkers). */ - THROUGHPUT_BASED("AUTOSCALING_ALGORITHM_BASIC"); - - private final String algorithm; - - private AutoscalingAlgorithmType(String algorithm) { - this.algorithm = algorithm; - } - - /** Returns the string representation of this type. */ - public String getAlgorithm() { - return this.algorithm; - } - } - - /** - * The autoscaling algorithm to use for the workerpool. - * - *

                - *
              • NONE: does not change the size of the worker pool.
              • - *
              • BASIC: autoscale the worker pool size up to maxNumWorkers until the job completes.
              • - *
              • THROUGHPUT_BASED: autoscale the workerpool based on throughput (up to maxNumWorkers). - *
              • - *
              - */ - @Description("The autoscaling algorithm to use for the workerpool. " - + "NONE: does not change the size of the worker pool. " - + "BASIC (deprecated): autoscale the worker pool size up to maxNumWorkers until the job " - + "completes. " - + "THROUGHPUT_BASED: autoscale the workerpool based on throughput (up to maxNumWorkers).") - AutoscalingAlgorithmType getAutoscalingAlgorithm(); - void setAutoscalingAlgorithm(AutoscalingAlgorithmType value); - - /** - * The maximum number of workers to use for the workerpool. This options limits the size of the - * workerpool for the lifetime of the job, including - * pipeline updates. - * If left unspecified, the Dataflow service will compute a ceiling. - */ - @Description("The maximum number of workers to use for the workerpool. This options limits the " - + "size of the workerpool for the lifetime of the job, including pipeline updates. " - + "If left unspecified, the Dataflow service will compute a ceiling.") - int getMaxNumWorkers(); - void setMaxNumWorkers(int value); - - /** - * Remote worker disk size, in gigabytes, or 0 to use the default size. - */ - @Description("Remote worker disk size, in gigabytes, or 0 to use the default size.") - int getDiskSizeGb(); - void setDiskSizeGb(int value); - - /** - * Docker container image that executes Dataflow worker harness, residing in Google Container - * Registry. - */ - @Default.InstanceFactory(WorkerHarnessContainerImageFactory.class) - @Description("Docker container image that executes Dataflow worker harness, residing in Google " - + " Container Registry.") - @Hidden - String getWorkerHarnessContainerImage(); - void setWorkerHarnessContainerImage(String value); - - /** - * Returns the default Docker container image that executes Dataflow worker harness, residing in - * Google Container Registry. - */ - class WorkerHarnessContainerImageFactory - implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - if (dataflowOptions.isStreaming()) { - return DataflowPipelineRunner.STREAMING_WORKER_HARNESS_CONTAINER_IMAGE; - } else { - return DataflowPipelineRunner.BATCH_WORKER_HARNESS_CONTAINER_IMAGE; - } - } - } - - /** - * GCE network for launching - * workers. - * - *

              Default is up to the Dataflow service. - */ - @Description("GCE network for launching workers. For more information, see the reference " - + "documentation https://cloud.google.com/compute/docs/networking. " - + "Default is up to the Dataflow service.") - String getNetwork(); - void setNetwork(String value); - - /** - * GCE subnetwork for launching - * workers. - * - *

              Default is up to the Dataflow service. Expected format is - * regions/REGION/subnetworks/SUBNETWORK. - * - *

              You may also need to specify network option. - */ - @Description("GCE subnetwork for launching workers. For more information, see the reference " - + "documentation https://cloud.google.com/compute/docs/networking. " - + "Default is up to the Dataflow service.") - String getSubnetwork(); - void setSubnetwork(String value); - - /** - * GCE availability zone for launching workers. - * - *

              Default is up to the Dataflow service. - */ - @Description("GCE availability zone for launching workers. See " - + "https://developers.google.com/compute/docs/zones for a list of valid options. " - + "Default is up to the Dataflow service.") - String getZone(); - void setZone(String value); - - /** - * Machine type to create Dataflow worker VMs as. - * - *

              See GCE machine types - * for a list of valid options. - * - *

              If unset, the Dataflow service will choose a reasonable default. - */ - @Description("Machine type to create Dataflow worker VMs as. See " - + "https://cloud.google.com/compute/docs/machine-types for a list of valid options. " - + "If unset, the Dataflow service will choose a reasonable default.") - String getWorkerMachineType(); - void setWorkerMachineType(String value); - - /** - * The policy for tearing down the workers spun up by the service. - * @deprecated - * Dataflow Service will only support TEARDOWN_ALWAYS policy in the future. - */ - @Deprecated - enum TeardownPolicy { - /** - * All VMs created for a Dataflow job are deleted when the job finishes, regardless of whether - * it fails or succeeds. - */ - TEARDOWN_ALWAYS("TEARDOWN_ALWAYS"), - /** - * All VMs created for a Dataflow job are left running when the job finishes, regardless of - * whether it fails or succeeds. - */ - TEARDOWN_NEVER("TEARDOWN_NEVER"), - /** - * All VMs created for a Dataflow job are deleted when the job succeeds, but are left running - * when it fails. (This is typically used for debugging failing jobs by SSHing into the - * workers.) - */ - TEARDOWN_ON_SUCCESS("TEARDOWN_ON_SUCCESS"); - - private final String teardownPolicy; - - TeardownPolicy(String teardownPolicy) { - this.teardownPolicy = teardownPolicy; - } - - public String getTeardownPolicyName() { - return this.teardownPolicy; - } - } - - /** - * The teardown policy for the VMs. - * - *

              If unset, the Dataflow service will choose a reasonable default. - */ - @Description("The teardown policy for the VMs. If unset, the Dataflow service will " - + "choose a reasonable default.") - TeardownPolicy getTeardownPolicy(); - void setTeardownPolicy(TeardownPolicy value); - - /** - * List of local files to make available to workers. - * - *

              Files are placed on the worker's classpath. - * - *

              The default value is the list of jars from the main program's classpath. - */ - @Description("Files to stage on GCS and make available to workers. " - + "Files are placed on the worker's classpath. " - + "The default value is all files from the classpath.") - @JsonIgnore - List getFilesToStage(); - void setFilesToStage(List value); - - /** - * Specifies what type of persistent disk should be used. The value should be a full or partial - * URL of a disk type resource, e.g., zones/us-central1-f/disks/pd-standard. For - * more information, see the - * API reference - * documentation for DiskTypes. - */ - @Description("Specifies what type of persistent disk should be used. The value should be a full " - + "or partial URL of a disk type resource, e.g., zones/us-central1-f/disks/pd-standard. For " - + "more information, see the API reference documentation for DiskTypes: " - + "https://cloud.google.com/compute/docs/reference/latest/diskTypes") - String getWorkerDiskType(); - void setWorkerDiskType(String value); - - /** - * Specifies whether worker pools should be started with public IP addresses. - * - *

              WARNING: This feature is experimental. You must be whitelisted to use it. - */ - @Description("Specifies whether worker pools should be started with public IP addresses. WARNING:" - + "This feature is experimental. You must be whitelisted to use it.") - @Experimental - @JsonIgnore - @Nullable Boolean getUsePublicIps(); - void setUsePublicIps(@Nullable Boolean value); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java deleted file mode 100644 index bd1fbff285..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptions.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; - -import java.util.HashMap; - -/** - * Options for controlling profiling of pipeline execution. - */ -@Description("[Experimental] Used to configure profiling of the Dataflow pipeline") -@Experimental -@Hidden -public interface DataflowProfilingOptions { - - @Description( - "This option is deprecated and ignored. Using --saveProfilesToGcs= is preferred.") - boolean getEnableProfilingAgent(); - void setEnableProfilingAgent(boolean enabled); - - @Description( - "When set to a non-empty value, enables recording profiles and saving them to GCS.\n" - + "Profiles will continue until the pipeline is stopped or updated without this option.\n") - String getSaveProfilesToGcs(); - void setSaveProfilesToGcs(String gcsPath); - - @Description( - "[INTERNAL] Additional configuration for the profiling agent. Not typically necessary.") - @Hidden - DataflowProfilingAgentConfiguration getProfilingAgentConfiguration(); - void setProfilingAgentConfiguration(DataflowProfilingAgentConfiguration configuration); - - /** - * Configuration the for profiling agent. - */ - class DataflowProfilingAgentConfiguration extends HashMap { - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerHarnessOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerHarnessOptions.java deleted file mode 100644 index e4b1d72570..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerHarnessOptions.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -/** - * Options that are used exclusively within the Dataflow worker harness. - * These options have no effect at pipeline creation time. - */ -@Description("[Internal] Options that are used exclusively within the Dataflow worker harness. " - + "These options have no effect at pipeline creation time.") -@Hidden -public interface DataflowWorkerHarnessOptions extends DataflowPipelineOptions { - /** - * The identity of the worker running this pipeline. - */ - @Description("The identity of the worker running this pipeline.") - String getWorkerId(); - void setWorkerId(String value); - - /** - * The identity of the Dataflow job. - */ - @Description("The identity of the Dataflow job.") - String getJobId(); - void setJobId(String value); - - /** - * The size of the worker's in-memory cache, in megabytes. - * - *

              Currently, this cache is used for storing read values of side inputs. - */ - @Description("The size of the worker's in-memory cache, in megabytes.") - @Default.Integer(100) - Integer getWorkerCacheMb(); - void setWorkerCacheMb(Integer value); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptions.java deleted file mode 100644 index 25d91c19ed..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptions.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Options that are used to control logging configuration on the Dataflow worker. - */ -@Description("Options that are used to control logging configuration on the Dataflow worker.") -public interface DataflowWorkerLoggingOptions extends PipelineOptions { - /** - * The set of log levels that can be used on the Dataflow worker. - */ - enum Level { - DEBUG, ERROR, INFO, TRACE, WARN - } - - /** - * This option controls the default log level of all loggers without a log level override. - */ - @Description("Controls the default log level of all loggers without a log level override.") - @Default.Enum("INFO") - Level getDefaultWorkerLogLevel(); - void setDefaultWorkerLogLevel(Level level); - - /** - * This option controls the log levels for specifically named loggers. - * - *

              Later options with equivalent names override earlier options. - * - *

              See {@link WorkerLogLevelOverrides} for more information on how to configure logging - * on a per {@link Class}, {@link Package}, or name basis. If used from the command line, - * the expected format is {"Name":"Level",...}, further details on - * {@link WorkerLogLevelOverrides#from}. - */ - @Description("This option controls the log levels for specifically named loggers. " - + "The expected format is {\"Name\":\"Level\",...}. The Dataflow worker uses " - + "java.util.logging, which supports a logging hierarchy based off of names that are '.' " - + "separated. For example, by specifying the value {\"a.b.c.Foo\":\"DEBUG\"}, the logger " - + "for the class 'a.b.c.Foo' will be configured to output logs at the DEBUG level. " - + "Similarly, by specifying the value {\"a.b.c\":\"WARN\"}, all loggers underneath the " - + "'a.b.c' package will be configured to output logs at the WARN level. Also, note that " - + "when multiple overrides are specified, the exact name followed by the closest parent " - + "takes precedence.") - WorkerLogLevelOverrides getWorkerLogLevelOverrides(); - void setWorkerLogLevelOverrides(WorkerLogLevelOverrides value); - - /** - * Defines a log level override for a specific class, package, or name. - * - *

              {@code java.util.logging} is used on the Dataflow worker harness and supports - * a logging hierarchy based off of names that are "." separated. It is a common - * pattern to have the logger for a given class share the same name as the class itself. - * Given the classes {@code a.b.c.Foo}, {@code a.b.c.Xyz}, and {@code a.b.Bar}, with - * loggers named {@code "a.b.c.Foo"}, {@code "a.b.c.Xyz"}, and {@code "a.b.Bar"} respectively, - * we can override the log levels: - *

                - *
              • for {@code Foo} by specifying the name {@code "a.b.c.Foo"} or the {@link Class} - * representing {@code a.b.c.Foo}. - *
              • for {@code Foo}, {@code Xyz}, and {@code Bar} by specifying the name {@code "a.b"} or - * the {@link Package} representing {@code a.b}. - *
              • for {@code Foo} and {@code Bar} by specifying both of their names or classes. - *
              - * Note that by specifying multiple overrides, the exact name followed by the closest parent - * takes precedence. - */ - class WorkerLogLevelOverrides extends HashMap { - /** - * Overrides the default log level for the passed in class. - * - *

              This is equivalent to calling - * {@link #addOverrideForName(String, DataflowWorkerLoggingOptions.Level)} - * and passing in the {@link Class#getName() class name}. - */ - public WorkerLogLevelOverrides addOverrideForClass(Class klass, Level level) { - checkNotNull(klass, "Expected class to be not null."); - addOverrideForName(klass.getName(), level); - return this; - } - - /** - * Overrides the default log level for the passed in package. - * - *

              This is equivalent to calling - * {@link #addOverrideForName(String, DataflowWorkerLoggingOptions.Level)} - * and passing in the {@link Package#getName() package name}. - */ - public WorkerLogLevelOverrides addOverrideForPackage(Package pkg, Level level) { - checkNotNull(pkg, "Expected package to be not null."); - addOverrideForName(pkg.getName(), level); - return this; - } - - /** - * Overrides the default log level for the passed in name. - * - *

              Note that because of the hierarchical nature of logger names, this will - * override the log level of all loggers that have the passed in name or - * a parent logger that has the passed in name. - */ - public WorkerLogLevelOverrides addOverrideForName(String name, Level level) { - checkNotNull(name, "Expected name to be not null."); - checkNotNull(level, - "Expected level to be one of %s.", Arrays.toString(Level.values())); - put(name, level); - return this; - } - - /** - * Expects a map keyed by logger {@code Name}s with values representing {@code Level}s. - * The {@code Name} generally represents the fully qualified Java - * {@link Class#getName() class name}, or fully qualified Java - * {@link Package#getName() package name}, or custom logger name. The {@code Level} - * represents the log level and must be one of {@link Level}. - */ - @JsonCreator - public static WorkerLogLevelOverrides from(Map values) { - checkNotNull(values, "Expected values to be not null."); - WorkerLogLevelOverrides overrides = new WorkerLogLevelOverrides(); - for (Map.Entry entry : values.entrySet()) { - try { - overrides.addOverrideForName(entry.getKey(), Level.valueOf(entry.getValue())); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(String.format( - "Unsupported log level '%s' requested for %s. Must be one of %s.", - entry.getValue(), entry.getKey(), Arrays.toString(Level.values()))); - } - - } - return overrides; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Default.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Default.java deleted file mode 100644 index 46ff682f5b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Default.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * {@link Default} represents a set of annotations that can be used to annotate getter properties - * on {@link PipelineOptions} with information representing the default value to be returned - * if no value is specified. - */ -public @interface Default { - /** - * This represents that the default of the option is the specified {@link java.lang.Class} value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Class { - java.lang.Class value(); - } - - /** - * This represents that the default of the option is the specified {@link java.lang.String} - * value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface String { - java.lang.String value(); - } - - /** - * This represents that the default of the option is the specified boolean primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Boolean { - boolean value(); - } - - /** - * This represents that the default of the option is the specified char primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Character { - char value(); - } - - /** - * This represents that the default of the option is the specified byte primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Byte { - byte value(); - } - /** - * This represents that the default of the option is the specified short primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Short { - short value(); - } - /** - * This represents that the default of the option is the specified int primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Integer { - int value(); - } - - /** - * This represents that the default of the option is the specified long primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Long { - long value(); - } - - /** - * This represents that the default of the option is the specified float primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Float { - float value(); - } - - /** - * This represents that the default of the option is the specified double primitive value. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Double { - double value(); - } - - /** - * This represents that the default of the option is the specified enum. - * The value should equal the enum's {@link java.lang.Enum#name() name}. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Enum { - java.lang.String value(); - } - - /** - * Value must be of type {@link DefaultValueFactory} and have a default constructor. - * Value is instantiated and then used as a factory to generate the default. - * - *

              See {@link DefaultValueFactory} for more details. - */ - @Target(ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface InstanceFactory { - java.lang.Class> value(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DefaultValueFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DefaultValueFactory.java deleted file mode 100644 index 1faedb70d6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DefaultValueFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -/** - * An interface used with the {@link Default.InstanceFactory} annotation to specify the class that - * will be an instance factory to produce default values for a given getter on - * {@link PipelineOptions}. When a property on a {@link PipelineOptions} is fetched, and is - * currently unset, the default value factory will be instantiated and invoked. - * - *

              Care must be taken to not produce an infinite loop when accessing other fields on the - * {@link PipelineOptions} object. - * - * @param The type of object this factory produces. - */ -public interface DefaultValueFactory { - /** - * Creates a default value for a getter marked with {@link Default.InstanceFactory}. - * - * @param options The current pipeline options. - * @return The default value to be used for the annotated getter. - */ - T create(PipelineOptions options); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Description.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Description.java deleted file mode 100644 index 9ceaf586f5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Description.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Descriptions are used to generate human readable output when the {@code --help} - * command is specified. Description annotations placed on interfaces that extend - * {@link PipelineOptions} will describe groups of related options. Description annotations - * placed on getter methods will be used to provide human readable information - * for the specific option. - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Description { - String value(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DirectPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DirectPipelineOptions.java deleted file mode 100644 index 0867740fab..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/DirectPipelineOptions.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.DirectPipeline; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -/** - * Options that can be used to configure the {@link DirectPipeline}. - */ -public interface DirectPipelineOptions extends - ApplicationNameOptions, BigQueryOptions, GcsOptions, GcpOptions, - PipelineOptions, StreamingOptions { - - /** - * The random seed to use for pseudorandom behaviors in the {@link DirectPipelineRunner}. - * If not explicitly specified, a random seed will be generated. - */ - @JsonIgnore - @Description("The random seed to use for pseudorandom behaviors in the DirectPipelineRunner." - + " If not explicitly specified, a random seed will be generated.") - Long getDirectPipelineRunnerRandomSeed(); - void setDirectPipelineRunnerRandomSeed(Long value); - - /** - * Controls whether the runner should ensure that all of the elements of - * the pipeline, such as DoFns, can be serialized. - */ - @JsonIgnore - @Description("Controls whether the runner should ensure that all of the elements of the " - + "pipeline, such as DoFns, can be serialized.") - @Default.Boolean(true) - boolean isTestSerializability(); - void setTestSerializability(boolean testSerializability); - - /** - * Controls whether the runner should ensure that all of the elements of - * every {@link PCollection} can be encoded using the appropriate - * {@link Coder}. - */ - @JsonIgnore - @Description("Controls whether the runner should ensure that all of the elements of every " - + "PCollection can be encoded using the appropriate Coder.") - @Default.Boolean(true) - boolean isTestEncodability(); - void setTestEncodability(boolean testEncodability); - - /** - * Controls whether the runner should randomize the order of each - * {@link PCollection}. - */ - @JsonIgnore - @Description("Controls whether the runner should randomize the order of each PCollection.") - @Default.Boolean(true) - boolean isTestUnorderedness(); - void setTestUnorderedness(boolean testUnorderedness); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcpOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcpOptions.java deleted file mode 100644 index bfc2f839dd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcpOptions.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants; -import com.google.cloud.dataflow.sdk.util.CredentialFactory; -import com.google.cloud.dataflow.sdk.util.GcpCredentialFactory; -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.io.Files; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Options used to configure Google Cloud Platform project and credentials. - * - *

              These options configure which of the following three different mechanisms for obtaining a - * credential are used: - *

                - *
              1. - * It can fetch the - * - * application default credentials. - *
              2. - *
              3. - * The user can specify a client secrets file and go through the OAuth2 - * webflow. The credential will then be cached in the user's home - * directory for reuse. - *
              4. - *
              5. - * The user can specify a file containing a service account private key along - * with the service account name. - *
              6. - *
              - * - *

              The default mechanism is to use the - * - * application default credentials. The other options can be - * used by setting the corresponding properties. - */ -@Description("Options used to configure Google Cloud Platform project and credentials.") -public interface GcpOptions extends GoogleApiDebugOptions, PipelineOptions { - /** - * Project id to use when launching jobs. - */ - @Description("Project id. Required when running a Dataflow in the cloud. " - + "See https://cloud.google.com/storage/docs/projects for further details.") - @Default.InstanceFactory(DefaultProjectFactory.class) - String getProject(); - void setProject(String value); - - /** - * This option controls which file to use when attempting to create the credentials using the - * service account method. - * - *

              This option if specified, needs be combined with the - * {@link GcpOptions#getServiceAccountName() serviceAccountName}. - */ - @JsonIgnore - @Description("Controls which file to use when attempting to create the credentials " - + "using the service account method. This option if specified, needs to be combined with " - + "the serviceAccountName option.") - String getServiceAccountKeyfile(); - void setServiceAccountKeyfile(String value); - - /** - * This option controls which service account to use when attempting to create the credentials - * using the service account method. - * - *

              This option if specified, needs be combined with the - * {@link GcpOptions#getServiceAccountKeyfile() serviceAccountKeyfile}. - */ - @JsonIgnore - @Description("Controls which service account to use when attempting to create the credentials " - + "using the service account method. This option if specified, needs to be combined with " - + "the serviceAccountKeyfile option.") - String getServiceAccountName(); - void setServiceAccountName(String value); - - /** - * This option controls which file to use when attempting to create the credentials - * using the OAuth 2 webflow. After the OAuth2 webflow, the credentials will be stored - * within credentialDir. - */ - @JsonIgnore - @Description("This option controls which file to use when attempting to create the credentials " - + "using the OAuth 2 webflow. After the OAuth2 webflow, the credentials will be stored " - + "within credentialDir.") - String getSecretsFile(); - void setSecretsFile(String value); - - /** - * This option controls which credential store to use when creating the credentials - * using the OAuth 2 webflow. - */ - @Description("This option controls which credential store to use when creating the credentials " - + "using the OAuth 2 webflow.") - @Default.String("cloud_dataflow") - String getCredentialId(); - void setCredentialId(String value); - - /** - * Directory for storing dataflow credentials after execution of the OAuth 2 webflow. Defaults - * to using the $HOME/.store/data-flow directory. - */ - @Description("Directory for storing dataflow credentials after execution of the OAuth 2 webflow. " - + "Defaults to using the $HOME/.store/data-flow directory.") - @Default.InstanceFactory(CredentialDirFactory.class) - String getCredentialDir(); - void setCredentialDir(String value); - - /** - * Returns the default credential directory of ${user.home}/.store/data-flow. - */ - class CredentialDirFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - File home = new File(System.getProperty("user.home")); - File store = new File(home, ".store"); - File dataflow = new File(store, "data-flow"); - return dataflow.getPath(); - } - } - - /** - * The class of the credential factory that should be created and used to create - * credentials. If gcpCredential has not been set explicitly, an instance of this class will - * be constructed and used as a credential factory. - */ - @Description("The class of the credential factory that should be created and used to create " - + "credentials. If gcpCredential has not been set explicitly, an instance of this class will " - + "be constructed and used as a credential factory.") - @Default.Class(GcpCredentialFactory.class) - Class getCredentialFactoryClass(); - void setCredentialFactoryClass( - Class credentialFactoryClass); - - /** - * The credential instance that should be used to authenticate against GCP services. - * If no credential has been set explicitly, the default is to use the instance factory - * that constructs a credential based upon the currently set credentialFactoryClass. - */ - @JsonIgnore - @Description("The credential instance that should be used to authenticate against GCP services. " - + "If no credential has been set explicitly, the default is to use the instance factory " - + "that constructs a credential based upon the currently set credentialFactoryClass.") - @Default.InstanceFactory(GcpUserCredentialsFactory.class) - @Hidden - Credential getGcpCredential(); - void setGcpCredential(Credential value); - - /** - * Attempts to infer the default project based upon the environment this application - * is executing within. Currently this only supports getting the default project from gcloud. - */ - class DefaultProjectFactory implements DefaultValueFactory { - private static final Logger LOG = LoggerFactory.getLogger(DefaultProjectFactory.class); - - @Override - public String create(PipelineOptions options) { - try { - File configFile; - if (getEnvironment().containsKey("CLOUDSDK_CONFIG")) { - configFile = new File(getEnvironment().get("CLOUDSDK_CONFIG"), "properties"); - } else if (isWindows() && getEnvironment().containsKey("APPDATA")) { - configFile = new File(getEnvironment().get("APPDATA"), "gcloud/properties"); - } else { - // New versions of gcloud use this file - configFile = new File( - System.getProperty("user.home"), - ".config/gcloud/configurations/config_default"); - if (!configFile.exists()) { - // Old versions of gcloud use this file - configFile = new File(System.getProperty("user.home"), ".config/gcloud/properties"); - } - } - String section = null; - Pattern projectPattern = Pattern.compile("^project\\s*=\\s*(.*)$"); - Pattern sectionPattern = Pattern.compile("^\\[(.*)\\]$"); - for (String line : Files.readLines(configFile, StandardCharsets.UTF_8)) { - line = line.trim(); - if (line.isEmpty() || line.startsWith(";")) { - continue; - } - Matcher matcher = sectionPattern.matcher(line); - if (matcher.matches()) { - section = matcher.group(1); - } else if (section == null || section.equals("core")) { - matcher = projectPattern.matcher(line); - if (matcher.matches()) { - String project = matcher.group(1).trim(); - LOG.info("Inferred default GCP project '{}' from gcloud. If this is the incorrect " - + "project, please cancel this Pipeline and specify the command-line " - + "argument --project.", project); - return project; - } - } - } - } catch (IOException expected) { - LOG.debug("Failed to find default project.", expected); - } - // return null if can't determine - return null; - } - - /** - * Returns true if running on the Windows OS. - */ - private static boolean isWindows() { - return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"); - } - - /** - * Used to mock out getting environment variables. - */ - @VisibleForTesting - Map getEnvironment() { - return System.getenv(); - } - } - - /** - * Attempts to load the GCP credentials. See - * {@link CredentialFactory#getCredential()} for more details. - */ - class GcpUserCredentialsFactory implements DefaultValueFactory { - @Override - public Credential create(PipelineOptions options) { - GcpOptions gcpOptions = options.as(GcpOptions.class); - try { - CredentialFactory factory = InstanceBuilder.ofType(CredentialFactory.class) - .fromClass(gcpOptions.getCredentialFactoryClass()) - .fromFactoryMethod("fromOptions") - .withArg(PipelineOptions.class, options) - .build(); - return factory.getCredential(); - } catch (IOException | GeneralSecurityException e) { - throw new RuntimeException("Unable to obtain credential", e); - } - } - } - - /** - * The token server URL to use for OAuth 2 authentication. Normally, the default is sufficient, - * but some specialized use cases may want to override this value. - */ - @Description("The token server URL to use for OAuth 2 authentication. Normally, the default " - + "is sufficient, but some specialized use cases may want to override this value.") - @Default.String(GoogleOAuthConstants.TOKEN_SERVER_URL) - @Hidden - String getTokenServerUrl(); - void setTokenServerUrl(String value); - - /** - * The authorization server URL to use for OAuth 2 authentication. Normally, the default is - * sufficient, but some specialized use cases may want to override this value. - */ - @Description("The authorization server URL to use for OAuth 2 authentication. Normally, the " - + "default is sufficient, but some specialized use cases may want to override this value.") - @Default.String(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL) - @Hidden - String getAuthorizationServerEncodedUrl(); - void setAuthorizationServerEncodedUrl(String value); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcsOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcsOptions.java deleted file mode 100644 index 9070cd8206..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GcsOptions.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.cloud.dataflow.sdk.util.AppEngineEnvironment; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel; -import com.google.common.util.concurrent.MoreExecutors; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * Options used to configure Google Cloud Storage. - */ -public interface GcsOptions extends - ApplicationNameOptions, GcpOptions, PipelineOptions { - /** - * The GcsUtil instance that should be used to communicate with Google Cloud Storage. - */ - @JsonIgnore - @Description("The GcsUtil instance that should be used to communicate with Google Cloud Storage.") - @Default.InstanceFactory(GcsUtil.GcsUtilFactory.class) - @Hidden - GcsUtil getGcsUtil(); - void setGcsUtil(GcsUtil value); - - /** - * The ExecutorService instance to use to create threads, can be overridden to specify an - * ExecutorService that is compatible with the users environment. If unset, the - * default is to create an ExecutorService with an unbounded number of threads; this - * is compatible with Google AppEngine. - */ - @JsonIgnore - @Description("The ExecutorService instance to use to create multiple threads. Can be overridden " - + "to specify an ExecutorService that is compatible with the users environment. If unset, " - + "the default is to create an ExecutorService with an unbounded number of threads; this " - + "is compatible with Google AppEngine.") - @Default.InstanceFactory(ExecutorServiceFactory.class) - @Hidden - ExecutorService getExecutorService(); - void setExecutorService(ExecutorService value); - - /** - * GCS endpoint to use. If unspecified, uses the default endpoint. - */ - @JsonIgnore - @Hidden - @Description("The URL for the GCS API.") - String getGcsEndpoint(); - void setGcsEndpoint(String value); - - /** - * The buffer size (in bytes) to use when uploading files to GCS. Please see the documentation for - * {@link AbstractGoogleAsyncWriteChannel#setUploadBufferSize} for more information on the - * restrictions and performance implications of this value. - */ - @Description("The buffer size (in bytes) to use when uploading files to GCS. Please see the " - + "documentation for AbstractGoogleAsyncWriteChannel.setUploadBufferSize for more " - + "information on the restrictions and performance implications of this value.\n\n" - + "https://github.com/GoogleCloudPlatform/bigdata-interop/blob/master/util/src/main/java/" - + "com/google/cloud/hadoop/util/AbstractGoogleAsyncWriteChannel.java") - Integer getGcsUploadBufferSizeBytes(); - void setGcsUploadBufferSizeBytes(Integer bytes); - - /** - * Returns the default {@link ExecutorService} to use within the Dataflow SDK. The - * {@link ExecutorService} is compatible with AppEngine. - */ - class ExecutorServiceFactory implements DefaultValueFactory { - @SuppressWarnings("deprecation") // IS_APP_ENGINE is deprecated for internal use only. - @Override - public ExecutorService create(PipelineOptions options) { - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); - threadFactoryBuilder.setThreadFactory(MoreExecutors.platformThreadFactory()); - if (!AppEngineEnvironment.IS_APP_ENGINE) { - // AppEngine doesn't allow modification of threads to be daemon threads. - threadFactoryBuilder.setDaemon(true); - } - /* The SDK requires an unbounded thread pool because a step may create X writers - * each requiring their own thread to perform the writes otherwise a writer may - * block causing deadlock for the step because the writers buffer is full. - * Also, the MapTaskExecutor launches the steps in reverse order and completes - * them in forward order thus requiring enough threads so that each step's writers - * can be active. - */ - return new ThreadPoolExecutor( - 0, Integer.MAX_VALUE, // Allow an unlimited number of re-usable threads. - Long.MAX_VALUE, TimeUnit.NANOSECONDS, // Keep non-core threads alive forever. - new SynchronousQueue(), - threadFactoryBuilder.build()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptions.java deleted file mode 100644 index 9b86e7fb2b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptions.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.api.client.googleapis.services.AbstractGoogleClient; -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * These options configure debug settings for Google API clients created within the Dataflow SDK. - */ -public interface GoogleApiDebugOptions extends PipelineOptions { - /** - * This option enables tracing of API calls to Google services used within the - * Dataflow SDK. Values are expected in JSON format {"ApiName":"TraceDestination",...} - * where the {@code ApiName} represents the request classes canonical name. The - * {@code TraceDestination} is a logical trace consumer to whom the trace will be reported. - * Typically, "producer" is the right destination to use: this makes API traces available to the - * team offering the API. Note that by enabling this option, the contents of the requests to and - * from Google Cloud services will be made available to Google. For example, by specifying - * {"Dataflow":"producer"}, all calls to the Dataflow service will be made available - * to Google, specifically to the Google Cloud Dataflow team. - */ - @Description("This option enables tracing of API calls to Google services used within the " - + "Dataflow SDK. Values are expected in JSON format {\"ApiName\":\"TraceDestination\",...} " - + "where the ApiName represents the request classes canonical name. The TraceDestination is " - + "a logical trace consumer to whom the trace will be reported. Typically, \"producer\" is " - + "the right destination to use: this makes API traces available to the team offering the " - + "API. Note that by enabling this option, the contents of the requests to and from " - + "Google Cloud services will be made available to Google. For example, by specifying " - + "{\"Dataflow\":\"producer\"}, all calls to the Dataflow service will be made available to " - + "Google, specifically to the Google Cloud Dataflow team.") - GoogleApiTracer getGoogleApiTrace(); - void setGoogleApiTrace(GoogleApiTracer commands); - - /** - * A {@link GoogleClientRequestInitializer} that adds the trace destination to Google API calls. - */ - class GoogleApiTracer extends HashMap - implements GoogleClientRequestInitializer { - /** - * Creates a {@link GoogleApiTracer} that sets the trace destination on all - * calls that match the given client type. - */ - public GoogleApiTracer addTraceFor(AbstractGoogleClient client, String traceDestination) { - put(client.getClass().getCanonicalName(), traceDestination); - return this; - } - - /** - * Creates a {@link GoogleApiTracer} that sets the trace {@code traceDestination} on all - * calls that match for the given request type. - */ - public GoogleApiTracer addTraceFor( - AbstractGoogleClientRequest request, String traceDestination) { - put(request.getClass().getCanonicalName(), traceDestination); - return this; - } - - @Override - public void initialize(AbstractGoogleClientRequest request) throws IOException { - for (Map.Entry entry : this.entrySet()) { - if (request.getClass().getCanonicalName().contains(entry.getKey())) { - request.set("$trace", entry.getValue()); - } - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Hidden.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Hidden.java deleted file mode 100644 index 6a487eb2f5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Hidden.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Methods and/or interfaces annotated with {@code @Hidden} will be suppressed from - * being output when {@code --help} is specified on the command-line. - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface Hidden { -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java deleted file mode 100644 index 06fec4e453..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionSpec.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.auto.value.AutoValue; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.lang.reflect.Method; - -/** - * For internal use. Specification for an option defined in a {@link PipelineOptions} interface. - */ -@AutoValue -abstract class PipelineOptionSpec { - static PipelineOptionSpec of(Class clazz, String name, Method getter) { - return new AutoValue_PipelineOptionSpec(clazz, name, getter); - } - - /** - * The {@link PipelineOptions} interface which defines this {@link PipelineOptionSpec}. - */ - abstract Class getDefiningInterface(); - - /** - * Name of the property. - */ - abstract String getName(); - - /** - * The getter method for this property. - */ - abstract Method getGetterMethod(); - - /** - * Whether the option should be serialized. Uses the {@link JsonIgnore} annotation. - */ - boolean shouldSerialize() { - return !getGetterMethod().isAnnotationPresent(JsonIgnore.class); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java deleted file mode 100644 index 99eac3d7b3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptions.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.auto.service.AutoService; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.options.GoogleApiDebugOptions.GoogleApiTracer; -import com.google.cloud.dataflow.sdk.options.ProxyInvocationHandler.Deserializer; -import com.google.cloud.dataflow.sdk.options.ProxyInvocationHandler.Serializer; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.Context; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import java.lang.reflect.Proxy; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.concurrent.atomic.AtomicLong; -import javax.annotation.concurrent.ThreadSafe; - -/** - * PipelineOptions are used to configure Pipelines. You can extend {@link PipelineOptions} - * to create custom configuration options specific to your {@link Pipeline}, - * for both local execution and execution via a {@link PipelineRunner}. - * - *

              {@link PipelineOptions} and their subinterfaces represent a collection of properties - * which can be manipulated in a type safe manner. {@link PipelineOptions} is backed by a - * dynamic {@link Proxy} which allows for type safe manipulation of properties in an extensible - * fashion through plain old Java interfaces. - * - *

              {@link PipelineOptions} can be created with {@link PipelineOptionsFactory#create()} - * and {@link PipelineOptionsFactory#as(Class)}. They can be created - * from command-line arguments with {@link PipelineOptionsFactory#fromArgs(String[])}. - * They can be converted to another type by invoking {@link PipelineOptions#as(Class)} and - * can be accessed from within a {@link DoFn} by invoking - * {@link Context#getPipelineOptions()}. - * - *

              For example: - *

              {@code
              - * // The most common way to construct PipelineOptions is via command-line argument parsing:
              - * public static void main(String[] args) {
              - *   // Will parse the arguments passed into the application and construct a PipelineOptions
              - *   // Note that --help will print registered options, and --help=PipelineOptionsClassName
              - *   // will print out usage for the specific class.
              - *   PipelineOptions options =
              - *       PipelineOptionsFactory.fromArgs(args).create();
              - *
              - *   Pipeline p = Pipeline.create(options);
              - *   ...
              - *   p.run();
              - * }
              - *
              - * // To create options for the DirectPipeline:
              - * DirectPipelineOptions directPipelineOptions =
              - *     PipelineOptionsFactory.as(DirectPipelineOptions.class);
              - * directPipelineOptions.setStreaming(true);
              - *
              - * // To cast from one type to another using the as(Class) method:
              - * DataflowPipelineOptions dataflowPipelineOptions =
              - *     directPipelineOptions.as(DataflowPipelineOptions.class);
              - *
              - * // Options for the same property are shared between types
              - * // The statement below will print out "true"
              - * System.out.println(dataflowPipelineOptions.isStreaming());
              - *
              - * // Prints out registered options.
              - * PipelineOptionsFactory.printHelp(System.out);
              - *
              - * // Prints out options which are available to be set on DataflowPipelineOptions
              - * PipelineOptionsFactory.printHelp(System.out, DataflowPipelineOptions.class);
              - * }
              - * - *

              Defining Your Own PipelineOptions

              - * - *

              Defining your own {@link PipelineOptions} is the way for you to make configuration - * options available for both local execution and execution via a {@link PipelineRunner}. - * By having PipelineOptionsFactory as your command-line interpreter, you will provide - * a standardized way for users to interact with your application via the command-line. - * - *

              To define your own {@link PipelineOptions}, you create an interface which - * extends {@link PipelineOptions} and define getter/setter pairs. These - * getter/setter pairs define a collection of - * - * JavaBean properties. - * - *

              For example: - *

              {@code
              - *  // Creates a user defined property called "myProperty"
              - *  public interface MyOptions extends PipelineOptions {
              - *    String getMyProperty();
              - *    void setMyProperty(String value);
              - *  }
              - * }
              - * - *

              Note: Please see the section on Registration below when using custom property types. - * - *

              Restrictions

              - * - *

              Since PipelineOptions can be "cast" to multiple types dynamically using - * {@link PipelineOptions#as(Class)}, a property must conform to the following set of restrictions: - *

                - *
              • Any property with the same name must have the same return type for all derived - * interfaces of {@link PipelineOptions}. - *
              • Every bean property of any interface derived from {@link PipelineOptions} must have a - * getter and setter method. - *
              • Every method must conform to being a getter or setter for a JavaBean. - *
              • The derived interface of {@link PipelineOptions} must be composable with every interface - * part registered with the PipelineOptionsFactory. - *
              • Only getters may be annotated with {@link JsonIgnore @JsonIgnore}. - *
              • If any getter is annotated with {@link JsonIgnore @JsonIgnore}, then all getters for - * this property must be annotated with {@link JsonIgnore @JsonIgnore}. - *
              - * - *

              Annotations For PipelineOptions

              - * - * {@link Description @Description} can be used to annotate an interface or a getter - * with useful information which is output when {@code --help} - * is invoked via {@link PipelineOptionsFactory#fromArgs(String[])}. - * - *

              {@link Default @Default} represents a set of annotations that can be used to annotate getter - * properties on {@link PipelineOptions} with information representing the default value to be - * returned if no value is specified. Any default implementation (using the {@code default} keyword) - * is ignored. - * - *

              {@link Hidden @Hidden} hides an option from being listed when {@code --help} - * is invoked via {@link PipelineOptionsFactory#fromArgs(String[])}. - * - *

              {@link Validation @Validation} represents a set of annotations that can be used to annotate - * getter properties on {@link PipelineOptions} with information representing the validation - * criteria to be used when validating with the {@link PipelineOptionsValidator}. Validation - * will be performed if during construction of the {@link PipelineOptions}, - * {@link PipelineOptionsFactory#withValidation()} is invoked. - * - *

              {@link JsonIgnore @JsonIgnore} is used to prevent a property from being serialized and - * available during execution of {@link DoFn}. See the Serialization section below for more - * details. - * - *

              Registration Of PipelineOptions

              - * - *

              Registration of {@link PipelineOptions} by an application guarantees that the - * {@link PipelineOptions} is composable during execution of their {@link Pipeline} and - * meets the restrictions listed above or will fail during registration. Registration - * also lists the registered {@link PipelineOptions} when {@code --help} - * is invoked via {@link PipelineOptionsFactory#fromArgs(String[])}. - * - *

              Registration can be performed by invoking {@link PipelineOptionsFactory#register} within - * a users application or via automatic registration by creating a {@link ServiceLoader} entry - * and a concrete implementation of the {@link PipelineOptionsRegistrar} interface. - * - *

              It is optional but recommended to use one of the many build time tools such as - * {@link AutoService} to generate the necessary META-INF files automatically. - * - *

              A list of registered options can be fetched from - * {@link PipelineOptionsFactory#getRegisteredOptions()}. - * - *

              Serialization Of PipelineOptions

              - * - * {@link PipelineRunner}s require support for options to be serialized. Each property - * within {@link PipelineOptions} must be able to be serialized using Jackson's - * {@link ObjectMapper} or the getter method for the property annotated with - * {@link JsonIgnore @JsonIgnore}. - * - *

              Jackson supports serialization of many types and supports a useful set of - * annotations to aid in - * serialization of custom types. We point you to the public - * Jackson documentation when attempting - * to add serialization support for your custom types. See {@link GoogleApiTracer} for an - * example using the Jackson annotations to serialize and deserialize a custom type. - * - *

              Note: It is an error to have the same property available in multiple interfaces with only - * some of them being annotated with {@link JsonIgnore @JsonIgnore}. It is also an error to mark a - * setter for a property with {@link JsonIgnore @JsonIgnore}. - */ -@JsonSerialize(using = Serializer.class) -@JsonDeserialize(using = Deserializer.class) -@ThreadSafe -public interface PipelineOptions extends HasDisplayData { - /** - * Transforms this object into an object of type {@code } saving each property - * that has been manipulated. {@code } must extend {@link PipelineOptions}. - * - *

              If {@code } is not registered with the {@link PipelineOptionsFactory}, then we - * attempt to verify that {@code } is composable with every interface that this - * instance of the {@code PipelineOptions} has seen. - * - * @param kls The class of the type to transform to. - * @return An object of type kls. - */ - T as(Class kls); - - /** - * Makes a deep clone of this object, and transforms the cloned object into the specified - * type {@code kls}. See {@link #as} for more information about the conversion. - * - *

              Properties that are marked with {@code @JsonIgnore} will not be cloned. - */ - T cloneAs(Class kls); - - /** - * The pipeline runner that will be used to execute the pipeline. - * For registered runners, the class name can be specified, otherwise the fully - * qualified name needs to be specified. - */ - @Validation.Required - @Description("The pipeline runner that will be used to execute the pipeline. " - + "For registered runners, the class name can be specified, otherwise the fully " - + "qualified name needs to be specified.") - @Default.Class(DirectPipelineRunner.class) - Class> getRunner(); - void setRunner(Class> kls); - - /** - * Enumeration of the possible states for a given check. - */ - enum CheckEnabled { - OFF, - WARNING, - ERROR; - } - - /** - * Whether to check for stable unique names on each transform. This is necessary to - * support updating of pipelines. - */ - @Validation.Required - @Description("Whether to check for stable unique names on each transform. This is necessary to " - + "support updating of pipelines.") - @Default.Enum("WARNING") - CheckEnabled getStableUniqueNames(); - void setStableUniqueNames(CheckEnabled enabled); - - /** - * A pipeline level default location for storing temporary files. - * - *

              This can be a path of any file system. - * - *

              {@link #getTempLocation()} can be used as a default location in other - * {@link PipelineOptions}. - * - *

              If it is unset, {@link PipelineRunner} can override it. - */ - @Description("A pipeline level default location for storing temporary files.") - String getTempLocation(); - void setTempLocation(String value); - - /** - * Returns a map of properties which correspond to {@link RuntimeValueProvider}, - * keyed by the property name. The value is a map containing type and default - * information. - */ - Map> outputRuntimeOptions(); - - /** - * Provides a unique ID for this {@link PipelineOptions} object, assigned at graph - * construction time. - */ - @Hidden - @Default.InstanceFactory(AtomicLongFactory.class) - Long getOptionsId(); - void setOptionsId(Long id); - - /** - * {@link DefaultValueFactory} which supplies an ID that is guaranteed to be unique - * within the given process. - */ - class AtomicLongFactory implements DefaultValueFactory { - private static final AtomicLong NEXT_ID = new AtomicLong(0); - - @Override - public Long create(PipelineOptions options) { - return NEXT_ID.getAndIncrement(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java deleted file mode 100644 index 54e4d87a7d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactory.java +++ /dev/null @@ -1,1611 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.options.Validation.Required; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.base.Strings; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Iterators; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Ordering; -import com.google.common.collect.RowSortedTable; -import com.google.common.collect.Sets; -import com.google.common.collect.SortedSetMultimap; -import com.google.common.collect.TreeBasedTable; -import com.google.common.collect.TreeMultimap; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.io.IOException; -import java.io.PrintStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Proxy; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.ServiceLoader; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -import javax.annotation.Nullable; - -/** - * Constructs a {@link PipelineOptions} or any derived interface that is composable to any other - * derived interface of {@link PipelineOptions} via the {@link PipelineOptions#as} method. Being - * able to compose one derived interface of {@link PipelineOptions} to another has the following - * restrictions: - *

                - *
              • Any property with the same name must have the same return type for all derived interfaces - * of {@link PipelineOptions}. - *
              • Every bean property of any interface derived from {@link PipelineOptions} must have a - * getter and setter method. - *
              • Every method must conform to being a getter or setter for a JavaBean. - *
              • The derived interface of {@link PipelineOptions} must be composable with every interface - * registered with this factory. - *
              - * - *

              See the JavaBeans - * specification for more details as to what constitutes a property. - */ -public class PipelineOptionsFactory { - /** - * Creates and returns an object that implements {@link PipelineOptions}. - * This sets the {@link ApplicationNameOptions#getAppName() "appName"} to the calling - * {@link Class#getSimpleName() classes simple name}. - * - * @return An object that implements {@link PipelineOptions}. - */ - public static PipelineOptions create() { - return new Builder().as(PipelineOptions.class); - } - - /** - * Creates and returns an object that implements {@code }. - * This sets the {@link ApplicationNameOptions#getAppName() "appName"} to the calling - * {@link Class#getSimpleName() classes simple name}. - * - *

              Note that {@code } must be composable with every registered interface with this factory. - * See {@link PipelineOptionsFactory#validateWellFormed(Class, Set)} for more details. - * - * @return An object that implements {@code }. - */ - public static T as(Class klass) { - return new Builder().as(klass); - } - - /** - * Sets the command line arguments to parse when constructing the {@link PipelineOptions}. - * - *

              Example GNU style command line arguments: - *

              -   *   --project=MyProject (simple property, will set the "project" property to "MyProject")
              -   *   --readOnly=true (for boolean properties, will set the "readOnly" property to "true")
              -   *   --readOnly (shorthand for boolean properties, will set the "readOnly" property to "true")
              -   *   --x=1 --x=2 --x=3 (list style simple property, will set the "x" property to [1, 2, 3])
              -   *   --x=1,2,3 (shorthand list style simple property, will set the "x" property to [1, 2, 3])
              -   *   --complexObject='{"key1":"value1",...} (JSON format for all other complex types)
              -   * 
              - * - *

              Simple properties are able to bound to {@link String}, {@link Class}, enums and Java - * primitives {@code boolean}, {@code byte}, {@code short}, {@code int}, {@code long}, - * {@code float}, {@code double} and their primitive wrapper classes. - * - *

              Simple list style properties are able to be bound to {@code boolean[]}, {@code char[]}, - * {@code short[]}, {@code int[]}, {@code long[]}, {@code float[]}, {@code double[]}, - * {@code Class[]}, enum arrays, {@code String[]}, and {@code List}. - * - *

              JSON format is required for all other types. - * - *

              By default, strict parsing is enabled and arguments must conform to be either - * {@code --booleanArgName} or {@code --argName=argValue}. Strict parsing can be disabled with - * {@link Builder#withoutStrictParsing()}. Empty or null arguments will be ignored whether - * or not strict parsing is enabled. - * - *

              Help information can be output to {@link System#out} by specifying {@code --help} as an - * argument. After help is printed, the application will exit. Specifying only {@code --help} - * will print out the list of - * {@link PipelineOptionsFactory#getRegisteredOptions() registered options} - * by invoking {@link PipelineOptionsFactory#printHelp(PrintStream)}. Specifying - * {@code --help=PipelineOptionsClassName} will print out detailed usage information about the - * specifically requested PipelineOptions by invoking - * {@link PipelineOptionsFactory#printHelp(PrintStream, Class)}. - */ - public static Builder fromArgs(String[] args) { - return new Builder().fromArgs(args); - } - - /** - * After creation we will validate that {@code } conforms to all the - * validation criteria. See - * {@link PipelineOptionsValidator#validate(Class, PipelineOptions)} for more details about - * validation. - */ - public Builder withValidation() { - return new Builder().withValidation(); - } - - /** A fluent {@link PipelineOptions} builder. */ - public static class Builder { - private final String defaultAppName; - private final String[] args; - private final boolean validation; - private final boolean strictParsing; - - // Do not allow direct instantiation - private Builder() { - this(null, false, true); - } - - private Builder(String[] args, boolean validation, - boolean strictParsing) { - this.defaultAppName = findCallersClassName(); - this.args = args; - this.validation = validation; - this.strictParsing = strictParsing; - } - - /** - * Sets the command line arguments to parse when constructing the {@link PipelineOptions}. - * - *

              Example GNU style command line arguments: - *

              -     *   --project=MyProject (simple property, will set the "project" property to "MyProject")
              -     *   --readOnly=true (for boolean properties, will set the "readOnly" property to "true")
              -     *   --readOnly (shorthand for boolean properties, will set the "readOnly" property to "true")
              -     *   --x=1 --x=2 --x=3 (list style simple property, will set the "x" property to [1, 2, 3])
              -     *   --x=1,2,3 (shorthand list style simple property, will set the "x" property to [1, 2, 3])
              -     *   --complexObject='{"key1":"value1",...} (JSON format for all other complex types)
              -     * 
              - * - *

              Simple properties are able to bound to {@link String}, {@link Class}, enums and Java - * primitives {@code boolean}, {@code byte}, {@code short}, {@code int}, {@code long}, - * {@code float}, {@code double} and their primitive wrapper classes. - * - *

              Simple list style properties are able to be bound to {@code boolean[]}, {@code char[]}, - * {@code short[]}, {@code int[]}, {@code long[]}, {@code float[]}, {@code double[]}, - * {@code Class[]}, enum arrays, {@code String[]}, and {@code List}. - * - *

              JSON format is required for all other types. - * - *

              By default, strict parsing is enabled and arguments must conform to be either - * {@code --booleanArgName} or {@code --argName=argValue}. Strict parsing can be disabled with - * {@link Builder#withoutStrictParsing()}. Empty or null arguments will be ignored whether - * or not strict parsing is enabled. - * - *

              Help information can be output to {@link System#out} by specifying {@code --help} as an - * argument. After help is printed, the application will exit. Specifying only {@code --help} - * will print out the list of - * {@link PipelineOptionsFactory#getRegisteredOptions() registered options} - * by invoking {@link PipelineOptionsFactory#printHelp(PrintStream)}. Specifying - * {@code --help=PipelineOptionsClassName} will print out detailed usage information about the - * specifically requested PipelineOptions by invoking - * {@link PipelineOptionsFactory#printHelp(PrintStream, Class)}. - */ - public Builder fromArgs(String[] args) { - checkNotNull(args, "Arguments should not be null."); - return new Builder(args, validation, strictParsing); - } - - /** - * After creation we will validate that {@link PipelineOptions} conforms to all the - * validation criteria from {@code }. See - * {@link PipelineOptionsValidator#validate(Class, PipelineOptions)} for more details about - * validation. - */ - public Builder withValidation() { - return new Builder(args, true, strictParsing); - } - - /** - * During parsing of the arguments, we will skip over improperly formatted and unknown - * arguments. - */ - public Builder withoutStrictParsing() { - return new Builder(args, validation, false); - } - - /** - * Creates and returns an object that implements {@link PipelineOptions} using the values - * configured on this builder during construction. - * - * @return An object that implements {@link PipelineOptions}. - */ - public PipelineOptions create() { - return as(PipelineOptions.class); - } - - /** - * Creates and returns an object that implements {@code } using the values configured on - * this builder during construction. - * - *

              Note that {@code } must be composable with every registered interface with this - * factory. See {@link PipelineOptionsFactory#validateWellFormed(Class, Set)} for more - * details. - * - * @return An object that implements {@code }. - */ - public T as(Class klass) { - Map initialOptions = Maps.newHashMap(); - - // Attempt to parse the arguments into the set of initial options to use - if (args != null) { - ListMultimap options = parseCommandLine(args, strictParsing); - LOG.debug("Provided Arguments: {}", options); - printHelpUsageAndExitIfNeeded(options, System.out, true /* exit */); - initialOptions = parseObjects(klass, options, strictParsing); - } - - // Create our proxy - ProxyInvocationHandler handler = new ProxyInvocationHandler(initialOptions); - T t = handler.as(klass); - - // Set the application name to the default if none was set. - ApplicationNameOptions appNameOptions = t.as(ApplicationNameOptions.class); - if (appNameOptions.getAppName() == null) { - appNameOptions.setAppName(defaultAppName); - } - - if (validation) { - PipelineOptionsValidator.validate(klass, t); - } - return t; - } - } - - /** - * Determines whether the generic {@code --help} was requested or help was - * requested for a specific class and invokes the appropriate - * {@link PipelineOptionsFactory#printHelp(PrintStream)} and - * {@link PipelineOptionsFactory#printHelp(PrintStream, Class)} variant. - * Prints to the specified {@link PrintStream}, and exits if requested. - * - *

              Visible for testing. - * {@code printStream} and {@code exit} used for testing. - */ - @SuppressWarnings("unchecked") - static boolean printHelpUsageAndExitIfNeeded(ListMultimap options, - PrintStream printStream, boolean exit) { - if (options.containsKey("help")) { - final String helpOption = Iterables.getOnlyElement(options.get("help")); - - // Print the generic help if only --help was specified. - if (Boolean.TRUE.toString().equals(helpOption)) { - printHelp(printStream); - if (exit) { - System.exit(0); - } else { - return true; - } - } - - // Otherwise attempt to print the specific help option. - try { - Class klass = Class.forName(helpOption); - if (!PipelineOptions.class.isAssignableFrom(klass)) { - throw new ClassNotFoundException("PipelineOptions of type " + klass + " not found."); - } - printHelp(printStream, (Class) klass); - } catch (ClassNotFoundException e) { - // If we didn't find an exact match, look for any that match the class name. - Iterable> matches = Iterables.filter( - getRegisteredOptions(), - new Predicate>() { - @Override - public boolean apply(Class input) { - if (helpOption.contains(".")) { - return input.getName().endsWith(helpOption); - } else { - return input.getSimpleName().equals(helpOption); - } - } - }); - try { - printHelp(printStream, Iterables.getOnlyElement(matches)); - } catch (NoSuchElementException exception) { - printStream.format("Unable to find option %s.%n", helpOption); - printHelp(printStream); - } catch (IllegalArgumentException exception) { - printStream.format("Multiple matches found for %s: %s.%n", helpOption, - Iterables.transform(matches, ReflectHelpers.CLASS_NAME)); - printHelp(printStream); - } - } - if (exit) { - System.exit(0); - } else { - return true; - } - } - return false; - } - - /** - * Returns the simple name of the calling class using the current threads stack. - */ - private static String findCallersClassName() { - Iterator elements = - Iterators.forArray(Thread.currentThread().getStackTrace()); - // First find the PipelineOptionsFactory/Builder class in the stack trace. - while (elements.hasNext()) { - StackTraceElement next = elements.next(); - if (PIPELINE_OPTIONS_FACTORY_CLASSES.contains(next.getClassName())) { - break; - } - } - // Then find the first instance after that is not the PipelineOptionsFactory/Builder class. - while (elements.hasNext()) { - StackTraceElement next = elements.next(); - if (!PIPELINE_OPTIONS_FACTORY_CLASSES.contains(next.getClassName())) { - try { - return Class.forName(next.getClassName()).getSimpleName(); - } catch (ClassNotFoundException e) { - break; - } - } - } - - return "unknown"; - } - - /** - * Stores the generated proxyClass and its respective {@link BeanInfo} object. - * - * @param The type of the proxyClass. - */ - static class Registration { - private final Class proxyClass; - private final List propertyDescriptors; - - public Registration(Class proxyClass, List beanInfo) { - this.proxyClass = proxyClass; - this.propertyDescriptors = beanInfo; - } - - List getPropertyDescriptors() { - return propertyDescriptors; - } - - Class getProxyClass() { - return proxyClass; - } - } - - private static final Set> SIMPLE_TYPES = ImmutableSet.>builder() - .add(boolean.class) - .add(Boolean.class) - .add(char.class) - .add(Character.class) - .add(short.class) - .add(Short.class) - .add(int.class) - .add(Integer.class) - .add(long.class) - .add(Long.class) - .add(float.class) - .add(Float.class) - .add(double.class) - .add(Double.class) - .add(String.class) - .add(Class.class).build(); - private static final Logger LOG = LoggerFactory.getLogger(PipelineOptionsFactory.class); - @SuppressWarnings("rawtypes") - private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; - private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final ClassLoader CLASS_LOADER; - private static final Map>> SUPPORTED_PIPELINE_RUNNERS; - - /** Classes that are used as the boundary in the stack trace to find the callers class name. */ - private static final Set PIPELINE_OPTIONS_FACTORY_CLASSES = - ImmutableSet.of(PipelineOptionsFactory.class.getName(), Builder.class.getName()); - - /** Methods that are ignored when validating the proxy class. */ - private static final Set IGNORED_METHODS; - - /** A predicate that checks if a method is synthetic via {@link Method#isSynthetic()}. */ - private static final Predicate NOT_SYNTHETIC_PREDICATE = - new Predicate() { - @Override - public boolean apply(Method input) { - return !input.isSynthetic(); - } - }; - - /** The set of options that have been registered and visible to the user. */ - private static final Set> REGISTERED_OPTIONS = - Sets.newConcurrentHashSet(); - - /** A cache storing a mapping from a given interface to its registration record. */ - private static final Map, Registration> INTERFACE_CACHE = - Maps.newConcurrentMap(); - - /** A cache storing a mapping from a set of interfaces to its registration record. */ - private static final Map>, Registration> COMBINED_CACHE = - Maps.newConcurrentMap(); - - /** The width at which options should be output. */ - private static final int TERMINAL_WIDTH = 80; - - /** - * Finds the appropriate {@code ClassLoader} to be used by the - * {@link ServiceLoader#load} call, which by default would use the context - * {@code ClassLoader}, which can be null. The fallback is as follows: context - * ClassLoader, class ClassLoader and finaly the system ClassLoader. - */ - static ClassLoader findClassLoader() { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader == null) { - classLoader = PipelineOptionsFactory.class.getClassLoader(); - } - if (classLoader == null) { - classLoader = ClassLoader.getSystemClassLoader(); - } - return classLoader; - } - - static { - try { - IGNORED_METHODS = ImmutableSet.builder() - .add(Object.class.getMethod("getClass")) - .add(Object.class.getMethod("wait")) - .add(Object.class.getMethod("wait", long.class)) - .add(Object.class.getMethod("wait", long.class, int.class)) - .add(Object.class.getMethod("notify")) - .add(Object.class.getMethod("notifyAll")) - .add(Proxy.class.getMethod("getInvocationHandler", Object.class)) - .build(); - } catch (NoSuchMethodException | SecurityException e) { - LOG.error("Unable to find expected method", e); - throw new ExceptionInInitializerError(e); - } - - CLASS_LOADER = findClassLoader(); - - // Store the list of all available pipeline runners. - ImmutableMap.Builder>> builder = - ImmutableMap.builder(); - Set pipelineRunnerRegistrars = - Sets.newTreeSet(ObjectsClassComparator.INSTANCE); - pipelineRunnerRegistrars.addAll( - Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class, CLASS_LOADER))); - for (PipelineRunnerRegistrar registrar : pipelineRunnerRegistrars) { - for (Class> klass : registrar.getPipelineRunners()) { - builder.put(klass.getSimpleName(), klass); - } - } - SUPPORTED_PIPELINE_RUNNERS = builder.build(); - initializeRegistry(); - } - - /** - * This registers the interface with this factory. This interface must conform to the following - * restrictions: - *

                - *
              • Any property with the same name must have the same return type for all derived - * interfaces of {@link PipelineOptions}. - *
              • Every bean property of any interface derived from {@link PipelineOptions} must have a - * getter and setter method. - *
              • Every method must conform to being a getter or setter for a JavaBean. - *
              • The derived interface of {@link PipelineOptions} must be composable with every interface - * registered with this factory. - *
              - * - * @param iface The interface object to manually register. - */ - public static synchronized void register(Class iface) { - checkNotNull(iface); - checkArgument(iface.isInterface(), "Only interface types are supported."); - - if (REGISTERED_OPTIONS.contains(iface)) { - return; - } - validateWellFormed(iface, REGISTERED_OPTIONS); - REGISTERED_OPTIONS.add(iface); - } - - /** - * Resets the set of interfaces registered with this factory to the default state. - * - * @see PipelineOptionsFactory#register(Class) - */ - @VisibleForTesting - static synchronized void resetRegistry() { - REGISTERED_OPTIONS.clear(); - initializeRegistry(); - } - - /** - * Load and register the list of all classes that extend PipelineOptions. - */ - private static void initializeRegistry() { - register(PipelineOptions.class); - Set pipelineOptionsRegistrars = - Sets.newTreeSet(ObjectsClassComparator.INSTANCE); - pipelineOptionsRegistrars.addAll( - Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class, CLASS_LOADER))); - for (PipelineOptionsRegistrar registrar : pipelineOptionsRegistrars) { - for (Class klass : registrar.getPipelineOptions()) { - register(klass); - } - } - } - - /** - * Validates that the interface conforms to the following: - *
                - *
              • Any property with the same name must have the same return type for all derived - * interfaces of {@link PipelineOptions}. - *
              • Every bean property of any interface derived from {@link PipelineOptions} must have a - * getter and setter method. - *
              • Every method must conform to being a getter or setter for a JavaBean. - *
              • The derived interface of {@link PipelineOptions} must be composable with every interface - * part of allPipelineOptionsClasses. - *
              • Only getters may be annotated with {@link JsonIgnore @JsonIgnore}. - *
              • If any getter is annotated with {@link JsonIgnore @JsonIgnore}, then all getters for - * this property must be annotated with {@link JsonIgnore @JsonIgnore}. - *
              - * - * @param iface The interface to validate. - * @param validatedPipelineOptionsInterfaces The set of validated pipeline options interfaces to - * validate against. - * @return A registration record containing the proxy class and bean info for iface. - */ - static synchronized Registration validateWellFormed( - Class iface, Set> validatedPipelineOptionsInterfaces) { - checkArgument(iface.isInterface(), "Only interface types are supported."); - - @SuppressWarnings("unchecked") - Set> combinedPipelineOptionsInterfaces = - FluentIterable.from(validatedPipelineOptionsInterfaces).append(iface).toSet(); - // Validate that the view of all currently passed in options classes is well formed. - if (!COMBINED_CACHE.containsKey(combinedPipelineOptionsInterfaces)) { - @SuppressWarnings("unchecked") - Class allProxyClass = - (Class) Proxy.getProxyClass(PipelineOptionsFactory.class.getClassLoader(), - combinedPipelineOptionsInterfaces.toArray(EMPTY_CLASS_ARRAY)); - try { - List propertyDescriptors = - validateClass(iface, validatedPipelineOptionsInterfaces, allProxyClass); - COMBINED_CACHE.put(combinedPipelineOptionsInterfaces, - new Registration(allProxyClass, propertyDescriptors)); - } catch (IntrospectionException e) { - throw new RuntimeException(e); - } - } - - // Validate that the local view of the class is well formed. - if (!INTERFACE_CACHE.containsKey(iface)) { - @SuppressWarnings({"rawtypes", "unchecked"}) - Class proxyClass = (Class) Proxy.getProxyClass( - PipelineOptionsFactory.class.getClassLoader(), new Class[] {iface}); - try { - List propertyDescriptors = - validateClass(iface, validatedPipelineOptionsInterfaces, proxyClass); - INTERFACE_CACHE.put(iface, - new Registration(proxyClass, propertyDescriptors)); - } catch (IntrospectionException e) { - throw new RuntimeException(e); - } - } - @SuppressWarnings("unchecked") - Registration result = (Registration) INTERFACE_CACHE.get(iface); - return result; - } - - public static Set> getRegisteredOptions() { - return Collections.unmodifiableSet(REGISTERED_OPTIONS); - } - - /** - * Outputs the set of registered options with the PipelineOptionsFactory - * with a description for each one if available to the output stream. This output - * is pretty printed and meant to be human readable. This method will attempt to - * format its output to be compatible with a terminal window. - */ - public static void printHelp(PrintStream out) { - checkNotNull(out); - out.println("The set of registered options are:"); - Set> sortedOptions = - new TreeSet<>(ClassNameComparator.INSTANCE); - sortedOptions.addAll(REGISTERED_OPTIONS); - for (Class kls : sortedOptions) { - out.format(" %s%n", kls.getName()); - } - out.format("%nUse --help= for detailed help. For example:%n" - + " --help=DataflowPipelineOptions %n" - + " --help=com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions%n"); - } - - /** - * Outputs the set of options available to be set for the passed in {@link PipelineOptions} - * interface. The output is in a human readable format. The format is: - *
              -   * OptionGroup:
              -   *     ... option group description ...
              -   *
              -   *  --option1={@code } or list of valid enum choices
              -   *     Default: value (if available, see {@link Default})
              -   *     ... option description ... (if available, see {@link Description})
              -   *     Required groups (if available, see {@link Required})
              -   *  --option2={@code } or list of valid enum choices
              -   *     Default: value (if available, see {@link Default})
              -   *     ... option description ... (if available, see {@link Description})
              -   *     Required groups (if available, see {@link Required})
              -   * 
              - * This method will attempt to format its output to be compatible with a terminal window. - */ - public static void printHelp(PrintStream out, Class iface) { - checkNotNull(out); - checkNotNull(iface); - validateWellFormed(iface, REGISTERED_OPTIONS); - - Set properties = - PipelineOptionsReflector.getOptionSpecs(iface); - - RowSortedTable, String, Method> ifacePropGetterTable = TreeBasedTable.create( - ClassNameComparator.INSTANCE, Ordering.natural()); - for (PipelineOptionSpec prop : properties) { - ifacePropGetterTable.put(prop.getDefiningInterface(), prop.getName(), prop.getGetterMethod()); - } - - for (Map.Entry, Map> ifaceToPropertyMap : - ifacePropGetterTable.rowMap().entrySet()) { - Class currentIface = ifaceToPropertyMap.getKey(); - Map propertyNamesToGetters = ifaceToPropertyMap.getValue(); - - SortedSetMultimap requiredGroupNameToProperties = - getRequiredGroupNamesToProperties(propertyNamesToGetters); - - out.format("%s:%n", currentIface.getName()); - prettyPrintDescription(out, currentIface.getAnnotation(Description.class)); - - out.println(); - - List lists = Lists.newArrayList(propertyNamesToGetters.keySet()); - Collections.sort(lists, String.CASE_INSENSITIVE_ORDER); - for (String propertyName : lists) { - Method method = propertyNamesToGetters.get(propertyName); - String printableType = method.getReturnType().getSimpleName(); - if (method.getReturnType().isEnum()) { - printableType = Joiner.on(" | ").join(method.getReturnType().getEnumConstants()); - } - out.format(" --%s=<%s>%n", propertyName, printableType); - Optional defaultValue = getDefaultValueFromAnnotation(method); - if (defaultValue.isPresent()) { - out.format(" Default: %s%n", defaultValue.get()); - } - prettyPrintDescription(out, method.getAnnotation(Description.class)); - prettyPrintRequiredGroups(out, method.getAnnotation(Validation.Required.class), - requiredGroupNameToProperties); - } - out.println(); - } - } - - /** - * Output the requirement groups that the property is a member of, including all properties that - * satisfy the group requirement, breaking up long lines on white space characters and attempting - * to honor a line limit of {@code TERMINAL_WIDTH}. - */ - private static void prettyPrintRequiredGroups(PrintStream out, Required annotation, - SortedSetMultimap requiredGroupNameToProperties) { - if (annotation == null || annotation.groups() == null) { - return; - } - for (String group : annotation.groups()) { - SortedSet groupMembers = requiredGroupNameToProperties.get(group); - String requirement; - if (groupMembers.size() == 1) { - requirement = Iterables.getOnlyElement(groupMembers) + " is required."; - } else { - requirement = "At least one of " + groupMembers + " is required"; - } - terminalPrettyPrint(out, requirement.split("\\s+")); - } - } - - /** - * Outputs the value of the description, breaking up long lines on white space characters and - * attempting to honor a line limit of {@code TERMINAL_WIDTH}. - */ - private static void prettyPrintDescription(PrintStream out, Description description) { - if (description == null || description.value() == null) { - return; - } - - String[] words = description.value().split("\\s+"); - terminalPrettyPrint(out, words); - } - - private static void terminalPrettyPrint(PrintStream out, String[] words) { - final String spacing = " "; - - if (words.length == 0) { - return; - } - - out.print(spacing); - int lineLength = spacing.length(); - for (int i = 0; i < words.length; ++i) { - out.print(" "); - out.print(words[i]); - lineLength += 1 + words[i].length(); - - // If the next word takes us over the terminal width, then goto the next line. - if (i + 1 != words.length && words[i + 1].length() + lineLength + 1 > TERMINAL_WIDTH) { - out.println(); - out.print(spacing); - lineLength = spacing.length(); - } - } - out.println(); - } - - /** - * Returns a string representation of the {@link Default} value on the passed in method. - */ - private static Optional getDefaultValueFromAnnotation(Method method) { - for (Annotation annotation : method.getAnnotations()) { - if (annotation instanceof Default.Class) { - return Optional.of(((Default.Class) annotation).value().getSimpleName()); - } else if (annotation instanceof Default.String) { - return Optional.of(((Default.String) annotation).value()); - } else if (annotation instanceof Default.Boolean) { - return Optional.of(Boolean.toString(((Default.Boolean) annotation).value())); - } else if (annotation instanceof Default.Character) { - return Optional.of(Character.toString(((Default.Character) annotation).value())); - } else if (annotation instanceof Default.Byte) { - return Optional.of(Byte.toString(((Default.Byte) annotation).value())); - } else if (annotation instanceof Default.Short) { - return Optional.of(Short.toString(((Default.Short) annotation).value())); - } else if (annotation instanceof Default.Integer) { - return Optional.of(Integer.toString(((Default.Integer) annotation).value())); - } else if (annotation instanceof Default.Long) { - return Optional.of(Long.toString(((Default.Long) annotation).value())); - } else if (annotation instanceof Default.Float) { - return Optional.of(Float.toString(((Default.Float) annotation).value())); - } else if (annotation instanceof Default.Double) { - return Optional.of(Double.toString(((Default.Double) annotation).value())); - } else if (annotation instanceof Default.Enum) { - return Optional.of(((Default.Enum) annotation).value()); - } else if (annotation instanceof Default.InstanceFactory) { - return Optional.of(((Default.InstanceFactory) annotation).value().getSimpleName()); - } - } - return Optional.absent(); - } - - static Map>> getRegisteredRunners() { - return SUPPORTED_PIPELINE_RUNNERS; - } - - static List getPropertyDescriptors( - Set> interfaces) { - return COMBINED_CACHE.get(interfaces).getPropertyDescriptors(); - } - - /** - * Creates a set of Dataflow worker harness options based of a set of known system - * properties. This is meant to only be used from the Dataflow worker harness as a method to - * bootstrap the worker harness. - * - *

              For internal use only. - * - * @return A {@link DataflowWorkerHarnessOptions} object configured for the - * Dataflow worker harness. - */ - public static DataflowWorkerHarnessOptions createFromSystemPropertiesInternal() - throws IOException { - return createFromSystemProperties(); - } - - /** - * Creates a set of {@link DataflowWorkerHarnessOptions} based of a set of known system - * properties. This is meant to only be used from the Dataflow worker harness as a method to - * bootstrap the worker harness. - * - * @return A {@link DataflowWorkerHarnessOptions} object configured for the - * Dataflow worker harness. - * @deprecated for internal use only - */ - @Deprecated - public static DataflowWorkerHarnessOptions createFromSystemProperties() throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - DataflowWorkerHarnessOptions options; - if (System.getProperties().containsKey("sdk_pipeline_options")) { - String serializedOptions = System.getProperty("sdk_pipeline_options"); - LOG.info("Worker harness starting with: " + serializedOptions); - options = objectMapper.readValue(serializedOptions, PipelineOptions.class) - .as(DataflowWorkerHarnessOptions.class); - } else { - options = PipelineOptionsFactory.as(DataflowWorkerHarnessOptions.class); - } - - // These values will not be known at job submission time and must be provided. - if (System.getProperties().containsKey("worker_id")) { - options.setWorkerId(System.getProperty("worker_id")); - } - if (System.getProperties().containsKey("job_id")) { - options.setJobId(System.getProperty("job_id")); - } - - return options; - } - - /** - * This method is meant to emulate the behavior of {@link Introspector#getBeanInfo(Class, int)} - * to construct the list of {@link PropertyDescriptor}. - * - *

              TODO: Swap back to using Introspector once the proxy class issue with AppEngine is - * resolved. - */ - private static List getPropertyDescriptors( - - Set methods, Class beanClass) - throws IntrospectionException { - SortedMap propertyNamesToGetters = new TreeMap<>(); - for (Map.Entry entry : - PipelineOptionsReflector.getPropertyNamesToGetters(methods).entries()) { - propertyNamesToGetters.put(entry.getKey(), entry.getValue()); - } - - List descriptors = Lists.newArrayList(); - List mismatches = new ArrayList<>(); - Set usedDescriptors = Sets.newHashSet(); - /* - * Add all the getter/setter pairs to the list of descriptors removing the getter once - * it has been paired up. - */ - for (Method method : methods) { - String methodName = method.getName(); - if (!methodName.startsWith("set") - || method.getParameterTypes().length != 1 - || method.getReturnType() != void.class) { - continue; - } - String propertyName = Introspector.decapitalize(methodName.substring(3)); - Method getterMethod = propertyNamesToGetters.remove(propertyName); - - // Validate that the getter and setter property types are the same. - if (getterMethod != null) { - Type getterPropertyType = getterMethod.getGenericReturnType(); - Type setterPropertyType = method.getGenericParameterTypes()[0]; - if (!getterPropertyType.equals(setterPropertyType)) { - TypeMismatch mismatch = new TypeMismatch(); - mismatch.propertyName = propertyName; - mismatch.getterPropertyType = getterPropertyType; - mismatch.setterPropertyType = setterPropertyType; - mismatches.add(mismatch); - continue; - } - } - // Properties can appear multiple times with subclasses, and we don't - // want to add a bad entry if we have already added a good one (with both - // getter and setter). - if (!usedDescriptors.contains(propertyName)) { - descriptors.add(new PropertyDescriptor( - propertyName, getterMethod, method)); - usedDescriptors.add(propertyName); - } - } - throwForTypeMismatches(mismatches); - - // Add the remaining getters with missing setters. - for (Map.Entry getterToMethod : propertyNamesToGetters.entrySet()) { - descriptors.add(new PropertyDescriptor( - getterToMethod.getKey(), getterToMethod.getValue(), null)); - } - return descriptors; - } - - private static class TypeMismatch { - private String propertyName; - private Type getterPropertyType; - private Type setterPropertyType; - } - - private static void throwForTypeMismatches(List mismatches) { - if (mismatches.size() == 1) { - TypeMismatch mismatch = mismatches.get(0); - throw new IllegalArgumentException(String.format( - "Type mismatch between getter and setter methods for property [%s]. " - + "Getter is of type [%s] whereas setter is of type [%s].", - mismatch.propertyName, - mismatch.getterPropertyType, - mismatch.setterPropertyType)); - } else if (mismatches.size() > 1) { - StringBuilder builder = new StringBuilder( - String.format("Type mismatches between getters and setters detected:")); - for (TypeMismatch mismatch : mismatches) { - builder.append(String.format( - "%n - Property [%s]: Getter is of type [%s] whereas setter is of type [%s].", - mismatch.propertyName, - mismatch.getterPropertyType.toString(), - mismatch.setterPropertyType.toString())); - } - throw new IllegalArgumentException(builder.toString()); - } - } - - /** - * Returns a map of required groups of arguments to the properties that satisfy the requirement. - */ - private static SortedSetMultimap getRequiredGroupNamesToProperties( - Map propertyNamesToGetters) { - SortedSetMultimap result = TreeMultimap.create(); - for (Map.Entry propertyEntry : propertyNamesToGetters.entrySet()) { - Required requiredAnnotation = - propertyEntry.getValue().getAnnotation(Validation.Required.class); - if (requiredAnnotation != null) { - for (String groupName : requiredAnnotation.groups()) { - result.put(groupName, propertyEntry.getKey()); - } - } - } - return result; - } - - /** - * Validates that a given class conforms to the following properties: - *

                - *
              • Any property with the same name must have the same return type for all derived - * interfaces of {@link PipelineOptions}. - *
              • Every bean property of any interface derived from {@link PipelineOptions} must have a - * getter and setter method. - *
              • Every method must conform to being a getter or setter for a JavaBean. - *
              • Only getters may be annotated with {@link JsonIgnore @JsonIgnore}. - *
              • If any getter is annotated with {@link JsonIgnore @JsonIgnore}, then all getters for - * this property must be annotated with {@link JsonIgnore @JsonIgnore}. - *
              - * - * @param iface The interface to validate. - * @param validatedPipelineOptionsInterfaces The set of validated pipeline options interfaces to - * validate against. - * @param klass The proxy class representing the interface. - * @return A list of {@link PropertyDescriptor}s representing all valid bean properties of - * {@code iface}. - * @throws IntrospectionException if invalid property descriptors. - */ - private static List validateClass(Class iface, - Set> validatedPipelineOptionsInterfaces, - Class klass) throws IntrospectionException { - Set methods = Sets.newHashSet(IGNORED_METHODS); - // Ignore synthetic methods - for (Method method : klass.getMethods()) { - if (Modifier.isStatic(method.getModifiers()) || method.isSynthetic()) { - methods.add(method); - } - } - - // Ignore methods on the base PipelineOptions interface. - try { - methods.add(iface.getMethod("as", Class.class)); - methods.add(iface.getMethod("outputRuntimeOptions")); - methods.add(iface.getMethod("cloneAs", Class.class)); - methods.add(iface.getMethod("populateDisplayData", DisplayData.Builder.class)); - } catch (NoSuchMethodException | SecurityException e) { - throw new RuntimeException(e); - } - - // Verify that there are no methods with the same name with two different return types. - Iterable interfaceMethods = FluentIterable - .from(ReflectHelpers.getClosureOfMethodsOnInterface(iface)) - .filter(NOT_SYNTHETIC_PREDICATE) - .toSortedSet(MethodComparator.INSTANCE); - SortedSetMultimap methodNameToMethodMap = - TreeMultimap.create(MethodNameComparator.INSTANCE, MethodComparator.INSTANCE); - for (Method method : interfaceMethods) { - methodNameToMethodMap.put(method, method); - } - List multipleDefinitions = Lists.newArrayList(); - for (Map.Entry> entry - : methodNameToMethodMap.asMap().entrySet()) { - Set> returnTypes = FluentIterable.from(entry.getValue()) - .transform(ReturnTypeFetchingFunction.INSTANCE).toSet(); - SortedSet collidingMethods = FluentIterable.from(entry.getValue()) - .toSortedSet(MethodComparator.INSTANCE); - if (returnTypes.size() > 1) { - MultipleDefinitions defs = new MultipleDefinitions(); - defs.method = entry.getKey(); - defs.collidingMethods = collidingMethods; - multipleDefinitions.add(defs); - } - } - throwForMultipleDefinitions(iface, multipleDefinitions); - - // Verify that there is no getter with a mixed @JsonIgnore annotation and verify - // that no setter has @JsonIgnore. - SortedSet allInterfaceMethods = - FluentIterable.from( - ReflectHelpers.getClosureOfMethodsOnInterfaces( - validatedPipelineOptionsInterfaces)) - .append(ReflectHelpers.getClosureOfMethodsOnInterface(iface)) - .filter(NOT_SYNTHETIC_PREDICATE) - .toSortedSet(MethodComparator.INSTANCE); - SortedSetMultimap methodNameToAllMethodMap = - TreeMultimap.create(MethodNameComparator.INSTANCE, MethodComparator.INSTANCE); - for (Method method : allInterfaceMethods) { - methodNameToAllMethodMap.put(method, method); - } - - List descriptors = getPropertyDescriptors(allInterfaceMethods, iface); - - List incompletelyIgnoredGetters = new ArrayList<>(); - List ignoredSetters = new ArrayList<>(); - - for (PropertyDescriptor descriptor : descriptors) { - if (descriptor.getReadMethod() == null - || descriptor.getWriteMethod() == null - || IGNORED_METHODS.contains(descriptor.getReadMethod()) - || IGNORED_METHODS.contains(descriptor.getWriteMethod())) { - continue; - } - SortedSet getters = methodNameToAllMethodMap.get(descriptor.getReadMethod()); - SortedSet gettersWithJsonIgnore = Sets.filter(getters, JsonIgnorePredicate.INSTANCE); - - Iterable getterClassNames = FluentIterable.from(getters) - .transform(MethodToDeclaringClassFunction.INSTANCE) - .transform(ReflectHelpers.CLASS_NAME); - Iterable gettersWithJsonIgnoreClassNames = FluentIterable.from(gettersWithJsonIgnore) - .transform(MethodToDeclaringClassFunction.INSTANCE) - .transform(ReflectHelpers.CLASS_NAME); - - if (!(gettersWithJsonIgnore.isEmpty() || getters.size() == gettersWithJsonIgnore.size())) { - InconsistentlyIgnoredGetters err = new InconsistentlyIgnoredGetters(); - err.descriptor = descriptor; - err.getterClassNames = getterClassNames; - err.gettersWithJsonIgnoreClassNames = gettersWithJsonIgnoreClassNames; - incompletelyIgnoredGetters.add(err); - } - if (!incompletelyIgnoredGetters.isEmpty()) { - continue; - } - - SortedSet settersWithJsonIgnore = - Sets.filter(methodNameToAllMethodMap.get(descriptor.getWriteMethod()), - JsonIgnorePredicate.INSTANCE); - - Iterable settersWithJsonIgnoreClassNames = FluentIterable.from(settersWithJsonIgnore) - .transform(MethodToDeclaringClassFunction.INSTANCE) - .transform(ReflectHelpers.CLASS_NAME); - - if (!settersWithJsonIgnore.isEmpty()) { - IgnoredSetter ignored = new IgnoredSetter(); - ignored.descriptor = descriptor; - ignored.settersWithJsonIgnoreClassNames = settersWithJsonIgnoreClassNames; - ignoredSetters.add(ignored); - } - } - throwForGettersWithInconsistentJsonIgnore(incompletelyIgnoredGetters); - throwForSettersWithJsonIgnore(ignoredSetters); - - List missingBeanMethods = new ArrayList<>(); - // Verify that each property has a matching read and write method. - for (PropertyDescriptor propertyDescriptor : descriptors) { - if (!(IGNORED_METHODS.contains(propertyDescriptor.getWriteMethod()) - || propertyDescriptor.getReadMethod() != null)) { - MissingBeanMethod method = new MissingBeanMethod(); - method.property = propertyDescriptor; - method.methodType = "getter"; - missingBeanMethods.add(method); - continue; - } - if (!(IGNORED_METHODS.contains(propertyDescriptor.getReadMethod()) - || propertyDescriptor.getWriteMethod() != null)) { - MissingBeanMethod method = new MissingBeanMethod(); - method.property = propertyDescriptor; - method.methodType = "setter"; - missingBeanMethods.add(method); - continue; - } - methods.add(propertyDescriptor.getReadMethod()); - methods.add(propertyDescriptor.getWriteMethod()); - } - throwForMissingBeanMethod(iface, missingBeanMethods); - final Set knownMethods = Sets.newHashSet(); - for (Method method : methods) { - knownMethods.add(method.getName()); - } - - // Verify that no additional methods are on an interface that aren't a bean property. - // Because methods can have multiple declarations, we do a name-based comparison - // here to prevent false positives. - SortedSet unknownMethods = new TreeSet<>(MethodComparator.INSTANCE); - unknownMethods.addAll( - Sets.filter( - Sets.difference(Sets.newHashSet(iface.getMethods()), methods), - Predicates.and(NOT_SYNTHETIC_PREDICATE, - new Predicate() { - @Override - public boolean apply(Method input) { - return !knownMethods.contains(input.getName()); - } - }))); - checkArgument(unknownMethods.isEmpty(), - "Methods %s on [%s] do not conform to being bean properties.", - FluentIterable.from(unknownMethods).transform(ReflectHelpers.METHOD_FORMATTER), - iface.getName()); - - return descriptors; - } - - private static class MultipleDefinitions { - private Method method; - private SortedSet collidingMethods; - } - - private static void throwForMultipleDefinitions( - Class iface, List definitions) { - if (definitions.size() == 1) { - MultipleDefinitions errDef = definitions.get(0); - throw new IllegalArgumentException(String.format( - "Method [%s] has multiple definitions %s with different return types for [%s].", - errDef.method.getName(), errDef.collidingMethods, iface.getName())); - } else if (definitions.size() > 1) { - StringBuilder errorBuilder = new StringBuilder(String.format( - "Interface [%s] has Methods with multiple definitions with different return types:", - iface.getName())); - for (MultipleDefinitions errDef : definitions) { - errorBuilder.append(String.format( - "%n - Method [%s] has multiple definitions %s", - errDef.method.getName(), - errDef.collidingMethods)); - } - throw new IllegalArgumentException(errorBuilder.toString()); - } - } - - private static class InconsistentlyIgnoredGetters { - PropertyDescriptor descriptor; - Iterable getterClassNames; - Iterable gettersWithJsonIgnoreClassNames; - } - - private static void throwForGettersWithInconsistentJsonIgnore( - List getters) { - if (getters.size() == 1) { - InconsistentlyIgnoredGetters getter = getters.get(0); - throw new IllegalArgumentException(String.format( - "Expected getter for property [%s] to be marked with @JsonIgnore on all %s, " - + "found only on %s", - getter.descriptor.getName(), getter.getterClassNames, - getter.gettersWithJsonIgnoreClassNames)); - } else if (getters.size() > 1) { - StringBuilder errorBuilder = - new StringBuilder("Property getters are inconsistently marked with @JsonIgnore:"); - for (InconsistentlyIgnoredGetters getter : getters) { - errorBuilder.append( - String.format("%n - Expected for property [%s] to be marked on all %s, " - + "found only on %s", - getter.descriptor.getName(), getter.getterClassNames, - getter.gettersWithJsonIgnoreClassNames)); - } - throw new IllegalArgumentException(errorBuilder.toString()); - } - } - - private static class IgnoredSetter { - PropertyDescriptor descriptor; - Iterable settersWithJsonIgnoreClassNames; - } - - private static void throwForSettersWithJsonIgnore(List setters) { - if (setters.size() == 1) { - IgnoredSetter setter = setters.get(0); - throw new IllegalArgumentException( - String.format("Expected setter for property [%s] to not be marked with @JsonIgnore on %s", - setter.descriptor.getName(), setter.settersWithJsonIgnoreClassNames)); - } else if (setters.size() > 1) { - StringBuilder builder = new StringBuilder("Found setters marked with @JsonIgnore:"); - for (IgnoredSetter setter : setters) { - builder.append( - String.format("%n - Setter for property [%s] should not be marked with @JsonIgnore " - + "on %s", - setter.descriptor.getName(), setter.settersWithJsonIgnoreClassNames)); - } - throw new IllegalArgumentException(builder.toString()); - } - } - - private static class MissingBeanMethod { - String methodType; - PropertyDescriptor property; - } - - private static void throwForMissingBeanMethod( - Class iface, List missingBeanMethods) { - if (missingBeanMethods.size() == 1) { - MissingBeanMethod missingBeanMethod = missingBeanMethods.get(0); - throw new IllegalArgumentException( - String.format("Expected %s for property [%s] of type [%s] on [%s].", - missingBeanMethod.methodType, missingBeanMethod.property.getName(), - missingBeanMethod.property.getPropertyType().getName(), iface.getName())); - } else if (missingBeanMethods.size() > 1) { - StringBuilder builder = new StringBuilder(String.format( - "Found missing property methods on [%s]:", iface.getName())); - for (MissingBeanMethod method : missingBeanMethods) { - builder.append( - String.format("%n - Expected %s for property [%s] of type [%s]", method.methodType, - method.property.getName(), method.property.getPropertyType().getName())); - } - throw new IllegalArgumentException(builder.toString()); - } - } - - /** A {@link Comparator} that uses the classes name to compare them. */ - private static class ClassNameComparator implements Comparator> { - static final ClassNameComparator INSTANCE = new ClassNameComparator(); - @Override - public int compare(Class o1, Class o2) { - return o1.getName().compareTo(o2.getName()); - } - } - - /** A {@link Comparator} that uses the object's classes canonical name to compare them. */ - private static class ObjectsClassComparator implements Comparator { - static final ObjectsClassComparator INSTANCE = new ObjectsClassComparator(); - @Override - public int compare(Object o1, Object o2) { - return o1.getClass().getCanonicalName().compareTo(o2.getClass().getCanonicalName()); - } - } - - /** A {@link Comparator} that uses the generic method signature to sort them. */ - private static class MethodComparator implements Comparator { - static final MethodComparator INSTANCE = new MethodComparator(); - @Override - public int compare(Method o1, Method o2) { - return o1.toGenericString().compareTo(o2.toGenericString()); - } - } - - /** A {@link Comparator} that uses the methods name to compare them. */ - static class MethodNameComparator implements Comparator { - static final MethodNameComparator INSTANCE = new MethodNameComparator(); - @Override - public int compare(Method o1, Method o2) { - return o1.getName().compareTo(o2.getName()); - } - } - - /** A {@link Function} that gets the method's return type. */ - private static class ReturnTypeFetchingFunction implements Function> { - static final ReturnTypeFetchingFunction INSTANCE = new ReturnTypeFetchingFunction(); - @Override - public Class apply(Method input) { - return input.getReturnType(); - } - } - - /** A {@link Function} with returns the declaring class for the method. */ - private static class MethodToDeclaringClassFunction implements Function> { - static final MethodToDeclaringClassFunction INSTANCE = new MethodToDeclaringClassFunction(); - @Override - public Class apply(Method input) { - return input.getDeclaringClass(); - } - } - - /** - * A {@link Predicate} that returns true if the method is annotated with - * {@link JsonIgnore @JsonIgnore}. - */ - static class JsonIgnorePredicate implements Predicate { - static final JsonIgnorePredicate INSTANCE = new JsonIgnorePredicate(); - @Override - public boolean apply(Method input) { - return input.isAnnotationPresent(JsonIgnore.class); - } - } - - /** - * Splits string arguments based upon expected pattern of --argName=value. - * - *

              Example GNU style command line arguments: - * - *

              -   *   --project=MyProject (simple property, will set the "project" property to "MyProject")
              -   *   --readOnly=true (for boolean properties, will set the "readOnly" property to "true")
              -   *   --readOnly (shorthand for boolean properties, will set the "readOnly" property to "true")
              -   *   --x=1 --x=2 --x=3 (list style simple property, will set the "x" property to [1, 2, 3])
              -   *   --x=1,2,3 (shorthand list style simple property, will set the "x" property to [1, 2, 3])
              -   *   --complexObject='{"key1":"value1",...} (JSON format for all other complex types)
              -   * 
              - * - *

              Simple properties are able to bound to {@link String}, {@link Class}, enums and Java - * primitives {@code boolean}, {@code byte}, {@code short}, {@code int}, {@code long}, - * {@code float}, {@code double} and their primitive wrapper classes. - * - *

              Simple list style properties are able to be bound to {@code boolean[]}, {@code char[]}, - * {@code short[]}, {@code int[]}, {@code long[]}, {@code float[]}, {@code double[]}, - * {@code Class[]}, enum arrays, {@code String[]}, and {@code List}. - * - *

              JSON format is required for all other types. - * - *

              If strict parsing is enabled, options must start with '--', and not have an empty argument - * name or value based upon the positioning of the '='. Empty or null arguments will be ignored - * whether or not strict parsing is enabled. - */ - private static ListMultimap parseCommandLine( - String[] args, boolean strictParsing) { - ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); - for (String arg : args) { - if (Strings.isNullOrEmpty(arg)) { - continue; - } - try { - checkArgument(arg.startsWith("--"), - "Argument '%s' does not begin with '--'", arg); - int index = arg.indexOf("="); - // Make sure that '=' isn't the first character after '--' or the last character - checkArgument(index != 2, - "Argument '%s' starts with '--=', empty argument name not allowed", arg); - if (index > 0) { - builder.put(arg.substring(2, index), arg.substring(index + 1, arg.length())); - } else { - builder.put(arg.substring(2), "true"); - } - } catch (IllegalArgumentException e) { - if (strictParsing) { - throw e; - } else { - LOG.warn("Strict parsing is disabled, ignoring option '{}' because {}", - arg, e.getMessage()); - } - } - } - return builder.build(); - } - - /** - * Using the parsed string arguments, we convert the strings to the expected - * return type of the methods that are found on the passed-in class. - * - *

              For any return type that is expected to be an array or a collection, we further - * split up each string on ','. - * - *

              We special case the "runner" option. It is mapped to the class of the {@link PipelineRunner} - * based off of the {@link PipelineRunner PipelineRunners} simple class name. If the provided - * runner name is not registered via a {@link PipelineRunnerRegistrar}, we attempt to obtain the - * class that the name represents using {@link Class#forName(String)} and use the result class if - * it subclasses {@link PipelineRunner}. - * - *

              If strict parsing is enabled, unknown options or options that cannot be converted to - * the expected java type using an {@link ObjectMapper} will be ignored. - */ - private static Map parseObjects( - Class klass, ListMultimap options, boolean strictParsing) { - Map propertyNamesToGetters = Maps.newHashMap(); - PipelineOptionsFactory.validateWellFormed(klass, REGISTERED_OPTIONS); - @SuppressWarnings("unchecked") - Iterable propertyDescriptors = - PipelineOptionsFactory.getPropertyDescriptors( - FluentIterable.from(getRegisteredOptions()).append(klass).toSet()); - for (PropertyDescriptor descriptor : propertyDescriptors) { - propertyNamesToGetters.put(descriptor.getName(), descriptor.getReadMethod()); - } - Map convertedOptions = Maps.newHashMap(); - for (final Map.Entry> entry : options.asMap().entrySet()) { - try { - // Search for close matches for missing properties. - // Either off by one or off by two character errors. - if (!propertyNamesToGetters.containsKey(entry.getKey())) { - SortedSet closestMatches = new TreeSet( - Sets.filter(propertyNamesToGetters.keySet(), new Predicate() { - @Override - public boolean apply(@Nullable String input) { - return StringUtils.getLevenshteinDistance(entry.getKey(), input) <= 2; - } - })); - switch (closestMatches.size()) { - case 0: - throw new IllegalArgumentException( - String.format("Class %s missing a property named '%s'.", - klass, entry.getKey())); - case 1: - throw new IllegalArgumentException( - String.format("Class %s missing a property named '%s'. Did you mean '%s'?", - klass, entry.getKey(), Iterables.getOnlyElement(closestMatches))); - default: - throw new IllegalArgumentException( - String.format("Class %s missing a property named '%s'. Did you mean one of %s?", - klass, entry.getKey(), closestMatches)); - } - } - - Method method = propertyNamesToGetters.get(entry.getKey()); - // Only allow empty argument values for String, String Array, and Collection. - Class returnType = method.getReturnType(); - JavaType type = MAPPER.getTypeFactory().constructType(method.getGenericReturnType()); - if ("runner".equals(entry.getKey())) { - String runner = Iterables.getOnlyElement(entry.getValue()); - if (SUPPORTED_PIPELINE_RUNNERS.containsKey(runner)) { - convertedOptions.put("runner", SUPPORTED_PIPELINE_RUNNERS.get(runner)); - } else { - try { - Class runnerClass = Class.forName(runner); - checkArgument( - PipelineRunner.class.isAssignableFrom(runnerClass), - "Class '%s' does not implement PipelineRunner. Supported pipeline runners %s", - runner, - Sets.newTreeSet(SUPPORTED_PIPELINE_RUNNERS.keySet())); - convertedOptions.put("runner", runnerClass); - } catch (ClassNotFoundException e) { - String msg = - String.format( - "Unknown 'runner' specified '%s', supported pipeline runners %s", - runner, - Sets.newTreeSet(SUPPORTED_PIPELINE_RUNNERS.keySet())); - throw new IllegalArgumentException(msg, e); - } - } - } else if (isCollectionOrArrayOfAllowedTypes(returnType, type)) { - // Split any strings with "," - List values = FluentIterable.from(entry.getValue()) - .transformAndConcat(new Function>() { - @Override - public Iterable apply(String input) { - return Arrays.asList(input.split(",")); - } - }).toList(); - - if (values.contains("")) { - checkEmptyStringAllowed(returnType, type, method.getGenericReturnType().toString()); - } - convertedOptions.put(entry.getKey(), MAPPER.convertValue(values, type)); - } else if (isSimpleType(returnType, type)) { - String value = Iterables.getOnlyElement(entry.getValue()); - if (value.isEmpty()) { - checkEmptyStringAllowed(returnType, type, method.getGenericReturnType().toString()); - } - convertedOptions.put(entry.getKey(), MAPPER.convertValue(value, type)); - } else { - String value = Iterables.getOnlyElement(entry.getValue()); - if (value.isEmpty()) { - checkEmptyStringAllowed(returnType, type, method.getGenericReturnType().toString()); - } - try { - convertedOptions.put(entry.getKey(), MAPPER.readValue(value, type)); - } catch (IOException e) { - throw new IllegalArgumentException("Unable to parse JSON value " + value, e); - } - } - } catch (IllegalArgumentException e) { - if (strictParsing) { - throw e; - } else { - LOG.warn("Strict parsing is disabled, ignoring option '{}' with value '{}' because {}", - entry.getKey(), entry.getValue(), e.getMessage()); - } - } - } - return convertedOptions; - } - - /** - * Returns true if the given type is one of {@code SIMPLE_TYPES} or an enum, or if the given type - * is a {@link ValueProvider ValueProvider<T>} and {@code T} is one of {@code SIMPLE_TYPES} - * or an enum. - */ - private static boolean isSimpleType(Class type, JavaType genericType) { - Class unwrappedType = type.equals(ValueProvider.class) - ? genericType.containedType(0).getRawClass() : type; - return SIMPLE_TYPES.contains(unwrappedType) || unwrappedType.isEnum(); - } - - /** - * Returns true if the given type is an array or {@link Collection} of {@code SIMPLE_TYPES} or - * enums, or if the given type is a {@link ValueProvider ValueProvider<T>} and {@code T} is - * one of an array or {@link Collection} of {@code SIMPLE_TYPES} or enums. - */ - private static boolean isCollectionOrArrayOfAllowedTypes(Class type, JavaType genericType) { - JavaType containerType = type.equals(ValueProvider.class) - ? genericType.containedType(0) : genericType; - - // Check if it is an array of simple types or enum. - if (containerType.getRawClass().isArray() - && (SIMPLE_TYPES.contains(containerType.getRawClass().getComponentType()) - || containerType.getRawClass().getComponentType().isEnum())) { - return true; - } - // Check if it is Collection of simple types or enum. - if (Collection.class.isAssignableFrom(containerType.getRawClass())) { - JavaType innerType = containerType.containedType(0); - // Note that raw types are allowed, hence the null check. - if (innerType == null || SIMPLE_TYPES.contains(innerType.getRawClass()) - || innerType.getRawClass().isEnum()) { - return true; - } - } - return false; - } - - /** - * Ensures that empty string value is allowed for a given type. - * - *

              Empty strings are only allowed for {@link String}, {@link String String[]}, - * {@link Collection Collection<String>}, or {@link ValueProvider ValueProvider<T>} - * and {@code T} is of type {@link String}, {@link String String[]}, - * {@link Collection Collection<String>}. - * - * @param type class object for the type under check. - * @param genericType complete type information for the type under check. - * @param genericTypeName a string representation of the complete type information. - */ - private static void checkEmptyStringAllowed(Class type, JavaType genericType, - String genericTypeName) { - JavaType unwrappedType = type.equals(ValueProvider.class) - ? genericType.containedType(0) : genericType; - - Class containedType = unwrappedType.getRawClass(); - if (unwrappedType.getRawClass().isArray()) { - containedType = unwrappedType.getRawClass().getComponentType(); - } else if (Collection.class.isAssignableFrom(unwrappedType.getRawClass())) { - JavaType innerType = unwrappedType.containedType(0); - // Note that raw types are allowed, hence the null check. - containedType = innerType == null ? String.class : innerType.getRawClass(); - } - if (!containedType.equals(String.class)) { - String msg = String.format("Empty argument value is only allowed for String, String Array, " - + "Collections of Strings or any of these types in a parameterized ValueProvider, " - + "but received: %s", - genericTypeName); - throw new IllegalArgumentException(msg); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java deleted file mode 100644 index 77cf91592f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflector.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Multimap; - -import java.beans.Introspector; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Set; - -/** - * Utilities to reflect over {@link PipelineOptions}. - */ -class PipelineOptionsReflector { - private PipelineOptionsReflector() {} - - /** - * Retrieve metadata for the full set of pipeline options visible within the type hierarchy - * of a single {@link PipelineOptions} interface. - * - * @see PipelineOptionsReflector#getOptionSpecs(Iterable) - */ - static Set getOptionSpecs(Class optionsInterface) { - Iterable methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface); - Multimap propsToGetters = getPropertyNamesToGetters(methods); - - ImmutableSet.Builder setBuilder = ImmutableSet.builder(); - for (Map.Entry propAndGetter : propsToGetters.entries()) { - String prop = propAndGetter.getKey(); - Method getter = propAndGetter.getValue(); - - @SuppressWarnings("unchecked") - Class declaringClass = - (Class) getter.getDeclaringClass(); - - if (!PipelineOptions.class.isAssignableFrom(declaringClass)) { - continue; - } - - if (declaringClass.isAnnotationPresent(Hidden.class)) { - continue; - } - - setBuilder.add(PipelineOptionSpec.of(declaringClass, prop, getter)); - } - - return setBuilder.build(); - } - - /** - * Retrieve metadata for the full set of pipeline options visible within the type hierarchy - * closure of the set of input interfaces. An option is "visible" if: - * - *

                - *
              • The option is defined within the interface hierarchy closure of the input - * {@link PipelineOptions}.
              • - *
              • The defining interface is not marked {@link Hidden}.
              • - *
              - */ - static Set getOptionSpecs( - Iterable> optionsInterfaces) { - ImmutableSet.Builder setBuilder = ImmutableSet.builder(); - for (Class optionsInterface : optionsInterfaces) { - setBuilder.addAll(getOptionSpecs(optionsInterface)); - } - - return setBuilder.build(); - } - - /** - * Extract pipeline options and their respective getter methods from a series of - * {@link Method methods}. A single pipeline option may appear in many methods. - * - * @return A mapping of option name to the input methods which declare it. - */ - static Multimap getPropertyNamesToGetters(Iterable methods) { - Multimap propertyNamesToGetters = HashMultimap.create(); - for (Method method : methods) { - String methodName = method.getName(); - if ((!methodName.startsWith("get") - && !methodName.startsWith("is")) - || method.getParameterTypes().length != 0 - || method.getReturnType() == void.class) { - continue; - } - String propertyName = Introspector.decapitalize( - methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3)); - propertyNamesToGetters.put(propertyName, method); - } - return propertyNamesToGetters; - } - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsRegistrar.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsRegistrar.java deleted file mode 100644 index 1678541bef..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsRegistrar.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import com.google.auto.service.AutoService; - -import java.util.ServiceLoader; - -/** - * {@link PipelineOptions} creators have the ability to automatically have their - * {@link PipelineOptions} registered with this SDK by creating a {@link ServiceLoader} entry - * and a concrete implementation of this interface. - * - *

              Note that automatic registration of any {@link PipelineOptions} requires users - * conform to the limitations discussed on {@link PipelineOptionsFactory#register(Class)}. - * - *

              It is optional but recommended to use one of the many build time tools such as - * {@link AutoService} to generate the necessary META-INF files automatically. - */ -public interface PipelineOptionsRegistrar { - Iterable> getPipelineOptions(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidator.java deleted file mode 100644 index 72bc3cc80b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidator.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.options.Validation.Required; -import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; -import com.google.common.collect.Collections2; -import com.google.common.collect.Ordering; -import com.google.common.collect.SortedSetMultimap; -import com.google.common.collect.TreeMultimap; - -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Collection; - -/** - * Validates that the {@link PipelineOptions} conforms to all the {@link Validation} criteria. - */ -public class PipelineOptionsValidator { - /** - * Validates that the passed {@link PipelineOptions} conforms to all the validation criteria from - * the passed in interface. - * - *

              Note that the interface requested must conform to the validation criteria specified on - * {@link PipelineOptions#as(Class)}. - * - * @param klass The interface to fetch validation criteria from. - * @param options The {@link PipelineOptions} to validate. - * @return The type - */ - public static T validate(Class klass, PipelineOptions options) { - checkNotNull(klass); - checkNotNull(options); - checkArgument(Proxy.isProxyClass(options.getClass())); - checkArgument(Proxy.getInvocationHandler(options) - instanceof ProxyInvocationHandler); - - // Ensure the methods for T are registered on the ProxyInvocationHandler - T asClassOptions = options.as(klass); - - ProxyInvocationHandler handler = - (ProxyInvocationHandler) Proxy.getInvocationHandler(asClassOptions); - - SortedSetMultimap requiredGroups = TreeMultimap.create( - Ordering.natural(), PipelineOptionsFactory.MethodNameComparator.INSTANCE); - for (Method method : ReflectHelpers.getClosureOfMethodsOnInterface(klass)) { - Required requiredAnnotation = method.getAnnotation(Validation.Required.class); - if (requiredAnnotation != null) { - if (requiredAnnotation.groups().length > 0) { - for (String requiredGroup : requiredAnnotation.groups()) { - requiredGroups.put(requiredGroup, method); - } - } else { - checkArgument(handler.invoke(asClassOptions, method, null) != null, - "Missing required value for [" + method + ", \"" + getDescription(method) + "\"]. "); - } - } - } - - for (String requiredGroup : requiredGroups.keySet()) { - if (!verifyGroup(handler, asClassOptions, requiredGroups.get(requiredGroup))) { - throw new IllegalArgumentException("Missing required value for group [" + requiredGroup - + "]. At least one of the following properties " - + Collections2.transform( - requiredGroups.get(requiredGroup), ReflectHelpers.METHOD_FORMATTER) - + " required. Run with --help=" + klass.getSimpleName() + " for more information."); - } - } - - return asClassOptions; - } - - private static boolean verifyGroup(ProxyInvocationHandler handler, PipelineOptions options, - Collection requiredGroup) { - for (Method m : requiredGroup) { - if (handler.invoke(options, m, null) != null) { - return true; - } - } - return false; - } - - private static String getDescription(Method method) { - Description description = method.getAnnotation(Description.class); - return description == null ? "" : description.value(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java deleted file mode 100644 index 3a6f106322..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandler.java +++ /dev/null @@ -1,769 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.JsonIgnorePredicate; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.Registration; -import com.google.cloud.dataflow.sdk.options.ValueProvider.RuntimeValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; -import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; -import com.google.common.base.Defaults; -import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.MutableClassToInstanceMap; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import java.beans.PropertyDescriptor; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Proxy; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; - -import javax.annotation.Nullable; -import javax.annotation.concurrent.ThreadSafe; - -/** - * Represents and {@link InvocationHandler} for a {@link Proxy}. The invocation handler uses bean - * introspection of the proxy class to store and retrieve values based off of the property name. - * - *

              Unset properties use the {@code @Default} metadata on the getter to return values. If there - * is no {@code @Default} annotation on the getter, then a default as - * per the Java Language Specification for the expected return type is returned. - * - *

              In addition to the getter/setter pairs, this proxy invocation handler supports - * {@link Object#equals(Object)}, {@link Object#hashCode()}, {@link Object#toString()} and - * {@link PipelineOptions#as(Class)}. - */ -@ThreadSafe -class ProxyInvocationHandler implements InvocationHandler, HasDisplayData { - private static final ObjectMapper MAPPER = new ObjectMapper(); - /** - * No two instances of this class are considered equivalent hence we generate a random hash code - * between 0 and {@link Integer#MAX_VALUE}. - */ - private final int hashCode = (int) (Math.random() * Integer.MAX_VALUE); - private final Set> knownInterfaces; - private final ClassToInstanceMap interfaceToProxyCache; - private final Map options; - private final Map jsonOptions; - private final Map gettersToPropertyNames; - private final Map settersToPropertyNames; - - ProxyInvocationHandler(Map options) { - this(bindOptions(options), Maps.newHashMap()); - } - - private static Map bindOptions(Map inputOptions) { - HashMap options = Maps.newHashMap(); - for (Map.Entry entry : inputOptions.entrySet()) { - options.put(entry.getKey(), BoundValue.fromExplicitOption(entry.getValue())); - } - - return options; - } - - private ProxyInvocationHandler( - Map options, Map jsonOptions) { - this.options = options; - this.jsonOptions = jsonOptions; - this.knownInterfaces = new HashSet<>(PipelineOptionsFactory.getRegisteredOptions()); - gettersToPropertyNames = Maps.newHashMap(); - settersToPropertyNames = Maps.newHashMap(); - interfaceToProxyCache = MutableClassToInstanceMap.create(); - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) { - if (args == null && "toString".equals(method.getName())) { - return toString(); - } else if (args != null && args.length == 1 && "equals".equals(method.getName())) { - return equals(args[0]); - } else if (args == null && "hashCode".equals(method.getName())) { - return hashCode(); - } else if (args == null && "outputRuntimeOptions".equals(method.getName())) { - return outputRuntimeOptions((PipelineOptions) proxy); - } else if (args != null && "as".equals(method.getName()) && args[0] instanceof Class) { - @SuppressWarnings("unchecked") - Class clazz = (Class) args[0]; - return as(clazz); - } else if (args != null && "cloneAs".equals(method.getName()) && args[0] instanceof Class) { - @SuppressWarnings("unchecked") - Class clazz = (Class) args[0]; - return cloneAs(proxy, clazz); - } else if (args != null && "populateDisplayData".equals(method.getName()) - && args[0] instanceof DisplayData.Builder) { - @SuppressWarnings("unchecked") - DisplayData.Builder builder = (DisplayData.Builder) args[0]; - // Explicitly set display data namespace so thrown exceptions will have sensible type. - builder.include(this, PipelineOptions.class); - return Void.TYPE; - } - String methodName = method.getName(); - synchronized (this) { - if (gettersToPropertyNames.containsKey(methodName)) { - String propertyName = gettersToPropertyNames.get(methodName); - if (!options.containsKey(propertyName)) { - // Lazy bind the default to the method. - Object value = jsonOptions.containsKey(propertyName) - ? getValueFromJson(propertyName, method) - : getDefault((PipelineOptions) proxy, method); - options.put(propertyName, BoundValue.fromDefault(value)); - } - return options.get(propertyName).getValue(); - } else if (settersToPropertyNames.containsKey(methodName)) { - options.put(settersToPropertyNames.get(methodName), BoundValue.fromExplicitOption(args[0])); - return Void.TYPE; - } - } - throw new RuntimeException("Unknown method [" + method + "] invoked with args [" - + Arrays.toString(args) + "]."); - } - - /** - * Track whether options values are explicitly set, or retrieved from defaults. - */ - static final class BoundValue { - @Nullable - private final Object value; - private final boolean isDefault; - - @Nullable - Object getValue() { - return value; - } - - boolean isDefault() { - return isDefault; - } - - private static BoundValue of(@Nullable Object value, boolean isDefault) { - return new BoundValue(value, isDefault); - } - - private BoundValue(@Nullable Object value, boolean isDefault) { - this.value = value; - this.isDefault = isDefault; - } - - /** - * Create a {@link BoundValue} representing an explicitly set option. - */ - static BoundValue fromExplicitOption(@Nullable Object value) { - return BoundValue.of(value, false); - } - - /** - * Create a {@link BoundValue} representing a default option value. - */ - static BoundValue fromDefault(@Nullable Object value) { - return BoundValue.of(value, true); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(BoundValue.class) - .add("value", value) - .add("isDefault", isDefault) - .toString(); - } - - @Override - public int hashCode() { - return Objects.hash(value, isDefault); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof BoundValue)) { - return false; - } - - BoundValue that = (BoundValue) obj; - return - Objects.equals(this.value, that.value) && Objects.equals(this.isDefault, that.isDefault); - } - } - - /** - * Backing implementation for {@link PipelineOptions#as(Class)}. - * - * @param iface The interface that the returned object needs to implement. - * @return An object that implements the interface {@code }. - */ - synchronized T as(Class iface) { - checkNotNull(iface); - checkArgument(iface.isInterface(), "Not an interface: %s", iface); - if (!interfaceToProxyCache.containsKey(iface)) { - Registration registration = - PipelineOptionsFactory.validateWellFormed(iface, knownInterfaces); - List propertyDescriptors = registration.getPropertyDescriptors(); - Class proxyClass = registration.getProxyClass(); - gettersToPropertyNames.putAll(generateGettersToPropertyNames(propertyDescriptors)); - settersToPropertyNames.putAll(generateSettersToPropertyNames(propertyDescriptors)); - knownInterfaces.add(iface); - interfaceToProxyCache.putInstance(iface, - InstanceBuilder.ofType(proxyClass) - .fromClass(proxyClass) - .withArg(InvocationHandler.class, this) - .build()); - } - return interfaceToProxyCache.getInstance(iface); - } - - /** - * Backing implementation for {@link PipelineOptions#cloneAs(Class)}. - * - * @return A copy of the PipelineOptions. - */ - synchronized T cloneAs(Object proxy, Class iface) { - PipelineOptions clonedOptions; - try { - clonedOptions = MAPPER.readValue(MAPPER.writeValueAsBytes(proxy), PipelineOptions.class); - } catch (IOException e) { - throw new IllegalStateException("Failed to serialize the pipeline options to JSON.", e); - } - for (Class knownIface : knownInterfaces) { - clonedOptions.as(knownIface); - } - return clonedOptions.as(iface); - } - - /** - * Returns true if the other object is a ProxyInvocationHandler or is a Proxy object and has the - * same ProxyInvocationHandler as this. - * - * @param obj The object to compare against this. - * @return true iff the other object is a ProxyInvocationHandler or is a Proxy object and has the - * same ProxyInvocationHandler as this. - */ - @Override - public boolean equals(Object obj) { - return obj != null && ((obj instanceof ProxyInvocationHandler && this == obj) - || (Proxy.isProxyClass(obj.getClass()) && this == Proxy.getInvocationHandler(obj))); - } - - /** - * Each instance of this ProxyInvocationHandler is unique and has a random hash code. - * - * @return A hash code that was generated randomly. - */ - @Override - public int hashCode() { - return hashCode; - } - - /** - * Returns a map of properties which correspond to {@link RuntimeValueProvider}. - */ - public Map> outputRuntimeOptions(PipelineOptions options) { - Set optionSpecs = PipelineOptionsReflector.getOptionSpecs(knownInterfaces); - Map> properties = Maps.newHashMap(); - - for (PipelineOptionSpec spec : optionSpecs) { - if (spec.getGetterMethod().getReturnType().equals(ValueProvider.class)) { - Object vp = invoke(options, spec.getGetterMethod(), null); - if (((ValueProvider) vp).isAccessible()) { - continue; - } - Map property = Maps.newHashMap(); - property.put("type", - ((ParameterizedType) spec.getGetterMethod() - .getGenericReturnType()).getActualTypeArguments()[0]); - properties.put(spec.getName(), property); - } - } - return properties; - } - - /** - * Populate display data. See {@link HasDisplayData#populateDisplayData}. All explicitly set - * pipeline options will be added as display data. - */ - public void populateDisplayData(DisplayData.Builder builder) { - Set optionSpecs = PipelineOptionsReflector.getOptionSpecs(knownInterfaces); - Multimap optionsMap = buildOptionNameToSpecMap(optionSpecs); - - for (Map.Entry option : options.entrySet()) { - BoundValue boundValue = option.getValue(); - if (boundValue.isDefault()) { - continue; - } - - Object value = boundValue.getValue() == null ? "" : boundValue.getValue(); - DisplayData.Type type = DisplayData.inferType(value); - HashSet specs = new HashSet<>(optionsMap.get(option.getKey())); - - for (PipelineOptionSpec optionSpec : specs) { - if (!optionSpec.shouldSerialize()) { - // Options that are excluded for serialization (i.e. those with @JsonIgnore) are also - // excluded from display data. These options are generally not useful for display. - continue; - } - - Class pipelineInterface = optionSpec.getDefiningInterface(); - if (type != null) { - builder.add(DisplayData.item(option.getKey(), type, value) - .withNamespace(pipelineInterface)); - } else { - builder.add(DisplayData.item(option.getKey(), displayDataString(value)) - .withNamespace(pipelineInterface)); - } - } - } - - for (Map.Entry jsonOption : jsonOptions.entrySet()) { - if (options.containsKey(jsonOption.getKey())) { - // Option overwritten since deserialization; don't re-write - continue; - } - - HashSet specs = new HashSet<>(optionsMap.get(jsonOption.getKey())); - if (specs.isEmpty()) { - builder.add(DisplayData.item(jsonOption.getKey(), jsonOption.getValue().toString()) - .withNamespace(UnknownPipelineOptions.class)); - } else { - for (PipelineOptionSpec spec : specs) { - if (!spec.shouldSerialize()) { - continue; - } - - Object value = getValueFromJson(jsonOption.getKey(), spec.getGetterMethod()); - value = value == null ? "" : value; - DisplayData.Type type = DisplayData.inferType(value); - if (type != null) { - builder.add(DisplayData.item(jsonOption.getKey(), type, value) - .withNamespace(spec.getDefiningInterface())); - } else { - builder.add(DisplayData.item(jsonOption.getKey(), displayDataString(value)) - .withNamespace(spec.getDefiningInterface())); - } - } - } - } - } - - /** - * {@link Object#toString()} wrapper to extract display data values for various types. - */ - private String displayDataString(Object value) { - checkNotNull(value, "value cannot be null"); - if (!value.getClass().isArray()) { - return value.toString(); - } - if (!value.getClass().getComponentType().isPrimitive()) { - return Arrays.deepToString((Object[]) value); - } - - // At this point, we have some type of primitive array. Arrays.deepToString(..) requires an - // Object array, but will unwrap nested primitive arrays. - String wrapped = Arrays.deepToString(new Object[]{value}); - return wrapped.substring(1, wrapped.length() - 1); - } - - /** - * Marker interface used when the original {@link PipelineOptions} interface is not known at - * runtime. This can occur if {@link PipelineOptions} are deserialized from JSON. - * - *

              Pipeline authors can ensure {@link PipelineOptions} type information is available at - * runtime by registering their {@link PipelineOptions options} interfaces. See the "Registration" - * section of {@link PipelineOptions} documentation. - */ - interface UnknownPipelineOptions extends PipelineOptions {} - - /** - * Construct a mapping from an option name to its {@link PipelineOptions} interface(s) - * declarations. An option may be declared in multiple interfaces. If it is overridden in a - * type hierarchy, only the overriding interface will be included. - */ - private Multimap buildOptionNameToSpecMap( - Set props) { - - Multimap optionsMap = HashMultimap.create(); - for (PipelineOptionSpec prop : props) { - optionsMap.put(prop.getName(), prop); - } - - // Filter out overridden options - for (Map.Entry> entry : optionsMap.asMap().entrySet()) { - - /* Compare all interfaces for an option pairwise (iface1, iface2) to look for type - hierarchies. If one is the base-class of the other, remove it from the output and continue - iterating. - - This is an N^2 operation per-option, but the number of interfaces defining an option - should always be small (usually 1). */ - List specs = Lists.newArrayList(entry.getValue()); - if (specs.size() < 2) { - // Only one known implementing interface, no need to check for inheritance - continue; - } - - for (int i = 0; i < specs.size() - 1; i++) { - Class iface1 = specs.get(i).getDefiningInterface(); - for (int j = i + 1; j < specs.size(); j++) { - Class iface2 = specs.get(j).getDefiningInterface(); - - if (iface1.isAssignableFrom(iface2)) { - optionsMap.remove(entry.getKey(), specs.get(i)); - specs.remove(i); - - // Removed element at current "i" index. Set iterators to re-evaluate - // new "i" element in outer loop. - i--; - j = specs.size(); - } else if (iface2.isAssignableFrom(iface1)) { - optionsMap.remove(entry.getKey(), specs.get(j)); - specs.remove(j); - - // Removed element at current "j" index. Set iterator to re-evaluate - // new "j" element in inner-loop. - j--; - } - } - } - } - - return optionsMap; - } - - /** - * This will output all the currently set values. This is a relatively costly function - * as it will call {@code toString()} on each object that has been set and format - * the results in a readable format. - * - * @return A pretty printed string representation of this. - */ - @Override - public synchronized String toString() { - SortedMap sortedOptions = new TreeMap<>(); - // Add the options that we received from deserialization - sortedOptions.putAll(jsonOptions); - // Override with any programmatically set options. - for (Map.Entry entry : options.entrySet()) { - sortedOptions.put(entry.getKey(), entry.getValue().getValue()); - } - - StringBuilder b = new StringBuilder(); - b.append("Current Settings:\n"); - for (Map.Entry entry : sortedOptions.entrySet()) { - b.append(" " + entry.getKey() + ": " + entry.getValue() + "\n"); - } - return b.toString(); - } - - /** - * Uses a Jackson {@link ObjectMapper} to attempt type conversion. - * - * @param method The method whose return type you would like to return. - * @param propertyName The name of the property that is being returned. - * @return An object matching the return type of the method passed in. - */ - private Object getValueFromJson(String propertyName, Method method) { - try { - JavaType type = MAPPER.getTypeFactory().constructType(method.getGenericReturnType()); - JsonNode jsonNode = jsonOptions.get(propertyName); - return MAPPER.readValue(jsonNode.toString(), type); - } catch (IOException e) { - throw new RuntimeException("Unable to parse representation", e); - } - } - - /** - * Returns a default value for the method based upon {@code @Default} metadata on the getter - * to return values. If there is no {@code @Default} annotation on the getter, then a default as - * per the Java Language Specification for the expected return type is returned. - * - * @param proxy The proxy object for which we are attempting to get the default. - * @param method The getter method that was invoked. - * @return The default value from an {@link Default} annotation if present, otherwise a default - * value as per the Java Language Specification. - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - private Object getDefault(PipelineOptions proxy, Method method) { - if (method.getReturnType().equals(RuntimeValueProvider.class)) { - throw new RuntimeException(String.format( - "Method %s should not have return type " - + "RuntimeValueProvider, use ValueProvider instead.", method.getName())); - } - if (method.getReturnType().equals(StaticValueProvider.class)) { - throw new RuntimeException(String.format( - "Method %s should not have return type " - + "StaticValueProvider, use ValueProvider instead.", method.getName())); - } - @Nullable Object defaultObject = null; - for (Annotation annotation : method.getAnnotations()) { - defaultObject = returnDefaultHelper(annotation, proxy, method); - if (defaultObject != null) { - break; - } - } - if (method.getReturnType().equals(ValueProvider.class)) { - String propertyName = gettersToPropertyNames.get(method.getName()); - return defaultObject == null - ? new RuntimeValueProvider( - method.getName(), propertyName, - (Class) method.getDeclaringClass(), - proxy.getOptionsId()) - : new RuntimeValueProvider( - method.getName(), propertyName, - (Class) method.getDeclaringClass(), - defaultObject, proxy.getOptionsId()); - } else if (defaultObject != null) { - return defaultObject; - } - - /* - * We need to make sure that we return something appropriate for the return type. Thus we return - * a default value as defined by the JLS. - */ - return Defaults.defaultValue(method.getReturnType()); - } - - /** - * Helper method to return standard Default cases. - */ - @Nullable - private Object returnDefaultHelper( - Annotation annotation, PipelineOptions proxy, Method method) { - if (annotation instanceof Default.Class) { - return ((Default.Class) annotation).value(); - } else if (annotation instanceof Default.String) { - return ((Default.String) annotation).value(); - } else if (annotation instanceof Default.Boolean) { - return ((Default.Boolean) annotation).value(); - } else if (annotation instanceof Default.Character) { - return ((Default.Character) annotation).value(); - } else if (annotation instanceof Default.Byte) { - return ((Default.Byte) annotation).value(); - } else if (annotation instanceof Default.Short) { - return ((Default.Short) annotation).value(); - } else if (annotation instanceof Default.Integer) { - return ((Default.Integer) annotation).value(); - } else if (annotation instanceof Default.Long) { - return ((Default.Long) annotation).value(); - } else if (annotation instanceof Default.Float) { - return ((Default.Float) annotation).value(); - } else if (annotation instanceof Default.Double) { - return ((Default.Double) annotation).value(); - } else if (annotation instanceof Default.Enum) { - return Enum.valueOf((Class) method.getReturnType(), - ((Default.Enum) annotation).value()); - } else if (annotation instanceof Default.InstanceFactory) { - return InstanceBuilder.ofType(((Default.InstanceFactory) annotation).value()) - .build() - .create(proxy); - } - return null; - } - - /** - * Returns a map from the getters method name to the name of the property based upon the passed in - * {@link PropertyDescriptor}s property descriptors. - * - * @param propertyDescriptors A list of {@link PropertyDescriptor}s to use when generating the - * map. - * @return A map of getter method name to property name. - */ - private static Map generateGettersToPropertyNames( - List propertyDescriptors) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (PropertyDescriptor descriptor : propertyDescriptors) { - if (descriptor.getReadMethod() != null) { - builder.put(descriptor.getReadMethod().getName(), descriptor.getName()); - } - } - return builder.build(); - } - - /** - * Returns a map from the setters method name to its matching getters method name based upon the - * passed in {@link PropertyDescriptor}s property descriptors. - * - * @param propertyDescriptors A list of {@link PropertyDescriptor}s to use when generating the - * map. - * @return A map of setter method name to getter method name. - */ - private static Map generateSettersToPropertyNames( - List propertyDescriptors) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (PropertyDescriptor descriptor : propertyDescriptors) { - if (descriptor.getWriteMethod() != null) { - builder.put(descriptor.getWriteMethod().getName(), descriptor.getName()); - } - } - return builder.build(); - } - - static class Serializer extends JsonSerializer { - @Override - public void serialize(PipelineOptions value, JsonGenerator jgen, SerializerProvider provider) - throws IOException, JsonProcessingException { - ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(value); - synchronized (handler) { - // We first filter out any properties that have been modified since - // the last serialization of this PipelineOptions and then verify that - // they are all serializable. - Map filteredOptions = Maps.newHashMap(handler.options); - removeIgnoredOptions(handler.knownInterfaces, filteredOptions); - ensureSerializable(handler.knownInterfaces, filteredOptions); - - // Now we create the map of serializable options by taking the original - // set of serialized options (if any) and updating them with any properties - // instances that have been modified since the previous serialization. - Map serializableOptions = - Maps.newHashMap(handler.jsonOptions); - for (Map.Entry entry : filteredOptions.entrySet()) { - serializableOptions.put(entry.getKey(), entry.getValue().getValue()); - } - - jgen.writeStartObject(); - jgen.writeFieldName("options"); - jgen.writeObject(serializableOptions); - - List> serializedDisplayData = Lists.newArrayList(); - DisplayData displayData = DisplayData.from(value); - for (DisplayData.Item item : displayData.items()) { - @SuppressWarnings("unchecked") - Map serializedItem = MAPPER.convertValue(item, Map.class); - serializedDisplayData.add(serializedItem); - } - - jgen.writeFieldName("display_data"); - jgen.writeObject(serializedDisplayData); - jgen.writeEndObject(); - } - } - - /** - * We remove all properties within the passed in options where there getter is annotated with - * {@link JsonIgnore @JsonIgnore} from the passed in options using the passed in interfaces. - */ - private void removeIgnoredOptions( - Set> interfaces, Map options) { - // Find all the method names that are annotated with JSON ignore. - Set jsonIgnoreMethodNames = FluentIterable.from( - ReflectHelpers.getClosureOfMethodsOnInterfaces(interfaces)) - .filter(JsonIgnorePredicate.INSTANCE).transform(new Function() { - @Override - public String apply(Method input) { - return input.getName(); - } - }).toSet(); - - // Remove all options that have the same method name as the descriptor. - for (PropertyDescriptor descriptor - : PipelineOptionsFactory.getPropertyDescriptors(interfaces)) { - if (jsonIgnoreMethodNames.contains(descriptor.getReadMethod().getName())) { - options.remove(descriptor.getName()); - } - } - } - - /** - * We use an {@link ObjectMapper} to verify that the passed in options are serializable - * and deserializable. - */ - private void ensureSerializable(Set> interfaces, - Map options) throws IOException { - // Construct a map from property name to the return type of the getter. - Map propertyToReturnType = Maps.newHashMap(); - for (PropertyDescriptor descriptor - : PipelineOptionsFactory.getPropertyDescriptors(interfaces)) { - if (descriptor.getReadMethod() != null) { - propertyToReturnType.put(descriptor.getName(), - descriptor.getReadMethod().getGenericReturnType()); - } - } - - // Attempt to serialize and deserialize each property. - for (Map.Entry entry : options.entrySet()) { - try { - String serializedValue = MAPPER.writeValueAsString(entry.getValue().getValue()); - JavaType type = MAPPER.getTypeFactory() - .constructType(propertyToReturnType.get(entry.getKey())); - MAPPER.readValue(serializedValue, type); - } catch (Exception e) { - throw new IOException(String.format( - "Failed to serialize and deserialize property '%s' with value '%s'", - entry.getKey(), entry.getValue().getValue()), e); - } - } - } - } - - static class Deserializer extends JsonDeserializer { - @Override - public PipelineOptions deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException, JsonProcessingException { - ObjectNode objectNode = (ObjectNode) jp.readValueAsTree(); - ObjectNode optionsNode = (ObjectNode) objectNode.get("options"); - - Map fields = Maps.newHashMap(); - for (Iterator> iterator = optionsNode.fields(); - iterator.hasNext(); ) { - Map.Entry field = iterator.next(); - fields.put(field.getKey(), field.getValue()); - } - PipelineOptions options = - new ProxyInvocationHandler(Maps.newHashMap(), fields) - .as(PipelineOptions.class); - ValueProvider.RuntimeValueProvider.setRuntimeOptions(options); - return options; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/StreamingOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/StreamingOptions.java deleted file mode 100644 index 9563c58904..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/StreamingOptions.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -/** - * Options used to configure streaming. - */ -public interface StreamingOptions extends - ApplicationNameOptions, GcpOptions, PipelineOptions { - /** - * Set to true if running a streaming pipeline. - */ - @Description("Set to true if running a streaming pipeline.") - boolean isStreaming(); - void setStreaming(boolean value); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Validation.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Validation.java deleted file mode 100644 index 20034f83e2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/Validation.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * {@link Validation} represents a set of annotations that can be used to annotate getter - * properties on {@link PipelineOptions} with information representing the validation criteria to - * be used when validating with the {@link PipelineOptionsValidator}. - */ -public @interface Validation { - /** - * This criteria specifies that the value must be not null. Note that this annotation - * should only be applied to methods that return nullable objects. - */ - @Target(value = ElementType.METHOD) - @Retention(RetentionPolicy.RUNTIME) - @Documented - public @interface Required { - /** - * The groups that the annotated attribute is a member of. A member can be in 0 or more groups. - * Members not in any groups are considered to be in a group consisting exclusively of - * themselves. At least one member of a group must be non-null if the options are to be valid. - */ - String[] groups() default {}; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java deleted file mode 100644 index 24a6a0666b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProvider.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.common.base.MoreObjects; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.BeanProperty; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.ContextualDeserializer; - -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.concurrent.ConcurrentHashMap; -import javax.annotation.Nullable; - -/** - * {@link ValueProvider} is an interface which abstracts the notion of - * fetching a value that may or may not be currently available. This can be - * used to parameterize transforms that only read values in at runtime, for - * example. - */ -@JsonSerialize(using = ValueProvider.Serializer.class) -@JsonDeserialize(using = ValueProvider.Deserializer.class) -public interface ValueProvider extends Serializable { - /** - * Return the value wrapped by this {@link ValueProvider}. - */ - T get(); - - /** - * Whether the contents of this {@link ValueProvider} is available to - * routines that run at graph construction time. - */ - boolean isAccessible(); - - /** - * {@link StaticValueProvider} is an implementation of {@link ValueProvider} that - * allows for a static value to be provided. - */ - class StaticValueProvider implements ValueProvider, Serializable { - @Nullable - private final T value; - - StaticValueProvider(@Nullable T value) { - this.value = value; - } - - /** - * Creates a {@link StaticValueProvider} that wraps the provided value. - */ - public static StaticValueProvider of(T value) { - StaticValueProvider factory = new StaticValueProvider<>(value); - return factory; - } - - @Override - public T get() { - return value; - } - - @Override - public boolean isAccessible() { - return true; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("value", value) - .toString(); - } - } - - /** - * {@link NestedValueProvider} is an implementation of {@link ValueProvider} that - * allows for wrapping another {@link ValueProvider} object. - */ - class NestedValueProvider implements ValueProvider, Serializable { - - private final ValueProvider value; - private final SerializableFunction translator; - - NestedValueProvider(ValueProvider value, SerializableFunction translator) { - this.value = checkNotNull(value); - this.translator = checkNotNull(translator); - } - - /** - * Creates a {@link NestedValueProvider} that wraps the provided value. - */ - public static NestedValueProvider of( - ValueProvider value, SerializableFunction translator) { - NestedValueProvider factory = new NestedValueProvider(value, translator); - return factory; - } - - @Override - public T get() { - return translator.apply(value.get()); - } - - @Override - public boolean isAccessible() { - return value.isAccessible(); - } - - /** - * Return the property name associated with this provider. - */ - public String propertyName() { - if (value instanceof RuntimeValueProvider) { - return ((RuntimeValueProvider) value).propertyName(); - } else if (value instanceof NestedValueProvider) { - return ((NestedValueProvider) value).propertyName(); - } else { - throw new RuntimeException("Only a RuntimeValueProvider or a NestedValueProvider can supply" - + " a property name."); - } - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("value", value) - .toString(); - } - } - - /** - * {@link RuntimeValueProvider} is an implementation of {@link ValueProvider} that - * allows for a value to be provided at execution time rather than at graph - * construction time. - * - *

              To enforce this contract, if there is no default, users must only call - * {@link #get()} at execution time (after a call to - * {@link com.google.cloud.dataflow.sdk.Pipeline#run}), - * which will provide the value of {@code optionsMap}. - */ - class RuntimeValueProvider implements ValueProvider, Serializable { - private static ConcurrentHashMap optionsMap = - new ConcurrentHashMap<>(); - - private final Class klass; - private final String methodName; - private final String propertyName; - @Nullable - private final T defaultValue; - private final Long optionsId; - - /** - * Creates a {@link RuntimeValueProvider} that will query the provided - * {@code optionsId} for a value. - */ - RuntimeValueProvider(String methodName, String propertyName, - Class klass, Long optionsId) { - this.methodName = methodName; - this.propertyName = propertyName; - this.klass = klass; - this.defaultValue = null; - this.optionsId = optionsId; - } - - /** - * Creates a {@link RuntimeValueProvider} that will query the provided - * {@code optionsId} for a value, or use the default if no value is available. - */ - RuntimeValueProvider(String methodName, String propertyName, - Class klass, - T defaultValue, Long optionsId) { - this.methodName = methodName; - this.propertyName = propertyName; - this.klass = klass; - this.defaultValue = defaultValue; - this.optionsId = optionsId; - } - - /** - * Once set, all {@code RuntimeValueProviders} will return {@code true} - * from {@code isAccessible()}. By default, the value is set when - * deserializing {@link PipelineOptions}. - */ - static void setRuntimeOptions(PipelineOptions runtimeOptions) { - optionsMap.put(runtimeOptions.getOptionsId(), runtimeOptions); - } - - @Override - public T get() { - PipelineOptions options = optionsMap.get(optionsId); - if (options == null) { - throw new RuntimeException("Not called from a runtime context."); - } - try { - Method method = klass.getMethod(methodName); - PipelineOptions methodOptions = options.as(klass); - InvocationHandler handler = Proxy.getInvocationHandler(methodOptions); - ValueProvider result = - (ValueProvider) handler.invoke(methodOptions, method, null); - // Two cases: If we have deserialized a new value from JSON, it will - // be wrapped in a StaticValueProvider, which we can provide here. If - // not, there was no JSON value, and we return the default, whether or - // not it is null. - if (result instanceof StaticValueProvider) { - return result.get(); - } - return defaultValue; - } catch (Throwable e) { - throw new RuntimeException("Unable to load runtime value.", e); - } - } - - @Override - public boolean isAccessible() { - PipelineOptions options = optionsMap.get(optionsId); - return options != null; - } - - /** - * Returns the property name that corresponds to this provider. - */ - public String propertyName() { - return propertyName; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("propertyName", propertyName) - .add("default", defaultValue) - .add("value", isAccessible() ? get() : null) - .toString(); - } - } - - /** - * Serializer for {@link ValueProvider}. - */ - class Serializer extends JsonSerializer> { - @Override - public void serialize(ValueProvider value, JsonGenerator jgen, - SerializerProvider provider) throws IOException { - if (value.isAccessible()) { - jgen.writeObject(value.get()); - } else { - jgen.writeNull(); - } - } - } - - /** - * Deserializer for {@link ValueProvider}, which handles type marshalling. - */ - class Deserializer extends JsonDeserializer> - implements ContextualDeserializer { - - private final JavaType innerType; - - // A 0-arg constructor is required by the compiler. - Deserializer() { - this.innerType = null; - } - - Deserializer(JavaType innerType) { - this.innerType = innerType; - } - - @Override - public JsonDeserializer createContextual(DeserializationContext ctxt, - BeanProperty property) - throws JsonMappingException { - checkNotNull(ctxt, "Null DeserializationContext."); - JavaType type = checkNotNull(ctxt.getContextualType(), "Invalid type: %s", getClass()); - JavaType[] params = type.findTypeParameters(ValueProvider.class); - if (params.length != 1) { - throw new RuntimeException( - "Unable to derive type for ValueProvider: " + type.toString()); - } - JavaType param = params[0]; - return new Deserializer(param); - } - - @Override - public ValueProvider deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException, JsonProcessingException { - JsonDeserializer dser = ctxt.findRootValueDeserializer( - checkNotNull(innerType, "Invalid %s: innerType is null. Serialization error?", getClass())); - Object o = dser.deserialize(jp, ctxt); - return StaticValueProvider.of(o); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java deleted file mode 100644 index 8b628e8484..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtils.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import java.io.IOException; -import java.util.Map; - -/** - * Utilities for working with the {@link ValueProvider} interface. - */ -public class ValueProviderUtils { - private ValueProviderUtils() {} - - /** - * Given {@code serializedOptions} as a JSON-serialized {@link PipelineOptions}, updates - * the values according to the provided values in {@code runtimeValues}. - */ - public static String updateSerializedOptions( - String serializedOptions, Map runtimeValues) { - ObjectMapper mapper = new ObjectMapper(); - ObjectNode root, options; - try { - root = mapper.readValue(serializedOptions, ObjectNode.class); - options = (ObjectNode) root.get("options"); - checkNotNull(options, "Unable to locate 'options' in %s", serializedOptions); - } catch (IOException e) { - throw new RuntimeException( - String.format("Unable to parse %s", serializedOptions), e); - } - - for (Map.Entry entry : runtimeValues.entrySet()) { - options.put(entry.getKey(), entry.getValue()); - } - try { - return mapper.writeValueAsString(root); - } catch (IOException e) { - throw new RuntimeException("Unable to parse re-serialize options", e); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/package-info.java deleted file mode 100644 index cef995f115..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/options/package-info.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines {@link com.google.cloud.dataflow.sdk.options.PipelineOptions} for - * configuring pipeline execution. - * - *

              {@link com.google.cloud.dataflow.sdk.options.PipelineOptions} encapsulates the various - * parameters that describe how a pipeline should be run. {@code PipelineOptions} are created - * using a {@link com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory}. - */ -package com.google.cloud.dataflow.sdk.options; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/package-info.java deleted file mode 100644 index 5567f038ec..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/package-info.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Provides a simple, powerful model for building both batch and - * streaming parallel data processing - * {@link com.google.cloud.dataflow.sdk.Pipeline}s. - * - *

              To use the Google Cloud Dataflow SDK, you build a - * {@link com.google.cloud.dataflow.sdk.Pipeline}, which manages a graph of - * {@link com.google.cloud.dataflow.sdk.transforms.PTransform}s - * and the {@link com.google.cloud.dataflow.sdk.values.PCollection}s that - * the PTransforms consume and produce. - * - *

              Each Pipeline has a - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} to specify - * where and how it should run after pipeline construction is complete. - * - */ -package com.google.cloud.dataflow.sdk; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractor.java deleted file mode 100644 index ab87f2ea22..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractor.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.AggregatorRetriever; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.SetMultimap; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -/** - * Retrieves {@link Aggregator Aggregators} at each {@link ParDo} and returns a {@link Map} of - * {@link Aggregator} to the {@link PTransform PTransforms} in which it is present. - */ -public class AggregatorPipelineExtractor { - private final Pipeline pipeline; - - /** - * Creates an {@code AggregatorPipelineExtractor} for the given {@link Pipeline}. - */ - public AggregatorPipelineExtractor(Pipeline pipeline) { - this.pipeline = pipeline; - } - - /** - * Returns a {@link Map} between each {@link Aggregator} in the {@link Pipeline} to the {@link - * PTransform PTransforms} in which it is used. - */ - public Map, Collection>> getAggregatorSteps() { - HashMultimap, PTransform> aggregatorSteps = HashMultimap.create(); - pipeline.traverseTopologically(new AggregatorVisitor(aggregatorSteps)); - return aggregatorSteps.asMap(); - } - - private static class AggregatorVisitor implements PipelineVisitor { - private final SetMultimap, PTransform> aggregatorSteps; - - public AggregatorVisitor(SetMultimap, PTransform> aggregatorSteps) { - this.aggregatorSteps = aggregatorSteps; - } - - @Override - public void enterCompositeTransform(TransformTreeNode node) {} - - @Override - public void leaveCompositeTransform(TransformTreeNode node) {} - - @Override - public void visitTransform(TransformTreeNode node) { - PTransform transform = node.getTransform(); - addStepToAggregators(transform, getAggregators(transform)); - } - - private Collection> getAggregators(PTransform transform) { - if (transform != null) { - if (transform instanceof ParDo.Bound) { - return AggregatorRetriever.getAggregators(((ParDo.Bound) transform).getFn()); - } else if (transform instanceof ParDo.BoundMulti) { - return AggregatorRetriever.getAggregators(((ParDo.BoundMulti) transform).getFn()); - } - } - return Collections.emptyList(); - } - - private void addStepToAggregators( - PTransform transform, Collection> aggregators) { - for (Aggregator aggregator : aggregators) { - aggregatorSteps.put(aggregator, transform); - } - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) {} - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorRetrievalException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorRetrievalException.java deleted file mode 100644 index 90162aded2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorRetrievalException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; - -/** - * Signals that an exception has occurred while retrieving {@link Aggregator}s. - */ -public class AggregatorRetrievalException extends Exception { - /** - * Constructs a new {@code AggregatorRetrievalException} with the specified detail message and - * cause. - */ - public AggregatorRetrievalException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorValues.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorValues.java deleted file mode 100644 index 21f02821c5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/AggregatorValues.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn; - -import java.util.Collection; -import java.util.Map; - -/** - * A collection of values associated with an {@link Aggregator}. Aggregators declared in a - * {@link DoFn} are emitted on a per-{@code DoFn}-application basis. - * - * @param the output type of the aggregator - */ -public abstract class AggregatorValues { - /** - * Get the values of the {@link Aggregator} at all steps it was used. - */ - public Collection getValues() { - return getValuesAtSteps().values(); - } - - /** - * Get the values of the {@link Aggregator} by the user name at each step it was used. - */ - public abstract Map getValuesAtSteps(); - - /** - * Get the total value of this {@link Aggregator} by applying the specified {@link CombineFn}. - */ - public T getTotalValue(CombineFn combineFn) { - return combineFn.apply(getValues()); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java deleted file mode 100644 index 7b45e5b34e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.options.BlockingDataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * A {@link PipelineRunner} that's like {@link DataflowPipelineRunner} - * but that waits for the launched job to finish. - * - *

              Prints out job status updates and console messages while it waits. - * - *

              Returns the final job state, or throws an exception if the job - * fails or cannot be monitored. - * - *

              Permissions

              - * When reading from a Dataflow source or writing to a Dataflow sink using - * {@code BlockingDataflowPipelineRunner}, the Google cloud services account and the Google compute - * engine service account of the GCP project running the Dataflow Job will need access to the - * corresponding source/sink. - * - *

              Please see Google Cloud - * Dataflow Security and Permissions for more details. - */ -public class BlockingDataflowPipelineRunner extends - PipelineRunner { - private static final Logger LOG = LoggerFactory.getLogger(BlockingDataflowPipelineRunner.class); - - // Defaults to an infinite wait period. - // TODO: make this configurable after removal of option map. - private static final long BUILTIN_JOB_TIMEOUT_SEC = -1L; - - private final DataflowPipelineRunner dataflowPipelineRunner; - private final BlockingDataflowPipelineOptions options; - - protected BlockingDataflowPipelineRunner( - DataflowPipelineRunner internalRunner, - BlockingDataflowPipelineOptions options) { - this.dataflowPipelineRunner = internalRunner; - this.options = options; - } - - /** - * Constructs a runner from the provided options. - */ - public static BlockingDataflowPipelineRunner fromOptions( - PipelineOptions options) { - BlockingDataflowPipelineOptions dataflowOptions = - PipelineOptionsValidator.validate(BlockingDataflowPipelineOptions.class, options); - DataflowPipelineRunner dataflowPipelineRunner = - DataflowPipelineRunner.fromOptions(dataflowOptions); - - return new BlockingDataflowPipelineRunner(dataflowPipelineRunner, dataflowOptions); - } - - /** - * {@inheritDoc} - * - * @throws DataflowJobExecutionException if there is an exception during job execution. - * @throws DataflowServiceException if there is an exception retrieving information about the job. - */ - @Override - public DataflowPipelineJob run(Pipeline p) { - final DataflowPipelineJob job = dataflowPipelineRunner.run(p); - - // We ignore the potential race condition here (Ctrl-C after job submission but before the - // shutdown hook is registered). Even if we tried to do something smarter (eg., SettableFuture) - // the run method (which produces the job) could fail or be Ctrl-C'd before it had returned a - // job. The display of the command to cancel the job is best-effort anyways -- RPC's could fail, - // etc. If the user wants to verify the job was cancelled they should look at the job status. - Thread shutdownHook = new Thread() { - @Override - public void run() { - LOG.warn("Job is already running in Google Cloud Platform, Ctrl-C will not cancel it.\n" - + "To cancel the job in the cloud, run:\n> {}", - MonitoringUtil.getGcloudCancelCommand(options, job.getJobId())); - } - }; - - try { - Runtime.getRuntime().addShutdownHook(shutdownHook); - - @Nullable - State result; - try { - result = job.waitToFinish( - BUILTIN_JOB_TIMEOUT_SEC, TimeUnit.SECONDS, - new MonitoringUtil.PrintHandler(options.getJobMessageOutput())); - } catch (IOException | InterruptedException ex) { - if (ex instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - LOG.debug("Exception caught while retrieving status for job {}", job.getJobId(), ex); - throw new DataflowServiceException( - job, "Exception caught while retrieving status for job " + job.getJobId(), ex); - } - - if (result == null) { - throw new DataflowServiceException( - job, "Timed out while retrieving status for job " + job.getJobId()); - } - - LOG.info("Job finished with status {}", result); - if (!result.isTerminal()) { - throw new IllegalStateException("Expected terminal state for job " + job.getJobId() - + ", got " + result); - } - - if (result == State.DONE) { - return job; - } else if (result == State.UPDATED) { - DataflowPipelineJob newJob = job.getReplacedByJob(); - LOG.info("Job {} has been updated and is running as the new job with id {}." - + "To access the updated job on the Dataflow monitoring console, please navigate to {}", - job.getJobId(), - newJob.getJobId(), - MonitoringUtil.getJobMonitoringPageURL(newJob.getProjectId(), newJob.getJobId())); - throw new DataflowJobUpdatedException( - job, - String.format("Job %s updated; new job is %s.", job.getJobId(), newJob.getJobId()), - newJob); - } else if (result == State.CANCELLED) { - String message = String.format("Job %s cancelled by user", job.getJobId()); - LOG.info(message); - throw new DataflowJobCancelledException(job, message); - } else { - throw new DataflowJobExecutionException(job, "Job " + job.getJobId() - + " failed with status " + result); - } - } finally { - Runtime.getRuntime().removeShutdownHook(shutdownHook); - } - } - - @Override - public OutputT apply( - PTransform transform, InputT input) { - return dataflowPipelineRunner.apply(transform, input); - } - - /** - * Sets callbacks to invoke during execution. See {@link DataflowPipelineRunnerHooks}. - */ - @Experimental - public void setHooks(DataflowPipelineRunnerHooks hooks) { - this.dataflowPipelineRunner.setHooks(hooks); - } - - @Override - public String toString() { - return "BlockingDataflowPipelineRunner#" + options.getJobName(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyExistsException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyExistsException.java deleted file mode 100644 index 1547f73efe..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyExistsException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -/** - * An exception that is thrown if the unique job name constraint of the Dataflow - * service is broken because an existing job with the same job name is currently active. - * The {@link DataflowPipelineJob} contained within this exception contains information - * about the pre-existing job. - */ -public class DataflowJobAlreadyExistsException extends DataflowJobException { - /** - * Create a new {@code DataflowJobAlreadyExistsException} with the specified {@link - * DataflowPipelineJob} and message. - */ - public DataflowJobAlreadyExistsException( - DataflowPipelineJob job, String message) { - super(job, message, null); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyUpdatedException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyUpdatedException.java deleted file mode 100644 index d4ae4f514d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobAlreadyUpdatedException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -/** - * An exception that is thrown if the existing job has already been updated within the Dataflow - * service and is no longer able to be updated. The {@link DataflowPipelineJob} contained within - * this exception contains information about the pre-existing updated job. - */ -public class DataflowJobAlreadyUpdatedException extends DataflowJobException { - /** - * Create a new {@code DataflowJobAlreadyUpdatedException} with the specified {@link - * DataflowPipelineJob} and message. - */ - public DataflowJobAlreadyUpdatedException( - DataflowPipelineJob job, String message) { - super(job, message, null); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobCancelledException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobCancelledException.java deleted file mode 100644 index 0d31726ee9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobCancelledException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -/** - * Signals that a job run by a {@link BlockingDataflowPipelineRunner} was updated during execution. - */ -public class DataflowJobCancelledException extends DataflowJobException { - /** - * Create a new {@code DataflowJobAlreadyUpdatedException} with the specified {@link - * DataflowPipelineJob} and message. - */ - public DataflowJobCancelledException(DataflowPipelineJob job, String message) { - super(job, message, null); - } - - /** - * Create a new {@code DataflowJobAlreadyUpdatedException} with the specified {@link - * DataflowPipelineJob}, message, and cause. - */ - public DataflowJobCancelledException(DataflowPipelineJob job, String message, Throwable cause) { - super(job, message, cause); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobException.java deleted file mode 100644 index 9e305d565c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import java.util.Objects; - -import javax.annotation.Nullable; - -/** - * A {@link RuntimeException} that contains information about a {@link DataflowPipelineJob}. - */ -public abstract class DataflowJobException extends RuntimeException { - private final DataflowPipelineJob job; - - DataflowJobException(DataflowPipelineJob job, String message, @Nullable Throwable cause) { - super(message, cause); - this.job = Objects.requireNonNull(job); - } - - /** - * Returns the failed job. - */ - public DataflowPipelineJob getJob() { - return job; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobExecutionException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobExecutionException.java deleted file mode 100644 index ae6df0fa65..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobExecutionException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import javax.annotation.Nullable; - -/** - * Signals that a job run by a {@link BlockingDataflowPipelineRunner} fails during execution, and - * provides access to the failed job. - */ -public class DataflowJobExecutionException extends DataflowJobException { - DataflowJobExecutionException(DataflowPipelineJob job, String message) { - this(job, message, null); - } - - DataflowJobExecutionException( - DataflowPipelineJob job, String message, @Nullable Throwable cause) { - super(job, message, cause); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobUpdatedException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobUpdatedException.java deleted file mode 100644 index 1becdd7c10..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowJobUpdatedException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -/** - * Signals that a job run by a {@link BlockingDataflowPipelineRunner} was updated during execution. - */ -public class DataflowJobUpdatedException extends DataflowJobException { - private DataflowPipelineJob replacedByJob; - - /** - * Create a new {@code DataflowJobUpdatedException} with the specified original {@link - * DataflowPipelineJob}, message, and replacement {@link DataflowPipelineJob}. - */ - public DataflowJobUpdatedException( - DataflowPipelineJob job, String message, DataflowPipelineJob replacedByJob) { - this(job, message, replacedByJob, null); - } - - /** - * Create a new {@code DataflowJobUpdatedException} with the specified original {@link - * DataflowPipelineJob}, message, replacement {@link DataflowPipelineJob}, and cause. - */ - public DataflowJobUpdatedException( - DataflowPipelineJob job, String message, DataflowPipelineJob replacedByJob, Throwable cause) { - super(job, message, cause); - this.replacedByJob = replacedByJob; - } - - /** - * The new job that replaces the job terminated with this exception. - */ - public DataflowPipelineJob getReplacedByJob() { - return replacedByJob; - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipeline.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipeline.java deleted file mode 100644 index 5a78624f3c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipeline.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -/** - * A {@link DataflowPipeline} is a {@link Pipeline} that returns a - * {@link DataflowPipelineJob} when it is - * {@link com.google.cloud.dataflow.sdk.Pipeline#run()}. - * - *

              This is not intended for use by users of Cloud Dataflow. - * Instead, use {@link Pipeline#create(PipelineOptions)} to initialize a - * {@link Pipeline}. - */ -public class DataflowPipeline extends Pipeline { - - /** - * Creates and returns a new {@link DataflowPipeline} instance for tests. - */ - public static DataflowPipeline create(DataflowPipelineOptions options) { - return new DataflowPipeline(options); - } - - private DataflowPipeline(DataflowPipelineOptions options) { - super(DataflowPipelineRunner.fromOptions(options), options); - } - - @Override - public DataflowPipelineJob run() { - return (DataflowPipelineJob) super.run(); - } - - @Override - public DataflowPipelineRunner getRunner() { - return (DataflowPipelineRunner) super.getRunner(); - } - - @Override - public String toString() { - return "DataflowPipeline#" + getOptions().as(DataflowPipelineOptions.class).getJobName(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java deleted file mode 100644 index 4a68755565..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudTime; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.NanoClock; -import com.google.api.client.util.Sleeper; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.JobMessage; -import com.google.api.services.dataflow.model.JobMetrics; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowMetricUpdateExtractor; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.util.FluentBackoff; -import com.google.cloud.dataflow.sdk.util.MapAggregatorValues; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.common.annotations.VisibleForTesting; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * A DataflowPipelineJob represents a job submitted to Dataflow using - * {@link DataflowPipelineRunner}. - */ -public class DataflowPipelineJob implements PipelineResult { - private static final Logger LOG = LoggerFactory.getLogger(DataflowPipelineJob.class); - - /** - * The id for the job. - */ - private String jobId; - - /** - * Google cloud project to associate this pipeline with. - */ - private String projectId; - - /** - * Client for the Dataflow service. This can be used to query the service - * for information about the job. - */ - private Dataflow dataflowClient; - - /** - * The state the job terminated in or {@code null} if the job has not terminated. - */ - @Nullable - private State terminalState = null; - - /** - * The job that replaced this one or {@code null} if the job has not been replaced. - */ - @Nullable - private DataflowPipelineJob replacedByJob = null; - - private DataflowAggregatorTransforms aggregatorTransforms; - - /** - * The Metric Updates retrieved after the job was in a terminal state. - */ - private List terminalMetricUpdates; - - /** - * The polling interval for job status and messages information. - */ - static final Duration MESSAGES_POLLING_INTERVAL = Duration.standardSeconds(2); - static final Duration STATUS_POLLING_INTERVAL = Duration.standardSeconds(2); - - static final double DEFAULT_BACKOFF_EXPONENT = 1.5; - - /** - * The amount of polling retries for job status and messages information. - */ - static final int MESSAGES_POLLING_RETRIES = 11; - static final int STATUS_POLLING_RETRIES = 4; - - private static final FluentBackoff MESSAGES_BACKOFF_FACTORY = - FluentBackoff.DEFAULT - .withInitialBackoff(MESSAGES_POLLING_INTERVAL) - .withMaxRetries(MESSAGES_POLLING_RETRIES) - .withExponent(DEFAULT_BACKOFF_EXPONENT); - protected static final FluentBackoff STATUS_BACKOFF_FACTORY = - FluentBackoff.DEFAULT - .withInitialBackoff(STATUS_POLLING_INTERVAL) - .withMaxRetries(STATUS_POLLING_RETRIES) - .withExponent(DEFAULT_BACKOFF_EXPONENT); - - /** - * Constructs the job. - * - * @param projectId the project id - * @param jobId the job id - * @param dataflowClient the client for the Dataflow Service - */ - public DataflowPipelineJob(String projectId, String jobId, Dataflow dataflowClient, - DataflowAggregatorTransforms aggregatorTransforms) { - this.projectId = projectId; - this.jobId = jobId; - this.dataflowClient = dataflowClient; - this.aggregatorTransforms = aggregatorTransforms; - } - - /** - * Get the id of this job. - */ - public String getJobId() { - return jobId; - } - - /** - * Get the project this job exists in. - */ - public String getProjectId() { - return projectId; - } - - /** - * Returns a new {@link DataflowPipelineJob} for the job that replaced this one, if applicable. - * - * @throws IllegalStateException if called before the job has terminated or if the job terminated - * but was not updated - */ - public DataflowPipelineJob getReplacedByJob() { - if (terminalState == null) { - throw new IllegalStateException("getReplacedByJob() called before job terminated"); - } - if (replacedByJob == null) { - throw new IllegalStateException("getReplacedByJob() called for job that was not replaced"); - } - return replacedByJob; - } - - /** - * Get the Cloud Dataflow API Client used by this job. - */ - public Dataflow getDataflowClient() { - return dataflowClient; - } - - /** - * Waits for the job to finish and return the final status. - * - * @param timeToWait The time to wait in units timeUnit for the job to finish. - * Provide a value less than 1 ms for an infinite wait. - * @param timeUnit The unit of time for timeToWait. - * @param messageHandler If non null this handler will be invoked for each - * batch of messages received. - * @return The final state of the job or null on timeout or if the - * thread is interrupted. - * @throws IOException If there is a persistent problem getting job - * information. - * @throws InterruptedException - */ - @Nullable - public State waitToFinish( - long timeToWait, - TimeUnit timeUnit, - MonitoringUtil.JobMessagesHandler messageHandler) - throws IOException, InterruptedException { - Duration duration = Duration.millis(timeUnit.toMillis(timeToWait)); - return waitToFinish(duration, messageHandler, Sleeper.DEFAULT, NanoClock.SYSTEM); - } - - /** - * Wait for the job to finish and return the final status. - * - * @param duration The total time to wait for the job to finish. - * Provide a value less than 1 ms for an infinite wait. - * @param messageHandler If non null this handler will be invoked for each - * batch of messages received. - * @param sleeper A sleeper to use to sleep between attempts. - * @param nanoClock A nanoClock used to time the total time taken. - * @return The final state of the job or null on timeout or if the - * thread is interrupted. - * @throws IOException If there is a persistent problem getting job - * information. - * @throws InterruptedException - */ - @Nullable - @VisibleForTesting - State waitToFinish( - Duration duration, - MonitoringUtil.JobMessagesHandler messageHandler, - Sleeper sleeper, - NanoClock nanoClock) - throws IOException, InterruptedException { - MonitoringUtil monitor = new MonitoringUtil(projectId, dataflowClient); - - long lastTimestamp = 0; - BackOff backoff; - if (!duration.isLongerThan(Duration.ZERO)) { - backoff = MESSAGES_BACKOFF_FACTORY.backoff(); - } else { - backoff = MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(duration).backoff(); - } - - // This function tracks the cumulative time from the *first request* to enforce the wall-clock - // limit. Any backoff instance could, at best, track the the time since the first attempt at a - // given request. Thus, we need to track the cumulative time ourselves. - long startNanos = nanoClock.nanoTime(); - - State state; - do { - // Get the state of the job before listing messages. This ensures we always fetch job - // messages after the job finishes to ensure we have all them. - state = getStateWithRetries(STATUS_BACKOFF_FACTORY.withMaxRetries(0).backoff(), sleeper); - boolean hasError = state == State.UNKNOWN; - - if (messageHandler != null && !hasError) { - // Process all the job messages that have accumulated so far. - try { - List allMessages = monitor.getJobMessages( - jobId, lastTimestamp); - - if (!allMessages.isEmpty()) { - lastTimestamp = - fromCloudTime(allMessages.get(allMessages.size() - 1).getTime()).getMillis(); - messageHandler.process(allMessages); - } - } catch (GoogleJsonResponseException | SocketTimeoutException e) { - hasError = true; - LOG.warn("There were problems getting current job messages: {}.", e.getMessage()); - LOG.debug("Exception information:", e); - } - } - - if (!hasError) { - // We can stop if the job is done. - if (state.isTerminal()) { - return state; - } - - // The job is not done, so we must keep polling. - backoff.reset(); - - // If a total duration for all backoff has been set, update the new cumulative sleep time to - // be the remaining total backoff duration, stopping if we have already exceeded the - // allotted time. - if (duration.isLongerThan(Duration.ZERO)) { - long nanosConsumed = nanoClock.nanoTime() - startNanos; - Duration consumed = Duration.millis((nanosConsumed + 999999) / 1000000); - Duration remaining = duration.minus(consumed); - if (remaining.isLongerThan(Duration.ZERO)) { - backoff = MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(remaining).backoff(); - } else { - // If there is no time remaining, don't bother backing off. - backoff = BackOff.STOP_BACKOFF; - } - } - } - } while(BackOffUtils.next(sleeper, backoff)); - LOG.warn("No terminal state was returned. State value {}", state); - return null; // Timed out. - } - - /** - * Cancels the job. - * @throws IOException if there is a problem executing the cancel request. - */ - public void cancel() throws IOException { - Job content = new Job(); - content.setProjectId(projectId); - content.setId(jobId); - content.setRequestedState("JOB_STATE_CANCELLED"); - dataflowClient.projects().jobs() - .update(projectId, jobId, content) - .execute(); - } - - @Override - public State getState() { - if (terminalState != null) { - return terminalState; - } - - return getStateWithRetries(STATUS_BACKOFF_FACTORY.backoff(), Sleeper.DEFAULT); - } - - /** - * Attempts to get the state. Uses exponential backoff on failure up to the maximum number - * of passed in attempts. - * - * @param attempts The amount of attempts to make. - * @param sleeper Object used to do the sleeps between attempts. - * @return The state of the job or State.UNKNOWN in case of failure. - */ - @VisibleForTesting - State getStateWithRetries(BackOff attempts, Sleeper sleeper) { - if (terminalState != null) { - return terminalState; - } - try { - Job job = getJobWithRetries(attempts, sleeper); - return MonitoringUtil.toState(job.getCurrentState()); - } catch (IOException exn) { - // The only IOException that getJobWithRetries is permitted to throw is the final IOException - // that caused the failure of retry. Other exceptions are wrapped in an unchecked exceptions - // and will propagate. - return State.UNKNOWN; - } - } - - /** - * Attempts to get the underlying {@link Job}. Uses exponential backoff on failure up to the - * maximum number of passed in attempts. - * - * @param backoff the {@link BackOff} used to control retries. - * @param sleeper Object used to do the sleeps between attempts. - * @return The underlying {@link Job} object. - * @throws IOException When the maximum number of retries is exhausted, the last exception is - * thrown. - */ - private Job getJobWithRetries(BackOff backoff, Sleeper sleeper) throws IOException { - // Retry loop ends in return or throw - while (true) { - try { - Job job = dataflowClient - .projects() - .jobs() - .get(projectId, jobId) - .execute(); - State currentState = MonitoringUtil.toState(job.getCurrentState()); - if (currentState.isTerminal()) { - terminalState = currentState; - replacedByJob = new DataflowPipelineJob( - getProjectId(), job.getReplacedByJobId(), dataflowClient, aggregatorTransforms); - } - return job; - } catch (IOException exn) { - LOG.warn("There were problems getting current job status: {}.", exn.getMessage()); - LOG.debug("Exception information:", exn); - - if (!nextBackOff(sleeper, backoff)) { - throw exn; - } - } - } - } - - /** - * Identical to {@link BackOffUtils#next} but without checked exceptions. - */ - private boolean nextBackOff(Sleeper sleeper, BackOff backoff) { - try { - return BackOffUtils.next(sleeper, backoff); - } catch (InterruptedException | IOException e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - throw new RuntimeException(e); - } - } - - @Override - public AggregatorValues getAggregatorValues(Aggregator aggregator) - throws AggregatorRetrievalException { - try { - return new MapAggregatorValues<>(fromMetricUpdates(aggregator)); - } catch (IOException e) { - throw new AggregatorRetrievalException( - "IOException when retrieving Aggregator values for Aggregator " + aggregator, e); - } - } - - private Map fromMetricUpdates(Aggregator aggregator) - throws IOException { - if (aggregatorTransforms.contains(aggregator)) { - List metricUpdates; - if (terminalMetricUpdates != null) { - metricUpdates = terminalMetricUpdates; - } else { - boolean terminal = getState().isTerminal(); - JobMetrics jobMetrics = - dataflowClient.projects().jobs().getMetrics(projectId, jobId).execute(); - metricUpdates = jobMetrics.getMetrics(); - if (terminal && jobMetrics.getMetrics() != null) { - terminalMetricUpdates = metricUpdates; - } - } - - return DataflowMetricUpdateExtractor.fromMetricUpdates( - aggregator, aggregatorTransforms, metricUpdates); - } else { - throw new IllegalArgumentException( - "Aggregator " + aggregator + " is not used in this pipeline"); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrar.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrar.java deleted file mode 100644 index 0e4d4e96b9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrar.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.auto.service.AutoService; -import com.google.cloud.dataflow.sdk.options.BlockingDataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; -import com.google.common.collect.ImmutableList; - -/** - * Contains the {@link PipelineOptionsRegistrar} and {@link PipelineRunnerRegistrar} for - * the {@link DataflowPipeline}. - */ -public class DataflowPipelineRegistrar { - private DataflowPipelineRegistrar() { } - - /** - * Register the {@link DataflowPipelineOptions} and {@link BlockingDataflowPipelineOptions}. - */ - @AutoService(PipelineOptionsRegistrar.class) - public static class Options implements PipelineOptionsRegistrar { - @Override - public Iterable> getPipelineOptions() { - return ImmutableList.>of( - DataflowPipelineOptions.class, - BlockingDataflowPipelineOptions.class); - } - } - - /** - * Register the {@link DataflowPipelineRunner} and {@link BlockingDataflowPipelineRunner}. - */ - @AutoService(PipelineRunnerRegistrar.class) - public static class Runner implements PipelineRunnerRegistrar { - @Override - public Iterable>> getPipelineRunners() { - return ImmutableList.>>of( - DataflowPipelineRunner.class, - BlockingDataflowPipelineRunner.class); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java deleted file mode 100644 index f4cdba516b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java +++ /dev/null @@ -1,3251 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.cloud.dataflow.sdk.util.StringUtils.approximatePTransformName; -import static com.google.cloud.dataflow.sdk.util.StringUtils.approximateSimpleName; -import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInEmptyWindows; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.json.JsonFactory; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.clouddebugger.v2.Clouddebugger; -import com.google.api.services.clouddebugger.v2.model.Debuggee; -import com.google.api.services.clouddebugger.v2.model.RegisterDebuggeeRequest; -import com.google.api.services.clouddebugger.v2.model.RegisterDebuggeeResponse; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.ListJobsResponse; -import com.google.api.services.dataflow.model.WorkerPool; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.FileBasedSink; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO.Read.Bound.PubsubReader; -import com.google.cloud.dataflow.sdk.io.PubsubIO.Write.Bound.PubsubWriter; -import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSink; -import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.io.Write; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; -import com.google.cloud.dataflow.sdk.options.StreamingOptions; -import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.JobSpecification; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.runners.dataflow.AssignWindows; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource; -import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; -import com.google.cloud.dataflow.sdk.util.MimeTypes; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.util.PCollectionViews; -import com.google.cloud.dataflow.sdk.util.PathValidator; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.Reshuffle; -import com.google.cloud.dataflow.sdk.util.SystemDoFnInternal; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.util.ValueWithRecordId; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.base.Optional; -import com.google.common.base.Strings; -import com.google.common.base.Utf8; -import com.google.common.collect.ForwardingMap; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.DateTimeUtils; -import org.joda.time.DateTimeZone; -import org.joda.time.Duration; -import org.joda.time.format.DateTimeFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.Serializable; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.annotation.Nullable; - -/** - * A {@link PipelineRunner} that executes the operations in the - * pipeline by first translating them to the Dataflow representation - * using the {@link DataflowPipelineTranslator} and then submitting - * them to a Dataflow service for execution. - * - *

              Permissions

              - * When reading from a Dataflow source or writing to a Dataflow sink using - * {@code DataflowPipelineRunner}, the Google cloudservices account and the Google compute engine - * service account of the GCP project running the Dataflow Job will need access to the corresponding - * source/sink. - * - *

              Please see Google Cloud - * Dataflow Security and Permissions for more details. - */ -public class DataflowPipelineRunner extends PipelineRunner { - private static final Logger LOG = LoggerFactory.getLogger(DataflowPipelineRunner.class); - - /** Provided configuration options. */ - private final DataflowPipelineOptions options; - - /** Client for the Dataflow service. This is used to actually submit jobs. */ - private final Dataflow dataflowClient; - - /** Translator for this DataflowPipelineRunner, based on options. */ - private final DataflowPipelineTranslator translator; - - /** Custom transforms implementations. */ - private final Map, Class> overrides; - - /** A set of user defined functions to invoke at different points in execution. */ - private DataflowPipelineRunnerHooks hooks; - - // Environment version information. - private static final String ENVIRONMENT_MAJOR_VERSION = "6"; - - // Default Docker container images that execute Dataflow worker harness, residing in Google - // Container Registry, separately for Batch and Streaming. - public static final String BATCH_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-batch:1.9.0"; - public static final String STREAMING_WORKER_HARNESS_CONTAINER_IMAGE - = "dataflow.gcr.io/v1beta3/java-streaming:1.9.0"; - - // The limit of CreateJob request size. - private static final int CREATE_JOB_REQUEST_LIMIT_BYTES = 10 * 1024 * 1024; - - @VisibleForTesting - static final int GCS_UPLOAD_BUFFER_SIZE_BYTES_DEFAULT = 1 * 1024 * 1024; - - private final Set> pcollectionsRequiringIndexedFormat; - - /** - * Project IDs must contain lowercase letters, digits, or dashes. - * IDs must start with a letter and may not end with a dash. - * This regex isn't exact - this allows for patterns that would be rejected by - * the service, but this is sufficient for basic validation of project IDs. - */ - public static final String PROJECT_ID_REGEXP = "[a-z][-a-z0-9:.]+[a-z0-9]"; - - private static final JsonFactory JSON_FACTORY = Transport.getJsonFactory(); - /** - * Construct a runner from the provided options. - * - * @param options Properties that configure the runner. - * @return The newly created runner. - */ - public static DataflowPipelineRunner fromOptions(PipelineOptions options) { - // (Re-)register standard IO factories. Clobbers any prior credentials. - IOChannelUtils.registerStandardIOFactories(options); - - DataflowPipelineOptions dataflowOptions = - PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options); - ArrayList missing = new ArrayList<>(); - - if (dataflowOptions.getAppName() == null) { - missing.add("appName"); - } - if (missing.size() > 0) { - throw new IllegalArgumentException( - "Missing required values: " + Joiner.on(',').join(missing)); - } - - PathValidator validator = dataflowOptions.getPathValidator(); - checkArgument(!(Strings.isNullOrEmpty(dataflowOptions.getTempLocation()) - && Strings.isNullOrEmpty(dataflowOptions.getStagingLocation())), - "Missing required value: at least one of tempLocation or stagingLocation must be set."); - - if (dataflowOptions.getStagingLocation() != null) { - validator.validateOutputFilePrefixSupported(dataflowOptions.getStagingLocation()); - } - if (dataflowOptions.getTempLocation() != null) { - validator.validateOutputFilePrefixSupported(dataflowOptions.getTempLocation()); - } - if (!Strings.isNullOrEmpty(dataflowOptions.getSaveProfilesToGcs())) { - validator.validateOutputFilePrefixSupported(dataflowOptions.getSaveProfilesToGcs()); - } - if (dataflowOptions.getEnableProfilingAgent()) { - LOG.error("--enableProfilingAgent is no longer supported, and will be ignored. " - + "Use --saveProfilesToGcs instead."); - } - - if (Strings.isNullOrEmpty(dataflowOptions.getTempLocation())) { - dataflowOptions.setTempLocation(dataflowOptions.getStagingLocation()); - } else if (Strings.isNullOrEmpty(dataflowOptions.getStagingLocation())) { - try { - dataflowOptions.setStagingLocation( - IOChannelUtils.resolve(dataflowOptions.getTempLocation(), "staging")); - } catch (IOException e) { - throw new IllegalArgumentException("Unable to resolve PipelineOptions.stagingLocation " - + "from PipelineOptions.tempLocation. Please set the staging location explicitly.", e); - } - } - - if (dataflowOptions.getFilesToStage() == null) { - dataflowOptions.setFilesToStage(detectClassPathResourcesToStage( - DataflowPipelineRunner.class.getClassLoader())); - LOG.info("PipelineOptions.filesToStage was not specified. " - + "Defaulting to files from the classpath: will stage {} files. " - + "Enable logging at DEBUG level to see which files will be staged.", - dataflowOptions.getFilesToStage().size()); - LOG.debug("Classpath elements: {}", dataflowOptions.getFilesToStage()); - } - - // Verify jobName according to service requirements, truncating converting to lowercase if - // necessary. - String jobName = - dataflowOptions - .getJobName() - .toLowerCase(); - checkArgument( - jobName.matches("[a-z]([-a-z0-9]*[a-z0-9])?"), - "JobName invalid; the name must consist of only the characters " - + "[-a-z0-9], starting with a letter and ending with a letter " - + "or number"); - if (!jobName.equals(dataflowOptions.getJobName())) { - LOG.info( - "PipelineOptions.jobName did not match the service requirements. " - + "Using {} instead of {}.", - jobName, - dataflowOptions.getJobName()); - } - dataflowOptions.setJobName(jobName); - - // Verify project - String project = dataflowOptions.getProject(); - if (project.matches("[0-9]*")) { - throw new IllegalArgumentException("Project ID '" + project - + "' invalid. Please make sure you specified the Project ID, not project number."); - } else if (!project.matches(PROJECT_ID_REGEXP)) { - throw new IllegalArgumentException("Project ID '" + project - + "' invalid. Please make sure you specified the Project ID, not project description."); - } - - DataflowPipelineDebugOptions debugOptions = - dataflowOptions.as(DataflowPipelineDebugOptions.class); - // Verify the number of worker threads is a valid value - if (debugOptions.getNumberOfWorkerHarnessThreads() < 0) { - throw new IllegalArgumentException("Number of worker harness threads '" - + debugOptions.getNumberOfWorkerHarnessThreads() - + "' invalid. Please make sure the value is non-negative."); - } - - if (dataflowOptions.isStreaming() && dataflowOptions.getGcsUploadBufferSizeBytes() == null) { - dataflowOptions.setGcsUploadBufferSizeBytes(GCS_UPLOAD_BUFFER_SIZE_BYTES_DEFAULT); - } - return new DataflowPipelineRunner(dataflowOptions); - } - - @VisibleForTesting protected DataflowPipelineRunner(DataflowPipelineOptions options) { - this.options = options; - this.dataflowClient = options.getDataflowClient(); - this.translator = DataflowPipelineTranslator.fromOptions(options); - this.pcollectionsRequiringIndexedFormat = new HashSet<>(); - this.ptransformViewsWithNonDeterministicKeyCoders = new HashSet<>(); - - ImmutableMap.Builder, Class> builder = ImmutableMap., Class>builder(); - if (options.isStreaming()) { - builder.put(Combine.GloballyAsSingletonView.class, - StreamingCombineGloballyAsSingletonView.class); - builder.put(Create.Values.class, StreamingCreate.class); - builder.put(View.AsMap.class, StreamingViewAsMap.class); - builder.put(View.AsMultimap.class, StreamingViewAsMultimap.class); - builder.put(View.AsSingleton.class, StreamingViewAsSingleton.class); - builder.put(View.AsList.class, StreamingViewAsList.class); - builder.put(View.AsIterable.class, StreamingViewAsIterable.class); - builder.put(Read.Unbounded.class, StreamingUnboundedRead.class); - builder.put(Read.Bounded.class, StreamingBoundedRead.class); - builder.put(AvroIO.Write.Bound.class, UnsupportedIO.class); - builder.put(Window.Bound.class, AssignWindows.class); - // In streaming mode must use either the custom Pubsub unbounded source/sink or - // defer to Windmill's built-in implementation. - builder.put(PubsubReader.class, UnsupportedIO.class); - builder.put(PubsubWriter.class, UnsupportedIO.class); - if (options.getExperiments() == null - || !options.getExperiments().contains("enable_custom_pubsub_sink")) { - builder.put(PubsubIO.Write.Bound.class, StreamingPubsubIOWrite.class); - } - } else { - builder.put(Read.Unbounded.class, UnsupportedIO.class); - builder.put(Window.Bound.class, AssignWindows.class); - builder.put(Write.Bound.class, BatchWrite.class); - // In batch mode must use the custom Pubsub bounded source/sink. - builder.put(PubsubUnboundedSource.class, UnsupportedIO.class); - builder.put(PubsubUnboundedSink.class, UnsupportedIO.class); - if (options.getExperiments() == null - || !options.getExperiments().contains("disable_ism_side_input")) { - builder.put(View.AsMap.class, BatchViewAsMap.class); - builder.put(View.AsMultimap.class, BatchViewAsMultimap.class); - builder.put(View.AsSingleton.class, BatchViewAsSingleton.class); - builder.put(View.AsList.class, BatchViewAsList.class); - builder.put(View.AsIterable.class, BatchViewAsIterable.class); - } - if (options.getExperiments() == null - || !options.getExperiments().contains("enable_custom_bigquery_source")) { - builder.put(BigQueryIO.Read.Bound.class, BatchBigQueryIONativeRead.class); - } - if (options.getExperiments() == null - || !options.getExperiments().contains("enable_custom_bigquery_sink")) { - builder.put(BigQueryIO.Write.Bound.class, BatchBigQueryIOWrite.class); - } - } - overrides = builder.build(); - } - - /** - * Applies the given transform to the input. For transforms with customized definitions - * for the Dataflow pipeline runner, the application is intercepted and modified here. - */ - @Override - public OutputT apply( - PTransform transform, InputT input) { - - if (Combine.GroupedValues.class.equals(transform.getClass()) - || GroupByKey.class.equals(transform.getClass())) { - - // For both Dataflow runners (streaming and batch), GroupByKey and GroupedValues are - // primitives. Returning a primitive output instead of the expanded definition - // signals to the translator that translation is necessary. - @SuppressWarnings("unchecked") - PCollection pc = (PCollection) input; - @SuppressWarnings("unchecked") - OutputT outputT = (OutputT) PCollection.createPrimitiveOutputInternal( - pc.getPipeline(), - transform instanceof GroupByKey - ? ((GroupByKey) transform).updateWindowingStrategy(pc.getWindowingStrategy()) - : pc.getWindowingStrategy(), - pc.isBounded()); - return outputT; - } else if (PubsubIO.Read.Bound.class.equals(transform.getClass()) - && options.isStreaming() - && (options.getExperiments() == null - || !options.getExperiments().contains("enable_custom_pubsub_source"))) { - // casting to wildcard - @SuppressWarnings("unchecked") - OutputT pubsub = (OutputT) applyPubsubStreamingRead((PubsubIO.Read.Bound) transform, - input); - return pubsub; - } else if (Window.Bound.class.equals(transform.getClass())) { - /* - * TODO: make this the generic way overrides are applied (using super.apply() rather than - * Pipeline.applyTransform(); this allows the apply method to be replaced without inserting - * additional nodes into the graph. - */ - // casting to wildcard - @SuppressWarnings("unchecked") - OutputT windowed = (OutputT) applyWindow((Window.Bound) transform, (PCollection) input); - return windowed; - } else if (Flatten.FlattenPCollectionList.class.equals(transform.getClass()) - && ((PCollectionList) input).size() == 0) { - return (OutputT) Pipeline.applyTransform(input, Create.of()); - } else if (overrides.containsKey(transform.getClass())) { - // It is the responsibility of whoever constructs overrides to ensure this is type safe. - @SuppressWarnings("unchecked") - Class> transformClass = - (Class>) transform.getClass(); - - @SuppressWarnings("unchecked") - Class> customTransformClass = - (Class>) overrides.get(transform.getClass()); - - PTransform customTransform = - InstanceBuilder.ofType(customTransformClass) - .withArg(DataflowPipelineRunner.class, this) - .withArg(transformClass, transform) - .build(); - - return Pipeline.applyTransform(input, customTransform); - } else { - return super.apply(transform, input); - } - } - - private PCollection - applyPubsubStreamingRead(PubsubIO.Read.Bound initialTransform, PInput input) { - // types are matched at compile time - @SuppressWarnings("unchecked") - PubsubIO.Read.Bound transform = (PubsubIO.Read.Bound) initialTransform; - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED) - .setCoder(transform.getCoder()); - } - - private PCollection applyWindow( - Window.Bound intitialTransform, PCollection initialInput) { - // types are matched at compile time - @SuppressWarnings("unchecked") - Window.Bound transform = (Window.Bound) intitialTransform; - @SuppressWarnings("unchecked") - PCollection input = (PCollection) initialInput; - return super.apply(new AssignWindows<>(transform), input); - } - - private String debuggerMessage(String projectId, String uniquifier) { - return String.format("To debug your job, visit Google Cloud Debugger at: " - + "https://console.developers.google.com/debug?project=%s&dbgee=%s", - projectId, uniquifier); - } - - private void maybeRegisterDebuggee(DataflowPipelineOptions options, String uniquifier) { - if (!options.getEnableCloudDebugger()) { - return; - } - - if (options.getDebuggee() != null) { - throw new RuntimeException("Should not specify the debuggee"); - } - - Clouddebugger debuggerClient = Transport.newClouddebuggerClient(options).build(); - Debuggee debuggee = registerDebuggee(debuggerClient, uniquifier); - options.setDebuggee(debuggee); - - System.out.println(debuggerMessage(options.getProject(), debuggee.getUniquifier())); - } - - private Debuggee registerDebuggee(Clouddebugger debuggerClient, String uniquifier) { - RegisterDebuggeeRequest registerReq = new RegisterDebuggeeRequest(); - registerReq.setDebuggee(new Debuggee() - .setProject(options.getProject()) - .setUniquifier(uniquifier) - .setDescription(uniquifier) - .setAgentVersion("google.com/cloud-dataflow-java/v1")); - - try { - RegisterDebuggeeResponse registerResponse = - debuggerClient.controller().debuggees().register(registerReq).execute(); - Debuggee debuggee = registerResponse.getDebuggee(); - if (debuggee.getStatus() != null && debuggee.getStatus().getIsError()) { - throw new RuntimeException("Unable to register with the debugger: " - + debuggee.getStatus().getDescription().getFormat()); - } - - return debuggee; - } catch (IOException e) { - throw new RuntimeException("Unable to register with the debugger: ", e); - } - } - - @Override - public DataflowPipelineJob run(Pipeline pipeline) { - logWarningIfPCollectionViewHasNonDeterministicKeyCoder(pipeline); - - LOG.info("Executing pipeline on the Dataflow Service, which will have billing implications " - + "related to Google Compute Engine usage and other Google Cloud Services."); - - List packages = options.getStager().stageFiles(); - - - // Set a unique client_request_id in the CreateJob request. - // This is used to ensure idempotence of job creation across retried - // attempts to create a job. Specifically, if the service returns a job with - // a different client_request_id, it means the returned one is a different - // job previously created with the same job name, and that the job creation - // has been effectively rejected. The SDK should return - // Error::Already_Exists to user in that case. - int randomNum = new Random().nextInt(9000) + 1000; - String requestId = DateTimeFormat.forPattern("YYYYMMddHHmmssmmm").withZone(DateTimeZone.UTC) - .print(DateTimeUtils.currentTimeMillis()) + "_" + randomNum; - - // Try to create a debuggee ID. This must happen before the job is translated since it may - // update the options. - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - maybeRegisterDebuggee(dataflowOptions, requestId); - - JobSpecification jobSpecification = - translator.translate(pipeline, this, packages); - Job newJob = jobSpecification.getJob(); - newJob.setClientRequestId(requestId); - - String version = DataflowReleaseInfo.getReleaseInfo().getVersion(); - System.out.println("Dataflow SDK version: " + version); - - newJob.getEnvironment().setUserAgent(DataflowReleaseInfo.getReleaseInfo()); - // The Dataflow Service may write to the temporary directory directly, so - // must be verified. - if (!Strings.isNullOrEmpty(options.getTempLocation())) { - newJob.getEnvironment().setTempStoragePrefix( - dataflowOptions.getPathValidator().verifyPath(options.getTempLocation())); - } - newJob.getEnvironment().setDataset(options.getTempDatasetId()); - newJob.getEnvironment().setExperiments(options.getExperiments()); - - // Set the Docker container image that executes Dataflow worker harness, residing in Google - // Container Registry. Translator is guaranteed to create a worker pool prior to this point. - String workerHarnessContainerImage = - options.as(DataflowPipelineWorkerPoolOptions.class) - .getWorkerHarnessContainerImage(); - for (WorkerPool workerPool : newJob.getEnvironment().getWorkerPools()) { - workerPool.setWorkerHarnessContainerImage(workerHarnessContainerImage); - } - - // Requirements about the service. - Map environmentVersion = new HashMap<>(); - environmentVersion.put(PropertyNames.ENVIRONMENT_VERSION_MAJOR_KEY, ENVIRONMENT_MAJOR_VERSION); - newJob.getEnvironment().setVersion(environmentVersion); - // Default jobType is JAVA_BATCH_AUTOSCALING: A Java job with workers that the job can - // autoscale if specified. - String jobType = "JAVA_BATCH_AUTOSCALING"; - - if (options.isStreaming()) { - jobType = "STREAMING"; - } - environmentVersion.put(PropertyNames.ENVIRONMENT_VERSION_JOB_TYPE_KEY, jobType); - - if (hooks != null) { - hooks.modifyEnvironmentBeforeSubmission(newJob.getEnvironment()); - } - - if (!Strings.isNullOrEmpty(options.getDataflowJobFile())) { - runJobFileHooks(newJob); - } - if (hooks != null && !hooks.shouldActuallyRunJob()) { - return null; - } - - String jobIdToUpdate = null; - if (options.getUpdate()) { - jobIdToUpdate = getJobIdFromName(options.getJobName()); - newJob.setTransformNameMapping(options.getTransformNameMapping()); - newJob.setReplaceJobId(jobIdToUpdate); - } - Job jobResult; - try { - jobResult = dataflowClient - .projects() - .jobs() - .create(options.getProject(), newJob) - .execute(); - } catch (GoogleJsonResponseException e) { - String errorMessages = "Unexpected errors"; - if (e.getDetails() != null) { - if (Utf8.encodedLength(newJob.toString()) >= CREATE_JOB_REQUEST_LIMIT_BYTES) { - errorMessages = "The size of the serialized JSON representation of the pipeline " - + "exceeds the allowable limit. " - + "For more information, please check the FAQ link below:\n" - + "https://cloud.google.com/dataflow/faq"; - } else { - errorMessages = e.getDetails().getMessage(); - } - } - throw new RuntimeException("Failed to create a workflow job: " + errorMessages, e); - } catch (IOException e) { - throw new RuntimeException("Failed to create a workflow job", e); - } - - // Obtain all of the extractors from the PTransforms used in the pipeline so the - // DataflowPipelineJob has access to them. - AggregatorPipelineExtractor aggregatorExtractor = new AggregatorPipelineExtractor(pipeline); - Map, Collection>> aggregatorSteps = - aggregatorExtractor.getAggregatorSteps(); - - DataflowAggregatorTransforms aggregatorTransforms = - new DataflowAggregatorTransforms(aggregatorSteps, jobSpecification.getStepNames()); - - // Use a raw client for post-launch monitoring, as status calls may fail - // regularly and need not be retried automatically. - DataflowPipelineJob dataflowPipelineJob = - new DataflowPipelineJob(options.getProject(), jobResult.getId(), - Transport.newDataflowClient(options).build(), aggregatorTransforms); - - // If the service returned client request id, the SDK needs to compare it - // with the original id generated in the request, if they are not the same - // (i.e., the returned job is not created by this request), throw - // DataflowJobAlreadyExistsException or DataflowJobAlreadyUpdatedExcetpion - // depending on whether this is a reload or not. - if (jobResult.getClientRequestId() != null && !jobResult.getClientRequestId().isEmpty() - && !jobResult.getClientRequestId().equals(requestId)) { - // If updating a job. - if (options.getUpdate()) { - throw new DataflowJobAlreadyUpdatedException(dataflowPipelineJob, - String.format("The job named %s with id: %s has already been updated into job id: %s " - + "and cannot be updated again.", - newJob.getName(), jobIdToUpdate, jobResult.getId())); - } else { - throw new DataflowJobAlreadyExistsException(dataflowPipelineJob, - String.format("There is already an active job named %s with id: %s. If you want " - + "to submit a second job, try again by setting a different name using --jobName.", - newJob.getName(), jobResult.getId())); - } - } - - LOG.info("To access the Dataflow monitoring console, please navigate to {}", - MonitoringUtil.getJobMonitoringPageURL(options.getProject(), jobResult.getId())); - System.out.println("Submitted job: " + jobResult.getId()); - - LOG.info("To cancel the job using the 'gcloud' tool, run:\n> {}", - MonitoringUtil.getGcloudCancelCommand(options, jobResult.getId())); - - return dataflowPipelineJob; - } - - /** - * Returns the DataflowPipelineTranslator associated with this object. - */ - public DataflowPipelineTranslator getTranslator() { - return translator; - } - - /** - * Sets callbacks to invoke during execution see {@code DataflowPipelineRunnerHooks}. - */ - @Experimental - public void setHooks(DataflowPipelineRunnerHooks hooks) { - this.hooks = hooks; - } - - ///////////////////////////////////////////////////////////////////////////// - - /** Outputs a warning about PCollection views without deterministic key coders. */ - private void logWarningIfPCollectionViewHasNonDeterministicKeyCoder(Pipeline pipeline) { - // We need to wait till this point to determine the names of the transforms since only - // at this time do we know the hierarchy of the transforms otherwise we could - // have just recorded the full names during apply time. - if (!ptransformViewsWithNonDeterministicKeyCoders.isEmpty()) { - final SortedSet ptransformViewNamesWithNonDeterministicKeyCoders = new TreeSet<>(); - pipeline.traverseTopologically(new PipelineVisitor() { - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - } - - @Override - public void visitTransform(TransformTreeNode node) { - if (ptransformViewsWithNonDeterministicKeyCoders.contains(node.getTransform())) { - ptransformViewNamesWithNonDeterministicKeyCoders.add(node.getFullName()); - } - } - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - if (ptransformViewsWithNonDeterministicKeyCoders.contains(node.getTransform())) { - ptransformViewNamesWithNonDeterministicKeyCoders.add(node.getFullName()); - } - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - } - }); - - LOG.warn("Unable to use indexed implementation for View.AsMap and View.AsMultimap for {} " - + "because the key coder is not deterministic. Falling back to singleton implementation " - + "which may cause memory and/or performance problems. Future major versions of " - + "Dataflow will require deterministic key coders.", - ptransformViewNamesWithNonDeterministicKeyCoders); - } - } - - private void runJobFileHooks(Job newJob) { - try { - WritableByteChannel writer = - IOChannelUtils.create(options.getDataflowJobFile(), MimeTypes.TEXT); - PrintWriter printWriter = new PrintWriter(Channels.newOutputStream(writer)); - String workSpecJson = DataflowPipelineTranslator.jobToString(newJob); - printWriter.print(workSpecJson); - printWriter.flush(); - printWriter.close(); - LOG.info("Printed job specification to {}", options.getDataflowJobFile()); - } catch (IllegalStateException ex) { - String error = "Cannot translate workflow spec to JSON."; - if (hooks != null && hooks.failOnJobFileWriteFailure()) { - throw new RuntimeException(error, ex); - } else { - LOG.warn(error, ex); - } - } catch (IOException ex) { - String error = - String.format("Cannot create output file at {}", options.getDataflowJobFile()); - if (hooks != null && hooks.failOnJobFileWriteFailure()) { - throw new RuntimeException(error, ex); - } else { - LOG.warn(error, ex); - } - } - } - - /** - * Returns true if the passed in {@link PCollection} needs to be materialiazed using - * an indexed format. - */ - boolean doesPCollectionRequireIndexedFormat(PCollection pcol) { - return pcollectionsRequiringIndexedFormat.contains(pcol); - } - - /** - * Marks the passed in {@link PCollection} as requiring to be materialized using - * an indexed format. - */ - private void addPCollectionRequiringIndexedFormat(PCollection pcol) { - pcollectionsRequiringIndexedFormat.add(pcol); - } - - /** A set of {@link View}s with non-deterministic key coders. */ - Set> ptransformViewsWithNonDeterministicKeyCoders; - - /** - * Records that the {@link PTransform} requires a deterministic key coder. - */ - private void recordViewUsesNonDeterministicKeyCoder(PTransform ptransform) { - ptransformViewsWithNonDeterministicKeyCoders.add(ptransform); - } - - /** - * A {@link GroupByKey} transform for the {@link DataflowPipelineRunner} which sorts - * values using the secondary key {@code K2}. - * - *

              The {@link PCollection} created created by this {@link PTransform} will have values in - * the empty window. Care must be taken *afterwards* to either re-window - * (using {@link Window#into}) or only use {@link PTransform}s that do not depend on the - * values being within a window. - */ - static class GroupByKeyAndSortValuesOnly - extends PTransform>>, PCollection>>>> { - private GroupByKeyAndSortValuesOnly() { - } - - @Override - public PCollection>>> apply(PCollection>> input) { - PCollection>>> rval = - PCollection.>>>createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - IsBounded.BOUNDED); - - @SuppressWarnings({"unchecked", "rawtypes"}) - KvCoder> inputCoder = (KvCoder) input.getCoder(); - rval.setCoder( - KvCoder.of(inputCoder.getKeyCoder(), - IterableCoder.of(inputCoder.getValueCoder()))); - return rval; - } - } - - /** - * A {@link PTransform} that groups the values by a hash of the window's byte representation - * and sorts the values using the windows byte representation. - */ - private static class GroupByWindowHashAsKeyAndWindowAsSortKey extends - PTransform, PCollection>>>>> { - - /** - * A {@link DoFn} that for each element outputs a {@code KV} structure suitable for - * grouping by the hash of the window's byte representation and sorting the grouped values - * using the window's byte representation. - */ - @SystemDoFnInternal - private static class UseWindowHashAsKeyAndWindowAsSortKeyDoFn - extends DoFn>>> implements DoFn.RequiresWindowAccess { - - private final IsmRecordCoder ismCoderForHash; - private UseWindowHashAsKeyAndWindowAsSortKeyDoFn(IsmRecordCoder ismCoderForHash) { - this.ismCoderForHash = ismCoderForHash; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - @SuppressWarnings("unchecked") - W window = (W) c.window(); - c.output( - KV.of(ismCoderForHash.hash(ImmutableList.of(window)), - KV.of(window, - WindowedValue.of( - c.element(), - c.timestamp(), - c.window(), - c.pane())))); - } - } - - private final IsmRecordCoder ismCoderForHash; - private GroupByWindowHashAsKeyAndWindowAsSortKey(IsmRecordCoder ismCoderForHash) { - this.ismCoderForHash = ismCoderForHash; - } - - @Override - public PCollection>>>> apply(PCollection input) { - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - PCollection>>> rval = - input.apply(ParDo.of( - new UseWindowHashAsKeyAndWindowAsSortKeyDoFn(ismCoderForHash))); - rval.setCoder( - KvCoder.of( - VarIntCoder.of(), - KvCoder.of(windowCoder, - FullWindowedValueCoder.of(input.getCoder(), windowCoder)))); - return rval.apply(new GroupByKeyAndSortValuesOnly>()); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} for the - * Dataflow runner in batch mode. - * - *

              Creates a set of files in the {@link IsmFormat} sharded by the hash of the windows - * byte representation and with records having: - *

                - *
              • Key 1: Window
              • - *
              • Value: Windowed value
              • - *
              - */ - static class BatchViewAsSingleton - extends PTransform, PCollectionView> { - - /** - * A {@link DoFn} that outputs {@link IsmRecord}s. These records are structured as follows: - *
                - *
              • Key 1: Window - *
              • Value: Windowed value - *
              - */ - static class IsmRecordForSingularValuePerWindowDoFn - extends DoFn>>>, - IsmRecord>> { - - private final Coder windowCoder; - IsmRecordForSingularValuePerWindowDoFn(Coder windowCoder) { - this.windowCoder = windowCoder; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - Optional previousWindowStructuralValue = Optional.absent(); - T previousValue = null; - - Iterator>> iterator = c.element().getValue().iterator(); - while (iterator.hasNext()) { - KV> next = iterator.next(); - Object currentWindowStructuralValue = windowCoder.structuralValue(next.getKey()); - - // Verify that the user isn't trying to have more than one element per window as - // a singleton. - checkState(!previousWindowStructuralValue.isPresent() - || !previousWindowStructuralValue.get().equals(currentWindowStructuralValue), - "Multiple values [%s, %s] found for singleton within window [%s].", - previousValue, - next.getValue().getValue(), - next.getKey()); - - c.output( - IsmRecord.of( - ImmutableList.of(next.getKey()), next.getValue())); - - previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); - previousValue = next.getValue().getValue(); - } - } - } - - private final DataflowPipelineRunner runner; - private final View.AsSingleton transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchViewAsSingleton(DataflowPipelineRunner runner, View.AsSingleton transform) { - this.runner = runner; - this.transform = transform; - } - - @Override - public PCollectionView apply(PCollection input) { - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - - return BatchViewAsSingleton.applyForSingleton( - runner, - input, - new IsmRecordForSingularValuePerWindowDoFn(windowCoder), - transform.hasDefaultValue(), - transform.defaultValue(), - input.getCoder()); - } - - static PCollectionView - applyForSingleton( - DataflowPipelineRunner runner, - PCollection input, - DoFn>>>, - IsmRecord>> doFn, - boolean hasDefault, - FinalT defaultValue, - Coder defaultValueCoder) { - - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - - @SuppressWarnings({"rawtypes", "unchecked"}) - PCollectionView view = PCollectionViews.singletonView( - input.getPipeline(), - (WindowingStrategy) input.getWindowingStrategy(), - hasDefault, - defaultValue, - defaultValueCoder); - - IsmRecordCoder> ismCoder = - coderForSingleton(windowCoder, defaultValueCoder); - - PCollection>> reifiedPerWindowAndSorted = input - .apply(new GroupByWindowHashAsKeyAndWindowAsSortKey(ismCoder)) - .apply(ParDo.of(doFn)); - reifiedPerWindowAndSorted.setCoder(ismCoder); - - runner.addPCollectionRequiringIndexedFormat(reifiedPerWindowAndSorted); - return reifiedPerWindowAndSorted.apply( - CreatePCollectionView.>, ViewT>of(view)); - } - - @Override - protected String getKindString() { - return "BatchViewAsSingleton"; - } - - static IsmRecordCoder> coderForSingleton( - Coder windowCoder, Coder valueCoder) { - return IsmRecordCoder.of( - 1, // We hash using only the window - 0, // There are no metadata records - ImmutableList.>of(windowCoder), - FullWindowedValueCoder.of(valueCoder, windowCoder)); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsIterable View.AsIterable} for the - * Dataflow runner in batch mode. - * - *

              Creates a set of {@code Ism} files sharded by the hash of the windows byte representation - * and with records having: - *

                - *
              • Key 1: Window
              • - *
              • Key 2: Index offset within window
              • - *
              • Value: Windowed value
              • - *
              - */ - static class BatchViewAsIterable - extends PTransform, PCollectionView>> { - - private final DataflowPipelineRunner runner; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchViewAsIterable(DataflowPipelineRunner runner, View.AsIterable transform) { - this.runner = runner; - } - - @Override - public PCollectionView> apply(PCollection input) { - PCollectionView> view = PCollectionViews.iterableView( - input.getPipeline(), input.getWindowingStrategy(), input.getCoder()); - return BatchViewAsList.applyForIterableLike(runner, input, view); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsList View.AsList} for the - * Dataflow runner in batch mode. - * - *

              Creates a set of {@code Ism} files sharded by the hash of the window's byte representation - * and with records having: - *

                - *
              • Key 1: Window
              • - *
              • Key 2: Index offset within window
              • - *
              • Value: Windowed value
              • - *
              - */ - static class BatchViewAsList - extends PTransform, PCollectionView>> { - /** - * A {@link DoFn} which creates {@link IsmRecord}s assuming that each element is within the - * global window. Each {@link IsmRecord} has - *
                - *
              • Key 1: Global window
              • - *
              • Key 2: Index offset within window
              • - *
              • Value: Windowed value
              • - *
              - */ - @SystemDoFnInternal - static class ToIsmRecordForGlobalWindowDoFn - extends DoFn>> { - - long indexInBundle; - @Override - public void startBundle(Context c) throws Exception { - indexInBundle = 0; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(IsmRecord.of( - ImmutableList.of(GlobalWindow.INSTANCE, indexInBundle), - WindowedValue.of( - c.element(), - c.timestamp(), - GlobalWindow.INSTANCE, - c.pane()))); - indexInBundle += 1; - } - } - - /** - * A {@link DoFn} which creates {@link IsmRecord}s comparing successive elements windows - * to locate the window boundaries. The {@link IsmRecord} has: - *
                - *
              • Key 1: Window
              • - *
              • Key 2: Index offset within window
              • - *
              • Value: Windowed value
              • - *
              - */ - @SystemDoFnInternal - static class ToIsmRecordForNonGlobalWindowDoFn - extends DoFn>>>, - IsmRecord>> { - - private final Coder windowCoder; - ToIsmRecordForNonGlobalWindowDoFn(Coder windowCoder) { - this.windowCoder = windowCoder; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - long elementsInWindow = 0; - Optional previousWindowStructuralValue = Optional.absent(); - for (KV> value : c.element().getValue()) { - Object currentWindowStructuralValue = windowCoder.structuralValue(value.getKey()); - // Compare to see if this is a new window so we can reset the index counter i - if (previousWindowStructuralValue.isPresent() - && !previousWindowStructuralValue.get().equals(currentWindowStructuralValue)) { - // Reset i since we have a new window. - elementsInWindow = 0; - } - c.output(IsmRecord.of( - ImmutableList.of(value.getKey(), elementsInWindow), - value.getValue())); - previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); - elementsInWindow += 1; - } - } - } - - private final DataflowPipelineRunner runner; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchViewAsList(DataflowPipelineRunner runner, View.AsList transform) { - this.runner = runner; - } - - @Override - public PCollectionView> apply(PCollection input) { - PCollectionView> view = PCollectionViews.listView( - input.getPipeline(), input.getWindowingStrategy(), input.getCoder()); - return applyForIterableLike(runner, input, view); - } - - static PCollectionView applyForIterableLike( - DataflowPipelineRunner runner, - PCollection input, - PCollectionView view) { - - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - - IsmRecordCoder> ismCoder = coderForListLike(windowCoder, input.getCoder()); - - // If we are working in the global window, we do not need to do a GBK using the window - // as the key since all the elements of the input PCollection are already such. - // We just reify the windowed value while converting them to IsmRecords and generating - // an index based upon where we are within the bundle. Each bundle - // maps to one file exactly. - if (input.getWindowingStrategy().getWindowFn() instanceof GlobalWindows) { - PCollection>> reifiedPerWindowAndSorted = - input.apply(ParDo.of(new ToIsmRecordForGlobalWindowDoFn())); - reifiedPerWindowAndSorted.setCoder(ismCoder); - - runner.addPCollectionRequiringIndexedFormat(reifiedPerWindowAndSorted); - return reifiedPerWindowAndSorted.apply( - CreatePCollectionView.>, ViewT>of(view)); - } - - PCollection>> reifiedPerWindowAndSorted = input - .apply(new GroupByWindowHashAsKeyAndWindowAsSortKey(ismCoder)) - .apply(ParDo.of(new ToIsmRecordForNonGlobalWindowDoFn(windowCoder))); - reifiedPerWindowAndSorted.setCoder(ismCoder); - - runner.addPCollectionRequiringIndexedFormat(reifiedPerWindowAndSorted); - return reifiedPerWindowAndSorted.apply( - CreatePCollectionView.>, ViewT>of(view)); - } - - @Override - protected String getKindString() { - return "BatchViewAsList"; - } - - static IsmRecordCoder> coderForListLike( - Coder windowCoder, Coder valueCoder) { - // TODO: swap to use a variable length long coder which has values which compare - // the same as their byte representation compare lexicographically within the key coder - return IsmRecordCoder.of( - 1, // We hash using only the window - 0, // There are no metadata records - ImmutableList.of(windowCoder, BigEndianLongCoder.of()), - FullWindowedValueCoder.of(valueCoder, windowCoder)); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsMap View.AsMap} for the - * Dataflow runner in batch mode. - * - *

              Creates a set of {@code Ism} files sharded by the hash of the key's byte - * representation. Each record is structured as follows: - *

                - *
              • Key 1: User key K
              • - *
              • Key 2: Window
              • - *
              • Key 3: 0L (constant)
              • - *
              • Value: Windowed value
              • - *
              - * - *

              Alongside the data records, there are the following metadata records: - *

                - *
              • Key 1: Metadata Key
              • - *
              • Key 2: Window
              • - *
              • Key 3: Index [0, size of map]
              • - *
              • Value: variable length long byte representation of size of map if index is 0, - * otherwise the byte representation of a key
              • - *
              - * The {@code [META, Window, 0]} record stores the number of unique keys per window, while - * {@code [META, Window, i]} for {@code i} in {@code [1, size of map]} stores a the users key. - * This allows for one to access the size of the map by looking at {@code [META, Window, 0]} - * and iterate over all the keys by accessing {@code [META, Window, i]} for {@code i} in - * {@code [1, size of map]}. - * - *

              Note that in the case of a non-deterministic key coder, we fallback to using - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} printing - * a warning to users to specify a deterministic key coder. - */ - static class BatchViewAsMap - extends PTransform>, PCollectionView>> { - - /** - * A {@link DoFn} which groups elements by window boundaries. For each group, - * the group of elements is transformed into a {@link TransformedMap}. - * The transformed {@code Map} is backed by a {@code Map>} - * and contains a function {@code WindowedValue -> V}. - * - *

              Outputs {@link IsmRecord}s having: - *

                - *
              • Key 1: Window
              • - *
              • Value: Transformed map containing a transform that removes the encapsulation - * of the window around each value, - * {@code Map> -> Map}.
              • - *
              - */ - static class ToMapDoFn - extends DoFn>>>>, - IsmRecord, - V>>>> { - - private final Coder windowCoder; - ToMapDoFn(Coder windowCoder) { - this.windowCoder = windowCoder; - } - - @Override - public void processElement(ProcessContext c) - throws Exception { - Optional previousWindowStructuralValue = Optional.absent(); - Optional previousWindow = Optional.absent(); - Map> map = new HashMap<>(); - for (KV>> kv : c.element().getValue()) { - Object currentWindowStructuralValue = windowCoder.structuralValue(kv.getKey()); - if (previousWindowStructuralValue.isPresent() - && !previousWindowStructuralValue.get().equals(currentWindowStructuralValue)) { - // Construct the transformed map containing all the elements since we - // are at a window boundary. - c.output(IsmRecord.of( - ImmutableList.of(previousWindow.get()), - valueInEmptyWindows(new TransformedMap<>(WindowedValueToValue.of(), map)))); - map = new HashMap<>(); - } - - // Verify that the user isn't trying to insert the same key multiple times. - checkState(!map.containsKey(kv.getValue().getValue().getKey()), - "Multiple values [%s, %s] found for single key [%s] within window [%s].", - map.get(kv.getValue().getValue().getKey()), - kv.getValue().getValue().getValue(), - kv.getKey()); - map.put(kv.getValue().getValue().getKey(), - kv.getValue().withValue(kv.getValue().getValue().getValue())); - previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); - previousWindow = Optional.of(kv.getKey()); - } - - // The last value for this hash is guaranteed to be at a window boundary - // so we output a transformed map containing all the elements since the last - // window boundary. - c.output(IsmRecord.of( - ImmutableList.of(previousWindow.get()), - valueInEmptyWindows(new TransformedMap<>(WindowedValueToValue.of(), map)))); - } - } - - private final DataflowPipelineRunner runner; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchViewAsMap(DataflowPipelineRunner runner, View.AsMap transform) { - this.runner = runner; - } - - @Override - public PCollectionView> apply(PCollection> input) { - return this.applyInternal(input); - } - - private PCollectionView> - applyInternal(PCollection> input) { - - @SuppressWarnings({"rawtypes", "unchecked"}) - KvCoder inputCoder = (KvCoder) input.getCoder(); - try { - PCollectionView> view = PCollectionViews.mapView( - input.getPipeline(), input.getWindowingStrategy(), inputCoder); - return BatchViewAsMultimap.applyForMapLike(runner, input, view, true /* unique keys */); - } catch (NonDeterministicException e) { - runner.recordViewUsesNonDeterministicKeyCoder(this); - - // Since the key coder is not deterministic, we convert the map into a singleton - // and return a singleton view equivalent. - return applyForSingletonFallback(input); - } - } - - @Override - protected String getKindString() { - return "BatchViewAsMap"; - } - - /** Transforms the input {@link PCollection} into a singleton {@link Map} per window. */ - private PCollectionView> - applyForSingletonFallback(PCollection> input) { - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - - @SuppressWarnings({"rawtypes", "unchecked"}) - KvCoder inputCoder = (KvCoder) input.getCoder(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder, V>> transformCoder = - (Coder) SerializableCoder.of(WindowedValueToValue.class); - - Coder, V>> finalValueCoder = - TransformedMapCoder.of( - transformCoder, - MapCoder.of( - inputCoder.getKeyCoder(), - FullWindowedValueCoder.of(inputCoder.getValueCoder(), windowCoder))); - - TransformedMap, V> defaultValue = new TransformedMap<>( - WindowedValueToValue.of(), - ImmutableMap.>of()); - - return BatchViewAsSingleton., - TransformedMap, V>, - Map, - W> applyForSingleton( - runner, - input, - new ToMapDoFn(windowCoder), - true, - defaultValue, - finalValueCoder); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsMultimap View.AsMultimap} for the - * Dataflow runner in batch mode. - * - *

              Creates a set of {@code Ism} files sharded by the hash of the key's byte - * representation. Each record is structured as follows: - *

                - *
              • Key 1: User key K
              • - *
              • Key 2: Window
              • - *
              • Key 3: Index offset for a given key and window.
              • - *
              • Value: Windowed value
              • - *
              - * - *

              Alongside the data records, there are the following metadata records: - *

                - *
              • Key 1: Metadata Key
              • - *
              • Key 2: Window
              • - *
              • Key 3: Index [0, size of map]
              • - *
              • Value: variable length long byte representation of size of map if index is 0, - * otherwise the byte representation of a key
              • - *
              - * The {@code [META, Window, 0]} record stores the number of unique keys per window, while - * {@code [META, Window, i]} for {@code i} in {@code [1, size of map]} stores a the users key. - * This allows for one to access the size of the map by looking at {@code [META, Window, 0]} - * and iterate over all the keys by accessing {@code [META, Window, i]} for {@code i} in - * {@code [1, size of map]}. - * - *

              Note that in the case of a non-deterministic key coder, we fallback to using - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} printing - * a warning to users to specify a deterministic key coder. - */ - static class BatchViewAsMultimap - extends PTransform>, PCollectionView>>> { - /** - * A {@link PTransform} that groups elements by the hash of window's byte representation - * if the input {@link PCollection} is not within the global window. Otherwise by the hash - * of the window and key's byte representation. This {@link PTransform} also sorts - * the values by the combination of the window and key's byte representations. - */ - private static class GroupByKeyHashAndSortByKeyAndWindow - extends PTransform>, - PCollection, WindowedValue>>>>> { - - @SystemDoFnInternal - private static class GroupByKeyHashAndSortByKeyAndWindowDoFn - extends DoFn, KV, WindowedValue>>> - implements DoFn.RequiresWindowAccess { - - private final IsmRecordCoder coder; - private GroupByKeyHashAndSortByKeyAndWindowDoFn(IsmRecordCoder coder) { - this.coder = coder; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - @SuppressWarnings("unchecked") - W window = (W) c.window(); - - c.output( - KV.of(coder.hash(ImmutableList.of(c.element().getKey())), - KV.of(KV.of(c.element().getKey(), window), - WindowedValue.of( - c.element().getValue(), - c.timestamp(), - (BoundedWindow) window, - c.pane())))); - } - } - - private final IsmRecordCoder coder; - public GroupByKeyHashAndSortByKeyAndWindow(IsmRecordCoder coder) { - this.coder = coder; - } - - @Override - public PCollection, WindowedValue>>>> - apply(PCollection> input) { - - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - @SuppressWarnings("unchecked") - KvCoder inputCoder = (KvCoder) input.getCoder(); - - PCollection, WindowedValue>>> keyedByHash; - keyedByHash = input.apply( - ParDo.of(new GroupByKeyHashAndSortByKeyAndWindowDoFn(coder))); - keyedByHash.setCoder( - KvCoder.of( - VarIntCoder.of(), - KvCoder.of(KvCoder.of(inputCoder.getKeyCoder(), windowCoder), - FullWindowedValueCoder.of(inputCoder.getValueCoder(), windowCoder)))); - - return keyedByHash.apply( - new GroupByKeyAndSortValuesOnly, WindowedValue>()); - } - } - - /** - * A {@link DoFn} which creates {@link IsmRecord}s comparing successive elements windows - * and keys to locate window and key boundaries. The main output {@link IsmRecord}s have: - *

                - *
              • Key 1: Window
              • - *
              • Key 2: User key K
              • - *
              • Key 3: Index offset for a given key and window.
              • - *
              • Value: Windowed value
              • - *
              - * - *

              Additionally, we output all the unique keys per window seen to {@code outputForEntrySet} - * and the unique key count per window to {@code outputForSize}. - * - *

              Finally, if this DoFn has been requested to perform unique key checking, it will - * throw an {@link IllegalStateException} if more than one key per window is found. - */ - static class ToIsmRecordForMapLikeDoFn - extends DoFn, WindowedValue>>>, - IsmRecord>> { - - private final TupleTag>> outputForSize; - private final TupleTag>> outputForEntrySet; - private final Coder windowCoder; - private final Coder keyCoder; - private final IsmRecordCoder> ismCoder; - private final boolean uniqueKeysExpected; - ToIsmRecordForMapLikeDoFn( - TupleTag>> outputForSize, - TupleTag>> outputForEntrySet, - Coder windowCoder, - Coder keyCoder, - IsmRecordCoder> ismCoder, - boolean uniqueKeysExpected) { - this.outputForSize = outputForSize; - this.outputForEntrySet = outputForEntrySet; - this.windowCoder = windowCoder; - this.keyCoder = keyCoder; - this.ismCoder = ismCoder; - this.uniqueKeysExpected = uniqueKeysExpected; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - long currentKeyIndex = 0; - // We use one based indexing while counting - long currentUniqueKeyCounter = 1; - Iterator, WindowedValue>> iterator = c.element().getValue().iterator(); - - KV, WindowedValue> currentValue = iterator.next(); - Object currentKeyStructuralValue = - keyCoder.structuralValue(currentValue.getKey().getKey()); - Object currentWindowStructuralValue = - windowCoder.structuralValue(currentValue.getKey().getValue()); - - while (iterator.hasNext()) { - KV, WindowedValue> nextValue = iterator.next(); - Object nextKeyStructuralValue = - keyCoder.structuralValue(nextValue.getKey().getKey()); - Object nextWindowStructuralValue = - windowCoder.structuralValue(nextValue.getKey().getValue()); - - outputDataRecord(c, currentValue, currentKeyIndex); - - final long nextKeyIndex; - final long nextUniqueKeyCounter; - - // Check to see if its a new window - if (!currentWindowStructuralValue.equals(nextWindowStructuralValue)) { - // The next value is a new window, so we output for size the number of unique keys - // seen and the last key of the window. We also reset the next key index the unique - // key counter. - outputMetadataRecordForSize(c, currentValue, currentUniqueKeyCounter); - outputMetadataRecordForEntrySet(c, currentValue); - - nextKeyIndex = 0; - nextUniqueKeyCounter = 1; - } else if (!currentKeyStructuralValue.equals(nextKeyStructuralValue)){ - // It is a new key within the same window so output the key for the entry set, - // reset the key index and increase the count of unique keys seen within this window. - outputMetadataRecordForEntrySet(c, currentValue); - - nextKeyIndex = 0; - nextUniqueKeyCounter = currentUniqueKeyCounter + 1; - } else if (!uniqueKeysExpected) { - // It is not a new key so we don't have to output the number of elements in this - // window or increase the unique key counter. All we do is increase the key index. - - nextKeyIndex = currentKeyIndex + 1; - nextUniqueKeyCounter = currentUniqueKeyCounter; - } else { - throw new IllegalStateException(String.format( - "Unique keys are expected but found key %s with values %s and %s in window %s.", - currentValue.getKey().getKey(), - currentValue.getValue().getValue(), - nextValue.getValue().getValue(), - currentValue.getKey().getValue())); - } - - currentValue = nextValue; - currentWindowStructuralValue = nextWindowStructuralValue; - currentKeyStructuralValue = nextKeyStructuralValue; - currentKeyIndex = nextKeyIndex; - currentUniqueKeyCounter = nextUniqueKeyCounter; - } - - outputDataRecord(c, currentValue, currentKeyIndex); - outputMetadataRecordForSize(c, currentValue, currentUniqueKeyCounter); - // The last value for this hash is guaranteed to be at a window boundary - // so we output a record with the number of unique keys seen. - outputMetadataRecordForEntrySet(c, currentValue); - } - - /** This outputs the data record. */ - private void outputDataRecord( - ProcessContext c, KV, WindowedValue> value, long keyIndex) { - IsmRecord> ismRecord = IsmRecord.of( - ImmutableList.of( - value.getKey().getKey(), - value.getKey().getValue(), - keyIndex), - value.getValue()); - c.output(ismRecord); - } - - /** - * This outputs records which will be used to compute the number of keys for a given window. - */ - private void outputMetadataRecordForSize( - ProcessContext c, KV, WindowedValue> value, long uniqueKeyCount) { - c.sideOutput(outputForSize, - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), - value.getKey().getValue())), - KV.of(value.getKey().getValue(), uniqueKeyCount))); - } - - /** This outputs records which will be used to construct the entry set. */ - private void outputMetadataRecordForEntrySet( - ProcessContext c, KV, WindowedValue> value) { - c.sideOutput(outputForEntrySet, - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), - value.getKey().getValue())), - KV.of(value.getKey().getValue(), value.getKey().getKey()))); - } - } - - /** - * A {@link DoFn} which outputs a metadata {@link IsmRecord} per window of: - *

                - *
              • Key 1: META key
              • - *
              • Key 2: window
              • - *
              • Key 3: 0L (constant)
              • - *
              • Value: sum of values for window
              • - *
              - * - *

              This {@link DoFn} is meant to be used to compute the number of unique keys - * per window for map and multimap side inputs. - */ - static class ToIsmMetadataRecordForSizeDoFn - extends DoFn>>, IsmRecord>> { - private final Coder windowCoder; - ToIsmMetadataRecordForSizeDoFn(Coder windowCoder) { - this.windowCoder = windowCoder; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - Iterator> iterator = c.element().getValue().iterator(); - KV currentValue = iterator.next(); - Object currentWindowStructuralValue = windowCoder.structuralValue(currentValue.getKey()); - long size = 0; - while (iterator.hasNext()) { - KV nextValue = iterator.next(); - Object nextWindowStructuralValue = windowCoder.structuralValue(nextValue.getKey()); - - size += currentValue.getValue(); - if (!currentWindowStructuralValue.equals(nextWindowStructuralValue)) { - c.output(IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), 0L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), size))); - size = 0; - } - - currentValue = nextValue; - currentWindowStructuralValue = nextWindowStructuralValue; - } - - size += currentValue.getValue(); - // Output the final value since it is guaranteed to be on a window boundary. - c.output(IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), 0L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), size))); - } - } - - /** - * A {@link DoFn} which outputs a metadata {@link IsmRecord} per window and key pair of: - *

                - *
              • Key 1: META key
              • - *
              • Key 2: window
              • - *
              • Key 3: index offset (1-based index)
              • - *
              • Value: key
              • - *
              - * - *

              This {@link DoFn} is meant to be used to output index to key records - * per window for map and multimap side inputs. - */ - static class ToIsmMetadataRecordForKeyDoFn - extends DoFn>>, IsmRecord>> { - - private final Coder keyCoder; - private final Coder windowCoder; - ToIsmMetadataRecordForKeyDoFn(Coder keyCoder, Coder windowCoder) { - this.keyCoder = keyCoder; - this.windowCoder = windowCoder; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - Iterator> iterator = c.element().getValue().iterator(); - KV currentValue = iterator.next(); - Object currentWindowStructuralValue = windowCoder.structuralValue(currentValue.getKey()); - long elementsInWindow = 1; - while (iterator.hasNext()) { - KV nextValue = iterator.next(); - Object nextWindowStructuralValue = windowCoder.structuralValue(nextValue.getKey()); - - c.output(IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), elementsInWindow), - CoderUtils.encodeToByteArray(keyCoder, currentValue.getValue()))); - elementsInWindow += 1; - - if (!currentWindowStructuralValue.equals(nextWindowStructuralValue)) { - elementsInWindow = 1; - } - - currentValue = nextValue; - currentWindowStructuralValue = nextWindowStructuralValue; - } - - // Output the final value since it is guaranteed to be on a window boundary. - c.output(IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), currentValue.getKey(), elementsInWindow), - CoderUtils.encodeToByteArray(keyCoder, currentValue.getValue()))); - } - } - - /** - * A {@link DoFn} which partitions sets of elements by window boundaries. Within each - * partition, the set of elements is transformed into a {@link TransformedMap}. - * The transformed {@code Map>} is backed by a - * {@code Map>>} and contains a function - * {@code Iterable> -> Iterable}. - * - *

              Outputs {@link IsmRecord}s having: - *

                - *
              • Key 1: Window
              • - *
              • Value: Transformed map containing a transform that removes the encapsulation - * of the window around each value, - * {@code Map>> -> Map>}.
              • - *
              - */ - static class ToMultimapDoFn - extends DoFn>>>>, - IsmRecord>, - Iterable>>>> { - - private final Coder windowCoder; - ToMultimapDoFn(Coder windowCoder) { - this.windowCoder = windowCoder; - } - - @Override - public void processElement(ProcessContext c) - throws Exception { - Optional previousWindowStructuralValue = Optional.absent(); - Optional previousWindow = Optional.absent(); - Multimap> multimap = HashMultimap.create(); - for (KV>> kv : c.element().getValue()) { - Object currentWindowStructuralValue = windowCoder.structuralValue(kv.getKey()); - if (previousWindowStructuralValue.isPresent() - && !previousWindowStructuralValue.get().equals(currentWindowStructuralValue)) { - // Construct the transformed map containing all the elements since we - // are at a window boundary. - @SuppressWarnings({"unchecked", "rawtypes"}) - Map>> resultMap = (Map) multimap.asMap(); - c.output(IsmRecord.>, - Iterable>>>of( - ImmutableList.of(previousWindow.get()), - valueInEmptyWindows( - new TransformedMap<>( - IterableWithWindowedValuesToIterable.of(), resultMap)))); - multimap = HashMultimap.create(); - } - - multimap.put(kv.getValue().getValue().getKey(), - kv.getValue().withValue(kv.getValue().getValue().getValue())); - previousWindowStructuralValue = Optional.of(currentWindowStructuralValue); - previousWindow = Optional.of(kv.getKey()); - } - - // The last value for this hash is guaranteed to be at a window boundary - // so we output a transformed map containing all the elements since the last - // window boundary. - @SuppressWarnings({"unchecked", "rawtypes"}) - Map>> resultMap = (Map) multimap.asMap(); - c.output(IsmRecord.>, - Iterable>>>of( - ImmutableList.of(previousWindow.get()), - valueInEmptyWindows( - new TransformedMap<>(IterableWithWindowedValuesToIterable.of(), resultMap)))); - } - } - - private final DataflowPipelineRunner runner; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchViewAsMultimap(DataflowPipelineRunner runner, View.AsMultimap transform) { - this.runner = runner; - } - - @Override - public PCollectionView>> apply(PCollection> input) { - return this.applyInternal(input); - } - - private PCollectionView>> - applyInternal(PCollection> input) { - @SuppressWarnings({"rawtypes", "unchecked"}) - KvCoder inputCoder = (KvCoder) input.getCoder(); - try { - PCollectionView>> view = PCollectionViews.multimapView( - input.getPipeline(), input.getWindowingStrategy(), inputCoder); - - return applyForMapLike(runner, input, view, false /* unique keys not expected */); - } catch (NonDeterministicException e) { - runner.recordViewUsesNonDeterministicKeyCoder(this); - - // Since the key coder is not deterministic, we convert the map into a singleton - // and return a singleton view equivalent. - return applyForSingletonFallback(input); - } - } - - /** Transforms the input {@link PCollection} into a singleton {@link Map} per window. */ - private PCollectionView>> - applyForSingletonFallback(PCollection> input) { - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - - @SuppressWarnings({"rawtypes", "unchecked"}) - KvCoder inputCoder = (KvCoder) input.getCoder(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder>, Iterable>> transformCoder = - (Coder) SerializableCoder.of(IterableWithWindowedValuesToIterable.class); - - Coder>, Iterable>> finalValueCoder = - TransformedMapCoder.of( - transformCoder, - MapCoder.of( - inputCoder.getKeyCoder(), - IterableCoder.of( - FullWindowedValueCoder.of(inputCoder.getValueCoder(), windowCoder)))); - - TransformedMap>, Iterable> defaultValue = - new TransformedMap<>( - IterableWithWindowedValuesToIterable.of(), - ImmutableMap.>>of()); - - return BatchViewAsSingleton., - TransformedMap>, Iterable>, - Map>, - W> applyForSingleton( - runner, - input, - new ToMultimapDoFn(windowCoder), - true, - defaultValue, - finalValueCoder); - } - - private static PCollectionView applyForMapLike( - DataflowPipelineRunner runner, - PCollection> input, - PCollectionView view, - boolean uniqueKeysExpected) throws NonDeterministicException { - - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) - input.getWindowingStrategy().getWindowFn().windowCoder(); - - @SuppressWarnings({"rawtypes", "unchecked"}) - KvCoder inputCoder = (KvCoder) input.getCoder(); - - // If our key coder is deterministic, we can use the key portion of each KV - // part of a composite key containing the window , key and index. - inputCoder.getKeyCoder().verifyDeterministic(); - - IsmRecordCoder> ismCoder = - coderForMapLike(windowCoder, inputCoder.getKeyCoder(), inputCoder.getValueCoder()); - - // Create the various output tags representing the main output containing the data stream - // and the side outputs containing the metadata about the size and entry set. - TupleTag>> mainOutputTag = new TupleTag<>(); - TupleTag>> outputForSizeTag = new TupleTag<>(); - TupleTag>> outputForEntrySetTag = new TupleTag<>(); - - // Process all the elements grouped by key hash, and sorted by key and then window - // outputting to all the outputs defined above. - PCollectionTuple outputTuple = input - .apply("GBKaSVForData", new GroupByKeyHashAndSortByKeyAndWindow(ismCoder)) - .apply(ParDo.of(new ToIsmRecordForMapLikeDoFn( - outputForSizeTag, outputForEntrySetTag, - windowCoder, inputCoder.getKeyCoder(), ismCoder, uniqueKeysExpected)) - .withOutputTags(mainOutputTag, - TupleTagList.of( - ImmutableList.>of(outputForSizeTag, - outputForEntrySetTag)))); - - // Set the coder on the main data output. - PCollection>> perHashWithReifiedWindows = - outputTuple.get(mainOutputTag); - perHashWithReifiedWindows.setCoder(ismCoder); - - // Set the coder on the metadata output for size and process the entries - // producing a [META, Window, 0L] record per window storing the number of unique keys - // for each window. - PCollection>> outputForSize = outputTuple.get(outputForSizeTag); - outputForSize.setCoder( - KvCoder.of(VarIntCoder.of(), - KvCoder.of(windowCoder, VarLongCoder.of()))); - PCollection>> windowMapSizeMetadata = outputForSize - .apply("GBKaSVForSize", new GroupByKeyAndSortValuesOnly()) - .apply(ParDo.of(new ToIsmMetadataRecordForSizeDoFn(windowCoder))); - windowMapSizeMetadata.setCoder(ismCoder); - - // Set the coder on the metadata output destined to build the entry set and process the - // entries producing a [META, Window, Index] record per window key pair storing the key. - PCollection>> outputForEntrySet = - outputTuple.get(outputForEntrySetTag); - outputForEntrySet.setCoder( - KvCoder.of(VarIntCoder.of(), - KvCoder.of(windowCoder, inputCoder.getKeyCoder()))); - PCollection>> windowMapKeysMetadata = outputForEntrySet - .apply("GBKaSVForKeys", new GroupByKeyAndSortValuesOnly()) - .apply(ParDo.of( - new ToIsmMetadataRecordForKeyDoFn(inputCoder.getKeyCoder(), windowCoder))); - windowMapKeysMetadata.setCoder(ismCoder); - - // Set that all these outputs should be materialized using an indexed format. - runner.addPCollectionRequiringIndexedFormat(perHashWithReifiedWindows); - runner.addPCollectionRequiringIndexedFormat(windowMapSizeMetadata); - runner.addPCollectionRequiringIndexedFormat(windowMapKeysMetadata); - - PCollectionList>> outputs = - PCollectionList.of(ImmutableList.of( - perHashWithReifiedWindows, windowMapSizeMetadata, windowMapKeysMetadata)); - - return Pipeline.applyTransform(outputs, - Flatten.>>pCollections()) - .apply(CreatePCollectionView.>, - ViewT>of(view)); - } - - @Override - protected String getKindString() { - return "BatchViewAsMultimap"; - } - - static IsmRecordCoder> coderForMapLike( - Coder windowCoder, Coder keyCoder, Coder valueCoder) { - // TODO: swap to use a variable length long coder which has values which compare - // the same as their byte representation compare lexicographically within the key coder - return IsmRecordCoder.of( - 1, // We use only the key for hashing when producing value records - 2, // Since the key is not present, we add the window to the hash when - // producing metadata records - ImmutableList.of( - MetadataKeyCoder.of(keyCoder), - windowCoder, - BigEndianLongCoder.of()), - FullWindowedValueCoder.of(valueCoder, windowCoder)); - } - } - - /** - * A {@code Map} backed by a {@code Map} and a function that transforms - * {@code V1 -> V2}. - */ - static class TransformedMap - extends ForwardingMap { - private final Function transform; - private final Map originalMap; - private final Map transformedMap; - - private TransformedMap(Function transform, Map originalMap) { - this.transform = transform; - this.originalMap = Collections.unmodifiableMap(originalMap); - this.transformedMap = Maps.transformValues(originalMap, transform); - } - - @Override - protected Map delegate() { - return transformedMap; - } - } - - /** - * A {@link Coder} for {@link TransformedMap}s. - */ - static class TransformedMapCoder - extends StandardCoder> { - private final Coder> transformCoder; - private final Coder> originalMapCoder; - - private TransformedMapCoder( - Coder> transformCoder, Coder> originalMapCoder) { - this.transformCoder = transformCoder; - this.originalMapCoder = originalMapCoder; - } - - public static TransformedMapCoder of( - Coder> transformCoder, Coder> originalMapCoder) { - return new TransformedMapCoder<>(transformCoder, originalMapCoder); - } - - @JsonCreator - public static TransformedMapCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 2, - "Expecting 2 components, got " + components.size()); - @SuppressWarnings("unchecked") - Coder> transformCoder = (Coder>) components.get(0); - @SuppressWarnings("unchecked") - Coder> originalMapCoder = (Coder>) components.get(1); - return of(transformCoder, originalMapCoder); - } - - @Override - public void encode(TransformedMap value, OutputStream outStream, - Coder.Context context) throws CoderException, IOException { - transformCoder.encode(value.transform, outStream, context.nested()); - originalMapCoder.encode(value.originalMap, outStream, context.nested()); - } - - @Override - public TransformedMap decode( - InputStream inStream, Coder.Context context) throws CoderException, IOException { - return new TransformedMap<>( - transformCoder.decode(inStream, context.nested()), - originalMapCoder.decode(inStream, context.nested())); - } - - @Override - public List> getCoderArguments() { - return Arrays.asList(transformCoder, originalMapCoder); - } - - @Override - public void verifyDeterministic() - throws com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException { - verifyDeterministic("Expected transform coder to be deterministic.", transformCoder); - verifyDeterministic("Expected map coder to be deterministic.", originalMapCoder); - } - } - - /** - * A {@link Function} which converts {@code WindowedValue} to {@code V}. - */ - private static class WindowedValueToValue implements - Function, V>, Serializable { - private static final WindowedValueToValue INSTANCE = new WindowedValueToValue<>(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static WindowedValueToValue of() { - return (WindowedValueToValue) INSTANCE; - } - - @Override - public V apply(WindowedValue input) { - return input.getValue(); - } - } - - /** - * A {@link Function} which converts {@code Iterable>} to {@code Iterable}. - */ - private static class IterableWithWindowedValuesToIterable implements - Function>, Iterable>, Serializable { - private static final IterableWithWindowedValuesToIterable INSTANCE = - new IterableWithWindowedValuesToIterable<>(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static IterableWithWindowedValuesToIterable of() { - return (IterableWithWindowedValuesToIterable) INSTANCE; - } - - @Override - public Iterable apply(Iterable> input) { - return Iterables.transform(input, WindowedValueToValue.of()); - } - } - - /** - * Specialized implementation which overrides - * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} to provide Google - * Cloud Dataflow specific path validation of {@link FileBasedSink}s. - */ - private static class BatchWrite extends PTransform, PDone> { - private final DataflowPipelineRunner runner; - private final Write.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchWrite(DataflowPipelineRunner runner, Write.Bound transform) { - this.runner = runner; - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - if (transform.getSink() instanceof FileBasedSink) { - FileBasedSink sink = (FileBasedSink) transform.getSink(); - if (sink.getBaseOutputFilenameProvider().isAccessible()) { - PathValidator validator = runner.options.getPathValidator(); - validator.validateOutputFilePrefixSupported( - sink.getBaseOutputFilenameProvider().get()); - } - } - return transform.apply(input); - } - } - - /** - * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way - * to provide the native definition of the BigQuery sink. - */ - private static class BatchBigQueryIONativeRead extends PTransform> { - private final BigQueryIO.Read.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchBigQueryIONativeRead( - DataflowPipelineRunner runner, BigQueryIO.Read.Bound transform) { - this.transform = transform; - } - - @Override - public PCollection apply(PInput input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - IsBounded.BOUNDED) - // Force the output's Coder to be what the read is using, and - // unchangeable later, to ensure that we read the input in the - // format specified by the Read transform. - .setCoder(TableRowJsonCoder.of()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - transform.populateDisplayData(builder); - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - BatchBigQueryIONativeRead.class, new BatchBigQueryIONativeReadTranslator()); - } - } - - /** - * Implements BigQueryIO Read translation for the Dataflow backend. - */ - public static class BatchBigQueryIONativeReadTranslator - implements DataflowPipelineTranslator.TransformTranslator { - - @Override - public void translate( - BatchBigQueryIONativeRead transform, - DataflowPipelineTranslator.TranslationContext context) { - translateWriteHelper(transform, transform.transform, context); - } - - private void translateWriteHelper( - BatchBigQueryIONativeRead transform, - BigQueryIO.Read.Bound originalTransform, - TranslationContext context) { - // Actual translation. - context.addStep(transform, "ParallelRead"); - context.addInput(PropertyNames.FORMAT, "bigquery"); - context.addInput(PropertyNames.BIGQUERY_EXPORT_FORMAT, "FORMAT_AVRO"); - - if (originalTransform.getQuery() != null) { - context.addInput(PropertyNames.BIGQUERY_QUERY, originalTransform.getQuery()); - context.addInput( - PropertyNames.BIGQUERY_FLATTEN_RESULTS, originalTransform.getFlattenResults()); - context.addInput( - PropertyNames.BIGQUERY_USE_LEGACY_SQL, originalTransform.getUseLegacySql()); - } else { - TableReference table = originalTransform.getTable(); - if (table.getProjectId() == null) { - // If user does not specify a project we assume the table to be located in the project - // that owns the Dataflow job. - String projectIdFromOptions = context.getPipelineOptions().getProject(); - LOG.warn( - "No project specified for BigQuery table \"{}.{}\". Assuming it is in \"{}\". If the" - + " table is in a different project please specify it as a part of the BigQuery table" - + " definition.", - table.getDatasetId(), - table.getTableId(), - projectIdFromOptions); - table.setProjectId(projectIdFromOptions); - } - - context.addInput(PropertyNames.BIGQUERY_TABLE, table.getTableId()); - context.addInput(PropertyNames.BIGQUERY_DATASET, table.getDatasetId()); - if (table.getProjectId() != null) { - context.addInput(PropertyNames.BIGQUERY_PROJECT, table.getProjectId()); - } - } - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - } - - private static class BatchBigQueryIOWrite extends PTransform, PDone> { - private final BigQueryIO.Write.Bound transform; - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public BatchBigQueryIOWrite(DataflowPipelineRunner runner, BigQueryIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - if (transform.getTable() == null) { - // BigQueryIO.Write is using tableRefFunction with StreamWithDeDup. - return transform.apply(input); - } else { - return input - .apply(new BatchBigQueryIONativeWrite(transform)); - } - } - } - - /** - * This {@link PTransform} is used by the {@link DataflowPipelineTranslator} as a way - * to provide the native definition of the BigQuery sink. - */ - private static class BatchBigQueryIONativeWrite extends PTransform, PDone> { - private final BigQueryIO.Write.Bound transform; - public BatchBigQueryIONativeWrite(BigQueryIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - return PDone.in(input.getPipeline()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - transform.populateDisplayData(builder); - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - BatchBigQueryIONativeWrite.class, new BatchBigQueryIONativeWriteTranslator()); - } - } - - /** - * {@code BigQueryIO.Write.Bound} support code for the Dataflow backend. - */ - private static class BatchBigQueryIONativeWriteTranslator - implements TransformTranslator { - @SuppressWarnings("unchecked") - @Override - public void translate(BatchBigQueryIONativeWrite transform, - TranslationContext context) { - translateWriteHelper(transform, transform.transform, context); - } - - private void translateWriteHelper( - BatchBigQueryIONativeWrite transform, - BigQueryIO.Write.Bound originalTransform, - TranslationContext context) { - if (context.getPipelineOptions().isStreaming()) { - // Streaming is handled by the streaming runner. - throw new AssertionError( - "BigQueryIO is specified to use streaming write in batch mode."); - } - - TableReference table = originalTransform.getTable().get(); - - // Actual translation. - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.FORMAT, "bigquery"); - context.addInput(PropertyNames.BIGQUERY_TABLE, - table.getTableId()); - context.addInput(PropertyNames.BIGQUERY_DATASET, - table.getDatasetId()); - if (table.getProjectId() != null) { - context.addInput(PropertyNames.BIGQUERY_PROJECT, table.getProjectId()); - } - if (originalTransform.getSchema() != null) { - try { - context.addInput(PropertyNames.BIGQUERY_SCHEMA, - JSON_FACTORY.toString(originalTransform.getSchema())); - } catch (IOException exn) { - throw new IllegalArgumentException("Invalid table schema.", exn); - } - } - context.addInput( - PropertyNames.BIGQUERY_CREATE_DISPOSITION, - originalTransform.getCreateDisposition().name()); - context.addInput( - PropertyNames.BIGQUERY_WRITE_DISPOSITION, - originalTransform.getWriteDisposition().name()); - // Set sink encoding to TableRowJsonCoder. - context.addEncodingInput( - WindowedValue.getValueOnlyCoder(TableRowJsonCoder.of())); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - } - } - - /** - * Specialized (non-)implementation for - * {@link com.google.cloud.dataflow.sdk.io.Write.Bound Write.Bound} - * for the Dataflow runner in streaming mode. - */ - private static class StreamingWrite extends PTransform, PDone> { - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingWrite(DataflowPipelineRunner runner, Write.Bound transform) { } - - @Override - public PDone apply(PCollection input) { - throw new UnsupportedOperationException( - "The Write transform is not supported by the Dataflow streaming runner."); - } - - @Override - protected String getKindString() { - return "StreamingWrite"; - } - } - - // ================================================================================ - // PubsubIO translations - // ================================================================================ - - static { - DataflowPipelineTranslator.registerTransformTranslator( - PubsubIO.Read.Bound.class, new StreamingPubsubIOReadTranslator()); - } - - /** - * Rewrite {@link PubsubIO.Read.Bound} to the appropriate internal node. - */ - private static class StreamingPubsubIOReadTranslator implements - TransformTranslator { - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public void translate( - PubsubIO.Read.Bound transform, - TranslationContext context) { - translateTyped(transform, context); - } - - @SuppressWarnings("deprecation") // uses internal deprecated code deliberately. - private void translateTyped( - PubsubIO.Read.Bound transform, - TranslationContext context) { - checkState(context.getPipelineOptions().isStreaming(), - "StreamingPubsubIORead is only for streaming pipelines."); - context.addStep(transform, "ParallelRead"); - context.addInput(PropertyNames.FORMAT, "pubsub"); - if (transform.getTopicProvider() != null) { - if (transform.getTopicProvider().isAccessible()) { - context.addInput( - PropertyNames.PUBSUB_TOPIC, transform.getTopic().asV1Beta1Path()); - } else { - context.addInput( - PropertyNames.PUBSUB_TOPIC_OVERRIDE, - ((NestedValueProvider) transform.getTopicProvider()).propertyName()); - } - } - if (transform.getSubscriptionProvider() != null) { - if (transform.getSubscriptionProvider().isAccessible()) { - context.addInput( - PropertyNames.PUBSUB_SUBSCRIPTION, - transform.getSubscription().asV1Beta1Path()); - } else { - context.addInput( - PropertyNames.PUBSUB_SUBSCRIPTION_OVERRIDE, - ((NestedValueProvider) transform.getSubscriptionProvider()) - .propertyName()); - } - } - if (transform.getTimestampLabel() != null) { - context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, - transform.getTimestampLabel()); - } - if (transform.getIdLabel() != null) { - context.addInput(PropertyNames.PUBSUB_ID_LABEL, transform.getIdLabel()); - } - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - } - - /** - * Suppress application of {@link PubsubUnboundedSink#apply} in streaming mode so that we - * can instead defer to Windmill's implementation. - */ - private static class StreamingPubsubIOWrite extends PTransform, PDone> { - private final PubsubIO.Write.Bound transform; - - /** - * Builds an instance of this class from the overridden transform. - */ - public StreamingPubsubIOWrite( - DataflowPipelineRunner runner, PubsubIO.Write.Bound transform) { - this.transform = transform; - } - - PubsubIO.Write.Bound getOverriddenTransform() { - return transform; - } - - @Override - public PDone apply(PCollection input) { - return PDone.in(input.getPipeline()); - } - - @Override - protected String getKindString() { - return "StreamingPubsubIOWrite"; - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - StreamingPubsubIOWrite.class, new StreamingPubsubIOWriteTranslator()); - } - } - - /** - * Rewrite {@link StreamingPubsubIOWrite} to the appropriate internal node. - */ - private static class StreamingPubsubIOWriteTranslator implements - TransformTranslator { - - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public void translate( - StreamingPubsubIOWrite transform, - TranslationContext context) { - translateTyped(transform, context); - } - - @SuppressWarnings("deprecation") // uses internal deprecated code deliberately. - private void translateTyped( - StreamingPubsubIOWrite transform, - TranslationContext context) { - checkState(context.getPipelineOptions().isStreaming(), - "StreamingPubsubIOWrite is only for streaming pipelines."); - PubsubIO.Write.Bound overriddenTransform = transform.getOverriddenTransform(); - context.addStep(transform, "ParallelWrite"); - context.addInput(PropertyNames.FORMAT, "pubsub"); - if (overriddenTransform.getTopicProvider().isAccessible()) { - context.addInput( - PropertyNames.PUBSUB_TOPIC, overriddenTransform.getTopic().asV1Beta1Path()); - } else { - context.addInput( - PropertyNames.PUBSUB_TOPIC_OVERRIDE, - ((NestedValueProvider) overriddenTransform.getTopicProvider()).propertyName()); - } - if (overriddenTransform.getTimestampLabel() != null) { - context.addInput(PropertyNames.PUBSUB_TIMESTAMP_LABEL, - overriddenTransform.getTimestampLabel()); - } - if (overriddenTransform.getIdLabel() != null) { - context.addInput(PropertyNames.PUBSUB_ID_LABEL, overriddenTransform.getIdLabel()); - } - context.addEncodingInput( - WindowedValue.getValueOnlyCoder(overriddenTransform.getCoder())); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - } - } - - // ================================================================================ - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.io.Read.Unbounded Read.Unbounded} for the - * Dataflow runner in streaming mode. - * - *

              In particular, if an UnboundedSource requires deduplication, then features of WindmillSink - * are leveraged to do the deduplication. - */ - private static class StreamingUnboundedRead extends PTransform> { - private final UnboundedSource source; - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingUnboundedRead(DataflowPipelineRunner runner, Read.Unbounded transform) { - this.source = transform.getSource(); - } - - @Override - protected Coder getDefaultOutputCoder() { - return source.getDefaultOutputCoder(); - } - - @Override - public final PCollection apply(PInput input) { - source.validate(); - - if (source.requiresDeduping()) { - return Pipeline.applyTransform(input, new ReadWithIds(source)) - .apply(new Deduplicate()); - } else { - return Pipeline.applyTransform(input, new ReadWithIds(source)) - .apply(ValueWithRecordId.stripIds()); - } - } - - /** - * {@link PTransform} that reads {@code (record,recordId)} pairs from an - * {@link UnboundedSource}. - */ - private static class ReadWithIds - extends PTransform>> { - private final UnboundedSource source; - - private ReadWithIds(UnboundedSource source) { - this.source = source; - } - - @Override - public final PCollection> apply(PInput input) { - return PCollection.>createPrimitiveOutputInternal( - input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED); - } - - @Override - protected Coder> getDefaultOutputCoder() { - return ValueWithRecordId.ValueWithRecordIdCoder.of(source.getDefaultOutputCoder()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("source", source.getClass())); - builder.include(source); - } - - public UnboundedSource getSource() { - return source; - } - } - - @Override - public String getKindString() { - return "Read(" + approximateSimpleName(source.getClass()) + ")"; - } - - static { - DataflowPipelineTranslator.registerTransformTranslator( - ReadWithIds.class, new ReadWithIdsTranslator()); - } - - private static class ReadWithIdsTranslator - implements DataflowPipelineTranslator.TransformTranslator> { - @Override - public void translate(ReadWithIds transform, - DataflowPipelineTranslator.TranslationContext context) { - ReadTranslator.translateReadHelper(transform.getSource(), transform, context); - } - } - } - - /** - * Remove values with duplicate ids. - */ - private static class Deduplicate - extends PTransform>, PCollection> { - // Use a finite set of keys to improve bundling. Without this, the key space - // will be the space of ids which is potentially very large, which results in much - // more per-key overhead. - private static final int NUM_RESHARD_KEYS = 10000; - @Override - public PCollection apply(PCollection> input) { - return input - .apply(WithKeys.of(new SerializableFunction, Integer>() { - @Override - public Integer apply(ValueWithRecordId value) { - return Arrays.hashCode(value.getId()) % NUM_RESHARD_KEYS; - } - })) - // Reshuffle will dedup based on ids in ValueWithRecordId by passing the data through - // WindmillSink. - .apply(Reshuffle.>of()) - .apply(ParDo.named("StripIds").of( - new DoFn>, T>() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().getValue().getValue()); - } - })); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.io.Read.Bounded Read.Bounded} for the - * Dataflow runner in streaming mode. - */ - private static class StreamingBoundedRead extends PTransform> { - private final BoundedSource source; - - /** Builds an instance of this class from the overridden transform. */ - @SuppressWarnings("unused") // used via reflection in DataflowRunner#apply() - public StreamingBoundedRead(DataflowPipelineRunner runner, Read.Bounded transform) { - this.source = transform.getSource(); - } - - @Override - protected Coder getDefaultOutputCoder() { - return source.getDefaultOutputCoder(); - } - - @Override - public final PCollection apply(PInput input) { - source.validate(); - - return Pipeline.applyTransform(input, new DataflowUnboundedReadFromBoundedSource<>(source)) - .setIsBoundedInternal(IsBounded.BOUNDED); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.Create.Values Create.Values} for the - * Dataflow runner in streaming mode. - */ - private static class StreamingCreate extends PTransform> { - private final Create.Values transform; - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingCreate(DataflowPipelineRunner runner, Create.Values transform) { - this.transform = transform; - } - - /** - * {@link DoFn} that outputs a single KV.of(null, null) kick off the {@link GroupByKey} - * in the streaming create implementation. - */ - private static class OutputNullKv extends DoFn> { - @Override - public void processElement(DoFn>.ProcessContext c) throws Exception { - c.output(KV.of((Void) null, (Void) null)); - } - } - - /** - * A {@link DoFn} which outputs the specified elements by first encoding them to bytes using - * the specified {@link Coder} so that they are serialized as part of the {@link DoFn} but - * need not implement {@code Serializable}. - */ - private static class OutputElements extends DoFn { - private final Coder coder; - private final List encodedElements; - - public OutputElements(Iterable elems, Coder coder) { - this.coder = coder; - this.encodedElements = new ArrayList<>(); - for (T t : elems) { - try { - encodedElements.add(CoderUtils.encodeToByteArray(coder, t)); - } catch (CoderException e) { - throw new IllegalArgumentException("Unable to encode value " + t - + " with coder " + coder, e); - } - } - } - - @Override - public void processElement(ProcessContext c) throws IOException { - for (byte[] encodedElement : encodedElements) { - c.output(CoderUtils.decodeFromByteArray(coder, encodedElement)); - } - } - } - - @Override - public PCollection apply(PInput input) { - try { - Coder coder = transform.getDefaultOutputCoder(input); - return Pipeline.applyTransform( - input, PubsubIO.Read.named("StartingSignal").subscription("_starting_signal/")) - .apply(ParDo.of(new OutputNullKv())) - .apply("GlobalSingleton", Window.>into(new GlobalWindows()) - .triggering(AfterPane.elementCountAtLeast(1)) - .withAllowedLateness(Duration.ZERO) - .discardingFiredPanes()) - .apply(GroupByKey.create()) - // Go back to the default windowing strategy, so that our setting allowed lateness - // doesn't count as the user having set it. - .setWindowingStrategyInternal(WindowingStrategy.globalDefault()) - .apply(Window.>>into(new GlobalWindows())) - .apply(ParDo.of(new OutputElements<>(transform.getElements(), coder))) - .setCoder(coder).setIsBoundedInternal(IsBounded.BOUNDED); - } catch (CannotProvideCoderException e) { - throw new IllegalArgumentException("Unable to infer a coder and no Coder was specified. " - + "Please set a coder by invoking Create.withCoder() explicitly.", e); - } - } - - @Override - protected String getKindString() { - return "StreamingCreate"; - } - } - - /** - * A specialized {@link DoFn} for writing the contents of a {@link PCollection} - * to a streaming {@link PCollectionView} backend implementation. - */ - private static class StreamingPCollectionViewWriterFn - extends DoFn, T> implements DoFn.RequiresWindowAccess { - private final PCollectionView view; - private final Coder dataCoder; - - public static StreamingPCollectionViewWriterFn create( - PCollectionView view, Coder dataCoder) { - return new StreamingPCollectionViewWriterFn(view, dataCoder); - } - - private StreamingPCollectionViewWriterFn(PCollectionView view, Coder dataCoder) { - this.view = view; - this.dataCoder = dataCoder; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - List> output = new ArrayList<>(); - for (T elem : c.element()) { - output.add(WindowedValue.of(elem, c.timestamp(), c.window(), c.pane())); - } - - c.windowingInternals().writePCollectionViewData( - view.getTagInternal(), output, dataCoder); - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsMap View.AsMap} - * for the Dataflow runner in streaming mode. - */ - private static class StreamingViewAsMap - extends PTransform>, PCollectionView>> { - private final DataflowPipelineRunner runner; - - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsMap(DataflowPipelineRunner runner, View.AsMap transform) { - this.runner = runner; - } - - @Override - public PCollectionView> apply(PCollection> input) { - PCollectionView> view = - PCollectionViews.mapView( - input.getPipeline(), - input.getWindowingStrategy(), - input.getCoder()); - - @SuppressWarnings({"rawtypes", "unchecked"}) - KvCoder inputCoder = (KvCoder) input.getCoder(); - try { - inputCoder.getKeyCoder().verifyDeterministic(); - } catch (NonDeterministicException e) { - runner.recordViewUsesNonDeterministicKeyCoder(this); - } - - return input - .apply(Combine.globally(new Concatenate>()).withoutDefaults()) - .apply(ParDo.of(StreamingPCollectionViewWriterFn.create(view, input.getCoder()))) - .apply(View.CreatePCollectionView., Map>of(view)); - } - - @Override - protected String getKindString() { - return "StreamingViewAsMap"; - } - } - - /** - * Specialized expansion for {@link - * com.google.cloud.dataflow.sdk.transforms.View.AsMultimap View.AsMultimap} for the - * Dataflow runner in streaming mode. - */ - private static class StreamingViewAsMultimap - extends PTransform>, PCollectionView>>> { - private final DataflowPipelineRunner runner; - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsMultimap(DataflowPipelineRunner runner, View.AsMultimap transform) { - this.runner = runner; - } - - @Override - public PCollectionView>> apply(PCollection> input) { - PCollectionView>> view = - PCollectionViews.multimapView( - input.getPipeline(), - input.getWindowingStrategy(), - input.getCoder()); - - @SuppressWarnings({"rawtypes", "unchecked"}) - KvCoder inputCoder = (KvCoder) input.getCoder(); - try { - inputCoder.getKeyCoder().verifyDeterministic(); - } catch (NonDeterministicException e) { - runner.recordViewUsesNonDeterministicKeyCoder(this); - } - - return input - .apply(Combine.globally(new Concatenate>()).withoutDefaults()) - .apply(ParDo.of(StreamingPCollectionViewWriterFn.create(view, input.getCoder()))) - .apply(View.CreatePCollectionView., Map>>of(view)); - } - - @Override - protected String getKindString() { - return "StreamingViewAsMultimap"; - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsList View.AsList} for the - * Dataflow runner in streaming mode. - */ - private static class StreamingViewAsList - extends PTransform, PCollectionView>> { - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsList(DataflowPipelineRunner runner, View.AsList transform) {} - - @Override - public PCollectionView> apply(PCollection input) { - PCollectionView> view = - PCollectionViews.listView( - input.getPipeline(), - input.getWindowingStrategy(), - input.getCoder()); - - return input.apply(Combine.globally(new Concatenate()).withoutDefaults()) - .apply(ParDo.of(StreamingPCollectionViewWriterFn.create(view, input.getCoder()))) - .apply(View.CreatePCollectionView.>of(view)); - } - - @Override - protected String getKindString() { - return "StreamingViewAsList"; - } - } - - /** - * Specialized implementation for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsIterable View.AsIterable} for the - * Dataflow runner in streaming mode. - */ - private static class StreamingViewAsIterable - extends PTransform, PCollectionView>> { - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsIterable(DataflowPipelineRunner runner, View.AsIterable transform) { } - - @Override - public PCollectionView> apply(PCollection input) { - PCollectionView> view = - PCollectionViews.iterableView( - input.getPipeline(), - input.getWindowingStrategy(), - input.getCoder()); - - return input.apply(Combine.globally(new Concatenate()).withoutDefaults()) - .apply(ParDo.of(StreamingPCollectionViewWriterFn.create(view, input.getCoder()))) - .apply(View.CreatePCollectionView.>of(view)); - } - - @Override - protected String getKindString() { - return "StreamingViewAsIterable"; - } - } - - private static class WrapAsList extends DoFn> { - @Override - public void processElement(ProcessContext c) { - c.output(Arrays.asList(c.element())); - } - } - - /** - * Specialized expansion for - * {@link com.google.cloud.dataflow.sdk.transforms.View.AsSingleton View.AsSingleton} for the - * Dataflow runner in streaming mode. - */ - private static class StreamingViewAsSingleton - extends PTransform, PCollectionView> { - private View.AsSingleton transform; - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingViewAsSingleton(DataflowPipelineRunner runner, View.AsSingleton transform) { - this.transform = transform; - } - - @Override - public PCollectionView apply(PCollection input) { - Combine.Globally combine = Combine.globally( - new SingletonCombine<>(transform.hasDefaultValue(), transform.defaultValue())); - if (!transform.hasDefaultValue()) { - combine = combine.withoutDefaults(); - } - return input.apply(combine.asSingletonView()); - } - - @Override - protected String getKindString() { - return "StreamingViewAsSingleton"; - } - - private static class SingletonCombine extends Combine.BinaryCombineFn { - private boolean hasDefaultValue; - private T defaultValue; - - SingletonCombine(boolean hasDefaultValue, T defaultValue) { - this.hasDefaultValue = hasDefaultValue; - this.defaultValue = defaultValue; - } - - @Override - public T apply(T left, T right) { - throw new IllegalArgumentException("PCollection with more than one element " - + "accessed as a singleton view. Consider using Combine.globally().asSingleton() to " - + "combine the PCollection into a single value"); - } - - @Override - public T identity() { - if (hasDefaultValue) { - return defaultValue; - } else { - throw new IllegalArgumentException( - "Empty PCollection accessed as a singleton view. " - + "Consider setting withDefault to provide a default value"); - } - } - } - } - - private static class StreamingCombineGloballyAsSingletonView - extends PTransform, PCollectionView> { - Combine.GloballyAsSingletonView transform; - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public StreamingCombineGloballyAsSingletonView( - DataflowPipelineRunner runner, - Combine.GloballyAsSingletonView transform) { - this.transform = transform; - } - - @Override - public PCollectionView apply(PCollection input) { - PCollection combined = - input.apply(Combine.globally(transform.getCombineFn()) - .withoutDefaults() - .withFanout(transform.getFanout())); - - PCollectionView view = PCollectionViews.singletonView( - combined.getPipeline(), - combined.getWindowingStrategy(), - transform.getInsertDefault(), - transform.getInsertDefault() - ? transform.getCombineFn().defaultValue() : null, - combined.getCoder()); - return combined - .apply(ParDo.of(new WrapAsList())) - .apply(ParDo.of(StreamingPCollectionViewWriterFn.create(view, combined.getCoder()))) - .apply(View.CreatePCollectionView.of(view)); - } - - @Override - protected String getKindString() { - return "StreamingCombineGloballyAsSingletonView"; - } - } - - /** - * Combiner that combines {@code T}s into a single {@code List} containing all inputs. - * - *

              For internal use by {@link StreamingViewAsMap}, {@link StreamingViewAsMultimap}, - * {@link StreamingViewAsList}, {@link StreamingViewAsIterable}. - * They require the input {@link PCollection} fits in memory. - * For a large {@link PCollection} this is expected to crash! - * - * @param the type of elements to concatenate. - */ - private static class Concatenate extends CombineFn, List> { - @Override - public List createAccumulator() { - return new ArrayList(); - } - - @Override - public List addInput(List accumulator, T input) { - accumulator.add(input); - return accumulator; - } - - @Override - public List mergeAccumulators(Iterable> accumulators) { - List result = createAccumulator(); - for (List accumulator : accumulators) { - result.addAll(accumulator); - } - return result; - } - - @Override - public List extractOutput(List accumulator) { - return accumulator; - } - - @Override - public Coder> getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) { - return ListCoder.of(inputCoder); - } - - @Override - public Coder> getDefaultOutputCoder(CoderRegistry registry, Coder inputCoder) { - return ListCoder.of(inputCoder); - } - } - - /** - * Specialized expansion for unsupported IO transforms and DoFns that throws an error. - */ - private static class UnsupportedIO - extends PTransform { - @Nullable - private PTransform transform; - @Nullable - private DoFn doFn; - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, AvroIO.Read.Bound transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, BigQueryIO.Read.Bound transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, TextIO.Read.Bound transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, Read.Bounded transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, Read.Unbounded transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, AvroIO.Write.Bound transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, TextIO.Write.Bound transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden doFn. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, - PubsubReader doFn) { - this.doFn = doFn; - } - - /** - * Builds an instance of this class from the overridden doFn. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, - PubsubWriter doFn) { - this.doFn = doFn; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, PubsubUnboundedSource transform) { - this.transform = transform; - } - - /** - * Builds an instance of this class from the overridden transform. - */ - @SuppressWarnings("unused") // used via reflection in DataflowPipelineRunner#apply() - public UnsupportedIO(DataflowPipelineRunner runner, PubsubUnboundedSink transform) { - this.transform = transform; - } - - - @Override - public OutputT apply(InputT input) { - String mode = input.getPipeline().getOptions().as(StreamingOptions.class).isStreaming() - ? "streaming" : "batch"; - String name = - transform == null - ? approximateSimpleName(doFn.getClass()) - : approximatePTransformName(transform.getClass()); - throw new UnsupportedOperationException( - String.format("The DataflowPipelineRunner in %s mode does not support %s.", mode, name)); - } - } - - @Override - public String toString() { - return "DataflowPipelineRunner#" + options.getJobName(); - } - - /** - * Attempts to detect all the resources the class loader has access to. This does not recurse - * to class loader parents stopping it from pulling in resources from the system class loader. - * - * @param classLoader The URLClassLoader to use to detect resources to stage. - * @throws IllegalArgumentException If either the class loader is not a URLClassLoader or one - * of the resources the class loader exposes is not a file resource. - * @return A list of absolute paths to the resources the class loader uses. - */ - protected static List detectClassPathResourcesToStage(ClassLoader classLoader) { - if (!(classLoader instanceof URLClassLoader)) { - String message = String.format("Unable to use ClassLoader to detect classpath elements. " - + "Current ClassLoader is %s, only URLClassLoaders are supported.", classLoader); - LOG.error(message); - throw new IllegalArgumentException(message); - } - - List files = new ArrayList<>(); - for (URL url : ((URLClassLoader) classLoader).getURLs()) { - try { - files.add(new File(url.toURI()).getAbsolutePath()); - } catch (IllegalArgumentException | URISyntaxException e) { - String message = String.format("Unable to convert url (%s) to file.", url); - LOG.error(message); - throw new IllegalArgumentException(message, e); - } - } - return files; - } - - /** - * Finds the id for the running job of the given name. - */ - private String getJobIdFromName(String jobName) { - try { - ListJobsResponse listResult; - String token = null; - do { - listResult = dataflowClient.projects().jobs() - .list(options.getProject()) - .setPageToken(token) - .execute(); - token = listResult.getNextPageToken(); - for (Job job : listResult.getJobs()) { - if (job.getName().equals(jobName) - && MonitoringUtil.toState(job.getCurrentState()).equals(State.RUNNING)) { - return job.getId(); - } - } - } while (token != null); - } catch (GoogleJsonResponseException e) { - throw new RuntimeException( - "Got error while looking up jobs: " - + (e.getDetails() != null ? e.getDetails().getMessage() : e), e); - } catch (IOException e) { - throw new RuntimeException("Got error while looking up jobs: ", e); - } - - throw new IllegalArgumentException("Could not find running job named " + jobName); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java deleted file mode 100644 index 982f631da6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerHooks.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.api.services.dataflow.model.Environment; -import com.google.cloud.dataflow.sdk.annotations.Experimental; - -/** - * An instance of this class can be passed to the - * {@link DataflowPipelineRunner} to add user defined hooks to be - * invoked at various times during pipeline execution. - */ -@Experimental -public class DataflowPipelineRunnerHooks { - /** - * Allows the user to modify the environment of their job before their job is submitted - * to the service for execution. - * - * @param environment The environment of the job. Users can make change to this instance in order - * to change the environment with which their job executes on the service. - */ - public void modifyEnvironmentBeforeSubmission(Environment environment) {} - - /** Allows the user to specify whether the job should actually be executed. */ - public boolean shouldActuallyRunJob() { - return true; - } - - /** Specifies whether the runner should fail if it fails to write to a job file. */ - public boolean failOnJobFileWriteFailure() { - return false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java deleted file mode 100644 index 05f9bfe818..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslator.java +++ /dev/null @@ -1,1102 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; -import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; -import static com.google.cloud.dataflow.sdk.util.StringUtils.jsonStringToByteArray; -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addDictionary; -import static com.google.cloud.dataflow.sdk.util.Structs.addList; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.addObject; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.services.dataflow.model.AutoscalingSettings; -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.api.services.dataflow.model.Disk; -import com.google.api.services.dataflow.model.Environment; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.Step; -import com.google.api.services.dataflow.model.WorkerPool; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.StreamingOptions; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.GroupByKeyAndSortValuesOnly; -import com.google.cloud.dataflow.sdk.runners.dataflow.ReadTranslator; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.DoFnInfo; -import com.google.cloud.dataflow.sdk.util.OutputReference; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TypedPValue; -import com.google.common.base.Strings; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * {@link DataflowPipelineTranslator} knows how to translate {@link Pipeline} objects - * into Cloud Dataflow Service API {@link Job}s. - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class DataflowPipelineTranslator { - // Must be kept in sync with their internal counterparts. - private static final Logger LOG = LoggerFactory.getLogger(DataflowPipelineTranslator.class); - private static final ObjectMapper MAPPER = new ObjectMapper(); - - /** - * A map from {@link PTransform} subclass to the corresponding - * {@link TransformTranslator} to use to translate that transform. - * - *

              A static map that contains system-wide defaults. - */ - private static Map transformTranslators = - new HashMap<>(); - - /** Provided configuration options. */ - private final DataflowPipelineOptions options; - - /** - * Constructs a translator from the provided options. - * - * @param options Properties that configure the translator. - * - * @return The newly created translator. - */ - public static DataflowPipelineTranslator fromOptions( - DataflowPipelineOptions options) { - return new DataflowPipelineTranslator(options); - } - - private DataflowPipelineTranslator(DataflowPipelineOptions options) { - this.options = options; - } - - /** - * Translates a {@link Pipeline} into a {@code JobSpecification}. - */ - public JobSpecification translate( - Pipeline pipeline, - DataflowPipelineRunner runner, - List packages) { - - Translator translator = new Translator(pipeline, runner); - Job result = translator.translate(packages); - return new JobSpecification(result, Collections.unmodifiableMap(translator.stepNames)); - } - - /** - * The result of a job translation. - * - *

              Used to pass the result {@link Job} and any state that was used to construct the job that - * may be of use to other classes (eg the {@link PTransform} to StepName mapping). - */ - public static class JobSpecification { - private final Job job; - private final Map, String> stepNames; - - public JobSpecification(Job job, Map, String> stepNames) { - this.job = job; - this.stepNames = stepNames; - } - - public Job getJob() { - return job; - } - - /** - * Returns the mapping of {@link AppliedPTransform AppliedPTransforms} to the internal step - * name for that {@code AppliedPTransform}. - */ - public Map, String> getStepNames() { - return stepNames; - } - } - - /** - * Renders a {@link Job} as a string. - */ - public static String jobToString(Job job) { - try { - return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(job); - } catch (JsonProcessingException exc) { - throw new IllegalStateException("Failed to render Job as String.", exc); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Records that instances of the specified PTransform class - * should be translated by default by the corresponding - * {@link TransformTranslator}. - */ - public static void registerTransformTranslator( - Class transformClass, - TransformTranslator transformTranslator) { - if (transformTranslators.put(transformClass, transformTranslator) != null) { - throw new IllegalArgumentException( - "defining multiple translators for " + transformClass); - } - } - - /** - * Returns the {@link TransformTranslator} to use for instances of the - * specified PTransform class, or null if none registered. - */ - public - TransformTranslator getTransformTranslator(Class transformClass) { - return transformTranslators.get(transformClass); - } - - /** - * A {@link TransformTranslator} knows how to translate - * a particular subclass of {@link PTransform} for the - * Cloud Dataflow service. It does so by - * mutating the {@link TranslationContext}. - */ - public interface TransformTranslator { - void translate(TransformT transform, - TranslationContext context); - } - - /** - * The interface provided to registered callbacks for interacting - * with the {@link DataflowPipelineRunner}, including reading and writing the - * values of {@link PCollection}s and side inputs ({@link PCollectionView}s). - */ - public interface TranslationContext { - /** - * Returns the configured pipeline options. - */ - DataflowPipelineOptions getPipelineOptions(); - - /** - * Returns the input of the currently being translated transform. - */ - InputT getInput(PTransform transform); - - /** - * Returns the output of the currently being translated transform. - */ - OutputT getOutput(PTransform transform); - - /** - * Returns the full name of the currently being translated transform. - */ - String getFullName(PTransform transform); - - /** - * Adds a step to the Dataflow workflow for the given transform, with - * the given Dataflow step type. - * This step becomes "current" for the purpose of {@link #addInput} and - * {@link #addOutput}. - */ - void addStep(PTransform transform, String type); - - /** - * Adds a pre-defined step to the Dataflow workflow. The given PTransform should be - * consistent with the Step, in terms of input, output and coder types. - * - *

              This is a low-level operation, when using this method it is up to - * the caller to ensure that names do not collide. - */ - void addStep(PTransform transform, Step step); - - /** - * Sets the encoding for the current Dataflow step. - */ - void addEncodingInput(Coder value); - - /** - * Adds an input with the given name and value to the current - * Dataflow step. - */ - void addInput(String name, Boolean value); - - /** - * Adds an input with the given name and value to the current - * Dataflow step. - */ - void addInput(String name, String value); - - /** - * Adds an input with the given name and value to the current - * Dataflow step. - */ - void addInput(String name, Long value); - - /** - * Adds an input with the given name to the previously added Dataflow - * step, coming from the specified input PValue. - */ - void addInput(String name, PInput value); - - /** - * Adds an input that is a dictionary of strings to objects. - */ - void addInput(String name, Map elements); - - /** - * Adds an input that is a list of objects. - */ - void addInput(String name, List> elements); - - /** - * Adds an output with the given name to the previously added - * Dataflow step, producing the specified output {@code PValue}, - * including its {@code Coder} if a {@code TypedPValue}. If the - * {@code PValue} is a {@code PCollection}, wraps its coder inside - * a {@code WindowedValueCoder}. - */ - void addOutput(String name, PValue value); - - /** - * Adds an output with the given name to the previously added - * Dataflow step, producing the specified output {@code PValue}, - * including its {@code Coder} if a {@code TypedPValue}. If the - * {@code PValue} is a {@code PCollection}, wraps its coder inside - * a {@code ValueOnlyCoder}. - */ - void addValueOnlyOutput(String name, PValue value); - - /** - * Adds an output with the given name to the previously added - * CollectionToSingleton Dataflow step, consuming the specified - * input {@code PValue} and producing the specified output - * {@code PValue}. This step requires special treatment for its - * output encoding. - */ - void addCollectionToSingletonOutput(String name, - PValue inputValue, - PValue outputValue); - - /** - * Encode a PValue reference as an output reference. - */ - OutputReference asOutputReference(PValue value); - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Translates a Pipeline into the Dataflow representation. - */ - class Translator implements PipelineVisitor, TranslationContext { - /** The Pipeline to translate. */ - private final Pipeline pipeline; - - /** The runner which will execute the pipeline. */ - private final DataflowPipelineRunner runner; - - /** The Cloud Dataflow Job representation. */ - private final Job job = new Job(); - - /** - * Translator is stateful, as addProperty calls refer to the current step. - */ - private Step currentStep; - - /** - * A Map from AppliedPTransform to their unique Dataflow step names. - */ - private final Map, String> stepNames = new HashMap<>(); - - /** - * A Map from PValues to their output names used by their producer - * Dataflow steps. - */ - private final Map outputNames = new HashMap<>(); - - /** - * A Map from PValues to the Coders used for them. - */ - private final Map> outputCoders = new HashMap<>(); - - /** - * The transform currently being applied. - */ - private AppliedPTransform currentTransform; - - /** - * Constructs a Translator that will translate the specified - * Pipeline into Dataflow objects. - */ - public Translator(Pipeline pipeline, DataflowPipelineRunner runner) { - this.pipeline = pipeline; - this.runner = runner; - } - - /** - * Translates this Translator's pipeline onto its writer. - * @return a Job definition filled in with the type of job, the environment, - * and the job steps. - */ - public Job translate(List packages) { - job.setName(options.getJobName().toLowerCase()); - - Environment environment = new Environment(); - job.setEnvironment(environment); - - try { - environment.setSdkPipelineOptions( - MAPPER.readValue(MAPPER.writeValueAsBytes(options), Map.class)); - } catch (IOException e) { - throw new IllegalArgumentException( - "PipelineOptions specified failed to serialize to JSON.", e); - } - - WorkerPool workerPool = new WorkerPool(); - - if (options.getTeardownPolicy() != null) { - workerPool.setTeardownPolicy(options.getTeardownPolicy().getTeardownPolicyName()); - } - - if (options.isStreaming()) { - job.setType("JOB_TYPE_STREAMING"); - } else { - job.setType("JOB_TYPE_BATCH"); - workerPool.setDiskType(options.getWorkerDiskType()); - } - - if (options.getWorkerMachineType() != null) { - workerPool.setMachineType(options.getWorkerMachineType()); - } - - if (options.getUsePublicIps() != null) { - if (options.getUsePublicIps()) { - workerPool.setIpConfiguration("WORKER_IP_PUBLIC"); - } else { - workerPool.setIpConfiguration("WORKER_IP_PRIVATE"); - } - } - workerPool.setPackages(packages); - workerPool.setNumWorkers(options.getNumWorkers()); - - if (options.getLabels() != null) { - job.setLabels(options.getLabels()); - } - if (options.isStreaming() - && (options.getExperiments() == null - || !options.getExperiments().contains("enable_windmill_service"))) { - // Use separate data disk for streaming. - Disk disk = new Disk(); - disk.setDiskType(options.getWorkerDiskType()); - workerPool.setDataDisks(Collections.singletonList(disk)); - } - if (!Strings.isNullOrEmpty(options.getZone())) { - workerPool.setZone(options.getZone()); - } - if (!Strings.isNullOrEmpty(options.getNetwork())) { - workerPool.setNetwork(options.getNetwork()); - } - if (!Strings.isNullOrEmpty(options.getSubnetwork())) { - workerPool.setSubnetwork(options.getSubnetwork()); - } - if (options.getDiskSizeGb() > 0) { - workerPool.setDiskSizeGb(options.getDiskSizeGb()); - } - AutoscalingSettings settings = new AutoscalingSettings(); - if (options.getAutoscalingAlgorithm() != null) { - settings.setAlgorithm(options.getAutoscalingAlgorithm().getAlgorithm()); - } - settings.setMaxNumWorkers(options.getMaxNumWorkers()); - workerPool.setAutoscalingSettings(settings); - - List workerPools = new LinkedList<>(); - - workerPools.add(workerPool); - environment.setWorkerPools(workerPools); - - if (options.getServiceAccount() != null) { - environment.setServiceAccountEmail(options.getServiceAccount()); - } - - pipeline.traverseTopologically(this); - return job; - } - - @Override - public DataflowPipelineOptions getPipelineOptions() { - return options; - } - - @Override - public InputT getInput(PTransform transform) { - return (InputT) getCurrentTransform(transform).getInput(); - } - - @Override - public OutputT getOutput(PTransform transform) { - return (OutputT) getCurrentTransform(transform).getOutput(); - } - - @Override - public String getFullName(PTransform transform) { - return getCurrentTransform(transform).getFullName(); - } - - private AppliedPTransform getCurrentTransform(PTransform transform) { - checkArgument( - currentTransform != null && currentTransform.getTransform() == transform, - "can only be called with current transform"); - return currentTransform; - } - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - } - - @Override - public void visitTransform(TransformTreeNode node) { - PTransform transform = node.getTransform(); - TransformTranslator translator = - getTransformTranslator(transform.getClass()); - if (translator == null) { - throw new IllegalStateException( - "no translator registered for " + transform); - } - LOG.debug("Translating {}", transform); - currentTransform = AppliedPTransform.of( - node.getFullName(), node.getInput(), node.getOutput(), (PTransform) transform); - translator.translate(transform, this); - currentTransform = null; - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - LOG.debug("Checking translation of {}", value); - if (value.getProducingTransformInternal() == null) { - throw new RuntimeException( - "internal error: expecting a PValue " - + "to have a producingTransform"); - } - if (!producer.isCompositeNode()) { - // Primitive transforms are the only ones assigned step names. - asOutputReference(value); - } - } - - @Override - public void addStep(PTransform transform, String type) { - String stepName = genStepName(); - if (stepNames.put(getCurrentTransform(transform), stepName) != null) { - throw new IllegalArgumentException( - transform + " already has a name specified"); - } - // Start the next "steps" list item. - List steps = job.getSteps(); - if (steps == null) { - steps = new LinkedList<>(); - job.setSteps(steps); - } - - currentStep = new Step(); - currentStep.setName(stepName); - currentStep.setKind(type); - steps.add(currentStep); - addInput(PropertyNames.USER_NAME, getFullName(transform)); - addDisplayData(stepName, transform); - } - - @Override - public void addStep(PTransform transform, Step original) { - Step step = original.clone(); - String stepName = step.getName(); - if (stepNames.put(getCurrentTransform(transform), stepName) != null) { - throw new IllegalArgumentException(transform + " already has a name specified"); - } - - Map properties = step.getProperties(); - if (properties != null) { - @Nullable List> outputInfoList = null; - try { - // TODO: This should be done via a Structs accessor. - @Nullable List> list = - (List>) properties.get(PropertyNames.OUTPUT_INFO); - outputInfoList = list; - } catch (Exception e) { - throw new RuntimeException("Inconsistent dataflow pipeline translation", e); - } - if (outputInfoList != null && outputInfoList.size() > 0) { - Map firstOutputPort = outputInfoList.get(0); - @Nullable String name; - try { - name = getString(firstOutputPort, PropertyNames.OUTPUT_NAME); - } catch (Exception e) { - name = null; - } - if (name != null) { - registerOutputName(getOutput(transform), name); - } - } - } - - List steps = job.getSteps(); - if (steps == null) { - steps = new LinkedList<>(); - job.setSteps(steps); - } - currentStep = step; - steps.add(step); - } - - @Override - public void addEncodingInput(Coder coder) { - CloudObject encoding = SerializableUtils.ensureSerializable(coder); - addObject(getProperties(), PropertyNames.ENCODING, encoding); - } - - @Override - public void addInput(String name, Boolean value) { - addBoolean(getProperties(), name, value); - } - - @Override - public void addInput(String name, String value) { - addString(getProperties(), name, value); - } - - @Override - public void addInput(String name, Long value) { - addLong(getProperties(), name, value); - } - - @Override - public void addInput(String name, Map elements) { - addDictionary(getProperties(), name, elements); - } - - @Override - public void addInput(String name, List> elements) { - addList(getProperties(), name, elements); - } - - @Override - public void addInput(String name, PInput value) { - if (value instanceof PValue) { - addInput(name, asOutputReference((PValue) value)); - } else { - throw new IllegalStateException("Input must be a PValue"); - } - } - - @Override - public void addOutput(String name, PValue value) { - Coder coder; - if (value instanceof TypedPValue) { - coder = ((TypedPValue) value).getCoder(); - if (value instanceof PCollection) { - // Wrap the PCollection element Coder inside a WindowedValueCoder. - coder = WindowedValue.getFullCoder( - coder, - ((PCollection) value).getWindowingStrategy().getWindowFn().windowCoder()); - } - } else { - // No output coder to encode. - coder = null; - } - addOutput(name, value, coder); - } - - @Override - public void addValueOnlyOutput(String name, PValue value) { - Coder coder; - if (value instanceof TypedPValue) { - coder = ((TypedPValue) value).getCoder(); - if (value instanceof PCollection) { - // Wrap the PCollection element Coder inside a ValueOnly - // WindowedValueCoder. - coder = WindowedValue.getValueOnlyCoder(coder); - } - } else { - // No output coder to encode. - coder = null; - } - addOutput(name, value, coder); - } - - @Override - public void addCollectionToSingletonOutput(String name, - PValue inputValue, - PValue outputValue) { - Coder inputValueCoder = - checkNotNull(outputCoders.get(inputValue)); - // The inputValueCoder for the input PCollection should be some - // WindowedValueCoder of the input PCollection's element - // coder. - checkState(inputValueCoder instanceof WindowedValue.WindowedValueCoder); - // The outputValueCoder for the output should be an - // IterableCoder of the inputValueCoder. This is a property - // of the backend "CollectionToSingleton" step. - Coder outputValueCoder = IterableCoder.of(inputValueCoder); - addOutput(name, outputValue, outputValueCoder); - } - - /** - * Adds an output with the given name to the previously added - * Dataflow step, producing the specified output {@code PValue} - * with the given {@code Coder} (if not {@code null}). - */ - private void addOutput(String name, PValue value, Coder valueCoder) { - registerOutputName(value, name); - - Map properties = getProperties(); - @Nullable List> outputInfoList = null; - try { - // TODO: This should be done via a Structs accessor. - outputInfoList = (List>) properties.get(PropertyNames.OUTPUT_INFO); - } catch (Exception e) { - throw new RuntimeException("Inconsistent dataflow pipeline translation", e); - } - if (outputInfoList == null) { - outputInfoList = new ArrayList<>(); - // TODO: This should be done via a Structs accessor. - properties.put(PropertyNames.OUTPUT_INFO, outputInfoList); - } - - Map outputInfo = new HashMap<>(); - addString(outputInfo, PropertyNames.OUTPUT_NAME, name); - addString(outputInfo, PropertyNames.USER_NAME, value.getName()); - if (value instanceof PCollection - && runner.doesPCollectionRequireIndexedFormat((PCollection) value)) { - addBoolean(outputInfo, PropertyNames.USE_INDEXED_FORMAT, true); - } - if (valueCoder != null) { - // Verify that encoding can be decoded, in order to catch serialization - // failures as early as possible. - CloudObject encoding = SerializableUtils.ensureSerializable(valueCoder); - addObject(outputInfo, PropertyNames.ENCODING, encoding); - outputCoders.put(value, valueCoder); - } - - outputInfoList.add(outputInfo); - } - - private void addDisplayData(String stepName, HasDisplayData hasDisplayData) { - DisplayData displayData = DisplayData.from(hasDisplayData); - List> list = MAPPER.convertValue(displayData, List.class); - addList(getProperties(), PropertyNames.DISPLAY_DATA, list); - } - - @Override - public OutputReference asOutputReference(PValue value) { - AppliedPTransform transform = - value.getProducingTransformInternal(); - String stepName = stepNames.get(transform); - if (stepName == null) { - throw new IllegalArgumentException(transform + " doesn't have a name specified"); - } - - String outputName = outputNames.get(value); - if (outputName == null) { - throw new IllegalArgumentException( - "output " + value + " doesn't have a name specified"); - } - - return new OutputReference(stepName, outputName); - } - - private Map getProperties() { - Map properties = currentStep.getProperties(); - if (properties == null) { - properties = new HashMap<>(); - currentStep.setProperties(properties); - } - return properties; - } - - /** - * Returns a fresh Dataflow step name. - */ - private String genStepName() { - return "s" + (stepNames.size() + 1); - } - - /** - * Records the name of the given output PValue, - * within its producing transform. - */ - private void registerOutputName(POutput value, String name) { - if (outputNames.put(value, name) != null) { - throw new IllegalArgumentException( - "output " + value + " already has a name specified"); - } - } - } - - ///////////////////////////////////////////////////////////////////////////// - - @Override - public String toString() { - return "DataflowPipelineTranslator#" + hashCode(); - } - - - /////////////////////////////////////////////////////////////////////////// - - static { - registerTransformTranslator( - View.CreatePCollectionView.class, - new TransformTranslator() { - @Override - public void translate( - View.CreatePCollectionView transform, - TranslationContext context) { - translateTyped(transform, context); - } - - private void translateTyped( - View.CreatePCollectionView transform, - TranslationContext context) { - context.addStep(transform, "CollectionToSingleton"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - context.addCollectionToSingletonOutput( - PropertyNames.OUTPUT, - context.getInput(transform), - context.getOutput(transform)); - } - }); - - DataflowPipelineTranslator.registerTransformTranslator( - Combine.GroupedValues.class, - new DataflowPipelineTranslator.TransformTranslator() { - @Override - public void translate( - Combine.GroupedValues transform, - DataflowPipelineTranslator.TranslationContext context) { - translateHelper(transform, context); - } - - private void translateHelper( - final Combine.GroupedValues transform, - DataflowPipelineTranslator.TranslationContext context) { - context.addStep(transform, "CombineValues"); - translateInputs(context.getInput(transform), transform.getSideInputs(), context); - - AppliedCombineFn fn = - transform.getAppliedFn( - context.getInput(transform).getPipeline().getCoderRegistry(), - context.getInput(transform).getCoder(), - context.getInput(transform).getWindowingStrategy()); - - context.addEncodingInput(fn.getAccumulatorCoder()); - context.addInput( - PropertyNames.SERIALIZED_FN, - byteArrayToJsonString(serializeToByteArray(fn))); - context.addOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - }); - - registerTransformTranslator( - Create.Values.class, - new TransformTranslator() { - @Override - public void translate( - Create.Values transform, - TranslationContext context) { - createHelper(transform, context); - } - - private void createHelper( - Create.Values transform, - TranslationContext context) { - context.addStep(transform, "CreateCollection"); - - Coder coder = context.getOutput(transform).getCoder(); - List elements = new LinkedList<>(); - for (T elem : transform.getElements()) { - byte[] encodedBytes; - try { - encodedBytes = encodeToByteArray(coder, elem); - } catch (CoderException exn) { - // TODO: Put in better element printing: - // truncate if too long. - throw new IllegalArgumentException( - "Unable to encode element '" + elem + "' of transform '" + transform - + "' using coder '" + coder + "'.", - exn); - } - String encodedJson = byteArrayToJsonString(encodedBytes); - assert Arrays.equals(encodedBytes, - jsonStringToByteArray(encodedJson)); - elements.add(CloudObject.forString(encodedJson)); - } - context.addInput(PropertyNames.ELEMENT, elements); - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - }); - - registerTransformTranslator( - Flatten.FlattenPCollectionList.class, - new TransformTranslator() { - @Override - public void translate( - Flatten.FlattenPCollectionList transform, - TranslationContext context) { - flattenHelper(transform, context); - } - - private void flattenHelper( - Flatten.FlattenPCollectionList transform, - TranslationContext context) { - context.addStep(transform, "Flatten"); - - List inputs = new LinkedList<>(); - for (PCollection input : context.getInput(transform).getAll()) { - inputs.add(context.asOutputReference(input)); - } - context.addInput(PropertyNames.INPUTS, inputs); - context.addOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - }); - - registerTransformTranslator( - GroupByKeyAndSortValuesOnly.class, - new TransformTranslator() { - @Override - public void translate( - GroupByKeyAndSortValuesOnly transform, - TranslationContext context) { - groupByKeyAndSortValuesHelper(transform, context); - } - - private void groupByKeyAndSortValuesHelper( - GroupByKeyAndSortValuesOnly transform, - TranslationContext context) { - context.addStep(transform, "GroupByKey"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - context.addOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - context.addInput(PropertyNames.SORT_VALUES, true); - - // TODO: Add support for combiner lifting once the need arises. - context.addInput( - PropertyNames.DISALLOW_COMBINER_LIFTING, true); - } - }); - - registerTransformTranslator( - GroupByKey.class, - new TransformTranslator() { - @Override - public void translate( - GroupByKey transform, - TranslationContext context) { - groupByKeyHelper(transform, context); - } - - private void groupByKeyHelper( - GroupByKey transform, - TranslationContext context) { - context.addStep(transform, "GroupByKey"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - context.addOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - - WindowingStrategy windowingStrategy = - context.getInput(transform).getWindowingStrategy(); - boolean isStreaming = - context.getPipelineOptions().as(StreamingOptions.class).isStreaming(); - boolean disallowCombinerLifting = - !windowingStrategy.getWindowFn().isNonMerging() - || (isStreaming && !transform.fewKeys()) - // TODO: Allow combiner lifting on the non-default trigger, as appropriate. - || !(windowingStrategy.getTrigger().getSpec() instanceof DefaultTrigger); - context.addInput( - PropertyNames.DISALLOW_COMBINER_LIFTING, disallowCombinerLifting); - context.addInput( - PropertyNames.SERIALIZED_FN, - byteArrayToJsonString(serializeToByteArray(windowingStrategy))); - context.addInput( - PropertyNames.IS_MERGING_WINDOW_FN, - !windowingStrategy.getWindowFn().isNonMerging()); - } - }); - - registerTransformTranslator( - ParDo.BoundMulti.class, - new TransformTranslator() { - @Override - public void translate( - ParDo.BoundMulti transform, - TranslationContext context) { - translateMultiHelper(transform, context); - } - - private void translateMultiHelper( - ParDo.BoundMulti transform, - TranslationContext context) { - context.addStep(transform, "ParallelDo"); - translateInputs(context.getInput(transform), transform.getSideInputs(), context); - translateFn(transform.getFn(), context.getInput(transform).getWindowingStrategy(), - transform.getSideInputs(), context.getInput(transform).getCoder(), context); - translateOutputs(context.getOutput(transform), context); - } - }); - - registerTransformTranslator( - ParDo.Bound.class, - new TransformTranslator() { - @Override - public void translate( - ParDo.Bound transform, - TranslationContext context) { - translateSingleHelper(transform, context); - } - - private void translateSingleHelper( - ParDo.Bound transform, - TranslationContext context) { - context.addStep(transform, "ParallelDo"); - translateInputs(context.getInput(transform), transform.getSideInputs(), context); - translateFn( - transform.getFn(), - context.getInput(transform).getWindowingStrategy(), - transform.getSideInputs(), context.getInput(transform).getCoder(), context); - context.addOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } - }); - - registerTransformTranslator( - Window.Bound.class, - new DataflowPipelineTranslator.TransformTranslator() { - @Override - public void translate( - Window.Bound transform, TranslationContext context) { - translateHelper(transform, context); - } - - private void translateHelper( - Window.Bound transform, TranslationContext context) { - context.addStep(transform, "Bucket"); - context.addInput(PropertyNames.PARALLEL_INPUT, context.getInput(transform)); - context.addOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - - WindowingStrategy strategy = context.getOutput(transform).getWindowingStrategy(); - byte[] serializedBytes = serializeToByteArray(strategy); - String serializedJson = byteArrayToJsonString(serializedBytes); - assert Arrays.equals(serializedBytes, - jsonStringToByteArray(serializedJson)); - context.addInput(PropertyNames.SERIALIZED_FN, serializedJson); - } - }); - - /////////////////////////////////////////////////////////////////////////// - // IO Translation. - - registerTransformTranslator(Read.Bounded.class, new ReadTranslator()); - } - - private static void translateInputs( - PCollection input, - List> sideInputs, - TranslationContext context) { - context.addInput(PropertyNames.PARALLEL_INPUT, input); - translateSideInputs(sideInputs, context); - } - - // Used for ParDo - private static void translateSideInputs( - List> sideInputs, - TranslationContext context) { - Map nonParInputs = new HashMap<>(); - - for (PCollectionView view : sideInputs) { - nonParInputs.put( - view.getTagInternal().getId(), - context.asOutputReference(view)); - } - - context.addInput(PropertyNames.NON_PARALLEL_INPUTS, nonParInputs); - } - - private static void translateFn( - DoFn fn, - WindowingStrategy windowingStrategy, - Iterable> sideInputs, - Coder inputCoder, - TranslationContext context) { - context.addInput(PropertyNames.USER_FN, fn.getClass().getName()); - context.addInput( - PropertyNames.SERIALIZED_FN, - byteArrayToJsonString(serializeToByteArray( - new DoFnInfo(fn, windowingStrategy, sideInputs, inputCoder)))); - } - - private static void translateOutputs( - PCollectionTuple outputs, - TranslationContext context) { - for (Map.Entry, PCollection> entry - : outputs.getAll().entrySet()) { - TupleTag tag = entry.getKey(); - PCollection output = entry.getValue(); - context.addOutput(tag.getId(), output); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowServiceException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowServiceException.java deleted file mode 100644 index 6e8301b13a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowServiceException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import javax.annotation.Nullable; - -/** - * Signals there was an error retrieving information about a job from the Cloud Dataflow Service. - */ -public class DataflowServiceException extends DataflowJobException { - DataflowServiceException(DataflowPipelineJob job, String message) { - this(job, message, null); - } - - DataflowServiceException(DataflowPipelineJob job, String message, @Nullable Throwable cause) { - super(job, message, cause); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipeline.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipeline.java deleted file mode 100644 index 5217a90813..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipeline.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; - -/** - * A {@link DirectPipeline} is a {@link Pipeline} that returns - * {@link DirectPipelineRunner.EvaluationResults} when it is - * {@link com.google.cloud.dataflow.sdk.Pipeline#run()}. - */ -public class DirectPipeline extends Pipeline { - - /** - * Creates and returns a new DirectPipeline instance for tests. - */ - public static DirectPipeline createForTest() { - DirectPipelineRunner runner = DirectPipelineRunner.createForTest(); - return new DirectPipeline(runner, runner.getPipelineOptions()); - } - - private DirectPipeline(DirectPipelineRunner runner, DirectPipelineOptions options) { - super(runner, options); - } - - @Override - public DirectPipelineRunner.EvaluationResults run() { - return (DirectPipelineRunner.EvaluationResults) super.run(); - } - - @Override - public DirectPipelineRunner getRunner() { - return (DirectPipelineRunner) super.getRunner(); - } - - @Override - public String toString() { - return "DirectPipeline#" + hashCode(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrar.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrar.java deleted file mode 100644 index f2dd40cbdb..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrar.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.auto.service.AutoService; -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; -import com.google.common.collect.ImmutableList; - -/** - * Contains the {@link PipelineOptionsRegistrar} and {@link PipelineRunnerRegistrar} for - * the {@link DirectPipeline}. - */ -public class DirectPipelineRegistrar { - private DirectPipelineRegistrar() { } - - /** - * Register the {@link DirectPipelineRunner}. - */ - @AutoService(PipelineRunnerRegistrar.class) - public static class Runner implements PipelineRunnerRegistrar { - @Override - public Iterable>> getPipelineRunners() { - return ImmutableList.>>of(DirectPipelineRunner.class); - } - } - - /** - * Register the {@link DirectPipelineOptions}. - */ - @AutoService(PipelineOptionsRegistrar.class) - public static class Options implements PipelineOptionsRegistrar { - @Override - public Iterable> getPipelineOptions() { - return ImmutableList.>of(DirectPipelineOptions.class); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java deleted file mode 100644 index 67e23c7cbd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java +++ /dev/null @@ -1,1155 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.FileBasedSink; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Partition; -import com.google.cloud.dataflow.sdk.transforms.Partition.PartitionFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.MapAggregatorValues; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunner; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunners; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.cloud.dataflow.sdk.values.TypedPValue; -import com.google.common.base.Function; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -/** - * Executes the operations in the pipeline directly, in this process, without - * any optimization. Useful for small local execution and tests. - * - *

              Throws an exception from {@link #run} if execution fails. - * - *

              Permissions

              - * When reading from a Dataflow source or writing to a Dataflow sink using - * {@code DirectPipelineRunner}, the Cloud Platform account that you configured with the - * gcloud executable will need access to the - * corresponding source/sink. - * - *

              Please see Google Cloud - * Dataflow Security and Permissions for more details. - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class DirectPipelineRunner - extends PipelineRunner { - private static final Logger LOG = LoggerFactory.getLogger(DirectPipelineRunner.class); - - /** - * A source of random data, which can be seeded if determinism is desired. - */ - private Random rand; - - /** - * A map from PTransform class to the corresponding - * TransformEvaluator to use to evaluate that transform. - * - *

              A static map that contains system-wide defaults. - */ - private static Map defaultTransformEvaluators = - new HashMap<>(); - - /** - * A map from PTransform class to the corresponding - * TransformEvaluator to use to evaluate that transform. - * - *

              An instance map that contains bindings for this DirectPipelineRunner. - * Bindings in this map override those in the default map. - */ - private Map localTransformEvaluators = - new HashMap<>(); - - /** - * Records that instances of the specified PTransform class - * should be evaluated by default by the corresponding - * TransformEvaluator. - */ - public static > - void registerDefaultTransformEvaluator( - Class transformClass, - TransformEvaluator transformEvaluator) { - if (defaultTransformEvaluators.put(transformClass, transformEvaluator) - != null) { - throw new IllegalArgumentException( - "defining multiple evaluators for " + transformClass); - } - } - - /** - * Records that instances of the specified PTransform class - * should be evaluated by the corresponding TransformEvaluator. - * Overrides any bindings specified by - * {@link #registerDefaultTransformEvaluator}. - */ - public > - void registerTransformEvaluator( - Class transformClass, - TransformEvaluator transformEvaluator) { - if (localTransformEvaluators.put(transformClass, transformEvaluator) - != null) { - throw new IllegalArgumentException( - "defining multiple evaluators for " + transformClass); - } - } - - /** - * Returns the TransformEvaluator to use for instances of the - * specified PTransform class, or null if none registered. - */ - public > - TransformEvaluator getTransformEvaluator(Class transformClass) { - TransformEvaluator transformEvaluator = - localTransformEvaluators.get(transformClass); - if (transformEvaluator == null) { - transformEvaluator = defaultTransformEvaluators.get(transformClass); - } - return transformEvaluator; - } - - /** - * Constructs a DirectPipelineRunner from the given options. - */ - public static DirectPipelineRunner fromOptions(PipelineOptions options) { - DirectPipelineOptions directOptions = - PipelineOptionsValidator.validate(DirectPipelineOptions.class, options); - LOG.debug("Creating DirectPipelineRunner"); - return new DirectPipelineRunner(directOptions); - } - - /** - * Constructs a runner with default properties for testing. - * - * @return The newly created runner. - */ - public static DirectPipelineRunner createForTest() { - DirectPipelineOptions options = PipelineOptionsFactory.as(DirectPipelineOptions.class); - options.setStableUniqueNames(CheckEnabled.ERROR); - options.setGcpCredential(new TestCredential()); - return new DirectPipelineRunner(options); - } - - /** - * Enable runtime testing to verify that all functions and {@link Coder} - * instances can be serialized. - * - *

              Enabled by default. - * - *

              This method modifies the {@code DirectPipelineRunner} instance and - * returns itself. - */ - public DirectPipelineRunner withSerializabilityTesting(boolean enable) { - this.testSerializability = enable; - return this; - } - - /** - * Enable runtime testing to verify that all values can be encoded. - * - *

              Enabled by default. - * - *

              This method modifies the {@code DirectPipelineRunner} instance and - * returns itself. - */ - public DirectPipelineRunner withEncodabilityTesting(boolean enable) { - this.testEncodability = enable; - return this; - } - - /** - * Enable runtime testing to verify that functions do not depend on order - * of the elements. - * - *

              This is accomplished by randomizing the order of elements. - * - *

              Enabled by default. - * - *

              This method modifies the {@code DirectPipelineRunner} instance and - * returns itself. - */ - public DirectPipelineRunner withUnorderednessTesting(boolean enable) { - this.testUnorderedness = enable; - return this; - } - - @Override - public OutputT apply( - PTransform transform, InputT input) { - if (transform instanceof Combine.GroupedValues) { - return (OutputT) applyTestCombine((Combine.GroupedValues) transform, (PCollection) input); - } else if (transform instanceof TextIO.Write.Bound) { - return (OutputT) applyTextIOWrite((TextIO.Write.Bound) transform, (PCollection) input); - } else if (transform instanceof AvroIO.Write.Bound) { - return (OutputT) applyAvroIOWrite((AvroIO.Write.Bound) transform, (PCollection) input); - } else { - return super.apply(transform, input); - } - } - - private PCollection> applyTestCombine( - Combine.GroupedValues transform, - PCollection>> input) { - - PCollection> output = input - .apply(ParDo.of(TestCombineDoFn.create(transform, input, testSerializability, rand)) - .withSideInputs(transform.getSideInputs())); - - try { - output.setCoder(transform.getDefaultOutputCoder(input)); - } catch (CannotProvideCoderException exc) { - // let coder inference occur later, if it can - } - return output; - } - - private static class ElementProcessingOrderPartitionFn implements PartitionFn { - private int elementNumber; - @Override - public int partitionFor(T elem, int numPartitions) { - return elementNumber++ % numPartitions; - } - } - - /** - * Applies TextIO.Write honoring user requested sharding controls (i.e. withNumShards) - * by applying a partition function based upon the number of shards the user requested. - */ - private static class DirectTextIOWrite extends PTransform, PDone> { - private final TextIO.Write.Bound transform; - - private DirectTextIOWrite(TextIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - checkState(transform.getNumShards() > 1, - "DirectTextIOWrite is expected to only be used when sharding controls are required."); - - // Evenly distribute all the elements across the partitions. - PCollectionList partitionedElements = - input.apply(Partition.of(transform.getNumShards(), - new ElementProcessingOrderPartitionFn())); - - // For each input PCollection partition, create a write transform that represents - // one of the specific shards. - for (int i = 0; i < transform.getNumShards(); ++i) { - /* - * This logic mirrors the file naming strategy within - * {@link FileBasedSink#generateDestinationFilenames()} - */ - String outputFilename = IOChannelUtils.constructName( - transform.getFilenamePrefix(), - transform.getShardNameTemplate(), - getFileExtension(transform.getFilenameSuffix()), - i, - transform.getNumShards()); - - String transformName = String.format("%s(Shard:%s)", transform.getName(), i); - partitionedElements.get(i).apply(transformName, - transform.withNumShards(1).withShardNameTemplate("").withSuffix("").to(outputFilename)); - } - return PDone.in(input.getPipeline()); - } - } - - /** - * Returns the file extension to be used. If the user did not request a file - * extension then this method returns the empty string. Otherwise this method - * adds a {@code "."} to the beginning of the users extension if one is not present. - * - *

              This is copied from {@link FileBasedSink} to not expose it. - */ - private static String getFileExtension(String usersExtension) { - if (usersExtension == null || usersExtension.isEmpty()) { - return ""; - } - if (usersExtension.startsWith(".")) { - return usersExtension; - } - return "." + usersExtension; - } - - /** - * Apply the override for TextIO.Write.Bound if the user requested sharding controls - * greater than one. - */ - private PDone applyTextIOWrite(TextIO.Write.Bound transform, PCollection input) { - if (transform.getNumShards() <= 1) { - // By default, the DirectPipelineRunner outputs to only 1 shard. Since the user never - // requested sharding controls greater than 1, we default to outputting to 1 file. - return super.apply(transform.withNumShards(1), input); - } - return input.apply(new DirectTextIOWrite<>(transform)); - } - - /** - * Applies AvroIO.Write honoring user requested sharding controls (i.e. withNumShards) - * by applying a partition function based upon the number of shards the user requested. - */ - private static class DirectAvroIOWrite extends PTransform, PDone> { - private final AvroIO.Write.Bound transform; - - private DirectAvroIOWrite(AvroIO.Write.Bound transform) { - this.transform = transform; - } - - @Override - public PDone apply(PCollection input) { - checkState(transform.getNumShards() > 1, - "DirectAvroIOWrite is expected to only be used when sharding controls are required."); - - // Evenly distribute all the elements across the partitions. - PCollectionList partitionedElements = - input.apply(Partition.of(transform.getNumShards(), - new ElementProcessingOrderPartitionFn())); - - // For each input PCollection partition, create a write transform that represents - // one of the specific shards. - for (int i = 0; i < transform.getNumShards(); ++i) { - /* - * This logic mirrors the file naming strategy within - * {@link FileBasedSink#generateDestinationFilenames()} - */ - String outputFilename = IOChannelUtils.constructName( - transform.getFilenamePrefix(), - transform.getShardNameTemplate(), - getFileExtension(transform.getFilenameSuffix()), - i, - transform.getNumShards()); - - String transformName = String.format("%s(Shard:%s)", transform.getName(), i); - partitionedElements.get(i).apply(transformName, - transform.withNumShards(1).withShardNameTemplate("").withSuffix("").to(outputFilename)); - } - return PDone.in(input.getPipeline()); - } - } - - /** - * Apply the override for AvroIO.Write.Bound if the user requested sharding controls - * greater than one. - */ - private PDone applyAvroIOWrite(AvroIO.Write.Bound transform, PCollection input) { - if (transform.getNumShards() <= 1) { - // By default, the DirectPipelineRunner outputs to only 1 shard. Since the user never - // requested sharding controls greater than 1, we default to outputting to 1 file. - return super.apply(transform.withNumShards(1), input); - } - return input.apply(new DirectAvroIOWrite<>(transform)); - } - - /** - * The implementation may split the {@link KeyedCombineFn} into ADD, MERGE and EXTRACT phases ( - * see {@code com.google.cloud.dataflow.sdk.runners.worker.CombineValuesFn}). In order to emulate - * this for the {@link DirectPipelineRunner} and provide an experience closer to the service, go - * through heavy serializability checks for the equivalent of the results of the ADD phase, but - * after the {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey} shuffle, and the MERGE - * phase. Doing these checks ensure that not only is the accumulator coder serializable, but - * the accumulator coder can actually serialize the data in question. - */ - public static class TestCombineDoFn - extends DoFn>, KV> { - private final PerKeyCombineFnRunner fnRunner; - private final Coder accumCoder; - private final boolean testSerializability; - private final Random rand; - - public static TestCombineDoFn create( - Combine.GroupedValues transform, - PCollection>> input, - boolean testSerializability, - Random rand) { - - AppliedCombineFn fn = transform.getAppliedFn( - input.getPipeline().getCoderRegistry(), input.getCoder(), input.getWindowingStrategy()); - - return new TestCombineDoFn( - PerKeyCombineFnRunners.create(fn.getFn()), - fn.getAccumulatorCoder(), - testSerializability, - rand); - } - - public TestCombineDoFn( - PerKeyCombineFnRunner fnRunner, - Coder accumCoder, - boolean testSerializability, - Random rand) { - this.fnRunner = fnRunner; - this.accumCoder = accumCoder; - this.testSerializability = testSerializability; - this.rand = rand; - - // Check that this does not crash, specifically to catch anonymous CustomCoder subclasses. - this.accumCoder.getEncodingId(); - } - - @Override - public void processElement(ProcessContext c) throws Exception { - K key = c.element().getKey(); - Iterable values = c.element().getValue(); - List groupedPostShuffle = - ensureSerializableByCoder(ListCoder.of(accumCoder), - addInputsRandomly(fnRunner, key, values, rand, c), - "After addInputs of KeyedCombineFn " + fnRunner.fn().toString()); - AccumT merged = - ensureSerializableByCoder(accumCoder, - fnRunner.mergeAccumulators(key, groupedPostShuffle, c), - "After mergeAccumulators of KeyedCombineFn " + fnRunner.fn().toString()); - // Note: The serializability of KV is ensured by the - // runner itself, since it's a transform output. - c.output(KV.of(key, fnRunner.extractOutput(key, merged, c))); - } - - /** - * Create a random list of accumulators from the given list of values. - * - *

              Visible for testing purposes only. - */ - public static List addInputsRandomly( - PerKeyCombineFnRunner fnRunner, - K key, - Iterable values, - Random random, - DoFn.ProcessContext c) { - List out = new ArrayList(); - int i = 0; - AccumT accumulator = fnRunner.createAccumulator(key, c); - boolean hasInput = false; - - for (InputT value : values) { - accumulator = fnRunner.addInput(key, accumulator, value, c); - hasInput = true; - - // For each index i, flip a 1/2^i weighted coin for whether to - // create a new accumulator after index i is added, i.e. [0] - // is guaranteed, [1] is an even 1/2, [2] is 1/4, etc. The - // goal is to partition the inputs into accumulators, and make - // the accumulators potentially lumpy. Also compact about half - // of the accumulators. - if (i == 0 || random.nextInt(1 << Math.min(i, 30)) == 0) { - if (i % 2 == 0) { - accumulator = fnRunner.compact(key, accumulator, c); - } - out.add(accumulator); - accumulator = fnRunner.createAccumulator(key, c); - hasInput = false; - } - i++; - } - if (hasInput) { - out.add(accumulator); - } - - Collections.shuffle(out, random); - return out; - } - - public T ensureSerializableByCoder( - Coder coder, T value, String errorContext) { - if (testSerializability) { - return SerializableUtils.ensureSerializableByCoder( - coder, value, errorContext); - } - return value; - } - } - - @Override - public EvaluationResults run(Pipeline pipeline) { - LOG.info("Executing pipeline using the DirectPipelineRunner."); - - Evaluator evaluator = new Evaluator(rand); - evaluator.run(pipeline); - - // Log all counter values for debugging purposes. - for (Counter counter : evaluator.getCounters()) { - LOG.info("Final aggregator value: {}", counter); - } - - LOG.info("Pipeline execution complete."); - - return evaluator; - } - - /** - * An evaluator of a PTransform. - */ - public interface TransformEvaluator { - void evaluate(TransformT transform, - EvaluationContext context); - } - - /** - * The interface provided to registered callbacks for interacting - * with the {@code DirectPipelineRunner}, including reading and writing the - * values of {@link PCollection}s and {@link PCollectionView}s. - */ - public interface EvaluationResults extends PipelineResult { - /** - * Retrieves the value of the given PCollection. - * Throws an exception if the PCollection's value hasn't already been set. - */ - List getPCollection(PCollection pc); - - /** - * Retrieves the windowed value of the given PCollection. - * Throws an exception if the PCollection's value hasn't already been set. - */ - List> getPCollectionWindowedValues(PCollection pc); - - /** - * Retrieves the values of each PCollection in the given - * PCollectionList. Throws an exception if the PCollectionList's - * value hasn't already been set. - */ - List> getPCollectionList(PCollectionList pcs); - - /** - * Retrieves the values indicated by the given {@link PCollectionView}. - * Note that within the {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context} - * implementation a {@link PCollectionView} should convert from this representation to a - * suitable side input value. - */ - Iterable> getPCollectionView(PCollectionView view); - } - - /** - * An immutable (value, timestamp) pair, along with other metadata necessary - * for the implementation of {@code DirectPipelineRunner}. - */ - public static class ValueWithMetadata { - /** - * Returns a new {@code ValueWithMetadata} with the {@code WindowedValue}. - * Key is null. - */ - public static ValueWithMetadata of(WindowedValue windowedValue) { - return new ValueWithMetadata<>(windowedValue, null); - } - - /** - * Returns a new {@code ValueWithMetadata} with the implicit key associated - * with this value set. The key is the last key grouped by in the chain of - * productions that produced this element. - * These keys are used internally by {@link DirectPipelineRunner} for keeping - * persisted state separate across keys. - */ - public ValueWithMetadata withKey(Object key) { - return new ValueWithMetadata<>(windowedValue, key); - } - - /** - * Returns a new {@code ValueWithMetadata} that is a copy of this one, but with - * a different value. - */ - public ValueWithMetadata withValue(T value) { - return new ValueWithMetadata(windowedValue.withValue(value), getKey()); - } - - /** - * Returns the {@code WindowedValue} associated with this element. - */ - public WindowedValue getWindowedValue() { - return windowedValue; - } - - /** - * Returns the value associated with this element. - * - * @see #withValue - */ - public V getValue() { - return windowedValue.getValue(); - } - - /** - * Returns the timestamp associated with this element. - */ - public Instant getTimestamp() { - return windowedValue.getTimestamp(); - } - - /** - * Returns the collection of windows this element has been placed into. May - * be null if the {@code PCollection} this element is in has not yet been - * windowed. - * - * @see #getWindows() - */ - public Collection getWindows() { - return windowedValue.getWindows(); - } - - - /** - * Returns the key associated with this element. May be null if the - * {@code PCollection} this element is in is not keyed. - * - * @see #withKey - */ - public Object getKey() { - return key; - } - - //////////////////////////////////////////////////////////////////////////// - - private final Object key; - private final WindowedValue windowedValue; - - private ValueWithMetadata(WindowedValue windowedValue, - Object key) { - this.windowedValue = windowedValue; - this.key = key; - } - } - - /** - * The interface provided to registered callbacks for interacting - * with the {@code DirectPipelineRunner}, including reading and writing the - * values of {@link PCollection}s and {@link PCollectionView}s. - */ - public interface EvaluationContext extends EvaluationResults { - /** - * Returns the configured pipeline options. - */ - DirectPipelineOptions getPipelineOptions(); - - /** - * Returns the input of the currently being processed transform. - */ - InputT getInput(PTransform transform); - - /** - * Returns the output of the currently being processed transform. - */ - OutputT getOutput(PTransform transform); - - /** - * Sets the value of the given PCollection, where each element also has a timestamp - * and collection of windows. - * Throws an exception if the PCollection's value has already been set. - */ - void setPCollectionValuesWithMetadata( - PCollection pc, List> elements); - - /** - * Sets the value of the given PCollection, where each element also has a timestamp - * and collection of windows. - * Throws an exception if the PCollection's value has already been set. - */ - void setPCollectionWindowedValue(PCollection pc, List> elements); - - /** - * Shorthand for setting the value of a PCollection where the elements do not have - * timestamps or windows. - * Throws an exception if the PCollection's value has already been set. - */ - void setPCollection(PCollection pc, List elements); - - /** - * Retrieves the value of the given PCollection, along with element metadata - * such as timestamps and windows. - * Throws an exception if the PCollection's value hasn't already been set. - */ - List> getPCollectionValuesWithMetadata(PCollection pc); - - /** - * Sets the value associated with the given {@link PCollectionView}. - * Throws an exception if the {@link PCollectionView}'s value has already been set. - */ - void setPCollectionView( - PCollectionView pc, - Iterable> value); - - /** - * Ensures that the element is encodable and decodable using the - * TypePValue's coder, by encoding it and decoding it, and - * returning the result. - */ - T ensureElementEncodable(TypedPValue pvalue, T element); - - /** - * If the evaluation context is testing unorderedness, - * randomly permutes the order of the elements, in a - * copy if !inPlaceAllowed, and returns the permuted list, - * otherwise returns the argument unchanged. - */ - List randomizeIfUnordered(List elements, - boolean inPlaceAllowed); - - /** - * If the evaluation context is testing serializability, ensures - * that the argument function is serializable and deserializable - * by encoding it and then decoding it, and returning the result. - * Otherwise returns the argument unchanged. - */ - FunctionT ensureSerializable(FunctionT fn); - - /** - * If the evaluation context is testing serializability, ensures - * that the argument Coder is serializable and deserializable - * by encoding it and then decoding it, and returning the result. - * Otherwise returns the argument unchanged. - */ - Coder ensureCoderSerializable(Coder coder); - - /** - * If the evaluation context is testing serializability, ensures - * that the given data is serializable and deserializable with the - * given Coder by encoding it and then decoding it, and returning - * the result. Otherwise returns the argument unchanged. - * - *

              Error context is prefixed to any thrown exceptions. - */ - T ensureSerializableByCoder(Coder coder, - T data, String errorContext); - - /** - * Returns a mutator, which can be used to add additional counters to - * this EvaluationContext. - */ - CounterSet.AddCounterMutator getAddCounterMutator(); - - /** - * Gets the step name for this transform. - */ - String getStepName(PTransform transform); - } - - - ///////////////////////////////////////////////////////////////////////////// - - class Evaluator implements PipelineVisitor, EvaluationContext { - /** - * A map from PTransform to the step name of that transform. This is the internal name for the - * transform (e.g. "s2"). - */ - private final Map, String> stepNames = new HashMap<>(); - private final Map store = new HashMap<>(); - private final CounterSet counters = new CounterSet(); - private AppliedPTransform currentTransform; - - private Map, Collection>> aggregatorSteps = null; - - /** - * A map from PTransform to the full name of that transform. This is the user name of the - * transform (e.g. "RemoveDuplicates/Combine/GroupByKey"). - */ - private final Map, String> fullNames = new HashMap<>(); - - private Random rand; - - public Evaluator() { - this(new Random()); - } - - public Evaluator(Random rand) { - this.rand = rand; - } - - public void run(Pipeline pipeline) { - pipeline.traverseTopologically(this); - aggregatorSteps = new AggregatorPipelineExtractor(pipeline).getAggregatorSteps(); - } - - @Override - public DirectPipelineOptions getPipelineOptions() { - return options; - } - - @Override - public InputT getInput(PTransform transform) { - checkArgument(currentTransform != null && currentTransform.getTransform() == transform, - "can only be called with current transform"); - return (InputT) currentTransform.getInput(); - } - - @Override - public OutputT getOutput(PTransform transform) { - checkArgument(currentTransform != null && currentTransform.getTransform() == transform, - "can only be called with current transform"); - return (OutputT) currentTransform.getOutput(); - } - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - } - - @Override - public void visitTransform(TransformTreeNode node) { - PTransform transform = node.getTransform(); - fullNames.put(transform, node.getFullName()); - TransformEvaluator evaluator = - getTransformEvaluator(transform.getClass()); - if (evaluator == null) { - throw new IllegalStateException( - "no evaluator registered for " + transform); - } - LOG.debug("Evaluating {}", transform); - currentTransform = AppliedPTransform.of( - node.getFullName(), node.getInput(), node.getOutput(), (PTransform) transform); - evaluator.evaluate(transform, this); - currentTransform = null; - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - LOG.debug("Checking evaluation of {}", value); - if (value.getProducingTransformInternal() == null) { - throw new RuntimeException( - "internal error: expecting a PValue to have a producingTransform"); - } - if (!producer.isCompositeNode()) { - // Verify that primitive transform outputs are already computed. - getPValue(value); - } - } - - /** - * Sets the value of the given PValue. - * Throws an exception if the PValue's value has already been set. - */ - void setPValue(PValue pvalue, Object contents) { - if (store.containsKey(pvalue)) { - throw new IllegalStateException( - "internal error: setting the value of " + pvalue - + " more than once"); - } - store.put(pvalue, contents); - } - - /** - * Retrieves the value of the given PValue. - * Throws an exception if the PValue's value hasn't already been set. - */ - Object getPValue(PValue pvalue) { - if (!store.containsKey(pvalue)) { - throw new IllegalStateException( - "internal error: getting the value of " + pvalue - + " before it has been computed"); - } - return store.get(pvalue); - } - - /** - * Convert a list of T to a list of {@code ValueWithMetadata}, with a timestamp of 0 - * and null windows. - */ - List> toValueWithMetadata(List values) { - List> result = new ArrayList<>(values.size()); - for (T value : values) { - result.add(ValueWithMetadata.of(WindowedValue.valueInGlobalWindow(value))); - } - return result; - } - - /** - * Convert a list of {@code WindowedValue} to a list of {@code ValueWithMetadata}. - */ - List> toValueWithMetadataFromWindowedValue( - List> values) { - List> result = new ArrayList<>(values.size()); - for (WindowedValue value : values) { - result.add(ValueWithMetadata.of(value)); - } - return result; - } - - @Override - public void setPCollection(PCollection pc, List elements) { - setPCollectionValuesWithMetadata(pc, toValueWithMetadata(elements)); - } - - @Override - public void setPCollectionWindowedValue( - PCollection pc, List> elements) { - setPCollectionValuesWithMetadata(pc, toValueWithMetadataFromWindowedValue(elements)); - } - - @Override - public void setPCollectionValuesWithMetadata( - PCollection pc, List> elements) { - LOG.debug("Setting {} = {}", pc, elements); - List> encoded = ensurePCollectionEncodable(pc, elements); - setPValue(pc, encoded); - } - - @Override - public void setPCollectionView( - PCollectionView view, - Iterable> value) { - LOG.debug("Setting {} = {}", view, value); - setPValue(view, value); - } - - /** - * Retrieves the value of the given {@link PCollection}. - * Throws an exception if the {@link PCollection}'s value hasn't already been set. - */ - @Override - public List getPCollection(PCollection pc) { - List result = new ArrayList<>(); - for (ValueWithMetadata elem : getPCollectionValuesWithMetadata(pc)) { - result.add(elem.getValue()); - } - return result; - } - - @Override - public List> getPCollectionWindowedValues(PCollection pc) { - return Lists.transform( - getPCollectionValuesWithMetadata(pc), - new Function, WindowedValue>() { - @Override - public WindowedValue apply(ValueWithMetadata input) { - return input.getWindowedValue(); - }}); - } - - @Override - public List> getPCollectionValuesWithMetadata(PCollection pc) { - List> elements = (List>) getPValue(pc); - elements = randomizeIfUnordered(elements, false /* not inPlaceAllowed */); - LOG.debug("Getting {} = {}", pc, elements); - return elements; - } - - @Override - public List> getPCollectionList(PCollectionList pcs) { - List> elementsList = new ArrayList<>(); - for (PCollection pc : pcs.getAll()) { - elementsList.add(getPCollection(pc)); - } - return elementsList; - } - - /** - * Retrieves the value indicated by the given {@link PCollectionView}. - * Note that within the {@link DoFnContext} a {@link PCollectionView} - * converts from this representation to a suitable side input value. - */ - @Override - public Iterable> getPCollectionView(PCollectionView view) { - Iterable> value = (Iterable>) getPValue(view); - LOG.debug("Getting {} = {}", view, value); - return value; - } - - /** - * If {@code testEncodability}, ensures that the {@link PCollection}'s coder and elements are - * encodable and decodable by encoding them and decoding them, and returning the result. - * Otherwise returns the argument elements. - */ - List> ensurePCollectionEncodable( - PCollection pc, List> elements) { - ensureCoderSerializable(pc.getCoder()); - if (!testEncodability) { - return elements; - } - List> elementsCopy = new ArrayList<>(elements.size()); - for (ValueWithMetadata element : elements) { - elementsCopy.add( - element.withValue(ensureElementEncodable(pc, element.getValue()))); - } - return elementsCopy; - } - - @Override - public T ensureElementEncodable(TypedPValue pvalue, T element) { - return ensureSerializableByCoder( - pvalue.getCoder(), element, "Within " + pvalue.toString()); - } - - @Override - public List randomizeIfUnordered(List elements, - boolean inPlaceAllowed) { - if (!testUnorderedness) { - return elements; - } - List elementsCopy = new ArrayList<>(elements); - Collections.shuffle(elementsCopy, rand); - return elementsCopy; - } - - @Override - public FunctionT ensureSerializable(FunctionT fn) { - if (!testSerializability) { - return fn; - } - return SerializableUtils.ensureSerializable(fn); - } - - @Override - public Coder ensureCoderSerializable(Coder coder) { - if (testSerializability) { - SerializableUtils.ensureSerializable(coder); - } - return coder; - } - - @Override - public T ensureSerializableByCoder( - Coder coder, T value, String errorContext) { - if (testSerializability) { - return SerializableUtils.ensureSerializableByCoder( - coder, value, errorContext); - } - return value; - } - - @Override - public CounterSet.AddCounterMutator getAddCounterMutator() { - return counters.getAddCounterMutator(); - } - - @Override - public String getStepName(PTransform transform) { - String stepName = stepNames.get(transform); - if (stepName == null) { - stepName = "s" + (stepNames.size() + 1); - stepNames.put(transform, stepName); - } - return stepName; - } - - /** - * Returns the CounterSet generated during evaluation, which includes - * user-defined Aggregators and may include system-defined counters. - */ - public CounterSet getCounters() { - return counters; - } - - /** - * Returns JobState.DONE in all situations. The Evaluator is not returned - * until the pipeline has been traversed, so it will either be returned - * after a successful run or the run call will terminate abnormally. - */ - @Override - public State getState() { - return State.DONE; - } - - @Override - public AggregatorValues getAggregatorValues(Aggregator aggregator) { - Map stepValues = new HashMap<>(); - for (PTransform step : aggregatorSteps.get(aggregator)) { - String stepName = String.format("user-%s-%s", stepNames.get(step), aggregator.getName()); - String fullName = fullNames.get(step); - Counter counter = counters.getExistingCounter(stepName); - if (counter == null) { - throw new IllegalArgumentException( - "Aggregator " + aggregator + " is not used in this pipeline"); - } - stepValues.put(fullName, (T) counter.getAggregate()); - } - return new MapAggregatorValues<>(stepValues); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - private final DirectPipelineOptions options; - private boolean testSerializability; - private boolean testEncodability; - private boolean testUnorderedness; - - /** Returns a new DirectPipelineRunner. */ - private DirectPipelineRunner(DirectPipelineOptions options) { - this.options = options; - // (Re-)register standard IO factories. Clobbers any prior credentials. - IOChannelUtils.registerStandardIOFactories(options); - long randomSeed; - if (options.getDirectPipelineRunnerRandomSeed() != null) { - randomSeed = options.getDirectPipelineRunnerRandomSeed(); - } else { - randomSeed = new Random().nextLong(); - } - - LOG.debug("DirectPipelineRunner using random seed {}.", randomSeed); - rand = new Random(randomSeed); - - testSerializability = options.isTestSerializability(); - testEncodability = options.isTestEncodability(); - testUnorderedness = options.isTestUnorderedness(); - } - - /** - * Get the options used in this {@link Pipeline}. - */ - public DirectPipelineOptions getPipelineOptions() { - return options; - } - - @Override - public String toString() { - return "DirectPipelineRunner#" + hashCode(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunner.java deleted file mode 100644 index c5a5b24a89..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunner.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.InstanceBuilder; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; - -/** - * A {@link PipelineRunner} can execute, translate, or otherwise process a - * {@link Pipeline}. - * - * @param the type of the result of {@link #run}. - */ -public abstract class PipelineRunner { - - /** - * Constructs a runner from the provided options. - * - * @return The newly created runner. - */ - public static PipelineRunner fromOptions(PipelineOptions options) { - GcsOptions gcsOptions = PipelineOptionsValidator.validate(GcsOptions.class, options); - checkNotNull(options); - - // (Re-)register standard IO factories. Clobbers any prior credentials. - IOChannelUtils.registerStandardIOFactories(gcsOptions); - - @SuppressWarnings("unchecked") - PipelineRunner result = - InstanceBuilder.ofType(PipelineRunner.class) - .fromClass(options.getRunner()) - .fromFactoryMethod("fromOptions") - .withArg(PipelineOptions.class, options) - .build(); - return result; - } - - /** - * Processes the given Pipeline, returning the results. - */ - public abstract ResultT run(Pipeline pipeline); - - /** - * Applies a transform to the given input, returning the output. - * - *

              The default implementation calls PTransform.apply(input), but can be overridden - * to customize behavior for a particular runner. - */ - public OutputT apply( - PTransform transform, InputT input) { - return transform.apply(input); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerRegistrar.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerRegistrar.java deleted file mode 100644 index a577e758f6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerRegistrar.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.auto.service.AutoService; -import java.util.ServiceLoader; - -/** - * {@link PipelineRunner} creators have the ability to automatically have their - * {@link PipelineRunner} registered with this SDK by creating a {@link ServiceLoader} entry - * and a concrete implementation of this interface. - * - *

              Note that automatic registration of any - * {@link com.google.cloud.dataflow.sdk.options.PipelineOptions} requires users - * conform to the limit that each {@link PipelineRunner}'s - * {@link Class#getSimpleName() simple name} must be unique. - * - *

              It is optional but recommended to use one of the many build time tools such as - * {@link AutoService} to generate the necessary META-INF files automatically. - */ -public interface PipelineRunnerRegistrar { - /** - * Get the set of {@link PipelineRunner PipelineRunners} to register. - */ - Iterable>> getPipelineRunners(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/RecordingPipelineVisitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/RecordingPipelineVisitor.java deleted file mode 100644 index ca02b39d13..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/RecordingPipelineVisitor.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PValue; - -import java.util.ArrayList; -import java.util.List; - -/** - * Provides a simple {@link com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor} - * that records the transformation tree. - * - *

              Provided for internal unit tests. - */ -public class RecordingPipelineVisitor implements Pipeline.PipelineVisitor { - - public final List> transforms = new ArrayList<>(); - public final List values = new ArrayList<>(); - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - } - - @Override - public void visitTransform(TransformTreeNode node) { - transforms.add(node.getTransform()); - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - values.add(value); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java deleted file mode 100644 index f7c3274bd9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunner.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.services.dataflow.Dataflow; -import com.google.auto.service.AutoService; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** - * A {@link PipelineRunner} that's like {@link DataflowPipelineRunner} but only stores a template of - * a job. - * - *

              Requires that {@link getDataflowJobFile} is set. - */ -public class TemplatingDataflowPipelineRunner extends PipelineRunner { - private static final Logger LOG = LoggerFactory.getLogger(TemplatingDataflowPipelineRunner.class); - - private final DataflowPipelineRunner dataflowPipelineRunner; - private final PipelineOptions options; - - protected TemplatingDataflowPipelineRunner(DataflowPipelineRunner internalRunner, - PipelineOptions options) { - this.dataflowPipelineRunner = internalRunner; - this.options = options; - } - - private static class TemplateHooks extends DataflowPipelineRunnerHooks { - @Override - public boolean shouldActuallyRunJob() { - return false; - } - - @Override - public boolean failOnJobFileWriteFailure() { - return true; - } - } - - /** Constructs a runner from the provided options. */ - public static TemplatingDataflowPipelineRunner fromOptions(PipelineOptions options) { - DataflowPipelineDebugOptions dataflowOptions = - PipelineOptionsValidator.validate(DataflowPipelineDebugOptions.class, options); - List experiments = dataflowOptions.getExperiments(); - if (experiments == null) { - experiments = new ArrayList<>(); - dataflowOptions.setExperiments(experiments); - } - experiments.add("enable_custom_bigquery_source"); - experiments.add("enable_custom_bigquery_sink"); - DataflowPipelineRunner dataflowPipelineRunner = - DataflowPipelineRunner.fromOptions(dataflowOptions); - checkArgument(!Strings.isNullOrEmpty(dataflowOptions.getDataflowJobFile()), - "--dataflowJobFile must be present to create a template."); - - return new TemplatingDataflowPipelineRunner(dataflowPipelineRunner, options); - } - - private static class TemplateJob extends DataflowPipelineJob { - private static final String ERROR = - "The result of template creation should not be used."; - - TemplateJob() { - super(null, null, null, null); - } - - @Override - public String getJobId() { - throw new UnsupportedOperationException(ERROR); - } - - @Override - public String getProjectId() { - throw new UnsupportedOperationException(ERROR); - } - - @Override - public DataflowPipelineJob getReplacedByJob() { - throw new UnsupportedOperationException(ERROR); - } - - @Override - public Dataflow getDataflowClient() { - throw new UnsupportedOperationException(ERROR); - } - - @Override - public State waitToFinish( - long timeToWait, - TimeUnit timeUnit, - MonitoringUtil.JobMessagesHandler messageHandler) { - throw new UnsupportedOperationException(ERROR); - } - - @Override - public void cancel() { - throw new UnsupportedOperationException(ERROR); - } - - @Override - public State getState() { - throw new UnsupportedOperationException(ERROR); - } - } - - @Override - public DataflowPipelineJob run(Pipeline p) { - dataflowPipelineRunner.setHooks(new TemplateHooks()); - final DataflowPipelineJob job = dataflowPipelineRunner.run(p); - LOG.info("Template successfully created."); - return new TemplateJob(); - } - - @Override - public OutputT apply( - PTransform transform, InputT input) { - // We delegate graph building to the inner runner. - return dataflowPipelineRunner.apply(transform, input); - } - - @Override - public String toString() { - return "TemplatingDataflowPipelineRunner"; - } - - /** Register the {@link TemplatingDataflowPipelineRunner}. */ - @AutoService(PipelineRunnerRegistrar.class) - public static class Runner implements PipelineRunnerRegistrar { - @Override - public Iterable>> getPipelineRunners() { - return ImmutableList - .>>of(TemplatingDataflowPipelineRunner.class); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformHierarchy.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformHierarchy.java deleted file mode 100644 index fcb9224947..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformHierarchy.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; - -import java.util.Deque; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; - -/** - * Captures information about a collection of transformations and their - * associated {@link PValue}s. - */ -public class TransformHierarchy { - private final Deque transformStack = new LinkedList<>(); - private final Map producingTransformNode = new HashMap<>(); - - /** - * Create a {@code TransformHierarchy} containing a root node. - */ - public TransformHierarchy() { - // First element in the stack is the root node, holding all child nodes. - transformStack.add(new TransformTreeNode(null, null, "", null)); - } - - /** - * Returns the last TransformTreeNode on the stack. - */ - public TransformTreeNode getCurrent() { - return transformStack.peek(); - } - - /** - * Add a TransformTreeNode to the stack. - */ - public void pushNode(TransformTreeNode current) { - transformStack.push(current); - } - - /** - * Removes the last TransformTreeNode from the stack. - */ - public void popNode() { - transformStack.pop(); - checkState(!transformStack.isEmpty()); - } - - /** - * Adds an input to the given node. - * - *

              This forces the producing node to be finished. - */ - public void addInput(TransformTreeNode node, PInput input) { - for (PValue i : input.expand()) { - TransformTreeNode producer = producingTransformNode.get(i); - if (producer == null) { - throw new IllegalStateException("Producer unknown for input: " + i); - } - - producer.finishSpecifying(); - node.addInputProducer(i, producer); - } - } - - /** - * Sets the output of a transform node. - */ - public void setOutput(TransformTreeNode producer, POutput output) { - producer.setOutput(output); - - for (PValue o : output.expand()) { - producingTransformNode.put(o, producer); - } - } - - /** - * Visits all nodes in the transform hierarchy, in transitive order. - */ - public void visit(Pipeline.PipelineVisitor visitor, - Set visitedNodes) { - transformStack.peekFirst().visit(visitor, visitedNodes); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformTreeNode.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformTreeNode.java deleted file mode 100644 index 6b6e25fe85..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/TransformTreeNode.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * Provides internal tracking of transform relationships with helper methods - * for initialization and ordered visitation. - */ -public class TransformTreeNode { - private final TransformTreeNode enclosingNode; - - // The PTransform for this node, which may be a composite PTransform. - // The root of a TransformHierarchy is represented as a TransformTreeNode - // with a null transform field. - private final PTransform transform; - - private final String fullName; - - // Nodes for sub-transforms of a composite transform. - private final Collection parts = new ArrayList<>(); - - // Inputs to the transform, in expanded form and mapped to the producer - // of the input. - private final Map inputs = new HashMap<>(); - - // Input to the transform, in unexpanded form. - private final PInput input; - - // TODO: track which outputs need to be exported to parent. - // Output of the transform, in unexpanded form. - private POutput output; - - private boolean finishedSpecifying = false; - - /** - * Creates a new TransformTreeNode with the given parent and transform. - * - *

              EnclosingNode and transform may both be null for - * a root-level node, which holds all other nodes. - * - * @param enclosingNode the composite node containing this node - * @param transform the PTransform tracked by this node - * @param fullName the fully qualified name of the transform - * @param input the unexpanded input to the transform - */ - public TransformTreeNode(@Nullable TransformTreeNode enclosingNode, - @Nullable PTransform transform, - String fullName, - @Nullable PInput input) { - this.enclosingNode = enclosingNode; - this.transform = transform; - checkArgument((enclosingNode == null && transform == null) - || (enclosingNode != null && transform != null), - "EnclosingNode and transform must both be specified, or both be null"); - this.fullName = fullName; - this.input = input; - } - - /** - * Returns the transform associated with this transform node. - */ - public PTransform getTransform() { - return transform; - } - - /** - * Returns the enclosing composite transform node, or null if there is none. - */ - public TransformTreeNode getEnclosingNode() { - return enclosingNode; - } - - /** - * Adds a composite operation to the transform node. - * - *

              As soon as a node is added, the transform node is considered a - * composite operation instead of a primitive transform. - */ - public void addComposite(TransformTreeNode node) { - parts.add(node); - } - - /** - * Returns true if this node represents a composite transform that does not perform - * processing of its own, but merely encapsulates a sub-pipeline (which may be empty). - * - *

              Note that a node may be composite with no sub-transforms if it returns its input directly - * extracts a component of a tuple, or other operations that occur at pipeline assembly time. - */ - public boolean isCompositeNode() { - return !parts.isEmpty() || returnsOthersOutput() || isRootNode(); - } - - private boolean returnsOthersOutput() { - PTransform transform = getTransform(); - for (PValue output : getExpandedOutputs()) { - if (!output.getProducingTransformInternal().getTransform().equals(transform)) { - return true; - } - } - return false; - } - - public boolean isRootNode() { - return transform == null; - } - - public String getFullName() { - return fullName; - } - - /** - * Adds an input to the transform node. - */ - public void addInputProducer(PValue expandedInput, TransformTreeNode producer) { - checkState(!finishedSpecifying); - inputs.put(expandedInput, producer); - } - - /** - * Returns the transform input, in unexpanded form. - */ - public PInput getInput() { - return input; - } - - /** - * Returns a mapping of inputs to the producing nodes for all inputs to - * the transform. - */ - public Map getInputs() { - return Collections.unmodifiableMap(inputs); - } - - /** - * Adds an output to the transform node. - */ - public void setOutput(POutput output) { - checkState(!finishedSpecifying); - checkState(this.output == null); - this.output = output; - } - - /** - * Returns the transform output, in unexpanded form. - */ - public POutput getOutput() { - return output; - } - - /** - * Returns the transform outputs, in expanded form. - */ - public Collection getExpandedOutputs() { - if (output != null) { - return output.expand(); - } else { - return Collections.emptyList(); - } - } - - /** - * Visit the transform node. - * - *

              Provides an ordered visit of the input values, the primitive - * transform (or child nodes for composite transforms), then the - * output values. - */ - public void visit(Pipeline.PipelineVisitor visitor, - Set visitedValues) { - if (!finishedSpecifying) { - finishSpecifying(); - } - - // Visit inputs. - for (Map.Entry entry : inputs.entrySet()) { - if (visitedValues.add(entry.getKey())) { - visitor.visitValue(entry.getKey(), entry.getValue()); - } - } - - if (isCompositeNode()) { - visitor.enterCompositeTransform(this); - for (TransformTreeNode child : parts) { - child.visit(visitor, visitedValues); - } - visitor.leaveCompositeTransform(this); - } else { - visitor.visitTransform(this); - } - - // Visit outputs. - for (PValue pValue : getExpandedOutputs()) { - if (visitedValues.add(pValue)) { - visitor.visitValue(pValue, this); - } - } - } - - /** - * Finish specifying a transform. - * - *

              All inputs are finished first, then the transform, then - * all outputs. - */ - public void finishSpecifying() { - if (finishedSpecifying) { - return; - } - finishedSpecifying = true; - - for (TransformTreeNode input : inputs.values()) { - if (input != null) { - input.finishSpecifying(); - } - } - - if (output != null) { - output.finishSpecifyingOutput(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java deleted file mode 100644 index 846de43bb6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/AssignWindows.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * A primitive {@link PTransform} that implements the {@link Window#into(WindowFn)} - * {@link PTransform}. - * - *

              For an application of {@link Window#into(WindowFn)} that changes the {@link WindowFn}, applies - * a primitive {@link PTransform} in the Dataflow service. - * - *

              For an application of {@link Window#into(WindowFn)} that does not change the {@link WindowFn}, - * applies an identity {@link ParDo} and sets the windowing strategy of the output - * {@link PCollection}. - * - *

              For internal use only. - * - * @param the type of input element - */ -public class AssignWindows extends PTransform, PCollection> { - private final Window.Bound transform; - - /** - * Builds an instance of this class from the overriden transform. - */ - @SuppressWarnings("unused") // Used via reflection - public AssignWindows(Window.Bound transform) { - this.transform = transform; - } - - @Override - public PCollection apply(PCollection input) { - WindowingStrategy outputStrategy = - transform.getOutputStrategyInternal(input.getWindowingStrategy()); - if (transform.getWindowFn() != null) { - // If the windowFn changed, we create a primitive, and run the AssignWindows operation here. - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), outputStrategy, input.isBounded()); - } else { - // If the windowFn didn't change, we just run a pass-through transform and then set the - // new windowing strategy. - return input.apply(ParDo.named("Identity").of(new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - c.output(c.element()); - } - })).setWindowingStrategyInternal(outputStrategy); - } - } - - @Override - public void validate(PCollection input) { - transform.validate(input); - } - - @Override - protected Coder getDefaultOutputCoder(PCollection input) { - return input.getCoder(); - } - - @Override - protected String getKindString() { - return "Window.Into()"; - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java deleted file mode 100644 index 8160693195..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/CustomSources.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import static com.google.api.client.util.Base64.encodeBase64String; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.services.dataflow.model.SourceMetadata; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.Source; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.common.annotations.VisibleForTesting; -import com.google.protobuf.ByteString; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - - -/** - * A helper class for supporting sources defined as {@code Source}. - * - *

              Provides a bridge between the high-level {@code Source} API and the - * low-level {@code CloudSource} class. - */ -public class CustomSources { - private static final String SERIALIZED_SOURCE = "serialized_source"; - @VisibleForTesting static final String SERIALIZED_SOURCE_SPLITS = "serialized_source_splits"; - /** - * The current limit on the size of a ReportWorkItemStatus RPC to Google Cloud Dataflow, which - * includes the initial splits, is 20 MB. - */ - public static final long DATAFLOW_SPLIT_RESPONSE_API_SIZE_BYTES = 20 * (1 << 20); - - private static final Logger LOG = LoggerFactory.getLogger(CustomSources.class); - - private static final ByteString firstSplitKey = ByteString.copyFromUtf8("0000000000000001"); - - public static boolean isFirstUnboundedSourceSplit(ByteString splitKey) { - return splitKey.equals(firstSplitKey); - } - - private static int getDesiredNumUnboundedSourceSplits(DataflowPipelineOptions options) { - if (options.getMaxNumWorkers() > 0) { - return options.getMaxNumWorkers(); - } else if (options.getNumWorkers() > 0) { - return options.getNumWorkers() * 3; - } else { - return 20; - } - } - - public static com.google.api.services.dataflow.model.Source serializeToCloudSource( - Source source, PipelineOptions options) throws Exception { - com.google.api.services.dataflow.model.Source cloudSource = - new com.google.api.services.dataflow.model.Source(); - // We ourselves act as the SourceFormat. - cloudSource.setSpec(CloudObject.forClass(CustomSources.class)); - addString( - cloudSource.getSpec(), SERIALIZED_SOURCE, encodeBase64String(serializeToByteArray(source))); - - SourceMetadata metadata = new SourceMetadata(); - if (source instanceof BoundedSource) { - BoundedSource boundedSource = (BoundedSource) source; - try { - metadata.setProducesSortedKeys(boundedSource.producesSortedKeys(options)); - } catch (Exception e) { - LOG.warn("Failed to check if the source produces sorted keys: " + source, e); - } - - // Size estimation is best effort so we continue even if it fails here. - try { - metadata.setEstimatedSizeBytes(boundedSource.getEstimatedSizeBytes(options)); - } catch (Exception e) { - LOG.warn("Size estimation of the source failed: " + source, e); - } - } else if (source instanceof UnboundedSource) { - UnboundedSource unboundedSource = (UnboundedSource) source; - metadata.setInfinite(true); - List encodedSplits = new ArrayList<>(); - int desiredNumSplits = - getDesiredNumUnboundedSourceSplits(options.as(DataflowPipelineOptions.class)); - for (UnboundedSource split : - unboundedSource.generateInitialSplits(desiredNumSplits, options)) { - encodedSplits.add(encodeBase64String(serializeToByteArray(split))); - } - checkArgument(!encodedSplits.isEmpty(), "UnboundedSources must have at least one split"); - addStringList(cloudSource.getSpec(), SERIALIZED_SOURCE_SPLITS, encodedSplits); - } else { - throw new IllegalArgumentException("Unexpected source kind: " + source.getClass()); - } - - cloudSource.setMetadata(metadata); - return cloudSource; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowAggregatorTransforms.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowAggregatorTransforms.java deleted file mode 100644 index e1d73019fe..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowAggregatorTransforms.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; - -/** - * A mapping relating {@link Aggregator}s and the {@link PTransform} in which they are used. - */ -public class DataflowAggregatorTransforms { - private final Map, Collection>> aggregatorTransforms; - private final Multimap, AppliedPTransform> transformAppliedTransforms; - private final BiMap, String> appliedStepNames; - - public DataflowAggregatorTransforms( - Map, Collection>> aggregatorTransforms, - Map, String> transformStepNames) { - this.aggregatorTransforms = aggregatorTransforms; - appliedStepNames = HashBiMap.create(transformStepNames); - - transformAppliedTransforms = HashMultimap.create(); - for (AppliedPTransform appliedTransform : transformStepNames.keySet()) { - transformAppliedTransforms.put(appliedTransform.getTransform(), appliedTransform); - } - } - - /** - * Returns true if the provided {@link Aggregator} is used in the constructing {@link Pipeline}. - */ - public boolean contains(Aggregator aggregator) { - return aggregatorTransforms.containsKey(aggregator); - } - - /** - * Gets the step names in which the {@link Aggregator} is used. - */ - public Collection getAggregatorStepNames(Aggregator aggregator) { - Collection names = new HashSet<>(); - Collection> transforms = aggregatorTransforms.get(aggregator); - for (PTransform transform : transforms) { - for (AppliedPTransform applied : transformAppliedTransforms.get(transform)) { - names.add(appliedStepNames.get(applied)); - } - } - return names; - } - - /** - * Gets the {@link PTransform} that was assigned the provided step name. - */ - public AppliedPTransform getAppliedTransformForStepName(String stepName) { - return appliedStepNames.inverse().get(stepName); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java deleted file mode 100644 index 13016dd493..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowMetricUpdateExtractor.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import com.google.api.services.dataflow.model.MetricStructuredName; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Methods for extracting the values of an {@link Aggregator} from a collection of {@link - * MetricUpdate MetricUpdates}. - */ -public final class DataflowMetricUpdateExtractor { - private static final String STEP_NAME_CONTEXT_KEY = "step"; - private static final String IS_TENTATIVE_KEY = "tentative"; - - private DataflowMetricUpdateExtractor() { - // Do not instantiate. - } - - /** - * Extract the values of the provided {@link Aggregator} at each {@link PTransform} it was used in - * according to the provided {@link DataflowAggregatorTransforms} from the given list of {@link - * MetricUpdate MetricUpdates}. - */ - public static Map fromMetricUpdates(Aggregator aggregator, - DataflowAggregatorTransforms aggregatorTransforms, List metricUpdates) { - Map results = new HashMap<>(); - if (metricUpdates == null) { - return results; - } - - String aggregatorName = aggregator.getName(); - Collection aggregatorSteps = aggregatorTransforms.getAggregatorStepNames(aggregator); - - for (MetricUpdate metricUpdate : metricUpdates) { - MetricStructuredName metricStructuredName = metricUpdate.getName(); - Map context = metricStructuredName.getContext(); - if (metricStructuredName.getName().equals(aggregatorName) && context != null - && aggregatorSteps.contains(context.get(STEP_NAME_CONTEXT_KEY))) { - AppliedPTransform transform = - aggregatorTransforms.getAppliedTransformForStepName( - context.get(STEP_NAME_CONTEXT_KEY)); - String fullName = transform.getFullName(); - // Prefer the tentative (fresher) value if it exists. - if (Boolean.parseBoolean(context.get(IS_TENTATIVE_KEY)) || !results.containsKey(fullName)) { - results.put(fullName, toValue(aggregator, metricUpdate)); - } - } - } - - return results; - - } - - private static OutputT toValue( - Aggregator aggregator, MetricUpdate metricUpdate) { - CombineFn combineFn = aggregator.getCombineFn(); - Class outputType = combineFn.getOutputType().getRawType(); - - if (outputType.equals(Long.class)) { - @SuppressWarnings("unchecked") - OutputT asLong = (OutputT) Long.valueOf(toNumber(metricUpdate).longValue()); - return asLong; - } - if (outputType.equals(Integer.class)) { - @SuppressWarnings("unchecked") - OutputT asInt = (OutputT) Integer.valueOf(toNumber(metricUpdate).intValue()); - return asInt; - } - if (outputType.equals(Double.class)) { - @SuppressWarnings("unchecked") - OutputT asDouble = (OutputT) Double.valueOf(toNumber(metricUpdate).doubleValue()); - return asDouble; - } - throw new UnsupportedOperationException( - "Unsupported Output Type " + outputType + " in aggregator " + aggregator); - } - - private static Number toNumber(MetricUpdate update) { - if (update.getScalar() instanceof Number) { - return (Number) update.getScalar(); - } - throw new IllegalArgumentException( - "Metric Update " + update + " does not have a numeric scalar"); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java deleted file mode 100644 index 6cfaad13eb..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSource.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import static com.google.cloud.dataflow.sdk.util.StringUtils.approximateSimpleName; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.NullableCoder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * {@link PTransform} that converts a {@link BoundedSource} as an {@link UnboundedSource}. - * - *

              {@link BoundedSource} is read directly without calling {@link BoundedSource#splitIntoBundles}, - * and element timestamps are propagated. While any elements remain, the watermark is the beginning - * of time {@link BoundedWindow#TIMESTAMP_MIN_VALUE}, and after all elements have been produced - * the watermark goes to the end of time {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. - * - *

              Checkpoints are created by calling {@link BoundedReader#splitAtFraction} on inner - * {@link BoundedSource}. - * Sources that cannot be split are read entirely into memory, so this transform does not work well - * with large, unsplittable sources. - * - *

              This transform is intended to be used by a runner during pipeline translation to convert - * a Read.Bounded into a Read.Unbounded. - */ -public class DataflowUnboundedReadFromBoundedSource extends PTransform> { - - private static final Logger LOG = - LoggerFactory.getLogger(DataflowUnboundedReadFromBoundedSource.class); - - private final BoundedSource source; - - /** - * Constructs a {@link PTransform} that performs an unbounded read from a {@link BoundedSource}. - */ - public DataflowUnboundedReadFromBoundedSource(BoundedSource source) { - this.source = source; - } - - @Override - public PCollection apply(PInput input) { - return input.getPipeline().apply( - Read.from(new BoundedToUnboundedSourceAdapter<>(source))); - } - - @Override - protected Coder getDefaultOutputCoder() { - return source.getDefaultOutputCoder(); - } - - @Override - public String getKindString() { - String sourceName; - if (source.getClass().isAnonymousClass()) { - sourceName = "AnonymousSource"; - } else { - sourceName = approximateSimpleName(source.getClass()); - } - - return "Read(" + sourceName + ")"; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - // We explicitly do not register base-class data, instead we use the delegate inner source. - builder - .add(DisplayData.item("source", source.getClass())) - .include(source); - } - - /** - * A {@code BoundedSource} to {@code UnboundedSource} adapter. - */ - @VisibleForTesting - public static class BoundedToUnboundedSourceAdapter - extends UnboundedSource> { - - private BoundedSource boundedSource; - - public BoundedToUnboundedSourceAdapter(BoundedSource boundedSource) { - this.boundedSource = boundedSource; - } - - @Override - public void validate() { - boundedSource.validate(); - } - - @Override - public List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception { - try { - long desiredBundleSize = boundedSource.getEstimatedSizeBytes(options) / desiredNumSplits; - if (desiredBundleSize <= 0) { - LOG.warn("BoundedSource {} cannot estimate its size, skips the initial splits.", - boundedSource); - return ImmutableList.of(this); - } - List> splits - = boundedSource.splitIntoBundles(desiredBundleSize, options); - if (splits == null) { - LOG.warn("BoundedSource cannot split {}, skips the initial splits.", boundedSource); - return ImmutableList.of(this); - } - return Lists.transform( - splits, - new Function, BoundedToUnboundedSourceAdapter>() { - @Override - public BoundedToUnboundedSourceAdapter apply(BoundedSource input) { - return new BoundedToUnboundedSourceAdapter<>(input); - }}); - } catch (Exception e) { - LOG.warn("Exception while splitting {}, skips the initial splits.", boundedSource, e); - return ImmutableList.of(this); - } - } - - @Override - public Reader createReader(PipelineOptions options, Checkpoint checkpoint) { - if (checkpoint == null) { - return new Reader(null /* residualElements */, boundedSource, options); - } else { - return new Reader(checkpoint.residualElements, checkpoint.residualSource, options); - } - } - - @Override - public Coder getDefaultOutputCoder() { - return boundedSource.getDefaultOutputCoder(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public Coder> getCheckpointMarkCoder() { - return new CheckpointCoder<>(boundedSource.getDefaultOutputCoder()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("source", boundedSource.getClass())); - builder.include(boundedSource); - } - - @VisibleForTesting - static class Checkpoint implements UnboundedSource.CheckpointMark { - @Nullable private final List> residualElements; - @Nullable private final BoundedSource residualSource; - - public Checkpoint( - @Nullable List> residualElements, - @Nullable BoundedSource residualSource) { - this.residualElements = residualElements; - this.residualSource = residualSource; - } - - @Override - public void finalizeCheckpoint() {} - - @VisibleForTesting - @Nullable List> getResidualElements() { - return residualElements; - } - - @VisibleForTesting - @Nullable BoundedSource getResidualSource() { - return residualSource; - } - } - - @VisibleForTesting - static class CheckpointCoder extends StandardCoder> { - - @JsonCreator - public static CheckpointCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, - "Expecting 1 components, got %s", components.size()); - return new CheckpointCoder<>(components.get(0)); - } - - // The coder for a list of residual elements and their timestamps - private final Coder>> elemsCoder; - // The coder from the BoundedReader for coding each element - private final Coder elemCoder; - // The nullable and serializable coder for the BoundedSource. - @SuppressWarnings("rawtypes") - private final Coder sourceCoder; - - CheckpointCoder(Coder elemCoder) { - this.elemsCoder = NullableCoder.of( - ListCoder.of(TimestampedValue.TimestampedValueCoder.of(elemCoder))); - this.elemCoder = elemCoder; - this.sourceCoder = NullableCoder.of(SerializableCoder.of(BoundedSource.class)); - } - - @Override - public void encode(Checkpoint value, OutputStream outStream, Context context) - throws CoderException, IOException { - Context nested = context.nested(); - elemsCoder.encode(value.residualElements, outStream, nested); - sourceCoder.encode(value.residualSource, outStream, nested); - } - - @SuppressWarnings("unchecked") - @Override - public Checkpoint decode(InputStream inStream, Context context) - throws CoderException, IOException { - Context nested = context.nested(); - return new Checkpoint<>( - elemsCoder.decode(inStream, nested), - sourceCoder.decode(inStream, nested)); - } - - @Override - public List> getCoderArguments() { - return Arrays.>asList(elemCoder); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "CheckpointCoder uses Java Serialization, which may be non-deterministic."); - } - } - - /** - * An {@code UnboundedReader} that wraps a {@code BoundedSource} into - * {@link ResidualElements} and {@link ResidualSource}. - * - *

              In the initial state, {@link ResidualElements} is null and {@link ResidualSource} contains - * the {@code BoundedSource}. After the first checkpoint, the {@code BoundedSource} will - * be split into {@link ResidualElements} and {@link ResidualSource}. - */ - @VisibleForTesting - class Reader extends UnboundedReader { - private ResidualElements residualElements; - @Nullable private ResidualSource residualSource; - private final PipelineOptions options; - private boolean done; - - Reader( - @Nullable List> residualElementsList, - @Nullable BoundedSource residualSource, - PipelineOptions options) { - init(residualElementsList, residualSource, options); - this.options = checkNotNull(options, "options"); - this.done = false; - } - - private void init( - @Nullable List> residualElementsList, - @Nullable BoundedSource residualSource, - PipelineOptions options) { - this.residualElements = residualElementsList == null - ? new ResidualElements(Collections.>emptyList()) - : new ResidualElements(residualElementsList); - this.residualSource = - residualSource == null ? null : new ResidualSource(residualSource, options); - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - if (residualElements.advance()) { - return true; - } else if (residualSource != null && residualSource.advance()) { - return true; - } else { - done = true; - return false; - } - } - - @Override - public void close() throws IOException { - if (residualSource != null) { - residualSource.close(); - } - } - - @Override - public T getCurrent() throws NoSuchElementException { - if (residualElements.hasCurrent()) { - return residualElements.getCurrent(); - } else if (residualSource != null) { - return residualSource.getCurrent(); - } else { - throw new NoSuchElementException(); - } - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - if (residualElements.hasCurrent()) { - return residualElements.getCurrentTimestamp(); - } else if (residualSource != null) { - return residualSource.getCurrentTimestamp(); - } else { - throw new NoSuchElementException(); - } - } - - @Override - public Instant getWatermark() { - return done ? BoundedWindow.TIMESTAMP_MAX_VALUE : BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - /** - * {@inheritDoc} - * - *

              If only part of the {@link ResidualElements} is consumed, the new - * checkpoint will contain the remaining elements in {@link ResidualElements} and - * the {@link ResidualSource}. - * - *

              If all {@link ResidualElements} and part of the - * {@link ResidualSource} are consumed, the new checkpoint is done by splitting - * {@link ResidualSource} into new {@link ResidualElements} and {@link ResidualSource}. - * {@link ResidualSource} is the source split from the current source, - * and {@link ResidualElements} contains rest elements from the current source after - * the splitting. For unsplittable source, it will put all remaining elements into - * the {@link ResidualElements}. - */ - @Override - public Checkpoint getCheckpointMark() { - Checkpoint newCheckpoint; - if (!residualElements.done()) { - // Part of residualElements are consumed. - // Checkpoints the remaining elements and residualSource. - newCheckpoint = new Checkpoint<>( - residualElements.getRestElements(), - residualSource == null ? null : residualSource.getSource()); - } else if (residualSource != null) { - newCheckpoint = residualSource.getCheckpointMark(); - } else { - newCheckpoint = new Checkpoint<>(null /* residualElements */, null /* residualSource */); - } - // Re-initialize since the residualElements and the residualSource might be - // consumed or split by checkpointing. - init(newCheckpoint.residualElements, newCheckpoint.residualSource, options); - return newCheckpoint; - } - - @Override - public BoundedToUnboundedSourceAdapter getCurrentSource() { - return BoundedToUnboundedSourceAdapter.this; - } - } - - private class ResidualElements { - private final List> elementsList; - @Nullable private Iterator> elementsIterator; - @Nullable private TimestampedValue currentT; - private boolean hasCurrent; - private boolean done; - - ResidualElements(List> residualElementsList) { - this.elementsList = checkNotNull(residualElementsList, "residualElementsList"); - this.elementsIterator = null; - this.currentT = null; - this.hasCurrent = false; - this.done = false; - } - - public boolean advance() { - if (elementsIterator == null) { - elementsIterator = elementsList.iterator(); - } - if (elementsIterator.hasNext()) { - currentT = elementsIterator.next(); - hasCurrent = true; - return true; - } else { - done = true; - hasCurrent = false; - return false; - } - } - - boolean hasCurrent() { - return hasCurrent; - } - - boolean done() { - return done; - } - - TimestampedValue getCurrentTimestampedValue() { - if (!hasCurrent) { - throw new NoSuchElementException(); - } - return currentT; - } - - T getCurrent() { - return getCurrentTimestampedValue().getValue(); - } - - Instant getCurrentTimestamp() { - return getCurrentTimestampedValue().getTimestamp(); - } - - List> getRestElements() { - if (elementsIterator == null) { - return elementsList; - } else { - List> newResidualElements = Lists.newArrayList(); - while (elementsIterator.hasNext()) { - newResidualElements.add(elementsIterator.next()); - } - return newResidualElements; - } - } - } - - private class ResidualSource { - private BoundedSource residualSource; - private PipelineOptions options; - @Nullable private BoundedReader reader; - private boolean closed; - - public ResidualSource(BoundedSource residualSource, PipelineOptions options) { - this.residualSource = checkNotNull(residualSource, "residualSource"); - this.options = checkNotNull(options, "options"); - this.reader = null; - this.closed = false; - } - - private boolean advance() throws IOException { - if (reader == null && !closed) { - reader = residualSource.createReader(options); - return reader.start(); - } else { - return reader.advance(); - } - } - - T getCurrent() throws NoSuchElementException { - if (reader == null) { - throw new NoSuchElementException(); - } - return reader.getCurrent(); - } - - Instant getCurrentTimestamp() throws NoSuchElementException { - if (reader == null) { - throw new NoSuchElementException(); - } - return reader.getCurrentTimestamp(); - } - - void close() throws IOException { - if (reader != null) { - reader.close(); - reader = null; - } - closed = true; - } - - BoundedSource getSource() { - return residualSource; - } - - Checkpoint getCheckpointMark() { - if (reader == null) { - // Reader hasn't started, checkpoint the residualSource. - return new Checkpoint<>(null /* residualElements */, residualSource); - } else { - // Part of residualSource are consumed. - // Splits the residualSource and tracks the new residualElements in current source. - BoundedSource residualSplit = null; - Double fractionConsumed = reader.getFractionConsumed(); - if (fractionConsumed != null && 0 <= fractionConsumed && fractionConsumed <= 1) { - double fractionRest = 1 - fractionConsumed; - int splitAttempts = 8; - for (int i = 0; i < 8 && residualSplit == null; ++i) { - double fractionToSplit = fractionConsumed + fractionRest * i / splitAttempts; - residualSplit = reader.splitAtFraction(fractionToSplit); - } - } - List> newResidualElements = Lists.newArrayList(); - try { - while (advance()) { - newResidualElements.add( - TimestampedValue.of(reader.getCurrent(), reader.getCurrentTimestamp())); - } - } catch (IOException e) { - throw new RuntimeException("Failed to read elements from the bounded reader.", e); - } - return new Checkpoint<>(newResidualElements, residualSplit); - } - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java deleted file mode 100644 index 1111d786c3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/ReadTranslator.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addDictionary; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; - -import com.google.api.services.dataflow.model.SourceMetadata; -import com.google.cloud.dataflow.sdk.io.FileBasedSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.Source; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.values.PValue; - -import java.util.HashMap; -import java.util.Map; - -/** - * Translator for the {@code Read} {@code PTransform} for the Dataflow back-end. - */ -public class ReadTranslator implements TransformTranslator> { - @Override - public void translate(Read.Bounded transform, TranslationContext context) { - translateReadHelper(transform.getSource(), transform, context); - } - - public static void translateReadHelper(Source source, - PTransform transform, - DataflowPipelineTranslator.TranslationContext context) { - try { - // TODO: Move this validation out of translation once IOChannelUtils is portable - // and can be reconstructed on the worker. - if (source instanceof FileBasedSource) { - ValueProvider filePatternOrSpec = - ((FileBasedSource) source).getFileOrPatternSpecProvider(); - if (filePatternOrSpec.isAccessible()) { - context.getPipelineOptions() - .getPathValidator() - .validateInputFilePatternSupported(filePatternOrSpec.get()); - } - } - - context.addStep(transform, "ParallelRead"); - context.addInput(PropertyNames.FORMAT, PropertyNames.CUSTOM_SOURCE_FORMAT); - context.addInput( - PropertyNames.SOURCE_STEP_INPUT, - cloudSourceToDictionary( - CustomSources.serializeToCloudSource(source, context.getPipelineOptions()))); - context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - // Represents a cloud Source as a dictionary for encoding inside the {@code SOURCE_STEP_INPUT} - // property of CloudWorkflowStep.input. - private static Map cloudSourceToDictionary( - com.google.api.services.dataflow.model.Source source) { - // Do not translate encoding - the source's encoding is translated elsewhere - // to the step's output info. - Map res = new HashMap<>(); - addDictionary(res, PropertyNames.SOURCE_SPEC, source.getSpec()); - if (source.getMetadata() != null) { - addDictionary(res, PropertyNames.SOURCE_METADATA, - cloudSourceMetadataToDictionary(source.getMetadata())); - } - if (source.getDoesNotNeedSplitting() != null) { - addBoolean( - res, PropertyNames.SOURCE_DOES_NOT_NEED_SPLITTING, source.getDoesNotNeedSplitting()); - } - return res; - } - - private static Map cloudSourceMetadataToDictionary(SourceMetadata metadata) { - Map res = new HashMap<>(); - if (metadata.getProducesSortedKeys() != null) { - addBoolean(res, PropertyNames.SOURCE_PRODUCES_SORTED_KEYS, metadata.getProducesSortedKeys()); - } - if (metadata.getEstimatedSizeBytes() != null) { - addLong(res, PropertyNames.SOURCE_ESTIMATED_SIZE_BYTES, metadata.getEstimatedSizeBytes()); - } - if (metadata.getInfinite() != null) { - addBoolean(res, PropertyNames.SOURCE_IS_INFINITE, metadata.getInfinite()); - } - return res; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/package-info.java deleted file mode 100644 index b6b2ce6901..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/dataflow/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Implementation of the {@link com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner}. - */ -package com.google.cloud.dataflow.sdk.runners.dataflow; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java deleted file mode 100644 index 32b2a676c1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/AbstractModelEnforcement.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -/** - * An abstract {@link ModelEnforcement} that provides default empty implementations for each method. - */ -abstract class AbstractModelEnforcement implements ModelEnforcement { - @Override - public void beforeElement(WindowedValue element) {} - - @Override - public void afterElement(WindowedValue element) {} - - @Override - public void afterFinish( - CommittedBundle input, - InProcessTransformResult result, - Iterable> outputs) {} -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java deleted file mode 100644 index b6b657f94f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactory.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import java.io.IOException; -import java.util.Queue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; - -import javax.annotation.Nullable; - -/** - * A {@link TransformEvaluatorFactory} that produces {@link TransformEvaluator TransformEvaluators} - * for the {@link Bounded Read.Bounded} primitive {@link PTransform}. - */ -final class BoundedReadEvaluatorFactory implements TransformEvaluatorFactory { - /* - * An evaluator for a Source is stateful, to ensure data is not read multiple times. - * Evaluators are cached here to ensure that the reader is not restarted if the evaluator is - * retriggered. - */ - private final ConcurrentMap>> - sourceEvaluators = new ConcurrentHashMap<>(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - @Nullable - public TransformEvaluator forApplication( - AppliedPTransform application, - @Nullable CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) - throws IOException { - return getTransformEvaluator((AppliedPTransform) application, evaluationContext); - } - - /** - * Get a {@link TransformEvaluator} that produce elements for the provided application of - * {@link Bounded Read.Bounded}, initializing the queue of evaluators if required. - * - *

              This method is thread-safe, and will only produce new evaluators if no other invocation has - * already done so. - */ - @SuppressWarnings("unchecked") - private BoundedReadEvaluator getTransformEvaluator( - final AppliedPTransform, Bounded> transform, - final InProcessEvaluationContext evaluationContext) { - // Key by the application and the context the evaluation is occurring in (which call to - // Pipeline#run). - EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); - Queue> evaluatorQueue = - (Queue>) sourceEvaluators.get(key); - if (evaluatorQueue == null) { - evaluatorQueue = new ConcurrentLinkedQueue<>(); - if (sourceEvaluators.putIfAbsent(key, evaluatorQueue) == null) { - // If no queue existed in the evaluators, add an evaluator to initialize the evaluator - // factory for this transform - BoundedSource source = transform.getTransform().getSource(); - BoundedReadEvaluator evaluator = - new BoundedReadEvaluator(transform, evaluationContext, source); - evaluatorQueue.offer(evaluator); - } else { - // otherwise return the existing Queue that arrived before us - evaluatorQueue = (Queue>) sourceEvaluators.get(key); - } - } - return evaluatorQueue.poll(); - } - - /** - * A {@link BoundedReadEvaluator} produces elements from an underlying {@link BoundedSource}, - * discarding all input elements. Within the call to {@link #finishBundle()}, the evaluator - * creates the {@link BoundedReader} and consumes all available input. - * - *

              A {@link BoundedReadEvaluator} should only be created once per {@link BoundedSource}, and - * each evaluator should only be called once per evaluation of the pipeline. Otherwise, the source - * may produce duplicate elements. - */ - private static class BoundedReadEvaluator implements TransformEvaluator { - private final AppliedPTransform, Bounded> transform; - private final InProcessEvaluationContext evaluationContext; - /** - * The source being read from by this {@link BoundedReadEvaluator}. This may not be the same - * as the source derived from {@link #transform} due to splitting. - */ - private BoundedSource source; - - public BoundedReadEvaluator( - AppliedPTransform, Bounded> transform, - InProcessEvaluationContext evaluationContext, - BoundedSource source) { - this.transform = transform; - this.evaluationContext = evaluationContext; - this.source = source; - } - - @Override - public void processElement(WindowedValue element) {} - - @Override - public InProcessTransformResult finishBundle() throws IOException { - try (final BoundedReader reader = - source.createReader(evaluationContext.getPipelineOptions())) { - boolean contentsRemaining = reader.start(); - UncommittedBundle output = - evaluationContext.createRootBundle(transform.getOutput()); - while (contentsRemaining) { - output.add( - WindowedValue.timestampedValueInGlobalWindow( - reader.getCurrent(), reader.getCurrentTimestamp())); - contentsRemaining = reader.advance(); - } - return StepTransformResult.withHold(transform, BoundedWindow.TIMESTAMP_MAX_VALUE) - .addOutput(output) - .build(); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java deleted file mode 100644 index 092dc238a5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/BundleFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * A factory that creates {@link UncommittedBundle UncommittedBundles}. - */ -interface BundleFactory { - /** - * Create an {@link UncommittedBundle} from an empty input. Elements added to the bundle belong to - * the {@code output} {@link PCollection}. - */ - UncommittedBundle createRootBundle(PCollection output); - - /** - * Create an {@link UncommittedBundle} from the specified input. Elements added to the bundle - * belong to the {@code output} {@link PCollection}. - */ - UncommittedBundle createBundle(CommittedBundle input, PCollection output); - - /** - * Create an {@link UncommittedBundle} with the specified keys at the specified step. For use by - * {@link InProcessGroupByKeyOnly} {@link PTransform PTransforms}. Elements added to the bundle - * belong to the {@code output} {@link PCollection}. - */ - UncommittedBundle createKeyedBundle( - CommittedBundle input, StructuralKey key, PCollection output); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/Clock.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/Clock.java deleted file mode 100644 index 11e6ec1686..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/Clock.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import org.joda.time.Instant; - -/** - * Access to the current time. - */ -public interface Clock { - /** - * Returns the current time as an {@link Instant}. - */ - Instant now(); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java deleted file mode 100644 index 2e4dfe6ab9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResult.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - - -import com.google.auto.value.AutoValue; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; - -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * A {@link InProcessTransformResult} that has been committed. - */ -@AutoValue -abstract class CommittedResult { - /** - * Returns the {@link AppliedPTransform} that produced this result. - */ - public abstract AppliedPTransform getTransform(); - - /** - * Returns the {@link CommittedBundle} that contains the input elements that could not be - * processed by the evaluation. - * - *

              {@code null} if the input bundle was null. - */ - @Nullable - public abstract CommittedBundle getUnprocessedInputs(); - - /** - * Returns the outputs produced by the transform. - */ - public abstract Iterable> getOutputs(); - - /** - * Returns if the transform that produced this result produced outputs. - * - *

              Transforms that produce output via modifying the state of the runner (e.g. - * {@link CreatePCollectionView}) should explicitly set this to true. If {@link #getOutputs()} - * returns a nonempty iterable, this will also return true. - */ - public abstract Set getProducedOutputTypes(); - - public static CommittedResult create( - InProcessTransformResult original, - CommittedBundle unprocessedElements, - Iterable> outputs, - Set producedOutputs) { - return new AutoValue_CommittedResult(original.getTransform(), - unprocessedElements, - outputs, - producedOutputs); - } - - enum OutputType { - PCOLLECTION_VIEW, - BUNDLE - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java deleted file mode 100644 index a4495d395d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/CompletionCallback.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; - -/** - * A callback for completing a bundle of input. - */ -interface CompletionCallback { - /** - * Handle a successful result, returning the committed outputs of the result. - */ - CommittedResult handleResult( - CommittedBundle inputBundle, InProcessTransformResult result); - - /** - * Handle an input bundle that did not require processing. - * - *

              This occurs when a Source has no splits that can currently produce outputs. - */ - void handleEmpty(AppliedPTransform transform); - - /** - * Handle a result that terminated abnormally due to the provided {@link Throwable}. - */ - void handleThrowable(CommittedBundle inputBundle, Throwable t); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java deleted file mode 100644 index 42704b162b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitor.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.PValue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Tracks the {@link AppliedPTransform AppliedPTransforms} that consume each {@link PValue} in the - * {@link Pipeline}. This is used to schedule consuming {@link PTransform PTransforms} to consume - * input after the upstream transform has produced and committed output. - */ -class ConsumerTrackingPipelineVisitor implements PipelineVisitor { - private Map>> valueToConsumers = new HashMap<>(); - private Collection> rootTransforms = new ArrayList<>(); - private Collection> views = new ArrayList<>(); - private Map, String> stepNames = new HashMap<>(); - private Set toFinalize = new HashSet<>(); - private int numTransforms = 0; - private boolean finalized = false; - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - checkState( - !finalized, - "Attempting to traverse a pipeline (node %s) with a %s " - + "which has already visited a Pipeline and is finalized", - node.getFullName(), - ConsumerTrackingPipelineVisitor.class.getSimpleName()); - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - checkState( - !finalized, - "Attempting to traverse a pipeline (node %s) with a %s which is already finalized", - node.getFullName(), - ConsumerTrackingPipelineVisitor.class.getSimpleName()); - if (node.isRootNode()) { - finalized = true; - } - } - - @Override - public void visitTransform(TransformTreeNode node) { - toFinalize.removeAll(node.getInput().expand()); - AppliedPTransform appliedTransform = getAppliedTransform(node); - stepNames.put(appliedTransform, genStepName()); - if (node.getInput().expand().isEmpty()) { - rootTransforms.add(appliedTransform); - } else { - for (PValue value : node.getInput().expand()) { - valueToConsumers.get(value).add(appliedTransform); - } - } - } - - private AppliedPTransform getAppliedTransform(TransformTreeNode node) { - @SuppressWarnings({"rawtypes", "unchecked"}) - AppliedPTransform application = AppliedPTransform.of( - node.getFullName(), node.getInput(), node.getOutput(), (PTransform) node.getTransform()); - return application; - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - toFinalize.add(value); - for (PValue expandedValue : value.expand()) { - valueToConsumers.put(expandedValue, new ArrayList>()); - if (expandedValue instanceof PCollectionView) { - views.add((PCollectionView) expandedValue); - } - expandedValue.recordAsOutput(getAppliedTransform(producer)); - } - value.recordAsOutput(getAppliedTransform(producer)); - } - - private String genStepName() { - return String.format("s%s", numTransforms++); - } - - - /** - * Returns a mapping of each fully-expanded {@link PValue} to each - * {@link AppliedPTransform} that consumes it. For each AppliedPTransform in the collection - * returned from {@code getValueToCustomers().get(PValue)}, - * {@code AppliedPTransform#getInput().expand()} will contain the argument {@link PValue}. - */ - public Map>> getValueToConsumers() { - checkState( - finalized, - "Can't call getValueToConsumers before the Pipeline has been completely traversed"); - - return valueToConsumers; - } - - /** - * Returns the mapping for each {@link AppliedPTransform} in the {@link Pipeline} to a unique step - * name. - */ - public Map, String> getStepNames() { - checkState( - finalized, "Can't call getStepNames before the Pipeline has been completely traversed"); - - return stepNames; - } - - /** - * Returns the root transforms of the {@link Pipeline}. A root {@link AppliedPTransform} consumes - * a {@link PInput} where the {@link PInput#expand()} returns an empty collection. - */ - public Collection> getRootTransforms() { - checkState( - finalized, - "Can't call getRootTransforms before the Pipeline has been completely traversed"); - - return rootTransforms; - } - - /** - * Returns all of the {@link PCollectionView PCollectionViews} contained in the visited - * {@link Pipeline}. - */ - public Collection> getViews() { - checkState(finalized, "Can't call getViews before the Pipeline has been completely traversed"); - - return views; - } - - /** - * Returns all of the {@link PValue PValues} that have been produced but not consumed. These - * {@link PValue PValues} should be finalized by the {@link PipelineRunner} before the - * {@link Pipeline} is executed. - */ - public Set getUnfinalizedPValues() { - checkState( - finalized, - "Can't call getUnfinalizedPValues before the Pipeline has been completely traversed"); - - return toFinalize; - } -} - - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java deleted file mode 100644 index a0d9b86fb9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/DisplayDataValidator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.values.PValue; - -/** - * Validate correct implementation of {@link DisplayData} by evaluating - * {@link HasDisplayData#populateDisplayData(DisplayData.Builder)} during pipeline construction. - */ -class DisplayDataValidator { - // Do not instantiate - private DisplayDataValidator() {} - - static void validatePipeline(Pipeline pipeline) { - validateOptions(pipeline); - validateTransforms(pipeline); - } - - private static void validateOptions(Pipeline pipeline) { - evaluateDisplayData(pipeline.getOptions()); - } - - private static void validateTransforms(Pipeline pipeline) { - pipeline.traverseTopologically(Visitor.INSTANCE); - } - - private static void evaluateDisplayData(HasDisplayData component) { - DisplayData.from(component); - } - - private static class Visitor implements Pipeline.PipelineVisitor { - private static final Visitor INSTANCE = new Visitor(); - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - if (!node.isRootNode()) { - evaluateDisplayData(node.getTransform()); - } - } - - @Override - public void visitTransform(TransformTreeNode node) { - evaluateDisplayData(node.getTransform()); - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) {} - - @Override - public void visitValue(PValue value, TransformTreeNode producer) {} - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EmptyTransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EmptyTransformEvaluator.java deleted file mode 100644 index fc09237794..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EmptyTransformEvaluator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -/** - * A {@link TransformEvaluator} that ignores all input and produces no output. The result of - * invoking {@link #finishBundle()} on this evaluator is to return an - * {@link InProcessTransformResult} with no elements and a timestamp hold equal to - * {@link BoundedWindow#TIMESTAMP_MIN_VALUE}. Because the result contains no elements, this hold - * will not affect the watermark. - */ -final class EmptyTransformEvaluator implements TransformEvaluator { - public static TransformEvaluator create(AppliedPTransform transform) { - return new EmptyTransformEvaluator(transform); - } - - private final AppliedPTransform transform; - - private EmptyTransformEvaluator(AppliedPTransform transform) { - this.transform = transform; - } - - @Override - public void processElement(WindowedValue element) throws Exception {} - - @Override - public InProcessTransformResult finishBundle() throws Exception { - return StepTransformResult.withHold(transform, BoundedWindow.TIMESTAMP_MIN_VALUE) - .build(); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java deleted file mode 100644 index 5b13949dde..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactory.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * Enforces that all elements in a {@link PCollection} can be encoded using that - * {@link PCollection PCollection's} {@link Coder}. - */ -class EncodabilityEnforcementFactory implements ModelEnforcementFactory { - public static EncodabilityEnforcementFactory create() { - return new EncodabilityEnforcementFactory(); - } - - @Override - public ModelEnforcement forBundle( - CommittedBundle input, AppliedPTransform consumer) { - return new EncodabilityEnforcement<>(input); - } - - private static class EncodabilityEnforcement extends AbstractModelEnforcement { - private Coder coder; - - public EncodabilityEnforcement(CommittedBundle input) { - coder = input.getPCollection().getCoder(); - } - - @Override - public void beforeElement(WindowedValue element) { - try { - T clone = CoderUtils.clone(coder, element.getValue()); - if (coder.consistentWithEquals()) { - checkArgument( - coder.structuralValue(element.getValue()).equals(coder.structuralValue(clone)), - "Coder %s of class %s does not maintain structural value equality" - + " on input element %s", - coder, - coder.getClass().getSimpleName(), - element.getValue()); - } - } catch (Exception e) { - throw UserCodeException.wrap(e); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java deleted file mode 100644 index f6aafcc1b3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/EvaluatorKey.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; - -import java.util.Objects; - -/** - * A (Transform, Pipeline Execution) key for stateful evaluators. - * - *

              Source evaluators are stateful to ensure data is not read multiple times. Evaluators are - * cached to ensure that the reader is not restarted if the evaluator is retriggered. An - * {@link EvaluatorKey} is used to ensure that multiple Pipelines can be executed without sharing - * the same evaluators. - */ -final class EvaluatorKey { - private final AppliedPTransform transform; - private final InProcessEvaluationContext context; - - public EvaluatorKey(AppliedPTransform transform, InProcessEvaluationContext context) { - this.transform = transform; - this.context = context; - } - - @Override - public int hashCode() { - return Objects.hash(transform, context); - } - - @Override - public boolean equals(Object other) { - if (other == null || !(other instanceof EvaluatorKey)) { - return false; - } - EvaluatorKey that = (EvaluatorKey) other; - return Objects.equals(this.transform, that.transform) - && Objects.equals(this.context, that.context); - } -} - - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java deleted file mode 100644 index 480bcdefed..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import java.util.concurrent.ExecutorService; - -/** - * A factory that creates {@link ExecutorService ExecutorServices}. - * {@link ExecutorService ExecutorServices} created by this factory should be independent of one - * another (e.g., if any executor is shut down the remaining executors should continue to process - * work). - */ -public interface ExecutorServiceFactory { - /** - * Create a new {@link ExecutorService}. - */ - ExecutorService create(); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java deleted file mode 100644 index 88c93f795c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ExecutorServiceParallelExecutor.java +++ /dev/null @@ -1,513 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.auto.value.AutoValue; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItems; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.base.MoreObjects; -import com.google.common.base.Optional; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Nullable; - -/** - * An {@link InProcessExecutor} that uses an underlying {@link ExecutorService} and - * {@link InProcessEvaluationContext} to execute a {@link Pipeline}. - */ -final class ExecutorServiceParallelExecutor implements InProcessExecutor { - private static final Logger LOG = LoggerFactory.getLogger(ExecutorServiceParallelExecutor.class); - - private final ExecutorService executorService; - - private final Map>> valueToConsumers; - private final Set keyedPValues; - private final TransformEvaluatorRegistry registry; - @SuppressWarnings("rawtypes") - private final Map, Collection> - transformEnforcements; - - private final InProcessEvaluationContext evaluationContext; - - private final LoadingCache executorServices; - - private final Queue allUpdates; - private final BlockingQueue visibleUpdates; - - private final TransformExecutorService parallelExecutorService; - private final CompletionCallback defaultCompletionCallback; - - private Collection> rootNodes; - - private final AtomicReference state = - new AtomicReference<>(ExecutorState.QUIESCENT); - - /** - * Measures the number of {@link TransformExecutor TransformExecutors} that have been scheduled - * but not yet completed. - * - *

              Before a {@link TransformExecutor} is scheduled, this value is incremented. All methods in - * {@link CompletionCallback} decrement this value. - */ - private final AtomicLong outstandingWork = new AtomicLong(); - - public static ExecutorServiceParallelExecutor create( - ExecutorService executorService, - Map>> valueToConsumers, - Set keyedPValues, - TransformEvaluatorRegistry registry, - @SuppressWarnings("rawtypes") - Map, Collection> transformEnforcements, - InProcessEvaluationContext context) { - return new ExecutorServiceParallelExecutor( - executorService, valueToConsumers, keyedPValues, registry, transformEnforcements, context); - } - - private ExecutorServiceParallelExecutor( - ExecutorService executorService, - Map>> valueToConsumers, - Set keyedPValues, - TransformEvaluatorRegistry registry, - @SuppressWarnings("rawtypes") - Map, Collection> transformEnforcements, - InProcessEvaluationContext context) { - this.executorService = executorService; - this.valueToConsumers = valueToConsumers; - this.keyedPValues = keyedPValues; - this.registry = registry; - this.transformEnforcements = transformEnforcements; - this.evaluationContext = context; - - // Weak Values allows TransformExecutorServices that are no longer in use to be reclaimed. - // Executing TransformExecutorServices have a strong reference to their TransformExecutorService - // which stops the TransformExecutorServices from being prematurely garbage collected - executorServices = - CacheBuilder.newBuilder().weakValues().build(serialTransformExecutorServiceCacheLoader()); - - this.allUpdates = new ConcurrentLinkedQueue<>(); - this.visibleUpdates = new ArrayBlockingQueue<>(20); - - parallelExecutorService = TransformExecutorServices.parallel(executorService); - defaultCompletionCallback = - new TimerIterableCompletionCallback(Collections.emptyList()); - } - - private CacheLoader - serialTransformExecutorServiceCacheLoader() { - return new CacheLoader() { - @Override - public TransformExecutorService load(StepAndKey stepAndKey) throws Exception { - return TransformExecutorServices.serial(executorService); - } - }; - } - - @Override - public void start(Collection> roots) { - rootNodes = ImmutableList.copyOf(roots); - Runnable monitorRunnable = new MonitorRunnable(); - executorService.submit(monitorRunnable); - } - - @SuppressWarnings("unchecked") - public void scheduleConsumption( - AppliedPTransform consumer, - @Nullable CommittedBundle bundle, - CompletionCallback onComplete) { - evaluateBundle(consumer, bundle, onComplete); - } - - private void evaluateBundle( - final AppliedPTransform transform, - @Nullable final CommittedBundle bundle, - final CompletionCallback onComplete) { - TransformExecutorService transformExecutor; - - if (bundle != null && isKeyed(bundle.getPCollection())) { - final StepAndKey stepAndKey = - StepAndKey.of(transform, bundle == null ? null : bundle.getKey()); - // This executor will remain reachable until it has executed all scheduled transforms. - // The TransformExecutors keep a strong reference to the Executor, the ExecutorService keeps - // a reference to the scheduled TransformExecutor callable. Follow-up TransformExecutors - // (scheduled due to the completion of another TransformExecutor) are provided to the - // ExecutorService before the Earlier TransformExecutor callable completes. - transformExecutor = executorServices.getUnchecked(stepAndKey); - } else { - transformExecutor = parallelExecutorService; - } - - Collection enforcements = - MoreObjects.firstNonNull( - transformEnforcements.get(transform.getTransform().getClass()), - Collections.emptyList()); - - TransformExecutor callable = - TransformExecutor.create( - registry, - enforcements, - evaluationContext, - bundle, - transform, - onComplete, - transformExecutor); - outstandingWork.incrementAndGet(); - transformExecutor.schedule(callable); - } - - private boolean isKeyed(PValue pvalue) { - return keyedPValues.contains(pvalue); - } - - private void scheduleConsumers(ExecutorUpdate update) { - CommittedBundle bundle = update.getBundle().get(); - for (AppliedPTransform consumer : update.getConsumers()) { - scheduleConsumption(consumer, bundle, defaultCompletionCallback); - } - } - - @Override - public void awaitCompletion() throws Throwable { - VisibleExecutorUpdate update; - do { - // Get an update; don't block forever if another thread has handled it - update = visibleUpdates.poll(2L, TimeUnit.SECONDS); - if (update == null && executorService.isShutdown()) { - // there are no updates to process and no updates will ever be published because the - // executor is shutdown - return; - } else if (update != null && update.throwable.isPresent()) { - throw update.throwable.get(); - } - } while (update == null || !update.isDone()); - executorService.shutdown(); - } - - /** - * The base implementation of {@link CompletionCallback} that provides implementations for - * {@link #handleResult(CommittedBundle, InProcessTransformResult)} and - * {@link #handleThrowable(CommittedBundle, Throwable)}. - */ - private class TimerIterableCompletionCallback implements CompletionCallback { - private final Iterable timers; - - protected TimerIterableCompletionCallback(Iterable timers) { - this.timers = timers; - } - - @Override - public final CommittedResult handleResult( - CommittedBundle inputBundle, InProcessTransformResult result) { - CommittedResult committedResult = evaluationContext.handleResult(inputBundle, timers, result); - for (CommittedBundle outputBundle : committedResult.getOutputs()) { - allUpdates.offer(ExecutorUpdate.fromBundle(outputBundle, - valueToConsumers.get(outputBundle.getPCollection()))); - } - CommittedBundle unprocessedInputs = committedResult.getUnprocessedInputs(); - if (unprocessedInputs != null && !Iterables.isEmpty(unprocessedInputs.getElements())) { - allUpdates.offer(ExecutorUpdate.fromBundle(unprocessedInputs, - Collections.>singleton(committedResult.getTransform()))); - } - if (!committedResult.getProducedOutputTypes().isEmpty()) { - state.set(ExecutorState.ACTIVE); - } - outstandingWork.decrementAndGet(); - return committedResult; - } - - @Override - public void handleEmpty(AppliedPTransform transform) { - outstandingWork.decrementAndGet(); - } - - @Override - public final void handleThrowable(CommittedBundle inputBundle, Throwable t) { - allUpdates.offer(ExecutorUpdate.fromThrowable(t)); - outstandingWork.decrementAndGet(); - } - } - /** - * An internal status update on the state of the executor. - * - *

              Used to signal when the executor should be shut down (due to an exception). - */ - @AutoValue - abstract static class ExecutorUpdate { - public static ExecutorUpdate fromBundle( - CommittedBundle bundle, - Collection> consumers) { - return new AutoValue_ExecutorServiceParallelExecutor_ExecutorUpdate( - Optional.of(bundle), - consumers, - Optional.absent()); - } - - public static ExecutorUpdate fromThrowable(Throwable t) { - return new AutoValue_ExecutorServiceParallelExecutor_ExecutorUpdate( - Optional.>absent(), - Collections.>emptyList(), - Optional.of(t)); - } - - /** - * Returns the bundle that produced this update. - */ - public abstract Optional> getBundle(); - - /** - * Returns the transforms to process the bundle. If nonempty, {@link #getBundle()} will return - * a present {@link Optional}. - */ - public abstract Collection> getConsumers(); - - public abstract Optional getException(); - } - - /** - * An update of interest to the user. Used in {@link #awaitCompletion} to decide whether to - * return normally or throw an exception. - */ - private static class VisibleExecutorUpdate { - private final Optional throwable; - private final boolean done; - - public static VisibleExecutorUpdate fromThrowable(Throwable e) { - return new VisibleExecutorUpdate(false, e); - } - - public static VisibleExecutorUpdate finished() { - return new VisibleExecutorUpdate(true, null); - } - - private VisibleExecutorUpdate(boolean done, @Nullable Throwable exception) { - this.throwable = Optional.fromNullable(exception); - this.done = done; - } - - public boolean isDone() { - return done; - } - } - - private class MonitorRunnable implements Runnable { - // arbitrary termination condition to ensure progress in the presence of pushback - private final long maxTimeProcessingUpdatesNanos = TimeUnit.MILLISECONDS.toNanos(5L); - private final String runnableName = String.format("%s$%s-monitor", - evaluationContext.getPipelineOptions().getAppName(), - ExecutorServiceParallelExecutor.class.getSimpleName()); - - private boolean exceptionThrown = false; - - @Override - public void run() { - String oldName = Thread.currentThread().getName(); - Thread.currentThread().setName(runnableName); - try { - boolean noWorkOutstanding = outstandingWork.get() == 0L; - ExecutorState startingState = state.get(); - if (startingState == ExecutorState.ACTIVE) { - // The remainder of this call will add all available work to the Executor, and there will - // be no new work available - state.compareAndSet(ExecutorState.ACTIVE, ExecutorState.PROCESSING); - } else if (startingState == ExecutorState.PROCESSING && noWorkOutstanding) { - // The executor has consumed all new work and no new work was added - state.compareAndSet(ExecutorState.PROCESSING, ExecutorState.QUIESCING); - } else if (startingState == ExecutorState.QUIESCING && noWorkOutstanding) { - // The executor re-ran all blocked work and nothing could make progress. - state.compareAndSet(ExecutorState.QUIESCING, ExecutorState.QUIESCENT); - } - fireTimers(); - Collection updates = new ArrayList<>(); - // Pull all available updates off of the queue before adding additional work. This ensures - // both loops terminate. - ExecutorUpdate pendingUpdate = allUpdates.poll(); - while (pendingUpdate != null) { - updates.add(pendingUpdate); - pendingUpdate = allUpdates.poll(); - } - for (ExecutorUpdate update : updates) { - LOG.debug("Executor Update: {}", update); - if (update.getBundle().isPresent()) { - if (ExecutorState.ACTIVE == startingState || (ExecutorState.PROCESSING == startingState - && noWorkOutstanding)) { - scheduleConsumers(update); - } else { - allUpdates.offer(update); - } - } else if (update.getException().isPresent()) { - visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(update.getException().get())); - exceptionThrown = true; - } - } - addWorkIfNecessary(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOG.error("Monitor died due to being interrupted"); - while (!visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(e))) { - visibleUpdates.poll(); - } - } catch (Throwable t) { - LOG.error("Monitor thread died due to throwable", t); - while (!visibleUpdates.offer(VisibleExecutorUpdate.fromThrowable(t))) { - visibleUpdates.poll(); - } - } finally { - if (!shouldShutdown()) { - // The monitor thread should always be scheduled; but we only need to be scheduled once - executorService.submit(this); - } - Thread.currentThread().setName(oldName); - } - } - - /** - * Fires any available timers. Returns true if at least one timer was fired. - */ - private void fireTimers() throws Exception { - try { - for (Map.Entry< - AppliedPTransform, Map, FiredTimers>> transformTimers : - evaluationContext.extractFiredTimers().entrySet()) { - AppliedPTransform transform = transformTimers.getKey(); - for (Map.Entry, FiredTimers> keyTimers : - transformTimers.getValue().entrySet()) { - for (TimeDomain domain : TimeDomain.values()) { - Collection delivery = keyTimers.getValue().getTimers(domain); - if (delivery.isEmpty()) { - continue; - } - KeyedWorkItem work = - KeyedWorkItems.timersWorkItem(keyTimers.getKey().getKey(), delivery); - @SuppressWarnings({"unchecked", "rawtypes"}) - CommittedBundle bundle = - evaluationContext - .createKeyedBundle( - null, keyTimers.getKey(), (PCollection) transform.getInput()) - .add(WindowedValue.valueInEmptyWindows(work)) - .commit(evaluationContext.now()); - state.set(ExecutorState.ACTIVE); - scheduleConsumption(transform, bundle, new TimerIterableCompletionCallback(delivery)); - } - } - } - } catch (Exception e) { - LOG.error("Internal Error while delivering timers", e); - throw e; - } - } - - private boolean shouldShutdown() { - boolean shouldShutdown = exceptionThrown || evaluationContext.isDone(); - if (shouldShutdown) { - if (evaluationContext.isDone()) { - LOG.debug("Pipeline is finished. Shutting down. {}"); - while (!visibleUpdates.offer(VisibleExecutorUpdate.finished())) { - visibleUpdates.poll(); - } - executorService.shutdown(); - } - } - return shouldShutdown; - } - - /** - * If all active {@link TransformExecutor TransformExecutors} are in a blocked state, - * add more work from root nodes that may have additional work. This ensures that if a pipeline - * has elements available from the root nodes it will add those elements when necessary. - */ - private void addWorkIfNecessary() { - // If any timers have fired, they will add more work; We don't need to add more - if (state.get() == ExecutorState.QUIESCENT) { - // All current TransformExecutors are blocked; add more work from the roots. - for (AppliedPTransform root : rootNodes) { - if (!evaluationContext.isDone(root)) { - scheduleConsumption(root, null, defaultCompletionCallback); - state.set(ExecutorState.ACTIVE); - } - } - } - } - } - - - /** - * The state of the executor. The state of the executor determines the behavior of the - * {@link MonitorRunnable} when it runs. - */ - private enum ExecutorState { - /** - * Output has been produced since the last time the monitor ran. Work exists that has not yet - * been evaluated, and all pending, including potentially blocked work, should be evaluated. - * - *

              The executor becomes active whenever a timer fires, a {@link PCollectionView} is updated, - * or output is produced by the evaluation of a {@link TransformExecutor}. - */ - ACTIVE, - /** - * The Executor does not have any unevaluated work available to it, but work is in progress. - * Work should not be added until the Executor becomes active or no work is outstanding. - * - *

              If all outstanding work completes without the executor becoming {@code ACTIVE}, the - * Executor enters state {@code QUIESCING}. Previously evaluated work must be reevaluated, in - * case a side input has made progress. - */ - PROCESSING, - /** - * All outstanding work is work that may be blocked on a side input. When there is no - * outstanding work, the executor becomes {@code QUIESCENT}. - */ - QUIESCING, - /** - * All elements are either buffered in state or are blocked on a side input. There are no - * timers that are permitted to fire but have not. There is no outstanding work. - * - *

              The pipeline will not make progress without the progression of watermarks, the progression - * of processing time, or the addition of elements. - */ - QUIESCENT - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FixedThreadPoolExecutorServiceFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FixedThreadPoolExecutorServiceFactory.java deleted file mode 100644 index d71b1b0ae8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FixedThreadPoolExecutorServiceFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * A {@link ExecutorServiceFactory} that produces fixed thread pools via - * {@link Executors#newFixedThreadPool(int)}, with the number of threads equal to the available - * processors as provided by {@link Runtime#availableProcessors()}. - */ -class FixedThreadPoolExecutorServiceFactory - implements DefaultValueFactory, ExecutorServiceFactory { - private static final FixedThreadPoolExecutorServiceFactory INSTANCE = - new FixedThreadPoolExecutorServiceFactory(); - - @Override - public ExecutorServiceFactory create(PipelineOptions options) { - return INSTANCE; - } - - @Override - public ExecutorService create() { - return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java deleted file mode 100644 index bde1df45e9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactory.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -/** - * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the {@link Flatten} - * {@link PTransform}. - */ -class FlattenEvaluatorFactory implements TransformEvaluatorFactory { - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public TransformEvaluator forApplication( - AppliedPTransform application, - CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) { - return createInMemoryEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); - } - - private TransformEvaluator createInMemoryEvaluator( - final AppliedPTransform< - PCollectionList, PCollection, FlattenPCollectionList> - application, - final CommittedBundle inputBundle, - final InProcessEvaluationContext evaluationContext) { - if (inputBundle == null) { - // it is impossible to call processElement on a flatten with no input bundle. A Flatten with - // no input bundle occurs as an output of Flatten.pcollections(PCollectionList.empty()) - return new FlattenEvaluator<>( - null, StepTransformResult.withoutHold(application).build()); - } - final UncommittedBundle outputBundle = - evaluationContext.createBundle(inputBundle, application.getOutput()); - final InProcessTransformResult result = - StepTransformResult.withoutHold(application).addOutput(outputBundle).build(); - return new FlattenEvaluator<>(outputBundle, result); - } - - private static class FlattenEvaluator implements TransformEvaluator { - private final UncommittedBundle outputBundle; - private final InProcessTransformResult result; - - public FlattenEvaluator( - UncommittedBundle outputBundle, InProcessTransformResult result) { - this.outputBundle = outputBundle; - this.result = result; - } - - @Override - public void processElement(WindowedValue element) { - outputBundle.add(element); - } - - @Override - public InProcessTransformResult finishBundle() { - return result; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java deleted file mode 100644 index cd04336d05..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransform.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.TypedPValue; - -/** - * A base class for implementing {@link PTransform} overrides, which behave identically to the - * delegate transform but with overridden methods. Implementors are required to implement - * {@link #delegate()}, which returns the object to forward calls to, and {@link #apply(PInput)}. - */ -public abstract class ForwardingPTransform - extends PTransform { - protected abstract PTransform delegate(); - - @Override - public OutputT apply(InputT input) { - return delegate().apply(input); - } - - @Override - public void validate(InputT input) { - delegate().validate(input); - } - - @Override - public String getName() { - return delegate().getName(); - } - - @Override - public Coder getDefaultOutputCoder(InputT input, @SuppressWarnings("unused") - TypedPValue output) throws CannotProvideCoderException { - return delegate().getDefaultOutputCoder(input, output); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - delegate().populateDisplayData(builder); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java deleted file mode 100644 index 2dacf665ae..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactory.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.StepTransformResult.Builder; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey.ReifyTimestampsAndWindows; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowViaWindowSetDoFn; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItemCoder; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItems; -import com.google.cloud.dataflow.sdk.util.SystemReduceFn; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.annotations.VisibleForTesting; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the {@link GroupByKey} - * {@link PTransform}. - */ -class GroupByKeyEvaluatorFactory implements TransformEvaluatorFactory { - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public TransformEvaluator forApplication( - AppliedPTransform application, - CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) { - @SuppressWarnings({"cast", "unchecked", "rawtypes"}) - TransformEvaluator evaluator = createEvaluator( - (AppliedPTransform) application, (CommittedBundle) inputBundle, evaluationContext); - return evaluator; - } - - private TransformEvaluator>> createEvaluator( - final AppliedPTransform< - PCollection>>, PCollection>, - InProcessGroupByKeyOnly> - application, - final CommittedBundle> inputBundle, - final InProcessEvaluationContext evaluationContext) { - return new GroupByKeyEvaluator(evaluationContext, inputBundle, application); - } - - private static class GroupByKeyEvaluator - implements TransformEvaluator>> { - private final InProcessEvaluationContext evaluationContext; - - private final CommittedBundle> inputBundle; - private final AppliedPTransform< - PCollection>>, PCollection>, - InProcessGroupByKeyOnly> - application; - private final Coder keyCoder; - private Map, List>> groupingMap; - - public GroupByKeyEvaluator( - InProcessEvaluationContext evaluationContext, - CommittedBundle> inputBundle, - AppliedPTransform< - PCollection>>, PCollection>, - InProcessGroupByKeyOnly> - application) { - this.evaluationContext = evaluationContext; - this.inputBundle = inputBundle; - this.application = application; - - PCollection>> input = application.getInput(); - keyCoder = getKeyCoder(input.getCoder()); - groupingMap = new HashMap<>(); - } - - private Coder getKeyCoder(Coder>> coder) { - if (!(coder instanceof KvCoder)) { - throw new IllegalStateException(); - } - @SuppressWarnings("unchecked") - Coder keyCoder = ((KvCoder>) coder).getKeyCoder(); - return keyCoder; - } - - @Override - public void processElement(WindowedValue>> element) { - KV> kv = element.getValue(); - K key = kv.getKey(); - byte[] encodedKey; - try { - encodedKey = encodeToByteArray(keyCoder, key); - } catch (CoderException exn) { - // TODO: Put in better element printing: - // truncate if too long. - throw new IllegalArgumentException( - String.format("unable to encode key %s of input to %s using %s", key, this, keyCoder), - exn); - } - GroupingKey groupingKey = new GroupingKey<>(key, encodedKey); - List> values = groupingMap.get(groupingKey); - if (values == null) { - values = new ArrayList>(); - groupingMap.put(groupingKey, values); - } - values.add(kv.getValue()); - } - - @Override - public InProcessTransformResult finishBundle() { - Builder resultBuilder = StepTransformResult.withoutHold(application); - for (Map.Entry, List>> groupedEntry : - groupingMap.entrySet()) { - K key = groupedEntry.getKey().key; - KeyedWorkItem groupedKv = - KeyedWorkItems.elementsWorkItem(key, groupedEntry.getValue()); - UncommittedBundle> bundle = evaluationContext.createKeyedBundle( - inputBundle, - StructuralKey.of(key, keyCoder), - application.getOutput()); - bundle.add(WindowedValue.valueInGlobalWindow(groupedKv)); - resultBuilder.addOutput(bundle); - } - return resultBuilder.build(); - } - - private static class GroupingKey { - private K key; - private byte[] encodedKey; - - public GroupingKey(K key, byte[] encodedKey) { - this.key = key; - this.encodedKey = encodedKey; - } - - @Override - public boolean equals(Object o) { - if (o instanceof GroupingKey) { - GroupingKey that = (GroupingKey) o; - return Arrays.equals(this.encodedKey, that.encodedKey); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Arrays.hashCode(encodedKey); - } - } - } - - /** - * A {@link PTransformOverrideFactory} for {@link GroupByKey} PTransforms. - */ - public static final class InProcessGroupByKeyOverrideFactory - implements PTransformOverrideFactory { - @Override - public PTransform override( - PTransform transform) { - if (transform instanceof GroupByKey) { - @SuppressWarnings({"rawtypes", "unchecked"}) - PTransform override = new InProcessGroupByKey((GroupByKey) transform); - return override; - } - return transform; - } - } - - /** - * An in-memory implementation of the {@link GroupByKey} primitive as a composite - * {@link PTransform}. - */ - private static final class InProcessGroupByKey - extends ForwardingPTransform>, PCollection>>> { - private final GroupByKey original; - - private InProcessGroupByKey(GroupByKey from) { - this.original = from; - } - - @Override - public PTransform>, PCollection>>> delegate() { - return original; - } - - @Override - public PCollection>> apply(PCollection> input) { - KvCoder inputCoder = (KvCoder) input.getCoder(); - - // This operation groups by the combination of key and window, - // merging windows as needed, using the windows assigned to the - // key/value input elements and the window merge operation of the - // window function associated with the input PCollection. - WindowingStrategy windowingStrategy = input.getWindowingStrategy(); - - // Use the default GroupAlsoByWindow implementation - DoFn, KV>> groupAlsoByWindow = - groupAlsoByWindow(windowingStrategy, inputCoder.getValueCoder()); - - // By default, implement GroupByKey via a series of lower-level operations. - return input - // Make each input element's timestamp and assigned windows - // explicit, in the value part. - .apply(new ReifyTimestampsAndWindows()) - - .apply(new InProcessGroupByKeyOnly()) - .setCoder(KeyedWorkItemCoder.of(inputCoder.getKeyCoder(), - inputCoder.getValueCoder(), input.getWindowingStrategy().getWindowFn().windowCoder())) - - // Group each key's values by window, merging windows as needed. - .apply("GroupAlsoByWindow", ParDo.of(groupAlsoByWindow)) - - // And update the windowing strategy as appropriate. - .setWindowingStrategyInternal(original.updateWindowingStrategy(windowingStrategy)) - .setCoder( - KvCoder.of(inputCoder.getKeyCoder(), IterableCoder.of(inputCoder.getValueCoder()))); - } - - private - DoFn, KV>> groupAlsoByWindow( - final WindowingStrategy windowingStrategy, final Coder inputCoder) { - return GroupAlsoByWindowViaWindowSetDoFn.create( - windowingStrategy, SystemReduceFn.buffering(inputCoder)); - } - } - - /** - * An implementation primitive to use in the evaluation of a {@link GroupByKey} - * {@link PTransform}. - */ - public static final class InProcessGroupByKeyOnly - extends PTransform>>, PCollection>> { - @Override - public PCollection> apply(PCollection>> input) { - return PCollection.>createPrimitiveOutputInternal( - input.getPipeline(), input.getWindowingStrategy(), input.isBounded()); - } - - @VisibleForTesting - InProcessGroupByKeyOnly() {} - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java deleted file mode 100644 index 4f7b73c9de..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactory.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.MutationDetector; -import com.google.cloud.dataflow.sdk.util.MutationDetectors; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.SetMultimap; - -import org.joda.time.Instant; - -/** - * A {@link BundleFactory} that ensures that elements added to it are not mutated after being - * output. Immutability checks are enforced at the time {@link UncommittedBundle#commit(Instant)} is - * called, checking the value at that time against the value at the time the element was added. All - * elements added to the bundle will be encoded by the {@link Coder} of the underlying - * {@link PCollection}. - * - *

              This catches errors during the execution of a {@link DoFn} caused by modifying an element - * after it is added to an output {@link PCollection}. - */ -class ImmutabilityCheckingBundleFactory implements BundleFactory { - /** - * Create a new {@link ImmutabilityCheckingBundleFactory} that uses the underlying - * {@link BundleFactory} to create the output bundle. - */ - public static ImmutabilityCheckingBundleFactory create(BundleFactory underlying) { - return new ImmutabilityCheckingBundleFactory(underlying); - } - - private final BundleFactory underlying; - - private ImmutabilityCheckingBundleFactory(BundleFactory underlying) { - this.underlying = checkNotNull(underlying); - } - - @Override - public UncommittedBundle createRootBundle(PCollection output) { - return new ImmutabilityEnforcingBundle<>(underlying.createRootBundle(output)); - } - - @Override - public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { - return new ImmutabilityEnforcingBundle<>(underlying.createBundle(input, output)); - } - - @Override - public UncommittedBundle createKeyedBundle( - CommittedBundle input, StructuralKey key, PCollection output) { - return new ImmutabilityEnforcingBundle<>(underlying.createKeyedBundle(input, key, output)); - } - - private static class ImmutabilityEnforcingBundle implements UncommittedBundle { - private final UncommittedBundle underlying; - private final SetMultimap, MutationDetector> mutationDetectors; - private Coder coder; - - public ImmutabilityEnforcingBundle(UncommittedBundle underlying) { - this.underlying = underlying; - mutationDetectors = HashMultimap.create(); - coder = getPCollection().getCoder(); - } - - @Override - public PCollection getPCollection() { - return underlying.getPCollection(); - } - - @Override - public UncommittedBundle add(WindowedValue element) { - try { - mutationDetectors.put( - element, MutationDetectors.forValueWithCoder(element.getValue(), coder)); - } catch (CoderException e) { - throw new RuntimeException(e); - } - underlying.add(element); - return this; - } - - @Override - public CommittedBundle commit(Instant synchronizedProcessingTime) { - for (MutationDetector detector : mutationDetectors.values()) { - try { - detector.verifyUnmodified(); - } catch (IllegalMutationException exn) { - throw UserCodeException.wrap( - new IllegalMutationException( - String.format( - "PTransform %s mutated value %s after it was output (new value was %s)." - + " Values must not be mutated in any way after being output.", - underlying.getPCollection().getProducingTransformInternal().getFullName(), - exn.getSavedValue(), - exn.getNewValue()), - exn.getSavedValue(), - exn.getNewValue(), - exn)); - } - } - return underlying.commit(synchronizedProcessingTime); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java deleted file mode 100644 index a7a37028ae..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.MutationDetector; -import com.google.cloud.dataflow.sdk.util.MutationDetectors; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -import java.util.IdentityHashMap; -import java.util.Map; - -/** - * {@link ModelEnforcement} that enforces elements are not modified over the course of processing - * an element. - * - *

              Implies {@link EncodabilityEnforcment}. - */ -class ImmutabilityEnforcementFactory implements ModelEnforcementFactory { - public static ModelEnforcementFactory create() { - return new ImmutabilityEnforcementFactory(); - } - - @Override - public ModelEnforcement forBundle( - CommittedBundle input, AppliedPTransform consumer) { - return new ImmutabilityCheckingEnforcement(input, consumer); - } - - private static class ImmutabilityCheckingEnforcement extends AbstractModelEnforcement { - private final AppliedPTransform transform; - private final Map, MutationDetector> mutationElements; - private final Coder coder; - - private ImmutabilityCheckingEnforcement( - CommittedBundle input, AppliedPTransform transform) { - this.transform = transform; - coder = input.getPCollection().getCoder(); - mutationElements = new IdentityHashMap<>(); - } - - @Override - public void beforeElement(WindowedValue element) { - try { - mutationElements.put( - element, MutationDetectors.forValueWithCoder(element.getValue(), coder)); - } catch (CoderException e) { - throw UserCodeException.wrap(e); - } - } - - @Override - public void afterElement(WindowedValue element) { - verifyUnmodified(mutationElements.get(element)); - } - - @Override - public void afterFinish( - CommittedBundle input, - InProcessTransformResult result, - Iterable> outputs) { - for (MutationDetector detector : mutationElements.values()) { - verifyUnmodified(detector); - } - } - - private void verifyUnmodified(MutationDetector detector) { - try { - detector.verifyUnmodified(); - } catch (IllegalMutationException e) { - throw new IllegalMutationException( - String.format( - "PTransform %s illegaly mutated value %s of class %s." - + " Input values must not be mutated in any way.", - transform.getFullName(), - e.getSavedValue(), - e.getSavedValue().getClass()), - e.getSavedValue(), - e.getNewValue()); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java deleted file mode 100644 index 9d145e8c09..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManager.java +++ /dev/null @@ -1,1407 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.auto.value.AutoValue; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ComparisonChain; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Ordering; -import com.google.common.collect.SortedMultiset; -import com.google.common.collect.TreeMultiset; -import org.joda.time.Instant; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.NavigableSet; -import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicReference; -import javax.annotation.Nullable; - -/** - * Manages watermarks of {@link PCollection PCollections} and input and output watermarks of - * {@link AppliedPTransform AppliedPTransforms} to provide event-time and completion tracking for - * in-memory execution. {@link InMemoryWatermarkManager} is designed to update and return a - * consistent view of watermarks in the presence of concurrent updates. - * - *

              An {@link InMemoryWatermarkManager} is provided with the collection of root - * {@link AppliedPTransform AppliedPTransforms} and a map of {@link PCollection PCollections} to - * all the {@link AppliedPTransform AppliedPTransforms} that consume them at construction time. - * - *

              Whenever a root {@link AppliedPTransform transform} produces elements, the - * {@link InMemoryWatermarkManager} is provided with the produced elements and the output watermark - * of the producing {@link AppliedPTransform transform}. The - * {@link InMemoryWatermarkManager watermark manager} is responsible for computing the watermarks - * of all {@link AppliedPTransform transforms} that consume one or more - * {@link PCollection PCollections}. - * - *

              Whenever a non-root {@link AppliedPTransform} finishes processing one or more in-flight - * elements (referred to as the input {@link CommittedBundle bundle}), the following occurs - * atomically: - *

                - *
              • All of the in-flight elements are removed from the collection of pending elements for the - * {@link AppliedPTransform}.
              • - *
              • All of the elements produced by the {@link AppliedPTransform} are added to the collection - * of pending elements for each {@link AppliedPTransform} that consumes them.
              • - *
              • The input watermark for the {@link AppliedPTransform} becomes the maximum value of - *
                  - *
                • the previous input watermark
                • - *
                • the minimum of - *
                    - *
                  • the timestamps of all currently pending elements
                  • - *
                  • all input {@link PCollection} watermarks
                  • - *
                  - *
                • - *
                - *
              • - *
              • The output watermark for the {@link AppliedPTransform} becomes the maximum of - *
                  - *
                • the previous output watermark
                • - *
                • the minimum of - *
                    - *
                  • the current input watermark
                  • - *
                  • the current watermark holds
                  • - *
                  - *
                • - *
                - *
              • - *
              • The watermark of the output {@link PCollection} can be advanced to the output watermark of - * the {@link AppliedPTransform}
              • - *
              • The watermark of all downstream {@link AppliedPTransform AppliedPTransforms} can be - * advanced.
              • - *
              - * - *

              The watermark of a {@link PCollection} is equal to the output watermark of the - * {@link AppliedPTransform} that produces it. - * - *

              The watermarks for a {@link PTransform} are updated as follows when output is committed:

              - * Watermark_In'  = MAX(Watermark_In, MIN(U(TS_Pending), U(Watermark_InputPCollection)))
              - * Watermark_Out' = MAX(Watermark_Out, MIN(Watermark_In', U(StateHold)))
              - * Watermark_PCollection = Watermark_Out_ProducingPTransform
              - * 
              - */ -class InMemoryWatermarkManager { - /** - * The watermark of some {@link Pipeline} element, usually a {@link PTransform} or a - * {@link PCollection}. - * - *

              A watermark is a monotonically increasing value, which represents the point up to which the - * system believes it has received all of the data. Data that arrives with a timestamp that is - * before the watermark is considered late. {@link BoundedWindow#TIMESTAMP_MAX_VALUE} is a special - * timestamp which indicates we have received all of the data and there will be no more on-time or - * late data. This value is represented by {@link InMemoryWatermarkManager#THE_END_OF_TIME}. - */ - private interface Watermark { - /** - * Returns the current value of this watermark. - */ - Instant get(); - - /** - * Refreshes the value of this watermark from its input watermarks and watermark holds. - * - * @return true if the value of the watermark has changed (and thus dependent watermark must - * also be updated - */ - WatermarkUpdate refresh(); - } - - /** - * The result of computing a {@link Watermark}. - */ - private enum WatermarkUpdate { - /** The watermark is later than the value at the previous time it was computed. */ - ADVANCED(true), - /** The watermark is equal to the value at the previous time it was computed. */ - NO_CHANGE(false); - - private final boolean advanced; - - private WatermarkUpdate(boolean advanced) { - this.advanced = advanced; - } - - public boolean isAdvanced() { - return advanced; - } - - /** - * Returns the {@link WatermarkUpdate} that is a result of combining the two watermark updates. - * - *

              If either of the input {@link WatermarkUpdate WatermarkUpdates} were advanced, the result - * {@link WatermarkUpdate} has been advanced. - */ - public WatermarkUpdate union(WatermarkUpdate that) { - if (this.advanced) { - return this; - } - return that; - } - - /** - * Returns the {@link WatermarkUpdate} based on the former and current - * {@link Instant timestamps}. - */ - public static WatermarkUpdate fromTimestamps(Instant oldTime, Instant currentTime) { - if (currentTime.isAfter(oldTime)) { - return ADVANCED; - } - return NO_CHANGE; - } - } - - /** - * The input {@link Watermark} of an {@link AppliedPTransform}. - * - *

              At any point, the value of an {@link AppliedPTransformInputWatermark} is equal to the - * minimum watermark across all of its input {@link Watermark Watermarks}, and the minimum - * timestamp of all of the pending elements, restricted to be monotonically increasing. - * - *

              See {@link #refresh()} for more information. - */ - private static class AppliedPTransformInputWatermark implements Watermark { - private final Collection inputWatermarks; - private final SortedMultiset> pendingElements; - private final Map, NavigableSet> objectTimers; - - private AtomicReference currentWatermark; - - public AppliedPTransformInputWatermark(Collection inputWatermarks) { - this.inputWatermarks = inputWatermarks; - this.pendingElements = TreeMultiset.create(new WindowedValueByTimestampComparator()); - this.objectTimers = new HashMap<>(); - currentWatermark = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); - } - - @Override - public Instant get() { - return currentWatermark.get(); - } - - /** - * {@inheritDoc}. - * - *

              When refresh is called, the value of the {@link AppliedPTransformInputWatermark} becomes - * equal to the maximum value of - *

                - *
              • the previous input watermark
              • - *
              • the minimum of - *
                  - *
                • the timestamps of all currently pending elements
                • - *
                • all input {@link PCollection} watermarks
                • - *
                - *
              • - *
              - */ - @Override - public synchronized WatermarkUpdate refresh() { - Instant oldWatermark = currentWatermark.get(); - Instant minInputWatermark = BoundedWindow.TIMESTAMP_MAX_VALUE; - for (Watermark inputWatermark : inputWatermarks) { - minInputWatermark = INSTANT_ORDERING.min(minInputWatermark, inputWatermark.get()); - } - if (!pendingElements.isEmpty()) { - minInputWatermark = INSTANT_ORDERING.min( - minInputWatermark, pendingElements.firstEntry().getElement().getTimestamp()); - } - Instant newWatermark = INSTANT_ORDERING.max(oldWatermark, minInputWatermark); - currentWatermark.set(newWatermark); - return WatermarkUpdate.fromTimestamps(oldWatermark, newWatermark); - } - - private synchronized void addPendingElements(Iterable> newPending) { - for (WindowedValue pendingElement : newPending) { - pendingElements.add(pendingElement); - } - } - - private synchronized void removePendingElements( - Iterable> finishedElements) { - for (WindowedValue finishedElement : finishedElements) { - pendingElements.remove(finishedElement); - } - } - - private synchronized void updateTimers(TimerUpdate update) { - NavigableSet keyTimers = objectTimers.get(update.key); - if (keyTimers == null) { - keyTimers = new TreeSet<>(); - objectTimers.put(update.key, keyTimers); - } - for (TimerData timer : update.setTimers) { - if (TimeDomain.EVENT_TIME.equals(timer.getDomain())) { - keyTimers.add(timer); - } - } - for (TimerData timer : update.deletedTimers) { - if (TimeDomain.EVENT_TIME.equals(timer.getDomain())) { - keyTimers.remove(timer); - } - } - // We don't keep references to timers that have been fired and delivered via #getFiredTimers() - } - - private synchronized Map, List> extractFiredEventTimeTimers() { - return extractFiredTimers(currentWatermark.get(), objectTimers); - } - - @Override - public synchronized String toString() { - return MoreObjects.toStringHelper(AppliedPTransformInputWatermark.class) - .add("pendingElements", pendingElements) - .add("currentWatermark", currentWatermark) - .toString(); - } - } - - /** - * The output {@link Watermark} of an {@link AppliedPTransform}. - * - *

              The value of an {@link AppliedPTransformOutputWatermark} is equal to the minimum of the - * current watermark hold and the {@link AppliedPTransformInputWatermark} for the same - * {@link AppliedPTransform}, restricted to be monotonically increasing. See - * {@link #refresh()} for more information. - */ - private static class AppliedPTransformOutputWatermark implements Watermark { - private final Watermark inputWatermark; - private final PerKeyHolds holds; - private AtomicReference currentWatermark; - - public AppliedPTransformOutputWatermark(AppliedPTransformInputWatermark inputWatermark) { - this.inputWatermark = inputWatermark; - holds = new PerKeyHolds(); - currentWatermark = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); - } - - public synchronized void updateHold(Object key, Instant newHold) { - if (newHold == null) { - holds.removeHold(key); - } else { - holds.updateHold(key, newHold); - } - } - - @Override - public Instant get() { - return currentWatermark.get(); - } - - /** - * {@inheritDoc}. - * - *

              When refresh is called, the value of the {@link AppliedPTransformOutputWatermark} becomes - * equal to the maximum value of: - *

                - *
              • the previous output watermark
              • - *
              • the minimum of - *
                  - *
                • the current input watermark
                • - *
                • the current watermark holds
                • - *
                - *
              • - *
              - */ - @Override - public synchronized WatermarkUpdate refresh() { - Instant oldWatermark = currentWatermark.get(); - Instant newWatermark = INSTANT_ORDERING.min(inputWatermark.get(), holds.getMinHold()); - newWatermark = INSTANT_ORDERING.max(oldWatermark, newWatermark); - currentWatermark.set(newWatermark); - return WatermarkUpdate.fromTimestamps(oldWatermark, newWatermark); - } - - @Override - public synchronized String toString() { - return MoreObjects.toStringHelper(AppliedPTransformOutputWatermark.class) - .add("holds", holds) - .add("currentWatermark", currentWatermark) - .toString(); - } - } - - /** - * The input {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} hold for an - * {@link AppliedPTransform}. - * - *

              At any point, the hold value of an {@link SynchronizedProcessingTimeInputWatermark} is equal - * to the minimum across all pending bundles at the {@link AppliedPTransform} and all upstream - * {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} watermarks. The value of the input - * synchronized processing time at any step is equal to the maximum of: - *

                - *
              • The most recently returned synchronized processing input time - *
              • The minimum of - *
                  - *
                • The current processing time - *
                • The current synchronized processing time input hold - *
                - *
              - */ - private static class SynchronizedProcessingTimeInputWatermark implements Watermark { - private final Collection inputWms; - private final Collection> pendingBundles; - private final Map, NavigableSet> processingTimers; - private final Map, NavigableSet> synchronizedProcessingTimers; - - private final NavigableSet pendingTimers; - - private AtomicReference earliestHold; - - public SynchronizedProcessingTimeInputWatermark(Collection inputWms) { - this.inputWms = inputWms; - this.pendingBundles = new HashSet<>(); - this.processingTimers = new HashMap<>(); - this.synchronizedProcessingTimers = new HashMap<>(); - this.pendingTimers = new TreeSet<>(); - Instant initialHold = BoundedWindow.TIMESTAMP_MAX_VALUE; - for (Watermark wm : inputWms) { - initialHold = INSTANT_ORDERING.min(initialHold, wm.get()); - } - earliestHold = new AtomicReference<>(initialHold); - } - - @Override - public Instant get() { - return earliestHold.get(); - } - - /** - * {@inheritDoc}. - * - *

              When refresh is called, the value of the {@link SynchronizedProcessingTimeInputWatermark} - * becomes equal to the minimum value of - *

                - *
              • the timestamps of all currently pending bundles
              • - *
              • all input {@link PCollection} synchronized processing time watermarks
              • - *
              - * - *

              Note that this value is not monotonic, but the returned value for the synchronized - * processing time must be. - */ - @Override - public synchronized WatermarkUpdate refresh() { - Instant oldHold = earliestHold.get(); - Instant minTime = THE_END_OF_TIME.get(); - for (Watermark input : inputWms) { - minTime = INSTANT_ORDERING.min(minTime, input.get()); - } - for (CommittedBundle bundle : pendingBundles) { - // TODO: Track elements in the bundle by the processing time they were output instead of - // entire bundles. Requried to support arbitrarily splitting and merging bundles between - // steps - minTime = INSTANT_ORDERING.min(minTime, bundle.getSynchronizedProcessingOutputWatermark()); - } - earliestHold.set(minTime); - return WatermarkUpdate.fromTimestamps(oldHold, minTime); - } - - public synchronized void addPending(CommittedBundle bundle) { - pendingBundles.add(bundle); - } - - public synchronized void removePending(CommittedBundle bundle) { - pendingBundles.remove(bundle); - } - - /** - * Return the earliest timestamp of the earliest timer that has not been completed. This is - * either the earliest timestamp across timers that have not been completed, or the earliest - * timestamp across timers that have been delivered but have not been completed. - */ - public synchronized Instant getEarliestTimerTimestamp() { - Instant earliest = THE_END_OF_TIME.get(); - for (NavigableSet timers : processingTimers.values()) { - if (!timers.isEmpty()) { - earliest = INSTANT_ORDERING.min(timers.first().getTimestamp(), earliest); - } - } - for (NavigableSet timers : synchronizedProcessingTimers.values()) { - if (!timers.isEmpty()) { - earliest = INSTANT_ORDERING.min(timers.first().getTimestamp(), earliest); - } - } - if (!pendingTimers.isEmpty()) { - earliest = INSTANT_ORDERING.min(pendingTimers.first().getTimestamp(), earliest); - } - return earliest; - } - - private synchronized void updateTimers(TimerUpdate update) { - Map> timerMap = timerMap(update.key); - for (TimerData addedTimer : update.setTimers) { - NavigableSet timerQueue = timerMap.get(addedTimer.getDomain()); - if (timerQueue != null) { - timerQueue.add(addedTimer); - } - } - - for (TimerData completedTimer : update.completedTimers) { - pendingTimers.remove(completedTimer); - } - for (TimerData deletedTimer : update.deletedTimers) { - NavigableSet timerQueue = timerMap.get(deletedTimer.getDomain()); - if (timerQueue != null) { - timerQueue.remove(deletedTimer); - } - } - } - - private synchronized Map, List> extractFiredDomainTimers( - TimeDomain domain, Instant firingTime) { - Map, List> firedTimers; - switch (domain) { - case PROCESSING_TIME: - firedTimers = extractFiredTimers(firingTime, processingTimers); - break; - case SYNCHRONIZED_PROCESSING_TIME: - firedTimers = - extractFiredTimers( - INSTANT_ORDERING.min(firingTime, earliestHold.get()), - synchronizedProcessingTimers); - break; - default: - throw new IllegalArgumentException( - "Called getFiredTimers on a Synchronized Processing Time watermark" - + " and gave a non-processing time domain " - + domain); - } - for (Map.Entry, ? extends Collection> firedTimer : - firedTimers.entrySet()) { - pendingTimers.addAll(firedTimer.getValue()); - } - return firedTimers; - } - - private Map> timerMap(StructuralKey key) { - NavigableSet processingQueue = processingTimers.get(key); - if (processingQueue == null) { - processingQueue = new TreeSet<>(); - processingTimers.put(key, processingQueue); - } - NavigableSet synchronizedProcessingQueue = - synchronizedProcessingTimers.get(key); - if (synchronizedProcessingQueue == null) { - synchronizedProcessingQueue = new TreeSet<>(); - synchronizedProcessingTimers.put(key, synchronizedProcessingQueue); - } - EnumMap> result = new EnumMap<>(TimeDomain.class); - result.put(TimeDomain.PROCESSING_TIME, processingQueue); - result.put(TimeDomain.SYNCHRONIZED_PROCESSING_TIME, synchronizedProcessingQueue); - return result; - } - - @Override - public synchronized String toString() { - return MoreObjects.toStringHelper(SynchronizedProcessingTimeInputWatermark.class) - .add("earliestHold", earliestHold) - .toString(); - } - } - - /** - * The output {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} hold for an - * {@link AppliedPTransform}. - * - *

              At any point, the hold value of an {@link SynchronizedProcessingTimeOutputWatermark} is - * equal to the minimum across all incomplete timers at the {@link AppliedPTransform} and all - * upstream {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} watermarks. The value of the output - * synchronized processing time at any step is equal to the maximum of: - *

                - *
              • The most recently returned synchronized processing output time - *
              • The minimum of - *
                  - *
                • The current processing time - *
                • The current synchronized processing time output hold - *
                - *
              - */ - private static class SynchronizedProcessingTimeOutputWatermark implements Watermark { - private final SynchronizedProcessingTimeInputWatermark inputWm; - private AtomicReference latestRefresh; - - public SynchronizedProcessingTimeOutputWatermark( - SynchronizedProcessingTimeInputWatermark inputWm) { - this.inputWm = inputWm; - this.latestRefresh = new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); - } - - @Override - public Instant get() { - return latestRefresh.get(); - } - - /** - * {@inheritDoc}. - * - *

              When refresh is called, the value of the {@link SynchronizedProcessingTimeOutputWatermark} - * becomes equal to the minimum value of: - *

                - *
              • the current input watermark. - *
              • all {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} timers that are based on the input - * watermark. - *
              • all {@link TimeDomain#PROCESSING_TIME} timers that are based on the input watermark. - *
              - * - *

              Note that this value is not monotonic, but the returned value for the synchronized - * processing time must be. - */ - @Override - public synchronized WatermarkUpdate refresh() { - // Hold the output synchronized processing time to the input watermark, which takes into - // account buffered bundles, and the earliest pending timer, which determines what to hold - // downstream timers to. - Instant oldRefresh = latestRefresh.get(); - Instant newTimestamp = - INSTANT_ORDERING.min(inputWm.get(), inputWm.getEarliestTimerTimestamp()); - latestRefresh.set(newTimestamp); - return WatermarkUpdate.fromTimestamps(oldRefresh, newTimestamp); - } - - @Override - public synchronized String toString() { - return MoreObjects.toStringHelper(SynchronizedProcessingTimeOutputWatermark.class) - .add("latestRefresh", latestRefresh) - .toString(); - } - } - - /** - * The {@code Watermark} that is after the latest time it is possible to represent in the global - * window. This is a distinguished value representing a complete {@link PTransform}. - */ - private static final Watermark THE_END_OF_TIME = new Watermark() { - @Override - public WatermarkUpdate refresh() { - // THE_END_OF_TIME is a distinguished value that cannot be advanced. - return WatermarkUpdate.NO_CHANGE; - } - - @Override - public Instant get() { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - }; - - private static final Ordering INSTANT_ORDERING = Ordering.natural(); - - /** - * A function that takes a WindowedValue and returns the exploded representation of that - * {@link WindowedValue}. - */ - private static final Function, ? extends Iterable>> - EXPLODE_WINDOWS_FN = - new Function, Iterable>>() { - @Override - public Iterable> apply(WindowedValue input) { - return input.explodeWindows(); - } - }; - - /** - * For each (Object, NavigableSet) pair in the provided map, remove each Timer that is before the - * latestTime argument and put in in the result with the same key, then remove all of the keys - * which have no more pending timers. - * - *

              The result collection retains ordering of timers (from earliest to latest). - */ - private static Map, List> extractFiredTimers( - Instant latestTime, Map, NavigableSet> objectTimers) { - Map, List> result = new HashMap<>(); - Set> emptyKeys = new HashSet<>(); - for (Map.Entry, NavigableSet> pendingTimers : - objectTimers.entrySet()) { - NavigableSet timers = pendingTimers.getValue(); - if (!timers.isEmpty() && timers.first().getTimestamp().isBefore(latestTime)) { - ArrayList keyFiredTimers = new ArrayList<>(); - result.put(pendingTimers.getKey(), keyFiredTimers); - while (!timers.isEmpty() && timers.first().getTimestamp().isBefore(latestTime)) { - keyFiredTimers.add(timers.first()); - timers.remove(timers.first()); - } - } - if (timers.isEmpty()) { - emptyKeys.add(pendingTimers.getKey()); - } - } - objectTimers.keySet().removeAll(emptyKeys); - return result; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * The {@link Clock} providing the current time in the {@link TimeDomain#PROCESSING_TIME} domain. - */ - private final Clock clock; - - /** - * A map from each {@link PCollection} to all {@link AppliedPTransform PTransform applications} - * that consume that {@link PCollection}. - */ - private final Map>> consumers; - - /** - * The input and output watermark of each {@link AppliedPTransform}. - */ - private final Map, TransformWatermarks> transformToWatermarks; - - /** - * A queue of pending updates to the state of this {@link InMemoryWatermarkManager}. - */ - private final ConcurrentLinkedQueue pendingUpdates; - - /** - * A queue of pending {@link AppliedPTransform AppliedPTransforms} that have potentially - * stale data. - */ - private final ConcurrentLinkedQueue> pendingRefreshes; - - /** - * Creates a new {@link InMemoryWatermarkManager}. All watermarks within the newly created - * {@link InMemoryWatermarkManager} start at {@link BoundedWindow#TIMESTAMP_MIN_VALUE}, the - * minimum watermark, with no watermark holds or pending elements. - * - * @param rootTransforms the root-level transforms of the {@link Pipeline} - * @param consumers a mapping between each {@link PCollection} in the {@link Pipeline} to the - * transforms that consume it as a part of their input - */ - public static InMemoryWatermarkManager create( - Clock clock, - Collection> rootTransforms, - Map>> consumers) { - return new InMemoryWatermarkManager(clock, rootTransforms, consumers); - } - - private InMemoryWatermarkManager( - Clock clock, - Collection> rootTransforms, - Map>> consumers) { - this.clock = clock; - this.consumers = consumers; - this.pendingUpdates = new ConcurrentLinkedQueue<>(); - this.pendingRefreshes = new ConcurrentLinkedQueue<>(); - - transformToWatermarks = new HashMap<>(); - - for (AppliedPTransform rootTransform : rootTransforms) { - getTransformWatermark(rootTransform); - } - for (Collection> intermediateTransforms : consumers.values()) { - for (AppliedPTransform transform : intermediateTransforms) { - getTransformWatermark(transform); - } - } - } - - private TransformWatermarks getTransformWatermark(AppliedPTransform transform) { - TransformWatermarks wms = transformToWatermarks.get(transform); - if (wms == null) { - List inputCollectionWatermarks = getInputWatermarks(transform); - AppliedPTransformInputWatermark inputWatermark = - new AppliedPTransformInputWatermark(inputCollectionWatermarks); - AppliedPTransformOutputWatermark outputWatermark = - new AppliedPTransformOutputWatermark(inputWatermark); - - SynchronizedProcessingTimeInputWatermark inputProcessingWatermark = - new SynchronizedProcessingTimeInputWatermark(getInputProcessingWatermarks(transform)); - SynchronizedProcessingTimeOutputWatermark outputProcessingWatermark = - new SynchronizedProcessingTimeOutputWatermark(inputProcessingWatermark); - - wms = - new TransformWatermarks( - inputWatermark, outputWatermark, inputProcessingWatermark, outputProcessingWatermark); - transformToWatermarks.put(transform, wms); - } - return wms; - } - - private Collection getInputProcessingWatermarks( - AppliedPTransform transform) { - ImmutableList.Builder inputWmsBuilder = ImmutableList.builder(); - Collection inputs = transform.getInput().expand(); - if (inputs.isEmpty()) { - inputWmsBuilder.add(THE_END_OF_TIME); - } - for (PValue pvalue : inputs) { - Watermark producerOutputWatermark = - getTransformWatermark(pvalue.getProducingTransformInternal()) - .synchronizedProcessingOutputWatermark; - inputWmsBuilder.add(producerOutputWatermark); - } - return inputWmsBuilder.build(); - } - - private List getInputWatermarks(AppliedPTransform transform) { - ImmutableList.Builder inputWatermarksBuilder = ImmutableList.builder(); - Collection inputs = transform.getInput().expand(); - if (inputs.isEmpty()) { - inputWatermarksBuilder.add(THE_END_OF_TIME); - } - for (PValue pvalue : inputs) { - Watermark producerOutputWatermark = - getTransformWatermark(pvalue.getProducingTransformInternal()).outputWatermark; - inputWatermarksBuilder.add(producerOutputWatermark); - } - List inputCollectionWatermarks = inputWatermarksBuilder.build(); - return inputCollectionWatermarks; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Gets the input and output watermarks for an {@link AppliedPTransform}. If the - * {@link AppliedPTransform PTransform} has not processed any elements, return a watermark of - * {@link BoundedWindow#TIMESTAMP_MIN_VALUE}. - * - * @return a snapshot of the input watermark and output watermark for the provided transform - */ - public TransformWatermarks getWatermarks(AppliedPTransform transform) { - return transformToWatermarks.get(transform); - } - - /** - * Updates the watermarks of a transform with one or more inputs. - * - *

              Each transform has two monotonically increasing watermarks: the input watermark, which can, - * at any time, be updated to equal: - *

              -   * MAX(CurrentInputWatermark, MIN(PendingElements, InputPCollectionWatermarks))
              -   * 
              - * and the output watermark, which can, at any time, be updated to equal: - *
              -   * MAX(CurrentOutputWatermark, MIN(InputWatermark, WatermarkHolds))
              -   * 
              . - * - * @param completed the input that has completed - * @param timerUpdate the timers that were added, removed, and completed as part of producing - * this update - * @param result the result that was produced by processing the input - * @param earliestHold the earliest watermark hold in the transform's state. {@code null} if there - * is no hold - */ - public void updateWatermarks( - @Nullable CommittedBundle completed, - TimerUpdate timerUpdate, - CommittedResult result, - Instant earliestHold) { - pendingUpdates.offer(PendingWatermarkUpdate.create(completed, - timerUpdate, - result, - earliestHold)); - } - - /** - * Applies all pending updates to this {@link InMemoryWatermarkManager}, causing the pending state - * of all {@link TransformWatermarks} to be advanced as far as possible. - */ - private void applyPendingUpdates() { - Set> updatedTransforms = new HashSet<>(); - PendingWatermarkUpdate pending = pendingUpdates.poll(); - while (pending != null) { - applyPendingUpdate(pending); - updatedTransforms.add(pending.getTransform()); - pending = pendingUpdates.poll(); - } - pendingRefreshes.addAll(updatedTransforms); - } - - private void applyPendingUpdate(PendingWatermarkUpdate pending) { - CommittedResult result = pending.getResult(); - AppliedPTransform transform = result.getTransform(); - CommittedBundle inputBundle = pending.getInputBundle(); - - updatePending(inputBundle, pending.getTimerUpdate(), result); - - TransformWatermarks transformWms = transformToWatermarks.get(transform); - transformWms.setEventTimeHold(inputBundle == null ? null : inputBundle.getKey(), - pending.getEarliestHold()); - } - - /** - * First adds all produced elements to the queue of pending elements for each consumer, then adds - * all pending timers to the collection of pending timers, then removes all completed and deleted - * timers from the collection of pending timers, then removes all completed elements from the - * pending queue of the transform. - * - *

              It is required that all newly pending elements are added to the queue of pending elements - * for each consumer prior to the completed elements being removed, as doing otherwise could cause - * a Watermark to appear in a state in which the upstream (completed) element does not hold the - * watermark but the element it produced is not yet pending. This can cause the watermark to - * erroneously advance. - */ - private void updatePending( - CommittedBundle input, - TimerUpdate timerUpdate, - CommittedResult result) { - // Newly pending elements must be added before completed elements are removed, as the two - // do not share a Mutex within this call and thus can be interleaved with external calls to - // refresh. - for (CommittedBundle bundle : result.getOutputs()) { - for (AppliedPTransform consumer : consumers.get(bundle.getPCollection())) { - TransformWatermarks watermarks = transformToWatermarks.get(consumer); - watermarks.addPending(bundle); - } - } - - TransformWatermarks completedTransform = transformToWatermarks.get(result.getTransform()); - if (input != null) { - // Add the unprocessed inputs - completedTransform.addPending(result.getUnprocessedInputs()); - } - completedTransform.updateTimers(timerUpdate); - if (input != null) { - completedTransform.removePending(input); - } - } - - /** - * Refresh the watermarks contained within this {@link InMemoryWatermarkManager}, causing all - * watermarks to be advanced as far as possible. - */ - synchronized void refreshAll() { - applyPendingUpdates(); - while (!pendingRefreshes.isEmpty()) { - refreshWatermarks(pendingRefreshes.poll()); - } - } - - private void refreshWatermarks(AppliedPTransform toRefresh) { - TransformWatermarks myWatermarks = transformToWatermarks.get(toRefresh); - WatermarkUpdate updateResult = myWatermarks.refresh(); - Set> additionalRefreshes = new HashSet<>(); - if (updateResult.isAdvanced()) { - for (PValue outputPValue : toRefresh.getOutput().expand()) { - additionalRefreshes.addAll(consumers.get(outputPValue)); - } - } - pendingRefreshes.addAll(additionalRefreshes); - } - - /** - * Returns a map of each {@link PTransform} that has pending timers to those timers. All of the - * pending timers will be removed from this {@link InMemoryWatermarkManager}. - */ - public Map, Map, FiredTimers>> extractFiredTimers() { - Map, Map, FiredTimers>> allTimers = new HashMap<>(); - for (Map.Entry, TransformWatermarks> watermarksEntry : - transformToWatermarks.entrySet()) { - Map, FiredTimers> keyFiredTimers = - watermarksEntry.getValue().extractFiredTimers(); - if (!keyFiredTimers.isEmpty()) { - allTimers.put(watermarksEntry.getKey(), keyFiredTimers); - } - } - return allTimers; - } - - /** - * A (key, Instant) pair that holds the watermark. Holds are per-key, but the watermark is global, - * and as such the watermark manager must track holds and the release of holds on a per-key basis. - * - *

              The {@link #compareTo(KeyedHold)} method of {@link KeyedHold} is not consistent with equals, - * as the key is arbitrarily ordered via identity, rather than object equality. - */ - private static final class KeyedHold implements Comparable { - private static final Ordering KEY_ORDERING = Ordering.arbitrary().nullsLast(); - - private final Object key; - private final Instant timestamp; - - /** - * Create a new KeyedHold with the specified key and timestamp. - */ - public static KeyedHold of(Object key, Instant timestamp) { - return new KeyedHold(key, MoreObjects.firstNonNull(timestamp, THE_END_OF_TIME.get())); - } - - private KeyedHold(Object key, Instant timestamp) { - this.key = key; - this.timestamp = timestamp; - } - - @Override - public int compareTo(KeyedHold that) { - return ComparisonChain.start() - .compare(this.timestamp, that.timestamp) - .compare(this.key, that.key, KEY_ORDERING) - .result(); - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, key); - } - - @Override - public boolean equals(Object other) { - if (other == null || !(other instanceof KeyedHold)) { - return false; - } - KeyedHold that = (KeyedHold) other; - return Objects.equals(this.timestamp, that.timestamp) && Objects.equals(this.key, that.key); - } - - /** - * Get the value of this {@link KeyedHold}. - */ - public Instant getTimestamp() { - return timestamp; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(KeyedHold.class) - .add("key", key) - .add("hold", timestamp) - .toString(); - } - } - - private static class PerKeyHolds { - private final Map keyedHolds; - private final NavigableSet allHolds; - - private PerKeyHolds() { - this.keyedHolds = new HashMap<>(); - this.allHolds = new TreeSet<>(); - } - - /** - * Gets the minimum hold across all keys in this {@link PerKeyHolds}, or THE_END_OF_TIME if - * there are no holds within this {@link PerKeyHolds}. - */ - public Instant getMinHold() { - return allHolds.isEmpty() ? THE_END_OF_TIME.get() : allHolds.first().getTimestamp(); - } - - /** - * Updates the hold of the provided key to the provided value, removing any other holds for - * the same key. - */ - public void updateHold(@Nullable Object key, Instant newHold) { - removeHold(key); - KeyedHold newKeyedHold = KeyedHold.of(key, newHold); - keyedHolds.put(key, newKeyedHold); - allHolds.add(newKeyedHold); - } - - /** - * Removes the hold of the provided key. - */ - public void removeHold(Object key) { - KeyedHold oldHold = keyedHolds.get(key); - if (oldHold != null) { - allHolds.remove(oldHold); - } - } - } - - /** - * A reference to the input and output watermarks of an {@link AppliedPTransform}. - */ - public class TransformWatermarks { - private final AppliedPTransformInputWatermark inputWatermark; - private final AppliedPTransformOutputWatermark outputWatermark; - - private final SynchronizedProcessingTimeInputWatermark synchronizedProcessingInputWatermark; - private final SynchronizedProcessingTimeOutputWatermark synchronizedProcessingOutputWatermark; - - private Instant latestSynchronizedInputWm; - private Instant latestSynchronizedOutputWm; - - private TransformWatermarks( - AppliedPTransformInputWatermark inputWatermark, - AppliedPTransformOutputWatermark outputWatermark, - SynchronizedProcessingTimeInputWatermark inputSynchProcessingWatermark, - SynchronizedProcessingTimeOutputWatermark outputSynchProcessingWatermark) { - this.inputWatermark = inputWatermark; - this.outputWatermark = outputWatermark; - - this.synchronizedProcessingInputWatermark = inputSynchProcessingWatermark; - this.synchronizedProcessingOutputWatermark = outputSynchProcessingWatermark; - this.latestSynchronizedInputWm = BoundedWindow.TIMESTAMP_MIN_VALUE; - this.latestSynchronizedOutputWm = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - /** - * Returns the input watermark of the {@link AppliedPTransform}. - */ - public Instant getInputWatermark() { - return checkNotNull(inputWatermark.get()); - } - - /** - * Returns the output watermark of the {@link AppliedPTransform}. - */ - public Instant getOutputWatermark() { - return outputWatermark.get(); - } - - /** - * Returns the synchronized processing input time of the {@link AppliedPTransform}. - * - *

              The returned value is guaranteed to be monotonically increasing, and outside of the - * presence of holds, will increase as the system time progresses. - */ - public synchronized Instant getSynchronizedProcessingInputTime() { - latestSynchronizedInputWm = INSTANT_ORDERING.max( - latestSynchronizedInputWm, - INSTANT_ORDERING.min(clock.now(), synchronizedProcessingInputWatermark.get())); - return latestSynchronizedInputWm; - } - - /** - * Returns the synchronized processing output time of the {@link AppliedPTransform}. - * - *

              The returned value is guaranteed to be monotonically increasing, and outside of the - * presence of holds, will increase as the system time progresses. - */ - public synchronized Instant getSynchronizedProcessingOutputTime() { - latestSynchronizedOutputWm = INSTANT_ORDERING.max( - latestSynchronizedOutputWm, - INSTANT_ORDERING.min(clock.now(), synchronizedProcessingOutputWatermark.get())); - return latestSynchronizedOutputWm; - } - - private WatermarkUpdate refresh() { - inputWatermark.refresh(); - synchronizedProcessingInputWatermark.refresh(); - WatermarkUpdate eventOutputUpdate = outputWatermark.refresh(); - WatermarkUpdate syncOutputUpdate = synchronizedProcessingOutputWatermark.refresh(); - return eventOutputUpdate.union(syncOutputUpdate); - } - - private void setEventTimeHold(Object key, Instant newHold) { - outputWatermark.updateHold(key, newHold); - } - - private void removePending(CommittedBundle bundle) { - inputWatermark.removePendingElements(elementsFromBundle(bundle)); - synchronizedProcessingInputWatermark.removePending(bundle); - } - - private void addPending(CommittedBundle bundle) { - inputWatermark.addPendingElements(elementsFromBundle(bundle)); - synchronizedProcessingInputWatermark.addPending(bundle); - } - - private Iterable> elementsFromBundle(CommittedBundle bundle) { - return FluentIterable.from(bundle.getElements()).transformAndConcat(EXPLODE_WINDOWS_FN); - } - - private Map, FiredTimers> extractFiredTimers() { - Map, List> eventTimeTimers = - inputWatermark.extractFiredEventTimeTimers(); - Map, List> processingTimers = - synchronizedProcessingInputWatermark.extractFiredDomainTimers(TimeDomain.PROCESSING_TIME, - clock.now()); - Map, List> synchronizedTimers = - synchronizedProcessingInputWatermark.extractFiredDomainTimers( - TimeDomain.SYNCHRONIZED_PROCESSING_TIME, getSynchronizedProcessingInputTime()); - Map, Map>> groupedTimers = new HashMap<>(); - groupFiredTimers(groupedTimers, eventTimeTimers, processingTimers, synchronizedTimers); - - Map, FiredTimers> keyFiredTimers = new HashMap<>(); - for (Map.Entry, Map>> firedTimers : - groupedTimers.entrySet()) { - keyFiredTimers.put(firedTimers.getKey(), new FiredTimers(firedTimers.getValue())); - } - return keyFiredTimers; - } - - @SafeVarargs - private final void groupFiredTimers( - Map, Map>> groupedToMutate, - Map, List>... timersToGroup) { - for (Map, List> subGroup : timersToGroup) { - for (Map.Entry, List> newTimers : subGroup.entrySet()) { - Map> grouped = groupedToMutate.get(newTimers.getKey()); - if (grouped == null) { - grouped = new HashMap<>(); - groupedToMutate.put(newTimers.getKey(), grouped); - } - grouped.put(newTimers.getValue().get(0).getDomain(), newTimers.getValue()); - } - } - } - - private void updateTimers(TimerUpdate update) { - inputWatermark.updateTimers(update); - synchronizedProcessingInputWatermark.updateTimers(update); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(TransformWatermarks.class) - .add("inputWatermark", inputWatermark) - .add("outputWatermark", outputWatermark) - .add("inputProcessingTime", synchronizedProcessingInputWatermark) - .add("outputProcessingTime", synchronizedProcessingOutputWatermark) - .toString(); - } - } - - /** - * A collection of newly set, deleted, and completed timers. - * - *

              setTimers and deletedTimers are collections of {@link TimerData} that have been added to the - * {@link TimerInternals} of an executed step. completedTimers are timers that were delivered as - * the input to the executed step. - */ - public static class TimerUpdate { - private final StructuralKey key; - private final Iterable completedTimers; - - private final Iterable setTimers; - private final Iterable deletedTimers; - - /** - * Returns a TimerUpdate for a null key with no timers. - */ - public static TimerUpdate empty() { - return new TimerUpdate( - null, - Collections.emptyList(), - Collections.emptyList(), - Collections.emptyList()); - } - - /** - * Creates a new {@link TimerUpdate} builder with the provided completed timers that needs the - * set and deleted timers to be added to it. - */ - public static TimerUpdateBuilder builder(StructuralKey key) { - return new TimerUpdateBuilder(key); - } - - /** - * A {@link TimerUpdate} builder that needs to be provided with set timers and deleted timers. - */ - public static final class TimerUpdateBuilder { - private final StructuralKey key; - private final Collection completedTimers; - private final Collection setTimers; - private final Collection deletedTimers; - - private TimerUpdateBuilder(StructuralKey key) { - this.key = key; - this.completedTimers = new HashSet<>(); - this.setTimers = new HashSet<>(); - this.deletedTimers = new HashSet<>(); - } - - /** - * Adds all of the provided timers to the collection of completed timers, and returns this - * {@link TimerUpdateBuilder}. - */ - public TimerUpdateBuilder withCompletedTimers(Iterable completedTimers) { - Iterables.addAll(this.completedTimers, completedTimers); - return this; - } - - /** - * Adds the provided timer to the collection of set timers, removing it from deleted timers if - * it has previously been deleted. Returns this {@link TimerUpdateBuilder}. - */ - public TimerUpdateBuilder setTimer(TimerData setTimer) { - deletedTimers.remove(setTimer); - setTimers.add(setTimer); - return this; - } - - /** - * Adds the provided timer to the collection of deleted timers, removing it from set timers if - * it has previously been set. Returns this {@link TimerUpdateBuilder}. - */ - public TimerUpdateBuilder deletedTimer(TimerData deletedTimer) { - deletedTimers.add(deletedTimer); - setTimers.remove(deletedTimer); - return this; - } - - /** - * Returns a new {@link TimerUpdate} with the most recently set completedTimers, setTimers, - * and deletedTimers. - */ - public TimerUpdate build() { - return new TimerUpdate( - key, - ImmutableSet.copyOf(completedTimers), - ImmutableSet.copyOf(setTimers), - ImmutableSet.copyOf(deletedTimers)); - } - } - - private TimerUpdate( - StructuralKey key, - Iterable completedTimers, - Iterable setTimers, - Iterable deletedTimers) { - this.key = key; - this.completedTimers = completedTimers; - this.setTimers = setTimers; - this.deletedTimers = deletedTimers; - } - - @VisibleForTesting - StructuralKey getKey() { - return key; - } - - @VisibleForTesting - Iterable getCompletedTimers() { - return completedTimers; - } - - @VisibleForTesting - Iterable getSetTimers() { - return setTimers; - } - - @VisibleForTesting - Iterable getDeletedTimers() { - return deletedTimers; - } - - /** - * Returns a {@link TimerUpdate} that is like this one, but with the specified completed timers. - */ - public TimerUpdate withCompletedTimers(Iterable completedTimers) { - return new TimerUpdate(this.key, completedTimers, setTimers, deletedTimers); - } - - @Override - public int hashCode() { - return Objects.hash(key, completedTimers, setTimers, deletedTimers); - } - - @Override - public boolean equals(Object other) { - if (other == null || !(other instanceof TimerUpdate)) { - return false; - } - TimerUpdate that = (TimerUpdate) other; - return Objects.equals(this.key, that.key) - && Objects.equals(this.completedTimers, that.completedTimers) - && Objects.equals(this.setTimers, that.setTimers) - && Objects.equals(this.deletedTimers, that.deletedTimers); - } - } - - /** - * A pair of {@link TimerData} and key which can be delivered to the appropriate - * {@link AppliedPTransform}. A timer fires at the transform that set it with a specific key when - * the time domain in which it lives progresses past a specified time, as determined by the - * {@link InMemoryWatermarkManager}. - */ - public static class FiredTimers { - private final Map> timers; - - private FiredTimers(Map> timers) { - this.timers = timers; - } - - /** - * Gets all of the timers that have fired within the provided {@link TimeDomain}. If no timers - * fired within the provided domain, return an empty collection. - * - *

              Timers within a {@link TimeDomain} are guaranteed to be in order of increasing timestamp. - */ - public Collection getTimers(TimeDomain domain) { - Collection domainTimers = timers.get(domain); - if (domainTimers == null) { - return Collections.emptyList(); - } - return domainTimers; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(FiredTimers.class).add("timers", timers).toString(); - } - } - - private static class WindowedValueByTimestampComparator extends Ordering> { - @Override - public int compare(WindowedValue o1, WindowedValue o2) { - return ComparisonChain.start() - .compare(o1.getTimestamp(), o2.getTimestamp()) - .result(); - } - } - - public Set> getCompletedTransforms() { - Set> result = new HashSet<>(); - for (Map.Entry, TransformWatermarks> wms : - transformToWatermarks.entrySet()) { - if (wms.getValue().getOutputWatermark().equals(THE_END_OF_TIME.get())) { - result.add(wms.getKey()); - } - } - return result; - } - - @AutoValue - abstract static class PendingWatermarkUpdate { - @Nullable - public abstract CommittedBundle getInputBundle(); - public abstract TimerUpdate getTimerUpdate(); - public abstract CommittedResult getResult(); - public abstract Instant getEarliestHold(); - - /** - * Gets the {@link AppliedPTransform} that generated this result. - */ - public AppliedPTransform getTransform() { - return getResult().getTransform(); - } - - public static PendingWatermarkUpdate create( - CommittedBundle inputBundle, - TimerUpdate timerUpdate, - CommittedResult result, Instant earliestHold) { - return new AutoValue_InMemoryWatermarkManager_PendingWatermarkUpdate(inputBundle, - timerUpdate, - result, - earliestHold); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java deleted file mode 100644 index d6f7cb4f61..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; - -/** - * A factory that produces bundles that perform no additional validation. - */ -class InProcessBundleFactory implements BundleFactory { - public static InProcessBundleFactory create() { - return new InProcessBundleFactory(); - } - - private InProcessBundleFactory() {} - - @Override - public UncommittedBundle createRootBundle(PCollection output) { - return InProcessBundle.create(output, StructuralKey.of(null, VoidCoder.of())); - } - - @Override - public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { - return InProcessBundle.create(output, input.getKey()); - } - - @Override - public UncommittedBundle createKeyedBundle( - CommittedBundle input, StructuralKey key, PCollection output) { - return InProcessBundle.create(output, key); - } - - /** - * A {@link UncommittedBundle} that buffers elements in memory. - */ - private static final class InProcessBundle implements UncommittedBundle { - private final PCollection pcollection; - private final StructuralKey key; - private boolean committed = false; - private ImmutableList.Builder> elements; - - /** - * Create a new {@link InProcessBundle} for the specified {@link PCollection}. - */ - public static InProcessBundle create(PCollection pcollection, StructuralKey key) { - return new InProcessBundle<>(pcollection, key); - } - - private InProcessBundle(PCollection pcollection, StructuralKey key) { - this.pcollection = pcollection; - this.key = key; - this.elements = ImmutableList.builder(); - } - - @Override - public PCollection getPCollection() { - return pcollection; - } - - @Override - public InProcessBundle add(WindowedValue element) { - checkState( - !committed, - "Can't add element %s to committed bundle in PCollection %s", - element, - pcollection); - elements.add(element); - return this; - } - - @Override - public CommittedBundle commit(final Instant synchronizedCompletionTime) { - checkState(!committed, "Can't commit already committed bundle %s", this); - committed = true; - final Iterable> committedElements = elements.build(); - return new CommittedInProcessBundle<>( - pcollection, key, committedElements, synchronizedCompletionTime); - } - } - - private static class CommittedInProcessBundle implements CommittedBundle { - public CommittedInProcessBundle( - PCollection pcollection, - StructuralKey key, - Iterable> committedElements, - Instant synchronizedCompletionTime) { - this.pcollection = pcollection; - this.key = key; - this.committedElements = committedElements; - this.synchronizedCompletionTime = synchronizedCompletionTime; - } - - private final PCollection pcollection; - /** The structural value key of the Bundle, as specified by the coder that created it. */ - private final StructuralKey key; - private final Iterable> committedElements; - private final Instant synchronizedCompletionTime; - - @Override - public StructuralKey getKey() { - return key; - } - - @Override - public Iterable> getElements() { - return committedElements; - } - - @Override - public PCollection getPCollection() { - return pcollection; - } - - @Override - public Instant getSynchronizedProcessingOutputWatermark() { - return synchronizedCompletionTime; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .omitNullValues() - .add("pcollection", pcollection) - .add("key", key) - .add("elements", committedElements) - .toString(); - } - - @Override - public CommittedBundle withElements(Iterable> elements) { - return new CommittedInProcessBundle<>( - pcollection, key, ImmutableList.copyOf(elements), synchronizedCompletionTime); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java deleted file mode 100644 index bd8f3f72b4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleOutputManager.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.util.Map; - -/** - * An {@link OutputManager} that outputs to {@link CommittedBundle Bundles} used by the - * {@link InProcessPipelineRunner}. - */ -class InProcessBundleOutputManager implements OutputManager { - private final Map, UncommittedBundle> bundles; - - public static InProcessBundleOutputManager create( - Map, UncommittedBundle> outputBundles) { - return new InProcessBundleOutputManager(outputBundles); - } - - public InProcessBundleOutputManager(Map, UncommittedBundle> bundles) { - this.bundles = bundles; - } - - @SuppressWarnings("unchecked") - @Override - public void output(TupleTag tag, WindowedValue output) { - @SuppressWarnings("rawtypes") - UncommittedBundle bundle = bundles.get(tag); - bundle.add(output); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java deleted file mode 100644 index 802851a8db..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreate.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.OffsetBasedSource; -import com.google.cloud.dataflow.sdk.io.OffsetBasedSource.OffsetBasedReader; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Create.Values; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableList; - -import java.io.IOException; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * An in-process implementation of the {@link Values Create.Values} {@link PTransform}, implemented - * using a {@link BoundedSource}. - * - *

              The coder is inferred via the {@link Values#getDefaultOutputCoder(PInput)} method on the - * original transform. - */ -class InProcessCreate extends ForwardingPTransform> { - private final Create.Values original; - - /** - * A {@link PTransformOverrideFactory} for {@link InProcessCreate}. - */ - public static class InProcessCreateOverrideFactory implements PTransformOverrideFactory { - @Override - public PTransform override( - PTransform transform) { - if (transform instanceof Create.Values) { - @SuppressWarnings("unchecked") - PTransform override = - (PTransform) from((Create.Values) transform); - return override; - } - return transform; - } - } - - public static InProcessCreate from(Create.Values original) { - return new InProcessCreate<>(original); - } - - private InProcessCreate(Values original) { - this.original = original; - } - - @Override - public PCollection apply(PInput input) { - Coder elementCoder; - try { - elementCoder = original.getDefaultOutputCoder(input); - } catch (CannotProvideCoderException e) { - throw new IllegalArgumentException( - "Unable to infer a coder and no Coder was specified. " - + "Please set a coder by invoking Create.withCoder() explicitly.", - e); - } - InMemorySource source; - try { - source = InMemorySource.fromIterable(original.getElements(), elementCoder); - } catch (IOException e) { - throw new RuntimeException(e); - } - PCollection result = input.getPipeline().apply(Read.from(source)); - result.setCoder(elementCoder); - return result; - } - - @Override - public PTransform> delegate() { - return original; - } - - @VisibleForTesting - static class InMemorySource extends OffsetBasedSource { - private final List allElementsBytes; - private final long totalSize; - private final Coder coder; - - public static InMemorySource fromIterable(Iterable elements, Coder elemCoder) - throws CoderException, IOException { - ImmutableList.Builder allElementsBytes = ImmutableList.builder(); - long totalSize = 0L; - for (T element : elements) { - byte[] bytes = CoderUtils.encodeToByteArray(elemCoder, element); - allElementsBytes.add(bytes); - totalSize += bytes.length; - } - return new InMemorySource<>(allElementsBytes.build(), totalSize, elemCoder); - } - - /** - * Create a new source with the specified bytes. The new source owns the input element bytes, - * which must not be modified after this constructor is called. - */ - private InMemorySource(List elementBytes, long totalSize, Coder coder) { - super(0, elementBytes.size(), 1); - this.allElementsBytes = ImmutableList.copyOf(elementBytes); - this.totalSize = totalSize; - this.coder = coder; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return totalSize; - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public BoundedSource.BoundedReader createReader(PipelineOptions options) throws IOException { - return new BytesReader<>(this); - } - - @Override - public void validate() {} - - @Override - public Coder getDefaultOutputCoder() { - return coder; - } - - @Override - public long getMaxEndOffset(PipelineOptions options) throws Exception { - return allElementsBytes.size(); - } - - @Override - public OffsetBasedSource createSourceForSubrange(long start, long end) { - List primaryElems = allElementsBytes.subList((int) start, (int) end); - long primarySizeEstimate = - (long) (totalSize * primaryElems.size() / (double) allElementsBytes.size()); - return new InMemorySource<>(primaryElems, primarySizeEstimate, coder); - } - - @Override - public long getBytesPerOffset() { - if (allElementsBytes.size() == 0) { - return 1L; - } - return Math.max(1L, totalSize / allElementsBytes.size()); - } - } - - private static class BytesReader extends OffsetBasedReader { - private int index; - /** - * Use an optional to distinguish between null next element (as Optional.absent()) and no next - * element (next is null). - */ - @Nullable private Optional next; - - public BytesReader(InMemorySource source) { - super(source); - index = -1; - } - - @Override - @Nullable - public T getCurrent() throws NoSuchElementException { - if (next == null) { - throw new NoSuchElementException(); - } - return next.orNull(); - } - - @Override - public void close() throws IOException {} - - @Override - protected long getCurrentOffset() { - return index; - } - - @Override - protected boolean startImpl() throws IOException { - return advanceImpl(); - } - - @Override - public synchronized InMemorySource getCurrentSource() { - return (InMemorySource) super.getCurrentSource(); - } - - @Override - protected boolean advanceImpl() throws IOException { - InMemorySource source = getCurrentSource(); - index++; - if (index >= source.allElementsBytes.size()) { - return false; - } - next = - Optional.fromNullable( - CoderUtils.decodeFromByteArray( - source.coder, source.allElementsBytes.get(index))); - return true; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java deleted file mode 100644 index 7669f4ba97..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContext.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.util.concurrent.MoreExecutors; -import org.joda.time.Instant; -import java.util.Collection; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import javax.annotation.Nullable; - -/** - * The evaluation context for a specific pipeline being executed by the - * {@link InProcessPipelineRunner}. Contains state shared within the execution across all - * transforms. - * - *

              {@link InProcessEvaluationContext} contains shared state for an execution of the - * {@link InProcessPipelineRunner} that can be used while evaluating a {@link PTransform}. This - * consists of views into underlying state and watermark implementations, access to read and write - * {@link PCollectionView PCollectionViews}, and constructing {@link CounterSet CounterSets} and - * {@link ExecutionContext ExecutionContexts}. This includes executing callbacks asynchronously when - * state changes to the appropriate point (e.g. when a {@link PCollectionView} is requested and - * known to be empty). - * - *

              {@link InProcessEvaluationContext} also handles results by committing finalizing bundles based - * on the current global state and updating the global state appropriately. This includes updating - * the per-{@link StepAndKey} state, updating global watermarks, and executing any callbacks that - * can be executed. - */ -class InProcessEvaluationContext { - /** The step name for each {@link AppliedPTransform} in the {@link Pipeline}. */ - private final Map, String> stepNames; - - /** The options that were used to create this {@link Pipeline}. */ - private final InProcessPipelineOptions options; - private final Clock clock; - - private final BundleFactory bundleFactory; - /** The current processing time and event time watermarks and timers. */ - private final InMemoryWatermarkManager watermarkManager; - - /** Executes callbacks based on the progression of the watermark. */ - private final WatermarkCallbackExecutor callbackExecutor; - - /** The stateInternals of the world, by applied PTransform and key. */ - private final ConcurrentMap> - applicationStateInternals; - - private final InProcessSideInputContainer sideInputContainer; - - private final CounterSet mergedCounters; - - public static InProcessEvaluationContext create( - InProcessPipelineOptions options, - Clock clock, - BundleFactory bundleFactory, - Collection> rootTransforms, - Map>> valueToConsumers, - Map, String> stepNames, - Collection> views) { - return new InProcessEvaluationContext( - options, clock, bundleFactory, rootTransforms, valueToConsumers, stepNames, views); - } - - private InProcessEvaluationContext( - InProcessPipelineOptions options, - Clock clock, - BundleFactory bundleFactory, - Collection> rootTransforms, - Map>> valueToConsumers, - Map, String> stepNames, - Collection> views) { - this.options = checkNotNull(options); - this.clock = clock; - this.bundleFactory = checkNotNull(bundleFactory); - checkNotNull(rootTransforms); - checkNotNull(valueToConsumers); - checkNotNull(stepNames); - checkNotNull(views); - this.stepNames = stepNames; - - this.watermarkManager = - InMemoryWatermarkManager.create(clock, rootTransforms, valueToConsumers); - this.sideInputContainer = InProcessSideInputContainer.create(this, views); - - this.applicationStateInternals = new ConcurrentHashMap<>(); - this.mergedCounters = new CounterSet(); - - this.callbackExecutor = WatermarkCallbackExecutor.create(MoreExecutors.directExecutor()); - } - - /** - * Handle the provided {@link InProcessTransformResult}, produced after evaluating the provided - * {@link CommittedBundle} (potentially null, if the result of a root {@link PTransform}). - * - *

              The result is the output of running the transform contained in the - * {@link InProcessTransformResult} on the contents of the provided bundle. - * - * @param completedBundle the bundle that was processed to produce the result. Potentially - * {@code null} if the transform that produced the result is a root - * transform - * @param completedTimers the timers that were delivered to produce the {@code completedBundle}, - * or an empty iterable if no timers were delivered - * @param result the result of evaluating the input bundle - * @return the committed bundles contained within the handled {@code result} - */ - public CommittedResult handleResult( - @Nullable CommittedBundle completedBundle, - Iterable completedTimers, - InProcessTransformResult result) { - Iterable> committedBundles = - commitBundles(result.getOutputBundles()); - // Update watermarks and timers - EnumSet outputTypes = EnumSet.copyOf(result.getOutputTypes()); - if (Iterables.isEmpty(committedBundles)) { - outputTypes.remove(OutputType.BUNDLE); - } else { - outputTypes.add(OutputType.BUNDLE); - } - CommittedResult committedResult = CommittedResult.create(result, - completedBundle == null - ? null - : completedBundle.withElements((Iterable) result.getUnprocessedElements()), - committedBundles, - outputTypes); - watermarkManager.updateWatermarks( - completedBundle, - result.getTimerUpdate().withCompletedTimers(completedTimers), - committedResult, - result.getWatermarkHold()); - // Update counters - if (result.getCounters() != null) { - mergedCounters.merge(result.getCounters()); - } - // Update state internals - CopyOnAccessInMemoryStateInternals theirState = result.getState(); - if (theirState != null) { - CopyOnAccessInMemoryStateInternals committedState = theirState.commit(); - StepAndKey stepAndKey = - StepAndKey.of( - result.getTransform(), completedBundle == null ? null : completedBundle.getKey()); - if (!committedState.isEmpty()) { - applicationStateInternals.put(stepAndKey, committedState); - } else { - applicationStateInternals.remove(stepAndKey); - } - } - return committedResult; - } - - private Iterable> commitBundles( - Iterable> bundles) { - ImmutableList.Builder> completed = ImmutableList.builder(); - for (UncommittedBundle inProgress : bundles) { - AppliedPTransform producing = - inProgress.getPCollection().getProducingTransformInternal(); - TransformWatermarks watermarks = watermarkManager.getWatermarks(producing); - CommittedBundle committed = - inProgress.commit(watermarks.getSynchronizedProcessingOutputTime()); - // Empty bundles don't impact watermarks and shouldn't trigger downstream execution, so - // filter them out - if (!Iterables.isEmpty(committed.getElements())) { - completed.add(committed); - } - } - return completed.build(); - } - - private void fireAllAvailableCallbacks() { - for (AppliedPTransform transform : stepNames.keySet()) { - fireAvailableCallbacks(transform); - } - } - - private void fireAvailableCallbacks(AppliedPTransform producingTransform) { - TransformWatermarks watermarks = watermarkManager.getWatermarks(producingTransform); - callbackExecutor.fireForWatermark(producingTransform, watermarks.getOutputWatermark()); - } - - /** - * Create a {@link UncommittedBundle} for use by a source. - */ - public UncommittedBundle createRootBundle(PCollection output) { - return bundleFactory.createRootBundle(output); - } - - /** - * Create a {@link UncommittedBundle} whose elements belong to the specified {@link - * PCollection}. - */ - public UncommittedBundle createBundle(CommittedBundle input, PCollection output) { - return bundleFactory.createBundle(input, output); - } - - /** - * Create a {@link UncommittedBundle} with the specified keys at the specified step. For use by - * {@link InProcessGroupByKeyOnly} {@link PTransform PTransforms}. - */ - public UncommittedBundle createKeyedBundle( - CommittedBundle input, StructuralKey key, PCollection output) { - return bundleFactory.createKeyedBundle(input, key, output); - } - - /** - * Create a {@link PCollectionViewWriter}, whose elements will be used in the provided - * {@link PCollectionView}. - */ - public PCollectionViewWriter createPCollectionViewWriter( - PCollection> input, final PCollectionView output) { - return new PCollectionViewWriter() { - @Override - public void add(Iterable> values) { - sideInputContainer.write(output, values); - } - }; - } - - /** - * Schedule a callback to be executed after output would be produced for the given window - * if there had been input. - * - *

              Output would be produced when the watermark for a {@link PValue} passes the point at - * which the trigger for the specified window (with the specified windowing strategy) must have - * fired from the perspective of that {@link PValue}, as specified by the value of - * {@link Trigger#getWatermarkThatGuaranteesFiring(BoundedWindow)} for the trigger of the - * {@link WindowingStrategy}. When the callback has fired, either values will have been produced - * for a key in that window, the window is empty, or all elements in the window are late. The - * callback will be executed regardless of whether values have been produced. - */ - public void scheduleAfterOutputWouldBeProduced( - PValue value, - BoundedWindow window, - WindowingStrategy windowingStrategy, - Runnable runnable) { - AppliedPTransform producing = getProducing(value); - callbackExecutor.callOnGuaranteedFiring(producing, window, windowingStrategy, runnable); - - fireAvailableCallbacks(lookupProducing(value)); - } - - private AppliedPTransform getProducing(PValue value) { - if (value.getProducingTransformInternal() != null) { - return value.getProducingTransformInternal(); - } - return lookupProducing(value); - } - - private AppliedPTransform lookupProducing(PValue value) { - for (AppliedPTransform transform : stepNames.keySet()) { - if (transform.getOutput().equals(value) || transform.getOutput().expand().contains(value)) { - return transform; - } - } - return null; - } - - /** - * Get the options used by this {@link Pipeline}. - */ - public InProcessPipelineOptions getPipelineOptions() { - return options; - } - - /** - * Get an {@link ExecutionContext} for the provided {@link AppliedPTransform} and key. - */ - public InProcessExecutionContext getExecutionContext( - AppliedPTransform application, StructuralKey key) { - StepAndKey stepAndKey = StepAndKey.of(application, key); - return new InProcessExecutionContext( - clock, - key, - (CopyOnAccessInMemoryStateInternals) applicationStateInternals.get(stepAndKey), - watermarkManager.getWatermarks(application)); - } - - /** - * Get all of the steps used in this {@link Pipeline}. - */ - public Collection> getSteps() { - return stepNames.keySet(); - } - - /** - * Get the Step Name for the provided application. - */ - public String getStepName(AppliedPTransform application) { - return stepNames.get(application); - } - - /** - * Returns a {@link ReadyCheckingSideInputReader} capable of reading the provided - * {@link PCollectionView PCollectionViews}. - * - * @param sideInputs the {@link PCollectionView PCollectionViews} the result should be able to - * read - * @return a {@link SideInputReader} that can read all of the provided {@link PCollectionView - * PCollectionViews} - */ - public ReadyCheckingSideInputReader createSideInputReader( - final List> sideInputs) { - return sideInputContainer.createReaderForViews(sideInputs); - } - - /** - * Create a {@link CounterSet} for this {@link Pipeline}. The {@link CounterSet} is independent - * of all other {@link CounterSet CounterSets} created by this call. - * - *

              The {@link InProcessEvaluationContext} is responsible for unifying the counters present in - * all created {@link CounterSet CounterSets} when the transforms that call this method - * complete. - */ - public CounterSet createCounterSet() { - return new CounterSet(); - } - - /** - * Returns all of the counters that have been merged into this context via calls to - * {@link CounterSet#merge(CounterSet)}. - */ - public CounterSet getCounters() { - return mergedCounters; - } - - @VisibleForTesting - void forceRefresh() { - watermarkManager.refreshAll(); - fireAllAvailableCallbacks(); - } - - /** - * Extracts all timers that have been fired and have not already been extracted. - * - *

              This is a destructive operation. Timers will only appear in the result of this method once - * for each time they are set. - */ - public Map, Map, FiredTimers>> extractFiredTimers() { - forceRefresh(); - Map, Map, FiredTimers>> fired = - watermarkManager.extractFiredTimers(); - return fired; - } - - /** - * Returns true if the step will not produce additional output. - * - *

              If the provided transform produces only {@link IsBounded#BOUNDED} - * {@link PCollection PCollections}, returns true if the watermark is at - * {@link BoundedWindow#TIMESTAMP_MAX_VALUE positive infinity}. - * - *

              If the provided transform produces any {@link IsBounded#UNBOUNDED} - * {@link PCollection PCollections}, returns the value of - * {@link InProcessPipelineOptions#isShutdownUnboundedProducersWithMaxWatermark()}. - */ - public boolean isDone(AppliedPTransform transform) { - // if the PTransform's watermark isn't at the max value, it isn't done - if (watermarkManager - .getWatermarks(transform) - .getOutputWatermark() - .isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - return false; - } - // If the PTransform has any unbounded outputs, and unbounded producers should not be shut down, - // the PTransform may produce additional output. It is not done. - for (PValue output : transform.getOutput().expand()) { - if (output instanceof PCollection) { - IsBounded bounded = ((PCollection) output).isBounded(); - if (bounded.equals(IsBounded.UNBOUNDED) - && !options.isShutdownUnboundedProducersWithMaxWatermark()) { - return false; - } - } - } - // The PTransform's watermark was at positive infinity and all of its outputs are known to be - // done. It is done. - return true; - } - - /** - * Returns true if all steps are done. - */ - public boolean isDone() { - for (AppliedPTransform transform : stepNames.keySet()) { - if (!isDone(transform)) { - return false; - } - } - return true; - } - - public Instant now() { - return clock.now(); - } - - Clock getClock() { - return clock; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java deleted file mode 100644 index 46894cdaf5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutionContext.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; -import com.google.cloud.dataflow.sdk.util.BaseExecutionContext; -import com.google.cloud.dataflow.sdk.util.ExecutionContext; -import com.google.cloud.dataflow.sdk.util.TimerInternals; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; - -/** - * Execution Context for the {@link InProcessPipelineRunner}. - * - *

              This implementation is not thread safe. A new {@link InProcessExecutionContext} must be - * created for each thread that requires it. - */ -class InProcessExecutionContext - extends BaseExecutionContext { - private final Clock clock; - private final StructuralKey key; - private final CopyOnAccessInMemoryStateInternals existingState; - private final TransformWatermarks watermarks; - - public InProcessExecutionContext(Clock clock, StructuralKey key, - CopyOnAccessInMemoryStateInternals existingState, TransformWatermarks watermarks) { - this.clock = clock; - this.key = key; - this.existingState = existingState; - this.watermarks = watermarks; - } - - @Override - protected InProcessStepContext createStepContext( - String stepName, String transformName, StateSampler stateSampler) { - return new InProcessStepContext(this, stepName, transformName); - } - - /** - * Step Context for the {@link InProcessPipelineRunner}. - */ - public class InProcessStepContext - extends com.google.cloud.dataflow.sdk.util.BaseExecutionContext.StepContext { - private CopyOnAccessInMemoryStateInternals stateInternals; - private InProcessTimerInternals timerInternals; - - public InProcessStepContext( - ExecutionContext executionContext, String stepName, String transformName) { - super(executionContext, stepName, transformName); - } - - @Override - public CopyOnAccessInMemoryStateInternals stateInternals() { - if (stateInternals == null) { - stateInternals = CopyOnAccessInMemoryStateInternals.withUnderlying(key, existingState); - } - return stateInternals; - } - - @Override - public InProcessTimerInternals timerInternals() { - if (timerInternals == null) { - timerInternals = - InProcessTimerInternals.create(clock, watermarks, TimerUpdate.builder(key)); - } - return timerInternals; - } - - /** - * Commits the state of this step, and returns the committed state. If the step has not - * accessed any state, return null. - */ - public CopyOnAccessInMemoryStateInternals commitState() { - if (stateInternals != null) { - return stateInternals.commit(); - } - return null; - } - - /** - * Gets the timer update of the {@link TimerInternals} of this {@link InProcessStepContext}, - * which is empty if the {@link TimerInternals} were never accessed. - */ - public TimerUpdate getTimerUpdate() { - if (timerInternals == null) { - return TimerUpdate.empty(); - } - return timerInternals.getTimerUpdate(); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java deleted file mode 100644 index 7b60bca17d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessExecutor.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -import java.util.Collection; - -/** - * An executor that schedules and executes {@link AppliedPTransform AppliedPTransforms} for both - * source and intermediate {@link PTransform PTransforms}. - */ -interface InProcessExecutor { - /** - * Starts this executor. The provided collection is the collection of root transforms to - * initially schedule. - * - * @param rootTransforms - */ - void start(Collection> rootTransforms); - - /** - * Blocks until the job being executed enters a terminal state. A job is completed after all - * root {@link AppliedPTransform AppliedPTransforms} have completed, and all - * {@link CommittedBundle Bundles} have been consumed. Jobs may also terminate abnormally. - * - * @throws Throwable whenever an executor thread throws anything, transfers the throwable to the - * waiting thread and rethrows it - */ - void awaitCompletion() throws Throwable; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java deleted file mode 100644 index b2894871ce..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineOptions.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.Hidden; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.fasterxml.jackson.annotation.JsonIgnore; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Options that can be used to configure the {@link InProcessPipelineRunner}. - */ -public interface InProcessPipelineOptions extends PipelineOptions, ApplicationNameOptions { - /** - * Gets the {@link ExecutorServiceFactory} to use to create instances of {@link ExecutorService} - * to execute {@link PTransform PTransforms}. - * - *

              Defaults to a {@link FixedThreadPoolExecutorServiceFactory}, which produces instances of - * {@link Executors#newCachedThreadPool()}. - * - * @deprecated the runner manages its own {@link ExecutorService} as an implementation detail - */ - @Deprecated - @JsonIgnore - @Hidden - ExecutorServiceFactory getExecutorServiceFactory(); - - void setExecutorServiceFactory(ExecutorServiceFactory executorService); - - /** - * Gets the {@link Clock} used by this pipeline. The clock is used in place of accessing the - * system time when time values are required by the evaluator. - * - * @deprecated the runner manages its own {@link Clock} as an implementation detail - */ - @Deprecated - @JsonIgnore - @Hidden - @Description( - "The processing time source used by the pipeline. When the current time is " - + "needed by the evaluator, the result of clock#now() is used.") - Clock getClock(); - - void setClock(Clock clock); - - @Default.Boolean(false) - @Description( - "If the pipeline should shut down producers which have reached the maximum " - + "representable watermark. If this is set to true, a pipeline in which all PTransforms " - + "have reached the maximum watermark will be shut down, even if there are unbounded " - + "sources that could produce additional (late) data. By default, if the pipeline " - + "contains any unbounded PCollections, it will run until explicitly shut down.") - boolean isShutdownUnboundedProducersWithMaxWatermark(); - - void setShutdownUnboundedProducersWithMaxWatermark(boolean shutdown); - - @Default.Boolean(true) - @Description( - "If the pipeline should block awaiting completion of the pipeline. If set to true, " - + "a call to Pipeline#run() will block until all PTransforms are complete. Otherwise, " - + "the Pipeline will execute asynchronously. If set to false, the completion of the " - + "pipeline can be awaited on by use of InProcessPipelineResult#awaitCompletion().") - boolean isBlockOnRun(); - - void setBlockOnRun(boolean b); - - @Default.Boolean(true) - @Description( - "Controls whether the runner should ensure that all of the elements of every " - + "PCollection are not mutated. PTransforms are not permitted to mutate input elements " - + "at any point, or output elements after they are output.") - boolean isTestImmutability(); - - void setTestImmutability(boolean test); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java deleted file mode 100644 index 9f19c588ef..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunner.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.io.Write; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.AggregatorPipelineExtractor; -import com.google.cloud.dataflow.sdk.runners.AggregatorRetrievalException; -import com.google.cloud.dataflow.sdk.runners.AggregatorValues; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly; -import com.google.cloud.dataflow.sdk.runners.inprocess.GroupByKeyEvaluatorFactory.InProcessGroupByKeyOverrideFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessCreate.InProcessCreateOverrideFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.TestStreamEvaluatorFactory.InProcessTestStreamFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.ViewEvaluatorFactory.InProcessViewOverrideFactory; -import com.google.cloud.dataflow.sdk.testing.TestStream; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; -import com.google.cloud.dataflow.sdk.util.MapAggregatorValues; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import org.joda.time.Instant; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * An In-Memory implementation of the Dataflow Programming Model. Supports Unbounded - * {@link PCollection PCollections}. - */ -@Experimental -public class InProcessPipelineRunner - extends PipelineRunner { - /** - * The default set of transform overrides to use in the {@link InProcessPipelineRunner}. - * - *

              A transform override must have a single-argument constructor that takes an instance of the - * type of transform it is overriding. - */ - @SuppressWarnings("rawtypes") - private static Map, PTransformOverrideFactory> - defaultTransformOverrides = - ImmutableMap., PTransformOverrideFactory>builder() - .put(Create.Values.class, new InProcessCreateOverrideFactory()) - .put(GroupByKey.class, new InProcessGroupByKeyOverrideFactory()) - .put(CreatePCollectionView.class, new InProcessViewOverrideFactory()) - .put(TestStream.class, new InProcessTestStreamFactory()) - .put(Write.Bound.class, new WriteWithShardingFactory()) - .build(); - - /** - * Part of a {@link PCollection}. Elements are output to a bundle, which will cause them to be - * executed by {@link PTransform PTransforms} that consume the {@link PCollection} this bundle is - * a part of at a later point. This is an uncommitted bundle and can have elements added to it. - * - * @param the type of elements that can be added to this bundle - */ - public interface UncommittedBundle { - /** - * Returns the PCollection that the elements of this {@link UncommittedBundle} belong to. - */ - PCollection getPCollection(); - - /** - * Outputs an element to this bundle. - * - * @param element the element to add to this bundle - * @return this bundle - */ - UncommittedBundle add(WindowedValue element); - - /** - * Commits this {@link UncommittedBundle}, returning an immutable {@link CommittedBundle} - * containing all of the elements that were added to it. The {@link #add(WindowedValue)} method - * will throw an {@link IllegalStateException} if called after a call to commit. - * @param synchronizedProcessingTime the synchronized processing time at which this bundle was - * committed - */ - CommittedBundle commit(Instant synchronizedProcessingTime); - } - - /** - * Part of a {@link PCollection}. Elements are output to an {@link UncommittedBundle}, which will - * eventually committed. Committed elements are executed by the {@link PTransform PTransforms} - * that consume the {@link PCollection} this bundle is - * a part of at a later point. - * @param the type of elements contained within this bundle - */ - public interface CommittedBundle { - /** - * Returns the PCollection that the elements of this bundle belong to. - */ - PCollection getPCollection(); - - /** - * Returns the key that was output in the most recent {@link GroupByKey} in the - * execution of this bundle. - */ - StructuralKey getKey(); - - /** - * Returns an {@link Iterable} containing all of the elements that have been added to this - * {@link CommittedBundle}. - */ - Iterable> getElements(); - - /** - * Returns the processing time output watermark at the time the producing {@link PTransform} - * committed this bundle. Downstream synchronized processing time watermarks cannot progress - * past this point before consuming this bundle. - * - *

              This value is no greater than the earliest incomplete processing time or synchronized - * processing time {@link TimerData timer} at the time this bundle was committed, including any - * timers that fired to produce this bundle. - */ - Instant getSynchronizedProcessingOutputWatermark(); - - /** - * Return a new {@link CommittedBundle} that is like this one, except calls to - * {@link #getElements()} will return the provided elements. This bundle is unchanged. - * - *

              The value of the {@link #getSynchronizedProcessingOutputWatermark() synchronized - * processing output watermark} of the returned {@link CommittedBundle} is equal to the value - * returned from the current bundle. This is used to ensure a {@link PTransform} that could not - * complete processing on input elements properly holds the synchronized processing time to the - * appropriate value. - */ - CommittedBundle withElements(Iterable> elements); - } - - /** - * A {@link PCollectionViewWriter} is responsible for writing contents of a {@link PCollection} to - * a storage mechanism that can be read from while constructing a {@link PCollectionView}. - * @param the type of elements the input {@link PCollection} contains. - * @param the type of the PCollectionView this writer writes to. - */ - public interface PCollectionViewWriter { - void add(Iterable> values); - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - private final InProcessPipelineOptions options; - private Supplier executorServiceSupplier; - private Supplier clockSupplier; - - public static InProcessPipelineRunner fromOptions(PipelineOptions options) { - return new InProcessPipelineRunner(options.as(InProcessPipelineOptions.class)); - } - - private InProcessPipelineRunner(InProcessPipelineOptions options) { - this.options = options; - if (options.getExecutorServiceFactory() == null) { - executorServiceSupplier = new FixedThreadPoolSupplier(); - } else { - executorServiceSupplier = - new ExecutorServiceFactorySupplier(options.getExecutorServiceFactory()); - } - if (options.getClock() == null) { - clockSupplier = new NanosOffsetClockSupplier(); - } else { - clockSupplier = Suppliers.ofInstance(options.getClock()); - } - } - - /** - * Returns the {@link PipelineOptions} used to create this {@link InProcessPipelineRunner}. - */ - public InProcessPipelineOptions getPipelineOptions() { - return options; - } - - Supplier getClockSupplier() { - return clockSupplier; - } - - void setClockSupplier(Supplier supplier) { - this.clockSupplier = supplier; - } - - @Override - public OutputT apply( - PTransform transform, InputT input) { - PTransformOverrideFactory overrideFactory = defaultTransformOverrides.get(transform.getClass()); - if (overrideFactory != null) { - PTransform customTransform = overrideFactory.override(transform); - - return super.apply(customTransform, input); - } - // If there is no override, or we should not apply the override, apply the original transform - return super.apply(transform, input); - } - - @Override - public InProcessPipelineResult run(Pipeline pipeline) { - ConsumerTrackingPipelineVisitor consumerTrackingVisitor = new ConsumerTrackingPipelineVisitor(); - pipeline.traverseTopologically(consumerTrackingVisitor); - for (PValue unfinalized : consumerTrackingVisitor.getUnfinalizedPValues()) { - unfinalized.finishSpecifying(); - } - @SuppressWarnings("rawtypes") - KeyedPValueTrackingVisitor keyedPValueVisitor = - KeyedPValueTrackingVisitor.create( - ImmutableSet.>of( - GroupByKey.class, InProcessGroupByKeyOnly.class)); - pipeline.traverseTopologically(keyedPValueVisitor); - - DisplayDataValidator.validatePipeline(pipeline); - - InProcessEvaluationContext context = - InProcessEvaluationContext.create( - getPipelineOptions(), - clockSupplier.get(), - createBundleFactory(getPipelineOptions()), - consumerTrackingVisitor.getRootTransforms(), - consumerTrackingVisitor.getValueToConsumers(), - consumerTrackingVisitor.getStepNames(), - consumerTrackingVisitor.getViews()); - - // independent executor service for each run - ExecutorService executorService = executorServiceSupplier.get(); - - TransformEvaluatorRegistry registry = TransformEvaluatorRegistry.defaultRegistry(); - InProcessExecutor executor = - ExecutorServiceParallelExecutor.create( - executorService, - consumerTrackingVisitor.getValueToConsumers(), - keyedPValueVisitor.getKeyedPValues(), - registry, - defaultModelEnforcements(options), - context); - executor.start(consumerTrackingVisitor.getRootTransforms()); - - Map, Collection>> aggregatorSteps = - new AggregatorPipelineExtractor(pipeline).getAggregatorSteps(); - InProcessPipelineResult result = - new InProcessPipelineResult(executor, context, aggregatorSteps); - if (options.isBlockOnRun()) { - try { - result.awaitCompletion(); - } catch (UserCodeException userException) { - throw new PipelineExecutionException(userException.getCause()); - } catch (Throwable t) { - throw new RuntimeException(t); - } - } - return result; - } - - private Map, Collection> - defaultModelEnforcements(InProcessPipelineOptions options) { - ImmutableMap.Builder, Collection> - enforcements = ImmutableMap.builder(); - Collection parDoEnforcements = createParDoEnforcements(options); - enforcements.put(ParDo.Bound.class, parDoEnforcements); - enforcements.put(ParDo.BoundMulti.class, parDoEnforcements); - return enforcements.build(); - } - - private Collection createParDoEnforcements( - InProcessPipelineOptions options) { - ImmutableList.Builder enforcements = ImmutableList.builder(); - if (options.isTestImmutability()) { - enforcements.add(ImmutabilityEnforcementFactory.create()); - } - return enforcements.build(); - } - - private BundleFactory createBundleFactory(InProcessPipelineOptions pipelineOptions) { - BundleFactory bundleFactory = InProcessBundleFactory.create(); - if (pipelineOptions.isTestImmutability()) { - bundleFactory = ImmutabilityCheckingBundleFactory.create(bundleFactory); - } - return bundleFactory; - } - - /** - * The result of running a {@link Pipeline} with the {@link InProcessPipelineRunner}. - * - *

              Throws {@link UnsupportedOperationException} for all methods. - */ - public static class InProcessPipelineResult implements PipelineResult { - private final InProcessExecutor executor; - private final InProcessEvaluationContext evaluationContext; - private final Map, Collection>> aggregatorSteps; - private State state; - - private InProcessPipelineResult( - InProcessExecutor executor, - InProcessEvaluationContext evaluationContext, - Map, Collection>> aggregatorSteps) { - this.executor = executor; - this.evaluationContext = evaluationContext; - this.aggregatorSteps = aggregatorSteps; - // Only ever constructed after the executor has started. - this.state = State.RUNNING; - } - - @Override - public State getState() { - return state; - } - - @Override - public AggregatorValues getAggregatorValues(Aggregator aggregator) - throws AggregatorRetrievalException { - CounterSet counters = evaluationContext.getCounters(); - Collection> steps = aggregatorSteps.get(aggregator); - Map stepValues = new HashMap<>(); - for (AppliedPTransform transform : evaluationContext.getSteps()) { - if (steps.contains(transform.getTransform())) { - String stepName = - String.format( - "user-%s-%s", evaluationContext.getStepName(transform), aggregator.getName()); - Counter counter = (Counter) counters.getExistingCounter(stepName); - if (counter != null) { - stepValues.put(transform.getFullName(), counter.getAggregate()); - } - } - } - return new MapAggregatorValues<>(stepValues); - } - - /** - * Blocks until the {@link Pipeline} execution represented by this - * {@link InProcessPipelineResult} is complete, returning the terminal state. - * - *

              If the pipeline terminates abnormally by throwing an exception, this will rethrow the - * exception. Future calls to {@link #getState()} will return - * {@link com.google.cloud.dataflow.sdk.PipelineResult.State#FAILED}. - * - *

              NOTE: if the {@link Pipeline} contains an {@link IsBounded#UNBOUNDED unbounded} - * {@link PCollection}, and the {@link PipelineRunner} was created with - * {@link InProcessPipelineOptions#isShutdownUnboundedProducersWithMaxWatermark()} set to false, - * this method will never return. - * - *

              See also {@link InProcessExecutor#awaitCompletion()}. - */ - public State awaitCompletion() throws Throwable { - if (!state.isTerminal()) { - try { - executor.awaitCompletion(); - state = State.DONE; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw e; - } catch (Throwable t) { - state = State.FAILED; - throw t; - } - } - return state; - } - } - - /** - * A {@link Supplier} that creates a {@link ExecutorService} based on - * {@link Executors#newFixedThreadPool(int)}. - */ - private static class FixedThreadPoolSupplier implements Supplier { - @Override - public ExecutorService get() { - return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); - } - } - - - /** - * A {@link Supplier} that wraps an {@link ExecutorServiceFactory}. - */ - private static class ExecutorServiceFactorySupplier implements Supplier { - private final ExecutorServiceFactory executorServiceFactory; - - public ExecutorServiceFactorySupplier( - ExecutorServiceFactory executorServiceFactory) { - this.executorServiceFactory = executorServiceFactory; - } - - @Override - public ExecutorService get() { - return executorServiceFactory.create(); - } - } - - /** - * A {@link Supplier} that creates a {@link NanosOffsetClock}. - */ - private static class NanosOffsetClockSupplier implements Supplier { - @Override - public Clock get() { - return NanosOffsetClock.create(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java deleted file mode 100644 index 52f238f9d0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessRegistrar.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.auto.service.AutoService; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; -import com.google.common.collect.ImmutableList; - -/** - * Contains the {@link PipelineRunnerRegistrar} and {@link PipelineOptionsRegistrar} for the - * {@link InProcessPipelineRunner}. - */ -public class InProcessRegistrar { - private InProcessRegistrar() {} - /** - * Registers the {@link InProcessPipelineRunner}. - */ - @AutoService(PipelineRunnerRegistrar.class) - public static class InProcessRunner implements PipelineRunnerRegistrar { - @Override - public Iterable>> getPipelineRunners() { - return ImmutableList.>>of(InProcessPipelineRunner.class); - } - } - - /** - * Registers the {@link InProcessPipelineOptions}. - */ - @AutoService(PipelineOptionsRegistrar.class) - public static class InProcessOptions implements PipelineOptionsRegistrar { - @Override - public Iterable> getPipelineOptions() { - return ImmutableList.>of(InProcessPipelineOptions.class); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java deleted file mode 100644 index d0199e079a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainer.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.PCollectionViewWindow; -import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.base.MoreObjects; -import com.google.common.base.Optional; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Nullable; - -/** - * An in-process container for {@link PCollectionView PCollectionViews}, which provides methods for - * constructing {@link SideInputReader SideInputReaders} which block until a side input is - * available and writing to a {@link PCollectionView}. - */ -class InProcessSideInputContainer { - private final Collection> containedViews; - private final LoadingCache< - PCollectionViewWindow, AtomicReference>>> - viewByWindows; - - /** - * Create a new {@link InProcessSideInputContainer} with the provided views and the provided - * context. - */ - public static InProcessSideInputContainer create( - final InProcessEvaluationContext context, Collection> containedViews) { - LoadingCache, AtomicReference>>> - viewByWindows = CacheBuilder.newBuilder().build(new CallbackSchedulingLoader(context)); - return new InProcessSideInputContainer(containedViews, viewByWindows); - } - - private InProcessSideInputContainer( - Collection> containedViews, - LoadingCache, AtomicReference>>> - viewByWindows) { - this.containedViews = ImmutableSet.copyOf(containedViews); - this.viewByWindows = viewByWindows; - } - - /** - * Return a view of this {@link InProcessSideInputContainer} that contains only the views in the - * provided argument. The returned {@link InProcessSideInputContainer} is unmodifiable without - * casting, but will change as this {@link InProcessSideInputContainer} is modified. - */ - public ReadyCheckingSideInputReader createReaderForViews( - Collection> newContainedViews) { - if (!containedViews.containsAll(newContainedViews)) { - Set> currentlyContained = ImmutableSet.copyOf(containedViews); - Set> newRequested = ImmutableSet.copyOf(newContainedViews); - throw new IllegalArgumentException("Can't create a SideInputReader with unknown views " - + Sets.difference(newRequested, currentlyContained)); - } - return new SideInputContainerSideInputReader(newContainedViews); - } - - /** - * Write the provided values to the provided view. - * - *

              The windowed values are first exploded, then for each window the pane is determined. For - * each window, if the pane is later than the current pane stored within this container, write - * all of the values to the container as the new values of the {@link PCollectionView}. - * - *

              The provided iterable is expected to contain only a single window and pane. - */ - public void write(PCollectionView view, Iterable> values) { - Map>> valuesPerWindow = - indexValuesByWindow(values); - for (Map.Entry>> windowValues : - valuesPerWindow.entrySet()) { - updatePCollectionViewWindowValues(view, windowValues.getKey(), windowValues.getValue()); - } - } - - /** - * Index the provided values by all {@link BoundedWindow windows} in which they appear. - */ - private Map>> indexValuesByWindow( - Iterable> values) { - Map>> valuesPerWindow = new HashMap<>(); - for (WindowedValue value : values) { - for (BoundedWindow window : value.getWindows()) { - Collection> windowValues = valuesPerWindow.get(window); - if (windowValues == null) { - windowValues = new ArrayList<>(); - valuesPerWindow.put(window, windowValues); - } - windowValues.add(value); - } - } - return valuesPerWindow; - } - - /** - * Set the value of the {@link PCollectionView} in the {@link BoundedWindow} to be based on the - * specified values, if the values are part of a later pane than currently exist within the - * {@link PCollectionViewWindow}. - */ - private void updatePCollectionViewWindowValues( - PCollectionView view, BoundedWindow window, Collection> windowValues) { - PCollectionViewWindow windowedView = PCollectionViewWindow.of(view, window); - AtomicReference>> contents = - viewByWindows.getUnchecked(windowedView); - if (contents.compareAndSet(null, windowValues)) { - // the value had never been set, so we set it and are done. - return; - } - PaneInfo newPane = windowValues.iterator().next().getPane(); - - Iterable> existingValues; - long existingPane; - do { - existingValues = contents.get(); - existingPane = - Iterables.isEmpty(existingValues) - ? -1L - : existingValues.iterator().next().getPane().getIndex(); - } while (newPane.getIndex() > existingPane - && !contents.compareAndSet(existingValues, windowValues)); - } - - private static class CallbackSchedulingLoader extends - CacheLoader, AtomicReference>>> { - private final InProcessEvaluationContext context; - - public CallbackSchedulingLoader( - InProcessEvaluationContext context) { - this.context = context; - } - - @Override - public AtomicReference>> - load(PCollectionViewWindow view) { - - AtomicReference>> contents = new AtomicReference<>(); - WindowingStrategy windowingStrategy = view.getView().getWindowingStrategyInternal(); - - context.scheduleAfterOutputWouldBeProduced(view.getView(), - view.getWindow(), - windowingStrategy, - new WriteEmptyViewContents(view.getView(), view.getWindow(), contents)); - return contents; - } - } - - private static class WriteEmptyViewContents implements Runnable { - private final PCollectionView view; - private final BoundedWindow window; - private final AtomicReference>> contents; - - private WriteEmptyViewContents(PCollectionView view, BoundedWindow window, - AtomicReference>> contents) { - this.contents = contents; - this.view = view; - this.window = window; - } - - @Override - public void run() { - // The requested window has closed without producing elements, so reflect that in - // the PCollectionView. If set has already been called, will do nothing. - contents.compareAndSet(null, Collections.>emptyList()); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("view", view) - .add("window", window) - .toString(); - } - } - - private final class SideInputContainerSideInputReader implements ReadyCheckingSideInputReader { - private final Collection> readerViews; - private final LoadingCache< - PCollectionViewWindow, Optional>>> - viewContents; - - private SideInputContainerSideInputReader(Collection> readerViews) { - this.readerViews = ImmutableSet.copyOf(readerViews); - this.viewContents = CacheBuilder.newBuilder().build(new CurrentViewContentsLoader()); - } - - @Override - public boolean isReady(final PCollectionView view, final BoundedWindow window) { - checkArgument( - readerViews.contains(view), - "Tried to check if view %s was ready in a SideInputReader that does not contain it. " - + "Contained views; %s", - view, - readerViews); - return viewContents.getUnchecked(PCollectionViewWindow.of(view, window)).isPresent(); - } - - @Override - @Nullable - public T get(final PCollectionView view, final BoundedWindow window) { - checkArgument(readerViews.contains(view), - "call to get(PCollectionView) with unknown view: %s", - view); - checkArgument( - isReady(view, window), - "calling get() on PCollectionView %s that is not ready in window %s", - view, - window); - // Safe covariant cast - @SuppressWarnings("unchecked") Iterable> values = - (Iterable>) viewContents.getUnchecked(PCollectionViewWindow.of(view, - window)).get(); - return view.fromIterableInternal(values); - } - - @Override - public boolean contains(PCollectionView view) { - return readerViews.contains(view); - } - - @Override - public boolean isEmpty() { - return readerViews.isEmpty(); - } - } - - /** - * A {@link CacheLoader} that loads the current contents of a {@link PCollectionViewWindow} into - * an optional. - */ - private class CurrentViewContentsLoader extends CacheLoader< - PCollectionViewWindow, Optional>>> { - - @Override - public Optional>> - load(PCollectionViewWindow key) { - return Optional.fromNullable(viewByWindows.getUnchecked(key).get()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java deleted file mode 100644 index 72f8b4621b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternals.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; -import com.google.cloud.dataflow.sdk.util.TimerInternals; - -import org.joda.time.Instant; - -import javax.annotation.Nullable; - -/** - * An implementation of {@link TimerInternals} where all relevant data exists in memory. - */ -class InProcessTimerInternals implements TimerInternals { - private final Clock processingTimeClock; - private final TransformWatermarks watermarks; - private final TimerUpdateBuilder timerUpdateBuilder; - - public static InProcessTimerInternals create( - Clock clock, TransformWatermarks watermarks, TimerUpdateBuilder timerUpdateBuilder) { - return new InProcessTimerInternals(clock, watermarks, timerUpdateBuilder); - } - - private InProcessTimerInternals( - Clock clock, TransformWatermarks watermarks, TimerUpdateBuilder timerUpdateBuilder) { - this.processingTimeClock = clock; - this.watermarks = watermarks; - this.timerUpdateBuilder = timerUpdateBuilder; - } - - @Override - public void setTimer(TimerData timerKey) { - timerUpdateBuilder.setTimer(timerKey); - } - - @Override - public void deleteTimer(TimerData timerKey) { - timerUpdateBuilder.deletedTimer(timerKey); - } - - public TimerUpdate getTimerUpdate() { - return timerUpdateBuilder.build(); - } - - @Override - public Instant currentProcessingTime() { - return processingTimeClock.now(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return watermarks.getSynchronizedProcessingInputTime(); - } - - @Override - public Instant currentInputWatermarkTime() { - return watermarks.getInputWatermark(); - } - - @Override - @Nullable - public Instant currentOutputWatermarkTime() { - return watermarks.getOutputWatermark(); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java deleted file mode 100644 index 996d51b6b1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTransformResult.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; -import org.joda.time.Instant; -import java.util.Set; -import javax.annotation.Nullable; - -/** - * The result of evaluating an {@link AppliedPTransform} with a {@link TransformEvaluator}. - */ -interface InProcessTransformResult { - /** - * Returns the {@link AppliedPTransform} that produced this result. - */ - AppliedPTransform getTransform(); - - /** - * Returns the {@link UncommittedBundle (uncommitted) Bundles} output by this transform. These - * will be committed by the evaluation context as part of completing this result. - */ - Iterable> getOutputBundles(); - - /** - * Returns elements that were provided to the {@link TransformEvaluator} as input but were not - * processed. - */ - Iterable> getUnprocessedElements(); - - /** - * Returns the {@link CounterSet} used by this {@link PTransform}, or null if this transform did - * not use a {@link CounterSet}. - */ - @Nullable CounterSet getCounters(); - - /** - * Returns the Watermark Hold for the transform at the time this result was produced. - * - *

              If the transform does not set any watermark hold, returns - * {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. - */ - Instant getWatermarkHold(); - - /** - * Returns the State used by the transform. - * - *

              If this evaluation did not access state, this may return null. - */ - @Nullable - CopyOnAccessInMemoryStateInternals getState(); - - /** - * Returns a TimerUpdateBuilder that was produced as a result of this evaluation. If the - * evaluation was triggered due to the delivery of one or more timers, those timers must be added - * to the builder before it is complete. - * - *

              If this evaluation did not add or remove any timers, returns an empty TimerUpdate. - */ - TimerUpdate getTimerUpdate(); - - /** - * Returns the types of output produced by this {@link PTransform}. This may not include - * {@link OutputType#BUNDLE}, as empty bundles may be dropped when the transform is committed. - */ - Set getOutputTypes(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java deleted file mode 100644 index 23a8c0f506..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitor.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PValue; - -import java.util.HashSet; -import java.util.Set; - -/** - * A pipeline visitor that tracks all keyed {@link PValue PValues}. A {@link PValue} is keyed if it - * is the result of a {@link PTransform} that produces keyed outputs. A {@link PTransform} that - * produces keyed outputs is assumed to colocate output elements that share a key. - * - *

              All {@link GroupByKey} transforms, or their runner-specific implementation primitive, produce - * keyed output. - */ -// TODO: Handle Key-preserving transforms when appropriate and more aggressively make PTransforms -// unkeyed -class KeyedPValueTrackingVisitor implements PipelineVisitor { - @SuppressWarnings("rawtypes") - private final Set> producesKeyedOutputs; - private final Set keyedValues; - private boolean finalized; - - public static KeyedPValueTrackingVisitor create( - @SuppressWarnings("rawtypes") Set> producesKeyedOutputs) { - return new KeyedPValueTrackingVisitor(producesKeyedOutputs); - } - - private KeyedPValueTrackingVisitor( - @SuppressWarnings("rawtypes") Set> producesKeyedOutputs) { - this.producesKeyedOutputs = producesKeyedOutputs; - this.keyedValues = new HashSet<>(); - } - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - checkState( - !finalized, - "Attempted to use a %s that has already been finalized on a pipeline (visiting node %s)", - KeyedPValueTrackingVisitor.class.getSimpleName(), - node); - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - checkState( - !finalized, - "Attempted to use a %s that has already been finalized on a pipeline (visiting node %s)", - KeyedPValueTrackingVisitor.class.getSimpleName(), - node); - if (node.isRootNode()) { - finalized = true; - } else if (producesKeyedOutputs.contains(node.getTransform().getClass())) { - keyedValues.addAll(node.getExpandedOutputs()); - } - } - - @Override - public void visitTransform(TransformTreeNode node) {} - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - if (producesKeyedOutputs.contains(producer.getTransform().getClass())) { - keyedValues.addAll(value.expand()); - } - } - - public Set getKeyedPValues() { - checkState( - finalized, "can't call getKeyedPValues before a Pipeline has been completely traversed"); - return keyedValues; - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java deleted file mode 100644 index ee41f42276..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedResourcePool.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.common.base.Optional; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; - -/** - * A pool of resources associated with specific keys. Implementations enforce specific use patterns, - * such as limiting the the number of outstanding elements available per key. - */ -interface KeyedResourcePool { - /** - * Tries to acquire a value for the provided key, loading it via the provided loader if necessary. - * - *

              If the returned {@link Optional} contains a value, the caller obtains ownership of that - * value. The value should be released back to this {@link KeyedResourcePool} after the - * caller no longer has use of it using {@link #release(Object, Object)}. - * - *

              The provided {@link Callable} must not return null; it may either return a non-null - * value or throw an exception. - */ - Optional tryAcquire(K key, Callable loader) throws ExecutionException; - - /** - * Release the provided value, relinquishing ownership of it. Future calls to - * {@link #tryAcquire(Object, Callable)} may return the released value. - */ - void release(K key, V value); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java deleted file mode 100644 index 8757183e06..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePool.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.ExecutionError; -import com.google.common.util.concurrent.UncheckedExecutionException; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutionException; - -/** - * A {@link KeyedResourcePool} which is limited to at most one outstanding instance at a time for - * each key. - */ -class LockedKeyedResourcePool implements KeyedResourcePool { - /** - * A map from each key to an {@link Optional} of the associated value. At most one value is stored - * per key, and it is obtained by at most one thread at a time. - * - *

              For each key in this map: - * - *

                - *
              • If there is no associated value, then no value has been stored yet. - *
              • If the value is {@code Optional.absent()} then the value is currently in use. - *
              • If the value is {@code Optional.present()} then the contained value is available for use. - *
              - */ - public static LockedKeyedResourcePool create() { - return new LockedKeyedResourcePool<>(); - } - - private final ConcurrentMap> cache; - - private LockedKeyedResourcePool() { - cache = new ConcurrentHashMap<>(); - } - - @Override - public Optional tryAcquire(K key, Callable loader) throws ExecutionException { - Optional value = cache.replace(key, Optional.absent()); - if (value == null) { - // No value already existed, so populate the cache with the value returned by the loader - cache.putIfAbsent(key, Optional.of(load(loader))); - // Some other thread may obtain the result after the putIfAbsent, so retry acquisition - value = cache.replace(key, Optional.absent()); - } - return value; - } - - private V load(Callable loader) throws ExecutionException { - try { - return loader.call(); - } catch (Error t) { - throw new ExecutionError(t); - } catch (RuntimeException e) { - throw new UncheckedExecutionException(e); - } catch (Exception e) { - throw new ExecutionException(e); - } - } - - @Override - public void release(K key, V value) { - Optional replaced = cache.replace(key, Optional.of(value)); - checkNotNull(replaced, "Tried to release before a value was acquired"); - checkState( - !replaced.isPresent(), - "Released a value to a %s where there is already a value present for key %s (%s). " - + "At most one value may be present at a time.", - LockedKeyedResourcePool.class.getSimpleName(), - key, - replaced); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java deleted file mode 100644 index 66bea3767a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcement.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * Enforcement tools that verify that executing code conforms to the model. - * - *

              ModelEnforcement is performed on a per-element and per-bundle basis. The - * {@link ModelEnforcement} is provided with the input bundle as part of - * {@link ModelEnforcementFactory#forBundle(CommittedBundle, AppliedPTransform)}, each element - * before and after that element is provided to an underlying {@link TransformEvaluator}, and the - * output {@link InProcessTransformResult} and committed output bundles after the - * {@link TransformEvaluator} has completed. - * - *

              Typically, {@link ModelEnforcement} will obtain required metadata (such as the {@link Coder} - * of the input {@link PCollection} on construction, and then enforce per-element behavior - * (such as the immutability of input elements). When the element is output or the bundle is - * completed, the required conditions can be enforced across all elements. - */ -public interface ModelEnforcement { - /** - * Called before a call to {@link TransformEvaluator#processElement(WindowedValue)} on the - * provided {@link WindowedValue}. - */ - void beforeElement(WindowedValue element); - - /** - * Called after a call to {@link TransformEvaluator#processElement(WindowedValue)} on the - * provided {@link WindowedValue}. - */ - void afterElement(WindowedValue element); - - /** - * Called after a bundle has been completed and {@link TransformEvaluator#finishBundle()} has been - * called, producing the provided {@link InProcessTransformResult} and - * {@link CommittedBundle output bundles}. - */ - void afterFinish( - CommittedBundle input, - InProcessTransformResult result, - Iterable> outputs); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java deleted file mode 100644 index 66c01b3c81..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ModelEnforcementFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; - -/** - * Creates {@link ModelEnforcement} instances for an {@link AppliedPTransform} on an input - * {@link CommittedBundle bundle}. {@link ModelEnforcement} instances are created before the - * {@link TransformEvaluator} is created. - */ -public interface ModelEnforcementFactory { - ModelEnforcement forBundle(CommittedBundle input, AppliedPTransform consumer); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java deleted file mode 100644 index ce95b541f6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/NanosOffsetClock.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import org.joda.time.Instant; -import java.util.concurrent.TimeUnit; - -/** - * A {@link Clock} that uses {@link System#nanoTime()} to track the progress of time. - */ -public class NanosOffsetClock implements Clock { - private final long baseMillis; - private final long nanosAtBaseMillis; - - public static NanosOffsetClock create() { - return new NanosOffsetClock(); - } - - private NanosOffsetClock() { - baseMillis = System.currentTimeMillis(); - nanosAtBaseMillis = System.nanoTime(); - } - - @Override - public Instant now() { - return new Instant( - baseMillis + (TimeUnit.MILLISECONDS.convert( - System.nanoTime() - nanosAtBaseMillis, TimeUnit.NANOSECONDS))); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java deleted file mode 100644 index f32552614a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PTransformOverrideFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; - -interface PTransformOverrideFactory { - /** - * Create a {@link PTransform} override for the provided {@link PTransform} if applicable. - * Otherwise, return the input {@link PTransform}. - * - *

              The returned PTransform must be semantically equivalent to the input {@link PTransform}. - */ - PTransform override( - PTransform transform); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java deleted file mode 100644 index 4fba3bdbeb..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluator.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.PushbackSideInputDoFnRunner; -import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ImmutableList; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -class ParDoInProcessEvaluator implements TransformEvaluator { - public static ParDoInProcessEvaluator create( - InProcessEvaluationContext evaluationContext, - CommittedBundle inputBundle, - AppliedPTransform, ?, ?> application, - DoFn fn, - List> sideInputs, - TupleTag mainOutputTag, - List> sideOutputTags, - Map, PCollection> outputs) { - InProcessExecutionContext executionContext = - evaluationContext.getExecutionContext(application, inputBundle.getKey()); - String stepName = evaluationContext.getStepName(application); - InProcessStepContext stepContext = - executionContext.getOrCreateStepContext(stepName, stepName, null); - - CounterSet counters = evaluationContext.createCounterSet(); - - Map, UncommittedBundle> outputBundles = new HashMap<>(); - for (Map.Entry, PCollection> outputEntry : outputs.entrySet()) { - outputBundles.put( - outputEntry.getKey(), - evaluationContext.createBundle(inputBundle, outputEntry.getValue())); - } - - ReadyCheckingSideInputReader sideInputReader = - evaluationContext.createSideInputReader(sideInputs); - DoFnRunner underlying = - DoFnRunners.createDefault( - evaluationContext.getPipelineOptions(), - SerializableUtils.clone(fn), - sideInputReader, - BundleOutputManager.create(outputBundles), - mainOutputTag, - sideOutputTags, - stepContext, - counters.getAddCounterMutator(), - application.getInput().getWindowingStrategy()); - PushbackSideInputDoFnRunner runner = - PushbackSideInputDoFnRunner.create(underlying, sideInputs, sideInputReader); - - try { - runner.startBundle(); - } catch (Exception e) { - throw UserCodeException.wrap(e); - } - - return new ParDoInProcessEvaluator<>( - runner, application, counters, outputBundles.values(), stepContext); - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - - private final PushbackSideInputDoFnRunner fnRunner; - private final AppliedPTransform, ?, ?> transform; - private final CounterSet counters; - private final Collection> outputBundles; - private final InProcessStepContext stepContext; - - private final ImmutableList.Builder> unprocessedElements; - - private ParDoInProcessEvaluator( - PushbackSideInputDoFnRunner fnRunner, - AppliedPTransform, ?, ?> transform, - CounterSet counters, - Collection> outputBundles, - InProcessStepContext stepContext) { - this.fnRunner = fnRunner; - this.transform = transform; - this.counters = counters; - this.outputBundles = outputBundles; - this.stepContext = stepContext; - - this.unprocessedElements = ImmutableList.builder(); - } - - @Override - public void processElement(WindowedValue element) { - try { - Iterable> unprocessed = fnRunner.processElementInReadyWindows(element); - unprocessedElements.addAll(unprocessed); - } catch (Exception e) { - throw UserCodeException.wrap(e); - } - } - - @Override - public InProcessTransformResult finishBundle() { - try { - fnRunner.finishBundle(); - } catch (Exception e) { - throw UserCodeException.wrap(e); - } - StepTransformResult.Builder resultBuilder; - CopyOnAccessInMemoryStateInternals state = stepContext.commitState(); - if (state != null) { - resultBuilder = - StepTransformResult.withHold(transform, state.getEarliestWatermarkHold()) - .withState(state); - } else { - resultBuilder = StepTransformResult.withoutHold(transform); - } - return resultBuilder - .addOutput(outputBundles) - .withTimerUpdate(stepContext.getTimerUpdate()) - .withCounters(counters) - .addUnprocessedElements(unprocessedElements.build()) - .build(); - } - - static class BundleOutputManager implements OutputManager { - private final Map, UncommittedBundle> bundles; - private final Map, List> undeclaredOutputs; - - public static BundleOutputManager create(Map, UncommittedBundle> outputBundles) { - return new BundleOutputManager(outputBundles); - } - - private BundleOutputManager(Map, UncommittedBundle> bundles) { - this.bundles = bundles; - undeclaredOutputs = new HashMap<>(); - } - - @SuppressWarnings("unchecked") - @Override - public void output(TupleTag tag, WindowedValue output) { - @SuppressWarnings("rawtypes") - UncommittedBundle bundle = bundles.get(tag); - if (bundle == null) { - List undeclaredContents = undeclaredOutputs.get(tag); - if (undeclaredContents == null) { - undeclaredContents = new ArrayList(); - undeclaredOutputs.put(tag, undeclaredContents); - } - undeclaredContents.add(output); - } else { - bundle.add(output); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java deleted file mode 100644 index 245115b95b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.util.Map; - -/** - * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the - * {@link BoundMulti} primitive {@link PTransform}. - */ -class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory { - @Override - public TransformEvaluator forApplication( - AppliedPTransform application, - CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) { - @SuppressWarnings({"unchecked", "rawtypes"}) - TransformEvaluator evaluator = - createMultiEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); - return evaluator; - } - - private static ParDoInProcessEvaluator createMultiEvaluator( - AppliedPTransform, PCollectionTuple, BoundMulti> application, - CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) { - Map, PCollection> outputs = application.getOutput().getAll(); - DoFn fn = application.getTransform().getFn(); - - return ParDoInProcessEvaluator.create( - evaluationContext, - inputBundle, - application, - fn, - application.getTransform().getSideInputs(), - application.getTransform().getMainOutputTag(), - application.getTransform().getSideOutputTags().getAll(), - outputs); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java deleted file mode 100644 index 4d46fd1c1b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ImmutableMap; - -import java.util.Collections; - -/** - * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the - * {@link Bound ParDo.Bound} primitive {@link PTransform}. - */ -class ParDoSingleEvaluatorFactory implements TransformEvaluatorFactory { - @Override - public TransformEvaluator forApplication( - final AppliedPTransform application, - CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) { - @SuppressWarnings({"unchecked", "rawtypes"}) - TransformEvaluator evaluator = - createSingleEvaluator((AppliedPTransform) application, inputBundle, evaluationContext); - return evaluator; - } - - private static ParDoInProcessEvaluator createSingleEvaluator( - @SuppressWarnings("rawtypes") AppliedPTransform, PCollection, - Bound> application, - CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - TupleTag mainOutputTag = new TupleTag<>("out"); - - return ParDoInProcessEvaluator.create( - evaluationContext, - inputBundle, - application, - application.getTransform().getFn(), - application.getTransform().getSideInputs(), - mainOutputTag, - Collections.>emptyList(), - ImmutableMap., PCollection>of(mainOutputTag, application.getOutput())); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java deleted file mode 100644 index 0392dab19b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/PassthroughTransformEvaluator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -class PassthroughTransformEvaluator implements TransformEvaluator { - public static PassthroughTransformEvaluator create( - AppliedPTransform transform, UncommittedBundle output) { - return new PassthroughTransformEvaluator<>(transform, output); - } - - private final AppliedPTransform transform; - private final UncommittedBundle output; - - private PassthroughTransformEvaluator( - AppliedPTransform transform, UncommittedBundle output) { - this.transform = transform; - this.output = output; - } - - @Override - public void processElement(WindowedValue element) throws Exception { - output.add(element); - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - return StepTransformResult.withoutHold(transform).addOutput(output).build(); - } - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java deleted file mode 100644 index feba98f001..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepAndKey.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.common.base.MoreObjects; - -import java.util.Objects; - -/** - * A (Step, Key) pair. This is useful as a map key or cache key for things that are available - * per-step in a keyed manner (e.g. State). - */ -final class StepAndKey { - private final AppliedPTransform step; - private final StructuralKey key; - - /** - * Create a new {@link StepAndKey} with the provided step and key. - */ - public static StepAndKey of(AppliedPTransform step, StructuralKey key) { - return new StepAndKey(step, key); - } - - private StepAndKey(AppliedPTransform step, StructuralKey key) { - this.step = step; - this.key = key; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(StepAndKey.class) - .add("step", step.getFullName()) - .add("key", key.getKey()) - .toString(); - } - - @Override - public int hashCode() { - return Objects.hash(step, key); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } else if (!(other instanceof StepAndKey)) { - return false; - } else { - StepAndKey that = (StepAndKey) other; - return Objects.equals(this.step, that.step) - && Objects.equals(this.key, that.key); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java deleted file mode 100644 index da6d658870..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResult.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.auto.value.AutoValue; -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; -import com.google.common.collect.ImmutableList; -import org.joda.time.Instant; -import java.util.Collection; -import java.util.EnumSet; -import java.util.Set; -import javax.annotation.Nullable; - -/** - * An immutable {@link InProcessTransformResult}. - */ -@AutoValue -public abstract class StepTransformResult implements InProcessTransformResult { - @Override - public abstract AppliedPTransform getTransform(); - - @Override - public abstract Iterable> getOutputBundles(); - - @Override - public abstract Iterable> getUnprocessedElements(); - - @Override - @Nullable - public abstract CounterSet getCounters(); - - @Override - public abstract Instant getWatermarkHold(); - - @Nullable - @Override - public abstract CopyOnAccessInMemoryStateInternals getState(); - - @Override - public abstract TimerUpdate getTimerUpdate(); - - @Override - public abstract Set getOutputTypes(); - - public static Builder withHold(AppliedPTransform transform, Instant watermarkHold) { - return new Builder(transform, watermarkHold); - } - - public static Builder withoutHold(AppliedPTransform transform) { - return new Builder(transform, BoundedWindow.TIMESTAMP_MAX_VALUE); - } - - /** - * A builder for creating instances of {@link StepTransformResult}. - */ - public static class Builder { - private final AppliedPTransform transform; - private final ImmutableList.Builder> bundlesBuilder; - private final ImmutableList.Builder> unprocessedElementsBuilder; - private CopyOnAccessInMemoryStateInternals state; - private TimerUpdate timerUpdate; - private CounterSet counters; - private final Set producedOutputs; - private final Instant watermarkHold; - - private Builder(AppliedPTransform transform, Instant watermarkHold) { - this.transform = transform; - this.watermarkHold = watermarkHold; - this.bundlesBuilder = ImmutableList.builder(); - this.producedOutputs = EnumSet.noneOf(OutputType.class); - this.unprocessedElementsBuilder = ImmutableList.builder(); - this.timerUpdate = TimerUpdate.builder(null).build(); - } - - public StepTransformResult build() { - return new AutoValue_StepTransformResult( - transform, - bundlesBuilder.build(), - unprocessedElementsBuilder.build(), - counters, - watermarkHold, - state, - timerUpdate, - producedOutputs); - } - - public Builder withCounters(CounterSet counters) { - this.counters = counters; - return this; - } - - public Builder withState(CopyOnAccessInMemoryStateInternals state) { - this.state = state; - return this; - } - - public Builder withTimerUpdate(TimerUpdate timerUpdate) { - this.timerUpdate = timerUpdate; - return this; - } - - public Builder addUnprocessedElements(Iterable> unprocessed) { - unprocessedElementsBuilder.addAll(unprocessed); - return this; - } - - public Builder addOutput( - UncommittedBundle outputBundle, UncommittedBundle... outputBundles) { - bundlesBuilder.add(outputBundle); - bundlesBuilder.add(outputBundles); - return this; - } - - public Builder addOutput(Collection> outputBundles) { - bundlesBuilder.addAll(outputBundles); - return this; - } - - public Builder withAdditionalOutput(OutputType producedAdditionalOutput) { - producedOutputs.add(producedAdditionalOutput); - return this; - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java deleted file mode 100644 index a1fe07e4d9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKey.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -/** - * A (Key, Coder) pair that uses the structural value of the key (as provided by - * {@link Coder#structuralValue(Object)}) to perform equality and hashing. - */ -class StructuralKey { - /** - * Create a new Structural Key of the provided key that can be encoded by the provided coder. - */ - public static StructuralKey of(K key, Coder coder) { - try { - return new StructuralKey<>(coder, key); - } catch (Exception e) { - throw new IllegalArgumentException( - "Could not encode a key with its provided coder " + coder.getClass().getSimpleName(), e); - } - } - - private final Coder coder; - private final Object structuralValue; - private final byte[] encoded; - - private StructuralKey(Coder coder, K key) throws Exception { - this.coder = coder; - this.structuralValue = coder.structuralValue(key); - this.encoded = CoderUtils.encodeToByteArray(coder, key); - } - - public K getKey() { - try { - return CoderUtils.decodeFromByteArray(coder, encoded); - } catch (CoderException e) { - throw new IllegalArgumentException( - "Could not decode Key with coder of type " + coder.getClass().getSimpleName()); - } - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (other instanceof StructuralKey) { - StructuralKey that = (StructuralKey) other; - return structuralValue.equals(that.structuralValue); - } - return false; - } - - @Override - public int hashCode() { - return structuralValue.hashCode(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java deleted file mode 100644 index 52e4e19e2e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactory.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestStream; -import com.google.cloud.dataflow.sdk.testing.TestStream.ElementEvent; -import com.google.cloud.dataflow.sdk.testing.TestStream.Event; -import com.google.cloud.dataflow.sdk.testing.TestStream.EventType; -import com.google.cloud.dataflow.sdk.testing.TestStream.ProcessingTimeEvent; -import com.google.cloud.dataflow.sdk.testing.TestStream.WatermarkEvent; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.base.Supplier; -import org.joda.time.Duration; -import org.joda.time.Instant; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicReference; -import javax.annotation.Nullable; - -/** The {@link TransformEvaluatorFactory} for the {@link TestStream} primitive. */ -class TestStreamEvaluatorFactory implements TransformEvaluatorFactory { - private final KeyedResourcePool, Evaluator> evaluators = - LockedKeyedResourcePool.create(); - - @Nullable - @Override - public TransformEvaluator forApplication( - AppliedPTransform application, - @Nullable CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) - throws Exception { - return createEvaluator((AppliedPTransform) application, evaluationContext); - } - - /** - * Returns the evaluator for the provided application of {@link TestStream}, or null if it is - * already in use. - * - *

              The documented behavior of {@link TestStream} requires the output of one event to travel - * completely through the pipeline before any additional event, so additional instances that have - * a separate collection of events cannot be created. - */ - private TransformEvaluator createEvaluator( - AppliedPTransform, TestStream> application, - InProcessEvaluationContext evaluationContext) - throws ExecutionException { - return evaluators - .tryAcquire(application, new CreateEvaluator<>(application, evaluationContext, evaluators)) - .orNull(); - } - - private static class Evaluator implements TransformEvaluator { - private final AppliedPTransform, TestStream> application; - private final InProcessEvaluationContext context; - private final KeyedResourcePool, Evaluator> cache; - private final List> events; - private int index; - private Instant currentWatermark; - - private Evaluator( - AppliedPTransform, TestStream> application, - InProcessEvaluationContext context, - KeyedResourcePool, Evaluator> cache) { - this.application = application; - this.context = context; - this.cache = cache; - this.events = application.getTransform().getEvents(); - index = 0; - currentWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - @Override - public void processElement(WindowedValue element) throws Exception {} - - @Override - public InProcessTransformResult finishBundle() throws Exception { - try { - if (index >= events.size()) { - return StepTransformResult.withoutHold(application).build(); - } - Event event = events.get(index); - if (event.getType().equals(EventType.WATERMARK)) { - currentWatermark = ((WatermarkEvent) event).getWatermark(); - } - StepTransformResult.Builder result = - StepTransformResult.withHold(application, currentWatermark); - if (event.getType().equals(EventType.ELEMENT)) { - UncommittedBundle bundle = context.createRootBundle(application.getOutput()); - for (TimestampedValue elem : ((ElementEvent) event).getElements()) { - bundle.add( - WindowedValue.timestampedValueInGlobalWindow(elem.getValue(), elem.getTimestamp())); - } - result.addOutput(bundle); - } - if (event.getType().equals(EventType.PROCESSING_TIME)) { - ((TestClock) context.getClock()) - .advance(((ProcessingTimeEvent) event).getProcessingTimeAdvance()); - } - index++; - return result.build(); - } finally { - cache.release(application, this); - } - } - } - - private static class TestClock implements Clock { - private final AtomicReference currentTime = - new AtomicReference<>(BoundedWindow.TIMESTAMP_MIN_VALUE); - - public void advance(Duration amount) { - Instant now = currentTime.get(); - currentTime.compareAndSet(now, now.plus(amount)); - } - - @Override - public Instant now() { - return currentTime.get(); - } - } - - private static class TestClockSupplier implements Supplier { - @Override - public Clock get() { - return new TestClock(); - } - } - - static class InProcessTestStreamFactory implements PTransformOverrideFactory { - @Override - public PTransform override( - PTransform transform) { - if (transform instanceof TestStream) { - return (PTransform) - new DirectTestStream((TestStream) transform); - } - return transform; - } - - private static class DirectTestStream extends PTransform> { - private final TestStream original; - - private DirectTestStream(TestStream transform) { - this.original = transform; - } - - @Override - public PCollection apply(PBegin input) { - PipelineRunner runner = input.getPipeline().getRunner(); - checkState( - runner instanceof InProcessPipelineRunner, - "%s can only be used when running with the %s", - getClass().getSimpleName(), - InProcessPipelineRunner.class.getSimpleName()); - input.getPipeline() - .getOptions() - .as(InProcessPipelineOptions.class) - .setShutdownUnboundedProducersWithMaxWatermark(true); - ((InProcessPipelineRunner) runner).setClockSupplier(new TestClockSupplier()); - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), WindowingStrategy.globalDefault(), IsBounded.UNBOUNDED) - .setCoder(original.getValueCoder()); - } - } - } - - private static class CreateEvaluator implements Callable> { - private final AppliedPTransform, TestStream> application; - private final InProcessEvaluationContext evaluationContext; - private final KeyedResourcePool, Evaluator> evaluators; - - public CreateEvaluator( - AppliedPTransform, TestStream> application, - InProcessEvaluationContext evaluationContext, - KeyedResourcePool, Evaluator> evaluators) { - this.application = application; - this.evaluationContext = evaluationContext; - this.evaluators = evaluators; - } - - @Override - public Evaluator call() throws Exception { - return new Evaluator<>(application, evaluationContext, evaluators); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java deleted file mode 100644 index f4e9d028f7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -/** - * An evaluator of a specific application of a transform. Will be used for at least one - * {@link CommittedBundle}. - * - * @param the type of elements that will be passed to {@link #processElement} - */ -interface TransformEvaluator { - /** - * Process an element in the input {@link CommittedBundle}. - * - * @param element the element to process - */ - void processElement(WindowedValue element) throws Exception; - - /** - * Finish processing the bundle of this {@link TransformEvaluator}. - * - *

              After {@link #finishBundle()} is called, the {@link TransformEvaluator} will not be reused, - * and no more elements will be processed. - * - * @return an {@link InProcessTransformResult} containing the results of this bundle evaluation. - */ - InProcessTransformResult finishBundle() throws Exception; -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java deleted file mode 100644 index a91337f28e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -import javax.annotation.Nullable; - -/** - * A factory for creating instances of {@link TransformEvaluator} for the application of a - * {@link PTransform}. - */ -interface TransformEvaluatorFactory { - /** - * Create a new {@link TransformEvaluator} for the application of the {@link PTransform}. - * - *

              Any work that must be done before input elements are processed (such as calling - * {@link DoFn#startBundle(DoFn.Context)}) must be done before the {@link TransformEvaluator} is - * made available to the caller. - * - *

              May return null if the application cannot produce an evaluator (for example, it is a - * {@link Read} {@link PTransform} where all evaluators are in-use). - * - * @return An evaluator capable of processing the transform on the bundle, or null if no evaluator - * can be constructed. - * @throws Exception whenever constructing the underlying evaluator throws an exception - */ - @Nullable TransformEvaluator forApplication( - AppliedPTransform application, @Nullable CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java deleted file mode 100644 index cbcf3ba77b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformEvaluatorRegistry.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestStream; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Flatten.FlattenPCollectionList; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import javax.annotation.Nullable; - -/** - * A {@link TransformEvaluatorFactory} that delegates to primitive {@link TransformEvaluatorFactory} - * implementations based on the type of {@link PTransform} of the application. - */ -class TransformEvaluatorRegistry implements TransformEvaluatorFactory { - public static TransformEvaluatorRegistry defaultRegistry() { - @SuppressWarnings("rawtypes") - ImmutableMap, TransformEvaluatorFactory> primitives = - ImmutableMap., TransformEvaluatorFactory>builder() - .put(Read.Bounded.class, new BoundedReadEvaluatorFactory()) - .put(Read.Unbounded.class, new UnboundedReadEvaluatorFactory()) - .put(ParDo.Bound.class, new ParDoSingleEvaluatorFactory()) - .put(ParDo.BoundMulti.class, new ParDoMultiEvaluatorFactory()) - .put( - GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly.class, - new GroupByKeyEvaluatorFactory()) - .put(FlattenPCollectionList.class, new FlattenEvaluatorFactory()) - .put(ViewEvaluatorFactory.WriteView.class, new ViewEvaluatorFactory()) - .put(Window.Bound.class, new WindowEvaluatorFactory()) - .put(TestStream.class, new TestStreamEvaluatorFactory()) - .build(); - return new TransformEvaluatorRegistry(primitives); - } - - // the TransformEvaluatorFactories can construct instances of all generic types of transform, - // so all instances of a primitive can be handled with the same evaluator factory. - @SuppressWarnings("rawtypes") - private final Map, TransformEvaluatorFactory> factories; - - private TransformEvaluatorRegistry( - @SuppressWarnings("rawtypes") - Map, TransformEvaluatorFactory> factories) { - this.factories = factories; - } - - @Override - public TransformEvaluator forApplication( - AppliedPTransform application, - @Nullable CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) - throws Exception { - TransformEvaluatorFactory factory = factories.get(application.getTransform().getClass()); - return factory.forApplication(application, inputBundle, evaluationContext); - } - - /** - * A factory to create Transform Evaluator Registries. - */ - public static class Factory { - public TransformEvaluatorRegistry create() { - return TransformEvaluatorRegistry.defaultRegistry(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java deleted file mode 100644 index bc20af13fe..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutor.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Nullable; - -/** - * A {@link Callable} responsible for constructing a {@link TransformEvaluator} from a - * {@link TransformEvaluatorFactory} and evaluating it on some bundle of input, and registering - * the result using a registered {@link CompletionCallback}. - * - *

              A {@link TransformExecutor} that is currently executing also provides access to the thread - * that it is being executed on. - */ -class TransformExecutor implements Runnable { - public static TransformExecutor create( - TransformEvaluatorFactory factory, - Iterable modelEnforcements, - InProcessEvaluationContext evaluationContext, - CommittedBundle inputBundle, - AppliedPTransform transform, - CompletionCallback completionCallback, - TransformExecutorService transformEvaluationState) { - return new TransformExecutor<>( - factory, - modelEnforcements, - evaluationContext, - inputBundle, - transform, - completionCallback, - transformEvaluationState); - } - - private final TransformEvaluatorFactory evaluatorFactory; - private final Iterable modelEnforcements; - - private final InProcessEvaluationContext evaluationContext; - - /** The transform that will be evaluated. */ - private final AppliedPTransform transform; - /** The inputs this {@link TransformExecutor} will deliver to the transform. */ - private final CommittedBundle inputBundle; - - private final CompletionCallback onComplete; - private final TransformExecutorService transformEvaluationState; - - private final AtomicReference thread; - - private TransformExecutor( - TransformEvaluatorFactory factory, - Iterable modelEnforcements, - InProcessEvaluationContext evaluationContext, - CommittedBundle inputBundle, - AppliedPTransform transform, - CompletionCallback completionCallback, - TransformExecutorService transformEvaluationState) { - this.evaluatorFactory = factory; - this.modelEnforcements = modelEnforcements; - this.evaluationContext = evaluationContext; - - this.inputBundle = inputBundle; - this.transform = transform; - - this.onComplete = completionCallback; - - this.transformEvaluationState = transformEvaluationState; - this.thread = new AtomicReference<>(); - } - - @Override - public void run() { - checkState( - thread.compareAndSet(null, Thread.currentThread()), - "Tried to execute %s for %s on thread %s, but is already executing on thread %s", - TransformExecutor.class.getSimpleName(), - transform.getFullName(), - Thread.currentThread(), - thread.get()); - try { - Collection> enforcements = new ArrayList<>(); - for (ModelEnforcementFactory enforcementFactory : modelEnforcements) { - ModelEnforcement enforcement = enforcementFactory.forBundle(inputBundle, transform); - enforcements.add(enforcement); - } - TransformEvaluator evaluator = - evaluatorFactory.forApplication(transform, inputBundle, evaluationContext); - if (evaluator == null) { - onComplete.handleEmpty(transform); - // Nothing to do - return; - } - - processElements(evaluator, enforcements); - - finishBundle(evaluator, enforcements); - } catch (Throwable t) { - onComplete.handleThrowable(inputBundle, t); - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - throw new RuntimeException(t); - } finally { - transformEvaluationState.complete(this); - } - } - - /** - * Processes all the elements in the input bundle using the transform evaluator, applying any - * necessary {@link ModelEnforcement ModelEnforcements}. - */ - private void processElements( - TransformEvaluator evaluator, Collection> enforcements) - throws Exception { - if (inputBundle != null) { - for (WindowedValue value : inputBundle.getElements()) { - for (ModelEnforcement enforcement : enforcements) { - enforcement.beforeElement(value); - } - - evaluator.processElement(value); - - for (ModelEnforcement enforcement : enforcements) { - enforcement.afterElement(value); - } - } - } - } - - /** - * Finishes processing the input bundle and commit the result using the - * {@link CompletionCallback}, applying any {@link ModelEnforcement} if necessary. - * - * @return the {@link InProcessTransformResult} produced by - * {@link TransformEvaluator#finishBundle()} - */ - private InProcessTransformResult finishBundle( - TransformEvaluator evaluator, Collection> enforcements) - throws Exception { - InProcessTransformResult result = evaluator.finishBundle(); - CommittedResult outputs = onComplete.handleResult(inputBundle, result); - for (ModelEnforcement enforcement : enforcements) { - enforcement.afterFinish(inputBundle, result, outputs.getOutputs()); - } - return result; - } - - /** - * If this {@link TransformExecutor} is currently executing, return the thread it is executing in. - * Otherwise, return null. - */ - @Nullable - public Thread getThread() { - return thread.get(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java deleted file mode 100644 index 3f00da6ebe..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorService.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -/** - * Schedules and completes {@link TransformExecutor TransformExecutors}, controlling concurrency as - * appropriate for the {@link StepAndKey} the executor exists for. - */ -interface TransformExecutorService { - /** - * Schedule the provided work to be eventually executed. - */ - void schedule(TransformExecutor work); - - /** - * Finish executing the provided work. This may cause additional - * {@link TransformExecutor TransformExecutors} to be evaluated. - */ - void complete(TransformExecutor completed); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java deleted file mode 100644 index a4315ec0c9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServices.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.common.base.MoreObjects; - -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Static factory methods for constructing instances of {@link TransformExecutorService}. - */ -final class TransformExecutorServices { - private TransformExecutorServices() { - // Do not instantiate - } - - /** - * Returns an EvaluationState that evaluates {@link TransformExecutor TransformExecutors} in - * parallel. - */ - public static TransformExecutorService parallel(ExecutorService executor) { - return new ParallelEvaluationState(executor); - } - - /** - * Returns an EvaluationState that evaluates {@link TransformExecutor TransformExecutors} in - * serial. - */ - public static TransformExecutorService serial(ExecutorService executor) { - return new SerialEvaluationState(executor); - } - - /** - * A {@link TransformExecutorService} with unlimited parallelism. Any {@link TransformExecutor} - * scheduled will be immediately submitted to the {@link ExecutorService}. - * - *

              A principal use of this is for the evaluation of an unkeyed Step. Unkeyed computations are - * processed in parallel. - */ - private static class ParallelEvaluationState implements TransformExecutorService { - private final ExecutorService executor; - - private ParallelEvaluationState(ExecutorService executor) { - this.executor = executor; - } - - @Override - public void schedule(TransformExecutor work) { - executor.submit(work); - } - - @Override - public void complete(TransformExecutor completed) { - } - } - - /** - * A {@link TransformExecutorService} with a single work queue. Any {@link TransformExecutor} - * scheduled will be placed on the work queue. Only one item of work will be submitted to the - * {@link ExecutorService} at any time. - * - *

              A principal use of this is for the serial evaluation of a (Step, Key) pair. - * Keyed computations are processed serially per step. - */ - private static class SerialEvaluationState implements TransformExecutorService { - private final ExecutorService executor; - - private AtomicReference> currentlyEvaluating; - private final Queue> workQueue; - - private SerialEvaluationState(ExecutorService executor) { - this.executor = executor; - this.currentlyEvaluating = new AtomicReference<>(); - this.workQueue = new ConcurrentLinkedQueue<>(); - } - - /** - * Schedules the work, adding it to the work queue if there is a bundle currently being - * evaluated and scheduling it immediately otherwise. - */ - @Override - public void schedule(TransformExecutor work) { - workQueue.offer(work); - updateCurrentlyEvaluating(); - } - - @Override - public void complete(TransformExecutor completed) { - if (!currentlyEvaluating.compareAndSet(completed, null)) { - throw new IllegalStateException( - "Finished work " - + completed - + " but could not complete due to unexpected currently executing " - + currentlyEvaluating.get()); - } - updateCurrentlyEvaluating(); - } - - private void updateCurrentlyEvaluating() { - if (currentlyEvaluating.get() == null) { - // Only synchronize if we need to update what's currently evaluating - synchronized (this) { - TransformExecutor newWork = workQueue.poll(); - if (newWork != null) { - if (currentlyEvaluating.compareAndSet(null, newWork)) { - executor.submit(newWork); - } else { - workQueue.offer(newWork); - } - } - } - } - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(SerialEvaluationState.class) - .add("currentlyEvaluating", currentlyEvaluating) - .add("workQueue", workQueue) - .toString(); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java deleted file mode 100644 index 98ef0f54cd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicator.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; - -import org.joda.time.Duration; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Provides methods to determine if a record is a duplicate within the evaluation of a - * {@link Unbounded} {@link PTransform}. - */ -interface UnboundedReadDeduplicator { - /** - * Returns true if the record with the provided ID should be output, and false if it should not - * be because it is a duplicate. - */ - boolean shouldOutput(byte[] recordId); - - /** - * An {@link UnboundedReadDeduplicator} that always returns true. For use with sources do not - * require deduplication. - */ - class NeverDeduplicator implements UnboundedReadDeduplicator { - /** - * Create a new {@link NeverDeduplicator}. - */ - public static UnboundedReadDeduplicator create() { - return new NeverDeduplicator(); - } - - @Override - public boolean shouldOutput(byte[] recordId) { - return true; - } - } - - - /** - * An {@link UnboundedReadDeduplicator} that returns true if the record ID has not been seen - * within 10 minutes. - */ - class CachedIdDeduplicator implements UnboundedReadDeduplicator { - private static final ByteArrayCoder RECORD_ID_CODER = ByteArrayCoder.of(); - private static final long MAX_RETENTION_SINCE_ACCESS = - Duration.standardMinutes(10L).getMillis(); - - private final LoadingCache, AtomicBoolean> ids; - - /** - * Create a new {@link CachedIdDeduplicator}. - */ - public static UnboundedReadDeduplicator create() { - return new CachedIdDeduplicator(); - } - - private CachedIdDeduplicator() { - ids = CacheBuilder.newBuilder() - .expireAfterAccess(MAX_RETENTION_SINCE_ACCESS, TimeUnit.MILLISECONDS) - .maximumSize(100_000L) - .build(new TrueBooleanLoader()); - } - - @Override - public boolean shouldOutput(byte[] recordId) { - return ids.getUnchecked(StructuralKey.of(recordId, RECORD_ID_CODER)).getAndSet(false); - } - - private static class TrueBooleanLoader - extends CacheLoader, AtomicBoolean> { - @Override - public AtomicBoolean load(StructuralKey key) throws Exception { - return new AtomicBoolean(true); - } - } - } - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java deleted file mode 100644 index 3f57a9ae52..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactory.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.io.Read.Unbounded; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.annotations.VisibleForTesting; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; - -import javax.annotation.Nullable; - -/** - * A {@link TransformEvaluatorFactory} that produces {@link TransformEvaluator TransformEvaluators} - * for the {@link Unbounded Read.Unbounded} primitive {@link PTransform}. - */ -class UnboundedReadEvaluatorFactory implements TransformEvaluatorFactory { - // Resume from a checkpoint every nth invocation, to ensure close-and-resume is exercised - @VisibleForTesting - static final int MAX_READER_REUSE_COUNT = 20; - - /* - * An evaluator for a Source is stateful, to ensure the CheckpointMark is properly persisted. - * Evaluators are cached here to ensure that the checkpoint mark is appropriately reused - * and any splits are honored. - * - *

              The Queue storing available evaluators must enforce a happens-before relationship for - * elements being added to the queue to accesses after it, to ensure that updates performed to the - * state of an evaluator are properly visible. ConcurrentLinkedQueue provides this relation, but - * an arbitrary Queue implementation does not, so the concrete type is used explicitly. - */ - private final ConcurrentMap< - EvaluatorKey, ConcurrentLinkedQueue>> - sourceEvaluators = new ConcurrentHashMap<>(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - @Nullable - public TransformEvaluator forApplication(AppliedPTransform application, - @Nullable CommittedBundle inputBundle, InProcessEvaluationContext evaluationContext) { - return getTransformEvaluator((AppliedPTransform) application, evaluationContext); - } - - /** - * Get a {@link TransformEvaluator} that produce elements for the provided application of - * {@link Unbounded Read.Unbounded}, initializing the queue of evaluators if required. - * - *

              This method is thread-safe, and will only produce new evaluators if no other invocation has - * already done so. - */ - private - TransformEvaluator getTransformEvaluator( - final AppliedPTransform, Unbounded> transform, - final InProcessEvaluationContext evaluationContext) { - // Key by the application and the context the evaluation is occurring in (which call to - // Pipeline#run). - EvaluatorKey key = new EvaluatorKey(transform, evaluationContext); - @SuppressWarnings("unchecked") - ConcurrentLinkedQueue> evaluatorQueue = - (ConcurrentLinkedQueue>) - sourceEvaluators.get(key); - if (evaluatorQueue == null) { - evaluatorQueue = new ConcurrentLinkedQueue<>(); - if (sourceEvaluators.putIfAbsent(key, evaluatorQueue) == null) { - // If no queue existed in the evaluators, add an evaluator to initialize the evaluator - // factory for this transform - UnboundedSource source = - (UnboundedSource) transform.getTransform().getSource(); - UnboundedReadDeduplicator deduplicator; - if (source.requiresDeduping()) { - deduplicator = UnboundedReadDeduplicator.CachedIdDeduplicator.create(); - } else { - deduplicator = UnboundedReadDeduplicator.NeverDeduplicator.create(); - } - UnboundedReadEvaluator evaluator = - new UnboundedReadEvaluator<>( - transform, evaluationContext, source, deduplicator, evaluatorQueue); - evaluatorQueue.offer(evaluator); - } else { - // otherwise return the existing Queue that arrived before us - evaluatorQueue = - (ConcurrentLinkedQueue>) - sourceEvaluators.get(key); - } - } - return evaluatorQueue.poll(); - } - - /** - * A {@link UnboundedReadEvaluator} produces elements from an underlying {@link UnboundedSource}, - * discarding all input elements. Within the call to {@link #finishBundle()}, the evaluator - * creates the {@link UnboundedReader} and consumes some currently available input. - * - *

              Calls to {@link UnboundedReadEvaluator} are not internally thread-safe, and should only be - * used by a single thread at a time. Each {@link UnboundedReadEvaluator} maintains its own - * checkpoint, and constructs its reader from the current checkpoint in each call to - * {@link #finishBundle()}. - */ - private static class UnboundedReadEvaluator - implements TransformEvaluator { - private static final int ARBITRARY_MAX_ELEMENTS = 10; - - private final AppliedPTransform, Unbounded> transform; - private final InProcessEvaluationContext evaluationContext; - private final ConcurrentLinkedQueue> - evaluatorQueue; - /** - * The source being read from by this {@link UnboundedReadEvaluator}. This may not be the same - * source as derived from {@link #transform} due to splitting. - */ - private final UnboundedSource source; - private final UnboundedReadDeduplicator deduplicator; - private UnboundedReader currentReader; - private CheckpointMarkT checkpointMark; - - /** - * The count of bundles output from this {@link UnboundedReadEvaluator}. Used to exercise - * {@link UnboundedReader#close()}. - */ - private int outputBundles = 0; - - public UnboundedReadEvaluator( - AppliedPTransform, Unbounded> transform, - InProcessEvaluationContext evaluationContext, - UnboundedSource source, - UnboundedReadDeduplicator deduplicator, - ConcurrentLinkedQueue> evaluatorQueue) { - this.transform = transform; - this.evaluationContext = evaluationContext; - this.evaluatorQueue = evaluatorQueue; - this.source = source; - this.currentReader = null; - this.deduplicator = deduplicator; - this.checkpointMark = null; - } - - @Override - public void processElement(WindowedValue element) {} - - @Override - public InProcessTransformResult finishBundle() throws IOException { - UncommittedBundle output = evaluationContext.createRootBundle(transform.getOutput()); - try { - boolean elementAvailable = startReader(); - - Instant watermark = currentReader.getWatermark(); - if (elementAvailable) { - int numElements = 0; - do { - if (deduplicator.shouldOutput(currentReader.getCurrentRecordId())) { - output.add(WindowedValue.timestampedValueInGlobalWindow(currentReader.getCurrent(), - currentReader.getCurrentTimestamp())); - } - numElements++; - } while (numElements < ARBITRARY_MAX_ELEMENTS && currentReader.advance()); - watermark = currentReader.getWatermark(); - // Only take a checkpoint if we did any work - finishRead(); - } - // TODO: When exercising create initial splits, make this the minimum watermark across all - // existing readers - StepTransformResult result = - StepTransformResult.withHold(transform, watermark).addOutput(output).build(); - evaluatorQueue.offer(this); - return result; - } catch (IOException e) { - closeReader(); - throw e; - } - } - - private boolean startReader() throws IOException { - if (currentReader == null) { - if (checkpointMark != null) { - checkpointMark.finalizeCheckpoint(); - } - currentReader = source.createReader(evaluationContext.getPipelineOptions(), checkpointMark); - checkpointMark = null; - return currentReader.start(); - } else { - return currentReader.advance(); - } - } - - /** - * Checkpoint the current reader, finalize the previous checkpoint, and update the state of this - * evaluator. - */ - private void finishRead() throws IOException { - final CheckpointMark oldMark = checkpointMark; - @SuppressWarnings("unchecked") - final CheckpointMarkT mark = (CheckpointMarkT) currentReader.getCheckpointMark(); - checkpointMark = mark; - if (oldMark != null) { - oldMark.finalizeCheckpoint(); - } - - // If the watermark is the max value, this source may not be invoked again. Finalize after - // committing the output. - if (!currentReader.getWatermark().isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - evaluationContext.scheduleAfterOutputWouldBeProduced(transform.getOutput(), - GlobalWindow.INSTANCE, - transform.getOutput().getWindowingStrategy(), - new Runnable() { - public void run() { - try { - mark.finalizeCheckpoint(); - } catch (IOException e) { - throw new RuntimeException( - "Couldn't finalize checkpoint after the end of the Global Window", - e); - } - } - }); - } - // Sometimes resume from a checkpoint even if it's not required - - if (outputBundles >= MAX_READER_REUSE_COUNT) { - closeReader(); - outputBundles = 0; - } else { - outputBundles++; - } - } - - private void closeReader() throws IOException { - if (currentReader != null) { - currentReader.close(); - currentReader = null; - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java deleted file mode 100644 index 9b296dbdc7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactory.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import java.util.ArrayList; -import java.util.List; - -/** - * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the - * {@link CreatePCollectionView} primitive {@link PTransform}. - * - *

              The {@link ViewEvaluatorFactory} produces {@link TransformEvaluator TransformEvaluators} for - * the {@link WriteView} {@link PTransform}, which is part of the - * {@link InProcessCreatePCollectionView} composite transform. This transform is an override for the - * {@link CreatePCollectionView} transform that applies windowing and triggers before the view is - * written. - */ -class ViewEvaluatorFactory implements TransformEvaluatorFactory { - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public TransformEvaluator forApplication( - AppliedPTransform application, - InProcessPipelineRunner.CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) { - @SuppressWarnings({"cast", "unchecked", "rawtypes"}) - TransformEvaluator evaluator = createEvaluator( - (AppliedPTransform) application, evaluationContext); - return evaluator; - } - - private TransformEvaluator> createEvaluator( - final AppliedPTransform>, PCollectionView, WriteView> - application, - InProcessEvaluationContext context) { - PCollection> input = application.getInput(); - final PCollectionViewWriter writer = - context.createPCollectionViewWriter(input, application.getOutput()); - return new TransformEvaluator>() { - private final List> elements = new ArrayList<>(); - - @Override - public void processElement(WindowedValue> element) { - for (InT input : element.getValue()) { - elements.add(element.withValue(input)); - } - } - - @Override - public InProcessTransformResult finishBundle() { - writer.add(elements); - StepTransformResult.Builder resultBuilder = StepTransformResult.withoutHold(application); - if (!elements.isEmpty()) { - resultBuilder = resultBuilder.withAdditionalOutput(OutputType.PCOLLECTION_VIEW); - } - return resultBuilder - .build(); - } - }; - } - - public static class InProcessViewOverrideFactory implements PTransformOverrideFactory { - @Override - public - PTransform override(PTransform transform) { - if (transform instanceof CreatePCollectionView) { - - } - @SuppressWarnings({"rawtypes", "unchecked"}) - PTransform createView = - (PTransform) - new InProcessCreatePCollectionView<>((CreatePCollectionView) transform); - return createView; - } - } - - /** - * An in-process override for {@link CreatePCollectionView}. - */ - private static class InProcessCreatePCollectionView - extends ForwardingPTransform, PCollectionView> { - private final CreatePCollectionView og; - - private InProcessCreatePCollectionView(CreatePCollectionView og) { - this.og = og; - } - - @Override - public PCollectionView apply(PCollection input) { - return input.apply(WithKeys.of((Void) null)) - .setCoder(KvCoder.of(VoidCoder.of(), input.getCoder())) - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(new WriteView(og)); - } - - @Override - protected PTransform, PCollectionView> delegate() { - return og; - } - } - - /** - * An in-process implementation of the {@link CreatePCollectionView} primitive. - * - *

              This implementation requires the input {@link PCollection} to be an iterable, which is - * provided to {@link PCollectionView#fromIterableInternal(Iterable)}. - */ - public static final class WriteView - extends PTransform>, PCollectionView> { - private final CreatePCollectionView og; - - WriteView(CreatePCollectionView og) { - this.og = og; - } - - @Override - public PCollectionView apply(PCollection> input) { - return og.getView(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java deleted file mode 100644 index a331f5c12b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutor.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.common.collect.ComparisonChain; -import com.google.common.collect.Ordering; - -import org.joda.time.Instant; - -import java.util.PriorityQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Executor; - -/** - * Executes callbacks that occur based on the progression of the watermark per-step. - * - *

              Callbacks are registered by calls to - * {@link #callOnGuaranteedFiring(AppliedPTransform, BoundedWindow, WindowingStrategy, Runnable)}, - * and are executed after a call to {@link #fireForWatermark(AppliedPTransform, Instant)} with the - * same {@link AppliedPTransform} and a watermark sufficient to ensure that the trigger for the - * windowing strategy would have been produced. - * - *

              NOTE: {@link WatermarkCallbackExecutor} does not track the latest observed watermark for any - * {@link AppliedPTransform} - any call to - * {@link #callOnGuaranteedFiring(AppliedPTransform, BoundedWindow, WindowingStrategy, Runnable)} - * that could have potentially already fired should be followed by a call to - * {@link #fireForWatermark(AppliedPTransform, Instant)} for the same transform with the current - * value of the watermark. - */ -class WatermarkCallbackExecutor { - /** - * Create a new {@link WatermarkCallbackExecutor}. - */ - public static WatermarkCallbackExecutor create(Executor executor) { - return new WatermarkCallbackExecutor(executor); - } - - private final ConcurrentMap, PriorityQueue> - callbacks; - private final Executor executor; - - private WatermarkCallbackExecutor(Executor executor) { - this.callbacks = new ConcurrentHashMap<>(); - this.executor = executor; - } - - /** - * Execute the provided {@link Runnable} after the next call to - * {@link #fireForWatermark(AppliedPTransform, Instant)} where the window is guaranteed to have - * produced output. - */ - public void callOnGuaranteedFiring( - AppliedPTransform step, - BoundedWindow window, - WindowingStrategy windowingStrategy, - Runnable runnable) { - WatermarkCallback callback = - WatermarkCallback.onGuaranteedFiring(window, windowingStrategy, runnable); - - PriorityQueue callbackQueue = callbacks.get(step); - if (callbackQueue == null) { - callbackQueue = new PriorityQueue<>(11, new CallbackOrdering()); - if (callbacks.putIfAbsent(step, callbackQueue) != null) { - callbackQueue = callbacks.get(step); - } - } - - synchronized (callbackQueue) { - callbackQueue.offer(callback); - } - } - - /** - * Schedule all pending callbacks that must have produced output by the time of the provided - * watermark. - */ - public void fireForWatermark(AppliedPTransform step, Instant watermark) { - PriorityQueue callbackQueue = callbacks.get(step); - if (callbackQueue == null) { - return; - } - synchronized (callbackQueue) { - while (!callbackQueue.isEmpty() && callbackQueue.peek().shouldFire(watermark)) { - executor.execute(callbackQueue.poll().getCallback()); - } - } - } - - private static class WatermarkCallback { - public static WatermarkCallback onGuaranteedFiring( - BoundedWindow window, WindowingStrategy strategy, Runnable callback) { - @SuppressWarnings("unchecked") - Instant firingAfter = - strategy.getTrigger().getSpec().getWatermarkThatGuaranteesFiring((W) window); - return new WatermarkCallback(firingAfter, callback); - } - - private final Instant fireAfter; - private final Runnable callback; - - private WatermarkCallback(Instant fireAfter, Runnable callback) { - this.fireAfter = fireAfter; - this.callback = callback; - } - - public boolean shouldFire(Instant currentWatermark) { - return currentWatermark.isAfter(fireAfter) - || currentWatermark.equals(BoundedWindow.TIMESTAMP_MAX_VALUE); - } - - public Runnable getCallback() { - return callback; - } - } - - private static class CallbackOrdering extends Ordering { - @Override - public int compare(WatermarkCallback left, WatermarkCallback right) { - return ComparisonChain.start() - .compare(left.fireAfter, right.fireAfter) - .compare(left.callback, right.callback, Ordering.arbitrary()) - .result(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java deleted file mode 100644 index 17741abf95..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactory.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Instant; - -import java.util.Collection; - -import javax.annotation.Nullable; - -/** - * The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the - * {@link Bound Window.Bound} primitive {@link PTransform}. - */ -class WindowEvaluatorFactory implements TransformEvaluatorFactory { - - @Override - public TransformEvaluator forApplication( - AppliedPTransform application, - @Nullable CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) - throws Exception { - return createTransformEvaluator( - (AppliedPTransform) application, inputBundle, evaluationContext); - } - - private TransformEvaluator createTransformEvaluator( - AppliedPTransform, PCollection, Window.Bound> transform, - CommittedBundle inputBundle, - InProcessEvaluationContext evaluationContext) { - WindowFn fn = transform.getTransform().getWindowFn(); - UncommittedBundle outputBundle = - evaluationContext.createBundle(inputBundle, transform.getOutput()); - if (fn == null) { - return PassthroughTransformEvaluator.create(transform, outputBundle); - } - return new WindowIntoEvaluator<>(transform, fn, outputBundle); - } - - private static class WindowIntoEvaluator implements TransformEvaluator { - private final AppliedPTransform, PCollection, Window.Bound> - transform; - private final WindowFn windowFn; - private final UncommittedBundle outputBundle; - - @SuppressWarnings("unchecked") - public WindowIntoEvaluator( - AppliedPTransform, PCollection, Window.Bound> transform, - WindowFn windowFn, - UncommittedBundle outputBundle) { - this.outputBundle = outputBundle; - this.transform = transform; - // Safe contravariant cast - this.windowFn = (WindowFn) windowFn; - } - - @Override - public void processElement(WindowedValue element) throws Exception { - Collection windows = assignWindows(windowFn, element); - outputBundle.add( - WindowedValue.of( - element.getValue(), element.getTimestamp(), windows, PaneInfo.NO_FIRING)); - } - - private Collection assignWindows( - WindowFn windowFn, WindowedValue element) throws Exception { - WindowFn.AssignContext assignContext = - new InProcessAssignContext<>(windowFn, element); - Collection windows = windowFn.assignWindows(assignContext); - return windows; - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - return StepTransformResult.withoutHold(transform).addOutput(outputBundle).build(); - } - } - - private static class InProcessAssignContext - extends WindowFn.AssignContext { - private final WindowedValue value; - - public InProcessAssignContext(WindowFn fn, WindowedValue value) { - fn.super(); - this.value = value; - } - - @Override - public InputT element() { - return value.getValue(); - } - - @Override - public Instant timestamp() { - return value.getTimestamp(); - } - - @Override - public Collection windows() { - return value.getWindows(); - } - - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java deleted file mode 100644 index 6d1d71d0ad..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactory.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.io.Write; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.annotations.VisibleForTesting; -import org.joda.time.Duration; -import java.util.concurrent.ThreadLocalRandom; - -/** - * A {@link PTransformOverrideFactory} that overrides {@link Write} {@link PTransform PTransforms} - * with an unspecified number of shards with a write with a specified number of shards. The number - * of shards is the log base 10 of the number of input records, with up to 2 additional shards. - */ -class WriteWithShardingFactory implements PTransformOverrideFactory { - static final int MAX_RANDOM_EXTRA_SHARDS = 3; - - @Override - public PTransform override( - PTransform transform) { - if (transform instanceof Write.Bound) { - Write.Bound that = (Write.Bound) transform; - if (that.getNumShards() == 0) { - return (PTransform) new DynamicallyReshardedWrite(that); - } - } - return transform; - } - - private static class DynamicallyReshardedWrite extends PTransform, PDone> { - private final transient Write.Bound original; - - private DynamicallyReshardedWrite(Write.Bound original) { - this.original = original; - } - - @Override - public PDone apply(PCollection input) { - PCollection records = input.apply("RewindowInputs", - Window.into(new GlobalWindows()).triggering(DefaultTrigger.of()) - .withAllowedLateness(Duration.ZERO) - .discardingFiredPanes()); - final PCollectionView numRecords = records.apply(Count.globally().asSingletonView()); - PCollection resharded = - records - .apply( - "ApplySharding", - ParDo.withSideInputs(numRecords) - .of( - new KeyBasedOnCountFn( - numRecords, - ThreadLocalRandom.current().nextInt(MAX_RANDOM_EXTRA_SHARDS)))) - .apply("GroupIntoShards", GroupByKey.create()) - .apply("DropShardingKeys", Values.>create()) - .apply("FlattenShardIterables", Flatten.iterables()); - // This is an inverted application to apply the expansion of the original Write PTransform - // without adding a new Write Transform Node, which would be overwritten the same way, leading - // to an infinite recursion. We cannot modify the number of shards, because that is determined - // at runtime. - return original.apply(resharded); - } - } - - @VisibleForTesting - static class KeyBasedOnCountFn extends DoFn> { - @VisibleForTesting - static final int MIN_SHARDS_FOR_LOG = 3; - - private final PCollectionView numRecords; - private final int randomExtraShards; - private int currentShard; - private int maxShards; - - KeyBasedOnCountFn(PCollectionView numRecords, int extraShards) { - this.numRecords = numRecords; - this.randomExtraShards = extraShards; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - if (maxShards == 0L) { - maxShards = calculateShards(c.sideInput(numRecords)); - currentShard = ThreadLocalRandom.current().nextInt(maxShards); - } - int shard = currentShard; - currentShard = (currentShard + 1) % maxShards; - c.output(KV.of(shard, c.element())); - } - - private int calculateShards(long totalRecords) { - checkArgument( - totalRecords > 0, - "KeyBasedOnCountFn cannot be invoked on an element if there are no elements"); - if (totalRecords < MIN_SHARDS_FOR_LOG + randomExtraShards) { - return (int) totalRecords; - } - // 100mil records before >7 output files - int floorLogRecs = Double.valueOf(Math.log10(totalRecords)).intValue(); - int shards = Math.max(floorLogRecs, MIN_SHARDS_FOR_LOG) + randomExtraShards; - return shards; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java deleted file mode 100644 index a68325935c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines the {@link com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner}, - * which executes both Bounded and Unbounded {@code Pipelines} on the local machine. - * - *

              See {@link com.google.cloud.dataflow.sdk.runners} for more information about Pipeline Runners. - */ -package com.google.cloud.dataflow.sdk.runners.inprocess; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/package-info.java deleted file mode 100644 index d1aa6af192..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/package-info.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines runners for executing Pipelines in different modes, including - * {@link com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner} and - * {@link com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner}. - * - *

              {@link com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner} executes a {@code Pipeline} - * locally, without contacting the Dataflow service. - * {@link com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner} submits a - * {@code Pipeline} to the Dataflow service, which executes it on Dataflow-managed Compute Engine - * instances. {@code DataflowPipelineRunner} returns - * as soon as the {@code Pipeline} has been submitted. Use - * {@link com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner} to have execution - * updates printed to the console. - * - *

              The runner is specified as part {@link com.google.cloud.dataflow.sdk.options.PipelineOptions}. - */ -package com.google.cloud.dataflow.sdk.runners; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java deleted file mode 100644 index b2a3fd592f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/IsmFormat.java +++ /dev/null @@ -1,945 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.worker; - -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.RandomAccessData; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.MoreObjects; -import com.google.common.base.MoreObjects.ToStringHelper; -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableList; -import com.google.common.hash.HashFunction; -import com.google.common.hash.Hashing; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * An Ism file is a prefix encoded composite key value file broken into shards. Each composite - * key is composed of a fixed number of component keys. A fixed number of those sub keys represent - * the shard key portion; see {@link IsmRecord} and {@link IsmRecordCoder} for further details - * around the data format. In addition to the data, there is a bloom filter, - * and multiple indices to allow for efficient retrieval. - * - *

              An Ism file is composed of these high level sections (in order): - *

                - *
              • shard block
              • - *
              • bloom filter (See {@code ScalableBloomFilter} for details on encoding format)
              • - *
              • shard index
              • - *
              • footer (See {@link Footer} for details on encoding format)
              • - *
              - * - *

              The shard block is composed of multiple copies of the following: - *

                - *
              • data block
              • - *
              • data index
              • - *
              - * - *

              The data block is composed of multiple copies of the following: - *

                - *
              • key prefix (See {@link KeyPrefix} for details on encoding format)
              • - *
              • unshared key bytes
              • - *
              • value bytes
              • - *
              • optional 0x00 0x00 bytes followed by metadata bytes - * (if the following 0x00 0x00 bytes are not present, then there are no metadata bytes)
              • - *
              - * Each key written into the data block must be in unsigned lexicographically increasing order - * and also its shard portion of the key must hash to the same shard id as all other keys - * within the same data block. The hashing function used is the - * - * 32-bit murmur3 algorithm, x86 variant (little-endian variant), - * using {@code 1225801234} as the seed value. - * - *

              The data index is composed of {@code N} copies of the following: - *

                - *
              • key prefix (See {@link KeyPrefix} for details on encoding format)
              • - *
              • unshared key bytes
              • - *
              • byte offset to key prefix in data block (variable length long coding)
              • - *
              - * - *

              The shard index is composed of a {@link VarInt variable length integer} encoding representing - * the number of shard index records followed by that many shard index records. - * See {@link IsmShardCoder} for further details as to its encoding scheme. - */ -public class IsmFormat { - private static final int HASH_SEED = 1225801234; - private static final HashFunction HASH_FUNCTION = Hashing.murmur3_32(HASH_SEED); - static final int SHARD_BITS = 0x7F; // [0-127] shards + [128-255] metadata shards - - /** - * A record containing a composite key and either a value or metadata. The composite key - * must not contain the metadata key component place holder if producing a value record, and must - * contain the metadata component key place holder if producing a metadata record. - * - *

              The composite key is a fixed number of component keys where the first {@code N} component - * keys are used to create a shard id via hashing. See {@link IsmRecordCoder#hash(List)} for - * further details. - */ - public static class IsmRecord { - /** Returns an IsmRecord with the specified key components and value. */ - public static IsmRecord of(List keyComponents, V value) { - checkNotNull(keyComponents); - checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); - checkArgument(!isMetadataKey(keyComponents), - "Expected key components to not contain metadata key."); - return new IsmRecord<>(keyComponents, value, null); - } - - public static IsmRecord meta(List keyComponents, byte[] metadata) { - checkNotNull(keyComponents); - checkNotNull(metadata); - checkArgument(!keyComponents.isEmpty(), "Expected non-empty list of key components."); - checkArgument(isMetadataKey(keyComponents), - "Expected key components to contain metadata key."); - return new IsmRecord(keyComponents, null, metadata); - } - - private final List keyComponents; - @Nullable - private final V value; - @Nullable - private final byte[] metadata; - private IsmRecord(List keyComponents, V value, byte[] metadata) { - this.keyComponents = keyComponents; - this.value = value; - this.metadata = metadata; - } - - /** Returns the list of key components. */ - public List getKeyComponents() { - return keyComponents; - } - - /** Returns the key component at the specified index. */ - public Object getKeyComponent(int index) { - return keyComponents.get(index); - } - - /** - * Returns the value. Throws {@link IllegalStateException} if this is not a - * value record. - */ - public V getValue() { - checkState(!isMetadataKey(keyComponents), - "This is a metadata record and not a value record."); - return value; - } - - /** - * Returns the metadata. Throws {@link IllegalStateException} if this is not a - * metadata record. - */ - public byte[] getMetadata() { - checkState(isMetadataKey(keyComponents), - "This is a value record and not a metadata record."); - return metadata; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof IsmRecord)) { - return false; - } - IsmRecord other = (IsmRecord) obj; - return Objects.equal(keyComponents, other.keyComponents) - && Objects.equal(value, other.value) - && Arrays.equals(metadata, other.metadata); - } - - @Override - public int hashCode() { - return Objects.hashCode(keyComponents, value, Arrays.hashCode(metadata)); - } - - @Override - public String toString() { - ToStringHelper builder = MoreObjects.toStringHelper(IsmRecord.class) - .add("keyComponents", keyComponents); - if (isMetadataKey(keyComponents)) { - builder.add("metadata", metadata); - } else { - builder.add("value", value); - } - return builder.toString(); - } - } - - /** A {@link Coder} for {@link IsmRecord}s. - * - *

              Note that this coder standalone will not produce an Ism file. This coder can be used - * to materialize a {@link PCollection} of {@link IsmRecord}s. Only when this coder - * is combined with an {@link IsmSink} will one produce an Ism file. - * - *

              The {@link IsmRecord} encoded format is: - *

                - *
              • encoded key component 1 using key component coder 1
              • - *
              • ...
              • - *
              • encoded key component N using key component coder N
              • - *
              • encoded value using value coder
              • - *
              - */ - public static class IsmRecordCoder - extends StandardCoder> { - /** Returns an IsmRecordCoder with the specified key component coders, value coder. */ - public static IsmRecordCoder of( - int numberOfShardKeyCoders, - int numberOfMetadataShardKeyCoders, - List> keyComponentCoders, - Coder valueCoder) { - checkNotNull(keyComponentCoders); - checkArgument(keyComponentCoders.size() > 0); - checkArgument(numberOfShardKeyCoders > 0); - checkArgument(numberOfShardKeyCoders <= keyComponentCoders.size()); - checkArgument(numberOfMetadataShardKeyCoders <= keyComponentCoders.size()); - return new IsmRecordCoder<>( - numberOfShardKeyCoders, - numberOfMetadataShardKeyCoders, - keyComponentCoders, - valueCoder); - } - - /** - * Returns an IsmRecordCoder with the specified coders. Note that this method is not meant - * to be called by users but used by Jackson when decoding this coder. - */ - @JsonCreator - public static IsmRecordCoder of( - @JsonProperty(PropertyNames.NUM_SHARD_CODERS) int numberOfShardCoders, - @JsonProperty(PropertyNames.NUM_METADATA_SHARD_CODERS) int numberOfMetadataShardCoders, - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { - checkArgument(components.size() >= 2, - "Expecting at least 2 components, got " + components.size()); - return of( - numberOfShardCoders, - numberOfMetadataShardCoders, - components.subList(0, components.size() - 1), - components.get(components.size() - 1)); - } - - private final int numberOfShardKeyCoders; - private final int numberOfMetadataShardKeyCoders; - private final List> keyComponentCoders; - private final Coder valueCoder; - - private IsmRecordCoder( - int numberOfShardKeyCoders, - int numberOfMetadataShardKeyCoders, - List> keyComponentCoders, Coder valueCoder) { - this.numberOfShardKeyCoders = numberOfShardKeyCoders; - this.numberOfMetadataShardKeyCoders = numberOfMetadataShardKeyCoders; - this.keyComponentCoders = keyComponentCoders; - this.valueCoder = valueCoder; - } - - /** Returns the list of key component coders. */ - public List> getKeyComponentCoders() { - return keyComponentCoders; - } - - /** Returns the key coder at the specified index. */ - public Coder getKeyComponentCoder(int index) { - return keyComponentCoders.get(index); - } - - /** Returns the value coder. */ - public Coder getValueCoder() { - return valueCoder; - } - - @Override - public void encode(IsmRecord value, OutputStream outStream, - Coder.Context context) throws CoderException, IOException { - if (value.getKeyComponents().size() != keyComponentCoders.size()) { - throw new CoderException(String.format( - "Expected %s key component(s) but received key component(s) %s.", - keyComponentCoders.size(), value.getKeyComponents())); - } - for (int i = 0; i < keyComponentCoders.size(); ++i) { - getKeyComponentCoder(i).encode(value.getKeyComponent(i), outStream, context.nested()); - } - if (isMetadataKey(value.getKeyComponents())) { - ByteArrayCoder.of().encode(value.getMetadata(), outStream, context.nested()); - } else { - valueCoder.encode(value.getValue(), outStream, context.nested()); - } - } - - @Override - public IsmRecord decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - List keyComponents = new ArrayList<>(keyComponentCoders.size()); - for (Coder keyCoder : keyComponentCoders) { - keyComponents.add(keyCoder.decode(inStream, context.nested())); - } - if (isMetadataKey(keyComponents)) { - return IsmRecord.meta( - keyComponents, ByteArrayCoder.of().decode(inStream, context.nested())); - } else { - return IsmRecord.of(keyComponents, valueCoder.decode(inStream, context.nested())); - } - } - - int getNumberOfShardKeyCoders(List keyComponents) { - if (isMetadataKey(keyComponents)) { - return numberOfMetadataShardKeyCoders; - } else { - return numberOfShardKeyCoders; - } - } - - /** - * Computes the shard id for the given key component(s). - * - *

              The shard keys are encoded into their byte representations and hashed using the - * - * 32-bit murmur3 algorithm, x86 variant (little-endian variant), - * using {@code 1225801234} as the seed value. We ensure that shard ids for - * metadata keys and normal keys do not overlap. - */ - public int hash(List keyComponents) { - return encodeAndHash(keyComponents, new RandomAccessData(), new ArrayList()); - } - - /** - * Computes the shard id for the given key component(s). - * - *

              Mutates {@code keyBytes} such that when returned, contains the encoded - * version of the key components. - */ - int encodeAndHash(List keyComponents, RandomAccessData keyBytesToMutate) { - return encodeAndHash(keyComponents, keyBytesToMutate, new ArrayList()); - } - - /** - * Computes the shard id for the given key component(s). - * - * Mutates {@code keyBytes} such that when returned, contains the encoded - * version of the key components. Also, mutates {@code keyComponentByteOffsetsToMutate} to - * store the location where each key component's encoded byte representation ends within - * {@code keyBytes}. - */ - int encodeAndHash( - List keyComponents, - RandomAccessData keyBytesToMutate, - List keyComponentByteOffsetsToMutate) { - checkNotNull(keyComponents); - checkArgument(keyComponents.size() <= keyComponentCoders.size(), - "Expected at most %s key component(s) but received %s.", - keyComponentCoders.size(), keyComponents); - - final int numberOfKeyCodersToUse; - final int shardOffset; - if (isMetadataKey(keyComponents)) { - numberOfKeyCodersToUse = numberOfMetadataShardKeyCoders; - shardOffset = SHARD_BITS + 1; - } else { - numberOfKeyCodersToUse = numberOfShardKeyCoders; - shardOffset = 0; - } - - checkArgument(numberOfKeyCodersToUse <= keyComponents.size(), - "Expected at least %s key component(s) but received %s.", - numberOfShardKeyCoders, keyComponents); - - try { - // Encode the shard portion - for (int i = 0; i < numberOfKeyCodersToUse; ++i) { - getKeyComponentCoder(i).encode( - keyComponents.get(i), keyBytesToMutate.asOutputStream(), Context.NESTED); - keyComponentByteOffsetsToMutate.add(keyBytesToMutate.size()); - } - int rval = HASH_FUNCTION.hashBytes( - keyBytesToMutate.array(), 0, keyBytesToMutate.size()).asInt() & SHARD_BITS; - rval += shardOffset; - - // Encode the remainder - for (int i = numberOfKeyCodersToUse; i < keyComponents.size(); ++i) { - getKeyComponentCoder(i).encode( - keyComponents.get(i), keyBytesToMutate.asOutputStream(), Context.NESTED); - keyComponentByteOffsetsToMutate.add(keyBytesToMutate.size()); - } - return rval; - } catch (IOException e) { - throw new IllegalStateException( - String.format("Failed to hash %s with coder %s", keyComponents, this), e); - } - } - - @Override - public List> getCoderArguments() { - return ImmutableList.>builder() - .addAll(keyComponentCoders) - .add(valueCoder) - .build(); - } - - @Override - public CloudObject asCloudObject() { - CloudObject cloudObject = super.asCloudObject(); - addLong(cloudObject, PropertyNames.NUM_SHARD_CODERS, numberOfShardKeyCoders); - addLong(cloudObject, PropertyNames.NUM_METADATA_SHARD_CODERS, numberOfMetadataShardKeyCoders); - return cloudObject; - } - - @Override - public void verifyDeterministic() throws Coder.NonDeterministicException { - verifyDeterministic("Key component coders expected to be deterministic.", keyComponentCoders); - verifyDeterministic("Value coder expected to be deterministic.", valueCoder); - } - - @Override - public boolean consistentWithEquals() { - for (Coder keyComponentCoder : keyComponentCoders) { - if (!keyComponentCoder.consistentWithEquals()) { - return false; - } - } - return valueCoder.consistentWithEquals(); - } - - @Override - public Object structuralValue(IsmRecord record) throws Exception { - checkState(record.getKeyComponents().size() == keyComponentCoders.size(), - "Expected the number of key component coders %s " - + "to match the number of key components %s.", - keyComponentCoders.size(), record.getKeyComponents()); - - if (record != null && consistentWithEquals()) { - ArrayList keyComponentStructuralValues = new ArrayList<>(); - for (int i = 0; i < keyComponentCoders.size(); ++i) { - keyComponentStructuralValues.add( - getKeyComponentCoder(i).structuralValue(record.getKeyComponent(i))); - } - if (isMetadataKey(record.getKeyComponents())) { - return IsmRecord.meta(keyComponentStructuralValues, record.getMetadata()); - } else { - return IsmRecord.of(keyComponentStructuralValues, - valueCoder.structuralValue(record.getValue())); - } - } - return super.structuralValue(record); - } - } - - /** - * Validates that the key portion of the given coder is deterministic. - */ - static void validateCoderIsCompatible(IsmRecordCoder coder) { - for (Coder keyComponentCoder : coder.getKeyComponentCoders()) { - try { - keyComponentCoder.verifyDeterministic(); - } catch (NonDeterministicException e) { - throw new IllegalArgumentException( - String.format("Key component coder %s is expected to be deterministic.", - keyComponentCoder), e); - } - } - } - - /** Returns true if and only if any of the passed in key components represent a metadata key. */ - public static boolean isMetadataKey(List keyComponents) { - for (Object keyComponent : keyComponents) { - if (keyComponent == METADATA_KEY) { - return true; - } - } - return false; - } - - /** A marker object representing the wildcard metadata key component. */ - private static final Object METADATA_KEY = new Object() { - @Override - public String toString() { - return "META"; - } - - @Override - public boolean equals(Object obj) { - return this == obj; - } - - @Override - public int hashCode() { - return -1248902349; - } - }; - - /** - * An object representing a wild card for a key component. - * Encoded using {@link MetadataKeyCoder}. - */ - public static Object getMetadataKey() { - return METADATA_KEY; - } - - /** - * A coder for metadata key component. Can be used to wrap key component coder allowing for - * the metadata key component to be used as a place holder instead of an actual key. - */ - public static class MetadataKeyCoder extends StandardCoder { - public static MetadataKeyCoder of(Coder keyCoder) { - checkNotNull(keyCoder); - return new MetadataKeyCoder<>(keyCoder); - } - - /** - * Returns an IsmRecordCoder with the specified coders. Note that this method is not meant - * to be called by users but used by Jackson when decoding this coder. - */ - @JsonCreator - public static MetadataKeyCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { - checkArgument(components.size() == 1, - "Expecting one component, got " + components.size()); - return of(components.get(0)); - } - - private final Coder keyCoder; - - private MetadataKeyCoder(Coder keyCoder) { - this.keyCoder = keyCoder; - } - - public Coder getKeyCoder() { - return keyCoder; - } - - @Override - public void encode(K value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - if (value == METADATA_KEY) { - outStream.write(0); - } else { - outStream.write(1); - keyCoder.encode(value, outStream, context.nested()); - } - } - - @Override - public K decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - int marker = inStream.read(); - if (marker == 0) { - return (K) getMetadataKey(); - } else if (marker == 1) { - return keyCoder.decode(inStream, context.nested()); - } else { - throw new CoderException(String.format("Expected marker but got %s.", marker)); - } - } - - @Override - public List> getCoderArguments() { - return ImmutableList.>of(keyCoder); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic("Expected key coder to be deterministic", keyCoder); - } - } - - /** - * A shard descriptor containing shard id, the data block offset, and the index offset for the - * given shard. - */ - public static class IsmShard { - private final int id; - private final long blockOffset; - private final long indexOffset; - - /** Returns an IsmShard with the given id, block offset and no index offset. */ - public static IsmShard of(int id, long blockOffset) { - IsmShard ismShard = new IsmShard(id, blockOffset, -1); - checkState(id >= 0, - "%s attempting to be written with negative shard id.", - ismShard); - checkState(blockOffset >= 0, - "%s attempting to be written with negative block offset.", - ismShard); - return ismShard; - } - - /** Returns an IsmShard with the given id, block offset, and index offset. */ - public static IsmShard of(int id, long blockOffset, long indexOffset) { - IsmShard ismShard = new IsmShard(id, blockOffset, indexOffset); - checkState(id >= 0, - "%s attempting to be written with negative shard id.", - ismShard); - checkState(blockOffset >= 0, - "%s attempting to be written with negative block offset.", - ismShard); - checkState(indexOffset >= 0, - "%s attempting to be written with negative index offset.", - ismShard); - return ismShard; - } - - private IsmShard(int id, long blockOffset, long indexOffset) { - this.id = id; - this.blockOffset = blockOffset; - this.indexOffset = indexOffset; - } - - /** Return the shard id. */ - public int getId() { - return id; - } - - /** Return the absolute position within the Ism file where the data block begins. */ - public long getBlockOffset() { - return blockOffset; - } - - /** - * Return the absolute position within the Ism file where the index block begins. - * Throws {@link IllegalStateException} if the index offset was never specified. - */ - public long getIndexOffset() { - checkState(indexOffset >= 0, - "Unable to fetch index offset because it was never specified."); - return indexOffset; - } - - /** Returns a new IsmShard like this one with the specified index offset. */ - public IsmShard withIndexOffset(long indexOffset) { - return of(id, blockOffset, indexOffset); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(IsmShard.class) - .add("id", id) - .add("blockOffset", blockOffset) - .add("indexOffset", indexOffset) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof IsmShard)) { - return false; - } - IsmShard other = (IsmShard) obj; - return Objects.equal(id, other.id) - && Objects.equal(blockOffset, other.blockOffset) - && Objects.equal(indexOffset, other.indexOffset); - } - - @Override - public int hashCode() { - return Objects.hashCode(id, blockOffset, indexOffset); - } - } - - /** - * A {@link ListCoder} wrapping a {@link IsmShardCoder} used to encode the shard index. - * See {@link ListCoder} for its encoding specification and {@link IsmShardCoder} for its - * encoding specification. - */ - public static final Coder> ISM_SHARD_INDEX_CODER = - ListCoder.of(IsmShardCoder.of()); - - /** - * A coder for {@link IsmShard}s. - * - *

              The shard descriptor is encoded as: - *

                - *
              • id (variable length integer encoding)
              • - *
              • blockOffset (variable length long encoding)
              • - *
              • indexOffset (variable length long encoding)
              • - *
              - */ - public static class IsmShardCoder extends AtomicCoder { - private static final IsmShardCoder INSTANCE = new IsmShardCoder(); - - /** Returns an IsmShardCoder. */ - @JsonCreator - public static IsmShardCoder of() { - return INSTANCE; - } - - private IsmShardCoder() { - } - - @Override - public void encode(IsmShard value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - checkState(value.getIndexOffset() >= 0, - "%s attempting to be written without index offset.", - value); - VarIntCoder.of().encode(value.getId(), outStream, context.nested()); - VarLongCoder.of().encode(value.getBlockOffset(), outStream, context.nested()); - VarLongCoder.of().encode(value.getIndexOffset(), outStream, context.nested()); - } - - @Override - public IsmShard decode( - InputStream inStream, Coder.Context context) throws CoderException, IOException { - return IsmShard.of( - VarIntCoder.of().decode(inStream, context), - VarLongCoder.of().decode(inStream, context), - VarLongCoder.of().decode(inStream, context)); - } - - @Override - public boolean consistentWithEquals() { - return true; - } - } - - /** - * The prefix used before each key which contains the number of shared and unshared - * bytes from the previous key that was read. The key prefix along with the previous key - * and the unshared key bytes allows one to construct the current key by doing the following - * {@code currentKey = previousKey[0 : sharedBytes] + read(unsharedBytes)}. - * - *

              The key prefix is encoded as: - *

                - *
              • number of shared key bytes (variable length integer coding)
              • - *
              • number of unshared key bytes (variable length integer coding)
              • - *
              - */ - static class KeyPrefix { - private final int sharedKeySize; - private final int unsharedKeySize; - - KeyPrefix(int sharedBytes, int unsharedBytes) { - this.sharedKeySize = sharedBytes; - this.unsharedKeySize = unsharedBytes; - } - - public int getSharedKeySize() { - return sharedKeySize; - } - - public int getUnsharedKeySize() { - return unsharedKeySize; - } - - @Override - public int hashCode() { - return Objects.hashCode(sharedKeySize, unsharedKeySize); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (!(other instanceof KeyPrefix)) { - return false; - } - KeyPrefix keyPrefix = (KeyPrefix) other; - return sharedKeySize == keyPrefix.sharedKeySize - && unsharedKeySize == keyPrefix.unsharedKeySize; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("sharedKeySize", sharedKeySize) - .add("unsharedKeySize", unsharedKeySize) - .toString(); - } - } - - /** A {@link Coder} for {@link KeyPrefix}. */ - static final class KeyPrefixCoder extends AtomicCoder { - private static final KeyPrefixCoder INSTANCE = new KeyPrefixCoder(); - - @JsonCreator - public static KeyPrefixCoder of() { - return INSTANCE; - } - - @Override - public void encode(KeyPrefix value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - VarInt.encode(value.sharedKeySize, outStream); - VarInt.encode(value.unsharedKeySize, outStream); - } - - @Override - public KeyPrefix decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - return new KeyPrefix(VarInt.decodeInt(inStream), VarInt.decodeInt(inStream)); - } - - @Override - public boolean consistentWithEquals() { - return true; - } - - @Override - public boolean isRegisterByteSizeObserverCheap(KeyPrefix value, Coder.Context context) { - return true; - } - - @Override - protected long getEncodedElementByteSize(KeyPrefix value, Coder.Context context) - throws Exception { - checkNotNull(value); - return VarInt.getLength(value.sharedKeySize) + VarInt.getLength(value.unsharedKeySize); - } - } - - /** - * The footer stores the relevant information required to locate the index and bloom filter. - * It also stores a version byte and the number of keys stored. - * - *

              The footer is encoded as the value containing: - *

                - *
              • start of bloom filter offset (big endian long coding)
              • - *
              • start of shard index position offset (big endian long coding)
              • - *
              • number of keys in file (big endian long coding)
              • - *
              • 0x01 (version key as a single byte)
              • - *
              - */ - static class Footer { - static final int LONG_BYTES = 8; - static final int FIXED_LENGTH = 3 * LONG_BYTES + 1; - static final byte VERSION = 2; - - private final long indexPosition; - private final long bloomFilterPosition; - private final long numberOfKeys; - - Footer(long indexPosition, long bloomFilterPosition, long numberOfKeys) { - this.indexPosition = indexPosition; - this.bloomFilterPosition = bloomFilterPosition; - this.numberOfKeys = numberOfKeys; - } - - public long getIndexPosition() { - return indexPosition; - } - - public long getBloomFilterPosition() { - return bloomFilterPosition; - } - - public long getNumberOfKeys() { - return numberOfKeys; - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (!(other instanceof Footer)) { - return false; - } - Footer footer = (Footer) other; - return indexPosition == footer.indexPosition - && bloomFilterPosition == footer.bloomFilterPosition - && numberOfKeys == footer.numberOfKeys; - } - - @Override - public int hashCode() { - return Objects.hashCode(indexPosition, bloomFilterPosition, numberOfKeys); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("version", Footer.VERSION) - .add("indexPosition", indexPosition) - .add("bloomFilterPosition", bloomFilterPosition) - .add("numberOfKeys", numberOfKeys) - .toString(); - } - } - - /** A {@link Coder} for {@link Footer}. */ - static final class FooterCoder extends AtomicCoder
              { - private static final FooterCoder INSTANCE = new FooterCoder(); - - @JsonCreator - public static FooterCoder of() { - return INSTANCE; - } - - @Override - public void encode(Footer value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - DataOutputStream dataOut = new DataOutputStream(outStream); - dataOut.writeLong(value.indexPosition); - dataOut.writeLong(value.bloomFilterPosition); - dataOut.writeLong(value.numberOfKeys); - dataOut.write(Footer.VERSION); - } - - @Override - public Footer decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - DataInputStream dataIn = new DataInputStream(inStream); - Footer footer = new Footer(dataIn.readLong(), dataIn.readLong(), dataIn.readLong()); - int version = dataIn.read(); - if (version != Footer.VERSION) { - throw new IOException("Unknown version " + version + ". " - + "Only version 2 is currently supported."); - } - return footer; - } - - @Override - public boolean consistentWithEquals() { - return true; - } - - @Override - public boolean isRegisterByteSizeObserverCheap(Footer value, Coder.Context context) { - return true; - } - - @Override - protected long getEncodedElementByteSize(Footer value, Coder.Context context) - throws Exception { - return Footer.FIXED_LENGTH; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/package-info.java deleted file mode 100644 index af0a345d6d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Implementation of the harness that runs on each Google Compute Engine instance to coordinate - * execution of Pipeline code. - */ -@ParametersAreNonnullByDefault -package com.google.cloud.dataflow.sdk.runners.worker; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/CoderProperties.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/CoderProperties.java deleted file mode 100644 index 5705dc4c78..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/CoderProperties.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.util.Structs; -import com.google.cloud.dataflow.sdk.util.UnownedInputStream; -import com.google.cloud.dataflow.sdk.util.UnownedOutputStream; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Iterables; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** - * Properties for use in {@link Coder} tests. These are implemented with junit assertions - * rather than as predicates for the sake of error messages. - * - *

              We serialize and deserialize the coder to make sure that any state information required by - * the coder is preserved. This causes tests written such that coders that lose information during - * serialization or change state during encoding/decoding will fail. - */ -public class CoderProperties { - - /** - * All the contexts, for use in test cases. - */ - public static final List ALL_CONTEXTS = Arrays.asList( - Coder.Context.OUTER, Coder.Context.NESTED); - - /** - * Verifies that for the given {@code Coder}, and values of - * type {@code T}, if the values are equal then the encoded bytes are equal, in any - * {@code Coder.Context}. - */ - public static void coderDeterministic( - Coder coder, T value1, T value2) - throws Exception { - for (Coder.Context context : ALL_CONTEXTS) { - coderDeterministicInContext(coder, context, value1, value2); - } - } - - /** - * Verifies that for the given {@code Coder}, {@code Coder.Context}, and values of - * type {@code T}, if the values are equal then the encoded bytes are equal. - */ - public static void coderDeterministicInContext( - Coder coder, Coder.Context context, T value1, T value2) - throws Exception { - - try { - coder.verifyDeterministic(); - } catch (NonDeterministicException e) { - fail("Expected that the coder is deterministic"); - } - assertThat("Expected that the passed in values are equal()", value1, equalTo(value2)); - assertThat( - encode(coder, context, value1), - equalTo(encode(coder, context, value2))); - } - - /** - * Verifies that for the given {@code Coder}, - * and value of type {@code T}, encoding followed by decoding yields an - * equal value of type {@code T}, in any {@code Coder.Context}. - */ - public static void coderDecodeEncodeEqual( - Coder coder, T value) - throws Exception { - for (Coder.Context context : ALL_CONTEXTS) { - coderDecodeEncodeEqualInContext(coder, context, value); - } - } - - /** - * Verifies that for the given {@code Coder}, {@code Coder.Context}, - * and value of type {@code T}, encoding followed by decoding yields an - * equal value of type {@code T}. - */ - public static void coderDecodeEncodeEqualInContext( - Coder coder, Coder.Context context, T value) - throws Exception { - assertThat(decodeEncode(coder, context, value), equalTo(value)); - } - - /** - * Verifies that for the given {@code Coder>}, - * and value of type {@code Collection}, encoding followed by decoding yields an - * equal value of type {@code Collection}, in any {@code Coder.Context}. - */ - public static > void coderDecodeEncodeContentsEqual( - Coder coder, CollectionT value) - throws Exception { - for (Coder.Context context : ALL_CONTEXTS) { - coderDecodeEncodeContentsEqualInContext(coder, context, value); - } - } - - /** - * Verifies that for the given {@code Coder>}, - * and value of type {@code Collection}, encoding followed by decoding yields an - * equal value of type {@code Collection}, in the given {@code Coder.Context}. - */ - @SuppressWarnings("unchecked") - public static > void coderDecodeEncodeContentsEqualInContext( - Coder coder, Coder.Context context, CollectionT value) - throws Exception { - // Matchers.containsInAnyOrder() requires at least one element - Collection result = decodeEncode(coder, context, value); - if (value.isEmpty()) { - assertThat(result, emptyIterable()); - } else { - // This is the only Matchers.containInAnyOrder() overload that takes literal values - assertThat(result, containsInAnyOrder((T[]) value.toArray())); - } - } - - /** - * Verifies that for the given {@code Coder>}, - * and value of type {@code Collection}, encoding followed by decoding yields an - * equal value of type {@code Collection}, in any {@code Coder.Context}. - */ - public static > void coderDecodeEncodeContentsInSameOrder( - Coder coder, IterableT value) - throws Exception { - for (Coder.Context context : ALL_CONTEXTS) { - CoderProperties.coderDecodeEncodeContentsInSameOrderInContext( - coder, context, value); - } - } - - /** - * Verifies that for the given {@code Coder>}, - * and value of type {@code Iterable}, encoding followed by decoding yields an - * equal value of type {@code Collection}, in the given {@code Coder.Context}. - */ - @SuppressWarnings("unchecked") - public static > void - coderDecodeEncodeContentsInSameOrderInContext( - Coder coder, Coder.Context context, IterableT value) - throws Exception { - Iterable result = decodeEncode(coder, context, value); - // Matchers.contains() requires at least one element - if (Iterables.isEmpty(value)) { - assertThat(result, emptyIterable()); - } else { - // This is the only Matchers.contains() overload that takes literal values - assertThat(result, contains((T[]) Iterables.toArray(value, Object.class))); - } - } - - public static void coderSerializable(Coder coder) { - SerializableUtils.ensureSerializable(coder); - } - - public static void coderConsistentWithEquals( - Coder coder, T value1, T value2) - throws Exception { - - for (Coder.Context context : ALL_CONTEXTS) { - CoderProperties.coderConsistentWithEqualsInContext(coder, context, value1, value2); - } - } - - public static void coderConsistentWithEqualsInContext( - Coder coder, Coder.Context context, T value1, T value2) throws Exception { - - assertEquals( - value1.equals(value2), - Arrays.equals( - encode(coder, context, value1), - encode(coder, context, value2))); - } - - public static void coderHasEncodingId(Coder coder, String encodingId) throws Exception { - assertThat(coder.getEncodingId(), equalTo(encodingId)); - assertThat(Structs.getString(coder.asCloudObject(), PropertyNames.ENCODING_ID, ""), - equalTo(encodingId)); - } - - public static void coderAllowsEncoding(Coder coder, String encodingId) throws Exception { - assertThat(coder.getAllowedEncodings(), hasItem(encodingId)); - assertThat( - String.format("Expected to find \"%s\" in property \"%s\" of %s", - encodingId, PropertyNames.ALLOWED_ENCODINGS, coder.asCloudObject()), - Structs.getStrings( - coder.asCloudObject(), - PropertyNames.ALLOWED_ENCODINGS, - Collections.emptyList()), - hasItem(encodingId)); - } - - public static void structuralValueConsistentWithEquals( - Coder coder, T value1, T value2) - throws Exception { - - for (Coder.Context context : ALL_CONTEXTS) { - CoderProperties.structuralValueConsistentWithEqualsInContext( - coder, context, value1, value2); - } - } - - public static void structuralValueConsistentWithEqualsInContext( - Coder coder, Coder.Context context, T value1, T value2) throws Exception { - - assertEquals( - coder.structuralValue(value1).equals(coder.structuralValue(value2)), - Arrays.equals( - encode(coder, context, value1), - encode(coder, context, value2))); - } - - - private static final String DECODING_WIRE_FORMAT_MESSAGE = - "Decoded value from known wire format does not match expected value." - + " This probably means that this Coder no longer correctly decodes" - + " a prior wire format. Changing the wire formats this Coder can read" - + " should be avoided, as it is likely to cause breakage." - + " If you truly intend to change the backwards compatibility for this Coder " - + " then you must remove any now-unsupported encodings from getAllowedEncodings()."; - - public static void coderDecodesBase64(Coder coder, String base64Encoding, T value) - throws Exception { - assertThat(DECODING_WIRE_FORMAT_MESSAGE, CoderUtils.decodeFromBase64(coder, base64Encoding), - equalTo(value)); - } - - public static void coderDecodesBase64( - Coder coder, List base64Encodings, List values) throws Exception { - assertThat("List of base64 encodings has different size than List of values", - base64Encodings.size(), equalTo(values.size())); - - for (int i = 0; i < base64Encodings.size(); i++) { - coderDecodesBase64(coder, base64Encodings.get(i), values.get(i)); - } - } - - private static final String ENCODING_WIRE_FORMAT_MESSAGE = - "Encoded value does not match expected wire format." - + " Changing the wire format should be avoided, as it is likely to cause breakage." - + " If you truly intend to change the wire format for this Coder " - + " then you must update getEncodingId() to a new value and add any supported" - + " prior formats to getAllowedEncodings()." - + " See com.google.cloud.dataflow.sdk.coders.PrintBase64Encoding for how to generate" - + " new test data."; - - public static void coderEncodesBase64(Coder coder, T value, String base64Encoding) - throws Exception { - assertThat(ENCODING_WIRE_FORMAT_MESSAGE, CoderUtils.encodeToBase64(coder, value), - equalTo(base64Encoding)); - } - - public static void coderEncodesBase64( - Coder coder, List values, List base64Encodings) throws Exception { - assertThat("List of base64 encodings has different size than List of values", - base64Encodings.size(), equalTo(values.size())); - - for (int i = 0; i < base64Encodings.size(); i++) { - coderEncodesBase64(coder, values.get(i), base64Encodings.get(i)); - } - } - - @SuppressWarnings("unchecked") - public static > void coderDecodesBase64ContentsEqual( - Coder coder, String base64Encoding, IterableT expected) throws Exception { - - IterableT result = CoderUtils.decodeFromBase64(coder, base64Encoding); - if (Iterables.isEmpty(expected)) { - assertThat(ENCODING_WIRE_FORMAT_MESSAGE, result, emptyIterable()); - } else { - assertThat(ENCODING_WIRE_FORMAT_MESSAGE, result, - containsInAnyOrder((T[]) Iterables.toArray(expected, Object.class))); - } - } - - public static > void coderDecodesBase64ContentsEqual( - Coder coder, List base64Encodings, List expected) - throws Exception { - assertThat("List of base64 encodings has different size than List of values", - base64Encodings.size(), equalTo(expected.size())); - - for (int i = 0; i < base64Encodings.size(); i++) { - coderDecodesBase64ContentsEqual(coder, base64Encodings.get(i), expected.get(i)); - } - } - - ////////////////////////////////////////////////////////////////////////// - - @VisibleForTesting - static byte[] encode( - Coder coder, Coder.Context context, T value) throws CoderException, IOException { - @SuppressWarnings("unchecked") - Coder deserializedCoder = Serializer.deserialize(coder.asCloudObject(), Coder.class); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - deserializedCoder.encode(value, new UnownedOutputStream(os), context); - return os.toByteArray(); - } - - @VisibleForTesting - static T decode( - Coder coder, Coder.Context context, byte[] bytes) throws CoderException, IOException { - @SuppressWarnings("unchecked") - Coder deserializedCoder = Serializer.deserialize(coder.asCloudObject(), Coder.class); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - return deserializedCoder.decode(new UnownedInputStream(is), context); - } - - private static T decodeEncode(Coder coder, Coder.Context context, T value) - throws CoderException, IOException { - return decode(coder, context, encode(coder, context, value)); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java deleted file mode 100644 index 559f5179fd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/DataflowAssert.java +++ /dev/null @@ -1,1579 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.StreamingOptions; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Never; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.GatherAllPanes; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.NoSuchElementException; - -/** - * An assertion on the contents of a {@link PCollection} incorporated into the pipeline. Such an - * assertion can be checked no matter what kind of {@link PipelineRunner} is used. - * - *

              Note that the {@code DataflowAssert} call must precede the call - * to {@link Pipeline#run}. - * - *

              Examples of use:

              {@code
              - * Pipeline p = TestPipeline.create();
              - * ...
              - * PCollection output =
              - *      input
              - *      .apply(ParDo.of(new TestDoFn()));
              - * DataflowAssert.that(output)
              - *     .containsInAnyOrder("out1", "out2", "out3");
              - * ...
              - * PCollection ints = ...
              - * PCollection sum =
              - *     ints
              - *     .apply(Combine.globally(new SumInts()));
              - * DataflowAssert.that(sum)
              - *     .is(42);
              - * ...
              - * p.run();
              - * }
              - * - *

              JUnit and Hamcrest must be linked in by any code that uses DataflowAssert. - */ -public class DataflowAssert { - - private static final Logger LOG = LoggerFactory.getLogger(DataflowAssert.class); - - static final String SUCCESS_COUNTER = "DataflowAssertSuccess"; - static final String FAILURE_COUNTER = "DataflowAssertFailure"; - - private static int assertCount = 0; - - private static String nextAssertionName() { - return "DataflowAssert$" + (assertCount++); - } - - // Do not instantiate. - private DataflowAssert() {} - - /** - * Builder interface for assertions applicable to iterables and PCollection contents. - */ - public interface IterableAssert { - /** - * Sets the coder of the actual {@link PCollection}. - * - * @return the same {@link IterableAssert} builder for further assertions - * @deprecated instead call {@link PCollection#setCoder(Coder)} on the actual - * {@link PCollection} directly. - */ - @Deprecated - IterableAssert setCoder(Coder coderOrNull); - - /** - * Returns the coder of the actual {@link PCollection}. - * - * @deprecated instead call {@link PCollection#getCoder()} on the actual {@link PCollection} - * directly - */ - @Deprecated - Coder getCoder(); - /** - * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only - * run on the provided window. - * - *

              The assertion will concatenate all panes present in the provided window if the - * {@link Trigger} produces multiple panes. If the windowing strategy accumulates fired panes - * and triggers fire multple times, consider using instead {@link #inFinalPane(BoundedWindow)} - * or {@link #inOnTimePane(BoundedWindow)}. - * - * @return a new {@link IterableAssert} like this one but with the assertion only applied to the - * specified window. - */ - IterableAssert inWindow(BoundedWindow window); - - /** - * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only - * run on the provided window, running the checker only on the final pane for each key. - * - *

              If the input {@link WindowingStrategy} does not always produce final panes, the assertion - * may be executed over an empty input even if the trigger has fired previously. To ensure that - * a final pane is always produced, set the {@link ClosingBehavior} of the windowing strategy - * (via {@link Window.Bound#withAllowedLateness(Duration, ClosingBehavior)} setting - * {@link ClosingBehavior} to {@link ClosingBehavior#FIRE_ALWAYS}). - * - * @return a new {@link IterableAssert} like this one but with the assertion only applied to the - * specified window. - */ - IterableAssert inFinalPane(BoundedWindow window); - - /** - * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only - * run on the provided window. - * - * @return a new {@link IterableAssert} like this one but with the assertion only applied to the - * specified window. - */ - IterableAssert inOnTimePane(BoundedWindow window); - - /** - * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only - * run on the provided window across all panes that were not produced by the arrival of late - * data. - * - * @return a new {@link IterableAssert} like this one but with the assertion only applied to the - * specified window. - */ - IterableAssert inCombinedNonLatePanes(BoundedWindow window); - - /** - * Creates a new {@link IterableAssert} like this one, but with the assertion restricted to only - * run on panes in the {@link GlobalWindow} that were emitted before the {@link GlobalWindow} - * closed. These panes have {@link Timing#EARLY}. - */ - IterableAssert inEarlyGlobalWindowPanes(); - - /** - * Asserts that the iterable in question contains the provided elements. - * - * @return the same {@link IterableAssert} builder for further assertions - */ - IterableAssert containsInAnyOrder(T... expectedElements); - - /** - * Asserts that the iterable in question contains the provided elements. - * - * @return the same {@link IterableAssert} builder for further assertions - */ - IterableAssert containsInAnyOrder(Iterable expectedElements); - - /** - * Asserts that the iterable in question is empty. - * - * @return the same {@link IterableAssert} builder for further assertions - */ - IterableAssert empty(); - - /** - * Applies the provided checking function (presumably containing assertions) to the - * iterable in question. - * - * @return the same {@link IterableAssert} builder for further assertions - */ - IterableAssert satisfies(SerializableFunction, Void> checkerFn); - } - - /** - * Builder interface for assertions applicable to a single value. - */ - public interface SingletonAssert { - /** - * Sets the coder of the actual {@link PCollection}. - * - * @return the same {@link IterableAssert} builder for further assertions - * @deprecated instead call {@link PCollection#setCoder(Coder)} on the actual - * {@link PCollection} directly. - */ - @Deprecated - SingletonAssert setCoder(Coder coderOrNull); - - /** - * Returns the coder of the actual {@link PCollection}. - * - * @deprecated instead call {@link PCollection#getCoder()} on the actual {@link PCollection} - * directly - */ - @Deprecated - Coder getCoder(); - - /** - * Creates a new {@link SingletonAssert} like this one, but with the assertion restricted to - * only run on the provided window. - * - *

              The assertion will expect outputs to be produced to the provided window exactly once. If - * the upstream {@link Trigger} may produce output multiple times, consider instead using - * {@link #inFinalPane(BoundedWindow)} or {@link #inOnTimePane(BoundedWindow)}. - * - * @return a new {@link SingletonAssert} like this one but with the assertion only applied to - * the specified window. - */ - SingletonAssert inOnlyPane(BoundedWindow window); - - /** - * Creates a new {@link SingletonAssert} like this one, but with the assertion restricted to - * only run on the provided window, running the checker only on the final pane for each key. - * - *

              If the input {@link WindowingStrategy} does not always produce final panes, the assertion - * may be executed over an empty input even if the trigger has fired previously. To ensure that - * a final pane is always produced, set the {@link ClosingBehavior} of the windowing strategy - * (via {@link Window.Bound#withAllowedLateness(Duration, ClosingBehavior)} setting - * {@link ClosingBehavior} to {@link ClosingBehavior#FIRE_ALWAYS}). - * - * @return a new {@link SingletonAssert} like this one but with the assertion only applied to - * the specified window. - */ - SingletonAssert inFinalPane(BoundedWindow window); - - /** - * Creates a new {@link SingletonAssert} like this one, but with the assertion restricted to - * only run on the provided window, running the checker only on the on-time pane for each key. - * - * @return a new {@link SingletonAssert} like this one but with the assertion only applied to - * the specified window. - */ - SingletonAssert inOnTimePane(BoundedWindow window); - - /** - * Asserts that the value in question is equal to the provided value, according to - * {@link Object#equals}. - * - * @return the same {@link SingletonAssert} builder for further assertions - */ - SingletonAssert isEqualTo(T expected); - - /** - * Asserts that the value in question is equal to the provided value, according to - * {@link Object#equals}. - * - * @deprecated instead use {@link #isEqualTo(Object)} - * @return the same {@link SingletonAssert} builder for further assertions - */ - @Deprecated - SingletonAssert is(T expected); - - /** - * Asserts that the value in question is not equal to the provided value, according - * to {@link Object#equals}. - * - * @return the same {@link SingletonAssert} builder for further assertions - */ - SingletonAssert notEqualTo(T notExpected); - - /** - * Applies the provided checking function (presumably containing assertions) to the - * value in question. - * - * @return the same {@link SingletonAssert} builder for further assertions - */ - SingletonAssert satisfies(SerializableFunction checkerFn); - } - - /** - * Constructs an {@link IterableAssert} for the elements of the provided {@link PCollection}. - */ - public static IterableAssert that(PCollection actual) { - return new PCollectionContentsAssert<>(actual); - } - - /** - * Constructs an {@link IterableAssert} for the value of the provided {@link PCollection} which - * must contain a single {@code Iterable} value. - */ - public static IterableAssert thatSingletonIterable( - PCollection> actual) { - - try { - } catch (NoSuchElementException | IllegalArgumentException exc) { - throw new IllegalArgumentException( - "DataflowAssert.thatSingletonIterable requires a PCollection>" - + " with a Coder> where getCoderArguments() yields a" - + " single Coder to apply to the elements."); - } - - @SuppressWarnings("unchecked") // Safe covariant cast - PCollection> actualIterables = (PCollection>) actual; - - return new PCollectionSingletonIterableAssert<>(actualIterables); - } - - /** - * Constructs an {@link IterableAssert} for the value of the provided {@link PCollectionView}. - * - * @deprecated use {@link #thatSingletonIterable(PCollection)}, - * {@link #thatSingleton(PCollection)} or {@link #that(PCollection)} instead. - */ - @Deprecated - public static IterableAssert thatIterable(PCollectionView> actual) { - return new PCollectionViewIterableAssert(actual); - } - - /** - * Constructs a {@link SingletonAssert} for the value of the provided - * {@code PCollection PCollection}, which must be a singleton. - */ - public static SingletonAssert thatSingleton(PCollection actual) { - return new PCollectionViewAssert<>(actual, View.asSingleton(), actual.getCoder()); - } - - /** - * Constructs a {@link SingletonAssert} for the value of the provided {@link PCollection}. - * - *

              Note that the actual value must be coded by a {@link KvCoder}, not just any - * {@code Coder}. - */ - public static SingletonAssert>> thatMultimap( - PCollection> actual) { - @SuppressWarnings("unchecked") - KvCoder kvCoder = (KvCoder) actual.getCoder(); - return new PCollectionViewAssert<>( - actual, - View.asMultimap(), - MapCoder.of(kvCoder.getKeyCoder(), IterableCoder.of(kvCoder.getValueCoder()))); - } - - /** - * Constructs a {@link SingletonAssert} for the value of the provided {@link PCollection}, which - * must have at most one value per key. - * - *

              Note that the actual value must be coded by a {@link KvCoder}, not just any - * {@code Coder}. - */ - public static SingletonAssert> thatMap(PCollection> actual) { - @SuppressWarnings("unchecked") - KvCoder kvCoder = (KvCoder) actual.getCoder(); - return new PCollectionViewAssert<>( - actual, View.asMap(), MapCoder.of(kvCoder.getKeyCoder(), kvCoder.getValueCoder())); - } - - //////////////////////////////////////////////////////////// - - /** - * An {@link IterableAssert} about the contents of a {@link PCollection}. This does not require - * the runner to support side inputs. - */ - private static class PCollectionContentsAssert implements IterableAssert { - private final PCollection actual; - private final AssertionWindows rewindowingStrategy; - private final SimpleFunction>, Iterable> paneExtractor; - - public PCollectionContentsAssert(PCollection actual) { - this(actual, IntoGlobalWindow.of(), PaneExtractors.onlyPane()); - } - - public PCollectionContentsAssert( - PCollection actual, - AssertionWindows rewindowingStrategy, - SimpleFunction>, Iterable> paneExtractor) { - this.actual = actual; - this.rewindowingStrategy = rewindowingStrategy; - this.paneExtractor = paneExtractor; - } - - @Override - public PCollectionContentsAssert inWindow(BoundedWindow window) { - return withPane(window, PaneExtractors.allPanes()); - } - - @Override - public PCollectionContentsAssert inFinalPane(BoundedWindow window) { - return withPane(window, PaneExtractors.finalPane()); - } - - @Override - public PCollectionContentsAssert inOnTimePane(BoundedWindow window) { - return withPane(window, PaneExtractors.onTimePane()); - } - - @Override - public PCollectionContentsAssert inCombinedNonLatePanes(BoundedWindow window) { - return withPane(window, PaneExtractors.nonLatePanes()); - } - - @Override - public IterableAssert inEarlyGlobalWindowPanes() { - return withPane(GlobalWindow.INSTANCE, PaneExtractors.earlyPanes()); - } - - private PCollectionContentsAssert withPane( - BoundedWindow window, - SimpleFunction>, Iterable> paneExtractor) { - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder windowCoder = - (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(); - return new PCollectionContentsAssert<>( - actual, IntoStaticWindows.of(windowCoder, window), paneExtractor); - } - - @Override - public IterableAssert setCoder(Coder coderOrNull) { - if (coderOrNull != null) { - actual.setCoder(coderOrNull); - } - return this; - } - - @Override - public Coder getCoder() { - return actual.getCoder(); - } - - /** - * Checks that the {@code Iterable} contains the expected elements, in any order. - * - *

              Returns this {@code IterableAssert}. - */ - @Override - @SafeVarargs - public final PCollectionContentsAssert containsInAnyOrder(T... expectedElements) { - return containsInAnyOrder(Arrays.asList(expectedElements)); - } - - /** - * Checks that the {@code Iterable} contains the expected elements, in any order. - * - *

              Returns this {@code IterableAssert}. - */ - @Override - public PCollectionContentsAssert containsInAnyOrder(Iterable expectedElements) { - return satisfies(new AssertContainsInAnyOrderRelation(), expectedElements); - } - - @Override - public PCollectionContentsAssert empty() { - containsInAnyOrder(Collections.emptyList()); - return this; - } - - @Override - public PCollectionContentsAssert satisfies( - SerializableFunction, Void> checkerFn) { - actual.apply( - nextAssertionName(), - new GroupThenAssert<>(checkerFn, rewindowingStrategy, paneExtractor)); - return this; - } - - /** - * Checks that the {@code Iterable} contains elements that match the provided matchers, in any - * order. - * - *

              Returns this {@code IterableAssert}. - */ - @SafeVarargs - final PCollectionContentsAssert containsInAnyOrder( - SerializableMatcher... elementMatchers) { - return satisfies(SerializableMatchers.containsInAnyOrder(elementMatchers)); - } - - /** - * Applies a {@link SerializableFunction} to check the elements of the {@code Iterable}. - * - *

              Returns this {@code IterableAssert}. - */ - private PCollectionContentsAssert satisfies( - AssertRelation, Iterable> relation, Iterable expectedElements) { - return satisfies( - new CheckRelationAgainstExpected>( - relation, expectedElements, IterableCoder.of(actual.getCoder()))); - } - - /** - * Applies a {@link SerializableMatcher} to check the elements of the {@code Iterable}. - * - *

              Returns this {@code IterableAssert}. - */ - PCollectionContentsAssert satisfies( - final SerializableMatcher> matcher) { - // Safe covariant cast. Could be elided by changing a lot of this file to use - // more flexible bounds. - @SuppressWarnings({"rawtypes", "unchecked"}) - SerializableFunction, Void> checkerFn = - (SerializableFunction) new MatcherCheckerFn<>(matcher); - actual.apply( - "DataflowAssert$" + (assertCount++), - new GroupThenAssert<>(checkerFn, rewindowingStrategy, paneExtractor)); - return this; - } - - private static class MatcherCheckerFn implements SerializableFunction { - private SerializableMatcher matcher; - - public MatcherCheckerFn(SerializableMatcher matcher) { - this.matcher = matcher; - } - - @Override - public Void apply(T actual) { - assertThat(actual, matcher); - return null; - } - } - - /** - * @throws UnsupportedOperationException always - * @deprecated {@link Object#equals(Object)} is not supported on DataflowAssert objects. - * If you meant to test object equality, use a variant of {@link #containsInAnyOrder} - * instead. - */ - @Deprecated - @Override - public boolean equals(Object o) { - throw new UnsupportedOperationException( - "If you meant to test object equality, use .containsInAnyOrder instead."); - } - - /** - * @throws UnsupportedOperationException always. - * @deprecated {@link Object#hashCode()} is not supported on DataflowAssert objects. - */ - @Deprecated - @Override - public int hashCode() { - throw new UnsupportedOperationException( - String.format("%s.hashCode() is not supported.", IterableAssert.class.getSimpleName())); - } - } - - /** - * An {@link IterableAssert} for an iterable that is the sole element of a {@link PCollection}. - * This does not require the runner to support side inputs. - */ - private static class PCollectionSingletonIterableAssert implements IterableAssert { - private final PCollection> actual; - private final Coder elementCoder; - private final AssertionWindows rewindowingStrategy; - private final SimpleFunction>>, Iterable>> - paneExtractor; - - public PCollectionSingletonIterableAssert(PCollection> actual) { - this(actual, IntoGlobalWindow.>of(), PaneExtractors.>onlyPane()); - } - - public PCollectionSingletonIterableAssert( - PCollection> actual, - AssertionWindows rewindowingStrategy, - SimpleFunction>>, Iterable>> paneExtractor) { - this.actual = actual; - - @SuppressWarnings("unchecked") - Coder typedCoder = (Coder) actual.getCoder().getCoderArguments().get(0); - this.elementCoder = typedCoder; - - this.rewindowingStrategy = rewindowingStrategy; - this.paneExtractor = paneExtractor; - } - - @Override - public PCollectionSingletonIterableAssert inWindow(BoundedWindow window) { - return withPanes(window, PaneExtractors.>allPanes()); - } - - @Override - public PCollectionSingletonIterableAssert inFinalPane(BoundedWindow window) { - return withPanes(window, PaneExtractors.>finalPane()); - } - - @Override - public PCollectionSingletonIterableAssert inOnTimePane(BoundedWindow window) { - return withPanes(window, PaneExtractors.>onTimePane()); - } - - @Override - public PCollectionSingletonIterableAssert inCombinedNonLatePanes(BoundedWindow window) { - return withPanes(window, PaneExtractors.>nonLatePanes()); - } - - @Override - public IterableAssert inEarlyGlobalWindowPanes() { - return withPanes(GlobalWindow.INSTANCE, PaneExtractors.>earlyPanes()); - } - - private PCollectionSingletonIterableAssert withPanes( - BoundedWindow window, - SimpleFunction>>, Iterable>> paneExtractor) { - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder windowCoder = - (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(); - return new PCollectionSingletonIterableAssert<>( - actual, IntoStaticWindows.>of(windowCoder, window), paneExtractor); - } - - @Override - public IterableAssert setCoder(Coder coderOrNull) { - return this; - } - - @Override - public Coder getCoder() { - return elementCoder; - } - - @Override - @SafeVarargs - public final PCollectionSingletonIterableAssert containsInAnyOrder(T... expectedElements) { - return containsInAnyOrder(Arrays.asList(expectedElements)); - } - - @Override - public PCollectionSingletonIterableAssert empty() { - return containsInAnyOrder(Collections.emptyList()); - } - - @Override - public PCollectionSingletonIterableAssert containsInAnyOrder(Iterable expectedElements) { - return satisfies(new AssertContainsInAnyOrderRelation(), expectedElements); - } - - @Override - public PCollectionSingletonIterableAssert satisfies( - SerializableFunction, Void> checkerFn) { - actual.apply( - "DataflowAssert$" + (assertCount++), - new GroupThenAssertForSingleton<>(checkerFn, rewindowingStrategy, paneExtractor)); - return this; - } - - private PCollectionSingletonIterableAssert satisfies( - AssertRelation, Iterable> relation, Iterable expectedElements) { - return satisfies( - new CheckRelationAgainstExpected>( - relation, expectedElements, IterableCoder.of(elementCoder))); - } - } - - private static class PCollectionViewIterableAssert implements IterableAssert { - private final PCollectionView> actual; - private Optional> valueCoder; - - private PCollectionViewIterableAssert( - PCollectionView> actual) { - this.actual = actual; - valueCoder = Optional.absent(); - } - - @Override - public IterableAssert setCoder(Coder coderOrNull) { - valueCoder = Optional.fromNullable(coderOrNull); - return this; - } - - @Override - public Coder getCoder() { - if (valueCoder.isPresent()) { - return valueCoder.get(); - } else { - throw new IllegalArgumentException("Blah"); - } - } - - @Override - public IterableAssert inWindow(BoundedWindow window) { - throw new UnsupportedOperationException( - "IterableAssert of a PCollectionView does not support windowed assertions"); - } - - @Override - public IterableAssert inFinalPane(BoundedWindow window) { - // TODO: Can maybe be supported? - throw new UnsupportedOperationException( - "IterableAssert of a PCollectionView does not support windowed assertions"); - } - - @Override - public IterableAssert inOnTimePane(BoundedWindow window) { - throw new UnsupportedOperationException( - "IterableAssert of a PCollectionView does not support windowed assertions"); - } - - @Override - public IterableAssert inCombinedNonLatePanes(BoundedWindow window) { - throw new UnsupportedOperationException( - "IterableAssert of a PCollectionView does not support windowed assertions"); - } - - @Override - public IterableAssert inEarlyGlobalWindowPanes() { - throw new UnsupportedOperationException( - "IterableAssert of a PCollectionView does not support windowed assertions"); - } - - @Override - public IterableAssert containsInAnyOrder(T... expectedElements) { - return containsInAnyOrder(ImmutableList.copyOf(expectedElements)); - } - - @Override - public IterableAssert containsInAnyOrder(Iterable expectedElements) { - return satisfies(new AssertContainsInAnyOrderRelation(), expectedElements); - } - - private IterableAssert satisfies( - AssertRelation, Iterable> relation, - Iterable expectedElements) { - Coder elemCoder; - if (valueCoder.isPresent()) { - elemCoder = valueCoder.get(); - } else { - try { - elemCoder = - Create.of(expectedElements).getDefaultOutputCoder(actual.getPipeline().begin()); - } catch (CannotProvideCoderException e) { - throw new IllegalArgumentException( - "Attempted to infer the Coder of an IterableAssert, but no Coder was explicitly set " - + "and no coder could be inferred", e); - } - } - return satisfies(new CheckRelationAgainstExpected>( - relation, expectedElements, IterableCoder.of(elemCoder))); - } - - @Override - public IterableAssert empty() { - return containsInAnyOrder(); - } - - @Override - public IterableAssert satisfies(SerializableFunction, Void> checkerFn) { - PTransform>> identity = - new PTransform>>() { - @Override - public PCollectionView> apply(PBegin input) { - return actual; - } - }; - actual.getPipeline() - .apply(nextAssertionName(), - new OneSideInputAssert<>( - identity, - Window.into(new GlobalWindows()), - checkerFn)); - return this; - } - - /** - * @throws UnsupportedOperationException always - * @deprecated {@link Object#equals(Object)} is not supported on DataflowAssert objects. - * If you meant to test object equality, use a variant of {@link #containsInAnyOrder} - * instead. - */ - @Deprecated - @Override - public boolean equals(Object o) { - throw new UnsupportedOperationException( - "If you meant to test object equality, use .containsInAnyOrder instead."); - } - - /** - * @throws UnsupportedOperationException always. - * @deprecated {@link Object#hashCode()} is not supported on DataflowAssert objects. - */ - @Deprecated - @Override - public int hashCode() { - throw new UnsupportedOperationException( - String.format("%s.hashCode() is not supported.", IterableAssert.class.getSimpleName())); - } - } - - /** - * An assertion about the contents of a {@link PCollection} when it is viewed as a single value - * of type {@code ViewT}. This requires side input support from the runner. - */ - private static class PCollectionViewAssert implements SingletonAssert { - private final PCollection actual; - private final PTransform, PCollectionView> view; - private final AssertionWindows rewindowActuals; - private final SimpleFunction>, Iterable> paneExtractor; - private final Coder coder; - - protected PCollectionViewAssert( - PCollection actual, - PTransform, PCollectionView> view, - Coder coder) { - this(actual, view, IntoGlobalWindow.of(), PaneExtractors.onlyPane(), coder); - } - - private PCollectionViewAssert( - PCollection actual, - PTransform, PCollectionView> view, - AssertionWindows rewindowActuals, - SimpleFunction>, Iterable> paneExtractor, - Coder coder) { - this.actual = actual; - this.view = view; - this.rewindowActuals = rewindowActuals; - this.paneExtractor = paneExtractor; - this.coder = coder; - } - - @Override - public SingletonAssert setCoder(Coder coderOrNull) { - return this; - } - - @Override - public Coder getCoder() { - return coder; - } - - public PCollectionViewAssert inOnlyPane(BoundedWindow window) { - return inPane(window, PaneExtractors.onlyPane()); - } - - @Override - public PCollectionViewAssert inFinalPane(BoundedWindow window) { - return inPane(window, PaneExtractors.finalPane()); - } - - @Override - public PCollectionViewAssert inOnTimePane(BoundedWindow window) { - return inPane(window, PaneExtractors.onTimePane()); - } - - private PCollectionViewAssert inPane( - BoundedWindow window, - SimpleFunction>, Iterable> paneExtractor) { - return new PCollectionViewAssert<>( - actual, - view, - IntoStaticWindows.of( - (Coder) actual.getWindowingStrategy().getWindowFn().windowCoder(), window), - paneExtractor, - coder); - } - - @Override - public PCollectionViewAssert isEqualTo(ViewT expectedValue) { - return satisfies(new AssertIsEqualToRelation(), expectedValue); - } - - @Override - public SingletonAssert is(ViewT expected) { - return isEqualTo(expected); - } - - @Override - public PCollectionViewAssert notEqualTo(ViewT expectedValue) { - return satisfies(new AssertNotEqualToRelation(), expectedValue); - } - - @Override - public PCollectionViewAssert satisfies( - SerializableFunction checkerFn) { - actual - .getPipeline() - .apply( - "DataflowAssert$" + (assertCount++), - new OneSideInputAssert( - CreateActual.from(actual, rewindowActuals, paneExtractor, view), - rewindowActuals.windowDummy(), - checkerFn)); - return this; - } - - /** - * Applies an {@link AssertRelation} to check the provided relation against the value of this - * assert and the provided expected value. - * - *

              Returns this {@code SingletonAssert}. - */ - private PCollectionViewAssert satisfies( - AssertRelation relation, final ViewT expectedValue) { - return satisfies(new CheckRelationAgainstExpected(relation, expectedValue, coder)); - } - - /** - * Always throws an {@link UnsupportedOperationException}: users are probably looking for - * {@link #isEqualTo}. - */ - @Deprecated - @Override - public boolean equals(Object o) { - throw new UnsupportedOperationException( - String.format( - "tests for Java equality of the %s object, not the PCollection in question. " - + "Call a test method, such as isEqualTo.", - getClass().getSimpleName())); - } - - /** - * @throws UnsupportedOperationException always. - * @deprecated {@link Object#hashCode()} is not supported on {@link DataflowAssert} objects. - */ - @Deprecated - @Override - public int hashCode() { - throw new UnsupportedOperationException( - String.format("%s.hashCode() is not supported.", SingletonAssert.class.getSimpleName())); - } - } - - //////////////////////////////////////////////////////////////////////// - - private static class CreateActual - extends PTransform> { - - private final transient PCollection actual; - private final transient AssertionWindows rewindowActuals; - private final transient SimpleFunction>, Iterable> extractPane; - private final transient PTransform, PCollectionView> actualView; - - public static CreateActual from( - PCollection actual, - AssertionWindows rewindowActuals, - SimpleFunction>, Iterable> extractPane, - PTransform, PCollectionView> actualView) { - return new CreateActual<>(actual, rewindowActuals, extractPane, actualView); - } - - private CreateActual( - PCollection actual, - AssertionWindows rewindowActuals, - SimpleFunction>, Iterable> extractPane, - PTransform, PCollectionView> actualView) { - this.actual = actual; - this.rewindowActuals = rewindowActuals; - this.extractPane = extractPane; - this.actualView = actualView; - } - - @Override - public PCollectionView apply(PBegin input) { - final Coder coder = actual.getCoder(); - return actual - .apply("FilterActuals", rewindowActuals.prepareActuals()) - .apply("GatherPanes", GatherAllPanes.globally()) - .apply("ExtractPane", MapElements.via(extractPane)) - .setCoder(IterableCoder.of(actual.getCoder())) - .apply(Flatten.iterables()) - .apply("RewindowActuals", rewindowActuals.windowActuals()) - .apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(ProcessContext context) throws CoderException { - context.output(CoderUtils.clone(coder, context.element())); - } - })) - .apply(actualView); - } - } - - /** - * A partially applied {@link AssertRelation}, where one value is provided along with a coder to - * serialize/deserialize them. - */ - private static class CheckRelationAgainstExpected implements SerializableFunction { - private final AssertRelation relation; - private final byte[] encodedExpected; - private final Coder coder; - - public CheckRelationAgainstExpected(AssertRelation relation, T expected, Coder coder) { - this.relation = relation; - this.coder = coder; - - try { - this.encodedExpected = CoderUtils.encodeToByteArray(coder, expected); - } catch (IOException coderException) { - throw new RuntimeException(coderException); - } - } - - @Override - public Void apply(T actual) { - try { - T expected = CoderUtils.decodeFromByteArray(coder, encodedExpected); - return relation.assertFor(expected).apply(actual); - } catch (IOException coderException) { - throw new RuntimeException(coderException); - } - } - } - - /** - * A transform that gathers the contents of a {@link PCollection} into a single main input - * iterable in the global window. This requires a runner to support {@link GroupByKey} in the - * global window, but not side inputs or other windowing or triggers. - * - *

              If the {@link PCollection} is empty, this transform returns a {@link PCollection} containing - * a single empty iterable, even though in practice most runners will not produce any element. - */ - private static class GroupGlobally - extends PTransform, PCollection>>> - implements Serializable { - private final AssertionWindows rewindowingStrategy; - - public GroupGlobally(AssertionWindows rewindowingStrategy) { - this.rewindowingStrategy = rewindowingStrategy; - } - - @Override - public PCollection>> apply(PCollection input) { - final int combinedKey = 42; - - // Remove the triggering on both - PTransform< - PCollection>>>, - PCollection>>>> - removeTriggering = - Window.>>>triggering(Never.ever()) - .discardingFiredPanes() - .withAllowedLateness(input.getWindowingStrategy().getAllowedLateness()); - // Group the contents by key. If it is empty, this PCollection will be empty, too. - // Then key it again with a dummy key. - PCollection>>> groupedContents = - // TODO: Split the filtering from the rewindowing, and apply filtering before the Gather - // if the grouping of extra records - input - .apply(rewindowingStrategy.prepareActuals()) - .apply("GatherAllOutputs", GatherAllPanes.globally()) - .apply( - "RewindowActuals", - rewindowingStrategy.>>windowActuals()) - .apply("KeyForDummy", WithKeys.>>of(combinedKey)) - .apply("RemoveActualsTriggering", removeTriggering); - - // Create another non-empty PCollection that is keyed with a distinct dummy key - PCollection>>> keyedDummy = - input - .getPipeline() - .apply( - Create.of( - KV.of( - combinedKey, - (Iterable>) - Collections.>emptyList())) - .withCoder(groupedContents.getCoder())) - .apply( - "WindowIntoDummy", - rewindowingStrategy.>>>windowDummy()) - .apply("RemoveDummyTriggering", removeTriggering); - - // Flatten them together and group by the combined key to get a single element - Bound>>> trigger = - Window.>>>triggering(Never.ever()) - .withAllowedLateness(input.getWindowingStrategy().getAllowedLateness()) - .discardingFiredPanes(); - PCollection>>>> dummyAndContents = - PCollectionList.of(groupedContents) - .and(keyedDummy) - .apply( - "FlattenDummyAndContents", - Flatten.>>>pCollections()) - .apply("NeverTrigger", trigger) - .apply( - "GroupDummyAndContents", - GroupByKey.>>create()); - - return dummyAndContents - .apply(Values.>>>create()) - .apply(ParDo.of(new ConcatFn>())); - } - } - - private static final class ConcatFn extends DoFn>, Iterable> { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(Iterables.concat(c.element())); - } - } - - /** - * A transform that applies an assertion-checking function over iterables of {@code ActualT} to - * the entirety of the contents of its input. - */ - public static class GroupThenAssert extends PTransform, PDone> - implements Serializable { - private final SerializableFunction, Void> checkerFn; - private final AssertionWindows rewindowingStrategy; - private final SimpleFunction>, Iterable> paneExtractor; - - private GroupThenAssert( - SerializableFunction, Void> checkerFn, - AssertionWindows rewindowingStrategy, - SimpleFunction>, Iterable> paneExtractor) { - this.checkerFn = checkerFn; - this.rewindowingStrategy = rewindowingStrategy; - this.paneExtractor = paneExtractor; - } - - @Override - public PDone apply(PCollection input) { - input - .apply("GroupGlobally", new GroupGlobally(rewindowingStrategy)) - .apply("GetPane", MapElements.via(paneExtractor)) - .setCoder(IterableCoder.of(input.getCoder())) - .apply("RunChecks", ParDo.of(new GroupedValuesCheckerDoFn<>(checkerFn))); - - return PDone.in(input.getPipeline()); - } - } - - /** - * A transform that applies an assertion-checking function to a single iterable contained as the - * sole element of a {@link PCollection}. - */ - public static class GroupThenAssertForSingleton - extends PTransform>, PDone> implements Serializable { - private final SerializableFunction, Void> checkerFn; - private final AssertionWindows rewindowingStrategy; - private final SimpleFunction>>, Iterable>> - paneExtractor; - - private GroupThenAssertForSingleton( - SerializableFunction, Void> checkerFn, - AssertionWindows rewindowingStrategy, - SimpleFunction>>, Iterable>> paneExtractor) { - this.checkerFn = checkerFn; - this.rewindowingStrategy = rewindowingStrategy; - this.paneExtractor = paneExtractor; - } - - @Override - public PDone apply(PCollection> input) { - input - .apply("GroupGlobally", new GroupGlobally>(rewindowingStrategy)) - .apply("GetPane", MapElements.via(paneExtractor)) - .setCoder(IterableCoder.of(input.getCoder())) - .apply("RunChecks", ParDo.of(new SingletonCheckerDoFn<>(checkerFn))); - - return PDone.in(input.getPipeline()); - } - } - - /** - * An assertion checker that takes a single {@link PCollectionView - * PCollectionView<ActualT>} and an assertion over {@code ActualT}, and checks it within a - * Beam pipeline. - * - *

              Note that the entire assertion must be serializable. - * - *

              This is generally useful for assertion functions that are serializable but whose underlying - * data may not have a coder. - */ - public static class OneSideInputAssert extends PTransform - implements Serializable { - private final transient PTransform> createActual; - private final transient PTransform, PCollection> windowToken; - private final SerializableFunction checkerFn; - - private OneSideInputAssert( - PTransform> createActual, - PTransform, PCollection> windowToken, - SerializableFunction checkerFn) { - this.createActual = createActual; - this.windowToken = windowToken; - this.checkerFn = checkerFn; - } - - @Override - public PDone apply(PBegin input) { - final PCollectionView actual = input.apply("CreateActual", createActual); - - input - .apply(Create.of(0).withCoder(VarIntCoder.of())) - .apply("WindowToken", windowToken) - .apply( - "RunChecks", - ParDo.withSideInputs(actual).of(new SideInputCheckerDoFn<>(checkerFn, actual))); - - return PDone.in(input.getPipeline()); - } - } - - /** - * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of a - * {@link PCollectionView}, and adjusts counters and thrown exceptions for use in testing. - * - *

              The input is ignored, but is {@link Integer} to be usable on runners that do not support - * null values. - */ - private static class SideInputCheckerDoFn extends DoFn { - private final SerializableFunction checkerFn; - private final Aggregator success = - createAggregator(SUCCESS_COUNTER, new Sum.SumIntegerFn()); - private final Aggregator failure = - createAggregator(FAILURE_COUNTER, new Sum.SumIntegerFn()); - private final PCollectionView actual; - - private SideInputCheckerDoFn( - SerializableFunction checkerFn, PCollectionView actual) { - this.checkerFn = checkerFn; - this.actual = actual; - } - - @Override - public void processElement(ProcessContext c) { - try { - ActualT actualContents = c.sideInput(actual); - doChecks(actualContents, checkerFn, success, failure); - } catch (Throwable t) { - // Suppress exception in streaming - if (!c.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { - throw t; - } - } - } - } - - /** - * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of - * the single iterable element of the input {@link PCollection} and adjusts counters and - * thrown exceptions for use in testing. - * - *

              The singleton property is presumed, not enforced. - */ - private static class GroupedValuesCheckerDoFn extends DoFn { - private final SerializableFunction checkerFn; - private final Aggregator success = - createAggregator(SUCCESS_COUNTER, new Sum.SumIntegerFn()); - private final Aggregator failure = - createAggregator(FAILURE_COUNTER, new Sum.SumIntegerFn()); - - private GroupedValuesCheckerDoFn(SerializableFunction checkerFn) { - this.checkerFn = checkerFn; - } - - @Override - public void processElement(ProcessContext c) { - try { - doChecks(c.element(), checkerFn, success, failure); - } catch (Throwable t) { - // Suppress exception in streaming - if (!c.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { - throw t; - } - } - } - } - - /** - * A {@link DoFn} that runs a checking {@link SerializableFunction} on the contents of - * the single item contained within the single iterable on input and - * adjusts counters and thrown exceptions for use in testing. - * - *

              The singleton property of the input {@link PCollection} is presumed, not enforced. However, - * each input element must be a singleton iterable, or this will fail. - */ - private static class SingletonCheckerDoFn extends DoFn, Void> { - private final SerializableFunction checkerFn; - private final Aggregator success = - createAggregator(SUCCESS_COUNTER, new Sum.SumIntegerFn()); - private final Aggregator failure = - createAggregator(FAILURE_COUNTER, new Sum.SumIntegerFn()); - - private SingletonCheckerDoFn(SerializableFunction checkerFn) { - this.checkerFn = checkerFn; - } - - @Override - public void processElement(ProcessContext c) { - try { - ActualT actualContents = Iterables.getOnlyElement(c.element()); - doChecks(actualContents, checkerFn, success, failure); - } catch (Throwable t) { - // Suppress exception in streaming - if (!c.getPipelineOptions().as(StreamingOptions.class).isStreaming()) { - throw t; - } - } - } - } - - private static void doChecks( - ActualT actualContents, - SerializableFunction checkerFn, - Aggregator successAggregator, - Aggregator failureAggregator) { - try { - checkerFn.apply(actualContents); - successAggregator.addValue(1); - } catch (Throwable t) { - LOG.error("DataflowAssert failed expectations.", t); - failureAggregator.addValue(1); - throw t; - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@link SerializableFunction} that verifies that an actual value is equal to an expected - * value. - */ - private static class AssertIsEqualTo implements SerializableFunction { - private T expected; - - public AssertIsEqualTo(T expected) { - this.expected = expected; - } - - @Override - public Void apply(T actual) { - assertThat(actual, equalTo(expected)); - return null; - } - } - - /** - * A {@link SerializableFunction} that verifies that an actual value is not equal to an expected - * value. - */ - private static class AssertNotEqualTo implements SerializableFunction { - private T expected; - - public AssertNotEqualTo(T expected) { - this.expected = expected; - } - - @Override - public Void apply(T actual) { - assertThat(actual, not(equalTo(expected))); - return null; - } - } - - /** - * A {@link SerializableFunction} that verifies that an {@code Iterable} contains expected items - * in any order. - */ - private static class AssertContainsInAnyOrder - implements SerializableFunction, Void> { - private T[] expected; - - @SafeVarargs - public AssertContainsInAnyOrder(T... expected) { - this.expected = expected; - } - - @SuppressWarnings("unchecked") - public AssertContainsInAnyOrder(Collection expected) { - this((T[]) expected.toArray()); - } - - public AssertContainsInAnyOrder(Iterable expected) { - this(Lists.newArrayList(expected)); - } - - @Override - public Void apply(Iterable actual) { - assertThat(actual, containsInAnyOrder(expected)); - return null; - } - } - - //////////////////////////////////////////////////////////// - - /** - * A binary predicate between types {@code Actual} and {@code Expected}. Implemented as a method - * {@code assertFor(Expected)} which returns a {@code SerializableFunction} that - * should verify the assertion.. - */ - private interface AssertRelation extends Serializable { - SerializableFunction assertFor(ExpectedT input); - } - - /** - * An {@link AssertRelation} implementing the binary predicate that two objects are equal. - */ - private static class AssertIsEqualToRelation implements AssertRelation { - @Override - public SerializableFunction assertFor(T expected) { - return new AssertIsEqualTo(expected); - } - } - - /** - * An {@link AssertRelation} implementing the binary predicate that two objects are not equal. - */ - private static class AssertNotEqualToRelation implements AssertRelation { - @Override - public SerializableFunction assertFor(T expected) { - return new AssertNotEqualTo(expected); - } - } - - /** - * An {@code AssertRelation} implementing the binary predicate that two collections are equal - * modulo reordering. - */ - private static class AssertContainsInAnyOrderRelation - implements AssertRelation, Iterable> { - @Override - public SerializableFunction, Void> assertFor(Iterable expectedElements) { - return new AssertContainsInAnyOrder(expectedElements); - } - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * A strategy for filtering and rewindowing the actual and dummy {@link PCollection PCollections} - * within a {@link DataflowAssert}. - * - *

              This must ensure that the windowing strategies of the output of {@link #windowActuals()} and - * {@link #windowDummy()} are compatible (and can be {@link Flatten Flattened}). - * - *

              The {@link PCollection} produced by {@link #prepareActuals()} will be a parent (though not - * a direct parent) of the transform provided to {@link #windowActuals()}. - */ - private interface AssertionWindows { - /** - * Returns a transform that assigns the dummy element into the appropriate - * {@link BoundedWindow windows}. - */ - PTransform, PCollection> windowDummy(); - - /** - * Returns a transform that filters and reassigns windows of the actual elements if necessary. - */ - PTransform, PCollection> prepareActuals(); - - /** - * Returns a transform that assigns the actual elements into the appropriate - * {@link BoundedWindow windows}. Will be called after {@link #prepareActuals()}. - */ - PTransform, PCollection> windowActuals(); - } - - /** - * An {@link AssertionWindows} which assigns all elements to the {@link GlobalWindow}. - */ - private static class IntoGlobalWindow implements AssertionWindows, Serializable { - public static AssertionWindows of() { - return new IntoGlobalWindow(); - } - - private PTransform, PCollection> window() { - return Window.into(new GlobalWindows()); - } - - @Override - public PTransform, PCollection> windowDummy() { - return window(); - } - - /** - * Rewindows all input elements into the {@link GlobalWindow}. This ensures that the result - * PCollection will contain all of the elements of the PCollection when the window is not - * specified. - */ - @Override - public PTransform, PCollection> prepareActuals() { - return window(); - } - - @Override - public PTransform, PCollection> windowActuals() { - return window(); - } - } - - private static class IntoStaticWindows implements AssertionWindows { - private final StaticWindows windowFn; - - public static AssertionWindows of(Coder windowCoder, BoundedWindow window) { - return new IntoStaticWindows(StaticWindows.of(windowCoder, window)); - } - - private IntoStaticWindows(StaticWindows windowFn) { - this.windowFn = windowFn; - } - - @Override - public PTransform, PCollection> windowDummy() { - return Window.into(windowFn); - } - - @Override - public PTransform, PCollection> prepareActuals() { - return new FilterWindows<>(windowFn); - } - - @Override - public PTransform, PCollection> windowActuals() { - return Window.into(windowFn.intoOnlyExisting()); - } - } - - /** - * A DoFn that filters elements based on their presence in a static collection of windows. - */ - private static final class FilterWindows extends PTransform, PCollection> { - private final StaticWindows windows; - - public FilterWindows(StaticWindows windows) { - this.windows = windows; - } - - @Override - public PCollection apply(PCollection input) { - return input.apply("FilterWindows", ParDo.of(new Fn())); - } - - private class Fn extends DoFn implements RequiresWindowAccess { - @Override - public void processElement(ProcessContext c) throws Exception { - if (windows.getWindows().contains(c.window())) { - c.output(c.element()); - } - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java deleted file mode 100644 index 700f035315..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/PaneExtractors.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link PTransform PTransforms} which take an {@link Iterable} of {@link WindowedValue - * WindowedValues} and outputs an {@link Iterable} of all values in the specified pane, dropping the - * {@link WindowedValue} metadata. - * - *

              Although all of the method signatures return SimpleFunction, users should ensure to set the - * coder of any output {@link PCollection}, as appropriate {@link TypeDescriptor TypeDescriptors} - * cannot be obtained when the extractor is created. - */ -final class PaneExtractors { - private PaneExtractors() { - } - - static SimpleFunction>, Iterable> onlyPane() { - return new ExtractOnlyPane<>(); - } - - static SimpleFunction>, Iterable> onTimePane() { - return new ExtractOnTimePane<>(); - } - - static SimpleFunction>, Iterable> finalPane() { - return new ExtractFinalPane<>(); - } - - static SimpleFunction>, Iterable> nonLatePanes() { - return new ExtractNonLatePanes<>(); - } - - static SimpleFunction>, Iterable> earlyPanes() { - return new ExtractEarlyPanes<>(); - } - - static SimpleFunction>, Iterable> allPanes() { - return new ExtractAllPanes<>(); - } - - private static class ExtractOnlyPane - extends SimpleFunction>, Iterable> { - @Override - public Iterable apply(Iterable> input) { - List outputs = new ArrayList<>(); - for (WindowedValue value : input) { - checkState(value.getPane().isFirst() && value.getPane().isLast(), - "Expected elements to be produced by a trigger that fires at most once, but got" - + "a value in a pane that is %s. Actual Pane Info: %s", - value.getPane().isFirst() ? "not the last pane" : "not the first pane", - value.getPane()); - outputs.add(value.getValue()); - } - return outputs; - } - } - - - private static class ExtractOnTimePane - extends SimpleFunction>, Iterable> { - @Override - public Iterable apply(Iterable> input) { - List outputs = new ArrayList<>(); - for (WindowedValue value : input) { - if (value.getPane().getTiming().equals(Timing.ON_TIME)) { - outputs.add(value.getValue()); - } - } - return outputs; - } - } - - - private static class ExtractFinalPane - extends SimpleFunction>, Iterable> { - @Override - public Iterable apply(Iterable> input) { - List outputs = new ArrayList<>(); - for (WindowedValue value : input) { - if (value.getPane().isLast()) { - outputs.add(value.getValue()); - } - } - return outputs; - } - } - - - private static class ExtractAllPanes - extends SimpleFunction>, Iterable> { - @Override - public Iterable apply(Iterable> input) { - List outputs = new ArrayList<>(); - for (WindowedValue value : input) { - outputs.add(value.getValue()); - } - return outputs; - } - } - - - private static class ExtractNonLatePanes - extends SimpleFunction>, Iterable> { - @Override - public Iterable apply(Iterable> input) { - List outputs = new ArrayList<>(); - for (WindowedValue value : input) { - if (value.getPane().getTiming() != PaneInfo.Timing.LATE) { - outputs.add(value.getValue()); - } - } - return outputs; - } - } - - private static class ExtractEarlyPanes - extends SimpleFunction>, Iterable> { - @Override - public Iterable apply(Iterable> input) { - List outputs = new ArrayList<>(); - for (WindowedValue value : input) { - if (value.getPane().getTiming() == PaneInfo.Timing.EARLY) { - outputs.add(value.getValue()); - } - } - return outputs; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/RunnableOnService.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/RunnableOnService.java deleted file mode 100644 index 60ab2e51b6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/RunnableOnService.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -/** - * Category tag for tests that can be run on the - * {@link com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner} if the - * {@code runIntegrationTestOnService} System property is set to true. - * Example usage: - *

              
              - *     {@literal @}Test
              - *     {@literal @}Category(RunnableOnService.class)
              - *     public void testParDo() {...
              - * 
              - */ -public interface RunnableOnService {} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatcher.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatcher.java deleted file mode 100644 index 10f221e347..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatcher.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import org.hamcrest.Matcher; - -import java.io.Serializable; - -/** - * A {@link Matcher} that is also {@link Serializable}. - * - *

              Such matchers can be used with {@link DataflowAssert}, which builds Dataflow pipelines - * such that these matchers may be serialized and executed remotely. - * - *

              To create a {@code SerializableMatcher}, extend {@link org.hamcrest.BaseMatcher} - * and also implement this interface. - * - * @param The type of value matched. - */ -interface SerializableMatcher extends Matcher, Serializable { -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java deleted file mode 100644 index 85b1d5b072..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchers.java +++ /dev/null @@ -1,1179 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.MoreObjects; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Static class for building and using {@link SerializableMatcher} instances. - * - *

              Most matchers are wrappers for hamcrest's {@link Matchers}. Please be familiar with the - * documentation there. Values retained by a {@link SerializableMatcher} are required to be - * serializable, either via Java serialization or via a provided {@link Coder}. - * - *

              The following matchers are novel to Dataflow: - *

                - *
              • {@link #kvWithKey} for matching just the key of a {@link KV}. - *
              • {@link #kvWithValue} for matching just the value of a {@link KV}. - *
              • {@link #kv} for matching the key and value of a {@link KV}. - *
              - * - *

              For example, to match a group from - * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}, which has type - * {@code KV>} for some {@code K} and {@code V} and where the order of the iterable - * is undefined, use a matcher like - * {@code kv(equalTo("some key"), containsInAnyOrder(1, 2, 3))}. - */ -class SerializableMatchers implements Serializable { - - // Serializable only because of capture by anonymous inner classes - private SerializableMatchers() { } // not instantiable - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#allOf(Iterable)}. - */ - public static SerializableMatcher - allOf(Iterable> serializableMatchers) { - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe covariant cast - final Iterable> matchers = (Iterable) serializableMatchers; - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.allOf(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#allOf(Matcher[])}. - */ - @SafeVarargs - public static SerializableMatcher allOf(final SerializableMatcher... matchers) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.allOf(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#anyOf(Iterable)}. - */ - public static SerializableMatcher - anyOf(Iterable> serializableMatchers) { - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe covariant cast - final Iterable> matchers = (Iterable) serializableMatchers; - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.anyOf(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#anyOf(Matcher[])}. - */ - @SafeVarargs - public static SerializableMatcher anyOf(final SerializableMatcher... matchers) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.anyOf(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#anything()}. - */ - public static SerializableMatcher anything() { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.anything(); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContaining(Object[])}. - */ - @SafeVarargs - public static SerializableMatcher - arrayContaining(final T... items) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContaining(items); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContaining(Object[])}. - * - *

              The items of type {@code T} will be serialized using the provided {@link Coder}. They are - * explicitly not required or expected to be serializable via Java serialization. - */ - @SafeVarargs - public static SerializableMatcher arrayContaining(Coder coder, T... items) { - - final SerializableSupplier itemsSupplier = - new SerializableArrayViaCoder<>(coder, items); - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContaining(itemsSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContaining(Matcher[])}. - */ - @SafeVarargs - public static SerializableMatcher - arrayContaining(final SerializableMatcher... matchers) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContaining(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContaining(List)}. - */ - public static SerializableMatcher - arrayContaining(List> serializableMatchers) { - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe covariant cast - final List> matchers = (List) serializableMatchers; - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContaining(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContainingInAnyOrder(Object[])}. - */ - @SafeVarargs - public static SerializableMatcher - arrayContainingInAnyOrder(final T... items) { - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContainingInAnyOrder(items); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContainingInAnyOrder(Object[])}. - * - *

              The items of type {@code T} will be serialized using the provided {@link Coder}. They are - * explicitly not required or expected to be serializable via Java serialization. - */ - @SafeVarargs - public static SerializableMatcher arrayContainingInAnyOrder(Coder coder, T... items) { - - final SerializableSupplier itemsSupplier = - new SerializableArrayViaCoder<>(coder, items); - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContaining(itemsSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContainingInAnyOrder(Matcher[])}. - */ - @SafeVarargs - public static SerializableMatcher arrayContainingInAnyOrder( - final SerializableMatcher... matchers) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContainingInAnyOrder(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayContainingInAnyOrder(Collection)}. - */ - public static SerializableMatcher arrayContainingInAnyOrder( - Collection> serializableMatchers) { - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe covariant cast - final Collection> matchers = (Collection) serializableMatchers; - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayContainingInAnyOrder(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayWithSize(int)}. - */ - public static SerializableMatcher arrayWithSize(final int size) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayWithSize(size); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#arrayWithSize(Matcher)}. - */ - public static SerializableMatcher arrayWithSize( - final SerializableMatcher sizeMatcher) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.arrayWithSize(sizeMatcher); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#closeTo(double,double)}. - */ - public static SerializableMatcher closeTo(final double target, final double error) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.closeTo(target, error); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#contains(Object[])}. - */ - @SafeVarargs - public static SerializableMatcher> contains( - final T... items) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.contains(items); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#contains(Object[])}. - * - *

              The items of type {@code T} will be serialized using the provided {@link Coder}. They are - * explicitly not required or expected to be serializable via Java serialization. - */ - @SafeVarargs - public static SerializableMatcher> - contains(Coder coder, T... items) { - - final SerializableSupplier itemsSupplier = - new SerializableArrayViaCoder<>(coder, items); - - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.containsInAnyOrder(itemsSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#contains(Matcher[])}. - */ - @SafeVarargs - public static SerializableMatcher> contains( - final SerializableMatcher... matchers) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.contains(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#contains(List)}. - */ - public static SerializableMatcher> contains( - List> serializableMatchers) { - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe covariant cast - final List> matchers = (List) serializableMatchers; - - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.contains(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#containsInAnyOrder(Object[])}. - */ - @SafeVarargs - public static SerializableMatcher> - containsInAnyOrder(final T... items) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.containsInAnyOrder(items); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#containsInAnyOrder(Object[])}. - * - *

              The items of type {@code T} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - @SafeVarargs - public static SerializableMatcher> - containsInAnyOrder(Coder coder, T... items) { - - final SerializableSupplier itemsSupplier = - new SerializableArrayViaCoder<>(coder, items); - - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.containsInAnyOrder(itemsSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#containsInAnyOrder(Matcher[])}. - */ - @SafeVarargs - public static SerializableMatcher> containsInAnyOrder( - final SerializableMatcher... matchers) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.containsInAnyOrder(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#containsInAnyOrder(Collection)}. - */ - public static SerializableMatcher> containsInAnyOrder( - Collection> serializableMatchers) { - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe covariant cast - final Collection> matchers = (Collection) serializableMatchers; - - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.containsInAnyOrder(matchers); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#containsString}. - */ - public static SerializableMatcher containsString(final String substring) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.containsString(substring); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#empty()}. - */ - public static SerializableMatcher> empty() { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.empty(); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#emptyArray()}. - */ - public static SerializableMatcher emptyArray() { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.emptyArray(); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#emptyIterable()}. - */ - public static SerializableMatcher> emptyIterable() { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.emptyIterable(); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#endsWith}. - */ - public static SerializableMatcher endsWith(final String substring) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.endsWith(substring); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#equalTo()}. - */ - public static SerializableMatcher equalTo(final T expected) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.equalTo(expected); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#equalTo()}. - * - *

              The expected value of type {@code T} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static SerializableMatcher equalTo(Coder coder, T expected) { - - final SerializableSupplier expectedSupplier = new SerializableViaCoder<>(coder, expected); - - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.equalTo(expectedSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#greaterThan()}. - */ - public static & Serializable> SerializableMatcher - greaterThan(final T target) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.greaterThan(target); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#greaterThan()}. - * - *

              The target value of type {@code T} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static & Serializable> SerializableMatcher - greaterThan(final Coder coder, T target) { - final SerializableSupplier targetSupplier = new SerializableViaCoder<>(coder, target); - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.greaterThan(targetSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#greaterThanOrEqualTo()}. - */ - public static > SerializableMatcher greaterThanOrEqualTo( - final T target) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.greaterThanOrEqualTo(target); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#greaterThanOrEqualTo()}. - * - *

              The target value of type {@code T} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static & Serializable> SerializableMatcher - greaterThanOrEqualTo(final Coder coder, T target) { - final SerializableSupplier targetSupplier = new SerializableViaCoder<>(coder, target); - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.greaterThanOrEqualTo(targetSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#hasItem(Object)}. - */ - public static SerializableMatcher> hasItem( - final T target) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.hasItem(target); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#hasItem(Object)}. - * - *

              The item of type {@code T} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static SerializableMatcher> hasItem(Coder coder, T target) { - final SerializableSupplier targetSupplier = new SerializableViaCoder<>(coder, target); - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.hasItem(targetSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#hasItem(Matcher)}. - */ - public static SerializableMatcher> hasItem( - final SerializableMatcher matcher) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.hasItem(matcher); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#hasSize(int)}. - */ - public static SerializableMatcher> hasSize(final int size) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.hasSize(size); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#hasSize(Matcher)}. - */ - public static SerializableMatcher> hasSize( - final SerializableMatcher sizeMatcher) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.hasSize(sizeMatcher); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#iterableWithSize(int)}. - */ - public static SerializableMatcher> iterableWithSize(final int size) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.iterableWithSize(size); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#iterableWithSize(Matcher)}. - */ - public static SerializableMatcher> iterableWithSize( - final SerializableMatcher sizeMatcher) { - return fromSupplier(new SerializableSupplier>>() { - @Override - public Matcher> get() { - return Matchers.iterableWithSize(sizeMatcher); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#isIn(Collection)}. - */ - public static SerializableMatcher - isIn(final Collection collection) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.isIn(collection); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#isIn(Collection)}. - * - *

              The items of type {@code T} will be serialized using the provided {@link Coder}. - * They are explicitly not required or expected to be serializable via Java serialization. - */ - public static SerializableMatcher isIn(Coder coder, Collection collection) { - @SuppressWarnings("unchecked") - T[] items = (T[]) collection.toArray(); - final SerializableSupplier itemsSupplier = - new SerializableArrayViaCoder<>(coder, items); - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.isIn(itemsSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#isIn(Object[])}. - */ - public static SerializableMatcher isIn(final T[] items) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.isIn(items); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#isIn(Object[])}. - * - *

              The items of type {@code T} will be serialized using the provided {@link Coder}. - * They are explicitly not required or expected to be serializable via Java serialization. - */ - public static SerializableMatcher isIn(Coder coder, T[] items) { - final SerializableSupplier itemsSupplier = - new SerializableArrayViaCoder<>(coder, items); - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.isIn(itemsSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#isOneOf}. - */ - @SafeVarargs - public static SerializableMatcher isOneOf(final T... elems) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.isOneOf(elems); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#isOneOf}. - * - *

              The items of type {@code T} will be serialized using the provided {@link Coder}. - * They are explicitly not required or expected to be serializable via Java serialization. - */ - @SafeVarargs - public static SerializableMatcher isOneOf(Coder coder, T... items) { - final SerializableSupplier itemsSupplier = - new SerializableArrayViaCoder<>(coder, items); - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.isOneOf(itemsSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} that matches any {@link KV} with the specified key. - */ - public static SerializableMatcher> - kvWithKey(K key) { - return new KvKeyMatcher(equalTo(key)); - } - - /** - * A {@link SerializableMatcher} that matches any {@link KV} with the specified key. - * - *

              The key of type {@code K} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static SerializableMatcher> - kvWithKey(Coder coder, K key) { - return new KvKeyMatcher(equalTo(coder, key)); - } - - /** - * A {@link SerializableMatcher} that matches any {@link KV} with matching key. - */ - public static SerializableMatcher> kvWithKey( - final SerializableMatcher keyMatcher) { - return new KvKeyMatcher(keyMatcher); - } - - /** - * A {@link SerializableMatcher} that matches any {@link KV} with the specified value. - */ - public static SerializableMatcher> - kvWithValue(V value) { - return new KvValueMatcher(equalTo(value)); - } - - /** - * A {@link SerializableMatcher} that matches any {@link KV} with the specified value. - * - *

              The value of type {@code V} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static SerializableMatcher> - kvWithValue(Coder coder, V value) { - return new KvValueMatcher(equalTo(coder, value)); - } - - /** - * A {@link SerializableMatcher} that matches any {@link KV} with matching value. - */ - public static SerializableMatcher> kvWithValue( - final SerializableMatcher valueMatcher) { - return new KvValueMatcher<>(valueMatcher); - } - - /** - * A {@link SerializableMatcher} that matches any {@link KV} with matching key and value. - */ - public static SerializableMatcher> kv( - final SerializableMatcher keyMatcher, - final SerializableMatcher valueMatcher) { - - return SerializableMatchers.>allOf( - SerializableMatchers.kvWithKey(keyMatcher), - SerializableMatchers.kvWithValue(valueMatcher)); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#lessThan()}. - */ - public static & Serializable> SerializableMatcher lessThan( - final T target) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.lessThan(target); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#lessThan()}. - * - *

              The target value of type {@code T} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static > SerializableMatcher - lessThan(Coder coder, T target) { - final SerializableSupplier targetSupplier = new SerializableViaCoder<>(coder, target); - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.lessThan(targetSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#lessThanOrEqualTo()}. - */ - public static & Serializable> SerializableMatcher lessThanOrEqualTo( - final T target) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.lessThanOrEqualTo(target); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#lessThanOrEqualTo()}. - * - *

              The target value of type {@code T} will be serialized using the provided {@link Coder}. - * It is explicitly not required or expected to be serializable via Java serialization. - */ - public static > SerializableMatcher lessThanOrEqualTo( - Coder coder, T target) { - final SerializableSupplier targetSupplier = new SerializableViaCoder<>(coder, target); - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.lessThanOrEqualTo(targetSupplier.get()); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#not}. - */ - public static SerializableMatcher not(final SerializableMatcher matcher) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.not(matcher); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to - * {@link Matchers#nullValue}. - */ - public static SerializableMatcher nullValue() { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.nullValue(); - } - }); - } - - /** - * A {@link SerializableMatcher} with identical criteria to {@link Matchers#startsWith}. - */ - public static SerializableMatcher startsWith(final String substring) { - return fromSupplier(new SerializableSupplier>() { - @Override - public Matcher get() { - return Matchers.startsWith(substring); - } - }); - } - - private static class KvKeyMatcher - extends BaseMatcher> - implements SerializableMatcher> { - private final SerializableMatcher keyMatcher; - - public KvKeyMatcher(SerializableMatcher keyMatcher) { - this.keyMatcher = keyMatcher; - } - - @Override - public boolean matches(Object item) { - @SuppressWarnings("unchecked") - KV kvItem = (KV) item; - return keyMatcher.matches(kvItem.getKey()); - } - - @Override - public void describeMismatch(Object item, Description mismatchDescription) { - @SuppressWarnings("unchecked") - KV kvItem = (KV) item; - if (!keyMatcher.matches(kvItem.getKey())) { - mismatchDescription.appendText("key did not match: "); - keyMatcher.describeMismatch(kvItem.getKey(), mismatchDescription); - } - } - - @Override - public void describeTo(Description description) { - description.appendText("KV with key matching "); - keyMatcher.describeTo(description); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .addValue(keyMatcher) - .toString(); - } - } - - private static class KvValueMatcher - extends BaseMatcher> - implements SerializableMatcher> { - private final SerializableMatcher valueMatcher; - - public KvValueMatcher(SerializableMatcher valueMatcher) { - this.valueMatcher = valueMatcher; - } - - @Override - public boolean matches(Object item) { - @SuppressWarnings("unchecked") - KV kvItem = (KV) item; - return valueMatcher.matches(kvItem.getValue()); - } - - @Override - public void describeMismatch(Object item, Description mismatchDescription) { - @SuppressWarnings("unchecked") - KV kvItem = (KV) item; - if (!valueMatcher.matches(kvItem.getValue())) { - mismatchDescription.appendText("value did not match: "); - valueMatcher.describeMismatch(kvItem.getValue(), mismatchDescription); - } - } - - @Override - public void describeTo(Description description) { - description.appendText("KV with value matching "); - valueMatcher.describeTo(description); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .addValue(valueMatcher) - .toString(); - } - } - - /** - * Constructs a {@link SerializableMatcher} from a non-serializable {@link Matcher} via - * indirection through {@link SerializableSupplier}. - * - *

              To wrap a {@link Matcher} which is not serializable, provide a {@link SerializableSupplier} - * with a {@link SerializableSupplier#get()} method that returns a fresh instance of the - * {@link Matcher} desired. The resulting {@link SerializableMatcher} will behave according to - * the {@link Matcher} returned by {@link SerializableSupplier#get() get()} when it is invoked - * during matching (which may occur on another machine, such as a Dataflow worker). - * - *

              {@code
              -   * return fromSupplier(new SerializableSupplier>() {
              -   *     public Matcher get() {
              -   *       return new MyMatcherForT();
              -   *     }
              -   * });
              -   * }
              - */ - public static SerializableMatcher fromSupplier( - SerializableSupplier> supplier) { - return new SerializableMatcherFromSupplier<>(supplier); - } - - /** - * Supplies values of type {@code T}, and is serializable. Thus, even if {@code T} is not - * serializable, the supplier can be serialized and provide a {@code T} wherever it is - * deserialized. - * - * @param the type of value supplied. - */ - public interface SerializableSupplier extends Serializable { - T get(); - } - - /** - * Since the delegate {@link Matcher} is not generally serializable, instead this takes a nullary - * SerializableFunction to return such a matcher. - */ - private static class SerializableMatcherFromSupplier extends BaseMatcher - implements SerializableMatcher { - - private SerializableSupplier> supplier; - - public SerializableMatcherFromSupplier(SerializableSupplier> supplier) { - this.supplier = supplier; - } - - @Override - public void describeTo(Description description) { - supplier.get().describeTo(description); - } - - @Override - public boolean matches(Object item) { - return supplier.get().matches(item); - } - - @Override - public void describeMismatch(Object item, Description mismatchDescription) { - supplier.get().describeMismatch(item, mismatchDescription); - } - } - - /** - * Wraps any value that can be encoded via a {@link Coder} to make it {@link Serializable}. - * This is not likely to be a good encoding, so should be used only for tests, where data - * volume is small and minor costs are not critical. - */ - private static class SerializableViaCoder implements SerializableSupplier { - /** Cached value that is not serialized. */ - @Nullable - private transient T value; - - /** The bytes of {@link #value} when encoded via {@link #coder}. */ - private byte[] encodedValue; - - private Coder coder; - - public SerializableViaCoder(Coder coder, T value) { - this.coder = coder; - this.value = value; - try { - this.encodedValue = CoderUtils.encodeToByteArray(coder, value); - } catch (CoderException exc) { - throw new RuntimeException("Error serializing via Coder", exc); - } - } - - @Override - public T get() { - if (value == null) { - try { - value = CoderUtils.decodeFromByteArray(coder, encodedValue); - } catch (CoderException exc) { - throw new RuntimeException("Error deserializing via Coder", exc); - } - } - return value; - } - } - - /** - * Wraps any array with values that can be encoded via a {@link Coder} to make it - * {@link Serializable}. This is not likely to be a good encoding, so should be used only for - * tests, where data volume is small and minor costs are not critical. - */ - private static class SerializableArrayViaCoder implements SerializableSupplier { - /** Cached value that is not serialized. */ - @Nullable - private transient T[] value; - - /** The bytes of {@link #value} when encoded via {@link #coder}. */ - private byte[] encodedValue; - - private Coder> coder; - - public SerializableArrayViaCoder(Coder elementCoder, T[] value) { - this.coder = ListCoder.of(elementCoder); - this.value = value; - try { - this.encodedValue = CoderUtils.encodeToByteArray(coder, Arrays.asList(value)); - } catch (CoderException exc) { - throw UserCodeException.wrap(exc); - } - } - - @Override - public T[] get() { - if (value == null) { - try { - @SuppressWarnings("unchecked") - T[] decoded = (T[]) CoderUtils.decodeFromByteArray(coder, encodedValue).toArray(); - value = decoded; - } catch (CoderException exc) { - throw new RuntimeException("Error deserializing via Coder", exc); - } - } - return value; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java deleted file mode 100644 index 8dbc600b8f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtils.java +++ /dev/null @@ -1,806 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static com.google.common.base.Preconditions.checkNotNull; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.Source; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import javax.annotation.Nullable; - -/** - * Helper functions and test harnesses for checking correctness of {@link Source} - * implementations. - * - *

              Contains a few lightweight utilities (e.g. reading items from a source or a reader, - * such as {@link #readFromSource} and {@link #readFromUnstartedReader}), as well as - * heavyweight property testing and stress testing harnesses that help getting a large - * amount of test coverage with few code. Most notable ones are: - *

                - *
              • {@link #assertSourcesEqualReferenceSource} helps testing that the data read - * by the union of sources produced by {@link BoundedSource#splitIntoBundles} - * is the same as data read by the original source. - *
              • If your source implements dynamic work rebalancing, use the - * {@code assertSplitAtFraction} family of functions - they test behavior of - * {@link BoundedSource.BoundedReader#splitAtFraction}, in particular, that - * various consistency properties are respected and the total set of data read - * by the source is preserved when splits happen. - * Use {@link #assertSplitAtFractionBehavior} to test individual cases - * of {@code splitAtFraction} and use {@link #assertSplitAtFractionExhaustive} - * as a heavy-weight stress test including concurrency. We strongly recommend to - * use both. - *
              - * For example usages, see the unit tests of classes such as - * {@link com.google.cloud.dataflow.sdk.io.AvroSource} or - * {@link com.google.cloud.dataflow.sdk.io.XmlSource}. - * - *

              Like {@link DataflowAssert}, requires JUnit and Hamcrest to be present in the classpath. - */ -public class SourceTestUtils { - private static final Logger LOG = LoggerFactory.getLogger(SourceTestUtils.class); - - // A wrapper around a value of type T that compares according to the structural - // value provided by a Coder, but prints both the original and structural value, - // to help get good error messages from JUnit equality assertion failures and such. - private static class ReadableStructuralValue { - private T originalValue; - private Object structuralValue; - - public ReadableStructuralValue(T originalValue, Object structuralValue) { - this.originalValue = originalValue; - this.structuralValue = structuralValue; - } - - @Override - public int hashCode() { - return Objects.hashCode(structuralValue); - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof ReadableStructuralValue)) { - return false; - } - return Objects.equals(structuralValue, ((ReadableStructuralValue) obj).structuralValue); - } - - @Override - public String toString() { - return String.format("[%s (structural %s)]", originalValue, structuralValue); - } - } - - /** - * Testing utilities below depend on standard assertions and matchers to compare elements read by - * sources. In general the elements may not implement {@code equals}/{@code hashCode} properly, - * however every source has a {@link Coder} and every {@code Coder} can - * produce a {@link Coder#structuralValue} whose {@code equals}/{@code hashCode} is - * consistent with equality of encoded format. - * So we use this {@link Coder#structuralValue} to compare elements read by sources. - */ - public static List> createStructuralValues( - Coder coder, List list) - throws Exception { - List> result = new ArrayList<>(); - for (T elem : list) { - result.add(new ReadableStructuralValue<>(elem, coder.structuralValue(elem))); - } - return result; - } - - /** - * Reads all elements from the given {@link BoundedSource}. - */ - public static List readFromSource(BoundedSource source, PipelineOptions options) - throws IOException { - try (BoundedSource.BoundedReader reader = source.createReader(options)) { - return readFromUnstartedReader(reader); - } - } - - /** - * Reads all elements from the given unstarted {@link Source.Reader}. - */ - public static List readFromUnstartedReader(Source.Reader reader) throws IOException { - return readRemainingFromReader(reader, false); - } - - /** - * Reads all elements from the given started {@link Source.Reader}. - */ - public static List readFromStartedReader(Source.Reader reader) throws IOException { - return readRemainingFromReader(reader, true); - } - - /** - * Read elements from a {@link Source.Reader} until n elements are read. - */ - public static List readNItemsFromUnstartedReader(Source.Reader reader, int n) - throws IOException { - return readNItemsFromReader(reader, n, false); - } - - /** - * Read elements from a {@link Source.Reader} that has already had {@link Source.Reader#start} - * called on it, until n elements are read. - */ - public static List readNItemsFromStartedReader(Source.Reader reader, int n) - throws IOException { - return readNItemsFromReader(reader, n, true); - } - - /** - * Read elements from a {@link Source.Reader} until n elements are read. - * - *

              There must be at least n elements remaining in the reader, except for - * the case when n is {@code Integer.MAX_VALUE}, which means "read all - * remaining elements". - */ - private static List readNItemsFromReader(Source.Reader reader, int n, boolean started) - throws IOException { - List res = new ArrayList<>(); - for (int i = 0; i < n; i++) { - boolean shouldStart = (i == 0 && !started); - boolean more = shouldStart ? reader.start() : reader.advance(); - if (n != Integer.MAX_VALUE) { - assertTrue(more); - } - if (!more) { - break; - } - res.add(reader.getCurrent()); - } - return res; - } - - /** - * Read all remaining elements from a {@link Source.Reader}. - */ - public static List readRemainingFromReader(Source.Reader reader, boolean started) - throws IOException { - return readNItemsFromReader(reader, Integer.MAX_VALUE, started); - } - - /** - * Given a reference {@code Source} and a list of {@code Source}s, assert that the union of - * the records read from the list of sources is equal to the records read from the reference - * source. - */ - public static void assertSourcesEqualReferenceSource( - BoundedSource referenceSource, - List> sources, - PipelineOptions options) - throws Exception { - Coder coder = referenceSource.getDefaultOutputCoder(); - List referenceRecords = readFromSource(referenceSource, options); - List bundleRecords = new ArrayList<>(); - for (BoundedSource source : sources) { - assertThat( - "Coder type for source " - + source - + " is not compatible with Coder type for referenceSource " - + referenceSource, - source.getDefaultOutputCoder(), - equalTo(coder)); - List elems = readFromSource(source, options); - bundleRecords.addAll(elems); - } - List> bundleValues = - createStructuralValues(coder, bundleRecords); - List> referenceValues = - createStructuralValues(coder, referenceRecords); - assertThat(bundleValues, containsInAnyOrder(referenceValues.toArray())); - } - - /** - * Assert that a {@code Reader} returns a {@code Source} that, when read from, produces the same - * records as the reader. - */ - public static void assertUnstartedReaderReadsSameAsItsSource( - BoundedSource.BoundedReader reader, PipelineOptions options) throws Exception { - Coder coder = reader.getCurrentSource().getDefaultOutputCoder(); - List expected = readFromUnstartedReader(reader); - List actual = readFromSource(reader.getCurrentSource(), options); - List> expectedStructural = createStructuralValues(coder, expected); - List> actualStructural = createStructuralValues(coder, actual); - assertThat(actualStructural, containsInAnyOrder(expectedStructural.toArray())); - } - - /** - * Expected outcome of - * {@link com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader#splitAtFraction}. - */ - public enum ExpectedSplitOutcome { - /** - * The operation must succeed and the results must be consistent. - */ - MUST_SUCCEED_AND_BE_CONSISTENT, - /** - * The operation must fail (return {@code null}). - */ - MUST_FAIL, - /** - * The operation must either fail, or succeed and the results be consistent. - */ - MUST_BE_CONSISTENT_IF_SUCCEEDS - } - - /** - * Contains two values: the number of items in the primary source, and the number of items in - * the residual source, -1 if split failed. - */ - private static class SplitAtFractionResult { - public int numPrimaryItems; - public int numResidualItems; - - public SplitAtFractionResult(int numPrimaryItems, int numResidualItems) { - this.numPrimaryItems = numPrimaryItems; - this.numResidualItems = numResidualItems; - } - } - - /** - * Asserts that the {@code source}'s reader either fails to {@code splitAtFraction(fraction)} - * after reading {@code numItemsToReadBeforeSplit} items, or succeeds in a way that is - * consistent according to {@link #assertSplitAtFractionSucceedsAndConsistent}. - * - *

              Returns SplitAtFractionResult. - */ - - public static SplitAtFractionResult assertSplitAtFractionBehavior( - BoundedSource source, - int numItemsToReadBeforeSplit, - double splitFraction, - ExpectedSplitOutcome expectedOutcome, - PipelineOptions options) - throws Exception { - return assertSplitAtFractionBehaviorImpl( - source, readFromSource(source, options), numItemsToReadBeforeSplit, splitFraction, - expectedOutcome, options); - } - - /** - * Compares two lists elementwise and throws a detailed assertion failure optimized for - * human reading in case they are unequal. - */ - private static void assertListsEqualInOrder( - String message, String expectedLabel, List expected, String actualLabel, List actual) { - int i = 0; - for (; i < expected.size() && i < actual.size(); ++i) { - if (!Objects.equals(expected.get(i), actual.get(i))) { - Assert.fail(String.format( - "%s: %s and %s have %d items in common and then differ. " - + "Item in %s (%d more): %s, item in %s (%d more): %s", - message, expectedLabel, actualLabel, i, - expectedLabel, expected.size() - i - 1, expected.get(i), - actualLabel, actual.size() - i - 1, actual.get(i))); - } - } - if (i < expected.size() /* but i == actual.size() */) { - Assert.fail(String.format( - "%s: %s has %d more items after matching all %d from %s. First 5: %s", - message, expectedLabel, expected.size() - actual.size(), actual.size(), actualLabel, - expected.subList(actual.size(), Math.min(expected.size(), actual.size() + 5)))); - } else if (i < actual.size() /* but i == expected.size() */) { - Assert.fail(String.format( - "%s: %s has %d more items after matching all %d from %s. First 5: %s", - message, actualLabel, actual.size() - expected.size(), expected.size(), expectedLabel, - actual.subList(expected.size(), Math.min(actual.size(), expected.size() + 5)))); - } else { - // All is well. - } - } - - private static SourceTestUtils.SplitAtFractionResult assertSplitAtFractionBehaviorImpl( - BoundedSource source, List expectedItems, int numItemsToReadBeforeSplit, - double splitFraction, ExpectedSplitOutcome expectedOutcome, PipelineOptions options) - throws Exception { - try (BoundedSource.BoundedReader reader = source.createReader(options)) { - BoundedSource originalSource = reader.getCurrentSource(); - List currentItems = readNItemsFromUnstartedReader(reader, numItemsToReadBeforeSplit); - BoundedSource residual = reader.splitAtFraction(splitFraction); - if (residual != null) { - assertFalse( - String.format( - "Primary source didn't change after a successful split of %s at %f " - + "after reading %d items. " - + "Was the source object mutated instead of creating a new one? " - + "Source objects MUST be immutable.", - source, splitFraction, numItemsToReadBeforeSplit), - reader.getCurrentSource() == originalSource); - assertFalse( - String.format( - "Residual source equal to original source after a successful split of %s at %f " - + "after reading %d items. " - + "Was the source object mutated instead of creating a new one? " - + "Source objects MUST be immutable.", - source, splitFraction, numItemsToReadBeforeSplit), - reader.getCurrentSource() == residual); - } - // Failure cases are: must succeed but fails; must fail but succeeds. - switch (expectedOutcome) { - case MUST_SUCCEED_AND_BE_CONSISTENT: - assertNotNull( - "Failed to split reader of source: " - + source - + " at " - + splitFraction - + " after reading " - + numItemsToReadBeforeSplit - + " items", - residual); - break; - case MUST_FAIL: - assertEquals(null, residual); - break; - case MUST_BE_CONSISTENT_IF_SUCCEEDS: - // Nothing. - break; - } - currentItems.addAll(readRemainingFromReader(reader, numItemsToReadBeforeSplit > 0)); - BoundedSource primary = reader.getCurrentSource(); - return verifySingleSplitAtFractionResult( - source, expectedItems, currentItems, primary, residual, - numItemsToReadBeforeSplit, splitFraction, options); - } - } - - private static SourceTestUtils.SplitAtFractionResult verifySingleSplitAtFractionResult( - BoundedSource source, List expectedItems, List currentItems, - BoundedSource primary, BoundedSource residual, - int numItemsToReadBeforeSplit, double splitFraction, PipelineOptions options) - throws Exception { - List primaryItems = readFromSource(primary, options); - if (residual != null) { - List residualItems = readFromSource(residual, options); - List totalItems = new ArrayList<>(); - totalItems.addAll(primaryItems); - totalItems.addAll(residualItems); - String errorMsgForPrimarySourceComp = - String.format( - "Continued reading after split yielded different items than primary source: " - + "split at %s after reading %s items, original source: %s, primary source: %s", - splitFraction, - numItemsToReadBeforeSplit, - source, - primary); - String errorMsgForTotalSourceComp = - String.format( - "Items in primary and residual sources after split do not add up to items " - + "in the original source. Split at %s after reading %s items; " - + "original source: %s, primary: %s, residual: %s", - splitFraction, - numItemsToReadBeforeSplit, - source, - primary, - residual); - Coder coder = primary.getDefaultOutputCoder(); - List> primaryValues = - createStructuralValues(coder, primaryItems); - List> currentValues = - createStructuralValues(coder, currentItems); - List> expectedValues = - createStructuralValues(coder, expectedItems); - List> totalValues = - createStructuralValues(coder, totalItems); - assertListsEqualInOrder( - errorMsgForPrimarySourceComp, "current", currentValues, "primary", primaryValues); - assertListsEqualInOrder( - errorMsgForTotalSourceComp, "total", expectedValues, "primary+residual", totalValues); - return new SplitAtFractionResult(primaryItems.size(), residualItems.size()); - } - return new SplitAtFractionResult(primaryItems.size(), -1); - } - - /** - * Verifies some consistency properties of - * {@link BoundedSource.BoundedReader#splitAtFraction} on the given source. Equivalent to - * the following pseudocode: - *

              -   *   Reader reader = source.createReader();
              -   *   read N items from reader;
              -   *   Source residual = reader.splitAtFraction(splitFraction);
              -   *   Source primary = reader.getCurrentSource();
              -   *   assert: items in primary == items we read so far
              -   *                               + items we'll get by continuing to read from reader;
              -   *   assert: items in original source == items in primary + items in residual
              -   * 
              - */ - public static void assertSplitAtFractionSucceedsAndConsistent( - BoundedSource source, - int numItemsToReadBeforeSplit, - double splitFraction, - PipelineOptions options) - throws Exception { - assertSplitAtFractionBehavior( - source, - numItemsToReadBeforeSplit, - splitFraction, - ExpectedSplitOutcome.MUST_SUCCEED_AND_BE_CONSISTENT, - options); - } - - /** - * Asserts that the {@code source}'s reader fails to {@code splitAtFraction(fraction)} - * after reading {@code numItemsToReadBeforeSplit} items. - */ - public static void assertSplitAtFractionFails( - BoundedSource source, - int numItemsToReadBeforeSplit, - double splitFraction, - PipelineOptions options) - throws Exception { - assertSplitAtFractionBehavior( - source, numItemsToReadBeforeSplit, splitFraction, ExpectedSplitOutcome.MUST_FAIL, options); - } - - private static class SplitFractionStatistics { - List successfulFractions = new ArrayList<>(); - List nonTrivialFractions = new ArrayList<>(); - } - - /** - * Asserts that given a start position, - * {@link BoundedSource.BoundedReader#splitAtFraction} at every interesting fraction (halfway - * between two fractions that differ by at least one item) can be called successfully and the - * results are consistent if a split succeeds. - */ - private static void assertSplitAtFractionBinary( - BoundedSource source, - List expectedItems, - int numItemsToBeReadBeforeSplit, - double leftFraction, - SplitAtFractionResult leftResult, - double rightFraction, - SplitAtFractionResult rightResult, - PipelineOptions options, - SplitFractionStatistics stats) - throws Exception { - if (rightFraction - leftFraction < 0.001) { - // Do not recurse too deeply. Otherwise we will end up in infinite - // recursion, e.g., while trying to find the exact minimal fraction s.t. - // split succeeds. A precision of 0.001 when looking for such a fraction - // ought to be enough for everybody. - return; - } - double middleFraction = (rightFraction + leftFraction) / 2; - if (leftResult == null) { - leftResult = assertSplitAtFractionBehaviorImpl( - source, expectedItems, numItemsToBeReadBeforeSplit, leftFraction, - ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - } - if (rightResult == null) { - rightResult = assertSplitAtFractionBehaviorImpl( - source, expectedItems, numItemsToBeReadBeforeSplit, rightFraction, - ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - } - SplitAtFractionResult middleResult = assertSplitAtFractionBehaviorImpl( - source, expectedItems, numItemsToBeReadBeforeSplit, middleFraction, - ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - if (middleResult.numResidualItems != -1) { - stats.successfulFractions.add(middleFraction); - } - if (middleResult.numResidualItems > 0) { - stats.nonTrivialFractions.add(middleFraction); - } - // Two split fractions are equivalent if they yield the same number of - // items in primary vs. residual source. Left and right are already not - // equivalent. Recurse into [left, middle) and [right, middle) respectively - // if middle is not equivalent to left or right. - if (leftResult.numPrimaryItems != middleResult.numPrimaryItems) { - assertSplitAtFractionBinary( - source, expectedItems, numItemsToBeReadBeforeSplit, - leftFraction, leftResult, middleFraction, middleResult, options, stats); - } - if (rightResult.numPrimaryItems != middleResult.numPrimaryItems) { - assertSplitAtFractionBinary( - source, expectedItems, numItemsToBeReadBeforeSplit, - middleFraction, middleResult, rightFraction, rightResult, options, stats); - } - } - - private static final int MAX_CONCURRENT_SPLITTING_TRIALS_PER_ITEM = 100; - private static final int MAX_CONCURRENT_SPLITTING_TRIALS_TOTAL = 1000; - - /** - * Asserts that for each possible start position, - * {@link BoundedSource.BoundedReader#splitAtFraction} at every interesting fraction (halfway - * between two fractions that differ by at least one item) can be called successfully and the - * results are consistent if a split succeeds. Verifies multithreaded splitting as well. - */ - public static void assertSplitAtFractionExhaustive( - BoundedSource source, PipelineOptions options) throws Exception { - List expectedItems = readFromSource(source, options); - assertFalse("Empty source", expectedItems.isEmpty()); - assertFalse("Source reads a single item", expectedItems.size() == 1); - List> allNonTrivialFractions = new ArrayList<>(); - { - boolean anySuccessfulFractions = false; - boolean anyNonTrivialFractions = false; - for (int i = 0; i < expectedItems.size(); i++) { - SplitFractionStatistics stats = new SplitFractionStatistics(); - assertSplitAtFractionBinary(source, expectedItems, i, - 0.0, null, 1.0, null, options, stats); - if (!stats.successfulFractions.isEmpty()) { - anySuccessfulFractions = true; - } - if (!stats.nonTrivialFractions.isEmpty()) { - anyNonTrivialFractions = true; - } - allNonTrivialFractions.add(stats.nonTrivialFractions); - } - assertTrue( - "splitAtFraction test completed vacuously: no successful split fractions found", - anySuccessfulFractions); - assertTrue( - "splitAtFraction test completed vacuously: no non-trivial split fractions found", - anyNonTrivialFractions); - } - { - // Perform a stress test of "racy" concurrent splitting: - // for every position (number of items read), try to split at the minimum nontrivial - // split fraction for that position concurrently with reading the record at that position. - // To ensure that the test is non-vacuous, make sure that the splitting succeeds - // at least once and fails at least once. - ExecutorService executor = Executors.newFixedThreadPool(2); - int numTotalTrials = 0; - for (int i = 0; i < expectedItems.size(); i++) { - double minNonTrivialFraction = 2.0; // Greater than any possible fraction. - for (double fraction : allNonTrivialFractions.get(i)) { - minNonTrivialFraction = Math.min(minNonTrivialFraction, fraction); - } - if (minNonTrivialFraction == 2.0) { - // This will not happen all the time because otherwise the test above would - // detect vacuousness. - continue; - } - int numTrials = 0; - boolean haveSuccess = false, haveFailure = false; - while (true) { - ++numTrials; - if (numTrials > MAX_CONCURRENT_SPLITTING_TRIALS_PER_ITEM) { - LOG.warn( - "After {} concurrent splitting trials at item #{}, observed only {}, " - + "giving up on this item", - numTrials, i, haveSuccess ? "success" : "failure"); - break; - } - if (assertSplitAtFractionConcurrent( - executor, source, expectedItems, i, minNonTrivialFraction, options)) { - haveSuccess = true; - } else { - haveFailure = true; - } - if (haveSuccess && haveFailure) { - LOG.info( - "{} trials to observe both success and failure of concurrent splitting at item #{}", - numTrials, i); - break; - } - } - numTotalTrials += numTrials; - if (numTotalTrials > MAX_CONCURRENT_SPLITTING_TRIALS_TOTAL) { - LOG.warn( - "After {} total concurrent splitting trials, considered only {} items, giving up.", - numTotalTrials, i); - break; - } - } - LOG.info( - "{} total concurrent splitting trials for {} items", - numTotalTrials, expectedItems.size()); - } - } - - private static boolean assertSplitAtFractionConcurrent( - ExecutorService executor, BoundedSource source, List expectedItems, - final int numItemsToReadBeforeSplitting, final double fraction, PipelineOptions options) - throws Exception { - @SuppressWarnings("resource") // Closed in readerThread - final BoundedSource.BoundedReader reader = source.createReader(options); - final CountDownLatch unblockSplitter = new CountDownLatch(1); - Future> readerThread = - executor.submit( - new Callable>() { - @Override - public List call() throws Exception { - try { - List items = - readNItemsFromUnstartedReader(reader, numItemsToReadBeforeSplitting); - unblockSplitter.countDown(); - items.addAll(readRemainingFromReader(reader, numItemsToReadBeforeSplitting > 0)); - return items; - } finally { - reader.close(); - } - } - }); - Future, BoundedSource>> splitterThread = executor.submit( - new Callable, BoundedSource>>() { - @Override - public KV, BoundedSource> call() throws Exception { - unblockSplitter.await(); - BoundedSource residual = reader.splitAtFraction(fraction); - if (residual == null) { - return null; - } - return KV.of(reader.getCurrentSource(), residual); - } - }); - List currentItems = readerThread.get(); - KV, BoundedSource> splitSources = splitterThread.get(); - if (splitSources == null) { - return false; - } - SplitAtFractionResult res = verifySingleSplitAtFractionResult( - source, expectedItems, currentItems, splitSources.getKey(), splitSources.getValue(), - numItemsToReadBeforeSplitting, fraction, options); - return (res.numResidualItems > 0); - } - - /** - * Returns an equivalent unsplittable {@code BoundedSource}. - * - *

              It forwards most methods to the given {@code boundedSource}, except: - *

                - *
              1. {@link BoundedSource#splitIntoBundles} rejects initial splitting - * by returning itself in a list. - *
              2. {@link BoundedReader#splitAtFraction} rejects dynamic splitting by returning null. - *
              - */ - public static BoundedSource toUnsplittableSource(BoundedSource boundedSource) { - return new UnsplittableSource<>(boundedSource); - } - - private static class UnsplittableSource extends BoundedSource { - - private final BoundedSource boundedSource; - - private UnsplittableSource(BoundedSource boundedSource) { - this.boundedSource = checkNotNull(boundedSource, "boundedSource"); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - this.boundedSource.populateDisplayData(builder); - } - - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - return ImmutableList.of(this); - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return boundedSource.getEstimatedSizeBytes(options); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return boundedSource.producesSortedKeys(options); - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return new UnsplittableReader<>(boundedSource, boundedSource.createReader(options)); - } - - @Override - public void validate() { - boundedSource.validate(); - } - - @Override - public Coder getDefaultOutputCoder() { - return boundedSource.getDefaultOutputCoder(); - } - - private static class UnsplittableReader extends BoundedReader { - - private final BoundedSource boundedSource; - private final BoundedReader boundedReader; - - private UnsplittableReader(BoundedSource boundedSource, BoundedReader boundedReader) { - this.boundedSource = checkNotNull(boundedSource, "boundedSource"); - this.boundedReader = checkNotNull(boundedReader, "boundedReader"); - } - - @Override - public BoundedSource getCurrentSource() { - return boundedSource; - } - - @Override - public boolean start() throws IOException { - return boundedReader.start(); - } - - @Override - public boolean advance() throws IOException { - return boundedReader.advance(); - } - - @Override - public T getCurrent() throws NoSuchElementException { - return boundedReader.getCurrent(); - } - - @Override - public void close() throws IOException { - boundedReader.close(); - } - - @Override - @Nullable - public BoundedSource splitAtFraction(double fraction) { - return null; - } - - @Override - @Nullable - public Double getFractionConsumed() { - return boundedReader.getFractionConsumed(); - } - - @Override - public long getSplitPointsConsumed() { - return boundedReader.getSplitPointsConsumed(); - } - - @Override - public long getSplitPointsRemaining() { - return boundedReader.getSplitPointsRemaining(); - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - return boundedReader.getCurrentTimestamp(); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java deleted file mode 100644 index 88f2db9a94..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/StaticWindows.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.NonMergingWindowFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.joda.time.Instant; - -import java.util.Collection; -import java.util.Collections; -import java.util.Objects; - -/** - * A {@link WindowFn} that assigns all elements to a static collection of - * {@link BoundedWindow BoundedWindows}. Side inputs windowed into static windows only support - * main input windows in the provided collection of windows. - */ -final class StaticWindows extends NonMergingWindowFn { - private final Supplier> windows; - private final Coder coder; - - private final boolean onlyExisting; - - private StaticWindows( - Supplier> windows, - Coder coder, - boolean onlyExisting) { - this.windows = windows; - this.coder = coder; - this.onlyExisting = onlyExisting; - } - - public static StaticWindows of(Coder coder, Iterable windows) { - checkArgument(!Iterables.isEmpty(windows), "Input windows to StaticWindows may not be empty"); - @SuppressWarnings("unchecked") - StaticWindows windowFn = - new StaticWindows( - WindowSupplier.of((Coder) coder, (Iterable) windows), - (Coder) coder, - false); - return windowFn; - } - - public static StaticWindows of(Coder coder, W window) { - return of(coder, Collections.singleton(window)); - } - - public StaticWindows intoOnlyExisting() { - return new StaticWindows(windows, coder, true); - } - - public Collection getWindows() { - return windows.get(); - } - - @Override - public Collection assignWindows(AssignContext c) throws Exception { - if (onlyExisting) { - checkArgument( - windows.get().containsAll(c.windows()), - "Tried to assign windows to an element that is not already windowed into a provided " - + "window when onlyExisting is set to true"); - return ImmutableList.copyOf(c.windows()); - } else { - return getWindows(); - } - } - - @Override - public boolean isCompatible(WindowFn other) { - if (!(other instanceof StaticWindows)) { - return false; - } - StaticWindows that = (StaticWindows) other; - return Objects.equals(this.windows.get(), that.windows.get()); - } - - @Override - public Coder windowCoder() { - return coder; - } - - @Override - public BoundedWindow getSideInputWindow(BoundedWindow window) { - checkArgument(windows.get().contains(window), - "StaticWindows only supports side input windows for main input windows that it contains"); - return window; - } - - @Override - public Instant getOutputTime(Instant inputTimestamp, BoundedWindow window) { - return inputTimestamp; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineOptions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineOptions.java deleted file mode 100644 index 1afb691044..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineOptions.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.options.BlockingDataflowPipelineOptions; - -/** - * A set of options used to configure the {@link TestPipeline}. - */ -public interface TestDataflowPipelineOptions extends BlockingDataflowPipelineOptions { - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java deleted file mode 100644 index 118ba2f822..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunner.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.api.services.dataflow.model.JobMessage; -import com.google.api.services.dataflow.model.JobMetrics; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DataflowJobExecutionException; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineJob; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil.JobMessagesHandler; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.base.Optional; -import com.google.common.base.Throwables; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -/** - * {@link TestDataflowPipelineRunner} is a pipeline runner that wraps a - * {@link DataflowPipelineRunner} when running tests against the {@link TestPipeline}. - * - * @see TestPipeline - */ -public class TestDataflowPipelineRunner extends PipelineRunner { - private static final String TENTATIVE_COUNTER = "tentative"; - private static final Logger LOG = LoggerFactory.getLogger(TestDataflowPipelineRunner.class); - - private final TestDataflowPipelineOptions options; - private final DataflowPipelineRunner runner; - private int expectedNumberOfAssertions = 0; - - TestDataflowPipelineRunner(TestDataflowPipelineOptions options) { - this.options = options; - this.runner = DataflowPipelineRunner.fromOptions(options); - } - - /** - * Constructs a runner from the provided options. - */ - public static TestDataflowPipelineRunner fromOptions( - PipelineOptions options) { - TestDataflowPipelineOptions dataflowOptions = options.as(TestDataflowPipelineOptions.class); - - return new TestDataflowPipelineRunner(dataflowOptions); - } - - @Override - public DataflowPipelineJob run(Pipeline pipeline) { - return run(pipeline, runner); - } - - DataflowPipelineJob run(Pipeline pipeline, DataflowPipelineRunner runner) { - - final JobMessagesHandler messageHandler = - new MonitoringUtil.PrintHandler(options.getJobMessageOutput()); - final DataflowPipelineJob job; - try { - job = runner.run(pipeline); - } catch (DataflowJobExecutionException ex) { - throw new IllegalStateException("The dataflow failed."); - } - - LOG.info("Running Dataflow job {} with {} expected assertions.", - job.getJobId(), expectedNumberOfAssertions); - - try { - final Optional result; - if (options.isStreaming()) { - Future> resultFuture = options.getExecutorService().submit( - new Callable>() { - @Override - public Optional call() throws Exception { - try { - for (;;) { - Optional result = checkForSuccess(job); - if (result.isPresent()) { - return result; - } - Thread.sleep(10000L); - } - } finally { - LOG.info("Cancelling Dataflow job {}", job.getJobId()); - job.cancel(); - } - } - }); - State finalState = job.waitToFinish(10L, TimeUnit.MINUTES, new JobMessagesHandler() { - @Override - public void process(List messages) { - messageHandler.process(messages); - for (JobMessage message : messages) { - if (message.getMessageImportance() != null - && message.getMessageImportance().equals("JOB_MESSAGE_ERROR")) { - LOG.info("Dataflow job {} threw exception, cancelling. Exception was: {}", - job.getJobId(), message.getMessageText()); - try { - job.cancel(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - } - }); - if (finalState == null || finalState == State.RUNNING) { - LOG.info("Dataflow job {} took longer than 10 minutes to complete, cancelling.", - job.getJobId()); - job.cancel(); - } - result = resultFuture.get(); - } else { - job.waitToFinish(-1, TimeUnit.SECONDS, messageHandler); - result = checkForSuccess(job); - } - if (!result.isPresent()) { - throw new IllegalStateException( - "The dataflow did not output a success or failure metric."); - } else if (!result.get()) { - throw new IllegalStateException("The dataflow failed."); - } - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new RuntimeException(e); - } - return job; - } - - @Override - public OutputT apply( - PTransform transform, InputT input) { - if (transform instanceof DataflowAssert.OneSideInputAssert - || transform instanceof DataflowAssert.GroupThenAssert - || transform instanceof DataflowAssert.GroupThenAssertForSingleton) { - expectedNumberOfAssertions += 1; - } - - return runner.apply(transform, input); - } - - Optional checkForSuccess(DataflowPipelineJob job) - throws IOException { - State state = job.getState(); - if (state == State.FAILED || state == State.CANCELLED) { - LOG.info("The pipeline failed"); - return Optional.of(false); - } - - JobMetrics metrics = job.getDataflowClient().projects().jobs() - .getMetrics(job.getProjectId(), job.getJobId()).execute(); - - if (metrics == null || metrics.getMetrics() == null) { - LOG.warn("Metrics not present for Dataflow job {}.", job.getJobId()); - } else { - int successes = 0; - int failures = 0; - for (MetricUpdate metric : metrics.getMetrics()) { - if (metric.getName() == null || metric.getName().getContext() == null - || !metric.getName().getContext().containsKey(TENTATIVE_COUNTER)) { - // Don't double count using the non-tentative version of the metric. - continue; - } - if (DataflowAssert.SUCCESS_COUNTER.equals(metric.getName().getName())) { - successes += ((BigDecimal) metric.getScalar()).intValue(); - } else if (DataflowAssert.FAILURE_COUNTER.equals(metric.getName().getName())) { - failures += ((BigDecimal) metric.getScalar()).intValue(); - } - } - - if (failures > 0) { - LOG.info("Found result while running Dataflow job {}. Found {} success, {} failures out of " - + "{} expected assertions.", job.getJobId(), successes, failures, - expectedNumberOfAssertions); - return Optional.of(false); - } else if (successes >= expectedNumberOfAssertions) { - LOG.info("Found result while running Dataflow job {}. Found {} success, {} failures out of " - + "{} expected assertions.", job.getJobId(), successes, failures, - expectedNumberOfAssertions); - return Optional.of(true); - } - - LOG.info("Running Dataflow job {}. Found {} success, {} failures out of {} expected " - + "assertions.", job.getJobId(), successes, failures, expectedNumberOfAssertions); - } - - return Optional.absent(); - } - - @Override - public String toString() { - return "TestDataflowPipelineRunner#" + options.getAppName(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java deleted file mode 100644 index 620ff0055c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestPipeline.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.common.base.Optional; -import com.google.common.collect.Iterators; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.util.Iterator; - -import javax.annotation.Nullable; - -/** - * A creator of test pipelines that can be used inside of tests that can be - * configured to run locally or against the live service. - * - *

              It is recommended to tag hand-selected tests for this purpose using the - * {@code @RunnableOnService} category annotation, and use a category aware - * test executor such as JUnit. Each test run against the service will spin - * up and tear down VMs. - * - *

              In order to run tests on Google Cloud Dataflow, the following - * conditions must be met: - *

                - *
              • System property {@code runIntegrationTestOnService} must be set to true.
              • - *
              • System property {@code dataflowOptions} must contain a JSON delimited list - * of pipeline options with all options that the Google Cloud Dataflow service requires. - * For example: - *
                {@code [
                - *     "--project=mygcpproject",
                - *     "--stagingLocation=gs://mygcsbucket/path"
                - *     ]}
                - * Note that the set of pipeline options required can also be test specific.
              • - *
              • Jars containing the SDK and test classes must be available on the classpath.
              • - *
              - * - *

              Use {@link DataflowAssert} for tests, as it integrates with this test - * harness in both direct and remote execution modes. For example: - * - *

              {@code
              - * Pipeline p = TestPipeline.create();
              - * PCollection output = ...
              - *
              - * DataflowAssert.that(output)
              - *     .containsInAnyOrder(1, 2, 3, 4);
              - * p.run();
              - * }
              - * - */ -public class TestPipeline extends Pipeline { - private static final String PROPERTY_DATAFLOW_OPTIONS = "dataflowOptions"; - private static final ObjectMapper MAPPER = new ObjectMapper(); - - /** - * Creates and returns a new test pipeline. - * - *

              Use {@link DataflowAssert} to add tests, then call - * {@link Pipeline#run} to execute the pipeline and check the tests. - */ - public static TestPipeline create() { - return fromOptions(testingPipelineOptions()); - } - - public static TestPipeline fromOptions(PipelineOptions options) { - return new TestPipeline(PipelineRunner.fromOptions(options), options); - } - - /** - * Returns whether a {@link TestPipeline} supports dynamic work rebalancing, and thus tests - * of dynamic work rebalancing are expected to pass. - */ - public boolean supportsDynamicWorkRebalancing() { - return getRunner() instanceof DataflowPipelineRunner; - } - - private TestPipeline(PipelineRunner runner, PipelineOptions options) { - super(runner, options); - } - - /** - * Runs this {@link TestPipeline}, unwrapping any {@code AssertionError} - * that is raised during testing. - */ - @Override - public PipelineResult run() { - try { - return super.run(); - } catch (RuntimeException exc) { - Throwable cause = exc.getCause(); - if (cause instanceof AssertionError) { - throw (AssertionError) cause; - } else { - throw exc; - } - } - } - - @Override - public String toString() { - return "TestPipeline#" + getOptions().as(ApplicationNameOptions.class).getAppName(); - } - - /** - * Creates {@link PipelineOptions} for testing. - */ - public static PipelineOptions testingPipelineOptions() { - try { - @Nullable String systemDataflowOptions = System.getProperty(PROPERTY_DATAFLOW_OPTIONS); - PipelineOptions options = - systemDataflowOptions == null - ? PipelineOptionsFactory.create() - : PipelineOptionsFactory.fromArgs( - MAPPER.readValue( - System.getProperty(PROPERTY_DATAFLOW_OPTIONS), String[].class)) - .as(PipelineOptions.class); - - options.as(ApplicationNameOptions.class).setAppName(getAppName()); - if (isIntegrationTest()) { - // TODO: adjust everyone's integration test frameworks to set the runner class via the - // pipeline options via PROPERTY_DATAFLOW_OPTIONS - options.setRunner(TestDataflowPipelineRunner.class); - } else { - options.as(GcpOptions.class).setGcpCredential(new TestCredential()); - } - options.setStableUniqueNames(CheckEnabled.ERROR); - return options; - } catch (IOException e) { - throw new RuntimeException("Unable to instantiate test options from system property " - + PROPERTY_DATAFLOW_OPTIONS + ":" + System.getProperty(PROPERTY_DATAFLOW_OPTIONS), e); - } - } - - /** - * Returns whether a {@link TestPipeline} should be treated as an integration test. - */ - private static boolean isIntegrationTest() { - return Boolean.parseBoolean(System.getProperty("runIntegrationTestOnService")); - } - - /** Returns the class + method name of the test, or a default name. */ - private static String getAppName() { - Optional stackTraceElement = findCallersStackTrace(); - if (stackTraceElement.isPresent()) { - String methodName = stackTraceElement.get().getMethodName(); - String className = stackTraceElement.get().getClassName(); - if (className.contains(".")) { - className = className.substring(className.lastIndexOf(".") + 1); - } - return className + "-" + methodName; - } - return "UnitTest"; - } - - /** Returns the {@link StackTraceElement} of the calling class. */ - private static Optional findCallersStackTrace() { - Iterator elements = - Iterators.forArray(Thread.currentThread().getStackTrace()); - // First find the TestPipeline class in the stack trace. - while (elements.hasNext()) { - StackTraceElement next = elements.next(); - if (TestPipeline.class.getName().equals(next.getClassName())) { - break; - } - } - // Then find the first instance after that is not the TestPipeline - while (elements.hasNext()) { - StackTraceElement next = elements.next(); - if (!TestPipeline.class.getName().equals(next.getClassName())) { - return Optional.of(next); - } - } - return Optional.absent(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java deleted file mode 100644 index 03c7e4389f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/TestStream.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.auto.value.AutoValue; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.DurationCoder; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TimestampedValue.TimestampedValueCoder; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableList; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.ReadableDuration; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collections; -import java.util.List; - -/** - * A testing input that generates an unbounded {@link PCollection} of elements, advancing the - * watermark and processing time as elements are emitted. After all of the specified elements are - * emitted, ceases to produce output. - * - *

              Each call to a {@link TestStream.Builder} method will only be reflected in the state of the - * {@link Pipeline} after each method before it has completed and no more progress can be made by - * the {@link Pipeline}. A {@link PipelineRunner} must ensure that no more progress can be made in - * the {@link Pipeline} before advancing the state of the {@link TestStream}. - */ -public final class TestStream extends PTransform> { - private final List> events; - private final Coder coder; - - /** - * Create a new {@link TestStream.Builder} with no elements and watermark equal to {@link - * BoundedWindow#TIMESTAMP_MIN_VALUE}. - */ - public static Builder create(Coder coder) { - return new Builder<>(coder); - } - - private TestStream(Coder coder, List> events) { - this.coder = coder; - this.events = checkNotNull(events); - } - - /** - * An incomplete {@link TestStream}. Elements added to this builder will be produced in sequence - * when the pipeline created by the {@link TestStream} is run. - */ - public static class Builder { - private final Coder coder; - private final ImmutableList> events; - private final Instant currentWatermark; - - private Builder(Coder coder) { - this(coder, ImmutableList.>of(), BoundedWindow.TIMESTAMP_MIN_VALUE); - } - - private Builder(Coder coder, ImmutableList> events, Instant currentWatermark) { - this.coder = coder; - this.events = events; - this.currentWatermark = currentWatermark; - } - - /** - * Adds the specified elements to the source with timestamp equal to the current watermark. - * - * @return A {@link TestStream.Builder} like this one that will emit the provided elements - * after all earlier events have completed. - */ - @SafeVarargs - public final Builder addElements(T first, T... rest) { - TimestampedValue firstElement = TimestampedValue.of(first, currentWatermark); - @SuppressWarnings("unchecked") - TimestampedValue[] remainingElements = new TimestampedValue[rest.length]; - for (int i = 0; i < rest.length; i++) { - remainingElements[i] = TimestampedValue.of(rest[i], currentWatermark); - } - return addElements(firstElement, remainingElements); - } - - /** - * Adds the specified elements to the source with the provided timestamps. - * - * @return A {@link TestStream.Builder} like this one that will emit the provided elements - * after all earlier events have completed. - */ - @SafeVarargs - public final Builder addElements( - TimestampedValue first, TimestampedValue... rest) { - checkArgument( - first.getTimestamp().isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE), - "Elements must have timestamps before %s. Got: %s", - BoundedWindow.TIMESTAMP_MAX_VALUE, - first.getTimestamp()); - for (TimestampedValue element : rest) { - checkArgument( - element.getTimestamp().isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE), - "Elements must have timestamps before %s. Got: %s", - BoundedWindow.TIMESTAMP_MAX_VALUE, - element.getTimestamp()); - } - ImmutableList> newEvents = - ImmutableList.>builder() - .addAll(events) - .add(ElementEvent.add(first, rest)) - .build(); - return new Builder(coder, newEvents, currentWatermark); - } - - /** - * Advance the watermark of this source to the specified instant. - * - *

              The watermark must advance monotonically and cannot advance to {@link - * BoundedWindow#TIMESTAMP_MAX_VALUE} or beyond. - * - * @return A {@link TestStream.Builder} like this one that will advance the watermark to the - * specified point after all earlier events have completed. - */ - public Builder advanceWatermarkTo(Instant newWatermark) { - checkArgument( - newWatermark.isAfter(currentWatermark), "The watermark must monotonically advance"); - checkArgument( - newWatermark.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE), - "The Watermark cannot progress beyond the maximum. Got: %s. Maximum: %s", - newWatermark, - BoundedWindow.TIMESTAMP_MAX_VALUE); - ImmutableList> newEvents = ImmutableList.>builder() - .addAll(events) - .add(WatermarkEvent.advanceTo(newWatermark)) - .build(); - return new Builder(coder, newEvents, newWatermark); - } - - /** - * Advance the processing time by the specified amount. - * - * @return A {@link TestStream.Builder} like this one that will advance the processing time by - * the specified amount after all earlier events have completed. - */ - public Builder advanceProcessingTime(Duration amount) { - checkArgument( - amount.getMillis() > 0, - "Must advance the processing time by a positive amount. Got: ", - amount); - ImmutableList> newEvents = - ImmutableList.>builder() - .addAll(events) - .add(ProcessingTimeEvent.advanceBy(amount)) - .build(); - return new Builder(coder, newEvents, currentWatermark); - } - - /** - * Advance the watermark to infinity, completing this {@link TestStream}. Future calls to the - * same builder will not affect the returned {@link TestStream}. - */ - public TestStream advanceWatermarkToInfinity() { - ImmutableList> newEvents = - ImmutableList.>builder() - .addAll(events) - .add(WatermarkEvent.advanceTo(BoundedWindow.TIMESTAMP_MAX_VALUE)) - .build(); - return new TestStream<>(coder, newEvents); - } - } - - /** - * An event in a {@link TestStream}. A marker interface for all events that happen while - * evaluating a {@link TestStream}. - */ - public interface Event { - EventType getType(); - } - - /** - * The types of {@link Event} that are supported by {@link TestStream}. - */ - public enum EventType { - ELEMENT, - WATERMARK, - PROCESSING_TIME - } - - /** An {@link Event} that produces elements. */ - @AutoValue - public abstract static class ElementEvent implements Event { - public abstract Iterable> getElements(); - - @SafeVarargs - static Event add(TimestampedValue element, TimestampedValue... elements) { - return add(ImmutableList.>builder().add(element).add(elements).build()); - } - - static Event add(Iterable> elements) { - return new AutoValue_TestStream_ElementEvent<>(EventType.ELEMENT, elements); - } - } - - /** An {@link Event} that advances the watermark. */ - @AutoValue - public abstract static class WatermarkEvent implements Event { - public abstract Instant getWatermark(); - - static Event advanceTo(Instant newWatermark) { - return new AutoValue_TestStream_WatermarkEvent<>(EventType.WATERMARK, newWatermark); - } - } - - /** An {@link Event} that advances the processing time clock. */ - @AutoValue - public abstract static class ProcessingTimeEvent implements Event { - public abstract Duration getProcessingTimeAdvance(); - - static Event advanceBy(Duration amount) { - return new AutoValue_TestStream_ProcessingTimeEvent<>(EventType.PROCESSING_TIME, amount); - } - } - - @Override - public PCollection apply(PBegin input) { - throw new IllegalStateException( - String.format( - "Pipeline Runner %s does not support %s", - input.getPipeline().getRunner().getClass().getSimpleName(), - getClass().getSimpleName())); - } - - public Coder getValueCoder() { - return coder; - } - - /** - * Returns a coder suitable for encoding {@link TestStream.Event}. - */ - public Coder> getEventCoder() { - return EventCoder.of(coder); - } - - /** - * Returns the sequence of {@link Event Events} in this {@link TestStream}. - * - *

              For use by {@link PipelineRunner} authors. - */ - public List> getEvents() { - return events; - } - - /** - * A {@link Coder} that encodes and decodes {@link TestStream.Event Events}. - * - * @param the type of elements in {@link ElementEvent ElementEvents} encoded and decoded by - * this {@link EventCoder} - */ - @VisibleForTesting - static final class EventCoder extends StandardCoder> { - private static final Coder DURATION_CODER = DurationCoder.of(); - private static final Coder INSTANT_CODER = InstantCoder.of(); - private final Coder valueCoder; - private final Coder>> elementCoder; - - public static EventCoder of(Coder valueCoder) { - return new EventCoder<>(valueCoder); - } - - @JsonCreator - public static EventCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { - checkArgument( - components.size() == 1, - "Was expecting exactly one component coder, got %s", - components.size()); - return new EventCoder<>((Coder) components.get(0)); - } - - private EventCoder(Coder valueCoder) { - this.valueCoder = valueCoder; - this.elementCoder = IterableCoder.of(TimestampedValueCoder.of(valueCoder)); - } - - @Override - public void encode( - Event value, OutputStream outStream, Context context) - throws IOException { - VarInt.encode(value.getType().ordinal(), outStream); - switch (value.getType()) { - case ELEMENT: - Iterable> elems = ((ElementEvent) value).getElements(); - elementCoder.encode(elems, outStream, context); - break; - case WATERMARK: - Instant ts = ((WatermarkEvent) value).getWatermark(); - INSTANT_CODER.encode(ts, outStream, context); - break; - case PROCESSING_TIME: - Duration processingAdvance = ((ProcessingTimeEvent) value).getProcessingTimeAdvance(); - DURATION_CODER.encode(processingAdvance, outStream, context); - break; - default: - throw new AssertionError("Unreachable: Unsupported Event Type " + value.getType()); - } - } - - @Override - public Event decode( - InputStream inStream, Context context) throws IOException { - EventType eventType = EventType.values()[VarInt.decodeInt(inStream)]; - switch (eventType) { - case ELEMENT: - Iterable> elements = elementCoder.decode(inStream, context); - return ElementEvent.add(elements); - case WATERMARK: - return WatermarkEvent.advanceTo(INSTANT_CODER.decode(inStream, context)); - case PROCESSING_TIME: - return ProcessingTimeEvent.advanceBy( - DURATION_CODER.decode(inStream, context).toDuration()); - default: - throw new AssertionError("Unreachable: Unsupported Event Type " + eventType); - } - } - - @Override - public List> getCoderArguments() { - return Collections.singletonList(valueCoder); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - elementCoder.verifyDeterministic(); - DURATION_CODER.verifyDeterministic(); - INSTANT_CODER.verifyDeterministic(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowFnTestUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowFnTestUtils.java deleted file mode 100644 index dc0baf52b8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowFnTestUtils.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; - -import org.joda.time.Instant; -import org.joda.time.ReadableInstant; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * A utility class for testing {@link WindowFn}s. - */ -public class WindowFnTestUtils { - - /** - * Creates a Set of elements to be used as expected output in - * {@link #runWindowFn}. - */ - public static Set set(long... timestamps) { - Set result = new HashSet<>(); - for (long timestamp : timestamps) { - result.add(timestampValue(timestamp)); - } - return result; - } - - /** - * Runs the {@link WindowFn} over the provided input, returning a map - * of windows to the timestamps in those windows. - */ - public static Map> runWindowFn( - WindowFn windowFn, - List timestamps) throws Exception { - - final TestWindowSet windowSet = new TestWindowSet(); - for (final Long timestamp : timestamps) { - for (W window : windowFn.assignWindows( - new TestAssignContext(new Instant(timestamp), windowFn))) { - windowSet.put(window, timestampValue(timestamp)); - } - windowFn.mergeWindows(new TestMergeContext(windowSet, windowFn)); - } - Map> actual = new HashMap<>(); - for (W window : windowSet.windows()) { - actual.put(window, windowSet.get(window)); - } - return actual; - } - - public static Collection assignedWindows( - WindowFn windowFn, long timestamp) throws Exception { - return windowFn.assignWindows(new TestAssignContext(new Instant(timestamp), windowFn)); - } - - private static String timestampValue(long timestamp) { - return "T" + new Instant(timestamp); - } - - /** - * Test implementation of AssignContext. - */ - private static class TestAssignContext - extends WindowFn.AssignContext { - private Instant timestamp; - - public TestAssignContext(Instant timestamp, WindowFn windowFn) { - windowFn.super(); - this.timestamp = timestamp; - } - - @Override - public T element() { - return null; - } - - @Override - public Instant timestamp() { - return timestamp; - } - - @Override - public Collection windows() { - return null; - } - } - - /** - * Test implementation of MergeContext. - */ - private static class TestMergeContext - extends WindowFn.MergeContext { - private TestWindowSet windowSet; - - public TestMergeContext( - TestWindowSet windowSet, WindowFn windowFn) { - windowFn.super(); - this.windowSet = windowSet; - } - - @Override - public Collection windows() { - return windowSet.windows(); - } - - @Override - public void merge(Collection toBeMerged, W mergeResult) { - windowSet.merge(toBeMerged, mergeResult); - } - } - - /** - * A WindowSet useful for testing WindowFns that simply - * collects the placed elements into multisets. - */ - private static class TestWindowSet { - - private Map> elements = new HashMap<>(); - - public void put(W window, V value) { - Set all = elements.get(window); - if (all == null) { - all = new HashSet<>(); - elements.put(window, all); - } - all.add(value); - } - - public void merge(Collection otherWindows, W window) { - if (otherWindows.isEmpty()) { - return; - } - Set merged = new HashSet<>(); - if (elements.containsKey(window) && !otherWindows.contains(window)) { - merged.addAll(elements.get(window)); - } - for (W w : otherWindows) { - if (!elements.containsKey(w)) { - throw new IllegalArgumentException("Tried to merge a non-existent window:" + w); - } - merged.addAll(elements.get(w)); - elements.remove(w); - } - elements.put(window, merged); - } - - public Collection windows() { - return elements.keySet(); - } - - // For testing. - - public Set get(W window) { - return elements.get(window); - } - } - - /** - * Assigns the given {@code timestamp} to windows using the specified {@code windowFn}, and - * verifies that result of {@code windowFn.getOutputTimestamp} for each window is within the - * proper bound. - */ - public static void validateNonInterferingOutputTimes( - WindowFn windowFn, long timestamp) throws Exception { - Collection windows = WindowFnTestUtils.assignedWindows(windowFn, timestamp); - - Instant instant = new Instant(timestamp); - for (W window : windows) { - Instant outputTimestamp = windowFn.getOutputTimeFn().assignOutputTime(instant, window); - assertFalse("getOutputTime must be greater than or equal to input timestamp", - outputTimestamp.isBefore(instant)); - assertFalse("getOutputTime must be less than or equal to the max timestamp", - outputTimestamp.isAfter(window.maxTimestamp())); - } - } - - /** - * Assigns the given {@code timestamp} to windows using the specified {@code windowFn}, and - * verifies that result of {@link WindowFn#getOutputTime windowFn.getOutputTime} for later windows - * (as defined by {@code maxTimestamp} won't prevent the watermark from passing the end of earlier - * windows. - * - *

              This verifies that overlapping windows don't interfere at all. Depending on the - * {@code windowFn} this may be stricter than desired. - */ - public static void validateGetOutputTimestamp( - WindowFn windowFn, long timestamp) throws Exception { - Collection windows = WindowFnTestUtils.assignedWindows(windowFn, timestamp); - List sortedWindows = new ArrayList<>(windows); - Collections.sort(sortedWindows, new Comparator() { - @Override - public int compare(BoundedWindow o1, BoundedWindow o2) { - return o1.maxTimestamp().compareTo(o2.maxTimestamp()); - } - }); - - Instant instant = new Instant(timestamp); - Instant endOfPrevious = null; - for (W window : sortedWindows) { - Instant outputTimestamp = windowFn.getOutputTimeFn().assignOutputTime(instant, window); - if (endOfPrevious == null) { - // If this is the first window, the output timestamp can be anything, as long as it is in - // the valid range. - assertFalse("getOutputTime must be greater than or equal to input timestamp", - outputTimestamp.isBefore(instant)); - assertFalse("getOutputTime must be less than or equal to the max timestamp", - outputTimestamp.isAfter(window.maxTimestamp())); - } else { - // If this is a later window, the output timestamp must be after the end of the previous - // window - assertTrue("getOutputTime must be greater than the end of the previous window", - outputTimestamp.isAfter(endOfPrevious)); - assertFalse("getOutputTime must be less than or equal to the max timestamp", - outputTimestamp.isAfter(window.maxTimestamp())); - } - endOfPrevious = window.maxTimestamp(); - } - } - - /** - * Verifies that later-ending merged windows from any of the timestamps hold up output of - * earlier-ending windows, using the provided {@link WindowFn} and {@link OutputTimeFn}. - * - *

              Given a list of lists of timestamps, where each list is expected to merge into a single - * window with end times in ascending order, assigns and merges windows for each list (as though - * each were a separate key/user session). Then maps each timestamp in the list according to - * {@link OutputTimeFn#assignOutputTime outputTimeFn.assignOutputTime()} and - * {@link OutputTimeFn#combine outputTimeFn.combine()}. - * - *

              Verifies that a overlapping windows do not hold each other up via the watermark. - */ - public static - void validateGetOutputTimestamps( - WindowFn windowFn, - OutputTimeFn outputTimeFn, - List> timestampsPerWindow) throws Exception { - - // Assign windows to each timestamp, then merge them, storing the merged windows in - // a list in corresponding order to timestampsPerWindow - final List windows = new ArrayList<>(); - for (List timestampsForWindow : timestampsPerWindow) { - final Set windowsToMerge = new HashSet<>(); - - for (long timestamp : timestampsForWindow) { - windowsToMerge.addAll( - WindowFnTestUtils.assignedWindows(windowFn, timestamp)); - } - - windowFn.mergeWindows(windowFn.new MergeContext() { - @Override - public Collection windows() { - return windowsToMerge; - } - - @Override - public void merge(Collection toBeMerged, W mergeResult) throws Exception { - windows.add(mergeResult); - } - }); - } - - // Map every list of input timestamps to an output timestamp - final List combinedOutputTimestamps = new ArrayList<>(); - for (int i = 0; i < timestampsPerWindow.size(); ++i) { - List timestampsForWindow = timestampsPerWindow.get(i); - W window = windows.get(i); - - List outputInstants = new ArrayList<>(); - for (long inputTimestamp : timestampsForWindow) { - outputInstants.add(outputTimeFn.assignOutputTime(new Instant(inputTimestamp), window)); - } - - combinedOutputTimestamps.add(OutputTimeFns.combineOutputTimes(outputTimeFn, outputInstants)); - } - - // Consider windows in increasing order of max timestamp; ensure the output timestamp is after - // the max timestamp of the previous - @Nullable W earlierEndingWindow = null; - for (int i = 0; i < windows.size(); ++i) { - W window = windows.get(i); - ReadableInstant outputTimestamp = combinedOutputTimestamps.get(i); - - if (earlierEndingWindow != null) { - assertThat(outputTimestamp, - greaterThan((ReadableInstant) earlierEndingWindow.maxTimestamp())); - } - - earlierEndingWindow = window; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java deleted file mode 100644 index 5a76447fdc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/WindowSupplier.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -import java.io.Serializable; -import java.util.Collection; - -/** - * A {@link Supplier} that returns a static set of {@link BoundedWindow BoundedWindows}. The - * supplier is {@link Serializable}, and handles encoding and decoding the windows with a - * {@link Coder} provided for the windows. - */ -final class WindowSupplier implements Supplier>, Serializable { - private final Coder coder; - private final Collection encodedWindows; - - private transient Collection windows; - - public static WindowSupplier of(Coder coder, Iterable windows) { - ImmutableSet.Builder windowsBuilder = ImmutableSet.builder(); - for (W window : windows) { - try { - windowsBuilder.add(CoderUtils.encodeToByteArray(coder, window)); - } catch (CoderException e) { - throw new IllegalArgumentException( - "Could not encode provided windows with the provided window coder", e); - } - } - return new WindowSupplier(coder, windowsBuilder.build()); - } - - private WindowSupplier(Coder coder, Collection encodedWindows) { - this.coder = coder; - this.encodedWindows = encodedWindows; - } - - @Override - public Collection get() { - if (windows == null) { - decodeWindows(); - } - return windows; - } - - private synchronized void decodeWindows() { - if (windows == null) { - ImmutableList.Builder windowsBuilder = ImmutableList.builder(); - for (byte[] encoded : encodedWindows) { - try { - windowsBuilder.add(CoderUtils.decodeFromByteArray(coder, encoded)); - } catch (CoderException e) { - throw new IllegalArgumentException( - "Could not decode provided windows with the provided window coder", e); - } - } - this.windows = windowsBuilder.build(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/package-info.java deleted file mode 100644 index d6f075d097..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/testing/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines utilities for unit testing Dataflow pipelines. The tests for the {@code PTransform}s and - * examples included the Dataflow SDK provide examples of using these utilities. - */ -package com.google.cloud.dataflow.sdk.testing; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Aggregator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Aggregator.java deleted file mode 100644 index 7e56ddac0d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Aggregator.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; - -/** - * An {@code Aggregator} enables monitoring of values of type {@code InputT}, - * to be combined across all bundles. - * - *

              Aggregators are created by calling {@link DoFn#createAggregator}, - * typically from the {@link DoFn} constructor. Elements can be added to the - * {@code Aggregator} by calling {@link Aggregator#addValue}. - * - *

              Aggregators are visible in the monitoring UI, when the pipeline is run - * using DataflowPipelineRunner or BlockingDataflowPipelineRunner, along with - * their current value. Aggregators may not become visible until the system - * begins executing the ParDo transform that created them and/or their initial - * value is changed. - * - *

              Example: - *

               {@code
              - * class MyDoFn extends DoFn {
              - *   private Aggregator myAggregator;
              - *
              - *   public MyDoFn() {
              - *     myAggregator = createAggregator("myAggregator", new Sum.SumIntegerFn());
              - *   }
              - *
              - *   @Override
              - *   public void processElement(ProcessContext c) {
              - *     myAggregator.addValue(1);
              - *   }
              - * }
              - * } 
              - * - * @param the type of input values - * @param the type of output values - */ -public interface Aggregator { - - /** - * Adds a new value into the Aggregator. - */ - void addValue(InputT value); - - /** - * Returns the name of the Aggregator. - */ - String getName(); - - /** - * Returns the {@link CombineFn}, which combines input elements in the - * aggregator. - */ - CombineFn getCombineFn(); - - // TODO: Consider the following additional API conveniences: - // - In addition to createAggregator(), consider adding getAggregator() to - // avoid the need to store the aggregator locally in a DoFn, i.e., create - // if not already present. - // - Add a shortcut for the most common aggregator: - // c.createAggregator("name", new Sum.SumIntegerFn()). -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AggregatorRetriever.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AggregatorRetriever.java deleted file mode 100644 index 4bbea85f52..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AggregatorRetriever.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import java.util.Collection; - -/** - * An internal class for extracting {@link Aggregator Aggregators} from {@link DoFn DoFns}. - */ -public final class AggregatorRetriever { - private AggregatorRetriever() { - // do not instantiate - } - - /** - * Returns the {@link Aggregator Aggregators} created by the provided {@link DoFn}. - */ - public static Collection> getAggregators(DoFn fn) { - return fn.getAggregators(); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AppliedPTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AppliedPTransform.java deleted file mode 100644 index 7b3d87dfcf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/AppliedPTransform.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.base.MoreObjects; -import com.google.common.base.Objects; - -/** - * Represents the application of a {@link PTransform} to a specific input to produce - * a specific output. - * - *

              For internal use. - * - * @param transform input type - * @param transform output type - * @param transform type - */ -public class AppliedPTransform - > { - - private final String fullName; - private final InputT input; - private final OutputT output; - private final TransformT transform; - - private AppliedPTransform(String fullName, InputT input, OutputT output, TransformT transform) { - this.input = input; - this.output = output; - this.transform = transform; - this.fullName = fullName; - } - - public static > - AppliedPTransform of( - String fullName, InputT input, OutputT output, TransformT transform) { - return new AppliedPTransform(fullName, input, output, transform); - } - - public String getFullName() { - return fullName; - } - - public InputT getInput() { - return input; - } - - public OutputT getOutput() { - return output; - } - - public TransformT getTransform() { - return transform; - } - - @Override - public int hashCode() { - return Objects.hashCode(getFullName(), getInput(), getOutput(), getTransform()); - } - - @Override - public boolean equals(Object other) { - if (other instanceof AppliedPTransform) { - AppliedPTransform that = (AppliedPTransform) other; - return Objects.equal(this.getFullName(), that.getFullName()) - && Objects.equal(this.getInput(), that.getInput()) - && Objects.equal(this.getOutput(), that.getOutput()) - && Objects.equal(this.getTransform(), that.getTransform()); - } else { - return false; - } - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("fullName", getFullName()) - .add("input", getInput()) - .add("output", getOutput()) - .add("transform", getTransform()) - .toString(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java deleted file mode 100644 index a995431b7a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantiles.java +++ /dev/null @@ -1,778 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.CustomCoder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn.Accumulator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.WeightedValue; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import com.google.common.collect.UnmodifiableIterator; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.PriorityQueue; - -import javax.annotation.Nullable; - -/** - * {@code PTransform}s for getting an idea of a {@code PCollection}'s - * data distribution using approximate {@code N}-tiles (e.g. quartiles, - * percentiles, etc.), either globally or per-key. - */ -public class ApproximateQuantiles { - private ApproximateQuantiles() { - // do not instantiate - } - - /** - * Returns a {@code PTransform} that takes a {@code PCollection} - * and returns a {@code PCollection>} whose single value is a - * {@code List} of the approximate {@code N}-tiles of the elements - * of the input {@code PCollection}. This gives an idea of the - * distribution of the input elements. - * - *

              The computed {@code List} is of size {@code numQuantiles}, - * and contains the input elements' minimum value, - * {@code numQuantiles-2} intermediate values, and maximum value, in - * sorted order, using the given {@code Comparator} to order values. - * To compute traditional {@code N}-tiles, one should use - * {@code ApproximateQuantiles.globally(compareFn, N+1)}. - * - *

              If there are fewer input elements than {@code numQuantiles}, - * then the result {@code List} will contain all the input elements, - * in sorted order. - * - *

              The argument {@code Comparator} must be {@code Serializable}. - * - *

              Example of use: - *

               {@code
              -   * PCollection pc = ...;
              -   * PCollection> quantiles =
              -   *     pc.apply(ApproximateQuantiles.globally(stringCompareFn, 11));
              -   * } 
              - * - * @param the type of the elements in the input {@code PCollection} - * @param numQuantiles the number of elements in the resulting - * quantile values {@code List} - * @param compareFn the function to use to order the elements - */ - public static & Serializable> - PTransform, PCollection>> globally( - int numQuantiles, ComparatorT compareFn) { - return Combine.globally( - ApproximateQuantilesCombineFn.create(numQuantiles, compareFn)); - } - - /** - * Like {@link #globally(int, Comparator)}, but sorts using the - * elements' natural ordering. - * - * @param the type of the elements in the input {@code PCollection} - * @param numQuantiles the number of elements in the resulting - * quantile values {@code List} - */ - public static > - PTransform, PCollection>> globally(int numQuantiles) { - return Combine.globally( - ApproximateQuantilesCombineFn.create(numQuantiles)); - } - - /** - * Returns a {@code PTransform} that takes a - * {@code PCollection>} and returns a - * {@code PCollection>>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to a {@code List} of the approximate - * {@code N}-tiles of the values associated with that key in the - * input {@code PCollection}. This gives an idea of the - * distribution of the input values for each key. - * - *

              Each of the computed {@code List}s is of size {@code numQuantiles}, - * and contains the input values' minimum value, - * {@code numQuantiles-2} intermediate values, and maximum value, in - * sorted order, using the given {@code Comparator} to order values. - * To compute traditional {@code N}-tiles, one should use - * {@code ApproximateQuantiles.perKey(compareFn, N+1)}. - * - *

              If a key has fewer than {@code numQuantiles} values - * associated with it, then that key's output {@code List} will - * contain all the key's input values, in sorted order. - * - *

              The argument {@code Comparator} must be {@code Serializable}. - * - *

              Example of use: - *

               {@code
              -   * PCollection> pc = ...;
              -   * PCollection>> quantilesPerKey =
              -   *     pc.apply(ApproximateQuantiles.perKey(stringCompareFn, 11));
              -   * } 
              - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - * - * @param the type of the keys in the input and output - * {@code PCollection}s - * @param the type of the values in the input {@code PCollection} - * @param numQuantiles the number of elements in the resulting - * quantile values {@code List} - * @param compareFn the function to use to order the elements - */ - public static & Serializable> - PTransform>, PCollection>>> - perKey(int numQuantiles, ComparatorT compareFn) { - return Combine.perKey( - ApproximateQuantilesCombineFn.create(numQuantiles, compareFn) - .asKeyedFn()); - } - - /** - * Like {@link #perKey(int, Comparator)}, but sorts - * values using the their natural ordering. - * - * @param the type of the keys in the input and output - * {@code PCollection}s - * @param the type of the values in the input {@code PCollection} - * @param numQuantiles the number of elements in the resulting - * quantile values {@code List} - */ - public static > - PTransform>, PCollection>>> - perKey(int numQuantiles) { - return Combine.perKey( - ApproximateQuantilesCombineFn.create(numQuantiles) - .asKeyedFn()); - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * The {@code ApproximateQuantilesCombineFn} combiner gives an idea - * of the distribution of a collection of values using approximate - * {@code N}-tiles. The output of this combiner is a {@code List} - * of size {@code numQuantiles}, containing the input values' - * minimum value, {@code numQuantiles-2} intermediate values, and - * maximum value, in sorted order, so for traditional - * {@code N}-tiles, one should use - * {@code ApproximateQuantilesCombineFn#create(N+1)}. - * - *

              If there are fewer values to combine than - * {@code numQuantiles}, then the result {@code List} will contain all the - * values being combined, in sorted order. - * - *

              Values are ordered using either a specified - * {@code Comparator} or the values' natural ordering. - * - *

              To evaluate the quantiles we use the "New Algorithm" described here: - *

              -   *   [MRL98] Manku, Rajagopalan & Lindsay, "Approximate Medians and other
              -   *   Quantiles in One Pass and with Limited Memory", Proc. 1998 ACM
              -   *   SIGMOD, Vol 27, No 2, p 426-435, June 1998.
              -   *   http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.6.6513&rep=rep1&type=pdf
              -   * 
              - * - *

              The default error bound is {@code 1 / N}, though in practice - * the accuracy tends to be much better. See - * {@link #create(int, Comparator, long, double)} for - * more information about the meaning of {@code epsilon}, and - * {@link #withEpsilon} for a convenient way to adjust it. - * - * @param the type of the values being combined - */ - public static class ApproximateQuantilesCombineFn - & Serializable> - extends AccumulatingCombineFn, List> { - - /** - * The cost (in time and space) to compute quantiles to a given - * accuracy is a function of the total number of elements in the - * data set. If an estimate is not known or specified, we use - * this as an upper bound. If this is too low, errors may exceed - * the requested tolerance; if too high, efficiency may be - * non-optimal. The impact is logarithmic with respect to this - * value, so this default should be fine for most uses. - */ - public static final long DEFAULT_MAX_NUM_ELEMENTS = (long) 1e9; - - /** The comparison function to use. */ - private final ComparatorT compareFn; - - /** - * Number of quantiles to produce. The size of the final output - * list, including the minimum and maximum, is numQuantiles. - */ - private final int numQuantiles; - - /** The size of the buffers, corresponding to k in the referenced paper. */ - private final int bufferSize; - - /** The number of buffers, corresponding to b in the referenced paper. */ - private final int numBuffers; - - private final long maxNumElements; - - private ApproximateQuantilesCombineFn( - int numQuantiles, - ComparatorT compareFn, - int bufferSize, - int numBuffers, - long maxNumElements) { - checkArgument(numQuantiles >= 2); - checkArgument(bufferSize >= 2); - checkArgument(numBuffers >= 2); - this.numQuantiles = numQuantiles; - this.compareFn = compareFn; - this.bufferSize = bufferSize; - this.numBuffers = numBuffers; - this.maxNumElements = maxNumElements; - } - - /** - * Returns an approximate quantiles combiner with the given - * {@code compareFn} and desired number of quantiles. A total of - * {@code numQuantiles} elements will appear in the output list, - * including the minimum and maximum. - * - *

              The {@code Comparator} must be {@code Serializable}. - * - *

              The default error bound is {@code 1 / numQuantiles}, which - * holds as long as the number of elements is less than - * {@link #DEFAULT_MAX_NUM_ELEMENTS}. - */ - public static & Serializable> - ApproximateQuantilesCombineFn create( - int numQuantiles, ComparatorT compareFn) { - return create( - numQuantiles, compareFn, DEFAULT_MAX_NUM_ELEMENTS, 1.0 / numQuantiles); - } - - /** - * Like {@link #create(int, Comparator)}, but sorts values using their natural ordering. - */ - public static > - ApproximateQuantilesCombineFn> create(int numQuantiles) { - return create(numQuantiles, new Top.Largest()); - } - - /** - * Returns an {@code ApproximateQuantilesCombineFn} that's like - * this one except that it uses the specified {@code epsilon} - * value. Does not modify this combiner. - * - *

              See {@link #create(int, Comparator, long, - * double)} for more information about the meaning of - * {@code epsilon}. - */ - public ApproximateQuantilesCombineFn withEpsilon(double epsilon) { - return create(numQuantiles, compareFn, maxNumElements, epsilon); - } - - /** - * Returns an {@code ApproximateQuantilesCombineFn} that's like - * this one except that it uses the specified {@code maxNumElements} - * value. Does not modify this combiner. - * - *

              See {@link #create(int, Comparator, long, double)} for more - * information about the meaning of {@code maxNumElements}. - */ - public ApproximateQuantilesCombineFn withMaxInputSize( - long maxNumElements) { - return create(numQuantiles, compareFn, maxNumElements, maxNumElements); - } - - /** - * Creates an approximate quantiles combiner with the given - * {@code compareFn} and desired number of quantiles. A total of - * {@code numQuantiles} elements will appear in the output list, - * including the minimum and maximum. - * - *

              The {@code Comparator} must be {@code Serializable}. - * - *

              The default error bound is {@code epsilon}, which holds as long - * as the number of elements is less than {@code maxNumElements}. - * Specifically, if one considers the input as a sorted list x_1, ..., x_N, - * then the distance between the each exact quantile x_c and its - * approximation x_c' is bounded by {@code |c - c'| < epsilon * N}. - * Note that these errors are worst-case scenarios; in practice the accuracy - * tends to be much better. - */ - public static & Serializable> - ApproximateQuantilesCombineFn create( - int numQuantiles, - ComparatorT compareFn, - long maxNumElements, - double epsilon) { - // Compute optimal b and k. - int b = 2; - while ((b - 2) * (1 << (b - 2)) < epsilon * maxNumElements) { - b++; - } - b--; - int k = Math.max(2, (int) Math.ceil(maxNumElements / (1 << (b - 1)))); - return new ApproximateQuantilesCombineFn( - numQuantiles, compareFn, k, b, maxNumElements); - } - - @Override - public QuantileState createAccumulator() { - return QuantileState.empty(compareFn, numQuantiles, numBuffers, bufferSize); - } - - @Override - public Coder> getAccumulatorCoder( - CoderRegistry registry, Coder elementCoder) { - return new QuantileStateCoder<>(compareFn, elementCoder); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("numQuantiles", numQuantiles) - .withLabel("Quantile Count")) - .add(DisplayData.item("comparer", compareFn.getClass()) - .withLabel("Record Comparer")); - } - } - - /** - * Compact summarization of a collection on which quantiles can be estimated. - */ - static class QuantileState & Serializable> - implements Accumulator, List> { - - private ComparatorT compareFn; - private int numQuantiles; - private int numBuffers; - private int bufferSize; - - @Nullable - private T min; - - @Nullable - private T max; - - /** - * The set of buffers, ordered by level from smallest to largest. - */ - private PriorityQueue> buffers; - - /** - * The algorithm requires that the manipulated buffers always be filled - * to capacity to perform the collapse operation. This operation can - * be extended to buffers of varying sizes by introducing the notion of - * fractional weights, but it's easier to simply combine the remainders - * from all shards into new, full buffers and then take them into account - * when computing the final output. - */ - private List unbufferedElements = Lists.newArrayList(); - - private QuantileState( - ComparatorT compareFn, - int numQuantiles, - @Nullable T min, - @Nullable T max, - int numBuffers, - int bufferSize, - Collection unbufferedElements, - Collection> buffers) { - this.compareFn = compareFn; - this.numQuantiles = numQuantiles; - this.numBuffers = numBuffers; - this.bufferSize = bufferSize; - this.buffers = new PriorityQueue<>(numBuffers + 1); - this.min = min; - this.max = max; - this.unbufferedElements.addAll(unbufferedElements); - this.buffers.addAll(buffers); - } - - public static & Serializable> - QuantileState empty( - ComparatorT compareFn, int numQuantiles, int numBuffers, int bufferSize) { - return new QuantileState( - compareFn, - numQuantiles, - null, /* min */ - null, /* max */ - numBuffers, - bufferSize, - Collections.emptyList(), - Collections.>emptyList()); - } - - public static & Serializable> - QuantileState singleton( - ComparatorT compareFn, int numQuantiles, T elem, int numBuffers, int bufferSize) { - return new QuantileState( - compareFn, - numQuantiles, - elem, /* min */ - elem, /* max */ - numBuffers, - bufferSize, - Collections.singletonList(elem), - Collections.>emptyList()); - } - - /** - * Add a new element to the collection being summarized by this state. - */ - @Override - public void addInput(T elem) { - if (isEmpty()) { - min = max = elem; - } else if (compareFn.compare(elem, min) < 0) { - min = elem; - } else if (compareFn.compare(elem, max) > 0) { - max = elem; - } - addUnbuffered(elem); - } - - /** - * Add a new buffer to the unbuffered list, creating a new buffer and - * collapsing if needed. - */ - private void addUnbuffered(T elem) { - unbufferedElements.add(elem); - if (unbufferedElements.size() == bufferSize) { - Collections.sort(unbufferedElements, compareFn); - buffers.add(new QuantileBuffer(unbufferedElements)); - unbufferedElements = Lists.newArrayListWithCapacity(bufferSize); - collapseIfNeeded(); - } - } - - /** - * Updates this as if adding all elements seen by other. - * - *

              Note that this ignores the {@code Comparator} of the other {@link QuantileState}. In - * practice, they should generally be equal, but this method tolerates a mismatch. - */ - @Override - public void mergeAccumulator(QuantileState other) { - if (other.isEmpty()) { - return; - } - if (min == null || compareFn.compare(other.min, min) < 0) { - min = other.min; - } - if (max == null || compareFn.compare(other.max, max) > 0) { - max = other.max; - } - for (T elem : other.unbufferedElements) { - addUnbuffered(elem); - } - buffers.addAll(other.buffers); - collapseIfNeeded(); - } - - public boolean isEmpty() { - return unbufferedElements.size() == 0 && buffers.size() == 0; - } - - private void collapseIfNeeded() { - while (buffers.size() > numBuffers) { - List> toCollapse = Lists.newArrayList(); - toCollapse.add(buffers.poll()); - toCollapse.add(buffers.poll()); - int minLevel = toCollapse.get(1).level; - while (!buffers.isEmpty() && buffers.peek().level == minLevel) { - toCollapse.add(buffers.poll()); - } - buffers.add(collapse(toCollapse)); - } - } - - private QuantileBuffer collapse( - Iterable> buffers) { - int newLevel = 0; - long newWeight = 0; - for (QuantileBuffer buffer : buffers) { - // As presented in the paper, there should always be at least two - // buffers of the same (minimal) level to collapse, but it is possible - // to violate this condition when combining buffers from independently - // computed shards. If they differ we take the max. - newLevel = Math.max(newLevel, buffer.level + 1); - newWeight += buffer.weight; - } - List newElements = - interpolate(buffers, bufferSize, newWeight, offset(newWeight)); - return new QuantileBuffer<>(newLevel, newWeight, newElements); - } - - /** - * If the weight is even, we must round up or down. Alternate between these two options to - * avoid a bias. - */ - private long offset(long newWeight) { - if (newWeight % 2 == 1) { - return (newWeight + 1) / 2; - } else { - offsetJitter = 2 - offsetJitter; - return (newWeight + offsetJitter) / 2; - } - } - - /** For alternating between biasing up and down in the above even weight collapse operation. */ - private int offsetJitter = 0; - - - /** - * Emulates taking the ordered union of all elements in buffers, repeated - * according to their weight, and picking out the (k * step + offset)-th - * elements of this list for {@code 0 <= k < count}. - */ - private List interpolate(Iterable> buffers, - int count, double step, double offset) { - List>> iterators = Lists.newArrayList(); - for (QuantileBuffer buffer : buffers) { - iterators.add(buffer.sizedIterator()); - } - // Each of the buffers is already sorted by element. - Iterator> sorted = Iterators.mergeSorted( - iterators, - new Comparator>() { - @Override - public int compare(WeightedValue a, WeightedValue b) { - return compareFn.compare(a.getValue(), b.getValue()); - } - }); - - List newElements = Lists.newArrayListWithCapacity(count); - WeightedValue weightedElement = sorted.next(); - double current = weightedElement.getWeight(); - for (int j = 0; j < count; j++) { - double target = j * step + offset; - while (current <= target && sorted.hasNext()) { - weightedElement = sorted.next(); - current += weightedElement.getWeight(); - } - newElements.add(weightedElement.getValue()); - } - return newElements; - } - - /** - * Outputs numQuantiles elements consisting of the minimum, maximum, and - * numQuantiles - 2 evenly spaced intermediate elements. - * - *

              Returns the empty list if no elements have been added. - */ - @Override - public List extractOutput() { - if (isEmpty()) { - return Lists.newArrayList(); - } - long totalCount = unbufferedElements.size(); - for (QuantileBuffer buffer : buffers) { - totalCount += bufferSize * buffer.weight; - } - List> all = Lists.newArrayList(buffers); - if (!unbufferedElements.isEmpty()) { - Collections.sort(unbufferedElements, compareFn); - all.add(new QuantileBuffer<>(unbufferedElements)); - } - double step = 1.0 * totalCount / (numQuantiles - 1); - double offset = (1.0 * totalCount - 1) / (numQuantiles - 1); - List quantiles = interpolate(all, numQuantiles - 2, step, offset); - quantiles.add(0, min); - quantiles.add(max); - return quantiles; - } - } - - /** - * A single buffer in the sense of the referenced algorithm. - */ - private static class QuantileBuffer implements Comparable> { - private int level; - private long weight; - private List elements; - - public QuantileBuffer(List elements) { - this(0, 1, elements); - } - - public QuantileBuffer(int level, long weight, List elements) { - this.level = level; - this.weight = weight; - this.elements = elements; - } - - @Override - public int compareTo(QuantileBuffer other) { - return this.level - other.level; - } - - @Override - public String toString() { - return "QuantileBuffer[" - + "level=" + level - + ", weight=" - + weight + ", elements=" + elements + "]"; - } - - public Iterator> sizedIterator() { - return new UnmodifiableIterator>() { - Iterator iter = elements.iterator(); - @Override - public boolean hasNext() { - return iter.hasNext(); - } - @Override public WeightedValue next() { - return WeightedValue.of(iter.next(), weight); - } - }; - } - } - - /** - * Coder for QuantileState. - */ - private static class QuantileStateCoder & Serializable> - extends CustomCoder> { - private final ComparatorT compareFn; - private final Coder elementCoder; - private final Coder> elementListCoder; - private final Coder intCoder = BigEndianIntegerCoder.of(); - - public QuantileStateCoder(ComparatorT compareFn, Coder elementCoder) { - this.compareFn = compareFn; - this.elementCoder = elementCoder; - this.elementListCoder = ListCoder.of(elementCoder); - } - - @Override - public void encode( - QuantileState state, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - Coder.Context nestedContext = context.nested(); - intCoder.encode(state.numQuantiles, outStream, nestedContext); - intCoder.encode(state.bufferSize, outStream, nestedContext); - elementCoder.encode(state.min, outStream, nestedContext); - elementCoder.encode(state.max, outStream, nestedContext); - elementListCoder.encode( - state.unbufferedElements, outStream, nestedContext); - BigEndianIntegerCoder.of().encode( - state.buffers.size(), outStream, nestedContext); - for (QuantileBuffer buffer : state.buffers) { - encodeBuffer(buffer, outStream, nestedContext); - } - } - - @Override - public QuantileState decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - Coder.Context nestedContext = context.nested(); - int numQuantiles = intCoder.decode(inStream, nestedContext); - int bufferSize = intCoder.decode(inStream, nestedContext); - T min = elementCoder.decode(inStream, nestedContext); - T max = elementCoder.decode(inStream, nestedContext); - List unbufferedElements = - elementListCoder.decode(inStream, nestedContext); - int numBuffers = - BigEndianIntegerCoder.of().decode(inStream, nestedContext); - List> buffers = new ArrayList<>(numBuffers); - for (int i = 0; i < numBuffers; i++) { - buffers.add(decodeBuffer(inStream, nestedContext)); - } - return new QuantileState( - compareFn, numQuantiles, min, max, numBuffers, bufferSize, unbufferedElements, buffers); - } - - private void encodeBuffer( - QuantileBuffer buffer, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - DataOutputStream outData = new DataOutputStream(outStream); - outData.writeInt(buffer.level); - outData.writeLong(buffer.weight); - elementListCoder.encode(buffer.elements, outStream, context); - } - - private QuantileBuffer decodeBuffer( - InputStream inStream, Coder.Context context) - throws IOException, CoderException { - DataInputStream inData = new DataInputStream(inStream); - return new QuantileBuffer<>( - inData.readInt(), - inData.readLong(), - elementListCoder.decode(inStream, context)); - } - - /** - * Notifies ElementByteSizeObserver about the byte size of the - * encoded value using this coder. - */ - @Override - public void registerByteSizeObserver( - QuantileState state, - ElementByteSizeObserver observer, - Coder.Context context) - throws Exception { - Coder.Context nestedContext = context.nested(); - elementCoder.registerByteSizeObserver( - state.min, observer, nestedContext); - elementCoder.registerByteSizeObserver( - state.max, observer, nestedContext); - elementListCoder.registerByteSizeObserver( - state.unbufferedElements, observer, nestedContext); - - BigEndianIntegerCoder.of().registerByteSizeObserver( - state.buffers.size(), observer, nestedContext); - for (QuantileBuffer buffer : state.buffers) { - observer.update(4L + 8); - - elementListCoder.registerByteSizeObserver( - buffer.elements, observer, nestedContext); - } - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "QuantileState.ElementCoder must be deterministic", - elementCoder); - verifyDeterministic( - "QuantileState.ElementListCoder must be deterministic", - elementListCoder); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java deleted file mode 100644 index ff5e131012..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUnique.java +++ /dev/null @@ -1,467 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.hash.Hashing; -import com.google.common.hash.HashingOutputStream; -import com.google.common.io.ByteStreams; - -import org.apache.avro.reflect.Nullable; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.PriorityQueue; - -/** - * {@code PTransform}s for estimating the number of distinct elements - * in a {@code PCollection}, or the number of distinct values - * associated with each key in a {@code PCollection} of {@code KV}s. - */ -public class ApproximateUnique { - - /** - * Returns a {@code PTransform} that takes a {@code PCollection} - * and returns a {@code PCollection} containing a single value - * that is an estimate of the number of distinct elements in the - * input {@code PCollection}. - * - *

              The {@code sampleSize} parameter controls the estimation - * error. The error is about {@code 2 / sqrt(sampleSize)}, so for - * {@code ApproximateUnique.globally(10000)} the estimation error is - * about 2%. Similarly, for {@code ApproximateUnique.of(16)} the - * estimation error is about 50%. If there are fewer than - * {@code sampleSize} distinct elements then the returned result - * will be exact with extremely high probability (the chance of a - * hash collision is about {@code sampleSize^2 / 2^65}). - * - *

              This transform approximates the number of elements in a set - * by computing the top {@code sampleSize} hash values, and using - * that to extrapolate the size of the entire set of hash values by - * assuming the rest of the hash values are as densely distributed - * as the top {@code sampleSize}. - * - *

              See also {@link #globally(double)}. - * - *

              Example of use: - *

               {@code
              -   * PCollection pc = ...;
              -   * PCollection approxNumDistinct =
              -   *     pc.apply(ApproximateUnique.globally(1000));
              -   * } 
              - * - * @param the type of the elements in the input {@code PCollection} - * @param sampleSize the number of entries in the statistical - * sample; the higher this number, the more accurate the - * estimate will be; should be {@code >= 16} - * @throws IllegalArgumentException if the {@code sampleSize} - * argument is too small - */ - public static Globally globally(int sampleSize) { - return new Globally<>(sampleSize); - } - - /** - * Like {@link #globally(int)}, but specifies the desired maximum - * estimation error instead of the sample size. - * - * @param the type of the elements in the input {@code PCollection} - * @param maximumEstimationError the maximum estimation error, which - * should be in the range {@code [0.01, 0.5]} - * @throws IllegalArgumentException if the - * {@code maximumEstimationError} argument is out of range - */ - public static Globally globally(double maximumEstimationError) { - return new Globally<>(maximumEstimationError); - } - - /** - * Returns a {@code PTransform} that takes a - * {@code PCollection>} and returns a - * {@code PCollection>} that contains an output element - * mapping each distinct key in the input {@code PCollection} to an - * estimate of the number of distinct values associated with that - * key in the input {@code PCollection}. - * - *

              See {@link #globally(int)} for an explanation of the - * {@code sampleSize} parameter. A separate sampling is computed - * for each distinct key of the input. - * - *

              See also {@link #perKey(double)}. - * - *

              Example of use: - *

               {@code
              -   * PCollection> pc = ...;
              -   * PCollection> approxNumDistinctPerKey =
              -   *     pc.apply(ApproximateUnique.perKey(1000));
              -   * } 
              - * - * @param the type of the keys in the input and output - * {@code PCollection}s - * @param the type of the values in the input {@code PCollection} - * @param sampleSize the number of entries in the statistical - * sample; the higher this number, the more accurate the - * estimate will be; should be {@code >= 16} - * @throws IllegalArgumentException if the {@code sampleSize} - * argument is too small - */ - public static PerKey perKey(int sampleSize) { - return new PerKey<>(sampleSize); - } - - /** - * Like {@link #perKey(int)}, but specifies the desired maximum - * estimation error instead of the sample size. - * - * @param the type of the keys in the input and output - * {@code PCollection}s - * @param the type of the values in the input {@code PCollection} - * @param maximumEstimationError the maximum estimation error, which - * should be in the range {@code [0.01, 0.5]} - * @throws IllegalArgumentException if the - * {@code maximumEstimationError} argument is out of range - */ - public static PerKey perKey(double maximumEstimationError) { - return new PerKey<>(maximumEstimationError); - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * {@code PTransform} for estimating the number of distinct elements - * in a {@code PCollection}. - * - * @param the type of the elements in the input {@code PCollection} - */ - static class Globally extends PTransform, PCollection> { - - /** - * The number of entries in the statistical sample; the higher this number, - * the more accurate the estimate will be. - */ - private final long sampleSize; - - /** - * The desired maximum estimation error or null if not specified. - */ - @Nullable - private final Double maximumEstimationError; - - /** - * @see ApproximateUnique#globally(int) - */ - public Globally(int sampleSize) { - if (sampleSize < 16) { - throw new IllegalArgumentException( - "ApproximateUnique needs a sampleSize " - + ">= 16 for an estimation error <= 50%. " - + "In general, the estimation " - + "error is about 2 / sqrt(sampleSize)."); - } - - this.sampleSize = sampleSize; - this.maximumEstimationError = null; - } - - /** - * @see ApproximateUnique#globally(double) - */ - public Globally(double maximumEstimationError) { - if (maximumEstimationError < 0.01 || maximumEstimationError > 0.5) { - throw new IllegalArgumentException( - "ApproximateUnique needs an " - + "estimation error between 1% (0.01) and 50% (0.5)."); - } - - this.sampleSize = sampleSizeFromEstimationError(maximumEstimationError); - this.maximumEstimationError = maximumEstimationError; - } - - @Override - public PCollection apply(PCollection input) { - Coder coder = input.getCoder(); - return input.apply( - Combine.globally( - new ApproximateUniqueCombineFn<>(sampleSize, coder))); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - ApproximateUnique.populateDisplayData(builder, sampleSize, maximumEstimationError); - } - } - - /** - * {@code PTransform} for estimating the number of distinct values - * associated with each key in a {@code PCollection} of {@code KV}s. - * - * @param the type of the keys in the input and output - * {@code PCollection}s - * @param the type of the values in the input {@code PCollection} - */ - static class PerKey - extends PTransform>, PCollection>> { - - /** - * The number of entries in the statistical sample; the higher this number, - * the more accurate the estimate will be. - */ - private final long sampleSize; - - /** - * The the desired maximum estimation error or null if not specified. - */ - @Nullable - private final Double maximumEstimationError; - - /** - * @see ApproximateUnique#perKey(int) - */ - public PerKey(int sampleSize) { - if (sampleSize < 16) { - throw new IllegalArgumentException( - "ApproximateUnique needs a " - + "sampleSize >= 16 for an estimation error <= 50%. In general, " - + "the estimation error is about 2 / sqrt(sampleSize)."); - } - - this.sampleSize = sampleSize; - this.maximumEstimationError = null; - } - - /** - * @see ApproximateUnique#perKey(double) - */ - public PerKey(double estimationError) { - if (estimationError < 0.01 || estimationError > 0.5) { - throw new IllegalArgumentException( - "ApproximateUnique.PerKey needs an " - + "estimation error between 1% (0.01) and 50% (0.5)."); - } - - this.sampleSize = sampleSizeFromEstimationError(estimationError); - this.maximumEstimationError = estimationError; - } - - @Override - public PCollection> apply(PCollection> input) { - Coder> inputCoder = input.getCoder(); - if (!(inputCoder instanceof KvCoder)) { - throw new IllegalStateException( - "ApproximateUnique.PerKey requires its input to use KvCoder"); - } - @SuppressWarnings("unchecked") - final Coder coder = ((KvCoder) inputCoder).getValueCoder(); - - return input.apply( - Combine.perKey(new ApproximateUniqueCombineFn<>( - sampleSize, coder).asKeyedFn())); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - ApproximateUnique.populateDisplayData(builder, sampleSize, maximumEstimationError); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * {@code CombineFn} that computes an estimate of the number of - * distinct values that were combined. - * - *

              Hashes input elements, computes the top {@code sampleSize} - * hash values, and uses those to extrapolate the size of the entire - * set of hash values by assuming the rest of the hash values are as - * densely distributed as the top {@code sampleSize}. - * - *

              Used to implement - * {@link #globally(int) ApproximatUnique.globally(...)} and - * {@link #perKey(int) ApproximatUnique.perKey(...)}. - * - * @param the type of the values being combined - */ - public static class ApproximateUniqueCombineFn extends - CombineFn { - - /** - * The size of the space of hashes returned by the hash function. - */ - static final double HASH_SPACE_SIZE = - Long.MAX_VALUE - (double) Long.MIN_VALUE; - - /** - * A heap utility class to efficiently track the largest added elements. - */ - public static class LargestUnique implements Serializable { - private PriorityQueue heap = new PriorityQueue<>(); - private final long sampleSize; - - /** - * Creates a heap to track the largest {@code sampleSize} elements. - * - * @param sampleSize the size of the heap - */ - public LargestUnique(long sampleSize) { - this.sampleSize = sampleSize; - } - - /** - * Adds a value to the heap, returning whether the value is (large enough - * to be) in the heap. - */ - public boolean add(Long value) { - if (heap.contains(value)) { - return true; - } else if (heap.size() < sampleSize) { - heap.add(value); - return true; - } else if (value > heap.element()) { - heap.remove(); - heap.add(value); - return true; - } else { - return false; - } - } - - /** - * Returns the values in the heap, ordered largest to smallest. - */ - public List extractOrderedList() { - // The only way to extract the order from the heap is element-by-element - // from smallest to largest. - Long[] array = new Long[heap.size()]; - for (int i = heap.size() - 1; i >= 0; i--) { - array[i] = heap.remove(); - } - return Arrays.asList(array); - } - } - - private final long sampleSize; - private final Coder coder; - - public ApproximateUniqueCombineFn(long sampleSize, Coder coder) { - this.sampleSize = sampleSize; - this.coder = coder; - } - - @Override - public LargestUnique createAccumulator() { - return new LargestUnique(sampleSize); - } - - @Override - public LargestUnique addInput(LargestUnique heap, T input) { - try { - heap.add(hash(input, coder)); - return heap; - } catch (Throwable e) { - throw new RuntimeException(e); - } - } - - @Override - public LargestUnique mergeAccumulators(Iterable heaps) { - Iterator iterator = heaps.iterator(); - LargestUnique heap = iterator.next(); - while (iterator.hasNext()) { - List largestHashes = iterator.next().extractOrderedList(); - for (long hash : largestHashes) { - if (!heap.add(hash)) { - break; // The remainder of this list is all smaller. - } - } - } - return heap; - } - - @Override - public Long extractOutput(LargestUnique heap) { - List largestHashes = heap.extractOrderedList(); - if (largestHashes.size() < sampleSize) { - return (long) largestHashes.size(); - } else { - long smallestSampleHash = largestHashes.get(largestHashes.size() - 1); - double sampleSpaceSize = Long.MAX_VALUE - (double) smallestSampleHash; - // This formula takes into account the possibility of hash collisions, - // which become more likely than not for 2^32 distinct elements. - // Note that log(1+x) ~ x for small x, so for sampleSize << maxHash - // log(1 - sampleSize/sampleSpace) / log(1 - 1/sampleSpace) ~ sampleSize - // and hence estimate ~ sampleSize * HASH_SPACE_SIZE / sampleSpace - // as one would expect. - double estimate = Math.log1p(-sampleSize / sampleSpaceSize) - / Math.log1p(-1 / sampleSpaceSize) - * HASH_SPACE_SIZE / sampleSpaceSize; - return Math.round(estimate); - } - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, - Coder inputCoder) { - return SerializableCoder.of(LargestUnique.class); - } - - /** - * Encodes the given element using the given coder and hashes the encoding. - */ - static long hash(T element, Coder coder) throws CoderException, IOException { - try (HashingOutputStream stream = - new HashingOutputStream(Hashing.murmur3_128(), ByteStreams.nullOutputStream())) { - coder.encode(element, stream, Context.OUTER); - return stream.hash().asLong(); - } - } - } - - /** - * Computes the sampleSize based on the desired estimation error. - * - * @param estimationError should be bounded by [0.01, 0.5] - * @return the sample size needed for the desired estimation error - */ - static long sampleSizeFromEstimationError(double estimationError) { - return Math.round(Math.ceil(4.0 / Math.pow(estimationError, 2.0))); - } - - private static void populateDisplayData( - DisplayData.Builder builder, long sampleSize, Double maxEstimationError) { - builder - .add(DisplayData.item("sampleSize", sampleSize) - .withLabel("Sample Size")) - .addIfNotNull(DisplayData.item("maximumEstimationError", maxEstimationError) - .withLabel("Maximum Estimation Error")); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java deleted file mode 100644 index bd1ccf977f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Combine.java +++ /dev/null @@ -1,2367 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.CustomCoder; -import com.google.cloud.dataflow.sdk.coders.DelegateCoder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.AbstractGlobalCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.AbstractPerKeyCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.GlobalCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.AppliedCombineFn; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunner; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunners; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -/** - * {@code PTransform}s for combining {@code PCollection} elements - * globally and per-key. - * - *

              See the documentation - * for how to use the operations in this class. - */ -public class Combine { - private Combine() { - // do not instantiate - } - - /** - * Returns a {@link Globally Combine.Globally} {@code PTransform} - * that uses the given {@code SerializableFunction} to combine all - * the elements in each window of the input {@code PCollection} into a - * single value in the output {@code PCollection}. The types of the input - * elements and the output elements must be the same. - * - *

              If the input {@code PCollection} is windowed into {@link GlobalWindows}, - * a default value in the {@link GlobalWindow} will be output if the input - * {@code PCollection} is empty. To use this with inputs with other windowing, - * either {@link Globally#withoutDefaults} or {@link Globally#asSingletonView} - * must be called. - * - *

              See {@link Globally Combine.Globally} for more information. - */ - public static Globally globally( - SerializableFunction, V> combiner) { - return globally(IterableCombineFn.of(combiner), displayDataForFn(combiner)); - } - - - /** - * Returns a {@link Globally Combine.Globally} {@code PTransform} - * that uses the given {@code GloballyCombineFn} to combine all - * the elements in each window of the input {@code PCollection} into a - * single value in the output {@code PCollection}. The types of the input - * elements and the output elements can differ. - * - *

              If the input {@code PCollection} is windowed into {@link GlobalWindows}, - * a default value in the {@link GlobalWindow} will be output if the input - * {@code PCollection} is empty. To use this with inputs with other windowing, - * either {@link Globally#withoutDefaults} or {@link Globally#asSingletonView} - * must be called. - * - *

              See {@link Globally Combine.Globally} for more information. - */ - public static Globally globally( - GlobalCombineFn fn) { - return globally(fn, displayDataForFn(fn)); - } - - private static DisplayData.Item> displayDataForFn(T fn) { - return DisplayData.item("combineFn", fn.getClass()) - .withLabel("Combiner"); - } - - private static Globally globally( - GlobalCombineFn fn, - DisplayData.Item> fnDisplayData) { - return new Globally<>(fn, fnDisplayData, true, 0); - } - - /** - * Returns a {@link PerKey Combine.PerKey} {@code PTransform} that - * first groups its input {@code PCollection} of {@code KV}s by keys and - * windows, then invokes the given function on each of the values lists to - * produce a combined value, and then returns a {@code PCollection} - * of {@code KV}s mapping each distinct key to its combined value for each - * window. - * - *

              Each output element is in the window by which its corresponding input - * was grouped, and has the timestamp of the end of that window. The output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * as the input. - * - *

              See {@link PerKey Combine.PerKey} for more information. - */ - public static PerKey perKey( - SerializableFunction, V> fn) { - return perKey(IterableCombineFn.of(fn).asKeyedFn(), displayDataForFn(fn)); - } - - /** - * Returns a {@link PerKey Combine.PerKey} {@code PTransform} that - * first groups its input {@code PCollection} of {@code KV}s by keys and - * windows, then invokes the given function on each of the values lists to - * produce a combined value, and then returns a {@code PCollection} - * of {@code KV}s mapping each distinct key to its combined value for each - * window. - * - *

              Each output element is in the window by which its corresponding input - * was grouped, and has the timestamp of the end of that window. The output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * as the input. - * - *

              See {@link PerKey Combine.PerKey} for more information. - */ - public static PerKey perKey( - GlobalCombineFn fn) { - return perKey(fn.asKeyedFn(), displayDataForFn(fn)); - } - - /** - * Returns a {@link PerKey Combine.PerKey} {@code PTransform} that - * first groups its input {@code PCollection} of {@code KV}s by keys and - * windows, then invokes the given function on each of the key/values-lists - * pairs to produce a combined value, and then returns a - * {@code PCollection} of {@code KV}s mapping each distinct key to - * its combined value for each window. - * - *

              Each output element is in the window by which its corresponding input - * was grouped, and has the timestamp of the end of that window. The output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * as the input. - * - *

              See {@link PerKey Combine.PerKey} for more information. - */ - public static PerKey perKey( - PerKeyCombineFn fn) { - return perKey(fn, displayDataForFn(fn)); - } - - private static PerKey perKey( - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData) { - return new PerKey<>(fn, fnDisplayData, false /*fewKeys*/); - } - - /** - * Returns a {@link PerKey Combine.PerKey}, and set fewKeys - * in {@link GroupByKey}. - */ - private static PerKey fewKeys( - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData) { - return new PerKey<>(fn, fnDisplayData, true /*fewKeys*/); - } - - /** - * Returns a {@link GroupedValues Combine.GroupedValues} - * {@code PTransform} that takes a {@code PCollection} of - * {@code KV}s where a key maps to an {@code Iterable} of values, e.g., - * the result of a {@code GroupByKey}, then uses the given - * {@code SerializableFunction} to combine all the values associated - * with a key, ignoring the key. The type of the input and - * output values must be the same. - * - *

              Each output element has the same timestamp and is in the same window - * as its corresponding input element, and the output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - *

              See {@link GroupedValues Combine.GroupedValues} for more information. - * - *

              Note that {@link #perKey(SerializableFunction)} is typically - * more convenient to use than {@link GroupByKey} followed by - * {@code groupedValues(...)}. - */ - public static GroupedValues groupedValues( - SerializableFunction, V> fn) { - return groupedValues(IterableCombineFn.of(fn).asKeyedFn(), displayDataForFn(fn)); - } - - /** - * Returns a {@link GroupedValues Combine.GroupedValues} - * {@code PTransform} that takes a {@code PCollection} of - * {@code KV}s where a key maps to an {@code Iterable} of values, e.g., - * the result of a {@code GroupByKey}, then uses the given - * {@code CombineFn} to combine all the values associated with a - * key, ignoring the key. The types of the input and output values - * can differ. - * - *

              Each output element has the same timestamp and is in the same window - * as its corresponding input element, and the output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - *

              See {@link GroupedValues Combine.GroupedValues} for more information. - * - *

              Note that {@link #perKey(CombineFnBase.GlobalCombineFn)} is typically - * more convenient to use than {@link GroupByKey} followed by - * {@code groupedValues(...)}. - */ - public static GroupedValues groupedValues( - GlobalCombineFn fn) { - return groupedValues(fn.asKeyedFn(), displayDataForFn(fn)); - } - - /** - * Returns a {@link GroupedValues Combine.GroupedValues} - * {@code PTransform} that takes a {@code PCollection} of - * {@code KV}s where a key maps to an {@code Iterable} of values, e.g., - * the result of a {@code GroupByKey}, then uses the given - * {@code KeyedCombineFn} to combine all the values associated with - * each key. The combining function is provided the key. The types - * of the input and output values can differ. - * - *

              Each output element has the same timestamp and is in the same window - * as its corresponding input element, and the output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - *

              See {@link GroupedValues Combine.GroupedValues} for more information. - * - *

              Note that {@link #perKey(CombineFnBase.PerKeyCombineFn)} is typically - * more convenient to use than {@link GroupByKey} followed by - * {@code groupedValues(...)}. - */ - public static GroupedValues groupedValues( - PerKeyCombineFn fn) { - return groupedValues(fn, displayDataForFn(fn)); - } - - private static GroupedValues groupedValues( - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData) { - return new GroupedValues<>(fn, fnDisplayData); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code CombineFn} specifies how to combine a - * collection of input values of type {@code InputT} into a single - * output value of type {@code OutputT}. It does this via one or more - * intermediate mutable accumulator values of type {@code AccumT}. - * - *

              The overall process to combine a collection of input - * {@code InputT} values into a single output {@code OutputT} value is as - * follows: - * - *

                - * - *
              1. The input {@code InputT} values are partitioned into one or more - * batches. - * - *
              2. For each batch, the {@link #createAccumulator} operation is - * invoked to create a fresh mutable accumulator value of type - * {@code AccumT}, initialized to represent the combination of zero - * values. - * - *
              3. For each input {@code InputT} value in a batch, the - * {@link #addInput} operation is invoked to add the value to that - * batch's accumulator {@code AccumT} value. The accumulator may just - * record the new value (e.g., if {@code AccumT == List}, or may do - * work to represent the combination more compactly. - * - *
              4. The {@link #mergeAccumulators} operation is invoked to - * combine a collection of accumulator {@code AccumT} values into a - * single combined output accumulator {@code AccumT} value, once the - * merging accumulators have had all all the input values in their - * batches added to them. This operation is invoked repeatedly, - * until there is only one accumulator value left. - * - *
              5. The {@link #extractOutput} operation is invoked on the final - * accumulator {@code AccumT} value to get the output {@code OutputT} value. - * - *
              - * - *

              For example: - *

               {@code
              -   * public class AverageFn extends CombineFn {
              -   *   public static class Accum {
              -   *     int sum = 0;
              -   *     int count = 0;
              -   *   }
              -   *   public Accum createAccumulator() {
              -   *     return new Accum();
              -   *   }
              -   *   public Accum addInput(Accum accum, Integer input) {
              -   *       accum.sum += input;
              -   *       accum.count++;
              -   *       return accum;
              -   *   }
              -   *   public Accum mergeAccumulators(Iterable accums) {
              -   *     Accum merged = createAccumulator();
              -   *     for (Accum accum : accums) {
              -   *       merged.sum += accum.sum;
              -   *       merged.count += accum.count;
              -   *     }
              -   *     return merged;
              -   *   }
              -   *   public Double extractOutput(Accum accum) {
              -   *     return ((double) accum.sum) / accum.count;
              -   *   }
              -   * }
              -   * PCollection pc = ...;
              -   * PCollection average = pc.apply(Combine.globally(new AverageFn()));
              -   * } 
              - * - *

              Combining functions used by {@link Combine.Globally}, - * {@link Combine.PerKey}, {@link Combine.GroupedValues}, and - * {@code PTransforms} derived from them should be - * associative and commutative. Associativity is - * required because input values are first broken up into subgroups - * before being combined, and their intermediate results further - * combined, in an arbitrary tree structure. Commutativity is - * required because any order of the input values is ignored when - * breaking up input values into groups. - * - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - public abstract static class CombineFn - extends AbstractGlobalCombineFn { - - /** - * Returns a new, mutable accumulator value, representing the accumulation of zero input values. - */ - public abstract AccumT createAccumulator(); - - /** - * Adds the given input value to the given accumulator, returning the - * new accumulator value. - * - *

              For efficiency, the input accumulator may be modified and returned. - */ - public abstract AccumT addInput(AccumT accumulator, InputT input); - - /** - * Returns an accumulator representing the accumulation of all the - * input values accumulated in the merging accumulators. - * - *

              May modify any of the argument accumulators. May return a - * fresh accumulator, or may return one of the (modified) argument - * accumulators. - */ - public abstract AccumT mergeAccumulators(Iterable accumulators); - - /** - * Returns the output value that is the result of combining all - * the input values represented by the given accumulator. - */ - public abstract OutputT extractOutput(AccumT accumulator); - - /** - * Returns an accumulator that represents the same logical value as the - * input accumulator, but may have a more compact representation. - * - *

              For most CombineFns this would be a no-op, but should be overridden - * by CombineFns that (for example) buffer up elements and combine - * them in batches. - * - *

              For efficiency, the input accumulator may be modified and returned. - * - *

              By default returns the original accumulator. - */ - public AccumT compact(AccumT accumulator) { - return accumulator; - } - - /** - * Applies this {@code CombineFn} to a collection of input values - * to produce a combined output value. - * - *

              Useful when using a {@code CombineFn} separately from a - * {@code Combine} transform. Does not invoke the - * {@link #mergeAccumulators} operation. - */ - public OutputT apply(Iterable inputs) { - AccumT accum = createAccumulator(); - for (InputT input : inputs) { - accum = addInput(accum, input); - } - return extractOutput(accum); - } - - /** - * {@inheritDoc} - * - *

              By default returns the extract output of an empty accumulator. - */ - @Override - public OutputT defaultValue() { - return extractOutput(createAccumulator()); - } - - /** - * Returns a {@link TypeDescriptor} capturing what is known statically - * about the output type of this {@code CombineFn} instance's - * most-derived class. - * - *

              In the normal case of a concrete {@code CombineFn} subclass with - * no generic type parameters of its own, this will be a complete - * non-generic type. - */ - public TypeDescriptor getOutputType() { - return new TypeDescriptor(getClass()) {}; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public KeyedCombineFn asKeyedFn() { - // The key, an object, is never even looked at. - return new KeyedCombineFn() { - @Override - public AccumT createAccumulator(K key) { - return CombineFn.this.createAccumulator(); - } - - @Override - public AccumT addInput(K key, AccumT accumulator, InputT input) { - return CombineFn.this.addInput(accumulator, input); - } - - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators) { - return CombineFn.this.mergeAccumulators(accumulators); - } - - @Override - public OutputT extractOutput(K key, AccumT accumulator) { - return CombineFn.this.extractOutput(accumulator); - } - - @Override - public AccumT compact(K key, AccumT accumulator) { - return CombineFn.this.compact(accumulator); - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder keyCoder, Coder inputCoder) - throws CannotProvideCoderException { - return CombineFn.this.getAccumulatorCoder(registry, inputCoder); - } - - @Override - public Coder getDefaultOutputCoder( - CoderRegistry registry, Coder keyCoder, Coder inputCoder) - throws CannotProvideCoderException { - return CombineFn.this.getDefaultOutputCoder(registry, inputCoder); - } - - @Override - public CombineFn forKey(K key, Coder keyCoder) { - return CombineFn.this; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.include(CombineFn.this); - } - }; - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * An abstract subclass of {@link CombineFn} for implementing combiners that are more - * easily expressed as binary operations. - */ - public abstract static class BinaryCombineFn extends - CombineFn, V> { - - /** - * Applies the binary operation to the two operands, returning the result. - */ - public abstract V apply(V left, V right); - - /** - * Returns the value that should be used for the combine of the empty set. - */ - public V identity() { - return null; - } - - @Override - public Holder createAccumulator() { - return new Holder<>(); - } - - @Override - public Holder addInput(Holder accumulator, V input) { - if (accumulator.present) { - accumulator.set(apply(accumulator.value, input)); - } else { - accumulator.set(input); - } - return accumulator; - } - - @Override - public Holder mergeAccumulators(Iterable> accumulators) { - Iterator> iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(); - } else { - Holder running = iter.next(); - while (iter.hasNext()) { - Holder accum = iter.next(); - if (accum.present) { - if (running.present) { - running.set(apply(running.value, accum.value)); - } else { - running.set(accum.value); - } - } - } - return running; - } - } - - @Override - public V extractOutput(Holder accumulator) { - if (accumulator.present) { - return accumulator.value; - } else { - return identity(); - } - } - - @Override - public Coder> getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) { - return new HolderCoder<>(inputCoder); - } - - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder inputCoder) { - return inputCoder; - } - - } - - /** - * Holds a single value value of type {@code V} which may or may not be present. - * - *

              Used only as a private accumulator class. - */ - public static class Holder { - private V value; - private boolean present; - private Holder() { } - private Holder(V value) { - set(value); - } - - private void set(V value) { - this.present = true; - this.value = value; - } - } - - /** - * A {@link Coder} for a {@link Holder}. - */ - private static class HolderCoder extends CustomCoder> { - - private Coder valueCoder; - - public HolderCoder(Coder valueCoder) { - this.valueCoder = valueCoder; - } - - @Override - public List> getCoderArguments() { - return Arrays.>asList(valueCoder); - } - - @Override - public void encode(Holder accumulator, OutputStream outStream, Context context) - throws CoderException, IOException { - if (accumulator.present) { - outStream.write(1); - valueCoder.encode(accumulator.value, outStream, context); - } else { - outStream.write(0); - } - } - - @Override - public Holder decode(InputStream inStream, Context context) - throws CoderException, IOException { - if (inStream.read() == 1) { - return new Holder<>(valueCoder.decode(inStream, context)); - } else { - return new Holder<>(); - } - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - valueCoder.verifyDeterministic(); - } - } - - /** - * An abstract subclass of {@link CombineFn} for implementing combiners that are more - * easily and efficiently expressed as binary operations on ints - * - *

              It uses {@code int[0]} as the mutable accumulator. - */ - public abstract static class BinaryCombineIntegerFn extends CombineFn { - - /** - * Applies the binary operation to the two operands, returning the result. - */ - public abstract int apply(int left, int right); - - /** - * Returns the identity element of this operation, i.e. an element {@code e} - * such that {@code apply(e, x) == apply(x, e) == x} for all values of {@code x}. - */ - public abstract int identity(); - - @Override - public int[] createAccumulator() { - return wrap(identity()); - } - - @Override - public int[] addInput(int[] accumulator, Integer input) { - accumulator[0] = apply(accumulator[0], input); - return accumulator; - } - - @Override - public int[] mergeAccumulators(Iterable accumulators) { - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(); - } else { - int[] running = iter.next(); - while (iter.hasNext()) { - running[0] = apply(running[0], iter.next()[0]); - } - return running; - } - } - - @Override - public Integer extractOutput(int[] accumulator) { - return accumulator[0]; - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) { - return DelegateCoder.of( - inputCoder, - new DelegateCoder.CodingFunction() { - @Override - public Integer apply(int[] accumulator) { - return accumulator[0]; - } - }, - new DelegateCoder.CodingFunction() { - @Override - public int[] apply(Integer value) { - return wrap(value); - } - }); - } - - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, - Coder inputCoder) { - return inputCoder; - } - - private int[] wrap(int value) { - return new int[] { value }; - } - - public Counter getCounter(String name) { - throw new UnsupportedOperationException("BinaryCombineDoubleFn does not support getCounter"); - } - } - - /** - * An abstract subclass of {@link CombineFn} for implementing combiners that are more - * easily and efficiently expressed as binary operations on longs. - * - *

              It uses {@code long[0]} as the mutable accumulator. - */ - public abstract static class BinaryCombineLongFn extends CombineFn { - /** - * Applies the binary operation to the two operands, returning the result. - */ - public abstract long apply(long left, long right); - - /** - * Returns the identity element of this operation, i.e. an element {@code e} - * such that {@code apply(e, x) == apply(x, e) == x} for all values of {@code x}. - */ - public abstract long identity(); - - @Override - public long[] createAccumulator() { - return wrap(identity()); - } - - @Override - public long[] addInput(long[] accumulator, Long input) { - accumulator[0] = apply(accumulator[0], input); - return accumulator; - } - - @Override - public long[] mergeAccumulators(Iterable accumulators) { - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(); - } else { - long[] running = iter.next(); - while (iter.hasNext()) { - running[0] = apply(running[0], iter.next()[0]); - } - return running; - } - } - - @Override - public Long extractOutput(long[] accumulator) { - return accumulator[0]; - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) { - return DelegateCoder.of( - inputCoder, - new DelegateCoder.CodingFunction() { - @Override - public Long apply(long[] accumulator) { - return accumulator[0]; - } - }, - new DelegateCoder.CodingFunction() { - @Override - public long[] apply(Long value) { - return wrap(value); - } - }); - } - - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder inputCoder) { - return inputCoder; - } - - private long[] wrap(long value) { - return new long[] { value }; - } - - public Counter getCounter(String name) { - throw new UnsupportedOperationException("BinaryCombineDoubleFn does not support getCounter"); - } - } - - /** - * An abstract subclass of {@link CombineFn} for implementing combiners that are more - * easily and efficiently expressed as binary operations on doubles. - * - *

              It uses {@code double[0]} as the mutable accumulator. - */ - public abstract static class BinaryCombineDoubleFn extends CombineFn { - - /** - * Applies the binary operation to the two operands, returning the result. - */ - public abstract double apply(double left, double right); - - /** - * Returns the identity element of this operation, i.e. an element {@code e} - * such that {@code apply(e, x) == apply(x, e) == x} for all values of {@code x}. - */ - public abstract double identity(); - - @Override - public double[] createAccumulator() { - return wrap(identity()); - } - - @Override - public double[] addInput(double[] accumulator, Double input) { - accumulator[0] = apply(accumulator[0], input); - return accumulator; - } - - @Override - public double[] mergeAccumulators(Iterable accumulators) { - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(); - } else { - double[] running = iter.next(); - while (iter.hasNext()) { - running[0] = apply(running[0], iter.next()[0]); - } - return running; - } - } - - @Override - public Double extractOutput(double[] accumulator) { - return accumulator[0]; - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) { - return DelegateCoder.of( - inputCoder, - new DelegateCoder.CodingFunction() { - @Override - public Double apply(double[] accumulator) { - return accumulator[0]; - } - }, - new DelegateCoder.CodingFunction() { - @Override - public double[] apply(Double value) { - return wrap(value); - } - }); - } - - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder inputCoder) { - return inputCoder; - } - - private double[] wrap(double value) { - return new double[] { value }; - } - - public Counter getCounter(String name) { - throw new UnsupportedOperationException("BinaryCombineDoubleFn does not support getCounter"); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code CombineFn} that uses a subclass of - * {@link AccumulatingCombineFn.Accumulator} as its accumulator - * type. By defining the operations of the {@code Accumulator} - * helper class, the operations of the enclosing {@code CombineFn} - * are automatically provided. This can reduce the code required to - * implement a {@code CombineFn}. - * - *

              For example, the example from {@link CombineFn} above can be - * expressed using {@code AccumulatingCombineFn} more concisely as - * follows: - * - *

               {@code
              -   * public class AverageFn
              -   *     extends AccumulatingCombineFn {
              -   *   public Accum createAccumulator() {
              -   *     return new Accum();
              -   *   }
              -   *   public class Accum
              -   *       extends AccumulatingCombineFn
              -   *               .Accumulator {
              -   *     private int sum = 0;
              -   *     private int count = 0;
              -   *     public void addInput(Integer input) {
              -   *       sum += input;
              -   *       count++;
              -   *     }
              -   *     public void mergeAccumulator(Accum other) {
              -   *       sum += other.sum;
              -   *       count += other.count;
              -   *     }
              -   *     public Double extractOutput() {
              -   *       return ((double) sum) / count;
              -   *     }
              -   *   }
              -   * }
              -   * PCollection pc = ...;
              -   * PCollection average = pc.apply(Combine.globally(new AverageFn()));
              -   * } 
              - * - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - public abstract static class AccumulatingCombineFn< - InputT, - AccumT extends AccumulatingCombineFn.Accumulator, - OutputT> - extends CombineFn { - - /** - * The type of mutable accumulator values used by this - * {@code AccumulatingCombineFn}. - */ - public interface Accumulator { - /** - * Adds the given input value to this accumulator, modifying - * this accumulator. - */ - void addInput(InputT input); - - /** - * Adds the input values represented by the given accumulator - * into this accumulator. - */ - void mergeAccumulator(AccumT other); - - /** - * Returns the output value that is the result of combining all - * the input values represented by this accumulator. - */ - OutputT extractOutput(); - } - - @Override - public final AccumT addInput(AccumT accumulator, InputT input) { - accumulator.addInput(input); - return accumulator; - } - - @Override - public final AccumT mergeAccumulators(Iterable accumulators) { - AccumT accumulator = createAccumulator(); - for (AccumT partial : accumulators) { - accumulator.mergeAccumulator(partial); - } - return accumulator; - } - - @Override - public final OutputT extractOutput(AccumT accumulator) { - return accumulator.extractOutput(); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - - /** - * A {@code KeyedCombineFn} specifies how to combine - * a collection of input values of type {@code InputT}, associated with - * a key of type {@code K}, into a single output value of type - * {@code OutputT}. It does this via one or more intermediate mutable - * accumulator values of type {@code AccumT}. - * - *

              The overall process to combine a collection of input - * {@code InputT} values associated with an input {@code K} key into a - * single output {@code OutputT} value is as follows: - * - *

                - * - *
              1. The input {@code InputT} values are partitioned into one or more - * batches. - * - *
              2. For each batch, the {@link #createAccumulator} operation is - * invoked to create a fresh mutable accumulator value of type - * {@code AccumT}, initialized to represent the combination of zero - * values. - * - *
              3. For each input {@code InputT} value in a batch, the - * {@link #addInput} operation is invoked to add the value to that - * batch's accumulator {@code AccumT} value. The accumulator may just - * record the new value (e.g., if {@code AccumT == List}, or may do - * work to represent the combination more compactly. - * - *
              4. The {@link #mergeAccumulators} operation is invoked to - * combine a collection of accumulator {@code AccumT} values into a - * single combined output accumulator {@code AccumT} value, once the - * merging accumulators have had all all the input values in their - * batches added to them. This operation is invoked repeatedly, - * until there is only one accumulator value left. - * - *
              5. The {@link #extractOutput} operation is invoked on the final - * accumulator {@code AccumT} value to get the output {@code OutputT} value. - * - *
              - * - *

              All of these operations are passed the {@code K} key that the - * values being combined are associated with. - * - *

              For example: - *

               {@code
              -   * public class ConcatFn
              -   *     extends KeyedCombineFn {
              -   *   public static class Accum {
              -   *     String s = "";
              -   *   }
              -   *   public Accum createAccumulator(String key) {
              -   *     return new Accum();
              -   *   }
              -   *   public Accum addInput(String key, Accum accum, Integer input) {
              -   *       accum.s += "+" + input;
              -   *       return accum;
              -   *   }
              -   *   public Accum mergeAccumulators(String key, Iterable accums) {
              -   *     Accum merged = new Accum();
              -   *     for (Accum accum : accums) {
              -   *       merged.s += accum.s;
              -   *     }
              -   *     return merged;
              -   *   }
              -   *   public String extractOutput(String key, Accum accum) {
              -   *     return key + accum.s;
              -   *   }
              -   * }
              -   * PCollection> pc = ...;
              -   * PCollection> pc2 = pc.apply(
              -   *     Combine.perKey(new ConcatFn()));
              -   * } 
              - * - *

              Keyed combining functions used by {@link Combine.PerKey}, - * {@link Combine.GroupedValues}, and {@code PTransforms} derived - * from them should be associative and commutative. - * Associativity is required because input values are first broken - * up into subgroups before being combined, and their intermediate - * results further combined, in an arbitrary tree structure. - * Commutativity is required because any order of the input values - * is ignored when breaking up input values into groups. - * - * @param type of keys - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - public abstract static class KeyedCombineFn - extends AbstractPerKeyCombineFn { - /** - * Returns a new, mutable accumulator value representing the accumulation of zero input values. - * - * @param key the key that all the accumulated values using the - * accumulator are associated with - */ - public abstract AccumT createAccumulator(K key); - - /** - * Adds the given input value to the given accumulator, returning the new accumulator value. - * - *

              For efficiency, the input accumulator may be modified and returned. - * - * @param key the key that all the accumulated values using the - * accumulator are associated with - */ - public abstract AccumT addInput(K key, AccumT accumulator, InputT value); - - /** - * Returns an accumulator representing the accumulation of all the - * input values accumulated in the merging accumulators. - * - *

              May modify any of the argument accumulators. May return a - * fresh accumulator, or may return one of the (modified) argument - * accumulators. - * - * @param key the key that all the accumulators are associated - * with - */ - public abstract AccumT mergeAccumulators(K key, Iterable accumulators); - - /** - * Returns the output value that is the result of combining all - * the input values represented by the given accumulator. - * - * @param key the key that all the accumulated values using the - * accumulator are associated with - */ - public abstract OutputT extractOutput(K key, AccumT accumulator); - - /** - * Returns an accumulator that represents the same logical value as the - * input accumulator, but may have a more compact representation. - * - *

              For most CombineFns this would be a no-op, but should be overridden - * by CombineFns that (for example) buffer up elements and combine - * them in batches. - * - *

              For efficiency, the input accumulator may be modified and returned. - * - *

              By default returns the original accumulator. - */ - public AccumT compact(K key, AccumT accumulator) { - return accumulator; - } - - @Override - public CombineFn forKey(final K key, final Coder keyCoder) { - return new CombineFn() { - - @Override - public AccumT createAccumulator() { - return KeyedCombineFn.this.createAccumulator(key); - } - - @Override - public AccumT addInput(AccumT accumulator, InputT input) { - return KeyedCombineFn.this.addInput(key, accumulator, input); - } - - @Override - public AccumT mergeAccumulators(Iterable accumulators) { - return KeyedCombineFn.this.mergeAccumulators(key, accumulators); - } - - @Override - public OutputT extractOutput(AccumT accumulator) { - return KeyedCombineFn.this.extractOutput(key, accumulator); - } - - @Override - public AccumT compact(AccumT accumulator) { - return KeyedCombineFn.this.compact(key, accumulator); - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException { - return KeyedCombineFn.this.getAccumulatorCoder(registry, keyCoder, inputCoder); - } - - @Override - public Coder getDefaultOutputCoder( - CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { - return KeyedCombineFn.this.getDefaultOutputCoder(registry, keyCoder, inputCoder); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.include(KeyedCombineFn.this); - } - }; - } - - /** - * Applies this {@code KeyedCombineFn} to a key and a collection - * of input values to produce a combined output value. - * - *

              Useful when testing the behavior of a {@code KeyedCombineFn} - * separately from a {@code Combine} transform. - */ - public OutputT apply(K key, Iterable inputs) { - AccumT accum = createAccumulator(key); - for (InputT input : inputs) { - accum = addInput(key, accum, input); - } - return extractOutput(key, accum); - } - } - - //////////////////////////////////////////////////////////////////////////// - - /** - * {@code Combine.Globally} takes a {@code PCollection} - * and returns a {@code PCollection} whose elements are the result of - * combining all the elements in each window of the input {@code PCollection}, - * using a specified {@link CombineFn CombineFn<InputT, AccumT, OutputT>}. - * It is common for {@code InputT == OutputT}, but not required. Common combining - * functions include sums, mins, maxes, and averages of numbers, - * conjunctions and disjunctions of booleans, statistical - * aggregations, etc. - * - *

              Example of use: - *

               {@code
              -   * PCollection pc = ...;
              -   * PCollection sum = pc.apply(
              -   *     Combine.globally(new Sum.SumIntegerFn()));
              -   * } 
              - * - *

              Combining can happen in parallel, with different subsets of the - * input {@code PCollection} being combined separately, and their - * intermediate results combined further, in an arbitrary tree - * reduction pattern, until a single result value is produced. - * - *

              If the input {@code PCollection} is windowed into {@link GlobalWindows}, - * a default value in the {@link GlobalWindow} will be output if the input - * {@code PCollection} is empty. To use this with inputs with other windowing, - * either {@link #withoutDefaults} or {@link #asSingletonView} must be called, - * as the default value cannot be automatically assigned to any single window. - * - *

              By default, the {@code Coder} of the output {@code PValue} - * is inferred from the concrete type of the - * {@code CombineFn}'s output type {@code OutputT}. - * - *

              See also {@link #perKey}/{@link PerKey Combine.PerKey} and - * {@link #groupedValues}/{@link GroupedValues Combine.GroupedValues}, which - * are useful for combining values associated with each key in - * a {@code PCollection} of {@code KV}s. - * - * @param type of input values - * @param type of output values - */ - public static class Globally - extends PTransform, PCollection> { - - private final GlobalCombineFn fn; - private final DisplayData.Item> fnDisplayData; - private final boolean insertDefault; - private final int fanout; - private final List> sideInputs; - - private Globally(GlobalCombineFn fn, - DisplayData.Item> fnDisplayData, boolean insertDefault, int fanout) { - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.insertDefault = insertDefault; - this.fanout = fanout; - this.sideInputs = ImmutableList.of(); - } - - private Globally(String name, GlobalCombineFn fn, - DisplayData.Item> fnDisplayData, boolean insertDefault, int fanout) { - super(name); - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.insertDefault = insertDefault; - this.fanout = fanout; - this.sideInputs = ImmutableList.of(); - } - - private Globally(String name, GlobalCombineFn fn, - DisplayData.Item> fnDisplayData, boolean insertDefault, int fanout, - List> sideInputs) { - super(name); - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.insertDefault = insertDefault; - this.fanout = fanout; - this.sideInputs = sideInputs; - } - - /** - * Return a new {@code Globally} transform that's like this transform but with the - * specified name. Does not modify this transform. - */ - public Globally named(String name) { - return new Globally<>(name, fn, fnDisplayData, insertDefault, fanout); - } - - /** - * Returns a {@link PTransform} that produces a {@code PCollectionView} - * whose elements are the result of combining elements per-window in - * the input {@code PCollection}. If a value is requested from the view - * for a window that is not present, the result of applying the {@code CombineFn} - * to an empty input set will be returned. - */ - public GloballyAsSingletonView asSingletonView() { - return new GloballyAsSingletonView<>(fn, fnDisplayData, insertDefault, fanout); - } - - /** - * Returns a {@link PTransform} identical to this, but that does not attempt to - * provide a default value in the case of empty input. Required when the input - * is not globally windowed and the output is not being used as a side input. - */ - public Globally withoutDefaults() { - return new Globally<>(name, fn, fnDisplayData, false, fanout); - } - - /** - * Returns a {@link PTransform} identical to this, but that uses an intermediate node - * to combine parts of the data to reduce load on the final global combine step. - * - *

              The {@code fanout} parameter determines the number of intermediate keys - * that will be used. - */ - public Globally withFanout(int fanout) { - return new Globally<>(name, fn, fnDisplayData, insertDefault, fanout); - } - - /** - * Returns a {@link PTransform} identical to this, but with the specified side inputs to use - * in {@link CombineFnWithContext}. - */ - public Globally withSideInputs( - Iterable> sideInputs) { - checkState(fn instanceof RequiresContextInternal); - return new Globally<>(name, fn, fnDisplayData, insertDefault, fanout, - ImmutableList.copyOf(sideInputs)); - } - - @Override - public PCollection apply(PCollection input) { - PCollection> withKeys = input - .apply(WithKeys.of((Void) null)) - .setCoder(KvCoder.of(VoidCoder.of(), input.getCoder())); - - Combine.PerKey combine = - Combine.fewKeys(fn.asKeyedFn(), fnDisplayData); - if (!sideInputs.isEmpty()) { - combine = combine.withSideInputs(sideInputs); - } - - PCollection> combined; - if (fanout >= 2) { - combined = withKeys.apply(combine.withHotKeyFanout(fanout)); - } else { - combined = withKeys.apply(combine); - } - - PCollection output = combined.apply(Values.create()); - - if (insertDefault) { - if (!output.getWindowingStrategy().getWindowFn().isCompatible(new GlobalWindows())) { - throw new IllegalStateException(fn.getIncompatibleGlobalWindowErrorMessage()); - } - return insertDefaultValueIfEmpty(output); - } else { - return output; - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - Combine.populateDisplayData(builder, fn, fnDisplayData); - Combine.populateGlobalDisplayData(builder, fanout, insertDefault); - } - - private PCollection insertDefaultValueIfEmpty(PCollection maybeEmpty) { - final PCollectionView> maybeEmptyView = maybeEmpty.apply( - View.asIterable()); - - - final OutputT defaultValue = fn.defaultValue(); - PCollection defaultIfEmpty = maybeEmpty.getPipeline() - .apply("CreateVoid", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply(ParDo.named("ProduceDefault").withSideInputs(maybeEmptyView).of( - new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) { - Iterator combined = c.sideInput(maybeEmptyView).iterator(); - if (!combined.hasNext()) { - c.output(defaultValue); - } - } - })) - .setCoder(maybeEmpty.getCoder()) - .setWindowingStrategyInternal(maybeEmpty.getWindowingStrategy()); - - return PCollectionList.of(maybeEmpty).and(defaultIfEmpty) - .apply(Flatten.pCollections()); - } - } - - private static void populateDisplayData( - DisplayData.Builder builder, HasDisplayData fn, - DisplayData.Item> fnDisplayItem) { - builder - .include(fn) - .add(fnDisplayItem); - } - - private static void populateGlobalDisplayData( - DisplayData.Builder builder, int fanout, boolean insertDefault) { - builder - .addIfNotDefault(DisplayData.item("fanout", fanout) - .withLabel("Key Fanout Size"), 0) - .add(DisplayData.item("emitDefaultOnEmptyInput", insertDefault) - .withLabel("Emit Default On Empty Input")); - } - - /** - * {@code Combine.GloballyAsSingletonView} takes a {@code PCollection} - * and returns a {@code PCollectionView} whose elements are the result of - * combining all the elements in each window of the input {@code PCollection}, - * using a specified {@link CombineFn CombineFn<InputT, AccumT, OutputT>}. - * It is common for {@code InputT == OutputT}, but not required. Common combining - * functions include sums, mins, maxes, and averages of numbers, - * conjunctions and disjunctions of booleans, statistical - * aggregations, etc. - * - *

              Example of use: - *

               {@code
              -   * PCollection pc = ...;
              -   * PCollection sum = pc.apply(
              -   *     Combine.globally(new Sum.SumIntegerFn()));
              -   * } 
              - * - *

              Combining can happen in parallel, with different subsets of the - * input {@code PCollection} being combined separately, and their - * intermediate results combined further, in an arbitrary tree - * reduction pattern, until a single result value is produced. - * - *

              If a value is requested from the view for a window that is not present - * and {@code insertDefault} is true, the result of calling the {@code CombineFn} - * on empty input will returned. If {@code insertDefault} is false, an - * exception will be thrown instead. - * - *

              By default, the {@code Coder} of the output {@code PValue} - * is inferred from the concrete type of the - * {@code CombineFn}'s output type {@code OutputT}. - * - *

              See also {@link #perKey}/{@link PerKey Combine.PerKey} and - * {@link #groupedValues}/{@link GroupedValues Combine.GroupedValues}, which - * are useful for combining values associated with each key in - * a {@code PCollection} of {@code KV}s. - * - * @param type of input values - * @param type of output values - */ - public static class GloballyAsSingletonView - extends PTransform, PCollectionView> { - - private final GlobalCombineFn fn; - private final DisplayData.Item> fnDisplayData; - private final boolean insertDefault; - private final int fanout; - - private GloballyAsSingletonView( - GlobalCombineFn fn, - DisplayData.Item> fnDisplayData, boolean insertDefault, int fanout) { - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.insertDefault = insertDefault; - this.fanout = fanout; - } - - @Override - public PCollectionView apply(PCollection input) { - Globally combineGlobally = - Combine.globally(fn).withoutDefaults().withFanout(fanout); - if (insertDefault) { - return input - .apply(combineGlobally) - .apply(View.asSingleton().withDefaultValue(fn.defaultValue())); - } else { - return input - .apply(combineGlobally) - .apply(View.asSingleton()); - } - } - - public int getFanout() { - return fanout; - } - - public boolean getInsertDefault() { - return insertDefault; - } - - public GlobalCombineFn getCombineFn() { - return fn; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - Combine.populateDisplayData(builder, fn, fnDisplayData); - Combine.populateGlobalDisplayData(builder, fanout, insertDefault); - } - } - - /** - * Converts a {@link SerializableFunction} from {@code Iterable}s - * to {@code V}s into a simple {@link CombineFn} over {@code V}s. - * - *

              Used in the implementation of convenience methods like - * {@link #globally(SerializableFunction)}, - * {@link #perKey(SerializableFunction)}, and - * {@link #groupedValues(SerializableFunction)}. - */ - public static class IterableCombineFn extends CombineFn, V> { - /** - * Returns a {@code CombineFn} that uses the given - * {@code SerializableFunction} to combine values. - */ - public static IterableCombineFn of( - SerializableFunction, V> combiner) { - return of(combiner, DEFAULT_BUFFER_SIZE); - } - - /** - * Returns a {@code CombineFn} that uses the given - * {@code SerializableFunction} to combine values, - * attempting to buffer at least {@code bufferSize} - * values between invocations. - */ - public static IterableCombineFn of( - SerializableFunction, V> combiner, int bufferSize) { - return new IterableCombineFn<>(combiner, bufferSize); - } - - private static final int DEFAULT_BUFFER_SIZE = 20; - - /** The combiner function. */ - private final SerializableFunction, V> combiner; - - /** - * The number of values to accumulate before invoking the combiner - * function to combine them. - */ - private final int bufferSize; - - private IterableCombineFn( - SerializableFunction, V> combiner, int bufferSize) { - this.combiner = combiner; - this.bufferSize = bufferSize; - } - - @Override - public List createAccumulator() { - return new ArrayList<>(); - } - - @Override - public List addInput(List accumulator, V input) { - accumulator.add(input); - if (accumulator.size() > bufferSize) { - return mergeToSingleton(accumulator); - } else { - return accumulator; - } - } - - @Override - public List mergeAccumulators(Iterable> accumulators) { - return mergeToSingleton(Iterables.concat(accumulators)); - } - - @Override - public V extractOutput(List accumulator) { - return combiner.apply(accumulator); - } - - @Override - public List compact(List accumulator) { - return accumulator.size() > 1 ? mergeToSingleton(accumulator) : accumulator; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("combineFn", combiner.getClass()) - .withLabel("Combiner")); - } - - private List mergeToSingleton(Iterable values) { - List singleton = new ArrayList<>(); - singleton.add(combiner.apply(values)); - return singleton; - } - } - - /** - * Converts a {@link SerializableFunction} from {@code Iterable}s - * to {@code V}s into a simple {@link CombineFn} over {@code V}s. - * - *

              @deprecated Use {@link IterableCombineFn} or the more space efficient - * {@link BinaryCombineFn} instead (which avoids buffering values). - */ - @Deprecated - public static class SimpleCombineFn extends IterableCombineFn { - - /** - * Returns a {@code CombineFn} that uses the given - * {@code SerializableFunction} to combine values. - */ - @Deprecated - public static SimpleCombineFn of( - SerializableFunction, V> combiner) { - return new SimpleCombineFn<>(combiner); - } - - protected SimpleCombineFn(SerializableFunction, V> combiner) { - super(combiner, IterableCombineFn.DEFAULT_BUFFER_SIZE); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * {@code PerKey} takes a - * {@code PCollection>}, groups it by key, applies a - * combining function to the {@code InputT} values associated with each - * key to produce a combined {@code OutputT} value, and returns a - * {@code PCollection>} representing a map from each - * distinct key of the input {@code PCollection} to the corresponding - * combined value. {@code InputT} and {@code OutputT} are often the same. - * - *

              This is a concise shorthand for an application of - * {@link GroupByKey} followed by an application of - * {@link GroupedValues Combine.GroupedValues}. See those - * operations for more details on how keys are compared for equality - * and on the default {@code Coder} for the output. - * - *

              Example of use: - *

               {@code
              -   * PCollection> salesRecords = ...;
              -   * PCollection> totalSalesPerPerson =
              -   *     salesRecords.apply(Combine.perKey(
              -   *         new Sum.SumDoubleFn()));
              -   * } 
              - * - *

              Each output element is in the window by which its corresponding input - * was grouped, and has the timestamp of the end of that window. The output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * as the input. - * - * @param the type of the keys of the input and output - * {@code PCollection}s - * @param the type of the values of the input {@code PCollection} - * @param the type of the values of the output {@code PCollection} - */ - public static class PerKey - extends PTransform>, PCollection>> { - - private final transient PerKeyCombineFn fn; - private final DisplayData.Item> fnDisplayData; - private final boolean fewKeys; - private final List> sideInputs; - - private PerKey( - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData, boolean fewKeys) { - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.fewKeys = fewKeys; - this.sideInputs = ImmutableList.of(); - } - - private PerKey(String name, - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData, - boolean fewKeys, List> sideInputs) { - super(name); - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.fewKeys = fewKeys; - this.sideInputs = sideInputs; - } - - private PerKey( - String name, PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData, boolean fewKeys) { - super(name); - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.fewKeys = fewKeys; - this.sideInputs = ImmutableList.of(); - } - - /** - * Return a new {@code Globally} transform that's like this transform but with the - * specified name. Does not modify this transform. - */ - public PerKey named(String name) { - return new PerKey<>(name, fn, fnDisplayData, fewKeys); - } - - /** - * Returns a {@link PTransform} identical to this, but with the specified side inputs to use - * in {@link KeyedCombineFnWithContext}. - */ - public PerKey withSideInputs( - Iterable> sideInputs) { - checkState(fn instanceof RequiresContextInternal); - return new PerKey<>(name, fn, fnDisplayData, fewKeys, - ImmutableList.copyOf(sideInputs)); - } - - /** - * If a single key has disproportionately many values, it may become a - * bottleneck, especially in streaming mode. This returns a new per-key - * combining transform that inserts an intermediate node to combine "hot" - * keys partially before performing the full combine. - * - * @param hotKeyFanout a function from keys to an integer N, where the key - * will be spread among N intermediate nodes for partial combining. - * If N is less than or equal to 1, this key will not be sent through an - * intermediate node. - */ - public PerKeyWithHotKeyFanout withHotKeyFanout( - SerializableFunction hotKeyFanout) { - return new PerKeyWithHotKeyFanout<>(name, fn, fnDisplayData, hotKeyFanout); - } - - /** - * Like {@link #withHotKeyFanout(SerializableFunction)}, but returning the given - * constant value for every key. - */ - public PerKeyWithHotKeyFanout withHotKeyFanout(final int hotKeyFanout) { - return new PerKeyWithHotKeyFanout<>(name, fn, fnDisplayData, - new SerializableFunction() { - @Override - public Integer apply(K unused) { - return hotKeyFanout; - } - }); - } - - /** - * Returns the {@link PerKeyCombineFn} used by this Combine operation. - */ - public PerKeyCombineFn getFn() { - return fn; - } - - /** - * Returns the side inputs used by this Combine operation. - */ - public List> getSideInputs() { - return sideInputs; - } - - @Override - public PCollection> apply(PCollection> input) { - return input - .apply(GroupByKey.create(fewKeys)) - .apply(Combine.groupedValues(fn, fnDisplayData) - .withSideInputs(sideInputs)); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Combine.populateDisplayData(builder, fn, fnDisplayData); - } - } - - /** - * Like {@link PerKey}, but sharding the combining of hot keys. - */ - public static class PerKeyWithHotKeyFanout - extends PTransform>, PCollection>> { - - private final transient PerKeyCombineFn fn; - private final DisplayData.Item> fnDisplayData; - private final SerializableFunction hotKeyFanout; - - private PerKeyWithHotKeyFanout(String name, - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData, - SerializableFunction hotKeyFanout) { - super(name); - this.fn = fn; - this.fnDisplayData = fnDisplayData; - this.hotKeyFanout = hotKeyFanout; - } - - @Override - public PCollection> apply(PCollection> input) { - return applyHelper(input); - } - - private PCollection> applyHelper(PCollection> input) { - - // Name the accumulator type. - @SuppressWarnings("unchecked") - final PerKeyCombineFn typedFn = - (PerKeyCombineFn) this.fn; - - if (!(input.getCoder() instanceof KvCoder)) { - throw new IllegalStateException( - "Expected input coder to be KvCoder, but was " + input.getCoder()); - } - - @SuppressWarnings("unchecked") - final KvCoder inputCoder = (KvCoder) input.getCoder(); - final Coder accumCoder; - - try { - accumCoder = typedFn.getAccumulatorCoder( - input.getPipeline().getCoderRegistry(), - inputCoder.getKeyCoder(), inputCoder.getValueCoder()); - } catch (CannotProvideCoderException e) { - throw new IllegalStateException("Unable to determine accumulator coder.", e); - } - Coder> inputOrAccumCoder = - new InputOrAccum.InputOrAccumCoder( - inputCoder.getValueCoder(), accumCoder); - - // A CombineFn's mergeAccumulator can be applied in a tree-like fashon. - // Here we shard the key using an integer nonce, combine on that partial - // set of values, then drop the nonce and do a final combine of the - // aggregates. We do this by splitting the original CombineFn into two, - // on that does addInput + merge and another that does merge + extract. - PerKeyCombineFn, InputT, AccumT, AccumT> hotPreCombine; - PerKeyCombineFn, AccumT, OutputT> postCombine; - if (!(typedFn instanceof RequiresContextInternal)) { - final KeyedCombineFn keyedFn = - (KeyedCombineFn) typedFn; - hotPreCombine = - new KeyedCombineFn, InputT, AccumT, AccumT>() { - @Override - public AccumT createAccumulator(KV key) { - return keyedFn.createAccumulator(key.getKey()); - } - @Override - public AccumT addInput(KV key, AccumT accumulator, InputT value) { - return keyedFn.addInput(key.getKey(), accumulator, value); - } - @Override - public AccumT mergeAccumulators( - KV key, Iterable accumulators) { - return keyedFn.mergeAccumulators(key.getKey(), accumulators); - } - @Override - public AccumT compact(KV key, AccumT accumulator) { - return keyedFn.compact(key.getKey(), accumulator); - } - @Override - public AccumT extractOutput(KV key, AccumT accumulator) { - return accumulator; - } - @Override - @SuppressWarnings("unchecked") - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder> keyCoder, Coder inputCoder) - throws CannotProvideCoderException { - return accumCoder; - } - }; - postCombine = - new KeyedCombineFn, AccumT, OutputT>() { - @Override - public AccumT createAccumulator(K key) { - return keyedFn.createAccumulator(key); - } - @Override - public AccumT addInput( - K key, AccumT accumulator, InputOrAccum value) { - if (value.accum == null) { - return keyedFn.addInput(key, accumulator, value.input); - } else { - return keyedFn.mergeAccumulators(key, ImmutableList.of(accumulator, value.accum)); - } - } - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators) { - return keyedFn.mergeAccumulators(key, accumulators); - } - @Override - public AccumT compact(K key, AccumT accumulator) { - return keyedFn.compact(key, accumulator); - } - @Override - public OutputT extractOutput(K key, AccumT accumulator) { - return keyedFn.extractOutput(key, accumulator); - } - @Override - public Coder getDefaultOutputCoder( - CoderRegistry registry, - Coder keyCoder, - Coder> accumulatorCoder) - throws CannotProvideCoderException { - return keyedFn.getDefaultOutputCoder( - registry, keyCoder, inputCoder.getValueCoder()); - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder> inputCoder) - throws CannotProvideCoderException { - return accumCoder; - } - }; - } else { - final KeyedCombineFnWithContext keyedFnWithContext = - (KeyedCombineFnWithContext) typedFn; - hotPreCombine = - new KeyedCombineFnWithContext, InputT, AccumT, AccumT>() { - @Override - public AccumT createAccumulator(KV key, Context c) { - return keyedFnWithContext.createAccumulator(key.getKey(), c); - } - - @Override - public AccumT addInput( - KV key, AccumT accumulator, InputT value, Context c) { - return keyedFnWithContext.addInput(key.getKey(), accumulator, value, c); - } - - @Override - public AccumT mergeAccumulators( - KV key, Iterable accumulators, Context c) { - return keyedFnWithContext.mergeAccumulators(key.getKey(), accumulators, c); - } - - @Override - public AccumT compact(KV key, AccumT accumulator, Context c) { - return keyedFnWithContext.compact(key.getKey(), accumulator, c); - } - - @Override - public AccumT extractOutput(KV key, AccumT accumulator, Context c) { - return accumulator; - } - - @Override - @SuppressWarnings("unchecked") - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder> keyCoder, Coder inputCoder) - throws CannotProvideCoderException { - return accumCoder; - } - }; - postCombine = - new KeyedCombineFnWithContext, AccumT, OutputT>() { - @Override - public AccumT createAccumulator(K key, Context c) { - return keyedFnWithContext.createAccumulator(key, c); - } - @Override - public AccumT addInput( - K key, AccumT accumulator, InputOrAccum value, Context c) { - if (value.accum == null) { - return keyedFnWithContext.addInput(key, accumulator, value.input, c); - } else { - return keyedFnWithContext.mergeAccumulators( - key, ImmutableList.of(accumulator, value.accum), c); - } - } - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators, Context c) { - return keyedFnWithContext.mergeAccumulators(key, accumulators, c); - } - @Override - public AccumT compact(K key, AccumT accumulator, Context c) { - return keyedFnWithContext.compact(key, accumulator, c); - } - @Override - public OutputT extractOutput(K key, AccumT accumulator, Context c) { - return keyedFnWithContext.extractOutput(key, accumulator, c); - } - @Override - public Coder getDefaultOutputCoder( - CoderRegistry registry, - Coder keyCoder, - Coder> accumulatorCoder) - throws CannotProvideCoderException { - return keyedFnWithContext.getDefaultOutputCoder( - registry, keyCoder, inputCoder.getValueCoder()); - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder> inputCoder) - throws CannotProvideCoderException { - return accumCoder; - } - }; - } - - // Use the provided hotKeyFanout fn to split into "hot" and "cold" keys, - // augmenting the hot keys with a nonce. - final TupleTag, InputT>> hot = new TupleTag<>(); - final TupleTag> cold = new TupleTag<>(); - PCollectionTuple split = input.apply( - ParDo.named("AddNonce").of( - new DoFn, KV>() { - transient int counter; - @Override - public void startBundle(Context c) { - counter = ThreadLocalRandom.current().nextInt( - Integer.MAX_VALUE); - } - - @Override - public void processElement(ProcessContext c) { - KV kv = c.element(); - int spread = Math.max(1, hotKeyFanout.apply(kv.getKey())); - if (spread <= 1) { - c.output(kv); - } else { - int nonce = counter++ % spread; - c.sideOutput(hot, KV.of(KV.of(kv.getKey(), nonce), kv.getValue())); - } - } - }) - .withOutputTags(cold, TupleTagList.of(hot))); - - // The first level of combine should never use accumulating mode. - WindowingStrategy preCombineStrategy = input.getWindowingStrategy(); - if (preCombineStrategy.getMode() - == WindowingStrategy.AccumulationMode.ACCUMULATING_FIRED_PANES) { - preCombineStrategy = preCombineStrategy.withMode( - WindowingStrategy.AccumulationMode.DISCARDING_FIRED_PANES); - } - - // Combine the hot and cold keys separately. - PCollection>> precombinedHot = split - .get(hot) - .setCoder(KvCoder.of(KvCoder.of(inputCoder.getKeyCoder(), VarIntCoder.of()), - inputCoder.getValueCoder())) - .setWindowingStrategyInternal(preCombineStrategy) - .apply("PreCombineHot", Combine.perKey(hotPreCombine)) - .apply(ParDo.named("StripNonce").of( - new DoFn, AccumT>, - KV>>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of( - c.element().getKey().getKey(), - InputOrAccum.accum(c.element().getValue()))); - } - })) - .setCoder(KvCoder.of(inputCoder.getKeyCoder(), inputOrAccumCoder)) - .apply(Window.>>remerge()) - .setWindowingStrategyInternal(input.getWindowingStrategy()); - PCollection>> preprocessedCold = split - .get(cold) - .setCoder(inputCoder) - .apply(ParDo.named("PrepareCold").of( - new DoFn, KV>>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element().getKey(), - InputOrAccum.input(c.element().getValue()))); - } - })) - .setCoder(KvCoder.of(inputCoder.getKeyCoder(), inputOrAccumCoder)); - - // Combine the union of the pre-processed hot and cold key results. - return PCollectionList.of(precombinedHot).and(preprocessedCold) - .apply(Flatten.>>pCollections()) - .apply("PostCombine", Combine.perKey(postCombine)); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - Combine.populateDisplayData(builder, fn, fnDisplayData); - builder.add(DisplayData.item("fanoutFn", hotKeyFanout.getClass()) - .withLabel("Fanout Function")); - } - - /** - * Used to store either an input or accumulator value, for flattening - * the hot and cold key paths. - */ - private static class InputOrAccum { - public final InputT input; - public final AccumT accum; - - private InputOrAccum(InputT input, AccumT aggr) { - this.input = input; - this.accum = aggr; - } - - public static InputOrAccum input(InputT input) { - return new InputOrAccum(input, null); - } - - public static InputOrAccum accum(AccumT aggr) { - return new InputOrAccum(null, aggr); - } - - private static class InputOrAccumCoder - extends StandardCoder> { - - private final Coder inputCoder; - private final Coder accumCoder; - - public InputOrAccumCoder(Coder inputCoder, Coder accumCoder) { - this.inputCoder = inputCoder; - this.accumCoder = accumCoder; - } - - @JsonCreator - @SuppressWarnings({"rawtypes", "unchecked"}) - public static InputOrAccumCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> elementCoders) { - return new InputOrAccumCoder(elementCoders.get(0), elementCoders.get(1)); - } - - @Override - public void encode( - InputOrAccum value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - if (value.input != null) { - outStream.write(0); - inputCoder.encode(value.input, outStream, context); - } else { - outStream.write(1); - accumCoder.encode(value.accum, outStream, context); - } - } - - @Override - public InputOrAccum decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - if (inStream.read() == 0) { - return InputOrAccum.input(inputCoder.decode(inStream, context)); - } else { - return InputOrAccum.accum(accumCoder.decode(inStream, context)); - } - } - - @Override - public List> getCoderArguments() { - return ImmutableList.of(inputCoder, accumCoder); - } - - @Override - public void verifyDeterministic() throws Coder.NonDeterministicException { - inputCoder.verifyDeterministic(); - accumCoder.verifyDeterministic(); - } - } - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * {@code GroupedValues} takes a - * {@code PCollection>>}, such as the result of - * {@link GroupByKey}, applies a specified - * {@link KeyedCombineFn KeyedCombineFn<K, InputT, AccumT, OutputT>} - * to each of the input {@code KV>} elements to - * produce a combined output {@code KV} element, and returns a - * {@code PCollection>} containing all the combined output - * elements. It is common for {@code InputT == OutputT}, but not required. - * Common combining functions include sums, mins, maxes, and averages - * of numbers, conjunctions and disjunctions of booleans, statistical - * aggregations, etc. - * - *

              Example of use: - *

               {@code
              -   * PCollection> pc = ...;
              -   * PCollection>> groupedByKey = pc.apply(
              -   *     new GroupByKey());
              -   * PCollection> sumByKey = groupedByKey.apply(
              -   *     Combine.groupedValues(
              -   *         new Sum.SumIntegerFn()));
              -   * } 
              - * - *

              See also {@link #perKey}/{@link PerKey Combine.PerKey}, which - * captures the common pattern of "combining by key" in a - * single easy-to-use {@code PTransform}. - * - *

              Combining for different keys can happen in parallel. Moreover, - * combining of the {@code Iterable} values associated a single - * key can happen in parallel, with different subsets of the values - * being combined separately, and their intermediate results combined - * further, in an arbitrary tree reduction pattern, until a single - * result value is produced for each key. - * - *

              By default, the {@code Coder} of the keys of the output - * {@code PCollection>} is that of the keys of the input - * {@code PCollection>}, and the {@code Coder} of the values - * of the output {@code PCollection>} is inferred from the - * concrete type of the {@code KeyedCombineFn}'s output - * type {@code OutputT}. - * - *

              Each output element has the same timestamp and is in the same window - * as its corresponding input element, and the output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - *

              See also {@link #globally}/{@link Globally Combine.Globally}, which - * combines all the values in a {@code PCollection} into a - * single value in a {@code PCollection}. - * - * @param type of input and output keys - * @param type of input values - * @param type of output values - */ - public static class GroupedValues - extends PTransform - >>, - PCollection>> { - - private final PerKeyCombineFn fn; - private final DisplayData.Item> fnDisplayData; - private final List> sideInputs; - - private GroupedValues( - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData) { - this.fn = SerializableUtils.clone(fn); - this.fnDisplayData = fnDisplayData; - this.sideInputs = ImmutableList.of(); - } - - private GroupedValues( - PerKeyCombineFn fn, - DisplayData.Item> fnDisplayData, - List> sideInputs) { - this.fn = SerializableUtils.clone(fn); - this.fnDisplayData = fnDisplayData; - this.sideInputs = sideInputs; - } - - public GroupedValues withSideInputs( - Iterable> sideInputs) { - return new GroupedValues<>(fn, fnDisplayData, ImmutableList.copyOf(sideInputs)); - } - - /** - * Returns the KeyedCombineFn used by this Combine operation. - */ - public PerKeyCombineFn getFn() { - return fn; - } - - public List> getSideInputs() { - return sideInputs; - } - - @Override - public PCollection> apply( - PCollection>> input) { - - final PerKeyCombineFnRunner combineFnRunner = - PerKeyCombineFnRunners.create(fn); - PCollection> output = input.apply(ParDo.of( - new DoFn>, KV>() { - @Override - public void processElement(ProcessContext c) { - K key = c.element().getKey(); - - c.output(KV.of(key, combineFnRunner.apply(key, c.element().getValue(), c))); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - Combine.GroupedValues.this.populateDisplayData(builder); - } - }).withSideInputs(sideInputs)); - - try { - Coder> outputCoder = getDefaultOutputCoder(input); - output.setCoder(outputCoder); - } catch (CannotProvideCoderException exc) { - // let coder inference happen later, if it can - } - - return output; - } - - /** - * Returns the {@link CombineFn} bound to its coders. - * - *

              For internal use. - */ - public AppliedCombineFn getAppliedFn( - CoderRegistry registry, Coder>> inputCoder, - WindowingStrategy windowingStrategy) { - KvCoder kvCoder = getKvCoder(inputCoder); - return AppliedCombineFn.withInputCoder( - fn, registry, kvCoder, sideInputs, windowingStrategy); - } - - private KvCoder getKvCoder( - Coder>> inputCoder) { - if (!(inputCoder instanceof KvCoder)) { - throw new IllegalStateException( - "Combine.GroupedValues requires its input to use KvCoder"); - } - @SuppressWarnings({"unchecked", "rawtypes"}) - KvCoder> kvCoder = (KvCoder) inputCoder; - Coder keyCoder = kvCoder.getKeyCoder(); - Coder> kvValueCoder = kvCoder.getValueCoder(); - if (!(kvValueCoder instanceof IterableCoder)) { - throw new IllegalStateException( - "Combine.GroupedValues requires its input values to use " - + "IterableCoder"); - } - @SuppressWarnings("unchecked") - IterableCoder inputValuesCoder = (IterableCoder) kvValueCoder; - Coder inputValueCoder = inputValuesCoder.getElemCoder(); - return KvCoder.of(keyCoder, inputValueCoder); - } - - @Override - public Coder> getDefaultOutputCoder( - PCollection>> input) - throws CannotProvideCoderException { - KvCoder kvCoder = getKvCoder(input.getCoder()); - @SuppressWarnings("unchecked") - Coder outputValueCoder = - ((PerKeyCombineFn) fn) - .getDefaultOutputCoder( - input.getPipeline().getCoderRegistry(), - kvCoder.getKeyCoder(), kvCoder.getValueCoder()); - return KvCoder.of(kvCoder.getKeyCoder(), outputValueCoder); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Combine.populateDisplayData(builder, fn, fnDisplayData); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java deleted file mode 100644 index ff6e7b5918..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFnBase.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableMap; - -import java.io.Serializable; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; - -/** - * This class contains the shared interfaces and abstract classes for different types of combine - * functions. - * - *

              Users should not implement or extend them directly. - */ -public class CombineFnBase { - /** - * A {@code GloballyCombineFn} specifies how to combine a - * collection of input values of type {@code InputT} into a single - * output value of type {@code OutputT}. It does this via one or more - * intermediate mutable accumulator values of type {@code AccumT}. - * - *

              Do not implement this interface directly. - * Extends {@link CombineFn} and {@link CombineFnWithContext} instead. - * - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - public interface GlobalCombineFn extends Serializable, HasDisplayData { - - /** - * Returns the {@code Coder} to use for accumulator {@code AccumT} - * values, or null if it is not able to be inferred. - * - *

              By default, uses the knowledge of the {@code Coder} being used - * for {@code InputT} values and the enclosing {@code Pipeline}'s - * {@code CoderRegistry} to try to infer the Coder for {@code AccumT} - * values. - * - *

              This is the Coder used to send data through a communication-intensive - * shuffle step, so a compact and efficient representation may have - * significant performance benefits. - */ - Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException; - - /** - * Returns the {@code Coder} to use by default for output - * {@code OutputT} values, or null if it is not able to be inferred. - * - *

              By default, uses the knowledge of the {@code Coder} being - * used for input {@code InputT} values and the enclosing - * {@code Pipeline}'s {@code CoderRegistry} to try to infer the - * Coder for {@code OutputT} values. - */ - Coder getDefaultOutputCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException; - - /** - * Returns the error message for not supported default values in Combine.globally(). - */ - String getIncompatibleGlobalWindowErrorMessage(); - - /** - * Returns the default value when there are no values added to the accumulator. - */ - OutputT defaultValue(); - - /** - * Converts this {@code GloballyCombineFn} into an equivalent - * {@link PerKeyCombineFn} that ignores the keys passed to it and - * combines the values according to this {@code GloballyCombineFn}. - * - * @param the type of the (ignored) keys - */ - PerKeyCombineFn asKeyedFn(); - } - - /** - * A {@code PerKeyCombineFn} specifies how to combine - * a collection of input values of type {@code InputT}, associated with - * a key of type {@code K}, into a single output value of type - * {@code OutputT}. It does this via one or more intermediate mutable - * accumulator values of type {@code AccumT}. - * - *

              Do not implement this interface directly. - * Extends {@link KeyedCombineFn} and {@link KeyedCombineFnWithContext} instead. - * - * @param type of keys - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - public interface PerKeyCombineFn - extends Serializable, HasDisplayData { - /** - * Returns the {@code Coder} to use for accumulator {@code AccumT} - * values, or null if it is not able to be inferred. - * - *

              By default, uses the knowledge of the {@code Coder} being - * used for {@code K} keys and input {@code InputT} values and the - * enclosing {@code Pipeline}'s {@code CoderRegistry} to try to - * infer the Coder for {@code AccumT} values. - * - *

              This is the Coder used to send data through a communication-intensive - * shuffle step, so a compact and efficient representation may have - * significant performance benefits. - */ - Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException; - - /** - * Returns the {@code Coder} to use by default for output - * {@code OutputT} values, or null if it is not able to be inferred. - * - *

              By default, uses the knowledge of the {@code Coder} being - * used for {@code K} keys and input {@code InputT} values and the - * enclosing {@code Pipeline}'s {@code CoderRegistry} to try to - * infer the Coder for {@code OutputT} values. - */ - Coder getDefaultOutputCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException; - - /** - * Returns the a regular {@link GlobalCombineFn} that operates on a specific key. - */ - GlobalCombineFn forKey(K key, Coder keyCoder); - } - - /** - * An abstract {@link GlobalCombineFn} base class shared by - * {@link CombineFn} and {@link CombineFnWithContext}. - * - *

              Do not extend this class directly. - * Extends {@link CombineFn} and {@link CombineFnWithContext} instead. - * - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - abstract static class AbstractGlobalCombineFn - implements GlobalCombineFn, Serializable { - private static final String INCOMPATIBLE_GLOBAL_WINDOW_ERROR_MESSAGE = - "Default values are not supported in Combine.globally() if the output " - + "PCollection is not windowed by GlobalWindows. Instead, use " - + "Combine.globally().withoutDefaults() to output an empty PCollection if the input " - + "PCollection is empty, or Combine.globally().asSingletonView() to get the default " - + "output of the CombineFn if the input PCollection is empty."; - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException { - return registry.getDefaultCoder(getClass(), AbstractGlobalCombineFn.class, - ImmutableMap.>of(getInputTVariable(), inputCoder), getAccumTVariable()); - } - - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException { - return registry.getDefaultCoder(getClass(), AbstractGlobalCombineFn.class, - ImmutableMap.>of(getInputTVariable(), inputCoder, getAccumTVariable(), - this.getAccumulatorCoder(registry, inputCoder)), - getOutputTVariable()); - } - - @Override - public String getIncompatibleGlobalWindowErrorMessage() { - return INCOMPATIBLE_GLOBAL_WINDOW_ERROR_MESSAGE; - } - - /** - * Returns the {@link TypeVariable} of {@code InputT}. - */ - public TypeVariable getInputTVariable() { - return (TypeVariable) - new TypeDescriptor(AbstractGlobalCombineFn.class) {}.getType(); - } - - /** - * Returns the {@link TypeVariable} of {@code AccumT}. - */ - public TypeVariable getAccumTVariable() { - return (TypeVariable) - new TypeDescriptor(AbstractGlobalCombineFn.class) {}.getType(); - } - - /** - * Returns the {@link TypeVariable} of {@code OutputT}. - */ - public TypeVariable getOutputTVariable() { - return (TypeVariable) - new TypeDescriptor(AbstractGlobalCombineFn.class) {}.getType(); - } - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(DisplayData.Builder builder) { - } - } - - /** - * An abstract {@link PerKeyCombineFn} base class shared by - * {@link KeyedCombineFn} and {@link KeyedCombineFnWithContext}. - * - *

              Do not extends this class directly. - * Extends {@link KeyedCombineFn} and {@link KeyedCombineFnWithContext} instead. - * - * @param type of keys - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - abstract static class AbstractPerKeyCombineFn - implements PerKeyCombineFn { - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return registry.getDefaultCoder(getClass(), AbstractPerKeyCombineFn.class, - ImmutableMap.>of( - getKTypeVariable(), keyCoder, getInputTVariable(), inputCoder), - getAccumTVariable()); - } - - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return registry.getDefaultCoder(getClass(), AbstractPerKeyCombineFn.class, - ImmutableMap.>of(getKTypeVariable(), keyCoder, getInputTVariable(), - inputCoder, getAccumTVariable(), - this.getAccumulatorCoder(registry, keyCoder, inputCoder)), - getOutputTVariable()); - } - - /** - * Returns the {@link TypeVariable} of {@code K}. - */ - public TypeVariable getKTypeVariable() { - return (TypeVariable) new TypeDescriptor(AbstractPerKeyCombineFn.class) {}.getType(); - } - - /** - * Returns the {@link TypeVariable} of {@code InputT}. - */ - public TypeVariable getInputTVariable() { - return (TypeVariable) - new TypeDescriptor(AbstractPerKeyCombineFn.class) {}.getType(); - } - - /** - * Returns the {@link TypeVariable} of {@code AccumT}. - */ - public TypeVariable getAccumTVariable() { - return (TypeVariable) - new TypeDescriptor(AbstractPerKeyCombineFn.class) {}.getType(); - } - - /** - * Returns the {@link TypeVariable} of {@code OutputT}. - */ - public TypeVariable getOutputTVariable() { - return (TypeVariable) - new TypeDescriptor(AbstractPerKeyCombineFn.class) {}.getType(); - } - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(DisplayData.Builder builder) { - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java deleted file mode 100644 index b9ee5aeeeb..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineFns.java +++ /dev/null @@ -1,1166 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.GlobalCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Static utility methods that create combine function instances. - */ -public class CombineFns { - - /** - * Returns a {@link ComposeKeyedCombineFnBuilder} to construct a composed - * {@link PerKeyCombineFn}. - * - *

              The same {@link TupleTag} cannot be used in a composition multiple times. - * - *

              Example: - *

              {@code
              -   * PCollection> latencies = ...;
              -   *
              -   * TupleTag maxLatencyTag = new TupleTag();
              -   * TupleTag meanLatencyTag = new TupleTag();
              -   *
              -   * SimpleFunction identityFn =
              -   *     new SimpleFunction() {
              -   *       public Integer apply(Integer input) {
              -   *           return input;
              -   *       }};
              -   * PCollection> maxAndMean = latencies.apply(
              -   *     Combine.perKey(
              -   *         CombineFns.composeKeyed()
              -   *            .with(identityFn, new MaxIntegerFn(), maxLatencyTag)
              -   *            .with(identityFn, new MeanFn(), meanLatencyTag)));
              -   *
              -   * PCollection finalResultCollection = maxAndMean
              -   *     .apply(ParDo.of(
              -   *         new DoFn, T>() {
              -   *           public void processElement(ProcessContext c) throws Exception {
              -   *             KV e = c.element();
              -   *             Integer maxLatency = e.getValue().get(maxLatencyTag);
              -   *             Double meanLatency = e.getValue().get(meanLatencyTag);
              -   *             .... Do Something ....
              -   *             c.output(...some T...);
              -   *           }
              -   *         }));
              -   * }
              - */ - public static ComposeKeyedCombineFnBuilder composeKeyed() { - return new ComposeKeyedCombineFnBuilder(); - } - - /** - * Returns a {@link ComposeCombineFnBuilder} to construct a composed - * {@link GlobalCombineFn}. - * - *

              The same {@link TupleTag} cannot be used in a composition multiple times. - * - *

              Example: - *

              {@code
              -   * PCollection globalLatencies = ...;
              -   *
              -   * TupleTag maxLatencyTag = new TupleTag();
              -   * TupleTag meanLatencyTag = new TupleTag();
              -   *
              -   * SimpleFunction identityFn =
              -   *     new SimpleFunction() {
              -   *       public Integer apply(Integer input) {
              -   *           return input;
              -   *       }};
              -   * PCollection maxAndMean = globalLatencies.apply(
              -   *     Combine.globally(
              -   *         CombineFns.compose()
              -   *            .with(identityFn, new MaxIntegerFn(), maxLatencyTag)
              -   *            .with(identityFn, new MeanFn(), meanLatencyTag)));
              -   *
              -   * PCollection finalResultCollection = maxAndMean
              -   *     .apply(ParDo.of(
              -   *         new DoFn() {
              -   *           public void processElement(ProcessContext c) throws Exception {
              -   *             CoCombineResult e = c.element();
              -   *             Integer maxLatency = e.get(maxLatencyTag);
              -   *             Double meanLatency = e.get(meanLatencyTag);
              -   *             .... Do Something ....
              -   *             c.output(...some T...);
              -   *           }
              -   *         }));
              -   * }
              - */ - public static ComposeCombineFnBuilder compose() { - return new ComposeCombineFnBuilder(); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A builder class to construct a composed {@link PerKeyCombineFn}. - */ - public static class ComposeKeyedCombineFnBuilder { - /** - * Returns a {@link ComposedKeyedCombineFn} that can take additional - * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. - * - *

              The {@link ComposedKeyedCombineFn} extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them with the {@code keyedCombineFn}, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public ComposedKeyedCombineFn with( - SimpleFunction extractInputFn, - KeyedCombineFn keyedCombineFn, - TupleTag outputTag) { - return new ComposedKeyedCombineFn() - .with(extractInputFn, keyedCombineFn, outputTag); - } - - /** - * Returns a {@link ComposedKeyedCombineFnWithContext} that can take additional - * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. - * - *

              The {@link ComposedKeyedCombineFnWithContext} extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them with the {@code keyedCombineFnWithContext}, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public ComposedKeyedCombineFnWithContext with( - SimpleFunction extractInputFn, - KeyedCombineFnWithContext keyedCombineFnWithContext, - TupleTag outputTag) { - return new ComposedKeyedCombineFnWithContext() - .with(extractInputFn, keyedCombineFnWithContext, outputTag); - } - - /** - * Returns a {@link ComposedKeyedCombineFn} that can take additional - * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. - */ - public ComposedKeyedCombineFn with( - SimpleFunction extractInputFn, - CombineFn combineFn, - TupleTag outputTag) { - return with(extractInputFn, combineFn.asKeyedFn(), outputTag); - } - - /** - * Returns a {@link ComposedKeyedCombineFnWithContext} that can take additional - * {@link PerKeyCombineFn PerKeyCombineFns} and apply them as a single combine function. - */ - public ComposedKeyedCombineFnWithContext with( - SimpleFunction extractInputFn, - CombineFnWithContext combineFnWithContext, - TupleTag outputTag) { - return with(extractInputFn, combineFnWithContext.asKeyedFn(), outputTag); - } - } - - /** - * A builder class to construct a composed {@link GlobalCombineFn}. - */ - public static class ComposeCombineFnBuilder { - /** - * Returns a {@link ComposedCombineFn} that can take additional - * {@link GlobalCombineFn GlobalCombineFns} and apply them as a single combine function. - * - *

              The {@link ComposedCombineFn} extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them with the {@code combineFn}, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public ComposedCombineFn with( - SimpleFunction extractInputFn, - CombineFn combineFn, - TupleTag outputTag) { - return new ComposedCombineFn() - .with(extractInputFn, combineFn, outputTag); - } - - /** - * Returns a {@link ComposedCombineFnWithContext} that can take additional - * {@link GlobalCombineFn GlobalCombineFns} and apply them as a single combine function. - * - *

              The {@link ComposedCombineFnWithContext} extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them with the {@code combineFnWithContext}, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public ComposedCombineFnWithContext with( - SimpleFunction extractInputFn, - CombineFnWithContext combineFnWithContext, - TupleTag outputTag) { - return new ComposedCombineFnWithContext() - .with(extractInputFn, combineFnWithContext, outputTag); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A tuple of outputs produced by a composed combine functions. - * - *

              See {@link #compose()} or {@link #composeKeyed()}) for details. - */ - public static class CoCombineResult implements Serializable { - - private enum NullValue { - INSTANCE; - } - - private final Map, Object> valuesMap; - - /** - * The constructor of {@link CoCombineResult}. - * - *

              Null values should have been filtered out from the {@code valuesMap}. - * {@link TupleTag TupleTags} that associate with null values doesn't exist in the key set of - * {@code valuesMap}. - * - * @throws NullPointerException if any key or value in {@code valuesMap} is null - */ - CoCombineResult(Map, Object> valuesMap) { - ImmutableMap.Builder, Object> builder = ImmutableMap.builder(); - for (Entry, Object> entry : valuesMap.entrySet()) { - if (entry.getValue() != null) { - builder.put(entry); - } else { - builder.put(entry.getKey(), NullValue.INSTANCE); - } - } - this.valuesMap = builder.build(); - } - - /** - * Returns the value represented by the given {@link TupleTag}. - * - *

              It is an error to request a non-exist tuple tag from the {@link CoCombineResult}. - */ - @SuppressWarnings("unchecked") - public V get(TupleTag tag) { - checkArgument( - valuesMap.keySet().contains(tag), "TupleTag " + tag + " is not in the CoCombineResult"); - Object value = valuesMap.get(tag); - if (value == NullValue.INSTANCE) { - return null; - } else { - return (V) value; - } - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A composed {@link CombineFn} that applies multiple {@link CombineFn CombineFns}. - * - *

              For each {@link CombineFn} it extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public static class ComposedCombineFn extends CombineFn { - - private final List> combineFns; - private final List> extractInputFns; - private final List> outputTags; - private final int combineFnCount; - - private ComposedCombineFn() { - this.extractInputFns = ImmutableList.of(); - this.combineFns = ImmutableList.of(); - this.outputTags = ImmutableList.of(); - this.combineFnCount = 0; - } - - private ComposedCombineFn( - ImmutableList> extractInputFns, - ImmutableList> combineFns, - ImmutableList> outputTags) { - @SuppressWarnings({"unchecked", "rawtypes"}) - List> castedExtractInputFns = (List) extractInputFns; - this.extractInputFns = castedExtractInputFns; - - @SuppressWarnings({"unchecked", "rawtypes"}) - List> castedCombineFns = (List) combineFns; - this.combineFns = castedCombineFns; - - this.outputTags = outputTags; - this.combineFnCount = this.combineFns.size(); - } - - /** - * Returns a {@link ComposedCombineFn} with an additional {@link CombineFn}. - */ - public ComposedCombineFn with( - SimpleFunction extractInputFn, - CombineFn combineFn, - TupleTag outputTag) { - checkUniqueness(outputTags, outputTag); - return new ComposedCombineFn<>( - ImmutableList.>builder() - .addAll(extractInputFns) - .add(extractInputFn) - .build(), - ImmutableList.>builder() - .addAll(combineFns) - .add(combineFn) - .build(), - ImmutableList.>builder() - .addAll(outputTags) - .add(outputTag) - .build()); - } - - /** - * Returns a {@link ComposedCombineFnWithContext} with an additional - * {@link CombineFnWithContext}. - */ - public ComposedCombineFnWithContext with( - SimpleFunction extractInputFn, - CombineFnWithContext combineFn, - TupleTag outputTag) { - checkUniqueness(outputTags, outputTag); - List> fnsWithContext = Lists.newArrayList(); - for (CombineFn fn : combineFns) { - fnsWithContext.add(toFnWithContext(fn)); - } - return new ComposedCombineFnWithContext<>( - ImmutableList.>builder() - .addAll(extractInputFns) - .add(extractInputFn) - .build(), - ImmutableList.>builder() - .addAll(fnsWithContext) - .add(combineFn) - .build(), - ImmutableList.>builder() - .addAll(outputTags) - .add(outputTag) - .build()); - } - - @Override - public Object[] createAccumulator() { - Object[] accumsArray = new Object[combineFnCount]; - for (int i = 0; i < combineFnCount; ++i) { - accumsArray[i] = combineFns.get(i).createAccumulator(); - } - return accumsArray; - } - - @Override - public Object[] addInput(Object[] accumulator, DataT value) { - for (int i = 0; i < combineFnCount; ++i) { - Object input = extractInputFns.get(i).apply(value); - accumulator[i] = combineFns.get(i).addInput(accumulator[i], input); - } - return accumulator; - } - - @Override - public Object[] mergeAccumulators(Iterable accumulators) { - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(); - } else { - // Reuses the first accumulator, and overwrites its values. - // It is safe because {@code accum[i]} only depends on - // the i-th component of each accumulator. - Object[] accum = iter.next(); - for (int i = 0; i < combineFnCount; ++i) { - accum[i] = combineFns.get(i).mergeAccumulators(new ProjectionIterable(accumulators, i)); - } - return accum; - } - } - - @Override - public CoCombineResult extractOutput(Object[] accumulator) { - Map, Object> valuesMap = Maps.newHashMap(); - for (int i = 0; i < combineFnCount; ++i) { - valuesMap.put( - outputTags.get(i), - combineFns.get(i).extractOutput(accumulator[i])); - } - return new CoCombineResult(valuesMap); - } - - @Override - public Object[] compact(Object[] accumulator) { - for (int i = 0; i < combineFnCount; ++i) { - accumulator[i] = combineFns.get(i).compact(accumulator[i]); - } - return accumulator; - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder dataCoder) - throws CannotProvideCoderException { - List> coders = Lists.newArrayList(); - for (int i = 0; i < combineFnCount; ++i) { - Coder inputCoder = - registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); - coders.add(combineFns.get(i).getAccumulatorCoder(registry, inputCoder)); - } - return new ComposedAccumulatorCoder(coders); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - CombineFns.populateDisplayData(builder, combineFns); - } - } - - /** - * A composed {@link CombineFnWithContext} that applies multiple - * {@link CombineFnWithContext CombineFnWithContexts}. - * - *

              For each {@link CombineFnWithContext} it extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public static class ComposedCombineFnWithContext - extends CombineFnWithContext { - - private final List> extractInputFns; - private final List> combineFnWithContexts; - private final List> outputTags; - private final int combineFnCount; - - private ComposedCombineFnWithContext() { - this.extractInputFns = ImmutableList.of(); - this.combineFnWithContexts = ImmutableList.of(); - this.outputTags = ImmutableList.of(); - this.combineFnCount = 0; - } - - private ComposedCombineFnWithContext( - ImmutableList> extractInputFns, - ImmutableList> combineFnWithContexts, - ImmutableList> outputTags) { - @SuppressWarnings({"unchecked", "rawtypes"}) - List> castedExtractInputFns = - (List) extractInputFns; - this.extractInputFns = castedExtractInputFns; - - @SuppressWarnings({"rawtypes", "unchecked"}) - List> castedCombineFnWithContexts - = (List) combineFnWithContexts; - this.combineFnWithContexts = castedCombineFnWithContexts; - - this.outputTags = outputTags; - this.combineFnCount = this.combineFnWithContexts.size(); - } - - /** - * Returns a {@link ComposedCombineFnWithContext} with an additional {@link GlobalCombineFn}. - */ - public ComposedCombineFnWithContext with( - SimpleFunction extractInputFn, - GlobalCombineFn globalCombineFn, - TupleTag outputTag) { - checkUniqueness(outputTags, outputTag); - return new ComposedCombineFnWithContext<>( - ImmutableList.>builder() - .addAll(extractInputFns) - .add(extractInputFn) - .build(), - ImmutableList.>builder() - .addAll(combineFnWithContexts) - .add(toFnWithContext(globalCombineFn)) - .build(), - ImmutableList.>builder() - .addAll(outputTags) - .add(outputTag) - .build()); - } - - @Override - public Object[] createAccumulator(Context c) { - Object[] accumsArray = new Object[combineFnCount]; - for (int i = 0; i < combineFnCount; ++i) { - accumsArray[i] = combineFnWithContexts.get(i).createAccumulator(c); - } - return accumsArray; - } - - @Override - public Object[] addInput(Object[] accumulator, DataT value, Context c) { - for (int i = 0; i < combineFnCount; ++i) { - Object input = extractInputFns.get(i).apply(value); - accumulator[i] = combineFnWithContexts.get(i).addInput(accumulator[i], input, c); - } - return accumulator; - } - - @Override - public Object[] mergeAccumulators(Iterable accumulators, Context c) { - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(c); - } else { - // Reuses the first accumulator, and overwrites its values. - // It is safe because {@code accum[i]} only depends on - // the i-th component of each accumulator. - Object[] accum = iter.next(); - for (int i = 0; i < combineFnCount; ++i) { - accum[i] = combineFnWithContexts.get(i).mergeAccumulators( - new ProjectionIterable(accumulators, i), c); - } - return accum; - } - } - - @Override - public CoCombineResult extractOutput(Object[] accumulator, Context c) { - Map, Object> valuesMap = Maps.newHashMap(); - for (int i = 0; i < combineFnCount; ++i) { - valuesMap.put( - outputTags.get(i), - combineFnWithContexts.get(i).extractOutput(accumulator[i], c)); - } - return new CoCombineResult(valuesMap); - } - - @Override - public Object[] compact(Object[] accumulator, Context c) { - for (int i = 0; i < combineFnCount; ++i) { - accumulator[i] = combineFnWithContexts.get(i).compact(accumulator[i], c); - } - return accumulator; - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder dataCoder) - throws CannotProvideCoderException { - List> coders = Lists.newArrayList(); - for (int i = 0; i < combineFnCount; ++i) { - Coder inputCoder = - registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); - coders.add(combineFnWithContexts.get(i).getAccumulatorCoder(registry, inputCoder)); - } - return new ComposedAccumulatorCoder(coders); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - CombineFns.populateDisplayData(builder, combineFnWithContexts); - } - } - - /** - * A composed {@link KeyedCombineFn} that applies multiple {@link KeyedCombineFn KeyedCombineFns}. - * - *

              For each {@link KeyedCombineFn} it extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public static class ComposedKeyedCombineFn - extends KeyedCombineFn { - - private final List> extractInputFns; - private final List> keyedCombineFns; - private final List> outputTags; - private final int combineFnCount; - - private ComposedKeyedCombineFn() { - this.extractInputFns = ImmutableList.of(); - this.keyedCombineFns = ImmutableList.of(); - this.outputTags = ImmutableList.of(); - this.combineFnCount = 0; - } - - private ComposedKeyedCombineFn( - ImmutableList> extractInputFns, - ImmutableList> keyedCombineFns, - ImmutableList> outputTags) { - @SuppressWarnings({"unchecked", "rawtypes"}) - List> castedExtractInputFns = (List) extractInputFns; - this.extractInputFns = castedExtractInputFns; - - @SuppressWarnings({"unchecked", "rawtypes"}) - List> castedKeyedCombineFns = - (List) keyedCombineFns; - this.keyedCombineFns = castedKeyedCombineFns; - this.outputTags = outputTags; - this.combineFnCount = this.keyedCombineFns.size(); - } - - /** - * Returns a {@link ComposedKeyedCombineFn} with an additional {@link KeyedCombineFn}. - */ - public ComposedKeyedCombineFn with( - SimpleFunction extractInputFn, - KeyedCombineFn keyedCombineFn, - TupleTag outputTag) { - checkUniqueness(outputTags, outputTag); - return new ComposedKeyedCombineFn<>( - ImmutableList.>builder() - .addAll(extractInputFns) - .add(extractInputFn) - .build(), - ImmutableList.>builder() - .addAll(keyedCombineFns) - .add(keyedCombineFn) - .build(), - ImmutableList.>builder() - .addAll(outputTags) - .add(outputTag) - .build()); - } - - /** - * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional - * {@link KeyedCombineFnWithContext}. - */ - public ComposedKeyedCombineFnWithContext with( - SimpleFunction extractInputFn, - KeyedCombineFnWithContext keyedCombineFn, - TupleTag outputTag) { - checkUniqueness(outputTags, outputTag); - List> fnsWithContext = - Lists.newArrayList(); - for (KeyedCombineFn fn : keyedCombineFns) { - fnsWithContext.add(toFnWithContext(fn)); - } - return new ComposedKeyedCombineFnWithContext<>( - ImmutableList.>builder() - .addAll(extractInputFns) - .add(extractInputFn) - .build(), - ImmutableList.>builder() - .addAll(fnsWithContext) - .add(keyedCombineFn) - .build(), - ImmutableList.>builder() - .addAll(outputTags) - .add(outputTag) - .build()); - } - - /** - * Returns a {@link ComposedKeyedCombineFn} with an additional {@link CombineFn}. - */ - public ComposedKeyedCombineFn with( - SimpleFunction extractInputFn, - CombineFn keyedCombineFn, - TupleTag outputTag) { - return with(extractInputFn, keyedCombineFn.asKeyedFn(), outputTag); - } - - /** - * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional - * {@link CombineFnWithContext}. - */ - public ComposedKeyedCombineFnWithContext with( - SimpleFunction extractInputFn, - CombineFnWithContext keyedCombineFn, - TupleTag outputTag) { - return with(extractInputFn, keyedCombineFn.asKeyedFn(), outputTag); - } - - @Override - public Object[] createAccumulator(K key) { - Object[] accumsArray = new Object[combineFnCount]; - for (int i = 0; i < combineFnCount; ++i) { - accumsArray[i] = keyedCombineFns.get(i).createAccumulator(key); - } - return accumsArray; - } - - @Override - public Object[] addInput(K key, Object[] accumulator, DataT value) { - for (int i = 0; i < combineFnCount; ++i) { - Object input = extractInputFns.get(i).apply(value); - accumulator[i] = keyedCombineFns.get(i).addInput(key, accumulator[i], input); - } - return accumulator; - } - - @Override - public Object[] mergeAccumulators(K key, final Iterable accumulators) { - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(key); - } else { - // Reuses the first accumulator, and overwrites its values. - // It is safe because {@code accum[i]} only depends on - // the i-th component of each accumulator. - Object[] accum = iter.next(); - for (int i = 0; i < combineFnCount; ++i) { - accum[i] = keyedCombineFns.get(i).mergeAccumulators( - key, new ProjectionIterable(accumulators, i)); - } - return accum; - } - } - - @Override - public CoCombineResult extractOutput(K key, Object[] accumulator) { - Map, Object> valuesMap = Maps.newHashMap(); - for (int i = 0; i < combineFnCount; ++i) { - valuesMap.put( - outputTags.get(i), - keyedCombineFns.get(i).extractOutput(key, accumulator[i])); - } - return new CoCombineResult(valuesMap); - } - - @Override - public Object[] compact(K key, Object[] accumulator) { - for (int i = 0; i < combineFnCount; ++i) { - accumulator[i] = keyedCombineFns.get(i).compact(key, accumulator[i]); - } - return accumulator; - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder keyCoder, Coder dataCoder) - throws CannotProvideCoderException { - List> coders = Lists.newArrayList(); - for (int i = 0; i < combineFnCount; ++i) { - Coder inputCoder = - registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); - coders.add(keyedCombineFns.get(i).getAccumulatorCoder(registry, keyCoder, inputCoder)); - } - return new ComposedAccumulatorCoder(coders); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - CombineFns.populateDisplayData(builder, keyedCombineFns); - } - } - - /** - * A composed {@link KeyedCombineFnWithContext} that applies multiple - * {@link KeyedCombineFnWithContext KeyedCombineFnWithContexts}. - * - *

              For each {@link KeyedCombineFnWithContext} it extracts inputs from {@code DataT} with - * the {@code extractInputFn} and combines them, - * and then it outputs each combined value with a {@link TupleTag} to a - * {@link CoCombineResult}. - */ - public static class ComposedKeyedCombineFnWithContext - extends KeyedCombineFnWithContext { - - private final List> extractInputFns; - private final List> keyedCombineFns; - private final List> outputTags; - private final int combineFnCount; - - private ComposedKeyedCombineFnWithContext() { - this.extractInputFns = ImmutableList.of(); - this.keyedCombineFns = ImmutableList.of(); - this.outputTags = ImmutableList.of(); - this.combineFnCount = 0; - } - - private ComposedKeyedCombineFnWithContext( - ImmutableList> extractInputFns, - ImmutableList> keyedCombineFns, - ImmutableList> outputTags) { - @SuppressWarnings({"unchecked", "rawtypes"}) - List> castedExtractInputFns = - (List) extractInputFns; - this.extractInputFns = castedExtractInputFns; - - @SuppressWarnings({"unchecked", "rawtypes"}) - List> castedKeyedCombineFns = - (List) keyedCombineFns; - this.keyedCombineFns = castedKeyedCombineFns; - this.outputTags = outputTags; - this.combineFnCount = this.keyedCombineFns.size(); - } - - /** - * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional - * {@link PerKeyCombineFn}. - */ - public ComposedKeyedCombineFnWithContext with( - SimpleFunction extractInputFn, - PerKeyCombineFn perKeyCombineFn, - TupleTag outputTag) { - checkUniqueness(outputTags, outputTag); - return new ComposedKeyedCombineFnWithContext<>( - ImmutableList.>builder() - .addAll(extractInputFns) - .add(extractInputFn) - .build(), - ImmutableList.>builder() - .addAll(keyedCombineFns) - .add(toFnWithContext(perKeyCombineFn)) - .build(), - ImmutableList.>builder() - .addAll(outputTags) - .add(outputTag) - .build()); - } - - /** - * Returns a {@link ComposedKeyedCombineFnWithContext} with an additional - * {@link GlobalCombineFn}. - */ - public ComposedKeyedCombineFnWithContext with( - SimpleFunction extractInputFn, - GlobalCombineFn perKeyCombineFn, - TupleTag outputTag) { - return with(extractInputFn, perKeyCombineFn.asKeyedFn(), outputTag); - } - - @Override - public Object[] createAccumulator(K key, Context c) { - Object[] accumsArray = new Object[combineFnCount]; - for (int i = 0; i < combineFnCount; ++i) { - accumsArray[i] = keyedCombineFns.get(i).createAccumulator(key, c); - } - return accumsArray; - } - - @Override - public Object[] addInput(K key, Object[] accumulator, DataT value, Context c) { - for (int i = 0; i < combineFnCount; ++i) { - Object input = extractInputFns.get(i).apply(value); - accumulator[i] = keyedCombineFns.get(i).addInput(key, accumulator[i], input, c); - } - return accumulator; - } - - @Override - public Object[] mergeAccumulators(K key, Iterable accumulators, Context c) { - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(key, c); - } else { - // Reuses the first accumulator, and overwrites its values. - // It is safe because {@code accum[i]} only depends on - // the i-th component of each accumulator. - Object[] accum = iter.next(); - for (int i = 0; i < combineFnCount; ++i) { - accum[i] = keyedCombineFns.get(i).mergeAccumulators( - key, new ProjectionIterable(accumulators, i), c); - } - return accum; - } - } - - @Override - public CoCombineResult extractOutput(K key, Object[] accumulator, Context c) { - Map, Object> valuesMap = Maps.newHashMap(); - for (int i = 0; i < combineFnCount; ++i) { - valuesMap.put( - outputTags.get(i), - keyedCombineFns.get(i).extractOutput(key, accumulator[i], c)); - } - return new CoCombineResult(valuesMap); - } - - @Override - public Object[] compact(K key, Object[] accumulator, Context c) { - for (int i = 0; i < combineFnCount; ++i) { - accumulator[i] = keyedCombineFns.get(i).compact(key, accumulator[i], c); - } - return accumulator; - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder keyCoder, Coder dataCoder) - throws CannotProvideCoderException { - List> coders = Lists.newArrayList(); - for (int i = 0; i < combineFnCount; ++i) { - Coder inputCoder = - registry.getDefaultOutputCoder(extractInputFns.get(i), dataCoder); - coders.add(keyedCombineFns.get(i).getAccumulatorCoder( - registry, keyCoder, inputCoder)); - } - return new ComposedAccumulatorCoder(coders); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - CombineFns.populateDisplayData(builder, keyedCombineFns); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - private static class ProjectionIterable implements Iterable { - private final Iterable iterable; - private final int column; - - private ProjectionIterable(Iterable iterable, int column) { - this.iterable = iterable; - this.column = column; - } - - @Override - public Iterator iterator() { - final Iterator iter = iterable.iterator(); - return new Iterator() { - @Override - public boolean hasNext() { - return iter.hasNext(); - } - - @Override - public Object next() { - return iter.next()[column]; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - } - - private static class ComposedAccumulatorCoder extends StandardCoder { - private List> coders; - private int codersCount; - - public ComposedAccumulatorCoder(List> coders) { - this.coders = ImmutableList.copyOf(coders); - this.codersCount = coders.size(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @JsonCreator - public static ComposedAccumulatorCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - return new ComposedAccumulatorCoder((List) components); - } - - @Override - public void encode(Object[] value, OutputStream outStream, Context context) - throws CoderException, IOException { - checkArgument(value.length == codersCount); - Context nestedContext = context.nested(); - for (int i = 0; i < codersCount; ++i) { - coders.get(i).encode(value[i], outStream, nestedContext); - } - } - - @Override - public Object[] decode(InputStream inStream, Context context) - throws CoderException, IOException { - Object[] ret = new Object[codersCount]; - Context nestedContext = context.nested(); - for (int i = 0; i < codersCount; ++i) { - ret[i] = coders.get(i).decode(inStream, nestedContext); - } - return ret; - } - - @Override - public List> getCoderArguments() { - return coders; - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - for (int i = 0; i < codersCount; ++i) { - coders.get(i).verifyDeterministic(); - } - } - } - - @SuppressWarnings("unchecked") - private static CombineFnWithContext - toFnWithContext(GlobalCombineFn globalCombineFn) { - if (globalCombineFn instanceof CombineFnWithContext) { - return (CombineFnWithContext) globalCombineFn; - } else { - final CombineFn combineFn = - (CombineFn) globalCombineFn; - return new CombineFnWithContext() { - @Override - public AccumT createAccumulator(Context c) { - return combineFn.createAccumulator(); - } - @Override - public AccumT addInput(AccumT accumulator, InputT input, Context c) { - return combineFn.addInput(accumulator, input); - } - @Override - public AccumT mergeAccumulators(Iterable accumulators, Context c) { - return combineFn.mergeAccumulators(accumulators); - } - @Override - public OutputT extractOutput(AccumT accumulator, Context c) { - return combineFn.extractOutput(accumulator); - } - @Override - public AccumT compact(AccumT accumulator, Context c) { - return combineFn.compact(accumulator); - } - @Override - public OutputT defaultValue() { - return combineFn.defaultValue(); - } - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException { - return combineFn.getAccumulatorCoder(registry, inputCoder); - } - @Override - public Coder getDefaultOutputCoder( - CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { - return combineFn.getDefaultOutputCoder(registry, inputCoder); - } - }; - } - } - - private static KeyedCombineFnWithContext - toFnWithContext(PerKeyCombineFn perKeyCombineFn) { - if (perKeyCombineFn instanceof KeyedCombineFnWithContext) { - @SuppressWarnings("unchecked") - KeyedCombineFnWithContext keyedCombineFnWithContext = - (KeyedCombineFnWithContext) perKeyCombineFn; - return keyedCombineFnWithContext; - } else { - @SuppressWarnings("unchecked") - final KeyedCombineFn keyedCombineFn = - (KeyedCombineFn) perKeyCombineFn; - return new KeyedCombineFnWithContext() { - @Override - public AccumT createAccumulator(K key, Context c) { - return keyedCombineFn.createAccumulator(key); - } - @Override - public AccumT addInput(K key, AccumT accumulator, InputT value, Context c) { - return keyedCombineFn.addInput(key, accumulator, value); - } - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators, Context c) { - return keyedCombineFn.mergeAccumulators(key, accumulators); - } - @Override - public OutputT extractOutput(K key, AccumT accumulator, Context c) { - return keyedCombineFn.extractOutput(key, accumulator); - } - @Override - public AccumT compact(K key, AccumT accumulator, Context c) { - return keyedCombineFn.compact(key, accumulator); - } - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return keyedCombineFn.getAccumulatorCoder(registry, keyCoder, inputCoder); - } - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return keyedCombineFn.getDefaultOutputCoder(registry, keyCoder, inputCoder); - } - }; - } - } - - private static void checkUniqueness( - List> registeredTags, TupleTag outputTag) { - checkArgument( - !registeredTags.contains(outputTag), - "Cannot compose with tuple tag %s because it is already present in the composition.", - outputTag); - } - - /** - * Populate display data for the {@code combineFns} that make up a composed combine transform. - * - *

              The same combineFn class may be used multiple times, in which case we must take special care - * to register display data with unique namespaces. - */ - private static void populateDisplayData( - DisplayData.Builder builder, List combineFns) { - - // NB: ArrayListMultimap necessary to maintain ordering of combineFns of the same type. - Multimap, HasDisplayData> combineFnMap = ArrayListMultimap.create(); - - for (int i = 0; i < combineFns.size(); i++) { - HasDisplayData combineFn = combineFns.get(i); - builder.add(DisplayData.item("combineFn" + (i + 1), combineFn.getClass()) - .withLabel("Combine Function")); - combineFnMap.put(combineFn.getClass(), combineFn); - } - - for (Map.Entry, Collection> combineFnEntries : - combineFnMap.asMap().entrySet()) { - - Collection classCombineFns = combineFnEntries.getValue(); - if (classCombineFns.size() == 1) { - // Only one combineFn of this type, include it directly. - builder.include(Iterables.getOnlyElement(classCombineFns)); - - } else { - // Multiple combineFns of same type, add a namespace suffix so display data is - // unique and ordered. - String baseNamespace = combineFnEntries.getKey().getName(); - for (int i = 0; i < combineFns.size(); i++) { - HasDisplayData combineFn = combineFns.get(i); - String namespace = String.format("%s#%d", baseNamespace, i + 1); - builder.include(combineFn, namespace); - } - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java deleted file mode 100644 index d7439b1fc5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/CombineWithContext.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -/** - * This class contains combine functions that have access to {@code PipelineOptions} and side inputs - * through {@code CombineWithContext.Context}. - * - *

              {@link CombineFnWithContext} and {@link KeyedCombineFnWithContext} are for users to extend. - */ -public class CombineWithContext { - - /** - * Information accessible to all methods in {@code CombineFnWithContext} - * and {@code KeyedCombineFnWithContext}. - */ - public abstract static class Context { - /** - * Returns the {@code PipelineOptions} specified with the - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} - * invoking this {@code KeyedCombineFn}. - */ - public abstract PipelineOptions getPipelineOptions(); - - /** - * Returns the value of the side input for the window corresponding to the - * window of the main input element. - */ - public abstract T sideInput(PCollectionView view); - } - - /** - * An internal interface for signaling that a {@code GloballyCombineFn} - * or a {@code PerKeyCombineFn} needs to access {@code CombineWithContext.Context}. - * - *

              For internal use only. - */ - public interface RequiresContextInternal {} - - /** - * A combine function that has access to {@code PipelineOptions} and side inputs through - * {@code CombineWithContext.Context}. - * - *

              See the equivalent {@link CombineFn} for details about combine functions. - */ - public abstract static class CombineFnWithContext - extends CombineFnBase.AbstractGlobalCombineFn - implements RequiresContextInternal { - /** - * Returns a new, mutable accumulator value, representing the accumulation of zero input values. - * - *

              It is equivalent to {@link CombineFn#createAccumulator}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public abstract AccumT createAccumulator(Context c); - - /** - * Adds the given input value to the given accumulator, returning the - * new accumulator value. - * - *

              It is equivalent to {@link CombineFn#addInput}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public abstract AccumT addInput(AccumT accumulator, InputT input, Context c); - - /** - * Returns an accumulator representing the accumulation of all the - * input values accumulated in the merging accumulators. - * - *

              It is equivalent to {@link CombineFn#mergeAccumulators}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public abstract AccumT mergeAccumulators(Iterable accumulators, Context c); - - /** - * Returns the output value that is the result of combining all - * the input values represented by the given accumulator. - * - *

              It is equivalent to {@link CombineFn#extractOutput}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public abstract OutputT extractOutput(AccumT accumulator, Context c); - - /** - * Returns an accumulator that represents the same logical value as the - * input accumulator, but may have a more compact representation. - * - *

              It is equivalent to {@link CombineFn#compact}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public AccumT compact(AccumT accumulator, Context c) { - return accumulator; - } - - @Override - public OutputT defaultValue() { - throw new UnsupportedOperationException( - "Override this function to provide the default value."); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public KeyedCombineFnWithContext asKeyedFn() { - // The key, an object, is never even looked at. - return new KeyedCombineFnWithContext() { - @Override - public AccumT createAccumulator(K key, Context c) { - return CombineFnWithContext.this.createAccumulator(c); - } - - @Override - public AccumT addInput(K key, AccumT accumulator, InputT input, Context c) { - return CombineFnWithContext.this.addInput(accumulator, input, c); - } - - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators, Context c) { - return CombineFnWithContext.this.mergeAccumulators(accumulators, c); - } - - @Override - public OutputT extractOutput(K key, AccumT accumulator, Context c) { - return CombineFnWithContext.this.extractOutput(accumulator, c); - } - - @Override - public AccumT compact(K key, AccumT accumulator, Context c) { - return CombineFnWithContext.this.compact(accumulator, c); - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return CombineFnWithContext.this.getAccumulatorCoder(registry, inputCoder); - } - - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return CombineFnWithContext.this.getDefaultOutputCoder(registry, inputCoder); - } - - @Override - public CombineFnWithContext forKey(K key, Coder keyCoder) { - return CombineFnWithContext.this; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - CombineFnWithContext.this.populateDisplayData(builder); - } - }; - } - } - - /** - * A keyed combine function that has access to {@code PipelineOptions} and side inputs through - * {@code CombineWithContext.Context}. - * - *

              See the equivalent {@link KeyedCombineFn} for details about keyed combine functions. - */ - public abstract static class KeyedCombineFnWithContext - extends CombineFnBase.AbstractPerKeyCombineFn - implements RequiresContextInternal { - /** - * Returns a new, mutable accumulator value representing the accumulation of zero input values. - * - *

              It is equivalent to {@link KeyedCombineFn#createAccumulator}, - * but it has additional access to {@code CombineWithContext.Context}. - */ - public abstract AccumT createAccumulator(K key, Context c); - - /** - * Adds the given input value to the given accumulator, returning the new accumulator value. - * - *

              It is equivalent to {@link KeyedCombineFn#addInput}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public abstract AccumT addInput(K key, AccumT accumulator, InputT value, Context c); - - /** - * Returns an accumulator representing the accumulation of all the - * input values accumulated in the merging accumulators. - * - *

              It is equivalent to {@link KeyedCombineFn#mergeAccumulators}, - * but it has additional access to {@code CombineWithContext.Context}.. - */ - public abstract AccumT mergeAccumulators(K key, Iterable accumulators, Context c); - - /** - * Returns the output value that is the result of combining all - * the input values represented by the given accumulator. - * - *

              It is equivalent to {@link KeyedCombineFn#extractOutput}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public abstract OutputT extractOutput(K key, AccumT accumulator, Context c); - - /** - * Returns an accumulator that represents the same logical value as the - * input accumulator, but may have a more compact representation. - * - *

              It is equivalent to {@link KeyedCombineFn#compact}, but it has additional access to - * {@code CombineWithContext.Context}. - */ - public AccumT compact(K key, AccumT accumulator, Context c) { - return accumulator; - } - - /** - * Applies this {@code KeyedCombineFnWithContext} to a key and a collection - * of input values to produce a combined output value. - */ - public OutputT apply(K key, Iterable inputs, Context c) { - AccumT accum = createAccumulator(key, c); - for (InputT input : inputs) { - accum = addInput(key, accum, input, c); - } - return extractOutput(key, accum, c); - } - - @Override - public CombineFnWithContext forKey( - final K key, final Coder keyCoder) { - return new CombineFnWithContext() { - @Override - public AccumT createAccumulator(Context c) { - return KeyedCombineFnWithContext.this.createAccumulator(key, c); - } - - @Override - public AccumT addInput(AccumT accumulator, InputT input, Context c) { - return KeyedCombineFnWithContext.this.addInput(key, accumulator, input, c); - } - - @Override - public AccumT mergeAccumulators(Iterable accumulators, Context c) { - return KeyedCombineFnWithContext.this.mergeAccumulators(key, accumulators, c); - } - - @Override - public OutputT extractOutput(AccumT accumulator, Context c) { - return KeyedCombineFnWithContext.this.extractOutput(key, accumulator, c); - } - - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException { - return KeyedCombineFnWithContext.this.getAccumulatorCoder(registry, keyCoder, inputCoder); - } - - @Override - public Coder getDefaultOutputCoder( - CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { - return KeyedCombineFnWithContext.this.getDefaultOutputCoder( - registry, keyCoder, inputCoder); - } - }; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java deleted file mode 100644 index ffa11d13a3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * {@code PTransorm}s to count the elements in a {@link PCollection}. - * - *

              {@link Count#perElement()} can be used to count the number of occurrences of each - * distinct element in the PCollection, {@link Count#perKey()} can be used to count the - * number of values per key, and {@link Count#globally()} can be used to count the total - * number of elements in a PCollection. - */ -public class Count { - private Count() { - // do not instantiate - } - - /** - * Returns a {@link Combine.Globally} {@link PTransform} that counts the number of elements in - * its input {@link PCollection}. - */ - public static Combine.Globally globally() { - return Combine.globally(new CountFn()).named("Count.Globally"); - } - - /** - * Returns a {@link Combine.PerKey} {@link PTransform} that counts the number of elements - * associated with each key of its input {@link PCollection}. - */ - public static Combine.PerKey perKey() { - return Combine.perKey(new CountFn()).named("Count.PerKey"); - } - - /** - * Returns a {@link PerElement Count.PerElement} {@link PTransform} that counts the number of - * occurrences of each element in its input {@link PCollection}. - * - *

              See {@link PerElement Count.PerElement} for more details. - */ - public static PerElement perElement() { - return new PerElement<>(); - } - - /** - * {@code Count.PerElement} takes a {@code PCollection} and returns a - * {@code PCollection>} representing a map from each distinct element of the input - * {@code PCollection} to the number of times that element occurs in the input. Each key in the - * output {@code PCollection} is unique. - * - *

              This transform compares two values of type {@code T} by first encoding each element using - * the input {@code PCollection}'s {@code Coder}, then comparing the encoded bytes. Because of - * this, the input coder must be deterministic. - * (See {@link com.google.cloud.dataflow.sdk.coders.Coder#verifyDeterministic()} for more detail). - * Performing the comparison in this manner admits efficient parallel evaluation. - * - *

              By default, the {@code Coder} of the keys of the output {@code PCollection} is the same as - * the {@code Coder} of the elements of the input {@code PCollection}. - * - *

              Example of use: - *

               {@code
              -   * PCollection words = ...;
              -   * PCollection> wordCounts =
              -   *     words.apply(Count.perElement());
              -   * } 
              - * - * @param the type of the elements of the input {@code PCollection}, and the type of the keys - * of the output {@code PCollection} - */ - public static class PerElement - extends PTransform, PCollection>> { - - public PerElement() { } - - @Override - public PCollection> apply(PCollection input) { - return - input - .apply(ParDo.named("Init").of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), (Void) null)); - } - })) - .apply(Count.perKey()); - } - } - - /** - * A {@link CombineFn} that counts elements. - */ - private static class CountFn extends CombineFn { - - @Override - public Long createAccumulator() { - return 0L; - } - - @Override - public Long addInput(Long accumulator, T input) { - return accumulator + 1; - } - - @Override - public Long mergeAccumulators(Iterable accumulators) { - long result = 0L; - for (Long accum : accumulators) { - result += accum; - } - return result; - } - - @Override - public Long extractOutput(Long accumulator) { - return accumulator; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Create.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Create.java deleted file mode 100644 index 0005403253..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Create.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TimestampedValue.TimestampedValueCoder; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.collect.Iterables; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * {@code Create} takes a collection of elements of type {@code T} - * known when the pipeline is constructed and returns a - * {@code PCollection} containing the elements. - * - *

              Example of use: - *

               {@code
              - * Pipeline p = ...;
              - *
              - * PCollection pc = p.apply(Create.of(3, 4, 5).withCoder(BigEndianIntegerCoder.of()));
              - *
              - * Map map = ...;
              - * PCollection> pt =
              - *     p.apply(Create.of(map)
              - *      .withCoder(KvCoder.of(StringUtf8Coder.of(),
              - *                            BigEndianIntegerCoder.of())));
              - * } 
              - * - *

              {@code Create} can automatically determine the {@code Coder} to use - * if all elements have the same run-time class, and a default coder is registered for that - * class. See {@link CoderRegistry} for details on how defaults are determined. - * - *

              If a coder can not be inferred, {@link Create.Values#withCoder} must be called - * explicitly to set the encoding of the resulting - * {@code PCollection}. - * - *

              A good use for {@code Create} is when a {@code PCollection} - * needs to be created without dependencies on files or other external - * entities. This is especially useful during testing. - * - *

              Caveat: {@code Create} only supports small in-memory datasets, - * particularly when submitting jobs to the Google Cloud Dataflow - * service. - * - * @param the type of the elements of the resulting {@code PCollection} - */ -public class Create { - /** - * Returns a new {@code Create.Values} transform that produces a - * {@link PCollection} containing elements of the provided - * {@code Iterable}. - * - *

              The argument should not be modified after this is called. - * - *

              The elements of the output {@link PCollection} will have a timestamp of negative infinity, - * see {@link Create#timestamped} for a way of creating a {@code PCollection} with timestamped - * elements. - * - *

              By default, {@code Create.Values} can automatically determine the {@code Coder} to use - * if all elements have the same non-parameterized run-time class, and a default coder is - * registered for that class. See {@link CoderRegistry} for details on how defaults are - * determined. - * Otherwise, use {@link Create.Values#withCoder} to set the coder explicitly. - */ - public static Values of(Iterable elems) { - return new Values<>(elems, Optional.>absent()); - } - - /** - * Returns a new {@code Create.Values} transform that produces a - * {@link PCollection} containing the specified elements. - * - *

              The elements will have a timestamp of negative infinity, see - * {@link Create#timestamped} for a way of creating a {@code PCollection} - * with timestamped elements. - * - *

              The arguments should not be modified after this is called. - * - *

              By default, {@code Create.Values} can automatically determine the {@code Coder} to use - * if all elements have the same non-parameterized run-time class, and a default coder is - * registered for that class. See {@link CoderRegistry} for details on how defaults are - * determined. - * Otherwise, use {@link Create.Values#withCoder} to set the coder explicitly. - */ - @SafeVarargs - public static Values of(T... elems) { - return of(Arrays.asList(elems)); - } - - /** - * Returns a new {@code Create.Values} transform that produces a - * {@link PCollection} of {@link KV}s corresponding to the keys and - * values of the specified {@code Map}. - * - *

              The elements will have a timestamp of negative infinity, see - * {@link Create#timestamped} for a way of creating a {@code PCollection} - * with timestamped elements. - * - *

              By default, {@code Create.Values} can automatically determine the {@code Coder} to use - * if all elements have the same non-parameterized run-time class, and a default coder is - * registered for that class. See {@link CoderRegistry} for details on how defaults are - * determined. - * Otherwise, use {@link Create.Values#withCoder} to set the coder explicitly. - */ - public static Values> of(Map elems) { - List> kvs = new ArrayList<>(elems.size()); - for (Map.Entry entry : elems.entrySet()) { - kvs.add(KV.of(entry.getKey(), entry.getValue())); - } - return of(kvs); - } - - /** - * Returns a new {@link Create.TimestampedValues} transform that produces a - * {@link PCollection} containing the elements of the provided {@code Iterable} - * with the specified timestamps. - * - *

              The argument should not be modified after this is called. - * - *

              By default, {@code Create.TimestampedValues} can automatically determine the {@code Coder} - * to use if all elements have the same non-parameterized run-time class, and a default coder is - * registered for that class. See {@link CoderRegistry} for details on how defaults are - * determined. - * Otherwise, use {@link Create.TimestampedValues#withCoder} to set the coder explicitly. - */ - public static TimestampedValues timestamped(Iterable> elems) { - return new TimestampedValues<>(elems, Optional.>absent()); - } - - /** - * Returns a new {@link Create.TimestampedValues} transform that produces a {@link PCollection} - * containing the specified elements with the specified timestamps. - * - *

              The arguments should not be modified after this is called. - */ - @SafeVarargs - public static TimestampedValues timestamped( - @SuppressWarnings("unchecked") TimestampedValue... elems) { - return timestamped(Arrays.asList(elems)); - } - - /** - * Returns a new root transform that produces a {@link PCollection} containing - * the specified elements with the specified timestamps. - * - *

              The arguments should not be modified after this is called. - * - *

              By default, {@code Create.TimestampedValues} can automatically determine the {@code Coder} - * to use if all elements have the same non-parameterized run-time class, and a default coder - * is registered for that class. See {@link CoderRegistry} for details on how defaults are - * determined. - * Otherwise, use {@link Create.TimestampedValues#withCoder} to set the coder explicitly. - - * @throws IllegalArgumentException if there are a different number of values - * and timestamps - */ - public static TimestampedValues timestamped( - Iterable values, Iterable timestamps) { - List> elems = new ArrayList<>(); - Iterator valueIter = values.iterator(); - Iterator timestampIter = timestamps.iterator(); - while (valueIter.hasNext() && timestampIter.hasNext()) { - elems.add(TimestampedValue.of(valueIter.next(), new Instant(timestampIter.next()))); - } - checkArgument( - !valueIter.hasNext() && !timestampIter.hasNext(), - "Expect sizes of values and timestamps are same."); - return timestamped(elems); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code PTransform} that creates a {@code PCollection} from a set of in-memory objects. - */ - public static class Values extends PTransform> { - /** - * Returns a {@link Create.Values} PTransform like this one that uses the given - * {@code Coder} to decode each of the objects into a - * value of type {@code T}. - * - *

              By default, {@code Create.Values} can automatically determine the {@code Coder} to use - * if all elements have the same non-parameterized run-time class, and a default coder is - * registered for that class. See {@link CoderRegistry} for details on how defaults are - * determined. - * - *

              Note that for {@link Create.Values} with no elements, the {@link VoidCoder} is used. - */ - public Values withCoder(Coder coder) { - return new Values<>(elems, Optional.of(coder)); - } - - public Iterable getElements() { - return elems; - } - - @Override - public PCollection apply(PInput input) { - try { - Coder coder = getDefaultOutputCoder(input); - return PCollection - .createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - IsBounded.BOUNDED) - .setCoder(coder); - } catch (CannotProvideCoderException e) { - throw new IllegalArgumentException("Unable to infer a coder and no Coder was specified. " - + "Please set a coder by invoking Create.withCoder() explicitly.", e); - } - } - - @Override - public Coder getDefaultOutputCoder(PInput input) throws CannotProvideCoderException { - if (coder.isPresent()) { - return coder.get(); - } - // First try to deduce a coder using the types of the elements. - Class elementClazz = Void.class; - for (T elem : elems) { - if (elem == null) { - continue; - } - Class clazz = elem.getClass(); - if (elementClazz.equals(Void.class)) { - elementClazz = clazz; - } else if (!elementClazz.equals(clazz)) { - // Elements are not the same type, require a user-specified coder. - throw new CannotProvideCoderException( - "Cannot provide coder for Create: The elements are not all of the same class."); - } - } - - if (elementClazz.getTypeParameters().length == 0) { - try { - @SuppressWarnings("unchecked") // elementClazz is a wildcard type - Coder coder = (Coder) input.getPipeline().getCoderRegistry() - .getDefaultCoder(TypeDescriptor.of(elementClazz)); - return coder; - } catch (CannotProvideCoderException exc) { - // let the next stage try - } - } - - // If that fails, try to deduce a coder using the elements themselves - Optional> coder = Optional.absent(); - for (T elem : elems) { - Coder c = input.getPipeline().getCoderRegistry().getDefaultCoder(elem); - if (!coder.isPresent()) { - coder = Optional.of(c); - } else if (!Objects.equals(c, coder.get())) { - throw new CannotProvideCoderException( - "Cannot provide coder for elements of " + Create.class.getSimpleName() + ":" - + " For their common class, no coder could be provided." - + " Based on their values, they do not all default to the same Coder."); - } - } - - if (!coder.isPresent()) { - throw new CannotProvideCoderException("Unable to infer a coder. Please register " - + "a coder for "); - } - return coder.get(); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** The elements of the resulting PCollection. */ - private final transient Iterable elems; - - /** The coder used to encode the values to and from a binary representation. */ - private final transient Optional> coder; - - /** - * Constructs a {@code Create.Values} transform that produces a - * {@link PCollection} containing the specified elements. - * - *

              The arguments should not be modified after this is called. - */ - private Values(Iterable elems, Optional> coder) { - this.elems = elems; - this.coder = coder; - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code PTransform} that creates a {@code PCollection} whose elements have - * associated timestamps. - */ - public static class TimestampedValues extends Values { - /** - * Returns a {@link Create.TimestampedValues} PTransform like this one that uses the given - * {@code Coder} to decode each of the objects into a - * value of type {@code T}. - * - *

              By default, {@code Create.TimestampedValues} can automatically determine the - * {@code Coder} to use if all elements have the same non-parameterized run-time class, - * and a default coder is registered for that class. See {@link CoderRegistry} for details - * on how defaults are determined. - * - *

              Note that for {@link Create.TimestampedValues with no elements}, the {@link VoidCoder} - * is used. - */ - @Override - public TimestampedValues withCoder(Coder coder) { - return new TimestampedValues<>(elems, Optional.>of(coder)); - } - - @Override - public PCollection apply(PInput input) { - try { - Coder coder = getDefaultOutputCoder(input); - PCollection> intermediate = Pipeline.applyTransform(input, - Create.of(elems).withCoder(TimestampedValueCoder.of(coder))); - - PCollection output = intermediate.apply(ParDo.of(new ConvertTimestamps())); - output.setCoder(coder); - return output; - } catch (CannotProvideCoderException e) { - throw new IllegalArgumentException("Unable to infer a coder and no Coder was specified. " - + "Please set a coder by invoking CreateTimestamped.withCoder() explicitly.", e); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** The timestamped elements of the resulting PCollection. */ - private final transient Iterable> elems; - - private TimestampedValues(Iterable> elems, - Optional> coder) { - super( - Iterables.transform(elems, new Function, T>() { - @Override - public T apply(TimestampedValue input) { - return input.getValue(); - } - }), coder); - this.elems = elems; - } - - private static class ConvertTimestamps extends DoFn, T> { - @Override - public void processElement(ProcessContext c) { - c.outputWithTimestamp(c.element().getValue(), c.element().getTimestamp()); - } - } - } - - ///////////////////////////////////////////////////////////////////////////// - - static { - registerDefaultTransformEvaluator(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private static void registerDefaultTransformEvaluator() { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Create.Values.class, - new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Create.Values transform, - DirectPipelineRunner.EvaluationContext context) { - evaluateHelper(transform, context); - } - }); - } - - private static void evaluateHelper( - Create.Values transform, - DirectPipelineRunner.EvaluationContext context) { - // Convert the Iterable of elems into a List of elems. - List listElems; - if (transform.elems instanceof Collection) { - Collection collectionElems = (Collection) transform.elems; - listElems = new ArrayList<>(collectionElems.size()); - } else { - listElems = new ArrayList<>(); - } - for (T elem : transform.elems) { - listElems.add( - context.ensureElementEncodable(context.getOutput(transform), elem)); - } - context.setPCollection(context.getOutput(transform), listElems); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java deleted file mode 100644 index c9dc9f433a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFn.java +++ /dev/null @@ -1,563 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowingInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.MoreObjects; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; - -/** - * The argument to {@link ParDo} providing the code to use to process - * elements of the input - * {@link com.google.cloud.dataflow.sdk.values.PCollection}. - * - *

              See {@link ParDo} for more explanation, examples of use, and - * discussion of constraints on {@code DoFn}s, including their - * serializability, lack of access to global shared mutable state, - * requirements for failure tolerance, and benefits of optimization. - * - *

              {@code DoFn}s can be tested in the context of a particular - * {@code Pipeline} by running that {@code Pipeline} on sample input - * and then checking its output. Unit testing of a {@code DoFn}, - * separately from any {@code ParDo} transform or {@code Pipeline}, - * can be done via the {@link DoFnTester} harness. - * - *

              {@link DoFnWithContext} (currently experimental) offers an alternative - * mechanism for accessing {@link ProcessContext#window()} without the need - * to implement {@link RequiresWindowAccess}. - * - *

              See also {@link #processElement} for details on implementing the transformation - * from {@code InputT} to {@code OutputT}. - * - * @param the type of the (main) input elements - * @param the type of the (main) output elements - */ -public abstract class DoFn implements Serializable, HasDisplayData { - - /** - * Information accessible to all methods in this {@code DoFn}. - * Used primarily to output elements. - */ - public abstract class Context { - - /** - * Returns the {@code PipelineOptions} specified with the - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} - * invoking this {@code DoFn}. The {@code PipelineOptions} will - * be the default running via {@link DoFnTester}. - */ - public abstract PipelineOptions getPipelineOptions(); - - /** - * Adds the given element to the main output {@code PCollection}. - * - *

              Once passed to {@code output} the element should be considered - * immutable and not be modified in any way. It may be cached or retained - * by the Dataflow runtime or later steps in the pipeline, or used in - * other unspecified ways. - * - *

              If invoked from {@link DoFn#processElement processElement}, the output - * element will have the same timestamp and be in the same windows - * as the input element passed to {@link DoFn#processElement processElement}. - * - *

              If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element. The output element - * will have a timestamp of negative infinity. - */ - public abstract void output(OutputT output); - - /** - * Adds the given element to the main output {@code PCollection}, - * with the given timestamp. - * - *

              Once passed to {@code outputWithTimestamp} the element should not be - * modified in any way. - * - *

              If invoked from {@link DoFn#processElement processElement}, the timestamp - * must not be older than the input element's timestamp minus - * {@link DoFn#getAllowedTimestampSkew getAllowedTimestampSkew}. The output element will - * be in the same windows as the input element. - * - *

              If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element except for the - * timestamp. - */ - public abstract void outputWithTimestamp(OutputT output, Instant timestamp); - - /** - * Adds the given element to the side output {@code PCollection} with the - * given tag. - * - *

              Once passed to {@code sideOutput} the element should not be modified - * in any way. - * - *

              The caller of {@code ParDo} uses {@link ParDo#withOutputTags withOutputTags} to - * specify the tags of side outputs that it consumes. Non-consumed side - * outputs, e.g., outputs for monitoring purposes only, don't necessarily - * need to be specified. - * - *

              The output element will have the same timestamp and be in the same - * windows as the input element passed to {@link DoFn#processElement processElement}. - * - *

              If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element. The output element - * will have a timestamp of negative infinity. - * - * @see ParDo#withOutputTags - */ - public abstract void sideOutput(TupleTag tag, T output); - - /** - * Adds the given element to the specified side output {@code PCollection}, - * with the given timestamp. - * - *

              Once passed to {@code sideOutputWithTimestamp} the element should not be - * modified in any way. - * - *

              If invoked from {@link DoFn#processElement processElement}, the timestamp - * must not be older than the input element's timestamp minus - * {@link DoFn#getAllowedTimestampSkew getAllowedTimestampSkew}. The output element will - * be in the same windows as the input element. - * - *

              If invoked from {@link #startBundle startBundle} or {@link #finishBundle finishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element except for the - * timestamp. - * - * @see ParDo#withOutputTags - */ - public abstract void sideOutputWithTimestamp( - TupleTag tag, T output, Instant timestamp); - - /** - * Creates an {@link Aggregator} in the {@link DoFn} context with the - * specified name and aggregation logic specified by {@link CombineFn}. - * - *

              For internal use only. - * - * @param name the name of the aggregator - * @param combiner the {@link CombineFn} to use in the aggregator - * @return an aggregator for the provided name and {@link CombineFn} in this - * context - */ - @Experimental(Kind.AGGREGATOR) - protected abstract Aggregator - createAggregatorInternal(String name, CombineFn combiner); - - /** - * Sets up {@link Aggregator}s created by the {@link DoFn} so they are - * usable within this context. - * - *

              This method should be called by runners before {@link DoFn#startBundle} - * is executed. - */ - @Experimental(Kind.AGGREGATOR) - protected final void setupDelegateAggregators() { - for (DelegatingAggregator aggregator : aggregators.values()) { - setupDelegateAggregator(aggregator); - } - - aggregatorsAreFinal = true; - } - - private void setupDelegateAggregator( - DelegatingAggregator aggregator) { - - Aggregator delegate = createAggregatorInternal( - aggregator.getName(), aggregator.getCombineFn()); - - aggregator.setDelegate(delegate); - } - } - - /** - * Information accessible when running {@link DoFn#processElement}. - */ - public abstract class ProcessContext extends Context { - - /** - * Returns the input element to be processed. - * - *

              The element should be considered immutable. The Dataflow runtime will not mutate the - * element, so it is safe to cache, etc. The element should not be mutated by any of the - * {@link DoFn} methods, because it may be cached elsewhere, retained by the Dataflow runtime, - * or used in other unspecified ways. - */ - public abstract InputT element(); - - /** - * Returns the value of the side input for the window corresponding to the - * window of the main input element. - * - *

              See - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn#getSideInputWindow} - * for how this corresponding window is determined. - * - * @throws IllegalArgumentException if this is not a side input - * @see ParDo#withSideInputs - */ - public abstract T sideInput(PCollectionView view); - - /** - * Returns the timestamp of the input element. - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} - * for more information. - */ - public abstract Instant timestamp(); - - /** - * Returns the window into which the input element has been assigned. - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} - * for more information. - * - * @throws UnsupportedOperationException if this {@link DoFn} does - * not implement {@link RequiresWindowAccess}. - */ - public abstract BoundedWindow window(); - - /** - * Returns information about the pane within this window into which the - * input element has been assigned. - * - *

              Generally all data is in a single, uninteresting pane unless custom - * triggering and/or late data has been explicitly requested. - * See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} - * for more information. - */ - public abstract PaneInfo pane(); - - /** - * Returns the process context to use for implementing windowing. - */ - @Experimental - public abstract WindowingInternals windowingInternals(); - } - - /** - * Returns the allowed timestamp skew duration, which is the maximum - * duration that timestamps can be shifted backward in - * {@link DoFn.Context#outputWithTimestamp}. - * - *

              The default value is {@code Duration.ZERO}, in which case - * timestamps can only be shifted forward to future. For infinite - * skew, return {@code Duration.millis(Long.MAX_VALUE)}. - * - *

              Note that producing an element whose timestamp is less than the - * current timestamp may result in late data, i.e. returning a non-zero - * value here does not impact watermark calculations used for firing - * windows. - * - * @deprecated does not interact well with the watermark. - */ - @Deprecated - public Duration getAllowedTimestampSkew() { - return Duration.ZERO; - } - - /** - * Interface for signaling that a {@link DoFn} needs to access the window the - * element is being processed in, via {@link DoFn.ProcessContext#window}. - */ - @Experimental - public interface RequiresWindowAccess {} - - public DoFn() { - this(new HashMap>()); - } - - DoFn(Map> aggregators) { - this.aggregators = aggregators; - } - - ///////////////////////////////////////////////////////////////////////////// - - private final Map> aggregators; - - /** - * Protects aggregators from being created after initialization. - */ - private boolean aggregatorsAreFinal; - - /** - * Prepares this {@code DoFn} instance for processing a batch of elements. - * - *

              By default, does nothing. - */ - public void startBundle(Context c) throws Exception { - } - - /** - * Processes one input element. - * - *

              The current element of the input {@code PCollection} is returned by - * {@link ProcessContext#element() c.element()}. It should be considered immutable. The Dataflow - * runtime will not mutate the element, so it is safe to cache, etc. The element should not be - * mutated by any of the {@link DoFn} methods, because it may be cached elsewhere, retained by the - * Dataflow runtime, or used in other unspecified ways. - * - *

              A value is added to the main output {@code PCollection} by {@link ProcessContext#output}. - * Once passed to {@code output} the element should be considered immutable and not be modified in - * any way. It may be cached elsewhere, retained by the Dataflow runtime, or used in other - * unspecified ways. - * - * @see ProcessContext - */ - public abstract void processElement(ProcessContext c) throws Exception; - - /** - * Finishes processing this batch of elements. - * - *

              By default, does nothing. - */ - public void finishBundle(Context c) throws Exception { - } - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(DisplayData.Builder builder) { - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Returns a {@link TypeDescriptor} capturing what is known statically - * about the input type of this {@code DoFn} instance's most-derived - * class. - * - *

              See {@link #getOutputTypeDescriptor} for more discussion. - */ - protected TypeDescriptor getInputTypeDescriptor() { - return new TypeDescriptor(getClass()) {}; - } - - /** - * Returns a {@link TypeDescriptor} capturing what is known statically - * about the output type of this {@code DoFn} instance's - * most-derived class. - * - *

              In the normal case of a concrete {@code DoFn} subclass with - * no generic type parameters of its own (including anonymous inner - * classes), this will be a complete non-generic type, which is good - * for choosing a default output {@code Coder} for the output - * {@code PCollection}. - */ - protected TypeDescriptor getOutputTypeDescriptor() { - return new TypeDescriptor(getClass()) {}; - } - - /** - * Returns an {@link Aggregator} with aggregation logic specified by the - * {@link CombineFn} argument. The name provided must be unique across - * {@link Aggregator}s created within the DoFn. Aggregators can only be created - * during pipeline construction. - * - * @param name the name of the aggregator - * @param combiner the {@link CombineFn} to use in the aggregator - * @return an aggregator for the provided name and combiner in the scope of - * this DoFn - * @throws NullPointerException if the name or combiner is null - * @throws IllegalArgumentException if the given name collides with another - * aggregator in this scope - * @throws IllegalStateException if called during pipeline processing. - */ - protected final Aggregator - createAggregator(String name, CombineFn combiner) { - checkNotNull(name, "name cannot be null"); - checkNotNull(combiner, "combiner cannot be null"); - checkArgument(!aggregators.containsKey(name), - "Cannot create aggregator with name %s." - + " An Aggregator with that name already exists within this scope.", - name); - - checkState(!aggregatorsAreFinal, "Cannot create an aggregator during DoFn processing." - + " Aggregators should be registered during pipeline construction."); - - DelegatingAggregator aggregator = - new DelegatingAggregator<>(name, combiner); - aggregators.put(name, aggregator); - return aggregator; - } - - /** - * Returns an {@link Aggregator} with the aggregation logic specified by the - * {@link SerializableFunction} argument. The name provided must be unique - * across {@link Aggregator}s created within the DoFn. Aggregators can only be - * created during pipeline construction. - * - * @param name the name of the aggregator - * @param combiner the {@link SerializableFunction} to use in the aggregator - * @return an aggregator for the provided name and combiner in the scope of - * this DoFn - * @throws NullPointerException if the name or combiner is null - * @throws IllegalArgumentException if the given name collides with another - * aggregator in this scope - * @throws IllegalStateException if called during pipeline processing. - */ - protected final Aggregator createAggregator(String name, - SerializableFunction, AggInputT> combiner) { - checkNotNull(combiner, "combiner cannot be null."); - return createAggregator(name, Combine.IterableCombineFn.of(combiner)); - } - - /** - * Returns the {@link Aggregator Aggregators} created by this {@code DoFn}. - */ - Collection> getAggregators() { - return Collections.>unmodifiableCollection(aggregators.values()); - } - - /** - * An {@link Aggregator} that delegates calls to addValue to another - * aggregator. - * - * @param the type of input element - * @param the type of output element - */ - static class DelegatingAggregator implements - Aggregator, Serializable { - private final UUID id; - - private final String name; - - private final CombineFn combineFn; - - private Aggregator delegate; - - public DelegatingAggregator(String name, - CombineFn combiner) { - this.id = UUID.randomUUID(); - this.name = checkNotNull(name, "name cannot be null"); - // Safe contravariant cast - @SuppressWarnings("unchecked") - CombineFn specificCombiner = - (CombineFn) checkNotNull(combiner, "combineFn cannot be null"); - this.combineFn = specificCombiner; - } - - @Override - public void addValue(AggInputT value) { - if (delegate == null) { - throw new IllegalStateException( - "addValue cannot be called on Aggregator outside of the execution of a DoFn."); - } else { - delegate.addValue(value); - } - } - - @Override - public String getName() { - return name; - } - - @Override - public CombineFn getCombineFn() { - return combineFn; - } - - /** - * Sets the current delegate of the Aggregator. - * - * @param delegate the delegate to set in this aggregator - */ - public void setDelegate(Aggregator delegate) { - this.delegate = delegate; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("name", name) - .add("combineFn", combineFn) - .toString(); - } - - @Override - public int hashCode() { - return Objects.hash(id, name, combineFn.getClass()); - } - - /** - * Indicates whether some other object is "equal to" this one. - * - *

              {@code DelegatingAggregator} instances are equal if they have the same name, their - * CombineFns are the same class, and they have identical IDs. - */ - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (o == null) { - return false; - } - if (o instanceof DelegatingAggregator) { - DelegatingAggregator that = (DelegatingAggregator) o; - return Objects.equals(this.id, that.id) - && Objects.equals(this.name, that.name) - && Objects.equals(this.combineFn.getClass(), that.combineFn.getClass()); - } - return false; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java deleted file mode 100644 index a5ab9be334..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflector.java +++ /dev/null @@ -1,672 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.ExtraContextFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.FinishBundle; -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.ProcessElement; -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.StartBundle; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowingInternals; -import com.google.cloud.dataflow.sdk.util.common.ReflectHelpers; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableMap; -import com.google.common.reflect.TypeParameter; -import com.google.common.reflect.TypeToken; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * Utility implementing the necessary reflection for working with {@link DoFnWithContext}s. - */ -public abstract class DoFnReflector { - - private interface ExtraContextInfo { - /** - * Create an instance of the given instance using the instance factory. - */ - Object createInstance( - DoFnWithContext.ExtraContextFactory factory); - - /** - * Create the type token for the given type, filling in the generics. - */ - TypeToken tokenFor(TypeToken in, TypeToken out); - } - - private static final Map, ExtraContextInfo> EXTRA_CONTEXTS = Collections.emptyMap(); - private static final Map, ExtraContextInfo> EXTRA_PROCESS_CONTEXTS = - ImmutableMap., ExtraContextInfo>builder() - .putAll(EXTRA_CONTEXTS) - .put(BoundedWindow.class, new ExtraContextInfo() { - @Override - public Object - createInstance(ExtraContextFactory factory) { - return factory.window(); - } - - @Override - public TypeToken - tokenFor(TypeToken in, TypeToken out) { - return TypeToken.of(BoundedWindow.class); - } - }) - .put(WindowingInternals.class, new ExtraContextInfo() { - @Override - public Object - createInstance(ExtraContextFactory factory) { - return factory.windowingInternals(); - } - - @Override - public TypeToken - tokenFor(TypeToken in, TypeToken out) { - return new TypeToken>() { - } - .where(new TypeParameter() {}, in) - .where(new TypeParameter() {}, out); - } - }) - .build(); - - /** - * @return true if the reflected {@link DoFnWithContext} uses a Single Window. - */ - public abstract boolean usesSingleWindow(); - - /** - * Invoke the reflected {@link ProcessElement} method on the given instance. - * - * @param fn an instance of the {@link DoFnWithContext} to invoke {@link ProcessElement} on. - * @param c the {@link com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.ProcessContext} - * to pass to {@link ProcessElement}. - */ - abstract void invokeProcessElement( - DoFnWithContext fn, - DoFnWithContext.ProcessContext c, - ExtraContextFactory extra); - - /** - * Invoke the reflected {@link StartBundle} method on the given instance. - * - * @param fn an instance of the {@link DoFnWithContext} to invoke {@link StartBundle} on. - * @param c the {@link com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.Context} - * to pass to {@link StartBundle}. - */ - void invokeStartBundle( - DoFnWithContext fn, - DoFnWithContext.Context c, - ExtraContextFactory extra) { - fn.prepareForProcessing(); - } - - /** - * Invoke the reflected {@link FinishBundle} method on the given instance. - * - * @param fn an instance of the {@link DoFnWithContext} to invoke {@link FinishBundle} on. - * @param c the {@link com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.Context} - * to pass to {@link FinishBundle}. - */ - abstract void invokeFinishBundle( - DoFnWithContext fn, - DoFnWithContext.Context c, - ExtraContextFactory extra); - - private static final Map, DoFnReflector> REFLECTOR_CACHE = - new LinkedHashMap, DoFnReflector>(); - - /** - * @return the {@link DoFnReflector} for the given {@link DoFnWithContext}. - */ - public static DoFnReflector of( - @SuppressWarnings("rawtypes") Class fn) { - DoFnReflector reflector = REFLECTOR_CACHE.get(fn); - if (reflector != null) { - return reflector; - } - - reflector = new GenericDoFnReflector(fn); - REFLECTOR_CACHE.put(fn, reflector); - return reflector; - } - - /** - * Create a {@link DoFn} that the {@link DoFnWithContext}. - */ - public DoFn toDoFn(DoFnWithContext fn) { - if (usesSingleWindow()) { - return new WindowDoFnAdapter(this, fn); - } else { - return new SimpleDoFnAdapter(this, fn); - } - } - - private static String formatType(TypeToken t) { - return ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(t.getType()); - } - - private static String format(Method m) { - return ReflectHelpers.CLASS_AND_METHOD_FORMATTER.apply(m); - } - - private static Collection describeSupportedTypes( - Map, ExtraContextInfo> extraProcessContexts, - final TypeToken in, final TypeToken out) { - return FluentIterable - .from(extraProcessContexts.values()) - .transform(new Function() { - @Override - @Nullable - public String apply(@Nullable ExtraContextInfo input) { - if (input == null) { - return null; - } else { - return formatType(input.tokenFor(in, out)); - } - } - }) - .toSortedSet(String.CASE_INSENSITIVE_ORDER); - } - - @VisibleForTesting - static ExtraContextInfo[] verifyProcessMethodArguments(Method m) { - return verifyMethodArguments(m, - EXTRA_PROCESS_CONTEXTS, - new TypeToken.ProcessContext>() { - }, - new TypeParameter() {}, - new TypeParameter() {}); - } - - @VisibleForTesting - static ExtraContextInfo[] verifyBundleMethodArguments(Method m) { - return verifyMethodArguments(m, - EXTRA_CONTEXTS, - new TypeToken.Context>() { - }, - new TypeParameter() {}, - new TypeParameter() {}); - } - - /** - * Verify the method arguments for a given {@link DoFnWithContext} method. - * - *

              The requirements for a method to be valid, are: - *

                - *
              1. The method has at least one argument. - *
              2. The first argument is of type firstContextArg. - *
              3. The remaining arguments have raw types that appear in {@code contexts} - *
              4. Any generics on the extra context arguments match what is expected. Eg., - * {@code WindowingInternals} either matches the - * {@code InputT} and {@code OutputT} parameters of the - * {@code DoFn.ProcessContext}, or it uses a wildcard, etc. - *
              - * - * @param m the method to verify - * @param contexts mapping from raw classes to the {@link ExtraContextInfo} used - * to create new instances. - * @param firstContextArg the expected type of the first context argument - * @param iParam TypeParameter representing the input type - * @param oParam TypeParameter representing the output type - */ - @VisibleForTesting static ExtraContextInfo[] verifyMethodArguments(Method m, - Map, ExtraContextInfo> contexts, - TypeToken firstContextArg, TypeParameter iParam, TypeParameter oParam) { - - if (!void.class.equals(m.getReturnType())) { - throw new IllegalStateException(String.format( - "%s must have a void return type", format(m))); - } - if (m.isVarArgs()) { - throw new IllegalStateException(String.format( - "%s must not have var args", format(m))); - } - - // The first parameter must be present, and must be the specified type - Type[] params = m.getGenericParameterTypes(); - TypeToken contextToken = null; - if (params.length > 0) { - contextToken = TypeToken.of(params[0]); - } - if (contextToken == null - || !contextToken.getRawType().equals(firstContextArg.getRawType())) { - throw new IllegalStateException(String.format( - "%s must take a %s as its first argument", - format(m), firstContextArg.getRawType().getSimpleName())); - } - ExtraContextInfo[] contextInfos = new ExtraContextInfo[params.length - 1]; - - // Fill in the generics in the allExtraContextArgs interface from the types in the - // Context or ProcessContext DoFn. - ParameterizedType pt = (ParameterizedType) contextToken.getType(); - // We actually want the owner, since ProcessContext and Context are owned by DoFnWithContext. - pt = (ParameterizedType) pt.getOwnerType(); - @SuppressWarnings("unchecked") - TypeToken iActual = (TypeToken) TypeToken.of(pt.getActualTypeArguments()[0]); - @SuppressWarnings("unchecked") - TypeToken oActual = (TypeToken) TypeToken.of(pt.getActualTypeArguments()[1]); - - // All of the remaining parameters must be a super-interface of allExtraContextArgs - // that is not listed in the EXCLUDED_INTERFACES set. - for (int i = 1; i < params.length; i++) { - TypeToken param = TypeToken.of(params[i]); - - ExtraContextInfo info = contexts.get(param.getRawType()); - if (info == null) { - throw new IllegalStateException(String.format( - "%s is not a valid context parameter for method %s. Should be one of %s", - formatType(param), format(m), - describeSupportedTypes(contexts, iActual, oActual))); - } - - // If we get here, the class matches, but maybe the generics don't: - TypeToken expected = info.tokenFor(iActual, oActual); - if (!expected.isSubtypeOf(param)) { - throw new IllegalStateException(String.format( - "Incompatible generics in context parameter %s for method %s. Should be %s", - formatType(param), format(m), formatType(info.tokenFor(iActual, oActual)))); - } - - // Register the (now validated) context info - contextInfos[i - 1] = info; - } - return contextInfos; - } - - /** - * Implementation of {@link DoFnReflector} for the arbitrary {@link DoFnWithContext}. - */ - private static class GenericDoFnReflector extends DoFnReflector { - - private Method startBundle; - private Method processElement; - private Method finishBundle; - private ExtraContextInfo[] processElementArgs; - private ExtraContextInfo[] startBundleArgs; - private ExtraContextInfo[] finishBundleArgs; - - private GenericDoFnReflector(Class fn) { - // Locate the annotated methods - this.processElement = findAnnotatedMethod(ProcessElement.class, fn, true); - this.startBundle = findAnnotatedMethod(StartBundle.class, fn, false); - this.finishBundle = findAnnotatedMethod(FinishBundle.class, fn, false); - - // Verify that their method arguments satisfy our conditions. - processElementArgs = verifyProcessMethodArguments(processElement); - if (startBundle != null) { - startBundleArgs = verifyBundleMethodArguments(startBundle); - } - if (finishBundle != null) { - finishBundleArgs = verifyBundleMethodArguments(finishBundle); - } - } - - private static Collection declaredMethodsWithAnnotation( - Class anno, - Class startClass, Class stopClass) { - Collection matches = new ArrayList<>(); - - Class clazz = startClass; - LinkedHashSet> interfaces = new LinkedHashSet<>(); - - // First, find all declared methods on the startClass and parents (up to stopClass) - while (clazz != null && !clazz.equals(stopClass)) { - for (Method method : clazz.getDeclaredMethods()) { - if (method.isAnnotationPresent(anno)) { - matches.add(method); - } - } - - Collections.addAll(interfaces, clazz.getInterfaces()); - - clazz = clazz.getSuperclass(); - } - - // Now, iterate over all the discovered interfaces - for (Method method : ReflectHelpers.getClosureOfMethodsOnInterfaces(interfaces)) { - if (method.isAnnotationPresent(anno)) { - matches.add(method); - } - } - return matches; - } - - private static Method findAnnotatedMethod( - Class anno, Class fnClazz, boolean required) { - Collection matches = declaredMethodsWithAnnotation( - anno, fnClazz, DoFnWithContext.class); - - if (matches.size() == 0) { - if (required == true) { - throw new IllegalStateException(String.format( - "No method annotated with @%s found in %s", - anno.getSimpleName(), fnClazz.getName())); - } else { - return null; - } - } - - // If we have at least one match, then either it should be the only match - // or it should be an extension of the other matches (which came from parent - // classes). - Method first = matches.iterator().next(); - for (Method other : matches) { - if (!first.getName().equals(other.getName()) - || !Arrays.equals(first.getParameterTypes(), other.getParameterTypes())) { - throw new IllegalStateException(String.format( - "Found multiple methods annotated with @%s. [%s] and [%s]", - anno.getSimpleName(), format(first), format(other))); - } - } - - // We need to be able to call it. We require it is public. - if ((first.getModifiers() & Modifier.PUBLIC) == 0) { - throw new IllegalStateException(format(first) + " must be public"); - } - - // And make sure its not static. - if ((first.getModifiers() & Modifier.STATIC) != 0) { - throw new IllegalStateException(format(first) + " must not be static"); - } - - first.setAccessible(true); - return first; - } - - @Override - public boolean usesSingleWindow() { - return usesContext(BoundedWindow.class); - } - - private boolean usesContext(Class context) { - for (Class clazz : processElement.getParameterTypes()) { - if (clazz.equals(context)) { - return true; - } - } - return false; - } - - @Override - void invokeProcessElement( - DoFnWithContext fn, - DoFnWithContext.ProcessContext c, - ExtraContextFactory extra) { - invoke(processElement, fn, c, extra, processElementArgs); - } - - @Override - void invokeStartBundle( - DoFnWithContext fn, - DoFnWithContext.Context c, - ExtraContextFactory extra) { - super.invokeStartBundle(fn, c, extra); - if (startBundle != null) { - invoke(startBundle, fn, c, extra, startBundleArgs); - } - } - - @Override - void invokeFinishBundle( - DoFnWithContext fn, - DoFnWithContext.Context c, - ExtraContextFactory extra) { - if (finishBundle != null) { - invoke(finishBundle, fn, c, extra, finishBundleArgs); - } - } - - private void invoke(Method m, - DoFnWithContext on, - DoFnWithContext.Context contextArg, - ExtraContextFactory extraArgFactory, - ExtraContextInfo[] extraArgs) { - - Class[] parameterTypes = m.getParameterTypes(); - Object[] args = new Object[parameterTypes.length]; - args[0] = contextArg; - for (int i = 1; i < args.length; i++) { - args[i] = extraArgs[i - 1].createInstance(extraArgFactory); - } - - try { - m.invoke(on, args); - } catch (InvocationTargetException e) { - // Exception in user code. - throw UserCodeException.wrap(e.getCause()); - } catch (IllegalAccessException | IllegalArgumentException e) { - // Exception in our code. - throw new RuntimeException(e); - } - } - } - - private static class ContextAdapter - extends DoFnWithContext.Context - implements DoFnWithContext.ExtraContextFactory { - - private DoFn.Context context; - - private ContextAdapter( - DoFnWithContext fn, DoFn.Context context) { - fn.super(); - this.context = context; - } - - @Override - public PipelineOptions getPipelineOptions() { - return context.getPipelineOptions(); - } - - @Override - public void output(OutputT output) { - context.output(output); - } - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - context.outputWithTimestamp(output, timestamp); - } - - @Override - public void sideOutput(TupleTag tag, T output) { - context.sideOutput(tag, output); - } - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - context.sideOutputWithTimestamp(tag, output, timestamp); - } - - @Override - public BoundedWindow window() { - // The DoFnWithContext doesn't allow us to ask for these outside ProcessElements, so this - // should be unreachable. - throw new UnsupportedOperationException("Can only get the window in ProcessElements"); - } - - @Override - public WindowingInternals windowingInternals() { - // The DoFnWithContext doesn't allow us to ask for these outside ProcessElements, so this - // should be unreachable. - throw new UnsupportedOperationException( - "Can only get the windowingInternals in ProcessElements"); - } - } - - private static class ProcessContextAdapter - extends DoFnWithContext.ProcessContext - implements DoFnWithContext.ExtraContextFactory { - - private DoFn.ProcessContext context; - - private ProcessContextAdapter( - DoFnWithContext fn, - DoFn.ProcessContext context) { - fn.super(); - this.context = context; - } - - @Override - public PipelineOptions getPipelineOptions() { - return context.getPipelineOptions(); - } - - @Override - public T sideInput(PCollectionView view) { - return context.sideInput(view); - } - - @Override - public void output(OutputT output) { - context.output(output); - } - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - context.outputWithTimestamp(output, timestamp); - } - - @Override - public void sideOutput(TupleTag tag, T output) { - context.sideOutput(tag, output); - } - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - context.sideOutputWithTimestamp(tag, output, timestamp); - } - - @Override - public InputT element() { - return context.element(); - } - - @Override - public Instant timestamp() { - return context.timestamp(); - } - - @Override - public PaneInfo pane() { - return context.pane(); - } - - @Override - public BoundedWindow window() { - return context.window(); - } - - @Override - public WindowingInternals windowingInternals() { - return context.windowingInternals(); - } - } - - public static Class getDoFnClass(DoFn fn) { - if (fn instanceof SimpleDoFnAdapter) { - return ((SimpleDoFnAdapter) fn).fn.getClass(); - } else { - return fn.getClass(); - } - } - - private static class SimpleDoFnAdapter extends DoFn { - - private transient DoFnReflector reflector; - private DoFnWithContext fn; - - private SimpleDoFnAdapter(DoFnReflector reflector, DoFnWithContext fn) { - super(fn.aggregators); - this.reflector = reflector; - this.fn = fn; - } - - @Override - public void startBundle(DoFn.Context c) throws Exception { - ContextAdapter adapter = new ContextAdapter<>(fn, c); - reflector.invokeStartBundle(fn, adapter, adapter); - } - - @Override - public void finishBundle(DoFn.Context c) throws Exception { - ContextAdapter adapter = new ContextAdapter<>(fn, c); - reflector.invokeFinishBundle(fn, adapter, adapter); - } - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - ProcessContextAdapter adapter = new ProcessContextAdapter<>(fn, c); - reflector.invokeProcessElement(fn, adapter, adapter); - } - - @Override - protected TypeDescriptor getInputTypeDescriptor() { - return fn.getInputTypeDescriptor(); - } - - @Override - protected TypeDescriptor getOutputTypeDescriptor() { - return fn.getOutputTypeDescriptor(); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.include(fn); - } - - private void readObject(java.io.ObjectInputStream in) - throws IOException, ClassNotFoundException { - in.defaultReadObject(); - reflector = DoFnReflector.of(fn.getClass()); - } - } - - private static class WindowDoFnAdapter - extends SimpleDoFnAdapter implements DoFn.RequiresWindowAccess { - - private WindowDoFnAdapter(DoFnReflector reflector, DoFnWithContext fn) { - super(reflector, fn); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java deleted file mode 100644 index d4bbcc5e3d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnTester.java +++ /dev/null @@ -1,528 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.PTuple; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * A harness for unit-testing a {@link DoFn}. - * - *

              For example: - * - *

               {@code
              - * DoFn fn = ...;
              - *
              - * DoFnTester fnTester = DoFnTester.of(fn);
              - *
              - * // Set arguments shared across all batches:
              - * fnTester.setSideInputs(...);      // If fn takes side inputs.
              - * fnTester.setSideOutputTags(...);  // If fn writes to side outputs.
              - *
              - * // Process a batch containing a single input element:
              - * Input testInput = ...;
              - * List testOutputs = fnTester.processBatch(testInput);
              - * Assert.assertThat(testOutputs, Matchers.hasItems(...));
              - *
              - * // Process a bigger batch:
              - * Assert.assertThat(fnTester.processBatch(i1, i2, ...), Matchers.hasItems(...));
              - * } 
              - * - * @param the type of the {@code DoFn}'s (main) input elements - * @param the type of the {@code DoFn}'s (main) output elements - */ -public class DoFnTester { - /** - * Returns a {@code DoFnTester} supporting unit-testing of the given - * {@link DoFn}. - */ - @SuppressWarnings("unchecked") - public static DoFnTester of(DoFn fn) { - return new DoFnTester(fn); - } - - /** - * Returns a {@code DoFnTester} supporting unit-testing of the given - * {@link DoFn}. - */ - @SuppressWarnings("unchecked") - public static DoFnTester - of(DoFnWithContext fn) { - return new DoFnTester(DoFnReflector.of(fn.getClass()).toDoFn(fn)); - } - - /** - * Registers the tuple of values of the side input {@link PCollectionView}s to - * pass to the {@link DoFn} under test. - * - *

              If needed, first creates a fresh instance of the {@link DoFn} - * under test. - * - *

              If this isn't called, {@code DoFnTester} assumes the - * {@link DoFn} takes no side inputs. - */ - public void setSideInputs(Map, Iterable>> sideInputs) { - this.sideInputs = sideInputs; - resetState(); - } - - /** - * Registers the values of a side input {@link PCollectionView} to - * pass to the {@link DoFn} under test. - * - *

              If needed, first creates a fresh instance of the {@code DoFn} - * under test. - * - *

              If this isn't called, {@code DoFnTester} assumes the - * {@code DoFn} takes no side inputs. - */ - public void setSideInput(PCollectionView sideInput, Iterable> value) { - sideInputs.put(sideInput, value); - } - - /** - * Registers the values for a side input {@link PCollectionView} to - * pass to the {@link DoFn} under test. All values are placed - * in the global window. - */ - public void setSideInputInGlobalWindow( - PCollectionView sideInput, - Iterable value) { - sideInputs.put( - sideInput, - Iterables.transform(value, new Function>() { - @Override - public WindowedValue apply(Object input) { - return WindowedValue.valueInGlobalWindow(input); - } - })); - } - - - /** - * Registers the list of {@code TupleTag}s that can be used by the - * {@code DoFn} under test to output to side output - * {@code PCollection}s. - * - *

              If needed, first creates a fresh instance of the DoFn under test. - * - *

              If this isn't called, {@code DoFnTester} assumes the - * {@code DoFn} doesn't emit to any side outputs. - */ - public void setSideOutputTags(TupleTagList sideOutputTags) { - this.sideOutputTags = sideOutputTags.getAll(); - resetState(); - } - - - /** - * Whether or not a {@link DoFnTester} should clone the {@link DoFn} under test. - */ - public enum CloningBehavior { - CLONE, - DO_NOT_CLONE; - } - - /** - * Instruct this {@link DoFnTester} whether or not to clone the {@link DoFn} under test. - */ - public void setCloningBehavior(CloningBehavior newValue) { - this.cloningBehavior = newValue; - } - - /** - * Indicates whether this {@link DoFnTester} will clone the {@link DoFn} under test. - */ - public CloningBehavior getCloningBehavior() { - return cloningBehavior; - } - - /** - * A convenience operation that first calls {@link #startBundle}, - * then calls {@link #processElement} on each of the input elements, then - * calls {@link #finishBundle}, then returns the result of - * {@link #takeOutputElements}. - */ - public List processBatch(Iterable inputElements) { - startBundle(); - for (InputT inputElement : inputElements) { - processElement(inputElement); - } - finishBundle(); - return takeOutputElements(); - } - - /** - * A convenience method for testing {@link DoFn DoFns} with bundles of elements. - * Logic proceeds as follows: - * - *

                - *
              1. Calls {@link #startBundle}.
              2. - *
              3. Calls {@link #processElement} on each of the arguments.
              4. - *
              5. Calls {@link #finishBundle}.
              6. - *
              7. Returns the result of {@link #takeOutputElements}.
              8. - *
              - */ - @SafeVarargs - public final List processBatch(InputT... inputElements) { - return processBatch(Arrays.asList(inputElements)); - } - - /** - * Calls {@link DoFn#startBundle} on the {@code DoFn} under test. - * - *

              If needed, first creates a fresh instance of the DoFn under test. - */ - public void startBundle() { - resetState(); - initializeState(); - fnRunner.startBundle(); - state = State.STARTED; - } - - /** - * Calls {@link DoFn#processElement} on the {@code DoFn} under test, in a - * context where {@link DoFn.ProcessContext#element} returns the - * given element. - * - *

              Will call {@link #startBundle} automatically, if it hasn't - * already been called. - * - * @throws IllegalStateException if the {@code DoFn} under test has already - * been finished - */ - public void processElement(InputT element) { - if (state == State.FINISHED) { - throw new IllegalStateException("finishBundle() has already been called"); - } - if (state == State.UNSTARTED) { - startBundle(); - } - fnRunner.processElement(WindowedValue.valueInGlobalWindow(element)); - } - - /** - * Calls {@link DoFn#finishBundle} of the {@code DoFn} under test. - * - *

              Will call {@link #startBundle} automatically, if it hasn't - * already been called. - * - * @throws IllegalStateException if the {@code DoFn} under test has already - * been finished - */ - public void finishBundle() { - if (state == State.FINISHED) { - throw new IllegalStateException("finishBundle() has already been called"); - } - if (state == State.UNSTARTED) { - startBundle(); - } - fnRunner.finishBundle(); - state = State.FINISHED; - } - - /** - * Returns the elements output so far to the main output. Does not - * clear them, so subsequent calls will continue to include these - * elements. - * - * @see #takeOutputElements - * @see #clearOutputElements - * - */ - public List peekOutputElements() { - // TODO: Should we return an unmodifiable list? - return Lists.transform( - peekOutputElementsWithTimestamp(), - new Function, OutputT>() { - @Override - @SuppressWarnings("unchecked") - public OutputT apply(OutputElementWithTimestamp input) { - return input.getValue(); - } - }); - } - - /** - * Returns the elements output so far to the main output with associated timestamps. Does not - * clear them, so subsequent calls will continue to include these. - * elements. - * - * @see #takeOutputElementsWithTimestamp - * @see #clearOutputElements - */ - @Experimental - public List> peekOutputElementsWithTimestamp() { - // TODO: Should we return an unmodifiable list? - return Lists.transform( - outputManager.getOutput(mainOutputTag), - new Function>() { - @Override - @SuppressWarnings("unchecked") - public OutputElementWithTimestamp apply(Object input) { - return new OutputElementWithTimestamp( - ((WindowedValue) input).getValue(), - ((WindowedValue) input).getTimestamp()); - } - }); - } - - /** - * Clears the record of the elements output so far to the main output. - * - * @see #peekOutputElements - */ - public void clearOutputElements() { - peekOutputElements().clear(); - } - - /** - * Returns the elements output so far to the main output. - * Clears the list so these elements don't appear in future calls. - * - * @see #peekOutputElements - */ - public List takeOutputElements() { - List resultElems = new ArrayList<>(peekOutputElements()); - clearOutputElements(); - return resultElems; - } - - /** - * Returns the elements output so far to the main output with associated timestamps. - * Clears the list so these elements don't appear in future calls. - * - * @see #peekOutputElementsWithTimestamp - * @see #takeOutputElements - * @see #clearOutputElements - */ - @Experimental - public List> takeOutputElementsWithTimestamp() { - List> resultElems = - new ArrayList<>(peekOutputElementsWithTimestamp()); - clearOutputElements(); - return resultElems; - } - - /** - * Returns the elements output so far to the side output with the - * given tag. Does not clear them, so subsequent calls will - * continue to include these elements. - * - * @see #takeSideOutputElements - * @see #clearSideOutputElements - */ - public List peekSideOutputElements(TupleTag tag) { - // TODO: Should we return an unmodifiable list? - return Lists.transform( - outputManager.getOutput(tag), - new Function, T>() { - @SuppressWarnings("unchecked") - @Override - public T apply(WindowedValue input) { - return input.getValue(); - }}); - } - - /** - * Clears the record of the elements output so far to the side - * output with the given tag. - * - * @see #peekSideOutputElements - */ - public void clearSideOutputElements(TupleTag tag) { - peekSideOutputElements(tag).clear(); - } - - /** - * Returns the elements output so far to the side output with the given tag. - * Clears the list so these elements don't appear in future calls. - * - * @see #peekSideOutputElements - */ - public List takeSideOutputElements(TupleTag tag) { - List resultElems = new ArrayList<>(peekSideOutputElements(tag)); - clearSideOutputElements(tag); - return resultElems; - } - - /** - * Returns the value of the provided {@link Aggregator}. - */ - public AggregateT getAggregatorValue(Aggregator agg) { - @SuppressWarnings("unchecked") - Counter counter = - (Counter) - counterSet.getExistingCounter("user-" + STEP_NAME + "-" + agg.getName()); - return counter.getAggregate(); - } - - /** - * Holder for an OutputElement along with its associated timestamp. - */ - @Experimental - public static class OutputElementWithTimestamp { - private final OutputT value; - private final Instant timestamp; - - OutputElementWithTimestamp(OutputT value, Instant timestamp) { - this.value = value; - this.timestamp = timestamp; - } - - OutputT getValue() { - return value; - } - - Instant getTimestamp() { - return timestamp; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof OutputElementWithTimestamp)) { - return false; - } - OutputElementWithTimestamp other = (OutputElementWithTimestamp) obj; - return Objects.equal(other.value, value) && Objects.equal(other.timestamp, timestamp); - } - - @Override - public int hashCode() { - return Objects.hashCode(value, timestamp); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** The possible states of processing a DoFn. */ - enum State { - UNSTARTED, - STARTED, - FINISHED - } - - /** The name of the step of a DoFnTester. */ - static final String STEP_NAME = "stepName"; - /** The name of the enclosing DoFn PTransform for a DoFnTester. */ - static final String TRANSFORM_NAME = "transformName"; - - final PipelineOptions options = PipelineOptionsFactory.create(); - - /** The original DoFn under test. */ - final DoFn origFn; - - /** The side input values to provide to the DoFn under test. */ - private Map, Iterable>> sideInputs = - new HashMap<>(); - - /** - * Whether to clone the original {@link DoFn} or just use it as-is. - * - *

              Worker-side {@link DoFn DoFns} may not be serializable, and are not required to be. - */ - private CloningBehavior cloningBehavior = CloningBehavior.CLONE; - - /** The output tags used by the DoFn under test. */ - TupleTag mainOutputTag = new TupleTag<>(); - List> sideOutputTags = new ArrayList<>(); - - /** The original DoFn under test, if started. */ - DoFn fn; - - /** The ListOutputManager to examine the outputs. */ - DoFnRunnerBase.ListOutputManager outputManager; - - /** The DoFnRunner if processing is in progress. */ - DoFnRunner fnRunner; - - /** Counters for user-defined Aggregators if processing is in progress. */ - CounterSet counterSet; - - /** The state of processing of the DoFn under test. */ - State state; - - DoFnTester(DoFn origFn) { - this.origFn = origFn; - resetState(); - } - - void resetState() { - fn = null; - outputManager = null; - fnRunner = null; - counterSet = null; - state = State.UNSTARTED; - } - - @SuppressWarnings("unchecked") - void initializeState() { - if (cloningBehavior.equals(CloningBehavior.DO_NOT_CLONE)) { - fn = origFn; - } else { - fn = (DoFn) - SerializableUtils.deserializeFromByteArray( - SerializableUtils.serializeToByteArray(origFn), - origFn.toString()); - } - - counterSet = new CounterSet(); - PTuple runnerSideInputs = PTuple.empty(); - for (Map.Entry, Iterable>> entry - : sideInputs.entrySet()) { - runnerSideInputs = runnerSideInputs.and(entry.getKey().getTagInternal(), entry.getValue()); - } - outputManager = new DoFnRunnerBase.ListOutputManager(); - fnRunner = DoFnRunners.createDefault( - options, - fn, - DirectSideInputReader.of(runnerSideInputs), - outputManager, - mainOutputTag, - sideOutputTags, - DirectModeExecutionContext.create().getOrCreateStepContext(STEP_NAME, TRANSFORM_NAME, null), - counterSet.getAddCounterMutator(), - WindowingStrategy.globalDefault()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java deleted file mode 100644 index 355a100518..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContext.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.DelegatingAggregator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowingInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.io.Serializable; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.HashMap; -import java.util.Map; - -/** - * The argument to {@link ParDo} providing the code to use to process - * elements of the input - * {@link com.google.cloud.dataflow.sdk.values.PCollection}. - * - *

              See {@link ParDo} for more explanation, examples of use, and - * discussion of constraints on {@code DoFnWithContext}s, including their - * serializability, lack of access to global shared mutable state, - * requirements for failure tolerance, and benefits of optimization. - * - *

              {@code DoFnWithContext}s can be tested in a particular - * {@code Pipeline} by running that {@code Pipeline} on sample input - * and then checking its output. Unit testing of a {@code DoFnWithContext}, - * separately from any {@code ParDo} transform or {@code Pipeline}, - * can be done via the {@link DoFnTester} harness. - * - *

              Implementations must define a method annotated with {@link ProcessElement} - * that satisfies the requirements described there. See the {@link ProcessElement} - * for details. - * - *

              This functionality is experimental and likely to change. - * - *

              Example usage: - * - *

               {@code
              - * PCollection lines = ... ;
              - * PCollection words =
              - *     lines.apply(ParDo.of(new DoFnWithContext() {
              - *         @ProcessElement
              - *         public void processElement(ProcessContext c, BoundedWindow window) {
              - *
              - *         }}));
              - * } 
              - * - * @param the type of the (main) input elements - * @param the type of the (main) output elements - */ -@Experimental -public abstract class DoFnWithContext implements Serializable, HasDisplayData { - - /** Information accessible to all methods in this {@code DoFnWithContext}. */ - public abstract class Context { - - /** - * Returns the {@code PipelineOptions} specified with the - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} - * invoking this {@code DoFnWithContext}. The {@code PipelineOptions} will - * be the default running via {@link DoFnTester}. - */ - public abstract PipelineOptions getPipelineOptions(); - - /** - * Adds the given element to the main output {@code PCollection}. - * - *

              Once passed to {@code output} the element should not be modified in - * any way. - * - *

              If invoked from {@link ProcessElement}, the output - * element will have the same timestamp and be in the same windows - * as the input element passed to the method annotated with - * {@code @ProcessElement}. - * - *

              If invoked from {@link StartBundle} or {@link FinishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element. The output element - * will have a timestamp of negative infinity. - */ - public abstract void output(OutputT output); - - /** - * Adds the given element to the main output {@code PCollection}, - * with the given timestamp. - * - *

              Once passed to {@code outputWithTimestamp} the element should not be - * modified in any way. - * - *

              If invoked from {@link ProcessElement}), the timestamp - * must not be older than the input element's timestamp minus - * {@link DoFn#getAllowedTimestampSkew}. The output element will - * be in the same windows as the input element. - * - *

              If invoked from {@link StartBundle} or {@link FinishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element except for the - * timestamp. - */ - public abstract void outputWithTimestamp(OutputT output, Instant timestamp); - - /** - * Adds the given element to the side output {@code PCollection} with the - * given tag. - * - *

              Once passed to {@code sideOutput} the element should not be modified - * in any way. - * - *

              The caller of {@code ParDo} uses {@link ParDo#withOutputTags} to - * specify the tags of side outputs that it consumes. Non-consumed side - * outputs, e.g., outputs for monitoring purposes only, don't necessarily - * need to be specified. - * - *

              The output element will have the same timestamp and be in the same - * windows as the input element passed to {@link ProcessElement}). - * - *

              If invoked from {@link StartBundle} or {@link FinishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element. The output element - * will have a timestamp of negative infinity. - * - * @see ParDo#withOutputTags - */ - public abstract void sideOutput(TupleTag tag, T output); - - /** - * Adds the given element to the specified side output {@code PCollection}, - * with the given timestamp. - * - *

              Once passed to {@code sideOutputWithTimestamp} the element should not be - * modified in any way. - * - *

              If invoked from {@link ProcessElement}), the timestamp - * must not be older than the input element's timestamp minus - * {@link DoFn#getAllowedTimestampSkew}. The output element will - * be in the same windows as the input element. - * - *

              If invoked from {@link StartBundle} or {@link FinishBundle}, - * this will attempt to use the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * of the input {@code PCollection} to determine what windows the element - * should be in, throwing an exception if the {@code WindowFn} attempts - * to access any information about the input element except for the - * timestamp. - * - * @see ParDo#withOutputTags - */ - public abstract void sideOutputWithTimestamp( - TupleTag tag, T output, Instant timestamp); - } - - /** - * Information accessible when running {@link DoFn#processElement}. - */ - public abstract class ProcessContext extends Context { - - /** - * Returns the input element to be processed. - * - *

              The element will not be changed -- it is safe to cache, etc. - * without copying. - */ - public abstract InputT element(); - - - /** - * Returns the value of the side input. - * - * @throws IllegalArgumentException if this is not a side input - * @see ParDo#withSideInputs - */ - public abstract T sideInput(PCollectionView view); - - /** - * Returns the timestamp of the input element. - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} - * for more information. - */ - public abstract Instant timestamp(); - - /** - * Returns information about the pane within this window into which the - * input element has been assigned. - * - *

              Generally all data is in a single, uninteresting pane unless custom - * triggering and/or late data has been explicitly requested. - * See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} - * for more information. - */ - public abstract PaneInfo pane(); - } - - /** - * Returns the allowed timestamp skew duration, which is the maximum - * duration that timestamps can be shifted backward in - * {@link DoFnWithContext.Context#outputWithTimestamp}. - * - *

              The default value is {@code Duration.ZERO}, in which case - * timestamps can only be shifted forward to future. For infinite - * skew, return {@code Duration.millis(Long.MAX_VALUE)}. - */ - public Duration getAllowedTimestampSkew() { - return Duration.ZERO; - } - - ///////////////////////////////////////////////////////////////////////////// - - Map> aggregators = new HashMap<>(); - - /** - * Protects aggregators from being created after initialization. - */ - private boolean aggregatorsAreFinal; - - /** - * Returns a {@link TypeDescriptor} capturing what is known statically - * about the input type of this {@code DoFnWithContext} instance's most-derived - * class. - * - *

              See {@link #getOutputTypeDescriptor} for more discussion. - */ - protected TypeDescriptor getInputTypeDescriptor() { - return new TypeDescriptor(getClass()) {}; - } - - /** - * Returns a {@link TypeDescriptor} capturing what is known statically - * about the output type of this {@code DoFnWithContext} instance's - * most-derived class. - * - *

              In the normal case of a concrete {@code DoFnWithContext} subclass with - * no generic type parameters of its own (including anonymous inner - * classes), this will be a complete non-generic type, which is good - * for choosing a default output {@code Coder} for the output - * {@code PCollection}. - */ - protected TypeDescriptor getOutputTypeDescriptor() { - return new TypeDescriptor(getClass()) {}; - } - - /** - * Interface for runner implementors to provide implementations of extra context information. - * - *

              The methods on this interface are called by {@link DoFnReflector} before invoking an - * annotated {@link StartBundle}, {@link ProcessElement} or {@link FinishBundle} method that - * has indicated it needs the given extra context. - * - *

              In the case of {@link ProcessElement} it is called once per invocation of - * {@link ProcessElement}. - */ - public interface ExtraContextFactory { - /** - * Construct the {@link BoundedWindow} to use within a {@link DoFnWithContext} that - * needs it. This is called if the {@link ProcessElement} method has a parameter of type - * {@link BoundedWindow}. - * - * @return {@link BoundedWindow} of the element currently being processed. - */ - BoundedWindow window(); - - /** - * Construct the {@link WindowingInternals} to use within a {@link DoFnWithContext} that - * needs it. This is called if the {@link ProcessElement} method has a parameter of type - * {@link WindowingInternals}. - */ - WindowingInternals windowingInternals(); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Annotation for the method to use to prepare an instance for processing a batch of elements. - * The method annotated with this must satisfy the following constraints: - *

                - *
              • It must have at least one argument. - *
              • Its first (and only) argument must be a {@link DoFnWithContext.Context}. - *
              - */ - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - public @interface StartBundle {} - - /** - * Annotation for the method to use for processing elements. A subclass of - * {@link DoFnWithContext} must have a method with this annotation satisfying - * the following constraints in order for it to be executable: - *
                - *
              • It must have at least one argument. - *
              • Its first argument must be a {@link DoFnWithContext.ProcessContext}. - *
              • Its remaining arguments must be {@link BoundedWindow}, or - * {@link WindowingInternals WindowingInternals<InputT, OutputT>}. - *
              - */ - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - public @interface ProcessElement {} - - /** - * Annotation for the method to use to prepare an instance for processing a batch of elements. - * The method annotated with this must satisfy the following constraints: - *
                - *
              • It must have at least one argument. - *
              • Its first (and only) argument must be a {@link DoFnWithContext.Context}. - *
              - */ - @Documented - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - public @interface FinishBundle {} - - /** - * Returns an {@link Aggregator} with aggregation logic specified by the - * {@link CombineFn} argument. The name provided must be unique across - * {@link Aggregator}s created within the DoFn. Aggregators can only be created - * during pipeline construction. - * - * @param name the name of the aggregator - * @param combiner the {@link CombineFn} to use in the aggregator - * @return an aggregator for the provided name and combiner in the scope of - * this DoFn - * @throws NullPointerException if the name or combiner is null - * @throws IllegalArgumentException if the given name collides with another - * aggregator in this scope - * @throws IllegalStateException if called during pipeline execution. - */ - public final Aggregator - createAggregator(String name, Combine.CombineFn combiner) { - checkNotNull(name, "name cannot be null"); - checkNotNull(combiner, "combiner cannot be null"); - checkArgument(!aggregators.containsKey(name), - "Cannot create aggregator with name %s." - + " An Aggregator with that name already exists within this scope.", - name); - checkState(!aggregatorsAreFinal, - "Cannot create an aggregator during pipeline execution." - + " Aggregators should be registered during pipeline construction."); - - DelegatingAggregator aggregator = - new DelegatingAggregator<>(name, combiner); - aggregators.put(name, aggregator); - return aggregator; - } - - /** - * Returns an {@link Aggregator} with the aggregation logic specified by the - * {@link SerializableFunction} argument. The name provided must be unique - * across {@link Aggregator}s created within the DoFn. Aggregators can only be - * created during pipeline construction. - * - * @param name the name of the aggregator - * @param combiner the {@link SerializableFunction} to use in the aggregator - * @return an aggregator for the provided name and combiner in the scope of - * this DoFn - * @throws NullPointerException if the name or combiner is null - * @throws IllegalArgumentException if the given name collides with another - * aggregator in this scope - * @throws IllegalStateException if called during pipeline execution. - */ - public final Aggregator createAggregator( - String name, SerializableFunction, AggInputT> combiner) { - checkNotNull(combiner, "combiner cannot be null."); - return createAggregator(name, Combine.IterableCombineFn.of(combiner)); - } - - /** - * Finalize the {@link DoFnWithContext} construction to prepare for processing. - * This method should be called by runners before any processing methods. - */ - void prepareForProcessing() { - aggregatorsAreFinal = true; - } - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(DisplayData.Builder builder) { - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java deleted file mode 100644 index cbd58cc071..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Filter.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * {@code PTransform}s for filtering from a {@code PCollection} the - * elements satisfying a predicate, or satisfying an inequality with - * a given value based on the elements' natural ordering. - * - * @param the type of the values in the input {@code PCollection}, - * and the type of the elements in the output {@code PCollection} - */ -public class Filter extends PTransform, PCollection> { - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a {@code PCollection} with - * elements that satisfy the given predicate. The predicate must be - * a {@code SerializableFunction}. - * - *

              Example of use: - *

               {@code
              -   * PCollection wordList = ...;
              -   * PCollection longWords =
              -   *     wordList.apply(Filter.byPredicate(new MatchIfWordLengthGT(6)));
              -   * } 
              - * - *

              See also {@link #lessThan}, {@link #lessThanEq}, - * {@link #greaterThan}, {@link #greaterThanEq}, which return elements - * satisfying various inequalities with the specified value based on - * the elements' natural ordering. - */ - public static > Filter - byPredicate(PredicateT predicate) { - return new Filter("Filter", predicate); - } - - /** - * @deprecated use {@link #byPredicate}, which returns a {@link Filter} transform instead of - * a {@link ParDo.Bound}. - */ - @Deprecated - public static > ParDo.Bound - by(final PredicateT filterPred) { - return ParDo.named("Filter").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - if (filterPred.apply(c.element()) == true) { - c.output(c.element()); - } - } - }); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@link PCollection} and returns a {@link PCollection} with - * elements that are less than a given value, based on the - * elements' natural ordering. Elements must be {@code Comparable}. - * - *

              Example of use: - *

               {@code
              -   * PCollection listOfNumbers = ...;
              -   * PCollection smallNumbers =
              -   *     listOfNumbers.apply(Filter.lessThan(10));
              -   * } 
              - * - *

              See also {@link #lessThanEq}, {@link #greaterThanEq}, - * and {@link #greaterThan}, which return elements satisfying various - * inequalities with the specified value based on the elements' - * natural ordering. - * - *

              See also {@link #byPredicate}, which returns elements - * that satisfy the given predicate. - */ - public static > ParDo.Bound lessThan(final T value) { - return ParDo.named("Filter.lessThan").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - if (c.element().compareTo(value) < 0) { - c.output(c.element()); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Filter.populateDisplayData(builder, String.format("x < %s", value)); - } - }); - } - - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a {@code PCollection} with - * elements that are greater than a given value, based on the - * elements' natural ordering. Elements must be {@code Comparable}. - * - *

              Example of use: - *

               {@code
              -   * PCollection listOfNumbers = ...;
              -   * PCollection largeNumbers =
              -   *     listOfNumbers.apply(Filter.greaterThan(1000));
              -   * } 
              - * - *

              See also {@link #greaterThanEq}, {@link #lessThan}, - * and {@link #lessThanEq}, which return elements satisfying various - * inequalities with the specified value based on the elements' - * natural ordering. - * - *

              See also {@link #byPredicate}, which returns elements - * that satisfy the given predicate. - */ - public static > ParDo.Bound greaterThan(final T value) { - return ParDo.named("Filter.greaterThan").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - if (c.element().compareTo(value) > 0) { - c.output(c.element()); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Filter.populateDisplayData(builder, String.format("x > %s", value)); - } - }); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a {@code PCollection} with - * elements that are less than or equal to a given value, based on the - * elements' natural ordering. Elements must be {@code Comparable}. - * - *

              Example of use: - *

               {@code
              -   * PCollection listOfNumbers = ...;
              -   * PCollection smallOrEqualNumbers =
              -   *     listOfNumbers.apply(Filter.lessThanEq(10));
              -   * } 
              - * - *

              See also {@link #lessThan}, {@link #greaterThanEq}, - * and {@link #greaterThan}, which return elements satisfying various - * inequalities with the specified value based on the elements' - * natural ordering. - * - *

              See also {@link #byPredicate}, which returns elements - * that satisfy the given predicate. - */ - public static > ParDo.Bound lessThanEq(final T value) { - return ParDo.named("Filter.lessThanEq").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - if (c.element().compareTo(value) <= 0) { - c.output(c.element()); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Filter.populateDisplayData(builder, String.format("x ≤ %s", value)); - } - }); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a {@code PCollection} with - * elements that are greater than or equal to a given value, based on - * the elements' natural ordering. Elements must be {@code Comparable}. - * - *

              Example of use: - *

               {@code
              -   * PCollection listOfNumbers = ...;
              -   * PCollection largeOrEqualNumbers =
              -   *     listOfNumbers.apply(Filter.greaterThanEq(1000));
              -   * } 
              - * - *

              See also {@link #greaterThan}, {@link #lessThan}, - * and {@link #lessThanEq}, which return elements satisfying various - * inequalities with the specified value based on the elements' - * natural ordering. - * - *

              See also {@link #byPredicate}, which returns elements - * that satisfy the given predicate. - */ - public static > ParDo.Bound greaterThanEq(final T value) { - return ParDo.named("Filter.greaterThanEq").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - if (c.element().compareTo(value) >= 0) { - c.output(c.element()); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - Filter.populateDisplayData(builder, String.format("x ≥ %s", value)); - } - }); - } - - /////////////////////////////////////////////////////////////////////////////// - - private SerializableFunction predicate; - - private Filter(SerializableFunction predicate) { - this.predicate = predicate; - } - - private Filter(String name, SerializableFunction predicate) { - super(name); - this.predicate = predicate; - } - - public Filter named(String name) { - return new Filter<>(name, predicate); - } - - @Override - public PCollection apply(PCollection input) { - PCollection output = input.apply(ParDo.named("Filter").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - if (predicate.apply(c.element()) == true) { - c.output(c.element()); - } - } - })); - return output; - } - - @Override - protected Coder getDefaultOutputCoder(PCollection input) { - return input.getCoder(); - } - - private static void populateDisplayData( - DisplayData.Builder builder, String predicateDescription) { - builder.add(DisplayData.item("predicate", predicateDescription) - .withLabel("Filter Predicate")); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java deleted file mode 100644 index fbaad5be6d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElements.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import java.lang.reflect.ParameterizedType; - -/** - * {@code PTransform}s for mapping a simple function that returns iterables over the elements of a - * {@link PCollection} and merging the results. - */ -public class FlatMapElements -extends PTransform, PCollection> { - /** - * For a {@code SerializableFunction>} {@code fn}, - * returns a {@link PTransform} that applies {@code fn} to every element of the input - * {@code PCollection} and outputs all of the elements to the output - * {@code PCollection}. - * - *

              Example of use in Java 8: - *

              {@code
              -   * PCollection words = lines.apply(
              -   *     FlatMapElements.via((String line) -> Arrays.asList(line.split(" ")))
              -   *         .withOutputType(new TypeDescriptor(){});
              -   * }
              - * - *

              In Java 7, the overload {@link #via(SimpleFunction)} is more concise as the output type - * descriptor need not be provided. - */ - public static MissingOutputTypeDescriptor - via(SerializableFunction> fn) { - return new MissingOutputTypeDescriptor<>(fn); - } - - /** - * For a {@code SimpleFunction>} {@code fn}, - * return a {@link PTransform} that applies {@code fn} to every element of the input - * {@code PCollection} and outputs all of the elements to the output - * {@code PCollection}. - * - *

              This overload is intended primarily for use in Java 7. In Java 8, the overload - * {@link #via(SerializableFunction)} supports use of lambda for greater concision. - * - *

              Example of use in Java 7: - *

              {@code
              -   * PCollection lines = ...;
              -   * PCollection words = lines.apply(FlatMapElements.via(
              -   *     new SimpleFunction>() {
              -   *       public Integer apply(String line) {
              -   *         return Arrays.asList(line.split(" "));
              -   *       }
              -   *     });
              -   * }
              - * - *

              To use a Java 8 lambda, see {@link #via(SerializableFunction)}. - */ - public static FlatMapElements - via(SimpleFunction> fn) { - - @SuppressWarnings({"rawtypes", "unchecked"}) // safe by static typing - TypeDescriptor> iterableType = (TypeDescriptor) fn.getOutputTypeDescriptor(); - - @SuppressWarnings("unchecked") // safe by correctness of getIterableElementType - TypeDescriptor outputType = - (TypeDescriptor) getIterableElementType(iterableType); - - return new FlatMapElements<>(fn, outputType); - } - - /** - * An intermediate builder for a {@link FlatMapElements} transform. To complete the transform, - * provide an output type descriptor to {@link MissingOutputTypeDescriptor#withOutputType}. See - * {@link #via(SerializableFunction)} for a full example of use. - */ - public static final class MissingOutputTypeDescriptor { - - private final SerializableFunction> fn; - - private MissingOutputTypeDescriptor( - SerializableFunction> fn) { - this.fn = fn; - } - - public FlatMapElements withOutputType(TypeDescriptor outputType) { - return new FlatMapElements<>(fn, outputType); - } - } - - private static TypeDescriptor getIterableElementType( - TypeDescriptor> iterableTypeDescriptor) { - - // If a rawtype was used, the type token may be for Object, not a subtype of Iterable. - // In this case, we rely on static typing of the function elsewhere to ensure it is - // at least some kind of iterable, and grossly overapproximate the element type to be Object. - if (!iterableTypeDescriptor.isSubtypeOf(new TypeDescriptor>() {})) { - return new TypeDescriptor() {}; - } - - // Otherwise we can do the proper thing and get the actual type parameter. - ParameterizedType iterableType = - (ParameterizedType) iterableTypeDescriptor.getSupertype(Iterable.class).getType(); - return TypeDescriptor.of(iterableType.getActualTypeArguments()[0]); - } - - ////////////////////////////////////////////////////////////////////////////////////////////////// - - private final SerializableFunction> fn; - private final transient TypeDescriptor outputType; - - private FlatMapElements( - SerializableFunction> fn, - TypeDescriptor outputType) { - this.fn = fn; - this.outputType = outputType; - } - - @Override - public PCollection apply(PCollection input) { - return input.apply(ParDo.named("Map").of(new DoFn() { - private static final long serialVersionUID = 0L; - @Override - public void processElement(ProcessContext c) { - for (OutputT element : fn.apply(c.element())) { - c.output(element); - } - } - })).setTypeDescriptorInternal(outputType); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Flatten.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Flatten.java deleted file mode 100644 index de6add0ea3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Flatten.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableLikeCoder; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@code Flatten} takes multiple {@code PCollection}s bundled - * into a {@code PCollectionList} and returns a single - * {@code PCollection} containing all the elements in all the input - * {@code PCollection}s. The name "Flatten" suggests taking a list of - * lists and flattening them into a single list. - * - *

              Example of use: - *

               {@code
              - * PCollection pc1 = ...;
              - * PCollection pc2 = ...;
              - * PCollection pc3 = ...;
              - * PCollectionList pcs = PCollectionList.of(pc1).and(pc2).and(pc3);
              - * PCollection merged = pcs.apply(Flatten.pCollections());
              - * } 
              - * - *

              By default, the {@code Coder} of the output {@code PCollection} - * is the same as the {@code Coder} of the first {@code PCollection} - * in the input {@code PCollectionList} (if the - * {@code PCollectionList} is non-empty). - * - */ -public class Flatten { - - /** - * Returns a {@link PTransform} that flattens a {@link PCollectionList} - * into a {@link PCollection} containing all the elements of all - * the {@link PCollection}s in its input. - * - *

              All inputs must have equal {@link WindowFn}s. - * The output elements of {@code Flatten} are in the same windows and - * have the same timestamps as their corresponding input elements. The output - * {@code PCollection} will have the same - * {@link WindowFn} as all of the inputs. - * - * @param the type of the elements in the input and output - * {@code PCollection}s. - */ - public static FlattenPCollectionList pCollections() { - return new FlattenPCollectionList<>(); - } - - /** - * Returns a {@code PTransform} that takes a {@code PCollection>} - * and returns a {@code PCollection} containing all the elements from - * all the {@code Iterable}s. - * - *

              Example of use: - *

               {@code
              -   * PCollection> pcOfIterables = ...;
              -   * PCollection pc = pcOfIterables.apply(Flatten.iterables());
              -   * } 
              - * - *

              By default, the output {@code PCollection} encodes its elements - * using the same {@code Coder} that the input uses for - * the elements in its {@code Iterable}. - * - * @param the type of the elements of the input {@code Iterable} and - * the output {@code PCollection} - */ - public static FlattenIterables iterables() { - return new FlattenIterables<>(); - } - - /** - * A {@link PTransform} that flattens a {@link PCollectionList} - * into a {@link PCollection} containing all the elements of all - * the {@link PCollection}s in its input. - * Implements {@link #pCollections}. - * - * @param the type of the elements in the input and output - * {@code PCollection}s. - */ - public static class FlattenPCollectionList - extends PTransform, PCollection> { - - private FlattenPCollectionList() { } - - @Override - public PCollection apply(PCollectionList inputs) { - WindowingStrategy windowingStrategy; - IsBounded isBounded = IsBounded.BOUNDED; - if (!inputs.getAll().isEmpty()) { - windowingStrategy = inputs.get(0).getWindowingStrategy(); - for (PCollection input : inputs.getAll()) { - WindowingStrategy other = input.getWindowingStrategy(); - if (!windowingStrategy.getWindowFn().isCompatible(other.getWindowFn())) { - throw new IllegalStateException( - "Inputs to Flatten had incompatible window windowFns: " - + windowingStrategy.getWindowFn() + ", " + other.getWindowFn()); - } - - if (!windowingStrategy.getTrigger().getSpec() - .isCompatible(other.getTrigger().getSpec())) { - throw new IllegalStateException( - "Inputs to Flatten had incompatible triggers: " - + windowingStrategy.getTrigger() + ", " + other.getTrigger()); - } - isBounded = isBounded.and(input.isBounded()); - } - } else { - windowingStrategy = WindowingStrategy.globalDefault(); - } - - return PCollection.createPrimitiveOutputInternal( - inputs.getPipeline(), - windowingStrategy, - isBounded); - } - - @Override - protected Coder getDefaultOutputCoder(PCollectionList input) - throws CannotProvideCoderException { - - // Take coder from first collection - for (PCollection pCollection : input.getAll()) { - return pCollection.getCoder(); - } - - // No inputs - throw new CannotProvideCoderException( - this.getClass().getSimpleName() + " cannot provide a Coder for" - + " empty " + PCollectionList.class.getSimpleName()); - } - } - - /** - * {@code FlattenIterables} takes a {@code PCollection>} and returns a - * {@code PCollection} that contains all the elements from each iterable. - * Implements {@link #iterables}. - * - * @param the type of the elements of the input {@code Iterable}s and - * the output {@code PCollection} - */ - public static class FlattenIterables - extends PTransform>, PCollection> { - - @Override - public PCollection apply(PCollection> in) { - Coder> inCoder = in.getCoder(); - if (!(inCoder instanceof IterableLikeCoder)) { - throw new IllegalArgumentException( - "expecting the input Coder to be an IterableLikeCoder"); - } - @SuppressWarnings("unchecked") - Coder elemCoder = ((IterableLikeCoder) inCoder).getElemCoder(); - - return in.apply(ParDo.named("FlattenIterables").of( - new DoFn, T>() { - @Override - public void processElement(ProcessContext c) { - for (T i : c.element()) { - c.output(i); - } - } - })) - .setCoder(elemCoder); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - FlattenPCollectionList.class, - new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - FlattenPCollectionList transform, - DirectPipelineRunner.EvaluationContext context) { - evaluateHelper(transform, context); - } - }); - } - - private static void evaluateHelper( - FlattenPCollectionList transform, - DirectPipelineRunner.EvaluationContext context) { - List> outputElems = new ArrayList<>(); - PCollectionList inputs = context.getInput(transform); - - for (PCollection input : inputs.getAll()) { - outputElems.addAll(context.getPCollectionValuesWithMetadata(input)); - } - - context.setPCollectionValuesWithMetadata(context.getOutput(transform), outputElems); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java deleted file mode 100644 index 2168e59653..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/GroupByKey.java +++ /dev/null @@ -1,585 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.ValueWithMetadata; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.InvalidWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsViaOutputBufferDoFn; -import com.google.cloud.dataflow.sdk.util.ReifyTimestampAndWindowsDoFn; -import com.google.cloud.dataflow.sdk.util.SystemReduceFn; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.WindowedValue.WindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * {@code GroupByKey} takes a {@code PCollection>}, - * groups the values by key and windows, and returns a - * {@code PCollection>>} representing a map from - * each distinct key and window of the input {@code PCollection} to an - * {@code Iterable} over all the values associated with that key in - * the input per window. Absent repeatedly-firing - * {@link Window#triggering triggering}, each key in the output - * {@code PCollection} is unique within each window. - * - *

              {@code GroupByKey} is analogous to converting a multi-map into - * a uni-map, and related to {@code GROUP BY} in SQL. It corresponds - * to the "shuffle" step between the Mapper and the Reducer in the - * MapReduce framework. - * - *

              Two keys of type {@code K} are compared for equality - * not by regular Java {@link Object#equals}, but instead by - * first encoding each of the keys using the {@code Coder} of the - * keys of the input {@code PCollection}, and then comparing the - * encoded bytes. This admits efficient parallel evaluation. Note that - * this requires that the {@code Coder} of the keys be deterministic (see - * {@link Coder#verifyDeterministic()}). If the key {@code Coder} is not - * deterministic, an exception is thrown at pipeline construction time. - * - *

              By default, the {@code Coder} of the keys of the output - * {@code PCollection} is the same as that of the keys of the input, - * and the {@code Coder} of the elements of the {@code Iterable} - * values of the output {@code PCollection} is the same as the - * {@code Coder} of the values of the input. - * - *

              Example of use: - *

               {@code
              - * PCollection> urlDocPairs = ...;
              - * PCollection>> urlToDocs =
              - *     urlDocPairs.apply(GroupByKey.create());
              - * PCollection results =
              - *     urlToDocs.apply(ParDo.of(new DoFn>, R>() {
              - *       public void processElement(ProcessContext c) {
              - *         String url = c.element().getKey();
              - *         Iterable docsWithThatUrl = c.element().getValue();
              - *         ... process all docs having that url ...
              - *       }}));
              - * } 
              - * - *

              {@code GroupByKey} is a key primitive in data-parallel - * processing, since it is the main way to efficiently bring - * associated data together into one location. It is also a key - * determiner of the performance of a data-parallel pipeline. - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey} - * for a way to group multiple input PCollections by a common key at once. - * - *

              See {@link Combine.PerKey} for a common pattern of - * {@code GroupByKey} followed by {@link Combine.GroupedValues}. - * - *

              When grouping, windows that can be merged according to the {@link WindowFn} - * of the input {@code PCollection} will be merged together, and a window pane - * corresponding to the new, merged window will be created. The items in this pane - * will be emitted when a trigger fires. By default this will be when the input - * sources estimate there will be no more data for the window. See - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark} - * for details on the estimation. - * - *

              The timestamp for each emitted pane is determined by the - * {@link Window.Bound#withOutputTimeFn windowing operation}. - * The output {@code PCollection} will have the same {@link WindowFn} - * as the input. - * - *

              If the input {@code PCollection} contains late data (see - * {@link com.google.cloud.dataflow.sdk.io.PubsubIO.Read.Bound#timestampLabel} - * for an example of how this can occur) or the - * {@link Window#triggering requested TriggerFn} can fire before - * the watermark, then there may be multiple elements - * output by a {@code GroupByKey} that correspond to the same key and window. - * - *

              If the {@link WindowFn} of the input requires merging, it is not - * valid to apply another {@code GroupByKey} without first applying a new - * {@link WindowFn} or applying {@link Window#remerge()}. - * - * @param the type of the keys of the input and output - * {@code PCollection}s - * @param the type of the values of the input {@code PCollection} - * and the elements of the {@code Iterable}s in the output - * {@code PCollection} - */ -public class GroupByKey - extends PTransform>, - PCollection>>> { - - private final boolean fewKeys; - - private GroupByKey(boolean fewKeys) { - this.fewKeys = fewKeys; - } - - /** - * Returns a {@code GroupByKey} {@code PTransform}. - * - * @param the type of the keys of the input and output - * {@code PCollection}s - * @param the type of the values of the input {@code PCollection} - * and the elements of the {@code Iterable}s in the output - * {@code PCollection} - */ - public static GroupByKey create() { - return new GroupByKey<>(false); - } - - /** - * Returns a {@code GroupByKey} {@code PTransform}. - * - * @param the type of the keys of the input and output - * {@code PCollection}s - * @param the type of the values of the input {@code PCollection} - * and the elements of the {@code Iterable}s in the output - * {@code PCollection} - * @param fewKeys whether it groups just few keys. - */ - static GroupByKey create(boolean fewKeys) { - return new GroupByKey<>(fewKeys); - } - - /** - * Returns whether it groups just few keys. - */ - public boolean fewKeys() { - return fewKeys; - } - - ///////////////////////////////////////////////////////////////////////////// - - public static void applicableTo(PCollection input) { - WindowingStrategy windowingStrategy = input.getWindowingStrategy(); - // Verify that the input PCollection is bounded, or that there is windowing/triggering being - // used. Without this, the watermark (at end of global window) will never be reached. - if (windowingStrategy.getWindowFn() instanceof GlobalWindows - && windowingStrategy.getTrigger().getSpec() instanceof DefaultTrigger - && input.isBounded() != IsBounded.BOUNDED) { - throw new IllegalStateException("GroupByKey cannot be applied to non-bounded PCollection in " - + "the GlobalWindow without a trigger. Use a Window.into or Window.triggering transform " - + "prior to GroupByKey."); - } - - // Validate the window merge function. - if (windowingStrategy.getWindowFn() instanceof InvalidWindows) { - String cause = ((InvalidWindows) windowingStrategy.getWindowFn()).getCause(); - throw new IllegalStateException( - "GroupByKey must have a valid Window merge function. " - + "Invalid because: " + cause); - } - } - - @Override - public void validate(PCollection> input) { - applicableTo(input); - - // Verify that the input Coder> is a KvCoder, and that - // the key coder is deterministic. - Coder keyCoder = getKeyCoder(input.getCoder()); - try { - keyCoder.verifyDeterministic(); - } catch (NonDeterministicException e) { - throw new IllegalStateException( - "the keyCoder of a GroupByKey must be deterministic", e); - } - } - - public WindowingStrategy updateWindowingStrategy(WindowingStrategy inputStrategy) { - WindowFn inputWindowFn = inputStrategy.getWindowFn(); - if (!inputWindowFn.isNonMerging()) { - // Prevent merging windows again, without explicit user - // involvement, e.g., by Window.into() or Window.remerge(). - inputWindowFn = new InvalidWindows<>( - "WindowFn has already been consumed by previous GroupByKey", inputWindowFn); - } - - // We also switch to the continuation trigger associated with the current trigger. - return inputStrategy - .withWindowFn(inputWindowFn) - .withTrigger(inputStrategy.getTrigger().getSpec().getContinuationTrigger()); - } - - @Override - public PCollection>> apply(PCollection> input) { - // This operation groups by the combination of key and window, - // merging windows as needed, using the windows assigned to the - // key/value input elements and the window merge operation of the - // window function associated with the input PCollection. - WindowingStrategy windowingStrategy = input.getWindowingStrategy(); - - // By default, implement GroupByKey[AndWindow] via a series of lower-level - // operations. - return input - // Make each input element's timestamp and assigned windows - // explicit, in the value part. - .apply(new ReifyTimestampsAndWindows()) - - // Group by just the key. - // Combiner lifting will not happen regardless of the disallowCombinerLifting value. - // There will be no combiners right after the GroupByKeyOnly because of the two ParDos - // introduced in here. - .apply(new GroupByKeyOnly>()) - - // Sort each key's values by timestamp. GroupAlsoByWindow requires - // its input to be sorted by timestamp. - .apply(new SortValuesByTimestamp()) - - // Group each key's values by window, merging windows as needed. - .apply(new GroupAlsoByWindow(windowingStrategy)) - - // And update the windowing strategy as appropriate. - .setWindowingStrategyInternal(updateWindowingStrategy(windowingStrategy)); - } - - @Override - protected Coder>> getDefaultOutputCoder(PCollection> input) { - return getOutputKvCoder(input.getCoder()); - } - - /** - * Returns the {@code Coder} of the input to this transform, which - * should be a {@code KvCoder}. - */ - @SuppressWarnings("unchecked") - static KvCoder getInputKvCoder(Coder> inputCoder) { - if (!(inputCoder instanceof KvCoder)) { - throw new IllegalStateException( - "GroupByKey requires its input to use KvCoder"); - } - return (KvCoder) inputCoder; - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Returns the {@code Coder} of the keys of the input to this - * transform, which is also used as the {@code Coder} of the keys of - * the output of this transform. - */ - static Coder getKeyCoder(Coder> inputCoder) { - return getInputKvCoder(inputCoder).getKeyCoder(); - } - - /** - * Returns the {@code Coder} of the values of the input to this transform. - */ - public static Coder getInputValueCoder(Coder> inputCoder) { - return getInputKvCoder(inputCoder).getValueCoder(); - } - - /** - * Returns the {@code Coder} of the {@code Iterable} values of the - * output of this transform. - */ - static Coder> getOutputValueCoder(Coder> inputCoder) { - return IterableCoder.of(getInputValueCoder(inputCoder)); - } - - /** - * Returns the {@code Coder} of the output of this transform. - */ - static KvCoder> getOutputKvCoder(Coder> inputCoder) { - return KvCoder.of(getKeyCoder(inputCoder), getOutputValueCoder(inputCoder)); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - if (fewKeys) { - builder.add(DisplayData.item("fewKeys", true) - .withLabel("Has Few Keys")); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Helper transform that makes timestamps and window assignments - * explicit in the value part of each key/value pair. - */ - public static class ReifyTimestampsAndWindows - extends PTransform>, - PCollection>>> { - @Override - public PCollection>> apply( - PCollection> input) { - @SuppressWarnings("unchecked") - KvCoder inputKvCoder = (KvCoder) input.getCoder(); - Coder keyCoder = inputKvCoder.getKeyCoder(); - Coder inputValueCoder = inputKvCoder.getValueCoder(); - Coder> outputValueCoder = FullWindowedValueCoder.of( - inputValueCoder, input.getWindowingStrategy().getWindowFn().windowCoder()); - Coder>> outputKvCoder = - KvCoder.of(keyCoder, outputValueCoder); - return input.apply(ParDo.of(new ReifyTimestampAndWindowsDoFn())) - .setCoder(outputKvCoder); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Helper transform that sorts the values associated with each key - * by timestamp. - */ - public static class SortValuesByTimestamp - extends PTransform>>>, - PCollection>>>> { - @Override - public PCollection>>> apply( - PCollection>>> input) { - return input.apply(ParDo.of( - new DoFn>>, - KV>>>() { - @Override - public void processElement(ProcessContext c) { - KV>> kvs = c.element(); - K key = kvs.getKey(); - Iterable> unsortedValues = kvs.getValue(); - List> sortedValues = new ArrayList<>(); - for (WindowedValue value : unsortedValues) { - sortedValues.add(value); - } - Collections.sort(sortedValues, - new Comparator>() { - @Override - public int compare(WindowedValue e1, WindowedValue e2) { - return e1.getTimestamp().compareTo(e2.getTimestamp()); - } - }); - c.output(KV.>>of(key, sortedValues)); - }})) - .setCoder(input.getCoder()); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Helper transform that takes a collection of timestamp-ordered - * values associated with each key, groups the values by window, - * combines windows as needed, and for each window in each key, - * outputs a collection of key/value-list pairs implicitly assigned - * to the window and with the timestamp derived from that window. - */ - public static class GroupAlsoByWindow - extends PTransform>>>, - PCollection>>> { - private final WindowingStrategy windowingStrategy; - - public GroupAlsoByWindow(WindowingStrategy windowingStrategy) { - this.windowingStrategy = windowingStrategy; - } - - @Override - @SuppressWarnings("unchecked") - public PCollection>> apply( - PCollection>>> input) { - @SuppressWarnings("unchecked") - KvCoder>> inputKvCoder = - (KvCoder>>) input.getCoder(); - - Coder keyCoder = inputKvCoder.getKeyCoder(); - Coder>> inputValueCoder = - inputKvCoder.getValueCoder(); - - IterableCoder> inputIterableValueCoder = - (IterableCoder>) inputValueCoder; - Coder> inputIterableElementCoder = - inputIterableValueCoder.getElemCoder(); - WindowedValueCoder inputIterableWindowedValueCoder = - (WindowedValueCoder) inputIterableElementCoder; - - Coder inputIterableElementValueCoder = - inputIterableWindowedValueCoder.getValueCoder(); - Coder> outputValueCoder = - IterableCoder.of(inputIterableElementValueCoder); - Coder>> outputKvCoder = KvCoder.of(keyCoder, outputValueCoder); - - return input - .apply(ParDo.of(groupAlsoByWindowsFn(windowingStrategy, inputIterableElementValueCoder))) - .setCoder(outputKvCoder); - } - - private GroupAlsoByWindowsViaOutputBufferDoFn, W> - groupAlsoByWindowsFn( - WindowingStrategy strategy, Coder inputIterableElementValueCoder) { - return new GroupAlsoByWindowsViaOutputBufferDoFn, W>( - strategy, SystemReduceFn.buffering(inputIterableElementValueCoder)); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Primitive helper transform that groups by key only, ignoring any - * window assignments. - */ - public static class GroupByKeyOnly - extends PTransform>, - PCollection>>> { - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public PCollection>> apply(PCollection> input) { - return PCollection.>>createPrimitiveOutputInternal( - input.getPipeline(), input.getWindowingStrategy(), input.isBounded()); - } - - /** - * Returns the {@code Coder} of the input to this transform, which - * should be a {@code KvCoder}. - */ - @SuppressWarnings("unchecked") - KvCoder getInputKvCoder(Coder> inputCoder) { - if (!(inputCoder instanceof KvCoder)) { - throw new IllegalStateException( - "GroupByKey requires its input to use KvCoder"); - } - return (KvCoder) inputCoder; - } - - @Override - protected Coder>> getDefaultOutputCoder(PCollection> input) { - return GroupByKey.getOutputKvCoder(input.getCoder()); - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - static { - registerWithDirectPipelineRunner(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private static void registerWithDirectPipelineRunner() { - DirectPipelineRunner.registerDefaultTransformEvaluator( - GroupByKeyOnly.class, - new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - GroupByKeyOnly transform, - DirectPipelineRunner.EvaluationContext context) { - evaluateHelper(transform, context); - } - }); - } - - private static void evaluateHelper( - GroupByKeyOnly transform, - DirectPipelineRunner.EvaluationContext context) { - PCollection> input = context.getInput(transform); - - List>> inputElems = - context.getPCollectionValuesWithMetadata(input); - - Coder keyCoder = GroupByKey.getKeyCoder(input.getCoder()); - - Map, List> groupingMap = new HashMap<>(); - - for (ValueWithMetadata> elem : inputElems) { - K key = elem.getValue().getKey(); - V value = elem.getValue().getValue(); - byte[] encodedKey; - try { - encodedKey = encodeToByteArray(keyCoder, key); - } catch (CoderException exn) { - // TODO: Put in better element printing: - // truncate if too long. - throw new IllegalArgumentException( - "unable to encode key " + key + " of input to " + transform - + " using " + keyCoder, - exn); - } - GroupingKey groupingKey = new GroupingKey<>(key, encodedKey); - List values = groupingMap.get(groupingKey); - if (values == null) { - values = new ArrayList(); - groupingMap.put(groupingKey, values); - } - values.add(value); - } - - List>>> outputElems = - new ArrayList<>(); - for (Map.Entry, List> entry : groupingMap.entrySet()) { - GroupingKey groupingKey = entry.getKey(); - K key = groupingKey.getKey(); - List values = entry.getValue(); - values = context.randomizeIfUnordered(values, true /* inPlaceAllowed */); - outputElems.add(ValueWithMetadata - .of(WindowedValue.valueInEmptyWindows(KV.>of(key, values))) - .withKey(key)); - } - - context.setPCollectionValuesWithMetadata(context.getOutput(transform), - outputElems); - } - - private static class GroupingKey { - private K key; - private byte[] encodedKey; - - public GroupingKey(K key, byte[] encodedKey) { - this.key = key; - this.encodedKey = encodedKey; - } - - public K getKey() { - return key; - } - - @Override - public boolean equals(Object o) { - if (o instanceof GroupingKey) { - GroupingKey that = (GroupingKey) o; - return Arrays.equals(this.encodedKey, that.encodedKey); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Arrays.hashCode(encodedKey); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java deleted file mode 100644 index 4f3a80f5bf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelization.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowingInternals; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Throwables; - -import org.joda.time.Instant; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Provides multi-threading of {@link DoFn}s, using threaded execution to - * process multiple elements concurrently within a bundle. - * - *

              Note, that each Dataflow worker will already process multiple bundles - * concurrently and usage of this class is meant only for cases where processing - * elements from within a bundle is limited by blocking calls. - * - *

              CPU intensive or IO intensive tasks are in general a poor fit for parallelization. - * This is because a limited resource that is already maximally utilized does not - * benefit from sub-division of work. The parallelization will increase the amount of time - * to process each element yet the throughput for processing will remain relatively the same. - * For example, if the local disk (an IO resource) has a maximum write rate of 10 MiB/s, - * and processing each element requires to write 20 MiBs to disk, then processing one element - * to disk will take 2 seconds. Yet processing 3 elements concurrently (each getting an equal - * share of the maximum write rate) will take at least 6 seconds to complete (there is additional - * overhead in the extra parallelization). - * - *

              To parallelize a {@link DoFn} to 10 threads: - *

              {@code
              - * PCollection data = ...;
              - * data.apply(
              - *   IntraBundleParallelization.of(new MyDoFn())
              - *                             .withMaxParallelism(10)));
              - * }
              - * - *

              An uncaught exception from the wrapped {@link DoFn} will result in the exception - * being rethrown in later calls to {@link MultiThreadedIntraBundleProcessingDoFn#processElement} - * or a call to {@link MultiThreadedIntraBundleProcessingDoFn#finishBundle}. - */ -public class IntraBundleParallelization { - /** - * Creates a {@link IntraBundleParallelization} {@link PTransform} for the given - * {@link DoFn} that processes elements using multiple threads. - * - *

              Note that the specified {@code doFn} needs to be thread safe. - */ - public static Bound of(DoFn doFn) { - return new Unbound().of(doFn); - } - - /** - * Creates a {@link IntraBundleParallelization} {@link PTransform} with the specified - * maximum concurrency level. - */ - public static Unbound withMaxParallelism(int maxParallelism) { - return new Unbound().withMaxParallelism(maxParallelism); - } - - /** - * An incomplete {@code IntraBundleParallelization} transform, with unbound input/output types. - * - *

              Before being applied, {@link IntraBundleParallelization.Unbound#of} must be - * invoked to specify the {@link DoFn} to invoke, which will also - * bind the input/output types of this {@code PTransform}. - */ - public static class Unbound { - private final int maxParallelism; - - Unbound() { - this(DEFAULT_MAX_PARALLELISM); - } - - Unbound(int maxParallelism) { - checkArgument(maxParallelism > 0, - "Expected parallelism factor greater than zero, received %s.", maxParallelism); - this.maxParallelism = maxParallelism; - } - - /** - * Returns a new {@link IntraBundleParallelization} {@link PTransform} like this one - * with the specified maximum concurrency level. - */ - public Unbound withMaxParallelism(int maxParallelism) { - return new Unbound(maxParallelism); - } - - /** - * Returns a new {@link IntraBundleParallelization} {@link PTransform} like this one - * with the specified {@link DoFn}. - * - *

              Note that the specified {@code doFn} needs to be thread safe. - */ - public Bound of(DoFn doFn) { - return new Bound<>(doFn, maxParallelism); - } - } - - /** - * A {@code PTransform} that, when applied to a {@code PCollection}, - * invokes a user-specified {@code DoFn} on all its elements, - * with all its outputs collected into an output - * {@code PCollection}. - * - *

              Note that the specified {@code doFn} needs to be thread safe. - * - * @param the type of the (main) input {@code PCollection} elements - * @param the type of the (main) output {@code PCollection} elements - */ - public static class Bound - extends PTransform, PCollection> { - private final DoFn doFn; - private final int maxParallelism; - - Bound(DoFn doFn, int maxParallelism) { - checkArgument(maxParallelism > 0, - "Expected parallelism factor greater than zero, received %s.", maxParallelism); - this.doFn = doFn; - this.maxParallelism = maxParallelism; - } - - /** - * Returns a new {@link IntraBundleParallelization} {@link PTransform} like this one - * with the specified maximum concurrency level. - */ - public Bound withMaxParallelism(int maxParallelism) { - return new Bound<>(doFn, maxParallelism); - } - - /** - * Returns a new {@link IntraBundleParallelization} {@link PTransform} like this one - * with the specified {@link DoFn}. - * - *

              Note that the specified {@code doFn} needs to be thread safe. - */ - public Bound - of(DoFn doFn) { - return new Bound<>(doFn, maxParallelism); - } - - @Override - public PCollection apply(PCollection input) { - return input.apply( - ParDo.of(new MultiThreadedIntraBundleProcessingDoFn<>(doFn, maxParallelism))); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("maxParallelism", maxParallelism) - .withLabel("Maximum Parallelism")) - .add(DisplayData.item("fn", doFn.getClass()) - .withLabel("Function")) - .include(doFn); - } - } - - /** - * A multi-threaded {@code DoFn} wrapper. - * - * @see IntraBundleParallelization#of(DoFn) - * - * @param the type of the (main) input elements - * @param the type of the (main) output elements - */ - public static class MultiThreadedIntraBundleProcessingDoFn - extends DoFn { - - public MultiThreadedIntraBundleProcessingDoFn(DoFn doFn, int maxParallelism) { - checkArgument(maxParallelism > 0, - "Expected parallelism factor greater than zero, received %s.", maxParallelism); - this.doFn = doFn; - this.maxParallelism = maxParallelism; - } - - @Override - public void startBundle(Context c) throws Exception { - doFn.startBundle(c); - - executor = c.getPipelineOptions().as(GcsOptions.class).getExecutorService(); - workTickets = new Semaphore(maxParallelism); - failure = new AtomicReference<>(); - } - - @Override - public void processElement(final ProcessContext c) throws Exception { - try { - workTickets.acquire(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException("Interrupted while scheduling work", e); - } - - if (failure.get() != null) { - throw new RuntimeException(failure.get()); - } - - executor.submit(new Runnable() { - @Override - public void run() { - try { - doFn.processElement(new WrappedContext(c)); - } catch (Throwable t) { - failure.compareAndSet(null, t); - Throwables.propagateIfPossible(t); - throw new AssertionError("Unexpected checked exception: " + t); - } finally { - workTickets.release(); - } - } - }); - } - - @Override - public void finishBundle(Context c) throws Exception { - // Acquire all the work tickets to guarantee that all the previous - // processElement calls have finished. - workTickets.acquire(maxParallelism); - if (failure.get() != null) { - throw new RuntimeException(failure.get()); - } - doFn.finishBundle(c); - } - - @Override - protected TypeDescriptor getInputTypeDescriptor() { - return doFn.getInputTypeDescriptor(); - } - - @Override - protected TypeDescriptor getOutputTypeDescriptor() { - return doFn.getOutputTypeDescriptor(); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Wraps a DoFn context, forcing single-thread output so that threads don't - * propagate through to downstream functions. - */ - private class WrappedContext extends ProcessContext { - private final ProcessContext context; - - WrappedContext(ProcessContext context) { - this.context = context; - } - - @Override - public InputT element() { - return context.element(); - } - - @Override - public PipelineOptions getPipelineOptions() { - return context.getPipelineOptions(); - } - - @Override - public T sideInput(PCollectionView view) { - return context.sideInput(view); - } - - @Override - public void output(OutputT output) { - synchronized (MultiThreadedIntraBundleProcessingDoFn.this) { - context.output(output); - } - } - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - synchronized (MultiThreadedIntraBundleProcessingDoFn.this) { - context.outputWithTimestamp(output, timestamp); - } - } - - @Override - public void sideOutput(TupleTag tag, T output) { - synchronized (MultiThreadedIntraBundleProcessingDoFn.this) { - context.sideOutput(tag, output); - } - } - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - synchronized (MultiThreadedIntraBundleProcessingDoFn.this) { - context.sideOutputWithTimestamp(tag, output, timestamp); - } - } - - @Override - public Instant timestamp() { - return context.timestamp(); - } - - @Override - public BoundedWindow window() { - return context.window(); - } - - @Override - public PaneInfo pane() { - return context.pane(); - } - - @Override - public WindowingInternals windowingInternals() { - return context.windowingInternals(); - } - - @Override - protected Aggregator createAggregatorInternal( - String name, CombineFn combiner) { - return context.createAggregatorInternal(name, combiner); - } - } - - private final DoFn doFn; - private int maxParallelism; - - private transient ExecutorService executor; - private transient Semaphore workTickets; - private transient AtomicReference failure; - } - - /** - * Default maximum for number of concurrent elements to process. - */ - private static final int DEFAULT_MAX_PARALLELISM = 16; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Keys.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Keys.java deleted file mode 100644 index 370d43dd02..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Keys.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * {@code Keys} takes a {@code PCollection} of {@code KV}s and - * returns a {@code PCollection} of the keys. - * - *

              Example of use: - *

               {@code
              - * PCollection> wordCounts = ...;
              - * PCollection words = wordCounts.apply(Keys.create());
              - * } 
              - * - *

              Each output element has the same timestamp and is in the same windows - * as its corresponding input element, and the output {@code PCollection} - * has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - *

              See also {@link Values}. - * - * @param the type of the keys in the input {@code PCollection}, - * and the type of the elements in the output {@code PCollection} - */ -public class Keys extends PTransform>, - PCollection> { - /** - * Returns a {@code Keys} {@code PTransform}. - * - * @param the type of the keys in the input {@code PCollection}, - * and the type of the elements in the output {@code PCollection} - */ - public static Keys create() { - return new Keys<>(); - } - - private Keys() { } - - @Override - public PCollection apply(PCollection> in) { - return - in.apply(ParDo.named("Keys") - .of(new DoFn, K>() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().getKey()); - } - })); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/KvSwap.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/KvSwap.java deleted file mode 100644 index 5a9cc87bc2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/KvSwap.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * {@code KvSwap} takes a {@code PCollection>} and - * returns a {@code PCollection>}, where all the keys and - * values have been swapped. - * - *

              Example of use: - *

               {@code
              - * PCollection wordsToCounts = ...;
              - * PCollection countsToWords =
              - *     wordToCounts.apply(KvSwap.create());
              - * } 
              - * - *

              Each output element has the same timestamp and is in the same windows - * as its corresponding input element, and the output {@code PCollection} - * has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - * @param the type of the keys in the input {@code PCollection} - * and the values in the output {@code PCollection} - * @param the type of the values in the input {@code PCollection} - * and the keys in the output {@code PCollection} - */ -public class KvSwap extends PTransform>, - PCollection>> { - /** - * Returns a {@code KvSwap} {@code PTransform}. - * - * @param the type of the keys in the input {@code PCollection} - * and the values in the output {@code PCollection} - * @param the type of the values in the input {@code PCollection} - * and the keys in the output {@code PCollection} - */ - public static KvSwap create() { - return new KvSwap<>(); - } - - private KvSwap() { } - - @Override - public PCollection> apply(PCollection> in) { - return - in.apply(ParDo.named("KvSwap") - .of(new DoFn, KV>() { - @Override - public void processElement(ProcessContext c) { - KV e = c.element(); - c.output(KV.of(e.getValue(), e.getKey())); - } - })); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java deleted file mode 100644 index d0733933c3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/MapElements.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -/** - * {@code PTransform}s for mapping a simple function over the elements of a {@link PCollection}. - */ -public class MapElements -extends PTransform, PCollection> { - - /** - * For a {@code SerializableFunction} {@code fn} and output type descriptor, - * returns a {@code PTransform} that takes an input {@code PCollection} and returns - * a {@code PCollection} containing {@code fn.apply(v)} for every element {@code v} in - * the input. - * - *

              Example of use in Java 8: - *

              {@code
              -   * PCollection wordLengths = words.apply(
              -   *     MapElements.via((String word) -> word.length())
              -   *         .withOutputType(new TypeDescriptor() {});
              -   * }
              - * - *

              In Java 7, the overload {@link #via(SimpleFunction)} is more concise as the output type - * descriptor need not be provided. - */ - public static MissingOutputTypeDescriptor - via(SerializableFunction fn) { - return new MissingOutputTypeDescriptor<>(fn); - } - - /** - * For a {@code SimpleFunction} {@code fn}, returns a {@code PTransform} that - * takes an input {@code PCollection} and returns a {@code PCollection} - * containing {@code fn.apply(v)} for every element {@code v} in the input. - * - *

              This overload is intended primarily for use in Java 7. In Java 8, the overload - * {@link #via(SerializableFunction)} supports use of lambda for greater concision. - * - *

              Example of use in Java 7: - *

              {@code
              -   * PCollection words = ...;
              -   * PCollection wordsPerLine = words.apply(MapElements.via(
              -   *     new SimpleFunction() {
              -   *       public Integer apply(String word) {
              -   *         return word.length();
              -   *       }
              -   *     }));
              -   * }
              - */ - public static MapElements - via(final SimpleFunction fn) { - return new MapElements<>(fn, fn.getOutputTypeDescriptor()); - } - - /** - * An intermediate builder for a {@link MapElements} transform. To complete the transform, provide - * an output type descriptor to {@link MissingOutputTypeDescriptor#withOutputType}. See - * {@link #via(SerializableFunction)} for a full example of use. - */ - public static final class MissingOutputTypeDescriptor { - - private final SerializableFunction fn; - - private MissingOutputTypeDescriptor(SerializableFunction fn) { - this.fn = fn; - } - - public MapElements withOutputType(TypeDescriptor outputType) { - return new MapElements<>(fn, outputType); - } - } - - /////////////////////////////////////////////////////////////////// - - private final SerializableFunction fn; - private final transient TypeDescriptor outputType; - - private MapElements( - SerializableFunction fn, - TypeDescriptor outputType) { - this.fn = fn; - this.outputType = outputType; - } - - @Override - public PCollection apply(PCollection input) { - return input.apply(ParDo.named("Map").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(fn.apply(c.element())); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - MapElements.this.populateDisplayData(builder); - } - })).setTypeDescriptorInternal(outputType); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("mapFn", fn.getClass()) - .withLabel("Map Function")); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java deleted file mode 100644 index 04bd360173..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Max.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.transforms.Combine.BinaryCombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; -import com.google.cloud.dataflow.sdk.util.common.CounterProvider; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * {@code PTransform}s for computing the maximum of the elements in a {@code PCollection}, or the - * maximum of the values associated with each key in a {@code PCollection} of {@code KV}s. - * - *

              Example 1: get the maximum of a {@code PCollection} of {@code Double}s. - *

               {@code
              - * PCollection input = ...;
              - * PCollection max = input.apply(Max.doublesGlobally());
              - * } 
              - * - *

              Example 2: calculate the maximum of the {@code Integer}s - * associated with each unique key (which is of type {@code String}). - *

               {@code
              - * PCollection> input = ...;
              - * PCollection> maxPerKey = input
              - *     .apply(Max.integersPerKey());
              - * } 
              - */ -public class Max { - - private Max() { - // do not instantiate - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a - * {@code PCollection} whose contents is the maximum of the input {@code PCollection}'s - * elements, or {@code Integer.MIN_VALUE} if there are no elements. - */ - public static Combine.Globally integersGlobally() { - return Combine.globally(new MaxIntegerFn()).named("Max.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and - * returns a {@code PCollection>} that contains an output element mapping each - * distinct key in the input {@code PCollection} to the maximum of the values associated with that - * key in the input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static Combine.PerKey integersPerKey() { - return Combine.perKey(new MaxIntegerFn()).named("Max.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a {@code - * PCollection} whose contents is the maximum of the input {@code PCollection}'s elements, - * or {@code Long.MIN_VALUE} if there are no elements. - */ - public static Combine.Globally longsGlobally() { - return Combine.globally(new MaxLongFn()).named("Max.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns a - * {@code PCollection>} that contains an output element mapping each distinct key in - * the input {@code PCollection} to the maximum of the values associated with that key in the - * input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static Combine.PerKey longsPerKey() { - return Combine.perKey(new MaxLongFn()).named("Max.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a - * {@code PCollection} whose contents is the maximum of the input {@code PCollection}'s - * elements, or {@code Double.NEGATIVE_INFINITY} if there are no elements. - */ - public static Combine.Globally doublesGlobally() { - return Combine.globally(new MaxDoubleFn()).named("Max.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns - * a {@code PCollection>} that contains an output element mapping each distinct key - * in the input {@code PCollection} to the maximum of the values associated with that key in the - * input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static Combine.PerKey doublesPerKey() { - return Combine.perKey(new MaxDoubleFn()).named("Max.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a {@code - * PCollection} whose contents is the maximum according to the natural ordering of {@code T} - * of the input {@code PCollection}'s elements, or {@code null} if there are no elements. - */ - public static > - Combine.Globally globally() { - return Combine.globally(MaxFn.naturalOrder()).named("Max.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns a - * {@code PCollection>} that contains an output element mapping each distinct key in the - * input {@code PCollection} to the maximum according to the natural ordering of {@code T} of the - * values associated with that key in the input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static > - Combine.PerKey perKey() { - return Combine.perKey(MaxFn.naturalOrder()).named("Max.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a {@code - * PCollection} whose contents is the maximum of the input {@code PCollection}'s elements, or - * {@code null} if there are no elements. - */ - public static & Serializable> - Combine.Globally globally(ComparatorT comparator) { - return Combine.globally(MaxFn.of(comparator)).named("Max.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns a - * {@code PCollection>} that contains one output element per key mapping each - * to the maximum of the values associated with that key in the input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static & Serializable> - Combine.PerKey perKey(ComparatorT comparator) { - return Combine.perKey(MaxFn.of(comparator)).named("Max.PerKey"); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code CombineFn} that computes the maximum of a collection of elements of type {@code T} - * using an arbitrary {@link Comparator}, useful as an argument to {@link Combine#globally} or - * {@link Combine#perKey}. - * - * @param the type of the values being compared - */ - public static class MaxFn extends BinaryCombineFn { - - private final T identity; - private final Comparator comparator; - - private & Serializable> MaxFn( - T identity, ComparatorT comparator) { - this.identity = identity; - this.comparator = comparator; - } - - public static & Serializable> - MaxFn of(T identity, ComparatorT comparator) { - return new MaxFn(identity, comparator); - } - - public static & Serializable> - MaxFn of(ComparatorT comparator) { - return new MaxFn(null, comparator); - } - - public static > MaxFn naturalOrder(T identity) { - return new MaxFn(identity, new Top.Largest()); - } - - public static > MaxFn naturalOrder() { - return new MaxFn(null, new Top.Largest()); - } - - @Override - public T identity() { - return identity; - } - - @Override - public T apply(T left, T right) { - return comparator.compare(left, right) >= 0 ? left : right; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("comparer", comparator.getClass()) - .withLabel("Record Comparer")); - } - } - - /** - * A {@code CombineFn} that computes the maximum of a collection of {@code Integer}s, useful as an - * argument to {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class MaxIntegerFn extends MaxFn implements - CounterProvider { - public MaxIntegerFn() { - super(Integer.MIN_VALUE, new Top.Largest()); - } - - @Override - public Counter getCounter(String name) { - return Counter.ints(name, AggregationKind.MAX); - } - } - - /** - * A {@code CombineFn} that computes the maximum of a collection of {@code Long}s, useful as an - * argument to {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class MaxLongFn extends MaxFn implements - CounterProvider { - public MaxLongFn() { - super(Long.MIN_VALUE, new Top.Largest()); - } - - @Override - public Counter getCounter(String name) { - return Counter.longs(name, AggregationKind.MAX); - } - } - - /** - * A {@code CombineFn} that computes the maximum of a collection of {@code Double}s, useful as an - * argument to {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class MaxDoubleFn extends MaxFn implements - CounterProvider { - public MaxDoubleFn() { - super(Double.NEGATIVE_INFINITY, new Top.Largest()); - } - - @Override - public Counter getCounter(String name) { - return Counter.doubles(name, AggregationKind.MAX); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Mean.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Mean.java deleted file mode 100644 index 7dccfb626b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Mean.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.DoubleCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn.Accumulator; -import com.google.common.base.MoreObjects; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Objects; - -/** - * {@code PTransform}s for computing the arithmetic mean - * (a.k.a. average) of the elements in a {@code PCollection}, or the - * mean of the values associated with each key in a - * {@code PCollection} of {@code KV}s. - * - *

              Example 1: get the mean of a {@code PCollection} of {@code Long}s. - *

               {@code
              - * PCollection input = ...;
              - * PCollection mean = input.apply(Mean.globally());
              - * } 
              - * - *

              Example 2: calculate the mean of the {@code Integer}s - * associated with each unique key (which is of type {@code String}). - *

               {@code
              - * PCollection> input = ...;
              - * PCollection> meanPerKey =
              - *     input.apply(Mean.perKey());
              - * } 
              - */ -public class Mean { - - private Mean() { } // Namespace only - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a - * {@code PCollection} whose contents is the mean of the - * input {@code PCollection}'s elements, or - * {@code 0} if there are no elements. - * - * @param the type of the {@code Number}s being combined - */ - public static Combine.Globally globally() { - return Combine.globally(new MeanFn<>()).named("Mean.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to the mean of the values associated with - * that key in the input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and bucketing. - * - * @param the type of the keys - * @param the type of the {@code Number}s being combined - */ - public static Combine.PerKey perKey() { - return Combine.perKey(new MeanFn<>()).named("Mean.PerKey"); - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code Combine.CombineFn} that computes the arithmetic mean - * (a.k.a. average) of an {@code Iterable} of numbers of type - * {@code N}, useful as an argument to {@link Combine#globally} or - * {@link Combine#perKey}. - * - *

              Returns {@code Double.NaN} if combining zero elements. - * - * @param the type of the {@code Number}s being combined - */ - static class MeanFn - extends Combine.AccumulatingCombineFn, Double> { - /** - * Constructs a combining function that computes the mean over - * a collection of values of type {@code N}. - */ - public MeanFn() {} - - @Override - public CountSum createAccumulator() { - return new CountSum<>(); - } - - @Override - public Coder> getAccumulatorCoder( - CoderRegistry registry, Coder inputCoder) { - return new CountSumCoder<>(); - } - } - - /** - * Accumulator class for {@link MeanFn}. - */ - static class CountSum - implements Accumulator, Double> { - - long count = 0; - double sum = 0.0; - - public CountSum() { - this(0, 0); - } - - public CountSum(long count, double sum) { - this.count = count; - this.sum = sum; - } - - @Override - public void addInput(NumT element) { - count++; - sum += element.doubleValue(); - } - - @Override - public void mergeAccumulator(CountSum accumulator) { - count += accumulator.count; - sum += accumulator.sum; - } - - @Override - public Double extractOutput() { - return count == 0 ? Double.NaN : sum / count; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof CountSum)) { - return false; - } - @SuppressWarnings("unchecked") - CountSum otherCountSum = (CountSum) other; - return (count == otherCountSum.count) - && (sum == otherCountSum.sum); - } - - @Override - public int hashCode() { - return Objects.hash(count, sum); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("count", count) - .add("sum", sum) - .toString(); - } - } - - static class CountSumCoder - extends AtomicCoder> { - private static final Coder LONG_CODER = BigEndianLongCoder.of(); - private static final Coder DOUBLE_CODER = DoubleCoder.of(); - - @Override - public void encode(CountSum value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - Coder.Context nestedContext = context.nested(); - LONG_CODER.encode(value.count, outStream, nestedContext); - DOUBLE_CODER.encode(value.sum, outStream, nestedContext); - } - - @Override - public CountSum decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - Coder.Context nestedContext = context.nested(); - return new CountSum<>( - LONG_CODER.decode(inStream, nestedContext), - DOUBLE_CODER.decode(inStream, nestedContext)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java deleted file mode 100644 index 7194d9d3aa..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Min.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.transforms.Combine.BinaryCombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; -import com.google.cloud.dataflow.sdk.util.common.CounterProvider; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * {@code PTransform}s for computing the minimum of the elements in a {@code PCollection}, or the - * minimum of the values associated with each key in a {@code PCollection} of {@code KV}s. - * - *

              Example 1: get the minimum of a {@code PCollection} of {@code Double}s. - *

               {@code
              - * PCollection input = ...;
              - * PCollection min = input.apply(Min.doublesGlobally());
              - * } 
              - * - *

              Example 2: calculate the minimum of the {@code Integer}s - * associated with each unique key (which is of type {@code String}). - *

               {@code
              - * PCollection> input = ...;
              - * PCollection> minPerKey = input
              - *     .apply(Min.integersPerKey());
              - * } 
              - */ -public class Min { - - private Min() { - // do not instantiate - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a - * {@code PCollection} whose contents is a single value that is the minimum of the input - * {@code PCollection}'s elements, or {@code Integer.MAX_VALUE} if there are no elements. - */ - public static Combine.Globally integersGlobally() { - return Combine.globally(new MinIntegerFn()).named("Min.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and - * returns a {@code PCollection>} that contains an output element mapping each - * distinct key in the input {@code PCollection} to the minimum of the values associated with that - * key in the input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static Combine.PerKey integersPerKey() { - return Combine.perKey(new MinIntegerFn()).named("Min.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a {@code - * PCollection} whose contents is the minimum of the input {@code PCollection}'s elements, - * or {@code Long.MAX_VALUE} if there are no elements. - */ - public static Combine.Globally longsGlobally() { - return Combine.globally(new MinLongFn()).named("Min.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns a - * {@code PCollection>} that contains an output element mapping each distinct key in - * the input {@code PCollection} to the minimum of the values associated with that key in the - * input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static Combine.PerKey longsPerKey() { - return Combine.perKey(new MinLongFn()).named("Min.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a - * {@code PCollection} whose contents is the minimum of the input {@code PCollection}'s - * elements, or {@code Double.POSITIVE_INFINITY} if there are no elements. - */ - public static Combine.Globally doublesGlobally() { - return Combine.globally(new MinDoubleFn()).named("Min.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns - * a {@code PCollection>} that contains an output element mapping each distinct key - * in the input {@code PCollection} to the minimum of the values associated with that key in the - * input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static Combine.PerKey doublesPerKey() { - return Combine.perKey(new MinDoubleFn()).named("Min.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a {@code - * PCollection} whose contents is the minimum according to the natural ordering of {@code T} - * of the input {@code PCollection}'s elements, or {@code null} if there are no elements. - */ - public static > - Combine.Globally globally() { - return Combine.globally(MinFn.naturalOrder()).named("Min.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns a - * {@code PCollection>} that contains an output element mapping each distinct key in the - * input {@code PCollection} to the minimum according to the natural ordering of {@code T} of the - * values associated with that key in the input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static > - Combine.PerKey perKey() { - return Combine.perKey(MinFn.naturalOrder()).named("Min.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection} and returns a {@code - * PCollection} whose contents is the minimum of the input {@code PCollection}'s elements, or - * {@code null} if there are no elements. - */ - public static & Serializable> - Combine.Globally globally(ComparatorT comparator) { - return Combine.globally(MinFn.of(comparator)).named("Min.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input {@code PCollection>} and returns a - * {@code PCollection>} that contains one output element per key mapping each - * to the minimum of the values associated with that key in the input {@code PCollection}. - * - *

              See {@link Combine.PerKey} for how this affects timestamps and windowing. - */ - public static & Serializable> - Combine.PerKey perKey(ComparatorT comparator) { - return Combine.perKey(MinFn.of(comparator)).named("Min.PerKey"); - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code CombineFn} that computes the maximum of a collection of elements of type {@code T} - * using an arbitrary {@link Comparator}, useful as an argument to {@link Combine#globally} or - * {@link Combine#perKey}. - * - * @param the type of the values being compared - */ - public static class MinFn extends BinaryCombineFn { - - private final T identity; - private final Comparator comparator; - - private & Serializable> MinFn( - T identity, ComparatorT comparator) { - this.identity = identity; - this.comparator = comparator; - } - - public static & Serializable> - MinFn of(T identity, ComparatorT comparator) { - return new MinFn(identity, comparator); - } - - public static & Serializable> - MinFn of(ComparatorT comparator) { - return new MinFn(null, comparator); - } - - public static > MinFn naturalOrder(T identity) { - return new MinFn(identity, new Top.Largest()); - } - - public static > MinFn naturalOrder() { - return new MinFn(null, new Top.Largest()); - } - - @Override - public T identity() { - return identity; - } - - @Override - public T apply(T left, T right) { - return comparator.compare(left, right) <= 0 ? left : right; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("comparer", comparator.getClass()) - .withLabel("Record Comparer")); - } - } - - /** - * A {@code CombineFn} that computes the minimum of a collection of {@code Integer}s, useful as an - * argument to {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class MinIntegerFn extends MinFn implements - CounterProvider { - public MinIntegerFn() { - super(Integer.MAX_VALUE, new Top.Largest()); - } - - @Override - public Counter getCounter(String name) { - return Counter.ints(name, AggregationKind.MIN); - } - } - - /** - * A {@code CombineFn} that computes the minimum of a collection of {@code Long}s, useful as an - * argument to {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class MinLongFn extends MinFn implements - CounterProvider { - public MinLongFn() { - super(Long.MAX_VALUE, new Top.Largest()); - } - - @Override - public Counter getCounter(String name) { - return Counter.longs(name, AggregationKind.MIN); - } - } - - /** - * A {@code CombineFn} that computes the minimum of a collection of {@code Double}s, useful as an - * argument to {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class MinDoubleFn extends MinFn implements - CounterProvider { - public MinDoubleFn() { - super(Double.POSITIVE_INFINITY, new Top.Largest()); - } - - @Override - public Counter getCounter(String name) { - return Counter.doubles(name, AggregationKind.MIN); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java deleted file mode 100644 index 38e0312857..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.TypedPValue; - -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -/** - * A {@code PTransform} is an operation that takes an - * {@code InputT} (some subtype of {@link PInput}) and produces an - * {@code OutputT} (some subtype of {@link POutput}). - * - *

              Common PTransforms include root PTransforms like - * {@link com.google.cloud.dataflow.sdk.io.TextIO.Read}, - * {@link Create}, processing and - * conversion operations like {@link ParDo}, - * {@link GroupByKey}, - * {@link com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey}, - * {@link Combine}, and {@link Count}, and outputting - * PTransforms like - * {@link com.google.cloud.dataflow.sdk.io.TextIO.Write}. Users also - * define their own application-specific composite PTransforms. - * - *

              Each {@code PTransform} has a single - * {@code InputT} type and a single {@code OutputT} type. Many - * PTransforms conceptually transform one input value to one output - * value, and in this case {@code InputT} and {@code Output} are - * typically instances of - * {@link com.google.cloud.dataflow.sdk.values.PCollection}. - * A root - * PTransform conceptually has no input; in this case, conventionally - * a {@link com.google.cloud.dataflow.sdk.values.PBegin} object - * produced by calling {@link Pipeline#begin} is used as the input. - * An outputting PTransform conceptually has no output; in this case, - * conventionally {@link com.google.cloud.dataflow.sdk.values.PDone} - * is used as its output type. Some PTransforms conceptually have - * multiple inputs and/or outputs; in these cases special "bundling" - * classes like - * {@link com.google.cloud.dataflow.sdk.values.PCollectionList}, - * {@link com.google.cloud.dataflow.sdk.values.PCollectionTuple} - * are used - * to combine multiple values into a single bundle for passing into or - * returning from the PTransform. - * - *

              A {@code PTransform} is invoked by calling - * {@code apply()} on its {@code InputT}, returning its {@code OutputT}. - * Calls can be chained to concisely create linear pipeline segments. - * For example: - * - *

               {@code
              - * PCollection pc1 = ...;
              - * PCollection pc2 =
              - *     pc1.apply(ParDo.of(new MyDoFn>()))
              - *        .apply(GroupByKey.create())
              - *        .apply(Combine.perKey(new MyKeyedCombineFn()))
              - *        .apply(ParDo.of(new MyDoFn2,T2>()));
              - * } 
              - * - *

              PTransform operations have unique names, which are used by the - * system when explaining what's going on during optimization and - * execution. Each PTransform gets a system-provided default name, - * but it's a good practice to specify an explicit name, where - * possible, using the {@code named()} method offered by some - * PTransforms such as {@link ParDo}. For example: - * - *

               {@code
              - * ...
              - * .apply(ParDo.named("Step1").of(new MyDoFn3()))
              - * ...
              - * } 
              - * - *

              Each PCollection output produced by a PTransform, - * either directly or within a "bundling" class, automatically gets - * its own name derived from the name of its producing PTransform. - * - *

              Each PCollection output produced by a PTransform - * also records a {@link com.google.cloud.dataflow.sdk.coders.Coder} - * that specifies how the elements of that PCollection - * are to be encoded as a byte string, if necessary. The - * PTransform may provide a default Coder for any of its outputs, for - * instance by deriving it from the PTransform input's Coder. If the - * PTransform does not specify the Coder for an output PCollection, - * the system will attempt to infer a Coder for it, based on - * what's known at run-time about the Java type of the output's - * elements. The enclosing {@link Pipeline}'s - * {@link com.google.cloud.dataflow.sdk.coders.CoderRegistry} - * (accessible via {@link Pipeline#getCoderRegistry}) defines the - * mapping from Java types to the default Coder to use, for a standard - * set of Java types; users can extend this mapping for additional - * types, via - * {@link com.google.cloud.dataflow.sdk.coders.CoderRegistry#registerCoder}. - * If this inference process fails, either because the Java type was - * not known at run-time (e.g., due to Java's "erasure" of generic - * types) or there was no default Coder registered, then the Coder - * should be specified manually by calling - * {@link com.google.cloud.dataflow.sdk.values.TypedPValue#setCoder} - * on the output PCollection. The Coder of every output - * PCollection must be determined one way or another - * before that output is used as an input to another PTransform, or - * before the enclosing Pipeline is run. - * - *

              A small number of PTransforms are implemented natively by the - * Google Cloud Dataflow SDK; such PTransforms simply return an - * output value as their apply implementation. - * The majority of PTransforms are - * implemented as composites of other PTransforms. Such a PTransform - * subclass typically just implements {@link #apply}, computing its - * Output value from its {@code InputT} value. User programs are encouraged to - * use this mechanism to modularize their own code. Such composite - * abstractions get their own name, and navigating through the - * composition hierarchy of PTransforms is supported by the monitoring - * interface. Examples of composite PTransforms can be found in this - * directory and in examples. From the caller's point of view, there - * is no distinction between a PTransform implemented natively and one - * implemented in terms of other PTransforms; both kinds of PTransform - * are invoked in the same way, using {@code apply()}. - * - *

              Note on Serialization

              - * - *

              {@code PTransform} doesn't actually support serialization, despite - * implementing {@code Serializable}. - * - *

              {@code PTransform} is marked {@code Serializable} solely - * because it is common for an anonymous {@code DoFn}, - * instance to be created within an - * {@code apply()} method of a composite {@code PTransform}. - * - *

              Each of those {@code *Fn}s is {@code Serializable}, but - * unfortunately its instance state will contain a reference to the - * enclosing {@code PTransform} instance, and so attempt to serialize - * the {@code PTransform} instance, even though the {@code *Fn} - * instance never references anything about the enclosing - * {@code PTransform}. - * - *

              To allow such anonymous {@code *Fn}s to be written - * conveniently, {@code PTransform} is marked as {@code Serializable}, - * and includes dummy {@code writeObject()} and {@code readObject()} - * operations that do not save or restore any state. - * - * @see Applying Transformations - * - * @param the type of the input to this PTransform - * @param the type of the output of this PTransform - */ -public abstract class PTransform - implements Serializable /* See the note above */, HasDisplayData { - /** - * Applies this {@code PTransform} on the given {@code InputT}, and returns its - * {@code Output}. - * - *

              Composite transforms, which are defined in terms of other transforms, - * should return the output of one of the composed transforms. Non-composite - * transforms, which do not apply any transforms internally, should return - * a new unbound output and register evaluators (via backend-specific - * registration methods). - * - *

              The default implementation throws an exception. A derived class must - * either implement apply, or else each runner must supply a custom - * implementation via - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner#apply}. - */ - public OutputT apply(InputT input) { - throw new IllegalArgumentException( - "Runner " + input.getPipeline().getRunner() - + " has not registered an implementation for the required primitive operation " - + this); - } - - /** - * Called before invoking apply (which may be intercepted by the runner) to - * verify this transform is fully specified and applicable to the specified - * input. - * - *

              By default, does nothing. - */ - public void validate(InputT input) { } - - /** - * Returns the transform name. - * - *

              This name is provided by the transform creator and is not required to be unique. - */ - public String getName() { - return name != null ? name : getKindString(); - } - - ///////////////////////////////////////////////////////////////////////////// - - // See the note about about PTransform's fake Serializability, to - // understand why all of its instance state is transient. - - /** - * The base name of this {@code PTransform}, e.g., from - * {@link ParDo#named(String)}, or from defaults, or {@code null} if not - * yet assigned. - */ - protected final transient String name; - - protected PTransform() { - this.name = null; - } - - protected PTransform(String name) { - this.name = name; - } - - @Override - public String toString() { - if (name == null) { - return getKindString(); - } else { - return getName() + " [" + getKindString() + "]"; - } - } - - /** - * Returns the name to use by default for this {@code PTransform} - * (not including the names of any enclosing {@code PTransform}s). - * - *

              By default, returns the base name of this {@code PTransform}'s class. - * - *

              The caller is responsible for ensuring that names of applied - * {@code PTransform}s are unique, e.g., by adding a uniquifying - * suffix when needed. - */ - protected String getKindString() { - if (getClass().isAnonymousClass()) { - return "AnonymousTransform"; - } else { - return StringUtils.approximatePTransformName(getClass()); - } - } - - private void writeObject(ObjectOutputStream oos) { - // We don't really want to be serializing this object, but we - // often have serializable anonymous DoFns nested within a - // PTransform. - } - - private void readObject(ObjectInputStream oos) { - // We don't really want to be serializing this object, but we - // often have serializable anonymous DoFns nested within a - // PTransform. - } - - /** - * Returns the default {@code Coder} to use for the output of this - * single-output {@code PTransform}. - * - *

              By default, always throws - * - * @throws CannotProvideCoderException if no coder can be inferred - */ - protected Coder getDefaultOutputCoder() throws CannotProvideCoderException { - throw new CannotProvideCoderException( - "PTransform.getDefaultOutputCoder called."); - } - - /** - * Returns the default {@code Coder} to use for the output of this - * single-output {@code PTransform} when applied to the given input. - * - *

              By default, always throws. - * - * @throws CannotProvideCoderException if none can be inferred. - */ - protected Coder getDefaultOutputCoder(@SuppressWarnings("unused") InputT input) - throws CannotProvideCoderException { - return getDefaultOutputCoder(); - } - - /** - * Returns the default {@code Coder} to use for the given output of - * this single-output {@code PTransform} when applied to the given input. - * - *

              By default, always throws. - * - * @throws CannotProvideCoderException if none can be inferred. - */ - public Coder getDefaultOutputCoder( - InputT input, @SuppressWarnings("unused") TypedPValue output) - throws CannotProvideCoderException { - @SuppressWarnings("unchecked") - Coder defaultOutputCoder = (Coder) getDefaultOutputCoder(input); - return defaultOutputCoder; - } - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(Builder builder) { - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java deleted file mode 100644 index 2134de6474..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/ParDo.java +++ /dev/null @@ -1,1358 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.DirectModeExecutionContext; -import com.google.cloud.dataflow.sdk.util.DirectSideInputReader; -import com.google.cloud.dataflow.sdk.util.DoFnRunner; -import com.google.cloud.dataflow.sdk.util.DoFnRunnerBase; -import com.google.cloud.dataflow.sdk.util.DoFnRunners; -import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.MutationDetector; -import com.google.cloud.dataflow.sdk.util.MutationDetectors; -import com.google.cloud.dataflow.sdk.util.PTuple; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.StringUtils; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.cloud.dataflow.sdk.values.TypedPValue; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Maps; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentMap; - -import javax.annotation.Nullable; - -/** - * {@link ParDo} is the core element-wise transform in Google Cloud - * Dataflow, invoking a user-specified function on each of the elements of the input - * {@link PCollection} to produce zero or more output elements, all - * of which are collected into the output {@link PCollection}. - * - *

              Elements are processed independently, and possibly in parallel across - * distributed cloud resources. - * - *

              The {@link ParDo} processing style is similar to what happens inside - * the "Mapper" or "Reducer" class of a MapReduce-style algorithm. - * - *

              {@link DoFn DoFns}

              - * - *

              The function to use to process each element is specified by a - * {@link DoFn DoFn<InputT, OutputT>}, primarily via its - * {@link DoFn#processElement processElement} method. The {@link DoFn} may also - * override the default implementations of {@link DoFn#startBundle startBundle} - * and {@link DoFn#finishBundle finishBundle}. - * - *

              Conceptually, when a {@link ParDo} transform is executed, the - * elements of the input {@link PCollection} are first divided up - * into some number of "bundles". These are farmed off to distributed - * worker machines (or run locally, if using the {@link DirectPipelineRunner}). - * For each bundle of input elements processing proceeds as follows: - * - *

                - *
              1. A fresh instance of the argument {@link DoFn} is created on a worker. This may - * be through deserialization or other means. If the {@link DoFn} subclass - * does not override {@link DoFn#startBundle startBundle} or - * {@link DoFn#finishBundle finishBundle} then this may be optimized since - * it cannot observe the start and end of a bundle.
              2. - *
              3. The {@link DoFn DoFn's} {@link DoFn#startBundle} method is called to - * initialize it. If this method is not overridden, the call may be optimized - * away.
              4. - *
              5. The {@link DoFn DoFn's} {@link DoFn#processElement} method - * is called on each of the input elements in the bundle.
              6. - *
              7. The {@link DoFn DoFn's} {@link DoFn#finishBundle} method is called - * to complete its work. After {@link DoFn#finishBundle} is called, the - * framework will never again invoke any of these three processing methods. - * If this method is not overridden, this call may be optimized away.
              8. - *
              - * - *

              Each of the calls to any of the {@link DoFn DoFn's} processing - * methods can produce zero or more output elements. All of the - * of output elements from all of the {@link DoFn} instances - * are included in the output {@link PCollection}. - * - *

              For example: - * - *

               {@code
              - * PCollection lines = ...;
              - * PCollection words =
              - *     lines.apply(ParDo.of(new DoFn() {
              - *         public void processElement(ProcessContext c) {
              - *           String line = c.element();
              - *           for (String word : line.split("[^a-zA-Z']+")) {
              - *             c.output(word);
              - *           }
              - *         }}));
              - * PCollection wordLengths =
              - *     words.apply(ParDo.of(new DoFn() {
              - *         public void processElement(ProcessContext c) {
              - *           String word = c.element();
              - *           Integer length = word.length();
              - *           c.output(length);
              - *         }}));
              - * } 
              - * - *

              Each output element has the same timestamp and is in the same windows - * as its corresponding input element, and the output {@code PCollection} - * has the same {@link WindowFn} associated with it as the input. - * - *

              Naming {@link ParDo ParDo} transforms

              - * - *

              The name of a transform is used to provide a name for any node in the - * {@link Pipeline} graph resulting from application of the transform. - * It is best practice to provide a name at the time of application, - * via {@link PCollection#apply(String, PTransform)}. Otherwise, - * a unique name - which may not be stable across pipeline revision - - * will be generated, based on the transform name. - * - *

              If a {@link ParDo} is applied exactly once inlined, then - * it can be given a name via {@link #named}. For example: - * - *

               {@code
              - * PCollection words =
              - *     lines.apply(ParDo.named("ExtractWords")
              - *                      .of(new DoFn() { ... }));
              - * PCollection wordLengths =
              - *     words.apply(ParDo.named("ComputeWordLengths")
              - *                      .of(new DoFn() { ... }));
              - * } 
              - * - *

              Side Inputs

              - * - *

              While a {@link ParDo} processes elements from a single "main input" - * {@link PCollection}, it can take additional "side input" - * {@link PCollectionView PCollectionViews}. These side input - * {@link PCollectionView PCollectionViews} express styles of accessing - * {@link PCollection PCollections} computed by earlier pipeline operations, - * passed in to the {@link ParDo} transform using - * {@link #withSideInputs}, and their contents accessible to each of - * the {@link DoFn} operations via {@link DoFn.ProcessContext#sideInput sideInput}. - * For example: - * - *

               {@code
              - * PCollection words = ...;
              - * PCollection maxWordLengthCutOff = ...; // Singleton PCollection
              - * final PCollectionView maxWordLengthCutOffView =
              - *     maxWordLengthCutOff.apply(View.asSingleton());
              - * PCollection wordsBelowCutOff =
              - *     words.apply(ParDo.withSideInputs(maxWordLengthCutOffView)
              - *                      .of(new DoFn() {
              - *         public void processElement(ProcessContext c) {
              - *           String word = c.element();
              - *           int lengthCutOff = c.sideInput(maxWordLengthCutOffView);
              - *           if (word.length() <= lengthCutOff) {
              - *             c.output(word);
              - *           }
              - *         }}));
              - * } 
              - * - *

              Side Outputs

              - * - *

              Optionally, a {@link ParDo} transform can produce multiple - * output {@link PCollection PCollections}, both a "main output" - * {@code PCollection} plus any number of "side output" - * {@link PCollection PCollections}, each keyed by a distinct {@link TupleTag}, - * and bundled in a {@link PCollectionTuple}. The {@link TupleTag TupleTags} - * to be used for the output {@link PCollectionTuple} are specified by - * invoking {@link #withOutputTags}. Unconsumed side outputs do not - * necessarily need to be explicitly specified, even if the {@link DoFn} - * generates them. Within the {@link DoFn}, an element is added to the - * main output {@link PCollection} as normal, using - * {@link DoFn.Context#output}, while an element is added to a side output - * {@link PCollection} using {@link DoFn.Context#sideOutput}. For example: - * - *

               {@code
              - * PCollection words = ...;
              - * // Select words whose length is below a cut off,
              - * // plus the lengths of words that are above the cut off.
              - * // Also select words starting with "MARKER".
              - * final int wordLengthCutOff = 10;
              - * // Create tags to use for the main and side outputs.
              - * final TupleTag wordsBelowCutOffTag =
              - *     new TupleTag(){};
              - * final TupleTag wordLengthsAboveCutOffTag =
              - *     new TupleTag(){};
              - * final TupleTag markedWordsTag =
              - *     new TupleTag(){};
              - * PCollectionTuple results =
              - *     words.apply(
              - *         ParDo
              - *         // Specify the main and consumed side output tags of the
              - *         // PCollectionTuple result:
              - *         .withOutputTags(wordsBelowCutOffTag,
              - *                         TupleTagList.of(wordLengthsAboveCutOffTag)
              - *                                     .and(markedWordsTag))
              - *         .of(new DoFn() {
              - *             // Create a tag for the unconsumed side output.
              - *             final TupleTag specialWordsTag =
              - *                 new TupleTag(){};
              - *             public void processElement(ProcessContext c) {
              - *               String word = c.element();
              - *               if (word.length() <= wordLengthCutOff) {
              - *                 // Emit this short word to the main output.
              - *                 c.output(word);
              - *               } else {
              - *                 // Emit this long word's length to a side output.
              - *                 c.sideOutput(wordLengthsAboveCutOffTag, word.length());
              - *               }
              - *               if (word.startsWith("MARKER")) {
              - *                 // Emit this word to a different side output.
              - *                 c.sideOutput(markedWordsTag, word);
              - *               }
              - *               if (word.startsWith("SPECIAL")) {
              - *                 // Emit this word to the unconsumed side output.
              - *                 c.sideOutput(specialWordsTag, word);
              - *               }
              - *             }}));
              - * // Extract the PCollection results, by tag.
              - * PCollection wordsBelowCutOff =
              - *     results.get(wordsBelowCutOffTag);
              - * PCollection wordLengthsAboveCutOff =
              - *     results.get(wordLengthsAboveCutOffTag);
              - * PCollection markedWords =
              - *     results.get(markedWordsTag);
              - * } 
              - * - *

              Properties May Be Specified In Any Order

              - * - *

              Several properties can be specified for a {@link ParDo} - * {@link PTransform}, including name, side inputs, side output tags, - * and {@link DoFn} to invoke. Only the {@link DoFn} is required; the - * name is encouraged but not required, and side inputs and side - * output tags are only specified when they're needed. These - * properties can be specified in any order, as long as they're - * specified before the {@link ParDo} {@link PTransform} is applied. - * - *

              The approach used to allow these properties to be specified in - * any order, with some properties omitted, is to have each of the - * property "setter" methods defined as static factory methods on - * {@link ParDo} itself, which return an instance of either - * {@link ParDo.Unbound} or - * {@link ParDo.Bound} nested classes, each of which offer - * property setter instance methods to enable setting additional - * properties. {@link ParDo.Bound} is used for {@link ParDo} - * transforms whose {@link DoFn} is specified and whose input and - * output static types have been bound. {@link ParDo.Unbound ParDo.Unbound} is used - * for {@link ParDo} transforms that have not yet had their - * {@link DoFn} specified. Only {@link ParDo.Bound} instances can be - * applied. - * - *

              Another benefit of this approach is that it reduces the number - * of type parameters that need to be specified manually. In - * particular, the input and output types of the {@link ParDo} - * {@link PTransform} are inferred automatically from the type - * parameters of the {@link DoFn} argument passed to {@link ParDo#of}. - * - *

              Output Coders

              - * - *

              By default, the {@link Coder Coder<OutputT>} for the - * elements of the main output {@link PCollection PCollection<OutputT>} is - * inferred from the concrete type of the {@link DoFn DoFn<InputT, OutputT>}. - * - *

              By default, the {@link Coder Coder<SideOutputT>} for the elements of - * a side output {@link PCollection PCollection<SideOutputT>} is inferred - * from the concrete type of the corresponding {@link TupleTag TupleTag<SideOutputT>}. - * To be successful, the {@link TupleTag} should be created as an instance - * of a trivial anonymous subclass, with {@code {}} suffixed to the - * constructor call. Such uses block Java's generic type parameter - * inference, so the {@code } argument must be provided explicitly. - * For example: - *

               {@code
              - * // A TupleTag to use for a side input can be written concisely:
              - * final TupleTag sideInputag = new TupleTag<>();
              - * // A TupleTag to use for a side output should be written with "{}",
              - * // and explicit generic parameter type:
              - * final TupleTag sideOutputTag = new TupleTag(){};
              - * } 
              - * This style of {@code TupleTag} instantiation is used in the example of - * multiple side outputs, above. - * - *

              Serializability of {@link DoFn DoFns}

              - * - *

              A {@link DoFn} passed to a {@link ParDo} transform must be - * {@link Serializable}. This allows the {@link DoFn} instance - * created in this "main program" to be sent (in serialized form) to - * remote worker machines and reconstituted for each bundles of elements - * of the input {@link PCollection} being processed. A {@link DoFn} - * can have instance variable state, and non-transient instance - * variable state will be serialized in the main program and then - * deserialized on remote worker machines for each bundle of elements - * to process. - * - *

              To aid in ensuring that {@link DoFn DoFns} are properly - * {@link Serializable}, even local execution using the - * {@link DirectPipelineRunner} will serialize and then deserialize - * {@link DoFn DoFns} before executing them on a bundle. - * - *

              {@link DoFn DoFns} expressed as anonymous inner classes can be - * convenient, but due to a quirk in Java's rules for serializability, - * non-static inner or nested classes (including anonymous inner - * classes) automatically capture their enclosing class's instance in - * their serialized state. This can lead to including much more than - * intended in the serialized state of a {@link DoFn}, or even things - * that aren't {@link Serializable}. - * - *

              There are two ways to avoid unintended serialized state in a - * {@link DoFn}: - * - *

                - * - *
              • Define the {@link DoFn} as a named, static class. - * - *
              • Define the {@link DoFn} as an anonymous inner class inside of - * a static method. - * - *
              - * - *

              Both of these approaches ensure that there is no implicit enclosing - * instance serialized along with the {@link DoFn} instance. - * - *

              Prior to Java 8, any local variables of the enclosing - * method referenced from within an anonymous inner class need to be - * marked as {@code final}. If defining the {@link DoFn} as a named - * static class, such variables would be passed as explicit - * constructor arguments and stored in explicit instance variables. - * - *

              There are three main ways to initialize the state of a - * {@link DoFn} instance processing a bundle: - * - *

                - * - *
              • Define instance variable state (including implicit instance - * variables holding final variables captured by an anonymous inner - * class), initialized by the {@link DoFn}'s constructor (which is - * implicit for an anonymous inner class). This state will be - * automatically serialized and then deserialized in the {@code DoFn} - * instance created for each bundle. This method is good for state - * known when the original {@code DoFn} is created in the main - * program, if it's not overly large. - * - *
              • Compute the state as a singleton {@link PCollection} and pass it - * in as a side input to the {@link DoFn}. This is good if the state - * needs to be computed by the pipeline, or if the state is very large - * and so is best read from file(s) rather than sent as part of the - * {@code DoFn}'s serialized state. - * - *
              • Initialize the state in each {@link DoFn} instance, in - * {@link DoFn#startBundle}. This is good if the initialization - * doesn't depend on any information known only by the main program or - * computed by earlier pipeline operations, but is the same for all - * instances of this {@link DoFn} for all program executions, say - * setting up empty caches or initializing constant data. - * - *
              - * - *

              No Global Shared State

              - * - *

              {@link ParDo} operations are intended to be able to run in - * parallel across multiple worker machines. This precludes easy - * sharing and updating mutable state across those machines. There is - * no support in the Google Cloud Dataflow system for communicating - * and synchronizing updates to shared state across worker machines, - * so programs should not access any mutable static variable state in - * their {@link DoFn}, without understanding that the Java processes - * for the main program and workers will each have its own independent - * copy of such state, and there won't be any automatic copying of - * that state across Java processes. All information should be - * communicated to {@link DoFn} instances via main and side inputs and - * serialized state, and all output should be communicated from a - * {@link DoFn} instance via main and side outputs, in the absence of - * external communication mechanisms written by user code. - * - *

              Fault Tolerance

              - * - *

              In a distributed system, things can fail: machines can crash, - * machines can be unable to communicate across the network, etc. - * While individual failures are rare, the larger the job, the greater - * the chance that something, somewhere, will fail. The Google Cloud - * Dataflow service strives to mask such failures automatically, - * principally by retrying failed {@link DoFn} bundle. This means - * that a {@code DoFn} instance might process a bundle partially, then - * crash for some reason, then be rerun (often on a different worker - * machine) on that same bundle and on the same elements as before. - * Sometimes two or more {@link DoFn} instances will be running on the - * same bundle simultaneously, with the system taking the results of - * the first instance to complete successfully. Consequently, the - * code in a {@link DoFn} needs to be written such that these - * duplicate (sequential or concurrent) executions do not cause - * problems. If the outputs of a {@link DoFn} are a pure function of - * its inputs, then this requirement is satisfied. However, if a - * {@link DoFn DoFn's} execution has external side-effects, such as performing - * updates to external HTTP services, then the {@link DoFn DoFn's} code - * needs to take care to ensure that those updates are idempotent and - * that concurrent updates are acceptable. This property can be - * difficult to achieve, so it is advisable to strive to keep - * {@link DoFn DoFns} as pure functions as much as possible. - * - *

              Optimization

              - * - *

              The Google Cloud Dataflow service automatically optimizes a - * pipeline before it is executed. A key optimization, fusion, - * relates to {@link ParDo} operations. If one {@link ParDo} operation produces a - * {@link PCollection} that is then consumed as the main input of another - * {@link ParDo} operation, the two {@link ParDo} operations will be fused - * together into a single ParDo operation and run in a single pass; - * this is "producer-consumer fusion". Similarly, if - * two or more ParDo operations have the same {@link PCollection} main input, - * they will be fused into a single {@link ParDo} that makes just one pass - * over the input {@link PCollection}; this is "sibling fusion". - * - *

              If after fusion there are no more unfused references to a - * {@link PCollection} (e.g., one between a producer ParDo and a consumer - * {@link ParDo}), the {@link PCollection} itself is "fused away" and won't ever be - * written to disk, saving all the I/O and space expense of - * constructing it. - * - *

              The Google Cloud Dataflow service applies fusion as much as - * possible, greatly reducing the cost of executing pipelines. As a - * result, it is essentially "free" to write {@link ParDo} operations in a - * very modular, composable style, each {@link ParDo} operation doing one - * clear task, and stringing together sequences of {@link ParDo} operations to - * get the desired overall effect. Such programs can be easier to - * understand, easier to unit-test, easier to extend and evolve, and - * easier to reuse in new programs. The predefined library of - * PTransforms that come with Google Cloud Dataflow makes heavy use of - * this modular, composable style, trusting to the Google Cloud - * Dataflow service's optimizer to "flatten out" all the compositions - * into highly optimized stages. - * - * @see the web - * documentation for ParDo - */ -public class ParDo { - - /** - * Creates a {@link ParDo} {@link PTransform} with the given name. - * - *

              See the discussion of naming above for more explanation. - * - *

              The resulting {@link PTransform} is incomplete, and its - * input/output types are not yet bound. Use - * {@link ParDo.Unbound#of} to specify the {@link DoFn} to - * invoke, which will also bind the input/output types of this - * {@link PTransform}. - */ - public static Unbound named(String name) { - return new Unbound().named(name); - } - - /** - * Creates a {@link ParDo} {@link PTransform} with the given - * side inputs. - * - *

              Side inputs are {@link PCollectionView PCollectionViews}, whose contents are - * computed during pipeline execution and then made accessible to - * {@link DoFn} code via {@link DoFn.ProcessContext#sideInput sideInput}. Each - * invocation of the {@link DoFn} receives the same values for these - * side inputs. - * - *

              See the discussion of Side Inputs above for more explanation. - * - *

              The resulting {@link PTransform} is incomplete, and its - * input/output types are not yet bound. Use - * {@link ParDo.Unbound#of} to specify the {@link DoFn} to - * invoke, which will also bind the input/output types of this - * {@link PTransform}. - */ - public static Unbound withSideInputs(PCollectionView... sideInputs) { - return new Unbound().withSideInputs(sideInputs); - } - - /** - * Creates a {@link ParDo} with the given side inputs. - * - *

              Side inputs are {@link PCollectionView}s, whose contents are - * computed during pipeline execution and then made accessible to - * {@code DoFn} code via {@link DoFn.ProcessContext#sideInput sideInput}. - * - *

              See the discussion of Side Inputs above for more explanation. - * - *

              The resulting {@link PTransform} is incomplete, and its - * input/output types are not yet bound. Use - * {@link ParDo.Unbound#of} to specify the {@link DoFn} to - * invoke, which will also bind the input/output types of this - * {@link PTransform}. - */ - public static Unbound withSideInputs( - Iterable> sideInputs) { - return new Unbound().withSideInputs(sideInputs); - } - - /** - * Creates a multi-output {@link ParDo} {@link PTransform} whose - * output {@link PCollection}s will be referenced using the given main - * output and side output tags. - * - *

              {@link TupleTag TupleTags} are used to name (with its static element - * type {@code T}) each main and side output {@code PCollection}. - * This {@link PTransform PTransform's} {@link DoFn} emits elements to the main - * output {@link PCollection} as normal, using - * {@link DoFn.Context#output}. The {@link DoFn} emits elements to - * a side output {@code PCollection} using - * {@link DoFn.Context#sideOutput}, passing that side output's tag - * as an argument. The result of invoking this {@link PTransform} - * will be a {@link PCollectionTuple}, and any of the the main and - * side output {@code PCollection}s can be retrieved from it via - * {@link PCollectionTuple#get}, passing the output's tag as an - * argument. - * - *

              See the discussion of Side Outputs above for more explanation. - * - *

              The resulting {@link PTransform} is incomplete, and its input - * type is not yet bound. Use {@link ParDo.UnboundMulti#of} - * to specify the {@link DoFn} to invoke, which will also bind the - * input type of this {@link PTransform}. - */ - public static UnboundMulti withOutputTags( - TupleTag mainOutputTag, - TupleTagList sideOutputTags) { - return new Unbound().withOutputTags(mainOutputTag, sideOutputTags); - } - - /** - * Creates a {@link ParDo} {@link PTransform} that will invoke the - * given {@link DoFn} function. - * - *

              The resulting {@link PTransform PTransform's} types have been bound, with the - * input being a {@code PCollection} and the output a - * {@code PCollection}, inferred from the types of the argument - * {@code DoFn}. It is ready to be applied, or further - * properties can be set on it first. - */ - public static Bound of(DoFn fn) { - return of(fn, fn.getClass()); - } - - private static Bound of( - DoFn fn, Class fnClass) { - return new Unbound().of(fn, fnClass); - } - - private static DoFn - adapt(DoFnWithContext fn) { - return DoFnReflector.of(fn.getClass()).toDoFn(fn); - } - - /** - * Creates a {@link ParDo} {@link PTransform} that will invoke the - * given {@link DoFnWithContext} function. - * - *

              The resulting {@link PTransform PTransform's} types have been bound, with the - * input being a {@code PCollection} and the output a - * {@code PCollection}, inferred from the types of the argument - * {@code DoFn}. It is ready to be applied, or further - * properties can be set on it first. - * - *

              {@link DoFnWithContext} is an experimental alternative to - * {@link DoFn} which simplifies accessing the window of the element. - */ - @Experimental - public static Bound of(DoFnWithContext fn) { - return of(adapt(fn), fn.getClass()); - } - - /** - * An incomplete {@link ParDo} transform, with unbound input/output types. - * - *

              Before being applied, {@link ParDo.Unbound#of} must be - * invoked to specify the {@link DoFn} to invoke, which will also - * bind the input/output types of this {@link PTransform}. - */ - public static class Unbound { - private final String name; - private final List> sideInputs; - - Unbound() { - this(null, ImmutableList.>of()); - } - - Unbound(String name, List> sideInputs) { - this.name = name; - this.sideInputs = sideInputs; - } - - /** - * Returns a new {@link ParDo} transform that's like this - * transform but with the specified name. Does not modify this - * transform. The resulting transform is still incomplete. - * - *

              See the discussion of naming above for more explanation. - */ - public Unbound named(String name) { - return new Unbound(name, sideInputs); - } - - /** - * Returns a new {@link ParDo} transform that's like this - * transform but with the specified additional side inputs. - * Does not modify this transform. The resulting transform is - * still incomplete. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public Unbound withSideInputs(PCollectionView... sideInputs) { - return withSideInputs(Arrays.asList(sideInputs)); - } - - /** - * Returns a new {@link ParDo} transform that is like this - * transform but with the specified additional side inputs. Does not modify - * this transform. The resulting transform is still incomplete. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public Unbound withSideInputs( - Iterable> sideInputs) { - ImmutableList.Builder> builder = ImmutableList.builder(); - builder.addAll(this.sideInputs); - builder.addAll(sideInputs); - return new Unbound(name, builder.build()); - } - - /** - * Returns a new multi-output {@link ParDo} transform that's like - * this transform but with the specified main and side output - * tags. Does not modify this transform. The resulting transform - * is still incomplete. - * - *

              See the discussion of Side Outputs above and on - * {@link ParDo#withOutputTags} for more explanation. - */ - public UnboundMulti withOutputTags(TupleTag mainOutputTag, - TupleTagList sideOutputTags) { - return new UnboundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags); - } - - /** - * Returns a new {@link ParDo} {@link PTransform} that's like this - * transform but that will invoke the given {@link DoFn} - * function, and that has its input and output types bound. Does - * not modify this transform. The resulting {@link PTransform} is - * sufficiently specified to be applied, but more properties can - * still be specified. - */ - public Bound of(DoFn fn) { - return of(fn, fn.getClass()); - } - - private Bound of( - DoFn fn, Class fnClass) { - return new Bound<>(name, sideInputs, fn, fnClass); - } - - - /** - * Returns a new {@link ParDo} {@link PTransform} that's like this - * transform but which will invoke the given {@link DoFnWithContext} - * function, and which has its input and output types bound. Does - * not modify this transform. The resulting {@link PTransform} is - * sufficiently specified to be applied, but more properties can - * still be specified. - */ - public Bound of(DoFnWithContext fn) { - return of(adapt(fn), fn.getClass()); - } - } - - /** - * A {@link PTransform} that, when applied to a {@code PCollection}, - * invokes a user-specified {@code DoFn} on all its elements, - * with all its outputs collected into an output - * {@code PCollection}. - * - *

              A multi-output form of this transform can be created with - * {@link ParDo.Bound#withOutputTags}. - * - * @param the type of the (main) input {@link PCollection} elements - * @param the type of the (main) output {@link PCollection} elements - */ - public static class Bound - extends PTransform, PCollection> { - // Inherits name. - private final List> sideInputs; - private final DoFn fn; - private final Class fnClass; - - Bound(String name, - List> sideInputs, - DoFn fn, - Class fnClass) { - super(name); - this.sideInputs = sideInputs; - this.fn = SerializableUtils.clone(fn); - this.fnClass = fnClass; - } - - /** - * Returns a new {@link ParDo} {@link PTransform} that's like this - * {@link PTransform} but with the specified name. Does not - * modify this {@link PTransform}. - * - *

              See the discussion of Naming above for more explanation. - */ - public Bound named(String name) { - return new Bound<>(name, sideInputs, fn, fnClass); - } - - /** - * Returns a new {@link ParDo} {@link PTransform} that's like this - * {@link PTransform} but with the specified additional side inputs. Does not - * modify this {@link PTransform}. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public Bound withSideInputs(PCollectionView... sideInputs) { - return withSideInputs(Arrays.asList(sideInputs)); - } - - /** - * Returns a new {@link ParDo} {@link PTransform} that's like this - * {@link PTransform} but with the specified additional side inputs. Does not - * modify this {@link PTransform}. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public Bound withSideInputs( - Iterable> sideInputs) { - ImmutableList.Builder> builder = ImmutableList.builder(); - builder.addAll(this.sideInputs); - builder.addAll(sideInputs); - return new Bound<>(name, builder.build(), fn, fnClass); - } - - /** - * Returns a new multi-output {@link ParDo} {@link PTransform} - * that's like this {@link PTransform} but with the specified main - * and side output tags. Does not modify this {@link PTransform}. - * - *

              See the discussion of Side Outputs above and on - * {@link ParDo#withOutputTags} for more explanation. - */ - public BoundMulti withOutputTags(TupleTag mainOutputTag, - TupleTagList sideOutputTags) { - return new BoundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags, fn, fnClass); - } - - @Override - public PCollection apply(PCollection input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - input.getWindowingStrategy(), - input.isBounded()) - .setTypeDescriptorInternal(fn.getOutputTypeDescriptor()); - } - - @Override - @SuppressWarnings("unchecked") - protected Coder getDefaultOutputCoder(PCollection input) - throws CannotProvideCoderException { - return input.getPipeline().getCoderRegistry().getDefaultCoder( - fn.getOutputTypeDescriptor(), - fn.getInputTypeDescriptor(), - ((PCollection) input).getCoder()); - } - - @Override - protected String getKindString() { - Class clazz = DoFnReflector.getDoFnClass(fn); - if (clazz.isAnonymousClass()) { - return "AnonymousParDo"; - } else { - return String.format("ParDo(%s)", StringUtils.approximateSimpleName(clazz)); - } - } - - /** - * {@inheritDoc} - * - *

              {@link ParDo} registers its internal {@link DoFn} as a subcomponent for display data. - * {@link DoFn} implementations can register display data by overriding - * {@link DoFn#populateDisplayData}. - */ - @Override - public void populateDisplayData(Builder builder) { - super.populateDisplayData(builder); - ParDo.populateDisplayData(builder, fn, fnClass); - } - - public DoFn getFn() { - return fn; - } - - public List> getSideInputs() { - return sideInputs; - } - } - - /** - * An incomplete multi-output {@link ParDo} transform, with unbound - * input type. - * - *

              Before being applied, {@link ParDo.UnboundMulti#of} must be - * invoked to specify the {@link DoFn} to invoke, which will also - * bind the input type of this {@link PTransform}. - * - * @param the type of the main output {@code PCollection} elements - */ - public static class UnboundMulti { - private final String name; - private final List> sideInputs; - private final TupleTag mainOutputTag; - private final TupleTagList sideOutputTags; - - UnboundMulti(String name, - List> sideInputs, - TupleTag mainOutputTag, - TupleTagList sideOutputTags) { - this.name = name; - this.sideInputs = sideInputs; - this.mainOutputTag = mainOutputTag; - this.sideOutputTags = sideOutputTags; - } - - /** - * Returns a new multi-output {@link ParDo} transform that's like - * this transform but with the specified name. Does not modify - * this transform. The resulting transform is still incomplete. - * - *

              See the discussion of Naming above for more explanation. - */ - public UnboundMulti named(String name) { - return new UnboundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags); - } - - /** - * Returns a new multi-output {@link ParDo} transform that's like - * this transform but with the specified side inputs. Does not - * modify this transform. The resulting transform is still - * incomplete. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public UnboundMulti withSideInputs( - PCollectionView... sideInputs) { - return withSideInputs(Arrays.asList(sideInputs)); - } - - /** - * Returns a new multi-output {@link ParDo} transform that's like - * this transform but with the specified additional side inputs. Does not - * modify this transform. The resulting transform is still - * incomplete. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public UnboundMulti withSideInputs( - Iterable> sideInputs) { - ImmutableList.Builder> builder = ImmutableList.builder(); - builder.addAll(this.sideInputs); - builder.addAll(sideInputs); - return new UnboundMulti<>( - name, builder.build(), - mainOutputTag, sideOutputTags); - } - - /** - * Returns a new multi-output {@link ParDo} {@link PTransform} - * that's like this transform but that will invoke the given - * {@link DoFn} function, and that has its input type bound. - * Does not modify this transform. The resulting - * {@link PTransform} is sufficiently specified to be applied, but - * more properties can still be specified. - */ - public BoundMulti of(DoFn fn) { - return of(fn, fn.getClass()); - } - - public BoundMulti of(DoFn fn, Class fnClass) { - return new BoundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags, fn, fnClass); - } - - /** - * Returns a new multi-output {@link ParDo} {@link PTransform} - * that's like this transform but which will invoke the given - * {@link DoFnWithContext} function, and which has its input type bound. - * Does not modify this transform. The resulting - * {@link PTransform} is sufficiently specified to be applied, but - * more properties can still be specified. - */ - public BoundMulti of(DoFnWithContext fn) { - return of(adapt(fn), fn.getClass()); - } - } - - /** - * A {@link PTransform} that, when applied to a - * {@code PCollection}, invokes a user-specified - * {@code DoFn} on all its elements, which can emit elements - * to any of the {@link PTransform}'s main and side output - * {@code PCollection}s, which are bundled into a result - * {@code PCollectionTuple}. - * - * @param the type of the (main) input {@code PCollection} elements - * @param the type of the main output {@code PCollection} elements - */ - public static class BoundMulti - extends PTransform, PCollectionTuple> { - // Inherits name. - private final List> sideInputs; - private final TupleTag mainOutputTag; - private final TupleTagList sideOutputTags; - private final DoFn fn; - private final Class fnClass; - - BoundMulti(String name, - List> sideInputs, - TupleTag mainOutputTag, - TupleTagList sideOutputTags, - DoFn fn, - Class fnClass) { - super(name); - this.sideInputs = sideInputs; - this.mainOutputTag = mainOutputTag; - this.sideOutputTags = sideOutputTags; - this.fn = SerializableUtils.clone(fn); - this.fnClass = fnClass; - } - - /** - * Returns a new multi-output {@link ParDo} {@link PTransform} - * that's like this {@link PTransform} but with the specified - * name. Does not modify this {@link PTransform}. - * - *

              See the discussion of Naming above for more explanation. - */ - public BoundMulti named(String name) { - return new BoundMulti<>( - name, sideInputs, mainOutputTag, sideOutputTags, fn, fnClass); - } - - /** - * Returns a new multi-output {@link ParDo} {@link PTransform} - * that's like this {@link PTransform} but with the specified additional side - * inputs. Does not modify this {@link PTransform}. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public BoundMulti withSideInputs( - PCollectionView... sideInputs) { - return withSideInputs(Arrays.asList(sideInputs)); - } - - /** - * Returns a new multi-output {@link ParDo} {@link PTransform} - * that's like this {@link PTransform} but with the specified additional side - * inputs. Does not modify this {@link PTransform}. - * - *

              See the discussion of Side Inputs above and on - * {@link ParDo#withSideInputs} for more explanation. - */ - public BoundMulti withSideInputs( - Iterable> sideInputs) { - ImmutableList.Builder> builder = ImmutableList.builder(); - builder.addAll(this.sideInputs); - builder.addAll(sideInputs); - return new BoundMulti<>( - name, builder.build(), - mainOutputTag, sideOutputTags, fn, fnClass); - } - - - @Override - public PCollectionTuple apply(PCollection input) { - PCollectionTuple outputs = PCollectionTuple.ofPrimitiveOutputsInternal( - input.getPipeline(), - TupleTagList.of(mainOutputTag).and(sideOutputTags.getAll()), - input.getWindowingStrategy(), - input.isBounded()); - - // The fn will likely be an instance of an anonymous subclass - // such as DoFn { }, thus will have a high-fidelity - // TypeDescriptor for the output type. - outputs.get(mainOutputTag).setTypeDescriptorInternal(fn.getOutputTypeDescriptor()); - - return outputs; - } - - @Override - protected Coder getDefaultOutputCoder() { - throw new RuntimeException( - "internal error: shouldn't be calling this on a multi-output ParDo"); - } - - @Override - public Coder getDefaultOutputCoder( - PCollection input, TypedPValue output) - throws CannotProvideCoderException { - @SuppressWarnings("unchecked") - Coder inputCoder = ((PCollection) input).getCoder(); - return input.getPipeline().getCoderRegistry().getDefaultCoder( - output.getTypeDescriptor(), - fn.getInputTypeDescriptor(), - inputCoder); - } - - @Override - protected String getKindString() { - Class clazz = DoFnReflector.getDoFnClass(fn); - if (fn.getClass().isAnonymousClass()) { - return "AnonymousParMultiDo"; - } else { - return String.format("ParMultiDo(%s)", StringUtils.approximateSimpleName(clazz)); - } - } - - @Override - public void populateDisplayData(Builder builder) { - super.populateDisplayData(builder); - ParDo.populateDisplayData(builder, fn, fnClass); - } - - public DoFn getFn() { - return fn; - } - - public TupleTag getMainOutputTag() { - return mainOutputTag; - } - - public TupleTagList getSideOutputTags() { - return sideOutputTags; - } - - public List> getSideInputs() { - return sideInputs; - } - } - - ///////////////////////////////////////////////////////////////////////////// - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - Bound.class, - new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - Bound transform, - DirectPipelineRunner.EvaluationContext context) { - evaluateSingleHelper(transform, context); - } - }); - } - - private static void evaluateSingleHelper( - Bound transform, - DirectPipelineRunner.EvaluationContext context) { - TupleTag mainOutputTag = new TupleTag<>("out"); - - DirectModeExecutionContext executionContext = DirectModeExecutionContext.create(); - - PCollectionTuple outputs = PCollectionTuple.of(mainOutputTag, context.getOutput(transform)); - - evaluateHelper( - transform.fn, - context.getStepName(transform), - context.getInput(transform), - transform.sideInputs, - mainOutputTag, - Collections.>emptyList(), - outputs, - context, - executionContext); - - context.setPCollectionValuesWithMetadata( - context.getOutput(transform), - executionContext.getOutput(mainOutputTag)); - } - - ///////////////////////////////////////////////////////////////////////////// - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - BoundMulti.class, - new DirectPipelineRunner.TransformEvaluator() { - @Override - public void evaluate( - BoundMulti transform, - DirectPipelineRunner.EvaluationContext context) { - evaluateMultiHelper(transform, context); - } - }); - } - - private static void evaluateMultiHelper( - BoundMulti transform, - DirectPipelineRunner.EvaluationContext context) { - - DirectModeExecutionContext executionContext = DirectModeExecutionContext.create(); - - evaluateHelper( - transform.fn, - context.getStepName(transform), - context.getInput(transform), - transform.sideInputs, - transform.mainOutputTag, - transform.sideOutputTags.getAll(), - context.getOutput(transform), - context, - executionContext); - - for (Map.Entry, PCollection> entry - : context.getOutput(transform).getAll().entrySet()) { - @SuppressWarnings("unchecked") - TupleTag tag = (TupleTag) entry.getKey(); - @SuppressWarnings("unchecked") - PCollection pc = (PCollection) entry.getValue(); - - context.setPCollectionValuesWithMetadata( - pc, - (tag == transform.mainOutputTag - ? executionContext.getOutput(tag) - : executionContext.getSideOutput(tag))); - } - } - - /** - * Evaluates a single-output or multi-output {@link ParDo} directly. - * - *

              This evaluation method is intended for use in testing scenarios; it is designed for clarity - * and correctness-checking, not speed. - * - *

              Of particular note, this performs best-effort checking that inputs and outputs are not - * mutated in violation of the requirements upon a {@link DoFn}. - */ - private static void evaluateHelper( - DoFn doFn, - String stepName, - PCollection input, - List> sideInputs, - TupleTag mainOutputTag, - List> sideOutputTags, - PCollectionTuple outputs, - DirectPipelineRunner.EvaluationContext context, - DirectModeExecutionContext executionContext) { - // TODO: Run multiple shards? - DoFn fn = context.ensureSerializable(doFn); - - SideInputReader sideInputReader = makeSideInputReader(context, sideInputs); - - // When evaluating via the DirectPipelineRunner, this output manager checks each output for - // illegal mutations when the next output comes along. We then verify again after finishBundle() - // The common case we expect this to catch is a user mutating an input in order to repeatedly - // emit "variations". - ImmutabilityCheckingOutputManager outputManager = - new ImmutabilityCheckingOutputManager<>( - fn.getClass().getSimpleName(), - new DoFnRunnerBase.ListOutputManager(), - outputs); - - DoFnRunner fnRunner = - DoFnRunners.createDefault( - context.getPipelineOptions(), - fn, - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - executionContext.getOrCreateStepContext(stepName, stepName, null), - context.getAddCounterMutator(), - input.getWindowingStrategy()); - - fnRunner.startBundle(); - - for (DirectPipelineRunner.ValueWithMetadata elem - : context.getPCollectionValuesWithMetadata(input)) { - if (elem.getValue() instanceof KV) { - // In case the DoFn needs keyed state, set the implicit keys to the keys - // in the input elements. - @SuppressWarnings("unchecked") - KV kvElem = (KV) elem.getValue(); - executionContext.setKey(kvElem.getKey()); - } else { - executionContext.setKey(elem.getKey()); - } - - // We check the input for mutations only through the call span of processElement. - // This will miss some cases, but the check is ad hoc and best effort. The common case - // is that the input is mutated to be used for output. - try { - MutationDetector inputMutationDetector = MutationDetectors.forValueWithCoder( - elem.getWindowedValue().getValue(), input.getCoder()); - @SuppressWarnings("unchecked") - WindowedValue windowedElem = ((WindowedValue) elem.getWindowedValue()); - fnRunner.processElement(windowedElem); - inputMutationDetector.verifyUnmodified(); - } catch (CoderException e) { - throw UserCodeException.wrap(e); - } catch (IllegalMutationException exn) { - throw new IllegalMutationException( - String.format("DoFn %s mutated input value %s of class %s (new value was %s)." - + " Input values must not be mutated in any way.", - fn.getClass().getSimpleName(), - exn.getSavedValue(), exn.getSavedValue().getClass(), exn.getNewValue()), - exn.getSavedValue(), - exn.getNewValue(), - exn); - } - } - - // Note that the input could have been retained and mutated prior to this final output, - // but for now it degrades readability too much to be worth trying to catch that particular - // corner case. - fnRunner.finishBundle(); - outputManager.verifyLatestOutputsUnmodified(); - } - - private static SideInputReader makeSideInputReader( - DirectPipelineRunner.EvaluationContext context, List> sideInputs) { - PTuple sideInputValues = PTuple.empty(); - for (PCollectionView view : sideInputs) { - sideInputValues = sideInputValues.and( - view.getTagInternal(), - context.getPCollectionView(view)); - } - return DirectSideInputReader.of(sideInputValues); - } - - private static void populateDisplayData( - DisplayData.Builder builder, DoFn fn, Class fnClass) { - builder - .include(fn) - .add(DisplayData.item("fn", fnClass) - .withLabel("Transform Function")); - } - - /** - * A {@code DoFnRunner.OutputManager} that provides facilities for checking output values for - * illegal mutations. - * - *

              When used via the try-with-resources pattern, it is guaranteed that every value passed - * to {@link #output} will have been checked for illegal mutation. - */ - private static class ImmutabilityCheckingOutputManager - implements DoFnRunners.OutputManager, AutoCloseable { - - private final DoFnRunners.OutputManager underlyingOutputManager; - private final ConcurrentMap, MutationDetector> mutationDetectorForTag; - private final PCollectionTuple outputs; - private String doFnName; - - public ImmutabilityCheckingOutputManager( - String doFnName, - DoFnRunners.OutputManager underlyingOutputManager, - PCollectionTuple outputs) { - this.doFnName = doFnName; - this.underlyingOutputManager = underlyingOutputManager; - this.outputs = outputs; - this.mutationDetectorForTag = Maps.newConcurrentMap(); - } - - @Override - public void output(TupleTag tag, WindowedValue output) { - - // Skip verifying undeclared outputs, since we don't have coders for them. - if (outputs.has(tag)) { - try { - MutationDetector newDetector = - MutationDetectors.forValueWithCoder( - output.getValue(), outputs.get(tag).getCoder()); - MutationDetector priorDetector = mutationDetectorForTag.put(tag, newDetector); - verifyOutputUnmodified(priorDetector); - } catch (CoderException e) { - throw UserCodeException.wrap(e); - } - } - - // Actually perform the output. - underlyingOutputManager.output(tag, output); - } - - /** - * Throws {@link IllegalMutationException} if the prior output for any tag has been mutated - * since being output. - */ - public void verifyLatestOutputsUnmodified() { - for (MutationDetector detector : mutationDetectorForTag.values()) { - verifyOutputUnmodified(detector); - } - } - - /** - * Adapts the error message from the provided {@code detector}. - * - *

              The {@code detector} may be null, in which case no check is performed. This is merely - * to consolidate null checking to this method. - */ - private void verifyOutputUnmodified(@Nullable MutationDetector detector) { - if (detector == null) { - return; - } - - try { - detector.verifyUnmodified(); - } catch (IllegalMutationException exn) { - throw new IllegalMutationException(String.format( - "DoFn %s mutated value %s after it was output (new value was %s)." - + " Values must not be mutated in any way after being output.", - doFnName, exn.getSavedValue(), exn.getNewValue()), - exn.getSavedValue(), exn.getNewValue(), - exn); - } - } - - /** - * When used in a {@code try}-with-resources block, verifies all of the latest outputs upon - * {@link #close()}. - */ - @Override - public void close() { - verifyLatestOutputsUnmodified(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java deleted file mode 100644 index 9545bf765c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Partition.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import java.io.Serializable; - -/** - * {@code Partition} takes a {@code PCollection} and a - * {@code PartitionFn}, uses the {@code PartitionFn} to split the - * elements of the input {@code PCollection} into {@code N} partitions, and - * returns a {@code PCollectionList} that bundles {@code N} - * {@code PCollection}s containing the split elements. - * - *

              Example of use: - *

               {@code
              - * PCollection students = ...;
              - * // Split students up into 10 partitions, by percentile:
              - * PCollectionList studentsByPercentile =
              - *     students.apply(Partition.of(10, new PartitionFn() {
              - *         public int partitionFor(Student student, int numPartitions) {
              - *             return student.getPercentile()  // 0..99
              - *                  * numPartitions / 100;
              - *         }}))
              - * for (int i = 0; i < 10; i++) {
              - *   PCollection partition = studentsByPercentile.get(i);
              - *   ...
              - * }
              - * } 
              - * - *

              By default, the {@code Coder} of each of the - * {@code PCollection}s in the output {@code PCollectionList} is the - * same as the {@code Coder} of the input {@code PCollection}. - * - *

              Each output element has the same timestamp and is in the same windows - * as its corresponding input element, and each output {@code PCollection} - * has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - * @param the type of the elements of the input and output - * {@code PCollection}s - */ -public class Partition extends PTransform, PCollectionList> { - - /** - * A function object that chooses an output partition for an element. - * - * @param the type of the elements being partitioned - */ - public interface PartitionFn extends Serializable { - /** - * Chooses the partition into which to put the given element. - * - * @param elem the element to be partitioned - * @param numPartitions the total number of partitions ({@code >= 1}) - * @return index of the selected partition (in the range - * {@code [0..numPartitions-1]}) - */ - int partitionFor(T elem, int numPartitions); - } - - /** - * Returns a new {@code Partition} {@code PTransform} that divides - * its input {@code PCollection} into the given number of partitions, - * using the given partitioning function. - * - * @param numPartitions the number of partitions to divide the input - * {@code PCollection} into - * @param partitionFn the function to invoke on each element to - * choose its output partition - * @throws IllegalArgumentException if {@code numPartitions <= 0} - */ - public static Partition of( - int numPartitions, PartitionFn partitionFn) { - return new Partition<>(new PartitionDoFn(numPartitions, partitionFn)); - } - - ///////////////////////////////////////////////////////////////////////////// - - @Override - public PCollectionList apply(PCollection in) { - final TupleTagList outputTags = partitionDoFn.getOutputTags(); - - PCollectionTuple outputs = in.apply( - ParDo - .withOutputTags(new TupleTag(){}, outputTags) - .of(partitionDoFn)); - - PCollectionList pcs = PCollectionList.empty(in.getPipeline()); - Coder coder = in.getCoder(); - - for (TupleTag outputTag : outputTags.getAll()) { - // All the tuple tags are actually TupleTag - // And all the collections are actually PCollection - @SuppressWarnings("unchecked") - TupleTag typedOutputTag = (TupleTag) outputTag; - pcs = pcs.and(outputs.get(typedOutputTag).setCoder(coder)); - } - return pcs; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.include(partitionDoFn); - } - - private final transient PartitionDoFn partitionDoFn; - - private Partition(PartitionDoFn partitionDoFn) { - this.partitionDoFn = partitionDoFn; - } - - private static class PartitionDoFn extends DoFn { - private final int numPartitions; - private final PartitionFn partitionFn; - private final TupleTagList outputTags; - - /** - * Constructs a PartitionDoFn. - * - * @throws IllegalArgumentException if {@code numPartitions <= 0} - */ - public PartitionDoFn(int numPartitions, PartitionFn partitionFn) { - if (numPartitions <= 0) { - throw new IllegalArgumentException("numPartitions must be > 0"); - } - - this.numPartitions = numPartitions; - this.partitionFn = partitionFn; - - TupleTagList buildOutputTags = TupleTagList.empty(); - for (int partition = 0; partition < numPartitions; partition++) { - buildOutputTags = buildOutputTags.and(new TupleTag()); - } - outputTags = buildOutputTags; - } - - public TupleTagList getOutputTags() { - return outputTags; - } - - @Override - public void processElement(ProcessContext c) { - X input = c.element(); - int partition = partitionFn.partitionFor(input, numPartitions); - if (0 <= partition && partition < numPartitions) { - @SuppressWarnings("unchecked") - TupleTag typedTag = (TupleTag) outputTags.get(partition); - c.sideOutput(typedTag, input); - } else { - throw new IndexOutOfBoundsException( - "Partition function returned out of bounds index: " - + partition + " not in [0.." + numPartitions + ")"); - } - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("numPartitions", numPartitions) - .withLabel("Partition Count")) - .add(DisplayData.item("partitionFn", partitionFn.getClass()) - .withLabel("Partition Function")); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java deleted file mode 100644 index 4388c2d5b8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicates.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -/** - * {@code RemoveDuplicates} takes a {@code PCollection} and - * returns a {@code PCollection} that has all the elements of the - * input but with duplicate elements removed such that each element is - * unique within each window. - * - *

              Two values of type {@code T} are compared for equality not by - * regular Java {@link Object#equals}, but instead by first encoding - * each of the elements using the {@code PCollection}'s {@code Coder}, and then - * comparing the encoded bytes. This admits efficient parallel - * evaluation. - * - *

              Optionally, a function may be provided that maps each element to a representative - * value. In this case, two elements will be considered duplicates if they have equal - * representative values, with equality being determined as above. - * - *

              By default, the {@code Coder} of the output {@code PCollection} - * is the same as the {@code Coder} of the input {@code PCollection}. - * - *

              Each output element is in the same window as its corresponding input - * element, and has the timestamp of the end of that window. The output - * {@code PCollection} has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * as the input. - * - *

              Does not preserve any order the input PCollection might have had. - * - *

              Example of use: - *

               {@code
              - * PCollection words = ...;
              - * PCollection uniqueWords =
              - *     words.apply(RemoveDuplicates.create());
              - * } 
              - * - * @param the type of the elements of the input and output - * {@code PCollection}s - */ -public class RemoveDuplicates extends PTransform, - PCollection> { - /** - * Returns a {@code RemoveDuplicates} {@code PTransform}. - * - * @param the type of the elements of the input and output - * {@code PCollection}s - */ - public static RemoveDuplicates create() { - return new RemoveDuplicates(); - } - - /** - * Returns a {@code RemoveDuplicates} {@code PTransform}. - * - * @param the type of the elements of the input and output - * {@code PCollection}s - * @param the type of the representative value used to dedup - */ - public static WithRepresentativeValues withRepresentativeValueFn( - SerializableFunction fn) { - return new WithRepresentativeValues(fn, null); - } - - @Override - public PCollection apply(PCollection in) { - return in - .apply(ParDo.named("CreateIndex") - .of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), (Void) null)); - } - })) - .apply(Combine.perKey( - new SerializableFunction, Void>() { - @Override - public Void apply(Iterable iter) { - return null; // ignore input - } - })) - .apply(Keys.create()); - } - - /** - * A {@link RemoveDuplicates} {@link PTransform} that uses a {@link SerializableFunction} to - * obtain a representative value for each input element. - * - *

              Construct via {@link RemoveDuplicates#withRepresentativeValueFn(SerializableFunction)}. - * - * @param the type of input and output element - * @param the type of representative values used to dedup - */ - public static class WithRepresentativeValues - extends PTransform, PCollection> { - private final SerializableFunction fn; - private final TypeDescriptor representativeType; - - private WithRepresentativeValues( - SerializableFunction fn, TypeDescriptor representativeType) { - this.fn = fn; - this.representativeType = representativeType; - } - - @Override - public PCollection apply(PCollection in) { - WithKeys withKeys = WithKeys.of(fn); - if (representativeType != null) { - withKeys = withKeys.withKeyType(representativeType); - } - return in - .apply(withKeys) - .apply(Combine.perKey( - new Combine.BinaryCombineFn() { - @Override - public T apply(T left, T right) { - return left; - } - })) - .apply(Values.create()); - } - - /** - * Return a {@code WithRepresentativeValues} {@link PTransform} that is like this one, but with - * the specified output type descriptor. - * - *

              Required for use of - * {@link RemoveDuplicates#withRepresentativeValueFn(SerializableFunction)} in Java 8 with a - * lambda as the fn. - * - * @param type a {@link TypeDescriptor} describing the representative type of this - * {@code WithRepresentativeValues} - * @return A {@code WithRepresentativeValues} {@link PTransform} that is like this one, but with - * the specified output type descriptor. - */ - public WithRepresentativeValues withRepresentativeType(TypeDescriptor type) { - return new WithRepresentativeValues<>(fn, type); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java deleted file mode 100644 index 2730a05a07..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * {@code PTransform}s for taking samples of the elements in a - * {@code PCollection}, or samples of the values associated with each - * key in a {@code PCollection} of {@code KV}s. - **/ -public class Sample { - - /** - * {@code Sample#any(long)} takes a {@code PCollection} and a limit, and - * produces a new {@code PCollection} containing up to limit - * elements of the input {@code PCollection}. - * - *

              If limit is less than or equal to the size of the input - * {@code PCollection}, then all the input's elements will be selected. - * - *

              All of the elements of the output {@code PCollection} should fit into - * main memory of a single worker machine. This operation does not - * run in parallel. - * - *

              Example of use: - *

               {@code
              -   * PCollection input = ...;
              -   * PCollection output = input.apply(Sample.any(100));
              -   * } 
              - * - * @param the type of the elements of the input and output - * {@code PCollection}s - * @param limit the number of elements to take from the input - */ - public static PTransform, PCollection> any(long limit) { - return new SampleAny<>(limit); - } - - /** - * Returns a {@code PTransform} that takes a {@code PCollection}, - * selects {@code sampleSize} elements, uniformly at random, and returns a - * {@code PCollection>} containing the selected elements. - * If the input {@code PCollection} has fewer than - * {@code sampleSize} elements, then the output {@code Iterable} - * will be all the input's elements. - * - *

              Example of use: - *

               {@code
              -   * PCollection pc = ...;
              -   * PCollection> sampleOfSize10 =
              -   *     pc.apply(Sample.fixedSizeGlobally(10));
              -   * } 
              - * - * @param sampleSize the number of elements to select; must be {@code >= 0} - * @param the type of the elements - */ - public static PTransform, PCollection>> - fixedSizeGlobally(int sampleSize) { - return Combine.globally(new FixedSizedSampleFn(sampleSize)); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to a sample of {@code sampleSize} values - * associated with that key in the input {@code PCollection}, taken - * uniformly at random. If a key in the input {@code PCollection} - * has fewer than {@code sampleSize} values associated with it, then - * the output {@code Iterable} associated with that key will be - * all the values associated with that key in the input - * {@code PCollection}. - * - *

              Example of use: - *

               {@code
              -   * PCollection> pc = ...;
              -   * PCollection>> sampleOfSize10PerKey =
              -   *     pc.apply(Sample.fixedSizePerKey());
              -   * } 
              - * - * @param sampleSize the number of values to select for each - * distinct key; must be {@code >= 0} - * @param the type of the keys - * @param the type of the values - */ - public static PTransform>, - PCollection>>> - fixedSizePerKey(int sampleSize) { - return Combine.perKey(new FixedSizedSampleFn(sampleSize)); - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@link PTransform} that takes a {@code PCollection} and a limit, and - * produces a new {@code PCollection} containing up to limit - * elements of the input {@code PCollection}. - */ - public static class SampleAny extends PTransform, PCollection> { - private final long limit; - - /** - * Constructs a {@code SampleAny} PTransform that, when applied, - * produces a new PCollection containing up to {@code limit} - * elements of its input {@code PCollection}. - */ - private SampleAny(long limit) { - checkArgument(limit >= 0, "Expected non-negative limit, received %s.", limit); - this.limit = limit; - } - - @Override - public PCollection apply(PCollection in) { - PCollectionView> iterableView = in.apply(View.asIterable()); - return - in.getPipeline() - .apply(Create.of((Void) null).withCoder(VoidCoder.of())) - .apply(ParDo - .withSideInputs(iterableView) - .of(new SampleAnyDoFn<>(limit, iterableView))) - .setCoder(in.getCoder()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("sampleSize", limit) - .withLabel("Sample Size")); - } - } - - /** - * A {@link DoFn} that returns up to limit elements from the side input PCollection. - */ - private static class SampleAnyDoFn extends DoFn { - long limit; - final PCollectionView> iterableView; - - public SampleAnyDoFn(long limit, PCollectionView> iterableView) { - this.limit = limit; - this.iterableView = iterableView; - } - - @Override - public void processElement(ProcessContext c) { - for (T i : c.sideInput(iterableView)) { - if (limit-- <= 0) { - break; - } - c.output(i); - } - } - } - - /** - * {@code CombineFn} that computes a fixed-size sample of a - * collection of values. - * - * @param the type of the elements - */ - public static class FixedSizedSampleFn - extends CombineFn, SerializableComparator>>, - Iterable> { - private final int sampleSize; - private final Top.TopCombineFn, SerializableComparator>> - topCombineFn; - private final Random rand = new Random(); - - private FixedSizedSampleFn(int sampleSize) { - if (sampleSize < 0) { - throw new IllegalArgumentException("sample size must be >= 0"); - } - - this.sampleSize = sampleSize; - topCombineFn = new Top.TopCombineFn, SerializableComparator>>( - sampleSize, new KV.OrderByKey()); - } - - @Override - public Top.BoundedHeap, SerializableComparator>> - createAccumulator() { - return topCombineFn.createAccumulator(); - } - - @Override - public Top.BoundedHeap, SerializableComparator>> addInput( - Top.BoundedHeap, SerializableComparator>> accumulator, - T input) { - accumulator.addInput(KV.of(rand.nextInt(), input)); - return accumulator; - } - - @Override - public Top.BoundedHeap, SerializableComparator>> - mergeAccumulators( - Iterable, SerializableComparator>>> - accumulators) { - return topCombineFn.mergeAccumulators(accumulators); - } - - @Override - public Iterable extractOutput( - Top.BoundedHeap, SerializableComparator>> accumulator) { - List out = new ArrayList<>(); - for (KV element : accumulator.extractOutput()) { - out.add(element.getValue()); - } - return out; - } - - @Override - public Coder, SerializableComparator>>> - getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) { - return topCombineFn.getAccumulatorCoder( - registry, KvCoder.of(BigEndianIntegerCoder.of(), inputCoder)); - } - - @Override - public Coder> getDefaultOutputCoder( - CoderRegistry registry, Coder inputCoder) { - return IterableCoder.of(inputCoder); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("sampleSize", sampleSize) - .withLabel("Sample Size")); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableComparator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableComparator.java deleted file mode 100644 index 7d41917a94..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableComparator.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * A {@code Comparator} that is also {@code Serializable}. - * - * @param type of values being compared - */ -public interface SerializableComparator extends Comparator, Serializable { -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableFunction.java deleted file mode 100644 index 2c35f52b55..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SerializableFunction.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import java.io.Serializable; - -/** - * A function that computes an output value of type {@code OutputT} from an input value of type - * {@code InputT} and is {@link Serializable}. - * - * @param input value type - * @param output value type - */ -public interface SerializableFunction extends Serializable { - /** Returns the result of invoking this function on the given input. */ - OutputT apply(InputT input); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java deleted file mode 100644 index ef6fd81a23..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/SimpleFunction.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -/** - * A {@link SerializableFunction} which is not a functional interface. - * Concrete subclasses allow us to infer type information, which in turn aids - * {@link Coder} inference. - */ -public abstract class SimpleFunction - implements SerializableFunction { - - /** - * Returns a {@link TypeDescriptor} capturing what is known statically - * about the input type of this {@code DoFn} instance's most-derived - * class. - * - *

              See {@link #getOutputTypeDescriptor} for more discussion. - */ - public TypeDescriptor getInputTypeDescriptor() { - return new TypeDescriptor(this) {}; - } - - /** - * Returns a {@link TypeDescriptor} capturing what is known statically - * about the output type of this {@code DoFn} instance's - * most-derived class. - * - *

              In the normal case of a concrete {@code DoFn} subclass with - * no generic type parameters of its own (including anonymous inner - * classes), this will be a complete non-generic type, which is good - * for choosing a default output {@code Coder} for the output - * {@code PCollection}. - */ - public TypeDescriptor getOutputTypeDescriptor() { - return new TypeDescriptor(this) {}; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sum.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sum.java deleted file mode 100644 index 5b30475a9d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sum.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; -import com.google.cloud.dataflow.sdk.util.common.CounterProvider; - -/** - * {@code PTransform}s for computing the sum of the elements in a - * {@code PCollection}, or the sum of the values associated with - * each key in a {@code PCollection} of {@code KV}s. - * - *

              Example 1: get the sum of a {@code PCollection} of {@code Double}s. - *

               {@code
              - * PCollection input = ...;
              - * PCollection sum = input.apply(Sum.doublesGlobally());
              - * } 
              - * - *

              Example 2: calculate the sum of the {@code Integer}s - * associated with each unique key (which is of type {@code String}). - *

               {@code
              - * PCollection> input = ...;
              - * PCollection> sumPerKey = input
              - *     .apply(Sum.integersPerKey());
              - * } 
              - */ -public class Sum { - - private Sum() { - // do not instantiate - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a - * {@code PCollection} whose contents is the sum of the - * input {@code PCollection}'s elements, or - * {@code 0} if there are no elements. - */ - public static Combine.Globally integersGlobally() { - return Combine.globally(new SumIntegerFn()).named("Sum.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to the sum of the values associated with - * that key in the input {@code PCollection}. - */ - public static Combine.PerKey integersPerKey() { - return Combine.perKey(new SumIntegerFn()).named("Sum.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a - * {@code PCollection} whose contents is the sum of the - * input {@code PCollection}'s elements, or - * {@code 0} if there are no elements. - */ - public static Combine.Globally longsGlobally() { - return Combine.globally(new SumLongFn()).named("Sum.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to the sum of the values associated with - * that key in the input {@code PCollection}. - */ - public static Combine.PerKey longsPerKey() { - return Combine.perKey(new SumLongFn()).named("Sum.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a - * {@code PCollection} whose contents is the sum of the - * input {@code PCollection}'s elements, or - * {@code 0} if there are no elements. - */ - public static Combine.Globally doublesGlobally() { - return Combine.globally(new SumDoubleFn()).named("Sum.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to the sum of the values associated with - * that key in the input {@code PCollection}. - */ - public static Combine.PerKey doublesPerKey() { - return Combine.perKey(new SumDoubleFn()).named("Sum.PerKey"); - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@code SerializableFunction} that computes the sum of an - * {@code Iterable} of {@code Integer}s, useful as an argument to - * {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class SumIntegerFn - extends Combine.BinaryCombineIntegerFn implements CounterProvider { - @Override - public int apply(int a, int b) { - return a + b; - } - - @Override - public int identity() { - return 0; - } - - @Override - public Counter getCounter(String name) { - return Counter.ints(name, AggregationKind.SUM); - } - } - - /** - * A {@code SerializableFunction} that computes the sum of an - * {@code Iterable} of {@code Long}s, useful as an argument to - * {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class SumLongFn - extends Combine.BinaryCombineLongFn implements CounterProvider { - @Override - public long apply(long a, long b) { - return a + b; - } - - @Override - public long identity() { - return 0; - } - - @Override - public Counter getCounter(String name) { - return Counter.longs(name, AggregationKind.SUM); - } - } - - /** - * A {@code SerializableFunction} that computes the sum of an - * {@code Iterable} of {@code Double}s, useful as an argument to - * {@link Combine#globally} or {@link Combine#perKey}. - */ - public static class SumDoubleFn - extends Combine.BinaryCombineDoubleFn implements CounterProvider { - @Override - public double apply(double a, double b) { - return a + b; - } - - @Override - public double identity() { - return 0; - } - - @Override - public Counter getCounter(String name) { - return Counter.doubles(name, AggregationKind.SUM); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java deleted file mode 100644 index 5bec8b9451..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Top.java +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.CustomCoder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.AccumulatingCombineFn.Accumulator; -import com.google.cloud.dataflow.sdk.transforms.Combine.PerKey; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.PriorityQueue; - -/** - * {@code PTransform}s for finding the largest (or smallest) set - * of elements in a {@code PCollection}, or the largest (or smallest) - * set of values associated with each key in a {@code PCollection} of - * {@code KV}s. - */ -public class Top { - - private Top() { - // do not instantiate - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a {@code PCollection>} with a - * single element containing the largest {@code count} elements of the input - * {@code PCollection}, in decreasing order, sorted using the - * given {@code Comparator}. The {@code Comparator} must also - * be {@code Serializable}. - * - *

              If {@code count} {@code <} the number of elements in the - * input {@code PCollection}, then all the elements of the input - * {@code PCollection} will be in the resulting - * {@code List}, albeit in sorted order. - * - *

              All the elements of the result's {@code List} - * must fit into the memory of a single machine. - * - *

              Example of use: - *

               {@code
              -   * PCollection students = ...;
              -   * PCollection> top10Students =
              -   *     students.apply(Top.of(10, new CompareStudentsByAvgGrade()));
              -   * } 
              - * - *

              By default, the {@code Coder} of the output {@code PCollection} - * is a {@code ListCoder} of the {@code Coder} of the elements of - * the input {@code PCollection}. - * - *

              If the input {@code PCollection} is windowed into {@link GlobalWindows}, - * an empty {@code List} in the {@link GlobalWindow} will be output if the input - * {@code PCollection} is empty. To use this with inputs with other windowing, - * either {@link Combine.Globally#withoutDefaults withoutDefaults} or - * {@link Combine.Globally#asSingletonView asSingletonView} must be called. - * - *

              See also {@link #smallest} and {@link #largest}, which sort - * {@code Comparable} elements using their natural ordering. - * - *

              See also {@link #perKey}, {@link #smallestPerKey}, and - * {@link #largestPerKey}, which take a {@code PCollection} of - * {@code KV}s and return the top values associated with each key. - */ - public static & Serializable> - Combine.Globally> of(int count, ComparatorT compareFn) { - return Combine.globally(new TopCombineFn<>(count, compareFn)).named("Top.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a {@code PCollection>} with a - * single element containing the smallest {@code count} elements of the input - * {@code PCollection}, in increasing order, sorted according to - * their natural order. - * - *

              If {@code count} {@code <} the number of elements in the - * input {@code PCollection}, then all the elements of the input - * {@code PCollection} will be in the resulting {@code PCollection}'s - * {@code List}, albeit in sorted order. - * - *

              All the elements of the result {@code List} - * must fit into the memory of a single machine. - * - *

              Example of use: - *

               {@code
              -   * PCollection values = ...;
              -   * PCollection> smallest10Values = values.apply(Top.smallest(10));
              -   * } 
              - * - *

              By default, the {@code Coder} of the output {@code PCollection} - * is a {@code ListCoder} of the {@code Coder} of the elements of - * the input {@code PCollection}. - * - *

              If the input {@code PCollection} is windowed into {@link GlobalWindows}, - * an empty {@code List} in the {@link GlobalWindow} will be output if the input - * {@code PCollection} is empty. To use this with inputs with other windowing, - * either {@link Combine.Globally#withoutDefaults withoutDefaults} or - * {@link Combine.Globally#asSingletonView asSingletonView} must be called. - * - *

              See also {@link #largest}. - * - *

              See also {@link #of}, which sorts using a user-specified - * {@code Comparator} function. - * - *

              See also {@link #perKey}, {@link #smallestPerKey}, and - * {@link #largestPerKey}, which take a {@code PCollection} of - * {@code KV}s and return the top values associated with each key. - */ - public static > Combine.Globally> smallest(int count) { - return Combine.globally(new TopCombineFn<>(count, new Smallest())) - .named("Smallest.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection} and returns a {@code PCollection>} with a - * single element containing the largest {@code count} elements of the input - * {@code PCollection}, in decreasing order, sorted according to - * their natural order. - * - *

              If {@code count} {@code <} the number of elements in the - * input {@code PCollection}, then all the elements of the input - * {@code PCollection} will be in the resulting {@code PCollection}'s - * {@code List}, albeit in sorted order. - * - *

              All the elements of the result's {@code List} - * must fit into the memory of a single machine. - * - *

              Example of use: - *

               {@code
              -   * PCollection values = ...;
              -   * PCollection> largest10Values = values.apply(Top.largest(10));
              -   * } 
              - * - *

              By default, the {@code Coder} of the output {@code PCollection} - * is a {@code ListCoder} of the {@code Coder} of the elements of - * the input {@code PCollection}. - * - *

              If the input {@code PCollection} is windowed into {@link GlobalWindows}, - * an empty {@code List} in the {@link GlobalWindow} will be output if the input - * {@code PCollection} is empty. To use this with inputs with other windowing, - * either {@link Combine.Globally#withoutDefaults withoutDefaults} or - * {@link Combine.Globally#asSingletonView asSingletonView} must be called. - * - *

              See also {@link #smallest}. - * - *

              See also {@link #of}, which sorts using a user-specified - * {@code Comparator} function. - * - *

              See also {@link #perKey}, {@link #smallestPerKey}, and - * {@link #largestPerKey}, which take a {@code PCollection} of - * {@code KV}s and return the top values associated with each key. - */ - public static > Combine.Globally> largest(int count) { - return Combine.globally(new TopCombineFn<>(count, new Largest())).named("Largest.Globally"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to the largest {@code count} values - * associated with that key in the input - * {@code PCollection>}, in decreasing order, sorted using - * the given {@code Comparator}. The - * {@code Comparator} must also be {@code Serializable}. - * - *

              If there are fewer than {@code count} values associated with - * a particular key, then all those values will be in the result - * mapping for that key, albeit in sorted order. - * - *

              All the values associated with a single key must fit into the - * memory of a single machine, but there can be many more - * {@code KV}s in the resulting {@code PCollection} than can fit - * into the memory of a single machine. - * - *

              Example of use: - *

               {@code
              -   * PCollection> studentsBySchool = ...;
              -   * PCollection>> top10StudentsBySchool =
              -   *     studentsBySchool.apply(
              -   *         Top.perKey(10, new CompareStudentsByAvgGrade()));
              -   * } 
              - * - *

              By default, the {@code Coder} of the keys of the output - * {@code PCollection} is the same as that of the keys of the input - * {@code PCollection}, and the {@code Coder} of the values of the - * output {@code PCollection} is a {@code ListCoder} of the - * {@code Coder} of the values of the input {@code PCollection}. - * - *

              See also {@link #smallestPerKey} and {@link #largestPerKey}, which - * sort {@code Comparable} values using their natural - * ordering. - * - *

              See also {@link #of}, {@link #smallest}, and {@link #largest}, which - * take a {@code PCollection} and return the top elements. - */ - public static & Serializable> - PTransform>, PCollection>>> - perKey(int count, ComparatorT compareFn) { - return Combine.perKey( - new TopCombineFn<>(count, compareFn).asKeyedFn()).named("Top.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to the smallest {@code count} values - * associated with that key in the input - * {@code PCollection>}, in increasing order, sorted - * according to their natural order. - * - *

              If there are fewer than {@code count} values associated with - * a particular key, then all those values will be in the result - * mapping for that key, albeit in sorted order. - * - *

              All the values associated with a single key must fit into the - * memory of a single machine, but there can be many more - * {@code KV}s in the resulting {@code PCollection} than can fit - * into the memory of a single machine. - * - *

              Example of use: - *

               {@code
              -   * PCollection> keyedValues = ...;
              -   * PCollection>> smallest10ValuesPerKey =
              -   *     keyedValues.apply(Top.smallestPerKey(10));
              -   * } 
              - * - *

              By default, the {@code Coder} of the keys of the output - * {@code PCollection} is the same as that of the keys of the input - * {@code PCollection}, and the {@code Coder} of the values of the - * output {@code PCollection} is a {@code ListCoder} of the - * {@code Coder} of the values of the input {@code PCollection}. - * - *

              See also {@link #largestPerKey}. - * - *

              See also {@link #perKey}, which sorts values using a user-specified - * {@code Comparator} function. - * - *

              See also {@link #of}, {@link #smallest}, and {@link #largest}, which - * take a {@code PCollection} and return the top elements. - */ - public static > - PTransform>, PCollection>>> - smallestPerKey(int count) { - return Combine.perKey(new TopCombineFn<>(count, new Smallest()).asKeyedFn()) - .named("Smallest.PerKey"); - } - - /** - * Returns a {@code PTransform} that takes an input - * {@code PCollection>} and returns a - * {@code PCollection>>} that contains an output - * element mapping each distinct key in the input - * {@code PCollection} to the largest {@code count} values - * associated with that key in the input - * {@code PCollection>}, in decreasing order, sorted - * according to their natural order. - * - *

              If there are fewer than {@code count} values associated with - * a particular key, then all those values will be in the result - * mapping for that key, albeit in sorted order. - * - *

              All the values associated with a single key must fit into the - * memory of a single machine, but there can be many more - * {@code KV}s in the resulting {@code PCollection} than can fit - * into the memory of a single machine. - * - *

              Example of use: - *

               {@code
              -   * PCollection> keyedValues = ...;
              -   * PCollection>> largest10ValuesPerKey =
              -   *     keyedValues.apply(Top.largestPerKey(10));
              -   * } 
              - * - *

              By default, the {@code Coder} of the keys of the output - * {@code PCollection} is the same as that of the keys of the input - * {@code PCollection}, and the {@code Coder} of the values of the - * output {@code PCollection} is a {@code ListCoder} of the - * {@code Coder} of the values of the input {@code PCollection}. - * - *

              See also {@link #smallestPerKey}. - * - *

              See also {@link #perKey}, which sorts values using a user-specified - * {@code Comparator} function. - * - *

              See also {@link #of}, {@link #smallest}, and {@link #largest}, which - * take a {@code PCollection} and return the top elements. - */ - public static > - PerKey> - largestPerKey(int count) { - return Combine.perKey( -new TopCombineFn<>(count, new Largest()).asKeyedFn()) - .named("Largest.PerKey"); - } - - /** - * A {@code Serializable} {@code Comparator} that that uses the compared elements' natural - * ordering. - */ - public static class Largest> - implements Comparator, Serializable { - @Override - public int compare(T a, T b) { - return a.compareTo(b); - } - } - - /** - * {@code Serializable} {@code Comparator} that that uses the reverse of the compared elements' - * natural ordering. - */ - public static class Smallest> - implements Comparator, Serializable { - @Override - public int compare(T a, T b) { - return b.compareTo(a); - } - } - - - //////////////////////////////////////////////////////////////////////////// - - /** - * {@code CombineFn} for {@code Top} transforms that combines a - * bunch of {@code T}s into a single {@code count}-long - * {@code List}, using {@code compareFn} to choose the largest - * {@code T}s. - * - * @param type of element being compared - */ - public static class TopCombineFn & Serializable> - extends AccumulatingCombineFn, List> { - - private final int count; - private final ComparatorT compareFn; - - public TopCombineFn(int count, ComparatorT compareFn) { - checkArgument(count >= 0, "count must be >= 0"); - this.count = count; - this.compareFn = compareFn; - } - - @Override - public BoundedHeap createAccumulator() { - return new BoundedHeap<>(count, compareFn, new ArrayList()); - } - - @Override - public Coder> getAccumulatorCoder( - CoderRegistry registry, Coder inputCoder) { - return new BoundedHeapCoder<>(count, compareFn, inputCoder); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("count", count) - .withLabel("Top Count")) - .add(DisplayData.item("comparer", compareFn.getClass()) - .withLabel("Record Comparer")); - } - - @Override - public String getIncompatibleGlobalWindowErrorMessage() { - return "Default values are not supported in Top.[of, smallest, largest]() if the output " - + "PCollection is not windowed by GlobalWindows. Instead, use " - + "Top.[of, smallest, largest]().withoutDefaults() to output an empty PCollection if the" - + " input PCollection is empty, or Top.[of, smallest, largest]().asSingletonView() to " - + "get a PCollection containing the empty list if the input PCollection is empty."; - } - } - - /** - * A heap that stores only a finite number of top elements according to its provided - * {@code Comparator}. Implemented as an {@link Accumulator} to facilitate implementation of - * {@link Top}. - * - *

              This class is not safe for multithreaded use, except read-only. - */ - static class BoundedHeap & Serializable> - implements Accumulator, List> { - - /** - * A queue with smallest at the head, for quick adds. - * - *

              Only one of asList and asQueue may be non-null. - */ - private PriorityQueue asQueue; - - /** - * A list in with largest first, the form of extractOutput(). - * - *

              Only one of asList and asQueue may be non-null. - */ - private List asList; - - /** The user-provided Comparator. */ - private final ComparatorT compareFn; - - /** The maximum size of the heap. */ - private final int maximumSize; - - /** - * Creates a new heap with the provided size, comparator, and initial elements. - */ - private BoundedHeap(int maximumSize, ComparatorT compareFn, List asList) { - this.maximumSize = maximumSize; - this.asList = asList; - this.compareFn = compareFn; - } - - @Override - public void addInput(T value) { - maybeAddInput(value); - } - - /** - * Adds {@code value} to this heap if it is larger than any of the current elements. - * Returns {@code true} if {@code value} was added. - */ - private boolean maybeAddInput(T value) { - if (maximumSize == 0) { - // Don't add anything. - return false; - } - - // If asQueue == null, then this is the first add after the latest call to the - // constructor or asList(). - if (asQueue == null) { - asQueue = new PriorityQueue<>(maximumSize, compareFn); - for (T item : asList) { - asQueue.add(item); - } - asList = null; - } - - if (asQueue.size() < maximumSize) { - asQueue.add(value); - return true; - } else if (compareFn.compare(value, asQueue.peek()) > 0) { - asQueue.poll(); - asQueue.add(value); - return true; - } else { - return false; - } - } - - @Override - public void mergeAccumulator(BoundedHeap accumulator) { - for (T value : accumulator.asList()) { - if (!maybeAddInput(value)) { - // If this element of accumulator does not make the top N, neither - // will the rest, which are all smaller. - break; - } - } - } - - @Override - public List extractOutput() { - return asList(); - } - - /** - * Returns the contents of this Heap as a List sorted largest-to-smallest. - */ - private List asList() { - if (asList == null) { - List smallestFirstList = Lists.newArrayListWithCapacity(asQueue.size()); - while (!asQueue.isEmpty()) { - smallestFirstList.add(asQueue.poll()); - } - asList = Lists.reverse(smallestFirstList); - asQueue = null; - } - return asList; - } - } - - /** - * A {@link Coder} for {@link BoundedHeap}, using Java serialization via {@link CustomCoder}. - */ - private static class BoundedHeapCoder & Serializable> - extends CustomCoder> { - private final Coder> listCoder; - private final ComparatorT compareFn; - private final int maximumSize; - - public BoundedHeapCoder(int maximumSize, ComparatorT compareFn, Coder elementCoder) { - listCoder = ListCoder.of(elementCoder); - this.compareFn = compareFn; - this.maximumSize = maximumSize; - } - - @Override - public void encode( - BoundedHeap value, OutputStream outStream, Context context) - throws CoderException, IOException { - listCoder.encode(value.asList(), outStream, context); - } - - @Override - public BoundedHeap decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - return new BoundedHeap<>(maximumSize, compareFn, listCoder.decode(inStream, context)); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "HeapCoder requires a deterministic list coder", listCoder); - } - - @Override - public boolean isRegisterByteSizeObserverCheap( - BoundedHeap value, Context context) { - return listCoder.isRegisterByteSizeObserverCheap( - value.asList(), context); - } - - @Override - public void registerByteSizeObserver( - BoundedHeap value, ElementByteSizeObserver observer, Context context) - throws Exception { - listCoder.registerByteSizeObserver(value.asList(), observer, context); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java deleted file mode 100644 index c9026e969c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Values.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -/** - * {@code Values} takes a {@code PCollection} of {@code KV}s and - * returns a {@code PCollection} of the values. - * - *

              Example of use: - *

               {@code
              - * PCollection> wordCounts = ...;
              - * PCollection counts = wordCounts.apply(Values.create());
              - * } 
              - * - *

              Each output element has the same timestamp and is in the same windows - * as its corresponding input element, and the output {@code PCollection} - * has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - *

              See also {@link Keys}. - * - * @param the type of the values in the input {@code PCollection}, - * and the type of the elements in the output {@code PCollection} - */ -public class Values extends PTransform>, - PCollection> { - /** - * Returns a {@code Values} {@code PTransform}. - * - * @param the type of the values in the input {@code PCollection}, - * and the type of the elements in the output {@code PCollection} - */ - public static Values create() { - return new Values<>(); - } - - private Values() { } - - @Override - public PCollection apply(PCollection> in) { - return - in.apply(ParDo.named("Values") - .of(new DoFn, V>() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().getValue()); - } - })); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java deleted file mode 100644 index ce2a3afe1b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/View.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.util.PCollectionViews; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.util.List; -import java.util.Map; - -/** - * Transforms for creating {@link PCollectionView PCollectionViews} from - * {@link PCollection PCollections} (to read them as side inputs). - * - *

              While a {@link PCollection PCollection<ElemT>} has many values of type {@code ElemT} per - * window, a {@link PCollectionView PCollectionView<ViewT>} has a single value of type - * {@code ViewT} for each window. It can be thought of as a mapping from windows to values of - * type {@code ViewT}. The transforms here represent ways of converting the {@code ElemT} values - * in a window into a {@code ViewT} for that window. - * - *

              When a {@link ParDo} tranform is processing a main input - * element in a window {@code w} and a {@link PCollectionView} is read via - * {@link DoFn.ProcessContext#sideInput}, the value of the view for {@code w} is - * returned. - * - *

              The SDK supports viewing a {@link PCollection}, per window, as a single value, - * a {@link List}, an {@link Iterable}, a {@link Map}, or a multimap (iterable-valued {@link Map}). - * - *

              For a {@link PCollection} that contains a single value of type {@code T} - * per window, such as the output of {@link Combine#globally}, - * use {@link View#asSingleton()} to prepare it for use as a side input: - * - *

              - * {@code
              - * PCollectionView output = someOtherPCollection
              - *     .apply(Combine.globally(...))
              - *     .apply(View.asSingleton());
              - * }
              - * 
              - * - *

              For a small {@link PCollection} with windows that can fit entirely in memory, - * use {@link View#asList()} to prepare it for use as a {@code List}. - * When read as a side input, the entire list for a window will be cached in memory. - * - *

              - * {@code
              - * PCollectionView> output =
              - *    smallPCollection.apply(View.asList());
              - * }
              - * 
              - * - *

              If a {@link PCollection} of {@code KV} is known to - * have a single value per window for each key, then use {@link View#asMap()} - * to view it as a {@code Map}: - * - *

              - * {@code
              - * PCollectionView output =
              - *     somePCollection.apply(View.asMap());
              - * }
              - * 
              - * - *

              Otherwise, to access a {@link PCollection} of {@code KV} as a - * {@code Map>} side input, use {@link View#asMultimap()}: - * - *

              - * {@code
              - * PCollectionView> output =
              - *     somePCollection.apply(View.>asMap());
              - * }
              - * 
              - * - *

              To iterate over an entire window of a {@link PCollection} via - * side input, use {@link View#asIterable()}: - * - *

              - * {@code
              - * PCollectionView> output =
              - *     somePCollection.apply(View.asIterable());
              - * }
              - * 
              - * - * - *

              Both {@link View#asMultimap()} and {@link View#asMap()} are useful - * for implementing lookup based "joins" with the main input, when the - * side input is small enough to fit into memory. - * - *

              For example, if you represent a page on a website via some {@code Page} object and - * have some type {@code UrlVisits} logging that a URL was visited, you could convert these - * to more fully structured {@code PageVisit} objects using a side input, something like the - * following: - * - *

              - * {@code
              - * PCollection pages = ... // pages fit into memory
              - * PCollection urlVisits = ... // very large collection
              - * final PCollectionView> = urlToPage
              - *     .apply(WithKeys.of( ... )) // extract the URL from the page
              - *     .apply(View.asMap());
              - *
              - * PCollection PageVisits = urlVisits
              - *     .apply(ParDo.withSideInputs(urlToPage)
              - *         .of(new DoFn() {
              - *             {@literal @}Override
              - *             void processElement(ProcessContext context) {
              - *               UrlVisit urlVisit = context.element();
              - *               Page page = urlToPage.get(urlVisit.getUrl());
              - *               c.output(new PageVisit(page, urlVisit.getVisitData()));
              - *             }
              - *         }));
              - * }
              - * 
              - * - *

              See {@link ParDo#withSideInputs} for details on how to access - * this variable inside a {@link ParDo} over another {@link PCollection}. - */ -public class View { - - // Do not instantiate - private View() { } - - /** - * Returns a {@link AsSingleton} transform that takes a - * {@link PCollection} with a single value per window - * as input and produces a {@link PCollectionView} that returns - * the value in the main input window when read as a side input. - * - *

              -   * {@code
              -   * PCollection input = ...
              -   * CombineFn yourCombineFn = ...
              -   * PCollectionView output = input
              -   *     .apply(Combine.globally(yourCombineFn))
              -   *     .apply(View.asSingleton());
              -   * }
              - * - *

              If the input {@link PCollection} is empty, - * throws {@link java.util.NoSuchElementException} in the consuming - * {@link DoFn}. - * - *

              If the input {@link PCollection} contains more than one - * element, throws {@link IllegalArgumentException} in the - * consuming {@link DoFn}. - */ - public static AsSingleton asSingleton() { - return new AsSingleton<>(); - } - - /** - * Returns a {@link View.AsList} transform that takes a {@link PCollection} and returns a - * {@link PCollectionView} mapping each window to a {@link List} containing - * all of the elements in the window. - * - *

              The resulting list is required to fit in memory. - */ - public static AsList asList() { - return new AsList<>(); - } - - /** - * Returns a {@link View.AsIterable} transform that takes a {@link PCollection} as input - * and produces a {@link PCollectionView} mapping each window to an - * {@link Iterable} of the values in that window. - * - *

              The values of the {@link Iterable} for a window are not required to fit in memory, - * but they may also not be effectively cached. If it is known that every window fits in memory, - * and stronger caching is desired, use {@link #asList}. - */ - public static AsIterable asIterable() { - return new AsIterable<>(); - } - - /** - * Returns a {@link View.AsMap} transform that takes a - * {@link PCollection PCollection<KV<K, V>>} as - * input and produces a {@link PCollectionView} mapping each window to - * a {@link Map Map<K, V>}. It is required that each key of the input be - * associated with a single value, per window. If this is not the case, precede this - * view with {@code Combine.perKey}, as in the example below, or alternatively - * use {@link View#asMultimap()}. - * - *

              -   * {@code
              -   * PCollection> input = ...
              -   * CombineFn yourCombineFn = ...
              -   * PCollectionView> output = input
              -   *     .apply(Combine.perKey(yourCombineFn.asKeyedFn()))
              -   *     .apply(View.asMap());
              -   * }
              - * - *

              Currently, the resulting map is required to fit into memory. - */ - public static AsMap asMap() { - return new AsMap(); - } - - /** - * Returns a {@link View.AsMultimap} transform that takes a - * {@link PCollection PCollection<KV<K, V>>} - * as input and produces a {@link PCollectionView} mapping - * each window to its contents as a {@link Map Map<K, Iterable<V>>} - * for use as a side input. - * In contrast to {@link View#asMap()}, it is not required that the keys in the - * input collection be unique. - * - *

              -   * {@code
              -   * PCollection> input = ... // maybe more than one occurrence of a some keys
              -   * PCollectionView> output = input.apply(View.asMultimap());
              -   * }
              - * - *

              Currently, the resulting map is required to fit into memory. - */ - public static AsMultimap asMultimap() { - return new AsMultimap(); - } - - /** - * Not intended for direct use by pipeline authors; public only so a {@link PipelineRunner} may - * override its behavior. - * - *

              See {@link View#asList()}. - */ - public static class AsList extends PTransform, PCollectionView>> { - private AsList() { } - - @Override - public void validate(PCollection input) { - try { - GroupByKey.applicableTo(input); - } catch (IllegalStateException e) { - throw new IllegalStateException("Unable to create a side-input view from input", e); - } - } - - @Override - public PCollectionView> apply(PCollection input) { - return input.apply(CreatePCollectionView.>of(PCollectionViews.listView( - input.getPipeline(), input.getWindowingStrategy(), input.getCoder()))); - } - } - - /** - * Not intended for direct use by pipeline authors; public only so a {@link PipelineRunner} may - * override its behavior. - * - *

              See {@link View#asIterable()}. - */ - public static class AsIterable - extends PTransform, PCollectionView>> { - private AsIterable() { } - - @Override - public void validate(PCollection input) { - try { - GroupByKey.applicableTo(input); - } catch (IllegalStateException e) { - throw new IllegalStateException("Unable to create a side-input view from input", e); - } - } - - @Override - public PCollectionView> apply(PCollection input) { - return input.apply(CreatePCollectionView.>of(PCollectionViews.iterableView( - input.getPipeline(), input.getWindowingStrategy(), input.getCoder()))); - } - } - - /** - * Not intended for direct use by pipeline authors; public only so a {@link PipelineRunner} may - * override its behavior. - * - *

              See {@link View#asSingleton()}. - */ - public static class AsSingleton extends PTransform, PCollectionView> { - private final T defaultValue; - private final boolean hasDefault; - - private AsSingleton() { - this.defaultValue = null; - this.hasDefault = false; - } - - private AsSingleton(T defaultValue) { - this.defaultValue = defaultValue; - this.hasDefault = true; - } - - /** - * Returns whether this transform has a default value. - */ - public boolean hasDefaultValue() { - return hasDefault; - } - - /** - * Returns the default value of this transform, or null if there isn't one. - */ - public T defaultValue() { - return defaultValue; - } - - /** - * Default value to return for windows with no value in them. - */ - public AsSingleton withDefaultValue(T defaultValue) { - return new AsSingleton<>(defaultValue); - } - - @Override - public void validate(PCollection input) { - try { - GroupByKey.applicableTo(input); - } catch (IllegalStateException e) { - throw new IllegalStateException("Unable to create a side-input view from input", e); - } - } - - @Override - public PCollectionView apply(PCollection input) { - return input.apply(CreatePCollectionView.of(PCollectionViews.singletonView( - input.getPipeline(), - input.getWindowingStrategy(), - hasDefault, - defaultValue, - input.getCoder()))); - } - } - - /** - * Not intended for direct use by pipeline authors; public only so a {@link PipelineRunner} may - * override its behavior. - * - *

              See {@link View#asMultimap()}. - */ - public static class AsMultimap - extends PTransform>, PCollectionView>>> { - private AsMultimap() { } - - @Override - public void validate(PCollection> input) { - try { - GroupByKey.applicableTo(input); - } catch (IllegalStateException e) { - throw new IllegalStateException("Unable to create a side-input view from input", e); - } - } - - @Override - public PCollectionView>> apply(PCollection> input) { - return input.apply(CreatePCollectionView., Map>>of( - PCollectionViews.multimapView( - input.getPipeline(), - input.getWindowingStrategy(), - input.getCoder()))); - } - } - - /** - * Not intended for direct use by pipeline authors; public only so a {@link PipelineRunner} may - * override its behavior. - * - *

              See {@link View#asMap()}. - */ - public static class AsMap - extends PTransform>, PCollectionView>> { - private AsMap() { } - - /** - * @deprecated this method simply returns this AsMap unmodified - */ - @Deprecated() - public AsMap withSingletonValues() { - return this; - } - - @Override - public void validate(PCollection> input) { - try { - GroupByKey.applicableTo(input); - } catch (IllegalStateException e) { - throw new IllegalStateException("Unable to create a side-input view from input", e); - } - } - - @Override - public PCollectionView> apply(PCollection> input) { - return input.apply(CreatePCollectionView., Map>of( - PCollectionViews.mapView( - input.getPipeline(), - input.getWindowingStrategy(), - input.getCoder()))); - } - } - - //////////////////////////////////////////////////////////////////////////// - // Internal details below - - /** - * Creates a primitive {@link PCollectionView}. - * - *

              For internal use only by runner implementors. - * - * @param The type of the elements of the input PCollection - * @param The type associated with the {@link PCollectionView} used as a side input - */ - public static class CreatePCollectionView - extends PTransform, PCollectionView> { - private PCollectionView view; - - private CreatePCollectionView(PCollectionView view) { - this.view = view; - } - - public static CreatePCollectionView of( - PCollectionView view) { - return new CreatePCollectionView<>(view); - } - - public PCollectionView getView() { - return view; - } - - @Override - public PCollectionView apply(PCollection input) { - return view; - } - - static { - DirectPipelineRunner.registerDefaultTransformEvaluator( - CreatePCollectionView.class, - new DirectPipelineRunner.TransformEvaluator() { - @SuppressWarnings("rawtypes") - @Override - public void evaluate( - CreatePCollectionView transform, - DirectPipelineRunner.EvaluationContext context) { - evaluateTyped(transform, context); - } - - private void evaluateTyped( - CreatePCollectionView transform, - DirectPipelineRunner.EvaluationContext context) { - List> elems = - context.getPCollectionWindowedValues(context.getInput(transform)); - context.setPCollectionView(context.getOutput(transform), elems); - } - }); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java deleted file mode 100644 index 4c1ce7f073..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithKeys.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -/** - * {@code WithKeys} takes a {@code PCollection}, and either a - * constant key of type {@code K} or a function from {@code V} to - * {@code K}, and returns a {@code PCollection>}, where each - * of the values in the input {@code PCollection} has been paired with - * either the constant key or a key computed from the value. - * - *

              Example of use: - *

               {@code
              - * PCollection words = ...;
              - * PCollection> lengthsToWords =
              - *     words.apply(WithKeys.of(new SerializableFunction() {
              - *         public Integer apply(String s) { return s.length(); } }));
              - * } 
              - * - *

              Each output element has the same timestamp and is in the same windows - * as its corresponding input element, and the output {@code PCollection} - * has the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn} - * associated with it as the input. - * - * @param the type of the keys in the output {@code PCollection} - * @param the type of the elements in the input - * {@code PCollection} and the values in the output - * {@code PCollection} - */ -public class WithKeys extends PTransform, - PCollection>> { - /** - * Returns a {@code PTransform} that takes a {@code PCollection} - * and returns a {@code PCollection>}, where each of the - * values in the input {@code PCollection} has been paired with a - * key computed from the value by invoking the given - * {@code SerializableFunction}. - * - *

              If using a lambda in Java 8, {@link #withKeyType(TypeDescriptor)} must - * be called on the result {@link PTransform}. - */ - public static WithKeys of(SerializableFunction fn) { - return new WithKeys<>(fn, null); - } - - /** - * Returns a {@code PTransform} that takes a {@code PCollection} - * and returns a {@code PCollection>}, where each of the - * values in the input {@code PCollection} has been paired with the - * given key. - */ - @SuppressWarnings("unchecked") - public static WithKeys of(final K key) { - return new WithKeys<>( - new SerializableFunction() { - @Override - public K apply(V value) { - return key; - } - }, - (Class) (key == null ? null : key.getClass())); - } - - - ///////////////////////////////////////////////////////////////////////////// - - private SerializableFunction fn; - private transient Class keyClass; - - private WithKeys(SerializableFunction fn, Class keyClass) { - this.fn = fn; - this.keyClass = keyClass; - } - - /** - * Return a {@link WithKeys} that is like this one with the specified key type descriptor. - * - *

              For use with lambdas in Java 8, either this method must be called with an appropriate type - * descriptor or {@link PCollection#setCoder(Coder)} must be called on the output - * {@link PCollection}. - */ - public WithKeys withKeyType(TypeDescriptor keyType) { - // Safe cast - @SuppressWarnings("unchecked") - Class rawType = (Class) keyType.getRawType(); - return new WithKeys<>(fn, rawType); - } - - @Override - public PCollection> apply(PCollection in) { - PCollection> result = - in.apply(ParDo.named("AddKeys") - .of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(fn.apply(c.element()), - c.element())); - } - })); - - try { - Coder keyCoder; - CoderRegistry coderRegistry = in.getPipeline().getCoderRegistry(); - if (keyClass == null) { - keyCoder = coderRegistry.getDefaultOutputCoder(fn, in.getCoder()); - } else { - keyCoder = coderRegistry.getDefaultCoder(TypeDescriptor.of(keyClass)); - } - // TODO: Remove when we can set the coder inference context. - result.setCoder(KvCoder.of(keyCoder, in.getCoder())); - } catch (CannotProvideCoderException exc) { - // let lazy coder inference have a try - } - - return result; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithTimestamps.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithTimestamps.java deleted file mode 100644 index 85a93bfe18..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/WithTimestamps.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.io.Source; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -/** - * A {@link PTransform} for assigning timestamps to all the elements of a {@link PCollection}. - * - *

              Timestamps are used to assign {@link BoundedWindow Windows} to elements within the - * {@link Window#into(com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn)} - * {@link PTransform}. Assigning timestamps is useful when the input data set comes from a - * {@link Source} without implicit timestamps (such as - * {@link com.google.cloud.dataflow.sdk.io.TextIO.Read TextIO}). - * - */ -public class WithTimestamps extends PTransform, PCollection> { - /** - * For a {@link SerializableFunction} {@code fn} from {@code T} to {@link Instant}, outputs a - * {@link PTransform} that takes an input {@link PCollection PCollection<T>} and outputs a - * {@link PCollection PCollection<T>} containing every element {@code v} in the input where - * each element is output with a timestamp obtained as the result of {@code fn.apply(v)}. - * - *

              If the input {@link PCollection} elements have timestamps, the output timestamp for each - * element must not be before the input element's timestamp minus the value of - * {@link #getAllowedTimestampSkew()}. If an output timestamp is before this time, the transform - * will throw an {@link IllegalArgumentException} when executed. Use - * {@link #withAllowedTimestampSkew(Duration)} to update the allowed skew. - * - *

              Each output element will be in the same windows as the input element. If a new window based - * on the new output timestamp is desired, apply a new instance of {@link Window#into(WindowFn)}. - * - *

              This transform will fail at execution time with a {@link NullPointerException} if for any - * input element the result of {@code fn.apply(v)} is {@code null}. - * - *

              Example of use in Java 8: - *

              {@code
              -   * PCollection timestampedRecords = records.apply(
              -   *     WithTimestamps.of((Record rec) -> rec.getInstant());
              -   * }
              - */ - public static WithTimestamps of(SerializableFunction fn) { - return new WithTimestamps<>(fn, Duration.ZERO); - } - - /////////////////////////////////////////////////////////////////// - - private final SerializableFunction fn; - private final Duration allowedTimestampSkew; - - private WithTimestamps(SerializableFunction fn, Duration allowedTimestampSkew) { - this.fn = checkNotNull(fn, "WithTimestamps fn cannot be null"); - this.allowedTimestampSkew = allowedTimestampSkew; - } - - /** - * Return a new WithTimestamps like this one with updated allowed timestamp skew, which is the - * maximum duration that timestamps can be shifted backward. Does not modify this object. - * - *

              The default value is {@code Duration.ZERO}, allowing timestamps to only be shifted into the - * future. For infinite skew, use {@code new Duration(Long.MAX_VALUE)}. - */ - public WithTimestamps withAllowedTimestampSkew(Duration allowedTimestampSkew) { - return new WithTimestamps<>(this.fn, allowedTimestampSkew); - } - - /** - * Returns the allowed timestamp skew duration, which is the maximum - * duration that timestamps can be shifted backwards from the timestamp of the input element. - * - * @see DoFn#getAllowedTimestampSkew() - */ - public Duration getAllowedTimestampSkew() { - return allowedTimestampSkew; - } - - @Override - public PCollection apply(PCollection input) { - return input - .apply(ParDo.named("AddTimestamps").of(new AddTimestampsDoFn(fn, allowedTimestampSkew))) - .setTypeDescriptorInternal(input.getTypeDescriptor()); - } - - private static class AddTimestampsDoFn extends DoFn { - private final SerializableFunction fn; - private final Duration allowedTimestampSkew; - - public AddTimestampsDoFn(SerializableFunction fn, Duration allowedTimestampSkew) { - this.fn = fn; - this.allowedTimestampSkew = allowedTimestampSkew; - } - - @Override - public void processElement(ProcessContext c) { - Instant timestamp = fn.apply(c.element()); - checkNotNull( - timestamp, "Timestamps for WithTimestamps cannot be null. Timestamp provided by %s.", fn); - c.outputWithTimestamp(c.element(), timestamp); - } - - @Override - public Duration getAllowedTimestampSkew() { - return allowedTimestampSkew; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Write.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Write.java deleted file mode 100644 index 5cf655a3e5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Write.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -/** - * A backwards-compatible {@code Write} class that simply inherits from the - * {@link com.google.cloud.dataflow.sdk.io.Write} class that should be used instead. - * - * @deprecated: use {@link com.google.cloud.dataflow.sdk.io.Write} from the - * {@code com.google.cloud.dataflow.sdk.io} package instead. - */ -@Deprecated -public class Write extends com.google.cloud.dataflow.sdk.io.Write { -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java deleted file mode 100644 index 7413eb7ef5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayData.java +++ /dev/null @@ -1,826 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonValue; - -import org.apache.avro.reflect.Nullable; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * Static display data associated with a pipeline component. Display data is useful for - * pipeline runner UIs and diagnostic dashboards to display details about - * {@link PTransform PTransforms} that make up a pipeline. - * - *

              Components specify their display data by implementing the {@link HasDisplayData} - * interface. - */ -public class DisplayData implements Serializable { - private static final DisplayData EMPTY = new DisplayData(Maps.>newHashMap()); - private static final DateTimeFormatter TIMESTAMP_FORMATTER = ISODateTimeFormat.dateTime(); - - private final ImmutableMap> entries; - - private DisplayData(Map> entries) { - this.entries = ImmutableMap.copyOf(entries); - } - - /** - * Default empty {@link DisplayData} instance. - */ - public static DisplayData none() { - return EMPTY; - } - - /** - * Collect the {@link DisplayData} from a component. This will traverse all subcomponents - * specified via {@link Builder#include} in the given component. Data in this component will be in - * a namespace derived from the component. - */ - public static DisplayData from(HasDisplayData component) { - checkNotNull(component, "component argument cannot be null"); - return InternalBuilder.forRoot(component).build(); - } - - /** - * Infer the {@link Type} for the given object. - * - *

              Use this method if the type of metadata is not known at compile time. For example: - * - *

              -   * {@code
              -   * @Override
              -   * public void populateDisplayData(DisplayData.Builder builder) {
              -   *   Optional type = DisplayData.inferType(foo);
              -   *   if (type.isPresent()) {
              -   *     builder.add(DisplayData.item("foo", type.get(), foo));
              -   *   }
              -   * }
              -   * }
              -   * 
              - * - * @return The inferred {@link Type}, or null if the type cannot be inferred, - */ - @Nullable - public static Type inferType(@Nullable Object value) { - return Type.tryInferFrom(value); - } - - @JsonValue - public Collection> items() { - return entries.values(); - } - - public Map> asMap() { - return entries; - } - - @Override - public int hashCode() { - return entries.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof DisplayData) { - DisplayData that = (DisplayData) obj; - return Objects.equals(this.entries, that.entries); - } - - return false; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - boolean isFirstLine = true; - for (Item entry : entries.values()) { - if (isFirstLine) { - isFirstLine = false; - } else { - builder.append("\n"); - } - - builder.append(entry); - } - - return builder.toString(); - } - - private static String namespaceOf(Class clazz) { - return clazz.getName(); - } - - /** - * Utility to build up display data from a component and its included - * subcomponents. - */ - public interface Builder { - /** - * Register display data from the specified subcomponent. For example, a {@link PTransform} - * which delegates to a user-provided function can implement {@link HasDisplayData} on the - * function and include it from the {@link PTransform}: - * - *
              {@literal @Override}
              -     * public void populateDisplayData(DisplayData.Builder builder) {
              -     *   super.populateDisplayData(builder);
              -     *
              -     *   builder
              -     *     .add(DisplayData.item("userFn", userFn)) // To register the class name of the userFn
              -     *     .include(userFn); // To allow the userFn to register additional display data
              -     * }
              -     * 
              - * - *

              Using {@code include(subcomponent)} will associate each of the registered items with the - * namespace of the {@code subcomponent} being registered. To register display data in the - * current namespace, such as from a base class implementation, use - * {@code subcomponent.populateDisplayData(builder)} instead. - * - * @see HasDisplayData#populateDisplayData(DisplayData.Builder) - */ - Builder include(HasDisplayData subComponent); - - /** - * Register display data from the specified subcomponent, overriding the namespace of - * subcomponent display items with the specified namespace. - * - * @see #include(HasDisplayData) - */ - Builder include(HasDisplayData subComponent, Class namespace); - - /** - * Register display data from the specified subcomponent, overriding the namespace of - * subcomponent display items with the specified namespace. - * - * @see #include(HasDisplayData) - */ - Builder include(HasDisplayData subComponent, String namespace); - - /** - * Register the given display item. - */ - Builder add(Item item); - - /** - * Register the given display item if the value is not null. - */ - Builder addIfNotNull(Item item); - - /** - * Register the given display item if the value is different than the specified default. - */ - Builder addIfNotDefault(Item item, @Nullable T defaultValue); - } - - /** - * {@link Item Items} are the unit of display data. Each item is identified by a given key - * and namespace from the component the display item belongs to. - * - *

              {@link Item Items} are registered via {@link DisplayData.Builder#add} - * within {@link HasDisplayData#populateDisplayData} implementations. - */ - public static final class Item implements Serializable { - @Nullable private final String namespace; - private final String key; - private final Type type; - @Nullable private final Object value; - @Nullable private final Object shortValue; - @Nullable private final String label; - @Nullable private final String linkUrl; - - /** - * The namespace for the display item. The namespace defaults to the component which - * the display item belongs to. - */ - @Nullable - @JsonGetter("namespace") - public String getNamespace() { - return namespace; - } - - /** - * The key for the display item. Each display item is created with a key and value - * via {@link DisplayData#item}. - */ - @JsonGetter("key") - public String getKey() { - return key; - } - - /** - * Retrieve the {@link DisplayData.Type} of display data. All metadata conforms to a - * predefined set of allowed types. - */ - @JsonGetter("type") - public Type getType() { - return type; - } - - /** - * Retrieve the value of the display item. The value is translated from the input to - * {@link DisplayData#item} into a format suitable for display. Translation is based on the - * item's {@link #getType() type}. - * - *

              The value will only be {@literal null} if the input value during creation was null. - */ - @JsonGetter("value") - @Nullable - public Object getValue() { - return value; - } - - /** - * Return the optional short value for an item, or null if none is provided. - * - *

              The short value is an alternative display representation for items having a long display - * value. For example, the {@link #getValue() value} for {@link Type#JAVA_CLASS} items contains - * the full class name with package, while the short value contains just the class name. - * - *

              A {@link #getValue() value} will be provided for each display item, and some types may - * also provide a short-value. If a short value is provided, display data consumers may - * choose to display it instead of or in addition to the {@link #getValue() value}. - */ - @JsonGetter("shortValue") - @JsonInclude(JsonInclude.Include.NON_NULL) - public Object getShortValue() { - return shortValue; - } - - /** - * Retrieve the optional label for an item. The label is a human-readable description of what - * the metadata represents. UIs may choose to display the label instead of the item key. - * - *

              If no label was specified, this will return {@code null}. - */ - @JsonGetter("label") - @JsonInclude(JsonInclude.Include.NON_NULL) - @Nullable - public String getLabel() { - return label; - } - - /** - * Retrieve the optional link URL for an item. The URL points to an address where the reader - * can find additional context for the display data. - * - *

              If no URL was specified, this will return {@code null}. - */ - @JsonGetter("linkUrl") - @JsonInclude(JsonInclude.Include.NON_NULL) - @Nullable - public String getLinkUrl() { - return linkUrl; - } - - private static Item create(String key, Type type, @Nullable T value) { - FormattedItemValue formatted = type.safeFormat(value); - return new Item<>( - null, key, type, formatted.getLongValue(), formatted.getShortValue(), null, null); - } - - /** - * Set the item {@link Item#getNamespace() namespace} from the given {@link Class}. - * - *

              This method does not alter the current instance, but instead returns a new {@link Item} - * with the namespace set. - */ - public Item withNamespace(Class namespace) { - checkNotNull(namespace, "namespace argument cannot be null"); - return withNamespace(namespaceOf(namespace)); - } - - /** @see #withNamespace(Class) */ - public Item withNamespace(String namespace) { - checkNotNull(namespace, "namespace argument cannot be null"); - return new Item<>( - namespace, getKey(), getType(), getValue(), getShortValue(), getLabel(), getLinkUrl()); - } - - /** - * Set the item {@link Item#getLabel() label}. - * - *

              Specifying a null value will clear the label if it was previously defined. - * - *

              This method does not alter the current instance, but instead returns a new {@link Item} - * with the label set. - */ - public Item withLabel(String label) { - return new Item<>( - getNamespace(), getKey(), getType(), getValue(), getShortValue(), label, getLinkUrl()); - } - - /** - * Set the item {@link Item#getLinkUrl() link url}. - * - *

              Specifying a null value will clear the link url if it was previously defined. - * - *

              This method does not alter the current instance, but instead returns a new {@link Item} - * with the link url set. - */ - public Item withLinkUrl(String url) { - return new Item<>( - getNamespace(), getKey(), getType(), getValue(), getShortValue(), getLabel(), url); - } - - /** - * Creates a similar item to the current instance but with the specified value. - * - *

              This should only be used internally. It is useful to compare the value of a - * {@link DisplayData.Item} to the value derived from a specified input. - */ - private Item withValue(Object value) { - FormattedItemValue formatted = getType().safeFormat(value); - return new Item<>(getNamespace(), getKey(), getType(), formatted.getLongValue(), - formatted.getShortValue(), getLabel(), getLinkUrl()); - } - - private Item( - @Nullable String namespace, - String key, - Type type, - @Nullable Object value, - @Nullable Object shortValue, - @Nullable String label, - @Nullable String linkUrl) { - this.namespace = namespace; - this.key = checkNotNull(key); - this.type = checkNotNull(type); - this.value = value; - this.shortValue = shortValue; - this.label = label; - this.linkUrl = linkUrl; - } - - @Override - public int hashCode() { - return Objects.hash( - namespace, - key, - type, - value, - shortValue, - label, - linkUrl - ); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Item)) { - return false; - } - - Item that = (Item) obj; - return Objects.equals(this.namespace, that.namespace) - && Objects.equals(this.key, that.key) - && Objects.equals(this.type, that.type) - && Objects.equals(this.value, that.value) - && Objects.equals(this.shortValue, that.shortValue) - && Objects.equals(this.label, that.label) - && Objects.equals(this.linkUrl, that.linkUrl); - } - - @Override - public String toString() { - return String.format("%s:%s=%s", getNamespace(), getKey(), getValue()); - } - } - - /** - * Unique identifier for a display data item within a component. - * Identifiers are composed of the key they are registered with and a namespace generated from - * the class of the component which registered the item. - * - *

              Display data registered with the same key from different components will have different - * namespaces and thus will both be represented in the composed {@link DisplayData}. If a - * single component registers multiple metadata items with the same key, only the most recent - * item will be retained; previous versions are discarded. - */ - public static class Identifier { - private final String ns; - private final String key; - - public static Identifier of(Class namespace, String key) { - return of(namespaceOf(namespace), key); - } - - public static Identifier of(String namespace, String key) { - return new Identifier(namespace, key); - } - - private Identifier(String ns, String key) { - this.ns = ns; - this.key = key; - } - - public String getNamespace() { - return ns; - } - - public String getKey() { - return key; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Identifier) { - Identifier that = (Identifier) obj; - return Objects.equals(this.ns, that.ns) - && Objects.equals(this.key, that.key); - } - - return false; - } - - @Override - public int hashCode() { - return Objects.hash(ns, key); - } - - @Override - public String toString() { - return String.format("%s:%s", ns, key); - } - } - - /** - * Display data type. - */ - public enum Type { - STRING { - @Override - FormattedItemValue format(Object value) { - return new FormattedItemValue(checkType(value, String.class, STRING)); - } - }, - INTEGER { - @Override - FormattedItemValue format(Object value) { - if (value instanceof Integer) { - long l = ((Integer) value).longValue(); - return format(l); - } - - return new FormattedItemValue(checkType(value, Long.class, INTEGER)); - } - }, - FLOAT { - @Override - FormattedItemValue format(Object value) { - return new FormattedItemValue(checkType(value, Number.class, FLOAT)); - } - }, - BOOLEAN() { - @Override - FormattedItemValue format(Object value) { - return new FormattedItemValue(checkType(value, Boolean.class, BOOLEAN)); - } - }, - TIMESTAMP() { - @Override - FormattedItemValue format(Object value) { - Instant instant = checkType(value, Instant.class, TIMESTAMP); - return new FormattedItemValue((TIMESTAMP_FORMATTER.print(instant))); - } - }, - DURATION { - @Override - FormattedItemValue format(Object value) { - Duration duration = checkType(value, Duration.class, DURATION); - return new FormattedItemValue(duration.getMillis()); - } - }, - JAVA_CLASS { - @Override - FormattedItemValue format(Object value) { - Class clazz = checkType(value, Class.class, JAVA_CLASS); - return new FormattedItemValue(clazz.getName(), clazz.getSimpleName()); - } - }; - - private static T checkType(Object value, Class clazz, DisplayData.Type expectedType) { - if (!clazz.isAssignableFrom(value.getClass())) { - throw new ClassCastException(String.format( - "Value is not valid for DisplayData type %s: %s", expectedType, value)); - } - - @SuppressWarnings("unchecked") // type checked above. - T typedValue = (T) value; - return typedValue; - } - - /** - * Format the display data value into a long string representation, and optionally - * a shorter representation for display. - * - *

              Internal-only. Value objects can be safely cast to the expected Java type. - */ - abstract FormattedItemValue format(Object value); - - /** - * Safe version of {@link Type#format(Object)}, which checks for null input value and if so - * returns a {@link FormattedItemValue} with null value properties. - * - * @see #format(Object) - */ - FormattedItemValue safeFormat(@Nullable Object value) { - if (value == null) { - return FormattedItemValue.NULL_VALUES; - } - - return format(value); - } - - @Nullable - private static Type tryInferFrom(@Nullable Object value) { - if (value instanceof Integer || value instanceof Long) { - return INTEGER; - } else if (value instanceof Double || value instanceof Float) { - return FLOAT; - } else if (value instanceof Boolean) { - return BOOLEAN; - } else if (value instanceof Instant) { - return TIMESTAMP; - } else if (value instanceof Duration) { - return DURATION; - } else if (value instanceof Class) { - return JAVA_CLASS; - } else if (value instanceof String) { - return STRING; - } else { - return null; - } - } - } - - static class FormattedItemValue { - /** - * Default instance which contains null values. - */ - private static final FormattedItemValue NULL_VALUES = new FormattedItemValue(null); - - private final Object shortValue; - private final Object longValue; - - private FormattedItemValue(Object longValue) { - this(longValue, null); - } - - private FormattedItemValue(Object longValue, Object shortValue) { - this.longValue = longValue; - this.shortValue = shortValue; - } - - Object getLongValue() { - return this.longValue; - } - - Object getShortValue() { - return this.shortValue; - } - } - - private static class InternalBuilder implements Builder { - private final Map> entries; - private final Set visited; - - private String latestNs; - - private InternalBuilder() { - this.entries = Maps.newHashMap(); - this.visited = Sets.newIdentityHashSet(); - } - - private static InternalBuilder forRoot(HasDisplayData instance) { - InternalBuilder builder = new InternalBuilder(); - builder.include(instance); - return builder; - } - - @Override - public Builder include(HasDisplayData subComponent) { - checkNotNull(subComponent, "subComponent argument cannot be null"); - return include(subComponent, subComponent.getClass()); - } - - @Override - public Builder include(HasDisplayData subComponent, Class namespace) { - checkNotNull(namespace, "Input namespace override cannot be null"); - return include(subComponent, namespaceOf(namespace)); - } - - @Override - public Builder include(HasDisplayData subComponent, String namespace) { - checkNotNull(subComponent, "subComponent argument cannot be null"); - checkNotNull(namespace, "Input namespace override cannot be null"); - - boolean newComponent = visited.add(subComponent); - if (newComponent) { - String prevNs = this.latestNs; - this.latestNs = namespace; - - try { - subComponent.populateDisplayData(this); - } catch (PopulateDisplayDataException e) { - // Don't re-wrap exceptions recursively. - throw e; - } catch (Throwable e) { - String msg = String.format("Error while populating display data for component: %s", - namespace); - throw new PopulateDisplayDataException(msg, e); - } - - this.latestNs = prevNs; - } - - return this; - } - - /** - * Marker exception class for exceptions encountered while populating display data. - */ - private class PopulateDisplayDataException extends RuntimeException { - PopulateDisplayDataException(String message, Throwable cause) { - super(message, cause); - } - } - - @Override - public Builder add(Item item) { - checkNotNull(item, "Input display item cannot be null"); - return addItemIf(true, item); - } - - @Override - public Builder addIfNotNull(Item item) { - checkNotNull(item, "Input display item cannot be null"); - return addItemIf(item.getValue() != null, item); - } - - @Override - public Builder addIfNotDefault(Item item, @Nullable T defaultValue) { - checkNotNull(item, "Input display item cannot be null"); - Item defaultItem = item.withValue(defaultValue); - return addItemIf(!Objects.equals(item, defaultItem), item); - } - - private Builder addItemIf(boolean condition, Item item) { - if (!condition) { - return this; - } - - checkNotNull(item, "Input display item cannot be null"); - checkNotNull(item.getValue(), "Input display value cannot be null"); - if (item.getNamespace() == null) { - item = item.withNamespace(latestNs); - } - - Identifier id = Identifier.of(item.getNamespace(), item.getKey()); - checkArgument(!entries.containsKey(id), - "Display data key (%s) is not unique within the specified namespace (%s).", - item.getKey(), item.getNamespace()); - - entries.put(id, item); - return this; - } - - private DisplayData build() { - return new DisplayData(this.entries); - } - } - - /** - * Create a display item for the specified key and string value. - */ - public static Item item(String key, @Nullable String value) { - return item(key, Type.STRING, value); - } - - /** - * Create a display item for the specified key and {@link ValueProvider}. - */ - public static Item item(String key, ValueProvider value) { - if (value == null) { - return item(key, Type.STRING, null); - } - if (value.isAccessible()) { - Object got = value.get(); - if (got == null) { - return item(key, Type.STRING, null); - } - Type type = inferType(got); - if (type == null) { - throw new RuntimeException(String.format("Unknown value type: %s", got)); - } - return item(key, type, got); - } - return item(key, Type.STRING, value.toString()); - } - - /** - * Create a display item for the specified key and integer value. - */ - public static Item item(String key, @Nullable Integer value) { - return item(key, Type.INTEGER, value); - } - - /** - * Create a display item for the specified key and integer value. - */ - public static Item item(String key, @Nullable Long value) { - return item(key, Type.INTEGER, value); - } - - /** - * Create a display item for the specified key and floating point value. - */ - public static Item item(String key, @Nullable Float value) { - return item(key, Type.FLOAT, value); - } - - /** - * Create a display item for the specified key and floating point value. - */ - public static Item item(String key, @Nullable Double value) { - return item(key, Type.FLOAT, value); - } - - /** - * Create a display item for the specified key and boolean value. - */ - public static Item item(String key, @Nullable Boolean value) { - return item(key, Type.BOOLEAN, value); - } - - /** - * Create a display item for the specified key and timestamp value. - */ - public static Item item(String key, @Nullable Instant value) { - return item(key, Type.TIMESTAMP, value); - } - - /** - * Create a display item for the specified key and duration value. - */ - public static Item item(String key, @Nullable Duration value) { - return item(key, Type.DURATION, value); - } - - /** - * Create a display item for the specified key and class value. - */ - public static Item> item(String key, @Nullable Class value) { - return item(key, Type.JAVA_CLASS, value); - } - - /** - * Create a display item for the specified key, type, and value. This method should be used - * if the type of the input value can only be determined at runtime. Otherwise, - * {@link HasDisplayData} implementors should call one of the typed factory methods, such as - * {@link #item(String, String)} or {@link #item(String, Integer)}. - * - * @throws ClassCastException if the value cannot be formatted as the given type. - * - * @see Type#inferType(Object) - */ - public static Item item(String key, Type type, @Nullable T value) { - checkNotNull(key, "key argument cannot be null"); - checkNotNull(type, "type argument cannot be null"); - - return Item.create(key, type, value); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java deleted file mode 100644 index 04727a1caf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/HasDisplayData.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -/** - * Marker interface for {@link PTransform PTransforms} and components to specify display data used - * within UIs and diagnostic tools. - * - *

              Display data is registered by overriding - * {@link #populateDisplayData(DisplayData.Builder)} in a component which implements - * {@code HasDisplayData}. Display data is available for {@link PipelineOptions} and - * {@link PTransform} implementations. - * - *

              {@literal @Override}
              - * public void populateDisplayData(DisplayData.Builder builder) {
              - *  super.populateDisplayData(builder);
              - *
              - *  builder
              - *     .include(subComponent)
              - *     .add(DisplayData.item("minFilter", 42))
              - *     .addIfNotDefault(DisplayData.item("useTransactions", this.txn), false)
              - *     .add(DisplayData.item("topic", "projects/myproject/topics/mytopic")
              - *       .withLabel("Pub/Sub Topic"))
              - *     .add(DisplayData.item("serviceInstance", "myservice.com/fizzbang")
              - *       .withLinkUrl("http://www.myservice.com/fizzbang"));
              - * }
              - * 
              - * - *

              Display data is optional and may be collected during pipeline construction. It should - * only be used for informational purposes. Tools and components should not assume that display data - * will always be collected, or that collected display data will always be displayed. - * - * @see #populateDisplayData(DisplayData.Builder) - */ -public interface HasDisplayData { - /** - * Register display data for the given transform or component. - * - *

              {@code populateDisplayData(DisplayData.Builder)} is invoked by Pipeline runners to collect - * display data via {@link DisplayData#from(HasDisplayData)}. Implementations may call - * {@code super.populateDisplayData(builder)} in order to register display data in the current - * namespace, but should otherwise use {@code subcomponent.populateDisplayData(builder)} to use - * the namespace of the subcomponent. - * - * @param builder The builder to populate with display data. - * - * @see HasDisplayData - */ - void populateDisplayData(DisplayData.Builder builder); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java deleted file mode 100644 index d3e624006f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/display/package-info.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines {@link com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData} for annotating - * components which provide - * {@link com.google.cloud.dataflow.sdk.transforms.display.DisplayData display data} used within UIs - * and diagnostic tools. - * - * @see com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData - */ -package com.google.cloud.dataflow.sdk.transforms.display; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java deleted file mode 100644 index d66c860dd2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import static com.google.cloud.dataflow.sdk.util.Structs.addObject; -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.Reiterator; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.common.collect.Iterators; -import com.google.common.collect.PeekingIterator; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; - -/** - * A row result of a {@link CoGroupByKey}. This is a tuple of {@link Iterable}s produced for - * a given key, and these can be accessed in different ways. - */ -public class CoGbkResult { - /** - * A map of integer union tags to a list of union objects. - * Note: the key and the embedded union tag are the same, so it is redundant - * to store it multiple times, but for now it makes encoding easier. - */ - private final List> valueMap; - - private final CoGbkResultSchema schema; - - private static final int DEFAULT_IN_MEMORY_ELEMENT_COUNT = 10_000; - - private static final Logger LOG = LoggerFactory.getLogger(CoGbkResult.class); - - /** - * A row in the {@link PCollection} resulting from a {@link CoGroupByKey} transform. - * Currently, this row must fit into memory. - * - * @param schema the set of tuple tags used to refer to input tables and - * result values - * @param taggedValues the raw results from a group-by-key - */ - public CoGbkResult( - CoGbkResultSchema schema, - Iterable taggedValues) { - this(schema, taggedValues, DEFAULT_IN_MEMORY_ELEMENT_COUNT); - } - - @SuppressWarnings("unchecked") - public CoGbkResult( - CoGbkResultSchema schema, - Iterable taggedValues, - int inMemoryElementCount) { - this.schema = schema; - valueMap = new ArrayList<>(); - for (int unionTag = 0; unionTag < schema.size(); unionTag++) { - valueMap.add(new ArrayList<>()); - } - - // Demultiplex the first imMemoryElementCount tagged union values - // according to their tag. - final Iterator taggedIter = taggedValues.iterator(); - int elementCount = 0; - while (taggedIter.hasNext()) { - if (elementCount++ >= inMemoryElementCount && taggedIter instanceof Reiterator) { - // Let the tails be lazy. - break; - } - RawUnionValue value = taggedIter.next(); - // Make sure the given union tag has a corresponding tuple tag in the - // schema. - int unionTag = value.getUnionTag(); - if (schema.size() <= unionTag) { - throw new IllegalStateException("union tag " + unionTag - + " has no corresponding tuple tag in the result schema"); - } - List valueList = (List) valueMap.get(unionTag); - valueList.add(value.getValue()); - } - - if (taggedIter.hasNext()) { - // If we get here, there were more elements than we can afford to - // keep in memory, so we copy the re-iterable of remaining items - // and append filtered views to each of the sorted lists computed earlier. - LOG.info("CoGbkResult has more than " + inMemoryElementCount + " elements," - + " reiteration (which may be slow) is required."); - final Reiterator tail = (Reiterator) taggedIter; - // This is a trinary-state array recording whether a given tag is present in the tail. The - // initial value is null (unknown) for all tags, and the first iteration through the entire - // list will set these values to true or false to avoid needlessly iterating if filtering - // against a given tag would not match anything. - final Boolean[] containsTag = new Boolean[schema.size()]; - for (int unionTag = 0; unionTag < schema.size(); unionTag++) { - final int unionTag0 = unionTag; - updateUnionTag(tail, containsTag, unionTag, unionTag0); - } - } - } - - private void updateUnionTag( - final Reiterator tail, final Boolean[] containsTag, - int unionTag, final int unionTag0) { - @SuppressWarnings("unchecked") - final Iterable head = (Iterable) valueMap.get(unionTag); - valueMap.set( - unionTag, - new Iterable() { - @Override - public Iterator iterator() { - return Iterators.concat( - head.iterator(), - new UnionValueIterator(unionTag0, tail.copy(), containsTag)); - } - }); - } - - public boolean isEmpty() { - for (Iterable tagValues : valueMap) { - if (tagValues.iterator().hasNext()) { - return false; - } - } - return true; - } - - /** - * Returns the schema used by this {@link CoGbkResult}. - */ - public CoGbkResultSchema getSchema() { - return schema; - } - - @Override - public String toString() { - return valueMap.toString(); - } - - /** - * Returns the values from the table represented by the given - * {@code TupleTag} as an {@code Iterable} (which may be empty if there - * are no results). - * - *

              If tag was not part of the original {@link CoGroupByKey}, - * throws an IllegalArgumentException. - */ - public Iterable getAll(TupleTag tag) { - int index = schema.getIndex(tag); - if (index < 0) { - throw new IllegalArgumentException("TupleTag " + tag - + " is not in the schema"); - } - @SuppressWarnings("unchecked") - Iterable unions = (Iterable) valueMap.get(index); - return unions; - } - - /** - * If there is a singleton value for the given tag, returns it. - * Otherwise, throws an IllegalArgumentException. - * - *

              If tag was not part of the original {@link CoGroupByKey}, - * throws an IllegalArgumentException. - */ - public V getOnly(TupleTag tag) { - return innerGetOnly(tag, null, false); - } - - /** - * If there is a singleton value for the given tag, returns it. If there is - * no value for the given tag, returns the defaultValue. - * - *

              If tag was not part of the original {@link CoGroupByKey}, - * throws an IllegalArgumentException. - */ - public V getOnly(TupleTag tag, V defaultValue) { - return innerGetOnly(tag, defaultValue, true); - } - - /** - * A {@link Coder} for {@link CoGbkResult}s. - */ - public static class CoGbkResultCoder extends StandardCoder { - - private final CoGbkResultSchema schema; - private final UnionCoder unionCoder; - - /** - * Returns a {@link CoGbkResultCoder} for the given schema and {@link UnionCoder}. - */ - public static CoGbkResultCoder of( - CoGbkResultSchema schema, - UnionCoder unionCoder) { - return new CoGbkResultCoder(schema, unionCoder); - } - - @JsonCreator - public static CoGbkResultCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components, - @JsonProperty(PropertyNames.CO_GBK_RESULT_SCHEMA) CoGbkResultSchema schema) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return new CoGbkResultCoder(schema, (UnionCoder) components.get(0)); - } - - private CoGbkResultCoder( - CoGbkResultSchema tupleTags, - UnionCoder unionCoder) { - this.schema = tupleTags; - this.unionCoder = unionCoder; - } - - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public List> getComponents() { - return Arrays.>asList(unionCoder); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addObject(result, PropertyNames.CO_GBK_RESULT_SCHEMA, schema.asCloudObject()); - return result; - } - - @Override - @SuppressWarnings("unchecked") - public void encode( - CoGbkResult value, - OutputStream outStream, - Context context) throws CoderException, - IOException { - if (!schema.equals(value.getSchema())) { - throw new CoderException("input schema does not match coder schema"); - } - for (int unionTag = 0; unionTag < schema.size(); unionTag++) { - tagListCoder(unionTag).encode(value.valueMap.get(unionTag), outStream, Context.NESTED); - } - } - - @Override - public CoGbkResult decode( - InputStream inStream, - Context context) - throws CoderException, IOException { - List> valueMap = new ArrayList<>(); - for (int unionTag = 0; unionTag < schema.size(); unionTag++) { - valueMap.add(tagListCoder(unionTag).decode(inStream, Context.NESTED)); - } - return new CoGbkResult(schema, valueMap); - } - - @SuppressWarnings("rawtypes") - private IterableCoder tagListCoder(int unionTag) { - return IterableCoder.of(unionCoder.getComponents().get(unionTag)); - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof CoGbkResultCoder)) { - return false; - } - CoGbkResultCoder other = (CoGbkResultCoder) object; - return schema.equals(other.schema) && unionCoder.equals(other.unionCoder); - } - - @Override - public int hashCode() { - return Objects.hashCode(schema); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "CoGbkResult requires the union coder to be deterministic", unionCoder); - } - } - - - ////////////////////////////////////////////////////////////////////////////// - // Methods for directly constructing a CoGbkResult - // - // (for example, creating test data for a transform that consumes a - // CoGbkResult) - - /** - * Returns a new CoGbkResult that contains just the given tag and given data. - */ - public static CoGbkResult of(TupleTag tag, List data) { - return CoGbkResult.empty().and(tag, data); - } - - /** - * Returns a new {@link CoGbkResult} based on this, with the given tag and given data - * added to it. - */ - public CoGbkResult and(TupleTag tag, List data) { - if (nextTestUnionId != schema.size()) { - throw new IllegalArgumentException( - "Attempting to call and() on a CoGbkResult apparently not created by" - + " of()."); - } - List> valueMap = new ArrayList<>(this.valueMap); - valueMap.add(data); - return new CoGbkResult( - new CoGbkResultSchema(schema.getTupleTagList().and(tag)), valueMap, - nextTestUnionId + 1); - } - - /** - * Returns an empty {@link CoGbkResult}. - */ - public static CoGbkResult empty() { - return new CoGbkResult(new CoGbkResultSchema(TupleTagList.empty()), - new ArrayList>()); - } - - ////////////////////////////////////////////////////////////////////////////// - - private int nextTestUnionId = 0; - - private CoGbkResult( - CoGbkResultSchema schema, - List> valueMap, - int nextTestUnionId) { - this(schema, valueMap); - this.nextTestUnionId = nextTestUnionId; - } - - private CoGbkResult( - CoGbkResultSchema schema, - List> valueMap) { - this.schema = schema; - this.valueMap = valueMap; - } - - private V innerGetOnly( - TupleTag tag, - V defaultValue, - boolean useDefault) { - int index = schema.getIndex(tag); - if (index < 0) { - throw new IllegalArgumentException("TupleTag " + tag - + " is not in the schema"); - } - @SuppressWarnings("unchecked") - Iterator unions = (Iterator) valueMap.get(index).iterator(); - if (!unions.hasNext()) { - if (useDefault) { - return defaultValue; - } else { - throw new IllegalArgumentException("TupleTag " + tag - + " corresponds to an empty result, and no default was provided"); - } - } - V value = unions.next(); - if (unions.hasNext()) { - throw new IllegalArgumentException("TupleTag " + tag - + " corresponds to a non-singleton result"); - } - return value; - } - - /** - * Lazily filters and recasts an {@code Iterator} into an - * {@code Iterator}, where V is the type of the raw union value's contents. - */ - private static class UnionValueIterator implements Iterator { - - private final int tag; - private final PeekingIterator unions; - private final Boolean[] containsTag; - - private UnionValueIterator(int tag, Iterator unions, Boolean[] containsTag) { - this.tag = tag; - this.unions = Iterators.peekingIterator(unions); - this.containsTag = containsTag; - } - - @Override - public boolean hasNext() { - if (containsTag[tag] == Boolean.FALSE) { - return false; - } - advance(); - if (unions.hasNext()) { - return true; - } else { - // Now that we've iterated over all the values, we can resolve all the "unknown" null - // values to false. - for (int i = 0; i < containsTag.length; i++) { - if (containsTag[i] == null) { - containsTag[i] = false; - } - } - return false; - } - } - - @Override - @SuppressWarnings("unchecked") - public V next() { - advance(); - return (V) unions.next().getValue(); - } - - private void advance() { - while (unions.hasNext()) { - int curTag = unions.peek().getUnionTag(); - containsTag[curTag] = true; - if (curTag == tag) { - break; - } - unions.next(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultSchema.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultSchema.java deleted file mode 100644 index 2860ba70e1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultSchema.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import static com.google.cloud.dataflow.sdk.util.Structs.addList; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - * A schema for the results of a {@link CoGroupByKey}. This maintains the full - * set of {@link TupleTag}s for the results of a {@link CoGroupByKey} and - * facilitates mapping between {@link TupleTag}s and - * {@link RawUnionValue} tags (which are used as secondary keys in the - * {@link CoGroupByKey}). - */ -public class CoGbkResultSchema implements Serializable { - - private final TupleTagList tupleTagList; - - @JsonCreator - public static CoGbkResultSchema of( - @JsonProperty(PropertyNames.TUPLE_TAGS) List> tags) { - TupleTagList tupleTags = TupleTagList.empty(); - for (TupleTag tag : tags) { - tupleTags = tupleTags.and(tag); - } - return new CoGbkResultSchema(tupleTags); - } - - /** - * Maps TupleTags to union tags. This avoids needing to encode the tags - * themselves. - */ - private final HashMap, Integer> tagMap = new HashMap<>(); - - /** - * Builds a schema from a tuple of {@code TupleTag}s. - */ - public CoGbkResultSchema(TupleTagList tupleTagList) { - this.tupleTagList = tupleTagList; - int index = -1; - for (TupleTag tag : tupleTagList.getAll()) { - index++; - tagMap.put(tag, index); - } - } - - /** - * Returns the index for the given tuple tag, if the tag is present in this - * schema, -1 if it isn't. - */ - public int getIndex(TupleTag tag) { - Integer index = tagMap.get(tag); - return index == null ? -1 : index; - } - - /** - * Returns the tuple tag at the given index. - */ - public TupleTag getTag(int index) { - return tupleTagList.get(index); - } - - /** - * Returns the number of columns for this schema. - */ - public int size() { - return tupleTagList.getAll().size(); - } - - /** - * Returns the TupleTagList tuple associated with this schema. - */ - public TupleTagList getTupleTagList() { - return tupleTagList; - } - - public CloudObject asCloudObject() { - CloudObject result = CloudObject.forClass(getClass()); - List serializedTags = new ArrayList<>(tupleTagList.size()); - for (TupleTag tag : tupleTagList.getAll()) { - serializedTags.add(tag.asCloudObject()); - } - addList(result, PropertyNames.TUPLE_TAGS, serializedTags); - return result; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof CoGbkResultSchema)) { - return false; - } - CoGbkResultSchema other = (CoGbkResultSchema) obj; - return tupleTagList.getAll().equals(other.tupleTagList.getAll()); - } - - @Override - public int hashCode() { - return tupleTagList.getAll().hashCode(); - } - - @Override - public String toString() { - return "CoGbkResultSchema: " + tupleTagList.getAll(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKey.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKey.java deleted file mode 100644 index b84068295a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKey.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult.CoGbkResultCoder; -import com.google.cloud.dataflow.sdk.transforms.join.KeyedPCollectionTuple.TaggedKeyedPCollection; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -import java.util.ArrayList; -import java.util.List; - -/** - * A {@link PTransform} that performs a {@link CoGroupByKey} on a tuple - * of tables. A {@link CoGroupByKey} groups results from all - * tables by like keys into {@link CoGbkResult}s, - * from which the results for any specific table can be accessed by the - * {@link com.google.cloud.dataflow.sdk.values.TupleTag} - * supplied with the initial table. - * - *

              Example of performing a {@link CoGroupByKey} followed by a - * {@link ParDo} that consumes - * the results: - *

               {@code
              - * PCollection> pt1 = ...;
              - * PCollection> pt2 = ...;
              - *
              - * final TupleTag t1 = new TupleTag<>();
              - * final TupleTag t2 = new TupleTag<>();
              - * PCollection> coGbkResultCollection =
              - *   KeyedPCollectionTuple.of(t1, pt1)
              - *                        .and(t2, pt2)
              - *                        .apply(CoGroupByKey.create());
              - *
              - * PCollection finalResultCollection =
              - *   coGbkResultCollection.apply(ParDo.of(
              - *     new DoFn, T>() {
              - *       @Override
              - *       public void processElement(ProcessContext c) {
              - *         KV e = c.element();
              - *         Iterable pt1Vals = e.getValue().getAll(t1);
              - *         V2 pt2Val = e.getValue().getOnly(t2);
              - *          ... Do Something ....
              - *         c.output(...some T...);
              - *       }
              - *     }));
              - * } 
              - * - * @param the type of the keys in the input and output - * {@code PCollection}s - */ -public class CoGroupByKey extends - PTransform, - PCollection>> { - /** - * Returns a {@code CoGroupByKey} {@code PTransform}. - * - * @param the type of the keys in the input and output - * {@code PCollection}s - */ - public static CoGroupByKey create() { - return new CoGroupByKey<>(); - } - - private CoGroupByKey() { } - - @Override - public PCollection> apply( - KeyedPCollectionTuple input) { - if (input.isEmpty()) { - throw new IllegalArgumentException( - "must have at least one input to a KeyedPCollections"); - } - - // First build the union coder. - // TODO: Look at better integration of union types with the - // schema specified in the input. - List> codersList = new ArrayList<>(); - for (TaggedKeyedPCollection entry : input.getKeyedCollections()) { - codersList.add(getValueCoder(entry.pCollection)); - } - UnionCoder unionCoder = UnionCoder.of(codersList); - Coder keyCoder = input.getKeyCoder(); - KvCoder kVCoder = - KvCoder.of(keyCoder, unionCoder); - - PCollectionList> unionTables = - PCollectionList.empty(input.getPipeline()); - - // TODO: Use the schema to order the indices rather than depending - // on the fact that the schema ordering is identical to the ordering from - // input.getJoinCollections(). - int index = -1; - for (TaggedKeyedPCollection entry : input.getKeyedCollections()) { - index++; - PCollection> unionTable = - makeUnionTable(index, entry.pCollection, kVCoder); - unionTables = unionTables.and(unionTable); - } - - PCollection> flattenedTable = - unionTables.apply(Flatten.>pCollections()); - - PCollection>> groupedTable = - flattenedTable.apply(GroupByKey.create()); - - CoGbkResultSchema tupleTags = input.getCoGbkResultSchema(); - PCollection> result = groupedTable.apply( - ParDo.of(new ConstructCoGbkResultFn(tupleTags)) - .named("ConstructCoGbkResultFn")); - result.setCoder(KvCoder.of(keyCoder, - CoGbkResultCoder.of(tupleTags, unionCoder))); - - return result; - } - - ////////////////////////////////////////////////////////////////////////////// - - /** - * Returns the value coder for the given PCollection. Assumes that the value - * coder is an instance of {@code KvCoder}. - */ - private Coder getValueCoder(PCollection> pCollection) { - // Assumes that the PCollection uses a KvCoder. - Coder entryCoder = pCollection.getCoder(); - if (!(entryCoder instanceof KvCoder)) { - throw new IllegalArgumentException("PCollection does not use a KvCoder"); - } - @SuppressWarnings("unchecked") - KvCoder coder = (KvCoder) entryCoder; - return coder.getValueCoder(); - } - - /** - * Returns a UnionTable for the given input PCollection, using the given - * union index and the given unionTableEncoder. - */ - private PCollection> makeUnionTable( - final int index, - PCollection> pCollection, - KvCoder unionTableEncoder) { - - return pCollection.apply(ParDo.of( - new ConstructUnionTableFn(index)).named("MakeUnionTable" + index)) - .setCoder(unionTableEncoder); - } - - /** - * A DoFn to construct a UnionTable (i.e., a - * {@code PCollection>} from a - * {@code PCollection>}. - */ - private static class ConstructUnionTableFn extends - DoFn, KV> { - - private final int index; - - public ConstructUnionTableFn(int index) { - this.index = index; - } - - @Override - public void processElement(ProcessContext c) { - KV e = c.element(); - c.output(KV.of(e.getKey(), new RawUnionValue(index, e.getValue()))); - } - } - - /** - * A DoFn to construct a CoGbkResult from an input grouped union - * table. - */ - private static class ConstructCoGbkResultFn - extends DoFn>, - KV> { - - private final CoGbkResultSchema schema; - - public ConstructCoGbkResultFn(CoGbkResultSchema schema) { - this.schema = schema; - } - - @Override - public void processElement(ProcessContext c) { - KV> e = c.element(); - c.output(KV.of(e.getKey(), new CoGbkResult(schema, e.getValue()))); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/KeyedPCollectionTuple.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/KeyedPCollectionTuple.java deleted file mode 100644 index abfbe08b28..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/KeyedPCollectionTuple.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * An immutable tuple of keyed {@link PCollection PCollections} - * with key type K. - * ({@link PCollection PCollections} containing values of type - * {@code KV}) - * - * @param the type of key shared by all constituent PCollections - */ -public class KeyedPCollectionTuple implements PInput { - /** - * Returns an empty {@code KeyedPCollectionTuple} on the given pipeline. - */ - public static KeyedPCollectionTuple empty(Pipeline pipeline) { - return new KeyedPCollectionTuple<>(pipeline); - } - - /** - * Returns a new {@code KeyedPCollectionTuple} with the given tag and initial - * PCollection. - */ - public static KeyedPCollectionTuple of( - TupleTag tag, - PCollection> pc) { - return new KeyedPCollectionTuple(pc.getPipeline()).and(tag, pc); - } - - /** - * Returns a new {@code KeyedPCollectionTuple} that is the same as this, - * appended with the given PCollection. - */ - public KeyedPCollectionTuple and( - TupleTag< V> tag, - PCollection> pc) { - if (pc.getPipeline() != getPipeline()) { - throw new IllegalArgumentException( - "PCollections come from different Pipelines"); - } - TaggedKeyedPCollection wrapper = - new TaggedKeyedPCollection<>(tag, pc); - Coder myKeyCoder = keyCoder == null ? getKeyCoder(pc) : keyCoder; - List> - newKeyedCollections = - copyAddLast( - keyedCollections, - wrapper); - return new KeyedPCollectionTuple<>( - getPipeline(), - newKeyedCollections, - schema.getTupleTagList().and(tag), - myKeyCoder); - } - - public boolean isEmpty() { - return keyedCollections.isEmpty(); - } - - /** - * Returns a list of {@link TaggedKeyedPCollection TaggedKeyedPCollections} for the - * {@link PCollection PCollections} contained in this {@link KeyedPCollectionTuple}. - */ - public List> getKeyedCollections() { - return keyedCollections; - } - - /** - * Like {@link #apply(String, PTransform)} but defaulting to the name - * provided by the {@link PTransform}. - */ - public OutputT apply( - PTransform, OutputT> transform) { - return Pipeline.applyTransform(this, transform); - } - - /** - * Applies the given {@link PTransform} to this input {@code KeyedPCollectionTuple} and returns - * its {@code OutputT}. This uses {@code name} to identify the specific application of - * the transform. This name is used in various places, including the monitoring UI, - * logging, and to stably identify this application node in the job graph. - */ - public OutputT apply( - String name, PTransform, OutputT> transform) { - return Pipeline.applyTransform(name, this, transform); - } - - /** - * Expands the component {@link PCollection PCollections}, stripping off - * any tag-specific information. - */ - @Override - public Collection expand() { - List> retval = new ArrayList<>(); - for (TaggedKeyedPCollection taggedPCollection : keyedCollections) { - retval.add(taggedPCollection.pCollection); - } - return retval; - } - - /** - * Returns the key {@link Coder} for all {@link PCollection PCollections} - * in this {@link KeyedPCollectionTuple}. - */ - public Coder getKeyCoder() { - if (keyCoder == null) { - throw new IllegalStateException("cannot return null keyCoder"); - } - return keyCoder; - } - - /** - * Returns the {@link CoGbkResultSchema} associated with this - * {@link KeyedPCollectionTuple}. - */ - public CoGbkResultSchema getCoGbkResultSchema() { - return schema; - } - - @Override - public Pipeline getPipeline() { - return pipeline; - } - - @Override - public void finishSpecifying() { - for (TaggedKeyedPCollection taggedPCollection : keyedCollections) { - taggedPCollection.pCollection.finishSpecifying(); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A utility class to help ensure coherence of tag and input PCollection - * types. - */ - public static class TaggedKeyedPCollection { - - final TupleTag tupleTag; - final PCollection> pCollection; - - public TaggedKeyedPCollection( - TupleTag tupleTag, - PCollection> pCollection) { - this.tupleTag = tupleTag; - this.pCollection = pCollection; - } - - /** - * Returns the underlying PCollection of this TaggedKeyedPCollection. - */ - public PCollection> getCollection() { - return pCollection; - } - - /** - * Returns the TupleTag of this TaggedKeyedPCollection. - */ - public TupleTag getTupleTag() { - return tupleTag; - } - } - - /** - * We use a List to properly track the order in which collections are added. - */ - private final List> keyedCollections; - - private final Coder keyCoder; - - private final CoGbkResultSchema schema; - - private final Pipeline pipeline; - - KeyedPCollectionTuple(Pipeline pipeline) { - this(pipeline, - new ArrayList>(), - TupleTagList.empty(), - null); - } - - KeyedPCollectionTuple( - Pipeline pipeline, - List> keyedCollections, - TupleTagList tupleTagList, - Coder keyCoder) { - this.pipeline = pipeline; - this.keyedCollections = keyedCollections; - this.schema = new CoGbkResultSchema(tupleTagList); - this.keyCoder = keyCoder; - } - - private static Coder getKeyCoder(PCollection> pc) { - // Need to run coder inference on this PCollection before inspecting it. - pc.finishSpecifying(); - - // Assumes that the PCollection uses a KvCoder. - Coder entryCoder = pc.getCoder(); - if (!(entryCoder instanceof KvCoder)) { - throw new IllegalArgumentException("PCollection does not use a KvCoder"); - } - @SuppressWarnings("unchecked") - KvCoder coder = (KvCoder) entryCoder; - return coder.getKeyCoder(); - } - - private static List> copyAddLast( - List> keyedCollections, - TaggedKeyedPCollection taggedCollection) { - List> retval = - new ArrayList<>(keyedCollections); - retval.add(taggedCollection); - return retval; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/RawUnionValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/RawUnionValue.java deleted file mode 100644 index 514853e446..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/RawUnionValue.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -// TODO: Think about making this a complete dynamic union by adding -// a schema. Type would then be defined by the corresponding schema entry. - -/** - * This corresponds to an integer union tag and value. The mapping of - * union tag to type must come from elsewhere. - */ -public class RawUnionValue { - private final int unionTag; - private final Object value; - - /** - * Constructs a partial union from the given union tag and value. - */ - public RawUnionValue(int unionTag, Object value) { - this.unionTag = unionTag; - this.value = value; - } - - public int getUnionTag() { - return unionTag; - } - - public Object getValue() { - return value; - } - - @Override - public String toString() { - return unionTag + ":" + value; - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoder.java deleted file mode 100644 index e2c8a8c586..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoder.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -/** - * A UnionCoder encodes RawUnionValues. - */ -public class UnionCoder extends StandardCoder { - // TODO: Think about how to integrate this with a schema object (i.e. - // a tuple of tuple tags). - /** - * Builds a union coder with the given list of element coders. This list - * corresponds to a mapping of union tag to Coder. Union tags start at 0. - */ - public static UnionCoder of(List> elementCoders) { - return new UnionCoder(elementCoders); - } - - @JsonCreator - public static UnionCoder jsonOf( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> elements) { - return UnionCoder.of(elements); - } - - private int getIndexForEncoding(RawUnionValue union) { - if (union == null) { - throw new IllegalArgumentException("cannot encode a null tagged union"); - } - int index = union.getUnionTag(); - if (index < 0 || index >= elementCoders.size()) { - throw new IllegalArgumentException( - "union value index " + index + " not in range [0.." - + (elementCoders.size() - 1) + "]"); - } - return index; - } - - @SuppressWarnings("unchecked") - @Override - public void encode( - RawUnionValue union, - OutputStream outStream, - Context context) - throws IOException, CoderException { - int index = getIndexForEncoding(union); - // Write out the union tag. - VarInt.encode(index, outStream); - - // Write out the actual value. - Coder coder = (Coder) elementCoders.get(index); - coder.encode( - union.getValue(), - outStream, - context); - } - - @Override - public RawUnionValue decode(InputStream inStream, Context context) - throws IOException, CoderException { - int index = VarInt.decodeInt(inStream); - Object value = elementCoders.get(index).decode(inStream, context); - return new RawUnionValue(index, value); - } - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public List> getComponents() { - return elementCoders; - } - - /** - * Since this coder uses elementCoders.get(index) and coders that are known to run in constant - * time, we defer the return value to that coder. - */ - @Override - public boolean isRegisterByteSizeObserverCheap(RawUnionValue union, Context context) { - int index = getIndexForEncoding(union); - @SuppressWarnings("unchecked") - Coder coder = (Coder) elementCoders.get(index); - return coder.isRegisterByteSizeObserverCheap(union.getValue(), context); - } - - /** - * Notifies ElementByteSizeObserver about the byte size of the encoded value using this coder. - */ - @Override - public void registerByteSizeObserver( - RawUnionValue union, ElementByteSizeObserver observer, Context context) - throws Exception { - int index = getIndexForEncoding(union); - // Write out the union tag. - observer.update(VarInt.getLength(index)); - // Write out the actual value. - @SuppressWarnings("unchecked") - Coder coder = (Coder) elementCoders.get(index); - coder.registerByteSizeObserver(union.getValue(), observer, context); - } - - ///////////////////////////////////////////////////////////////////////////// - - private final List> elementCoders; - - private UnionCoder(List> elementCoders) { - this.elementCoders = elementCoders; - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "UnionCoder is only deterministic if all element coders are", - elementCoders); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/package-info.java deleted file mode 100644 index be8bffad29..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines the {@link com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey} transform - * for joining multiple PCollections. - */ -package com.google.cloud.dataflow.sdk.transforms.join; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/package-info.java deleted file mode 100644 index 3c041f6736..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/package-info.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines {@link com.google.cloud.dataflow.sdk.transforms.PTransform}s for transforming - * data in a pipeline. - * - *

              A {@link com.google.cloud.dataflow.sdk.transforms.PTransform} is an operation that takes an - * {@code InputT} (some subtype of {@link com.google.cloud.dataflow.sdk.values.PInput}) - * and produces an - * {@code OutputT} (some subtype of {@link com.google.cloud.dataflow.sdk.values.POutput}). - * - *

              Common PTransforms include root PTransforms like - * {@link com.google.cloud.dataflow.sdk.io.TextIO.Read} and - * {@link com.google.cloud.dataflow.sdk.transforms.Create}, processing and - * conversion operations like {@link com.google.cloud.dataflow.sdk.transforms.ParDo}, - * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}, - * {@link com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey}, - * {@link com.google.cloud.dataflow.sdk.transforms.Combine}, and - * {@link com.google.cloud.dataflow.sdk.transforms.Count}, and outputting - * PTransforms like - * {@link com.google.cloud.dataflow.sdk.io.TextIO.Write}. - * - *

              New PTransforms can be created by composing existing PTransforms. - * Most PTransforms in this package are composites, and users can also create composite PTransforms - * for their own application-specific logic. - * - */ -package com.google.cloud.dataflow.sdk.transforms; - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java deleted file mode 100644 index 57fca2d338..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAll.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.common.base.Joiner; - -import org.joda.time.Instant; - -import java.util.Arrays; -import java.util.List; - -/** - * Create a {@link Trigger} that fires and finishes once after all of its sub-triggers have fired. - * - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@code Trigger} - */ -@Experimental(Experimental.Kind.TRIGGER) -public class AfterAll extends OnceTrigger { - - private AfterAll(List> subTriggers) { - super(subTriggers); - checkArgument(subTriggers.size() > 1); - } - - /** - * Returns an {@code AfterAll} {@code Trigger} with the given subtriggers. - */ - @SafeVarargs - public static OnceTrigger of( - OnceTrigger... triggers) { - return new AfterAll(Arrays.>asList(triggers)); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - for (ExecutableTrigger subTrigger : c.trigger().unfinishedSubTriggers()) { - // Since subTriggers are all OnceTriggers, they must either CONTINUE or FIRE_AND_FINISH. - // invokeElement will automatically mark the finish bit if they return FIRE_AND_FINISH. - subTrigger.invokeOnElement(c); - } - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - subTrigger.invokeOnMerge(c); - } - boolean allFinished = true; - for (ExecutableTrigger subTrigger1 : c.trigger().subTriggers()) { - allFinished &= c.forTrigger(subTrigger1).trigger().isFinished(); - } - c.trigger().setFinished(allFinished); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - // This trigger will fire after the latest of its sub-triggers. - Instant deadline = BoundedWindow.TIMESTAMP_MIN_VALUE; - for (Trigger subTrigger : subTriggers) { - Instant subDeadline = subTrigger.getWatermarkThatGuaranteesFiring(window); - if (deadline.isBefore(subDeadline)) { - deadline = subDeadline; - } - } - return deadline; - } - - @Override - public OnceTrigger getContinuationTrigger(List> continuationTriggers) { - return new AfterAll(continuationTriggers); - } - - /** - * {@inheritDoc} - * - * @return {@code true} if all subtriggers return {@code true}. - */ - @Override - public boolean shouldFire(TriggerContext context) throws Exception { - for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { - if (!context.forTrigger(subtrigger).trigger().isFinished() - && !subtrigger.invokeShouldFire(context)) { - return false; - } - } - return true; - } - - /** - * Invokes {@link #onFire} for all subtriggers, eliding redundant calls to {@link #shouldFire} - * because they all must be ready to fire. - */ - @Override - public void onOnlyFiring(TriggerContext context) throws Exception { - for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { - subtrigger.invokeOnFire(context); - } - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder("AfterAll.of("); - Joiner.on(", ").appendTo(builder, subTriggers); - builder.append(")"); - - return builder.toString(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java deleted file mode 100644 index fa4a113366..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterDelayFromFirstElement.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; -import com.google.cloud.dataflow.sdk.util.state.CombiningState; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateMerging; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.PeriodFormat; -import org.joda.time.format.PeriodFormatter; - -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import javax.annotation.Nullable; - -/** - * A base class for triggers that happen after a processing time delay from the arrival - * of the first element in a pane. - * - *

              This class is for internal use only and may change at any time. - */ -@Experimental(Experimental.Kind.TRIGGER) -public abstract class AfterDelayFromFirstElement extends OnceTrigger { - - protected static final List> IDENTITY = - ImmutableList.>of(); - - protected static final StateTag, Instant>> DELAYED_UNTIL_TAG = - StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( - "delayed", InstantCoder.of(), Min.MinFn.naturalOrder())); - - private static final PeriodFormatter PERIOD_FORMATTER = PeriodFormat.wordBased(Locale.ENGLISH); - - /** - * To complete an implementation, return the desired time from the TriggerContext. - */ - @Nullable - public abstract Instant getCurrentTime(Trigger.TriggerContext context); - - /** - * To complete an implementation, return a new instance like this one, but incorporating - * the provided timestamp mapping functions. Generally should be used by calling the - * constructor of this class from the constructor of the subclass. - */ - protected abstract AfterDelayFromFirstElement newWith( - List> transform); - - /** - * A list of timestampMappers m1, m2, m3, ... m_n considered to be composed in sequence. The - * overall mapping for an instance `instance` is `m_n(... m3(m2(m1(instant))`, - * implemented via #computeTargetTimestamp - */ - protected final List> timestampMappers; - - private final TimeDomain timeDomain; - - public AfterDelayFromFirstElement( - TimeDomain timeDomain, - List> timestampMappers) { - super(null); - this.timestampMappers = timestampMappers; - this.timeDomain = timeDomain; - } - - private Instant getTargetTimestamp(OnElementContext c) { - return computeTargetTimestamp(c.currentProcessingTime()); - } - - /** - * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater - * than the timestamp. - * - *

              TODO: Consider sharing this with FixedWindows, and bring over the equivalent of - * CalendarWindows. - */ - public AfterDelayFromFirstElement alignedTo(final Duration size, final Instant offset) { - return newWith(new AlignFn(size, offset)); - } - - /** - * Aligns the time to be the smallest multiple of {@code size} greater than the timestamp - * since the epoch. - */ - public AfterDelayFromFirstElement alignedTo(final Duration size) { - return alignedTo(size, new Instant(0)); - } - - /** - * Adds some delay to the original target time. - * - * @param delay the delay to add - * @return An updated time trigger that will wait the additional time before firing. - */ - public AfterDelayFromFirstElement plusDelayOf(final Duration delay) { - return newWith(new DelayFn(delay)); - } - - /** - * @deprecated This will be removed in the next major version. Please use only - * {@link #plusDelayOf} and {@link #alignedTo}. - */ - @Deprecated - public OnceTrigger mappedTo(SerializableFunction timestampMapper) { - return newWith(timestampMapper); - } - - @Override - public boolean isCompatible(Trigger other) { - if (!getClass().equals(other.getClass())) { - return false; - } - - AfterDelayFromFirstElement that = (AfterDelayFromFirstElement) other; - return this.timestampMappers.equals(that.timestampMappers); - } - - - private AfterDelayFromFirstElement newWith( - SerializableFunction timestampMapper) { - return newWith( - ImmutableList.>builder() - .addAll(timestampMappers) - .add(timestampMapper) - .build()); - } - - @Override - public void prefetchOnElement(StateAccessor state) { - state.access(DELAYED_UNTIL_TAG).readLater(); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - CombiningState delayUntilState = c.state().access(DELAYED_UNTIL_TAG); - Instant oldDelayUntil = delayUntilState.read(); - - // Since processing time can only advance, resulting in target wake-up times we would - // ignore anyhow, we don't bother with it if it is already set. - if (oldDelayUntil != null) { - return; - } - - Instant targetTimestamp = getTargetTimestamp(c); - delayUntilState.add(targetTimestamp); - c.setTimer(targetTimestamp, timeDomain); - } - - @Override - public void prefetchOnMerge(MergingStateAccessor state) { - super.prefetchOnMerge(state); - StateMerging.prefetchCombiningValues(state, DELAYED_UNTIL_TAG); - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - // NOTE: We could try to delete all timers which are still active, but we would - // need access to a timer context for each merging window. - // for (CombiningValueStateInternal, Instant> state : - // c.state().accessInEachMergingWindow(DELAYED_UNTIL_TAG).values()) { - // Instant timestamp = state.get().read(); - // if (timestamp != null) { - // .deleteTimer(timestamp, timeDomain); - // } - // } - // Instead let them fire and be ignored. - - // If the trigger is already finished, there is no way it will become re-activated - if (c.trigger().isFinished()) { - StateMerging.clear(c.state(), DELAYED_UNTIL_TAG); - // NOTE: We do not attempt to delete the timers. - return; - } - - // Determine the earliest point across all the windows, and delay to that. - StateMerging.mergeCombiningValues(c.state(), DELAYED_UNTIL_TAG); - - Instant earliestTargetTime = c.state().access(DELAYED_UNTIL_TAG).read(); - if (earliestTargetTime != null) { - c.setTimer(earliestTargetTime, timeDomain); - } - } - - @Override - public void prefetchShouldFire(StateAccessor state) { - state.access(DELAYED_UNTIL_TAG).readLater(); - } - - @Override - public void clear(TriggerContext c) throws Exception { - c.state().access(DELAYED_UNTIL_TAG).clear(); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - Instant delayedUntil = context.state().access(DELAYED_UNTIL_TAG).read(); - return delayedUntil != null - && getCurrentTime(context) != null - && getCurrentTime(context).isAfter(delayedUntil); - } - - @Override - protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { - clear(context); - } - - protected Instant computeTargetTimestamp(Instant time) { - Instant result = time; - for (SerializableFunction timestampMapper : timestampMappers) { - result = timestampMapper.apply(result); - } - return result; - } - - /** - * A {@link SerializableFunction} to delay the timestamp at which this triggers fires. - */ - private static final class DelayFn implements SerializableFunction { - private final Duration delay; - - public DelayFn(Duration delay) { - this.delay = delay; - } - - @Override - public Instant apply(Instant input) { - return input.plus(delay); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - - if (!(object instanceof DelayFn)) { - return false; - } - - return this.delay.equals(((DelayFn) object).delay); - } - - @Override - public int hashCode() { - return Objects.hash(delay); - } - - @Override - public String toString() { - return PERIOD_FORMATTER.print(delay.toPeriod()); - } - } - - /** - * A {@link SerializableFunction} to align an instant to the nearest interval boundary. - */ - static final class AlignFn implements SerializableFunction { - private final Duration size; - private final Instant offset; - - - /** - * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater - * than the timestamp. - */ - public AlignFn(Duration size, Instant offset) { - this.size = size; - this.offset = offset; - } - - @Override - public Instant apply(Instant point) { - long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis(); - return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - - if (!(object instanceof AlignFn)) { - return false; - } - - AlignFn other = (AlignFn) object; - return other.size.equals(this.size) - && other.offset.equals(this.offset); - } - - @Override - public int hashCode() { - return Objects.hash(size, offset); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java deleted file mode 100644 index 9adecdcab4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEach.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; - -import com.google.common.base.Joiner; -import org.joda.time.Instant; - -import java.util.Arrays; -import java.util.List; - -/** - * A composite {@link Trigger} that executes its sub-triggers in order. - * Only one sub-trigger is executing at a time, - * and any time it fires the {@code AfterEach} fires. When the currently executing - * sub-trigger finishes, the {@code AfterEach} starts executing the next sub-trigger. - * - *

              {@code AfterEach.inOrder(t1, t2, ...)} finishes when all of the sub-triggers have finished. - * - *

              The following properties hold: - *

                - *
              • {@code AfterEach.inOrder(AfterEach.inOrder(a, b), c)} behaves the same as - * {@code AfterEach.inOrder(a, b, c)} and {@code AfterEach.inOrder(a, AfterEach.inOrder(b, c)}. - *
              • {@code AfterEach.inOrder(Repeatedly.forever(a), b)} behaves the same as - * {@code Repeatedly.forever(a)}, since the repeated trigger never finishes. - *
              - * - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@code Trigger} - */ -@Experimental(Experimental.Kind.TRIGGER) -public class AfterEach extends Trigger { - - private AfterEach(List> subTriggers) { - super(subTriggers); - checkArgument(subTriggers.size() > 1); - } - - /** - * Returns an {@code AfterEach} {@code Trigger} with the given subtriggers. - */ - @SafeVarargs - public static Trigger inOrder(Trigger... triggers) { - return new AfterEach(Arrays.>asList(triggers)); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - if (!c.trigger().isMerging()) { - // If merges are not possible, we need only run the first unfinished subtrigger - c.trigger().firstUnfinishedSubTrigger().invokeOnElement(c); - } else { - // If merges are possible, we need to run all subtriggers in parallel - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - // Even if the subTrigger is done, it may be revived via merging and must have - // adequate state. - subTrigger.invokeOnElement(c); - } - } - } - - @Override - public void onMerge(OnMergeContext context) throws Exception { - // If merging makes a subtrigger no-longer-finished, it will automatically - // begin participating in shouldFire and onFire appropriately. - - // All the following triggers are retroactively "not started" but that is - // also automatic because they are cleared whenever this trigger - // fires. - boolean priorTriggersAllFinished = true; - for (ExecutableTrigger subTrigger : context.trigger().subTriggers()) { - if (priorTriggersAllFinished) { - subTrigger.invokeOnMerge(context); - priorTriggersAllFinished &= context.forTrigger(subTrigger).trigger().isFinished(); - } else { - subTrigger.invokeClear(context); - } - } - updateFinishedState(context); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - // This trigger will fire at least once when the first trigger in the sequence - // fires at least once. - return subTriggers.get(0).getWatermarkThatGuaranteesFiring(window); - } - - @Override - public Trigger getContinuationTrigger(List> continuationTriggers) { - return Repeatedly.forever(new AfterFirst(continuationTriggers)); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - ExecutableTrigger firstUnfinished = context.trigger().firstUnfinishedSubTrigger(); - return firstUnfinished.invokeShouldFire(context); - } - - @Override - public void onFire(Trigger.TriggerContext context) throws Exception { - context.trigger().firstUnfinishedSubTrigger().invokeOnFire(context); - - // Reset all subtriggers if in a merging context; any may be revived by merging so they are - // all run in parallel for each pending pane. - if (context.trigger().isMerging()) { - for (ExecutableTrigger subTrigger : context.trigger().subTriggers()) { - subTrigger.invokeClear(context); - } - } - - updateFinishedState(context); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder("AfterEach.inOrder("); - Joiner.on(", ").appendTo(builder, subTriggers); - builder.append(")"); - - return builder.toString(); - } - - private void updateFinishedState(TriggerContext context) { - context.trigger().setFinished(context.trigger().firstUnfinishedSubTrigger() == null); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java deleted file mode 100644 index d6a9fc5d0e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirst.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.common.base.Joiner; - -import org.joda.time.Instant; - -import java.util.Arrays; -import java.util.List; - -/** - * Create a composite {@link Trigger} that fires once after at least one of its sub-triggers have - * fired. - * - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@code Trigger} - */ -@Experimental(Experimental.Kind.TRIGGER) -public class AfterFirst extends OnceTrigger { - - AfterFirst(List> subTriggers) { - super(subTriggers); - checkArgument(subTriggers.size() > 1); - } - - /** - * Returns an {@code AfterFirst} {@code Trigger} with the given subtriggers. - */ - @SafeVarargs - public static OnceTrigger of( - OnceTrigger... triggers) { - return new AfterFirst(Arrays.>asList(triggers)); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - subTrigger.invokeOnElement(c); - } - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - subTrigger.invokeOnMerge(c); - } - updateFinishedStatus(c); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - // This trigger will fire after the earliest of its sub-triggers. - Instant deadline = BoundedWindow.TIMESTAMP_MAX_VALUE; - for (Trigger subTrigger : subTriggers) { - Instant subDeadline = subTrigger.getWatermarkThatGuaranteesFiring(window); - if (deadline.isAfter(subDeadline)) { - deadline = subDeadline; - } - } - return deadline; - } - - @Override - public OnceTrigger getContinuationTrigger(List> continuationTriggers) { - return new AfterFirst(continuationTriggers); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { - if (context.forTrigger(subtrigger).trigger().isFinished() - || subtrigger.invokeShouldFire(context)) { - return true; - } - } - return false; - } - - @Override - protected void onOnlyFiring(TriggerContext context) throws Exception { - for (ExecutableTrigger subtrigger : context.trigger().subTriggers()) { - TriggerContext subContext = context.forTrigger(subtrigger); - if (subtrigger.invokeShouldFire(subContext)) { - // If the trigger is ready to fire, then do whatever it needs to do. - subtrigger.invokeOnFire(subContext); - } else { - // If the trigger is not ready to fire, it is nonetheless true that whatever - // pending pane it was tracking is now gone. - subtrigger.invokeClear(subContext); - } - } - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder("AfterFirst.of("); - Joiner.on(", ").appendTo(builder, subTriggers); - builder.append(")"); - - return builder.toString(); - } - - private void updateFinishedStatus(TriggerContext c) { - boolean anyFinished = false; - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - anyFinished |= c.forTrigger(subTrigger).trigger().isFinished(); - } - c.trigger().setFinished(anyFinished); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java deleted file mode 100644 index 28c8560ac4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPane.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateMerging; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; - -import org.joda.time.Instant; - -import java.util.List; -import java.util.Objects; - -/** - * {@link Trigger}s that fire based on properties of the elements in the current pane. - * - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@link Trigger} - */ -@Experimental(Experimental.Kind.TRIGGER) -public class AfterPane extends OnceTrigger{ - -private static final StateTag> - ELEMENTS_IN_PANE_TAG = - StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( - "count", VarLongCoder.of(), new Sum.SumLongFn())); - - private final int countElems; - - private AfterPane(int countElems) { - super(null); - this.countElems = countElems; - } - - /** - * Creates a trigger that fires when the pane contains at least {@code countElems} elements. - */ - public static AfterPane elementCountAtLeast(int countElems) { - return new AfterPane<>(countElems); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - c.state().access(ELEMENTS_IN_PANE_TAG).add(1L); - } - - @Override - public void prefetchOnMerge(MergingStateAccessor state) { - super.prefetchOnMerge(state); - StateMerging.prefetchCombiningValues(state, ELEMENTS_IN_PANE_TAG); - } - - @Override - public void onMerge(OnMergeContext context) throws Exception { - // If we've already received enough elements and finished in some window, - // then this trigger is just finished. - if (context.trigger().finishedInAnyMergingWindow()) { - context.trigger().setFinished(true); - StateMerging.clear(context.state(), ELEMENTS_IN_PANE_TAG); - return; - } - - // Otherwise, compute the sum of elements in all the active panes. - StateMerging.mergeCombiningValues(context.state(), ELEMENTS_IN_PANE_TAG); - } - - @Override - public void prefetchShouldFire(StateAccessor state) { - state.access(ELEMENTS_IN_PANE_TAG).readLater(); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - long count = context.state().access(ELEMENTS_IN_PANE_TAG).read(); - return count >= countElems; - } - - @Override - public void clear(TriggerContext c) throws Exception { - c.state().access(ELEMENTS_IN_PANE_TAG).clear(); - } - - @Override - public boolean isCompatible(Trigger other) { - return this.equals(other); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - public OnceTrigger getContinuationTrigger(List> continuationTriggers) { - return AfterPane.elementCountAtLeast(1); - } - - @Override - public String toString() { - return "AfterPane.elementCountAtLeast(" + countElems + ")"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof AfterPane)) { - return false; - } - AfterPane that = (AfterPane) obj; - return this.countElems == that.countElems; - } - - @Override - public int hashCode() { - return Objects.hash(countElems); - } - - @Override - protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { - clear(context); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java deleted file mode 100644 index 5db290127f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTime.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.TimeDomain; - -import org.joda.time.Instant; - -import java.util.List; -import java.util.Objects; -import javax.annotation.Nullable; - -/** - * {@code AfterProcessingTime} triggers fire based on the current processing time. They operate in - * the real-time domain. - * - *

              The time at which to fire the timer can be adjusted via the methods in {@link TimeTrigger}, - * such as {@link TimeTrigger#plusDelayOf} or {@link TimeTrigger#alignedTo}. - * - * @param {@link BoundedWindow} subclass used to represent the windows used - */ -@Experimental(Experimental.Kind.TRIGGER) -public class AfterProcessingTime extends AfterDelayFromFirstElement { - - @Override - @Nullable - public Instant getCurrentTime(Trigger.TriggerContext context) { - return context.currentProcessingTime(); - } - - private AfterProcessingTime(List> transforms) { - super(TimeDomain.PROCESSING_TIME, transforms); - } - - /** - * Creates a trigger that fires when the current processing time passes the processing time - * at which this trigger saw the first element in a pane. - */ - public static AfterProcessingTime pastFirstElementInPane() { - return new AfterProcessingTime(IDENTITY); - } - - @Override - protected AfterProcessingTime newWith( - List> transforms) { - return new AfterProcessingTime(transforms); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - protected Trigger getContinuationTrigger(List> continuationTriggers) { - return new AfterSynchronizedProcessingTime(); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder("AfterProcessingTime.pastFirstElementInPane()"); - for (SerializableFunction delayFn : timestampMappers) { - builder - .append(".plusDelayOf(") - .append(delayFn) - .append(")"); - } - - return builder.toString(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof AfterProcessingTime)) { - return false; - } - AfterProcessingTime that = (AfterProcessingTime) obj; - return Objects.equals(this.timestampMappers, that.timestampMappers); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), this.timestampMappers); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java deleted file mode 100644 index 0a274c9ce0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTime.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.common.base.Objects; - -import org.joda.time.Instant; - -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - -class AfterSynchronizedProcessingTime - extends AfterDelayFromFirstElement { - - @Override - @Nullable - public Instant getCurrentTime(Trigger.TriggerContext context) { - return context.currentSynchronizedProcessingTime(); - } - - public AfterSynchronizedProcessingTime() { - super(TimeDomain.SYNCHRONIZED_PROCESSING_TIME, - Collections.>emptyList()); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - protected Trigger getContinuationTrigger(List> continuationTriggers) { - return this; - } - - @Override - public String toString() { - return "AfterSynchronizedProcessingTime.pastFirstElementInPane()"; - } - - @Override - public boolean equals(Object obj) { - return this == obj || obj instanceof AfterSynchronizedProcessingTime; - } - - @Override - public int hashCode() { - return Objects.hashCode(AfterSynchronizedProcessingTime.class); - } - - @Override - protected AfterSynchronizedProcessingTime - newWith(List> transforms) { - // ignore transforms - return this; - } - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java deleted file mode 100644 index 5fd8554c90..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; - -import java.util.List; -import java.util.Objects; - -import javax.annotation.Nullable; - -/** - * {@code AfterWatermark} triggers fire based on progress of the system watermark. This time is a - * lower-bound, sometimes heuristically established, on event times that have been fully processed - * by the pipeline. - * - *

              For sources that provide non-heuristic watermarks (e.g. - * {@link com.google.cloud.dataflow.sdk.io.PubsubIO} when using arrival times as event times), the - * watermark is a strict guarantee that no data with an event time earlier than - * that watermark will ever be observed in the pipeline. In this case, it's safe to assume that any - * pane triggered by an {@code AfterWatermark} trigger with a reference point at or beyond the end - * of the window will be the last pane ever for that window. - * - *

              For sources that provide heuristic watermarks (e.g. - * {@link com.google.cloud.dataflow.sdk.io.PubsubIO} when using user-supplied event times), the - * watermark itself becomes an estimate that no data with an event time earlier than that - * watermark (i.e. "late data") will ever be observed in the pipeline. These heuristics can - * often be quite accurate, but the chance of seeing late data for any given window is non-zero. - * Thus, if absolute correctness over time is important to your use case, you may want to consider - * using a trigger that accounts for late data. The default trigger, - * {@code Repeatedly.forever(AfterWatermark.pastEndOfWindow())}, which fires - * once when the watermark passes the end of the window and then immediately therafter when any - * late data arrives, is one such example. - * - *

              The watermark is the clock that defines {@link TimeDomain#EVENT_TIME}. - * - *

              Additionaly firings before or after the watermark can be requested by calling - * {@code AfterWatermark.pastEndOfWindow.withEarlyFirings(OnceTrigger)} or - * {@code AfterWatermark.pastEndOfWindow.withEarlyFirings(OnceTrigger)}. - * - * @param {@link BoundedWindow} subclass used to represent the windows used. - */ -@Experimental(Experimental.Kind.TRIGGER) -public class AfterWatermark { - - private static final String TO_STRING = "AfterWatermark.pastEndOfWindow()"; - - // Static factory class. - private AfterWatermark() {} - - /** - * Creates a trigger that fires when the watermark passes the end of the window. - */ - public static FromEndOfWindow pastEndOfWindow() { - return new FromEndOfWindow(); - } - - /** - * Interface for building an AfterWatermarkTrigger with early firings already filled in. - */ - public interface AfterWatermarkEarly extends TriggerBuilder { - /** - * Creates a new {@code Trigger} like the this, except that it fires repeatedly whenever - * the given {@code Trigger} fires after the watermark has passed the end of the window. - */ - TriggerBuilder withLateFirings(OnceTrigger lateTrigger); - } - - /** - * Interface for building an AfterWatermarkTrigger with late firings already filled in. - */ - public interface AfterWatermarkLate extends TriggerBuilder { - /** - * Creates a new {@code Trigger} like the this, except that it fires repeatedly whenever - * the given {@code Trigger} fires before the watermark has passed the end of the window. - */ - TriggerBuilder withEarlyFirings(OnceTrigger earlyTrigger); - } - - - private static class AfterWatermarkEarlyAndLate - extends Trigger - implements TriggerBuilder, AfterWatermarkEarly, AfterWatermarkLate { - - private static final int EARLY_INDEX = 0; - private static final int LATE_INDEX = 1; - - private final OnceTrigger earlyTrigger; - @Nullable - private final OnceTrigger lateTrigger; - - @SuppressWarnings("unchecked") - private AfterWatermarkEarlyAndLate(OnceTrigger earlyTrigger, OnceTrigger lateTrigger) { - super(lateTrigger == null - ? ImmutableList.>of(earlyTrigger) - : ImmutableList.>of(earlyTrigger, lateTrigger)); - this.earlyTrigger = checkNotNull(earlyTrigger, "earlyTrigger should not be null"); - this.lateTrigger = lateTrigger; - } - - @Override - public TriggerBuilder withEarlyFirings(OnceTrigger earlyTrigger) { - return new AfterWatermarkEarlyAndLate(earlyTrigger, lateTrigger); - } - - @Override - public TriggerBuilder withLateFirings(OnceTrigger lateTrigger) { - return new AfterWatermarkEarlyAndLate(earlyTrigger, lateTrigger); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - if (!c.trigger().isMerging()) { - // If merges can never happen, we just run the unfinished subtrigger - c.trigger().firstUnfinishedSubTrigger().invokeOnElement(c); - } else { - // If merges can happen, we run for all subtriggers because they might be - // de-activated or re-activated - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - subTrigger.invokeOnElement(c); - } - } - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - // NOTE that the ReduceFnRunner will delete all end-of-window timers for the - // merged-away windows. - - ExecutableTrigger earlySubtrigger = c.trigger().subTrigger(EARLY_INDEX); - // We check the early trigger to determine if we are still processing it or - // if the end of window has transitioned us to the late trigger - OnMergeContext earlyContext = c.forTrigger(earlySubtrigger); - - // If the early trigger is still active in any merging window then it is still active in - // the new merged window, because even if the merged window is "done" some pending elements - // haven't had a chance to fire. - if (!earlyContext.trigger().finishedInAllMergingWindows() || !endOfWindowReached(c)) { - earlyContext.trigger().setFinished(false); - if (lateTrigger != null) { - ExecutableTrigger lateSubtrigger = c.trigger().subTrigger(LATE_INDEX); - OnMergeContext lateContext = c.forTrigger(lateSubtrigger); - lateContext.trigger().setFinished(false); - lateSubtrigger.invokeClear(lateContext); - } - } else { - // Otherwise the early trigger and end-of-window bit is done for good. - earlyContext.trigger().setFinished(true); - if (lateTrigger != null) { - c.trigger().subTrigger(LATE_INDEX).invokeOnMerge(c); - } - } - } - - @Override - public Trigger getContinuationTrigger() { - return new AfterWatermarkEarlyAndLate( - earlyTrigger.getContinuationTrigger(), - lateTrigger == null ? null : lateTrigger.getContinuationTrigger()); - } - - @Override - protected Trigger getContinuationTrigger(List> continuationTriggers) { - throw new UnsupportedOperationException( - "Should not call getContinuationTrigger(List>)"); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - // Even without an early or late trigger, we'll still produce a firing at the watermark. - return window.maxTimestamp(); - } - - private boolean endOfWindowReached(Trigger.TriggerContext context) { - return context.currentEventTime() != null - && context.currentEventTime().isAfter(context.window().maxTimestamp()); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - if (!context.trigger().isFinished(EARLY_INDEX)) { - // We have not yet transitioned to late firings. - // We should fire if either the trigger is ready or we reach the end of the window. - return context.trigger().subTrigger(EARLY_INDEX).invokeShouldFire(context) - || endOfWindowReached(context); - } else if (lateTrigger == null) { - return false; - } else { - // We are running the late trigger - return context.trigger().subTrigger(LATE_INDEX).invokeShouldFire(context); - } - } - - @Override - public void onFire(Trigger.TriggerContext context) throws Exception { - if (!context.forTrigger(context.trigger().subTrigger(EARLY_INDEX)).trigger().isFinished()) { - onNonLateFiring(context); - } else if (lateTrigger != null) { - onLateFiring(context); - } else { - // all done - context.trigger().setFinished(true); - } - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(TO_STRING); - - if (!(earlyTrigger instanceof Never.NeverTrigger)) { - builder - .append(".withEarlyFirings(") - .append(earlyTrigger) - .append(")"); - } - - if (lateTrigger != null && !(lateTrigger instanceof Never.NeverTrigger)) { - builder - .append(".withLateFirings(") - .append(lateTrigger) - .append(")"); - } - - return builder.toString(); - } - - private void onNonLateFiring(Trigger.TriggerContext context) throws Exception { - // We have not yet transitioned to late firings. - ExecutableTrigger earlySubtrigger = context.trigger().subTrigger(EARLY_INDEX); - Trigger.TriggerContext earlyContext = context.forTrigger(earlySubtrigger); - - if (!endOfWindowReached(context)) { - // This is an early firing, since we have not arrived at the end of the window - // Implicitly repeats - earlySubtrigger.invokeOnFire(context); - earlySubtrigger.invokeClear(context); - earlyContext.trigger().setFinished(false); - } else { - // We have arrived at the end of the window; terminate the early trigger - // and clear out the late trigger's state - if (earlySubtrigger.invokeShouldFire(context)) { - earlySubtrigger.invokeOnFire(context); - } - earlyContext.trigger().setFinished(true); - earlySubtrigger.invokeClear(context); - - if (lateTrigger == null) { - // Done if there is no late trigger. - context.trigger().setFinished(true); - } else { - // If there is a late trigger, we transition to it, and need to clear its state - // because it was run in parallel. - context.trigger().subTrigger(LATE_INDEX).invokeClear(context); - } - } - - } - - private void onLateFiring(Trigger.TriggerContext context) throws Exception { - // We are firing the late trigger, with implicit repeat - ExecutableTrigger lateSubtrigger = context.trigger().subTrigger(LATE_INDEX); - lateSubtrigger.invokeOnFire(context); - // It is a OnceTrigger, so it must have finished; unfinished it and clear it - lateSubtrigger.invokeClear(context); - context.forTrigger(lateSubtrigger).trigger().setFinished(false); - } - } - - /** - * A watermark trigger targeted relative to the end of the window. - */ - public static class FromEndOfWindow extends OnceTrigger { - - private FromEndOfWindow() { - super(null); - } - - /** - * Creates a new {@code Trigger} like the this, except that it fires repeatedly whenever - * the given {@code Trigger} fires before the watermark has passed the end of the window. - */ - public AfterWatermarkEarly withEarlyFirings(OnceTrigger earlyFirings) { - checkNotNull(earlyFirings, "Must specify the trigger to use for early firings"); - return new AfterWatermarkEarlyAndLate(earlyFirings, null); - } - - /** - * Creates a new {@code Trigger} like the this, except that it fires repeatedly whenever - * the given {@code Trigger} fires after the watermark has passed the end of the window. - */ - public AfterWatermarkLate withLateFirings(OnceTrigger lateFirings) { - checkNotNull(lateFirings, "Must specify the trigger to use for late firings"); - return new AfterWatermarkEarlyAndLate(Never.ever(), lateFirings); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - // We're interested in knowing when the input watermark passes the end of the window. - // (It is possible this has already happened, in which case the timer will be fired - // almost immediately). - c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - // NOTE that the ReduceFnRunner will delete all end-of-window timers for the - // merged-away windows. - - if (!c.trigger().finishedInAllMergingWindows()) { - // If the trigger is still active in any merging window then it is still active in the new - // merged window, because even if the merged window is "done" some pending elements haven't - // had a chance to fire - c.trigger().setFinished(false); - } else if (!endOfWindowReached(c)) { - // If the end of the new window has not been reached, then the trigger is active again. - c.trigger().setFinished(false); - } else { - // Otherwise it is done for good - c.trigger().setFinished(true); - } - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return window.maxTimestamp(); - } - - @Override - public FromEndOfWindow getContinuationTrigger(List> continuationTriggers) { - return this; - } - - @Override - public String toString() { - return TO_STRING; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof FromEndOfWindow; - } - - @Override - public int hashCode() { - return Objects.hash(getClass()); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return endOfWindowReached(context); - } - - private boolean endOfWindowReached(Trigger.TriggerContext context) { - return context.currentEventTime() != null - && context.currentEventTime().isAfter(context.window().maxTimestamp()); - } - - @Override - protected void onOnlyFiring(Trigger.TriggerContext context) throws Exception { } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/BoundedWindow.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/BoundedWindow.java deleted file mode 100644 index 0afd8e33c2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/BoundedWindow.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import org.joda.time.Instant; - -import java.util.concurrent.TimeUnit; - -/** - * A {@code BoundedWindow} represents a finite grouping of elements, with an - * upper bound (larger timestamps represent more recent data) on the timestamps - * of elements that can be placed in the window. This finiteness means that for - * every window, at some point in time, all data for that window will have - * arrived and can be processed together. - * - *

              Windows must also implement {@link Object#equals} and - * {@link Object#hashCode} such that windows that are logically equal will - * be treated as equal by {@code equals()} and {@code hashCode()}. - */ -public abstract class BoundedWindow { - // The min and max timestamps that won't overflow when they are converted to - // usec. - public static final Instant TIMESTAMP_MIN_VALUE = - new Instant(TimeUnit.MICROSECONDS.toMillis(Long.MIN_VALUE)); - public static final Instant TIMESTAMP_MAX_VALUE = - new Instant(TimeUnit.MICROSECONDS.toMillis(Long.MAX_VALUE)); - - /** - * Returns the inclusive upper bound of timestamps for values in this window. - */ - public abstract Instant maxTimestamp(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java deleted file mode 100644 index a0e8357066..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindows.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.Days; -import org.joda.time.Instant; -import org.joda.time.Months; -import org.joda.time.Years; - -/** - * A collection of {@link WindowFn}s that windows values into calendar-based - * windows such as spans of days, months, or years. - * - *

              For example, to group data into quarters that change on the 15th, use - * {@code CalendarWindows.months(3).withStartingMonth(2014, 1).beginningOnDay(15)}. - */ -public class CalendarWindows { - - private static final DateTime DEFAULT_START_DATE = new DateTime(0, DateTimeZone.UTC); - - /** - * Returns a {@link WindowFn} that windows elements into periods measured by days. - * - *

              For example, {@code CalendarWindows.days(1)} will window elements into - * separate windows for each day. - */ - public static DaysWindows days(int number) { - return new DaysWindows(number, DEFAULT_START_DATE, DateTimeZone.UTC); - } - - /** - * Returns a {@link WindowFn} that windows elements into periods measured by weeks. - * - *

              For example, {@code CalendarWindows.weeks(1, DateTimeConstants.TUESDAY)} will - * window elements into week-long windows starting on Tuesdays. - */ - public static DaysWindows weeks(int number, int startDayOfWeek) { - return new DaysWindows( - 7 * number, - DEFAULT_START_DATE.withDayOfWeek(startDayOfWeek), - DateTimeZone.UTC); - } - - /** - * Returns a {@link WindowFn} that windows elements into periods measured by months. - * - *

              For example, - * {@code CalendarWindows.months(8).withStartingMonth(2014, 1).beginningOnDay(10)} - * will window elements into 8 month windows where that start on the 10th day of month, - * and the first window begins in January 2014. - */ - public static MonthsWindows months(int number) { - return new MonthsWindows(number, 1, DEFAULT_START_DATE, DateTimeZone.UTC); - } - - /** - * Returns a {@link WindowFn} that windows elements into periods measured by years. - * - *

              For example, - * {@code CalendarWindows.years(1).withTimeZone(DateTimeZone.forId("America/Los_Angeles"))} - * will window elements into year-long windows that start at midnight on Jan 1, in the - * America/Los_Angeles time zone. - */ - public static YearsWindows years(int number) { - return new YearsWindows(number, 1, 1, DEFAULT_START_DATE, DateTimeZone.UTC); - } - - /** - * A {@link WindowFn} that windows elements into periods measured by days. - * - *

              By default, periods of multiple days are measured starting at the - * epoch. This can be overridden with {@link #withStartingDay}. - * - *

              The time zone used to determine calendar boundaries is UTC, unless this - * is overridden with the {@link #withTimeZone} method. - */ - public static class DaysWindows extends PartitioningWindowFn { - public DaysWindows withStartingDay(int year, int month, int day) { - return new DaysWindows( - number, new DateTime(year, month, day, 0, 0, timeZone), timeZone); - } - - public DaysWindows withTimeZone(DateTimeZone timeZone) { - return new DaysWindows( - number, startDate.withZoneRetainFields(timeZone), timeZone); - } - - //////////////////////////////////////////////////////////////////////////// - - private int number; - private DateTime startDate; - private DateTimeZone timeZone; - - private DaysWindows(int number, DateTime startDate, DateTimeZone timeZone) { - this.number = number; - this.startDate = startDate; - this.timeZone = timeZone; - } - - @Override - public IntervalWindow assignWindow(Instant timestamp) { - DateTime datetime = new DateTime(timestamp, timeZone); - - int dayOffset = Days.daysBetween(startDate, datetime).getDays() / number * number; - - DateTime begin = startDate.plusDays(dayOffset); - DateTime end = begin.plusDays(number); - - return new IntervalWindow(begin.toInstant(), end.toInstant()); - } - - @Override - public Coder windowCoder() { - return IntervalWindow.getCoder(); - } - - @Override - public boolean isCompatible(WindowFn other) { - if (!(other instanceof DaysWindows)) { - return false; - } - DaysWindows that = (DaysWindows) other; - return number == that.number - && startDate == that.startDate - && timeZone == that.timeZone; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .add(DisplayData.item("numDays", number) - .withLabel("Windows Days")) - .addIfNotDefault( - DisplayData.item("startDate", new DateTime(startDate, timeZone).toInstant()) - .withLabel("Window Start Date"), - new DateTime(DEFAULT_START_DATE, DateTimeZone.UTC).toInstant()); - } - - public int getNumber() { - return number; - } - - public DateTime getStartDate() { - return startDate; - } - - public DateTimeZone getTimeZone() { - return timeZone; - } - - } - - /** - * A {@link WindowFn} that windows elements into periods measured by months. - * - *

              By default, periods of multiple months are measured starting at the - * epoch. This can be overridden with {@link #withStartingMonth}. - * - *

              Months start on the first day of each calendar month, unless overridden by - * {@link #beginningOnDay}. - * - *

              The time zone used to determine calendar boundaries is UTC, unless this - * is overridden with the {@link #withTimeZone} method. - */ - public static class MonthsWindows extends PartitioningWindowFn { - public MonthsWindows beginningOnDay(int dayOfMonth) { - return new MonthsWindows( - number, dayOfMonth, startDate, timeZone); - } - - public MonthsWindows withStartingMonth(int year, int month) { - return new MonthsWindows( - number, dayOfMonth, new DateTime(year, month, 1, 0, 0, timeZone), timeZone); - } - - public MonthsWindows withTimeZone(DateTimeZone timeZone) { - return new MonthsWindows( - number, dayOfMonth, startDate.withZoneRetainFields(timeZone), timeZone); - } - - //////////////////////////////////////////////////////////////////////////// - - private int number; - private int dayOfMonth; - private DateTime startDate; - private DateTimeZone timeZone; - - private MonthsWindows(int number, int dayOfMonth, DateTime startDate, DateTimeZone timeZone) { - this.number = number; - this.dayOfMonth = dayOfMonth; - this.startDate = startDate; - this.timeZone = timeZone; - } - - @Override - public IntervalWindow assignWindow(Instant timestamp) { - DateTime datetime = new DateTime(timestamp, timeZone); - - int monthOffset = - Months.monthsBetween(startDate.withDayOfMonth(dayOfMonth), datetime).getMonths() - / number * number; - - DateTime begin = startDate.withDayOfMonth(dayOfMonth).plusMonths(monthOffset); - DateTime end = begin.plusMonths(number); - - return new IntervalWindow(begin.toInstant(), end.toInstant()); - } - - @Override - public Coder windowCoder() { - return IntervalWindow.getCoder(); - } - - @Override - public boolean isCompatible(WindowFn other) { - if (!(other instanceof MonthsWindows)) { - return false; - } - MonthsWindows that = (MonthsWindows) other; - return number == that.number - && dayOfMonth == that.dayOfMonth - && startDate == that.startDate - && timeZone == that.timeZone; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .add(DisplayData.item("numMonths", number) - .withLabel("Window Months")) - .addIfNotDefault( - DisplayData.item("startDate", new DateTime(startDate, timeZone).toInstant()) - .withLabel("Window Start Date"), - new DateTime(DEFAULT_START_DATE, DateTimeZone.UTC).toInstant()); - } - - public int getNumber() { - return number; - } - - public int getDayOfMonth() { - return dayOfMonth; - } - - public DateTime getStartDate() { - return startDate; - } - - public DateTimeZone getTimeZone() { - return timeZone; - } - - } - - /** - * A {@link WindowFn} that windows elements into periods measured by years. - * - *

              By default, periods of multiple years are measured starting at the - * epoch. This can be overridden with {@link #withStartingYear}. - * - *

              Years start on the first day of each calendar year, unless overridden by - * {@link #beginningOnDay}. - * - *

              The time zone used to determine calendar boundaries is UTC, unless this - * is overridden with the {@link #withTimeZone} method. - */ - public static class YearsWindows extends PartitioningWindowFn { - public YearsWindows beginningOnDay(int monthOfYear, int dayOfMonth) { - return new YearsWindows( - number, monthOfYear, dayOfMonth, startDate, timeZone); - } - - public YearsWindows withStartingYear(int year) { - return new YearsWindows( - number, monthOfYear, dayOfMonth, new DateTime(year, 1, 1, 0, 0, timeZone), timeZone); - } - - public YearsWindows withTimeZone(DateTimeZone timeZone) { - return new YearsWindows( - number, monthOfYear, dayOfMonth, startDate.withZoneRetainFields(timeZone), timeZone); - } - - //////////////////////////////////////////////////////////////////////////// - - private int number; - private int monthOfYear; - private int dayOfMonth; - private DateTime startDate; - private DateTimeZone timeZone; - - private YearsWindows( - int number, int monthOfYear, int dayOfMonth, DateTime startDate, DateTimeZone timeZone) { - this.number = number; - this.monthOfYear = monthOfYear; - this.dayOfMonth = dayOfMonth; - this.startDate = startDate; - this.timeZone = timeZone; - } - - @Override - public IntervalWindow assignWindow(Instant timestamp) { - DateTime datetime = new DateTime(timestamp, timeZone); - - DateTime offsetStart = startDate.withMonthOfYear(monthOfYear).withDayOfMonth(dayOfMonth); - - int yearOffset = - Years.yearsBetween(offsetStart, datetime).getYears() / number * number; - - DateTime begin = offsetStart.plusYears(yearOffset); - DateTime end = begin.plusYears(number); - - return new IntervalWindow(begin.toInstant(), end.toInstant()); - } - - @Override - public Coder windowCoder() { - return IntervalWindow.getCoder(); - } - - @Override - public boolean isCompatible(WindowFn other) { - if (!(other instanceof YearsWindows)) { - return false; - } - YearsWindows that = (YearsWindows) other; - return number == that.number - && monthOfYear == that.monthOfYear - && dayOfMonth == that.dayOfMonth - && startDate == that.startDate - && timeZone == that.timeZone; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - builder - .add(DisplayData.item("numYears", number) - .withLabel("Window Years")) - .addIfNotDefault( - DisplayData.item("startDate", new DateTime(startDate, timeZone).toInstant()) - .withLabel("Window Start Date"), - new DateTime(DEFAULT_START_DATE, DateTimeZone.UTC).toInstant()); - } - - public DateTimeZone getTimeZone() { - return timeZone; - } - - public DateTime getStartDate() { - return startDate; - } - - public int getDayOfMonth() { - return dayOfMonth; - } - - public int getMonthOfYear() { - return monthOfYear; - } - - public int getNumber() { - return number; - } - - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java deleted file mode 100644 index 9ac4abd894..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTrigger.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.util.TimeDomain; - -import org.joda.time.Instant; - -import java.util.List; - -/** - * A trigger that is equivalent to {@code Repeatedly.forever(AfterWatermark.pastEndOfWindow())}. - * See {@link Repeatedly#forever} and {@link AfterWatermark#pastEndOfWindow} for more details. - * - * @param The type of windows being triggered/encoded. - */ -@Experimental(Experimental.Kind.TRIGGER) -public class DefaultTrigger extends Trigger{ - - private DefaultTrigger() { - super(null); - } - - /** - * Returns the default trigger. - */ - public static DefaultTrigger of() { - return new DefaultTrigger(); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - // If the end of the window has already been reached, then we are already ready to fire - // and do not need to set a wake-up timer. - if (!endOfWindowReached(c)) { - c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - } - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - // If the end of the window has already been reached, then we are already ready to fire - // and do not need to set a wake-up timer. - if (!endOfWindowReached(c)) { - c.setTimer(c.window().maxTimestamp(), TimeDomain.EVENT_TIME); - } - } - - @Override - public void clear(TriggerContext c) throws Exception { } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - return window.maxTimestamp(); - } - - @Override - public boolean isCompatible(Trigger other) { - // Semantically, all default triggers are identical - return other instanceof DefaultTrigger; - } - - @Override - public Trigger getContinuationTrigger(List> continuationTriggers) { - return this; - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return endOfWindowReached(context); - } - - private boolean endOfWindowReached(Trigger.TriggerContext context) { - return context.currentEventTime() != null - && context.currentEventTime().isAfter(context.window().maxTimestamp()); - } - - @Override - public void onFire(Trigger.TriggerContext context) throws Exception { } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java deleted file mode 100644 index 2218628f25..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindows.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.Objects; - -/** - * A {@link WindowFn} that windows values into fixed-size timestamp-based windows. - * - *

              For example, in order to partition the data into 10 minute windows: - *

               {@code
              - * PCollection items = ...;
              - * PCollection windowedItems = items.apply(
              - *   Window.into(FixedWindows.of(Duration.standardMinutes(10))));
              - * } 
              - */ -public class FixedWindows extends PartitioningWindowFn { - - /** - * Size of this window. - */ - private final Duration size; - - /** - * Offset of this window. Windows start at time - * N * size + offset, where 0 is the epoch. - */ - private final Duration offset; - - /** - * Partitions the timestamp space into half-open intervals of the form - * [N * size, (N + 1) * size), where 0 is the epoch. - */ - public static FixedWindows of(Duration size) { - return new FixedWindows(size, Duration.ZERO); - } - - /** - * Partitions the timestamp space into half-open intervals of the form - * [N * size + offset, (N + 1) * size + offset), - * where 0 is the epoch. - * - * @throws IllegalArgumentException if offset is not in [0, size) - */ - public FixedWindows withOffset(Duration offset) { - return new FixedWindows(size, offset); - } - - private FixedWindows(Duration size, Duration offset) { - if (offset.isShorterThan(Duration.ZERO) || !offset.isShorterThan(size)) { - throw new IllegalArgumentException( - "FixedWindows WindowingStrategies must have 0 <= offset < size"); - } - this.size = size; - this.offset = offset; - } - - @Override - public IntervalWindow assignWindow(Instant timestamp) { - long start = timestamp.getMillis() - - timestamp.plus(size).minus(offset).getMillis() % size.getMillis(); - return new IntervalWindow(new Instant(start), size); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("size", size) - .withLabel("Window Duration")) - .addIfNotDefault(DisplayData.item("offset", offset) - .withLabel("Window Start Offset"), Duration.ZERO); - } - - @Override - public Coder windowCoder() { - return IntervalWindow.getCoder(); - } - - @Override - public boolean isCompatible(WindowFn other) { - return this.equals(other); - } - - public Duration getSize() { - return size; - } - - public Duration getOffset() { - return offset; - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof FixedWindows)) { - return false; - } - FixedWindows other = (FixedWindows) object; - return getOffset().equals(other.getOffset()) - && getSize().equals(other.getSize()); - } - - @Override - public int hashCode() { - return Objects.hash(size, offset); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindow.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindow.java deleted file mode 100644 index d7fc396f49..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindow.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.io.InputStream; -import java.io.OutputStream; - -/** - * The default window into which all data is placed (via {@link GlobalWindows}). - */ -public class GlobalWindow extends BoundedWindow { - /** - * Singleton instance of {@link GlobalWindow}. - */ - public static final GlobalWindow INSTANCE = new GlobalWindow(); - - // Triggers use maxTimestamp to set timers' timestamp. Timers fires when - // the watermark passes their timestamps. So, the maxTimestamp needs to be - // smaller than the TIMESTAMP_MAX_VALUE. - // One standard day is subtracted from TIMESTAMP_MAX_VALUE to make sure - // the maxTimestamp is smaller than TIMESTAMP_MAX_VALUE even after rounding up - // to seconds or minutes. - private static final Instant END_OF_GLOBAL_WINDOW = - TIMESTAMP_MAX_VALUE.minus(Duration.standardDays(1)); - - @Override - public Instant maxTimestamp() { - return END_OF_GLOBAL_WINDOW; - } - - private GlobalWindow() {} - - /** - * {@link Coder} for encoding and decoding {@code GlobalWindow}s. - */ - public static class Coder extends AtomicCoder { - public static final Coder INSTANCE = new Coder(); - - @Override - public void encode(GlobalWindow window, OutputStream outStream, Context context) {} - - @Override - public GlobalWindow decode(InputStream inStream, Context context) { - return GlobalWindow.INSTANCE; - } - - private Coder() {} - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindows.java deleted file mode 100644 index d3d949c7c9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/GlobalWindows.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.coders.Coder; - -import org.joda.time.Instant; - -import java.util.Collection; -import java.util.Collections; - -/** - * Default {@link WindowFn} that assigns all data to the same window. - */ -public class GlobalWindows extends NonMergingWindowFn { - - private static final Collection GLOBAL_WINDOWS = - Collections.singletonList(GlobalWindow.INSTANCE); - - @Override - public Collection assignWindows(AssignContext c) { - return GLOBAL_WINDOWS; - } - - @Override - public boolean isCompatible(WindowFn o) { - return o instanceof GlobalWindows; - } - - @Override - public Coder windowCoder() { - return GlobalWindow.Coder.INSTANCE; - } - - @Override - public GlobalWindow getSideInputWindow(BoundedWindow window) { - return GlobalWindow.INSTANCE; - } - - @Override - public boolean assignsToSingleWindow() { - return true; - } - - @Override - public Instant getOutputTime(Instant inputTimestamp, GlobalWindow window) { - return inputTimestamp; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindow.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindow.java deleted file mode 100644 index 58287c71d6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindow.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.DurationCoder; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.ReadableDuration; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * An implementation of {@link BoundedWindow} that represents an interval from - * {@link #start} (inclusive) to {@link #end} (exclusive). - */ -public class IntervalWindow extends BoundedWindow - implements Comparable { - /** - * Start of the interval, inclusive. - */ - private final Instant start; - - /** - * End of the interval, exclusive. - */ - private final Instant end; - - /** - * Creates a new IntervalWindow that represents the half-open time - * interval [start, end). - */ - public IntervalWindow(Instant start, Instant end) { - this.start = start; - this.end = end; - } - - public IntervalWindow(Instant start, ReadableDuration size) { - this.start = start; - this.end = start.plus(size); - } - - /** - * Returns the start of this window, inclusive. - */ - public Instant start() { - return start; - } - - /** - * Returns the end of this window, exclusive. - */ - public Instant end() { - return end; - } - - /** - * Returns the largest timestamp that can be included in this window. - */ - @Override - public Instant maxTimestamp() { - // end not inclusive - return end.minus(1); - } - - /** - * Returns whether this window contains the given window. - */ - public boolean contains(IntervalWindow other) { - return !this.start.isAfter(other.start) && !this.end.isBefore(other.end); - } - - /** - * Returns whether this window is disjoint from the given window. - */ - public boolean isDisjoint(IntervalWindow other) { - return !this.end.isAfter(other.start) || !other.end.isAfter(this.start); - } - - /** - * Returns whether this window intersects the given window. - */ - public boolean intersects(IntervalWindow other) { - return !isDisjoint(other); - } - - /** - * Returns the minimal window that includes both this window and - * the given window. - */ - public IntervalWindow span(IntervalWindow other) { - return new IntervalWindow( - new Instant(Math.min(start.getMillis(), other.start.getMillis())), - new Instant(Math.max(end.getMillis(), other.end.getMillis()))); - } - - @Override - public boolean equals(Object o) { - return (o instanceof IntervalWindow) - && ((IntervalWindow) o).end.isEqual(end) - && ((IntervalWindow) o).start.isEqual(start); - } - - @Override - public int hashCode() { - // The end values are themselves likely to be arithmetic sequence, which - // is a poor distribution to use for a hashtable, so we - // add a highly non-linear transformation. - return (int) - (start.getMillis() + modInverse((int) (end.getMillis() << 1) + 1)); - } - - /** - * Compute the inverse of (odd) x mod 2^32. - */ - private int modInverse(int x) { - // Cube gives inverse mod 2^4, as x^4 == 1 (mod 2^4) for all odd x. - int inverse = x * x * x; - // Newton iteration doubles correct bits at each step. - inverse *= 2 - x * inverse; - inverse *= 2 - x * inverse; - inverse *= 2 - x * inverse; - return inverse; - } - - @Override - public String toString() { - return "[" + start + ".." + end + ")"; - } - - @Override - public int compareTo(IntervalWindow o) { - if (start.isEqual(o.start)) { - return end.compareTo(o.end); - } - return start.compareTo(o.start); - } - - /** - * Returns a {@link Coder} suitable for {@link IntervalWindow}. - */ - public static Coder getCoder() { - return IntervalWindowCoder.of(); - } - - /** - * Encodes an {@link IntervalWindow} as a pair of its upper bound and duration. - */ - private static class IntervalWindowCoder extends AtomicCoder { - - private static final IntervalWindowCoder INSTANCE = - new IntervalWindowCoder(); - - private static final Coder instantCoder = InstantCoder.of(); - private static final Coder durationCoder = DurationCoder.of(); - - @JsonCreator - public static IntervalWindowCoder of() { - return INSTANCE; - } - - @Override - public void encode(IntervalWindow window, - OutputStream outStream, - Context context) - throws IOException, CoderException { - instantCoder.encode(window.end, outStream, context.nested()); - durationCoder.encode(new Duration(window.start, window.end), outStream, context.nested()); - } - - @Override - public IntervalWindow decode(InputStream inStream, Context context) - throws IOException, CoderException { - Instant end = instantCoder.decode(inStream, context.nested()); - ReadableDuration duration = durationCoder.decode(inStream, context.nested()); - return new IntervalWindow(end.minus(duration), end); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/InvalidWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/InvalidWindows.java deleted file mode 100644 index 596f4e7253..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/InvalidWindows.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.coders.Coder; - -import org.joda.time.Instant; - -import java.util.Collection; - -/** - * A {@link WindowFn} that represents an invalid pipeline state. - * - * @param window type - */ -public class InvalidWindows extends WindowFn { - private String cause; - private WindowFn originalWindowFn; - - public InvalidWindows(String cause, WindowFn originalWindowFn) { - this.originalWindowFn = originalWindowFn; - this.cause = cause; - } - - /** - * Returns the reason that this {@code WindowFn} is invalid. - */ - public String getCause() { - return cause; - } - - /** - * Returns the original windowFn that this InvalidWindows replaced. - */ - public WindowFn getOriginalWindowFn() { - return originalWindowFn; - } - - @Override - public Collection assignWindows(AssignContext c) { - throw new UnsupportedOperationException(); - } - - @Override - public void mergeWindows(MergeContext c) { - throw new UnsupportedOperationException(); - } - - @Override - public Coder windowCoder() { - return originalWindowFn.windowCoder(); - } - - /** - * {@code InvalidWindows} objects with the same {@code originalWindowFn} are compatible. - */ - @Override - public boolean isCompatible(WindowFn other) { - return getClass() == other.getClass() - && getOriginalWindowFn().isCompatible( - ((InvalidWindows) other).getOriginalWindowFn()); - } - - @Override - public W getSideInputWindow(BoundedWindow window) { - throw new UnsupportedOperationException("InvalidWindows is not allowed in side inputs"); - } - - @Override - public Instant getOutputTime(Instant inputTimestamp, W window) { - return inputTimestamp; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/MergeOverlappingIntervalWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/MergeOverlappingIntervalWindows.java deleted file mode 100644 index 4e06234c15..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/MergeOverlappingIntervalWindows.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * A utility function for merging overlapping {@link IntervalWindow}s. - */ -public class MergeOverlappingIntervalWindows { - - /** - * Merge overlapping {@link IntervalWindow}s. - */ - public static void mergeWindows(WindowFn.MergeContext c) throws Exception { - // Merge any overlapping windows into a single window. - // Sort the list of existing windows so we only have to - // traverse the list once rather than considering all - // O(n^2) window pairs. - List sortedWindows = new ArrayList<>(); - for (IntervalWindow window : c.windows()) { - sortedWindows.add(window); - } - Collections.sort(sortedWindows); - List merges = new ArrayList<>(); - MergeCandidate current = new MergeCandidate(); - for (IntervalWindow window : sortedWindows) { - if (current.intersects(window)) { - current.add(window); - } else { - merges.add(current); - current = new MergeCandidate(window); - } - } - merges.add(current); - for (MergeCandidate merge : merges) { - merge.apply(c); - } - } - - private static class MergeCandidate { - private IntervalWindow union; - private final List parts; - public MergeCandidate() { - parts = new ArrayList<>(); - } - public MergeCandidate(IntervalWindow window) { - union = window; - parts = new ArrayList<>(Arrays.asList(window)); - } - public boolean intersects(IntervalWindow window) { - return union == null || union.intersects(window); - } - public void add(IntervalWindow window) { - union = union == null ? window : union.span(window); - parts.add(window); - } - public void apply(WindowFn.MergeContext c) throws Exception { - if (parts.size() > 1) { - c.merge(parts, union); - } - } - - @Override - public String toString() { - return "MergeCandidate[union=" + union + ", parts=" + parts + "]"; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java deleted file mode 100644 index 12a3cc707c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Never.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import org.joda.time.Instant; - -import java.util.List; - -/** - * A trigger which never fires. - * - *

              Using this trigger will only produce output when the watermark passes the end of the - * {@link BoundedWindow window} plus the {@link Window#withAllowedLateness allowed - * lateness}. - */ -public final class Never { - /** - * Returns a trigger which never fires. Output will be produced from the using {@link GroupByKey} - * when the {@link BoundedWindow} closes. - */ - public static Trigger.OnceTrigger ever() { - // NeverTrigger ignores all inputs and is Window-type independent. - return new NeverTrigger(); - } - - static class NeverTrigger extends Trigger.OnceTrigger { - protected NeverTrigger() { - super(null); - } - - @Override - public void onElement(OnElementContext c) {} - - @Override - public void onMerge(OnMergeContext c) {} - - @Override - protected Trigger getContinuationTrigger(List> continuationTriggers) { - return this; - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(BoundedWindow window) { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) { - return false; - } - - @Override - protected void onOnlyFiring(Trigger.TriggerContext context) { - throw new UnsupportedOperationException( - String.format("%s should never fire", getClass().getSimpleName())); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/NonMergingWindowFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/NonMergingWindowFn.java deleted file mode 100644 index 8aa66fcfc8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/NonMergingWindowFn.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -/** - * Abstract base class for {@link WindowFn}s that do not merge windows. - * - * @param type of elements being windowed - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@code WindowFn} - */ -public abstract class NonMergingWindowFn - extends WindowFn { - @Override - public final void mergeWindows(MergeContext c) { } - - @Override - public final boolean isNonMerging() { - return true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java deleted file mode 100644 index afbbb45343..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTrigger.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.common.annotations.VisibleForTesting; - -import org.joda.time.Instant; - -import java.util.Arrays; -import java.util.List; - -/** - * Executes the {@code actual} trigger until it finishes or until the {@code until} trigger fires. - */ -class OrFinallyTrigger extends Trigger { - - private static final int ACTUAL = 0; - private static final int UNTIL = 1; - - @VisibleForTesting OrFinallyTrigger(Trigger actual, Trigger.OnceTrigger until) { - super(Arrays.asList(actual, until)); - } - - @Override - public void onElement(OnElementContext c) throws Exception { - c.trigger().subTrigger(ACTUAL).invokeOnElement(c); - c.trigger().subTrigger(UNTIL).invokeOnElement(c); - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - subTrigger.invokeOnMerge(c); - } - updateFinishedState(c); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - // This trigger fires once either the trigger or the until trigger fires. - Instant actualDeadline = subTriggers.get(ACTUAL).getWatermarkThatGuaranteesFiring(window); - Instant untilDeadline = subTriggers.get(UNTIL).getWatermarkThatGuaranteesFiring(window); - return actualDeadline.isBefore(untilDeadline) ? actualDeadline : untilDeadline; - } - - @Override - public Trigger getContinuationTrigger(List> continuationTriggers) { - // Use OrFinallyTrigger instead of AfterFirst because the continuation of ACTUAL - // may not be a OnceTrigger. - return Repeatedly.forever( - new OrFinallyTrigger( - continuationTriggers.get(ACTUAL), - (Trigger.OnceTrigger) continuationTriggers.get(UNTIL))); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return context.trigger().subTrigger(ACTUAL).invokeShouldFire(context) - || context.trigger().subTrigger(UNTIL).invokeShouldFire(context); - } - - @Override - public void onFire(Trigger.TriggerContext context) throws Exception { - ExecutableTrigger actualSubtrigger = context.trigger().subTrigger(ACTUAL); - ExecutableTrigger untilSubtrigger = context.trigger().subTrigger(UNTIL); - - if (untilSubtrigger.invokeShouldFire(context)) { - untilSubtrigger.invokeOnFire(context); - actualSubtrigger.invokeClear(context); - } else { - // If until didn't fire, then the actual must have (or it is forbidden to call - // onFire) so we are done only if actual is done. - actualSubtrigger.invokeOnFire(context); - // Do not clear the until trigger, because it tracks data cross firings. - } - updateFinishedState(context); - } - - @Override - public String toString() { - return String.format("%s.orFinally(%s)", subTriggers.get(ACTUAL), subTriggers.get(UNTIL)); - } - - private void updateFinishedState(TriggerContext c) throws Exception { - boolean anyStillFinished = false; - for (ExecutableTrigger subTrigger : c.trigger().subTriggers()) { - anyStillFinished |= c.forTrigger(subTrigger).trigger().isFinished(); - } - c.trigger().setFinished(anyStillFinished); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java deleted file mode 100644 index c5d943d3c5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFn.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.common.collect.Ordering; - -import org.joda.time.Instant; - -import java.io.Serializable; -import java.util.Objects; - -/** - * (Experimental) A function from timestamps of input values to the timestamp for a - * computed value. - * - *

              The function is represented via three components: - *

                - *
              1. {@link #assignOutputTime} calculates an output timestamp for any input - * value in a particular window.
              2. - *
              3. The output timestamps for all non-late input values within a window are combined - * according to {@link #combine combine()}, a commutative and associative operation on - * the output timestamps.
              4. - *
              5. The output timestamp when windows merge is provided by {@link #merge merge()}.
              6. - *
              - * - *

              This abstract class cannot be subclassed directly, by design: it may grow - * in consumer-compatible ways that require mutually-exclusive default implementations. To - * create a concrete subclass, extend {@link OutputTimeFn.Defaults} or - * {@link OutputTimeFn.DependsOnlyOnWindow}. Note that as long as this class remains - * experimental, we may also choose to change it in arbitrary backwards-incompatible ways. - * - * @param the type of window. Contravariant: methods accepting any subtype of - * {@code OutputTimeFn} should use the parameter type {@code OutputTimeFn}. - */ -@Experimental(Experimental.Kind.OUTPUT_TIME) -public abstract class OutputTimeFn implements Serializable { - - /** - * Private constructor to prevent subclassing other than provided base classes. - */ - private OutputTimeFn() { } - - /** - * Returns the output timestamp to use for data depending on the given - * {@code inputTimestamp} in the specified {@code window}. - * - * - *

              The result of this method must be between {@code inputTimestamp} and - * {@code window.maxTimestamp()} (inclusive on both sides). - * - *

              This function must be monotonic across input timestamps. Specifically, if {@code A < B}, - * then {@code assignOutputTime(A, window) <= assignOutputTime(B, window)}. - * - *

              For a {@link WindowFn} that doesn't produce overlapping windows, this can (and typically - * should) just return {@code inputTimestamp}. In the presence of overlapping windows, it is - * suggested that the result in later overlapping windows is past the end of earlier windows - * so that the later windows don't prevent the watermark from - * progressing past the end of the earlier window. - * - *

              See the overview of {@link OutputTimeFn} for the consistency properties required - * between {@link #assignOutputTime}, {@link #combine}, and {@link #merge}. - */ - public abstract Instant assignOutputTime(Instant inputTimestamp, W window); - - /** - * Combines the given output times, which must be from the same window, into an output time - * for a computed value. - * - *

                - *
              • {@code combine} must be commutative: {@code combine(a, b).equals(combine(b, a))}.
              • - *
              • {@code combine} must be associative: - * {@code combine(a, combine(b, c)).equals(combine(combine(a, b), c))}.
              • - *
              - */ - public abstract Instant combine(Instant outputTime, Instant otherOutputTime); - - /** - * Merges the given output times, presumed to be combined output times for windows that - * are merging, into an output time for the {@code resultWindow}. - * - *

              When windows {@code w1} and {@code w2} merge to become a new window {@code w1plus2}, - * then {@link #merge} must be implemented such that the output time is the same as - * if all timestamps were assigned in {@code w1plus2}. Formally: - * - *

              {@code fn.merge(w, fn.assignOutputTime(t1, w1), fn.assignOutputTime(t2, w2))} - * - *

              must be equal to - * - *

              {@code fn.combine(fn.assignOutputTime(t1, w1plus2), fn.assignOutputTime(t2, w1plus2))} - * - *

              If the assigned time depends only on the window, the correct implementation of - * {@link #merge merge()} necessarily returns the result of - * {@link #assignOutputTime assignOutputTime(t1, w1plus2)} - * (which equals {@link #assignOutputTime assignOutputTime(t2, w1plus2)}. - * Defaults for this case are provided by {@link DependsOnlyOnWindow}. - * - *

              For many other {@link OutputTimeFn} implementations, such as taking the earliest or latest - * timestamp, this will be the same as {@link #combine combine()}. Defaults for this - * case are provided by {@link Defaults}. - */ - public abstract Instant merge(W intoWindow, Iterable mergingTimestamps); - - /** - * Returns {@code true} if the result of combination of many output timestamps actually depends - * only on the earliest. - * - *

              This may allow optimizations when it is very efficient to retrieve the earliest timestamp - * to be combined. - */ - public abstract boolean dependsOnlyOnEarliestInputTimestamp(); - - /** - * Returns {@code true} if the result does not depend on what outputs were combined but only - * the window they are in. The canonical example is if all timestamps are sure to - * be the end of the window. - * - *

              This may allow optimizations, since it is typically very efficient to retrieve the window - * and combining output timestamps is not necessary. - * - *

              If the assigned output time for an implementation depends only on the window, consider - * extending {@link DependsOnlyOnWindow}, which returns {@code true} here and also provides - * a framework for easily implementing a correct {@link #merge}, {@link #combine} and - * {@link #assignOutputTime}. - */ - public abstract boolean dependsOnlyOnWindow(); - - /** - * (Experimental) Default method implementations for {@link OutputTimeFn} where the - * output time depends on the input element timestamps and possibly the window. - * - *

              To complete an implementation, override {@link #assignOutputTime}, at a minimum. - * - *

              By default, {@link #combine} and {@link #merge} return the earliest timestamp of their - * inputs. - */ - public abstract static class Defaults extends OutputTimeFn { - - protected Defaults() { - super(); - } - - /** - * {@inheritDoc} - * - * @return the earlier of the two timestamps. - */ - @Override - public Instant combine(Instant outputTimestamp, Instant otherOutputTimestamp) { - return Ordering.natural().min(outputTimestamp, otherOutputTimestamp); - } - - /** - * {@inheritDoc} - * - * @return the result of {@link #combine combine(outputTimstamp, otherOutputTimestamp)}, - * by default. - */ - @Override - public Instant merge(W resultWindow, Iterable mergingTimestamps) { - return OutputTimeFns.combineOutputTimes(this, mergingTimestamps); - } - - /** - * {@inheritDoc} - * - * @return {@code false}. An {@link OutputTimeFn} that depends only on the window should extend - * {@link OutputTimeFn.DependsOnlyOnWindow}. - */ - @Override - public final boolean dependsOnlyOnWindow() { - return false; - } - - /** - * {@inheritDoc} - * - * @return {@code true} by default. - */ - @Override - public boolean dependsOnlyOnEarliestInputTimestamp() { - return false; - } - - /** - * {@inheritDoc} - * - * @return {@code true} if the two {@link OutputTimeFn} instances have the same class, by - * default. - */ - @Override - public boolean equals(Object other) { - if (other == null) { - return false; - } - - return this.getClass().equals(other.getClass()); - } - - @Override - public int hashCode() { - return Objects.hash(getClass()); - } - } - - /** - * (Experimental) Default method implementations for {@link OutputTimeFn} when the - * output time depends only on the window. - * - *

              To complete an implementation, override {@link #assignOutputTime(BoundedWindow)}. - */ - public abstract static class DependsOnlyOnWindow - extends OutputTimeFn { - - protected DependsOnlyOnWindow() { - super(); - } - - /** - * Returns the output timestamp to use for data in the specified {@code window}. - * - *

              Note that the result of this method must be between the maximum possible input timestamp - * in {@code window} and {@code window.maxTimestamp()} (inclusive on both sides). - * - *

              For example, using {@code Sessions.withGapDuration(gapDuration)}, we know that all input - * timestamps must lie at least {@code gapDuration} from the end of the session, so - * {@code window.maxTimestamp() - gapDuration} is an acceptable assigned timestamp. - * - * @see #assignOutputTime(Instant, BoundedWindow) - */ - protected abstract Instant assignOutputTime(W window); - - /** - * {@inheritDoc} - * - * @return the result of {#link assignOutputTime(BoundedWindow) assignOutputTime(window)}. - */ - @Override - public final Instant assignOutputTime(Instant timestamp, W window) { - return assignOutputTime(window); - } - - /** - * {@inheritDoc} - * - * @return the same timestamp as both argument timestamps, which are necessarily equal. - */ - @Override - public final Instant combine(Instant outputTimestamp, Instant otherOutputTimestamp) { - return outputTimestamp; - } - - /** - * {@inheritDoc} - * - * @return the result of - * {@link #assignOutputTime(BoundedWindow) assignOutputTime(resultWindow)}. - */ - @Override - public final Instant merge(W resultWindow, Iterable mergingTimestamps) { - return assignOutputTime(resultWindow); - } - - /** - * {@inheritDoc} - * - * @return {@code true}. - */ - @Override - public final boolean dependsOnlyOnWindow() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true}. Since the output time depends only on the window, it can - * certainly be ascertained given a single input timestamp. - */ - @Override - public final boolean dependsOnlyOnEarliestInputTimestamp() { - return true; - } - - /** - * {@inheritDoc} - * - * @return {@code true} if the two {@link OutputTimeFn} instances have the same class, by - * default. - */ - @Override - public boolean equals(Object other) { - if (other == null) { - return false; - } - - return this.getClass().equals(other.getClass()); - } - - @Override - public int hashCode() { - return Objects.hash(getClass()); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFns.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFns.java deleted file mode 100644 index dcc0f5b7b9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/OutputTimeFns.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.common.collect.Iterables; -import com.google.common.collect.Ordering; - -import org.joda.time.Instant; - -import javax.annotation.Nullable; - -/** - * (Experimental) Static utility methods and provided implementations for - * {@link OutputTimeFn}. - */ -@Experimental(Experimental.Kind.OUTPUT_TIME) -public class OutputTimeFns { - /** - * The policy of outputting at the earliest of the input timestamps for non-late input data - * that led to a computed value. - * - *

              For example, suppose v1 through vn are all on-time - * elements being aggregated via some function {@code f} into - * {@code f}(v1, ..., vn. When emitted, the output - * timestamp of the result will be the earliest of the event time timestamps - * - *

              If data arrives late, it has no effect on the output timestamp. - */ - public static OutputTimeFn outputAtEarliestInputTimestamp() { - return new OutputAtEarliestInputTimestamp(); - } - - /** - * The policy of holding the watermark to the latest of the input timestamps - * for non-late input data that led to a computed value. - * - *

              For example, suppose v1 through vn are all on-time - * elements being aggregated via some function {@code f} into - * {@code f}(v1, ..., vn. When emitted, the output - * timestamp of the result will be the latest of the event time timestamps - * - *

              If data arrives late, it has no effect on the output timestamp. - */ - public static OutputTimeFn outputAtLatestInputTimestamp() { - return new OutputAtLatestInputTimestamp(); - } - - /** - * The policy of outputting with timestamps at the end of the window. - * - *

              Note that this output timestamp depends only on the window. See - * {#link dependsOnlyOnWindow()}. - * - *

              When windows merge, instead of using {@link OutputTimeFn#combine} to obtain an output - * timestamp for the results in the new window, it is mandatory to obtain a new output - * timestamp from {@link OutputTimeFn#assignOutputTime} with the new window and an arbitrary - * timestamp (because it is guaranteed that the timestamp is irrelevant). - * - *

              For non-merging window functions, this {@link OutputTimeFn} works transparently. - */ - public static OutputTimeFn outputAtEndOfWindow() { - return new OutputAtEndOfWindow(); - } - - /** - * Applies the given {@link OutputTimeFn} to the given output times, obtaining - * the output time for a value computed. See {@link OutputTimeFn#combine} for - * a full specification. - * - * @throws IllegalArgumentException if {@code outputTimes} is empty. - */ - public static Instant combineOutputTimes( - OutputTimeFn outputTimeFn, Iterable outputTimes) { - checkArgument( - !Iterables.isEmpty(outputTimes), - "Collection of output times must not be empty in %s.combineOutputTimes", - OutputTimeFns.class.getName()); - - @Nullable - Instant combinedOutputTime = null; - for (Instant outputTime : outputTimes) { - combinedOutputTime = - combinedOutputTime == null - ? outputTime : outputTimeFn.combine(combinedOutputTime, outputTime); - } - return combinedOutputTime; - } - - /** - * See {@link #outputAtEarliestInputTimestamp}. - */ - private static class OutputAtEarliestInputTimestamp extends OutputTimeFn.Defaults { - @Override - public Instant assignOutputTime(Instant inputTimestamp, BoundedWindow window) { - return inputTimestamp; - } - - @Override - public Instant combine(Instant outputTime, Instant otherOutputTime) { - return Ordering.natural().min(outputTime, otherOutputTime); - } - - /** - * {@inheritDoc} - * - * @return {@code true}. The result of any combine will be the earliest input timestamp. - */ - @Override - public boolean dependsOnlyOnEarliestInputTimestamp() { - return true; - } - } - - /** - * See {@link #outputAtLatestInputTimestamp}. - */ - private static class OutputAtLatestInputTimestamp extends OutputTimeFn.Defaults { - @Override - public Instant assignOutputTime(Instant inputTimestamp, BoundedWindow window) { - return inputTimestamp; - } - - @Override - public Instant combine(Instant outputTime, Instant otherOutputTime) { - return Ordering.natural().max(outputTime, otherOutputTime); - } - - /** - * {@inheritDoc} - * - * @return {@code false}. - */ - @Override - public boolean dependsOnlyOnEarliestInputTimestamp() { - return false; - } - } - - private static class OutputAtEndOfWindow extends OutputTimeFn.DependsOnlyOnWindow { - - /** - *{@inheritDoc} - * - *@return {@code window.maxTimestamp()}. - */ - @Override - protected Instant assignOutputTime(BoundedWindow window) { - return window.maxTimestamp(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java deleted file mode 100644 index 3cb556852f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfo.java +++ /dev/null @@ -1,385 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.util.VarInt; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableMap; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Objects; - -/** - * Provides information about the pane an element belongs to. Every pane is implicitly associated - * with a window. Panes are observable only via the - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.ProcessContext#pane} method of the context - * passed to a {@link DoFn#processElement} overridden method. - * - *

              Note: This does not uniquely identify a pane, and should not be used for comparisons. - */ -public final class PaneInfo { - /** - * Enumerates the possibilities for the timing of this pane firing related to the - * input and output watermarks for its computation. - * - *

              A window may fire multiple panes, and the timing of those panes generally follows the - * regular expression {@code EARLY* ON_TIME? LATE*}. Generally a pane is considered: - *

                - *
              1. {@code EARLY} if the system cannot be sure it has seen all data which may contribute - * to the pane's window. - *
              2. {@code ON_TIME} if the system predicts it has seen all the data which may contribute - * to the pane's window. - *
              3. {@code LATE} if the system has encountered new data after predicting no more could arrive. - * It is possible an {@code ON_TIME} pane has already been emitted, in which case any - * following panes are considered {@code LATE}. - *
              - * - *

              Only an - * {@link AfterWatermark#pastEndOfWindow} trigger may produce an {@code ON_TIME} pane. - * With merging {@link WindowFn}'s, windows may be merged to produce new windows that satisfy - * their own instance of the above regular expression. The only guarantee is that once a window - * produces a final pane, it will not be merged into any new windows. - * - *

              The predictions above are made using the mechanism of watermarks. - * See {@link com.google.cloud.dataflow.sdk.util.TimerInternals} for more information - * about watermarks. - * - *

              We can state some properties of {@code LATE} and {@code ON_TIME} panes, but first need some - * definitions: - *

                - *
              1. We'll call a pipeline 'simple' if it does not use - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#outputWithTimestamp} in - * any {@code DoFn}, and it uses the same - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound#withAllowedLateness} - * argument value on all windows (or uses the default of {@link org.joda.time.Duration#ZERO}). - *
              2. We'll call an element 'locally late', from the point of view of a computation on a - * worker, if the element's timestamp is before the input watermark for that computation - * on that worker. The element is otherwise 'locally on-time'. - *
              3. We'll say 'the pane's timestamp' to mean the timestamp of the element produced to - * represent the pane's contents. - *
              - * - *

              Then in simple pipelines: - *

                - *
              1. (Soundness) An {@code ON_TIME} pane can never cause a later computation to generate a - * {@code LATE} pane. (If it did, it would imply a later computation's input watermark progressed - * ahead of an earlier stage's output watermark, which by design is not possible.) - *
              2. (Liveness) An {@code ON_TIME} pane is emitted as soon as possible after the input - * watermark passes the end of the pane's window. - *
              3. (Consistency) A pane with only locally on-time elements will always be {@code ON_TIME}. - * And a {@code LATE} pane cannot contain locally on-time elements. - *
              - * - *

              However, note that: - *

                - *
              1. An {@code ON_TIME} pane may contain locally late elements. It may even contain only - * locally late elements. Provided a locally late element finds its way into an {@code ON_TIME} - * pane its lateness becomes unobservable. - *
              2. A {@code LATE} pane does not necessarily cause any following computation panes to be - * marked as {@code LATE}. - *
              - */ - public enum Timing { - /** - * Pane was fired before the input watermark had progressed after the end of the window. - */ - EARLY, - /** - * Pane was fired by a {@link AfterWatermark#pastEndOfWindow} trigger because the input - * watermark progressed after the end of the window. However the output watermark has not - * yet progressed after the end of the window. Thus it is still possible to assign a timestamp - * to the element representing this pane which cannot be considered locally late by any - * following computation. - */ - ON_TIME, - /** - * Pane was fired after the output watermark had progressed past the end of the window. - */ - LATE, - /** - * This element was not produced in a triggered pane and its relation to input and - * output watermarks is unknown. - */ - UNKNOWN; - - // NOTE: Do not add fields or re-order them. The ordinal is used as part of - // the encoding. - } - - private static byte encodedByte(boolean isFirst, boolean isLast, Timing timing) { - byte result = 0x0; - if (isFirst) { - result |= 1; - } - if (isLast) { - result |= 2; - } - result |= timing.ordinal() << 2; - return result; - } - - private static final ImmutableMap BYTE_TO_PANE_INFO; - static { - ImmutableMap.Builder decodingBuilder = ImmutableMap.builder(); - for (Timing timing : Timing.values()) { - long onTimeIndex = timing == Timing.EARLY ? -1 : 0; - register(decodingBuilder, new PaneInfo(true, true, timing, 0, onTimeIndex)); - register(decodingBuilder, new PaneInfo(true, false, timing, 0, onTimeIndex)); - register(decodingBuilder, new PaneInfo(false, true, timing, -1, onTimeIndex)); - register(decodingBuilder, new PaneInfo(false, false, timing, -1, onTimeIndex)); - } - BYTE_TO_PANE_INFO = decodingBuilder.build(); - } - - private static void register(ImmutableMap.Builder builder, PaneInfo info) { - builder.put(info.encodedByte, info); - } - - private final byte encodedByte; - - private final boolean isFirst; - private final boolean isLast; - private final Timing timing; - private final long index; - private final long nonSpeculativeIndex; - - /** - * {@code PaneInfo} to use for elements on (and before) initial window assignemnt (including - * elements read from sources) before they have passed through a {@link GroupByKey} and are - * associated with a particular trigger firing. - */ - public static final PaneInfo NO_FIRING = - PaneInfo.createPane(true, true, Timing.UNKNOWN, 0, 0); - - /** - * {@code PaneInfo} to use when there will be exactly one firing and it is on time. - */ - public static final PaneInfo ON_TIME_AND_ONLY_FIRING = - PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0); - - private PaneInfo(boolean isFirst, boolean isLast, Timing timing, long index, long onTimeIndex) { - this.encodedByte = encodedByte(isFirst, isLast, timing); - this.isFirst = isFirst; - this.isLast = isLast; - this.timing = timing; - this.index = index; - this.nonSpeculativeIndex = onTimeIndex; - } - - public static PaneInfo createPane(boolean isFirst, boolean isLast, Timing timing) { - checkArgument(isFirst, "Indices must be provided for non-first pane info."); - return createPane(isFirst, isLast, timing, 0, timing == Timing.EARLY ? -1 : 0); - } - - /** - * Factory method to create a {@link PaneInfo} with the specified parameters. - */ - public static PaneInfo createPane( - boolean isFirst, boolean isLast, Timing timing, long index, long onTimeIndex) { - if (isFirst || timing == Timing.UNKNOWN) { - return checkNotNull(BYTE_TO_PANE_INFO.get(encodedByte(isFirst, isLast, timing))); - } else { - return new PaneInfo(isFirst, isLast, timing, index, onTimeIndex); - } - } - - public static PaneInfo decodePane(byte encodedPane) { - return checkNotNull(BYTE_TO_PANE_INFO.get(encodedPane)); - } - - /** - * Return true if there is no timing information for the current {@link PaneInfo}. - * This typically indicates that the current element has not been assigned to - * windows or passed through an operation that executes triggers yet. - */ - public boolean isUnknown() { - return Timing.UNKNOWN.equals(timing); - } - - /** - * Return true if this is the first pane produced for the associated window. - */ - public boolean isFirst() { - return isFirst; - } - - /** - * Return true if this is the last pane that will be produced in the associated window. - */ - public boolean isLast() { - return isLast; - } - - /** - * Return true if this is the last pane that will be produced in the associated window. - */ - public Timing getTiming() { - return timing; - } - - /** - * The zero-based index of this trigger firing that produced this pane. - * - *

              This will return 0 for the first time the timer fires, 1 for the next time, etc. - * - *

              A given (key, window, pane-index) is guaranteed to be unique in the - * output of a group-by-key operation. - */ - public long getIndex() { - return index; - } - - /** - * The zero-based index of this trigger firing among non-speculative panes. - * - *

              This will return 0 for the first non-{@link Timing#EARLY} timer firing, 1 for the next one, - * etc. - * - *

              Always -1 for speculative data. - */ - public long getNonSpeculativeIndex() { - return nonSpeculativeIndex; - } - - int getEncodedByte() { - return encodedByte; - } - - @Override - public int hashCode() { - return Objects.hash(encodedByte, index, nonSpeculativeIndex); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - // Simple PaneInfos are interned. - return true; - } else if (obj instanceof PaneInfo) { - PaneInfo that = (PaneInfo) obj; - return this.encodedByte == that.encodedByte - && this.index == that.index - && this.nonSpeculativeIndex == that.nonSpeculativeIndex; - } else { - return false; - } - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .omitNullValues() - .add("isFirst", isFirst ? true : null) - .add("isLast", isLast ? true : null) - .add("timing", timing) - .add("index", index) - .add("onTimeIndex", nonSpeculativeIndex != -1 ? nonSpeculativeIndex : null) - .toString(); - } - - /** - * A Coder for encoding PaneInfo instances. - */ - public static class PaneInfoCoder extends AtomicCoder { - private enum Encoding { - FIRST, - ONE_INDEX, - TWO_INDICES; - - // NOTE: Do not reorder fields. The ordinal is used as part of - // the encoding. - - public final byte tag; - - private Encoding() { - assert ordinal() < 16; - tag = (byte) (ordinal() << 4); - } - - public static Encoding fromTag(byte b) { - return Encoding.values()[b >> 4]; - } - } - - private Encoding chooseEncoding(PaneInfo value) { - if (value.index == 0 && value.nonSpeculativeIndex == 0 || value.timing == Timing.UNKNOWN) { - return Encoding.FIRST; - } else if (value.index == value.nonSpeculativeIndex || value.timing == Timing.EARLY) { - return Encoding.ONE_INDEX; - } else { - return Encoding.TWO_INDICES; - } - } - - public static final PaneInfoCoder INSTANCE = new PaneInfoCoder(); - - @Override - public void encode(PaneInfo value, final OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - Encoding encoding = chooseEncoding(value); - switch (chooseEncoding(value)) { - case FIRST: - outStream.write(value.encodedByte); - break; - case ONE_INDEX: - outStream.write(value.encodedByte | encoding.tag); - VarInt.encode(value.index, outStream); - break; - case TWO_INDICES: - outStream.write(value.encodedByte | encoding.tag); - VarInt.encode(value.index, outStream); - VarInt.encode(value.nonSpeculativeIndex, outStream); - break; - default: - throw new CoderException("Unknown encoding " + encoding); - } - } - - @Override - public PaneInfo decode(final InputStream inStream, Coder.Context context) - throws CoderException, IOException { - byte keyAndTag = (byte) inStream.read(); - PaneInfo base = BYTE_TO_PANE_INFO.get((byte) (keyAndTag & 0x0F)); - long index, onTimeIndex; - switch (Encoding.fromTag(keyAndTag)) { - case FIRST: - return base; - case ONE_INDEX: - index = VarInt.decodeLong(inStream); - onTimeIndex = base.timing == Timing.EARLY ? -1 : index; - break; - case TWO_INDICES: - index = VarInt.decodeLong(inStream); - onTimeIndex = VarInt.decodeLong(inStream); - break; - default: - throw new CoderException("Unknown encoding " + (keyAndTag & 0xF0)); - } - return new PaneInfo(base.isFirst, base.isLast, base.timing, index, onTimeIndex); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PartitioningWindowFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PartitioningWindowFn.java deleted file mode 100644 index bea0285b61..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/PartitioningWindowFn.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import org.joda.time.Instant; - -import java.util.Arrays; -import java.util.Collection; - -/** - * A {@link WindowFn} that places each value into exactly one window based on its timestamp and - * never merges windows. - * - * @param type of elements being windowed - * @param window type - */ -public abstract class PartitioningWindowFn - extends NonMergingWindowFn { - /** - * Returns the single window to which elements with this timestamp belong. - */ - public abstract W assignWindow(Instant timestamp); - - @Override - public final Collection assignWindows(AssignContext c) { - return Arrays.asList(assignWindow(c.timestamp())); - } - - @Override - public W getSideInputWindow(final BoundedWindow window) { - if (window instanceof GlobalWindow) { - throw new IllegalArgumentException( - "Attempted to get side input window for GlobalWindow from non-global WindowFn"); - } - return assignWindow(window.maxTimestamp()); - } - - @Override - public boolean assignsToSingleWindow() { - return true; - } - - @Override - public Instant getOutputTime(Instant inputTimestamp, W window) { - return inputTimestamp; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java deleted file mode 100644 index c1000c2261..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Repeatedly.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; - -import org.joda.time.Instant; - -import java.util.Arrays; -import java.util.List; - -/** - * Repeat a trigger, either until some condition is met or forever. - * - *

              For example, to fire after the end of the window, and every time late data arrives: - *

               {@code
              - *     Repeatedly.forever(AfterWatermark.isPastEndOfWindow());
              - * } 
              - * - *

              {@code Repeatedly.forever(someTrigger)} behaves like an infinite - * {@code AfterEach.inOrder(someTrigger, someTrigger, someTrigger, ...)}. - * - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@code Trigger} - */ -public class Repeatedly extends Trigger { - - private static final int REPEATED = 0; - - /** - * Create a composite trigger that repeatedly executes the trigger {@code repeated}, firing each - * time it fires and ignoring any indications to finish. - * - *

              Unless used with {@link Trigger#orFinally} the composite trigger will never finish. - * - * @param repeated the trigger to execute repeatedly. - */ - public static Repeatedly forever(Trigger repeated) { - return new Repeatedly(repeated); - } - - private Repeatedly(Trigger repeated) { - super(Arrays.asList(repeated)); - } - - - @Override - public void onElement(OnElementContext c) throws Exception { - getRepeated(c).invokeOnElement(c); - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - getRepeated(c).invokeOnMerge(c); - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - // This trigger fires once the repeated trigger fires. - return subTriggers.get(REPEATED).getWatermarkThatGuaranteesFiring(window); - } - - @Override - public Trigger getContinuationTrigger(List> continuationTriggers) { - return new Repeatedly(continuationTriggers.get(REPEATED)); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return getRepeated(context).invokeShouldFire(context); - } - - @Override - public void onFire(TriggerContext context) throws Exception { - getRepeated(context).invokeOnFire(context); - - if (context.trigger().isFinished(REPEATED)) { - // Reset tree will recursively clear the finished bits, and invoke clear. - context.forTrigger(getRepeated(context)).trigger().resetTree(); - } - } - - @Override - public String toString() { - return String.format("Repeatedly.forever(%s)", subTriggers.get(REPEATED)); - } - - private ExecutableTrigger getRepeated(TriggerContext context) { - return context.trigger().subTrigger(REPEATED); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java deleted file mode 100644 index 8ffe82fc42..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Sessions.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.joda.time.Duration; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Objects; - -/** - * A {@link WindowFn} windowing values into sessions separated by {@link #gapDuration}-long - * periods with no elements. - * - *

              For example, in order to window data into session with at least 10 minute - * gaps in between them: - *

               {@code
              - * PCollection pc = ...;
              - * PCollection windowed_pc = pc.apply(
              - *   Window.into(Sessions.withGapDuration(Duration.standardMinutes(10))));
              - * } 
              - */ -public class Sessions extends WindowFn { - /** - * Duration of the gaps between sessions. - */ - private final Duration gapDuration; - - /** - * Creates a {@code Sessions} {@link WindowFn} with the specified gap duration. - */ - public static Sessions withGapDuration(Duration gapDuration) { - return new Sessions(gapDuration); - } - - /** - * Creates a {@code Sessions} {@link WindowFn} with the specified gap duration. - */ - private Sessions(Duration gapDuration) { - this.gapDuration = gapDuration; - } - - @Override - public Collection assignWindows(AssignContext c) { - // Assign each element into a window from its timestamp until gapDuration in the - // future. Overlapping windows (representing elements within gapDuration of - // each other) will be merged. - return Arrays.asList(new IntervalWindow(c.timestamp(), gapDuration)); - } - - @Override - public void mergeWindows(MergeContext c) throws Exception { - MergeOverlappingIntervalWindows.mergeWindows(c); - } - - @Override - public Coder windowCoder() { - return IntervalWindow.getCoder(); - } - - @Override - public boolean isCompatible(WindowFn other) { - return other instanceof Sessions; - } - - @Override - public IntervalWindow getSideInputWindow(BoundedWindow window) { - throw new UnsupportedOperationException("Sessions is not allowed in side inputs"); - } - - @Experimental(Kind.OUTPUT_TIME) - @Override - public OutputTimeFn getOutputTimeFn() { - return OutputTimeFns.outputAtEarliestInputTimestamp(); - } - - public Duration getGapDuration() { - return gapDuration; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder.add(DisplayData.item("gapDuration", gapDuration) - .withLabel("Session Gap Duration")); - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof Sessions)) { - return false; - } - Sessions other = (Sessions) object; - return getGapDuration().equals(other.getGapDuration()); - } - - @Override - public int hashCode() { - return Objects.hash(gapDuration); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java deleted file mode 100644 index e2a9f59ba3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindows.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Objects; - -/** - * A {@link WindowFn} that windows values into possibly overlapping fixed-size - * timestamp-based windows. - * - *

              For example, in order to window data into 10 minute windows that - * update every minute: - *

               {@code
              - * PCollection items = ...;
              - * PCollection windowedItems = items.apply(
              - *   Window.into(SlidingWindows.of(Duration.standardMinutes(10))));
              - * } 
              - */ -public class SlidingWindows extends NonMergingWindowFn { - - /** - * Amount of time between generated windows. - */ - private final Duration period; - - /** - * Size of the generated windows. - */ - private final Duration size; - - /** - * Offset of the generated windows. - * Windows start at time N * start + offset, where 0 is the epoch. - */ - private final Duration offset; - - /** - * Assigns timestamps into half-open intervals of the form - * [N * period, N * period + size), where 0 is the epoch. - * - *

              If {@link SlidingWindows#every} is not called, the period defaults - * to the largest time unit smaller than the given duration. For example, - * specifying a size of 5 seconds will result in a default period of 1 second. - */ - public static SlidingWindows of(Duration size) { - return new SlidingWindows(getDefaultPeriod(size), size, Duration.ZERO); - } - - /** - * Returns a new {@code SlidingWindows} with the original size, that assigns - * timestamps into half-open intervals of the form - * [N * period, N * period + size), where 0 is the epoch. - */ - public SlidingWindows every(Duration period) { - return new SlidingWindows(period, size, offset); - } - - /** - * Assigns timestamps into half-open intervals of the form - * [N * period + offset, N * period + offset + size). - * - * @throws IllegalArgumentException if offset is not in [0, period) - */ - public SlidingWindows withOffset(Duration offset) { - return new SlidingWindows(period, size, offset); - } - - private SlidingWindows(Duration period, Duration size, Duration offset) { - if (offset.isShorterThan(Duration.ZERO) - || !offset.isShorterThan(period) - || !size.isLongerThan(Duration.ZERO)) { - throw new IllegalArgumentException( - "SlidingWindows WindowingStrategies must have 0 <= offset < period and 0 < size"); - } - this.period = period; - this.size = size; - this.offset = offset; - } - - @Override - public Coder windowCoder() { - return IntervalWindow.getCoder(); - } - - @Override - public Collection assignWindows(AssignContext c) { - List windows = - new ArrayList<>((int) (size.getMillis() / period.getMillis())); - Instant timestamp = c.timestamp(); - long lastStart = lastStartFor(timestamp); - for (long start = lastStart; - start > timestamp.minus(size).getMillis(); - start -= period.getMillis()) { - windows.add(new IntervalWindow(new Instant(start), size)); - } - return windows; - } - - /** - * Return the earliest window that contains the end of the main-input window. - */ - @Override - public IntervalWindow getSideInputWindow(final BoundedWindow window) { - if (window instanceof GlobalWindow) { - throw new IllegalArgumentException( - "Attempted to get side input window for GlobalWindow from non-global WindowFn"); - } - long lastStart = lastStartFor(window.maxTimestamp().minus(size)); - return new IntervalWindow(new Instant(lastStart + period.getMillis()), size); - } - - @Override - public boolean isCompatible(WindowFn other) { - return equals(other); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - builder - .add(DisplayData.item("size", size) - .withLabel("Window Size")) - .add(DisplayData.item("period", period) - .withLabel("Window Period")) - .add(DisplayData.item("offset", offset) - .withLabel("Window Start Offset")); - } - - /** - * Return the last start of a sliding window that contains the timestamp. - */ - private long lastStartFor(Instant timestamp) { - return timestamp.getMillis() - - timestamp.plus(period).minus(offset).getMillis() % period.getMillis(); - } - - static Duration getDefaultPeriod(Duration size) { - if (size.isLongerThan(Duration.standardHours(1))) { - return Duration.standardHours(1); - } - if (size.isLongerThan(Duration.standardMinutes(1))) { - return Duration.standardMinutes(1); - } - if (size.isLongerThan(Duration.standardSeconds(1))) { - return Duration.standardSeconds(1); - } - return Duration.millis(1); - } - - public Duration getPeriod() { - return period; - } - - public Duration getSize() { - return size; - } - - public Duration getOffset() { - return offset; - } - - /** - * Ensures that later sliding windows have an output time that is past the end of earlier windows. - * - *

              If this is the earliest sliding window containing {@code inputTimestamp}, that's fine. - * Otherwise, we pick the earliest time that doesn't overlap with earlier windows. - */ - @Experimental(Kind.OUTPUT_TIME) - @Override - public OutputTimeFn getOutputTimeFn() { - return new OutputTimeFn.Defaults() { - @Override - public Instant assignOutputTime(Instant inputTimestamp, BoundedWindow window) { - Instant startOfLastSegment = window.maxTimestamp().minus(period); - return startOfLastSegment.isBefore(inputTimestamp) - ? inputTimestamp - : startOfLastSegment.plus(1); - } - - @Override - public boolean dependsOnlyOnEarliestInputTimestamp() { - return true; - } - }; - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof SlidingWindows)) { - return false; - } - SlidingWindows other = (SlidingWindows) object; - return getOffset().equals(other.getOffset()) - && getSize().equals(other.getSize()) - && getPeriod().equals(other.getPeriod()); - } - - @Override - public int hashCode() { - return Objects.hash(size, offset, period); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java deleted file mode 100644 index 37fa3b19c0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Trigger.java +++ /dev/null @@ -1,544 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.util.ExecutableTrigger; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.common.base.Joiner; - -import org.joda.time.Instant; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import javax.annotation.Nullable; - -/** - * {@code Trigger}s control when the elements for a specific key and window are output. As elements - * arrive, they are put into one or more windows by a {@link Window} transform and its associated - * {@link WindowFn}, and then passed to the associated {@code Trigger} to determine if the - * {@code Window}s contents should be output. - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey} and {@link Window} - * for more information about how grouping with windows works. - * - *

              The elements that are assigned to a window since the last time it was fired (or since the - * window was created) are placed into the current window pane. Triggers are evaluated against the - * elements as they are added. When the root trigger fires, the elements in the current pane will be - * output. When the root trigger finishes (indicating it will never fire again), the window is - * closed and any new elements assigned to that window are discarded. - * - *

              Several predefined {@code Trigger}s are provided: - *

                - *
              • {@link AfterWatermark} for firing when the watermark passes a timestamp determined from - * either the end of the window or the arrival of the first element in a pane. - *
              • {@link AfterProcessingTime} for firing after some amount of processing time has elapsed - * (typically since the first element in a pane). - *
              • {@link AfterPane} for firing off a property of the elements in the current pane, such as - * the number of elements that have been assigned to the current pane. - *
              - * - *

              In addition, {@code Trigger}s can be combined in a variety of ways: - *

                - *
              • {@link Repeatedly#forever} to create a trigger that executes forever. Any time its - * argument finishes it gets reset and starts over. Can be combined with - * {@link Trigger#orFinally} to specify a condition that causes the repetition to stop. - *
              • {@link AfterEach#inOrder} to execute each trigger in sequence, firing each (and every) - * time that a trigger fires, and advancing to the next trigger in the sequence when it finishes. - *
              • {@link AfterFirst#of} to create a trigger that fires after at least one of its arguments - * fires. An {@link AfterFirst} trigger finishes after it fires once. - *
              • {@link AfterAll#of} to create a trigger that fires after all least one of its arguments - * have fired at least once. An {@link AfterAll} trigger finishes after it fires once. - *
              - * - *

              Each trigger tree is instantiated per-key and per-window. Every trigger in the tree is in one - * of the following states: - *

                - *
              • Never Existed - before the trigger has started executing, there is no state associated - * with it anywhere in the system. A trigger moves to the executing state as soon as it - * processes in the current pane. - *
              • Executing - while the trigger is receiving items and may fire. While it is in this state, - * it may persist book-keeping information to persisted state, set timers, etc. - *
              • Finished - after a trigger finishes, all of its book-keeping data is cleaned up, and the - * system remembers only that it is finished. Entering this state causes us to discard any - * elements in the buffer for that window, as well. - *
              - * - *

              Once finished, a trigger cannot return itself back to an earlier state, however a composite - * trigger could reset its sub-triggers. - * - *

              Triggers should not build up any state internally since they may be recreated - * between invocations of the callbacks. All important values should be persisted using - * state before the callback returns. - * - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@code Trigger} - */ -@Experimental(Experimental.Kind.TRIGGER) -public abstract class Trigger implements Serializable, TriggerBuilder { - - /** - * Interface for accessing information about the trigger being executed and other triggers in the - * same tree. - */ - public interface TriggerInfo { - - /** - * Returns true if the windowing strategy of the current {@code PCollection} is a merging - * WindowFn. If true, the trigger execution needs to keep enough information to support the - * possibility of {@link Trigger#onMerge} being called. If false, {@link Trigger#onMerge} will - * never be called. - */ - boolean isMerging(); - - /** - * Access the executable versions of the sub-triggers of the current trigger. - */ - Iterable> subTriggers(); - - /** - * Access the executable version of the specified sub-trigger. - */ - ExecutableTrigger subTrigger(int subtriggerIndex); - - /** - * Returns true if the current trigger is marked finished. - */ - boolean isFinished(); - - /** - * Return true if the given subtrigger is marked finished. - */ - boolean isFinished(int subtriggerIndex); - - /** - * Returns true if all the sub-triggers of the current trigger are marked finished. - */ - boolean areAllSubtriggersFinished(); - - /** - * Returns an iterable over the unfinished sub-triggers of the current trigger. - */ - Iterable> unfinishedSubTriggers(); - - /** - * Returns the first unfinished sub-trigger. - */ - ExecutableTrigger firstUnfinishedSubTrigger(); - - /** - * Clears all keyed state for triggers in the current sub-tree and unsets all the associated - * finished bits. - */ - void resetTree() throws Exception; - - /** - * Sets the finished bit for the current trigger. - */ - void setFinished(boolean finished); - - /** - * Sets the finished bit for the given sub-trigger. - */ - void setFinished(boolean finished, int subTriggerIndex); - } - - /** - * Interact with properties of the trigger being executed, with extensions to deal with the - * merging windows. - */ - public interface MergingTriggerInfo extends TriggerInfo { - - /** Return true if the trigger is finished in any window being merged. */ - boolean finishedInAnyMergingWindow(); - - /** Return true if the trigger is finished in all windows being merged. */ - boolean finishedInAllMergingWindows(); - - /** Return the merging windows in which the trigger is finished. */ - Iterable getFinishedMergingWindows(); - } - - /** - * Information accessible to all operational hooks in this {@code Trigger}. - * - *

              Used directly in {@link Trigger#shouldFire} and {@link Trigger#clear}, and - * extended with additional information in other methods. - */ - public abstract class TriggerContext { - - /** Returns the interface for accessing trigger info. */ - public abstract TriggerInfo trigger(); - - /** Returns the interface for accessing persistent state. */ - public abstract StateAccessor state(); - - /** The window that the current context is executing in. */ - public abstract W window(); - - /** Create a sub-context for the given sub-trigger. */ - public abstract TriggerContext forTrigger(ExecutableTrigger trigger); - - /** - * Removes the timer set in this trigger context for the given {@link Instant} - * and {@link TimeDomain}. - */ - public abstract void deleteTimer(Instant timestamp, TimeDomain domain); - - /** The current processing time. */ - public abstract Instant currentProcessingTime(); - - /** The current synchronized upstream processing time or {@code null} if unknown. */ - @Nullable - public abstract Instant currentSynchronizedProcessingTime(); - - /** The current event time for the input or {@code null} if unknown. */ - @Nullable - public abstract Instant currentEventTime(); - } - - /** - * Extended {@link TriggerContext} containing information accessible to the {@link #onElement} - * operational hook. - */ - public abstract class OnElementContext extends TriggerContext { - /** The event timestamp of the element currently being processed. */ - public abstract Instant eventTimestamp(); - - /** - * Sets a timer to fire when the watermark or processing time is beyond the given timestamp. - * Timers are not guaranteed to fire immediately, but will be delivered at some time afterwards. - * - *

              As with {@link #state}, timers are implicitly scoped to the current window. All - * timer firings for a window will be received, but the implementation should choose to ignore - * those that are not applicable. - * - * @param timestamp the time at which the trigger should be re-evaluated - * @param domain the domain that the {@code timestamp} applies to - */ - public abstract void setTimer(Instant timestamp, TimeDomain domain); - - /** Create an {@code OnElementContext} for executing the given trigger. */ - @Override - public abstract OnElementContext forTrigger(ExecutableTrigger trigger); - } - - /** - * Extended {@link TriggerContext} containing information accessible to the {@link #onMerge} - * operational hook. - */ - public abstract class OnMergeContext extends TriggerContext { - /** - * Sets a timer to fire when the watermark or processing time is beyond the given timestamp. - * Timers are not guaranteed to fire immediately, but will be delivered at some time afterwards. - * - *

              As with {@link #state}, timers are implicitly scoped to the current window. All - * timer firings for a window will be received, but the implementation should choose to ignore - * those that are not applicable. - * - * @param timestamp the time at which the trigger should be re-evaluated - * @param domain the domain that the {@code timestamp} applies to - */ - public abstract void setTimer(Instant timestamp, TimeDomain domain); - - /** Create an {@code OnMergeContext} for executing the given trigger. */ - @Override - public abstract OnMergeContext forTrigger(ExecutableTrigger trigger); - - @Override - public abstract MergingStateAccessor state(); - - @Override - public abstract MergingTriggerInfo trigger(); - } - - @Nullable - protected final List> subTriggers; - - protected Trigger(@Nullable List> subTriggers) { - this.subTriggers = subTriggers; - } - - - /** - * Called immediately after an element is first incorporated into a window. - */ - public abstract void onElement(OnElementContext c) throws Exception; - - /** - * Called immediately after windows have been merged. - * - *

              Leaf triggers should update their state by inspecting their status and any state - * in the merging windows. Composite triggers should update their state by calling - * {@link ExecutableTrigger#invokeOnMerge} on their sub-triggers, and applying appropriate logic. - * - *

              A trigger such as {@link AfterWatermark#pastEndOfWindow} may no longer be finished; - * it is the responsibility of the trigger itself to record this fact. It is forbidden for - * a trigger to become finished due to {@link #onMerge}, as it has not yet fired the pending - * elements that led to it being ready to fire. - * - *

              The implementation does not need to clear out any state associated with the old windows. - */ - public abstract void onMerge(OnMergeContext c) throws Exception; - - /** - * Returns {@code true} if the current state of the trigger indicates that its condition - * is satisfied and it is ready to fire. - */ - public abstract boolean shouldFire(TriggerContext context) throws Exception; - - /** - * Adjusts the state of the trigger to be ready for the next pane. For example, a - * {@link Repeatedly} trigger will reset its inner trigger, since it has fired. - * - *

              If the trigger is finished, it is the responsibility of the trigger itself to - * record that fact via the {@code context}. - */ - public abstract void onFire(TriggerContext context) throws Exception; - - /** - * Called to allow the trigger to prefetch any state it will likely need to read from during - * an {@link #onElement} call. - */ - public void prefetchOnElement(StateAccessor state) { - if (subTriggers != null) { - for (Trigger trigger : subTriggers) { - trigger.prefetchOnElement(state); - } - } - } - - /** - * Called to allow the trigger to prefetch any state it will likely need to read from during - * an {@link #onMerge} call. - */ - public void prefetchOnMerge(MergingStateAccessor state) { - if (subTriggers != null) { - for (Trigger trigger : subTriggers) { - trigger.prefetchOnMerge(state); - } - } - } - - /** - * Called to allow the trigger to prefetch any state it will likely need to read from during - * an {@link #shouldFire} call. - */ - public void prefetchShouldFire(StateAccessor state) { - if (subTriggers != null) { - for (Trigger trigger : subTriggers) { - trigger.prefetchShouldFire(state); - } - } - } - - /** - * Called to allow the trigger to prefetch any state it will likely need to read from during - * an {@link #onFire} call. - */ - public void prefetchOnFire(StateAccessor state) { - if (subTriggers != null) { - for (Trigger trigger : subTriggers) { - trigger.prefetchOnFire(state); - } - } - } - - /** - * Clear any state associated with this trigger in the given window. - * - *

              This is called after a trigger has indicated it will never fire again. The trigger system - * keeps enough information to know that the trigger is finished, so this trigger should clear all - * of its state. - */ - public void clear(TriggerContext c) throws Exception { - if (subTriggers != null) { - for (ExecutableTrigger trigger : c.trigger().subTriggers()) { - trigger.invokeClear(c); - } - } - } - - public Iterable> subTriggers() { - return subTriggers; - } - - /** - * Return a trigger to use after a {@code GroupByKey} to preserve the - * intention of this trigger. Specifically, triggers that are time based - * and intended to provide speculative results should continue providing - * speculative results. Triggers that fire once (or multiple times) should - * continue firing once (or multiple times). - */ - public Trigger getContinuationTrigger() { - if (subTriggers == null) { - return getContinuationTrigger(null); - } - - List> subTriggerContinuations = new ArrayList<>(); - for (Trigger subTrigger : subTriggers) { - subTriggerContinuations.add(subTrigger.getContinuationTrigger()); - } - return getContinuationTrigger(subTriggerContinuations); - } - - /** - * Return the {@link #getContinuationTrigger} of this {@code Trigger}. For convenience, this - * is provided the continuation trigger of each of the sub-triggers. - */ - protected abstract Trigger getContinuationTrigger(List> continuationTriggers); - - /** - * Returns a bound in watermark time by which this trigger would have fired at least once - * for a given window had there been input data. This is a static property of a trigger - * that does not depend on its state. - * - *

              For triggers that do not fire based on the watermark advancing, returns - * {@link BoundedWindow#TIMESTAMP_MAX_VALUE}. - * - *

              This estimate is used to determine that there are no elements in a side-input window, which - * causes the default value to be used instead. - */ - public abstract Instant getWatermarkThatGuaranteesFiring(W window); - - /** - * Returns whether this performs the same triggering as the given {@code Trigger}. - */ - public boolean isCompatible(Trigger other) { - if (!getClass().equals(other.getClass())) { - return false; - } - - if (subTriggers == null) { - return other.subTriggers == null; - } else if (other.subTriggers == null) { - return false; - } else if (subTriggers.size() != other.subTriggers.size()) { - return false; - } - - for (int i = 0; i < subTriggers.size(); i++) { - if (!subTriggers.get(i).isCompatible(other.subTriggers.get(i))) { - return false; - } - } - - return true; - } - - @Override - public String toString() { - String simpleName = getClass().getSimpleName(); - if (getClass().getEnclosingClass() != null) { - simpleName = getClass().getEnclosingClass().getSimpleName() + "." + simpleName; - } - if (subTriggers == null || subTriggers.size() == 0) { - return simpleName; - } else { - return simpleName + "(" + Joiner.on(", ").join(subTriggers) + ")"; - } - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof Trigger)) { - return false; - } - @SuppressWarnings("unchecked") - Trigger that = (Trigger) obj; - return Objects.equals(getClass(), that.getClass()) - && Objects.equals(subTriggers, that.subTriggers); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), subTriggers); - } - - /** - * Specify an ending condition for this trigger. If the {@code until} fires then the combination - * fires. - * - *

              The expression {@code t1.orFinally(t2)} fires every time {@code t1} fires, and finishes - * as soon as either {@code t1} finishes or {@code t2} fires, in which case it fires one last time - * for {@code t2}. Both {@code t1} and {@code t2} are executed in parallel. This means that - * {@code t1} may have fired since {@code t2} started, so not all of the elements that {@code t2} - * has seen are necessarily in the current pane. - * - *

              For example the final firing of the following trigger may only have 1 element: - *

               {@code
              -   * Repeatedly.forever(AfterPane.elementCountAtLeast(2))
              -   *     .orFinally(AfterPane.elementCountAtLeast(5))
              -   * } 
              - * - *

              Note that if {@code t1} is {@link OnceTrigger}, then {@code t1.orFinally(t2)} is the same - * as {@code AfterFirst.of(t1, t2)}. - */ - public Trigger orFinally(OnceTrigger until) { - return new OrFinallyTrigger(this, until); - } - - @Override - public Trigger buildTrigger() { - return this; - } - - /** - * {@link Trigger}s that are guaranteed to fire at most once should extend from this, rather - * than the general {@link Trigger} class to indicate that behavior. - * - * @param {@link BoundedWindow} subclass used to represent the windows used by this - * {@code AtMostOnceTrigger} - */ - public abstract static class OnceTrigger extends Trigger { - protected OnceTrigger(List> subTriggers) { - super(subTriggers); - } - - @Override - public final OnceTrigger getContinuationTrigger() { - Trigger continuation = super.getContinuationTrigger(); - if (!(continuation instanceof OnceTrigger)) { - throw new IllegalStateException("Continuation of a OnceTrigger must be a OnceTrigger"); - } - return (OnceTrigger) continuation; - } - - /** - * {@inheritDoc} - */ - @Override - public final void onFire(TriggerContext context) throws Exception { - onOnlyFiring(context); - context.trigger().setFinished(true); - } - - /** - * Called exactly once by {@link #onFire} when the trigger is fired. By default, - * invokes {@link #onFire} on all subtriggers for which {@link #shouldFire} is {@code true}. - */ - protected abstract void onOnlyFiring(TriggerContext context) throws Exception; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerBuilder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerBuilder.java deleted file mode 100644 index cc817ba1a3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerBuilder.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -/** - * Anything that can be used to create an instance of a {@code Trigger} implements this interface. - * - *

              This includes {@code Trigger}s (which can return themselves) and any "enhanced" syntax for - * constructing a trigger. - * - * @param The type of windows the built trigger will operate on. - */ -public interface TriggerBuilder { - /** Return the {@code Trigger} built by this builder. */ - Trigger buildTrigger(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java deleted file mode 100644 index 70ed44c71d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/Window.java +++ /dev/null @@ -1,701 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.AssignWindowsDoFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; - -import javax.annotation.Nullable; - -/** - * {@code Window} logically divides up or groups the elements of a - * {@link PCollection} into finite windows according to a {@link WindowFn}. - * The output of {@code Window} contains the same elements as input, but they - * have been logically assigned to windows. The next - * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey GroupByKeys}, - * including one within composite transforms, will group by the combination of - * keys and windows. - * - *

              See {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey} - * for more information about how grouping with windows works. - * - *

              Windowing

              - * - *

              Windowing a {@code PCollection} divides the elements into windows based - * on the associated event time for each element. This is especially useful - * for {@code PCollection}s with unbounded size, since it allows operating on - * a sub-group of the elements placed into a related window. For {@code PCollection}s - * with a bounded size (aka. conventional batch mode), by default, all data is - * implicitly in a single window, unless {@code Window} is applied. - * - *

              For example, a simple form of windowing divides up the data into - * fixed-width time intervals, using {@link FixedWindows}. - * The following example demonstrates how to use {@code Window} in a pipeline - * that counts the number of occurrences of strings each minute: - * - *

               {@code
              - * PCollection items = ...;
              - * PCollection windowed_items = items.apply(
              - *   Window.into(FixedWindows.of(Duration.standardMinutes(1))));
              - * PCollection> windowed_counts = windowed_items.apply(
              - *   Count.perElement());
              - * } 
              - * - *

              Let (data, timestamp) denote a data element along with its timestamp. - * Then, if the input to this pipeline consists of - * {("foo", 15s), ("bar", 30s), ("foo", 45s), ("foo", 1m30s)}, - * the output will be - * {(KV("foo", 2), 1m), (KV("bar", 1), 1m), (KV("foo", 1), 2m)} - * - *

              Several predefined {@link WindowFn}s are provided: - *

                - *
              • {@link FixedWindows} partitions the timestamps into fixed-width intervals. - *
              • {@link SlidingWindows} places data into overlapping fixed-width intervals. - *
              • {@link Sessions} groups data into sessions where each item in a window - * is separated from the next by no more than a specified gap. - *
              - * - *

              Additionally, custom {@link WindowFn}s can be created, by creating new - * subclasses of {@link WindowFn}. - * - *

              Triggers

              - * - *

              {@link Window.Bound#triggering(TriggerBuilder)} allows specifying a trigger to control when - * (in processing time) results for the given window can be produced. If unspecified, the default - * behavior is to trigger first when the watermark passes the end of the window, and then trigger - * again every time there is late arriving data. - * - *

              Elements are added to the current window pane as they arrive. When the root trigger fires, - * output is produced based on the elements in the current pane. - * - *

              Depending on the trigger, this can be used both to output partial results - * early during the processing of the whole window, and to deal with late - * arriving in batches. - * - *

              Continuing the earlier example, if we wanted to emit the values that were available - * when the watermark passed the end of the window, and then output any late arriving - * elements once-per (actual hour) hour until we have finished processing the next 24-hours of data. - * (The use of watermark time to stop processing tends to be more robust if the data source is slow - * for a few days, etc.) - * - *

               {@code
              - * PCollection items = ...;
              - * PCollection windowed_items = items.apply(
              - *   Window.into(FixedWindows.of(Duration.standardMinutes(1)))
              - *      .triggering(
              - *          AfterWatermark.pastEndOfWindow()
              - *              .withLateFirings(AfterProcessingTime
              - *                  .pastFirstElementInPane().plusDelayOf(Duration.standardHours(1))))
              - *      .withAllowedLateness(Duration.standardDays(1)));
              - * PCollection> windowed_counts = windowed_items.apply(
              - *   Count.perElement());
              - * } 
              - * - *

              On the other hand, if we wanted to get early results every minute of processing - * time (for which there were new elements in the given window) we could do the following: - * - *

               {@code
              - * PCollection windowed_items = items.apply(
              - *   Window.into(FixedWindows.of(Duration.standardMinutes(1))
              - *      .triggering(
              - *      .triggering(
              - *          AfterWatermark.pastEndOfWindow()
              - *              .withEarlyFirings(AfterProcessingTime
              - *                  .pastFirstElementInPane().plusDelayOf(Duration.standardMinutes(1))))
              - *      .withAllowedLateness(Duration.ZERO));
              - * } 
              - * - *

              After a {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey} the trigger is set to - * a trigger that will preserve the intent of the upstream trigger. See - * {@link Trigger#getContinuationTrigger} for more information. - * - *

              See {@link Trigger} for details on the available triggers. - */ -public class Window { - - /** - * Specifies the conditions under which a final pane will be created when a window is permanently - * closed. - */ - public enum ClosingBehavior { - /** - * Always fire the last pane. Even if there is no new data since the previous firing, an element - * with {@link PaneInfo#isLast()} {@code true} will be produced. - */ - FIRE_ALWAYS, - /** - * Only fire the last pane if there is new data since the previous firing. - * - *

              This is the default behavior. - */ - FIRE_IF_NON_EMPTY; - } - - /** - * Creates a {@code Window} {@code PTransform} with the given name. - * - *

              See the discussion of Naming in - * {@link com.google.cloud.dataflow.sdk.transforms.ParDo} for more explanation. - * - *

              The resulting {@code PTransform} is incomplete, and its input/output - * type is not yet bound. Use {@link Window.Unbound#into} to specify the - * {@link WindowFn} to use, which will also bind the input/output type of this - * {@code PTransform}. - */ - public static Unbound named(String name) { - return new Unbound().named(name); - } - - /** - * Creates a {@code Window} {@code PTransform} that uses the given - * {@link WindowFn} to window the data. - * - *

              The resulting {@code PTransform}'s types have been bound, with both the - * input and output being a {@code PCollection}, inferred from the types of - * the argument {@code WindowFn}. It is ready to be applied, or further - * properties can be set on it first. - */ - public static Bound into(WindowFn fn) { - return new Unbound().into(fn); - } - - /** - * Sets a non-default trigger for this {@code Window} {@code PTransform}. - * Elements that are assigned to a specific window will be output when - * the trigger fires. - * - *

              Must also specify allowed lateness using {@link #withAllowedLateness} and accumulation - * mode using either {@link #discardingFiredPanes()} or {@link #accumulatingFiredPanes()}. - */ - @Experimental(Kind.TRIGGER) - public static Bound triggering(TriggerBuilder trigger) { - return new Unbound().triggering(trigger); - } - - /** - * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and - * Triggering behavior, and that discards elements in a pane after they are triggered. - * - *

              Does not modify this transform. The resulting {@code PTransform} is sufficiently - * specified to be applied, but more properties can still be specified. - */ - @Experimental(Kind.TRIGGER) - public static Bound discardingFiredPanes() { - return new Unbound().discardingFiredPanes(); - } - - /** - * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and - * Triggering behavior, and that accumulates elements in a pane after they are triggered. - * - *

              Does not modify this transform. The resulting {@code PTransform} is sufficiently - * specified to be applied, but more properties can still be specified. - */ - @Experimental(Kind.TRIGGER) - public static Bound accumulatingFiredPanes() { - return new Unbound().accumulatingFiredPanes(); - } - - /** - * Override the amount of lateness allowed for data elements in the pipeline. Like - * the other properties on this {@link Window} operation, this will be applied at - * the next {@link GroupByKey}. Any elements that are later than this as decided by - * the system-maintained watermark will be dropped. - * - *

              This value also determines how long state will be kept around for old windows. - * Once no elements will be added to a window (because this duration has passed) any state - * associated with the window will be cleaned up. - */ - @Experimental(Kind.TRIGGER) - public static Bound withAllowedLateness(Duration allowedLateness) { - return new Unbound().withAllowedLateness(allowedLateness); - } - - /** - * An incomplete {@code Window} transform, with unbound input/output type. - * - *

              Before being applied, {@link Window.Unbound#into} must be - * invoked to specify the {@link WindowFn} to invoke, which will also - * bind the input/output type of this {@code PTransform}. - */ - public static class Unbound { - String name; - - Unbound() {} - - Unbound(String name) { - this.name = name; - } - - /** - * Returns a new {@code Window} transform that's like this - * transform but with the specified name. Does not modify this - * transform. The resulting transform is still incomplete. - * - *

              See the discussion of Naming in - * {@link com.google.cloud.dataflow.sdk.transforms.ParDo} for more - * explanation. - */ - public Unbound named(String name) { - return new Unbound(name); - } - - /** - * Returns a new {@code Window} {@code PTransform} that's like this - * transform but that will use the given {@link WindowFn}, and that has - * its input and output types bound. Does not modify this transform. The - * resulting {@code PTransform} is sufficiently specified to be applied, - * but more properties can still be specified. - */ - public Bound into(WindowFn fn) { - return new Bound(name).into(fn); - } - - /** - * Sets a non-default trigger for this {@code Window} {@code PTransform}. - * Elements that are assigned to a specific window will be output when - * the trigger fires. - * - *

              {@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger} - * has more details on the available triggers. - * - *

              Must also specify allowed lateness using {@link #withAllowedLateness} and accumulation - * mode using either {@link #discardingFiredPanes()} or {@link #accumulatingFiredPanes()}. - */ - @Experimental(Kind.TRIGGER) - public Bound triggering(TriggerBuilder trigger) { - return new Bound(name).triggering(trigger); - } - - /** - * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and - * Triggering behavior, and that discards elements in a pane after they are triggered. - * - *

              Does not modify this transform. The resulting {@code PTransform} is sufficiently - * specified to be applied, but more properties can still be specified. - */ - @Experimental(Kind.TRIGGER) - public Bound discardingFiredPanes() { - return new Bound(name).discardingFiredPanes(); - } - - /** - * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and - * Triggering behavior, and that accumulates elements in a pane after they are triggered. - * - *

              Does not modify this transform. The resulting {@code PTransform} is sufficiently - * specified to be applied, but more properties can still be specified. - */ - @Experimental(Kind.TRIGGER) - public Bound accumulatingFiredPanes() { - return new Bound(name).accumulatingFiredPanes(); - } - - /** - * Override the amount of lateness allowed for data elements in the pipeline. Like - * the other properties on this {@link Window} operation, this will be applied at - * the next {@link GroupByKey}. Any elements that are later than this as decided by - * the system-maintained watermark will be dropped. - * - *

              This value also determines how long state will be kept around for old windows. - * Once no elements will be added to a window (because this duration has passed) any state - * associated with the window will be cleaned up. - * - *

              Depending on the trigger this may not produce a pane with {@link PaneInfo#isLast}. See - * {@link ClosingBehavior#FIRE_IF_NON_EMPTY} for more details. - */ - @Experimental(Kind.TRIGGER) - public Bound withAllowedLateness(Duration allowedLateness) { - return new Bound(name).withAllowedLateness(allowedLateness); - } - - /** - * Override the amount of lateness allowed for data elements in the pipeline. Like - * the other properties on this {@link Window} operation, this will be applied at - * the next {@link GroupByKey}. Any elements that are later than this as decided by - * the system-maintained watermark will be dropped. - * - *

              This value also determines how long state will be kept around for old windows. - * Once no elements will be added to a window (because this duration has passed) any state - * associated with the window will be cleaned up. - */ - @Experimental(Kind.TRIGGER) - public Bound withAllowedLateness(Duration allowedLateness, ClosingBehavior behavior) { - return new Bound(name).withAllowedLateness(allowedLateness, behavior); - } - } - - /** - * A {@code PTransform} that windows the elements of a {@code PCollection}, - * into finite windows according to a user-specified {@code WindowFn}. - * - * @param The type of elements this {@code Window} is applied to - */ - public static class Bound extends PTransform, PCollection> { - - @Nullable private final WindowFn windowFn; - @Nullable private final Trigger trigger; - @Nullable private final AccumulationMode mode; - @Nullable private final Duration allowedLateness; - @Nullable private final ClosingBehavior closingBehavior; - @Nullable private final OutputTimeFn outputTimeFn; - - private Bound(String name, - @Nullable WindowFn windowFn, @Nullable Trigger trigger, - @Nullable AccumulationMode mode, @Nullable Duration allowedLateness, - ClosingBehavior behavior, @Nullable OutputTimeFn outputTimeFn) { - super(name); - this.windowFn = windowFn; - this.trigger = trigger; - this.mode = mode; - this.allowedLateness = allowedLateness; - this.closingBehavior = behavior; - this.outputTimeFn = outputTimeFn; - } - - private Bound(String name) { - this(name, null, null, null, null, null, null); - } - - /** - * Returns a new {@code Window} {@code PTransform} that's like this - * transform but that will use the given {@link WindowFn}, and that has - * its input and output types bound. Does not modify this transform. The - * resulting {@code PTransform} is sufficiently specified to be applied, - * but more properties can still be specified. - */ - private Bound into(WindowFn windowFn) { - try { - windowFn.windowCoder().verifyDeterministic(); - } catch (NonDeterministicException e) { - throw new IllegalArgumentException("Window coders must be deterministic.", e); - } - - return new Bound<>( - name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn); - } - - /** - * Returns a new {@code Window} {@code PTransform} that's like this - * {@code PTransform} but with the specified name. Does not - * modify this {@code PTransform}. - * - *

              See the discussion of Naming in - * {@link com.google.cloud.dataflow.sdk.transforms.ParDo} for more - * explanation. - */ - public Bound named(String name) { - return new Bound<>( - name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn); - } - - /** - * Sets a non-default trigger for this {@code Window} {@code PTransform}. - * Elements that are assigned to a specific window will be output when - * the trigger fires. - * - *

              {@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger} - * has more details on the available triggers. - * - *

              Must also specify allowed lateness using {@link #withAllowedLateness} and accumulation - * mode using either {@link #discardingFiredPanes()} or {@link #accumulatingFiredPanes()}. - */ - @Experimental(Kind.TRIGGER) - public Bound triggering(TriggerBuilder trigger) { - return new Bound( - name, - windowFn, - trigger.buildTrigger(), - mode, - allowedLateness, - closingBehavior, - outputTimeFn); - } - - /** - * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and - * Triggering behavior, and that discards elements in a pane after they are triggered. - * - *

              Does not modify this transform. The resulting {@code PTransform} is sufficiently - * specified to be applied, but more properties can still be specified. - */ - @Experimental(Kind.TRIGGER) - public Bound discardingFiredPanes() { - return new Bound( - name, - windowFn, - trigger, - AccumulationMode.DISCARDING_FIRED_PANES, - allowedLateness, - closingBehavior, - outputTimeFn); - } - - /** - * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and - * Triggering behavior, and that accumulates elements in a pane after they are triggered. - * - *

              Does not modify this transform. The resulting {@code PTransform} is sufficiently - * specified to be applied, but more properties can still be specified. - */ - @Experimental(Kind.TRIGGER) - public Bound accumulatingFiredPanes() { - return new Bound( - name, - windowFn, - trigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, - allowedLateness, - closingBehavior, - outputTimeFn); - } - - /** - * Override the amount of lateness allowed for data elements in the pipeline. Like - * the other properties on this {@link Window} operation, this will be applied at - * the next {@link GroupByKey}. Any elements that are later than this as decided by - * the system-maintained watermark will be dropped. - * - *

              This value also determines how long state will be kept around for old windows. - * Once no elements will be added to a window (because this duration has passed) any state - * associated with the window will be cleaned up. - * - *

              Depending on the trigger this may not produce a pane with {@link PaneInfo#isLast}. See - * {@link ClosingBehavior#FIRE_IF_NON_EMPTY} for more details. - */ - @Experimental(Kind.TRIGGER) - public Bound withAllowedLateness(Duration allowedLateness) { - return new Bound( - name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn); - } - - /** - * (Experimental) Override the default {@link OutputTimeFn}, to control - * the output timestamp of values output from a {@link GroupByKey} operation. - */ - @Experimental(Kind.OUTPUT_TIME) - public Bound withOutputTimeFn(OutputTimeFn outputTimeFn) { - return new Bound( - name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn); - } - - /** - * Override the amount of lateness allowed for data elements in the pipeline. Like - * the other properties on this {@link Window} operation, this will be applied at - * the next {@link GroupByKey}. Any elements that are later than this as decided by - * the system-maintained watermark will be dropped. - * - *

              This value also determines how long state will be kept around for old windows. - * Once no elements will be added to a window (because this duration has passed) any state - * associated with the window will be cleaned up. - */ - @Experimental(Kind.TRIGGER) - public Bound withAllowedLateness(Duration allowedLateness, ClosingBehavior behavior) { - return new Bound(name, windowFn, trigger, mode, allowedLateness, behavior, outputTimeFn); - } - - /** - * Get the output strategy of this {@link Window.Bound Window PTransform}. For internal use - * only. - */ - // Rawtype cast of OutputTimeFn cannot be eliminated with intermediate variable, as it is - // casting between wildcards - public WindowingStrategy getOutputStrategyInternal( - WindowingStrategy inputStrategy) { - WindowingStrategy result = inputStrategy; - if (windowFn != null) { - result = result.withWindowFn(windowFn); - } - if (trigger != null) { - result = result.withTrigger(trigger); - } - if (mode != null) { - result = result.withMode(mode); - } - if (allowedLateness != null) { - result = result.withAllowedLateness(allowedLateness); - } - if (closingBehavior != null) { - result = result.withClosingBehavior(closingBehavior); - } - if (outputTimeFn != null) { - result = result.withOutputTimeFn(outputTimeFn); - } - return result; - } - - /** - * Get the {@link WindowFn} of this {@link Window.Bound Window PTransform}. - */ - public WindowFn getWindowFn() { - return windowFn; - } - - @Override - public void validate(PCollection input) { - WindowingStrategy outputStrategy = - getOutputStrategyInternal(input.getWindowingStrategy()); - - // Make sure that the windowing strategy is complete & valid. - if (outputStrategy.isTriggerSpecified() - && !(outputStrategy.getTrigger().getSpec() instanceof DefaultTrigger)) { - if (!(outputStrategy.getWindowFn() instanceof GlobalWindows) - && !outputStrategy.isAllowedLatenessSpecified()) { - throw new IllegalArgumentException("Except when using GlobalWindows," - + " calling .triggering() to specify a trigger requires that the allowed lateness be" - + " specified using .withAllowedLateness() to set the upper bound on how late data" - + " can arrive before being dropped. See Javadoc for more details."); - } - - if (!outputStrategy.isModeSpecified()) { - throw new IllegalArgumentException( - "Calling .triggering() to specify a trigger requires that the accumulation mode be" - + " specified using .discardingFiredPanes() or .accumulatingFiredPanes()." - + " See Javadoc for more details."); - } - } - } - - @Override - public PCollection apply(PCollection input) { - WindowingStrategy outputStrategy = - getOutputStrategyInternal(input.getWindowingStrategy()); - PCollection output; - if (windowFn != null) { - // If the windowFn changed, we create a primitive, and run the AssignWindows operation here. - output = assignWindows(input, windowFn); - } else { - // If the windowFn didn't change, we just run a pass-through transform and then set the - // new windowing strategy. - output = input.apply(Window.identity()); - } - return output.setWindowingStrategyInternal(outputStrategy); - } - - private PCollection assignWindows( - PCollection input, WindowFn windowFn) { - return input.apply("AssignWindows", ParDo.of(new AssignWindowsDoFn(windowFn))); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - - if (windowFn != null) { - builder - .add(DisplayData.item("windowFn", windowFn.getClass()) - .withLabel("Windowing Function")) - .include(windowFn); - } - - if (allowedLateness != null) { - builder.addIfNotDefault(DisplayData.item("allowedLateness", allowedLateness) - .withLabel("Allowed Lateness"), - Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis())); - } - - if (trigger != null && !(trigger instanceof DefaultTrigger)) { - builder.add(DisplayData.item("trigger", trigger.toString()) - .withLabel("Trigger")); - } - - if (mode != null) { - builder.add(DisplayData.item("accumulationMode", mode.toString()) - .withLabel("Accumulation Mode")); - } - - if (closingBehavior != null) { - builder.add(DisplayData.item("closingBehavior", closingBehavior.toString()) - .withLabel("Window Closing Behavior")); - } - - if (outputTimeFn != null) { - builder.add(DisplayData.item("outputTimeFn", outputTimeFn.getClass()) - .withLabel("Output Time Function")); - } - } - - @Override - protected Coder getDefaultOutputCoder(PCollection input) { - return input.getCoder(); - } - - @Override - protected String getKindString() { - return "Window.Into()"; - } - } - - ///////////////////////////////////////////////////////////////////////////// - - private static PTransform, PCollection> identity() { - return ParDo.named("Identity").of(new DoFn() { - @Override public void processElement(ProcessContext c) { - c.output(c.element()); - } - }); - } - - /** - * Creates a {@code Window} {@code PTransform} that does not change assigned - * windows, but will cause windows to be merged again as part of the next - * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}. - */ - public static Remerge remerge() { - return new Remerge(); - } - - /** - * {@code PTransform} that does not change assigned windows, but will cause - * windows to be merged again as part of the next - * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}. - */ - public static class Remerge extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection input) { - WindowingStrategy outputWindowingStrategy = getOutputWindowing( - input.getWindowingStrategy()); - - return input.apply(Window.identity()) - .setWindowingStrategyInternal(outputWindowingStrategy); - } - - private WindowingStrategy getOutputWindowing( - WindowingStrategy inputStrategy) { - if (inputStrategy.getWindowFn() instanceof InvalidWindows) { - @SuppressWarnings("unchecked") - InvalidWindows invalidWindows = (InvalidWindows) inputStrategy.getWindowFn(); - return inputStrategy.withWindowFn(invalidWindows.getOriginalWindowFn()); - } else { - return inputStrategy; - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java deleted file mode 100644 index 9bbb28fb62..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowFn.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.HasDisplayData; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.common.collect.Ordering; - -import org.joda.time.Instant; - -import java.io.Serializable; -import java.util.Collection; - -/** - * The argument to the {@link Window} transform used to assign elements into - * windows and to determine how windows are merged. See {@link Window} for more - * information on how {@code WindowFn}s are used and for a library of - * predefined {@code WindowFn}s. - * - *

              Users will generally want to use the predefined - * {@code WindowFn}s, but it is also possible to create new - * subclasses. - * - *

              To create a custom {@code WindowFn}, inherit from this class and override all required - * methods. If no merging is required, inherit from {@link NonMergingWindowFn} - * instead. If no merging is required and each element is assigned to a single window, inherit from - * {@code PartitioningWindowFn}. Inheriting from the most specific subclass will enable more - * optimizations in the runner. - * - * @param type of elements being windowed - * @param {@link BoundedWindow} subclass used to represent the - * windows used by this {@code WindowFn} - */ -public abstract class WindowFn - implements Serializable, HasDisplayData { - /** - * Information available when running {@link #assignWindows}. - */ - public abstract class AssignContext { - /** - * Returns the current element. - */ - public abstract T element(); - - /** - * Returns the timestamp of the current element. - */ - public abstract Instant timestamp(); - - /** - * Returns the windows the current element was in, prior to this - * {@code WindowFn} being called. - */ - public abstract Collection windows(); - } - - /** - * Given a timestamp and element, returns the set of windows into which it - * should be placed. - */ - public abstract Collection assignWindows(AssignContext c) throws Exception; - - /** - * Information available when running {@link #mergeWindows}. - */ - public abstract class MergeContext { - /** - * Returns the current set of windows. - */ - public abstract Collection windows(); - - /** - * Signals to the framework that the windows in {@code toBeMerged} should - * be merged together to form {@code mergeResult}. - * - *

              {@code toBeMerged} should be a subset of {@link #windows} - * and disjoint from the {@code toBeMerged} set of previous calls - * to {@code merge}. - * - *

              {@code mergeResult} must either not be in {@link #windows} or be in - * {@code toBeMerged}. - * - * @throws IllegalArgumentException if any elements of toBeMerged are not - * in windows(), or have already been merged - */ - public abstract void merge(Collection toBeMerged, W mergeResult) - throws Exception; - } - - /** - * Does whatever merging of windows is necessary. - * - *

              See {@link MergeOverlappingIntervalWindows#mergeWindows} for an - * example of how to override this method. - */ - public abstract void mergeWindows(MergeContext c) throws Exception; - - /** - * Returns whether this performs the same merging as the given - * {@code WindowFn}. - */ - public abstract boolean isCompatible(WindowFn other); - - /** - * Returns the {@link Coder} used for serializing the windows used - * by this windowFn. - */ - public abstract Coder windowCoder(); - - /** - * Returns the window of the side input corresponding to the given window of - * the main input. - * - *

              Authors of custom {@code WindowFn}s should override this. - */ - public abstract W getSideInputWindow(BoundedWindow window); - - /** - * @deprecated Implement {@link #getOutputTimeFn} to return one of the appropriate - * {@link OutputTimeFns}, or a custom {@link OutputTimeFn} extending - * {@link OutputTimeFn.Defaults}. - */ - @Deprecated - @Experimental(Kind.OUTPUT_TIME) - public Instant getOutputTime(Instant inputTimestamp, W window) { - return getOutputTimeFn().assignOutputTime(inputTimestamp, window); - } - - /** - * Provides a default implementation for {@link WindowingStrategy#getOutputTimeFn()}. - * See the full specification there. - * - *

              If this {@link WindowFn} doesn't produce overlapping windows, this need not (and probably - * should not) override any of the default implementations in {@link OutputTimeFn.Defaults}. - * - *

              If this {@link WindowFn} does produce overlapping windows that can be predicted here, it is - * suggested that the result in later overlapping windows is past the end of earlier windows so - * that the later windows don't prevent the watermark from progressing past the end of the earlier - * window. - * - *

              For example, a timestamp in a sliding window should be moved past the beginning of the next - * sliding window. See {@link SlidingWindows#getOutputTimeFn}. - */ - @Experimental(Kind.OUTPUT_TIME) - public OutputTimeFn getOutputTimeFn() { - return new OutputAtEarliestAssignedTimestamp<>(this); - } - - /** - * Returns true if this {@code WindowFn} never needs to merge any windows. - */ - public boolean isNonMerging() { - return false; - } - - /** - * Returns true if this {@code WindowFn} assigns each element to a single window. - */ - public boolean assignsToSingleWindow() { - return false; - } - - /** - * {@inheritDoc} - * - *

              By default, does not register any display data. Implementors may override this method - * to provide their own display data. - */ - @Override - public void populateDisplayData(DisplayData.Builder builder) { - } - - /** - * A compatibility adapter that will return the assigned timestamps according to the - * {@link WindowFn}, which was the prior policy. Specifying the assigned output timestamps - * on the {@link WindowFn} is now deprecated. - */ - private static class OutputAtEarliestAssignedTimestamp - extends OutputTimeFn.Defaults { - - private final WindowFn windowFn; - - public OutputAtEarliestAssignedTimestamp(WindowFn windowFn) { - this.windowFn = windowFn; - } - - /** - * {@inheritDoc} - * - * @return the result of {@link WindowFn#getOutputTime windowFn.getOutputTime()}. - */ - @Override - @SuppressWarnings("deprecation") // this is an adapter for the deprecated behavior - public Instant assignOutputTime(Instant timestamp, W window) { - return windowFn.getOutputTime(timestamp, window); - } - - @Override - public Instant combine(Instant outputTime, Instant otherOutputTime) { - return Ordering.natural().min(outputTime, otherOutputTime); - } - - /** - * {@inheritDoc} - * - * @return {@code true}. When the {@link OutputTimeFn} is not overridden by {@link WindowFn} - * or {@link WindowingStrategy}, the minimum output timestamp is taken, which depends - * only on the minimum input timestamp by monotonicity of {@link #assignOutputTime}. - */ - @Override - public boolean dependsOnlyOnEarliestInputTimestamp() { - return true; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/package-info.java deleted file mode 100644 index 65ccf710bd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/package-info.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines the {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} transform - * for dividing the elements in a PCollection into windows, and the - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger} for controlling when those - * elements are output. - * - *

              {@code Window} logically divides up or groups the elements of a - * {@link com.google.cloud.dataflow.sdk.values.PCollection} into finite windows according to a - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn}. - * The output of {@code Window} contains the same elements as input, but they - * have been logically assigned to windows. The next - * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}s, including one - * within composite transforms, will group by the combination of keys and - * windows. - * - *

              Windowing a {@code PCollection} allows chunks of it to be processed - * individually, before the entire {@code PCollection} is available. This is - * especially important for {@code PCollection}s with unbounded size, since the full - * {@code PCollection} is never available at once. - * - *

              For {@code PCollection}s with a bounded size, by default, all data is implicitly in a - * single window, and this replicates conventional batch mode. However, windowing can still be a - * convenient way to express time-sliced algorithms over bounded {@code PCollection}s. - * - *

              As elements are assigned to a window, they are are placed into a pane. When the trigger fires - * all of the elements in the current pane are output. - * - *

              The {@link com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger} will output a - * window when the system watermark passes the end of the window. See - * {@link com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark} for details on the - * watermark. - */ -package com.google.cloud.dataflow.sdk.transforms.windowing; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java deleted file mode 100644 index f93b81dcf1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ActiveWindowSet.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; - -import com.google.common.annotations.VisibleForTesting; - -import java.util.Collection; -import java.util.Set; - -/** - * Track which windows are active, and the state address window(s) under which their - * state is stored. Also help with the multi-step process of merging windows and their associated - * state. - * - *

              When windows are merged we must also merge their state. For example, we may need to - * concatenate buffered elements, sum a count of elements, or find a new minimum timestamp. - * If we start with two windows {@code Wa} and {@code Wb} and later discover they should be - * merged into window {@code Wab} then, naively, we must copy and merge the states of {@code Wa} - * and {@code Wab} into {@code Wab}. - * - *

              However, the common case for merging windows is for a new window to be merged into an - * existing window. Thus, if {@code Wa} is the existing window and {@code Wb} the new window it - * is more efficient to leave the state for {@code Wa} where it is, and simply redirect {@code - * Wab} to it. In this case we say {@code Wab} has a state address window of {@code Wa}. - * - *

              Even if windows {@code Wa} and {@code Wb} already have state, it can still be more efficient - * to append the state of {@code Wb} onto {@code Wa} rather than copy the state from {@code Wa} - * and {@code Wb} into {@code Wab}. - * - *

              We use the following terminology for windows: - *

                - *
              1. ACTIVE: A window that has state associated with it and has not itself been merged - * away. The window may have one (or more) state address windows under which its - * non-empty state is stored. A state value for an ACTIVE window must be derived by reading - * the state in (all of) its state address windows. Note that only pre 1.4 pipelines - * use multiple state address windows per active window. From 1.4 onwards we eagerly merge - * window state into a single state address window. - *
              2. NEW: The initial state for a window of an incoming element which is not - * already ACTIVE. We have not yet called {@link WindowFn#mergeWindows}, and so don't yet know - * whether the window will be be merged into another NEW or ACTIVE window, or will - * become an ACTIVE window in its own right. - *
              - * - *

              If no windows will ever be merged we can use the trivial implementation {@link - * NonMergingActiveWindowSet}. Otherwise, the actual implementation of this data structure is in - * {@link MergingActiveWindowSet}. - * - * @param the type of window being managed - */ -public interface ActiveWindowSet { - /** - * Callback for {@link #merge}. - */ - public interface MergeCallback { - /** - * Called when windows are about to be merged, but before any {@link #onMerge} callback - * has been made. - * - * @param toBeMerged the windows about to be merged. - * @param mergeResult the result window, either a member of {@code toBeMerged} or new. - */ - void prefetchOnMerge(Collection toBeMerged, W mergeResult) throws Exception; - - /** - * Called when windows are about to be merged, after all {@link #prefetchOnMerge} calls - * have been made, but before the active window set has been updated to reflect the merge. - * - * @param toBeMerged the windows about to be merged. - * @param mergeResult the result window, either a member of {@code toBeMerged} or new. - */ - void onMerge(Collection toBeMerged, W mergeResult) throws Exception; - } - - /** - * Remove any remaining NEW windows since they were not promoted to being ACTIVE - * by {@link #ensureWindowIsActive} and we don't need to record anything about them. - */ - void cleanupTemporaryWindows(); - - /** - * Save any state changes needed. - */ - void persist(); - - /** - * Return (a view of) the set of currently ACTIVE and NEW windows. - */ - Set getActiveAndNewWindows(); - - /** - * Return {@code true} if {@code window} is ACTIVE. - */ - boolean isActive(W window); - - /** - * Return {@code true} if {@code window} is ACTIVE or NEW. - */ - boolean isActiveOrNew(W window); - - /** - * Called when an incoming element indicates it is a member of {@code window}, but before we - * have started processing that element. If {@code window} is not already known to be ACTIVE, - * then add it as NEW. - */ - void ensureWindowExists(W window); - - /** - * Called when a NEW or ACTIVE window is now known to be ACTIVE. - * Ensure that if it is NEW then it becomes ACTIVE (with itself as its only state address - * window). - */ - void ensureWindowIsActive(W window); - - /** - * If {@code window} is not already known to be ACTIVE then add it as ACTIVE. - * For testing only. - */ - @VisibleForTesting - void addActiveForTesting(W window); - - /** - * Remove {@code window} from the set. - */ - void remove(W window); - - /** - * Invoke {@link WindowFn#mergeWindows} on the {@code WindowFn} associated with this window set, - * merging as many of the NEW and ACTIVE windows as possible. {@code mergeCallback} will be - * invoked for each group of windows that are merged. After this all merge result windows will - * be ACTIVE, and all windows which have been merged away will be neither ACTIVE nor NEW. - */ - void merge(MergeCallback mergeCallback) throws Exception; - - /** - * Signal that all state in {@link #readStateAddresses} for {@code window} has been merged into - * the {@link #writeStateAddress} for {@code window}. - */ - void merged(W window); - - /** - * Return the state address windows for ACTIVE {@code window} from which all state associated - * should be read and merged. - */ - Set readStateAddresses(W window); - - /** - * Return the state address window of ACTIVE {@code window} into which all new state should be - * written. Always one of the results of {@link #readStateAddresses}. - */ - W writeStateAddress(W window); - - /** - * Return the state address window into which all new state should be written after - * ACTIVE windows {@code toBeMerged} have been merged into {@code mergeResult}. - */ - W mergedWriteStateAddress(Collection toBeMerged, W mergeResult); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java deleted file mode 100644 index c711093f3b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ApiSurface.java +++ /dev/null @@ -1,648 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.common.base.Joiner; -import com.google.common.base.Supplier; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.google.common.collect.Sets; -import com.google.common.reflect.ClassPath; -import com.google.common.reflect.ClassPath.ClassInfo; -import com.google.common.reflect.Invokable; -import com.google.common.reflect.Parameter; -import com.google.common.reflect.TypeToken; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * Represents the API surface of a package prefix. Used for accessing public classes, - * methods, and the types they reference, to control what dependencies are re-exported. - * - *

              For the purposes of calculating the public API surface, exposure includes any public - * or protected occurrence of: - * - *

                - *
              • superclasses - *
              • interfaces implemented - *
              • actual type arguments to generic types - *
              • array component types - *
              • method return types - *
              • method parameter types - *
              • type variable bounds - *
              • wildcard bounds - *
              - * - *

              Exposure is a transitive property. The resulting map excludes primitives - * and array classes themselves. - * - *

              It is prudent (though not required) to prune prefixes like "java" via the builder - * method {@link #pruningPrefix} to halt the traversal so it does not uselessly catalog references - * that are not interesting. - */ -@SuppressWarnings("rawtypes") -public class ApiSurface { - private static Logger logger = LoggerFactory.getLogger(ApiSurface.class); - - /** - * Returns an empty {@link ApiSurface}. - */ - public static ApiSurface empty() { - logger.debug("Returning an empty ApiSurface"); - return new ApiSurface(Collections.>emptySet(), Collections.emptySet()); - } - - /** - * Returns an {@link ApiSurface} object representing the given package and all subpackages. - */ - public static ApiSurface ofPackage(String packageName) throws IOException { - return ApiSurface.empty().includingPackage(packageName); - } - - /** - * Returns an {@link ApiSurface} object representing just the surface of the given class. - */ - public static ApiSurface ofClass(Class clazz) { - return ApiSurface.empty().includingClass(clazz); - } - - /** - * Returns an {@link ApiSurface} like this one, but also including the named - * package and all of its subpackages. - */ - public ApiSurface includingPackage(String packageName) throws IOException { - ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader()); - - Set> newRootClasses = Sets.newHashSet(); - for (ClassInfo classInfo : classPath.getTopLevelClassesRecursive(packageName)) { - Class clazz = classInfo.load(); - if (exposed(clazz.getModifiers())) { - newRootClasses.add(clazz); - } - } - logger.debug("Including package {} and subpackages: {}", packageName, newRootClasses); - newRootClasses.addAll(rootClasses); - - return new ApiSurface(newRootClasses, patternsToPrune); - } - - /** - * Returns an {@link ApiSurface} like this one, but also including the given class. - */ - public ApiSurface includingClass(Class clazz) { - Set> newRootClasses = Sets.newHashSet(); - logger.debug("Including class {}", clazz); - newRootClasses.add(clazz); - newRootClasses.addAll(rootClasses); - return new ApiSurface(newRootClasses, patternsToPrune); - } - - /** - * Returns an {@link ApiSurface} like this one, but pruning transitive - * references from classes whose full name (including package) begins with the provided prefix. - */ - public ApiSurface pruningPrefix(String prefix) { - return pruningPattern(Pattern.compile(Pattern.quote(prefix) + ".*")); - } - - /** - * Returns an {@link ApiSurface} like this one, but pruning references from the named - * class. - */ - public ApiSurface pruningClassName(String className) { - return pruningPattern(Pattern.compile(Pattern.quote(className))); - } - - /** - * Returns an {@link ApiSurface} like this one, but pruning references from the - * provided class. - */ - public ApiSurface pruningClass(Class clazz) { - return pruningClassName(clazz.getName()); - } - - /** - * Returns an {@link ApiSurface} like this one, but pruning transitive - * references from classes whose full name (including package) begins with the provided prefix. - */ - public ApiSurface pruningPattern(Pattern pattern) { - Set newPatterns = Sets.newHashSet(); - newPatterns.addAll(patternsToPrune); - newPatterns.add(pattern); - return new ApiSurface(rootClasses, newPatterns); - } - - /** - * See {@link #pruningPattern(Pattern)}. - */ - public ApiSurface pruningPattern(String patternString) { - return pruningPattern(Pattern.compile(patternString)); - } - - /** - * Returns all public classes originally belonging to the package - * in the {@link ApiSurface}. - */ - public Set> getRootClasses() { - return rootClasses; - } - - /** - * Returns exposed types in this set, including arrays and primitives as - * specified. - */ - public Set> getExposedClasses() { - return getExposedToExposers().keySet(); - } - - /** - * Returns a path from an exposed class to a root class. There may be many, but this - * gives only one. - * - *

              If there are only cycles, with no path back to a root class, throws - * IllegalStateException. - */ - public List> getAnyExposurePath(Class exposedClass) { - Set> excluded = Sets.newHashSet(); - excluded.add(exposedClass); - List> path = getAnyExposurePath(exposedClass, excluded); - if (path == null) { - throw new IllegalArgumentException( - "Class " + exposedClass + " has no path back to any root class." - + " It should never have been considered exposed."); - } else { - return path; - } - } - - /** - * Returns a path from an exposed class to a root class. There may be many, but this - * gives only one. It will not return a path that crosses the excluded classes. - * - *

              If there are only cycles or paths through the excluded classes, returns null. - * - *

              If the class is not actually in the exposure map, throws IllegalArgumentException - */ - private List> getAnyExposurePath(Class exposedClass, Set> excluded) { - List> exposurePath = Lists.newArrayList(); - exposurePath.add(exposedClass); - - Collection> exposers = getExposedToExposers().get(exposedClass); - if (exposers.isEmpty()) { - throw new IllegalArgumentException("Class " + exposedClass + " is not exposed."); - } - - for (Class exposer : exposers) { - if (excluded.contains(exposer)) { - continue; - } - - // A null exposer means this is already a root class. - if (exposer == null) { - return exposurePath; - } - - List> restOfPath = getAnyExposurePath( - exposer, - Sets.union(excluded, Sets.newHashSet(exposer))); - - if (restOfPath != null) { - exposurePath.addAll(restOfPath); - return exposurePath; - } - } - return null; - } - - //////////////////////////////////////////////////////////////////// - - // Fields initialized upon construction - private final Set> rootClasses; - private final Set patternsToPrune; - - // Fields computed on-demand - private Multimap, Class> exposedToExposers = null; - private Pattern prunedPattern = null; - private Set visited = null; - - private ApiSurface(Set> rootClasses, Set patternsToPrune) { - this.rootClasses = rootClasses; - this.patternsToPrune = patternsToPrune; - } - - /** - * A map from exposed types to place where they are exposed, in the sense of being a part - * of a public-facing API surface. - * - *

              This map is the adjencency list representation of a directed graph, where an edge from type - * {@code T1} to type {@code T2} indicates that {@code T2} directly exposes {@code T1} in its API - * surface. - * - *

              The traversal methods in this class are designed to avoid repeatedly processing types, since - * there will almost always be cyclic references. - */ - private Multimap, Class> getExposedToExposers() { - if (exposedToExposers == null) { - constructExposedToExposers(); - } - return exposedToExposers; - } - - /** - * See {@link #getExposedToExposers}. - */ - private void constructExposedToExposers() { - visited = Sets.newHashSet(); - exposedToExposers = Multimaps.newSetMultimap( - Maps., Collection>>newHashMap(), - new Supplier>>() { - @Override - public Set> get() { - return Sets.newHashSet(); - } - }); - - for (Class clazz : rootClasses) { - addExposedTypes(clazz, null); - } - } - - /** - * A combined {@code Pattern} that implements all the pruning specified. - */ - private Pattern getPrunedPattern() { - if (prunedPattern == null) { - constructPrunedPattern(); - } - return prunedPattern; - } - - /** - * See {@link #getPrunedPattern}. - */ - private void constructPrunedPattern() { - Set prunedPatternStrings = Sets.newHashSet(); - for (Pattern patternToPrune : patternsToPrune) { - prunedPatternStrings.add(patternToPrune.pattern()); - } - prunedPattern = Pattern.compile("(" + Joiner.on(")|(").join(prunedPatternStrings) + ")"); - } - - /** - * Whether a type and all that it references should be pruned from the graph. - */ - private boolean pruned(Type type) { - return pruned(TypeToken.of(type).getRawType()); - } - - /** - * Whether a class and all that it references should be pruned from the graph. - */ - private boolean pruned(Class clazz) { - return clazz.isPrimitive() - || clazz.isArray() - || getPrunedPattern().matcher(clazz.getName()).matches(); - } - - /** - * Whether a type has already beens sufficiently processed. - */ - private boolean done(Type type) { - return visited.contains(type); - } - - private void recordExposure(Class exposed, Class cause) { - exposedToExposers.put(exposed, cause); - } - - private void recordExposure(Type exposed, Class cause) { - exposedToExposers.put(TypeToken.of(exposed).getRawType(), cause); - } - - private void visit(Type type) { - visited.add(type); - } - - /** - * See {@link #addExposedTypes(Type, Class)}. - */ - private void addExposedTypes(TypeToken type, Class cause) { - logger.debug( - "Adding exposed types from {}, which is the type in type token {}", type.getType(), type); - addExposedTypes(type.getType(), cause); - } - - /** - * Adds any references learned by following a link from {@code cause} to {@code type}. - * This will dispatch according to the concrete {@code Type} implementation. See the - * other overloads of {@code addExposedTypes} for their details. - */ - private void addExposedTypes(Type type, Class cause) { - if (type instanceof TypeVariable) { - logger.debug("Adding exposed types from {}, which is a type variable", type); - addExposedTypes((TypeVariable) type, cause); - } else if (type instanceof WildcardType) { - logger.debug("Adding exposed types from {}, which is a wildcard type", type); - addExposedTypes((WildcardType) type, cause); - } else if (type instanceof GenericArrayType) { - logger.debug("Adding exposed types from {}, which is a generic array type", type); - addExposedTypes((GenericArrayType) type, cause); - } else if (type instanceof ParameterizedType) { - logger.debug("Adding exposed types from {}, which is a parameterized type", type); - addExposedTypes((ParameterizedType) type, cause); - } else if (type instanceof Class) { - logger.debug("Adding exposed types from {}, which is a class", type); - addExposedTypes((Class) type, cause); - } else { - throw new IllegalArgumentException("Unknown implementation of Type"); - } - } - - /** - * Adds any types exposed to this set. These will - * come from the (possibly absent) bounds on the - * type variable. - */ - private void addExposedTypes(TypeVariable type, Class cause) { - if (done(type)) { - return; - } - visit(type); - for (Type bound : type.getBounds()) { - logger.debug("Adding exposed types from {}, which is a type bound on {}", bound, type); - addExposedTypes(bound, cause); - } - } - - /** - * Adds any types exposed to this set. These will come from the (possibly absent) bounds on the - * wildcard. - */ - private void addExposedTypes(WildcardType type, Class cause) { - visit(type); - for (Type lowerBound : type.getLowerBounds()) { - logger.debug( - "Adding exposed types from {}, which is a type lower bound on wildcard type {}", - lowerBound, - type); - addExposedTypes(lowerBound, cause); - } - for (Type upperBound : type.getUpperBounds()) { - logger.debug( - "Adding exposed types from {}, which is a type upper bound on wildcard type {}", - upperBound, - type); - addExposedTypes(upperBound, cause); - } - } - - /** - * Adds any types exposed from the given array type. The array type itself is not added. The - * cause of the exposure of the underlying type is considered whatever type exposed the array - * type. - */ - private void addExposedTypes(GenericArrayType type, Class cause) { - if (done(type)) { - return; - } - visit(type); - logger.debug( - "Adding exposed types from {}, which is the component type on generic array type {}", - type.getGenericComponentType(), - type); - addExposedTypes(type.getGenericComponentType(), cause); - } - - /** - * Adds any types exposed to this set. Even if the - * root type is to be pruned, the actual type arguments - * are processed. - */ - private void addExposedTypes(ParameterizedType type, Class cause) { - // Even if the type is already done, this link to it may be new - boolean alreadyDone = done(type); - if (!pruned(type)) { - visit(type); - recordExposure(type, cause); - } - if (alreadyDone) { - return; - } - - // For a parameterized type, pruning does not take place - // here, only for the raw class. - // The type parameters themselves may not be pruned, - // for example with List probably the - // standard List is pruned, but MyApiType is not. - logger.debug( - "Adding exposed types from {}, which is the raw type on parameterized type {}", - type.getRawType(), - type); - addExposedTypes(type.getRawType(), cause); - for (Type typeArg : type.getActualTypeArguments()) { - logger.debug( - "Adding exposed types from {}, which is a type argument on parameterized type {}", - typeArg, - type); - addExposedTypes(typeArg, cause); - } - } - - /** - * Adds a class and all of the types it exposes. The cause - * of the class being exposed is given, and the cause - * of everything within the class is that class itself. - */ - private void addExposedTypes(Class clazz, Class cause) { - if (pruned(clazz)) { - return; - } - // Even if `clazz` has been visited, the link from `cause` may be new - boolean alreadyDone = done(clazz); - visit(clazz); - recordExposure(clazz, cause); - if (alreadyDone || pruned(clazz)) { - return; - } - - TypeToken token = TypeToken.of(clazz); - for (TypeToken superType : token.getTypes()) { - if (!superType.equals(token)) { - logger.debug( - "Adding exposed types from {}, which is a super type token on {}", superType, clazz); - addExposedTypes(superType, clazz); - } - } - for (Class innerClass : clazz.getDeclaredClasses()) { - if (exposed(innerClass.getModifiers())) { - logger.debug( - "Adding exposed types from {}, which is an exposed inner class of {}", - innerClass, - clazz); - addExposedTypes(innerClass, clazz); - } - } - for (Field field : clazz.getDeclaredFields()) { - if (exposed(field.getModifiers())) { - logger.debug("Adding exposed types from {}, which is an exposed field on {}", field, clazz); - addExposedTypes(field, clazz); - } - } - for (Invokable invokable : getExposedInvokables(token)) { - logger.debug( - "Adding exposed types from {}, which is an exposed invokable on {}", invokable, clazz); - addExposedTypes(invokable, clazz); - } - } - - private void addExposedTypes(Invokable invokable, Class cause) { - addExposedTypes(invokable.getReturnType(), cause); - for (Annotation annotation : invokable.getAnnotations()) { - logger.debug( - "Adding exposed types from {}, which is an annotation on invokable {}", - annotation, - invokable); - addExposedTypes(annotation.annotationType(), cause); - } - for (Parameter parameter : invokable.getParameters()) { - logger.debug( - "Adding exposed types from {}, which is a parameter on invokable {}", - parameter, - invokable); - addExposedTypes(parameter, cause); - } - for (TypeToken exceptionType : invokable.getExceptionTypes()) { - logger.debug( - "Adding exposed types from {}, which is an exception type on invokable {}", - exceptionType, - invokable); - addExposedTypes(exceptionType, cause); - } - } - - private void addExposedTypes(Parameter parameter, Class cause) { - logger.debug( - "Adding exposed types from {}, which is the type of parameter {}", - parameter.getType(), - parameter); - addExposedTypes(parameter.getType(), cause); - for (Annotation annotation : parameter.getAnnotations()) { - logger.debug( - "Adding exposed types from {}, which is an annotation on parameter {}", - annotation, - parameter); - addExposedTypes(annotation.annotationType(), cause); - } - } - - private void addExposedTypes(Field field, Class cause) { - addExposedTypes(field.getGenericType(), cause); - for (Annotation annotation : field.getDeclaredAnnotations()) { - logger.debug( - "Adding exposed types from {}, which is an annotation on field {}", annotation, field); - addExposedTypes(annotation.annotationType(), cause); - } - } - - /** - * Returns an {@link Invokable} for each public methods or constructors of a type. - */ - private Set getExposedInvokables(TypeToken type) { - Set invokables = Sets.newHashSet(); - - for (Constructor constructor : type.getRawType().getConstructors()) { - if (0 != (constructor.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED))) { - invokables.add(type.constructor(constructor)); - } - } - - for (Method method : type.getRawType().getMethods()) { - if (0 != (method.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED))) { - invokables.add(type.method(method)); - } - } - - return invokables; - } - - /** - * Returns true of the given modifier bitmap indicates exposure (public or protected access). - */ - private boolean exposed(int modifiers) { - return 0 != (modifiers & (Modifier.PUBLIC | Modifier.PROTECTED)); - } - - - //////////////////////////////////////////////////////////////////////////// - - public static ApiSurface getSdkApiSurface() throws IOException { - return ApiSurface.ofPackage("com.google.cloud.dataflow") - .pruningPattern("com[.]google[.]cloud[.]dataflow.*Test") - .pruningPattern("com[.]google[.]cloud[.]dataflow.*Benchmark") - .pruningPrefix("com.google.cloud.dataflow.integration") - .pruningPrefix("java") - .pruningPrefix("com.google.api") - .pruningPrefix("com.google.auth") - .pruningPrefix("com.google.bigtable.v1") - .pruningPrefix("com.google.cloud.bigtable.config") - .pruningPrefix("com.google.cloud.bigtable.grpc.Bigtable*Name") - .pruningPrefix("com.google.datastore") - .pruningPrefix("com.google.protobuf") - .pruningPrefix("com.google.rpc") - .pruningPrefix("com.google.type") - .pruningPrefix("org.joda.time") - .pruningPrefix("org.apache.avro") - .pruningPrefix("org.junit") - .pruningPrefix("com.fasterxml.jackson.annotation") - .pruningPrefix("com.fasterxml.jackson.core") - .pruningPrefix("com.fasterxml.jackson.databind") - .pruningPrefix("com.fasterxml.jackson.deser"); - } - - public static void main(String[] args) throws Exception { - List names = Lists.newArrayList(); - for (Class clazz : getSdkApiSurface().getExposedClasses()) { - names.add(clazz.getName()); - } - List sortedNames = Lists.newArrayList(names); - Collections.sort(sortedNames); - - for (String name : sortedNames) { - System.out.println(name); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppEngineEnvironment.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppEngineEnvironment.java deleted file mode 100644 index c7fe4b4ff2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppEngineEnvironment.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.lang.reflect.InvocationTargetException; - -/** Stores whether we are running within AppEngine or not. */ -public class AppEngineEnvironment { - /** - * True if running inside of AppEngine, false otherwise. - */ - @Deprecated - public static final boolean IS_APP_ENGINE = isAppEngine(); - - /** - * Attempts to detect whether we are inside of AppEngine. - * - *

              Purposely copied and left private from private code.google.common.util.concurrent.MoreExecutors#isAppEngine. - * - * @return true if we are inside of AppEngine, false otherwise. - */ - static boolean isAppEngine() { - if (System.getProperty("com.google.appengine.runtime.environment") == null) { - return false; - } - try { - // If the current environment is null, we're not inside AppEngine. - return Class.forName("com.google.apphosting.api.ApiProxy") - .getMethod("getCurrentEnvironment") - .invoke(null) != null; - } catch (ClassNotFoundException e) { - // If ApiProxy doesn't exist, we're not on AppEngine at all. - return false; - } catch (InvocationTargetException e) { - // If ApiProxy throws an exception, we're not in a proper AppEngine environment. - return false; - } catch (IllegalAccessException e) { - // If the method isn't accessible, we're not on a supported version of AppEngine; - return false; - } catch (NoSuchMethodException e) { - // If the method doesn't exist, we're not on a supported version of AppEngine; - return false; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppliedCombineFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppliedCombineFn.java deleted file mode 100644 index 512d72def9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AppliedCombineFn.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.annotations.VisibleForTesting; - -import java.io.Serializable; - -/** - * A {@link KeyedCombineFnWithContext} with a fixed accumulator coder. This is created from a - * specific application of the {@link KeyedCombineFnWithContext}. - * - *

              Because the {@code AccumT} may reference {@code InputT}, the specific {@code Coder} - * may depend on the {@code Coder}. - * - * @param type of keys - * @param type of input values - * @param type of mutable accumulator values - * @param type of output values - */ -public class AppliedCombineFn implements Serializable { - - private final PerKeyCombineFn fn; - private final Coder accumulatorCoder; - - private final Iterable> sideInputViews; - private final KvCoder kvCoder; - private final WindowingStrategy windowingStrategy; - - private AppliedCombineFn(PerKeyCombineFn fn, - Coder accumulatorCoder, Iterable> sideInputViews, - KvCoder kvCoder, WindowingStrategy windowingStrategy) { - this.fn = fn; - this.accumulatorCoder = accumulatorCoder; - this.sideInputViews = sideInputViews; - this.kvCoder = kvCoder; - this.windowingStrategy = windowingStrategy; - } - - public static AppliedCombineFn - withAccumulatorCoder( - PerKeyCombineFn fn, - Coder accumCoder) { - return withAccumulatorCoder(fn, accumCoder, null, null, null); - } - - public static AppliedCombineFn - withAccumulatorCoder( - PerKeyCombineFn fn, - Coder accumCoder, Iterable> sideInputViews, - KvCoder kvCoder, WindowingStrategy windowingStrategy) { - // Casting down the K and InputT is safe because they're only used as inputs. - @SuppressWarnings("unchecked") - PerKeyCombineFn clonedFn = - (PerKeyCombineFn) SerializableUtils.clone(fn); - return create(clonedFn, accumCoder, sideInputViews, kvCoder, windowingStrategy); - } - - @VisibleForTesting - public static AppliedCombineFn - withInputCoder(PerKeyCombineFn fn, - CoderRegistry registry, KvCoder kvCoder) { - return withInputCoder(fn, registry, kvCoder, null, null); - } - - public static AppliedCombineFn - withInputCoder(PerKeyCombineFn fn, - CoderRegistry registry, KvCoder kvCoder, - Iterable> sideInputViews, WindowingStrategy windowingStrategy) { - // Casting down the K and InputT is safe because they're only used as inputs. - @SuppressWarnings("unchecked") - PerKeyCombineFn clonedFn = - (PerKeyCombineFn) SerializableUtils.clone(fn); - try { - Coder accumulatorCoder = clonedFn.getAccumulatorCoder( - registry, kvCoder.getKeyCoder(), kvCoder.getValueCoder()); - return create(clonedFn, accumulatorCoder, sideInputViews, kvCoder, windowingStrategy); - } catch (CannotProvideCoderException e) { - throw new IllegalStateException("Could not determine coder for accumulator", e); - } - } - - private static AppliedCombineFn create( - PerKeyCombineFn fn, - Coder accumulatorCoder, Iterable> sideInputViews, - KvCoder kvCoder, WindowingStrategy windowingStrategy) { - return new AppliedCombineFn<>( - fn, accumulatorCoder, sideInputViews, kvCoder, windowingStrategy); - } - - public PerKeyCombineFn getFn() { - return fn; - } - - public Iterable> getSideInputViews() { - return sideInputViews; - } - - public Coder getAccumulatorCoder() { - return accumulatorCoder; - } - - public KvCoder getKvCoder() { - return kvCoder; - } - - public WindowingStrategy getWindowingStrategy() { - return windowingStrategy; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AssignWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AssignWindowsDoFn.java deleted file mode 100644 index ca59c53957..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AssignWindowsDoFn.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; - -import org.joda.time.Instant; - -import java.util.Collection; - -/** - * {@link DoFn} that tags elements of a PCollection with windows, according - * to the provided {@link WindowFn}. - * @param Type of elements being windowed - * @param Window type - */ -@SystemDoFnInternal -public class AssignWindowsDoFn extends DoFn { - private WindowFn fn; - - public AssignWindowsDoFn(WindowFn fn) { - this.fn = fn; - } - - @Override - @SuppressWarnings("unchecked") - public void processElement(final ProcessContext c) throws Exception { - Collection windows = - ((WindowFn) fn).assignWindows( - ((WindowFn) fn).new AssignContext() { - @Override - public T element() { - return c.element(); - } - - @Override - public Instant timestamp() { - return c.timestamp(); - } - - @Override - public Collection windows() { - return c.windowingInternals().windows(); - } - }); - - c.windowingInternals() - .outputWindowedValue(c.element(), c.timestamp(), windows, PaneInfo.NO_FIRING); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java deleted file mode 100644 index 823c0616ac..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOff.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.NanoClock; - -import java.util.concurrent.TimeUnit; - -/** - * Extension of {@link AttemptBoundedExponentialBackOff} that bounds the total time that the backoff - * is happening as well as the amount of retries. Acts exactly as a AttemptBoundedExponentialBackOff - * unless the time interval has expired since the object was created. At this point, it will always - * return BackOff.STOP. Calling reset() resets both the timer and the number of retry attempts, - * unless a custom ResetPolicy (ResetPolicy.ATTEMPTS or ResetPolicy.TIMER) is passed to the - * constructor. - * - *

              Implementation is not thread-safe. - * - * @deprecated prefer {@link FluentBackoff} - */ -@Deprecated -public class AttemptAndTimeBoundedExponentialBackOff extends AttemptBoundedExponentialBackOff { - private long endTimeMillis; - private long maximumTotalWaitTimeMillis; - private ResetPolicy resetPolicy; - private final NanoClock nanoClock; - // NanoClock.SYSTEM has a max elapsed time of 292 years or 2^63 ns. Here, we choose 2^53 ns as - // a smaller but still huge limit. - private static final long MAX_ELAPSED_TIME_MILLIS = 1L << 53; - - /** - * A ResetPolicy controls the behavior of this BackOff when reset() is called. By default, both - * the number of attempts and the time bound for the BackOff are reset, but an alternative - * ResetPolicy may be set to only reset one of these two. - */ - public enum ResetPolicy { - ALL, - ATTEMPTS, - TIMER - } - - /** - * Constructs an instance of AttemptAndTimeBoundedExponentialBackoff. - * - * @param maximumNumberOfAttempts The maximum number of attempts it will make. - * @param initialIntervalMillis The original interval to wait between attempts in milliseconds. - * @param maximumTotalWaitTimeMillis The maximum total time that this object will - * allow more attempts in milliseconds. - */ - public AttemptAndTimeBoundedExponentialBackOff( - int maximumNumberOfAttempts, long initialIntervalMillis, long maximumTotalWaitTimeMillis) { - this( - maximumNumberOfAttempts, - initialIntervalMillis, - maximumTotalWaitTimeMillis, - ResetPolicy.ALL, - NanoClock.SYSTEM); - } - - /** - * Constructs an instance of AttemptAndTimeBoundedExponentialBackoff. - * - * @param maximumNumberOfAttempts The maximum number of attempts it will make. - * @param initialIntervalMillis The original interval to wait between attempts in milliseconds. - * @param maximumTotalWaitTimeMillis The maximum total time that this object will - * allow more attempts in milliseconds. - * @param resetPolicy The ResetPolicy specifying the properties of this BackOff that are subject - * to being reset. - */ - public AttemptAndTimeBoundedExponentialBackOff( - int maximumNumberOfAttempts, - long initialIntervalMillis, - long maximumTotalWaitTimeMillis, - ResetPolicy resetPolicy) { - this( - maximumNumberOfAttempts, - initialIntervalMillis, - maximumTotalWaitTimeMillis, - resetPolicy, - NanoClock.SYSTEM); - } - - /** - * Constructs an instance of AttemptAndTimeBoundedExponentialBackoff. - * - * @param maximumNumberOfAttempts The maximum number of attempts it will make. - * @param initialIntervalMillis The original interval to wait between attempts in milliseconds. - * @param maximumTotalWaitTimeMillis The maximum total time that this object will - * allow more attempts in milliseconds. - * @param resetPolicy The ResetPolicy specifying the properties of this BackOff that are subject - * to being reset. - * @param nanoClock clock used to measure the time that has passed. - */ - public AttemptAndTimeBoundedExponentialBackOff( - int maximumNumberOfAttempts, - long initialIntervalMillis, - long maximumTotalWaitTimeMillis, - ResetPolicy resetPolicy, - NanoClock nanoClock) { - super(maximumNumberOfAttempts, initialIntervalMillis); - checkArgument( - maximumTotalWaitTimeMillis > 0, "Maximum total wait time must be greater than zero."); - checkArgument( - maximumTotalWaitTimeMillis < MAX_ELAPSED_TIME_MILLIS, - "Maximum total wait time must be less than " + MAX_ELAPSED_TIME_MILLIS + " milliseconds"); - checkArgument(resetPolicy != null, "resetPolicy may not be null"); - checkArgument(nanoClock != null, "nanoClock may not be null"); - this.maximumTotalWaitTimeMillis = maximumTotalWaitTimeMillis; - this.resetPolicy = resetPolicy; - this.nanoClock = nanoClock; - // Set the end time for this BackOff. Note that we cannot simply call reset() here since the - // resetPolicy may not be set to reset the time bound. - endTimeMillis = getTimeMillis() + maximumTotalWaitTimeMillis; - } - - @Override - public void reset() { - // reset() is called in the constructor of the parent class before resetPolicy and nanoClock are - // set. In this case, we call the parent class's reset() method and return. - if (resetPolicy == null) { - super.reset(); - return; - } - // Reset the number of attempts. - if (resetPolicy == ResetPolicy.ALL || resetPolicy == ResetPolicy.ATTEMPTS) { - super.reset(); - } - // Reset the time bound. - if (resetPolicy == ResetPolicy.ALL || resetPolicy == ResetPolicy.TIMER) { - endTimeMillis = getTimeMillis() + maximumTotalWaitTimeMillis; - } - } - - public void setEndtimeMillis(long endTimeMillis) { - this.endTimeMillis = endTimeMillis; - } - - @Override - public long nextBackOffMillis() { - if (atMaxAttempts()) { - return BackOff.STOP; - } - long backoff = Math.min(super.nextBackOffMillis(), endTimeMillis - getTimeMillis()); - return (backoff > 0 ? backoff : BackOff.STOP); - } - - private long getTimeMillis() { - return TimeUnit.NANOSECONDS.toMillis(nanoClock.nanoTime()); - } - - @Override - public boolean atMaxAttempts() { - return super.atMaxAttempts() || getTimeMillis() >= endTimeMillis; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java deleted file mode 100644 index 85cf3c3887..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOff.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.util.BackOff; - -/** - * Implementation of {@link BackOff} that increases the back off period for each retry attempt - * using a randomization function that grows exponentially. - * - *

              Example: The initial interval is .5 seconds and the maximum number of retries is 10. - * For 10 tries the sequence will be (values in seconds): - * - *

              - * retry#      retry_interval     randomized_interval
              - * 1             0.5                [0.25,   0.75]
              - * 2             0.75               [0.375,  1.125]
              - * 3             1.125              [0.562,  1.687]
              - * 4             1.687              [0.8435, 2.53]
              - * 5             2.53               [1.265,  3.795]
              - * 6             3.795              [1.897,  5.692]
              - * 7             5.692              [2.846,  8.538]
              - * 8             8.538              [4.269, 12.807]
              - * 9            12.807              [6.403, 19.210]
              - * 10           {@link BackOff#STOP}
              - * 
              - * - *

              Implementation is not thread-safe. - * - * @deprecated prefer {@link FluentBackoff} - */ -@Deprecated -public class AttemptBoundedExponentialBackOff implements BackOff { - public static final double DEFAULT_MULTIPLIER = 1.5; - public static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5; - private final int maximumNumberOfAttempts; - private final long initialIntervalMillis; - private int currentAttempt; - - public AttemptBoundedExponentialBackOff(int maximumNumberOfAttempts, long initialIntervalMillis) { - checkArgument(maximumNumberOfAttempts > 0, - "Maximum number of attempts must be greater than zero."); - checkArgument(initialIntervalMillis > 0, "Initial interval must be greater than zero."); - this.maximumNumberOfAttempts = maximumNumberOfAttempts; - this.initialIntervalMillis = initialIntervalMillis; - reset(); - } - - @Override - public void reset() { - currentAttempt = 1; - } - - @Override - public long nextBackOffMillis() { - if (currentAttempt >= maximumNumberOfAttempts) { - return BackOff.STOP; - } - double currentIntervalMillis = initialIntervalMillis - * Math.pow(DEFAULT_MULTIPLIER, currentAttempt - 1); - double randomOffset = (Math.random() * 2 - 1) - * DEFAULT_RANDOMIZATION_FACTOR * currentIntervalMillis; - currentAttempt += 1; - return Math.round(currentIntervalMillis + randomOffset); - } - - public boolean atMaxAttempts() { - return currentAttempt >= maximumNumberOfAttempts; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java deleted file mode 100644 index 35c11f6c88..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/AvroUtils.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.MoreObjects.firstNonNull; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Verify.verify; -import static com.google.common.base.Verify.verifyNotNull; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.io.BaseEncoding; - -import org.apache.avro.Schema; -import org.apache.avro.Schema.Field; -import org.apache.avro.Schema.Type; -import org.apache.avro.file.DataFileConstants; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.BinaryDecoder; -import org.apache.avro.io.DecoderFactory; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A set of utilities for working with Avro files. - * - *

              These utilities are based on the Avro 1.7.7 specification. - */ -public class AvroUtils { - - /** - * Avro file metadata. - */ - public static class AvroMetadata { - private byte[] syncMarker; - private String codec; - private String schemaString; - - AvroMetadata(byte[] syncMarker, String codec, String schemaString) { - this.syncMarker = syncMarker; - this.codec = codec; - this.schemaString = schemaString; - } - - /** - * The JSON-encoded schema - * string for the file. - */ - public String getSchemaString() { - return schemaString; - } - - /** - * The codec of the - * file. - */ - public String getCodec() { - return codec; - } - - /** - * The 16-byte sync marker for the file. See the documentation for - * Object - * Container File for more information. - */ - public byte[] getSyncMarker() { - return syncMarker; - } - } - - /** - * Reads the {@link AvroMetadata} from the header of an Avro file. - * - *

              This method parses the header of an Avro - * - * Object Container File. - * - * @throws IOException if the file is an invalid format. - */ - public static AvroMetadata readMetadataFromFile(String fileName) throws IOException { - String codec = null; - String schemaString = null; - byte[] syncMarker; - try (InputStream stream = - Channels.newInputStream(IOChannelUtils.getFactory(fileName).open(fileName))) { - BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(stream, null); - - // The header of an object container file begins with a four-byte magic number, followed - // by the file metadata (including the schema and codec), encoded as a map. Finally, the - // header ends with the file's 16-byte sync marker. - // See https://avro.apache.org/docs/1.7.7/spec.html#Object+Container+Files for details on - // the encoding of container files. - - // Read the magic number. - byte[] magic = new byte[DataFileConstants.MAGIC.length]; - decoder.readFixed(magic); - if (!Arrays.equals(magic, DataFileConstants.MAGIC)) { - throw new IOException("Missing Avro file signature: " + fileName); - } - - // Read the metadata to find the codec and schema. - ByteBuffer valueBuffer = ByteBuffer.allocate(512); - long numRecords = decoder.readMapStart(); - while (numRecords > 0) { - for (long recordIndex = 0; recordIndex < numRecords; recordIndex++) { - String key = decoder.readString(); - // readBytes() clears the buffer and returns a buffer where: - // - position is the start of the bytes read - // - limit is the end of the bytes read - valueBuffer = decoder.readBytes(valueBuffer); - byte[] bytes = new byte[valueBuffer.remaining()]; - valueBuffer.get(bytes); - if (key.equals(DataFileConstants.CODEC)) { - codec = new String(bytes, "UTF-8"); - } else if (key.equals(DataFileConstants.SCHEMA)) { - schemaString = new String(bytes, "UTF-8"); - } - } - numRecords = decoder.mapNext(); - } - if (codec == null) { - codec = DataFileConstants.NULL_CODEC; - } - - // Finally, read the sync marker. - syncMarker = new byte[DataFileConstants.SYNC_SIZE]; - decoder.readFixed(syncMarker); - } - return new AvroMetadata(syncMarker, codec, schemaString); - } - - /** - * Formats BigQuery seconds-since-epoch into String matching JSON export. Thread-safe and - * immutable. - */ - private static final DateTimeFormatter DATE_AND_SECONDS_FORMATTER = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC(); - // Package private for BigQueryTableRowIterator to use. - static String formatTimestamp(String timestamp) { - // timestamp is in "seconds since epoch" format, with scientific notation. - // e.g., "1.45206229112345E9" to mean "2016-01-06 06:38:11.123456 UTC". - // Separate into seconds and microseconds. - double timestampDoubleMicros = Double.parseDouble(timestamp) * 1000000; - long timestampMicros = (long) timestampDoubleMicros; - long seconds = timestampMicros / 1000000; - int micros = (int) (timestampMicros % 1000000); - String dayAndTime = DATE_AND_SECONDS_FORMATTER.print(seconds * 1000); - - // No sub-second component. - if (micros == 0) { - return String.format("%s UTC", dayAndTime); - } - - // Sub-second component. - int digits = 6; - int subsecond = micros; - while (subsecond % 10 == 0) { - digits--; - subsecond /= 10; - } - String formatString = String.format("%%0%dd", digits); - String fractionalSeconds = String.format(formatString, subsecond); - return String.format("%s.%s UTC", dayAndTime, fractionalSeconds); - } - - /** - * Utility function to convert from an Avro {@link GenericRecord} to a BigQuery {@link TableRow}. - * - *

              See - * "Avro format" for more information. - */ - public static TableRow convertGenericRecordToTableRow(GenericRecord record, TableSchema schema) { - return convertGenericRecordToTableRow(record, schema.getFields()); - } - - private static TableRow convertGenericRecordToTableRow( - GenericRecord record, List fields) { - TableRow row = new TableRow(); - for (TableFieldSchema subSchema : fields) { - // Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the name field - // is required, so it may not be null. - Field field = record.getSchema().getField(subSchema.getName()); - Object convertedValue = - getTypedCellValue(field.schema(), subSchema, record.get(field.name())); - if (convertedValue != null) { - // To match the JSON files exported by BigQuery, do not include null values in the output. - row.set(field.name(), convertedValue); - } - } - return row; - } - - @Nullable - private static Object getTypedCellValue(Schema schema, TableFieldSchema fieldSchema, Object v) { - // Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the mode field - // is optional (and so it may be null), but defaults to "NULLABLE". - String mode = firstNonNull(fieldSchema.getMode(), "NULLABLE"); - switch (mode) { - case "REQUIRED": - return convertRequiredField(schema.getType(), fieldSchema, v); - case "REPEATED": - return convertRepeatedField(schema, fieldSchema, v); - case "NULLABLE": - return convertNullableField(schema, fieldSchema, v); - default: - throw new UnsupportedOperationException( - "Parsing a field with BigQuery field schema mode " + fieldSchema.getMode()); - } - } - - private static List convertRepeatedField( - Schema schema, TableFieldSchema fieldSchema, Object v) { - Type arrayType = schema.getType(); - verify( - arrayType == Type.ARRAY, - "BigQuery REPEATED field %s should be Avro ARRAY, not %s", - fieldSchema.getName(), - arrayType); - // REPEATED fields are represented as Avro arrays. - if (v == null) { - // Handle the case of an empty repeated field. - return ImmutableList.of(); - } - @SuppressWarnings("unchecked") - List elements = (List) v; - ImmutableList.Builder values = ImmutableList.builder(); - Type elementType = schema.getElementType().getType(); - for (Object element : elements) { - values.add(convertRequiredField(elementType, fieldSchema, element)); - } - return values.build(); - } - - private static Object convertRequiredField( - Type avroType, TableFieldSchema fieldSchema, Object v) { - // REQUIRED fields are represented as the corresponding Avro types. For example, a BigQuery - // INTEGER type maps to an Avro LONG type. - checkNotNull(v, "REQUIRED field %s should not be null", fieldSchema.getName()); - ImmutableMap fieldMap = - ImmutableMap.builder() - .put("STRING", Type.STRING) - .put("BYTES", Type.BYTES) - .put("INTEGER", Type.LONG) - .put("FLOAT", Type.DOUBLE) - .put("BOOLEAN", Type.BOOLEAN) - .put("TIMESTAMP", Type.LONG) - .put("RECORD", Type.RECORD) - .put("DATE", Type.STRING) - .put("DATETIME", Type.STRING) - .put("TIME", Type.STRING) - .build(); - // Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the type field - // is required, so it may not be null. - String bqType = fieldSchema.getType(); - Type expectedAvroType = fieldMap.get(bqType); - verifyNotNull(expectedAvroType, "Unsupported BigQuery type: %s", bqType); - verify( - avroType == expectedAvroType, - "Expected Avro schema type %s, not %s, for BigQuery %s field %s", - expectedAvroType, - avroType, - bqType, - fieldSchema.getName()); - switch (fieldSchema.getType()) { - case "STRING": - case "DATE": - case "DATETIME": - case "TIME": - // Avro will use a CharSequence to represent String objects, but it may not always use - // java.lang.String; for example, it may prefer org.apache.avro.util.Utf8. - verify(v instanceof CharSequence, "Expected CharSequence (String), got %s", v.getClass()); - return v.toString(); - case "INTEGER": - verify(v instanceof Long, "Expected Long, got %s", v.getClass()); - return ((Long) v).toString(); - case "FLOAT": - verify(v instanceof Double, "Expected Double, got %s", v.getClass()); - return v; - case "BOOLEAN": - verify(v instanceof Boolean, "Expected Boolean, got %s", v.getClass()); - return v; - case "TIMESTAMP": - // TIMESTAMP data types are represented as Avro LONG types. They are converted back to - // Strings with variable-precision (up to six digits) to match the JSON files export - // by BigQuery. - verify(v instanceof Long, "Expected Long, got %s", v.getClass()); - Double doubleValue = ((Long) v) / 1000000.0; - return formatTimestamp(doubleValue.toString()); - case "RECORD": - verify(v instanceof GenericRecord, "Expected GenericRecord, got %s", v.getClass()); - return convertGenericRecordToTableRow((GenericRecord) v, fieldSchema.getFields()); - case "BYTES": - verify(v instanceof ByteBuffer, "Expected ByteBuffer, got %s", v.getClass()); - ByteBuffer byteBuffer = (ByteBuffer) v; - byte[] bytes = new byte[byteBuffer.limit()]; - byteBuffer.get(bytes); - return BaseEncoding.base64().encode(bytes); - default: - throw new UnsupportedOperationException( - String.format( - "Unexpected BigQuery field schema type %s for field named %s", - fieldSchema.getType(), - fieldSchema.getName())); - } - } - - @Nullable - private static Object convertNullableField( - Schema avroSchema, TableFieldSchema fieldSchema, Object v) { - // NULLABLE fields are represented as an Avro Union of the corresponding type and "null". - verify( - avroSchema.getType() == Type.UNION, - "Expected Avro schema type UNION, not %s, for BigQuery NULLABLE field %s", - avroSchema.getType(), - fieldSchema.getName()); - List unionTypes = avroSchema.getTypes(); - verify( - unionTypes.size() == 2, - "BigQuery NULLABLE field %s should be an Avro UNION of NULL and another type, not %s", - fieldSchema.getName(), - unionTypes); - - if (v == null) { - return null; - } - - Type firstType = unionTypes.get(0).getType(); - if (!firstType.equals(Type.NULL)) { - return convertRequiredField(firstType, fieldSchema, v); - } - return convertRequiredField(unionTypes.get(1).getType(), fieldSchema, v); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java deleted file mode 100644 index 19ba8d6256..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BaseExecutionContext.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * Base class for implementations of {@link ExecutionContext}. - * - *

              A concrete subclass should implement {@link #createStepContext} to create the appropriate - * {@link StepContext} implementation. Any {@code StepContext} created will - * be cached for the lifetime of this {@link ExecutionContext}. - * - *

              BaseExecutionContext is generic to allow implementing subclasses to return a concrete subclass - * of {@link StepContext} from {@link #getOrCreateStepContext(String, String, StateSampler)} and - * {@link #getAllStepContexts()} without forcing each subclass to override the method, e.g. - * - *

              {@code
              - * {@literal @}Override
              - * StreamingModeExecutionContext.StepContext getOrCreateStepContext(...) {
              - *   return (StreamingModeExecutionContext.StepContext) super.getOrCreateStepContext(...);
              - * }
              - * }
              - * - *

              When a subclass of {@code BaseExecutionContext} has been downcast, the return types of - * {@link #createStepContext(String, String, StateSampler)}, - * {@link #getOrCreateStepContext(String, String, StateSampler)}, and {@link #getAllStepContexts()} - * will be appropriately specialized. - */ -public abstract class BaseExecutionContext - implements ExecutionContext { - - private Map cachedStepContexts = new HashMap<>(); - - /** - * Implementations should override this to create the specific type - * of {@link StepContext} they need. - */ - protected abstract T createStepContext( - String stepName, String transformName, StateSampler stateSampler); - - - /** - * Returns the {@link StepContext} associated with the given step. - */ - @Override - public T getOrCreateStepContext( - String stepName, String transformName, StateSampler stateSampler) { - T context = cachedStepContexts.get(stepName); - if (context == null) { - context = createStepContext(stepName, transformName, stateSampler); - cachedStepContexts.put(stepName, context); - } - return context; - } - - /** - * Returns a collection view of all of the {@link StepContext}s. - */ - @Override - public Collection getAllStepContexts() { - return Collections.unmodifiableCollection(cachedStepContexts.values()); - } - - /** - * Hook for subclasses to implement that will be called whenever - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#output} - * is called. - */ - @Override - public void noteOutput(WindowedValue output) {} - - /** - * Hook for subclasses to implement that will be called whenever - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#sideOutput} - * is called. - */ - @Override - public void noteSideOutput(TupleTag tag, WindowedValue output) {} - - /** - * Base class for implementations of {@link ExecutionContext.StepContext}. - * - *

              To complete a concrete subclass, implement {@link #timerInternals} and - * {@link #stateInternals}. - */ - public abstract static class StepContext implements ExecutionContext.StepContext { - private final ExecutionContext executionContext; - private final String stepName; - private final String transformName; - - public StepContext(ExecutionContext executionContext, String stepName, String transformName) { - this.executionContext = executionContext; - this.stepName = stepName; - this.transformName = transformName; - } - - @Override - public String getStepName() { - return stepName; - } - - @Override - public String getTransformName() { - return transformName; - } - - @Override - public void noteOutput(WindowedValue output) { - executionContext.noteOutput(output); - } - - @Override - public void noteSideOutput(TupleTag tag, WindowedValue output) { - executionContext.noteSideOutput(tag, output); - } - - @Override - public void writePCollectionViewData( - TupleTag tag, - Iterable> data, Coder>> dataCoder, - W window, Coder windowCoder) throws IOException { - throw new UnsupportedOperationException("Not implemented."); - } - - @Override - public abstract StateInternals stateInternals(); - - @Override - public abstract TimerInternals timerInternals(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java deleted file mode 100644 index ca34165927..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternals.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.common.base.MoreObjects; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.PriorityQueue; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * TimerInternals that uses priority queues to manage the timers that are ready to fire. - */ -public class BatchTimerInternals implements TimerInternals { - /** Set of timers that are scheduled used for deduplicating timers. */ - private Set existingTimers = new HashSet<>(); - - // Keep these queues separate so we can advance over them separately. - private PriorityQueue watermarkTimers = new PriorityQueue<>(11); - private PriorityQueue processingTimers = new PriorityQueue<>(11); - - private Instant inputWatermarkTime; - private Instant processingTime; - - private PriorityQueue queue(TimeDomain domain) { - return TimeDomain.EVENT_TIME.equals(domain) ? watermarkTimers : processingTimers; - } - - public BatchTimerInternals(Instant processingTime) { - this.processingTime = processingTime; - this.inputWatermarkTime = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - @Override - public void setTimer(TimerData timer) { - if (existingTimers.add(timer)) { - queue(timer.getDomain()).add(timer); - } - } - - @Override - public void deleteTimer(TimerData timer) { - existingTimers.remove(timer); - queue(timer.getDomain()).remove(timer); - } - - @Override - public Instant currentProcessingTime() { - return processingTime; - } - - /** - * {@inheritDoc} - * - * @return {@link BoundedWindow#TIMESTAMP_MAX_VALUE}: in batch mode, upstream processing - * is already complete. - */ - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - public Instant currentInputWatermarkTime() { - return inputWatermarkTime; - } - - @Override - @Nullable - public Instant currentOutputWatermarkTime() { - // The output watermark is always undefined in batch mode. - return null; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("watermarkTimers", watermarkTimers) - .add("processingTimers", processingTimers) - .toString(); - } - - public void advanceInputWatermark(ReduceFnRunner runner, Instant newInputWatermark) - throws Exception { - checkState(!newInputWatermark.isBefore(inputWatermarkTime), - "Cannot move input watermark time backwards from %s to %s", inputWatermarkTime, - newInputWatermark); - inputWatermarkTime = newInputWatermark; - advance(runner, newInputWatermark, TimeDomain.EVENT_TIME); - } - - public void advanceProcessingTime(ReduceFnRunner runner, Instant newProcessingTime) - throws Exception { - checkState(!newProcessingTime.isBefore(processingTime), - "Cannot move processing time backwards from %s to %s", processingTime, newProcessingTime); - processingTime = newProcessingTime; - advance(runner, newProcessingTime, TimeDomain.PROCESSING_TIME); - } - - private void advance(ReduceFnRunner runner, Instant newTime, TimeDomain domain) - throws Exception { - PriorityQueue timers = queue(domain); - boolean shouldFire = false; - - while (true) { - ArrayList firedTimers = new ArrayList(); - while (!timers.isEmpty() && newTime.isAfter(timers.peek().getTimestamp())) { - // Remove before firing, so that if the callback adds another identical - // timer we don't remove it. - TimerData timer = timers.remove(); - existingTimers.remove(timer); - firedTimers.add(timer); - } - if (firedTimers.isEmpty()) { - break; - } - runner.onTimers(firedTimers); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java deleted file mode 100644 index ec96009494..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.Job; -import com.google.api.services.bigquery.model.JobConfigurationExtract; -import com.google.api.services.bigquery.model.JobConfigurationLoad; -import com.google.api.services.bigquery.model.JobConfigurationQuery; -import com.google.api.services.bigquery.model.JobConfigurationTableCopy; -import com.google.api.services.bigquery.model.JobReference; -import com.google.api.services.bigquery.model.JobStatistics; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; - -import java.io.IOException; -import java.io.Serializable; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * An interface for real, mock, or fake implementations of Cloud BigQuery services. - */ -public interface BigQueryServices extends Serializable { - - /** - * Returns a real, mock, or fake {@link JobService}. - */ - JobService getJobService(BigQueryOptions bqOptions); - - /** - * Returns a real, mock, or fake {@link DatasetService}. - */ - DatasetService getDatasetService(BigQueryOptions bqOptions); - - /** - * Returns a real, mock, or fake {@link BigQueryJsonReader} to read tables. - */ - BigQueryJsonReader getReaderFromTable(BigQueryOptions bqOptions, TableReference tableRef); - - /** - * Returns a real, mock, or fake {@link BigQueryJsonReader} to query tables. - */ - BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten, - @Nullable Boolean useLegacySql); - - /** - * An interface for the Cloud BigQuery load service. - */ - public interface JobService { - /** - * Start a BigQuery load job. - */ - void startLoadJob(JobReference jobRef, JobConfigurationLoad loadConfig) - throws InterruptedException, IOException; - /** - * Start a BigQuery extract job. - */ - void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) - throws InterruptedException, IOException; - - /** - * Start a BigQuery query job. - */ - void startQueryJob(JobReference jobRef, JobConfigurationQuery query) - throws IOException, InterruptedException; - - /** - * Start a BigQuery copy job. - */ - void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) - throws IOException, InterruptedException; - - /** - * Waits for the job is Done, and returns the job. - * - *

              Returns null if the {@code maxAttempts} retries reached. - */ - Job pollJob(JobReference jobRef, int maxAttempts) - throws InterruptedException, IOException; - - /** - * Dry runs the query in the given project. - */ - JobStatistics dryRunQuery(String projectId, JobConfigurationQuery queryConfig) - throws InterruptedException, IOException; - - /** - * Gets the specified {@link Job} by the given {@link JobReference}. - * - *

              Returns null if the job is not found. - */ - Job getJob(JobReference jobRef) throws IOException, InterruptedException; - } - - /** - * An interface to get, create and delete Cloud BigQuery datasets and tables. - */ - interface DatasetService { - /** - * Gets the specified {@link Table} resource by table ID. - */ - Table getTable(String projectId, String datasetId, String tableId) - throws InterruptedException, IOException; - - /** - * Deletes the table specified by tableId from the dataset. - * If the table contains data, all the data will be deleted. - */ - void deleteTable(String projectId, String datasetId, String tableId) - throws IOException, InterruptedException; - - /** - * Create a {@link Dataset} with the given {@code location} and {@code description}. - */ - void createDataset( - String projectId, String datasetId, @Nullable String location, @Nullable String description) - throws IOException, InterruptedException; - - /** - * Deletes the dataset specified by the datasetId value. - * - *

              Before you can delete a dataset, you must delete all its tables. - */ - void deleteDataset(String projectId, String datasetId) - throws IOException, InterruptedException; - } - - /** - * An interface to read the Cloud BigQuery directly. - */ - public interface BigQueryJsonReader { - /** - * Initializes the reader and advances the reader to the first record. - */ - boolean start() throws IOException; - - /** - * Advances the reader to the next valid record. - */ - boolean advance() throws IOException; - - /** - * Returns the value of the data item that was read by the last {@link #start} or - * {@link #advance} call. The returned value must be effectively immutable and remain valid - * indefinitely. - * - *

              Multiple calls to this method without an intervening call to {@link #advance} should - * return the same result. - * - * @throws java.util.NoSuchElementException if {@link #start} was never called, or if - * the last {@link #start} or {@link #advance} returned {@code false}. - */ - TableRow getCurrent() throws NoSuchElementException; - - /** - * Closes the reader. The reader cannot be used after this method is called. - */ - void close() throws IOException; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java deleted file mode 100644 index 1a37e01375..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.Sleeper; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.DatasetReference; -import com.google.api.services.bigquery.model.Job; -import com.google.api.services.bigquery.model.JobConfiguration; -import com.google.api.services.bigquery.model.JobConfigurationExtract; -import com.google.api.services.bigquery.model.JobConfigurationLoad; -import com.google.api.services.bigquery.model.JobConfigurationQuery; -import com.google.api.services.bigquery.model.JobConfigurationTableCopy; -import com.google.api.services.bigquery.model.JobReference; -import com.google.api.services.bigquery.model.JobStatistics; -import com.google.api.services.bigquery.model.JobStatus; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableDataList; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; -import com.google.cloud.hadoop.util.ApiErrorExtractor; -import com.google.common.annotations.VisibleForTesting; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * An implementation of {@link BigQueryServices} that actually communicates with the cloud BigQuery - * service. - */ -public class BigQueryServicesImpl implements BigQueryServices { - - private static final Logger LOG = LoggerFactory.getLogger(BigQueryServicesImpl.class); - - // The maximum number of retries to execute a BigQuery RPC. - private static final int MAX_RPC_RETRIES = 9; - - // The initial backoff for executing a BigQuery RPC. - private static final Duration INITIAL_RPC_BACKOFF = Duration.standardSeconds(1); - - // The initial backoff for polling the status of a BigQuery job. - private static final Duration INITIAL_JOB_STATUS_POLL_BACKOFF = Duration.standardSeconds(1); - - @Override - public JobService getJobService(BigQueryOptions options) { - return new JobServiceImpl(options); - } - - @Override - public DatasetService getDatasetService(BigQueryOptions options) { - return new DatasetServiceImpl(options); - } - - @Override - public BigQueryJsonReader getReaderFromTable(BigQueryOptions bqOptions, TableReference tableRef) { - return BigQueryJsonReaderImpl.fromTable(bqOptions, tableRef); - } - - @Override - public BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten, - @Nullable Boolean useLegacySql) { - return BigQueryJsonReaderImpl.fromQuery(bqOptions, query, projectId, flatten, useLegacySql); - } - - @VisibleForTesting - static class JobServiceImpl implements BigQueryServices.JobService { - private final ApiErrorExtractor errorExtractor; - private final Bigquery client; - - @VisibleForTesting - JobServiceImpl(Bigquery client) { - this.errorExtractor = new ApiErrorExtractor(); - this.client = client; - } - - private JobServiceImpl(BigQueryOptions options) { - this.errorExtractor = new ApiErrorExtractor(); - this.client = Transport.newBigQueryClient(options).build(); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public void startLoadJob( - JobReference jobRef, - JobConfigurationLoad loadConfig) throws InterruptedException, IOException { - Job job = new Job() - .setJobReference(jobRef) - .setConfiguration(new JobConfiguration().setLoad(loadConfig)); - - startJob(job, errorExtractor, client); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) - throws InterruptedException, IOException { - Job job = new Job() - .setJobReference(jobRef) - .setConfiguration( - new JobConfiguration().setExtract(extractConfig)); - - startJob(job, errorExtractor, client); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public void startQueryJob(JobReference jobRef, JobConfigurationQuery queryConfig) - throws IOException, InterruptedException { - Job job = new Job() - .setJobReference(jobRef) - .setConfiguration( - new JobConfiguration().setQuery(queryConfig)); - - startJob(job, errorExtractor, client); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) - throws IOException, InterruptedException { - Job job = new Job() - .setJobReference(jobRef) - .setConfiguration( - new JobConfiguration().setCopy(copyConfig)); - - startJob(job, errorExtractor, client); - } - - private static void startJob(Job job, - ApiErrorExtractor errorExtractor, - Bigquery client) throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - startJob(job, errorExtractor, client, Sleeper.DEFAULT, backoff); - } - - @VisibleForTesting - static void startJob( - Job job, - ApiErrorExtractor errorExtractor, - Bigquery client, - Sleeper sleeper, - BackOff backoff) throws IOException, InterruptedException { - JobReference jobRef = job.getJobReference(); - Exception lastException = null; - do { - try { - client.jobs().insert(jobRef.getProjectId(), job).execute(); - return; // SUCCEEDED - } catch (GoogleJsonResponseException e) { - if (errorExtractor.itemAlreadyExists(e)) { - return; // SUCCEEDED - } - // ignore and retry - LOG.warn("Ignore the error and retry inserting the job.", e); - lastException = e; - } catch (IOException e) { - // ignore and retry - LOG.warn("Ignore the error and retry inserting the job.", e); - lastException = e; - } - } while (nextBackOff(sleeper, backoff)); - throw new IOException( - String.format( - "Unable to insert job: %s, aborting after %d .", - jobRef.getJobId(), MAX_RPC_RETRIES), - lastException); - } - - @Override - public Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(maxAttempts) - .withInitialBackoff(INITIAL_JOB_STATUS_POLL_BACKOFF) - .withMaxBackoff(Duration.standardMinutes(1)) - .backoff(); - return pollJob(jobRef, Sleeper.DEFAULT, backoff); - } - - @VisibleForTesting - Job pollJob( - JobReference jobRef, - Sleeper sleeper, - BackOff backoff) throws InterruptedException { - do { - try { - Job job = client.jobs().get(jobRef.getProjectId(), jobRef.getJobId()).execute(); - JobStatus status = job.getStatus(); - if (status != null && status.getState() != null && status.getState().equals("DONE")) { - return job; - } - // The job is not DONE, wait longer and retry. - } catch (IOException e) { - // ignore and retry - LOG.warn("Ignore the error and retry polling job status.", e); - } - } while (nextBackOff(sleeper, backoff)); - LOG.warn("Unable to poll job status: {}, aborting after reached max .", jobRef.getJobId()); - return null; - } - - @Override - public JobStatistics dryRunQuery(String projectId, JobConfigurationQuery queryConfig) - throws InterruptedException, IOException { - Job job = new Job() - .setConfiguration(new JobConfiguration() - .setQuery(queryConfig) - .setDryRun(true)); - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - return executeWithRetries( - client.jobs().insert(projectId, job), - String.format( - "Unable to dry run query: %s, aborting after %d retries.", - queryConfig, MAX_RPC_RETRIES), - Sleeper.DEFAULT, - backoff).getStatistics(); - } - - /** - * {@inheritDoc} - * - *

              Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. - * - * @throws IOException if it exceeds max RPC retries. - */ - @Override - public Job getJob(JobReference jobRef) throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - return getJob(jobRef, Sleeper.DEFAULT, backoff); - } - - @VisibleForTesting - public Job getJob(JobReference jobRef, Sleeper sleeper, BackOff backoff) - throws IOException, InterruptedException { - String jobId = jobRef.getJobId(); - Exception lastException; - do { - try { - return client.jobs().get(jobRef.getProjectId(), jobId).execute(); - } catch (GoogleJsonResponseException e) { - if (errorExtractor.itemNotFound(e)) { - LOG.info("No BigQuery job with job id {} found.", jobId); - return null; - } - LOG.warn( - "Ignoring the error encountered while trying to query the BigQuery job {}", - jobId, e); - lastException = e; - } catch (IOException e) { - LOG.warn( - "Ignoring the error encountered while trying to query the BigQuery job {}", - jobId, e); - lastException = e; - } - } while (nextBackOff(sleeper, backoff)); - throw new IOException( - String.format( - "Unable to find BigQuery job: %s, aborting after %d retries.", - jobRef, MAX_RPC_RETRIES), - lastException); - } - } - - @VisibleForTesting - static class DatasetServiceImpl implements DatasetService { - // Approximate amount of table data to upload per InsertAll request. - private static final long UPLOAD_BATCH_SIZE_BYTES = 64 * 1024; - - // The maximum number of rows to upload per InsertAll request. - private static final long MAX_ROWS_PER_BATCH = 500; - - private static final FluentBackoff INSERT_BACKOFF_FACTORY = - FluentBackoff.DEFAULT.withInitialBackoff(Duration.millis(200)).withMaxRetries(5); - - // A backoff for rate limit exceeded errors. Retries forever. - private static final FluentBackoff DEFAULT_BACKOFF_FACTORY = - FluentBackoff.DEFAULT - .withInitialBackoff(Duration.standardSeconds(1)) - .withMaxBackoff(Duration.standardMinutes(2)); - - private final ApiErrorExtractor errorExtractor; - private final Bigquery client; - - @VisibleForTesting - DatasetServiceImpl(Bigquery client) { - this.errorExtractor = new ApiErrorExtractor(); - this.client = client; - } - - private DatasetServiceImpl(BigQueryOptions bqOptions) { - this.errorExtractor = new ApiErrorExtractor(); - this.client = Transport.newBigQueryClient(bqOptions).build(); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public Table getTable(String projectId, String datasetId, String tableId) - throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - return executeWithRetries( - client.tables().get(projectId, datasetId, tableId), - String.format( - "Unable to get table: %s, aborting after %d retries.", - tableId, MAX_RPC_RETRIES), - Sleeper.DEFAULT, - backoff); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public void deleteTable(String projectId, String datasetId, String tableId) - throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - executeWithRetries( - client.tables().delete(projectId, datasetId, tableId), - String.format( - "Unable to delete table: %s, aborting after %d retries.", - tableId, MAX_RPC_RETRIES), - Sleeper.DEFAULT, - backoff); - } - - public boolean isTableEmpty(String projectId, String datasetId, String tableId) - throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - TableDataList dataList = executeWithRetries( - client.tabledata().list(projectId, datasetId, tableId), - String.format( - "Unable to list table data: %s, aborting after %d retries.", - tableId, MAX_RPC_RETRIES), - Sleeper.DEFAULT, - backoff); - return dataList.getRows() == null || dataList.getRows().isEmpty(); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - public Dataset getDataset(String projectId, String datasetId) - throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - return executeWithRetries( - client.datasets().get(projectId, datasetId), - String.format( - "Unable to get dataset: %s, aborting after %d retries.", - datasetId, MAX_RPC_RETRIES), - Sleeper.DEFAULT, - backoff); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public void createDataset( - String projectId, String datasetId, @Nullable String location, @Nullable String description) - throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - createDataset(projectId, datasetId, location, description, Sleeper.DEFAULT, backoff); - } - - private void createDataset( - String projectId, - String datasetId, - @Nullable String location, - @Nullable String description, - Sleeper sleeper, - BackOff backoff) throws IOException, InterruptedException { - DatasetReference datasetRef = new DatasetReference() - .setProjectId(projectId) - .setDatasetId(datasetId); - - Dataset dataset = new Dataset().setDatasetReference(datasetRef); - if (location != null) { - dataset.setLocation(location); - } - if (description != null) { - dataset.setFriendlyName(description); - dataset.setDescription(description); - } - - Exception lastException; - do { - try { - client.datasets().insert(projectId, dataset).execute(); - return; // SUCCEEDED - } catch (GoogleJsonResponseException e) { - if (errorExtractor.itemAlreadyExists(e)) { - return; // SUCCEEDED - } - // ignore and retry - LOG.warn("Ignore the error and retry creating the dataset.", e); - lastException = e; - } catch (IOException e) { - LOG.warn("Ignore the error and retry creating the dataset.", e); - lastException = e; - } - } while (nextBackOff(sleeper, backoff)); - throw new IOException( - String.format( - "Unable to create dataset: %s, aborting after %d .", - datasetId, MAX_RPC_RETRIES), - lastException); - } - - /** - * {@inheritDoc} - * - *

              Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. - * - * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. - */ - @Override - public void deleteDataset(String projectId, String datasetId) - throws IOException, InterruptedException { - BackOff backoff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); - executeWithRetries( - client.datasets().delete(projectId, datasetId), - String.format( - "Unable to delete table: %s, aborting after %d retries.", - datasetId, MAX_RPC_RETRIES), - Sleeper.DEFAULT, - backoff); - } - } - - private static class BigQueryJsonReaderImpl implements BigQueryJsonReader { - private BigQueryTableRowIterator iterator; - - private BigQueryJsonReaderImpl(BigQueryTableRowIterator iterator) { - this.iterator = iterator; - } - - private static BigQueryJsonReader fromQuery( - BigQueryOptions bqOptions, - String query, - String projectId, - @Nullable Boolean flattenResults, - @Nullable Boolean useLegacySql) { - return new BigQueryJsonReaderImpl( - BigQueryTableRowIterator.fromQuery( - query, projectId, Transport.newBigQueryClient(bqOptions).build(), flattenResults, - useLegacySql)); - } - - private static BigQueryJsonReader fromTable( - BigQueryOptions bqOptions, - TableReference tableRef) { - return new BigQueryJsonReaderImpl(BigQueryTableRowIterator.fromTable( - tableRef, Transport.newBigQueryClient(bqOptions).build())); - } - - @Override - public boolean start() throws IOException { - try { - iterator.open(); - return iterator.advance(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException("Interrupted during start() operation", e); - } - } - - @Override - public boolean advance() throws IOException { - try { - return iterator.advance(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException("Interrupted during advance() operation", e); - } - } - - @Override - public TableRow getCurrent() throws NoSuchElementException { - return iterator.getCurrent(); - } - - @Override - public void close() throws IOException { - iterator.close(); - } - } - - @VisibleForTesting - static T executeWithRetries( - AbstractGoogleClientRequest request, - String errorMessage, - Sleeper sleeper, - BackOff backoff) - throws IOException, InterruptedException { - Exception lastException = null; - do { - try { - return request.execute(); - } catch (IOException e) { - LOG.warn("Ignore the error and retry the request.", e); - lastException = e; - } - } while (nextBackOff(sleeper, backoff)); - throw new IOException( - errorMessage, - lastException); - } - - /** - * Identical to {@link BackOffUtils#next} but without checked IOException. - */ - private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { - try { - return BackOffUtils.next(sleeper, backoff); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java deleted file mode 100644 index a55823ec55..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserter.java +++ /dev/null @@ -1,472 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.client.util.Sleeper; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableDataInsertAllRequest; -import com.google.api.services.bigquery.model.TableDataInsertAllResponse; -import com.google.api.services.bigquery.model.TableDataList; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.hadoop.util.ApiErrorExtractor; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.util.concurrent.MoreExecutors; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * Inserts rows into BigQuery. - */ -public class BigQueryTableInserter { - private static final Logger LOG = LoggerFactory.getLogger(BigQueryTableInserter.class); - - // Approximate amount of table data to upload per InsertAll request. - private static final long UPLOAD_BATCH_SIZE_BYTES = 64 * 1024; - - // The maximum number of rows to upload per InsertAll request. - private static final long MAX_ROWS_PER_BATCH = 500; - - // Backoff for inserting rows to BigQuery. - private static final FluentBackoff INSERT_BACKOFF_FACTORY = - FluentBackoff.DEFAULT.withInitialBackoff(Duration.millis(200)).withMaxRetries(5); - - // Backoff time bounds for rate limit exceeded errors. - private static final long INITIAL_RATE_LIMIT_EXCEEDED_BACKOFF_MS = TimeUnit.SECONDS.toMillis(1); - private static final long MAX_RATE_LIMIT_EXCEEDED_BACKOFF_MS = TimeUnit.MINUTES.toMillis(2); - - private final Bigquery client; - private final TableReference defaultRef; - private final long maxRowsPerBatch; - - private static final ExecutorService executor; - static { - ThreadPoolExecutor tempExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(100); - tempExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); - executor = MoreExecutors.getExitingExecutorService(tempExecutor, 10, TimeUnit.SECONDS); - } - - /** - * Constructs a new row inserter. - * - * @param client a BigQuery client - */ - public BigQueryTableInserter(Bigquery client) { - this.client = client; - this.defaultRef = null; - this.maxRowsPerBatch = MAX_ROWS_PER_BATCH; - } - - /** - * Constructs a new row inserter. - * - * @param client a BigQuery client - * @param defaultRef identifies the table to insert into - * @deprecated replaced by {@link #BigQueryTableInserter(Bigquery)} - */ - @Deprecated - public BigQueryTableInserter(Bigquery client, TableReference defaultRef) { - this.client = client; - this.defaultRef = defaultRef; - this.maxRowsPerBatch = MAX_ROWS_PER_BATCH; - } - - /** - * Constructs a new row inserter. - * - * @param client a BigQuery client - */ - public BigQueryTableInserter(Bigquery client, int maxRowsPerBatch) { - this.client = client; - this.defaultRef = null; - this.maxRowsPerBatch = maxRowsPerBatch; - } - - /** - * Constructs a new row inserter. - * - * @param client a BigQuery client - * @param defaultRef identifies the default table to insert into - * @deprecated replaced by {@link #BigQueryTableInserter(Bigquery, int)} - */ - @Deprecated - public BigQueryTableInserter(Bigquery client, TableReference defaultRef, int maxRowsPerBatch) { - this.client = client; - this.defaultRef = defaultRef; - this.maxRowsPerBatch = maxRowsPerBatch; - } - - /** - * Insert all rows from the given list. - * - * @deprecated replaced by {@link #insertAll(TableReference, List)} - */ - @Deprecated - public void insertAll(List rowList) throws IOException { - insertAll(defaultRef, rowList, null, null); - } - - /** - * Insert all rows from the given list using specified insertIds if not null. - * - * @deprecated replaced by {@link #insertAll(TableReference, List, List, Aggregator)} - */ - @Deprecated - public void insertAll(List rowList, - @Nullable List insertIdList) throws IOException { - insertAll(defaultRef, rowList, insertIdList, null); - } - - /** - * Insert all rows from the given list. - */ - public void insertAll(TableReference ref, List rowList) throws IOException { - insertAll(ref, rowList, null, null); - } - - /** - * Insert all rows from the given list using specified insertIds if not null. Track count of - * bytes written with the Aggregator. - */ - public void insertAll(TableReference ref, List rowList, - @Nullable List insertIdList, Aggregator byteCountAggregator) - throws IOException { - insertAll( - ref, rowList, insertIdList, byteCountAggregator, INSERT_BACKOFF_FACTORY.backoff(), - Sleeper.DEFAULT); - } - - @VisibleForTesting - void insertAll(TableReference ref, List rowList, - @Nullable List insertIdList, Aggregator byteCountAggregator, - BackOff backoff, final Sleeper sleeper) throws IOException { - checkNotNull(ref, "ref"); - if (insertIdList != null && rowList.size() != insertIdList.size()) { - throw new AssertionError("If insertIdList is not null it needs to have at least " - + "as many elements as rowList"); - } - - List allErrors = new ArrayList<>(); - // These lists contain the rows to publish. Initially the contain the entire list. If there are - // failures, they will contain only the failed rows to be retried. - List rowsToPublish = rowList; - List idsToPublish = insertIdList; - while (true) { - List retryRows = new ArrayList<>(); - List retryIds = (idsToPublish != null) ? new ArrayList() : null; - - int strideIndex = 0; - // Upload in batches. - List rows = new LinkedList<>(); - int dataSize = 0; - - List>> futures = new ArrayList<>(); - List strideIndices = new ArrayList<>(); - - for (int i = 0; i < rowsToPublish.size(); ++i) { - TableRow row = rowsToPublish.get(i); - TableDataInsertAllRequest.Rows out = new TableDataInsertAllRequest.Rows(); - if (idsToPublish != null) { - out.setInsertId(idsToPublish.get(i)); - } - out.setJson(row.getUnknownKeys()); - rows.add(out); - - dataSize += row.toString().length(); - if (dataSize >= UPLOAD_BATCH_SIZE_BYTES || rows.size() >= maxRowsPerBatch - || i == rowsToPublish.size() - 1) { - TableDataInsertAllRequest content = new TableDataInsertAllRequest(); - content.setRows(rows); - - final Bigquery.Tabledata.InsertAll insert = client.tabledata() - .insertAll(ref.getProjectId(), ref.getDatasetId(), ref.getTableId(), - content); - - futures.add( - executor.submit(new Callable>() { - @Override - public List call() throws IOException { - BackOff backoff = new IntervalBoundedExponentialBackOff( - MAX_RATE_LIMIT_EXCEEDED_BACKOFF_MS, INITIAL_RATE_LIMIT_EXCEEDED_BACKOFF_MS); - while (true) { - try { - return insert.execute().getInsertErrors(); - } catch (IOException e) { - if (new ApiErrorExtractor().rateLimited(e)) { - LOG.info("BigQuery insertAll exceeded rate limit, retrying"); - try { - sleeper.sleep(backoff.nextBackOffMillis()); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IOException( - "Interrupted while waiting before retrying insertAll"); - } - } else { - throw e; - } - } - } - } - })); - strideIndices.add(strideIndex); - - if (byteCountAggregator != null) { - byteCountAggregator.addValue(Long.valueOf(dataSize)); - } - dataSize = 0; - strideIndex = i + 1; - rows = new LinkedList<>(); - } - } - - try { - for (int i = 0; i < futures.size(); i++) { - List errors = futures.get(i).get(); - if (errors != null) { - for (TableDataInsertAllResponse.InsertErrors error : errors) { - allErrors.add(error); - if (error.getIndex() == null) { - throw new IOException("Insert failed: " + allErrors); - } - - int errorIndex = error.getIndex().intValue() + strideIndices.get(i); - retryRows.add(rowsToPublish.get(errorIndex)); - if (retryIds != null) { - retryIds.add(idsToPublish.get(errorIndex)); - } - } - } - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException("Interrupted while inserting " + rowsToPublish); - } catch (ExecutionException e) { - throw new RuntimeException(e.getCause()); - } - - if (allErrors.isEmpty()) { - break; - } - - long nextBackoffMillis = backoff.nextBackOffMillis(); - if (nextBackoffMillis == BackOff.STOP) { - break; - } - try { - sleeper.sleep(nextBackoffMillis); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException("Interrupted while waiting before retrying insert of " + retryRows); - } - rowsToPublish = retryRows; - idsToPublish = retryIds; - allErrors.clear(); - LOG.info("Retrying {} failed inserts to BigQuery", rowsToPublish.size()); - } - - if (!allErrors.isEmpty()) { - throw new IOException("Insert failed: " + allErrors); - } - } - - /** - * Retrieves or creates the table. - * - *

              The table is checked to conform to insertion requirements as specified - * by WriteDisposition and CreateDisposition. - * - *

              If table truncation is requested (WriteDisposition.WRITE_TRUNCATE), then - * this will re-create the table if necessary to ensure it is empty. - * - *

              If an empty table is required (WriteDisposition.WRITE_EMPTY), then this - * will fail if the table exists and is not empty. - * - *

              When constructing a table, a {@code TableSchema} must be available. If a - * schema is provided, then it will be used. If no schema is provided, but - * an existing table is being cleared (WRITE_TRUNCATE option above), then - * the existing schema will be re-used. If no schema is available, then an - * {@code IOException} is thrown. - */ - public Table getOrCreateTable( - TableReference ref, - WriteDisposition writeDisposition, - CreateDisposition createDisposition, - @Nullable TableSchema schema) throws IOException { - // Check if table already exists. - Bigquery.Tables.Get get = client.tables() - .get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - Table table = null; - try { - table = get.execute(); - } catch (IOException e) { - ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); - if (!errorExtractor.itemNotFound(e) - || createDisposition != CreateDisposition.CREATE_IF_NEEDED) { - // Rethrow. - throw e; - } - } - - // If we want an empty table, and it isn't, then delete it first. - if (table != null) { - if (writeDisposition == WriteDisposition.WRITE_APPEND) { - return table; - } - - boolean empty = isEmpty(ref); - if (empty) { - if (writeDisposition == WriteDisposition.WRITE_TRUNCATE) { - LOG.info("Empty table found, not removing {}", BigQueryIO.toTableSpec(ref)); - } - return table; - - } else if (writeDisposition == WriteDisposition.WRITE_EMPTY) { - throw new IOException("WriteDisposition is WRITE_EMPTY, " - + "but table is not empty"); - } - - // Reuse the existing schema if none was provided. - if (schema == null) { - schema = table.getSchema(); - } - - // Delete table and fall through to re-creating it below. - LOG.info("Deleting table {}", BigQueryIO.toTableSpec(ref)); - Bigquery.Tables.Delete delete = client.tables() - .delete(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - delete.execute(); - } - - if (schema == null) { - throw new IllegalArgumentException( - "Table schema required for new table."); - } - - // Create the table. - return tryCreateTable(ref, schema); - } - - /** - * Checks if a table is empty. - */ - public boolean isEmpty(TableReference ref) throws IOException { - Bigquery.Tabledata.List list = client.tabledata() - .list(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - list.setMaxResults(1L); - TableDataList dataList = list.execute(); - - return dataList.getRows() == null || dataList.getRows().isEmpty(); - } - - /** - * Retry table creation up to 5 minutes (with exponential backoff) when this user is near the - * quota for table creation. This relatively innocuous behavior can happen when BigQueryIO is - * configured with a table spec function to use different tables for each window. - */ - private static final int RETRY_CREATE_TABLE_DURATION_MILLIS = (int) TimeUnit.MINUTES.toMillis(5); - - /** - * Tries to create the BigQuery table. - * If a table with the same name already exists in the dataset, the table - * creation fails, and the function returns null. In such a case, - * the existing table doesn't necessarily have the same schema as specified - * by the parameter. - * - * @param schema Schema of the new BigQuery table. - * @return The newly created BigQuery table information, or null if the table - * with the same name already exists. - * @throws IOException if other error than already existing table occurs. - */ - @Nullable - public Table tryCreateTable(TableReference ref, TableSchema schema) throws IOException { - LOG.info("Trying to create BigQuery table: {}", BigQueryIO.toTableSpec(ref)); - BackOff backoff = - new ExponentialBackOff.Builder() - .setMaxElapsedTimeMillis(RETRY_CREATE_TABLE_DURATION_MILLIS) - .build(); - - Table table = new Table().setTableReference(ref).setSchema(schema); - return tryCreateTable(table, ref.getProjectId(), ref.getDatasetId(), backoff, Sleeper.DEFAULT); - } - - @VisibleForTesting - @Nullable - Table tryCreateTable( - Table table, String projectId, String datasetId, BackOff backoff, Sleeper sleeper) - throws IOException { - boolean retry = false; - while (true) { - try { - return client.tables().insert(projectId, datasetId, table).execute(); - } catch (IOException e) { - ApiErrorExtractor extractor = new ApiErrorExtractor(); - if (extractor.itemAlreadyExists(e)) { - // The table already exists, nothing to return. - return null; - } else if (extractor.rateLimited(e)) { - // The request failed because we hit a temporary quota. Back off and try again. - try { - if (BackOffUtils.next(sleeper, backoff)) { - if (!retry) { - LOG.info( - "Quota limit reached when creating table {}:{}.{}, retrying up to {} minutes", - projectId, - datasetId, - table.getTableReference().getTableId(), - TimeUnit.MILLISECONDS.toSeconds(RETRY_CREATE_TABLE_DURATION_MILLIS) / 60.0); - retry = true; - } - continue; - } - } catch (InterruptedException e1) { - // Restore interrupted state and throw the last failure. - Thread.currentThread().interrupt(); - throw e; - } - } - throw e; - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java deleted file mode 100644 index 8f4ff793dc..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.ClassInfo; -import com.google.api.client.util.Data; -import com.google.api.client.util.Sleeper; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.DatasetReference; -import com.google.api.services.bigquery.model.ErrorProto; -import com.google.api.services.bigquery.model.Job; -import com.google.api.services.bigquery.model.JobConfiguration; -import com.google.api.services.bigquery.model.JobConfigurationQuery; -import com.google.api.services.bigquery.model.JobReference; -import com.google.api.services.bigquery.model.JobStatistics; -import com.google.api.services.bigquery.model.JobStatus; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableCell; -import com.google.api.services.bigquery.model.TableDataList; -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.Uninterruptibles; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Random; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * Iterates over all rows in a table. - */ -public class BigQueryTableRowIterator implements AutoCloseable { - private static final Logger LOG = LoggerFactory.getLogger(BigQueryTableRowIterator.class); - - @Nullable private TableReference ref; - @Nullable private final String projectId; - @Nullable private TableSchema schema; - private final Bigquery client; - private String pageToken; - private Iterator iteratorOverCurrentBatch; - private TableRow current; - // Set true when the final page is seen from the service. - private boolean lastPage = false; - - // The maximum number of times a BigQuery request will be retried - private static final int MAX_RETRIES = 3; - // Initial wait time for the backoff implementation - private static final Duration INITIAL_BACKOFF_TIME = Duration.standardSeconds(1); - - // After sending a query to BQ service we will be polling the BQ service to check the status with - // following interval to check the status of query execution job - private static final Duration QUERY_COMPLETION_POLL_TIME = Duration.standardSeconds(1); - - private final String query; - // Whether to flatten query results. - private final boolean flattenResults; - // Whether to use the BigQuery legacy SQL dialect.. - private final boolean useLegacySql; - // Temporary dataset used to store query results. - private String temporaryDatasetId = null; - // Temporary table used to store query results. - private String temporaryTableId = null; - - private BigQueryTableRowIterator( - @Nullable TableReference ref, @Nullable String query, @Nullable String projectId, - Bigquery client, boolean flattenResults, boolean useLegacySql) { - this.ref = ref; - this.query = query; - this.projectId = projectId; - this.client = checkNotNull(client, "client"); - this.flattenResults = flattenResults; - this.useLegacySql = useLegacySql; - } - - /** - * Constructs a {@code BigQueryTableRowIterator} that reads from the specified table. - */ - public static BigQueryTableRowIterator fromTable(TableReference ref, Bigquery client) { - checkNotNull(ref, "ref"); - checkNotNull(client, "client"); - return new BigQueryTableRowIterator(ref, null, ref.getProjectId(), client, true, true); - } - - /** - * Constructs a {@code BigQueryTableRowIterator} that reads from the results of executing the - * specified query in the specified project with useLegacySql set to True. - * - * @deprecated use {@link #fromQuery(String, String, Bigquery, Boolean, Boolean)}. - */ - @Deprecated - public static BigQueryTableRowIterator fromQuery( - String query, String projectId, Bigquery client, @Nullable Boolean flattenResults) { - return fromQuery(query, projectId, client, flattenResults, null /* useLegacySql */); - } - - /** - * Constructs a {@code BigQueryTableRowIterator} that reads from the results of executing the - * specified query in the specified project. - */ - public static BigQueryTableRowIterator fromQuery( - String query, String projectId, Bigquery client, @Nullable Boolean flattenResults, - @Nullable Boolean useLegacySql) { - checkNotNull(query, "query"); - checkNotNull(projectId, "projectId"); - checkNotNull(client, "client"); - return new BigQueryTableRowIterator(null, query, projectId, client, - MoreObjects.firstNonNull(flattenResults, Boolean.TRUE), - MoreObjects.firstNonNull(useLegacySql, Boolean.TRUE)); - } - - /** - * Opens the table for read. - * @throws IOException on failure - */ - public void open() throws IOException, InterruptedException { - if (query != null) { - ref = executeQueryAndWaitForCompletion(); - } - // Get table schema. - schema = getTable(ref).getSchema(); - } - - public boolean advance() throws IOException, InterruptedException { - while (true) { - if (iteratorOverCurrentBatch != null && iteratorOverCurrentBatch.hasNext()) { - // Embed schema information into the raw row, so that values have an - // associated key. This matches how rows are read when using the - // DataflowPipelineRunner. - current = getTypedTableRow(schema.getFields(), iteratorOverCurrentBatch.next()); - return true; - } - if (lastPage) { - return false; - } - - Bigquery.Tabledata.List list = - client.tabledata().list(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - if (pageToken != null) { - list.setPageToken(pageToken); - } - - TableDataList result = executeWithBackOff( - list, - String.format( - "Error reading from BigQuery table %s of dataset %s.", - ref.getTableId(), ref.getDatasetId())); - - pageToken = result.getPageToken(); - iteratorOverCurrentBatch = - result.getRows() != null - ? result.getRows().iterator() - : Collections.emptyIterator(); - - // The server may return a page token indefinitely on a zero-length table. - if (pageToken == null || result.getTotalRows() != null && result.getTotalRows() == 0) { - lastPage = true; - } - } - } - - public TableRow getCurrent() { - if (current == null) { - throw new NoSuchElementException(); - } - return current; - } - - /** - * Adjusts a field returned from the BigQuery API to match what we will receive when running - * BigQuery's export-to-GCS and parallel read, which is the efficient parallel implementation - * used for batch jobs executed on the Cloud Dataflow service. - * - *

              The following is the relationship between BigQuery schema and Java types: - * - *

                - *
              • Nulls are {@code null}. - *
              • Repeated fields are {@code List} of objects. - *
              • Record columns are {@link TableRow} objects. - *
              • {@code BOOLEAN} columns are JSON booleans, hence Java {@code Boolean} objects. - *
              • {@code FLOAT} columns are JSON floats, hence Java {@code Double} objects. - *
              • {@code TIMESTAMP} columns are {@code String} objects that are of the format - * {@code yyyy-MM-dd HH:mm:ss[.SSSSSS] UTC}, where the {@code .SSSSSS} has no trailing - * zeros and can be 1 to 6 digits long. - *
              • Every other atomic type is a {@code String}. - *
              - * - *

              Note that integers are encoded as strings to match BigQuery's exported JSON format. - * - *

              Finally, values are stored in the {@link TableRow} as {"field name": value} pairs - * and are not accessible through the {@link TableRow#getF} function. - */ - @Nullable private Object getTypedCellValue(TableFieldSchema fieldSchema, Object v) { - if (Data.isNull(v)) { - return null; - } - - if (Objects.equals(fieldSchema.getMode(), "REPEATED")) { - TableFieldSchema elementSchema = fieldSchema.clone().setMode("REQUIRED"); - @SuppressWarnings("unchecked") - List> rawCells = (List>) v; - ImmutableList.Builder values = ImmutableList.builder(); - for (Map element : rawCells) { - values.add(getTypedCellValue(elementSchema, element.get("v"))); - } - return values.build(); - } - - if (fieldSchema.getType().equals("RECORD")) { - @SuppressWarnings("unchecked") - Map typedV = (Map) v; - return getTypedTableRow(fieldSchema.getFields(), typedV); - } - - if (fieldSchema.getType().equals("FLOAT")) { - return Double.parseDouble((String) v); - } - - if (fieldSchema.getType().equals("BOOLEAN")) { - return Boolean.parseBoolean((String) v); - } - - if (fieldSchema.getType().equals("TIMESTAMP")) { - return AvroUtils.formatTimestamp((String) v); - } - - // Returns the original value for: - // 1. String, 2. base64 encoded BYTES, 3. DATE, DATETIME, TIME strings. - return v; - } - - /** - * A list of the field names that cannot be used in BigQuery tables processed by Dataflow, - * because they are reserved keywords in {@link TableRow}. - */ - // TODO: This limitation is unfortunate. We need to give users a way to use BigQueryIO that does - // not indirect through our broken use of {@link TableRow}. - // See discussion: https://github.com/GoogleCloudPlatform/DataflowJavaSDK/pull/41 - private static final Collection RESERVED_FIELD_NAMES = - ClassInfo.of(TableRow.class).getNames(); - - /** - * Converts a row returned from the BigQuery JSON API as a {@code Map} into a - * Java {@link TableRow} with nested {@link TableCell TableCells}. The {@code Object} values in - * the cells are converted to Java types according to the provided field schemas. - * - *

              See {@link #getTypedCellValue(TableFieldSchema, Object)} for details on how BigQuery - * types are mapped to Java types. - */ - private TableRow getTypedTableRow(List fields, Map rawRow) { - // If rawRow is a TableRow, use it. If not, create a new one. - TableRow row; - List> cells; - if (rawRow instanceof TableRow) { - // Since rawRow is a TableRow it already has TableCell objects in setF. We do not need to do - // any type conversion, but extract the cells for cell-wise processing below. - row = (TableRow) rawRow; - cells = row.getF(); - // Clear the cells from the row, so that row.getF() will return null. This matches the - // behavior of rows produced by the BigQuery export API used on the service. - row.setF(null); - } else { - row = new TableRow(); - - // Since rawRow is a Map we use Map.get("f") instead of TableRow.getF() to - // get its cells. Similarly, when rawCell is a Map instead of a TableCell, - // we will use Map.get("v") instead of TableCell.getV() get its value. - @SuppressWarnings("unchecked") - List> rawCells = - (List>) rawRow.get("f"); - cells = rawCells; - } - - checkState(cells.size() == fields.size(), - "Expected that the row has the same number of cells %s as fields in the schema %s", - cells.size(), fields.size()); - - // Loop through all the fields in the row, normalizing their types with the TableFieldSchema - // and storing the normalized values by field name in the Map that - // underlies the TableRow. - Iterator> cellIt = cells.iterator(); - Iterator fieldIt = fields.iterator(); - while (cellIt.hasNext()) { - Map cell = cellIt.next(); - TableFieldSchema fieldSchema = fieldIt.next(); - - // Convert the object in this cell to the Java type corresponding to its type in the schema. - Object convertedValue = getTypedCellValue(fieldSchema, cell.get("v")); - - String fieldName = fieldSchema.getName(); - checkArgument(!RESERVED_FIELD_NAMES.contains(fieldName), - "BigQueryIO does not support records with columns named %s", fieldName); - - if (convertedValue == null) { - // BigQuery does not include null values when the export operation (to JSON) is used. - // To match that behavior, BigQueryTableRowiterator, and the DirectPipelineRunner, - // intentionally omits columns with null values. - continue; - } - - row.set(fieldName, convertedValue); - } - return row; - } - - // Get the BiqQuery table. - private Table getTable(TableReference ref) throws IOException, InterruptedException { - Bigquery.Tables.Get get = - client.tables().get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); - - return executeWithBackOff( - get, - String.format( - "Error opening BigQuery table %s of dataset %s.", - ref.getTableId(), - ref.getDatasetId())); - } - - // Create a new BigQuery dataset - private void createDataset(String datasetId, @Nullable String location) - throws IOException, InterruptedException { - Dataset dataset = new Dataset(); - DatasetReference reference = new DatasetReference(); - reference.setProjectId(projectId); - reference.setDatasetId(datasetId); - dataset.setDatasetReference(reference); - if (location != null) { - dataset.setLocation(location); - } - - executeWithBackOff( - client.datasets().insert(projectId, dataset), - String.format( - "Error when trying to create the temporary dataset %s in project %s.", - datasetId, projectId)); - } - - // Delete the given table that is available in the given dataset. - private void deleteTable(String datasetId, String tableId) - throws IOException, InterruptedException { - executeWithBackOff( - client.tables().delete(projectId, datasetId, tableId), - String.format( - "Error when trying to delete the temporary table %s in dataset %s of project %s. " - + "Manual deletion may be required.", - tableId, datasetId, projectId)); - } - - // Delete the given dataset. This will fail if the given dataset has any tables. - private void deleteDataset(String datasetId) throws IOException, InterruptedException { - executeWithBackOff( - client.datasets().delete(projectId, datasetId), - String.format( - "Error when trying to delete the temporary dataset %s in project %s. " - + "Manual deletion may be required.", - datasetId, projectId)); - } - - /** - * Executes the specified query and returns a reference to the temporary BigQuery table created - * to hold the results. - * - * @throws IOException if the query fails. - */ - private TableReference executeQueryAndWaitForCompletion() - throws IOException, InterruptedException { - // Dry run query to get source table location - Job dryRunJob = new Job() - .setConfiguration(new JobConfiguration() - .setQuery(new JobConfigurationQuery() - .setQuery(query)) - .setDryRun(true)); - JobStatistics jobStats = executeWithBackOff( - client.jobs().insert(projectId, dryRunJob), - String.format("Error when trying to dry run query %s.", query)).getStatistics(); - - // Let BigQuery to pick default location if the query does not read any tables. - String location = null; - @Nullable List tables = jobStats.getQuery().getReferencedTables(); - if (tables != null && !tables.isEmpty()) { - Table table = getTable(tables.get(0)); - location = table.getLocation(); - } - - // Create a temporary dataset to store results. - // Starting dataset name with an "_" so that it is hidden. - Random rnd = new Random(System.currentTimeMillis()); - temporaryDatasetId = "_dataflow_temporary_dataset_" + rnd.nextInt(1000000); - temporaryTableId = "dataflow_temporary_table_" + rnd.nextInt(1000000); - - createDataset(temporaryDatasetId, location); - Job job = new Job(); - JobConfiguration config = new JobConfiguration(); - JobConfigurationQuery queryConfig = new JobConfigurationQuery(); - config.setQuery(queryConfig); - job.setConfiguration(config); - queryConfig.setQuery(query); - queryConfig.setAllowLargeResults(true); - queryConfig.setFlattenResults(flattenResults); - queryConfig.setUseLegacySql(useLegacySql); - - - TableReference destinationTable = new TableReference(); - destinationTable.setProjectId(projectId); - destinationTable.setDatasetId(temporaryDatasetId); - destinationTable.setTableId(temporaryTableId); - queryConfig.setDestinationTable(destinationTable); - - Job queryJob = executeWithBackOff( - client.jobs().insert(projectId, job), - String.format("Error when trying to execute the job for query %s.", query)); - JobReference jobId = queryJob.getJobReference(); - - while (true) { - Job pollJob = executeWithBackOff( - client.jobs().get(projectId, jobId.getJobId()), - String.format("Error when trying to get status of the job for query %s.", query)); - JobStatus status = pollJob.getStatus(); - if (status.getState().equals("DONE")) { - // Job is DONE, but did not necessarily succeed. - ErrorProto error = status.getErrorResult(); - if (error == null) { - return pollJob.getConfiguration().getQuery().getDestinationTable(); - } else { - // There will be no temporary table to delete, so null out the reference. - temporaryTableId = null; - throw new IOException("Executing query " + query + " failed: " + error.getMessage()); - } - } - Uninterruptibles.sleepUninterruptibly( - QUERY_COMPLETION_POLL_TIME.getMillis(), TimeUnit.MILLISECONDS); - } - } - - /** - * Execute a BQ request with exponential backoff and return the result. - * - * @deprecated use {@link #executeWithBackOff(AbstractGoogleClientRequest, String)}. - */ - @Deprecated - public static T executeWithBackOff(AbstractGoogleClientRequest client, String error, - Object... errorArgs) throws IOException, InterruptedException { - return executeWithBackOff(client, String.format(error, errorArgs)); - } - - // Execute a BQ request with exponential backoff and return the result. - // client - BQ request to be executed - // error - Formatted message to log if when a request fails. Takes exception message as a - // formatter parameter. - public static T executeWithBackOff(AbstractGoogleClientRequest client, String error) - throws IOException, InterruptedException { - Sleeper sleeper = Sleeper.DEFAULT; - BackOff backOff = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RETRIES).withInitialBackoff(INITIAL_BACKOFF_TIME).backoff(); - - T result = null; - while (true) { - try { - result = client.execute(); - break; - } catch (IOException e) { - LOG.error("{}", error, e); - if (!BackOffUtils.next(sleeper, backOff)) { - String errorMessage = String.format( - "%s Failing to execute job after %d attempts.", error, MAX_RETRIES + 1); - LOG.error("{}", errorMessage, e); - throw new IOException(errorMessage, e); - } - } - } - return result; - } - - @Override - public void close() { - // Prevent any further requests. - lastPage = true; - - try { - // Deleting temporary table and dataset that gets generated when executing a query. - if (temporaryDatasetId != null) { - if (temporaryTableId != null) { - deleteTable(temporaryDatasetId, temporaryTableId); - } - deleteDataset(temporaryDatasetId); - } - } catch (IOException | InterruptedException e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - throw new RuntimeException(e); - } - - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BitSetCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BitSetCoder.java deleted file mode 100644 index f3a039ad66..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BitSetCoder.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.CoderException; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.BitSet; - -/** - * Coder for the BitSet used to track child-trigger finished states. - */ -class BitSetCoder extends AtomicCoder { - - private static final BitSetCoder INSTANCE = new BitSetCoder(); - private transient ByteArrayCoder byteArrayCoder = ByteArrayCoder.of(); - - private BitSetCoder() {} - - public static BitSetCoder of() { - return INSTANCE; - } - - @Override - public void encode(BitSet value, OutputStream outStream, Context context) - throws CoderException, IOException { - byteArrayCoder.encodeAndOwn(value.toByteArray(), outStream, context); - } - - @Override - public BitSet decode(InputStream inStream, Context context) - throws CoderException, IOException { - return BitSet.valueOf(byteArrayCoder.decode(inStream, context)); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "BitSetCoder requires its byteArrayCoder to be deterministic.", - byteArrayCoder); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java deleted file mode 100644 index 36efcce94c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BucketingFunction.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.Combine; -import java.util.HashMap; -import java.util.Map; - -/** - * Keep track of the minimum/maximum/sum of a set of timestamped long values. - * For efficiency, bucket values by their timestamp. - */ -public class BucketingFunction { - private static class Bucket { - private int numSamples; - private long combinedValue; - - public Bucket(BucketingFunction outer) { - numSamples = 0; - combinedValue = outer.function.identity(); - } - - public void add(BucketingFunction outer, long value) { - combinedValue = outer.function.apply(combinedValue, value); - numSamples++; - } - - public boolean remove() { - numSamples--; - checkState(numSamples >= 0, "Lost count of samples"); - return numSamples == 0; - } - - public long get() { - return combinedValue; - } - } - - /** - * How large a time interval to fit within each bucket. - */ - private final long bucketWidthMs; - - /** - * How many buckets are considered 'significant'? - */ - private final int numSignificantBuckets; - - /** - * How many samples are considered 'significant'? - */ - private final int numSignificantSamples; - - /** - * Function for combining sample values. - */ - private final Combine.BinaryCombineLongFn function; - - /** - * Active buckets. - */ - private final Map buckets; - - public BucketingFunction( - long bucketWidthMs, - int numSignificantBuckets, - int numSignificantSamples, - Combine.BinaryCombineLongFn function) { - this.bucketWidthMs = bucketWidthMs; - this.numSignificantBuckets = numSignificantBuckets; - this.numSignificantSamples = numSignificantSamples; - this.function = function; - this.buckets = new HashMap<>(); - } - - /** - * Which bucket key corresponds to {@code timeMsSinceEpoch}. - */ - private long key(long timeMsSinceEpoch) { - return timeMsSinceEpoch - (timeMsSinceEpoch % bucketWidthMs); - } - - /** - * Add one sample of {@code value} (to bucket) at {@code timeMsSinceEpoch}. - */ - public void add(long timeMsSinceEpoch, long value) { - long key = key(timeMsSinceEpoch); - Bucket bucket = buckets.get(key); - if (bucket == null) { - bucket = new Bucket(this); - buckets.put(key, bucket); - } - bucket.add(this, value); - } - - /** - * Remove one sample (from bucket) at {@code timeMsSinceEpoch}. - */ - public void remove(long timeMsSinceEpoch) { - long key = key(timeMsSinceEpoch); - Bucket bucket = buckets.get(key); - if (bucket == null) { - return; - } - if (bucket.remove()) { - buckets.remove(key); - } - } - - /** - * Return the (bucketized) combined value of all samples. - */ - public long get() { - long result = function.identity(); - for (Bucket bucket : buckets.values()) { - result = function.apply(result, bucket.get()); - } - return result; - } - - /** - * Is the current result 'significant'? Ie is it drawn from enough buckets - * or from enough samples? - */ - public boolean isSignificant() { - if (buckets.size() >= numSignificantBuckets) { - return true; - } - int totalSamples = 0; - for (Bucket bucket : buckets.values()) { - totalSamples += bucket.numSamples; - } - return totalSamples >= numSignificantSamples; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStream.java deleted file mode 100644 index e8e693a996..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStream.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder.Context; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -import javax.annotation.concurrent.NotThreadSafe; - -/** - * Provides an efficient encoding for {@link Iterable}s containing small values by - * buffering up to {@code bufferSize} bytes of data before prefixing the count. - * Note that each element needs to be encoded in a nested context. See - * {@link Context Coder.Context} for more details. - * - *

              To use this stream: - *

              
              - * BufferedElementCountingOutputStream os = ...
              - * for (Element E : elements) {
              - *   os.markElementStart();
              - *   // write an element to os
              - * }
              - * os.finish();
              - * 
              - * - *

              The resulting output stream is: - *

              - * countA element(0) element(1) ... element(countA - 1)
              - * countB element(0) element(1) ... element(countB - 1)
              - * ...
              - * countX element(0) element(1) ... element(countX - 1)
              - * countY
              - * 
              - * - *

              To read this stream: - *

              
              - * InputStream is = ...
              - * long count;
              - * do {
              - *   count = VarInt.decodeLong(is);
              - *   for (int i = 0; i < count; ++i) {
              - *     // read an element from is
              - *   }
              - * } while(count > 0);
              - * 
              - * - *

              The counts are encoded as variable length longs. See {@link VarInt#encode(long, OutputStream)} - * for more details. The end of the iterable is detected by reading a count of 0. - */ -@NotThreadSafe -public class BufferedElementCountingOutputStream extends OutputStream { - public static final int DEFAULT_BUFFER_SIZE = 64 * 1024; - private final ByteBuffer buffer; - private final OutputStream os; - private boolean finished; - private long count; - - /** - * Creates an output stream which encodes the number of elements output to it in a streaming - * manner. - */ - public BufferedElementCountingOutputStream(OutputStream os) { - this(os, DEFAULT_BUFFER_SIZE); - } - - /** - * Creates an output stream which encodes the number of elements output to it in a streaming - * manner with the given {@code bufferSize}. - */ - BufferedElementCountingOutputStream(OutputStream os, int bufferSize) { - this.buffer = ByteBuffer.allocate(bufferSize); - this.os = os; - this.finished = false; - this.count = 0; - } - - /** - * Finishes the encoding by flushing any buffered data, - * and outputting a final count of 0. - */ - public void finish() throws IOException { - if (finished) { - return; - } - flush(); - // Finish the stream by stating that there are 0 elements that follow. - VarInt.encode(0, os); - finished = true; - } - - /** - * Marks that a new element is being output. This allows this output stream - * to use the buffer if it had previously overflowed marking the start of a new - * block of elements. - */ - public void markElementStart() throws IOException { - if (finished) { - throw new IOException("Stream has been finished. Can not add any more elements."); - } - count++; - } - - @Override - public void write(int b) throws IOException { - if (finished) { - throw new IOException("Stream has been finished. Can not write any more data."); - } - if (count == 0) { - os.write(b); - return; - } - - if (buffer.hasRemaining()) { - buffer.put((byte) b); - } else { - outputBuffer(); - os.write(b); - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - if (finished) { - throw new IOException("Stream has been finished. Can not write any more data."); - } - if (count == 0) { - os.write(b, off, len); - return; - } - - if (buffer.remaining() >= len) { - buffer.put(b, off, len); - } else { - outputBuffer(); - os.write(b, off, len); - } - } - - @Override - public void flush() throws IOException { - if (finished) { - return; - } - outputBuffer(); - os.flush(); - } - - @Override - public void close() throws IOException { - finish(); - os.close(); - } - - // Output the buffer if it contains any data. - private void outputBuffer() throws IOException { - if (count > 0) { - VarInt.encode(count, os); - // We are using a heap based buffer and not a direct buffer so it is safe to access - // the underlying array. - os.write(buffer.array(), buffer.arrayOffset(), buffer.position()); - buffer.clear(); - // The buffer has been flushed so we must write to the underlying stream until - // we learn of the next element. We reset the count to zero marking that we should - // not use the buffer. - count = 0; - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudKnownType.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudKnownType.java deleted file mode 100644 index 8b41eb83da..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudKnownType.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.Nullable; - -/** A utility for manipulating well-known cloud types. */ -enum CloudKnownType { - TEXT("http://schema.org/Text", String.class) { - @Override - public T parse(Object value, Class clazz) { - return clazz.cast(value); - } - }, - BOOLEAN("http://schema.org/Boolean", Boolean.class) { - @Override - public T parse(Object value, Class clazz) { - return clazz.cast(value); - } - }, - INTEGER("http://schema.org/Integer", Long.class, Integer.class) { - @Override - public T parse(Object value, Class clazz) { - Object result = null; - if (value.getClass() == clazz) { - result = value; - } else if (clazz == Long.class) { - if (value instanceof Integer) { - result = ((Integer) value).longValue(); - } else if (value instanceof String) { - result = Long.valueOf((String) value); - } - } else if (clazz == Integer.class) { - if (value instanceof Long) { - result = ((Long) value).intValue(); - } else if (value instanceof String) { - result = Integer.valueOf((String) value); - } - } - return clazz.cast(result); - } - }, - FLOAT("http://schema.org/Float", Double.class, Float.class) { - @Override - public T parse(Object value, Class clazz) { - Object result = null; - if (value.getClass() == clazz) { - result = value; - } else if (clazz == Double.class) { - if (value instanceof Float) { - result = ((Float) value).doubleValue(); - } else if (value instanceof String) { - result = Double.valueOf((String) value); - } - } else if (clazz == Float.class) { - if (value instanceof Double) { - result = ((Double) value).floatValue(); - } else if (value instanceof String) { - result = Float.valueOf((String) value); - } - } - return clazz.cast(result); - } - }; - - private final String uri; - private final Class[] classes; - - private CloudKnownType(String uri, Class... classes) { - this.uri = uri; - this.classes = classes; - } - - public String getUri() { - return uri; - } - - public abstract T parse(Object value, Class clazz); - - public Class defaultClass() { - return classes[0]; - } - - private static final Map typesByUri = - Collections.unmodifiableMap(buildTypesByUri()); - - private static Map buildTypesByUri() { - Map result = new HashMap<>(); - for (CloudKnownType ty : CloudKnownType.values()) { - result.put(ty.getUri(), ty); - } - return result; - } - - @Nullable - public static CloudKnownType forUri(@Nullable String uri) { - if (uri == null) { - return null; - } - return typesByUri.get(uri); - } - - private static final Map, CloudKnownType> typesByClass = - Collections.unmodifiableMap(buildTypesByClass()); - - private static Map, CloudKnownType> buildTypesByClass() { - Map, CloudKnownType> result = new HashMap<>(); - for (CloudKnownType ty : CloudKnownType.values()) { - for (Class clazz : ty.classes) { - result.put(clazz, ty); - } - } - return result; - } - - @Nullable - public static CloudKnownType forClass(Class clazz) { - return typesByClass.get(clazz); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java deleted file mode 100644 index 26645aa773..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CloudObject.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.json.GenericJson; -import com.google.api.client.util.Key; - -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * A representation of an arbitrary Java object to be instantiated by Dataflow - * workers. - * - *

              Typically, an object to be written by the SDK to the Dataflow service will - * implement a method (typically called {@code asCloudObject()}) that returns a - * {@code CloudObject} to represent the object in the protocol. Once the - * {@code CloudObject} is constructed, the method should explicitly add - * additional properties to be presented during deserialization, representing - * child objects by building additional {@code CloudObject}s. - */ -public final class CloudObject extends GenericJson { - /** - * Constructs a {@code CloudObject} by copying the supplied serialized object - * spec, which must represent an SDK object serialized for transport via the - * Dataflow API. - * - *

              The most common use of this method is during deserialization on the worker, - * where it's used as a binding type during instance construction. - * - * @param spec supplies the serialized form of the object as a nested map - * @throws RuntimeException if the supplied map does not represent an SDK object - */ - public static CloudObject fromSpec(Map spec) { - CloudObject result = new CloudObject(); - result.putAll(spec); - if (result.className == null) { - throw new RuntimeException("Unable to create an SDK object from " + spec - + ": Object class not specified (missing \"" - + PropertyNames.OBJECT_TYPE_NAME + "\" field)"); - } - return result; - } - - /** - * Constructs a {@code CloudObject} to be used for serializing an instance of - * the supplied class for transport via the Dataflow API. The instance - * parameters to be serialized must be supplied explicitly after the - * {@code CloudObject} is created, by using {@link CloudObject#put}. - * - * @param cls the class to use when deserializing the object on the worker - */ - public static CloudObject forClass(Class cls) { - CloudObject result = new CloudObject(); - result.className = checkNotNull(cls).getName(); - return result; - } - - /** - * Constructs a {@code CloudObject} to be used for serializing data to be - * deserialized using the supplied class name the supplied class name for - * transport via the Dataflow API. The instance parameters to be serialized - * must be supplied explicitly after the {@code CloudObject} is created, by - * using {@link CloudObject#put}. - * - * @param className the class to use when deserializing the object on the worker - */ - public static CloudObject forClassName(String className) { - CloudObject result = new CloudObject(); - result.className = checkNotNull(className); - return result; - } - - /** - * Constructs a {@code CloudObject} representing the given value. - * @param value the scalar value to represent. - */ - public static CloudObject forString(String value) { - CloudObject result = forClassName(CloudKnownType.TEXT.getUri()); - result.put(PropertyNames.SCALAR_FIELD_NAME, value); - return result; - } - - /** - * Constructs a {@code CloudObject} representing the given value. - * @param value the scalar value to represent. - */ - public static CloudObject forBoolean(Boolean value) { - CloudObject result = forClassName(CloudKnownType.BOOLEAN.getUri()); - result.put(PropertyNames.SCALAR_FIELD_NAME, value); - return result; - } - - /** - * Constructs a {@code CloudObject} representing the given value. - * @param value the scalar value to represent. - */ - public static CloudObject forInteger(Long value) { - CloudObject result = forClassName(CloudKnownType.INTEGER.getUri()); - result.put(PropertyNames.SCALAR_FIELD_NAME, value); - return result; - } - - /** - * Constructs a {@code CloudObject} representing the given value. - * @param value the scalar value to represent. - */ - public static CloudObject forInteger(Integer value) { - CloudObject result = forClassName(CloudKnownType.INTEGER.getUri()); - result.put(PropertyNames.SCALAR_FIELD_NAME, value); - return result; - } - - /** - * Constructs a {@code CloudObject} representing the given value. - * @param value the scalar value to represent. - */ - public static CloudObject forFloat(Float value) { - CloudObject result = forClassName(CloudKnownType.FLOAT.getUri()); - result.put(PropertyNames.SCALAR_FIELD_NAME, value); - return result; - } - - /** - * Constructs a {@code CloudObject} representing the given value. - * @param value the scalar value to represent. - */ - public static CloudObject forFloat(Double value) { - CloudObject result = forClassName(CloudKnownType.FLOAT.getUri()); - result.put(PropertyNames.SCALAR_FIELD_NAME, value); - return result; - } - - /** - * Constructs a {@code CloudObject} representing the given value of a - * well-known cloud object type. - * @param value the scalar value to represent. - * @throws RuntimeException if the value does not have a - * {@link CloudKnownType} mapping - */ - public static CloudObject forKnownType(Object value) { - @Nullable CloudKnownType ty = CloudKnownType.forClass(value.getClass()); - if (ty == null) { - throw new RuntimeException("Unable to represent value via the Dataflow API: " + value); - } - CloudObject result = forClassName(ty.getUri()); - result.put(PropertyNames.SCALAR_FIELD_NAME, value); - return result; - } - - @Key(PropertyNames.OBJECT_TYPE_NAME) - private String className; - - private CloudObject() {} - - /** - * Gets the name of the Java class that this CloudObject represents. - */ - public String getClassName() { - return className; - } - - @Override - public CloudObject clone() { - return (CloudObject) super.clone(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java deleted file mode 100644 index ddab933f54..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CoderUtils.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.Structs.addList; - -import com.google.api.client.util.Base64; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoderBase; -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.MapCoderBase; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Throwables; - -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeInfo.As; -import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; -import com.fasterxml.jackson.databind.DatabindContext; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; -import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.databind.type.TypeFactory; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.ref.SoftReference; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.TypeVariable; - -/** - * Utilities for working with Coders. - */ -public final class CoderUtils { - private CoderUtils() {} // Non-instantiable - - /** - * Coder class-name alias for a key-value type. - */ - public static final String KIND_PAIR = "kind:pair"; - - /** - * Coder class-name alias for a stream type. - */ - public static final String KIND_STREAM = "kind:stream"; - - private static ThreadLocal> threadLocalOutputStream - = new ThreadLocal<>(); - - /** - * If true, a call to {@code encodeToByteArray} is already on the call stack. - */ - private static ThreadLocal threadLocalOutputStreamInUse = new ThreadLocal() { - @Override - protected Boolean initialValue() { - return false; - } - }; - - /** - * Encodes the given value using the specified Coder, and returns - * the encoded bytes. - * - *

              This function is not reentrant; it should not be called from methods of the provided - * {@link Coder}. - */ - public static byte[] encodeToByteArray(Coder coder, T value) throws CoderException { - return encodeToByteArray(coder, value, Coder.Context.OUTER); - } - - public static byte[] encodeToByteArray(Coder coder, T value, Coder.Context context) - throws CoderException { - if (threadLocalOutputStreamInUse.get()) { - // encodeToByteArray() is called recursively and the thread local stream is in use, - // allocating a new one. - ByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); - encodeToSafeStream(coder, value, stream, context); - return stream.toByteArray(); - } else { - threadLocalOutputStreamInUse.set(true); - try { - ByteArrayOutputStream stream = getThreadLocalOutputStream(); - encodeToSafeStream(coder, value, stream, context); - return stream.toByteArray(); - } finally { - threadLocalOutputStreamInUse.set(false); - } - } - } - - /** - * Encodes {@code value} to the given {@code stream}, which should be a stream that never throws - * {@code IOException}, such as {@code ByteArrayOutputStream} or - * {@link ExposedByteArrayOutputStream}. - */ - private static void encodeToSafeStream( - Coder coder, T value, OutputStream stream, Coder.Context context) throws CoderException { - try { - coder.encode(value, new UnownedOutputStream(stream), context); - } catch (IOException exn) { - Throwables.propagateIfPossible(exn, CoderException.class); - throw new IllegalArgumentException( - "Forbidden IOException when writing to OutputStream", exn); - } - } - - /** - * Decodes the given bytes using the specified Coder, and returns - * the resulting decoded value. - */ - public static T decodeFromByteArray(Coder coder, byte[] encodedValue) - throws CoderException { - return decodeFromByteArray(coder, encodedValue, Coder.Context.OUTER); - } - - public static T decodeFromByteArray( - Coder coder, byte[] encodedValue, Coder.Context context) throws CoderException { - try (ExposedByteArrayInputStream stream = new ExposedByteArrayInputStream(encodedValue)) { - T result = decodeFromSafeStream(coder, stream, context); - if (stream.available() != 0) { - throw new CoderException( - stream.available() + " unexpected extra bytes after decoding " + result); - } - return result; - } - } - - /** - * Decodes a value from the given {@code stream}, which should be a stream that never throws - * {@code IOException}, such as {@code ByteArrayInputStream} or - * {@link ExposedByteArrayInputStream}. - */ - private static T decodeFromSafeStream( - Coder coder, InputStream stream, Coder.Context context) throws CoderException { - try { - return coder.decode(new UnownedInputStream(stream), context); - } catch (IOException exn) { - Throwables.propagateIfPossible(exn, CoderException.class); - throw new IllegalArgumentException( - "Forbidden IOException when reading from InputStream", exn); - } - } - - private static ByteArrayOutputStream getThreadLocalOutputStream() { - SoftReference refStream = threadLocalOutputStream.get(); - ExposedByteArrayOutputStream stream = refStream == null ? null : refStream.get(); - if (stream == null) { - stream = new ExposedByteArrayOutputStream(); - threadLocalOutputStream.set(new SoftReference<>(stream)); - } - stream.reset(); - return stream; - } - - /** - * Clones the given value by encoding and then decoding it with the specified Coder. - * - *

              This function is not reentrant; it should not be called from methods of the provided - * {@link Coder}. - */ - public static T clone(Coder coder, T value) throws CoderException { - return decodeFromByteArray(coder, encodeToByteArray(coder, value, Coder.Context.OUTER)); - } - - /** - * Encodes the given value using the specified Coder, and returns the Base64 encoding of the - * encoded bytes. - * - * @throws CoderException if there are errors during encoding. - */ - public static String encodeToBase64(Coder coder, T value) - throws CoderException { - byte[] rawValue = encodeToByteArray(coder, value); - return Base64.encodeBase64URLSafeString(rawValue); - } - - /** - * Parses a value from a base64-encoded String using the given coder. - */ - public static T decodeFromBase64(Coder coder, String encodedValue) throws CoderException { - return decodeFromSafeStream( - coder, new ByteArrayInputStream(Base64.decodeBase64(encodedValue)), Coder.Context.OUTER); - } - - /** - * If {@code coderType} is a subclass of {@code Coder} for a specific - * type {@code T}, returns {@code T.class}. - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public static TypeDescriptor getCodedType(TypeDescriptor coderDescriptor) { - ParameterizedType coderType = - (ParameterizedType) coderDescriptor.getSupertype(Coder.class).getType(); - TypeDescriptor codedType = TypeDescriptor.of(coderType.getActualTypeArguments()[0]); - return codedType; - } - - public static CloudObject makeCloudEncoding( - String type, - CloudObject... componentSpecs) { - CloudObject encoding = CloudObject.forClassName(type); - if (componentSpecs.length > 0) { - addList(encoding, PropertyNames.COMPONENT_ENCODINGS, componentSpecs); - } - return encoding; - } - - /** - * A {@link com.fasterxml.jackson.databind.Module} that adds the type - * resolver needed for Coder definitions created by the Dataflow service. - */ - static final class Jackson2Module extends SimpleModule { - /** - * The Coder custom type resolver. - * - *

              This resolver resolves coders. If the Coder ID is a particular - * well-known identifier supplied by the Dataflow service, it's replaced - * with the corresponding class. All other Coder instances are resolved - * by class name, using the package com.google.cloud.dataflow.sdk.coders - * if there are no "."s in the ID. - */ - private static final class Resolver extends TypeIdResolverBase { - @SuppressWarnings("unused") // Used via @JsonTypeIdResolver annotation on Mixin - public Resolver() { - super(TypeFactory.defaultInstance().constructType(Coder.class), - TypeFactory.defaultInstance()); - } - - @Deprecated - @Override - public JavaType typeFromId(String id) { - return typeFromId(null, id); - } - - @Override - public JavaType typeFromId(DatabindContext context, String id) { - Class clazz = getClassForId(id); - if (clazz == KvCoder.class) { - clazz = KvCoderBase.class; - } - if (clazz == MapCoder.class) { - clazz = MapCoderBase.class; - } - @SuppressWarnings("rawtypes") - TypeVariable[] tvs = clazz.getTypeParameters(); - JavaType[] types = new JavaType[tvs.length]; - for (int lupe = 0; lupe < tvs.length; lupe++) { - types[lupe] = TypeFactory.unknownType(); - } - return _typeFactory.constructSimpleType(clazz, types); - } - - private Class getClassForId(String id) { - try { - if (id.contains(".")) { - return Class.forName(id); - } - - if (id.equals(KIND_STREAM)) { - return IterableCoder.class; - } else if (id.equals(KIND_PAIR)) { - return KvCoder.class; - } - - // Otherwise, see if the ID is the name of a class in - // com.google.cloud.dataflow.sdk.coders. We do this via creating - // the class object so that class loaders have a chance to get - // involved -- and since we need the class object anyway. - return Class.forName(Coder.class.getPackage().getName() + "." + id); - } catch (ClassNotFoundException e) { - throw new RuntimeException("Unable to convert coder ID " + id + " to class", e); - } - } - - @Override - public String idFromValueAndType(Object o, Class clazz) { - return clazz.getName(); - } - - @Override - public String idFromValue(Object o) { - return o.getClass().getName(); - } - - @Override - public JsonTypeInfo.Id getMechanism() { - return JsonTypeInfo.Id.CUSTOM; - } - } - - /** - * The mixin class defining how Coders are handled by the deserialization - * {@link ObjectMapper}. - * - *

              This is done via a mixin so that this resolver is only used - * during deserialization requested by the Dataflow SDK. - */ - @JsonTypeIdResolver(Resolver.class) - @JsonTypeInfo(use = Id.CUSTOM, include = As.PROPERTY, property = PropertyNames.OBJECT_TYPE_NAME) - private static final class Mixin {} - - public Jackson2Module() { - super("DataflowCoders"); - setMixInAnnotation(Coder.class, Mixin.class); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java deleted file mode 100644 index 6f2b89b84d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineContextFactory.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.state.StateContext; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -/** - * Factory that produces {@code Combine.Context} based on different inputs. - */ -public class CombineContextFactory { - - private static final Context NULL_CONTEXT = new Context() { - @Override - public PipelineOptions getPipelineOptions() { - throw new IllegalArgumentException("cannot call getPipelineOptions() in a null context"); - } - - @Override - public T sideInput(PCollectionView view) { - throw new IllegalArgumentException("cannot call sideInput() in a null context"); - } - }; - - /** - * Returns a fake {@code Combine.Context} for tests. - */ - public static Context nullContext() { - return NULL_CONTEXT; - } - - /** - * Returns a {@code Combine.Context} that wraps a {@code DoFn.ProcessContext}. - */ - public static Context createFromProcessContext(final DoFn.ProcessContext c) { - return new Context() { - @Override - public PipelineOptions getPipelineOptions() { - return c.getPipelineOptions(); - } - - @Override - public T sideInput(PCollectionView view) { - return c.sideInput(view); - } - }; - } - - /** - * Returns a {@code Combine.Context} that wraps a {@link StateContext}. - */ - public static Context createFromStateContext(final StateContext c) { - return new Context() { - @Override - public PipelineOptions getPipelineOptions() { - return c.getPipelineOptions(); - } - - @Override - public T sideInput(PCollectionView view) { - return c.sideInput(view); - } - }; - } - - /** - * Returns a {@code Combine.Context} from {@code PipelineOptions}, {@code SideInputReader}, - * and the main input window. - */ - public static Context createFromComponents(final PipelineOptions options, - final SideInputReader sideInputReader, final BoundedWindow mainInputWindow) { - return new Context() { - @Override - public PipelineOptions getPipelineOptions() { - return options; - } - - @Override - public T sideInput(PCollectionView view) { - if (!sideInputReader.contains(view)) { - throw new IllegalArgumentException("calling sideInput() with unknown view"); - } - - BoundedWindow sideInputWindow = - view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(mainInputWindow); - return sideInputReader.get(view, sideInputWindow); - } - }; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java deleted file mode 100644 index 15c6272e21..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CombineFnUtil.java +++ /dev/null @@ -1,164 +0,0 @@ - -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.GlobalCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.state.StateContext; - -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectOutputStream; - -/** - * Static utility methods that create combine function instances. - */ -public class CombineFnUtil { - /** - * Returns the partial application of the {@link KeyedCombineFnWithContext} to a specific - * context to produce a {@link KeyedCombineFn}. - * - *

              The returned {@link KeyedCombineFn} cannot be serialized. - */ - public static KeyedCombineFn - bindContext( - KeyedCombineFnWithContext combineFn, - StateContext stateContext) { - Context context = CombineContextFactory.createFromStateContext(stateContext); - return new NonSerializableBoundedKeyedCombineFn<>(combineFn, context); - } - - /** - * Return a {@link CombineFnWithContext} from the given {@link GlobalCombineFn}. - */ - public static - CombineFnWithContext toFnWithContext( - GlobalCombineFn globalCombineFn) { - if (globalCombineFn instanceof CombineFnWithContext) { - @SuppressWarnings("unchecked") - CombineFnWithContext combineFnWithContext = - (CombineFnWithContext) globalCombineFn; - return combineFnWithContext; - } else { - @SuppressWarnings("unchecked") - final CombineFn combineFn = - (CombineFn) globalCombineFn; - return new CombineFnWithContext() { - @Override - public AccumT createAccumulator(Context c) { - return combineFn.createAccumulator(); - } - @Override - public AccumT addInput(AccumT accumulator, InputT input, Context c) { - return combineFn.addInput(accumulator, input); - } - @Override - public AccumT mergeAccumulators(Iterable accumulators, Context c) { - return combineFn.mergeAccumulators(accumulators); - } - @Override - public OutputT extractOutput(AccumT accumulator, Context c) { - return combineFn.extractOutput(accumulator); - } - @Override - public AccumT compact(AccumT accumulator, Context c) { - return combineFn.compact(accumulator); - } - @Override - public OutputT defaultValue() { - return combineFn.defaultValue(); - } - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder inputCoder) - throws CannotProvideCoderException { - return combineFn.getAccumulatorCoder(registry, inputCoder); - } - @Override - public Coder getDefaultOutputCoder( - CoderRegistry registry, Coder inputCoder) throws CannotProvideCoderException { - return combineFn.getDefaultOutputCoder(registry, inputCoder); - } - @Override - public void populateDisplayData(DisplayData.Builder builder) { - super.populateDisplayData(builder); - combineFn.populateDisplayData(builder); - } - }; - } - } - - private static class NonSerializableBoundedKeyedCombineFn - extends KeyedCombineFn { - private final KeyedCombineFnWithContext combineFn; - private final Context context; - - private NonSerializableBoundedKeyedCombineFn( - KeyedCombineFnWithContext combineFn, - Context context) { - this.combineFn = combineFn; - this.context = context; - } - @Override - public AccumT createAccumulator(K key) { - return combineFn.createAccumulator(key, context); - } - @Override - public AccumT addInput(K key, AccumT accumulator, InputT value) { - return combineFn.addInput(key, accumulator, value, context); - } - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators) { - return combineFn.mergeAccumulators(key, accumulators, context); - } - @Override - public OutputT extractOutput(K key, AccumT accumulator) { - return combineFn.extractOutput(key, accumulator, context); - } - @Override - public AccumT compact(K key, AccumT accumulator) { - return combineFn.compact(key, accumulator, context); - } - @Override - public Coder getAccumulatorCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return combineFn.getAccumulatorCoder(registry, keyCoder, inputCoder); - } - @Override - public Coder getDefaultOutputCoder(CoderRegistry registry, Coder keyCoder, - Coder inputCoder) throws CannotProvideCoderException { - return combineFn.getDefaultOutputCoder(registry, keyCoder, inputCoder); - } - @Override - public void populateDisplayData(DisplayData.Builder builder) { - combineFn.populateDisplayData(builder); - } - - private void writeObject(@SuppressWarnings("unused") ObjectOutputStream out) - throws IOException { - throw new NotSerializableException( - "Cannot serialize the CombineFn resulting from CombineFnUtil.bindContext."); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CounterAggregator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CounterAggregator.java deleted file mode 100644 index 824825f41f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CounterAggregator.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterProvider; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; - -/** - * An implementation of the {@code Aggregator} interface that uses a - * {@link Counter} as the underlying representation. Supports {@link CombineFn}s - * from the {@link Sum}, {@link Min} and {@link Max} classes. - * - * @param the type of input values - * @param the type of accumulator values - * @param the type of output value - */ -public class CounterAggregator implements Aggregator { - - private final Counter counter; - private final CombineFn combiner; - - /** - * Constructs a new aggregator with the given name and aggregation logic - * specified in the CombineFn argument. The underlying counter is - * automatically added into the provided CounterSet. - * - *

              If a counter with the same name already exists, it will be reused, as - * long as it has the same type. - */ - public CounterAggregator(String name, CombineFn combiner, - CounterSet.AddCounterMutator addCounterMutator) { - // Safe contravariant cast - this(constructCounter(name, combiner), addCounterMutator, - (CombineFn) combiner); - } - - private CounterAggregator(Counter counter, - CounterSet.AddCounterMutator addCounterMutator, - CombineFn combiner) { - try { - this.counter = addCounterMutator.addCounter(counter); - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException( - "aggregator's name collides with an existing aggregator " - + "or system-provided counter of an incompatible type"); - } - this.combiner = combiner; - } - - private static Counter constructCounter(String name, - CombineFn combiner) { - if (combiner instanceof CounterProvider) { - @SuppressWarnings("unchecked") - CounterProvider counterProvider = (CounterProvider) combiner; - return counterProvider.getCounter(name); - } else { - throw new IllegalArgumentException("unsupported combiner in Aggregator: " - + combiner.getClass().getName()); - } - } - - @Override - public void addValue(InputT value) { - counter.addValue(value); - } - - @Override - public String getName() { - return counter.getName(); - } - - @Override - public CombineFn getCombineFn() { - return combiner; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CredentialFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CredentialFactory.java deleted file mode 100644 index add8d7ad14..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/CredentialFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.auth.oauth2.Credential; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -/** - * Construct an oauth credential to be used by the SDK and the SDK workers. - */ -public interface CredentialFactory { - Credential getCredential() throws IOException, GeneralSecurityException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Credentials.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Credentials.java deleted file mode 100644 index 207a152f0c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Credentials.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.extensions.java6.auth.oauth2.AbstractPromptReceiver; -import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; -import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; -import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants; -import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; -import com.google.api.client.http.GenericUrl; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.client.util.store.FileDataStoreFactory; -import com.google.cloud.dataflow.sdk.options.GcpOptions; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** - * Provides support for loading credentials. - */ -public class Credentials { - - private static final Logger LOG = LoggerFactory.getLogger(Credentials.class); - - /** - * OAuth 2.0 scopes used by a local worker (not on GCE). - * The scope cloud-platform provides access to all Cloud Platform resources. - * cloud-platform isn't sufficient yet for talking to datastore so we request - * those resources separately. - * - *

              Note that trusted scope relationships don't apply to OAuth tokens, so for - * services we access directly (GCS) as opposed to through the backend - * (BigQuery, GCE), we need to explicitly request that scope. - */ - private static final List SCOPES = Arrays.asList( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/devstorage.full_control", - "https://www.googleapis.com/auth/userinfo.email", - "https://www.googleapis.com/auth/datastore"); - - private static class PromptReceiver extends AbstractPromptReceiver { - @Override - public String getRedirectUri() { - return GoogleOAuthConstants.OOB_REDIRECT_URI; - } - } - - /** - * Initializes OAuth2 credentials. - * - *

              This can use 3 different mechanisms for obtaining a credential: - *

                - *
              1. - * It can fetch the - * - * application default credentials. - *
              2. - *
              3. - * The user can specify a client secrets file and go through the OAuth2 - * webflow. The credential will then be cached in the user's home - * directory for reuse. Provide the property "secrets_file" to use this - * mechanism. - *
              4. - *
              5. - * The user can specify a file containing a service account. - * Provide the properties "service_account_keyfile" and - * "service_account_name" to use this mechanism. - *
              6. - *
              - * The default mechanism is to use the - * - * application default credentials. The other options can be used by providing the - * corresponding properties. - */ - public static Credential getCredential(GcpOptions options) - throws IOException, GeneralSecurityException { - String keyFile = options.getServiceAccountKeyfile(); - String accountName = options.getServiceAccountName(); - - if (keyFile != null && accountName != null) { - try { - return getCredentialFromFile(keyFile, accountName, SCOPES); - } catch (GeneralSecurityException e) { - throw new IOException("Unable to obtain credentials from file", e); - } - } - - if (options.getSecretsFile() != null) { - return getCredentialFromClientSecrets(options, SCOPES); - } - - try { - return GoogleCredential.getApplicationDefault().createScoped(SCOPES); - } catch (IOException e) { - throw new RuntimeException("Unable to get application default credentials. Please see " - + "https://developers.google.com/accounts/docs/application-default-credentials " - + "for details on how to specify credentials. This version of the SDK is " - + "dependent on the gcloud core component version 2015.02.05 or newer to " - + "be able to get credentials from the currently authorized user via gcloud auth.", e); - } - } - - /** - * Loads OAuth2 credential from a local file. - */ - private static Credential getCredentialFromFile( - String keyFile, String accountId, Collection scopes) - throws IOException, GeneralSecurityException { - GoogleCredential credential = new GoogleCredential.Builder() - .setTransport(Transport.getTransport()) - .setJsonFactory(Transport.getJsonFactory()) - .setServiceAccountId(accountId) - .setServiceAccountScopes(scopes) - .setServiceAccountPrivateKeyFromP12File(new File(keyFile)) - .build(); - - LOG.info("Created credential from file {}", keyFile); - return credential; - } - - /** - * Loads OAuth2 credential from client secrets, which may require an - * interactive authorization prompt. - */ - private static Credential getCredentialFromClientSecrets( - GcpOptions options, Collection scopes) - throws IOException, GeneralSecurityException { - String clientSecretsFile = options.getSecretsFile(); - - checkArgument(clientSecretsFile != null); - HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); - - JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); - GoogleClientSecrets clientSecrets; - - try { - clientSecrets = GoogleClientSecrets.load(jsonFactory, - new FileReader(clientSecretsFile)); - } catch (IOException e) { - throw new RuntimeException( - "Could not read the client secrets from file: " + clientSecretsFile, - e); - } - - FileDataStoreFactory dataStoreFactory = - new FileDataStoreFactory(new java.io.File(options.getCredentialDir())); - - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( - httpTransport, jsonFactory, clientSecrets, scopes) - .setDataStoreFactory(dataStoreFactory) - .setTokenServerUrl(new GenericUrl(options.getTokenServerUrl())) - .setAuthorizationServerEncodedUrl(options.getAuthorizationServerEncodedUrl()) - .build(); - - // The credentialId identifies the credential if we're using a persistent - // credential store. - Credential credential = - new AuthorizationCodeInstalledApp(flow, new PromptReceiver()) - .authorize(options.getCredentialId()); - - LOG.info("Got credential from client secret"); - return credential; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidator.java deleted file mode 100644 index c9a663fa0d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidator.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; - -import java.io.IOException; - -/** - * GCP implementation of {@link PathValidator}. Only GCS paths are allowed. - */ -public class DataflowPathValidator implements PathValidator { - - private DataflowPipelineOptions dataflowOptions; - - DataflowPathValidator(DataflowPipelineOptions options) { - this.dataflowOptions = options; - } - - public static DataflowPathValidator fromOptions(PipelineOptions options) { - return new DataflowPathValidator(options.as(DataflowPipelineOptions.class)); - } - - /** - * Validates the the input GCS path is accessible and that the path - * is well formed. - */ - @Override - public String validateInputFilePatternSupported(String filepattern) { - GcsPath gcsPath = getGcsPath(filepattern); - checkArgument( - dataflowOptions.getGcsUtil().isGcsPatternSupported(gcsPath.getObject())); - String returnValue = verifyPath(filepattern); - verifyPathIsAccessible(filepattern, "Could not find file %s"); - return returnValue; - } - - /** - * Validates the the output GCS path is accessible and that the path - * is well formed. - */ - @Override - public String validateOutputFilePrefixSupported(String filePrefix) { - String returnValue = verifyPath(filePrefix); - verifyPathIsAccessible(filePrefix, "Output path does not exist or is not writeable: %s"); - return returnValue; - } - - @Override - public String verifyPath(String path) { - GcsPath gcsPath = getGcsPath(path); - checkArgument(gcsPath.isAbsolute(), - "Must provide absolute paths for Dataflow"); - checkArgument(!gcsPath.getObject().contains("//"), - "Dataflow Service does not allow objects with consecutive slashes"); - return gcsPath.toResourceName(); - } - - private void verifyPathIsAccessible(String path, String errorMessage) { - GcsPath gcsPath = getGcsPath(path); - try { - checkArgument(dataflowOptions.getGcsUtil().bucketExists(gcsPath), - errorMessage, path); - } catch (IOException e) { - throw new RuntimeException( - String.format("Unable to verify that GCS bucket gs://%s exists.", gcsPath.getBucket()), - e); - } - } - - private GcsPath getGcsPath(String path) { - try { - return GcsPath.fromUri(path); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(String.format( - "%s expected a valid 'gs://' path but was given '%s'", - dataflowOptions.getRunner().getSimpleName(), path), e); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java deleted file mode 100644 index 538ab960d9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DataflowReleaseInfo.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.json.GenericJson; -import com.google.api.client.util.Key; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * Utilities for working with the Dataflow distribution. - */ -public final class DataflowReleaseInfo extends GenericJson { - private static final Logger LOG = LoggerFactory.getLogger(DataflowReleaseInfo.class); - - private static final String DATAFLOW_PROPERTIES_PATH = - "/com/google/cloud/dataflow/sdk/sdk.properties"; - - private static class LazyInit { - private static final DataflowReleaseInfo INSTANCE = - new DataflowReleaseInfo(DATAFLOW_PROPERTIES_PATH); - } - - /** - * Returns an instance of DataflowReleaseInfo. - */ - public static DataflowReleaseInfo getReleaseInfo() { - return LazyInit.INSTANCE; - } - - @Key private String name = "Google Cloud Dataflow SDK for Java"; - @Key private String version = "Unknown"; - - /** Provides the SDK name. */ - public String getName() { - return name; - } - - /** Provides the SDK version. */ - public String getVersion() { - return version; - } - - private DataflowReleaseInfo(String resourcePath) { - Properties properties = new Properties(); - - InputStream in = DataflowReleaseInfo.class.getResourceAsStream( - DATAFLOW_PROPERTIES_PATH); - if (in == null) { - LOG.warn("Dataflow properties resource not found: {}", resourcePath); - return; - } - - try { - properties.load(in); - } catch (IOException e) { - LOG.warn("Error loading Dataflow properties resource: ", e); - } - - for (String name : properties.stringPropertyNames()) { - if (name.equals("name")) { - // We don't allow the properties to override the SDK name. - continue; - } - put(name, properties.getProperty(name)); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java deleted file mode 100644 index 6e970535db..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectModeExecutionContext.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.ValueWithMetadata; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.List; -import java.util.Map; - -/** - * {@link ExecutionContext} for use in direct mode. - */ -public class DirectModeExecutionContext - extends BaseExecutionContext { - - private Object key; - private List> output = Lists.newArrayList(); - private Map, List>> sideOutputs = Maps.newHashMap(); - - protected DirectModeExecutionContext() {} - - public static DirectModeExecutionContext create() { - return new DirectModeExecutionContext(); - } - - @Override - protected StepContext createStepContext( - String stepName, String transformName, StateSampler stateSampler) { - return new StepContext(this, stepName, transformName); - } - - public Object getKey() { - return key; - } - - public void setKey(Object newKey) { - // The direct mode runner may reorder elements, so we need to keep - // around the state used for each key. - for (ExecutionContext.StepContext stepContext : getAllStepContexts()) { - ((StepContext) stepContext).switchKey(newKey); - } - key = newKey; - } - - @Override - public void noteOutput(WindowedValue outputElem) { - output.add(ValueWithMetadata.of(outputElem).withKey(getKey())); - } - - @Override - public void noteSideOutput(TupleTag tag, WindowedValue outputElem) { - List> output = sideOutputs.get(tag); - if (output == null) { - output = Lists.newArrayList(); - sideOutputs.put(tag, output); - } - output.add(ValueWithMetadata.of(outputElem).withKey(getKey())); - } - - public List> getOutput(@SuppressWarnings("unused") TupleTag tag) { - @SuppressWarnings({"unchecked", "rawtypes"}) // Cast not expressible without rawtypes - List> typedOutput = (List) output; - return typedOutput; - } - - public List> getSideOutput(TupleTag tag) { - if (sideOutputs.containsKey(tag)) { - @SuppressWarnings({"unchecked", "rawtypes"}) // Cast not expressible without rawtypes - List> typedOutput = (List) sideOutputs.get(tag); - return typedOutput; - } else { - return Lists.newArrayList(); - } - } - - /** - * {@link ExecutionContext.StepContext} used in direct mode. - */ - public static class StepContext extends BaseExecutionContext.StepContext { - - /** A map from each key to the state associated with it. */ - private final Map> stateInternals = Maps.newHashMap(); - private InMemoryStateInternals currentStateInternals = null; - - private StepContext(ExecutionContext executionContext, String stepName, String transformName) { - super(executionContext, stepName, transformName); - switchKey(null); - } - - public void switchKey(Object newKey) { - currentStateInternals = stateInternals.get(newKey); - if (currentStateInternals == null) { - currentStateInternals = InMemoryStateInternals.forKey(newKey); - stateInternals.put(newKey, currentStateInternals); - } - } - - @Override - public StateInternals stateInternals() { - return checkNotNull(currentStateInternals); - } - - @Override - public TimerInternals timerInternals() { - throw new UnsupportedOperationException("Direct mode cannot return timerInternals"); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectSideInputReader.java deleted file mode 100644 index ee8c922897..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DirectSideInputReader.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -/** - * Basic side input reader wrapping a {@link PTuple} of side input iterables. Encapsulates - * conversion according to the {@link PCollectionView} and projection to a particular - * window. - */ -public class DirectSideInputReader implements SideInputReader { - - private PTuple sideInputValues; - - private DirectSideInputReader(PTuple sideInputValues) { - this.sideInputValues = sideInputValues; - } - - public static DirectSideInputReader of(PTuple sideInputValues) { - return new DirectSideInputReader(sideInputValues); - } - - @Override - public boolean contains(PCollectionView view) { - return sideInputValues.has(view.getTagInternal()); - } - - @Override - public boolean isEmpty() { - return sideInputValues.isEmpty(); - } - - @Override - public T get(PCollectionView view, final BoundedWindow window) { - final TupleTag>> tag = view.getTagInternal(); - if (!sideInputValues.has(tag)) { - throw new IllegalArgumentException("calling getSideInput() with unknown view"); - } - - if (view.getWindowingStrategyInternal().getWindowFn() instanceof GlobalWindows) { - return view.fromIterableInternal(sideInputValues.get(tag)); - } else { - return view.fromIterableInternal( - Iterables.filter(sideInputValues.get(tag), - new Predicate>() { - @Override - public boolean apply(WindowedValue element) { - return element.getWindows().contains(window); - } - })); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnInfo.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnInfo.java deleted file mode 100644 index 15a3a471c2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnInfo.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.io.Serializable; - -/** - * Wrapper class holding the necessary information to serialize a DoFn. - * - * @param the type of the (main) input elements of the DoFn - * @param the type of the (main) output elements of the DoFn - */ -public class DoFnInfo implements Serializable { - private final DoFn doFn; - private final WindowingStrategy windowingStrategy; - private final Iterable> sideInputViews; - private final Coder inputCoder; - - public DoFnInfo(DoFn doFn, WindowingStrategy windowingStrategy) { - this.doFn = doFn; - this.windowingStrategy = windowingStrategy; - this.sideInputViews = null; - this.inputCoder = null; - } - - public DoFnInfo(DoFn doFn, WindowingStrategy windowingStrategy, - Iterable> sideInputViews, Coder inputCoder) { - this.doFn = doFn; - this.windowingStrategy = windowingStrategy; - this.sideInputViews = sideInputViews; - this.inputCoder = inputCoder; - } - - public DoFn getDoFn() { - return doFn; - } - - public WindowingStrategy getWindowingStrategy() { - return windowingStrategy; - } - - public Iterable> getSideInputViews() { - return sideInputViews; - } - - public Coder getInputCoder() { - return inputCoder; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java deleted file mode 100644 index e0ce0ae097..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunner.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.ProcessContext; -import com.google.cloud.dataflow.sdk.values.KV; - -/** - * An wrapper interface that represents the execution of a {@link DoFn}. - */ -public interface DoFnRunner { - /** - * Prepares and calls {@link DoFn#startBundle}. - */ - void startBundle(); - - /** - * Calls {@link DoFn#processElement} with a {@link ProcessContext} containing the current element. - */ - void processElement(WindowedValue elem); - - /** - * Calls {@link DoFn#finishBundle} and performs additional tasks, such as - * flushing in-memory states. - */ - void finishBundle(); - - /** - * An internal interface for signaling that a {@link DoFn} requires late data dropping. - */ - public interface ReduceFnExecutor { - /** - * Gets this object as a {@link DoFn}. - * - *

              Most implementors of this interface are expected to be {@link DoFn} instances, and will - * return themselves. - */ - DoFn, KV> asDoFn(); - - /** - * Returns an aggregator that tracks elements that are dropped due to being late. - */ - Aggregator getDroppedDueToLatenessAggregator(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java deleted file mode 100644 index 0c2465161e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunnerBase.java +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import org.joda.time.Instant; -import org.joda.time.format.PeriodFormat; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * A base implementation of {@link DoFnRunner}. - * - *

              Sub-classes should override {@link #invokeProcessElement}. - */ -public abstract class DoFnRunnerBase implements DoFnRunner { - - /** The DoFn being run. */ - public final DoFn fn; - - /** The context used for running the DoFn. */ - public final DoFnContext context; - - protected DoFnRunnerBase( - PipelineOptions options, - DoFn fn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - this.fn = fn; - this.context = new DoFnContext<>( - options, - fn, - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - windowingStrategy == null ? null : windowingStrategy.getWindowFn()); - } - - /** - * An implementation of {@code OutputManager} using simple lists, for testing and in-memory - * contexts such as the {@link DirectPipelineRunner}. - */ - public static class ListOutputManager implements OutputManager { - - private Map, List>> outputLists = Maps.newHashMap(); - - @Override - public void output(TupleTag tag, WindowedValue output) { - @SuppressWarnings({"rawtypes", "unchecked"}) - List> outputList = (List) outputLists.get(tag); - - if (outputList == null) { - outputList = Lists.newArrayList(); - @SuppressWarnings({"rawtypes", "unchecked"}) - List> untypedList = (List) outputList; - outputLists.put(tag, untypedList); - } - - outputList.add(output); - } - - public List> getOutput(TupleTag tag) { - // Safe cast by design, inexpressible in Java without rawtypes - @SuppressWarnings({"rawtypes", "unchecked"}) - List> outputList = (List) outputLists.get(tag); - return (outputList != null) ? outputList : Collections.>emptyList(); - } - } - - @Override - public void startBundle() { - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.startBundle(context); - } catch (Throwable t) { - // Exception in user code. - throw wrapUserCodeException(t); - } - } - - @Override - public void processElement(WindowedValue elem) { - if (elem.getWindows().size() <= 1 - || (!RequiresWindowAccess.class.isAssignableFrom(fn.getClass()) - && context.sideInputReader.isEmpty())) { - invokeProcessElement(elem); - } else { - // We could modify the windowed value (and the processContext) to - // avoid repeated allocations, but this is more straightforward. - for (WindowedValue windowedValue : elem.explodeWindows()) { - invokeProcessElement(windowedValue); - } - } - } - - /** - * Invokes {@link DoFn#processElement} after certain pre-processings has been done in - * {@link DoFnRunnerBase#processElement}. - */ - protected abstract void invokeProcessElement(WindowedValue elem); - - @Override - public void finishBundle() { - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.finishBundle(context); - } catch (Throwable t) { - // Exception in user code. - throw wrapUserCodeException(t); - } - } - - /** - * A concrete implementation of {@code DoFn.Context} used for running a {@link DoFn}. - * - * @param the type of the DoFn's (main) input elements - * @param the type of the DoFn's (main) output elements - */ - private static class DoFnContext - extends DoFn.Context { - private static final int MAX_SIDE_OUTPUTS = 1000; - - final PipelineOptions options; - final DoFn fn; - final SideInputReader sideInputReader; - final OutputManager outputManager; - final TupleTag mainOutputTag; - final StepContext stepContext; - final CounterSet.AddCounterMutator addCounterMutator; - final WindowFn windowFn; - - /** - * The set of known output tags, some of which may be undeclared, so we can throw an - * exception when it exceeds {@link #MAX_SIDE_OUTPUTS}. - */ - private Set> outputTags; - - public DoFnContext(PipelineOptions options, - DoFn fn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowFn windowFn) { - fn.super(); - this.options = options; - this.fn = fn; - this.sideInputReader = sideInputReader; - this.outputManager = outputManager; - this.mainOutputTag = mainOutputTag; - this.outputTags = Sets.newHashSet(); - - outputTags.add(mainOutputTag); - for (TupleTag sideOutputTag : sideOutputTags) { - outputTags.add(sideOutputTag); - } - - this.stepContext = stepContext; - this.addCounterMutator = addCounterMutator; - this.windowFn = windowFn; - super.setupDelegateAggregators(); - } - - ////////////////////////////////////////////////////////////////////////////// - - @Override - public PipelineOptions getPipelineOptions() { - return options; - } - - WindowedValue makeWindowedValue( - T output, Instant timestamp, Collection windows, PaneInfo pane) { - final Instant inputTimestamp = timestamp; - - if (timestamp == null) { - timestamp = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - if (windows == null) { - try { - // The windowFn can never succeed at accessing the element, so its type does not - // matter here - @SuppressWarnings("unchecked") - WindowFn objectWindowFn = (WindowFn) windowFn; - windows = objectWindowFn.assignWindows(objectWindowFn.new AssignContext() { - @Override - public Object element() { - throw new UnsupportedOperationException( - "WindowFn attempted to access input element when none was available"); - } - - @Override - public Instant timestamp() { - if (inputTimestamp == null) { - throw new UnsupportedOperationException( - "WindowFn attempted to access input timestamp when none was available"); - } - return inputTimestamp; - } - - @Override - public Collection windows() { - throw new UnsupportedOperationException( - "WindowFn attempted to access input windows when none were available"); - } - }); - } catch (Exception e) { - throw UserCodeException.wrap(e); - } - } - - return WindowedValue.of(output, timestamp, windows, pane); - } - - public T sideInput(PCollectionView view, BoundedWindow mainInputWindow) { - if (!sideInputReader.contains(view)) { - throw new IllegalArgumentException("calling sideInput() with unknown view"); - } - BoundedWindow sideInputWindow = - view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(mainInputWindow); - return sideInputReader.get(view, sideInputWindow); - } - - void outputWindowedValue( - OutputT output, - Instant timestamp, - Collection windows, - PaneInfo pane) { - outputWindowedValue(makeWindowedValue(output, timestamp, windows, pane)); - } - - void outputWindowedValue(WindowedValue windowedElem) { - outputManager.output(mainOutputTag, windowedElem); - if (stepContext != null) { - stepContext.noteOutput(windowedElem); - } - } - - protected void sideOutputWindowedValue(TupleTag tag, - T output, - Instant timestamp, - Collection windows, - PaneInfo pane) { - sideOutputWindowedValue(tag, makeWindowedValue(output, timestamp, windows, pane)); - } - - protected void sideOutputWindowedValue(TupleTag tag, WindowedValue windowedElem) { - if (!outputTags.contains(tag)) { - // This tag wasn't declared nor was it seen before during this execution. - // Thus, this must be a new, undeclared and unconsumed output. - // To prevent likely user errors, enforce the limit on the number of side - // outputs. - if (outputTags.size() >= MAX_SIDE_OUTPUTS) { - throw new IllegalArgumentException( - "the number of side outputs has exceeded a limit of " + MAX_SIDE_OUTPUTS); - } - outputTags.add(tag); - } - - outputManager.output(tag, windowedElem); - if (stepContext != null) { - stepContext.noteSideOutput(tag, windowedElem); - } - } - - // Following implementations of output, outputWithTimestamp, and sideOutput - // are only accessible in DoFn.startBundle and DoFn.finishBundle, and will be shadowed by - // ProcessContext's versions in DoFn.processElement. - @Override - public void output(OutputT output) { - outputWindowedValue(output, null, null, PaneInfo.NO_FIRING); - } - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - outputWindowedValue(output, timestamp, null, PaneInfo.NO_FIRING); - } - - @Override - public void sideOutput(TupleTag tag, T output) { - checkNotNull(tag, "TupleTag passed to sideOutput cannot be null"); - sideOutputWindowedValue(tag, output, null, null, PaneInfo.NO_FIRING); - } - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - checkNotNull(tag, "TupleTag passed to sideOutputWithTimestamp cannot be null"); - sideOutputWindowedValue(tag, output, timestamp, null, PaneInfo.NO_FIRING); - } - - private String generateInternalAggregatorName(String userName) { - boolean system = fn.getClass().isAnnotationPresent(SystemDoFnInternal.class); - return (system ? "" : "user-") + stepContext.getStepName() + "-" + userName; - } - - @Override - protected Aggregator createAggregatorInternal( - String name, CombineFn combiner) { - checkNotNull(combiner, - "Combiner passed to createAggregator cannot be null"); - return new CounterAggregator<>(generateInternalAggregatorName(name), - combiner, addCounterMutator); - } - } - - /** - * Returns a new {@code DoFn.ProcessContext} for the given element. - */ - protected DoFn.ProcessContext createProcessContext(WindowedValue elem) { - return new DoFnProcessContext(fn, context, elem); - } - - protected RuntimeException wrapUserCodeException(Throwable t) { - throw UserCodeException.wrapIf(!isSystemDoFn(), t); - } - - private boolean isSystemDoFn() { - return fn.getClass().isAnnotationPresent(SystemDoFnInternal.class); - } - - /** - * A concrete implementation of {@code DoFn.ProcessContext} used for - * running a {@link DoFn} over a single element. - * - * @param the type of the DoFn's (main) input elements - * @param the type of the DoFn's (main) output elements - */ - static class DoFnProcessContext - extends DoFn.ProcessContext { - - - final DoFn fn; - final DoFnContext context; - final WindowedValue windowedValue; - - public DoFnProcessContext(DoFn fn, - DoFnContext context, - WindowedValue windowedValue) { - fn.super(); - this.fn = fn; - this.context = context; - this.windowedValue = windowedValue; - } - - @Override - public PipelineOptions getPipelineOptions() { - return context.getPipelineOptions(); - } - - @Override - public InputT element() { - return windowedValue.getValue(); - } - - @Override - public T sideInput(PCollectionView view) { - checkNotNull(view, "View passed to sideInput cannot be null"); - Iterator windowIter = windows().iterator(); - BoundedWindow window; - if (!windowIter.hasNext()) { - if (context.windowFn instanceof GlobalWindows) { - // TODO: Remove this once GroupByKeyOnly no longer outputs elements - // without windows - window = GlobalWindow.INSTANCE; - } else { - throw new IllegalStateException( - "sideInput called when main input element is not in any windows"); - } - } else { - window = windowIter.next(); - if (windowIter.hasNext()) { - throw new IllegalStateException( - "sideInput called when main input element is in multiple windows"); - } - } - return context.sideInput(view, window); - } - - @Override - public BoundedWindow window() { - if (!(fn instanceof RequiresWindowAccess)) { - throw new UnsupportedOperationException( - "window() is only available in the context of a DoFn marked as RequiresWindowAccess."); - } - return Iterables.getOnlyElement(windows()); - } - - @Override - public PaneInfo pane() { - return windowedValue.getPane(); - } - - @Override - public void output(OutputT output) { - context.outputWindowedValue(windowedValue.withValue(output)); - } - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - checkTimestamp(timestamp); - context.outputWindowedValue(output, timestamp, - windowedValue.getWindows(), windowedValue.getPane()); - } - - void outputWindowedValue( - OutputT output, - Instant timestamp, - Collection windows, - PaneInfo pane) { - context.outputWindowedValue(output, timestamp, windows, pane); - } - - @Override - public void sideOutput(TupleTag tag, T output) { - checkNotNull(tag, "Tag passed to sideOutput cannot be null"); - context.sideOutputWindowedValue(tag, windowedValue.withValue(output)); - } - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - checkNotNull(tag, "Tag passed to sideOutputWithTimestamp cannot be null"); - checkTimestamp(timestamp); - context.sideOutputWindowedValue( - tag, output, timestamp, windowedValue.getWindows(), windowedValue.getPane()); - } - - @Override - public Instant timestamp() { - return windowedValue.getTimestamp(); - } - - public Collection windows() { - return windowedValue.getWindows(); - } - - private void checkTimestamp(Instant timestamp) { - if (timestamp.isBefore(windowedValue.getTimestamp().minus(fn.getAllowedTimestampSkew()))) { - throw new IllegalArgumentException(String.format( - "Cannot output with timestamp %s. Output timestamps must be no earlier than the " - + "timestamp of the current input (%s) minus the allowed skew (%s). See the " - + "DoFn#getAllowedTimestampSkew() Javadoc for details on changing the allowed skew.", - timestamp, windowedValue.getTimestamp(), - PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod()))); - } - } - - @Override - public WindowingInternals windowingInternals() { - return new WindowingInternals() { - @Override - public void outputWindowedValue(OutputT output, Instant timestamp, - Collection windows, PaneInfo pane) { - context.outputWindowedValue(output, timestamp, windows, pane); - } - - @Override - public Collection windows() { - return windowedValue.getWindows(); - } - - @Override - public PaneInfo pane() { - return windowedValue.getPane(); - } - - @Override - public TimerInternals timerInternals() { - return context.stepContext.timerInternals(); - } - - @Override - public void writePCollectionViewData( - TupleTag tag, - Iterable> data, - Coder elemCoder) throws IOException { - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) context.windowFn.windowCoder(); - - context.stepContext.writePCollectionViewData( - tag, data, IterableCoder.of(WindowedValue.getFullCoder(elemCoder, windowCoder)), - window(), windowCoder); - } - - @Override - public StateInternals stateInternals() { - return context.stepContext.stateInternals(); - } - - @Override - public T sideInput(PCollectionView view, BoundedWindow mainInputWindow) { - return context.sideInput(view, mainInputWindow); - } - }; - } - - @Override - protected Aggregator - createAggregatorInternal( - String name, CombineFn combiner) { - return context.createAggregatorInternal(name, combiner); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java deleted file mode 100644 index 257a7a6a42..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.DoFnRunner.ReduceFnExecutor; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.util.List; - -/** - * Static utility methods that provide {@link DoFnRunner} implementations. - */ -public class DoFnRunners { - /** - * Information about how to create output receivers and output to them. - */ - public interface OutputManager { - /** - * Outputs a single element to the receiver indicated by the given {@link TupleTag}. - */ - void output(TupleTag tag, WindowedValue output); - } - - /** - * Returns a basic implementation of {@link DoFnRunner} that works for most {@link DoFn DoFns}. - * - *

              It invokes {@link DoFn#processElement} for each input. - */ - public static DoFnRunner simpleRunner( - PipelineOptions options, - DoFn fn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - return new SimpleDoFnRunner<>( - options, - fn, - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - windowingStrategy); - } - - /** - * Returns an implementation of {@link DoFnRunner} that handles late data dropping. - * - *

              It drops elements from expired windows before they reach the underlying {@link DoFn}. - */ - public static - DoFnRunner, KV> lateDataDroppingRunner( - PipelineOptions options, - ReduceFnExecutor reduceFnExecutor, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag> mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - CounterSet.AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - DoFnRunner, KV> simpleDoFnRunner = - simpleRunner( - options, - reduceFnExecutor.asDoFn(), - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - windowingStrategy); - return new LateDataDroppingDoFnRunner<>( - simpleDoFnRunner, - windowingStrategy, - stepContext.timerInternals(), - reduceFnExecutor.getDroppedDueToLatenessAggregator()); - } - - public static DoFnRunner createDefault( - PipelineOptions options, - DoFn doFn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, - List> sideOutputTags, - StepContext stepContext, - AddCounterMutator addCounterMutator, - WindowingStrategy windowingStrategy) { - if (doFn instanceof ReduceFnExecutor) { - @SuppressWarnings("rawtypes") - ReduceFnExecutor fn = (ReduceFnExecutor) doFn; - return lateDataDroppingRunner( - options, - fn, - sideInputReader, - outputManager, - (TupleTag) mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - (WindowingStrategy) windowingStrategy); - } - return simpleRunner( - options, - doFn, - sideInputReader, - outputManager, - mainOutputTag, - sideOutputTags, - stepContext, - addCounterMutator, - windowingStrategy); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java deleted file mode 100644 index 1a85fc68a7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutableTrigger.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * A wrapper around a trigger used during execution. While an actual trigger may appear multiple - * times (both in the same trigger expression and in other trigger expressions), the - * {@code ExecutableTrigger} wrapped around them forms a tree (only one occurrence). - * - * @param {@link BoundedWindow} subclass used to represent the windows used. - */ -public class ExecutableTrigger implements Serializable { - - /** Store the index assigned to this trigger. */ - private final int triggerIndex; - private final int firstIndexAfterSubtree; - private final List> subTriggers = new ArrayList<>(); - private final Trigger trigger; - - public static ExecutableTrigger create(Trigger trigger) { - return create(trigger, 0); - } - - private static ExecutableTrigger create( - Trigger trigger, int nextUnusedIndex) { - if (trigger instanceof OnceTrigger) { - return new ExecutableOnceTrigger((OnceTrigger) trigger, nextUnusedIndex); - } else { - return new ExecutableTrigger(trigger, nextUnusedIndex); - } - } - - public static ExecutableTrigger createForOnceTrigger( - OnceTrigger trigger, int nextUnusedIndex) { - return new ExecutableOnceTrigger(trigger, nextUnusedIndex); - } - - private ExecutableTrigger(Trigger trigger, int nextUnusedIndex) { - this.trigger = checkNotNull(trigger, "trigger must not be null"); - this.triggerIndex = nextUnusedIndex++; - - if (trigger.subTriggers() != null) { - for (Trigger subTrigger : trigger.subTriggers()) { - ExecutableTrigger subExecutable = create(subTrigger, nextUnusedIndex); - subTriggers.add(subExecutable); - nextUnusedIndex = subExecutable.firstIndexAfterSubtree; - } - } - firstIndexAfterSubtree = nextUnusedIndex; - } - - public List> subTriggers() { - return subTriggers; - } - - @Override - public String toString() { - return trigger.toString(); - } - - /** - * Return the underlying trigger specification corresponding to this {@code ExecutableTrigger}. - */ - public Trigger getSpec() { - return trigger; - } - - public int getTriggerIndex() { - return triggerIndex; - } - - public final int getFirstIndexAfterSubtree() { - return firstIndexAfterSubtree; - } - - public boolean isCompatible(ExecutableTrigger other) { - return trigger.isCompatible(other.trigger); - } - - public ExecutableTrigger getSubTriggerContaining(int index) { - checkNotNull(subTriggers); - checkState(index > triggerIndex && index < firstIndexAfterSubtree, - "Cannot find sub-trigger containing index not in this tree."); - ExecutableTrigger previous = null; - for (ExecutableTrigger subTrigger : subTriggers) { - if (index < subTrigger.triggerIndex) { - return previous; - } - previous = subTrigger; - } - return previous; - } - - /** - * Invoke the {@link Trigger#onElement} method for this trigger, ensuring that the bits are - * properly updated if the trigger finishes. - */ - public void invokeOnElement(Trigger.OnElementContext c) throws Exception { - trigger.onElement(c.forTrigger(this)); - } - - /** - * Invoke the {@link Trigger#onMerge} method for this trigger, ensuring that the bits are properly - * updated. - */ - public void invokeOnMerge(Trigger.OnMergeContext c) throws Exception { - Trigger.OnMergeContext subContext = c.forTrigger(this); - trigger.onMerge(subContext); - } - - public boolean invokeShouldFire(Trigger.TriggerContext c) throws Exception { - return trigger.shouldFire(c.forTrigger(this)); - } - - public void invokeOnFire(Trigger.TriggerContext c) throws Exception { - trigger.onFire(c.forTrigger(this)); - } - - /** - * Invoke clear for the current this trigger. - */ - public void invokeClear(Trigger.TriggerContext c) throws Exception { - trigger.clear(c.forTrigger(this)); - } - - /** - * {@link ExecutableTrigger} that enforces the fact that the trigger should always FIRE_AND_FINISH - * and never just FIRE. - */ - private static class ExecutableOnceTrigger extends ExecutableTrigger { - - public ExecutableOnceTrigger(OnceTrigger trigger, int nextUnusedIndex) { - super(trigger, nextUnusedIndex); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java deleted file mode 100644 index cff5b95cf9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExecutionContext.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.io.IOException; -import java.util.Collection; - -/** - * Context for the current execution. This is guaranteed to exist during processing, - * but does not necessarily persist between different batches of work. - */ -public interface ExecutionContext { - /** - * Returns the {@link StepContext} associated with the given step. - */ - StepContext getOrCreateStepContext( - String stepName, String transformName, StateSampler stateSampler); - - /** - * Returns a collection view of all of the {@link StepContext}s. - */ - Collection getAllStepContexts(); - - /** - * Hook for subclasses to implement that will be called whenever - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#output} - * is called. - */ - void noteOutput(WindowedValue output); - - /** - * Hook for subclasses to implement that will be called whenever - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#sideOutput} - * is called. - */ - void noteSideOutput(TupleTag tag, WindowedValue output); - - /** - * Per-step, per-key context used for retrieving state. - */ - public interface StepContext { - - /** - * The name of the step. - */ - String getStepName(); - - /** - * The name of the transform for the step. - */ - String getTransformName(); - - /** - * Hook for subclasses to implement that will be called whenever - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#output} - * is called. - */ - void noteOutput(WindowedValue output); - - /** - * Hook for subclasses to implement that will be called whenever - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#sideOutput} - * is called. - */ - void noteSideOutput(TupleTag tag, WindowedValue output); - - /** - * Writes the given {@code PCollectionView} data to a globally accessible location. - */ - void writePCollectionViewData( - TupleTag tag, - Iterable> data, - Coder>> dataCoder, - W window, - Coder windowCoder) - throws IOException; - - StateInternals stateInternals(); - - TimerInternals timerInternals(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStream.java deleted file mode 100644 index dff5fd17a3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStream.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -/** - * {@link ByteArrayInputStream} that allows accessing the entire internal buffer without copying. - */ -public class ExposedByteArrayInputStream extends ByteArrayInputStream{ - - public ExposedByteArrayInputStream(byte[] buf) { - super(buf); - } - - /** Read all remaining bytes. - * @throws IOException */ - public byte[] readAll() throws IOException { - if (pos == 0 && count == buf.length) { - pos = count; - return buf; - } - byte[] ret = new byte[count - pos]; - super.read(ret); - return ret; - } - - @Override - public void close() { - try { - super.close(); - } catch (IOException exn) { - throw new RuntimeException("Unexpected IOException closing ByteArrayInputStream", exn); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java deleted file mode 100644 index 8bb931ae21..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStream.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * {@link ByteArrayOutputStream} special cased to treat writes of a single byte-array specially. - * When calling {@link #toByteArray()} after writing only one {@code byte[]} using - * {@link #writeAndOwn(byte[])}, it will return that array directly. - */ -public class ExposedByteArrayOutputStream extends ByteArrayOutputStream { - - private byte[] swappedBuffer; - - /** - * If true, this stream doesn't allow direct access to the passed in byte-array. It behaves just - * like a normal {@link ByteArrayOutputStream}. - * - *

              It is set to true after any write operations other than the first call to - * {@link #writeAndOwn(byte[])}. - */ - private boolean isFallback = false; - - /** - * Fall back to the behavior of a normal {@link ByteArrayOutputStream}. - */ - private void fallback() { - isFallback = true; - if (swappedBuffer != null) { - // swappedBuffer != null means buf is actually provided by the caller of writeAndOwn(), - // while swappedBuffer is the original buffer. - // Recover the buffer and copy the bytes from buf. - byte[] tempBuffer = buf; - count = 0; - buf = swappedBuffer; - super.write(tempBuffer, 0, tempBuffer.length); - swappedBuffer = null; - } - } - - /** - * Write {@code b} to the stream and take the ownership of {@code b}. - * If the stream is empty, {@code b} itself will be used as the content of the stream and - * no content copy will be involved. - * - *

              Note: After passing any byte array to this method, it must not be modified again. - * - * @throws IOException - */ - public void writeAndOwn(byte[] b) throws IOException { - if (b.length == 0) { - return; - } - if (count == 0) { - // Optimized first-time whole write. - // The original buffer will be swapped to swappedBuffer, while the input b is used as buf. - swappedBuffer = buf; - buf = b; - count = b.length; - } else { - fallback(); - super.write(b); - } - } - - @Override - public void write(byte[] b, int off, int len) { - fallback(); - super.write(b, off, len); - } - - @Override - public void write(int b) { - fallback(); - super.write(b); - } - - @Override - public byte[] toByteArray() { - // Note: count == buf.length is not a correct criteria to "return buf;", because the internal - // buf may be reused after reset(). - if (!isFallback && count > 0) { - return buf; - } else { - return super.toByteArray(); - } - } - - @Override - public void reset() { - if (count == 0) { - return; - } - count = 0; - if (isFallback) { - isFallback = false; - } else { - buf = swappedBuffer; - swappedBuffer = null; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java deleted file mode 100644 index 443c5e240f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactory.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.PathMatcher; -import java.nio.file.Paths; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.regex.Matcher; - -/** - * Implements IOChannelFactory for local files. - */ -public class FileIOChannelFactory implements IOChannelFactory { - private static final Logger LOG = LoggerFactory.getLogger(FileIOChannelFactory.class); - - // This implementation only allows for wildcards in the file name. - // The directory portion must exist as-is. - @Override - public Collection match(String spec) throws IOException { - File file = new File(spec); - - File parent = file.getAbsoluteFile().getParentFile(); - if (!parent.exists()) { - throw new IOException("Unable to find parent directory of " + spec); - } - - // Method getAbsolutePath() on Windows platform may return something like - // "c:\temp\file.txt". FileSystem.getPathMatcher() call below will treat - // '\' (backslash) as an escape character, instead of a directory - // separator. Replacing backslash with double-backslash solves the problem. - // We perform the replacement on all platforms, even those that allow - // backslash as a part of the filename, because Globs.toRegexPattern will - // eat one backslash. - String pathToMatch = file.getAbsolutePath().replaceAll(Matcher.quoteReplacement("\\"), - Matcher.quoteReplacement("\\\\")); - - final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch); - - Iterable files = com.google.common.io.Files.fileTreeTraverser().preOrderTraversal(parent); - Iterable matchedFiles = Iterables.filter(files, - Predicates.and( - com.google.common.io.Files.isFile(), - new Predicate() { - @Override - public boolean apply(File input) { - return matcher.matches(input.toPath()); - } - })); - - List result = new LinkedList<>(); - for (File match : matchedFiles) { - result.add(match.getPath()); - } - - return result; - } - - @Override - public ReadableByteChannel open(String spec) throws IOException { - LOG.debug("opening file {}", spec); - @SuppressWarnings("resource") // The caller is responsible for closing the channel. - FileInputStream inputStream = new FileInputStream(spec); - // Use this method for creating the channel (rather than new FileChannel) so that we get - // regular FileNotFoundException. Closing the underyling channel will close the inputStream. - return inputStream.getChannel(); - } - - @Override - public WritableByteChannel create(String spec, String mimeType) - throws IOException { - LOG.debug("creating file {}", spec); - File file = new File(spec); - if (file.getAbsoluteFile().getParentFile() != null - && !file.getAbsoluteFile().getParentFile().exists() - && !file.getAbsoluteFile().getParentFile().mkdirs() - && !file.getAbsoluteFile().getParentFile().exists()) { - throw new IOException("Unable to create parent directories for '" + spec + "'"); - } - return Channels.newChannel( - new BufferedOutputStream(new FileOutputStream(file))); - } - - @Override - public long getSizeBytes(String spec) throws IOException { - try { - return Files.size(FileSystems.getDefault().getPath(spec)); - } catch (NoSuchFileException e) { - throw new FileNotFoundException(e.getReason()); - } - } - - @Override - public boolean isReadSeekEfficient(String spec) throws IOException { - return true; - } - - @Override - public String resolve(String path, String other) throws IOException { - return Paths.get(path).resolve(other).toString(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java deleted file mode 100644 index 00d1b6a486..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggers.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * A mutable set which tracks whether any particular {@link ExecutableTrigger} is - * finished. - */ -public interface FinishedTriggers { - /** - * Returns {@code true} if the trigger is finished. - */ - boolean isFinished(ExecutableTrigger trigger); - - /** - * Sets the fact that the trigger is finished. - */ - void setFinished(ExecutableTrigger trigger, boolean value); - - /** - * Sets the trigger and all of its subtriggers to unfinished. - */ - void clearRecursively(ExecutableTrigger trigger); - - /** - * Create an independent copy of this mutable {@link FinishedTriggers}. - */ - FinishedTriggers copy(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java deleted file mode 100644 index 09f7af7a95..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSet.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.util.BitSet; - -/** - * A {@link FinishedTriggers} implementation based on an underlying {@link BitSet}. - */ -public class FinishedTriggersBitSet implements FinishedTriggers { - - private final BitSet bitSet; - - private FinishedTriggersBitSet(BitSet bitSet) { - this.bitSet = bitSet; - } - - public static FinishedTriggersBitSet emptyWithCapacity(int capacity) { - return new FinishedTriggersBitSet(new BitSet(capacity)); - } - - public static FinishedTriggersBitSet fromBitSet(BitSet bitSet) { - return new FinishedTriggersBitSet(bitSet); - } - - /** - * Returns the underlying {@link BitSet} for this {@link FinishedTriggersBitSet}. - */ - public BitSet getBitSet() { - return bitSet; - } - - @Override - public boolean isFinished(ExecutableTrigger trigger) { - return bitSet.get(trigger.getTriggerIndex()); - } - - @Override - public void setFinished(ExecutableTrigger trigger, boolean value) { - bitSet.set(trigger.getTriggerIndex(), value); - } - - @Override - public void clearRecursively(ExecutableTrigger trigger) { - bitSet.clear(trigger.getTriggerIndex(), trigger.getFirstIndexAfterSubtree()); - } - - @Override - public FinishedTriggersBitSet copy() { - return new FinishedTriggersBitSet((BitSet) bitSet.clone()); - } -} - - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java deleted file mode 100644 index 6da673d28c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSet.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.common.collect.Sets; - -import java.util.Set; - -/** - * An implementation of {@link FinishedTriggers} atop a user-provided mutable {@link Set}. - */ -public class FinishedTriggersSet implements FinishedTriggers { - - private final Set> finishedTriggers; - - private FinishedTriggersSet(Set> finishedTriggers) { - this.finishedTriggers = finishedTriggers; - } - - public static FinishedTriggersSet fromSet(Set> finishedTriggers) { - return new FinishedTriggersSet(finishedTriggers); - } - - /** - * Returns a mutable {@link Set} of the underlying triggers that are finished. - */ - public Set> getFinishedTriggers() { - return finishedTriggers; - } - - @Override - public boolean isFinished(ExecutableTrigger trigger) { - return finishedTriggers.contains(trigger); - } - - @Override - public void setFinished(ExecutableTrigger trigger, boolean value) { - if (value) { - finishedTriggers.add(trigger); - } else { - finishedTriggers.remove(trigger); - } - } - - @Override - public void clearRecursively(ExecutableTrigger trigger) { - finishedTriggers.remove(trigger); - for (ExecutableTrigger subTrigger : trigger.subTriggers()) { - clearRecursively(subTrigger); - } - } - - @Override - public FinishedTriggersSet copy() { - return fromSet(Sets.newHashSet(finishedTriggers)); - } - -} - - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java deleted file mode 100644 index cae3e6a3da..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/FluentBackoff.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.util.BackOff; -import com.google.common.base.MoreObjects; -import org.joda.time.Duration; - -/** - * A fluent builder for {@link BackOff} objects that allows customization of the retry algorithm. - * - * @see #DEFAULT for the default configuration parameters. - */ -public final class FluentBackoff { - - private static final double DEFAULT_EXPONENT = 1.5; - private static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5; - private static final Duration DEFAULT_MIN_BACKOFF = Duration.standardSeconds(1); - private static final Duration DEFAULT_MAX_BACKOFF = Duration.standardDays(1000); - private static final int DEFAULT_MAX_RETRIES = Integer.MAX_VALUE; - private static final Duration DEFAULT_MAX_CUM_BACKOFF = Duration.standardDays(1000); - - private final double exponent; - private final Duration initialBackoff; - private final Duration maxBackoff; - private final Duration maxCumulativeBackoff; - private final int maxRetries; - - /** - * By default the {@link BackOff} created by this builder will use exponential backoff (base - * exponent 1.5) with an initial backoff of 1 second. These parameters can be overridden with - * {@link #withExponent(double)} and {@link #withInitialBackoff(Duration)}, - * respectively, and the maximum backoff after exponential increase can be capped using {@link - * FluentBackoff#withMaxBackoff(Duration)}. - * - *

              The default {@link BackOff} does not limit the number of retries. To limit the backoff, the - * maximum total number of retries can be set using {@link #withMaxRetries(int)}. The - * total time spent in backoff can be time-bounded as well by configuring {@link - * #withMaxCumulativeBackoff(Duration)}. If either of these limits are reached, calls - * to {@link BackOff#nextBackOffMillis()} will return {@link BackOff#STOP} to signal that no more - * retries should continue. - */ - public static final FluentBackoff DEFAULT = new FluentBackoff( - DEFAULT_EXPONENT, - DEFAULT_MIN_BACKOFF, DEFAULT_MAX_BACKOFF, DEFAULT_MAX_CUM_BACKOFF, - DEFAULT_MAX_RETRIES); - - /** - * Instantiates a {@link BackOff} that will obey the current configuration. - * - * @see FluentBackoff - */ - public BackOff backoff() { - return new BackoffImpl(this); - } - - /** - * Returns a copy of this {@link FluentBackoff} that instead uses the specified exponent to - * control the exponential growth of delay. - * - *

              Does not modify this object. - * - * @see FluentBackoff - */ - public FluentBackoff withExponent(double exponent) { - checkArgument(exponent > 0, "exponent %s must be greater than 0", exponent); - return new FluentBackoff( - exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); - } - - /** - * Returns a copy of this {@link FluentBackoff} that instead uses the specified initial backoff - * duration. - * - *

              Does not modify this object. - * - * @see FluentBackoff - */ - public FluentBackoff withInitialBackoff(Duration initialBackoff) { - checkArgument( - initialBackoff.isLongerThan(Duration.ZERO), - "initialBackoff %s must be at least 1 millisecond", - initialBackoff); - return new FluentBackoff( - exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); - } - - /** - * Returns a copy of this {@link FluentBackoff} that limits the maximum backoff of an individual - * attempt to the specified duration. - * - *

              Does not modify this object. - * - * @see FluentBackoff - */ - public FluentBackoff withMaxBackoff(Duration maxBackoff) { - checkArgument( - maxBackoff.getMillis() > 0, - "maxBackoff %s must be at least 1 millisecond", - maxBackoff); - return new FluentBackoff( - exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); - } - - /** - * Returns a copy of this {@link FluentBackoff} that limits the total time spent in backoff - * returned across all calls to {@link BackOff#nextBackOffMillis()}. - * - *

              Does not modify this object. - * - * @see FluentBackoff - */ - public FluentBackoff withMaxCumulativeBackoff(Duration maxCumulativeBackoff) { - checkArgument(maxCumulativeBackoff.isLongerThan(Duration.ZERO), - "maxCumulativeBackoff %s must be at least 1 millisecond", maxCumulativeBackoff); - return new FluentBackoff( - exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); - } - - /** - * Returns a copy of this {@link FluentBackoff} that limits the total number of retries, aka - * the total number of calls to {@link BackOff#nextBackOffMillis()} before returning - * {@link BackOff#STOP}. - * - *

              Does not modify this object. - * - * @see FluentBackoff - */ - public FluentBackoff withMaxRetries(int maxRetries) { - checkArgument(maxRetries >= 0, "maxRetries %s cannot be negative", maxRetries); - return new FluentBackoff( - exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); - } - - public String toString() { - return MoreObjects.toStringHelper(FluentBackoff.class) - .add("exponent", exponent) - .add("initialBackoff", initialBackoff) - .add("maxBackoff", maxBackoff) - .add("maxRetries", maxRetries) - .add("maxCumulativeBackoff", maxCumulativeBackoff) - .toString(); - } - - private static class BackoffImpl implements BackOff { - - // Customization of this backoff. - private final FluentBackoff backoffConfig; - // Current state - private Duration currentCumulativeBackoff; - private int currentRetry; - - @Override - public void reset() { - currentRetry = 0; - currentCumulativeBackoff = Duration.ZERO; - } - - @Override - public long nextBackOffMillis() { - // Maximum number of retries reached. - if (currentRetry >= backoffConfig.maxRetries) { - return BackOff.STOP; - } - // Maximum cumulative backoff reached. - if (currentCumulativeBackoff.compareTo(backoffConfig.maxCumulativeBackoff) >= 0) { - return BackOff.STOP; - } - - double currentIntervalMillis = - Math.min( - backoffConfig.initialBackoff.getMillis() - * Math.pow(backoffConfig.exponent, currentRetry), - backoffConfig.maxBackoff.getMillis()); - double randomOffset = - (Math.random() * 2 - 1) * DEFAULT_RANDOMIZATION_FACTOR * currentIntervalMillis; - long nextBackoffMillis = Math.round(currentIntervalMillis + randomOffset); - // Cap to limit on cumulative backoff - Duration remainingCumulative = - backoffConfig.maxCumulativeBackoff.minus(currentCumulativeBackoff); - nextBackoffMillis = Math.min(nextBackoffMillis, remainingCumulative.getMillis()); - - // Update state and return backoff. - currentCumulativeBackoff = currentCumulativeBackoff.plus(nextBackoffMillis); - currentRetry += 1; - return nextBackoffMillis; - } - - private BackoffImpl(FluentBackoff backoffConfig) { - this.backoffConfig = backoffConfig; - this.reset(); - } - - public String toString() { - return MoreObjects.toStringHelper(BackoffImpl.class) - .add("backoffConfig", backoffConfig) - .add("currentRetry", currentRetry) - .add("currentCumulativeBackoff", currentCumulativeBackoff) - .toString(); - } - } - - private FluentBackoff( - double exponent, Duration initialBackoff, Duration maxBackoff, Duration maxCumulativeBackoff, - int maxRetries) { - this.exponent = exponent; - this.initialBackoff = initialBackoff; - this.maxBackoff = maxBackoff; - this.maxRetries = maxRetries; - this.maxCumulativeBackoff = maxCumulativeBackoff; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java deleted file mode 100644 index 1d675e3487..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GatherAllPanes.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey.ReifyTimestampsAndWindows; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.windowing.Never; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -/** - * Gathers all panes of each window into exactly one output. - * - *

              Note that this will delay the output of a window until the garbage collection time (when the - * watermark passes the end of the window plus allowed lateness) even if the upstream triggers - * closed the window earlier. - */ -public class GatherAllPanes - extends PTransform, PCollection>>> { - /** - * Gathers all panes of each window into a single output element. - * - *

              This will gather all output panes into a single element, which causes them to be colocated - * on a single worker. As a result, this is only suitable for {@link PCollection PCollections} - * where all of the output elements for each pane fit in memory, such as in tests. - */ - public static GatherAllPanes globally() { - return new GatherAllPanes<>(); - } - - private GatherAllPanes() {} - - @Override - public PCollection>> apply(PCollection input) { - WindowFn originalWindowFn = input.getWindowingStrategy().getWindowFn(); - - return input - .apply(WithKeys.of(0).withKeyType(new TypeDescriptor() {})) - .apply(new ReifyTimestampsAndWindows()) - .apply( - Window.into( - new IdentityWindowFn>>( - originalWindowFn.windowCoder(), originalWindowFn.assignsToSingleWindow())) - .triggering(Never.ever()) - .withAllowedLateness(input.getWindowingStrategy().getAllowedLateness()) - .discardingFiredPanes()) - // all values have the same key so they all appear as a single output element - .apply(GroupByKey.>create()) - .apply(Values.>>create()) - .setWindowingStrategyInternal(input.getWindowingStrategy()); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcpCredentialFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcpCredentialFactory.java deleted file mode 100644 index 8b6f495e9e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcpCredentialFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -/** - * Construct an oauth credential to be used by the SDK and the SDK workers. - * Returns a GCP credential. - */ -public class GcpCredentialFactory implements CredentialFactory { - private GcpOptions options; - - private GcpCredentialFactory(GcpOptions options) { - this.options = options; - } - - public static GcpCredentialFactory fromOptions(PipelineOptions options) { - return new GcpCredentialFactory(options.as(GcpOptions.class)); - } - - @Override - public Credential getCredential() throws IOException, GeneralSecurityException { - return Credentials.getCredential(options); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactory.java deleted file mode 100644 index ce933f563a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactory.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; - -import java.io.IOException; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -/** - * Implements IOChannelFactory for GCS. - */ -public class GcsIOChannelFactory implements IOChannelFactory { - - private final GcsOptions options; - - public GcsIOChannelFactory(GcsOptions options) { - this.options = options; - } - - @Override - public Collection match(String spec) throws IOException { - GcsPath path = GcsPath.fromUri(spec); - GcsUtil util = options.getGcsUtil(); - List matched = util.expand(path); - - List specs = new LinkedList<>(); - for (GcsPath match : matched) { - specs.add(match.toString()); - } - - return specs; - } - - @Override - public ReadableByteChannel open(String spec) throws IOException { - GcsPath path = GcsPath.fromUri(spec); - GcsUtil util = options.getGcsUtil(); - return util.open(path); - } - - @Override - public WritableByteChannel create(String spec, String mimeType) - throws IOException { - GcsPath path = GcsPath.fromUri(spec); - GcsUtil util = options.getGcsUtil(); - return util.create(path, mimeType); - } - - @Override - public long getSizeBytes(String spec) throws IOException { - GcsPath path = GcsPath.fromUri(spec); - GcsUtil util = options.getGcsUtil(); - return util.fileSize(path); - } - - @Override - public boolean isReadSeekEfficient(String spec) throws IOException { - // TODO It is incorrect to return true here for files with content encoding set to gzip. - return true; - } - - @Override - public String resolve(String path, String other) throws IOException { - return GcsPath.fromUri(path).resolve(other).toString(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsStager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsStager.java deleted file mode 100644 index 99f30be217..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsStager.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -import java.util.List; - -/** - * Utility class for staging files to GCS. - */ -public class GcsStager implements Stager { - private DataflowPipelineOptions options; - - private GcsStager(DataflowPipelineOptions options) { - this.options = options; - } - - public static GcsStager fromOptions(PipelineOptions options) { - return new GcsStager(options.as(DataflowPipelineOptions.class)); - } - - @Override - public List stageFiles() { - checkNotNull(options.getStagingLocation()); - List filesToStage = options.getFilesToStage(); - String windmillBinary = - options.as(DataflowPipelineDebugOptions.class).getOverrideWindmillBinary(); - if (windmillBinary != null) { - filesToStage.add("windmill_main=" + windmillBinary); - } - return PackageUtil.stageClasspathElements( - options.getFilesToStage(), options.getStagingLocation()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java deleted file mode 100644 index c4bc87352a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GcsUtil.java +++ /dev/null @@ -1,564 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.googleapis.batch.BatchRequest; -import com.google.api.client.googleapis.batch.json.JsonBatchCallback; -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpHeaders; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.Sleeper; -import com.google.api.services.storage.Storage; -import com.google.api.services.storage.model.Objects; -import com.google.api.services.storage.model.StorageObject; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.hadoop.gcsio.GoogleCloudStorageReadChannel; -import com.google.cloud.hadoop.gcsio.GoogleCloudStorageWriteChannel; -import com.google.cloud.hadoop.gcsio.ObjectWriteConditions; -import com.google.cloud.hadoop.util.ApiErrorExtractor; -import com.google.cloud.hadoop.util.AsyncWriteChannelOptions; -import com.google.cloud.hadoop.util.ClientRequestHelper; -import com.google.cloud.hadoop.util.ResilientOperation; -import com.google.cloud.hadoop.util.RetryDeterminer; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.channels.SeekableByteChannel; -import java.nio.channels.WritableByteChannel; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; - -/** - * Provides operations on GCS. - */ -public class GcsUtil { - /** - * This is a {@link DefaultValueFactory} able to create a {@link GcsUtil} using - * any transport flags specified on the {@link PipelineOptions}. - */ - public static class GcsUtilFactory implements DefaultValueFactory { - /** - * Returns an instance of {@link GcsUtil} based on the - * {@link PipelineOptions}. - * - *

              If no instance has previously been created, one is created and the value - * stored in {@code options}. - */ - @Override - public GcsUtil create(PipelineOptions options) { - LOG.debug("Creating new GcsUtil"); - GcsOptions gcsOptions = options.as(GcsOptions.class); - return new GcsUtil(Transport.newStorageClient(gcsOptions).build(), - gcsOptions.getExecutorService(), gcsOptions.getGcsUploadBufferSizeBytes()); - } - } - - private static final Logger LOG = LoggerFactory.getLogger(GcsUtil.class); - - /** Maximum number of items to retrieve per Objects.List request. */ - private static final long MAX_LIST_ITEMS_PER_CALL = 1024; - - /** Matches a glob containing a wildcard, capturing the portion before the first wildcard. */ - private static final Pattern GLOB_PREFIX = Pattern.compile("(?[^\\[*?]*)[\\[*?].*"); - - private static final String RECURSIVE_WILDCARD = "[*]{2}"; - - /** - * A {@link Pattern} for globs with a recursive wildcard. - */ - private static final Pattern RECURSIVE_GCS_PATTERN = - Pattern.compile(".*" + RECURSIVE_WILDCARD + ".*"); - - /** - * Maximum number of requests permitted in a GCS batch request. - */ - private static final int MAX_REQUESTS_PER_BATCH = 100; - /** - * Maximum number of concurrent batches of requests executing on GCS. - */ - private static final int MAX_CONCURRENT_BATCHES = 256; - - private static final FluentBackoff BACKOFF_FACTORY = - FluentBackoff.DEFAULT.withMaxRetries(3).withInitialBackoff(Duration.millis(200)); - - ///////////////////////////////////////////////////////////////////////////// - - /** Client for the GCS API. */ - private Storage storageClient; - /** Buffer size for GCS uploads (in bytes). */ - @Nullable private final Integer uploadBufferSizeBytes; - - // Helper delegate for turning IOExceptions from API calls into higher-level semantics. - private final ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); - - // Exposed for testing. - final ExecutorService executorService; - - /** - * Returns true if the given GCS pattern is supported otherwise fails with an - * exception. - */ - public boolean isGcsPatternSupported(String gcsPattern) { - if (RECURSIVE_GCS_PATTERN.matcher(gcsPattern).matches()) { - throw new IllegalArgumentException("Unsupported wildcard usage in \"" + gcsPattern + "\": " - + " recursive wildcards are not supported."); - } - - return true; - } - - private GcsUtil( - Storage storageClient, ExecutorService executorService, - @Nullable Integer uploadBufferSizeBytes) { - this.storageClient = storageClient; - this.uploadBufferSizeBytes = uploadBufferSizeBytes; - this.executorService = executorService; - } - - // Use this only for testing purposes. - protected void setStorageClient(Storage storageClient) { - this.storageClient = storageClient; - } - - /** - * Expands a pattern into matched paths. The pattern path may contain globs, which are expanded - * in the result. For patterns that only match a single object, we ensure that the object - * exists. - */ - public List expand(GcsPath gcsPattern) throws IOException { - checkArgument(isGcsPatternSupported(gcsPattern.getObject())); - Matcher m = GLOB_PREFIX.matcher(gcsPattern.getObject()); - Pattern p = null; - String prefix = null; - if (!m.matches()) { - // Not a glob. - Storage.Objects.Get getObject = storageClient.objects().get( - gcsPattern.getBucket(), gcsPattern.getObject()); - try { - // Use a get request to fetch the metadata of the object, - // the request has strong global consistency. - ResilientOperation.retry( - ResilientOperation.getGoogleRequestCallable(getObject), - BACKOFF_FACTORY.backoff(), - RetryDeterminer.SOCKET_ERRORS, - IOException.class); - return ImmutableList.of(gcsPattern); - } catch (IOException | InterruptedException e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - if (e instanceof IOException && errorExtractor.itemNotFound((IOException) e)) { - // If the path was not found, return an empty list. - return ImmutableList.of(); - } - throw new IOException("Unable to match files for pattern " + gcsPattern, e); - } - } else { - // Part before the first wildcard character. - prefix = m.group("PREFIX"); - p = Pattern.compile(globToRegexp(gcsPattern.getObject())); - } - - LOG.debug("matching files in bucket {}, prefix {} against pattern {}", gcsPattern.getBucket(), - prefix, p.toString()); - - // List all objects that start with the prefix (including objects in sub-directories). - Storage.Objects.List listObject = storageClient.objects().list(gcsPattern.getBucket()); - listObject.setMaxResults(MAX_LIST_ITEMS_PER_CALL); - listObject.setPrefix(prefix); - - String pageToken = null; - List results = new LinkedList<>(); - do { - if (pageToken != null) { - listObject.setPageToken(pageToken); - } - - Objects objects; - try { - objects = ResilientOperation.retry( - ResilientOperation.getGoogleRequestCallable(listObject), - BACKOFF_FACTORY.backoff(), - RetryDeterminer.SOCKET_ERRORS, - IOException.class); - } catch (Exception e) { - throw new IOException("Unable to match files in bucket " + gcsPattern.getBucket() - + ", prefix " + prefix + " against pattern " + p.toString(), e); - } - //Objects objects = listObject.execute(); - checkNotNull(objects); - - if (objects.getItems() == null) { - break; - } - - // Filter objects based on the regex. - for (StorageObject o : objects.getItems()) { - String name = o.getName(); - // Skip directories, which end with a slash. - if (p.matcher(name).matches() && !name.endsWith("/")) { - LOG.debug("Matched object: {}", name); - results.add(GcsPath.fromObject(o)); - } - } - - pageToken = objects.getNextPageToken(); - } while (pageToken != null); - - return results; - } - - @VisibleForTesting - @Nullable - Integer getUploadBufferSizeBytes() { - return uploadBufferSizeBytes; - } - - /** - * Returns the file size from GCS or throws {@link FileNotFoundException} - * if the resource does not exist. - */ - public long fileSize(GcsPath path) throws IOException { - return fileSize( - path, - BACKOFF_FACTORY.backoff(), - Sleeper.DEFAULT); - } - - /** - * Returns the file size from GCS or throws {@link FileNotFoundException} - * if the resource does not exist. - */ - @VisibleForTesting - long fileSize(GcsPath path, BackOff backoff, Sleeper sleeper) throws IOException { - Storage.Objects.Get getObject = - storageClient.objects().get(path.getBucket(), path.getObject()); - try { - StorageObject object = ResilientOperation.retry( - ResilientOperation.getGoogleRequestCallable(getObject), - backoff, - RetryDeterminer.SOCKET_ERRORS, - IOException.class, - sleeper); - return object.getSize().longValue(); - } catch (Exception e) { - if (e instanceof IOException && errorExtractor.itemNotFound((IOException) e)) { - throw new FileNotFoundException(path.toString()); - } - throw new IOException("Unable to get file size", e); - } - } - - /** - * Opens an object in GCS. - * - *

              Returns a SeekableByteChannel that provides access to data in the bucket. - * - * @param path the GCS filename to read from - * @return a SeekableByteChannel that can read the object data - * @throws IOException - */ - public SeekableByteChannel open(GcsPath path) - throws IOException { - return new GoogleCloudStorageReadChannel(storageClient, path.getBucket(), - path.getObject(), errorExtractor, - new ClientRequestHelper()); - } - - /** - * Creates an object in GCS. - * - *

              Returns a WritableByteChannel that can be used to write data to the - * object. - * - * @param path the GCS file to write to - * @param type the type of object, eg "text/plain". - * @return a Callable object that encloses the operation. - * @throws IOException - */ - public WritableByteChannel create(GcsPath path, - String type) throws IOException { - GoogleCloudStorageWriteChannel channel = new GoogleCloudStorageWriteChannel( - executorService, - storageClient, - new ClientRequestHelper(), - path.getBucket(), - path.getObject(), - AsyncWriteChannelOptions.newBuilder().build(), - new ObjectWriteConditions(), - Collections.emptyMap(), - type); - if (uploadBufferSizeBytes != null) { - channel.setUploadBufferSize(uploadBufferSizeBytes); - } - channel.initialize(); - return channel; - } - - /** - * Returns whether the GCS bucket exists. If the bucket exists, it must - * be accessible otherwise the permissions exception will be propagated. - */ - public boolean bucketExists(GcsPath path) throws IOException { - return bucketExists( - path, - BACKOFF_FACTORY.backoff(), - Sleeper.DEFAULT); - } - - /** - * Returns whether the GCS bucket exists. This will return false if the bucket - * is inaccessible due to permissions. - */ - @VisibleForTesting - boolean bucketExists(GcsPath path, BackOff backoff, Sleeper sleeper) throws IOException { - Storage.Buckets.Get getBucket = - storageClient.buckets().get(path.getBucket()); - - try { - ResilientOperation.retry( - ResilientOperation.getGoogleRequestCallable(getBucket), - backoff, - new RetryDeterminer() { - @Override - public boolean shouldRetry(IOException e) { - if (errorExtractor.itemNotFound(e) || errorExtractor.accessDenied(e)) { - return false; - } - return RetryDeterminer.SOCKET_ERRORS.shouldRetry(e); - } - }, - IOException.class, - sleeper); - return true; - } catch (GoogleJsonResponseException e) { - if (errorExtractor.itemNotFound(e) || errorExtractor.accessDenied(e)) { - return false; - } - throw e; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException( - String.format("Error while attempting to verify existence of bucket gs://%s", - path.getBucket()), e); - } - } - - private static void executeBatches(List batches) throws IOException { - ListeningExecutorService executor = MoreExecutors.listeningDecorator( - MoreExecutors.getExitingExecutorService( - new ThreadPoolExecutor(MAX_CONCURRENT_BATCHES, MAX_CONCURRENT_BATCHES, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue()))); - - List> futures = new LinkedList<>(); - for (final BatchRequest batch : batches) { - futures.add(executor.submit(new Callable() { - public Void call() throws IOException { - batch.execute(); - return null; - } - })); - } - - try { - Futures.allAsList(futures).get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException("Interrupted while executing batch GCS request", e); - } catch (ExecutionException e) { - throw new IOException("Error executing batch GCS request", e); - } finally { - executor.shutdown(); - } - } - - public void copy(List srcFilenames, List destFilenames) throws IOException { - executeBatches(makeCopyBatches(srcFilenames, destFilenames)); - } - - List makeCopyBatches(List srcFilenames, List destFilenames) - throws IOException { - checkArgument( - srcFilenames.size() == destFilenames.size(), - "Number of source files %s must equal number of destination files %s", - srcFilenames.size(), - destFilenames.size()); - - List batches = new LinkedList<>(); - BatchRequest batch = storageClient.batch(); - for (int i = 0; i < srcFilenames.size(); i++) { - final GcsPath sourcePath = GcsPath.fromUri(srcFilenames.get(i)); - final GcsPath destPath = GcsPath.fromUri(destFilenames.get(i)); - enqueueCopy(sourcePath, destPath, batch); - if (batch.size() >= MAX_REQUESTS_PER_BATCH) { - batches.add(batch); - batch = storageClient.batch(); - } - } - if (batch.size() > 0) { - batches.add(batch); - } - return batches; - } - - List makeRemoveBatches(Collection filenames) throws IOException { - List batches = new LinkedList<>(); - for (List filesToDelete : - Lists.partition(Lists.newArrayList(filenames), MAX_REQUESTS_PER_BATCH)) { - BatchRequest batch = storageClient.batch(); - for (String file : filesToDelete) { - enqueueDelete(GcsPath.fromUri(file), batch); - } - batches.add(batch); - } - return batches; - } - - public void remove(Collection filenames) throws IOException { - executeBatches(makeRemoveBatches(filenames)); - } - - private void enqueueCopy(final GcsPath from, final GcsPath to, BatchRequest batch) - throws IOException { - Storage.Objects.Copy copyRequest = storageClient.objects() - .copy(from.getBucket(), from.getObject(), to.getBucket(), to.getObject(), null); - copyRequest.queue(batch, new JsonBatchCallback() { - @Override - public void onSuccess(StorageObject obj, HttpHeaders responseHeaders) { - LOG.debug("Successfully copied {} to {}", from, to); - } - - @Override - public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { - if (errorExtractor.itemNotFound(e)) { - // Do nothing on item not found. - LOG.debug("{} does not exist, assuming this is a retry after deletion.", from); - return; - } - throw new IOException( - String.format("Error trying to copy %s to %s: %s", from, to, e)); - } - }); - } - - private void enqueueDelete(final GcsPath file, BatchRequest batch) throws IOException { - Storage.Objects.Delete deleteRequest = storageClient.objects() - .delete(file.getBucket(), file.getObject()); - deleteRequest.queue(batch, new JsonBatchCallback() { - @Override - public void onSuccess(Void obj, HttpHeaders responseHeaders) { - LOG.debug("Successfully deleted {}", file); - } - - @Override - public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { - if (errorExtractor.itemNotFound(e)) { - // Do nothing on item not found. - LOG.debug("{} does not exist.", file); - return; - } - throw new IOException(String.format("Error trying to delete %s: %s", file, e)); - } - }); - } - - /** - * Expands glob expressions to regular expressions. - * - * @param globExp the glob expression to expand - * @return a string with the regular expression this glob expands to - */ - static String globToRegexp(String globExp) { - StringBuilder dst = new StringBuilder(); - char[] src = globExp.toCharArray(); - int i = 0; - while (i < src.length) { - char c = src[i++]; - switch (c) { - case '*': - dst.append("[^/]*"); - break; - case '?': - dst.append("[^/]"); - break; - case '.': - case '+': - case '{': - case '}': - case '(': - case ')': - case '|': - case '^': - case '$': - // These need to be escaped in regular expressions - dst.append('\\').append(c); - break; - case '\\': - i = doubleSlashes(dst, src, i); - break; - default: - dst.append(c); - break; - } - } - return dst.toString(); - } - - private static int doubleSlashes(StringBuilder dst, char[] src, int i) { - // Emit the next character without special interpretation - dst.append('\\'); - if ((i - 1) != src.length) { - dst.append(src[i]); - i++; - } else { - // A backslash at the very end is treated like an escaped backslash - dst.append('\\'); - } - return i; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java deleted file mode 100644 index 5110ff199f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowViaWindowSetDoFn.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.DoFnRunner.ReduceFnExecutor; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.KV; - -/** - * A general {@link GroupAlsoByWindowsDoFn}. This delegates all of the logic to the - * {@link ReduceFnRunner}. - */ -@SystemDoFnInternal -public class GroupAlsoByWindowViaWindowSetDoFn< - K, InputT, OutputT, W extends BoundedWindow, RinT extends KeyedWorkItem> - extends DoFn> implements ReduceFnExecutor { - - public static - DoFn, KV> create( - WindowingStrategy strategy, SystemReduceFn reduceFn) { - return new GroupAlsoByWindowViaWindowSetDoFn<>(strategy, reduceFn); - } - - protected final Aggregator droppedDueToClosedWindow = - createAggregator( - GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); - protected final Aggregator droppedDueToLateness = - createAggregator(GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); - - private final WindowingStrategy windowingStrategy; - private SystemReduceFn reduceFn; - - private GroupAlsoByWindowViaWindowSetDoFn( - WindowingStrategy windowingStrategy, - SystemReduceFn reduceFn) { - @SuppressWarnings("unchecked") - WindowingStrategy noWildcard = (WindowingStrategy) windowingStrategy; - this.windowingStrategy = noWildcard; - this.reduceFn = reduceFn; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - KeyedWorkItem element = c.element(); - - K key = c.element().key(); - TimerInternals timerInternals = c.windowingInternals().timerInternals(); - - // It is the responsibility of the user of GroupAlsoByWindowsViaWindowSet to only - // provide a WindowingInternals instance with the appropriate key type for StateInternals. - @SuppressWarnings("unchecked") - StateInternals stateInternals = (StateInternals) c.windowingInternals().stateInternals(); - - ReduceFnRunner reduceFnRunner = - new ReduceFnRunner<>( - key, - windowingStrategy, - stateInternals, - timerInternals, - c.windowingInternals(), - droppedDueToClosedWindow, - reduceFn, - c.getPipelineOptions()); - - reduceFnRunner.processElements(element.elementsIterable()); - reduceFnRunner.onTimers(element.timersIterable()); - reduceFnRunner.persist(); - } - - @Override - public DoFn, KV> asDoFn() { - // Safe contravariant cast - @SuppressWarnings("unchecked") - DoFn, KV> asFn = - (DoFn, KV>) this; - return asFn; - } - - @Override - public Aggregator getDroppedDueToLatenessAggregator() { - return droppedDueToLateness; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java deleted file mode 100644 index 175921d434..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFn.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.KV; - -/** - * DoFn that merges windows and groups elements in those windows, optionally - * combining values. - * - * @param key type - * @param input value element type - * @param output value element type - * @param window type - */ -@SystemDoFnInternal -public abstract class GroupAlsoByWindowsDoFn - extends DoFn>>, KV> { - public static final String DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER = "DroppedDueToClosedWindow"; - public static final String DROPPED_DUE_TO_LATENESS_COUNTER = "DroppedDueToLateness"; - - protected final Aggregator droppedDueToClosedWindow = - createAggregator(DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER, new Sum.SumLongFn()); - protected final Aggregator droppedDueToLateness = - createAggregator(DROPPED_DUE_TO_LATENESS_COUNTER, new Sum.SumLongFn()); - - /** - * Create the default {@link GroupAlsoByWindowsDoFn}, which uses window sets to implement the - * grouping. - * - * @param windowingStrategy The window function and trigger to use for grouping - * @param inputCoder the input coder to use - */ - public static GroupAlsoByWindowsDoFn, W> - createDefault(WindowingStrategy windowingStrategy, Coder inputCoder) { - return new GroupAlsoByWindowsViaOutputBufferDoFn<>( - windowingStrategy, SystemReduceFn.buffering(inputCoder)); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java deleted file mode 100644 index d394e81a0e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFn.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.Iterables; - -import org.joda.time.Instant; - -import java.util.List; - -/** - * The default batch {@link GroupAlsoByWindowsDoFn} implementation, if no specialized "fast path" - * implementation is applicable. - */ -@SystemDoFnInternal -public class GroupAlsoByWindowsViaOutputBufferDoFn - extends GroupAlsoByWindowsDoFn { - - private final WindowingStrategy strategy; - private SystemReduceFn reduceFn; - - public GroupAlsoByWindowsViaOutputBufferDoFn( - WindowingStrategy windowingStrategy, - SystemReduceFn reduceFn) { - this.strategy = windowingStrategy; - this.reduceFn = reduceFn; - } - - @Override - public void processElement( - DoFn>>, KV>.ProcessContext c) - throws Exception { - K key = c.element().getKey(); - // Used with Batch, we know that all the data is available for this key. We can't use the - // timer manager from the context because it doesn't exist. So we create one and emulate the - // watermark, knowing that we have all data and it is in timestamp order. - BatchTimerInternals timerInternals = new BatchTimerInternals(Instant.now()); - - // It is the responsibility of the user of GroupAlsoByWindowsViaOutputBufferDoFn to only - // provide a WindowingInternals instance with the appropriate key type for StateInternals. - @SuppressWarnings("unchecked") - StateInternals stateInternals = (StateInternals) c.windowingInternals().stateInternals(); - - ReduceFnRunner reduceFnRunner = - new ReduceFnRunner( - key, - strategy, - stateInternals, - timerInternals, - c.windowingInternals(), - droppedDueToClosedWindow, - reduceFn, - c.getPipelineOptions()); - - Iterable>> chunks = - Iterables.partition(c.element().getValue(), 1000); - for (Iterable> chunk : chunks) { - // Process the chunk of elements. - reduceFnRunner.processElements(chunk); - - // Then, since elements are sorted by their timestamp, advance the input watermark - // to the first element, and fire any timers that may have been scheduled. - timerInternals.advanceInputWatermark(reduceFnRunner, chunk.iterator().next().getTimestamp()); - - // Fire any processing timers that need to fire - timerInternals.advanceProcessingTime(reduceFnRunner, Instant.now()); - - // Leave the output watermark undefined. Since there's no late data in batch mode - // there's really no need to track it as we do for streaming. - } - - // Finish any pending windows by advancing the input watermark to infinity. - timerInternals.advanceInputWatermark(reduceFnRunner, BoundedWindow.TIMESTAMP_MAX_VALUE); - - // Finally, advance the processing time to infinity to fire any timers. - timerInternals.advanceProcessingTime(reduceFnRunner, BoundedWindow.TIMESTAMP_MAX_VALUE); - - reduceFnRunner.persist(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java deleted file mode 100644 index 03822ff110..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; -import java.util.Collection; - -/** - * Defines a factory for working with read and write channels. - * - *

              Channels provide an abstract API for IO operations. - * - *

              See Java NIO Channels - */ -public interface IOChannelFactory { - - /** - * Matches a specification, which may contain globs, against available - * resources. - * - *

              Glob handling is dependent on the implementation. Implementations should - * all support globs in the final component of a path (eg /foo/bar/*.txt), - * however they are not required to support globs in the directory paths. - * - *

              The list of resources returned are required to exist and not represent abstract - * resources such as symlinks and directories. - */ - Collection match(String spec) throws IOException; - - /** - * Returns a read channel for the given specification. - * - *

              The specification is not expanded; it is used verbatim. - * - *

              If seeking is supported, then this returns a - * {@link java.nio.channels.SeekableByteChannel}. - */ - ReadableByteChannel open(String spec) throws IOException; - - /** - * Returns a write channel for the given specification. - * - *

              The specification is not expanded; is it used verbatim. - */ - WritableByteChannel create(String spec, String mimeType) throws IOException; - - /** - * Returns the size in bytes for the given specification. - * - *

              The specification is not expanded; it is used verbatim. - * - *

              {@link FileNotFoundException} will be thrown if the resource does not exist. - */ - long getSizeBytes(String spec) throws IOException; - - /** - * Returns {@code true} if the channel created when invoking method {@link #open} for the given - * file specification is guaranteed to be of type {@link java.nio.channels.SeekableByteChannel - * SeekableByteChannel} and if seeking into positions of the channel is recommended. Returns - * {@code false} if the channel returned is not a {@code SeekableByteChannel}. May return - * {@code false} even if the channel returned is a {@code SeekableByteChannel}, if seeking is not - * efficient for the given file specification. - * - *

              Only efficiently seekable files can be split into offset ranges. - * - *

              The specification is not expanded; it is used verbatim. - */ - boolean isReadSeekEfficient(String spec) throws IOException; - - /** - * Resolve the given {@code other} against the {@code path}. - * - *

              If the {@code other} parameter is an absolute path then this method trivially returns - * other. If {@code other} is an empty path then this method trivially returns the given - * {@code path}. Otherwise this method considers the given {@code path} to be a directory and - * resolves the {@code other} path against this path. In the simplest case, the {@code other} - * path does not have a root component, in which case this method joins the {@code other} path - * to the given {@code path} and returns a resulting path that ends with the {@code other} path. - * Where the {@code other} path has a root component then resolution is highly implementation - * dependent and therefore unspecified. - */ - String resolve(String path, String other) throws IOException; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelUtils.java deleted file mode 100644 index cbf420ec6b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IOChannelUtils.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.channels.WritableByteChannel; -import java.text.DecimalFormat; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Provides utilities for creating read and write channels. - */ -public class IOChannelUtils { - // TODO: add registration mechanism for adding new schemas. - private static final Map FACTORY_MAP = - Collections.synchronizedMap(new HashMap()); - - // Pattern that matches shard placeholders within a shard template. - private static final Pattern SHARD_FORMAT_RE = Pattern.compile("(S+|N+)"); - - /** - * Associates a scheme with an {@link IOChannelFactory}. - * - *

              The given factory is used to construct read and write channels when - * a URI is provided with the given scheme. - * - *

              For example, when reading from "gs://bucket/path", the scheme "gs" is - * used to lookup the appropriate factory. - */ - public static void setIOFactory(String scheme, IOChannelFactory factory) { - FACTORY_MAP.put(scheme, factory); - } - - /** - * Registers standard factories globally. This requires {@link PipelineOptions} - * to provide, e.g., credentials for GCS. - */ - public static void registerStandardIOFactories(PipelineOptions options) { - setIOFactory("gs", new GcsIOChannelFactory(options.as(GcsOptions.class))); - } - - /** - * Creates a write channel for the given filename. - */ - public static WritableByteChannel create(String filename, String mimeType) - throws IOException { - return getFactory(filename).create(filename, mimeType); - } - - /** - * Creates a write channel for the given file components. - * - *

              If numShards is specified, then a ShardingWritableByteChannel is - * returned. - * - *

              Shard numbers are 0 based, meaning they start with 0 and end at the - * number of shards - 1. - */ - public static WritableByteChannel create(String prefix, String shardTemplate, - String suffix, int numShards, String mimeType) throws IOException { - if (numShards == 1) { - return create(constructName(prefix, shardTemplate, suffix, 0, 1), - mimeType); - } - - // It is the callers responsibility to close this channel. - @SuppressWarnings("resource") - ShardingWritableByteChannel shardingChannel = - new ShardingWritableByteChannel(); - - Set outputNames = new HashSet<>(); - for (int i = 0; i < numShards; i++) { - String outputName = - constructName(prefix, shardTemplate, suffix, i, numShards); - if (!outputNames.add(outputName)) { - throw new IllegalArgumentException( - "Shard name collision detected for: " + outputName); - } - WritableByteChannel channel = create(outputName, mimeType); - shardingChannel.addChannel(channel); - } - - return shardingChannel; - } - - /** - * Returns the size in bytes for the given specification. - * - *

              The specification is not expanded; it is used verbatim. - * - *

              {@link FileNotFoundException} will be thrown if the resource does not exist. - */ - public static long getSizeBytes(String spec) throws IOException { - return getFactory(spec).getSizeBytes(spec); - } - - /** - * Constructs a fully qualified name from components. - * - *

              The name is built from a prefix, shard template (with shard numbers - * applied), and a suffix. All components are required, but may be empty - * strings. - * - *

              Within a shard template, repeating sequences of the letters "S" or "N" - * are replaced with the shard number, or number of shards respectively. The - * numbers are formatted with leading zeros to match the length of the - * repeated sequence of letters. - * - *

              For example, if prefix = "output", shardTemplate = "-SSS-of-NNN", and - * suffix = ".txt", with shardNum = 1 and numShards = 100, the following is - * produced: "output-001-of-100.txt". - */ - public static String constructName(String prefix, - String shardTemplate, String suffix, int shardNum, int numShards) { - // Matcher API works with StringBuffer, rather than StringBuilder. - StringBuffer sb = new StringBuffer(); - sb.append(prefix); - - Matcher m = SHARD_FORMAT_RE.matcher(shardTemplate); - while (m.find()) { - boolean isShardNum = (m.group(1).charAt(0) == 'S'); - - char[] zeros = new char[m.end() - m.start()]; - Arrays.fill(zeros, '0'); - DecimalFormat df = new DecimalFormat(String.valueOf(zeros)); - String formatted = df.format(isShardNum - ? shardNum - : numShards); - m.appendReplacement(sb, formatted); - } - m.appendTail(sb); - - sb.append(suffix); - return sb.toString(); - } - - private static final Pattern URI_SCHEME_PATTERN = Pattern.compile( - "(?[a-zA-Z][-a-zA-Z0-9+.]*)://.*"); - - /** - * Returns the IOChannelFactory associated with an input specification. - */ - public static IOChannelFactory getFactory(String spec) throws IOException { - // The spec is almost, but not quite, a URI. In particular, - // the reserved characters '[', ']', and '?' have meanings that differ - // from their use in the URI spec. ('*' is not reserved). - // Here, we just need the scheme, which is so circumscribed as to be - // very easy to extract with a regex. - Matcher matcher = URI_SCHEME_PATTERN.matcher(spec); - - if (!matcher.matches()) { - return new FileIOChannelFactory(); - } - - String scheme = matcher.group("scheme"); - IOChannelFactory ioFactory = FACTORY_MAP.get(scheme); - if (ioFactory != null) { - return ioFactory; - } - - throw new IOException("Unable to find handler for " + spec); - } - - /** - * Resolve the given {@code other} against the {@code path}. - * - *

              If the {@code other} parameter is an absolute path then this method trivially returns - * other. If {@code other} is an empty path then this method trivially returns the given - * {@code path}. Otherwise this method considers the given {@code path} to be a directory and - * resolves the {@code other} path against this path. In the simplest case, the {@code other} - * path does not have a root component, in which case this method joins the {@code other} path - * to the given {@code path} and returns a resulting path that ends with the {@code other} path. - * Where the {@code other} path has a root component then resolution is highly implementation - * dependent and therefore unspecified. - */ - public static String resolve(String path, String other) throws IOException { - return getFactory(path).resolve(path, other); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java deleted file mode 100644 index 757b0963c8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IdentityWindowFn.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.NonMergingWindowFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import org.joda.time.Instant; - -import java.util.Collection; - -/** - * A {@link WindowFn} that leaves all associations between elements and windows unchanged. - * - *

              This {@link WindowFn} is applied when elements must be passed through a {@link GroupByKey}, - * but should maintain their existing {@link Window} assignments. Because windows may have been - * merged, the earlier {@link WindowFn} may not appropriately maintain the existing window - * assignments. For example, if the earlier {@link WindowFn} merges windows, after a - * {@link GroupByKey} the {@link WindowingStrategy} uses {@link InvalidWindows}, and no further - * {@link GroupByKey} can be applied without applying a new {@link WindowFn}. This {@link WindowFn} - * allows existing window assignments to be maintained across a single group by key, at which point - * the earlier {@link WindowingStrategy} should be restored. - * - *

              This {@link WindowFn} is an internal implementation detail of sdk-provided utilities, and - * should not be used by {@link Pipeline} writers. - */ -class IdentityWindowFn extends NonMergingWindowFn { - - /** - * The coder of the type of windows of the input {@link PCollection}. This is not an arbitrary - * {@link BoundedWindow} {@link Coder}, but is safe to use for all windows assigned by this - * transform, as it should be the same coder used by the {@link WindowFn} that initially assigned - * these windows. - */ - private final Coder coder; - private final boolean assignsToSingleWindow; - - public IdentityWindowFn(Coder coder, boolean assignsToSingleWindow) { - // Safe because it is only used privately here. - // At every point where a window is returned or accepted, it has been provided - // by priorWindowFn, so it is of the expected type. - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) coder; - this.coder = windowCoder; - this.assignsToSingleWindow = assignsToSingleWindow; - } - - @Override - public Collection assignWindows(WindowFn.AssignContext c) - throws Exception { - // The windows are provided by priorWindowFn, which also provides the coder for them - @SuppressWarnings("unchecked") - Collection priorWindows = (Collection) c.windows(); - return priorWindows; - } - - @Override - public boolean isCompatible(WindowFn other) { - throw new UnsupportedOperationException( - String.format( - "%s.isCompatible() should never be called." - + " It is a private implementation detail of sdk utilities." - + " This message indicates a bug in the Beam SDK.", - getClass().getCanonicalName())); - } - - @Override - public Coder windowCoder() { - // Safe because the previous WindowFn provides both the windows and the coder. - // The Coder is _not_ actually a coder for an arbitrary BoundedWindow. - return coder; - } - - @Override - public boolean assignsToSingleWindow() { - return assignsToSingleWindow; - } - - @Override - public BoundedWindow getSideInputWindow(BoundedWindow window) { - throw new UnsupportedOperationException( - String.format( - "%s.getSideInputWindow() should never be called." - + " It is a private implementation detail of sdk utilities." - + " This message indicates a bug in the Beam SDK.", - getClass().getCanonicalName())); - } - - @Deprecated - @Override - public Instant getOutputTime(Instant inputTimestamp, BoundedWindow window) { - return inputTimestamp; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IllegalMutationException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IllegalMutationException.java deleted file mode 100644 index dbe249eeab..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IllegalMutationException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * Thrown when a value appears to have been mutated, but that mutation is forbidden. - */ -public class IllegalMutationException extends RuntimeException { - private Object savedValue; - private Object newValue; - - public IllegalMutationException(String message, Object savedValue, Object newValue) { - super(message); - this.savedValue = savedValue; - this.newValue = newValue; - } - - public IllegalMutationException( - String message, Object savedValue, Object newValue, Throwable cause) { - super(message, cause); - this.savedValue = savedValue; - this.newValue = newValue; - } - - /** - * The original value, before the illegal mutation. - */ - public Object getSavedValue() { - return savedValue; - } - - /** - * The value after the illegal mutation. - */ - public Object getNewValue() { - return newValue; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/InstanceBuilder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/InstanceBuilder.java deleted file mode 100644 index f66d785e6c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/InstanceBuilder.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Joiner; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.LinkedList; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Utility for creating objects dynamically. - * - * @param type type of object returned by this instance builder - */ -public class InstanceBuilder { - - /** - * Create an InstanceBuilder for the given type. - * - *

              The specified type is the type returned by {@link #build}, which is - * typically the common base type or interface of the instance being - * constructed. - */ - public static InstanceBuilder ofType(Class type) { - return new InstanceBuilder<>(type); - } - - /** - * Create an InstanceBuilder for the given type. - * - *

              The specified type is the type returned by {@link #build}, which is - * typically the common base type or interface for the instance to be - * constructed. - * - *

              The TypeDescriptor argument allows specification of generic types. For example, - * a {@code List} return type can be specified as - * {@code ofType(new TypeDescriptor>(){})}. - */ - public static InstanceBuilder ofType(TypeDescriptor token) { - @SuppressWarnings("unchecked") - Class type = (Class) token.getRawType(); - return new InstanceBuilder<>(type); - } - - /** - * Sets the class name to be constructed. - * - *

              If the name is a simple name (ie {@link Class#getSimpleName()}), then - * the package of the return type is added as a prefix. - * - *

              The default class is the return type, specified in {@link #ofType}. - * - *

              Modifies and returns the {@code InstanceBuilder} for chaining. - * - * @throws ClassNotFoundException if no class can be found by the given name - */ - public InstanceBuilder fromClassName(String name) - throws ClassNotFoundException { - checkArgument(factoryClass == null, "Class name may only be specified once"); - if (name.indexOf('.') == -1) { - name = type.getPackage().getName() + "." + name; - } - - try { - factoryClass = Class.forName(name); - } catch (ClassNotFoundException e) { - throw new ClassNotFoundException( - String.format("Could not find class: %s", name), e); - } - return this; - } - - /** - * Sets the factory class to use for instance construction. - * - *

              Modifies and returns the {@code InstanceBuilder} for chaining. - */ - public InstanceBuilder fromClass(Class factoryClass) { - this.factoryClass = factoryClass; - return this; - } - - /** - * Sets the name of the factory method used to construct the instance. - * - *

              The default, if no factory method was specified, is to look for a class - * constructor. - * - *

              Modifies and returns the {@code InstanceBuilder} for chaining. - */ - public InstanceBuilder fromFactoryMethod(String methodName) { - checkArgument(this.methodName == null, - "Factory method name may only be specified once"); - this.methodName = methodName; - return this; - } - - /** - * Adds an argument to be passed to the factory method. - * - *

              The argument type is used to lookup the factory method. This type may be - * a supertype of the argument value's class. - * - *

              Modifies and returns the {@code InstanceBuilder} for chaining. - * - * @param the argument type - */ - public InstanceBuilder withArg(Class argType, ArgT value) { - parameterTypes.add(argType); - arguments.add(value); - return this; - } - - /** - * Creates the instance by calling the factory method with the given - * arguments. - * - *

              Defaults

              - *
                - *
              • factory class: defaults to the output type class, overridden - * via {@link #fromClassName(String)}. - *
              • factory method: defaults to using a constructor on the factory - * class, overridden via {@link #fromFactoryMethod(String)}. - *
              - * - * @throws RuntimeException if the method does not exist, on type mismatch, - * or if the method cannot be made accessible. - */ - public T build() { - if (factoryClass == null) { - factoryClass = type; - } - - Class[] types = parameterTypes - .toArray(new Class[parameterTypes.size()]); - - // TODO: cache results, to speed repeated type lookups? - if (methodName != null) { - return buildFromMethod(types); - } else { - return buildFromConstructor(types); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Type of object to construct. - */ - private final Class type; - - /** - * Types of parameters for Method lookup. - * - * @see Class#getDeclaredMethod(String, Class[]) - */ - private final List> parameterTypes = new LinkedList<>(); - - /** - * Arguments to factory method {@link Method#invoke(Object, Object...)}. - */ - private final List arguments = new LinkedList<>(); - - /** - * Name of factory method, or null to invoke the constructor. - */ - @Nullable private String methodName; - - /** - * Factory class, or null to instantiate {@code type}. - */ - @Nullable private Class factoryClass; - - private InstanceBuilder(Class type) { - this.type = type; - } - - private T buildFromMethod(Class[] types) { - checkState(factoryClass != null); - checkState(methodName != null); - - try { - Method method = factoryClass.getDeclaredMethod(methodName, types); - - checkState(Modifier.isStatic(method.getModifiers()), - "Factory method must be a static method for " - + factoryClass.getName() + "#" + method.getName() - ); - - checkState(type.isAssignableFrom(method.getReturnType()), - "Return type for " + factoryClass.getName() + "#" + method.getName() - + " must be assignable to " + type.getSimpleName()); - - if (!method.isAccessible()) { - method.setAccessible(true); - } - - Object[] args = arguments.toArray(new Object[arguments.size()]); - return type.cast(method.invoke(null, args)); - - } catch (NoSuchMethodException e) { - throw new RuntimeException( - String.format("Unable to find factory method %s#%s(%s)", - factoryClass.getSimpleName(), - methodName, - Joiner.on(", ").join(types))); - - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException( - String.format("Failed to construct instance from factory method %s#%s(%s)", - factoryClass.getSimpleName(), - methodName, - Joiner.on(", ").join(types)), - e); - } - } - - private T buildFromConstructor(Class[] types) { - checkState(factoryClass != null); - - try { - Constructor constructor = factoryClass.getDeclaredConstructor(types); - - checkState(type.isAssignableFrom(factoryClass), - "Instance type " + factoryClass.getName() - + " must be assignable to " + type.getSimpleName()); - - if (!constructor.isAccessible()) { - constructor.setAccessible(true); - } - - Object[] args = arguments.toArray(new Object[arguments.size()]); - return type.cast(constructor.newInstance(args)); - - } catch (NoSuchMethodException e) { - throw new RuntimeException("Unable to find constructor for " - + factoryClass.getName()); - - } catch (InvocationTargetException - | InstantiationException - | IllegalAccessException e) { - throw new RuntimeException("Failed to construct instance from " - + "constructor " + factoryClass.getName(), e); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java deleted file mode 100644 index 11b9cd14ff..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOff.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.client.util.BackOff; - -/** - * Implementation of {@link BackOff} that increases the back off period for each retry attempt - * using a randomization function that grows exponentially. - * - *

              Example: The initial interval is .5 seconds and the maximum interval is 60 secs. - * For 14 tries the sequence will be (values in seconds): - * - *

              - * retry#      retry_interval     randomized_interval
              - * 1             0.5                [0.25,   0.75]
              - * 2             0.75               [0.375,  1.125]
              - * 3             1.125              [0.562,  1.687]
              - * 4             1.687              [0.8435, 2.53]
              - * 5             2.53               [1.265,  3.795]
              - * 6             3.795              [1.897,  5.692]
              - * 7             5.692              [2.846,  8.538]
              - * 8             8.538              [4.269, 12.807]
              - * 9            12.807              [6.403, 19.210]
              - * 10           28.832              [14.416, 43.248]
              - * 11           43.248              [21.624, 64.873]
              - * 12           60.0                [30.0, 90.0]
              - * 13           60.0                [30.0, 90.0]
              - * 14           60.0                [30.0, 90.0]
              - * 
              - * - *

              Implementation is not thread-safe. - */ -@Deprecated -public class IntervalBoundedExponentialBackOff implements BackOff { - public static final double DEFAULT_MULTIPLIER = 1.5; - public static final double DEFAULT_RANDOMIZATION_FACTOR = 0.5; - private final long maximumIntervalMillis; - private final long initialIntervalMillis; - private int currentAttempt; - - // BEAM-168: https://issues.apache.org/jira/browse/BEAM-168 - @Deprecated - public IntervalBoundedExponentialBackOff(int maximumIntervalMillis, long initialIntervalMillis) { - this((long) maximumIntervalMillis, initialIntervalMillis); - } - - public IntervalBoundedExponentialBackOff(long maximumIntervalMillis, long initialIntervalMillis) { - checkArgument(maximumIntervalMillis > 0, "Maximum interval must be greater than zero."); - checkArgument(initialIntervalMillis > 0, "Initial interval must be greater than zero."); - this.maximumIntervalMillis = maximumIntervalMillis; - this.initialIntervalMillis = initialIntervalMillis; - reset(); - } - - @Override - public void reset() { - currentAttempt = 1; - } - - @Override - public long nextBackOffMillis() { - double currentIntervalMillis = - Math.min( - initialIntervalMillis * Math.pow(DEFAULT_MULTIPLIER, currentAttempt - 1), - maximumIntervalMillis); - double randomOffset = - (Math.random() * 2 - 1) * DEFAULT_RANDOMIZATION_FACTOR * currentIntervalMillis; - currentAttempt += 1; - return Math.round(currentIntervalMillis + randomOffset); - } - - public boolean atMaxInterval() { - return initialIntervalMillis * Math.pow(DEFAULT_MULTIPLIER, currentAttempt - 1) - >= maximumIntervalMillis; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItem.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItem.java deleted file mode 100644 index 355f0bbc47..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItem.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; - -/** - * Interface that contains all the timers and elements associated with a specific work item. - * - * @param the key type - * @param the element type - */ -public interface KeyedWorkItem { - /** - * Returns the key. - */ - K key(); - - /** - * Returns an iterable containing the timers. - */ - Iterable timersIterable(); - - /** - * Returns an iterable containing the elements. - */ - Iterable> elementsIterable(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java deleted file mode 100644 index 398e82a8d6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoder.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerDataCoder; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.common.collect.ImmutableList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -/** - * A {@link Coder} for {@link KeyedWorkItem KeyedWorkItems}. - */ -public class KeyedWorkItemCoder extends StandardCoder> { - /** - * Create a new {@link KeyedWorkItemCoder} with the provided key coder, element coder, and window - * coder. - */ - public static KeyedWorkItemCoder of( - Coder keyCoder, Coder elemCoder, Coder windowCoder) { - return new KeyedWorkItemCoder<>(keyCoder, elemCoder, windowCoder); - } - - @JsonCreator - public static KeyedWorkItemCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { - checkArgument(components.size() == 3, "Expecting 3 components, got %s", components.size()); - @SuppressWarnings("unchecked") - Coder keyCoder = (Coder) components.get(0); - @SuppressWarnings("unchecked") - Coder elemCoder = (Coder) components.get(1); - @SuppressWarnings("unchecked") - Coder windowCoder = (Coder) components.get(2); - return new KeyedWorkItemCoder<>(keyCoder, elemCoder, windowCoder); - } - - private final Coder keyCoder; - private final Coder elemCoder; - private final Coder windowCoder; - private final Coder> timersCoder; - private final Coder>> elemsCoder; - - private KeyedWorkItemCoder( - Coder keyCoder, Coder elemCoder, Coder windowCoder) { - this.keyCoder = keyCoder; - this.elemCoder = elemCoder; - this.windowCoder = windowCoder; - this.timersCoder = IterableCoder.of(TimerDataCoder.of(windowCoder)); - this.elemsCoder = IterableCoder.of(FullWindowedValueCoder.of(elemCoder, windowCoder)); - } - - @Override - public void encode(KeyedWorkItem value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - Coder.Context nestedContext = context.nested(); - keyCoder.encode(value.key(), outStream, nestedContext); - timersCoder.encode(value.timersIterable(), outStream, nestedContext); - elemsCoder.encode(value.elementsIterable(), outStream, nestedContext); - } - - @Override - public KeyedWorkItem decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - Coder.Context nestedContext = context.nested(); - K key = keyCoder.decode(inStream, nestedContext); - Iterable timers = timersCoder.decode(inStream, nestedContext); - Iterable> elems = elemsCoder.decode(inStream, nestedContext); - return KeyedWorkItems.workItem(key, timers, elems); - } - - @Override - public List> getCoderArguments() { - return ImmutableList.of(keyCoder, elemCoder, windowCoder); - } - - @Override - public void verifyDeterministic() throws Coder.NonDeterministicException { - keyCoder.verifyDeterministic(); - timersCoder.verifyDeterministic(); - elemsCoder.verifyDeterministic(); - } - - /** - * {@inheritDoc}. - * - * {@link KeyedWorkItemCoder} is not consistent with equals as it can return a - * {@link KeyedWorkItem} of a type different from the originally encoded type. - */ - @Override - public boolean consistentWithEquals() { - return false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java deleted file mode 100644 index 734bd2c537..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItems.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.common.base.MoreObjects; -import com.google.common.collect.Iterables; - -import java.util.Collections; -import java.util.Objects; - -/** - * Static utility methods that provide {@link KeyedWorkItem} implementations. - */ -public class KeyedWorkItems { - /** - * Returns an implementation of {@link KeyedWorkItem} that wraps around an elements iterable. - * - * @param the key type - * @param the element type - */ - public static KeyedWorkItem elementsWorkItem( - K key, Iterable> elementsIterable) { - return new ComposedKeyedWorkItem<>(key, Collections.emptyList(), elementsIterable); - } - - /** - * Returns an implementation of {@link KeyedWorkItem} that wraps around an timers iterable. - * - * @param the key type - * @param the element type - */ - public static KeyedWorkItem timersWorkItem( - K key, Iterable timersIterable) { - return new ComposedKeyedWorkItem<>( - key, timersIterable, Collections.>emptyList()); - } - - /** - * Returns an implementation of {@link KeyedWorkItem} that wraps around - * an timers iterable and an elements iterable. - * - * @param the key type - * @param the element type - */ - public static KeyedWorkItem workItem( - K key, Iterable timersIterable, Iterable> elementsIterable) { - return new ComposedKeyedWorkItem<>(key, timersIterable, elementsIterable); - } - - /** - * A {@link KeyedWorkItem} composed of an underlying key, {@link TimerData} iterable, and element - * iterable. - */ - public static class ComposedKeyedWorkItem implements KeyedWorkItem { - private final K key; - private final Iterable timers; - private final Iterable> elements; - - private ComposedKeyedWorkItem( - K key, Iterable timers, Iterable> elements) { - this.key = key; - this.timers = timers; - this.elements = elements; - } - - @Override - public K key() { - return key; - } - - @Override - public Iterable timersIterable() { - return timers; - } - - @Override - public Iterable> elementsIterable() { - return elements; - } - - @Override - public boolean equals(Object other) { - if (other == null || !(other instanceof ComposedKeyedWorkItem)) { - return false; - } - KeyedWorkItem that = (KeyedWorkItem) other; - return Objects.equals(this.key, that.key()) - && Iterables.elementsEqual(this.timersIterable(), that.timersIterable()) - && Iterables.elementsEqual(this.elementsIterable(), that.elementsIterable()); - } - - @Override - public int hashCode() { - return Objects.hash(key, timers, elements); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(ComposedKeyedWorkItem.class) - .add("key", key) - .add("elements", elements) - .add("timers", timers) - .toString(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java deleted file mode 100644 index 721953a644..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunner.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -import org.joda.time.Instant; - -/** - * A customized {@link DoFnRunner} that handles late data dropping for - * a {@link KeyedWorkItem} input {@link DoFn}. - * - *

              It expands windows before checking data lateness. - * - *

              {@link KeyedWorkItem KeyedWorkItems} are always in empty windows. - * - * @param key type - * @param input value element type - * @param output value element type - * @param window type - */ -public class LateDataDroppingDoFnRunner - implements DoFnRunner, KV> { - private final DoFnRunner, KV> doFnRunner; - private final LateDataFilter lateDataFilter; - - public LateDataDroppingDoFnRunner( - DoFnRunner, KV> doFnRunner, - WindowingStrategy windowingStrategy, - TimerInternals timerInternals, - Aggregator droppedDueToLateness) { - this.doFnRunner = doFnRunner; - lateDataFilter = new LateDataFilter(windowingStrategy, timerInternals, droppedDueToLateness); - } - - @Override - public void startBundle() { - doFnRunner.startBundle(); - } - - @Override - public void processElement(WindowedValue> elem) { - Iterable> nonLateElements = lateDataFilter.filter( - elem.getValue().key(), elem.getValue().elementsIterable()); - KeyedWorkItem keyedWorkItem = KeyedWorkItems.workItem( - elem.getValue().key(), elem.getValue().timersIterable(), nonLateElements); - doFnRunner.processElement(elem.withValue(keyedWorkItem)); - } - - @Override - public void finishBundle() { - doFnRunner.finishBundle(); - } - - /** - * It filters late data in a {@link KeyedWorkItem}. - */ - @VisibleForTesting - static class LateDataFilter { - private final WindowingStrategy windowingStrategy; - private final TimerInternals timerInternals; - private final Aggregator droppedDueToLateness; - - public LateDataFilter( - WindowingStrategy windowingStrategy, - TimerInternals timerInternals, - Aggregator droppedDueToLateness) { - this.windowingStrategy = windowingStrategy; - this.timerInternals = timerInternals; - this.droppedDueToLateness = droppedDueToLateness; - } - - /** - * Returns an {@code Iterable>} that only contains - * non-late input elements. - */ - public Iterable> filter( - final K key, Iterable> elements) { - Iterable>> windowsExpandedElements = Iterables.transform( - elements, - new Function, Iterable>>() { - @Override - public Iterable> apply(final WindowedValue input) { - return Iterables.transform( - input.getWindows(), - new Function>() { - @Override - public WindowedValue apply(BoundedWindow window) { - return WindowedValue.of( - input.getValue(), input.getTimestamp(), window, input.getPane()); - } - }); - }}); - - Iterable> concatElements = Iterables.concat(windowsExpandedElements); - - // Bump the counter separately since we don't want multiple iterations to - // increase it multiple times. - for (WindowedValue input : concatElements) { - BoundedWindow window = Iterables.getOnlyElement(input.getWindows()); - if (canDropDueToExpiredWindow(window)) { - // The element is too late for this window. - droppedDueToLateness.addValue(1L); - WindowTracing.debug( - "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since too far behind inputWatermark:{}; outputWatermark:{}", - input.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - } - } - - Iterable> nonLateElements = Iterables.filter( - concatElements, - new Predicate>() { - @Override - public boolean apply(WindowedValue input) { - BoundedWindow window = Iterables.getOnlyElement(input.getWindows()); - if (canDropDueToExpiredWindow(window)) { - return false; - } else { - return true; - } - } - }); - return nonLateElements; - } - - /** Is {@code window} expired w.r.t. the garbage collection watermark? */ - private boolean canDropDueToExpiredWindow(BoundedWindow window) { - Instant inputWM = timerInternals.currentInputWatermarkTime(); - return window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()).isBefore(inputWM); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MapAggregatorValues.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MapAggregatorValues.java deleted file mode 100644 index a4d8ffd168..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MapAggregatorValues.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.runners.AggregatorValues; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.common.base.MoreObjects; - -import java.util.Map; - -/** - * An {@link AggregatorValues} implementation that is backed by an in-memory map. - * - * @param the output type of the {@link Aggregator} - */ -public class MapAggregatorValues extends AggregatorValues { - private final Map stepValues; - - public MapAggregatorValues(Map stepValues) { - this.stepValues = stepValues; - } - - @Override - public Map getValuesAtSteps() { - return stepValues; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(MapAggregatorValues.class) - .add("stepValues", stepValues) - .toString(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java deleted file mode 100644 index 10946ca40a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSet.java +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.SetCoder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.ValueState; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * An {@link ActiveWindowSet} for merging {@link WindowFn} implementations. - */ -public class MergingActiveWindowSet implements ActiveWindowSet { - private final WindowFn windowFn; - - /** - * Map ACTIVE and NEW windows to their state address windows. Persisted. - *

                - *
              • A NEW window has the empty set as its value. - *
              • An ACTIVE window has its (typically singleton) set of state address windows as - * its value. - *
              - */ - private final Map> activeWindowToStateAddressWindows; - - /** - * Deep clone of {@link #activeWindowToStateAddressWindows} as of last commit. - * Used to avoid writing to state if no changes have been made during the work unit. - */ - private final Map> originalActiveWindowToStateAddressWindows; - - /** - * Handle representing our state in the backend. - */ - private final ValueState>> valueState; - - public MergingActiveWindowSet(WindowFn windowFn, StateInternals state) { - this.windowFn = windowFn; - - StateTag>>> tag = - StateTags.makeSystemTagInternal(StateTags.value( - "tree", MapCoder.of(windowFn.windowCoder(), SetCoder.of(windowFn.windowCoder())))); - valueState = state.state(StateNamespaces.global(), tag); - // Little use trying to prefetch this state since the ReduceFnRunner - // is stymied until it is available. - activeWindowToStateAddressWindows = emptyIfNull(valueState.read()); - originalActiveWindowToStateAddressWindows = deepCopy(activeWindowToStateAddressWindows); - } - - @Override - public void cleanupTemporaryWindows() { - // All NEW windows can be forgotten since they must have ended up being merged into - // some other ACTIVE window. - Iterator>> iter = activeWindowToStateAddressWindows.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry> entry = iter.next(); - if (entry.getValue().isEmpty()) { - iter.remove(); - } - } - } - - @Override - public void persist() { - checkInvariants(); - if (activeWindowToStateAddressWindows.isEmpty()) { - // Force all persistent state to disappear. - valueState.clear(); - return; - } - if (activeWindowToStateAddressWindows.equals(originalActiveWindowToStateAddressWindows)) { - // No change. - return; - } - valueState.write(activeWindowToStateAddressWindows); - // No need to update originalActiveWindowToStateAddressWindows since this object is about to - // become garbage. - } - - @Override - public Set getActiveAndNewWindows() { - return activeWindowToStateAddressWindows.keySet(); - } - - @Override - public boolean isActive(W window) { - Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); - return stateAddressWindows != null && !stateAddressWindows.isEmpty(); - } - - @Override - public boolean isActiveOrNew(W window) { - return activeWindowToStateAddressWindows.containsKey(window); - } - - @Override - public void ensureWindowExists(W window) { - if (!activeWindowToStateAddressWindows.containsKey(window)) { - // Add window as NEW. - activeWindowToStateAddressWindows.put(window, new LinkedHashSet()); - } - } - - @Override - public void ensureWindowIsActive(W window) { - Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); - checkState(stateAddressWindows != null, - "Cannot ensure window %s is active since it is neither ACTIVE nor NEW", - window); - if (stateAddressWindows.isEmpty()) { - // Window was NEW, make it ACTIVE with itself as its state address window. - stateAddressWindows.add(window); - } - } - - @Override - @VisibleForTesting - public void addActiveForTesting(W window) { - if (!activeWindowToStateAddressWindows.containsKey(window)) { - // Make window ACTIVE with itself as its state address window. - Set stateAddressWindows = new LinkedHashSet<>(); - stateAddressWindows.add(window); - activeWindowToStateAddressWindows.put(window, stateAddressWindows); - } - } - - @VisibleForTesting - public void addActiveForTesting(W window, Iterable stateAddressWindows) { - if (!activeWindowToStateAddressWindows.containsKey(window)) { - activeWindowToStateAddressWindows.put(window, Sets.newLinkedHashSet(stateAddressWindows)); - } - } - - @Override - public void remove(W window) { - activeWindowToStateAddressWindows.remove(window); - } - - private class MergeContextImpl extends WindowFn.MergeContext { - private MergeCallback mergeCallback; - private final List> allToBeMerged; - private final List allMergeResults; - private final Set seen; - - public MergeContextImpl(MergeCallback mergeCallback) { - windowFn.super(); - this.mergeCallback = mergeCallback; - allToBeMerged = new ArrayList<>(); - allMergeResults = new ArrayList<>(); - seen = new HashSet<>(); - } - - @Override - public Collection windows() { - return activeWindowToStateAddressWindows.keySet(); - } - - @Override - public void merge(Collection toBeMerged, W mergeResult) throws Exception { - // The arguments have come from userland. - checkNotNull(toBeMerged); - checkNotNull(mergeResult); - List copyOfToBeMerged = new ArrayList<>(toBeMerged.size()); - boolean includesMergeResult = false; - for (W window : toBeMerged) { - checkNotNull(window); - checkState( - isActiveOrNew(window), "Expecting merge window %s to be ACTIVE or NEW", window); - if (window.equals(mergeResult)) { - includesMergeResult = true; - } - boolean notDup = seen.add(window); - checkState( - notDup, "Expecting merge window %s to appear in at most one merge set", window); - copyOfToBeMerged.add(window); - } - if (!includesMergeResult) { - checkState( - !isActive(mergeResult), "Expecting result window %s to be NEW", mergeResult); - } - allToBeMerged.add(copyOfToBeMerged); - allMergeResults.add(mergeResult); - } - - public void recordMerges() throws Exception { - for (int i = 0; i < allToBeMerged.size(); i++) { - mergeCallback.prefetchOnMerge(allToBeMerged.get(i), allMergeResults.get(i)); - } - for (int i = 0; i < allToBeMerged.size(); i++) { - mergeCallback.onMerge(allToBeMerged.get(i), allMergeResults.get(i)); - recordMerge(allToBeMerged.get(i), allMergeResults.get(i)); - } - allToBeMerged.clear(); - allMergeResults.clear(); - seen.clear(); - } - } - - @Override - public void merge(MergeCallback mergeCallback) throws Exception { - MergeContextImpl context = new MergeContextImpl(mergeCallback); - - // See what the window function does with the NEW and already ACTIVE windows. - // Entering userland. - windowFn.mergeWindows(context); - - // Actually do the merging and invoke the callbacks. - context.recordMerges(); - } - - /** - * A {@link WindowFn#mergeWindows} call has determined that {@code toBeMerged} (which must - * all be ACTIVE}) should be considered equivalent to {@code activeWindow} (which is either a - * member of {@code toBeMerged} or is a new window). Make the corresponding change in - * the active window set. - */ - private void recordMerge(Collection toBeMerged, W mergeResult) throws Exception { - // Note that mergedWriteStateAddress must predict the result of writeStateAddress - // after the corresponding merge has been applied. - // Thus we must ensure the first state address window in the merged result here is - // deterministic. - // Thus we use a linked hash set. - Set newStateAddressWindows = new LinkedHashSet<>(); - Set existingStateAddressWindows = activeWindowToStateAddressWindows.get(mergeResult); - if (existingStateAddressWindows != null) { - // Preserve all the existing state address windows for mergeResult. - newStateAddressWindows.addAll(existingStateAddressWindows); - } - - for (W other : toBeMerged) { - Set otherStateAddressWindows = activeWindowToStateAddressWindows.get(other); - checkState(otherStateAddressWindows != null, - "Window %s is not ACTIVE or NEW", other); - - for (W otherStateAddressWindow : otherStateAddressWindows) { - // Since otherTarget equiv other AND other equiv mergeResult - // THEN otherTarget equiv mergeResult. - newStateAddressWindows.add(otherStateAddressWindow); - } - activeWindowToStateAddressWindows.remove(other); - - // Now other equiv mergeResult. - } - - if (newStateAddressWindows.isEmpty()) { - // If stateAddressWindows is empty then toBeMerged must have only contained EPHEMERAL windows. - // Promote mergeResult to be ACTIVE now. - newStateAddressWindows.add(mergeResult); - } - - activeWindowToStateAddressWindows.put(mergeResult, newStateAddressWindows); - - merged(mergeResult); - } - - @Override - public void merged(W window) { - // Take just the first state address window. - Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); - checkState(stateAddressWindows != null, "Window %s is not ACTIVE", window); - W first = Iterables.getFirst(stateAddressWindows, null); - stateAddressWindows.clear(); - stateAddressWindows.add(first); - } - - /** - * Return the state address windows for ACTIVE {@code window} from which all state associated - * should be read and merged. - */ - @Override - public Set readStateAddresses(W window) { - Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); - checkState(stateAddressWindows != null, "Window %s is not ACTIVE", window); - return stateAddressWindows; - } - - /** - * Return the state address window of ACTIVE {@code window} into which all new state should be - * written. - */ - @Override - public W writeStateAddress(W window) { - Set stateAddressWindows = activeWindowToStateAddressWindows.get(window); - checkState(stateAddressWindows != null, "Window %s is not ACTIVE", window); - W result = Iterables.getFirst(stateAddressWindows, null); - checkState(result != null, "Window %s is still NEW", window); - return result; - } - - @Override - public W mergedWriteStateAddress(Collection toBeMerged, W mergeResult) { - Set stateAddressWindows = activeWindowToStateAddressWindows.get(mergeResult); - if (stateAddressWindows != null && !stateAddressWindows.isEmpty()) { - return Iterables.getFirst(stateAddressWindows, null); - } - for (W mergedWindow : toBeMerged) { - stateAddressWindows = activeWindowToStateAddressWindows.get(mergedWindow); - if (stateAddressWindows != null && !stateAddressWindows.isEmpty()) { - return Iterables.getFirst(stateAddressWindows, null); - } - } - return mergeResult; - } - - @VisibleForTesting - public void checkInvariants() { - Set knownStateAddressWindows = new HashSet<>(); - for (Map.Entry> entry : activeWindowToStateAddressWindows.entrySet()) { - W active = entry.getKey(); - checkState(!entry.getValue().isEmpty(), - "Unexpected empty state address window set for ACTIVE window %s", - active); - for (W stateAddressWindow : entry.getValue()) { - checkState(knownStateAddressWindows.add(stateAddressWindow), - "%s is in more than one state address window set", - stateAddressWindow); - } - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("MergingActiveWindowSet {\n"); - for (Map.Entry> entry : activeWindowToStateAddressWindows.entrySet()) { - W active = entry.getKey(); - Set stateAddressWindows = entry.getValue(); - if (stateAddressWindows.isEmpty()) { - sb.append(" NEW "); - sb.append(active); - sb.append('\n'); - } else { - sb.append(" ACTIVE "); - sb.append(active); - sb.append(":\n"); - for (W stateAddressWindow : stateAddressWindows) { - sb.append(" "); - sb.append(stateAddressWindow); - sb.append("\n"); - } - } - } - sb.append("}"); - return sb.toString(); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof MergingActiveWindowSet)) { - return false; - } - - @SuppressWarnings("unchecked") - MergingActiveWindowSet other = (MergingActiveWindowSet) o; - - return activeWindowToStateAddressWindows.equals(other.activeWindowToStateAddressWindows); - } - - @Override - public int hashCode() { - return Objects.hashCode(activeWindowToStateAddressWindows); - } - - /** - * Replace null {@code multimap} with empty map, and replace null entries in {@code multimap} - * with - * empty sets. - */ - private static Map> emptyIfNull(@Nullable Map> multimap) { - if (multimap == null) { - return new HashMap<>(); - } else { - for (Map.Entry> entry : multimap.entrySet()) { - if (entry.getValue() == null) { - entry.setValue(new LinkedHashSet()); - } - } - return multimap; - } - } - - /** - * Return a deep copy of {@code multimap}. - */ - private static Map> deepCopy(Map> multimap) { - Map> newMultimap = new HashMap<>(); - for (Map.Entry> entry : multimap.entrySet()) { - newMultimap.put(entry.getKey(), new LinkedHashSet<>(entry.getValue())); - } - return newMultimap; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MimeTypes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MimeTypes.java deleted file mode 100644 index 489d1832a1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MimeTypes.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** Constants representing various mime types. */ -public class MimeTypes { - public static final String TEXT = "text/plain"; - public static final String BINARY = "application/octet-stream"; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java deleted file mode 100644 index 7eb3c4aa84..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudTime; - -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Messages; -import com.google.api.services.dataflow.model.JobMessage; -import com.google.api.services.dataflow.model.ListJobMessagesResponse; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableMap; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * A helper class for monitoring jobs submitted to the service. - */ -public final class MonitoringUtil { - - private static final String GCLOUD_DATAFLOW_PREFIX = "gcloud beta dataflow"; - private static final String ENDPOINT_OVERRIDE_ENV_VAR = - "CLOUDSDK_API_ENDPOINT_OVERRIDES_DATAFLOW"; - - private static final Map DATAFLOW_STATE_TO_JOB_STATE = - ImmutableMap - .builder() - .put("JOB_STATE_UNKNOWN", State.UNKNOWN) - .put("JOB_STATE_STOPPED", State.STOPPED) - .put("JOB_STATE_RUNNING", State.RUNNING) - .put("JOB_STATE_DONE", State.DONE) - .put("JOB_STATE_FAILED", State.FAILED) - .put("JOB_STATE_CANCELLED", State.CANCELLED) - .put("JOB_STATE_UPDATED", State.UPDATED) - .build(); - - private String projectId; - private Messages messagesClient; - - /** - * An interface that can be used for defining callbacks to receive a list - * of JobMessages containing monitoring information. - */ - public interface JobMessagesHandler { - /** Process the rows. */ - void process(List messages); - } - - /** A handler that prints monitoring messages to a stream. */ - public static class PrintHandler implements JobMessagesHandler { - private PrintStream out; - - /** - * Construct the handler. - * - * @param stream The stream to write the messages to. - */ - public PrintHandler(PrintStream stream) { - out = stream; - } - - @Override - public void process(List messages) { - for (JobMessage message : messages) { - if (message.getMessageText() == null || message.getMessageText().isEmpty()) { - continue; - } - String importanceString = null; - if (message.getMessageImportance() == null) { - continue; - } else if (message.getMessageImportance().equals("JOB_MESSAGE_ERROR")) { - importanceString = "Error: "; - } else if (message.getMessageImportance().equals("JOB_MESSAGE_WARNING")) { - importanceString = "Warning: "; - } else if (message.getMessageImportance().equals("JOB_MESSAGE_BASIC")) { - importanceString = "Basic: "; - } else if (message.getMessageImportance().equals("JOB_MESSAGE_DETAILED")) { - importanceString = "Detail: "; - } else { - // TODO: Remove filtering here once getJobMessages supports minimum - // importance. - continue; - } - @Nullable Instant time = TimeUtil.fromCloudTime(message.getTime()); - if (time == null) { - out.print("UNKNOWN TIMESTAMP: "); - } else { - out.print(time + ": "); - } - if (importanceString != null) { - out.print(importanceString); - } - out.println(message.getMessageText()); - } - out.flush(); - } - } - - /** Construct a helper for monitoring. */ - public MonitoringUtil(String projectId, Dataflow dataflow) { - this(projectId, dataflow.projects().jobs().messages()); - } - - // @VisibleForTesting - MonitoringUtil(String projectId, Messages messagesClient) { - this.projectId = projectId; - this.messagesClient = messagesClient; - } - - /** - * Comparator for sorting rows in increasing order based on timestamp. - */ - public static class TimeStampComparator implements Comparator { - @Override - public int compare(JobMessage o1, JobMessage o2) { - @Nullable Instant t1 = fromCloudTime(o1.getTime()); - if (t1 == null) { - return -1; - } - @Nullable Instant t2 = fromCloudTime(o2.getTime()); - if (t2 == null) { - return 1; - } - return t1.compareTo(t2); - } - } - - /** - * Return job messages sorted in ascending order by timestamp. - * @param jobId The id of the job to get the messages for. - * @param startTimestampMs Return only those messages with a - * timestamp greater than this value. - * @return collection of messages - * @throws IOException - */ - public ArrayList getJobMessages( - String jobId, long startTimestampMs) throws IOException { - // TODO: Allow filtering messages by importance - Instant startTimestamp = new Instant(startTimestampMs); - ArrayList allMessages = new ArrayList<>(); - String pageToken = null; - while (true) { - Messages.List listRequest = messagesClient.list(projectId, jobId); - if (pageToken != null) { - listRequest.setPageToken(pageToken); - } - ListJobMessagesResponse response = listRequest.execute(); - - if (response == null || response.getJobMessages() == null) { - return allMessages; - } - - for (JobMessage m : response.getJobMessages()) { - @Nullable Instant timestamp = fromCloudTime(m.getTime()); - if (timestamp == null) { - continue; - } - if (timestamp.isAfter(startTimestamp)) { - allMessages.add(m); - } - } - - if (response.getNextPageToken() == null) { - break; - } else { - pageToken = response.getNextPageToken(); - } - } - - Collections.sort(allMessages, new TimeStampComparator()); - return allMessages; - } - - public static String getJobMonitoringPageURL(String projectName, String jobId) { - try { - // Project name is allowed in place of the project id: the user will be redirected to a URL - // that has the project name replaced with project id. - return String.format( - "https://console.developers.google.com/project/%s/dataflow/job/%s", - URLEncoder.encode(projectName, "UTF-8"), - URLEncoder.encode(jobId, "UTF-8")); - } catch (UnsupportedEncodingException e) { - // Should never happen. - throw new AssertionError("UTF-8 encoding is not supported by the environment", e); - } - } - - public static String getGcloudCancelCommand(DataflowPipelineOptions options, String jobId) { - - // If using a different Dataflow API than default, prefix command with an API override. - String dataflowApiOverridePrefix = ""; - String apiUrl = options.getDataflowClient().getBaseUrl(); - if (!apiUrl.equals(Dataflow.DEFAULT_BASE_URL)) { - dataflowApiOverridePrefix = String.format("%s=%s ", ENDPOINT_OVERRIDE_ENV_VAR, apiUrl); - } - - // Assemble cancel command from optional prefix and project/job parameters. - return String.format("%s%s jobs --project=%s cancel %s", - dataflowApiOverridePrefix, GCLOUD_DATAFLOW_PREFIX, options.getProject(), jobId); - } - - public static State toState(String stateName) { - return MoreObjects.firstNonNull(DATAFLOW_STATE_TO_JOB_STATE.get(stateName), - State.UNKNOWN); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java deleted file mode 100644 index 73386e12c5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MovingFunction.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.transforms.Combine; -import java.util.Arrays; - -/** - * Keep track of the moving minimum/maximum/sum of sampled long values. The minimum/maximum/sum - * is over at most the last {@link #samplePeriodMs}, and is updated every - * {@link #sampleUpdateMs}. - */ -public class MovingFunction { - /** - * How frequently to update the moving function, in ms. - */ - private final long sampleUpdateMs; - - /** - * How many buckets are considered 'significant'? - */ - private final int numSignificantBuckets; - - /** - * How many samples are considered 'significant'? - */ - private final int numSignificantSamples; - - /** - * Function for combining sample values. - */ - private final Combine.BinaryCombineLongFn function; - - /** - * Minimum/maximum/sum of all values per bucket. - */ - private final long[] buckets; - - /** - * How many samples have been added to each bucket. - */ - private final int[] numSamples; - - /** - * Time of start of current bucket. - */ - private long currentMsSinceEpoch; - - /** - * Index of bucket corresponding to above timestamp, or -1 if no entries. - */ - private int currentIndex; - - public MovingFunction(long samplePeriodMs, long sampleUpdateMs, - int numSignificantBuckets, int numSignificantSamples, - Combine.BinaryCombineLongFn function) { - this.sampleUpdateMs = sampleUpdateMs; - this.numSignificantBuckets = numSignificantBuckets; - this.numSignificantSamples = numSignificantSamples; - this.function = function; - int n = (int) (samplePeriodMs / sampleUpdateMs); - buckets = new long[n]; - Arrays.fill(buckets, function.identity()); - numSamples = new int[n]; - Arrays.fill(numSamples, 0); - currentMsSinceEpoch = -1; - currentIndex = -1; - } - - /** - * Flush stale values. - */ - private void flush(long nowMsSinceEpoch) { - checkArgument(nowMsSinceEpoch >= 0, "Only positive timestamps supported"); - if (currentIndex < 0) { - currentMsSinceEpoch = nowMsSinceEpoch - (nowMsSinceEpoch % sampleUpdateMs); - currentIndex = 0; - } - checkArgument(nowMsSinceEpoch >= currentMsSinceEpoch, "Attempting to move backwards"); - int newBuckets = - Math.min((int) ((nowMsSinceEpoch - currentMsSinceEpoch) / sampleUpdateMs), - buckets.length); - while (newBuckets > 0) { - currentIndex = (currentIndex + 1) % buckets.length; - buckets[currentIndex] = function.identity(); - numSamples[currentIndex] = 0; - newBuckets--; - currentMsSinceEpoch += sampleUpdateMs; - } - } - - /** - * Add {@code value} at {@code nowMsSinceEpoch}. - */ - public void add(long nowMsSinceEpoch, long value) { - flush(nowMsSinceEpoch); - buckets[currentIndex] = function.apply(buckets[currentIndex], value); - numSamples[currentIndex]++; - } - - /** - * Return the minimum/maximum/sum of all retained values within samplePeriodMs - * of {@code nowMsSinceEpoch}. - */ - public long get(long nowMsSinceEpoch) { - flush(nowMsSinceEpoch); - long result = function.identity(); - for (int i = 0; i < buckets.length; i++) { - result = function.apply(result, buckets[i]); - } - return result; - } - - /** - * Is the current result 'significant'? Ie is it drawn from enough buckets - * or from enough samples? - */ - public boolean isSignificant() { - int totalSamples = 0; - int activeBuckets = 0; - for (int i = 0; i < buckets.length; i++) { - totalSamples += numSamples[i]; - if (numSamples[i] > 0) { - activeBuckets++; - } - } - return activeBuckets >= numSignificantBuckets || totalSamples >= numSignificantSamples; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetector.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetector.java deleted file mode 100644 index 51e65ab878..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetector.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * An object for detecting illegal mutations. - * - *

              The {@link AutoCloseable} aspect of this interface allows use in a try-with-resources - * style, where the implementing class may choose to perform a final mutation check upon - * {@link #close()}. - */ -public interface MutationDetector extends AutoCloseable { - /** - * @throws IllegalMutationException if illegal mutations are detected. - */ - void verifyUnmodified(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java deleted file mode 100644 index 7558a0e19a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/MutationDetectors.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; - -import java.util.Arrays; -import java.util.Objects; - -/** - * Static methods for creating and working with {@link MutationDetector}. - */ -public class MutationDetectors { - - private MutationDetectors() {} - - /** - * Creates a new {@code MutationDetector} for the provided {@code value} that uses the provided - * {@link Coder} to perform deep copies and comparisons by serializing and deserializing values. - * - *

              It is permissible for {@code value} to be {@code null}. Since {@code null} is immutable, - * the mutation check will always succeed. - */ - public static MutationDetector forValueWithCoder(T value, Coder coder) - throws CoderException { - if (value == null) { - return noopMutationDetector(); - } else { - return new CodedValueMutationDetector<>(value, coder); - } - } - - /** - * Creates a new {@code MutationDetector} that always succeeds. - * - *

              This is useful, for example, for providing a very efficient mutation detector for a value - * which is already immutable by design. - */ - public static MutationDetector noopMutationDetector() { - return new NoopMutationDetector(); - } - - /** - * A {@link MutationDetector} for {@code null}, which is immutable. - */ - private static class NoopMutationDetector implements MutationDetector { - - @Override - public void verifyUnmodified() { } - - @Override - public void close() { } - } - - /** - * Given a value of type {@code T} and a {@link Coder} for that type, provides facilities to save - * check that the value has not changed. - * - * @param the type of values checked for mutation - */ - private static class CodedValueMutationDetector implements MutationDetector { - - private final Coder coder; - - /** - * A saved pointer to an in-memory value provided upon construction, which we will check for - * forbidden mutations. - */ - private final T possiblyModifiedObject; - - /** - * A saved encoded copy of the same value as {@link #possiblyModifiedObject}. Naturally, it - * will not change if {@link #possiblyModifiedObject} is mutated. - */ - private final byte[] encodedOriginalObject; - - /** - * The object decoded from {@link #encodedOriginalObject}. It will be used during every call to - * {@link #verifyUnmodified}, which could be called many times throughout the lifetime of this - * {@link CodedValueMutationDetector}. - */ - private final T clonedOriginalObject; - - /** - * Create a mutation detector for the provided {@code value}, using the provided {@link Coder} - * for cloning and checking serialized forms for equality. - */ - public CodedValueMutationDetector(T value, Coder coder) throws CoderException { - this.coder = coder; - this.possiblyModifiedObject = value; - this.encodedOriginalObject = CoderUtils.encodeToByteArray(coder, value); - this.clonedOriginalObject = CoderUtils.decodeFromByteArray(coder, encodedOriginalObject); - } - - @Override - public void verifyUnmodified() { - try { - verifyUnmodifiedThrowingCheckedExceptions(); - } catch (CoderException exn) { - throw new RuntimeException(exn); - } - } - - private void verifyUnmodifiedThrowingCheckedExceptions() throws CoderException { - // If either object believes they are equal, we trust that and short-circuit deeper checks. - if (Objects.equals(possiblyModifiedObject, clonedOriginalObject) - || Objects.equals(clonedOriginalObject, possiblyModifiedObject)) { - return; - } - - // Since retainedObject is in general an instance of a subclass of T, when it is cloned to - // clonedObject using a Coder, the two will generally be equivalent viewed as a T, but in - // general neither retainedObject.equals(clonedObject) nor clonedObject.equals(retainedObject) - // will hold. - // - // For example, CoderUtils.clone(IterableCoder, IterableSubclass) will - // produce an ArrayList with the same contents as the IterableSubclass, but the - // latter will quite reasonably not consider itself equivalent to an ArrayList (and vice - // versa). - // - // To enable a reasonable comparison, we clone retainedObject again here, converting it to - // the same sort of T that the Coder output when it created clonedObject. - T clonedPossiblyModifiedObject = CoderUtils.clone(coder, possiblyModifiedObject); - - // If deepEquals() then we trust the equals implementation. - // This deliberately allows fields to escape this check. - if (Objects.deepEquals(clonedPossiblyModifiedObject, clonedOriginalObject)) { - return; - } - - // If not deepEquals(), the class may just have a poor equals() implementation. - // So we next try checking their serialized forms. We re-serialize instead of checking - // encodedObject, because the Coder may treat it differently. - // - // For example, an unbounded Iterable will be encoded in an unbounded way, but decoded into an - // ArrayList, which will then be re-encoded in a bounded format. So we really do need to - // encode-decode-encode retainedObject. - if (Arrays.equals( - CoderUtils.encodeToByteArray(coder, clonedOriginalObject), - CoderUtils.encodeToByteArray(coder, clonedPossiblyModifiedObject))) { - return; - } - - // If we got here, then they are not deepEquals() and do not have deepEquals() encodings. - // Even if there is some conceptual sense in which the objects are equivalent, it has not - // been adequately expressed in code. - illegalMutation(clonedOriginalObject, clonedPossiblyModifiedObject); - } - - private void illegalMutation(T previousValue, T newValue) throws CoderException { - throw new IllegalMutationException( - String.format("Value %s mutated illegally, new value was %s." - + " Encoding was %s, now %s.", - previousValue, newValue, - CoderUtils.encodeToBase64(coder, previousValue), - CoderUtils.encodeToBase64(coder, newValue)), - previousValue, newValue); - } - - @Override - public void close() { - verifyUnmodified(); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java deleted file mode 100644 index 1270f01423..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonEmptyPanes.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.ReadableState; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateMerging; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; - -/** - * Tracks which windows have non-empty panes. Specifically, which windows have new elements since - * their last triggering. - * - * @param The kind of windows being tracked. - */ -public abstract class NonEmptyPanes { - - static NonEmptyPanes create( - WindowingStrategy strategy, ReduceFn reduceFn) { - if (strategy.getMode() == AccumulationMode.DISCARDING_FIRED_PANES) { - return new DiscardingModeNonEmptyPanes<>(reduceFn); - } else { - return new GeneralNonEmptyPanes<>(); - } - } - - /** - * Record that some content has been added to the window in {@code context}, and therefore the - * current pane is not empty. - */ - public abstract void recordContent(StateAccessor context); - - /** - * Record that the given pane is empty. - */ - public abstract void clearPane(StateAccessor state); - - /** - * Return true if the current pane for the window in {@code context} is empty. - */ - public abstract ReadableState isEmpty(StateAccessor context); - - /** - * Prefetch in preparation for merging. - */ - public abstract void prefetchOnMerge(MergingStateAccessor state); - - /** - * Eagerly merge backing state. - */ - public abstract void onMerge(MergingStateAccessor context); - - /** - * An implementation of {@code NonEmptyPanes} optimized for use with discarding mode. Uses the - * presence of data in the accumulation buffer to record non-empty panes. - */ - private static class DiscardingModeNonEmptyPanes - extends NonEmptyPanes { - - private ReduceFn reduceFn; - - private DiscardingModeNonEmptyPanes(ReduceFn reduceFn) { - this.reduceFn = reduceFn; - } - - @Override - public ReadableState isEmpty(StateAccessor state) { - return reduceFn.isEmpty(state); - } - - @Override - public void recordContent(StateAccessor state) { - // Nothing to do -- the reduceFn is tracking contents - } - - @Override - public void clearPane(StateAccessor state) { - // Nothing to do -- the reduceFn is tracking contents - } - - @Override - public void prefetchOnMerge(MergingStateAccessor state) { - // Nothing to do -- the reduceFn is tracking contents - } - - @Override - public void onMerge(MergingStateAccessor context) { - // Nothing to do -- the reduceFn is tracking contents - } - } - - /** - * An implementation of {@code NonEmptyPanes} for general use. - */ - private static class GeneralNonEmptyPanes - extends NonEmptyPanes { - - private static final StateTag> - PANE_ADDITIONS_TAG = - StateTags.makeSystemTagInternal(StateTags.combiningValueFromInputInternal( - "count", VarLongCoder.of(), new Sum.SumLongFn())); - - @Override - public void recordContent(StateAccessor state) { - state.access(PANE_ADDITIONS_TAG).add(1L); - } - - @Override - public void clearPane(StateAccessor state) { - state.access(PANE_ADDITIONS_TAG).clear(); - } - - @Override - public ReadableState isEmpty(StateAccessor state) { - return state.access(PANE_ADDITIONS_TAG).isEmpty(); - } - - @Override - public void prefetchOnMerge(MergingStateAccessor state) { - StateMerging.prefetchCombiningValues(state, PANE_ADDITIONS_TAG); - } - - @Override - public void onMerge(MergingStateAccessor context) { - StateMerging.mergeCombiningValues(context, PANE_ADDITIONS_TAG); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java deleted file mode 100644 index 544c1149b6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NonMergingActiveWindowSet.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableSet; - -import java.util.Collection; -import java.util.Set; - -/** - * Implementation of {@link ActiveWindowSet} used with {@link WindowFn WindowFns} that don't - * support - * merging. - * - * @param the types of windows being managed - */ -public class NonMergingActiveWindowSet implements ActiveWindowSet { - @Override - public void cleanupTemporaryWindows() {} - - @Override - public void persist() {} - - @Override - public Set getActiveAndNewWindows() { - // Only supported when merging. - throw new java.lang.UnsupportedOperationException(); - } - - @Override - public boolean isActive(W window) { - // Windows should never disappear, since we don't support merging. - return true; - } - - @Override - public boolean isActiveOrNew(W window) { - return true; - } - - @Override - public void ensureWindowExists(W window) {} - - @Override - public void ensureWindowIsActive(W window) {} - - @Override - @VisibleForTesting - public void addActiveForTesting(W window) {} - - @Override - public void remove(W window) {} - - @Override - public void merge(MergeCallback mergeCallback) throws Exception {} - - @Override - public void merged(W window) {} - - @Override - public Set readStateAddresses(W window) { - return ImmutableSet.of(window); - } - - @Override - public W writeStateAddress(W window) { - return window; - } - - @Override - public W mergedWriteStateAddress(Collection toBeMerged, W mergeResult) { - return mergeResult; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopCredentialFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopCredentialFactory.java deleted file mode 100644 index 9ef4c2eb09..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopCredentialFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -/** - * Construct an oauth credential to be used by the SDK and the SDK workers. - * Always returns a null Credential object. - */ -public class NoopCredentialFactory implements CredentialFactory { - public static NoopCredentialFactory fromOptions(PipelineOptions options) { - return new NoopCredentialFactory(); - } - - @Override - public Credential getCredential() throws IOException, GeneralSecurityException { - return null; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopPathValidator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopPathValidator.java deleted file mode 100644 index 00abbb146f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NoopPathValidator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -/** - * Noop implementation of {@link PathValidator}. All paths are allowed and returned unchanged. - */ -public class NoopPathValidator implements PathValidator { - - private NoopPathValidator() { - } - - public static PathValidator fromOptions( - @SuppressWarnings("unused") PipelineOptions options) { - return new NoopPathValidator(); - } - - @Override - public String validateInputFilePatternSupported(String filepattern) { - return filepattern; - } - - @Override - public String validateOutputFilePrefixSupported(String filePrefix) { - return filePrefix; - } - - @Override - public String verifyPath(String path) { - return path; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NullSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NullSideInputReader.java deleted file mode 100644 index 0fc264606f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/NullSideInputReader.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.Sets; - -import java.util.Collections; -import java.util.Set; - -/** - * A {@link SideInputReader} representing a well-defined set of views, but not storing - * any values for them. Used to check if a side input is present when the data itself - * comes from elsewhere. - */ -public class NullSideInputReader implements SideInputReader { - - private Set> views; - - public static NullSideInputReader empty() { - return new NullSideInputReader(Collections.>emptySet()); - } - - public static NullSideInputReader of(Iterable> views) { - return new NullSideInputReader(views); - } - - private NullSideInputReader(Iterable> views) { - this.views = Sets.newHashSet(views); - } - - @Override - public T get(PCollectionView view, BoundedWindow window) { - throw new IllegalArgumentException("cannot call NullSideInputReader.get()"); - } - - @Override - public boolean isEmpty() { - return views.isEmpty(); - } - - @Override - public boolean contains(PCollectionView view) { - return views.contains(view); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java deleted file mode 100644 index baa505b923..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/OutputReference.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.json.GenericJson; -import com.google.api.client.util.Key; - -/** - * A representation used by {@link com.google.api.services.dataflow.model.Step}s - * to reference the output of other {@code Step}s. - */ -public final class OutputReference extends GenericJson { - @Key("@type") - public final String type = "OutputReference"; - - @Key("step_name") - private final String stepName; - - @Key("output_name") - private final String outputName; - - public OutputReference(String stepName, String outputName) { - this.stepName = checkNotNull(stepName); - this.outputName = checkNotNull(outputName); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java deleted file mode 100644 index 7cf636eb63..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViewWindow.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.util.Objects; - -/** - * A pair of a {@link PCollectionView} and a {@link BoundedWindow}, which can - * be thought of as window "of" the view. This is a value class for use e.g. - * as a compound cache key. - * - * @param the type of the underlying PCollectionView - */ -public final class PCollectionViewWindow { - - private final PCollectionView view; - private final BoundedWindow window; - - private PCollectionViewWindow(PCollectionView view, BoundedWindow window) { - this.view = view; - this.window = window; - } - - public static PCollectionViewWindow of(PCollectionView view, BoundedWindow window) { - return new PCollectionViewWindow<>(view, window); - } - - public PCollectionView getView() { - return view; - } - - public BoundedWindow getWindow() { - return window; - } - - @Override - public boolean equals(Object otherObject) { - if (!(otherObject instanceof PCollectionViewWindow)) { - return false; - } - @SuppressWarnings("unchecked") - PCollectionViewWindow other = (PCollectionViewWindow) otherObject; - return getView().equals(other.getView()) && getWindow().equals(other.getWindow()); - } - - @Override - public int hashCode() { - return Objects.hash(getView(), getWindow()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java deleted file mode 100644 index 7e735473c3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PCollectionViews.java +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.InvalidWindows; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PValueBase; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; - -import javax.annotation.Nullable; - -/** - * Implementations of {@link PCollectionView} shared across the SDK. - * - *

              For internal use only, subject to change. - */ -public class PCollectionViews { - - /** - * Returns a {@code PCollectionView} capable of processing elements encoded using the provided - * {@link Coder} and windowed using the provided * {@link WindowingStrategy}. - * - *

              If {@code hasDefault} is {@code true}, then the view will take on the value - * {@code defaultValue} for any empty windows. - */ - public static PCollectionView singletonView( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - boolean hasDefault, - T defaultValue, - Coder valueCoder) { - return new SingletonPCollectionView<>( - pipeline, windowingStrategy, hasDefault, defaultValue, valueCoder); - } - - /** - * Returns a {@code PCollectionView>} capable of processing elements encoded using the - * provided {@link Coder} and windowed using the provided {@link WindowingStrategy}. - */ - public static PCollectionView> iterableView( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - Coder valueCoder) { - return new IterablePCollectionView<>(pipeline, windowingStrategy, valueCoder); - } - - /** - * Returns a {@code PCollectionView>} capable of processing elements encoded using the - * provided {@link Coder} and windowed using the provided {@link WindowingStrategy}. - */ - public static PCollectionView> listView( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - Coder valueCoder) { - return new ListPCollectionView<>(pipeline, windowingStrategy, valueCoder); - } - - /** - * Returns a {@code PCollectionView>} capable of processing elements encoded using the - * provided {@link Coder} and windowed using the provided {@link WindowingStrategy}. - */ - public static PCollectionView> mapView( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - Coder> valueCoder) { - - return new MapPCollectionView(pipeline, windowingStrategy, valueCoder); - } - - /** - * Returns a {@code PCollectionView>>} capable of processing elements encoded - * using the provided {@link Coder} and windowed using the provided {@link WindowingStrategy}. - */ - public static PCollectionView>> multimapView( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - Coder> valueCoder) { - return new MultimapPCollectionView(pipeline, windowingStrategy, valueCoder); - } - - /** - * Implementation of conversion of singleton {@code Iterable>} to {@code T}. - * - *

              For internal use only. - * - *

              Instantiate via {@link PCollectionViews#singletonView}. - */ - public static class SingletonPCollectionView - extends PCollectionViewBase { - @Nullable private byte[] encodedDefaultValue; - @Nullable private transient T defaultValue; - @Nullable private Coder valueCoder; - private boolean hasDefault; - - private SingletonPCollectionView( - Pipeline pipeline, WindowingStrategy windowingStrategy, - boolean hasDefault, T defaultValue, Coder valueCoder) { - super(pipeline, windowingStrategy, valueCoder); - this.hasDefault = hasDefault; - this.defaultValue = defaultValue; - this.valueCoder = valueCoder; - if (hasDefault) { - try { - this.encodedDefaultValue = CoderUtils.encodeToByteArray(valueCoder, defaultValue); - } catch (IOException e) { - throw new RuntimeException("Unexpected IOException: ", e); - } - } - } - - /** - * Returns the default value that was specified. - * - *

              For internal use only. - * - * @throws NoSuchElementException if no default was specified. - */ - public T getDefaultValue() { - if (!hasDefault) { - throw new NoSuchElementException("Empty PCollection accessed as a singleton view."); - } - // Lazily decode the default value once - synchronized (this) { - if (encodedDefaultValue != null) { - try { - defaultValue = CoderUtils.decodeFromByteArray(valueCoder, encodedDefaultValue); - encodedDefaultValue = null; - } catch (IOException e) { - throw new RuntimeException("Unexpected IOException: ", e); - } - } - } - return defaultValue; - } - - @Override - protected T fromElements(Iterable> contents) { - try { - return Iterables.getOnlyElement(contents).getValue(); - } catch (NoSuchElementException exc) { - return getDefaultValue(); - } catch (IllegalArgumentException exc) { - throw new IllegalArgumentException( - "PCollection with more than one element " - + "accessed as a singleton view."); - } - } - } - - /** - * Implementation of conversion {@code Iterable>} to {@code Iterable}. - * - *

              For internal use only. - * - *

              Instantiate via {@link PCollectionViews#iterableView}. - */ - public static class IterablePCollectionView - extends PCollectionViewBase, W> { - private IterablePCollectionView( - Pipeline pipeline, WindowingStrategy windowingStrategy, Coder valueCoder) { - super(pipeline, windowingStrategy, valueCoder); - } - - @Override - protected Iterable fromElements(Iterable> contents) { - return Iterables.unmodifiableIterable( - Iterables.transform(contents, new Function, T>() { - @SuppressWarnings("unchecked") - @Override - public T apply(WindowedValue input) { - return input.getValue(); - } - })); - } - } - - /** - * Implementation of conversion {@code Iterable>} to {@code List}. - * - *

              For internal use only. - * - *

              Instantiate via {@link PCollectionViews#listView}. - */ - public static class ListPCollectionView - extends PCollectionViewBase, W> { - private ListPCollectionView( - Pipeline pipeline, WindowingStrategy windowingStrategy, Coder valueCoder) { - super(pipeline, windowingStrategy, valueCoder); - } - - @Override - protected List fromElements(Iterable> contents) { - return ImmutableList.copyOf( - Iterables.transform(contents, new Function, T>() { - @SuppressWarnings("unchecked") - @Override - public T apply(WindowedValue input) { - return input.getValue(); - } - })); - } - } - - /** - * Implementation of conversion {@code Iterable>>} - * to {@code Map>}. - * - *

              For internal use only. - */ - public static class MultimapPCollectionView - extends PCollectionViewBase, Map>, W> { - private MultimapPCollectionView( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - Coder> valueCoder) { - super(pipeline, windowingStrategy, valueCoder); - } - - @Override - protected Map> fromElements(Iterable>> elements) { - Multimap multimap = HashMultimap.create(); - for (WindowedValue> elem : elements) { - KV kv = elem.getValue(); - multimap.put(kv.getKey(), kv.getValue()); - } - // Safe covariant cast that Java cannot express without rawtypes, even with unchecked casts - @SuppressWarnings({"unchecked", "rawtypes"}) - Map> resultMap = (Map) multimap.asMap(); - return Collections.unmodifiableMap(resultMap); - } - } - - /** - * Implementation of conversion {@code Iterable>} with - * one value per key to {@code Map}. - * - *

              For internal use only. - */ - public static class MapPCollectionView - extends PCollectionViewBase, Map, W> { - private MapPCollectionView( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - Coder> valueCoder) { - super(pipeline, windowingStrategy, valueCoder); - } - - /** - * Input iterable must actually be {@code Iterable>>}. - */ - @Override - protected Map fromElements(Iterable>> elements) { - Map map = new HashMap<>(); - for (WindowedValue> elem : elements) { - KV kv = elem.getValue(); - if (map.containsKey(kv.getKey())) { - throw new IllegalArgumentException("Duplicate values for " + kv.getKey()); - } - map.put(kv.getKey(), kv.getValue()); - } - return Collections.unmodifiableMap(map); - } - } - - /** - * A base class for {@link PCollectionView} implementations, with additional type parameters - * that are not visible at pipeline assembly time when the view is used as a side input. - */ - private abstract static class PCollectionViewBase - extends PValueBase - implements PCollectionView { - /** A unique tag for the view, typed according to the elements underlying the view. */ - private TupleTag>> tag; - - /** The windowing strategy for the PCollection underlying the view. */ - private WindowingStrategy windowingStrategy; - - /** The coder for the elements underlying the view. */ - private Coder>> coder; - - /** - * Implement this to complete the implementation. It is a conversion function from - * all of the elements of the underlying {@link PCollection} to the value of the view. - */ - protected abstract ViewT fromElements(Iterable> elements); - - /** - * Call this constructor to initialize the fields for which this base class provides - * boilerplate accessors. - */ - protected PCollectionViewBase( - Pipeline pipeline, - TupleTag>> tag, - WindowingStrategy windowingStrategy, - Coder valueCoder) { - super(pipeline); - if (windowingStrategy.getWindowFn() instanceof InvalidWindows) { - throw new IllegalArgumentException("WindowFn of PCollectionView cannot be InvalidWindows"); - } - this.tag = tag; - this.windowingStrategy = windowingStrategy; - this.coder = - IterableCoder.of(WindowedValue.getFullCoder( - valueCoder, windowingStrategy.getWindowFn().windowCoder())); - } - - /** - * Call this constructor to initialize the fields for which this base class provides - * boilerplate accessors, with an auto-generated tag. - */ - protected PCollectionViewBase( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - Coder valueCoder) { - this(pipeline, new TupleTag>>(), windowingStrategy, valueCoder); - } - - /** - * For serialization only. Do not use directly. Subclasses should call from their own - * protected no-argument constructor. - */ - @SuppressWarnings("unused") // used for serialization - protected PCollectionViewBase() { - super(); - } - - @Override - public ViewT fromIterableInternal(Iterable> elements) { - // Safe cast: it is required that the rest of the SDK maintain the invariant - // that a PCollectionView is only provided an iterable for the elements of an - // appropriately typed PCollection. - @SuppressWarnings({"rawtypes", "unchecked"}) - Iterable> typedElements = (Iterable) elements; - return fromElements(typedElements); - } - - /** - * Returns a unique {@link TupleTag} identifying this {@link PCollectionView}. - * - *

              For internal use only by runner implementors. - */ - @Override - public TupleTag>> getTagInternal() { - // Safe cast: It is required that the rest of the SDK maintain the invariant that - // this tag is only used to access the contents of an appropriately typed underlying - // PCollection - @SuppressWarnings({"rawtypes", "unchecked"}) - TupleTag>> untypedTag = (TupleTag) tag; - return untypedTag; - } - - /** - * Returns the {@link WindowingStrategy} of this {@link PCollectionView}, which should - * be that of the underlying {@link PCollection}. - * - *

              For internal use only by runner implementors. - */ - @Override - public WindowingStrategy getWindowingStrategyInternal() { - return windowingStrategy; - } - - @Override - public Coder>> getCoderInternal() { - // Safe cast: It is required that the rest of the SDK only use this untyped coder - // for the elements of an appropriately typed underlying PCollection. - @SuppressWarnings({"rawtypes", "unchecked"}) - Coder>> untypedCoder = (Coder) coder; - return untypedCoder; - } - - @Override - public int hashCode() { - return Objects.hash(tag); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof PCollectionView) || other == null) { - return false; - } - @SuppressWarnings("unchecked") - PCollectionView otherView = (PCollectionView) other; - return tag.equals(otherView.getTagInternal()); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this).add("tag", tag).toString(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PTuple.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PTuple.java deleted file mode 100644 index 5b87b5cf88..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PTuple.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * A {@code PTuple} is an immutable tuple of - * heterogeneously-typed values, "keyed" by {@link TupleTag}s. - * - *

              PTuples can be created and accessed like follows: - *

               {@code
              - * String v1 = ...;
              - * Integer v2 = ...;
              - * Iterable v3 = ...;
              - *
              - * // Create TupleTags for each of the values to put in the
              - * // PTuple (the type of the TupleTag enables tracking the
              - * // static type of each of the values in the PTuple):
              - * TupleTag tag1 = new TupleTag<>();
              - * TupleTag tag2 = new TupleTag<>();
              - * TupleTag> tag3 = new TupleTag<>();
              - *
              - * // Create a PTuple with three values:
              - * PTuple povs =
              - *     PTuple.of(tag1, v1)
              - *         .and(tag2, v2)
              - *         .and(tag3, v3);
              - *
              - * // Create an empty PTuple:
              - * Pipeline p = ...;
              - * PTuple povs2 = PTuple.empty(p);
              - *
              - * // Get values out of a PTuple, using the same tags
              - * // that were used to put them in:
              - * Integer vX = povs.get(tag2);
              - * String vY = povs.get(tag1);
              - * Iterable vZ = povs.get(tag3);
              - *
              - * // Get a map of all values in a PTuple:
              - * Map, ?> allVs = povs.getAll();
              - * } 
              - */ -public class PTuple { - /** - * Returns an empty PTuple. - * - *

              Longer PTuples can be created by calling - * {@link #and} on the result. - */ - public static PTuple empty() { - return new PTuple(); - } - - /** - * Returns a singleton PTuple containing the given - * value keyed by the given TupleTag. - * - *

              Longer PTuples can be created by calling - * {@link #and} on the result. - */ - public static PTuple of(TupleTag tag, V value) { - return empty().and(tag, value); - } - - /** - * Returns a new PTuple that has all the values and - * tags of this PTuple plus the given value and tag. - * - *

              The given TupleTag should not already be mapped to a - * value in this PTuple. - */ - public PTuple and(TupleTag tag, V value) { - Map, Object> newMap = new LinkedHashMap, Object>(); - newMap.putAll(valueMap); - newMap.put(tag, value); - return new PTuple(newMap); - } - - /** - * Returns whether this PTuple contains a value with - * the given tag. - */ - public boolean has(TupleTag tag) { - return valueMap.containsKey(tag); - } - - /** - * Returns true if this {@code PTuple} is empty. - */ - public boolean isEmpty() { - return valueMap.isEmpty(); - } - - /** - * Returns the value with the given tag in this - * PTuple. Throws IllegalArgumentException if there is no - * such value, i.e., {@code !has(tag)}. - */ - public V get(TupleTag tag) { - if (!has(tag)) { - throw new IllegalArgumentException( - "TupleTag not found in this PTuple"); - } - @SuppressWarnings("unchecked") - V value = (V) valueMap.get(tag); - return value; - } - - /** - * Returns an immutable Map from TupleTag to corresponding - * value, for all the members of this PTuple. - */ - public Map, ?> getAll() { - return valueMap; - } - - - ///////////////////////////////////////////////////////////////////////////// - // Internal details below here. - - private final Map, ?> valueMap; - - @SuppressWarnings("rawtypes") - private PTuple() { - this(new LinkedHashMap()); - } - - private PTuple(Map, ?> valueMap) { - this.valueMap = Collections.unmodifiableMap(valueMap); - } - - /** - * Returns a PTuple with each of the given tags mapping - * to the corresponding value. - * - *

              For internal use only. - */ - public static PTuple ofInternal(Map, ?> valueMap) { - return new PTuple(valueMap); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java deleted file mode 100644 index d5f0e3f099..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PackageUtil.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.util.BackOff; -import com.google.api.client.util.Sleeper; -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.cloud.hadoop.util.ApiErrorExtractor; -import com.google.common.hash.Funnels; -import com.google.common.hash.Hasher; -import com.google.common.hash.Hashing; -import com.google.common.io.CountingOutputStream; -import com.google.common.io.Files; - -import com.fasterxml.jackson.core.Base64Variants; - -import org.joda.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Objects; - -/** Helper routines for packages. */ -public class PackageUtil { - private static final Logger LOG = LoggerFactory.getLogger(PackageUtil.class); - /** - * A reasonable upper bound on the number of jars required to launch a Dataflow job. - */ - public static final int SANE_CLASSPATH_SIZE = 1000; - /** - * The initial interval to use between package staging attempts. - */ - private static final Duration INITIAL_BACKOFF_INTERVAL = Duration.standardSeconds(5); - /** - * The maximum number of retries when staging a file. - */ - private static final int MAX_RETRIES = 4; - - private static final FluentBackoff BACKOFF_FACTORY = - FluentBackoff.DEFAULT - .withMaxRetries(MAX_RETRIES).withInitialBackoff(INITIAL_BACKOFF_INTERVAL); - - /** - * Translates exceptions from API calls. - */ - private static final ApiErrorExtractor ERROR_EXTRACTOR = new ApiErrorExtractor(); - - /** - * Creates a DataflowPackage containing information about how a classpath element should be - * staged, including the staging destination as well as its size and hash. - * - * @param classpathElement The local path for the classpath element. - * @param stagingPath The base location for staged classpath elements. - * @param overridePackageName If non-null, use the given value as the package name - * instead of generating one automatically. - * @return The package. - */ - @Deprecated - public static DataflowPackage createPackage(File classpathElement, - String stagingPath, String overridePackageName) { - return createPackageAttributes(classpathElement, stagingPath, overridePackageName) - .getDataflowPackage(); - } - - /** - * Compute and cache the attributes of a classpath element that we will need to stage it. - * - * @param classpathElement the file or directory to be staged. - * @param stagingPath The base location for staged classpath elements. - * @param overridePackageName If non-null, use the given value as the package name - * instead of generating one automatically. - * @return a {@link PackageAttributes} that containing metadata about the object to be staged. - */ - static PackageAttributes createPackageAttributes(File classpathElement, - String stagingPath, String overridePackageName) { - try { - boolean directory = classpathElement.isDirectory(); - - // Compute size and hash in one pass over file or directory. - Hasher hasher = Hashing.md5().newHasher(); - OutputStream hashStream = Funnels.asOutputStream(hasher); - CountingOutputStream countingOutputStream = new CountingOutputStream(hashStream); - - if (!directory) { - // Files are staged as-is. - Files.asByteSource(classpathElement).copyTo(countingOutputStream); - } else { - // Directories are recursively zipped. - ZipFiles.zipDirectory(classpathElement, countingOutputStream); - } - - long size = countingOutputStream.getCount(); - String hash = Base64Variants.MODIFIED_FOR_URL.encode(hasher.hash().asBytes()); - - // Create the DataflowPackage with staging name and location. - String uniqueName = getUniqueContentName(classpathElement, hash); - String resourcePath = IOChannelUtils.resolve(stagingPath, uniqueName); - DataflowPackage target = new DataflowPackage(); - target.setName(overridePackageName != null ? overridePackageName : uniqueName); - target.setLocation(resourcePath); - - return new PackageAttributes(size, hash, directory, target); - } catch (IOException e) { - throw new RuntimeException("Package setup failure for " + classpathElement, e); - } - } - - /** - * Transfers the classpath elements to the staging location. - * - * @param classpathElements The elements to stage. - * @param stagingPath The base location to stage the elements to. - * @return A list of cloud workflow packages, each representing a classpath element. - */ - public static List stageClasspathElements( - Collection classpathElements, String stagingPath) { - return stageClasspathElements(classpathElements, stagingPath, Sleeper.DEFAULT); - } - - // Visible for testing. - static List stageClasspathElements( - Collection classpathElements, String stagingPath, - Sleeper retrySleeper) { - LOG.info("Uploading {} files from PipelineOptions.filesToStage to staging location to " - + "prepare for execution.", classpathElements.size()); - - if (classpathElements.size() > SANE_CLASSPATH_SIZE) { - LOG.warn("Your classpath contains {} elements, which Google Cloud Dataflow automatically " - + "copies to all workers. Having this many entries on your classpath may be indicative " - + "of an issue in your pipeline. You may want to consider trimming the classpath to " - + "necessary dependencies only, using --filesToStage pipeline option to override " - + "what files are being staged, or bundling several dependencies into one.", - classpathElements.size()); - } - - ArrayList packages = new ArrayList<>(); - - if (stagingPath == null) { - throw new IllegalArgumentException( - "Can't stage classpath elements on because no staging location has been provided"); - } - - int numUploaded = 0; - int numCached = 0; - for (String classpathElement : classpathElements) { - String packageName = null; - if (classpathElement.contains("=")) { - String[] components = classpathElement.split("=", 2); - packageName = components[0]; - classpathElement = components[1]; - } - - File file = new File(classpathElement); - if (!file.exists()) { - LOG.warn("Skipping non-existent classpath element {} that was specified.", - classpathElement); - continue; - } - - PackageAttributes attributes = createPackageAttributes(file, stagingPath, packageName); - - DataflowPackage workflowPackage = attributes.getDataflowPackage(); - packages.add(workflowPackage); - String target = workflowPackage.getLocation(); - - // TODO: Should we attempt to detect the Mime type rather than - // always using MimeTypes.BINARY? - try { - try { - long remoteLength = IOChannelUtils.getSizeBytes(target); - if (remoteLength == attributes.getSize()) { - LOG.debug("Skipping classpath element already staged: {} at {}", - classpathElement, target); - numCached++; - continue; - } - } catch (FileNotFoundException expected) { - // If the file doesn't exist, it means we need to upload it. - } - - // Upload file, retrying on failure. - BackOff backoff = BACKOFF_FACTORY.backoff(); - while (true) { - try { - LOG.debug("Uploading classpath element {} to {}", classpathElement, target); - try (WritableByteChannel writer = IOChannelUtils.create(target, MimeTypes.BINARY)) { - copyContent(classpathElement, writer); - } - numUploaded++; - break; - } catch (IOException e) { - if (ERROR_EXTRACTOR.accessDenied(e)) { - String errorMessage = String.format( - "Uploaded failed due to permissions error, will NOT retry staging " - + "of classpath %s. Please verify credentials are valid and that you have " - + "write access to %s. Stale credentials can be resolved by executing " - + "'gcloud auth login'.", classpathElement, target); - LOG.error(errorMessage); - throw new IOException(errorMessage, e); - } - long sleep = backoff.nextBackOffMillis(); - if (sleep == BackOff.STOP) { - // Rethrow last error, to be included as a cause in the catch below. - LOG.error("Upload failed, will NOT retry staging of classpath: {}", - classpathElement, e); - throw e; - } else { - LOG.warn("Upload attempt failed, sleeping before retrying staging of classpath: {}", - classpathElement, e); - retrySleeper.sleep(sleep); - } - } - } - } catch (Exception e) { - throw new RuntimeException("Could not stage classpath element: " + classpathElement, e); - } - } - - LOG.info("Uploading PipelineOptions.filesToStage complete: {} files newly uploaded, " - + "{} files cached", - numUploaded, numCached); - - return packages; - } - - /** - * Returns a unique name for a file with a given content hash. - * - *

              Directory paths are removed. Example: - *

              -   * dir="a/b/c/d", contentHash="f000" => d-f000.jar
              -   * file="a/b/c/d.txt", contentHash="f000" => d-f000.txt
              -   * file="a/b/c/d", contentHash="f000" => d-f000
              -   * 
              - */ - static String getUniqueContentName(File classpathElement, String contentHash) { - String fileName = Files.getNameWithoutExtension(classpathElement.getAbsolutePath()); - String fileExtension = Files.getFileExtension(classpathElement.getAbsolutePath()); - if (classpathElement.isDirectory()) { - return fileName + "-" + contentHash + ".jar"; - } else if (fileExtension.isEmpty()) { - return fileName + "-" + contentHash; - } - return fileName + "-" + contentHash + "." + fileExtension; - } - - /** - * Copies the contents of the classpathElement to the output channel. - * - *

              If the classpathElement is a directory, a Zip stream is constructed on the fly, - * otherwise the file contents are copied as-is. - * - *

              The output channel is not closed. - */ - private static void copyContent(String classpathElement, WritableByteChannel outputChannel) - throws IOException { - final File classpathElementFile = new File(classpathElement); - if (classpathElementFile.isDirectory()) { - ZipFiles.zipDirectory(classpathElementFile, Channels.newOutputStream(outputChannel)); - } else { - Files.asByteSource(classpathElementFile).copyTo(Channels.newOutputStream(outputChannel)); - } - } - /** - * Holds the metadata necessary to stage a file or confirm that a staged file has not changed. - */ - static class PackageAttributes { - private final boolean directory; - private final long size; - private final String hash; - private DataflowPackage dataflowPackage; - - public PackageAttributes(long size, String hash, boolean directory, - DataflowPackage dataflowPackage) { - this.size = size; - this.hash = Objects.requireNonNull(hash, "hash"); - this.directory = directory; - this.dataflowPackage = Objects.requireNonNull(dataflowPackage, "dataflowPackage"); - } - - /** - * @return the dataflowPackage - */ - public DataflowPackage getDataflowPackage() { - return dataflowPackage; - } - - /** - * @return the directory - */ - public boolean isDirectory() { - return directory; - } - - /** - * @return the size - */ - public long getSize() { - return size; - } - - /** - * @return the hash - */ - public String getHash() { - return hash; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java deleted file mode 100644 index 934917bb1e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PaneInfoTracker.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.state.ReadableState; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.ValueState; -import com.google.common.annotations.VisibleForTesting; - -import org.joda.time.Instant; - -/** - * Determine the timing and other properties of a new pane for a given computation, key and window. - * Incorporates any previous pane, whether the pane has been produced because an - * on-time {@link AfterWatermark} trigger firing, and the relation between the element's timestamp - * and the current output watermark. - */ -public class PaneInfoTracker { - private TimerInternals timerInternals; - - public PaneInfoTracker(TimerInternals timerInternals) { - this.timerInternals = timerInternals; - } - - @VisibleForTesting - static final StateTag> PANE_INFO_TAG = - StateTags.makeSystemTagInternal(StateTags.value("pane", PaneInfoCoder.INSTANCE)); - - public void clear(StateAccessor state) { - state.access(PANE_INFO_TAG).clear(); - } - - public void prefetchPaneInfo(ReduceFn.Context context) { - context.state().access(PaneInfoTracker.PANE_INFO_TAG).readLater(); - } - - /** - * Return a ({@link ReadableState} for) the pane info appropriate for {@code context}. The pane - * info includes the timing for the pane, who's calculation is quite subtle. - * - * @param isFinal should be {@code true} only if the triggering machinery can guarantee - * no further firings for the - */ - public ReadableState getNextPaneInfo( - ReduceFn.Context context, final boolean isFinal) { - final Object key = context.key(); - final ReadableState previousPaneFuture = - context.state().access(PaneInfoTracker.PANE_INFO_TAG); - final Instant windowMaxTimestamp = context.window().maxTimestamp(); - - return new ReadableState() { - @Override - public ReadableState readLater() { - previousPaneFuture.readLater(); - return this; - } - - @Override - public PaneInfo read() { - PaneInfo previousPane = previousPaneFuture.read(); - return describePane(key, windowMaxTimestamp, previousPane, isFinal); - } - }; - } - - public void storeCurrentPaneInfo(ReduceFn.Context context, PaneInfo currentPane) { - context.state().access(PANE_INFO_TAG).write(currentPane); - } - - private PaneInfo describePane( - Object key, Instant windowMaxTimestamp, PaneInfo previousPane, boolean isFinal) { - boolean isFirst = previousPane == null; - Timing previousTiming = isFirst ? null : previousPane.getTiming(); - long index = isFirst ? 0 : previousPane.getIndex() + 1; - long nonSpeculativeIndex = isFirst ? 0 : previousPane.getNonSpeculativeIndex() + 1; - Instant outputWM = timerInternals.currentOutputWatermarkTime(); - Instant inputWM = timerInternals.currentInputWatermarkTime(); - - // True if it is not possible to assign the element representing this pane a timestamp - // which will make an ON_TIME pane for any following computation. - // Ie true if the element's latest possible timestamp is before the current output watermark. - boolean isLateForOutput = outputWM != null && windowMaxTimestamp.isBefore(outputWM); - - // True if all emitted panes (if any) were EARLY panes. - // Once the ON_TIME pane has fired, all following panes must be considered LATE even - // if the output watermark is behind the end of the window. - boolean onlyEarlyPanesSoFar = previousTiming == null || previousTiming == Timing.EARLY; - - // True is the input watermark hasn't passed the window's max timestamp. - boolean isEarlyForInput = !inputWM.isAfter(windowMaxTimestamp); - - Timing timing; - if (isLateForOutput || !onlyEarlyPanesSoFar) { - // The output watermark has already passed the end of this window, or we have already - // emitted a non-EARLY pane. Irrespective of how this pane was triggered we must - // consider this pane LATE. - timing = Timing.LATE; - } else if (isEarlyForInput) { - // This is an EARLY firing. - timing = Timing.EARLY; - nonSpeculativeIndex = -1; - } else { - // This is the unique ON_TIME firing for the window. - timing = Timing.ON_TIME; - } - - WindowTracing.debug( - "describePane: {} pane (prev was {}) for key:{}; windowMaxTimestamp:{}; " - + "inputWatermark:{}; outputWatermark:{}; isLateForOutput:{}", - timing, previousTiming, key, windowMaxTimestamp, inputWM, outputWM, isLateForOutput); - - if (previousPane != null) { - // Timing transitions should follow EARLY* ON_TIME? LATE* - switch (previousTiming) { - case EARLY: - checkState( - timing == Timing.EARLY || timing == Timing.ON_TIME || timing == Timing.LATE, - "EARLY cannot transition to %s", timing); - break; - case ON_TIME: - checkState(timing == Timing.LATE, "ON_TIME cannot transition to %s", timing); - break; - case LATE: - checkState(timing == Timing.LATE, "LATE cannot transtion to %s", timing); - break; - case UNKNOWN: - break; - } - checkState(!previousPane.isLast(), "Last pane was not last after all."); - } - - return PaneInfo.createPane(isFirst, isFinal, timing, index, nonSpeculativeIndex); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PathValidator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PathValidator.java deleted file mode 100644 index c051b1ce8b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PathValidator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * Interface for controlling validation of paths. - */ -public interface PathValidator { - /** - * Validate that a file pattern is conforming. - * - * @param filepattern The file pattern to verify. - * @return The post-validation filepattern. - */ - String validateInputFilePatternSupported(String filepattern); - - /** - * Validate that an output file prefix is conforming. - * - * @param filePrefix the file prefix to verify. - * @return The post-validation filePrefix. - */ - String validateOutputFilePrefixSupported(String filePrefix); - - /** - * Validate that a path is a valid path and that the path - * is accessible. - * - * @param path The path to verify. - * @return The post-validation path. - */ - String verifyPath(String path); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java deleted file mode 100644 index bd970c4242..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunner.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; - -import java.io.Serializable; -import java.util.Collection; - -/** - * An interface that runs a {@link PerKeyCombineFn} with unified APIs. - * - *

              Different keyed combine functions have their own implementations. - * For example, the implementation can skip allocating {@code Combine.Context}, - * if the keyed combine function doesn't use it. - */ -public interface PerKeyCombineFnRunner extends Serializable { - /** - * Returns the {@link PerKeyCombineFn} it holds. - * - *

              It can be a {@code KeyedCombineFn} or a {@code KeyedCombineFnWithContext}. - */ - PerKeyCombineFn fn(); - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Forwards the call to a {@link PerKeyCombineFn} to create the accumulator in a {@link DoFn}. - * - *

              It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} - * if it is required. - */ - AccumT createAccumulator(K key, DoFn.ProcessContext c); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to add the input in a {@link DoFn}. - * - *

              It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} - * if it is required. - */ - AccumT addInput(K key, AccumT accumulator, InputT input, DoFn.ProcessContext c); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to merge accumulators in a {@link DoFn}. - * - *

              It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} - * if it is required. - */ - AccumT mergeAccumulators( - K key, Iterable accumulators, DoFn.ProcessContext c); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to extract the output in a {@link DoFn}. - * - *

              It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} - * if it is required. - */ - OutputT extractOutput(K key, AccumT accumulator, DoFn.ProcessContext c); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to compact the accumulator in a {@link DoFn}. - * - *

              It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} - * if it is required. - */ - AccumT compact(K key, AccumT accumulator, DoFn.ProcessContext c); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to combine the inputs and extract output - * in a {@link DoFn}. - * - *

              It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} - * if it is required. - */ - OutputT apply(K key, Iterable inputs, DoFn.ProcessContext c); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to add all inputs in a {@link DoFn}. - * - *

              It constructs a {@code CombineWithContext.Context} from {@code DoFn.ProcessContext} - * if it is required. - */ - AccumT addInputs(K key, Iterable inputs, DoFn.ProcessContext c); - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Forwards the call to a {@link PerKeyCombineFn} to create the accumulator. - * - *

              It constructs a {@code CombineWithContext.Context} from - * {@link PipelineOptions} and {@link SideInputReader} if it is required. - */ - AccumT createAccumulator(K key, PipelineOptions options, - SideInputReader sideInputReader, Collection windows); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to add the input. - * - *

              It constructs a {@code CombineWithContext.Context} from - * {@link PipelineOptions} and {@link SideInputReader} if it is required. - */ - AccumT addInput(K key, AccumT accumulator, InputT value, PipelineOptions options, - SideInputReader sideInputReader, Collection windows); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to merge accumulators. - * - *

              It constructs a {@code CombineWithContext.Context} from - * {@link PipelineOptions} and {@link SideInputReader} if it is required. - */ - AccumT mergeAccumulators(K key, Iterable accumulators, PipelineOptions options, - SideInputReader sideInputReader, Collection windows); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to extract the output. - * - *

              It constructs a {@code CombineWithContext.Context} from - * {@link PipelineOptions} and {@link SideInputReader} if it is required. - */ - OutputT extractOutput(K key, AccumT accumulator, PipelineOptions options, - SideInputReader sideInputReader, Collection windows); - - /** - * Forwards the call to a {@link PerKeyCombineFn} to compact the accumulator. - * - *

              It constructs a {@code CombineWithContext.Context} from - * {@link PipelineOptions} and {@link SideInputReader} if it is required. - */ - AccumT compact(K key, AccumT accumulator, PipelineOptions options, - SideInputReader sideInputReader, Collection windows); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java deleted file mode 100644 index a11b275a4f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PerKeyCombineFnRunners.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFnBase.PerKeyCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.RequiresContextInternal; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.common.collect.Iterables; - -import java.util.Collection; - -/** - * Static utility methods that provide {@link PerKeyCombineFnRunner} implementations - * for different keyed combine functions. - */ -public class PerKeyCombineFnRunners { - /** - * Returns a {@link PerKeyCombineFnRunner} from a {@link PerKeyCombineFn}. - */ - public static PerKeyCombineFnRunner - create(PerKeyCombineFn perKeyCombineFn) { - if (perKeyCombineFn instanceof RequiresContextInternal) { - return new KeyedCombineFnWithContextRunner<>( - (KeyedCombineFnWithContext) perKeyCombineFn); - } else { - return new KeyedCombineFnRunner<>( - (KeyedCombineFn) perKeyCombineFn); - } - } - - /** - * An implementation of {@link PerKeyCombineFnRunner} with {@link KeyedCombineFn}. - * - *

              It forwards functions calls to the {@link KeyedCombineFn}. - */ - private static class KeyedCombineFnRunner - implements PerKeyCombineFnRunner { - private final KeyedCombineFn keyedCombineFn; - - private KeyedCombineFnRunner( - KeyedCombineFn keyedCombineFn) { - this.keyedCombineFn = keyedCombineFn; - } - - @Override - public KeyedCombineFn fn() { - return keyedCombineFn; - } - - @Override - public AccumT createAccumulator(K key, DoFn.ProcessContext c) { - return keyedCombineFn.createAccumulator(key); - } - - @Override - public AccumT addInput( - K key, AccumT accumulator, InputT input, DoFn.ProcessContext c) { - return keyedCombineFn.addInput(key, accumulator, input); - } - - @Override - public AccumT mergeAccumulators( - K key, Iterable accumulators, DoFn.ProcessContext c) { - return keyedCombineFn.mergeAccumulators(key, accumulators); - } - - @Override - public OutputT extractOutput(K key, AccumT accumulator, DoFn.ProcessContext c) { - return keyedCombineFn.extractOutput(key, accumulator); - } - - @Override - public AccumT compact(K key, AccumT accumulator, DoFn.ProcessContext c) { - return keyedCombineFn.compact(key, accumulator); - } - - @Override - public OutputT apply(K key, Iterable inputs, DoFn.ProcessContext c) { - return keyedCombineFn.apply(key, inputs); - } - - @Override - public AccumT addInputs(K key, Iterable inputs, DoFn.ProcessContext c) { - AccumT accum = keyedCombineFn.createAccumulator(key); - for (InputT input : inputs) { - accum = keyedCombineFn.addInput(key, accum, input); - } - return accum; - } - - @Override - public String toString() { - return keyedCombineFn.toString(); - } - - @Override - public AccumT createAccumulator(K key, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFn.createAccumulator(key); - } - - @Override - public AccumT addInput(K key, AccumT accumulator, InputT input, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFn.addInput(key, accumulator, input); - } - - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFn.mergeAccumulators(key, accumulators); - } - - @Override - public OutputT extractOutput(K key, AccumT accumulator, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFn.extractOutput(key, accumulator); - } - - @Override - public AccumT compact(K key, AccumT accumulator, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFn.compact(key, accumulator); - } - } - - /** - * An implementation of {@link PerKeyCombineFnRunner} with {@link KeyedCombineFnWithContext}. - * - *

              It forwards functions calls to the {@link KeyedCombineFnWithContext}. - */ - private static class KeyedCombineFnWithContextRunner - implements PerKeyCombineFnRunner { - private final KeyedCombineFnWithContext keyedCombineFnWithContext; - - private KeyedCombineFnWithContextRunner( - KeyedCombineFnWithContext keyedCombineFnWithContext) { - this.keyedCombineFnWithContext = keyedCombineFnWithContext; - } - - @Override - public KeyedCombineFnWithContext fn() { - return keyedCombineFnWithContext; - } - - @Override - public AccumT createAccumulator(K key, DoFn.ProcessContext c) { - return keyedCombineFnWithContext.createAccumulator(key, - CombineContextFactory.createFromProcessContext(c)); - } - - @Override - public AccumT addInput( - K key, AccumT accumulator, InputT value, DoFn.ProcessContext c) { - return keyedCombineFnWithContext.addInput(key, accumulator, value, - CombineContextFactory.createFromProcessContext(c)); - } - - @Override - public AccumT mergeAccumulators( - K key, Iterable accumulators, DoFn.ProcessContext c) { - return keyedCombineFnWithContext.mergeAccumulators( - key, accumulators, CombineContextFactory.createFromProcessContext(c)); - } - - @Override - public OutputT extractOutput(K key, AccumT accumulator, DoFn.ProcessContext c) { - return keyedCombineFnWithContext.extractOutput(key, accumulator, - CombineContextFactory.createFromProcessContext(c)); - } - - @Override - public AccumT compact(K key, AccumT accumulator, DoFn.ProcessContext c) { - return keyedCombineFnWithContext.compact(key, accumulator, - CombineContextFactory.createFromProcessContext(c)); - } - - @Override - public OutputT apply(K key, Iterable inputs, DoFn.ProcessContext c) { - return keyedCombineFnWithContext.apply(key, inputs, - CombineContextFactory.createFromProcessContext(c)); - } - - @Override - public AccumT addInputs(K key, Iterable inputs, DoFn.ProcessContext c) { - CombineWithContext.Context combineContext = CombineContextFactory.createFromProcessContext(c); - AccumT accum = keyedCombineFnWithContext.createAccumulator(key, combineContext); - for (InputT input : inputs) { - accum = keyedCombineFnWithContext.addInput(key, accum, input, combineContext); - } - return accum; - } - - @Override - public String toString() { - return keyedCombineFnWithContext.toString(); - } - - @Override - public AccumT createAccumulator(K key, PipelineOptions options, SideInputReader sideInputReader, - Collection windows) { - return keyedCombineFnWithContext.createAccumulator(key, - CombineContextFactory.createFromComponents( - options, sideInputReader, Iterables.getOnlyElement(windows))); - } - - @Override - public AccumT addInput(K key, AccumT accumulator, InputT input, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFnWithContext.addInput(key, accumulator, input, - CombineContextFactory.createFromComponents( - options, sideInputReader, Iterables.getOnlyElement(windows))); - } - - @Override - public AccumT mergeAccumulators(K key, Iterable accumulators, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFnWithContext.mergeAccumulators(key, accumulators, - CombineContextFactory.createFromComponents( - options, sideInputReader, Iterables.getOnlyElement(windows))); - } - - @Override - public OutputT extractOutput(K key, AccumT accumulator, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFnWithContext.extractOutput(key, accumulator, - CombineContextFactory.createFromComponents( - options, sideInputReader, Iterables.getOnlyElement(windows))); - } - - @Override - public AccumT compact(K key, AccumT accumulator, PipelineOptions options, - SideInputReader sideInputReader, Collection windows) { - return keyedCombineFnWithContext.compact(key, accumulator, - CombineContextFactory.createFromComponents( - options, sideInputReader, Iterables.getOnlyElement(windows))); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java deleted file mode 100644 index 5771fa44e4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PropertyNames.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * Constant property names used by the SDK in CloudWorkflow specifications. - */ -public class PropertyNames { - public static final String ALLOWED_ENCODINGS = "allowed_encodings"; - public static final String APPEND_TRAILING_NEWLINES = "append_trailing_newlines"; - public static final String BIGQUERY_CREATE_DISPOSITION = "create_disposition"; - public static final String BIGQUERY_DATASET = "dataset"; - public static final String BIGQUERY_PROJECT = "project"; - public static final String BIGQUERY_SCHEMA = "schema"; - public static final String BIGQUERY_TABLE = "table"; - public static final String BIGQUERY_QUERY = "bigquery_query"; - public static final String BIGQUERY_FLATTEN_RESULTS = "bigquery_flatten_results"; - public static final String BIGQUERY_USE_LEGACY_SQL = "bigquery_use_legacy_sql"; - public static final String BIGQUERY_WRITE_DISPOSITION = "write_disposition"; - public static final String BIGQUERY_EXPORT_FORMAT = "bigquery_export_format"; - public static final String BIGQUERY_EXPORT_SCHEMA = "bigquery_export_schema"; - public static final String CO_GBK_RESULT_SCHEMA = "co_gbk_result_schema"; - public static final String COMBINE_FN = "combine_fn"; - public static final String COMPONENT_ENCODINGS = "component_encodings"; - public static final String COMPRESSION_TYPE = "compression_type"; - public static final String CUSTOM_SOURCE_FORMAT = "custom_source"; - public static final String CONCAT_SOURCE_SOURCES = "sources"; - public static final String CONCAT_SOURCE_BASE_SPECS = "base_specs"; - public static final String SOURCE_STEP_INPUT = "custom_source_step_input"; - public static final String SOURCE_SPEC = "spec"; - public static final String SOURCE_METADATA = "metadata"; - public static final String SOURCE_DOES_NOT_NEED_SPLITTING = "does_not_need_splitting"; - public static final String SOURCE_PRODUCES_SORTED_KEYS = "produces_sorted_keys"; - public static final String SOURCE_IS_INFINITE = "is_infinite"; - public static final String SOURCE_ESTIMATED_SIZE_BYTES = "estimated_size_bytes"; - public static final String ELEMENT = "element"; - public static final String ELEMENTS = "elements"; - public static final String ENCODING = "encoding"; - public static final String ENCODING_ID = "encoding_id"; - public static final String END_INDEX = "end_index"; - public static final String END_OFFSET = "end_offset"; - public static final String END_SHUFFLE_POSITION = "end_shuffle_position"; - public static final String ENVIRONMENT_VERSION_JOB_TYPE_KEY = "job_type"; - public static final String ENVIRONMENT_VERSION_MAJOR_KEY = "major"; - public static final String FILENAME = "filename"; - public static final String FILENAME_PREFIX = "filename_prefix"; - public static final String FILENAME_SUFFIX = "filename_suffix"; - public static final String FILEPATTERN = "filepattern"; - public static final String FOOTER = "footer"; - public static final String FORMAT = "format"; - public static final String HEADER = "header"; - public static final String INPUTS = "inputs"; - public static final String INPUT_CODER = "input_coder"; - public static final String IS_GENERATED = "is_generated"; - public static final String IS_MERGING_WINDOW_FN = "is_merging_window_fn"; - public static final String IS_PAIR_LIKE = "is_pair_like"; - public static final String IS_STREAM_LIKE = "is_stream_like"; - public static final String IS_WRAPPER = "is_wrapper"; - public static final String DISALLOW_COMBINER_LIFTING = "disallow_combiner_lifting"; - public static final String NON_PARALLEL_INPUTS = "non_parallel_inputs"; - public static final String NUM_SHARD_CODERS = "num_shard_coders"; - public static final String NUM_METADATA_SHARD_CODERS = "num_metadata_shard_coders"; - public static final String NUM_SHARDS = "num_shards"; - public static final String OBJECT_TYPE_NAME = "@type"; - public static final String OUTPUT = "output"; - public static final String OUTPUT_INFO = "output_info"; - public static final String OUTPUT_NAME = "output_name"; - public static final String PARALLEL_INPUT = "parallel_input"; - public static final String PHASE = "phase"; - public static final String PUBSUB_ID_LABEL = "pubsub_id_label"; - public static final String PUBSUB_SUBSCRIPTION = "pubsub_subscription"; - public static final String PUBSUB_SUBSCRIPTION_OVERRIDE = "pubsub_subscription_runtime_override"; - public static final String PUBSUB_TIMESTAMP_LABEL = "pubsub_timestamp_label"; - public static final String PUBSUB_TOPIC = "pubsub_topic"; - public static final String PUBSUB_TOPIC_OVERRIDE = "pubsub_topic_runtime_override"; - public static final String SCALAR_FIELD_NAME = "value"; - public static final String SERIALIZED_FN = "serialized_fn"; - public static final String SHARD_NAME_TEMPLATE = "shard_template"; - public static final String SHUFFLE_KIND = "shuffle_kind"; - public static final String SHUFFLE_READER_CONFIG = "shuffle_reader_config"; - public static final String SHUFFLE_WRITER_CONFIG = "shuffle_writer_config"; - public static final String SORT_VALUES = "sort_values"; - public static final String START_INDEX = "start_index"; - public static final String START_OFFSET = "start_offset"; - public static final String START_SHUFFLE_POSITION = "start_shuffle_position"; - public static final String STRIP_TRAILING_NEWLINES = "strip_trailing_newlines"; - public static final String TUPLE_TAGS = "tuple_tags"; - public static final String USE_INDEXED_FORMAT = "use_indexed_format"; - public static final String USER_FN = "user_fn"; - public static final String USER_NAME = "user_name"; - public static final String USES_KEYED_STATE = "uses_keyed_state"; - public static final String VALIDATE_SINK = "validate_sink"; - public static final String VALIDATE_SOURCE = "validate_source"; - public static final String VALUE = "value"; - public static final String DISPLAY_DATA = "display_data"; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java deleted file mode 100644 index e544bde333..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubClient.java +++ /dev/null @@ -1,557 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.client.util.DateTime; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.common.base.Objects; -import com.google.common.base.Strings; - -import java.io.Closeable; -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; -import javax.annotation.Nullable; - -/** - * An (abstract) helper class for talking to Pubsub via an underlying transport. - */ -public abstract class PubsubClient implements Closeable { - /** - * Factory for creating clients. - */ - public interface PubsubClientFactory extends Serializable { - /** - * Construct a new Pubsub client. It should be closed via {@link #close} in order - * to ensure tidy cleanup of underlying netty resources (or use the try-with-resources - * construct). Uses {@code options} to derive pubsub endpoints and application credentials. - * If non-{@literal null}, use {@code timestampLabel} and {@code idLabel} to store custom - * timestamps/ids within message metadata. - */ - PubsubClient newClient( - @Nullable String timestampLabel, - @Nullable String idLabel, - DataflowPipelineOptions options) throws IOException; - - /** - * Return the display name for this factory. Eg "Json", "gRPC". - */ - String getKind(); - } - - /** - * Return timestamp as ms-since-unix-epoch corresponding to {@code timestamp}. - * Return {@literal null} if no timestamp could be found. Throw {@link IllegalArgumentException} - * if timestamp cannot be recognized. - */ - @Nullable - private static Long asMsSinceEpoch(@Nullable String timestamp) { - if (Strings.isNullOrEmpty(timestamp)) { - return null; - } - try { - // Try parsing as milliseconds since epoch. Note there is no way to parse a - // string in RFC 3339 format here. - // Expected IllegalArgumentException if parsing fails; we use that to fall back - // to RFC 3339. - return Long.parseLong(timestamp); - } catch (IllegalArgumentException e1) { - // Try parsing as RFC3339 string. DateTime.parseRfc3339 will throw an - // IllegalArgumentException if parsing fails, and the caller should handle. - return DateTime.parseRfc3339(timestamp).getValue(); - } - } - - /** - * Return the timestamp (in ms since unix epoch) to use for a Pubsub message with {@code - * attributes} and {@code pubsubTimestamp}. - * - *

              If {@code timestampLabel} is non-{@literal null} then the message attributes must contain - * that label, and the value of that label will be taken as the timestamp. - * Otherwise the timestamp will be taken from the Pubsub publish timestamp {@code - * pubsubTimestamp}. Throw {@link IllegalArgumentException} if the timestamp cannot be - * recognized as a ms-since-unix-epoch or RFC3339 time. - * - * @throws IllegalArgumentException - */ - protected static long extractTimestamp( - @Nullable String timestampLabel, - @Nullable String pubsubTimestamp, - @Nullable Map attributes) { - Long timestampMsSinceEpoch; - if (Strings.isNullOrEmpty(timestampLabel)) { - timestampMsSinceEpoch = asMsSinceEpoch(pubsubTimestamp); - checkArgument(timestampMsSinceEpoch != null, - "Cannot interpret PubSub publish timestamp: %s", - pubsubTimestamp); - } else { - String value = attributes == null ? null : attributes.get(timestampLabel); - checkArgument(value != null, - "PubSub message is missing a value for timestamp label %s", - timestampLabel); - timestampMsSinceEpoch = asMsSinceEpoch(value); - checkArgument(timestampMsSinceEpoch != null, - "Cannot interpret value of label %s as timestamp: %s", - timestampLabel, value); - } - return timestampMsSinceEpoch; - } - - /** - * Path representing a cloud project id. - */ - public static class ProjectPath implements Serializable { - private final String projectId; - - /** - * Creates a {@link ProjectPath} from a {@link String} representation, which - * must be of the form {@code "projects/" + projectId}. - */ - ProjectPath(String path) { - String[] splits = path.split("/"); - checkArgument( - splits.length == 2 && splits[0].equals("projects"), - "Malformed project path \"%s\": must be of the form \"projects/\" + ", - path); - this.projectId = splits[1]; - } - - public String getPath() { - return String.format("projects/%s", projectId); - } - - public String getId() { - return projectId; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - ProjectPath that = (ProjectPath) o; - - return projectId.equals(that.projectId); - } - - @Override - public int hashCode() { - return projectId.hashCode(); - } - - @Override - public String toString() { - return getPath(); - } - } - - public static ProjectPath projectPathFromPath(String path) { - return new ProjectPath(path); - } - - public static ProjectPath projectPathFromId(String projectId) { - return new ProjectPath(String.format("projects/%s", projectId)); - } - - /** - * Path representing a Pubsub subscription. - */ - public static class SubscriptionPath implements Serializable { - private final String projectId; - private final String subscriptionName; - - SubscriptionPath(String path) { - String[] splits = path.split("/"); - checkState( - splits.length == 4 && splits[0].equals("projects") && splits[2].equals("subscriptions"), - "Malformed subscription path %s: " - + "must be of the form \"projects/\" + + \"subscriptions\"", path); - this.projectId = splits[1]; - this.subscriptionName = splits[3]; - } - - public String getPath() { - return String.format("projects/%s/subscriptions/%s", projectId, subscriptionName); - } - - public String getName() { - return subscriptionName; - } - - public String getV1Beta1Path() { - return String.format("/subscriptions/%s/%s", projectId, subscriptionName); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SubscriptionPath that = (SubscriptionPath) o; - return this.subscriptionName.equals(that.subscriptionName) - && this.projectId.equals(that.projectId); - } - - @Override - public int hashCode() { - return Objects.hashCode(projectId, subscriptionName); - } - - @Override - public String toString() { - return getPath(); - } - } - - public static SubscriptionPath subscriptionPathFromPath(String path) { - return new SubscriptionPath(path); - } - - public static SubscriptionPath subscriptionPathFromName( - String projectId, String subscriptionName) { - return new SubscriptionPath(String.format("projects/%s/subscriptions/%s", - projectId, subscriptionName)); - } - - /** - * Path representing a Pubsub topic. - */ - public static class TopicPath implements Serializable { - private final String path; - - TopicPath(String path) { - this.path = path; - } - - public String getPath() { - return path; - } - - public String getName() { - String[] splits = path.split("/"); - checkState(splits.length == 4, "Malformed topic path %s", path); - return splits[3]; - } - - public String getV1Beta1Path() { - String[] splits = path.split("/"); - checkState(splits.length == 4, "Malformed topic path %s", path); - return String.format("/topics/%s/%s", splits[1], splits[3]); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - TopicPath topicPath = (TopicPath) o; - return path.equals(topicPath.path); - } - - @Override - public int hashCode() { - return path.hashCode(); - } - - @Override - public String toString() { - return path; - } - } - - public static TopicPath topicPathFromPath(String path) { - return new TopicPath(path); - } - - public static TopicPath topicPathFromName(String projectId, String topicName) { - return new TopicPath(String.format("projects/%s/topics/%s", projectId, topicName)); - } - - /** - * A message to be sent to Pubsub. - * - *

              NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. - * Java serialization is never used for non-test clients. - */ - public static class OutgoingMessage implements Serializable { - /** - * Underlying (encoded) element. - */ - public final byte[] elementBytes; - - /** - * Timestamp for element (ms since epoch). - */ - public final long timestampMsSinceEpoch; - - /** - * If using an id label, the record id to associate with this record's metadata so the receiver - * can reject duplicates. Otherwise {@literal null}. - */ - @Nullable - public final String recordId; - - public OutgoingMessage( - byte[] elementBytes, long timestampMsSinceEpoch, @Nullable String recordId) { - this.elementBytes = elementBytes; - this.timestampMsSinceEpoch = timestampMsSinceEpoch; - this.recordId = recordId; - } - - @Override - public String toString() { - return String.format("OutgoingMessage(%db, %dms)", - elementBytes.length, timestampMsSinceEpoch); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - OutgoingMessage that = (OutgoingMessage) o; - - return timestampMsSinceEpoch == that.timestampMsSinceEpoch - && Arrays.equals(elementBytes, that.elementBytes) - && Objects.equal(recordId, that.recordId); - } - - @Override - public int hashCode() { - return Objects.hashCode(Arrays.hashCode(elementBytes), timestampMsSinceEpoch, recordId); - } - } - - /** - * A message received from Pubsub. - * - *

              NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. - * Java serialization is never used for non-test clients. - */ - public static class IncomingMessage implements Serializable { - /** - * Underlying (encoded) element. - */ - public final byte[] elementBytes; - - /** - * Timestamp for element (ms since epoch). Either Pubsub's processing time, - * or the custom timestamp associated with the message. - */ - public final long timestampMsSinceEpoch; - - /** - * Timestamp (in system time) at which we requested the message (ms since epoch). - */ - public final long requestTimeMsSinceEpoch; - - /** - * Id to pass back to Pubsub to acknowledge receipt of this message. - */ - public final String ackId; - - /** - * Id to pass to the runner to distinguish this message from all others. - */ - public final String recordId; - - public IncomingMessage( - byte[] elementBytes, - long timestampMsSinceEpoch, - long requestTimeMsSinceEpoch, - String ackId, - String recordId) { - this.elementBytes = elementBytes; - this.timestampMsSinceEpoch = timestampMsSinceEpoch; - this.requestTimeMsSinceEpoch = requestTimeMsSinceEpoch; - this.ackId = ackId; - this.recordId = recordId; - } - - public IncomingMessage withRequestTime(long requestTimeMsSinceEpoch) { - return new IncomingMessage(elementBytes, timestampMsSinceEpoch, requestTimeMsSinceEpoch, - ackId, recordId); - } - - @Override - public String toString() { - return String.format("IncomingMessage(%db, %dms)", - elementBytes.length, timestampMsSinceEpoch); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - IncomingMessage that = (IncomingMessage) o; - - return timestampMsSinceEpoch == that.timestampMsSinceEpoch - && requestTimeMsSinceEpoch == that.requestTimeMsSinceEpoch - && ackId.equals(that.ackId) - && recordId.equals(that.recordId) - && Arrays.equals(elementBytes, that.elementBytes); - } - - @Override - public int hashCode() { - return Objects.hashCode(Arrays.hashCode(elementBytes), timestampMsSinceEpoch, - requestTimeMsSinceEpoch, - ackId, recordId); - } - } - - /** - * Publish {@code outgoingMessages} to Pubsub {@code topic}. Return number of messages - * published. - * - * @throws IOException - */ - public abstract int publish(TopicPath topic, List outgoingMessages) - throws IOException; - - /** - * Request the next batch of up to {@code batchSize} messages from {@code subscription}. - * Return the received messages, or empty collection if none were available. Does not - * wait for messages to arrive if {@code returnImmediately} is {@literal true}. - * Returned messages will record their request time as {@code requestTimeMsSinceEpoch}. - * - * @throws IOException - */ - public abstract List pull( - long requestTimeMsSinceEpoch, - SubscriptionPath subscription, - int batchSize, - boolean returnImmediately) - throws IOException; - - /** - * Acknowldege messages from {@code subscription} with {@code ackIds}. - * - * @throws IOException - */ - public abstract void acknowledge(SubscriptionPath subscription, List ackIds) - throws IOException; - - /** - * Modify the ack deadline for messages from {@code subscription} with {@code ackIds} to - * be {@code deadlineSeconds} from now. - * - * @throws IOException - */ - public abstract void modifyAckDeadline( - SubscriptionPath subscription, List ackIds, - int deadlineSeconds) throws IOException; - - /** - * Create {@code topic}. - * - * @throws IOException - */ - public abstract void createTopic(TopicPath topic) throws IOException; - - /* - * Delete {@code topic}. - * - * @throws IOException - */ - public abstract void deleteTopic(TopicPath topic) throws IOException; - - /** - * Return a list of topics for {@code project}. - * - * @throws IOException - */ - public abstract List listTopics(ProjectPath project) throws IOException; - - /** - * Create {@code subscription} to {@code topic}. - * - * @throws IOException - */ - public abstract void createSubscription( - TopicPath topic, SubscriptionPath subscription, int ackDeadlineSeconds) throws IOException; - - /** - * Create a random subscription for {@code topic}. Return the {@link SubscriptionPath}. It - * is the responsibility of the caller to later delete the subscription. - * - * @throws IOException - */ - public SubscriptionPath createRandomSubscription( - ProjectPath project, TopicPath topic, int ackDeadlineSeconds) throws IOException { - // Create a randomized subscription derived from the topic name. - String subscriptionName = topic.getName() + "_beam_" + ThreadLocalRandom.current().nextLong(); - SubscriptionPath subscription = - PubsubClient.subscriptionPathFromName(project.getId(), subscriptionName); - createSubscription(topic, subscription, ackDeadlineSeconds); - return subscription; - } - - /** - * Delete {@code subscription}. - * - * @throws IOException - */ - public abstract void deleteSubscription(SubscriptionPath subscription) throws IOException; - - /** - * Return a list of subscriptions for {@code topic} in {@code project}. - * - * @throws IOException - */ - public abstract List listSubscriptions(ProjectPath project, TopicPath topic) - throws IOException; - - /** - * Return the ack deadline, in seconds, for {@code subscription}. - * - * @throws IOException - */ - public abstract int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException; - - /** - * Return {@literal true} if {@link #pull} will always return empty list. Actual clients - * will return {@literal false}. Test clients may return {@literal true} to signal that all - * expected messages have been pulled and the test may complete. - */ - public abstract boolean isEOF(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java deleted file mode 100644 index 05ebfa3883..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClient.java +++ /dev/null @@ -1,444 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.auth.oauth2.GoogleCredentials; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.protobuf.ByteString; -import com.google.protobuf.Timestamp; -import com.google.pubsub.v1.AcknowledgeRequest; -import com.google.pubsub.v1.DeleteSubscriptionRequest; -import com.google.pubsub.v1.DeleteTopicRequest; -import com.google.pubsub.v1.GetSubscriptionRequest; -import com.google.pubsub.v1.ListSubscriptionsRequest; -import com.google.pubsub.v1.ListSubscriptionsResponse; -import com.google.pubsub.v1.ListTopicsRequest; -import com.google.pubsub.v1.ListTopicsResponse; -import com.google.pubsub.v1.ModifyAckDeadlineRequest; -import com.google.pubsub.v1.PublishRequest; -import com.google.pubsub.v1.PublishResponse; -import com.google.pubsub.v1.PublisherGrpc; -import com.google.pubsub.v1.PublisherGrpc.PublisherBlockingStub; -import com.google.pubsub.v1.PubsubMessage; -import com.google.pubsub.v1.PullRequest; -import com.google.pubsub.v1.PullResponse; -import com.google.pubsub.v1.ReceivedMessage; -import com.google.pubsub.v1.SubscriberGrpc; -import com.google.pubsub.v1.SubscriberGrpc.SubscriberBlockingStub; -import com.google.pubsub.v1.Subscription; -import com.google.pubsub.v1.Topic; - -import io.grpc.Channel; -import io.grpc.ClientInterceptors; -import io.grpc.ManagedChannel; -import io.grpc.auth.ClientAuthInterceptor; -import io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.NegotiationType; -import io.grpc.netty.NettyChannelBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * A helper class for talking to Pubsub via grpc. - * - *

              CAUTION: Currently uses the application default credentials and does not respect any - * credentials-related arguments in {@link DataflowPipelineOptions}. - */ -public class PubsubGrpcClient extends PubsubClient { - private static final String PUBSUB_ADDRESS = "pubsub.googleapis.com"; - private static final int PUBSUB_PORT = 443; - // Will be needed when credentials are correctly constructed and scoped. - @SuppressWarnings("unused") - private static final List PUBSUB_SCOPES = - Collections.singletonList("https://www.googleapis.com/auth/pubsub"); - private static final int LIST_BATCH_SIZE = 1000; - - private static final int DEFAULT_TIMEOUT_S = 15; - - private static class PubsubGrpcClientFactory implements PubsubClientFactory { - @Override - public PubsubClient newClient( - @Nullable String timestampLabel, @Nullable String idLabel, DataflowPipelineOptions options) - throws IOException { - ManagedChannel channel = NettyChannelBuilder - .forAddress(PUBSUB_ADDRESS, PUBSUB_PORT) - .negotiationType(NegotiationType.TLS) - .sslContext(GrpcSslContexts.forClient().ciphers(null).build()) - .build(); - // TODO: GcpOptions needs to support building com.google.auth.oauth2.Credentials from the - // various command line options. It currently only supports the older - // com.google.api.client.auth.oauth2.Credentials. - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); - return new PubsubGrpcClient(timestampLabel, - idLabel, - DEFAULT_TIMEOUT_S, - channel, - credentials, - null /* publisher stub */, - null /* subscriber stub */); - } - - @Override - public String getKind() { - return "Grpc"; - } - } - - /** - * Factory for creating Pubsub clients using gRCP transport. - */ - public static final PubsubClientFactory FACTORY = new PubsubGrpcClientFactory(); - - /** - * Timeout for grpc calls (in s). - */ - private final int timeoutSec; - - /** - * Underlying netty channel, or {@literal null} if closed. - */ - @Nullable - private ManagedChannel publisherChannel; - - /** - * Credentials determined from options and environment. - */ - private final GoogleCredentials credentials; - - /** - * Label to use for custom timestamps, or {@literal null} if should use Pubsub publish time - * instead. - */ - @Nullable - private final String timestampLabel; - - /** - * Label to use for custom ids, or {@literal null} if should use Pubsub provided ids. - */ - @Nullable - private final String idLabel; - - - /** - * Cached stubs, or null if not cached. - */ - @Nullable - private PublisherGrpc.PublisherBlockingStub cachedPublisherStub; - private SubscriberGrpc.SubscriberBlockingStub cachedSubscriberStub; - - @VisibleForTesting - PubsubGrpcClient( - @Nullable String timestampLabel, - @Nullable String idLabel, - int timeoutSec, - ManagedChannel publisherChannel, - GoogleCredentials credentials, - PublisherGrpc.PublisherBlockingStub cachedPublisherStub, - SubscriberGrpc.SubscriberBlockingStub cachedSubscriberStub) { - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - this.timeoutSec = timeoutSec; - this.publisherChannel = publisherChannel; - this.credentials = credentials; - this.cachedPublisherStub = cachedPublisherStub; - this.cachedSubscriberStub = cachedSubscriberStub; - } - - /** - * Gracefully close the underlying netty channel. - */ - @Override - public void close() { - if (publisherChannel == null) { - // Already closed. - return; - } - // Can gc the underlying stubs. - cachedPublisherStub = null; - cachedSubscriberStub = null; - // Mark the client as having been closed before going further - // in case we have an exception from the channel. - ManagedChannel publisherChannel = this.publisherChannel; - this.publisherChannel = null; - // Gracefully shutdown the channel. - publisherChannel.shutdown(); - if (timeoutSec > 0) { - try { - publisherChannel.awaitTermination(timeoutSec, TimeUnit.SECONDS); - } catch (InterruptedException e) { - // Ignore. - Thread.currentThread().interrupt(); - } - } - } - - /** - * Return channel with interceptor for returning credentials. - */ - private Channel newChannel() throws IOException { - checkState(publisherChannel != null, "PubsubGrpcClient has been closed"); - ClientAuthInterceptor interceptor = - new ClientAuthInterceptor(credentials, Executors.newSingleThreadExecutor()); - return ClientInterceptors.intercept(publisherChannel, interceptor); - } - - /** - * Return a stub for making a publish request with a timeout. - */ - private PublisherBlockingStub publisherStub() throws IOException { - if (cachedPublisherStub == null) { - cachedPublisherStub = PublisherGrpc.newBlockingStub(newChannel()); - } - if (timeoutSec > 0) { - return cachedPublisherStub.withDeadlineAfter(timeoutSec, TimeUnit.SECONDS); - } else { - return cachedPublisherStub; - } - } - - /** - * Return a stub for making a subscribe request with a timeout. - */ - private SubscriberBlockingStub subscriberStub() throws IOException { - if (cachedSubscriberStub == null) { - cachedSubscriberStub = SubscriberGrpc.newBlockingStub(newChannel()); - } - if (timeoutSec > 0) { - return cachedSubscriberStub.withDeadlineAfter(timeoutSec, TimeUnit.SECONDS); - } else { - return cachedSubscriberStub; - } - } - - @Override - public int publish(TopicPath topic, List outgoingMessages) - throws IOException { - PublishRequest.Builder request = PublishRequest.newBuilder() - .setTopic(topic.getPath()); - for (OutgoingMessage outgoingMessage : outgoingMessages) { - PubsubMessage.Builder message = - PubsubMessage.newBuilder() - .setData(ByteString.copyFrom(outgoingMessage.elementBytes)); - - if (timestampLabel != null) { - message.getMutableAttributes() - .put(timestampLabel, String.valueOf(outgoingMessage.timestampMsSinceEpoch)); - } - - if (idLabel != null && !Strings.isNullOrEmpty(outgoingMessage.recordId)) { - message.getMutableAttributes().put(idLabel, outgoingMessage.recordId); - } - - request.addMessages(message); - } - - PublishResponse response = publisherStub().publish(request.build()); - return response.getMessageIdsCount(); - } - - @Override - public List pull( - long requestTimeMsSinceEpoch, - SubscriptionPath subscription, - int batchSize, - boolean returnImmediately) throws IOException { - PullRequest request = PullRequest.newBuilder() - .setSubscription(subscription.getPath()) - .setReturnImmediately(returnImmediately) - .setMaxMessages(batchSize) - .build(); - PullResponse response = subscriberStub().pull(request); - if (response.getReceivedMessagesCount() == 0) { - return ImmutableList.of(); - } - List incomingMessages = new ArrayList<>(response.getReceivedMessagesCount()); - for (ReceivedMessage message : response.getReceivedMessagesList()) { - PubsubMessage pubsubMessage = message.getMessage(); - @Nullable Map attributes = pubsubMessage.getAttributes(); - - // Payload. - byte[] elementBytes = pubsubMessage.getData().toByteArray(); - - // Timestamp. - String pubsubTimestampString = null; - Timestamp timestampProto = pubsubMessage.getPublishTime(); - if (timestampProto != null) { - pubsubTimestampString = String.valueOf(timestampProto.getSeconds() - + timestampProto.getNanos() / 1000L); - } - long timestampMsSinceEpoch = - extractTimestamp(timestampLabel, pubsubTimestampString, attributes); - - // Ack id. - String ackId = message.getAckId(); - checkState(!Strings.isNullOrEmpty(ackId)); - - // Record id, if any. - @Nullable String recordId = null; - if (idLabel != null && attributes != null) { - recordId = attributes.get(idLabel); - } - if (Strings.isNullOrEmpty(recordId)) { - // Fall back to the Pubsub provided message id. - recordId = pubsubMessage.getMessageId(); - } - - incomingMessages.add(new IncomingMessage(elementBytes, timestampMsSinceEpoch, - requestTimeMsSinceEpoch, ackId, recordId)); - } - return incomingMessages; - } - - @Override - public void acknowledge(SubscriptionPath subscription, List ackIds) - throws IOException { - AcknowledgeRequest request = AcknowledgeRequest.newBuilder() - .setSubscription(subscription.getPath()) - .addAllAckIds(ackIds) - .build(); - subscriberStub().acknowledge(request); // ignore Empty result. - } - - @Override - public void modifyAckDeadline( - SubscriptionPath subscription, List ackIds, int deadlineSeconds) - throws IOException { - ModifyAckDeadlineRequest request = - ModifyAckDeadlineRequest.newBuilder() - .setSubscription(subscription.getPath()) - .addAllAckIds(ackIds) - .setAckDeadlineSeconds(deadlineSeconds) - .build(); - subscriberStub().modifyAckDeadline(request); // ignore Empty result. - } - - @Override - public void createTopic(TopicPath topic) throws IOException { - Topic request = Topic.newBuilder() - .setName(topic.getPath()) - .build(); - publisherStub().createTopic(request); // ignore Topic result. - } - - @Override - public void deleteTopic(TopicPath topic) throws IOException { - DeleteTopicRequest request = DeleteTopicRequest.newBuilder() - .setTopic(topic.getPath()) - .build(); - publisherStub().deleteTopic(request); // ignore Empty result. - } - - @Override - public List listTopics(ProjectPath project) throws IOException { - ListTopicsRequest.Builder request = - ListTopicsRequest.newBuilder() - .setProject(project.getPath()) - .setPageSize(LIST_BATCH_SIZE); - ListTopicsResponse response = publisherStub().listTopics(request.build()); - if (response.getTopicsCount() == 0) { - return ImmutableList.of(); - } - List topics = new ArrayList<>(response.getTopicsCount()); - while (true) { - for (Topic topic : response.getTopicsList()) { - topics.add(topicPathFromPath(topic.getName())); - } - if (response.getNextPageToken().isEmpty()) { - break; - } - request.setPageToken(response.getNextPageToken()); - response = publisherStub().listTopics(request.build()); - } - return topics; - } - - @Override - public void createSubscription( - TopicPath topic, SubscriptionPath subscription, - int ackDeadlineSeconds) throws IOException { - Subscription request = Subscription.newBuilder() - .setTopic(topic.getPath()) - .setName(subscription.getPath()) - .setAckDeadlineSeconds(ackDeadlineSeconds) - .build(); - subscriberStub().createSubscription(request); // ignore Subscription result. - } - - @Override - public void deleteSubscription(SubscriptionPath subscription) throws IOException { - DeleteSubscriptionRequest request = - DeleteSubscriptionRequest.newBuilder() - .setSubscription(subscription.getPath()) - .build(); - subscriberStub().deleteSubscription(request); // ignore Empty result. - } - - @Override - public List listSubscriptions(ProjectPath project, TopicPath topic) - throws IOException { - ListSubscriptionsRequest.Builder request = - ListSubscriptionsRequest.newBuilder() - .setProject(project.getPath()) - .setPageSize(LIST_BATCH_SIZE); - ListSubscriptionsResponse response = subscriberStub().listSubscriptions(request.build()); - if (response.getSubscriptionsCount() == 0) { - return ImmutableList.of(); - } - List subscriptions = new ArrayList<>(response.getSubscriptionsCount()); - while (true) { - for (Subscription subscription : response.getSubscriptionsList()) { - if (subscription.getTopic().equals(topic.getPath())) { - subscriptions.add(subscriptionPathFromPath(subscription.getName())); - } - } - if (response.getNextPageToken().isEmpty()) { - break; - } - request.setPageToken(response.getNextPageToken()); - response = subscriberStub().listSubscriptions(request.build()); - } - return subscriptions; - } - - @Override - public int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException { - GetSubscriptionRequest request = - GetSubscriptionRequest.newBuilder() - .setSubscription(subscription.getPath()) - .build(); - Subscription response = subscriberStub().getSubscription(request); - return response.getAckDeadlineSeconds(); - } - - @Override - public boolean isEOF() { - return false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClient.java deleted file mode 100644 index c8ac8f5126..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClient.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.Pubsub.Builder; -import com.google.api.services.pubsub.model.AcknowledgeRequest; -import com.google.api.services.pubsub.model.ListSubscriptionsResponse; -import com.google.api.services.pubsub.model.ListTopicsResponse; -import com.google.api.services.pubsub.model.ModifyAckDeadlineRequest; -import com.google.api.services.pubsub.model.PublishRequest; -import com.google.api.services.pubsub.model.PublishResponse; -import com.google.api.services.pubsub.model.PubsubMessage; -import com.google.api.services.pubsub.model.PullRequest; -import com.google.api.services.pubsub.model.PullResponse; -import com.google.api.services.pubsub.model.ReceivedMessage; -import com.google.api.services.pubsub.model.Subscription; -import com.google.api.services.pubsub.model.Topic; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import javax.annotation.Nullable; - -/** - * A Pubsub client using JSON. - */ -public class PubsubJsonClient extends PubsubClient { - - private static class PubsubJsonClientFactory implements PubsubClientFactory { - private static HttpRequestInitializer chainHttpRequestInitializer( - Credential credential, HttpRequestInitializer httpRequestInitializer) { - if (credential == null) { - return httpRequestInitializer; - } else { - return new ChainingHttpRequestInitializer(credential, httpRequestInitializer); - } - } - - @Override - public PubsubClient newClient( - @Nullable String timestampLabel, @Nullable String idLabel, DataflowPipelineOptions options) - throws IOException { - Pubsub pubsub = new Builder( - Transport.getTransport(), - Transport.getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setRootUrl(options.getPubsubRootUrl()) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()) - .build(); - return new PubsubJsonClient(timestampLabel, idLabel, pubsub); - } - - @Override - public String getKind() { - return "Json"; - } - } - - /** - * Factory for creating Pubsub clients using JSON transport. - */ - public static final PubsubClientFactory FACTORY = new PubsubJsonClientFactory(); - - /** - * Label to use for custom timestamps, or {@literal null} if should use Pubsub publish time - * instead. - */ - @Nullable - private final String timestampLabel; - - /** - * Label to use for custom ids, or {@literal null} if should use Pubsub provided ids. - */ - @Nullable - private final String idLabel; - - /** - * Underlying JSON transport. - */ - private Pubsub pubsub; - - @VisibleForTesting - PubsubJsonClient( - @Nullable String timestampLabel, - @Nullable String idLabel, - Pubsub pubsub) { - this.timestampLabel = timestampLabel; - this.idLabel = idLabel; - this.pubsub = pubsub; - } - - @Override - public void close() { - // Nothing to close. - } - - @Override - public int publish(TopicPath topic, List outgoingMessages) - throws IOException { - List pubsubMessages = new ArrayList<>(outgoingMessages.size()); - for (OutgoingMessage outgoingMessage : outgoingMessages) { - PubsubMessage pubsubMessage = new PubsubMessage().encodeData(outgoingMessage.elementBytes); - - Map attributes = pubsubMessage.getAttributes(); - if ((timestampLabel != null || idLabel != null) && attributes == null) { - attributes = new TreeMap<>(); - pubsubMessage.setAttributes(attributes); - } - - if (timestampLabel != null) { - attributes.put(timestampLabel, String.valueOf(outgoingMessage.timestampMsSinceEpoch)); - } - - if (idLabel != null && !Strings.isNullOrEmpty(outgoingMessage.recordId)) { - attributes.put(idLabel, outgoingMessage.recordId); - } - - pubsubMessages.add(pubsubMessage); - } - PublishRequest request = new PublishRequest().setMessages(pubsubMessages); - PublishResponse response = pubsub.projects() - .topics() - .publish(topic.getPath(), request) - .execute(); - return response.getMessageIds().size(); - } - - @Override - public List pull( - long requestTimeMsSinceEpoch, - SubscriptionPath subscription, - int batchSize, - boolean returnImmediately) throws IOException { - PullRequest request = new PullRequest() - .setReturnImmediately(returnImmediately) - .setMaxMessages(batchSize); - PullResponse response = pubsub.projects() - .subscriptions() - .pull(subscription.getPath(), request) - .execute(); - if (response.getReceivedMessages() == null || response.getReceivedMessages().size() == 0) { - return ImmutableList.of(); - } - List incomingMessages = new ArrayList<>(response.getReceivedMessages().size()); - for (ReceivedMessage message : response.getReceivedMessages()) { - PubsubMessage pubsubMessage = message.getMessage(); - @Nullable Map attributes = pubsubMessage.getAttributes(); - - // Payload. - byte[] elementBytes = pubsubMessage.decodeData(); - - // Timestamp. - long timestampMsSinceEpoch = - extractTimestamp(timestampLabel, message.getMessage().getPublishTime(), attributes); - - // Ack id. - String ackId = message.getAckId(); - checkState(!Strings.isNullOrEmpty(ackId)); - - // Record id, if any. - @Nullable String recordId = null; - if (idLabel != null && attributes != null) { - recordId = attributes.get(idLabel); - } - if (Strings.isNullOrEmpty(recordId)) { - // Fall back to the Pubsub provided message id. - recordId = pubsubMessage.getMessageId(); - } - - incomingMessages.add(new IncomingMessage(elementBytes, timestampMsSinceEpoch, - requestTimeMsSinceEpoch, ackId, recordId)); - } - - return incomingMessages; - } - - @Override - public void acknowledge(SubscriptionPath subscription, List ackIds) throws IOException { - AcknowledgeRequest request = new AcknowledgeRequest().setAckIds(ackIds); - pubsub.projects() - .subscriptions() - .acknowledge(subscription.getPath(), request) - .execute(); // ignore Empty result. - } - - @Override - public void modifyAckDeadline( - SubscriptionPath subscription, List ackIds, int deadlineSeconds) - throws IOException { - ModifyAckDeadlineRequest request = - new ModifyAckDeadlineRequest().setAckIds(ackIds) - .setAckDeadlineSeconds(deadlineSeconds); - pubsub.projects() - .subscriptions() - .modifyAckDeadline(subscription.getPath(), request) - .execute(); // ignore Empty result. - } - - @Override - public void createTopic(TopicPath topic) throws IOException { - pubsub.projects() - .topics() - .create(topic.getPath(), new Topic()) - .execute(); // ignore Topic result. - } - - @Override - public void deleteTopic(TopicPath topic) throws IOException { - pubsub.projects() - .topics() - .delete(topic.getPath()) - .execute(); // ignore Empty result. - } - - @Override - public List listTopics(ProjectPath project) throws IOException { - ListTopicsResponse response = pubsub.projects() - .topics() - .list(project.getPath()) - .execute(); - if (response.getTopics() == null || response.getTopics().isEmpty()) { - return ImmutableList.of(); - } - List topics = new ArrayList<>(response.getTopics().size()); - for (Topic topic : response.getTopics()) { - topics.add(topicPathFromPath(topic.getName())); - } - return topics; - } - - @Override - public void createSubscription( - TopicPath topic, SubscriptionPath subscription, - int ackDeadlineSeconds) throws IOException { - Subscription request = new Subscription() - .setTopic(topic.getPath()) - .setAckDeadlineSeconds(ackDeadlineSeconds); - pubsub.projects() - .subscriptions() - .create(subscription.getPath(), request) - .execute(); // ignore Subscription result. - } - - @Override - public void deleteSubscription(SubscriptionPath subscription) throws IOException { - pubsub.projects() - .subscriptions() - .delete(subscription.getPath()) - .execute(); // ignore Empty result. - } - - @Override - public List listSubscriptions(ProjectPath project, TopicPath topic) - throws IOException { - ListSubscriptionsResponse response = pubsub.projects() - .subscriptions() - .list(project.getPath()) - .execute(); - if (response.getSubscriptions() == null || response.getSubscriptions().isEmpty()) { - return ImmutableList.of(); - } - List subscriptions = new ArrayList<>(response.getSubscriptions().size()); - for (Subscription subscription : response.getSubscriptions()) { - if (subscription.getTopic().equals(topic.getPath())) { - subscriptions.add(subscriptionPathFromPath(subscription.getName())); - } - } - return subscriptions; - } - - @Override - public int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException { - Subscription response = pubsub.projects().subscriptions().get(subscription.getPath()).execute(); - return response.getAckDeadlineSeconds(); - } - - @Override - public boolean isEOF() { - return false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java deleted file mode 100644 index c3a5a4e959..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.api.client.util.Clock; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import java.io.Closeable; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.annotation.Nullable; - -/** - * A (partial) implementation of {@link PubsubClient} for use by unit tests. Only suitable for - * testing {@link #publish}, {@link #pull}, {@link #acknowledge} and {@link #modifyAckDeadline} - * methods. Relies on statics to mimic the Pubsub service, though we try to hide that. - */ -public class PubsubTestClient extends PubsubClient { - /** - * Mimic the state of the simulated Pubsub 'service'. - * - *

              Note that the {@link PubsubTestClientFactory} is serialized/deserialized even when running - * test pipelines. Meanwhile it is valid for multiple {@link PubsubTestClient}s to be created - * from the same client factory and run in parallel. Thus we can't enforce aliasing of the - * following data structures over all clients and must resort to a static. - */ - private static class State { - /** - * True if has been primed for a test but not yet validated. - */ - boolean isActive; - - /** - * Publish mode only: Only publish calls for this topic are allowed. - */ - @Nullable - TopicPath expectedTopic; - - /** - * Publish mode only: Messages yet to seen in a {@link #publish} call. - */ - @Nullable - Set remainingExpectedOutgoingMessages; - - /** - * Publish mode only: Messages which should throw when first sent to simulate transient publish - * failure. - */ - @Nullable - Set remainingFailingOutgoingMessages; - - /** - * Pull mode only: Clock from which to get current time. - */ - @Nullable - Clock clock; - - /** - * Pull mode only: Only pull calls for this subscription are allowed. - */ - @Nullable - SubscriptionPath expectedSubscription; - - /** - * Pull mode only: Timeout to simulate. - */ - int ackTimeoutSec; - - /** - * Pull mode only: Messages waiting to be received by a {@link #pull} call. - */ - @Nullable - List remainingPendingIncomingMessages; - - /** - * Pull mode only: Messages which have been returned from a {@link #pull} call and - * not yet ACKed by an {@link #acknowledge} call. - */ - @Nullable - Map pendingAckIncomingMessages; - - /** - * Pull mode only: When above messages are due to have their ACK deadlines expire. - */ - @Nullable - Map ackDeadline; - } - - private static final State STATE = new State(); - - /** Closing the factory will validate all expected messages were processed. */ - public interface PubsubTestClientFactory extends PubsubClientFactory, Closeable { - } - - /** - * Return a factory for testing publishers. Only one factory may be in-flight at a time. - * The factory must be closed when the test is complete, at which point final validation will - * occur. - */ - public static PubsubTestClientFactory createFactoryForPublish( - final TopicPath expectedTopic, - final Iterable expectedOutgoingMessages, - final Iterable failingOutgoingMessages) { - synchronized (STATE) { - checkState(!STATE.isActive, "Test still in flight"); - STATE.expectedTopic = expectedTopic; - STATE.remainingExpectedOutgoingMessages = Sets.newHashSet(expectedOutgoingMessages); - STATE.remainingFailingOutgoingMessages = Sets.newHashSet(failingOutgoingMessages); - STATE.isActive = true; - } - return new PubsubTestClientFactory() { - @Override - public PubsubClient newClient( - @Nullable String timestampLabel, @Nullable String idLabel, - DataflowPipelineOptions options) - throws IOException { - return new PubsubTestClient(); - } - - @Override - public String getKind() { - return "PublishTest"; - } - - @Override - public void close() { - synchronized (STATE) { - checkState(STATE.isActive, "No test still in flight"); - checkState(STATE.remainingExpectedOutgoingMessages.isEmpty(), - "Still waiting for %s messages to be published", - STATE.remainingExpectedOutgoingMessages.size()); - STATE.isActive = false; - STATE.remainingExpectedOutgoingMessages = null; - } - } - }; - } - - /** - * Return a factory for testing subscribers. Only one factory may be in-flight at a time. - * The factory must be closed when the test in complete - */ - public static PubsubTestClientFactory createFactoryForPull( - final Clock clock, - final SubscriptionPath expectedSubscription, - final int ackTimeoutSec, - final Iterable expectedIncomingMessages) { - synchronized (STATE) { - checkState(!STATE.isActive, "Test still in flight"); - STATE.clock = clock; - STATE.expectedSubscription = expectedSubscription; - STATE.ackTimeoutSec = ackTimeoutSec; - STATE.remainingPendingIncomingMessages = Lists.newArrayList(expectedIncomingMessages); - STATE.pendingAckIncomingMessages = new HashMap<>(); - STATE.ackDeadline = new HashMap<>(); - STATE.isActive = true; - } - return new PubsubTestClientFactory() { - @Override - public PubsubClient newClient( - @Nullable String timestampLabel, @Nullable String idLabel, - DataflowPipelineOptions options) - throws IOException { - return new PubsubTestClient(); - } - - @Override - public String getKind() { - return "PullTest"; - } - - @Override - public void close() { - synchronized (STATE) { - checkState(STATE.isActive, "No test still in flight"); - checkState(STATE.remainingPendingIncomingMessages.isEmpty(), - "Still waiting for %s messages to be pulled", - STATE.remainingPendingIncomingMessages.size()); - checkState(STATE.pendingAckIncomingMessages.isEmpty(), - "Still waiting for %s messages to be ACKed", - STATE.pendingAckIncomingMessages.size()); - checkState(STATE.ackDeadline.isEmpty(), - "Still waiting for %s messages to be ACKed", - STATE.ackDeadline.size()); - STATE.isActive = false; - STATE.remainingPendingIncomingMessages = null; - STATE.pendingAckIncomingMessages = null; - STATE.ackDeadline = null; - } - } - }; - } - - /** - * Return true if in pull mode. - */ - private boolean inPullMode() { - checkState(STATE.isActive, "No test is active"); - return STATE.expectedSubscription != null; - } - - /** - * Return true if in publish mode. - */ - private boolean inPublishMode() { - checkState(STATE.isActive, "No test is active"); - return STATE.expectedTopic != null; - } - - /** - * For subscription mode only: - * Track progression of time according to the {@link Clock} passed . This will simulate Pubsub - * expiring - * outstanding ACKs. - */ - public void advance() { - synchronized (STATE) { - checkState(inPullMode(), "Can only advance in pull mode"); - // Any messages who's ACKs timed out are available for re-pulling. - Iterator> deadlineItr = STATE.ackDeadline.entrySet().iterator(); - while (deadlineItr.hasNext()) { - Map.Entry entry = deadlineItr.next(); - if (entry.getValue() <= STATE.clock.currentTimeMillis()) { - STATE.remainingPendingIncomingMessages.add( - STATE.pendingAckIncomingMessages.remove(entry.getKey())); - deadlineItr.remove(); - } - } - } - } - - @Override - public void close() { - } - - @Override - public int publish( - TopicPath topic, List outgoingMessages) throws IOException { - synchronized (STATE) { - checkState(inPublishMode(), "Can only publish in publish mode"); - checkState(topic.equals(STATE.expectedTopic), "Topic %s does not match expected %s", topic, - STATE.expectedTopic); - for (OutgoingMessage outgoingMessage : outgoingMessages) { - if (STATE.remainingFailingOutgoingMessages.remove(outgoingMessage)) { - throw new RuntimeException("Simulating failure for " + outgoingMessage); - } - checkState(STATE.remainingExpectedOutgoingMessages.remove(outgoingMessage), - "Unexpected outgoing message %s", outgoingMessage); - } - return outgoingMessages.size(); - } - } - - @Override - public List pull( - long requestTimeMsSinceEpoch, SubscriptionPath subscription, int batchSize, - boolean returnImmediately) throws IOException { - synchronized (STATE) { - checkState(inPullMode(), "Can only pull in pull mode"); - long now = STATE.clock.currentTimeMillis(); - checkState(requestTimeMsSinceEpoch == now, - "Simulated time %s does not match request time %s", now, requestTimeMsSinceEpoch); - checkState(subscription.equals(STATE.expectedSubscription), - "Subscription %s does not match expected %s", subscription, - STATE.expectedSubscription); - checkState(returnImmediately, "Pull only supported if returning immediately"); - - List incomingMessages = new ArrayList<>(); - Iterator pendItr = STATE.remainingPendingIncomingMessages.iterator(); - while (pendItr.hasNext()) { - IncomingMessage incomingMessage = pendItr.next(); - pendItr.remove(); - IncomingMessage incomingMessageWithRequestTime = - incomingMessage.withRequestTime(requestTimeMsSinceEpoch); - incomingMessages.add(incomingMessageWithRequestTime); - STATE.pendingAckIncomingMessages.put(incomingMessageWithRequestTime.ackId, - incomingMessageWithRequestTime); - STATE.ackDeadline.put(incomingMessageWithRequestTime.ackId, - requestTimeMsSinceEpoch + STATE.ackTimeoutSec * 1000); - if (incomingMessages.size() >= batchSize) { - break; - } - } - return incomingMessages; - } - } - - @Override - public void acknowledge( - SubscriptionPath subscription, - List ackIds) throws IOException { - synchronized (STATE) { - checkState(inPullMode(), "Can only acknowledge in pull mode"); - checkState(subscription.equals(STATE.expectedSubscription), - "Subscription %s does not match expected %s", subscription, - STATE.expectedSubscription); - - for (String ackId : ackIds) { - checkState(STATE.ackDeadline.remove(ackId) != null, - "No message with ACK id %s is waiting for an ACK", ackId); - checkState(STATE.pendingAckIncomingMessages.remove(ackId) != null, - "No message with ACK id %s is waiting for an ACK", ackId); - } - } - } - - @Override - public void modifyAckDeadline( - SubscriptionPath subscription, List ackIds, int deadlineSeconds) throws IOException { - synchronized (STATE) { - checkState(inPullMode(), "Can only modify ack deadline in pull mode"); - checkState(subscription.equals(STATE.expectedSubscription), - "Subscription %s does not match expected %s", subscription, - STATE.expectedSubscription); - - for (String ackId : ackIds) { - if (deadlineSeconds > 0) { - checkState(STATE.ackDeadline.remove(ackId) != null, - "No message with ACK id %s is waiting for an ACK", ackId); - checkState(STATE.pendingAckIncomingMessages.containsKey(ackId), - "No message with ACK id %s is waiting for an ACK", ackId); - STATE.ackDeadline.put(ackId, STATE.clock.currentTimeMillis() + deadlineSeconds * 1000); - } else { - checkState(STATE.ackDeadline.remove(ackId) != null, - "No message with ACK id %s is waiting for an ACK", ackId); - IncomingMessage message = STATE.pendingAckIncomingMessages.remove(ackId); - checkState(message != null, "No message with ACK id %s is waiting for an ACK", ackId); - STATE.remainingPendingIncomingMessages.add(message); - } - } - } - } - - @Override - public void createTopic(TopicPath topic) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void deleteTopic(TopicPath topic) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public List listTopics(ProjectPath project) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void createSubscription( - TopicPath topic, SubscriptionPath subscription, int ackDeadlineSeconds) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void deleteSubscription(SubscriptionPath subscription) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public List listSubscriptions( - ProjectPath project, TopicPath topic) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException { - synchronized (STATE) { - return STATE.ackTimeoutSec; - } - } - - @Override - public boolean isEOF() { - synchronized (STATE) { - checkState(inPullMode(), "Can only check EOF in pull mode"); - return STATE.remainingPendingIncomingMessages.isEmpty(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java deleted file mode 100644 index d047d739f9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunner.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -/** - * A {@link DoFnRunner} that can refuse to process elements that are not ready, instead returning - * them via the {@link #processElementInReadyWindows(WindowedValue)}. - */ -public class PushbackSideInputDoFnRunner implements DoFnRunner { - private final DoFnRunner underlying; - private final Collection> views; - private final ReadyCheckingSideInputReader sideInputReader; - - private Set notReadyWindows; - - public static PushbackSideInputDoFnRunner create( - DoFnRunner underlying, - Collection> views, - ReadyCheckingSideInputReader sideInputReader) { - return new PushbackSideInputDoFnRunner<>(underlying, views, sideInputReader); - } - - private PushbackSideInputDoFnRunner( - DoFnRunner underlying, - Collection> views, - ReadyCheckingSideInputReader sideInputReader) { - this.underlying = underlying; - this.views = views; - this.sideInputReader = sideInputReader; - } - - @Override - public void startBundle() { - notReadyWindows = new HashSet<>(); - underlying.startBundle(); - } - - /** - * Call the underlying {@link DoFnRunner#processElement(WindowedValue)} for the provided element - * for each window the element is in that is ready. - * - * @param elem the element to process in all ready windows - * @return each element that could not be processed because it requires a side input window - * that is not ready. - */ - public Iterable> processElementInReadyWindows(WindowedValue elem) { - if (views.isEmpty()) { - processElement(elem); - return Collections.emptyList(); - } - ImmutableList.Builder> pushedBack = ImmutableList.builder(); - for (WindowedValue windowElem : elem.explodeWindows()) { - BoundedWindow mainInputWindow = Iterables.getOnlyElement(windowElem.getWindows()); - boolean isReady = !notReadyWindows.contains(mainInputWindow); - for (PCollectionView view : views) { - BoundedWindow sideInputWindow = - view.getWindowingStrategyInternal() - .getWindowFn() - .getSideInputWindow(mainInputWindow); - if (!sideInputReader.isReady(view, sideInputWindow)) { - isReady = false; - break; - } - } - if (isReady) { - processElement(windowElem); - } else { - notReadyWindows.add(mainInputWindow); - pushedBack.add(windowElem); - } - } - return pushedBack.build(); - } - - @Override - public void processElement(WindowedValue elem) { - underlying.processElement(elem); - } - - /** - * Call the underlying {@link DoFnRunner#finishBundle()}. - */ - @Override - public void finishBundle() { - notReadyWindows = null; - underlying.finishBundle(); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java deleted file mode 100644 index 359e40ff64..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RandomAccessData.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.common.base.MoreObjects; -import com.google.common.io.ByteStreams; -import com.google.common.primitives.UnsignedBytes; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.Comparator; - -import javax.annotation.concurrent.NotThreadSafe; - -/** - * An elastic-sized byte array which allows you to manipulate it as a stream, or access - * it directly. This allows for a quick succession of moving bytes from an {@link InputStream} - * to this wrapper to be used as an {@link OutputStream} and vice versa. This wrapper - * also provides random access to bytes stored within. This wrapper allows users to finely - * control the number of byte copies that occur. - * - *

              Anything stored within the in-memory buffer from offset {@link #size()} is considered - * temporary unused storage. - */ -@NotThreadSafe -public class RandomAccessData { - /** - * A {@link Coder} which encodes the valid parts of this stream. - * This follows the same encoding scheme as {@link ByteArrayCoder}. - * This coder is deterministic and consistent with equals. - * - *

              This coder does not support encoding positive infinity. - */ - public static class RandomAccessDataCoder extends AtomicCoder { - private static final RandomAccessDataCoder INSTANCE = new RandomAccessDataCoder(); - - @JsonCreator - public static RandomAccessDataCoder of() { - return INSTANCE; - } - - @Override - public void encode(RandomAccessData value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - if (value == POSITIVE_INFINITY) { - throw new CoderException("Positive infinity can not be encoded."); - } - if (!context.isWholeStream) { - VarInt.encode(value.size, outStream); - } - value.writeTo(outStream, 0, value.size); - } - - @Override - public RandomAccessData decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - RandomAccessData rval = new RandomAccessData(); - if (!context.isWholeStream) { - int length = VarInt.decodeInt(inStream); - rval.readFrom(inStream, 0, length); - } else { - ByteStreams.copy(inStream, rval.asOutputStream()); - } - return rval; - } - - @Override - public boolean consistentWithEquals() { - return true; - } - - @Override - public boolean isRegisterByteSizeObserverCheap( - RandomAccessData value, Coder.Context context) { - return true; - } - - @Override - protected long getEncodedElementByteSize(RandomAccessData value, Coder.Context context) - throws Exception { - if (value == null) { - throw new CoderException("cannot encode a null in memory stream"); - } - long size = 0; - if (!context.isWholeStream) { - size += VarInt.getLength(value.size); - } - return size + value.size; - } - } - - public static final UnsignedLexicographicalComparator UNSIGNED_LEXICOGRAPHICAL_COMPARATOR = - new UnsignedLexicographicalComparator(); - - /** - * A {@link Comparator} that compares two byte arrays lexicographically. It compares - * values as a list of unsigned bytes. The first pair of values that follow any common prefix, - * or when one array is a prefix of the other, treats the shorter array as the lesser. - * For example, [] < [0x01] < [0x01, 0x7F] < [0x01, 0x80] < [0x02] < POSITIVE INFINITY. - * - *

              Note that a token type of positive infinity is supported and is greater than - * all other {@link RandomAccessData}. - */ - public static final class UnsignedLexicographicalComparator - implements Comparator { - // Do not instantiate - private UnsignedLexicographicalComparator() { - } - - @Override - public int compare(RandomAccessData o1, RandomAccessData o2) { - return compare(o1, o2, 0 /* start from the beginning */); - } - - /** - * Compare the two sets of bytes starting at the given offset. - */ - public int compare(RandomAccessData o1, RandomAccessData o2, int startOffset) { - if (o1 == o2) { - return 0; - } - if (o1 == POSITIVE_INFINITY) { - return 1; - } - if (o2 == POSITIVE_INFINITY) { - return -1; - } - - int minBytesLen = Math.min(o1.size, o2.size); - for (int i = startOffset; i < minBytesLen; i++) { - // unsigned comparison - int b1 = o1.buffer[i] & 0xFF; - int b2 = o2.buffer[i] & 0xFF; - if (b1 == b2) { - continue; - } - // Return the stream with the smaller byte as the smaller value. - return b1 - b2; - } - // If one is a prefix of the other, return the shorter one as the smaller one. - // If both lengths are equal, then both streams are equal. - return o1.size - o2.size; - } - - /** - * Compute the length of the common prefix of the two provided sets of bytes. - */ - public int commonPrefixLength(RandomAccessData o1, RandomAccessData o2) { - int minBytesLen = Math.min(o1.size, o2.size); - for (int i = 0; i < minBytesLen; i++) { - // unsigned comparison - int b1 = o1.buffer[i] & 0xFF; - int b2 = o2.buffer[i] & 0xFF; - if (b1 != b2) { - return i; - } - } - return minBytesLen; - } - } - - /** A token type representing positive infinity. */ - static final RandomAccessData POSITIVE_INFINITY = new RandomAccessData(0); - - /** - * Returns a RandomAccessData that is the smallest value of same length which - * is strictly greater than this. Note that if this is empty or is all 0xFF then - * a token value of positive infinity is returned. - * - *

              The {@link UnsignedLexicographicalComparator} supports comparing {@link RandomAccessData} - * with support for positive infinitiy. - */ - public RandomAccessData increment() throws IOException { - RandomAccessData copy = copy(); - for (int i = copy.size - 1; i >= 0; --i) { - if (copy.buffer[i] != UnsignedBytes.MAX_VALUE) { - copy.buffer[i] = UnsignedBytes.checkedCast(UnsignedBytes.toInt(copy.buffer[i]) + 1); - return copy; - } - } - return POSITIVE_INFINITY; - } - - private static final int DEFAULT_INITIAL_BUFFER_SIZE = 128; - - /** Constructs a RandomAccessData with a default buffer size. */ - public RandomAccessData() { - this(DEFAULT_INITIAL_BUFFER_SIZE); - } - - /** Constructs a RandomAccessData with the initial buffer. */ - public RandomAccessData(byte[] initialBuffer) { - checkNotNull(initialBuffer); - this.buffer = initialBuffer; - this.size = initialBuffer.length; - } - - /** Constructs a RandomAccessData with the given buffer size. */ - public RandomAccessData(int initialBufferSize) { - checkArgument(initialBufferSize >= 0, "Expected initial buffer size to be greater than zero."); - this.buffer = new byte[initialBufferSize]; - } - - private byte[] buffer; - private int size; - - /** Returns the backing array. */ - public byte[] array() { - return buffer; - } - - /** Returns the number of bytes in the backing array that are valid. */ - public int size() { - return size; - } - - /** Resets the end of the stream to the specified position. */ - public void resetTo(int position) { - ensureCapacity(position); - size = position; - } - - private final OutputStream outputStream = new OutputStream() { - @Override - public void write(int b) throws IOException { - ensureCapacity(size + 1); - buffer[size] = (byte) b; - size += 1; - } - - @Override - public void write(byte[] b, int offset, int length) throws IOException { - ensureCapacity(size + length); - System.arraycopy(b, offset, buffer, size, length); - size += length; - } - }; - - /** - * Returns an output stream which writes to the backing buffer from the current position. - * Note that the internal buffer will grow as required to accomodate all data written. - */ - public OutputStream asOutputStream() { - return outputStream; - } - - /** - * Returns an {@link InputStream} wrapper which supplies the portion of this backing byte buffer - * starting at {@code offset} and up to {@code length} bytes. Note that the returned - * {@link InputStream} is only a wrapper and any modifications to the underlying - * {@link RandomAccessData} will be visible by the {@link InputStream}. - */ - public InputStream asInputStream(final int offset, final int length) { - return new ByteArrayInputStream(buffer, offset, length); - } - - /** - * Writes {@code length} bytes starting at {@code offset} from the backing data store to the - * specified output stream. - */ - public void writeTo(OutputStream out, int offset, int length) throws IOException { - out.write(buffer, offset, length); - } - - /** - * Reads {@code length} bytes from the specified input stream writing them into the backing - * data store starting at {@code offset}. - * - *

              Note that the in memory stream will be grown to ensure there is enough capacity. - */ - public void readFrom(InputStream inStream, int offset, int length) throws IOException { - ensureCapacity(offset + length); - ByteStreams.readFully(inStream, buffer, offset, length); - size = offset + length; - } - - /** Returns a copy of this RandomAccessData. */ - public RandomAccessData copy() throws IOException { - RandomAccessData copy = new RandomAccessData(size); - writeTo(copy.asOutputStream(), 0, size); - return copy; - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (!(other instanceof RandomAccessData)) { - return false; - } - return UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare(this, (RandomAccessData) other) == 0; - } - - @Override - public int hashCode() { - int result = 1; - for (int i = 0; i < size; ++i) { - result = 31 * result + buffer[i]; - } - - return result; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("buffer", Arrays.copyOf(buffer, size)) - .add("size", size) - .toString(); - } - - private void ensureCapacity(int minCapacity) { - // If we have enough space, don't grow the buffer. - if (minCapacity <= buffer.length) { - return; - } - - // Try to double the size of the buffer, if thats not enough, just use the new capacity. - // Note that we use Math.min(long, long) to not cause overflow on the multiplication. - int newCapacity = (int) Math.min(Integer.MAX_VALUE, buffer.length * 2L); - if (newCapacity < minCapacity) { - newCapacity = minCapacity; - } - buffer = Arrays.copyOf(buffer, newCapacity); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java deleted file mode 100644 index 718c9438de..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReadyCheckingSideInputReader.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -/** - * A {@link SideInputReader} that allows callers to check to see if a {@link PCollectionView} has - * had its contents set in a window. - */ -public interface ReadyCheckingSideInputReader extends SideInputReader { - /** - * Returns true if the {@link PCollectionView} is ready in the provided {@link BoundedWindow}. - */ - boolean isReady(PCollectionView view, BoundedWindow window); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java deleted file mode 100644 index c5ef2ea126..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFn.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.ReadableState; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; - -import org.joda.time.Instant; - -import java.io.Serializable; - -/** - * Specification for processing to happen after elements have been grouped by key. - * - * @param The type of key being processed. - * @param The type of input values associated with the key. - * @param The output type that will be produced for each key. - * @param The type of windows this operates on. - */ -public abstract class ReduceFn - implements Serializable { - - /** Information accessible to all the processing methods in this {@code ReduceFn}. */ - public abstract class Context { - /** Return the key that is being processed. */ - public abstract K key(); - - /** The window that is being processed. */ - public abstract W window(); - - /** Access the current {@link WindowingStrategy}. */ - public abstract WindowingStrategy windowingStrategy(); - - /** Return the interface for accessing state. */ - public abstract StateAccessor state(); - - /** Return the interface for accessing timers. */ - public abstract Timers timers(); - } - - /** Information accessible within {@link #processValue}. */ - public abstract class ProcessValueContext extends Context { - /** Return the actual value being processed. */ - public abstract InputT value(); - - /** Return the timestamp associated with the value. */ - public abstract Instant timestamp(); - } - - /** Information accessible within {@link #onMerge}. */ - public abstract class OnMergeContext extends Context { - /** Return the interface for accessing state. */ - @Override - public abstract MergingStateAccessor state(); - } - - /** Information accessible within {@link #onTrigger}. */ - public abstract class OnTriggerContext extends Context { - /** Returns the {@link PaneInfo} for the trigger firing being processed. */ - public abstract PaneInfo paneInfo(); - - /** Output the given value in the current window. */ - public abstract void output(OutputT value); - } - - ////////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Called for each value of type {@code InputT} associated with the current key. - */ - public abstract void processValue(ProcessValueContext c) throws Exception; - - /** - * Called when windows are merged. - */ - public abstract void onMerge(OnMergeContext context) throws Exception; - - /** - * Called when triggers fire. - * - *

              Implementations of {@link ReduceFn} should call {@link OnTriggerContext#output} to emit - * any results that should be included in the pane produced by this trigger firing. - */ - public abstract void onTrigger(OnTriggerContext context) throws Exception; - - /** - * Called before {@link #onMerge} is invoked to provide an opportunity to prefetch any needed - * state. - * - * @param c Context to use prefetch from. - */ - public void prefetchOnMerge(MergingStateAccessor c) throws Exception {} - - /** - * Called before {@link #onTrigger} is invoked to provide an opportunity to prefetch any needed - * state. - * - * @param context Context to use prefetch from. - */ - public void prefetchOnTrigger(StateAccessor context) {} - - /** - * Called to clear any persisted state that the {@link ReduceFn} may be holding. This will be - * called when the windowing is closing and will receive no future interactions. - */ - public abstract void clearState(Context context) throws Exception; - - /** - * Returns true if the there is no buffered state. - */ - public abstract ReadableState isEmpty(StateAccessor context); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java deleted file mode 100644 index 06ae2e6593..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnContextFactory.java +++ /dev/null @@ -1,493 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateContext; -import com.google.cloud.dataflow.sdk.util.state.StateContexts; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.common.collect.ImmutableMap; - -import org.joda.time.Instant; - -import java.util.Collection; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * Factory for creating instances of the various {@link ReduceFn} contexts. - */ -class ReduceFnContextFactory { - public interface OnTriggerCallbacks { - void output(OutputT toOutput); - } - - private final K key; - private final ReduceFn reduceFn; - private final WindowingStrategy windowingStrategy; - private final StateInternals stateInternals; - private final ActiveWindowSet activeWindows; - private final TimerInternals timerInternals; - private final WindowingInternals windowingInternals; - private final PipelineOptions options; - - ReduceFnContextFactory(K key, ReduceFn reduceFn, - WindowingStrategy windowingStrategy, StateInternals stateInternals, - ActiveWindowSet activeWindows, TimerInternals timerInternals, - WindowingInternals windowingInternals, PipelineOptions options) { - this.key = key; - this.reduceFn = reduceFn; - this.windowingStrategy = windowingStrategy; - this.stateInternals = stateInternals; - this.activeWindows = activeWindows; - this.timerInternals = timerInternals; - this.windowingInternals = windowingInternals; - this.options = options; - } - - /** Where should we look for state associated with a given window? */ - public enum StateStyle { - /** All state is associated with the window itself. */ - DIRECT, - /** State is associated with the 'state address' windows tracked by the active window set. */ - RENAMED - } - - private StateAccessorImpl stateAccessor(W window, StateStyle style) { - return new StateAccessorImpl( - activeWindows, windowingStrategy.getWindowFn().windowCoder(), - stateInternals, StateContexts.createFromComponents(options, windowingInternals, window), - style); - } - - public ReduceFn.Context base(W window, StateStyle style) { - return new ContextImpl(stateAccessor(window, style)); - } - - public ReduceFn.ProcessValueContext forValue( - W window, InputT value, Instant timestamp, StateStyle style) { - return new ProcessValueContextImpl(stateAccessor(window, style), value, timestamp); - } - - public ReduceFn.OnTriggerContext forTrigger(W window, - PaneInfo pane, StateStyle style, OnTriggerCallbacks callbacks) { - return new OnTriggerContextImpl(stateAccessor(window, style), pane, callbacks); - } - - public ReduceFn.OnMergeContext forMerge( - Collection activeToBeMerged, W mergeResult, StateStyle style) { - return new OnMergeContextImpl( - new MergingStateAccessorImpl(activeWindows, - windowingStrategy.getWindowFn().windowCoder(), - stateInternals, style, activeToBeMerged, mergeResult)); - } - - public ReduceFn.OnMergeContext forPremerge(W window) { - return new OnPremergeContextImpl(new PremergingStateAccessorImpl( - activeWindows, windowingStrategy.getWindowFn().windowCoder(), stateInternals, window)); - } - - private class TimersImpl implements Timers { - private final StateNamespace namespace; - - public TimersImpl(StateNamespace namespace) { - checkArgument(namespace instanceof WindowNamespace); - this.namespace = namespace; - } - - @Override - public void setTimer(Instant timestamp, TimeDomain timeDomain) { - timerInternals.setTimer(TimerData.of(namespace, timestamp, timeDomain)); - } - - @Override - public void deleteTimer(Instant timestamp, TimeDomain timeDomain) { - timerInternals.deleteTimer(TimerData.of(namespace, timestamp, timeDomain)); - } - - @Override - public Instant currentProcessingTime() { - return timerInternals.currentProcessingTime(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return timerInternals.currentSynchronizedProcessingTime(); - } - - @Override - public Instant currentEventTime() { - return timerInternals.currentInputWatermarkTime(); - } - } - - // ====================================================================== - // StateAccessors - // ====================================================================== - static class StateAccessorImpl implements StateAccessor { - - - protected final ActiveWindowSet activeWindows; - protected final StateContext context; - protected final StateNamespace windowNamespace; - protected final Coder windowCoder; - protected final StateInternals stateInternals; - protected final StateStyle style; - - public StateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, - StateInternals stateInternals, StateContext context, StateStyle style) { - - this.activeWindows = activeWindows; - this.windowCoder = windowCoder; - this.stateInternals = stateInternals; - this.context = checkNotNull(context); - this.windowNamespace = namespaceFor(context.window()); - this.style = style; - } - - protected StateNamespace namespaceFor(W window) { - return StateNamespaces.window(windowCoder, window); - } - - protected StateNamespace windowNamespace() { - return windowNamespace; - } - - W window() { - return context.window(); - } - - StateNamespace namespace() { - return windowNamespace(); - } - - @Override - public StateT access(StateTag address) { - switch (style) { - case DIRECT: - return stateInternals.state(windowNamespace(), address, context); - case RENAMED: - return stateInternals.state( - namespaceFor(activeWindows.writeStateAddress(context.window())), address, context); - } - throw new RuntimeException(); // cases are exhaustive. - } - } - - static class MergingStateAccessorImpl - extends StateAccessorImpl implements MergingStateAccessor { - private final Collection activeToBeMerged; - - public MergingStateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, - StateInternals stateInternals, StateStyle style, Collection activeToBeMerged, - W mergeResult) { - super(activeWindows, windowCoder, stateInternals, - StateContexts.windowOnly(mergeResult), style); - this.activeToBeMerged = activeToBeMerged; - } - - @Override - public StateT access(StateTag address) { - switch (style) { - case DIRECT: - return stateInternals.state(windowNamespace(), address, context); - case RENAMED: - return stateInternals.state( - namespaceFor(activeWindows.mergedWriteStateAddress( - activeToBeMerged, context.window())), - address, - context); - } - throw new RuntimeException(); // cases are exhaustive. - } - - @Override - public Map accessInEachMergingWindow( - StateTag address) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (W mergingWindow : activeToBeMerged) { - StateNamespace namespace = null; - switch (style) { - case DIRECT: - namespace = namespaceFor(mergingWindow); - break; - case RENAMED: - namespace = namespaceFor(activeWindows.writeStateAddress(mergingWindow)); - break; - } - checkNotNull(namespace); // cases are exhaustive. - builder.put(mergingWindow, stateInternals.state(namespace, address, context)); - } - return builder.build(); - } - } - - static class PremergingStateAccessorImpl - extends StateAccessorImpl implements MergingStateAccessor { - public PremergingStateAccessorImpl(ActiveWindowSet activeWindows, Coder windowCoder, - StateInternals stateInternals, W window) { - super(activeWindows, windowCoder, stateInternals, - StateContexts.windowOnly(window), StateStyle.RENAMED); - } - - Collection mergingWindows() { - return activeWindows.readStateAddresses(context.window()); - } - - @Override - public Map accessInEachMergingWindow( - StateTag address) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (W stateAddressWindow : activeWindows.readStateAddresses(context.window())) { - StateT stateForWindow = - stateInternals.state(namespaceFor(stateAddressWindow), address, context); - builder.put(stateAddressWindow, stateForWindow); - } - return builder.build(); - } - } - - // ====================================================================== - // Contexts - // ====================================================================== - - private class ContextImpl extends ReduceFn.Context { - private final StateAccessorImpl state; - private final TimersImpl timers; - - private ContextImpl(StateAccessorImpl state) { - reduceFn.super(); - this.state = state; - this.timers = new TimersImpl(state.namespace()); - } - - @Override - public K key() { - return key; - } - - @Override - public W window() { - return state.window(); - } - - @Override - public WindowingStrategy windowingStrategy() { - return windowingStrategy; - } - - @Override - public StateAccessor state() { - return state; - } - - @Override - public Timers timers() { - return timers; - } - } - - private class ProcessValueContextImpl - extends ReduceFn.ProcessValueContext { - private final InputT value; - private final Instant timestamp; - private final StateAccessorImpl state; - private final TimersImpl timers; - - private ProcessValueContextImpl(StateAccessorImpl state, - InputT value, Instant timestamp) { - reduceFn.super(); - this.state = state; - this.value = value; - this.timestamp = timestamp; - this.timers = new TimersImpl(state.namespace()); - } - - @Override - public K key() { - return key; - } - - @Override - public W window() { - return state.window(); - } - - @Override - public WindowingStrategy windowingStrategy() { - return windowingStrategy; - } - - @Override - public StateAccessor state() { - return state; - } - - @Override - public InputT value() { - return value; - } - - @Override - public Instant timestamp() { - return timestamp; - } - - @Override - public Timers timers() { - return timers; - } - } - - private class OnTriggerContextImpl extends ReduceFn.OnTriggerContext { - private final StateAccessorImpl state; - private final PaneInfo pane; - private final OnTriggerCallbacks callbacks; - private final TimersImpl timers; - - private OnTriggerContextImpl(StateAccessorImpl state, PaneInfo pane, - OnTriggerCallbacks callbacks) { - reduceFn.super(); - this.state = state; - this.pane = pane; - this.callbacks = callbacks; - this.timers = new TimersImpl(state.namespace()); - } - - @Override - public K key() { - return key; - } - - @Override - public W window() { - return state.window(); - } - - @Override - public WindowingStrategy windowingStrategy() { - return windowingStrategy; - } - - @Override - public StateAccessor state() { - return state; - } - - @Override - public PaneInfo paneInfo() { - return pane; - } - - @Override - public void output(OutputT value) { - callbacks.output(value); - } - - @Override - public Timers timers() { - return timers; - } - } - - private class OnMergeContextImpl extends ReduceFn.OnMergeContext { - private final MergingStateAccessorImpl state; - private final TimersImpl timers; - - private OnMergeContextImpl(MergingStateAccessorImpl state) { - reduceFn.super(); - this.state = state; - this.timers = new TimersImpl(state.namespace()); - } - - @Override - public K key() { - return key; - } - - @Override - public WindowingStrategy windowingStrategy() { - return windowingStrategy; - } - - @Override - public MergingStateAccessor state() { - return state; - } - - @Override - public W window() { - return state.window(); - } - - @Override - public Timers timers() { - return timers; - } - } - - private class OnPremergeContextImpl extends ReduceFn.OnMergeContext { - private final PremergingStateAccessorImpl state; - private final TimersImpl timers; - - private OnPremergeContextImpl(PremergingStateAccessorImpl state) { - reduceFn.super(); - this.state = state; - this.timers = new TimersImpl(state.namespace()); - } - - @Override - public K key() { - return key; - } - - @Override - public WindowingStrategy windowingStrategy() { - return windowingStrategy; - } - - @Override - public MergingStateAccessor state() { - return state; - } - - @Override - public W window() { - return state.window(); - } - - @Override - public Timers timers() { - return timers; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java deleted file mode 100644 index 500d755083..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunner.java +++ /dev/null @@ -1,1118 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey.GroupByKeyOnly; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.ReduceFnContextFactory.OnTriggerCallbacks; -import com.google.cloud.dataflow.sdk.util.ReduceFnContextFactory.StateStyle; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowNamespace; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableSet; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * Manages the execution of a {@link ReduceFn} after a {@link GroupByKeyOnly} has partitioned the - * {@link PCollection} by key. - * - *

              The {@link #onTrigger} relies on a {@link TriggerRunner} to manage the execution of - * the triggering logic. The {@code ReduceFnRunner}s responsibilities are: - * - *

                - *
              • Tracking the windows that are active (have buffered data) as elements arrive and - * triggers are fired. - *
              • Holding the watermark based on the timestamps of elements in a pane and releasing it - * when the trigger fires. - *
              • Calling the appropriate callbacks on {@link ReduceFn} based on trigger execution, timer - * firings, etc, and providing appropriate contexts to the {@link ReduceFn} for actions - * such as output. - *
              • Scheduling garbage collection of state associated with a specific window, and making that - * happen when the appropriate timer fires. - *
              - * - * @param The type of key being processed. - * @param The type of values associated with the key. - * @param The output type that will be produced for each key. - * @param The type of windows this operates on. - */ -public class ReduceFnRunner { - - /** - * The {@link ReduceFnRunner} depends on most aspects of the {@link WindowingStrategy}. - * - *
                - *
              • It runs the trigger from the {@link WindowingStrategy}.
              • - *
              • It merges windows according to the {@link WindowingStrategy}.
              • - *
              • It chooses how to track active windows and clear out expired windows - * according to the {@link WindowingStrategy}, based on the allowed lateness and - * whether windows can merge.
              • - *
              • It decides whether to emit empty final panes according to whether the - * {@link WindowingStrategy} requires it.
              • - *
              • It uses discarding or accumulation mode according to the {@link WindowingStrategy}.
              • - *
              - */ - private final WindowingStrategy windowingStrategy; - - private final OutputWindowedValue> outputter; - - private final StateInternals stateInternals; - - private final Aggregator droppedDueToClosedWindow; - - private final K key; - - /** - * Track which windows are still active and the 'state address' windows which hold their state. - * - *
                - *
              • State: Global map for all active windows for this computation and key. - *
              • Lifetime: Cleared when no active windows need to be tracked. A window lives within - * the active window set until its trigger is closed or the window is garbage collected. - *
              - */ - private final ActiveWindowSet activeWindows; - - /** - * Always a {@link SystemReduceFn}. - * - *
                - *
              • State: A bag of accumulated values, or the intermediate result of a combiner. - *
              • State style: RENAMED - *
              • Merging: Concatenate or otherwise combine the state from each merged window. - *
              • Lifetime: Cleared when a pane fires if DISCARDING_FIRED_PANES. Otherwise cleared - * when trigger is finished or when the window is garbage collected. - *
              - */ - private final ReduceFn reduceFn; - - /** - * Manage the setting and firing of timer events. - * - *
                - *
              • Merging: End-of-window and garbage collection timers are cancelled when windows are - * merged away. Timers created by triggers are never garbage collected and are left to - * fire and be ignored. - *
              • Lifetime: Timers automatically disappear after they fire. - *
              - */ - private final TimerInternals timerInternals; - - /** - * Manage the execution and state for triggers. - * - *
                - *
              • State: Tracks which sub-triggers have finished, and any additional state needed to - * determine when the trigger should fire. - *
              • State style: DIRECT - *
              • Merging: Finished bits are explicitly managed. Other state is eagerly merged as - * needed. - *
              • Lifetime: Most trigger state is cleared when the final pane is emitted. However - * the finished bits are left behind and must be cleared when the window is - * garbage collected. - *
              - */ - private final TriggerRunner triggerRunner; - - /** - * Store the output watermark holds for each window. - * - *
                - *
              • State: Bag of hold timestamps. - *
              • State style: RENAMED - *
              • Merging: Depending on {@link OutputTimeFn}, may need to be recalculated on merging. - * When a pane fires it may be necessary to add (back) an end-of-window or garbage collection - * hold. - *
              • Lifetime: Cleared when a pane fires or when the window is garbage collected. - *
              - */ - private final WatermarkHold watermarkHold; - - private final ReduceFnContextFactory contextFactory; - - /** - * Store the previously emitted pane (if any) for each window. - * - *
                - *
              • State: The previous {@link PaneInfo} passed to the user's {@link DoFn#processElement}, - * if any. - *
              • Style style: DIRECT - *
              • Merging: Always keyed by actual window, so does not depend on {@link #activeWindows}. - * Cleared when window is merged away. - *
              • Lifetime: Cleared when trigger is closed or window is garbage collected. - *
              - */ - private final PaneInfoTracker paneInfoTracker; - - /** - * Store whether we've seen any elements for a window since the last pane was emitted. - * - *
                - *
              • State: Unless DISCARDING_FIRED_PANES, a count of number of elements added so far. - *
              • State style: RENAMED. - *
              • Merging: Counts are summed when windows are merged. - *
              • Lifetime: Cleared when pane fires or window is garbage collected. - *
              - */ - private final NonEmptyPanes nonEmptyPanes; - - public ReduceFnRunner( - K key, - WindowingStrategy windowingStrategy, - StateInternals stateInternals, - TimerInternals timerInternals, - WindowingInternals> windowingInternals, - Aggregator droppedDueToClosedWindow, - ReduceFn reduceFn, - PipelineOptions options) { - this.key = key; - this.timerInternals = timerInternals; - this.paneInfoTracker = new PaneInfoTracker(timerInternals); - this.stateInternals = stateInternals; - this.outputter = new OutputViaWindowingInternals<>(windowingInternals); - this.droppedDueToClosedWindow = droppedDueToClosedWindow; - this.reduceFn = reduceFn; - - @SuppressWarnings("unchecked") - WindowingStrategy objectWindowingStrategy = - (WindowingStrategy) windowingStrategy; - this.windowingStrategy = objectWindowingStrategy; - - this.nonEmptyPanes = NonEmptyPanes.create(this.windowingStrategy, this.reduceFn); - - // Note this may incur I/O to load persisted window set data. - this.activeWindows = createActiveWindowSet(); - - this.contextFactory = - new ReduceFnContextFactory(key, reduceFn, this.windowingStrategy, - stateInternals, this.activeWindows, timerInternals, windowingInternals, options); - - this.watermarkHold = new WatermarkHold<>(timerInternals, windowingStrategy); - this.triggerRunner = - new TriggerRunner<>( - windowingStrategy.getTrigger(), - new TriggerContextFactory<>(windowingStrategy, stateInternals, activeWindows)); - } - - private ActiveWindowSet createActiveWindowSet() { - return windowingStrategy.getWindowFn().isNonMerging() - ? new NonMergingActiveWindowSet() - : new MergingActiveWindowSet(windowingStrategy.getWindowFn(), stateInternals); - } - - @VisibleForTesting - boolean isFinished(W window) { - return triggerRunner.isClosed(contextFactory.base(window, StateStyle.DIRECT).state()); - } - - @VisibleForTesting - boolean hasNoActiveWindows() { - return activeWindows.getActiveAndNewWindows().isEmpty(); - } - - private Set openWindows(Collection windows) { - Set result = new HashSet<>(); - for (W window : windows) { - ReduceFn.Context directContext = contextFactory.base( - window, StateStyle.DIRECT); - if (!triggerRunner.isClosed(directContext.state())) { - result.add(window); - } - } - return result; - } - - private Collection windowsThatShouldFire(Set windows) throws Exception { - Collection result = new ArrayList<>(); - // Filter out timers that didn't trigger. - for (W window : windows) { - ReduceFn.Context directContext = - contextFactory.base(window, StateStyle.DIRECT); - if (triggerRunner.shouldFire( - directContext.window(), directContext.timers(), directContext.state())) { - result.add(window); - } - } - return result; - } - - /** - * Incorporate {@code values} into the underlying reduce function, and manage holds, timers, - * triggers, and window merging. - * - *

              The general strategy is: - *

                - *
              1. Use {@link WindowedValue#getWindows} (itself determined using - * {@link WindowFn#assignWindows}) to determine which windows each element belongs to. Some - * of those windows will already have state associated with them. The rest are considered - * NEW. - *
              2. Use {@link WindowFn#mergeWindows} to attempt to merge currently ACTIVE and NEW windows. - * Each NEW window will become either ACTIVE or be discardedL. - * (See {@link ActiveWindowSet} for definitions of these terms.) - *
              3. If at all possible, eagerly substitute NEW windows with their ACTIVE state address - * windows before any state is associated with the NEW window. In the common case that - * windows for new elements are merged into existing ACTIVE windows then no additional - * storage or merging overhead will be incurred. - *
              4. Otherwise, keep track of the state address windows for ACTIVE windows so that their - * states can be merged on-demand when a pane fires. - *
              5. Process the element for each of the windows it's windows have been merged into according - * to {@link ActiveWindowSet}. Processing may require running triggers, setting timers, - * setting holds, and invoking {@link ReduceFn#onTrigger}. - *
              - */ - public void processElements(Iterable> values) throws Exception { - if (!values.iterator().hasNext()) { - return; - } - - // Determine all the windows for elements. - Set windows = collectWindows(values); - // If an incoming element introduces a new window, attempt to merge it into an existing - // window eagerly. - Map windowToMergeResult = mergeWindows(windows); - if (!windowToMergeResult.isEmpty()) { - // Update windows by removing all windows that were merged away and adding - // the windows they were merged to. We add after completing all the - // removals to avoid removing a window that was also added. - List addedWindows = new ArrayList<>(windowToMergeResult.size()); - for (Map.Entry entry : windowToMergeResult.entrySet()) { - windows.remove(entry.getKey()); - addedWindows.add(entry.getValue()); - } - windows.addAll(addedWindows); - } - - prefetchWindowsForValues(windows); - - // All windows that are open before element processing may need to fire. - Set windowsToConsider = openWindows(windows); - - // Process each element, using the updated activeWindows determined by mergeWindows. - for (WindowedValue value : values) { - processElement(windowToMergeResult, value); - } - - // Now that we've processed the elements, see if any of the windows need to fire. - // Prefetch state necessary to determine if the triggers should fire. - for (W mergedWindow : windowsToConsider) { - triggerRunner.prefetchShouldFire( - mergedWindow, contextFactory.base(mergedWindow, StateStyle.DIRECT).state()); - } - // Filter to windows that are firing. - Collection windowsToFire = windowsThatShouldFire(windowsToConsider); - // Prefetch windows that are firing. - for (W window : windowsToFire) { - prefetchEmit(contextFactory.base(window, StateStyle.DIRECT), - contextFactory.base(window, StateStyle.RENAMED)); - } - // Trigger output from firing windows. - for (W window : windowsToFire) { - emit(contextFactory.base(window, StateStyle.DIRECT), - contextFactory.base(window, StateStyle.RENAMED)); - } - - // We're all done with merging and emitting elements so can compress the activeWindow state. - // Any windows which are still NEW must have come in on a new element which was then discarded - // due to the window's trigger being closed. We can thus delete them. - activeWindows.cleanupTemporaryWindows(); - } - - public void persist() { - activeWindows.persist(); - } - - /** - * Extract the windows associated with the values. - */ - private Set collectWindows(Iterable> values) throws Exception { - Set windows = new HashSet<>(); - for (WindowedValue value : values) { - for (BoundedWindow untypedWindow : value.getWindows()) { - @SuppressWarnings("unchecked") - W window = (W) untypedWindow; - windows.add(window); - } - } - return windows; - } - - /** - * Invoke merge for the given windows and return a map from windows to the - * merge result window. Windows that were not merged are not present in the - * map. - */ - private Map mergeWindows(Set windows) throws Exception { - if (windowingStrategy.getWindowFn().isNonMerging()) { - // Return an empty map, indicating that every window is not merged. - return Collections.emptyMap(); - } - - Map windowToMergeResult = new HashMap<>(); - // Collect the windows from all elements (except those which are too late) and - // make sure they are already in the active window set or are added as NEW windows. - for (W window : windows) { - // For backwards compat with pre 1.4 only. - // We may still have ACTIVE windows with multiple state addresses, representing - // a window who's state has not yet been eagerly merged. - // We'll go ahead and merge that state now so that we don't have to worry about - // this legacy case anywhere else. - if (activeWindows.isActive(window)) { - Set stateAddressWindows = activeWindows.readStateAddresses(window); - if (stateAddressWindows.size() > 1) { - // This is a legacy window who's state has not been eagerly merged. - // Do that now. - ReduceFn.OnMergeContext premergeContext = - contextFactory.forPremerge(window); - reduceFn.onMerge(premergeContext); - watermarkHold.onMerge(premergeContext); - activeWindows.merged(window); - } - } - - // Add this window as NEW if it is not currently ACTIVE. - // If we had already seen this window and closed its trigger, then the - // window will not be currently ACTIVE. It will then be added as NEW here, - // and fall into the merging logic as usual. - activeWindows.ensureWindowExists(window); - } - - // Merge all of the active windows and retain a mapping from source windows to result windows. - activeWindows.merge(new OnMergeCallback(windowToMergeResult)); - return windowToMergeResult; - } - - private class OnMergeCallback implements ActiveWindowSet.MergeCallback { - private final Map windowToMergeResult; - - OnMergeCallback(Map windowToMergeResult) { - this.windowToMergeResult = windowToMergeResult; - } - - /** - * Return the subset of {@code windows} which are currently ACTIVE. We only need to worry - * about merging state from ACTIVE windows. NEW windows by definition have no existing state. - */ - private List activeWindows(Iterable windows) { - List active = new ArrayList<>(); - for (W window : windows) { - if (activeWindows.isActive(window)) { - active.add(window); - } - } - return active; - } - - /** - * Called from the active window set to indicate {@code toBeMerged} (of which only - * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) will later - * be merged into {@code mergeResult}. - */ - @Override - public void prefetchOnMerge( - Collection toBeMerged, W mergeResult) throws Exception { - List activeToBeMerged = activeWindows(toBeMerged); - ReduceFn.OnMergeContext directMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); - ReduceFn.OnMergeContext renamedMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); - - // Prefetch various state. - triggerRunner.prefetchForMerge(mergeResult, activeToBeMerged, directMergeContext.state()); - reduceFn.prefetchOnMerge(renamedMergeContext.state()); - watermarkHold.prefetchOnMerge(renamedMergeContext.state()); - nonEmptyPanes.prefetchOnMerge(renamedMergeContext.state()); - } - - /** - * Called from the active window set to indicate {@code toBeMerged} (of which only - * {@code activeToBeMerged} are ACTIVE and thus have state associated with them) are about - * to be merged into {@code mergeResult}. - */ - @Override - public void onMerge(Collection toBeMerged, W mergeResult) throws Exception { - // Remember we have merged these windows. - for (W window : toBeMerged) { - windowToMergeResult.put(window, mergeResult); - } - - // At this point activeWindows has NOT incorporated the results of the merge. - List activeToBeMerged = activeWindows(toBeMerged); - ReduceFn.OnMergeContext directMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.DIRECT); - ReduceFn.OnMergeContext renamedMergeContext = - contextFactory.forMerge(activeToBeMerged, mergeResult, StateStyle.RENAMED); - - // Run the reduceFn to perform any needed merging. - reduceFn.onMerge(renamedMergeContext); - - // Merge the watermark holds. - watermarkHold.onMerge(renamedMergeContext); - - // Merge non-empty pane state. - nonEmptyPanes.onMerge(renamedMergeContext.state()); - - // Have the trigger merge state as needed. - triggerRunner.onMerge( - directMergeContext.window(), directMergeContext.timers(), directMergeContext.state()); - - for (W active : activeToBeMerged) { - if (active.equals(mergeResult)) { - // Not merged away. - continue; - } - // Cleanup flavor A: Currently ACTIVE window is about to be merged away. - // Clear any state not already cleared by the onMerge calls above. - WindowTracing.debug("ReduceFnRunner.onMerge: Merging {} into {}", active, mergeResult); - ReduceFn.Context directClearContext = - contextFactory.base(active, StateStyle.DIRECT); - // No need for the end-of-window or garbage collection timers. - // We will establish a new end-of-window or garbage collection timer for the mergeResult - // window in processElement below. There must be at least one element for the mergeResult - // window since a new element with a new window must have triggered this onMerge. - cancelEndOfWindowAndGarbageCollectionTimers(directClearContext); - // We no longer care about any previous panes of merged away windows. The - // merge result window gets to start fresh if it is new. - paneInfoTracker.clear(directClearContext.state()); - } - } - } - - /** - * Redirect element windows to the ACTIVE windows they have been merged into. - * The compressed representation (value, {window1, window2, ...}) actually represents - * distinct elements (value, window1), (value, window2), ... - * so if window1 and window2 merge, the resulting window will contain both copies - * of the value. - */ - private ImmutableSet toMergedWindows(final Map windowToMergeResult, - final Collection windows) { - return ImmutableSet.copyOf( - FluentIterable.from(windows).transform( - new Function() { - @Override - public W apply(BoundedWindow untypedWindow) { - @SuppressWarnings("unchecked") - W window = (W) untypedWindow; - W mergedWindow = windowToMergeResult.get(window); - // If the element is not present in the map, the window is unmerged. - return (mergedWindow == null) ? window : mergedWindow; - } - } - )); - } - - private void prefetchWindowsForValues(Collection windows) { - // Prefetch in each of the windows if we're going to need to process triggers - for (W window : windows) { - ReduceFn.Context directContext = contextFactory.base( - window, StateStyle.DIRECT); - triggerRunner.prefetchForValue(window, directContext.state()); - } - } - - /** - * Process an element. - * - * @param windowToMergeResult map of windows to merged windows. If a window is - * not present it is unmerged. - * @param value the value being processed - */ - private void processElement(Map windowToMergeResult, WindowedValue value) - throws Exception { - ImmutableSet windows = toMergedWindows(windowToMergeResult, value.getWindows()); - - // Process the element for each (mergeResultWindow, not closed) window it belongs to. - for (W window : windows) { - ReduceFn.ProcessValueContext directContext = contextFactory.forValue( - window, value.getValue(), value.getTimestamp(), StateStyle.DIRECT); - if (triggerRunner.isClosed(directContext.state())) { - // This window has already been closed. - droppedDueToClosedWindow.addValue(1L); - WindowTracing.debug( - "ReduceFnRunner.processElement: Dropping element at {} for key:{}; window:{} " - + "since window is no longer active at inputWatermark:{}; outputWatermark:{}", - value.getTimestamp(), key, window, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - continue; - } - - activeWindows.ensureWindowIsActive(window); - ReduceFn.ProcessValueContext renamedContext = contextFactory.forValue( - window, value.getValue(), value.getTimestamp(), StateStyle.RENAMED); - - nonEmptyPanes.recordContent(renamedContext.state()); - - // Make sure we've scheduled the end-of-window or garbage collection timer for this window. - Instant timer = scheduleEndOfWindowOrGarbageCollectionTimer(directContext); - - // Hold back progress of the output watermark until we have processed the pane this - // element will be included within. If the element is too late for that, place a hold at - // the end-of-window or garbage collection time to allow empty panes to contribute elements - // which won't be dropped due to lateness by a following computation (assuming the following - // computation uses the same allowed lateness value...) - @Nullable Instant hold = watermarkHold.addHolds(renamedContext); - - if (hold != null) { - // Assert that holds have a proximate timer. - boolean holdInWindow = !hold.isAfter(window.maxTimestamp()); - boolean timerInWindow = !timer.isAfter(window.maxTimestamp()); - checkState( - holdInWindow == timerInWindow, - "set a hold at %s, a timer at %s, which disagree as to whether they are in window %s", - hold, - timer, - directContext.window()); - } - - // Execute the reduceFn, which will buffer the value as appropriate - reduceFn.processValue(renamedContext); - - // Run the trigger to update its state - triggerRunner.processValue( - directContext.window(), - directContext.timestamp(), - directContext.timers(), - directContext.state()); - - // At this point, if triggerRunner.shouldFire before the processValue then - // triggerRunner.shouldFire after the processValue. In other words adding values - // cannot take a trigger state from firing to non-firing. - // (We don't actually assert this since it is too slow.) - } - } - - /** - * Enriches TimerData with state necessary for processing a timer as well as - * common queries about a timer. - */ - private class EnrichedTimerData { - public final Instant timestamp; - public final ReduceFn.Context directContext; - public final ReduceFn.Context renamedContext; - // If this is an end-of-window timer then we may need to set a garbage collection timer - // if allowed lateness is non-zero. - public final boolean isEndOfWindow; - // If this is a garbage collection timer then we should trigger and - // garbage collect the window. We'll consider any timer at or after the - // end-of-window time to be a signal to garbage collect. - public final boolean isGarbageCollection; - - EnrichedTimerData( - TimerData timer, - ReduceFn.Context directContext, - ReduceFn.Context renamedContext) { - this.timestamp = timer.getTimestamp(); - this.directContext = directContext; - this.renamedContext = renamedContext; - W window = directContext.window(); - this.isEndOfWindow = TimeDomain.EVENT_TIME == timer.getDomain() - && timer.getTimestamp().equals(window.maxTimestamp()); - Instant cleanupTime = garbageCollectionTime(window); - this.isGarbageCollection = !timer.getTimestamp().isBefore(cleanupTime); - } - - // Has this window had its trigger finish? - // - The trigger may implement isClosed as constant false. - // - If the window function does not support windowing then all windows will be considered - // active. - // So we must take conjunction of activeWindows and triggerRunner state. - public boolean windowIsActiveAndOpen() { - return activeWindows.isActive(directContext.window()) - && !triggerRunner.isClosed(directContext.state()); - } - } - - public void onTimers(Iterable timers) throws Exception { - if (!timers.iterator().hasNext()) { - return; - } - - // Create a reusable context for each timer and begin prefetching necessary - // state. - List enrichedTimers = new LinkedList(); - for (TimerData timer : timers) { - checkArgument(timer.getNamespace() instanceof WindowNamespace, - "Expected timer to be in WindowNamespace, but was in %s", timer.getNamespace()); - @SuppressWarnings("unchecked") - WindowNamespace windowNamespace = (WindowNamespace) timer.getNamespace(); - W window = windowNamespace.getWindow(); - ReduceFn.Context directContext = - contextFactory.base(window, StateStyle.DIRECT); - ReduceFn.Context renamedContext = - contextFactory.base(window, StateStyle.RENAMED); - EnrichedTimerData enrichedTimer = new EnrichedTimerData(timer, directContext, renamedContext); - enrichedTimers.add(enrichedTimer); - - // Perform prefetching of state to determine if the trigger should fire. - if (enrichedTimer.isGarbageCollection) { - triggerRunner.prefetchIsClosed(directContext.state()); - } else { - triggerRunner.prefetchShouldFire(directContext.window(), directContext.state()); - } - } - - // For those windows that are active and open, prefetch the triggering or emitting state. - for (EnrichedTimerData timer : enrichedTimers) { - if (timer.windowIsActiveAndOpen()) { - ReduceFn.Context directContext = timer.directContext; - if (timer.isGarbageCollection) { - prefetchOnTrigger(directContext, timer.renamedContext); - } else if (triggerRunner.shouldFire( - directContext.window(), directContext.timers(), directContext.state())) { - prefetchEmit(directContext, timer.renamedContext); - } - } - } - - // Perform processing now that everything is prefetched. - for (EnrichedTimerData timer : enrichedTimers) { - ReduceFn.Context directContext = timer.directContext; - ReduceFn.Context renamedContext = timer.renamedContext; - - if (timer.isGarbageCollection) { - WindowTracing.debug("ReduceFnRunner.onTimer: Cleaning up for key:{}; window:{} at {} with " - + "inputWatermark:{}; outputWatermark:{}", - key, directContext.window(), timer.timestamp, - timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - - boolean windowIsActiveAndOpen = timer.windowIsActiveAndOpen(); - if (windowIsActiveAndOpen) { - // We need to call onTrigger to emit the final pane if required. - // The final pane *may* be ON_TIME if no prior ON_TIME pane has been emitted, - // and the watermark has passed the end of the window. - @Nullable - Instant newHold = onTrigger( - directContext, renamedContext, true /* isFinished */, timer.isEndOfWindow); - checkState(newHold == null, "Hold placed at %s despite isFinished being true.", newHold); - } - - // Cleanup flavor B: Clear all the remaining state for this window since we'll never - // see elements for it again. - clearAllState(directContext, renamedContext, windowIsActiveAndOpen); - } else { - WindowTracing.debug("ReduceFnRunner.onTimer: Triggering for key:{}; window:{} at {} with " - + "inputWatermark:{}; outputWatermark:{}", - key, directContext.window(), timer.timestamp, - timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - if (timer.windowIsActiveAndOpen() - && triggerRunner.shouldFire( - directContext.window(), directContext.timers(), directContext.state())) { - emit(directContext, renamedContext); - } - - if (timer.isEndOfWindow) { - // If the window strategy trigger includes a watermark trigger then at this point - // there should be no data holds, either because we'd already cleared them on an - // earlier onTrigger, or because we just cleared them on the above emit. - // We could assert this but it is very expensive. - - // Since we are processing an on-time firing we should schedule the garbage collection - // timer. (If getAllowedLateness is zero then the timer event will be considered a - // cleanup event and handled by the above). - // Note we must do this even if the trigger is finished so that we are sure to cleanup - // any final trigger finished bits. - checkState(windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO), - "Unexpected zero getAllowedLateness"); - Instant cleanupTime = garbageCollectionTime(directContext.window()); - WindowTracing.debug( - "ReduceFnRunner.onTimer: Scheduling cleanup timer for key:{}; window:{} at {} with " - + "inputWatermark:{}; outputWatermark:{}", - key, directContext.window(), cleanupTime, timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - checkState(!cleanupTime.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), - "Cleanup time %s is beyond end-of-time", cleanupTime); - directContext.timers().setTimer(cleanupTime, TimeDomain.EVENT_TIME); - } - } - } - } - - /** - * Clear all the state associated with {@code context}'s window. - * Should only be invoked if we know all future elements for this window will be considered - * beyond allowed lateness. - * This is a superset of the clearing done by {@link #emit} below since: - *
                - *
              1. We can clear the trigger finished bits since we'll never need to ask if the trigger is - * closed again. - *
              2. We can clear any remaining garbage collection hold. - *
              - */ - private void clearAllState( - ReduceFn.Context directContext, - ReduceFn.Context renamedContext, - boolean windowIsActiveAndOpen) - throws Exception { - if (windowIsActiveAndOpen) { - // Since both the window is in the active window set AND the trigger was not yet closed, - // it is possible we still have state. - reduceFn.clearState(renamedContext); - watermarkHold.clearHolds(renamedContext); - nonEmptyPanes.clearPane(renamedContext.state()); - // These calls work irrespective of whether the window is active or not, but - // are unnecessary if the window is not active. - triggerRunner.clearState( - directContext.window(), directContext.timers(), directContext.state()); - paneInfoTracker.clear(directContext.state()); - } else { - // If !windowIsActiveAndOpen then !activeWindows.isActive (1) or triggerRunner.isClosed (2). - // For (1), if !activeWindows.isActive then the window must be merging and has been - // explicitly removed by emit. But in that case the trigger must have fired - // and been closed, so this case reduces to (2). - // For (2), if triggerRunner.isClosed then the trigger was fired and entered the - // closed state. In that case emit will have cleared all state in - // reduceFn, triggerRunner (except for finished bits), paneInfoTracker and activeWindows. - // We also know nonEmptyPanes must have been unconditionally cleared by the trigger. - // Since the trigger fired the existing watermark holds must have been cleared, and since - // the trigger closed no new end of window or garbage collection hold will have been - // placed by WatermarkHold.extractAndRelease. - // Thus all the state clearing above is unnecessary. - // - // But(!) for backwards compatibility we must allow a pipeline to be updated from - // an sdk version <= 1.3. In that case it is possible we have an end-of-window or - // garbage collection hold keyed by the current window (reached via directContext) rather - // than the state address window (reached via renamedContext). - // However this can only happen if: - // - We have merging windows. - // - We are DISCARDING_FIRED_PANES. - // - A pane has fired. - // - But the trigger is not (yet) closed. - if (windowingStrategy.getMode() == AccumulationMode.DISCARDING_FIRED_PANES - && !windowingStrategy.getWindowFn().isNonMerging()) { - watermarkHold.clearHolds(directContext); - } - } - - // Don't need to track address state windows anymore. - activeWindows.remove(directContext.window()); - // We'll never need to test for the trigger being closed again. - triggerRunner.clearFinished(directContext.state()); - } - - /** Should the reduce function state be cleared? */ - private boolean shouldDiscardAfterFiring(boolean isFinished) { - if (isFinished) { - // This is the last firing for trigger. - return true; - } - if (windowingStrategy.getMode() == AccumulationMode.DISCARDING_FIRED_PANES) { - // Nothing should be accumulated between panes. - return true; - } - return false; - } - - private void prefetchEmit(ReduceFn.Context directContext, - ReduceFn.Context renamedContext) { - triggerRunner.prefetchShouldFire(directContext.window(), directContext.state()); - triggerRunner.prefetchOnFire(directContext.window(), directContext.state()); - triggerRunner.prefetchIsClosed(directContext.state()); - prefetchOnTrigger(directContext, renamedContext); - } - - /** - * Emit if a trigger is ready to fire or timers require it, and cleanup state. - */ - private void emit( - ReduceFn.Context directContext, - ReduceFn.Context renamedContext) - throws Exception { - checkState(triggerRunner.shouldFire( - directContext.window(), directContext.timers(), directContext.state())); - - // Inform the trigger of the transition to see if it is finished - triggerRunner.onFire(directContext.window(), directContext.timers(), directContext.state()); - boolean isFinished = triggerRunner.isClosed(directContext.state()); - - // Will be able to clear all element state after triggering? - boolean shouldDiscard = shouldDiscardAfterFiring(isFinished); - - // Run onTrigger to produce the actual pane contents. - // As a side effect it will clear all element holds, but not necessarily any - // end-of-window or garbage collection holds. - onTrigger(directContext, renamedContext, isFinished, false /*isEndOfWindow*/); - - // Now that we've triggered, the pane is empty. - nonEmptyPanes.clearPane(renamedContext.state()); - - // Cleanup buffered data if appropriate - if (shouldDiscard) { - // Cleanup flavor C: The user does not want any buffered data to persist between panes. - reduceFn.clearState(renamedContext); - } - - if (isFinished) { - // Cleanup flavor D: If trigger is closed we will ignore all new incoming elements. - // Clear state not otherwise cleared by onTrigger and clearPane above. - // Remember the trigger is, indeed, closed until the window is garbage collected. - triggerRunner.clearState( - directContext.window(), directContext.timers(), directContext.state()); - paneInfoTracker.clear(directContext.state()); - activeWindows.remove(directContext.window()); - } - } - - /** - * Do we need to emit? - */ - private boolean needToEmit(boolean isEmpty, boolean isFinished, PaneInfo.Timing timing) { - if (!isEmpty) { - // The pane has elements. - return true; - } - if (timing == Timing.ON_TIME) { - // This is the unique ON_TIME pane. - return true; - } - if (isFinished && windowingStrategy.getClosingBehavior() == ClosingBehavior.FIRE_ALWAYS) { - // This is known to be the final pane, and the user has requested it even when empty. - return true; - } - return false; - } - - private void prefetchOnTrigger( - final ReduceFn.Context directContext, - ReduceFn.Context renamedContext) { - paneInfoTracker.prefetchPaneInfo(directContext); - watermarkHold.prefetchExtract(renamedContext); - nonEmptyPanes.isEmpty(renamedContext.state()).readLater(); - reduceFn.prefetchOnTrigger(directContext.state()); - } - - /** - * Run the {@link ReduceFn#onTrigger} method and produce any necessary output. - * - * @return output watermark hold added, or {@literal null} if none. - */ - @Nullable - private Instant onTrigger( - final ReduceFn.Context directContext, - ReduceFn.Context renamedContext, - boolean isFinished, boolean isEndOfWindow) - throws Exception { - Instant inputWM = timerInternals.currentInputWatermarkTime(); - - // Calculate the pane info. - final PaneInfo pane = paneInfoTracker.getNextPaneInfo(directContext, isFinished).read(); - - // Extract the window hold, and as a side effect clear it. - final WatermarkHold.OldAndNewHolds pair = - watermarkHold.extractAndRelease(renamedContext, isFinished).read(); - final Instant outputTimestamp = pair.oldHold; - @Nullable Instant newHold = pair.newHold; - - final boolean isEmpty = nonEmptyPanes.isEmpty(renamedContext.state()).read(); - - if (newHold != null) { - // We can't be finished yet. - checkState( - !isFinished, "new hold at %s but finished %s", newHold, directContext.window()); - // The hold cannot be behind the input watermark. - checkState( - !newHold.isBefore(inputWM), "new hold %s is before input watermark %s", newHold, inputWM); - if (newHold.isAfter(directContext.window().maxTimestamp())) { - // The hold must be for garbage collection, which can't have happened yet. - checkState( - newHold.isEqual(garbageCollectionTime(directContext.window())), - "new hold %s should be at garbage collection for window %s plus %s", - newHold, - directContext.window(), - windowingStrategy.getAllowedLateness()); - } else { - // The hold must be for the end-of-window, which can't have happened yet. - checkState( - newHold.isEqual(directContext.window().maxTimestamp()), - "new hold %s should be at end of window %s", - newHold, - directContext.window()); - checkState( - !isEndOfWindow, - "new hold at %s for %s but this is the watermark trigger", - newHold, - directContext.window()); - } - } - - // Only emit a pane if it has data or empty panes are observable. - if (needToEmit(isEmpty, isFinished, pane.getTiming())) { - // Run reduceFn.onTrigger method. - final List windows = Collections.singletonList(directContext.window()); - ReduceFn.OnTriggerContext renamedTriggerContext = - contextFactory.forTrigger(directContext.window(), pane, StateStyle.RENAMED, - new OnTriggerCallbacks() { - @Override - public void output(OutputT toOutput) { - // We're going to output panes, so commit the (now used) PaneInfo. - // TODO: This is unnecessary if the trigger isFinished since the saved - // state will be immediately deleted. - paneInfoTracker.storeCurrentPaneInfo(directContext, pane); - - // Output the actual value. - outputter.outputWindowedValue( - KV.of(key, toOutput), outputTimestamp, windows, pane); - } - }); - - reduceFn.onTrigger(renamedTriggerContext); - } - - return newHold; - } - - /** - * Make sure we'll eventually have a timer fire which will tell us to garbage collect - * the window state. For efficiency we may need to do this in two steps rather - * than one. Return the time at which the timer will fire. - * - *
                - *
              • If allowedLateness is zero then we'll garbage collect at the end of the window. - * For simplicity we'll set our own timer for this situation even though an - * {@link AfterWatermark} trigger may have also set an end-of-window timer. - * ({@code setTimer} is idempotent.) - *
              • If allowedLateness is non-zero then we could just always set a timer for the garbage - * collection time. However if the windows are large (eg hourly) and the allowedLateness is small - * (eg seconds) then we'll end up with nearly twice the number of timers in-flight. So we - * instead set an end-of-window timer and then roll that forward to a garbage collection timer - * when it fires. We use the input watermark to distinguish those cases. - *
              - */ - private Instant scheduleEndOfWindowOrGarbageCollectionTimer( - ReduceFn.Context directContext) { - Instant inputWM = timerInternals.currentInputWatermarkTime(); - Instant endOfWindow = directContext.window().maxTimestamp(); - String which; - Instant timer; - if (endOfWindow.isBefore(inputWM)) { - timer = garbageCollectionTime(directContext.window()); - which = "garbage collection"; - } else { - timer = endOfWindow; - which = "end-of-window"; - } - WindowTracing.trace( - "ReduceFnRunner.scheduleEndOfWindowOrGarbageCollectionTimer: Scheduling {} timer at {} for " - + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", - which, - timer, - key, - directContext.window(), - inputWM, - timerInternals.currentOutputWatermarkTime()); - checkState(!timer.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), - "Timer %s is beyond end-of-time", timer); - directContext.timers().setTimer(timer, TimeDomain.EVENT_TIME); - return timer; - } - - private void cancelEndOfWindowAndGarbageCollectionTimers( - ReduceFn.Context directContext) { - WindowTracing.debug( - "ReduceFnRunner.cancelEndOfWindowAndGarbageCollectionTimers: Deleting timers for " - + "key:{}; window:{} where inputWatermark:{}; outputWatermark:{}", - key, directContext.window(), timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - Instant eow = directContext.window().maxTimestamp(); - directContext.timers().deleteTimer(eow, TimeDomain.EVENT_TIME); - Instant gc = garbageCollectionTime(directContext.window()); - if (gc.isAfter(eow)) { - directContext.timers().deleteTimer(eow, TimeDomain.EVENT_TIME); - } - } - - /** - * Return when {@code window} should be garbage collected. If the window's expiration time is on - * or after the end of the global window, it will be truncated to the end of the global window. - */ - private Instant garbageCollectionTime(W window) { - - // If the end of the window + allowed lateness is beyond the "end of time" aka the end of the - // global window, then we truncate it. The conditional is phrased like it is because the - // addition of EOW + allowed lateness might even overflow the maximum allowed Instant - if (GlobalWindow.INSTANCE - .maxTimestamp() - .minus(windowingStrategy.getAllowedLateness()) - .isBefore(window.maxTimestamp())) { - return GlobalWindow.INSTANCE.maxTimestamp(); - } else { - return window.maxTimestamp().plus(windowingStrategy.getAllowedLateness()); - } - } - - /** - * An object that can output a value with all of its windowing information. This is a deliberately - * restricted subinterface of {@link WindowingInternals} to express how it is used here. - */ - private interface OutputWindowedValue { - void outputWindowedValue(OutputT output, Instant timestamp, - Collection windows, PaneInfo pane); - } - - private static class OutputViaWindowingInternals - implements OutputWindowedValue { - - private final WindowingInternals windowingInternals; - - public OutputViaWindowingInternals(WindowingInternals windowingInternals) { - this.windowingInternals = windowingInternals; - } - - @Override - public void outputWindowedValue( - OutputT output, - Instant timestamp, - Collection windows, - PaneInfo pane) { - windowingInternals.outputWindowedValue(output, timestamp, windows, pane); - } - - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReifyTimestampAndWindowsDoFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReifyTimestampAndWindowsDoFn.java deleted file mode 100644 index 88a1c15eb7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReifyTimestampAndWindowsDoFn.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.values.KV; - -/** - * DoFn that makes timestamps and window assignments explicit in the value part of each key/value - * pair. - * - * @param the type of the keys of the input and output {@code PCollection}s - * @param the type of the values of the input {@code PCollection} - */ -@SystemDoFnInternal -public class ReifyTimestampAndWindowsDoFn - extends DoFn, KV>> { - @Override - public void processElement(ProcessContext c) - throws Exception { - KV kv = c.element(); - K key = kv.getKey(); - V value = kv.getValue(); - c.output(KV.of( - key, - WindowedValue.of( - value, - c.timestamp(), - c.windowingInternals().windows(), - c.pane()))); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java deleted file mode 100644 index 040801d308..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Reshuffle.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; - -/** - * A {@link PTransform} that returns a {@link PCollection} equivalent to its input but operationally - * provides some of the side effects of a {@link GroupByKey}, in particular preventing fusion of - * the surrounding transforms, checkpointing and deduplication by id (see - * {@link ValueWithRecordId}). - * - *

              Performs a {@link GroupByKey} so that the data is key-partitioned. Configures the - * {@link WindowingStrategy} so that no data is dropped, but doesn't affect the need for - * the user to specify allowed lateness and accumulation mode before a user-inserted GroupByKey. - * - * @param The type of key being reshuffled on. - * @param The type of value being reshuffled. - */ -public class Reshuffle extends PTransform>, PCollection>> { - - private Reshuffle() { - } - - public static Reshuffle of() { - return new Reshuffle(); - } - - @Override - public PCollection> apply(PCollection> input) { - WindowingStrategy originalStrategy = input.getWindowingStrategy(); - // If the input has already had its windows merged, then the GBK that performed the merge - // will have set originalStrategy.getWindowFn() to InvalidWindows, causing the GBK contained - // here to fail. Instead, we install a valid WindowFn that leaves all windows unchanged. - Window.Bound> rewindow = - Window.>into( - new IdentityWindowFn<>( - originalStrategy.getWindowFn().windowCoder(), - originalStrategy.getWindowFn().assignsToSingleWindow())) - .triggering(new ReshuffleTrigger<>()) - .discardingFiredPanes() - .withAllowedLateness(Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis())); - - return input.apply(rewindow) - .apply(GroupByKey.create()) - // Set the windowing strategy directly, so that it doesn't get counted as the user having - // set allowed lateness. - .setWindowingStrategyInternal(originalStrategy) - .apply(ParDo.named("ExpandIterable").of( - new DoFn>, KV>() { - @Override - public void processElement(ProcessContext c) { - K key = c.element().getKey(); - for (V value : c.element().getValue()) { - c.output(KV.of(key, value)); - } - } - })); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java deleted file mode 100644 index fb7efd9620..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ReshuffleTrigger.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; - -import org.joda.time.Instant; - -import java.util.List; - -/** - * The trigger used with {@link Reshuffle} which triggers on every element - * and never buffers state. - * - * @param The kind of window that is being reshuffled. - */ -public class ReshuffleTrigger extends Trigger { - - ReshuffleTrigger() { - super(null); - } - - @Override - public void onElement(Trigger.OnElementContext c) { } - - @Override - public void onMerge(Trigger.OnMergeContext c) { } - - @Override - protected Trigger getContinuationTrigger(List> continuationTriggers) { - return this; - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(W window) { - throw new UnsupportedOperationException( - "ReshuffleTrigger should not be used outside of Reshuffle"); - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return true; - } - - @Override - public void onFire(Trigger.TriggerContext context) throws Exception { } - - @Override - public String toString() { - return "ReshuffleTrigger()"; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializer.java deleted file mode 100644 index 756dce0a99..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializer.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.http.HttpBackOffIOExceptionHandler; -import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpResponseInterceptor; -import com.google.api.client.http.HttpUnsuccessfulResponseHandler; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.client.util.NanoClock; -import com.google.api.client.util.Sleeper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * Implements a request initializer that adds retry handlers to all - * HttpRequests. - * - *

              This allows chaining through to another HttpRequestInitializer, since - * clients have exactly one HttpRequestInitializer, and Credential is also - * a required HttpRequestInitializer. - * - *

              Also can take a HttpResponseInterceptor to be applied to the responses. - */ -public class RetryHttpRequestInitializer implements HttpRequestInitializer { - - private static final Logger LOG = LoggerFactory.getLogger(RetryHttpRequestInitializer.class); - - /** - * Http response codes that should be silently ignored. - */ - private static final Set DEFAULT_IGNORED_RESPONSE_CODES = new HashSet<>( - Arrays.asList(307 /* Redirect, handled by the client library */, - 308 /* Resume Incomplete, handled by the client library */)); - - /** - * Http response timeout to use for hanging gets. - */ - private static final int HANGING_GET_TIMEOUT_SEC = 80; - - private static class LoggingHttpBackOffIOExceptionHandler - extends HttpBackOffIOExceptionHandler { - public LoggingHttpBackOffIOExceptionHandler(BackOff backOff) { - super(backOff); - } - - @Override - public boolean handleIOException(HttpRequest request, boolean supportsRetry) - throws IOException { - boolean willRetry = super.handleIOException(request, supportsRetry); - if (willRetry) { - LOG.debug("Request failed with IOException, will retry: {}", request.getUrl()); - } else { - LOG.warn("Request failed with IOException, will NOT retry: {}", request.getUrl()); - } - return willRetry; - } - } - - private static class LoggingHttpBackoffUnsuccessfulResponseHandler - implements HttpUnsuccessfulResponseHandler { - private final HttpBackOffUnsuccessfulResponseHandler handler; - private final Set ignoredResponseCodes; - - public LoggingHttpBackoffUnsuccessfulResponseHandler(BackOff backoff, - Sleeper sleeper, Set ignoredResponseCodes) { - this.ignoredResponseCodes = ignoredResponseCodes; - handler = new HttpBackOffUnsuccessfulResponseHandler(backoff); - handler.setSleeper(sleeper); - handler.setBackOffRequired( - new HttpBackOffUnsuccessfulResponseHandler.BackOffRequired() { - @Override - public boolean isRequired(HttpResponse response) { - int statusCode = response.getStatusCode(); - return (statusCode / 100 == 5) || // 5xx: server error - statusCode == 429; // 429: Too many requests - } - }); - } - - @Override - public boolean handleResponse(HttpRequest request, HttpResponse response, - boolean supportsRetry) throws IOException { - boolean retry = handler.handleResponse(request, response, supportsRetry); - if (retry) { - LOG.debug("Request failed with code {} will retry: {}", - response.getStatusCode(), request.getUrl()); - - } else if (!ignoredResponseCodes.contains(response.getStatusCode())) { - LOG.warn("Request failed with code {}, will NOT retry: {}", - response.getStatusCode(), request.getUrl()); - } - - return retry; - } - } - - @Deprecated - private final HttpRequestInitializer chained; - - private final HttpResponseInterceptor responseInterceptor; // response Interceptor to use - - private final NanoClock nanoClock; // used for testing - - private final Sleeper sleeper; // used for testing - - private Set ignoredResponseCodes = new HashSet<>(DEFAULT_IGNORED_RESPONSE_CODES); - - public RetryHttpRequestInitializer() { - this(Collections.emptyList()); - } - - /** - * @param chained a downstream HttpRequestInitializer, which will also be - * applied to HttpRequest initialization. May be null. - * - * @deprecated use {@link #RetryHttpRequestInitializer}. - */ - @Deprecated - public RetryHttpRequestInitializer(@Nullable HttpRequestInitializer chained) { - this(chained, Collections.emptyList()); - } - - /** - * @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged. - */ - public RetryHttpRequestInitializer(Collection additionalIgnoredResponseCodes) { - this(additionalIgnoredResponseCodes, null); - } - - - /** - * @param chained a downstream HttpRequestInitializer, which will also be - * applied to HttpRequest initialization. May be null. - * @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged. - * - * @deprecated use {@link #RetryHttpRequestInitializer(Collection)}. - */ - @Deprecated - public RetryHttpRequestInitializer(@Nullable HttpRequestInitializer chained, - Collection additionalIgnoredResponseCodes) { - this(chained, additionalIgnoredResponseCodes, null); - } - - /** - * @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged. - * @param responseInterceptor HttpResponseInterceptor to be applied on all requests. May be null. - */ - public RetryHttpRequestInitializer( - Collection additionalIgnoredResponseCodes, - @Nullable HttpResponseInterceptor responseInterceptor) { - this(null, NanoClock.SYSTEM, Sleeper.DEFAULT, additionalIgnoredResponseCodes, - responseInterceptor); - } - - /** - * @param chained a downstream HttpRequestInitializer, which will also be applied to HttpRequest - * initialization. May be null. - * @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged. - * @param responseInterceptor HttpResponseInterceptor to be applied on all requests. May be null. - * - * @deprecated use {@link #RetryHttpRequestInitializer(Collection, HttpResponseInterceptor)}. - */ - @Deprecated - public RetryHttpRequestInitializer( - @Nullable HttpRequestInitializer chained, - Collection additionalIgnoredResponseCodes, - @Nullable HttpResponseInterceptor responseInterceptor) { - this(chained, NanoClock.SYSTEM, Sleeper.DEFAULT, additionalIgnoredResponseCodes, - responseInterceptor); - } - - /** - * Visible for testing. - * - * @param chained a downstream HttpRequestInitializer, which will also be - * applied to HttpRequest initialization. May be null. - * @param nanoClock used as a timing source for knowing how much time has elapsed. - * @param sleeper used to sleep between retries. - * @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged. - */ - RetryHttpRequestInitializer(@Nullable HttpRequestInitializer chained, - NanoClock nanoClock, Sleeper sleeper, Collection additionalIgnoredResponseCodes, - HttpResponseInterceptor responseInterceptor) { - this.chained = chained; - this.nanoClock = nanoClock; - this.sleeper = sleeper; - this.ignoredResponseCodes.addAll(additionalIgnoredResponseCodes); - this.responseInterceptor = responseInterceptor; - } - - @Override - public void initialize(HttpRequest request) throws IOException { - if (chained != null) { - chained.initialize(request); - } - - // Set a timeout for hanging-gets. - // TODO: Do this exclusively for work requests. - request.setReadTimeout(HANGING_GET_TIMEOUT_SEC * 1000); - - // Back off on retryable http errors. - request.setUnsuccessfulResponseHandler( - // A back-off multiplier of 2 raises the maximum request retrying time - // to approximately 5 minutes (keeping other back-off parameters to - // their default values). - new LoggingHttpBackoffUnsuccessfulResponseHandler( - new ExponentialBackOff.Builder().setNanoClock(nanoClock) - .setMultiplier(2).build(), - sleeper, ignoredResponseCodes)); - - // Retry immediately on IOExceptions. - LoggingHttpBackOffIOExceptionHandler loggingBackoffHandler = - new LoggingHttpBackOffIOExceptionHandler(BackOff.ZERO_BACKOFF); - request.setIOExceptionHandler(loggingBackoffHandler); - - // Set response initializer - if (responseInterceptor != null) { - request.setResponseInterceptor(responseInterceptor); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java deleted file mode 100644 index 2406adc17c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SerializableUtils.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.decodeFromByteArray; -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; - -import org.xerial.snappy.SnappyInputStream; -import org.xerial.snappy.SnappyOutputStream; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.Arrays; - -/** - * Utilities for working with Serializables. - */ -public class SerializableUtils { - /** - * Serializes the argument into an array of bytes, and returns it. - * - * @throws IllegalArgumentException if there are errors when serializing - */ - public static byte[] serializeToByteArray(Serializable value) { - try { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - try (ObjectOutputStream oos = new ObjectOutputStream(new SnappyOutputStream(buffer))) { - oos.writeObject(value); - } - return buffer.toByteArray(); - } catch (IOException exn) { - throw new IllegalArgumentException( - "unable to serialize " + value, - exn); - } - } - - /** - * Deserializes an object from the given array of bytes, e.g., as - * serialized using {@link #serializeToByteArray}, and returns it. - * - * @throws IllegalArgumentException if there are errors when - * deserializing, using the provided description to identify what - * was being deserialized - */ - public static Object deserializeFromByteArray(byte[] encodedValue, - String description) { - try { - try (ObjectInputStream ois = new ObjectInputStream( - new SnappyInputStream(new ByteArrayInputStream(encodedValue)))) { - return ois.readObject(); - } - } catch (IOException | ClassNotFoundException exn) { - throw new IllegalArgumentException( - "unable to deserialize " + description, - exn); - } - } - - public static T ensureSerializable(T value) { - @SuppressWarnings("unchecked") - T copy = (T) deserializeFromByteArray(serializeToByteArray(value), - value.toString()); - return copy; - } - - public static T clone(T value) { - @SuppressWarnings("unchecked") - T copy = (T) deserializeFromByteArray(serializeToByteArray(value), - value.toString()); - return copy; - } - - /** - * Serializes a Coder and verifies that it can be correctly deserialized. - * - *

              Throws a RuntimeException if serialized Coder cannot be deserialized, or - * if the deserialized instance is not equal to the original. - * - * @return the serialized Coder, as a {@link CloudObject} - */ - public static CloudObject ensureSerializable(Coder coder) { - // Make sure that Coders are java serializable as well since - // they are regularly captured within DoFn's. - Coder copy = (Coder) ensureSerializable((Serializable) coder); - - CloudObject cloudObject = copy.asCloudObject(); - - Coder decoded; - try { - decoded = Serializer.deserialize(cloudObject, Coder.class); - } catch (RuntimeException e) { - throw new RuntimeException( - String.format("Unable to deserialize Coder: %s. " - + "Check that a suitable constructor is defined. " - + "See Coder for details.", coder), e - ); - } - checkState(coder.equals(decoded), - String.format("Coder not equal to original after serialization, " - + "indicating that the Coder may not implement serialization " - + "correctly. Before: %s, after: %s, cloud encoding: %s", - coder, decoded, cloudObject)); - - return cloudObject; - } - - /** - * Serializes an arbitrary T with the given {@code Coder} and verifies - * that it can be correctly deserialized. - */ - public static T ensureSerializableByCoder( - Coder coder, T value, String errorContext) { - byte[] encodedValue; - try { - encodedValue = encodeToByteArray(coder, value); - } catch (CoderException exn) { - // TODO: Put in better element printing: - // truncate if too long. - throw new IllegalArgumentException( - errorContext + ": unable to encode value " - + value + " using " + coder, - exn); - } - try { - return decodeFromByteArray(coder, encodedValue); - } catch (CoderException exn) { - // TODO: Put in better encoded byte array printing: - // use printable chars with escapes instead of codes, and - // truncate if too long. - throw new IllegalArgumentException( - errorContext + ": unable to decode " + Arrays.toString(encodedValue) - + ", encoding of value " + value + ", using " + coder, - exn); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Serializer.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Serializer.java deleted file mode 100644 index 6a8a337ab1..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Serializer.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * Utility for converting objects between Java and Cloud representations. - */ -public final class Serializer { - // Delay initialization of statics until the first call to Serializer. - private static class SingletonHelper { - static final ObjectMapper OBJECT_MAPPER = createObjectMapper(); - static final ObjectMapper TREE_MAPPER = createTreeMapper(); - - /** - * Creates the object mapper that will be used for serializing Google API - * client maps into Jackson trees. - */ - private static ObjectMapper createTreeMapper() { - return new ObjectMapper(); - } - - /** - * Creates the object mapper that will be used for deserializing Jackson - * trees into objects. - */ - private static ObjectMapper createObjectMapper() { - ObjectMapper m = new ObjectMapper(); - // Ignore properties that are not used by the object. - m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - - // For parameters of type Object, use the @type property to determine the - // class to instantiate. - // - // TODO: It would be ideal to do this for all non-final classes. The - // problem with using DefaultTyping.NON_FINAL is that it insists on having - // type information in the JSON for classes with useful default - // implementations, such as List. Ideally, we'd combine these defaults - // with available type information if that information's present. - m.enableDefaultTypingAsProperty( - ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT, - PropertyNames.OBJECT_TYPE_NAME); - - m.registerModule(new CoderUtils.Jackson2Module()); - - return m; - } - } - - /** - * Deserializes an object from a Dataflow structured encoding (represented in - * Java as a map). - * - *

              The standard Dataflow SDK object serialization protocol is based on JSON. - * Data is typically encoded as a JSON object whose fields represent the - * object's data. - * - *

              The actual deserialization is performed by Jackson, which can deserialize - * public fields, use JavaBean setters, or use injection annotations to - * indicate how to construct the object. The {@link ObjectMapper} used is - * configured to use the "@type" field as the name of the class to instantiate - * (supporting polymorphic types), and may be further configured by - * annotations or via {@link ObjectMapper#registerModule}. - * - * @see - * Jackson Data-Binding - * @see - * Jackson-Annotations - * @param serialized the object in untyped decoded form (i.e. a nested {@link Map}) - * @param clazz the expected object class - */ - public static T deserialize(Map serialized, Class clazz) { - try { - return SingletonHelper.OBJECT_MAPPER.treeToValue( - SingletonHelper.TREE_MAPPER.valueToTree( - deserializeCloudKnownTypes(serialized)), - clazz); - } catch (JsonProcessingException e) { - throw new RuntimeException( - "Unable to deserialize class " + clazz, e); - } - } - - /** - * Recursively walks the supplied map, looking for well-known cloud type - * information (keyed as {@link PropertyNames#OBJECT_TYPE_NAME}, matching a - * URI value from the {@link CloudKnownType} enum. Upon finding this type - * information, it converts it into the correspondingly typed Java value. - */ - @SuppressWarnings("unchecked") - private static Object deserializeCloudKnownTypes(Object src) { - if (src instanceof Map) { - Map srcMap = (Map) src; - @Nullable Object value = srcMap.get(PropertyNames.SCALAR_FIELD_NAME); - @Nullable CloudKnownType type = - CloudKnownType.forUri((String) srcMap.get(PropertyNames.OBJECT_TYPE_NAME)); - if (type != null && value != null) { - // It's a value of a well-known cloud type; let the known type handler - // handle the translation. - Object result = type.parse(value, type.defaultClass()); - return result; - } - // Otherwise, it's just an ordinary map. - Map dest = new HashMap<>(srcMap.size()); - for (Map.Entry entry : srcMap.entrySet()) { - dest.put(entry.getKey(), deserializeCloudKnownTypes(entry.getValue())); - } - return dest; - } - if (src instanceof List) { - List srcList = (List) src; - List dest = new ArrayList<>(srcList.size()); - for (Object obj : srcList) { - dest.add(deserializeCloudKnownTypes(obj)); - } - return dest; - } - // Neither a Map nor a List; no translation needed. - return src; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ShardingWritableByteChannel.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ShardingWritableByteChannel.java deleted file mode 100644 index 54794ef04a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ShardingWritableByteChannel.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.WritableByteChannel; -import java.util.ArrayList; - -/** - * Implements a WritableByteChannel that may contain multiple output shards. - * - *

              This provides {@link #writeToShard}, which takes a shard number for - * writing to a particular shard. - * - *

              The channel is considered open if all downstream channels are open, and - * closes all downstream channels when closed. - */ -public class ShardingWritableByteChannel implements WritableByteChannel { - - /** - * Special shard number that causes a write to all shards. - */ - public static final int ALL_SHARDS = -2; - - - private final ArrayList writers = new ArrayList<>(); - - /** - * Returns the number of output shards. - */ - public int getNumShards() { - return writers.size(); - } - - /** - * Adds another shard output channel. - */ - public void addChannel(WritableByteChannel writer) { - writers.add(writer); - } - - /** - * Returns the WritableByteChannel associated with the given shard number. - */ - public WritableByteChannel getChannel(int shardNum) { - return writers.get(shardNum); - } - - /** - * Writes the buffer to the given shard. - * - *

              This does not change the current output shard. - * - * @return The total number of bytes written. If the shard number is - * {@link #ALL_SHARDS}, then the total is the sum of each individual shard - * write. - */ - public int writeToShard(int shardNum, ByteBuffer src) throws IOException { - if (shardNum >= 0) { - return writers.get(shardNum).write(src); - } - - switch (shardNum) { - case ALL_SHARDS: - int size = 0; - for (WritableByteChannel writer : writers) { - size += writer.write(src); - } - return size; - - default: - throw new IllegalArgumentException("Illegal shard number: " + shardNum); - } - } - - /** - * Writes a buffer to all shards. - * - *

              Same as calling {@code writeToShard(ALL_SHARDS, buf)}. - */ - @Override - public int write(ByteBuffer src) throws IOException { - return writeToShard(ALL_SHARDS, src); - } - - @Override - public boolean isOpen() { - for (WritableByteChannel writer : writers) { - if (!writer.isOpen()) { - return false; - } - } - - return true; - } - - @Override - public void close() throws IOException { - for (WritableByteChannel writer : writers) { - writer.close(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SideInputReader.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SideInputReader.java deleted file mode 100644 index 37873f3136..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SideInputReader.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import javax.annotation.Nullable; - -/** - * The interface to objects that provide side inputs. Particular implementations - * may read a side input directly or use appropriate sorts of caching, etc. - */ -public interface SideInputReader { - /** - * Returns the value of the given {@link PCollectionView} for the given {@link BoundedWindow}. - * - *

              It is valid for a side input to be {@code null}. It is not valid for this to - * return {@code null} for any other reason. - */ - @Nullable - T get(PCollectionView view, BoundedWindow window); - - /** - * Returns true if the given {@link PCollectionView} is valid for this reader. - */ - boolean contains(PCollectionView view); - - /** - * Returns true if there are no side inputs in this reader. - */ - boolean isEmpty(); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java deleted file mode 100644 index 15a5e51834..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunner.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.DoFnRunners.OutputManager; -import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import java.util.List; - -/** - * Runs a {@link DoFn} by constructing the appropriate contexts and passing them in. - * - * @param the type of the DoFn's (main) input elements - * @param the type of the DoFn's (main) output elements - */ -public class SimpleDoFnRunner extends DoFnRunnerBase{ - - protected SimpleDoFnRunner(PipelineOptions options, DoFn fn, - SideInputReader sideInputReader, - OutputManager outputManager, - TupleTag mainOutputTag, List> sideOutputTags, StepContext stepContext, - AddCounterMutator addCounterMutator, WindowingStrategy windowingStrategy) { - super(options, fn, sideInputReader, outputManager, mainOutputTag, sideOutputTags, stepContext, - addCounterMutator, windowingStrategy); - } - - @Override - protected void invokeProcessElement(WindowedValue elem) { - final DoFn.ProcessContext processContext = createProcessContext(elem); - // This can contain user code. Wrap it in case it throws an exception. - try { - fn.processElement(processContext); - } catch (Exception ex) { - throw wrapUserCodeException(ex); - } - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Stager.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Stager.java deleted file mode 100644 index 5048fb0163..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Stager.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.services.dataflow.model.DataflowPackage; - -import java.util.List; - -/** - * Interface for staging files needed for running a Dataflow pipeline. - */ -public interface Stager { - /* Stage files and return a list of packages. */ - List stageFiles(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StreamUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StreamUtils.java deleted file mode 100644 index 268eb7fe4e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StreamUtils.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.SoftReference; - -/** - * Utility functions for stream operations. - */ -public class StreamUtils { - - private StreamUtils() { - } - - private static final int BUF_SIZE = 8192; - - private static ThreadLocal> threadLocalBuffer = new ThreadLocal<>(); - - /** - * Efficient converting stream to bytes. - */ - public static byte[] getBytes(InputStream stream) throws IOException { - if (stream instanceof ExposedByteArrayInputStream) { - // Fast path for the exposed version. - return ((ExposedByteArrayInputStream) stream).readAll(); - } else if (stream instanceof ByteArrayInputStream) { - // Fast path for ByteArrayInputStream. - byte[] ret = new byte[stream.available()]; - stream.read(ret); - return ret; - } - // Falls back to normal stream copying. - SoftReference refBuffer = threadLocalBuffer.get(); - byte[] buffer = refBuffer == null ? null : refBuffer.get(); - if (buffer == null) { - buffer = new byte[BUF_SIZE]; - threadLocalBuffer.set(new SoftReference(buffer)); - } - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - while (true) { - int r = stream.read(buffer); - if (r == -1) { - break; - } - outStream.write(buffer, 0, r); - } - return outStream.toByteArray(); - } - -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StringUtils.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StringUtils.java deleted file mode 100644 index 8cf2d6c5f6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/StringUtils.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.common.base.Joiner; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Utilities for working with JSON and other human-readable string formats. - */ -public class StringUtils { - /** - * Converts the given array of bytes into a legal JSON string. - * - *

              Uses a simple strategy of converting each byte to a single char, - * except for non-printable chars, non-ASCII chars, and '%', '\', - * and '"', which are encoded as three chars in '%xx' format, where - * 'xx' is the hexadecimal encoding of the byte. - */ - public static String byteArrayToJsonString(byte[] bytes) { - StringBuilder sb = new StringBuilder(bytes.length * 2); - for (byte b : bytes) { - if (b >= 32 && b < 127) { - // A printable ascii character. - char c = (char) b; - if (c != '%' && c != '\\' && c != '\"') { - // Not an escape prefix or special character, either. - // Send through unchanged. - sb.append(c); - continue; - } - } - // Send through escaped. Use '%xx' format. - sb.append(String.format("%%%02x", b)); - } - return sb.toString(); - } - - /** - * Converts the given string, encoded using {@link #byteArrayToJsonString}, - * into a byte array. - * - * @throws IllegalArgumentException if the argument string is not legal - */ - public static byte[] jsonStringToByteArray(String string) { - List bytes = new ArrayList<>(); - for (int i = 0; i < string.length(); ) { - char c = string.charAt(i); - Byte b; - if (c == '%') { - // Escaped. Expect '%xx' format. - try { - b = (byte) Integer.parseInt(string.substring(i + 1, i + 3), 16); - } catch (IndexOutOfBoundsException | NumberFormatException exn) { - throw new IllegalArgumentException( - "not in legal encoded format; " - + "substring [" + i + ".." + (i + 2) + "] not in format \"%xx\"", - exn); - } - i += 3; - } else { - // Send through unchanged. - b = (byte) c; - i++; - } - bytes.add(b); - } - byte[] byteArray = new byte[bytes.size()]; - int i = 0; - for (Byte b : bytes) { - byteArray[i++] = b; - } - return byteArray; - } - - private static final String[] STANDARD_NAME_SUFFIXES = - new String[]{"DoFn", "Fn"}; - - /** - * Pattern to match a non-anonymous inner class. - * Eg, matches "Foo$Bar", or even "Foo$1$Bar", but not "Foo$1" or "Foo$1$2". - */ - private static final Pattern NAMED_INNER_CLASS = - Pattern.compile(".+\\$(?[^0-9].*)"); - - private static final String ANONYMOUS_CLASS_REGEX = "\\$[0-9]+\\$"; - - /** - * Returns a simple name for a class. - * - *

              Note: this is non-invertible - the name may be simplified to an - * extent that it cannot be mapped back to the original class. - * - *

              This can be used to generate human-readable names. It - * removes the package and outer classes from the name, - * and removes common suffixes. - * - *

              Examples: - *

                - *
              • {@code some.package.Word.SummaryDoFn} -> "Summary" - *
              • {@code another.package.PairingFn} -> "Pairing" - *
              - * - * @throws IllegalArgumentException if the class is anonymous - */ - public static String approximateSimpleName(Class clazz) { - return approximateSimpleName(clazz, /* dropOuterClassNames */ true); - } - - /** - * Returns a name for a PTransform class. - * - *

              This can be used to generate human-readable transform names. It - * removes the package from the name, and removes common suffixes. - * - *

              It is different than approximateSimpleName: - *

                - *
              • 1. It keeps the outer classes names. - *
              • 2. It removes the common transform inner class: "Bound". - *
              - * - *

              Examples: - *

                - *
              • {@code some.package.Word.Summary} -> "Word.Summary" - *
              • {@code another.package.Pairing.Bound} -> "Pairing" - *
              - */ - public static String approximatePTransformName(Class clazz) { - checkArgument(PTransform.class.isAssignableFrom(clazz)); - return approximateSimpleName(clazz, /* dropOuterClassNames */ false) - .replaceFirst("\\.Bound$", ""); - } - - /** - * Calculate the Levenshtein distance between two strings. - * - *

              The Levenshtein distance between two words is the minimum number of single-character edits - * (i.e. insertions, deletions or substitutions) required to change one string into the other. - */ - public static int getLevenshteinDistance(final String s, final String t) { - checkNotNull(s); - checkNotNull(t); - - // base cases - if (s.equals(t)) { - return 0; - } - if (s.length() == 0) { - return t.length(); - } - if (t.length() == 0) { - return s.length(); - } - - // create two work arrays to store integer distances - final int[] v0 = new int[t.length() + 1]; - final int[] v1 = new int[t.length() + 1]; - - // initialize v0 (the previous row of distances) - // this row is A[0][i]: edit distance for an empty s - // the distance is just the number of characters to delete from t - for (int i = 0; i < v0.length; i++) { - v0[i] = i; - } - - for (int i = 0; i < s.length(); i++) { - // calculate v1 (current row distances) from the previous row v0 - - // first element of v1 is A[i+1][0] - // edit distance is delete (i+1) chars from s to match empty t - v1[0] = i + 1; - - // use formula to fill in the rest of the row - for (int j = 0; j < t.length(); j++) { - int cost = (s.charAt(i) == t.charAt(j)) ? 0 : 1; - v1[j + 1] = Math.min(Math.min(v1[j] + 1, v0[j + 1] + 1), v0[j] + cost); - } - - // copy v1 (current row) to v0 (previous row) for next iteration - System.arraycopy(v1, 0, v0, 0, v0.length); - } - - return v1[t.length()]; - } - - private static String approximateSimpleName(Class clazz, boolean dropOuterClassNames) { - checkArgument(!clazz.isAnonymousClass(), - "Attempted to get simple name of anonymous class"); - - String fullName = clazz.getName(); - String shortName = fullName.substring(fullName.lastIndexOf('.') + 1); - - // Drop common suffixes for each named component. - String[] names = shortName.split("\\$"); - for (int i = 0; i < names.length; i++) { - names[i] = simplifyNameComponent(names[i]); - } - shortName = Joiner.on('$').join(names); - - if (dropOuterClassNames) { - // Simplify inner class name by dropping outer class prefixes. - Matcher m = NAMED_INNER_CLASS.matcher(shortName); - if (m.matches()) { - shortName = m.group("INNER"); - } - } else { - // Dropping anonymous outer classes - shortName = shortName.replaceAll(ANONYMOUS_CLASS_REGEX, "."); - shortName = shortName.replaceAll("\\$", "."); - } - return shortName; - } - - private static String simplifyNameComponent(String name) { - for (String suffix : STANDARD_NAME_SUFFIXES) { - if (name.endsWith(suffix) && name.length() > suffix.length()) { - return name.substring(0, name.length() - suffix.length()); - } - } - return name; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java deleted file mode 100644 index c621c5564e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Structs.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.util.Data; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * A collection of static methods for manipulating datastructure representations - * transferred via the Dataflow API. - */ -public final class Structs { - private Structs() {} // Non-instantiable - - public static String getString(Map map, String name) throws Exception { - return getValue(map, name, String.class, "a string"); - } - - public static String getString( - Map map, String name, @Nullable String defaultValue) - throws Exception { - return getValue(map, name, String.class, "a string", defaultValue); - } - - public static byte[] getBytes(Map map, String name) throws Exception { - @Nullable byte[] result = getBytes(map, name, null); - if (result == null) { - throw new ParameterNotFoundException(name, map); - } - return result; - } - - @Nullable - public static byte[] getBytes(Map map, String name, @Nullable byte[] defaultValue) - throws Exception { - @Nullable String jsonString = getString(map, name, null); - if (jsonString == null) { - return defaultValue; - } - // TODO: Need to agree on a format for encoding bytes in - // a string that can be sent to the backend, over the cloud - // map task work API. base64 encoding seems pretty common. Switch to it? - return StringUtils.jsonStringToByteArray(jsonString); - } - - public static Boolean getBoolean(Map map, String name) throws Exception { - return getValue(map, name, Boolean.class, "a boolean"); - } - - @Nullable - public static Boolean getBoolean( - Map map, String name, @Nullable Boolean defaultValue) - throws Exception { - return getValue(map, name, Boolean.class, "a boolean", defaultValue); - } - - public static Long getLong(Map map, String name) throws Exception { - return getValue(map, name, Long.class, "a long"); - } - - @Nullable - public static Long getLong(Map map, String name, @Nullable Long defaultValue) - throws Exception { - return getValue(map, name, Long.class, "a long", defaultValue); - } - - public static Integer getInt(Map map, String name) throws Exception { - return getValue(map, name, Integer.class, "an int"); - } - - @Nullable - public static Integer getInt(Map map, String name, @Nullable Integer defaultValue) - throws Exception { - return getValue(map, name, Integer.class, "an int", defaultValue); - } - - @Nullable - public static List getStrings( - Map map, String name, @Nullable List defaultValue) - throws Exception { - @Nullable Object value = map.get(name); - if (value == null) { - if (map.containsKey(name)) { - throw new IncorrectTypeException(name, map, "a string or a list"); - } - return defaultValue; - } - if (Data.isNull(value)) { - // This is a JSON literal null. When represented as a list of strings, - // this is an empty list. - return Collections.emptyList(); - } - @Nullable String singletonString = decodeValue(value, String.class); - if (singletonString != null) { - return Collections.singletonList(singletonString); - } - if (!(value instanceof List)) { - throw new IncorrectTypeException(name, map, "a string or a list"); - } - @SuppressWarnings("unchecked") - List elements = (List) value; - List result = new ArrayList<>(elements.size()); - for (Object o : elements) { - @Nullable String s = decodeValue(o, String.class); - if (s == null) { - throw new IncorrectTypeException(name, map, "a list of strings"); - } - result.add(s); - } - return result; - } - - public static Map getObject(Map map, String name) - throws Exception { - @Nullable Map result = getObject(map, name, null); - if (result == null) { - throw new ParameterNotFoundException(name, map); - } - return result; - } - - @Nullable - public static Map getObject( - Map map, String name, @Nullable Map defaultValue) - throws Exception { - @Nullable Object value = map.get(name); - if (value == null) { - if (map.containsKey(name)) { - throw new IncorrectTypeException(name, map, "an object"); - } - return defaultValue; - } - return checkObject(value, map, name); - } - - private static Map checkObject( - Object value, Map map, String name) throws Exception { - if (Data.isNull(value)) { - // This is a JSON literal null. When represented as an object, this is an - // empty map. - return Collections.emptyMap(); - } - if (!(value instanceof Map)) { - throw new IncorrectTypeException(name, map, "an object (not a map)"); - } - @SuppressWarnings("unchecked") - Map mapValue = (Map) value; - if (!mapValue.containsKey(PropertyNames.OBJECT_TYPE_NAME)) { - throw new IncorrectTypeException(name, map, - "an object (no \"" + PropertyNames.OBJECT_TYPE_NAME + "\" field)"); - } - return mapValue; - } - - @Nullable - public static List> getListOfMaps(Map map, String name, - @Nullable List> defaultValue) throws Exception { - @Nullable - Object value = map.get(name); - if (value == null) { - if (map.containsKey(name)) { - throw new IncorrectTypeException(name, map, "a list"); - } - return defaultValue; - } - if (Data.isNull(value)) { - // This is a JSON literal null. When represented as a list, - // this is an empty list. - return Collections.>emptyList(); - } - - if (!(value instanceof List)) { - throw new IncorrectTypeException(name, map, "a list"); - } - - List elements = (List) value; - for (Object elem : elements) { - if (!(elem instanceof Map)) { - throw new IncorrectTypeException(name, map, "a list of Map objects"); - } - } - - @SuppressWarnings("unchecked") - List> result = (List>) elements; - return result; - } - - public static Map getDictionary( - Map map, String name) throws Exception { - @Nullable Object value = map.get(name); - if (value == null) { - throw new ParameterNotFoundException(name, map); - } - if (Data.isNull(value)) { - // This is a JSON literal null. When represented as a dictionary, this is - // an empty map. - return Collections.emptyMap(); - } - if (!(value instanceof Map)) { - throw new IncorrectTypeException(name, map, "a dictionary"); - } - @SuppressWarnings("unchecked") - Map result = (Map) value; - return result; - } - - @Nullable - public static Map getDictionary( - Map map, String name, @Nullable Map defaultValue) - throws Exception { - @Nullable Object value = map.get(name); - if (value == null) { - if (map.containsKey(name)) { - throw new IncorrectTypeException(name, map, "a dictionary"); - } - return defaultValue; - } - if (Data.isNull(value)) { - // This is a JSON literal null. When represented as a dictionary, this is - // an empty map. - return Collections.emptyMap(); - } - if (!(value instanceof Map)) { - throw new IncorrectTypeException(name, map, "a dictionary"); - } - @SuppressWarnings("unchecked") - Map result = (Map) value; - return result; - } - - // Builder operations. - - public static void addString(Map map, String name, String value) { - addObject(map, name, CloudObject.forString(value)); - } - - public static void addBoolean(Map map, String name, boolean value) { - addObject(map, name, CloudObject.forBoolean(value)); - } - - public static void addLong(Map map, String name, long value) { - addObject(map, name, CloudObject.forInteger(value)); - } - - public static void addObject( - Map map, String name, Map value) { - map.put(name, value); - } - - public static void addNull(Map map, String name) { - map.put(name, Data.nullOf(Object.class)); - } - - public static void addLongs(Map map, String name, long... longs) { - List> elements = new ArrayList<>(longs.length); - for (Long value : longs) { - elements.add(CloudObject.forInteger(value)); - } - map.put(name, elements); - } - - public static void addList( - Map map, String name, List> elements) { - map.put(name, elements); - } - - public static void addStringList(Map map, String name, List elements) { - ArrayList objects = new ArrayList<>(elements.size()); - for (String element : elements) { - objects.add(CloudObject.forString(element)); - } - addList(map, name, objects); - } - - public static > void addList( - Map map, String name, T[] elements) { - map.put(name, Arrays.asList(elements)); - } - - public static void addDictionary( - Map map, String name, Map value) { - map.put(name, value); - } - - public static void addDouble(Map map, String name, Double value) { - addObject(map, name, CloudObject.forFloat(value)); - } - - // Helper methods for a few of the accessor methods. - - private static T getValue(Map map, String name, Class clazz, String type) - throws Exception { - @Nullable T result = getValue(map, name, clazz, type, null); - if (result == null) { - throw new ParameterNotFoundException(name, map); - } - return result; - } - - @Nullable - private static T getValue( - Map map, String name, Class clazz, String type, @Nullable T defaultValue) - throws Exception { - @Nullable Object value = map.get(name); - if (value == null) { - if (map.containsKey(name)) { - throw new IncorrectTypeException(name, map, type); - } - return defaultValue; - } - T result = decodeValue(value, clazz); - if (result == null) { - // The value exists, but can't be decoded. - throw new IncorrectTypeException(name, map, type); - } - return result; - } - - @Nullable - private static T decodeValue(Object value, Class clazz) { - try { - if (value.getClass() == clazz) { - // decodeValue() is only called for final classes; if the class matches, - // it's safe to just return the value, and if it doesn't match, decoding - // is needed. - return clazz.cast(value); - } - if (!(value instanceof Map)) { - return null; - } - @SuppressWarnings("unchecked") - Map map = (Map) value; - @Nullable String typeName = (String) map.get(PropertyNames.OBJECT_TYPE_NAME); - if (typeName == null) { - return null; - } - @Nullable CloudKnownType knownType = CloudKnownType.forUri(typeName); - if (knownType == null) { - return null; - } - @Nullable Object scalar = map.get(PropertyNames.SCALAR_FIELD_NAME); - if (scalar == null) { - return null; - } - return knownType.parse(scalar, clazz); - } catch (ClassCastException e) { - // If any class cast fails during decoding, the value's not decodable. - return null; - } - } - - private static final class ParameterNotFoundException extends Exception { - public ParameterNotFoundException(String name, Map map) { - super("didn't find required parameter " + name + " in " + map); - } - } - - private static final class IncorrectTypeException extends Exception { - public IncorrectTypeException(String name, Map map, String type) { - super("required parameter " + name + " in " + map + " not " + type); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemDoFnInternal.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemDoFnInternal.java deleted file mode 100644 index 3255ede875..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemDoFnInternal.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation to mark {@link DoFn DoFns} as an internal component of the Dataflow SDK. - * - *

              Currently, the only effect of this is to mark any aggregators reported by an annotated - * {@code DoFn} as a system counter (as opposed to a user counter). - * - *

              This is internal to the Dataflow SDK. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface SystemDoFnInternal {} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java deleted file mode 100644 index 16657925e3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/SystemReduceFn.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.state.AccumulatorCombiningState; -import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.CombiningState; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.ReadableState; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateMerging; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; - -/** - * {@link ReduceFn} implementing the default reduction behaviors of {@link GroupByKey}. - * - * @param The type of key being processed. - * @param The type of values associated with the key. - * @param The output type that will be produced for each key. - * @param The type of windows this operates on. - */ -public abstract class SystemReduceFn - extends ReduceFn { - private static final String BUFFER_NAME = "buf"; - - /** - * Create a factory that produces {@link SystemReduceFn} instances that that buffer all of the - * input values in persistent state and produces an {@code Iterable}. - */ - public static SystemReduceFn, Iterable, W> - buffering(final Coder inputCoder) { - final StateTag> bufferTag = - StateTags.makeSystemTagInternal(StateTags.bag(BUFFER_NAME, inputCoder)); - return new SystemReduceFn, Iterable, W>(bufferTag) { - @Override - public void prefetchOnMerge(MergingStateAccessor state) throws Exception { - StateMerging.prefetchBags(state, bufferTag); - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - StateMerging.mergeBags(c.state(), bufferTag); - } - }; - } - - /** - * Create a factory that produces {@link SystemReduceFn} instances that combine all of the input - * values using a {@link CombineFn}. - */ - public static SystemReduceFn - combining( - final Coder keyCoder, final AppliedCombineFn combineFn) { - final StateTag> bufferTag; - if (combineFn.getFn() instanceof KeyedCombineFnWithContext) { - bufferTag = StateTags.makeSystemTagInternal( - StateTags.keyedCombiningValueWithContext( - BUFFER_NAME, combineFn.getAccumulatorCoder(), - (KeyedCombineFnWithContext) combineFn.getFn())); - - } else { - bufferTag = StateTags.makeSystemTagInternal( - StateTags.keyedCombiningValue( - BUFFER_NAME, combineFn.getAccumulatorCoder(), - (KeyedCombineFn) combineFn.getFn())); - } - return new SystemReduceFn(bufferTag) { - @Override - public void prefetchOnMerge(MergingStateAccessor state) throws Exception { - StateMerging.prefetchCombiningValues(state, bufferTag); - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - StateMerging.mergeCombiningValues(c.state(), bufferTag); - } - }; - } - - private StateTag> bufferTag; - - public SystemReduceFn( - StateTag> bufferTag) { - this.bufferTag = bufferTag; - } - - @Override - public void processValue(ProcessValueContext c) throws Exception { - c.state().access(bufferTag).add(c.value()); - } - - @Override - public void prefetchOnTrigger(StateAccessor state) { - state.access(bufferTag).readLater(); - } - - @Override - public void onTrigger(OnTriggerContext c) throws Exception { - c.output(c.state().access(bufferTag).read()); - } - - @Override - public void clearState(Context c) throws Exception { - c.state().access(bufferTag).clear(); - } - - @Override - public ReadableState isEmpty(StateAccessor state) { - return state.access(bufferTag).isEmpty(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TestCredential.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TestCredential.java deleted file mode 100644 index 359e15774f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TestCredential.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.auth.oauth2.BearerToken; -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.auth.oauth2.TokenResponse; -import com.google.api.client.testing.http.MockHttpTransport; - -import java.io.IOException; - -/** - * Fake credential, for use in testing. - */ -public class TestCredential extends Credential { - - private final String token; - - public TestCredential() { - this("NULL"); - } - - public TestCredential(String token) { - super(new Builder( - BearerToken.authorizationHeaderAccessMethod()) - .setTransport(new MockHttpTransport())); - this.token = token; - } - - @Override - protected TokenResponse executeRefreshToken() throws IOException { - TokenResponse response = new TokenResponse(); - response.setExpiresInSeconds(5L * 60); - response.setAccessToken(token); - return response; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java deleted file mode 100644 index 4ff36f722a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeDomain.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * {@code TimeDomain} specifies whether an operation is based on - * timestamps of elements or current "real-world" time as reported while processing. - */ -public enum TimeDomain { - /** - * The {@code EVENT_TIME} domain corresponds to the timestamps on the elements. Time advances - * on the system watermark advances. - */ - EVENT_TIME, - - /** - * The {@code PROCESSING_TIME} domain corresponds to the current to the current (system) time. - * This is advanced during execution of the Dataflow pipeline. - */ - PROCESSING_TIME, - - /** - * Same as the {@code PROCESSING_TIME} domain, except it won't fire a timer set for time - * {@code T} until all timers from earlier stages set for a time earlier than {@code T} have - * fired. - */ - SYNCHRONIZED_PROCESSING_TIME; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeUtil.java deleted file mode 100644 index 93195a7635..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimeUtil.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.ReadableDuration; -import org.joda.time.ReadableInstant; -import org.joda.time.chrono.ISOChronology; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; - -/** - * A helper class for converting between Dataflow API and SDK time - * representations. - * - *

              Dataflow API times are strings of the form - * {@code YYYY-MM-dd'T'HH:mm:ss[.nnnn]'Z'}: that is, RFC 3339 - * strings with optional fractional seconds and a 'Z' offset. - * - *

              Dataflow API durations are strings of the form {@code ['-']sssss[.nnnn]'s'}: - * that is, seconds with optional fractional seconds and a literal 's' at the end. - * - *

              In both formats, fractional seconds are either three digits (millisecond - * resolution), six digits (microsecond resolution), or nine digits (nanosecond - * resolution). - */ -public final class TimeUtil { - private TimeUtil() {} // Non-instantiable. - - private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)(?:\\.(\\d+))?s"); - private static final Pattern TIME_PATTERN = - Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?Z"); - - /** - * Converts a {@link ReadableInstant} into a Dateflow API time value. - */ - public static String toCloudTime(ReadableInstant instant) { - // Note that since Joda objects use millisecond resolution, we always - // produce either no fractional seconds or fractional seconds with - // millisecond resolution. - - // Translate the ReadableInstant to a DateTime with ISOChronology. - DateTime time = new DateTime(instant); - - int millis = time.getMillisOfSecond(); - if (millis == 0) { - return String.format("%04d-%02d-%02dT%02d:%02d:%02dZ", - time.getYear(), - time.getMonthOfYear(), - time.getDayOfMonth(), - time.getHourOfDay(), - time.getMinuteOfHour(), - time.getSecondOfMinute()); - } else { - return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", - time.getYear(), - time.getMonthOfYear(), - time.getDayOfMonth(), - time.getHourOfDay(), - time.getMinuteOfHour(), - time.getSecondOfMinute(), - millis); - } - } - - /** - * Converts a time value received via the Dataflow API into the corresponding - * {@link Instant}. - * @return the parsed time, or null if a parse error occurs - */ - @Nullable - public static Instant fromCloudTime(String time) { - Matcher matcher = TIME_PATTERN.matcher(time); - if (!matcher.matches()) { - return null; - } - int year = Integer.valueOf(matcher.group(1)); - int month = Integer.valueOf(matcher.group(2)); - int day = Integer.valueOf(matcher.group(3)); - int hour = Integer.valueOf(matcher.group(4)); - int minute = Integer.valueOf(matcher.group(5)); - int second = Integer.valueOf(matcher.group(6)); - int millis = 0; - - String frac = matcher.group(7); - if (frac != null) { - int fracs = Integer.valueOf(frac); - if (frac.length() == 3) { // millisecond resolution - millis = fracs; - } else if (frac.length() == 6) { // microsecond resolution - millis = fracs / 1000; - } else if (frac.length() == 9) { // nanosecond resolution - millis = fracs / 1000000; - } else { - return null; - } - } - - return new DateTime(year, month, day, hour, minute, second, millis, - ISOChronology.getInstanceUTC()).toInstant(); - } - - /** - * Converts a {@link ReadableDuration} into a Dataflow API duration string. - */ - public static String toCloudDuration(ReadableDuration duration) { - // Note that since Joda objects use millisecond resolution, we always - // produce either no fractional seconds or fractional seconds with - // millisecond resolution. - long millis = duration.getMillis(); - long seconds = millis / 1000; - millis = millis % 1000; - if (millis == 0) { - return String.format("%ds", seconds); - } else { - return String.format("%d.%03ds", seconds, millis); - } - } - - /** - * Converts a Dataflow API duration string into a {@link Duration}. - * @return the parsed duration, or null if a parse error occurs - */ - @Nullable - public static Duration fromCloudDuration(String duration) { - Matcher matcher = DURATION_PATTERN.matcher(duration); - if (!matcher.matches()) { - return null; - } - long millis = Long.valueOf(matcher.group(1)) * 1000; - String frac = matcher.group(2); - if (frac != null) { - long fracs = Long.valueOf(frac); - if (frac.length() == 3) { // millisecond resolution - millis += fracs; - } else if (frac.length() == 6) { // microsecond resolution - millis += fracs / 1000; - } else if (frac.length() == 9) { // nanosecond resolution - millis += fracs / 1000000; - } else { - return null; - } - } - return Duration.millis(millis); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java deleted file mode 100644 index 57518b1ac3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TimerInternals.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ComparisonChain; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import javax.annotation.Nullable; - -/** - * Encapsulate interaction with time within the execution environment. - * - *

              This class allows setting and deleting timers, and also retrieving an - * estimate of the current time. - */ -public interface TimerInternals { - - /** - * Writes out a timer to be fired when the watermark reaches the given - * timestamp. - * - *

              The combination of {@code namespace}, {@code timestamp} and {@code domain} uniquely - * identify a timer. Multiple timers set for the same parameters can be safely deduplicated. - */ - void setTimer(TimerData timerKey); - - /** - * Deletes the given timer. - */ - void deleteTimer(TimerData timerKey); - - /** - * Returns the current timestamp in the {@link TimeDomain#PROCESSING_TIME} time domain. - */ - Instant currentProcessingTime(); - - /** - * Returns the current timestamp in the {@link TimeDomain#SYNCHRONIZED_PROCESSING_TIME} time - * domain or {@code null} if unknown. - */ - @Nullable - Instant currentSynchronizedProcessingTime(); - - /** - * Return the current, local input watermark timestamp for this computation - * in the {@link TimeDomain#EVENT_TIME} time domain. - * - *

              This value: - *

                - *
              1. Is never {@literal null}, but may be {@link BoundedWindow#TIMESTAMP_MIN_VALUE}. - *
              2. Is monotonically increasing. - *
              3. May differ between workers due to network and other delays. - *
              4. Will never be ahead of the global input watermark for this computation. But it - * may be arbitrarily behind the global input watermark. - *
              5. Any element with a timestamp before the local input watermark can be considered - * 'locally late' and be subject to special processing or be dropped entirely. - *
              - * - *

              Note that because the local input watermark can be behind the global input watermark, - * it is possible for an element to be considered locally on-time even though it is - * globally late. - */ - Instant currentInputWatermarkTime(); - - /** - * Return the current, local output watermark timestamp for this computation - * in the {@link TimeDomain#EVENT_TIME} time domain. Return {@code null} if unknown. - * - *

              This value: - *

                - *
              1. Is monotonically increasing. - *
              2. Will never be ahead of {@link #currentInputWatermarkTime} as returned above. - *
              3. May differ between workers due to network and other delays. - *
              4. However will never be behind the global input watermark for any following computation. - *
              - * - *

              In pictures: - *

              -   *  |              |       |       |       |
              -   *  |              |   D   |   C   |   B   |   A
              -   *  |              |       |       |       |
              -   * GIWM     <=    GOWM <= LOWM <= LIWM <= GIWM
              -   * (next stage)
              -   * -------------------------------------------------> event time
              -   * 
              - * where - *
                - *
              • LOWM = local output water mark. - *
              • GOWM = global output water mark. - *
              • GIWM = global input water mark. - *
              • LIWM = local input water mark. - *
              • A = A globally on-time element. - *
              • B = A globally late, but locally on-time element. - *
              • C = A locally late element which may still contribute to the timestamp of a pane. - *
              • D = A locally late element which cannot contribute to the timestamp of a pane. - *
              - * - *

              Note that if a computation emits an element which is not before the current output watermark - * then that element will always appear locally on-time in all following computations. However, - * it is possible for an element emitted before the current output watermark to appear locally - * on-time in a following computation. Thus we must be careful to never assume locally late data - * viewed on the output of a computation remains locally late on the input of a following - * computation. - */ - @Nullable - Instant currentOutputWatermarkTime(); - - /** - * Data about a timer as represented within {@link TimerInternals}. - */ - class TimerData implements Comparable { - private final StateNamespace namespace; - private final Instant timestamp; - private final TimeDomain domain; - - private TimerData(StateNamespace namespace, Instant timestamp, TimeDomain domain) { - this.namespace = checkNotNull(namespace); - this.timestamp = checkNotNull(timestamp); - this.domain = checkNotNull(domain); - } - - public StateNamespace getNamespace() { - return namespace; - } - - public Instant getTimestamp() { - return timestamp; - } - - public TimeDomain getDomain() { - return domain; - } - - /** - * Construct the {@code TimerKey} for the given parameters. - */ - public static TimerData of(StateNamespace namespace, Instant timestamp, TimeDomain domain) { - return new TimerData(namespace, timestamp, domain); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof TimerData)) { - return false; - } - - TimerData that = (TimerData) obj; - return Objects.equals(this.domain, that.domain) - && this.timestamp.isEqual(that.timestamp) - && Objects.equals(this.namespace, that.namespace); - } - - @Override - public int hashCode() { - return Objects.hash(domain, timestamp, namespace); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("namespace", namespace) - .add("timestamp", timestamp) - .add("domain", domain) - .toString(); - } - - /** - * {@inheritDoc}. - * - *

              The ordering of {@link TimerData} that are not in the same namespace or domain is - * arbitrary. - */ - @Override - public int compareTo(TimerData o) { - ComparisonChain chain = ComparisonChain.start() - .compare(timestamp.getMillis(), o.getTimestamp().getMillis()) - .compare(domain, o.domain); - if (chain.result() == 0) { - // Computing the string key may be expensive, so only do so if it is meaningful in this - // comparison. - chain = chain.compare(namespace.stringKey(), o.namespace.stringKey()); - } - return chain.result(); - } - } - - /** - * A {@link Coder} for {@link TimerData}. - */ - class TimerDataCoder extends StandardCoder { - private static final StringUtf8Coder STRING_CODER = StringUtf8Coder.of(); - private static final InstantCoder INSTANT_CODER = InstantCoder.of(); - private final Coder windowCoder; - - public static TimerDataCoder of(Coder windowCoder) { - return new TimerDataCoder(windowCoder); - } - - @SuppressWarnings("unchecked") - @JsonCreator - public static TimerDataCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 components, got " + components.size()); - return of((Coder) components.get(0)); - } - - private TimerDataCoder(Coder windowCoder) { - this.windowCoder = windowCoder; - } - - @Override - public void encode(TimerData timer, OutputStream outStream, Context context) - throws CoderException, IOException { - Context nestedContext = context.nested(); - STRING_CODER.encode(timer.namespace.stringKey(), outStream, nestedContext); - INSTANT_CODER.encode(timer.timestamp, outStream, nestedContext); - STRING_CODER.encode(timer.domain.name(), outStream, nestedContext); - } - - @Override - public TimerData decode(InputStream inStream, Context context) - throws CoderException, IOException { - Context nestedContext = context.nested(); - StateNamespace namespace = - StateNamespaces.fromString(STRING_CODER.decode(inStream, nestedContext), windowCoder); - Instant timestamp = INSTANT_CODER.decode(inStream, nestedContext); - TimeDomain domain = TimeDomain.valueOf(STRING_CODER.decode(inStream, nestedContext)); - return TimerData.of(namespace, timestamp, domain); - } - - @Override - public List> getCoderArguments() { - return Arrays.asList(windowCoder); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic("window coder must be deterministic", windowCoder); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java deleted file mode 100644 index cd4a1e7b45..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Timers.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; - -import org.joda.time.Instant; - -import javax.annotation.Nullable; - -/** - * Interface for interacting with time. - */ -@Experimental(Experimental.Kind.TIMERS) -public interface Timers { - /** - * Sets a timer to fire when the event time watermark, the current processing time, or - * the synchronized processing time watermark surpasses a given timestamp. - * - *

              See {@link TimeDomain} for details on the time domains available. - * - *

              Timers are not guaranteed to fire immediately, but will be delivered at some time - * afterwards. - * - *

              An implementation of {@link Timers} implicitly scopes timers that are set - they may - * be scoped to a key and window, or a key, window, and trigger, etc. - * - * @param timestamp the time at which the timer should be delivered - * @param timeDomain the domain that the {@code timestamp} applies to - */ - void setTimer(Instant timestamp, TimeDomain timeDomain); - - /** Removes the timer set in this context for the {@code timestmap} and {@code timeDomain}. */ - void deleteTimer(Instant timestamp, TimeDomain timeDomain); - - /** Returns the current processing time. */ - Instant currentProcessingTime(); - - /** Returns the current synchronized processing time or {@code null} if unknown. */ - @Nullable - Instant currentSynchronizedProcessingTime(); - - /** Returns the current event time. */ - Instant currentEventTime(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java deleted file mode 100644 index 6fa5d59adb..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Transport.java +++ /dev/null @@ -1,198 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.clouddebugger.v2.Clouddebugger; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.storage.Storage; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer; -import com.google.common.collect.ImmutableList; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.GeneralSecurityException; - -/** - * Helpers for cloud communication. - */ -public class Transport { - - private static class SingletonHelper { - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY; - - /** Global instance of the HTTP transport. */ - private static final HttpTransport HTTP_TRANSPORT; - - static { - try { - JSON_FACTORY = JacksonFactory.getDefaultInstance(); - HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - } catch (GeneralSecurityException | IOException e) { - throw new RuntimeException(e); - } - } - } - - public static HttpTransport getTransport() { - return SingletonHelper.HTTP_TRANSPORT; - } - - public static JsonFactory getJsonFactory() { - return SingletonHelper.JSON_FACTORY; - } - - private static class ApiComponents { - public String rootUrl; - public String servicePath; - - public ApiComponents(String root, String path) { - this.rootUrl = root; - this.servicePath = path; - } - } - - private static ApiComponents apiComponentsFromUrl(String urlString) { - try { - URL url = new URL(urlString); - String rootUrl = url.getProtocol() + "://" + url.getHost() - + (url.getPort() > 0 ? ":" + url.getPort() : ""); - return new ApiComponents(rootUrl, url.getPath()); - } catch (MalformedURLException e) { - throw new RuntimeException("Invalid URL: " + urlString); - } - } - - /** - * Returns a BigQuery client builder. - * - *

              Note: this client's endpoint is not modified by the - * {@link DataflowPipelineDebugOptions#getApiRootUrl()} option. - */ - public static Bigquery.Builder - newBigQueryClient(BigQueryOptions options) { - return new Bigquery.Builder(getTransport(), getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - /** - * Returns a Pubsub client builder. - * - *

              Note: this client's endpoint is not modified by the - * {@link DataflowPipelineDebugOptions#getApiRootUrl()} option. - * - * @deprecated Use an appropriate - * {@link com.google.cloud.dataflow.sdk.util.PubsubClient.PubsubClientFactory} - */ - @Deprecated - public static Pubsub.Builder - newPubsubClient(DataflowPipelineOptions options) { - return new Pubsub.Builder(getTransport(), getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setRootUrl(options.getPubsubRootUrl()) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - /** - * Returns a Google Cloud Dataflow client builder. - */ - public static Dataflow.Builder newDataflowClient(DataflowPipelineOptions options) { - String servicePath = options.getDataflowEndpoint(); - ApiComponents components; - if (servicePath.contains("://")) { - components = apiComponentsFromUrl(servicePath); - } else { - components = new ApiComponents(options.getApiRootUrl(), servicePath); - } - - return new Dataflow.Builder(getTransport(), - getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setApplicationName(options.getAppName()) - .setRootUrl(components.rootUrl) - .setServicePath(components.servicePath) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - public static Clouddebugger.Builder newClouddebuggerClient(DataflowPipelineOptions options) { - return new Clouddebugger.Builder(getTransport(), - getJsonFactory(), - chainHttpRequestInitializer(options.getGcpCredential(), new RetryHttpRequestInitializer())) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - /** - * Returns a Cloud Storage client builder. - * - *

              Note: this client's endpoint is not modified by the - * {@link DataflowPipelineDebugOptions#getApiRootUrl()} option. - */ - public static Storage.Builder - newStorageClient(GcsOptions options) { - String servicePath = options.getGcsEndpoint(); - Storage.Builder storageBuilder = new Storage.Builder(getTransport(), getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log the code 404. Code up the stack will deal with 404's if needed, and - // logging it by default clutters the output during file staging. - new RetryHttpRequestInitializer( - ImmutableList.of(404), new UploadIdResponseInterceptor()))) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - if (servicePath != null) { - ApiComponents components = apiComponentsFromUrl(servicePath); - storageBuilder.setRootUrl(components.rootUrl); - storageBuilder.setServicePath(components.servicePath); - } - return storageBuilder; - } - - private static HttpRequestInitializer chainHttpRequestInitializer( - Credential credential, HttpRequestInitializer httpRequestInitializer) { - if (credential == null) { - return httpRequestInitializer; - } else { - return new ChainingHttpRequestInitializer(credential, httpRequestInitializer); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java deleted file mode 100644 index 50e8b324ea..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerContextFactory.java +++ /dev/null @@ -1,521 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.MergingTriggerInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.TriggerInfo; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; - -import org.joda.time.Instant; - -import java.util.Collection; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * Factory for creating instances of the various {@link Trigger} contexts. - * - *

              These contexts are highly interdependent and share many fields; it is inadvisable - * to create them via any means other than this factory class. - */ -public class TriggerContextFactory { - - private final WindowingStrategy windowingStrategy; - private StateInternals stateInternals; - // Future triggers may be able to exploit the active window to state address window mapping. - @SuppressWarnings("unused") - private ActiveWindowSet activeWindows; - private final Coder windowCoder; - - public TriggerContextFactory(WindowingStrategy windowingStrategy, - StateInternals stateInternals, ActiveWindowSet activeWindows) { - this.windowingStrategy = windowingStrategy; - this.stateInternals = stateInternals; - this.activeWindows = activeWindows; - this.windowCoder = windowingStrategy.getWindowFn().windowCoder(); - } - - public Trigger.TriggerContext base(W window, Timers timers, - ExecutableTrigger rootTrigger, FinishedTriggers finishedSet) { - return new TriggerContextImpl(window, timers, rootTrigger, finishedSet); - } - - public Trigger.OnElementContext createOnElementContext( - W window, Timers timers, Instant elementTimestamp, - ExecutableTrigger rootTrigger, FinishedTriggers finishedSet) { - return new OnElementContextImpl(window, timers, rootTrigger, finishedSet, elementTimestamp); - } - - public Trigger.OnMergeContext createOnMergeContext(W window, Timers timers, - ExecutableTrigger rootTrigger, FinishedTriggers finishedSet, - Map finishedSets) { - return new OnMergeContextImpl(window, timers, rootTrigger, finishedSet, finishedSets); - } - - public StateAccessor createStateAccessor(W window, ExecutableTrigger trigger) { - return new StateAccessorImpl(window, trigger); - } - - public MergingStateAccessor createMergingStateAccessor( - W mergeResult, Collection mergingWindows, ExecutableTrigger trigger) { - return new MergingStateAccessorImpl(trigger, mergingWindows, mergeResult); - } - - private class TriggerInfoImpl implements Trigger.TriggerInfo { - - protected final ExecutableTrigger trigger; - protected final FinishedTriggers finishedSet; - private final Trigger.TriggerContext context; - - public TriggerInfoImpl(ExecutableTrigger trigger, FinishedTriggers finishedSet, - Trigger.TriggerContext context) { - this.trigger = trigger; - this.finishedSet = finishedSet; - this.context = context; - } - - @Override - public boolean isMerging() { - return !windowingStrategy.getWindowFn().isNonMerging(); - } - - @Override - public Iterable> subTriggers() { - return trigger.subTriggers(); - } - - @Override - public ExecutableTrigger subTrigger(int subtriggerIndex) { - return trigger.subTriggers().get(subtriggerIndex); - } - - @Override - public boolean isFinished() { - return finishedSet.isFinished(trigger); - } - - @Override - public boolean isFinished(int subtriggerIndex) { - return finishedSet.isFinished(subTrigger(subtriggerIndex)); - } - - @Override - public boolean areAllSubtriggersFinished() { - return Iterables.isEmpty(unfinishedSubTriggers()); - } - - @Override - public Iterable> unfinishedSubTriggers() { - return FluentIterable - .from(trigger.subTriggers()) - .filter(new Predicate>() { - @Override - public boolean apply(ExecutableTrigger trigger) { - return !finishedSet.isFinished(trigger); - } - }); - } - - @Override - public ExecutableTrigger firstUnfinishedSubTrigger() { - for (ExecutableTrigger subTrigger : trigger.subTriggers()) { - if (!finishedSet.isFinished(subTrigger)) { - return subTrigger; - } - } - return null; - } - - @Override - public void resetTree() throws Exception { - finishedSet.clearRecursively(trigger); - trigger.invokeClear(context); - } - - @Override - public void setFinished(boolean finished) { - finishedSet.setFinished(trigger, finished); - } - - @Override - public void setFinished(boolean finished, int subTriggerIndex) { - finishedSet.setFinished(subTrigger(subTriggerIndex), finished); - } - } - - private class TriggerTimers implements Timers { - - private final Timers timers; - private final W window; - - public TriggerTimers(W window, Timers timers) { - this.timers = timers; - this.window = window; - } - - @Override - public void setTimer(Instant timestamp, TimeDomain timeDomain) { - timers.setTimer(timestamp, timeDomain); - } - - @Override - public void deleteTimer(Instant timestamp, TimeDomain timeDomain) { - if (timeDomain == TimeDomain.EVENT_TIME - && timestamp.equals(window.maxTimestamp())) { - // Don't allow triggers to unset the at-max-timestamp timer. This is necessary for on-time - // state transitions. - return; - } - timers.deleteTimer(timestamp, timeDomain); - } - - @Override - public Instant currentProcessingTime() { - return timers.currentProcessingTime(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return timers.currentSynchronizedProcessingTime(); - } - - @Override - public Instant currentEventTime() { - return timers.currentEventTime(); - } - } - - private class MergingTriggerInfoImpl - extends TriggerInfoImpl implements Trigger.MergingTriggerInfo { - - private final Map finishedSets; - - public MergingTriggerInfoImpl( - ExecutableTrigger trigger, - FinishedTriggers finishedSet, - Trigger.TriggerContext context, - Map finishedSets) { - super(trigger, finishedSet, context); - this.finishedSets = finishedSets; - } - - @Override - public boolean finishedInAnyMergingWindow() { - for (FinishedTriggers finishedSet : finishedSets.values()) { - if (finishedSet.isFinished(trigger)) { - return true; - } - } - return false; - } - - @Override - public boolean finishedInAllMergingWindows() { - for (FinishedTriggers finishedSet : finishedSets.values()) { - if (!finishedSet.isFinished(trigger)) { - return false; - } - } - return true; - } - - @Override - public Iterable getFinishedMergingWindows() { - return Maps.filterValues(finishedSets, new Predicate() { - @Override - public boolean apply(FinishedTriggers finishedSet) { - return finishedSet.isFinished(trigger); - } - }).keySet(); - } - } - - private class StateAccessorImpl implements StateAccessor { - protected final int triggerIndex; - protected final StateNamespace windowNamespace; - - public StateAccessorImpl( - W window, - ExecutableTrigger trigger) { - this.triggerIndex = trigger.getTriggerIndex(); - this.windowNamespace = namespaceFor(window); - } - - protected StateNamespace namespaceFor(W window) { - return StateNamespaces.windowAndTrigger(windowCoder, window, triggerIndex); - } - - @Override - public StateT access(StateTag address) { - return stateInternals.state(windowNamespace, address); - } - } - - private class MergingStateAccessorImpl extends StateAccessorImpl - implements MergingStateAccessor { - private final Collection activeToBeMerged; - - public MergingStateAccessorImpl(ExecutableTrigger trigger, Collection activeToBeMerged, - W mergeResult) { - super(mergeResult, trigger); - this.activeToBeMerged = activeToBeMerged; - } - - @Override - public StateT access( - StateTag address) { - return stateInternals.state(windowNamespace, address); - } - - @Override - public Map accessInEachMergingWindow( - StateTag address) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (W mergingWindow : activeToBeMerged) { - StateT stateForWindow = stateInternals.state(namespaceFor(mergingWindow), address); - builder.put(mergingWindow, stateForWindow); - } - return builder.build(); - } - } - - private class TriggerContextImpl extends Trigger.TriggerContext { - - private final W window; - private final StateAccessorImpl state; - private final Timers timers; - private final TriggerInfoImpl triggerInfo; - - private TriggerContextImpl( - W window, - Timers timers, - ExecutableTrigger trigger, - FinishedTriggers finishedSet) { - trigger.getSpec().super(); - this.window = window; - this.state = new StateAccessorImpl(window, trigger); - this.timers = new TriggerTimers(window, timers); - this.triggerInfo = new TriggerInfoImpl(trigger, finishedSet, this); - } - - @Override - public Trigger.TriggerContext forTrigger(ExecutableTrigger trigger) { - return new TriggerContextImpl(window, timers, trigger, triggerInfo.finishedSet); - } - - @Override - public TriggerInfo trigger() { - return triggerInfo; - } - - @Override - public StateAccessor state() { - return state; - } - - @Override - public W window() { - return window; - } - - @Override - public void deleteTimer(Instant timestamp, TimeDomain domain) { - timers.deleteTimer(timestamp, domain); - } - - @Override - public Instant currentProcessingTime() { - return timers.currentProcessingTime(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return timers.currentSynchronizedProcessingTime(); - } - - @Override - @Nullable - public Instant currentEventTime() { - return timers.currentEventTime(); - } - } - - private class OnElementContextImpl extends Trigger.OnElementContext { - - private final W window; - private final StateAccessorImpl state; - private final Timers timers; - private final TriggerInfoImpl triggerInfo; - private final Instant eventTimestamp; - - private OnElementContextImpl( - W window, - Timers timers, - ExecutableTrigger trigger, - FinishedTriggers finishedSet, - Instant eventTimestamp) { - trigger.getSpec().super(); - this.window = window; - this.state = new StateAccessorImpl(window, trigger); - this.timers = new TriggerTimers(window, timers); - this.triggerInfo = new TriggerInfoImpl(trigger, finishedSet, this); - this.eventTimestamp = eventTimestamp; - } - - - @Override - public Instant eventTimestamp() { - return eventTimestamp; - } - - @Override - public Trigger.OnElementContext forTrigger(ExecutableTrigger trigger) { - return new OnElementContextImpl( - window, timers, trigger, triggerInfo.finishedSet, eventTimestamp); - } - - @Override - public TriggerInfo trigger() { - return triggerInfo; - } - - @Override - public StateAccessor state() { - return state; - } - - @Override - public W window() { - return window; - } - - @Override - public void setTimer(Instant timestamp, TimeDomain domain) { - timers.setTimer(timestamp, domain); - } - - - @Override - public void deleteTimer(Instant timestamp, TimeDomain domain) { - timers.deleteTimer(timestamp, domain); - } - - @Override - public Instant currentProcessingTime() { - return timers.currentProcessingTime(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return timers.currentSynchronizedProcessingTime(); - } - - @Override - @Nullable - public Instant currentEventTime() { - return timers.currentEventTime(); - } - } - - private class OnMergeContextImpl extends Trigger.OnMergeContext { - private final MergingStateAccessor state; - private final W window; - private final Collection mergingWindows; - private final Timers timers; - private final MergingTriggerInfoImpl triggerInfo; - - private OnMergeContextImpl( - W window, - Timers timers, - ExecutableTrigger trigger, - FinishedTriggers finishedSet, - Map finishedSets) { - trigger.getSpec().super(); - this.mergingWindows = finishedSets.keySet(); - this.window = window; - this.state = new MergingStateAccessorImpl(trigger, mergingWindows, window); - this.timers = new TriggerTimers(window, timers); - this.triggerInfo = new MergingTriggerInfoImpl(trigger, finishedSet, this, finishedSets); - } - - @Override - public Trigger.OnMergeContext forTrigger(ExecutableTrigger trigger) { - return new OnMergeContextImpl( - window, timers, trigger, triggerInfo.finishedSet, triggerInfo.finishedSets); - } - - @Override - public MergingStateAccessor state() { - return state; - } - - @Override - public MergingTriggerInfo trigger() { - return triggerInfo; - } - - @Override - public W window() { - return window; - } - - @Override - public void setTimer(Instant timestamp, TimeDomain domain) { - timers.setTimer(timestamp, domain); - } - - @Override - public void deleteTimer(Instant timestamp, TimeDomain domain) { - timers.setTimer(timestamp, domain); - - } - - @Override - public Instant currentProcessingTime() { - return timers.currentProcessingTime(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return timers.currentSynchronizedProcessingTime(); - } - - @Override - @Nullable - public Instant currentEventTime() { - return timers.currentEventTime(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java deleted file mode 100644 index 672d846bb6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/TriggerRunner.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateAccessor; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.ValueState; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMap; - -import org.joda.time.Instant; - -import java.util.BitSet; -import java.util.Collection; -import java.util.Map; - -/** - * Executes a trigger while managing persistence of information about which subtriggers are - * finished. Subtriggers include all recursive trigger expressions as well as the entire trigger. - * - *

              Specifically, the responsibilities are: - * - *

                - *
              • Invoking the trigger's methods via its {@link ExecutableTrigger} wrapper by - * constructing the appropriate trigger contexts.
              • - *
              • Committing a record of which subtriggers are finished to persistent state.
              • - *
              • Restoring the record of which subtriggers are finished from persistent state.
              • - *
              • Clearing out the persisted finished set when a caller indicates - * (via {#link #clearFinished}) that it is no longer needed.
              • - *
              - * - *

              These responsibilities are intertwined: trigger contexts include mutable information about - * which subtriggers are finished. This class provides the information when building the contexts - * and commits the information when the method of the {@link ExecutableTrigger} returns. - * - * @param The kind of windows being processed. - */ -public class TriggerRunner { - @VisibleForTesting - static final StateTag> FINISHED_BITS_TAG = - StateTags.makeSystemTagInternal(StateTags.value("closed", BitSetCoder.of())); - - private final ExecutableTrigger rootTrigger; - private final TriggerContextFactory contextFactory; - - public TriggerRunner(ExecutableTrigger rootTrigger, TriggerContextFactory contextFactory) { - checkState(rootTrigger.getTriggerIndex() == 0); - this.rootTrigger = rootTrigger; - this.contextFactory = contextFactory; - } - - private FinishedTriggersBitSet readFinishedBits(ValueState state) { - if (!isFinishedSetNeeded()) { - // If no trigger in the tree will ever have finished bits, then we don't need to read them. - // So that the code can be agnostic to that fact, we create a BitSet that is all 0 (not - // finished) for each trigger in the tree. - return FinishedTriggersBitSet.emptyWithCapacity(rootTrigger.getFirstIndexAfterSubtree()); - } - - BitSet bitSet = state.read(); - return bitSet == null - ? FinishedTriggersBitSet.emptyWithCapacity(rootTrigger.getFirstIndexAfterSubtree()) - : FinishedTriggersBitSet.fromBitSet(bitSet); - } - - private void clearFinishedBits(ValueState state) { - if (!isFinishedSetNeeded()) { - // Nothing to clear. - return; - } - state.clear(); - } - - /** Return true if the trigger is closed in the window corresponding to the specified state. */ - public boolean isClosed(StateAccessor state) { - return readFinishedBits(state.access(FINISHED_BITS_TAG)).isFinished(rootTrigger); - } - - public void prefetchIsClosed(StateAccessor state) { - if (isFinishedSetNeeded()) { - state.access(FINISHED_BITS_TAG).readLater(); - } - } - - public void prefetchForValue(W window, StateAccessor state) { - prefetchIsClosed(state); - rootTrigger.getSpec().prefetchOnElement( - contextFactory.createStateAccessor(window, rootTrigger)); - } - - public void prefetchOnFire(W window, StateAccessor state) { - prefetchIsClosed(state); - rootTrigger.getSpec().prefetchOnFire(contextFactory.createStateAccessor(window, rootTrigger)); - } - - public void prefetchShouldFire(W window, StateAccessor state) { - prefetchIsClosed(state); - rootTrigger.getSpec().prefetchShouldFire( - contextFactory.createStateAccessor(window, rootTrigger)); - } - - /** - * Run the trigger logic to deal with a new value. - */ - public void processValue(W window, Instant timestamp, Timers timers, StateAccessor state) - throws Exception { - // Clone so that we can detect changes and so that changes here don't pollute merging. - FinishedTriggersBitSet finishedSet = - readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); - Trigger.OnElementContext triggerContext = contextFactory.createOnElementContext( - window, timers, timestamp, rootTrigger, finishedSet); - rootTrigger.invokeOnElement(triggerContext); - persistFinishedSet(state, finishedSet); - } - - public void prefetchForMerge( - W window, Collection mergingWindows, MergingStateAccessor state) { - if (isFinishedSetNeeded()) { - for (ValueState value : state.accessInEachMergingWindow(FINISHED_BITS_TAG).values()) { - value.readLater(); - } - } - rootTrigger.getSpec().prefetchOnMerge(contextFactory.createMergingStateAccessor( - window, mergingWindows, rootTrigger)); - } - - /** - * Run the trigger merging logic as part of executing the specified merge. - */ - public void onMerge(W window, Timers timers, MergingStateAccessor state) throws Exception { - // Clone so that we can detect changes and so that changes here don't pollute merging. - FinishedTriggersBitSet finishedSet = - readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); - - // And read the finished bits in each merging window. - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (Map.Entry> entry : - state.accessInEachMergingWindow(FINISHED_BITS_TAG).entrySet()) { - // Don't need to clone these, since the trigger context doesn't allow modification - builder.put(entry.getKey(), readFinishedBits(entry.getValue())); - // Clear the underlying finished bits. - clearFinishedBits(entry.getValue()); - } - ImmutableMap mergingFinishedSets = builder.build(); - - Trigger.OnMergeContext mergeContext = contextFactory.createOnMergeContext( - window, timers, rootTrigger, finishedSet, mergingFinishedSets); - - // Run the merge from the trigger - rootTrigger.invokeOnMerge(mergeContext); - - persistFinishedSet(state, finishedSet); - - } - - public boolean shouldFire(W window, Timers timers, StateAccessor state) throws Exception { - FinishedTriggers finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); - Trigger.TriggerContext context = contextFactory.base(window, timers, - rootTrigger, finishedSet); - return rootTrigger.invokeShouldFire(context); - } - - public void onFire(W window, Timers timers, StateAccessor state) throws Exception { - // shouldFire should be false. - // However it is too expensive to assert. - FinishedTriggersBitSet finishedSet = - readFinishedBits(state.access(FINISHED_BITS_TAG)).copy(); - Trigger.TriggerContext context = contextFactory.base(window, timers, - rootTrigger, finishedSet); - rootTrigger.invokeOnFire(context); - persistFinishedSet(state, finishedSet); - } - - private void persistFinishedSet( - StateAccessor state, FinishedTriggersBitSet modifiedFinishedSet) { - if (!isFinishedSetNeeded()) { - return; - } - - ValueState finishedSetState = state.access(FINISHED_BITS_TAG); - if (!readFinishedBits(finishedSetState).equals(modifiedFinishedSet)) { - if (modifiedFinishedSet.getBitSet().isEmpty()) { - finishedSetState.clear(); - } else { - finishedSetState.write(modifiedFinishedSet.getBitSet()); - } - } - } - - /** - * Clear the finished bits. - */ - public void clearFinished(StateAccessor state) { - clearFinishedBits(state.access(FINISHED_BITS_TAG)); - } - - /** - * Clear the state used for executing triggers, but leave the finished set to indicate - * the window is closed. - */ - public void clearState(W window, Timers timers, StateAccessor state) throws Exception { - // Don't need to clone, because we'll be clearing the finished bits anyways. - FinishedTriggers finishedSet = readFinishedBits(state.access(FINISHED_BITS_TAG)); - rootTrigger.invokeClear(contextFactory.base(window, timers, rootTrigger, finishedSet)); - } - - private boolean isFinishedSetNeeded() { - // TODO: If we know that no trigger in the tree will ever finish, we don't need to do the - // lookup. Right now, we special case this for the DefaultTrigger. - return !(rootTrigger.getSpec() instanceof DefaultTrigger); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedInputStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedInputStream.java deleted file mode 100644 index 3d80230a52..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedInputStream.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.common.base.MoreObjects; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A {@link OutputStream} wrapper which protects against the user attempting to modify - * the underlying stream by closing it or using mark. - */ -public class UnownedInputStream extends FilterInputStream { - public UnownedInputStream(InputStream delegate) { - super(delegate); - } - - @Override - public void close() throws IOException { - throw new UnsupportedOperationException("Caller does not own the underlying input stream " - + " and should not call close()."); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof UnownedInputStream - && ((UnownedInputStream) obj).in.equals(in); - } - - @Override - public int hashCode() { - return in.hashCode(); - } - - @SuppressWarnings("UnsynchronizedOverridesSynchronized") - @Override - public void mark(int readlimit) { - throw new UnsupportedOperationException("Caller does not own the underlying input stream " - + " and should not call mark()."); - } - - @Override - public boolean markSupported() { - return false; - } - - @SuppressWarnings("UnsynchronizedOverridesSynchronized") - @Override - public void reset() throws IOException { - throw new UnsupportedOperationException("Caller does not own the underlying input stream " - + " and should not call reset()."); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(UnownedInputStream.class).add("in", in).toString(); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStream.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStream.java deleted file mode 100644 index 29187a1b9d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStream.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.common.base.MoreObjects; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * A {@link OutputStream} wrapper which protects against the user attempting to modify - * the underlying stream by closing it. - */ -public class UnownedOutputStream extends FilterOutputStream { - public UnownedOutputStream(OutputStream delegate) { - super(delegate); - } - - @Override - public void close() throws IOException { - throw new UnsupportedOperationException("Caller does not own the underlying output stream " - + " and should not call close()."); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof UnownedOutputStream - && ((UnownedOutputStream) obj).out.equals(out); - } - - @Override - public int hashCode() { - return out.hashCode(); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(UnownedOutputStream.class).add("out", out).toString(); - } -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptor.java deleted file mode 100644 index da597e692e..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptor.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.http.GenericUrl; -import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpResponseInterceptor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -/** - * Implements a response intercepter that logs the upload id if the upload - * id header exists and it is the first request (does not have upload_id parameter in the request). - * Only logs if debug level is enabled. - */ -public class UploadIdResponseInterceptor implements HttpResponseInterceptor { - - private static final Logger LOG = LoggerFactory.getLogger(UploadIdResponseInterceptor.class); - private static final String UPLOAD_ID_PARAM = "upload_id"; - private static final String UPLOAD_TYPE_PARAM = "uploadType"; - private static final String UPLOAD_HEADER = "X-GUploader-UploadID"; - - @Override - public void interceptResponse(HttpResponse response) throws IOException { - if (!LOG.isDebugEnabled()) { - return; - } - String uploadId = response.getHeaders().getFirstHeaderStringValue(UPLOAD_HEADER); - if (uploadId == null) { - return; - } - - GenericUrl url = response.getRequest().getUrl(); - // The check for no upload id limits the output to one log line per upload. - // The check for upload type makes sure this is an upload and not a read. - if (url.get(UPLOAD_ID_PARAM) == null && url.get(UPLOAD_TYPE_PARAM) != null) { - LOG.debug( - "Upload ID for url {} on worker {} is {}", - url, - System.getProperty("worker_id"), - uploadId); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java deleted file mode 100644 index 12ae1059b2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/UserCodeException.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.util.Arrays; -import java.util.Objects; - -/** - * An exception that was thrown in user-code. Sets the stack trace - * from the first time execution enters user code down through the - * rest of the user's stack frames until the exception is - * reached. - */ -public class UserCodeException extends RuntimeException { - - public static UserCodeException wrap(Throwable t) { - if (t instanceof UserCodeException) { - return (UserCodeException) t; - } - - return new UserCodeException(t); - } - - public static RuntimeException wrapIf(boolean condition, Throwable t) { - if (condition) { - return wrap(t); - } - - if (t instanceof RuntimeException) { - return (RuntimeException) t; - } - - return new RuntimeException(t); - } - - private UserCodeException(Throwable t) { - super(t); - truncateStackTrace(t); - } - - /** - * Truncates the @{Throwable}'s stack trace to contain only user code, - * removing all frames below. - * - *

              This is to remove infrastructure noise below user code entry point. We do this - * by finding common stack frames between the throwable's captured stack and that - * of the current thread. - */ - private void truncateStackTrace(Throwable t) { - StackTraceElement[] currentStack = Thread.currentThread().getStackTrace(); - StackTraceElement[] throwableStack = t.getStackTrace(); - - int currentStackSize = currentStack.length; - int throwableStackSize = throwableStack.length; - - if (throwableStackSize == 0) { - // Nothing to truncate. - return; - } - - int commonFrames = 0; - while (framesEqual(currentStack[currentStackSize - commonFrames - 1], - throwableStack[throwableStackSize - commonFrames - 1])) { - commonFrames++; - if (commonFrames >= Math.min(currentStackSize, throwableStackSize)) { - break; - } - } - - StackTraceElement[] truncatedStack = Arrays.copyOfRange(throwableStack, 0, - throwableStackSize - commonFrames); - t.setStackTrace(truncatedStack); - } - - /** - * Check if two frames are equal; Frames are considered equal if they point to the same method. - */ - private boolean framesEqual(StackTraceElement frame1, StackTraceElement frame2) { - boolean areEqual = Objects.equals(frame1.getClassName(), frame2.getClassName()); - areEqual &= Objects.equals(frame1.getMethodName(), frame2.getMethodName()); - - return areEqual; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ValueWithRecordId.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ValueWithRecordId.java deleted file mode 100644 index ea1c16ffdf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ValueWithRecordId.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.MoreObjects; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -/** - * Immutable struct containing a value as well as a unique id identifying the value. - * - * @param the underlying value type - */ -public class ValueWithRecordId { - private final ValueT value; - private final byte[] id; - - public ValueWithRecordId(ValueT value, byte[] id) { - this.value = value; - this.id = id; - } - - public ValueT getValue() { - return value; - } - - public byte[] getId() { - return id; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("id", id) - .add("value", value) - .toString(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof ValueWithRecordId)) { - return false; - } - ValueWithRecordId otherRecord = (ValueWithRecordId) other; - return Objects.deepEquals(id, otherRecord.id) - && Objects.deepEquals(value, otherRecord.value); - } - - @Override - public int hashCode() { - return Objects.hash(Arrays.hashCode(id), value); - } - - /** - * A {@link Coder} for {@code ValueWithRecordId}, using a wrapped value {@code Coder}. - */ - public static class ValueWithRecordIdCoder - extends StandardCoder> { - public static ValueWithRecordIdCoder of(Coder valueCoder) { - return new ValueWithRecordIdCoder<>(valueCoder); - } - - @JsonCreator - public static ValueWithRecordIdCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return of(components.get(0)); - } - - protected ValueWithRecordIdCoder(Coder valueCoder) { - this.valueCoder = valueCoder; - this.idCoder = ByteArrayCoder.of(); - } - - @Override - public List> getCoderArguments() { - return Arrays.asList(valueCoder); - } - - @Override - public void encode(ValueWithRecordId value, OutputStream outStream, Context context) - throws IOException { - valueCoder.encode(value.value, outStream, context.nested()); - idCoder.encode(value.id, outStream, context); - } - - @Override - public ValueWithRecordId decode(InputStream inStream, Context context) - throws IOException { - return new ValueWithRecordId( - valueCoder.decode(inStream, context.nested()), - idCoder.decode(inStream, context)); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - valueCoder.verifyDeterministic(); - } - - public Coder getValueCoder() { - return valueCoder; - } - - Coder valueCoder; - ByteArrayCoder idCoder; - } - - public static - PTransform>, PCollection> stripIds() { - return ParDo.named("StripIds") - .of( - new DoFn, T>() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().getValue()); - } - }); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Values.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Values.java deleted file mode 100644 index d4440e76de..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Values.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * A collection of static methods for manipulating value representations - * transfered via the Dataflow API. - */ -public final class Values { - private Values() {} // Non-instantiable - - public static Boolean asBoolean(Object value) throws ClassCastException { - @Nullable Boolean knownResult = checkKnownValue(CloudKnownType.BOOLEAN, value, Boolean.class); - if (knownResult != null) { - return knownResult; - } - return Boolean.class.cast(value); - } - - public static Double asDouble(Object value) throws ClassCastException { - @Nullable Double knownResult = checkKnownValue(CloudKnownType.FLOAT, value, Double.class); - if (knownResult != null) { - return knownResult; - } - if (value instanceof Double) { - return (Double) value; - } - return ((Float) value).doubleValue(); - } - - public static Long asLong(Object value) throws ClassCastException { - @Nullable Long knownResult = checkKnownValue(CloudKnownType.INTEGER, value, Long.class); - if (knownResult != null) { - return knownResult; - } - if (value instanceof Long) { - return (Long) value; - } - return ((Integer) value).longValue(); - } - - public static String asString(Object value) throws ClassCastException { - @Nullable String knownResult = checkKnownValue(CloudKnownType.TEXT, value, String.class); - if (knownResult != null) { - return knownResult; - } - return String.class.cast(value); - } - - @Nullable - private static T checkKnownValue(CloudKnownType type, Object value, Class clazz) { - if (!(value instanceof Map)) { - return null; - } - Map map = (Map) value; - @Nullable String typeName = (String) map.get(PropertyNames.OBJECT_TYPE_NAME); - if (typeName == null) { - return null; - } - @Nullable CloudKnownType knownType = CloudKnownType.forUri(typeName); - if (knownType == null || knownType != type) { - return null; - } - @Nullable Object scalar = map.get(PropertyNames.SCALAR_FIELD_NAME); - if (scalar == null) { - return null; - } - return knownType.parse(scalar, clazz); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/VarInt.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/VarInt.java deleted file mode 100644 index af039112ea..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/VarInt.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Variable-length encoding for integers. - * - *

              Handles, in a common encoding format, signed bytes, shorts, ints, and longs. - * Takes between 1 and 10 bytes. - * Less efficient than BigEndian{Int,Long} coder for negative or large numbers. - * All negative ints are encoded using 5 bytes, longs take 10 bytes. - */ -public class VarInt { - - private static long convertIntToLongNoSignExtend(int v) { - return v & 0xFFFFFFFFL; - } - - /** - * Encodes the given value onto the stream. - */ - public static void encode(int v, OutputStream stream) throws IOException { - encode(convertIntToLongNoSignExtend(v), stream); - } - - /** - * Encodes the given value onto the stream. - */ - public static void encode(long v, OutputStream stream) throws IOException { - do { - // Encode next 7 bits + terminator bit - long bits = v & 0x7F; - v >>>= 7; - byte b = (byte) (bits | ((v != 0) ? 0x80 : 0)); - stream.write(b); - } while (v != 0); - } - - /** - * Decodes an integer value from the given stream. - */ - public static int decodeInt(InputStream stream) throws IOException { - long r = decodeLong(stream); - if (r < 0 || r >= 1L << 32) { - throw new IOException("varint overflow " + r); - } - return (int) r; - } - - /** - * Decodes a long value from the given stream. - */ - public static long decodeLong(InputStream stream) throws IOException { - long result = 0; - int shift = 0; - int b; - do { - // Get 7 bits from next byte - b = stream.read(); - if (b < 0) { - if (shift == 0) { - throw new EOFException(); - } else { - throw new IOException("varint not terminated"); - } - } - long bits = b & 0x7F; - if (shift >= 64 || (shift == 63 && bits > 1)) { - // Out of range - throw new IOException("varint too long"); - } - result |= bits << shift; - shift += 7; - } while ((b & 0x80) != 0); - return result; - } - - /** - * Returns the length of the encoding of the given value (in bytes). - */ - public static int getLength(int v) { - return getLength(convertIntToLongNoSignExtend(v)); - } - - /** - * Returns the length of the encoding of the given value (in bytes). - */ - public static int getLength(long v) { - int result = 0; - do { - result++; - v >>>= 7; - } while (v != 0); - return result; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java deleted file mode 100644 index 06de70fe5f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WatermarkHold.java +++ /dev/null @@ -1,540 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.util.state.MergingStateAccessor; -import com.google.cloud.dataflow.sdk.util.state.ReadableState; -import com.google.cloud.dataflow.sdk.util.state.StateMerging; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; -import com.google.common.annotations.VisibleForTesting; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.io.Serializable; - -import javax.annotation.Nullable; - -/** - * Implements the logic to hold the output watermark for a computation back - * until it has seen all the elements it needs based on the input watermark for the - * computation. - * - *

              The backend ensures the output watermark can never progress beyond the - * input watermark for a computation. GroupAlsoByWindows computations may add a 'hold' - * to the output watermark in order to prevent it progressing beyond a time within a window. - * The hold will be 'cleared' when the associated pane is emitted. - * - *

              This class is only intended for use by {@link ReduceFnRunner}. The two evolve together and - * will likely break any other uses. - * - * @param The kind of {@link BoundedWindow} the hold is for. - */ -class WatermarkHold implements Serializable { - /** - * Return tag for state containing the output watermark hold - * used for elements. - */ - public static - StateTag> watermarkHoldTagForOutputTimeFn( - OutputTimeFn outputTimeFn) { - return StateTags.>makeSystemTagInternal( - StateTags.watermarkStateInternal("hold", outputTimeFn)); - } - - /** - * Tag for state containing end-of-window and garbage collection output watermark holds. - * (We can't piggy-back on the data hold state since the outputTimeFn may be - * {@link OutputTimeFns#outputAtLatestInputTimestamp()}, in which case every pane will - * would take the end-of-window time as its element time.) - */ - @VisibleForTesting - public static final StateTag> EXTRA_HOLD_TAG = - StateTags.makeSystemTagInternal(StateTags.watermarkStateInternal( - "extra", OutputTimeFns.outputAtEarliestInputTimestamp())); - - private final TimerInternals timerInternals; - private final WindowingStrategy windowingStrategy; - private final StateTag> elementHoldTag; - - public WatermarkHold(TimerInternals timerInternals, WindowingStrategy windowingStrategy) { - this.timerInternals = timerInternals; - this.windowingStrategy = windowingStrategy; - this.elementHoldTag = watermarkHoldTagForOutputTimeFn(windowingStrategy.getOutputTimeFn()); - } - - /** - * Add a hold to prevent the output watermark progressing beyond the (possibly adjusted) - * timestamp - * of the element in {@code context}. We allow the actual hold time to be shifted later by - * {@link OutputTimeFn#assignOutputTime}, but no further than the end of the window. The hold - * will - * remain until cleared by {@link #extractAndRelease}. Return the timestamp at which the hold - * was placed, or {@literal null} if no hold was placed. - * - *

              In the following we'll write {@code E} to represent an element's timestamp after passing - * through the window strategy's output time function, {@code IWM} for the local input watermark, - * {@code OWM} for the local output watermark, and {@code GCWM} for the garbage collection - * watermark (which is at {@code IWM - getAllowedLateness}). Time progresses from left to right, - * and we write {@code [ ... ]} to denote a bounded window with implied lower bound. - * - *

              Note that the GCWM will be the same as the IWM if {@code getAllowedLateness} - * is {@code ZERO}. - * - *

              Here are the cases we need to handle. They are conceptually considered in the - * sequence written since if getAllowedLateness is ZERO the GCWM is the same as the IWM. - *

                - *
              1. (Normal) - *
                -   *          |
                -   *      [   | E        ]
                -   *          |
                -   *         IWM
                -   * 
                - * This is, hopefully, the common and happy case. The element is locally on-time and can - * definitely make it to an {@code ON_TIME} pane which we can still set an end-of-window timer - * for. We place an element hold at E, which may contribute to the {@code ON_TIME} pane's - * timestamp (depending on the output time function). Thus the OWM will not proceed past E - * until the next pane fires. - * - *
              2. (Discard - no target window) - *
                -   *                       |                            |
                -   *      [     E        ] |                            |
                -   *                       |                            |
                -   *                     GCWM  <-getAllowedLateness->  IWM
                -   * 
                - * The element is very locally late. The window has been garbage collected, thus there - * is no target pane E could be assigned to. We discard E. - * - *
              3. (Unobservably late) - *
                -   *          |    |
                -   *      [   | E  |     ]
                -   *          |    |
                -   *         OWM  IWM
                -   * 
                - * The element is locally late, however we can still treat this case as for 'Normal' above - * since the IWM has not yet passed the end of the window and the element is ahead of the - * OWM. In effect, we get to 'launder' the locally late element and consider it as locally - * on-time because no downstream computation can observe the difference. - * - *
              4. (Maybe late 1) - *
                -   *          |            |
                -   *      [   | E        ] |
                -   *          |            |
                -   *         OWM          IWM
                -   * 
                - * The end-of-window timer may have already fired for this window, and thus an {@code ON_TIME} - * pane may have already been emitted. However, if timer firings have been delayed then it - * is possible the {@code ON_TIME} pane has not yet been emitted. We can't place an element - * hold since we can't be sure if it will be cleared promptly. Thus this element *may* find - * its way into an {@code ON_TIME} pane, but if so it will *not* contribute to that pane's - * timestamp. We may however set a garbage collection hold if required. - * - *
              5. (Maybe late 2) - *
                -   *               |   |
                -   *      [     E  |   | ]
                -   *               |   |
                -   *              OWM IWM
                -   * 
                - * The end-of-window timer has not yet fired, so this element may still appear in an - * {@code ON_TIME} pane. However the element is too late to contribute to the output - * watermark hold, and thus won't contribute to the pane's timestamp. We can still place an - * end-of-window hold. - * - *
              6. (Maybe late 3) - *
                -   *               |       |
                -   *      [     E  |     ] |
                -   *               |       |
                -   *              OWM     IWM
                -   * 
                - * As for the (Maybe late 2) case, however we don't even know if the end-of-window timer - * has already fired, or it is about to fire. We can place only the garbage collection hold, - * if required. - * - *
              7. (Definitely late) - *
                -   *                       |   |
                -   *      [     E        ] |   |
                -   *                       |   |
                -   *                      OWM IWM
                -   * 
                - * The element is definitely too late to make an {@code ON_TIME} pane. We are too late to - * place an end-of-window hold. We can still place a garbage collection hold if required. - * - *
              - */ - @Nullable - public Instant addHolds(ReduceFn.ProcessValueContext context) { - Instant hold = addElementHold(context); - if (hold == null) { - hold = addEndOfWindowOrGarbageCollectionHolds(context, false/*paneIsEmpty*/); - } - return hold; - } - - /** - * Return {@code timestamp}, possibly shifted forward in time according to the window - * strategy's output time function. - */ - private Instant shift(Instant timestamp, W window) { - Instant shifted = windowingStrategy.getOutputTimeFn().assignOutputTime(timestamp, window); - checkState(!shifted.isBefore(timestamp), - "OutputTimeFn moved element from %s to earlier time %s for window %s", - timestamp, shifted, window); - checkState(timestamp.isAfter(window.maxTimestamp()) || !shifted.isAfter(window.maxTimestamp()), - "OutputTimeFn moved element from %s to %s which is beyond end of " - + "window %s", - timestamp, shifted, window); - - return shifted; - } - - /** - * Attempt to add an 'element hold'. Return the {@link Instant} at which the hold was - * added (ie the element timestamp plus any forward shift requested by the - * {@link WindowingStrategy#getOutputTimeFn}), or {@literal null} if no hold was added. - * The hold is only added if both: - *
                - *
              1. The backend will be able to respect it. In other words the output watermark cannot - * be ahead of the proposed hold time. - *
              2. A timer will be set (by {@link ReduceFnRunner}) to clear the hold by the end of the - * window. In other words the input watermark cannot be ahead of the end of the window. - *
              - * The hold ensures the pane which incorporates the element is will not be considered late by - * any downstream computation when it is eventually emitted. - */ - @Nullable - private Instant addElementHold(ReduceFn.ProcessValueContext context) { - // Give the window function a chance to move the hold timestamp forward to encourage progress. - // (A later hold implies less impediment to the output watermark making progress, which in - // turn encourages end-of-window triggers to fire earlier in following computations.) - Instant elementHold = shift(context.timestamp(), context.window()); - - Instant outputWM = timerInternals.currentOutputWatermarkTime(); - Instant inputWM = timerInternals.currentInputWatermarkTime(); - - String which; - boolean tooLate; - // TODO: These case labels could be tightened. - // See the case analysis in addHolds above for the motivation. - if (outputWM != null && elementHold.isBefore(outputWM)) { - which = "too late to effect output watermark"; - tooLate = true; - } else if (context.window().maxTimestamp().isBefore(inputWM)) { - which = "too late for end-of-window timer"; - tooLate = true; - } else { - which = "on time"; - tooLate = false; - checkState(!elementHold.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), - "Element hold %s is beyond end-of-time", elementHold); - context.state().access(elementHoldTag).add(elementHold); - } - WindowTracing.trace( - "WatermarkHold.addHolds: element hold at {} is {} for " - + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - elementHold, which, context.key(), context.window(), inputWM, - outputWM); - - return tooLate ? null : elementHold; - } - - /** - * Add an end-of-window hold or, if too late for that, a garbage collection hold (if required). - * Return the {@link Instant} at which hold was added, or {@literal null} if no hold was added. - */ - @Nullable - private Instant addEndOfWindowOrGarbageCollectionHolds( - ReduceFn.Context context, boolean paneIsEmpty) { - Instant hold = addEndOfWindowHold(context, paneIsEmpty); - if (hold == null) { - hold = addGarbageCollectionHold(context, paneIsEmpty); - } - return hold; - } - - /** - * Attempt to add an 'end-of-window hold'. Return the {@link Instant} at which the hold was added - * (ie the end of window time), or {@literal null} if no end of window hold is possible and we - * should fallback to a garbage collection hold. - * - *

              We only add the hold if we can be sure a timer will be set (by {@link ReduceFnRunner}) - * to clear it. In other words, the input watermark cannot be ahead of the end of window time. - * - *

              An end-of-window hold is added in two situations: - *

                - *
              1. An incoming element came in behind the output watermark (so we are too late for placing - * the usual element hold), but it may still be possible to include the element in an - * {@link Timing#ON_TIME} pane. We place the end of window hold to ensure that pane will - * not be considered late by any downstream computation. - *
              2. We guarantee an {@link Timing#ON_TIME} pane will be emitted for all windows which saw at - * least one element, even if that {@link Timing#ON_TIME} pane is empty. Thus when elements in - * a pane are processed due to a fired trigger we must set both an end of window timer and an end - * of window hold. Again, the hold ensures the {@link Timing#ON_TIME} pane will not be considered - * late by any downstream computation. - *
              - */ - @Nullable - private Instant addEndOfWindowHold(ReduceFn.Context context, boolean paneIsEmpty) { - Instant outputWM = timerInternals.currentOutputWatermarkTime(); - Instant inputWM = timerInternals.currentInputWatermarkTime(); - Instant eowHold = context.window().maxTimestamp(); - - if (eowHold.isBefore(inputWM)) { - WindowTracing.trace( - "WatermarkHold.addEndOfWindowHold: end-of-window hold at {} is too late for " - + "end-of-window timer for key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - eowHold, context.key(), context.window(), inputWM, outputWM); - return null; - } - - checkState(outputWM == null || !eowHold.isBefore(outputWM), - "End-of-window hold %s cannot be before output watermark %s", - eowHold, outputWM); - checkState(!eowHold.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), - "End-of-window hold %s is beyond end-of-time", eowHold); - // If paneIsEmpty then this hold is just for empty ON_TIME panes, so we want to keep - // the hold away from the combining function in elementHoldTag. - // However if !paneIsEmpty then it could make sense to use the elementHoldTag here. - // Alas, onMerge is forced to add an end of window or garbage collection hold without - // knowing whether an element hold is already in place (stopping to check is too expensive). - // This it would end up adding an element hold at the end of the window which could - // upset the elementHoldTag combining function. - context.state().access(EXTRA_HOLD_TAG).add(eowHold); - WindowTracing.trace( - "WatermarkHold.addEndOfWindowHold: end-of-window hold at {} is on time for " - + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - eowHold, context.key(), context.window(), inputWM, outputWM); - return eowHold; - } - - /** - * Attempt to add a 'garbage collection hold' if it is required. Return the {@link Instant} at - * which the hold was added (ie the end of window time plus allowed lateness), - * or {@literal null} if no hold was added. - * - *

              We only add the hold if it is distinct from what would be added by - * {@link #addEndOfWindowHold}. In other words, {@link WindowingStrategy#getAllowedLateness} - * must be non-zero. - * - *

              A garbage collection hold is added in two situations: - *

                - *
              1. An incoming element came in behind the output watermark, and was too late for placing - * the usual element hold or an end of window hold. Place the garbage collection hold so that - * we can guarantee when the pane is finally triggered its output will not be dropped due to - * excessive lateness by any downstream computation. - *
              2. The {@link WindowingStrategy#getClosingBehavior()} is - * {@link ClosingBehavior#FIRE_ALWAYS}, and thus we guarantee a final pane will be emitted - * for all windows which saw at least one element. Again, the garbage collection hold guarantees - * that any empty final pane can be given a timestamp which will not be considered beyond - * allowed lateness by any downstream computation. - *
              - * - *

              We use {@code paneIsEmpty} to distinguish cases 1 and 2. - */ - @Nullable - private Instant addGarbageCollectionHold( - ReduceFn.Context context, boolean paneIsEmpty) { - Instant outputWM = timerInternals.currentOutputWatermarkTime(); - Instant inputWM = timerInternals.currentInputWatermarkTime(); - Instant eow = context.window().maxTimestamp(); - Instant gcHold = eow.plus(windowingStrategy.getAllowedLateness()); - - if (!windowingStrategy.getAllowedLateness().isLongerThan(Duration.ZERO)) { - WindowTracing.trace( - "WatermarkHold.addGarbageCollectionHold: garbage collection hold at {} is unnecessary " - + "since no allowed lateness for key:{}; window:{}; inputWatermark:{}; " - + "outputWatermark:{}", - gcHold, context.key(), context.window(), inputWM, outputWM); - return null; - } - - if (paneIsEmpty && context.windowingStrategy().getClosingBehavior() - == ClosingBehavior.FIRE_IF_NON_EMPTY) { - WindowTracing.trace( - "WatermarkHold.addGarbageCollectionHold: garbage collection hold at {} is unnecessary " - + "since empty pane and FIRE_IF_NON_EMPTY for key:{}; window:{}; inputWatermark:{}; " - + "outputWatermark:{}", - gcHold, context.key(), context.window(), inputWM, outputWM); - return null; - } - - checkState(!gcHold.isBefore(inputWM), - "Garbage collection hold %s cannot be before input watermark %s", - gcHold, inputWM); - checkState(!gcHold.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE), - "Garbage collection hold %s is beyond end-of-time", gcHold); - // Same EXTRA_HOLD_TAG vs elementHoldTag discussion as in addEndOfWindowHold above. - context.state().access(EXTRA_HOLD_TAG).add(gcHold); - - WindowTracing.trace( - "WatermarkHold.addGarbageCollectionHold: garbage collection hold at {} is on time for " - + "key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - gcHold, context.key(), context.window(), inputWM, outputWM); - return gcHold; - } - - /** - * Prefetch watermark holds in preparation for merging. - */ - public void prefetchOnMerge(MergingStateAccessor state) { - StateMerging.prefetchWatermarks(state, elementHoldTag); - } - - /** - * Updates the watermark hold when windows merge if it is possible the merged value does - * not equal all of the existing holds. For example, if the new window implies a later - * watermark hold, then earlier holds may be released. - */ - public void onMerge(ReduceFn.OnMergeContext context) { - WindowTracing.debug("WatermarkHold.onMerge: for key:{}; window:{}; inputWatermark:{}; " - + "outputWatermark:{}", - context.key(), context.window(), timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - StateMerging.mergeWatermarks(context.state(), elementHoldTag, context.window()); - // If we had a cheap way to determine if we have an element hold then we could - // avoid adding an unnecessary end-of-window or garbage collection hold. - // Simply reading the above merged watermark would impose an additional read for the - // common case that the active window has just one underlying state address window and - // the hold depends on the min of the element timestamps. - // At least one merged window must be non-empty for the merge to have been triggered. - StateMerging.clear(context.state(), EXTRA_HOLD_TAG); - addEndOfWindowOrGarbageCollectionHolds(context, false /*paneIsEmpty*/); - } - - /** - * Result of {@link #extractAndRelease}. - */ - public static class OldAndNewHolds { - public final Instant oldHold; - @Nullable - public final Instant newHold; - - public OldAndNewHolds(Instant oldHold, @Nullable Instant newHold) { - this.oldHold = oldHold; - this.newHold = newHold; - } - } - - public void prefetchExtract(final ReduceFn.Context context) { - context.state().access(elementHoldTag).readLater(); - context.state().access(EXTRA_HOLD_TAG).readLater(); - } - - /** - * Return (a future for) the earliest hold for {@code context}. Clear all the holds after - * reading, but add/restore an end-of-window or garbage collection hold if required. - * - *

              The returned timestamp is the output timestamp according to the {@link OutputTimeFn} - * from the windowing strategy of this {@link WatermarkHold}, combined across all the non-late - * elements in the current pane. If there is no such value the timestamp is the end - * of the window. - */ - public ReadableState extractAndRelease( - final ReduceFn.Context context, final boolean isFinished) { - WindowTracing.debug( - "WatermarkHold.extractAndRelease: for key:{}; window:{}; inputWatermark:{}; " - + "outputWatermark:{}", - context.key(), context.window(), timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - final WatermarkHoldState elementHoldState = context.state().access(elementHoldTag); - final WatermarkHoldState extraHoldState = context.state().access(EXTRA_HOLD_TAG); - return new ReadableState() { - @Override - public ReadableState readLater() { - elementHoldState.readLater(); - extraHoldState.readLater(); - return this; - } - - @Override - public OldAndNewHolds read() { - // Read both the element and extra holds. - Instant elementHold = elementHoldState.read(); - Instant extraHold = extraHoldState.read(); - Instant oldHold; - // Find the minimum, accounting for null. - if (elementHold == null) { - oldHold = extraHold; - } else if (extraHold == null) { - oldHold = elementHold; - } else if (elementHold.isBefore(extraHold)) { - oldHold = elementHold; - } else { - oldHold = extraHold; - } - if (oldHold == null || oldHold.isAfter(context.window().maxTimestamp())) { - // If no hold (eg because all elements came in behind the output watermark), or - // the hold was for garbage collection, take the end of window as the result. - WindowTracing.debug( - "WatermarkHold.extractAndRelease.read: clipping from {} to end of window " - + "for key:{}; window:{}", - oldHold, context.key(), context.window()); - oldHold = context.window().maxTimestamp(); - } - WindowTracing.debug("WatermarkHold.extractAndRelease.read: clearing for key:{}; window:{}", - context.key(), context.window()); - - // Clear the underlying state to allow the output watermark to progress. - elementHoldState.clear(); - extraHoldState.clear(); - - @Nullable Instant newHold = null; - if (!isFinished) { - // Only need to leave behind an end-of-window or garbage collection hold - // if future elements will be processed. - newHold = addEndOfWindowOrGarbageCollectionHolds(context, true /*paneIsEmpty*/); - } - - return new OldAndNewHolds(oldHold, newHold); - } - }; - } - - /** - * Clear any remaining holds. - */ - public void clearHolds(ReduceFn.Context context) { - WindowTracing.debug( - "WatermarkHold.clearHolds: For key:{}; window:{}; inputWatermark:{}; outputWatermark:{}", - context.key(), context.window(), timerInternals.currentInputWatermarkTime(), - timerInternals.currentOutputWatermarkTime()); - context.state().access(elementHoldTag).clear(); - context.state().access(EXTRA_HOLD_TAG).clear(); - } - - /** - * Return the current data hold, or null if none. Does not clear. For debugging only. - */ - @Nullable - public Instant getDataCurrent(ReduceFn.Context context) { - return context.state().access(elementHoldTag).read(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Weighted.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Weighted.java deleted file mode 100644 index c31ad7f861..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/Weighted.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * Interface representing an object that has a weight, in unspecified units. - */ -public interface Weighted { - /** - * Returns the weight of the object. - */ - long getWeight(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedValue.java deleted file mode 100644 index 4a6e84079f..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WeightedValue.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -/** - * A {@code T} with an accompanying weight. Units are unspecified. - * - * @param the underlying type of object - */ -public final class WeightedValue implements Weighted { - - private final T value; - private final long weight; - - private WeightedValue(T value, long weight) { - this.value = value; - this.weight = weight; - } - - public static WeightedValue of(T value, long weight) { - return new WeightedValue<>(value, weight); - } - - public long getWeight() { - return weight; - } - - public T getValue() { - return value; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowTracing.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowTracing.java deleted file mode 100644 index 6ae2f4206c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowTracing.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Logging for window operations. Generally only feasible to enable on hand-picked pipelines. - */ -public final class WindowTracing { - private static final Logger LOG = LoggerFactory.getLogger(WindowTracing.class); - - public static void debug(String format, Object... args) { - LOG.debug(format, args); - } - - @SuppressWarnings("unused") - public static void trace(String format, Object... args) { - LOG.trace(format, args); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java deleted file mode 100644 index 4716e849c0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowedValue.java +++ /dev/null @@ -1,732 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CollectionCoder; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * An immutable triple of value, timestamp, and windows. - * - * @param the type of the value - */ -public abstract class WindowedValue { - - protected final T value; - protected final PaneInfo pane; - - /** - * Returns a {@code WindowedValue} with the given value, timestamp, - * and windows. - */ - public static WindowedValue of( - T value, - Instant timestamp, - Collection windows, - PaneInfo pane) { - checkNotNull(pane); - - if (windows.size() == 0 && BoundedWindow.TIMESTAMP_MIN_VALUE.equals(timestamp)) { - return valueInEmptyWindows(value, pane); - } else if (windows.size() == 1) { - return of(value, timestamp, windows.iterator().next(), pane); - } else { - return new TimestampedValueInMultipleWindows<>(value, timestamp, windows, pane); - } - } - - /** - * Returns a {@code WindowedValue} with the given value, timestamp, and window. - */ - public static WindowedValue of( - T value, - Instant timestamp, - BoundedWindow window, - PaneInfo pane) { - checkNotNull(pane); - - boolean isGlobal = GlobalWindow.INSTANCE.equals(window); - if (isGlobal && BoundedWindow.TIMESTAMP_MIN_VALUE.equals(timestamp)) { - return valueInGlobalWindow(value, pane); - } else if (isGlobal) { - return new TimestampedValueInGlobalWindow<>(value, timestamp, pane); - } else { - return new TimestampedValueInSingleWindow<>(value, timestamp, window, pane); - } - } - - /** - * Returns a {@code WindowedValue} with the given value in the {@link GlobalWindow} using the - * default timestamp and pane. - */ - public static WindowedValue valueInGlobalWindow(T value) { - return new ValueInGlobalWindow<>(value, PaneInfo.NO_FIRING); - } - - /** - * Returns a {@code WindowedValue} with the given value in the {@link GlobalWindow} using the - * default timestamp and the specified pane. - */ - public static WindowedValue valueInGlobalWindow(T value, PaneInfo pane) { - return new ValueInGlobalWindow<>(value, pane); - } - - /** - * Returns a {@code WindowedValue} with the given value and timestamp, - * {@code GlobalWindow} and default pane. - */ - public static WindowedValue timestampedValueInGlobalWindow(T value, Instant timestamp) { - if (BoundedWindow.TIMESTAMP_MIN_VALUE.equals(timestamp)) { - return valueInGlobalWindow(value); - } else { - return new TimestampedValueInGlobalWindow<>(value, timestamp, PaneInfo.NO_FIRING); - } - } - - /** - * Returns a {@code WindowedValue} with the given value in no windows, and the default timestamp - * and pane. - */ - public static WindowedValue valueInEmptyWindows(T value) { - return new ValueInEmptyWindows(value, PaneInfo.NO_FIRING); - } - - /** - * Returns a {@code WindowedValue} with the given value in no windows, and the default timestamp - * and the specified pane. - */ - public static WindowedValue valueInEmptyWindows(T value, PaneInfo pane) { - return new ValueInEmptyWindows(value, pane); - } - - private WindowedValue(T value, PaneInfo pane) { - this.value = value; - this.pane = checkNotNull(pane); - } - - /** - * Returns a new {@code WindowedValue} that is a copy of this one, but with a different value, - * which may have a new type {@code NewT}. - */ - public abstract WindowedValue withValue(NewT value); - - /** - * Returns the value of this {@code WindowedValue}. - */ - public T getValue() { - return value; - } - - /** - * Returns the timestamp of this {@code WindowedValue}. - */ - public abstract Instant getTimestamp(); - - /** - * Returns the windows of this {@code WindowedValue}. - */ - public abstract Collection getWindows(); - - /** - * Returns a collection of {@link WindowedValue WindowedValues} identical to this one, except each - * is in exactly one of the windows that this {@link WindowedValue} is in. - */ - public Iterable> explodeWindows() { - ImmutableList.Builder> windowedValues = ImmutableList.builder(); - for (BoundedWindow w : getWindows()) { - windowedValues.add(of(getValue(), getTimestamp(), w, getPane())); - } - return windowedValues.build(); - } - - /** - * Returns the pane of this {@code WindowedValue} in its window. - */ - public PaneInfo getPane() { - return pane; - } - - @Override - public abstract boolean equals(Object o); - - @Override - public abstract int hashCode(); - - @Override - public abstract String toString(); - - private static final Collection GLOBAL_WINDOWS = - Collections.singletonList(GlobalWindow.INSTANCE); - - /** - * The abstract superclass of WindowedValue representations where - * timestamp == MIN. - */ - private abstract static class MinTimestampWindowedValue - extends WindowedValue { - public MinTimestampWindowedValue(T value, PaneInfo pane) { - super(value, pane); - } - - @Override - public Instant getTimestamp() { - return BoundedWindow.TIMESTAMP_MIN_VALUE; - } - } - - /** - * The representation of a WindowedValue where timestamp == MIN and - * windows == {GlobalWindow}. - */ - private static class ValueInGlobalWindow - extends MinTimestampWindowedValue { - public ValueInGlobalWindow(T value, PaneInfo pane) { - super(value, pane); - } - - @Override - public WindowedValue withValue(NewT value) { - return new ValueInGlobalWindow<>(value, pane); - } - - @Override - public Collection getWindows() { - return GLOBAL_WINDOWS; - } - - @Override - public boolean equals(Object o) { - if (o instanceof ValueInGlobalWindow) { - ValueInGlobalWindow that = (ValueInGlobalWindow) o; - return Objects.equals(that.pane, this.pane) - && Objects.equals(that.value, this.value); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Objects.hash(value, pane); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("value", value) - .add("pane", pane) - .toString(); - } - } - - /** - * The representation of a WindowedValue where timestamp == MIN and - * windows == {}. - */ - private static class ValueInEmptyWindows - extends MinTimestampWindowedValue { - public ValueInEmptyWindows(T value, PaneInfo pane) { - super(value, pane); - } - - @Override - public WindowedValue withValue(NewT value) { - return new ValueInEmptyWindows<>(value, pane); - } - - @Override - public Collection getWindows() { - return Collections.emptyList(); - } - - @Override - public boolean equals(Object o) { - if (o instanceof ValueInEmptyWindows) { - ValueInEmptyWindows that = (ValueInEmptyWindows) o; - return Objects.equals(that.pane, this.pane) - && Objects.equals(that.value, this.value); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Objects.hash(value, pane); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("value", value) - .add("pane", pane) - .toString(); - } - } - - /** - * The abstract superclass of WindowedValue representations where - * timestamp is arbitrary. - */ - private abstract static class TimestampedWindowedValue - extends WindowedValue { - protected final Instant timestamp; - - public TimestampedWindowedValue(T value, - Instant timestamp, - PaneInfo pane) { - super(value, pane); - this.timestamp = checkNotNull(timestamp); - } - - @Override - public Instant getTimestamp() { - return timestamp; - } - } - - /** - * The representation of a WindowedValue where timestamp {@code >} - * MIN and windows == {GlobalWindow}. - */ - private static class TimestampedValueInGlobalWindow - extends TimestampedWindowedValue { - public TimestampedValueInGlobalWindow(T value, - Instant timestamp, - PaneInfo pane) { - super(value, timestamp, pane); - } - - @Override - public WindowedValue withValue(NewT value) { - return new TimestampedValueInGlobalWindow<>(value, timestamp, pane); - } - - @Override - public Collection getWindows() { - return GLOBAL_WINDOWS; - } - - @Override - public boolean equals(Object o) { - if (o instanceof TimestampedValueInGlobalWindow) { - TimestampedValueInGlobalWindow that = - (TimestampedValueInGlobalWindow) o; - return this.timestamp.isEqual(that.timestamp) // don't compare chronology objects - && Objects.equals(that.pane, this.pane) - && Objects.equals(that.value, this.value); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Objects.hash(value, pane, timestamp.getMillis()); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("value", value) - .add("timestamp", timestamp) - .add("pane", pane) - .toString(); - } - } - - /** - * The representation of a WindowedValue where timestamp is arbitrary and - * windows == a single non-Global window. - */ - private static class TimestampedValueInSingleWindow - extends TimestampedWindowedValue { - private final BoundedWindow window; - - public TimestampedValueInSingleWindow(T value, - Instant timestamp, - BoundedWindow window, - PaneInfo pane) { - super(value, timestamp, pane); - this.window = checkNotNull(window); - } - - @Override - public WindowedValue withValue(NewT value) { - return new TimestampedValueInSingleWindow<>(value, timestamp, window, pane); - } - - @Override - public Collection getWindows() { - return Collections.singletonList(window); - } - - @Override - public boolean equals(Object o) { - if (o instanceof TimestampedValueInSingleWindow) { - TimestampedValueInSingleWindow that = - (TimestampedValueInSingleWindow) o; - return Objects.equals(that.value, this.value) - && this.timestamp.isEqual(that.timestamp) // don't compare chronology objects - && Objects.equals(that.pane, this.pane) - && Objects.equals(that.window, this.window); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Objects.hash(value, timestamp.getMillis(), pane, window); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("value", value) - .add("timestamp", timestamp) - .add("window", window) - .add("pane", pane) - .toString(); - } - } - - /** - * The representation of a WindowedValue, excluding the special - * cases captured above. - */ - private static class TimestampedValueInMultipleWindows - extends TimestampedWindowedValue { - private Collection windows; - - public TimestampedValueInMultipleWindows( - T value, - Instant timestamp, - Collection windows, - PaneInfo pane) { - super(value, timestamp, pane); - this.windows = checkNotNull(windows); - } - - @Override - public WindowedValue withValue(NewT value) { - return new TimestampedValueInMultipleWindows<>(value, timestamp, windows, pane); - } - - @Override - public Collection getWindows() { - return windows; - } - - @Override - public boolean equals(Object o) { - if (o instanceof TimestampedValueInMultipleWindows) { - TimestampedValueInMultipleWindows that = - (TimestampedValueInMultipleWindows) o; - if (this.timestamp.isEqual(that.timestamp) // don't compare chronology objects - && Objects.equals(that.value, this.value) - && Objects.equals(that.pane, this.pane)) { - ensureWindowsAreASet(); - that.ensureWindowsAreASet(); - return that.windows.equals(this.windows); - } - } - return false; - } - - @Override - public int hashCode() { - ensureWindowsAreASet(); - return Objects.hash(value, timestamp.getMillis(), pane, windows); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("value", value) - .add("timestamp", timestamp) - .add("windows", windows) - .add("pane", pane) - .toString(); - } - - private void ensureWindowsAreASet() { - if (!(windows instanceof Set)) { - windows = new LinkedHashSet<>(windows); - } - } - } - - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Returns the {@code Coder} to use for a {@code WindowedValue}, - * using the given valueCoder and windowCoder. - */ - public static FullWindowedValueCoder getFullCoder( - Coder valueCoder, - Coder windowCoder) { - return FullWindowedValueCoder.of(valueCoder, windowCoder); - } - - /** - * Returns the {@code ValueOnlyCoder} from the given valueCoder. - */ - public static ValueOnlyWindowedValueCoder getValueOnlyCoder(Coder valueCoder) { - return ValueOnlyWindowedValueCoder.of(valueCoder); - } - - /** - * Abstract class for {@code WindowedValue} coder. - */ - public abstract static class WindowedValueCoder - extends StandardCoder> { - final Coder valueCoder; - - WindowedValueCoder(Coder valueCoder) { - this.valueCoder = checkNotNull(valueCoder); - } - - /** - * Returns the value coder. - */ - public Coder getValueCoder() { - return valueCoder; - } - - /** - * Returns a new {@code WindowedValueCoder} that is a copy of this one, - * but with a different value coder. - */ - public abstract WindowedValueCoder withValueCoder(Coder valueCoder); - } - - /** - * Coder for {@code WindowedValue}. - */ - public static class FullWindowedValueCoder extends WindowedValueCoder { - private final Coder windowCoder; - // Precompute and cache the coder for a list of windows. - private final Coder> windowsCoder; - - public static FullWindowedValueCoder of( - Coder valueCoder, - Coder windowCoder) { - return new FullWindowedValueCoder<>(valueCoder, windowCoder); - } - - @JsonCreator - public static FullWindowedValueCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 2, - "Expecting 2 components, got " + components.size()); - @SuppressWarnings("unchecked") - Coder window = (Coder) components.get(1); - return of(components.get(0), window); - } - - FullWindowedValueCoder(Coder valueCoder, - Coder windowCoder) { - super(valueCoder); - this.windowCoder = checkNotNull(windowCoder); - // It's not possible to statically type-check correct use of the - // windowCoder (we have to ensure externally that we only get - // windows of the class handled by windowCoder), so type - // windowsCoder in a way that makes encode() and decode() work - // right, and cast the window type away here. - @SuppressWarnings({"unchecked", "rawtypes"}) - Coder> collectionCoder = - (Coder) CollectionCoder.of(this.windowCoder); - this.windowsCoder = collectionCoder; - } - - public Coder getWindowCoder() { - return windowCoder; - } - - public Coder> getWindowsCoder() { - return windowsCoder; - } - - @Override - public WindowedValueCoder withValueCoder(Coder valueCoder) { - return new FullWindowedValueCoder<>(valueCoder, windowCoder); - } - - @Override - public void encode(WindowedValue windowedElem, - OutputStream outStream, - Context context) - throws CoderException, IOException { - Context nestedContext = context.nested(); - valueCoder.encode(windowedElem.getValue(), outStream, nestedContext); - InstantCoder.of().encode( - windowedElem.getTimestamp(), outStream, nestedContext); - windowsCoder.encode(windowedElem.getWindows(), outStream, nestedContext); - PaneInfoCoder.INSTANCE.encode(windowedElem.getPane(), outStream, context); - } - - @Override - public WindowedValue decode(InputStream inStream, Context context) - throws CoderException, IOException { - Context nestedContext = context.nested(); - T value = valueCoder.decode(inStream, nestedContext); - Instant timestamp = InstantCoder.of().decode(inStream, nestedContext); - Collection windows = - windowsCoder.decode(inStream, nestedContext); - PaneInfo pane = PaneInfoCoder.INSTANCE.decode(inStream, nestedContext); - return WindowedValue.of(value, timestamp, windows, pane); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "FullWindowedValueCoder requires a deterministic valueCoder", - valueCoder); - verifyDeterministic( - "FullWindowedValueCoder requires a deterministic windowCoder", - windowCoder); - } - - @Override - public void registerByteSizeObserver(WindowedValue value, - ElementByteSizeObserver observer, - Context context) throws Exception { - valueCoder.registerByteSizeObserver(value.getValue(), observer, context); - InstantCoder.of().registerByteSizeObserver(value.getTimestamp(), observer, context); - windowsCoder.registerByteSizeObserver(value.getWindows(), observer, context); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addBoolean(result, PropertyNames.IS_WRAPPER, true); - return result; - } - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public List> getComponents() { - return Arrays.>asList(valueCoder, windowCoder); - } - } - - /** - * Coder for {@code WindowedValue}. - * - *

              A {@code ValueOnlyWindowedValueCoder} only encodes and decodes the value. It drops - * timestamp and windows for encoding, and uses defaults timestamp, and windows for decoding. - */ - public static class ValueOnlyWindowedValueCoder extends WindowedValueCoder { - public static ValueOnlyWindowedValueCoder of( - Coder valueCoder) { - return new ValueOnlyWindowedValueCoder<>(valueCoder); - } - - @JsonCreator - public static ValueOnlyWindowedValueCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return of(components.get(0)); - } - - ValueOnlyWindowedValueCoder(Coder valueCoder) { - super(valueCoder); - } - - @Override - public WindowedValueCoder withValueCoder(Coder valueCoder) { - return new ValueOnlyWindowedValueCoder<>(valueCoder); - } - - @Override - public void encode(WindowedValue windowedElem, OutputStream outStream, Context context) - throws CoderException, IOException { - valueCoder.encode(windowedElem.getValue(), outStream, context); - } - - @Override - public WindowedValue decode(InputStream inStream, Context context) - throws CoderException, IOException { - T value = valueCoder.decode(inStream, context); - return WindowedValue.valueInGlobalWindow(value); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "ValueOnlyWindowedValueCoder requires a deterministic valueCoder", - valueCoder); - } - - @Override - public void registerByteSizeObserver( - WindowedValue value, ElementByteSizeObserver observer, Context context) - throws Exception { - valueCoder.registerByteSizeObserver(value.getValue(), observer, context); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addBoolean(result, PropertyNames.IS_WRAPPER, true); - return result; - } - - @Override - public List> getCoderArguments() { - return Arrays.>asList(valueCoder); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java deleted file mode 100644 index 12fcd532a2..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingInternals.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.Collection; - -/** - * Interface that may be required by some (internal) {@code DoFn}s to implement windowing. It should - * not be necessary for general user code to interact with this at all. - * - *

              This interface should be provided by runner implementors to support windowing on their runner. - * - * @param input type - * @param output type - */ -public interface WindowingInternals { - - /** - * Unsupported state internals. The key type is unknown. It is up to the user to use the - * correct type of key. - */ - StateInternals stateInternals(); - - /** - * Output the value at the specified timestamp in the listed windows. - */ - void outputWindowedValue(OutputT output, Instant timestamp, - Collection windows, PaneInfo pane); - - /** - * Return the timer manager provided by the underlying system, or null if Timers need - * to be emulated. - */ - TimerInternals timerInternals(); - - /** - * Access the windows the element is being processed in without "exploding" it. - */ - Collection windows(); - - /** - * Access the pane of the current window(s). - */ - PaneInfo pane(); - - /** - * Write the given {@link PCollectionView} data to a location accessible by other workers. - */ - void writePCollectionViewData( - TupleTag tag, - Iterable> data, - Coder elemCoder) throws IOException; - - /** - * Return the value of the side input for the window of a main input element. - */ - T sideInput(PCollectionView view, BoundedWindow mainInputWindow); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingStrategy.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingStrategy.java deleted file mode 100644 index c167b8c0cd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/WindowingStrategy.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.common.base.MoreObjects; - -import org.joda.time.Duration; - -import java.io.Serializable; -import java.util.Objects; - -/** - * A {@code WindowingStrategy} describes the windowing behavior for a specific collection of values. - * It has both a {@link WindowFn} describing how elements are assigned to windows and a - * {@link Trigger} that controls when output is produced for each window. - * - * @param type of elements being windowed - * @param {@link BoundedWindow} subclass used to represent the - * windows used by this {@code WindowingStrategy} - */ -public class WindowingStrategy implements Serializable { - - /** - * The accumulation modes that can be used with windowing. - */ - public enum AccumulationMode { - DISCARDING_FIRED_PANES, - ACCUMULATING_FIRED_PANES; - } - - private static final Duration DEFAULT_ALLOWED_LATENESS = Duration.ZERO; - private static final WindowingStrategy DEFAULT = of(new GlobalWindows()); - - private final WindowFn windowFn; - private final OutputTimeFn outputTimeFn; - private final ExecutableTrigger trigger; - private final AccumulationMode mode; - private final Duration allowedLateness; - private final ClosingBehavior closingBehavior; - private final boolean triggerSpecified; - private final boolean modeSpecified; - private final boolean allowedLatenessSpecified; - private final boolean outputTimeFnSpecified; - - private WindowingStrategy( - WindowFn windowFn, - ExecutableTrigger trigger, boolean triggerSpecified, - AccumulationMode mode, boolean modeSpecified, - Duration allowedLateness, boolean allowedLatenessSpecified, - OutputTimeFn outputTimeFn, boolean outputTimeFnSpecified, - ClosingBehavior closingBehavior) { - this.windowFn = windowFn; - this.trigger = trigger; - this.triggerSpecified = triggerSpecified; - this.mode = mode; - this.modeSpecified = modeSpecified; - this.allowedLateness = allowedLateness; - this.allowedLatenessSpecified = allowedLatenessSpecified; - this.closingBehavior = closingBehavior; - this.outputTimeFn = outputTimeFn; - this.outputTimeFnSpecified = outputTimeFnSpecified; - } - - /** - * Return a fully specified, default windowing strategy. - */ - public static WindowingStrategy globalDefault() { - return DEFAULT; - } - - public static WindowingStrategy of( - WindowFn windowFn) { - return new WindowingStrategy<>(windowFn, - ExecutableTrigger.create(DefaultTrigger.of()), false, - AccumulationMode.DISCARDING_FIRED_PANES, false, - DEFAULT_ALLOWED_LATENESS, false, - windowFn.getOutputTimeFn(), false, - ClosingBehavior.FIRE_IF_NON_EMPTY); - } - - public WindowFn getWindowFn() { - return windowFn; - } - - public ExecutableTrigger getTrigger() { - return trigger; - } - - public boolean isTriggerSpecified() { - return triggerSpecified; - } - - public Duration getAllowedLateness() { - return allowedLateness; - } - - public boolean isAllowedLatenessSpecified() { - return allowedLatenessSpecified; - } - - public AccumulationMode getMode() { - return mode; - } - - public boolean isModeSpecified() { - return modeSpecified; - } - - public ClosingBehavior getClosingBehavior() { - return closingBehavior; - } - - public OutputTimeFn getOutputTimeFn() { - return outputTimeFn; - } - - public boolean isOutputTimeFnSpecified() { - return outputTimeFnSpecified; - } - - /** - * Returns a {@link WindowingStrategy} identical to {@code this} but with the trigger set to - * {@code wildcardTrigger}. - */ - public WindowingStrategy withTrigger(Trigger wildcardTrigger) { - @SuppressWarnings("unchecked") - Trigger typedTrigger = (Trigger) wildcardTrigger; - return new WindowingStrategy( - windowFn, - ExecutableTrigger.create(typedTrigger), true, - mode, modeSpecified, - allowedLateness, allowedLatenessSpecified, - outputTimeFn, outputTimeFnSpecified, - closingBehavior); - } - - /** - * Returns a {@link WindowingStrategy} identical to {@code this} but with the accumulation mode - * set to {@code mode}. - */ - public WindowingStrategy withMode(AccumulationMode mode) { - return new WindowingStrategy( - windowFn, - trigger, triggerSpecified, - mode, true, - allowedLateness, allowedLatenessSpecified, - outputTimeFn, outputTimeFnSpecified, - closingBehavior); - } - - /** - * Returns a {@link WindowingStrategy} identical to {@code this} but with the window function - * set to {@code wildcardWindowFn}. - */ - public WindowingStrategy withWindowFn(WindowFn wildcardWindowFn) { - @SuppressWarnings("unchecked") - WindowFn typedWindowFn = (WindowFn) wildcardWindowFn; - - // The onus of type correctness falls on the callee. - @SuppressWarnings("unchecked") - OutputTimeFn newOutputTimeFn = (OutputTimeFn) - (outputTimeFnSpecified ? outputTimeFn : typedWindowFn.getOutputTimeFn()); - - return new WindowingStrategy( - typedWindowFn, - trigger, triggerSpecified, - mode, modeSpecified, - allowedLateness, allowedLatenessSpecified, - newOutputTimeFn, outputTimeFnSpecified, - closingBehavior); - } - - /** - * Returns a {@link WindowingStrategy} identical to {@code this} but with the allowed lateness - * set to {@code allowedLateness}. - */ - public WindowingStrategy withAllowedLateness(Duration allowedLateness) { - return new WindowingStrategy( - windowFn, - trigger, triggerSpecified, - mode, modeSpecified, - allowedLateness, true, - outputTimeFn, outputTimeFnSpecified, - closingBehavior); - } - - public WindowingStrategy withClosingBehavior(ClosingBehavior closingBehavior) { - return new WindowingStrategy( - windowFn, - trigger, triggerSpecified, - mode, modeSpecified, - allowedLateness, allowedLatenessSpecified, - outputTimeFn, outputTimeFnSpecified, - closingBehavior); - } - - @Experimental(Experimental.Kind.OUTPUT_TIME) - public WindowingStrategy withOutputTimeFn(OutputTimeFn outputTimeFn) { - - @SuppressWarnings("unchecked") - OutputTimeFn typedOutputTimeFn = (OutputTimeFn) outputTimeFn; - - return new WindowingStrategy( - windowFn, - trigger, triggerSpecified, - mode, modeSpecified, - allowedLateness, allowedLatenessSpecified, - typedOutputTimeFn, true, - closingBehavior); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("windowFn", windowFn) - .add("allowedLateness", allowedLateness) - .add("trigger", trigger) - .add("accumulationMode", mode) - .add("outputTimeFn", outputTimeFn) - .toString(); - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof WindowingStrategy)) { - return false; - } - WindowingStrategy other = (WindowingStrategy) object; - return - isTriggerSpecified() == other.isTriggerSpecified() - && isAllowedLatenessSpecified() == other.isAllowedLatenessSpecified() - && isModeSpecified() == other.isModeSpecified() - && getMode().equals(other.getMode()) - && getAllowedLateness().equals(other.getAllowedLateness()) - && getClosingBehavior().equals(other.getClosingBehavior()) - && getTrigger().equals(other.getTrigger()) - && getWindowFn().equals(other.getWindowFn()); - } - - @Override - public int hashCode() { - return Objects.hash(triggerSpecified, allowedLatenessSpecified, modeSpecified, - windowFn, trigger, mode, allowedLateness, closingBehavior); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ZipFiles.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ZipFiles.java deleted file mode 100644 index 773b65fb98..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/ZipFiles.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.common.collect.FluentIterable; -import com.google.common.collect.Iterators; -import com.google.common.io.ByteSource; -import com.google.common.io.CharSource; -import com.google.common.io.Closer; -import com.google.common.io.Files; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Iterator; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -/** - * Functions for zipping a directory (including a subdirectory) into a ZIP-file - * or unzipping it again. - */ -public final class ZipFiles { - private ZipFiles() {} - - /** - * Returns a new {@link ByteSource} for reading the contents of the given - * entry in the given zip file. - */ - static ByteSource asByteSource(ZipFile file, ZipEntry entry) { - return new ZipEntryByteSource(file, entry); - } - - /** - * Returns a new {@link CharSource} for reading the contents of the given - * entry in the given zip file as text using the given charset. - */ - static CharSource asCharSource( - ZipFile file, ZipEntry entry, Charset charset) { - return asByteSource(file, entry).asCharSource(charset); - } - - private static final class ZipEntryByteSource extends ByteSource { - - private final ZipFile file; - private final ZipEntry entry; - - ZipEntryByteSource(ZipFile file, ZipEntry entry) { - this.file = checkNotNull(file); - this.entry = checkNotNull(entry); - } - - @Override - public InputStream openStream() throws IOException { - return file.getInputStream(entry); - } - - // TODO: implement size() to try calling entry.getSize()? - - @Override - public String toString() { - return "ZipFiles.asByteSource(" + file + ", " + entry + ")"; - } - } - - /** - * Returns a {@link FluentIterable} of all the entries in the given zip file. - */ - // unmodifiable Iterator can be safely cast - // to Iterator - @SuppressWarnings("unchecked") - static FluentIterable entries(final ZipFile file) { - checkNotNull(file); - return new FluentIterable() { - @Override - public Iterator iterator() { - return (Iterator) Iterators.forEnumeration(file.entries()); - } - }; - } - - /** - * Unzips the zip file specified by the path and creates the directory structure inside - * the target directory. Refuses to unzip files that refer to a parent directory, for security - * reasons. - * - * @param zipFile the source zip-file to unzip - * @param targetDirectory the directory to unzip to. If the zip-file contains - * any subdirectories, they will be created within our target directory. - * @throws IOException the unzipping failed, e.g. because the output was not writable, the {@code - * zipFile} was not readable, or contains an illegal entry (contains "..", pointing outside - * the target directory) - * @throws IllegalArgumentException the target directory is not a valid directory (e.g. does not - * exist, or is a file instead of a directory) - */ - static void unzipFile( - File zipFile, - File targetDirectory) throws IOException { - checkNotNull(zipFile); - checkNotNull(targetDirectory); - checkArgument( - targetDirectory.isDirectory(), - "%s is not a valid directory", - targetDirectory.getAbsolutePath()); - final ZipFile zipFileObj = new ZipFile(zipFile); - try { - for (ZipEntry entry : entries(zipFileObj)) { - checkName(entry.getName()); - File targetFile = new File(targetDirectory, entry.getName()); - if (entry.isDirectory()) { - if (!targetFile.isDirectory() && !targetFile.mkdirs()) { - throw new IOException( - "Failed to create directory: " + targetFile.getAbsolutePath()); - } - } else { - File parentFile = targetFile.getParentFile(); - if (!parentFile.isDirectory()) { - if (!parentFile.mkdirs()) { - throw new IOException( - "Failed to create directory: " - + parentFile.getAbsolutePath()); - } - } - // Write the file to the destination. - asByteSource(zipFileObj, entry).copyTo(Files.asByteSink(targetFile)); - } - } - } finally { - zipFileObj.close(); - } - } - - /** - * Checks that the given entry name is legal for unzipping: if it contains - * ".." as a name element, it could cause the entry to be unzipped outside - * the directory we're unzipping to. - * - * @throws IOException if the name is illegal - */ - private static void checkName(String name) throws IOException { - // First just check whether the entry name string contains "..". - // This should weed out the the vast majority of entries, which will not - // contain "..". - if (name.contains("..")) { - // If the string does contain "..", break it down into its actual name - // elements to ensure it actually contains ".." as a name, not just a - // name like "foo..bar" or even "foo..", which should be fine. - File file = new File(name); - while (file != null) { - if (file.getName().equals("..")) { - throw new IOException("Cannot unzip file containing an entry with " - + "\"..\" in the name: " + name); - } - file = file.getParentFile(); - } - } - } - - /** - * Zips an entire directory specified by the path. - * - * @param sourceDirectory the directory to read from. This directory and all - * subdirectories will be added to the zip-file. The path within the zip - * file is relative to the directory given as parameter, not absolute. - * @param zipFile the zip-file to write to. - * @throws IOException the zipping failed, e.g. because the input was not - * readable. - */ - static void zipDirectory( - File sourceDirectory, - File zipFile) throws IOException { - checkNotNull(sourceDirectory); - checkNotNull(zipFile); - checkArgument( - sourceDirectory.isDirectory(), - "%s is not a valid directory", - sourceDirectory.getAbsolutePath()); - checkArgument( - !zipFile.exists(), - "%s does already exist, files are not being overwritten", - zipFile.getAbsolutePath()); - Closer closer = Closer.create(); - try { - OutputStream outputStream = closer.register(new BufferedOutputStream( - new FileOutputStream(zipFile))); - zipDirectory(sourceDirectory, outputStream); - } catch (Throwable t) { - throw closer.rethrow(t); - } finally { - closer.close(); - } - } - - /** - * Zips an entire directory specified by the path. - * - * @param sourceDirectory the directory to read from. This directory and all - * subdirectories will be added to the zip-file. The path within the zip - * file is relative to the directory given as parameter, not absolute. - * @param outputStream the stream to write the zip-file to. This method does not close - * outputStream. - * @throws IOException the zipping failed, e.g. because the input was not - * readable. - */ - static void zipDirectory( - File sourceDirectory, - OutputStream outputStream) throws IOException { - checkNotNull(sourceDirectory); - checkNotNull(outputStream); - checkArgument( - sourceDirectory.isDirectory(), - "%s is not a valid directory", - sourceDirectory.getAbsolutePath()); - ZipOutputStream zos = new ZipOutputStream(outputStream); - for (File file : sourceDirectory.listFiles()) { - zipDirectoryInternal(file, "", zos); - } - zos.finish(); - } - - /** - * Private helper function for zipping files. This one goes recursively - * through the input directory and all of its subdirectories and adds the - * single zip entries. - * - * @param inputFile the file or directory to be added to the zip file - * @param directoryName the string-representation of the parent directory - * name. Might be an empty name, or a name containing multiple directory - * names separated by "/". The directory name must be a valid name - * according to the file system limitations. The directory name should be - * empty or should end in "/". - * @param zos the zipstream to write to - * @throws IOException the zipping failed, e.g. because the output was not - * writeable. - */ - private static void zipDirectoryInternal( - File inputFile, - String directoryName, - ZipOutputStream zos) throws IOException { - String entryName = directoryName + inputFile.getName(); - if (inputFile.isDirectory()) { - entryName += "/"; - - // We are hitting a sub-directory. Recursively add children to zip in deterministic, - // sorted order. - File[] childFiles = inputFile.listFiles(); - if (childFiles.length > 0) { - Arrays.sort(childFiles); - // loop through the directory content, and zip the files - for (File file : childFiles) { - zipDirectoryInternal(file, entryName, zos); - } - - // Since this directory has children, exit now without creating a zipentry specific to - // this directory. The entry for a non-entry directory is incompatible with certain - // implementations of unzip. - return; - } - } - - // Put the zip-entry for this file or empty directory into the zipoutputstream. - ZipEntry entry = new ZipEntry(entryName); - entry.setTime(inputFile.lastModified()); - zos.putNextEntry(entry); - - // Copy file contents into zipoutput stream. - if (inputFile.isFile()) { - Files.asByteSource(inputFile).copyTo(zos); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java deleted file mode 100644 index 0b73d382b0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Counter.java +++ /dev/null @@ -1,1338 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.AND; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.OR; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.auto.value.AutoValue; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.MoreObjects; -import com.google.common.util.concurrent.AtomicDouble; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Nullable; - -/** - * A Counter enables the aggregation of a stream of values over time. The - * cumulative aggregate value is updated as new values are added, or it can be - * reset to a new value. Multiple kinds of aggregation are supported depending - * on the type of the counter. - * - *

              Counters compare using value equality of their name, kind, and - * cumulative value. Equal counters should have equal toString()s. - * - *

              After all possible mutations have completed, the reader should check - * {@link #isDirty} for every counter, otherwise updates may be lost. - * - *

              A counter may become dirty without a corresponding update to the value. - * This generally will occur when the calls to {@code addValue()}, {@code committing()}, - * and {@code committed()} are interleaved such that the value is updated - * between the calls to committing and the read of the value. - * - * @param the type of values aggregated by this counter - */ -public abstract class Counter { - /** - * Possible kinds of counter aggregation. - */ - public enum AggregationKind { - - /** - * Computes the sum of all added values. - * Applicable to {@link Integer}, {@link Long}, and {@link Double} values. - */ - SUM, - - /** - * Computes the maximum value of all added values. - * Applicable to {@link Integer}, {@link Long}, and {@link Double} values. - */ - MAX, - - /** - * Computes the minimum value of all added values. - * Applicable to {@link Integer}, {@link Long}, and {@link Double} values. - */ - MIN, - - /** - * Computes the arithmetic mean of all added values. Applicable to - * {@link Integer}, {@link Long}, and {@link Double} values. - */ - MEAN, - - /** - * Computes boolean AND over all added values. - * Applicable only to {@link Boolean} values. - */ - AND, - - /** - * Computes boolean OR over all added values. Applicable only to - * {@link Boolean} values. - */ - OR - // TODO: consider adding VECTOR_SUM, HISTOGRAM, KV_SET, PRODUCT, TOP. - } - - /** - * Constructs a new {@link Counter} that aggregates {@link Integer}, values - * according to the desired aggregation kind. The supported aggregation kinds - * are {@link AggregationKind#SUM}, {@link AggregationKind#MIN}, - * {@link AggregationKind#MAX}, and {@link AggregationKind#MEAN}. - * This is a convenience wrapper over a - * {@link Counter} implementation that aggregates {@link Long} values. This is - * useful when the application handles (boxed) {@link Integer} values that - * are not readily convertible to the (boxed) {@link Long} values otherwise - * expected by the {@link Counter} implementation aggregating {@link Long} - * values. - * - * @param name the name of the new counter - * @param kind the new counter's aggregation kind - * @return the newly constructed Counter - * @throws IllegalArgumentException if the aggregation kind is not supported - */ - public static Counter ints(String name, AggregationKind kind) { - return new IntegerCounter(Name.withoutStructure(name), kind); - } - - /** - * Like {@link #ints(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a - * string. - */ - public static Counter ints(Counter.Name name, AggregationKind kind) { - return new IntegerCounter(name, kind); - } - - /** - * Constructs a new {@link Counter} that aggregates {@link Long} values - * according to the desired aggregation kind. The supported aggregation kinds - * are {@link AggregationKind#SUM}, {@link AggregationKind#MIN}, - * {@link AggregationKind#MAX}, and {@link AggregationKind#MEAN}. - * - * @param name the name of the new counter - * @param kind the new counter's aggregation kind - * @return the newly constructed Counter - * @throws IllegalArgumentException if the aggregation kind is not supported - */ - public static Counter longs(String name, AggregationKind kind) { - return new LongCounter(Name.withoutStructure(name), kind); - } - - /** - * Like {@link #longs(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a - * string. - */ - public static Counter longs(Counter.Name name, AggregationKind kind) { - return new LongCounter(name, kind); - } - - /** - * Constructs a new {@link Counter} that aggregates {@link Double} values - * according to the desired aggregation kind. The supported aggregation kinds - * are {@link AggregationKind#SUM}, {@link AggregationKind#MIN}, - * {@link AggregationKind#MAX}, and {@link AggregationKind#MEAN}. - * - * @param name the name of the new counter - * @param kind the new counter's aggregation kind - * @return the newly constructed Counter - * @throws IllegalArgumentException if the aggregation kind is not supported - */ - public static Counter doubles(String name, AggregationKind kind) { - return new DoubleCounter(Name.withoutStructure(name), kind); - } - - /** - * Like {@link #doubles(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a - * string. - */ - public static Counter doubles(Counter.Name name, AggregationKind kind) { - return new DoubleCounter(name, kind); - } - - /** - * Constructs a new {@link Counter} that aggregates {@link Boolean} values - * according to the desired aggregation kind. The only supported aggregation - * kinds are {@link AggregationKind#AND} and {@link AggregationKind#OR}. - * - * @param name the name of the new counter - * @param kind the new counter's aggregation kind - * @return the newly constructed Counter - * @throws IllegalArgumentException if the aggregation kind is not supported - */ - public static Counter booleans(String name, AggregationKind kind) { - return new BooleanCounter(Name.withoutStructure(name), kind); - } - - /** - * Like {@link #booleans(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a - * string. - */ - public static Counter booleans(Counter.Name name, AggregationKind kind) { - return new BooleanCounter(name, kind); - } - - /** - * Constructs a new {@link Counter} that aggregates {@link String} values - * according to the desired aggregation kind. The only supported aggregation - * kind is {@link AggregationKind#MIN} and {@link AggregationKind#MAX}. - * - * @param name the name of the new counter - * @param kind the new counter's aggregation kind - * @return the newly constructed Counter - * @throws IllegalArgumentException if the aggregation kind is not supported - */ - @SuppressWarnings("unused") - private static Counter strings(String name, AggregationKind kind) { - return new StringCounter(Name.withoutStructure(name), kind); - } - - /** - * Like {@link #strings(String, AggregationKind)}, but takes a {@link Counter.Name} instead of a - * string. - */ - @SuppressWarnings("unused") - private static Counter strings(Counter.Name name, AggregationKind kind) { - return new StringCounter(name, kind); - } - - ////////////////////////////////////////////////////////////////////////////// - - /** - * Adds a new value to the aggregation stream. Returns this (to allow method - * chaining). - */ - public abstract Counter addValue(T value); - - /** - * Resets the aggregation stream to this new value. This aggregator must not - * be a MEAN aggregator. Returns this (to allow method chaining). - */ - public abstract Counter resetToValue(T value); - - /** - * Resets the aggregation stream to this new value. Returns this (to allow - * method chaining). The value of elementCount must be non-negative, and this - * aggregator must be a MEAN aggregator. - */ - public abstract Counter resetMeanToValue(long elementCount, T value); - - /** - * Resets the counter's delta value to have no values accumulated and returns - * the value of the delta prior to the reset. - * - * @return the aggregate delta at the time this method is called - */ - public abstract T getAndResetDelta(); - - /** - * Resets the counter's delta value to have no values accumulated and returns - * the value of the delta prior to the reset, for a MEAN counter. - * - * @return the mean delta t the time this method is called - */ - public abstract CounterMean getAndResetMeanDelta(); - - /** - * Returns the counter's name. - */ - public String getName() { - return this.name.counterName(); - } - - /** Returns a Name object which uniquely identifies this counter. */ - public Name getUniqueName() { - return this.name; - } - - /** - * Returns the counter's aggregation kind. - */ - public AggregationKind getKind() { - return kind; - } - - /** - * Returns the counter's type. - */ - public Class getType() { - return new TypeDescriptor(getClass()) {}.getRawType(); - } - - /** - * Returns the aggregated value, or the sum for MEAN aggregation, either - * total or, if delta, since the last update extraction or resetDelta. - */ - public abstract T getAggregate(); - - /** - * The mean value of a {@code Counter}, represented as an aggregate value and - * a count. - * - * @param the type of the aggregate - */ - public interface CounterMean { - /** - * Gets the aggregate value of this {@code CounterMean}. - */ - T getAggregate(); - - /** - * Gets the count of this {@code CounterMean}. - */ - long getCount(); - } - - /** - * Returns the mean in the form of a CounterMean, or null if this is not a - * MEAN counter. - */ - @Nullable - public abstract CounterMean getMean(); - - /** - * Represents whether counters' values have been committed to the backend. - * - *

              Runners can use this information to optimize counters updates. - * For example, if counters are committed, runners may choose to skip the updates. - * - *

              Counters' state transition table: - * {@code - * Action\Current State COMMITTED DIRTY COMMITTING - * addValue() DIRTY DIRTY DIRTY - * committing() None COMMITTING None - * committed() None None COMMITTED - * } - */ - @VisibleForTesting - enum CommitState { - /** - * There are no local updates that haven't been committed to the backend. - */ - COMMITTED, - /** - * There are local updates that haven't been committed to the backend. - */ - DIRTY, - /** - * Local updates are committing to the backend, but are still pending. - */ - COMMITTING, - } - - /** - * Returns if the counter contains non-committed aggregate. - */ - public boolean isDirty() { - return commitState.get() != CommitState.COMMITTED; - } - - /** - * Changes the counter from {@code CommitState.DIRTY} to {@code CommitState.COMMITTING}. - * - * @return true if successful. False return indicates that the commit state - * was not in {@code CommitState.DIRTY}. - */ - public boolean committing() { - return commitState.compareAndSet(CommitState.DIRTY, CommitState.COMMITTING); - } - - /** - * Changes the counter from {@code CommitState.COMMITTING} to {@code CommitState.COMMITTED}. - * - *

              False return indicates that the counter was updated while the committing is pending. - * That counter update might or might not has been committed. The {@code commitState} has to - * stay in {@code CommitState.DIRTY}. - * - * @return true if successful. - */ - public boolean committed() { - return commitState.compareAndSet(CommitState.COMMITTING, CommitState.COMMITTED); - } - - /** - * Sets the counter to {@code CommitState.DIRTY}. - * - *

              Must be called at the end of {@link #addValue}, {@link #resetToValue}, - * {@link #resetMeanToValue}, and {@link #merge}. - */ - protected void setDirty() { - commitState.set(CommitState.DIRTY); - } - - /** - * Returns a string representation of the Counter. Useful for debugging logs. - * Example return value: "ElementCount:SUM(15)". - */ - @Override - public String toString() { - String valueString; - switch (kind) { - case SUM: - case MAX: - case MIN: - case AND: - case OR: - valueString = getAggregate().toString(); - break; - case MEAN: - valueString = getMean().toString(); - break; - default: - throw illegalArgumentException(); - } - return MoreObjects.toStringHelper(this) - .add("Name", name) - .add("Kind", getKind()) - .add("Value", valueString) - .toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } else if (o instanceof Counter) { - Counter that = (Counter) o; - if (this.name.equals(that.name) && this.kind == that.kind - && this.getClass().equals(that.getClass())) { - if (kind == MEAN) { - CounterMean thisMean = this.getMean(); - CounterMean thatMean = that.getMean(); - return thisMean == thatMean - || (Objects.equals(thisMean.getAggregate(), thatMean.getAggregate()) - && thisMean.getCount() == thatMean.getCount()); - } else { - return Objects.equals(this.getAggregate(), that.getAggregate()); - } - } - } - return false; - } - - @Override - public int hashCode() { - if (kind == MEAN) { - CounterMean mean = getMean(); - return Objects.hash(getClass(), name, kind, mean.getAggregate(), mean.getCount()); - } else { - return Objects.hash(getClass(), name, kind, getAggregate()); - } - } - - /** - * Returns whether this Counter is compatible with that Counter. If - * so, they can be merged into a single Counter. - */ - public boolean isCompatibleWith(Counter that) { - return this.name.equals(that.name) - && this.kind == that.kind - && this.getClass().equals(that.getClass()); - } - - /** - * Merges this counter with the provided counter, returning this counter with the combined value - * of both counters. This may reset the delta of this counter. - * - * @throws IllegalArgumentException if the provided Counter is not compatible with this Counter - */ - public abstract Counter merge(Counter that); - - ////////////////////////////////////////////////////////////////////////////// - - /** The kind of aggregation function to apply to this counter. */ - protected final AggregationKind kind; - - /** The commit state of this counter. **/ - protected final AtomicReference commitState; - - /** - * {@link Counter.Name} is the full unique name of the counter. Counters must have - * at least a name, and optionally may be associated with a {@code systemName}, an - * {@code originalName}, or both. All of these names together define a counter uniquely. - */ - @AutoValue - public abstract static class Name { - /** Create a {@link Counter.Name} with the {@code originalName} from a {@link NameContext}. */ - public static Name withOriginalName(String name, NameContext context) { - return new AutoValue_Counter_Name(name, null, - checkNotNull(context.originalName(), "Expected original name in context %s", context)); - } - - /** Create a {@link Counter.Name} with the {@code systemName} from a {@link NameContext}. */ - public static Name withSystemName(String name, NameContext context) { - return new AutoValue_Counter_Name(name, - checkNotNull(context.systemName(), "Expected system name in context %s", context), - null); - } - - /** Create a {@link Counter.Name} without a {@link NameContext}. */ - public static Name withoutStructure(String name) { - return new AutoValue_Counter_Name(name, null, null); - } - - /** Returns the non-unique {@code counterName}. */ - public abstract String counterName(); - - /** Returns an optional {@code contextSystemName}. */ - @Nullable public abstract String contextSystemName(); - - /** Returns an optional {@code contextOriginalName}. */ - @Nullable public abstract String contextOriginalName(); - } - - /** The name of this counter. */ - protected final Name name; - - protected Counter(String name, AggregationKind kind) { - this.name = Name.withoutStructure(name); - this.kind = kind; - this.commitState = new AtomicReference<>(CommitState.COMMITTED); - } - - protected Counter(Name name, AggregationKind kind) { - this.name = checkNotNull(name); - this.kind = kind; - this.commitState = new AtomicReference<>(CommitState.COMMITTED); - } - - ////////////////////////////////////////////////////////////////////////////// - - /** - * Implements a {@link Counter} for {@link Long} values. - */ - private static class LongCounter extends Counter { - private final AtomicLong aggregate; - private final AtomicLong deltaAggregate; - private final AtomicReference mean; - private final AtomicReference deltaMean; - - /** Initializes a new {@link Counter} for {@link Long} values. */ - private LongCounter(Counter.Name name, AggregationKind kind) { - super(name, kind); - switch (kind) { - case MEAN: - mean = new AtomicReference<>(); - deltaMean = new AtomicReference<>(); - getAndResetMeanDelta(); - mean.set(deltaMean.get()); - aggregate = deltaAggregate = null; - break; - case SUM: - case MAX: - case MIN: - aggregate = new AtomicLong(); - deltaAggregate = new AtomicLong(); - getAndResetDelta(); - aggregate.set(deltaAggregate.get()); - mean = deltaMean = null; - break; - default: - throw illegalArgumentException(); - } - } - - @Override - public LongCounter addValue(Long value) { - try { - switch (kind) { - case SUM: - aggregate.addAndGet(value); - deltaAggregate.addAndGet(value); - break; - case MEAN: - addToMeanAndSet(value, mean); - addToMeanAndSet(value, deltaMean); - break; - case MAX: - maxAndSet(value, aggregate); - maxAndSet(value, deltaAggregate); - break; - case MIN: - minAndSet(value, aggregate); - minAndSet(value, deltaAggregate); - break; - default: - throw illegalArgumentException(); - } - return this; - } finally { - setDirty(); - } - } - - private void minAndSet(Long value, AtomicLong target) { - long current; - long update; - do { - current = target.get(); - update = Math.min(value, current); - } while (update < current && !target.compareAndSet(current, update)); - } - - private void maxAndSet(Long value, AtomicLong target) { - long current; - long update; - do { - current = target.get(); - update = Math.max(value, current); - } while (update > current && !target.compareAndSet(current, update)); - } - - private void addToMeanAndSet(Long value, AtomicReference target) { - LongCounterMean current; - LongCounterMean update; - do { - current = target.get(); - update = new LongCounterMean(current.getAggregate() + value, current.getCount() + 1L); - } while (!target.compareAndSet(current, update)); - } - - @Override - public Long getAggregate() { - if (kind != MEAN) { - return aggregate.get(); - } else { - return getMean().getAggregate(); - } - } - - @Override - public Long getAndResetDelta() { - switch (kind) { - case SUM: - return deltaAggregate.getAndSet(0L); - case MAX: - return deltaAggregate.getAndSet(Long.MIN_VALUE); - case MIN: - return deltaAggregate.getAndSet(Long.MAX_VALUE); - default: - throw illegalArgumentException(); - } - } - - @Override - public Counter resetToValue(Long value) { - try { - if (kind == MEAN) { - throw illegalArgumentException(); - } - aggregate.set(value); - deltaAggregate.set(value); - return this; - } finally { - setDirty(); - } - } - - @Override - public Counter resetMeanToValue(long elementCount, Long value) { - try { - if (kind != MEAN) { - throw illegalArgumentException(); - } - if (elementCount < 0) { - throw new IllegalArgumentException("elementCount must be non-negative"); - } - LongCounterMean counterMean = new LongCounterMean(value, elementCount); - mean.set(counterMean); - deltaMean.set(counterMean); - return this; - } finally { - setDirty(); - } - } - - @Override - public CounterMean getAndResetMeanDelta() { - if (kind != MEAN) { - throw illegalArgumentException(); - } - return deltaMean.getAndSet(new LongCounterMean(0L, 0L)); - } - - @Override - @Nullable - public CounterMean getMean() { - if (kind != MEAN) { - throw illegalArgumentException(); - } - return mean.get(); - } - - @Override - public Counter merge(Counter that) { - try { - checkArgument( - this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - switch (kind) { - case SUM: - case MIN: - case MAX: - return addValue(that.getAggregate()); - case MEAN: - CounterMean thisCounterMean = this.getMean(); - CounterMean thatCounterMean = that.getMean(); - return resetMeanToValue( - thisCounterMean.getCount() + thatCounterMean.getCount(), - thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); - default: - throw illegalArgumentException(); - } - } finally { - setDirty(); - } - } - - private static class LongCounterMean implements CounterMean { - private final long aggregate; - private final long count; - - public LongCounterMean(long aggregate, long count) { - this.aggregate = aggregate; - this.count = count; - } - - @Override - public Long getAggregate() { - return aggregate; - } - - @Override - public long getCount() { - return count; - } - - @Override - public String toString() { - return aggregate + "/" + count; - } - } - } - - /** - * Implements a {@link Counter} for {@link Double} values. - */ - private static class DoubleCounter extends Counter { - AtomicDouble aggregate; - AtomicDouble deltaAggregate; - AtomicReference mean; - AtomicReference deltaMean; - - /** Initializes a new {@link Counter} for {@link Double} values. */ - private DoubleCounter(Counter.Name name, AggregationKind kind) { - super(name, kind); - switch (kind) { - case MEAN: - aggregate = deltaAggregate = null; - mean = new AtomicReference<>(); - deltaMean = new AtomicReference<>(); - getAndResetMeanDelta(); - mean.set(deltaMean.get()); - break; - case SUM: - case MAX: - case MIN: - mean = deltaMean = null; - aggregate = new AtomicDouble(); - deltaAggregate = new AtomicDouble(); - getAndResetDelta(); - aggregate.set(deltaAggregate.get()); - break; - default: - throw illegalArgumentException(); - } - } - - @Override - public DoubleCounter addValue(Double value) { - try { - switch (kind) { - case SUM: - aggregate.addAndGet(value); - deltaAggregate.addAndGet(value); - break; - case MEAN: - addToMeanAndSet(value, mean); - addToMeanAndSet(value, deltaMean); - break; - case MAX: - maxAndSet(value, aggregate); - maxAndSet(value, deltaAggregate); - break; - case MIN: - minAndSet(value, aggregate); - minAndSet(value, deltaAggregate); - break; - default: - throw illegalArgumentException(); - } - return this; - } finally { - setDirty(); - } - } - - private void addToMeanAndSet(Double value, AtomicReference target) { - DoubleCounterMean current; - DoubleCounterMean update; - do { - current = target.get(); - update = new DoubleCounterMean(current.getAggregate() + value, current.getCount() + 1); - } while (!target.compareAndSet(current, update)); - } - - private void maxAndSet(Double value, AtomicDouble target) { - double current; - double update; - do { - current = target.get(); - update = Math.max(current, value); - } while (update > current && !target.compareAndSet(current, update)); - } - - private void minAndSet(Double value, AtomicDouble target) { - double current; - double update; - do { - current = target.get(); - update = Math.min(current, value); - } while (update < current && !target.compareAndSet(current, update)); - } - - @Override - public Double getAndResetDelta() { - switch (kind) { - case SUM: - return deltaAggregate.getAndSet(0.0); - case MAX: - return deltaAggregate.getAndSet(Double.NEGATIVE_INFINITY); - case MIN: - return deltaAggregate.getAndSet(Double.POSITIVE_INFINITY); - default: - throw illegalArgumentException(); - } - } - - @Override - public Counter resetToValue(Double value) { - try { - if (kind == MEAN) { - throw illegalArgumentException(); - } - aggregate.set(value); - deltaAggregate.set(value); - return this; - } finally { - setDirty(); - } - } - - @Override - public Counter resetMeanToValue(long elementCount, Double value) { - try { - if (kind != MEAN) { - throw illegalArgumentException(); - } - if (elementCount < 0) { - throw new IllegalArgumentException("elementCount must be non-negative"); - } - DoubleCounterMean counterMean = new DoubleCounterMean(value, elementCount); - mean.set(counterMean); - deltaMean.set(counterMean); - return this; - } finally { - setDirty(); - } - } - - @Override - public CounterMean getAndResetMeanDelta() { - if (kind != MEAN) { - throw illegalArgumentException(); - } - return deltaMean.getAndSet(new DoubleCounterMean(0.0, 0L)); - } - - @Override - public Double getAggregate() { - if (kind != MEAN) { - return aggregate.get(); - } else { - return getMean().getAggregate(); - } - } - - @Override - @Nullable - public CounterMean getMean() { - if (kind != MEAN) { - throw illegalArgumentException(); - } - return mean.get(); - } - - @Override - public Counter merge(Counter that) { - try { - checkArgument( - this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - switch (kind) { - case SUM: - case MIN: - case MAX: - return addValue(that.getAggregate()); - case MEAN: - CounterMean thisCounterMean = this.getMean(); - CounterMean thatCounterMean = that.getMean(); - return resetMeanToValue( - thisCounterMean.getCount() + thatCounterMean.getCount(), - thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); - default: - throw illegalArgumentException(); - } - } finally { - setDirty(); - } - } - - private static class DoubleCounterMean implements CounterMean { - private final double aggregate; - private final long count; - - public DoubleCounterMean(double aggregate, long count) { - this.aggregate = aggregate; - this.count = count; - } - - @Override - public Double getAggregate() { - return aggregate; - } - - @Override - public long getCount() { - return count; - } - - @Override - public String toString() { - return aggregate + "/" + count; - } - } - } - - /** - * Implements a {@link Counter} for {@link Boolean} values. - */ - private static class BooleanCounter extends Counter { - private final AtomicBoolean aggregate; - private final AtomicBoolean deltaAggregate; - - /** Initializes a new {@link Counter} for {@link Boolean} values. */ - private BooleanCounter(Counter.Name name, AggregationKind kind) { - super(name, kind); - aggregate = new AtomicBoolean(); - deltaAggregate = new AtomicBoolean(); - getAndResetDelta(); - aggregate.set(deltaAggregate.get()); - } - - @Override - public BooleanCounter addValue(Boolean value) { - try { - if (kind.equals(AND) && !value) { - aggregate.set(value); - deltaAggregate.set(value); - } else if (kind.equals(OR) && value) { - aggregate.set(value); - deltaAggregate.set(value); - } - return this; - } finally { - setDirty(); - } - } - - @Override - public Boolean getAndResetDelta() { - switch (kind) { - case AND: - return deltaAggregate.getAndSet(true); - case OR: - return deltaAggregate.getAndSet(false); - default: - throw illegalArgumentException(); - } - } - - @Override - public Counter resetToValue(Boolean value) { - try { - aggregate.set(value); - deltaAggregate.set(value); - return this; - } finally { - setDirty(); - } - } - - @Override - public Counter resetMeanToValue(long elementCount, Boolean value) { - throw illegalArgumentException(); - } - - @Override - public CounterMean getAndResetMeanDelta() { - throw illegalArgumentException(); - } - - @Override - public Boolean getAggregate() { - return aggregate.get(); - } - - @Override - @Nullable - public CounterMean getMean() { - throw illegalArgumentException(); - } - - @Override - public Counter merge(Counter that) { - try { - checkArgument( - this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - return addValue(that.getAggregate()); - } finally { - setDirty(); - } - } - } - - /** - * Implements a {@link Counter} for {@link String} values. - */ - private static class StringCounter extends Counter { - /** Initializes a new {@link Counter} for {@link String} values. */ - private StringCounter(Counter.Name name, AggregationKind kind) { - super(name, kind); - // TODO: Support MIN, MAX of Strings. - throw illegalArgumentException(); - } - - @Override - public StringCounter addValue(String value) { - switch (kind) { - default: - throw illegalArgumentException(); - } - } - - @Override - public Counter resetToValue(String value) { - switch (kind) { - default: - throw illegalArgumentException(); - } - } - - @Override - public Counter resetMeanToValue(long elementCount, String value) { - switch (kind) { - default: - throw illegalArgumentException(); - } - } - - @Override - public String getAndResetDelta() { - switch (kind) { - default: - throw illegalArgumentException(); - } - } - - @Override - public CounterMean getAndResetMeanDelta() { - switch (kind) { - default: - throw illegalArgumentException(); - } - } - - @Override - public String getAggregate() { - switch (kind) { - default: - throw illegalArgumentException(); - } - } - - @Override - @Nullable - public CounterMean getMean() { - switch (kind) { - default: - throw illegalArgumentException(); - } - } - - @Override - public Counter merge(Counter that) { - checkArgument( - this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - switch (kind) { - default: - throw illegalArgumentException(); - } - } - } - - /** - * Implements a {@link Counter} for {@link Integer} values. - */ - private static class IntegerCounter extends Counter { - private final AtomicInteger aggregate; - private final AtomicInteger deltaAggregate; - private final AtomicReference mean; - private final AtomicReference deltaMean; - - /** Initializes a new {@link Counter} for {@link Integer} values. */ - private IntegerCounter(Counter.Name name, AggregationKind kind) { - super(name, kind); - switch (kind) { - case MEAN: - aggregate = deltaAggregate = null; - mean = new AtomicReference<>(); - deltaMean = new AtomicReference<>(); - getAndResetMeanDelta(); - mean.set(deltaMean.get()); - break; - case SUM: - case MAX: - case MIN: - mean = deltaMean = null; - aggregate = new AtomicInteger(); - deltaAggregate = new AtomicInteger(); - getAndResetDelta(); - aggregate.set(deltaAggregate.get()); - break; - default: - throw illegalArgumentException(); - } - } - - @Override - public IntegerCounter addValue(Integer value) { - try { - switch (kind) { - case SUM: - aggregate.getAndAdd(value); - deltaAggregate.getAndAdd(value); - break; - case MEAN: - addToMeanAndSet(value, mean); - addToMeanAndSet(value, deltaMean); - break; - case MAX: - maxAndSet(value, aggregate); - maxAndSet(value, deltaAggregate); - break; - case MIN: - minAndSet(value, aggregate); - minAndSet(value, deltaAggregate); - break; - default: - throw illegalArgumentException(); - } - return this; - } finally { - setDirty(); - } - } - - private void addToMeanAndSet(int value, AtomicReference target) { - IntegerCounterMean current; - IntegerCounterMean update; - do { - current = target.get(); - update = new IntegerCounterMean(current.getAggregate() + value, current.getCount() + 1); - } while (!target.compareAndSet(current, update)); - } - - private void maxAndSet(int value, AtomicInteger target) { - int current; - int update; - do { - current = target.get(); - update = Math.max(value, current); - } while (update > current && !target.compareAndSet(current, update)); - } - - private void minAndSet(int value, AtomicInteger target) { - int current; - int update; - do { - current = target.get(); - update = Math.min(value, current); - } while (update < current && !target.compareAndSet(current, update)); - } - - @Override - public Integer getAndResetDelta() { - switch (kind) { - case SUM: - return deltaAggregate.getAndSet(0); - case MAX: - return deltaAggregate.getAndSet(Integer.MIN_VALUE); - case MIN: - return deltaAggregate.getAndSet(Integer.MAX_VALUE); - default: - throw illegalArgumentException(); - } - } - - @Override - public Counter resetToValue(Integer value) { - try { - if (kind == MEAN) { - throw illegalArgumentException(); - } - aggregate.set(value); - deltaAggregate.set(value); - return this; - } finally { - setDirty(); - } - } - - @Override - public Counter resetMeanToValue(long elementCount, Integer value) { - try { - if (kind != MEAN) { - throw illegalArgumentException(); - } - if (elementCount < 0) { - throw new IllegalArgumentException("elementCount must be non-negative"); - } - IntegerCounterMean counterMean = new IntegerCounterMean(value, elementCount); - mean.set(counterMean); - deltaMean.set(counterMean); - return this; - } finally { - setDirty(); - } - } - - @Override - public CounterMean getAndResetMeanDelta() { - if (kind != MEAN) { - throw illegalArgumentException(); - } - return deltaMean.getAndSet(new IntegerCounterMean(0, 0L)); - } - - @Override - public Integer getAggregate() { - if (kind != MEAN) { - return aggregate.get(); - } else { - return getMean().getAggregate(); - } - } - - @Override - @Nullable - public CounterMean getMean() { - if (kind != MEAN) { - throw illegalArgumentException(); - } - return mean.get(); - } - - @Override - public Counter merge(Counter that) { - try { - checkArgument( - this.isCompatibleWith(that), "Counters %s and %s are incompatible", this, that); - switch (kind) { - case SUM: - case MIN: - case MAX: - return addValue(that.getAggregate()); - case MEAN: - CounterMean thisCounterMean = this.getMean(); - CounterMean thatCounterMean = that.getMean(); - return resetMeanToValue( - thisCounterMean.getCount() + thatCounterMean.getCount(), - thisCounterMean.getAggregate() + thatCounterMean.getAggregate()); - default: - throw illegalArgumentException(); - } - } finally { - setDirty(); - } - } - - private static class IntegerCounterMean implements CounterMean { - private final int aggregate; - private final long count; - - public IntegerCounterMean(int aggregate, long count) { - this.aggregate = aggregate; - this.count = count; - } - - @Override - public Integer getAggregate() { - return aggregate; - } - - @Override - public long getCount() { - return count; - } - - @Override - public String toString() { - return aggregate + "/" + count; - } - } - } - - ////////////////////////////////////////////////////////////////////////////// - - /** - * Constructs an {@link IllegalArgumentException} explaining that this - * {@link Counter}'s aggregation kind is not supported by its value type. - */ - protected IllegalArgumentException illegalArgumentException() { - return new IllegalArgumentException("Cannot compute " + kind - + " aggregation over " + getType().getSimpleName() + " values."); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterProvider.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterProvider.java deleted file mode 100644 index ba53f80d20..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterProvider.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -/** - * A counter provider can provide {@link Counter} instances. - * - * @param the input type of the counter. - */ -public interface CounterProvider { - Counter getCounter(String name); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java deleted file mode 100644 index 0e89693319..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/CounterSet.java +++ /dev/null @@ -1,214 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.AbstractSet; -import java.util.Iterator; -import java.util.concurrent.ConcurrentHashMap; - -/** - * A CounterSet maintains a set of {@link Counter}s. - * - *

              Thread-safe. - */ -public class CounterSet extends AbstractSet> { - - /** Registered counters. */ - private final ConcurrentHashMap> counters = new ConcurrentHashMap<>(); - - private final AddCounterMutator addCounterMutator = new AddCounterMutator(); - - /** - * Constructs a CounterSet containing the given Counters. - */ - public CounterSet(Counter... counters) { - for (Counter counter : counters) { - addNewCounter(counter); - } - } - - /** - * Returns an object that supports adding additional counters into - * this CounterSet. - */ - public AddCounterMutator getAddCounterMutator() { - return addCounterMutator; - } - - /** - * Returns an object that supports adding additional counters into - * this {@link CounterSet} with the supplied {@link NameContext}. - */ - public AddCounterMutator getAddCounterMutator(NameContext context) { - AddCounterMutator addCounterWithContextMutator = new AddCounterMutator(context); - return addCounterWithContextMutator; - } - - /** - * Adds a new counter, throwing an exception if a counter of the - * same name already exists. - */ - public void addNewCounter(Counter counter) { - if (!addCounter(counter)) { - throw new IllegalArgumentException( - "Counter " + counter + " duplicates an existing counter in " + this); - } - } - - /** - * Adds the given Counter to this CounterSet. - * - *

              If a counter with the same name already exists, it will be - * reused, as long as it is compatible. - * - * @return the Counter that was reused, or added - * @throws IllegalArgumentException if a counter with the same - * name but an incompatible kind had already been added - */ - public Counter addOrReuseCounter(Counter counter) { - Counter oldCounter = counters.putIfAbsent(counter.getUniqueName(), counter); - if (oldCounter != null) { - checkArgument(counter.isCompatibleWith(oldCounter), - "Counter %s duplicates incompatible counter %s in %s", counter, oldCounter, this); - // Return the counter to reuse. - @SuppressWarnings("unchecked") - Counter compatibleCounter = (Counter) oldCounter; - return compatibleCounter; - } - return counter; - } - - /** - * Adds a counter. Returns {@code true} if the counter was added to the set - * and false if the given counter was {@code null} or it already existed in - * the set. - * - * @param counter to register - */ - public boolean addCounter(Counter counter) { - return add(counter); - } - - /** - * Returns the {@link Counter} with the given {@link Counter.Name} in this {@link CounterSet}; - * returns null if no such {@link Counter} exists. - */ - public synchronized Counter getExistingCounter(Counter.Name name) { - return counters.get(name); - } - - /** - * Returns the Counter with the given name in this CounterSet; - * returns null if no such Counter exists. - */ - public Counter getExistingCounter(String name) { - Counter.Name unstructuredName = Counter.Name.withoutStructure(name); - return counters.get(unstructuredName); - } - - @Override - public Iterator> iterator() { - return counters.values().iterator(); - } - - @Override - public int size() { - return counters.size(); - } - - @Override - public boolean add(Counter e) { - if (null == e) { - return false; - } - return counters.putIfAbsent(e.getUniqueName(), e) == null; - } - - public void merge(CounterSet that) { - for (Counter theirCounter : that) { - Counter myCounter = counters.get(theirCounter.getUniqueName()); - if (myCounter != null) { - mergeCounters(myCounter, theirCounter); - } else { - addCounter(theirCounter); - } - } - } - - private void mergeCounters(Counter mine, Counter theirCounter) { - checkArgument( - mine.isCompatibleWith(theirCounter), - "Can't merge CounterSets containing incompatible counters with the same name: " - + "%s (existing) and %s (merged)", - mine, - theirCounter); - @SuppressWarnings("unchecked") - Counter theirs = (Counter) theirCounter; - mine.merge(theirs); - } - - /** - * A nested class that supports adding additional counters into the - * enclosing CounterSet. This is useful as a mutator, hiding other - * public methods of the CounterSet. - */ - public class AddCounterMutator { - - /** - * The {@link NameContext} to add counters into, optional. - */ - private final NameContext context; - - /** - * Constructor which takes a {@link NameContext}. - */ - public AddCounterMutator(NameContext context) { - this.context = checkNotNull(context); - } - - /** - * Default Constructor has no context associated. - */ - public AddCounterMutator() { - this.context = null; - } - - /** - * Adds the given Counter into the enclosing CounterSet. - * - *

              If a counter with the same name already exists, it will be - * reused, as long as it has the same type. - * - * @return the Counter that was reused, or added - * @throws IllegalArgumentException if a counter with the same - * name but an incompatible kind had already been added - */ - public Counter addCounter(Counter counter) { - return addOrReuseCounter(counter); - } - - /** - * Returns the {@link NameContext} associated with this mutator, if any. - */ - public NameContext getNameContext() { - return this.context; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservable.java deleted file mode 100644 index 92571de6bf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservable.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -/** - * An interface for things that allow observing the size in bytes of - * encoded values of type {@code T}. - * - * @param the type of the values being observed - */ -public interface ElementByteSizeObservable { - /** - * Returns whether {@link #registerByteSizeObserver} is cheap enough - * to call for every element, that is, if this - * {@code ElementByteSizeObservable} can calculate the byte size of - * the element to be coded in roughly constant time (or lazily). - */ - boolean isRegisterByteSizeObserverCheap(T value); - - /** - * Notifies the {@code ElementByteSizeObserver} about the byte size - * of the encoded value using this {@code ElementByteSizeObservable}. - */ - void registerByteSizeObserver(T value, ElementByteSizeObserver observer) - throws Exception; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterable.java deleted file mode 100644 index 591d2be28a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterable.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import java.util.ArrayList; -import java.util.List; -import java.util.Observer; - -/** - * An abstract class used for iterables that notify observers about size in - * bytes of their elements, as they are being iterated over. - * - * @param the type of elements returned by this iterable - * @param type type of iterator returned by this iterable - */ -public abstract class ElementByteSizeObservableIterable< - V, InputT extends ElementByteSizeObservableIterator> - implements Iterable { - private List observers = new ArrayList<>(); - - /** - * Derived classes override this method to return an iterator for this - * iterable. - */ - protected abstract InputT createIterator(); - - /** - * Sets the observer, which will observe the iterator returned in - * the next call to iterator() method. Future calls to iterator() - * won't be observed, unless an observer is set again. - */ - public void addObserver(Observer observer) { - observers.add(observer); - } - - /** - * Returns a new iterator for this iterable. If an observer was set in - * a previous call to setObserver(), it will observe the iterator returned. - */ - @Override - public InputT iterator() { - InputT iterator = createIterator(); - for (Observer observer : observers) { - iterator.addObserver(observer); - } - observers.clear(); - return iterator; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterator.java deleted file mode 100644 index c094900301..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObservableIterator.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import java.util.Iterator; -import java.util.Observable; - -/** - * An abstract class used for iterators that notify observers about size in - * bytes of their elements, as they are being iterated over. The subclasses - * need to implement the standard Iterator interface and call method - * notifyValueReturned() for each element read and/or iterated over. - * - * @param value type - */ -public abstract class ElementByteSizeObservableIterator - extends Observable implements Iterator { - protected final void notifyValueReturned(long byteSize) { - setChanged(); - notifyObservers(byteSize); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObserver.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObserver.java deleted file mode 100644 index 6c764d99bb..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ElementByteSizeObserver.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import java.util.Observable; -import java.util.Observer; - -/** - * An observer that gets notified when additional bytes are read - * and/or used. It adds all bytes into a local counter. When the - * observer gets advanced via the next() call, it adds the total byte - * count to the specified counter, and prepares for the next element. - */ -public class ElementByteSizeObserver implements Observer { - private final Counter counter; - private boolean isLazy = false; - private long totalSize = 0; - private double scalingFactor = 1.0; - - public ElementByteSizeObserver(Counter counter) { - this.counter = counter; - } - - /** - * Sets byte counting for the current element as lazy. That is, the - * observer will get notified of the element's byte count only as - * element's pieces are being processed or iterated over. - */ - public void setLazy() { - isLazy = true; - } - - /** - * Returns whether byte counting for the current element is lazy, that is, - * whether the observer gets notified of the element's byte count only as - * element's pieces are being processed or iterated over. - */ - public boolean getIsLazy() { - return isLazy; - } - - /** - * Updates the observer with a context specified, but without an instance of - * the Observable. - */ - public void update(Object obj) { - update(null, obj); - } - - /** - * Sets a multiplier to use on observed sizes. - */ - public void setScalingFactor(double scalingFactor) { - this.scalingFactor = scalingFactor; - } - - @Override - public void update(Observable obs, Object obj) { - if (obj instanceof Long) { - totalSize += scalingFactor * (Long) obj; - } else if (obj instanceof Integer) { - totalSize += scalingFactor * (Integer) obj; - } else { - throw new AssertionError("unexpected parameter object"); - } - } - - /** - * Advances the observer to the next element. Adds the current total byte - * size to the counter, and prepares the observer for the next element. - */ - public void advance() { - counter.addValue(totalSize); - - totalSize = 0; - isLazy = false; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java deleted file mode 100644 index 2e35c2f93c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/NameContext.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import com.google.auto.value.AutoValue; - -/** - * The {@link NameContext} represents the context in which a counter is reported. Specifically, - * it may be associated with a specific original step name and associated system name. - */ -@AutoValue -public abstract class NameContext { - /** Create a {@link NameContext} with both an {@code originalName} and {@code systemName}. */ - public static NameContext create(String originalName, String systemName) { - return new AutoValue_NameContext(originalName, systemName); - } - - /** - * Returns the {@code systemName} associated with this {@link NameContext}. - * This name represents the system determined name for this instruction. */ - public abstract String systemName(); - - /** - * Returns the {@code originalName} associated with this {@link NameContext}. - * This name is the name of the step in the original workflow graph which - * caused this instruction to be generated. - */ - public abstract String originalName(); -} - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/PeekingReiterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/PeekingReiterator.java deleted file mode 100644 index 0948747918..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/PeekingReiterator.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import java.util.NoSuchElementException; - -/** - * A {@link Reiterator} that supports one-element lookahead during iteration. - * - * @param the type of elements returned by this iterator - */ -public final class PeekingReiterator implements Reiterator { - private T nextElement; - private boolean nextElementComputed; - private final Reiterator iterator; - - public PeekingReiterator(Reiterator iterator) { - this.iterator = checkNotNull(iterator); - } - - PeekingReiterator(PeekingReiterator it) { - this.iterator = checkNotNull(checkNotNull(it).iterator.copy()); - this.nextElement = it.nextElement; - this.nextElementComputed = it.nextElementComputed; - } - - @Override - public boolean hasNext() { - computeNext(); - return nextElementComputed; - } - - @Override - public T next() { - T result = peek(); - nextElementComputed = false; - return result; - } - - /** - * {@inheritDoc} - * - *

              If {@link #peek} is called, {@code remove} is disallowed until - * {@link #next} has been subsequently called. - */ - @Override - public void remove() { - checkState(!nextElementComputed, - "After peek(), remove() is disallowed until next() is called"); - iterator.remove(); - } - - @Override - public PeekingReiterator copy() { - return new PeekingReiterator<>(this); - } - - /** - * Returns the element that would be returned by {@link #next}, without - * actually consuming the element. - * @throws NoSuchElementException if there is no next element - */ - public T peek() { - computeNext(); - if (!nextElementComputed) { - throw new NoSuchElementException(); - } - return nextElement; - } - - private void computeNext() { - if (nextElementComputed) { - return; - } - if (!iterator.hasNext()) { - return; - } - nextElement = iterator.next(); - nextElementComputed = true; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpers.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpers.java deleted file mode 100644 index 65f57ed975..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpers.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import static java.util.Arrays.asList; - -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Queues; - -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Queue; - -import javax.annotation.Nullable; - -/** - * Utilities for working with with {@link Class Classes} and {@link Method Methods}. - */ -public class ReflectHelpers { - - private static final Joiner COMMA_SEPARATOR = Joiner.on(", "); - - /** A {@link Function} that turns a method into a simple method signature. */ - public static final Function METHOD_FORMATTER = new Function() { - @Override - public String apply(Method input) { - String parameterTypes = FluentIterable.from(asList(input.getParameterTypes())) - .transform(CLASS_SIMPLE_NAME) - .join(COMMA_SEPARATOR); - return String.format("%s(%s)", - input.getName(), - parameterTypes); - } - }; - - /** A {@link Function} that turns a method into the declaring class + method signature. */ - public static final Function CLASS_AND_METHOD_FORMATTER = - new Function() { - @Override - public String apply(Method input) { - return String.format("%s#%s", - CLASS_NAME.apply(input.getDeclaringClass()), - METHOD_FORMATTER.apply(input)); - } - }; - - /** A {@link Function} with returns the classes name. */ - public static final Function, String> CLASS_NAME = - new Function, String>() { - @Override - public String apply(Class input) { - return input.getName(); - } - }; - - /** A {@link Function} with returns the classes name. */ - public static final Function, String> CLASS_SIMPLE_NAME = - new Function, String>() { - @Override - public String apply(Class input) { - return input.getSimpleName(); - } - }; - - /** A {@link Function} that formats types. */ - public static final Function TYPE_SIMPLE_DESCRIPTION = - new Function() { - @Override - @Nullable - public String apply(@Nullable Type input) { - StringBuilder builder = new StringBuilder(); - format(builder, input); - return builder.toString(); - } - - private void format(StringBuilder builder, Type t) { - if (t instanceof Class) { - formatClass(builder, (Class) t); - } else if (t instanceof TypeVariable) { - formatTypeVariable(builder, (TypeVariable) t); - } else if (t instanceof WildcardType) { - formatWildcardType(builder, (WildcardType) t); - } else if (t instanceof ParameterizedType) { - formatParameterizedType(builder, (ParameterizedType) t); - } else if (t instanceof GenericArrayType) { - formatGenericArrayType(builder, (GenericArrayType) t); - } else { - builder.append(t.toString()); - } - } - - private void formatClass(StringBuilder builder, Class clazz) { - builder.append(clazz.getSimpleName()); - } - - private void formatTypeVariable(StringBuilder builder, TypeVariable t) { - builder.append(t.getName()); - } - - private void formatWildcardType(StringBuilder builder, WildcardType t) { - builder.append("?"); - for (Type lowerBound : t.getLowerBounds()) { - builder.append(" super "); - format(builder, lowerBound); - } - for (Type upperBound : t.getUpperBounds()) { - if (!Object.class.equals(upperBound)) { - builder.append(" extends "); - format(builder, upperBound); - } - } - } - - private void formatParameterizedType(StringBuilder builder, ParameterizedType t) { - format(builder, t.getRawType()); - builder.append('<'); - COMMA_SEPARATOR.appendTo(builder, - FluentIterable.from(asList(t.getActualTypeArguments())) - .transform(TYPE_SIMPLE_DESCRIPTION)); - builder.append('>'); - } - - private void formatGenericArrayType(StringBuilder builder, GenericArrayType t) { - format(builder, t.getGenericComponentType()); - builder.append("[]"); - } - }; - - /** - * Returns all interfaces of the given clazz. - * @param clazz - * @return - */ - public static FluentIterable> getClosureOfInterfaces(Class clazz) { - checkNotNull(clazz); - Queue> interfacesToProcess = Queues.newArrayDeque(); - Collections.addAll(interfacesToProcess, clazz.getInterfaces()); - - LinkedHashSet> interfaces = new LinkedHashSet<>(); - while (!interfacesToProcess.isEmpty()) { - Class current = interfacesToProcess.remove(); - if (interfaces.add(current)) { - Collections.addAll(interfacesToProcess, current.getInterfaces()); - } - } - return FluentIterable.from(interfaces); - } - - /** - * Returns all the methods visible from the provided interfaces. - * - * @param interfaces The interfaces to use when searching for all their methods. - * @return An iterable of {@link Method}s which interfaces expose. - */ - public static Iterable getClosureOfMethodsOnInterfaces( - Iterable> interfaces) { - return FluentIterable.from(interfaces).transformAndConcat( - new Function, Iterable>() { - @Override - public Iterable apply(Class input) { - return getClosureOfMethodsOnInterface(input); - } - }); - } - - /** - * Returns all the methods visible from {@code iface}. - * - * @param iface The interface to use when searching for all its methods. - * @return An iterable of {@link Method}s which {@code iface} exposes. - */ - public static Iterable getClosureOfMethodsOnInterface(Class iface) { - checkNotNull(iface); - checkArgument(iface.isInterface()); - ImmutableSet.Builder builder = ImmutableSet.builder(); - Queue> interfacesToProcess = Queues.newArrayDeque(); - interfacesToProcess.add(iface); - while (!interfacesToProcess.isEmpty()) { - Class current = interfacesToProcess.remove(); - builder.add(current.getMethods()); - interfacesToProcess.addAll(Arrays.asList(current.getInterfaces())); - } - return builder.build(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterable.java deleted file mode 100644 index ecdca6d62d..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterable.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -/** - * An {@link Iterable} that returns {@link Reiterator} iterators. - * - * @param the type of elements returned by the iterator - */ -public interface Reiterable extends Iterable { - @Override - Reiterator iterator(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterator.java deleted file mode 100644 index 93dfddc03b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/Reiterator.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import java.util.Iterator; - -/** - * An {@link Iterator} with the ability to copy its iteration state. - * - * @param the type of elements returned by this iterator - */ -public interface Reiterator extends Iterator { - /** - * Returns a copy of the current {@link Reiterator}. The copy's iteration - * state is logically independent of the current iterator; each may be - * advanced without affecting the other. - * - *

              The returned {@code Reiterator} is not guaranteed to return - * referentially identical iteration results as the original - * {@link Reiterator}, although {@link Object#equals} will typically return - * true for the corresponding elements of each if the original source is - * logically immutable. - */ - Reiterator copy(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/package-info.java deleted file mode 100644 index 7fb16c58fd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/package-info.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** Defines utilities shared by multiple PipelineRunner implementations. **/ -package com.google.cloud.dataflow.sdk.util.common; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java deleted file mode 100644 index d6483fc19a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/StateSampler.java +++ /dev/null @@ -1,427 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common.worker; - -import com.google.api.client.util.NanoClock; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import java.io.Closeable; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; - -import javax.annotation.concurrent.ThreadSafe; - -/** - * A StateSampler object may be used to obtain an approximate - * breakdown of the time spent by an execution context in various - * states, as a fraction of the total time. The sampling is taken at - * regular intervals, with adjustment for scheduling delay. - */ -@ThreadSafe -public class StateSampler implements Closeable { - - /** - * An interface for scheduling state sampling. - */ - public interface SampleScheduler { - Closeable scheduleSampling(StateSampler sampler); - } - - /** - * An implementation of {@link SampleScheduler} using a scheduled executor service and two - * callbacks per sample. The sampling uses "stratified sampling" -- in every bucket of - * samplingPeriodMs we choose a random point to sample. This prevents pathological behavior in - * case some states happen to occur at a similar period. - * - *

              The current implementation uses a fixed-rate timer with a period samplingPeriodMs as a - * trampoline to a one-shot random timer which fires with a random delay within - * samplingPeriodMs. - */ - @VisibleForTesting - static final class DefaultScheduler implements SampleScheduler { - private static final int NUM_EXECUTOR_THREADS = 16; - private static final ScheduledExecutorService EXECUTOR_SERVICE = - Executors.newScheduledThreadPool(NUM_EXECUTOR_THREADS, - new ThreadFactoryBuilder().setDaemon(true).build()); - - private final long samplingPeriodMs; - - @VisibleForTesting - DefaultScheduler(long samplingPeriodMs) { - this.samplingPeriodMs = samplingPeriodMs; - } - - @Override - public Closeable scheduleSampling(final StateSampler sampler) { - return new Closeable() { - private ScheduledFuture invocationFuture = null; - private ScheduledFuture invocationTriggerFuture = EXECUTOR_SERVICE.scheduleAtFixedRate( - new Runnable() { - @Override - public void run() { - long delay = ThreadLocalRandom.current().nextInt((int) samplingPeriodMs); - synchronized (sampler) { - if (invocationFuture != null) { - invocationFuture.cancel(false); - } - invocationFuture = EXECUTOR_SERVICE.schedule( - new Runnable() { - @Override - public void run() { - sampler.run(); - } - }, - delay, - TimeUnit.MILLISECONDS); - } - } - }, - 0, - samplingPeriodMs, - TimeUnit.MILLISECONDS); - - @Override - public void close() throws IOException { - synchronized (sampler) { - if (invocationTriggerFuture != null) { - invocationTriggerFuture.cancel(false); - invocationTriggerFuture = null; - } - if (invocationFuture != null) { - invocationFuture.cancel(false); - invocationFuture = null; - } - } - } - }; - } - } - - public static final SampleScheduler NOOP_SCHEDULER = new SampleScheduler() { - @Override - public Closeable scheduleSampling(StateSampler sampler) { - return new Closeable() { - @Override - public void close() throws IOException { - } - }; - } - }; - - /** Different kinds of states. */ - public enum StateKind { - /** IO, user code, etc. */ - USER, - /** Reading/writing from/to shuffle service, etc. */ - FRAMEWORK - } - - public static final long DEFAULT_SAMPLING_PERIOD_MS = 200; - - private final String prefix; - private final CounterSet.AddCounterMutator counterSetMutator; - - /** Array of counters indexed by their state. */ - private ArrayList> countersByState = new ArrayList<>(); - - /** Map of state name to state. */ - private Map statesByName = new HashMap<>(); - - /** Map of state id to kind. */ - private Map kindsByState = new HashMap<>(); - - /** The current state. */ - private volatile int currentState; - - /** Special value of {@code currentState} that means we do not sample. */ - public static final int DO_NOT_SAMPLE = -1; - - /** - * A counter that increments with each state transition. May be used - * to detect a context being stuck in a state for some amount of - * time. - */ - private volatile long stateTransitionCount; - - /** - * The timestamp (in nanoseconds) corresponding to the last time the - * state was sampled (and recorded). - */ - private long stateTimestampNs = 0; - - private List callbacks = new ArrayList<>(); - - private final Closeable sampleSchedule; - private final NanoClock nanoClock; - - /** - * Constructs a new {@link StateSampler} that can be used to obtain - * an approximate breakdown of the time spent by an execution - * context in various states, as a fraction of the total time. - * - * @param prefix the prefix of the counter names for the states - * @param counterSetMutator the {@link CounterSet.AddCounterMutator} - * used to create a counter for each distinct state - * @param scheduler the sample scheduler to use - */ - public StateSampler(String prefix, - CounterSet.AddCounterMutator counterSetMutator, - SampleScheduler scheduler, - NanoClock nanoClock) { - this.prefix = prefix; - this.counterSetMutator = counterSetMutator; - this.nanoClock = nanoClock; - this.currentState = DO_NOT_SAMPLE; - this.stateTimestampNs = nanoClock.nanoTime(); - - // Schedule sampling. It should be assumed that as soon as this call - // is made, sampling may happen. Therefore, it should be the final - // step of initialization. - this.sampleSchedule = scheduler.scheduleSampling(this); - } - - /** - * Constructs a new {@link StateSampler} that can be used to obtain - * an approximate breakdown of the time spent by an execution - * context in various states, as a fraction of the total time. - * - * @param prefix the prefix of the counter names for the states - * @param counterSetMutator the {@link CounterSet.AddCounterMutator} - * used to create a counter for each distinct state - * @param samplingPeriodMs the sampling period in milliseconds - */ - public StateSampler(String prefix, - CounterSet.AddCounterMutator counterSetMutator, - final long samplingPeriodMs) { - this(prefix, counterSetMutator, new DefaultScheduler(samplingPeriodMs), NanoClock.SYSTEM); - } - - /** - * Constructs a new {@link StateSampler} that can be used to obtain - * an approximate breakdown of the time spent by an execution - * context in various states, as a fraction of the total time. - * - * @param prefix the prefix of the counter names for the states - * @param counterSetMutator the {@link CounterSet.AddCounterMutator} - * used to create a counter for each distinct state - */ - public StateSampler(String prefix, - CounterSet.AddCounterMutator counterSetMutator) { - this(prefix, counterSetMutator, DEFAULT_SAMPLING_PERIOD_MS); - } - - public synchronized void run() { - long startTimestampNs = nanoClock.nanoTime(); - int state = currentState; - if (state != DO_NOT_SAMPLE) { - StateKind kind = null; - long elapsedMs = TimeUnit.NANOSECONDS.toMillis(startTimestampNs - stateTimestampNs); - kind = kindsByState.get(state); - countersByState.get(state).addValue(elapsedMs); - // Invoke all callbacks. - for (SamplingCallback c : callbacks) { - c.run(state, kind, elapsedMs); - } - } - stateTimestampNs = startTimestampNs; - } - - @Override - public synchronized void close() throws IOException { - currentState = DO_NOT_SAMPLE; - sampleSchedule.close(); - } - - /** - * Returns the state associated with a name; creating a new state if - * necessary. Using states instead of state names during state - * transitions is done for efficiency. - * - * @name the name for the state - * @kind kind of the state, see {#code StateKind} - * @return the state associated with the state name - */ - public int stateForName(String name, StateKind kind) { - if (name.isEmpty()) { - return DO_NOT_SAMPLE; - } - - synchronized (this) { - Integer state = statesByName.get(name); - if (state == null) { - String counterName = prefix + name + "-msecs"; - Counter counter = counterSetMutator.addCounter( - Counter.longs(counterName, Counter.AggregationKind.SUM)); - state = countersByState.size(); - statesByName.put(name, state); - countersByState.add(counter); - kindsByState.put(state, kind); - } - StateKind originalKind = kindsByState.get(state); - if (originalKind != kind) { - throw new IllegalArgumentException( - "for state named " + name - + ", requested kind " + kind + " different from the original kind " + originalKind); - } - return state; - } - } - - /** - * An internal class for representing StateSampler information - * typically used for debugging. - */ - public static class StateSamplerInfo { - public final String state; - public final Long transitionCount; - public final Long stateDurationMillis; - - public StateSamplerInfo(String state, Long transitionCount, - Long stateDurationMillis) { - this.state = state; - this.transitionCount = transitionCount; - this.stateDurationMillis = stateDurationMillis; - } - } - - /** - * Returns information about the current state of this state sampler - * into a {@link StateSamplerInfo} object, or null if sampling is - * not turned on. - * - * @return information about this state sampler or null if sampling is off - */ - public synchronized StateSamplerInfo getInfo() { - return currentState == DO_NOT_SAMPLE ? null - : new StateSamplerInfo(countersByState.get(currentState).getName(), - stateTransitionCount, null); - } - - /** - * Returns the current state of this state sampler. - */ - public int getCurrentState() { - return currentState; - } - - /** - * Sets the current thread state. - * - * @param state the new state to transition to - * @return the previous state - */ - public int setState(int state) { - // Updates to stateTransitionCount are always done by the same - // thread, making the non-atomic volatile update below safe. The - // count is updated first to avoid incorrectly attributing - // stuckness occuring in an old state to the new state. - long previousStateTransitionCount = this.stateTransitionCount; - this.stateTransitionCount = previousStateTransitionCount + 1; - int previousState = currentState; - currentState = state; - return previousState; - } - - /** - * Sets the current thread state. - * - * @param name the name of the new state to transition to - * @param kind kind of the new state - * @return the previous state - */ - public int setState(String name, StateKind kind) { - return setState(stateForName(name, kind)); - } - - /** - * Returns an {@link Closeable} {@link ScopedState} that will perform a - * state transition to the given state, and will automatically reset - * the state to the prior state upon closing. - * - * @param state the new state to transition to - * @return a {@link ScopedState} that automatically resets the state - * to the prior state - */ - public ScopedState scopedState(int state) { - return new ScopedState(this, setState(state)); - } - - /** - * Add a callback to the sampler. - * The callbacks will be executed sequentially upon {@link StateSampler#run}. - */ - public synchronized void addSamplingCallback(SamplingCallback callback) { - callbacks.add(callback); - } - - /** Get the counter prefix associated with this sampler. */ - public String getPrefix() { - return prefix; - } - - /** - * A nested class that is used to account for states and state - * transitions based on lexical scopes. - * - *

              Thread-safe. - */ - public class ScopedState implements Closeable { - private final StateSampler sampler; - private final int previousState; - private boolean closed = false; - - private ScopedState(StateSampler sampler, int previousState) { - this.sampler = sampler; - this.previousState = previousState; - } - - @Override - public void close() { - if (!closed) { - closed = true; - sampler.setState(previousState); - } - } - } - - /** - * Callbacks which supposed to be called sequentially upon {@link StateSampler#run}. - * They should be registered via {@link #addSamplingCallback}. - */ - public interface SamplingCallback { - /** - * The entrance method of the callback, it is called in {@link StateSampler#run}, - * once per sample. This method should be thread safe. - * - * @param state The state of the StateSampler at the time of sample. - * @param kind The kind associated with the state, see {@link StateKind}. - * @param elapsedMs Milliseconds since last sample. - */ - void run(int state, StateKind kind, long elapsedMs); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/package-info.java deleted file mode 100644 index c3da9ed8b8..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/common/worker/package-info.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** Defines utilities used to implement the harness that runs user code. **/ -package com.google.cloud.dataflow.sdk.util.common.worker; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPath.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPath.java deleted file mode 100644 index df95b1eb56..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPath.java +++ /dev/null @@ -1,619 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.gcsfs; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.api.services.storage.model.StorageObject; -import com.google.common.base.Strings; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.FileSystem; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; -import java.util.Iterator; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -/** - * Implements the Java NIO {@link Path} API for Google Cloud Storage paths. - * - *

              GcsPath uses a slash ('/') as a directory separator. Below is - * a summary of how slashes are treated: - *

                - *
              • A GCS bucket may not contain a slash. An object may contain zero or - * more slashes. - *
              • A trailing slash always indicates a directory, which is compliant - * with POSIX.1-2008. - *
              • Slashes separate components of a path. Empty components are allowed, - * these are represented as repeated slashes. An empty component always - * refers to a directory, and always ends in a slash. - *
              • {@link #getParent()}} always returns a path ending in a slash, as the - * parent of a GcsPath is always a directory. - *
              • Use {@link #resolve(String)} to append elements to a GcsPath -- this - * applies the rules consistently and is highly recommended over any - * custom string concatenation. - *
              - * - *

              GcsPath treats all GCS objects and buckets as belonging to the same - * filesystem, so the root of a GcsPath is the GcsPath bucket="", object="". - * - *

              Relative paths are not associated with any bucket. This matches common - * treatment of Path in which relative paths can be constructed from one - * filesystem and appended to another filesystem. - * - * @see Java Tutorials: Path Operations - */ -public class GcsPath implements Path { - - public static final String SCHEME = "gs"; - - /** - * Creates a GcsPath from a URI. - * - *

              The URI must be in the form {@code gs://[bucket]/[path]}, and may not - * contain a port, user info, a query, or a fragment. - */ - public static GcsPath fromUri(URI uri) { - checkArgument(uri.getScheme().equalsIgnoreCase(SCHEME), - "URI: %s is not a GCS URI", uri); - checkArgument(uri.getPort() == -1, - "GCS URI may not specify port: %s (%i)", uri, uri.getPort()); - checkArgument( - Strings.isNullOrEmpty(uri.getUserInfo()), - "GCS URI may not specify userInfo: %s (%s)", uri, uri.getUserInfo()); - checkArgument( - Strings.isNullOrEmpty(uri.getQuery()), - "GCS URI may not specify query: %s (%s)", uri, uri.getQuery()); - checkArgument( - Strings.isNullOrEmpty(uri.getFragment()), - "GCS URI may not specify fragment: %s (%s)", uri, uri.getFragment()); - - return fromUri(uri.toString()); - } - - /** - * Pattern that is used to parse a GCS URL. - * - *

              This is used to separate the components. Verification is handled - * separately. - */ - public static final Pattern GCS_URI = - Pattern.compile("(?[^:]+)://(?[^/]+)(/(?.*))?"); - - /** - * Creates a GcsPath from a URI in string form. - * - *

              This does not use URI parsing, which means it may accept patterns that - * the URI parser would not accept. - */ - public static GcsPath fromUri(String uri) { - Matcher m = GCS_URI.matcher(uri); - checkArgument(m.matches(), "Invalid GCS URI: %s", uri); - - checkArgument(m.group("SCHEME").equalsIgnoreCase(SCHEME), - "URI: %s is not a GCS URI", uri); - return new GcsPath(null, m.group("BUCKET"), m.group("OBJECT")); - } - - /** - * Pattern that is used to parse a GCS resource name. - */ - private static final Pattern GCS_RESOURCE_NAME = - Pattern.compile("storage.googleapis.com/(?[^/]+)(/(?.*))?"); - - /** - * Creates a GcsPath from a OnePlatform resource name in string form. - */ - public static GcsPath fromResourceName(String name) { - Matcher m = GCS_RESOURCE_NAME.matcher(name); - checkArgument(m.matches(), "Invalid GCS resource name: %s", name); - - return new GcsPath(null, m.group("BUCKET"), m.group("OBJECT")); - } - - /** - * Creates a GcsPath from a {@linkplain StorageObject}. - */ - public static GcsPath fromObject(StorageObject object) { - return new GcsPath(null, object.getBucket(), object.getName()); - } - - /** - * Creates a GcsPath from bucket and object components. - * - *

              A GcsPath without a bucket name is treated as a relative path, which - * is a path component with no linkage to the root element. This is similar - * to a Unix path that does not begin with the root marker (a slash). - * GCS has different naming constraints and APIs for working with buckets and - * objects, so these two concepts are kept separate to avoid accidental - * attempts to treat objects as buckets, or vice versa, as much as possible. - * - *

              A GcsPath without an object name is a bucket reference. - * A bucket is always a directory, which could be used to lookup or add - * files to a bucket, but could not be opened as a file. - * - *

              A GcsPath containing neither bucket or object names is treated as - * the root of the GCS filesystem. A listing on the root element would return - * the buckets available to the user. - * - *

              If {@code null} is passed as either parameter, it is converted to an - * empty string internally for consistency. There is no distinction between - * an empty string and a {@code null}, as neither are allowed by GCS. - * - * @param bucket a GCS bucket name, or none ({@code null} or an empty string) - * if the object is not associated with a bucket - * (e.g. relative paths or the root node). - * @param object a GCS object path, or none ({@code null} or an empty string) - * for no object. - */ - public static GcsPath fromComponents(@Nullable String bucket, - @Nullable String object) { - return new GcsPath(null, bucket, object); - } - - @Nullable - private FileSystem fs; - @Nonnull - private final String bucket; - @Nonnull - private final String object; - - /** - * Constructs a GcsPath. - * - * @param fs the associated FileSystem, if any - * @param bucket the associated bucket, or none ({@code null} or an empty - * string) for a relative path component - * @param object the object, which is a fully-qualified object name if bucket - * was also provided, or none ({@code null} or an empty string) - * for no object - * @throws java.lang.IllegalArgumentException if the bucket of object names - * are invalid. - */ - public GcsPath(@Nullable FileSystem fs, - @Nullable String bucket, - @Nullable String object) { - if (bucket == null) { - bucket = ""; - } - checkArgument(!bucket.contains("/"), - "GCS bucket may not contain a slash"); - checkArgument(bucket.isEmpty() - || bucket.matches("[a-z0-9][-_a-z0-9.]+[a-z0-9]"), - "GCS bucket names must contain only lowercase letters, numbers, " - + "dashes (-), underscores (_), and dots (.). Bucket names " - + "must start and end with a number or letter. " - + "See https://developers.google.com/storage/docs/bucketnaming " - + "for more details. Bucket name: " + bucket); - - if (object == null) { - object = ""; - } - checkArgument( - object.indexOf('\n') < 0 && object.indexOf('\r') < 0, - "GCS object names must not contain Carriage Return or " - + "Line Feed characters."); - - this.fs = fs; - this.bucket = bucket; - this.object = object; - } - - /** - * Returns the bucket name associated with this GCS path, or an empty string - * if this is a relative path component. - */ - public String getBucket() { - return bucket; - } - - /** - * Returns the object name associated with this GCS path, or an empty string - * if no object is specified. - */ - public String getObject() { - return object; - } - - public void setFileSystem(FileSystem fs) { - this.fs = fs; - } - - @Override - public FileSystem getFileSystem() { - return fs; - } - - // Absolute paths are those that have a bucket and the root path. - @Override - public boolean isAbsolute() { - return !bucket.isEmpty() || object.isEmpty(); - } - - @Override - public GcsPath getRoot() { - return new GcsPath(fs, "", ""); - } - - @Override - public GcsPath getFileName() { - throw new UnsupportedOperationException(); - } - - /** - * Returns the parent path, or {@code null} if this path does not - * have a parent. - * - *

              Returns a path that ends in '/', as the parent path always refers to - * a directory. - */ - @Override - public GcsPath getParent() { - if (bucket.isEmpty() && object.isEmpty()) { - // The root path has no parent, by definition. - return null; - } - - if (object.isEmpty()) { - // A GCS bucket. All buckets come from a common root. - return getRoot(); - } - - // Skip last character, in case it is a trailing slash. - int i = object.lastIndexOf('/', object.length() - 2); - if (i <= 0) { - if (bucket.isEmpty()) { - // Relative paths are not attached to the root node. - return null; - } - return new GcsPath(fs, bucket, ""); - } - - // Retain trailing slash. - return new GcsPath(fs, bucket, object.substring(0, i + 1)); - } - - @Override - public int getNameCount() { - int count = bucket.isEmpty() ? 0 : 1; - if (object.isEmpty()) { - return count; - } - - // Add another for each separator found. - int index = -1; - while ((index = object.indexOf('/', index + 1)) != -1) { - count++; - } - - return object.endsWith("/") ? count : count + 1; - } - - @Override - public GcsPath getName(int count) { - checkArgument(count >= 0); - - Iterator iterator = iterator(); - for (int i = 0; i < count; ++i) { - checkArgument(iterator.hasNext()); - iterator.next(); - } - - checkArgument(iterator.hasNext()); - return (GcsPath) iterator.next(); - } - - @Override - public GcsPath subpath(int beginIndex, int endIndex) { - checkArgument(beginIndex >= 0); - checkArgument(endIndex > beginIndex); - - Iterator iterator = iterator(); - for (int i = 0; i < beginIndex; ++i) { - checkArgument(iterator.hasNext()); - iterator.next(); - } - - GcsPath path = null; - while (beginIndex < endIndex) { - checkArgument(iterator.hasNext()); - if (path == null) { - path = (GcsPath) iterator.next(); - } else { - path = path.resolve(iterator.next()); - } - ++beginIndex; - } - - return path; - } - - @Override - public boolean startsWith(Path other) { - if (other instanceof GcsPath) { - GcsPath gcsPath = (GcsPath) other; - return startsWith(gcsPath.bucketAndObject()); - } else { - return startsWith(other.toString()); - } - } - - @Override - public boolean startsWith(String prefix) { - return bucketAndObject().startsWith(prefix); - } - - @Override - public boolean endsWith(Path other) { - if (other instanceof GcsPath) { - GcsPath gcsPath = (GcsPath) other; - return endsWith(gcsPath.bucketAndObject()); - } else { - return endsWith(other.toString()); - } - } - - @Override - public boolean endsWith(String suffix) { - return bucketAndObject().endsWith(suffix); - } - - // TODO: support "." and ".." path components? - @Override - public GcsPath normalize() { - return this; - } - - @Override - public GcsPath resolve(Path other) { - if (other instanceof GcsPath) { - GcsPath path = (GcsPath) other; - if (path.isAbsolute()) { - return path; - } else { - return resolve(path.getObject()); - } - } else { - return resolve(other.toString()); - } - } - - @Override - public GcsPath resolve(String other) { - if (bucket.isEmpty() && object.isEmpty()) { - // Resolve on a root path is equivalent to looking up a bucket and object. - other = SCHEME + "://" + other; - } - - if (other.startsWith(SCHEME + "://")) { - GcsPath path = GcsPath.fromUri(other); - path.setFileSystem(getFileSystem()); - return path; - } - - if (other.isEmpty()) { - // An empty component MUST refer to a directory. - other = "/"; - } - - if (object.isEmpty()) { - return new GcsPath(fs, bucket, other); - } else if (object.endsWith("/")) { - return new GcsPath(fs, bucket, object + other); - } else { - return new GcsPath(fs, bucket, object + "/" + other); - } - } - - @Override - public Path resolveSibling(Path other) { - throw new UnsupportedOperationException(); - } - - @Override - public Path resolveSibling(String other) { - throw new UnsupportedOperationException(); - } - - @Override - public Path relativize(Path other) { - throw new UnsupportedOperationException(); - } - - @Override - public GcsPath toAbsolutePath() { - return this; - } - - @Override - public GcsPath toRealPath(LinkOption... options) throws IOException { - return this; - } - - @Override - public File toFile() { - throw new UnsupportedOperationException(); - } - - @Override - public WatchKey register(WatchService watcher, WatchEvent.Kind[] events, - WatchEvent.Modifier... modifiers) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public WatchKey register(WatchService watcher, WatchEvent.Kind... events) - throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public Iterator iterator() { - return new NameIterator(fs, !bucket.isEmpty(), bucketAndObject()); - } - - private static class NameIterator implements Iterator { - private final FileSystem fs; - private boolean fullPath; - private String name; - - NameIterator(FileSystem fs, boolean fullPath, String name) { - this.fs = fs; - this.fullPath = fullPath; - this.name = name; - } - - @Override - public boolean hasNext() { - return !Strings.isNullOrEmpty(name); - } - - @Override - public GcsPath next() { - int i = name.indexOf('/'); - String component; - if (i >= 0) { - component = name.substring(0, i); - name = name.substring(i + 1); - } else { - component = name; - name = null; - } - if (fullPath) { - fullPath = false; - return new GcsPath(fs, component, ""); - } else { - // Relative paths have no bucket. - return new GcsPath(fs, "", component); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - @Override - public int compareTo(Path other) { - if (!(other instanceof GcsPath)) { - throw new ClassCastException(); - } - - GcsPath path = (GcsPath) other; - int b = bucket.compareTo(path.bucket); - if (b != 0) { - return b; - } - - // Compare a component at a time, so that the separator char doesn't - // get compared against component contents. Eg, "a/b" < "a-1/b". - Iterator left = iterator(); - Iterator right = path.iterator(); - - while (left.hasNext() && right.hasNext()) { - String leftStr = left.next().toString(); - String rightStr = right.next().toString(); - int c = leftStr.compareTo(rightStr); - if (c != 0) { - return c; - } - } - - if (!left.hasNext() && !right.hasNext()) { - return 0; - } else { - return left.hasNext() ? 1 : -1; - } - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - GcsPath paths = (GcsPath) o; - return bucket.equals(paths.bucket) && object.equals(paths.object); - } - - @Override - public int hashCode() { - int result = bucket.hashCode(); - result = 31 * result + object.hashCode(); - return result; - } - - @Override - public String toString() { - if (!isAbsolute()) { - return object; - } - StringBuilder sb = new StringBuilder(); - sb.append(SCHEME) - .append("://"); - if (!bucket.isEmpty()) { - sb.append(bucket) - .append('/'); - } - sb.append(object); - return sb.toString(); - } - - // TODO: Consider using resource names for all GCS paths used by the SDK. - public String toResourceName() { - StringBuilder sb = new StringBuilder(); - sb.append("storage.googleapis.com/"); - if (!bucket.isEmpty()) { - sb.append(bucket).append('/'); - } - sb.append(object); - return sb.toString(); - } - - @Override - public URI toUri() { - try { - return new URI(SCHEME, "//" + bucketAndObject(), null); - } catch (URISyntaxException e) { - throw new RuntimeException("Unable to create URI for GCS path " + this); - } - } - - private String bucketAndObject() { - if (bucket.isEmpty()) { - return object; - } else { - return bucket + "/" + object; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/package-info.java deleted file mode 100644 index 2f57938e20..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/gcsfs/package-info.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** Defines utilities used to interact with Google Cloud Storage. **/ -package com.google.cloud.dataflow.sdk.util.gcsfs; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/package-info.java deleted file mode 100644 index c92adab9b6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/package-info.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** Defines utilities used by the Dataflow SDK. **/ -package com.google.cloud.dataflow.sdk.util; diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/AccumulatorCombiningState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/AccumulatorCombiningState.java deleted file mode 100644 index 0d78b13bad..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/AccumulatorCombiningState.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; - -/** - * State for a single value that is managed by a {@link CombineFn}. This is an internal extension - * to {@link CombiningState} that includes the {@code AccumT} type. - * - * @param the type of values added to the state - * @param the type of accumulator - * @param the type of value extracted from the state - */ -public interface AccumulatorCombiningState - extends CombiningState { - - /** - * Read the merged accumulator for this combining value. It is implied that reading the - * state involes reading the accumulator, so {@link #readLater} is sufficient to prefetch for - * this. - */ - AccumT getAccum(); - - /** - * Add an accumulator to this combining value. Depending on implementation this may immediately - * merge it with the previous accumulator, or may buffer this accumulator for a future merge. - */ - void addAccum(AccumT accum); - - /** - * Merge the given accumulators according to the underlying combiner. - */ - AccumT mergeAccumulators(Iterable accumulators); - - @Override - AccumulatorCombiningState readLater(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java deleted file mode 100644 index 363e480797..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/BagState.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -/** - * State containing a bag values. Items can be added to the bag and the contents read out. - * - * @param The type of elements in the bag. - */ -public interface BagState extends CombiningState> { - @Override - BagState readLater(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningState.java deleted file mode 100644 index 673bebbfb4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CombiningState.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; - -/** - * State that combines multiple {@code InputT} values using a {@link CombineFn} to produce a single - * {@code OutputT} value. - * - * @param the type of values added to the state - * @param the type of value extracted from the state - */ -public interface CombiningState extends ReadableState, State { - /** - * Add a value to the buffer. - */ - void add(InputT value); - - /** - * Return true if this state is empty. - */ - ReadableState isEmpty(); - - @Override - CombiningState readLater(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java deleted file mode 100644 index bb4ccd8ae7..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternals.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.util.CombineFnUtil; -import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals.InMemoryState; -import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; -import com.google.common.base.Optional; -import com.google.common.collect.Iterables; - -import org.joda.time.Instant; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; - -import javax.annotation.Nullable; - -/** - * {@link StateInternals} built on top of an underlying {@link StateTable} that contains instances - * of {@link InMemoryState}. Whenever state that exists in the underlying {@link StateTable} is - * accessed, an independent copy will be created within this table. - */ -public class CopyOnAccessInMemoryStateInternals implements StateInternals { - private final K key; - private final CopyOnAccessInMemoryStateTable table; - - /** - * Creates a new {@link CopyOnAccessInMemoryStateInternals} with the underlying (possibly null) - * StateInternals. - */ - public static CopyOnAccessInMemoryStateInternals withUnderlying( - K key, @Nullable CopyOnAccessInMemoryStateInternals underlying) { - return new CopyOnAccessInMemoryStateInternals(key, underlying); - } - - private CopyOnAccessInMemoryStateInternals( - K key, CopyOnAccessInMemoryStateInternals underlying) { - this.key = key; - table = - new CopyOnAccessInMemoryStateTable(key, underlying == null ? null : underlying.table); - } - - /** - * Ensures this {@link CopyOnAccessInMemoryStateInternals} is complete. Other copies of state for - * the same Step and Key may be discarded after invoking this method. - * - *

              For each {@link StateNamespace}, for each {@link StateTag address} in that namespace that - * has not been bound in this {@link CopyOnAccessInMemoryStateInternals}, put a reference to that - * state within this {@link StateInternals}. - * - *

              Additionally, stores the {@link WatermarkHoldState} with the earliest time bound in the - * state table after the commit is completed, enabling calls to - * {@link #getEarliestWatermarkHold()}. - * - * @return this table - */ - public CopyOnAccessInMemoryStateInternals commit() { - table.commit(); - return this; - } - - /** - * Gets the earliest Watermark Hold present in this table. - * - *

              Must be called after this state has been committed. Will throw an - * {@link IllegalStateException} if the state has not been committed. - */ - public Instant getEarliestWatermarkHold() { - // After commit, the watermark hold is always present, but may be - // BoundedWindow#TIMESTAMP_MAX_VALUE if there is no hold set. - checkState( - table.earliestWatermarkHold.isPresent(), - "Can't get the earliest watermark hold in a %s before it is committed", - getClass().getSimpleName()); - return table.earliestWatermarkHold.get(); - } - - @Override - public T state(StateNamespace namespace, StateTag address) { - return state(namespace, address, StateContexts.nullContext()); - } - - @Override - public T state( - StateNamespace namespace, StateTag address, StateContext c) { - return table.get(namespace, address, c); - } - - @Override - public K getKey() { - return key; - } - - public boolean isEmpty() { - return Iterables.isEmpty(table.values()); - } - - /** - * A {@link StateTable} that, when a value is retrieved with - * {@link StateTable#get(StateNamespace, StateTag)}, first attempts to obtain a copy of existing - * {@link State} from an underlying {@link StateTable}. - */ - private static class CopyOnAccessInMemoryStateTable extends StateTable { - private final K key; - private Optional> underlying; - - /** - * The StateBinderFactory currently in use by this {@link CopyOnAccessInMemoryStateTable}. - * - *

              There are three {@link StateBinderFactory} implementations used by the {@link - * CopyOnAccessInMemoryStateTable}. - *

                - *
              • The default {@link StateBinderFactory} is a {@link CopyOnBindBinderFactory}, allowing - * the table to copy any existing {@link State} values to this {@link StateTable} from the - * underlying table when accessed, at which point mutations will not be visible to the - * underlying table - effectively a "Copy by Value" binder.
              • - *
              • During the execution of the {@link #commit()} method, this is a - * {@link ReadThroughBinderFactory}, which copies the references to the existing - * {@link State} objects to this {@link StateTable}.
              • - *
              • After the execution of the {@link #commit()} method, this is an - * instance of {@link InMemoryStateBinderFactory}, which constructs new instances of state - * when a {@link StateTag} is bound.
              • - *
              - */ - private StateBinderFactory binderFactory; - - /** - * The earliest watermark hold in this table. - */ - private Optional earliestWatermarkHold; - - public CopyOnAccessInMemoryStateTable(K key, StateTable underlying) { - this.key = key; - this.underlying = Optional.fromNullable(underlying); - binderFactory = new CopyOnBindBinderFactory<>(key, this.underlying); - earliestWatermarkHold = Optional.absent(); - } - - /** - * Copies all values in the underlying table to this table, then discards the underlying table. - * - *

              If there is an underlying table, this replaces the existing - * {@link CopyOnBindBinderFactory} with a {@link ReadThroughBinderFactory}, then reads all of - * the values in the existing table, binding the state values to this table. The old StateTable - * should be discarded after the call to {@link #commit()}. - * - *

              After copying all of the existing values, replace the binder factory with an instance of - * {@link InMemoryStateBinderFactory} to construct new values, since all existing values - * are bound in this {@link StateTable table} and this table represents the canonical state. - */ - private void commit() { - Instant earliestHold = getEarliestWatermarkHold(); - if (underlying.isPresent()) { - ReadThroughBinderFactory readThroughBinder = - new ReadThroughBinderFactory<>(underlying.get()); - binderFactory = readThroughBinder; - Instant earliestUnderlyingHold = readThroughBinder.readThroughAndGetEarliestHold(this); - if (earliestUnderlyingHold.isBefore(earliestHold)) { - earliestHold = earliestUnderlyingHold; - } - } - earliestWatermarkHold = Optional.of(earliestHold); - clearEmpty(); - binderFactory = new InMemoryStateBinderFactory<>(key); - underlying = Optional.absent(); - } - - /** - * Get the earliest watermark hold in this table. Ignores the contents of any underlying table. - */ - private Instant getEarliestWatermarkHold() { - Instant earliest = BoundedWindow.TIMESTAMP_MAX_VALUE; - for (State existingState : this.values()) { - if (existingState instanceof WatermarkHoldState) { - Instant hold = ((WatermarkHoldState) existingState).read(); - if (hold != null && hold.isBefore(earliest)) { - earliest = hold; - } - } - } - return earliest; - } - - /** - * Clear all empty {@link StateNamespace StateNamespaces} from this table. If all states are - * empty, clear the entire table. - * - *

              Because {@link InMemoryState} is not removed from the {@link StateTable} after it is - * cleared, in case contents are modified after being cleared, the table must be explicitly - * checked to ensure that it contains state and removed if not (otherwise we may never use - * the table again). - */ - private void clearEmpty() { - Collection emptyNamespaces = new HashSet<>(this.getNamespacesInUse()); - for (StateNamespace namespace : this.getNamespacesInUse()) { - for (State existingState : this.getTagsInUse(namespace).values()) { - if (!((InMemoryState) existingState).isCleared()) { - emptyNamespaces.remove(namespace); - break; - } - } - } - for (StateNamespace empty : emptyNamespaces) { - this.clearNamespace(empty); - } - } - - @Override - protected StateBinder binderForNamespace(final StateNamespace namespace, StateContext c) { - return binderFactory.forNamespace(namespace, c); - } - - private interface StateBinderFactory { - StateBinder forNamespace(StateNamespace namespace, StateContext c); - } - - /** - * {@link StateBinderFactory} that creates a copy of any existing state when the state is bound. - */ - private static class CopyOnBindBinderFactory implements StateBinderFactory { - private final K key; - private final Optional> underlying; - - public CopyOnBindBinderFactory(K key, Optional> underlying) { - this.key = key; - this.underlying = underlying; - } - - private boolean containedInUnderlying(StateNamespace namespace, StateTag tag) { - return underlying.isPresent() && underlying.get().isNamespaceInUse(namespace) - && underlying.get().getTagsInUse(namespace).containsKey(tag); - } - - @Override - public StateBinder forNamespace(final StateNamespace namespace, final StateContext c) { - return new StateBinder() { - @Override - public WatermarkHoldState bindWatermark( - StateTag> address, - OutputTimeFn outputTimeFn) { - if (containedInUnderlying(namespace, address)) { - @SuppressWarnings("unchecked") - InMemoryState> existingState = - (InMemoryStateInternals.InMemoryState>) - underlying.get().get(namespace, address, c); - return existingState.copy(); - } else { - return new InMemoryStateInternals.InMemoryWatermarkHold<>( - outputTimeFn); - } - } - - @Override - public ValueState bindValue( - StateTag> address, Coder coder) { - if (containedInUnderlying(namespace, address)) { - @SuppressWarnings("unchecked") - InMemoryState> existingState = - (InMemoryStateInternals.InMemoryState>) - underlying.get().get(namespace, address, c); - return existingState.copy(); - } else { - return new InMemoryStateInternals.InMemoryValue<>(); - } - } - - @Override - public AccumulatorCombiningState - bindCombiningValue( - StateTag> address, - Coder accumCoder, CombineFn combineFn) { - if (containedInUnderlying(namespace, address)) { - @SuppressWarnings("unchecked") - InMemoryState> - existingState = ( - InMemoryStateInternals - .InMemoryState>) underlying.get().get(namespace, address, c); - return existingState.copy(); - } else { - return new InMemoryStateInternals.InMemoryCombiningValue<>( - key, combineFn.asKeyedFn()); - } - } - - @Override - public BagState bindBag( - StateTag> address, Coder elemCoder) { - if (containedInUnderlying(namespace, address)) { - @SuppressWarnings("unchecked") - InMemoryState> existingState = - (InMemoryStateInternals.InMemoryState>) - underlying.get().get(namespace, address, c); - return existingState.copy(); - } else { - return new InMemoryStateInternals.InMemoryBag<>(); - } - } - - @Override - public AccumulatorCombiningState - bindKeyedCombiningValue( - StateTag> address, - Coder accumCoder, - KeyedCombineFn combineFn) { - if (containedInUnderlying(namespace, address)) { - @SuppressWarnings("unchecked") - InMemoryState> - existingState = ( - InMemoryStateInternals - .InMemoryState>) underlying.get().get(namespace, address, c); - return existingState.copy(); - } else { - return new InMemoryStateInternals.InMemoryCombiningValue<>(key, combineFn); - } - } - - @Override - public AccumulatorCombiningState - bindKeyedCombiningValueWithContext( - StateTag> address, - Coder accumCoder, - KeyedCombineFnWithContext combineFn) { - return bindKeyedCombiningValue( - address, accumCoder, CombineFnUtil.bindContext(combineFn, c)); - } - }; - } - } - - /** - * {@link StateBinderFactory} that reads directly from the underlying table. Used during calls - * to {@link CopyOnAccessInMemoryStateTable#commit()} to read all values from - * the underlying table. - */ - private static class ReadThroughBinderFactory implements StateBinderFactory { - private final StateTable underlying; - - public ReadThroughBinderFactory(StateTable underlying) { - this.underlying = underlying; - } - - public Instant readThroughAndGetEarliestHold(StateTable readTo) { - Instant earliestHold = BoundedWindow.TIMESTAMP_MAX_VALUE; - for (StateNamespace namespace : underlying.getNamespacesInUse()) { - for (Map.Entry, ? extends State> existingState : - underlying.getTagsInUse(namespace).entrySet()) { - if (!((InMemoryState) existingState.getValue()).isCleared()) { - // Only read through non-cleared values to ensure that completed windows are - // eventually discarded, and remember the earliest watermark hold from among those - // values. - State state = - readTo.get(namespace, existingState.getKey(), StateContexts.nullContext()); - if (state instanceof WatermarkHoldState) { - Instant hold = ((WatermarkHoldState) state).read(); - if (hold != null && hold.isBefore(earliestHold)) { - earliestHold = hold; - } - } - } - } - } - return earliestHold; - } - - @Override - public StateBinder forNamespace(final StateNamespace namespace, final StateContext c) { - return new StateBinder() { - @Override - public WatermarkHoldState bindWatermark( - StateTag> address, - OutputTimeFn outputTimeFn) { - return underlying.get(namespace, address, c); - } - - @Override - public ValueState bindValue( - StateTag> address, Coder coder) { - return underlying.get(namespace, address, c); - } - - @Override - public AccumulatorCombiningState - bindCombiningValue( - StateTag> address, - Coder accumCoder, CombineFn combineFn) { - return underlying.get(namespace, address, c); - } - - @Override - public BagState bindBag( - StateTag> address, Coder elemCoder) { - return underlying.get(namespace, address, c); - } - - @Override - public AccumulatorCombiningState - bindKeyedCombiningValue( - StateTag> address, - Coder accumCoder, - KeyedCombineFn combineFn) { - return underlying.get(namespace, address, c); - } - - @Override - public AccumulatorCombiningState - bindKeyedCombiningValueWithContext( - StateTag> address, - Coder accumCoder, - KeyedCombineFnWithContext combineFn) { - return bindKeyedCombiningValue( - address, accumCoder, CombineFnUtil.bindContext(combineFn, c)); - } - }; - } - } - - private static class InMemoryStateBinderFactory implements StateBinderFactory { - private final K key; - - public InMemoryStateBinderFactory(K key) { - this.key = key; - } - - @Override - public StateBinder forNamespace(StateNamespace namespace, StateContext c) { - return new InMemoryStateInternals.InMemoryStateBinder<>(key, c); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java deleted file mode 100644 index 8404801260..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternals.java +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.util.CombineFnUtil; -import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import javax.annotation.Nullable; - -/** - * In-memory implementation of {@link StateInternals}. Used in {@code BatchModeExecutionContext} - * and for running tests that need state. - */ -@Experimental(Kind.STATE) -public class InMemoryStateInternals implements StateInternals { - - public static InMemoryStateInternals forKey(K key) { - return new InMemoryStateInternals<>(key); - } - - private final K key; - - protected InMemoryStateInternals(K key) { - this.key = key; - } - - @Override - public K getKey() { - return key; - } - - interface InMemoryState> { - boolean isCleared(); - T copy(); - } - - protected final StateTable inMemoryState = new StateTable() { - @Override - protected StateBinder binderForNamespace(StateNamespace namespace, StateContext c) { - return new InMemoryStateBinder(key, c); - } - }; - - public void clear() { - inMemoryState.clear(); - } - - /** - * Return true if the given state is empty. This is used by the test framework to make sure - * that the state has been properly cleaned up. - */ - protected boolean isEmptyForTesting(State state) { - return ((InMemoryState) state).isCleared(); - } - - @Override - public T state(StateNamespace namespace, StateTag address) { - return inMemoryState.get(namespace, address, StateContexts.nullContext()); - } - - @Override - public T state( - StateNamespace namespace, StateTag address, final StateContext c) { - return inMemoryState.get(namespace, address, c); - } - - /** - * A {@link StateBinder} that returns In Memory {@link State} objects. - */ - static class InMemoryStateBinder implements StateBinder { - private final K key; - private final StateContext c; - - InMemoryStateBinder(K key, StateContext c) { - this.key = key; - this.c = c; - } - - @Override - public ValueState bindValue( - StateTag> address, Coder coder) { - return new InMemoryValue(); - } - - @Override - public BagState bindBag( - final StateTag> address, Coder elemCoder) { - return new InMemoryBag(); - } - - @Override - public AccumulatorCombiningState - bindCombiningValue( - StateTag> address, - Coder accumCoder, - final CombineFn combineFn) { - return new InMemoryCombiningValue(key, combineFn.asKeyedFn()); - } - - @Override - public WatermarkHoldState bindWatermark( - StateTag> address, - OutputTimeFn outputTimeFn) { - return new InMemoryWatermarkHold(outputTimeFn); - } - - @Override - public AccumulatorCombiningState - bindKeyedCombiningValue( - StateTag> address, - Coder accumCoder, - KeyedCombineFn combineFn) { - return new InMemoryCombiningValue(key, combineFn); - } - - @Override - public AccumulatorCombiningState - bindKeyedCombiningValueWithContext( - StateTag> address, - Coder accumCoder, - KeyedCombineFnWithContext combineFn) { - return bindKeyedCombiningValue(address, accumCoder, CombineFnUtil.bindContext(combineFn, c)); - } - } - - static final class InMemoryValue implements ValueState, InMemoryState> { - private boolean isCleared = true; - private T value = null; - - @Override - public void clear() { - // Even though we're clearing we can't remove this from the in-memory state map, since - // other users may already have a handle on this Value. - value = null; - isCleared = true; - } - - @Override - public InMemoryValue readLater() { - return this; - } - - @Override - public T read() { - return value; - } - - @Override - public void write(T input) { - isCleared = false; - this.value = input; - } - - @Override - public InMemoryValue copy() { - InMemoryValue that = new InMemoryValue<>(); - if (!this.isCleared) { - that.isCleared = this.isCleared; - that.value = this.value; - } - return that; - } - - @Override - public boolean isCleared() { - return isCleared; - } - } - - static final class InMemoryWatermarkHold - implements WatermarkHoldState, InMemoryState> { - - private final OutputTimeFn outputTimeFn; - - @Nullable - private Instant combinedHold = null; - - public InMemoryWatermarkHold(OutputTimeFn outputTimeFn) { - this.outputTimeFn = outputTimeFn; - } - - @Override - public InMemoryWatermarkHold readLater() { - return this; - } - - @Override - public void clear() { - // Even though we're clearing we can't remove this from the in-memory state map, since - // other users may already have a handle on this WatermarkBagInternal. - combinedHold = null; - } - - @Override - public Instant read() { - return combinedHold; - } - - @Override - public void add(Instant outputTime) { - combinedHold = combinedHold == null ? outputTime - : outputTimeFn.combine(combinedHold, outputTime); - } - - @Override - public boolean isCleared() { - return combinedHold == null; - } - - @Override - public ReadableState isEmpty() { - return new ReadableState() { - @Override - public ReadableState readLater() { - return this; - } - @Override - public Boolean read() { - return combinedHold == null; - } - }; - } - - @Override - public OutputTimeFn getOutputTimeFn() { - return outputTimeFn; - } - - @Override - public String toString() { - return Objects.toString(combinedHold); - } - - @Override - public InMemoryWatermarkHold copy() { - InMemoryWatermarkHold that = - new InMemoryWatermarkHold<>(outputTimeFn); - that.combinedHold = this.combinedHold; - return that; - } - } - - static final class InMemoryCombiningValue - implements AccumulatorCombiningState, - InMemoryState> { - private final K key; - private boolean isCleared = true; - private final KeyedCombineFn combineFn; - private AccumT accum; - - InMemoryCombiningValue( - K key, KeyedCombineFn combineFn) { - this.key = key; - this.combineFn = combineFn; - accum = combineFn.createAccumulator(key); - } - - @Override - public InMemoryCombiningValue readLater() { - return this; - } - - @Override - public void clear() { - // Even though we're clearing we can't remove this from the in-memory state map, since - // other users may already have a handle on this CombiningValue. - accum = combineFn.createAccumulator(key); - isCleared = true; - } - - @Override - public OutputT read() { - return combineFn.extractOutput(key, accum); - } - - @Override - public void add(InputT input) { - isCleared = false; - accum = combineFn.addInput(key, accum, input); - } - - @Override - public AccumT getAccum() { - return accum; - } - - @Override - public ReadableState isEmpty() { - return new ReadableState() { - @Override - public ReadableState readLater() { - return this; - } - @Override - public Boolean read() { - return isCleared; - } - }; - } - - @Override - public void addAccum(AccumT accum) { - isCleared = false; - this.accum = combineFn.mergeAccumulators(key, Arrays.asList(this.accum, accum)); - } - - @Override - public AccumT mergeAccumulators(Iterable accumulators) { - return combineFn.mergeAccumulators(key, accumulators); - } - - @Override - public boolean isCleared() { - return isCleared; - } - - @Override - public InMemoryCombiningValue copy() { - InMemoryCombiningValue that = - new InMemoryCombiningValue<>(key, combineFn); - if (!this.isCleared) { - that.isCleared = this.isCleared; - that.addAccum(accum); - } - return that; - } - } - - static final class InMemoryBag implements BagState, InMemoryState> { - private List contents = new ArrayList<>(); - - @Override - public void clear() { - // Even though we're clearing we can't remove this from the in-memory state map, since - // other users may already have a handle on this Bag. - // The result of get/read below must be stable for the lifetime of the bundle within which it - // was generated. In batch and direct runners the bundle lifetime can be - // greater than the window lifetime, in which case this method can be called while - // the result is still in use. We protect against this by hot-swapping instead of - // clearing the contents. - contents = new ArrayList<>(); - } - - @Override - public InMemoryBag readLater() { - return this; - } - - @Override - public Iterable read() { - return contents; - } - - @Override - public void add(T input) { - contents.add(input); - } - - @Override - public boolean isCleared() { - return contents.isEmpty(); - } - - @Override - public ReadableState isEmpty() { - return new ReadableState() { - @Override - public ReadableState readLater() { - return this; - } - - @Override - public Boolean read() { - return contents.isEmpty(); - } - }; - } - - @Override - public InMemoryBag copy() { - InMemoryBag that = new InMemoryBag<>(); - that.contents.addAll(this.contents); - return that; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateAccessor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateAccessor.java deleted file mode 100644 index 40211d739b..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/MergingStateAccessor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; - -import java.util.Map; - -/** - * Interface for accessing persistent state while windows are merging. - * - *

              For internal use only. - */ -@Experimental(Kind.STATE) -public interface MergingStateAccessor - extends StateAccessor { - /** - * Analogous to {@link #access}, but returned as a map from each window which is - * about to be merged to the corresponding state. Only includes windows which - * are known to have state. - */ - Map accessInEachMergingWindow( - StateTag address); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ReadableState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ReadableState.java deleted file mode 100644 index 8f690a33de..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ReadableState.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; - -/** - * A {@code StateContents} is produced by the read methods on all {@link State} objects. - * Calling {@link #read} returns the associated value. - * - *

              This class is similar to {@link java.util.concurrent.Future}, but each invocation of - * {@link #read} need not return the same value. - * - *

              Getting the {@code StateContents} from a read method indicates the desire to eventually - * read a value. Depending on the runner this may or may not immediately start the read. - * - * @param The type of value returned by {@link #read}. - */ -@Experimental(Kind.STATE) -public interface ReadableState { - /** - * Read the current value, blocking until it is available. - * - *

              If there will be many calls to {@link #read} for different state in short succession, - * you should first call {@link #readLater} for all of them so the reads can potentially be - * batched (depending on the underlying {@link StateInternals} implementation}. - */ - T read(); - - /** - * Indicate that the value will be read later. - * - *

              This allows a {@link StateInternals} implementation to start an asynchronous prefetch or - * to include this state in the next batch of reads. - * - * @return this for convenient chaining - */ - ReadableState readLater(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java deleted file mode 100644 index 0cef786ad5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/State.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -/** - * Base interface for all state locations. - * - *

              Specific types of state add appropriate accessors for reading and writing values, see - * {@link ValueState}, {@link BagState}, and {@link CombiningState}. - */ -public interface State { - - /** - * Clear out the state location. - */ - void clear(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateAccessor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateAccessor.java deleted file mode 100644 index 6cfbecff70..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateAccessor.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; - -/** - * Interface for accessing a {@link StateTag} in the current context. - * - *

              For internal use only. - */ -@Experimental(Kind.STATE) -public interface StateAccessor { - /** - * Access the storage for the given {@code address} in the current window. - * - *

              Never accounts for merged windows. When windows are merged, any state accessed via - * this method must be eagerly combined and written into the result window. - */ - StateT access(StateTag address); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java deleted file mode 100644 index c9431669f5..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContext.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -/** - * Information accessible the state API. - */ -public interface StateContext { - /** - * Returns the {@code PipelineOptions} specified with the - * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner}. - */ - PipelineOptions getPipelineOptions(); - - /** - * Returns the value of the side input for the corresponding state window. - */ - T sideInput(PCollectionView view); - - /** - * Returns the window corresponding to the state. - */ - W window(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java deleted file mode 100644 index e301d438cd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateContexts.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowingInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import javax.annotation.Nullable; - -/** - * Factory that produces {@link StateContext} based on different inputs. - */ -public class StateContexts { - private static final StateContext NULL_CONTEXT = - new StateContext() { - @Override - public PipelineOptions getPipelineOptions() { - throw new IllegalArgumentException("cannot call getPipelineOptions() in a null context"); - } - - @Override - public T sideInput(PCollectionView view) { - throw new IllegalArgumentException("cannot call sideInput() in a null context"); - } - - @Override - public BoundedWindow window() { - throw new IllegalArgumentException("cannot call window() in a null context"); - }}; - - /** - * Returns a fake {@link StateContext}. - */ - @SuppressWarnings("unchecked") - public static StateContext nullContext() { - return (StateContext) NULL_CONTEXT; - } - - /** - * Returns a {@link StateContext} that only contains the state window. - */ - public static StateContext windowOnly(final W window) { - return new StateContext() { - @Override - public PipelineOptions getPipelineOptions() { - throw new IllegalArgumentException( - "cannot call getPipelineOptions() in a window only context"); - } - @Override - public T sideInput(PCollectionView view) { - throw new IllegalArgumentException("cannot call sideInput() in a window only context"); - } - @Override - public W window() { - return window; - } - }; - } - - /** - * Returns a {@link StateContext} from {@code PipelineOptions}, {@link WindowingInternals}, - * and the state window. - */ - public static StateContext createFromComponents( - @Nullable final PipelineOptions options, - final WindowingInternals windowingInternals, - final W window) { - @SuppressWarnings("unchecked") - StateContext typedNullContext = (StateContext) NULL_CONTEXT; - if (options == null) { - return typedNullContext; - } else { - return new StateContext() { - - @Override - public PipelineOptions getPipelineOptions() { - return options; - } - - @Override - public T sideInput(PCollectionView view) { - return windowingInternals.sideInput(view, window); - } - - @Override - public W window() { - return window; - } - }; - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java deleted file mode 100644 index b31afb4698..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateInternals.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; - -/** - * {@code StateInternals} describes the functionality a runner needs to provide for the - * State API to be supported. - * - *

              The SDK will only use this after elements have been partitioned by key. For instance, after a - * {@link GroupByKey} operation. The runner implementation must ensure that any writes using - * {@link StateInternals} are implicitly scoped to the key being processed and the specific step - * accessing state. - * - *

              The runner implementation must also ensure that any writes to the associated state objects - * are persisted together with the completion status of the processing that produced these - * writes. - * - *

              This is a low-level API intended for use by the Dataflow SDK. It should not be - * used directly, and is highly likely to change. - */ -@Experimental(Kind.STATE) -public interface StateInternals { - - /** The key for this {@link StateInternals}. */ - K getKey(); - - /** - * Return the state associated with {@code address} in the specified {@code namespace}. - */ - T state(StateNamespace namespace, StateTag address); - - /** - * Return the state associated with {@code address} in the specified {@code namespace} - * with the {@link StateContext}. - */ - T state( - StateNamespace namespace, StateTag address, StateContext c); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java deleted file mode 100644 index 54aaf739dd..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateMerging.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; - -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * Helpers for merging state. - */ -public class StateMerging { - /** - * Clear all state in {@code address} in all windows under merge (even result windows) - * in {@code context}. - */ - public static void clear( - MergingStateAccessor context, StateTag address) { - for (StateT state : context.accessInEachMergingWindow(address).values()) { - state.clear(); - } - } - - /** - * Prefetch all bag state in {@code address} across all windows under merge in - * {@code context}, except for the bag state in the final state address window which we can - * blindly append to. - */ - public static void prefetchBags( - MergingStateAccessor context, StateTag> address) { - Map> map = context.accessInEachMergingWindow(address); - if (map.isEmpty()) { - // Nothing to prefetch. - return; - } - BagState result = context.access(address); - // Prefetch everything except what's already in result. - for (BagState source : map.values()) { - if (!source.equals(result)) { - source.readLater(); - } - } - } - - /** - * Merge all bag state in {@code address} across all windows under merge. - */ - public static void mergeBags( - MergingStateAccessor context, StateTag> address) { - mergeBags(context.accessInEachMergingWindow(address).values(), context.access(address)); - } - - /** - * Merge all bag state in {@code sources} (which may include {@code result}) into {@code result}. - */ - public static void mergeBags( - Collection> sources, BagState result) { - if (sources.isEmpty()) { - // Nothing to merge. - return; - } - // Prefetch everything except what's already in result. - List>> futures = new ArrayList<>(sources.size()); - for (BagState source : sources) { - if (!source.equals(result)) { - source.readLater(); - futures.add(source); - } - } - if (futures.isEmpty()) { - // Result already holds all the values. - return; - } - // Transfer from sources to result. - for (ReadableState> future : futures) { - for (T element : future.read()) { - result.add(element); - } - } - // Clear sources except for result. - for (BagState source : sources) { - if (!source.equals(result)) { - source.clear(); - } - } - } - - /** - * Prefetch all combining value state for {@code address} across all merging windows in {@code - * context}. - */ - public static , W extends BoundedWindow> void - prefetchCombiningValues(MergingStateAccessor context, - StateTag address) { - for (StateT state : context.accessInEachMergingWindow(address).values()) { - state.readLater(); - } - } - - /** - * Merge all value state in {@code address} across all merging windows in {@code context}. - */ - public static void mergeCombiningValues( - MergingStateAccessor context, - StateTag> address) { - mergeCombiningValues( - context.accessInEachMergingWindow(address).values(), context.access(address)); - } - - /** - * Merge all value state from {@code sources} (which may include {@code result}) into - * {@code result}. - */ - public static void mergeCombiningValues( - Collection> sources, - AccumulatorCombiningState result) { - if (sources.isEmpty()) { - // Nothing to merge. - return; - } - if (sources.size() == 1 && sources.contains(result)) { - // Result already holds combined value. - return; - } - // Prefetch. - List> futures = new ArrayList<>(sources.size()); - for (AccumulatorCombiningState source : sources) { - source.readLater(); - } - // Read. - List accumulators = new ArrayList<>(futures.size()); - for (AccumulatorCombiningState source : sources) { - accumulators.add(source.getAccum()); - } - // Merge (possibly update and return one of the existing accumulators). - AccumT merged = result.mergeAccumulators(accumulators); - // Clear sources. - for (AccumulatorCombiningState source : sources) { - source.clear(); - } - // Update result. - result.addAccum(merged); - } - - /** - * Prefetch all watermark state for {@code address} across all merging windows in - * {@code context}. - */ - public static void prefetchWatermarks( - MergingStateAccessor context, - StateTag> address) { - Map> map = context.accessInEachMergingWindow(address); - WatermarkHoldState result = context.access(address); - if (map.isEmpty()) { - // Nothing to prefetch. - return; - } - if (map.size() == 1 && map.values().contains(result) - && result.getOutputTimeFn().dependsOnlyOnEarliestInputTimestamp()) { - // Nothing to change. - return; - } - if (result.getOutputTimeFn().dependsOnlyOnWindow()) { - // No need to read existing holds. - return; - } - // Prefetch. - for (WatermarkHoldState source : map.values()) { - source.readLater(); - } - } - - /** - * Merge all watermark state in {@code address} across all merging windows in {@code context}, - * where the final merge result window is {@code mergeResult}. - */ - public static void mergeWatermarks( - MergingStateAccessor context, - StateTag> address, - W mergeResult) { - mergeWatermarks( - context.accessInEachMergingWindow(address).values(), context.access(address), mergeResult); - } - - /** - * Merge all watermark state in {@code sources} (which must include {@code result} if non-empty) - * into {@code result}, where the final merge result window is {@code mergeResult}. - */ - public static void mergeWatermarks( - Collection> sources, WatermarkHoldState result, - W resultWindow) { - if (sources.isEmpty()) { - // Nothing to merge. - return; - } - if (sources.size() == 1 && sources.contains(result) - && result.getOutputTimeFn().dependsOnlyOnEarliestInputTimestamp()) { - // Nothing to merge. - return; - } - if (result.getOutputTimeFn().dependsOnlyOnWindow()) { - // Clear sources. - for (WatermarkHoldState source : sources) { - source.clear(); - } - // Update directly from window-derived hold. - Instant hold = result.getOutputTimeFn().assignOutputTime( - BoundedWindow.TIMESTAMP_MIN_VALUE, resultWindow); - checkState(hold.isAfter(BoundedWindow.TIMESTAMP_MIN_VALUE)); - result.add(hold); - } else { - // Prefetch. - List> futures = new ArrayList<>(sources.size()); - for (WatermarkHoldState source : sources) { - futures.add(source); - } - // Read. - List outputTimesToMerge = new ArrayList<>(sources.size()); - for (ReadableState future : futures) { - Instant sourceOutputTime = future.read(); - if (sourceOutputTime != null) { - outputTimesToMerge.add(sourceOutputTime); - } - } - // Clear sources. - for (WatermarkHoldState source : sources) { - source.clear(); - } - if (!outputTimesToMerge.isEmpty()) { - // Merge and update. - result.add(result.getOutputTimeFn().merge(resultWindow, outputTimesToMerge)); - } - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespace.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespace.java deleted file mode 100644 index f972e312f9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespace.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import java.io.IOException; - -/** - * A namespace used for scoping state stored with {@link StateInternals}. - * - *

              Instances of {@code StateNamespace} are guaranteed to have a {@link #hashCode} and - * {@link #equals} that uniquely identify the namespace. - */ -public interface StateNamespace { - - /** - * Return a {@link String} representation of the key. It is guaranteed that this - * {@code String} will uniquely identify the key. - * - *

              This will encode the actual namespace as a {@code String}. It is - * preferable to use the {@code StateNamespace} object when possible. - * - *

              The string produced by the standard implementations will not contain a '+' character. This - * enables adding a '+' between the actual namespace and other information, if needed, to separate - * the two. - */ - String stringKey(); - - /** - * Append the string representation of this key to the {@link Appendable}. - */ - void appendTo(Appendable sb) throws IOException; - - /** - * Return an {@code Object} to use as a key in a cache. - * - *

              Different namespaces may use the same key in order to be treated as a unit in the cache. - * The {@code Object}'s {@code hashCode} and {@code equals} methods will be used to determine - * equality. - */ - Object getCacheKey(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaceForTest.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaceForTest.java deleted file mode 100644 index 09b86d67e9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaceForTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import java.io.IOException; -import java.util.Objects; - -/** - * A simple {@link StateNamespace} used for testing. - */ -public class StateNamespaceForTest implements StateNamespace { - private String key; - - public StateNamespaceForTest(String key) { - this.key = key; - } - - @Override - public String stringKey() { - return key; - } - - @Override - public Object getCacheKey() { - return key; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof StateNamespaceForTest)) { - return false; - } - - return Objects.equals(this.key, ((StateNamespaceForTest) obj).key); - } - - @Override - public int hashCode() { - return key.hashCode(); - } - - @Override - public void appendTo(Appendable sb) throws IOException { - sb.append(key); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaces.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaces.java deleted file mode 100644 index 8fee9959b9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateNamespaces.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.base.Splitter; - -import java.io.IOException; -import java.util.List; -import java.util.Objects; - -/** - * Factory methods for creating the {@link StateNamespace StateNamespaces}. - */ -public class StateNamespaces { - - private enum Namespace { - GLOBAL, - WINDOW, - WINDOW_AND_TRIGGER; - } - - public static StateNamespace global() { - return new GlobalNamespace(); - } - - public static StateNamespace window(Coder windowCoder, W window) { - return new WindowNamespace<>(windowCoder, window); - } - - public static - StateNamespace windowAndTrigger(Coder windowCoder, W window, int triggerIdx) { - return new WindowAndTriggerNamespace<>(windowCoder, window, triggerIdx); - } - - private StateNamespaces() {} - - /** - * {@link StateNamespace} that is global to the current key being processed. - */ - public static class GlobalNamespace implements StateNamespace { - - private static final String GLOBAL_STRING = "/"; - - @Override - public String stringKey() { - return GLOBAL_STRING; - } - - @Override - public Object getCacheKey() { - return GLOBAL_STRING; - } - - @Override - public boolean equals(Object obj) { - return obj == this || obj instanceof GlobalNamespace; - } - - @Override - public int hashCode() { - return Objects.hash(Namespace.GLOBAL); - } - - @Override - public String toString() { - return "Global"; - } - - @Override - public void appendTo(Appendable sb) throws IOException { - sb.append(GLOBAL_STRING); - } - } - - /** - * {@link StateNamespace} that is scoped to a specific window. - */ - public static class WindowNamespace implements StateNamespace { - - private static final String WINDOW_FORMAT = "/%s/"; - - private Coder windowCoder; - private W window; - - private WindowNamespace(Coder windowCoder, W window) { - this.windowCoder = windowCoder; - this.window = window; - } - - public W getWindow() { - return window; - } - - @Override - public String stringKey() { - try { - return String.format(WINDOW_FORMAT, CoderUtils.encodeToBase64(windowCoder, window)); - } catch (CoderException e) { - throw new RuntimeException("Unable to generate string key from window " + window, e); - } - } - - @Override - public void appendTo(Appendable sb) throws IOException { - sb.append('/').append(CoderUtils.encodeToBase64(windowCoder, window)).append('/'); - } - - /** - * State in the same window will all be evicted together. - */ - @Override - public Object getCacheKey() { - return window; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof WindowNamespace)) { - return false; - } - - WindowNamespace that = (WindowNamespace) obj; - return Objects.equals(this.window, that.window); - } - - @Override - public int hashCode() { - return Objects.hash(Namespace.WINDOW, window); - } - - @Override - public String toString() { - return "Window(" + window + ")"; - } - } - - /** - * {@link StateNamespace} that is scoped to a particular window and trigger index. - */ - public static class WindowAndTriggerNamespace - implements StateNamespace { - - private static final String WINDOW_AND_TRIGGER_FORMAT = "/%s/%s/"; - - private static final int TRIGGER_RADIX = 36; - private Coder windowCoder; - private W window; - private int triggerIndex; - - private WindowAndTriggerNamespace(Coder windowCoder, W window, int triggerIndex) { - this.windowCoder = windowCoder; - this.window = window; - this.triggerIndex = triggerIndex; - } - - public W getWindow() { - return window; - } - - public int getTriggerIndex() { - return triggerIndex; - } - - @Override - public String stringKey() { - try { - return String.format(WINDOW_AND_TRIGGER_FORMAT, - CoderUtils.encodeToBase64(windowCoder, window), - // Use base 36 so that can address 36 triggers in a single byte and still be human - // readable. - Integer.toString(triggerIndex, TRIGGER_RADIX).toUpperCase()); - } catch (CoderException e) { - throw new RuntimeException("Unable to generate string key from window " + window, e); - } - } - - @Override - public void appendTo(Appendable sb) throws IOException { - sb.append('/').append(CoderUtils.encodeToBase64(windowCoder, window)); - sb.append('/').append(Integer.toString(triggerIndex, TRIGGER_RADIX).toUpperCase()); - sb.append('/'); - } - - /** - * State in the same window will all be evicted together. - */ - @Override - public Object getCacheKey() { - return window; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof WindowAndTriggerNamespace)) { - return false; - } - - WindowAndTriggerNamespace that = (WindowAndTriggerNamespace) obj; - return this.triggerIndex == that.triggerIndex - && Objects.equals(this.window, that.window); - } - - @Override - public int hashCode() { - return Objects.hash(Namespace.WINDOW_AND_TRIGGER, window, triggerIndex); - } - - @Override - public String toString() { - return "WindowAndTrigger(" + window + "," + triggerIndex + ")"; - } - } - - private static final Splitter SLASH_SPLITTER = Splitter.on('/'); - - /** - * Convert a {@code stringKey} produced using {@link StateNamespace#stringKey} - * on one of the namespaces produced by this class into the original - * {@link StateNamespace}. - */ - public static StateNamespace fromString( - String stringKey, Coder windowCoder) { - if (!stringKey.startsWith("/") || !stringKey.endsWith("/")) { - throw new RuntimeException("Invalid namespace string: '" + stringKey + "'"); - } - - if (GlobalNamespace.GLOBAL_STRING.equals(stringKey)) { - return global(); - } - - List parts = SLASH_SPLITTER.splitToList(stringKey); - if (parts.size() != 3 && parts.size() != 4) { - throw new RuntimeException("Invalid namespace string: '" + stringKey + "'"); - } - // Ends should be empty (we start and end with /) - if (!parts.get(0).isEmpty() || !parts.get(parts.size() - 1).isEmpty()) { - throw new RuntimeException("Invalid namespace string: '" + stringKey + "'"); - } - - try { - W window = CoderUtils.decodeFromBase64(windowCoder, parts.get(1)); - if (parts.size() > 3) { - int index = Integer.parseInt(parts.get(2), WindowAndTriggerNamespace.TRIGGER_RADIX); - return windowAndTrigger(windowCoder, window, index); - } else { - return window(windowCoder, window); - } - } catch (Exception e) { - throw new RuntimeException("Invalid namespace string: '" + stringKey + "'", e); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java deleted file mode 100644 index 9e15e35197..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTable.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.util.state.StateTag.StateBinder; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Table; - -import java.util.Map; -import java.util.Set; - -/** - * Table mapping {@code StateNamespace} and {@code StateTag} to a {@code State} instance. - */ -public abstract class StateTable { - - private final Table, State> stateTable = - HashBasedTable.create(); - - /** - * Gets the {@link State} in the specified {@link StateNamespace} with the specified {@link - * StateTag}, binding it using the {@link #binderForNamespace} if it is not - * already present in this {@link StateTable}. - */ - public StateT get( - StateNamespace namespace, StateTag tag, StateContext c) { - State storage = stateTable.get(namespace, tag); - if (storage != null) { - @SuppressWarnings("unchecked") - StateT typedStorage = (StateT) storage; - return typedStorage; - } - - StateT typedStorage = tag.bind(binderForNamespace(namespace, c)); - stateTable.put(namespace, tag, typedStorage); - return typedStorage; - } - - public void clearNamespace(StateNamespace namespace) { - stateTable.rowKeySet().remove(namespace); - } - - public void clear() { - stateTable.clear(); - } - - public Iterable values() { - return stateTable.values(); - } - - public boolean isNamespaceInUse(StateNamespace namespace) { - return stateTable.containsRow(namespace); - } - - public Map, State> getTagsInUse(StateNamespace namespace) { - return stateTable.row(namespace); - } - - public Set getNamespacesInUse() { - return stateTable.rowKeySet(); - } - - /** - * Provide the {@code StateBinder} to use for creating {@code Storage} instances - * in the specified {@code namespace}. - */ - protected abstract StateBinder binderForNamespace(StateNamespace namespace, StateContext c); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java deleted file mode 100644 index c87bdb788c..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTag.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; - -import java.io.IOException; -import java.io.Serializable; - -/** - * An address for persistent state. This includes a unique identifier for the location, the - * information necessary to encode the value, and details about the intended access pattern. - * - *

              State can be thought of as a sparse table, with each {@code StateTag} defining a column - * that has cells of type {@code StateT}. - * - *

              Currently, this can only be used in a step immediately following a {@link GroupByKey}. - * - * @param The type of key that must be used with the state tag. Contravariant: methods should - * accept values of type {@code KeyedStateTag}. - * @param The type of state being tagged. - */ -@Experimental(Kind.STATE) -public interface StateTag extends Serializable { - - /** - * Visitor for binding a {@link StateTag} and to the associated {@link State}. - * - * @param the type of key this binder embodies. - */ - public interface StateBinder { - ValueState bindValue(StateTag> address, Coder coder); - - BagState bindBag(StateTag> address, Coder elemCoder); - - AccumulatorCombiningState - bindCombiningValue( - StateTag> address, - Coder accumCoder, CombineFn combineFn); - - AccumulatorCombiningState - bindKeyedCombiningValue( - StateTag> address, - Coder accumCoder, KeyedCombineFn combineFn); - - AccumulatorCombiningState - bindKeyedCombiningValueWithContext( - StateTag> address, - Coder accumCoder, - KeyedCombineFnWithContext combineFn); - - /** - * Bind to a watermark {@link StateTag}. - * - *

              This accepts the {@link OutputTimeFn} that dictates how watermark hold timestamps - * added to the returned {@link WatermarkHoldState} are to be combined. - */ - WatermarkHoldState bindWatermark( - StateTag> address, - OutputTimeFn outputTimeFn); - } - - /** Append the UTF-8 encoding of this tag to the given {@link Appendable}. */ - void appendTo(Appendable sb) throws IOException; - - /** - * Returns the user-provided name of this state cell. - */ - String getId(); - - /** - * Use the {@code binder} to create an instance of {@code StateT} appropriate for this address. - */ - StateT bind(StateBinder binder); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java deleted file mode 100644 index ec9a78feab..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/StateTags.java +++ /dev/null @@ -1,579 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.common.base.MoreObjects; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Objects; - -/** - * Static utility methods for creating {@link StateTag} instances. - */ -@Experimental(Kind.STATE) -public class StateTags { - - private static final CoderRegistry STANDARD_REGISTRY = new CoderRegistry(); - - static { - STANDARD_REGISTRY.registerStandardCoders(); - } - - private enum StateKind { - SYSTEM('s'), - USER('u'); - - private char prefix; - - StateKind(char prefix) { - this.prefix = prefix; - } - } - - private StateTags() { } - - private interface SystemStateTag { - StateTag asKind(StateKind kind); - } - - /** - * Create a simple state tag for values of type {@code T}. - */ - public static StateTag> value(String id, Coder valueCoder) { - return new ValueStateTag<>(new StructuredId(id), valueCoder); - } - - /** - * Create a state tag for values that use a {@link CombineFn} to automatically merge - * multiple {@code InputT}s into a single {@code OutputT}. - */ - public static - StateTag> - combiningValue( - String id, Coder accumCoder, CombineFn combineFn) { - return combiningValueInternal(id, accumCoder, combineFn); - } - - /** - * Create a state tag for values that use a {@link KeyedCombineFn} to automatically merge - * multiple {@code InputT}s into a single {@code OutputT}. The key provided to the - * {@link KeyedCombineFn} comes from the keyed {@link StateAccessor}. - */ - public static StateTag> - keyedCombiningValue(String id, Coder accumCoder, - KeyedCombineFn combineFn) { - return keyedCombiningValueInternal(id, accumCoder, combineFn); - } - - /** - * Create a state tag for values that use a {@link KeyedCombineFnWithContext} to automatically - * merge multiple {@code InputT}s into a single {@code OutputT}. The key provided to the - * {@link KeyedCombineFn} comes from the keyed {@link StateAccessor}, the context provided comes - * from the {@link StateContext}. - */ - public static - StateTag> - keyedCombiningValueWithContext( - String id, - Coder accumCoder, - KeyedCombineFnWithContext combineFn) { - return new KeyedCombiningValueWithContextStateTag( - new StructuredId(id), - accumCoder, - combineFn); - } - - /** - * Create a state tag for values that use a {@link CombineFn} to automatically merge - * multiple {@code InputT}s into a single {@code OutputT}. - * - *

              This determines the {@code Coder} from the given {@code Coder}, and - * should only be used to initialize static values. - */ - public static - StateTag> - combiningValueFromInputInternal( - String id, Coder inputCoder, CombineFn combineFn) { - try { - Coder accumCoder = combineFn.getAccumulatorCoder(STANDARD_REGISTRY, inputCoder); - return combiningValueInternal(id, accumCoder, combineFn); - } catch (CannotProvideCoderException e) { - throw new IllegalArgumentException( - "Unable to determine accumulator coder for " + combineFn.getClass().getSimpleName() - + " from " + inputCoder, e); - } - } - - private static StateTag> - combiningValueInternal( - String id, Coder accumCoder, CombineFn combineFn) { - return - new CombiningValueStateTag( - new StructuredId(id), accumCoder, combineFn); - } - - private static - StateTag> keyedCombiningValueInternal( - String id, - Coder accumCoder, - KeyedCombineFn combineFn) { - return new KeyedCombiningValueStateTag( - new StructuredId(id), accumCoder, combineFn); - } - - /** - * Create a state tag that is optimized for adding values frequently, and - * occasionally retrieving all the values that have been added. - */ - public static StateTag> bag(String id, Coder elemCoder) { - return new BagStateTag(new StructuredId(id), elemCoder); - } - - /** - * Create a state tag for holding the watermark. - */ - public static StateTag> - watermarkStateInternal(String id, OutputTimeFn outputTimeFn) { - return new WatermarkStateTagInternal(new StructuredId(id), outputTimeFn); - } - - /** - * Convert an arbitrary {@link StateTag} to a system-internal tag that is guaranteed not to - * collide with any user tags. - */ - public static StateTag makeSystemTagInternal( - StateTag tag) { - if (!(tag instanceof SystemStateTag)) { - throw new IllegalArgumentException("Expected subclass of StateTagBase, got " + tag); - } - // Checked above - @SuppressWarnings("unchecked") - SystemStateTag typedTag = (SystemStateTag) tag; - return typedTag.asKind(StateKind.SYSTEM); - } - - public static StateTag> - convertToBagTagInternal( - StateTag> combiningTag) { - if (combiningTag instanceof KeyedCombiningValueStateTag) { - // Checked above; conversion to a bag tag depends on the provided tag being one of those - // created via the factory methods in this class. - @SuppressWarnings("unchecked") - KeyedCombiningValueStateTag typedTag = - (KeyedCombiningValueStateTag) combiningTag; - return typedTag.asBagTag(); - } else if (combiningTag instanceof KeyedCombiningValueWithContextStateTag) { - @SuppressWarnings("unchecked") - KeyedCombiningValueWithContextStateTag typedTag = - (KeyedCombiningValueWithContextStateTag) combiningTag; - return typedTag.asBagTag(); - } else { - throw new IllegalArgumentException("Unexpected StateTag " + combiningTag); - } - } - - private static class StructuredId implements Serializable { - private final StateKind kind; - private final String rawId; - - private StructuredId(String rawId) { - this(StateKind.USER, rawId); - } - - private StructuredId(StateKind kind, String rawId) { - this.kind = kind; - this.rawId = rawId; - } - - public StructuredId asKind(StateKind kind) { - return new StructuredId(kind, rawId); - } - - public void appendTo(Appendable sb) throws IOException { - sb.append(kind.prefix).append(rawId); - } - - public String getRawId() { - return rawId; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("id", rawId) - .add("kind", kind) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof StructuredId)) { - return false; - } - - StructuredId that = (StructuredId) obj; - return Objects.equals(this.kind, that.kind) - && Objects.equals(this.rawId, that.rawId); - } - - @Override - public int hashCode() { - return Objects.hash(kind, rawId); - } - } - - /** - * A base class that just manages the structured ids. - */ - private abstract static class StateTagBase - implements StateTag, SystemStateTag { - - protected final StructuredId id; - - protected StateTagBase(StructuredId id) { - this.id = id; - } - - @Override - public String getId() { - return id.getRawId(); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("id", id) - .toString(); - } - - @Override - public void appendTo(Appendable sb) throws IOException { - id.appendTo(sb); - } - - @Override - public abstract StateTag asKind(StateKind kind); - } - - /** - * A value state cell for values of type {@code T}. - * - * @param the type of value being stored - */ - private static class ValueStateTag extends StateTagBase> - implements StateTag> { - - private final Coder coder; - - private ValueStateTag(StructuredId id, Coder coder) { - super(id); - this.coder = coder; - } - - @Override - public ValueState bind(StateBinder visitor) { - return visitor.bindValue(this, coder); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof ValueStateTag)) { - return false; - } - - ValueStateTag that = (ValueStateTag) obj; - return Objects.equals(this.id, that.id) - && Objects.equals(this.coder, that.coder); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), id, coder); - } - - @Override - public StateTag> asKind(StateKind kind) { - return new ValueStateTag(id.asKind(kind), coder); - } - } - - /** - * A state cell for values that are combined according to a {@link CombineFn}. - * - * @param the type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - private static class CombiningValueStateTag - extends KeyedCombiningValueStateTag - implements StateTag>, - SystemStateTag> { - - private final Coder accumCoder; - private final CombineFn combineFn; - - private CombiningValueStateTag( - StructuredId id, - Coder accumCoder, CombineFn combineFn) { - super(id, accumCoder, combineFn.asKeyedFn()); - this.combineFn = combineFn; - this.accumCoder = accumCoder; - } - - @Override - public StateTag> - asKind(StateKind kind) { - return new CombiningValueStateTag( - id.asKind(kind), accumCoder, combineFn); - } - } - - /** - * A state cell for values that are combined according to a {@link KeyedCombineFnWithContext}. - * - * @param the type of keys - * @param the type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - private static class KeyedCombiningValueWithContextStateTag - extends StateTagBase> - implements SystemStateTag> { - - private final Coder accumCoder; - private final KeyedCombineFnWithContext combineFn; - - protected KeyedCombiningValueWithContextStateTag( - StructuredId id, - Coder accumCoder, - KeyedCombineFnWithContext combineFn) { - super(id); - this.combineFn = combineFn; - this.accumCoder = accumCoder; - } - - @Override - public AccumulatorCombiningState bind( - StateBinder visitor) { - return visitor.bindKeyedCombiningValueWithContext(this, accumCoder, combineFn); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof KeyedCombiningValueWithContextStateTag)) { - return false; - } - - KeyedCombiningValueWithContextStateTag that = - (KeyedCombiningValueWithContextStateTag) obj; - return Objects.equals(this.id, that.id) - && Objects.equals(this.accumCoder, that.accumCoder); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), id, accumCoder); - } - - @Override - public StateTag> asKind( - StateKind kind) { - return new KeyedCombiningValueWithContextStateTag<>( - id.asKind(kind), accumCoder, combineFn); - } - - private StateTag> asBagTag() { - return new BagStateTag(id, accumCoder); - } - } - - /** - * A state cell for values that are combined according to a {@link KeyedCombineFn}. - * - * @param the type of keys - * @param the type of input values - * @param type of mutable accumulator values - * @param type of output values - */ - private static class KeyedCombiningValueStateTag - extends StateTagBase> - implements SystemStateTag> { - - private final Coder accumCoder; - private final KeyedCombineFn keyedCombineFn; - - protected KeyedCombiningValueStateTag( - StructuredId id, - Coder accumCoder, KeyedCombineFn keyedCombineFn) { - super(id); - this.keyedCombineFn = keyedCombineFn; - this.accumCoder = accumCoder; - } - - @Override - public AccumulatorCombiningState bind( - StateBinder visitor) { - return visitor.bindKeyedCombiningValue(this, accumCoder, keyedCombineFn); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof CombiningValueStateTag)) { - return false; - } - - KeyedCombiningValueStateTag that = (KeyedCombiningValueStateTag) obj; - return Objects.equals(this.id, that.id) - && Objects.equals(this.accumCoder, that.accumCoder); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), id, accumCoder); - } - - @Override - public StateTag> asKind( - StateKind kind) { - return new KeyedCombiningValueStateTag<>(id.asKind(kind), accumCoder, keyedCombineFn); - } - - private StateTag> asBagTag() { - return new BagStateTag(id, accumCoder); - } - } - - /** - * A state cell optimized for bag-like access patterns (frequent additions, occasional reads - * of all the values). - * - * @param the type of value in the bag - */ - private static class BagStateTag extends StateTagBase> - implements StateTag>{ - - private final Coder elemCoder; - - private BagStateTag(StructuredId id, Coder elemCoder) { - super(id); - this.elemCoder = elemCoder; - } - - @Override - public BagState bind(StateBinder visitor) { - return visitor.bindBag(this, elemCoder); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof BagStateTag)) { - return false; - } - - BagStateTag that = (BagStateTag) obj; - return Objects.equals(this.id, that.id) - && Objects.equals(this.elemCoder, that.elemCoder); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), id, elemCoder); - } - - @Override - public StateTag> asKind(StateKind kind) { - return new BagStateTag<>(id.asKind(kind), elemCoder); - } - } - - private static class WatermarkStateTagInternal - extends StateTagBase> { - - /** - * When multiple output times are added to hold the watermark, this determines how they are - * combined, and also the behavior when merging windows. Does not contribute to equality/hash - * since we have at most one watermark hold tag per computation. - */ - private final OutputTimeFn outputTimeFn; - - private WatermarkStateTagInternal(StructuredId id, OutputTimeFn outputTimeFn) { - super(id); - this.outputTimeFn = outputTimeFn; - } - - @Override - public WatermarkHoldState bind(StateBinder visitor) { - return visitor.bindWatermark(this, outputTimeFn); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof WatermarkStateTagInternal)) { - return false; - } - - WatermarkStateTagInternal that = (WatermarkStateTagInternal) obj; - return Objects.equals(this.id, that.id); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), id); - } - - @Override - public StateTag> asKind(StateKind kind) { - return new WatermarkStateTagInternal(id.asKind(kind), outputTimeFn); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java deleted file mode 100644 index 19c12bb164..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/ValueState.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; - -/** - * State holding a single value. - * - * @param The type of values being stored. - */ -@Experimental(Kind.STATE) -public interface ValueState extends ReadableState, State { - /** - * Set the value of the buffer. - */ - void write(T input); - - @Override - ValueState readLater(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkHoldState.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkHoldState.java deleted file mode 100644 index 8a1adc9558..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/state/WatermarkHoldState.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import com.google.cloud.dataflow.sdk.annotations.Experimental; -import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; - -import org.joda.time.Instant; - -/** - * A {@link State} accepting and aggregating output timestamps, which determines - * the time to which the output watermark must be held. - * - *

              For internal use only. This API may change at any time. - */ -@Experimental(Kind.STATE) -public interface WatermarkHoldState - extends CombiningState { - /** - * Return the {@link OutputTimeFn} which will be used to determine a watermark hold time given - * an element timestamp, and to combine watermarks from windows which are about to be merged. - */ - OutputTimeFn getOutputTimeFn(); - - @Override - WatermarkHoldState readLater(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/KV.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/KV.java deleted file mode 100644 index 23cee07cfe..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/KV.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.SerializableComparator; -import com.google.common.base.MoreObjects; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Objects; - -/** - * An immutable key/value pair. - * - *

              Various {@link PTransform PTransforms} like {@link GroupByKey} and {@link Combine#perKey} - * operate on {@link PCollection PCollections} of {@link KV KVs}. - * - * @param the type of the key - * @param the type of the value - */ -public class KV implements Serializable { - /** Returns a {@link KV} with the given key and value. */ - public static KV of(K key, V value) { - return new KV<>(key, value); - } - - /** Returns the key of this {@link KV}. */ - public K getKey() { - return key; - } - - /** Returns the value of this {@link KV}. */ - public V getValue() { - return value; - } - - - ///////////////////////////////////////////////////////////////////////////// - - final K key; - final V value; - - private KV(K key, V value) { - this.key = key; - this.value = value; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof KV)) { - return false; - } - KV otherKv = (KV) other; - // Arrays are very common as values and keys, so deepEquals is mandatory - return Objects.deepEquals(this.key, otherKv.key) - && Objects.deepEquals(this.value, otherKv.value); - } - - /** - * A {@link Comparator} that orders {@link KV KVs} by the natural ordering of their keys. - * - *

              A {@code null} key is less than any non-{@code null} key. - */ - public static class OrderByKey, V> implements - SerializableComparator> { - @Override - public int compare(KV a, KV b) { - if (a.key == null) { - return b.key == null ? 0 : -1; - } else if (b.key == null) { - return 1; - } else { - return a.key.compareTo(b.key); - } - } - } - - /** - * A {@link Comparator} that orders {@link KV KVs} by the natural ordering of their values. - * - *

              A {@code null} value is less than any non-{@code null} value. - */ - public static class OrderByValue> - implements SerializableComparator> { - @Override - public int compare(KV a, KV b) { - if (a.value == null) { - return b.value == null ? 0 : -1; - } else if (b.value == null) { - return 1; - } else { - return a.value.compareTo(b.value); - } - } - } - - @Override - public int hashCode() { - // Objects.deepEquals requires Arrays.deepHashCode for correctness - return Arrays.deepHashCode(new Object[]{key, value}); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .addValue(key) - .addValue(value) - .toString(); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PBegin.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PBegin.java deleted file mode 100644 index 23ac3aed32..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PBegin.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO.Read; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -import java.util.Collection; -import java.util.Collections; - -/** - * {@link PBegin} is the "input" to a root {@link PTransform}, such as {@link Read Read} or - * {@link Create}. - * - *

              Typically created by calling {@link Pipeline#begin} on a Pipeline. - */ -public class PBegin implements PInput { - /** - * Returns a {@link PBegin} in the given {@link Pipeline}. - */ - public static PBegin in(Pipeline pipeline) { - return new PBegin(pipeline); - } - - /** - * Like {@link #apply(String, PTransform)} but defaulting to the name - * of the {@link PTransform}. - */ - public OutputT apply( - PTransform t) { - return Pipeline.applyTransform(this, t); - } - - /** - * Applies the given {@link PTransform} to this input {@link PBegin}, - * using {@code name} to identify this specific application of the transform. - * This name is used in various places, including the monitoring UI, logging, - * and to stably identify this application node in the job graph. - */ - public OutputT apply( - String name, PTransform t) { - return Pipeline.applyTransform(name, this, t); - } - - @Override - public Pipeline getPipeline() { - return pipeline; - } - - @Override - public Collection expand() { - // A PBegin contains no PValues. - return Collections.emptyList(); - } - - @Override - public void finishSpecifying() { - // Nothing more to be done. - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * Constructs a {@link PBegin} in the given {@link Pipeline}. - */ - protected PBegin(Pipeline pipeline) { - this.pipeline = pipeline; - } - - private final Pipeline pipeline; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollection.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollection.java deleted file mode 100644 index 6fffddfeb9..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollection.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; - -/** - * A {@link PCollection PCollection<T>} is an immutable collection of values of type - * {@code T}. A {@link PCollection} can contain either a bounded or unbounded - * number of elements. Bounded and unbounded {@link PCollection PCollections} are produced - * as the output of {@link PTransform PTransforms} - * (including root PTransforms like {@link Read} and {@link Create}), and can - * be passed as the inputs of other PTransforms. - * - *

              Some root transforms produce bounded {@code PCollections} and others - * produce unbounded ones. For example, {@link TextIO.Read} reads a static set - * of files, so it produces a bounded {@link PCollection}. - * {@link PubsubIO.Read}, on the other hand, receives a potentially infinite stream - * of Pubsub messages, so it produces an unbounded {@link PCollection}. - * - *

              Each element in a {@link PCollection} may have an associated implicit - * timestamp. Readers assign timestamps to elements when they create - * {@link PCollection PCollections}, and other {@link PTransform PTransforms} propagate these - * timestamps from their input to their output. For example, {@link PubsubIO.Read} - * assigns pubsub message timestamps to elements, and {@link TextIO.Read} assigns - * the default value {@link BoundedWindow#TIMESTAMP_MIN_VALUE} to elements. User code can - * explicitly assign timestamps to elements with - * {@link com.google.cloud.dataflow.sdk.transforms.DoFn.Context#outputWithTimestamp}. - * - *

              Additionally, a {@link PCollection} has an associated - * {@link WindowFn} and each element is assigned to a set of windows. - * By default, the windowing function is {@link GlobalWindows} - * and all elements are assigned into a single default window. - * This default can be overridden with the {@link Window} - * {@link PTransform}. - * - *

              See the individual {@link PTransform} subclasses for specific information - * on how they propagate timestamps and windowing. - * - * @param the type of the elements of this {@link PCollection} - */ -public class PCollection extends TypedPValue { - - /** - * The enumeration of cases for whether a {@link PCollection} is bounded. - */ - public enum IsBounded { - /** - * Indicates that a {@link PCollection} contains bounded data elements, such as - * {@link PCollection PCollections} from {@link TextIO}, {@link BigQueryIO}, - * {@link Create} e.t.c. - */ - BOUNDED, - /** - * Indicates that a {@link PCollection} contains unbounded data elements, such as - * {@link PCollection PCollections} from {@link PubsubIO}. - */ - UNBOUNDED; - - /** - * Returns the composed IsBounded property. - * - *

              The composed property is {@link #BOUNDED} only if all components are {@link #BOUNDED}. - * Otherwise, it is {@link #UNBOUNDED}. - */ - public IsBounded and(IsBounded that) { - if (this == BOUNDED && that == BOUNDED) { - return BOUNDED; - } else { - return UNBOUNDED; - } - } - } - - /** - * Returns the name of this {@link PCollection}. - * - *

              By default, the name of a {@link PCollection} is based on the name of the - * {@link PTransform} that produces it. It can be specified explicitly by - * calling {@link #setName}. - * - * @throws IllegalStateException if the name hasn't been set yet - */ - @Override - public String getName() { - return super.getName(); - } - - /** - * Sets the name of this {@link PCollection}. Returns {@code this}. - * - * @throws IllegalStateException if this {@link PCollection} has already been - * finalized and may no longer be set. - * Once {@link #apply} has been called, this will be the case. - */ - @Override - public PCollection setName(String name) { - super.setName(name); - return this; - } - - /** - * Returns the {@link Coder} used by this {@link PCollection} to encode and decode - * the values stored in it. - * - * @throws IllegalStateException if the {@link Coder} hasn't been set, and - * couldn't be inferred. - */ - @Override - public Coder getCoder() { - return super.getCoder(); - } - - /** - * Sets the {@link Coder} used by this {@link PCollection} to encode and decode the - * values stored in it. Returns {@code this}. - * - * @throws IllegalStateException if this {@link PCollection} has already - * been finalized and may no longer be set. - * Once {@link #apply} has been called, this will be the case. - */ - @Override - public PCollection setCoder(Coder coder) { - super.setCoder(coder); - return this; - } - - /** - * Like {@link IsBounded#apply(String, PTransform)} but defaulting to the name - * of the {@link PTransform}. - * - * @return the output of the applied {@link PTransform} - */ - public OutputT apply(PTransform, OutputT> t) { - return Pipeline.applyTransform(this, t); - } - - /** - * Applies the given {@link PTransform} to this input {@link PCollection}, - * using {@code name} to identify this specific application of the transform. - * This name is used in various places, including the monitoring UI, logging, - * and to stably identify this application node in the job graph. - * - * @return the output of the applied {@link PTransform} - */ - public OutputT apply( - String name, PTransform, OutputT> t) { - return Pipeline.applyTransform(name, this, t); - } - - /** - * Returns the {@link WindowingStrategy} of this {@link PCollection}. - */ - public WindowingStrategy getWindowingStrategy() { - return windowingStrategy; - } - - public IsBounded isBounded() { - return isBounded; - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal details below here. - - /** - * {@link WindowingStrategy} that will be used for merging windows and triggering output in this - * {@link PCollection} and subsequence {@link PCollection PCollections} produced from this one. - * - *

              By default, no merging is performed. - */ - private WindowingStrategy windowingStrategy; - - private IsBounded isBounded; - - private PCollection(Pipeline p) { - super(p); - } - - /** - * Sets the {@link TypeDescriptor TypeDescriptor<T>} for this - * {@link PCollection PCollection<T>}. This may allow the enclosing - * {@link PCollectionTuple}, {@link PCollectionList}, or {@code PTransform>}, - * etc., to provide more detailed reflective information. - */ - @Override - public PCollection setTypeDescriptorInternal(TypeDescriptor typeDescriptor) { - super.setTypeDescriptorInternal(typeDescriptor); - return this; - } - - /** - * Sets the {@link WindowingStrategy} of this {@link PCollection}. - * - *

              For use by primitive transformations only. - */ - public PCollection setWindowingStrategyInternal(WindowingStrategy windowingStrategy) { - this.windowingStrategy = windowingStrategy; - return this; - } - - /** - * Sets the {@link PCollection.IsBounded} of this {@link PCollection}. - * - *

              For use by internal transformations only. - */ - public PCollection setIsBoundedInternal(IsBounded isBounded) { - this.isBounded = isBounded; - return this; - } - - /** - * Creates and returns a new {@link PCollection} for a primitive output. - * - *

              For use by primitive transformations only. - */ - public static PCollection createPrimitiveOutputInternal( - Pipeline pipeline, - WindowingStrategy windowingStrategy, - IsBounded isBounded) { - return new PCollection(pipeline) - .setWindowingStrategyInternal(windowingStrategy) - .setIsBoundedInternal(isBounded); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionList.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionList.java deleted file mode 100644 index cee25686c3..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionList.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.Partition; -import com.google.common.collect.ImmutableList; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * A {@link PCollectionList PCollectionList<T>} is an immutable list of homogeneously - * typed {@link PCollection PCollection<T>s}. A {@link PCollectionList} is used, for - * instance, as the input to - * {@link Flatten} or the output of {@link Partition}. - * - *

              PCollectionLists can be created and accessed like follows: - *

               {@code
              - * PCollection pc1 = ...;
              - * PCollection pc2 = ...;
              - * PCollection pc3 = ...;
              - *
              - * // Create a PCollectionList with three PCollections:
              - * PCollectionList pcs = PCollectionList.of(pc1).and(pc2).and(pc3);
              - *
              - * // Create an empty PCollectionList:
              - * Pipeline p = ...;
              - * PCollectionList pcs2 = PCollectionList.empty(p);
              - *
              - * // Get PCollections out of a PCollectionList, by index (origin 0):
              - * PCollection pcX = pcs.get(1);
              - * PCollection pcY = pcs.get(0);
              - * PCollection pcZ = pcs.get(2);
              - *
              - * // Get a list of all PCollections in a PCollectionList:
              - * List> allPcs = pcs.getAll();
              - * } 
              - * - * @param the type of the elements of all the {@link PCollection PCollections} in this list - */ -public class PCollectionList implements PInput, POutput { - /** - * Returns an empty {@link PCollectionList} that is part of the given {@link Pipeline}. - * - *

              Longer {@link PCollectionList PCollectionLists} can be created by calling - * {@link #and} on the result. - */ - public static PCollectionList empty(Pipeline pipeline) { - return new PCollectionList<>(pipeline); - } - - /** - * Returns a singleton {@link PCollectionList} containing the given {@link PCollection}. - * - *

              Longer {@link PCollectionList PCollectionLists} can be created by calling - * {@link #and} on the result. - */ - public static PCollectionList of(PCollection pc) { - return new PCollectionList(pc.getPipeline()).and(pc); - } - - /** - * Returns a {@link PCollectionList} containing the given {@link PCollection PCollections}, - * in order. - * - *

              The argument list cannot be empty. - * - *

              All the {@link PCollection PCollections} in the resulting {@link PCollectionList} must be - * part of the same {@link Pipeline}. - * - *

              Longer PCollectionLists can be created by calling - * {@link #and} on the result. - */ - public static PCollectionList of(Iterable> pcs) { - Iterator> pcsIter = pcs.iterator(); - if (!pcsIter.hasNext()) { - throw new IllegalArgumentException( - "must either have a non-empty list of PCollections, " - + "or must first call empty(Pipeline)"); - } - return new PCollectionList(pcsIter.next().getPipeline()).and(pcs); - } - - /** - * Returns a new {@link PCollectionList} that has all the {@link PCollection PCollections} of - * this {@link PCollectionList} plus the given {@link PCollection} appended to the end. - * - *

              All the {@link PCollection PCollections} in the resulting {@link PCollectionList} must be - * part of the same {@link Pipeline}. - */ - public PCollectionList and(PCollection pc) { - if (pc.getPipeline() != pipeline) { - throw new IllegalArgumentException( - "PCollections come from different Pipelines"); - } - return new PCollectionList<>(pipeline, - new ImmutableList.Builder>() - .addAll(pcollections) - .add(pc) - .build()); - } - - /** - * Returns a new {@link PCollectionList} that has all the {@link PCollection PCollections} of - * this {@link PCollectionList} plus the given {@link PCollection PCollections} appended to the - * end, in order. - * - *

              All the {@link PCollections} in the resulting {@link PCollectionList} must be - * part of the same {@link Pipeline}. - */ - public PCollectionList and(Iterable> pcs) { - List> copy = new ArrayList<>(pcollections); - for (PCollection pc : pcs) { - if (pc.getPipeline() != pipeline) { - throw new IllegalArgumentException( - "PCollections come from different Pipelines"); - } - copy.add(pc); - } - return new PCollectionList<>(pipeline, copy); - } - - /** - * Returns the number of {@link PCollection PCollections} in this {@link PCollectionList}. - */ - public int size() { - return pcollections.size(); - } - - /** - * Returns the {@link PCollection} at the given index (origin zero). - * - * @throws IndexOutOfBoundsException if the index is out of the range - * {@code [0..size()-1]}. - */ - public PCollection get(int index) { - return pcollections.get(index); - } - - /** - * Returns an immutable List of all the {@link PCollection PCollections} in this - * {@link PCollectionList}. - */ - public List> getAll() { - return pcollections; - } - - /** - * Like {@link #apply(String, PTransform)} but defaulting to the name - * of the {@code PTransform}. - */ - public OutputT apply( - PTransform, OutputT> t) { - return Pipeline.applyTransform(this, t); - } - - /** - * Applies the given {@link PTransform} to this input {@link PCollectionList}, - * using {@code name} to identify this specific application of the transform. - * This name is used in various places, including the monitoring UI, logging, - * and to stably identify this application node in the job graph. - * - * @return the output of the applied {@link PTransform} - */ - public OutputT apply( - String name, PTransform, OutputT> t) { - return Pipeline.applyTransform(name, this, t); - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal details below here. - - final Pipeline pipeline; - final List> pcollections; - - PCollectionList(Pipeline pipeline) { - this(pipeline, new ArrayList>()); - } - - PCollectionList(Pipeline pipeline, List> pcollections) { - this.pipeline = pipeline; - this.pcollections = Collections.unmodifiableList(pcollections); - } - - @Override - public Pipeline getPipeline() { - return pipeline; - } - - @Override - public Collection expand() { - return pcollections; - } - - @Override - public void recordAsOutput(AppliedPTransform transform) { - int i = 0; - for (PCollection pc : pcollections) { - pc.recordAsOutput(transform, "out" + i); - i++; - } - } - - @Override - public void finishSpecifying() { - for (PCollection pc : pcollections) { - pc.finishSpecifying(); - } - } - - @Override - public void finishSpecifyingOutput() { - for (PCollection pc : pcollections) { - pc.finishSpecifyingOutput(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionTuple.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionTuple.java deleted file mode 100644 index 58550e4182..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionTuple.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.common.collect.ImmutableMap; - -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * A {@link PCollectionTuple} is an immutable tuple of - * heterogeneously-typed {@link PCollection PCollections}, "keyed" by - * {@link TupleTag TupleTags}. A {@link PCollectionTuple} can be used as the input or - * output of a - * {@link PTransform} taking - * or producing multiple PCollection inputs or outputs that can be of - * different types, for instance a - * {@link ParDo} with side - * outputs. - * - *

              A {@link PCollectionTuple} can be created and accessed like follows: - *

               {@code
              - * PCollection pc1 = ...;
              - * PCollection pc2 = ...;
              - * PCollection> pc3 = ...;
              - *
              - * // Create TupleTags for each of the PCollections to put in the
              - * // PCollectionTuple (the type of the TupleTag enables tracking the
              - * // static type of each of the PCollections in the PCollectionTuple):
              - * TupleTag tag1 = new TupleTag<>();
              - * TupleTag tag2 = new TupleTag<>();
              - * TupleTag> tag3 = new TupleTag<>();
              - *
              - * // Create a PCollectionTuple with three PCollections:
              - * PCollectionTuple pcs =
              - *     PCollectionTuple.of(tag1, pc1)
              - *                     .and(tag2, pc2)
              - *                     .and(tag3, pc3);
              - *
              - * // Create an empty PCollectionTuple:
              - * Pipeline p = ...;
              - * PCollectionTuple pcs2 = PCollectionTuple.empty(p);
              - *
              - * // Get PCollections out of a PCollectionTuple, using the same tags
              - * // that were used to put them in:
              - * PCollection pcX = pcs.get(tag2);
              - * PCollection pcY = pcs.get(tag1);
              - * PCollection> pcZ = pcs.get(tag3);
              - *
              - * // Get a map of all PCollections in a PCollectionTuple:
              - * Map, PCollection> allPcs = pcs.getAll();
              - * } 
              - */ -public class PCollectionTuple implements PInput, POutput { - /** - * Returns an empty {@link PCollectionTuple} that is part of the given {@link Pipeline}. - * - *

              A {@link PCollectionTuple} containing additional elements can be created by calling - * {@link #and} on the result. - */ - public static PCollectionTuple empty(Pipeline pipeline) { - return new PCollectionTuple(pipeline); - } - - /** - * Returns a singleton {@link PCollectionTuple} containing the given - * {@link PCollection} keyed by the given {@link TupleTag}. - * - *

              A {@link PCollectionTuple} containing additional elements can be created by calling - * {@link #and} on the result. - */ - public static PCollectionTuple of(TupleTag tag, PCollection pc) { - return empty(pc.getPipeline()).and(tag, pc); - } - - /** - * Returns a new {@link PCollectionTuple} that has each {@link PCollection} and - * {@link TupleTag} of this {@link PCollectionTuple} plus the given {@link PCollection} - * associated with the given {@link TupleTag}. - * - *

              The given {@link TupleTag} should not already be mapped to a - * {@link PCollection} in this {@link PCollectionTuple}. - * - *

              Each {@link PCollection} in the resulting {@link PCollectionTuple} must be - * part of the same {@link Pipeline}. - */ - public PCollectionTuple and(TupleTag tag, PCollection pc) { - if (pc.getPipeline() != pipeline) { - throw new IllegalArgumentException( - "PCollections come from different Pipelines"); - } - - return new PCollectionTuple(pipeline, - new ImmutableMap.Builder, PCollection>() - .putAll(pcollectionMap) - .put(tag, pc) - .build()); - } - - /** - * Returns whether this {@link PCollectionTuple} contains a {@link PCollection} with - * the given tag. - */ - public boolean has(TupleTag tag) { - return pcollectionMap.containsKey(tag); - } - - /** - * Returns the {@link PCollection} associated with the given {@link TupleTag} - * in this {@link PCollectionTuple}. Throws {@link IllegalArgumentException} if there is no - * such {@link PCollection}, i.e., {@code !has(tag)}. - */ - public PCollection get(TupleTag tag) { - @SuppressWarnings("unchecked") - PCollection pcollection = (PCollection) pcollectionMap.get(tag); - if (pcollection == null) { - throw new IllegalArgumentException( - "TupleTag not found in this PCollectionTuple tuple"); - } - return pcollection; - } - - /** - * Returns an immutable Map from {@link TupleTag} to corresponding - * {@link PCollection}, for all the members of this {@link PCollectionTuple}. - */ - public Map, PCollection> getAll() { - return pcollectionMap; - } - - /** - * Like {@link #apply(String, PTransform)} but defaulting to the name - * of the {@link PTransform}. - * - * @return the output of the applied {@link PTransform} - */ - public OutputT apply( - PTransform t) { - return Pipeline.applyTransform(this, t); - } - - /** - * Applies the given {@link PTransform} to this input {@link PCollectionTuple}, - * using {@code name} to identify this specific application of the transform. - * This name is used in various places, including the monitoring UI, logging, - * and to stably identify this application node in the job graph. - * - * @return the output of the applied {@link PTransform} - */ - public OutputT apply( - String name, PTransform t) { - return Pipeline.applyTransform(name, this, t); - } - - - ///////////////////////////////////////////////////////////////////////////// - // Internal details below here. - - Pipeline pipeline; - final Map, PCollection> pcollectionMap; - - PCollectionTuple(Pipeline pipeline) { - this(pipeline, new LinkedHashMap, PCollection>()); - } - - PCollectionTuple(Pipeline pipeline, - Map, PCollection> pcollectionMap) { - this.pipeline = pipeline; - this.pcollectionMap = Collections.unmodifiableMap(pcollectionMap); - } - - /** - * Returns a {@link PCollectionTuple} with each of the given tags mapping to a new - * output {@link PCollection}. - * - *

              For use by primitive transformations only. - */ - public static PCollectionTuple ofPrimitiveOutputsInternal( - Pipeline pipeline, - TupleTagList outputTags, - WindowingStrategy windowingStrategy, - IsBounded isBounded) { - Map, PCollection> pcollectionMap = new LinkedHashMap<>(); - for (TupleTag outputTag : outputTags.tupleTags) { - if (pcollectionMap.containsKey(outputTag)) { - throw new IllegalArgumentException( - "TupleTag already present in this tuple"); - } - - // In fact, `token` and `outputCollection` should have - // types TypeDescriptor and PCollection for some - // unknown T. It is safe to create `outputCollection` - // with type PCollection because it has the same - // erasure as the correct type. When a transform adds - // elements to `outputCollection` they will be of type T. - @SuppressWarnings("unchecked") - TypeDescriptor token = (TypeDescriptor) outputTag.getTypeDescriptor(); - PCollection outputCollection = PCollection - .createPrimitiveOutputInternal(pipeline, windowingStrategy, isBounded) - .setTypeDescriptorInternal(token); - - pcollectionMap.put(outputTag, outputCollection); - } - return new PCollectionTuple(pipeline, pcollectionMap); - } - - @Override - public Pipeline getPipeline() { - return pipeline; - } - - @Override - public Collection expand() { - return pcollectionMap.values(); - } - - @Override - public void recordAsOutput(AppliedPTransform transform) { - int i = 0; - for (Map.Entry, PCollection> entry - : pcollectionMap.entrySet()) { - TupleTag tag = entry.getKey(); - PCollection pc = entry.getValue(); - pc.recordAsOutput(transform, tag.getOutName(i)); - i++; - } - } - - @Override - public void finishSpecifying() { - for (PCollection pc : pcollectionMap.values()) { - pc.finishSpecifying(); - } - } - - @Override - public void finishSpecifyingOutput() { - for (PCollection pc : pcollectionMap.values()) { - pc.finishSpecifyingOutput(); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionView.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionView.java deleted file mode 100644 index 50f945b881..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollectionView.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; - -import java.io.Serializable; - -/** - * A {@link PCollectionView PCollectionView<T>} is an immutable view of a {@link PCollection} - * as a value of type {@code T} that can be accessed - * as a side input to a {@link ParDo} transform. - * - *

              A {@link PCollectionView} should always be the output of a - * {@link com.google.cloud.dataflow.sdk.transforms.PTransform}. It is the joint responsibility of - * this transform and each {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} to implement - * the view in a runner-specific manner. - * - *

              The most common case is using the {@link View} transforms to prepare a {@link PCollection} - * for use as a side input to {@link ParDo}. See {@link View#asSingleton()}, - * {@link View#asIterable()}, and {@link View#asMap()} for more detail on specific views - * available in the SDK. - * - * @param the type of the value(s) accessible via this {@link PCollectionView} - */ -public interface PCollectionView extends PValue, Serializable { - /** - * A unique identifier, for internal use. - */ - TupleTag>> getTagInternal(); - - /** - * For internal use only. - */ - T fromIterableInternal(Iterable> contents); - - /** - * For internal use only. - */ - WindowingStrategy getWindowingStrategyInternal(); - - /** - * For internal use only. - */ - Coder>> getCoderInternal(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PDone.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PDone.java deleted file mode 100644 index 39a00616bf..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PDone.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -import java.util.Collection; -import java.util.Collections; - -/** - * {@link PDone} is the output of a {@link PTransform} that has a trivial result, - * such as a {@link Write}. - */ -public class PDone extends POutputValueBase { - - /** - * Creates a {@link PDone} in the given {@link Pipeline}. - */ - public static PDone in(Pipeline pipeline) { - return new PDone(pipeline); - } - - @Override - public Collection expand() { - // A PDone contains no PValues. - return Collections.emptyList(); - } - - private PDone(Pipeline pipeline) { - super(pipeline); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java deleted file mode 100644 index 77afe9d378..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PInput.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; - -import java.util.Collection; - -/** - * The interface for things that might be input to a - * {@link com.google.cloud.dataflow.sdk.transforms.PTransform}. - */ -public interface PInput { - /** - * Returns the owning {@link Pipeline} of this {@link PInput}. - */ - Pipeline getPipeline(); - - /** - * Expands this {@link PInput} into a list of its component output - * {@link PValue PValues}. - * - *

                - *
              • A {@link PValue} expands to itself.
              • - *
              • A tuple or list of {@link PValue PValues} (such as - * {@link PCollectionTuple} or {@link PCollectionList}) - * expands to its component {@code PValue PValues}.
              • - *
              - * - *

              Not intended to be invoked directly by user code. - */ - Collection expand(); - - /** - * After building, finalizes this {@code PInput} to make it ready for - * being used as an input to a {@link com.google.cloud.dataflow.sdk.transforms.PTransform}. - * - *

              Automatically invoked whenever {@code apply()} is invoked on - * this {@code PInput}, so users do not normally call this explicitly. - */ - void finishSpecifying(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutput.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutput.java deleted file mode 100644 index 057b849e52..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutput.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -import java.util.Collection; - -/** - * The interface for things that might be output from a {@link PTransform}. - */ -public interface POutput { - - /** - * Returns the owning {@link Pipeline} of this {@link POutput}. - */ - Pipeline getPipeline(); - - /** - * Expands this {@link POutput} into a list of its component output - * {@link PValue PValues}. - * - *

                - *
              • A {@link PValue} expands to itself.
              • - *
              • A tuple or list of {@link PValue PValues} (such as - * {@link PCollectionTuple} or {@link PCollectionList}) - * expands to its component {@code PValue PValues}.
              • - *
              - * - *

              Not intended to be invoked directly by user code. - */ - Collection expand(); - - /** - * Records that this {@code POutput} is an output of the given - * {@code PTransform}. - * - *

              For a compound {@code POutput}, it is advised to call - * this method on each component {@code POutput}. - * - *

              This is not intended to be invoked by user code, but - * is automatically invoked as part of applying the - * producing {@link PTransform}. - */ - void recordAsOutput(AppliedPTransform transform); - - /** - * As part of applying the producing {@link PTransform}, finalizes this - * output to make it ready for being used as an input and for running. - * - *

              This includes ensuring that all {@link PCollection PCollections} - * have {@link Coder Coders} specified or defaulted. - * - *

              Automatically invoked whenever this {@link POutput} is used - * as a {@link PInput} to another {@link PTransform}, or if never - * used as a {@link PInput}, when {@link Pipeline#run} - * is called, so users do not normally call this explicitly. - */ - void finishSpecifyingOutput(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutputValueBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutputValueBase.java deleted file mode 100644 index 69e04c3436..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/POutputValueBase.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -/** - * A {@link POutputValueBase} is the abstract base class of - * {@code PTransform} outputs. - * - *

              A {@link PValueBase} that adds tracking of its producing - * {@link AppliedPTransform}. - * - *

              For internal use. - */ -public abstract class POutputValueBase implements POutput { - - private final Pipeline pipeline; - - protected POutputValueBase(Pipeline pipeline) { - this.pipeline = pipeline; - } - - /** - * No-arg constructor for Java serialization only. - * The resulting {@link POutputValueBase} is unlikely to be - * valid. - */ - protected POutputValueBase() { - pipeline = null; - } - - @Override - public Pipeline getPipeline() { - return pipeline; - } - - /** - * Returns the {@link AppliedPTransform} that this {@link POutputValueBase} - * is an output of. - * - *

              For internal use only. - */ - public AppliedPTransform getProducingTransformInternal() { - return producingTransform; - } - - /** - * Records that this {@link POutputValueBase} is an output with the - * given name of the given {@link AppliedPTransform}. - * - *

              To be invoked only by {@link POutput#recordAsOutput} - * implementations. Not to be invoked directly by user code. - */ - @Override - public void recordAsOutput(AppliedPTransform transform) { - if (producingTransform != null) { - // Already used this POutput as a PTransform output. This can - // happen if the POutput is an output of a transform within a - // composite transform, and is also the result of the composite. - // We want to record the "immediate" atomic transform producing - // this output, and ignore all later composite transforms that - // also produce this output. - // - // Pipeline.applyInternal() uses !hasProducingTransform() to - // avoid calling this operation redundantly, but - // hasProducingTransform() doesn't apply to POutputValueBases - // that aren't PValues or composites of PValues, e.g., PDone. - return; - } - producingTransform = transform; - } - - /** - * Default behavior for {@link #finishSpecifyingOutput()} is - * to do nothing. Override if your {@link PValue} requires - * finalization. - */ - @Override - public void finishSpecifyingOutput() { } - - /** - * The {@link PTransform} that produces this {@link POutputValueBase}. - */ - private AppliedPTransform producingTransform; -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValue.java deleted file mode 100644 index b97f7874e0..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValue.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -/** - * The interface for values that can be input to and output from {@link PTransform PTransforms}. - */ -public interface PValue extends POutput, PInput { - - /** - * Returns the name of this {@link PValue}. - */ - String getName(); - - /** - * Returns the {@link AppliedPTransform} that this {@link PValue} is an output of. - * - *

              For internal use only. - */ - AppliedPTransform getProducingTransformInternal(); -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValueBase.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValueBase.java deleted file mode 100644 index 7e57204f33..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PValueBase.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.util.StringUtils; - -import java.util.Collection; -import java.util.Collections; - -/** - * A {@link PValueBase} is an abstract base class that provides - * sensible default implementations for methods of {@link PValue}. - * In particular, this includes functionality for getting/setting: - * - *

                - *
              • The {@link Pipeline} that the {@link PValue} is part of.
              • - *
              • Whether the {@link PValue} has bee finalized (as an input - * or an output), after which its properties can no longer be changed.
              • - *
              - * - *

              For internal use. - */ -public abstract class PValueBase extends POutputValueBase implements PValue { - /** - * Returns the name of this {@link PValueBase}. - * - *

              By default, the name of a {@link PValueBase} is based on the - * name of the {@link PTransform} that produces it. It can be - * specified explicitly by calling {@link #setName}. - * - * @throws IllegalStateException if the name hasn't been set yet - */ - @Override - public String getName() { - if (name == null) { - throw new IllegalStateException("name not set"); - } - return name; - } - - /** - * Sets the name of this {@link PValueBase}. Returns {@code this}. - * - * @throws IllegalStateException if this {@link PValueBase} has - * already been finalized and may no longer be set. - */ - public PValueBase setName(String name) { - if (finishedSpecifying) { - throw new IllegalStateException( - "cannot change the name of " + this + " once it's been used"); - } - this.name = name; - return this; - } - - ///////////////////////////////////////////////////////////////////////////// - - protected PValueBase(Pipeline pipeline) { - super(pipeline); - } - - /** - * No-arg constructor for Java serialization only. - * The resulting {@link PValueBase} is unlikely to be - * valid. - */ - protected PValueBase() { - super(); - } - - /** - * The name of this {@link PValueBase}, or null if not yet set. - */ - private String name; - - /** - * Whether this {@link PValueBase} has been finalized, and its core - * properties, e.g., name, can no longer be changed. - */ - private boolean finishedSpecifying = false; - - @Override - public void recordAsOutput(AppliedPTransform transform) { - recordAsOutput(transform, "out"); - } - - /** - * Records that this {@link POutputValueBase} is an output with the - * given name of the given {@link AppliedPTransform} in the given - * {@link Pipeline}. - * - *

              To be invoked only by {@link POutput#recordAsOutput} - * implementations. Not to be invoked directly by user code. - */ - protected void recordAsOutput(AppliedPTransform transform, - String outName) { - super.recordAsOutput(transform); - if (name == null) { - name = transform.getFullName() + "." + outName; - } - } - - /** - * Returns whether this {@link PValueBase} has been finalized, and - * its core properties, e.g., name, can no longer be changed. - * - *

              For internal use only. - */ - public boolean isFinishedSpecifyingInternal() { - return finishedSpecifying; - } - - @Override - public Collection expand() { - return Collections.singletonList(this); - } - - @Override - public void finishSpecifying() { - finishSpecifyingOutput(); - finishedSpecifying = true; - } - - @Override - public String toString() { - return (name == null ? "" : getName()) - + " [" + getKindString() + "]"; - } - - /** - * Returns a {@link String} capturing the kind of this - * {@link PValueBase}. - * - *

              By default, uses the base name of the current class as its kind string. - */ - protected String getKindString() { - return StringUtils.approximateSimpleName(getClass()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TimestampedValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TimestampedValue.java deleted file mode 100644 index 1085d44b13..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TimestampedValue.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.util.PropertyNames; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -/** - * An immutable pair of a value and a timestamp. - * - *

              The timestamp of a value determines many properties, such as its assignment to - * windows and whether the value is late (with respect to the watermark of a {@link PCollection}). - * - * @param the type of the value - */ -public class TimestampedValue { - - /** - * Returns a new {@code TimestampedValue} with the given value and timestamp. - */ - public static TimestampedValue of(V value, Instant timestamp) { - return new TimestampedValue<>(value, timestamp); - } - - public V getValue() { - return value; - } - - public Instant getTimestamp() { - return timestamp; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof TimestampedValue)) { - return false; - } - TimestampedValue that = (TimestampedValue) other; - return Objects.equals(value, that.value) && Objects.equals(timestamp, that.timestamp); - } - - @Override - public int hashCode() { - return Objects.hash(value, timestamp); - } - - @Override - public String toString() { - return "TimestampedValue(" + value + ", " + timestamp + ")"; - } - - ///////////////////////////////////////////////////////////////////////////// - - /** - * A {@link Coder} for {@link TimestampedValue}. - */ - public static class TimestampedValueCoder - extends StandardCoder> { - - private final Coder valueCoder; - - public static TimestampedValueCoder of(Coder valueCoder) { - return new TimestampedValueCoder<>(valueCoder); - } - - @JsonCreator - public static TimestampedValueCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List components) { - checkArgument(components.size() == 1, - "Expecting 1 component, got " + components.size()); - return of((Coder) components.get(0)); - } - - @SuppressWarnings("unchecked") - TimestampedValueCoder(Coder valueCoder) { - this.valueCoder = checkNotNull(valueCoder); - } - - @Override - public void encode(TimestampedValue windowedElem, - OutputStream outStream, - Context context) - throws IOException { - valueCoder.encode(windowedElem.getValue(), outStream, context.nested()); - InstantCoder.of().encode( - windowedElem.getTimestamp(), outStream, context); - } - - @Override - public TimestampedValue decode(InputStream inStream, Context context) - throws IOException { - T value = valueCoder.decode(inStream, context.nested()); - Instant timestamp = InstantCoder.of().decode(inStream, context); - return TimestampedValue.of(value, timestamp); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - verifyDeterministic( - "TimestampedValueCoder requires a deterministic valueCoder", - valueCoder); - } - - @Override - public List> getCoderArguments() { - return Arrays.>asList(valueCoder); - } - - public static List getInstanceComponents(TimestampedValue exampleValue) { - return Arrays.asList(exampleValue.getValue()); - } - } - - ///////////////////////////////////////////////////////////////////////////// - - private final V value; - private final Instant timestamp; - - protected TimestampedValue(V value, Instant timestamp) { - this.value = value; - this.timestamp = timestamp; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTag.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTag.java deleted file mode 100644 index 7494921132..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTag.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multiset; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; -import java.util.Random; - -/** - * A {@link TupleTag} is a typed tag to use as the key of a - * heterogeneously typed tuple, like {@link PCollectionTuple}. - * Its generic type parameter allows tracking - * the static type of things stored in tuples. - * - *

              To aid in assigning default {@link Coder Coders} for results of - * side outputs of {@link ParDo}, an output - * {@link TupleTag} should be instantiated with an extra {@code {}} so - * it is an instance of an anonymous subclass without generic type - * parameters. Input {@link TupleTag TupleTags} require no such extra - * instantiation (although it doesn't hurt). For example: - * - *

               {@code
              - * TupleTag inputTag = new TupleTag<>();
              - * TupleTag outputTag = new TupleTag(){};
              - * } 
              - * - * @param the type of the elements or values of the tagged thing, - * e.g., a {@code PCollection}. - */ -public class TupleTag implements Serializable { - /** - * Constructs a new {@code TupleTag}, with a fresh unique id. - * - *

              This is the normal way {@code TupleTag}s are constructed. - */ - public TupleTag() { - this(genId(), true); - } - - /** - * Constructs a new {@code TupleTag} with the given id. - * - *

              It is up to the user to ensure that two {@code TupleTag}s - * with the same id actually mean the same tag and carry the same - * generic type parameter. Violating this invariant can lead to - * hard-to-diagnose runtime type errors. Consequently, this - * operation should be used very sparingly, such as when the - * producer and consumer of {@code TupleTag}s are written in - * separate modules and can only coordinate via ids rather than - * shared {@code TupleTag} instances. Most of the time, - * {@link #TupleTag()} should be preferred. - */ - public TupleTag(String id) { - this(id, false); - } - - /** - * Returns the id of this {@code TupleTag}. - * - *

              Two {@code TupleTag}s with the same id are considered equal. - * - *

              {@code TupleTag}s are not ordered, i.e., the class does not implement - * Comparable interface. TupleTags implement equals and hashCode, making them - * suitable for use as keys in HashMap and HashSet. - */ - public String getId() { - return id; - } - - /** - * If this {@code TupleTag} is tagging output {@code outputIndex} of - * a {@code PTransform}, returns the name that should be used by - * default for the output. - */ - public String getOutName(int outIndex) { - if (generated) { - return "out" + outIndex; - } else { - return id; - } - } - - /** - * Returns a {@code TypeDescriptor} capturing what is known statically - * about the type of this {@code TupleTag} instance's most-derived - * class. - * - *

              This is useful for a {@code TupleTag} constructed as an - * instance of an anonymous subclass with a trailing {@code {}}, - * e.g., {@code new TupleTag(){}}. - */ - public TypeDescriptor getTypeDescriptor() { - return new TypeDescriptor(getClass()) {}; - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal details below here. - - static final Random RANDOM = new Random(0); - private static final Multiset staticInits = HashMultiset.create(); - - final String id; - final boolean generated; - - /** Generates and returns a fresh unique id for a TupleTag's id. */ - static synchronized String genId() { - // It is a common pattern to store tags that are shared between the main - // program and workers in static variables, but such references are not - // serialized as part of the *Fns state. Fortunately, most such tags - // are constructed in static class initializers, e.g. - // - // static final TupleTag MY_TAG = new TupleTag<>(); - // - // and class initialization order is well defined by the JVM spec, so in - // this case we can assign deterministic ids. - StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - for (StackTraceElement frame : stackTrace) { - if (frame.getMethodName().equals("")) { - int counter = staticInits.add(frame.getClassName(), 1); - return frame.getClassName() + "#" + counter; - } - } - // Otherwise, assume it'll be serialized and choose a random value to reduce - // the chance of collision. - String nonce = Long.toHexString(RANDOM.nextLong()); - // [Thread.getStackTrace, TupleTag.getId, TupleTag., caller, ...] - String caller = stackTrace.length >= 4 - ? stackTrace[3].getClassName() + "." + stackTrace[3].getMethodName() - + ":" + stackTrace[3].getLineNumber() - : "unknown"; - return caller + "#" + nonce; - } - - @JsonCreator - @SuppressWarnings("unused") - private static TupleTag fromJson( - @JsonProperty(PropertyNames.VALUE) String id, - @JsonProperty(PropertyNames.IS_GENERATED) boolean generated) { - return new TupleTag<>(id, generated); - } - - private TupleTag(String id, boolean generated) { - this.id = id; - this.generated = generated; - } - - public CloudObject asCloudObject() { - CloudObject result = CloudObject.forClass(getClass()); - addString(result, PropertyNames.VALUE, id); - addBoolean(result, PropertyNames.IS_GENERATED, generated); - return result; - } - - @Override - public boolean equals(Object that) { - if (that instanceof TupleTag) { - return this.id.equals(((TupleTag) that).id); - } else { - return false; - } - } - - @Override - public int hashCode() { - return id.hashCode(); - } - - @Override - public String toString() { - return "Tag<" + id + ">"; - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTagList.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTagList.java deleted file mode 100644 index f019fc26e4..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TupleTagList.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.common.collect.ImmutableList; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * A {@link TupleTagList} is an immutable list of heterogeneously - * typed {@link TupleTag TupleTags}. A {@link TupleTagList} is used, for instance, to - * specify the tags of the side outputs of a - * {@link ParDo}. - * - *

              A {@link TupleTagList} can be created and accessed like follows: - *

               {@code
              - * TupleTag tag1 = ...;
              - * TupleTag tag2 = ...;
              - * TupleTag> tag3 = ...;
              - *
              - * // Create a TupleTagList with three TupleTags:
              - * TupleTagList tags = TupleTagList.of(tag1).and(tag2).and(tag3);
              - *
              - * // Create an empty TupleTagList:
              - * Pipeline p = ...;
              - * TupleTagList tags2 = TupleTagList.empty(p);
              - *
              - * // Get TupleTags out of a TupleTagList, by index (origin 0):
              - * TupleTag tagX = tags.get(1);
              - * TupleTag tagY = tags.get(0);
              - * TupleTag tagZ = tags.get(2);
              - *
              - * // Get a list of all TupleTags in a TupleTagList:
              - * List> allTags = tags.getAll();
              - * } 
              - */ -public class TupleTagList implements Serializable { - /** - * Returns an empty {@link TupleTagList}. - * - *

              Longer {@link TupleTagList TupleTagLists} can be created by calling - * {@link #and} on the result. - */ - public static TupleTagList empty() { - return new TupleTagList(); - } - - /** - * Returns a singleton {@link TupleTagList} containing the given {@link TupleTag}. - * - *

              Longer {@link TupleTagList TupleTagLists} can be created by calling - * {@link #and} on the result. - */ - public static TupleTagList of(TupleTag tag) { - return empty().and(tag); - } - - /** - * Returns a {@link TupleTagList} containing the given {@link TupleTag TupleTags}, in order. - * - *

              Longer {@link TupleTagList TupleTagLists} can be created by calling - * {@link #and} on the result. - */ - public static TupleTagList of(List> tags) { - return empty().and(tags); - } - - /** - * Returns a new {@link TupleTagList} that has all the {@link TupleTag TupleTags} of - * this {@link TupleTagList} plus the given {@link TupleTag} appended to the end. - */ - public TupleTagList and(TupleTag tag) { - return new TupleTagList( - new ImmutableList.Builder>() - .addAll(tupleTags) - .add(tag) - .build()); - } - - /** - * Returns a new {@link TupleTagList} that has all the {@link TupleTag TupleTags} of - * this {@link TupleTagList} plus the given {@link TupleTag TupleTags} appended to the end, - * in order. - */ - public TupleTagList and(List> tags) { - return new TupleTagList( - new ImmutableList.Builder>() - .addAll(tupleTags) - .addAll(tags) - .build()); - } - - /** - * Returns the number of TupleTags in this TupleTagList. - */ - public int size() { - return tupleTags.size(); - } - - /** - * Returns the {@link TupleTag} at the given index (origin zero). - * - * @throws IndexOutOfBoundsException if the index is out of the range - * {@code [0..size()-1]}. - */ - public TupleTag get(int index) { - return tupleTags.get(index); - } - - /** - * Returns an immutable List of all the {@link TupleTag TupleTags} in this {@link TupleTagList}. - */ - public List> getAll() { - return tupleTags; - } - - - ///////////////////////////////////////////////////////////////////////////// - // Internal details below here. - - final List> tupleTags; - - TupleTagList() { - this(new ArrayList>()); - } - - TupleTagList(List> tupleTags) { - this.tupleTags = Collections.unmodifiableList(tupleTags); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java deleted file mode 100644 index 559d67ce05..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypeDescriptor.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.common.collect.Lists; -import com.google.common.reflect.Invokable; -import com.google.common.reflect.Parameter; -import com.google.common.reflect.TypeToken; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * A description of a Java type, including actual generic parameters where possible. - * - *

              To prevent losing actual type arguments due to erasure, create an anonymous subclass - * with concrete types: - *

              - * {@code
              - * TypeDecriptor> = new TypeDescriptor>() {};
              - * }
              - * 
              - * - *

              If the above were not an anonymous subclass, the type {@code List} - * would be erased and unavailable at run time. - * - * @param the type represented by this {@link TypeDescriptor} - */ -public abstract class TypeDescriptor implements Serializable { - - // This class is just a wrapper for TypeToken - private final TypeToken token; - - /** - * Creates a {@link TypeDescriptor} wrapping the provided token. - * This constructor is private so Guava types do not leak. - */ - private TypeDescriptor(TypeToken token) { - this.token = token; - } - - /** - * Creates a {@link TypeDescriptor} representing - * the type parameter {@code T}. To use this constructor - * properly, the type parameter must be a concrete type, for example - * {@code new TypeDescriptor>(){}}. - */ - protected TypeDescriptor() { - token = new TypeToken(getClass()) {}; - } - - /** - * Creates a {@link TypeDescriptor} representing the type parameter {@code T}, which should - * resolve to a concrete type in the context of the class {@code clazz}. - * - *

              Unlike {@link TypeDescriptor#TypeDescriptor(Class)} this will also use context's of the - * enclosing instances while attempting to resolve the type. This means that the types of any - * classes instantiated in the concrete instance should be resolvable. - */ - protected TypeDescriptor(Object instance) { - TypeToken unresolvedToken = new TypeToken(getClass()) {}; - - // While we haven't fully resolved the parameters, refine it using the captured - // enclosing instance of the object. - unresolvedToken = TypeToken.of(instance.getClass()).resolveType(unresolvedToken.getType()); - - if (hasUnresolvedParameters(unresolvedToken.getType())) { - for (Field field : instance.getClass().getDeclaredFields()) { - Object fieldInstance = getEnclosingInstance(field, instance); - if (fieldInstance != null) { - unresolvedToken = - TypeToken.of(fieldInstance.getClass()).resolveType(unresolvedToken.getType()); - if (!hasUnresolvedParameters(unresolvedToken.getType())) { - break; - } - } - } - } - - // Once we've either fully resolved the parameters or exhausted enclosing instances, we have - // the best approximation to the token we can get. - @SuppressWarnings("unchecked") - TypeToken typedToken = (TypeToken) unresolvedToken; - token = typedToken; - } - - private boolean hasUnresolvedParameters(Type type) { - if (type instanceof TypeVariable) { - return true; - } else if (type instanceof ParameterizedType) { - ParameterizedType param = (ParameterizedType) type; - for (Type arg : param.getActualTypeArguments()) { - if (hasUnresolvedParameters(arg)) { - return true; - } - } - } - return false; - } - - /** - * Returns the enclosing instance if the field is synthetic and it is able to access it, or - * {@literal null} if not. - */ - @Nullable - private Object getEnclosingInstance(Field field, Object instance) { - if (!field.isSynthetic()) { - return null; - } - - boolean accessible = field.isAccessible(); - try { - field.setAccessible(true); - return field.get(instance); - } catch (IllegalArgumentException | IllegalAccessException e) { - // If we fail to get the enclosing instance field, do nothing. In the worst case, we won't - // refine the type based on information in this enclosing class -- that is consistent with - // previous behavior and is still a correct answer that can be fixed by returning the correct - // type descriptor. - return null; - } finally { - field.setAccessible(accessible); - } - } - - /** - * Creates a {@link TypeDescriptor} representing the type parameter - * {@code T}, which should resolve to a concrete type in the context - * of the class {@code clazz}. - */ - @SuppressWarnings("unchecked") - protected TypeDescriptor(Class clazz) { - TypeToken unresolvedToken = new TypeToken(getClass()) {}; - token = (TypeToken) TypeToken.of(clazz).resolveType(unresolvedToken.getType()); - } - - /** - * Returns a {@link TypeDescriptor} representing the given type. - */ - public static TypeDescriptor of(Class type) { - return new SimpleTypeDescriptor<>(TypeToken.of(type)); - } - - /** - * Returns a {@link TypeDescriptor} representing the given type. - */ - @SuppressWarnings("unchecked") - public static TypeDescriptor of(Type type) { - return new SimpleTypeDescriptor<>((TypeToken) TypeToken.of(type)); - } - - /** - * Returns the {@link Type} represented by this {@link TypeDescriptor}. - */ - public Type getType() { - return token.getType(); - } - - /** - * Returns the {@link Class} underlying the {@link Type} represented by - * this {@link TypeDescriptor}. - */ - public Class getRawType() { - return token.getRawType(); - } - - /** - * Returns the component type if this type is an array type, - * otherwise returns {@code null}. - */ - public TypeDescriptor getComponentType() { - return new SimpleTypeDescriptor<>(token.getComponentType()); - } - - /** - * Returns the generic form of a supertype. - */ - public final TypeDescriptor getSupertype(Class superclass) { - return new SimpleTypeDescriptor<>(token.getSupertype(superclass)); - } - - /** - * Returns true if this type is known to be an array type. - */ - public final boolean isArray() { - return token.isArray(); - } - - /** - * Returns a {@link TypeVariable} for the named type parameter. Throws - * {@link IllegalArgumentException} if a type variable by the requested type parameter is not - * found. - * - *

              For example, {@code new TypeDescriptor(){}.getTypeParameter("T")} returns a - * {@code TypeVariable} representing the formal type parameter {@code T}. - * - *

              Do not mistake the type parameters (formal type argument list) with the actual - * type arguments. For example, if a class {@code Foo} extends {@code List}, it - * does not make sense to ask for a type parameter, because {@code Foo} does not have any. - */ - public final TypeVariable> getTypeParameter(String paramName) { - // Cannot convert TypeVariable>[] to TypeVariable>[] - // due to how they are used here, so the result of getTypeParameters() cannot be used - // without upcast. - Class rawType = getRawType(); - for (TypeVariable param : rawType.getTypeParameters()) { - if (param.getName().equals(paramName)) { - @SuppressWarnings("unchecked") - TypeVariable> typedParam = (TypeVariable>) param; - return typedParam; - } - } - throw new IllegalArgumentException( - "No type parameter named " + paramName + " found on " + getRawType()); - } - - /** - * Returns true if this type is assignable from the given type. - */ - public final boolean isSupertypeOf(TypeDescriptor source) { - return token.isSupertypeOf(source.token); - } - - /** - * Return true if this type is a subtype of the given type. - */ - public final boolean isSubtypeOf(TypeDescriptor parent) { - return token.isSubtypeOf(parent.token); - } - - /** - * Returns a list of argument types for the given method, which must - * be a part of the class. - */ - public List> getArgumentTypes(Method method) { - Invokable typedMethod = token.method(method); - - List> argTypes = Lists.newArrayList(); - for (Parameter parameter : typedMethod.getParameters()) { - argTypes.add(new SimpleTypeDescriptor<>(parameter.getType())); - } - return argTypes; - } - - /** - * Returns a {@link TypeDescriptor} representing the given - * type, with type variables resolved according to the specialization - * in this type. - * - *

              For example, consider the following class: - *

              -   * {@code
              -   * class MyList implements List { ... }
              -   * }
              -   * 
              - * - *

              The {@link TypeDescriptor} returned by - *

              -   * {@code
              -   * TypeDescriptor.of(MyList.class)
              -   *     .resolveType(Mylist.class.getMethod("get", int.class).getGenericReturnType)
              -   * }
              -   * 
              - * will represent the type {@code String}. - */ - public TypeDescriptor resolveType(Type type) { - return new SimpleTypeDescriptor<>(token.resolveType(type)); - } - - /** - * Returns a set of {@link TypeDescriptor}s, one for each - * interface implemented by this class. - */ - @SuppressWarnings("rawtypes") - public Iterable getInterfaces() { - List interfaces = Lists.newArrayList(); - for (TypeToken interfaceToken : token.getTypes().interfaces()) { - interfaces.add(new SimpleTypeDescriptor<>(interfaceToken)); - } - return interfaces; - } - - /** - * Returns a set of {@link TypeDescriptor}s, one for each - * superclass (including this class). - */ - @SuppressWarnings("rawtypes") - public Iterable getClasses() { - List classes = Lists.newArrayList(); - for (TypeToken classToken : token.getTypes().classes()) { - classes.add(new SimpleTypeDescriptor<>(classToken)); - } - return classes; - } - - @Override - public String toString() { - return token.toString(); - } - - /** - * Two type descriptor are equal if and only if they - * represent the same type. - */ - @Override - public boolean equals(Object other) { - if (!(other instanceof TypeDescriptor)) { - return false; - } else { - @SuppressWarnings("unchecked") - TypeDescriptor descriptor = (TypeDescriptor) other; - return token.equals(descriptor.token); - } - } - - @Override - public int hashCode() { - return token.hashCode(); - } - - /** - * A non-abstract {@link TypeDescriptor} for construction directly from an existing - * {@link TypeToken}. - */ - private static final class SimpleTypeDescriptor extends TypeDescriptor { - SimpleTypeDescriptor(TypeToken typeToken) { - super(typeToken); - } - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypedPValue.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypedPValue.java deleted file mode 100644 index 29fd639409..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TypedPValue.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException.ReasonCode; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; - -/** - * A {@link TypedPValue TypedPValue<T>} is the abstract base class of things that - * store some number of values of type {@code T}. - * - *

              Because we know the type {@code T}, this is the layer of the inheritance hierarchy where - * we store a coder for objects of type {@code T}. - * - * @param the type of the values stored in this {@link TypedPValue} - */ -public abstract class TypedPValue extends PValueBase implements PValue { - - /** - * Returns the {@link Coder} used by this {@link TypedPValue} to encode and decode - * the values stored in it. - * - * @throws IllegalStateException if the {@link Coder} hasn't been set, and - * couldn't be inferred. - */ - public Coder getCoder() { - if (coder == null) { - coder = inferCoderOrFail(); - } - return coder; - } - - /** - * Sets the {@link Coder} used by this {@link TypedPValue} to encode and decode the - * values stored in it. Returns {@code this}. - * - * @throws IllegalStateException if this {@link TypedPValue} has already - * been finalized and is no longer settable, e.g., by having - * {@code apply()} called on it - */ - public TypedPValue setCoder(Coder coder) { - if (isFinishedSpecifyingInternal()) { - throw new IllegalStateException( - "cannot change the Coder of " + this + " once it's been used"); - } - if (coder == null) { - throw new IllegalArgumentException( - "Cannot setCoder(null)"); - } - this.coder = coder; - return this; - } - - /** - * After building, finalizes this {@link PValue} to make it ready for - * running. Automatically invoked whenever the {@link PValue} is "used" - * (e.g., when apply() is called on it) and when the Pipeline is - * run (useful if this is a {@link PValue} with no consumers). - */ - @Override - public void finishSpecifying() { - if (isFinishedSpecifyingInternal()) { - return; - } - super.finishSpecifying(); - // Ensure that this TypedPValue has a coder by inferring the coder if none exists; If not, - // this will throw an exception. - getCoder(); - } - - ///////////////////////////////////////////////////////////////////////////// - // Internal details below here. - - /** - * The {@link Coder} used by this {@link TypedPValue} to encode and decode the - * values stored in it, or null if not specified nor inferred yet. - */ - private Coder coder; - - protected TypedPValue(Pipeline p) { - super(p); - } - - private TypeDescriptor typeDescriptor; - - /** - * Returns a {@link TypeDescriptor TypeDescriptor<T>} with some reflective information - * about {@code T}, if possible. May return {@code null} if no information - * is available. Subclasses may override this to enable better - * {@code Coder} inference. - */ - public TypeDescriptor getTypeDescriptor() { - return typeDescriptor; - } - - /** - * Sets the {@link TypeDescriptor TypeDescriptor<T>} associated with this class. Better - * reflective type information will lead to better {@link Coder} - * inference. - */ - public TypedPValue setTypeDescriptorInternal(TypeDescriptor typeDescriptor) { - this.typeDescriptor = typeDescriptor; - return this; - } - - /** - * If the coder is not explicitly set, this sets the coder for - * this {@link TypedPValue} to the best coder that can be inferred - * based upon the known {@link TypeDescriptor}. By default, this is null, - * but can and should be improved by subclasses. - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - private Coder inferCoderOrFail() { - // First option for a coder: use the Coder set on this PValue. - if (coder != null) { - return coder; - } - - AppliedPTransform application = getProducingTransformInternal(); - - // Second option for a coder: Look in the coder registry. - CoderRegistry registry = getPipeline().getCoderRegistry(); - TypeDescriptor token = getTypeDescriptor(); - CannotProvideCoderException inferFromTokenException = null; - if (token != null) { - try { - return registry.getDefaultCoder(token); - } catch (CannotProvideCoderException exc) { - inferFromTokenException = exc; - // Attempt to detect when the token came from a TupleTag used for a ParDo side output, - // and provide a better error message if so. Unfortunately, this information is not - // directly available from the TypeDescriptor, so infer based on the type of the PTransform - // and the error message itself. - if (application.getTransform() instanceof ParDo.BoundMulti - && exc.getReason() == ReasonCode.TYPE_ERASURE) { - inferFromTokenException = new CannotProvideCoderException(exc.getMessage() - + " If this error occurs for a side output of the producing ParDo, verify that the " - + "TupleTag for this output is constructed with proper type information (see " - + "TupleTag Javadoc) or explicitly set the Coder to use if this is not possible."); - } - } - } - - // Third option for a coder: use the default Coder from the producing PTransform. - CannotProvideCoderException inputCoderException; - try { - return ((PTransform) application.getTransform()).getDefaultOutputCoder( - application.getInput(), this); - } catch (CannotProvideCoderException exc) { - inputCoderException = exc; - } - - // Build up the error message and list of causes. - StringBuilder messageBuilder = new StringBuilder() - .append("Unable to return a default Coder for ").append(this) - .append(". Correct one of the following root causes:"); - - // No exception, but give the user a message about .setCoder() has not been called. - messageBuilder.append("\n No Coder has been manually specified; ") - .append(" you may do so using .setCoder()."); - - if (inferFromTokenException != null) { - messageBuilder - .append("\n Inferring a Coder from the CoderRegistry failed: ") - .append(inferFromTokenException.getMessage()); - } - - if (inputCoderException != null) { - messageBuilder - .append("\n Using the default output Coder from the producing PTransform failed: ") - .append(inputCoderException.getMessage()); - } - - // Build and throw the exception. - throw new IllegalStateException(messageBuilder.toString()); - } -} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/package-info.java deleted file mode 100644 index b8ca756f0a..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/package-info.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/** - * Defines {@link com.google.cloud.dataflow.sdk.values.PCollection} and other classes for - * representing data in a {@link com.google.cloud.dataflow.sdk.Pipeline}. - * - *

              In particular, see these collection abstractions: - * - *

                - *
              • {@link com.google.cloud.dataflow.sdk.values.PCollection} - an immutable collection of - * values of type {@code T} and the main representation for data in Dataflow.
              • - *
              • {@link com.google.cloud.dataflow.sdk.values.PCollectionView} - an immutable view of a - * {@link com.google.cloud.dataflow.sdk.values.PCollection} that can be accessed as a - * side input of a {@link com.google.cloud.dataflow.sdk.transforms.ParDo} - * {@link com.google.cloud.dataflow.sdk.transforms.PTransform}.
              • - *
              • {@link com.google.cloud.dataflow.sdk.values.PCollectionTuple} - a heterogeneous tuple of - * {@link com.google.cloud.dataflow.sdk.values.PCollection PCollections} - * used in cases where a {@link com.google.cloud.dataflow.sdk.transforms.PTransform} takes - * or returns multiple - * {@link com.google.cloud.dataflow.sdk.values.PCollection PCollections}.
              • - *
              • {@link com.google.cloud.dataflow.sdk.values.PCollectionList} - a homogeneous list of - * {@link com.google.cloud.dataflow.sdk.values.PCollection PCollections} used, for example, - * as input to {@link com.google.cloud.dataflow.sdk.transforms.Flatten}.
              • - *
              - * - *

              And these classes for individual values play particular roles in Dataflow: - * - *

                - *
              • {@link com.google.cloud.dataflow.sdk.values.KV} - a key/value pair that is used by - * keyed transforms, most notably {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}. - *
              • - *
              • {@link com.google.cloud.dataflow.sdk.values.TimestampedValue} - a timestamp/value pair - * that is used for windowing and handling out-of-order data in streaming execution.
              • - *
              - * - *

              For further details, see the documentation for each class in this package. - */ -package com.google.cloud.dataflow.sdk.values; diff --git a/sdk/src/main/proto/README.md b/sdk/src/main/proto/README.md deleted file mode 100644 index fa4e925c98..0000000000 --- a/sdk/src/main/proto/README.md +++ /dev/null @@ -1,27 +0,0 @@ -## Protocol Buffers in Google Cloud Dataflow - -This directory contains the Protocol Buffer messages used in Google Cloud -Dataflow. - -They aren't, however, used during the Maven build process, and are included here -for completeness only. Instead, the following artifact on Maven Central contains -the binary version of the generated code from these Protocol Buffers: - - - com.google.cloud.dataflow - google-cloud-dataflow-java-proto-library-all - LATEST - - -Please follow this process for testing changes: - -* Make changes to the Protocol Buffer messages in this directory. -* Use `protoc` to generate the new code, and compile it into a new Java library. -* Install that Java library into your local Maven repository. -* Update SDK's `pom.xml` to pick up the newly installed library, instead of -downloading it from Maven Central. - -Once the changes are ready for submission, please separate them into two -commits. The first commit should update the Protocol Buffer messages only. After -that, we need to update the generated artifact on Maven Central. Finally, -changes that make use of the Protocol Buffer changes may be committed. diff --git a/sdk/src/main/proto/proto2_coder_test_messages.proto b/sdk/src/main/proto/proto2_coder_test_messages.proto deleted file mode 100644 index eb3c3dfa9b..0000000000 --- a/sdk/src/main/proto/proto2_coder_test_messages.proto +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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. - */ - -/* - * Protocol Buffer messages used for testing Proto2Coder implementation. - */ - -syntax = "proto2"; - -package proto2_coder_test_messages; - -option java_package = "com.google.cloud.dataflow.sdk.coders"; - -message MessageA { - optional string field1 = 1; - repeated MessageB field2 = 2; -} - -message MessageB { - optional bool field1 = 1; -} - -message MessageC { - extensions 100 to 105; -} - -extend MessageC { - optional MessageA field1 = 101; - optional MessageB field2 = 102; -} - -message MessageWithMap { - map field1 = 1; -} - -message ReferencesMessageWithMap { - repeated MessageWithMap field1 = 1; -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/DataflowMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/DataflowMatchers.java deleted file mode 100644 index ad21072dc4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/DataflowMatchers.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import com.google.protobuf.ByteString; - -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; - -import java.io.Serializable; - -/** - * Matchers that are useful when writing Dataflow tests. - */ -public class DataflowMatchers { - /** - * Matcher for {@link ByteString} that prints the strings in UTF8. - */ - public static class ByteStringMatcher extends TypeSafeMatcher - implements Serializable { - private ByteString expected; - private ByteStringMatcher(ByteString expected) { - this.expected = expected; - } - - public static ByteStringMatcher byteStringEq(ByteString expected) { - return new ByteStringMatcher(expected); - } - - @Override - public void describeTo(Description description) { - description - .appendText("ByteString(") - .appendText(expected.toStringUtf8()) - .appendText(")"); - } - - @Override - public void describeMismatchSafely(ByteString actual, Description description) { - description - .appendText("was ByteString(") - .appendText(actual.toStringUtf8()) - .appendText(")"); - } - - @Override - protected boolean matchesSafely(ByteString actual) { - return actual.equals(expected); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java deleted file mode 100644 index abb52b9993..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ImmutableList; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for Pipeline. - */ -@RunWith(JUnit4.class) -public class PipelineTest { - - @Rule public ExpectedLogs logged = ExpectedLogs.none(Pipeline.class); - @Rule public ExpectedException thrown = ExpectedException.none(); - - static class PipelineWrapper extends Pipeline { - protected PipelineWrapper(PipelineRunner runner) { - super(runner, PipelineOptionsFactory.create()); - } - } - - // Mock class that throws a user code exception during the call to - // Pipeline.run(). - static class TestPipelineRunnerThrowingUserException - extends PipelineRunner { - @Override - public PipelineResult run(Pipeline pipeline) { - Throwable t = new IllegalStateException("user code exception"); - throw UserCodeException.wrap(t); - } - } - - // Mock class that throws an SDK or API client code exception during - // the call to Pipeline.run(). - static class TestPipelineRunnerThrowingSDKException - extends PipelineRunner { - @Override - public PipelineResult run(Pipeline pipeline) { - throw new IllegalStateException("SDK exception"); - } - } - - @Test - public void testPipelineUserExceptionHandling() { - Pipeline p = new PipelineWrapper( - new TestPipelineRunnerThrowingUserException()); - - // Check pipeline runner correctly catches user errors. - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalStateException.class)); - thrown.expectMessage("user code exception"); - p.run(); - } - - @Test - public void testPipelineSDKExceptionHandling() { - Pipeline p = new PipelineWrapper(new TestPipelineRunnerThrowingSDKException()); - - // Check pipeline runner correctly catches SDK errors. - try { - p.run(); - fail("Should have thrown an exception."); - } catch (RuntimeException exn) { - // Make sure the exception isn't a UserCodeException. - Assert.assertThat(exn, not(instanceOf(UserCodeException.class))); - // Assert that the message is correct. - Assert.assertThat(exn.getMessage(), containsString("SDK exception")); - // RuntimeException should be IllegalStateException. - Assert.assertThat(exn, instanceOf(IllegalStateException.class)); - } - } - - @Test - @Category(RunnableOnService.class) - public void testMultipleApply() { - PTransform, PCollection> myTransform = - addSuffix("+"); - - Pipeline p = TestPipeline.create(); - PCollection input = p.apply(Create.of(ImmutableList.of("a", "b"))); - - PCollection left = input.apply("Left1", myTransform).apply("Left2", myTransform); - PCollection right = input.apply("Right", myTransform); - - PCollection both = PCollectionList.of(left).and(right) - .apply(Flatten.pCollections()); - - DataflowAssert.that(both).containsInAnyOrder("a++", "b++", "a+", "b+"); - - p.run(); - } - - private static PTransform, PCollection> addSuffix( - final String suffix) { - return ParDo.of(new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) { - c.output(c.element() + suffix); - } - }); - } - - @Test - public void testToString() { - PipelineOptions options = PipelineOptionsFactory.as(PipelineOptions.class); - options.setRunner(DirectPipelineRunner.class); - Pipeline pipeline = Pipeline.create(options); - assertEquals("Pipeline#" + pipeline.hashCode(), pipeline.toString()); - } - - @Test - public void testStableUniqueNameOff() { - Pipeline p = TestPipeline.create(); - p.getOptions().setStableUniqueNames(CheckEnabled.OFF); - - p.apply(Create.of(5, 6, 7)); - p.apply(Create.of(5, 6, 7)); - - logged.verifyNotLogged("does not have a stable unique name."); - } - - @Test - public void testStableUniqueNameWarning() { - Pipeline p = TestPipeline.create(); - p.getOptions().setStableUniqueNames(CheckEnabled.WARNING); - - p.apply(Create.of(5, 6, 7)); - p.apply(Create.of(5, 6, 7)); - - logged.verifyWarn("does not have a stable unique name."); - } - - @Test - public void testStableUniqueNameError() { - Pipeline p = TestPipeline.create(); - p.getOptions().setStableUniqueNames(CheckEnabled.ERROR); - - p.apply(Create.of(5, 6, 7)); - - thrown.expectMessage("does not have a stable unique name."); - p.apply(Create.of(5, 6, 7)); - } - - /** - * Tests that Pipeline supports a pass-through identity function. - */ - @Test - @Category(RunnableOnService.class) - public void testIdentityTransform() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.of(1, 2, 3, 4)) - .apply("IdentityTransform", new IdentityTransform>()); - - DataflowAssert.that(output).containsInAnyOrder(1, 2, 3, 4); - pipeline.run(); - } - - private static class IdentityTransform - extends PTransform { - @Override - public T apply(T input) { - return input; - } - } - - /** - * Tests that Pipeline supports pulling an element out of a tuple as a transform. - */ - @Test - @Category(RunnableOnService.class) - public void testTupleProjectionTransform() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection input = pipeline - .apply(Create.of(1, 2, 3, 4)); - - TupleTag tag = new TupleTag(); - PCollectionTuple tuple = PCollectionTuple.of(tag, input); - - PCollection output = tuple - .apply("ProjectTag", new TupleProjectionTransform(tag)); - - DataflowAssert.that(output).containsInAnyOrder(1, 2, 3, 4); - pipeline.run(); - } - - private static class TupleProjectionTransform - extends PTransform> { - private TupleTag tag; - - public TupleProjectionTransform(TupleTag tag) { - this.tag = tag; - } - - @Override - public PCollection apply(PCollectionTuple input) { - return input.get(tag); - } - } - - /** - * Tests that Pipeline supports putting an element into a tuple as a transform. - */ - @Test - @Category(RunnableOnService.class) - public void testTupleInjectionTransform() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection input = pipeline - .apply(Create.of(1, 2, 3, 4)); - - TupleTag tag = new TupleTag(); - - PCollectionTuple output = input - .apply("ProjectTag", new TupleInjectionTransform(tag)); - - DataflowAssert.that(output.get(tag)).containsInAnyOrder(1, 2, 3, 4); - pipeline.run(); - } - - private static class TupleInjectionTransform - extends PTransform, PCollectionTuple> { - private TupleTag tag; - - public TupleInjectionTransform(TupleTag tag) { - this.tag = tag; - } - - @Override - public PCollectionTuple apply(PCollection input) { - return PCollectionTuple.of(tag, input); - } - } - - /** - * Tests that an empty pipeline runs. - */ - @Test - public void testEmptyPipeline() throws Exception { - Pipeline pipeline = TestPipeline.create(); - pipeline.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/TestUtils.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/TestUtils.java deleted file mode 100644 index 257ecbbd4e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/TestUtils.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.hamcrest.CoreMatchers; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Utilities for tests. - */ -public class TestUtils { - // Do not instantiate. - private TestUtils() {} - - public static final String[] NO_LINES_ARRAY = new String[] { }; - - public static final List NO_LINES = Arrays.asList(NO_LINES_ARRAY); - - public static final String[] LINES_ARRAY = new String[] { - "To be, or not to be: that is the question: ", - "Whether 'tis nobler in the mind to suffer ", - "The slings and arrows of outrageous fortune, ", - "Or to take arms against a sea of troubles, ", - "And by opposing end them? To die: to sleep; ", - "No more; and by a sleep to say we end ", - "The heart-ache and the thousand natural shocks ", - "That flesh is heir to, 'tis a consummation ", - "Devoutly to be wish'd. To die, to sleep; ", - "To sleep: perchance to dream: ay, there's the rub; ", - "For in that sleep of death what dreams may come ", - "When we have shuffled off this mortal coil, ", - "Must give us pause: there's the respect ", - "That makes calamity of so long life; ", - "For who would bear the whips and scorns of time, ", - "The oppressor's wrong, the proud man's contumely, ", - "The pangs of despised love, the law's delay, ", - "The insolence of office and the spurns ", - "That patient merit of the unworthy takes, ", - "When he himself might his quietus make ", - "With a bare bodkin? who would fardels bear, ", - "To grunt and sweat under a weary life, ", - "But that the dread of something after death, ", - "The undiscover'd country from whose bourn ", - "No traveller returns, puzzles the will ", - "And makes us rather bear those ills we have ", - "Than fly to others that we know not of? ", - "Thus conscience does make cowards of us all; ", - "And thus the native hue of resolution ", - "Is sicklied o'er with the pale cast of thought, ", - "And enterprises of great pith and moment ", - "With this regard their currents turn awry, ", - "And lose the name of action.--Soft you now! ", - "The fair Ophelia! Nymph, in thy orisons ", - "Be all my sins remember'd." }; - - public static final List LINES = Arrays.asList(LINES_ARRAY); - - public static final String[] LINES2_ARRAY = new String[] { - "hi", "there", "bob!" }; - - public static final List LINES2 = Arrays.asList(LINES2_ARRAY); - - public static final Integer[] NO_INTS_ARRAY = new Integer[] { }; - - public static final List NO_INTS = Arrays.asList(NO_INTS_ARRAY); - - public static final Integer[] INTS_ARRAY = new Integer[] { - 3, 42, Integer.MAX_VALUE, 0, -1, Integer.MIN_VALUE, 666 }; - - public static final List INTS = Arrays.asList(INTS_ARRAY); - - /** - * Matcher for KVs. - */ - public static class KvMatcher - extends TypeSafeMatcher> { - final Matcher keyMatcher; - final Matcher valueMatcher; - - public static KvMatcher isKv(Matcher keyMatcher, - Matcher valueMatcher) { - return new KvMatcher<>(keyMatcher, valueMatcher); - } - - public KvMatcher(Matcher keyMatcher, - Matcher valueMatcher) { - this.keyMatcher = keyMatcher; - this.valueMatcher = valueMatcher; - } - - @Override - public boolean matchesSafely(KV kv) { - return keyMatcher.matches(kv.getKey()) - && valueMatcher.matches(kv.getValue()); - } - - @Override - public void describeTo(Description description) { - description - .appendText("a KV(").appendValue(keyMatcher) - .appendText(", ").appendValue(valueMatcher) - .appendText(")"); - } - } - - //////////////////////////////////////////////////////////////////////////// - // Utilities for testing CombineFns, ensuring they give correct results - // across various permutations and shardings of the input. - - public static void checkCombineFn( - CombineFn fn, List input, final OutputT expected) { - checkCombineFn(fn, input, CoreMatchers.is(expected)); - } - - public static void checkCombineFn( - CombineFn fn, List input, Matcher matcher) { - checkCombineFnInternal(fn, input, matcher); - Collections.shuffle(input); - checkCombineFnInternal(fn, input, matcher); - } - - private static void checkCombineFnInternal( - CombineFn fn, List input, Matcher matcher) { - int size = input.size(); - checkCombineFnShards(fn, Collections.singletonList(input), matcher); - checkCombineFnShards(fn, shardEvenly(input, 2), matcher); - if (size > 4) { - checkCombineFnShards(fn, shardEvenly(input, size / 2), matcher); - checkCombineFnShards( - fn, shardEvenly(input, (int) (size / Math.sqrt(size))), matcher); - } - checkCombineFnShards(fn, shardExponentially(input, 1.4), matcher); - checkCombineFnShards(fn, shardExponentially(input, 2), matcher); - checkCombineFnShards(fn, shardExponentially(input, Math.E), matcher); - } - - public static void checkCombineFnShards( - CombineFn fn, - List> shards, - Matcher matcher) { - checkCombineFnShardsInternal(fn, shards, matcher); - Collections.shuffle(shards); - checkCombineFnShardsInternal(fn, shards, matcher); - } - - private static void checkCombineFnShardsInternal( - CombineFn fn, - Iterable> shards, - Matcher matcher) { - List accumulators = new ArrayList<>(); - int maybeCompact = 0; - for (Iterable shard : shards) { - AccumT accumulator = fn.createAccumulator(); - for (InputT elem : shard) { - accumulator = fn.addInput(accumulator, elem); - } - if (maybeCompact++ % 2 == 0) { - accumulator = fn.compact(accumulator); - } - accumulators.add(accumulator); - } - AccumT merged = fn.mergeAccumulators(accumulators); - assertThat(fn.extractOutput(merged), matcher); - } - - private static List> shardEvenly(List input, int numShards) { - List> shards = new ArrayList<>(numShards); - for (int i = 0; i < numShards; i++) { - shards.add(input.subList(i * input.size() / numShards, - (i + 1) * input.size() / numShards)); - } - return shards; - } - - private static List> shardExponentially( - List input, double base) { - assert base > 1.0; - List> shards = new ArrayList<>(); - int end = input.size(); - while (end > 0) { - int start = (int) (end / base); - shards.add(input.subList(start, end)); - end = start; - } - return shards; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java deleted file mode 100644 index 97b3756d3e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/WindowMatchers.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowedValue; - -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeMatcher; -import org.joda.time.Instant; - -import java.util.Collection; -import java.util.Objects; - -/** - * Matchers that are useful for working with Windowing, Timestamps, etc. - */ -public class WindowMatchers { - - public static Matcher> isWindowedValue( - Matcher valueMatcher, Matcher timestampMatcher, - Matcher> windowsMatcher) { - return new WindowedValueMatcher<>(valueMatcher, timestampMatcher, windowsMatcher); - } - - public static Matcher> isWindowedValue( - Matcher valueMatcher, Matcher timestampMatcher) { - return new WindowedValueMatcher<>(valueMatcher, timestampMatcher, Matchers.anything()); - } - - public static Matcher> isWindowedValue( - Matcher valueMatcher) { - return new WindowedValueMatcher<>(valueMatcher, Matchers.anything(), Matchers.anything()); - } - - public static Matcher> isSingleWindowedValue( - T value, long timestamp, long windowStart, long windowEnd) { - return WindowMatchers.isSingleWindowedValue( - Matchers.equalTo(value), timestamp, windowStart, windowEnd); - } - - public static Matcher> isSingleWindowedValue( - Matcher valueMatcher, long timestamp, long windowStart, long windowEnd) { - IntervalWindow intervalWindow = - new IntervalWindow(new Instant(windowStart), new Instant(windowEnd)); - return WindowMatchers.isSingleWindowedValue( - valueMatcher, - Matchers.describedAs("%0", Matchers.equalTo(new Instant(timestamp)), timestamp), - Matchers.equalTo(intervalWindow)); - } - - public static Matcher> isSingleWindowedValue( - Matcher valueMatcher, Matcher timestampMatcher, - Matcher windowMatcher) { - return new WindowedValueMatcher( - valueMatcher, timestampMatcher, Matchers.contains(windowMatcher)); - } - - public static Matcher intervalWindow(long start, long end) { - return Matchers.equalTo(new IntervalWindow(new Instant(start), new Instant(end))); - } - - public static Matcher> valueWithPaneInfo(final PaneInfo paneInfo) { - return new TypeSafeMatcher>() { - @Override - public void describeTo(Description description) { - description - .appendText("WindowedValue(paneInfo = ").appendValue(paneInfo).appendText(")"); - } - - @Override - protected boolean matchesSafely(WindowedValue item) { - return Objects.equals(item.getPane(), paneInfo); - } - - @Override - protected void describeMismatchSafely( - WindowedValue item, Description mismatchDescription) { - mismatchDescription.appendValue(item.getPane()); - } - }; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @SafeVarargs - public static final Matcher> ofWindows( - Matcher... windows) { - return (Matcher) Matchers.containsInAnyOrder(windows); - } - - private WindowMatchers() {} - - private static class WindowedValueMatcher extends TypeSafeMatcher> { - - private Matcher valueMatcher; - private Matcher timestampMatcher; - private Matcher> windowsMatcher; - - private WindowedValueMatcher( - Matcher valueMatcher, - Matcher timestampMatcher, - Matcher> windowsMatcher) { - this.valueMatcher = valueMatcher; - this.timestampMatcher = timestampMatcher; - this.windowsMatcher = windowsMatcher; - } - - @Override - public void describeTo(Description description) { - description - .appendText("a WindowedValue(").appendValue(valueMatcher) - .appendText(", ").appendValue(timestampMatcher) - .appendText(", ").appendValue(windowsMatcher) - .appendText(")"); - } - - @Override - protected boolean matchesSafely(WindowedValue windowedValue) { - return valueMatcher.matches(windowedValue.getValue()) - && timestampMatcher.matches(windowedValue.getTimestamp()) - && windowsMatcher.matches(windowedValue.getWindows()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java deleted file mode 100644 index 3ed055bc4a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java +++ /dev/null @@ -1,754 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.apache.avro.AvroTypeException; -import org.apache.avro.Schema; -import org.apache.avro.SchemaBuilder; -import org.apache.avro.generic.GenericData; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.reflect.AvroName; -import org.apache.avro.reflect.AvroSchema; -import org.apache.avro.reflect.Nullable; -import org.apache.avro.reflect.ReflectData; -import org.apache.avro.reflect.Stringable; -import org.apache.avro.reflect.Union; -import org.apache.avro.specific.SpecificData; -import org.apache.avro.util.Utf8; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -/** Tests for {@link AvroCoder}. */ -@RunWith(JUnit4.class) -public class AvroCoderTest { - - @DefaultCoder(AvroCoder.class) - private static class Pojo { - public String text; - public int count; - - // Empty constructor required for Avro decoding. - @SuppressWarnings("unused") - public Pojo() { - } - - public Pojo(String text, int count) { - this.text = text; - this.count = count; - } - - // auto-generated - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Pojo pojo = (Pojo) o; - - if (count != pojo.count) { - return false; - } - if (text != null - ? !text.equals(pojo.text) - : pojo.text != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public String toString() { - return "Pojo{" - + "text='" + text + '\'' - + ", count=" + count - + '}'; - } - } - - private static class GetTextFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().text); - } - } - - @Test - public void testAvroCoderEncoding() throws Exception { - AvroCoder coder = AvroCoder.of(Pojo.class); - CloudObject encoding = coder.asCloudObject(); - - Assert.assertThat(encoding.keySet(), - Matchers.containsInAnyOrder("@type", "type", "schema", "encoding_id")); - } - - @Test - public void testPojoEncoding() throws Exception { - Pojo value = new Pojo("Hello", 42); - AvroCoder coder = AvroCoder.of(Pojo.class); - - CoderProperties.coderDecodeEncodeEqual(coder, value); - } - - @Test - public void testPojoEncodingId() throws Exception { - AvroCoder coder = AvroCoder.of(Pojo.class); - CoderProperties.coderHasEncodingId(coder, Pojo.class.getName()); - } - - @Test - public void testGenericRecordEncoding() throws Exception { - String schemaString = - "{\"namespace\": \"example.avro\",\n" - + " \"type\": \"record\",\n" - + " \"name\": \"User\",\n" - + " \"fields\": [\n" - + " {\"name\": \"name\", \"type\": \"string\"},\n" - + " {\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]},\n" - + " {\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]}\n" - + " ]\n" - + "}"; - Schema schema = (new Schema.Parser()).parse(schemaString); - - GenericRecord before = new GenericData.Record(schema); - before.put("name", "Bob"); - before.put("favorite_number", 256); - // Leave favorite_color null - - AvroCoder coder = AvroCoder.of(GenericRecord.class, schema); - - CoderProperties.coderDecodeEncodeEqual(coder, before); - Assert.assertEquals(schema, coder.getSchema()); - } - - @Test - public void testEncodingNotBuffered() throws Exception { - // This test ensures that the coder doesn't read ahead and buffer data. - // Reading ahead causes a problem if the stream consists of records of different - // types. - Pojo before = new Pojo("Hello", 42); - - AvroCoder coder = AvroCoder.of(Pojo.class); - SerializableCoder intCoder = SerializableCoder.of(Integer.class); - - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - - Context context = Context.NESTED; - coder.encode(before, outStream, context); - intCoder.encode(10, outStream, context); - - ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); - - Pojo after = coder.decode(inStream, context); - Assert.assertEquals(before, after); - - Integer intAfter = intCoder.decode(inStream, context); - Assert.assertEquals(new Integer(10), intAfter); - } - - @Test - public void testDefaultCoder() throws Exception { - Pipeline p = TestPipeline.create(); - - // Use MyRecord as input and output types without explicitly specifying - // a coder (this uses the default coders, which may not be AvroCoder). - PCollection output = - p.apply(Create.of(new Pojo("hello", 1), new Pojo("world", 2))) - .apply(ParDo.of(new GetTextFn())); - - DataflowAssert.that(output) - .containsInAnyOrder("hello", "world"); - p.run(); - } - - @Test - public void testAvroCoderIsSerializable() throws Exception { - AvroCoder coder = AvroCoder.of(Pojo.class); - - // Check that the coder is serializable using the regular JSON approach. - SerializableUtils.ensureSerializable(coder); - } - - private void assertDeterministic(AvroCoder coder) { - try { - coder.verifyDeterministic(); - } catch (NonDeterministicException e) { - fail("Expected " + coder + " to be deterministic, but got:\n" + e); - } - } - - private void assertNonDeterministic(AvroCoder coder, - Matcher reason1) { - try { - coder.verifyDeterministic(); - fail("Expected " + coder + " to be non-deterministic."); - } catch (NonDeterministicException e) { - assertThat(e.getReasons(), Matchers.iterableWithSize(1)); - assertThat(e.getReasons(), Matchers.contains(reason1)); - } - } - - @Test - public void testDeterministicInteger() { - assertDeterministic(AvroCoder.of(Integer.class)); - } - - @Test - public void testDeterministicInt() { - assertDeterministic(AvroCoder.of(int.class)); - } - - private static class SimpleDeterministicClass { - @SuppressWarnings("unused") - private Integer intField; - @SuppressWarnings("unused") - private char charField; - @SuppressWarnings("unused") - private Integer[] intArray; - @SuppressWarnings("unused") - private Utf8 utf8field; - } - - @Test - public void testDeterministicSimple() { - assertDeterministic(AvroCoder.of(SimpleDeterministicClass.class)); - } - - private static class UnorderedMapClass { - @SuppressWarnings("unused") - private Map mapField; - } - - private Matcher reason(final String prefix, final String messagePart) { - return new TypeSafeMatcher(String.class) { - @Override - public void describeTo(Description description) { - description.appendText(String.format("Reason starting with '%s:' containing '%s'", - prefix, messagePart)); - } - - @Override - protected boolean matchesSafely(String item) { - return item.startsWith(prefix + ":") && item.contains(messagePart); - } - }; - } - - private Matcher reasonClass(Class clazz, String message) { - return reason(clazz.getName(), message); - } - - private Matcher reasonField( - Class clazz, String field, String message) { - return reason(clazz.getName() + "#" + field, message); - } - - @Test - public void testDeterministicUnorderedMap() { - assertNonDeterministic(AvroCoder.of(UnorderedMapClass.class), - reasonField(UnorderedMapClass.class, "mapField", - "java.util.Map " - + "may not be deterministically ordered")); - } - - private static class NonDeterministicArray { - @SuppressWarnings("unused") - private UnorderedMapClass[] arrayField; - } - @Test - public void testDeterministicNonDeterministicArray() { - assertNonDeterministic(AvroCoder.of(NonDeterministicArray.class), - reasonField(UnorderedMapClass.class, "mapField", - "java.util.Map" - + " may not be deterministically ordered")); - } - - private static class SubclassOfUnorderedMapClass extends UnorderedMapClass {} - - - @Test - public void testDeterministicNonDeterministicChild() { - // Super class has non deterministic fields. - assertNonDeterministic(AvroCoder.of(SubclassOfUnorderedMapClass.class), - reasonField(UnorderedMapClass.class, "mapField", - "may not be deterministically ordered")); - } - - private static class SubclassHidingParent extends UnorderedMapClass { - @SuppressWarnings("unused") - @AvroName("mapField2") // AvroName is not enough - private int mapField; - } - - @Test - public void testAvroProhibitsShadowing() { - // This test verifies that Avro won't serialize a class with two fields of - // the same name. This is important for our error reporting, and also how - // we lookup a field. - try { - ReflectData.get().getSchema(SubclassHidingParent.class); - fail("Expected AvroTypeException"); - } catch (AvroTypeException e) { - assertThat(e.getMessage(), containsString("mapField")); - assertThat(e.getMessage(), containsString("two fields named")); - } - } - - private static class FieldWithAvroName { - @AvroName("name") - @SuppressWarnings("unused") - private int someField; - } - - @Test - public void testDeterministicWithAvroName() { - assertDeterministic(AvroCoder.of(FieldWithAvroName.class)); - } - - @Test - public void testDeterminismSortedMap() { - assertDeterministic(AvroCoder.of(StringSortedMapField.class)); - } - - private static class StringSortedMapField { - @SuppressWarnings("unused") - SortedMap sortedMapField; - } - - @Test - public void testDeterminismTreeMapValue() { - // The value is non-deterministic, so we should fail. - assertNonDeterministic(AvroCoder.of(TreeMapNonDetValue.class), - reasonField(UnorderedMapClass.class, "mapField", - "java.util.Map " - + "may not be deterministically ordered")); - } - - private static class TreeMapNonDetValue { - @SuppressWarnings("unused") - TreeMap nonDeterministicField; - } - - @Test - public void testDeterminismUnorderedMap() { - // LinkedHashMap is not deterministically ordered, so we should fail. - assertNonDeterministic(AvroCoder.of(LinkedHashMapField.class), - reasonField(LinkedHashMapField.class, "nonDeterministicMap", - "java.util.LinkedHashMap " - + "may not be deterministically ordered")); - } - - private static class LinkedHashMapField { - @SuppressWarnings("unused") - LinkedHashMap nonDeterministicMap; - } - - @Test - public void testDeterminismCollection() { - assertNonDeterministic(AvroCoder.of(StringCollection.class), - reasonField(StringCollection.class, "stringCollection", - "java.util.Collection may not be deterministically ordered")); - } - - private static class StringCollection { - @SuppressWarnings("unused") - Collection stringCollection; - } - - @Test - public void testDeterminismList() { - assertDeterministic(AvroCoder.of(StringList.class)); - assertDeterministic(AvroCoder.of(StringArrayList.class)); - } - - private static class StringList { - @SuppressWarnings("unused") - List stringCollection; - } - - private static class StringArrayList { - @SuppressWarnings("unused") - ArrayList stringCollection; - } - - @Test - public void testDeterminismSet() { - assertDeterministic(AvroCoder.of(StringSortedSet.class)); - assertDeterministic(AvroCoder.of(StringTreeSet.class)); - assertNonDeterministic(AvroCoder.of(StringHashSet.class), - reasonField(StringHashSet.class, "stringCollection", - "java.util.HashSet may not be deterministically ordered")); - } - - private static class StringSortedSet{ - @SuppressWarnings("unused") - SortedSet stringCollection; - } - - private static class StringTreeSet { - @SuppressWarnings("unused") - TreeSet stringCollection; - } - - private static class StringHashSet { - @SuppressWarnings("unused") - HashSet stringCollection; - } - - @Test - public void testDeterminismCollectionValue() { - assertNonDeterministic(AvroCoder.of(OrderedSetOfNonDetValues.class), - reasonField(UnorderedMapClass.class, "mapField", - "may not be deterministically ordered")); - assertNonDeterministic(AvroCoder.of(ListOfNonDetValues.class), - reasonField(UnorderedMapClass.class, "mapField", - "may not be deterministically ordered")); - } - - private static class OrderedSetOfNonDetValues { - @SuppressWarnings("unused") - SortedSet set; - } - - private static class ListOfNonDetValues { - @SuppressWarnings("unused") - List set; - } - - @Test - public void testDeterminismUnion() { - assertDeterministic(AvroCoder.of(DeterministicUnionBase.class)); - assertNonDeterministic(AvroCoder.of(NonDeterministicUnionBase.class), - reasonField(UnionCase3.class, "mapField", "may not be deterministically ordered")); - } - - @Test - public void testDeterminismStringable() { - assertDeterministic(AvroCoder.of(String.class)); - assertNonDeterministic(AvroCoder.of(StringableClass.class), - reasonClass(StringableClass.class, "may not have deterministic #toString()")); - } - - @Stringable - private static class StringableClass { - } - - @Test - public void testDeterminismCyclicClass() { - assertNonDeterministic(AvroCoder.of(Cyclic.class), - reasonField(Cyclic.class, "cyclicField", "appears recursively")); - assertNonDeterministic(AvroCoder.of(CyclicField.class), - reasonField(Cyclic.class, "cyclicField", - Cyclic.class.getName() + " appears recursively")); - assertNonDeterministic(AvroCoder.of(IndirectCycle1.class), - reasonField(IndirectCycle2.class, "field2", - IndirectCycle1.class.getName() + " appears recursively")); - } - - private static class Cyclic { - @SuppressWarnings("unused") - int intField; - @SuppressWarnings("unused") - Cyclic cyclicField; - } - - private static class CyclicField { - @SuppressWarnings("unused") - Cyclic cyclicField2; - } - - private static class IndirectCycle1 { - @SuppressWarnings("unused") - IndirectCycle2 field1; - } - - private static class IndirectCycle2 { - @SuppressWarnings("unused") - IndirectCycle1 field2; - } - - @Test - public void testDeterminismHasGenericRecord() { - assertDeterministic(AvroCoder.of(HasGenericRecord.class)); - } - - private static class HasGenericRecord { - @AvroSchema("{\"name\": \"bar\", \"type\": \"record\", \"fields\": [" - + "{\"name\": \"foo\", \"type\": \"int\"}]}") - GenericRecord genericRecord; - } - - @Test - public void testDeterminismHasCustomSchema() { - assertNonDeterministic(AvroCoder.of(HasCustomSchema.class), - reasonField(HasCustomSchema.class, "withCustomSchema", - "Custom schemas are only supported for subtypes of IndexedRecord.")); - } - - private static class HasCustomSchema { - @AvroSchema("{\"name\": \"bar\", \"type\": \"record\", \"fields\": [" - + "{\"name\": \"foo\", \"type\": \"int\"}]}") - int withCustomSchema; - } - - @Test - public void testAvroCoderTreeMapDeterminism() - throws Exception, NonDeterministicException { - TreeMapField size1 = new TreeMapField(); - TreeMapField size2 = new TreeMapField(); - - // Different order for entries - size1.field.put("hello", "world"); - size1.field.put("another", "entry"); - - size2.field.put("another", "entry"); - size2.field.put("hello", "world"); - - AvroCoder coder = AvroCoder.of(TreeMapField.class); - coder.verifyDeterministic(); - - ByteArrayOutputStream outStream1 = new ByteArrayOutputStream(); - ByteArrayOutputStream outStream2 = new ByteArrayOutputStream(); - - Context context = Context.NESTED; - coder.encode(size1, outStream1, context); - coder.encode(size2, outStream2, context); - - assertTrue(Arrays.equals( - outStream1.toByteArray(), outStream2.toByteArray())); - } - - private static class TreeMapField { - private TreeMap field = new TreeMap<>(); - } - - @Union({ UnionCase1.class, UnionCase2.class }) - private abstract static class DeterministicUnionBase {} - - @Union({ UnionCase1.class, UnionCase2.class, UnionCase3.class }) - private abstract static class NonDeterministicUnionBase {} - private static class UnionCase1 extends DeterministicUnionBase {} - private static class UnionCase2 extends DeterministicUnionBase { - @SuppressWarnings("unused") - String field; - } - - private static class UnionCase3 extends NonDeterministicUnionBase { - @SuppressWarnings("unused") - private Map mapField; - } - - @Test - public void testAvroCoderSimpleSchemaDeterminism() { - assertDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .endRecord())); - assertDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .name("int").type().intType().noDefault() - .endRecord())); - assertDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .name("string").type().stringType().noDefault() - .endRecord())); - - assertNonDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .name("map").type().map().values().stringType().noDefault() - .endRecord()), - reason("someRecord.map", "HashMap to represent MAPs")); - - assertDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .name("array").type().array().items().stringType().noDefault() - .endRecord())); - - assertDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .name("enum").type().enumeration("anEnum").symbols("s1", "s2").enumDefault("s1") - .endRecord())); - - assertDeterministic(AvroCoder.of(SchemaBuilder.unionOf() - .intType().and() - .record("someRecord").fields().nullableString("someField", "").endRecord() - .endUnion())); - } - - @Test - public void testAvroCoderStrings() { - // Custom Strings in Records - assertDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .name("string").prop(SpecificData.CLASS_PROP, "java.lang.String") - .type().stringType().noDefault() - .endRecord())); - assertNonDeterministic(AvroCoder.of(SchemaBuilder.record("someRecord").fields() - .name("string").prop(SpecificData.CLASS_PROP, "unknownString") - .type().stringType().noDefault() - .endRecord()), - reason("someRecord.string", "unknownString is not known to be deterministic")); - - // Custom Strings in Unions - assertNonDeterministic(AvroCoder.of(SchemaBuilder.unionOf() - .intType().and() - .record("someRecord").fields() - .name("someField").prop(SpecificData.CLASS_PROP, "unknownString") - .type().stringType().noDefault().endRecord() - .endUnion()), - reason("someRecord.someField", "unknownString is not known to be deterministic")); - } - - @Test - public void testAvroCoderNestedRecords() { - // Nested Record - assertDeterministic(AvroCoder.of(SchemaBuilder.record("nestedRecord").fields() - .name("subRecord").type().record("subRecord").fields() - .name("innerField").type().stringType().noDefault() - .endRecord().noDefault() - .endRecord())); - } - - @Test - public void testAvroCoderCyclicRecords() { - // Recursive record - assertNonDeterministic(AvroCoder.of(SchemaBuilder.record("cyclicRecord").fields() - .name("cycle").type("cyclicRecord").noDefault() - .endRecord()), - reason("cyclicRecord.cycle", "cyclicRecord appears recursively")); - } - - private static class NullableField { - @SuppressWarnings("unused") - @Nullable private String nullable; - } - - @Test - public void testNullableField() { - assertDeterministic(AvroCoder.of(NullableField.class)); - } - - private static class NullableNonDeterministicField { - @SuppressWarnings("unused") - @Nullable private NonDeterministicArray nullableNonDetArray; - } - - private static class NullableCyclic { - @SuppressWarnings("unused") - @Nullable private NullableCyclic nullableNullableCyclicField; - } - - private static class NullableCyclicField { - @SuppressWarnings("unused") - @Nullable private Cyclic nullableCyclicField; - } - - @Test - public void testNullableNonDeterministicField() { - assertNonDeterministic(AvroCoder.of(NullableCyclic.class), - reasonField(NullableCyclic.class, "nullableNullableCyclicField", - NullableCyclic.class.getName() + " appears recursively")); - assertNonDeterministic(AvroCoder.of(NullableCyclicField.class), - reasonField(Cyclic.class, "cyclicField", - Cyclic.class.getName() + " appears recursively")); - assertNonDeterministic(AvroCoder.of(NullableNonDeterministicField.class), - reasonField(UnorderedMapClass.class, "mapField", - " may not be deterministically ordered")); - } - - /** - * Tests that a parameterized class can have an automatically generated schema if the generic - * field is annotated with a union tag. - */ - @Test - public void testGenericClassWithUnionAnnotation() throws Exception { - // Cast is safe as long as the same coder is used for encoding and decoding. - @SuppressWarnings({"unchecked", "rawtypes"}) - AvroCoder> coder = - (AvroCoder) AvroCoder.of(GenericWithAnnotation.class); - - assertThat(coder.getSchema().getField("onlySomeTypesAllowed").schema().getType(), - equalTo(Schema.Type.UNION)); - - CoderProperties.coderDecodeEncodeEqual(coder, new GenericWithAnnotation<>("hello")); - } - - private static class GenericWithAnnotation { - @AvroSchema("[\"string\", \"int\"]") - private T onlySomeTypesAllowed; - - public GenericWithAnnotation(T value) { - onlySomeTypesAllowed = value; - } - - // For deserialization only - @SuppressWarnings("unused") - protected GenericWithAnnotation() { } - - @Override - public boolean equals(Object other) { - return other instanceof GenericWithAnnotation - && onlySomeTypesAllowed.equals(((GenericWithAnnotation) other).onlySomeTypesAllowed); - } - - @Override - public int hashCode() { - return Objects.hash(getClass(), onlySomeTypesAllowed); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoderTest.java deleted file mode 100644 index d96c20805d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianIntegerCoderTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link BigEndianIntegerCoder}. - */ -@RunWith(JUnit4.class) -public class BigEndianIntegerCoderTest { - - private static final Coder TEST_CODER = BigEndianIntegerCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - -11, -3, -1, 0, 1, 5, 13, 29, - Integer.MAX_VALUE, - Integer.MIN_VALUE); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Integer value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // This should never change. The definition of big endian encoding is fixed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "____9Q", - "_____Q", - "_____w", - "AAAAAA", - "AAAAAQ", - "AAAABQ", - "AAAADQ", - "AAAAHQ", - "f____w", - "gAAAAA"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Integer"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoderTest.java deleted file mode 100644 index ea486c1823..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/BigEndianLongCoderTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link BigEndianLongCoder}. - */ -@RunWith(JUnit4.class) -public class BigEndianLongCoderTest { - - private static final Coder TEST_CODER = BigEndianLongCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - -11L, -3L, -1L, 0L, 1L, 5L, 13L, 29L, - Integer.MAX_VALUE + 131L, - Integer.MIN_VALUE - 29L, - Long.MAX_VALUE, - Long.MIN_VALUE); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Long value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // This should never change. The definition of big endian is fixed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "__________U", - "__________0", - "__________8", - "AAAAAAAAAAA", - "AAAAAAAAAAE", - "AAAAAAAAAAU", - "AAAAAAAAAA0", - "AAAAAAAAAB0", - "AAAAAIAAAII", - "_____3___-M", - "f_________8", - "gAAAAAAAAAA"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Long"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoderTest.java deleted file mode 100644 index 989bc7f80b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteArrayCoderTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.common.CounterTestUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -/** - * Unit tests for {@link ByteArrayCoder}. - */ -@RunWith(JUnit4.class) -public class ByteArrayCoderTest { - - private static final ByteArrayCoder TEST_CODER = ByteArrayCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - new byte[]{0xa, 0xb, 0xc}, - new byte[]{0xd, 0x3}, - new byte[]{0xd, 0xe}, - new byte[]{}); - - @Test - public void testDecodeEncodeEquals() throws Exception { - for (byte[] value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - @Test - public void testRegisterByteSizeObserver() throws Exception { - CounterTestUtils.testByteCount(ByteArrayCoder.of(), Coder.Context.OUTER, - new byte[][]{{ 0xa, 0xb, 0xc }}); - - CounterTestUtils.testByteCount(ByteArrayCoder.of(), Coder.Context.NESTED, - new byte[][]{{ 0xa, 0xb, 0xc }, {}, {}, { 0xd, 0xe }, {}}); - } - - @Test - public void testStructuralValueConsistentWithEquals() throws Exception { - // We know that byte array coders are NOT compatible with equals - // (aka injective w.r.t. Object.equals) - for (byte[] value1 : TEST_VALUES) { - for (byte[] value2 : TEST_VALUES) { - CoderProperties.structuralValueConsistentWithEquals(TEST_CODER, value1, value2); - } - } - } - - @Test - public void testEncodeThenMutate() throws Exception { - byte[] input = { 0x7, 0x3, 0xA, 0xf }; - byte[] encoded = CoderUtils.encodeToByteArray(TEST_CODER, input); - input[1] = 0x9; - byte[] decoded = CoderUtils.decodeFromByteArray(TEST_CODER, encoded); - - // now that I have mutated the input, the output should NOT match - assertThat(input, not(equalTo(decoded))); - } - - @Test - public void testEncodeAndOwn() throws Exception { - for (byte[] value : TEST_VALUES) { - byte[] encodedSlow = CoderUtils.encodeToByteArray(TEST_CODER, value); - byte[] encodedFast = encodeToByteArrayAndOwn(TEST_CODER, value); - assertThat(encodedSlow, equalTo(encodedFast)); - } - } - - private static byte[] encodeToByteArrayAndOwn(ByteArrayCoder coder, byte[] value) - throws IOException { - return encodeToByteArrayAndOwn(coder, value, Coder.Context.OUTER); - } - - private static byte[] encodeToByteArrayAndOwn( - ByteArrayCoder coder, byte[] value, Coder.Context context) throws IOException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - coder.encodeAndOwn(value, os, context); - return os.toByteArray(); - } - - // If this changes, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "CgsM", - "DQM", - "DQ4", - ""); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null byte[]"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteCoderTest.java deleted file mode 100644 index 6cb852e236..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteCoderTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link ByteCoder}. - */ -@RunWith(JUnit4.class) -public class ByteCoderTest { - - private static final Coder TEST_CODER = ByteCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - (byte) 1, - (byte) 4, - (byte) 6, - (byte) 50, - (byte) 124, - Byte.MAX_VALUE, - Byte.MIN_VALUE); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Byte value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // This should never change. The format is fixed by Java. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AQ", - "BA", - "Bg", - "Mg", - "fA", - "fw", - "gA"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Byte"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java deleted file mode 100644 index debae71fdd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ByteStringCoderTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.collect.ImmutableList; -import com.google.protobuf.ByteString; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link ByteStringCoder}. - */ -@RunWith(JUnit4.class) -public class ByteStringCoderTest { - - private static final ByteStringCoder TEST_CODER = ByteStringCoder.of(); - - private static final List TEST_STRING_VALUES = Arrays.asList( - "", "a", "13", "hello", - "a longer string with spaces and all that", - "a string with a \n newline", - "???????????????"); - private static final ImmutableList TEST_VALUES; - static { - ImmutableList.Builder builder = ImmutableList.builder(); - for (String s : TEST_STRING_VALUES) { - builder.add(ByteString.copyFrom(s.getBytes())); - } - TEST_VALUES = builder.build(); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "", - "YQ", - "MTM", - "aGVsbG8", - "YSBsb25nZXIgc3RyaW5nIHdpdGggc3BhY2VzIGFuZCBhbGwgdGhhdA", - "YSBzdHJpbmcgd2l0aCBhIAogbmV3bGluZQ", - "Pz8_Pz8_Pz8_Pz8_Pz8_"); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testDecodeEncodeEqualInAllContexts() throws Exception { - for (ByteString value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Test - public void testCoderDeterministic() throws Throwable { - TEST_CODER.verifyDeterministic(); - } - - @Test - public void testConsistentWithEquals() { - assertTrue(TEST_CODER.consistentWithEquals()); - } - - @Test - public void testEncodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null ByteString"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } - - @Test - public void testNestedCoding() throws Throwable { - Coder> listCoder = ListCoder.of(TEST_CODER); - CoderProperties.coderDecodeEncodeContentsEqual(listCoder, TEST_VALUES); - CoderProperties.coderDecodeEncodeContentsInSameOrder(listCoder, TEST_VALUES); - } - - @Test - public void testEncodedElementByteSizeInAllContexts() throws Throwable { - for (Context context : CoderProperties.ALL_CONTEXTS) { - for (ByteString value : TEST_VALUES) { - byte[] encoded = CoderUtils.encodeToByteArray(TEST_CODER, value, context); - assertEquals(encoded.length, TEST_CODER.getEncodedElementByteSize(value, context)); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderFactoriesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderFactoriesTest.java deleted file mode 100644 index 8d702bf259..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderFactoriesTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; - -/** - * Tests for {@link CoderFactories}. - */ -@RunWith(JUnit4.class) -public class CoderFactoriesTest { - - /** - * Ensures that a few of our standard atomic coder classes - * can each be built into a factory that works as expected. - * It is presumed that testing a few, not all, suffices to - * exercise CoderFactoryFromStaticMethods. - */ - @Test - public void testAtomicCoderClassFactories() { - checkAtomicCoderFactory(StringUtf8Coder.class, StringUtf8Coder.of()); - checkAtomicCoderFactory(DoubleCoder.class, DoubleCoder.of()); - checkAtomicCoderFactory(ByteArrayCoder.class, ByteArrayCoder.of()); - } - - /** - * Checks that {#link CoderFactories.fromStaticMethods} successfully - * builds a working {@link CoderFactory} from {@link KvCoder KvCoder.class}. - */ - @Test - public void testKvCoderFactory() { - CoderFactory kvCoderFactory = CoderFactories.fromStaticMethods(KvCoder.class); - assertEquals( - KvCoder.of(DoubleCoder.of(), DoubleCoder.of()), - kvCoderFactory.create(Arrays.asList(DoubleCoder.of(), DoubleCoder.of()))); - } - - /** - * Checks that {#link CoderFactories.fromStaticMethods} successfully - * builds a working {@link CoderFactory} from {@link ListCoder ListCoder.class}. - */ - @Test - public void testListCoderFactory() { - CoderFactory listCoderFactory = CoderFactories.fromStaticMethods(ListCoder.class); - - assertEquals( - ListCoder.of(DoubleCoder.of()), - listCoderFactory.create(Arrays.asList(DoubleCoder.of()))); - } - - /** - * Checks that {#link CoderFactories.fromStaticMethods} successfully - * builds a working {@link CoderFactory} from {@link IterableCoder IterableCoder.class}. - */ - @Test - public void testIterableCoderFactory() { - CoderFactory iterableCoderFactory = CoderFactories.fromStaticMethods(IterableCoder.class); - - assertEquals( - IterableCoder.of(DoubleCoder.of()), - iterableCoderFactory.create(Arrays.asList(DoubleCoder.of()))); - } - - /////////////////////////////////////////////////////////////////////// - - /** - * Checks that an atomic coder class can be converted into - * a factory that then yields a coder equal to the example - * provided. - */ - private void checkAtomicCoderFactory( - Class> coderClazz, - Coder expectedCoder) { - CoderFactory factory = CoderFactories.fromStaticMethods(coderClazz); - @SuppressWarnings("unchecked") - Coder actualCoder = (Coder) factory.create(Collections.>emptyList()); - assertEquals(expectedCoder, actualCoder); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderProvidersTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderProvidersTest.java deleted file mode 100644 index 1c0a89ed1b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderProvidersTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Map; - -/** - * Tests for {@link CoderFactories}. - */ -@RunWith(JUnit4.class) -public class CoderProvidersTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testAvroThenSerializableStringMap() throws Exception { - CoderProvider provider = CoderProviders.firstOf(AvroCoder.PROVIDER, SerializableCoder.PROVIDER); - Coder> coder = - provider.getCoder(new TypeDescriptor>(){}); - assertThat(coder, instanceOf(AvroCoder.class)); - } - - @Test - public void testThrowingThenSerializable() throws Exception { - CoderProvider provider = - CoderProviders.firstOf(new ThrowingCoderProvider(), SerializableCoder.PROVIDER); - Coder coder = provider.getCoder(new TypeDescriptor(){}); - assertThat(coder, instanceOf(SerializableCoder.class)); - } - - @Test - public void testNullThrows() throws Exception { - CoderProvider provider = CoderProviders.firstOf(new ThrowingCoderProvider()); - thrown.expect(CannotProvideCoderException.class); - thrown.expectMessage("ThrowingCoderProvider"); - provider.getCoder(new TypeDescriptor(){}); - } - - private static class ThrowingCoderProvider implements CoderProvider { - @Override - public Coder getCoder(TypeDescriptor type) throws CannotProvideCoderException { - throw new CannotProvideCoderException("ThrowingCoderProvider cannot ever provide a Coder"); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java deleted file mode 100644 index 2f350b288d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderRegistryTest.java +++ /dev/null @@ -1,521 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry.IncompatibleCoderException; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; -import com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; -import com.google.protobuf.Duration; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Tests for CoderRegistry. - */ -@RunWith(JUnit4.class) -public class CoderRegistryTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public static CoderRegistry getStandardRegistry() { - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - return registry; - } - - private static class SerializableClass implements Serializable { - } - - private static class NotSerializableClass { } - - @Test - public void testSerializableFallbackCoderProvider() throws Exception { - CoderRegistry registry = getStandardRegistry(); - registry.setFallbackCoderProvider(SerializableCoder.PROVIDER); - Coder serializableCoder = registry.getDefaultCoder(SerializableClass.class); - - assertEquals(serializableCoder, SerializableCoder.of(SerializableClass.class)); - } - - @Test - public void testProtoCoderFallbackCoderProvider() throws Exception { - CoderRegistry registry = getStandardRegistry(); - - // MessageA is a Protocol Buffers test message with syntax 2 - assertEquals(registry.getDefaultCoder(MessageA.class), ProtoCoder.of(MessageA.class)); - - // Duration is a Protocol Buffers default type with syntax 3 - assertEquals(registry.getDefaultCoder(Duration.class), ProtoCoder.of(Duration.class)); - } - - @Test - public void testAvroFallbackCoderProvider() throws Exception { - CoderRegistry registry = getStandardRegistry(); - registry.setFallbackCoderProvider(AvroCoder.PROVIDER); - Coder avroCoder = registry.getDefaultCoder(NotSerializableClass.class); - - assertEquals(avroCoder, AvroCoder.of(NotSerializableClass.class)); - } - - @Test - public void testRegisterInstantiatedCoder() throws Exception { - CoderRegistry registry = new CoderRegistry(); - registry.registerCoder(MyValue.class, MyValueCoder.of()); - assertEquals(registry.getDefaultCoder(MyValue.class), MyValueCoder.of()); - } - - @SuppressWarnings("rawtypes") // this class exists to fail a test because of its rawtypes - private class MyListCoder extends DeterministicStandardCoder { - @Override - public void encode(List value, OutputStream outStream, Context context) - throws CoderException, IOException { - } - - @Override - public List decode(InputStream inStream, Context context) - throws CoderException, IOException { - return Collections.emptyList(); - } - - @Override - public List> getCoderArguments() { - return Collections.emptyList(); - } - } - - @Test - public void testRegisterInstantiatedCoderInvalidRawtype() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("may not be used with unspecialized generic classes"); - CoderRegistry registry = new CoderRegistry(); - registry.registerCoder(List.class, new MyListCoder()); - } - - @Test - public void testSimpleDefaultCoder() throws Exception { - CoderRegistry registry = getStandardRegistry(); - assertEquals(StringUtf8Coder.of(), registry.getDefaultCoder(String.class)); - } - - @Test - public void testSimpleUnknownDefaultCoder() throws Exception { - CoderRegistry registry = getStandardRegistry(); - thrown.expect(CannotProvideCoderException.class); - thrown.expectMessage(allOf( - containsString(UnknownType.class.getCanonicalName()), - containsString("No CoderFactory has been registered"), - containsString("does not have a @DefaultCoder annotation"), - containsString("does not implement Serializable"))); - registry.getDefaultCoder(UnknownType.class); - } - - @Test - public void testParameterizedDefaultListCoder() throws Exception { - CoderRegistry registry = getStandardRegistry(); - TypeDescriptor> listToken = new TypeDescriptor>() {}; - assertEquals(ListCoder.of(VarIntCoder.of()), - registry.getDefaultCoder(listToken)); - - registry.registerCoder(MyValue.class, MyValueCoder.class); - TypeDescriptor>> kvToken = - new TypeDescriptor>>() {}; - assertEquals(KvCoder.of(StringUtf8Coder.of(), - ListCoder.of(MyValueCoder.of())), - registry.getDefaultCoder(kvToken)); - - } - - @Test - public void testParameterizedDefaultMapCoder() throws Exception { - CoderRegistry registry = getStandardRegistry(); - TypeDescriptor> mapToken = new TypeDescriptor>() {}; - assertEquals(MapCoder.of(VarIntCoder.of(), StringUtf8Coder.of()), - registry.getDefaultCoder(mapToken)); - } - - @Test - public void testParameterizedDefaultNestedMapCoder() throws Exception { - CoderRegistry registry = getStandardRegistry(); - TypeDescriptor>> mapToken = - new TypeDescriptor>>() {}; - assertEquals( - MapCoder.of(VarIntCoder.of(), MapCoder.of(StringUtf8Coder.of(), DoubleCoder.of())), - registry.getDefaultCoder(mapToken)); - } - - @Test - public void testParameterizedDefaultSetCoder() throws Exception { - CoderRegistry registry = getStandardRegistry(); - TypeDescriptor> setToken = new TypeDescriptor>() {}; - assertEquals(SetCoder.of(VarIntCoder.of()), registry.getDefaultCoder(setToken)); - } - - @Test - public void testParameterizedDefaultNestedSetCoder() throws Exception { - CoderRegistry registry = getStandardRegistry(); - TypeDescriptor>> setToken = new TypeDescriptor>>() {}; - assertEquals(SetCoder.of(SetCoder.of(VarIntCoder.of())), registry.getDefaultCoder(setToken)); - } - - @Test - public void testParameterizedDefaultCoderUnknown() throws Exception { - CoderRegistry registry = getStandardRegistry(); - TypeDescriptor> listUnknownToken = new TypeDescriptor>() {}; - - thrown.expect(CannotProvideCoderException.class); - thrown.expectMessage(String.format( - "Cannot provide coder for parameterized type %s: Unable to provide a default Coder for %s", - listUnknownToken, - UnknownType.class.getCanonicalName())); - - registry.getDefaultCoder(listUnknownToken); - } - - @Test - public void testTypeParameterInferenceForward() throws Exception { - CoderRegistry registry = getStandardRegistry(); - MyGenericClass> instance = - new MyGenericClass>() {}; - - Coder bazCoder = registry.getDefaultCoder( - instance.getClass(), - MyGenericClass.class, - Collections.>singletonMap( - TypeDescriptor.of(MyGenericClass.class).getTypeParameter("FooT"), MyValueCoder.of()), - TypeDescriptor.of(MyGenericClass.class).getTypeParameter("BazT")); - - assertEquals(ListCoder.of(MyValueCoder.of()), bazCoder); - } - - @Test - public void testTypeParameterInferenceBackward() throws Exception { - CoderRegistry registry = getStandardRegistry(); - MyGenericClass> instance = - new MyGenericClass>() {}; - - Coder fooCoder = registry.getDefaultCoder( - instance.getClass(), - MyGenericClass.class, - Collections.>singletonMap( - TypeDescriptor.of(MyGenericClass.class).getTypeParameter("BazT"), - ListCoder.of(MyValueCoder.of())), - TypeDescriptor.of(MyGenericClass.class).getTypeParameter("FooT")); - - assertEquals(MyValueCoder.of(), fooCoder); - } - - @Test - public void testGetDefaultCoderFromIntegerValue() throws Exception { - CoderRegistry registry = getStandardRegistry(); - Integer i = 13; - Coder coder = registry.getDefaultCoder(i); - assertEquals(VarIntCoder.of(), coder); - } - - @Test - public void testGetDefaultCoderFromNullValue() throws Exception { - CoderRegistry registry = getStandardRegistry(); - assertEquals(VoidCoder.of(), registry.getDefaultCoder((Void) null)); - } - - @Test - public void testGetDefaultCoderFromKvValue() throws Exception { - CoderRegistry registry = getStandardRegistry(); - KV kv = KV.of(13, "hello"); - Coder> coder = registry.getDefaultCoder(kv); - assertEquals(KvCoder.of(VarIntCoder.of(), StringUtf8Coder.of()), - coder); - } - - @Test - public void testGetDefaultCoderFromKvNullValue() throws Exception { - CoderRegistry registry = getStandardRegistry(); - KV kv = KV.of((Void) null, (Void) null); - assertEquals(KvCoder.of(VoidCoder.of(), VoidCoder.of()), - registry.getDefaultCoder(kv)); - } - - @Test - public void testGetDefaultCoderFromNestedKvValue() throws Exception { - CoderRegistry registry = getStandardRegistry(); - KV>> kv = KV.of(13, KV.of(17L, KV.of("hello", "goodbye"))); - Coder>>> coder = registry.getDefaultCoder(kv); - assertEquals( - KvCoder.of(VarIntCoder.of(), - KvCoder.of(VarLongCoder.of(), - KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()))), - coder); - } - - @Test - public void testTypeCompatibility() throws Exception { - CoderRegistry.verifyCompatible(BigEndianIntegerCoder.of(), Integer.class); - CoderRegistry.verifyCompatible( - ListCoder.of(BigEndianIntegerCoder.of()), - new TypeDescriptor>() {}.getType()); - } - - @Test - public void testIntVersusStringIncompatibility() throws Exception { - thrown.expect(IncompatibleCoderException.class); - thrown.expectMessage("not assignable"); - CoderRegistry.verifyCompatible(BigEndianIntegerCoder.of(), String.class); - } - - private static class TooManyComponentCoders extends ListCoder { - public TooManyComponentCoders(Coder actualComponentCoder) { - super(actualComponentCoder); - } - - @Override - public List> getCoderArguments() { - return ImmutableList.>builder() - .addAll(super.getCoderArguments()) - .add(BigEndianLongCoder.of()) - .build(); - } - } - - @Test - public void testTooManyCoderArguments() throws Exception { - thrown.expect(IncompatibleCoderException.class); - thrown.expectMessage("type parameters"); - thrown.expectMessage("less than the number of coder arguments"); - CoderRegistry.verifyCompatible( - new TooManyComponentCoders<>(BigEndianIntegerCoder.of()), List.class); - } - - @Test - public void testComponentIncompatibility() throws Exception { - thrown.expect(IncompatibleCoderException.class); - thrown.expectMessage("component coder is incompatible"); - CoderRegistry.verifyCompatible( - ListCoder.of(BigEndianIntegerCoder.of()), - new TypeDescriptor>() {}.getType()); - } - - @Test - public void testDefaultCoderAnnotationGenericRawtype() throws Exception { - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - assertEquals( - registry.getDefaultCoder(MySerializableGeneric.class), - SerializableCoder.of(MySerializableGeneric.class)); - } - - @Test - public void testDefaultCoderAnnotationGeneric() throws Exception { - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - assertEquals( - registry.getDefaultCoder(new TypeDescriptor>() {}), - SerializableCoder.of(MySerializableGeneric.class)); - } - - private static class PTransformOutputingMySerializableGeneric - extends PTransform, PCollection>>> { - - private class OutputDoFn extends DoFn>> { - @Override - public void processElement(ProcessContext c) { } - } - - @Override - public PCollection>> - apply(PCollection input) { - return input.apply(ParDo.of(new OutputDoFn())); - } - } - - /** - * Tests that the error message for a type variable includes a mention of where the - * type variable was declared. - */ - @Test - public void testTypeVariableErrorMessage() throws Exception { - CoderRegistry registry = new CoderRegistry(); - - thrown.expect(CannotProvideCoderException.class); - thrown.expectMessage(allOf( - containsString("TestGenericT"), - containsString("erasure"), - containsString("com.google.cloud.dataflow.sdk.coders.CoderRegistryTest$TestGenericClass"))); - registry.getDefaultCoder(TypeDescriptor.of( - TestGenericClass.class.getTypeParameters()[0])); - } - - private static class TestGenericClass { } - - /** - * In-context test that assures the functionality tested in - * {@link #testDefaultCoderAnnotationGeneric} is invoked in the right ways. - */ - @Test - public void testSpecializedButIgnoredGenericInPipeline() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of("hello", "goodbye")) - .apply(new PTransformOutputingMySerializableGeneric()); - - pipeline.run(); - } - - private static class GenericOutputMySerializedGeneric - extends PTransform< - PCollection, - PCollection>>> { - - private class OutputDoFn extends DoFn>> { - @Override - public void processElement(ProcessContext c) { } - } - - @Override - public PCollection>> - apply(PCollection input) { - return input.apply(ParDo.of(new OutputDoFn())); - } - } - - @Test - public void testIgnoredGenericInPipeline() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of("hello", "goodbye")) - .apply(new GenericOutputMySerializedGeneric()); - - pipeline.run(); - } - - private static class MyGenericClass { } - - private static class MyValue { } - - private static class MyValueCoder implements Coder { - - private static final MyValueCoder INSTANCE = new MyValueCoder(); - - public static MyValueCoder of() { - return INSTANCE; - } - - @SuppressWarnings("unused") - public static List getInstanceComponents( - @SuppressWarnings("unused") MyValue exampleValue) { - return Arrays.asList(); - } - - @Override - public void encode(MyValue value, OutputStream outStream, Context context) - throws CoderException, IOException { - } - - @Override - public MyValue decode(InputStream inStream, Context context) - throws CoderException, IOException { - return new MyValue(); - } - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public CloudObject asCloudObject() { - return null; - } - - @Override - public void verifyDeterministic() { } - - @Override - public boolean consistentWithEquals() { - return true; - } - - @Override - public Object structuralValue(MyValue value) { - return value; - } - - @Override - public boolean isRegisterByteSizeObserverCheap(MyValue value, Context context) { - return true; - } - - @Override - public void registerByteSizeObserver( - MyValue value, ElementByteSizeObserver observer, Context context) - throws Exception { - observer.update(0L); - } - - @Override - public String getEncodingId() { - return getClass().getName(); - } - - @Override - public Collection getAllowedEncodings() { - return Collections.singletonList(getEncodingId()); - } - } - - private static class UnknownType { } - - @DefaultCoder(SerializableCoder.class) - private static class MySerializableGeneric implements Serializable { - @SuppressWarnings("unused") - private T foo; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java deleted file mode 100644 index c5d275cf63..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CoderTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collections; - -/** Tests for constructs defined within {@link Coder}. */ -@RunWith(JUnit4.class) -public class CoderTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testContextEqualsAndHashCode() { - assertEquals(Context.NESTED, new Context(false)); - assertEquals(Context.OUTER, new Context(true)); - assertNotEquals(Context.NESTED, Context.OUTER); - - assertEquals(Context.NESTED.hashCode(), new Context(false).hashCode()); - assertEquals(Context.OUTER.hashCode(), new Context(true).hashCode()); - // Even though this isn't strictly required by the hashCode contract, - // we still want this to be true. - assertNotEquals(Context.NESTED.hashCode(), Context.OUTER.hashCode()); - } - - @Test - public void testContextToString() { - assertEquals("Context{NESTED}", Context.NESTED.toString()); - assertEquals("Context{OUTER}", Context.OUTER.toString()); - } - - @Test - public void testNonDeterministicExcpetionRequiresReason() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Reasons must not be empty"); - new NonDeterministicException(VoidCoder.of(), Collections.emptyList()); - } - - @Test - public void testNonDeterministicException() { - NonDeterministicException rootCause = - new NonDeterministicException(VoidCoder.of(), "Root Cause"); - NonDeterministicException exception = - new NonDeterministicException(StringUtf8Coder.of(), "Problem", rootCause); - assertEquals(rootCause, exception.getCause()); - assertThat(exception.getReasons(), contains("Problem")); - assertThat(exception.toString(), containsString("Problem")); - assertThat(exception.toString(), containsString("is not deterministic")); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CollectionCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CollectionCoderTest.java deleted file mode 100644 index ae1d167df1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CollectionCoderTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.TreeSet; - -/** - * Test case for {@link CollectionCoder}. - */ -@RunWith(JUnit4.class) -public class CollectionCoderTest { - - private static final Coder> TEST_CODER = CollectionCoder.of(VarIntCoder.of()); - - private static final List> TEST_VALUES = Arrays.>asList( - Collections.emptyList(), - Collections.emptySet(), - Collections.singletonList(13), - Arrays.asList(1, 2, 3, 4), - new LinkedList<>(Arrays.asList(7, 6, 5)), - new TreeSet<>(Arrays.asList(31, -5, 83))); - - @Test - public void testDecodeEncodeContentsEqual() throws Exception { - for (Collection value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeContentsEqual(TEST_CODER, value); - } - } - - // If this becomes nonempty, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AAAAAA", - "AAAAAA", - "AAAAAQ0", - "AAAABAECAwQ", - "AAAAAwcGBQ", - "AAAAA_v___8PH1M"); - - @Test - public void testWireFormat() throws Exception { - CoderProperties.coderDecodesBase64ContentsEqual(TEST_CODER, TEST_ENCODINGS, TEST_VALUES); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Collection"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CustomCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CustomCoderTest.java deleted file mode 100644 index 21f750362e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/CustomCoderTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** Unit tests for {@link CustomCoder}. */ -@RunWith(JUnit4.class) -public class CustomCoderTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static class MyCustomCoder extends CustomCoder> { - private final String key; - - public MyCustomCoder(String key) { - this.key = key; - } - - @Override - public void encode(KV kv, OutputStream out, Context context) - throws IOException { - new DataOutputStream(out).writeLong(kv.getValue()); - } - - @Override - public KV decode(InputStream inStream, Context context) - throws IOException { - return KV.of(key, new DataInputStream(inStream).readLong()); - } - - @Override - public boolean equals(Object other) { - return other instanceof MyCustomCoder - && key.equals(((MyCustomCoder) other).key); - } - - @Override - public int hashCode() { - return key.hashCode(); - } - } - - @Test - public void testEncodeDecode() throws Exception { - MyCustomCoder coder = new MyCustomCoder("key"); - CoderProperties.coderDecodeEncodeEqual(coder, KV.of("key", 3L)); - - byte[] encoded2 = CoderUtils.encodeToByteArray(coder, KV.of("ignored", 3L)); - Assert.assertEquals( - KV.of("key", 3L), CoderUtils.decodeFromByteArray(coder, encoded2)); - } - - @Test - public void testEncodable() throws Exception { - SerializableUtils.ensureSerializable(new MyCustomCoder("key")); - } - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(new MyCustomCoder("foo"), - MyCustomCoder.class.getCanonicalName()); - } - - @Test - public void testAnonymousEncodingIdError() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("Anonymous CustomCoder subclass"); - thrown.expectMessage("must override getEncodingId()"); - new CustomCoder() { - - @Override - public void encode(Integer kv, OutputStream out, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public Integer decode(InputStream inStream, Context context) { - throw new UnsupportedOperationException(); - } - }.getEncodingId(); - } - - @Test - public void testAnonymousEncodingIdOk() throws Exception { - new CustomCoder() { - - @Override - public void encode(Integer kv, OutputStream out, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public Integer decode(InputStream inStream, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public String getEncodingId() { - return "A user must specify this. It can contain any character, including these: !$#%$@."; - } - }.getEncodingId(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DefaultCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DefaultCoderTest.java deleted file mode 100644 index 498b64db57..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DefaultCoderTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.List; - -/** - * Tests of Coder defaults. - */ -@RunWith(JUnit4.class) -public class DefaultCoderTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public CoderRegistry registry = new CoderRegistry(); - - @Before - public void registerStandardCoders() { - registry.registerStandardCoders(); - } - - @DefaultCoder(AvroCoder.class) - private static class AvroRecord { - } - - private static class SerializableBase implements Serializable { - } - - @DefaultCoder(SerializableCoder.class) - private static class SerializableRecord extends SerializableBase { - } - - @DefaultCoder(CustomSerializableCoder.class) - private static class CustomRecord extends SerializableBase { - } - - @DefaultCoder(OldCustomSerializableCoder.class) - private static class OldCustomRecord extends SerializableBase { - } - - private static class Unknown { - } - - private static class CustomSerializableCoder extends SerializableCoder { - // Extending SerializableCoder isn't trivial, but it can be done. - @SuppressWarnings("unchecked") - public static SerializableCoder of(TypeDescriptor recordType) { - checkArgument(recordType.isSupertypeOf(new TypeDescriptor() {})); - return (SerializableCoder) new CustomSerializableCoder(); - } - - protected CustomSerializableCoder() { - super(CustomRecord.class); - } - } - - private static class OldCustomSerializableCoder extends SerializableCoder { - // Extending SerializableCoder isn't trivial, but it can be done. - @Deprecated // old form using a Class - @SuppressWarnings("unchecked") - public static SerializableCoder of(Class recordType) { - checkArgument(OldCustomRecord.class.isAssignableFrom(recordType)); - return (SerializableCoder) new OldCustomSerializableCoder(); - } - - protected OldCustomSerializableCoder() { - super(OldCustomRecord.class); - } - } - - @Test - public void testDefaultCoderClasses() throws Exception { - assertThat(registry.getDefaultCoder(AvroRecord.class), instanceOf(AvroCoder.class)); - assertThat(registry.getDefaultCoder(SerializableBase.class), - instanceOf(SerializableCoder.class)); - assertThat(registry.getDefaultCoder(SerializableRecord.class), - instanceOf(SerializableCoder.class)); - assertThat(registry.getDefaultCoder(CustomRecord.class), - instanceOf(CustomSerializableCoder.class)); - assertThat(registry.getDefaultCoder(OldCustomRecord.class), - instanceOf(OldCustomSerializableCoder.class)); - } - - @Test - public void testDefaultCoderInCollection() throws Exception { - assertThat(registry.getDefaultCoder(new TypeDescriptor>(){}), - instanceOf(ListCoder.class)); - assertThat(registry.getDefaultCoder(new TypeDescriptor>(){}), - equalTo((Coder>) - ListCoder.of(SerializableCoder.of(SerializableRecord.class)))); - } - - @Test - public void testUnknown() throws Exception { - thrown.expect(CannotProvideCoderException.class); - registry.getDefaultCoder(Unknown.class); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DelegateCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DelegateCoderTest.java deleted file mode 100644 index 3397818c90..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DelegateCoderTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** Unit tests for {@link DelegateCoder}. */ -@RunWith(JUnit4.class) -public class DelegateCoderTest implements Serializable { - - private static final List> TEST_VALUES = Arrays.>asList( - Collections.emptySet(), - Collections.singleton(13), - new HashSet<>(Arrays.asList(31, -5, 83))); - - private static final DelegateCoder, List> TEST_CODER = DelegateCoder.of( - ListCoder.of(VarIntCoder.of()), - new DelegateCoder.CodingFunction, List>() { - @Override - public List apply(Set input) { - return Lists.newArrayList(input); - } - }, - new DelegateCoder.CodingFunction, Set>() { - @Override - public Set apply(List input) { - return Sets.newHashSet(input); - } - }); - - @Test - public void testDeterministic() throws Exception { - for (Set value : TEST_VALUES) { - CoderProperties.coderDeterministic( - TEST_CODER, value, Sets.newHashSet(value)); - } - } - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Set value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - @Test - public void testSerializable() throws Exception { - CoderProperties.coderSerializable(TEST_CODER); - } - - private static final String TEST_ENCODING_ID = "test-encoding-id"; - private static final String TEST_ALLOWED_ENCODING = "test-allowed-encoding"; - - private static class TestAllowedEncodingsCoder extends StandardCoder { - - @Override - public void encode(Integer value, OutputStream outstream, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public Integer decode(InputStream instream, Context context) { - throw new UnsupportedOperationException(); - } - - @Override - public void verifyDeterministic() { - throw new UnsupportedOperationException(); - } - - @Override - public List> getCoderArguments() { - return Collections.emptyList(); - } - - @Override - public String getEncodingId() { - return TEST_ENCODING_ID; - } - - @Override - public Collection getAllowedEncodings() { - return Collections.singletonList(TEST_ALLOWED_ENCODING); - } - } - - @Test - public void testEncodingId() throws Exception { - Coder underlyingCoder = new TestAllowedEncodingsCoder(); - - Coder trivialDelegateCoder = DelegateCoder.of( - underlyingCoder, - new DelegateCoder.CodingFunction() { - @Override - public Integer apply(Integer input) { - return input; - } - }, - new DelegateCoder.CodingFunction() { - @Override - public Integer apply(Integer input) { - return input; - } - }); - CoderProperties.coderHasEncodingId( - trivialDelegateCoder, TestAllowedEncodingsCoder.class.getName() + ":" + TEST_ENCODING_ID); - CoderProperties.coderAllowsEncoding( - trivialDelegateCoder, - TestAllowedEncodingsCoder.class.getName() + ":" + TEST_ALLOWED_ENCODING); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DoubleCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DoubleCoderTest.java deleted file mode 100644 index 8791eb4d46..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DoubleCoderTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link DoubleCoder}. - */ -@RunWith(JUnit4.class) -public class DoubleCoderTest { - - private static final Coder TEST_CODER = DoubleCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - 0.0, -0.5, 0.5, 0.3, -0.3, 1.0, -43.89568740, 3.14159, - Double.MAX_VALUE, - Double.MIN_VALUE, - Double.POSITIVE_INFINITY, - Double.NEGATIVE_INFINITY, - Double.NaN); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Double value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // This should never change. The format is fixed by Java. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AAAAAAAAAAA", - "v-AAAAAAAAA", - "P-AAAAAAAAA", - "P9MzMzMzMzM", - "v9MzMzMzMzM", - "P_AAAAAAAAA", - "wEXypeJ9ODo", - "QAkh-fAbhm4", - "f-________8", - "AAAAAAAAAAE", - "f_AAAAAAAAA", - "__AAAAAAAAA", - "f_gAAAAAAAA"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Double"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DurationCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DurationCoderTest.java deleted file mode 100644 index 3d831b38c5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/DurationCoderTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.collect.Lists; - -import org.joda.time.Duration; -import org.joda.time.ReadableDuration; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** Unit tests for {@link DurationCoder}. */ -@RunWith(JUnit4.class) -public class DurationCoderTest { - - private static final DurationCoder TEST_CODER = DurationCoder.of(); - private static final List TEST_MILLIS = - Lists.newArrayList(0L, 1L, -1L, -255L, 256L, Long.MIN_VALUE, Long.MAX_VALUE); - - private static final List TEST_VALUES; - - static { - TEST_VALUES = Lists.newArrayList(); - for (long millis : TEST_MILLIS) { - TEST_VALUES.add(Duration.millis(millis)); - } - } - - @Test - public void testBasicEncoding() throws Exception { - for (ReadableDuration value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AA", - "AQ", - "____________AQ", - "gf7_________AQ", - "gAI", - "gICAgICAgICAAQ", - "__________9_"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null ReadableDuration"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java deleted file mode 100644 index 8c047d3418..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/EntityCoderTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static com.google.api.services.datastore.client.DatastoreHelper.makeKey; -import static com.google.api.services.datastore.client.DatastoreHelper.makeProperty; -import static com.google.api.services.datastore.client.DatastoreHelper.makeValue; - -import com.google.api.services.datastore.DatastoreV1.Entity; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link EntityCoder}. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("deprecation") // test of deprecated code. -public class EntityCoderTest { - - private static final Coder TEST_CODER = EntityCoder.of(); - - // Presumably if anything works, everything works, - // as actual serialization is fully delegated to - // autogenerated code from a well-tested library. - private static final List TEST_VALUES = Arrays.asList( - Entity.newBuilder() - .setKey(makeKey("TestKind", "emptyEntity")) - .build(), - Entity.newBuilder() - .setKey(makeKey("TestKind", "testSimpleProperties")) - .addProperty(makeProperty("trueProperty", makeValue(true))) - .addProperty(makeProperty("falseProperty", makeValue(false))) - .addProperty(makeProperty("stringProperty", makeValue("hello"))) - .addProperty(makeProperty("integerProperty", makeValue(3))) - .addProperty(makeProperty("doubleProperty", makeValue(-1.583257))) - .build(), - Entity.newBuilder() - .setKey(makeKey("TestKind", "testNestedEntity")) - .addProperty(makeProperty("entityProperty", - makeValue(Entity.newBuilder() - .addProperty(makeProperty("stringProperty", makeValue("goodbye")))))) - .build()); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Entity value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // If this changes, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AAAAGwoZEhcKCFRlc3RLaW5kGgtlbXB0eUVudGl0eQ", - "AAAAnQoiEiAKCFRlc3RLaW5kGhR0ZXN0U2ltcGxlUHJvcGVydGllcxISCgx0cnVlUHJvcGVydHkiAggBEhMKDWZhbHNl" - + "UHJvcGVydHkiAggAEhoKDnN0cmluZ1Byb3BlcnR5IgiKAQVoZWxsbxIVCg9pbnRlZ2VyUHJvcGVydHkiAhADEh" - + "sKDmRvdWJsZVByb3BlcnR5IgkZ8ZvCSgVV-b8", - "AAAAVAoeEhwKCFRlc3RLaW5kGhB0ZXN0TmVzdGVkRW50aXR5EjIKDmVudGl0eVByb3BlcnR5IiAyHhIcCg5zdHJpbmdQ" - + "cm9wZXJ0eSIKigEHZ29vZGJ5ZQ"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Entity"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/InstantCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/InstantCoderTest.java deleted file mode 100644 index 454500bf24..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/InstantCoderTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.collect.Lists; -import com.google.common.primitives.UnsignedBytes; - -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** Unit tests for {@link InstantCoder}. */ -@RunWith(JUnit4.class) -public class InstantCoderTest { - - private static final InstantCoder TEST_CODER = InstantCoder.of(); - - private static final List TEST_TIMESTAMPS = - Arrays.asList(0L, 1L, -1L, -255L, 256L, Long.MIN_VALUE, Long.MAX_VALUE); - - private static final List TEST_VALUES; - - static { - TEST_VALUES = Lists.newArrayList(); - for (long timestamp : TEST_TIMESTAMPS) { - TEST_VALUES.add(new Instant(timestamp)); - } - } - - @Test - public void testBasicEncoding() throws Exception { - for (Instant value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - @Test - public void testOrderedEncoding() throws Exception { - List sortedTimestamps = new ArrayList<>(TEST_TIMESTAMPS); - Collections.sort(sortedTimestamps); - - List encodings = new ArrayList<>(sortedTimestamps.size()); - for (long timestamp : sortedTimestamps) { - encodings.add(CoderUtils.encodeToByteArray(TEST_CODER, new Instant(timestamp))); - } - - // Verify that the encodings were already sorted, since they were generated - // in the correct order. - List sortedEncodings = new ArrayList<>(encodings); - Collections.sort(sortedEncodings, UnsignedBytes.lexicographicalComparator()); - - Assert.assertEquals(encodings, sortedEncodings); - } - - // If this changes, it implies that the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "gAAAAAAAAAA", - "gAAAAAAAAAE", - "f_________8", - "f________wE", - "gAAAAAAAAQA", - "AAAAAAAAAAA", - "__________8"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Instant"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/IterableCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/IterableCoderTest.java deleted file mode 100644 index 9afddc1b99..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/IterableCoderTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** Unit tests for {@link IterableCoder}. */ -@RunWith(JUnit4.class) -public class IterableCoderTest { - - private static final Coder> TEST_CODER = IterableCoder.of(VarIntCoder.of()); - - private static final List> TEST_VALUES = Arrays.>asList( - Collections.emptyList(), - Collections.singletonList(13), - Arrays.asList(1, 2, 3, 4), - new LinkedList(Arrays.asList(7, 6, 5))); - - @Test - public void testDecodeEncodeContentsInSameOrder() throws Exception { - for (Iterable value : TEST_VALUES) { - CoderProperties.>coderDecodeEncodeContentsInSameOrder( - TEST_CODER, value); - } - } - - @Test - public void testGetInstanceComponentsNonempty() { - Iterable iterable = Arrays.asList(2, 58, 99, 5); - List components = IterableCoder.getInstanceComponents(iterable); - assertEquals(1, components.size()); - assertEquals(2, components.get(0)); - } - - @Test - public void testGetInstanceComponentsEmpty() { - Iterable iterable = Arrays.asList(); - List components = IterableCoder.getInstanceComponents(iterable); - assertNull(components); - } - - @Test - public void testCoderSerializable() throws Exception { - CoderProperties.coderSerializable(TEST_CODER); - } - - // If this changes, it implies that the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AAAAAA", - "AAAAAQ0", - "AAAABAECAwQ", - "AAAAAwcGBQ"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Iterable"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java deleted file mode 100644 index e75c69c79c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/JAXBCoderTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicReference; - -import javax.xml.bind.annotation.XmlRootElement; - -/** Unit tests for {@link JAXBCoder}. */ -@RunWith(JUnit4.class) -public class JAXBCoderTest { - - @XmlRootElement - static class TestType { - private String testString = null; - private int testInt; - - public TestType() {} - - public TestType(String testString, int testInt) { - this.testString = testString; - this.testInt = testInt; - } - - public String getTestString() { - return testString; - } - - public void setTestString(String testString) { - this.testString = testString; - } - - public int getTestInt() { - return testInt; - } - - public void setTestInt(int testInt) { - this.testInt = testInt; - } - - @Override - public int hashCode() { - int hashCode = 1; - hashCode = 31 * hashCode + (testString == null ? 0 : testString.hashCode()); - hashCode = 31 * hashCode + testInt; - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof TestType)) { - return false; - } - - TestType other = (TestType) obj; - return (testString == null || testString.equals(other.testString)) - && (testInt == other.testInt); - } - } - - @Test - public void testEncodeDecode() throws Exception { - JAXBCoder coder = JAXBCoder.of(TestType.class); - - byte[] encoded = CoderUtils.encodeToByteArray(coder, new TestType("abc", 9999)); - assertEquals(new TestType("abc", 9999), CoderUtils.decodeFromByteArray(coder, encoded)); - } - - @Test - public void testEncodeDecodeAfterClone() throws Exception { - JAXBCoder coder = SerializableUtils.clone(JAXBCoder.of(TestType.class)); - - byte[] encoded = CoderUtils.encodeToByteArray(coder, new TestType("abc", 9999)); - assertEquals(new TestType("abc", 9999), CoderUtils.decodeFromByteArray(coder, encoded)); - } - - @Test - public void testEncodeDecodeMultithreaded() throws Throwable { - final JAXBCoder coder = JAXBCoder.of(TestType.class); - int numThreads = 100; - - final CountDownLatch ready = new CountDownLatch(numThreads); - final CountDownLatch start = new CountDownLatch(1); - final CountDownLatch done = new CountDownLatch(numThreads); - - final AtomicReference thrown = new AtomicReference<>(); - - Executor executor = Executors.newCachedThreadPool(); - for (int i = 0; i < numThreads; i++) { - final TestType elem = new TestType("abc", i); - final int index = i; - executor.execute( - new Runnable() { - @Override - public void run() { - ready.countDown(); - try { - start.await(); - } catch (InterruptedException e) { - } - - try { - byte[] encoded = CoderUtils.encodeToByteArray(coder, elem); - assertEquals( - new TestType("abc", index), CoderUtils.decodeFromByteArray(coder, encoded)); - } catch (Throwable e) { - thrown.compareAndSet(null, e); - } - done.countDown(); - } - }); - } - ready.await(); - start.countDown(); - - done.await(); - Throwable actuallyThrown = thrown.get(); - - if (actuallyThrown != null) { - throw actuallyThrown; - } - } - - @Test - public void testEncodable() throws Exception { - CoderProperties.coderSerializable(JAXBCoder.of(TestType.class)); - } - - @Test - public void testEncodingId() throws Exception { - Coder coder = JAXBCoder.of(TestType.class); - CoderProperties.coderHasEncodingId( - coder, TestType.class.getName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/KvCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/KvCoderTest.java deleted file mode 100644 index 0fd4c1b4d8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/KvCoderTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.ImmutableMap; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** - * Test case for {@link KvCoder}. - */ -@RunWith(JUnit4.class) -public class KvCoderTest { - - private static final Map, Iterable> TEST_DATA = - new ImmutableMap.Builder, Iterable>() - .put(VarIntCoder.of(), - Arrays.asList(-1, 0, 1, 13, Integer.MAX_VALUE, Integer.MIN_VALUE)) - .put(BigEndianLongCoder.of(), - Arrays.asList(-1L, 0L, 1L, 13L, Long.MAX_VALUE, Long.MIN_VALUE)) - .put(StringUtf8Coder.of(), - Arrays.asList("", "hello", "goodbye", "1")) - .put(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()), - Arrays.asList(KV.of("", -1), KV.of("hello", 0), KV.of("goodbye", Integer.MAX_VALUE))) - .put(ListCoder.of(VarLongCoder.of()), - Arrays.asList( - Arrays.asList(1L, 2L, 3L), - Collections.emptyList())) - .build(); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Map.Entry, Iterable> entry : TEST_DATA.entrySet()) { - // The coder and corresponding values must be the same type. - // If someone messes this up in the above test data, the test - // will fail anyhow (unless the coder magically works on data - // it does not understand). - @SuppressWarnings("unchecked") - Coder coder = (Coder) entry.getKey(); - Iterable values = entry.getValue(); - for (Object value : values) { - CoderProperties.coderDecodeEncodeEqual(coder, value); - } - } - } - - // If this changes, it implies the binary format has changed! - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId( - KvCoder.of(VarIntCoder.of(), VarIntCoder.of()), - EXPECTED_ENCODING_ID); - } - - /** - * Homogeneously typed test value for ease of use with the wire format test utility. - */ - private static final Coder> TEST_CODER = - KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()); - - private static final List> TEST_VALUES = Arrays.asList( - KV.of("", -1), - KV.of("hello", 0), - KV.of("goodbye", Integer.MAX_VALUE)); - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AP____8P", - "BWhlbGxvAA", - "B2dvb2RieWX_____Bw"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null KV"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ListCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ListCoderTest.java deleted file mode 100644 index 6993f323e9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/ListCoderTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** Unit tests for {@link ListCoder}. */ -@RunWith(JUnit4.class) -public class ListCoderTest { - - private static final Coder> TEST_CODER = ListCoder.of(VarIntCoder.of()); - - private static final List> TEST_VALUES = Arrays.>asList( - Collections.emptyList(), - Collections.singletonList(43), - Arrays.asList(1, 2, 3, 4), - new LinkedList(Arrays.asList(7, 6, 5))); - - @Test - public void testDecodeEncodeContentsInSameOrder() throws Exception { - for (List value : TEST_VALUES) { - CoderProperties.>coderDecodeEncodeContentsInSameOrder( - TEST_CODER, value); - } - } - - @Test - public void testGetInstanceComponentsNonempty() throws Exception { - List list = Arrays.asList(21, 5, 3, 5); - List components = ListCoder.getInstanceComponents(list); - assertEquals(1, components.size()); - assertEquals(21, components.get(0)); - } - - @Test - public void testGetInstanceComponentsEmpty() throws Exception { - List list = Arrays.asList(); - List components = ListCoder.getInstanceComponents(list); - assertNull(components); - } - - @Test - public void testEmptyList() throws Exception { - List list = Collections.emptyList(); - Coder> coder = ListCoder.of(VarIntCoder.of()); - CoderProperties.>coderDecodeEncodeEqual(coder, list); - } - - @Test - public void testCoderSerializable() throws Exception { - CoderProperties.coderSerializable(TEST_CODER); - } - - // If this changes, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AAAAAA", - "AAAAASs", - "AAAABAECAwQ", - "AAAAAwcGBQ"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null List"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } - - @Test - public void testListWithNullsAndVarIntCoderThrowsException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Integer"); - - List list = Arrays.asList(1, 2, 3, null, 4); - Coder> coder = ListCoder.of(VarIntCoder.of()); - CoderProperties.>coderDecodeEncodeEqual(coder, list); - } - - @Test - public void testListWithNullsAndSerializableCoder() throws Exception { - List list = Arrays.asList(1, 2, 3, null, 4); - Coder> coder = ListCoder.of(SerializableCoder.of(Integer.class)); - CoderProperties.>coderDecodeEncodeEqual(coder, list); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/MapCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/MapCoderTest.java deleted file mode 100644 index c263d2722d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/MapCoderTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.collect.ImmutableMap; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** Unit tests for {@link MapCoder}. */ -@RunWith(JUnit4.class) -public class MapCoderTest { - - private static final Coder> TEST_CODER = - MapCoder.of(VarIntCoder.of(), StringUtf8Coder.of()); - - private static final List> TEST_VALUES = Arrays.>asList( - Collections.emptyMap(), - new TreeMap(new ImmutableMap.Builder() - .put(1, "hello").put(-1, "foo").build())); - - @Test - public void testDecodeEncodeContentsInSameOrder() throws Exception { - for (Map value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - @Test - public void testGetInstanceComponentsNonempty() { - Map map = new HashMap<>(); - map.put(17, "foozle"); - List components = MapCoder.getInstanceComponents(map); - assertEquals(2, components.size()); - assertEquals(17, components.get(0)); - assertEquals("foozle", components.get(1)); - } - - @Test - public void testGetInstanceComponentsEmpty() { - Map map = new HashMap<>(); - List components = MapCoder.getInstanceComponents(map); - assertNull(components); - } - - // If this changes, it implies the binary format has changed! - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AAAAAA", - "AAAAAv____8PA2ZvbwEFaGVsbG8"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Map"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/NullableCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/NullableCoderTest.java deleted file mode 100644 index 644930e721..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/NullableCoderTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.Arrays; -import java.util.List; - -/** Unit tests for {@link NullableCoder}. */ -@RunWith(JUnit4.class) -public class NullableCoderTest { - - private static final Coder TEST_CODER = NullableCoder.of(StringUtf8Coder.of()); - - private static final List TEST_VALUES = Arrays.asList( - "", "a", "13", "hello", - null, - "a longer string with spaces and all that", - "a string with a \n newline", - "スタリング"); - - @Test - public void testDecodeEncodeContentsInSameOrder() throws Exception { - for (String value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - @Test - public void testCoderSerializable() throws Exception { - CoderProperties.coderSerializable(TEST_CODER); - } - - // If this changes, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@code PrintBase64Encodings}. - * - * @see com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AQA", - "AQFh", - "AQIxMw", - "AQVoZWxsbw", - "AA", - "AShhIGxvbmdlciBzdHJpbmcgd2l0aCBzcGFjZXMgYW5kIGFsbCB0aGF0", - "ARlhIHN0cmluZyB3aXRoIGEgCiBuZXdsaW5l", - "AQ_jgrnjgr_jg6rjg7PjgrA"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Test - public void testEncodedSize() throws Exception { - NullableCoder coder = NullableCoder.of(DoubleCoder.of()); - assertEquals(1, coder.getEncodedElementByteSize(null, Coder.Context.OUTER)); - assertEquals(9, coder.getEncodedElementByteSize(5.0, Coder.Context.OUTER)); - } - - @Test - public void testObserverIsCheap() throws Exception { - NullableCoder coder = NullableCoder.of(DoubleCoder.of()); - assertTrue(coder.isRegisterByteSizeObserverCheap(null, Coder.Context.OUTER)); - assertTrue(coder.isRegisterByteSizeObserverCheap(5.0, Coder.Context.OUTER)); - } - - @Test - public void testObserverIsNotCheap() throws Exception { - NullableCoder> coder = NullableCoder.of(ListCoder.of(StringUtf8Coder.of())); - assertFalse(coder.isRegisterByteSizeObserverCheap(null, Coder.Context.OUTER)); - assertFalse(coder.isRegisterByteSizeObserverCheap( - ImmutableList.of("hi", "test"), Coder.Context.OUTER)); - } - - @Test - public void testStructuralValueConsistentWithEquals() throws Exception { - CoderProperties.structuralValueConsistentWithEquals(TEST_CODER, null, null); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testDecodingError() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage(equalTo("NullableCoder expects either a byte valued 0 (null) " - + "or 1 (present), got 5")); - - InputStream input = new ByteArrayInputStream(new byte[] {5}); - TEST_CODER.decode(input, Coder.Context.OUTER); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/PrintBase64Encodings.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/PrintBase64Encodings.java deleted file mode 100644 index 0f08262aa2..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/PrintBase64Encodings.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.List; - -/** - * A command-line utility for printing the base-64 encodings of test values, for generating exact - * wire format tests. - * - *

              For internal use only. - * - *

              Example invocation via maven: - * {@code - * mvn test-compile exec:java \ - * -Dexec.classpathScope=test \ - * -Dexec.mainClass=com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings - * -Dexec.args='com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoderTest.TEST_CODER \ - * com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoderTest.TEST_VALUES' - * } - */ -public class PrintBase64Encodings { - - /** - * Gets a field even if it is private, which the test data generally will be. - */ - private static Field getField(Class clazz, String fieldName) throws Exception { - for (Field field : clazz.getDeclaredFields()) { - if (field.getName().equals(fieldName)) { - if (!Modifier.isPublic(field.getModifiers())) { - field.setAccessible(true); - } - return field; - } - } - throw new NoSuchFieldException(clazz.getCanonicalName() + "." + fieldName); - } - - private static Object getFullyQualifiedValue(String fullyQualifiedName) throws Exception { - int lastDot = fullyQualifiedName.lastIndexOf("."); - String className = fullyQualifiedName.substring(0, lastDot); - String fieldName = fullyQualifiedName.substring(lastDot + 1); - - Class clazz = Class.forName(className); - Field field = getField(clazz, fieldName); - return field.get(null); - } - - public static void main(String[] argv) throws Exception { - @SuppressWarnings("unchecked") - Coder testCoder = (Coder) getFullyQualifiedValue(argv[0]); - @SuppressWarnings("unchecked") - List testValues = (List) getFullyQualifiedValue(argv[1]); - - List base64Encodings = Lists.newArrayList(); - for (Object value : testValues) { - base64Encodings.add(CoderUtils.encodeToBase64(testCoder, value)); - } - System.out.println(String.format("\"%s\"", Joiner.on("\",\n\"").join(base64Encodings))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java deleted file mode 100644 index 91ebc65438..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/Proto2CoderTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageB; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageC; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for Proto2Coder. - */ -@SuppressWarnings("deprecation") // test of a deprecated coder. -@RunWith(JUnit4.class) -public class Proto2CoderTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testFactoryMethodAgreement() throws Exception { - assertEquals( - Proto2Coder.of(new TypeDescriptor() {}), - Proto2Coder.of(MessageA.class)); - - assertEquals( - Proto2Coder.of(new TypeDescriptor() {}), - Proto2Coder.coderProvider().getCoder(new TypeDescriptor() {})); - } - - @Test - public void testProviderCannotProvideCoder() throws Exception { - thrown.expect(CannotProvideCoderException.class); - Proto2Coder.coderProvider().getCoder(new TypeDescriptor() {}); - } - - @Test - public void testCoderEncodeDecodeEqual() throws Exception { - MessageA value = MessageA.newBuilder() - .setField1("hello") - .addField2(MessageB.newBuilder() - .setField1(true).build()) - .addField2(MessageB.newBuilder() - .setField1(false).build()) - .build(); - CoderProperties.coderDecodeEncodeEqual(Proto2Coder.of(MessageA.class), value); - } - - @Test - public void testCoderEncodeDecodeEqualNestedContext() throws Exception { - MessageA value1 = MessageA.newBuilder() - .setField1("hello") - .addField2(MessageB.newBuilder() - .setField1(true).build()) - .addField2(MessageB.newBuilder() - .setField1(false).build()) - .build(); - MessageA value2 = MessageA.newBuilder() - .setField1("world") - .addField2(MessageB.newBuilder() - .setField1(false).build()) - .addField2(MessageB.newBuilder() - .setField1(true).build()) - .build(); - CoderProperties.coderDecodeEncodeEqual( - ListCoder.of(Proto2Coder.of(MessageA.class)), - ImmutableList.of(value1, value2)); - } - - @Test - public void testCoderEncodeDecodeExtensionsEqual() throws Exception { - MessageC value = MessageC.newBuilder() - .setExtension(Proto2CoderTestMessages.field1, - MessageA.newBuilder() - .setField1("hello") - .addField2(MessageB.newBuilder() - .setField1(true) - .build()) - .build()) - .setExtension(Proto2CoderTestMessages.field2, - MessageB.newBuilder() - .setField1(false) - .build()) - .build(); - CoderProperties.coderDecodeEncodeEqual( - Proto2Coder.of(MessageC.class).withExtensionsFrom(Proto2CoderTestMessages.class), - value); - } - - @Test - public void testCoderSerialization() throws Exception { - Proto2Coder coder = Proto2Coder.of(MessageA.class); - CoderProperties.coderSerializable(coder); - } - - @Test - public void testCoderExtensionsSerialization() throws Exception { - Proto2Coder coder = Proto2Coder.of(MessageC.class) - .withExtensionsFrom(Proto2CoderTestMessages.class); - CoderProperties.coderSerializable(coder); - } - - @Test - public void testEncodingId() throws Exception { - Coder coderA = Proto2Coder.of(MessageA.class); - CoderProperties.coderHasEncodingId(coderA, MessageA.class.getName()); - - Proto2Coder coder = Proto2Coder.of(MessageC.class) - .withExtensionsFrom(Proto2CoderTestMessages.class); - CoderProperties.coderHasEncodingId(coder, MessageC.class.getName()); - } - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null MessageA"); - - CoderUtils.encodeToBase64(Proto2Coder.of(MessageA.class), null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SerializableCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SerializableCoderTest.java deleted file mode 100644 index b819967bdc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SerializableCoderTest.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.Serializer; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * Tests SerializableCoder. - */ -@RunWith(JUnit4.class) -public class SerializableCoderTest implements Serializable { - - @DefaultCoder(SerializableCoder.class) - static class MyRecord implements Serializable { - private static final long serialVersionUID = 42L; - - public String value; - - public MyRecord(String value) { - this.value = value; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - MyRecord myRecord = (MyRecord) o; - return value.equals(myRecord.value); - } - - @Override - public int hashCode() { - return value.hashCode(); - } - } - - static class StringToRecord extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(new MyRecord(c.element())); - } - } - - static class RecordToString extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().value); - } - } - - static final List LINES = Arrays.asList( - "To be,", - "or not to be"); - - @Test - public void testSerializableCoder() throws Exception { - IterableCoder coder = IterableCoder - .of(SerializableCoder.of(MyRecord.class)); - - List records = new LinkedList<>(); - for (String l : LINES) { - records.add(new MyRecord(l)); - } - - byte[] encoded = CoderUtils.encodeToByteArray(coder, records); - Iterable decoded = CoderUtils.decodeFromByteArray(coder, encoded); - - assertEquals(records, decoded); - } - - @Test - public void testSerializableCoderConstruction() throws Exception { - SerializableCoder coder = SerializableCoder.of(MyRecord.class); - assertEquals(coder.getRecordType(), MyRecord.class); - - CloudObject encoding = coder.asCloudObject(); - Assert.assertThat(encoding.getClassName(), - Matchers.containsString(SerializableCoder.class.getSimpleName())); - - Coder decoded = Serializer.deserialize(encoding, Coder.class); - Assert.assertThat(decoded, Matchers.instanceOf(SerializableCoder.class)); - } - - @Test - public void testDefaultCoder() throws Exception { - Pipeline p = TestPipeline.create(); - - // Use MyRecord as input and output types without explicitly specifying - // a coder (this uses the default coders, which may not be - // SerializableCoder). - PCollection output = - p.apply(Create.of("Hello", "World")) - .apply(ParDo.of(new StringToRecord())) - .apply(ParDo.of(new RecordToString())); - - DataflowAssert.that(output) - .containsInAnyOrder("Hello", "World"); - } - - @Test - public void testLongStringEncoding() throws Exception { - StringUtf8Coder coder = StringUtf8Coder.of(); - - // Java's DataOutputStream.writeUTF fails at 64k, so test well beyond that. - char[] chars = new char[100 * 1024]; - Arrays.fill(chars, 'o'); - String source = new String(chars); - - // Verify OUTER encoding. - assertEquals(source, CoderUtils.decodeFromByteArray(coder, - CoderUtils.encodeToByteArray(coder, source))); - - // Second string uses a UTF8 character. Each codepoint is translated into - // 4 characters in UTF8. - int[] codePoints = new int[20 * 1024]; - Arrays.fill(codePoints, 0x1D50A); // "MATHEMATICAL_FRAKTUR_CAPITAL_G" - String source2 = new String(codePoints, 0, codePoints.length); - - // Verify OUTER encoding. - assertEquals(source2, CoderUtils.decodeFromByteArray(coder, - CoderUtils.encodeToByteArray(coder, source2))); - - - // Encode both strings into NESTED form. - byte[] nestedEncoding; - try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { - coder.encode(source, os, Coder.Context.NESTED); - coder.encode(source2, os, Coder.Context.NESTED); - nestedEncoding = os.toByteArray(); - } - - // Decode from NESTED form. - try (ByteArrayInputStream is = new ByteArrayInputStream(nestedEncoding)) { - assertEquals(source, coder.decode(is, Coder.Context.NESTED)); - assertEquals(source2, coder.decode(is, Coder.Context.NESTED)); - assertEquals(0, is.available()); - } - } - - @Test - public void testNullEncoding() throws Exception { - Coder coder = SerializableCoder.of(String.class); - byte[] encodedBytes = CoderUtils.encodeToByteArray(coder, null); - assertNull(CoderUtils.decodeFromByteArray(coder, encodedBytes)); - } - - @Test - public void testMixedWithNullsEncoding() throws Exception { - Coder coder = SerializableCoder.of(String.class); - byte[] encodedBytes; - try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { - coder.encode(null, os, Coder.Context.NESTED); - coder.encode("TestValue", os, Coder.Context.NESTED); - coder.encode(null, os, Coder.Context.NESTED); - coder.encode("TestValue2", os, Coder.Context.NESTED); - coder.encode(null, os, Coder.Context.NESTED); - encodedBytes = os.toByteArray(); - } - - try (ByteArrayInputStream is = new ByteArrayInputStream(encodedBytes)) { - assertNull(coder.decode(is, Coder.Context.NESTED)); - assertEquals("TestValue", coder.decode(is, Coder.Context.NESTED)); - assertNull(coder.decode(is, Coder.Context.NESTED)); - assertEquals("TestValue2", coder.decode(is, Coder.Context.NESTED)); - assertNull(coder.decode(is, Coder.Context.NESTED)); - assertEquals(0, is.available()); - } - } - - @Test - public void testPojoEncodingId() throws Exception { - Coder coder = SerializableCoder.of(MyRecord.class); - CoderProperties.coderHasEncodingId( - coder, - String.format("%s:%s", MyRecord.class.getName(), MyRecord.serialVersionUID)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SetCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SetCoderTest.java deleted file mode 100644 index 42e560ca90..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/SetCoderTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -/** - * Test case for {@link SetCoder}. - */ -@RunWith(JUnit4.class) -public class SetCoderTest { - - private static final Coder> TEST_CODER = SetCoder.of(VarIntCoder.of()); - - private static final List> TEST_VALUES = Arrays.>asList( - Collections.emptySet(), - Collections.singleton(13), - new TreeSet<>(Arrays.asList(31, -5, 83))); - - @Test - public void testDecodeEncodeContentsEqual() throws Exception { - for (Set value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeContentsEqual(TEST_CODER, value); - } - } - - // If this changes, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "AAAAAA", - "AAAAAQ0", - "AAAAA_v___8PH1M"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Set"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StandardCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StandardCoderTest.java deleted file mode 100644 index 8a14374712..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StandardCoderTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Test case for {@link StandardCoder}. - */ -@RunWith(JUnit4.class) -public class StandardCoderTest { - - /** - * A coder for nullable {@code Boolean} values that is consistent with equals. - */ - private static class NullBooleanCoder extends StandardCoder { - - private static final long serialVersionUID = 0L; - - @Override - public void encode(@Nullable Boolean value, OutputStream outStream, Context context) - throws CoderException, IOException { - if (value == null) { - outStream.write(2); - } else if (value) { - outStream.write(1); - } else { - outStream.write(0); - } - } - - @Override - @Nullable - public Boolean decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - int value = inStream.read(); - if (value == 0) { - return false; - } else if (value == 1) { - return true; - } else if (value == 2) { - return null; - } - throw new CoderException("Invalid value for nullable Boolean: " + value); - } - - @Override - public List> getCoderArguments() { - return Collections.emptyList(); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { } - - @Override - public boolean consistentWithEquals() { - return true; - } - } - - /** - * A boxed {@code int} with {@code equals()} that compares object identity. - */ - private static class ObjectIdentityBoolean { - private final boolean value; - public ObjectIdentityBoolean(boolean value) { - this.value = value; - } - public boolean getValue() { - return value; - } - } - - /** - * A coder for nullable boxed {@code Boolean} values that is not consistent with equals. - */ - private static class ObjectIdentityBooleanCoder extends StandardCoder { - - private static final long serialVersionUID = 0L; - - @Override - public void encode( - @Nullable ObjectIdentityBoolean value, OutputStream outStream, Context context) - throws CoderException, IOException { - if (value == null) { - outStream.write(2); - } else if (value.getValue()){ - outStream.write(1); - } else { - outStream.write(0); - } - } - - @Override - @Nullable - public ObjectIdentityBoolean decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - int value = inStream.read(); - if (value == 0) { - return new ObjectIdentityBoolean(false); - } else if (value == 1) { - return new ObjectIdentityBoolean(true); - } else if (value == 2) { - return null; - } - throw new CoderException("Invalid value for nullable Boolean: " + value); - } - - @Override - public List> getCoderArguments() { - return Collections.emptyList(); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { } - - @Override - public boolean consistentWithEquals() { - return false; - } - } - - /** - * Tests that {@link StandardCoder#structuralValue()} is correct whenever a subclass has a correct - * {@link Coder#consistentWithEquals()}. - */ - @Test - public void testStructuralValue() throws Exception { - List testBooleans = Arrays.asList(null, true, false); - List testInconsistentBooleans = - Arrays.asList(null, new ObjectIdentityBoolean(true), new ObjectIdentityBoolean(false)); - - Coder consistentCoder = new NullBooleanCoder(); - for (Boolean value1 : testBooleans) { - for (Boolean value2 : testBooleans) { - CoderProperties.structuralValueConsistentWithEquals(consistentCoder, value1, value2); - } - } - - Coder inconsistentCoder = new ObjectIdentityBooleanCoder(); - for (ObjectIdentityBoolean value1 : testInconsistentBooleans) { - for (ObjectIdentityBoolean value2 : testInconsistentBooleans) { - CoderProperties.structuralValueConsistentWithEquals(inconsistentCoder, value1, value2); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoderTest.java deleted file mode 100644 index 46b3997b20..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringDelegateCoderTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.net.URI; -import java.util.Arrays; -import java.util.List; - -/** Unit tests for {@link StringDelegateCoder}. */ -@RunWith(JUnit4.class) -public class StringDelegateCoderTest { - - // Test data - - private static final Coder uriCoder = StringDelegateCoder.of(URI.class); - - private static final List TEST_URI_STRINGS = Arrays.asList( - "http://www.example.com", - "gs://myproject/mybucket/some/gcs/path", - "/just/some/path", - "file:/path/with/no/authority", - "file:///path/with/empty/authority"); - - // Tests - - @Test - public void testDeterministic() throws Exception, NonDeterministicException { - uriCoder.verifyDeterministic(); - for (String uriString : TEST_URI_STRINGS) { - CoderProperties.coderDeterministic(uriCoder, new URI(uriString), new URI(uriString)); - } - } - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (String uriString : TEST_URI_STRINGS) { - CoderProperties.coderDecodeEncodeEqual(uriCoder, new URI(uriString)); - } - } - - @Test - public void testSerializable() throws Exception { - CoderProperties.coderSerializable(uriCoder); - } - - @Test - public void testEncodingId() throws Exception { - StringDelegateCoder coder = StringDelegateCoder.of(URI.class); - CoderProperties.coderHasEncodingId(coder, URI.class.getName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringUtf8CoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringUtf8CoderTest.java deleted file mode 100644 index 7f40fc0bfd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StringUtf8CoderTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link StringUtf8Coder}. - */ -@RunWith(JUnit4.class) -public class StringUtf8CoderTest { - - private static final Coder TEST_CODER = StringUtf8Coder.of(); - - private static final List TEST_VALUES = Arrays.asList( - "", "a", "13", "hello", - "a longer string with spaces and all that", - "a string with a \n newline", - "スタリング"); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (String value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "", - "YQ", - "MTM", - "aGVsbG8", - "YSBsb25nZXIgc3RyaW5nIHdpdGggc3BhY2VzIGFuZCBhbGwgdGhhdA", - "YSBzdHJpbmcgd2l0aCBhIAogbmV3bGluZQ", - "44K544K_44Oq44Oz44Kw"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null String"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java deleted file mode 100644 index 8f8cd8cb08..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/StructuralByteArrayTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link StructuralByteArray}. - */ -@RunWith(JUnit4.class) -public final class StructuralByteArrayTest { - - @Test - public void testStructuralByteArray() throws Exception { - assertEquals( - new StructuralByteArray("test string".getBytes()), - new StructuralByteArray("test string".getBytes())); - assertFalse(new StructuralByteArray("test string".getBytes()).equals( - new StructuralByteArray("diff string".getBytes()))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoderTest.java deleted file mode 100644 index d376928823..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TableRowJsonCoderTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link TableRowJsonCoder}. - */ -@RunWith(JUnit4.class) -public class TableRowJsonCoderTest { - - private static class TableRowBuilder { - private TableRow row; - public TableRowBuilder() { - row = new TableRow(); - } - public TableRowBuilder set(String fieldName, Object value) { - row.set(fieldName, value); - return this; - } - public TableRow build() { - return row; - } - } - - private static final Coder TEST_CODER = TableRowJsonCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - new TableRowBuilder().build(), - new TableRowBuilder().set("a", "1").build(), - new TableRowBuilder().set("b", 3.14).build(), - new TableRowBuilder().set("a", "1").set("b", true).set("c", "hi").build()); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (TableRow value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // This identifier should only change if the JSON format of results from the BigQuery API changes. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "e30", - "eyJhIjoiMSJ9", - "eyJiIjozLjE0fQ", - "eyJhIjoiMSIsImIiOnRydWUsImMiOiJoaSJ9"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoderTest.java deleted file mode 100644 index 5ccff309d6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/TextualIntegerCoderTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link TextualIntegerCoder}. - */ -@RunWith(JUnit4.class) -public class TextualIntegerCoderTest { - - private static final Coder TEST_CODER = TextualIntegerCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - -11, -3, -1, 0, 1, 5, 13, 29, - Integer.MAX_VALUE, - Integer.MIN_VALUE); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Integer value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // This should never change. The textual representation of an integer is fixed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "LTEx", - "LTM", - "LTE", - "MA", - "MQ", - "NQ", - "MTM", - "Mjk", - "MjE0NzQ4MzY0Nw", - "LTIxNDc0ODM2NDg"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Integer"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarIntCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarIntCoderTest.java deleted file mode 100644 index cce3280361..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarIntCoderTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link VarIntCoder}. - */ -@RunWith(JUnit4.class) -public class VarIntCoderTest { - - private static final Coder TEST_CODER = VarIntCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - -11, -3, -1, 0, 1, 5, 13, 29, - Integer.MAX_VALUE, - Integer.MIN_VALUE); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Integer value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // If this changes, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "9f___w8", - "_f___w8", - "_____w8", - "AA", - "AQ", - "BQ", - "DQ", - "HQ", - "_____wc", - "gICAgAg"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Integer"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarLongCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarLongCoderTest.java deleted file mode 100644 index a371af3dfe..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/VarLongCoderTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Test case for {@link VarLongCoder}. - */ -@RunWith(JUnit4.class) -public class VarLongCoderTest { - - private static final Coder TEST_CODER = VarLongCoder.of(); - - private static final List TEST_VALUES = Arrays.asList( - -11L, -3L, -1L, 0L, 1L, 5L, 13L, 29L, - Integer.MAX_VALUE + 131L, - Integer.MIN_VALUE - 29L, - Long.MAX_VALUE, - Long.MIN_VALUE); - - @Test - public void testDecodeEncodeEqual() throws Exception { - for (Long value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - // If this changes, it implies the binary format has changed. - private static final String EXPECTED_ENCODING_ID = ""; - - @Test - public void testEncodingId() throws Exception { - CoderProperties.coderHasEncodingId(TEST_CODER, EXPECTED_ENCODING_ID); - } - - /** - * Generated data to check that the wire format has not changed. To regenerate, see - * {@link com.google.cloud.dataflow.sdk.coders.PrintBase64Encodings}. - */ - private static final List TEST_ENCODINGS = Arrays.asList( - "9f__________AQ", - "_f__________AQ", - "____________AQ", - "AA", - "AQ", - "BQ", - "DQ", - "HQ", - "goGAgAg", - "4_____f_____AQ", - "__________9_", - "gICAgICAgICAAQ"); - - @Test - public void testWireFormatEncode() throws Exception { - CoderProperties.coderEncodesBase64(TEST_CODER, TEST_VALUES, TEST_ENCODINGS); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null Long"); - - CoderUtils.encodeToBase64(TEST_CODER, null); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java deleted file mode 100644 index 6f4e99d388..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoderTest.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageB; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageC; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageWithMap; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link ProtoCoder}. - */ -@RunWith(JUnit4.class) -public class ProtoCoderTest { - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testFactoryMethodAgreement() throws Exception { - assertEquals(ProtoCoder.of(new TypeDescriptor() {}), ProtoCoder.of(MessageA.class)); - - assertEquals( - ProtoCoder.of(new TypeDescriptor() {}), - ProtoCoder.coderProvider().getCoder(new TypeDescriptor() {})); - } - - @Test - public void testProviderCannotProvideCoder() throws Exception { - thrown.expect(CannotProvideCoderException.class); - thrown.expectMessage("java.lang.Integer is not a subclass of com.google.protobuf.Message"); - - ProtoCoder.coderProvider().getCoder(new TypeDescriptor() {}); - } - - @Test - public void testCoderEncodeDecodeEqual() throws Exception { - MessageA value = - MessageA.newBuilder() - .setField1("hello") - .addField2(MessageB.newBuilder().setField1(true).build()) - .addField2(MessageB.newBuilder().setField1(false).build()) - .build(); - CoderProperties.coderDecodeEncodeEqual(ProtoCoder.of(MessageA.class), value); - } - - @Test - public void testCoderEncodeDecodeEqualNestedContext() throws Exception { - MessageA value1 = - MessageA.newBuilder() - .setField1("hello") - .addField2(MessageB.newBuilder().setField1(true).build()) - .addField2(MessageB.newBuilder().setField1(false).build()) - .build(); - MessageA value2 = - MessageA.newBuilder() - .setField1("world") - .addField2(MessageB.newBuilder().setField1(false).build()) - .addField2(MessageB.newBuilder().setField1(true).build()) - .build(); - CoderProperties.coderDecodeEncodeEqual( - ListCoder.of(ProtoCoder.of(MessageA.class)), ImmutableList.of(value1, value2)); - } - - @Test - public void testCoderEncodeDecodeExtensionsEqual() throws Exception { - MessageC value = - MessageC.newBuilder() - .setExtension( - Proto2CoderTestMessages.field1, - MessageA.newBuilder() - .setField1("hello") - .addField2(MessageB.newBuilder().setField1(true).build()) - .build()) - .setExtension( - Proto2CoderTestMessages.field2, MessageB.newBuilder().setField1(false).build()) - .build(); - CoderProperties.coderDecodeEncodeEqual( - ProtoCoder.of(MessageC.class).withExtensionsFrom(Proto2CoderTestMessages.class), value); - } - - @Test - public void testCoderSerialization() throws Exception { - ProtoCoder coder = ProtoCoder.of(MessageA.class); - CoderProperties.coderSerializable(coder); - } - - @Test - public void testCoderExtensionsSerialization() throws Exception { - ProtoCoder coder = - ProtoCoder.of(MessageC.class).withExtensionsFrom(Proto2CoderTestMessages.class); - CoderProperties.coderSerializable(coder); - } - - @Test - public void testEncodingId() throws Exception { - Coder coderA = ProtoCoder.of(MessageA.class); - CoderProperties.coderHasEncodingId(coderA, MessageA.class.getName() + "[]"); - - ProtoCoder coder = - ProtoCoder.of(MessageC.class).withExtensionsFrom(Proto2CoderTestMessages.class); - CoderProperties.coderHasEncodingId( - coder, - String.format("%s[%s]", MessageC.class.getName(), Proto2CoderTestMessages.class.getName())); - } - - @Test - public void encodeNullThrowsCoderException() throws Exception { - thrown.expect(CoderException.class); - thrown.expectMessage("cannot encode a null MessageA"); - - CoderUtils.encodeToBase64(ProtoCoder.of(MessageA.class), null); - } - - @Test - public void testDeterministicCoder() throws NonDeterministicException { - Coder coder = ProtoCoder.of(MessageA.class); - coder.verifyDeterministic(); - } - - @Test - public void testNonDeterministicCoder() throws NonDeterministicException { - thrown.expect(NonDeterministicException.class); - thrown.expectMessage(MessageWithMap.class.getName() + " transitively includes Map field"); - - Coder coder = ProtoCoder.of(MessageWithMap.class); - coder.verifyDeterministic(); - } - - @Test - public void testNonDeterministicProperty() throws CoderException { - MessageWithMap.Builder msg1B = MessageWithMap.newBuilder(); - MessageWithMap.Builder msg2B = MessageWithMap.newBuilder(); - - // Built in reverse order but with equal contents. - for (int i = 0; i < 10; ++i) { - msg1B.getMutableField1().put("key" + i, MessageA.getDefaultInstance()); - msg2B.getMutableField1().put("key" + (9 - i), MessageA.getDefaultInstance()); - } - - // Assert the messages are equal. - MessageWithMap msg1 = msg1B.build(); - MessageWithMap msg2 = msg2B.build(); - assertEquals(msg2, msg1); - - // Assert the encoded messages are not equal. - Coder coder = ProtoCoder.of(MessageWithMap.class); - assertNotEquals(CoderUtils.encodeToBase64(coder, msg2), CoderUtils.encodeToBase64(coder, msg1)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java deleted file mode 100644 index f6693f0fc8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtilTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.coders.protobuf; - -import static com.google.cloud.dataflow.sdk.coders.protobuf.ProtobufUtil.checkProto2Syntax; -import static com.google.cloud.dataflow.sdk.coders.protobuf.ProtobufUtil.getRecursiveDescriptorsForClass; -import static com.google.cloud.dataflow.sdk.coders.protobuf.ProtobufUtil.verifyDeterministic; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageA; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageB; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageC; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.MessageWithMap; -import com.google.cloud.dataflow.sdk.coders.Proto2CoderTestMessages.ReferencesMessageWithMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; -import com.google.protobuf.Any; -import com.google.protobuf.Descriptors.GenericDescriptor; -import com.google.protobuf.Duration; -import com.google.protobuf.ExtensionRegistry; -import com.google.protobuf.Message; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.HashSet; -import java.util.Set; - -/** - * Tests for {@link ProtobufUtil}. - */ -@RunWith(JUnit4.class) -public class ProtobufUtilTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - private static final Set MESSAGE_A_ONLY = - ImmutableSet.of("proto2_coder_test_messages.MessageA"); - - private static final Set MESSAGE_B_ONLY = - ImmutableSet.of("proto2_coder_test_messages.MessageB"); - - private static final Set MESSAGE_C_ONLY = - ImmutableSet.of("proto2_coder_test_messages.MessageC"); - - // map fields are actually represented as a nested Message in generated Java code. - private static final Set WITH_MAP_ONLY = - ImmutableSet.of( - "proto2_coder_test_messages.MessageWithMap", - "proto2_coder_test_messages.MessageWithMap.Field1Entry"); - - private static final Set REFERS_MAP_ONLY = - ImmutableSet.of("proto2_coder_test_messages.ReferencesMessageWithMap"); - - // A references A and B. - private static final Set MESSAGE_A_ALL = Sets.union(MESSAGE_A_ONLY, MESSAGE_B_ONLY); - - // C, only with registered extensions, references A. - private static final Set MESSAGE_C_EXT = Sets.union(MESSAGE_C_ONLY, MESSAGE_A_ALL); - - // MessageWithMap references A. - private static final Set WITH_MAP_ALL = Sets.union(WITH_MAP_ONLY, MESSAGE_A_ALL); - - // ReferencesMessageWithMap references MessageWithMap. - private static final Set REFERS_MAP_ALL = Sets.union(REFERS_MAP_ONLY, WITH_MAP_ALL); - - @Test - public void testRecursiveDescriptorsMessageA() { - assertThat(getRecursiveDescriptorFullNames(MessageA.class), equalTo(MESSAGE_A_ALL)); - } - - @Test - public void testRecursiveDescriptorsMessageB() { - assertThat(getRecursiveDescriptorFullNames(MessageB.class), equalTo(MESSAGE_B_ONLY)); - } - - @Test - public void testRecursiveDescriptorsMessageC() { - assertThat(getRecursiveDescriptorFullNames(MessageC.class), equalTo(MESSAGE_C_ONLY)); - } - - @Test - public void testRecursiveDescriptorsMessageCWithExtensions() { - // With extensions, Message C has a reference to Message A and Message B. - ExtensionRegistry registry = ExtensionRegistry.newInstance(); - Proto2CoderTestMessages.registerAllExtensions(registry); - assertThat(getRecursiveDescriptorFullNames(MessageC.class, registry), equalTo(MESSAGE_C_EXT)); - } - - @Test - public void testRecursiveDescriptorsMessageWithMap() { - assertThat(getRecursiveDescriptorFullNames(MessageWithMap.class), equalTo(WITH_MAP_ALL)); - } - - @Test - public void testRecursiveDescriptorsReferencesMessageWithMap() { - assertThat( - getRecursiveDescriptorFullNames(ReferencesMessageWithMap.class), equalTo(REFERS_MAP_ALL)); - } - - @Test - public void testVerifyProto2() { - // Everything in Dataflow's Proto2TestMessages uses Proto2 syntax. - checkProto2Syntax(MessageA.class, ExtensionRegistry.getEmptyRegistry()); - checkProto2Syntax(MessageB.class, ExtensionRegistry.getEmptyRegistry()); - checkProto2Syntax(MessageC.class, ExtensionRegistry.getEmptyRegistry()); - checkProto2Syntax(MessageWithMap.class, ExtensionRegistry.getEmptyRegistry()); - checkProto2Syntax(ReferencesMessageWithMap.class, ExtensionRegistry.getEmptyRegistry()); - } - - @Test - public void testAnyIsNotProto2() { - // Any is a core Protocol Buffers type that uses proto3 syntax. - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(Any.class.getCanonicalName()); - thrown.expectMessage("in file " + Any.getDescriptor().getFile().getName()); - - checkProto2Syntax(Any.class, ExtensionRegistry.getEmptyRegistry()); - } - - @Test - public void testDurationIsNotProto2() { - // Duration is a core Protocol Buffers type that uses proto3 syntax. - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(Duration.class.getCanonicalName()); - thrown.expectMessage("in file " + Duration.getDescriptor().getFile().getName()); - - checkProto2Syntax(Duration.class, ExtensionRegistry.getEmptyRegistry()); - } - - @Test - public void testDurationIsDeterministic() throws NonDeterministicException { - // Duration can be encoded deterministically. - verifyDeterministic(ProtoCoder.of(Duration.class)); - } - - @Test - public void testMessageWithMapIsNotDeterministic() throws NonDeterministicException { - String mapFieldName = MessageWithMap.getDescriptor().findFieldByNumber(1).getFullName(); - thrown.expect(NonDeterministicException.class); - thrown.expectMessage(MessageWithMap.class.getName()); - thrown.expectMessage("transitively includes Map field " + mapFieldName); - thrown.expectMessage("file " + MessageWithMap.getDescriptor().getFile().getName()); - - verifyDeterministic(ProtoCoder.of(MessageWithMap.class)); - } - - @Test - public void testMessageWithTransitiveMapIsNotDeterministic() throws NonDeterministicException { - String mapFieldName = MessageWithMap.getDescriptor().findFieldByNumber(1).getFullName(); - thrown.expect(NonDeterministicException.class); - thrown.expectMessage(ReferencesMessageWithMap.class.getName()); - thrown.expectMessage("transitively includes Map field " + mapFieldName); - thrown.expectMessage("file " + MessageWithMap.getDescriptor().getFile().getName()); - - verifyDeterministic(ProtoCoder.of(ReferencesMessageWithMap.class)); - } - - //////////////////////////////////////////////////////////////////////////////////////////// - - /** Helper used to test the recursive class traversal and print good error messages. */ - private static Set getRecursiveDescriptorFullNames(Class clazz) { - return getRecursiveDescriptorFullNames(clazz, ExtensionRegistry.getEmptyRegistry()); - } - - /** Helper used to test the recursive class traversal and print good error messages. */ - private static Set getRecursiveDescriptorFullNames( - Class clazz, ExtensionRegistry registry) { - Set result = new HashSet<>(); - for (GenericDescriptor d : getRecursiveDescriptorsForClass(clazz, registry)) { - result.add(d.getFullName()); - } - return result; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java deleted file mode 100644 index 6a7679f5ed..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOGeneratedClassTest.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.runners.DirectPipeline; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.EvaluationResults; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.apache.avro.Schema; -import org.apache.avro.file.DataFileReader; -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.generic.GenericData; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.DatumReader; -import org.apache.avro.io.DatumWriter; -import org.apache.avro.specific.SpecificDatumReader; -import org.apache.avro.specific.SpecificDatumWriter; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Tests for AvroIO Read and Write transforms, using classes generated from {@code user.avsc}. - */ -@RunWith(JUnit4.class) -public class AvroIOGeneratedClassTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - private File avroFile; - - @Before - public void prepareAvroFileBeforeAnyTest() throws IOException { - avroFile = tmpFolder.newFile("file.avro"); - } - - private final String schemaString = - "{\"namespace\": \"example.avro\",\n" - + " \"type\": \"record\",\n" - + " \"name\": \"AvroGeneratedUser\",\n" - + " \"fields\": [\n" - + " {\"name\": \"name\", \"type\": \"string\"},\n" - + " {\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]},\n" - + " {\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]}\n" - + " ]\n" - + "}"; - private final Schema.Parser parser = new Schema.Parser(); - private final Schema schema = parser.parse(schemaString); - - private AvroGeneratedUser[] generateAvroObjects() { - AvroGeneratedUser user1 = new AvroGeneratedUser(); - user1.setName("Bob"); - user1.setFavoriteNumber(256); - - AvroGeneratedUser user2 = new AvroGeneratedUser(); - user2.setName("Alice"); - user2.setFavoriteNumber(128); - - AvroGeneratedUser user3 = new AvroGeneratedUser(); - user3.setName("Ted"); - user3.setFavoriteColor("white"); - - return new AvroGeneratedUser[] { user1, user2, user3 }; - } - - private GenericRecord[] generateAvroGenericRecords() { - GenericRecord user1 = new GenericData.Record(schema); - user1.put("name", "Bob"); - user1.put("favorite_number", 256); - - GenericRecord user2 = new GenericData.Record(schema); - user2.put("name", "Alice"); - user2.put("favorite_number", 128); - - GenericRecord user3 = new GenericData.Record(schema); - user3.put("name", "Ted"); - user3.put("favorite_color", "white"); - - return new GenericRecord[] { user1, user2, user3 }; - } - - private void generateAvroFile(AvroGeneratedUser[] elements) throws IOException { - DatumWriter userDatumWriter = - new SpecificDatumWriter<>(AvroGeneratedUser.class); - try (DataFileWriter dataFileWriter = new DataFileWriter<>(userDatumWriter)) { - dataFileWriter.create(elements[0].getSchema(), avroFile); - for (AvroGeneratedUser user : elements) { - dataFileWriter.append(user); - } - } - } - - private List readAvroFile() throws IOException { - DatumReader userDatumReader = - new SpecificDatumReader<>(AvroGeneratedUser.class); - List users = new ArrayList<>(); - try (DataFileReader dataFileReader = - new DataFileReader<>(avroFile, userDatumReader)) { - while (dataFileReader.hasNext()) { - users.add(dataFileReader.next()); - } - } - return users; - } - - void runTestRead(AvroIO.Read.Bound read, String expectedName, T[] expectedOutput) - throws Exception { - generateAvroFile(generateAvroObjects()); - - DirectPipeline p = DirectPipeline.createForTest(); - PCollection output = p.apply(read); - EvaluationResults results = p.run(); - assertEquals(expectedName, output.getName()); - assertThat(results.getPCollection(output), - containsInAnyOrder(expectedOutput)); - } - - @Test - public void testReadFromGeneratedClass() throws Exception { - runTestRead( - AvroIO.Read.from(avroFile.getPath()).withSchema(AvroGeneratedUser.class), - "AvroIO.Read/Read.out", - generateAvroObjects()); - runTestRead( - AvroIO.Read.withSchema(AvroGeneratedUser.class).from(avroFile.getPath()), - "AvroIO.Read/Read.out", - generateAvroObjects()); - runTestRead( - AvroIO.Read.named("MyRead").from(avroFile.getPath()).withSchema(AvroGeneratedUser.class), - "MyRead/Read.out", - generateAvroObjects()); - runTestRead( - AvroIO.Read.named("MyRead").withSchema(AvroGeneratedUser.class).from(avroFile.getPath()), - "MyRead/Read.out", - generateAvroObjects()); - runTestRead( - AvroIO.Read.from(avroFile.getPath()).withSchema(AvroGeneratedUser.class).named("HerRead"), - "HerRead/Read.out", - generateAvroObjects()); - runTestRead( - AvroIO.Read.from(avroFile.getPath()).named("HerRead").withSchema(AvroGeneratedUser.class), - "HerRead/Read.out", - generateAvroObjects()); - runTestRead( - AvroIO.Read.withSchema(AvroGeneratedUser.class).named("HerRead").from(avroFile.getPath()), - "HerRead/Read.out", - generateAvroObjects()); - runTestRead( - AvroIO.Read.withSchema(AvroGeneratedUser.class).from(avroFile.getPath()).named("HerRead"), - "HerRead/Read.out", - generateAvroObjects()); - } - - @Test - public void testReadFromSchema() throws Exception { - runTestRead( - AvroIO.Read.from(avroFile.getPath()).withSchema(schema), - "AvroIO.Read/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.withSchema(schema).from(avroFile.getPath()), - "AvroIO.Read/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.named("MyRead").from(avroFile.getPath()).withSchema(schema), - "MyRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.named("MyRead").withSchema(schema).from(avroFile.getPath()), - "MyRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.from(avroFile.getPath()).withSchema(schema).named("HerRead"), - "HerRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.from(avroFile.getPath()).named("HerRead").withSchema(schema), - "HerRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.withSchema(schema).named("HerRead").from(avroFile.getPath()), - "HerRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.withSchema(schema).from(avroFile.getPath()).named("HerRead"), - "HerRead/Read.out", - generateAvroGenericRecords()); - } - - @Test - public void testReadFromSchemaString() throws Exception { - runTestRead( - AvroIO.Read.from(avroFile.getPath()).withSchema(schemaString), - "AvroIO.Read/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.withSchema(schemaString).from(avroFile.getPath()), - "AvroIO.Read/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.named("MyRead").from(avroFile.getPath()).withSchema(schemaString), - "MyRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.named("MyRead").withSchema(schemaString).from(avroFile.getPath()), - "MyRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.from(avroFile.getPath()).withSchema(schemaString).named("HerRead"), - "HerRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.from(avroFile.getPath()).named("HerRead").withSchema(schemaString), - "HerRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.withSchema(schemaString).named("HerRead").from(avroFile.getPath()), - "HerRead/Read.out", - generateAvroGenericRecords()); - runTestRead( - AvroIO.Read.withSchema(schemaString).from(avroFile.getPath()).named("HerRead"), - "HerRead/Read.out", - generateAvroGenericRecords()); - } - - void runTestWrite(AvroIO.Write.Bound write, String expectedName) - throws Exception { - AvroGeneratedUser[] users = generateAvroObjects(); - - DirectPipeline p = DirectPipeline.createForTest(); - @SuppressWarnings("unchecked") - PCollection input = p.apply(Create.of(Arrays.asList((T[]) users)) - .withCoder((Coder) AvroCoder.of(AvroGeneratedUser.class))); - input.apply(write.withoutSharding()); - p.run(); - assertEquals(expectedName, write.getName()); - - assertThat(readAvroFile(), containsInAnyOrder(users)); - } - - @Test - public void testWriteFromGeneratedClass() throws Exception { - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .withSchema(AvroGeneratedUser.class), - "AvroIO.Write"); - runTestWrite(AvroIO.Write.withSchema(AvroGeneratedUser.class) - .to(avroFile.getPath()), - "AvroIO.Write"); - runTestWrite(AvroIO.Write.named("MyWrite") - .to(avroFile.getPath()) - .withSchema(AvroGeneratedUser.class), - "MyWrite"); - runTestWrite(AvroIO.Write.named("MyWrite") - .withSchema(AvroGeneratedUser.class) - .to(avroFile.getPath()), - "MyWrite"); - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .withSchema(AvroGeneratedUser.class) - .named("HerWrite"), - "HerWrite"); - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .named("HerWrite") - .withSchema(AvroGeneratedUser.class), - "HerWrite"); - runTestWrite(AvroIO.Write.withSchema(AvroGeneratedUser.class) - .named("HerWrite") - .to(avroFile.getPath()), - "HerWrite"); - runTestWrite(AvroIO.Write.withSchema(AvroGeneratedUser.class) - .to(avroFile.getPath()) - .named("HerWrite"), - "HerWrite"); - } - - @Test - public void testWriteFromSchema() throws Exception { - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .withSchema(schema), - "AvroIO.Write"); - runTestWrite(AvroIO.Write.withSchema(schema) - .to(avroFile.getPath()), - "AvroIO.Write"); - runTestWrite(AvroIO.Write.named("MyWrite") - .to(avroFile.getPath()) - .withSchema(schema), - "MyWrite"); - runTestWrite(AvroIO.Write.named("MyWrite") - .withSchema(schema) - .to(avroFile.getPath()), - "MyWrite"); - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .withSchema(schema) - .named("HerWrite"), - "HerWrite"); - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .named("HerWrite") - .withSchema(schema), - "HerWrite"); - runTestWrite(AvroIO.Write.withSchema(schema) - .named("HerWrite") - .to(avroFile.getPath()), - "HerWrite"); - runTestWrite(AvroIO.Write.withSchema(schema) - .to(avroFile.getPath()) - .named("HerWrite"), - "HerWrite"); - } - - @Test - public void testWriteFromSchemaString() throws Exception { - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .withSchema(schemaString), - "AvroIO.Write"); - runTestWrite(AvroIO.Write.withSchema(schemaString) - .to(avroFile.getPath()), - "AvroIO.Write"); - runTestWrite(AvroIO.Write.named("MyWrite") - .to(avroFile.getPath()) - .withSchema(schemaString), - "MyWrite"); - runTestWrite(AvroIO.Write.named("MyWrite") - .withSchema(schemaString) - .to(avroFile.getPath()), - "MyWrite"); - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .withSchema(schemaString) - .named("HerWrite"), - "HerWrite"); - runTestWrite(AvroIO.Write.to(avroFile.getPath()) - .named("HerWrite") - .withSchema(schemaString), - "HerWrite"); - runTestWrite(AvroIO.Write.withSchema(schemaString) - .named("HerWrite") - .to(avroFile.getPath()), - "HerWrite"); - runTestWrite(AvroIO.Write.withSchema(schemaString) - .to(avroFile.getPath()) - .named("HerWrite"), - "HerWrite"); - } - - // TODO: for Write only, test withSuffix, withNumShards, - // withShardNameTemplate and withoutSharding. -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java deleted file mode 100644 index 9c155e2515..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroIOTest.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO.Write.Bound; -import com.google.cloud.dataflow.sdk.runners.DirectPipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterators; - -import org.apache.avro.Schema; -import org.apache.avro.file.DataFileReader; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.reflect.Nullable; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * Tests for AvroIO Read and Write transforms. - */ -@RunWith(JUnit4.class) -public class AvroIOTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Test - public void testReadWithoutValidationFlag() throws Exception { - AvroIO.Read.Bound read = AvroIO.Read.from("gs://bucket/foo*/baz"); - assertTrue(read.needsValidation()); - assertFalse(read.withoutValidation().needsValidation()); - } - - @Test - public void testWriteWithoutValidationFlag() throws Exception { - AvroIO.Write.Bound write = AvroIO.Write.to("gs://bucket/foo/baz"); - assertTrue(write.needsValidation()); - assertFalse(write.withoutValidation().needsValidation()); - } - - @Test - public void testAvroIOGetName() { - assertEquals("AvroIO.Read", AvroIO.Read.from("gs://bucket/foo*/baz").getName()); - assertEquals("AvroIO.Write", AvroIO.Write.to("gs://bucket/foo/baz").getName()); - assertEquals("ReadMyFile", - AvroIO.Read.named("ReadMyFile").from("gs://bucket/foo*/baz").getName()); - assertEquals("WriteMyFile", - AvroIO.Write.named("WriteMyFile").to("gs://bucket/foo/baz").getName()); - } - - @DefaultCoder(AvroCoder.class) - static class GenericClass { - int intField; - String stringField; - public GenericClass() {} - public GenericClass(int intValue, String stringValue) { - this.intField = intValue; - this.stringField = stringValue; - } - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("intField", intField) - .add("stringField", stringField) - .toString(); - } - @Override - public int hashCode() { - return Objects.hash(intField, stringField); - } - @Override - public boolean equals(Object other) { - if (other == null || !(other instanceof GenericClass)) { - return false; - } - GenericClass o = (GenericClass) other; - return Objects.equals(intField, o.intField) && Objects.equals(stringField, o.stringField); - } - } - - @Test - public void testAvroIOWriteAndReadASingleFile() throws Throwable { - DirectPipeline p = DirectPipeline.createForTest(); - List values = ImmutableList.of(new GenericClass(3, "hi"), - new GenericClass(5, "bar")); - File outputFile = tmpFolder.newFile("output.avro"); - - p.apply(Create.of(values)) - .apply(AvroIO.Write.to(outputFile.getAbsolutePath()) - .withoutSharding() - .withSchema(GenericClass.class)); - p.run(); - - p = DirectPipeline.createForTest(); - PCollection input = p - .apply(AvroIO.Read.from(outputFile.getAbsolutePath()).withSchema(GenericClass.class)); - - DataflowAssert.that(input).containsInAnyOrder(values); - p.run(); - } - - @DefaultCoder(AvroCoder.class) - static class GenericClassV2 { - int intField; - String stringField; - @Nullable String nullableField; - public GenericClassV2() {} - public GenericClassV2(int intValue, String stringValue, String nullableValue) { - this.intField = intValue; - this.stringField = stringValue; - this.nullableField = nullableValue; - } - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("intField", intField) - .add("stringField", stringField) - .add("nullableField", nullableField) - .toString(); - } - @Override - public int hashCode() { - return Objects.hash(intField, stringField, nullableField); - } - @Override - public boolean equals(Object other) { - if (other == null || !(other instanceof GenericClassV2)) { - return false; - } - GenericClassV2 o = (GenericClassV2) other; - return Objects.equals(intField, o.intField) - && Objects.equals(stringField, o.stringField) - && Objects.equals(nullableField, o.nullableField); - } - } - - /** - * Tests that {@code AvroIO} can read an upgraded version of an old class, as long as the - * schema resolution process succeeds. This test covers the case when a new, {@code @Nullable} - * field has been added. - * - *

              For more information, see http://avro.apache.org/docs/1.7.7/spec.html#Schema+Resolution - */ - @Test - public void testAvroIOWriteAndReadSchemaUpgrade() throws Throwable { - DirectPipeline p = DirectPipeline.createForTest(); - List values = ImmutableList.of(new GenericClass(3, "hi"), - new GenericClass(5, "bar")); - File outputFile = tmpFolder.newFile("output.avro"); - - p.apply(Create.of(values)) - .apply(AvroIO.Write.to(outputFile.getAbsolutePath()) - .withoutSharding() - .withSchema(GenericClass.class)); - p.run(); - - List expected = ImmutableList.of(new GenericClassV2(3, "hi", null), - new GenericClassV2(5, "bar", null)); - p = DirectPipeline.createForTest(); - PCollection input = p - .apply(AvroIO.Read.from(outputFile.getAbsolutePath()).withSchema(GenericClassV2.class)); - - DataflowAssert.that(input).containsInAnyOrder(expected); - p.run(); - } - - @SuppressWarnings("deprecation") // using AvroCoder#createDatumReader for tests. - private void runTestWrite(String[] expectedElements, int numShards) throws IOException { - File baseOutputFile = new File(tmpFolder.getRoot(), "prefix"); - String outputFilePrefix = baseOutputFile.getAbsolutePath(); - TestPipeline p = TestPipeline.create(); - Bound write = AvroIO.Write.to(outputFilePrefix).withSchema(String.class); - if (numShards > 1) { - write = write.withNumShards(numShards); - } else { - write = write.withoutSharding(); - } - p.apply(Create.of(expectedElements)).apply(write); - p.run(); - - String shardNameTemplate = write.getShardNameTemplate(); - - assertTestOutputs(expectedElements, numShards, outputFilePrefix, shardNameTemplate); - } - - public static void assertTestOutputs( - String[] expectedElements, int numShards, String outputFilePrefix, String shardNameTemplate) - throws IOException { - // Validate that the data written matches the expected elements in the expected order - List expectedFiles = new ArrayList<>(); - for (int i = 0; i < numShards; i++) { - expectedFiles.add( - new File( - IOChannelUtils.constructName( - outputFilePrefix, shardNameTemplate, "" /* no suffix */, i, numShards))); - } - - List actualElements = new ArrayList<>(); - for (File outputFile : expectedFiles) { - assertTrue("Expected output file " + outputFile.getName(), outputFile.exists()); - try (DataFileReader reader = - new DataFileReader<>(outputFile, AvroCoder.of(String.class).createDatumReader())) { - Iterators.addAll(actualElements, reader); - } - } - assertThat(actualElements, containsInAnyOrder(expectedElements)); - } - - @Test - public void testAvroSinkWrite() throws Exception { - String[] expectedElements = new String[] {"first", "second", "third"}; - - runTestWrite(expectedElements, 1); - } - - @Test - public void testAvroSinkShardedWrite() throws Exception { - String[] expectedElements = new String[] {"first", "second", "third", "fourth", "fifth"}; - - runTestWrite(expectedElements, 4); - } - // TODO: for Write only, test withSuffix, - // withShardNameTemplate and withoutSharding. - - @Test - public void testReadDisplayData() { - AvroIO.Read.Bound read = AvroIO.Read.from("foo.*") - .withoutValidation(); - - DisplayData displayData = DisplayData.from(read); - assertThat(displayData, hasDisplayItem("filePattern", "foo.*")); - assertThat(displayData, hasDisplayItem("validation", false)); - } - - @Test - public void testWriteDisplayData() { - AvroIO.Write.Bound write = AvroIO.Write - .to("foo") - .withShardNameTemplate("-SS-of-NN-") - .withSuffix("bar") - .withSchema(GenericClass.class) - .withNumShards(100) - .withoutValidation(); - - DisplayData displayData = DisplayData.from(write); - - assertThat(displayData, hasDisplayItem("filePrefix", "foo")); - assertThat(displayData, hasDisplayItem("shardNameTemplate", "-SS-of-NN-")); - assertThat(displayData, hasDisplayItem("fileSuffix", "bar")); - assertThat(displayData, hasDisplayItem("schema", GenericClass.class)); - assertThat(displayData, hasDisplayItem("numShards", 100)); - assertThat(displayData, hasDisplayItem("validation", false)); - } - - @Test - public void testPrimitiveWriteDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - - AvroIO.Write.Bound write = AvroIO.Write - .to("foo") - .withSchema(Schema.create(Schema.Type.STRING)) - .withoutValidation(); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(write); - assertThat("AvroIO.Write should include the file pattern in its primitive transform", - displayData, hasItem(hasDisplayItem("fileNamePattern"))); - } - - @Test - public void testPrimitiveReadDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - - AvroIO.Read.Bound read = AvroIO.Read.from("foo.*") - .withSchema(Schema.create(Schema.Type.STRING)) - .withoutValidation(); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(read); - assertThat("AvroIO.Read should include the file pattern in its primitive transform", - displayData, hasItem(hasDisplayItem("filePattern"))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java deleted file mode 100644 index 5141320e19..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/AvroSourceTest.java +++ /dev/null @@ -1,843 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.io.AvroSource.AvroReader; -import com.google.cloud.dataflow.sdk.io.AvroSource.AvroReader.Seeker; -import com.google.cloud.dataflow.sdk.io.BlockBasedSource.BlockBasedReader; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.AvroUtils; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.common.base.MoreObjects; - -import org.apache.avro.Schema; -import org.apache.avro.file.CodecFactory; -import org.apache.avro.file.DataFileConstants; -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.DatumWriter; -import org.apache.avro.reflect.AvroDefault; -import org.apache.avro.reflect.Nullable; -import org.apache.avro.reflect.ReflectData; -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PushbackInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Random; - -/** - * Tests for AvroSource. - */ -@RunWith(JUnit4.class) -public class AvroSourceTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - private enum SyncBehavior { - SYNC_REGULAR, // Sync at regular, user defined intervals - SYNC_RANDOM, // Sync at random intervals - SYNC_DEFAULT; // Sync at default intervals (i.e., no manual syncing). - } - - private static final int DEFAULT_RECORD_COUNT = 1000; - - /** - * Generates an input Avro file containing the given records in the temporary directory and - * returns the full path of the file. - */ - private String generateTestFile(String filename, List elems, SyncBehavior syncBehavior, - int syncInterval, AvroCoder coder, String codec) throws IOException { - Random random = new Random(0); - File tmpFile = tmpFolder.newFile(filename); - String path = tmpFile.toString(); - - FileOutputStream os = new FileOutputStream(tmpFile); - @SuppressWarnings("deprecation") // test uses internal AvroCoder code. - DatumWriter datumWriter = coder.createDatumWriter(); - try (DataFileWriter writer = new DataFileWriter<>(datumWriter)) { - writer.setCodec(CodecFactory.fromString(codec)); - writer.create(coder.getSchema(), os); - - int recordIndex = 0; - int syncIndex = syncBehavior == SyncBehavior.SYNC_RANDOM ? random.nextInt(syncInterval) : 0; - - for (T elem : elems) { - writer.append(elem); - recordIndex++; - - switch (syncBehavior) { - case SYNC_REGULAR: - if (recordIndex == syncInterval) { - recordIndex = 0; - writer.sync(); - } - break; - case SYNC_RANDOM: - if (recordIndex == syncIndex) { - recordIndex = 0; - writer.sync(); - syncIndex = random.nextInt(syncInterval); - } - break; - case SYNC_DEFAULT: - default: - } - } - } - return path; - } - - @Test - public void testReadWithDifferentCodecs() throws Exception { - // Test reading files generated using all codecs. - String codecs[] = { - DataFileConstants.NULL_CODEC, - DataFileConstants.BZIP2_CODEC, - DataFileConstants.DEFLATE_CODEC, - DataFileConstants.SNAPPY_CODEC, - DataFileConstants.XZ_CODEC, - }; - // As Avro's default block size is 64KB, write 64K records to ensure at least one full block. - // We could make this smaller than 64K assuming each record is at least B bytes, but then the - // test could silently stop testing the failure condition from BEAM-422. - List expected = createRandomRecords(1 << 16); - - for (String codec : codecs) { - String filename = generateTestFile( - codec, expected, SyncBehavior.SYNC_DEFAULT, 0, AvroCoder.of(Bird.class), codec); - AvroSource source = AvroSource.from(filename).withSchema(Bird.class); - List actual = SourceTestUtils.readFromSource(source, null); - assertThat(expected, containsInAnyOrder(actual.toArray())); - } - } - - @Test - public void testSplitAtFraction() throws Exception { - // A reduced dataset is enough here. - List expected = createFixedRecords(DEFAULT_RECORD_COUNT); - // Create an AvroSource where each block is 1/10th of the total set of records. - String filename = generateTestFile( - "tmp.avro", expected, SyncBehavior.SYNC_REGULAR, - DEFAULT_RECORD_COUNT / 10 /* max records per block */, - AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); - File file = new File(filename); - - AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); - List> splits = - source.splitIntoBundles(file.length() / 3, null); - for (BoundedSource subSource : splits) { - int items = SourceTestUtils.readFromSource(subSource, null).size(); - // Shouldn't split while unstarted. - SourceTestUtils.assertSplitAtFractionFails(subSource, 0, 0.0, null); - SourceTestUtils.assertSplitAtFractionFails(subSource, 0, 0.7, null); - SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent(subSource, 1, 0.7, null); - SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent( - subSource, DEFAULT_RECORD_COUNT / 100, 0.7, null); - SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent( - subSource, DEFAULT_RECORD_COUNT / 10, 0.1, null); - SourceTestUtils.assertSplitAtFractionFails( - subSource, DEFAULT_RECORD_COUNT / 10 + 1, 0.1, null); - SourceTestUtils.assertSplitAtFractionFails(subSource, DEFAULT_RECORD_COUNT / 3, 0.3, null); - SourceTestUtils.assertSplitAtFractionFails(subSource, items, 0.9, null); - SourceTestUtils.assertSplitAtFractionFails(subSource, items, 1.0, null); - SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent(subSource, items, 0.999, null); - } - } - - @Test - public void testGetProgressFromUnstartedReader() throws Exception { - List records = createFixedRecords(DEFAULT_RECORD_COUNT); - String filename = generateTestFile("tmp.avro", records, SyncBehavior.SYNC_DEFAULT, 1000, - AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); - File file = new File(filename); - - AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); - try (BoundedSource.BoundedReader reader = source.createReader(null)) { - assertEquals(new Double(0.0), reader.getFractionConsumed()); - } - - List> splits = - source.splitIntoBundles(file.length() / 3, null); - for (BoundedSource subSource : splits) { - try (BoundedSource.BoundedReader reader = subSource.createReader(null)) { - assertEquals(new Double(0.0), reader.getFractionConsumed()); - } - } - } - - @Test - public void testProgress() throws Exception { - // 5 records, 2 per block. - List records = createFixedRecords(5); - String filename = generateTestFile("tmp.avro", records, SyncBehavior.SYNC_REGULAR, 2, - AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); - - AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); - try (BoundedSource.BoundedReader readerOrig = source.createReader(null)) { - assertThat(readerOrig, Matchers.instanceOf(BlockBasedReader.class)); - BlockBasedReader reader = (BlockBasedReader) readerOrig; - - // Before starting - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // First 2 records are in the same block. - assertTrue(reader.start()); - assertTrue(reader.isAtSplitPoint()); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - // continued - assertTrue(reader.advance()); - assertFalse(reader.isAtSplitPoint()); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Second block -> parallelism consumed becomes 1. - assertTrue(reader.advance()); - assertTrue(reader.isAtSplitPoint()); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - // continued - assertTrue(reader.advance()); - assertFalse(reader.isAtSplitPoint()); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Third and final block -> parallelism consumed becomes 2, remaining becomes 1. - assertTrue(reader.advance()); - assertTrue(reader.isAtSplitPoint()); - assertEquals(2, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - - // Done - assertFalse(reader.advance()); - assertEquals(3, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - } - } - - @Test - public void testProgressEmptySource() throws Exception { - // 0 records, 20 per block. - List records = Collections.emptyList(); - String filename = generateTestFile("tmp.avro", records, SyncBehavior.SYNC_REGULAR, 2, - AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); - - AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); - try (BoundedSource.BoundedReader readerOrig = source.createReader(null)) { - assertThat(readerOrig, Matchers.instanceOf(BlockBasedReader.class)); - BlockBasedReader reader = (BlockBasedReader) readerOrig; - - // before starting - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // confirm empty - assertFalse(reader.start()); - - // after reading empty source - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - } - } - - @Test - public void testGetCurrentFromUnstartedReader() throws Exception { - List records = createFixedRecords(DEFAULT_RECORD_COUNT); - String filename = generateTestFile("tmp.avro", records, SyncBehavior.SYNC_DEFAULT, 1000, - AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); - - AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); - try (BlockBasedSource.BlockBasedReader reader = - (BlockBasedSource.BlockBasedReader) source.createReader(null)) { - assertEquals(null, reader.getCurrentBlock()); - - expectedException.expect(NoSuchElementException.class); - expectedException.expectMessage("No block has been successfully read from"); - reader.getCurrent(); - } - } - - @Test - public void testSplitAtFractionExhaustive() throws Exception { - // A small-sized input is sufficient, because the test verifies that splitting is non-vacuous. - List expected = createFixedRecords(20); - String filename = generateTestFile("tmp.avro", expected, SyncBehavior.SYNC_REGULAR, 5, - AvroCoder.of(FixedRecord.class), DataFileConstants.NULL_CODEC); - - AvroSource source = AvroSource.from(filename).withSchema(FixedRecord.class); - SourceTestUtils.assertSplitAtFractionExhaustive(source, null); - } - - @Test - public void testSplitsWithSmallBlocks() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - // Test reading from an object file with many small random-sized blocks. - // The file itself doesn't have to be big; we can use a decreased record count. - List expected = createRandomRecords(DEFAULT_RECORD_COUNT); - String filename = generateTestFile("tmp.avro", expected, SyncBehavior.SYNC_RANDOM, - DEFAULT_RECORD_COUNT / 20 /* max records/block */, - AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); - File file = new File(filename); - - // Small minimum bundle size - AvroSource source = - AvroSource.from(filename).withSchema(Bird.class).withMinBundleSize(100L); - - // Assert that the source produces the expected records - assertEquals(expected, SourceTestUtils.readFromSource(source, options)); - - List> splits; - int nonEmptySplits; - - // Split with the minimum bundle size - splits = source.splitIntoBundles(100L, options); - assertTrue(splits.size() > 2); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - nonEmptySplits = 0; - for (BoundedSource subSource : splits) { - if (SourceTestUtils.readFromSource(subSource, options).size() > 0) { - nonEmptySplits += 1; - } - } - assertTrue(nonEmptySplits > 2); - - // Split with larger bundle size - splits = source.splitIntoBundles(file.length() / 4, options); - assertTrue(splits.size() > 2); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - nonEmptySplits = 0; - for (BoundedSource subSource : splits) { - if (SourceTestUtils.readFromSource(subSource, options).size() > 0) { - nonEmptySplits += 1; - } - } - assertTrue(nonEmptySplits > 2); - - // Split with the file length - splits = source.splitIntoBundles(file.length(), options); - assertTrue(splits.size() == 1); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - } - - @Test - public void testMultipleFiles() throws Exception { - String baseName = "tmp-"; - List expected = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - List contents = createRandomRecords(DEFAULT_RECORD_COUNT / 10); - expected.addAll(contents); - generateTestFile(baseName + i, contents, SyncBehavior.SYNC_DEFAULT, 0, - AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); - } - - AvroSource source = - AvroSource.from(new File(tmpFolder.getRoot().toString(), baseName + "*").toString()) - .withSchema(Bird.class); - List actual = SourceTestUtils.readFromSource(source, null); - assertThat(actual, containsInAnyOrder(expected.toArray())); - } - - @Test - public void testCreationWithSchema() throws Exception { - List expected = createRandomRecords(100); - String filename = generateTestFile("tmp.avro", expected, SyncBehavior.SYNC_DEFAULT, 0, - AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); - - // Create a source with a schema object - Schema schema = ReflectData.get().getSchema(Bird.class); - AvroSource source = AvroSource.from(filename).withSchema(schema); - List records = SourceTestUtils.readFromSource(source, null); - assertEqualsWithGeneric(expected, records); - - // Create a source with a JSON schema - String schemaString = ReflectData.get().getSchema(Bird.class).toString(); - source = AvroSource.from(filename).withSchema(schemaString); - records = SourceTestUtils.readFromSource(source, null); - assertEqualsWithGeneric(expected, records); - - // Create a source with no schema - source = AvroSource.from(filename); - records = SourceTestUtils.readFromSource(source, null); - assertEqualsWithGeneric(expected, records); - } - - @Test - public void testSchemaUpdate() throws Exception { - List birds = createRandomRecords(100); - String filename = generateTestFile("tmp.avro", birds, SyncBehavior.SYNC_DEFAULT, 0, - AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); - - AvroSource source = AvroSource.from(filename).withSchema(FancyBird.class); - List actual = SourceTestUtils.readFromSource(source, null); - - List expected = new ArrayList<>(); - for (Bird bird : birds) { - expected.add(new FancyBird( - bird.number, bird.species, bird.quality, bird.quantity, null, "MAXIMUM OVERDRIVE")); - } - - assertThat(actual, containsInAnyOrder(expected.toArray())); - } - - @Test - public void testSchemaStringIsInterned() throws Exception { - List birds = createRandomRecords(100); - String filename = generateTestFile("tmp.avro", birds, SyncBehavior.SYNC_DEFAULT, 0, - AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); - String schemaA = AvroUtils.readMetadataFromFile(filename).getSchemaString(); - String schemaB = AvroUtils.readMetadataFromFile(filename).getSchemaString(); - assertNotSame(schemaA, schemaB); - - AvroSource sourceA = AvroSource.from(filename).withSchema(schemaA); - AvroSource sourceB = AvroSource.from(filename).withSchema(schemaB); - assertSame(sourceA.getSchema(), sourceB.getSchema()); - - // Ensure that deserialization still goes through interning - AvroSource sourceC = SerializableUtils.clone(sourceB); - assertSame(sourceA.getSchema(), sourceC.getSchema()); - } - - @Test - public void testSchemaIsInterned() throws Exception { - List birds = createRandomRecords(100); - String filename = generateTestFile("tmp.avro", birds, SyncBehavior.SYNC_DEFAULT, 0, - AvroCoder.of(Bird.class), DataFileConstants.NULL_CODEC); - String schemaA = AvroUtils.readMetadataFromFile(filename).getSchemaString(); - String schemaB = AvroUtils.readMetadataFromFile(filename).getSchemaString(); - assertNotSame(schemaA, schemaB); - - AvroSource sourceA = (AvroSource) AvroSource.from(filename) - .withSchema(schemaA).createForSubrangeOfFile(filename, 0L, 0L); - AvroSource sourceB = (AvroSource) AvroSource.from(filename) - .withSchema(schemaB).createForSubrangeOfFile(filename, 0L, 0L); - assertSame(sourceA.getReadSchema(), sourceA.getFileSchema()); - assertSame(sourceA.getReadSchema(), sourceB.getReadSchema()); - assertSame(sourceA.getReadSchema(), sourceB.getFileSchema()); - - // Schemas are transient and not serialized thus we don't need to worry about interning - // after deserialization. - } - - private void assertEqualsWithGeneric(List expected, List actual) { - assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) { - Bird fixed = expected.get(i); - GenericRecord generic = actual.get(i); - assertEquals(fixed.number, generic.get("number")); - assertEquals(fixed.quality, generic.get("quality").toString()); // From Avro util.Utf8 - assertEquals(fixed.quantity, generic.get("quantity")); - assertEquals(fixed.species, generic.get("species").toString()); - } - } - - /** - * Creates a haystack byte array of the give size with a needle that starts at the given position. - */ - private byte[] createHaystack(byte[] needle, int position, int size) { - byte[] haystack = new byte[size]; - for (int i = position, j = 0; i < size && j < needle.length; i++, j++) { - haystack[i] = needle[j]; - } - return haystack; - } - - /** - * Asserts that advancePastNextSyncMarker advances an input stream past a sync marker and - * correctly returns the number of bytes consumed from the stream. - * Creates a haystack of size bytes and places a 16-byte sync marker at the position specified. - */ - private void testAdvancePastNextSyncMarkerAt(int position, int size) throws IOException { - byte sentinel = (byte) 0xFF; - byte[] marker = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}; - byte[] haystack = createHaystack(marker, position, size); - PushbackInputStream stream = - new PushbackInputStream(new ByteArrayInputStream(haystack), marker.length); - if (position + marker.length < size) { - haystack[position + marker.length] = sentinel; - assertEquals(position + marker.length, AvroReader.advancePastNextSyncMarker(stream, marker)); - assertEquals(sentinel, (byte) stream.read()); - } else { - assertEquals(size, AvroReader.advancePastNextSyncMarker(stream, marker)); - assertEquals(-1, stream.read()); - } - } - - @Test - public void testAdvancePastNextSyncMarker() throws IOException { - // Test placing the sync marker at different locations at the start and in the middle of the - // buffer. - for (int i = 0; i <= 16; i++) { - testAdvancePastNextSyncMarkerAt(i, 1000); - testAdvancePastNextSyncMarkerAt(160 + i, 1000); - } - // Test placing the sync marker at the end of the buffer. - testAdvancePastNextSyncMarkerAt(983, 1000); - // Test placing the sync marker so that it begins at the end of the buffer. - testAdvancePastNextSyncMarkerAt(984, 1000); - testAdvancePastNextSyncMarkerAt(985, 1000); - testAdvancePastNextSyncMarkerAt(999, 1000); - // Test with no sync marker. - testAdvancePastNextSyncMarkerAt(1000, 1000); - } - - // Tests for Seeker. - @Test - public void testSeekerFind() { - byte[] marker = {0, 1, 2, 3}; - byte[] buffer; - Seeker s; - s = new Seeker(marker); - - buffer = new byte[] {0, 1, 2, 3, 4, 5, 6, 7}; - assertEquals(3, s.find(buffer, buffer.length)); - - buffer = new byte[] {0, 0, 0, 0, 0, 1, 2, 3}; - assertEquals(7, s.find(buffer, buffer.length)); - - buffer = new byte[] {0, 1, 2, 0, 0, 1, 2, 3}; - assertEquals(7, s.find(buffer, buffer.length)); - - buffer = new byte[] {0, 1, 2, 3}; - assertEquals(3, s.find(buffer, buffer.length)); - } - - @Test - public void testSeekerFindResume() { - byte[] marker = {0, 1, 2, 3}; - byte[] buffer; - Seeker s; - s = new Seeker(marker); - - buffer = new byte[] {0, 0, 0, 0, 0, 0, 0, 0}; - assertEquals(-1, s.find(buffer, buffer.length)); - buffer = new byte[] {1, 2, 3, 0, 0, 0, 0, 0}; - assertEquals(2, s.find(buffer, buffer.length)); - - buffer = new byte[] {0, 0, 0, 0, 0, 0, 1, 2}; - assertEquals(-1, s.find(buffer, buffer.length)); - buffer = new byte[] {3, 0, 1, 2, 3, 0, 1, 2}; - assertEquals(0, s.find(buffer, buffer.length)); - - buffer = new byte[] {0}; - assertEquals(-1, s.find(buffer, buffer.length)); - buffer = new byte[] {1}; - assertEquals(-1, s.find(buffer, buffer.length)); - buffer = new byte[] {2}; - assertEquals(-1, s.find(buffer, buffer.length)); - buffer = new byte[] {3}; - assertEquals(0, s.find(buffer, buffer.length)); - } - - @Test - public void testSeekerUsesBufferLength() { - byte[] marker = {0, 0, 1}; - byte[] buffer; - Seeker s; - s = new Seeker(marker); - - buffer = new byte[] {0, 0, 0, 1}; - assertEquals(-1, s.find(buffer, 3)); - - s = new Seeker(marker); - buffer = new byte[] {0, 0}; - assertEquals(-1, s.find(buffer, 1)); - buffer = new byte[] {1, 0}; - assertEquals(-1, s.find(buffer, 1)); - - s = new Seeker(marker); - buffer = new byte[] {0, 2}; - assertEquals(-1, s.find(buffer, 1)); - buffer = new byte[] {0, 2}; - assertEquals(-1, s.find(buffer, 1)); - buffer = new byte[] {1, 2}; - assertEquals(0, s.find(buffer, 1)); - } - - - @Test - public void testSeekerFindPartial() { - byte[] marker = {0, 0, 1}; - byte[] buffer; - Seeker s; - s = new Seeker(marker); - - buffer = new byte[] {0, 0, 0, 1}; - assertEquals(3, s.find(buffer, buffer.length)); - - marker = new byte[] {1, 1, 1, 2}; - s = new Seeker(marker); - - buffer = new byte[] {1, 1, 1, 1, 1}; - assertEquals(-1, s.find(buffer, buffer.length)); - buffer = new byte[] {1, 1, 2}; - assertEquals(2, s.find(buffer, buffer.length)); - - buffer = new byte[] {1, 1, 1, 1, 1}; - assertEquals(-1, s.find(buffer, buffer.length)); - buffer = new byte[] {2, 1, 1, 1, 2}; - assertEquals(0, s.find(buffer, buffer.length)); - } - - @Test - public void testSeekerFindAllLocations() { - byte[] marker = {1, 1, 2}; - byte[] allOnes = new byte[] {1, 1, 1, 1}; - byte[] findIn = new byte[] {1, 1, 1, 1}; - Seeker s = new Seeker(marker); - - for (int i = 0; i < findIn.length; i++) { - assertEquals(-1, s.find(allOnes, allOnes.length)); - findIn[i] = 2; - assertEquals(i, s.find(findIn, findIn.length)); - findIn[i] = 1; - } - } - - @Test - public void testDisplayData() { - AvroSource source = AvroSource - .from("foobar.txt") - .withSchema(Bird.class) - .withMinBundleSize(1234); - - DisplayData displayData = DisplayData.from(source); - assertThat(displayData, hasDisplayItem("filePattern", "foobar.txt")); - assertThat(displayData, hasDisplayItem("minBundleSize", 1234)); - } - - /** - * Class that will encode to a fixed size: 16 bytes. - * - *

              Each object has a 15-byte array. Avro encodes an object of this type as - * a byte array, so each encoded object will consist of 1 byte that encodes the - * length of the array, followed by 15 bytes. - */ - @DefaultCoder(AvroCoder.class) - public static class FixedRecord { - private byte[] value = new byte[15]; - - public FixedRecord() { - this(0); - } - - public FixedRecord(int i) { - value[0] = (byte) i; - value[1] = (byte) (i >> 8); - value[2] = (byte) (i >> 16); - value[3] = (byte) (i >> 24); - } - - public int asInt() { - return value[0] | (value[1] << 8) | (value[2] << 16) | (value[3] << 24); - } - - @Override - public boolean equals(Object o) { - if (o instanceof FixedRecord) { - FixedRecord other = (FixedRecord) o; - return this.asInt() == other.asInt(); - } - return false; - } - - @Override - public int hashCode() { - return toString().hashCode(); - } - - @Override - public String toString() { - return Integer.toString(this.asInt()); - } - } - - /** - * Create a list of count 16-byte records. - */ - private static List createFixedRecords(int count) { - List records = new ArrayList<>(); - for (int i = 0; i < count; i++) { - records.add(new FixedRecord(i)); - } - return records; - } - - /** - * Class used as the record type in tests. - */ - @DefaultCoder(AvroCoder.class) - static class Bird { - long number; - String species; - String quality; - long quantity; - - public Bird() {} - - public Bird(long number, String species, String quality, long quantity) { - this.number = number; - this.species = species; - this.quality = quality; - this.quantity = quantity; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(Bird.class) - .addValue(number) - .addValue(species) - .addValue(quantity) - .addValue(quality) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Bird) { - Bird other = (Bird) obj; - return Objects.equals(species, other.species) && Objects.equals(quality, other.quality) - && quantity == other.quantity && number == other.number; - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(number, species, quality, quantity); - } - } - - /** - * Class used as the record type in tests. - * - *

              Contains nullable fields and fields with default values. Can be read using a file written - * with the Bird schema. - */ - @DefaultCoder(AvroCoder.class) - public static class FancyBird { - long number; - String species; - String quality; - long quantity; - - @Nullable - String habitat; - - @AvroDefault("\"MAXIMUM OVERDRIVE\"") - String fancinessLevel; - - public FancyBird() {} - - public FancyBird(long number, String species, String quality, long quantity, String habitat, - String fancinessLevel) { - this.number = number; - this.species = species; - this.quality = quality; - this.quantity = quantity; - this.habitat = habitat; - this.fancinessLevel = fancinessLevel; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(FancyBird.class) - .addValue(number) - .addValue(species) - .addValue(quality) - .addValue(quantity) - .addValue(habitat) - .addValue(fancinessLevel) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof FancyBird) { - FancyBird other = (FancyBird) obj; - return Objects.equals(species, other.species) && Objects.equals(quality, other.quality) - && quantity == other.quantity && number == other.number - && Objects.equals(fancinessLevel, other.fancinessLevel) - && Objects.equals(habitat, other.habitat); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(number, species, quality, quantity, habitat, fancinessLevel); - } - } - - /** - * Create a list of n random records. - */ - private static List createRandomRecords(long n) { - String[] qualities = { - "miserable", "forelorn", "fidgity", "squirrelly", "fanciful", "chipper", "lazy"}; - String[] species = {"pigeons", "owls", "gulls", "hawks", "robins", "jays"}; - Random random = new Random(0); - - List records = new ArrayList<>(); - for (long i = 0; i < n; i++) { - Bird bird = new Bird(); - bird.quality = qualities[random.nextInt(qualities.length)]; - bird.species = species[random.nextInt(species.length)]; - bird.number = i; - bird.quantity = random.nextLong(); - records.add(bird); - } - return records; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java deleted file mode 100644 index a5bddec315..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ /dev/null @@ -1,1751 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.io.BigQueryIO.fromJsonString; -import static com.google.cloud.dataflow.sdk.io.BigQueryIO.toJsonString; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.common.base.Preconditions.checkArgument; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; - -import com.google.api.client.util.Data; -import com.google.api.services.bigquery.model.ErrorProto; -import com.google.api.services.bigquery.model.Job; -import com.google.api.services.bigquery.model.JobConfigurationExtract; -import com.google.api.services.bigquery.model.JobConfigurationLoad; -import com.google.api.services.bigquery.model.JobConfigurationQuery; -import com.google.api.services.bigquery.model.JobConfigurationTableCopy; -import com.google.api.services.bigquery.model.JobReference; -import com.google.api.services.bigquery.model.JobStatistics; -import com.google.api.services.bigquery.model.JobStatistics2; -import com.google.api.services.bigquery.model.JobStatistics4; -import com.google.api.services.bigquery.model.JobStatus; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryQuerySource; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.BigQueryTableSource; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.JsonSchemaToTableSchema; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.PassThroughThenCleanup; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.PassThroughThenCleanup.CleanupOperation; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Status; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.TransformingSource; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.TableRowWriter; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WritePartition; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteRename; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteTables; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils.ExpectedSplitOutcome; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.BigQueryServices; -import com.google.cloud.dataflow.sdk.util.BigQueryServices.DatasetService; -import com.google.cloud.dataflow.sdk.util.BigQueryServices.JobService; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.PCollectionViews; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; - -import org.hamcrest.CoreMatchers; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.io.Serializable; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * Tests for BigQueryIO. - */ -@RunWith(JUnit4.class) -public class BigQueryIOTest implements Serializable { - - // Status.UNKNOWN maps to null - private static final Map JOB_STATUS_MAP = ImmutableMap.of( - Status.SUCCEEDED, new Job().setStatus(new JobStatus()), - Status.FAILED, new Job().setStatus(new JobStatus().setErrorResult(new ErrorProto()))); - - private static class FakeBigQueryServices implements BigQueryServices { - - private String[] jsonTableRowReturns = new String[0]; - private JobService jobService; - private DatasetService datasetService; - - public FakeBigQueryServices withJobService(JobService jobService) { - this.jobService = jobService; - return this; - } - - public FakeBigQueryServices withDatasetService(DatasetService datasetService) { - this.datasetService = datasetService; - return this; - } - - public FakeBigQueryServices readerReturns(String... jsonTableRowReturns) { - this.jsonTableRowReturns = jsonTableRowReturns; - return this; - } - - @Override - public JobService getJobService(BigQueryOptions bqOptions) { - return jobService; - } - - @Override - public DatasetService getDatasetService(BigQueryOptions bqOptions) { - return datasetService; - } - - @Override - public BigQueryJsonReader getReaderFromTable( - BigQueryOptions bqOptions, TableReference tableRef) { - return new FakeBigQueryReader(jsonTableRowReturns); - } - - @Override - public BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten, - @Nullable Boolean useLegacySql) { - return new FakeBigQueryReader(jsonTableRowReturns); - } - - private static class FakeBigQueryReader implements BigQueryJsonReader { - private static final int UNSTARTED = -1; - private static final int CLOSED = Integer.MAX_VALUE; - - private String[] jsonTableRowReturns; - private int currIndex; - - FakeBigQueryReader(String[] jsonTableRowReturns) { - this.jsonTableRowReturns = jsonTableRowReturns; - this.currIndex = UNSTARTED; - } - - @Override - public boolean start() throws IOException { - assertEquals(UNSTARTED, currIndex); - currIndex = 0; - return currIndex < jsonTableRowReturns.length; - } - - @Override - public boolean advance() throws IOException { - return ++currIndex < jsonTableRowReturns.length; - } - - @Override - public TableRow getCurrent() throws NoSuchElementException { - if (currIndex >= jsonTableRowReturns.length) { - throw new NoSuchElementException(); - } - return fromJsonString(jsonTableRowReturns[currIndex], TableRow.class); - } - - @Override - public void close() throws IOException { - currIndex = CLOSED; - } - } - } - - private static class FakeJobService implements JobService, Serializable { - - private Object[] startJobReturns; - private Object[] pollJobReturns; - private Object[] getJobReturns; - private String executingProject; - // Both counts will be reset back to zeros after serialization. - // This is a work around for DoFn's verifyUnmodified check. - private transient int startJobCallsCount; - private transient int pollJobStatusCallsCount; - private transient int getJobCallsCount; - - public FakeJobService() { - this.startJobReturns = new Object[0]; - this.pollJobReturns = new Object[0]; - this.getJobReturns = new Object[0]; - this.startJobCallsCount = 0; - this.pollJobStatusCallsCount = 0; - this.getJobCallsCount = 0; - } - - /** - * Sets the return values to mock {@link JobService#startLoadJob}, - * {@link JobService#startExtractJob} and {@link JobService#startQueryJob}. - * - *

              Throws if the {@link Object} is a {@link Exception}, returns otherwise. - */ - public FakeJobService startJobReturns(Object... startJobReturns) { - this.startJobReturns = startJobReturns; - return this; - } - - /** - * Sets the return values to mock {@link JobService#getJob}. - * - *

              Throws if the {@link Object} is a {@link InterruptedException}, returns otherwise. - */ - public FakeJobService getJobReturns(Object... getJobReturns) { - this.getJobReturns = getJobReturns; - return this; - } - - /** - * Sets the return values to mock {@link JobService#pollJob}. - * - *

              Throws if the {@link Object} is a {@link Exception}, returns otherwise. - */ - public FakeJobService pollJobReturns(Object... pollJobReturns) { - this.pollJobReturns = pollJobReturns; - return this; - } - - /** - * Verifies executing project. - */ - public FakeJobService verifyExecutingProject(String executingProject) { - this.executingProject = executingProject; - return this; - } - - @Override - public void startLoadJob(JobReference jobRef, JobConfigurationLoad loadConfig) - throws InterruptedException, IOException { - startJob(jobRef); - } - - @Override - public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) - throws InterruptedException, IOException { - startJob(jobRef); - } - - @Override - public void startQueryJob(JobReference jobRef, JobConfigurationQuery query) - throws IOException, InterruptedException { - startJob(jobRef); - } - - @Override - public void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) - throws IOException, InterruptedException { - startJob(jobRef); - } - - @Override - public Job pollJob(JobReference jobRef, int maxAttempts) - throws InterruptedException { - if (!Strings.isNullOrEmpty(executingProject)) { - checkArgument( - jobRef.getProjectId().equals(executingProject), - "Project id: %s is not equal to executing project: %s", - jobRef.getProjectId(), executingProject); - } - - if (pollJobStatusCallsCount < pollJobReturns.length) { - Object ret = pollJobReturns[pollJobStatusCallsCount++]; - if (ret instanceof Job) { - return (Job) ret; - } else if (ret instanceof Status) { - return JOB_STATUS_MAP.get(ret); - } else if (ret instanceof InterruptedException) { - throw (InterruptedException) ret; - } else { - throw new RuntimeException("Unexpected return type: " + ret.getClass()); - } - } else { - throw new RuntimeException( - "Exceeded expected number of calls: " + pollJobReturns.length); - } - } - - private void startJob(JobReference jobRef) throws IOException, InterruptedException { - if (!Strings.isNullOrEmpty(executingProject)) { - checkArgument( - jobRef.getProjectId().equals(executingProject), - "Project id: %s is not equal to executing project: %s", - jobRef.getProjectId(), executingProject); - } - - if (startJobCallsCount < startJobReturns.length) { - Object ret = startJobReturns[startJobCallsCount++]; - if (ret instanceof IOException) { - throw (IOException) ret; - } else if (ret instanceof InterruptedException) { - throw (InterruptedException) ret; - } else { - return; - } - } else { - throw new RuntimeException( - "Exceeded expected number of calls: " + startJobReturns.length); - } - } - - @Override - public JobStatistics dryRunQuery(String projectId, JobConfigurationQuery query) - throws InterruptedException, IOException { - throw new UnsupportedOperationException(); - } - - @Override - public Job getJob(JobReference jobRef) throws InterruptedException { - if (!Strings.isNullOrEmpty(executingProject)) { - checkArgument( - jobRef.getProjectId().equals(executingProject), - "Project id: %s is not equal to executing project: %s", - jobRef.getProjectId(), executingProject); - } - - if (getJobCallsCount < getJobReturns.length) { - Object ret = getJobReturns[getJobCallsCount++]; - if (ret == null) { - return null; - } else if (ret instanceof Job) { - return (Job) ret; - } else if (ret instanceof InterruptedException) { - throw (InterruptedException) ret; - } else { - throw new RuntimeException("Unexpected return type: " + ret.getClass()); - } - } else { - throw new RuntimeException( - "Exceeded expected number of calls: " + getJobReturns.length); - } - } - } - - @Rule public transient ExpectedException thrown = ExpectedException.none(); - @Rule public transient ExpectedLogs logged = ExpectedLogs.none(BigQueryIO.class); - @Rule public transient TemporaryFolder testFolder = new TemporaryFolder(); - @Mock(extraInterfaces = Serializable.class) - public transient BigQueryServices.JobService mockJobService; - @Mock private transient IOChannelFactory mockIOChannelFactory; - @Mock(extraInterfaces = Serializable.class) private transient DatasetService mockDatasetService; - - private void checkReadTableObject( - BigQueryIO.Read.Bound bound, String project, String dataset, String table) { - checkReadTableObjectWithValidate(bound, project, dataset, table, true); - } - - private void checkReadQueryObject( - BigQueryIO.Read.Bound bound, String query) { - checkReadQueryObjectWithValidate(bound, query, true); - } - - private void checkReadTableObjectWithValidate( - BigQueryIO.Read.Bound bound, String project, String dataset, String table, boolean validate) { - assertEquals(project, bound.getTable().getProjectId()); - assertEquals(dataset, bound.getTable().getDatasetId()); - assertEquals(table, bound.getTable().getTableId()); - assertNull(bound.query); - assertEquals(validate, bound.getValidate()); - } - - private void checkReadQueryObjectWithValidate( - BigQueryIO.Read.Bound bound, String query, boolean validate) { - assertNull(bound.getTable()); - assertEquals(query, bound.getQuery()); - assertEquals(validate, bound.getValidate()); - } - - private void checkWriteObject( - BigQueryIO.Write.Bound bound, String project, String dataset, String table, - TableSchema schema, CreateDisposition createDisposition, - WriteDisposition writeDisposition) { - checkWriteObjectWithValidate( - bound, project, dataset, table, schema, createDisposition, writeDisposition, true); - } - - private void checkWriteObjectWithValidate( - BigQueryIO.Write.Bound bound, String project, String dataset, String table, - TableSchema schema, CreateDisposition createDisposition, - WriteDisposition writeDisposition, boolean validate) { - assertEquals(project, bound.getTable().get().getProjectId()); - assertEquals(dataset, bound.getTable().get().getDatasetId()); - assertEquals(table, bound.getTable().get().getTableId()); - assertEquals(schema, bound.getSchema()); - assertEquals(createDisposition, bound.createDisposition); - assertEquals(writeDisposition, bound.writeDisposition); - assertEquals(validate, bound.validate); - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testBuildTableBasedSource() { - BigQueryIO.Read.Bound bound = BigQueryIO.Read.named("ReadMyTable") - .from("foo.com:project:somedataset.sometable"); - checkReadTableObject(bound, "foo.com:project", "somedataset", "sometable"); - } - - @Test - public void testBuildQueryBasedSource() { - BigQueryIO.Read.Bound bound = BigQueryIO.Read.named("ReadMyQuery") - .fromQuery("foo_query"); - checkReadQueryObject(bound, "foo_query"); - } - - @Test - public void testBuildTableBasedSourceWithoutValidation() { - // This test just checks that using withoutValidation will not trigger object - // construction errors. - BigQueryIO.Read.Bound bound = BigQueryIO.Read.named("ReadMyTable") - .from("foo.com:project:somedataset.sometable").withoutValidation(); - checkReadTableObjectWithValidate(bound, "foo.com:project", "somedataset", "sometable", false); - } - - @Test - public void testBuildQueryBasedSourceWithoutValidation() { - // This test just checks that using withoutValidation will not trigger object - // construction errors. - BigQueryIO.Read.Bound bound = BigQueryIO.Read.named("ReadMyTable") - .fromQuery("some_query").withoutValidation(); - checkReadQueryObjectWithValidate(bound, "some_query", false); - } - - @Test - public void testBuildTableBasedSourceWithDefaultProject() { - BigQueryIO.Read.Bound bound = BigQueryIO.Read.named("ReadMyTable") - .from("somedataset.sometable"); - checkReadTableObject(bound, null, "somedataset", "sometable"); - } - - @Test - public void testBuildSourceWithTableReference() { - TableReference table = new TableReference() - .setProjectId("foo.com:project") - .setDatasetId("somedataset") - .setTableId("sometable"); - BigQueryIO.Read.Bound bound = BigQueryIO.Read.named("ReadMyTable") - .from(table); - checkReadTableObject(bound, "foo.com:project", "somedataset", "sometable"); - } - - @Test - public void testValidateReadSetsDefaultProject() { - String projectId = "someproject"; - String datasetId = "somedataset"; - String tableId = "sometable"; - BigQueryOptions bqOptions = TestPipeline.testingPipelineOptions().as(BigQueryOptions.class); - bqOptions.setProject(projectId); - bqOptions.setTempLocation("gs://testbucket/testdir"); - - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(new FakeJobService()) - .withDatasetService(mockDatasetService); - - Pipeline p = TestPipeline.create(bqOptions); - - TableReference tableRef = new TableReference(); - tableRef.setDatasetId(datasetId); - tableRef.setTableId(tableId); - - thrown.expect(RuntimeException.class); - // Message will be one of following depending on the execution environment. - thrown.expectMessage(Matchers.containsString( - "Unable to confirm BigQuery dataset presence for table")); - p.apply(BigQueryIO.Read.from(tableRef) - .withTestServices(fakeBqServices)); - } - - @Test - @Category(RunnableOnService.class) - public void testBuildSourceWithoutTableOrQuery() { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation("gs://testbucket/testdir"); - - Pipeline p = TestPipeline.create(bqOptions); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Invalid BigQueryIO.Read: one of table reference and query must be set"); - p.apply(BigQueryIO.Read.named("ReadMyTable")); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testBuildSourceWithTableAndQuery() { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation("gs://testbucket/testdir"); - - Pipeline p = TestPipeline.create(bqOptions); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Invalid BigQueryIO.Read: table reference and query may not both be set"); - p.apply( - BigQueryIO.Read.named("ReadMyTable") - .from("foo.com:project:somedataset.sometable") - .fromQuery("query")); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testBuildSourceWithTableAndFlatten() { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation("gs://testbucket/testdir"); - - Pipeline p = TestPipeline.create(bqOptions); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Invalid BigQueryIO.Read: Specifies a table with a result flattening preference," - + " which only applies to queries"); - p.apply( - BigQueryIO.Read.named("ReadMyTable") - .from("foo.com:project:somedataset.sometable") - .withoutResultFlattening()); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testBuildSourceWithTableAndSqlDialect() { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation("gs://testbucket/testdir"); - - Pipeline p = TestPipeline.create(bqOptions); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Invalid BigQueryIO.Read: Specifies a table with a SQL dialect preference," - + " which only applies to queries"); - p.apply( - BigQueryIO.Read.named("ReadMyTable") - .from("foo.com:project:somedataset.sometable") - .usingStandardSql()); - p.run(); - } - - @Test - public void testReadFromTable() throws IOException { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); - - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(new FakeJobService() - .startJobReturns("done", "done") - .getJobReturns((Job) null) - .verifyExecutingProject(bqOptions.getProject())) - .readerReturns( - toJsonString(new TableRow().set("name", "a").set("number", 1)), - toJsonString(new TableRow().set("name", "b").set("number", 2)), - toJsonString(new TableRow().set("name", "c").set("number", 3))); - - Pipeline p = TestPipeline.create(bqOptions); - PCollection output = p - .apply(BigQueryIO.Read.from("non-executing-project:somedataset.sometable") - .withTestServices(fakeBqServices) - .withoutValidation()) - .apply(ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output((String) c.element().get("name")); - } - })); - - DataflowAssert.that(output) - .containsInAnyOrder(ImmutableList.of("a", "b", "c")); - - p.run(); - } - - @Test - public void testWrite() throws Exception { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); - - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(new FakeJobService() - .startJobReturns("done", "done", "done") - .pollJobReturns(Status.FAILED, Status.FAILED, Status.SUCCEEDED)); - - Pipeline p = TestPipeline.create(bqOptions); - p.apply(Create.of( - new TableRow().set("name", "a").set("number", 1), - new TableRow().set("name", "b").set("number", 2), - new TableRow().set("name", "c").set("number", 3))) - .setCoder(TableRowJsonCoder.of()) - .apply(BigQueryIO.Write.to("dataset-id.table-id") - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withSchema(new TableSchema().setFields( - ImmutableList.of( - new TableFieldSchema().setName("name").setType("STRING"), - new TableFieldSchema().setName("number").setType("INTEGER")))) - .withTestServices(fakeBqServices) - .withoutValidation()); - p.run(); - - logged.verifyInfo("Starting BigQuery load job"); - logged.verifyInfo("BigQuery load job failed"); - logged.verifyInfo("try 0/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - logged.verifyInfo("try 1/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - logged.verifyInfo("try 2/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - logged.verifyNotLogged("try 3/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - File tempDir = new File(bqOptions.getTempLocation()); - testNumFiles(tempDir, 0); - } - - @Test - public void testWriteUnknown() throws Exception { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); - - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(new FakeJobService() - .startJobReturns("done", "done") - .pollJobReturns(Status.FAILED, Status.UNKNOWN)); - - Pipeline p = TestPipeline.create(bqOptions); - p.apply(Create.of( - new TableRow().set("name", "a").set("number", 1), - new TableRow().set("name", "b").set("number", 2), - new TableRow().set("name", "c").set("number", 3))) - .setCoder(TableRowJsonCoder.of()) - .apply(BigQueryIO.Write.to("project-id:dataset-id.table-id") - .withCreateDisposition(CreateDisposition.CREATE_NEVER) - .withTestServices(fakeBqServices) - .withoutValidation()); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("Failed to poll the load job status"); - p.run(); - - File tempDir = new File(bqOptions.getTempLocation()); - testNumFiles(tempDir, 0); - } - - @Test - public void testBuildSourceDisplayData() { - String tableSpec = "project:dataset.tableid"; - - BigQueryIO.Read.Bound read = BigQueryIO.Read - .from(tableSpec) - .fromQuery("myQuery") - .withoutResultFlattening() - .usingStandardSql() - .withoutValidation(); - - DisplayData displayData = DisplayData.from(read); - - assertThat(displayData, hasDisplayItem("table", tableSpec)); - assertThat(displayData, hasDisplayItem("query", "myQuery")); - assertThat(displayData, hasDisplayItem("flattenResults", false)); - assertThat(displayData, hasDisplayItem("useLegacySql", false)); - assertThat(displayData, hasDisplayItem("validation", false)); - } - - @Test - public void testTableSourcePrimitiveDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - BigQueryIO.Read.Bound read = BigQueryIO.Read - .from("project:dataset.tableId") - .withoutValidation(); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(read); - assertThat("BigQueryIO.Read should include the table spec in its primitive display data", - displayData, hasItem(hasDisplayItem("table"))); - } - - @Test - public void testQuerySourcePrimitiveDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - BigQueryIO.Read.Bound read = BigQueryIO.Read - .fromQuery("foobar") - .withoutValidation(); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(read); - assertThat("BigQueryIO.Read should include the query in its primitive display data", - displayData, hasItem(hasDisplayItem("query"))); - } - - @Test - public void testBuildWrite() { - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable"); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY); - } - - @Test - public void testBuildWritewithoutValidation() { - // This test just checks that using withoutValidation will not trigger object - // construction errors. - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable").withoutValidation(); - checkWriteObjectWithValidate( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY, false); - } - - @Test - public void testBuildWriteDefaultProject() { - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("somedataset.sometable"); - checkWriteObject( - bound, null, "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY); - } - - @Test - public void testBuildWriteWithTableReference() { - TableReference table = new TableReference() - .setProjectId("foo.com:project") - .setDatasetId("somedataset") - .setTableId("sometable"); - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to(table); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY); - } - - @Test - @Category(RunnableOnService.class) - public void testBuildWriteWithoutTable() { - Pipeline p = TestPipeline.create(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("must set the table reference"); - p.apply(Create.of().withCoder(TableRowJsonCoder.of())) - .apply(BigQueryIO.Write.named("WriteMyTable")); - } - - @Test - public void testBuildWriteWithSchema() { - TableSchema schema = new TableSchema(); - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable").withSchema(schema); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - schema, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY); - } - - @Test - public void testBuildWriteWithCreateDispositionNever() { - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable") - .withCreateDisposition(CreateDisposition.CREATE_NEVER); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_NEVER, WriteDisposition.WRITE_EMPTY); - } - - @Test - public void testBuildWriteWithCreateDispositionIfNeeded() { - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable") - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY); - } - - @Test - public void testBuildWriteWithWriteDispositionTruncate() { - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable") - .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_TRUNCATE); - } - - @Test - public void testBuildWriteWithWriteDispositionAppend() { - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable") - .withWriteDisposition(WriteDisposition.WRITE_APPEND); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_APPEND); - } - - @Test - public void testBuildWriteWithWriteDispositionEmpty() { - BigQueryIO.Write.Bound bound = BigQueryIO.Write.named("WriteMyTable") - .to("foo.com:project:somedataset.sometable") - .withWriteDisposition(WriteDisposition.WRITE_EMPTY); - checkWriteObject( - bound, "foo.com:project", "somedataset", "sometable", - null, CreateDisposition.CREATE_IF_NEEDED, WriteDisposition.WRITE_EMPTY); - } - - @Test - public void testBuildWriteDisplayData() { - String tableSpec = "project:dataset.table"; - TableSchema schema = new TableSchema().set("col1", "type1").set("col2", "type2"); - - BigQueryIO.Write.Bound write = BigQueryIO.Write - .to(tableSpec) - .withSchema(schema) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(WriteDisposition.WRITE_APPEND) - .withoutValidation(); - - DisplayData displayData = DisplayData.from(write); - - assertThat(displayData, hasDisplayItem("table")); - assertThat(displayData, hasDisplayItem("schema")); - assertThat(displayData, - hasDisplayItem("createDisposition", CreateDisposition.CREATE_IF_NEEDED.toString())); - assertThat(displayData, - hasDisplayItem("writeDisposition", WriteDisposition.WRITE_APPEND.toString())); - assertThat(displayData, hasDisplayItem("validation", false)); - } - - @Test - public void testBatchWritePrimitiveDisplayData() { - DataflowPipelineOptions options = DataflowDisplayDataEvaluator.getDefaultOptions(); - options.setStreaming(false); - testWritePrimitiveDisplayData(options); - } - - @Test - public void testStreamingWritePrimitiveDisplayData() { - DataflowPipelineOptions options = DataflowDisplayDataEvaluator.getDefaultOptions(); - options.setStreaming(true); - testWritePrimitiveDisplayData(options); - } - - private void testWritePrimitiveDisplayData(DataflowPipelineOptions options) { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(options); - - BigQueryIO.Write.Bound write = BigQueryIO.Write - .to("project:dataset.table") - .withSchema(new TableSchema().set("col1", "type1").set("col2", "type2")) - .withoutValidation(); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(write); - assertThat("BigQueryIO.Write should include the table spec in its primitive display data", - displayData, hasItem(hasDisplayItem("table"))); - - assertThat("BigQueryIO.Write should include the table schema in its primitive display data", - displayData, hasItem(hasDisplayItem("schema"))); - } - - private void testWriteValidatesDataset(boolean streaming) { - BigQueryOptions options = PipelineOptionsFactory.as(BigQueryOptions.class); - options.setProject("someproject"); - options.setStreaming(streaming); - - Pipeline p = Pipeline.create(options); - - TableReference tableRef = new TableReference(); - tableRef.setDatasetId("somedataset"); - tableRef.setTableId("sometable"); - - thrown.expect(RuntimeException.class); - // Message will be one of following depending on the execution environment. - thrown.expectMessage( - Matchers.either(Matchers.containsString("Unable to confirm BigQuery dataset presence")) - .or(Matchers.containsString("BigQuery dataset not found for table"))); - p.apply(Create.of().withCoder(TableRowJsonCoder.of())) - .apply(BigQueryIO.Write.named("WriteMyTable") - .to(tableRef) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withSchema(new TableSchema())); - } - - @Test - public void testWriteValidatesDatasetBatch() { - testWriteValidatesDataset(false); - } - - @Test - public void testWriteValidatesDatasetStreaming() { - testWriteValidatesDataset(true); - } - - @Test - public void testTableParsing() { - TableReference ref = BigQueryIO - .parseTableSpec("my-project:data_set.table_name"); - Assert.assertEquals("my-project", ref.getProjectId()); - Assert.assertEquals("data_set", ref.getDatasetId()); - Assert.assertEquals("table_name", ref.getTableId()); - } - - @Test - public void testTableParsing_validPatterns() { - BigQueryIO.parseTableSpec("a123-456:foo_bar.d"); - BigQueryIO.parseTableSpec("a12345:b.c"); - BigQueryIO.parseTableSpec("b12345.c"); - } - - @Test - public void testTableParsing_noProjectId() { - TableReference ref = BigQueryIO - .parseTableSpec("data_set.table_name"); - Assert.assertEquals(null, ref.getProjectId()); - Assert.assertEquals("data_set", ref.getDatasetId()); - Assert.assertEquals("table_name", ref.getTableId()); - } - - @Test - public void testTableParsingError() { - thrown.expect(IllegalArgumentException.class); - BigQueryIO.parseTableSpec("0123456:foo.bar"); - } - - @Test - public void testTableParsingError_2() { - thrown.expect(IllegalArgumentException.class); - BigQueryIO.parseTableSpec("myproject:.bar"); - } - - @Test - public void testTableParsingError_3() { - thrown.expect(IllegalArgumentException.class); - BigQueryIO.parseTableSpec(":a.b"); - } - - @Test - public void testTableParsingError_slash() { - thrown.expect(IllegalArgumentException.class); - BigQueryIO.parseTableSpec("a\\b12345:c.d"); - } - - // Test that BigQuery's special null placeholder objects can be encoded. - @Test - public void testCoder_nullCell() throws CoderException { - TableRow row = new TableRow(); - row.set("temperature", Data.nullOf(Object.class)); - row.set("max_temperature", Data.nullOf(Object.class)); - - byte[] bytes = CoderUtils.encodeToByteArray(TableRowJsonCoder.of(), row); - - TableRow newRow = CoderUtils.decodeFromByteArray(TableRowJsonCoder.of(), bytes); - byte[] newBytes = CoderUtils.encodeToByteArray(TableRowJsonCoder.of(), newRow); - - Assert.assertArrayEquals(bytes, newBytes); - } - - @Test - public void testBigQueryIOGetName() { - assertEquals("BigQueryIO.Read", BigQueryIO.Read.from("somedataset.sometable").getName()); - assertEquals("BigQueryIO.Write", BigQueryIO.Write.to("somedataset.sometable").getName()); - assertEquals("ReadMyTable", BigQueryIO.Read.named("ReadMyTable").getName()); - assertEquals("WriteMyTable", BigQueryIO.Write.named("WriteMyTable").getName()); - } - - @Test - public void testWriteValidateFailsCreateNoSchema() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("no schema was provided"); - TestPipeline.create() - .apply(Create.of()) - .apply(BigQueryIO.Write - .to("dataset.table") - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)); - } - - @Test - public void testWriteValidateFailsTableAndTableSpec() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Cannot set both a table reference and a table function"); - TestPipeline.create() - .apply(Create.of()) - .apply(BigQueryIO.Write - .to("dataset.table") - .to(new SerializableFunction() { - @Override - public String apply(BoundedWindow input) { - return null; - } - })); - } - - @Test - public void testWriteValidateFailsNoTableAndNoTableSpec() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("must set the table reference of a BigQueryIO.Write transform"); - TestPipeline.create() - .apply(Create.of()) - .apply(BigQueryIO.Write.named("name")); - } - - @Test - public void testBigQueryTableSourceThroughJsonAPI() throws Exception { - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(mockJobService) - .readerReturns( - toJsonString(new TableRow().set("name", "a").set("number", "1")), - toJsonString(new TableRow().set("name", "b").set("number", "2")), - toJsonString(new TableRow().set("name", "c").set("number", "3"))); - - String jobIdToken = "testJobIdToken"; - TableReference table = BigQueryIO.parseTableSpec("project:data_set.table_name"); - String extractDestinationDir = "mock://tempLocation"; - BoundedSource bqSource = BigQueryTableSource.create( - jobIdToken, StaticValueProvider.of(table), extractDestinationDir, fakeBqServices, - StaticValueProvider.of("project")); - - List expected = ImmutableList.of( - new TableRow().set("name", "a").set("number", "1"), - new TableRow().set("name", "b").set("number", "2"), - new TableRow().set("name", "c").set("number", "3")); - - PipelineOptions options = PipelineOptionsFactory.create(); - Assert.assertThat( - SourceTestUtils.readFromSource(bqSource, options), - CoreMatchers.is(expected)); - SourceTestUtils.assertSplitAtFractionBehavior( - bqSource, 2, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - } - - @Test - public void testBigQueryTableSourceInitSplit() throws Exception { - Job extractJob = new Job(); - JobStatistics jobStats = new JobStatistics(); - JobStatistics4 extractStats = new JobStatistics4(); - extractStats.setDestinationUriFileCounts(ImmutableList.of(1L)); - jobStats.setExtract(extractStats); - extractJob.setStatus(new JobStatus()) - .setStatistics(jobStats); - - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(mockJobService) - .withDatasetService(mockDatasetService) - .readerReturns( - toJsonString(new TableRow().set("name", "a").set("number", "1")), - toJsonString(new TableRow().set("name", "b").set("number", "2")), - toJsonString(new TableRow().set("name", "c").set("number", "3"))); - - String jobIdToken = "testJobIdToken"; - TableReference table = BigQueryIO.parseTableSpec("project:data_set.table_name"); - String extractDestinationDir = "mock://tempLocation"; - BoundedSource bqSource = BigQueryTableSource.create( - jobIdToken, StaticValueProvider.of(table), extractDestinationDir, fakeBqServices, - StaticValueProvider.of("project")); - - List expected = ImmutableList.of( - new TableRow().set("name", "a").set("number", "1"), - new TableRow().set("name", "b").set("number", "2"), - new TableRow().set("name", "c").set("number", "3")); - - when(mockJobService.pollJob(Mockito.any(), Mockito.anyInt())) - .thenReturn(extractJob); - PipelineOptions options = PipelineOptionsFactory.create(); - options.setTempLocation("mock://tempLocation"); - - IOChannelUtils.setIOFactory("mock", mockIOChannelFactory); - when(mockIOChannelFactory.resolve(anyString(), anyString())) - .thenReturn("mock://tempLocation/output"); - when(mockDatasetService.getTable(anyString(), anyString(), anyString())) - .thenReturn(new Table().setSchema(new TableSchema())); - - Assert.assertThat( - SourceTestUtils.readFromSource(bqSource, options), - CoreMatchers.is(expected)); - SourceTestUtils.assertSplitAtFractionBehavior( - bqSource, 2, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - - List> sources = bqSource.splitIntoBundles(100, options); - assertEquals(1, sources.size()); - BoundedSource actual = sources.get(0); - assertThat(actual, CoreMatchers.instanceOf(TransformingSource.class)); - - Mockito.verify(mockJobService) - .startExtractJob(Mockito.any(), Mockito.any()); - } - - @Test - public void testBigQueryQuerySourceInitSplit() throws Exception { - TableReference dryRunTable = new TableReference(); - - Job queryJob = new Job(); - JobStatistics queryJobStats = new JobStatistics(); - JobStatistics2 queryStats = new JobStatistics2(); - queryStats.setReferencedTables(ImmutableList.of(dryRunTable)); - queryJobStats.setQuery(queryStats); - queryJob.setStatus(new JobStatus()) - .setStatistics(queryJobStats); - - Job extractJob = new Job(); - JobStatistics extractJobStats = new JobStatistics(); - JobStatistics4 extractStats = new JobStatistics4(); - extractStats.setDestinationUriFileCounts(ImmutableList.of(1L)); - extractJobStats.setExtract(extractStats); - extractJob.setStatus(new JobStatus()) - .setStatistics(extractJobStats); - - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(mockJobService) - .withDatasetService(mockDatasetService) - .readerReturns( - toJsonString(new TableRow().set("name", "a").set("number", "1")), - toJsonString(new TableRow().set("name", "b").set("number", "2")), - toJsonString(new TableRow().set("name", "c").set("number", "3"))); - - String jobIdToken = "testJobIdToken"; - String extractDestinationDir = "mock://tempLocation"; - TableReference destinationTable = BigQueryIO.parseTableSpec("project:data_set.table_name"); - BoundedSource bqSource = BigQueryQuerySource.create( - jobIdToken, StaticValueProvider.of("query"), StaticValueProvider.of(destinationTable), - true /* flattenResults */, true /* useLegacySql */, - extractDestinationDir, fakeBqServices); - - List expected = ImmutableList.of( - new TableRow().set("name", "a").set("number", "1"), - new TableRow().set("name", "b").set("number", "2"), - new TableRow().set("name", "c").set("number", "3")); - - PipelineOptions options = PipelineOptionsFactory.create(); - options.setTempLocation(extractDestinationDir); - - TableReference queryTable = new TableReference() - .setProjectId("testProejct") - .setDatasetId("testDataset") - .setTableId("testTable"); - when(mockJobService.dryRunQuery(anyString(), Mockito.any())) - .thenReturn(new JobStatistics().setQuery( - new JobStatistics2() - .setTotalBytesProcessed(100L) - .setReferencedTables(ImmutableList.of(queryTable)))); - when(mockDatasetService.getTable( - eq(queryTable.getProjectId()), eq(queryTable.getDatasetId()), eq(queryTable.getTableId()))) - .thenReturn(new Table().setSchema(new TableSchema())); - when(mockDatasetService.getTable( - eq(destinationTable.getProjectId()), - eq(destinationTable.getDatasetId()), - eq(destinationTable.getTableId()))) - .thenReturn(new Table().setSchema(new TableSchema())); - IOChannelUtils.setIOFactory("mock", mockIOChannelFactory); - when(mockIOChannelFactory.resolve(anyString(), anyString())) - .thenReturn("mock://tempLocation/output"); - when(mockJobService.pollJob(Mockito.any(), Mockito.anyInt())) - .thenReturn(extractJob); - - Assert.assertThat( - SourceTestUtils.readFromSource(bqSource, options), - CoreMatchers.is(expected)); - SourceTestUtils.assertSplitAtFractionBehavior( - bqSource, 2, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - - List> sources = bqSource.splitIntoBundles(100, options); - assertEquals(1, sources.size()); - BoundedSource actual = sources.get(0); - assertThat(actual, CoreMatchers.instanceOf(TransformingSource.class)); - - Mockito.verify(mockJobService) - .startQueryJob( - Mockito.any(), Mockito.any()); - Mockito.verify(mockJobService) - .startExtractJob(Mockito.any(), Mockito.any()); - Mockito.verify(mockDatasetService) - .createDataset(anyString(), anyString(), anyString(), anyString()); - ArgumentCaptor queryConfigArg = - ArgumentCaptor.forClass(JobConfigurationQuery.class); - Mockito.verify(mockJobService).dryRunQuery(anyString(), queryConfigArg.capture()); - assertEquals(true, queryConfigArg.getValue().getFlattenResults()); - assertEquals(true, queryConfigArg.getValue().getUseLegacySql()); - } - - @Test - public void testBigQueryNoTableQuerySourceInitSplit() throws Exception { - TableReference dryRunTable = new TableReference(); - - Job queryJob = new Job(); - JobStatistics queryJobStats = new JobStatistics(); - JobStatistics2 queryStats = new JobStatistics2(); - queryStats.setReferencedTables(ImmutableList.of(dryRunTable)); - queryJobStats.setQuery(queryStats); - queryJob.setStatus(new JobStatus()) - .setStatistics(queryJobStats); - - Job extractJob = new Job(); - JobStatistics extractJobStats = new JobStatistics(); - JobStatistics4 extractStats = new JobStatistics4(); - extractStats.setDestinationUriFileCounts(ImmutableList.of(1L)); - extractJobStats.setExtract(extractStats); - extractJob.setStatus(new JobStatus()) - .setStatistics(extractJobStats); - - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(mockJobService) - .withDatasetService(mockDatasetService) - .readerReturns( - toJsonString(new TableRow().set("name", "a").set("number", "1")), - toJsonString(new TableRow().set("name", "b").set("number", "2")), - toJsonString(new TableRow().set("name", "c").set("number", "3"))); - - String jobIdToken = "testJobIdToken"; - String extractDestinationDir = "mock://tempLocation"; - TableReference destinationTable = BigQueryIO.parseTableSpec("project:data_set.table_name"); - BoundedSource bqSource = BigQueryQuerySource.create( - jobIdToken, StaticValueProvider.of("query"), StaticValueProvider.of(destinationTable), - true /* flattenResults */, true /* useLegacySql */, - extractDestinationDir, fakeBqServices); - - List expected = ImmutableList.of( - new TableRow().set("name", "a").set("number", "1"), - new TableRow().set("name", "b").set("number", "2"), - new TableRow().set("name", "c").set("number", "3")); - - PipelineOptions options = PipelineOptionsFactory.create(); - options.setTempLocation(extractDestinationDir); - - when(mockJobService.dryRunQuery(anyString(), Mockito.any())) - .thenReturn(new JobStatistics().setQuery( - new JobStatistics2() - .setTotalBytesProcessed(100L))); - when(mockDatasetService.getTable( - eq(destinationTable.getProjectId()), - eq(destinationTable.getDatasetId()), - eq(destinationTable.getTableId()))) - .thenReturn(new Table().setSchema(new TableSchema())); - IOChannelUtils.setIOFactory("mock", mockIOChannelFactory); - when(mockIOChannelFactory.resolve(anyString(), anyString())) - .thenReturn("mock://tempLocation/output"); - when(mockJobService.pollJob(Mockito.any(), Mockito.anyInt())) - .thenReturn(extractJob); - - Assert.assertThat( - SourceTestUtils.readFromSource(bqSource, options), - CoreMatchers.is(expected)); - SourceTestUtils.assertSplitAtFractionBehavior( - bqSource, 2, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - - List> sources = bqSource.splitIntoBundles(100, options); - assertEquals(1, sources.size()); - BoundedSource actual = sources.get(0); - assertThat(actual, CoreMatchers.instanceOf(TransformingSource.class)); - - Mockito.verify(mockJobService) - .startQueryJob( - Mockito.any(), Mockito.any()); - Mockito.verify(mockJobService) - .startExtractJob(Mockito.any(), Mockito.any()); - Mockito.verify(mockDatasetService) - .createDataset(anyString(), anyString(), anyString(), anyString()); - ArgumentCaptor queryConfigArg = - ArgumentCaptor.forClass(JobConfigurationQuery.class); - Mockito.verify(mockJobService).dryRunQuery(anyString(), queryConfigArg.capture()); - assertEquals(true, queryConfigArg.getValue().getFlattenResults()); - assertEquals(true, queryConfigArg.getValue().getUseLegacySql()); - } - - @Test - public void testTransformingSource() throws Exception { - int numElements = 10000; - @SuppressWarnings("deprecation") - BoundedSource longSource = CountingSource.upTo(numElements); - SerializableFunction toStringFn = - new SerializableFunction() { - @Override - public String apply(Long input) { - return input.toString(); - }}; - BoundedSource stringSource = new TransformingSource<>( - longSource, toStringFn, StringUtf8Coder.of()); - - List expected = Lists.newArrayList(); - for (int i = 0; i < numElements; i++) { - expected.add(String.valueOf(i)); - } - - PipelineOptions options = PipelineOptionsFactory.create(); - Assert.assertThat( - SourceTestUtils.readFromSource(stringSource, options), - CoreMatchers.is(expected)); - SourceTestUtils.assertSplitAtFractionBehavior( - stringSource, 100, 0.3, ExpectedSplitOutcome.MUST_SUCCEED_AND_BE_CONSISTENT, options); - - SourceTestUtils.assertSourcesEqualReferenceSource( - stringSource, stringSource.splitIntoBundles(100, options), options); - } - - @Test - public void testTransformingSourceUnsplittable() throws Exception { - int numElements = 10000; - @SuppressWarnings("deprecation") - BoundedSource longSource = - SourceTestUtils.toUnsplittableSource(CountingSource.upTo(numElements)); - SerializableFunction toStringFn = - new SerializableFunction() { - @Override - public String apply(Long input) { - return input.toString(); - } - }; - BoundedSource stringSource = - new TransformingSource<>(longSource, toStringFn, StringUtf8Coder.of()); - - List expected = Lists.newArrayList(); - for (int i = 0; i < numElements; i++) { - expected.add(String.valueOf(i)); - } - - PipelineOptions options = PipelineOptionsFactory.create(); - Assert.assertThat( - SourceTestUtils.readFromSource(stringSource, options), CoreMatchers.is(expected)); - SourceTestUtils.assertSplitAtFractionBehavior( - stringSource, 100, 0.3, ExpectedSplitOutcome.MUST_BE_CONSISTENT_IF_SUCCEEDS, options); - - SourceTestUtils.assertSourcesEqualReferenceSource( - stringSource, stringSource.splitIntoBundles(100, options), options); - } - - @Test - @Category(RunnableOnService.class) - public void testPassThroughThenCleanup() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(1, 2, 3)) - .apply(new PassThroughThenCleanup(new CleanupOperation() { - @Override - void cleanup(PipelineOptions options) throws Exception { - // no-op - }})); - - DataflowAssert.that(output).containsInAnyOrder(1, 2, 3); - - p.run(); - } - - @Test - public void testPassThroughThenCleanupExecuted() throws Exception { - Pipeline p = TestPipeline.create(); - - p.apply(Create.of()) - .apply(new PassThroughThenCleanup(new CleanupOperation() { - @Override - void cleanup(PipelineOptions options) throws Exception { - throw new RuntimeException("cleanup executed"); - }})); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("cleanup executed"); - - p.run(); - } - - @Test - public void testWritePartitionEmptyData() throws Exception { - long numFiles = 0; - long fileSize = 0; - - // An empty file is created for no input data. One partition is needed. - long expectedNumPartitions = 1; - testWritePartition(numFiles, fileSize, expectedNumPartitions); - } - - @Test - public void testWritePartitionSinglePartition() throws Exception { - long numFiles = BigQueryIO.Write.Bound.MAX_NUM_FILES; - long fileSize = 1; - - // One partition is needed. - long expectedNumPartitions = 1; - testWritePartition(numFiles, fileSize, expectedNumPartitions); - } - - @Test - public void testWritePartitionManyFiles() throws Exception { - long numFiles = BigQueryIO.Write.Bound.MAX_NUM_FILES * 3; - long fileSize = 1; - - // One partition is needed for each group of BigQueryWrite.MAX_NUM_FILES files. - long expectedNumPartitions = 3; - testWritePartition(numFiles, fileSize, expectedNumPartitions); - } - - @Test - public void testWritePartitionLargeFileSize() throws Exception { - long numFiles = 10; - long fileSize = BigQueryIO.Write.Bound.MAX_SIZE_BYTES / 3; - - // One partition is needed for each group of three files. - long expectedNumPartitions = 4; - testWritePartition(numFiles, fileSize, expectedNumPartitions); - } - - private void testWritePartition(long numFiles, long fileSize, long expectedNumPartitions) - throws Exception { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); - - List expectedPartitionIds = Lists.newArrayList(); - for (long i = 1; i <= expectedNumPartitions; ++i) { - expectedPartitionIds.add(i); - } - - List> files = Lists.newArrayList(); - List fileNames = Lists.newArrayList(); - for (int i = 0; i < numFiles; ++i) { - String fileName = String.format("files%05d", i); - fileNames.add(fileName); - files.add(KV.of(fileName, fileSize)); - } - - TupleTag>> multiPartitionsTag = - new TupleTag>>("multiPartitionsTag") {}; - TupleTag>> singlePartitionTag = - new TupleTag>>("singlePartitionTag") {}; - - PCollectionView>> filesView = PCollectionViews.iterableView( - TestPipeline.create(), - WindowingStrategy.globalDefault(), - KvCoder.of(StringUtf8Coder.of(), VarLongCoder.of())); - - WritePartition writePartition = - new WritePartition(filesView, multiPartitionsTag, singlePartitionTag); - - DoFnTester>> tester = DoFnTester.of(writePartition); - tester.setSideInputInGlobalWindow(filesView, files); - tester.processElement(bqOptions.getTempLocation()); - - List>> partitions; - if (expectedNumPartitions > 1) { - partitions = tester.takeSideOutputElements(multiPartitionsTag); - } else { - partitions = tester.takeSideOutputElements(singlePartitionTag); - } - List partitionIds = Lists.newArrayList(); - List partitionFileNames = Lists.newArrayList(); - for (KV> partition : partitions) { - partitionIds.add(partition.getKey()); - for (String name : partition.getValue()) { - partitionFileNames.add(name); - } - } - - assertEquals(expectedPartitionIds, partitionIds); - if (numFiles == 0) { - assertThat(partitionFileNames, Matchers.hasSize(1)); - assertTrue(Files.exists(Paths.get(partitionFileNames.get(0)))); - assertThat(Files.readAllBytes(Paths.get(partitionFileNames.get(0))).length, - Matchers.equalTo(0)); - } else { - assertEquals(fileNames, partitionFileNames); - } - } - - @Test - public void testWriteTables() throws Exception { - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(new FakeJobService() - .startJobReturns("done", "done", "done", "done") - .pollJobReturns(Status.FAILED, Status.SUCCEEDED, Status.SUCCEEDED, Status.SUCCEEDED)); - - long numPartitions = 3; - long numFilesPerPartition = 10; - String jobIdToken = "jobIdToken"; - String tempFilePrefix = "tempFilePrefix"; - String jsonTable = "{}"; - String jsonSchema = "{}"; - List expectedTempTables = Lists.newArrayList(); - - List>>> partitions = Lists.newArrayList(); - for (long i = 0; i < numPartitions; ++i) { - List filesPerPartition = Lists.newArrayList(); - for (int j = 0; j < numFilesPerPartition; ++j) { - filesPerPartition.add(String.format("files%05d", j)); - } - partitions.add(KV.of(i, (Iterable>) Collections.singleton(filesPerPartition))); - expectedTempTables.add(String.format("{\"tableId\":\"%s_%05d\"}", jobIdToken, i)); - } - - WriteTables writeTables = new WriteTables( - false, - fakeBqServices, - jobIdToken, - tempFilePrefix, - StaticValueProvider.of(jsonTable), - StaticValueProvider.of(jsonSchema), - WriteDisposition.WRITE_EMPTY, - CreateDisposition.CREATE_IF_NEEDED); - - DoFnTester>>, String> tester = DoFnTester.of(writeTables); - for (KV>> partition : partitions) { - tester.processElement(partition); - } - - List tempTables = tester.takeOutputElements(); - - logged.verifyInfo("Starting BigQuery load job"); - logged.verifyInfo("BigQuery load job failed"); - logged.verifyInfo("try 0/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - logged.verifyInfo("try 1/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - logged.verifyNotLogged("try 2/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - - assertEquals(expectedTempTables, tempTables); - } - - @Test - public void testRemoveTemporaryFiles() throws Exception { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("defaultProject"); - bqOptions.setTempLocation(testFolder.newFolder("BigQueryIOTest").getAbsolutePath()); - - int numFiles = 10; - List fileNames = Lists.newArrayList(); - String tempFilePrefix = bqOptions.getTempLocation() + "/"; - TableRowWriter writer = new TableRowWriter(tempFilePrefix); - for (int i = 0; i < numFiles; ++i) { - String fileName = String.format("files%05d", i); - writer.open(fileName); - fileNames.add(writer.close().getKey()); - } - fileNames.add(tempFilePrefix + String.format("files%05d", numFiles)); - - File tempDir = new File(bqOptions.getTempLocation()); - testNumFiles(tempDir, 10); - - WriteTables.removeTemporaryFiles(bqOptions, tempFilePrefix, fileNames); - - testNumFiles(tempDir, 0); - - for (String fileName : fileNames) { - logged.verifyDebug("Removing file " + fileName); - } - logged.verifyDebug(fileNames.get(numFiles) + " does not exist."); - } - - @Test - public void testWriteRename() throws Exception { - FakeBigQueryServices fakeBqServices = new FakeBigQueryServices() - .withJobService(new FakeJobService() - .startJobReturns("done", "done") - .pollJobReturns(Status.FAILED, Status.SUCCEEDED)) - .withDatasetService(mockDatasetService); - - long numTempTables = 3; - String jobIdToken = "jobIdToken"; - String jsonTable = "{}"; - List tempTables = Lists.newArrayList(); - for (long i = 0; i < numTempTables; ++i) { - tempTables.add(String.format("{\"tableId\":\"%s_%05d\"}", jobIdToken, i)); - } - - PCollectionView> tempTablesView = PCollectionViews.iterableView( - TestPipeline.create(), - WindowingStrategy.globalDefault(), - StringUtf8Coder.of()); - - WriteRename writeRename = new WriteRename( - fakeBqServices, - jobIdToken, - StaticValueProvider.of(jsonTable), - WriteDisposition.WRITE_EMPTY, - CreateDisposition.CREATE_IF_NEEDED, - tempTablesView); - - DoFnTester tester = DoFnTester.of(writeRename); - tester.setSideInputInGlobalWindow(tempTablesView, tempTables); - tester.processElement(null); - - logged.verifyInfo("Starting BigQuery copy job"); - logged.verifyInfo("BigQuery copy job failed"); - logged.verifyInfo("try 0/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - logged.verifyInfo("try 1/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - logged.verifyNotLogged("try 2/" + BigQueryIO.Write.Bound.MAX_RETRY_JOBS); - } - - @Test - public void testRemoveTemporaryTables() throws Exception { - String projectId = "someproject"; - String datasetId = "somedataset"; - List tables = Lists.newArrayList("table1", "table2", "table3"); - List tableRefs = Lists.newArrayList( - BigQueryIO.parseTableSpec(String.format("%s:%s.%s", projectId, datasetId, tables.get(0))), - BigQueryIO.parseTableSpec(String.format("%s:%s.%s", projectId, datasetId, tables.get(1))), - BigQueryIO.parseTableSpec(String.format("%s:%s.%s", projectId, datasetId, tables.get(2)))); - - doThrow(new IOException("Unable to delete table")) - .when(mockDatasetService).deleteTable(projectId, datasetId, tables.get(0)); - doNothing().when(mockDatasetService).deleteTable(projectId, datasetId, tables.get(1)); - doNothing().when(mockDatasetService).deleteTable(projectId, datasetId, tables.get(2)); - - WriteRename.removeTemporaryTables(mockDatasetService, tableRefs); - - for (TableReference ref : tableRefs) { - logged.verifyDebug("Deleting table " + toJsonString(ref)); - } - logged.verifyWarn("Failed to delete the table " + toJsonString(tableRefs.get(0))); - logged.verifyNotLogged("Failed to delete the table " + toJsonString(tableRefs.get(1))); - logged.verifyNotLogged("Failed to delete the table " + toJsonString(tableRefs.get(2))); - } - - /** Test options. **/ - public interface RuntimeTestOptions extends PipelineOptions { - ValueProvider getInputTable(); - void setInputTable(ValueProvider value); - - ValueProvider getInputQuery(); - void setInputQuery(ValueProvider value); - - ValueProvider getOutputTable(); - void setOutputTable(ValueProvider value); - - ValueProvider getOutputSchema(); - void setOutputSchema(ValueProvider value); - } - - @Test - public void testRuntimeOptionsNotCalledInApplyInputTable() { - RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - bqOptions.setTempLocation("gs://testbucket/testdir"); - Pipeline pipeline = TestPipeline.create(options); - BigQueryIO.Read.Bound read = BigQueryIO.Read.from( - options.getInputTable()).withoutValidation(); - pipeline.apply(read); - // Test that this doesn't throw. - DisplayData.from(read); - } - - @Test - public void testRuntimeOptionsNotCalledInApplyInputQuery() { - RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - bqOptions.setTempLocation("gs://testbucket/testdir"); - Pipeline pipeline = TestPipeline.create(options); - BigQueryIO.Read.Bound read = BigQueryIO.Read.fromQuery( - options.getInputQuery()).withoutValidation(); - pipeline.apply(read); - // Test that this doesn't throw. - DisplayData.from(read); - } - - @Test - public void testRuntimeOptionsNotCalledInApplyOutput() { - RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - bqOptions.setTempLocation("gs://testbucket/testdir"); - Pipeline pipeline = TestPipeline.create(options); - BigQueryIO.Write.Bound write = BigQueryIO.Write - .to(options.getOutputTable()) - .withSchema(NestedValueProvider.of( - options.getOutputSchema(), new JsonSchemaToTableSchema())) - .withoutValidation(); - pipeline - .apply(Create.of()) - .apply(write); - // Test that this doesn't throw. - DisplayData.from(write); - } - - @Test - public void testTagWithUniqueIdsAndTableProjectNotNullWithNvp() { - BigQueryOptions bqOptions = PipelineOptionsFactory.as(BigQueryOptions.class); - bqOptions.setProject("project"); - BigQueryIO.TagWithUniqueIdsAndTable tag = - new BigQueryIO.TagWithUniqueIdsAndTable( - bqOptions, NestedValueProvider.of( - StaticValueProvider.of("data_set.table_name"), - new BigQueryIO.TableSpecToTableRef()), null); - TableReference table = BigQueryIO.parseTableSpec(tag.getTableSpec().get()); - assertNotNull(table.getProjectId()); - } - - @Test - public void testWriteHandlesNullTable() { - BigQueryIO.Write.Bound write = BigQueryIO.Write - .withoutValidation(); - assertNull(write.getTable()); - } - - private static void testNumFiles(File tempDir, int expectedNumFiles) { - assertEquals(expectedNumFiles, tempDir.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isFile(); - }}).length); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java deleted file mode 100644 index 3aef499305..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BoundedReadFromUnboundedSourceTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import org.joda.time.Duration; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** Unit tests for {@link BoundedReadFromUnboundedSource}. */ -@RunWith(JUnit4.class) -public class BoundedReadFromUnboundedSourceTest implements Serializable{ - private static final int NUM_RECORDS = 100; - private static List finalizeTracker = null; - - @Test - @Category(RunnableOnService.class) - public void testNoDedup() throws Exception { - test(false, false); - } - - @Test - @Category(RunnableOnService.class) - public void testDedup() throws Exception { - test(true, false); - } - - @Test - @Category(RunnableOnService.class) - public void testTimeBound() throws Exception { - test(false, true); - } - - @Test - public void testForwardsDisplayData() { - TestCountingSource src = new TestCountingSource(1234) { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - BoundedReadFromUnboundedSource> read = Read.from(src).withMaxNumRecords(5); - assertThat(DisplayData.from(read), includesDisplayDataFrom(src)); - } - - private static class Checker - implements SerializableFunction>, Void> { - private final boolean dedup; - private final boolean timeBound; - - Checker(boolean dedup, boolean timeBound) { - this.dedup = dedup; - this.timeBound = timeBound; - } - - @Override - public Void apply(Iterable> input) { - List values = new ArrayList<>(); - for (KV kv : input) { - assertEquals(0, (int) kv.getKey()); - values.add(kv.getValue()); - } - if (timeBound) { - assertTrue(values.size() >= 1); - } else if (dedup) { - // Verify that at least some data came through. The chance of 90% of the input - // being duplicates is essentially zero. - assertTrue(values.size() > NUM_RECORDS / 10 && values.size() <= NUM_RECORDS); - } else { - assertEquals(NUM_RECORDS, values.size()); - } - Collections.sort(values); - for (int i = 0; i < values.size(); i++) { - assertEquals(i, (int) values.get(i)); - } - if (finalizeTracker != null) { - assertThat(finalizeTracker, containsInAnyOrder(values.size() - 1)); - } - return null; - } - } - - private void test(boolean dedup, boolean timeBound) throws Exception { - Pipeline p = TestPipeline.create(); - - if (p.getOptions().getRunner() == DirectPipelineRunner.class) { - finalizeTracker = new ArrayList<>(); - TestCountingSource.setFinalizeTracker(finalizeTracker); - } - TestCountingSource source = new TestCountingSource(Integer.MAX_VALUE).withoutSplitting(); - if (dedup) { - source = source.withDedup(); - } - PCollection> output = - timeBound - ? p.apply(Read.from(source).withMaxReadTime(Duration.millis(20))) - : p.apply(Read.from(source).withMaxNumRecords(NUM_RECORDS)); - - // Because some of the NUM_RECORDS elements read are dupes, the final output - // will only have output from 0 to n where n < NUM_RECORDS. - DataflowAssert.that(output).satisfies(new Checker(dedup, timeBound)); - - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java deleted file mode 100644 index 9f4f3cf246..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CompressedSourceTest.java +++ /dev/null @@ -1,654 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.CompressedSource.CompressedReader; -import com.google.cloud.dataflow.sdk.io.CompressedSource.CompressionMode; -import com.google.cloud.dataflow.sdk.io.CompressedSource.DecompressingChannelFactory; -import com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.io.Files; -import com.google.common.primitives.Bytes; - -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; -import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Random; -import java.util.zip.GZIPOutputStream; - -import javax.annotation.Nullable; - -/** - * Tests for CompressedSource. - */ -@RunWith(JUnit4.class) -public class CompressedSourceTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Test reading nonempty input with gzip. - */ - @Test - public void testReadGzip() throws Exception { - byte[] input = generateInput(5000); - runReadTest(input, CompressionMode.GZIP); - } - - /** - * Test splittability of files in AUTO mode. - */ - @Test - public void testAutoSplittable() throws Exception { - CompressedSource source; - - // GZip files are not splittable - source = CompressedSource.from(new ByteSource("input.gz", 1)); - assertFalse(source.isSplittable()); - source = CompressedSource.from(new ByteSource("input.GZ", 1)); - assertFalse(source.isSplittable()); - - // BZ2 files are not splittable - source = CompressedSource.from(new ByteSource("input.bz2", 1)); - assertFalse(source.isSplittable()); - source = CompressedSource.from(new ByteSource("input.BZ2", 1)); - assertFalse(source.isSplittable()); - - // Other extensions are assumed to be splittable. - source = CompressedSource.from(new ByteSource("input.txt", 1)); - assertTrue(source.isSplittable()); - source = CompressedSource.from(new ByteSource("input.csv", 1)); - assertTrue(source.isSplittable()); - } - - /** - * Test splittability of files in GZIP mode -- none should be splittable. - */ - @Test - public void testGzipSplittable() throws Exception { - CompressedSource source; - - // GZip files are not splittable - source = CompressedSource.from(new ByteSource("input.gz", 1)) - .withDecompression(CompressionMode.GZIP); - assertFalse(source.isSplittable()); - source = CompressedSource.from(new ByteSource("input.GZ", 1)) - .withDecompression(CompressionMode.GZIP); - assertFalse(source.isSplittable()); - - // Other extensions are also not splittable. - source = CompressedSource.from(new ByteSource("input.txt", 1)) - .withDecompression(CompressionMode.GZIP); - assertFalse(source.isSplittable()); - source = CompressedSource.from(new ByteSource("input.csv", 1)) - .withDecompression(CompressionMode.GZIP); - assertFalse(source.isSplittable()); - } - - /** - * Test reading nonempty input with bzip2. - */ - @Test - public void testReadBzip2() throws Exception { - byte[] input = generateInput(5000); - runReadTest(input, CompressionMode.BZIP2); - } - - /** - * Test reading empty input with gzip. - */ - @Test - public void testEmptyReadGzip() throws Exception { - byte[] input = generateInput(0); - runReadTest(input, CompressionMode.GZIP); - } - - private static byte[] compressGzip(byte[] input) throws IOException { - ByteArrayOutputStream res = new ByteArrayOutputStream(); - try (GZIPOutputStream gzipStream = new GZIPOutputStream(res)) { - gzipStream.write(input); - } - return res.toByteArray(); - } - - private static byte[] concat(byte[] first, byte[] second) { - byte[] res = new byte[first.length + second.length]; - System.arraycopy(first, 0, res, 0, first.length); - System.arraycopy(second, 0, res, first.length, second.length); - return res; - } - - /** - * Test a concatenation of gzip files is correctly decompressed. - * - *

              A concatenation of gzip files as one file is a valid gzip file and should decompress - * to be the concatenation of those individual files. - */ - @Test - public void testReadConcatenatedGzip() throws IOException { - byte[] header = "a,b,c\n".getBytes(StandardCharsets.UTF_8); - byte[] body = "1,2,3\n4,5,6\n7,8,9\n".getBytes(StandardCharsets.UTF_8); - byte[] expected = concat(header, body); - byte[] totalGz = concat(compressGzip(header), compressGzip(body)); - File tmpFile = tmpFolder.newFile(); - try (FileOutputStream os = new FileOutputStream(tmpFile)) { - os.write(totalGz); - } - - Pipeline p = TestPipeline.create(); - - CompressedSource source = - CompressedSource.from(new ByteSource(tmpFile.getAbsolutePath(), 1)) - .withDecompression(CompressionMode.GZIP); - PCollection output = p.apply(Read.from(source)); - - DataflowAssert.that(output).containsInAnyOrder(Bytes.asList(expected)); - p.run(); - } - - /** - * Test reading empty input with bzip2. - */ - @Test - public void testCompressedReadBzip2() throws Exception { - byte[] input = generateInput(0); - runReadTest(input, CompressionMode.BZIP2); - } - - /** - * Test reading according to filepattern when the file is bzipped. - */ - @Test - public void testCompressedAccordingToFilepatternGzip() throws Exception { - byte[] input = generateInput(100); - File tmpFile = tmpFolder.newFile("test.gz"); - writeFile(tmpFile, input, CompressionMode.GZIP); - verifyReadContents(input, tmpFile, null /* default auto decompression factory */); - } - - /** - * Test reading according to filepattern when the file is gzipped. - */ - @Test - public void testCompressedAccordingToFilepatternBzip2() throws Exception { - byte[] input = generateInput(100); - File tmpFile = tmpFolder.newFile("test.bz2"); - writeFile(tmpFile, input, CompressionMode.BZIP2); - verifyReadContents(input, tmpFile, null /* default auto decompression factory */); - } - - /** - * Test reading multiple files with different compression. - */ - @Test - public void testHeterogeneousCompression() throws Exception { - String baseName = "test-input"; - - // Expected data - byte[] generated = generateInput(1000); - List expected = new ArrayList<>(); - - // Every sort of compression - File uncompressedFile = tmpFolder.newFile(baseName + ".bin"); - generated = generateInput(1000); - Files.write(generated, uncompressedFile); - expected.addAll(Bytes.asList(generated)); - - File gzipFile = tmpFolder.newFile(baseName + ".gz"); - generated = generateInput(1000); - writeFile(gzipFile, generated, CompressionMode.GZIP); - expected.addAll(Bytes.asList(generated)); - - File bzip2File = tmpFolder.newFile(baseName + ".bz2"); - generated = generateInput(1000); - writeFile(bzip2File, generateInput(1000), CompressionMode.BZIP2); - expected.addAll(Bytes.asList(generated)); - - String filePattern = new File(tmpFolder.getRoot().toString(), baseName + ".*").toString(); - - Pipeline p = TestPipeline.create(); - - CompressedSource source = - CompressedSource.from(new ByteSource(filePattern, 1)); - PCollection output = p.apply(Read.from(source)); - - DataflowAssert.that(output).containsInAnyOrder(expected); - p.run(); - } - - @Test - public void testUncompressedFileIsSplittable() throws Exception { - String baseName = "test-input"; - - File uncompressedFile = tmpFolder.newFile(baseName + ".bin"); - Files.write(generateInput(10), uncompressedFile); - - CompressedSource source = - CompressedSource.from(new ByteSource(uncompressedFile.getPath(), 1)); - assertTrue(source.isSplittable()); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testGzipFileIsNotSplittable() throws Exception { - String baseName = "test-input"; - - File compressedFile = tmpFolder.newFile(baseName + ".gz"); - writeFile(compressedFile, generateInput(10), CompressionMode.GZIP); - - CompressedSource source = - CompressedSource.from(new ByteSource(compressedFile.getPath(), 1)); - assertFalse(source.isSplittable()); - } - - @Test - public void testBzip2FileIsNotSplittable() throws Exception { - String baseName = "test-input"; - - File compressedFile = tmpFolder.newFile(baseName + ".bz2"); - writeFile(compressedFile, generateInput(10), CompressionMode.BZIP2); - - CompressedSource source = - CompressedSource.from(new ByteSource(compressedFile.getPath(), 1)); - assertFalse(source.isSplittable()); - } - - /** - * Test reading an uncompressed file with {@link CompressionMode#GZIP}, since we must support - * this due to properties of services that we read from. - */ - @Test - public void testFalseGzipStream() throws Exception { - byte[] input = generateInput(1000); - File tmpFile = tmpFolder.newFile("test.gz"); - Files.write(input, tmpFile); - verifyReadContents(input, tmpFile, CompressionMode.GZIP); - } - - /** - * Test reading an uncompressed file with {@link CompressionMode#BZIP2}, and show that - * we fail. - */ - @Test - public void testFalseBzip2Stream() throws Exception { - byte[] input = generateInput(1000); - File tmpFile = tmpFolder.newFile("test.bz2"); - Files.write(input, tmpFile); - thrown.expectCause(Matchers.allOf( - instanceOf(IOException.class), - ThrowableMessageMatcher.hasMessage( - containsString("Stream is not in the BZip2 format")))); - verifyReadContents(input, tmpFile, CompressionMode.BZIP2); - } - - /** - * Test reading an empty input file with gzip; it must be interpreted as uncompressed because - * the gzip header is two bytes. - */ - @Test - public void testEmptyReadGzipUncompressed() throws Exception { - byte[] input = generateInput(0); - File tmpFile = tmpFolder.newFile("test.gz"); - Files.write(input, tmpFile); - verifyReadContents(input, tmpFile, CompressionMode.GZIP); - } - - /** - * Test reading single byte input with gzip; it must be interpreted as uncompressed because - * the gzip header is two bytes. - */ - @Test - public void testOneByteReadGzipUncompressed() throws Exception { - byte[] input = generateInput(1); - File tmpFile = tmpFolder.newFile("test.gz"); - Files.write(input, tmpFile); - verifyReadContents(input, tmpFile, CompressionMode.GZIP); - } - - /** - * Test reading multiple files. - */ - @Test - public void testCompressedReadMultipleFiles() throws Exception { - int numFiles = 10; - String baseName = "test_input-"; - String filePattern = new File(tmpFolder.getRoot().toString(), baseName + "*").toString(); - List expected = new ArrayList<>(); - - for (int i = 0; i < numFiles; i++) { - byte[] generated = generateInput(1000); - File tmpFile = tmpFolder.newFile(baseName + i); - writeFile(tmpFile, generated, CompressionMode.GZIP); - expected.addAll(Bytes.asList(generated)); - } - - Pipeline p = TestPipeline.create(); - - CompressedSource source = - CompressedSource.from(new ByteSource(filePattern, 1)) - .withDecompression(CompressionMode.GZIP); - PCollection output = p.apply(Read.from(source)); - - DataflowAssert.that(output).containsInAnyOrder(expected); - p.run(); - } - - @Test - public void testDisplayData() { - ByteSource inputSource = new ByteSource("foobar.txt", 1) { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - CompressedSource compressedSource = CompressedSource.from(inputSource); - CompressedSource gzipSource = compressedSource.withDecompression(CompressionMode.GZIP); - - DisplayData compressedSourceDisplayData = DisplayData.from(compressedSource); - DisplayData gzipDisplayData = DisplayData.from(gzipSource); - - assertThat(compressedSourceDisplayData, hasDisplayItem("compressionMode")); - assertThat(gzipDisplayData, hasDisplayItem("compressionMode", CompressionMode.GZIP.toString())); - assertThat(compressedSourceDisplayData, hasDisplayItem("source", inputSource.getClass())); - assertThat(compressedSourceDisplayData, includesDisplayDataFrom(inputSource)); - } - - /** - * Generate byte array of given size. - */ - private byte[] generateInput(int size) { - // Arbitrary but fixed seed - Random random = new Random(285930); - byte[] buff = new byte[size]; - random.nextBytes(buff); - return buff; - } - - /** - * Get a compressing stream for a given compression mode. - */ - private OutputStream getOutputStreamForMode(CompressionMode mode, OutputStream stream) - throws IOException { - switch (mode) { - case GZIP: - return new GzipCompressorOutputStream(stream); - case BZIP2: - return new BZip2CompressorOutputStream(stream); - default: - throw new RuntimeException("Unexpected compression mode"); - } - } - - /** - * Writes a single output file. - */ - private void writeFile(File file, byte[] input, CompressionMode mode) throws IOException { - try (OutputStream os = getOutputStreamForMode(mode, new FileOutputStream(file))) { - os.write(input); - } - } - - /** - * Run a single read test, writing and reading back input with the given compression mode. - */ - private void runReadTest(byte[] input, - CompressionMode inputCompressionMode, - @Nullable DecompressingChannelFactory decompressionFactory) - throws IOException { - File tmpFile = tmpFolder.newFile(); - writeFile(tmpFile, input, inputCompressionMode); - verifyReadContents(input, tmpFile, decompressionFactory); - } - - private void verifyReadContents(byte[] expected, File inputFile, - @Nullable DecompressingChannelFactory decompressionFactory) { - Pipeline p = TestPipeline.create(); - CompressedSource source = - CompressedSource.from(new ByteSource(inputFile.toPath().toString(), 1)); - if (decompressionFactory != null) { - source = source.withDecompression(decompressionFactory); - } - PCollection output = p.apply(Read.from(source)); - DataflowAssert.that(output).containsInAnyOrder(Bytes.asList(expected)); - p.run(); - } - - /** - * Run a single read test, writing and reading back input with the given compression mode. - */ - private void runReadTest(byte[] input, CompressionMode mode) throws IOException { - runReadTest(input, mode, mode); - } - - /** - * Dummy source for use in tests. - */ - private static class ByteSource extends FileBasedSource { - public ByteSource(String fileOrPatternSpec, long minBundleSize) { - super(fileOrPatternSpec, minBundleSize); - } - - public ByteSource(String fileName, long minBundleSize, long startOffset, long endOffset) { - super(fileName, minBundleSize, startOffset, endOffset); - } - - @Override - protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { - return new ByteSource(fileName, getMinBundleSize(), start, end); - } - - @Override - protected FileBasedReader createSingleFileReader(PipelineOptions options) { - return new ByteReader(this); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public Coder getDefaultOutputCoder() { - return SerializableCoder.of(Byte.class); - } - - private static class ByteReader extends FileBasedReader { - ByteBuffer buff = ByteBuffer.allocate(1); - Byte current; - long offset; - ReadableByteChannel channel; - - public ByteReader(ByteSource source) { - super(source); - offset = source.getStartOffset() - 1; - } - - @Override - public Byte getCurrent() throws NoSuchElementException { - return current; - } - - @Override - protected boolean isAtSplitPoint() { - return true; - } - - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - this.channel = channel; - } - - @Override - protected boolean readNextRecord() throws IOException { - buff.clear(); - if (channel.read(buff) != 1) { - return false; - } - current = buff.get(0); - offset += 1; - return true; - } - - @Override - protected long getCurrentOffset() { - return offset; - } - } - } - - @Test - public void testEmptyGzipProgress() throws IOException { - File tmpFile = tmpFolder.newFile("empty.gz"); - String filename = tmpFile.toPath().toString(); - writeFile(tmpFile, new byte[0], CompressionMode.GZIP); - - PipelineOptions options = PipelineOptionsFactory.create(); - CompressedSource source = CompressedSource.from(new ByteSource(filename, 1)); - try (BoundedReader readerOrig = source.createReader(options)) { - assertThat(readerOrig, instanceOf(CompressedReader.class)); - CompressedReader reader = (CompressedReader) readerOrig; - // before starting - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - - // confirm empty - assertFalse(reader.start()); - - // after reading empty source - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - public void testGzipProgress() throws IOException { - int numRecords = 3; - File tmpFile = tmpFolder.newFile("nonempty.gz"); - String filename = tmpFile.toPath().toString(); - writeFile(tmpFile, new byte[numRecords], CompressionMode.GZIP); - - PipelineOptions options = PipelineOptionsFactory.create(); - CompressedSource source = CompressedSource.from(new ByteSource(filename, 1)); - try (BoundedReader readerOrig = source.createReader(options)) { - assertThat(readerOrig, instanceOf(CompressedReader.class)); - CompressedReader reader = (CompressedReader) readerOrig; - // before starting - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - - // confirm has three records - for (int i = 0; i < numRecords; ++i) { - if (i == 0) { - assertTrue(reader.start()); - } else { - assertTrue(reader.advance()); - } - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - } - assertFalse(reader.advance()); - - // after reading empty source - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - public void testSplittableProgress() throws IOException { - File tmpFile = tmpFolder.newFile("nonempty.txt"); - String filename = tmpFile.toPath().toString(); - Files.write(new byte[2], tmpFile); - - PipelineOptions options = PipelineOptionsFactory.create(); - CompressedSource source = CompressedSource.from(new ByteSource(filename, 1)); - try (BoundedReader readerOrig = source.createReader(options)) { - assertThat(readerOrig, not(instanceOf(CompressedReader.class))); - assertThat(readerOrig, instanceOf(FileBasedReader.class)); - FileBasedReader reader = (FileBasedReader) readerOrig; - - // Check preconditions before starting - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // First record: none consumed, unknown remaining. - assertTrue(reader.start()); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Second record: 1 consumed, know that we're on the last record. - assertTrue(reader.advance()); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - - // Confirm empty and check post-conditions - assertFalse(reader.advance()); - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(2, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java deleted file mode 100644 index 529536e7a5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingInputTest.java +++ /dev/null @@ -1,184 +0,0 @@ - -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.CountingInput.UnboundedCountingInput; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link CountingInput}. - */ -@RunWith(JUnit4.class) -public class CountingInputTest { - public static void addCountingAsserts(PCollection input, long numElements) { - // Count == numElements - DataflowAssert.thatSingleton(input.apply("Count", Count.globally())) - .isEqualTo(numElements); - // Unique count == numElements - DataflowAssert.thatSingleton( - input - .apply(RemoveDuplicates.create()) - .apply("UniqueCount", Count.globally())) - .isEqualTo(numElements); - // Min == 0 - DataflowAssert.thatSingleton(input.apply("Min", Min.globally())).isEqualTo(0L); - // Max == numElements-1 - DataflowAssert.thatSingleton(input.apply("Max", Max.globally())) - .isEqualTo(numElements - 1); - } - - @Test - @Category(RunnableOnService.class) - public void testBoundedInput() { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - PCollection input = p.apply(CountingInput.upTo(numElements)); - - addCountingAsserts(input, numElements); - p.run(); - } - - @Test - public void testBoundedDisplayData() { - PTransform input = CountingInput.upTo(1234); - DisplayData displayData = DisplayData.from(input); - assertThat(displayData, hasDisplayItem("upTo", 1234)); - } - - @Test - @Category(RunnableOnService.class) - public void testUnboundedInput() { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - - PCollection input = p.apply(CountingInput.unbounded().withMaxNumRecords(numElements)); - - addCountingAsserts(input, numElements); - p.run(); - } - - @Test - public void testUnboundedInputRate() { - Pipeline p = TestPipeline.create(); - long numElements = 5000; - - long elemsPerPeriod = 10L; - Duration periodLength = Duration.millis(8); - PCollection input = - p.apply( - CountingInput.unbounded() - .withRate(elemsPerPeriod, periodLength) - .withMaxNumRecords(numElements)); - - addCountingAsserts(input, numElements); - long expectedRuntimeMillis = (periodLength.getMillis() * numElements) / elemsPerPeriod; - Instant startTime = Instant.now(); - p.run(); - Instant endTime = Instant.now(); - assertThat(endTime.isAfter(startTime.plus(expectedRuntimeMillis)), is(true)); - } - - private static class ElementValueDiff extends DoFn { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element() - c.timestamp().getMillis()); - } - } - - @Test - @Category(RunnableOnService.class) - public void testUnboundedInputTimestamps() { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - - PCollection input = - p.apply( - CountingInput.unbounded() - .withTimestampFn(new ValueAsTimestampFn()) - .withMaxNumRecords(numElements)); - addCountingAsserts(input, numElements); - - PCollection diffs = - input - .apply("TimestampDiff", ParDo.of(new ElementValueDiff())) - .apply("RemoveDuplicateTimestamps", RemoveDuplicates.create()); - // This assert also confirms that diffs only has one unique value. - DataflowAssert.thatSingleton(diffs).isEqualTo(0L); - - p.run(); - } - - @Test - public void testUnboundedDisplayData() { - Duration maxReadTime = Duration.standardHours(5); - SerializableFunction timestampFn = new SerializableFunction() { - @Override - public Instant apply(Long input) { - return Instant.now(); - } - }; - - PTransform input = CountingInput.unbounded() - .withMaxNumRecords(1234) - .withMaxReadTime(maxReadTime) - .withTimestampFn(timestampFn); - - DisplayData displayData = DisplayData.from(input); - - assertThat(displayData, hasDisplayItem("maxRecords", 1234)); - assertThat(displayData, hasDisplayItem("maxReadTime", maxReadTime)); - assertThat(displayData, hasDisplayItem("timestampFn", timestampFn.getClass())); - } - - /** - * A timestamp function that uses the given value as the timestamp. Because the input values will - * not wrap, this function is non-decreasing and meets the timestamp function criteria laid out - * in {@link UnboundedCountingInput#withTimestampFn(SerializableFunction)}. - */ - private static class ValueAsTimestampFn implements SerializableFunction { - @Override - public Instant apply(Long input) { - return new Instant(input); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java deleted file mode 100644 index 3cce395cc6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/CountingSourceTest.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.CountingSource.CounterMark; -import com.google.cloud.dataflow.sdk.io.CountingSource.UnboundedCountingSource; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.List; - -/** - * Tests of {@link CountingSource}. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("deprecation") // test of deprecated code. -public class CountingSourceTest { - - public static void addCountingAsserts(PCollection input, long numElements) { - // Count == numElements - DataflowAssert - .thatSingleton(input.apply("Count", Count.globally())) - .isEqualTo(numElements); - // Unique count == numElements - DataflowAssert - .thatSingleton(input.apply(RemoveDuplicates.create()) - .apply("UniqueCount", Count.globally())) - .isEqualTo(numElements); - // Min == 0 - DataflowAssert - .thatSingleton(input.apply("Min", Min.globally())) - .isEqualTo(0L); - // Max == numElements-1 - DataflowAssert - .thatSingleton(input.apply("Max", Max.globally())) - .isEqualTo(numElements - 1); - } - - @Test - @Category(RunnableOnService.class) - public void testBoundedSource() { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - PCollection input = p.apply(Read.from(CountingSource.upTo(numElements))); - - addCountingAsserts(input, numElements); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testBoundedSourceSplits() throws Exception { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - long numSplits = 10; - long splitSizeBytes = numElements * 8 / numSplits; // 8 bytes per long element. - - BoundedSource initial = CountingSource.upTo(numElements); - List> splits = - initial.splitIntoBundles(splitSizeBytes, p.getOptions()); - assertEquals("Expected exact splitting", numSplits, splits.size()); - - // Assemble all the splits into one flattened PCollection, also verify their sizes. - PCollectionList pcollections = PCollectionList.empty(p); - for (int i = 0; i < splits.size(); ++i) { - BoundedSource split = splits.get(i); - pcollections = pcollections.and(p.apply("split" + i, Read.from(split))); - assertEquals("Expected even splitting", - splitSizeBytes, split.getEstimatedSizeBytes(p.getOptions())); - } - PCollection input = pcollections.apply(Flatten.pCollections()); - - addCountingAsserts(input, numElements); - p.run(); - } - - @Test - public void testProgress() throws IOException { - final int numRecords = 5; - @SuppressWarnings("deprecation") // testing CountingSource - BoundedSource source = CountingSource.upTo(numRecords); - try (BoundedReader reader = source.createReader(PipelineOptionsFactory.create())) { - // Check preconditions before starting. Note that CountingReader can always give an accurate - // remaining parallelism. - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(numRecords, reader.getSplitPointsRemaining()); - - assertTrue(reader.start()); - int i = 0; - do { - assertEquals(i, reader.getSplitPointsConsumed()); - assertEquals(numRecords - i, reader.getSplitPointsRemaining()); - ++i; - } while (reader.advance()); - - assertEquals(numRecords, i); // exactly numRecords calls to advance() - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(numRecords, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - @Category(RunnableOnService.class) - public void testUnboundedSource() { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - - PCollection input = p - .apply(Read.from(CountingSource.unbounded()).withMaxNumRecords(numElements)); - - addCountingAsserts(input, numElements); - p.run(); - } - - private static class ElementValueDiff extends DoFn { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element() - c.timestamp().getMillis()); - } - } - - @Test - @Category(RunnableOnService.class) - public void testUnboundedSourceTimestamps() { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - - PCollection input = p.apply( - Read.from(CountingSource.unboundedWithTimestampFn(new ValueAsTimestampFn())) - .withMaxNumRecords(numElements)); - addCountingAsserts(input, numElements); - - PCollection diffs = input - .apply("TimestampDiff", ParDo.of(new ElementValueDiff())) - .apply("RemoveDuplicateTimestamps", RemoveDuplicates.create()); - // This assert also confirms that diffs only has one unique value. - DataflowAssert.thatSingleton(diffs).isEqualTo(0L); - - p.run(); - } - - @Test - public void testUnboundedSourceWithRate() { - Pipeline p = TestPipeline.create(); - - Duration period = Duration.millis(5); - long numElements = 1000L; - - PCollection input = - p.apply( - Read.from( - CountingSource.createUnbounded() - .withTimestampFn(new ValueAsTimestampFn()) - .withRate(1, period)) - .withMaxNumRecords(numElements)); - addCountingAsserts(input, numElements); - - PCollection diffs = - input - .apply("TimestampDiff", ParDo.of(new ElementValueDiff())) - .apply("RemoveDuplicateTimestamps", RemoveDuplicates.create()); - // This assert also confirms that diffs only has one unique value. - DataflowAssert.thatSingleton(diffs).isEqualTo(0L); - - Instant started = Instant.now(); - p.run(); - Instant finished = Instant.now(); - Duration expectedDuration = period.multipliedBy((int) numElements); - assertThat( - started - .plus(expectedDuration) - .isBefore(finished), - is(true)); - } - - @Test - @Category(RunnableOnService.class) - public void testUnboundedSourceSplits() throws Exception { - Pipeline p = TestPipeline.create(); - long numElements = 1000; - int numSplits = 10; - - UnboundedSource initial = CountingSource.unbounded(); - List> splits = - initial.generateInitialSplits(numSplits, p.getOptions()); - assertEquals("Expected exact splitting", numSplits, splits.size()); - - long elementsPerSplit = numElements / numSplits; - assertEquals("Expected even splits", numElements, elementsPerSplit * numSplits); - PCollectionList pcollections = PCollectionList.empty(p); - for (int i = 0; i < splits.size(); ++i) { - pcollections = pcollections.and( - p.apply("split" + i, Read.from(splits.get(i)).withMaxNumRecords(elementsPerSplit))); - } - PCollection input = pcollections.apply(Flatten.pCollections()); - - addCountingAsserts(input, numElements); - p.run(); - } - - @Test - public void testUnboundedSourceRateSplits() throws Exception { - Pipeline p = TestPipeline.create(); - int elementsPerPeriod = 10; - Duration period = Duration.millis(5); - - long numElements = 1000; - int numSplits = 10; - - UnboundedCountingSource initial = - CountingSource.createUnbounded().withRate(elementsPerPeriod, period); - List> splits = - initial.generateInitialSplits(numSplits, p.getOptions()); - assertEquals("Expected exact splitting", numSplits, splits.size()); - - long elementsPerSplit = numElements / numSplits; - assertEquals("Expected even splits", numElements, elementsPerSplit * numSplits); - PCollectionList pcollections = PCollectionList.empty(p); - for (int i = 0; i < splits.size(); ++i) { - pcollections = - pcollections.and( - p.apply("split" + i, Read.from(splits.get(i)).withMaxNumRecords(elementsPerSplit))); - } - PCollection input = pcollections.apply(Flatten.pCollections()); - - addCountingAsserts(input, numElements); - Instant startTime = Instant.now(); - p.run(); - Instant endTime = Instant.now(); - // 500 ms if the readers are all initialized in parallel; 5000 ms if they are evaluated serially - long expectedMinimumMillis = (numElements * period.getMillis()) / elementsPerPeriod; - assertThat(expectedMinimumMillis, lessThan(endTime.getMillis() - startTime.getMillis())); - } - - /** - * A timestamp function that uses the given value as the timestamp. Because the input values will - * not wrap, this function is non-decreasing and meets the timestamp function criteria laid out - * in {@link CountingSource#unboundedWithTimestampFn(SerializableFunction)}. - */ - private static class ValueAsTimestampFn implements SerializableFunction { - @Override - public Instant apply(Long input) { - return new Instant(input); - } - } - - @Test - public void testUnboundedSourceCheckpointMark() throws Exception { - UnboundedSource source = - CountingSource.unboundedWithTimestampFn(new ValueAsTimestampFn()); - UnboundedReader reader = source.createReader(null, null); - final long numToSkip = 3; - assertTrue(reader.start()); - - // Advance the source numToSkip elements and manually save state. - for (long l = 0; l < numToSkip; ++l) { - reader.advance(); - } - - // Confirm that we get the expected element in sequence before checkpointing. - assertEquals(numToSkip, (long) reader.getCurrent()); - assertEquals(numToSkip, reader.getCurrentTimestamp().getMillis()); - - // Checkpoint and restart, and confirm that the source continues correctly. - CounterMark mark = CoderUtils.clone( - source.getCheckpointMarkCoder(), (CounterMark) reader.getCheckpointMark()); - reader = source.createReader(null, mark); - assertTrue(reader.start()); - - // Confirm that we get the next element in sequence. - assertEquals(numToSkip + 1, (long) reader.getCurrent()); - assertEquals(numToSkip + 1, reader.getCurrentTimestamp().getMillis()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java deleted file mode 100644 index 46c053757f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/DatastoreIOTest.java +++ /dev/null @@ -1,693 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.api.services.datastore.client.DatastoreHelper.makeKey; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.Entity; -import com.google.api.services.datastore.DatastoreV1.EntityResult; -import com.google.api.services.datastore.DatastoreV1.Key; -import com.google.api.services.datastore.DatastoreV1.KindExpression; -import com.google.api.services.datastore.DatastoreV1.PartitionId; -import com.google.api.services.datastore.DatastoreV1.PropertyFilter; -import com.google.api.services.datastore.DatastoreV1.Query; -import com.google.api.services.datastore.DatastoreV1.QueryResultBatch; -import com.google.api.services.datastore.DatastoreV1.RunQueryRequest; -import com.google.api.services.datastore.DatastoreV1.RunQueryResponse; -import com.google.api.services.datastore.DatastoreV1.Value; -import com.google.api.services.datastore.client.Datastore; -import com.google.api.services.datastore.client.DatastoreHelper; -import com.google.api.services.datastore.client.QuerySplitter; -import com.google.cloud.dataflow.sdk.io.DatastoreIO.DatastoreReader; -import com.google.cloud.dataflow.sdk.io.DatastoreIO.DatastoreWriter; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.collect.Lists; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * Tests for {@link DatastoreIO}. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("deprecation") // test of deprecated code. -public class DatastoreIOTest { - private static final String HOST = "testHost"; - private static final String DATASET = "testDataset"; - private static final String NAMESPACE = "testNamespace"; - private static final String KIND = "testKind"; - private static final Query QUERY; - static { - Query.Builder q = Query.newBuilder(); - q.addKindBuilder().setName(KIND); - QUERY = q.build(); - } - private DatastoreIO.Source initialSource; - - @Mock - Datastore mockDatastore; - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - - @Rule public final ExpectedLogs logged = ExpectedLogs.none(DatastoreIO.Source.class); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - initialSource = DatastoreIO.source() - .withHost(HOST).withDataset(DATASET).withQuery(QUERY).withNamespace(NAMESPACE); - } - - /** - * Helper function to create a test {@code DataflowPipelineOptions}. - */ - static final DataflowPipelineOptions testPipelineOptions(@Nullable Integer numWorkers) { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - if (numWorkers != null) { - options.setNumWorkers(numWorkers); - } - return options; - } - - @Test - public void testBuildSource() throws Exception { - DatastoreIO.Source source = DatastoreIO.source() - .withHost(HOST).withDataset(DATASET).withQuery(QUERY).withNamespace(NAMESPACE); - assertEquals(QUERY, source.getQuery()); - assertEquals(DATASET, source.getDataset()); - assertEquals(HOST, source.getHost()); - assertEquals(NAMESPACE, source.getNamespace()); - } - - /** - * {@link #testBuildSource} but constructed in a different order. - */ - @Test - public void testBuildSourceAlt() throws Exception { - DatastoreIO.Source source = DatastoreIO.source() - .withDataset(DATASET).withNamespace(NAMESPACE).withQuery(QUERY).withHost(HOST); - assertEquals(QUERY, source.getQuery()); - assertEquals(DATASET, source.getDataset()); - assertEquals(HOST, source.getHost()); - assertEquals(NAMESPACE, source.getNamespace()); - } - - @Test - public void testSourceValidationFailsHost() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("host"); - - DatastoreIO.Source source = initialSource.withHost(null); - source.validate(); - } - - @Test - public void testSourceValidationFailsDataset() throws Exception { - DatastoreIO.Source source = DatastoreIO.source().withQuery(QUERY); - thrown.expect(NullPointerException.class); - thrown.expectMessage("dataset"); - source.validate(); - } - - @Test - public void testSourceValidationFailsQuery() throws Exception { - DatastoreIO.Source source = DatastoreIO.source().withDataset(DATASET); - thrown.expect(NullPointerException.class); - thrown.expectMessage("query"); - source.validate(); - } - - @Test - public void testSourceValidationFailsQueryLimitZero() throws Exception { - Query invalidLimit = Query.newBuilder().setLimit(0).build(); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid query limit 0"); - - DatastoreIO.source().withQuery(invalidLimit); - } - - @Test - public void testSourceValidationFailsQueryLimitNegative() throws Exception { - Query invalidLimit = Query.newBuilder().setLimit(-5).build(); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid query limit -5"); - - DatastoreIO.source().withQuery(invalidLimit); - } - - @Test - public void testSourceValidationSucceedsNamespace() throws Exception { - DatastoreIO.Source source = DatastoreIO.source().withDataset(DATASET).withQuery(QUERY); - /* Should succeed, as a null namespace is fine. */ - source.validate(); - } - - @Test - public void testSourceDisplayData() { - DatastoreIO.Source source = DatastoreIO.source() - .withDataset(DATASET) - .withQuery(QUERY) - .withHost(HOST) - .withNamespace(NAMESPACE); - - DisplayData displayData = DisplayData.from(source); - - assertThat(displayData, hasDisplayItem("dataset", DATASET)); - assertThat(displayData, hasDisplayItem("query", QUERY.toString())); - assertThat(displayData, hasDisplayItem("host", HOST)); - assertThat(displayData, hasDisplayItem("namespace", NAMESPACE)); - } - - @Test - public void testSourcePrimitiveDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - PTransform read = DatastoreIO.readFrom( - "myDataset", DatastoreV1.Query.newBuilder().build()); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(read); - assertThat("DatastoreIO read should include the dataset in its primitive display data", - displayData, hasItem(hasDisplayItem("dataset"))); - } - - @Test - public void testSinkDoesNotAllowNullHost() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("host"); - - DatastoreIO.sink().withDataset(DATASET).withHost(null); - } - - @Test - public void testSinkDoesNotAllowNullDataset() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("datasetId"); - - DatastoreIO.sink().withDataset(null); - } - - @Test - public void testSinkValidationFailsWithNoDataset() throws Exception { - DatastoreIO.Sink sink = DatastoreIO.sink(); - - thrown.expect(NullPointerException.class); - thrown.expectMessage("Dataset"); - - sink.validate(testPipelineOptions(null)); - } - - @Test - public void testSinkValidationSucceedsWithDataset() throws Exception { - DatastoreIO.Sink sink = DatastoreIO.sink().withDataset(DATASET); - sink.validate(testPipelineOptions(null)); - } - - @Test - public void testSinkDisplayData() { - DatastoreIO.Sink sink = DatastoreIO.sink() - .withDataset(DATASET) - .withHost(HOST); - - DisplayData displayData = DisplayData.from(sink); - - assertThat(displayData, hasDisplayItem("dataset", DATASET)); - assertThat(displayData, hasDisplayItem("host", HOST)); - } - - @Test - public void testSinkPrimitiveDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - PTransform, ?> write = DatastoreIO.writeTo("myDataset"); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(write); - assertThat("DatastoreIO write should include the dataset in its primitive display data", - displayData, hasItem(hasDisplayItem("dataset"))); - } - - - @Test - public void testQuerySplitBasic() throws Exception { - KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); - Query query = Query.newBuilder().addKind(mykind).build(); - - List mockSplits = new ArrayList<>(); - for (int i = 0; i < 8; ++i) { - mockSplits.add( - Query.newBuilder() - .addKind(mykind) - .setFilter( - DatastoreHelper.makeFilter("foo", PropertyFilter.Operator.EQUAL, - Value.newBuilder().setIntegerValue(i).build())) - .build()); - } - - QuerySplitter splitter = mock(QuerySplitter.class); - /* No namespace */ - PartitionId partition = PartitionId.newBuilder().build(); - when(splitter.getSplits(any(Query.class), eq(partition), eq(8), any(Datastore.class))) - .thenReturn(mockSplits); - - DatastoreIO.Source io = initialSource - .withNamespace(null) - .withQuery(query) - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(8 * 1024L); - - List bundles = io.splitIntoBundles(1024, testPipelineOptions(null)); - assertEquals(8, bundles.size()); - for (int i = 0; i < 8; ++i) { - DatastoreIO.Source bundle = bundles.get(i); - Query bundleQuery = bundle.getQuery(); - assertEquals("mykind", bundleQuery.getKind(0).getName()); - assertEquals(i, bundleQuery.getFilter().getPropertyFilter().getValue().getIntegerValue()); - } - } - - /** - * Verifies that when namespace is set in the source, the split request includes the namespace. - */ - @Test - public void testSourceWithNamespace() throws Exception { - QuerySplitter splitter = mock(QuerySplitter.class); - DatastoreIO.Source io = initialSource - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(8 * 1024L); - - io.splitIntoBundles(1024, testPipelineOptions(null)); - - PartitionId partition = PartitionId.newBuilder().setNamespace(NAMESPACE).build(); - verify(splitter).getSplits(eq(QUERY), eq(partition), eq(8), any(Datastore.class)); - verifyNoMoreInteractions(splitter); - } - - @Test - public void testQuerySplitWithZeroSize() throws Exception { - KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); - Query query = Query.newBuilder().addKind(mykind).build(); - - List mockSplits = Lists.newArrayList( - Query.newBuilder() - .addKind(mykind) - .build()); - - QuerySplitter splitter = mock(QuerySplitter.class); - when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class))) - .thenReturn(mockSplits); - - DatastoreIO.Source io = initialSource - .withQuery(query) - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(0L); - - List bundles = io.splitIntoBundles(1024, testPipelineOptions(null)); - assertEquals(1, bundles.size()); - verify(splitter, never()) - .getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class)); - DatastoreIO.Source bundle = bundles.get(0); - Query bundleQuery = bundle.getQuery(); - assertEquals("mykind", bundleQuery.getKind(0).getName()); - assertFalse(bundleQuery.hasFilter()); - } - - /** - * Tests that a query with a user-provided limit field does not split, and does not even - * interact with a query splitter. - */ - @Test - public void testQueryDoesNotSplitWithLimitSet() throws Exception { - // Minimal query with a limit - Query query = Query.newBuilder().setLimit(5).build(); - - // Mock query splitter, should not be invoked. - QuerySplitter splitter = mock(QuerySplitter.class); - when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(2), any(Datastore.class))) - .thenThrow(new AssertionError("Splitter should not be invoked")); - - List bundles = - initialSource - .withQuery(query) - .withMockSplitter(splitter) - .splitIntoBundles(1024, testPipelineOptions(null)); - - assertEquals(1, bundles.size()); - assertEquals(query, bundles.get(0).getQuery()); - verifyNoMoreInteractions(splitter); - } - - /** - * Tests that when {@link QuerySplitter} cannot split a query, {@link DatastoreIO} falls back to - * a single split. - */ - @Test - public void testQuerySplitterThrows() throws Exception { - // Mock query splitter that throws IllegalArgumentException - IllegalArgumentException exception = - new IllegalArgumentException("query not supported by splitter"); - QuerySplitter splitter = mock(QuerySplitter.class); - when( - splitter.getSplits( - any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class))) - .thenThrow(exception); - - Query query = Query.newBuilder().addKind(KindExpression.newBuilder().setName("myKind")).build(); - List bundles = - initialSource - .withQuery(query) - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(10240L) - .splitIntoBundles(1024, testPipelineOptions(null)); - - assertEquals(1, bundles.size()); - assertEquals(query, bundles.get(0).getQuery()); - verify(splitter, times(1)) - .getSplits( - any(Query.class), any(PartitionId.class), any(Integer.class), any(Datastore.class)); - logged.verifyWarn("Unable to parallelize the given query", exception); - } - - @Test - public void testQuerySplitSizeUnavailable() throws Exception { - KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); - Query query = Query.newBuilder().addKind(mykind).build(); - - List mockSplits = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - mockSplits.add( - Query.newBuilder() - .addKind(mykind) - .setFilter( - DatastoreHelper.makeFilter("foo", PropertyFilter.Operator.EQUAL, - Value.newBuilder().setIntegerValue(i).build())) - .build()); - } - - QuerySplitter splitter = mock(QuerySplitter.class); - when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(2), any(Datastore.class))) - .thenReturn(mockSplits); - - DatastoreIO.Source io = initialSource - .withQuery(query) - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(8 * 1024L); - - DatastoreIO.Source spiedIo = spy(io); - when(spiedIo.getEstimatedSizeBytes(any(PipelineOptions.class))).thenThrow(new IOException()); - - List bundles = spiedIo.splitIntoBundles(1024, testPipelineOptions(2)); - assertEquals(2, bundles.size()); - for (int i = 0; i < 2; ++i) { - DatastoreIO.Source bundle = bundles.get(i); - Query bundleQuery = bundle.getQuery(); - assertEquals("mykind", bundleQuery.getKind(0).getName()); - assertEquals(i, bundleQuery.getFilter().getPropertyFilter().getValue().getIntegerValue()); - } - } - - @Test - public void testQuerySplitNoWorkers() throws Exception { - KindExpression mykind = KindExpression.newBuilder().setName("mykind").build(); - Query query = Query.newBuilder().addKind(mykind).build(); - - List mockSplits = Lists.newArrayList(Query.newBuilder().addKind(mykind).build()); - - QuerySplitter splitter = mock(QuerySplitter.class); - when(splitter.getSplits(any(Query.class), any(PartitionId.class), eq(12), any(Datastore.class))) - .thenReturn(mockSplits); - - DatastoreIO.Source io = initialSource - .withQuery(query) - .withMockSplitter(splitter) - .withMockEstimateSizeBytes(8 * 1024L); - - DatastoreIO.Source spiedIo = spy(io); - when(spiedIo.getEstimatedSizeBytes(any(PipelineOptions.class))) - .thenThrow(new NoSuchElementException()); - - List bundles = spiedIo.splitIntoBundles(1024, testPipelineOptions(0)); - assertEquals(1, bundles.size()); - verify(splitter, never()) - .getSplits(any(Query.class), any(PartitionId.class), eq(1), any(Datastore.class)); - DatastoreIO.Source bundle = bundles.get(0); - Query bundleQuery = bundle.getQuery(); - assertEquals("mykind", bundleQuery.getKind(0).getName()); - assertFalse(bundleQuery.hasFilter()); - } - - /** - * Test building a Sink using builder methods. - */ - @Test - public void testBuildSink() throws Exception { - DatastoreIO.Sink sink = DatastoreIO.sink().withDataset(DATASET).withHost(HOST); - assertEquals(HOST, sink.host); - assertEquals(DATASET, sink.datasetId); - - sink = DatastoreIO.sink().withHost(HOST).withDataset(DATASET); - assertEquals(HOST, sink.host); - assertEquals(DATASET, sink.datasetId); - - sink = DatastoreIO.sink().withDataset(DATASET).withHost(HOST); - assertEquals(HOST, sink.host); - assertEquals(DATASET, sink.datasetId); - } - - /** - * Test building a sink using the default host. - */ - @Test - public void testBuildSinkDefaults() throws Exception { - DatastoreIO.Sink sink = DatastoreIO.sink().withDataset(DATASET); - assertEquals(DatastoreIO.DEFAULT_HOST, sink.host); - assertEquals(DATASET, sink.datasetId); - - sink = DatastoreIO.sink().withDataset(DATASET); - assertEquals(DatastoreIO.DEFAULT_HOST, sink.host); - assertEquals(DATASET, sink.datasetId); - } - - /** - * Test the detection of complete and incomplete keys. - */ - @Test - public void testHasNameOrId() { - Key key; - // Complete with name, no ancestor - key = DatastoreHelper.makeKey("bird", "finch").build(); - assertTrue(DatastoreWriter.isValidKey(key)); - - // Complete with id, no ancestor - key = DatastoreHelper.makeKey("bird", 123).build(); - assertTrue(DatastoreWriter.isValidKey(key)); - - // Incomplete, no ancestor - key = DatastoreHelper.makeKey("bird").build(); - assertFalse(DatastoreWriter.isValidKey(key)); - - // Complete with name and ancestor - key = DatastoreHelper.makeKey("bird", "owl").build(); - key = DatastoreHelper.makeKey(key, "bird", "horned").build(); - assertTrue(DatastoreWriter.isValidKey(key)); - - // Complete with id and ancestor - key = DatastoreHelper.makeKey("bird", "owl").build(); - key = DatastoreHelper.makeKey(key, "bird", 123).build(); - assertTrue(DatastoreWriter.isValidKey(key)); - - // Incomplete with ancestor - key = DatastoreHelper.makeKey("bird", "owl").build(); - key = DatastoreHelper.makeKey(key, "bird").build(); - assertFalse(DatastoreWriter.isValidKey(key)); - - key = DatastoreHelper.makeKey().build(); - assertFalse(DatastoreWriter.isValidKey(key)); - } - - /** - * Test that entities with incomplete keys cannot be updated. - */ - @Test - public void testAddEntitiesWithIncompleteKeys() throws Exception { - Key key = DatastoreHelper.makeKey("bird").build(); - Entity entity = Entity.newBuilder().setKey(key).build(); - DatastoreWriter writer = new DatastoreIO.DatastoreWriter(null, mockDatastore); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Entities to be written to the Datastore must have complete keys"); - - writer.write(entity); - } - - /** - * Test that entities are added to the batch to update. - */ - @Test - public void testAddingEntities() throws Exception { - List expected = Lists.newArrayList( - Entity.newBuilder().setKey(DatastoreHelper.makeKey("bird", "jay").build()).build(), - Entity.newBuilder().setKey(DatastoreHelper.makeKey("bird", "condor").build()).build(), - Entity.newBuilder().setKey(DatastoreHelper.makeKey("bird", "robin").build()).build()); - - List allEntities = Lists.newArrayList(expected); - Collections.shuffle(allEntities); - - DatastoreWriter writer = new DatastoreIO.DatastoreWriter(null, mockDatastore); - writer.open("test_id"); - for (Entity entity : allEntities) { - writer.write(entity); - } - - assertEquals(expected.size(), writer.entities.size()); - assertThat(writer.entities, containsInAnyOrder(expected.toArray())); - } - - /** Datastore batch API limit in number of records per query. */ - private static final int DATASTORE_QUERY_BATCH_LIMIT = 500; - - /** - * A helper function that creates mock {@link Entity} results in response to a query. Always - * indicates that more results are available, unless the batch is limited to fewer than - * {@link #DATASTORE_QUERY_BATCH_LIMIT} results. - */ - private static RunQueryResponse mockResponseForQuery(Query q) { - // Every query DatastoreIO sends should have a limit. - assertTrue(q.hasLimit()); - - // The limit should be in the range [1, DATASTORE_QUERY_BATCH_LIMIT] - int limit = q.getLimit(); - assertThat(limit, greaterThanOrEqualTo(1)); - assertThat(limit, lessThanOrEqualTo(DATASTORE_QUERY_BATCH_LIMIT)); - - // Create the requested number of entities. - List entities = new ArrayList<>(limit); - for (int i = 0; i < limit; ++i) { - entities.add( - EntityResult.newBuilder() - .setEntity(Entity.newBuilder().setKey(makeKey("key" + i, i + 1))) - .build()); - } - - // Fill out the other parameters on the returned result batch. - RunQueryResponse.Builder ret = RunQueryResponse.newBuilder(); - ret.getBatchBuilder() - .addAllEntityResult(entities) - .setEntityResultType(EntityResult.ResultType.FULL) - .setMoreResults( - limit == DATASTORE_QUERY_BATCH_LIMIT - ? QueryResultBatch.MoreResultsType.NOT_FINISHED - : QueryResultBatch.MoreResultsType.NO_MORE_RESULTS); - - return ret.build(); - } - - /** Helper function to run a test reading from a limited-result query. */ - private void runQueryLimitReadTest(int numEntities) throws Exception { - // An empty query to read entities. - Query query = Query.newBuilder().setLimit(numEntities).build(); - DatastoreIO.Source source = DatastoreIO.source().withQuery(query).withDataset("mockDataset"); - - // Use mockResponseForQuery to generate results. - when(mockDatastore.runQuery(any(RunQueryRequest.class))) - .thenAnswer( - new Answer() { - @Override - public RunQueryResponse answer(InvocationOnMock invocation) throws Throwable { - Query q = ((RunQueryRequest) invocation.getArguments()[0]).getQuery(); - return mockResponseForQuery(q); - } - }); - - // Actually instantiate the reader. - DatastoreReader reader = new DatastoreReader(source, mockDatastore); - - // Simply count the number of results returned by the reader. - assertTrue(reader.start()); - int resultCount = 1; - while (reader.advance()) { - resultCount++; - } - reader.close(); - - // Validate the number of results. - assertEquals(numEntities, resultCount); - } - - /** Tests reading with a query limit less than one batch. */ - @Test - public void testReadingWithLimitOneBatch() throws Exception { - runQueryLimitReadTest(5); - } - - /** Tests reading with a query limit more than one batch, and not a multiple. */ - @Test - public void testReadingWithLimitMultipleBatches() throws Exception { - runQueryLimitReadTest(DATASTORE_QUERY_BATCH_LIMIT + 5); - } - - /** Tests reading several batches, using an exact multiple of batch size results. */ - @Test - public void testReadingWithLimitMultipleBatchesExactMultiple() throws Exception { - runQueryLimitReadTest(5 * DATASTORE_QUERY_BATCH_LIMIT); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java deleted file mode 100644 index fc81db8958..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSinkTest.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation; -import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation.TemporaryFileRetention; -import com.google.cloud.dataflow.sdk.io.FileBasedSink.FileResult; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.PrintWriter; -import java.nio.ByteBuffer; -import java.nio.channels.WritableByteChannel; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Tests for FileBasedSink. - */ -@RunWith(JUnit4.class) -public class FileBasedSinkTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - private String baseOutputFilename = "output"; - private String baseTemporaryFilename = "temp"; - - private String appendToTempFolder(String filename) { - return Paths.get(tmpFolder.getRoot().getPath(), filename).toString(); - } - - private String getBaseOutputFilename() { - return appendToTempFolder(baseOutputFilename); - } - - private String getBaseTempFilename() { - return appendToTempFolder(baseTemporaryFilename); - } - - /** - * FileBasedWriter opens the correct file, writes the header, footer, and elements in the - * correct order, and returns the correct filename. - */ - @Test - public void testWriter() throws Exception { - String testUid = "testId"; - String expectedFilename = - getBaseTempFilename() + FileBasedWriteOperation.TEMPORARY_FILENAME_SEPARATOR + testUid; - SimpleSink.SimpleWriter writer = buildWriter(); - - List values = Arrays.asList("sympathetic vulture", "boresome hummingbird"); - List expected = new ArrayList<>(); - expected.add(SimpleSink.SimpleWriter.HEADER); - expected.addAll(values); - expected.add(SimpleSink.SimpleWriter.FOOTER); - - writer.open(testUid); - for (String value : values) { - writer.write(value); - } - FileResult result = writer.close(); - - assertEquals(expectedFilename, result.getFilename()); - assertFileContains(expected, expectedFilename); - } - - /** - * Assert that a file contains the lines provided, in the same order as expected. - */ - private void assertFileContains(List expected, String filename) throws Exception { - try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { - List actual = new ArrayList<>(); - for (;;) { - String line = reader.readLine(); - if (line == null) { - break; - } - actual.add(line); - } - assertEquals(expected, actual); - } - } - - /** - * Write lines to a file. - */ - private void writeFile(List lines, File file) throws Exception { - try (PrintWriter writer = new PrintWriter(new FileOutputStream(file))) { - for (String line : lines) { - writer.println(line); - } - } - } - - /** - * Removes temporary files when temporary and output filenames differ. - */ - @Test - public void testRemoveWithTempFilename() throws Exception { - testRemoveTemporaryFiles(3, baseTemporaryFilename); - } - - /** - * Removes only temporary files, even if temporary and output files share the same base filename. - */ - @Test - public void testRemoveWithSameFilename() throws Exception { - testRemoveTemporaryFiles(3, baseOutputFilename); - } - - /** - * Finalize copies temporary files to output files and removes any temporary files. - */ - @Test - public void testFinalizeWithNoRetention() throws Exception { - List files = generateTemporaryFilesForFinalize(3); - boolean retainTemporaryFiles = false; - runFinalize(buildWriteOperationForFinalize(retainTemporaryFiles), files, retainTemporaryFiles); - } - - /** - * Finalize retains temporary files when requested. - */ - @Test - public void testFinalizeWithRetention() throws Exception { - List files = generateTemporaryFilesForFinalize(3); - boolean retainTemporaryFiles = true; - runFinalize(buildWriteOperationForFinalize(retainTemporaryFiles), files, retainTemporaryFiles); - } - - /** - * Finalize can be called repeatedly. - */ - @Test - public void testFinalizeMultipleCalls() throws Exception { - List files = generateTemporaryFilesForFinalize(3); - SimpleSink.SimpleWriteOperation writeOp = buildWriteOperationForFinalize(false); - runFinalize(writeOp, files, false); - runFinalize(writeOp, files, false); - } - - /** - * Finalize can be called when some temporary files do not exist and output files exist. - */ - @Test - public void testFinalizeWithIntermediateState() throws Exception { - List files = generateTemporaryFilesForFinalize(3); - SimpleSink.SimpleWriteOperation writeOp = buildWriteOperationForFinalize(false); - runFinalize(writeOp, files, false); - - // create a temporary file - tmpFolder.newFile( - baseTemporaryFilename + FileBasedWriteOperation.TEMPORARY_FILENAME_SEPARATOR + "1"); - - runFinalize(writeOp, files, false); - } - - /** - * Build a SimpleWriteOperation with default values and the specified retention policy. - */ - private SimpleSink.SimpleWriteOperation buildWriteOperationForFinalize( - boolean retainTemporaryFiles) throws Exception { - TemporaryFileRetention retentionPolicy = - retainTemporaryFiles ? TemporaryFileRetention.KEEP : TemporaryFileRetention.REMOVE; - return buildWriteOperation(retentionPolicy); - } - - /** - * Generate n temporary files using the temporary file pattern of FileBasedWriter. - */ - private List generateTemporaryFilesForFinalize(int numFiles) throws Exception { - List temporaryFiles = new ArrayList<>(); - for (int i = 0; i < numFiles; i++) { - String temporaryFilename = - FileBasedWriteOperation.buildTemporaryFilename(baseTemporaryFilename, "" + i); - File tmpFile = tmpFolder.newFile(temporaryFilename); - temporaryFiles.add(tmpFile); - } - - return temporaryFiles; - } - - /** - * Finalize and verify that files are copied and temporary files are optionally removed. - */ - private void runFinalize(SimpleSink.SimpleWriteOperation writeOp, List temporaryFiles, - boolean retainTemporaryFiles) throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - - int numFiles = temporaryFiles.size(); - - List outputFiles = new ArrayList<>(); - List fileResults = new ArrayList<>(); - List outputFilenames = writeOp.generateDestinationFilenames(numFiles); - - // Create temporary output bundles and output File objects - for (int i = 0; i < numFiles; i++) { - fileResults.add(new FileResult(temporaryFiles.get(i).toString())); - outputFiles.add(new File(outputFilenames.get(i))); - } - - writeOp.finalize(fileResults, options); - - for (int i = 0; i < numFiles; i++) { - assertTrue(outputFiles.get(i).exists()); - assertEquals(retainTemporaryFiles, temporaryFiles.get(i).exists()); - } - } - - /** - * Create n temporary and output files and verify that removeTemporaryFiles only - * removes temporary files. - */ - private void testRemoveTemporaryFiles(int numFiles, String baseTemporaryFilename) - throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation(baseTemporaryFilename); - - List temporaryFiles = new ArrayList<>(); - List outputFiles = new ArrayList<>(); - for (int i = 0; i < numFiles; i++) { - File tmpFile = tmpFolder.newFile( - FileBasedWriteOperation.buildTemporaryFilename(baseTemporaryFilename, "" + i)); - temporaryFiles.add(tmpFile.getAbsolutePath()); - File outputFile = tmpFolder.newFile(baseOutputFilename + i); - outputFiles.add(outputFile); - } - - File extraFile = new File(tmpFolder.newFolder("extra"), "foo"); - assertTrue(extraFile.createNewFile()); - - temporaryFiles.add(extraFile.getAbsolutePath()); - - writeOp.removeTemporaryFiles(temporaryFiles, options); - - for (int i = 0; i < numFiles; i++) { - assertFalse(new File(temporaryFiles.get(i)).exists()); - assertTrue(outputFiles.get(i).exists()); - } - assertFalse(extraFile.exists()); - } - - /** - * Output files are copied to the destination location with the correct names and contents. - */ - @Test - public void testCopyToOutputFiles() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation(); - - List inputFilenames = Arrays.asList("input-3", "input-2", "input-1"); - List inputContents = Arrays.asList("3", "2", "1"); - List expectedOutputFilenames = Arrays.asList( - "output-00002-of-00003.test", "output-00001-of-00003.test", "output-00000-of-00003.test"); - - List inputFilePaths = new ArrayList<>(); - List expectedOutputPaths = new ArrayList<>(); - - for (int i = 0; i < inputFilenames.size(); i++) { - // Generate output paths. - File outputFile = tmpFolder.newFile(expectedOutputFilenames.get(i)); - expectedOutputPaths.add(outputFile.toString()); - - // Generate and write to input paths. - File inputTmpFile = tmpFolder.newFile(inputFilenames.get(i)); - List lines = Arrays.asList(inputContents.get(i)); - writeFile(lines, inputTmpFile); - inputFilePaths.add(inputTmpFile.toString()); - } - - // Copy input files to output files. - List actual = writeOp.copyToOutputFiles(inputFilePaths, options); - - // Assert that the expected paths are returned. - assertThat(expectedOutputPaths, containsInAnyOrder(actual.toArray())); - - // Assert that the contents were copied. - for (int i = 0; i < expectedOutputPaths.size(); i++) { - assertFileContains(Arrays.asList(inputContents.get(i)), expectedOutputPaths.get(i)); - } - } - - /** - * Output filenames use the supplied naming template. - */ - @Test - public void testGenerateOutputFilenamesWithTemplate() { - List expected; - List actual; - SimpleSink sink = new SimpleSink(getBaseOutputFilename(), "test", ".SS.of.NN"); - SimpleSink.SimpleWriteOperation writeOp = new SimpleSink.SimpleWriteOperation(sink); - - expected = Arrays.asList(appendToTempFolder("output.00.of.03.test"), - appendToTempFolder("output.01.of.03.test"), appendToTempFolder("output.02.of.03.test")); - actual = writeOp.generateDestinationFilenames(3); - assertEquals(expected, actual); - - expected = Arrays.asList(appendToTempFolder("output.00.of.01.test")); - actual = writeOp.generateDestinationFilenames(1); - assertEquals(expected, actual); - - expected = new ArrayList<>(); - actual = writeOp.generateDestinationFilenames(0); - assertEquals(expected, actual); - - // Also validate that we handle the case where the user specified "." that we do - // not prefix an additional "." making "..test" - sink = new SimpleSink(getBaseOutputFilename(), ".test", ".SS.of.NN"); - writeOp = new SimpleSink.SimpleWriteOperation(sink); - expected = Arrays.asList(appendToTempFolder("output.00.of.03.test"), - appendToTempFolder("output.01.of.03.test"), appendToTempFolder("output.02.of.03.test")); - actual = writeOp.generateDestinationFilenames(3); - assertEquals(expected, actual); - - expected = Arrays.asList(appendToTempFolder("output.00.of.01.test")); - actual = writeOp.generateDestinationFilenames(1); - assertEquals(expected, actual); - - expected = new ArrayList<>(); - actual = writeOp.generateDestinationFilenames(0); - assertEquals(expected, actual); - } - - /** - * Output filenames are generated correctly when an extension is supplied. - */ - @Test - public void testGenerateOutputFilenamesWithExtension() { - List expected; - List actual; - SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation(); - - expected = Arrays.asList( - appendToTempFolder("output-00000-of-00003.test"), - appendToTempFolder("output-00001-of-00003.test"), - appendToTempFolder("output-00002-of-00003.test")); - actual = writeOp.generateDestinationFilenames(3); - assertEquals(expected, actual); - - expected = Arrays.asList(appendToTempFolder("output-00000-of-00001.test")); - actual = writeOp.generateDestinationFilenames(1); - assertEquals(expected, actual); - - expected = new ArrayList<>(); - actual = writeOp.generateDestinationFilenames(0); - assertEquals(expected, actual); - } - - /** - * Output filenames are generated correctly when an extension is not supplied. - */ - @Test - public void testGenerateOutputFilenamesWithoutExtension() { - List expected; - List actual; - SimpleSink sink = new SimpleSink(appendToTempFolder(baseOutputFilename), ""); - SimpleSink.SimpleWriteOperation writeOp = new SimpleSink.SimpleWriteOperation(sink); - - expected = Arrays.asList(appendToTempFolder("output-00000-of-00003"), - appendToTempFolder("output-00001-of-00003"), appendToTempFolder("output-00002-of-00003")); - actual = writeOp.generateDestinationFilenames(3); - assertEquals(expected, actual); - - expected = Arrays.asList(appendToTempFolder("output-00000-of-00001")); - actual = writeOp.generateDestinationFilenames(1); - assertEquals(expected, actual); - - expected = new ArrayList<>(); - actual = writeOp.generateDestinationFilenames(0); - assertEquals(expected, actual); - } - - /** - * A simple FileBasedSink that writes String values as lines with header and footer lines. - */ - private static final class SimpleSink extends FileBasedSink { - public SimpleSink(String baseOutputFilename, String extension) { - super(baseOutputFilename, extension); - } - - public SimpleSink(String baseOutputFilename, String extension, String fileNamingTemplate) { - super(baseOutputFilename, extension, fileNamingTemplate); - } - - @Override - public SimpleWriteOperation createWriteOperation(PipelineOptions options) { - return new SimpleWriteOperation(this); - } - - private static final class SimpleWriteOperation extends FileBasedWriteOperation { - public SimpleWriteOperation( - SimpleSink sink, String tempOutputFilename, TemporaryFileRetention retentionPolicy) { - super(sink, tempOutputFilename, retentionPolicy); - } - - public SimpleWriteOperation(SimpleSink sink, String tempOutputFilename) { - super(sink, tempOutputFilename); - } - - public SimpleWriteOperation(SimpleSink sink) { - super(sink); - } - - @Override - public SimpleWriter createWriter(PipelineOptions options) throws Exception { - return new SimpleWriter(this); - } - } - - private static final class SimpleWriter extends FileBasedWriter { - static final String HEADER = "header"; - static final String FOOTER = "footer"; - - private WritableByteChannel channel; - - public SimpleWriter(SimpleWriteOperation writeOperation) { - super(writeOperation); - } - - private static ByteBuffer wrap(String value) throws Exception { - return ByteBuffer.wrap((value + "\n").getBytes("UTF-8")); - } - - @Override - protected void prepareWrite(WritableByteChannel channel) throws Exception { - this.channel = channel; - } - - @Override - protected void writeHeader() throws Exception { - channel.write(wrap(HEADER)); - } - - @Override - protected void writeFooter() throws Exception { - channel.write(wrap(FOOTER)); - } - - @Override - public void write(String value) throws Exception { - channel.write(wrap(value)); - } - } - } - - /** - * Build a SimpleSink with default options. - */ - private SimpleSink buildSink() { - return new SimpleSink(getBaseOutputFilename(), "test"); - } - - /** - * Build a SimpleWriteOperation with default options and the given file retention policy. - */ - private SimpleSink.SimpleWriteOperation buildWriteOperation( - TemporaryFileRetention fileRetention) { - SimpleSink sink = buildSink(); - return new SimpleSink.SimpleWriteOperation(sink, getBaseTempFilename(), fileRetention); - } - - /** - * Build a SimpleWriteOperation with default options and the given base temporary filename. - */ - private SimpleSink.SimpleWriteOperation buildWriteOperation(String baseTemporaryFilename) { - SimpleSink sink = buildSink(); - return new SimpleSink.SimpleWriteOperation(sink, appendToTempFolder(baseTemporaryFilename)); - } - - /** - * Build a write operation with the default options for it and its parent sink. - */ - private SimpleSink.SimpleWriteOperation buildWriteOperation() { - SimpleSink sink = buildSink(); - return new SimpleSink.SimpleWriteOperation( - sink, getBaseTempFilename(), TemporaryFileRetention.REMOVE); - } - - /** - * Build a writer with the default options for its parent write operation and sink. - */ - private SimpleSink.SimpleWriter buildWriter() { - SimpleSink.SimpleWriteOperation writeOp = buildWriteOperation(TemporaryFileRetention.REMOVE); - return new SimpleSink.SimpleWriter(writeOp); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java deleted file mode 100644 index 508e41a9b7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/FileBasedSourceTest.java +++ /dev/null @@ -1,926 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionExhaustive; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionFails; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.FileBasedSource.FileBasedReader; -import com.google.cloud.dataflow.sdk.io.Source.Reader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.IOChannelFactory; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SeekableByteChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Random; - -/** - * Tests code common to all file-based sources. - */ -@RunWith(JUnit4.class) -public class FileBasedSourceTest { - - Random random = new Random(0L); - - @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); - @Rule public ExpectedException thrown = ExpectedException.none(); - - /** - * If {@code splitHeader} is null, this is just a simple line-based reader. Otherwise, the file is - * considered to consist of blocks beginning with {@code splitHeader}. The header itself is not - * returned as a record. The first record after the header is considered to be a split point. - * - *

              E.g., if {@code splitHeader} is "h" and the lines of the file are: h, a, b, h, h, c, then - * the records in this source are a,b,c, and records a and c are split points. - */ - static class TestFileBasedSource extends FileBasedSource { - - final String splitHeader; - - public TestFileBasedSource(String fileOrPattern, long minBundleSize, String splitHeader) { - super(fileOrPattern, minBundleSize); - this.splitHeader = splitHeader; - } - - public TestFileBasedSource( - String fileOrPattern, - long minBundleSize, - long startOffset, - long endOffset, - String splitHeader) { - super(fileOrPattern, minBundleSize, startOffset, endOffset); - this.splitHeader = splitHeader; - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public void validate() {} - - @Override - public Coder getDefaultOutputCoder() { - return StringUtf8Coder.of(); - } - - @Override - protected FileBasedSource createForSubrangeOfFile( - String fileName, long start, long end) { - return new TestFileBasedSource(fileName, getMinBundleSize(), start, end, splitHeader); - } - - @Override - protected FileBasedReader createSingleFileReader(PipelineOptions options) { - if (splitHeader == null) { - return new TestReader(this); - } else { - return new TestReaderWithSplits(this); - } - } - } - - /** - * A utility class that starts reading lines from a given offset in a file until EOF. - */ - private static class LineReader { - private ReadableByteChannel channel = null; - private long nextLineStart = 0; - private long currentLineStart = 0; - private final ByteBuffer buf; - private static final int BUF_SIZE = 1024; - private String currentValue = null; - - public LineReader(ReadableByteChannel channel) throws IOException { - buf = ByteBuffer.allocate(BUF_SIZE); - buf.flip(); - - boolean removeLine = false; - // If we are not at the beginning of a line, we should ignore the current line. - if (channel instanceof SeekableByteChannel) { - SeekableByteChannel seekChannel = (SeekableByteChannel) channel; - if (seekChannel.position() > 0) { - // Start from one character back and read till we find a new line. - seekChannel.position(seekChannel.position() - 1); - removeLine = true; - } - nextLineStart = seekChannel.position(); - } - this.channel = channel; - if (removeLine) { - nextLineStart += readNextLine(new ByteArrayOutputStream()); - } - } - - private int readNextLine(ByteArrayOutputStream out) throws IOException { - int byteCount = 0; - while (true) { - if (!buf.hasRemaining()) { - buf.clear(); - int read = channel.read(buf); - if (read < 0) { - break; - } - buf.flip(); - } - byte b = buf.get(); - byteCount++; - if (b == '\n') { - break; - } - out.write(b); - } - return byteCount; - } - - public boolean readNextLine() throws IOException { - currentLineStart = nextLineStart; - - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - int offsetAdjustment = readNextLine(buf); - if (offsetAdjustment == 0) { - // EOF - return false; - } - nextLineStart += offsetAdjustment; - // When running on Windows, each line obtained from 'readNextLine()' will end with a '\r' - // since we use '\n' as the line boundary of the reader. So we trim it off here. - currentValue = CoderUtils.decodeFromByteArray(StringUtf8Coder.of(), buf.toByteArray()).trim(); - return true; - } - - public String getCurrent() { - return currentValue; - } - - public long getCurrentLineStart() { - return currentLineStart; - } - } - - /** - * A reader that can read lines of text from a {@link TestFileBasedSource}. This reader does not - * consider {@code splitHeader} defined by {@code TestFileBasedSource} hence every line can be the - * first line of a split. - */ - private static class TestReader extends FileBasedReader { - private LineReader lineReader = null; - - public TestReader(TestFileBasedSource source) { - super(source); - } - - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - this.lineReader = new LineReader(channel); - } - - @Override - protected boolean readNextRecord() throws IOException { - return lineReader.readNextLine(); - } - - @Override - protected boolean isAtSplitPoint() { - return true; - } - - @Override - protected long getCurrentOffset() { - return lineReader.getCurrentLineStart(); - } - - @Override - public String getCurrent() throws NoSuchElementException { - return lineReader.getCurrent(); - } - } - - /** - * A reader that can read lines of text from a {@link TestFileBasedSource}. This reader considers - * {@code splitHeader} defined by {@code TestFileBasedSource} hence only lines that immediately - * follow a {@code splitHeader} are split points. - */ - private static class TestReaderWithSplits extends FileBasedReader { - private LineReader lineReader; - private final String splitHeader; - private boolean foundFirstSplitPoint = false; - private boolean isAtSplitPoint = false; - private long currentOffset; - - public TestReaderWithSplits(TestFileBasedSource source) { - super(source); - this.splitHeader = source.splitHeader; - } - - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - this.lineReader = new LineReader(channel); - } - - @Override - protected boolean readNextRecord() throws IOException { - if (!foundFirstSplitPoint) { - while (!isAtSplitPoint) { - if (!readNextRecordInternal()) { - return false; - } - } - foundFirstSplitPoint = true; - return true; - } - return readNextRecordInternal(); - } - - private boolean readNextRecordInternal() throws IOException { - isAtSplitPoint = false; - if (!lineReader.readNextLine()) { - return false; - } - currentOffset = lineReader.getCurrentLineStart(); - while (getCurrent().equals(splitHeader)) { - currentOffset = lineReader.getCurrentLineStart(); - if (!lineReader.readNextLine()) { - return false; - } - isAtSplitPoint = true; - } - return true; - } - - @Override - protected boolean isAtSplitPoint() { - return isAtSplitPoint; - } - - @Override - protected long getCurrentOffset() { - return currentOffset; - } - - @Override - public String getCurrent() throws NoSuchElementException { - return lineReader.getCurrent(); - } - } - - public File createFileWithData(String fileName, List data) throws IOException { - File file = tempFolder.newFile(fileName); - Files.write(file.toPath(), data, StandardCharsets.UTF_8); - return file; - } - - private String createRandomString(int length) { - char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < length; i++) { - builder.append(chars[random.nextInt(chars.length)]); - } - return builder.toString(); - } - - public List createStringDataset(int dataItemLength, int numItems) { - List list = new ArrayList(); - for (int i = 0; i < numItems; i++) { - list.add(createRandomString(dataItemLength)); - } - return list; - } - - @Test - public void testFullyReadSingleFile() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List data = createStringDataset(3, 50); - - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source = new TestFileBasedSource(file.getPath(), 64, null); - assertEquals(data, readFromSource(source, options)); - } - - @Test - public void testFullyReadFilePattern() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List data1 = createStringDataset(3, 50); - File file1 = createFileWithData("file1", data1); - - List data2 = createStringDataset(3, 50); - createFileWithData("file2", data2); - - List data3 = createStringDataset(3, 50); - createFileWithData("file3", data3); - - List data4 = createStringDataset(3, 50); - createFileWithData("otherfile", data4); - - TestFileBasedSource source = - new TestFileBasedSource(new File(file1.getParent(), "file*").getPath(), 64, null); - List expectedResults = new ArrayList(); - expectedResults.addAll(data1); - expectedResults.addAll(data2); - expectedResults.addAll(data3); - assertThat(expectedResults, containsInAnyOrder(readFromSource(source, options).toArray())); - } - - @Test - public void testCloseUnstartedFilePatternReader() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List data1 = createStringDataset(3, 50); - File file1 = createFileWithData("file1", data1); - - List data2 = createStringDataset(3, 50); - createFileWithData("file2", data2); - - List data3 = createStringDataset(3, 50); - createFileWithData("file3", data3); - - List data4 = createStringDataset(3, 50); - createFileWithData("otherfile", data4); - - TestFileBasedSource source = - new TestFileBasedSource(new File(file1.getParent(), "file*").getPath(), 64, null); - Reader reader = source.createReader(options); - // Closing an unstarted FilePatternReader should not throw an exception. - try { - reader.close(); - } catch (Exception e) { - fail("Closing an unstarted FilePatternReader should not throw an exception"); - } - } - - @Test - public void testSplittingUsingFullThreadPool() throws Exception { - int numFiles = FileBasedSource.THREAD_POOL_SIZE * 5; - File file0 = null; - for (int i = 0; i < numFiles; i++) { - List data = createStringDataset(3, 1000); - File file = createFileWithData("file" + i, data); - if (i == 0) { - file0 = file; - } - } - - TestFileBasedSource source = - new TestFileBasedSource(file0.getParent() + "/" + "file*", Long.MAX_VALUE, null); - List> splits = source.splitIntoBundles(Long.MAX_VALUE, null); - assertEquals(numFiles, splits.size()); - } - - @Test - public void testSplittingFailsOnEmptyFileExpansion() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - String missingFilePath = tempFolder.newFolder().getAbsolutePath() + "/missing.txt"; - TestFileBasedSource source = new TestFileBasedSource(missingFilePath, Long.MAX_VALUE, null); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(String.format("Unable to find any files matching %s", missingFilePath)); - source.splitIntoBundles(1234, options); - } - - @Test - public void testFractionConsumedWhenReadingFilepattern() throws IOException { - List data1 = createStringDataset(3, 1000); - File file1 = createFileWithData("file1", data1); - - List data2 = createStringDataset(3, 1000); - createFileWithData("file2", data2); - - List data3 = createStringDataset(3, 1000); - createFileWithData("file3", data3); - - TestFileBasedSource source = - new TestFileBasedSource(file1.getParent() + "/" + "file*", 1024, null); - try (BoundedSource.BoundedReader reader = source.createReader(null)) { - double lastFractionConsumed = 0.0; - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertTrue(reader.start()); - assertTrue(reader.advance()); - assertTrue(reader.advance()); - // We're inside the first file. Should be in [0, 1/3). - assertTrue(reader.getFractionConsumed() > 0.0); - assertTrue(reader.getFractionConsumed() < 1.0 / 3.0); - while (reader.advance()) { - double fractionConsumed = reader.getFractionConsumed(); - assertTrue(fractionConsumed > lastFractionConsumed); - lastFractionConsumed = fractionConsumed; - } - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - } - } - - @Test - public void testFullyReadFilePatternFirstRecordEmpty() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - File file1 = createFileWithData("file1", new ArrayList()); - - IOChannelFactory mockIOFactory = Mockito.mock(IOChannelFactory.class); - String parent = file1.getParent(); - String pattern = "mocked://test"; - when(mockIOFactory.match(pattern)) - .thenReturn( - ImmutableList.of( - new File(parent, "file1").getPath(), - new File(parent, "file2").getPath(), - new File(parent, "file3").getPath())); - IOChannelUtils.setIOFactory("mocked", mockIOFactory); - - List data2 = createStringDataset(3, 50); - createFileWithData("file2", data2); - - List data3 = createStringDataset(3, 50); - createFileWithData("file3", data3); - - List data4 = createStringDataset(3, 50); - createFileWithData("otherfile", data4); - - TestFileBasedSource source = new TestFileBasedSource(pattern, 64, null); - - List expectedResults = new ArrayList(); - expectedResults.addAll(data2); - expectedResults.addAll(data3); - assertThat(expectedResults, containsInAnyOrder(readFromSource(source, options).toArray())); - } - - @Test - public void testReadRangeAtStart() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List data = createStringDataset(3, 50); - - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source1 = new TestFileBasedSource(file.getPath(), 64, 0, 25, null); - TestFileBasedSource source2 = - new TestFileBasedSource(file.getPath(), 64, 25, Long.MAX_VALUE, null); - - List results = new ArrayList(); - results.addAll(readFromSource(source1, options)); - results.addAll(readFromSource(source2, options)); - assertThat(data, containsInAnyOrder(results.toArray())); - } - - @Test - public void testReadEverythingFromFileWithSplits() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - String header = ""; - List data = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - data.add(header); - data.addAll(createStringDataset(3, 9)); - } - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source = new TestFileBasedSource(file.getPath(), 64, header); - - List expectedResults = new ArrayList(); - expectedResults.addAll(data); - // Remove all occurrences of header from expected results. - expectedResults.removeAll(Arrays.asList(header)); - - assertEquals(expectedResults, readFromSource(source, options)); - } - - @Test - public void testReadRangeFromFileWithSplitsFromStart() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - String header = ""; - List data = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - data.add(header); - data.addAll(createStringDataset(3, 9)); - } - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source1 = new TestFileBasedSource(file.getPath(), 64, 0, 60, header); - TestFileBasedSource source2 = - new TestFileBasedSource(file.getPath(), 64, 60, Long.MAX_VALUE, header); - - List expectedResults = new ArrayList(); - expectedResults.addAll(data); - // Remove all occurrences of header from expected results. - expectedResults.removeAll(Arrays.asList(header)); - - List results = new ArrayList<>(); - results.addAll(readFromSource(source1, options)); - results.addAll(readFromSource(source2, options)); - - assertThat(expectedResults, containsInAnyOrder(results.toArray())); - } - - @Test - public void testReadRangeFromFileWithSplitsFromMiddle() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - String header = ""; - List data = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - data.add(header); - data.addAll(createStringDataset(3, 9)); - } - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source1 = new TestFileBasedSource(file.getPath(), 64, 0, 42, header); - TestFileBasedSource source2 = new TestFileBasedSource(file.getPath(), 64, 42, 112, header); - TestFileBasedSource source3 = - new TestFileBasedSource(file.getPath(), 64, 112, Long.MAX_VALUE, header); - - List expectedResults = new ArrayList(); - - expectedResults.addAll(data); - // Remove all occurrences of header from expected results. - expectedResults.removeAll(Arrays.asList(header)); - - List results = new ArrayList<>(); - results.addAll(readFromSource(source1, options)); - results.addAll(readFromSource(source2, options)); - results.addAll(readFromSource(source3, options)); - - assertThat(expectedResults, containsInAnyOrder(results.toArray())); - } - - @Test - public void testReadFileWithSplitsWithEmptyRange() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - String header = ""; - List data = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - data.add(header); - data.addAll(createStringDataset(3, 9)); - } - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source1 = new TestFileBasedSource(file.getPath(), 64, 0, 42, header); - TestFileBasedSource source2 = new TestFileBasedSource(file.getPath(), 64, 42, 62, header); - TestFileBasedSource source3 = - new TestFileBasedSource(file.getPath(), 64, 62, Long.MAX_VALUE, header); - - List expectedResults = new ArrayList(); - - expectedResults.addAll(data); - // Remove all occurrences of header from expected results. - expectedResults.removeAll(Arrays.asList(header)); - - List results = new ArrayList<>(); - results.addAll(readFromSource(source1, options)); - results.addAll(readFromSource(source2, options)); - results.addAll(readFromSource(source3, options)); - - assertThat(expectedResults, containsInAnyOrder(results.toArray())); - } - - @Test - public void testReadRangeFromFileWithSplitsFromMiddleOfHeader() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - String header = ""; - List data = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - data.add(header); - data.addAll(createStringDataset(3, 9)); - } - String fileName = "file"; - File file = createFileWithData(fileName, data); - - List expectedResults = new ArrayList(); - expectedResults.addAll(data.subList(10, data.size())); - // Remove all occurrences of header from expected results. - expectedResults.removeAll(Arrays.asList(header)); - - // Split starts after "<" of the header - TestFileBasedSource source = - new TestFileBasedSource(file.getPath(), 64, 1, Long.MAX_VALUE, header); - assertThat(expectedResults, containsInAnyOrder(readFromSource(source, options).toArray())); - - // Split starts after "" of the header - source = new TestFileBasedSource(file.getPath(), 64, 3, Long.MAX_VALUE, header); - assertThat(expectedResults, containsInAnyOrder(readFromSource(source, options).toArray())); - } - - @Test - public void testReadRangeAtMiddle() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List data = createStringDataset(3, 50); - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source1 = new TestFileBasedSource(file.getPath(), 64, 0, 52, null); - TestFileBasedSource source2 = new TestFileBasedSource(file.getPath(), 64, 52, 72, null); - TestFileBasedSource source3 = - new TestFileBasedSource(file.getPath(), 64, 72, Long.MAX_VALUE, null); - - List results = new ArrayList<>(); - results.addAll(readFromSource(source1, options)); - results.addAll(readFromSource(source2, options)); - results.addAll(readFromSource(source3, options)); - - assertThat(data, containsInAnyOrder(results.toArray())); - } - - @Test - public void testReadRangeAtEnd() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List data = createStringDataset(3, 50); - - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source1 = new TestFileBasedSource(file.getPath(), 64, 0, 162, null); - TestFileBasedSource source2 = - new TestFileBasedSource(file.getPath(), 1024, 162, Long.MAX_VALUE, null); - - List results = new ArrayList<>(); - results.addAll(readFromSource(source1, options)); - results.addAll(readFromSource(source2, options)); - - assertThat(data, containsInAnyOrder(results.toArray())); - } - - @Test - public void testReadAllSplitsOfSingleFile() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - List data = createStringDataset(3, 50); - - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source = new TestFileBasedSource(file.getPath(), 16, null); - - List> sources = source.splitIntoBundles(32, null); - - // Not a trivial split. - assertTrue(sources.size() > 1); - - List results = new ArrayList(); - for (BoundedSource split : sources) { - results.addAll(readFromSource(split, options)); - } - - assertThat(data, containsInAnyOrder(results.toArray())); - } - - @Test - public void testDataflowFile() throws IOException { - Pipeline p = TestPipeline.create(); - List data = createStringDataset(3, 50); - - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source = new TestFileBasedSource(file.getPath(), 64, null); - PCollection output = p.apply(Read.from(source).named("ReadFileData")); - - DataflowAssert.that(output).containsInAnyOrder(data); - p.run(); - } - - @Test - public void testDataflowFilePattern() throws IOException { - Pipeline p = TestPipeline.create(); - - List data1 = createStringDataset(3, 50); - File file1 = createFileWithData("file1", data1); - - List data2 = createStringDataset(3, 50); - createFileWithData("file2", data2); - - List data3 = createStringDataset(3, 50); - createFileWithData("file3", data3); - - List data4 = createStringDataset(3, 50); - createFileWithData("otherfile", data4); - - TestFileBasedSource source = - new TestFileBasedSource(new File(file1.getParent(), "file*").getPath(), 64, null); - - PCollection output = p.apply(Read.from(source).named("ReadFileData")); - - List expectedResults = new ArrayList(); - expectedResults.addAll(data1); - expectedResults.addAll(data2); - expectedResults.addAll(data3); - - DataflowAssert.that(output).containsInAnyOrder(expectedResults); - p.run(); - } - - @Test - public void testEstimatedSizeOfFile() throws Exception { - List data = createStringDataset(3, 50); - String fileName = "file"; - File file = createFileWithData(fileName, data); - - TestFileBasedSource source = new TestFileBasedSource(file.getPath(), 64, null); - assertEquals(file.length(), source.getEstimatedSizeBytes(null)); - } - - @Test - public void testEstimatedSizeOfFilePattern() throws Exception { - List data1 = createStringDataset(3, 20); - File file1 = createFileWithData("file1", data1); - - List data2 = createStringDataset(3, 40); - File file2 = createFileWithData("file2", data2); - - List data3 = createStringDataset(3, 30); - File file3 = createFileWithData("file3", data3); - - List data4 = createStringDataset(3, 45); - createFileWithData("otherfile", data4); - - List data5 = createStringDataset(3, 53); - createFileWithData("anotherfile", data5); - - TestFileBasedSource source = - new TestFileBasedSource(new File(file1.getParent(), "file*").getPath(), 64, null); - - // Estimated size of the file pattern based source should be the total size of files that the - // corresponding pattern is expanded into. - assertEquals( - file1.length() + file2.length() + file3.length(), source.getEstimatedSizeBytes(null)); - } - - @Test - public void testEstimatedSizeOfFilePatternAllThreads() throws Exception { - File file0 = null; - int numFiles = FileBasedSource.THREAD_POOL_SIZE * 5; - long totalSize = 0; - for (int i = 0; i < numFiles; i++) { - List data = createStringDataset(3, 20); - File file = createFileWithData("file" + i, data); - if (i == 0) { - file0 = file; - } - totalSize += file.length(); - } - - TestFileBasedSource source = - new TestFileBasedSource(new File(file0.getParent(), "file*").getPath(), 64, null); - - // Since all files are of equal size, sampling should produce the exact result. - assertEquals(totalSize, source.getEstimatedSizeBytes(null)); - } - - @Test - public void testEstimatedSizeOfFilePatternThroughSamplingEqualSize() throws Exception { - // When all files are of equal size, we should get the exact size. - int numFilesToTest = FileBasedSource.MAX_NUMBER_OF_FILES_FOR_AN_EXACT_STAT * 2; - File file0 = null; - for (int i = 0; i < numFilesToTest; i++) { - List data = createStringDataset(3, 20); - File file = createFileWithData("file" + i, data); - if (i == 0) { - file0 = file; - } - } - - long actualTotalSize = file0.length() * numFilesToTest; - TestFileBasedSource source = - new TestFileBasedSource(new File(file0.getParent(), "file*").getPath(), 64, null); - assertEquals(actualTotalSize, source.getEstimatedSizeBytes(null)); - } - - @Test - public void testEstimatedSizeOfFilePatternThroughSamplingDifferentSizes() throws Exception { - float tolerableError = 0.2f; - int numFilesToTest = FileBasedSource.MAX_NUMBER_OF_FILES_FOR_AN_EXACT_STAT * 2; - File file0 = null; - - // Keeping sizes of files close to each other to make sure that the test passes reliably. - Random rand = new Random(System.currentTimeMillis()); - int dataSizeBase = 100; - int dataSizeDelta = 10; - - long actualTotalSize = 0; - for (int i = 0; i < numFilesToTest; i++) { - List data = createStringDataset( - 3, (int) (dataSizeBase + rand.nextFloat() * dataSizeDelta * 2 - dataSizeDelta)); - File file = createFileWithData("file" + i, data); - if (i == 0) { - file0 = file; - } - actualTotalSize += file.length(); - } - - TestFileBasedSource source = - new TestFileBasedSource(new File(file0.getParent(), "file*").getPath(), 64, null); - assertEquals((double) actualTotalSize, (double) source.getEstimatedSizeBytes(null), - actualTotalSize * tolerableError); - } - - @Test - public void testReadAllSplitsOfFilePattern() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - List data1 = createStringDataset(3, 50); - File file1 = createFileWithData("file1", data1); - - List data2 = createStringDataset(3, 50); - createFileWithData("file2", data2); - - List data3 = createStringDataset(3, 50); - createFileWithData("file3", data3); - - List data4 = createStringDataset(3, 50); - createFileWithData("otherfile", data4); - - TestFileBasedSource source = - new TestFileBasedSource(new File(file1.getParent(), "file*").getPath(), 64, null); - List> sources = source.splitIntoBundles(512, null); - - // Not a trivial split. - assertTrue(sources.size() > 1); - - List results = new ArrayList(); - for (BoundedSource split : sources) { - results.addAll(readFromSource(split, options)); - } - - List expectedResults = new ArrayList(); - expectedResults.addAll(data1); - expectedResults.addAll(data2); - expectedResults.addAll(data3); - - assertThat(expectedResults, containsInAnyOrder(results.toArray())); - } - - @Test - public void testSplitAtFraction() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - File file = createFileWithData("file", createStringDataset(3, 100)); - - TestFileBasedSource source = new TestFileBasedSource(file.getPath(), 1, 0, file.length(), null); - // Shouldn't be able to split while unstarted. - assertSplitAtFractionFails(source, 0, 0.7, options); - assertSplitAtFractionSucceedsAndConsistent(source, 1, 0.7, options); - assertSplitAtFractionSucceedsAndConsistent(source, 30, 0.7, options); - assertSplitAtFractionFails(source, 0, 0.0, options); - assertSplitAtFractionFails(source, 70, 0.3, options); - assertSplitAtFractionFails(source, 100, 1.0, options); - assertSplitAtFractionFails(source, 100, 0.99, options); - assertSplitAtFractionSucceedsAndConsistent(source, 100, 0.995, options); - } - - @Test - public void testSplitAtFractionExhaustive() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - // Smaller file for exhaustive testing. - File file = createFileWithData("file", createStringDataset(3, 20)); - - TestFileBasedSource source = new TestFileBasedSource(file.getPath(), 1, 0, file.length(), null); - assertSplitAtFractionExhaustive(source, options); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java deleted file mode 100644 index 1b3f8f3744..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/OffsetBasedSourceTest.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionExhaustive; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.OffsetBasedSource.OffsetBasedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Tests code common to all offset-based sources. - */ -@RunWith(JUnit4.class) -public class OffsetBasedSourceTest { - // An offset-based source with 4 bytes per offset that yields its own current offset - // and rounds the start and end offset to the nearest multiple of a given number, - // e.g. reading [13, 48) with granularity 10 gives records with values [20, 50). - private static class CoarseRangeSource extends OffsetBasedSource { - private long granularity; - - public CoarseRangeSource( - long startOffset, long endOffset, long minBundleSize, long granularity) { - super(startOffset, endOffset, minBundleSize); - this.granularity = granularity; - } - - @Override - public OffsetBasedSource createSourceForSubrange(long start, long end) { - return new CoarseRangeSource(start, end, getMinBundleSize(), granularity); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public void validate() {} - - @Override - public Coder getDefaultOutputCoder() { - return BigEndianIntegerCoder.of(); - } - - @Override - public long getBytesPerOffset() { - return 4; - } - - @Override - public long getMaxEndOffset(PipelineOptions options) { - return getEndOffset(); - } - - @Override - public OffsetBasedReader createReader(PipelineOptions options) throws IOException { - return new CoarseRangeReader(this); - } - } - - private static class CoarseRangeReader extends OffsetBasedReader { - private long current = -1; - private long granularity; - - public CoarseRangeReader(CoarseRangeSource source) { - super(source); - this.granularity = source.granularity; - } - - @Override - protected long getCurrentOffset() { - return current; - } - - @Override - public boolean startImpl() throws IOException { - current = getCurrentSource().getStartOffset(); - while (current % granularity != 0) { - ++current; - } - return true; - } - - @Override - public boolean advanceImpl() throws IOException { - ++current; - return true; - } - - @Override - public Integer getCurrent() throws NoSuchElementException { - return (int) current; - } - - @Override - public boolean isAtSplitPoint() { - return current % granularity == 0; - } - - @Override - public void close() throws IOException { } - } - - public static void assertSplitsAre(List> splits, - long[] expectedBoundaries) { - assertEquals(splits.size(), expectedBoundaries.length - 1); - int i = 0; - for (OffsetBasedSource split : splits) { - assertEquals(split.getStartOffset(), expectedBoundaries[i]); - assertEquals(split.getEndOffset(), expectedBoundaries[i + 1]); - i++; - } - } - - @Test - public void testSplitPositionsZeroStart() throws Exception { - long start = 0; - long end = 1000; - long minBundleSize = 50; - CoarseRangeSource testSource = new CoarseRangeSource(start, end, minBundleSize, 1); - long[] boundaries = {0, 150, 300, 450, 600, 750, 900, 1000}; - assertSplitsAre( - testSource.splitIntoBundles(150 * testSource.getBytesPerOffset(), null), - boundaries); - } - - @Test - public void testSplitPositionsNonZeroStart() throws Exception { - long start = 300; - long end = 1000; - long minBundleSize = 50; - CoarseRangeSource testSource = new CoarseRangeSource(start, end, minBundleSize, 1); - long[] boundaries = {300, 450, 600, 750, 900, 1000}; - assertSplitsAre( - testSource.splitIntoBundles(150 * testSource.getBytesPerOffset(), null), - boundaries); - } - - @Test - public void testEstimatedSizeBytes() throws Exception { - long start = 300; - long end = 1000; - long minBundleSize = 150; - CoarseRangeSource testSource = new CoarseRangeSource(start, end, minBundleSize, 1); - PipelineOptions options = PipelineOptionsFactory.create(); - assertEquals( - (end - start) * testSource.getBytesPerOffset(), testSource.getEstimatedSizeBytes(options)); - } - - @Test - public void testMinBundleSize() throws Exception { - long start = 300; - long end = 1000; - long minBundleSize = 150; - CoarseRangeSource testSource = new CoarseRangeSource(start, end, minBundleSize, 1); - long[] boundaries = {300, 450, 600, 750, 1000}; - assertSplitsAre( - testSource.splitIntoBundles(100 * testSource.getBytesPerOffset(), null), - boundaries); - } - - @Test - public void testSplitPositionsCollapseEndBundle() throws Exception { - long start = 0; - long end = 1000; - long minBundleSize = 50; - CoarseRangeSource testSource = new CoarseRangeSource(start, end, minBundleSize, 1); - // Last 10 bytes should collapse to the previous bundle. - long[] boundaries = {0, 110, 220, 330, 440, 550, 660, 770, 880, 1000}; - assertSplitsAre( - testSource.splitIntoBundles(110 * testSource.getBytesPerOffset(), null), - boundaries); - } - - @Test - public void testReadingGranularityAndFractionConsumed() throws IOException { - // Tests that the reader correctly snaps to multiples of the given granularity - // (note: this is testing test code), and that getFractionConsumed works sensibly - // in the face of that. - PipelineOptions options = PipelineOptionsFactory.create(); - CoarseRangeSource source = new CoarseRangeSource(13, 35, 1, 10); - try (BoundedSource.BoundedReader reader = source.createReader(options)) { - List items = new ArrayList<>(); - - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertTrue(reader.start()); - items.add(reader.getCurrent()); - while (reader.advance()) { - Double fraction = reader.getFractionConsumed(); - assertNotNull(fraction); - assertTrue(fraction.toString(), fraction > 0.0); - assertTrue(fraction.toString(), fraction <= 1.0); - items.add(reader.getCurrent()); - } - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - - assertEquals(20, items.size()); - assertEquals(20, items.get(0).intValue()); - assertEquals(39, items.get(items.size() - 1).intValue()); - - source = new CoarseRangeSource(13, 17, 1, 10); - } - try (BoundedSource.BoundedReader reader = source.createReader(options)) { - assertFalse(reader.start()); - } - } - - @Test - public void testProgress() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - CoarseRangeSource source = new CoarseRangeSource(13, 17, 1, 2); - try (OffsetBasedReader reader = source.createReader(options)) { - // Unstarted reader - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Start and produce the element 14 since granularity is 2. - assertTrue(reader.start()); - assertTrue(reader.isAtSplitPoint()); - assertEquals(14, reader.getCurrent().intValue()); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - // Advance and produce the element 15, not a split point. - assertTrue(reader.advance()); - assertEquals(15, reader.getCurrent().intValue()); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Advance and produce the element 16, is a split point. Since the next offset (17) is - // outside the range [13, 17), remaining parallelism should become 1 from UNKNOWN. - assertTrue(reader.advance()); - assertTrue(reader.isAtSplitPoint()); - assertEquals(16, reader.getCurrent().intValue()); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); // The next offset is outside the range. - // Advance and produce the element 17, not a split point. - assertTrue(reader.advance()); - assertEquals(17, reader.getCurrent().intValue()); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - - // Advance and reach the end of the reader. - assertFalse(reader.advance()); - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(2, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - public void testProgressEmptySource() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - CoarseRangeSource source = new CoarseRangeSource(13, 17, 1, 100); - try (OffsetBasedReader reader = source.createReader(options)) { - // before starting - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // confirm empty - assertFalse(reader.start()); - - // after reading empty source - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - public void testSplitAtFraction() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - CoarseRangeSource source = new CoarseRangeSource(13, 35, 1, 10); - try (CoarseRangeReader reader = (CoarseRangeReader) source.createReader(options)) { - List originalItems = new ArrayList<>(); - assertTrue(reader.start()); - originalItems.add(reader.getCurrent()); - assertTrue(reader.advance()); - originalItems.add(reader.getCurrent()); - assertTrue(reader.advance()); - originalItems.add(reader.getCurrent()); - assertTrue(reader.advance()); - originalItems.add(reader.getCurrent()); - assertNull(reader.splitAtFraction(0.0)); - assertNull(reader.splitAtFraction(reader.getFractionConsumed() - 0.1)); - - BoundedSource residual = reader.splitAtFraction(reader.getFractionConsumed() + 0.1); - BoundedSource primary = reader.getCurrentSource(); - List primaryItems = readFromSource(primary, options); - List residualItems = readFromSource(residual, options); - for (Integer item : residualItems) { - assertTrue(item > reader.getCurrentOffset()); - } - assertFalse(primaryItems.isEmpty()); - assertFalse(residualItems.isEmpty()); - assertTrue(primaryItems.get(primaryItems.size() - 1) <= residualItems.get(0)); - - while (reader.advance()) { - originalItems.add(reader.getCurrent()); - } - assertEquals(originalItems, primaryItems); - } - } - - @Test - public void testSplitAtFractionExhaustive() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - CoarseRangeSource original = new CoarseRangeSource(13, 35, 1, 10); - assertSplitAtFractionExhaustive(original, options); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java deleted file mode 100644 index fbb563e4d7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubIOTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; - -import org.joda.time.Duration; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Set; - -/** - * Tests for PubsubIO Read and Write transforms. - */ -@RunWith(JUnit4.class) -public class PubsubIOTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testPubsubIOGetName() { - assertEquals("PubsubIO.Read", - PubsubIO.Read.topic("projects/myproject/topics/mytopic").getName()); - assertEquals("PubsubIO.Write", - PubsubIO.Write.topic("projects/myproject/topics/mytopic").getName()); - assertEquals("ReadMyTopic", - PubsubIO.Read.named("ReadMyTopic").topic("projects/myproject/topics/mytopic").getName()); - assertEquals("WriteMyTopic", - PubsubIO.Write.named("WriteMyTopic").topic("projects/myproject/topics/mytopic").getName()); - } - - @Test - public void testTopicValidationSuccess() throws Exception { - PubsubIO.Read.topic("projects/my-project/topics/abc"); - PubsubIO.Read.topic("projects/my-project/topics/ABC"); - PubsubIO.Read.topic("projects/my-project/topics/AbC-DeF"); - PubsubIO.Read.topic("projects/my-project/topics/AbC-1234"); - PubsubIO.Read.topic("projects/my-project/topics/AbC-1234-_.~%+-_.~%+-_.~%+-abc"); - PubsubIO.Read.topic(new StringBuilder().append("projects/my-project/topics/A-really-long-one-") - .append("111111111111111111111111111111111111111111111111111111111111111111111111111111111") - .append("111111111111111111111111111111111111111111111111111111111111111111111111111111111") - .append("11111111111111111111111111111111111111111111111111111111111111111111111111") - .toString()); - } - - @Test - public void testTopicValidationBadCharacter() throws Exception { - thrown.expect(IllegalArgumentException.class); - PubsubIO.Read.topic("projects/my-project/topics/abc-*-abc"); - } - - @Test - public void testTopicValidationTooLong() throws Exception { - thrown.expect(IllegalArgumentException.class); - PubsubIO.Read.topic(new StringBuilder().append("projects/my-project/topics/A-really-long-one-") - .append("111111111111111111111111111111111111111111111111111111111111111111111111111111111") - .append("111111111111111111111111111111111111111111111111111111111111111111111111111111111") - .append("1111111111111111111111111111111111111111111111111111111111111111111111111111") - .toString()); - } - - @Test - public void testReadDisplayData() { - String topic = "projects/project/topics/topic"; - String subscription = "projects/project/subscriptions/subscription"; - Duration maxReadTime = Duration.standardMinutes(5); - PubsubIO.Read.Bound read = PubsubIO.Read - .topic(StaticValueProvider.of(topic)) - .subscription(StaticValueProvider.of(subscription)) - .timestampLabel("myTimestamp") - .idLabel("myId") - .maxNumRecords(1234) - .maxReadTime(maxReadTime); - - DisplayData displayData = DisplayData.from(read); - - assertThat(displayData, hasDisplayItem("topic", topic)); - assertThat(displayData, hasDisplayItem("subscription", subscription)); - assertThat(displayData, hasDisplayItem("timestampLabel", "myTimestamp")); - assertThat(displayData, hasDisplayItem("idLabel", "myId")); - assertThat(displayData, hasDisplayItem("maxNumRecords", 1234)); - assertThat(displayData, hasDisplayItem("maxReadTime", maxReadTime)); - } - - @Test - public void testWriteDisplayData() { - String topic = "projects/project/topics/topic"; - PubsubIO.Write.Bound write = PubsubIO.Write - .topic(topic) - .timestampLabel("myTimestamp") - .idLabel("myId"); - - DisplayData displayData = DisplayData.from(write); - - assertThat(displayData, hasDisplayItem("topic", topic)); - assertThat(displayData, hasDisplayItem("timestampLabel", "myTimestamp")); - assertThat(displayData, hasDisplayItem("idLabel", "myId")); - } - - @Test - public void testPrimitiveWriteDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - PubsubIO.Write.Bound write = PubsubIO.Write - .topic("projects/project/topics/topic"); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(write); - assertThat("PubsubIO.Write should include the topic in its primitive display data", - displayData, hasItem(hasDisplayItem("topic"))); - } - - @Test - public void testNullTopic() { - String subscription = "projects/project/subscriptions/subscription"; - PubsubIO.Read.Bound read = PubsubIO.Read - .subscription(StaticValueProvider.of(subscription)); - assertNull(read.getTopic()); - assertNotNull(read.getSubscription()); - assertNotNull(DisplayData.from(read)); - } - - @Test - public void testNullSubscription() { - String topic = "projects/project/topics/topic"; - PubsubIO.Read.Bound read = PubsubIO.Read - .topic(StaticValueProvider.of(topic)); - assertNotNull(read.getTopic()); - assertNull(read.getSubscription()); - assertNotNull(DisplayData.from(read)); - } - - @Test - public void testPrimitiveReadDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - PubsubIO.Read.Bound read = PubsubIO.Read.topic("projects/project/topics/topic") - .maxNumRecords(1); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(read); - assertThat("PubsubIO.Read should include the topic in its primitive display data", - displayData, hasItem(hasDisplayItem("topic"))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java deleted file mode 100644 index 287f07e52c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSinkTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSink.RecordIdMethod; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.PubsubClient; -import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; -import com.google.cloud.dataflow.sdk.util.PubsubTestClient; -import com.google.cloud.dataflow.sdk.util.PubsubTestClient.PubsubTestClientFactory; - -import com.google.common.collect.ImmutableList; -import com.google.common.hash.Hashing; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Test PubsubUnboundedSink. - */ -@RunWith(JUnit4.class) -public class PubsubUnboundedSinkTest { - private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); - private static final String DATA = "testData"; - private static final long TIMESTAMP = 1234L; - private static final String TIMESTAMP_LABEL = "timestamp"; - private static final String ID_LABEL = "id"; - private static final int NUM_SHARDS = 10; - - private static class Stamp extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.outputWithTimestamp(c.element(), new Instant(TIMESTAMP)); - } - } - - private String getRecordId(String data) { - return Hashing.murmur3_128().hashBytes(data.getBytes()).toString(); - } - - @Test - public void saneCoder() throws Exception { - OutgoingMessage message = new OutgoingMessage(DATA.getBytes(), TIMESTAMP, getRecordId(DATA)); - CoderProperties.coderDecodeEncodeEqual(PubsubUnboundedSink.CODER, message); - CoderProperties.coderSerializable(PubsubUnboundedSink.CODER); - } - - @Test - public void sendOneMessage() throws IOException { - List outgoing = - ImmutableList.of(new OutgoingMessage(DATA.getBytes(), TIMESTAMP, getRecordId(DATA))); - int batchSize = 1; - int batchBytes = 1; - try (PubsubTestClientFactory factory = - PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, - ImmutableList.of())) { - PubsubUnboundedSink sink = - new PubsubUnboundedSink<>(factory, StaticValueProvider.of(TOPIC), StringUtf8Coder.of(), - TIMESTAMP_LABEL, ID_LABEL, NUM_SHARDS, batchSize, batchBytes, - Duration.standardSeconds(2), RecordIdMethod.DETERMINISTIC); - TestPipeline p = TestPipeline.create(); - p.apply(Create.of(ImmutableList.of(DATA))) - .apply(ParDo.of(new Stamp())) - .apply(sink); - p.run(); - } - // The PubsubTestClientFactory will assert fail on close if the actual published - // message does not match the expected publish message. - } - - @Test - public void sendMoreThanOneBatchByNumMessages() throws IOException { - List outgoing = new ArrayList<>(); - List data = new ArrayList<>(); - int batchSize = 2; - int batchBytes = 1000; - for (int i = 0; i < batchSize * 10; i++) { - String str = String.valueOf(i); - outgoing.add(new OutgoingMessage(str.getBytes(), TIMESTAMP, getRecordId(str))); - data.add(str); - } - try (PubsubTestClientFactory factory = - PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, - ImmutableList.of())) { - PubsubUnboundedSink sink = - new PubsubUnboundedSink<>(factory, StaticValueProvider.of(TOPIC), StringUtf8Coder.of(), - TIMESTAMP_LABEL, ID_LABEL, NUM_SHARDS, batchSize, batchBytes, - Duration.standardSeconds(2), RecordIdMethod.DETERMINISTIC); - TestPipeline p = TestPipeline.create(); - p.apply(Create.of(data)) - .apply(ParDo.of(new Stamp())) - .apply(sink); - p.run(); - } - // The PubsubTestClientFactory will assert fail on close if the actual published - // message does not match the expected publish message. - } - - @Test - public void sendMoreThanOneBatchByByteSize() throws IOException { - List outgoing = new ArrayList<>(); - List data = new ArrayList<>(); - int batchSize = 100; - int batchBytes = 10; - int n = 0; - while (n < batchBytes * 10) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < batchBytes; i++) { - sb.append(String.valueOf(n)); - } - String str = sb.toString(); - outgoing.add(new OutgoingMessage(str.getBytes(), TIMESTAMP, getRecordId(str))); - data.add(str); - n += str.length(); - } - try (PubsubTestClientFactory factory = - PubsubTestClient.createFactoryForPublish(TOPIC, outgoing, - ImmutableList.of())) { - PubsubUnboundedSink sink = - new PubsubUnboundedSink<>(factory, StaticValueProvider.of(TOPIC), - StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL, - NUM_SHARDS, batchSize, batchBytes, Duration.standardSeconds(2), - RecordIdMethod.DETERMINISTIC); - TestPipeline p = TestPipeline.create(); - p.apply(Create.of(data)) - .apply(ParDo.of(new Stamp())) - .apply(sink); - p.run(); - } - // The PubsubTestClientFactory will assert fail on close if the actual published - // message does not match the expected publish message. - } - - // TODO: We would like to test that failed Pubsub publish calls cause the already assigned - // (and random) record ids to be reused. However that can't be done without the test runnner - // supporting retrying bundles. -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java deleted file mode 100644 index f7e4f863de..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static junit.framework.TestCase.assertFalse; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.api.client.util.Clock; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubCheckpoint; -import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubReader; -import com.google.cloud.dataflow.sdk.io.PubsubUnboundedSource.PubsubSource; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.PubsubClient; -import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; -import com.google.cloud.dataflow.sdk.util.PubsubTestClient; -import com.google.cloud.dataflow.sdk.util.PubsubTestClient.PubsubTestClientFactory; - -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Test PubsubUnboundedSource. - */ -@RunWith(JUnit4.class) -public class PubsubUnboundedSourceTest { - private static final SubscriptionPath SUBSCRIPTION = - PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); - private static final String DATA = "testData"; - private static final long TIMESTAMP = 1234L; - private static final long REQ_TIME = 6373L; - private static final String TIMESTAMP_LABEL = "timestamp"; - private static final String ID_LABEL = "id"; - private static final String ACK_ID = "testAckId"; - private static final String RECORD_ID = "testRecordId"; - private static final int ACK_TIMEOUT_S = 60; - - private AtomicLong now; - private Clock clock; - private PubsubTestClientFactory factory; - private PubsubSource primSource; - - private void setupOneMessage(Iterable incoming) { - now = new AtomicLong(REQ_TIME); - clock = new Clock() { - @Override - public long currentTimeMillis() { - return now.get(); - } - }; - factory = PubsubTestClient.createFactoryForPull(clock, SUBSCRIPTION, ACK_TIMEOUT_S, incoming); - PubsubUnboundedSource source = - new PubsubUnboundedSource<>( - clock, factory, null, null, StaticValueProvider.of(SUBSCRIPTION), - StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL); - primSource = new PubsubSource<>(source); - } - - private void setupOneMessage() { - setupOneMessage(ImmutableList.of( - new IncomingMessage(DATA.getBytes(), TIMESTAMP, 0, ACK_ID, RECORD_ID))); - } - - @After - public void after() throws IOException { - factory.close(); - now = null; - clock = null; - primSource = null; - factory = null; - } - - @Test - public void checkpointCoderIsSane() throws Exception { - setupOneMessage(ImmutableList.of()); - CoderProperties.coderSerializable(primSource.getCheckpointMarkCoder()); - // Since we only serialize/deserialize the 'notYetReadIds', and we don't want to make - // equals on checkpoints ignore those fields, we'll test serialization and deserialization - // of checkpoints in multipleReaders below. - } - - @Test - public void readOneMessage() throws IOException { - setupOneMessage(); - TestPipeline p = TestPipeline.create(); - PubsubReader reader = primSource.createReader(p.getOptions(), null); - // Read one message. - assertTrue(reader.start()); - assertEquals(DATA, reader.getCurrent()); - assertFalse(reader.advance()); - // ACK the message. - PubsubCheckpoint checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - reader.close(); - } - - @Test - public void timeoutAckAndRereadOneMessage() throws IOException { - setupOneMessage(); - TestPipeline p = TestPipeline.create(); - PubsubReader reader = primSource.createReader(p.getOptions(), null); - PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); - assertTrue(reader.start()); - assertEquals(DATA, reader.getCurrent()); - // Let the ACK deadline for the above expire. - now.addAndGet(65 * 1000); - pubsubClient.advance(); - // We'll now receive the same message again. - assertTrue(reader.advance()); - assertEquals(DATA, reader.getCurrent()); - assertFalse(reader.advance()); - // Now ACK the message. - PubsubCheckpoint checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - reader.close(); - } - - @Test - public void extendAck() throws IOException { - setupOneMessage(); - TestPipeline p = TestPipeline.create(); - PubsubReader reader = primSource.createReader(p.getOptions(), null); - PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); - // Pull the first message but don't take a checkpoint for it. - assertTrue(reader.start()); - assertEquals(DATA, reader.getCurrent()); - // Extend the ack - now.addAndGet(55 * 1000); - pubsubClient.advance(); - assertFalse(reader.advance()); - // Extend the ack again - now.addAndGet(25 * 1000); - pubsubClient.advance(); - assertFalse(reader.advance()); - // Now ACK the message. - PubsubCheckpoint checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - reader.close(); - } - - @Test - public void timeoutAckExtensions() throws IOException { - setupOneMessage(); - TestPipeline p = TestPipeline.create(); - PubsubReader reader = primSource.createReader(p.getOptions(), null); - PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); - // Pull the first message but don't take a checkpoint for it. - assertTrue(reader.start()); - assertEquals(DATA, reader.getCurrent()); - // Extend the ack. - now.addAndGet(55 * 1000); - pubsubClient.advance(); - assertFalse(reader.advance()); - // Let the ack expire. - for (int i = 0; i < 3; i++) { - now.addAndGet(25 * 1000); - pubsubClient.advance(); - assertFalse(reader.advance()); - } - // Wait for resend. - now.addAndGet(25 * 1000); - pubsubClient.advance(); - // Reread the same message. - assertTrue(reader.advance()); - assertEquals(DATA, reader.getCurrent()); - // Now ACK the message. - PubsubCheckpoint checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - reader.close(); - } - - @Test - public void multipleReaders() throws IOException { - List incoming = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - String data = String.format("data_%d", i); - String ackid = String.format("ackid_%d", i); - incoming.add(new IncomingMessage(data.getBytes(), TIMESTAMP, 0, ackid, RECORD_ID)); - } - setupOneMessage(incoming); - TestPipeline p = TestPipeline.create(); - PubsubReader reader = primSource.createReader(p.getOptions(), null); - // Consume two messages, only read one. - assertTrue(reader.start()); - assertEquals("data_0", reader.getCurrent()); - - // Grab checkpoint. - PubsubCheckpoint checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - assertEquals(1, checkpoint.notYetReadIds.size()); - assertEquals("ackid_1", checkpoint.notYetReadIds.get(0)); - - // Read second message. - assertTrue(reader.advance()); - assertEquals("data_1", reader.getCurrent()); - - // Restore from checkpoint. - byte[] checkpointBytes = - CoderUtils.encodeToByteArray(primSource.getCheckpointMarkCoder(), checkpoint); - checkpoint = CoderUtils.decodeFromByteArray(primSource.getCheckpointMarkCoder(), - checkpointBytes); - assertEquals(1, checkpoint.notYetReadIds.size()); - assertEquals("ackid_1", checkpoint.notYetReadIds.get(0)); - - // Re-read second message. - reader = primSource.createReader(p.getOptions(), checkpoint); - assertTrue(reader.start()); - assertEquals("data_1", reader.getCurrent()); - - // We are done. - assertFalse(reader.advance()); - - // ACK final message. - checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - reader.close(); - } - - private long messageNumToTimestamp(int messageNum) { - return TIMESTAMP + messageNum * 100; - } - - @Test - public void readManyMessages() throws IOException { - Map dataToMessageNum = new HashMap<>(); - - final int m = 97; - final int n = 10000; - List incoming = new ArrayList<>(); - for (int i = 0; i < n; i++) { - // Make the messages timestamps slightly out of order. - int messageNum = ((i / m) * m) + (m - 1) - (i % m); - String data = String.format("data_%d", messageNum); - dataToMessageNum.put(data, messageNum); - String recid = String.format("recordid_%d", messageNum); - String ackId = String.format("ackid_%d", messageNum); - incoming.add(new IncomingMessage(data.getBytes(), messageNumToTimestamp(messageNum), 0, - ackId, recid)); - } - setupOneMessage(incoming); - - TestPipeline p = TestPipeline.create(); - PubsubReader reader = primSource.createReader(p.getOptions(), null); - PubsubTestClient pubsubClient = (PubsubTestClient) reader.getPubsubClient(); - - for (int i = 0; i < n; i++) { - if (i == 0) { - assertTrue(reader.start()); - } else { - assertTrue(reader.advance()); - } - // We'll checkpoint and ack within the 2min limit. - now.addAndGet(30); - pubsubClient.advance(); - String data = reader.getCurrent(); - Integer messageNum = dataToMessageNum.remove(data); - // No duplicate messages. - assertNotNull(messageNum); - // Preserve timestamp. - assertEquals(new Instant(messageNumToTimestamp(messageNum)), reader.getCurrentTimestamp()); - // Preserve record id. - String recid = String.format("recordid_%d", messageNum); - assertArrayEquals(recid.getBytes(), reader.getCurrentRecordId()); - - if (i % 1000 == 999) { - // Estimated watermark can never get ahead of actual outstanding messages. - long watermark = reader.getWatermark().getMillis(); - long minOutstandingTimestamp = Long.MAX_VALUE; - for (Integer outstandingMessageNum : dataToMessageNum.values()) { - minOutstandingTimestamp = - Math.min(minOutstandingTimestamp, messageNumToTimestamp(outstandingMessageNum)); - } - assertThat(watermark, lessThanOrEqualTo(minOutstandingTimestamp)); - // Ack messages, but only every other finalization. - PubsubCheckpoint checkpoint = reader.getCheckpointMark(); - if (i % 2000 == 1999) { - checkpoint.finalizeCheckpoint(); - } - } - } - // We are done. - assertFalse(reader.advance()); - // We saw each message exactly once. - assertTrue(dataToMessageNum.isEmpty()); - reader.close(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java deleted file mode 100644 index 6939ad4b14..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/ReadTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.StreamingOptions; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import org.joda.time.Duration; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.Serializable; -import java.util.List; -import java.util.Set; -import javax.annotation.Nullable; - -/** - * Tests for {@link Read}. - */ -@RunWith(JUnit4.class) -public class ReadTest implements Serializable{ - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void failsWhenCustomBoundedSourceIsNotSerializable() { - thrown.expect(IllegalArgumentException.class); - Read.from(new NotSerializableBoundedSource()); - } - - @Test - public void succeedsWhenCustomBoundedSourceIsSerializable() { - Read.from(new SerializableBoundedSource()); - } - - @Test - public void failsWhenCustomUnboundedSourceIsNotSerializable() { - thrown.expect(IllegalArgumentException.class); - Read.from(new NotSerializableUnboundedSource()); - } - - @Test - public void succeedsWhenCustomUnboundedSourceIsSerializable() { - Read.from(new SerializableUnboundedSource()); - } - - @Test - public void testDisplayData() { - SerializableBoundedSource boundedSource = new SerializableBoundedSource() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - SerializableUnboundedSource unboundedSource = new SerializableUnboundedSource() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - Duration maxReadTime = Duration.standardMinutes(2345); - - Read.Bounded bounded = Read.from(boundedSource); - BoundedReadFromUnboundedSource unbounded = Read.from(unboundedSource) - .withMaxNumRecords(1234) - .withMaxReadTime(maxReadTime); - - DisplayData boundedDisplayData = DisplayData.from(bounded); - assertThat(boundedDisplayData, hasDisplayItem("source", boundedSource.getClass())); - assertThat(boundedDisplayData, includesDisplayDataFrom(boundedSource)); - - DisplayData unboundedDisplayData = DisplayData.from(unbounded); - assertThat(unboundedDisplayData, hasDisplayItem("source", unboundedSource.getClass())); - assertThat(unboundedDisplayData, includesDisplayDataFrom(unboundedSource)); - assertThat(unboundedDisplayData, hasDisplayItem("maxRecords", 1234)); - assertThat(unboundedDisplayData, hasDisplayItem("maxReadTime", maxReadTime)); - } - - @Test - @Category(RunnableOnService.class) - public void testBoundedPrimitiveDisplayData() { - testPrimitiveDisplayData(/* isStreaming: */ false); - } - - @Test - @Category(RunnableOnService.class) - public void testStreamingPrimitiveDisplayData() { - testPrimitiveDisplayData(/* isStreaming: */ true); - } - - private void testPrimitiveDisplayData(boolean isStreaming) { - PipelineOptions options = DisplayDataEvaluator.getDefaultOptions(); - options.as(StreamingOptions.class).setStreaming(isStreaming); - DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(options); - - SerializableBoundedSource boundedSource = new SerializableBoundedSource() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - SerializableUnboundedSource unboundedSource = new SerializableUnboundedSource() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - Read.Bounded bounded = Read.from(boundedSource); - BoundedReadFromUnboundedSource unbounded = Read.from(unboundedSource) - .withMaxNumRecords(1234); - - Set boundedDisplayData = evaluator - .displayDataForPrimitiveSourceTransforms(bounded); - assertThat(boundedDisplayData, hasItem(hasDisplayItem("source", boundedSource.getClass()))); - assertThat(boundedDisplayData, hasItem(includesDisplayDataFrom(boundedSource))); - - Set unboundedDisplayData = evaluator - .displayDataForPrimitiveSourceTransforms(unbounded); - assertThat(unboundedDisplayData, hasItem(hasDisplayItem("source"))); - assertThat(unboundedDisplayData, hasItem(includesDisplayDataFrom(unboundedSource))); - } - - private abstract static class CustomBoundedSource extends BoundedSource { - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - return null; - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return 0; - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public BoundedReader createReader(PipelineOptions options) throws IOException { - return null; - } - - @Override - public void validate() {} - - @Override - public Coder getDefaultOutputCoder() { - return StringUtf8Coder.of(); - } - } - - private static class NotSerializableBoundedSource extends CustomBoundedSource { - @SuppressWarnings("unused") - private final NotSerializableClass notSerializableClass = new NotSerializableClass(); - } - - private static class SerializableBoundedSource extends CustomBoundedSource {} - - private abstract static class CustomUnboundedSource - extends UnboundedSource { - @Override - public List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception { - return null; - } - - @Override - public UnboundedReader createReader( - PipelineOptions options, NoOpCheckpointMark checkpointMark) { - return null; - } - - @Override - @Nullable - public Coder getCheckpointMarkCoder() { - return null; - } - - @Override - public void validate() {} - - @Override - public Coder getDefaultOutputCoder() { - return StringUtf8Coder.of(); - } - } - - private static class NoOpCheckpointMark implements CheckpointMark { - @Override - public void finalizeCheckpoint() throws IOException {} - } - - private static class NotSerializableUnboundedSource extends CustomUnboundedSource { - @SuppressWarnings("unused") - private final NotSerializableClass notSerializableClass = new NotSerializableClass(); - } - - private static class SerializableUnboundedSource extends CustomUnboundedSource {} - - private static class NotSerializableClass {} -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java deleted file mode 100644 index 063760681e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/TextIOTest.java +++ /dev/null @@ -1,1092 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.TestUtils.INTS_ARRAY; -import static com.google.cloud.dataflow.sdk.TestUtils.LINES_ARRAY; -import static com.google.cloud.dataflow.sdk.TestUtils.NO_INTS_ARRAY; -import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES_ARRAY; -import static com.google.cloud.dataflow.sdk.io.TextIO.CompressionType.AUTO; -import static com.google.cloud.dataflow.sdk.io.TextIO.CompressionType.BZIP2; -import static com.google.cloud.dataflow.sdk.io.TextIO.CompressionType.GZIP; -import static com.google.cloud.dataflow.sdk.io.TextIO.CompressionType.UNCOMPRESSED; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; -import static com.google.cloud.dataflow.sdk.util.IOChannelUtils.resolve; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.TextualIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.TextIO.CompressionType; -import com.google.cloud.dataflow.sdk.io.TextIO.TextSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; -import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.nio.channels.FileChannel; -import java.nio.channels.SeekableByteChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.zip.GZIPOutputStream; - -import javax.annotation.Nullable; - -/** - * Tests for TextIO Read and Write transforms. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("unchecked") -public class TextIOTest { - private static final String MY_HEADER = "myHeader"; - private static final String MY_FOOTER = "myFooter"; - private static final String[] EMPTY = new String[] {}; - private static final String[] TINY = - new String[] {"Irritable eagle", "Optimistic jay", "Fanciful hawk"}; - private static final String[] LARGE = makeLines(5000); - - private static Path tempFolder; - private static File emptyTxt; - private static File tinyTxt; - private static File largeTxt; - private static File emptyGz; - private static File tinyGz; - private static File largeGz; - private static File emptyBzip2; - private static File tinyBzip2; - private static File largeBzip2; - - @Rule public ExpectedException expectedException = ExpectedException.none(); - - private GcsUtil buildMockGcsUtil() throws IOException { - GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); - - // Any request to open gets a new bogus channel - Mockito - .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); - - // Any request for expansion returns a list containing the original GcsPath - // This is required to pass validation that occurs in TextIO during apply() - Mockito - .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); - - return mockGcsUtil; - } - - private TestDataflowPipelineOptions buildTestPipelineOptions() { - TestDataflowPipelineOptions options = - PipelineOptionsFactory.as(TestDataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - return options; - } - - private static File writeToFile(String[] lines, String filename, CompressionType compression) - throws IOException { - File file = tempFolder.resolve(filename).toFile(); - OutputStream output = new FileOutputStream(file); - switch (compression) { - case UNCOMPRESSED: - break; - case GZIP: - output = new GZIPOutputStream(output); - break; - case BZIP2: - output = new BZip2CompressorOutputStream(output); - break; - default: - throw new UnsupportedOperationException(compression.toString()); - } - writeToStreamAndClose(lines, output); - return file; - } - - @BeforeClass - public static void setupClass() throws IOException { - IOChannelUtils.registerStandardIOFactories(TestPipeline.testingPipelineOptions()); - tempFolder = Files.createTempDirectory("TextIOTest"); - // empty files - emptyTxt = writeToFile(EMPTY, "empty.txt", UNCOMPRESSED); - emptyGz = writeToFile(EMPTY, "empty.gz", GZIP); - emptyBzip2 = writeToFile(EMPTY, "empty.bz2", BZIP2); - // tiny files - tinyTxt = writeToFile(TINY, "tiny.txt", UNCOMPRESSED); - tinyGz = writeToFile(TINY, "tiny.gz", GZIP); - tinyBzip2 = writeToFile(TINY, "tiny.bz2", BZIP2); - // large files - largeTxt = writeToFile(LARGE, "large.txt", UNCOMPRESSED); - largeGz = writeToFile(LARGE, "large.gz", GZIP); - largeBzip2 = writeToFile(LARGE, "large.bz2", BZIP2); - } - - @AfterClass - public static void testdownClass() throws IOException { - Files.walkFileTree(tempFolder, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - }); - } - - private void runTestRead(T[] expected, Coder coder) throws Exception { - File tmpFile = Files.createTempFile(tempFolder, "file", "txt").toFile(); - String filename = tmpFile.getPath(); - - try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) { - for (T elem : expected) { - byte[] encodedElem = CoderUtils.encodeToByteArray(coder, elem); - String line = new String(encodedElem); - writer.println(line); - } - } - - Pipeline p = TestPipeline.create(); - - TextIO.Read.Bound read; - if (coder.equals(StringUtf8Coder.of())) { - TextIO.Read.Bound readStrings = TextIO.Read.from(filename); - // T==String - read = (TextIO.Read.Bound) readStrings; - } else { - read = TextIO.Read.from(filename).withCoder(coder); - } - - PCollection output = p.apply(read); - - DataflowAssert.that(output).containsInAnyOrder(expected); - p.run(); - } - - @Test - public void testReadStrings() throws Exception { - runTestRead(LINES_ARRAY, StringUtf8Coder.of()); - } - - @Test - public void testReadEmptyStrings() throws Exception { - runTestRead(NO_LINES_ARRAY, StringUtf8Coder.of()); - } - - @Test - public void testReadInts() throws Exception { - runTestRead(INTS_ARRAY, TextualIntegerCoder.of()); - } - - @Test - public void testReadEmptyInts() throws Exception { - runTestRead(NO_INTS_ARRAY, TextualIntegerCoder.of()); - } - - @Test - public void testReadNulls() throws Exception { - runTestRead(new Void[]{ null, null, null }, VoidCoder.of()); - } - - @Test - public void testReadNamed() throws Exception { - Pipeline p = TestPipeline.create(); - - assertEquals( - "TextIO.Read/Read.out", - p.apply(TextIO.Read.withoutValidation().from("somefile")).getName()); - - assertEquals( - "MyRead/Read.out", - p.apply("MyRead", TextIO.Read.withoutValidation().from("somefile")).getName()); - - assertEquals( - "HerRead/Read.out", - p.apply(TextIO.Read.withoutValidation().named("HerRead").from("somefile")).getName()); - } - - @Test - public void testReadDisplayData() { - TextIO.Read.Bound read = TextIO.Read - .from("foo.*") - .withCompressionType(BZIP2) - .withoutValidation(); - - DisplayData displayData = DisplayData.from(read); - - assertThat(displayData, hasDisplayItem("filePattern", "foo.*")); - assertThat(displayData, hasDisplayItem("compressionType", BZIP2.toString())); - assertThat(displayData, hasDisplayItem("validation", false)); - } - - private void runTestWrite(T[] elems, Coder coder) throws Exception { - runTestWrite(elems, null, null, coder, 1); - } - - private void runTestWrite(T[] elems, Coder coder, int numShards) throws Exception { - runTestWrite(elems, null, null, coder, numShards); - } - - private void runTestWrite(T[] elems, Coder coder, String header, String footer) - throws Exception { - runTestWrite(elems, header, footer, coder, 1); - } - - private void runTestWrite( - T[] elems, String header, String footer, Coder coder, int numShards) throws Exception { - String outputName = "file.txt"; - Path baseDir = Files.createTempDirectory(tempFolder, "testwrite"); - String baseFilename = baseDir.resolve(outputName).toString(); - - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(Arrays.asList(elems)).withCoder(coder)); - - TextIO.Write.Bound write; - if (coder.equals(StringUtf8Coder.of())) { - TextIO.Write.Bound writeStrings = TextIO.Write.to(baseFilename); - // T==String - write = (TextIO.Write.Bound) writeStrings; - } else { - write = TextIO.Write.to(baseFilename).withCoder(coder); - } - if (numShards == 1) { - write = write.withoutSharding(); - } else { - write = write.withNumShards(numShards).withShardNameTemplate(ShardNameTemplate.INDEX_OF_MAX); - } - write = write.withHeader(header).withFooter(footer); - - input.apply(write); - - p.run(); - - assertOutputFiles(elems, header, footer, coder, numShards, baseDir, outputName, - write.getShardNameTemplate()); - } - - public static void assertOutputFiles( - T[] elems, - final String header, - final String footer, - Coder coder, - int numShards, - Path rootLocation, - String outputName, - String shardNameTemplate) - throws Exception { - List expectedFiles = new ArrayList<>(); - if (numShards == 0) { - String pattern = - resolve(rootLocation.toAbsolutePath().toString(), outputName + "*"); - for (String expected : IOChannelUtils.getFactory(pattern).match(pattern)) { - expectedFiles.add(new File(expected)); - } - } else { - for (int i = 0; i < numShards; i++) { - expectedFiles.add( - new File( - rootLocation.toString(), - IOChannelUtils.constructName(outputName, shardNameTemplate, "", i, numShards))); - } - } - - List> actual = new ArrayList<>(); - for (File tmpFile : expectedFiles) { - try (BufferedReader reader = new BufferedReader(new FileReader(tmpFile))) { - List currentFile = new ArrayList<>(); - for (;;) { - String line = reader.readLine(); - if (line == null) { - break; - } - currentFile.add(line); - } - actual.add(currentFile); - } - } - - List expectedElements = new ArrayList<>(elems.length); - for (T elem : elems) { - byte[] encodedElem = CoderUtils.encodeToByteArray(coder, elem); - String line = new String(encodedElem); - expectedElements.add(line); - } - - List actualElements = - Lists.newArrayList( - Iterables.concat( - FluentIterable - .from(actual) - .transform(removeHeaderAndFooter(header, footer)) - .toList())); - - assertThat(actualElements, containsInAnyOrder(expectedElements.toArray())); - - assertTrue(Iterables.all(actual, haveProperHeaderAndFooter(header, footer))); - } - - private static Function, List> removeHeaderAndFooter(final String header, - final String footer) { - return new Function, List>() { - @Nullable - @Override - public List apply(List lines) { - ArrayList newLines = Lists.newArrayList(lines); - if (header != null) { - newLines.remove(0); - } - if (footer != null) { - int last = newLines.size() - 1; - newLines.remove(last); - } - return newLines; - } - }; - } - - private static Predicate> haveProperHeaderAndFooter(final String header, - final String footer) { - return new Predicate>() { - @Override - public boolean apply(List fileLines) { - int last = fileLines.size() - 1; - return (header == null || fileLines.get(0).equals(header)) - && (footer == null || fileLines.get(last).equals(footer)); - } - }; - } - - @Test - public void testWriteStrings() throws Exception { - runTestWrite(LINES_ARRAY, StringUtf8Coder.of()); - } - - @Test - public void testWriteEmptyStrings() throws Exception { - runTestWrite(NO_LINES_ARRAY, StringUtf8Coder.of()); - } - - @Test - public void testWriteInts() throws Exception { - runTestWrite(INTS_ARRAY, TextualIntegerCoder.of()); - } - - @Test - public void testWriteEmptyInts() throws Exception { - runTestWrite(NO_INTS_ARRAY, TextualIntegerCoder.of()); - } - - @Test - public void testWriteNamed() { - { - PTransform, PDone> transform1 = - TextIO.Write.to("/tmp/file.txt"); - assertEquals("TextIO.Write", transform1.getName()); - } - - { - PTransform, PDone> transform2 = - TextIO.Write.named("MyWrite").to("/tmp/file.txt"); - assertEquals("MyWrite", transform2.getName()); - } - - { - PTransform, PDone> transform3 = - TextIO.Write.to("/tmp/file.txt").named("HerWrite"); - assertEquals("HerWrite", transform3.getName()); - } - } - - @Test - public void testShardedWrite() throws Exception { - runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), 5); - } - - @Test - public void testWriteWithHeader() throws Exception { - runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), MY_HEADER, null); - } - - @Test - public void testWriteWithFooter() throws Exception { - runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), null, MY_FOOTER); - } - - @Test - public void testWriteWithHeaderAndFooter() throws Exception { - runTestWrite(LINES_ARRAY, StringUtf8Coder.of(), MY_HEADER, MY_FOOTER); - } - - @Test - public void testWriteDisplayData() { - TextIO.Write.Bound write = TextIO.Write - .to("foo") - .withSuffix("bar") - .withShardNameTemplate("-SS-of-NN-") - .withNumShards(100) - .withFooter("myFooter") - .withHeader("myHeader") - .withoutValidation(); - - DisplayData displayData = DisplayData.from(write); - - assertThat(displayData, hasDisplayItem("filePrefix", "foo")); - assertThat(displayData, hasDisplayItem("fileSuffix", "bar")); - assertThat(displayData, hasDisplayItem("fileHeader", "myHeader")); - assertThat(displayData, hasDisplayItem("fileFooter", "myFooter")); - assertThat(displayData, hasDisplayItem("shardNameTemplate", "-SS-of-NN-")); - assertThat(displayData, hasDisplayItem("numShards", 100)); - assertThat(displayData, hasDisplayItem("validation", false)); - } - - @Test - public void testPrimitiveWriteDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - - TextIO.Write.Bound write = TextIO.Write.to("foobar"); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(write); - assertThat("TextIO.Write should include the file prefix in its primitive display data", - displayData, hasItem(hasDisplayItem(hasValue(startsWith("foobar"))))); - } - - @Test - public void testPrimitiveReadDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - - TextIO.Read.Bound read = TextIO.Read - .from("foobar") - .withoutValidation(); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(read); - assertThat("TextIO.Read should include the file prefix in its primitive display data", - displayData, - hasItem(hasDisplayItem(DisplayDataMatchers.hasValue(startsWith("foobar"))))); - } - - @Test - public void testUnsupportedFilePattern() throws IOException { - // Windows doesn't like resolving paths with * in them. - String filename = tempFolder.resolve("output@5").toString(); - - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(Arrays.asList(LINES_ARRAY)) - .withCoder(StringUtf8Coder.of())); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Output name components are not allowed to contain"); - input.apply(TextIO.Write.to(filename)); - } - - /** - * This tests a few corner cases that should not crash. - */ - @Test - public void testGoodWildcards() throws Exception { - TestDataflowPipelineOptions options = buildTestPipelineOptions(); - options.setGcsUtil(buildMockGcsUtil()); - - Pipeline pipeline = Pipeline.create(options); - - applyRead(pipeline, "gs://bucket/foo"); - applyRead(pipeline, "gs://bucket/foo/"); - applyRead(pipeline, "gs://bucket/foo/*"); - applyRead(pipeline, "gs://bucket/foo/?"); - applyRead(pipeline, "gs://bucket/foo/[0-9]"); - applyRead(pipeline, "gs://bucket/foo/*baz*"); - applyRead(pipeline, "gs://bucket/foo/*baz?"); - applyRead(pipeline, "gs://bucket/foo/[0-9]baz?"); - applyRead(pipeline, "gs://bucket/foo/baz/*"); - applyRead(pipeline, "gs://bucket/foo/baz/*wonka*"); - applyRead(pipeline, "gs://bucket/foo/*baz/wonka*"); - applyRead(pipeline, "gs://bucket/foo*/baz"); - applyRead(pipeline, "gs://bucket/foo?/baz"); - applyRead(pipeline, "gs://bucket/foo[0-9]/baz"); - - // Check that running doesn't fail. - pipeline.run(); - } - - private void applyRead(Pipeline pipeline, String path) { - pipeline.apply("Read(" + path + ")", TextIO.Read.from(path)); - } - - /** - * Recursive wildcards are not supported. - * This tests "**". - */ - @Test - public void testBadWildcardRecursive() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - // Check that applying does fail. - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("wildcard"); - - pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); - } - - /** Options for testing. */ - public interface RuntimeTestOptions extends PipelineOptions { - ValueProvider getInput(); - void setInput(ValueProvider value); - - ValueProvider getOutput(); - void setOutput(ValueProvider value); - } - - @Test - public void testRuntimeOptionsNotCalledInApply() throws Exception { - Pipeline pipeline = TestPipeline.create(); - RuntimeTestOptions options = PipelineOptionsFactory.as(RuntimeTestOptions.class); - pipeline - .apply(TextIO.Read.from(options.getInput()).withoutValidation()) - .apply(TextIO.Write.to(options.getOutput()).withoutValidation()); - } - - @Test - public void testReadWithoutValidationFlag() throws Exception { - TextIO.Read.Bound read = TextIO.Read.from("gs://bucket/foo*/baz"); - assertTrue(read.needsValidation()); - assertFalse(read.withoutValidation().needsValidation()); - } - - @Test - public void testWriteWithoutValidationFlag() throws Exception { - TextIO.Write.Bound write = TextIO.Write.to("gs://bucket/foo/baz"); - assertTrue(write.needsValidation()); - assertFalse(write.withoutValidation().needsValidation()); - } - - @Test - public void testCompressionTypeIsSet() throws Exception { - TextIO.Read.Bound read = TextIO.Read.from("gs://bucket/test"); - assertEquals(AUTO, read.getCompressionType()); - read = TextIO.Read.from("gs://bucket/test").withCompressionType(GZIP); - assertEquals(GZIP, read.getCompressionType()); - } - - /** - * Helper that writes the given lines (adding a newline in between) to a stream, then closes the - * stream. - */ - private static void writeToStreamAndClose(String[] lines, OutputStream outputStream) { - try (PrintStream writer = new PrintStream(outputStream)) { - for (String line : lines) { - writer.println(line); - } - } - } - - /** - * Helper method that runs TextIO.Read.from(filename).withCompressionType(compressionType) - * and asserts that the results match the given expected output. - */ - private static void assertReadingCompressedFileMatchesExpected( - File file, CompressionType compressionType, String[] expected) { - Pipeline p = TestPipeline.create(); - TextIO.Read.Bound read = - TextIO.Read.from(file.getPath()).withCompressionType(compressionType); - PCollection output = p.apply(read); - - DataflowAssert.that(output).containsInAnyOrder(expected); - p.run(); - } - - /** Helper to make an array of compressible strings. Returns ["word"+i] for i in range(0,n). */ - private static String[] makeLines(int n) { - String[] ret = new String[n]; - for (int i = 0; i < n; ++i) { - ret[i] = "word" + i; - } - return ret; - } - - /** Tests reading from a small, gzipped file with no .gz extension but GZIP compression set. */ - @Test - public void testSmallCompressedGzipReadNoExtension() throws Exception { - File smallGzNoExtension = writeToFile(TINY, "tiny_gz_no_extension", GZIP); - assertReadingCompressedFileMatchesExpected(smallGzNoExtension, GZIP, TINY); - } - - /** - * Tests reading from a small, uncompressed file with .gz extension. - * This must work in AUTO or GZIP modes. This is needed because some network file systems / HTTP - * clients will transparently decompress gzipped content. - */ - @Test - public void testSmallCompressedGzipReadActuallyUncompressed() throws Exception { - File smallGzNotCompressed = - writeToFile(TINY, "tiny_uncompressed.gz", UNCOMPRESSED); - // Should work with GZIP compression set. - assertReadingCompressedFileMatchesExpected(smallGzNotCompressed, GZIP, TINY); - // Should also work with AUTO mode set. - assertReadingCompressedFileMatchesExpected(smallGzNotCompressed, AUTO, TINY); - } - - /** Tests reading from a small, bzip2ed file with no .bz2 extension but BZIP2 compression set. */ - @Test - public void testSmallCompressedBzip2ReadNoExtension() throws Exception { - File smallBz2NoExtension = writeToFile(TINY, "tiny_bz2_no_extension", BZIP2); - assertReadingCompressedFileMatchesExpected(smallBz2NoExtension, BZIP2, TINY); - } - - @Test - public void testTxtRead() throws Exception { - // Files with non-compressed extensions should work in AUTO and UNCOMPRESSED modes. - for (CompressionType type : new CompressionType[] { AUTO, UNCOMPRESSED }) { - assertReadingCompressedFileMatchesExpected(emptyTxt, type, EMPTY); - assertReadingCompressedFileMatchesExpected(tinyTxt, type, TINY); - assertReadingCompressedFileMatchesExpected(largeTxt, type, LARGE); - } - } - - @Test - public void testGzipCompressedRead() throws Exception { - // Files with the right extensions should work in AUTO and GZIP modes. - for (CompressionType type : new CompressionType[] { AUTO, GZIP }) { - assertReadingCompressedFileMatchesExpected(emptyGz, type, EMPTY); - assertReadingCompressedFileMatchesExpected(tinyGz, type, TINY); - assertReadingCompressedFileMatchesExpected(largeGz, type, LARGE); - } - - // Sanity check that we're properly testing compression. - assertThat(largeTxt.length(), greaterThan(largeGz.length())); - - // GZIP files with non-gz extension should work in GZIP mode. - File gzFile = writeToFile(TINY, "tiny_gz_no_extension", GZIP); - assertReadingCompressedFileMatchesExpected(gzFile, GZIP, TINY); - } - - @Test - public void testBzip2CompressedRead() throws Exception { - // Files with the right extensions should work in AUTO and BZIP2 modes. - for (CompressionType type : new CompressionType[] { AUTO, BZIP2 }) { - assertReadingCompressedFileMatchesExpected(emptyBzip2, type, EMPTY); - assertReadingCompressedFileMatchesExpected(tinyBzip2, type, TINY); - assertReadingCompressedFileMatchesExpected(largeBzip2, type, LARGE); - } - - // Sanity check that we're properly testing compression. - assertThat(largeTxt.length(), greaterThan(largeBzip2.length())); - - // BZ2 files with non-bz2 extension should work in BZIP2 mode. - File bz2File = writeToFile(TINY, "tiny_bz2_no_extension", BZIP2); - assertReadingCompressedFileMatchesExpected(bz2File, BZIP2, TINY); - } - - @Test - public void testTextIOGetName() { - assertEquals("TextIO.Read", TextIO.Read.from("somefile").getName()); - assertEquals("TextIO.Write", TextIO.Write.to("somefile").getName()); - assertEquals("ReadMyFile", TextIO.Read.named("ReadMyFile").from("somefile").getName()); - assertEquals("WriteMyFile", TextIO.Write.named("WriteMyFile").to("somefile").getName()); - assertEquals("TextIO.Read", TextIO.Read.from("somefile").toString()); - assertEquals( - "ReadMyFile [TextIO.Read]", TextIO.Read.named("ReadMyFile").from("somefile").toString()); - } - - @Test - public void testProgressEmptyFile() throws IOException { - try (BoundedReader reader = - prepareSource(new byte[0]).createReader(PipelineOptionsFactory.create())) { - // Check preconditions before starting. - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Assert empty - assertFalse(reader.start()); - - // Check postconditions after finishing - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - public void testProgressTextFile() throws IOException { - String file = "line1\nline2\nline3"; - try (BoundedReader reader = - prepareSource(file.getBytes()).createReader(PipelineOptionsFactory.create())) { - // Check preconditions before starting - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Line 1 - assertTrue(reader.start()); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Line 2 - assertTrue(reader.advance()); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Line 3 - assertTrue(reader.advance()); - assertEquals(2, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - - // Check postconditions after finishing - assertFalse(reader.advance()); - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(3, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - public void testProgressAfterSplitting() throws IOException { - String file = "line1\nline2\nline3"; - BoundedSource source = prepareSource(file.getBytes()); - BoundedSource remainder; - - // Create the remainder, verifying properties pre- and post-splitting. - try (BoundedReader readerOrig = source.createReader(PipelineOptionsFactory.create())) { - // Preconditions. - assertEquals(0.0, readerOrig.getFractionConsumed(), 1e-6); - assertEquals(0, readerOrig.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, readerOrig.getSplitPointsRemaining()); - - // First record, before splitting. - assertTrue(readerOrig.start()); - assertEquals(0, readerOrig.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, readerOrig.getSplitPointsRemaining()); - - // Split. 0.1 is in line1, so should now be able to detect last record. - remainder = readerOrig.splitAtFraction(0.1); - System.err.println(readerOrig.getCurrentSource()); - assertNotNull(remainder); - - // First record, after splitting. - assertEquals(0, readerOrig.getSplitPointsConsumed()); - assertEquals(1, readerOrig.getSplitPointsRemaining()); - - // Finish and postconditions. - assertFalse(readerOrig.advance()); - assertEquals(1.0, readerOrig.getFractionConsumed(), 1e-6); - assertEquals(1, readerOrig.getSplitPointsConsumed()); - assertEquals(0, readerOrig.getSplitPointsRemaining()); - } - - // Check the properties of the remainder. - try (BoundedReader reader = remainder.createReader(PipelineOptionsFactory.create())) { - // Preconditions. - assertEquals(0.0, reader.getFractionConsumed(), 1e-6); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // First record should be line 2. - assertTrue(reader.start()); - assertEquals(0, reader.getSplitPointsConsumed()); - assertEquals(BoundedReader.SPLIT_POINTS_UNKNOWN, reader.getSplitPointsRemaining()); - - // Second record is line 3 - assertTrue(reader.advance()); - assertEquals(1, reader.getSplitPointsConsumed()); - assertEquals(1, reader.getSplitPointsRemaining()); - - // Check postconditions after finishing - assertFalse(reader.advance()); - assertEquals(1.0, reader.getFractionConsumed(), 1e-6); - assertEquals(2, reader.getSplitPointsConsumed()); - assertEquals(0, reader.getSplitPointsRemaining()); - } - } - - @Test - public void testReadEmptyLines() throws Exception { - runTestReadWithData("\n\n\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("", "", "")); - } - - @Test - public void testReadFileWithLineFeedDelimiter() throws Exception { - runTestReadWithData("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnDelimiter() throws Exception { - runTestReadWithData("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnAndLineFeedDelimiter() throws Exception { - runTestReadWithData("asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithMixedDelimiters() throws Exception { - runTestReadWithData("asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { - runTestReadWithData("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() throws Exception { - runTestReadWithData("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() - throws Exception { - runTestReadWithData("asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - @Test - public void testReadFileWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { - runTestReadWithData("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8), - ImmutableList.of("asdf", "hjkl", "xyz")); - } - - private void runTestReadWithData(byte[] data, List expectedResults) throws Exception { - TextSource source = prepareSource(data); - List actual = SourceTestUtils.readFromSource(source, PipelineOptionsFactory.create()); - assertThat(actual, containsInAnyOrder(new ArrayList<>(expectedResults).toArray(new String[0]))); - } - - @Test - public void testSplittingSourceWithEmptyLines() throws Exception { - TextSource source = prepareSource("\n\n\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithLineFeedDelimiter() throws Exception { - TextSource source = prepareSource("asdf\nhjkl\nxyz\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnDelimiter() throws Exception { - TextSource source = prepareSource("asdf\rhjkl\rxyz\r".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiter() throws Exception { - TextSource source = prepareSource( - "asdf\r\nhjkl\r\nxyz\r\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithMixedDelimiters() throws Exception { - TextSource source = prepareSource( - "asdf\rhjkl\r\nxyz\n".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithLineFeedDelimiterAndNonEmptyBytesAtEnd() throws Exception { - TextSource source = prepareSource("asdf\nhjkl\nxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnDelimiterAndNonEmptyBytesAtEnd() - throws Exception { - TextSource source = prepareSource("asdf\rhjkl\rxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithCarriageReturnAndLineFeedDelimiterAndNonEmptyBytesAtEnd() - throws Exception { - TextSource source = prepareSource( - "asdf\r\nhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - @Test - public void testSplittingSourceWithMixedDelimitersAndNonEmptyBytesAtEnd() throws Exception { - TextSource source = prepareSource("asdf\rhjkl\r\nxyz".getBytes(StandardCharsets.UTF_8)); - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } - - private TextSource prepareSource(byte[] data) throws IOException { - Path path = Files.createTempFile(tempFolder, "tempfile", "ext"); - Files.write(path, data); - return new TextSource<>(path.toString(), StringUtf8Coder.of()); - } - - @Test - public void testInitialSplitIntoBundlesAutoModeTxt() throws Exception { - PipelineOptions options = TestPipeline.testingPipelineOptions(); - long desiredBundleSize = 1000; - - // Sanity check: file is at least 2 bundles long. - assertThat(largeTxt.length(), greaterThan(2 * desiredBundleSize)); - - FileBasedSource source = TextIO.Read.from(largeTxt.getPath()).getSource(); - List> splits = - source.splitIntoBundles(desiredBundleSize, options); - - // At least 2 splits and they are equal to reading the whole file. - assertThat(splits, hasSize(greaterThan(1))); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - } - - @Test - public void testInitialSplitIntoBundlesAutoModeGz() throws Exception { - long desiredBundleSize = 1000; - PipelineOptions options = TestPipeline.testingPipelineOptions(); - - // Sanity check: file is at least 2 bundles long. - assertThat(largeGz.length(), greaterThan(2 * desiredBundleSize)); - - FileBasedSource source = TextIO.Read.from(largeGz.getPath()).getSource(); - List> splits = - source.splitIntoBundles(desiredBundleSize, options); - - // Exactly 1 split, even in AUTO mode, since it is a gzip file. - assertThat(splits, hasSize(equalTo(1))); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - } - - @Test - public void testInitialSplitIntoBundlesGzipModeTxt() throws Exception { - PipelineOptions options = TestPipeline.testingPipelineOptions(); - long desiredBundleSize = 1000; - - // Sanity check: file is at least 2 bundles long. - assertThat(largeTxt.length(), greaterThan(2 * desiredBundleSize)); - - FileBasedSource source = - TextIO.Read.from(largeTxt.getPath()).withCompressionType(GZIP).getSource(); - List> splits = - source.splitIntoBundles(desiredBundleSize, options); - - // Exactly 1 split, even though splittable text file, since using GZIP mode. - assertThat(splits, hasSize(equalTo(1))); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - } - - @Test - public void testInitialSplitIntoBundlesGzipModeGz() throws Exception { - PipelineOptions options = TestPipeline.testingPipelineOptions(); - long desiredBundleSize = 1000; - - // Sanity check: file is at least 2 bundles long. - assertThat(largeGz.length(), greaterThan(2 * desiredBundleSize)); - - FileBasedSource source = - TextIO.Read.from(largeGz.getPath()).withCompressionType(GZIP).getSource(); - List> splits = - source.splitIntoBundles(desiredBundleSize, options); - - // Exactly 1 split using .gz extension and using GZIP mode. - assertThat(splits, hasSize(equalTo(1))); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java deleted file mode 100644 index 9023ad0387..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/WriteTest.java +++ /dev/null @@ -1,541 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.Sink.WriteOperation; -import com.google.cloud.dataflow.sdk.io.Sink.Writer; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest.TestPipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.MoreObjects; -import com.google.common.base.Optional; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Tests for the Write PTransform. - */ -@RunWith(JUnit4.class) -public class WriteTest { - // Static store that can be accessed within the writer - private static List sinkContents = new ArrayList<>(); - // Static count of output shards - private static AtomicInteger numShards = new AtomicInteger(0); - // Static counts of the number of records per shard. - private static List recordsPerShard = new ArrayList<>(); - - private static final MapElements IDENTITY_MAP = - MapElements.via(new SimpleFunction() { - @Override - public String apply(String input) { - return input; - } - }); - - private static class WindowAndReshuffle extends PTransform, PCollection> { - private final Window.Bound window; - public WindowAndReshuffle(Window.Bound window) { - this.window = window; - } - - private static class AddArbitraryKey extends DoFn> { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(KV.of(ThreadLocalRandom.current().nextInt(), c.element())); - } - } - - private static class RemoveArbitraryKey extends DoFn>, T> { - @Override - public void processElement(ProcessContext c) throws Exception { - for (T s : c.element().getValue()) { - c.output(s); - } - } - } - - @Override - public PCollection apply(PCollection input) { - return input - .apply(window) - .apply(ParDo.of(new AddArbitraryKey())) - .apply(GroupByKey.create()) - .apply(ParDo.of(new RemoveArbitraryKey())); - } - } - - /** - * Test a Write transform with a PCollection of elements. - */ - @Test - public void testWrite() { - List inputs = Arrays.asList("Critical canary", "Apprehensive eagle", - "Intimidating pigeon", "Pedantic gull", "Frisky finch"); - runWrite(inputs, IDENTITY_MAP); - } - - /** - * Test that Write with an empty input still produces one shard. - */ - @Test - public void testEmptyWrite() { - runWrite(Collections.emptyList(), IDENTITY_MAP); - // Note we did not request a sharded write, so runWrite will not validate the number of shards. - assertThat(numShards.intValue(), greaterThan(0)); - } - - /** - * Test that Write with a configured number of shards produces the desired number of shards even - * when there are many elements. - */ - @Test - public void testShardedWrite() { - runShardedWrite( - Arrays.asList("one", "two", "three", "four", "five", "six"), - IDENTITY_MAP, - Optional.of(1)); - } - - /** - * Test that Write with a configured number of shards produces the desired number of shards even - * when there are too few elements. - */ - @Test - public void testExpandShardedWrite() { - runShardedWrite( - Arrays.asList("one", "two", "three", "four", "five", "six"), - IDENTITY_MAP, - Optional.of(20)); - } - - /** - * Tests that a Write can balance many elements. - */ - @Test - public void testShardedWriteBalanced() { - int numElements = 1000; - List inputs = new ArrayList<>(numElements); - for (int i = 0; i < numElements; ++i) { - inputs.add(String.format("elt%04d", i)); - } - - runShardedWrite( - inputs, - new WindowAndReshuffle<>( - Window.into(Sessions.withGapDuration(Duration.millis(1)))), - Optional.of(10)); - - // Check that both the min and max number of results per shard are close to the expected. - int min = Integer.MAX_VALUE; - int max = Integer.MIN_VALUE; - for (Integer i : recordsPerShard) { - min = Math.min(min, i); - max = Math.max(max, i); - } - assertThat((double) min, Matchers.greaterThanOrEqualTo(max * 0.9)); - } - - /** - * Test a Write transform with an empty PCollection. - */ - @Test - public void testWriteWithEmptyPCollection() { - List inputs = new ArrayList<>(); - runWrite(inputs, IDENTITY_MAP); - } - - /** - * Test a Write with a windowed PCollection. - */ - @Test - public void testWriteWindowed() { - List inputs = Arrays.asList("Critical canary", "Apprehensive eagle", - "Intimidating pigeon", "Pedantic gull", "Frisky finch"); - runWrite( - inputs, new WindowAndReshuffle<>(Window.into(FixedWindows.of(Duration.millis(2))))); - } - - /** - * Test a Write with sessions. - */ - @Test - public void testWriteWithSessions() { - List inputs = Arrays.asList("Critical canary", "Apprehensive eagle", - "Intimidating pigeon", "Pedantic gull", "Frisky finch"); - - runWrite( - inputs, - new WindowAndReshuffle<>( - Window.into(Sessions.withGapDuration(Duration.millis(1))))); - } - - @Test - public void testBuildWrite() { - Sink sink = new TestSink() {}; - Write.Bound write = Write.to(sink).withNumShards(3); - assertEquals(3, write.getNumShards()); - assertThat(write.getSink(), is(sink)); - - Write.Bound write2 = write.withNumShards(7); - assertEquals(7, write2.getNumShards()); - assertThat(write2.getSink(), is(sink)); - // original unchanged - assertEquals(3, write.getNumShards()); - } - - @Test - public void testDisplayData() { - TestSink sink = new TestSink() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - Write.Bound write = Write.to(sink); - DisplayData displayData = DisplayData.from(write); - - assertThat(displayData, hasDisplayItem("sink", sink.getClass())); - assertThat(displayData, includesDisplayDataFrom(sink)); - } - - @Test - public void testShardedDisplayData() { - TestSink sink = new TestSink() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - Write.Bound write = Write.to(sink).withNumShards(1); - DisplayData displayData = DisplayData.from(write); - assertThat(displayData, hasDisplayItem("sink", sink.getClass())); - assertThat(displayData, includesDisplayDataFrom(sink)); - assertThat(displayData, hasDisplayItem("numShards", 1)); - } - - /** - * Performs a Write transform and verifies the Write transform calls the appropriate methods on - * a test sink in the correct order, as well as verifies that the elements of a PCollection are - * written to the sink. - */ - private static void runWrite( - List inputs, PTransform, PCollection> transform) { - runShardedWrite(inputs, transform, Optional.absent()); - } - - /** - * Performs a Write transform with the desired number of shards. Verifies the Write transform - * calls the appropriate methods on a test sink in the correct order, as well as verifies that - * the elements of a PCollection are written to the sink. If numConfiguredShards is not null, also - * verifies that the output number of shards is correct. - */ - private static void runShardedWrite( - List inputs, PTransform, PCollection> transform, - Optional numConfiguredShards) { - // Flag to validate that the pipeline options are passed to the Sink - String[] args = {"--testFlag=test_value"}; - PipelineOptions options = PipelineOptionsFactory.fromArgs(args).as(WriteOptions.class); - Pipeline p = Pipeline.create(options); - - // Clear the sink's contents. - sinkContents.clear(); - // Reset the number of shards produced. - numShards.set(0); - // Reset the number of records in each shard. - recordsPerShard.clear(); - - // Prepare timestamps for the elements. - List timestamps = new ArrayList<>(); - for (long i = 0; i < inputs.size(); i++) { - timestamps.add(i + 1); - } - - TestSink sink = new TestSink(); - Write.Bound write = Write.to(sink); - if (numConfiguredShards.isPresent()) { - write = write.withNumShards(numConfiguredShards.get()); - } - p.apply(Create.timestamped(inputs, timestamps).withCoder(StringUtf8Coder.of())) - .apply(transform) - .apply(write); - - p.run(); - assertThat(sinkContents, containsInAnyOrder(inputs.toArray())); - assertTrue(sink.hasCorrectState()); - if (numConfiguredShards.isPresent()) { - assertEquals(numConfiguredShards.get().intValue(), numShards.intValue()); - assertEquals(numConfiguredShards.get().intValue(), recordsPerShard.size()); - } - } - - // Test sink and associated write operation and writer. TestSink, TestWriteOperation, and - // TestWriter each verify that the sequence of method calls is consistent with the specification - // of the Write PTransform. - private static class TestSink extends Sink { - private boolean createCalled = false; - private boolean validateCalled = false; - - @Override - public WriteOperation createWriteOperation(PipelineOptions options) { - assertTrue(validateCalled); - assertTestFlagPresent(options); - createCalled = true; - return new TestSinkWriteOperation(this); - } - - @Override - public void validate(PipelineOptions options) { - assertTestFlagPresent(options); - validateCalled = true; - } - - private void assertTestFlagPresent(PipelineOptions options) { - assertEquals("test_value", options.as(WriteOptions.class).getTestFlag()); - } - - private boolean hasCorrectState() { - return validateCalled && createCalled; - } - - /** - * Implementation of equals() that indicates all test sinks are equal. - */ - @Override - public boolean equals(Object other) { - return (other instanceof TestSink); - } - - @Override - public int hashCode() { - return Objects.hash(getClass()); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("createCalled", createCalled) - .add("validateCalled", validateCalled) - .toString(); - } - } - - private static class TestSinkWriteOperation extends WriteOperation { - private enum State { - INITIAL, - INITIALIZED, - FINALIZED - } - - // Must be static in case the WriteOperation is serialized before the its coder is obtained. - // If this occurs, the value will be modified but not reflected in the WriteOperation that is - // executed by the runner, and the finalize method will fail. - private static volatile boolean coderCalled = false; - - private State state = State.INITIAL; - - private final TestSink sink; - private final UUID id = UUID.randomUUID(); - - public TestSinkWriteOperation(TestSink sink) { - this.sink = sink; - } - - @Override - public TestSink getSink() { - return sink; - } - - @Override - public void initialize(PipelineOptions options) throws Exception { - assertEquals("test_value", options.as(WriteOptions.class).getTestFlag()); - assertThat(state, anyOf(equalTo(State.INITIAL), equalTo(State.INITIALIZED))); - state = State.INITIALIZED; - } - - @Override - public void finalize(Iterable bundleResults, PipelineOptions options) - throws Exception { - assertEquals("test_value", options.as(WriteOptions.class).getTestFlag()); - assertEquals(State.INITIALIZED, state); - // The coder for the test writer results should've been called. - assertTrue(coderCalled); - Set idSet = new HashSet<>(); - int resultCount = 0; - state = State.FINALIZED; - for (TestWriterResult result : bundleResults) { - resultCount += 1; - idSet.add(result.uId); - // Add the elements that were written to the sink's contents. - sinkContents.addAll(result.elementsWritten); - recordsPerShard.add(result.elementsWritten.size()); - } - // Each result came from a unique id. - assertEquals(resultCount, idSet.size()); - } - - @Override - public Writer createWriter(PipelineOptions options) { - return new TestSinkWriter(this); - } - - @Override - public Coder getWriterResultCoder() { - coderCalled = true; - return SerializableCoder.of(TestWriterResult.class); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("id", id) - .add("sink", sink) - .add("state", state) - .add("coderCalled", coderCalled) - .toString(); - } - - /** - * Implementation of equals() that does not depend on the state of the write operation, - * but only its specification. In general, write operations will have interesting - * specifications, but for a {@link TestSinkWriteOperation}, it is not the case. Instead, - * a unique identifier (that is serialized along with it) is used to simulate such a - * specification. - */ - @Override - public boolean equals(Object other) { - if (!(other instanceof TestSinkWriteOperation)) { - return false; - } - TestSinkWriteOperation otherOperation = (TestSinkWriteOperation) other; - return sink.equals(otherOperation.sink) - && id.equals(otherOperation.id); - } - - @Override - public int hashCode() { - return Objects.hash(id, sink); - } - } - - private static class TestWriterResult implements Serializable { - String uId; - List elementsWritten; - - public TestWriterResult(String uId, List elementsWritten) { - this.uId = uId; - this.elementsWritten = elementsWritten; - } - } - - private static class TestSinkWriter extends Writer { - private enum State { - INITIAL, - OPENED, - WRITING, - CLOSED - } - - private State state = State.INITIAL; - private List elementsWritten = new ArrayList<>(); - private String uId; - - private final TestSinkWriteOperation writeOperation; - - public TestSinkWriter(TestSinkWriteOperation writeOperation) { - this.writeOperation = writeOperation; - } - - @Override - public TestSinkWriteOperation getWriteOperation() { - return writeOperation; - } - - @Override - public void open(String uId) throws Exception { - numShards.incrementAndGet(); - this.uId = uId; - assertEquals(State.INITIAL, state); - state = State.OPENED; - } - - @Override - public void write(String value) throws Exception { - assertThat(state, anyOf(equalTo(State.OPENED), equalTo(State.WRITING))); - state = State.WRITING; - elementsWritten.add(value); - } - - @Override - public TestWriterResult close() throws Exception { - assertThat(state, anyOf(equalTo(State.OPENED), equalTo(State.WRITING))); - state = State.CLOSED; - return new TestWriterResult(uId, elementsWritten); - } - } - - /** - * Options for test, exposed for PipelineOptionsFactory. - */ - public interface WriteOptions extends TestPipelineOptions { - @Description("Test flag and value") - String getTestFlag(); - void setTestFlag(String value); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java deleted file mode 100644 index 9cf1ad1245..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSinkTest.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.cloud.dataflow.sdk.io.XmlSink.XmlWriteOperation; -import com.google.cloud.dataflow.sdk.io.XmlSink.XmlWriter; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.common.collect.Lists; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.nio.channels.WritableByteChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * Tests for XmlSink. - */ -@RunWith(JUnit4.class) -public class XmlSinkTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private Class testClass = Bird.class; - private String testRootElement = "testElement"; - private String testFilePrefix = "testPrefix"; - - /** - * An XmlWriter correctly writes objects as Xml elements with an enclosing root element. - */ - @Test - public void testXmlWriter() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - XmlWriteOperation writeOp = - XmlSink.writeOf(Bird.class, "birds", testFilePrefix).createWriteOperation(options); - XmlWriter writer = writeOp.createWriter(options); - - List bundle = - Lists.newArrayList(new Bird("bemused", "robin"), new Bird("evasive", "goose")); - List lines = Arrays.asList("", "", "robin", - "bemused", "", "", "goose", - "evasive", "", ""); - runTestWrite(writer, bundle, lines); - } - - /** - * Builder methods correctly initialize an XML Sink. - */ - @Test - public void testBuildXmlSink() { - XmlSink.Bound sink = - XmlSink.write() - .toFilenamePrefix(testFilePrefix) - .ofRecordClass(testClass) - .withRootElement(testRootElement); - assertEquals(testClass, sink.classToBind); - assertEquals(testRootElement, sink.rootElementName); - assertEquals(testFilePrefix, sink.baseOutputFilename.get()); - } - - /** - * Alternate builder method correctly initializes an XML Sink. - */ - @Test - public void testBuildXmlSinkDirect() { - XmlSink.Bound sink = - XmlSink.writeOf(Bird.class, testRootElement, testFilePrefix); - assertEquals(testClass, sink.classToBind); - assertEquals(testRootElement, sink.rootElementName); - assertEquals(testFilePrefix, sink.baseOutputFilename.get()); - } - - /** - * Validation ensures no fields are missing. - */ - @Test - public void testValidateXmlSinkMissingFields() { - XmlSink.Bound sink; - sink = XmlSink.writeOf(null, testRootElement, testFilePrefix); - validateAndFailIfSucceeds(sink, NullPointerException.class); - sink = XmlSink.writeOf(testClass, null, testFilePrefix); - validateAndFailIfSucceeds(sink, NullPointerException.class); - sink = XmlSink.writeOf(testClass, testRootElement, null); - validateAndFailIfSucceeds(sink, NullPointerException.class); - } - - /** - * Call validate and fail if validation does not throw the expected exception. - */ - private void validateAndFailIfSucceeds( - XmlSink.Bound sink, Class expected) { - thrown.expect(expected); - PipelineOptions options = PipelineOptionsFactory.create(); - sink.validate(options); - } - - /** - * An XML Sink correctly creates an XmlWriteOperation. - */ - @Test - public void testCreateWriteOperations() { - PipelineOptions options = PipelineOptionsFactory.create(); - XmlSink.Bound sink = - XmlSink.writeOf(testClass, testRootElement, testFilePrefix); - XmlWriteOperation writeOp = sink.createWriteOperation(options); - assertEquals(testClass, writeOp.getSink().classToBind); - assertEquals(testFilePrefix, writeOp.getSink().baseOutputFilename.get()); - assertEquals(testRootElement, writeOp.getSink().rootElementName); - assertEquals(XmlSink.XML_EXTENSION, writeOp.getSink().extension); - assertEquals(testFilePrefix, writeOp.baseTemporaryFilename.get()); - } - - /** - * An XmlWriteOperation correctly creates an XmlWriter. - */ - @Test - public void testCreateWriter() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - XmlWriteOperation writeOp = - XmlSink.writeOf(testClass, testRootElement, testFilePrefix) - .createWriteOperation(options); - XmlWriter writer = writeOp.createWriter(options); - assertEquals(testFilePrefix, writer.getWriteOperation().baseTemporaryFilename.get()); - assertEquals(testRootElement, writer.getWriteOperation().getSink().rootElementName); - assertNotNull(writer.marshaller); - } - - @Test - public void testDisplayData() { - XmlSink.Bound sink = XmlSink.write() - .toFilenamePrefix("foobar") - .withRootElement("bird") - .ofRecordClass(Integer.class); - - DisplayData displayData = DisplayData.from(sink); - - assertThat(displayData, hasDisplayItem("fileNamePattern", "foobar-SSSSS-of-NNNNN.xml")); - assertThat(displayData, hasDisplayItem("rootElement", "bird")); - assertThat(displayData, hasDisplayItem("recordClass", Integer.class)); - } - - /** - * Write a bundle with an XmlWriter and verify the output is expected. - */ - private void runTestWrite(XmlWriter writer, List bundle, List expected) - throws Exception { - File tmpFile = tmpFolder.newFile("foo.txt"); - try (FileOutputStream fileOutputStream = new FileOutputStream(tmpFile)) { - writeBundle(writer, bundle, fileOutputStream.getChannel()); - } - List lines = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader(new FileReader(tmpFile))) { - for (;;) { - String line = reader.readLine(); - if (line == null) { - break; - } - line = line.trim(); - if (line.length() > 0) { - lines.add(line); - } - } - assertEquals(expected, lines); - } - } - - /** - * Write a bundle with an XmlWriter. - */ - private void writeBundle(XmlWriter writer, List elements, WritableByteChannel channel) - throws Exception { - writer.prepareWrite(channel); - writer.writeHeader(); - for (T elem : elements) { - writer.write(elem); - } - writer.writeFooter(); - } - - /** - * Test JAXB annotated class. - */ - @SuppressWarnings("unused") - @XmlRootElement(name = "bird") - @XmlType(propOrder = {"name", "adjective"}) - private static final class Bird { - private String name; - private String adjective; - - @XmlElement(name = "species") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAdjective() { - return adjective; - } - - public void setAdjective(String adjective) { - this.adjective = adjective; - } - - public Bird() {} - - public Bird(String adjective, String name) { - this.adjective = adjective; - this.name = name; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java deleted file mode 100644 index cfc5b23d49..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/XmlSourceTest.java +++ /dev/null @@ -1,854 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io; - -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionExhaustive; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionFails; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static org.hamcrest.Matchers.both; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.Source.Reader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.apache.avro.reflect.ReflectData; -import org.hamcrest.Matchers; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Tests XmlSource. - */ -@RunWith(JUnit4.class) -public class XmlSourceTest { - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Rule - public ExpectedException exception = ExpectedException.none(); - - String tinyXML = - "ThomasHenry" - + "James"; - - String xmlWithMultiByteElementName = - "<දුම්රියන්><දුම්රිය>Thomas<දුම්රිය>Henry" - + "<දුම්රිය>James"; - - String xmlWithMultiByteChars = - "Thomas¥Hen¶ry" - + "Jamßes"; - - String trainXML = - "" - + "Thomas1blue" - + "Henry3green" - + "Toby7brown" - + "Gordon4blue" - + "Emily-1red" - + "Percy6green" - + ""; - - String trainXMLWithEmptyTags = - "" - + "" - + "Thomas1blue" - + "Henry3green" - + "" - + "Toby7brown" - + "Gordon4blue" - + "Emily-1red" - + "Percy6green" - + ""; - - String trainXMLWithAttributes = - "" - + "Thomas1blue" - + "Henry3green" - + "Toby7brown" - + "Gordon4blue" - + "Emily-1red" - + "Percy6green" - + ""; - - String trainXMLWithSpaces = - "" - + "Thomas 1blue" - + "Henry3green\n" - + "Toby7 brown " - + "Gordon 4blue\n\t" - + "Emily-1\tred" - + "\nPercy 6 green" - + ""; - - String trainXMLWithAllFeaturesMultiByte = - "<දුම්රියන්>" - + "<දුම්රිය/>" - + "<දුම්රිය size=\"small\"> Thomas¥1blue" - + "" - + "<දුම්රිය size=\"big\">He nry3green" - + "<දුම්රිය size=\"small\">Toby 7br¶own" - + "" - + "<දුම්රිය/>" - + "<දුම්රිය size=\"big\">Gordon4 blue" - + "<දුම්රිය size=\"small\">Emily-1red" - + "<දුම්රිය size=\"small\">Percy6green" - + "" - + ""; - - String trainXMLWithAllFeaturesSingleByte = - "" - + "" - + " Thomas1blue" - + "" - + "He nry3green" - + "Toby 7brown" - + "" - + "" - + "Gordon4 blue" - + "Emily-1red" - + "Percy6green" - + "" - + ""; - - @XmlRootElement - static class Train { - public static final int TRAIN_NUMBER_UNDEFINED = -1; - public String name = null; - public String color = null; - public int number = TRAIN_NUMBER_UNDEFINED; - - @XmlAttribute(name = "size") - public String size = null; - - public Train() {} - - public Train(String name, int number, String color, String size) { - this.name = name; - this.number = number; - this.color = color; - this.size = size; - } - - @Override - public int hashCode() { - int hashCode = 1; - hashCode = 31 * hashCode + (name == null ? 0 : name.hashCode()); - hashCode = 31 * hashCode + number; - hashCode = 31 * hashCode + (color == null ? 0 : name.hashCode()); - hashCode = 31 * hashCode + (size == null ? 0 : name.hashCode()); - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Train)) { - return false; - } - - Train other = (Train) obj; - return (name == null || name.equals(other.name)) && (number == other.number) - && (color == null || color.equals(other.color)) - && (size == null || size.equals(other.size)); - } - - @Override - public String toString() { - String str = "Train["; - boolean first = true; - if (name != null) { - str = str + "name=" + name; - first = false; - } - if (number != Integer.MIN_VALUE) { - if (!first) { - str = str + ","; - } - str = str + "number=" + number; - first = false; - } - if (color != null) { - if (!first) { - str = str + ","; - } - str = str + "color=" + color; - first = false; - } - if (size != null) { - if (!first) { - str = str + ","; - } - str = str + "size=" + size; - } - str = str + "]"; - return str; - } - } - - // Use a non-XML coder as JAXBCoder is not suitable for use as an intermediate coder, as it - // requires the entire stream to behave correctly. - private Coder trainCoder = - AvroCoder.of(Train.class, ReflectData.AllowNull.get().getSchema(Train.class)); - - private List generateRandomTrainList(int size) { - String[] names = {"Thomas", "Henry", "Gordon", "Emily", "Toby", "Percy", "Mavis", "Edward", - "Bertie", "Harold", "Hiro", "Terence", "Salty", "Trevor"}; - int[] numbers = {-1, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - String[] colors = {"red", "blue", "green", "orange", "brown", "black", "white"}; - String[] sizes = {"small", "medium", "big"}; - - Random random = new Random(System.currentTimeMillis()); - - List trains = new ArrayList<>(); - for (int i = 0; i < size; i++) { - trains.add(new Train(names[random.nextInt(names.length - 1)], - numbers[random.nextInt(numbers.length - 1)], colors[random.nextInt(colors.length - 1)], - sizes[random.nextInt(sizes.length - 1)])); - } - - return trains; - } - - private String trainToXMLElement(Train train) { - return "" + train.name + "" - + train.number + "" + train.color + ""; - } - - private File createRandomTrainXML(String fileName, List trains) throws IOException { - File file = tempFolder.newFile(fileName); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { - writer.write(""); - writer.newLine(); - for (Train train : trains) { - String str = trainToXMLElement(train); - writer.write(str); - writer.newLine(); - } - writer.write(""); - writer.newLine(); - } - return file; - } - - private List readEverythingFromReader(Reader reader) throws IOException { - List results = new ArrayList<>(); - for (boolean available = reader.start(); available; available = reader.advance()) { - Train train = reader.getCurrent(); - results.add(train); - } - return results; - } - - @Test - public void testReadXMLTiny() throws IOException { - File file = tempFolder.newFile("trainXMLTiny"); - Files.write(file.toPath(), tinyXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - List expectedResults = ImmutableList.of( - new Train("Thomas", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("Henry", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("James", Train.TRAIN_NUMBER_UNDEFINED, null, null)); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - public void testReadXMLWithMultiByteChars() throws IOException { - File file = tempFolder.newFile("trainXMLTiny"); - Files.write(file.toPath(), xmlWithMultiByteChars.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - List expectedResults = ImmutableList.of( - new Train("Thomas¥", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("Hen¶ry", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("Jamßes", Train.TRAIN_NUMBER_UNDEFINED, null, null)); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - @Ignore( - "Multi-byte characters in XML are not supported because the parser " - + "currently does not correctly report byte offsets") - public void testReadXMLWithMultiByteElementName() throws IOException { - File file = tempFolder.newFile("trainXMLTiny"); - Files.write(file.toPath(), xmlWithMultiByteElementName.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("දුම්රියන්") - .withRecordElement("දුම්රිය") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - List expectedResults = ImmutableList.of( - new Train("Thomas", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("Henry", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("James", Train.TRAIN_NUMBER_UNDEFINED, null, null)); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - public void testSplitWithEmptyBundleAtEnd() throws Exception { - File file = tempFolder.newFile("trainXMLTiny"); - Files.write(file.toPath(), tinyXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(10); - List> splits = source.splitIntoBundles(50, null); - - assertTrue(splits.size() > 2); - - List results = new ArrayList<>(); - for (FileBasedSource split : splits) { - results.addAll(readEverythingFromReader(split.createReader(null))); - } - - List expectedResults = ImmutableList.of( - new Train("Thomas", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("Henry", Train.TRAIN_NUMBER_UNDEFINED, null, null), - new Train("James", Train.TRAIN_NUMBER_UNDEFINED, null, null)); - - assertThat( - trainsToStrings(expectedResults), containsInAnyOrder(trainsToStrings(results).toArray())); - } - - List trainsToStrings(List input) { - List strings = new ArrayList<>(); - for (Object data : input) { - strings.add(data.toString()); - } - return strings; - } - - @Test - public void testReadXMLSmall() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - List expectedResults = - ImmutableList.of(new Train("Thomas", 1, "blue", null), new Train("Henry", 3, "green", null), - new Train("Toby", 7, "brown", null), new Train("Gordon", 4, "blue", null), - new Train("Emily", -1, "red", null), new Train("Percy", 6, "green", null)); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - public void testReadXMLNoRootElement() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRecordElement("train") - .withRecordClass(Train.class); - - exception.expect(NullPointerException.class); - exception.expectMessage( - "rootElement is null. Use builder method withRootElement() to set this."); - readEverythingFromReader(source.createReader(null)); - } - - @Test - public void testReadXMLNoRecordElement() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordClass(Train.class); - - exception.expect(NullPointerException.class); - exception.expectMessage( - "recordElement is null. Use builder method withRecordElement() to set this."); - readEverythingFromReader(source.createReader(null)); - } - - @Test - public void testReadXMLNoRecordClass() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train"); - - exception.expect(NullPointerException.class); - exception.expectMessage( - "recordClass is null. Use builder method withRecordClass() to set this."); - readEverythingFromReader(source.createReader(null)); - } - - @Test - public void testReadXMLIncorrectRootElement() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("something") - .withRecordElement("train") - .withRecordClass(Train.class); - - exception.expectMessage("Unexpected close tag ; expected ."); - readEverythingFromReader(source.createReader(null)); - } - - @Test - public void testReadXMLIncorrectRecordElement() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("something") - .withRecordClass(Train.class); - - assertEquals(readEverythingFromReader(source.createReader(null)), new ArrayList()); - } - - @XmlRootElement - private static class WrongTrainType { - @SuppressWarnings("unused") - public String something; - } - - @Test - public void testReadXMLInvalidRecordClass() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(WrongTrainType.class); - - exception.expect(RuntimeException.class); - - // JAXB internationalizes the error message. So this is all we can match for. - exception.expectMessage(both(containsString("name")).and(Matchers.containsString("something"))); - try (Reader reader = source.createReader(null)) { - - List results = new ArrayList<>(); - for (boolean available = reader.start(); available; available = reader.advance()) { - WrongTrainType train = reader.getCurrent(); - results.add(train); - } - } - } - - @Test - public void testReadXMLNoBundleSize() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class); - - List expectedResults = - ImmutableList.of(new Train("Thomas", 1, "blue", null), new Train("Henry", 3, "green", null), - new Train("Toby", 7, "brown", null), new Train("Gordon", 4, "blue", null), - new Train("Emily", -1, "red", null), new Train("Percy", 6, "green", null)); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - - @Test - public void testReadXMLWithEmptyTags() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXMLWithEmptyTags.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - List expectedResults = ImmutableList.of(new Train("Thomas", 1, "blue", null), - new Train("Henry", 3, "green", null), new Train("Toby", 7, "brown", null), - new Train("Gordon", 4, "blue", null), new Train("Emily", -1, "red", null), - new Train("Percy", 6, "green", null), new Train(), new Train()); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - public void testReadXMLSmallDataflow() throws IOException { - Pipeline p = TestPipeline.create(); - - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXML.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - PCollection output = - p.apply(Read.from(source).named("ReadFileData")).setCoder(trainCoder); - - List expectedResults = - ImmutableList.of(new Train("Thomas", 1, "blue", null), new Train("Henry", 3, "green", null), - new Train("Toby", 7, "brown", null), new Train("Gordon", 4, "blue", null), - new Train("Emily", -1, "red", null), new Train("Percy", 6, "green", null)); - - DataflowAssert.that(output).containsInAnyOrder(expectedResults); - p.run(); - } - - @Test - public void testReadXMLWithAttributes() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXMLWithAttributes.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - List expectedResults = ImmutableList.of(new Train("Thomas", 1, "blue", "small"), - new Train("Henry", 3, "green", "big"), new Train("Toby", 7, "brown", "small"), - new Train("Gordon", 4, "blue", "big"), new Train("Emily", -1, "red", "small"), - new Train("Percy", 6, "green", "small")); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - public void testReadXMLWithWhitespaces() throws IOException { - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXMLWithSpaces.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - List expectedResults = ImmutableList.of(new Train("Thomas ", 1, "blue", null), - new Train("Henry", 3, "green", null), new Train("Toby", 7, " brown ", null), - new Train("Gordon", 4, "blue", null), new Train("Emily", -1, "red", null), - new Train("Percy", 6, "green", null)); - - assertThat( - trainsToStrings(expectedResults), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - public void testReadXMLLarge() throws IOException { - String fileName = "temp.xml"; - List trains = generateRandomTrainList(100); - File file = createRandomTrainXML(fileName, trains); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - - assertThat( - trainsToStrings(trains), - containsInAnyOrder( - trainsToStrings(readEverythingFromReader(source.createReader(null))).toArray())); - } - - @Test - public void testReadXMLLargeDataflow() throws IOException { - String fileName = "temp.xml"; - List trains = generateRandomTrainList(100); - File file = createRandomTrainXML(fileName, trains); - - Pipeline p = TestPipeline.create(); - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - PCollection output = - p.apply(Read.from(source).named("ReadFileData")).setCoder(trainCoder); - - DataflowAssert.that(output).containsInAnyOrder(trains); - p.run(); - } - - @Test - public void testSplitWithEmptyBundles() throws Exception { - String fileName = "temp.xml"; - List trains = generateRandomTrainList(10); - File file = createRandomTrainXML(fileName, trains); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(10); - List> splits = source.splitIntoBundles(100, null); - - assertTrue(splits.size() > 2); - - List results = new ArrayList<>(); - for (FileBasedSource split : splits) { - results.addAll(readEverythingFromReader(split.createReader(null))); - } - - assertThat(trainsToStrings(trains), containsInAnyOrder(trainsToStrings(results).toArray())); - } - - @Test - public void testXMLWithSplits() throws Exception { - String fileName = "temp.xml"; - List trains = generateRandomTrainList(100); - File file = createRandomTrainXML(fileName, trains); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(10); - List> splits = source.splitIntoBundles(256, null); - - // Not a trivial split - assertTrue(splits.size() > 2); - - List results = new ArrayList<>(); - for (FileBasedSource split : splits) { - results.addAll(readEverythingFromReader(split.createReader(null))); - } - assertThat(trainsToStrings(trains), containsInAnyOrder(trainsToStrings(results).toArray())); - } - - @Test - public void testSplitAtFraction() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - String fileName = "temp.xml"; - List trains = generateRandomTrainList(100); - File file = createRandomTrainXML(fileName, trains); - - XmlSource fileSource = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(10); - - List> splits = - fileSource.splitIntoBundles(file.length() / 3, null); - for (BoundedSource splitSource : splits) { - int numItems = readEverythingFromReader(splitSource.createReader(null)).size(); - // Should not split while unstarted. - assertSplitAtFractionFails(splitSource, 0, 0.7, options); - assertSplitAtFractionSucceedsAndConsistent(splitSource, 1, 0.7, options); - assertSplitAtFractionSucceedsAndConsistent(splitSource, 15, 0.7, options); - assertSplitAtFractionFails(splitSource, 0, 0.0, options); - assertSplitAtFractionFails(splitSource, 20, 0.3, options); - assertSplitAtFractionFails(splitSource, numItems, 1.0, options); - - // After reading 100 elements we will be approximately at position - // 0.99 * (endOffset - startOffset) hence trying to split at fraction 0.9 will be - // unsuccessful. - assertSplitAtFractionFails(splitSource, numItems, 0.9, options); - - // Following passes since we can always find a fraction that is extremely close to 1 such that - // the position suggested by the fraction will be larger than the position the reader is at - // after reading "items - 1" elements. - // This also passes for "numItemsToReadBeforeSplit = items" if the position at suggested - // fraction is larger than the position the reader is at after reading all "items" elements - // (i.e., the start position of the last element). This is true for most cases but will not - // be true if reader position is only one less than the end position. (i.e., the last element - // of the bundle start at the last byte that belongs to the bundle). - assertSplitAtFractionSucceedsAndConsistent(splitSource, numItems - 1, 0.999, options); - } - } - - @Test - public void testSplitAtFractionExhaustiveSingleByte() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXMLWithAllFeaturesSingleByte.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class); - assertSplitAtFractionExhaustive(source, options); - } - - @Test - @Ignore( - "Multi-byte characters in XML are not supported because the parser " - + "currently does not correctly report byte offsets") - public void testSplitAtFractionExhaustiveMultiByte() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - File file = tempFolder.newFile("trainXMLSmall"); - Files.write(file.toPath(), trainXMLWithAllFeaturesMultiByte.getBytes(StandardCharsets.UTF_8)); - - XmlSource source = - XmlSource.from(file.toPath().toString()) - .withRootElement("දුම්රියන්") - .withRecordElement("දුම්රිය") - .withRecordClass(Train.class); - assertSplitAtFractionExhaustive(source, options); - } - - @Test - public void testReadXMLFilePattern() throws IOException { - List trains1 = generateRandomTrainList(20); - File file = createRandomTrainXML("temp1.xml", trains1); - List trains2 = generateRandomTrainList(10); - createRandomTrainXML("temp2.xml", trains2); - List trains3 = generateRandomTrainList(15); - createRandomTrainXML("temp3.xml", trains3); - generateRandomTrainList(8); - createRandomTrainXML("otherfile.xml", trains1); - - Pipeline p = TestPipeline.create(); - - XmlSource source = XmlSource.from(file.getParent() + "/" - + "temp*.xml") - .withRootElement("trains") - .withRecordElement("train") - .withRecordClass(Train.class) - .withMinBundleSize(1024); - PCollection output = p.apply(Read.from(source).named("ReadFileData")) - .setCoder(trainCoder); - - List expectedResults = new ArrayList<>(); - expectedResults.addAll(trains1); - expectedResults.addAll(trains2); - expectedResults.addAll(trains3); - - DataflowAssert.that(output).containsInAnyOrder(expectedResults); - p.run(); - } - - @Test - public void testDisplayData() { - - - XmlSource source = XmlSource - .from("foo.xml") - .withRootElement("bird") - .withRecordElement("cat") - .withMinBundleSize(1234) - .withRecordClass(Integer.class); - DisplayData displayData = DisplayData.from(source); - - assertThat(displayData, hasDisplayItem("filePattern", "foo.xml")); - assertThat(displayData, hasDisplayItem("rootElement", "bird")); - assertThat(displayData, hasDisplayItem("recordElement", "cat")); - assertThat(displayData, hasDisplayItem("recordClass", Integer.class)); - assertThat(displayData, hasDisplayItem("minBundleSize", 1234)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java deleted file mode 100644 index 87acd8fa8a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIOTest.java +++ /dev/null @@ -1,895 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.bigtable; - -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSourcesEqualReferenceSource; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionExhaustive; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionFails; -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.assertSplitAtFractionSucceedsAndConsistent; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Verify.verifyNotNull; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -import com.google.bigtable.v1.Cell; -import com.google.bigtable.v1.Column; -import com.google.bigtable.v1.Family; -import com.google.bigtable.v1.Mutation; -import com.google.bigtable.v1.Mutation.SetCell; -import com.google.bigtable.v1.Row; -import com.google.bigtable.v1.RowFilter; -import com.google.bigtable.v1.SampleRowKeysResponse; -import com.google.cloud.bigtable.config.BigtableOptions; -import com.google.cloud.bigtable.config.BulkOptions; -import com.google.cloud.bigtable.config.RetryOptions; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.bigtable.BigtableIO.BigtableSource; -import com.google.cloud.dataflow.sdk.io.range.ByteKey; -import com.google.cloud.dataflow.sdk.io.range.ByteKeyRange; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.protobuf.ByteString; -import com.google.protobuf.Empty; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import javax.annotation.Nullable; - -/** - * Unit tests for {@link BigtableIO}. - */ -@RunWith(JUnit4.class) -public class BigtableIOTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Rule public ExpectedLogs logged = ExpectedLogs.none(BigtableIO.class); - - /** - * These tests requires a static instance of the {@link FakeBigtableService} because the writers - * go through a serialization step when executing the test and would not affect passed-in objects - * otherwise. - */ - private static FakeBigtableService service; - private static final BigtableOptions BIGTABLE_OPTIONS = - new BigtableOptions.Builder() - .setProjectId("project") - .setClusterId("cluster") - .setZoneId("zone") - .build(); - private static BigtableIO.Read defaultRead = - BigtableIO.read().withBigtableOptions(BIGTABLE_OPTIONS); - private static BigtableIO.Write defaultWrite = - BigtableIO.write().withBigtableOptions(BIGTABLE_OPTIONS); - private Coder>> bigtableCoder; - private static final TypeDescriptor>> BIGTABLE_WRITE_TYPE = - new TypeDescriptor>>() {}; - - @Before - public void setup() throws Exception { - service = new FakeBigtableService(); - defaultRead = defaultRead.withBigtableService(service); - defaultWrite = defaultWrite.withBigtableService(service); - bigtableCoder = TestPipeline.create().getCoderRegistry().getCoder(BIGTABLE_WRITE_TYPE); - } - - @Test - public void testReadBuildsCorrectly() { - BigtableIO.Read read = - BigtableIO.read().withBigtableOptions(BIGTABLE_OPTIONS).withTableId("table"); - assertEquals("project", read.getBigtableOptions().getProjectId()); - assertEquals("cluster", read.getBigtableOptions().getClusterId()); - assertEquals("zone", read.getBigtableOptions().getZoneId()); - assertEquals("table", read.getTableId()); - } - - @Test - public void testReadBuildsCorrectlyInDifferentOrder() { - BigtableIO.Read read = - BigtableIO.read().withTableId("table").withBigtableOptions(BIGTABLE_OPTIONS); - assertEquals("project", read.getBigtableOptions().getProjectId()); - assertEquals("cluster", read.getBigtableOptions().getClusterId()); - assertEquals("zone", read.getBigtableOptions().getZoneId()); - assertEquals("table", read.getTableId()); - } - - @Test - public void testWriteBuildsCorrectly() { - BigtableIO.Write write = - BigtableIO.write().withBigtableOptions(BIGTABLE_OPTIONS).withTableId("table"); - assertEquals("table", write.getTableId()); - assertEquals("project", write.getBigtableOptions().getProjectId()); - assertEquals("zone", write.getBigtableOptions().getZoneId()); - assertEquals("cluster", write.getBigtableOptions().getClusterId()); - } - - @Test - public void testWriteBuildsCorrectlyInDifferentOrder() { - BigtableIO.Write write = - BigtableIO.write().withTableId("table").withBigtableOptions(BIGTABLE_OPTIONS); - assertEquals("cluster", write.getBigtableOptions().getClusterId()); - assertEquals("project", write.getBigtableOptions().getProjectId()); - assertEquals("zone", write.getBigtableOptions().getZoneId()); - assertEquals("table", write.getTableId()); - } - - @Test - public void testWriteValidationFailsMissingTable() { - BigtableIO.Write write = BigtableIO.write().withBigtableOptions(BIGTABLE_OPTIONS); - - thrown.expect(IllegalArgumentException.class); - - write.validate(null); - } - - @Test - public void testWriteValidationFailsMissingOptions() { - BigtableIO.Write write = BigtableIO.write().withTableId("table"); - - thrown.expect(IllegalArgumentException.class); - - write.validate(null); - } - - /** Helper function to make a single row mutation to be written. */ - private static KV> makeWrite(String key, String value) { - ByteString rowKey = ByteString.copyFromUtf8(key); - Iterable mutations = - ImmutableList.of( - Mutation.newBuilder() - .setSetCell(SetCell.newBuilder().setValue(ByteString.copyFromUtf8(value))) - .build()); - return KV.of(rowKey, mutations); - } - - /** Helper function to make a single bad row mutation (no set cell). */ - private static KV> makeBadWrite(String key) { - Iterable mutations = ImmutableList.of(Mutation.newBuilder().build()); - return KV.of(ByteString.copyFromUtf8(key), mutations); - } - - /** Tests that when reading from a non-existent table, the read fails. */ - @Test - public void testReadingFailsTableDoesNotExist() throws Exception { - final String table = "TEST-TABLE"; - - BigtableIO.Read read = - BigtableIO.read() - .withBigtableOptions(BIGTABLE_OPTIONS) - .withTableId(table) - .withBigtableService(service); - - // Exception will be thrown by read.validate() when read is applied. - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(String.format("Table %s does not exist", table)); - - TestPipeline.create().apply(read); - } - - /** Tests that when reading from an empty table, the read succeeds. */ - @Test - public void testReadingEmptyTable() throws Exception { - final String table = "TEST-EMPTY-TABLE"; - service.createTable(table); - - runReadTest(defaultRead.withTableId(table), new ArrayList()); - logged.verifyInfo("Closing reader after reading 0 records."); - } - - /** Tests reading all rows from a table. */ - @Test - public void testReading() throws Exception { - final String table = "TEST-MANY-ROWS-TABLE"; - final int numRows = 1001; - List testRows = makeTableData(table, numRows); - - runReadTest(defaultRead.withTableId(table), testRows); - logged.verifyInfo(String.format("Closing reader after reading %d records.", numRows)); - } - - /** A {@link Predicate} that a {@link Row Row's} key matches the given regex. */ - private static class KeyMatchesRegex implements Predicate { - private final String regex; - - public KeyMatchesRegex(String regex) { - this.regex = regex; - } - - @Override - public boolean apply(@Nullable ByteString input) { - verifyNotNull(input, "input"); - return input.toStringUtf8().matches(regex); - } - } - - private static List filterToRange(List rows, final ByteKeyRange range) { - return Lists.newArrayList(Iterables.filter( - rows, - new Predicate() { - @Override - public boolean apply(@Nullable Row input) { - verifyNotNull(input, "input"); - return range.containsKey(ByteKey.of(input.getKey())); - } - })); - } - - private static void runReadTest(BigtableIO.Read read, List expected) { - TestPipeline p = TestPipeline.create(); - PCollection rows = p.apply(read); - DataflowAssert.that(rows).containsInAnyOrder(expected); - p.run(); - } - - /** - * Tests reading all rows using key ranges. Tests a prefix [), a suffix (], and a restricted - * range [] and that some properties hold across them. - */ - @Test - public void testReadingWithKeyRange() throws Exception { - final String table = "TEST-KEY-RANGE-TABLE"; - final int numRows = 1001; - List testRows = makeTableData(table, numRows); - ByteKey startKey = ByteKey.copyFrom("key000000100".getBytes()); - ByteKey endKey = ByteKey.copyFrom("key000000300".getBytes()); - - // Test prefix: [beginning, startKey). - final ByteKeyRange prefixRange = ByteKeyRange.ALL_KEYS.withEndKey(startKey); - List prefixRows = filterToRange(testRows, prefixRange); - runReadTest(defaultRead.withTableId(table).withKeyRange(prefixRange), prefixRows); - - // Test suffix: [startKey, end). - final ByteKeyRange suffixRange = ByteKeyRange.ALL_KEYS.withStartKey(startKey); - List suffixRows = filterToRange(testRows, suffixRange); - runReadTest(defaultRead.withTableId(table).withKeyRange(suffixRange), suffixRows); - - // Test restricted range: [startKey, endKey). - final ByteKeyRange middleRange = ByteKeyRange.of(startKey, endKey); - List middleRows = filterToRange(testRows, middleRange); - runReadTest(defaultRead.withTableId(table).withKeyRange(middleRange), middleRows); - - //////// Size and content sanity checks ////////// - - // Prefix, suffix, middle should be non-trivial (non-zero,non-all). - assertThat(prefixRows, allOf(hasSize(lessThan(numRows)), hasSize(greaterThan(0)))); - assertThat(suffixRows, allOf(hasSize(lessThan(numRows)), hasSize(greaterThan(0)))); - assertThat(middleRows, allOf(hasSize(lessThan(numRows)), hasSize(greaterThan(0)))); - - // Prefix + suffix should be exactly all rows. - List union = Lists.newArrayList(prefixRows); - union.addAll(suffixRows); - assertThat("prefix + suffix = total", union, containsInAnyOrder(testRows.toArray(new Row[]{}))); - - // Suffix should contain the middle. - assertThat(suffixRows, hasItems(middleRows.toArray(new Row[]{}))); - } - - /** Tests reading all rows using a filter. */ - @Test - public void testReadingWithFilter() throws Exception { - final String table = "TEST-FILTER-TABLE"; - final int numRows = 1001; - List testRows = makeTableData(table, numRows); - String regex = ".*17.*"; - final KeyMatchesRegex keyPredicate = new KeyMatchesRegex(regex); - Iterable filteredRows = - Iterables.filter( - testRows, - new Predicate() { - @Override - public boolean apply(@Nullable Row input) { - verifyNotNull(input, "input"); - return keyPredicate.apply(input.getKey()); - } - }); - - RowFilter filter = - RowFilter.newBuilder().setRowKeyRegexFilter(ByteString.copyFromUtf8(regex)).build(); - - runReadTest( - defaultRead.withTableId(table).withRowFilter(filter), Lists.newArrayList(filteredRows)); - } - - /** - * Tests dynamic work rebalancing exhaustively. - */ - @Test - public void testReadingSplitAtFractionExhaustive() throws Exception { - final String table = "TEST-FEW-ROWS-SPLIT-EXHAUSTIVE-TABLE"; - final int numRows = 10; - final int numSamples = 1; - final long bytesPerRow = 1L; - makeTableData(table, numRows); - service.setupSampleRowKeys(table, numSamples, bytesPerRow); - - BigtableSource source = - new BigtableSource(service, table, null, service.getTableRange(table), null); - assertSplitAtFractionExhaustive(source, null); - } - - /** - * Unit tests of splitAtFraction. - */ - @Test - public void testReadingSplitAtFraction() throws Exception { - final String table = "TEST-SPLIT-AT-FRACTION"; - final int numRows = 10; - final int numSamples = 1; - final long bytesPerRow = 1L; - makeTableData(table, numRows); - service.setupSampleRowKeys(table, numSamples, bytesPerRow); - - BigtableSource source = - new BigtableSource(service, table, null, service.getTableRange(table), null); - // With 0 items read, all split requests will fail. - assertSplitAtFractionFails(source, 0, 0.1, null /* options */); - assertSplitAtFractionFails(source, 0, 1.0, null /* options */); - // With 1 items read, all split requests past 1/10th will succeed. - assertSplitAtFractionSucceedsAndConsistent(source, 1, 0.333, null /* options */); - assertSplitAtFractionSucceedsAndConsistent(source, 1, 0.666, null /* options */); - // With 3 items read, all split requests past 3/10ths will succeed. - assertSplitAtFractionFails(source, 3, 0.2, null /* options */); - assertSplitAtFractionSucceedsAndConsistent(source, 3, 0.571, null /* options */); - assertSplitAtFractionSucceedsAndConsistent(source, 3, 0.9, null /* options */); - // With 6 items read, all split requests past 6/10ths will succeed. - assertSplitAtFractionFails(source, 6, 0.5, null /* options */); - assertSplitAtFractionSucceedsAndConsistent(source, 6, 0.7, null /* options */); - } - - /** Tests reading all rows from a split table. */ - @Test - public void testReadingWithSplits() throws Exception { - final String table = "TEST-MANY-ROWS-SPLITS-TABLE"; - final int numRows = 1500; - final int numSamples = 10; - final long bytesPerRow = 100L; - - // Set up test table data and sample row keys for size estimation and splitting. - makeTableData(table, numRows); - service.setupSampleRowKeys(table, numSamples, bytesPerRow); - - // Generate source and split it. - BigtableSource source = - new BigtableSource(service, table, null /*filter*/, ByteKeyRange.ALL_KEYS, null /*size*/); - List splits = - source.splitIntoBundles(numRows * bytesPerRow / numSamples, null /* options */); - - // Test num splits and split equality. - assertThat(splits, hasSize(numSamples)); - assertSourcesEqualReferenceSource(source, splits, null /* options */); - } - - /** Tests reading all rows from a sub-split table. */ - @Test - public void testReadingWithSubSplits() throws Exception { - final String table = "TEST-MANY-ROWS-SPLITS-TABLE"; - final int numRows = 1000; - final int numSamples = 10; - final int numSplits = 20; - final long bytesPerRow = 100L; - - // Set up test table data and sample row keys for size estimation and splitting. - makeTableData(table, numRows); - service.setupSampleRowKeys(table, numSamples, bytesPerRow); - - // Generate source and split it. - BigtableSource source = - new BigtableSource(service, table, null /*filter*/, ByteKeyRange.ALL_KEYS, null /*size*/); - List splits = source.splitIntoBundles(numRows * bytesPerRow / numSplits, null); - - // Test num splits and split equality. - assertThat(splits, hasSize(numSplits)); - assertSourcesEqualReferenceSource(source, splits, null /* options */); - } - - /** Tests reading all rows from a sub-split table. */ - @Test - public void testReadingWithFilterAndSubSplits() throws Exception { - final String table = "TEST-FILTER-SUB-SPLITS"; - final int numRows = 1700; - final int numSamples = 10; - final int numSplits = 20; - final long bytesPerRow = 100L; - - // Set up test table data and sample row keys for size estimation and splitting. - makeTableData(table, numRows); - service.setupSampleRowKeys(table, numSamples, bytesPerRow); - - // Generate source and split it. - RowFilter filter = - RowFilter.newBuilder().setRowKeyRegexFilter(ByteString.copyFromUtf8(".*17.*")).build(); - BigtableSource source = - new BigtableSource(service, table, filter, ByteKeyRange.ALL_KEYS, null /*size*/); - List splits = source.splitIntoBundles(numRows * bytesPerRow / numSplits, null); - - // Test num splits and split equality. - assertThat(splits, hasSize(numSplits)); - assertSourcesEqualReferenceSource(source, splits, null /* options */); - } - - @Test - public void testReadingDisplayData() { - RowFilter rowFilter = RowFilter.newBuilder() - .setRowKeyRegexFilter(ByteString.copyFromUtf8("foo.*")) - .build(); - - ByteKeyRange keyRange = ByteKeyRange.ALL_KEYS.withEndKey(ByteKey.of(0xab, 0xcd)); - BigtableIO.Read read = BigtableIO.read() - .withBigtableOptions(BIGTABLE_OPTIONS) - .withTableId("fooTable") - .withRowFilter(rowFilter) - .withKeyRange(keyRange); - - DisplayData displayData = DisplayData.from(read); - - assertThat(displayData, hasDisplayItem(allOf(hasKey("tableId"), hasValue("fooTable")))); - - assertThat(displayData, hasDisplayItem("rowFilter", rowFilter.toString())); - - assertThat(displayData, hasDisplayItem("keyRange", keyRange.toString())); - - // BigtableIO adds user-agent to options; assert only on key and not value. - assertThat(displayData, hasDisplayItem("bigtableOptions")); - } - - @Test - public void testReadingPrimitiveDisplayData() throws IOException, InterruptedException { - final String table = "fooTable"; - service.createTable(table); - - RowFilter rowFilter = RowFilter.newBuilder() - .setRowKeyRegexFilter(ByteString.copyFromUtf8("foo.*")) - .build(); - - DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(); - BigtableIO.Read read = BigtableIO.read() - .withBigtableOptions(BIGTABLE_OPTIONS) - .withTableId(table) - .withRowFilter(rowFilter) - .withBigtableService(service); - - Set displayData = evaluator.displayDataForPrimitiveSourceTransforms(read); - assertThat("BigtableIO.Read should include the table id in its primitive display data", - displayData, Matchers.hasItem(hasDisplayItem("tableId"))); - assertThat("BigtableIO.Read should include the row filter, if it exists, in its primitive " - + "display data", displayData, Matchers.hasItem(hasDisplayItem("rowFilter"))); - } - - /** Tests that a record gets written to the service and messages are logged. */ - @Test - public void testWriting() throws Exception { - final String table = "table"; - final String key = "key"; - final String value = "value"; - - service.createTable(table); - - TestPipeline p = TestPipeline.create(); - p.apply("single row", Create.of(makeWrite(key, value)).withCoder(bigtableCoder)) - .apply("write", defaultWrite.withTableId(table)); - p.run(); - - logged.verifyInfo("Wrote 1 records"); - - assertEquals(1, service.tables.size()); - assertNotNull(service.getTable(table)); - Map rows = service.getTable(table); - assertEquals(1, rows.size()); - assertEquals(ByteString.copyFromUtf8(value), rows.get(ByteString.copyFromUtf8(key))); - } - - /** Tests that when writing to a non-existent table, the write fails. */ - @Test - public void testWritingFailsTableDoesNotExist() throws Exception { - final String table = "TEST-TABLE"; - - PCollection>> emptyInput = - TestPipeline.create().apply(Create.>>of()); - - // Exception will be thrown by write.validate() when write is applied. - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(String.format("Table %s does not exist", table)); - - emptyInput.apply("write", defaultWrite.withTableId(table)); - } - - /** Tests that when writing an element fails, the write fails. */ - @Test - public void testWritingFailsBadElement() throws Exception { - final String table = "TEST-TABLE"; - final String key = "KEY"; - service.createTable(table); - - TestPipeline p = TestPipeline.create(); - p.apply(Create.of(makeBadWrite(key)).withCoder(bigtableCoder)) - .apply(defaultWrite.withTableId(table)); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(Matchers.instanceOf(IOException.class)); - thrown.expectMessage("At least 1 errors occurred writing to Bigtable. First 1 errors:"); - thrown.expectMessage("Error mutating row " + key + " with mutations []: cell value missing"); - p.run(); - } - - @Test - public void testWritingDisplayData() { - BigtableIO.Write write = BigtableIO.write() - .withTableId("fooTable") - .withBigtableOptions(BIGTABLE_OPTIONS); - - DisplayData displayData = DisplayData.from(write); - assertThat(displayData, hasDisplayItem("tableId", "fooTable")); - } - - @Test - public void testGetSplitPointsConsumed() throws Exception { - final String table = "TEST-TABLE"; - final int numRows = 100; - int splitPointsConsumed = 0; - - makeTableData(table, numRows); - - BigtableSource source = - new BigtableSource(service, table, null, ByteKeyRange.ALL_KEYS, null); - - BoundedReader reader = source.createReader(TestPipeline.testingPipelineOptions()); - - reader.start(); - // Started, 0 split points consumed - assertEquals("splitPointsConsumed starting", - splitPointsConsumed, reader.getSplitPointsConsumed()); - - // Split points consumed increases for each row read - while (reader.advance()) { - assertEquals("splitPointsConsumed advancing", - ++splitPointsConsumed, reader.getSplitPointsConsumed()); - } - - // Reader marked as done, 100 split points consumed - assertEquals("splitPointsConsumed done", numRows, reader.getSplitPointsConsumed()); - - reader.close(); - } - - @Test - public void testReadWithBigTableOptionsSetsRetryOptions() { - final int initialBackoffMillis = -1; - - BigtableOptions.Builder optionsBuilder = BIGTABLE_OPTIONS.toBuilder(); - - RetryOptions.Builder retryOptionsBuilder = new RetryOptions.Builder(); - retryOptionsBuilder.setInitialBackoffMillis(initialBackoffMillis); - - optionsBuilder.setRetryOptions(retryOptionsBuilder.build()); - - BigtableIO.Read read = - BigtableIO.read().withBigtableOptions(optionsBuilder.build()); - - BigtableOptions options = read.getBigtableOptions(); - assertEquals(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE, - options.getRetryOptions().getStreamingBatchSize()); - assertEquals(initialBackoffMillis, options.getRetryOptions().getInitialBackoffMillis()); - - assertThat(options.getRetryOptions(), - Matchers.equalTo(retryOptionsBuilder - .setStreamingBatchSize(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE) - .build())); - } - - @Test - public void testWriteWithBigTableOptionsSetsBulkOptionsAndRetryOptions() { - final int maxInflightRpcs = 1; - final int initialBackoffMillis = -1; - - BigtableOptions.Builder optionsBuilder = BIGTABLE_OPTIONS.toBuilder(); - - BulkOptions.Builder bulkOptionsBuilder = new BulkOptions.Builder(); - bulkOptionsBuilder.setMaxInflightRpcs(maxInflightRpcs); - - RetryOptions.Builder retryOptionsBuilder = new RetryOptions.Builder(); - retryOptionsBuilder.setInitialBackoffMillis(initialBackoffMillis); - - optionsBuilder.setBulkOptions(bulkOptionsBuilder.build()) - .setRetryOptions(retryOptionsBuilder.build()); - - BigtableIO.Write write = - BigtableIO.write().withBigtableOptions(optionsBuilder.build()); - - BigtableOptions options = write.getBigtableOptions(); - assertEquals(true, options.getBulkOptions().useBulkApi()); - assertEquals(maxInflightRpcs, options.getBulkOptions().getMaxInflightRpcs()); - assertEquals(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE, - options.getRetryOptions().getStreamingBatchSize()); - assertEquals(initialBackoffMillis, options.getRetryOptions().getInitialBackoffMillis()); - - assertThat(options.getBulkOptions(), - Matchers.equalTo(bulkOptionsBuilder - .setUseBulkApi(true) - .build())); - assertThat(options.getRetryOptions(), - Matchers.equalTo(retryOptionsBuilder - .setStreamingBatchSize(RetryOptions.DEFAULT_STREAMING_BATCH_SIZE) - .build())); - } - - //////////////////////////////////////////////////////////////////////////////////////////// - private static final String COLUMN_FAMILY_NAME = "family"; - private static final ByteString COLUMN_NAME = ByteString.copyFromUtf8("column"); - private static final Column TEST_COLUMN = Column.newBuilder().setQualifier(COLUMN_NAME).build(); - private static final Family TEST_FAMILY = Family.newBuilder().setName(COLUMN_FAMILY_NAME).build(); - - /** Helper function that builds a {@link Row} in a test table that could be returned by read. */ - private static Row makeRow(ByteString key, ByteString value) { - // Build the currentRow and return true. - Column.Builder newColumn = TEST_COLUMN.toBuilder().addCells(Cell.newBuilder().setValue(value)); - return Row.newBuilder() - .setKey(key) - .addFamilies(TEST_FAMILY.toBuilder().addColumns(newColumn)) - .build(); - } - - /** Helper function to create a table and return the rows that it created. */ - private static List makeTableData(String tableId, int numRows) { - service.createTable(tableId); - Map testData = service.getTable(tableId); - - List testRows = new ArrayList<>(numRows); - for (int i = 0; i < numRows; ++i) { - ByteString key = ByteString.copyFromUtf8(String.format("key%09d", i)); - ByteString value = ByteString.copyFromUtf8(String.format("value%09d", i)); - testData.put(key, value); - testRows.add(makeRow(key, value)); - } - - return testRows; - } - - - /** - * A {@link BigtableService} implementation that stores tables and their contents in memory. - */ - private static class FakeBigtableService implements BigtableService { - private final Map> tables = new HashMap<>(); - private final Map> sampleRowKeys = new HashMap<>(); - - @Nullable - public SortedMap getTable(String tableId) { - return tables.get(tableId); - } - - public ByteKeyRange getTableRange(String tableId) { - verifyTableExists(tableId); - SortedMap data = tables.get(tableId); - return ByteKeyRange.of(ByteKey.of(data.firstKey()), ByteKey.of(data.lastKey())); - } - - public void createTable(String tableId) { - tables.put(tableId, new TreeMap(new ByteStringComparator())); - } - - @Override - public boolean tableExists(String tableId) { - return tables.containsKey(tableId); - } - - public void verifyTableExists(String tableId) { - checkArgument(tableExists(tableId), "Table %s does not exist", tableId); - } - - @Override - public FakeBigtableReader createReader(BigtableSource source) { - return new FakeBigtableReader(source); - } - - @Override - public FakeBigtableWriter openForWriting(String tableId) { - return new FakeBigtableWriter(tableId); - } - - @Override - public List getSampleRowKeys(BigtableSource source) { - List samples = sampleRowKeys.get(source.getTableId()); - checkArgument(samples != null, "No samples found for table %s", source.getTableId()); - return samples; - } - - /** Sets up the sample row keys for the specified table. */ - void setupSampleRowKeys(String tableId, int numSamples, long bytesPerRow) { - verifyTableExists(tableId); - checkArgument(numSamples > 0, "Number of samples must be positive: %s", numSamples); - checkArgument(bytesPerRow > 0, "Bytes/Row must be positive: %s", bytesPerRow); - - ImmutableList.Builder ret = ImmutableList.builder(); - SortedMap rows = getTable(tableId); - int currentSample = 1; - int rowsSoFar = 0; - for (Map.Entry entry : rows.entrySet()) { - if (((double) rowsSoFar) / rows.size() >= ((double) currentSample) / numSamples) { - // add the sample with the total number of bytes in the table before this key. - ret.add( - SampleRowKeysResponse.newBuilder() - .setRowKey(entry.getKey()) - .setOffsetBytes(rowsSoFar * bytesPerRow) - .build()); - // Move on to next sample - currentSample++; - } - ++rowsSoFar; - } - - // Add the last sample indicating the end of the table, with all rows before it. - ret.add(SampleRowKeysResponse.newBuilder().setOffsetBytes(rows.size() * bytesPerRow).build()); - sampleRowKeys.put(tableId, ret.build()); - } - } - - /** - * A {@link BigtableService.Reader} implementation that reads from the static instance of - * {@link FakeBigtableService} stored in {@link #service}. - * - *

              This reader does not support {@link RowFilter} objects. - */ - private static class FakeBigtableReader implements BigtableService.Reader { - private final BigtableSource source; - private Iterator> rows; - private Row currentRow; - private Predicate filter; - - public FakeBigtableReader(BigtableSource source) { - this.source = source; - if (source.getRowFilter() == null) { - filter = Predicates.alwaysTrue(); - } else { - ByteString keyRegex = source.getRowFilter().getRowKeyRegexFilter(); - checkArgument(!keyRegex.isEmpty(), "Only RowKeyRegexFilter is supported"); - filter = new KeyMatchesRegex(keyRegex.toStringUtf8()); - } - service.verifyTableExists(source.getTableId()); - } - - @Override - public boolean start() { - rows = service.tables.get(source.getTableId()).entrySet().iterator(); - return advance(); - } - - @Override - public boolean advance() { - // Loop until we find a row in range, or reach the end of the iterator. - Map.Entry entry = null; - while (rows.hasNext()) { - entry = rows.next(); - if (!filter.apply(entry.getKey()) - || !source.getRange().containsKey(ByteKey.of(entry.getKey()))) { - // Does not match row filter or does not match source range. Skip. - entry = null; - continue; - } - // Found a row inside this source's key range, stop. - break; - } - - // Return false if no more rows. - if (entry == null) { - currentRow = null; - return false; - } - - // Set the current row and return true. - currentRow = makeRow(entry.getKey(), entry.getValue()); - return true; - } - - @Override - public Row getCurrentRow() { - if (currentRow == null) { - throw new NoSuchElementException(); - } - return currentRow; - } - - @Override - public void close() { - rows = null; - currentRow = null; - } - } - - /** - * A {@link BigtableService.Writer} implementation that writes to the static instance of - * {@link FakeBigtableService} stored in {@link #service}. - * - *

              This writer only supports {@link Mutation Mutations} that consist only of {@link SetCell} - * entries. The column family in the {@link SetCell} is ignored; only the value is used. - * - *

              When no {@link SetCell} is provided, the write will fail and this will be exposed via an - * exception on the returned {@link ListenableFuture}. - */ - private static class FakeBigtableWriter implements BigtableService.Writer { - private final String tableId; - - public FakeBigtableWriter(String tableId) { - this.tableId = tableId; - } - - @Override - public ListenableFuture writeRecord(KV> record) { - service.verifyTableExists(tableId); - Map table = service.getTable(tableId); - ByteString key = record.getKey(); - for (Mutation m : record.getValue()) { - SetCell cell = m.getSetCell(); - if (cell.getValue().isEmpty()) { - return Futures.immediateFailedCheckedFuture(new IOException("cell value missing")); - } - table.put(key, cell.getValue()); - } - return Futures.immediateFuture(Empty.getDefaultInstance()); - } - - @Override - public void close() {} - } - - /** A serializable comparator for ByteString. Used to make row samples. */ - private static final class ByteStringComparator implements Comparator, Serializable { - @Override - public int compare(ByteString o1, ByteString o2) { - return ByteKey.of(o1).compareTo(ByteKey.of(o2)); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java deleted file mode 100644 index 917f87a1ef..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/datastore/DatastoreV1Test.java +++ /dev/null @@ -1,776 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.datastore; - -import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DATASTORE_BATCH_UPDATE_LIMIT; -import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.DEFAULT_BUNDLE_SIZE_BYTES; -import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.QUERY_BATCH_LIMIT; -import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.getEstimatedSizeBytes; -import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.makeRequest; -import static com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.isValidKey; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.datastore.v1.PropertyFilter.Operator.EQUAL; -import static com.google.datastore.v1.PropertyOrder.Direction.DESCENDING; -import static com.google.datastore.v1.client.DatastoreHelper.makeAndFilter; -import static com.google.datastore.v1.client.DatastoreHelper.makeDelete; -import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; -import static com.google.datastore.v1.client.DatastoreHelper.makeKey; -import static com.google.datastore.v1.client.DatastoreHelper.makeOrder; -import static com.google.datastore.v1.client.DatastoreHelper.makeUpsert; -import static com.google.datastore.v1.client.DatastoreHelper.makeValue; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DatastoreWriterFn; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteEntity; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteEntityFn; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteKey; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.DeleteKeyFn; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.ReadFn; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.SplitQueryFn; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Read.V1Options; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.UpsertFn; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.V1DatastoreFactory; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1.Write; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester.CloningBehavior; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.datastore.v1.CommitRequest; -import com.google.datastore.v1.Entity; -import com.google.datastore.v1.EntityResult; -import com.google.datastore.v1.Key; -import com.google.datastore.v1.Mutation; -import com.google.datastore.v1.PartitionId; -import com.google.datastore.v1.Query; -import com.google.datastore.v1.QueryResultBatch; -import com.google.datastore.v1.RunQueryRequest; -import com.google.datastore.v1.RunQueryResponse; -import com.google.datastore.v1.client.Datastore; -import com.google.datastore.v1.client.QuerySplitter; -import com.google.protobuf.Int32Value; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * Tests for {@link DatastoreV1}. - */ -@RunWith(JUnit4.class) -public class DatastoreV1Test { - private static final String PROJECT_ID = "testProject"; - private static final String NAMESPACE = "testNamespace"; - private static final String KIND = "testKind"; - private static final Query QUERY; - private static final V1Options v1Options; - static { - Query.Builder q = Query.newBuilder(); - q.addKindBuilder().setName(KIND); - QUERY = q.build(); - v1Options = V1Options.from(PROJECT_ID, QUERY, NAMESPACE); - } - private Read initialRead; - - @Mock - Datastore mockDatastore; - @Mock - QuerySplitter mockQuerySplitter; - @Mock - V1DatastoreFactory mockDatastoreFactory; - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - initialRead = DatastoreIO.v1().read() - .withProjectId(PROJECT_ID).withQuery(QUERY).withNamespace(NAMESPACE); - - when(mockDatastoreFactory.getDatastore(any(PipelineOptions.class), any(String.class))) - .thenReturn(mockDatastore); - when(mockDatastoreFactory.getQuerySplitter()) - .thenReturn(mockQuerySplitter); - } - - @Test - public void testBuildRead() throws Exception { - Read read = DatastoreIO.v1().read() - .withProjectId(PROJECT_ID).withQuery(QUERY).withNamespace(NAMESPACE); - assertEquals(QUERY, read.getQuery()); - assertEquals(PROJECT_ID, read.getProjectId()); - assertEquals(NAMESPACE, read.getNamespace()); - } - - /** - * {@link #testBuildRead} but constructed in a different order. - */ - @Test - public void testBuildReadAlt() throws Exception { - Read read = DatastoreIO.v1().read() - .withProjectId(PROJECT_ID).withNamespace(NAMESPACE).withQuery(QUERY); - assertEquals(QUERY, read.getQuery()); - assertEquals(PROJECT_ID, read.getProjectId()); - assertEquals(NAMESPACE, read.getNamespace()); - } - - @Test - public void testReadValidationFailsProject() throws Exception { - Read read = DatastoreIO.v1().read().withQuery(QUERY); - thrown.expect(NullPointerException.class); - thrown.expectMessage("project"); - read.validate(null); - } - - @Test - public void testReadValidationFailsQuery() throws Exception { - Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID); - thrown.expect(NullPointerException.class); - thrown.expectMessage("query"); - read.validate(null); - } - - @Test - public void testReadValidationFailsQueryLimitZero() throws Exception { - Query invalidLimit = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(0)).build(); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid query limit 0: must be positive"); - - DatastoreIO.v1().read().withQuery(invalidLimit); - } - - @Test - public void testReadValidationFailsQueryLimitNegative() throws Exception { - Query invalidLimit = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(-5)).build(); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid query limit -5: must be positive"); - - DatastoreIO.v1().read().withQuery(invalidLimit); - } - - @Test - public void testReadValidationSucceedsNamespace() throws Exception { - Read read = DatastoreIO.v1().read().withProjectId(PROJECT_ID).withQuery(QUERY); - /* Should succeed, as a null namespace is fine. */ - read.validate(null); - } - - @Test - public void testReadDisplayData() { - Read read = DatastoreIO.v1().read() - .withProjectId(PROJECT_ID) - .withQuery(QUERY) - .withNamespace(NAMESPACE); - - DisplayData displayData = DisplayData.from(read); - - assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); - assertThat(displayData, hasDisplayItem("query", QUERY.toString())); - assertThat(displayData, hasDisplayItem("namespace", NAMESPACE)); - } - - @Test - public void testWriteDoesNotAllowNullProject() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("projectId"); - - DatastoreIO.v1().write().withProjectId(null); - } - - @Test - public void testWriteValidationFailsWithNoProject() throws Exception { - Write write = DatastoreIO.v1().write(); - - thrown.expect(NullPointerException.class); - thrown.expectMessage("projectId"); - - write.validate(null); - } - - @Test - public void testWriteValidationSucceedsWithProject() throws Exception { - Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); - write.validate(null); - } - - @Test - public void testWriteDisplayData() { - Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); - - DisplayData displayData = DisplayData.from(write); - - assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); - assertThat(displayData, hasDisplayItem("mutationFn", UpsertFn.class)); - } - - @Test - public void testDeleteEntityDoesNotAllowNullProject() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("projectId"); - - DatastoreIO.v1().deleteEntity().withProjectId(null); - } - - @Test - public void testDeleteEntityValidationFailsWithNoProject() throws Exception { - DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity(); - - thrown.expect(NullPointerException.class); - thrown.expectMessage("projectId"); - - deleteEntity.validate(null); - } - - @Test - public void testDeleteEntityValidationSucceedsWithProject() throws Exception { - DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity().withProjectId(PROJECT_ID); - deleteEntity.validate(null); - } - - @Test - public void testDeleteEntityDisplayData() { - DeleteEntity deleteEntity = DatastoreIO.v1().deleteEntity().withProjectId(PROJECT_ID); - - DisplayData displayData = DisplayData.from(deleteEntity); - - assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); - assertThat(displayData, hasDisplayItem("mutationFn", DeleteEntityFn.class)); - } - - @Test - public void testDeleteKeyDoesNotAllowNullProject() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("projectId"); - - DatastoreIO.v1().deleteKey().withProjectId(null); - } - - @Test - public void testDeleteKeyValidationFailsWithNoProject() throws Exception { - DeleteKey deleteKey = DatastoreIO.v1().deleteKey(); - - thrown.expect(NullPointerException.class); - thrown.expectMessage("projectId"); - - deleteKey.validate(null); - } - - @Test - public void testDeleteKeyValidationSucceedsWithProject() throws Exception { - DeleteKey deleteKey = DatastoreIO.v1().deleteKey().withProjectId(PROJECT_ID); - deleteKey.validate(null); - } - - @Test - public void testDeleteKeyDisplayData() { - DeleteKey deleteKey = DatastoreIO.v1().deleteKey().withProjectId(PROJECT_ID); - - DisplayData displayData = DisplayData.from(deleteKey); - - assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); - assertThat(displayData, hasDisplayItem("mutationFn", DeleteKeyFn.class)); - } - - /** - * Test building a Write using builder methods. - */ - @Test - public void testBuildWrite() throws Exception { - DatastoreV1.Write write = DatastoreIO.v1().write().withProjectId(PROJECT_ID); - assertEquals(PROJECT_ID, write.getProjectId()); - } - - /** - * Test the detection of complete and incomplete keys. - */ - @Test - public void testHasNameOrId() { - Key key; - // Complete with name, no ancestor - key = makeKey("bird", "finch").build(); - assertTrue(isValidKey(key)); - - // Complete with id, no ancestor - key = makeKey("bird", 123).build(); - assertTrue(isValidKey(key)); - - // Incomplete, no ancestor - key = makeKey("bird").build(); - assertFalse(isValidKey(key)); - - // Complete with name and ancestor - key = makeKey("bird", "owl").build(); - key = makeKey(key, "bird", "horned").build(); - assertTrue(isValidKey(key)); - - // Complete with id and ancestor - key = makeKey("bird", "owl").build(); - key = makeKey(key, "bird", 123).build(); - assertTrue(isValidKey(key)); - - // Incomplete with ancestor - key = makeKey("bird", "owl").build(); - key = makeKey(key, "bird").build(); - assertFalse(isValidKey(key)); - - key = makeKey().build(); - assertFalse(isValidKey(key)); - } - - /** - * Test that entities with incomplete keys cannot be updated. - */ - @Test - public void testAddEntitiesWithIncompleteKeys() throws Exception { - Key key = makeKey("bird").build(); - Entity entity = Entity.newBuilder().setKey(key).build(); - UpsertFn upsertFn = new UpsertFn(); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Entities to be written to the Cloud Datastore must have complete keys"); - - upsertFn.apply(entity); - } - - @Test - /** - * Test that entities with valid keys are transformed to upsert mutations. - */ - public void testAddEntities() throws Exception { - Key key = makeKey("bird", "finch").build(); - Entity entity = Entity.newBuilder().setKey(key).build(); - UpsertFn upsertFn = new UpsertFn(); - - Mutation exceptedMutation = makeUpsert(entity).build(); - assertEquals(upsertFn.apply(entity), exceptedMutation); - } - - /** - * Test that entities with incomplete keys cannot be deleted. - */ - @Test - public void testDeleteEntitiesWithIncompleteKeys() throws Exception { - Key key = makeKey("bird").build(); - Entity entity = Entity.newBuilder().setKey(key).build(); - DeleteEntityFn deleteEntityFn = new DeleteEntityFn(); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Entities to be deleted from the Cloud Datastore must have complete keys"); - - deleteEntityFn.apply(entity); - } - - /** - * Test that entities with valid keys are transformed to delete mutations. - */ - @Test - public void testDeleteEntities() throws Exception { - Key key = makeKey("bird", "finch").build(); - Entity entity = Entity.newBuilder().setKey(key).build(); - DeleteEntityFn deleteEntityFn = new DeleteEntityFn(); - - Mutation exceptedMutation = makeDelete(entity.getKey()).build(); - assertEquals(deleteEntityFn.apply(entity), exceptedMutation); - } - - /** - * Test that incomplete keys cannot be deleted. - */ - @Test - public void testDeleteIncompleteKeys() throws Exception { - Key key = makeKey("bird").build(); - DeleteKeyFn deleteKeyFn = new DeleteKeyFn(); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Keys to be deleted from the Cloud Datastore must be complete"); - - deleteKeyFn.apply(key); - } - - /** - * Test that valid keys are transformed to delete mutations. - */ - @Test - public void testDeleteKeys() throws Exception { - Key key = makeKey("bird", "finch").build(); - DeleteKeyFn deleteKeyFn = new DeleteKeyFn(); - - Mutation exceptedMutation = makeDelete(key).build(); - assertEquals(deleteKeyFn.apply(key), exceptedMutation); - } - - @Test - public void testDatastoreWriteFnDisplayData() { - DatastoreWriterFn datastoreWriter = new DatastoreWriterFn(PROJECT_ID); - DisplayData displayData = DisplayData.from(datastoreWriter); - assertThat(displayData, hasDisplayItem("projectId", PROJECT_ID)); - } - - /** Tests {@link DatastoreWriterFn} with entities less than one batch. */ - @Test - public void testDatatoreWriterFnWithOneBatch() throws Exception { - datastoreWriterFnTest(100); - } - - /** Tests {@link DatastoreWriterFn} with entities of more than one batches, but not a multiple. */ - @Test - public void testDatatoreWriterFnWithMultipleBatches() throws Exception { - datastoreWriterFnTest(DATASTORE_BATCH_UPDATE_LIMIT * 3 + 100); - } - - /** - * Tests {@link DatastoreWriterFn} with entities of several batches, using an exact multiple of - * write batch size. - */ - @Test - public void testDatatoreWriterFnWithBatchesExactMultiple() throws Exception { - datastoreWriterFnTest(DATASTORE_BATCH_UPDATE_LIMIT * 2); - } - - // A helper method to test DatastoreWriterFn for various batch sizes. - private void datastoreWriterFnTest(int numMutations) throws Exception { - // Create the requested number of mutations. - List mutations = new ArrayList<>(numMutations); - for (int i = 0; i < numMutations; ++i) { - mutations.add( - makeUpsert(Entity.newBuilder().setKey(makeKey("key" + i, i + 1)).build()).build()); - } - - DatastoreWriterFn datastoreWriter = new DatastoreWriterFn(PROJECT_ID, mockDatastoreFactory); - DoFnTester doFnTester = DoFnTester.of(datastoreWriter); - doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); - doFnTester.processBatch(mutations); - - int start = 0; - while (start < numMutations) { - int end = Math.min(numMutations, start + DATASTORE_BATCH_UPDATE_LIMIT); - CommitRequest.Builder commitRequest = CommitRequest.newBuilder(); - commitRequest.setMode(CommitRequest.Mode.NON_TRANSACTIONAL); - commitRequest.addAllMutations(mutations.subList(start, end)); - // Verify all the batch requests were made with the expected mutations. - verify(mockDatastore, times(1)).commit(commitRequest.build()); - start = end; - } - } - - /** - * Tests {@link DatastoreV1.Read#getEstimatedSizeBytes} to fetch and return estimated size for a - * query. - */ - @Test - public void testEstimatedSizeBytes() throws Exception { - long entityBytes = 100L; - // In seconds - long timestamp = 1234L; - - RunQueryRequest latestTimestampRequest = makeRequest(makeLatestTimestampQuery(NAMESPACE), - NAMESPACE); - RunQueryResponse latestTimestampResponse = makeLatestTimestampResponse(timestamp); - // Per Kind statistics request and response - RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE, timestamp), NAMESPACE); - RunQueryResponse statResponse = makeStatKindResponse(entityBytes); - - when(mockDatastore.runQuery(latestTimestampRequest)) - .thenReturn(latestTimestampResponse); - when(mockDatastore.runQuery(statRequest)) - .thenReturn(statResponse); - - assertEquals(entityBytes, getEstimatedSizeBytes(mockDatastore, QUERY, NAMESPACE)); - verify(mockDatastore, times(1)).runQuery(latestTimestampRequest); - verify(mockDatastore, times(1)).runQuery(statRequest); - } - - /** - * Tests {@link SplitQueryFn} when number of query splits is specified. - */ - @Test - public void testSplitQueryFnWithNumSplits() throws Exception { - int numSplits = 100; - when(mockQuerySplitter.getSplits( - eq(QUERY), any(PartitionId.class), eq(numSplits), any(Datastore.class))) - .thenReturn(splitQuery(QUERY, numSplits)); - - SplitQueryFn splitQueryFn = new SplitQueryFn(v1Options, numSplits, mockDatastoreFactory); - DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); - /** - * Although Datastore client is marked transient in {@link SplitQueryFn}, when injected through - * mock factory using a when clause for unit testing purposes, it is not serializable - * because it doesn't have a no-arg constructor. Thus disabling the cloning to prevent the - * doFn from being serialized. - */ - doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); - List> queries = doFnTester.processBatch(QUERY); - - assertEquals(queries.size(), numSplits); - verifyUniqueKeys(queries); - verify(mockQuerySplitter, times(1)).getSplits( - eq(QUERY), any(PartitionId.class), eq(numSplits), any(Datastore.class)); - verifyZeroInteractions(mockDatastore); - } - - /** - * Tests {@link SplitQueryFn} when no query splits is specified. - */ - @Test - public void testSplitQueryFnWithoutNumSplits() throws Exception { - // Force SplitQueryFn to compute the number of query splits - int numSplits = 0; - int expectedNumSplits = 20; - long entityBytes = expectedNumSplits * DEFAULT_BUNDLE_SIZE_BYTES; - // In seconds - long timestamp = 1234L; - - RunQueryRequest latestTimestampRequest = makeRequest(makeLatestTimestampQuery(NAMESPACE), - NAMESPACE); - RunQueryResponse latestTimestampResponse = makeLatestTimestampResponse(timestamp); - - // Per Kind statistics request and response - RunQueryRequest statRequest = makeRequest(makeStatKindQuery(NAMESPACE, timestamp), NAMESPACE); - RunQueryResponse statResponse = makeStatKindResponse(entityBytes); - - when(mockDatastore.runQuery(latestTimestampRequest)) - .thenReturn(latestTimestampResponse); - when(mockDatastore.runQuery(statRequest)) - .thenReturn(statResponse); - when(mockQuerySplitter.getSplits( - eq(QUERY), any(PartitionId.class), eq(expectedNumSplits), any(Datastore.class))) - .thenReturn(splitQuery(QUERY, expectedNumSplits)); - - SplitQueryFn splitQueryFn = new SplitQueryFn(v1Options, numSplits, mockDatastoreFactory); - DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); - doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); - List> queries = doFnTester.processBatch(QUERY); - - assertEquals(queries.size(), expectedNumSplits); - verifyUniqueKeys(queries); - verify(mockQuerySplitter, times(1)).getSplits( - eq(QUERY), any(PartitionId.class), eq(expectedNumSplits), any(Datastore.class)); - verify(mockDatastore, times(1)).runQuery(latestTimestampRequest); - verify(mockDatastore, times(1)).runQuery(statRequest); - } - - /** - * Tests {@link DatastoreV1.Read.SplitQueryFn} when the query has a user specified limit. - */ - @Test - public void testSplitQueryFnWithQueryLimit() throws Exception { - Query queryWithLimit = QUERY.toBuilder().clone() - .setLimit(Int32Value.newBuilder().setValue(1)) - .build(); - - SplitQueryFn splitQueryFn = new SplitQueryFn(v1Options, 10, mockDatastoreFactory); - DoFnTester> doFnTester = DoFnTester.of(splitQueryFn); - doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); - List> queries = doFnTester.processBatch(queryWithLimit); - - assertEquals(queries.size(), 1); - verifyUniqueKeys(queries); - verifyNoMoreInteractions(mockDatastore); - verifyNoMoreInteractions(mockQuerySplitter); - } - - /** Tests {@link ReadFn} with a query limit less than one batch. */ - @Test - public void testReadFnWithOneBatch() throws Exception { - readFnTest(5); - } - - /** Tests {@link ReadFn} with a query limit more than one batch, and not a multiple. */ - @Test - public void testReadFnWithMultipleBatches() throws Exception { - readFnTest(QUERY_BATCH_LIMIT + 5); - } - - /** Tests {@link ReadFn} for several batches, using an exact multiple of batch size results. */ - @Test - public void testReadFnWithBatchesExactMultiple() throws Exception { - readFnTest(5 * QUERY_BATCH_LIMIT); - } - - /** Helper Methods */ - - /** A helper function that verifies if all the queries have unique keys. */ - private void verifyUniqueKeys(List> queries) { - Set keys = new HashSet<>(); - for (KV kv: queries) { - keys.add(kv.getKey()); - } - assertEquals(keys.size(), queries.size()); - } - - /** - * A helper function that creates mock {@link Entity} results in response to a query. Always - * indicates that more results are available, unless the batch is limited to fewer than - * {@link DatastoreV1.Read#QUERY_BATCH_LIMIT} results. - */ - private static RunQueryResponse mockResponseForQuery(Query q) { - // Every query DatastoreV1 sends should have a limit. - assertTrue(q.hasLimit()); - - // The limit should be in the range [1, QUERY_BATCH_LIMIT] - int limit = q.getLimit().getValue(); - assertThat(limit, greaterThanOrEqualTo(1)); - assertThat(limit, lessThanOrEqualTo(QUERY_BATCH_LIMIT)); - - // Create the requested number of entities. - List entities = new ArrayList<>(limit); - for (int i = 0; i < limit; ++i) { - entities.add( - EntityResult.newBuilder() - .setEntity(Entity.newBuilder().setKey(makeKey("key" + i, i + 1))) - .build()); - } - - // Fill out the other parameters on the returned result batch. - RunQueryResponse.Builder ret = RunQueryResponse.newBuilder(); - ret.getBatchBuilder() - .addAllEntityResults(entities) - .setEntityResultType(EntityResult.ResultType.FULL) - .setMoreResults( - limit == QUERY_BATCH_LIMIT - ? QueryResultBatch.MoreResultsType.NOT_FINISHED - : QueryResultBatch.MoreResultsType.NO_MORE_RESULTS); - - return ret.build(); - } - - /** Helper function to run a test reading from a {@link ReadFn}. */ - private void readFnTest(int numEntities) throws Exception { - // An empty query to read entities. - Query query = Query.newBuilder().setLimit( - Int32Value.newBuilder().setValue(numEntities)).build(); - - // Use mockResponseForQuery to generate results. - when(mockDatastore.runQuery(any(RunQueryRequest.class))) - .thenAnswer(new Answer() { - @Override - public RunQueryResponse answer(InvocationOnMock invocationOnMock) throws Throwable { - Query q = ((RunQueryRequest) invocationOnMock.getArguments()[0]).getQuery(); - return mockResponseForQuery(q); - } - }); - - ReadFn readFn = new ReadFn(v1Options, mockDatastoreFactory); - DoFnTester doFnTester = DoFnTester.of(readFn); - /** - * Although Datastore client is marked transient in {@link ReadFn}, when injected through - * mock factory using a when clause for unit testing purposes, it is not serializable - * because it doesn't have a no-arg constructor. Thus disabling the cloning to prevent the - * test object from being serialized. - */ - doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); - List entities = doFnTester.processBatch(query); - - int expectedNumCallsToRunQuery = (int) Math.ceil((double) numEntities / QUERY_BATCH_LIMIT); - verify(mockDatastore, times(expectedNumCallsToRunQuery)).runQuery(any(RunQueryRequest.class)); - // Validate the number of results. - assertEquals(numEntities, entities.size()); - } - - /** Builds a per-kind statistics response with the given entity size. */ - private static RunQueryResponse makeStatKindResponse(long entitySizeInBytes) { - RunQueryResponse.Builder statKindResponse = RunQueryResponse.newBuilder(); - Entity.Builder entity = Entity.newBuilder(); - entity.setKey(makeKey("dummyKind", "dummyId")); - entity.getMutableProperties().put("entity_bytes", makeValue(entitySizeInBytes).build()); - EntityResult.Builder entityResult = EntityResult.newBuilder(); - entityResult.setEntity(entity); - QueryResultBatch.Builder batch = QueryResultBatch.newBuilder(); - batch.addEntityResults(entityResult); - statKindResponse.setBatch(batch); - return statKindResponse.build(); - } - - /** Builds a response of the given timestamp. */ - private static RunQueryResponse makeLatestTimestampResponse(long timestamp) { - RunQueryResponse.Builder timestampResponse = RunQueryResponse.newBuilder(); - Entity.Builder entity = Entity.newBuilder(); - entity.setKey(makeKey("dummyKind", "dummyId")); - entity.getMutableProperties().put("timestamp", makeValue(new Date(timestamp * 1000)).build()); - EntityResult.Builder entityResult = EntityResult.newBuilder(); - entityResult.setEntity(entity); - QueryResultBatch.Builder batch = QueryResultBatch.newBuilder(); - batch.addEntityResults(entityResult); - timestampResponse.setBatch(batch); - return timestampResponse.build(); - } - - /** Builds a per-kind statistics query for the given timestamp and namespace. */ - private static Query makeStatKindQuery(String namespace, long timestamp) { - Query.Builder statQuery = Query.newBuilder(); - if (namespace == null) { - statQuery.addKindBuilder().setName("__Stat_Kind__"); - } else { - statQuery.addKindBuilder().setName("__Stat_Ns_Kind__"); - } - statQuery.setFilter(makeAndFilter( - makeFilter("kind_name", EQUAL, makeValue(KIND)).build(), - makeFilter("timestamp", EQUAL, makeValue(timestamp * 1000000L)).build())); - return statQuery.build(); - } - - /** Builds a latest timestamp statistics query. */ - private static Query makeLatestTimestampQuery(String namespace) { - Query.Builder timestampQuery = Query.newBuilder(); - if (namespace == null) { - timestampQuery.addKindBuilder().setName("__Stat_Total__"); - } else { - timestampQuery.addKindBuilder().setName("__Stat_Ns_Total__"); - } - timestampQuery.addOrder(makeOrder("timestamp", DESCENDING)); - timestampQuery.setLimit(Int32Value.newBuilder().setValue(1)); - return timestampQuery.build(); - } - - /** Generate dummy query splits. */ - private List splitQuery(Query query, int numSplits) { - List queries = new LinkedList<>(); - for (int i = 0; i < numSplits; i++) { - queries.add(query.toBuilder().clone().build()); - } - return queries; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java deleted file mode 100644 index 71928f400e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeEstimateFractionTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertThat; - -import com.google.common.collect.ImmutableList; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * A combinatorial test of {@link ByteKeyRange#estimateFractionForKey(ByteKey)}. - */ -@RunWith(Parameterized.class) -public class ByteKeyRangeEstimateFractionTest { - private static final ByteKey[] TEST_KEYS = ByteKeyRangeTest.RANGE_TEST_KEYS; - - @Parameters(name = "{index}: i={0}, k={1}") - public static Iterable data() { - ImmutableList.Builder ret = ImmutableList.builder(); - for (int i = 0; i < TEST_KEYS.length; ++i) { - for (int k = i + 1; k < TEST_KEYS.length; ++k) { - ret.add(new Object[] {i, k}); - } - } - return ret.build(); - } - - @Parameter(0) - public int i; - - @Parameter(1) - public int k; - - @Test - public void testEstimateFractionForKey() { - double last = 0.0; - ByteKeyRange range = ByteKeyRange.of(TEST_KEYS[i], TEST_KEYS[k]); - for (int j = i; j < k; ++j) { - ByteKey key = TEST_KEYS[j]; - if (key.isEmpty()) { - // Cannot compute progress for unspecified key - continue; - } - double fraction = range.estimateFractionForKey(key); - assertThat(fraction, greaterThanOrEqualTo(last)); - last = fraction; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java deleted file mode 100644 index c41f905455..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeInterpolateKeyTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static org.hamcrest.Matchers.closeTo; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertThat; - -import com.google.common.collect.ImmutableList; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * Combinatorial tests for {@link ByteKeyRange#interpolateKey}, which also checks - * {@link ByteKeyRange#estimateFractionForKey} by converting the interpolated keys back to - * fractions. - */ -@RunWith(Parameterized.class) -public class ByteKeyRangeInterpolateKeyTest { - private static final ByteKey[] TEST_KEYS = ByteKeyRangeTest.RANGE_TEST_KEYS; - - @Parameters(name = "{index}: {0}") - public static Iterable data() { - ImmutableList.Builder ret = ImmutableList.builder(); - for (int i = 0; i < TEST_KEYS.length; ++i) { - for (int j = i + 1; j < TEST_KEYS.length; ++j) { - ret.add(new Object[] {ByteKeyRange.of(TEST_KEYS[i], TEST_KEYS[j])}); - } - } - return ret.build(); - } - - @Parameter public ByteKeyRange range; - - @Test - public void testInterpolateKeyAndEstimateFraction() { - double delta = 0.0000001; - double[] testFractions = - new double[] {0.01, 0.1, 0.123, 0.2, 0.3, 0.45738, 0.5, 0.6, 0.7182, 0.8, 0.95, 0.97, 0.99}; - ByteKey last = range.getStartKey(); - for (double fraction : testFractions) { - String message = Double.toString(fraction); - try { - ByteKey key = range.interpolateKey(fraction); - assertThat(message, key, greaterThanOrEqualTo(last)); - assertThat(message, range.estimateFractionForKey(key), closeTo(fraction, delta)); - last = key; - } catch (IllegalStateException e) { - assertThat(message, e.getMessage(), containsString("near-empty ByteKeyRange")); - continue; - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java deleted file mode 100644 index f5c5d67d7b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTest.java +++ /dev/null @@ -1,396 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.common.collect.ImmutableList; -import com.google.protobuf.ByteString; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for {@link ByteKeyRange}. - */ -@RunWith(JUnit4.class) -public class ByteKeyRangeTest { - // A set of ranges for testing. - private static final ByteKeyRange RANGE_1_10 = ByteKeyRange.of(ByteKey.of(1), ByteKey.of(10)); - private static final ByteKeyRange RANGE_5_10 = ByteKeyRange.of(ByteKey.of(5), ByteKey.of(10)); - private static final ByteKeyRange RANGE_5_50 = ByteKeyRange.of(ByteKey.of(5), ByteKey.of(50)); - private static final ByteKeyRange RANGE_10_50 = ByteKeyRange.of(ByteKey.of(10), ByteKey.of(50)); - private static final ByteKeyRange UP_TO_1 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(1)); - private static final ByteKeyRange UP_TO_5 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(5)); - private static final ByteKeyRange UP_TO_10 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(10)); - private static final ByteKeyRange UP_TO_50 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(50)); - private static final ByteKeyRange AFTER_1 = ByteKeyRange.of(ByteKey.of(1), ByteKey.EMPTY); - private static final ByteKeyRange AFTER_5 = ByteKeyRange.of(ByteKey.of(5), ByteKey.EMPTY); - private static final ByteKeyRange AFTER_10 = ByteKeyRange.of(ByteKey.of(10), ByteKey.EMPTY); - private static final ByteKeyRange[] TEST_RANGES = - new ByteKeyRange[] { - ByteKeyRange.ALL_KEYS, - RANGE_1_10, - RANGE_5_10, - RANGE_5_50, - RANGE_10_50, - UP_TO_1, - UP_TO_5, - UP_TO_10, - UP_TO_50, - AFTER_1, - AFTER_5, - AFTER_10, - }; - - static final ByteKey[] RANGE_TEST_KEYS = - ImmutableList.builder() - .addAll(Arrays.asList(ByteKeyTest.TEST_KEYS)) - .add(ByteKey.EMPTY) - .build() - .toArray(ByteKeyTest.TEST_KEYS); - - /** - * Tests that the two ranges do not overlap, passing each in as the first range in the comparison. - */ - private static void bidirectionalNonOverlap(ByteKeyRange left, ByteKeyRange right) { - bidirectionalOverlapHelper(left, right, false); - } - - /** - * Tests that the two ranges overlap, passing each in as the first range in the comparison. - */ - private static void bidirectionalOverlap(ByteKeyRange left, ByteKeyRange right) { - bidirectionalOverlapHelper(left, right, true); - } - - /** - * Helper function for tests with a good error message. - */ - private static void bidirectionalOverlapHelper( - ByteKeyRange left, ByteKeyRange right, boolean result) { - assertEquals(String.format("%s overlaps %s", left, right), result, left.overlaps(right)); - assertEquals(String.format("%s overlaps %s", right, left), result, right.overlaps(left)); - } - - /** - * Tests of {@link ByteKeyRange#overlaps(ByteKeyRange)} with cases that should return true. - */ - @Test - public void testOverlappingRanges() { - bidirectionalOverlap(ByteKeyRange.ALL_KEYS, ByteKeyRange.ALL_KEYS); - bidirectionalOverlap(ByteKeyRange.ALL_KEYS, RANGE_1_10); - bidirectionalOverlap(UP_TO_1, UP_TO_1); - bidirectionalOverlap(UP_TO_1, UP_TO_5); - bidirectionalOverlap(UP_TO_50, AFTER_10); - bidirectionalOverlap(UP_TO_50, RANGE_1_10); - bidirectionalOverlap(UP_TO_10, UP_TO_50); - bidirectionalOverlap(RANGE_1_10, RANGE_5_50); - bidirectionalOverlap(AFTER_1, AFTER_5); - bidirectionalOverlap(RANGE_5_10, RANGE_1_10); - bidirectionalOverlap(RANGE_5_10, RANGE_5_50); - } - - /** - * Tests of {@link ByteKeyRange#overlaps(ByteKeyRange)} with cases that should return false. - */ - @Test - public void testNonOverlappingRanges() { - bidirectionalNonOverlap(UP_TO_1, AFTER_1); - bidirectionalNonOverlap(UP_TO_1, AFTER_5); - bidirectionalNonOverlap(RANGE_5_10, RANGE_10_50); - } - - /** - * Verifies that all keys in the given list are strictly ordered by size. - */ - private static void ensureOrderedKeys(List keys) { - for (int i = 0; i < keys.size() - 1; ++i) { - // This will throw if these two keys do not form a valid range. - ByteKeyRange.of(keys.get(i), keys.get(i + 1)); - // Also, a key is only allowed empty if it is the first key. - if (i > 0 && keys.get(i).isEmpty()) { - fail(String.format("Intermediate key %s/%s may not be empty", i, keys.size())); - } - } - } - - /** Tests for {@link ByteKeyRange#split(int)} with invalid inputs. */ - @Test - public void testRejectsInvalidSplit() { - try { - fail(String.format("%s.split(0) should fail: %s", RANGE_1_10, RANGE_1_10.split(0))); - } catch (IllegalArgumentException expected) { - // pass - } - - try { - fail(String.format("%s.split(-3) should fail: %s", RANGE_1_10, RANGE_1_10.split(-3))); - } catch (IllegalArgumentException expected) { - // pass - } - } - - /** Tests for {@link ByteKeyRange#split(int)} with weird inputs. */ - @Test - public void testSplitSpecialInputs() { - // Range split by 1 returns list of its keys. - assertEquals( - "Split 1 should return input", - ImmutableList.of(RANGE_1_10.getStartKey(), RANGE_1_10.getEndKey()), - RANGE_1_10.split(1)); - - // Unsplittable range returns list of its keys. - ByteKeyRange unsplittable = ByteKeyRange.of(ByteKey.of(), ByteKey.of(0, 0, 0, 0)); - assertEquals( - "Unsplittable should return input", - ImmutableList.of(unsplittable.getStartKey(), unsplittable.getEndKey()), - unsplittable.split(5)); - } - - /** Tests for {@link ByteKeyRange#split(int)}. */ - @Test - public void testSplitKeysCombinatorial() { - List sizes = ImmutableList.of(1, 2, 5, 10, 25, 32, 64); - for (int i = 0; i < RANGE_TEST_KEYS.length; ++i) { - for (int j = i + 1; j < RANGE_TEST_KEYS.length; ++j) { - ByteKeyRange range = ByteKeyRange.of(RANGE_TEST_KEYS[i], RANGE_TEST_KEYS[j]); - for (int s : sizes) { - List splits = range.split(s); - ensureOrderedKeys(splits); - assertThat("At least two entries in splits", splits.size(), greaterThanOrEqualTo(2)); - assertEquals("First split equals start of range", splits.get(0), RANGE_TEST_KEYS[i]); - assertEquals( - "Last split equals end of range", splits.get(splits.size() - 1), RANGE_TEST_KEYS[j]); - } - } - } - } - - /** Manual tests for {@link ByteKeyRange#estimateFractionForKey}. */ - @Test - public void testEstimateFractionForKey() { - final double delta = 0.0000001; - - /* 0x80 is halfway between [] and [] */ - assertEquals(0.5, ByteKeyRange.ALL_KEYS.estimateFractionForKey(ByteKey.of(0x80)), delta); - - /* 0x80 is halfway between [00] and [] */ - ByteKeyRange after0 = ByteKeyRange.of(ByteKey.of(0), ByteKey.EMPTY); - assertEquals(0.5, after0.estimateFractionForKey(ByteKey.of(0x80)), delta); - - /* 0x80 is halfway between [0000] and [] */ - ByteKeyRange after00 = ByteKeyRange.of(ByteKey.of(0, 0), ByteKey.EMPTY); - assertEquals(0.5, after00.estimateFractionForKey(ByteKey.of(0x80)), delta); - - /* 0x7f is halfway between [] and [fe] */ - ByteKeyRange upToFE = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0xfe)); - assertEquals(0.5, upToFE.estimateFractionForKey(ByteKey.of(0x7f)), delta); - - /* 0x40 is one-quarter of the way between [] and [] */ - assertEquals(0.25, ByteKeyRange.ALL_KEYS.estimateFractionForKey(ByteKey.of(0x40)), delta); - - /* 0x40 is one-half of the way between [] and [0x80] */ - ByteKeyRange upTo80 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0x80)); - assertEquals(0.50, upTo80.estimateFractionForKey(ByteKey.of(0x40)), delta); - - /* 0x40 is one-half of the way between [0x30] and [0x50] */ - ByteKeyRange range30to50 = ByteKeyRange.of(ByteKey.of(0x30), ByteKey.of(0x50)); - assertEquals(0.50, range30to50.estimateFractionForKey(ByteKey.of(0x40)), delta); - - /* 0x40 is one-half of the way between [0x30, 0, 1] and [0x4f, 0xff, 0xff, 0, 0] */ - ByteKeyRange range31to4f = - ByteKeyRange.of(ByteKey.of(0x30, 0, 1), ByteKey.of(0x4f, 0xff, 0xff, 0, 0)); - assertEquals(0.50, range31to4f.estimateFractionForKey(ByteKey.of(0x40)), delta); - - /* Exact fractions from 0 to 47 for a prime range. */ - ByteKeyRange upTo47 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(47)); - for (int i = 0; i <= 47; ++i) { - assertEquals("i=" + i, i / 47.0, upTo47.estimateFractionForKey(ByteKey.of(i)), delta); - } - - /* Exact fractions from 0 to 83 for a prime range. */ - ByteKeyRange rangeFDECtoFDEC83 = - ByteKeyRange.of(ByteKey.of(0xfd, 0xec), ByteKey.of(0xfd, 0xec, 83)); - for (int i = 0; i <= 83; ++i) { - assertEquals( - "i=" + i, - i / 83.0, - rangeFDECtoFDEC83.estimateFractionForKey(ByteKey.of(0xfd, 0xec, i)), - delta); - } - } - - /** Manual tests for {@link ByteKeyRange#interpolateKey}. */ - @Test - public void testInterpolateKey() { - /* 0x80 is halfway between [] and [] */ - assertEqualExceptPadding(ByteKey.of(0x80), ByteKeyRange.ALL_KEYS.interpolateKey(0.5)); - - /* 0x80 is halfway between [00] and [] */ - ByteKeyRange after0 = ByteKeyRange.of(ByteKey.of(0), ByteKey.EMPTY); - assertEqualExceptPadding(ByteKey.of(0x80), after0.interpolateKey(0.5)); - - /* 0x80 is halfway between [0000] and [] -- padding to longest key */ - ByteKeyRange after00 = ByteKeyRange.of(ByteKey.of(0, 0), ByteKey.EMPTY); - assertEqualExceptPadding(ByteKey.of(0x80), after00.interpolateKey(0.5)); - - /* 0x7f is halfway between [] and [fe] */ - ByteKeyRange upToFE = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0xfe)); - assertEqualExceptPadding(ByteKey.of(0x7f), upToFE.interpolateKey(0.5)); - - /* 0x40 is one-quarter of the way between [] and [] */ - assertEqualExceptPadding(ByteKey.of(0x40), ByteKeyRange.ALL_KEYS.interpolateKey(0.25)); - - /* 0x40 is halfway between [] and [0x80] */ - ByteKeyRange upTo80 = ByteKeyRange.of(ByteKey.EMPTY, ByteKey.of(0x80)); - assertEqualExceptPadding(ByteKey.of(0x40), upTo80.interpolateKey(0.5)); - - /* 0x40 is halfway between [0x30] and [0x50] */ - ByteKeyRange range30to50 = ByteKeyRange.of(ByteKey.of(0x30), ByteKey.of(0x50)); - assertEqualExceptPadding(ByteKey.of(0x40), range30to50.interpolateKey(0.5)); - - /* 0x40 is halfway between [0x30, 0, 1] and [0x4f, 0xff, 0xff, 0, 0] */ - ByteKeyRange range31to4f = - ByteKeyRange.of(ByteKey.of(0x30, 0, 1), ByteKey.of(0x4f, 0xff, 0xff, 0, 0)); - assertEqualExceptPadding(ByteKey.of(0x40), range31to4f.interpolateKey(0.5)); - } - - /** Tests that {@link ByteKeyRange#interpolateKey} does not return the empty key. */ - @Test - public void testInterpolateKeyIsNotEmpty() { - String fmt = "Interpolating %s at fraction 0.0 should not return the empty key"; - for (ByteKeyRange range : TEST_RANGES) { - range = ByteKeyRange.ALL_KEYS; - assertFalse(String.format(fmt, range), range.interpolateKey(0.0).isEmpty()); - } - } - - /** Test {@link ByteKeyRange} getters. */ - @Test - public void testKeyGetters() { - // [1,) - assertEquals(AFTER_1.getStartKey(), ByteKey.of(1)); - assertEquals(AFTER_1.getEndKey(), ByteKey.EMPTY); - // [1, 10) - assertEquals(RANGE_1_10.getStartKey(), ByteKey.of(1)); - assertEquals(RANGE_1_10.getEndKey(), ByteKey.of(10)); - // [, 10) - assertEquals(UP_TO_10.getStartKey(), ByteKey.EMPTY); - assertEquals(UP_TO_10.getEndKey(), ByteKey.of(10)); - } - - /** Test {@link ByteKeyRange#toString}. */ - @Test - public void testToString() { - assertEquals("ByteKeyRange{startKey=[], endKey=[0a]}", UP_TO_10.toString()); - } - - /** Test {@link ByteKeyRange#equals}. */ - @Test - public void testEquals() { - // Verify that the comparison gives the correct result for all values in both directions. - for (int i = 0; i < TEST_RANGES.length; ++i) { - for (int j = 0; j < TEST_RANGES.length; ++j) { - ByteKeyRange left = TEST_RANGES[i]; - ByteKeyRange right = TEST_RANGES[j]; - boolean eq = left.equals(right); - if (i == j) { - assertTrue(String.format("Expected that %s is equal to itself.", left), eq); - assertTrue( - String.format("Expected that %s is equal to a copy of itself.", left), - left.equals(ByteKeyRange.of(right.getStartKey(), right.getEndKey()))); - } else { - assertFalse(String.format("Expected that %s is not equal to %s", left, right), eq); - } - } - } - } - - /** Test that {@link ByteKeyRange#of} rejects invalid ranges. */ - @Test - public void testRejectsInvalidRanges() { - ByteKey[] testKeys = ByteKeyTest.TEST_KEYS; - for (int i = 0; i < testKeys.length; ++i) { - for (int j = i; j < testKeys.length; ++j) { - if (testKeys[i].isEmpty() || testKeys[j].isEmpty()) { - continue; // these are valid ranges. - } - try { - ByteKeyRange range = ByteKeyRange.of(testKeys[j], testKeys[i]); - fail(String.format("Expected failure constructing %s", range)); - } catch (IllegalArgumentException expected) { - // pass - } - } - } - } - - /** Test {@link ByteKeyRange#hashCode}. */ - @Test - public void testHashCode() { - // Verify that the hashCode is equal when i==j, and usually not equal otherwise. - int collisions = 0; - for (int i = 0; i < TEST_RANGES.length; ++i) { - ByteKeyRange current = TEST_RANGES[i]; - int left = current.hashCode(); - int leftClone = ByteKeyRange.of(current.getStartKey(), current.getEndKey()).hashCode(); - assertEquals( - String.format("Expected same hash code for %s and a copy of itself", current), - left, - leftClone); - for (int j = i + 1; j < TEST_RANGES.length; ++j) { - int right = TEST_RANGES[j].hashCode(); - if (left == right) { - ++collisions; - } - } - } - int totalUnequalTests = TEST_RANGES.length * (TEST_RANGES.length - 1) / 2; - assertThat("Too many hash collisions", collisions, lessThan(totalUnequalTests / 2)); - } - - /** Asserts the two keys are equal except trailing zeros. */ - private static void assertEqualExceptPadding(ByteKey expected, ByteKey key) { - ByteString shortKey = expected.getValue(); - ByteString longKey = key.getValue(); - if (shortKey.size() > longKey.size()) { - shortKey = key.getValue(); - longKey = expected.getValue(); - } - for (int i = 0; i < shortKey.size(); ++i) { - if (shortKey.byteAt(i) != longKey.byteAt(i)) { - fail(String.format("Expected %s (up to trailing zeros), got %s", expected, key)); - } - } - for (int j = shortKey.size(); j < longKey.size(); ++j) { - if (longKey.byteAt(j) != 0) { - fail(String.format("Expected %s (up to trailing zeros), got %s", expected, key)); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java deleted file mode 100644 index 076debe09c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyRangeTrackerTest.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link ByteKeyRangeTracker}. */ -@RunWith(JUnit4.class) -public class ByteKeyRangeTrackerTest { - private static final ByteKey BEFORE_START_KEY = ByteKey.of(0x11); - private static final ByteKey INITIAL_START_KEY = ByteKey.of(0x12); - private static final ByteKey AFTER_START_KEY = ByteKey.of(0x13); - private static final ByteKey INITIAL_MIDDLE_KEY = ByteKey.of(0x23); - private static final ByteKey NEW_START_KEY = ByteKey.of(0x14); - private static final ByteKey NEW_MIDDLE_KEY = ByteKey.of(0x24); - private static final ByteKey BEFORE_END_KEY = ByteKey.of(0x33); - private static final ByteKey END_KEY = ByteKey.of(0x34); - private static final double INITIAL_RANGE_SIZE = 0x34 - 0x12; - private static final ByteKeyRange INITIAL_RANGE = ByteKeyRange.of(INITIAL_START_KEY, END_KEY); - private static final double NEW_RANGE_SIZE = 0x34 - 0x14; - private static final ByteKeyRange NEW_RANGE = ByteKeyRange.of(NEW_START_KEY, END_KEY); - - @Rule public final ExpectedException expected = ExpectedException.none(); - - /** Tests for {@link ByteKeyRangeTracker#toString}. */ - @Test - public void testToString() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - String expected = String.format("ByteKeyRangeTracker{range=%s, position=null}", INITIAL_RANGE); - assertEquals(expected, tracker.toString()); - - tracker.tryReturnRecordAt(true, INITIAL_START_KEY); - tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY); - expected = - String.format("ByteKeyRangeTracker{range=%s, position=%s}", INITIAL_RANGE, - INITIAL_MIDDLE_KEY); - assertEquals(expected, tracker.toString()); - } - - /** Tests for updating the start key to the first record returned. */ - @Test - public void testUpdateStartKey() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - - tracker.tryReturnRecordAt(true, NEW_START_KEY); - String expected = - String.format("ByteKeyRangeTracker{range=%s, position=%s}", NEW_RANGE, NEW_START_KEY); - assertEquals(expected, tracker.toString()); - } - - /** Tests for {@link ByteKeyRangeTracker#of}. */ - @Test - public void testBuilding() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - - assertEquals(INITIAL_START_KEY, tracker.getStartPosition()); - assertEquals(END_KEY, tracker.getStopPosition()); - } - - /** Tests for {@link ByteKeyRangeTracker#getFractionConsumed()}. */ - @Test - public void testGetFractionConsumed() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - double delta = 0.00001; - - assertEquals(0.0, tracker.getFractionConsumed(), delta); - - tracker.tryReturnRecordAt(true, INITIAL_START_KEY); - assertEquals(0.0, tracker.getFractionConsumed(), delta); - - tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY); - assertEquals(0.5, tracker.getFractionConsumed(), delta); - - tracker.tryReturnRecordAt(true, BEFORE_END_KEY); - assertEquals(1 - 1 / INITIAL_RANGE_SIZE, tracker.getFractionConsumed(), delta); - } - - /** Tests for {@link ByteKeyRangeTracker#getFractionConsumed()} with updated start key. */ - @Test - public void testGetFractionConsumedUpdateStartKey() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - double delta = 0.00001; - - tracker.tryReturnRecordAt(true, NEW_START_KEY); - assertEquals(0.0, tracker.getFractionConsumed(), delta); - - tracker.tryReturnRecordAt(true, NEW_MIDDLE_KEY); - assertEquals(0.5, tracker.getFractionConsumed(), delta); - - tracker.tryReturnRecordAt(true, BEFORE_END_KEY); - assertEquals(1 - 1 / NEW_RANGE_SIZE, tracker.getFractionConsumed(), delta); - } - - /** Tests for {@link ByteKeyRangeTracker#tryReturnRecordAt}. */ - @Test - public void testTryReturnRecordAt() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - - // Should be able to emit at the same key twice, should that happen. - // Should be able to emit within range (in order, but system guarantees won't try out of order). - // Should not be able to emit past end of range. - - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); - - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); - - assertTrue(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); - - assertFalse(tracker.tryReturnRecordAt(true, END_KEY)); // after end - - assertFalse(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); // false because done - } - - @Test - public void testTryReturnFirstRecordNotSplitPoint() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(false, INITIAL_START_KEY); - } - - @Test - public void testTryReturnBeforeStartKey() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(true, BEFORE_START_KEY); - } - - @Test - public void testTryReturnBeforeLastReturnedRecord() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(true, AFTER_START_KEY); - } - - /** Tests for {@link ByteKeyRangeTracker#trySplitAtPosition}. */ - @Test - public void testSplitAtPosition() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - - // Unstarted, should not split. - assertFalse(tracker.trySplitAtPosition(INITIAL_MIDDLE_KEY)); - - // Start it, split it before the end. - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); - assertTrue(tracker.trySplitAtPosition(BEFORE_END_KEY)); - assertEquals(BEFORE_END_KEY, tracker.getStopPosition()); - - // Should not be able to split it after the end. - assertFalse(tracker.trySplitAtPosition(END_KEY)); - - // Should not be able to split after emitting. - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); - assertFalse(tracker.trySplitAtPosition(INITIAL_MIDDLE_KEY)); - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY)); - } - - /** Tests for {@link ByteKeyRangeTracker#getSplitPointsConsumed()}. */ - @Test - public void testGetSplitPointsConsumed() { - ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); - assertEquals(0, tracker.getSplitPointsConsumed()); - - // Started, 0 split points consumed - assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY)); - assertEquals(0, tracker.getSplitPointsConsumed()); - - // Processing new split point, 1 split point consumed - assertTrue(tracker.tryReturnRecordAt(true, AFTER_START_KEY)); - assertEquals(1, tracker.getSplitPointsConsumed()); - - // Processing new non-split point, 1 split point consumed - assertTrue(tracker.tryReturnRecordAt(false, INITIAL_MIDDLE_KEY)); - assertEquals(1, tracker.getSplitPointsConsumed()); - - // Processing new split point, 2 split points consumed - assertTrue(tracker.tryReturnRecordAt(true, BEFORE_END_KEY)); - assertEquals(2, tracker.getSplitPointsConsumed()); - - // Mark tracker as done, 3 split points consumed - tracker.markDone(); - assertEquals(3, tracker.getSplitPointsConsumed()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java deleted file mode 100644 index 922ac5b803..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/ByteKeyTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.io.range; - -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** - * Tests of {@link ByteKey}. - */ -@RunWith(JUnit4.class) -public class ByteKeyTest { - /* A big list of byte[] keys, in ascending sorted order. */ - static final ByteKey[] TEST_KEYS = - new ByteKey[] { - ByteKey.EMPTY, - ByteKey.of(0), - ByteKey.of(0, 1), - ByteKey.of(0, 1, 1), - ByteKey.of(0, 1, 2), - ByteKey.of(0, 1, 2, 0xfe), - ByteKey.of(0, 1, 3, 0xfe), - ByteKey.of(0, 0xfe, 0xfe, 0xfe), - ByteKey.of(0, 0xfe, 0xfe, 0xff), - ByteKey.of(0, 0xfe, 0xff, 0), - ByteKey.of(0, 0xff, 0xff, 0), - ByteKey.of(0, 0xff, 0xff, 1), - ByteKey.of(0, 0xff, 0xff, 0xfe), - ByteKey.of(0, 0xff, 0xff, 0xff), - ByteKey.of(1), - ByteKey.of(1, 2), - ByteKey.of(1, 2, 3), - ByteKey.of(3), - ByteKey.of(0xdd), - ByteKey.of(0xfe), - ByteKey.of(0xfe, 0xfe), - ByteKey.of(0xfe, 0xff), - ByteKey.of(0xff), - ByteKey.of(0xff, 0), - ByteKey.of(0xff, 0xfe), - ByteKey.of(0xff, 0xff), - ByteKey.of(0xff, 0xff, 0xff), - ByteKey.of(0xff, 0xff, 0xff, 0xff), - }; - - /** - * Tests {@link ByteKey#compareTo(ByteKey)} using exhaustive testing within a large sorted list - * of keys. - */ - @Test - public void testCompareToExhaustive() { - // Verify that the comparison gives the correct result for all values in both directions. - for (int i = 0; i < TEST_KEYS.length; ++i) { - for (int j = 0; j < TEST_KEYS.length; ++j) { - ByteKey left = TEST_KEYS[i]; - ByteKey right = TEST_KEYS[j]; - int cmp = left.compareTo(right); - if (i < j && !(cmp < 0)) { - fail( - String.format( - "Expected that cmp(%s, %s) < 0, got %d [i=%d, j=%d]", left, right, cmp, i, j)); - } else if (i == j && !(cmp == 0)) { - fail( - String.format( - "Expected that cmp(%s, %s) == 0, got %d [i=%d, j=%d]", left, right, cmp, i, j)); - } else if (i > j && !(cmp > 0)) { - fail( - String.format( - "Expected that cmp(%s, %s) > 0, got %d [i=%d, j=%d]", left, right, cmp, i, j)); - } - } - } - } - - /** - * Tests {@link ByteKey#equals}. - */ - @Test - public void testEquals() { - // Verify that the comparison gives the correct result for all values in both directions. - for (int i = 0; i < TEST_KEYS.length; ++i) { - for (int j = 0; j < TEST_KEYS.length; ++j) { - ByteKey left = TEST_KEYS[i]; - ByteKey right = TEST_KEYS[j]; - boolean eq = left.equals(right); - if (i == j) { - assertTrue(String.format("Expected that %s is equal to itself.", left), eq); - assertTrue( - String.format("Expected that %s is equal to a copy of itself.", left), - left.equals(ByteKey.of(right.getValue()))); - } else { - assertFalse(String.format("Expected that %s is not equal to %s", left, right), eq); - } - } - } - } - - /** - * Tests {@link ByteKey#hashCode}. - */ - @Test - public void testHashCode() { - // Verify that the hashCode is equal when i==j, and usually not equal otherwise. - int collisions = 0; - for (int i = 0; i < TEST_KEYS.length; ++i) { - int left = TEST_KEYS[i].hashCode(); - int leftClone = ByteKey.of(TEST_KEYS[i].getValue()).hashCode(); - assertEquals( - String.format("Expected same hash code for %s and a copy of itself", TEST_KEYS[i]), - left, - leftClone); - for (int j = i + 1; j < TEST_KEYS.length; ++j) { - int right = TEST_KEYS[j].hashCode(); - if (left == right) { - ++collisions; - } - } - } - int totalUnequalTests = TEST_KEYS.length * (TEST_KEYS.length - 1) / 2; - assertThat("Too many hash collisions", collisions, lessThan(totalUnequalTests / 2)); - } - - /** - * Tests {@link ByteKey#toString}. - */ - @Test - public void testToString() { - assertEquals("[]", ByteKey.EMPTY.toString()); - assertEquals("[00]", ByteKey.of(0).toString()); - assertEquals("[0000]", ByteKey.of(0x00, 0x00).toString()); - assertEquals( - "[0123456789abcdef]", - ByteKey.of(0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef).toString()); - } - - /** - * Tests {@link ByteKey#isEmpty}. - */ - @Test - public void testIsEmpty() { - assertTrue("[] is empty", ByteKey.EMPTY.isEmpty()); - assertFalse("[00]", ByteKey.of(0).isEmpty()); - } - - /** - * Tests {@link ByteKey#getBytes}. - */ - @Test - public void testGetBytes() { - assertTrue("[] equal after getBytes", Arrays.equals(new byte[] {}, ByteKey.EMPTY.getBytes())); - assertTrue( - "[00] equal after getBytes", Arrays.equals(new byte[] {0x00}, ByteKey.of(0x00).getBytes())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java deleted file mode 100644 index acf14f23e1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/range/OffsetRangeTrackerTest.java +++ /dev/null @@ -1,236 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * icensed under the Apache icense, Version 2.0 (the "icense"); you may not - * use this file except in compliance with the icense. You may obtain a copy of - * the icense at - * - * http://www.apache.org/licenses/ICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the icense is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * icense for the specific language governing permissions and limitations under - * the icense. - ******************************************************************************/ - -package com.google.cloud.dataflow.sdk.io.range; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link OffsetRangeTracker}. - */ -@RunWith(JUnit4.class) -public class OffsetRangeTrackerTest { - @Rule public final ExpectedException expected = ExpectedException.none(); - - @Test - public void testUpdateStartOffset() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - assertEquals(100, tracker.getStartPosition().longValue()); - // Update start offset to first record returned - assertTrue(tracker.tryReturnRecordAt(true, 150)); - assertEquals(150, tracker.getStartPosition().longValue()); - assertTrue(tracker.tryReturnRecordAt(true, 180)); - assertEquals(150, tracker.getStartPosition().longValue()); - } - - @Test - public void testTryReturnRecordSimpleSparse() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - assertTrue(tracker.tryReturnRecordAt(true, 110)); - assertTrue(tracker.tryReturnRecordAt(true, 140)); - assertTrue(tracker.tryReturnRecordAt(true, 183)); - assertFalse(tracker.tryReturnRecordAt(true, 210)); - } - - @Test - public void testTryReturnRecordSimpleDense() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(3, 6); - assertTrue(tracker.tryReturnRecordAt(true, 3)); - assertTrue(tracker.tryReturnRecordAt(true, 4)); - assertTrue(tracker.tryReturnRecordAt(true, 5)); - assertFalse(tracker.tryReturnRecordAt(true, 6)); - } - - @Test - public void testTryReturnRecordContinuesUntilSplitPoint() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(9, 18); - // Return records with gaps of 2; every 3rd record is a split point. - assertTrue(tracker.tryReturnRecordAt(true, 10)); - assertTrue(tracker.tryReturnRecordAt(false, 12)); - assertTrue(tracker.tryReturnRecordAt(false, 14)); - assertTrue(tracker.tryReturnRecordAt(true, 16)); - // Out of range, but not a split point... - assertTrue(tracker.tryReturnRecordAt(false, 18)); - assertTrue(tracker.tryReturnRecordAt(false, 20)); - // Out of range AND a split point. - assertFalse(tracker.tryReturnRecordAt(true, 22)); - } - - @Test - public void testSplitAtOffsetFailsIfUnstarted() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - assertFalse(tracker.trySplitAtPosition(150)); - } - - @Test - public void testSplitAtOffset() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - assertTrue(tracker.tryReturnRecordAt(true, 110)); - // Example positions we shouldn't split at, when last record is [110, 130]: - assertFalse(tracker.trySplitAtPosition(109)); - assertFalse(tracker.trySplitAtPosition(110)); - assertFalse(tracker.trySplitAtPosition(200)); - assertFalse(tracker.trySplitAtPosition(210)); - // Example positions we *should* split at: - assertTrue(tracker.copy().trySplitAtPosition(111)); - assertTrue(tracker.copy().trySplitAtPosition(129)); - assertTrue(tracker.copy().trySplitAtPosition(130)); - assertTrue(tracker.copy().trySplitAtPosition(131)); - assertTrue(tracker.copy().trySplitAtPosition(150)); - assertTrue(tracker.copy().trySplitAtPosition(199)); - - // If we split at 170 and then at 150: - assertTrue(tracker.trySplitAtPosition(170)); - assertTrue(tracker.trySplitAtPosition(150)); - // Should be able to return a record starting before the new stop offset. - // Returning records starting at the same offset is ok. - assertTrue(tracker.copy().tryReturnRecordAt(true, 135)); - assertTrue(tracker.copy().tryReturnRecordAt(true, 135)); - // Should be able to return a record starting right before the new stop offset. - assertTrue(tracker.copy().tryReturnRecordAt(true, 149)); - // Should not be able to return a record starting at or after the new stop offset - assertFalse(tracker.tryReturnRecordAt(true, 150)); - assertFalse(tracker.tryReturnRecordAt(true, 151)); - // Should accept non-splitpoint records starting after stop offset. - assertTrue(tracker.tryReturnRecordAt(false, 152)); - assertTrue(tracker.tryReturnRecordAt(false, 160)); - assertFalse(tracker.tryReturnRecordAt(true, 171)); - } - - @Test - public void testGetPositionForFractionDense() throws Exception { - // Represents positions 3, 4, 5. - OffsetRangeTracker tracker = new OffsetRangeTracker(3, 6); - // [3, 3) represents from [0, 1/3) fraction of [3, 6) - assertEquals(3, tracker.getPositionForFractionConsumed(0.0)); - assertEquals(3, tracker.getPositionForFractionConsumed(1.0 / 6)); - assertEquals(3, tracker.getPositionForFractionConsumed(0.333)); - // [3, 4) represents from [0, 2/3) fraction of [3, 6) - assertEquals(4, tracker.getPositionForFractionConsumed(0.334)); - assertEquals(4, tracker.getPositionForFractionConsumed(0.666)); - // [3, 5) represents from [0, 1) fraction of [3, 6) - assertEquals(5, tracker.getPositionForFractionConsumed(0.667)); - assertEquals(5, tracker.getPositionForFractionConsumed(0.999)); - // The whole [3, 6) is consumed for fraction 1 - assertEquals(6, tracker.getPositionForFractionConsumed(1.0)); - } - - @Test - public void testGetPositionForFractionDenseUpdateStartOffset() throws Exception { - // Represents positions 3, 4, 5. - OffsetRangeTracker tracker = new OffsetRangeTracker(3, 6); - // [3, 3) represents from [0, 1/3) fraction of [3, 6) - assertEquals(3, tracker.getPositionForFractionConsumed(0.333)); - // Update start offset to 4 - assertTrue(tracker.tryReturnRecordAt(true, 4)); - // [4, 4) represents from [0, 1/2) fraction of [4, 6) - assertEquals(4, tracker.getPositionForFractionConsumed(0.0)); - assertEquals(4, tracker.getPositionForFractionConsumed(0.499)); - // [4, 5) represents from [0, 1) fraction of [4, 6) - assertEquals(5, tracker.getPositionForFractionConsumed(0.5)); - assertEquals(5, tracker.getPositionForFractionConsumed(0.999)); - // The whole [4, 6) is consumed for fraction 1 - assertEquals(6, tracker.getPositionForFractionConsumed(1.0)); - } - - @Test - public void testGetFractionConsumedDense() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(3, 6); - assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 3)); - assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 4)); - assertEquals(1.0 / 3, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 5)); - assertEquals(2.0 / 3, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(false /* non-split-point */, 6)); - assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(false /* non-split-point */, 7)); - assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); - assertFalse(tracker.tryReturnRecordAt(true, 7)); - } - - @Test - public void testGetFractionConsumedSparse() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 100)); - assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 110)); - // Consumed positions through 109 = total 10 positions of 100. - assertEquals(0.1, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 150)); - assertEquals(0.5, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 195)); - assertEquals(0.95, tracker.getFractionConsumed(), 1e-6); - assertFalse(tracker.tryReturnRecordAt(true, 200)); - assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); - } - - @Test - public void testGetFractionConsumedUpdateStartOffset() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - assertTrue(tracker.tryReturnRecordAt(true, 150)); - assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 160)); - assertEquals(0.2, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 180)); - assertEquals(0.6, tracker.getFractionConsumed(), 1e-6); - assertTrue(tracker.tryReturnRecordAt(true, 195)); - assertEquals(0.9, tracker.getFractionConsumed(), 1e-6); - assertFalse(tracker.tryReturnRecordAt(true, 200)); - assertEquals(1.0, tracker.getFractionConsumed(), 1e-6); - } - - @Test - public void testEverythingWithUnboundedRange() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, Long.MAX_VALUE); - assertTrue(tracker.tryReturnRecordAt(true, 150)); - assertTrue(tracker.tryReturnRecordAt(true, 250)); - assertEquals(0.0, tracker.getFractionConsumed(), 1e-6); - assertFalse(tracker.trySplitAtPosition(1000)); - try { - tracker.getPositionForFractionConsumed(0.5); - fail("getPositionForFractionConsumed should fail for an unbounded range"); - } catch (IllegalArgumentException e) { - // Expected. - } - } - - @Test - public void testTryReturnFirstRecordNotSplitPoint() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(false, 120); - } - - @Test - public void testTryReturnRecordNonMonotonic() throws Exception { - OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200); - tracker.tryReturnRecordAt(true, 120); - expected.expect(IllegalStateException.class); - tracker.tryReturnRecordAt(true, 110); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/user.avsc b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/user.avsc deleted file mode 100644 index 0cd9cee690..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/user.avsc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "namespace": "com.google.cloud.dataflow.sdk.io", - "type": "record", - "name": "AvroGeneratedUser", - "fields": [ - { "name": "name", "type": "string"}, - { "name": "favorite_number", "type": ["int", "null"]}, - { "name": "favorite_color", "type": ["string", "null"]} - ] -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptionsTest.java deleted file mode 100644 index 9fea097050..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineDebugOptionsTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link DataflowPipelineDebugOptions}. */ -@RunWith(JUnit4.class) -public class DataflowPipelineDebugOptionsTest { - @Test - public void testTransformNameMapping() throws Exception { - DataflowPipelineDebugOptions options = PipelineOptionsFactory - .fromArgs(new String[]{"--transformNameMapping={\"a\":\"b\",\"foo\":\"\",\"bar\":\"baz\"}"}) - .as(DataflowPipelineDebugOptions.class); - assertEquals(3, options.getTransformNameMapping().size()); - assertThat(options.getTransformNameMapping(), hasEntry("a", "b")); - assertThat(options.getTransformNameMapping(), hasEntry("foo", "")); - assertThat(options.getTransformNameMapping(), hasEntry("bar", "baz")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptionsTest.java deleted file mode 100644 index 0207ba4b07..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowPipelineOptionsTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.testing.ResetDateTimeProvider; -import com.google.cloud.dataflow.sdk.testing.RestoreSystemProperties; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link DataflowPipelineOptions}. */ -@RunWith(JUnit4.class) -public class DataflowPipelineOptionsTest { - @Rule public TestRule restoreSystemProperties = new RestoreSystemProperties(); - @Rule public ResetDateTimeProvider resetDateTimeProviderRule = new ResetDateTimeProvider(); - - @Test - public void testJobNameIsSet() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setJobName("TestJobName"); - assertEquals("TestJobName", options.getJobName()); - } - - @Test - public void testUserNameIsNotSet() { - resetDateTimeProviderRule.setDateTimeFixed("2014-12-08T19:07:06.698Z"); - System.getProperties().remove("user.name"); - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setAppName("TestApplication"); - assertEquals("testapplication--1208190706", options.getJobName()); - assertTrue(options.getJobName().length() <= 40); - } - - @Test - public void testAppNameAndUserNameAreLong() { - resetDateTimeProviderRule.setDateTimeFixed("2014-12-08T19:07:06.698Z"); - System.getProperties().put("user.name", "abcdeabcdeabcdeabcdeabcdeabcde"); - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setAppName("1234567890123456789012345678901234567890"); - assertEquals( - "a234567890123456789012345678901234567890-abcdeabcdeabcdeabcdeabcdeabcde-1208190706", - options.getJobName()); - } - - @Test - public void testAppNameIsLong() { - resetDateTimeProviderRule.setDateTimeFixed("2014-12-08T19:07:06.698Z"); - System.getProperties().put("user.name", "abcde"); - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setAppName("1234567890123456789012345678901234567890"); - assertEquals("a234567890123456789012345678901234567890-abcde-1208190706", options.getJobName()); - } - - @Test - public void testUserNameIsLong() { - resetDateTimeProviderRule.setDateTimeFixed("2014-12-08T19:07:06.698Z"); - System.getProperties().put("user.name", "abcdeabcdeabcdeabcdeabcdeabcde"); - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setAppName("1234567890"); - assertEquals("a234567890-abcdeabcdeabcdeabcdeabcdeabcde-1208190706", options.getJobName()); - } - - @Test - public void testUtf8UserNameAndApplicationNameIsNormalized() { - resetDateTimeProviderRule.setDateTimeFixed("2014-12-08T19:07:06.698Z"); - System.getProperties().put("user.name", "ði ıntəˈnæʃənəl "); - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setAppName("fəˈnɛtık əsoʊsiˈeıʃn"); - assertEquals("f00n0t0k00so0si0e00n-0i00nt00n000n0l0-1208190706", options.getJobName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptionsTest.java deleted file mode 100644 index 8b89abd2b1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowProfilingOptionsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link DataflowProfilingOptions}. - */ -@RunWith(JUnit4.class) -public class DataflowProfilingOptionsTest { - - private static final ObjectMapper MAPPER = new ObjectMapper(); - - @Test - public void testOptionsObject() throws Exception { - DataflowPipelineOptions options = PipelineOptionsFactory.fromArgs(new String[] { - "--enableProfilingAgent", "--profilingAgentConfiguration={\"interval\": 21}"}) - .as(DataflowPipelineOptions.class); - assertTrue(options.getEnableProfilingAgent()); - - String json = MAPPER.writeValueAsString(options); - assertThat(json, Matchers.containsString( - "\"profilingAgentConfiguration\":{\"interval\":21}")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptionsTest.java deleted file mode 100644 index 82ec48a5f5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/DataflowWorkerLoggingOptionsTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.Level.WARN; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions.WorkerLogLevelOverrides; -import com.google.common.collect.ImmutableMap; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link DataflowWorkerLoggingOptions}. */ -@RunWith(JUnit4.class) -public class DataflowWorkerLoggingOptionsTest { - private static final ObjectMapper MAPPER = new ObjectMapper(); - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testWorkerLogLevelOverrideWithInvalidLogLevel() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported log level"); - WorkerLogLevelOverrides.from(ImmutableMap.of("Name", "FakeLevel")); - } - - @Test - public void testWorkerLogLevelOverrideForClass() throws Exception { - assertEquals("{\"org.junit.Test\":\"WARN\"}", - MAPPER.writeValueAsString( - new WorkerLogLevelOverrides().addOverrideForClass(Test.class, WARN))); - } - - @Test - public void testWorkerLogLevelOverrideForPackage() throws Exception { - assertEquals("{\"org.junit\":\"WARN\"}", - MAPPER.writeValueAsString( - new WorkerLogLevelOverrides().addOverrideForPackage(Test.class.getPackage(), WARN))); - } - - @Test - public void testWorkerLogLevelOverrideForName() throws Exception { - assertEquals("{\"A\":\"WARN\"}", - MAPPER.writeValueAsString( - new WorkerLogLevelOverrides().addOverrideForName("A", WARN))); - } - - @Test - public void testSerializationAndDeserializationOf() throws Exception { - String testValue = "{\"A\":\"WARN\"}"; - assertEquals(testValue, - MAPPER.writeValueAsString( - MAPPER.readValue(testValue, WorkerLogLevelOverrides.class))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GcpOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GcpOptionsTest.java deleted file mode 100644 index 40024d082b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GcpOptionsTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.options.GcpOptions.DefaultProjectFactory; -import com.google.cloud.dataflow.sdk.testing.RestoreSystemProperties; -import com.google.common.collect.ImmutableMap; -import com.google.common.io.Files; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -/** Tests for {@link GcpOptions}. */ -@RunWith(JUnit4.class) -public class GcpOptionsTest { - @Rule public TestRule restoreSystemProperties = new RestoreSystemProperties(); - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Test - public void testGetProjectFromCloudSdkConfigEnv() throws Exception { - Map environment = - ImmutableMap.of("CLOUDSDK_CONFIG", tmpFolder.getRoot().getAbsolutePath()); - assertEquals("test-project", - runGetProjectTest(tmpFolder.newFile("properties"), environment)); - } - - @Test - public void testGetProjectFromAppDataEnv() throws Exception { - Map environment = - ImmutableMap.of("APPDATA", tmpFolder.getRoot().getAbsolutePath()); - System.setProperty("os.name", "windows"); - assertEquals("test-project", - runGetProjectTest(new File(tmpFolder.newFolder("gcloud"), "properties"), - environment)); - } - - @Test - public void testGetProjectFromUserHomeEnvOld() throws Exception { - Map environment = ImmutableMap.of(); - System.setProperty("user.home", tmpFolder.getRoot().getAbsolutePath()); - assertEquals("test-project", - runGetProjectTest( - new File(tmpFolder.newFolder(".config", "gcloud"), "properties"), - environment)); - } - - @Test - public void testGetProjectFromUserHomeEnv() throws Exception { - Map environment = ImmutableMap.of(); - System.setProperty("user.home", tmpFolder.getRoot().getAbsolutePath()); - assertEquals("test-project", - runGetProjectTest( - new File(tmpFolder.newFolder(".config", "gcloud", "configurations"), "config_default"), - environment)); - } - - @Test - public void testGetProjectFromUserHomeOldAndNewPrefersNew() throws Exception { - Map environment = ImmutableMap.of(); - System.setProperty("user.home", tmpFolder.getRoot().getAbsolutePath()); - makePropertiesFileWithProject(new File(tmpFolder.newFolder(".config", "gcloud"), "properties"), - "old-project"); - assertEquals("test-project", - runGetProjectTest( - new File(tmpFolder.newFolder(".config", "gcloud", "configurations"), "config_default"), - environment)); - } - - @Test - public void testUnableToGetDefaultProject() throws Exception { - System.setProperty("user.home", tmpFolder.getRoot().getAbsolutePath()); - DefaultProjectFactory projectFactory = spy(new DefaultProjectFactory()); - when(projectFactory.getEnvironment()).thenReturn(ImmutableMap.of()); - assertNull(projectFactory.create(PipelineOptionsFactory.create())); - } - - private static void makePropertiesFileWithProject(File path, String projectId) - throws IOException { - String properties = String.format("[core]%n" - + "account = test-account@google.com%n" - + "project = %s%n" - + "%n" - + "[dataflow]%n" - + "magic = true%n", projectId); - Files.write(properties, path, StandardCharsets.UTF_8); - } - - private static String runGetProjectTest(File path, Map environment) - throws Exception { - makePropertiesFileWithProject(path, "test-project"); - DefaultProjectFactory projectFactory = spy(new DefaultProjectFactory()); - when(projectFactory.getEnvironment()).thenReturn(environment); - return projectFactory.create(PipelineOptionsFactory.create()); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptionsTest.java deleted file mode 100644 index 3a16cf5dee..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/GoogleApiDebugOptionsTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import com.google.api.services.bigquery.Bigquery.Datasets.Delete; -import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Create; -import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Get; -import com.google.cloud.dataflow.sdk.options.GoogleApiDebugOptions.GoogleApiTracer; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.Transport; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link GoogleApiDebugOptions}. */ -@RunWith(JUnit4.class) -public class GoogleApiDebugOptionsTest { - @Test - public void testWhenTracingMatches() throws Exception { - String[] args = - new String[] {"--googleApiTrace={\"Projects.Jobs.Get\":\"GetTraceDestination\"}"}; - DataflowPipelineOptions options = - PipelineOptionsFactory.fromArgs(args).as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - - assertNotNull(options.getGoogleApiTrace()); - - Get request = - options.getDataflowClient().projects().jobs().get("testProjectId", "testJobId"); - assertEquals("GetTraceDestination", request.get("$trace")); - } - - @Test - public void testWhenTracingDoesNotMatch() throws Exception { - String[] args = new String[] {"--googleApiTrace={\"Projects.Jobs.Create\":\"testToken\"}"}; - DataflowPipelineOptions options = - PipelineOptionsFactory.fromArgs(args).as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - - assertNotNull(options.getGoogleApiTrace()); - - Get request = - options.getDataflowClient().projects().jobs().get("testProjectId", "testJobId"); - assertNull(request.get("$trace")); - } - - @Test - public void testWithMultipleTraces() throws Exception { - String[] args = new String[] { - "--googleApiTrace={\"Projects.Jobs.Create\":\"CreateTraceDestination\"," - + "\"Projects.Jobs.Get\":\"GetTraceDestination\"}"}; - DataflowPipelineOptions options = - PipelineOptionsFactory.fromArgs(args).as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - - assertNotNull(options.getGoogleApiTrace()); - - Get getRequest = - options.getDataflowClient().projects().jobs().get("testProjectId", "testJobId"); - assertEquals("GetTraceDestination", getRequest.get("$trace")); - - Create createRequest = - options.getDataflowClient().projects().jobs().create("testProjectId", null); - assertEquals("CreateTraceDestination", createRequest.get("$trace")); - } - - @Test - public void testMatchingAllDataflowCalls() throws Exception { - String[] args = new String[] {"--googleApiTrace={\"Dataflow\":\"TraceDestination\"}"}; - DataflowPipelineOptions options = - PipelineOptionsFactory.fromArgs(args).as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - - assertNotNull(options.getGoogleApiTrace()); - - Get getRequest = - options.getDataflowClient().projects().jobs().get("testProjectId", "testJobId"); - assertEquals("TraceDestination", getRequest.get("$trace")); - - Create createRequest = - options.getDataflowClient().projects().jobs().create("testProjectId", null); - assertEquals("TraceDestination", createRequest.get("$trace")); - } - - @Test - public void testMatchingAgainstClient() throws Exception { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - options.setGoogleApiTrace(new GoogleApiTracer().addTraceFor( - Transport.newDataflowClient(options).build(), "TraceDestination")); - - Get getRequest = - options.getDataflowClient().projects().jobs().get("testProjectId", "testJobId"); - assertEquals("TraceDestination", getRequest.get("$trace")); - - Delete deleteRequest = Transport.newBigQueryClient(options).build().datasets() - .delete("testProjectId", "testDatasetId"); - assertNull(deleteRequest.get("$trace")); - } - - @Test - public void testMatchingAgainstRequestType() throws Exception { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - options.setGoogleApiTrace(new GoogleApiTracer().addTraceFor( - Transport.newDataflowClient(options).build().projects().jobs() - .get("aProjectId", "aJobId"), "TraceDestination")); - - Get getRequest = - options.getDataflowClient().projects().jobs().get("testProjectId", "testJobId"); - assertEquals("TraceDestination", getRequest.get("$trace")); - - Create createRequest = - options.getDataflowClient().projects().jobs().create("testProjectId", null); - assertNull(createRequest.get("$trace")); - } - - @Test - public void testDeserializationAndSerializationOfGoogleApiTracer() throws Exception { - String serializedValue = "{\"Api\":\"Token\"}"; - ObjectMapper objectMapper = new ObjectMapper(); - assertEquals(serializedValue, - objectMapper.writeValueAsString( - objectMapper.readValue(serializedValue, GoogleApiTracer.class))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java deleted file mode 100644 index c0ddac59a4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryTest.java +++ /dev/null @@ -1,1418 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.RestoreSystemProperties; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ListMultimap; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** Tests for {@link PipelineOptionsFactory}. */ -@RunWith(JUnit4.class) -public class PipelineOptionsFactoryTest { - private static final Class> DEFAULT_RUNNER_CLASS = - DirectPipelineRunner.class; - - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Rule public TestRule restoreSystemProperties = new RestoreSystemProperties(); - @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(PipelineOptionsFactory.class); - - @Test - public void testAutomaticRegistrationOfPipelineOptions() { - assertTrue(PipelineOptionsFactory.getRegisteredOptions().contains(DirectPipelineOptions.class)); - } - - @Test - public void testAutomaticRegistrationOfRunners() { - assertEquals( - DEFAULT_RUNNER_CLASS, - PipelineOptionsFactory.getRegisteredRunners().get(DEFAULT_RUNNER_CLASS.getSimpleName())); - } - - @Test - public void testCreationFromSystemProperties() throws Exception { - System.getProperties().putAll(ImmutableMap - .builder() - .put("worker_id", "test_worker_id") - .put("job_id", "test_job_id") - // Set a non-default value for testing - .put("sdk_pipeline_options", "{\"options\":{\"numWorkers\":999}}") - .build()); - - @SuppressWarnings("deprecation") // testing deprecated functionality - DataflowWorkerHarnessOptions options = PipelineOptionsFactory.createFromSystemProperties(); - assertEquals("test_worker_id", options.getWorkerId()); - assertEquals("test_job_id", options.getJobId()); - assertEquals(999, options.getNumWorkers()); - } - - @Test - public void testAppNameIsSet() { - ApplicationNameOptions options = PipelineOptionsFactory.as(ApplicationNameOptions.class); - assertEquals(PipelineOptionsFactoryTest.class.getSimpleName(), options.getAppName()); - } - - /** A simple test interface. */ - public interface TestPipelineOptions extends PipelineOptions { - String getTestPipelineOption(); - void setTestPipelineOption(String value); - } - - @Test - public void testAppNameIsSetWhenUsingAs() { - TestPipelineOptions options = PipelineOptionsFactory.as(TestPipelineOptions.class); - assertEquals(PipelineOptionsFactoryTest.class.getSimpleName(), - options.as(ApplicationNameOptions.class).getAppName()); - } - - @Test - public void testManualRegistration() { - assertFalse(PipelineOptionsFactory.getRegisteredOptions().contains(TestPipelineOptions.class)); - PipelineOptionsFactory.register(TestPipelineOptions.class); - assertTrue(PipelineOptionsFactory.getRegisteredOptions().contains(TestPipelineOptions.class)); - } - - @Test - public void testDefaultRegistration() { - assertTrue(PipelineOptionsFactory.getRegisteredOptions().contains(PipelineOptions.class)); - } - - /** A test interface missing a getter. */ - public interface MissingGetter extends PipelineOptions { - void setObject(Object value); - } - - @Test - public void testMissingGetterThrows() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Expected getter for property [object] of type [java.lang.Object] on " - + "[com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$MissingGetter]."); - - PipelineOptionsFactory.as(MissingGetter.class); - } - - /** A test interface missing multiple getters. */ - public interface MissingMultipleGetters extends MissingGetter { - void setOtherObject(Object value); - } - - @Test - public void testMultipleMissingGettersThrows() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "missing property methods on [com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MissingMultipleGetters]"); - expectedException.expectMessage("getter for property [object] of type [java.lang.Object]"); - expectedException.expectMessage("getter for property [otherObject] of type [java.lang.Object]"); - - PipelineOptionsFactory.as(MissingMultipleGetters.class); - } - - /** A test interface missing a setter. */ - public interface MissingSetter extends PipelineOptions { - Object getObject(); - } - - @Test - public void testMissingSetterThrows() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Expected setter for property [object] of type [java.lang.Object] on " - + "[com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$MissingSetter]."); - - PipelineOptionsFactory.as(MissingSetter.class); - } - - /** A test interface missing multiple setters. */ - public interface MissingMultipleSetters extends MissingSetter { - Object getOtherObject(); - } - - @Test - public void testMissingMultipleSettersThrows() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "missing property methods on [com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MissingMultipleSetters]"); - expectedException.expectMessage("setter for property [object] of type [java.lang.Object]"); - expectedException.expectMessage("setter for property [otherObject] of type [java.lang.Object]"); - - PipelineOptionsFactory.as(MissingMultipleSetters.class); - } - - /** A test interface missing a setter and a getter. */ - public interface MissingGettersAndSetters extends MissingGetter { - Object getOtherObject(); - } - - @Test - public void testMissingGettersAndSettersThrows() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "missing property methods on [com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MissingGettersAndSetters]"); - expectedException.expectMessage("getter for property [object] of type [java.lang.Object]"); - expectedException.expectMessage("setter for property [otherObject] of type [java.lang.Object]"); - - PipelineOptionsFactory.as(MissingGettersAndSetters.class); - } - - /** A test interface with a type mismatch between the getter and setter. */ - public interface GetterSetterTypeMismatch extends PipelineOptions { - boolean getValue(); - void setValue(int value); - } - - @Test - public void testGetterSetterTypeMismatchThrows() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Type mismatch between getter and setter methods for property [value]. Getter is of type " - + "[boolean] whereas setter is of type [int]."); - - PipelineOptionsFactory.as(GetterSetterTypeMismatch.class); - } - - /** A test interface with multiple type mismatches between getters and setters. */ - public interface MultiGetterSetterTypeMismatch extends GetterSetterTypeMismatch { - long getOther(); - void setOther(String other); - } - - @Test - public void testMultiGetterSetterTypeMismatchThrows() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Type mismatches between getters and setters detected:"); - expectedException.expectMessage("Property [value]: Getter is of type " - + "[boolean] whereas setter is of type [int]."); - expectedException.expectMessage("Property [other]: Getter is of type [long] " - + "whereas setter is of type [class java.lang.String]."); - - PipelineOptionsFactory.as(MultiGetterSetterTypeMismatch.class); - } - - /** A test interface representing a composite interface. */ - public interface CombinedObject extends MissingGetter, MissingSetter { - } - - @Test - public void testHavingSettersGettersFromSeparateInterfacesIsValid() { - PipelineOptionsFactory.as(CombinedObject.class); - } - - /** A test interface that contains a non-bean style method. */ - public interface ExtraneousMethod extends PipelineOptions { - String extraneousMethod(int value, String otherValue); - } - - @Test - public void testHavingExtraneousMethodThrows() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Methods [extraneousMethod(int, String)] on " - + "[com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$ExtraneousMethod] " - + "do not conform to being bean properties."); - - PipelineOptionsFactory.as(ExtraneousMethod.class); - } - - /** A test interface that has a conflicting return type with its parent. */ - public interface ReturnTypeConflict extends CombinedObject { - @Override - String getObject(); - void setObject(String value); - } - - @Test - public void testReturnTypeConflictThrows() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Method [getObject] has multiple definitions [public abstract java.lang.Object " - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$MissingSetter" - + ".getObject(), public abstract java.lang.String " - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$ReturnTypeConflict" - + ".getObject()] with different return types for [" - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$ReturnTypeConflict]."); - PipelineOptionsFactory.as(ReturnTypeConflict.class); - } - - /** An interface to provide multiple methods with return type conflicts. */ - public interface MultiReturnTypeConflictBase extends CombinedObject { - Object getOther(); - void setOther(Object object); - } - - /** A test interface that has multiple conflicting return types with its parent. */ - public interface MultiReturnTypeConflict extends MultiReturnTypeConflictBase { - @Override - String getObject(); - void setObject(String value); - - @Override - Long getOther(); - void setOther(Long other); - } - - @Test - public void testMultipleReturnTypeConflictsThrows() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("[com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultiReturnTypeConflict]"); - expectedException.expectMessage( - "Methods with multiple definitions with different return types"); - expectedException.expectMessage("Method [getObject] has multiple definitions"); - expectedException.expectMessage("public abstract java.lang.Object " - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$" - + "MissingSetter.getObject()"); - expectedException.expectMessage( - "public abstract java.lang.String com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultiReturnTypeConflict.getObject()"); - expectedException.expectMessage("Method [getOther] has multiple definitions"); - expectedException.expectMessage("public abstract java.lang.Object " - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$" - + "MultiReturnTypeConflictBase.getOther()"); - expectedException.expectMessage( - "public abstract java.lang.Long com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultiReturnTypeConflict.getOther()"); - - PipelineOptionsFactory.as(MultiReturnTypeConflict.class); - } - - /** Test interface that has {@link JsonIgnore @JsonIgnore} on a setter for a property. */ - public interface SetterWithJsonIgnore extends PipelineOptions { - String getValue(); - @JsonIgnore - void setValue(String value); - } - - @Test - public void testSetterAnnotatedWithJsonIgnore() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Expected setter for property [value] to not be marked with @JsonIgnore on [com." - + "google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$SetterWithJsonIgnore]"); - PipelineOptionsFactory.as(SetterWithJsonIgnore.class); - } - - /** Test interface that has {@link JsonIgnore @JsonIgnore} on multiple setters. */ - public interface MultiSetterWithJsonIgnore extends SetterWithJsonIgnore { - Integer getOther(); - @JsonIgnore - void setOther(Integer other); - } - - @Test - public void testMultipleSettersAnnotatedWithJsonIgnore() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Found setters marked with @JsonIgnore:"); - expectedException.expectMessage( - "property [other] should not be marked with @JsonIgnore on [com" - + ".google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultiSetterWithJsonIgnore]"); - expectedException.expectMessage( - "property [value] should not be marked with @JsonIgnore on [com." - + "google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$SetterWithJsonIgnore]"); - PipelineOptionsFactory.as(MultiSetterWithJsonIgnore.class); - } - - /** - * This class is has a conflicting field with {@link CombinedObject} that doesn't have - * {@link JsonIgnore @JsonIgnore}. - */ - public interface GetterWithJsonIgnore extends PipelineOptions { - @JsonIgnore - Object getObject(); - void setObject(Object value); - } - - @Test - public void testNotAllGettersAnnotatedWithJsonIgnore() throws Exception { - // Initial construction is valid. - GetterWithJsonIgnore options = PipelineOptionsFactory.as(GetterWithJsonIgnore.class); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Expected getter for property [object] to be marked with @JsonIgnore on all [" - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$GetterWithJsonIgnore, " - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$MissingSetter], " - + "found only on [com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$GetterWithJsonIgnore]"); - - // When we attempt to convert, we should error at this moment. - options.as(CombinedObject.class); - } - - private interface MultiGetters extends PipelineOptions { - Object getObject(); - void setObject(Object value); - - @JsonIgnore - Integer getOther(); - void setOther(Integer value); - - Void getConsistent(); - void setConsistent(Void consistent); - } - - private interface MultipleGettersWithInconsistentJsonIgnore extends PipelineOptions { - @JsonIgnore - Object getObject(); - void setObject(Object value); - - Integer getOther(); - void setOther(Integer value); - - Void getConsistent(); - void setConsistent(Void consistent); - } - - @Test - public void testMultipleGettersWithInconsistentJsonIgnore() { - // Initial construction is valid. - MultiGetters options = PipelineOptionsFactory.as(MultiGetters.class); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property getters are inconsistently marked with @JsonIgnore:"); - expectedException.expectMessage( - "property [object] to be marked on all"); - expectedException.expectMessage("found only on [com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultiGetters]"); - expectedException.expectMessage( - "property [other] to be marked on all"); - expectedException.expectMessage("found only on [com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultipleGettersWithInconsistentJsonIgnore]"); - - expectedException.expectMessage(Matchers.anyOf( - containsString(java.util.Arrays.toString(new String[] - {"com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultipleGettersWithInconsistentJsonIgnore", - "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$MultiGetters"})), - containsString(java.util.Arrays.toString(new String[] - {"com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryTest$MultiGetters", - "com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$MultipleGettersWithInconsistentJsonIgnore"})))); - expectedException.expectMessage(not(containsString("property [consistent]"))); - - // When we attempt to convert, we should error immediately - options.as(MultipleGettersWithInconsistentJsonIgnore.class); - } - - @Test - public void testAppNameIsNotOverriddenWhenPassedInViaCommandLine() { - ApplicationNameOptions options = PipelineOptionsFactory - .fromArgs(new String[]{ "--appName=testAppName" }) - .as(ApplicationNameOptions.class); - assertEquals("testAppName", options.getAppName()); - } - - @Test - public void testPropertyIsSetOnRegisteredPipelineOptionNotPartOfOriginalInterface() { - PipelineOptions options = PipelineOptionsFactory - .fromArgs(new String[]{ "--project=testProject" }) - .create(); - assertEquals("testProject", options.as(GcpOptions.class).getProject()); - } - - /** A test interface containing all the primitives. */ - public interface Primitives extends PipelineOptions { - boolean getBoolean(); - void setBoolean(boolean value); - char getChar(); - void setChar(char value); - byte getByte(); - void setByte(byte value); - short getShort(); - void setShort(short value); - int getInt(); - void setInt(int value); - long getLong(); - void setLong(long value); - float getFloat(); - void setFloat(float value); - double getDouble(); - void setDouble(double value); - } - - @Test - public void testPrimitives() { - String[] args = new String[] { - "--boolean=true", - "--char=d", - "--byte=12", - "--short=300", - "--int=100000", - "--long=123890123890", - "--float=55.5", - "--double=12.3"}; - - Primitives options = PipelineOptionsFactory.fromArgs(args).as(Primitives.class); - assertTrue(options.getBoolean()); - assertEquals('d', options.getChar()); - assertEquals((byte) 12, options.getByte()); - assertEquals((short) 300, options.getShort()); - assertEquals(100000, options.getInt()); - assertEquals(123890123890L, options.getLong()); - assertEquals(55.5f, options.getFloat(), 0.0f); - assertEquals(12.3, options.getDouble(), 0.0); - } - - @Test - public void testBooleanShorthandArgument() { - String[] args = new String[] {"--boolean"}; - - Primitives options = PipelineOptionsFactory.fromArgs(args).as(Primitives.class); - assertTrue(options.getBoolean()); - } - - @Test - public void testEmptyValueNotAllowed() { - String[] args = new String[] { - "--byte="}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - PipelineOptionsFactory.fromArgs(args).as(Primitives.class); - } - - /** Enum used for testing PipelineOptions CLI parsing. */ - public enum TestEnum { - Value, Value2 - } - - /** A test interface containing all supported objects. */ - public interface Objects extends PipelineOptions { - Boolean getBoolean(); - void setBoolean(Boolean value); - Character getChar(); - void setChar(Character value); - Byte getByte(); - void setByte(Byte value); - Short getShort(); - void setShort(Short value); - Integer getInt(); - void setInt(Integer value); - Long getLong(); - void setLong(Long value); - Float getFloat(); - void setFloat(Float value); - Double getDouble(); - void setDouble(Double value); - String getString(); - void setString(String value); - String getEmptyString(); - void setEmptyString(String value); - Class getClassValue(); - void setClassValue(Class value); - TestEnum getEnum(); - void setEnum(TestEnum value); - ValueProvider getStringValue(); - void setStringValue(ValueProvider value); - ValueProvider getLongValue(); - void setLongValue(ValueProvider value); - ValueProvider getEnumValue(); - void setEnumValue(ValueProvider value); - } - - @Test - public void testObjects() { - String[] args = new String[] { - "--boolean=true", - "--char=d", - "--byte=12", - "--short=300", - "--int=100000", - "--long=123890123890", - "--float=55.5", - "--double=12.3", - "--string=stringValue", - "--emptyString=", - "--classValue=" + PipelineOptionsFactoryTest.class.getName(), - "--enum=" + TestEnum.Value, - "--stringValue=beam", - "--longValue=12389049585840", - "--enumValue=" + TestEnum.Value}; - - Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); - assertTrue(options.getBoolean()); - assertEquals(Character.valueOf('d'), options.getChar()); - assertEquals(Byte.valueOf((byte) 12), options.getByte()); - assertEquals(Short.valueOf((short) 300), options.getShort()); - assertEquals(Integer.valueOf(100000), options.getInt()); - assertEquals(Long.valueOf(123890123890L), options.getLong()); - assertEquals(Float.valueOf(55.5f), options.getFloat(), 0.0f); - assertEquals(Double.valueOf(12.3), options.getDouble(), 0.0); - assertEquals("stringValue", options.getString()); - assertTrue(options.getEmptyString().isEmpty()); - assertEquals(PipelineOptionsFactoryTest.class, options.getClassValue()); - assertEquals(TestEnum.Value, options.getEnum()); - assertEquals("beam", options.getStringValue().get()); - assertEquals(Long.valueOf(12389049585840L), options.getLongValue().get()); - assertEquals(TestEnum.Value, options.getEnumValue().get()); - } - - @Test - public void testStringValueProvider() { - String[] args = new String[] {"--stringValue=beam"}; - String[] emptyArgs = new String[] { "--stringValue="}; - Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); - assertEquals("beam", options.getStringValue().get()); - options = PipelineOptionsFactory.fromArgs(emptyArgs).as(Objects.class); - assertEquals("", options.getStringValue().get()); - } - - @Test - public void testLongValueProvider() { - String[] args = new String[] {"--longValue=12345678762"}; - String[] emptyArgs = new String[] {"--longValue="}; - Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); - assertEquals(Long.valueOf(12345678762L), options.getLongValue().get()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - PipelineOptionsFactory.fromArgs(emptyArgs).as(Objects.class); - } - - @Test - public void testEnumValueProvider() { - String[] args = new String[] {"--enumValue=" + TestEnum.Value}; - String[] emptyArgs = new String[] {"--enumValue="}; - Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); - assertEquals(TestEnum.Value, options.getEnumValue().get()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - PipelineOptionsFactory.fromArgs(emptyArgs).as(Objects.class); - } - - /** A test class for verifying JSON -> Object conversion. */ - public static class ComplexType { - String value; - String value2; - public ComplexType(@JsonProperty("key") String value, @JsonProperty("key2") String value2) { - this.value = value; - this.value2 = value2; - } - } - - /** A test interface for verifying JSON -> complex type conversion. */ - interface ComplexTypes extends PipelineOptions { - Map getMap(); - void setMap(Map value); - - ComplexType getObject(); - void setObject(ComplexType value); - - ValueProvider getObjectValue(); - void setObjectValue(ValueProvider value); - } - - @Test - public void testComplexTypes() { - String[] args = new String[] { - "--map={\"key\":\"value\",\"key2\":\"value2\"}", - "--object={\"key\":\"value\",\"key2\":\"value2\"}", - "--objectValue={\"key\":\"value\",\"key2\":\"value2\"}"}; - ComplexTypes options = PipelineOptionsFactory.fromArgs(args).as(ComplexTypes.class); - assertEquals(ImmutableMap.of("key", "value", "key2", "value2"), options.getMap()); - assertEquals("value", options.getObject().value); - assertEquals("value2", options.getObject().value2); - assertEquals("value", options.getObjectValue().get().value); - assertEquals("value2", options.getObjectValue().get().value2); - } - - @Test - public void testMissingArgument() { - String[] args = new String[] {}; - - Objects options = PipelineOptionsFactory.fromArgs(args).as(Objects.class); - assertNull(options.getString()); - } - - /** A test interface containing all supported array return types. */ - public interface Arrays extends PipelineOptions { - boolean[] getBoolean(); - void setBoolean(boolean[] value); - char[] getChar(); - void setChar(char[] value); - short[] getShort(); - void setShort(short[] value); - int[] getInt(); - void setInt(int[] value); - long[] getLong(); - void setLong(long[] value); - float[] getFloat(); - void setFloat(float[] value); - double[] getDouble(); - void setDouble(double[] value); - String[] getString(); - void setString(String[] value); - Class[] getClassValue(); - void setClassValue(Class[] value); - TestEnum[] getEnum(); - void setEnum(TestEnum[] value); - ValueProvider getStringValue(); - void setStringValue(ValueProvider value); - ValueProvider getLongValue(); - void setLongValue(ValueProvider value); - ValueProvider getEnumValue(); - void setEnumValue(ValueProvider value); - } - - @Test - @SuppressWarnings("rawtypes") - public void testArrays() { - String[] args = new String[] { - "--boolean=true", - "--boolean=true", - "--boolean=false", - "--char=d", - "--char=e", - "--char=f", - "--short=300", - "--short=301", - "--short=302", - "--int=100000", - "--int=100001", - "--int=100002", - "--long=123890123890", - "--long=123890123891", - "--long=123890123892", - "--float=55.5", - "--float=55.6", - "--float=55.7", - "--double=12.3", - "--double=12.4", - "--double=12.5", - "--string=stringValue1", - "--string=stringValue2", - "--string=stringValue3", - "--classValue=" + PipelineOptionsFactory.class.getName(), - "--classValue=" + PipelineOptionsFactoryTest.class.getName(), - "--enum=" + TestEnum.Value, - "--enum=" + TestEnum.Value2, - "--stringValue=abc", - "--stringValue=beam", - "--longValue=123890123890", - "--longValue=123890123891", - "--enumValue=" + TestEnum.Value, - "--enumValue=" + TestEnum.Value2}; - - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - boolean[] bools = options.getBoolean(); - assertTrue(bools[0] && bools[1] && !bools[2]); - assertArrayEquals(new char[] {'d', 'e', 'f'}, options.getChar()); - assertArrayEquals(new short[] {300, 301, 302}, options.getShort()); - assertArrayEquals(new int[] {100000, 100001, 100002}, options.getInt()); - assertArrayEquals(new long[] {123890123890L, 123890123891L, 123890123892L}, options.getLong()); - assertArrayEquals(new float[] {55.5f, 55.6f, 55.7f}, options.getFloat(), 0.0f); - assertArrayEquals(new double[] {12.3, 12.4, 12.5}, options.getDouble(), 0.0); - assertArrayEquals(new String[] {"stringValue1", "stringValue2", "stringValue3"}, - options.getString()); - assertArrayEquals(new Class[] {PipelineOptionsFactory.class, - PipelineOptionsFactoryTest.class}, - options.getClassValue()); - assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, options.getEnum()); - assertArrayEquals(new String[] {"abc", "beam"}, options.getStringValue().get()); - assertArrayEquals(new Long[] {123890123890L, 123890123891L}, options.getLongValue().get()); - assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, - options.getEnumValue().get()); - } - - @Test - @SuppressWarnings("rawtypes") - public void testEmptyInStringArrays() { - String[] args = new String[] { - "--string=", - "--string=", - "--string="}; - - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - assertArrayEquals(new String[] {"", "", ""}, - options.getString()); - } - - @Test - @SuppressWarnings("rawtypes") - public void testEmptyInStringArraysWithCommaList() { - String[] args = new String[] { - "--string=a,,b"}; - - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - assertArrayEquals(new String[] {"a", "", "b"}, - options.getString()); - } - - @Test - public void testEmptyInNonStringArrays() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - - String[] args = new String[] { - "--boolean=true", - "--boolean=", - "--boolean=false"}; - - PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - } - - @Test - public void testEmptyInNonStringArraysWithCommaList() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - - String[] args = new String[] { - "--int=1,,9"}; - PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - } - - @Test - public void testStringArrayValueProvider() { - String[] args = new String[] {"--stringValue=abc", "--stringValue=xyz"}; - String[] commaArgs = new String[]{"--stringValue=abc,xyz"}; - String[] emptyArgs = new String[] { "--stringValue=", "--stringValue="}; - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - assertArrayEquals(new String[]{"abc", "xyz"}, options.getStringValue().get()); - options = PipelineOptionsFactory.fromArgs(commaArgs).as(Arrays.class); - assertArrayEquals(new String[]{"abc", "xyz"}, options.getStringValue().get()); - options = PipelineOptionsFactory.fromArgs(emptyArgs).as(Arrays.class); - assertArrayEquals(new String[]{"", ""}, options.getStringValue().get()); - } - - @Test - public void testLongArrayValueProvider() { - String[] args = new String[] {"--longValue=12345678762", "--longValue=12345678763"}; - String[] commaArgs = new String[] {"--longValue=12345678762,12345678763"}; - String[] emptyArgs = new String[] {"--longValue=", "--longValue="}; - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - assertArrayEquals(new Long[] {12345678762L, 12345678763L}, options.getLongValue().get()); - options = PipelineOptionsFactory.fromArgs(commaArgs).as(Arrays.class); - assertArrayEquals(new Long[] {12345678762L, 12345678763L}, options.getLongValue().get()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - PipelineOptionsFactory.fromArgs(emptyArgs).as(Arrays.class); - } - - @Test - public void testEnumArrayValueProvider() { - String[] args = new String[] {"--enumValue=" + TestEnum.Value, - "--enumValue=" + TestEnum.Value2}; - String[] commaArgs = new String[] {"--enumValue=" + TestEnum.Value + "," + TestEnum.Value2}; - String[] emptyArgs = new String[] {"--enumValue="}; - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, - options.getEnumValue().get()); - options = PipelineOptionsFactory.fromArgs(commaArgs).as(Arrays.class); - assertArrayEquals(new TestEnum[] {TestEnum.Value, TestEnum.Value2}, - options.getEnumValue().get()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - PipelineOptionsFactory.fromArgs(emptyArgs).as(Arrays.class); - } - - @Test - public void testOutOfOrderArrays() { - String[] args = new String[] { - "--char=d", - "--boolean=true", - "--boolean=true", - "--char=e", - "--char=f", - "--boolean=false"}; - - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - boolean[] bools = options.getBoolean(); - assertTrue(bools[0] && bools[1] && !bools[2]); - assertArrayEquals(new char[] {'d', 'e', 'f'}, options.getChar()); - } - - /** A test interface containing all supported List return types. */ - public interface Lists extends PipelineOptions { - List getString(); - void setString(List value); - List getInteger(); - void setInteger(List value); - List getList(); - void setList(List value); - ValueProvider> getStringValue(); - void setStringValue(ValueProvider> value); - ValueProvider> getLongValue(); - void setLongValue(ValueProvider> value); - ValueProvider> getEnumValue(); - void setEnumValue(ValueProvider> value); - } - - @Test - public void testListRawDefaultsToString() { - String[] manyArgs = - new String[] {"--list=stringValue1", "--list=stringValue2", "--list=stringValue3"}; - String[] manyArgsWithEmptyString = - new String[] {"--list=stringValue1", "--list=", "--list=stringValue3"}; - - Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); - assertEquals(ImmutableList.of("stringValue1", "stringValue2", "stringValue3"), - options.getList()); - options = PipelineOptionsFactory.fromArgs(manyArgsWithEmptyString).as(Lists.class); - assertEquals(ImmutableList.of("stringValue1", "", "stringValue3"), - options.getList()); - } - - @Test - public void testListString() { - String[] manyArgs = - new String[] {"--string=stringValue1", "--string=stringValue2", "--string=stringValue3"}; - String[] oneArg = new String[] {"--string=stringValue1"}; - String[] emptyArg = new String[] {"--string="}; - - Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); - assertEquals(ImmutableList.of("stringValue1", "stringValue2", "stringValue3"), - options.getString()); - options = PipelineOptionsFactory.fromArgs(oneArg).as(Lists.class); - assertEquals(ImmutableList.of("stringValue1"), options.getString()); - options = PipelineOptionsFactory.fromArgs(emptyArg).as(Lists.class); - assertEquals(ImmutableList.of(""), options.getString()); - } - - @Test - public void testListInt() { - String[] manyArgs = - new String[] {"--integer=1", "--integer=2", "--integer=3"}; - String[] manyArgsShort = - new String[] {"--integer=1,2,3"}; - String[] oneArg = new String[] {"--integer=1"}; - String[] missingArg = new String[] {"--integer="}; - - Lists options = PipelineOptionsFactory.fromArgs(manyArgs).as(Lists.class); - assertEquals(ImmutableList.of(1, 2, 3), options.getInteger()); - options = PipelineOptionsFactory.fromArgs(manyArgsShort).as(Lists.class); - assertEquals(ImmutableList.of(1, 2, 3), options.getInteger()); - options = PipelineOptionsFactory.fromArgs(oneArg).as(Lists.class); - assertEquals(ImmutableList.of(1), options.getInteger()); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage("java.util.List")); - PipelineOptionsFactory.fromArgs(missingArg).as(Lists.class); - } - - @Test - public void testListShorthand() { - String[] args = new String[] {"--string=stringValue1,stringValue2,stringValue3"}; - - Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); - assertEquals(ImmutableList.of("stringValue1", "stringValue2", "stringValue3"), - options.getString()); - } - - @Test - public void testMixedShorthandAndLongStyleList() { - String[] args = new String[] { - "--char=d", - "--char=e", - "--char=f", - "--char=g,h,i", - "--char=j", - "--char=k", - "--char=l", - "--char=m,n,o"}; - - Arrays options = PipelineOptionsFactory.fromArgs(args).as(Arrays.class); - assertArrayEquals(new char[] {'d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'}, - options.getChar()); - } - - - @Test - public void testStringListValueProvider() { - String[] args = new String[] {"--stringValue=abc", "--stringValue=xyz"}; - String[] commaArgs = new String[]{"--stringValue=abc,xyz"}; - String[] emptyArgs = new String[] { "--stringValue=", "--stringValue="}; - Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); - assertEquals(ImmutableList.of("abc", "xyz"), options.getStringValue().get()); - options = PipelineOptionsFactory.fromArgs(commaArgs).as(Lists.class); - assertEquals(ImmutableList.of("abc", "xyz"), options.getStringValue().get()); - options = PipelineOptionsFactory.fromArgs(emptyArgs).as(Lists.class); - assertEquals(ImmutableList.of("", ""), options.getStringValue().get()); - } - - @Test - public void testLongListValueProvider() { - String[] args = new String[] {"--longValue=12345678762", "--longValue=12345678763"}; - String[] commaArgs = new String[] {"--longValue=12345678762,12345678763"}; - String[] emptyArgs = new String[] {"--longValue=", "--longValue="}; - Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); - assertEquals(ImmutableList.of(12345678762L, 12345678763L), options.getLongValue().get()); - options = PipelineOptionsFactory.fromArgs(commaArgs).as(Lists.class); - assertEquals(ImmutableList.of(12345678762L, 12345678763L), options.getLongValue().get()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - PipelineOptionsFactory.fromArgs(emptyArgs).as(Lists.class); - } - - @Test - public void testEnumListValueProvider() { - String[] args = new String[] {"--enumValue=" + TestEnum.Value, - "--enumValue=" + TestEnum.Value2}; - String[] commaArgs = new String[] {"--enumValue=" + TestEnum.Value + "," + TestEnum.Value2}; - String[] emptyArgs = new String[] {"--enumValue="}; - Lists options = PipelineOptionsFactory.fromArgs(args).as(Lists.class); - assertEquals(ImmutableList.of(TestEnum.Value, TestEnum.Value2), options.getEnumValue().get()); - options = PipelineOptionsFactory.fromArgs(commaArgs).as(Lists.class); - assertEquals(ImmutableList.of(TestEnum.Value, TestEnum.Value2), options.getEnumValue().get()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage()); - PipelineOptionsFactory.fromArgs(emptyArgs).as(Lists.class); - } - - @Test - public void testSetASingularAttributeUsingAListThrowsAnError() { - String[] args = new String[] { - "--diskSizeGb=100", - "--diskSizeGb=200"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("expected one element but was"); - PipelineOptionsFactory.fromArgs(args).create(); - } - - @Test - public void testSetASingularAttributeUsingAListIsIgnoredWithoutStrictParsing() { - String[] args = new String[] { - "--diskSizeGb=100", - "--diskSizeGb=200"}; - PipelineOptionsFactory.fromArgs(args).withoutStrictParsing().create(); - expectedLogs.verifyWarn("Strict parsing is disabled, ignoring option"); - } - - /** A test interface containing all supported List return types. */ - public interface Maps extends PipelineOptions { - Map getMap(); - void setMap(Map value); - - Map> getNestedMap(); - void setNestedMap(Map> value); - } - - @Test - public void testMapIntInt() { - String[] manyArgsShort = - new String[] {"--map={\"1\":1,\"2\":2}"}; - String[] oneArg = new String[] {"--map={\"1\":1}"}; - String[] missingArg = new String[] {"--map="}; - - Maps options = PipelineOptionsFactory.fromArgs(manyArgsShort).as(Maps.class); - assertEquals(ImmutableMap.of(1, 1, 2, 2), options.getMap()); - options = PipelineOptionsFactory.fromArgs(oneArg).as(Maps.class); - assertEquals(ImmutableMap.of(1, 1), options.getMap()); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage( - "java.util.Map")); - PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); - } - - @Test - public void testNestedMap() { - String[] manyArgsShort = - new String[] {"--nestedMap={\"1\":{\"1\":1},\"2\":{\"2\":2}}"}; - String[] oneArg = new String[] {"--nestedMap={\"1\":{\"1\":1}}"}; - String[] missingArg = new String[] {"--nestedMap="}; - - Maps options = PipelineOptionsFactory.fromArgs(manyArgsShort).as(Maps.class); - assertEquals(ImmutableMap.of(1, ImmutableMap.of(1, 1), - 2, ImmutableMap.of(2, 2)), - options.getNestedMap()); - options = PipelineOptionsFactory.fromArgs(oneArg).as(Maps.class); - assertEquals(ImmutableMap.of(1, ImmutableMap.of(1, 1)), - options.getNestedMap()); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(emptyStringErrorMessage( - "java.util.Map>")); - PipelineOptionsFactory.fromArgs(missingArg).as(Maps.class); - } - - @Test - public void testSettingRunner() { - String[] args = new String[] {"--runner=BlockingDataflowPipelineRunner"}; - - PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create(); - assertEquals(BlockingDataflowPipelineRunner.class, options.getRunner()); - } - - @Test - public void testSettingRunnerFullName() { - String[] args = - new String[] {String.format("--runner=%s", DataflowPipelineRunner.class.getName())}; - PipelineOptions opts = PipelineOptionsFactory.fromArgs(args).create(); - assertEquals(opts.getRunner(), DataflowPipelineRunner.class); - } - - @Test - public void testSettingUnknownRunner() { - String[] args = new String[] {"--runner=UnknownRunner"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Unknown 'runner' specified 'UnknownRunner', supported " + "pipeline runners"); - Set registeredRunners = PipelineOptionsFactory.getRegisteredRunners().keySet(); - assertThat(registeredRunners, hasItem(DEFAULT_RUNNER_CLASS.getSimpleName())); - for (String registeredRunner : registeredRunners) { - expectedException.expectMessage(registeredRunner); - } - - PipelineOptionsFactory.fromArgs(args).create(); - } - - private static class ExampleTestRunner extends PipelineRunner { - @Override - public PipelineResult run(Pipeline pipeline) { - return null; - } - } - - @Test - public void testSettingRunnerCanonicalClassNameNotInSupportedExists() { - String[] args = new String[] {String.format("--runner=%s", ExampleTestRunner.class.getName())}; - PipelineOptions opts = PipelineOptionsFactory.fromArgs(args).create(); - assertEquals(opts.getRunner(), ExampleTestRunner.class); - } - - @Test - public void testSettingRunnerCanonicalClassNameNotInSupportedNotPipelineRunner() { - String[] args = new String[] {"--runner=java.lang.String"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("does not implement PipelineRunner"); - expectedException.expectMessage("java.lang.String"); - - PipelineOptionsFactory.fromArgs(args).create(); - } - - @Test - public void testUsingArgumentWithUnknownPropertyIsNotAllowed() { - String[] args = new String[] {"--unknownProperty=value"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("missing a property named 'unknownProperty'"); - PipelineOptionsFactory.fromArgs(args).create(); - } - - interface SuggestedOptions extends PipelineOptions { - String getAbc(); - void setAbc(String value); - - String getAbcdefg(); - void setAbcdefg(String value); - } - - @Test - public void testUsingArgumentWithMisspelledPropertyGivesASuggestion() { - String[] args = new String[] {"--ab=value"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("missing a property named 'ab'. Did you mean 'abc'?"); - PipelineOptionsFactory.fromArgs(args).as(SuggestedOptions.class); - } - - @Test - public void testUsingArgumentWithMisspelledPropertyGivesMultipleSuggestions() { - String[] args = new String[] {"--abcde=value"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "missing a property named 'abcde'. Did you mean one of [abc, abcdefg]?"); - PipelineOptionsFactory.fromArgs(args).as(SuggestedOptions.class); - } - - @Test - public void testUsingArgumentWithUnknownPropertyIsIgnoredWithoutStrictParsing() { - String[] args = new String[] {"--unknownProperty=value"}; - PipelineOptionsFactory.fromArgs(args).withoutStrictParsing().create(); - expectedLogs.verifyWarn("missing a property named 'unknownProperty'"); - } - - @Test - public void testUsingArgumentStartingWithIllegalCharacterIsNotAllowed() { - String[] args = new String[] {" --diskSizeGb=100"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Argument ' --diskSizeGb=100' does not begin with '--'"); - PipelineOptionsFactory.fromArgs(args).create(); - } - - @Test - public void testUsingArgumentStartingWithIllegalCharacterIsIgnoredWithoutStrictParsing() { - String[] args = new String[] {" --diskSizeGb=100"}; - PipelineOptionsFactory.fromArgs(args).withoutStrictParsing().create(); - expectedLogs.verifyWarn("Strict parsing is disabled, ignoring option"); - } - - @Test - public void testEmptyArgumentIsIgnored() { - String[] args = - new String[] { - "", "--diskSizeGb=100", "", "", "--runner=" + DEFAULT_RUNNER_CLASS.getSimpleName() - }; - PipelineOptionsFactory.fromArgs(args).create(); - } - - @Test - public void testNullArgumentIsIgnored() { - String[] args = - new String[] { - "--diskSizeGb=100", null, null, "--runner=" + DEFAULT_RUNNER_CLASS.getSimpleName() - }; - PipelineOptionsFactory.fromArgs(args).create(); - } - - @Test - public void testUsingArgumentWithInvalidNameIsNotAllowed() { - String[] args = new String[] {"--=100"}; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Argument '--=100' starts with '--='"); - PipelineOptionsFactory.fromArgs(args).create(); - } - - @Test - public void testUsingArgumentWithInvalidNameIsIgnoredWithoutStrictParsing() { - String[] args = new String[] {"--=100"}; - PipelineOptionsFactory.fromArgs(args).withoutStrictParsing().create(); - expectedLogs.verifyWarn("Strict parsing is disabled, ignoring option"); - } - - @Test - public void testWhenNoHelpIsRequested() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - assertFalse(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertEquals("", output); - } - - @Test - public void testDefaultHelpAsArgument() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "true"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("The set of registered options are:")); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - assertThat(output, containsString("Use --help= for detailed help.")); - } - - @Test - public void testSpecificHelpAsArgument() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "com.google.cloud.dataflow.sdk.options.PipelineOptions"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); - assertThat(output, - containsString("The pipeline runner that will be used to execute the pipeline.")); - } - - @Test - public void testSpecificHelpAsArgumentWithSimpleClassName() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "PipelineOptions"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); - assertThat(output, - containsString("The pipeline runner that will be used to execute the pipeline.")); - } - - @Test - public void testSpecificHelpAsArgumentWithClassNameSuffix() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "options.PipelineOptions"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); - assertThat(output, - containsString("The pipeline runner that will be used to execute the pipeline.")); - } - - /** Used for a name collision test with the other DataflowPipelineOptions. */ - private interface DataflowPipelineOptions extends PipelineOptions { - } - - @Test - public void testShortnameSpecificHelpHasMultipleMatches() { - PipelineOptionsFactory.register(DataflowPipelineOptions.class); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "DataflowPipelineOptions"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("Multiple matches found for DataflowPipelineOptions")); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options." - + "PipelineOptionsFactoryTest$DataflowPipelineOptions")); - assertThat(output, containsString("The set of registered options are:")); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - } - - @Test - public void testHelpWithOptionThatOutputsValidEnumTypes() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "com.google.cloud.dataflow.sdk.options.DataflowWorkerLoggingOptions"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("")); - } - - @Test - public void testHelpWithBadOptionNameAsArgument() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "com.google.cloud.dataflow.sdk.Pipeline"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - assertThat(output, - containsString("Unable to find option com.google.cloud.dataflow.sdk.Pipeline")); - assertThat(output, containsString("The set of registered options are:")); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - } - - @Test - public void testHelpWithHiddenMethodAndInterface() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ListMultimap arguments = ArrayListMultimap.create(); - arguments.put("help", "com.google.cloud.dataflow.sdk.option.DataflowPipelineOptions"); - assertTrue(PipelineOptionsFactory.printHelpUsageAndExitIfNeeded( - arguments, new PrintStream(baos), false /* exit */)); - String output = new String(baos.toByteArray()); - // A hidden interface. - assertThat(output, not( - containsString("com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions"))); - // A hidden option. - assertThat(output, not(containsString("--gcpCredential"))); - } - - @Test - public void testProgrammaticPrintHelp() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PipelineOptionsFactory.printHelp(new PrintStream(baos)); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("The set of registered options are:")); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - } - - @Test - public void testProgrammaticPrintHelpForSpecificType() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PipelineOptionsFactory.printHelp(new PrintStream(baos), PipelineOptions.class); - String output = new String(baos.toByteArray()); - assertThat(output, containsString("com.google.cloud.dataflow.sdk.options.PipelineOptions")); - assertThat(output, containsString("--runner")); - assertThat(output, containsString("Default: " + DEFAULT_RUNNER_CLASS.getSimpleName())); - assertThat(output, - containsString("The pipeline runner that will be used to execute the pipeline.")); - } - - @Test - public void testFindProperClassLoaderIfContextClassLoaderIsNull() throws InterruptedException { - final ClassLoader[] classLoader = new ClassLoader[1]; - Thread thread = new Thread(new Runnable() { - - @Override - public void run() { - classLoader[0] = PipelineOptionsFactory.findClassLoader(); - } - }); - thread.setContextClassLoader(null); - thread.start(); - thread.join(); - assertEquals(PipelineOptionsFactory.class.getClassLoader(), classLoader[0]); - } - - @Test - public void testFindProperClassLoaderIfContextClassLoaderIsAvailable() - throws InterruptedException { - final ClassLoader[] classLoader = new ClassLoader[1]; - Thread thread = new Thread(new Runnable() { - - @Override - public void run() { - classLoader[0] = PipelineOptionsFactory.findClassLoader(); - } - }); - ClassLoader cl = new ClassLoader() {}; - thread.setContextClassLoader(cl); - thread.start(); - thread.join(); - assertEquals(cl, classLoader[0]); - } - - private String emptyStringErrorMessage() { - return emptyStringErrorMessage(null); - } - - private String emptyStringErrorMessage(String type) { - String msg = "Empty argument value is only allowed for String, String Array, " - + "Collections of Strings or any of these types in a parameterized ValueProvider"; - if (type != null) { - return String.format("%s, but received: %s", msg, type); - } else { - return msg; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java deleted file mode 100644 index cc0c861065..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsReflectorTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isOneOf; -import static org.hamcrest.Matchers.not; - -import com.google.common.collect.ImmutableSet; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.hamcrest.FeatureMatcher; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Set; - -/** - * Unit tests for {@link PipelineOptionsReflector}. - */ -@RunWith(JUnit4.class) -public class PipelineOptionsReflectorTest { - @Test - public void testGetOptionSpecs() throws NoSuchMethodException { - Set properties = - PipelineOptionsReflector.getOptionSpecs(SimpleOptions.class); - - assertThat(properties, Matchers.hasItems(PipelineOptionSpec.of( - SimpleOptions.class, "foo", SimpleOptions.class.getDeclaredMethod("getFoo")))); - } - - interface SimpleOptions extends PipelineOptions { - String getFoo(); - void setFoo(String value); - } - - @Test - public void testFiltersNonGetterMethods() { - Set properties = - PipelineOptionsReflector.getOptionSpecs(OnlyTwoValidGetters.class); - - assertThat(properties, not(hasItem(hasName(isOneOf("misspelled", "hasParameter", "prefix"))))); - } - - interface OnlyTwoValidGetters extends PipelineOptions { - String getFoo(); - void setFoo(String value); - - boolean isBar(); - void setBar(boolean value); - - String gtMisspelled(); - void setMisspelled(String value); - - String getHasParameter(String value); - void setHasParameter(String value); - - String noPrefix(); - void setNoPrefix(String value); - } - - @Test - public void testBaseClassOptions() { - Set props = - PipelineOptionsReflector.getOptionSpecs(ExtendsSimpleOptions.class); - - assertThat(props, Matchers.hasItem( - allOf(hasName("foo"), hasClass(SimpleOptions.class)))); - assertThat(props, Matchers.hasItem( - allOf(hasName("foo"), hasClass(ExtendsSimpleOptions.class)))); - assertThat(props, Matchers.hasItem( - allOf(hasName("bar"), hasClass(ExtendsSimpleOptions.class)))); - } - - interface ExtendsSimpleOptions extends SimpleOptions { - @Override String getFoo(); - @Override void setFoo(String value); - - String getBar(); - void setBar(String value); - } - - @Test - public void testExcludesNonPipelineOptionsMethods() { - Set properties = - PipelineOptionsReflector.getOptionSpecs(ExtendsNonPipelineOptions.class); - - assertThat(properties, not(hasItem(hasName("foo")))); - } - - interface NoExtendsClause { - String getFoo(); - void setFoo(String value); - } - - interface ExtendsNonPipelineOptions extends NoExtendsClause, PipelineOptions {} - - @Test - public void testExcludesHiddenInterfaces() { - Set properties = - PipelineOptionsReflector.getOptionSpecs(HiddenOptions.class); - - assertThat(properties, not(hasItem(hasName("foo")))); - } - - @Hidden - interface HiddenOptions extends PipelineOptions { - String getFoo(); - void setFoo(String value); - } - - @Test - public void testShouldSerialize() { - Set properties = - PipelineOptionsReflector.getOptionSpecs(JsonIgnoreOptions.class); - - assertThat(properties, hasItem(allOf(hasName("notIgnored"), shouldSerialize()))); - assertThat(properties, hasItem(allOf(hasName("ignored"), not(shouldSerialize())))); - } - - interface JsonIgnoreOptions extends PipelineOptions { - String getNotIgnored(); - void setNotIgnored(String value); - - @JsonIgnore - String getIgnored(); - void setIgnored(String value); - } - - @Test - public void testMultipleInputInterfaces() { - Set> interfaces = - ImmutableSet.>of( - BaseOptions.class, - ExtendOptions1.class, - ExtendOptions2.class); - - Set props = PipelineOptionsReflector.getOptionSpecs(interfaces); - - assertThat(props, Matchers.hasItem(allOf(hasName("baseOption"), hasClass(BaseOptions.class)))); - assertThat(props, Matchers.hasItem( - allOf(hasName("extendOption1"), hasClass(ExtendOptions1.class)))); - assertThat(props, Matchers.hasItem( - allOf(hasName("extendOption2"), hasClass(ExtendOptions2.class)))); - } - - interface BaseOptions extends PipelineOptions { - String getBaseOption(); - void setBaseOption(String value); - } - - interface ExtendOptions1 extends BaseOptions { - String getExtendOption1(); - void setExtendOption1(String value); - } - - interface ExtendOptions2 extends BaseOptions { - String getExtendOption2(); - void setExtendOption2(String value); - } - - private static Matcher hasName(String name) { - return hasName(is(name)); - } - - private static Matcher hasName(Matcher matcher) { - return new FeatureMatcher(matcher, "name", "name") { - @Override - protected String featureValueOf(PipelineOptionSpec actual) { - return actual.getName(); - } - }; - } - - private static Matcher hasClass(Class clazz) { - return new FeatureMatcher>( - Matchers.>is(clazz), "defining class", "class") { - @Override - protected Class featureValueOf(PipelineOptionSpec actual) { - return actual.getDefiningInterface(); - } - }; - } - - private static Matcher hasGetter(String methodName) { - return new FeatureMatcher( - is(methodName), "getter method", "name") { - @Override - protected String featureValueOf(PipelineOptionSpec actual) { - return actual.getGetterMethod().getName(); - } - }; - } - - private static Matcher shouldSerialize() { - return new FeatureMatcher(equalTo(true), - "should serialize", "shouldSerialize") { - - @Override - protected Boolean featureValueOf(PipelineOptionSpec actual) { - return actual.shouldSerialize(); - } - }; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java deleted file mode 100644 index f430687ee3..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsTest.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** Unit tests for {@link PipelineOptions}. */ -@RunWith(JUnit4.class) -public class PipelineOptionsTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - /** Interfaces used for testing that {@link PipelineOptions#as(Class)} functions. */ - private interface DerivedTestOptions extends BaseTestOptions { - int getDerivedValue(); - void setDerivedValue(int derivedValue); - - @Override - @JsonIgnore - Set getIgnoredValue(); - @Override - void setIgnoredValue(Set ignoredValue); - } - - private interface ConflictedTestOptions extends BaseTestOptions { - String getDerivedValue(); - void setDerivedValue(String derivedValue); - - @Override - @JsonIgnore - Set getIgnoredValue(); - @Override - void setIgnoredValue(Set ignoredValue); - } - - private interface BaseTestOptions extends PipelineOptions { - List getBaseValue(); - void setBaseValue(List baseValue); - - @JsonIgnore - Set getIgnoredValue(); - void setIgnoredValue(Set ignoredValue); - } - - @Test - public void testDynamicAs() { - BaseTestOptions options = PipelineOptionsFactory.create().as(BaseTestOptions.class); - assertNotNull(options); - } - - @Test - public void testDefaultRunnerIsSet() { - assertEquals(DirectPipelineRunner.class, PipelineOptionsFactory.create().getRunner()); - } - - @Test - public void testCloneAs() throws IOException { - DerivedTestOptions options = PipelineOptionsFactory.create().as(DerivedTestOptions.class); - options.setBaseValue(Lists.newArrayList()); - options.setIgnoredValue(Sets.newHashSet()); - options.getIgnoredValue().add("ignoredString"); - options.setDerivedValue(0); - - BaseTestOptions clonedOptions = options.cloneAs(BaseTestOptions.class); - assertNotSame(clonedOptions, options); - assertNotSame(clonedOptions.getBaseValue(), options.getBaseValue()); - - clonedOptions.getBaseValue().add(true); - assertFalse(clonedOptions.getBaseValue().isEmpty()); - assertTrue(options.getBaseValue().isEmpty()); - - assertNull(clonedOptions.getIgnoredValue()); - - ObjectMapper mapper = new ObjectMapper(); - mapper.readValue(mapper.writeValueAsBytes(clonedOptions), PipelineOptions.class); - } - - @Test - public void testCloneAsConflicted() throws Exception { - DerivedTestOptions options = PipelineOptionsFactory.create().as(DerivedTestOptions.class); - options.setBaseValue(Lists.newArrayList()); - options.setIgnoredValue(Sets.newHashSet()); - options.getIgnoredValue().add("ignoredString"); - options.setDerivedValue(0); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("incompatible return types"); - options.cloneAs(ConflictedTestOptions.class); - } - - private interface ValueProviderOptions extends PipelineOptions { - ValueProvider getBool(); - void setBool(ValueProvider value); - - ValueProvider getString(); - void setString(ValueProvider value); - - String getNotAValueProvider(); - void setNotAValueProvider(String value); - } - - @Test - public void testOutputRuntimeOptions() { - ValueProviderOptions options = - PipelineOptionsFactory.fromArgs( - new String[]{"--string=baz"}).as(ValueProviderOptions.class); - Map expected = ImmutableMap.of( - "bool", ImmutableMap.of("type", Boolean.class)); - assertEquals(expected, options.outputRuntimeOptions()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidatorTest.java deleted file mode 100644 index bbb9529c1a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/PipelineOptionsValidatorTest.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link PipelineOptionsValidator}. */ -@RunWith(JUnit4.class) -public class PipelineOptionsValidatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - /** A test interface with an {@link Validation.Required} annotation. */ - public interface Required extends PipelineOptions { - @Validation.Required - @Description("Fake Description") - String getObject(); - void setObject(String value); - } - - @Test - public void testWhenRequiredOptionIsSet() { - Required required = PipelineOptionsFactory.as(Required.class); - required.setObject("blah"); - PipelineOptionsValidator.validate(Required.class, required); - } - - @Test - public void testWhenRequiredOptionIsSetAndCleared() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing required value for " - + "[public abstract java.lang.String com.google.cloud.dataflow." - + "sdk.options.PipelineOptionsValidatorTest$Required.getObject(), \"Fake Description\"]."); - - Required required = PipelineOptionsFactory.as(Required.class); - required.setObject("blah"); - required.setObject(null); - PipelineOptionsValidator.validate(Required.class, required); - } - - @Test - public void testWhenRequiredOptionIsNeverSet() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing required value for " - + "[public abstract java.lang.String com.google.cloud.dataflow." - + "sdk.options.PipelineOptionsValidatorTest$Required.getObject(), \"Fake Description\"]."); - - Required required = PipelineOptionsFactory.as(Required.class); - PipelineOptionsValidator.validate(Required.class, required); - } - - @Test - public void testWhenRequiredOptionIsNeverSetOnSuperInterface() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing required value for " - + "[public abstract java.lang.String com.google.cloud.dataflow." - + "sdk.options.PipelineOptionsValidatorTest$Required.getObject(), \"Fake Description\"]."); - - PipelineOptions options = PipelineOptionsFactory.create(); - PipelineOptionsValidator.validate(Required.class, options); - } - - /** A test interface that overrides the parent's method. */ - public interface SubClassValidation extends Required { - @Override - String getObject(); - @Override - void setObject(String value); - } - - @Test - public void testValidationOnOverriddenMethods() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing required value for " - + "[public abstract java.lang.String com.google.cloud.dataflow." - + "sdk.options.PipelineOptionsValidatorTest$Required.getObject(), \"Fake Description\"]."); - - SubClassValidation required = PipelineOptionsFactory.as(SubClassValidation.class); - PipelineOptionsValidator.validate(Required.class, required); - } - - /** A test interface with a required group. */ - public interface GroupRequired extends PipelineOptions { - @Validation.Required(groups = {"ham"}) - String getFoo(); - void setFoo(String foo); - - @Validation.Required(groups = {"ham"}) - String getBar(); - void setBar(String bar); - } - - @Test - public void testWhenOneOfRequiredGroupIsSetIsValid() { - GroupRequired groupRequired = PipelineOptionsFactory.as(GroupRequired.class); - groupRequired.setFoo("foo"); - groupRequired.setBar(null); - - PipelineOptionsValidator.validate(GroupRequired.class, groupRequired); - - // Symmetric - groupRequired.setFoo(null); - groupRequired.setBar("bar"); - PipelineOptionsValidator.validate(GroupRequired.class, groupRequired); - } - - @Test - public void testWhenNoneOfRequiredGroupIsSetThrowsException() { - GroupRequired groupRequired = PipelineOptionsFactory.as(GroupRequired.class); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing required value for group [ham]"); - expectedException.expectMessage("properties"); - expectedException.expectMessage("getFoo"); - expectedException.expectMessage("getBar"); - - PipelineOptionsValidator.validate(GroupRequired.class, groupRequired); - } - - /** A test interface with a member in multiple required groups. */ - public interface MultiGroupRequired extends PipelineOptions { - @Validation.Required(groups = {"spam", "ham"}) - String getFoo(); - void setFoo(String foo); - - @Validation.Required(groups = {"spam"}) - String getBar(); - void setBar(String bar); - - @Validation.Required(groups = {"ham"}) - String getBaz(); - void setBaz(String baz); - } - - @Test - public void testWhenOneOfMultipleRequiredGroupsIsSetIsValid() { - MultiGroupRequired multiGroupRequired = PipelineOptionsFactory.as(MultiGroupRequired.class); - - multiGroupRequired.setFoo("eggs"); - - PipelineOptionsValidator.validate(MultiGroupRequired.class, multiGroupRequired); - } - - private interface LeftOptions extends PipelineOptions { - @Validation.Required(groups = {"left"}) - String getFoo(); - void setFoo(String foo); - - @Validation.Required(groups = {"left"}) - String getLeft(); - void setLeft(String left); - - @Validation.Required(groups = {"both"}) - String getBoth(); - void setBoth(String both); - } - - private interface RightOptions extends PipelineOptions { - @Validation.Required(groups = {"right"}) - String getFoo(); - void setFoo(String foo); - - @Validation.Required(groups = {"right"}) - String getRight(); - void setRight(String right); - - @Validation.Required(groups = {"both"}) - String getBoth(); - void setBoth(String both); - } - - private interface JoinedOptions extends LeftOptions, RightOptions {} - - @Test - public void testWhenOptionIsDefinedInMultipleSuperInterfacesAndIsNotPresentFailsRequirement() { - RightOptions rightOptions = PipelineOptionsFactory.as(RightOptions.class); - rightOptions.setBoth("foo"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing required value for group"); - expectedException.expectMessage("getFoo"); - - PipelineOptionsValidator.validate(JoinedOptions.class, rightOptions); - } - - @Test - public void testWhenOptionIsDefinedInMultipleSuperInterfacesMeetsGroupRequirement() { - RightOptions rightOpts = PipelineOptionsFactory.as(RightOptions.class); - rightOpts.setFoo("true"); - rightOpts.setBoth("bar"); - - LeftOptions leftOpts = PipelineOptionsFactory.as(LeftOptions.class); - leftOpts.setFoo("Untrue"); - leftOpts.setBoth("Raise the"); - - PipelineOptionsValidator.validate(JoinedOptions.class, rightOpts); - PipelineOptionsValidator.validate(JoinedOptions.class, leftOpts); - } - - @Test - public void testWhenOptionIsDefinedOnOtherOptionsClassMeetsGroupRequirement() { - RightOptions rightOpts = PipelineOptionsFactory.as(RightOptions.class); - rightOpts.setFoo("true"); - rightOpts.setBoth("bar"); - - LeftOptions leftOpts = PipelineOptionsFactory.as(LeftOptions.class); - leftOpts.setFoo("Untrue"); - leftOpts.setBoth("Raise the"); - - PipelineOptionsValidator.validate(RightOptions.class, leftOpts); - PipelineOptionsValidator.validate(LeftOptions.class, rightOpts); - } - - @Test - public void testWhenOptionIsDefinedOnMultipleInterfacesOnlyListedOnceWhenNotPresent() { - JoinedOptions options = PipelineOptionsFactory.as(JoinedOptions.class); - options.setFoo("Hello"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("required value for group [both]"); - expectedException.expectMessage("properties [getBoth()]"); - - PipelineOptionsValidator.validate(JoinedOptions.class, options); - } - - private interface SuperOptions extends PipelineOptions { - @Validation.Required(groups = {"super"}) - String getFoo(); - void setFoo(String foo); - - @Validation.Required(groups = {"sub"}) - String getBar(); - void setBar(String bar); - - @Validation.Required(groups = {"otherSuper"}) - String getSuperclassObj(); - void setSuperclassObj(String sup); - } - - private interface SubOptions extends SuperOptions { - @Override - @Validation.Required(groups = {"sub"}) - String getFoo(); - @Override - void setFoo(String foo); - - @Override - String getSuperclassObj(); - @Override - void setSuperclassObj(String sup); - } - - @Test - public void testSuperInterfaceRequiredOptionsAlsoRequiredInSubInterface() { - SubOptions subOpts = PipelineOptionsFactory.as(SubOptions.class); - subOpts.setFoo("Bar"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("otherSuper"); - expectedException.expectMessage("Missing required value"); - expectedException.expectMessage("getSuperclassObj"); - - PipelineOptionsValidator.validate(SubOptions.class, subOpts); - } - - @Test - public void - testSuperInterfaceGroupIsInAdditionToSubInterfaceGroupOnlyWhenValidatingSuperInterface() { - SubOptions opts = PipelineOptionsFactory.as(SubOptions.class); - opts.setFoo("Foo"); - opts.setSuperclassObj("Hello world"); - - // Valid SubOptions, but invalid SuperOptions - PipelineOptionsValidator.validate(SubOptions.class, opts); - - expectedException.expectMessage("sub"); - expectedException.expectMessage("Missing required value"); - expectedException.expectMessage("getBar"); - PipelineOptionsValidator.validate(SuperOptions.class, opts); - } - - @Test - public void testSuperInterfaceRequiredOptionsSatisfiedBySubInterface() { - SubOptions subOpts = PipelineOptionsFactory.as(SubOptions.class); - subOpts.setFoo("bar"); - subOpts.setBar("bar"); - subOpts.setSuperclassObj("SuperDuper"); - - PipelineOptionsValidator.validate(SubOptions.class, subOpts); - PipelineOptionsValidator.validate(SuperOptions.class, subOpts); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java deleted file mode 100644 index 50183184f7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ProxyInvocationHandlerTest.java +++ /dev/null @@ -1,973 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.testing.EqualsTester; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.ExternalResource; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.Serializable; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** Tests for {@link ProxyInvocationHandler}. */ -@RunWith(JUnit4.class) -public class ProxyInvocationHandlerTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Rule public TestRule resetPipelineOptionsRegistry = new ExternalResource() { - @Override - protected void before() { - PipelineOptionsFactory.resetRegistry(); - } - }; - - private static final ObjectMapper MAPPER = new ObjectMapper(); - - /** A test interface with some primitives and objects. */ - public interface Simple extends PipelineOptions { - boolean isOptionEnabled(); - void setOptionEnabled(boolean value); - int getPrimitive(); - void setPrimitive(int value); - String getString(); - void setString(String value); - } - - @Test - public void testPropertySettingAndGetting() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy = handler.as(Simple.class); - proxy.setString("OBJECT"); - proxy.setOptionEnabled(true); - proxy.setPrimitive(4); - assertEquals("OBJECT", proxy.getString()); - assertTrue(proxy.isOptionEnabled()); - assertEquals(4, proxy.getPrimitive()); - } - - /** A test interface containing all the JLS default values. */ - public interface JLSDefaults extends PipelineOptions { - boolean getBoolean(); - void setBoolean(boolean value); - char getChar(); - void setChar(char value); - byte getByte(); - void setByte(byte value); - short getShort(); - void setShort(short value); - int getInt(); - void setInt(int value); - long getLong(); - void setLong(long value); - float getFloat(); - void setFloat(float value); - double getDouble(); - void setDouble(double value); - Object getObject(); - void setObject(Object value); - } - - @Test - public void testGettingJLSDefaults() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - JLSDefaults proxy = handler.as(JLSDefaults.class); - assertFalse(proxy.getBoolean()); - assertEquals('\0', proxy.getChar()); - assertEquals((byte) 0, proxy.getByte()); - assertEquals((short) 0, proxy.getShort()); - assertEquals(0, proxy.getInt()); - assertEquals(0L, proxy.getLong()); - assertEquals(0f, proxy.getFloat(), 0f); - assertEquals(0d, proxy.getDouble(), 0d); - assertNull(proxy.getObject()); - } - - /** A {@link DefaultValueFactory} that is used for testing. */ - public static class TestOptionFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return "testOptionFactory"; - } - } - - /** A test enum for testing {@link Default.Enum @Default.Enum}. */ - public enum EnumType { - MyEnum("MyTestEnum"); - - private final String value; - private EnumType(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } - } - - /** A test interface containing all the {@link Default} annotations. */ - public interface DefaultAnnotations extends PipelineOptions { - @Default.Boolean(true) - boolean getBoolean(); - void setBoolean(boolean value); - @Default.Character('a') - char getChar(); - void setChar(char value); - @Default.Byte((byte) 4) - byte getByte(); - void setByte(byte value); - @Default.Short((short) 5) - short getShort(); - void setShort(short value); - @Default.Integer(6) - int getInt(); - void setInt(int value); - @Default.Long(7L) - long getLong(); - void setLong(long value); - @Default.Float(8f) - float getFloat(); - void setFloat(float value); - @Default.Double(9d) - double getDouble(); - void setDouble(double value); - @Default.String("testString") - String getString(); - void setString(String value); - @Default.Class(DefaultAnnotations.class) - Class getClassOption(); - void setClassOption(Class value); - @Default.Enum("MyEnum") - EnumType getEnum(); - void setEnum(EnumType value); - @Default.InstanceFactory(TestOptionFactory.class) - String getComplex(); - void setComplex(String value); - } - - @Test - public void testAnnotationDefaults() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - DefaultAnnotations proxy = handler.as(DefaultAnnotations.class); - assertTrue(proxy.getBoolean()); - assertEquals('a', proxy.getChar()); - assertEquals((byte) 4, proxy.getByte()); - assertEquals((short) 5, proxy.getShort()); - assertEquals(6, proxy.getInt()); - assertEquals(7, proxy.getLong()); - assertEquals(8f, proxy.getFloat(), 0f); - assertEquals(9d, proxy.getDouble(), 0d); - assertEquals("testString", proxy.getString()); - assertEquals(DefaultAnnotations.class, proxy.getClassOption()); - assertEquals(EnumType.MyEnum, proxy.getEnum()); - assertEquals("testOptionFactory", proxy.getComplex()); - } - - @Test - public void testEqualsAndHashCode() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy = handler.as(Simple.class); - JLSDefaults sameAsProxy = proxy.as(JLSDefaults.class); - ProxyInvocationHandler handler2 = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy2 = handler2.as(Simple.class); - JLSDefaults sameAsProxy2 = proxy2.as(JLSDefaults.class); - new EqualsTester() - .addEqualityGroup(handler, proxy, sameAsProxy) - .addEqualityGroup(handler2, proxy2, sameAsProxy2) - .testEquals(); - } - - @Test - public void testToString() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy = handler.as(Simple.class); - proxy.setString("stringValue"); - DefaultAnnotations proxy2 = proxy.as(DefaultAnnotations.class); - proxy2.setLong(57L); - assertEquals("Current Settings:\n" - + " long: 57\n" - + " string: stringValue\n", - proxy.toString()); - } - - @Test - public void testToStringAfterDeserializationContainsJsonEntries() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy = handler.as(Simple.class); - Long optionsId = proxy.getOptionsId(); - proxy.setString("stringValue"); - DefaultAnnotations proxy2 = proxy.as(DefaultAnnotations.class); - proxy2.setLong(57L); - assertEquals(String.format("Current Settings:\n" - + " long: 57\n" - + " optionsId: %d\n" - + " string: \"stringValue\"\n", optionsId), - serializeDeserialize(PipelineOptions.class, proxy2).toString()); - } - - @Test - public void testToStringAfterDeserializationContainsOverriddenEntries() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - Simple proxy = handler.as(Simple.class); - Long optionsId = proxy.getOptionsId(); - proxy.setString("stringValue"); - DefaultAnnotations proxy2 = proxy.as(DefaultAnnotations.class); - proxy2.setLong(57L); - Simple deserializedOptions = serializeDeserialize(Simple.class, proxy2); - deserializedOptions.setString("overriddenValue"); - assertEquals(String.format("Current Settings:\n" - + " long: 57\n" - + " optionsId: %d\n" - + " string: overriddenValue\n", optionsId), - deserializedOptions.toString()); - } - - /** A test interface containing an unknown method. */ - public interface UnknownMethod { - void unknownMethod(); - } - - @Test - public void testInvokeWithUnknownMethod() throws Exception { - expectedException.expect(RuntimeException.class); - expectedException.expectMessage("Unknown method [public abstract void com.google.cloud." - + "dataflow.sdk.options.ProxyInvocationHandlerTest$UnknownMethod.unknownMethod()] " - + "invoked with args [null]."); - - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - handler.invoke(handler, UnknownMethod.class.getMethod("unknownMethod"), null); - } - - /** A test interface that extends another interface. */ - public interface SubClass extends Simple { - String getExtended(); - void setExtended(String value); - } - - @Test - public void testSubClassStoresSuperInterfaceValues() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - SubClass extended = handler.as(SubClass.class); - - extended.setString("parentValue"); - assertEquals("parentValue", extended.getString()); - } - - @Test - public void testUpCastRetainsSuperInterfaceValues() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - SubClass extended = handler.as(SubClass.class); - - extended.setString("parentValue"); - Simple simple = extended.as(Simple.class); - assertEquals("parentValue", simple.getString()); - } - - @Test - public void testUpCastRetainsSubClassValues() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - SubClass extended = handler.as(SubClass.class); - - extended.setExtended("subClassValue"); - SubClass extended2 = extended.as(Simple.class).as(SubClass.class); - assertEquals("subClassValue", extended2.getExtended()); - } - - /** A test interface that is a sibling to {@link SubClass}. */ - public interface Sibling extends Simple { - String getSibling(); - void setSibling(String value); - } - - @Test - public void testAsSiblingRetainsSuperInterfaceValues() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - SubClass extended = handler.as(SubClass.class); - - extended.setString("parentValue"); - Sibling sibling = extended.as(Sibling.class); - assertEquals("parentValue", sibling.getString()); - } - - /** A test interface that has the same methods as the parent. */ - public interface MethodConflict extends Simple { - @Override - String getString(); - @Override - void setString(String value); - } - - @Test - public void testMethodConflictProvidesSameValue() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - MethodConflict methodConflict = handler.as(MethodConflict.class); - - methodConflict.setString("conflictValue"); - assertEquals("conflictValue", methodConflict.getString()); - assertEquals("conflictValue", methodConflict.as(Simple.class).getString()); - } - - /** A test interface that has the same methods as its parent and grandparent. */ - public interface DeepMethodConflict extends MethodConflict { - @Override - String getString(); - @Override - void setString(String value); - @Override - int getPrimitive(); - @Override - void setPrimitive(int value); - } - - @Test - public void testDeepMethodConflictProvidesSameValue() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - DeepMethodConflict deepMethodConflict = handler.as(DeepMethodConflict.class); - - // Tests overriding an already overridden method - deepMethodConflict.setString("conflictValue"); - assertEquals("conflictValue", deepMethodConflict.getString()); - assertEquals("conflictValue", deepMethodConflict.as(MethodConflict.class).getString()); - assertEquals("conflictValue", deepMethodConflict.as(Simple.class).getString()); - - // Tests overriding a method from an ancestor class - deepMethodConflict.setPrimitive(5); - assertEquals(5, deepMethodConflict.getPrimitive()); - assertEquals(5, deepMethodConflict.as(MethodConflict.class).getPrimitive()); - assertEquals(5, deepMethodConflict.as(Simple.class).getPrimitive()); - } - - /** A test interface that shares the same methods as {@link Sibling}. */ - public interface SimpleSibling extends PipelineOptions { - String getString(); - void setString(String value); - } - - @Test - public void testDisjointSiblingsShareValues() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - SimpleSibling proxy = handler.as(SimpleSibling.class); - proxy.setString("siblingValue"); - assertEquals("siblingValue", proxy.getString()); - assertEquals("siblingValue", proxy.as(Simple.class).getString()); - } - - /** A test interface that joins two sibling interfaces that have conflicting methods. */ - public interface SiblingMethodConflict extends Simple, SimpleSibling { - } - - @Test - public void testSiblingMethodConflict() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - SiblingMethodConflict siblingMethodConflict = handler.as(SiblingMethodConflict.class); - siblingMethodConflict.setString("siblingValue"); - assertEquals("siblingValue", siblingMethodConflict.getString()); - assertEquals("siblingValue", siblingMethodConflict.as(Simple.class).getString()); - assertEquals("siblingValue", siblingMethodConflict.as(SimpleSibling.class).getString()); - } - - /** A test interface that has only the getter and only a setter overriden. */ - public interface PartialMethodConflict extends Simple { - @Override - String getString(); - @Override - void setPrimitive(int value); - } - - @Test - public void testPartialMethodConflictProvidesSameValue() throws Exception { - ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); - PartialMethodConflict partialMethodConflict = handler.as(PartialMethodConflict.class); - - // Tests overriding a getter property that is only partially bound - partialMethodConflict.setString("conflictValue"); - assertEquals("conflictValue", partialMethodConflict.getString()); - assertEquals("conflictValue", partialMethodConflict.as(Simple.class).getString()); - - // Tests overriding a setter property that is only partially bound - partialMethodConflict.setPrimitive(5); - assertEquals(5, partialMethodConflict.getPrimitive()); - assertEquals(5, partialMethodConflict.as(Simple.class).getPrimitive()); - } - - @Test - public void testResetRegistry() { - Set> defaultRegistry = - new HashSet<>(PipelineOptionsFactory.getRegisteredOptions()); - assertThat(defaultRegistry, not(hasItem(FooOptions.class))); - - PipelineOptionsFactory.register(FooOptions.class); - assertThat(PipelineOptionsFactory.getRegisteredOptions(), hasItem(FooOptions.class)); - - PipelineOptionsFactory.resetRegistry(); - assertEquals(defaultRegistry, PipelineOptionsFactory.getRegisteredOptions()); - } - - @Test - public void testJsonConversionForDefault() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - assertNotNull(serializeDeserialize(PipelineOptions.class, options)); - } - - /** Test interface for JSON conversion of simple types. */ - private interface SimpleTypes extends PipelineOptions { - int getInteger(); - void setInteger(int value); - String getString(); - void setString(String value); - } - - @Test - public void testJsonConversionForSimpleTypes() throws Exception { - SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class); - options.setString("TestValue"); - options.setInteger(5); - SimpleTypes options2 = serializeDeserialize(SimpleTypes.class, options); - assertEquals(5, options2.getInteger()); - assertEquals("TestValue", options2.getString()); - } - - @Test - public void testJsonConversionOfAJsonConvertedType() throws Exception { - SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class); - options.setString("TestValue"); - options.setInteger(5); - // It is important here that our first serialization goes to our most basic - // type so that we handle the case when we don't know the types of certain - // properties because the intermediate instance of PipelineOptions never - // saw their interface. - SimpleTypes options2 = serializeDeserialize(SimpleTypes.class, - serializeDeserialize(PipelineOptions.class, options)); - assertEquals(5, options2.getInteger()); - assertEquals("TestValue", options2.getString()); - } - - @Test - public void testJsonConversionForPartiallySerializedValues() throws Exception { - SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class); - options.setInteger(5); - SimpleTypes options2 = serializeDeserialize(SimpleTypes.class, options); - options2.setString("TestValue"); - SimpleTypes options3 = serializeDeserialize(SimpleTypes.class, options2); - assertEquals(5, options3.getInteger()); - assertEquals("TestValue", options3.getString()); - } - - @Test - public void testJsonConversionForOverriddenSerializedValues() throws Exception { - SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class); - options.setInteger(-5); - options.setString("NeedsToBeOverridden"); - SimpleTypes options2 = serializeDeserialize(SimpleTypes.class, options); - options2.setInteger(5); - options2.setString("TestValue"); - SimpleTypes options3 = serializeDeserialize(SimpleTypes.class, options2); - assertEquals(5, options3.getInteger()); - assertEquals("TestValue", options3.getString()); - } - - /** Test interface for JSON conversion of container types. */ - private interface ContainerTypes extends PipelineOptions { - List getList(); - void setList(List values); - Map getMap(); - void setMap(Map values); - Set getSet(); - void setSet(Set values); - } - - @Test - public void testJsonConversionForContainerTypes() throws Exception { - List list = ImmutableList.of("a", "b", "c"); - Map map = ImmutableMap.of("d", "x", "e", "y", "f", "z"); - Set set = ImmutableSet.of("g", "h", "i"); - ContainerTypes options = PipelineOptionsFactory.as(ContainerTypes.class); - options.setList(list); - options.setMap(map); - options.setSet(set); - ContainerTypes options2 = serializeDeserialize(ContainerTypes.class, options); - assertEquals(list, options2.getList()); - assertEquals(map, options2.getMap()); - assertEquals(set, options2.getSet()); - } - - /** Test interface for conversion of inner types. */ - private static class InnerType { - public double doubleField; - - static InnerType of(double value) { - InnerType rval = new InnerType(); - rval.doubleField = value; - return rval; - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public boolean equals(Object obj) { - return obj != null - && getClass().equals(obj.getClass()) - && Objects.equals(doubleField, ((InnerType) obj).doubleField); - } - } - - /** Test interface for conversion of generics and inner types. */ - private static class ComplexType { - public String stringField; - public Integer intField; - public List genericType; - public InnerType innerType; - - @Override - public int hashCode() { - return 0; - } - - @Override - public boolean equals(Object obj) { - return obj != null - && getClass().equals(obj.getClass()) - && Objects.equals(stringField, ((ComplexType) obj).stringField) - && Objects.equals(intField, ((ComplexType) obj).intField) - && Objects.equals(genericType, ((ComplexType) obj).genericType) - && Objects.equals(innerType, ((ComplexType) obj).innerType); - } - } - - private interface ComplexTypes extends PipelineOptions { - ComplexType getComplexType(); - void setComplexType(ComplexType value); - } - - @Test - public void testJsonConversionForComplexType() throws Exception { - ComplexType complexType = new ComplexType(); - complexType.stringField = "stringField"; - complexType.intField = 12; - complexType.innerType = InnerType.of(12); - complexType.genericType = ImmutableList.of(InnerType.of(16234), InnerType.of(24)); - - ComplexTypes options = PipelineOptionsFactory.as(ComplexTypes.class); - options.setComplexType(complexType); - ComplexTypes options2 = serializeDeserialize(ComplexTypes.class, options); - assertEquals(complexType, options2.getComplexType()); - } - - /** Test interface for testing ignored properties during serialization. */ - private interface IgnoredProperty extends PipelineOptions { - @JsonIgnore - String getValue(); - void setValue(String value); - } - - @Test - public void testJsonConversionOfIgnoredProperty() throws Exception { - IgnoredProperty options = PipelineOptionsFactory.as(IgnoredProperty.class); - options.setValue("TestValue"); - - IgnoredProperty options2 = serializeDeserialize(IgnoredProperty.class, options); - assertNull(options2.getValue()); - } - - /** Test class that is not serializable by Jackson. */ - public static class NotSerializable { - private String value; - public NotSerializable(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - } - - /** Test interface containing a class that is not serializable by Jackson. */ - private interface NotSerializableProperty extends PipelineOptions { - NotSerializable getValue(); - void setValue(NotSerializable value); - } - - @Test - public void testJsonConversionOfNotSerializableProperty() throws Exception { - NotSerializableProperty options = PipelineOptionsFactory.as(NotSerializableProperty.class); - options.setValue(new NotSerializable("TestString")); - - expectedException.expect(JsonMappingException.class); - expectedException.expectMessage("Failed to serialize and deserialize property 'value'"); - serializeDeserialize(NotSerializableProperty.class, options); - } - - /** - * Test interface that has {@link JsonIgnore @JsonIgnore} on a property that Jackson - * can't serialize. - */ - private interface IgnoredNotSerializableProperty extends PipelineOptions { - @JsonIgnore - NotSerializable getValue(); - void setValue(NotSerializable value); - } - - @Test - public void testJsonConversionOfIgnoredNotSerializableProperty() throws Exception { - IgnoredNotSerializableProperty options = - PipelineOptionsFactory.as(IgnoredNotSerializableProperty.class); - options.setValue(new NotSerializable("TestString")); - - IgnoredNotSerializableProperty options2 = - serializeDeserialize(IgnoredNotSerializableProperty.class, options); - assertNull(options2.getValue()); - } - - /** Test class that is only serializable by Jackson with the added metadata. */ - public static class SerializableWithMetadata { - private String value; - public SerializableWithMetadata(@JsonProperty("value") String value) { - this.value = value; - } - - @JsonProperty("value") - public String getValue() { - return value; - } - } - - /** - * Test interface containing a property that is serializable by Jackson only with - * the additional metadata. - */ - private interface SerializableWithMetadataProperty extends PipelineOptions { - SerializableWithMetadata getValue(); - void setValue(SerializableWithMetadata value); - } - - @Test - public void testJsonConversionOfSerializableWithMetadataProperty() throws Exception { - SerializableWithMetadataProperty options = - PipelineOptionsFactory.as(SerializableWithMetadataProperty.class); - options.setValue(new SerializableWithMetadata("TestString")); - - SerializableWithMetadataProperty options2 = - serializeDeserialize(SerializableWithMetadataProperty.class, options); - assertEquals("TestString", options2.getValue().getValue()); - } - - @Test - public void testDisplayDataItemProperties() { - PipelineOptions options = PipelineOptionsFactory.create(); - options.setTempLocation("myTemp"); - DisplayData displayData = DisplayData.from(options); - - assertThat(displayData, hasDisplayItem(allOf( - hasKey("tempLocation"), - hasType(DisplayData.Type.STRING), - hasValue("myTemp"), - hasNamespace(PipelineOptions.class) - ))); - } - - @Test - public void testDisplayDataTypes() { - Instant now = Instant.now(); - - TypedOptions options = PipelineOptionsFactory.as(TypedOptions.class); - options.setInteger(1234); - options.setTimestamp(now); - options.setJavaClass(ProxyInvocationHandlerTest.class); - options.setObject(new Serializable() { - @Override - public String toString() { - return "foobar"; - } - }); - - DisplayData displayData = DisplayData.from(options); - - assertThat(displayData, hasDisplayItem("integer", 1234)); - assertThat(displayData, hasDisplayItem("timestamp", now)); - assertThat(displayData, hasDisplayItem("javaClass", ProxyInvocationHandlerTest.class)); - assertThat(displayData, hasDisplayItem("object", "foobar")); - } - - interface TypedOptions extends PipelineOptions { - int getInteger(); - void setInteger(int value); - - Instant getTimestamp(); - void setTimestamp(Instant value); - - Class getJavaClass(); - void setJavaClass(Class value); - - Object getObject(); - void setObject(Object value); - } - - @Test - public void testDisplayDataInheritanceNamespace() { - ExtendsBaseOptions options = PipelineOptionsFactory.as(ExtendsBaseOptions.class); - options.setFoo("bar"); - - DisplayData displayData = DisplayData.from(options); - - assertThat(displayData, hasDisplayItem(allOf( - hasKey("foo"), - hasValue("bar"), - hasNamespace(ExtendsBaseOptions.class) - ))); - } - - interface BaseOptions extends PipelineOptions { - String getFoo(); - void setFoo(String value); - } - - interface ExtendsBaseOptions extends BaseOptions { - @Override String getFoo(); - @Override void setFoo(String value); - } - - @Test - public void testDisplayDataExcludedFromOverriddenBaseClass() { - ExtendsBaseOptions options = PipelineOptionsFactory.as(ExtendsBaseOptions.class); - options.setFoo("bar"); - - DisplayData displayData = DisplayData.from(options); - assertThat(displayData, not(hasDisplayItem(hasNamespace(BaseOptions.class)))); - } - - @Test - public void testDisplayDataIncludedForDisjointInterfaceHierarchies() { - FooOptions fooOptions = PipelineOptionsFactory.as(FooOptions.class); - fooOptions.setFoo("foo"); - - BarOptions barOptions = fooOptions.as(BarOptions.class); - barOptions.setBar("bar"); - - DisplayData data = DisplayData.from(barOptions); - assertThat(data, hasDisplayItem(allOf(hasKey("foo"), hasNamespace(FooOptions.class)))); - assertThat(data, hasDisplayItem(allOf(hasKey("bar"), hasNamespace(BarOptions.class)))); - } - - interface FooOptions extends PipelineOptions { - String getFoo(); - void setFoo(String value); - } - - interface BarOptions extends PipelineOptions { - String getBar(); - void setBar(String value); - } - - @Test - public void testDisplayDataExcludesDefaultValues() { - PipelineOptions options = PipelineOptionsFactory.as(HasDefaults.class); - DisplayData data = DisplayData.from(options); - - assertThat(data, not(hasDisplayItem("foo"))); - } - - interface HasDefaults extends PipelineOptions { - @Default.String("bar") - String getFoo(); - void setFoo(String value); - } - - @Test - public void testDisplayDataExcludesValuesAccessedButNeverSet() { - HasDefaults options = PipelineOptionsFactory.as(HasDefaults.class); - assertEquals("bar", options.getFoo()); - - DisplayData data = DisplayData.from(options); - assertThat(data, not(hasDisplayItem("foo"))); - } - - @Test - public void testDisplayDataIncludesExplicitlySetDefaults() { - HasDefaults options = PipelineOptionsFactory.as(HasDefaults.class); - String defaultValue = options.getFoo(); - options.setFoo(defaultValue); - - DisplayData data = DisplayData.from(options); - assertThat(data, hasDisplayItem("foo", defaultValue)); - } - - @Test - public void testDisplayDataNullValuesConvertedToEmptyString() throws Exception { - FooOptions options = PipelineOptionsFactory.as(FooOptions.class); - options.setFoo(null); - - DisplayData data = DisplayData.from(options); - assertThat(data, hasDisplayItem("foo", "")); - - FooOptions deserializedOptions = serializeDeserialize(FooOptions.class, options); - DisplayData deserializedData = DisplayData.from(deserializedOptions); - assertThat(deserializedData, hasDisplayItem("foo", "")); - } - - @Test - public void testDisplayDataArrayValue() throws Exception { - ArrayOptions options = PipelineOptionsFactory.as(ArrayOptions.class); - options.setDeepArray(new String[][] {new String[] {"a", "b"}, new String[] {"c"}}); - options.setDeepPrimitiveArray(new int[][] {new int[] {1, 2}, new int[] {3}}); - - DisplayData data = DisplayData.from(options); - assertThat(data, hasDisplayItem("deepArray", "[[a, b], [c]]")); - assertThat(data, hasDisplayItem("deepPrimitiveArray", "[[1, 2], [3]]")); - - ArrayOptions deserializedOptions = serializeDeserialize(ArrayOptions.class, options); - DisplayData deserializedData = DisplayData.from(deserializedOptions); - assertThat(deserializedData, hasDisplayItem("deepPrimitiveArray", "[[1, 2], [3]]")); - } - - private interface ArrayOptions extends PipelineOptions { - String[][] getDeepArray(); - void setDeepArray(String[][] value); - - int[][] getDeepPrimitiveArray(); - void setDeepPrimitiveArray(int[][] value); - } - - @Test - public void testDisplayDataJsonSerialization() throws IOException { - FooOptions options = PipelineOptionsFactory.as(FooOptions.class); - options.setFoo("bar"); - - @SuppressWarnings("unchecked") - Map map = MAPPER.readValue(MAPPER.writeValueAsBytes(options), Map.class); - - assertThat("main pipeline options data keyed as 'options'", map, Matchers.hasKey("options")); - assertThat("display data keyed as 'display_data'", map, Matchers.hasKey("display_data")); - - Map expectedDisplayItem = ImmutableMap.builder() - .put("namespace", FooOptions.class.getName()) - .put("key", "foo") - .put("value", "bar") - .put("type", "STRING") - .build(); - - @SuppressWarnings("unchecked") - List> deserializedDisplayData = (List>) map.get("display_data"); - assertThat(deserializedDisplayData, hasItem(expectedDisplayItem)); - } - - @Test - public void testDisplayDataFromDeserializedJson() throws Exception { - FooOptions options = PipelineOptionsFactory.as(FooOptions.class); - options.setFoo("bar"); - DisplayData data = DisplayData.from(options); - assertThat(data, hasDisplayItem("foo", "bar")); - - FooOptions deserializedOptions = serializeDeserialize(FooOptions.class, options); - DisplayData dataAfterDeserialization = DisplayData.from(deserializedOptions); - assertEquals(data, dataAfterDeserialization); - } - - @Test - public void testDisplayDataDeserializationWithRegistration() throws Exception { - PipelineOptionsFactory.register(HasClassOptions.class); - HasClassOptions options = PipelineOptionsFactory.as(HasClassOptions.class); - options.setClassOption(ProxyInvocationHandlerTest.class); - - PipelineOptions deserializedOptions = serializeDeserialize(PipelineOptions.class, options); - DisplayData displayData = DisplayData.from(deserializedOptions); - assertThat(displayData, hasDisplayItem("classOption", ProxyInvocationHandlerTest.class)); - } - - @Test - public void testDisplayDataMissingPipelineOptionsRegistration() throws Exception { - HasClassOptions options = PipelineOptionsFactory.as(HasClassOptions.class); - options.setClassOption(ProxyInvocationHandlerTest.class); - - PipelineOptions deserializedOptions = serializeDeserialize(PipelineOptions.class, options); - DisplayData displayData = DisplayData.from(deserializedOptions); - String expectedJsonValue = MAPPER.writeValueAsString(ProxyInvocationHandlerTest.class); - assertThat(displayData, hasDisplayItem("classOption", expectedJsonValue)); - } - - interface HasClassOptions extends PipelineOptions { - Class getClassOption(); - void setClassOption(Class value); - } - - @Test - public void testDisplayDataJsonValueSetAfterDeserialization() throws Exception { - FooOptions options = PipelineOptionsFactory.as(FooOptions.class); - options.setFoo("bar"); - DisplayData data = DisplayData.from(options); - assertThat(data, hasDisplayItem("foo", "bar")); - - FooOptions deserializedOptions = serializeDeserialize(FooOptions.class, options); - deserializedOptions.setFoo("baz"); - DisplayData dataAfterDeserialization = DisplayData.from(deserializedOptions); - assertThat(dataAfterDeserialization, hasDisplayItem("foo", "baz")); - } - - private T serializeDeserialize(Class kls, PipelineOptions options) - throws Exception { - String value = MAPPER.writeValueAsString(options); - return MAPPER.readValue(value, PipelineOptions.class).as(kls); - } - - @Test - public void testDisplayDataExcludesJsonIgnoreOptions() { - IgnoredProperty options = PipelineOptionsFactory.as(IgnoredProperty.class); - options.setValue("foobar"); - - DisplayData data = DisplayData.from(options); - assertThat(data, not(hasDisplayItem("value"))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java deleted file mode 100644 index 2f593ede1f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderTest.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.options.ValueProvider.NestedValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.RuntimeValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** Tests for {@link ValueProvider}. */ -@RunWith(JUnit4.class) -public class ValueProviderTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - /** A test interface. */ - public interface TestOptions extends PipelineOptions { - @Default.String("bar") - ValueProvider getBar(); - void setBar(ValueProvider bar); - - ValueProvider getFoo(); - void setFoo(ValueProvider foo); - - ValueProvider> getList(); - void setList(ValueProvider> list); - } - - @Test - public void testCommandLineNoDefault() { - TestOptions options = PipelineOptionsFactory.fromArgs( - new String[]{"--foo=baz"}).as(TestOptions.class); - ValueProvider provider = options.getFoo(); - assertEquals("baz", provider.get()); - assertTrue(provider.isAccessible()); - } - - @Test - public void testListValueProvider() { - TestOptions options = PipelineOptionsFactory.fromArgs( - new String[]{"--list=1,2,3"}).as(TestOptions.class); - ValueProvider> provider = options.getList(); - assertEquals(ImmutableList.of(1, 2, 3), provider.get()); - assertTrue(provider.isAccessible()); - } - - @Test - public void testCommandLineWithDefault() { - TestOptions options = PipelineOptionsFactory.fromArgs( - new String[]{"--bar=baz"}).as(TestOptions.class); - ValueProvider provider = options.getBar(); - assertEquals("baz", provider.get()); - assertTrue(provider.isAccessible()); - } - - @Test - public void testStaticValueProvider() { - ValueProvider provider = StaticValueProvider.of("foo"); - assertEquals("foo", provider.get()); - assertTrue(provider.isAccessible()); - assertEquals("StaticValueProvider{value=foo}", provider.toString()); - } - - @Test - public void testNoDefaultRuntimeProvider() { - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - ValueProvider provider = options.getFoo(); - assertFalse(provider.isAccessible()); - - expectedException.expect(RuntimeException.class); - expectedException.expectMessage("Not called from a runtime context"); - provider.get(); - } - - @Test - public void testRuntimePropertyName() { - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - ValueProvider provider = options.getFoo(); - assertEquals("foo", ((RuntimeValueProvider) provider).propertyName()); - assertEquals( - "RuntimeValueProvider{propertyName=foo, default=null, value=null}", - provider.toString()); - } - - @Test - public void testDefaultRuntimeProvider() { - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - ValueProvider provider = options.getBar(); - assertFalse(provider.isAccessible()); - } - - @Test - public void testNoDefaultRuntimeProviderWithOverride() throws Exception { - ObjectMapper mapper = new ObjectMapper(); - TestOptions runtime = mapper.readValue( - "{ \"options\": { \"foo\": \"quux\" }}", PipelineOptions.class) - .as(TestOptions.class); - - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - runtime.setOptionsId(options.getOptionsId()); - RuntimeValueProvider.setRuntimeOptions(runtime); - - ValueProvider provider = options.getFoo(); - assertTrue(provider.isAccessible()); - assertEquals("quux", provider.get()); - } - - @Test - public void testDefaultRuntimeProviderWithOverride() throws Exception { - ObjectMapper mapper = new ObjectMapper(); - TestOptions runtime = mapper.readValue( - "{ \"options\": { \"bar\": \"quux\" }}", PipelineOptions.class) - .as(TestOptions.class); - - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - runtime.setOptionsId(options.getOptionsId()); - RuntimeValueProvider.setRuntimeOptions(runtime); - - ValueProvider provider = options.getBar(); - assertTrue(provider.isAccessible()); - assertEquals("quux", provider.get()); - } - - @Test - public void testDefaultRuntimeProviderWithoutOverride() throws Exception { - TestOptions runtime = PipelineOptionsFactory.as(TestOptions.class); - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - runtime.setOptionsId(options.getOptionsId()); - RuntimeValueProvider.setRuntimeOptions(runtime); - - ValueProvider provider = options.getBar(); - assertTrue(provider.isAccessible()); - assertEquals("bar", provider.get()); - } - - /** A test interface. */ - public interface BadOptionsRuntime extends PipelineOptions { - RuntimeValueProvider getBar(); - void setBar(RuntimeValueProvider bar); - } - - @Test - public void testOptionReturnTypeRuntime() { - BadOptionsRuntime options = PipelineOptionsFactory.as(BadOptionsRuntime.class); - expectedException.expect(RuntimeException.class); - expectedException.expectMessage( - "Method getBar should not have return type " - + "RuntimeValueProvider, use ValueProvider instead."); - RuntimeValueProvider provider = options.getBar(); - } - - /** A test interface. */ - public interface BadOptionsStatic extends PipelineOptions { - StaticValueProvider getBar(); - void setBar(StaticValueProvider bar); - } - - @Test - public void testOptionReturnTypeStatic() { - BadOptionsStatic options = PipelineOptionsFactory.as(BadOptionsStatic.class); - expectedException.expect(RuntimeException.class); - expectedException.expectMessage( - "Method getBar should not have return type " - + "StaticValueProvider, use ValueProvider instead."); - StaticValueProvider provider = options.getBar(); - } - - @Test - public void testSerializeDeserializeNoArg() throws Exception { - TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); - assertFalse(submitOptions.getFoo().isAccessible()); - ObjectMapper mapper = new ObjectMapper(); - String serializedOptions = mapper.writeValueAsString(submitOptions); - - String runnerString = ValueProviderUtils.updateSerializedOptions( - serializedOptions, ImmutableMap.of("foo", "quux")); - TestOptions runtime = mapper.readValue(runnerString, PipelineOptions.class) - .as(TestOptions.class); - - ValueProvider vp = runtime.getFoo(); - assertTrue(vp.isAccessible()); - assertEquals("quux", vp.get()); - assertEquals(vp.getClass(), StaticValueProvider.class); - } - - @Test - public void testSerializeDeserializeWithArg() throws Exception { - TestOptions submitOptions = PipelineOptionsFactory.fromArgs( - new String[]{"--foo=baz"}).as(TestOptions.class); - assertEquals("baz", submitOptions.getFoo().get()); - assertTrue(submitOptions.getFoo().isAccessible()); - ObjectMapper mapper = new ObjectMapper(); - String serializedOptions = mapper.writeValueAsString(submitOptions); - - String runnerString = ValueProviderUtils.updateSerializedOptions( - serializedOptions, ImmutableMap.of("foo", "quux")); - TestOptions runtime = mapper.readValue(runnerString, PipelineOptions.class) - .as(TestOptions.class); - - ValueProvider vp = runtime.getFoo(); - assertTrue(vp.isAccessible()); - assertEquals("quux", vp.get()); - } - - @Test - public void testNestedValueProviderStatic() throws Exception { - ValueProvider svp = StaticValueProvider.of("foo"); - ValueProvider nvp = NestedValueProvider.of( - svp, new SerializableFunction() { - @Override - public String apply(String from) { - return from + "bar"; - } - }); - assertTrue(nvp.isAccessible()); - assertEquals("foobar", nvp.get()); - assertEquals( - "NestedValueProvider{value=StaticValueProvider{value=foo}}", - nvp.toString()); - } - - @Test - public void testNestedValueProviderRuntime() throws Exception { - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - ValueProvider rvp = options.getBar(); - ValueProvider nvp = NestedValueProvider.of( - rvp, new SerializableFunction() { - @Override - public String apply(String from) { - return from + "bar"; - } - }); - ValueProvider doubleNvp = NestedValueProvider.of( - nvp, new SerializableFunction() { - @Override - public String apply(String from) { - return from; - } - }); - assertEquals("bar", ((NestedValueProvider) nvp).propertyName()); - assertEquals("bar", ((NestedValueProvider) doubleNvp).propertyName()); - assertFalse(nvp.isAccessible()); - expectedException.expect(RuntimeException.class); - expectedException.expectMessage("Not called from a runtime context"); - nvp.get(); - } - - private static class NonSerializable {} - - private static class NonSerializableTranslator - implements SerializableFunction { - @Override - public NonSerializable apply(String from) { - return new NonSerializable(); - } - } - - @Test - public void testNestedValueProviderSerialize() throws Exception { - ValueProvider nvp = NestedValueProvider.of( - StaticValueProvider.of("foo"), new NonSerializableTranslator()); - SerializableUtils.ensureSerializable(nvp); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java deleted file mode 100644 index 6c92649b28..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/options/ValueProviderUtilsTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.common.collect.ImmutableMap; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link ValueProviderUtils}. */ -@RunWith(JUnit4.class) -public class ValueProviderUtilsTest { - /** A test interface. */ - public interface TestOptions extends PipelineOptions { - String getString(); - void setString(String value); - - String getOtherString(); - void setOtherString(String value); - } - - @Test - public void testUpdateSerialize() throws Exception { - TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); - ObjectMapper mapper = new ObjectMapper(); - String serializedOptions = mapper.writeValueAsString(submitOptions); - String updatedOptions = ValueProviderUtils.updateSerializedOptions( - serializedOptions, ImmutableMap.of("string", "bar")); - TestOptions runtime = mapper.readValue(updatedOptions, PipelineOptions.class) - .as(TestOptions.class); - assertEquals("bar", runtime.getString()); - } - - @Test - public void testUpdateSerializeExistingValue() throws Exception { - TestOptions submitOptions = PipelineOptionsFactory.fromArgs( - new String[]{"--string=baz", "--otherString=quux"}).as(TestOptions.class); - ObjectMapper mapper = new ObjectMapper(); - String serializedOptions = mapper.writeValueAsString(submitOptions); - String updatedOptions = ValueProviderUtils.updateSerializedOptions( - serializedOptions, ImmutableMap.of("string", "bar")); - TestOptions runtime = mapper.readValue(updatedOptions, PipelineOptions.class) - .as(TestOptions.class); - assertEquals("bar", runtime.getString()); - assertEquals("quux", runtime.getOtherString()); - } - - @Test - public void testUpdateSerializeEmptyUpdate() throws Exception { - TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); - ObjectMapper mapper = new ObjectMapper(); - String serializedOptions = mapper.writeValueAsString(submitOptions); - String updatedOptions = ValueProviderUtils.updateSerializedOptions( - serializedOptions, ImmutableMap.of()); - TestOptions runtime = mapper.readValue(updatedOptions, PipelineOptions.class) - .as(TestOptions.class); - assertNull(runtime.getString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractorTest.java deleted file mode 100644 index 04c7edef94..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/AggregatorPipelineExtractorTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * Tests for {@link AggregatorPipelineExtractor}. - */ -@RunWith(JUnit4.class) -public class AggregatorPipelineExtractorTest { - @Mock - private Pipeline p; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetAggregatorStepsWithParDoBoundExtractsSteps() { - @SuppressWarnings("rawtypes") - ParDo.Bound bound = mock(ParDo.Bound.class, "Bound"); - AggregatorProvidingDoFn fn = new AggregatorProvidingDoFn<>(); - when(bound.getFn()).thenReturn(fn); - - Aggregator aggregatorOne = fn.addAggregator(new Sum.SumLongFn()); - Aggregator aggregatorTwo = fn.addAggregator(new Min.MinIntegerFn()); - - TransformTreeNode transformNode = mock(TransformTreeNode.class); - when(transformNode.getTransform()).thenReturn(bound); - - doAnswer(new VisitNodesAnswer(ImmutableList.of(transformNode))) - .when(p) - .traverseTopologically(Mockito.any(PipelineVisitor.class)); - - AggregatorPipelineExtractor extractor = new AggregatorPipelineExtractor(p); - - Map, Collection>> aggregatorSteps = - extractor.getAggregatorSteps(); - - assertEquals(ImmutableSet.>of(bound), aggregatorSteps.get(aggregatorOne)); - assertEquals(ImmutableSet.>of(bound), aggregatorSteps.get(aggregatorTwo)); - assertEquals(aggregatorSteps.size(), 2); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetAggregatorStepsWithParDoBoundMultiExtractsSteps() { - @SuppressWarnings("rawtypes") - ParDo.BoundMulti bound = mock(ParDo.BoundMulti.class, "BoundMulti"); - AggregatorProvidingDoFn fn = new AggregatorProvidingDoFn<>(); - when(bound.getFn()).thenReturn(fn); - - Aggregator aggregatorOne = fn.addAggregator(new Max.MaxLongFn()); - Aggregator aggregatorTwo = fn.addAggregator(new Min.MinDoubleFn()); - - TransformTreeNode transformNode = mock(TransformTreeNode.class); - when(transformNode.getTransform()).thenReturn(bound); - - doAnswer(new VisitNodesAnswer(ImmutableList.of(transformNode))) - .when(p) - .traverseTopologically(Mockito.any(PipelineVisitor.class)); - - AggregatorPipelineExtractor extractor = new AggregatorPipelineExtractor(p); - - Map, Collection>> aggregatorSteps = - extractor.getAggregatorSteps(); - - assertEquals(ImmutableSet.>of(bound), aggregatorSteps.get(aggregatorOne)); - assertEquals(ImmutableSet.>of(bound), aggregatorSteps.get(aggregatorTwo)); - assertEquals(2, aggregatorSteps.size()); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetAggregatorStepsWithOneAggregatorInMultipleStepsAddsSteps() { - @SuppressWarnings("rawtypes") - ParDo.Bound bound = mock(ParDo.Bound.class, "Bound"); - @SuppressWarnings("rawtypes") - ParDo.BoundMulti otherBound = mock(ParDo.BoundMulti.class, "otherBound"); - AggregatorProvidingDoFn fn = new AggregatorProvidingDoFn<>(); - when(bound.getFn()).thenReturn(fn); - when(otherBound.getFn()).thenReturn(fn); - - Aggregator aggregatorOne = fn.addAggregator(new Sum.SumLongFn()); - Aggregator aggregatorTwo = fn.addAggregator(new Min.MinDoubleFn()); - - TransformTreeNode transformNode = mock(TransformTreeNode.class); - when(transformNode.getTransform()).thenReturn(bound); - TransformTreeNode otherTransformNode = mock(TransformTreeNode.class); - when(otherTransformNode.getTransform()).thenReturn(otherBound); - - doAnswer(new VisitNodesAnswer(ImmutableList.of(transformNode, otherTransformNode))) - .when(p) - .traverseTopologically(Mockito.any(PipelineVisitor.class)); - - AggregatorPipelineExtractor extractor = new AggregatorPipelineExtractor(p); - - Map, Collection>> aggregatorSteps = - extractor.getAggregatorSteps(); - - assertEquals( - ImmutableSet.>of(bound, otherBound), aggregatorSteps.get(aggregatorOne)); - assertEquals( - ImmutableSet.>of(bound, otherBound), aggregatorSteps.get(aggregatorTwo)); - assertEquals(2, aggregatorSteps.size()); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetAggregatorStepsWithDifferentStepsAddsSteps() { - @SuppressWarnings("rawtypes") - ParDo.Bound bound = mock(ParDo.Bound.class, "Bound"); - - AggregatorProvidingDoFn fn = new AggregatorProvidingDoFn<>(); - Aggregator aggregatorOne = fn.addAggregator(new Sum.SumLongFn()); - - when(bound.getFn()).thenReturn(fn); - - @SuppressWarnings("rawtypes") - ParDo.BoundMulti otherBound = mock(ParDo.BoundMulti.class, "otherBound"); - - AggregatorProvidingDoFn otherFn = new AggregatorProvidingDoFn<>(); - Aggregator aggregatorTwo = otherFn.addAggregator(new Sum.SumDoubleFn()); - - when(otherBound.getFn()).thenReturn(otherFn); - - TransformTreeNode transformNode = mock(TransformTreeNode.class); - when(transformNode.getTransform()).thenReturn(bound); - TransformTreeNode otherTransformNode = mock(TransformTreeNode.class); - when(otherTransformNode.getTransform()).thenReturn(otherBound); - - doAnswer(new VisitNodesAnswer(ImmutableList.of(transformNode, otherTransformNode))) - .when(p) - .traverseTopologically(Mockito.any(PipelineVisitor.class)); - - AggregatorPipelineExtractor extractor = new AggregatorPipelineExtractor(p); - - Map, Collection>> aggregatorSteps = - extractor.getAggregatorSteps(); - - assertEquals(ImmutableSet.>of(bound), aggregatorSteps.get(aggregatorOne)); - assertEquals(ImmutableSet.>of(otherBound), aggregatorSteps.get(aggregatorTwo)); - assertEquals(2, aggregatorSteps.size()); - } - - private static class VisitNodesAnswer implements Answer { - private final List nodes; - - public VisitNodesAnswer(List nodes) { - this.nodes = nodes; - } - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - PipelineVisitor visitor = (PipelineVisitor) invocation.getArguments()[0]; - for (TransformTreeNode node : nodes) { - visitor.visitTransform(node); - } - return null; - } - } - - private static class AggregatorProvidingDoFn extends DoFn { - public Aggregator addAggregator( - CombineFn combiner) { - return createAggregator(randomName(), combiner); - } - - private String randomName() { - return UUID.randomUUID().toString(); - } - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - fail(); - } - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java deleted file mode 100644 index 2578f0c5d2..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunnerTest.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.TestCredential; - -import org.hamcrest.Description; -import org.hamcrest.Factory; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.TimeUnit; - -/** - * Tests for BlockingDataflowPipelineRunner. - */ -@RunWith(JUnit4.class) -public class BlockingDataflowPipelineRunnerTest { - - @Rule - public ExpectedLogs expectedLogs = ExpectedLogs.none(BlockingDataflowPipelineRunner.class); - - @Rule - public ExpectedException expectedThrown = ExpectedException.none(); - - /** - * A {@link Matcher} for a {@link DataflowJobException} that applies an underlying {@link Matcher} - * to the {@link DataflowPipelineJob} returned by {@link DataflowJobException#getJob()}. - */ - private static class DataflowJobExceptionMatcher - extends TypeSafeMatcher { - - private final Matcher matcher; - - public DataflowJobExceptionMatcher(Matcher matcher) { - this.matcher = matcher; - } - - @Override - public boolean matchesSafely(T ex) { - return matcher.matches(ex.getJob()); - } - - @Override - protected void describeMismatchSafely(T item, Description description) { - description.appendText("job "); - matcher.describeMismatch(item.getMessage(), description); - } - - @Override - public void describeTo(Description description) { - description.appendText("exception with job matching "); - description.appendDescriptionOf(matcher); - } - - @Factory - public static Matcher expectJob( - Matcher matcher) { - return new DataflowJobExceptionMatcher(matcher); - } - } - - /** - * A {@link Matcher} for a {@link DataflowPipelineJob} that applies an underlying {@link Matcher} - * to the return value of {@link DataflowPipelineJob#getJobId()}. - */ - private static class JobIdMatcher extends TypeSafeMatcher { - - private final Matcher matcher; - - public JobIdMatcher(Matcher matcher) { - this.matcher = matcher; - } - - @Override - public boolean matchesSafely(T job) { - return matcher.matches(job.getJobId()); - } - - @Override - protected void describeMismatchSafely(T item, Description description) { - description.appendText("jobId "); - matcher.describeMismatch(item.getJobId(), description); - } - - @Override - public void describeTo(Description description) { - description.appendText("job with jobId "); - description.appendDescriptionOf(matcher); - } - - @Factory - public static Matcher expectJobId(final String jobId) { - return new JobIdMatcher(equalTo(jobId)); - } - } - - /** - * A {@link Matcher} for a {@link DataflowJobUpdatedException} that applies an underlying - * {@link Matcher} to the {@link DataflowPipelineJob} returned by - * {@link DataflowJobUpdatedException#getReplacedByJob()}. - */ - private static class ReplacedByJobMatcher - extends TypeSafeMatcher { - - private final Matcher matcher; - - public ReplacedByJobMatcher(Matcher matcher) { - this.matcher = matcher; - } - - @Override - public boolean matchesSafely(T ex) { - return matcher.matches(ex.getReplacedByJob()); - } - - @Override - protected void describeMismatchSafely(T item, Description description) { - description.appendText("job "); - matcher.describeMismatch(item.getMessage(), description); - } - - @Override - public void describeTo(Description description) { - description.appendText("exception with replacedByJob() "); - description.appendDescriptionOf(matcher); - } - - @Factory - public static Matcher expectReplacedBy( - Matcher matcher) { - return new ReplacedByJobMatcher(matcher); - } - } - - /** - * Creates a mocked {@link DataflowPipelineJob} with the given {@code projectId} and {@code jobId} - * that will immediately terminate in the provided {@code terminalState}. - * - *

              The return value may be further mocked. - */ - private DataflowPipelineJob createMockJob( - String projectId, String jobId, State terminalState) throws Exception { - DataflowPipelineJob mockJob = mock(DataflowPipelineJob.class); - when(mockJob.getProjectId()).thenReturn(projectId); - when(mockJob.getJobId()).thenReturn(jobId); - when(mockJob.waitToFinish( - anyLong(), isA(TimeUnit.class), isA(MonitoringUtil.JobMessagesHandler.class))) - .thenReturn(terminalState); - return mockJob; - } - - /** - * Returns a {@link BlockingDataflowPipelineRunner} that will return the provided a job to return. - * Some {@link PipelineOptions} will be extracted from the job, such as the project ID. - */ - private BlockingDataflowPipelineRunner createMockRunner(DataflowPipelineJob job) - throws Exception { - DataflowPipelineRunner mockRunner = mock(DataflowPipelineRunner.class); - TestDataflowPipelineOptions options = - PipelineOptionsFactory.as(TestDataflowPipelineOptions.class); - options.setProject(job.getProjectId()); - - when(mockRunner.run(isA(Pipeline.class))).thenReturn(job); - - return new BlockingDataflowPipelineRunner(mockRunner, options); - } - - /** - * Tests that the {@link BlockingDataflowPipelineRunner} returns normally when a job terminates in - * the {@link State#DONE DONE} state. - */ - @Test - public void testJobDoneComplete() throws Exception { - createMockRunner(createMockJob("testJobDone-projectId", "testJobDone-jobId", State.DONE)) - .run(DirectPipeline.createForTest()); - expectedLogs.verifyInfo("Job finished with status DONE"); - } - - /** - * Tests that the {@link BlockingDataflowPipelineRunner} throws the appropriate exception - * when a job terminates in the {@link State#FAILED FAILED} state. - */ - @Test - public void testFailedJobThrowsException() throws Exception { - expectedThrown.expect(DataflowJobExecutionException.class); - expectedThrown.expect(DataflowJobExceptionMatcher.expectJob( - JobIdMatcher.expectJobId("testFailedJob-jobId"))); - createMockRunner(createMockJob("testFailedJob-projectId", "testFailedJob-jobId", State.FAILED)) - .run(DirectPipeline.createForTest()); - } - - /** - * Tests that the {@link BlockingDataflowPipelineRunner} throws the appropriate exception - * when a job terminates in the {@link State#CANCELLED CANCELLED} state. - */ - @Test - public void testCancelledJobThrowsException() throws Exception { - expectedThrown.expect(DataflowJobCancelledException.class); - expectedThrown.expect(DataflowJobExceptionMatcher.expectJob( - JobIdMatcher.expectJobId("testCancelledJob-jobId"))); - createMockRunner( - createMockJob("testCancelledJob-projectId", "testCancelledJob-jobId", State.CANCELLED)) - .run(DirectPipeline.createForTest()); - } - - /** - * Tests that the {@link BlockingDataflowPipelineRunner} throws the appropriate exception - * when a job terminates in the {@link State#UPDATED UPDATED} state. - */ - @Test - public void testUpdatedJobThrowsException() throws Exception { - expectedThrown.expect(DataflowJobUpdatedException.class); - expectedThrown.expect(DataflowJobExceptionMatcher.expectJob( - JobIdMatcher.expectJobId("testUpdatedJob-jobId"))); - expectedThrown.expect(ReplacedByJobMatcher.expectReplacedBy( - JobIdMatcher.expectJobId("testUpdatedJob-replacedByJobId"))); - DataflowPipelineJob job = - createMockJob("testUpdatedJob-projectId", "testUpdatedJob-jobId", State.UPDATED); - DataflowPipelineJob replacedByJob = - createMockJob("testUpdatedJob-projectId", "testUpdatedJob-replacedByJobId", State.DONE); - when(job.getReplacedByJob()).thenReturn(replacedByJob); - createMockRunner(job).run(DirectPipeline.createForTest()); - } - - /** - * Tests that the {@link BlockingDataflowPipelineRunner} throws the appropriate exception - * when a job terminates in the {@link State#UNKNOWN UNKNOWN} state, indicating that the - * Dataflow service returned a state that the SDK is unfamiliar with (possibly because it - * is an old SDK relative the service). - */ - @Test - public void testUnknownJobThrowsException() throws Exception { - expectedThrown.expect(IllegalStateException.class); - createMockRunner( - createMockJob("testUnknownJob-projectId", "testUnknownJob-jobId", State.UNKNOWN)) - .run(DirectPipeline.createForTest()); - } - - /** - * Tests that the {@link BlockingDataflowPipelineRunner} throws the appropriate exception - * when a job returns a {@code null} state, indicating that it failed to contact the service, - * including all of its built-in resilience logic. - */ - @Test - public void testNullJobThrowsException() throws Exception { - expectedThrown.expect(DataflowServiceException.class); - expectedThrown.expect(DataflowJobExceptionMatcher.expectJob( - JobIdMatcher.expectJobId("testNullJob-jobId"))); - createMockRunner( - createMockJob("testNullJob-projectId", "testNullJob-jobId", null)) - .run(DirectPipeline.createForTest()); - } - - @Test - public void testToString() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setJobName("TestJobName"); - options.setProject("test-project"); - options.setTempLocation("gs://test/temp/location"); - options.setGcpCredential(new TestCredential()); - options.setPathValidatorClass(NoopPathValidator.class); - assertEquals("BlockingDataflowPipelineRunner#testjobname", - BlockingDataflowPipelineRunner.fromOptions(options).toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java deleted file mode 100644 index 1d6ccc66ab..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java +++ /dev/null @@ -1,648 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.api.client.util.NanoClock; -import com.google.api.client.util.Sleeper; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Get; -import com.google.api.services.dataflow.Dataflow.Projects.Jobs.GetMetrics; -import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Messages; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.JobMetrics; -import com.google.api.services.dataflow.model.MetricStructuredName; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; -import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSetMultimap; - -import org.joda.time.Duration; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.math.BigDecimal; -import java.net.SocketTimeoutException; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; - -/** - * Tests for DataflowPipelineJob. - */ -@RunWith(JUnit4.class) -public class DataflowPipelineJobTest { - private static final String PROJECT_ID = "someProject"; - private static final String JOB_ID = "1234"; - - @Mock - private Dataflow mockWorkflowClient; - @Mock - private Dataflow.Projects mockProjects; - @Mock - private Dataflow.Projects.Jobs mockJobs; - @Rule - public FastNanoClockAndSleeper fastClock = new FastNanoClockAndSleeper(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - when(mockWorkflowClient.projects()).thenReturn(mockProjects); - when(mockProjects.jobs()).thenReturn(mockJobs); - } - - /** - * Validates that a given time is valid for the total time slept by a - * AttemptBoundedExponentialBackOff given the number of retries and - * an initial polling interval. - * - * @param pollingInterval The initial polling interval given. - * @param retries The number of retries made - * @param timeSleptMillis The amount of time slept by the clock. This is checked - * against the valid interval. - */ - private void checkValidInterval(Duration pollingInterval, int retries, long timeSleptMillis) { - long highSum = 0; - long lowSum = 0; - for (int i = 0; i < retries; i++) { - double currentInterval = - pollingInterval.getMillis() - * Math.pow(DataflowPipelineJob.DEFAULT_BACKOFF_EXPONENT, i); - double randomOffset = 0.5 * currentInterval; - highSum += Math.round(currentInterval + randomOffset); - lowSum += Math.round(currentInterval - randomOffset); - } - assertThat(timeSleptMillis, allOf(greaterThanOrEqualTo(lowSum), lessThanOrEqualTo(highSum))); - } - - @Test - public void testWaitToFinishMessagesFail() throws Exception { - Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); - - Job statusResponse = new Job(); - statusResponse.setCurrentState("JOB_STATE_" + State.DONE.name()); - when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); - when(statusRequest.execute()).thenReturn(statusResponse); - - MonitoringUtil.JobMessagesHandler jobHandler = mock(MonitoringUtil.JobMessagesHandler.class); - Dataflow.Projects.Jobs.Messages mockMessages = - mock(Dataflow.Projects.Jobs.Messages.class); - Messages.List listRequest = mock(Dataflow.Projects.Jobs.Messages.List.class); - when(mockJobs.messages()).thenReturn(mockMessages); - when(mockMessages.list(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(listRequest); - when(listRequest.execute()).thenThrow(SocketTimeoutException.class); - DataflowAggregatorTransforms dataflowAggregatorTransforms = - mock(DataflowAggregatorTransforms.class); - - DataflowPipelineJob job = new DataflowPipelineJob( - PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - - State state = job.waitToFinish(Duration.standardMinutes(5), jobHandler, fastClock, fastClock); - assertEquals(null, state); - } - - public State mockWaitToFinishInState(State state) throws Exception { - Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); - - Job statusResponse = new Job(); - statusResponse.setCurrentState("JOB_STATE_" + state.name()); - - when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); - when(statusRequest.execute()).thenReturn(statusResponse); - DataflowAggregatorTransforms dataflowAggregatorTransforms = - mock(DataflowAggregatorTransforms.class); - - DataflowPipelineJob job = new DataflowPipelineJob( - PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - - return job.waitToFinish(Duration.standardMinutes(1), null, fastClock, fastClock); - } - - /** - * Tests that the {@link DataflowPipelineJob} understands that the {@link State#DONE DONE} - * state is terminal. - */ - @Test - public void testWaitToFinishDone() throws Exception { - assertEquals(State.DONE, mockWaitToFinishInState(State.DONE)); - } - - /** - * Tests that the {@link DataflowPipelineJob} understands that the {@link State#FAILED FAILED} - * state is terminal. - */ - @Test - public void testWaitToFinishFailed() throws Exception { - assertEquals(State.FAILED, mockWaitToFinishInState(State.FAILED)); - } - - /** - * Tests that the {@link DataflowPipelineJob} understands that the {@link State#FAILED FAILED} - * state is terminal. - */ - @Test - public void testWaitToFinishCancelled() throws Exception { - assertEquals(State.CANCELLED, mockWaitToFinishInState(State.CANCELLED)); - } - - /** - * Tests that the {@link DataflowPipelineJob} understands that the {@link State#FAILED FAILED} - * state is terminal. - */ - @Test - public void testWaitToFinishUpdated() throws Exception { - assertEquals(State.UPDATED, mockWaitToFinishInState(State.UPDATED)); - } - - @Test - public void testWaitToFinishFail() throws Exception { - Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); - - when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); - when(statusRequest.execute()).thenThrow(IOException.class); - DataflowAggregatorTransforms dataflowAggregatorTransforms = - mock(DataflowAggregatorTransforms.class); - - DataflowPipelineJob job = new DataflowPipelineJob( - PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - - long startTime = fastClock.nanoTime(); - State state = job.waitToFinish(Duration.standardMinutes(5), null, fastClock, fastClock); - assertEquals(null, state); - long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime); - checkValidInterval(DataflowPipelineJob.MESSAGES_POLLING_INTERVAL, - DataflowPipelineJob.MESSAGES_POLLING_RETRIES, timeDiff); - } - - @Test - public void testWaitToFinishTimeFail() throws Exception { - Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); - - when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); - when(statusRequest.execute()).thenThrow(IOException.class); - DataflowAggregatorTransforms dataflowAggregatorTransforms = - mock(DataflowAggregatorTransforms.class); - - DataflowPipelineJob job = new DataflowPipelineJob( - PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - long startTime = fastClock.nanoTime(); - State state = job.waitToFinish(Duration.millis(4), null, fastClock, fastClock); - assertEquals(null, state); - long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime); - // Should only have slept for the 4 ms allowed. - assertEquals(4L, timeDiff); - } - - @Test - public void testCumulativeTimeOverflow() throws Exception { - Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); - - Job statusResponse = new Job(); - statusResponse.setCurrentState("JOB_STATE_RUNNING"); - when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); - when(statusRequest.execute()).thenReturn(statusResponse); - - DataflowAggregatorTransforms dataflowAggregatorTransforms = - mock(DataflowAggregatorTransforms.class); - - FastNanoClockAndFuzzySleeper clock = new FastNanoClockAndFuzzySleeper(); - - DataflowPipelineJob job = new DataflowPipelineJob( - PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - long startTime = clock.nanoTime(); - State state = job.waitToFinish(Duration.millis(4), null, clock, clock); - assertEquals(null, state); - long timeDiff = TimeUnit.NANOSECONDS.toMillis(clock.nanoTime() - startTime); - // Should only have slept for the 4 ms allowed. - assertThat(timeDiff, lessThanOrEqualTo(4L)); - } - - @Test - public void testGetStateReturnsServiceState() throws Exception { - Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); - - Job statusResponse = new Job(); - statusResponse.setCurrentState("JOB_STATE_" + State.RUNNING.name()); - - when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); - when(statusRequest.execute()).thenReturn(statusResponse); - - DataflowAggregatorTransforms dataflowAggregatorTransforms = - mock(DataflowAggregatorTransforms.class); - - DataflowPipelineJob job = new DataflowPipelineJob( - PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - - assertEquals( - State.RUNNING, - job.getStateWithRetries(DataflowPipelineJob.STATUS_BACKOFF_FACTORY.backoff(), fastClock)); - } - - @Test - public void testGetStateWithExceptionReturnsUnknown() throws Exception { - Dataflow.Projects.Jobs.Get statusRequest = mock(Dataflow.Projects.Jobs.Get.class); - - when(mockJobs.get(eq(PROJECT_ID), eq(JOB_ID))).thenReturn(statusRequest); - when(statusRequest.execute()).thenThrow(IOException.class); - DataflowAggregatorTransforms dataflowAggregatorTransforms = - mock(DataflowAggregatorTransforms.class); - - DataflowPipelineJob job = new DataflowPipelineJob( - PROJECT_ID, JOB_ID, mockWorkflowClient, dataflowAggregatorTransforms); - - long startTime = fastClock.nanoTime(); - assertEquals( - State.UNKNOWN, - job.getStateWithRetries(DataflowPipelineJob.STATUS_BACKOFF_FACTORY.backoff(), fastClock)); - long timeDiff = TimeUnit.NANOSECONDS.toMillis(fastClock.nanoTime() - startTime); - checkValidInterval(DataflowPipelineJob.STATUS_POLLING_INTERVAL, - DataflowPipelineJob.STATUS_POLLING_RETRIES, timeDiff); - } - - @Test - public void testGetAggregatorValuesWithNoMetricUpdatesReturnsEmptyValue() - throws IOException, AggregatorRetrievalException { - Aggregator aggregator = mock(Aggregator.class); - @SuppressWarnings("unchecked") - PTransform pTransform = mock(PTransform.class); - String stepName = "s1"; - String fullName = "Foo/Bar/Baz"; - AppliedPTransform appliedTransform = appliedPTransform(fullName, pTransform); - - DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms( - ImmutableSetMultimap., PTransform>of(aggregator, pTransform).asMap(), - ImmutableMap., String>of(appliedTransform, stepName)); - - GetMetrics getMetrics = mock(GetMetrics.class); - when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics); - JobMetrics jobMetrics = new JobMetrics(); - when(getMetrics.execute()).thenReturn(jobMetrics); - - jobMetrics.setMetrics(ImmutableList.of()); - - Get getState = mock(Get.class); - when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState); - Job modelJob = new Job(); - when(getState.execute()).thenReturn(modelJob); - modelJob.setCurrentState(State.RUNNING.toString()); - - DataflowPipelineJob job = - new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms); - - AggregatorValues values = job.getAggregatorValues(aggregator); - - assertThat(values.getValues(), empty()); - } - - @Test - public void testGetAggregatorValuesWithNullMetricUpdatesReturnsEmptyValue() - throws IOException, AggregatorRetrievalException { - Aggregator aggregator = mock(Aggregator.class); - @SuppressWarnings("unchecked") - PTransform pTransform = mock(PTransform.class); - String stepName = "s1"; - String fullName = "Foo/Bar/Baz"; - AppliedPTransform appliedTransform = appliedPTransform(fullName, pTransform); - - DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms( - ImmutableSetMultimap., PTransform>of(aggregator, pTransform).asMap(), - ImmutableMap., String>of(appliedTransform, stepName)); - - GetMetrics getMetrics = mock(GetMetrics.class); - when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics); - JobMetrics jobMetrics = new JobMetrics(); - when(getMetrics.execute()).thenReturn(jobMetrics); - - jobMetrics.setMetrics(null); - - Get getState = mock(Get.class); - when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState); - Job modelJob = new Job(); - when(getState.execute()).thenReturn(modelJob); - modelJob.setCurrentState(State.RUNNING.toString()); - - DataflowPipelineJob job = - new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms); - - AggregatorValues values = job.getAggregatorValues(aggregator); - - assertThat(values.getValues(), empty()); - } - - @Test - public void testGetAggregatorValuesWithSingleMetricUpdateReturnsSingletonCollection() - throws IOException, AggregatorRetrievalException { - CombineFn combineFn = new Sum.SumLongFn(); - String aggregatorName = "agg"; - Aggregator aggregator = new TestAggregator<>(combineFn, aggregatorName); - @SuppressWarnings("unchecked") - PTransform pTransform = mock(PTransform.class); - String stepName = "s1"; - String fullName = "Foo/Bar/Baz"; - AppliedPTransform appliedTransform = appliedPTransform(fullName, pTransform); - - DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms( - ImmutableSetMultimap., PTransform>of(aggregator, pTransform).asMap(), - ImmutableMap., String>of(appliedTransform, stepName)); - - GetMetrics getMetrics = mock(GetMetrics.class); - when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics); - JobMetrics jobMetrics = new JobMetrics(); - when(getMetrics.execute()).thenReturn(jobMetrics); - - MetricUpdate update = new MetricUpdate(); - long stepValue = 1234L; - update.setScalar(new BigDecimal(stepValue)); - - MetricStructuredName structuredName = new MetricStructuredName(); - structuredName.setName(aggregatorName); - structuredName.setContext(ImmutableMap.of("step", stepName)); - update.setName(structuredName); - - jobMetrics.setMetrics(ImmutableList.of(update)); - - Get getState = mock(Get.class); - when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState); - Job modelJob = new Job(); - when(getState.execute()).thenReturn(modelJob); - modelJob.setCurrentState(State.RUNNING.toString()); - - DataflowPipelineJob job = - new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms); - - AggregatorValues values = job.getAggregatorValues(aggregator); - - assertThat(values.getValuesAtSteps(), hasEntry(fullName, stepValue)); - assertThat(values.getValuesAtSteps().size(), equalTo(1)); - assertThat(values.getValues(), contains(stepValue)); - assertThat(values.getTotalValue(combineFn), equalTo(Long.valueOf(stepValue))); - } - - @Test - public void testGetAggregatorValuesWithMultipleMetricUpdatesReturnsCollection() - throws IOException, AggregatorRetrievalException { - CombineFn combineFn = new Sum.SumLongFn(); - String aggregatorName = "agg"; - Aggregator aggregator = new TestAggregator<>(combineFn, aggregatorName); - - @SuppressWarnings("unchecked") - PTransform pTransform = mock(PTransform.class); - String stepName = "s1"; - String fullName = "Foo/Bar/Baz"; - AppliedPTransform appliedTransform = appliedPTransform(fullName, pTransform); - - @SuppressWarnings("unchecked") - PTransform otherTransform = mock(PTransform.class); - String otherStepName = "s88"; - String otherFullName = "Spam/Ham/Eggs"; - AppliedPTransform otherAppliedTransform = - appliedPTransform(otherFullName, otherTransform); - - DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms( - ImmutableSetMultimap., PTransform>of( - aggregator, pTransform, aggregator, otherTransform).asMap(), - ImmutableMap., String>of( - appliedTransform, stepName, otherAppliedTransform, otherStepName)); - - GetMetrics getMetrics = mock(GetMetrics.class); - when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics); - JobMetrics jobMetrics = new JobMetrics(); - when(getMetrics.execute()).thenReturn(jobMetrics); - - MetricUpdate updateOne = new MetricUpdate(); - long stepValue = 1234L; - updateOne.setScalar(new BigDecimal(stepValue)); - - MetricStructuredName structuredNameOne = new MetricStructuredName(); - structuredNameOne.setName(aggregatorName); - structuredNameOne.setContext(ImmutableMap.of("step", stepName)); - updateOne.setName(structuredNameOne); - - MetricUpdate updateTwo = new MetricUpdate(); - long stepValueTwo = 1024L; - updateTwo.setScalar(new BigDecimal(stepValueTwo)); - - MetricStructuredName structuredNameTwo = new MetricStructuredName(); - structuredNameTwo.setName(aggregatorName); - structuredNameTwo.setContext(ImmutableMap.of("step", otherStepName)); - updateTwo.setName(structuredNameTwo); - - jobMetrics.setMetrics(ImmutableList.of(updateOne, updateTwo)); - - Get getState = mock(Get.class); - when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState); - Job modelJob = new Job(); - when(getState.execute()).thenReturn(modelJob); - modelJob.setCurrentState(State.RUNNING.toString()); - - DataflowPipelineJob job = - new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms); - - AggregatorValues values = job.getAggregatorValues(aggregator); - - assertThat(values.getValuesAtSteps(), hasEntry(fullName, stepValue)); - assertThat(values.getValuesAtSteps(), hasEntry(otherFullName, stepValueTwo)); - assertThat(values.getValuesAtSteps().size(), equalTo(2)); - assertThat(values.getValues(), containsInAnyOrder(stepValue, stepValueTwo)); - assertThat(values.getTotalValue(combineFn), equalTo(Long.valueOf(stepValue + stepValueTwo))); - } - - @Test - public void testGetAggregatorValuesWithUnrelatedMetricUpdateIgnoresUpdate() - throws IOException, AggregatorRetrievalException { - CombineFn combineFn = new Sum.SumLongFn(); - String aggregatorName = "agg"; - Aggregator aggregator = new TestAggregator<>(combineFn, aggregatorName); - @SuppressWarnings("unchecked") - PTransform pTransform = mock(PTransform.class); - String stepName = "s1"; - String fullName = "Foo/Bar/Baz"; - AppliedPTransform appliedTransform = appliedPTransform(fullName, pTransform); - - DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms( - ImmutableSetMultimap., PTransform>of(aggregator, pTransform).asMap(), - ImmutableMap., String>of(appliedTransform, stepName)); - - GetMetrics getMetrics = mock(GetMetrics.class); - when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics); - JobMetrics jobMetrics = new JobMetrics(); - when(getMetrics.execute()).thenReturn(jobMetrics); - - MetricUpdate ignoredUpdate = new MetricUpdate(); - ignoredUpdate.setScalar(null); - - MetricStructuredName ignoredName = new MetricStructuredName(); - ignoredName.setName("ignoredAggregator.elementCount.out0"); - ignoredName.setContext(null); - ignoredUpdate.setName(ignoredName); - - jobMetrics.setMetrics(ImmutableList.of(ignoredUpdate)); - - Get getState = mock(Get.class); - when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState); - Job modelJob = new Job(); - when(getState.execute()).thenReturn(modelJob); - modelJob.setCurrentState(State.RUNNING.toString()); - - DataflowPipelineJob job = - new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms); - - AggregatorValues values = job.getAggregatorValues(aggregator); - - assertThat(values.getValuesAtSteps().entrySet(), empty()); - assertThat(values.getValues(), empty()); - } - - @Test - public void testGetAggregatorValuesWithUnusedAggregatorThrowsException() - throws AggregatorRetrievalException { - Aggregator aggregator = mock(Aggregator.class); - - DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms( - ImmutableSetMultimap., PTransform>of().asMap(), - ImmutableMap., String>of()); - - DataflowPipelineJob job = - new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("not used in this pipeline"); - - job.getAggregatorValues(aggregator); - } - - @Test - public void testGetAggregatorValuesWhenClientThrowsExceptionThrowsAggregatorRetrievalException() - throws IOException, AggregatorRetrievalException { - CombineFn combineFn = new Sum.SumLongFn(); - String aggregatorName = "agg"; - Aggregator aggregator = new TestAggregator<>(combineFn, aggregatorName); - @SuppressWarnings("unchecked") - PTransform pTransform = mock(PTransform.class); - String stepName = "s1"; - String fullName = "Foo/Bar/Baz"; - AppliedPTransform appliedTransform = appliedPTransform(fullName, pTransform); - - DataflowAggregatorTransforms aggregatorTransforms = new DataflowAggregatorTransforms( - ImmutableSetMultimap., PTransform>of(aggregator, pTransform).asMap(), - ImmutableMap., String>of(appliedTransform, stepName)); - - GetMetrics getMetrics = mock(GetMetrics.class); - when(mockJobs.getMetrics(PROJECT_ID, JOB_ID)).thenReturn(getMetrics); - IOException cause = new IOException(); - when(getMetrics.execute()).thenThrow(cause); - - Get getState = mock(Get.class); - when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(getState); - Job modelJob = new Job(); - when(getState.execute()).thenReturn(modelJob); - modelJob.setCurrentState(State.RUNNING.toString()); - - DataflowPipelineJob job = - new DataflowPipelineJob(PROJECT_ID, JOB_ID, mockWorkflowClient, aggregatorTransforms); - - thrown.expect(AggregatorRetrievalException.class); - thrown.expectCause(is(cause)); - thrown.expectMessage(aggregator.toString()); - thrown.expectMessage("when retrieving Aggregator values for"); - - job.getAggregatorValues(aggregator); - } - - private static class TestAggregator implements Aggregator { - private final CombineFn combineFn; - private final String name; - - public TestAggregator(CombineFn combineFn, String name) { - this.combineFn = combineFn; - this.name = name; - } - - @Override - public void addValue(InT value) { - throw new AssertionError(); - } - - @Override - public String getName() { - return name; - } - - @Override - public CombineFn getCombineFn() { - return combineFn; - } - } - - private AppliedPTransform appliedPTransform( - String fullName, PTransform transform) { - return AppliedPTransform.of(fullName, mock(PInput.class), mock(POutput.class), transform); - } - - - private static class FastNanoClockAndFuzzySleeper implements NanoClock, Sleeper { - private long fastNanoTime; - - public FastNanoClockAndFuzzySleeper() { - fastNanoTime = NanoClock.SYSTEM.nanoTime(); - } - - @Override - public long nanoTime() { - return fastNanoTime; - } - - @Override - public void sleep(long millis) throws InterruptedException { - fastNanoTime += millis * 1000000L + ThreadLocalRandom.current().nextInt(500000); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrarTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrarTest.java deleted file mode 100644 index d5125cf5ce..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRegistrarTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.options.BlockingDataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ServiceLoader; - -/** Tests for {@link DataflowPipelineRegistrar}. */ -@RunWith(JUnit4.class) -public class DataflowPipelineRegistrarTest { - @Test - public void testCorrectOptionsAreReturned() { - assertEquals(ImmutableList.of(DataflowPipelineOptions.class, - BlockingDataflowPipelineOptions.class), - new DataflowPipelineRegistrar.Options().getPipelineOptions()); - } - - @Test - public void testCorrectRunnersAreReturned() { - assertEquals(ImmutableList.of(DataflowPipelineRunner.class, - BlockingDataflowPipelineRunner.class), - new DataflowPipelineRegistrar.Runner().getPipelineRunners()); - } - - @Test - public void testServiceLoaderForOptions() { - for (PipelineOptionsRegistrar registrar : - Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class).iterator())) { - if (registrar instanceof DataflowPipelineRegistrar.Options) { - return; - } - } - fail("Expected to find " + DataflowPipelineRegistrar.Options.class); - } - - @Test - public void testServiceLoaderForRunner() { - for (PipelineRunnerRegistrar registrar : - Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class).iterator())) { - if (registrar instanceof DataflowPipelineRegistrar.Runner) { - return; - } - } - fail("Expected to find " + DataflowPipelineRegistrar.Runner.class); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java deleted file mode 100644 index ffcc688165..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunnerTest.java +++ /dev/null @@ -1,1483 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.cloud.dataflow.sdk.util.WindowedValue.valueInGlobalWindow; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.ListJobsResponse; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineVisitor; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsList; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMap; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsMultimap; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.BatchViewAsSingleton; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.TransformedMap; -import com.google.cloud.dataflow.sdk.runners.dataflow.TestCountingSource; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecord; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.IsmRecordCoder; -import com.google.cloud.dataflow.sdk.runners.worker.IsmFormat.MetadataKeyCoder; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.DataflowReleaseInfo; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowedValue.FullWindowedValueCoder; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -import org.hamcrest.Description; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeMatcher; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.channels.FileChannel; -import java.nio.channels.SeekableByteChannel; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Tests for DataflowPipelineRunner. - */ -@RunWith(JUnit4.class) -public class DataflowPipelineRunnerTest { - - private static final String PROJECT_ID = "some-project"; - public static final String VALID_GS_SPAM_HAM_EGGS = "gs://spam/ham/eggs"; - public static final String VALID_SOMEBUCKET_SOME_PATH = "gs://somebucket/some/path"; - public static final String VALID_BUCKET_OBJECT = "gs://bucket/object"; - - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private GcsUtil mockGcsUtil; - private Dataflow.Projects.Jobs mockJobs; - - @Before - public void setUp() throws IOException { - this.mockGcsUtil = mock(GcsUtil.class); - this.mockJobs = mock(Dataflow.Projects.Jobs.class); - when(mockGcsUtil.create(any(GcsPath.class), anyString())) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); - - when(mockGcsUtil.isGcsPatternSupported(anyString())).thenReturn(true); - when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); - when(mockGcsUtil.bucketExists(GcsPath.fromUri(VALID_GS_SPAM_HAM_EGGS))).thenReturn(true); - when(mockGcsUtil.bucketExists(GcsPath.fromUri(VALID_SOMEBUCKET_SOME_PATH))).thenReturn(true); - when(mockGcsUtil.bucketExists(GcsPath.fromUri(VALID_BUCKET_OBJECT))).thenReturn(true); - } - - // Asserts that the given Job has all expected fields set. - private static void assertValidJob(Job job) { - assertNull(job.getId()); - assertNull(job.getCurrentState()); - assertTrue(Pattern.matches("[a-z]([-a-z0-9]*[a-z0-9])?", job.getName())); - } - - private DataflowPipeline buildDataflowPipeline(DataflowPipelineOptions options) { - options.setStableUniqueNames(CheckEnabled.ERROR); - DataflowPipeline p = DataflowPipeline.create(options); - - p.apply(TextIO.Read.named("ReadMyFile").from(VALID_BUCKET_OBJECT)) - .apply(TextIO.Write.named("WriteMyFile").to(VALID_BUCKET_OBJECT)); - - return p; - } - - private Dataflow buildMockDataflow() throws IOException { - Dataflow mockDataflowClient = mock(Dataflow.class); - Dataflow.Projects mockProjects = mock(Dataflow.Projects.class); - Dataflow.Projects.Jobs.Create mockRequest = - mock(Dataflow.Projects.Jobs.Create.class); - Dataflow.Projects.Jobs.List mockList = mock(Dataflow.Projects.Jobs.List.class); - - when(mockDataflowClient.projects()).thenReturn(mockProjects); - when(mockProjects.jobs()).thenReturn(mockJobs); - when(mockJobs.create(eq(PROJECT_ID), isA(Job.class))).thenReturn(mockRequest); - when(mockJobs.list(eq(PROJECT_ID))).thenReturn(mockList); - when(mockList.setPageToken(anyString())).thenReturn(mockList); - when(mockList.execute()) - .thenReturn( - new ListJobsResponse() - .setJobs( - Arrays.asList( - new Job() - .setName("oldjobname") - .setId("oldJobId") - .setCurrentState("JOB_STATE_RUNNING")))); - - Job resultJob = new Job(); - resultJob.setId("newid"); - when(mockRequest.execute()).thenReturn(resultJob); - return mockDataflowClient; - } - - private DataflowPipelineOptions buildPipelineOptions() throws IOException { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setProject(PROJECT_ID); - options.setTempLocation(VALID_SOMEBUCKET_SOME_PATH); - // Set FILES_PROPERTY to empty to prevent a default value calculated from classpath. - options.setFilesToStage(new LinkedList()); - options.setDataflowClient(buildMockDataflow()); - options.setGcsUtil(mockGcsUtil); - options.setGcpCredential(new TestCredential()); - return options; - } - - @Test - public void testFromOptionsWithUppercaseConvertsToLowercase() throws Exception { - String mixedCase = "ThisJobNameHasMixedCase"; - DataflowPipelineOptions options = buildPipelineOptions(); - options.setJobName(mixedCase); - - DataflowPipelineRunner runner = DataflowPipelineRunner.fromOptions(options); - assertThat(options.getJobName(), equalTo(mixedCase.toLowerCase())); - } - - @Test - public void testRun() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipeline p = buildDataflowPipeline(options); - DataflowPipelineJob job = p.run(); - assertEquals("newid", job.getJobId()); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - assertValidJob(jobCaptor.getValue()); - } - - /** Options for testing. */ - public interface RuntimeTestOptions extends PipelineOptions { - ValueProvider getInput(); - void setInput(ValueProvider value); - - ValueProvider getOutput(); - void setOutput(ValueProvider value); - } - - @Test - public void testTextIOWithRuntimeParameters() throws IOException { - DataflowPipelineOptions dataflowOptions = buildPipelineOptions(); - RuntimeTestOptions options = dataflowOptions.as(RuntimeTestOptions.class); - Pipeline p = buildDataflowPipeline(dataflowOptions); - p - .apply(TextIO.Read.from(options.getInput()).withoutValidation()) - .apply(TextIO.Write.to(options.getOutput()).withoutValidation()); - } - - @Test - public void testRunReturnDifferentRequestId() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - Dataflow mockDataflowClient = options.getDataflowClient(); - Dataflow.Projects.Jobs.Create mockRequest = mock(Dataflow.Projects.Jobs.Create.class); - when(mockDataflowClient.projects().jobs().create(eq(PROJECT_ID), any(Job.class))) - .thenReturn(mockRequest); - Job resultJob = new Job(); - resultJob.setId("newid"); - // Return a different request id. - resultJob.setClientRequestId("different_request_id"); - when(mockRequest.execute()).thenReturn(resultJob); - - DataflowPipeline p = buildDataflowPipeline(options); - try { - p.run(); - fail("Expected DataflowJobAlreadyExistsException"); - } catch (DataflowJobAlreadyExistsException expected) { - assertThat(expected.getMessage(), - containsString("If you want to submit a second job, try again by setting a " - + "different name using --jobName.")); - assertEquals(expected.getJob().getJobId(), resultJob.getId()); - } - } - - @Test - public void testUpdate() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setUpdate(true); - options.setJobName("oldJobName"); - DataflowPipeline p = buildDataflowPipeline(options); - DataflowPipelineJob job = p.run(); - assertEquals("newid", job.getJobId()); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - assertValidJob(jobCaptor.getValue()); - } - - @Test - public void testUpdateNonExistentPipeline() throws IOException { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Could not find running job named badjobname"); - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setUpdate(true); - options.setJobName("badJobName"); - DataflowPipeline p = buildDataflowPipeline(options); - p.run(); - } - - @Test - public void testUpdateAlreadyUpdatedPipeline() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setUpdate(true); - options.setJobName("oldJobName"); - Dataflow mockDataflowClient = options.getDataflowClient(); - Dataflow.Projects.Jobs.Create mockRequest = mock(Dataflow.Projects.Jobs.Create.class); - when(mockDataflowClient.projects().jobs().create(eq(PROJECT_ID), any(Job.class))) - .thenReturn(mockRequest); - final Job resultJob = new Job(); - resultJob.setId("newid"); - // Return a different request id. - resultJob.setClientRequestId("different_request_id"); - when(mockRequest.execute()).thenReturn(resultJob); - - DataflowPipeline p = buildDataflowPipeline(options); - - thrown.expect(DataflowJobAlreadyUpdatedException.class); - thrown.expect(new TypeSafeMatcher() { - @Override - public void describeTo(Description description) { - description.appendText("Expected job ID: " + resultJob.getId()); - } - - @Override - protected boolean matchesSafely(DataflowJobAlreadyUpdatedException item) { - return resultJob.getId().equals(item.getJob().getJobId()); - } - }); - thrown.expectMessage("The job named oldjobname with id: oldJobId has already been updated " - + "into job id: newid and cannot be updated again."); - p.run(); - } - - @Test - public void testRunWithFiles() throws IOException { - // Test that the function DataflowPipelineRunner.stageFiles works as - // expected. - final String gcsStaging = VALID_SOMEBUCKET_SOME_PATH; - final String gcsTemp = "gs://somebucket/some/temp/path"; - final String cloudDataflowDataset = "somedataset"; - - // Create some temporary files. - File temp1 = File.createTempFile("DataflowPipelineRunnerTest", "txt"); - temp1.deleteOnExit(); - File temp2 = File.createTempFile("DataflowPipelineRunnerTest2", "txt"); - temp2.deleteOnExit(); - - String overridePackageName = "alias.txt"; - - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcsUtil(mockGcsUtil); - options.setFilesToStage(ImmutableList.of( - temp1.getAbsolutePath(), - overridePackageName + "=" + temp2.getAbsolutePath())); - options.setStagingLocation(gcsStaging); - options.setTempLocation(gcsTemp); - options.setTempDatasetId(cloudDataflowDataset); - options.setProject(PROJECT_ID); - options.setJobName("job"); - options.setDataflowClient(buildMockDataflow()); - options.setGcpCredential(new TestCredential()); - - when(mockGcsUtil.bucketExists(GcsPath.fromUri(gcsTemp))).thenReturn(true); - DataflowPipeline p = buildDataflowPipeline(options); - - DataflowPipelineJob job = p.run(); - assertEquals("newid", job.getJobId()); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - Job workflowJob = jobCaptor.getValue(); - assertValidJob(workflowJob); - - assertEquals( - 2, - workflowJob.getEnvironment().getWorkerPools().get(0).getPackages().size()); - DataflowPackage workflowPackage1 = - workflowJob.getEnvironment().getWorkerPools().get(0).getPackages().get(0); - assertThat(workflowPackage1.getName(), startsWith(temp1.getName())); - DataflowPackage workflowPackage2 = - workflowJob.getEnvironment().getWorkerPools().get(0).getPackages().get(1); - assertEquals(overridePackageName, workflowPackage2.getName()); - - assertEquals( - "storage.googleapis.com/somebucket/some/temp/path", - workflowJob.getEnvironment().getTempStoragePrefix()); - assertEquals( - cloudDataflowDataset, - workflowJob.getEnvironment().getDataset()); - assertEquals( - DataflowReleaseInfo.getReleaseInfo().getName(), - workflowJob.getEnvironment().getUserAgent().get("name")); - assertEquals( - DataflowReleaseInfo.getReleaseInfo().getVersion(), - workflowJob.getEnvironment().getUserAgent().get("version")); - } - - @Test - public void runWithDefaultFilesToStage() throws Exception { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setFilesToStage(null); - DataflowPipelineRunner.fromOptions(options); - assertTrue(!options.getFilesToStage().isEmpty()); - } - - @Test - public void detectClassPathResourceWithFileResources() throws Exception { - File file = tmpFolder.newFile("file"); - File file2 = tmpFolder.newFile("file2"); - URLClassLoader classLoader = new URLClassLoader(new URL[]{ - file.toURI().toURL(), - file2.toURI().toURL() - }); - - assertEquals(ImmutableList.of(file.getAbsolutePath(), file2.getAbsolutePath()), - DataflowPipelineRunner.detectClassPathResourcesToStage(classLoader)); - } - - @Test - public void detectClassPathResourcesWithUnsupportedClassLoader() { - ClassLoader mockClassLoader = Mockito.mock(ClassLoader.class); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unable to use ClassLoader to detect classpath elements."); - - DataflowPipelineRunner.detectClassPathResourcesToStage(mockClassLoader); - } - - @Test - public void detectClassPathResourceWithNonFileResources() throws Exception { - String url = "http://www.google.com/all-the-secrets.jar"; - URLClassLoader classLoader = new URLClassLoader(new URL[]{ - new URL(url) - }); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unable to convert url (" + url + ") to file."); - - DataflowPipelineRunner.detectClassPathResourcesToStage(classLoader); - } - - @Test - public void testGcsStagingLocationInitialization() throws Exception { - // Test that the staging location is initialized correctly. - String gcsTemp = "gs://somebucket/some/temp/path"; - - // Set temp location (required), and check that staging location is set. - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcsUtil(mockGcsUtil); - options.setTempLocation(gcsTemp); - options.setProject(PROJECT_ID); - options.setGcpCredential(new TestCredential()); - - when(mockGcsUtil.bucketExists(GcsPath.fromUri(gcsTemp))).thenReturn(true); - DataflowPipelineRunner.fromOptions(options); - - assertNotNull(options.getStagingLocation()); - } - - @Test - public void testNonGcsFilePathInReadFailure() throws IOException { - Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - p.apply(TextIO.Read.named("ReadMyNonGcsFile").from(tmpFolder.newFile().getPath())); - - thrown.expectCause(Matchers.allOf( - instanceOf(IllegalArgumentException.class), - ThrowableMessageMatcher.hasMessage( - containsString("expected a valid 'gs://' path but was given")))); - p.run(); - } - - @Test - public void testNonGcsFilePathInWriteFailure() throws IOException { - Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from(VALID_BUCKET_OBJECT)); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); - pc.apply(TextIO.Write.named("WriteMyNonGcsFile").to("/tmp/file")); - } - - @Test - public void testMultiSlashGcsFileReadPath() throws IOException { - Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - p.apply(TextIO.Read.named("ReadInvalidGcsFile") - .from("gs://bucket/tmp//file")); - - thrown.expectCause(Matchers.allOf( - instanceOf(IllegalArgumentException.class), - ThrowableMessageMatcher.hasMessage(containsString("consecutive slashes")))); - p.run(); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - assertValidJob(jobCaptor.getValue()); - } - - @Test - public void testMultiSlashGcsFileWritePath() throws IOException { - Pipeline p = buildDataflowPipeline(buildPipelineOptions()); - PCollection pc = p.apply(TextIO.Read.named("ReadMyGcsFile").from(VALID_BUCKET_OBJECT)); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("consecutive slashes"); - pc.apply(TextIO.Write.named("WriteInvalidGcsFile").to("gs://bucket/tmp//file")); - } - - @Test - public void testInvalidTempLocation() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setTempLocation("file://temp/location"); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(containsString("expected a valid 'gs://' path but was given")); - DataflowPipelineRunner.fromOptions(options); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - assertValidJob(jobCaptor.getValue()); - } - - @Test - public void testInvalidStagingLocation() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setStagingLocation("file://my/staging/location"); - try { - DataflowPipelineRunner.fromOptions(options); - fail("fromOptions should have failed"); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("expected a valid 'gs://' path but was given")); - } - options.setStagingLocation("my/staging/location"); - try { - DataflowPipelineRunner.fromOptions(options); - fail("fromOptions should have failed"); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("expected a valid 'gs://' path but was given")); - } - } - - @Test - public void testInvalidProfileLocation() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setSaveProfilesToGcs("file://my/staging/location"); - try { - DataflowPipelineRunner.fromOptions(options); - fail("fromOptions should have failed"); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("expected a valid 'gs://' path but was given")); - } - - options.setSaveProfilesToGcs("my/staging/location"); - try { - DataflowPipelineRunner.fromOptions(options); - fail("fromOptions should have failed"); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("expected a valid 'gs://' path but was given")); - } - } - - @Test - public void testNonExistentTempLocation() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setTempLocation("gs://non-existent-bucket/location"); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(containsString( - "Output path does not exist or is not writeable: gs://non-existent-bucket/location")); - DataflowPipelineRunner.fromOptions(options); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - assertValidJob(jobCaptor.getValue()); - } - - @Test - public void testNonExistentStagingLocation() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setStagingLocation("gs://non-existent-bucket/location"); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(containsString( - "Output path does not exist or is not writeable: gs://non-existent-bucket/location")); - DataflowPipelineRunner.fromOptions(options); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - assertValidJob(jobCaptor.getValue()); - } - - @Test - public void testNonExistentProfileLocation() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setSaveProfilesToGcs("gs://non-existent-bucket/location"); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(containsString( - "Output path does not exist or is not writeable: gs://non-existent-bucket/location")); - DataflowPipelineRunner.fromOptions(options); - - ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(Job.class); - verify(mockJobs).create(eq(PROJECT_ID), jobCaptor.capture()); - assertValidJob(jobCaptor.getValue()); - } - - @Test - public void testNoProjectFails() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - - options.setRunner(DataflowPipelineRunner.class); - // Explicitly set to null to prevent the default instance factory from reading credentials - // from a user's environment, causing this test to fail. - options.setProject(null); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Project id"); - thrown.expectMessage("when running a Dataflow in the cloud"); - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testProjectId() throws IOException { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("foo-12345"); - options.setGcsUtil(mockGcsUtil); - - options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); - options.setGcpCredential(new TestCredential()); - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testProjectPrefix() throws IOException { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcsUtil(mockGcsUtil); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("google.com:some-project-12345"); - - options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); - options.setGcpCredential(new TestCredential()); - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testProjectNumber() throws IOException { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcsUtil(mockGcsUtil); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("12345"); - - options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Project ID"); - thrown.expectMessage("project number"); - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testProjectDescription() throws IOException { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcsUtil(mockGcsUtil); - options.setGcsUtil(mockGcsUtil); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("some project"); - - options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Project ID"); - thrown.expectMessage("project description"); - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testInvalidNumberOfWorkerHarnessThreads() throws IOException { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("foo-12345"); - options.setGcsUtil(mockGcsUtil); - - options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); - options.as(DataflowPipelineDebugOptions.class).setNumberOfWorkerHarnessThreads(-1); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Number of worker harness threads"); - thrown.expectMessage("Please make sure the value is non-negative."); - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testNoStagingLocationAndNoTempLocationFails() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("foo-project"); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Missing required value: at least one of tempLocation or stagingLocation must be set."); - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testStagingLocationAndNoTempLocationSucceeds() throws Exception { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcsUtil(mockGcsUtil); - options.setRunner(DataflowPipelineRunner.class); - options.setGcpCredential(new TestCredential()); - options.setProject("foo-project"); - options.setStagingLocation(VALID_GS_SPAM_HAM_EGGS); - - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testTempLocationAndNoStagingLocationSucceeds() throws Exception { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcsUtil(mockGcsUtil); - options.setRunner(DataflowPipelineRunner.class); - options.setGcpCredential(new TestCredential()); - options.setProject("foo-project"); - options.setTempLocation(VALID_GS_SPAM_HAM_EGGS);; - - DataflowPipelineRunner.fromOptions(options); - } - - @Test - public void testInvalidJobName() throws IOException { - List invalidNames = Arrays.asList( - "invalid_name", - "0invalid", - "invalid-"); - List expectedReason = Arrays.asList( - "JobName invalid", - "JobName invalid", - "JobName invalid"); - - for (int i = 0; i < invalidNames.size(); ++i) { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setJobName(invalidNames.get(i)); - - try { - DataflowPipelineRunner.fromOptions(options); - fail("Expected IllegalArgumentException for jobName " - + options.getJobName()); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), - containsString(expectedReason.get(i))); - } - } - } - - @Test - public void testValidJobName() throws IOException { - List names = Arrays.asList("ok", "Ok", "A-Ok", "ok-123", - "this-one-is-fairly-long-01234567890123456789"); - - for (String name : names) { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setJobName(name); - - DataflowPipelineRunner runner = DataflowPipelineRunner - .fromOptions(options); - assertNotNull(runner); - } - } - - @Test - public void testGcsUploadBufferSizeIsUnsetForBatchWhenDefault() throws IOException { - DataflowPipelineOptions batchOptions = buildPipelineOptions(); - batchOptions.setRunner(DataflowPipelineRunner.class); - Pipeline.create(batchOptions); - assertNull(batchOptions.getGcsUploadBufferSizeBytes()); - } - - @Test - public void testGcsUploadBufferSizeIsSetForStreamingWhenDefault() throws IOException { - DataflowPipelineOptions streamingOptions = buildPipelineOptions(); - streamingOptions.setStreaming(true); - streamingOptions.setRunner(DataflowPipelineRunner.class); - Pipeline.create(streamingOptions); - assertEquals( - DataflowPipelineRunner.GCS_UPLOAD_BUFFER_SIZE_BYTES_DEFAULT, - streamingOptions.getGcsUploadBufferSizeBytes().intValue()); - } - - @Test - public void testGcsUploadBufferSizeUnchangedWhenNotDefault() throws IOException { - int gcsUploadBufferSizeBytes = 12345678; - DataflowPipelineOptions batchOptions = buildPipelineOptions(); - batchOptions.setGcsUploadBufferSizeBytes(gcsUploadBufferSizeBytes); - batchOptions.setRunner(DataflowPipelineRunner.class); - Pipeline.create(batchOptions); - assertEquals(gcsUploadBufferSizeBytes, batchOptions.getGcsUploadBufferSizeBytes().intValue()); - - DataflowPipelineOptions streamingOptions = buildPipelineOptions(); - streamingOptions.setStreaming(true); - streamingOptions.setGcsUploadBufferSizeBytes(gcsUploadBufferSizeBytes); - streamingOptions.setRunner(DataflowPipelineRunner.class); - Pipeline.create(streamingOptions); - assertEquals( - gcsUploadBufferSizeBytes, streamingOptions.getGcsUploadBufferSizeBytes().intValue()); - } - - /** - * A fake PTransform for testing. - */ - public static class TestTransform - extends PTransform, PCollection> { - public boolean translated = false; - - @Override - public PCollection apply(PCollection input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - input.isBounded()); - } - - @Override - protected Coder getDefaultOutputCoder(PCollection input) { - return input.getCoder(); - } - } - - @Test - public void testTransformTranslatorMissing() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipeline p = DataflowPipeline.create(options); - - p.apply(Create.of(Arrays.asList(1, 2, 3))) - .apply(new TestTransform()); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage(Matchers.containsString("no translator registered")); - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()); - } - - @Test - public void testTransformTranslator() throws IOException { - // Test that we can provide a custom translation - DataflowPipelineOptions options = buildPipelineOptions(); - when(mockGcsUtil.bucketExists(GcsPath.fromUri("gs://somebucket/some/path/staging"))) - .thenReturn(true); - DataflowPipeline p = DataflowPipeline.create(options); - TestTransform transform = new TestTransform(); - - p.apply(Create.of(Arrays.asList(1, 2, 3)).withCoder(BigEndianIntegerCoder.of())) - .apply(transform); - - DataflowPipelineTranslator translator = DataflowPipelineRunner - .fromOptions(options).getTranslator(); - - DataflowPipelineTranslator.registerTransformTranslator( - TestTransform.class, - new DataflowPipelineTranslator.TransformTranslator() { - @SuppressWarnings("unchecked") - @Override - public void translate( - TestTransform transform, - DataflowPipelineTranslator.TranslationContext context) { - transform.translated = true; - - // Note: This is about the minimum needed to fake out a - // translation. This obviously isn't a real translation. - context.addStep(transform, "TestTranslate"); - context.addOutput("output", context.getOutput(transform)); - } - }); - - translator.translate( - p, p.getRunner(), Collections.emptyList()); - assertTrue(transform.translated); - } - - /** Records all the composite transforms visited within the Pipeline. */ - private static class CompositeTransformRecorder implements PipelineVisitor { - private List> transforms = new ArrayList<>(); - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - if (node.getTransform() != null) { - transforms.add(node.getTransform()); - } - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - } - - @Override - public void visitTransform(TransformTreeNode node) { - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - } - - public List> getCompositeTransforms() { - return transforms; - } - } - - @Test - public void testApplyIsScopedToExactClass() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipeline p = DataflowPipeline.create(options); - - Create.TimestampedValues transform = - Create.timestamped(Arrays.asList(TimestampedValue.of("TestString", Instant.now()))); - p.apply(transform); - - CompositeTransformRecorder recorder = new CompositeTransformRecorder(); - p.traverseTopologically(recorder); - - assertThat("Expected to have seen CreateTimestamped composite transform.", - recorder.getCompositeTransforms(), - Matchers.>contains(transform)); - } - - @Test - public void testToString() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setJobName("TestJobName"); - options.setProject("test-project"); - options.setTempLocation("gs://test/temp/location"); - options.setGcpCredential(new TestCredential()); - options.setPathValidatorClass(NoopPathValidator.class); - assertEquals( - "DataflowPipelineRunner#testjobname", - DataflowPipelineRunner.fromOptions(options).toString()); - } - - private static PipelineOptions makeOptions(boolean streaming) { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setRunner(DataflowPipelineRunner.class); - options.setStreaming(streaming); - options.setJobName("TestJobName"); - options.setProject("test-project"); - options.setTempLocation("gs://test/temp/location"); - options.setGcpCredential(new TestCredential()); - options.setPathValidatorClass(NoopPathValidator.class); - return options; - } - - private void testUnsupportedSource(PTransform source, String name, boolean streaming) - throws Exception { - String mode = streaming ? "streaming" : "batch"; - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage( - "The DataflowPipelineRunner in " + mode + " mode does not support " + name); - - Pipeline p = Pipeline.create(makeOptions(streaming)); - p.apply(source); - p.run(); - } - - @Test - public void testReadUnboundedUnsupportedInBatch() throws Exception { - testUnsupportedSource(Read.from(new TestCountingSource(1)), "Read.Unbounded", false); - } - - private void testUnsupportedSink( - PTransform, PDone> sink, String name, boolean streaming) - throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage( - "The DataflowPipelineRunner in streaming mode does not support " + name); - - Pipeline p = Pipeline.create(makeOptions(streaming)); - p.apply(Create.of("foo")).apply(sink); - p.run(); - } - - @Test - public void testAvroIOSinkUnsupportedInStreaming() throws Exception { - testUnsupportedSink(AvroIO.Write.to("foo").withSchema(String.class), "AvroIO.Write", true); - } - - @Test - public void testBatchViewAsSingletonToIsmRecord() throws Exception { - DoFnTester>>>, - IsmRecord>> doFnTester = - DoFnTester.of( - new BatchViewAsSingleton.IsmRecordForSingularValuePerWindowDoFn - (GlobalWindow.Coder.INSTANCE)); - - assertThat( - doFnTester.processBatch( - ImmutableList.of(KV.>>>of( - 0, ImmutableList.of(KV.of(GlobalWindow.INSTANCE, valueInGlobalWindow("a")))))), - contains(IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE), valueInGlobalWindow("a")))); - } - - @Test - public void testBatchViewAsSingletonToIsmRecordWithMultipleValuesThrowsException() - throws Exception { - DoFnTester>>>, - IsmRecord>> doFnTester = - DoFnTester.of( - new BatchViewAsSingleton.IsmRecordForSingularValuePerWindowDoFn - (GlobalWindow.Coder.INSTANCE)); - - try { - doFnTester.processBatch( - ImmutableList.of(KV.>>>of( - 0, ImmutableList.of( - KV.of(GlobalWindow.INSTANCE, valueInGlobalWindow("a")), - KV.of(GlobalWindow.INSTANCE, valueInGlobalWindow("b")))))); - fail("Expected UserCodeException"); - } catch (UserCodeException e) { - assertTrue(e.getCause() instanceof IllegalStateException); - IllegalStateException rootCause = (IllegalStateException) e.getCause(); - assertThat(rootCause.getMessage(), containsString("found for singleton within window")); - } - } - - @Test - public void testBatchViewAsListToIsmRecordForGlobalWindow() throws Exception { - DoFnTester>> doFnTester = - DoFnTester.of(new BatchViewAsList.ToIsmRecordForGlobalWindowDoFn()); - - // The order of the output elements is important relative to processing order - assertThat(doFnTester.processBatch(ImmutableList.of("a", "b", "c")), contains( - IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE, 0L), valueInGlobalWindow("a")), - IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE, 1L), valueInGlobalWindow("b")), - IsmRecord.of(ImmutableList.of(GlobalWindow.INSTANCE, 2L), valueInGlobalWindow("c")))); - } - - @Test - public void testBatchViewAsListToIsmRecordForNonGlobalWindow() throws Exception { - DoFnTester>>>, - IsmRecord>> doFnTester = - DoFnTester.of( - new BatchViewAsList.ToIsmRecordForNonGlobalWindowDoFn( - IntervalWindow.getCoder())); - - IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); - IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); - IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); - - Iterable>>>> inputElements = - ImmutableList.of( - KV.of(1, (Iterable>>) ImmutableList.of( - KV.of( - windowA, WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), - KV.of( - windowA, WindowedValue.of(111L, new Instant(3), windowA, PaneInfo.NO_FIRING)), - KV.of( - windowA, WindowedValue.of(112L, new Instant(4), windowA, PaneInfo.NO_FIRING)), - KV.of( - windowB, WindowedValue.of(120L, new Instant(12), windowB, PaneInfo.NO_FIRING)), - KV.of( - windowB, WindowedValue.of(121L, new Instant(14), windowB, PaneInfo.NO_FIRING)) - )), - KV.of(2, (Iterable>>) ImmutableList.of( - KV.of( - windowC, WindowedValue.of(210L, new Instant(25), windowC, PaneInfo.NO_FIRING)) - ))); - - // The order of the output elements is important relative to processing order - assertThat(doFnTester.processBatch(inputElements), contains( - IsmRecord.of(ImmutableList.of(windowA, 0L), - WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), - IsmRecord.of(ImmutableList.of(windowA, 1L), - WindowedValue.of(111L, new Instant(3), windowA, PaneInfo.NO_FIRING)), - IsmRecord.of(ImmutableList.of(windowA, 2L), - WindowedValue.of(112L, new Instant(4), windowA, PaneInfo.NO_FIRING)), - IsmRecord.of(ImmutableList.of(windowB, 0L), - WindowedValue.of(120L, new Instant(12), windowB, PaneInfo.NO_FIRING)), - IsmRecord.of(ImmutableList.of(windowB, 1L), - WindowedValue.of(121L, new Instant(14), windowB, PaneInfo.NO_FIRING)), - IsmRecord.of(ImmutableList.of(windowC, 0L), - WindowedValue.of(210L, new Instant(25), windowC, PaneInfo.NO_FIRING)))); - } - - @Test - public void testToIsmRecordForMapLikeDoFn() throws Exception { - TupleTag>> outputForSizeTag = new TupleTag<>(); - TupleTag>> outputForEntrySetTag = new TupleTag<>(); - - Coder keyCoder = VarLongCoder.of(); - Coder windowCoder = IntervalWindow.getCoder(); - - IsmRecordCoder> ismCoder = IsmRecordCoder.of( - 1, - 2, - ImmutableList.>of( - MetadataKeyCoder.of(keyCoder), - IntervalWindow.getCoder(), - BigEndianLongCoder.of()), - FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); - - DoFnTester, WindowedValue>>>, - IsmRecord>> doFnTester = - DoFnTester.of(new BatchViewAsMultimap.ToIsmRecordForMapLikeDoFn( - outputForSizeTag, - outputForEntrySetTag, - windowCoder, - keyCoder, - ismCoder, - false /* unique keys */)); - doFnTester.setSideOutputTags(TupleTagList.of( - ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); - - IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); - IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); - IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); - - Iterable, WindowedValue>>>> inputElements = - ImmutableList.of( - KV.of(1, (Iterable, WindowedValue>>) ImmutableList.of( - KV.of(KV.of(1L, windowA), - WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), - // same window same key as to previous - KV.of(KV.of(1L, windowA), - WindowedValue.of(111L, new Instant(2), windowA, PaneInfo.NO_FIRING)), - // same window different key as to previous - KV.of(KV.of(2L, windowA), - WindowedValue.of(120L, new Instant(3), windowA, PaneInfo.NO_FIRING)), - // different window same key as to previous - KV.of(KV.of(2L, windowB), - WindowedValue.of(210L, new Instant(11), windowB, PaneInfo.NO_FIRING)), - // different window and different key as to previous - KV.of(KV.of(3L, windowB), - WindowedValue.of(220L, new Instant(12), windowB, PaneInfo.NO_FIRING)))), - KV.of(2, (Iterable, WindowedValue>>) ImmutableList.of( - // different shard - KV.of(KV.of(4L, windowC), - WindowedValue.of(330L, new Instant(21), windowC, PaneInfo.NO_FIRING))))); - - // The order of the output elements is important relative to processing order - assertThat(doFnTester.processBatch(inputElements), contains( - IsmRecord.of( - ImmutableList.of(1L, windowA, 0L), - WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), - IsmRecord.of( - ImmutableList.of(1L, windowA, 1L), - WindowedValue.of(111L, new Instant(2), windowA, PaneInfo.NO_FIRING)), - IsmRecord.of( - ImmutableList.of(2L, windowA, 0L), - WindowedValue.of(120L, new Instant(3), windowA, PaneInfo.NO_FIRING)), - IsmRecord.of( - ImmutableList.of(2L, windowB, 0L), - WindowedValue.of(210L, new Instant(11), windowB, PaneInfo.NO_FIRING)), - IsmRecord.of( - ImmutableList.of(3L, windowB, 0L), - WindowedValue.of(220L, new Instant(12), windowB, PaneInfo.NO_FIRING)), - IsmRecord.of( - ImmutableList.of(4L, windowC, 0L), - WindowedValue.of(330L, new Instant(21), windowC, PaneInfo.NO_FIRING)))); - - // Verify the number of unique keys per window. - assertThat(doFnTester.takeSideOutputElements(outputForSizeTag), contains( - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowA)), - KV.of(windowA, 2L)), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), - KV.of(windowB, 2L)), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowC)), - KV.of(windowC, 1L)) - )); - - // Verify the output for the unique keys. - assertThat(doFnTester.takeSideOutputElements(outputForEntrySetTag), contains( - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowA)), - KV.of(windowA, 1L)), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowA)), - KV.of(windowA, 2L)), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), - KV.of(windowB, 2L)), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), - KV.of(windowB, 3L)), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowC)), - KV.of(windowC, 4L)) - )); - } - - @Test - public void testToIsmRecordForMapLikeDoFnWithoutUniqueKeysThrowsException() throws Exception { - TupleTag>> outputForSizeTag = new TupleTag<>(); - TupleTag>> outputForEntrySetTag = new TupleTag<>(); - - Coder keyCoder = VarLongCoder.of(); - Coder windowCoder = IntervalWindow.getCoder(); - - IsmRecordCoder> ismCoder = IsmRecordCoder.of( - 1, - 2, - ImmutableList.>of( - MetadataKeyCoder.of(keyCoder), - IntervalWindow.getCoder(), - BigEndianLongCoder.of()), - FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); - - DoFnTester, WindowedValue>>>, - IsmRecord>> doFnTester = - DoFnTester.of(new BatchViewAsMultimap.ToIsmRecordForMapLikeDoFn( - outputForSizeTag, - outputForEntrySetTag, - windowCoder, - keyCoder, - ismCoder, - true /* unique keys */)); - doFnTester.setSideOutputTags(TupleTagList.of( - ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); - - IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); - - Iterable, WindowedValue>>>> inputElements = - ImmutableList.of( - KV.of(1, (Iterable, WindowedValue>>) ImmutableList.of( - KV.of(KV.of(1L, windowA), - WindowedValue.of(110L, new Instant(1), windowA, PaneInfo.NO_FIRING)), - // same window same key as to previous - KV.of(KV.of(1L, windowA), - WindowedValue.of(111L, new Instant(2), windowA, PaneInfo.NO_FIRING))))); - - try { - doFnTester.processBatch(inputElements); - fail("Expected UserCodeException"); - } catch (UserCodeException e) { - assertTrue(e.getCause() instanceof IllegalStateException); - IllegalStateException rootCause = (IllegalStateException) e.getCause(); - assertThat(rootCause.getMessage(), containsString("Unique keys are expected but found key")); - } - } - - @Test - public void testToIsmMetadataRecordForSizeDoFn() throws Exception { - TupleTag>> outputForSizeTag = new TupleTag<>(); - TupleTag>> outputForEntrySetTag = new TupleTag<>(); - - Coder keyCoder = VarLongCoder.of(); - Coder windowCoder = IntervalWindow.getCoder(); - - IsmRecordCoder> ismCoder = IsmRecordCoder.of( - 1, - 2, - ImmutableList.>of( - MetadataKeyCoder.of(keyCoder), - IntervalWindow.getCoder(), - BigEndianLongCoder.of()), - FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); - - DoFnTester>>, - IsmRecord>> doFnTester = DoFnTester.of( - new BatchViewAsMultimap.ToIsmMetadataRecordForSizeDoFn( - windowCoder)); - doFnTester.setSideOutputTags(TupleTagList.of( - ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); - - IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); - IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); - IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); - - Iterable>>> inputElements = - ImmutableList.of( - KV.of(1, - (Iterable>) ImmutableList.of( - KV.of(windowA, 2L), - KV.of(windowA, 3L), - KV.of(windowB, 7L))), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), - (Iterable>) ImmutableList.of( - KV.of(windowC, 9L)))); - - // The order of the output elements is important relative to processing order - assertThat(doFnTester.processBatch(inputElements), contains( - IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), windowA, 0L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), 5L)), - IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), windowB, 0L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), 7L)), - IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), windowC, 0L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), 9L)) - )); - } - - @Test - public void testToIsmMetadataRecordForKeyDoFn() throws Exception { - TupleTag>> outputForSizeTag = new TupleTag<>(); - TupleTag>> outputForEntrySetTag = new TupleTag<>(); - - Coder keyCoder = VarLongCoder.of(); - Coder windowCoder = IntervalWindow.getCoder(); - - IsmRecordCoder> ismCoder = IsmRecordCoder.of( - 1, - 2, - ImmutableList.>of( - MetadataKeyCoder.of(keyCoder), - IntervalWindow.getCoder(), - BigEndianLongCoder.of()), - FullWindowedValueCoder.of(VarLongCoder.of(), windowCoder)); - - DoFnTester>>, - IsmRecord>> doFnTester = DoFnTester.of( - new BatchViewAsMultimap.ToIsmMetadataRecordForKeyDoFn( - keyCoder, windowCoder)); - doFnTester.setSideOutputTags(TupleTagList.of( - ImmutableList.>of(outputForSizeTag, outputForEntrySetTag))); - - IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); - IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); - IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); - - Iterable>>> inputElements = - ImmutableList.of( - KV.of(1, - (Iterable>) ImmutableList.of( - KV.of(windowA, 2L), - // same window as previous - KV.of(windowA, 3L), - // different window as previous - KV.of(windowB, 3L))), - KV.of(ismCoder.hash(ImmutableList.of(IsmFormat.getMetadataKey(), windowB)), - (Iterable>) ImmutableList.of( - KV.of(windowC, 3L)))); - - // The order of the output elements is important relative to processing order - assertThat(doFnTester.processBatch(inputElements), contains( - IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), windowA, 1L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), 2L)), - IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), windowA, 2L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), 3L)), - IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), windowB, 1L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), 3L)), - IsmRecord.>meta( - ImmutableList.of(IsmFormat.getMetadataKey(), windowC, 1L), - CoderUtils.encodeToByteArray(VarLongCoder.of(), 3L)) - )); - } - - @Test - public void testToMapDoFn() throws Exception { - Coder windowCoder = IntervalWindow.getCoder(); - - DoFnTester>>>>, - IsmRecord, - Long>>>> doFnTester = - DoFnTester.of(new BatchViewAsMap.ToMapDoFn(windowCoder)); - - - IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); - IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); - IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); - - Iterable>>>>> inputElements = - ImmutableList.of( - KV.of(1, - (Iterable>>>) ImmutableList.of( - KV.of(windowA, WindowedValue.of( - KV.of(1L, 11L), new Instant(3), windowA, PaneInfo.NO_FIRING)), - KV.of(windowA, WindowedValue.of( - KV.of(2L, 21L), new Instant(7), windowA, PaneInfo.NO_FIRING)), - KV.of(windowB, WindowedValue.of( - KV.of(2L, 21L), new Instant(13), windowB, PaneInfo.NO_FIRING)), - KV.of(windowB, WindowedValue.of( - KV.of(3L, 31L), new Instant(15), windowB, PaneInfo.NO_FIRING)))), - KV.of(2, - (Iterable>>>) ImmutableList.of( - KV.of(windowC, WindowedValue.of( - KV.of(4L, 41L), new Instant(25), windowC, PaneInfo.NO_FIRING))))); - - // The order of the output elements is important relative to processing order - List, - Long>>>> output = - doFnTester.processBatch(inputElements); - assertEquals(3, output.size()); - Map outputMap; - - outputMap = output.get(0).getValue().getValue(); - assertEquals(2, outputMap.size()); - assertEquals(ImmutableMap.of(1L, 11L, 2L, 21L), outputMap); - - outputMap = output.get(1).getValue().getValue(); - assertEquals(2, outputMap.size()); - assertEquals(ImmutableMap.of(2L, 21L, 3L, 31L), outputMap); - - outputMap = output.get(2).getValue().getValue(); - assertEquals(1, outputMap.size()); - assertEquals(ImmutableMap.of(4L, 41L), outputMap); - } - - @Test - public void testToMultimapDoFn() throws Exception { - Coder windowCoder = IntervalWindow.getCoder(); - - DoFnTester>>>>, - IsmRecord>, - Iterable>>>> doFnTester = - DoFnTester.of( - new BatchViewAsMultimap.ToMultimapDoFn(windowCoder)); - - - IntervalWindow windowA = new IntervalWindow(new Instant(0), new Instant(10)); - IntervalWindow windowB = new IntervalWindow(new Instant(10), new Instant(20)); - IntervalWindow windowC = new IntervalWindow(new Instant(20), new Instant(30)); - - Iterable>>>>> inputElements = - ImmutableList.of( - KV.of(1, - (Iterable>>>) ImmutableList.of( - KV.of(windowA, WindowedValue.of( - KV.of(1L, 11L), new Instant(3), windowA, PaneInfo.NO_FIRING)), - KV.of(windowA, WindowedValue.of( - KV.of(1L, 12L), new Instant(5), windowA, PaneInfo.NO_FIRING)), - KV.of(windowA, WindowedValue.of( - KV.of(2L, 21L), new Instant(7), windowA, PaneInfo.NO_FIRING)), - KV.of(windowB, WindowedValue.of( - KV.of(2L, 21L), new Instant(13), windowB, PaneInfo.NO_FIRING)), - KV.of(windowB, WindowedValue.of( - KV.of(3L, 31L), new Instant(15), windowB, PaneInfo.NO_FIRING)))), - KV.of(2, - (Iterable>>>) ImmutableList.of( - KV.of(windowC, WindowedValue.of( - KV.of(4L, 41L), new Instant(25), windowC, PaneInfo.NO_FIRING))))); - - // The order of the output elements is important relative to processing order - List>, - Iterable>>>> output = - doFnTester.processBatch(inputElements); - assertEquals(3, output.size()); - Map> outputMap; - - outputMap = output.get(0).getValue().getValue(); - assertEquals(2, outputMap.size()); - assertThat(outputMap.get(1L), containsInAnyOrder(11L, 12L)); - assertThat(outputMap.get(2L), containsInAnyOrder(21L)); - - outputMap = output.get(1).getValue().getValue(); - assertEquals(2, outputMap.size()); - assertThat(outputMap.get(2L), containsInAnyOrder(21L)); - assertThat(outputMap.get(3L), containsInAnyOrder(31L)); - - outputMap = output.get(2).getValue().getValue(); - assertEquals(1, outputMap.size()); - assertThat(outputMap.get(4L), containsInAnyOrder(41L)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java deleted file mode 100644 index f5709ccab6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.TestCredential; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link DataflowPipeline}. */ -@RunWith(JUnit4.class) -public class DataflowPipelineTest { - @Test - public void testToString() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setJobName("TestJobName"); - options.setProject("project-id"); - options.setTempLocation("gs://test/temp/location"); - options.setGcpCredential(new TestCredential()); - options.setPathValidatorClass(NoopPathValidator.class); - assertEquals("DataflowPipeline#testjobname" /* lowercased for service requirements */, - DataflowPipeline.create(options).toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java deleted file mode 100644 index 78d905d160..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineTranslatorTest.java +++ /dev/null @@ -1,1018 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static com.google.cloud.dataflow.sdk.util.Structs.addObject; -import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.api.services.dataflow.model.Job; -import com.google.api.services.dataflow.model.Step; -import com.google.api.services.dataflow.model.WorkerPool; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO.PubsubTopic; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineWorkerPoolOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.DataflowPathValidator; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.OutputReference; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.Structs; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentMatcher; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -/** - * Tests for DataflowPipelineTranslator. - */ -@RunWith(JUnit4.class) -public class DataflowPipelineTranslatorTest implements Serializable { - @Rule public transient ExpectedException thrown = ExpectedException.none(); - - // A Custom Mockito matcher for an initial Job that checks that all - // expected fields are set. - private static class IsValidCreateRequest extends ArgumentMatcher { - @Override - public boolean matches(Object o) { - Job job = (Job) o; - return job.getId() == null - && job.getProjectId() == null - && job.getName() != null - && job.getType() != null - && job.getEnvironment() != null - && job.getSteps() != null - && job.getCurrentState() == null - && job.getCurrentStateTime() == null - && job.getExecutionInfo() == null - && job.getCreateTime() == null; - } - } - - private DataflowPipeline buildPipeline(DataflowPipelineOptions options) { - DataflowPipeline p = DataflowPipeline.create(options); - - p.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/object")) - .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/object")); - - return p; - } - - private static Dataflow buildMockDataflow( - ArgumentMatcher jobMatcher) throws IOException { - Dataflow mockDataflowClient = mock(Dataflow.class); - Dataflow.Projects mockProjects = mock(Dataflow.Projects.class); - Dataflow.Projects.Jobs mockJobs = mock(Dataflow.Projects.Jobs.class); - Dataflow.Projects.Jobs.Create mockRequest = mock( - Dataflow.Projects.Jobs.Create.class); - - when(mockDataflowClient.projects()).thenReturn(mockProjects); - when(mockProjects.jobs()).thenReturn(mockJobs); - when(mockJobs.create(eq("someProject"), argThat(jobMatcher))) - .thenReturn(mockRequest); - - Job resultJob = new Job(); - resultJob.setId("newid"); - when(mockRequest.execute()).thenReturn(resultJob); - return mockDataflowClient; - } - - private static DataflowPipelineOptions buildPipelineOptions() throws IOException { - GcsUtil mockGcsUtil = mock(GcsUtil.class); - when(mockGcsUtil.expand(any(GcsPath.class))).then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); - when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(true); - when(mockGcsUtil.isGcsPatternSupported(anyString())).thenCallRealMethod(); - - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - options.setJobName("some-job-name"); - options.setProject("some-project"); - options.setTempLocation(GcsPath.fromComponents("somebucket", "some/path").toString()); - options.setFilesToStage(new LinkedList()); - options.setDataflowClient(buildMockDataflow(new IsValidCreateRequest())); - options.setGcsUtil(mockGcsUtil); - return options; - } - - @Test - public void testSettingOfSdkPipelineOptions() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setRunner(DataflowPipelineRunner.class); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - Map sdkPipelineOptions = job.getEnvironment().getSdkPipelineOptions(); - assertThat(sdkPipelineOptions, hasKey("options")); - Map optionsMap = (Map) sdkPipelineOptions.get("options"); - - assertThat(optionsMap, hasEntry("appName", (Object) "DataflowPipelineTranslatorTest")); - assertThat(optionsMap, hasEntry("project", (Object) "some-project")); - assertThat(optionsMap, - hasEntry("pathValidatorClass", (Object) DataflowPathValidator.class.getName())); - assertThat(optionsMap, - hasEntry("runner", (Object) DataflowPipelineRunner.class.getName())); - assertThat(optionsMap, hasEntry("jobName", (Object) "some-job-name")); - assertThat(optionsMap, hasEntry("tempLocation", (Object) "gs://somebucket/some/path")); - assertThat(optionsMap, - hasEntry("stagingLocation", (Object) "gs://somebucket/some/path/staging")); - assertThat(optionsMap, hasEntry("stableUniqueNames", (Object) "WARNING")); - assertThat(optionsMap, hasEntry("streaming", (Object) false)); - assertThat(optionsMap, hasEntry("numberOfWorkerHarnessThreads", (Object) 0)); - } - - private static class TestValueProvider implements ValueProvider, Serializable { - @Override - public boolean isAccessible() { - return false; - } - - @Override - public String get() { - throw new RuntimeException("Should not be called."); - } - } - - @Test - public void testInaccessibleProvider() throws Exception { - DataflowPipelineOptions options = buildPipelineOptions(); - options.setRunner(DataflowPipelineRunner.class); - Pipeline pipeline = Pipeline.create(options); - DataflowPipelineTranslator t = DataflowPipelineTranslator.fromOptions(options); - - pipeline.apply(TextIO.Read.from(new TestValueProvider()).withoutValidation()); - - // Check that translation does not fail. - t.translate( - pipeline, - (DataflowPipelineRunner) pipeline.getRunner(), - Collections.emptyList()); - } - - @Test - public void testNetworkConfig() throws IOException { - final String testNetwork = "test-network"; - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setNetwork(testNetwork); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertEquals(testNetwork, - job.getEnvironment().getWorkerPools().get(0).getNetwork()); - } - - @Test - public void testNetworkConfigMissing() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertNull(job.getEnvironment().getWorkerPools().get(0).getNetwork()); - } - - @Test - public void testSubnetworkConfig() throws IOException { - final String testSubnetwork = "regions/REGION/subnetworks/SUBNETWORK"; - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setSubnetwork(testSubnetwork); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertEquals(testSubnetwork, - job.getEnvironment().getWorkerPools().get(0).getSubnetwork()); - } - - @Test - public void testSubnetworkConfigMissing() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertNull(job.getEnvironment().getWorkerPools().get(0).getSubnetwork()); - } - - @Test - public void testScalingAlgorithmMissing() throws IOException { - DataflowPipelineOptions options = buildPipelineOptions(); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - // Autoscaling settings are always set. - assertNull( - job - .getEnvironment() - .getWorkerPools() - .get(0) - .getAutoscalingSettings() - .getAlgorithm()); - assertEquals( - 0, - job - .getEnvironment() - .getWorkerPools() - .get(0) - .getAutoscalingSettings() - .getMaxNumWorkers() - .intValue()); - } - - @Test - public void testScalingAlgorithmNone() throws IOException { - final DataflowPipelineWorkerPoolOptions.AutoscalingAlgorithmType noScaling = - DataflowPipelineWorkerPoolOptions.AutoscalingAlgorithmType.NONE; - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setAutoscalingAlgorithm(noScaling); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertEquals( - "AUTOSCALING_ALGORITHM_NONE", - job - .getEnvironment() - .getWorkerPools() - .get(0) - .getAutoscalingSettings() - .getAlgorithm()); - assertEquals( - 0, - job - .getEnvironment() - .getWorkerPools() - .get(0) - .getAutoscalingSettings() - .getMaxNumWorkers() - .intValue()); - } - - @Test - public void testMaxNumWorkersIsPassedWhenNoAlgorithmIsSet() throws IOException { - final DataflowPipelineWorkerPoolOptions.AutoscalingAlgorithmType noScaling = null; - DataflowPipelineOptions options = buildPipelineOptions(); - options.setMaxNumWorkers(42); - options.setAutoscalingAlgorithm(noScaling); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertNull( - job - .getEnvironment() - .getWorkerPools() - .get(0) - .getAutoscalingSettings() - .getAlgorithm()); - assertEquals( - 42, - job - .getEnvironment() - .getWorkerPools() - .get(0) - .getAutoscalingSettings() - .getMaxNumWorkers() - .intValue()); - } - - @Test - public void testZoneConfig() throws IOException { - final String testZone = "test-zone-1"; - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setZone(testZone); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertEquals(testZone, - job.getEnvironment().getWorkerPools().get(0).getZone()); - } - - @Test - public void testWorkerMachineTypeConfig() throws IOException { - final String testMachineType = "test-machine-type"; - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setWorkerMachineType(testMachineType); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - - WorkerPool workerPool = job.getEnvironment().getWorkerPools().get(0); - assertEquals(testMachineType, workerPool.getMachineType()); - } - - @Test - public void testDiskSizeGbConfig() throws IOException { - final Integer diskSizeGb = 1234; - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setDiskSizeGb(diskSizeGb); - - DataflowPipeline p = buildPipeline(options); - p.traverseTopologically(new RecordingPipelineVisitor()); - Job job = - DataflowPipelineTranslator.fromOptions(options) - .translate(p, p.getRunner(), Collections.emptyList()) - .getJob(); - - assertEquals(1, job.getEnvironment().getWorkerPools().size()); - assertEquals(diskSizeGb, - job.getEnvironment().getWorkerPools().get(0).getDiskSizeGb()); - } - - @Test - public void testPredefinedAddStep() throws Exception { - DataflowPipelineOptions options = buildPipelineOptions(); - - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - DataflowPipelineTranslator.registerTransformTranslator( - EmbeddedTransform.class, new EmbeddedTranslator()); - - // Create a predefined step using another pipeline - Step predefinedStep = createPredefinedStep(); - - // Create a pipeline that the predefined step will be embedded into - DataflowPipeline pipeline = DataflowPipeline.create(options); - pipeline.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/in")) - .apply(ParDo.of(new NoOpFn())) - .apply(new EmbeddedTransform(predefinedStep.clone())) - .apply(ParDo.of(new NoOpFn())); - Job job = translator.translate( - pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - - List steps = job.getSteps(); - assertEquals(4, steps.size()); - - // The input to the embedded step should match the output of the step before - Map step1Out = getOutputPortReference(steps.get(1)); - Map step2In = getDictionary( - steps.get(2).getProperties(), PropertyNames.PARALLEL_INPUT); - assertEquals(step1Out, step2In); - - // The output from the embedded step should match the input of the step after - Map step2Out = getOutputPortReference(steps.get(2)); - Map step3In = getDictionary( - steps.get(3).getProperties(), PropertyNames.PARALLEL_INPUT); - assertEquals(step2Out, step3In); - - // The step should not have been modified other than remapping the input - Step predefinedStepClone = predefinedStep.clone(); - Step embeddedStepClone = steps.get(2).clone(); - predefinedStepClone.getProperties().remove(PropertyNames.PARALLEL_INPUT); - embeddedStepClone.getProperties().remove(PropertyNames.PARALLEL_INPUT); - assertEquals(predefinedStepClone, embeddedStepClone); - } - - /** - * Construct a OutputReference for the output of the step. - */ - private static OutputReference getOutputPortReference(Step step) throws Exception { - // TODO: This should be done via a Structs accessor. - @SuppressWarnings("unchecked") - List> output = - (List>) step.getProperties().get(PropertyNames.OUTPUT_INFO); - String outputTagId = getString(Iterables.getOnlyElement(output), PropertyNames.OUTPUT_NAME); - return new OutputReference(step.getName(), outputTagId); - } - - /** - * Returns a Step for a DoFn by creating and translating a pipeline. - */ - private static Step createPredefinedStep() throws Exception { - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - DataflowPipeline pipeline = DataflowPipeline.create(options); - String stepName = "DoFn1"; - pipeline.apply(TextIO.Read.named("ReadMyFile").from("gs://bucket/in")) - .apply(ParDo.of(new NoOpFn()).named(stepName)) - .apply(TextIO.Write.named("WriteMyFile").to("gs://bucket/out")); - Job job = translator.translate( - pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - - assertEquals(13, job.getSteps().size()); - Step step = job.getSteps().get(1); - assertEquals(stepName, getString(step.getProperties(), PropertyNames.USER_NAME)); - return step; - } - - private static class NoOpFn extends DoFn { - @Override public void processElement(ProcessContext c) throws Exception { - c.output(c.element()); - } - } - - /** - * A placeholder transform that will be used to substitute a predefined Step. - */ - private static class EmbeddedTransform - extends PTransform, PCollection> { - private final Step step; - - public EmbeddedTransform(Step step) { - this.step = step; - } - - @Override - public PCollection apply(PCollection input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - input.isBounded()); - } - - @Override - protected Coder getDefaultOutputCoder() { - return StringUtf8Coder.of(); - } - } - - /** - * A TransformTranslator that adds the predefined Step using - * {@link TranslationContext#addStep} and remaps the input port reference. - */ - private static class EmbeddedTranslator - implements DataflowPipelineTranslator.TransformTranslator { - @Override public void translate(EmbeddedTransform transform, TranslationContext context) { - addObject(transform.step.getProperties(), PropertyNames.PARALLEL_INPUT, - context.asOutputReference(context.getInput(transform))); - context.addStep(transform, transform.step); - } - } - - /** - * A composite transform that returns an output that is unrelated to - * the input. - */ - private static class UnrelatedOutputCreator - extends PTransform, PCollection> { - - @Override - public PCollection apply(PCollection input) { - // Apply an operation so that this is a composite transform. - input.apply(Count.perElement()); - - // Return a value unrelated to the input. - return input.getPipeline().apply(Create.of(1, 2, 3, 4)); - } - - @Override - protected Coder getDefaultOutputCoder() { - return VarIntCoder.of(); - } - } - - /** - * A composite transform that returns an output that is unbound. - */ - private static class UnboundOutputCreator - extends PTransform, PDone> { - - @Override - public PDone apply(PCollection input) { - // Apply an operation so that this is a composite transform. - input.apply(Count.perElement()); - - return PDone.in(input.getPipeline()); - } - - @Override - protected Coder getDefaultOutputCoder() { - return VoidCoder.of(); - } - } - - /** - * A composite transform that returns a partially bound output. - * - *

              This is not allowed and will result in a failure. - */ - private static class PartiallyBoundOutputCreator - extends PTransform, PCollectionTuple> { - - public final TupleTag sumTag = new TupleTag<>("sum"); - public final TupleTag doneTag = new TupleTag<>("done"); - - @Override - public PCollectionTuple apply(PCollection input) { - PCollection sum = input.apply(Sum.integersGlobally()); - - // Fails here when attempting to construct a tuple with an unbound object. - return PCollectionTuple.of(sumTag, sum) - .and(doneTag, PCollection.createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - input.isBounded())); - } - } - - @Test - public void testMultiGraphPipelineSerialization() throws IOException { - DataflowPipeline p = DataflowPipeline.create(buildPipelineOptions()); - - PCollection input = p.begin() - .apply(Create.of(1, 2, 3)); - - input.apply(new UnrelatedOutputCreator()); - input.apply(new UnboundOutputCreator()); - - DataflowPipelineTranslator t = DataflowPipelineTranslator.fromOptions( - PipelineOptionsFactory.as(DataflowPipelineOptions.class)); - - // Check that translation doesn't fail. - t.translate(p, p.getRunner(), Collections.emptyList()); - } - - @Test - public void testPartiallyBoundFailure() throws IOException { - Pipeline p = DataflowPipeline.create(buildPipelineOptions()); - - PCollection input = p.begin() - .apply(Create.of(1, 2, 3)); - - thrown.expect(IllegalStateException.class); - input.apply(new PartiallyBoundOutputCreator()); - - Assert.fail("Failure expected from use of partially bound output"); - } - - /** - * This tests a few corner cases that should not crash. - */ - @Test - public void testGoodWildcards() throws Exception { - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipeline pipeline = DataflowPipeline.create(options); - DataflowPipelineTranslator t = DataflowPipelineTranslator.fromOptions(options); - - applyRead(pipeline, "gs://bucket/foo"); - applyRead(pipeline, "gs://bucket/foo/"); - applyRead(pipeline, "gs://bucket/foo/*"); - applyRead(pipeline, "gs://bucket/foo/?"); - applyRead(pipeline, "gs://bucket/foo/[0-9]"); - applyRead(pipeline, "gs://bucket/foo/*baz*"); - applyRead(pipeline, "gs://bucket/foo/*baz?"); - applyRead(pipeline, "gs://bucket/foo/[0-9]baz?"); - applyRead(pipeline, "gs://bucket/foo/baz/*"); - applyRead(pipeline, "gs://bucket/foo/baz/*wonka*"); - applyRead(pipeline, "gs://bucket/foo/*baz/wonka*"); - applyRead(pipeline, "gs://bucket/foo*/baz"); - applyRead(pipeline, "gs://bucket/foo?/baz"); - applyRead(pipeline, "gs://bucket/foo[0-9]/baz"); - - // Check that translation doesn't fail. - t.translate(pipeline, pipeline.getRunner(), Collections.emptyList()); - } - - private void applyRead(Pipeline pipeline, String path) { - pipeline.apply("Read(" + path + ")", TextIO.Read.from(path)); - } - - /** - * Recursive wildcards are not supported. - * This tests "**". - */ - @Test - public void testBadWildcardRecursive() throws Exception { - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipeline pipeline = DataflowPipeline.create(options); - DataflowPipelineTranslator t = DataflowPipelineTranslator.fromOptions(options); - - pipeline.apply(TextIO.Read.from("gs://bucket/foo**/baz")); - - // Check that translation does fail. - thrown.expectCause(allOf( - instanceOf(IllegalArgumentException.class), - ThrowableMessageMatcher.hasMessage(containsString("Unsupported wildcard usage")))); - t.translate(pipeline, pipeline.getRunner(), Collections.emptyList()); - } - - @Test - public void testToSingletonTranslation() throws Exception { - // A "change detector" test that makes sure the translation - // of getting a PCollectionView does not change - // in bad ways during refactor - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setExperiments(ImmutableList.of("disable_ism_side_input")); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - - DataflowPipeline pipeline = DataflowPipeline.create(options); - pipeline.apply(Create.of(1)) - .apply(View.asSingleton()); - Job job = translator.translate( - pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - - List steps = job.getSteps(); - assertEquals(2, steps.size()); - - Step createStep = steps.get(0); - assertEquals("CreateCollection", createStep.getKind()); - - Step collectionToSingletonStep = steps.get(1); - assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); - - } - - @Test - public void testToIterableTranslation() throws Exception { - // A "change detector" test that makes sure the translation - // of getting a PCollectionView> does not change - // in bad ways during refactor - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setExperiments(ImmutableList.of("disable_ism_side_input")); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - - DataflowPipeline pipeline = DataflowPipeline.create(options); - pipeline.apply(Create.of(1, 2, 3)) - .apply(View.asIterable()); - Job job = translator.translate( - pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - - List steps = job.getSteps(); - assertEquals(2, steps.size()); - - Step createStep = steps.get(0); - assertEquals("CreateCollection", createStep.getKind()); - - Step collectionToSingletonStep = steps.get(1); - assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); - } - - @Test - public void testPubsubIOReadTranslation() throws Exception { - // A "change detector" test that makes sure the translation of PubsubIO.Read - // does not change in bad ways during refactor - String project = "fakeproject"; - String topicName = "faketopic"; - PubsubTopic topic = - PubsubTopic.fromPath(String.format("projects/%s/topics/%s", project, topicName)); - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setStreaming(true); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - - DataflowPipeline pipeline = DataflowPipeline.create(options); - pipeline.apply(PubsubIO.Read.topic(topic.asPath())); - Job job = - translator - .translate(pipeline, pipeline.getRunner(), Collections.emptyList()) - .getJob(); - - List steps = job.getSteps(); - assertEquals(1, steps.size()); - - Step pubsubStep = steps.get(0); - - // Ensure the core translation does not change; if we get this far, then the right translator - // was invoked, so we don't try to combinatorially test every combination of configuration - // options. That would be for the unit tests of that translator. - assertEquals("ParallelRead", pubsubStep.getKind()); - assertEquals("pubsub", Structs.getString(pubsubStep.getProperties(), PropertyNames.FORMAT)); - assertEquals( - topic.asV1Beta1Path(), - Structs.getString(pubsubStep.getProperties(), PropertyNames.PUBSUB_TOPIC)); - assertEquals( - "PubsubIO.Read", Structs.getString(pubsubStep.getProperties(), PropertyNames.USER_NAME)); - } - - @Test - public void testPubsubIOWriteTranslation() throws Exception { - // A "change detector" test that makes sure the translation of PubsubIO.Read - // does not change in bad ways during refactor - String project = "fakeproject"; - String topicName = "faketopic"; - PubsubTopic topic = - PubsubTopic.fromPath(String.format("projects/%s/topics/%s", project, topicName)); - - DataflowPipelineOptions options = buildPipelineOptions(); - options.setStreaming(true); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - - DataflowPipeline pipeline = DataflowPipeline.create(options); - pipeline.apply(Create.of("hello", "goodbye")) - .apply(PubsubIO.Write.topic(topic.asPath())); - Job job = - translator - .translate(pipeline, pipeline.getRunner(), Collections.emptyList()) - .getJob(); - - // There are 6 steps from the Create and 1 from the PubsubIO.Write - List steps = job.getSteps(); - assertEquals(7, steps.size()); - - Step prepStep = steps.get(5); - Step writeStep = steps.get(6); - - // Ensure the core translation does not change; if we get this far, then the right translator - // was invoked, so we don't try to combinatorially test every combination of configuration - // options. That would be for the unit tests of that translator. - assertEquals("ParallelWrite", writeStep.getKind()); - assertEquals("pubsub", Structs.getString(writeStep.getProperties(), PropertyNames.FORMAT)); - assertEquals( - topic.asV1Beta1Path(), - Structs.getString(writeStep.getProperties(), PropertyNames.PUBSUB_TOPIC)); - assertEquals( - "PubsubIO.Write/StreamingPubsubIOWrite", - Structs.getString(writeStep.getProperties(), PropertyNames.USER_NAME)); - } - - @Test - public void testToSingletonTranslationWithIsmSideInput() throws Exception { - // A "change detector" test that makes sure the translation - // of getting a PCollectionView does not change - // in bad ways during refactor - - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - - DataflowPipeline pipeline = DataflowPipeline.create(options); - pipeline.apply(Create.of(1)) - .apply(View.asSingleton()); - Job job = translator.translate( - pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - - List steps = job.getSteps(); - assertEquals(5, steps.size()); - - @SuppressWarnings("unchecked") - List> toIsmRecordOutputs = - (List>) steps.get(3).getProperties().get(PropertyNames.OUTPUT_INFO); - assertTrue( - Structs.getBoolean(Iterables.getOnlyElement(toIsmRecordOutputs), "use_indexed_format")); - - Step collectionToSingletonStep = steps.get(4); - assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); - } - - @Test - public void testToIterableTranslationWithIsmSideInput() throws Exception { - // A "change detector" test that makes sure the translation - // of getting a PCollectionView> does not change - // in bad ways during refactor - - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - - DataflowPipeline pipeline = DataflowPipeline.create(options); - pipeline.apply(Create.of(1, 2, 3)) - .apply(View.asIterable()); - Job job = translator.translate( - pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - - List steps = job.getSteps(); - assertEquals(3, steps.size()); - - @SuppressWarnings("unchecked") - List> toIsmRecordOutputs = - (List>) steps.get(1).getProperties().get(PropertyNames.OUTPUT_INFO); - assertTrue( - Structs.getBoolean(Iterables.getOnlyElement(toIsmRecordOutputs), "use_indexed_format")); - - - Step collectionToSingletonStep = steps.get(2); - assertEquals("CollectionToSingleton", collectionToSingletonStep.getKind()); - } - - @Test - public void testStepDisplayData() throws Exception { - DataflowPipelineOptions options = buildPipelineOptions(); - DataflowPipelineTranslator translator = DataflowPipelineTranslator.fromOptions(options); - DataflowPipeline pipeline = DataflowPipeline.create(options); - - DoFn fn1 = new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("foo", "bar")) - .add(DisplayData.item("foo2", DataflowPipelineTranslatorTest.class) - .withLabel("Test Class") - .withLinkUrl("http://www.google.com")); - } - }; - - DoFn fn2 = new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo3", 1234)); - } - }; - - ParDo.Bound parDo1 = ParDo.of(fn1); - ParDo.Bound parDo2 = ParDo.of(fn2); - pipeline - .apply(Create.of(1, 2, 3)) - .apply(parDo1) - .apply(parDo2); - - Job job = translator.translate( - pipeline, pipeline.getRunner(), Collections.emptyList()).getJob(); - - List steps = job.getSteps(); - assertEquals(3, steps.size()); - - Map parDo1Properties = steps.get(1).getProperties(); - Map parDo2Properties = steps.get(2).getProperties(); - assertThat(parDo1Properties, hasKey("display_data")); - - @SuppressWarnings("unchecked") - Collection> fn1displayData = - (Collection>) parDo1Properties.get("display_data"); - @SuppressWarnings("unchecked") - Collection> fn2displayData = - (Collection>) parDo2Properties.get("display_data"); - - ImmutableSet> expectedFn1DisplayData = ImmutableSet.of( - ImmutableMap.builder() - .put("key", "foo") - .put("type", "STRING") - .put("value", "bar") - .put("namespace", fn1.getClass().getName()) - .build(), - ImmutableMap.builder() - .put("key", "fn") - .put("label", "Transform Function") - .put("type", "JAVA_CLASS") - .put("value", fn1.getClass().getName()) - .put("shortValue", fn1.getClass().getSimpleName()) - .put("namespace", parDo1.getClass().getName()) - .build(), - ImmutableMap.builder() - .put("key", "foo2") - .put("type", "JAVA_CLASS") - .put("value", DataflowPipelineTranslatorTest.class.getName()) - .put("shortValue", DataflowPipelineTranslatorTest.class.getSimpleName()) - .put("namespace", fn1.getClass().getName()) - .put("label", "Test Class") - .put("linkUrl", "http://www.google.com") - .build() - ); - - ImmutableSet> expectedFn2DisplayData = ImmutableSet.of( - ImmutableMap.builder() - .put("key", "fn") - .put("label", "Transform Function") - .put("type", "JAVA_CLASS") - .put("value", fn2.getClass().getName()) - .put("shortValue", fn2.getClass().getSimpleName()) - .put("namespace", parDo2.getClass().getName()) - .build(), - ImmutableMap.builder() - .put("key", "foo3") - .put("type", "INTEGER") - .put("value", 1234L) - .put("namespace", fn2.getClass().getName()) - .build() - ); - - assertEquals(expectedFn1DisplayData, ImmutableSet.copyOf(fn1displayData)); - assertEquals(expectedFn2DisplayData, ImmutableSet.copyOf(fn2displayData)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrarTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrarTest.java deleted file mode 100644 index e7b24f0b30..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRegistrarTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ServiceLoader; - -/** Tests for {@link DirectPipelineRegistrar}. */ -@RunWith(JUnit4.class) -public class DirectPipelineRegistrarTest { - @Test - public void testCorrectOptionsAreReturned() { - assertEquals(ImmutableList.of(DirectPipelineOptions.class), - new DirectPipelineRegistrar.Options().getPipelineOptions()); - } - - @Test - public void testCorrectRunnersAreReturned() { - assertEquals(ImmutableList.of(DirectPipelineRunner.class), - new DirectPipelineRegistrar.Runner().getPipelineRunners()); - } - - @Test - public void testServiceLoaderForOptions() { - for (PipelineOptionsRegistrar registrar : - Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class).iterator())) { - if (registrar instanceof DirectPipelineRegistrar.Options) { - return; - } - } - fail("Expected to find " + DirectPipelineRegistrar.Options.class); - } - - @Test - public void testServiceLoaderForRunner() { - for (PipelineRunnerRegistrar registrar : - Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class).iterator())) { - if (registrar instanceof DirectPipelineRegistrar.Runner) { - return; - } - } - fail("Expected to find " + DirectPipelineRegistrar.Runner.class); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java deleted file mode 100644 index 8d09844d6d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunnerTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.io.AvroIO; -import com.google.cloud.dataflow.sdk.io.ShardNameTemplate; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.common.collect.Iterables; -import com.google.common.io.Files; - -import org.apache.avro.file.DataFileReader; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** Tests for {@link DirectPipelineRunner}. */ -@RunWith(JUnit4.class) -public class DirectPipelineRunnerTest implements Serializable { - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testToString() { - PipelineOptions options = PipelineOptionsFactory.create(); - DirectPipelineRunner runner = DirectPipelineRunner.fromOptions(options); - assertEquals("DirectPipelineRunner#" + runner.hashCode(), - runner.toString()); - } - - /** A {@link Coder} that fails during decoding. */ - private static class CrashingCoder extends AtomicCoder { - @Override - public void encode(T value, OutputStream stream, Context context) throws CoderException { - throw new CoderException("Called CrashingCoder.encode"); - } - - @Override - public T decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException { - throw new CoderException("Called CrashingCoder.decode"); - } - } - - /** A {@link DoFn} that outputs {@code 'hello'}. */ - private static class HelloDoFn extends DoFn { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - c.output("hello"); - } - } - - @Test - public void testCoderException() { - DirectPipeline pipeline = DirectPipeline.createForTest(); - - pipeline - .apply("CreateTestData", Create.of(42)) - .apply("CrashDuringCoding", ParDo.of(new HelloDoFn())) - .setCoder(new CrashingCoder()); - - expectedException.expect(RuntimeException.class); - expectedException.expectCause(isA(CoderException.class)); - pipeline.run(); - } - - @Test - public void testDirectPipelineOptions() { - DirectPipelineOptions options = PipelineOptionsFactory.create().as(DirectPipelineOptions.class); - assertNull(options.getDirectPipelineRunnerRandomSeed()); - } - - @Test - public void testTextIOWriteWithDefaultShardingStrategy() throws Exception { - String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "output"); - Pipeline p = DirectPipeline.createForTest(); - String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; - p.apply(Create.of(expectedElements)) - .apply(TextIO.Write.to(prefix).withSuffix("txt")); - p.run(); - - String filename = - IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".txt", 0, 1); - List fileContents = - Files.readLines(new File(filename), StandardCharsets.UTF_8); - // Ensure that each file got at least one record - assertFalse(fileContents.isEmpty()); - - assertThat(fileContents, containsInAnyOrder(expectedElements)); - } - - @Test - public void testTextIOWriteWithLimitedNumberOfShards() throws Exception { - final int numShards = 3; - String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "shardedOutput"); - Pipeline p = DirectPipeline.createForTest(); - String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; - p.apply(Create.of(expectedElements)) - .apply(TextIO.Write.to(prefix).withNumShards(numShards).withSuffix("txt")); - p.run(); - - List allContents = new ArrayList<>(); - for (int i = 0; i < numShards; ++i) { - String shardFileName = - IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".txt", i, 3); - List shardFileContents = - Files.readLines(new File(shardFileName), StandardCharsets.UTF_8); - - // Ensure that each file got at least one record - assertFalse(shardFileContents.isEmpty()); - - allContents.addAll(shardFileContents); - } - - assertThat(allContents, containsInAnyOrder(expectedElements)); - } - - @Test - @SuppressWarnings("deprecation") // test uses internal AvroCoder features. - public void testAvroIOWriteWithDefaultShardingStrategy() throws Exception { - String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "output"); - Pipeline p = DirectPipeline.createForTest(); - String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; - p.apply(Create.of(expectedElements)) - .apply(AvroIO.Write.withSchema(String.class).to(prefix).withSuffix(".avro")); - p.run(); - - String filename = - IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".avro", 0, 1); - List fileContents = new ArrayList<>(); - Iterables.addAll(fileContents, DataFileReader.openReader( - new File(filename), AvroCoder.of(String.class).createDatumReader())); - - // Ensure that each file got at least one record - assertFalse(fileContents.isEmpty()); - - assertThat(fileContents, containsInAnyOrder(expectedElements)); - } - - @Test - @SuppressWarnings("deprecation") // test uses internal AvroCoder features. - public void testAvroIOWriteWithLimitedNumberOfShards() throws Exception { - final int numShards = 3; - String prefix = IOChannelUtils.resolve(Files.createTempDir().toString(), "shardedOutput"); - Pipeline p = DirectPipeline.createForTest(); - String[] expectedElements = new String[]{ "a", "b", "c", "d", "e", "f", "g", "h", "i" }; - p.apply(Create.of(expectedElements)) - .apply(AvroIO.Write.withSchema(String.class).to(prefix) - .withNumShards(numShards).withSuffix(".avro")); - p.run(); - - List allContents = new ArrayList<>(); - for (int i = 0; i < numShards; ++i) { - String shardFileName = - IOChannelUtils.constructName(prefix, ShardNameTemplate.INDEX_OF_MAX, ".avro", i, 3); - List shardFileContents = new ArrayList<>(); - Iterables.addAll(shardFileContents, DataFileReader.openReader( - new File(shardFileName), AvroCoder.of(String.class).createDatumReader())); - - // Ensure that each file got at least one record - assertFalse(shardFileContents.isEmpty()); - - allContents.addAll(shardFileContents); - } - - assertThat(allContents, containsInAnyOrder(expectedElements)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineTest.java deleted file mode 100644 index ed4542fa13..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link DirectPipeline}. */ -@RunWith(JUnit4.class) -public class DirectPipelineTest { - @Test - public void testToString() { - DirectPipeline pipeline = DirectPipeline.createForTest(); - assertEquals("DirectPipeline#" + pipeline.hashCode(), - pipeline.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerTest.java deleted file mode 100644 index 4b1f786dc6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/PipelineRunnerTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.junit.Assert.assertTrue; - -import com.google.api.services.dataflow.Dataflow; -import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.TestCredential; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Tests for DataflowPipelineRunner. - */ -@RunWith(JUnit4.class) -public class PipelineRunnerTest { - - @Mock private Dataflow mockDataflow; - @Mock private GcsUtil mockGcsUtil; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testLongName() { - // Check we can create a pipeline runner using the full class name. - DirectPipelineOptions options = PipelineOptionsFactory.as(DirectPipelineOptions.class); - options.setAppName("test"); - options.setProject("test"); - options.setGcsUtil(mockGcsUtil); - options.setRunner(DirectPipelineRunner.class); - options.setGcpCredential(new TestCredential()); - PipelineRunner runner = PipelineRunner.fromOptions(options); - assertTrue(runner instanceof DirectPipelineRunner); - } - - @Test - public void testShortName() { - // Check we can create a pipeline runner using the short class name. - DirectPipelineOptions options = PipelineOptionsFactory.as(DirectPipelineOptions.class); - options.setAppName("test"); - options.setProject("test"); - options.setGcsUtil(mockGcsUtil); - options.setRunner(DirectPipelineRunner.class); - options.setGcpCredential(new TestCredential()); - PipelineRunner runner = PipelineRunner.fromOptions(options); - assertTrue(runner instanceof DirectPipelineRunner); - } - - @Test - public void testAppNameDefault() { - ApplicationNameOptions options = PipelineOptionsFactory.as(ApplicationNameOptions.class); - Assert.assertEquals(PipelineRunnerTest.class.getSimpleName(), - options.getAppName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java deleted file mode 100644 index bc9c00946e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TemplatingDataflowPipelineRunnerTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.TestDataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.TestCredential; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.File; - -/** - * Tests for TemplatingDataflowPipelineRunner. - */ -@RunWith(JUnit4.class) -public class TemplatingDataflowPipelineRunnerTest { - - @Mock private DataflowPipelineJob mockJob; - @Mock private DataflowPipelineRunner mockRunner; - - @Rule - public ExpectedLogs expectedLogs = ExpectedLogs.none(TemplatingDataflowPipelineRunner.class); - - @Rule - public ExpectedException expectedThrown = ExpectedException.none(); - - @Rule - public final TemporaryFolder tmpDir = new TemporaryFolder(); - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(mockJob.getProjectId()).thenReturn("project"); - when(mockJob.getJobId()).thenReturn("job"); - when(mockRunner.run(isA(Pipeline.class))).thenReturn(mockJob); - } - - /** - * Tests that the {@link TemplatingDataflowPipelineRunner} returns normally when the runner is - * successfully run. - */ - @Test - public void testLoggedCompletion() throws Exception { - File existingFile = tmpDir.newFile(); - TestDataflowPipelineOptions options = - PipelineOptionsFactory.as(TestDataflowPipelineOptions.class); - options.setProject(mockJob.getProjectId()); - options.setDataflowJobFile(existingFile.getPath()); - TemplatingDataflowPipelineRunner runner = - new TemplatingDataflowPipelineRunner(mockRunner, options); - runner.run(DirectPipeline.createForTest()); - expectedLogs.verifyInfo("Template successfully created"); - } - - - /** - * Tests that the {@link TemplatingDataflowPipelineRunner} returns normally when the runner is - * successfully run. - */ - @Test - public void testFullCompletion() throws Exception { - File existingFile = tmpDir.newFile(); - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setJobName("TestJobName"); - options.setGcpCredential(new TestCredential()); - options.setPathValidatorClass(NoopPathValidator.class); - options.setProject("test-project"); - options.setDataflowJobFile(existingFile.getPath()); - options.setTempLocation(tmpDir.getRoot().getPath()); - TemplatingDataflowPipelineRunner runner = - TemplatingDataflowPipelineRunner.fromOptions(options); - runner.run(DirectPipeline.createForTest()); - } - - /** - * Tests that the {@link TemplatingDataflowPipelineRunner} throws the appropriate exception when - * an output file is not writable. - */ - @Test - public void testLoggedErrorForFile() throws Exception { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setJobName("TestJobName"); - options.setDataflowJobFile("//bad/path"); - options.setProject("test-project"); - options.setTempLocation(tmpDir.getRoot().getPath()); - options.setGcpCredential(new TestCredential()); - options.setPathValidatorClass(NoopPathValidator.class); - TemplatingDataflowPipelineRunner runner = - TemplatingDataflowPipelineRunner.fromOptions(options); - - expectedThrown.expectMessage("Cannot create output file at"); - expectedThrown.expect(RuntimeException.class); - runner.run(DirectPipeline.createForTest()); - } - - @Test - public void testToString() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setJobName("TestJobName"); - options.setDataflowJobFile("foo"); - options.setProject("test-project"); - options.setTempLocation("gs://test/temp/location"); - options.setGcpCredential(new TestCredential()); - options.setPathValidatorClass(NoopPathValidator.class); - assertEquals("TemplatingDataflowPipelineRunner", - TemplatingDataflowPipelineRunner.fromOptions(options).toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java deleted file mode 100644 index 68e1db1a52..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/TransformTreeTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.Write; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.Sample; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PValue; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.util.Arrays; -import java.util.EnumSet; - -/** - * Tests for {@link TransformTreeNode} and {@link TransformHierarchy}. - */ -@RunWith(JUnit4.class) -public class TransformTreeTest { - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - - enum TransformsSeen { - READ, - WRITE, - SAMPLE_ANY - } - - /** - * INVALID TRANSFORM, DO NOT COPY. - * - *

              This is an invalid composite transform that returns unbound outputs. - * This should never happen, and is here to test that it is properly rejected. - */ - private static class InvalidCompositeTransform - extends PTransform> { - - @Override - public PCollectionList apply(PBegin b) { - // Composite transform: apply delegates to other transformations, - // here a Create transform. - PCollection result = b.apply(Create.of("hello", "world")); - - // Issue below: PCollection.createPrimitiveOutput should not be used - // from within a composite transform. - return PCollectionList.of( - Arrays.asList(result, PCollection.createPrimitiveOutputInternal( - b.getPipeline(), - WindowingStrategy.globalDefault(), - result.isBounded()))); - } - } - - /** - * A composite transform that returns an output that is unbound. - */ - private static class UnboundOutputCreator - extends PTransform, PDone> { - - @Override - public PDone apply(PCollection input) { - // Apply an operation so that this is a composite transform. - input.apply(Count.perElement()); - - return PDone.in(input.getPipeline()); - } - - @Override - protected Coder getDefaultOutputCoder() { - return VoidCoder.of(); - } - } - - // Builds a pipeline containing a composite operation (Pick), then - // visits the nodes and verifies that the hierarchy was captured. - @Test - public void testCompositeCapture() throws Exception { - File inputFile = tmpFolder.newFile(); - File outputFile = tmpFolder.newFile(); - - Pipeline p = DirectPipeline.createForTest(); - - p.apply(TextIO.Read.named("ReadMyFile").from(inputFile.getPath())) - .apply(Sample.any(10)) - .apply(TextIO.Write.named("WriteMyFile").to(outputFile.getPath())); - - final EnumSet visited = - EnumSet.noneOf(TransformsSeen.class); - final EnumSet left = - EnumSet.noneOf(TransformsSeen.class); - - p.traverseTopologically(new Pipeline.PipelineVisitor() { - @Override - public void enterCompositeTransform(TransformTreeNode node) { - PTransform transform = node.getTransform(); - if (transform instanceof Sample.SampleAny) { - assertTrue(visited.add(TransformsSeen.SAMPLE_ANY)); - assertNotNull(node.getEnclosingNode()); - assertTrue(node.isCompositeNode()); - } else if (transform instanceof Write.Bound) { - assertTrue(visited.add(TransformsSeen.WRITE)); - assertNotNull(node.getEnclosingNode()); - assertTrue(node.isCompositeNode()); - } - assertThat(transform, not(instanceOf(Read.Bounded.class))); - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - PTransform transform = node.getTransform(); - if (transform instanceof Sample.SampleAny) { - assertTrue(left.add(TransformsSeen.SAMPLE_ANY)); - } - } - - @Override - public void visitTransform(TransformTreeNode node) { - PTransform transform = node.getTransform(); - // Pick is a composite, should not be visited here. - assertThat(transform, not(instanceOf(Sample.SampleAny.class))); - assertThat(transform, not(instanceOf(Write.Bound.class))); - if (transform instanceof Read.Bounded) { - assertTrue(visited.add(TransformsSeen.READ)); - } - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - } - }); - - assertTrue(visited.equals(EnumSet.allOf(TransformsSeen.class))); - assertTrue(left.equals(EnumSet.of(TransformsSeen.SAMPLE_ANY))); - } - - @Test(expected = IllegalStateException.class) - public void testOutputChecking() throws Exception { - Pipeline p = DirectPipeline.createForTest(); - - p.apply(new InvalidCompositeTransform()); - - p.traverseTopologically(new RecordingPipelineVisitor()); - fail("traversal should have failed with an IllegalStateException"); - } - - @Test - public void testMultiGraphSetup() { - Pipeline p = DirectPipeline.createForTest(); - - PCollection input = p.begin() - .apply(Create.of(1, 2, 3)); - - input.apply(new UnboundOutputCreator()); - - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java deleted file mode 100644 index c144ca8ab9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/DataflowUnboundedReadFromBoundedSourceTest.java +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.CountingSource; -import com.google.cloud.dataflow.sdk.io.FileBasedSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource.BoundedToUnboundedSourceAdapter; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource.BoundedToUnboundedSourceAdapter.Checkpoint; -import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowUnboundedReadFromBoundedSource.BoundedToUnboundedSourceAdapter.CheckpointCoder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Random; - -/** - * Unit tests for {@link DataflowUnboundedReadFromBoundedSource}. - */ -@RunWith(JUnit4.class) -public class DataflowUnboundedReadFromBoundedSourceTest { - - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testCheckpointCoderNulls() throws Exception { - CheckpointCoder coder = new CheckpointCoder<>(StringUtf8Coder.of()); - Checkpoint emptyCheckpoint = new Checkpoint<>(null, null); - Checkpoint decodedEmptyCheckpoint = CoderUtils.decodeFromByteArray( - coder, - CoderUtils.encodeToByteArray(coder, emptyCheckpoint)); - assertNull(decodedEmptyCheckpoint.getResidualElements()); - assertNull(decodedEmptyCheckpoint.getResidualSource()); - } - - @Test - @Category(RunnableOnService.class) - public void testBoundedToUnboundedSourceAdapter() throws Exception { - long numElements = 100; - BoundedSource boundedSource = CountingSource.upTo(numElements); - UnboundedSource> unboundedSource = - new BoundedToUnboundedSourceAdapter<>(boundedSource); - - Pipeline p = TestPipeline.create(); - - PCollection output = - p.apply(Read.from(unboundedSource).withMaxNumRecords(numElements)); - - // Count == numElements - DataflowAssert - .thatSingleton(output.apply("Count", Count.globally())) - .isEqualTo(numElements); - // Unique count == numElements - DataflowAssert - .thatSingleton(output.apply(RemoveDuplicates.create()) - .apply("UniqueCount", Count.globally())) - .isEqualTo(numElements); - // Min == 0 - DataflowAssert - .thatSingleton(output.apply("Min", Min.globally())) - .isEqualTo(0L); - // Max == numElements-1 - DataflowAssert - .thatSingleton(output.apply("Max", Max.globally())) - .isEqualTo(numElements - 1); - p.run(); - } - - @Test - public void testCountingSourceToUnboundedCheckpoint() throws Exception { - long numElements = 100; - BoundedSource countingSource = CountingSource.upTo(numElements); - List expected = Lists.newArrayList(); - for (long i = 0; i < numElements; ++i) { - expected.add(i); - } - testBoundedToUnboundedSourceAdapterCheckpoint(countingSource, expected); - } - - @Test - public void testUnsplittableSourceToUnboundedCheckpoint() throws Exception { - String baseName = "test-input"; - File compressedFile = tmpFolder.newFile(baseName + ".gz"); - byte[] input = generateInput(100); - writeFile(compressedFile, input); - - BoundedSource source = new UnsplittableSource(compressedFile.getPath(), 1); - List expected = Lists.newArrayList(); - for (byte i : input) { - expected.add(i); - } - testBoundedToUnboundedSourceAdapterCheckpoint(source, expected); - } - - private void testBoundedToUnboundedSourceAdapterCheckpoint( - BoundedSource boundedSource, - List expectedElements) throws Exception { - BoundedToUnboundedSourceAdapter unboundedSource = - new BoundedToUnboundedSourceAdapter<>(boundedSource); - - PipelineOptions options = PipelineOptionsFactory.create(); - BoundedToUnboundedSourceAdapter.Reader reader = - unboundedSource.createReader(options, null); - - List actual = Lists.newArrayList(); - for (boolean hasNext = reader.start(); hasNext; hasNext = reader.advance()) { - actual.add(reader.getCurrent()); - // checkpoint every 9 elements - if (actual.size() % 9 == 0) { - Checkpoint checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - } - } - Checkpoint checkpointDone = reader.getCheckpointMark(); - assertTrue(checkpointDone.getResidualElements() == null - || checkpointDone.getResidualElements().isEmpty()); - - assertEquals(expectedElements.size(), actual.size()); - assertEquals(Sets.newHashSet(expectedElements), Sets.newHashSet(actual)); - } - - @Test - public void testCountingSourceToUnboundedCheckpointRestart() throws Exception { - long numElements = 100; - BoundedSource countingSource = CountingSource.upTo(numElements); - List expected = Lists.newArrayList(); - for (long i = 0; i < numElements; ++i) { - expected.add(i); - } - testBoundedToUnboundedSourceAdapterCheckpointRestart(countingSource, expected); - } - - @Test - public void testUnsplittableSourceToUnboundedCheckpointRestart() throws Exception { - String baseName = "test-input"; - File compressedFile = tmpFolder.newFile(baseName + ".gz"); - byte[] input = generateInput(1000); - writeFile(compressedFile, input); - - BoundedSource source = new UnsplittableSource(compressedFile.getPath(), 1); - List expected = Lists.newArrayList(); - for (byte i : input) { - expected.add(i); - } - testBoundedToUnboundedSourceAdapterCheckpointRestart(source, expected); - } - - private void testBoundedToUnboundedSourceAdapterCheckpointRestart( - BoundedSource boundedSource, - List expectedElements) throws Exception { - BoundedToUnboundedSourceAdapter unboundedSource = - new BoundedToUnboundedSourceAdapter<>(boundedSource); - - PipelineOptions options = PipelineOptionsFactory.create(); - BoundedToUnboundedSourceAdapter.Reader reader = - unboundedSource.createReader(options, null); - - List actual = Lists.newArrayList(); - for (boolean hasNext = reader.start(); hasNext;) { - actual.add(reader.getCurrent()); - // checkpoint every 9 elements - if (actual.size() % 9 == 0) { - Checkpoint checkpoint = reader.getCheckpointMark(); - Coder> checkpointCoder = unboundedSource.getCheckpointMarkCoder(); - Checkpoint decodedCheckpoint = CoderUtils.decodeFromByteArray( - checkpointCoder, - CoderUtils.encodeToByteArray(checkpointCoder, checkpoint)); - reader.close(); - checkpoint.finalizeCheckpoint(); - - BoundedToUnboundedSourceAdapter.Reader restarted = - unboundedSource.createReader(options, decodedCheckpoint); - reader = restarted; - hasNext = reader.start(); - } else { - hasNext = reader.advance(); - } - } - Checkpoint checkpointDone = reader.getCheckpointMark(); - assertTrue(checkpointDone.getResidualElements() == null - || checkpointDone.getResidualElements().isEmpty()); - - assertEquals(expectedElements.size(), actual.size()); - assertEquals(Sets.newHashSet(expectedElements), Sets.newHashSet(actual)); - } - - @Test - public void testReadBeforeStart() throws Exception { - thrown.expect(NoSuchElementException.class); - - BoundedSource countingSource = CountingSource.upTo(100); - BoundedToUnboundedSourceAdapter unboundedSource = - new BoundedToUnboundedSourceAdapter<>(countingSource); - PipelineOptions options = PipelineOptionsFactory.create(); - - unboundedSource.createReader(options, null).getCurrent(); - } - - @Test - public void testReadFromCheckpointBeforeStart() throws Exception { - thrown.expect(NoSuchElementException.class); - - BoundedSource countingSource = CountingSource.upTo(100); - BoundedToUnboundedSourceAdapter unboundedSource = - new BoundedToUnboundedSourceAdapter<>(countingSource); - PipelineOptions options = PipelineOptionsFactory.create(); - - List> elements = - ImmutableList.of(TimestampedValue.of(1L, new Instant(1L))); - Checkpoint checkpoint = new Checkpoint<>(elements, countingSource); - unboundedSource.createReader(options, checkpoint).getCurrent(); - } - - @Test - public void testKind() { - DataflowUnboundedReadFromBoundedSource read = new - DataflowUnboundedReadFromBoundedSource<>(new NoopNamedSource()); - - assertEquals("Read(NoopNamedSource)", read.getKindString()); - } - - @Test - public void testKindAnonymousSource() { - NoopNamedSource anonSource = new NoopNamedSource() {}; - DataflowUnboundedReadFromBoundedSource read = new - DataflowUnboundedReadFromBoundedSource<>(anonSource); - - assertEquals("Read(AnonymousSource)", read.getKindString()); - } - - /** Source implementation only useful for its identity. */ - static class NoopNamedSource extends BoundedSource { - @Override - public List> splitIntoBundles(long desiredBundleSizeBytes, - PipelineOptions options) throws Exception { - return null; - } - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return 0; - } - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - @Override - public BoundedReader createReader( - PipelineOptions options) throws IOException { - return null; - } - @Override - public void validate() { - - } - @Override - public Coder getDefaultOutputCoder() { - return null; - } - } - - /** - * Generate byte array of given size. - */ - private static byte[] generateInput(int size) { - // Arbitrary but fixed seed - Random random = new Random(285930); - byte[] buff = new byte[size]; - random.nextBytes(buff); - return buff; - } - - /** - * Writes a single output file. - */ - private static void writeFile(File file, byte[] input) throws IOException { - try (OutputStream os = new FileOutputStream(file)) { - os.write(input); - } - } - - /** - * Unsplittable source for use in tests. - */ - private static class UnsplittableSource extends FileBasedSource { - public UnsplittableSource(String fileOrPatternSpec, long minBundleSize) { - super(fileOrPatternSpec, minBundleSize); - } - - public UnsplittableSource( - String fileName, long minBundleSize, long startOffset, long endOffset) { - super(fileName, minBundleSize, startOffset, endOffset); - } - - @Override - protected FileBasedSource createForSubrangeOfFile(String fileName, long start, long end) { - return new UnsplittableSource(fileName, getMinBundleSize(), start, end); - } - - @Override - protected FileBasedReader createSingleFileReader(PipelineOptions options) { - return new UnsplittableReader(this); - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public boolean allowsDynamicSplitting() { - return false; - } - - @Override - public Coder getDefaultOutputCoder() { - return SerializableCoder.of(Byte.class); - } - - private static class UnsplittableReader extends FileBasedReader { - ByteBuffer buff = ByteBuffer.allocate(1); - Byte current; - long offset; - ReadableByteChannel channel; - - public UnsplittableReader(UnsplittableSource source) { - super(source); - offset = source.getStartOffset() - 1; - } - - @Override - public Byte getCurrent() throws NoSuchElementException { - return current; - } - - @Override - protected boolean isAtSplitPoint() { - return true; - } - - @Override - protected void startReading(ReadableByteChannel channel) throws IOException { - this.channel = channel; - } - - @Override - protected boolean readNextRecord() throws IOException { - buff.clear(); - if (channel.read(buff) != 1) { - return false; - } - current = new Byte(buff.get(0)); - offset += 1; - return true; - } - - @Override - protected long getCurrentOffset() { - return offset; - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java deleted file mode 100644 index 16752a9641..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSource.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.encodeToByteArray; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.DelegateCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -import javax.annotation.Nullable; - -/** - * An unbounded source for testing the unbounded sources framework code. - * - *

              Each split of this sources produces records of the form KV(split_id, i), - * where i counts up from 0. Each record has a timestamp of i, and the watermark - * accurately tracks these timestamps. The reader will occasionally return false - * from {@code advance}, in order to simulate a source where not all the data is - * available immediately. - */ -public class TestCountingSource - extends UnboundedSource, TestCountingSource.CounterMark> { - private static final Logger LOG = LoggerFactory.getLogger(TestCountingSource.class); - - private static List finalizeTracker; - private final int numMessagesPerShard; - private final int shardNumber; - private final boolean dedup; - private final boolean throwOnFirstSnapshot; - private final boolean allowSplitting; - - /** - * We only allow an exception to be thrown from getCheckpointMark - * at most once. This must be static since the entire TestCountingSource - * instance may re-serialized when the pipeline recovers and retries. - */ - private static boolean thrown = false; - - public static void setFinalizeTracker(List finalizeTracker) { - TestCountingSource.finalizeTracker = finalizeTracker; - } - - public TestCountingSource(int numMessagesPerShard) { - this(numMessagesPerShard, 0, false, false, true); - } - - public TestCountingSource withDedup() { - return new TestCountingSource( - numMessagesPerShard, shardNumber, true, throwOnFirstSnapshot, true); - } - - private TestCountingSource withShardNumber(int shardNumber) { - return new TestCountingSource( - numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot, true); - } - - public TestCountingSource withThrowOnFirstSnapshot(boolean throwOnFirstSnapshot) { - return new TestCountingSource( - numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot, true); - } - - public TestCountingSource withoutSplitting() { - return new TestCountingSource( - numMessagesPerShard, shardNumber, dedup, throwOnFirstSnapshot, false); - } - - private TestCountingSource(int numMessagesPerShard, int shardNumber, boolean dedup, - boolean throwOnFirstSnapshot, boolean allowSplitting) { - this.numMessagesPerShard = numMessagesPerShard; - this.shardNumber = shardNumber; - this.dedup = dedup; - this.throwOnFirstSnapshot = throwOnFirstSnapshot; - this.allowSplitting = allowSplitting; - } - - public int getShardNumber() { - return shardNumber; - } - - @Override - public List generateInitialSplits( - int desiredNumSplits, PipelineOptions options) { - List splits = new ArrayList<>(); - int numSplits = allowSplitting ? desiredNumSplits : 1; - for (int i = 0; i < numSplits; i++) { - splits.add(withShardNumber(i)); - } - return splits; - } - - class CounterMark implements UnboundedSource.CheckpointMark { - int current; - - public CounterMark(int current) { - this.current = current; - } - - @Override - public void finalizeCheckpoint() { - if (finalizeTracker != null) { - finalizeTracker.add(current); - } - } - } - - @Override - public Coder getCheckpointMarkCoder() { - return DelegateCoder.of( - VarIntCoder.of(), - new DelegateCoder.CodingFunction() { - @Override - public Integer apply(CounterMark input) { - return input.current; - } - }, - new DelegateCoder.CodingFunction() { - @Override - public CounterMark apply(Integer input) { - return new CounterMark(input); - } - }); - } - - @Override - public boolean requiresDeduping() { - return dedup; - } - - /** - * Public only so that the checkpoint can be conveyed from {@link #getCheckpointMark()} to - * {@link TestCountingSource#createReader(PipelineOptions, CounterMark)} without cast. - */ - public class CountingSourceReader extends UnboundedReader> { - private int current; - - public CountingSourceReader(int startingPoint) { - this.current = startingPoint; - } - - @Override - public boolean start() { - return advance(); - } - - @Override - public boolean advance() { - if (current >= numMessagesPerShard - 1) { - return false; - } - // If testing dedup, occasionally insert a duplicate value; - if (current >= 0 && dedup && ThreadLocalRandom.current().nextInt(5) == 0) { - return true; - } - current++; - return true; - } - - @Override - public KV getCurrent() { - return KV.of(shardNumber, current); - } - - @Override - public Instant getCurrentTimestamp() { - return new Instant(current); - } - - @Override - public byte[] getCurrentRecordId() { - try { - return encodeToByteArray(KvCoder.of(VarIntCoder.of(), VarIntCoder.of()), getCurrent()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void close() {} - - @Override - public TestCountingSource getCurrentSource() { - return TestCountingSource.this; - } - - @Override - public Instant getWatermark() { - // The watermark is a promise about future elements, and the timestamps of elements are - // strictly increasing for this source. - return new Instant(current + 1); - } - - @Override - public CounterMark getCheckpointMark() { - if (throwOnFirstSnapshot && !thrown) { - thrown = true; - LOG.error("Throwing exception while checkpointing counter"); - throw new RuntimeException("failed during checkpoint"); - } - // The checkpoint can assume all records read, including the current, have - // been commited. - return new CounterMark(current); - } - - @Override - public long getSplitBacklogBytes() { - return 7L; - } - } - - @Override - public CountingSourceReader createReader( - PipelineOptions options, @Nullable CounterMark checkpointMark) { - if (checkpointMark == null) { - LOG.debug("creating reader"); - } else { - LOG.debug("restoring reader from checkpoint with current = {}", checkpointMark.current); - } - return new CountingSourceReader(checkpointMark != null ? checkpointMark.current : -1); - } - - @Override - public void validate() {} - - @Override - public Coder> getDefaultOutputCoder() { - return KvCoder.of(VarIntCoder.of(), VarIntCoder.of()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java deleted file mode 100644 index b03398f479..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/dataflow/TestCountingSourceTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.dataflow; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; - -/** - * Test the TestCountingSource. - */ -@RunWith(JUnit4.class) -public class TestCountingSourceTest { - @Test - public void testRespectsCheckpointContract() throws IOException { - TestCountingSource source = new TestCountingSource(3); - PipelineOptions options = PipelineOptionsFactory.create(); - TestCountingSource.CountingSourceReader reader = - source.createReader(options, null /* no checkpoint */); - assertTrue(reader.start()); - assertEquals(0L, (long) reader.getCurrent().getValue()); - assertTrue(reader.advance()); - assertEquals(1L, (long) reader.getCurrent().getValue()); - TestCountingSource.CounterMark checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - reader = source.createReader(options, checkpoint); - assertTrue(reader.start()); - assertEquals(2L, (long) reader.getCurrent().getValue()); - assertFalse(reader.advance()); - } - - @Test - public void testCanResumeWithExpandedCount() throws IOException { - TestCountingSource source = new TestCountingSource(1); - PipelineOptions options = PipelineOptionsFactory.create(); - TestCountingSource.CountingSourceReader reader = - source.createReader(options, null /* no checkpoint */); - assertTrue(reader.start()); - assertEquals(0L, (long) reader.getCurrent().getValue()); - assertFalse(reader.advance()); - TestCountingSource.CounterMark checkpoint = reader.getCheckpointMark(); - checkpoint.finalizeCheckpoint(); - source = new TestCountingSource(2); - reader = source.createReader(options, checkpoint); - assertTrue(reader.start()); - assertEquals(1L, (long) reader.getCurrent().getValue()); - assertFalse(reader.advance()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java deleted file mode 100644 index b2fdc71bc8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/BoundedReadEvaluatorFactoryTest.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.CountingSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.Read.Bounded; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Tests for {@link BoundedReadEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class BoundedReadEvaluatorFactoryTest { - private BoundedSource source; - private PCollection longs; - private TransformEvaluatorFactory factory; - @Mock private InProcessEvaluationContext context; - private BundleFactory bundleFactory; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - source = CountingSource.upTo(10L); - TestPipeline p = TestPipeline.create(); - longs = p.apply(Read.from(source)); - - factory = new BoundedReadEvaluatorFactory(); - bundleFactory = InProcessBundleFactory.create(); - } - - @Test - public void boundedSourceInMemoryTransformEvaluatorProducesElements() throws Exception { - UncommittedBundle output = bundleFactory.createRootBundle(longs); - when(context.createRootBundle(longs)).thenReturn(output); - - TransformEvaluator evaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - InProcessTransformResult result = evaluator.finishBundle(); - assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - assertThat( - output.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(), - containsInAnyOrder( - gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); - } - - /** - * Demonstrate that acquiring multiple {@link TransformEvaluator TransformEvaluators} for the same - * {@link Bounded Read.Bounded} application with the same evaluation context only produces the - * elements once. - */ - @Test - public void boundedSourceInMemoryTransformEvaluatorAfterFinishIsEmpty() throws Exception { - UncommittedBundle output = bundleFactory.createRootBundle(longs); - when(context.createRootBundle(longs)).thenReturn(output); - - TransformEvaluator evaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - InProcessTransformResult result = evaluator.finishBundle(); - assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - Iterable> outputElements = - output.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(); - assertThat( - outputElements, - containsInAnyOrder( - gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); - - UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); - when(context.createRootBundle(longs)).thenReturn(secondOutput); - TransformEvaluator secondEvaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - assertThat(secondEvaluator, nullValue()); - } - - /** - * Demonstrates that acquiring multiple evaluators from the factory are independent, but - * the elements in the source are only produced once. - */ - @Test - public void boundedSourceEvaluatorSimultaneousEvaluations() throws Exception { - UncommittedBundle output = bundleFactory.createRootBundle(longs); - UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); - when(context.createRootBundle(longs)).thenReturn(output).thenReturn(secondOutput); - - // create both evaluators before finishing either. - TransformEvaluator evaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - TransformEvaluator secondEvaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - assertThat(secondEvaluator, nullValue()); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - Iterable> outputElements = - output.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(); - - assertThat( - outputElements, - containsInAnyOrder( - gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); - assertThat( - secondOutput.commit(BoundedWindow.TIMESTAMP_MAX_VALUE).getElements(), emptyIterable()); - assertThat( - outputElements, - containsInAnyOrder( - gw(1L), gw(2L), gw(4L), gw(8L), gw(9L), gw(7L), gw(6L), gw(5L), gw(3L), gw(0L))); - } - - @Test - public void boundedSourceEvaluatorClosesReader() throws Exception { - TestSource source = new TestSource<>(BigEndianLongCoder.of(), 1L, 2L, 3L); - - TestPipeline p = TestPipeline.create(); - PCollection pcollection = p.apply(Read.from(source)); - AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - - UncommittedBundle output = bundleFactory.createRootBundle(pcollection); - when(context.createRootBundle(pcollection)).thenReturn(output); - - TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); - evaluator.finishBundle(); - CommittedBundle committed = output.commit(Instant.now()); - assertThat(committed.getElements(), containsInAnyOrder(gw(2L), gw(3L), gw(1L))); - assertThat(TestSource.readerClosed, is(true)); - } - - @Test - public void boundedSourceEvaluatorNoElementsClosesReader() throws Exception { - TestSource source = new TestSource<>(BigEndianLongCoder.of()); - - TestPipeline p = TestPipeline.create(); - PCollection pcollection = p.apply(Read.from(source)); - AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - - UncommittedBundle output = bundleFactory.createRootBundle(pcollection); - when(context.createRootBundle(pcollection)).thenReturn(output); - - TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); - evaluator.finishBundle(); - CommittedBundle committed = output.commit(Instant.now()); - assertThat(committed.getElements(), emptyIterable()); - assertThat(TestSource.readerClosed, is(true)); - } - - private static class TestSource extends BoundedSource { - private static boolean readerClosed; - private final Coder coder; - private final T[] elems; - - public TestSource(Coder coder, T... elems) { - this.elems = elems; - this.coder = coder; - readerClosed = false; - } - - @Override - public List> splitIntoBundles( - long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - return ImmutableList.of(this); - } - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { - return 0; - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - @Override - public BoundedSource.BoundedReader createReader(PipelineOptions options) throws IOException { - return new TestReader<>(this, elems); - } - - @Override - public void validate() { - } - - @Override - public Coder getDefaultOutputCoder() { - return coder; - } - } - - private static class TestReader extends BoundedReader { - private final BoundedSource source; - private final List elems; - private int index; - - public TestReader(BoundedSource source, T... elems) { - this.source = source; - this.elems = Arrays.asList(elems); - this.index = -1; - } - - @Override - public BoundedSource getCurrentSource() { - return source; - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - if (elems.size() > index + 1) { - index++; - return true; - } - return false; - } - - @Override - public T getCurrent() throws NoSuchElementException { - return elems.get(index); - } - - @Override - public void close() throws IOException { - TestSource.readerClosed = true; - } - } - - private static WindowedValue gw(Long elem) { - return WindowedValue.valueInGlobalWindow(elem); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java deleted file mode 100644 index 2242c67c20..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/CommittedResultTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.collect.ImmutableList; -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.Serializable; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; - -/** - * Tests for {@link CommittedResult}. - */ -@RunWith(JUnit4.class) -public class CommittedResultTest implements Serializable { - private transient TestPipeline p = TestPipeline.create(); - private transient PCollection created = p.apply(Create.of(1, 2)); - private transient AppliedPTransform transform = - AppliedPTransform.of("foo", p.begin(), PDone.in(p), new PTransform() { - }); - private transient BundleFactory bundleFactory = InProcessBundleFactory.create(); - - @Test - public void getTransformExtractsFromResult() { - CommittedResult result = - CommittedResult.create( - StepTransformResult.withoutHold(transform).build(), - bundleFactory.createRootBundle(created).commit(Instant.now()), - Collections.>emptyList(), - EnumSet.noneOf(OutputType.class)); - - assertThat(result.getTransform(), Matchers.>equalTo(transform)); - } - - @Test - public void getUncommittedElementsEqualInput() { - InProcessPipelineRunner.CommittedBundle bundle = - bundleFactory.createRootBundle(created) - .add(WindowedValue.valueInGlobalWindow(2)) - .commit(Instant.now()); - CommittedResult result = - CommittedResult.create( - StepTransformResult.withoutHold(transform).build(), - bundle, - Collections.>emptyList(), - EnumSet.noneOf(OutputType.class)); - - assertThat(result.getUnprocessedInputs(), - Matchers.>equalTo(bundle)); - } - - @Test - public void getUncommittedElementsNull() { - CommittedResult result = - CommittedResult.create( - StepTransformResult.withoutHold(transform).build(), - null, - Collections.>emptyList(), - EnumSet.noneOf(OutputType.class)); - - assertThat(result.getUnprocessedInputs(), nullValue()); - } - - @Test - public void getOutputsEqualInput() { - List> outputs = - ImmutableList.of(bundleFactory.createRootBundle(PCollection.createPrimitiveOutputInternal(p, - WindowingStrategy.globalDefault(), - PCollection.IsBounded.BOUNDED)).commit(Instant.now()), - bundleFactory.createRootBundle(PCollection.createPrimitiveOutputInternal(p, - WindowingStrategy.globalDefault(), - PCollection.IsBounded.UNBOUNDED)).commit(Instant.now())); - CommittedResult result = - CommittedResult.create( - StepTransformResult.withoutHold(transform).build(), - bundleFactory.createRootBundle(created).commit(Instant.now()), - outputs, - EnumSet.of(OutputType.BUNDLE, OutputType.PCOLLECTION_VIEW)); - - assertThat(result.getOutputs(), Matchers.containsInAnyOrder(outputs.toArray())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java deleted file mode 100644 index 1d23c92ccf..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ConsumerTrackingPipelineVisitorTest.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.emptyIterable; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.io.CountingInput; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.PValue; - -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.List; - -/** - * Tests for {@link ConsumerTrackingPipelineVisitor}. - */ -@RunWith(JUnit4.class) -public class ConsumerTrackingPipelineVisitorTest implements Serializable { - @Rule public transient ExpectedException thrown = ExpectedException.none(); - - private transient TestPipeline p = TestPipeline.create(); - private transient ConsumerTrackingPipelineVisitor visitor = new ConsumerTrackingPipelineVisitor(); - - @Test - public void getViewsReturnsViews() { - PCollectionView> listView = - p.apply("listCreate", Create.of("foo", "bar")) - .apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) - throws Exception { - c.output(Integer.toString(c.element().length())); - } - })) - .apply(View.asList()); - PCollectionView singletonView = - p.apply("singletonCreate", Create.of(1, 2, 3)).apply(View.asSingleton()); - p.traverseTopologically(visitor); - assertThat( - visitor.getViews(), - Matchers.>containsInAnyOrder(listView, singletonView)); - } - - @Test - public void getRootTransformsContainsPBegins() { - PCollection created = p.apply(Create.of("foo", "bar")); - PCollection counted = p.apply(CountingInput.upTo(1234L)); - PCollection unCounted = p.apply(CountingInput.unbounded()); - p.traverseTopologically(visitor); - assertThat( - visitor.getRootTransforms(), - Matchers.>containsInAnyOrder( - created.getProducingTransformInternal(), - counted.getProducingTransformInternal(), - unCounted.getProducingTransformInternal())); - } - - @Test - public void getRootTransformsContainsEmptyFlatten() { - PCollection empty = - PCollectionList.empty(p).apply(Flatten.pCollections()); - p.traverseTopologically(visitor); - assertThat( - visitor.getRootTransforms(), - Matchers.>containsInAnyOrder( - empty.getProducingTransformInternal())); - } - - @Test - public void getValueToConsumersSucceeds() { - PCollection created = p.apply(Create.of("1", "2", "3")); - PCollection transformed = - created.apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) - throws Exception { - c.output(Integer.toString(c.element().length())); - } - })); - - PCollection flattened = - PCollectionList.of(created).and(transformed).apply(Flatten.pCollections()); - - p.traverseTopologically(visitor); - - assertThat( - visitor.getValueToConsumers().get(created), - Matchers.>containsInAnyOrder( - transformed.getProducingTransformInternal(), - flattened.getProducingTransformInternal())); - assertThat( - visitor.getValueToConsumers().get(transformed), - Matchers.>containsInAnyOrder( - flattened.getProducingTransformInternal())); - assertThat(visitor.getValueToConsumers().get(flattened), emptyIterable()); - } - - @Test - public void getUnfinalizedPValuesContainsDanglingOutputs() { - PCollection created = p.apply(Create.of("1", "2", "3")); - PCollection transformed = - created.apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) - throws Exception { - c.output(Integer.toString(c.element().length())); - } - })); - - p.traverseTopologically(visitor); - assertThat(visitor.getUnfinalizedPValues(), Matchers.contains(transformed)); - } - - @Test - public void getUnfinalizedPValuesEmpty() { - p.apply(Create.of("1", "2", "3")) - .apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) - throws Exception { - c.output(Integer.toString(c.element().length())); - } - })) - .apply( - new PTransform() { - @Override - public PDone apply(PInput input) { - return PDone.in(input.getPipeline()); - } - }); - - p.traverseTopologically(visitor); - assertThat(visitor.getUnfinalizedPValues(), emptyIterable()); - } - - @Test - public void getStepNamesContainsAllTransforms() { - PCollection created = p.apply(Create.of("1", "2", "3")); - PCollection transformed = - created.apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) - throws Exception { - c.output(Integer.toString(c.element().length())); - } - })); - PDone finished = - transformed.apply( - new PTransform() { - @Override - public PDone apply(PInput input) { - return PDone.in(input.getPipeline()); - } - }); - - p.traverseTopologically(visitor); - assertThat( - visitor.getStepNames(), - Matchers., String>hasEntry( - created.getProducingTransformInternal(), "s0")); - assertThat( - visitor.getStepNames(), - Matchers., String>hasEntry( - transformed.getProducingTransformInternal(), "s1")); - assertThat( - visitor.getStepNames(), - Matchers., String>hasEntry( - finished.getProducingTransformInternal(), "s2")); - } - - @Test - public void traverseMultipleTimesThrows() { - p.apply(Create.of(1, 2, 3)); - - p.traverseTopologically(visitor); - thrown.expect(IllegalStateException.class); - thrown.expectMessage(ConsumerTrackingPipelineVisitor.class.getSimpleName()); - thrown.expectMessage("is finalized"); - p.traverseTopologically(visitor); - } - - @Test - public void traverseIndependentPathsSucceeds() { - p.apply("left", Create.of(1, 2, 3)); - p.apply("right", Create.of("foo", "bar", "baz")); - - p.traverseTopologically(visitor); - } - - @Test - public void getRootTransformsWithoutVisitingThrows() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("completely traversed"); - thrown.expectMessage("getRootTransforms"); - visitor.getRootTransforms(); - } - @Test - public void getStepNamesWithoutVisitingThrows() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("completely traversed"); - thrown.expectMessage("getStepNames"); - visitor.getStepNames(); - } - @Test - public void getUnfinalizedPValuesWithoutVisitingThrows() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("completely traversed"); - thrown.expectMessage("getUnfinalizedPValues"); - visitor.getUnfinalizedPValues(); - } - - @Test - public void getValueToConsumersWithoutVisitingThrows() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("completely traversed"); - thrown.expectMessage("getValueToConsumers"); - visitor.getValueToConsumers(); - } - - @Test - public void getViewsWithoutVisitingThrows() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("completely traversed"); - thrown.expectMessage("getViews"); - visitor.getViews(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java deleted file mode 100644 index 559fc20285..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/EncodabilityEnforcementFactoryTest.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.isA; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collections; - -/** - * Tests for {@link EncodabilityEnforcementFactory}. - */ -@RunWith(JUnit4.class) -public class EncodabilityEnforcementFactoryTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - private EncodabilityEnforcementFactory factory = EncodabilityEnforcementFactory.create(); - private BundleFactory bundleFactory = InProcessBundleFactory.create(); - - @Test - public void encodeFailsThrows() { - TestPipeline p = TestPipeline.create(); - PCollection unencodable = - p.apply(Create.of(new Record()).withCoder(new RecordNoEncodeCoder())); - AppliedPTransform consumer = - unencodable.apply(Count.globally()).getProducingTransformInternal(); - - WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); - CommittedBundle input = - bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); - ModelEnforcement enforcement = factory.forBundle(input, consumer); - - thrown.expect(UserCodeException.class); - thrown.expectCause(isA(CoderException.class)); - thrown.expectMessage("Encode not allowed"); - enforcement.beforeElement(record); - } - - @Test - public void decodeFailsThrows() { - TestPipeline p = TestPipeline.create(); - PCollection unencodable = - p.apply(Create.of(new Record()).withCoder(new RecordNoDecodeCoder())); - AppliedPTransform consumer = - unencodable.apply(Count.globally()).getProducingTransformInternal(); - WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); - - CommittedBundle input = - bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); - ModelEnforcement enforcement = factory.forBundle(input, consumer); - - thrown.expect(UserCodeException.class); - thrown.expectCause(isA(CoderException.class)); - thrown.expectMessage("Decode not allowed"); - enforcement.beforeElement(record); - } - - @Test - public void consistentWithEqualsStructuralValueNotEqualThrows() { - TestPipeline p = TestPipeline.create(); - PCollection unencodable = - p.apply(Create.of(new Record()).withCoder(new RecordStructuralValueCoder())); - AppliedPTransform consumer = - unencodable.apply(Count.globally()).getProducingTransformInternal(); - - WindowedValue record = - WindowedValue.valueInGlobalWindow( - new Record() { - @Override - public String toString() { - return "OriginalRecord"; - } - }); - - CommittedBundle input = - bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); - ModelEnforcement enforcement = factory.forBundle(input, consumer); - - thrown.expect(UserCodeException.class); - thrown.expectCause(isA(IllegalArgumentException.class)); - thrown.expectMessage("does not maintain structural value equality"); - thrown.expectMessage(RecordStructuralValueCoder.class.getSimpleName()); - thrown.expectMessage("OriginalRecord"); - enforcement.beforeElement(record); - } - - @Test - public void notConsistentWithEqualsStructuralValueNotEqualSucceeds() { - TestPipeline p = TestPipeline.create(); - PCollection unencodable = - p.apply( - Create.of(new Record()) - .withCoder(new RecordNotConsistentWithEqualsStructuralValueCoder())); - AppliedPTransform consumer = - unencodable.apply(Count.globally()).getProducingTransformInternal(); - - WindowedValue record = WindowedValue.valueInGlobalWindow(new Record()); - - CommittedBundle input = - bundleFactory.createRootBundle(unencodable).add(record).commit(Instant.now()); - ModelEnforcement enforcement = factory.forBundle(input, consumer); - - enforcement.beforeElement(record); - enforcement.afterElement(record); - enforcement.afterFinish( - input, - StepTransformResult.withoutHold(consumer).build(), - Collections.>emptyList()); - } - - @Test - public void structurallyEqualResultsSucceeds() { - TestPipeline p = TestPipeline.create(); - PCollection unencodable = p.apply(Create.of(1).withCoder(VarIntCoder.of())); - AppliedPTransform consumer = - unencodable.apply(Count.globally()).getProducingTransformInternal(); - - WindowedValue value = WindowedValue.valueInGlobalWindow(1); - - CommittedBundle input = - bundleFactory.createRootBundle(unencodable).add(value).commit(Instant.now()); - ModelEnforcement enforcement = factory.forBundle(input, consumer); - - enforcement.beforeElement(value); - enforcement.afterElement(value); - enforcement.afterFinish( - input, - StepTransformResult.withoutHold(consumer).build(), - Collections.>emptyList()); - } - - private static class Record {} - private static class RecordNoEncodeCoder extends AtomicCoder { - - @Override - public void encode( - Record value, - OutputStream outStream, - com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - throw new CoderException("Encode not allowed"); - } - - @Override - public Record decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - return null; - } - } - - private static class RecordNoDecodeCoder extends AtomicCoder { - @Override - public void encode( - Record value, - OutputStream outStream, - com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException {} - - @Override - public Record decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - throw new CoderException("Decode not allowed"); - } - } - - private static class RecordStructuralValueCoder extends AtomicCoder { - @Override - public void encode( - Record value, - OutputStream outStream, - com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException {} - - @Override - public Record decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - return new Record() { - @Override - public String toString() { - return "DecodedRecord"; - } - }; - } - - @Override - public boolean consistentWithEquals() { - return true; - } - - @Override - public Object structuralValue(Record value) { - return value; - } - } - - private static class RecordNotConsistentWithEqualsStructuralValueCoder - extends AtomicCoder { - @Override - public void encode( - Record value, - OutputStream outStream, - com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException {} - - @Override - public Record decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - return new Record() { - @Override - public String toString() { - return "DecodedRecord"; - } - }; - } - - @Override - public boolean consistentWithEquals() { - return false; - } - - @Override - public Object structuralValue(Record value) { - return value; - } - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java deleted file mode 100644 index 42777a47e7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/FlattenEvaluatorFactoryTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link FlattenEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class FlattenEvaluatorFactoryTest { - private BundleFactory bundleFactory = InProcessBundleFactory.create(); - @Test - public void testFlattenInMemoryEvaluator() throws Exception { - TestPipeline p = TestPipeline.create(); - PCollection left = p.apply("left", Create.of(1, 2, 4)); - PCollection right = p.apply("right", Create.of(-1, 2, -4)); - PCollectionList list = PCollectionList.of(left).and(right); - - PCollection flattened = list.apply(Flatten.pCollections()); - - CommittedBundle leftBundle = - bundleFactory.createRootBundle(left).commit(Instant.now()); - CommittedBundle rightBundle = - bundleFactory.createRootBundle(right).commit(Instant.now()); - - InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - - UncommittedBundle flattenedLeftBundle = bundleFactory.createRootBundle(flattened); - UncommittedBundle flattenedRightBundle = bundleFactory.createRootBundle(flattened); - - when(context.createBundle(leftBundle, flattened)).thenReturn(flattenedLeftBundle); - when(context.createBundle(rightBundle, flattened)).thenReturn(flattenedRightBundle); - - FlattenEvaluatorFactory factory = new FlattenEvaluatorFactory(); - TransformEvaluator leftSideEvaluator = - factory.forApplication(flattened.getProducingTransformInternal(), leftBundle, context); - TransformEvaluator rightSideEvaluator = - factory.forApplication( - flattened.getProducingTransformInternal(), - rightBundle, - context); - - leftSideEvaluator.processElement(WindowedValue.valueInGlobalWindow(1)); - rightSideEvaluator.processElement(WindowedValue.valueInGlobalWindow(-1)); - leftSideEvaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1024))); - leftSideEvaluator.processElement(WindowedValue.valueInEmptyWindows(4, PaneInfo.NO_FIRING)); - rightSideEvaluator.processElement( - WindowedValue.valueInEmptyWindows(2, PaneInfo.ON_TIME_AND_ONLY_FIRING)); - rightSideEvaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow(-4, new Instant(-4096))); - - InProcessTransformResult rightSideResult = rightSideEvaluator.finishBundle(); - InProcessTransformResult leftSideResult = leftSideEvaluator.finishBundle(); - - assertThat( - rightSideResult.getOutputBundles(), - Matchers.>contains(flattenedRightBundle)); - assertThat( - rightSideResult.getTransform(), - Matchers.>equalTo(flattened.getProducingTransformInternal())); - assertThat( - leftSideResult.getOutputBundles(), - Matchers.>contains(flattenedLeftBundle)); - assertThat( - leftSideResult.getTransform(), - Matchers.>equalTo(flattened.getProducingTransformInternal())); - - assertThat( - flattenedLeftBundle.commit(Instant.now()).getElements(), - containsInAnyOrder( - WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1024)), - WindowedValue.valueInEmptyWindows(4, PaneInfo.NO_FIRING), - WindowedValue.valueInGlobalWindow(1))); - assertThat( - flattenedRightBundle.commit(Instant.now()).getElements(), - containsInAnyOrder( - WindowedValue.valueInEmptyWindows(2, PaneInfo.ON_TIME_AND_ONLY_FIRING), - WindowedValue.timestampedValueInGlobalWindow(-4, new Instant(-4096)), - WindowedValue.valueInGlobalWindow(-1))); - } - - @Test - public void testFlattenInMemoryEvaluatorWithEmptyPCollectionList() throws Exception { - TestPipeline p = TestPipeline.create(); - PCollectionList list = PCollectionList.empty(p); - - PCollection flattened = list.apply(Flatten.pCollections()); - - InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - - FlattenEvaluatorFactory factory = new FlattenEvaluatorFactory(); - TransformEvaluator emptyEvaluator = - factory.forApplication(flattened.getProducingTransformInternal(), null, context); - - InProcessTransformResult leftSideResult = emptyEvaluator.finishBundle(); - - assertThat(leftSideResult.getOutputBundles(), emptyIterable()); - assertThat( - leftSideResult.getTransform(), - Matchers.>equalTo(flattened.getProducingTransformInternal())); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java deleted file mode 100644 index 00e9785462..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ForwardingPTransformTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link ForwardingPTransform}. - */ -@RunWith(JUnit4.class) -public class ForwardingPTransformTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Mock private PTransform, PCollection> delegate; - - private ForwardingPTransform, PCollection> forwarding; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - forwarding = - new ForwardingPTransform, PCollection>() { - @Override - protected PTransform, PCollection> delegate() { - return delegate; - } - }; - } - - @Test - public void applyDelegates() { - @SuppressWarnings("unchecked") - PCollection collection = mock(PCollection.class); - @SuppressWarnings("unchecked") - PCollection output = mock(PCollection.class); - when(delegate.apply(collection)).thenReturn(output); - PCollection result = forwarding.apply(collection); - assertThat(result, equalTo(output)); - } - - @Test - public void getNameDelegates() { - String name = "My_forwardingptransform-name;for!thisTest"; - when(delegate.getName()).thenReturn(name); - assertThat(forwarding.getName(), equalTo(name)); - } - - @Test - public void validateDelegates() { - @SuppressWarnings("unchecked") - PCollection input = mock(PCollection.class); - doThrow(RuntimeException.class).when(delegate).validate(input); - - thrown.expect(RuntimeException.class); - forwarding.validate(input); - } - - @Test - public void getDefaultOutputCoderDelegates() throws Exception { - @SuppressWarnings("unchecked") - PCollection input = mock(PCollection.class); - @SuppressWarnings("unchecked") - PCollection output = mock(PCollection.class); - @SuppressWarnings("unchecked") - Coder outputCoder = mock(Coder.class); - - when(delegate.getDefaultOutputCoder(input, output)).thenReturn(outputCoder); - assertThat(forwarding.getDefaultOutputCoder(input, output), equalTo(outputCoder)); - } - - @Test - public void populateDisplayDataDelegates() { - DisplayData.Builder builder = mock(DisplayData.Builder.class); - doThrow(RuntimeException.class).when(delegate).populateDisplayData(builder); - - thrown.expect(RuntimeException.class); - forwarding.populateDisplayData(builder); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java deleted file mode 100644 index 5e8654be5b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/GroupByKeyEvaluatorFactoryTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItem; -import com.google.cloud.dataflow.sdk.util.KeyedWorkItems; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.HashMultiset; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Multiset; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link GroupByKeyEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class GroupByKeyEvaluatorFactoryTest { - private BundleFactory bundleFactory = InProcessBundleFactory.create(); - - @Test - public void testInMemoryEvaluator() throws Exception { - TestPipeline p = TestPipeline.create(); - KV firstFoo = KV.of("foo", -1); - KV secondFoo = KV.of("foo", 1); - KV thirdFoo = KV.of("foo", 3); - KV firstBar = KV.of("bar", 22); - KV secondBar = KV.of("bar", 12); - KV firstBaz = KV.of("baz", Integer.MAX_VALUE); - PCollection> values = - p.apply(Create.of(firstFoo, firstBar, secondFoo, firstBaz, secondBar, thirdFoo)); - PCollection>> kvs = - values.apply(new GroupByKey.ReifyTimestampsAndWindows()); - PCollection> groupedKvs = - kvs.apply(new GroupByKeyEvaluatorFactory.InProcessGroupByKeyOnly()); - - CommittedBundle>> inputBundle = - bundleFactory.createRootBundle(kvs).commit(Instant.now()); - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - StructuralKey fooKey = StructuralKey.of("foo", StringUtf8Coder.of()); - UncommittedBundle> fooBundle = - bundleFactory.createKeyedBundle(null, fooKey, groupedKvs); - - StructuralKey barKey = StructuralKey.of("bar", StringUtf8Coder.of()); - UncommittedBundle> barBundle = - bundleFactory.createKeyedBundle(null, barKey, groupedKvs); - - StructuralKey bazKey = StructuralKey.of("baz", StringUtf8Coder.of()); - UncommittedBundle> bazBundle = - bundleFactory.createKeyedBundle(null, bazKey, groupedKvs); - - when(evaluationContext.createKeyedBundle(inputBundle, - fooKey, - groupedKvs)).thenReturn(fooBundle); - when(evaluationContext.createKeyedBundle(inputBundle, - barKey, - groupedKvs)).thenReturn(barBundle); - when(evaluationContext.createKeyedBundle(inputBundle, - bazKey, - groupedKvs)).thenReturn(bazBundle); - - // The input to a GroupByKey is assumed to be a KvCoder - @SuppressWarnings("unchecked") - Coder keyCoder = - ((KvCoder>) kvs.getCoder()).getKeyCoder(); - TransformEvaluator>> evaluator = - new GroupByKeyEvaluatorFactory() - .forApplication( - groupedKvs.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(firstFoo))); - evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(secondFoo))); - evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(thirdFoo))); - evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(firstBar))); - evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(secondBar))); - evaluator.processElement(WindowedValue.valueInEmptyWindows(gwValue(firstBaz))); - - evaluator.finishBundle(); - - assertThat( - fooBundle.commit(Instant.now()).getElements(), - contains( - new KeyedWorkItemMatcher( - KeyedWorkItems.elementsWorkItem( - "foo", - ImmutableSet.of( - WindowedValue.valueInGlobalWindow(-1), - WindowedValue.valueInGlobalWindow(1), - WindowedValue.valueInGlobalWindow(3))), - keyCoder))); - assertThat( - barBundle.commit(Instant.now()).getElements(), - contains( - new KeyedWorkItemMatcher( - KeyedWorkItems.elementsWorkItem( - "bar", - ImmutableSet.of( - WindowedValue.valueInGlobalWindow(12), - WindowedValue.valueInGlobalWindow(22))), - keyCoder))); - assertThat( - bazBundle.commit(Instant.now()).getElements(), - contains( - new KeyedWorkItemMatcher( - KeyedWorkItems.elementsWorkItem( - "baz", - ImmutableSet.of(WindowedValue.valueInGlobalWindow(Integer.MAX_VALUE))), - keyCoder))); - } - - private KV> gwValue(KV kv) { - return KV.of(kv.getKey(), WindowedValue.valueInGlobalWindow(kv.getValue())); - } - - private static class KeyedWorkItemMatcher - extends BaseMatcher>> { - private final KeyedWorkItem myWorkItem; - private final Coder keyCoder; - - public KeyedWorkItemMatcher(KeyedWorkItem myWorkItem, Coder keyCoder) { - this.myWorkItem = myWorkItem; - this.keyCoder = keyCoder; - } - - @Override - public boolean matches(Object item) { - if (item == null || !(item instanceof WindowedValue)) { - return false; - } - WindowedValue> that = (WindowedValue>) item; - Multiset> myValues = HashMultiset.create(); - Multiset> thatValues = HashMultiset.create(); - for (WindowedValue value : myWorkItem.elementsIterable()) { - myValues.add(value); - } - for (WindowedValue value : that.getValue().elementsIterable()) { - thatValues.add(value); - } - try { - return myValues.equals(thatValues) - && keyCoder - .structuralValue(myWorkItem.key()) - .equals(keyCoder.structuralValue(that.getValue().key())); - } catch (Exception e) { - return false; - } - } - - @Override - public void describeTo(Description description) { - description - .appendText("KeyedWorkItem containing key ") - .appendValue(myWorkItem.key()) - .appendText(" and values ") - .appendValueList("[", ", ", "]", myWorkItem.elementsIterable()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java deleted file mode 100644 index b21a6b11e6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityCheckingBundleFactoryTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.isA; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.UserCodeException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link ImmutabilityCheckingBundleFactory}. - */ -@RunWith(JUnit4.class) -public class ImmutabilityCheckingBundleFactoryTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - private ImmutabilityCheckingBundleFactory factory; - private PCollection created; - private PCollection transformed; - - @Before - public void setup() { - TestPipeline p = TestPipeline.create(); - created = p.apply(Create.of().withCoder(ByteArrayCoder.of())); - transformed = created.apply(ParDo.of(new IdentityDoFn())); - factory = ImmutabilityCheckingBundleFactory.create(InProcessBundleFactory.create()); - } - - @Test - public void noMutationRootBundleSucceeds() { - UncommittedBundle root = factory.createRootBundle(created); - byte[] array = new byte[] {0, 1, 2}; - root.add(WindowedValue.valueInGlobalWindow(array)); - CommittedBundle committed = root.commit(Instant.now()); - - assertThat( - committed.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(array))); - } - - @Test - public void noMutationKeyedBundleSucceeds() { - CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle keyed = factory.createKeyedBundle(root, - StructuralKey.of("mykey", StringUtf8Coder.of()), - transformed); - - WindowedValue windowedArray = - WindowedValue.of( - new byte[] {4, 8, 12}, - new Instant(891L), - new IntervalWindow(new Instant(0), new Instant(1000)), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - keyed.add(windowedArray); - - CommittedBundle committed = keyed.commit(Instant.now()); - assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); - } - - @Test - public void noMutationCreateBundleSucceeds() { - CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle intermediate = factory.createBundle(root, transformed); - - WindowedValue windowedArray = - WindowedValue.of( - new byte[] {4, 8, 12}, - new Instant(891L), - new IntervalWindow(new Instant(0), new Instant(1000)), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - intermediate.add(windowedArray); - - CommittedBundle committed = intermediate.commit(Instant.now()); - assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); - } - - @Test - public void mutationBeforeAddRootBundleSucceeds() { - UncommittedBundle root = factory.createRootBundle(created); - byte[] array = new byte[] {0, 1, 2}; - array[1] = 2; - root.add(WindowedValue.valueInGlobalWindow(array)); - CommittedBundle committed = root.commit(Instant.now()); - - assertThat( - committed.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(array))); - } - - @Test - public void mutationBeforeAddKeyedBundleSucceeds() { - CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle keyed = factory.createKeyedBundle(root, - StructuralKey.of("mykey", StringUtf8Coder.of()), - transformed); - - byte[] array = new byte[] {4, 8, 12}; - array[0] = Byte.MAX_VALUE; - WindowedValue windowedArray = - WindowedValue.of( - array, - new Instant(891L), - new IntervalWindow(new Instant(0), new Instant(1000)), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - keyed.add(windowedArray); - - CommittedBundle committed = keyed.commit(Instant.now()); - assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); - } - - @Test - public void mutationBeforeAddCreateBundleSucceeds() { - CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle intermediate = factory.createBundle(root, transformed); - - byte[] array = new byte[] {4, 8, 12}; - WindowedValue windowedArray = - WindowedValue.of( - array, - new Instant(891L), - new IntervalWindow(new Instant(0), new Instant(1000)), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - array[2] = -3; - intermediate.add(windowedArray); - - CommittedBundle committed = intermediate.commit(Instant.now()); - assertThat(committed.getElements(), containsInAnyOrder(windowedArray)); - } - - @Test - public void mutationAfterAddRootBundleThrows() { - UncommittedBundle root = factory.createRootBundle(created); - byte[] array = new byte[] {0, 1, 2}; - root.add(WindowedValue.valueInGlobalWindow(array)); - - array[1] = 2; - thrown.expect(UserCodeException.class); - thrown.expectCause(isA(IllegalMutationException.class)); - thrown.expectMessage("Values must not be mutated in any way after being output"); - CommittedBundle committed = root.commit(Instant.now()); - } - - @Test - public void mutationAfterAddKeyedBundleThrows() { - CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle keyed = factory.createKeyedBundle(root, - StructuralKey.of("mykey", StringUtf8Coder.of()), - transformed); - - byte[] array = new byte[] {4, 8, 12}; - WindowedValue windowedArray = - WindowedValue.of( - array, - new Instant(891L), - new IntervalWindow(new Instant(0), new Instant(1000)), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - keyed.add(windowedArray); - - array[0] = Byte.MAX_VALUE; - thrown.expect(UserCodeException.class); - thrown.expectCause(isA(IllegalMutationException.class)); - thrown.expectMessage("Values must not be mutated in any way after being output"); - CommittedBundle committed = keyed.commit(Instant.now()); - } - - @Test - public void mutationAfterAddCreateBundleThrows() { - CommittedBundle root = factory.createRootBundle(created).commit(Instant.now()); - UncommittedBundle intermediate = factory.createBundle(root, transformed); - - byte[] array = new byte[] {4, 8, 12}; - WindowedValue windowedArray = - WindowedValue.of( - array, - new Instant(891L), - new IntervalWindow(new Instant(0), new Instant(1000)), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - intermediate.add(windowedArray); - - array[2] = -3; - thrown.expect(UserCodeException.class); - thrown.expectCause(isA(IllegalMutationException.class)); - thrown.expectMessage("Values must not be mutated in any way after being output"); - CommittedBundle committed = intermediate.commit(Instant.now()); - } - - private static class IdentityDoFn extends DoFn { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - c.output(c.element()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java deleted file mode 100644 index ced1354f61..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ImmutabilityEnforcementFactoryTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Collections; - -/** - * Tests for {@link ImmutabilityEnforcementFactory}. - */ -@RunWith(JUnit4.class) -public class ImmutabilityEnforcementFactoryTest implements Serializable { - @Rule public transient ExpectedException thrown = ExpectedException.none(); - private transient ImmutabilityEnforcementFactory factory; - private transient BundleFactory bundleFactory; - private transient PCollection pcollection; - private transient AppliedPTransform consumer; - - @Before - public void setup() { - factory = new ImmutabilityEnforcementFactory(); - bundleFactory = InProcessBundleFactory.create(); - TestPipeline p = TestPipeline.create(); - pcollection = - p.apply(Create.of("foo".getBytes(), "spamhameggs".getBytes())) - .apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) - throws Exception { - c.element()[0] = 'b'; - } - })); - consumer = pcollection.apply(Count.globally()).getProducingTransformInternal(); - } - - @Test - public void unchangedSucceeds() { - WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); - CommittedBundle elements = - bundleFactory.createRootBundle(pcollection).add(element).commit(Instant.now()); - - ModelEnforcement enforcement = factory.forBundle(elements, consumer); - enforcement.beforeElement(element); - enforcement.afterElement(element); - enforcement.afterFinish( - elements, - StepTransformResult.withoutHold(consumer).build(), - Collections.>emptyList()); - } - - @Test - public void mutatedDuringProcessElementThrows() { - WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); - CommittedBundle elements = - bundleFactory.createRootBundle(pcollection).add(element).commit(Instant.now()); - - ModelEnforcement enforcement = factory.forBundle(elements, consumer); - enforcement.beforeElement(element); - element.getValue()[0] = 'f'; - thrown.expect(IllegalMutationException.class); - thrown.expectMessage(consumer.getFullName()); - thrown.expectMessage("illegaly mutated"); - thrown.expectMessage("Input values must not be mutated"); - enforcement.afterElement(element); - enforcement.afterFinish( - elements, - StepTransformResult.withoutHold(consumer).build(), - Collections.>emptyList()); - } - - @Test - public void mutatedAfterProcessElementFails() { - - WindowedValue element = WindowedValue.valueInGlobalWindow("bar".getBytes()); - CommittedBundle elements = - bundleFactory.createRootBundle(pcollection).add(element).commit(Instant.now()); - - ModelEnforcement enforcement = factory.forBundle(elements, consumer); - enforcement.beforeElement(element); - enforcement.afterElement(element); - - element.getValue()[0] = 'f'; - thrown.expect(IllegalMutationException.class); - thrown.expectMessage(consumer.getFullName()); - thrown.expectMessage("illegaly mutated"); - thrown.expectMessage("Input values must not be mutated"); - enforcement.afterFinish( - elements, - StepTransformResult.withoutHold(consumer).build(), - Collections.>emptyList()); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java deleted file mode 100644 index bb46cbb19e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InMemoryWatermarkManagerTest.java +++ /dev/null @@ -1,1429 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Filter; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.joda.time.Instant; -import org.joda.time.ReadableInstant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; -import javax.annotation.Nullable; - -/** - * Tests for {@link InMemoryWatermarkManager}. - */ -@RunWith(JUnit4.class) -public class InMemoryWatermarkManagerTest implements Serializable { - private transient MockClock clock; - - private transient PCollection createdInts; - - private transient PCollection filtered; - private transient PCollection filteredTimesTwo; - private transient PCollection> keyed; - - private transient PCollection intsToFlatten; - private transient PCollection flattened; - - private transient InMemoryWatermarkManager manager; - private transient BundleFactory bundleFactory; - - @Before - public void setup() { - TestPipeline p = TestPipeline.create(); - - createdInts = p.apply("createdInts", Create.of(1, 2, 3)); - - filtered = createdInts.apply("filtered", Filter.greaterThan(1)); - filteredTimesTwo = filtered.apply("timesTwo", ParDo.of(new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - c.output(c.element() * 2); - } - })); - - keyed = createdInts.apply("keyed", WithKeys.of("MyKey")); - - intsToFlatten = p.apply("intsToFlatten", Create.of(-1, 256, 65535)); - PCollectionList preFlatten = PCollectionList.of(createdInts).and(intsToFlatten); - flattened = preFlatten.apply("flattened", Flatten.pCollections()); - - Collection> rootTransforms = - ImmutableList.>of( - createdInts.getProducingTransformInternal(), - intsToFlatten.getProducingTransformInternal()); - - Map>> consumers = new HashMap<>(); - consumers.put( - createdInts, - ImmutableList.>of(filtered.getProducingTransformInternal(), - keyed.getProducingTransformInternal(), flattened.getProducingTransformInternal())); - consumers.put( - filtered, - Collections.>singleton( - filteredTimesTwo.getProducingTransformInternal())); - consumers.put(filteredTimesTwo, Collections.>emptyList()); - consumers.put(keyed, Collections.>emptyList()); - - consumers.put( - intsToFlatten, - Collections.>singleton( - flattened.getProducingTransformInternal())); - consumers.put(flattened, Collections.>emptyList()); - - clock = MockClock.fromInstant(new Instant(1000)); - - manager = InMemoryWatermarkManager.create(clock, rootTransforms, consumers); - bundleFactory = InProcessBundleFactory.create(); - } - - /** - * Demonstrates that getWatermark, when called on an {@link AppliedPTransform} that has not - * processed any elements, returns the {@link BoundedWindow#TIMESTAMP_MIN_VALUE}. - */ - @Test - public void getWatermarkForUntouchedTransform() { - TransformWatermarks watermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - - assertThat(watermarks.getInputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - assertThat(watermarks.getOutputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - } - - /** - * Demonstrates that getWatermark for a transform that consumes no input uses the Watermark - * Hold value provided to it as the output watermark. - */ - @Test - public void getWatermarkForUpdatedSourceTransform() { - CommittedBundle output = multiWindowedBundle(createdInts, 1); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(output)), - new Instant(8000L)); - manager.refreshAll(); - TransformWatermarks updatedSourceWatermark = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - - assertThat(updatedSourceWatermark.getOutputWatermark(), equalTo(new Instant(8000L))); - } - - /** - * Demonstrates that getWatermark for a transform that takes multiple inputs is held to the - * minimum watermark across all of its inputs. - */ - @Test - public void getWatermarkForMultiInputTransform() { - CommittedBundle secondPcollectionBundle = multiWindowedBundle(intsToFlatten, -1); - - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(intsToFlatten.getProducingTransformInternal(), - null, - Collections.>singleton(secondPcollectionBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - - // We didn't do anything for the first source, so we shouldn't have progressed the watermark - TransformWatermarks firstSourceWatermark = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat( - firstSourceWatermark.getOutputWatermark(), - not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - - // the Second Source output all of the elements so it should be done (with a watermark at the - // end of time). - TransformWatermarks secondSourceWatermark = - manager.getWatermarks(intsToFlatten.getProducingTransformInternal()); - assertThat( - secondSourceWatermark.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - - // We haven't consumed anything yet, so our watermark should be at the beginning of time - TransformWatermarks transformWatermark = - manager.getWatermarks(flattened.getProducingTransformInternal()); - assertThat( - transformWatermark.getInputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - assertThat( - transformWatermark.getOutputWatermark(), not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - - CommittedBundle flattenedBundleSecondCreate = multiWindowedBundle(flattened, -1); - // We have finished processing the bundle from the second PCollection, but we haven't consumed - // anything from the first PCollection yet; so our watermark shouldn't advance - manager.updateWatermarks(secondPcollectionBundle, - TimerUpdate.empty(), - result(flattened.getProducingTransformInternal(), - secondPcollectionBundle.withElements(Collections.>emptyList()), - Collections.>singleton(flattenedBundleSecondCreate)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - TransformWatermarks transformAfterProcessing = - manager.getWatermarks(flattened.getProducingTransformInternal()); - manager.updateWatermarks(secondPcollectionBundle, - TimerUpdate.empty(), - result(flattened.getProducingTransformInternal(), - secondPcollectionBundle.withElements(Collections.>emptyList()), - Collections.>singleton(flattenedBundleSecondCreate)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - assertThat( - transformAfterProcessing.getInputWatermark(), - not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - assertThat( - transformAfterProcessing.getOutputWatermark(), - not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - - Instant firstCollectionTimestamp = new Instant(10000); - CommittedBundle firstPcollectionBundle = - timestampedBundle(createdInts, TimestampedValue.of(5, firstCollectionTimestamp)); - // the source is done, but elements are still buffered. The source output watermark should be - // past the end of the global window - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(firstPcollectionBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks firstSourceWatermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat( - firstSourceWatermarks.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - - // We still haven't consumed any of the first source's input, so the watermark should still not - // progress - TransformWatermarks flattenAfterSourcesProduced = - manager.getWatermarks(flattened.getProducingTransformInternal()); - assertThat( - flattenAfterSourcesProduced.getInputWatermark(), not(laterThan(firstCollectionTimestamp))); - assertThat( - flattenAfterSourcesProduced.getOutputWatermark(), not(laterThan(firstCollectionTimestamp))); - - // We have buffered inputs, but since the PCollection has all of the elements (has a WM past the - // end of the global window), we should have a watermark equal to the min among buffered - // elements - TransformWatermarks withBufferedElements = - manager.getWatermarks(flattened.getProducingTransformInternal()); - assertThat(withBufferedElements.getInputWatermark(), equalTo(firstCollectionTimestamp)); - assertThat(withBufferedElements.getOutputWatermark(), equalTo(firstCollectionTimestamp)); - - CommittedBundle completedFlattenBundle = - bundleFactory.createRootBundle(flattened).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(firstPcollectionBundle, - TimerUpdate.empty(), - result(flattened.getProducingTransformInternal(), - firstPcollectionBundle.withElements(Collections.>emptyList()), - Collections.>singleton(completedFlattenBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks afterConsumingAllInput = - manager.getWatermarks(flattened.getProducingTransformInternal()); - assertThat( - afterConsumingAllInput.getInputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat( - afterConsumingAllInput.getOutputWatermark(), - not(laterThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - } - - /** - * Demonstrates that pending elements are independent among - * {@link AppliedPTransform AppliedPTransforms} that consume the same input {@link PCollection}. - */ - @Test - public void getWatermarkForMultiConsumedCollection() { - CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createdBundle)), - new Instant(Long.MAX_VALUE)); - manager.refreshAll(); - TransformWatermarks createdAfterProducing = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat( - createdAfterProducing.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - - CommittedBundle> keyBundle = - timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), - TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), - TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, - TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(keyBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks keyedWatermarks = - manager.getWatermarks(keyed.getProducingTransformInternal()); - assertThat( - keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat( - keyedWatermarks.getOutputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - - TransformWatermarks filteredWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat(filteredWatermarks.getInputWatermark(), not(laterThan(new Instant(-1000L)))); - assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); - - CommittedBundle filteredBundle = - timestampedBundle(filtered, TimestampedValue.of(2, new Instant(1234L))); - manager.updateWatermarks(createdBundle, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(filteredBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks filteredProcessedWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat( - filteredProcessedWatermarks.getInputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat( - filteredProcessedWatermarks.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - } - - /** - * Demonstrates that the watermark of an {@link AppliedPTransform} is held to the provided - * watermark hold. - */ - @Test - public void updateWatermarkWithWatermarkHolds() { - CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createdBundle)), - new Instant(Long.MAX_VALUE)); - - CommittedBundle> keyBundle = timestampedBundle(keyed, - TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), - TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), - TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, - TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(keyBundle)), - new Instant(500L)); - manager.refreshAll(); - TransformWatermarks keyedWatermarks = - manager.getWatermarks(keyed.getProducingTransformInternal()); - assertThat( - keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); - } - - /** - * Demonstrates that the watermark of an {@link AppliedPTransform} is held to the provided - * watermark hold. - */ - @Test - public void updateWatermarkWithKeyedWatermarkHolds() { - CommittedBundle firstKeyBundle = bundleFactory.createKeyedBundle(null, - StructuralKey.of("Odd", StringUtf8Coder.of()), - createdInts) - .add(WindowedValue.timestampedValueInGlobalWindow(1, new Instant(1_000_000L))) - .add(WindowedValue.timestampedValueInGlobalWindow(3, new Instant(-1000L))) - .commit(clock.now()); - - CommittedBundle secondKeyBundle = bundleFactory.createKeyedBundle(null, - StructuralKey.of("Even", StringUtf8Coder.of()), - createdInts) - .add(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1234L))) - .commit(clock.now()); - - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - ImmutableList.of(firstKeyBundle, secondKeyBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - - manager.updateWatermarks(firstKeyBundle, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - firstKeyBundle.withElements(Collections.>emptyList()), - Collections.>emptyList()), - new Instant(-1000L)); - manager.updateWatermarks(secondKeyBundle, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - secondKeyBundle.withElements(Collections.>emptyList()), - Collections.>emptyList()), - new Instant(1234L)); - manager.refreshAll(); - - TransformWatermarks filteredWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat(filteredWatermarks.getInputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat(filteredWatermarks.getOutputWatermark(), not(laterThan(new Instant(-1000L)))); - - CommittedBundle fauxFirstKeyTimerBundle = bundleFactory.createKeyedBundle(null, - StructuralKey.of("Odd", StringUtf8Coder.of()), - createdInts).commit(clock.now()); - manager.updateWatermarks(fauxFirstKeyTimerBundle, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - fauxFirstKeyTimerBundle.withElements(Collections.>emptyList()), - Collections.>emptyList()), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - - assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(1234L))); - - CommittedBundle fauxSecondKeyTimerBundle = bundleFactory.createKeyedBundle(null, - StructuralKey.of("Even", StringUtf8Coder.of()), - createdInts).commit(clock.now()); - manager.updateWatermarks(fauxSecondKeyTimerBundle, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - fauxSecondKeyTimerBundle.withElements(Collections.>emptyList()), - Collections.>emptyList()), - new Instant(5678L)); - manager.refreshAll(); - assertThat(filteredWatermarks.getOutputWatermark(), equalTo(new Instant(5678L))); - - manager.updateWatermarks(fauxSecondKeyTimerBundle, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - fauxSecondKeyTimerBundle.withElements(Collections.>emptyList()), - Collections.>emptyList()), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - assertThat(filteredWatermarks.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - } - - /** - * Demonstrates that updated output watermarks are monotonic in the presence of late data, when - * called on an {@link AppliedPTransform} that consumes no input. - */ - @Test - public void updateOutputWatermarkShouldBeMonotonic() { - CommittedBundle firstInput = - bundleFactory.createRootBundle(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(null, TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(firstInput)), - new Instant(0L)); - manager.refreshAll(); - TransformWatermarks firstWatermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(firstWatermarks.getOutputWatermark(), equalTo(new Instant(0L))); - - CommittedBundle secondInput = - bundleFactory.createRootBundle(createdInts).commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(secondInput)), - new Instant(-250L)); - manager.refreshAll(); - TransformWatermarks secondWatermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(secondWatermarks.getOutputWatermark(), not(earlierThan(new Instant(0L)))); - } - - /** - * Demonstrates that updated output watermarks are monotonic in the presence of watermark holds - * that become earlier than a previous watermark hold. - */ - @Test - public void updateWatermarkWithHoldsShouldBeMonotonic() { - CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, new Instant(1_000_000L)), - TimestampedValue.of(2, new Instant(1234L)), - TimestampedValue.of(3, new Instant(-1000L))); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createdBundle)), - new Instant(Long.MAX_VALUE)); - - CommittedBundle> keyBundle = - timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), new Instant(1_000_000L)), - TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L)), - TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(createdBundle, - TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(keyBundle)), - new Instant(500L)); - manager.refreshAll(); - TransformWatermarks keyedWatermarks = - manager.getWatermarks(keyed.getProducingTransformInternal()); - assertThat( - keyedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat(keyedWatermarks.getOutputWatermark(), not(laterThan(new Instant(500L)))); - Instant oldOutputWatermark = keyedWatermarks.getOutputWatermark(); - - TransformWatermarks updatedWatermarks = - manager.getWatermarks(keyed.getProducingTransformInternal()); - assertThat( - updatedWatermarks.getInputWatermark(), not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - // We added a hold prior to the old watermark; we shouldn't progress (due to the earlier hold) - // but the watermark is monotonic and should not backslide to the new, earlier hold - assertThat(updatedWatermarks.getOutputWatermark(), equalTo(oldOutputWatermark)); - } - - @Test - public void updateWatermarkWithUnprocessedElements() { - WindowedValue first = WindowedValue.valueInGlobalWindow(1); - WindowedValue second = - WindowedValue.timestampedValueInGlobalWindow(2, new Instant(-1000L)); - WindowedValue third = - WindowedValue.timestampedValueInGlobalWindow(3, new Instant(1234L)); - CommittedBundle createdBundle = bundleFactory.createRootBundle(createdInts) - .add(first) - .add(second) - .add(third) - .commit(clock.now()); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createdBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - - CommittedBundle> keyBundle = timestampedBundle(keyed, - TimestampedValue.of(KV.of("MyKey", 1), BoundedWindow.TIMESTAMP_MIN_VALUE)); - manager.updateWatermarks(createdBundle, - TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), - createdBundle.withElements(ImmutableList.of(second, third)), - Collections.>singleton(keyBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - TransformWatermarks keyedWatermarks = - manager.getWatermarks(keyed.getProducingTransformInternal()); - // the unprocessed second and third are readded to pending - assertThat( - keyedWatermarks.getInputWatermark(), not(laterThan(new Instant(-1000L)))); - } - - /** - * Demonstrates that updateWatermarks in the presence of late data is monotonic. - */ - @Test - public void updateWatermarkWithLateData() { - Instant sourceWatermark = new Instant(1_000_000L); - CommittedBundle createdBundle = timestampedBundle(createdInts, - TimestampedValue.of(1, sourceWatermark), TimestampedValue.of(2, new Instant(1234L))); - - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createdBundle)), - sourceWatermark); - - CommittedBundle> keyBundle = - timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 1), sourceWatermark), - TimestampedValue.of(KV.of("MyKey", 2), new Instant(1234L))); - - // Finish processing the on-time data. The watermarks should progress to be equal to the source - manager.updateWatermarks(createdBundle, - TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(keyBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks onTimeWatermarks = - manager.getWatermarks(keyed.getProducingTransformInternal()); - assertThat(onTimeWatermarks.getInputWatermark(), equalTo(sourceWatermark)); - assertThat(onTimeWatermarks.getOutputWatermark(), equalTo(sourceWatermark)); - - CommittedBundle lateDataBundle = - timestampedBundle(createdInts, TimestampedValue.of(3, new Instant(-1000L))); - // the late data arrives in a downstream PCollection after its watermark has advanced past it; - // we don't advance the watermark past the current watermark until we've consumed the late data - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(lateDataBundle)), - new Instant(2_000_000L)); - manager.refreshAll(); - TransformWatermarks bufferedLateWm = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(bufferedLateWm.getOutputWatermark(), equalTo(new Instant(2_000_000L))); - - // The input watermark should be held to its previous value (not advanced due to late data; not - // moved backwards in the presence of watermarks due to monotonicity). - TransformWatermarks lateDataBufferedWatermark = - manager.getWatermarks(keyed.getProducingTransformInternal()); - assertThat(lateDataBufferedWatermark.getInputWatermark(), not(earlierThan(sourceWatermark))); - assertThat(lateDataBufferedWatermark.getOutputWatermark(), not(earlierThan(sourceWatermark))); - - CommittedBundle> lateKeyedBundle = - timestampedBundle(keyed, TimestampedValue.of(KV.of("MyKey", 3), new Instant(-1000L))); - manager.updateWatermarks(lateDataBundle, - TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), - lateDataBundle.withElements(Collections.>emptyList()), - Collections.>singleton(lateKeyedBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - } - - public void updateWatermarkWithDifferentWindowedValueInstances() { - manager.updateWatermarks( - null, - TimerUpdate.empty(), result(createdInts.getProducingTransformInternal(), null, - Collections.>singleton( - bundleFactory - .createRootBundle(createdInts) - .add(WindowedValue.valueInGlobalWindow(1)) - .commit(Instant.now()))), - BoundedWindow.TIMESTAMP_MAX_VALUE); - - CommittedBundle createdBundle = bundleFactory.createRootBundle(createdInts) - .add(WindowedValue.valueInGlobalWindow(1)) - .commit(Instant.now()); - manager.updateWatermarks(createdBundle, - TimerUpdate.empty(), - result(keyed.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>emptyList()), - null); - manager.refreshAll(); - TransformWatermarks onTimeWatermarks = - manager.getWatermarks(keyed.getProducingTransformInternal()); - assertThat(onTimeWatermarks.getInputWatermark(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - } - - /** - * Demonstrates that after watermarks of an upstream transform are updated, but no output has been - * produced, the watermarks of a downstream process are advanced. - */ - @Test - public void getWatermarksAfterOnlyEmptyOutput() { - CommittedBundle emptyCreateOutput = multiWindowedBundle(createdInts); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(emptyCreateOutput)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks updatedSourceWatermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - - assertThat( - updatedSourceWatermarks.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - - TransformWatermarks finishedFilterWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat( - finishedFilterWatermarks.getInputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat( - finishedFilterWatermarks.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - } - - /** - * Demonstrates that after watermarks of an upstream transform are updated, but no output has been - * produced, and the downstream transform has a watermark hold, the watermark is held to the hold. - */ - @Test - public void getWatermarksAfterHoldAndEmptyOutput() { - CommittedBundle firstCreateOutput = multiWindowedBundle(createdInts, 1, 2); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(firstCreateOutput)), - new Instant(12_000L)); - - CommittedBundle firstFilterOutput = multiWindowedBundle(filtered); - manager.updateWatermarks(firstCreateOutput, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - firstCreateOutput.withElements(Collections.>emptyList()), - Collections.>singleton(firstFilterOutput)), - new Instant(10_000L)); - manager.refreshAll(); - TransformWatermarks firstFilterWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat(firstFilterWatermarks.getInputWatermark(), not(earlierThan(new Instant(12_000L)))); - assertThat(firstFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); - - CommittedBundle emptyCreateOutput = multiWindowedBundle(createdInts); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(emptyCreateOutput)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks updatedSourceWatermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - - assertThat( - updatedSourceWatermarks.getOutputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - - TransformWatermarks finishedFilterWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat( - finishedFilterWatermarks.getInputWatermark(), - not(earlierThan(BoundedWindow.TIMESTAMP_MAX_VALUE))); - assertThat(finishedFilterWatermarks.getOutputWatermark(), not(laterThan(new Instant(10_000L)))); - } - - @Test - public void getSynchronizedProcessingTimeInputWatermarksHeldToPendingBundles() { - TransformWatermarks watermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(clock.now())); - assertThat( - watermarks.getSynchronizedProcessingOutputTime(), - equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - - TransformWatermarks filteredWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - // Non-root processing watermarks don't progress until data has been processed - assertThat( - filteredWatermarks.getSynchronizedProcessingInputTime(), - not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - assertThat( - filteredWatermarks.getSynchronizedProcessingOutputTime(), - not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - - CommittedBundle createOutput = - bundleFactory.createRootBundle(createdInts).commit(new Instant(1250L)); - - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createOutput)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks createAfterUpdate = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(clock.now())); - assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); - - TransformWatermarks filterAfterProduced = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat( - filterAfterProduced.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); - assertThat( - filterAfterProduced.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); - - clock.set(new Instant(1500L)); - assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), equalTo(clock.now())); - assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); - assertThat( - filterAfterProduced.getSynchronizedProcessingInputTime(), - not(laterThan(new Instant(1250L)))); - assertThat( - filterAfterProduced.getSynchronizedProcessingOutputTime(), - not(laterThan(new Instant(1250L)))); - - CommittedBundle filterOutputBundle = - bundleFactory.createRootBundle(intsToFlatten).commit(new Instant(1250L)); - manager.updateWatermarks(createOutput, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - createOutput.withElements(Collections.>emptyList()), - Collections.>singleton(filterOutputBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks filterAfterConsumed = - manager.getWatermarks(filtered.getProducingTransformInternal()); - assertThat( - filterAfterConsumed.getSynchronizedProcessingInputTime(), - not(laterThan(createAfterUpdate.getSynchronizedProcessingOutputTime()))); - assertThat( - filterAfterConsumed.getSynchronizedProcessingOutputTime(), - not(laterThan(filterAfterConsumed.getSynchronizedProcessingInputTime()))); - } - - /** - * Demonstrates that the Synchronized Processing Time output watermark cannot progress past - * pending timers in the same set. This propagates to all downstream SynchronizedProcessingTimes. - * - *

              Also demonstrate that the result is monotonic. - */ - // @Test - public void getSynchronizedProcessingTimeOutputHeldToPendingTimers() { - CommittedBundle createdBundle = multiWindowedBundle(createdInts, 1, 2, 4, 8); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createdBundle)), - new Instant(1248L)); - manager.refreshAll(); - - TransformWatermarks filteredWms = - manager.getWatermarks(filtered.getProducingTransformInternal()); - TransformWatermarks filteredDoubledWms = - manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); - Instant initialFilteredWm = filteredWms.getSynchronizedProcessingOutputTime(); - Instant initialFilteredDoubledWm = filteredDoubledWms.getSynchronizedProcessingOutputTime(); - - StructuralKey key = StructuralKey.of("key", StringUtf8Coder.of()); - CommittedBundle filteredBundle = multiWindowedBundle(filtered, 2, 8); - TimerData pastTimer = - TimerData.of(StateNamespaces.global(), new Instant(250L), TimeDomain.PROCESSING_TIME); - TimerData futureTimer = - TimerData.of(StateNamespaces.global(), new Instant(4096L), TimeDomain.PROCESSING_TIME); - TimerUpdate timers = - TimerUpdate.builder(key).setTimer(pastTimer).setTimer(futureTimer).build(); - manager.updateWatermarks(createdBundle, - timers, - result(filtered.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(filteredBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - Instant startTime = clock.now(); - clock.set(startTime.plus(250L)); - // We're held based on the past timer - assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); - assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); - // And we're monotonic - assertThat( - filteredWms.getSynchronizedProcessingOutputTime(), not(earlierThan(initialFilteredWm))); - assertThat( - filteredDoubledWms.getSynchronizedProcessingOutputTime(), - not(earlierThan(initialFilteredDoubledWm))); - - Map, Map, FiredTimers>> firedTimers = - manager.extractFiredTimers(); - assertThat( - firedTimers.get(filtered.getProducingTransformInternal()) - .get(key) - .getTimers(TimeDomain.PROCESSING_TIME), - contains(pastTimer)); - // Our timer has fired, but has not been completed, so it holds our synchronized processing WM - assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); - assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), not(laterThan(startTime))); - - CommittedBundle filteredTimerBundle = - bundleFactory - .createKeyedBundle(null, key, filtered) - .commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - CommittedBundle filteredTimerResult = - bundleFactory.createKeyedBundle(null, key, filteredTimesTwo) - .commit(filteredWms.getSynchronizedProcessingOutputTime()); - // Complete the processing time timer - manager.updateWatermarks(filteredTimerBundle, - TimerUpdate.builder(key) - .withCompletedTimers(Collections.singleton(pastTimer)).build(), - result(filtered.getProducingTransformInternal(), - filteredTimerBundle.withElements(Collections.>emptyList()), - Collections.>singleton(filteredTimerResult)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - - clock.set(startTime.plus(500L)); - assertThat(filteredWms.getSynchronizedProcessingOutputTime(), not(laterThan(clock.now()))); - // filtered should be held to the time at which the filteredTimerResult fired - assertThat( - filteredDoubledWms.getSynchronizedProcessingOutputTime(), - not(earlierThan(filteredTimerResult.getSynchronizedProcessingOutputWatermark()))); - - manager.updateWatermarks(filteredTimerResult, - TimerUpdate.empty(), - result(filteredTimesTwo.getProducingTransformInternal(), - filteredTimerResult.withElements(Collections.>emptyList()), - Collections.>emptyList()), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - assertThat(filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); - - clock.set(new Instant(Long.MAX_VALUE)); - assertThat(filteredWms.getSynchronizedProcessingOutputTime(), equalTo(new Instant(4096))); - assertThat( - filteredDoubledWms.getSynchronizedProcessingOutputTime(), equalTo(new Instant(4096))); - } - - /** - * Demonstrates that if any earlier processing holds appear in the synchronized processing time - * output hold the result is monotonic. - */ - @Test - public void getSynchronizedProcessingTimeOutputTimeIsMonotonic() { - Instant startTime = clock.now(); - TransformWatermarks watermarks = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(watermarks.getSynchronizedProcessingInputTime(), equalTo(startTime)); - - TransformWatermarks filteredWatermarks = - manager.getWatermarks(filtered.getProducingTransformInternal()); - // Non-root processing watermarks don't progress until data has been processed - assertThat( - filteredWatermarks.getSynchronizedProcessingInputTime(), - not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - assertThat( - filteredWatermarks.getSynchronizedProcessingOutputTime(), - not(laterThan(BoundedWindow.TIMESTAMP_MIN_VALUE))); - - CommittedBundle createOutput = - bundleFactory.createRootBundle(createdInts).commit(new Instant(1250L)); - - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createOutput)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - TransformWatermarks createAfterUpdate = - manager.getWatermarks(createdInts.getProducingTransformInternal()); - assertThat(createAfterUpdate.getSynchronizedProcessingInputTime(), not(laterThan(clock.now()))); - assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), - not(laterThan(clock.now()))); - - CommittedBundle createSecondOutput = - bundleFactory.createRootBundle(createdInts).commit(new Instant(750L)); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(createSecondOutput)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - - assertThat(createAfterUpdate.getSynchronizedProcessingOutputTime(), equalTo(clock.now())); - } - - @Test - public void synchronizedProcessingInputTimeIsHeldToUpstreamProcessingTimeTimers() { - CommittedBundle created = multiWindowedBundle(createdInts, 1, 2, 3); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(created)), - new Instant(40_900L)); - manager.refreshAll(); - - CommittedBundle filteredBundle = multiWindowedBundle(filtered, 2, 4); - Instant upstreamHold = new Instant(2048L); - TimerData upstreamProcessingTimer = - TimerData.of(StateNamespaces.global(), upstreamHold, TimeDomain.PROCESSING_TIME); - manager.updateWatermarks(created, - TimerUpdate.builder(StructuralKey.of("key", StringUtf8Coder.of())) - .setTimer(upstreamProcessingTimer) - .build(), - result(filtered.getProducingTransformInternal(), - created.withElements(Collections.>emptyList()), - Collections.>singleton(filteredBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - - TransformWatermarks downstreamWms = - manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(clock.now())); - - clock.set(BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); - - manager.extractFiredTimers(); - // Pending processing time timers that have been fired but aren't completed hold the - // synchronized processing time - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); - - CommittedBundle otherCreated = multiWindowedBundle(createdInts, 4, 8, 12); - manager.updateWatermarks(otherCreated, - TimerUpdate.builder(StructuralKey.of("key", StringUtf8Coder.of())) - .withCompletedTimers(Collections.singleton(upstreamProcessingTimer)).build(), - result(filtered.getProducingTransformInternal(), - otherCreated.withElements(Collections.>emptyList()), - Collections.>emptyList()), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), not(earlierThan(clock.now()))); - } - - @Test - public void synchronizedProcessingInputTimeIsHeldToPendingBundleTimes() { - CommittedBundle created = multiWindowedBundle(createdInts, 1, 2, 3); - manager.updateWatermarks( - null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>singleton(created)), - new Instant(29_919_235L)); - - Instant upstreamHold = new Instant(2048L); - CommittedBundle filteredBundle = bundleFactory.createKeyedBundle(created, - StructuralKey.of("key", StringUtf8Coder.of()), - filtered).commit(upstreamHold); - manager.updateWatermarks( - created, - TimerUpdate.empty(), - result(filtered.getProducingTransformInternal(), - created.withElements(Collections.>emptyList()), - Collections.>singleton(filteredBundle)), - BoundedWindow.TIMESTAMP_MAX_VALUE); - manager.refreshAll(); - - TransformWatermarks downstreamWms = - manager.getWatermarks(filteredTimesTwo.getProducingTransformInternal()); - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(clock.now())); - - clock.set(BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(downstreamWms.getSynchronizedProcessingInputTime(), equalTo(upstreamHold)); - } - - @Test - public void extractFiredTimersReturnsFiredEventTimeTimers() { - Map, Map, FiredTimers>> initialTimers = - manager.extractFiredTimers(); - // Watermarks haven't advanced - assertThat(initialTimers.entrySet(), emptyIterable()); - - // Advance WM of keyed past the first timer, but ahead of the second and third - CommittedBundle createdBundle = multiWindowedBundle(filtered); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.singleton(createdBundle)), - new Instant(1500L)); - manager.refreshAll(); - - TimerData earliestTimer = - TimerData.of(StateNamespaces.global(), new Instant(1000), TimeDomain.EVENT_TIME); - TimerData middleTimer = - TimerData.of(StateNamespaces.global(), new Instant(5000L), TimeDomain.EVENT_TIME); - TimerData lastTimer = - TimerData.of(StateNamespaces.global(), new Instant(10000L), TimeDomain.EVENT_TIME); - StructuralKey key = StructuralKey.of(new byte[] {1, 4, 9}, ByteArrayCoder.of()); - TimerUpdate update = - TimerUpdate.builder(key) - .setTimer(earliestTimer) - .setTimer(middleTimer) - .setTimer(lastTimer) - .build(); - - manager.updateWatermarks(createdBundle, - update, - result(filtered.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(multiWindowedBundle(intsToFlatten))), - new Instant(1000L)); - manager.refreshAll(); - - Map, Map, FiredTimers>> firstTransformFiredTimers = - manager.extractFiredTimers(); - assertThat( - firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map, FiredTimers> firstFilteredTimers = - firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); - assertThat(firstFilteredTimers.get(key), not(nullValue())); - FiredTimers firstFired = firstFilteredTimers.get(key); - assertThat(firstFired.getTimers(TimeDomain.EVENT_TIME), contains(earliestTimer)); - - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>emptyList()), - new Instant(50_000L)); - manager.refreshAll(); - Map, Map, FiredTimers>> secondTransformFiredTimers = - manager.extractFiredTimers(); - assertThat( - secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map, FiredTimers> secondFilteredTimers = - secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); - assertThat(secondFilteredTimers.get(key), not(nullValue())); - FiredTimers secondFired = secondFilteredTimers.get(key); - // Contains, in order, middleTimer and then lastTimer - assertThat(secondFired.getTimers(TimeDomain.EVENT_TIME), contains(middleTimer, lastTimer)); - } - - @Test - public void extractFiredTimersReturnsFiredProcessingTimeTimers() { - Map, Map, FiredTimers>> initialTimers = - manager.extractFiredTimers(); - // Watermarks haven't advanced - assertThat(initialTimers.entrySet(), emptyIterable()); - - // Advance WM of keyed past the first timer, but ahead of the second and third - CommittedBundle createdBundle = multiWindowedBundle(filtered); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.singleton(createdBundle)), - new Instant(1500L)); - - TimerData earliestTimer = - TimerData.of(StateNamespaces.global(), new Instant(999L), TimeDomain.PROCESSING_TIME); - TimerData middleTimer = - TimerData.of(StateNamespaces.global(), new Instant(5000L), TimeDomain.PROCESSING_TIME); - TimerData lastTimer = - TimerData.of(StateNamespaces.global(), new Instant(10000L), TimeDomain.PROCESSING_TIME); - StructuralKey key = StructuralKey.of(-12L, VarLongCoder.of()); - TimerUpdate update = - TimerUpdate.builder(key) - .setTimer(lastTimer) - .setTimer(earliestTimer) - .setTimer(middleTimer) - .build(); - - manager.updateWatermarks( - createdBundle, - update, - result(filtered.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(multiWindowedBundle(intsToFlatten))), - new Instant(1000L)); - manager.refreshAll(); - - Map, Map, FiredTimers>> firstTransformFiredTimers = - manager.extractFiredTimers(); - assertThat( - firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map, FiredTimers> firstFilteredTimers = - firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); - assertThat(firstFilteredTimers.get(key), not(nullValue())); - FiredTimers firstFired = firstFilteredTimers.get(key); - assertThat(firstFired.getTimers(TimeDomain.PROCESSING_TIME), contains(earliestTimer)); - - clock.set(new Instant(50_000L)); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>emptyList()), - new Instant(50_000L)); - manager.refreshAll(); - Map, Map, FiredTimers>> secondTransformFiredTimers = - manager.extractFiredTimers(); - assertThat( - secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map, FiredTimers> secondFilteredTimers = - secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); - assertThat(secondFilteredTimers.get(key), not(nullValue())); - FiredTimers secondFired = secondFilteredTimers.get(key); - // Contains, in order, middleTimer and then lastTimer - assertThat(secondFired.getTimers(TimeDomain.PROCESSING_TIME), contains(middleTimer, lastTimer)); - } - - @Test - public void extractFiredTimersReturnsFiredSynchronizedProcessingTimeTimers() { - Map, Map, FiredTimers>> initialTimers = - manager.extractFiredTimers(); - // Watermarks haven't advanced - assertThat(initialTimers.entrySet(), emptyIterable()); - - // Advance WM of keyed past the first timer, but ahead of the second and third - CommittedBundle createdBundle = multiWindowedBundle(filtered); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.singleton(createdBundle)), - new Instant(1500L)); - - TimerData earliestTimer = TimerData.of( - StateNamespaces.global(), new Instant(999L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - TimerData middleTimer = TimerData.of( - StateNamespaces.global(), new Instant(5000L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - TimerData lastTimer = TimerData.of( - StateNamespaces.global(), new Instant(10000L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - StructuralKey key = StructuralKey.of(new byte[] {2, -2, 22}, ByteArrayCoder.of()); - TimerUpdate update = - TimerUpdate.builder(key) - .setTimer(lastTimer) - .setTimer(earliestTimer) - .setTimer(middleTimer) - .build(); - - manager.updateWatermarks( - createdBundle, - update, - result(filtered.getProducingTransformInternal(), - createdBundle.withElements(Collections.>emptyList()), - Collections.>singleton(multiWindowedBundle(intsToFlatten))), - new Instant(1000L)); - manager.refreshAll(); - - Map, Map, FiredTimers>> firstTransformFiredTimers = - manager.extractFiredTimers(); - assertThat( - firstTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map, FiredTimers> firstFilteredTimers = - firstTransformFiredTimers.get(filtered.getProducingTransformInternal()); - assertThat(firstFilteredTimers.get(key), not(nullValue())); - FiredTimers firstFired = firstFilteredTimers.get(key); - assertThat( - firstFired.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), contains(earliestTimer)); - - clock.set(new Instant(50_000L)); - manager.updateWatermarks(null, - TimerUpdate.empty(), - result(createdInts.getProducingTransformInternal(), - null, - Collections.>emptyList()), - new Instant(50_000L)); - manager.refreshAll(); - Map, Map, FiredTimers>> secondTransformFiredTimers = - manager.extractFiredTimers(); - assertThat( - secondTransformFiredTimers.get(filtered.getProducingTransformInternal()), not(nullValue())); - Map, FiredTimers> secondFilteredTimers = - secondTransformFiredTimers.get(filtered.getProducingTransformInternal()); - assertThat(secondFilteredTimers.get(key), not(nullValue())); - FiredTimers secondFired = secondFilteredTimers.get(key); - // Contains, in order, middleTimer and then lastTimer - assertThat( - secondFired.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), - contains(middleTimer, lastTimer)); - } - - @Test - public void timerUpdateBuilderBuildAddsAllAddedTimers() { - TimerData set = TimerData.of(StateNamespaces.global(), new Instant(10L), TimeDomain.EVENT_TIME); - TimerData deleted = - TimerData.of(StateNamespaces.global(), new Instant(24L), TimeDomain.PROCESSING_TIME); - TimerData completedOne = TimerData.of( - StateNamespaces.global(), new Instant(1024L), TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - TimerData completedTwo = - TimerData.of(StateNamespaces.global(), new Instant(2048L), TimeDomain.EVENT_TIME); - - TimerUpdate update = - TimerUpdate.builder(StructuralKey.of("foo", StringUtf8Coder.of())) - .withCompletedTimers(ImmutableList.of(completedOne, completedTwo)) - .setTimer(set) - .deletedTimer(deleted) - .build(); - - assertThat(update.getCompletedTimers(), containsInAnyOrder(completedOne, completedTwo)); - assertThat(update.getSetTimers(), contains(set)); - assertThat(update.getDeletedTimers(), contains(deleted)); - } - - @Test - public void timerUpdateBuilderWithSetThenDeleteHasOnlyDeleted() { - TimerUpdateBuilder builder = TimerUpdate.builder(null); - TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); - - TimerUpdate built = builder.setTimer(timer).deletedTimer(timer).build(); - - assertThat(built.getSetTimers(), emptyIterable()); - assertThat(built.getDeletedTimers(), contains(timer)); - } - - @Test - public void timerUpdateBuilderWithDeleteThenSetHasOnlySet() { - TimerUpdateBuilder builder = TimerUpdate.builder(null); - TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); - - TimerUpdate built = builder.deletedTimer(timer).setTimer(timer).build(); - - assertThat(built.getSetTimers(), contains(timer)); - assertThat(built.getDeletedTimers(), emptyIterable()); - } - - @Test - public void timerUpdateBuilderWithSetAfterBuildNotAddedToBuilt() { - TimerUpdateBuilder builder = TimerUpdate.builder(null); - TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); - - TimerUpdate built = builder.build(); - builder.setTimer(timer); - assertThat(built.getSetTimers(), emptyIterable()); - builder.build(); - assertThat(built.getSetTimers(), emptyIterable()); - } - - @Test - public void timerUpdateBuilderWithDeleteAfterBuildNotAddedToBuilt() { - TimerUpdateBuilder builder = TimerUpdate.builder(null); - TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); - - TimerUpdate built = builder.build(); - builder.deletedTimer(timer); - assertThat(built.getDeletedTimers(), emptyIterable()); - builder.build(); - assertThat(built.getDeletedTimers(), emptyIterable()); - } - - @Test - public void timerUpdateBuilderWithCompletedAfterBuildNotAddedToBuilt() { - TimerUpdateBuilder builder = TimerUpdate.builder(null); - TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); - - TimerUpdate built = builder.build(); - builder.withCompletedTimers(ImmutableList.of(timer)); - assertThat(built.getCompletedTimers(), emptyIterable()); - builder.build(); - assertThat(built.getCompletedTimers(), emptyIterable()); - } - - @Test - public void timerUpdateWithCompletedTimersNotAddedToExisting() { - TimerUpdateBuilder builder = TimerUpdate.builder(null); - TimerData timer = TimerData.of(StateNamespaces.global(), Instant.now(), TimeDomain.EVENT_TIME); - - TimerUpdate built = builder.build(); - assertThat(built.getCompletedTimers(), emptyIterable()); - assertThat( - built.withCompletedTimers(ImmutableList.of(timer)).getCompletedTimers(), contains(timer)); - assertThat(built.getCompletedTimers(), emptyIterable()); - } - - private static Matcher earlierThan(final Instant laterInstant) { - return new BaseMatcher() { - @Override - public boolean matches(Object item) { - ReadableInstant instant = (ReadableInstant) item; - return instant.isBefore(laterInstant); - } - - @Override - public void describeTo(Description description) { - description.appendText("earlier than ").appendValue(laterInstant); - } - }; - } - - private static Matcher laterThan(final Instant shouldBeEarlier) { - return new BaseMatcher() { - @Override - public boolean matches(Object item) { - ReadableInstant instant = (ReadableInstant) item; - return instant.isAfter(shouldBeEarlier); - } - @Override - public void describeTo(Description description) { - description.appendText("later than ").appendValue(shouldBeEarlier); - } - }; - } - - @SafeVarargs - private final CommittedBundle timestampedBundle( - PCollection pc, TimestampedValue... values) { - UncommittedBundle bundle = bundleFactory.createRootBundle(pc); - for (TimestampedValue value : values) { - bundle.add( - WindowedValue.timestampedValueInGlobalWindow(value.getValue(), value.getTimestamp())); - } - return bundle.commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - } - - @SafeVarargs - private final CommittedBundle multiWindowedBundle(PCollection pc, T... values) { - UncommittedBundle bundle = bundleFactory.createRootBundle(pc); - Collection windows = - ImmutableList.of( - GlobalWindow.INSTANCE, - new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(0))); - for (T value : values) { - bundle.add( - WindowedValue.of(value, BoundedWindow.TIMESTAMP_MIN_VALUE, windows, PaneInfo.NO_FIRING)); - } - return bundle.commit(BoundedWindow.TIMESTAMP_MAX_VALUE); - } - - private CommittedResult result( - AppliedPTransform transform, - @Nullable CommittedBundle unprocessedBundle, - Iterable> bundles) { - return CommittedResult.create( - StepTransformResult.withoutHold(transform).build(), - unprocessedBundle, - bundles, - Iterables.isEmpty(bundles) - ? EnumSet.noneOf(OutputType.class) - : EnumSet.of(OutputType.BUNDLE)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java deleted file mode 100644 index 4cc5a37aa7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactoryTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; - -/** - * Tests for {@link InProcessBundleFactory}. - */ -@RunWith(JUnit4.class) -public class InProcessBundleFactoryTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - private InProcessBundleFactory bundleFactory = InProcessBundleFactory.create(); - - private PCollection created; - private PCollection> downstream; - - @Before - public void setup() { - TestPipeline p = TestPipeline.create(); - created = p.apply(Create.of(1, 2, 3)); - downstream = created.apply(WithKeys.of("foo")); - } - - @Test - public void createRootBundleShouldCreateWithEmptyKey() { - PCollection pcollection = TestPipeline.create().apply(Create.of(1)); - - UncommittedBundle inFlightBundle = bundleFactory.createRootBundle(pcollection); - - CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - - assertThat(bundle.getKey(), - Matchers.>equalTo(StructuralKey.of(null, VoidCoder.of()))); - } - - private void createKeyedBundle(Coder coder, T key) throws Exception { - PCollection pcollection = TestPipeline.create().apply(Create.of(1)); - StructuralKey skey = StructuralKey.of(key, coder); - - UncommittedBundle inFlightBundle = - bundleFactory.createKeyedBundle(null, skey, pcollection); - - CommittedBundle bundle = inFlightBundle.commit(Instant.now()); - assertThat(bundle.getKey(), equalTo(skey)); - } - - @Test - public void keyedWithNullKeyShouldCreateKeyedBundle() throws Exception { - createKeyedBundle(VoidCoder.of(), null); - } - - @Test - public void keyedWithKeyShouldCreateKeyedBundle() throws Exception { - createKeyedBundle(StringUtf8Coder.of(), "foo"); - createKeyedBundle(VarIntCoder.of(), 1234); - createKeyedBundle(ByteArrayCoder.of(), new byte[] {0, 2, 4, 99}); - } - - private CommittedBundle - afterCommitGetElementsShouldHaveAddedElements(Iterable> elems) { - PCollection pcollection = TestPipeline.create().apply(Create.of()); - - UncommittedBundle bundle = bundleFactory.createRootBundle(pcollection); - Collection>> expectations = new ArrayList<>(); - for (WindowedValue elem : elems) { - bundle.add(elem); - expectations.add(equalTo(elem)); - } - Matcher>> containsMatcher = - Matchers.>containsInAnyOrder(expectations); - CommittedBundle committed = bundle.commit(Instant.now()); - assertThat(committed.getElements(), containsMatcher); - - return committed; - } - - @Test - public void getElementsBeforeAddShouldReturnEmptyIterable() { - afterCommitGetElementsShouldHaveAddedElements(Collections.>emptyList()); - } - - @Test - public void getElementsAfterAddShouldReturnAddedElements() { - WindowedValue firstValue = WindowedValue.valueInGlobalWindow(1); - WindowedValue secondValue = - WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1000L)); - - afterCommitGetElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); - } - - @SuppressWarnings("unchecked") - @Test - public void withElementsShouldReturnIndependentBundle() { - WindowedValue firstValue = WindowedValue.valueInGlobalWindow(1); - WindowedValue secondValue = - WindowedValue.timestampedValueInGlobalWindow(2, new Instant(1000L)); - - CommittedBundle committed = - afterCommitGetElementsShouldHaveAddedElements(ImmutableList.of(firstValue, secondValue)); - - WindowedValue firstReplacement = - WindowedValue.of( - 9, - new Instant(2048L), - new IntervalWindow(new Instant(2044L), Instant.now()), - PaneInfo.NO_FIRING); - WindowedValue secondReplacement = - WindowedValue.timestampedValueInGlobalWindow(-1, Instant.now()); - CommittedBundle withed = - committed.withElements(ImmutableList.of(firstReplacement, secondReplacement)); - - assertThat(withed.getElements(), containsInAnyOrder(firstReplacement, secondReplacement)); - assertThat(committed.getElements(), containsInAnyOrder(firstValue, secondValue)); - assertThat(withed.getKey(), Matchers.>equalTo(committed.getKey())); - assertThat(withed.getPCollection(), equalTo(committed.getPCollection())); - assertThat( - withed.getSynchronizedProcessingOutputWatermark(), - equalTo(committed.getSynchronizedProcessingOutputWatermark())); - } - - @Test - public void addAfterCommitShouldThrowException() { - PCollection pcollection = TestPipeline.create().apply(Create.of()); - - UncommittedBundle bundle = bundleFactory.createRootBundle(pcollection); - bundle.add(WindowedValue.valueInGlobalWindow(1)); - CommittedBundle firstCommit = bundle.commit(Instant.now()); - assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("3"); - thrown.expectMessage("committed"); - - bundle.add(WindowedValue.valueInGlobalWindow(3)); - } - - @Test - public void commitAfterCommitShouldThrowException() { - PCollection pcollection = TestPipeline.create().apply(Create.of()); - - UncommittedBundle bundle = bundleFactory.createRootBundle(pcollection); - bundle.add(WindowedValue.valueInGlobalWindow(1)); - CommittedBundle firstCommit = bundle.commit(Instant.now()); - assertThat(firstCommit.getElements(), containsInAnyOrder(WindowedValue.valueInGlobalWindow(1))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("committed"); - - bundle.commit(Instant.now()); - } - - @Test - public void createBundleUnkeyedResultUnkeyed() { - CommittedBundle> newBundle = - bundleFactory - .createBundle(bundleFactory.createRootBundle(created).commit(Instant.now()), downstream) - .commit(Instant.now()); - } - - @Test - public void createBundleKeyedResultPropagatesKey() { - CommittedBundle> newBundle = - bundleFactory.createBundle( - bundleFactory.createKeyedBundle( - null, - StructuralKey.of("foo", StringUtf8Coder.of()), - created).commit(Instant.now()), - downstream).commit(Instant.now()); - assertThat(newBundle.getKey().getKey(), Matchers.equalTo("foo")); - } - - @Test - public void createKeyedBundleKeyed() { - CommittedBundle> keyedBundle = bundleFactory.createKeyedBundle( - bundleFactory.createRootBundle(created).commit(Instant.now()), - StructuralKey.of("foo", StringUtf8Coder.of()), - downstream).commit(Instant.now()); - assertThat(keyedBundle.getKey().getKey(), Matchers.equalTo("foo")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java deleted file mode 100644 index 543ab2968a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessCreateTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.NullableCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessCreate.InMemorySource; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * Tests for {@link InProcessCreate}. - */ -@RunWith(JUnit4.class) -public class InProcessCreateTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - @Category(RunnableOnService.class) - public void testConvertsCreate() { - TestPipeline p = TestPipeline.create(); - Create.Values og = Create.of(1, 2, 3); - - InProcessCreate converted = InProcessCreate.from(og); - - DataflowAssert.that(p.apply(converted)).containsInAnyOrder(2, 1, 3); - } - - @Test - @Category(RunnableOnService.class) - public void testConvertsCreateWithNullElements() { - Create.Values og = - Create.of("foo", null, "spam", "ham", null, "eggs") - .withCoder(NullableCoder.of(StringUtf8Coder.of())); - - InProcessCreate converted = InProcessCreate.from(og); - TestPipeline p = TestPipeline.create(); - - DataflowAssert.that(p.apply(converted)) - .containsInAnyOrder(null, "foo", null, "spam", "ham", "eggs"); - } - - static class Record implements Serializable {} - - static class Record2 extends Record {} - - @Test - public void testThrowsIllegalArgumentWhenCannotInferCoder() { - Create.Values og = Create.of(new Record(), new Record2()); - InProcessCreate converted = InProcessCreate.from(og); - - Pipeline p = TestPipeline.create(); - - // Create won't infer a default coder in this case. - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(Matchers.containsString("Unable to infer a coder")); - - PCollection c = p.apply(converted); - p.run(); - - fail("Unexpectedly Inferred Coder " + c.getCoder()); - } - - /** - * An unserializable class to demonstrate encoding of elements. - */ - private static class UnserializableRecord { - private final String myString; - - private UnserializableRecord(String myString) { - this.myString = myString; - } - - @Override - public int hashCode() { - return myString.hashCode(); - } - - @Override - public boolean equals(Object o) { - return myString.equals(((UnserializableRecord) o).myString); - } - - static class UnserializableRecordCoder extends AtomicCoder { - private final Coder stringCoder = StringUtf8Coder.of(); - - @Override - public void encode( - UnserializableRecord value, - OutputStream outStream, - com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - stringCoder.encode(value.myString, outStream, context.nested()); - } - - @Override - public UnserializableRecord decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - return new UnserializableRecord(stringCoder.decode(inStream, context.nested())); - } - } - } - - @Test - @Category(RunnableOnService.class) - public void testConvertsUnserializableElements() throws Exception { - List elements = - ImmutableList.of( - new UnserializableRecord("foo"), - new UnserializableRecord("bar"), - new UnserializableRecord("baz")); - InProcessCreate create = - InProcessCreate.from( - Create.of(elements).withCoder(new UnserializableRecord.UnserializableRecordCoder())); - - TestPipeline p = TestPipeline.create(); - DataflowAssert.that(p.apply(create)) - .containsInAnyOrder( - new UnserializableRecord("foo"), - new UnserializableRecord("bar"), - new UnserializableRecord("baz")); - p.run(); - } - - @Test - public void testSerializableOnUnserializableElements() throws Exception { - List elements = - ImmutableList.of( - new UnserializableRecord("foo"), - new UnserializableRecord("bar"), - new UnserializableRecord("baz")); - InMemorySource source = - InMemorySource.fromIterable(elements, new UnserializableRecord.UnserializableRecordCoder()); - SerializableUtils.ensureSerializable(source); - } - - @Test - public void testSplitIntoBundles() throws Exception { - InProcessCreate.InMemorySource source = - InMemorySource.fromIterable( - ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), BigEndianIntegerCoder.of()); - PipelineOptions options = PipelineOptionsFactory.create(); - List> splitSources = source.splitIntoBundles(12, options); - assertThat(splitSources, hasSize(3)); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splitSources, options); - } - - @Test - public void testDoesNotProduceSortedKeys() throws Exception { - InProcessCreate.InMemorySource source = - InMemorySource.fromIterable(ImmutableList.of("spam", "ham", "eggs"), StringUtf8Coder.of()); - assertThat(source.producesSortedKeys(PipelineOptionsFactory.create()), is(false)); - } - - @Test - public void testGetDefaultOutputCoderReturnsConstructorCoder() throws Exception { - Coder coder = VarIntCoder.of(); - InProcessCreate.InMemorySource source = - InMemorySource.fromIterable(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8), coder); - - Coder defaultCoder = source.getDefaultOutputCoder(); - assertThat(defaultCoder, equalTo(coder)); - } - - @Test - public void testSplitAtFraction() throws Exception { - List elements = new ArrayList<>(); - Random random = new Random(); - for (int i = 0; i < 25; i++) { - elements.add(random.nextInt()); - } - InProcessCreate.InMemorySource source = - InMemorySource.fromIterable(elements, VarIntCoder.of()); - - SourceTestUtils.assertSplitAtFractionExhaustive(source, PipelineOptionsFactory.create()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java deleted file mode 100644 index 21e45ffec5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessEvaluationContextTest.java +++ /dev/null @@ -1,543 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.io.CountingInput; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.FiredTimers; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.CopyOnAccessInMemoryStateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link InProcessEvaluationContext}. - */ -@RunWith(JUnit4.class) -public class InProcessEvaluationContextTest { - private TestPipeline p; - private InProcessEvaluationContext context; - - private PCollection created; - private PCollection> downstream; - private PCollectionView> view; - private PCollection unbounded; - private Collection> rootTransforms; - private Map>> valueToConsumers; - - private BundleFactory bundleFactory; - - @Before - public void setup() { - InProcessPipelineRunner runner = - InProcessPipelineRunner.fromOptions(PipelineOptionsFactory.create()); - - p = TestPipeline.create(); - - created = p.apply(Create.of(1, 2, 3)); - downstream = created.apply(WithKeys.of("foo")); - view = created.apply(View.asIterable()); - unbounded = p.apply(CountingInput.unbounded()); - - ConsumerTrackingPipelineVisitor cVis = new ConsumerTrackingPipelineVisitor(); - p.traverseTopologically(cVis); - rootTransforms = cVis.getRootTransforms(); - valueToConsumers = cVis.getValueToConsumers(); - - bundleFactory = InProcessBundleFactory.create(); - - context = - InProcessEvaluationContext.create( - runner.getPipelineOptions(), - NanosOffsetClock.create(), - InProcessBundleFactory.create(), - rootTransforms, - valueToConsumers, - cVis.getStepNames(), - cVis.getViews()); - } - - @Test - public void writeToViewWriterThenReadReads() { - PCollectionViewWriter> viewWriter = - context.createPCollectionViewWriter( - PCollection.>createPrimitiveOutputInternal( - p, WindowingStrategy.globalDefault(), IsBounded.BOUNDED), - view); - BoundedWindow window = new TestBoundedWindow(new Instant(1024L)); - BoundedWindow second = new TestBoundedWindow(new Instant(899999L)); - WindowedValue firstValue = - WindowedValue.of(1, new Instant(1222), window, PaneInfo.ON_TIME_AND_ONLY_FIRING); - WindowedValue secondValue = - WindowedValue.of( - 2, new Instant(8766L), second, PaneInfo.createPane(true, false, Timing.ON_TIME, 0, 0)); - Iterable> values = ImmutableList.of(firstValue, secondValue); - viewWriter.add(values); - - SideInputReader reader = - context.createSideInputReader(ImmutableList.>of(view)); - assertThat(reader.get(view, window), containsInAnyOrder(1)); - assertThat(reader.get(view, second), containsInAnyOrder(2)); - - WindowedValue overrittenSecondValue = - WindowedValue.of( - 4444, new Instant(8677L), second, PaneInfo.createPane(false, true, Timing.LATE, 1, 1)); - viewWriter.add(Collections.singleton(overrittenSecondValue)); - assertThat(reader.get(view, second), containsInAnyOrder(2)); - // The cached value is served in the earlier reader - reader = context.createSideInputReader(ImmutableList.>of(view)); - assertThat(reader.get(view, second), containsInAnyOrder(4444)); - } - - @Test - public void getExecutionContextSameStepSameKeyState() { - InProcessExecutionContext fooContext = - context.getExecutionContext(created.getProducingTransformInternal(), - StructuralKey.of("foo", StringUtf8Coder.of())); - - StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); - - InProcessStepContext stepContext = fooContext.getOrCreateStepContext("s1", "s1", null); - stepContext.stateInternals().state(StateNamespaces.global(), intBag).add(1); - - context.handleResult(InProcessBundleFactory.create() - .createKeyedBundle(null, StructuralKey.of("foo", StringUtf8Coder.of()), created) - .commit(Instant.now()), - ImmutableList.of(), - StepTransformResult.withoutHold(created.getProducingTransformInternal()) - .withState(stepContext.commitState()) - .build()); - - InProcessExecutionContext secondFooContext = - context.getExecutionContext(created.getProducingTransformInternal(), - StructuralKey.of("foo", StringUtf8Coder.of())); - assertThat( - secondFooContext - .getOrCreateStepContext("s1", "s1", null) - .stateInternals() - .state(StateNamespaces.global(), intBag) - .read(), - contains(1)); - } - - - @Test - public void getExecutionContextDifferentKeysIndependentState() { - InProcessExecutionContext fooContext = - context.getExecutionContext(created.getProducingTransformInternal(), - StructuralKey.of("foo", StringUtf8Coder.of())); - - StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); - - fooContext - .getOrCreateStepContext("s1", "s1", null) - .stateInternals() - .state(StateNamespaces.global(), intBag) - .add(1); - - InProcessExecutionContext barContext = - context.getExecutionContext(created.getProducingTransformInternal(), - StructuralKey.of("bar", StringUtf8Coder.of())); - assertThat(barContext, not(equalTo(fooContext))); - assertThat( - barContext - .getOrCreateStepContext("s1", "s1", null) - .stateInternals() - .state(StateNamespaces.global(), intBag) - .read(), - emptyIterable()); - } - - @Test - public void getExecutionContextDifferentStepsIndependentState() { - StructuralKey myKey = StructuralKey.of("foo", StringUtf8Coder.of()); - InProcessExecutionContext fooContext = - context.getExecutionContext(created.getProducingTransformInternal(), myKey); - - StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); - - fooContext - .getOrCreateStepContext("s1", "s1", null) - .stateInternals() - .state(StateNamespaces.global(), intBag) - .add(1); - - InProcessExecutionContext barContext = - context.getExecutionContext(downstream.getProducingTransformInternal(), myKey); - assertThat( - barContext - .getOrCreateStepContext("s1", "s1", null) - .stateInternals() - .state(StateNamespaces.global(), intBag) - .read(), - emptyIterable()); - } - - @Test - public void handleResultMergesCounters() { - CounterSet counters = context.createCounterSet(); - Counter myCounter = Counter.longs("foo", AggregationKind.SUM); - counters.addCounter(myCounter); - - myCounter.addValue(4L); - InProcessTransformResult result = - StepTransformResult.withoutHold(created.getProducingTransformInternal()) - .withCounters(counters) - .build(); - context.handleResult(null, ImmutableList.of(), result); - assertThat((Long) context.getCounters().getExistingCounter("foo").getAggregate(), equalTo(4L)); - - CounterSet againCounters = context.createCounterSet(); - Counter myLongCounterAgain = Counter.longs("foo", AggregationKind.SUM); - againCounters.add(myLongCounterAgain); - myLongCounterAgain.addValue(8L); - - InProcessTransformResult secondResult = - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()) - .withCounters(againCounters) - .build(); - context.handleResult( - context.createRootBundle(created).commit(Instant.now()), - ImmutableList.of(), - secondResult); - assertThat((Long) context.getCounters().getExistingCounter("foo").getAggregate(), equalTo(12L)); - } - - @Test - public void handleResultStoresState() { - StructuralKey myKey = StructuralKey.of("foo".getBytes(), ByteArrayCoder.of()); - InProcessExecutionContext fooContext = - context.getExecutionContext(downstream.getProducingTransformInternal(), myKey); - - StateTag> intBag = StateTags.bag("myBag", VarIntCoder.of()); - - CopyOnAccessInMemoryStateInternals state = - fooContext.getOrCreateStepContext("s1", "s1", null).stateInternals(); - BagState bag = state.state(StateNamespaces.global(), intBag); - bag.add(1); - bag.add(2); - bag.add(4); - - InProcessTransformResult stateResult = - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()) - .withState(state) - .build(); - - context.handleResult( - context.createKeyedBundle(null, myKey, created).commit(Instant.now()), - ImmutableList.of(), - stateResult); - - InProcessExecutionContext afterResultContext = - context.getExecutionContext(downstream.getProducingTransformInternal(), myKey); - - CopyOnAccessInMemoryStateInternals afterResultState = - afterResultContext.getOrCreateStepContext("s1", "s1", null).stateInternals(); - assertThat(afterResultState.state(StateNamespaces.global(), intBag).read(), contains(1, 2, 4)); - } - - @Test - public void callAfterOutputMustHaveBeenProducedAfterEndOfWatermarkCallsback() throws Exception { - final CountDownLatch callLatch = new CountDownLatch(1); - Runnable callback = - new Runnable() { - @Override - public void run() { - callLatch.countDown(); - } - }; - - // Should call back after the end of the global window - context.scheduleAfterOutputWouldBeProduced( - downstream, GlobalWindow.INSTANCE, WindowingStrategy.globalDefault(), callback); - - InProcessTransformResult result = - StepTransformResult.withHold(created.getProducingTransformInternal(), new Instant(0)) - .build(); - - context.handleResult(null, ImmutableList.of(), result); - // Difficult to demonstrate that we took no action in a multithreaded world; poll for a bit - // will likely be flaky if this logic is broken - assertThat(callLatch.await(500L, TimeUnit.MILLISECONDS), is(false)); - - InProcessTransformResult finishedResult = - StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); - context.handleResult(null, ImmutableList.of(), finishedResult); - context.forceRefresh(); - // Obtain the value via blocking call - assertThat(callLatch.await(1, TimeUnit.SECONDS), is(true)); - } - - @Test - public void callAfterOutputMustHaveBeenProducedAlreadyAfterCallsImmediately() throws Exception { - InProcessTransformResult finishedResult = - StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); - context.handleResult(null, ImmutableList.of(), finishedResult); - - final CountDownLatch callLatch = new CountDownLatch(1); - context.extractFiredTimers(); - Runnable callback = - new Runnable() { - @Override - public void run() { - callLatch.countDown(); - } - }; - context.scheduleAfterOutputWouldBeProduced( - downstream, GlobalWindow.INSTANCE, WindowingStrategy.globalDefault(), callback); - assertThat(callLatch.await(1, TimeUnit.SECONDS), is(true)); - } - - @Test - public void extractFiredTimersExtractsTimers() { - InProcessTransformResult holdResult = - StepTransformResult.withHold(created.getProducingTransformInternal(), new Instant(0)) - .build(); - context.handleResult(null, ImmutableList.of(), holdResult); - - StructuralKey key = StructuralKey.of("foo".length(), VarIntCoder.of()); - TimerData toFire = - TimerData.of(StateNamespaces.global(), new Instant(100L), TimeDomain.EVENT_TIME); - InProcessTransformResult timerResult = - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()) - .withState(CopyOnAccessInMemoryStateInternals.withUnderlying(key, null)) - .withTimerUpdate(TimerUpdate.builder(key).setTimer(toFire).build()) - .build(); - - // haven't added any timers, must be empty - assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); - context.handleResult( - context.createKeyedBundle(null, key, created).commit(Instant.now()), - ImmutableList.of(), - timerResult); - - // timer hasn't fired - assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); - - InProcessTransformResult advanceResult = - StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); - // Should cause the downstream timer to fire - context.handleResult(null, ImmutableList.of(), advanceResult); - - Map, Map, FiredTimers>> fired = - context.extractFiredTimers(); - assertThat( - fired, - Matchers.>hasKey(downstream.getProducingTransformInternal())); - Map, FiredTimers> downstreamFired = - fired.get(downstream.getProducingTransformInternal()); - assertThat(downstreamFired, Matchers.hasKey(key)); - - FiredTimers firedForKey = downstreamFired.get(key); - assertThat(firedForKey.getTimers(TimeDomain.PROCESSING_TIME), emptyIterable()); - assertThat(firedForKey.getTimers(TimeDomain.SYNCHRONIZED_PROCESSING_TIME), emptyIterable()); - assertThat(firedForKey.getTimers(TimeDomain.EVENT_TIME), contains(toFire)); - - // Don't reextract timers - assertThat(context.extractFiredTimers().entrySet(), emptyIterable()); - } - - @Test - public void createBundleKeyedResultPropagatesKey() { - StructuralKey key = StructuralKey.of("foo", StringUtf8Coder.of()); - CommittedBundle> newBundle = - context - .createBundle( - bundleFactory.createKeyedBundle( - null, key, - created).commit(Instant.now()), - downstream).commit(Instant.now()); - assertThat(newBundle.getKey(), Matchers.>equalTo(key)); - } - - @Test - public void createKeyedBundleKeyed() { - StructuralKey key = StructuralKey.of("foo", StringUtf8Coder.of()); - CommittedBundle> keyedBundle = - context.createKeyedBundle( - bundleFactory.createRootBundle(created).commit(Instant.now()), - key, - downstream).commit(Instant.now()); - assertThat(keyedBundle.getKey(), - Matchers.>equalTo(key)); - } - - @Test - public void isDoneWithUnboundedPCollectionAndShutdown() { - context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(true); - assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(false)); - - context.handleResult( - null, - ImmutableList.of(), - StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); - context.extractFiredTimers(); - assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(true)); - } - - @Test - public void isDoneWithUnboundedPCollectionAndNotShutdown() { - context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(false); - assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(false)); - - context.handleResult( - null, - ImmutableList.of(), - StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); - assertThat(context.isDone(unbounded.getProducingTransformInternal()), is(false)); - } - - @Test - public void isDoneWithOnlyBoundedPCollections() { - context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(false); - assertThat(context.isDone(created.getProducingTransformInternal()), is(false)); - - context.handleResult( - null, - ImmutableList.of(), - StepTransformResult.withoutHold(created.getProducingTransformInternal()).build()); - context.extractFiredTimers(); - assertThat(context.isDone(created.getProducingTransformInternal()), is(true)); - } - - @Test - public void isDoneWithPartiallyDone() { - context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(true); - assertThat(context.isDone(), is(false)); - - UncommittedBundle rootBundle = context.createRootBundle(created); - rootBundle.add(WindowedValue.valueInGlobalWindow(1)); - CommittedResult handleResult = - context.handleResult( - null, - ImmutableList.of(), - StepTransformResult.withoutHold(created.getProducingTransformInternal()) - .addOutput(rootBundle) - .build()); - @SuppressWarnings("unchecked") - CommittedBundle committedBundle = - (CommittedBundle) Iterables.getOnlyElement(handleResult.getOutputs()); - context.handleResult( - null, - ImmutableList.of(), - StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); - assertThat(context.isDone(), is(false)); - - for (AppliedPTransform consumers : valueToConsumers.get(created)) { - context.handleResult( - committedBundle, - ImmutableList.of(), - StepTransformResult.withoutHold(consumers).build()); - } - context.extractFiredTimers(); - assertThat(context.isDone(), is(true)); - } - - @Test - public void isDoneWithUnboundedAndNotShutdown() { - context.getPipelineOptions().setShutdownUnboundedProducersWithMaxWatermark(false); - assertThat(context.isDone(), is(false)); - - context.handleResult( - null, - ImmutableList.of(), - StepTransformResult.withoutHold(created.getProducingTransformInternal()).build()); - context.handleResult( - null, - ImmutableList.of(), - StepTransformResult.withoutHold(unbounded.getProducingTransformInternal()).build()); - context.handleResult( - context.createRootBundle(created).commit(Instant.now()), - ImmutableList.of(), - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build()); - context.extractFiredTimers(); - assertThat(context.isDone(), is(false)); - - context.handleResult( - context.createRootBundle(created).commit(Instant.now()), - ImmutableList.of(), - StepTransformResult.withoutHold(view.getProducingTransformInternal()).build()); - context.extractFiredTimers(); - assertThat(context.isDone(), is(false)); - } - - private static class TestBoundedWindow extends BoundedWindow { - private final Instant ts; - - public TestBoundedWindow(Instant ts) { - this.ts = ts; - } - - @Override - public Instant maxTimestamp() { - return ts; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java deleted file mode 100644 index 18898f0403..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRegistrarTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.options.PipelineOptionsRegistrar; -import com.google.cloud.dataflow.sdk.runners.PipelineRunnerRegistrar; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessRegistrar.InProcessRunner; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ServiceLoader; - -/** Tests for {@link InProcessRunner}. */ -@RunWith(JUnit4.class) -public class InProcessPipelineRegistrarTest { - @Test - public void testCorrectOptionsAreReturned() { - assertEquals( - ImmutableList.of(InProcessPipelineOptions.class), - new InProcessRegistrar.InProcessOptions().getPipelineOptions()); - } - - @Test - public void testCorrectRunnersAreReturned() { - assertEquals( - ImmutableList.of(InProcessPipelineRunner.class), - new InProcessRegistrar.InProcessRunner().getPipelineRunners()); - } - - @Test - public void testServiceLoaderForOptions() { - for (PipelineOptionsRegistrar registrar : - Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class).iterator())) { - if (registrar instanceof InProcessRegistrar.InProcessOptions) { - return; - } - } - fail("Expected to find " + InProcessRegistrar.InProcessOptions.class); - } - - @Test - public void testServiceLoaderForRunner() { - for (PipelineRunnerRegistrar registrar : - Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class).iterator())) { - if (registrar instanceof InProcessRegistrar.InProcessRunner) { - return; - } - } - fail("Expected to find " + InProcessRegistrar.InProcessRunner.class); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java deleted file mode 100644 index 7fcdee9028..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessPipelineRunnerTest.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.InProcessPipelineResult; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableMap; - -import com.fasterxml.jackson.annotation.JsonValue; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Tests for basic {@link InProcessPipelineRunner} functionality. - */ -@RunWith(JUnit4.class) -public class InProcessPipelineRunnerTest implements Serializable { - @Rule public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void wordCountShouldSucceed() throws Throwable { - Pipeline p = getPipeline(); - - PCollection> counts = - p.apply(Create.of("foo", "bar", "foo", "baz", "bar", "foo")) - .apply(MapElements.via(new SimpleFunction() { - @Override - public String apply(String input) { - return input; - } - })) - .apply(Count.perElement()); - PCollection countStrs = - counts.apply(MapElements.via(new SimpleFunction, String>() { - @Override - public String apply(KV input) { - String str = String.format("%s: %s", input.getKey(), input.getValue()); - return str; - } - })); - - DataflowAssert.that(countStrs).containsInAnyOrder("baz: 1", "bar: 2", "foo: 3"); - - InProcessPipelineResult result = ((InProcessPipelineResult) p.run()); - result.awaitCompletion(); - } - - private static AtomicInteger changed; - @Test - public void reusePipelineSucceeds() throws Throwable { - Pipeline p = getPipeline(); - - changed = new AtomicInteger(0); - - PCollection> counts = - p.apply(Create.of("foo", "bar", "foo", "baz", "bar", "foo")) - .apply(MapElements.via(new SimpleFunction() { - @Override - public String apply(String input) { - return input; - } - })) - .apply(Count.perElement()); - PCollection countStrs = - counts.apply(MapElements.via(new SimpleFunction, String>() { - @Override - public String apply(KV input) { - String str = String.format("%s: %s", input.getKey(), input.getValue()); - return str; - } - })); - - counts.apply(ParDo.of(new DoFn, Void>() { - @Override - public void processElement(ProcessContext c) throws Exception { - changed.getAndIncrement(); - } - })); - - DataflowAssert.that(countStrs).containsInAnyOrder("baz: 1", "bar: 2", "foo: 3"); - - InProcessPipelineResult result = ((InProcessPipelineResult) p.run()); - result.awaitCompletion(); - - InProcessPipelineResult otherResult = ((InProcessPipelineResult) p.run()); - otherResult.awaitCompletion(); - - assertThat("Each element should have been processed twice", changed.get(), equalTo(6)); - } - - @Test - public void byteArrayCountShouldSucceed() { - Pipeline p = getPipeline(); - - SerializableFunction getBytes = new SerializableFunction() { - @Override - public byte[] apply(Integer input) { - try { - return CoderUtils.encodeToByteArray(VarIntCoder.of(), input); - } catch (CoderException e) { - fail("Unexpected Coder Exception " + e); - throw new AssertionError("Unreachable"); - } - } - }; - TypeDescriptor td = new TypeDescriptor() { - }; - PCollection foos = - p.apply(Create.of(1, 1, 1, 2, 2, 3)).apply(MapElements.via(getBytes).withOutputType(td)); - PCollection msync = - p.apply(Create.of(1, -2, -8, -16)).apply(MapElements.via(getBytes).withOutputType(td)); - PCollection bytes = - PCollectionList.of(foos).and(msync).apply(Flatten.pCollections()); - PCollection> counts = bytes.apply(Count.perElement()); - PCollection> countsBackToString = - counts.apply(MapElements.via(new SimpleFunction, KV>() { - @Override - public KV apply(KV input) { - try { - return KV.of(CoderUtils.decodeFromByteArray(VarIntCoder.of(), input.getKey()), - input.getValue()); - } catch (CoderException e) { - fail("Unexpected Coder Exception " + e); - throw new AssertionError("Unreachable"); - } - } - })); - - Map expected = ImmutableMap.builder().put(1, 4L) - .put(2, 2L) - .put(3, 1L) - .put(-2, 1L) - .put(-8, 1L) - .put(-16, 1L) - .build(); - DataflowAssert.thatMap(countsBackToString).isEqualTo(expected); - } - - @Test - public void transformDisplayDataExceptionShouldFail() { - DoFn brokenDoFn = new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception {} - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - throw new RuntimeException("oh noes!"); - } - }; - - Pipeline p = getPipeline(); - p - .apply(Create.of(1, 2, 3)) - .apply(ParDo.of(brokenDoFn)); - - thrown.expectMessage(brokenDoFn.getClass().getName()); - thrown.expectCause(ThrowableMessageMatcher.hasMessage(is("oh noes!"))); - p.run(); - } - - @Test - public void pipelineOptionsDisplayDataExceptionShouldFail() { - Object brokenValueType = new Object() { - @JsonValue - public int getValue () { - return 42; - } - - @Override - public String toString() { - throw new RuntimeException("oh noes!!"); - } - }; - - Pipeline p = getPipeline(); - p.getOptions().as(ObjectPipelineOptions.class).setValue(brokenValueType); - - p.apply(Create.of(1, 2, 3)); - - thrown.expectMessage(PipelineOptions.class.getName()); - thrown.expectCause(ThrowableMessageMatcher.hasMessage(is("oh noes!!"))); - p.run(); - } - - /** {@link PipelineOptions} to inject broken object type. */ - public interface ObjectPipelineOptions extends PipelineOptions { - Object getValue(); - void setValue(Object value); - } - - - private Pipeline getPipeline() { - PipelineOptions opts = PipelineOptionsFactory.create(); - opts.setRunner(InProcessPipelineRunner.class); - - Pipeline p = Pipeline.create(opts); - return p; - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java deleted file mode 100644 index a46747622a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessSideInputContainerTest.java +++ /dev/null @@ -1,517 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.doAnswer; - -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Mean; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.PCollectionViews; -import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; -import com.google.cloud.dataflow.sdk.util.SideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link InProcessSideInputContainer}. - */ -@RunWith(JUnit4.class) -public class InProcessSideInputContainerTest { - private static final BoundedWindow FIRST_WINDOW = - new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(789541L); - } - - @Override - public String toString() { - return "firstWindow"; - } - }; - - private static final BoundedWindow SECOND_WINDOW = - new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(14564786L); - } - - @Override - public String toString() { - return "secondWindow"; - } - }; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Mock - private InProcessEvaluationContext context; - - private TestPipeline pipeline; - - private InProcessSideInputContainer container; - - private PCollectionView> mapView; - private PCollectionView singletonView; - - // Not present in container. - private PCollectionView> iterableView; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - pipeline = TestPipeline.create(); - - PCollection create = - pipeline.apply("forBaseCollection", Create.of(1, 2, 3, 4)); - - mapView = - create.apply("forKeyTypes", WithKeys.of("foo")) - .apply("asMapView", View.asMap()); - - singletonView = create.apply("forCombinedTypes", Mean.globally().asSingletonView()); - iterableView = create.apply("asIterableView", View.asIterable()); - - container = InProcessSideInputContainer.create( - context, ImmutableList.of(iterableView, mapView, singletonView)); - } - - @Test - public void getAfterWriteReturnsPaneInWindow() throws Exception { - WindowedValue> one = - WindowedValue.of( - KV.of("one", 1), new Instant(1L), FIRST_WINDOW, PaneInfo.ON_TIME_AND_ONLY_FIRING); - WindowedValue> two = - WindowedValue.of( - KV.of("two", 2), new Instant(20L), FIRST_WINDOW, PaneInfo.ON_TIME_AND_ONLY_FIRING); - container.write(mapView, ImmutableList.>of(one, two)); - - Map viewContents = - container - .createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, FIRST_WINDOW); - assertThat(viewContents, hasEntry("one", 1)); - assertThat(viewContents, hasEntry("two", 2)); - assertThat(viewContents.size(), is(2)); - } - - @Test - public void getReturnsLatestPaneInWindow() throws Exception { - WindowedValue> one = - WindowedValue.of( - KV.of("one", 1), - new Instant(1L), - SECOND_WINDOW, - PaneInfo.createPane(true, false, Timing.EARLY)); - WindowedValue> two = - WindowedValue.of( - KV.of("two", 2), - new Instant(20L), - SECOND_WINDOW, - PaneInfo.createPane(true, false, Timing.EARLY)); - container.write(mapView, ImmutableList.>of(one, two)); - - Map viewContents = - container - .createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, SECOND_WINDOW); - assertThat(viewContents, hasEntry("one", 1)); - assertThat(viewContents, hasEntry("two", 2)); - assertThat(viewContents.size(), is(2)); - - WindowedValue> three = - WindowedValue.of( - KV.of("three", 3), - new Instant(300L), - SECOND_WINDOW, - PaneInfo.createPane(false, false, Timing.EARLY, 1, -1)); - container.write(mapView, ImmutableList.>of(three)); - - Map overwrittenViewContents = - container - .createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, SECOND_WINDOW); - assertThat(overwrittenViewContents, hasEntry("three", 3)); - assertThat(overwrittenViewContents.size(), is(1)); - } - - /** - * Demonstrates that calling get() on a window that currently has no data does not return until - * there is data in the pane. - */ - @Test - public void getNotReadyThrows() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("not ready"); - - container.createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, GlobalWindow.INSTANCE); - } - - @Test - public void withPCollectionViewsErrorsForContainsNotInViews() { - PCollectionView>> newView = - PCollectionViews.multimapView( - pipeline, - WindowingStrategy.globalDefault(), - KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("with unknown views " + ImmutableList.of(newView).toString()); - - container.createReaderForViews(ImmutableList.>of(newView)); - } - - @Test - public void withViewsForViewNotInContainerFails() { - PCollectionView>> newView = - PCollectionViews.multimapView( - pipeline, - WindowingStrategy.globalDefault(), - KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of())); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("unknown views"); - thrown.expectMessage(newView.toString()); - - container.createReaderForViews(ImmutableList.>of(newView)); - } - - @Test - public void getOnReaderForViewNotInReaderFails() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("unknown view: " + iterableView.toString()); - - container.createReaderForViews(ImmutableList.>of(mapView)) - .get(iterableView, GlobalWindow.INSTANCE); - } - - @Test - public void writeForMultipleElementsInDifferentWindowsSucceeds() throws Exception { - WindowedValue firstWindowedValue = - WindowedValue.of( - 2.875, - FIRST_WINDOW.maxTimestamp().minus(200L), - FIRST_WINDOW, - PaneInfo.ON_TIME_AND_ONLY_FIRING); - WindowedValue secondWindowedValue = - WindowedValue.of( - 4.125, - SECOND_WINDOW.maxTimestamp().minus(2_000_000L), - SECOND_WINDOW, - PaneInfo.ON_TIME_AND_ONLY_FIRING); - container.write(singletonView, ImmutableList.of(firstWindowedValue, secondWindowedValue)); - assertThat( - container - .createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, FIRST_WINDOW), - equalTo(2.875)); - assertThat( - container - .createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, SECOND_WINDOW), - equalTo(4.125)); - } - - @Test - public void writeForMultipleIdenticalElementsInSameWindowSucceeds() throws Exception { - WindowedValue firstValue = - WindowedValue.of( - 44, - FIRST_WINDOW.maxTimestamp().minus(200L), - FIRST_WINDOW, - PaneInfo.ON_TIME_AND_ONLY_FIRING); - WindowedValue secondValue = - WindowedValue.of( - 44, - FIRST_WINDOW.maxTimestamp().minus(200L), - FIRST_WINDOW, - PaneInfo.ON_TIME_AND_ONLY_FIRING); - - container.write(iterableView, ImmutableList.of(firstValue, secondValue)); - - assertThat( - container - .createReaderForViews(ImmutableList.>of(iterableView)) - .get(iterableView, FIRST_WINDOW), - contains(44, 44)); - } - - @Test - public void writeForElementInMultipleWindowsSucceeds() throws Exception { - WindowedValue multiWindowedValue = - WindowedValue.of( - 2.875, - FIRST_WINDOW.maxTimestamp().minus(200L), - ImmutableList.of(FIRST_WINDOW, SECOND_WINDOW), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - container.write(singletonView, ImmutableList.of(multiWindowedValue)); - assertThat( - container - .createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, FIRST_WINDOW), - equalTo(2.875)); - assertThat( - container - .createReaderForViews(ImmutableList.>of(singletonView)) - .get(singletonView, SECOND_WINDOW), - equalTo(2.875)); - } - - @Test - public void finishDoesNotOverwriteWrittenElements() throws Exception { - WindowedValue> one = - WindowedValue.of( - KV.of("one", 1), - new Instant(1L), - SECOND_WINDOW, - PaneInfo.createPane(true, false, Timing.EARLY)); - WindowedValue> two = - WindowedValue.of( - KV.of("two", 2), - new Instant(20L), - SECOND_WINDOW, - PaneInfo.createPane(true, false, Timing.EARLY)); - container.write(mapView, ImmutableList.>of(one, two)); - - immediatelyInvokeCallback(mapView, SECOND_WINDOW); - - Map viewContents = - container - .createReaderForViews(ImmutableList.>of(mapView)) - .get(mapView, SECOND_WINDOW); - - assertThat(viewContents, hasEntry("one", 1)); - assertThat(viewContents, hasEntry("two", 2)); - assertThat(viewContents.size(), is(2)); - } - - @Test - public void finishOnPendingViewsSetsEmptyElements() throws Exception { - immediatelyInvokeCallback(mapView, SECOND_WINDOW); - Future> mapFuture = - getFutureOfView( - container.createReaderForViews(ImmutableList.>of(mapView)), - mapView, - SECOND_WINDOW); - - assertThat(mapFuture.get().isEmpty(), is(true)); - } - - /** - * Demonstrates that calling isReady on an empty container throws an - * {@link IllegalArgumentException}. - */ - @Test - public void isReadyInEmptyReaderThrows() { - ReadyCheckingSideInputReader reader = - container.createReaderForViews(ImmutableList.>of()); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("does not contain"); - thrown.expectMessage(ImmutableList.of().toString()); - reader.isReady(mapView, GlobalWindow.INSTANCE); - } - - /** - * Demonstrates that calling isReady returns false until elements are written to the - * {@link PCollectionView}, {@link BoundedWindow} pair, at which point it returns true. - */ - @Test - public void isReadyForSomeNotReadyViewsFalseUntilElements() { - container.write( - mapView, - ImmutableList.of( - WindowedValue.of( - KV.of("one", 1), - SECOND_WINDOW.maxTimestamp().minus(100L), - SECOND_WINDOW, - PaneInfo.ON_TIME_AND_ONLY_FIRING))); - - ReadyCheckingSideInputReader reader = - container.createReaderForViews(ImmutableList.of(mapView, singletonView)); - assertThat(reader.isReady(mapView, FIRST_WINDOW), is(false)); - assertThat(reader.isReady(mapView, SECOND_WINDOW), is(true)); - - assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(false)); - - container.write( - mapView, - ImmutableList.of( - WindowedValue.of( - KV.of("too", 2), - FIRST_WINDOW.maxTimestamp().minus(100L), - FIRST_WINDOW, - PaneInfo.ON_TIME_AND_ONLY_FIRING))); - // Cached value is false - assertThat(reader.isReady(mapView, FIRST_WINDOW), is(false)); - - container.write( - singletonView, - ImmutableList.of( - WindowedValue.of( - 1.25, - SECOND_WINDOW.maxTimestamp().minus(100L), - SECOND_WINDOW, - PaneInfo.ON_TIME_AND_ONLY_FIRING))); - assertThat(reader.isReady(mapView, SECOND_WINDOW), is(true)); - assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(false)); - - assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(false)); - assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); - - reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView)); - assertThat(reader.isReady(mapView, SECOND_WINDOW), is(true)); - assertThat(reader.isReady(singletonView, SECOND_WINDOW), is(true)); - assertThat(reader.isReady(mapView, FIRST_WINDOW), is(true)); - } - - @Test - public void isReadyForEmptyWindowTrue() throws Exception { - CountDownLatch onComplete = new CountDownLatch(1); - immediatelyInvokeCallback(mapView, GlobalWindow.INSTANCE); - CountDownLatch latch = invokeLatchedCallback(singletonView, GlobalWindow.INSTANCE, onComplete); - - ReadyCheckingSideInputReader reader = - container.createReaderForViews(ImmutableList.of(mapView, singletonView)); - assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(true)); - assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); - - latch.countDown(); - if (!onComplete.await(1500L, TimeUnit.MILLISECONDS)) { - fail("Callback to set empty values did not complete!"); - } - // The cached value was false, so it continues to be true - assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false)); - - // A new reader for the same container gets a fresh look - reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView)); - assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(true)); - } - - /** - * When a callAfterWindowCloses with the specified view's producing transform, window, and - * windowing strategy is invoked, immediately execute the callback. - */ - private void immediatelyInvokeCallback(PCollectionView view, BoundedWindow window) { - doAnswer( - new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object callback = invocation.getArguments()[3]; - Runnable callbackRunnable = (Runnable) callback; - callbackRunnable.run(); - return null; - } - }) - .when(context) - .scheduleAfterOutputWouldBeProduced( - Mockito.eq(view), - Mockito.eq(window), - Mockito.eq(view.getWindowingStrategyInternal()), - Mockito.any(Runnable.class)); - } - - /** - * When a callAfterWindowCloses with the specified view's producing transform, window, and - * windowing strategy is invoked, start a thread that will invoke the callback after the returned - * {@link CountDownLatch} is counted down once. - */ - private CountDownLatch invokeLatchedCallback( - PCollectionView view, BoundedWindow window, final CountDownLatch onComplete) { - final CountDownLatch runLatch = new CountDownLatch(1); - doAnswer( - new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object callback = invocation.getArguments()[3]; - final Runnable callbackRunnable = (Runnable) callback; - Executors.newSingleThreadExecutor().submit(new Runnable() { - public void run() { - try { - if (!runLatch.await(1500L, TimeUnit.MILLISECONDS)) { - fail("Run latch didn't count down within timeout"); - } - callbackRunnable.run(); - onComplete.countDown(); - } catch (InterruptedException e) { - fail("Unexpectedly interrupted while waiting for latch to be counted down"); - } - } - }); - return null; - } - }) - .when(context) - .scheduleAfterOutputWouldBeProduced( - Mockito.eq(view), - Mockito.eq(window), - Mockito.eq(view.getWindowingStrategyInternal()), - Mockito.any(Runnable.class)); - return runLatch; - } - - private Future getFutureOfView(final SideInputReader myReader, - final PCollectionView view, final BoundedWindow window) { - Callable callable = new Callable() { - @Override - public ValueT call() throws Exception { - return myReader.get(view, window); - } - }; - return Executors.newSingleThreadExecutor().submit(callable); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java deleted file mode 100644 index eeaa4c12a5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessTimerInternalsTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate.TimerUpdateBuilder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TransformWatermarks; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link InProcessTimerInternals}. - */ -@RunWith(JUnit4.class) -public class InProcessTimerInternalsTest { - private MockClock clock; - @Mock private TransformWatermarks watermarks; - - private TimerUpdateBuilder timerUpdateBuilder; - - private InProcessTimerInternals internals; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - clock = MockClock.fromInstant(new Instant(0)); - - timerUpdateBuilder = TimerUpdate.builder(StructuralKey.of(1234, VarIntCoder.of())); - - internals = InProcessTimerInternals.create(clock, watermarks, timerUpdateBuilder); - } - - @Test - public void setTimerAddsToBuilder() { - TimerData eventTimer = - TimerData.of(StateNamespaces.global(), new Instant(20145L), TimeDomain.EVENT_TIME); - TimerData processingTimer = - TimerData.of(StateNamespaces.global(), new Instant(125555555L), TimeDomain.PROCESSING_TIME); - TimerData synchronizedProcessingTimer = - TimerData.of( - StateNamespaces.global(), - new Instant(98745632189L), - TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - internals.setTimer(eventTimer); - internals.setTimer(processingTimer); - internals.setTimer(synchronizedProcessingTimer); - - assertThat( - internals.getTimerUpdate().getSetTimers(), - containsInAnyOrder(eventTimer, synchronizedProcessingTimer, processingTimer)); - } - - @Test - public void deleteTimerDeletesOnBuilder() { - TimerData eventTimer = - TimerData.of(StateNamespaces.global(), new Instant(20145L), TimeDomain.EVENT_TIME); - TimerData processingTimer = - TimerData.of(StateNamespaces.global(), new Instant(125555555L), TimeDomain.PROCESSING_TIME); - TimerData synchronizedProcessingTimer = - TimerData.of( - StateNamespaces.global(), - new Instant(98745632189L), - TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - internals.deleteTimer(eventTimer); - internals.deleteTimer(processingTimer); - internals.deleteTimer(synchronizedProcessingTimer); - - assertThat( - internals.getTimerUpdate().getDeletedTimers(), - containsInAnyOrder(eventTimer, synchronizedProcessingTimer, processingTimer)); - } - - @Test - public void getProcessingTimeIsClockNow() { - assertThat(internals.currentProcessingTime(), equalTo(clock.now())); - Instant oldProcessingTime = internals.currentProcessingTime(); - - clock.advance(Duration.standardHours(12)); - - assertThat(internals.currentProcessingTime(), equalTo(clock.now())); - assertThat( - internals.currentProcessingTime(), - equalTo(oldProcessingTime.plus(Duration.standardHours(12)))); - } - - @Test - public void getSynchronizedProcessingTimeIsWatermarkSynchronizedInputTime() { - when(watermarks.getSynchronizedProcessingInputTime()).thenReturn(new Instant(12345L)); - assertThat(internals.currentSynchronizedProcessingTime(), equalTo(new Instant(12345L))); - } - - @Test - public void getInputWatermarkTimeUsesWatermarkTime() { - when(watermarks.getInputWatermark()).thenReturn(new Instant(8765L)); - assertThat(internals.currentInputWatermarkTime(), equalTo(new Instant(8765L))); - } - - @Test - public void getOutputWatermarkTimeUsesWatermarkTime() { - when(watermarks.getOutputWatermark()).thenReturn(new Instant(25525L)); - assertThat(internals.currentOutputWatermarkTime(), equalTo(new Instant(25525L))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java deleted file mode 100644 index 0aaccc2848..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/KeyedPValueTrackingVisitorTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.Keys; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableSet; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collections; -import java.util.Set; - -/** - * Tests for {@link KeyedPValueTrackingVisitor}. - */ -@RunWith(JUnit4.class) -public class KeyedPValueTrackingVisitorTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - private KeyedPValueTrackingVisitor visitor; - private Pipeline p; - - @Before - public void setup() { - PipelineOptions options = PipelineOptionsFactory.create(); - - p = Pipeline.create(options); - @SuppressWarnings("rawtypes") - Set> producesKeyed = - ImmutableSet.>of(PrimitiveKeyer.class, CompositeKeyer.class); - visitor = KeyedPValueTrackingVisitor.create(producesKeyed); - } - - @Test - public void primitiveProducesKeyedOutputUnkeyedInputKeyedOutput() { - PCollection keyed = - p.apply(Create.of(1, 2, 3)).apply(new PrimitiveKeyer()); - - p.traverseTopologically(visitor); - assertThat(visitor.getKeyedPValues(), hasItem(keyed)); - } - - @Test - public void primitiveProducesKeyedOutputKeyedInputKeyedOutut() { - PCollection keyed = - p.apply(Create.of(1, 2, 3)) - .apply("firstKey", new PrimitiveKeyer()) - .apply("secondKey", new PrimitiveKeyer()); - - p.traverseTopologically(visitor); - assertThat(visitor.getKeyedPValues(), hasItem(keyed)); - } - - @Test - public void compositeProducesKeyedOutputUnkeyedInputKeyedOutput() { - PCollection keyed = - p.apply(Create.of(1, 2, 3)).apply(new CompositeKeyer()); - - p.traverseTopologically(visitor); - assertThat(visitor.getKeyedPValues(), hasItem(keyed)); - } - - @Test - public void compositeProducesKeyedOutputKeyedInputKeyedOutut() { - PCollection keyed = - p.apply(Create.of(1, 2, 3)) - .apply("firstKey", new CompositeKeyer()) - .apply("secondKey", new CompositeKeyer()); - - p.traverseTopologically(visitor); - assertThat(visitor.getKeyedPValues(), hasItem(keyed)); - } - - - @Test - public void noInputUnkeyedOutput() { - PCollection>> unkeyed = - p.apply( - Create.of(KV.>of(-1, Collections.emptyList())) - .withCoder(KvCoder.of(VarIntCoder.of(), IterableCoder.of(VoidCoder.of())))); - - p.traverseTopologically(visitor); - assertThat(visitor.getKeyedPValues(), not(hasItem(unkeyed))); - } - - @Test - public void keyedInputNotProducesKeyedOutputUnkeyedOutput() { - PCollection onceKeyed = - p.apply(Create.of(1, 2, 3)) - .apply(new PrimitiveKeyer()) - .apply(ParDo.of(new IdentityFn())); - - p.traverseTopologically(visitor); - assertThat(visitor.getKeyedPValues(), not(hasItem(onceKeyed))); - } - - @Test - public void unkeyedInputNotProducesKeyedOutputUnkeyedOutput() { - PCollection unkeyed = - p.apply(Create.of(1, 2, 3)).apply(ParDo.of(new IdentityFn())); - - p.traverseTopologically(visitor); - assertThat(visitor.getKeyedPValues(), not(hasItem(unkeyed))); - } - - @Test - public void traverseMultipleTimesThrows() { - p.apply( - Create.>of( - KV.of(1, (Void) null), KV.of(2, (Void) null), KV.of(3, (Void) null)) - .withCoder(KvCoder.of(VarIntCoder.of(), VoidCoder.of()))) - .apply(GroupByKey.create()) - .apply(Keys.create()); - - p.traverseTopologically(visitor); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("already been finalized"); - thrown.expectMessage(KeyedPValueTrackingVisitor.class.getSimpleName()); - p.traverseTopologically(visitor); - } - - @Test - public void getKeyedPValuesBeforeTraverseThrows() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("completely traversed"); - thrown.expectMessage("getKeyedPValues"); - visitor.getKeyedPValues(); - } - - private static class PrimitiveKeyer extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), input.getWindowingStrategy(), input.isBounded()) - .setCoder(input.getCoder()); - } - } - - private static class CompositeKeyer extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection input) { - return input.apply(new PrimitiveKeyer()).apply(ParDo.of(new IdentityFn())); - } - } - - private static class IdentityFn extends DoFn { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - c.output(c.element()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java deleted file mode 100644 index 7e650b48aa..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/LockedKeyedResourcePoolTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.ExecutionError; -import com.google.common.util.concurrent.UncheckedExecutionException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; - -/** - * Tests for {@link LockedKeyedResourcePool}. - */ -@RunWith(JUnit4.class) -public class LockedKeyedResourcePoolTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - private LockedKeyedResourcePool cache = - LockedKeyedResourcePool.create(); - - @Test - public void acquireReleaseAcquireLastLoadedOrReleased() throws ExecutionException { - Optional returned = cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - return 3; - } - }); - assertThat(returned.get(), equalTo(3)); - - cache.release("foo", 4); - Optional reacquired = cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - return 5; - } - }); - assertThat(reacquired.get(), equalTo(4)); - } - - @Test - public void acquireReleaseReleaseThrows() throws ExecutionException { - Optional returned = cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - return 3; - } - }); - assertThat(returned.get(), equalTo(3)); - - cache.release("foo", 4); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("already a value present"); - thrown.expectMessage("At most one"); - cache.release("foo", 4); - } - - @Test - public void releaseBeforeAcquireThrows() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("before a value was acquired"); - cache.release("bar", 3); - } - - @Test - public void multipleAcquireWithoutReleaseAbsent() throws ExecutionException { - Optional returned = cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - return 3; - } - }); - Optional secondReturned = cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - return 3; - } - }); - assertThat(secondReturned.isPresent(), is(false)); - } - - @Test - public void acquireMultipleKeysSucceeds() throws ExecutionException { - Optional returned = cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - return 3; - } - }); - Optional secondReturned = cache.tryAcquire("bar", new Callable() { - @Override - public Integer call() throws Exception { - return 4; - } - }); - - assertThat(returned.get(), equalTo(3)); - assertThat(secondReturned.get(), equalTo(4)); - } - - @Test - public void acquireThrowsExceptionWrapped() throws ExecutionException { - final Exception cause = new Exception("checkedException"); - thrown.expect(ExecutionException.class); - thrown.expectCause(equalTo(cause)); - cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - throw cause; - } - }); - } - - @Test - public void acquireThrowsRuntimeExceptionWrapped() throws ExecutionException { - final RuntimeException cause = new RuntimeException("UncheckedException"); - thrown.expect(UncheckedExecutionException.class); - thrown.expectCause(equalTo(cause)); - cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - throw cause; - } - }); - } - - @Test - public void acquireThrowsErrorWrapped() throws ExecutionException { - final Error cause = new Error("Error"); - thrown.expect(ExecutionError.class); - thrown.expectCause(equalTo(cause)); - cache.tryAcquire("foo", new Callable() { - @Override - public Integer call() throws Exception { - throw cause; - } - }); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/MockClock.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/MockClock.java deleted file mode 100644 index d69660b399..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/MockClock.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static com.google.common.base.Preconditions.checkArgument; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -/** - * A clock that returns a constant value for now which can be set with calls to - * {@link #set(Instant)}. - * - *

              For uses of the {@link Clock} interface in unit tests. - */ -public class MockClock implements Clock { - - private Instant now; - - public static MockClock fromInstant(Instant initial) { - return new MockClock(initial); - } - - private MockClock(Instant initialNow) { - this.now = initialNow; - } - - public void set(Instant newNow) { - checkArgument(!newNow.isBefore(now), "Cannot move MockClock backwards in time from %s to %s", - now, newNow); - this.now = newNow; - } - - public void advance(Duration duration) { - checkArgument( - duration.getMillis() > 0, - "Cannot move MockClock backwards in time by duration %s", - duration); - set(now.plus(duration)); - } - - @Override - public Instant now() { - return now; - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java deleted file mode 100644 index 5cf65c1f43..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoInProcessEvaluatorTest.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.IdentitySideInputWindowFn; -import com.google.cloud.dataflow.sdk.util.ReadyCheckingSideInputReader; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.worker.StateSampler; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.annotation.Nullable; - -/** - * Tests for {@link ParDoInProcessEvaluator}. - */ -@RunWith(JUnit4.class) -public class ParDoInProcessEvaluatorTest { - @Mock private InProcessEvaluationContext evaluationContext; - private PCollection inputPc; - private TupleTag mainOutputTag; - private List> sideOutputTags; - private BundleFactory bundleFactory; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - TestPipeline p = TestPipeline.create(); - inputPc = p.apply(Create.of(1, 2, 3)); - mainOutputTag = new TupleTag() {}; - sideOutputTags = TupleTagList.empty().getAll(); - - bundleFactory = InProcessBundleFactory.create(); - } - - @Test - public void sideInputsNotReadyResultHasUnprocessedElements() { - PCollectionView singletonView = - inputPc - .apply(Window.into(new IdentitySideInputWindowFn())) - .apply(View.asSingleton().withDefaultValue(0)); - RecorderFn fn = new RecorderFn(singletonView); - PCollection output = inputPc.apply(ParDo.of(fn).withSideInputs(singletonView)); - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(inputPc).commit(Instant.now()); - UncommittedBundle outputBundle = bundleFactory.createBundle(inputBundle, output); - when(evaluationContext.createBundle(inputBundle, output)) - .thenReturn(outputBundle); - - ParDoInProcessEvaluator evaluator = - createEvaluator(singletonView, fn, inputBundle, output); - - IntervalWindow nonGlobalWindow = new IntervalWindow(new Instant(0), new Instant(10_000L)); - WindowedValue first = WindowedValue.valueInGlobalWindow(3); - WindowedValue second = - WindowedValue.of(2, new Instant(1234L), nonGlobalWindow, PaneInfo.NO_FIRING); - WindowedValue third = - WindowedValue.of( - 1, - new Instant(2468L), - ImmutableList.of(nonGlobalWindow, GlobalWindow.INSTANCE), - PaneInfo.NO_FIRING); - - evaluator.processElement(first); - evaluator.processElement(second); - evaluator.processElement(third); - InProcessTransformResult result = evaluator.finishBundle(); - - assertThat( - result.getUnprocessedElements(), - Matchers.>containsInAnyOrder( - second, WindowedValue.of(1, new Instant(2468L), nonGlobalWindow, PaneInfo.NO_FIRING))); - assertThat(result.getOutputBundles(), Matchers.>contains(outputBundle)); - assertThat(RecorderFn.processed, containsInAnyOrder(1, 3)); - assertThat( - Iterables.getOnlyElement(result.getOutputBundles()).commit(Instant.now()).getElements(), - Matchers.>containsInAnyOrder( - first.withValue(8), - WindowedValue.timestampedValueInGlobalWindow(6, new Instant(2468L)))); - } - - private ParDoInProcessEvaluator createEvaluator( - PCollectionView singletonView, - RecorderFn fn, - InProcessPipelineRunner.CommittedBundle inputBundle, - PCollection output) { - when( - evaluationContext.createSideInputReader( - ImmutableList.>of(singletonView))) - .thenReturn(new ReadyInGlobalWindowReader()); - InProcessExecutionContext executionContext = mock(InProcessExecutionContext.class); - InProcessStepContext stepContext = mock(InProcessStepContext.class); - when(executionContext.getOrCreateStepContext(Mockito.any(String.class), - Mockito.any(String.class), - Mockito.any(StateSampler.class))).thenReturn(stepContext); - when(stepContext.getTimerUpdate()).thenReturn(TimerUpdate.empty()); - when( - evaluationContext.getExecutionContext( - Mockito.any(AppliedPTransform.class), Mockito.any(StructuralKey.class))) - .thenReturn(executionContext); - when(evaluationContext.createCounterSet()).thenReturn(new CounterSet()); - - return ParDoInProcessEvaluator.create( - evaluationContext, - inputBundle, - (AppliedPTransform, ?, ?>) output.getProducingTransformInternal(), - fn, - ImmutableList.>of(singletonView), - mainOutputTag, - sideOutputTags, - ImmutableMap., PCollection>of(mainOutputTag, output)); - } - - private static class RecorderFn extends DoFn { - private static Collection processed; - private final PCollectionView view; - - public RecorderFn(PCollectionView view) { - processed = new ArrayList<>(); - this.view = view; - } - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - processed.add(c.element()); - c.output(c.element() + c.sideInput(view)); - } - } - - private static class ReadyInGlobalWindowReader implements ReadyCheckingSideInputReader { - @Override - @Nullable - public T get(PCollectionView view, BoundedWindow window) { - if (window.equals(GlobalWindow.INSTANCE)) { - return (T) (Integer) 5; - } - fail("Should only call get in the Global Window, others are not ready"); - throw new AssertionError("Unreachable"); - } - - @Override - public boolean contains(PCollectionView view) { - return true; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public boolean isReady(PCollectionView view, BoundedWindow window) { - return window.equals(GlobalWindow.INSTANCE); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java deleted file mode 100644 index 8ba3045034..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactoryTest.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Tests for {@link ParDoMultiEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class ParDoMultiEvaluatorFactoryTest implements Serializable { - private transient BundleFactory bundleFactory = InProcessBundleFactory.create(); - - @Test - public void testParDoMultiInMemoryTransformEvaluator() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - - TupleTag> mainOutputTag = new TupleTag>() {}; - final TupleTag elementTag = new TupleTag<>(); - final TupleTag lengthTag = new TupleTag<>(); - - BoundMulti> pardo = - ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.element().length())); - c.sideOutput(elementTag, c.element()); - c.sideOutput(lengthTag, c.element().length()); - } - }) - .withOutputTags(mainOutputTag, TupleTagList.of(elementTag).and(lengthTag)); - PCollectionTuple outputTuple = input.apply(pardo); - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - PCollection> mainOutput = outputTuple.get(mainOutputTag); - PCollection elementOutput = outputTuple.get(elementTag); - PCollection lengthOutput = outputTuple.get(lengthTag); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = - bundleFactory.createRootBundle(mainOutput); - UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); - UncommittedBundle lengthOutputBundle = bundleFactory.createRootBundle(lengthOutput); - - when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - when(evaluationContext.createBundle(inputBundle, elementOutput)) - .thenReturn(elementOutputBundle); - when(evaluationContext.createBundle(inputBundle, lengthOutput)).thenReturn(lengthOutputBundle); - - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), - inputBundle.getKey())).thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory() - .forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); - evaluator.processElement( - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getOutputBundles(), - Matchers.>containsInAnyOrder( - lengthOutputBundle, mainOutputBundle, elementOutputBundle)); - assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - assertThat(result.getCounters(), equalTo(counters)); - - assertThat( - mainOutputBundle.commit(Instant.now()).getElements(), - Matchers.>>containsInAnyOrder( - WindowedValue.valueInGlobalWindow(KV.of("foo", 3)), - WindowedValue.timestampedValueInGlobalWindow(KV.of("bara", 4), new Instant(1000)), - WindowedValue.valueInGlobalWindow( - KV.of("bazam", 5), PaneInfo.ON_TIME_AND_ONLY_FIRING))); - assertThat( - elementOutputBundle.commit(Instant.now()).getElements(), - Matchers.>containsInAnyOrder( - WindowedValue.valueInGlobalWindow("foo"), - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000)), - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING))); - assertThat( - lengthOutputBundle.commit(Instant.now()).getElements(), - Matchers.>containsInAnyOrder( - WindowedValue.valueInGlobalWindow(3), - WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), - WindowedValue.valueInGlobalWindow(5, PaneInfo.ON_TIME_AND_ONLY_FIRING))); - } - - @Test - public void testParDoMultiUndeclaredSideOutput() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - - TupleTag> mainOutputTag = new TupleTag>() {}; - final TupleTag elementTag = new TupleTag<>(); - final TupleTag lengthTag = new TupleTag<>(); - - BoundMulti> pardo = - ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.element().length())); - c.sideOutput(elementTag, c.element()); - c.sideOutput(lengthTag, c.element().length()); - } - }) - .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); - PCollectionTuple outputTuple = input.apply(pardo); - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - PCollection> mainOutput = outputTuple.get(mainOutputTag); - PCollection elementOutput = outputTuple.get(elementTag); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = - bundleFactory.createRootBundle(mainOutput); - UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); - - when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - when(evaluationContext.createBundle(inputBundle, elementOutput)) - .thenReturn(elementOutputBundle); - - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), - inputBundle.getKey())).thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory() - .forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); - evaluator.processElement( - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getOutputBundles(), - Matchers.>containsInAnyOrder(mainOutputBundle, elementOutputBundle)); - assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - assertThat(result.getCounters(), equalTo(counters)); - - assertThat( - mainOutputBundle.commit(Instant.now()).getElements(), - Matchers.>>containsInAnyOrder( - WindowedValue.valueInGlobalWindow(KV.of("foo", 3)), - WindowedValue.timestampedValueInGlobalWindow(KV.of("bara", 4), new Instant(1000)), - WindowedValue.valueInGlobalWindow( - KV.of("bazam", 5), PaneInfo.ON_TIME_AND_ONLY_FIRING))); - assertThat( - elementOutputBundle.commit(Instant.now()).getElements(), - Matchers.>containsInAnyOrder( - WindowedValue.valueInGlobalWindow("foo"), - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000)), - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING))); - } - - @Test - public void finishBundleWithStatePutsStateInResult() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - - TupleTag> mainOutputTag = new TupleTag>() {}; - final TupleTag elementTag = new TupleTag<>(); - - final StateTag> watermarkTag = - StateTags.watermarkStateInternal("myId", OutputTimeFns.outputAtEndOfWindow()); - final StateTag> bagTag = StateTags.bag("myBag", StringUtf8Coder.of()); - final StateNamespace windowNs = - StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE); - BoundMulti> pardo = - ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.windowingInternals() - .stateInternals() - .state(StateNamespaces.global(), watermarkTag) - .add(new Instant(20202L + c.element().length())); - c.windowingInternals() - .stateInternals() - .state( - StateNamespaces.window( - GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE), - bagTag) - .add(c.element()); - } - }) - .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); - PCollectionTuple outputTuple = input.apply(pardo); - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - PCollection> mainOutput = outputTuple.get(mainOutputTag); - PCollection elementOutput = outputTuple.get(elementTag); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = - bundleFactory.createRootBundle(mainOutput); - UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); - - when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - when(evaluationContext.createBundle(inputBundle, elementOutput)) - .thenReturn(elementOutputBundle); - - InProcessExecutionContext executionContext = new InProcessExecutionContext(null, - StructuralKey.of("myKey", StringUtf8Coder.of()), - null, - null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), - inputBundle.getKey())).thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory() - .forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); - evaluator.processElement( - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getOutputBundles(), - Matchers.>containsInAnyOrder(mainOutputBundle, elementOutputBundle)); - assertThat(result.getWatermarkHold(), equalTo(new Instant(20205L))); - assertThat(result.getState(), not(nullValue())); - assertThat( - result.getState().state(StateNamespaces.global(), watermarkTag).read(), - equalTo(new Instant(20205L))); - assertThat( - result.getState().state(windowNs, bagTag).read(), - containsInAnyOrder("foo", "bara", "bazam")); - } - - @Test - public void finishBundleWithStateAndTimersPutsTimersInResult() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - - TupleTag> mainOutputTag = new TupleTag>() {}; - final TupleTag elementTag = new TupleTag<>(); - - final TimerData addedTimer = - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0).plus(Duration.standardMinutes(5)), - new Instant(1) - .plus(Duration.standardMinutes(5)) - .plus(Duration.standardHours(1)))), - new Instant(54541L), - TimeDomain.EVENT_TIME); - final TimerData deletedTimer = - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardHours(1)))), - new Instant(3400000), - TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - - BoundMulti> pardo = - ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.windowingInternals().stateInternals(); - c.windowingInternals() - .timerInternals() - .setTimer( - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0).plus(Duration.standardMinutes(5)), - new Instant(1) - .plus(Duration.standardMinutes(5)) - .plus(Duration.standardHours(1)))), - new Instant(54541L), - TimeDomain.EVENT_TIME)); - c.windowingInternals() - .timerInternals() - .deleteTimer( - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0), - new Instant(0).plus(Duration.standardHours(1)))), - new Instant(3400000), - TimeDomain.SYNCHRONIZED_PROCESSING_TIME)); - } - }) - .withOutputTags(mainOutputTag, TupleTagList.of(elementTag)); - PCollectionTuple outputTuple = input.apply(pardo); - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - PCollection> mainOutput = outputTuple.get(mainOutputTag); - PCollection elementOutput = outputTuple.get(elementTag); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = - bundleFactory.createRootBundle(mainOutput); - UncommittedBundle elementOutputBundle = bundleFactory.createRootBundle(elementOutput); - - when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - when(evaluationContext.createBundle(inputBundle, elementOutput)) - .thenReturn(elementOutputBundle); - - InProcessExecutionContext executionContext = new InProcessExecutionContext(null, - StructuralKey.of("myKey", StringUtf8Coder.of()), - null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), - inputBundle.getKey())).thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoMultiEvaluatorFactory() - .forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); - evaluator.processElement( - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getTimerUpdate(), - equalTo( - TimerUpdate.builder(StructuralKey.of("myKey", StringUtf8Coder.of())) - .setTimer(addedTimer) - .setTimer(addedTimer) - .setTimer(addedTimer) - .deletedTimer(deletedTimer) - .deletedTimer(deletedTimer) - .deletedTimer(deletedTimer) - .build())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java deleted file mode 100644 index 9aa41692b8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoSingleEvaluatorFactoryTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InMemoryWatermarkManager.TimerUpdate; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.TimeDomain; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.state.BagState; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.StateTags; -import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Tests for {@link ParDoSingleEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class ParDoSingleEvaluatorFactoryTest implements Serializable { - private transient BundleFactory bundleFactory = InProcessBundleFactory.create(); - - @Test - public void testParDoInMemoryTransformEvaluator() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - PCollection collection = - input.apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().length()); - } - })); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle outputBundle = bundleFactory.createRootBundle(collection); - when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), - inputBundle.getKey())).thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoSingleEvaluatorFactory() - .forApplication( - collection.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); - evaluator.processElement( - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat(result.getOutputBundles(), Matchers.>contains(outputBundle)); - assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - assertThat(result.getCounters(), equalTo(counters)); - - assertThat( - outputBundle.commit(Instant.now()).getElements(), - Matchers.>containsInAnyOrder( - WindowedValue.valueInGlobalWindow(3), - WindowedValue.timestampedValueInGlobalWindow(4, new Instant(1000)), - WindowedValue.valueInGlobalWindow(5, PaneInfo.ON_TIME_AND_ONLY_FIRING))); - } - - @Test - public void testSideOutputToUndeclaredSideOutputSucceeds() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - final TupleTag sideOutputTag = new TupleTag() {}; - PCollection collection = - input.apply( - ParDo.of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.sideOutput(sideOutputTag, c.element().length()); - } - })); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle outputBundle = bundleFactory.createRootBundle(collection); - when(evaluationContext.createBundle(inputBundle, collection)).thenReturn(outputBundle); - InProcessExecutionContext executionContext = - new InProcessExecutionContext(null, null, null, null); - when(evaluationContext.getExecutionContext(collection.getProducingTransformInternal(), - inputBundle.getKey())).thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - TransformEvaluator evaluator = - new ParDoSingleEvaluatorFactory() - .forApplication( - collection.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); - evaluator.processElement( - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getOutputBundles(), Matchers.>containsInAnyOrder(outputBundle)); - assertThat(result.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - assertThat(result.getCounters(), equalTo(counters)); - } - - @Test - public void finishBundleWithStatePutsStateInResult() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - - final StateTag> watermarkTag = - StateTags.watermarkStateInternal("myId", OutputTimeFns.outputAtEarliestInputTimestamp()); - final StateTag> bagTag = StateTags.bag("myBag", StringUtf8Coder.of()); - final StateNamespace windowNs = - StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE); - ParDo.Bound> pardo = - ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.windowingInternals() - .stateInternals() - .state(StateNamespaces.global(), watermarkTag) - .add(new Instant(124443L - c.element().length())); - c.windowingInternals() - .stateInternals() - .state( - StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE), - bagTag) - .add(c.element()); - } - }); - PCollection> mainOutput = input.apply(pardo); - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = - bundleFactory.createRootBundle(mainOutput); - - when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - - InProcessExecutionContext executionContext = new InProcessExecutionContext(null, - StructuralKey.of("myKey", StringUtf8Coder.of()), - null, null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), - inputBundle.getKey())) - .thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - com.google.cloud.dataflow.sdk.runners.inprocess.TransformEvaluator evaluator = - new ParDoSingleEvaluatorFactory() - .forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - evaluator.processElement( - WindowedValue.timestampedValueInGlobalWindow("bara", new Instant(1000))); - evaluator.processElement( - WindowedValue.valueInGlobalWindow("bazam", PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat(result.getWatermarkHold(), equalTo(new Instant(124438L))); - assertThat(result.getState(), not(nullValue())); - assertThat( - result.getState().state(StateNamespaces.global(), watermarkTag).read(), - equalTo(new Instant(124438L))); - assertThat( - result.getState().state(windowNs, bagTag).read(), - containsInAnyOrder("foo", "bara", "bazam")); - } - - @Test - public void finishBundleWithStateAndTimersPutsTimersInResult() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bara", "bazam")); - - final TimerData addedTimer = - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0).plus(Duration.standardMinutes(5)), - new Instant(1) - .plus(Duration.standardMinutes(5)) - .plus(Duration.standardHours(1)))), - new Instant(54541L), - TimeDomain.EVENT_TIME); - final TimerData deletedTimer = - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardHours(1)))), - new Instant(3400000), - TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - - ParDo.Bound> pardo = - ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.windowingInternals().stateInternals(); - c.windowingInternals() - .timerInternals() - .setTimer( - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0).plus(Duration.standardMinutes(5)), - new Instant(1) - .plus(Duration.standardMinutes(5)) - .plus(Duration.standardHours(1)))), - new Instant(54541L), - TimeDomain.EVENT_TIME)); - c.windowingInternals() - .timerInternals() - .deleteTimer( - TimerData.of( - StateNamespaces.window( - IntervalWindow.getCoder(), - new IntervalWindow( - new Instant(0), - new Instant(0).plus(Duration.standardHours(1)))), - new Instant(3400000), - TimeDomain.SYNCHRONIZED_PROCESSING_TIME)); - } - }); - PCollection> mainOutput = input.apply(pardo); - - StructuralKey key = StructuralKey.of("myKey", StringUtf8Coder.of()); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - - InProcessEvaluationContext evaluationContext = mock(InProcessEvaluationContext.class); - UncommittedBundle> mainOutputBundle = - bundleFactory.createRootBundle(mainOutput); - - when(evaluationContext.createBundle(inputBundle, mainOutput)).thenReturn(mainOutputBundle); - - InProcessExecutionContext executionContext = new InProcessExecutionContext(null, - key, - null, - null); - when(evaluationContext.getExecutionContext(mainOutput.getProducingTransformInternal(), - inputBundle.getKey())) - .thenReturn(executionContext); - CounterSet counters = new CounterSet(); - when(evaluationContext.createCounterSet()).thenReturn(counters); - - TransformEvaluator evaluator = - new ParDoSingleEvaluatorFactory() - .forApplication( - mainOutput.getProducingTransformInternal(), inputBundle, evaluationContext); - - evaluator.processElement(WindowedValue.valueInGlobalWindow("foo")); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat(result.getTimerUpdate(), - equalTo(TimerUpdate.builder(StructuralKey.of("myKey", StringUtf8Coder.of())) - .setTimer(addedTimer) - .deletedTimer(deletedTimer) - .build())); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java deleted file mode 100644 index 2cfaa17859..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StepTransformResultTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.values.PCollection; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link StepTransformResult}. - */ -@RunWith(JUnit4.class) -public class StepTransformResultTest { - private AppliedPTransform transform; - private BundleFactory bundleFactory; - private PCollection pc; - - @Before - public void setup() { - TestPipeline p = TestPipeline.create(); - pc = p.apply(Create.of(1, 2, 3)); - transform = pc.getProducingTransformInternal(); - - bundleFactory = InProcessBundleFactory.create(); - } - - @Test - public void producedBundlesProducedOutputs() { - UncommittedBundle bundle = bundleFactory.createRootBundle(pc); - InProcessTransformResult result = StepTransformResult.withoutHold(transform).addOutput(bundle) - .build(); - - assertThat(result.getOutputBundles(), - Matchers.>containsInAnyOrder(bundle)); - } - - @Test - public void withAdditionalOutputProducedOutputs() { - InProcessTransformResult result = StepTransformResult.withoutHold(transform) - .withAdditionalOutput(OutputType.PCOLLECTION_VIEW) - .build(); - - assertThat(result.getOutputTypes(), containsInAnyOrder(OutputType.PCOLLECTION_VIEW)); - } - - @Test - public void producedBundlesAndAdditionalOutputProducedOutputs() { - InProcessTransformResult result = StepTransformResult.withoutHold(transform) - .addOutput(bundleFactory.createRootBundle(pc)) - .withAdditionalOutput(OutputType.PCOLLECTION_VIEW) - .build(); - - assertThat(result.getOutputTypes(), hasItem(OutputType.PCOLLECTION_VIEW)); - } - - @Test - public void noBundlesNoAdditionalOutputProducedOutputsFalse() { - InProcessTransformResult result = StepTransformResult.withoutHold(transform).build(); - - assertThat(result.getOutputTypes(), emptyIterable()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java deleted file mode 100644 index d0e995f6ff..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/StructuralKeyTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.theInstance; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link StructuralKey}. - */ -@RunWith(JUnit4.class) -public class StructuralKeyTest { - @Test - public void getKeyEqualToOldKey() { - assertThat(StructuralKey.of(1234, VarIntCoder.of()).getKey(), equalTo(1234)); - assertThat(StructuralKey.of("foobar", StringUtf8Coder.of()).getKey(), equalTo("foobar")); - assertArrayEquals(StructuralKey.of(new byte[] {2, 9, -22}, ByteArrayCoder.of()).getKey(), - new byte[] {2, 9, -22}); - } - - @Test - public void getKeyNotSameInstance() { - byte[] original = new byte[] {1, 4, 9, 127, -22}; - StructuralKey key = StructuralKey.of(original, ByteArrayCoder.of()); - - assertThat(key.getKey(), not(theInstance(original))); - } - - @Test - public void objectEqualsTrueKeyEquals() { - StructuralKey original = StructuralKey.of(1234, VarIntCoder.of()); - assertThat(StructuralKey.of(1234, VarIntCoder.of()), equalTo(original)); - } - - @Test - public void objectsNotEqualEncodingsEqualEquals() { - byte[] original = new byte[] {1, 4, 9, 127, -22}; - StructuralKey key = StructuralKey.of(original, ByteArrayCoder.of()); - - StructuralKey otherKey = - StructuralKey.of(new byte[] {1, 4, 9, 127, -22}, ByteArrayCoder.of()); - assertThat(key, equalTo(otherKey)); - } - - @Test - public void notEqualEncodingsEqual() { - byte[] original = new byte[] {1, 4, 9, 127, -22}; - StructuralKey key = StructuralKey.of(original, ByteArrayCoder.of()); - - StructuralKey otherKey = - StructuralKey.of(new byte[] {9, -128, 22}, ByteArrayCoder.of()); - assertThat(key, not(equalTo(otherKey))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java deleted file mode 100644 index 40b548d893..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TestStreamEvaluatorFactoryTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.TestStream; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.Iterables; -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link TestStreamEvaluatorFactory}. */ -@RunWith(JUnit4.class) -public class TestStreamEvaluatorFactoryTest { - private TestStreamEvaluatorFactory factory = new TestStreamEvaluatorFactory(); - private BundleFactory bundleFactory = InProcessBundleFactory.create(); - - /** Demonstrates that returned evaluators produce elements in sequence. */ - @Test - public void producesElementsInSequence() throws Exception { - Pipeline p = getPipeline(); - PCollection streamVals = - p.apply( - TestStream.create(VarIntCoder.of()) - .addElements(1, 2, 3) - .addElements(4, 5, 6) - .advanceWatermarkToInfinity()); - - InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - when(context.createRootBundle(streamVals)) - .thenReturn( - bundleFactory.createRootBundle(streamVals), bundleFactory.createRootBundle(streamVals)); - - TransformEvaluator firstEvaluator = - factory.forApplication(streamVals.getProducingTransformInternal(), null, context); - InProcessTransformResult firstResult = firstEvaluator.finishBundle(); - - TransformEvaluator secondEvaluator = - factory.forApplication(streamVals.getProducingTransformInternal(), null, context); - InProcessTransformResult secondResult = secondEvaluator.finishBundle(); - - TransformEvaluator thirdEvaluator = - factory.forApplication(streamVals.getProducingTransformInternal(), null, context); - InProcessTransformResult thirdResult = thirdEvaluator.finishBundle(); - - assertThat( - Iterables.getOnlyElement(firstResult.getOutputBundles()) - .commit(Instant.now()) - .getElements(), - Matchers.>containsInAnyOrder( - WindowedValue.valueInGlobalWindow(1), - WindowedValue.valueInGlobalWindow(2), - WindowedValue.valueInGlobalWindow(3))); - assertThat(firstResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - - assertThat( - Iterables.getOnlyElement(secondResult.getOutputBundles()) - .commit(Instant.now()) - .getElements(), - Matchers.>containsInAnyOrder( - WindowedValue.valueInGlobalWindow(4), - WindowedValue.valueInGlobalWindow(5), - WindowedValue.valueInGlobalWindow(6))); - assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - - assertThat(Iterables.isEmpty(thirdResult.getOutputBundles()), is(true)); - assertThat(thirdResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MAX_VALUE)); - } - - /** Demonstrates that at most one evaluator for an application is available at a time. */ - @Test - public void onlyOneEvaluatorAtATime() throws Exception { - Pipeline p = getPipeline(); - PCollection streamVals = - p.apply( - TestStream.create(VarIntCoder.of()).addElements(4, 5, 6).advanceWatermarkToInfinity()); - - InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - TransformEvaluator firstEvaluator = - factory.forApplication(streamVals.getProducingTransformInternal(), null, context); - - // create a second evaluator before the first is finished. The evaluator should not be available - TransformEvaluator secondEvaluator = - factory.forApplication(streamVals.getProducingTransformInternal(), null, context); - assertThat(secondEvaluator, is(nullValue())); - } - - /** - * Demonstrates that multiple applications of the same {@link TestStream} produce separate - * evaluators. - */ - @Test - public void multipleApplicationsMultipleEvaluators() throws Exception { - Pipeline p = getPipeline(); - TestStream stream = - TestStream.create(VarIntCoder.of()).addElements(2).advanceWatermarkToInfinity(); - PCollection firstVals = p.apply("Stream One", stream); - PCollection secondVals = p.apply("Stream A", stream); - - InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - when(context.createRootBundle(firstVals)).thenReturn(bundleFactory.createRootBundle(firstVals)); - when(context.createRootBundle(secondVals)) - .thenReturn(bundleFactory.createRootBundle(secondVals)); - - TransformEvaluator firstEvaluator = - factory.forApplication(firstVals.getProducingTransformInternal(), null, context); - // The two evaluators can exist independently - TransformEvaluator secondEvaluator = - factory.forApplication(secondVals.getProducingTransformInternal(), null, context); - - InProcessTransformResult firstResult = firstEvaluator.finishBundle(); - InProcessTransformResult secondResult = secondEvaluator.finishBundle(); - - assertThat( - Iterables.getOnlyElement(firstResult.getOutputBundles()) - .commit(Instant.now()) - .getElements(), - Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow(2))); - assertThat(firstResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - - // They both produce equal results, and don't interfere with each other - assertThat( - Iterables.getOnlyElement(secondResult.getOutputBundles()) - .commit(Instant.now()) - .getElements(), - Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow(2))); - assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - } - - /** - * Demonstrates that multiple applications of different {@link TestStream} produce independent - * evaluators. - */ - @Test - public void multipleStreamsMultipleEvaluators() throws Exception { - Pipeline p = getPipeline(); - PCollection firstVals = - p.apply( - "Stream One", - TestStream.create(VarIntCoder.of()).addElements(2).advanceWatermarkToInfinity()); - PCollection secondVals = - p.apply( - "Stream A", - TestStream.create(StringUtf8Coder.of()) - .addElements("Two") - .advanceWatermarkToInfinity()); - - InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - when(context.createRootBundle(firstVals)).thenReturn(bundleFactory.createRootBundle(firstVals)); - when(context.createRootBundle(secondVals)) - .thenReturn(bundleFactory.createRootBundle(secondVals)); - - TransformEvaluator firstEvaluator = - factory.forApplication(firstVals.getProducingTransformInternal(), null, context); - // The two evaluators can exist independently - TransformEvaluator secondEvaluator = - factory.forApplication(secondVals.getProducingTransformInternal(), null, context); - - InProcessTransformResult firstResult = firstEvaluator.finishBundle(); - InProcessTransformResult secondResult = secondEvaluator.finishBundle(); - - assertThat( - Iterables.getOnlyElement(firstResult.getOutputBundles()) - .commit(Instant.now()) - .getElements(), - Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow(2))); - assertThat(firstResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - - assertThat( - Iterables.getOnlyElement(secondResult.getOutputBundles()) - .commit(Instant.now()) - .getElements(), - Matchers.>containsInAnyOrder(WindowedValue.valueInGlobalWindow("Two"))); - assertThat(secondResult.getWatermarkHold(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); - } - - private Pipeline getPipeline() { - PipelineOptions options = PipelineOptionsFactory.create(); - options.setRunner(InProcessPipelineRunner.class); - return Pipeline.create(options); - } - -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java deleted file mode 100644 index 1252f861ce..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorServicesTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import com.google.common.util.concurrent.MoreExecutors; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.ExecutorService; - -/** - * Tests for {@link TransformExecutorServices}. - */ -@RunWith(JUnit4.class) -public class TransformExecutorServicesTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - private ExecutorService executorService; - - @Before - public void setup() { - executorService = MoreExecutors.newDirectExecutorService(); - } - - @Test - public void parallelScheduleMultipleSchedulesBothImmediately() { - @SuppressWarnings("unchecked") - TransformExecutor first = mock(TransformExecutor.class); - @SuppressWarnings("unchecked") - TransformExecutor second = mock(TransformExecutor.class); - - TransformExecutorService parallel = - TransformExecutorServices.parallel(executorService); - parallel.schedule(first); - parallel.schedule(second); - - verify(first).run(); - verify(second).run(); - - parallel.complete(first); - parallel.complete(second); - } - - @Test - public void serialScheduleTwoWaitsForFirstToComplete() { - @SuppressWarnings("unchecked") - TransformExecutor first = mock(TransformExecutor.class); - @SuppressWarnings("unchecked") - TransformExecutor second = mock(TransformExecutor.class); - - TransformExecutorService serial = TransformExecutorServices.serial(executorService); - serial.schedule(first); - verify(first).run(); - - serial.schedule(second); - verify(second, never()).run(); - - serial.complete(first); - verify(second).run(); - - serial.complete(second); - } - - @Test - public void serialCompleteNotExecutingTaskThrows() { - @SuppressWarnings("unchecked") - TransformExecutor first = mock(TransformExecutor.class); - @SuppressWarnings("unchecked") - TransformExecutor second = mock(TransformExecutor.class); - - TransformExecutorService serial = TransformExecutorServices.serial(executorService); - serial.schedule(first); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("unexpected currently executing"); - - serial.complete(second); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java deleted file mode 100644 index 68e2d24cc7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/TransformExecutorTest.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.CommittedResult.OutputType; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.util.concurrent.MoreExecutors; -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; - - -/** - * Tests for {@link TransformExecutor}. - */ -@RunWith(JUnit4.class) -public class TransformExecutorTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - private PCollection created; - private PCollection> downstream; - - private CountDownLatch evaluatorCompleted; - - private RegisteringCompletionCallback completionCallback; - private TransformExecutorService transformEvaluationState; - private BundleFactory bundleFactory; - @Mock private InProcessEvaluationContext evaluationContext; - @Mock private TransformEvaluatorRegistry registry; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - bundleFactory = InProcessBundleFactory.create(); - - transformEvaluationState = - TransformExecutorServices.parallel(MoreExecutors.newDirectExecutorService()); - - evaluatorCompleted = new CountDownLatch(1); - completionCallback = new RegisteringCompletionCallback(evaluatorCompleted); - - TestPipeline p = TestPipeline.create(); - created = p.apply(Create.of("foo", "spam", "third")); - downstream = created.apply(WithKeys.of(3)); - } - - @Test - public void callWithNullInputBundleFinishesBundleAndCompletes() throws Exception { - final InProcessTransformResult result = - StepTransformResult.withoutHold(created.getProducingTransformInternal()).build(); - final AtomicBoolean finishCalled = new AtomicBoolean(false); - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception { - throw new IllegalArgumentException("Shouldn't be called"); - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - finishCalled.set(true); - return result; - } - }; - - when(registry.forApplication(created.getProducingTransformInternal(), null, evaluationContext)) - .thenReturn(evaluator); - - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.emptyList(), - evaluationContext, - null, - created.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - executor.run(); - - assertThat(finishCalled.get(), is(true)); - assertThat(completionCallback.handledResult, equalTo(result)); - assertThat(completionCallback.handledThrowable, is(nullValue())); - } - - @Test - public void nullTransformEvaluatorTerminates() throws Exception { - when(registry.forApplication(created.getProducingTransformInternal(), - null, - evaluationContext)).thenReturn(null); - - TransformExecutor executor = TransformExecutor.create(registry, - Collections.emptyList(), - evaluationContext, - null, - created.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - executor.run(); - - assertThat(completionCallback.handledResult, is(nullValue())); - assertThat(completionCallback.handledEmpty, equalTo(true)); - assertThat(completionCallback.handledThrowable, is(nullValue())); - } - - @Test - public void inputBundleProcessesEachElementFinishesAndCompletes() throws Exception { - final InProcessTransformResult result = - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); - final Collection> elementsProcessed = new ArrayList<>(); - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception { - elementsProcessed.add(element); - return; - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - return result; - } - }; - - WindowedValue foo = WindowedValue.valueInGlobalWindow("foo"); - WindowedValue spam = WindowedValue.valueInGlobalWindow("spam"); - WindowedValue third = WindowedValue.valueInGlobalWindow("third"); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(created).add(foo).add(spam).add(third).commit(Instant.now()); - when( - registry.forApplication( - downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) - .thenReturn(evaluator); - - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.emptyList(), - evaluationContext, - inputBundle, - downstream.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - - Executors.newSingleThreadExecutor().submit(executor); - - evaluatorCompleted.await(); - - assertThat(elementsProcessed, containsInAnyOrder(spam, third, foo)); - assertThat(completionCallback.handledResult, equalTo(result)); - assertThat(completionCallback.handledThrowable, is(nullValue())); - } - - @Test - public void processElementThrowsExceptionCallsback() throws Exception { - final InProcessTransformResult result = - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); - final Exception exception = new Exception(); - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception { - throw exception; - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - return result; - } - }; - - WindowedValue foo = WindowedValue.valueInGlobalWindow("foo"); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(created).add(foo).commit(Instant.now()); - when( - registry.forApplication( - downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) - .thenReturn(evaluator); - - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.emptyList(), - evaluationContext, - inputBundle, - downstream.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - Executors.newSingleThreadExecutor().submit(executor); - - evaluatorCompleted.await(); - - assertThat(completionCallback.handledResult, is(nullValue())); - assertThat(completionCallback.handledThrowable, Matchers.equalTo(exception)); - } - - @Test - public void finishBundleThrowsExceptionCallsback() throws Exception { - final Exception exception = new Exception(); - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception {} - - @Override - public InProcessTransformResult finishBundle() throws Exception { - throw exception; - } - }; - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(created).commit(Instant.now()); - when( - registry.forApplication( - downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) - .thenReturn(evaluator); - - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.emptyList(), - evaluationContext, - inputBundle, - downstream.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - Executors.newSingleThreadExecutor().submit(executor); - - evaluatorCompleted.await(); - - assertThat(completionCallback.handledResult, is(nullValue())); - assertThat(completionCallback.handledThrowable, Matchers.equalTo(exception)); - } - - @Test - public void duringCallGetThreadIsNonNull() throws Exception { - final InProcessTransformResult result = - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); - final CountDownLatch testLatch = new CountDownLatch(1); - final CountDownLatch evaluatorLatch = new CountDownLatch(1); - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception { - throw new IllegalArgumentException("Shouldn't be called"); - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - testLatch.countDown(); - evaluatorLatch.await(); - return result; - } - }; - - when(registry.forApplication(created.getProducingTransformInternal(), null, evaluationContext)) - .thenReturn(evaluator); - - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.emptyList(), - evaluationContext, - null, - created.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - - Executors.newSingleThreadExecutor().submit(executor); - testLatch.await(); - assertThat(executor.getThread(), not(nullValue())); - - // Finish the execution so everything can get closed down cleanly. - evaluatorLatch.countDown(); - } - - @Test - public void callWithEnforcementAppliesEnforcement() throws Exception { - final InProcessTransformResult result = - StepTransformResult.withoutHold(downstream.getProducingTransformInternal()).build(); - - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception { - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - return result; - } - }; - - WindowedValue fooElem = WindowedValue.valueInGlobalWindow("foo"); - WindowedValue barElem = WindowedValue.valueInGlobalWindow("bar"); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(created).add(fooElem).add(barElem).commit(Instant.now()); - when( - registry.forApplication( - downstream.getProducingTransformInternal(), inputBundle, evaluationContext)) - .thenReturn(evaluator); - - TestEnforcementFactory enforcement = new TestEnforcementFactory(); - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.singleton(enforcement), - evaluationContext, - inputBundle, - downstream.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - - executor.run(); - TestEnforcement testEnforcement = enforcement.instance; - assertThat( - testEnforcement.beforeElements, - Matchers.>containsInAnyOrder(barElem, fooElem)); - assertThat( - testEnforcement.afterElements, - Matchers.>containsInAnyOrder(barElem, fooElem)); - assertThat(testEnforcement.finishedBundles, contains(result)); - } - - @Test - public void callWithEnforcementThrowsOnFinishPropagates() throws Exception { - PCollection pcBytes = - created.apply( - new PTransform, PCollection>() { - @Override - public PCollection apply(PCollection input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), input.getWindowingStrategy(), input.isBounded()) - .setCoder(ByteArrayCoder.of()); - } - }); - - final InProcessTransformResult result = - StepTransformResult.withoutHold(pcBytes.getProducingTransformInternal()).build(); - final CountDownLatch testLatch = new CountDownLatch(1); - final CountDownLatch evaluatorLatch = new CountDownLatch(1); - - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception {} - - @Override - public InProcessTransformResult finishBundle() throws Exception { - testLatch.countDown(); - evaluatorLatch.await(); - return result; - } - }; - - WindowedValue fooBytes = WindowedValue.valueInGlobalWindow("foo".getBytes()); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(pcBytes).add(fooBytes).commit(Instant.now()); - when( - registry.forApplication( - pcBytes.getProducingTransformInternal(), inputBundle, evaluationContext)) - .thenReturn(evaluator); - - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.singleton(ImmutabilityEnforcementFactory.create()), - evaluationContext, - inputBundle, - pcBytes.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - - Future task = Executors.newSingleThreadExecutor().submit(executor); - testLatch.await(); - fooBytes.getValue()[0] = 'b'; - evaluatorLatch.countDown(); - - thrown.expectCause(isA(IllegalMutationException.class)); - task.get(); - } - - @Test - public void callWithEnforcementThrowsOnElementPropagates() throws Exception { - PCollection pcBytes = - created.apply( - new PTransform, PCollection>() { - @Override - public PCollection apply(PCollection input) { - return PCollection.createPrimitiveOutputInternal( - input.getPipeline(), input.getWindowingStrategy(), input.isBounded()) - .setCoder(ByteArrayCoder.of()); - } - }); - - final InProcessTransformResult result = - StepTransformResult.withoutHold(pcBytes.getProducingTransformInternal()).build(); - final CountDownLatch testLatch = new CountDownLatch(1); - final CountDownLatch evaluatorLatch = new CountDownLatch(1); - - TransformEvaluator evaluator = - new TransformEvaluator() { - @Override - public void processElement(WindowedValue element) throws Exception { - testLatch.countDown(); - evaluatorLatch.await(); - } - - @Override - public InProcessTransformResult finishBundle() throws Exception { - return result; - } - }; - - WindowedValue fooBytes = WindowedValue.valueInGlobalWindow("foo".getBytes()); - CommittedBundle inputBundle = - bundleFactory.createRootBundle(pcBytes).add(fooBytes).commit(Instant.now()); - when( - registry.forApplication( - pcBytes.getProducingTransformInternal(), inputBundle, evaluationContext)) - .thenReturn(evaluator); - - TransformExecutor executor = - TransformExecutor.create( - registry, - Collections.singleton(ImmutabilityEnforcementFactory.create()), - evaluationContext, - inputBundle, - pcBytes.getProducingTransformInternal(), - completionCallback, - transformEvaluationState); - - Future task = Executors.newSingleThreadExecutor().submit(executor); - testLatch.await(); - fooBytes.getValue()[0] = 'b'; - evaluatorLatch.countDown(); - - thrown.expectCause(isA(IllegalMutationException.class)); - task.get(); - } - - private static class RegisteringCompletionCallback implements CompletionCallback { - private InProcessTransformResult handledResult = null; - private boolean handledEmpty = false; - private Throwable handledThrowable = null; - private final CountDownLatch onMethod; - - private RegisteringCompletionCallback(CountDownLatch onMethod) { - this.onMethod = onMethod; - } - - @Override - public CommittedResult handleResult( - CommittedBundle inputBundle, InProcessTransformResult result) { - handledResult = result; - onMethod.countDown(); - @SuppressWarnings("rawtypes") Iterable unprocessedElements = - result.getUnprocessedElements() == null - ? Collections.emptyList() - : result.getUnprocessedElements(); - - CommittedBundle unprocessedBundle = - inputBundle == null ? null : inputBundle.withElements(unprocessedElements); - return CommittedResult.create(result, - unprocessedBundle, - Collections.>emptyList(), - EnumSet.noneOf(OutputType.class)); - } - - @Override - public void handleEmpty(AppliedPTransform transform) { - handledEmpty = true; - onMethod.countDown(); - } - - @Override - public void handleThrowable(CommittedBundle inputBundle, Throwable t) { - handledThrowable = t; - onMethod.countDown(); - } - } - - private static class TestEnforcementFactory implements ModelEnforcementFactory { - private TestEnforcement instance; - @Override - public TestEnforcement forBundle( - CommittedBundle input, AppliedPTransform consumer) { - TestEnforcement newEnforcement = new TestEnforcement<>(); - instance = newEnforcement; - return newEnforcement; - } - } - - private static class TestEnforcement implements ModelEnforcement { - private final List> beforeElements = new ArrayList<>(); - private final List> afterElements = new ArrayList<>(); - private final List finishedBundles = new ArrayList<>(); - - @Override - public void beforeElement(WindowedValue element) { - beforeElements.add(element); - } - - @Override - public void afterElement(WindowedValue element) { - afterElements.add(element); - } - - @Override - public void afterFinish( - CommittedBundle input, - InProcessTransformResult result, - Iterable> outputs) { - finishedBundles.add(result); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java deleted file mode 100644 index 8685920151..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadDeduplicatorTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.runners.inprocess.UnboundedReadDeduplicator.CachedIdDeduplicator; -import com.google.cloud.dataflow.sdk.runners.inprocess.UnboundedReadDeduplicator.NeverDeduplicator; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Tests for {@link UnboundedReadDeduplicator}. - */ -@RunWith(JUnit4.class) -public class UnboundedReadDeduplicatorTest { - @Test - public void neverDeduplicatorAlwaysTrue() { - byte[] id = new byte[] {-1, 2, 4, 22}; - UnboundedReadDeduplicator dedupper = NeverDeduplicator.create(); - - assertThat(dedupper.shouldOutput(id), is(true)); - assertThat(dedupper.shouldOutput(id), is(true)); - } - - @Test - public void cachedIdDeduplicatorTrueForFirstIdThenFalse() { - byte[] id = new byte[] {-1, 2, 4, 22}; - UnboundedReadDeduplicator dedupper = CachedIdDeduplicator.create(); - - assertThat(dedupper.shouldOutput(id), is(true)); - assertThat(dedupper.shouldOutput(id), is(false)); - } - - @Test - public void cachedIdDeduplicatorMultithreaded() throws InterruptedException { - byte[] id = new byte[] {-1, 2, 4, 22}; - UnboundedReadDeduplicator dedupper = CachedIdDeduplicator.create(); - final CountDownLatch startSignal = new CountDownLatch(1); - int numThreads = 1000; - final CountDownLatch readyLatch = new CountDownLatch(numThreads); - final CountDownLatch finishLine = new CountDownLatch(numThreads); - - ExecutorService executor = Executors.newCachedThreadPool(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger failureCount = new AtomicInteger(); - for (int i = 0; i < numThreads; i++) { - executor.submit(new TryOutputIdRunnable(dedupper, - id, - successCount, - failureCount, - readyLatch, - startSignal, - finishLine)); - } - - readyLatch.await(); - startSignal.countDown(); - finishLine.await(10L, TimeUnit.SECONDS); - executor.shutdownNow(); - - assertThat(successCount.get(), equalTo(1)); - assertThat(failureCount.get(), equalTo(numThreads - 1)); - } - - private static class TryOutputIdRunnable implements Runnable { - private final UnboundedReadDeduplicator deduplicator; - private final byte[] id; - private final AtomicInteger successCount; - private final AtomicInteger failureCount; - private final CountDownLatch readyLatch; - private final CountDownLatch startSignal; - private final CountDownLatch finishLine; - - public TryOutputIdRunnable( - UnboundedReadDeduplicator dedupper, - byte[] id, - AtomicInteger successCount, - AtomicInteger failureCount, - CountDownLatch readyLatch, - CountDownLatch startSignal, - CountDownLatch finishLine) { - this.deduplicator = dedupper; - this.id = id; - this.successCount = successCount; - this.failureCount = failureCount; - this.readyLatch = readyLatch; - this.startSignal = startSignal; - this.finishLine = finishLine; - } - - @Override - public void run() { - readyLatch.countDown(); - try { - startSignal.await(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - } - if (deduplicator.shouldOutput(id)) { - successCount.incrementAndGet(); - } else { - failureCount.incrementAndGet(); - } - finishLine.countDown(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java deleted file mode 100644 index 84a7ca2b0b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/UnboundedReadEvaluatorFactoryTest.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.io.CountingSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import com.google.common.collect.ContiguousSet; -import com.google.common.collect.DiscreteDomain; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Range; - -import org.hamcrest.Matchers; -import org.joda.time.DateTime; -import org.joda.time.Instant; -import org.joda.time.ReadableInstant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; -/** - * Tests for {@link UnboundedReadEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class UnboundedReadEvaluatorFactoryTest { - private PCollection longs; - private TransformEvaluatorFactory factory; - private InProcessEvaluationContext context; - private UncommittedBundle output; - - private BundleFactory bundleFactory = InProcessBundleFactory.create(); - - @Before - public void setup() { - UnboundedSource source = - CountingSource.unboundedWithTimestampFn(new LongToInstantFn()); - TestPipeline p = TestPipeline.create(); - longs = p.apply(Read.from(source)); - - factory = new UnboundedReadEvaluatorFactory(); - context = mock(InProcessEvaluationContext.class); - output = bundleFactory.createRootBundle(longs); - when(context.createRootBundle(longs)).thenReturn(output); - } - - @Test - public void unboundedSourceInMemoryTransformEvaluatorProducesElements() throws Exception { - TransformEvaluator evaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); - assertThat( - output.commit(Instant.now()).getElements(), - containsInAnyOrder( - tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), tgw(3L), - tgw(0L))); - } - - /** - * Demonstrate that multiple sequential creations will produce additional elements if the source - * can provide them. - */ - @Test - public void unboundedSourceInMemoryTransformEvaluatorMultipleSequentialCalls() throws Exception { - TransformEvaluator evaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - - InProcessTransformResult result = evaluator.finishBundle(); - assertThat( - result.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); - assertThat( - output.commit(Instant.now()).getElements(), - containsInAnyOrder( - tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), tgw(3L), - tgw(0L))); - - UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); - when(context.createRootBundle(longs)).thenReturn(secondOutput); - TransformEvaluator secondEvaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - InProcessTransformResult secondResult = secondEvaluator.finishBundle(); - assertThat( - secondResult.getWatermarkHold(), - Matchers.lessThan(DateTime.now().toInstant())); - assertThat( - secondOutput.commit(Instant.now()).getElements(), - containsInAnyOrder(tgw(11L), tgw(12L), tgw(14L), tgw(18L), tgw(19L), tgw(17L), tgw(16L), - tgw(15L), tgw(13L), tgw(10L))); - } - - @Test - public void unboundedSourceWithDuplicatesMultipleCalls() throws Exception { - Long[] outputs = new Long[20]; - for (long i = 0L; i < 20L; i++) { - outputs[(int) i] = i % 5L; - } - TestUnboundedSource source = - new TestUnboundedSource<>(BigEndianLongCoder.of(), outputs); - source.dedupes = true; - - TestPipeline p = TestPipeline.create(); - PCollection pcollection = p.apply(Read.from(source)); - AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - - UncommittedBundle output = bundleFactory.createRootBundle(pcollection); - when(context.createRootBundle(pcollection)).thenReturn(output); - TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); - - evaluator.finishBundle(); - assertThat( - output.commit(Instant.now()).getElements(), - containsInAnyOrder(tgw(1L), tgw(2L), tgw(4L), tgw(3L), tgw(0L))); - - UncommittedBundle secondOutput = bundleFactory.createRootBundle(longs); - when(context.createRootBundle(longs)).thenReturn(secondOutput); - TransformEvaluator secondEvaluator = factory.forApplication(sourceTransform, null, context); - secondEvaluator.finishBundle(); - assertThat( - secondOutput.commit(Instant.now()).getElements(), - Matchers.>emptyIterable()); - } - - @Test - public void evaluatorClosesReaderAfterOutputCount() throws Exception { - ContiguousSet elems = ContiguousSet.create( - Range.closed(0L, 20L * UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT), - DiscreteDomain.longs()); - TestUnboundedSource source = - new TestUnboundedSource<>(BigEndianLongCoder.of(), elems.toArray(new Long[0])); - - TestPipeline p = TestPipeline.create(); - PCollection pcollection = p.apply(Read.from(source)); - AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - - UncommittedBundle output = bundleFactory.createRootBundle(pcollection); - when(context.createRootBundle(pcollection)).thenReturn(output); - - for (int i = 0; i < UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT + 1; i++) { - TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); - evaluator.finishBundle(); - } - assertThat(TestUnboundedSource.readerClosedCount, equalTo(1)); - } - - @Test - public void evaluatorReusesReaderBeforeCount() throws Exception { - TestUnboundedSource source = - new TestUnboundedSource<>(BigEndianLongCoder.of(), 1L, 2L, 3L); - - TestPipeline p = TestPipeline.create(); - PCollection pcollection = p.apply(Read.from(source)); - AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - - UncommittedBundle output = bundleFactory.createRootBundle(pcollection); - when(context.createRootBundle(pcollection)).thenReturn(output); - - TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); - evaluator.finishBundle(); - CommittedBundle committed = output.commit(Instant.now()); - assertThat(ImmutableList.copyOf(committed.getElements()), hasSize(3)); - assertThat(TestUnboundedSource.readerClosedCount, equalTo(0)); - assertThat(TestUnboundedSource.readerAdvancedCount, equalTo(4)); - - evaluator = factory.forApplication(sourceTransform, null, context); - evaluator.finishBundle(); - assertThat(TestUnboundedSource.readerClosedCount, equalTo(0)); - // Tried to advance again, even with no elements - assertThat(TestUnboundedSource.readerAdvancedCount, equalTo(5)); - } - - @Test - public void evaluatorNoElementsReusesReaderAlways() throws Exception { - TestUnboundedSource source = new TestUnboundedSource<>(BigEndianLongCoder.of()); - - TestPipeline p = TestPipeline.create(); - PCollection pcollection = p.apply(Read.from(source)); - AppliedPTransform sourceTransform = pcollection.getProducingTransformInternal(); - - UncommittedBundle output = bundleFactory.createRootBundle(pcollection); - when(context.createRootBundle(pcollection)).thenReturn(output); - - for (int i = 0; i < 2 * UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT; i++) { - TransformEvaluator evaluator = factory.forApplication(sourceTransform, null, context); - evaluator.finishBundle(); - } - assertThat(TestUnboundedSource.readerClosedCount, equalTo(0)); - assertThat(TestUnboundedSource.readerAdvancedCount, - equalTo(2 * UnboundedReadEvaluatorFactory.MAX_READER_REUSE_COUNT)); - } - - // TODO: Once the source is split into multiple sources before evaluating, this test will have to - // be updated. - /** - * Demonstrate that only a single unfinished instance of TransformEvaluator can be created at a - * time, with other calls returning an empty evaluator. - */ - @Test - public void unboundedSourceWithMultipleSimultaneousEvaluatorsIndependent() throws Exception { - TransformEvaluator evaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - - TransformEvaluator secondEvaluator = - factory.forApplication(longs.getProducingTransformInternal(), null, context); - - assertThat(secondEvaluator, nullValue()); - InProcessTransformResult result = evaluator.finishBundle(); - - assertThat( - result.getWatermarkHold(), Matchers.lessThan(DateTime.now().toInstant())); - assertThat( - output.commit(Instant.now()).getElements(), - containsInAnyOrder( - tgw(1L), tgw(2L), tgw(4L), tgw(8L), tgw(9L), tgw(7L), tgw(6L), tgw(5L), tgw(3L), - tgw(0L))); - } - - /** - * A terse alias for producing timestamped longs in the {@link GlobalWindow}, where - * the timestamp is the epoch offset by the value of the element. - */ - private static WindowedValue tgw(Long elem) { - return WindowedValue.timestampedValueInGlobalWindow(elem, new Instant(elem)); - } - - private static class LongToInstantFn implements SerializableFunction { - @Override - public Instant apply(Long input) { - return new Instant(input); - } - } - - private static class TestUnboundedSource extends UnboundedSource { - static int readerClosedCount; - static int readerAdvancedCount; - private final Coder coder; - private final List elems; - private boolean dedupes = false; - - public TestUnboundedSource(Coder coder, T... elems) { - readerAdvancedCount = 0; - readerClosedCount = 0; - this.coder = coder; - this.elems = Arrays.asList(elems); - } - - @Override - public List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception { - return ImmutableList.of(this); - } - - @Override - public UnboundedSource.UnboundedReader createReader( - PipelineOptions options, TestCheckpointMark checkpointMark) { - return new TestUnboundedReader(elems); - } - - @Override - @Nullable - public Coder getCheckpointMarkCoder() { - return new TestCheckpointMark.Coder(); - } - - @Override - public boolean requiresDeduping() { - return dedupes; - } - - @Override - public void validate() {} - - @Override - public Coder getDefaultOutputCoder() { - return coder; - } - - private class TestUnboundedReader extends UnboundedReader { - private final List elems; - private int index; - - public TestUnboundedReader(List elems) { - this.elems = elems; - this.index = -1; - } - - @Override - public boolean start() throws IOException { - return advance(); - } - - @Override - public boolean advance() throws IOException { - readerAdvancedCount++; - if (index + 1 < elems.size()) { - index++; - return true; - } - return false; - } - - @Override - public Instant getWatermark() { - return Instant.now(); - } - - @Override - public CheckpointMark getCheckpointMark() { - return new TestCheckpointMark(); - } - - @Override - public UnboundedSource getCurrentSource() { - TestUnboundedSource source = TestUnboundedSource.this; - return source; - } - - @Override - public T getCurrent() throws NoSuchElementException { - return elems.get(index); - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - return new Instant(index); - } - - @Override - public byte[] getCurrentRecordId() { - try { - return CoderUtils.encodeToByteArray(coder, getCurrent()); - } catch (CoderException e) { - throw new RuntimeException(e); - } - } - - @Override - public void close() throws IOException { - readerClosedCount++; - } - } - } - - private static class TestCheckpointMark implements CheckpointMark { - @Override - public void finalizeCheckpoint() throws IOException {} - - public static class Coder extends AtomicCoder { - @Override - public void encode( - TestCheckpointMark value, - OutputStream outStream, - com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException {} - - @Override - public TestCheckpointMark decode( - InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws CoderException, IOException { - return new TestCheckpointMark(); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java deleted file mode 100644 index 26cafa74cc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/ViewEvaluatorFactoryTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.View.CreatePCollectionView; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.util.PCollectionViews; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link ViewEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class ViewEvaluatorFactoryTest { - private BundleFactory bundleFactory = InProcessBundleFactory.create(); - - @Test - public void testInMemoryEvaluator() throws Exception { - TestPipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of("foo", "bar")); - CreatePCollectionView> createView = - CreatePCollectionView.of( - PCollectionViews.iterableView(p, input.getWindowingStrategy(), StringUtf8Coder.of())); - PCollection> concat = - input.apply(WithKeys.of((Void) null)) - .setCoder(KvCoder.of(VoidCoder.of(), StringUtf8Coder.of())) - .apply(GroupByKey.create()) - .apply(Values.>create()); - PCollectionView> view = - concat.apply(new ViewEvaluatorFactory.WriteView<>(createView)); - - InProcessEvaluationContext context = mock(InProcessEvaluationContext.class); - TestViewWriter> viewWriter = new TestViewWriter<>(); - when(context.createPCollectionViewWriter(concat, view)).thenReturn(viewWriter); - - CommittedBundle inputBundle = - bundleFactory.createRootBundle(input).commit(Instant.now()); - TransformEvaluator> evaluator = - new ViewEvaluatorFactory() - .forApplication(view.getProducingTransformInternal(), inputBundle, context); - - evaluator.processElement( - WindowedValue.>valueInGlobalWindow(ImmutableList.of("foo", "bar"))); - assertThat(viewWriter.latest, nullValue()); - - evaluator.finishBundle(); - assertThat( - viewWriter.latest, - containsInAnyOrder( - WindowedValue.valueInGlobalWindow("foo"), WindowedValue.valueInGlobalWindow("bar"))); - } - - private static class TestViewWriter implements PCollectionViewWriter { - private Iterable> latest; - - @Override - public void add(Iterable> values) { - latest = values; - } - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java deleted file mode 100644 index 50d56abb04..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WatermarkCallbackExecutorTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link WatermarkCallbackExecutor}. - */ -@RunWith(JUnit4.class) -public class WatermarkCallbackExecutorTest { - private WatermarkCallbackExecutor executor = - WatermarkCallbackExecutor.create(Executors.newSingleThreadExecutor()); - private AppliedPTransform create; - private AppliedPTransform sum; - - @Before - public void setup() { - TestPipeline p = TestPipeline.create(); - PCollection created = p.apply(Create.of(1, 2, 3)); - create = created.getProducingTransformInternal(); - sum = created.apply(Sum.integersGlobally()).getProducingTransformInternal(); - } - - @Test - public void onGuaranteedFiringFiresAfterTrigger() throws Exception { - CountDownLatch latch = new CountDownLatch(1); - executor.callOnGuaranteedFiring( - create, - GlobalWindow.INSTANCE, - WindowingStrategy.globalDefault(), - new CountDownLatchCallback(latch)); - - executor.fireForWatermark(create, BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(true)); - } - - @Test - public void multipleCallbacksShouldFireFires() throws Exception { - CountDownLatch latch = new CountDownLatch(2); - WindowFn windowFn = FixedWindows.of(Duration.standardMinutes(10)); - IntervalWindow window = - new IntervalWindow(new Instant(0L), new Instant(0L).plus(Duration.standardMinutes(10))); - executor.callOnGuaranteedFiring( - create, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); - executor.callOnGuaranteedFiring( - create, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); - - executor.fireForWatermark(create, new Instant(0L).plus(Duration.standardMinutes(10))); - assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(true)); - } - - @Test - public void noCallbacksShouldFire() throws Exception { - CountDownLatch latch = new CountDownLatch(1); - WindowFn windowFn = FixedWindows.of(Duration.standardMinutes(10)); - IntervalWindow window = - new IntervalWindow(new Instant(0L), new Instant(0L).plus(Duration.standardMinutes(10))); - executor.callOnGuaranteedFiring( - create, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); - - executor.fireForWatermark(create, new Instant(0L).plus(Duration.standardMinutes(5))); - assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(false)); - } - - @Test - public void unrelatedStepShouldNotFire() throws Exception { - CountDownLatch latch = new CountDownLatch(1); - WindowFn windowFn = FixedWindows.of(Duration.standardMinutes(10)); - IntervalWindow window = - new IntervalWindow(new Instant(0L), new Instant(0L).plus(Duration.standardMinutes(10))); - executor.callOnGuaranteedFiring( - sum, window, WindowingStrategy.of(windowFn), new CountDownLatchCallback(latch)); - - executor.fireForWatermark(create, new Instant(0L).plus(Duration.standardMinutes(20))); - assertThat(latch.await(500, TimeUnit.MILLISECONDS), equalTo(false)); - } - - private static class CountDownLatchCallback implements Runnable { - private final CountDownLatch latch; - - public CountDownLatchCallback(CountDownLatch latch) { - this.latch = latch; - } - - @Override - public void run() { - latch.countDown(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java deleted file mode 100644 index e928c28559..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WindowEvaluatorFactoryTest.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link WindowEvaluatorFactory}. - */ -@RunWith(JUnit4.class) -public class WindowEvaluatorFactoryTest { - private static final Instant EPOCH = new Instant(0); - - private PCollection input; - private WindowEvaluatorFactory factory; - - @Mock private InProcessEvaluationContext evaluationContext; - - private BundleFactory bundleFactory; - - private WindowedValue first = - WindowedValue.timestampedValueInGlobalWindow(3L, new Instant(2L)); - private WindowedValue second = - WindowedValue.timestampedValueInGlobalWindow( - Long.valueOf(1L), EPOCH.plus(Duration.standardDays(3))); - private WindowedValue third = - WindowedValue.of( - Long.valueOf(2L), - new Instant(-10L), - new IntervalWindow(new Instant(-100), EPOCH), - PaneInfo.NO_FIRING); - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - TestPipeline p = TestPipeline.create(); - input = p.apply(Create.of(1L, 2L, 3L)); - - bundleFactory = InProcessBundleFactory.create(); - factory = new WindowEvaluatorFactory(); - } - - @Test - public void nullWindowFunSucceeds() throws Exception { - Bound transform = - Window.triggering( - AfterWatermark.pastEndOfWindow().withEarlyFirings(AfterPane.elementCountAtLeast(1))) - .accumulatingFiredPanes(); - PCollection triggering = input.apply(transform); - - CommittedBundle inputBundle = createInputBundle(); - - UncommittedBundle outputBundle = createOutputBundle(triggering, inputBundle); - - InProcessTransformResult result = runEvaluator(triggering, inputBundle, transform); - - assertThat( - Iterables.getOnlyElement(result.getOutputBundles()), - Matchers.>equalTo(outputBundle)); - CommittedBundle committed = outputBundle.commit(Instant.now()); - assertThat(committed.getElements(), containsInAnyOrder(third, first, second)); - } - - @Test - public void singleWindowFnSucceeds() throws Exception { - Duration windowDuration = Duration.standardDays(7); - Bound transform = Window.into(FixedWindows.of(windowDuration)); - PCollection windowed = input.apply(transform); - - CommittedBundle inputBundle = createInputBundle(); - - UncommittedBundle outputBundle = createOutputBundle(windowed, inputBundle); - - BoundedWindow firstSecondWindow = new IntervalWindow(EPOCH, EPOCH.plus(windowDuration)); - BoundedWindow thirdWindow = new IntervalWindow(EPOCH.minus(windowDuration), EPOCH); - - InProcessTransformResult result = runEvaluator(windowed, inputBundle, transform); - - assertThat( - Iterables.getOnlyElement(result.getOutputBundles()), - Matchers.>equalTo(outputBundle)); - CommittedBundle committed = outputBundle.commit(Instant.now()); - - WindowedValue expectedNewFirst = - WindowedValue.of(3L, new Instant(2L), firstSecondWindow, PaneInfo.NO_FIRING); - WindowedValue expectedNewSecond = - WindowedValue.of( - 1L, EPOCH.plus(Duration.standardDays(3)), firstSecondWindow, PaneInfo.NO_FIRING); - WindowedValue expectedNewThird = - WindowedValue.of(2L, new Instant(-10L), thirdWindow, PaneInfo.NO_FIRING); - assertThat( - committed.getElements(), - containsInAnyOrder(expectedNewFirst, expectedNewSecond, expectedNewThird)); - } - - @Test - public void multipleWindowsWindowFnSucceeds() throws Exception { - Duration windowDuration = Duration.standardDays(6); - Duration slidingBy = Duration.standardDays(3); - Bound transform = Window.into(SlidingWindows.of(windowDuration).every(slidingBy)); - PCollection windowed = input.apply(transform); - - CommittedBundle inputBundle = createInputBundle(); - UncommittedBundle outputBundle = createOutputBundle(windowed, inputBundle); - - InProcessTransformResult result = runEvaluator(windowed, inputBundle, transform); - - assertThat( - Iterables.getOnlyElement(result.getOutputBundles()), - Matchers.>equalTo(outputBundle)); - CommittedBundle committed = outputBundle.commit(Instant.now()); - - BoundedWindow w1 = new IntervalWindow(EPOCH, EPOCH.plus(windowDuration)); - BoundedWindow w2 = - new IntervalWindow(EPOCH.plus(slidingBy), EPOCH.plus(slidingBy).plus(windowDuration)); - BoundedWindow wMinus1 = new IntervalWindow(EPOCH.minus(windowDuration), EPOCH); - BoundedWindow wMinusSlide = - new IntervalWindow(EPOCH.minus(windowDuration).plus(slidingBy), EPOCH.plus(slidingBy)); - - WindowedValue expectedFirst = - WindowedValue.of( - first.getValue(), - first.getTimestamp(), - ImmutableSet.of(w1, wMinusSlide), - PaneInfo.NO_FIRING); - WindowedValue expectedSecond = - WindowedValue.of( - second.getValue(), second.getTimestamp(), ImmutableSet.of(w1, w2), PaneInfo.NO_FIRING); - WindowedValue expectedThird = - WindowedValue.of( - third.getValue(), - third.getTimestamp(), - ImmutableSet.of(wMinus1, wMinusSlide), - PaneInfo.NO_FIRING); - - assertThat( - committed.getElements(), containsInAnyOrder(expectedFirst, expectedSecond, expectedThird)); - } - - private CommittedBundle createInputBundle() { - CommittedBundle inputBundle = - bundleFactory - .createRootBundle(input) - .add(first) - .add(second) - .add(third) - .commit(Instant.now()); - return inputBundle; - } - - private UncommittedBundle createOutputBundle( - PCollection output, CommittedBundle inputBundle) { - UncommittedBundle outputBundle = bundleFactory.createBundle(inputBundle, output); - when(evaluationContext.createBundle(inputBundle, output)).thenReturn(outputBundle); - return outputBundle; - } - - private InProcessTransformResult runEvaluator( - PCollection windowed, - CommittedBundle inputBundle, - Window.Bound windowTransform /* Required while Window.Bound is a composite */) - throws Exception { - TransformEvaluator evaluator = - factory.forApplication( - AppliedPTransform.of("Window", input, windowed, windowTransform), - inputBundle, - evaluationContext); - - evaluator.processElement(first); - evaluator.processElement(second); - evaluator.processElement(third); - InProcessTransformResult result = evaluator.finishBundle(); - return result; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java deleted file mode 100644 index 96fa6bffcb..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/inprocess/WriteWithShardingFactoryTest.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.runners.inprocess; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.io.Sink; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.Write; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.inprocess.WriteWithShardingFactory.KeyBasedOnCountFn; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.IOChannelUtils; -import com.google.cloud.dataflow.sdk.util.PCollectionViews; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.File; -import java.io.FileReader; -import java.io.Reader; -import java.nio.CharBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; - -/** - * Tests for {@link WriteWithShardingFactory}. - */ -@RunWith(JUnit4.class) -public class WriteWithShardingFactoryTest { - public static final int INPUT_SIZE = 10000; - @Rule public TemporaryFolder tmp = new TemporaryFolder(); - private WriteWithShardingFactory factory = new WriteWithShardingFactory(); - - @Test - public void dynamicallyReshardedWrite() throws Exception { - List strs = new ArrayList<>(INPUT_SIZE); - for (int i = 0; i < INPUT_SIZE; i++) { - strs.add(UUID.randomUUID().toString()); - } - Collections.shuffle(strs); - - String fileName = "resharded_write"; - String outputPath = tmp.getRoot().getAbsolutePath(); - String targetLocation = IOChannelUtils.resolve(outputPath, fileName); - PipelineOptions testOptions = TestPipeline.testingPipelineOptions(); - testOptions.setRunner(InProcessPipelineRunner.class); - Pipeline p = Pipeline.create(testOptions); - // TextIO is implemented in terms of the Write PTransform. When sharding is not specified, - // resharding should be automatically applied - p.apply(Create.of(strs)).apply(TextIO.Write.to(targetLocation)); - - p.run(); - - Collection files = IOChannelUtils.getFactory(outputPath).match(targetLocation + "*"); - List actuals = new ArrayList<>(strs.size()); - for (String file : files) { - CharBuffer buf = CharBuffer.allocate((int) new File(file).length()); - try (Reader reader = new FileReader(file)) { - reader.read(buf); - buf.flip(); - } - - String[] readStrs = buf.toString().split("\n"); - for (String read : readStrs) { - if (read.length() > 0) { - actuals.add(read); - } - } - } - - assertThat(actuals, containsInAnyOrder(strs.toArray())); - assertThat( - files, - hasSize( - allOf( - greaterThan(1), - lessThan( - (int) - (Math.log10(INPUT_SIZE) - + WriteWithShardingFactory.MAX_RANDOM_EXTRA_SHARDS))))); - } - - @Test - public void withShardingSpecifiesOriginalTransform() { - PTransform, PDone> original = Write.to(new TestSink()).withNumShards(3); - - assertThat(factory.override(original), equalTo(original)); - } - - @Test - public void withNonWriteReturnsOriginalTransform() { - PTransform, PDone> original = - new PTransform, PDone>() { - @Override - public PDone apply(PCollection input) { - return PDone.in(input.getPipeline()); - } - }; - - assertThat(factory.override(original), equalTo(original)); - } - - @Test - public void withNoShardingSpecifiedReturnsNewTransform() { - PTransform, PDone> original = Write.to(new TestSink()); - assertThat(factory.override(original), not(equalTo(original))); - } - - @Test - public void keyBasedOnCountFnWithOneElement() throws Exception { - PCollectionView elementCountView = - PCollectionViews.singletonView( - TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); - KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); - DoFnTester> fnTester = DoFnTester.of(fn); - - fnTester.setSideInput(elementCountView, - Collections.>singleton(WindowedValue.valueInGlobalWindow(1L))); - - List> outputs = fnTester.processBatch("foo", "bar", "bazbar"); - assertThat( - outputs, containsInAnyOrder(KV.of(0, "foo"), KV.of(0, "bar"), KV.of(0, "bazbar"))); - } - - @Test - public void keyBasedOnCountFnWithTwoElements() throws Exception { - PCollectionView elementCountView = - PCollectionViews.singletonView( - TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); - KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); - DoFnTester> fnTester = DoFnTester.of(fn); - - fnTester.setSideInput(elementCountView, - Collections.>singleton(WindowedValue.valueInGlobalWindow(2L))); - - List> outputs = fnTester.processBatch("foo", "bar"); - assertThat( - outputs, - anyOf( - containsInAnyOrder(KV.of(0, "foo"), KV.of(1, "bar")), - containsInAnyOrder(KV.of(1, "foo"), KV.of(0, "bar")))); - } - - @Test - public void keyBasedOnCountFnFewElementsThreeShards() throws Exception { - PCollectionView elementCountView = - PCollectionViews.singletonView( - TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); - KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); - DoFnTester> fnTester = DoFnTester.of(fn); - - fnTester.setSideInput(elementCountView, - Collections.>singleton(WindowedValue.valueInGlobalWindow(100L))); - - List> outputs = - fnTester.processBatch("foo", "bar", "baz", "foobar", "foobaz", "barbaz"); - assertThat( - Iterables.transform( - outputs, - new Function, Integer>() { - @Override - public Integer apply(KV input) { - return input.getKey(); - } - }), - containsInAnyOrder(0, 0, 1, 1, 2, 2)); - } - - @Test - public void keyBasedOnCountFnManyElements() throws Exception { - PCollectionView elementCountView = - PCollectionViews.singletonView( - TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); - KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 0); - DoFnTester> fnTester = DoFnTester.of(fn); - - double count = Math.pow(10, 10); - fnTester.setSideInput(elementCountView, - Collections.>singleton(WindowedValue.valueInGlobalWindow((long) count))); - - List strings = new ArrayList<>(); - for (int i = 0; i < 100; i++) { - strings.add(Long.toHexString(ThreadLocalRandom.current().nextLong())); - } - List> kvs = fnTester.processBatch(strings); - long maxKey = -1L; - for (KV kv : kvs) { - maxKey = Math.max(maxKey, kv.getKey()); - } - assertThat(maxKey, equalTo(9L)); - } - - @Test - public void keyBasedOnCountFnFewElementsExtraShards() throws Exception { - PCollectionView elementCountView = - PCollectionViews.singletonView( - TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); - KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 10); - DoFnTester> fnTester = DoFnTester.of(fn); - - long countValue = (long) KeyBasedOnCountFn.MIN_SHARDS_FOR_LOG + 3; - fnTester.setSideInput(elementCountView, - Collections.>singleton(WindowedValue.valueInGlobalWindow(countValue))); - - List strings = new ArrayList<>(); - for (int i = 0; i < 100; i++) { - strings.add(Long.toHexString(ThreadLocalRandom.current().nextLong())); - } - List> kvs = fnTester.processBatch(strings); - long maxKey = -1L; - for (KV kv : kvs) { - maxKey = Math.max(maxKey, kv.getKey()); - } - // 0 to n-1 shard ids. - assertThat(maxKey, equalTo(countValue - 1)); - } - - @Test - public void keyBasedOnCountFnManyElementsExtraShards() throws Exception { - PCollectionView elementCountView = - PCollectionViews.singletonView( - TestPipeline.create(), WindowingStrategy.globalDefault(), true, 0L, VarLongCoder.of()); - KeyBasedOnCountFn fn = new KeyBasedOnCountFn<>(elementCountView, 3); - DoFnTester> fnTester = DoFnTester.of(fn); - - double count = Math.pow(10, 10); - fnTester.setSideInput(elementCountView, - Collections.>singleton(WindowedValue.valueInGlobalWindow((long) count))); - - List strings = new ArrayList<>(); - for (int i = 0; i < 100; i++) { - strings.add(Long.toHexString(ThreadLocalRandom.current().nextLong())); - } - List> kvs = fnTester.processBatch(strings); - long maxKey = -1L; - for (KV kv : kvs) { - maxKey = Math.max(maxKey, kv.getKey()); - } - assertThat(maxKey, equalTo(12L)); - } - - private static class TestSink extends Sink { - @Override - public void validate(PipelineOptions options) {} - - @Override - public WriteOperation createWriteOperation(PipelineOptions options) { - throw new IllegalArgumentException("Should not be used"); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java deleted file mode 100644 index 4564d95fc3..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/CoderPropertiesTest.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CustomCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.common.base.Strings; - -import org.hamcrest.CoreMatchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** Unit tests for {@link CoderProperties}. */ -@RunWith(JUnit4.class) -public class CoderPropertiesTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testGoodCoderIsDeterministic() throws Exception { - CoderProperties.coderDeterministic(StringUtf8Coder.of(), "TestData", "TestData"); - } - - /** A coder that says it is not deterministic but actually is. */ - public static class NonDeterministicCoder extends CustomCoder { - @Override - public void encode(String value, OutputStream outStream, Context context) - throws CoderException, IOException { - StringUtf8Coder.of().encode(value, outStream, context); - } - - @Override - public String decode(InputStream inStream, Context context) - throws CoderException, IOException { - return StringUtf8Coder.of().decode(inStream, context); - } - } - - @Test - public void testNonDeterministicCoder() throws Exception { - try { - CoderProperties.coderDeterministic(new NonDeterministicCoder(), "TestData", "TestData"); - fail("Expected AssertionError"); - } catch (AssertionError error) { - assertThat(error.getMessage(), - CoreMatchers.containsString("Expected that the coder is deterministic")); - } - } - - @Test - public void testPassingInNonEqualValuesWithDeterministicCoder() throws Exception { - try { - CoderProperties.coderDeterministic(StringUtf8Coder.of(), "AAA", "BBB"); - fail("Expected AssertionError"); - } catch (AssertionError error) { - assertThat(error.getMessage(), - CoreMatchers.containsString("Expected that the passed in values")); - } - } - - /** A coder that is non-deterministic because it adds a string to the value. */ - private static class BadDeterminsticCoder extends CustomCoder { - public BadDeterminsticCoder() { - } - - @Override - public void encode(String value, OutputStream outStream, Context context) - throws IOException, CoderException { - StringUtf8Coder.of().encode(value + System.nanoTime(), outStream, context); - } - - @Override - public String decode(InputStream inStream, Context context) - throws CoderException, IOException { - return StringUtf8Coder.of().decode(inStream, context); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { } - } - - @Test - public void testBadCoderIsNotDeterministic() throws Exception { - try { - CoderProperties.coderDeterministic(new BadDeterminsticCoder(), "TestData", "TestData"); - fail("Expected AssertionError"); - } catch (AssertionError error) { - assertThat(error.getMessage(), - CoreMatchers.containsString("<84>, <101>, <115>, <116>, <68>")); - } - } - - @Test - public void testGoodCoderEncodesEqualValues() throws Exception { - CoderProperties.coderDecodeEncodeEqual(StringUtf8Coder.of(), "TestData"); - } - - /** This coder changes state during encoding/decoding. */ - private static class StateChangingSerializingCoder extends CustomCoder { - private int changedState; - - public StateChangingSerializingCoder() { - changedState = 10; - } - - @Override - public void encode(String value, OutputStream outStream, Context context) - throws CoderException, IOException { - changedState += 1; - StringUtf8Coder.of().encode(value + Strings.repeat("A", changedState), outStream, context); - } - - @Override - public String decode(InputStream inStream, Context context) - throws CoderException, IOException { - String decodedValue = StringUtf8Coder.of().decode(inStream, context); - return decodedValue.substring(0, decodedValue.length() - changedState); - } - } - - @Test - public void testBadCoderThatDependsOnChangingState() throws Exception { - try { - CoderProperties.coderDecodeEncodeEqual(new StateChangingSerializingCoder(), "TestData"); - fail("Expected AssertionError"); - } catch (AssertionError error) { - assertThat(error.getMessage(), CoreMatchers.containsString("TestData")); - } - } - - /** This coder loses information critical to its operation. */ - private static class ForgetfulSerializingCoder extends CustomCoder { - private transient int lostState; - - public ForgetfulSerializingCoder(int lostState) { - this.lostState = lostState; - } - - @Override - public void encode(String value, OutputStream outStream, Context context) - throws CoderException, IOException { - if (lostState == 0) { - throw new RuntimeException("I forgot something..."); - } - StringUtf8Coder.of().encode(value, outStream, context); - } - - @Override - public String decode(InputStream inStream, Context context) - throws CoderException, IOException { - return StringUtf8Coder.of().decode(inStream, context); - } - } - - @Test - public void testBadCoderThatDependsOnStateThatIsLost() throws Exception { - expectedException.expect(RuntimeException.class); - expectedException.expectMessage("I forgot something..."); - CoderProperties.coderDecodeEncodeEqual(new ForgetfulSerializingCoder(1), "TestData"); - } - - /** A coder which closes the underlying stream during encoding and decoding. */ - public static class ClosingCoder extends CustomCoder { - @Override - public void encode(String value, OutputStream outStream, Context context) throws IOException { - outStream.close(); - } - - @Override - public String decode(InputStream inStream, Context context) throws IOException { - inStream.close(); - return null; - } - } - - @Test - public void testClosingCoderFailsWhenDecoding() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderProperties.decode(new ClosingCoder(), Context.NESTED, new byte[0]); - } - - @Test - public void testClosingCoderFailsWhenEncoding() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderProperties.encode(new ClosingCoder(), Context.NESTED, "test-value"); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java deleted file mode 100644 index c055d2d819..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowAssertTest.java +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.collect.Iterables; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; - -/** - * Test case for {@link DataflowAssert}. - */ -@RunWith(JUnit4.class) -public class DataflowAssertTest implements Serializable { - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - private static class NotSerializableObject { - - @Override - public boolean equals(Object other) { - return (other instanceof NotSerializableObject); - } - - @Override - public int hashCode() { - return 73; - } - } - - private static class NotSerializableObjectCoder extends AtomicCoder { - private NotSerializableObjectCoder() { } - private static final NotSerializableObjectCoder INSTANCE = new NotSerializableObjectCoder(); - - @JsonCreator - public static NotSerializableObjectCoder of() { - return INSTANCE; - } - - @Override - public void encode(NotSerializableObject value, OutputStream outStream, Context context) - throws CoderException, IOException { - } - - @Override - public NotSerializableObject decode(InputStream inStream, Context context) - throws CoderException, IOException { - return new NotSerializableObject(); - } - - @Override - public boolean isRegisterByteSizeObserverCheap(NotSerializableObject value, Context context) { - return true; - } - - @Override - public void registerByteSizeObserver( - NotSerializableObject value, ElementByteSizeObserver observer, Context context) - throws Exception { - observer.update(0L); - } - } - - /** - * A {@link DataflowAssert} about the contents of a {@link PCollection} - * must not require the contents of the {@link PCollection} to be - * serializable. - */ - @Test - @Category(RunnableOnService.class) - public void testContainsInAnyOrderNotSerializable() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection pcollection = pipeline - .apply(Create.of( - new NotSerializableObject(), - new NotSerializableObject()) - .withCoder(NotSerializableObjectCoder.of())); - - DataflowAssert.that(pcollection).containsInAnyOrder( - new NotSerializableObject(), - new NotSerializableObject()); - - pipeline.run(); - } - - /** - * A {@link DataflowAssert} about the contents of a {@link PCollection} - * is allows to be verified by an arbitrary {@link SerializableFunction}, - * though. - */ - @Test - @Category(RunnableOnService.class) - public void testSerializablePredicate() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection pcollection = pipeline - .apply(Create.of( - new NotSerializableObject(), - new NotSerializableObject()) - .withCoder(NotSerializableObjectCoder.of())); - - DataflowAssert.that(pcollection).satisfies( - new SerializableFunction, Void>() { - @Override - public Void apply(Iterable contents) { - return null; // no problem! - } - }); - - pipeline.run(); - } - - /** - * A {@link DataflowAssert} about the contents of a {@link PCollection} - * is allows to be verified by an arbitrary {@link SerializableFunction}, - * though. - */ - @Test - @Category(RunnableOnService.class) - public void testWindowedSerializablePredicate() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection pcollection = pipeline - .apply(Create.timestamped( - TimestampedValue.of(new NotSerializableObject(), new Instant(250L)), - TimestampedValue.of(new NotSerializableObject(), new Instant(500L))) - .withCoder(NotSerializableObjectCoder.of())) - .apply(Window.into(FixedWindows.of(Duration.millis(300L)))); - - DataflowAssert.that(pcollection) - .inWindow(new IntervalWindow(new Instant(0L), new Instant(300L))) - .satisfies(new SerializableFunction, Void>() { - @Override - public Void apply(Iterable contents) { - assertThat(Iterables.isEmpty(contents), is(false)); - return null; // no problem! - } - }); - DataflowAssert.that(pcollection) - .inWindow(new IntervalWindow(new Instant(300L), new Instant(600L))) - .satisfies(new SerializableFunction, Void>() { - @Override - public Void apply(Iterable contents) { - assertThat(Iterables.isEmpty(contents), is(false)); - return null; // no problem! - } - }); - - pipeline.run(); - } - - @Test - @SuppressWarnings("deprecation") - public void testContainsInAnyOrderIterableView() { - Pipeline p = TestPipeline.create(); - PCollectionView> iterableView = - p.apply(Create.of(1, 2, 3, 4)).apply(View.asIterable()); - - DataflowAssert.thatIterable(iterableView).containsInAnyOrder(4, 3, 2, 1); - p.run(); - } - - /** - * Test that we throw an error at pipeline construction time when the user mistakenly uses - * {@code DataflowAssert.thatSingleton().equals()} instead of the test method {@code .isEqualTo}. - */ - @SuppressWarnings("deprecation") // test of deprecated function - @Test - public void testDataflowAssertEqualsSingletonUnsupported() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("isEqualTo"); - - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(42)); - DataflowAssert.thatSingleton(pcollection).equals(42); - } - - /** - * Test that we throw an error at pipeline construction time when the user mistakenly uses - * {@code DataflowAssert.that().equals()} instead of the test method {@code .containsInAnyOrder}. - */ - @SuppressWarnings("deprecation") // test of deprecated function - @Test - public void testDataflowAssertEqualsIterableUnsupported() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("containsInAnyOrder"); - - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(42)); - DataflowAssert.that(pcollection).equals(42); - } - - /** - * Test that {@code DataflowAssert.thatSingleton().hashCode()} is unsupported. - * See {@link #testDataflowAssertEqualsSingletonUnsupported}. - */ - @SuppressWarnings("deprecation") // test of deprecated function - @Test - public void testDataflowAssertHashCodeSingletonUnsupported() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage(".hashCode() is not supported."); - - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(42)); - DataflowAssert.thatSingleton(pcollection).hashCode(); - } - - /** - * Test that {@code DataflowAssert.thatIterable().hashCode()} is unsupported. - * See {@link #testDataflowAssertEqualsIterableUnsupported}. - */ - @SuppressWarnings("deprecation") // test of deprecated function - @Test - public void testDataflowAssertHashCodeIterableUnsupported() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage(".hashCode() is not supported."); - - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(42)); - DataflowAssert.that(pcollection).hashCode(); - } - - /** - * Basic test for {@code isEqualTo}. - */ - @Test - @Category(RunnableOnService.class) - public void testIsEqualTo() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(43)); - DataflowAssert.thatSingleton(pcollection).isEqualTo(43); - pipeline.run(); - } - - /** - * Basic test for {@code isEqualTo}. - */ - @Test - @Category(RunnableOnService.class) - public void testWindowedIsEqualTo() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = - pipeline.apply(Create.timestamped(TimestampedValue.of(43, new Instant(250L)), - TimestampedValue.of(22, new Instant(-250L)))) - .apply(Window.into(FixedWindows.of(Duration.millis(500L)))); - DataflowAssert.thatSingleton(pcollection) - .inOnlyPane(new IntervalWindow(new Instant(0L), new Instant(500L))) - .isEqualTo(43); - DataflowAssert.thatSingleton(pcollection) - .inOnlyPane(new IntervalWindow(new Instant(-500L), new Instant(0L))) - .isEqualTo(22); - pipeline.run(); - } - - /** - * Basic test for {@code notEqualTo}. - */ - @Test - @Category(RunnableOnService.class) - public void testNotEqualTo() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(43)); - DataflowAssert.thatSingleton(pcollection).notEqualTo(42); - pipeline.run(); - } - - /** - * Tests that {@code containsInAnyOrder} is actually order-independent. - */ - @Test - @Category(RunnableOnService.class) - public void testContainsInAnyOrder() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(1, 2, 3, 4)); - DataflowAssert.that(pcollection).containsInAnyOrder(2, 1, 4, 3); - pipeline.run(); - } - - /** - * Tests that {@code containsInAnyOrder} is actually order-independent. - */ - @Test - @Category(RunnableOnService.class) - public void testGlobalWindowContainsInAnyOrder() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = pipeline.apply(Create.of(1, 2, 3, 4)); - DataflowAssert.that(pcollection).inWindow(GlobalWindow.INSTANCE).containsInAnyOrder(2, 1, 4, 3); - pipeline.run(); - } - - /** - * Tests that windowed {@code containsInAnyOrder} is actually order-independent. - */ - @Test - @Category(RunnableOnService.class) - public void testWindowedContainsInAnyOrder() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection pcollection = - pipeline.apply(Create.timestamped(TimestampedValue.of(1, new Instant(100L)), - TimestampedValue.of(2, new Instant(200L)), - TimestampedValue.of(3, new Instant(300L)), - TimestampedValue.of(4, new Instant(400L)))) - .apply(Window.into(SlidingWindows.of(Duration.millis(200L)) - .every(Duration.millis(100L)) - .withOffset(Duration.millis(50L)))); - - DataflowAssert.that(pcollection) - .inWindow(new IntervalWindow(new Instant(-50L), new Instant(150L))).containsInAnyOrder(1); - DataflowAssert.that(pcollection) - .inWindow(new IntervalWindow(new Instant(50L), new Instant(250L))) - .containsInAnyOrder(2, 1); - DataflowAssert.that(pcollection) - .inWindow(new IntervalWindow(new Instant(150L), new Instant(350L))) - .containsInAnyOrder(2, 3); - DataflowAssert.that(pcollection) - .inWindow(new IntervalWindow(new Instant(250L), new Instant(450L))) - .containsInAnyOrder(4, 3); - DataflowAssert.that(pcollection) - .inWindow(new IntervalWindow(new Instant(350L), new Instant(550L))) - .containsInAnyOrder(4); - pipeline.run(); - } - - /** - * Tests that {@code containsInAnyOrder} fails when and how it should. - */ - @Test - @Category(RunnableOnService.class) - public void testContainsInAnyOrderFalse() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection pcollection = pipeline - .apply(Create.of(1, 2, 3, 4)); - - DataflowAssert.that(pcollection).containsInAnyOrder(2, 1, 4, 3, 7); - - // The service runner does not give an exception we can usefully inspect. - @Nullable - Throwable exc = runExpectingAssertionFailure(pipeline); - Pattern expectedPattern = Pattern.compile( - "Expected: iterable over \\[((<4>|<7>|<3>|<2>|<1>)(, )?){5}\\] in any order"); - if (exc != null) { - // A loose pattern, but should get the job done. - assertTrue("Expected error message from DataflowAssert with substring matching " - + expectedPattern + " but the message was \"" + exc.getMessage() + "\"", - expectedPattern.matcher(exc.getMessage()).find()); - } - } - - private static Throwable runExpectingAssertionFailure(Pipeline pipeline) { - // Even though this test will succeed or fail adequately whether local or on the service, - // it results in a different exception depending on the runner. - if (pipeline.getRunner() instanceof DirectPipelineRunner - || pipeline.getRunner() instanceof InProcessPipelineRunner) { - // We cannot use thrown.expect(AssertionError.class) because the AssertionError - // is first caught by JUnit and causes a test failure. - try { - pipeline.run(); - } catch (AssertionError exc) { - return exc; - } - } else if (pipeline.getRunner() instanceof TestDataflowPipelineRunner) { - // Separately, if this is run on the service, then the TestDataflowPipelineRunner throws - // an IllegalStateException with a basic message. - try { - pipeline.run(); - } catch (IllegalStateException exc) { - assertThat(exc.getMessage(), containsString("The dataflow failed.")); - return null; - } - } - fail("assertion should have failed"); - throw new RuntimeException("unreachable"); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowJUnitTestRunner.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowJUnitTestRunner.java deleted file mode 100644 index fb8918fa77..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/DataflowJUnitTestRunner.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.reflect.ClassPath; -import com.google.common.reflect.ClassPath.ClassInfo; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Request; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * A test runner which can invoke a series of method or class test targets configuring - * the {@link TestPipeline} to run against the Dataflow service based upon command-line - * parameters specified. - * - *

              Supported target definitions as command line parameters are: - *

                - *
              • Class: "ClassName" - *
              • Method: "ClassName#methodName" - *
              - * Multiple parameters can be specified in sequence, which will cause the test - * runner to invoke the tests in the specified order. - * - *

              All tests will be executed after which, if any test had failed, the runner - * will exit with a non-zero status code. - */ -public class DataflowJUnitTestRunner { - private static final Logger LOG = LoggerFactory.getLogger(DataflowJUnitTestRunner.class); - - /** - * Options which control a Dataflow JUnit test runner to invoke - * a series of method and/or class targets. - */ - @Description("Options which control a Dataflow JUnit test runner to invoke " - + "a series of method and/or class targets.") - public interface Options extends PipelineOptions { - @Description("A list of supported test targets. Supported targets are 'ClassName' " - + "or 'ClassName#MethodName'") - @Validation.Required - String[] getTest(); - void setTest(String[] values); - } - - public static void main(String ... args) throws Exception { - PipelineOptionsFactory.register(Options.class); - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Set classes = - ClassPath.from(ClassLoader.getSystemClassLoader()).getAllClasses(); - - // Build a list of requested test targets - List requests = new ArrayList<>(); - for (String testTarget : options.getTest()) { - if (testTarget.contains("#")) { - String[] parts = testTarget.split("#", 2); - Class klass = findClass(parts[0], classes); - requests.add(Request.method(klass, parts[1])); - } else { - requests.add(Request.aClass(findClass(testTarget, classes))); - } - } - - // Set system properties required by TestPipeline so that it is able to execute tests - // on the service. - String dataflowPipelineOptions = new ObjectMapper().writeValueAsString(args); - System.setProperty("runIntegrationTestOnService", "true"); - System.setProperty("dataflowOptions", dataflowPipelineOptions); - - // Run the set of tests - boolean success = true; - JUnitCore core = new JUnitCore(); - for (Request request : requests) { - Result result = core.run(request); - if (!result.wasSuccessful()) { - for (Failure failure : result.getFailures()) { - LOG.error(failure.getTestHeader(), failure.getException()); - } - success = false; - } - } - if (!success) { - throw new IllegalStateException("Tests failed, check output logs for details."); - } - } - - private static Class findClass( - final String simpleName, Set classes) - throws ClassNotFoundException { - Iterable matches = - Iterables.filter(classes, new Predicate() { - @Override - public boolean apply(@Nullable ClassInfo input) { - return input != null && simpleName.equals(input.getSimpleName()); - } - }); - return Class.forName(Iterables.getOnlyElement(matches).getName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogs.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogs.java deleted file mode 100644 index 48449b3400..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogs.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.fail; - -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.rules.ExternalResource; -import org.junit.rules.TestRule; - -import java.util.Collection; -import java.util.concurrent.ConcurrentLinkedDeque; -import java.util.logging.Formatter; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; - -import javax.annotation.concurrent.ThreadSafe; - -/** - * This {@link TestRule} enables the ability to capture JUL logging events during test execution and - * assert expectations that they contain certain messages (with or without {@link Throwable}) at - * certain log levels. For logs generated via the SLF4J logging frontend, the JUL backend must be - * used. - */ -public class ExpectedLogs extends ExternalResource { - /** - * Returns a {@link TestRule} that captures logs for the given logger name. - * - * @param name The logger name to capture logs for. - * @return A {@link ExpectedLogs} test rule. - */ - public static ExpectedLogs none(String name) { - return new ExpectedLogs(name); - } - - /** - * Returns a {@link TestRule} that captures logs for the given class. - * - * @param klass The class to capture logs for. - * @return A {@link ExpectedLogs} test rule. - */ - public static ExpectedLogs none(Class klass) { - return ExpectedLogs.none(klass.getName()); - } - - /** - * Verify a logging event at the trace level with the given message. - * - * @param substring The message to match against. - */ - public void verifyTrace(String substring) { - verify(Level.FINEST, substring); - } - - /** - * Verify a logging event at the trace level with the given message and throwable. - * - * @param substring The message to match against. - * @param t The throwable to match against. - */ - public void verifyTrace(String substring, Throwable t) { - verify(Level.FINEST, substring, t); - } - - /** - * Verify a logging event at the debug level with the given message. - * - * @param substring The message to match against. - */ - public void verifyDebug(String substring) { - verify(Level.FINE, substring); - } - - /** - * Verify a logging event at the debug level with the given message and throwable. - * - * @param message The message to match against. - * @param t The throwable to match against. - */ - public void verifyDebug(String message, Throwable t) { - verify(Level.FINE, message, t); - } - - /** - * Verify a logging event at the info level with the given message. - * - * @param substring The message to match against. - */ - public void verifyInfo(String substring) { - verify(Level.INFO, substring); - } - - /** - * Verify a logging event at the info level with the given message and throwable. - * - * @param message The message to match against. - * @param t The throwable to match against. - */ - public void verifyInfo(String message, Throwable t) { - verify(Level.INFO, message, t); - } - - /** - * Verify a logging event at the warn level with the given message. - * - * @param substring The message to match against. - */ - public void verifyWarn(String substring) { - verify(Level.WARNING, substring); - } - - /** - * Verify a logging event at the warn level with the given message and throwable. - * - * @param substring The message to match against. - * @param t The throwable to match against. - */ - public void verifyWarn(String substring, Throwable t) { - verify(Level.WARNING, substring, t); - } - - /** - * Verify a logging event at the error level with the given message. - * - * @param substring The message to match against. - */ - public void verifyError(String substring) { - verify(Level.SEVERE, substring); - } - - /** - * Verify a logging event at the error level with the given message and throwable. - * - * @param substring The message to match against. - * @param t The throwable to match against. - */ - public void verifyError(String substring, Throwable t) { - verify(Level.SEVERE, substring, t); - } - - /** - * Verify there are no logging events with messages containing the given substring. - * - * @param substring The message to match against. - */ - public void verifyNotLogged(String substring) { - verifyNotLogged(matcher(substring)); - } - - /** - * Verify there is no logging event at the error level with the given message and throwable. - * - * @param substring The message to match against. - * @param t The throwable to match against. - */ - public void verifyNoError(String substring, Throwable t) { - verifyNo(Level.SEVERE, substring, t); - } - - private void verify(final Level level, final String substring) { - verifyLogged(matcher(level, substring)); - } - - private TypeSafeMatcher matcher(final String substring) { - return new TypeSafeMatcher() { - @Override - public void describeTo(Description description) { - description.appendText(String.format("log message containing message [%s]", substring)); - } - - @Override - protected boolean matchesSafely(LogRecord item) { - return item.getMessage().contains(substring); - } - }; - } - - private TypeSafeMatcher matcher(final Level level, final String substring) { - return new TypeSafeMatcher() { - @Override - public void describeTo(Description description) { - description.appendText(String.format( - "log message of level [%s] containing message [%s]", level, substring)); - } - - @Override - protected boolean matchesSafely(LogRecord item) { - return level.equals(item.getLevel()) - && item.getMessage().contains(substring); - } - }; - } - - private void verify(final Level level, final String substring, final Throwable throwable) { - verifyLogged(matcher(level, substring, throwable)); - } - - private void verifyNo(final Level level, final String substring, final Throwable throwable) { - verifyNotLogged(matcher(level, substring, throwable)); - } - - private TypeSafeMatcher matcher( - final Level level, final String substring, final Throwable throwable) { - return new TypeSafeMatcher() { - @Override - public void describeTo(Description description) { - description.appendText(String.format( - "log message of level [%s] containg message [%s] with exception [%s] " - + "containing message [%s]", - level, substring, throwable.getClass(), throwable.getMessage())); - } - - @Override - protected boolean matchesSafely(LogRecord item) { - return level.equals(item.getLevel()) - && item.getMessage().contains(substring) - && item.getThrown().getClass().equals(throwable.getClass()) - && item.getThrown().getMessage().contains(throwable.getMessage()); - } - }; - } - - private void verifyLogged(Matcher matcher) { - for (LogRecord record : logSaver.getLogs()) { - if (matcher.matches(record)) { - return; - } - } - - fail(String.format("Missing match for [%s]", matcher)); - } - - private void verifyNotLogged(Matcher matcher) { - // Don't use Matchers.everyItem(Matchers.not(matcher)) because it doesn't format the logRecord - for (LogRecord record : logSaver.getLogs()) { - if (matcher.matches(record)) { - fail(String.format("Unexpected match of [%s]: [%s]", matcher, logFormatter.format(record))); - } - } - } - - @Override - protected void before() throws Throwable { - previousLevel = log.getLevel(); - log.setLevel(Level.ALL); - log.addHandler(logSaver); - } - - @Override - protected void after() { - log.removeHandler(logSaver); - log.setLevel(previousLevel); - } - - private final Logger log; - private final LogSaver logSaver; - private final Formatter logFormatter = new SimpleFormatter(); - private Level previousLevel; - - private ExpectedLogs(String name) { - log = Logger.getLogger(name); - logSaver = new LogSaver(); - } - - /** - * A JUL logging {@link Handler} that records all logging events that are passed to it. - */ - @ThreadSafe - private static class LogSaver extends Handler { - Collection logRecords = new ConcurrentLinkedDeque<>(); - - public Collection getLogs() { - return logRecords; - } - - @Override - public void publish(LogRecord record) { - logRecords.add(record); - } - - @Override - public void flush() {} - - @Override - public void close() throws SecurityException {} - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogsTest.java deleted file mode 100644 index 2dce880ffc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ExpectedLogsTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.CompletionService; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** Tests for {@link FastNanoClockAndSleeper}. */ -@RunWith(JUnit4.class) -public class ExpectedLogsTest { - private static final Logger LOG = LoggerFactory.getLogger(ExpectedLogsTest.class); - - private Random random = new Random(); - - @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(ExpectedLogsTest.class); - - @Test - public void testWhenNoExpectations() throws Throwable { - LOG.error(generateRandomString()); - } - - @Test - public void testVerifyWhenMatchedFully() throws Throwable { - String expected = generateRandomString(); - - LOG.error(expected); - expectedLogs.verifyError(expected); - } - - @Test - public void testVerifyWhenMatchedPartially() throws Throwable { - String expected = generateRandomString(); - LOG.error("Extra stuff around expected " + expected + " blah"); - expectedLogs.verifyError(expected); - } - - @Test - public void testVerifyWhenMatchedWithExceptionBeingLogged() throws Throwable { - String expected = generateRandomString(); - LOG.error(expected, new IOException("Fake Exception")); - expectedLogs.verifyError(expected); - } - - @Test(expected = AssertionError.class) - public void testVerifyWhenNotMatched() throws Throwable { - String expected = generateRandomString(); - - expectedLogs.verifyError(expected); - } - - @Test(expected = AssertionError.class) - public void testVerifyNotLoggedWhenMatchedFully() throws Throwable { - String expected = generateRandomString(); - - LOG.error(expected); - expectedLogs.verifyNotLogged(expected); - } - - @Test(expected = AssertionError.class) - public void testVerifyNotLoggedWhenMatchedPartially() throws Throwable { - String expected = generateRandomString(); - LOG.error("Extra stuff around expected " + expected + " blah"); - expectedLogs.verifyNotLogged(expected); - } - - @Test(expected = AssertionError.class) - public void testVerifyNotLoggedWhenMatchedWithException() throws Throwable { - String expected = generateRandomString(); - LOG.error(expected, new IOException("Fake Exception")); - expectedLogs.verifyNotLogged(expected); - } - - @Test - public void testVerifyNotLoggedWhenNotMatched() throws Throwable { - String expected = generateRandomString(); - expectedLogs.verifyNotLogged(expected); - } - - @Test - public void testLogCaptureOccursAtLowestLogLevel() throws Throwable { - String expected = generateRandomString(); - LOG.trace(expected); - expectedLogs.verifyTrace(expected); - } - - @Test - public void testThreadSafetyOfLogSaver() throws Throwable { - CompletionService completionService = - new ExecutorCompletionService<>(Executors.newCachedThreadPool()); - final long scheduledLogTime = - TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS) + 500L; - - List expectedStrings = new ArrayList<>(); - for (int i = 0; i < 100; i++) { - final String expected = generateRandomString(); - expectedStrings.add(expected); - completionService.submit(new Callable() { - @Override - public Void call() throws Exception { - // Have all threads started and waiting to log at about the same moment. - sleepMillis(Math.max(1, scheduledLogTime - - TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS))); - LOG.trace(expected); - return null; - } - }); - } - - // Wait for all the threads to complete. - for (int i = 0; i < 100; i++) { - completionService.take(); - } - - for (String expected : expectedStrings) { - expectedLogs.verifyTrace(expected); - } - } - - // Generates a random fake error message. - private String generateRandomString() { - return "Fake error message: " + random.nextInt(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeper.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeper.java deleted file mode 100644 index 9447956733..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeper.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.api.client.util.NanoClock; -import com.google.api.client.util.Sleeper; - -import org.junit.rules.ExternalResource; -import org.junit.rules.TestRule; - -/** - * This object quickly moves time forward based upon how much it has been asked to sleep, - * without actually sleeping, to simulate the backoff. - */ -public class FastNanoClockAndSleeper extends ExternalResource - implements NanoClock, Sleeper, TestRule { - private long fastNanoTime; - - @Override - public long nanoTime() { - return fastNanoTime; - } - - @Override - protected void before() throws Throwable { - fastNanoTime = NanoClock.SYSTEM.nanoTime(); - } - - @Override - public void sleep(long millis) throws InterruptedException { - fastNanoTime += millis * 1000000L; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeperTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeperTest.java deleted file mode 100644 index 76256962ad..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/FastNanoClockAndSleeperTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.concurrent.TimeUnit; - -/** Tests for {@link FastNanoClockAndSleeper}. */ -@RunWith(JUnit4.class) -public class FastNanoClockAndSleeperTest { - @Rule public FastNanoClockAndSleeper fastNanoClockAndSleeper = new FastNanoClockAndSleeper(); - - @Test - public void testClockAndSleeper() throws Exception { - long sleepTimeMs = TimeUnit.SECONDS.toMillis(30); - long sleepTimeNano = TimeUnit.MILLISECONDS.toNanos(sleepTimeMs); - long fakeTimeNano = fastNanoClockAndSleeper.nanoTime(); - long startTimeNano = System.nanoTime(); - fastNanoClockAndSleeper.sleep(sleepTimeMs); - long maxTimeNano = startTimeNano + TimeUnit.SECONDS.toNanos(1); - // Verify that actual time didn't progress as much as was requested - assertTrue(System.nanoTime() < maxTimeNano); - // Verify that the fake time did go up by the amount requested - assertEquals(fakeTimeNano + sleepTimeNano, fastNanoClockAndSleeper.nanoTime()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PCollectionViewTesting.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PCollectionViewTesting.java deleted file mode 100644 index 6f677ddf3f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PCollectionViewTesting.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PValueBase; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.List; -import java.util.Objects; - -/** - * Methods for creating and using {@link PCollectionView} instances. - */ -public final class PCollectionViewTesting { - - // Do not instantiate; static methods only - private PCollectionViewTesting() { } - - /** - * The length of the default window, which is an {@link IntervalWindow}, but kept encapsulated - * as it is not for the user to know what sort of window it is. - */ - private static final long DEFAULT_WINDOW_MSECS = 1000 * 60 * 60; - - /** - * A default windowing strategy. Tests that are not concerned with the windowing - * strategy should not specify it, and all views will use this. - */ - public static final WindowingStrategy DEFAULT_WINDOWING_STRATEGY = - WindowingStrategy.of(FixedWindows.of(new Duration(DEFAULT_WINDOW_MSECS))); - - /** - * A default window into which test elements will be placed, if the window is - * not explicitly overridden. - */ - public static final BoundedWindow DEFAULT_NONEMPTY_WINDOW = - new IntervalWindow(new Instant(0), new Instant(DEFAULT_WINDOW_MSECS)); - - /** - * A timestamp in the {@link #DEFAULT_NONEMPTY_WINDOW}. - */ - public static final Instant DEFAULT_TIMESTAMP = DEFAULT_NONEMPTY_WINDOW.maxTimestamp().minus(1); - - /** - * A window into which no element will be placed by methods in this class, unless explicitly - * requested. - */ - public static final BoundedWindow DEFAULT_EMPTY_WINDOW = new IntervalWindow( - DEFAULT_NONEMPTY_WINDOW.maxTimestamp(), - DEFAULT_NONEMPTY_WINDOW.maxTimestamp().plus(DEFAULT_WINDOW_MSECS)); - - /** - * A specialization of {@link SerializableFunction} just for putting together - * {@link PCollectionView} instances. - */ - public interface ViewFn - extends SerializableFunction>, ViewT> { } - - /** - * A {@link ViewFn} that returns the provided contents as a fully lazy iterable. - */ - public static class IdentityViewFn implements ViewFn> { - @Override - public Iterable apply(Iterable> contents) { - return Iterables.transform(contents, new Function, T>() { - @Override - public T apply(WindowedValue windowedValue) { - return windowedValue.getValue(); - } - }); - } - } - - /** - * A {@link ViewFn} that traverses the whole iterable eagerly and returns the number of elements. - * - *

              Only for use in testing scenarios with small collections. If there are more elements - * provided than {@code Integer.MAX_VALUE} then behavior is unpredictable. - */ - public static class LengthViewFn implements ViewFn { - @Override - public Long apply(Iterable> contents) { - return (long) Iterables.size(contents); - } - } - - /** - * A {@link ViewFn} that always returns the value with which it is instantiated. - */ - public static class ConstantViewFn implements ViewFn { - private ViewT value; - - public ConstantViewFn(ViewT value) { - this.value = value; - } - - @Override - public ViewT apply(Iterable> contents) { - return value; - } - } - - /** - * A {@link PCollectionView} explicitly built from a {@link TupleTag} - * and conversion {@link ViewFn}, and an element coder, using the - * {@link #DEFAULT_WINDOWING_STRATEGY}. - * - *

              This method is only recommended for use by runner implementors to test their - * implementations. It is very easy to construct a {@link PCollectionView} that does - * not respect the invariants required for proper functioning. - * - *

              Note that if the provided {@code WindowingStrategy} does not match that of the windowed - * values provided to the view during execution, results are unpredictable. It is recommended - * that the values be prepared via {@link #contentsInDefaultWindow}. - */ - public static PCollectionView testingView( - TupleTag>> tag, - ViewFn viewFn, - Coder elemCoder) { - return testingView( - tag, - viewFn, - elemCoder, - DEFAULT_WINDOWING_STRATEGY); - } - - /** - * The default {@link Coder} used for windowed values, given an element {@link Coder}. - */ - public static Coder> defaultWindowedValueCoder(Coder elemCoder) { - return WindowedValue.getFullCoder( - elemCoder, DEFAULT_WINDOWING_STRATEGY.getWindowFn().windowCoder()); - } - - /** - * A {@link PCollectionView} explicitly built from its {@link TupleTag}, - * {@link WindowingStrategy}, {@link Coder}, and conversion function. - * - *

              This method is only recommended for use by runner implementors to test their - * implementations. It is very easy to construct a {@link PCollectionView} that does - * not respect the invariants required for proper functioning. - * - *

              Note that if the provided {@code WindowingStrategy} does not match that of the windowed - * values provided to the view during execution, results are unpredictable. - */ - public static PCollectionView testingView( - TupleTag>> tag, - ViewFn viewFn, - Coder elemCoder, - WindowingStrategy windowingStrategy) { - return new PCollectionViewFromParts<>( - tag, - viewFn, - windowingStrategy, - IterableCoder.of( - WindowedValue.getFullCoder(elemCoder, windowingStrategy.getWindowFn().windowCoder()))); - } - - /** - * Places the given {@code value} in the {@link #DEFAULT_NONEMPTY_WINDOW}. - */ - public static WindowedValue valueInDefaultWindow(T value) { - return WindowedValue.of(value, DEFAULT_TIMESTAMP, DEFAULT_NONEMPTY_WINDOW, PaneInfo.NO_FIRING); - } - - /** - * Prepares {@code values} for reading as the contents of a {@link PCollectionView} side input. - */ - @SafeVarargs - public static Iterable> contentsInDefaultWindow(T... values) - throws Exception { - List> windowedValues = Lists.newArrayList(); - for (T value : values) { - windowedValues.add(valueInDefaultWindow(value)); - } - return windowedValues; - } - - /** - * Prepares {@code values} for reading as the contents of a {@link PCollectionView} side input. - */ - public static Iterable> contentsInDefaultWindow(Iterable values) - throws Exception { - List> windowedValues = Lists.newArrayList(); - for (T value : values) { - windowedValues.add(valueInDefaultWindow(value)); - } - return windowedValues; - } - - // Internal details below here - - /** - * A {@link PCollectionView} explicitly built from its {@link TupleTag}, - * {@link WindowingStrategy}, and conversion function. - * - *

              Instantiate via {@link #testingView}. - */ - private static class PCollectionViewFromParts - extends PValueBase - implements PCollectionView { - private TupleTag>> tag; - private ViewFn viewFn; - private WindowingStrategy windowingStrategy; - private Coder>> coder; - - public PCollectionViewFromParts( - TupleTag>> tag, - ViewFn viewFn, - WindowingStrategy windowingStrategy, - Coder>> coder) { - this.tag = tag; - this.viewFn = viewFn; - this.windowingStrategy = windowingStrategy; - this.coder = coder; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public TupleTag>> getTagInternal() { - return (TupleTag) tag; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public ViewT fromIterableInternal(Iterable> contents) { - return (ViewT) viewFn.apply((Iterable) contents); - } - - @Override - public WindowingStrategy getWindowingStrategyInternal() { - return windowingStrategy; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public Coder>> getCoderInternal() { - return (Coder) coder; - } - - @Override - public int hashCode() { - return Objects.hash(tag); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof PCollectionView)) { - return false; - } - @SuppressWarnings("unchecked") - PCollectionView otherView = (PCollectionView) other; - return tag.equals(otherView.getTagInternal()); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("tag", tag) - .add("viewFn", viewFn) - .toString(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java deleted file mode 100644 index 4fb3848df8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/PaneExtractorsTest.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.util.WindowedValue; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link PaneExtractors}. - */ -@RunWith(JUnit4.class) -public class PaneExtractorsTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void onlyPaneNoFiring() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.onlyPane(); - Iterable> noFiring = - ImmutableList.of( - WindowedValue.valueInGlobalWindow(9), WindowedValue.valueInEmptyWindows(19)); - assertThat(extractor.apply(noFiring), containsInAnyOrder(9, 19)); - } - - @Test - public void onlyPaneOnlyOneFiring() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.onlyPane(); - Iterable> onlyFiring = - ImmutableList.of( - WindowedValue.of( - 2, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), - WindowedValue.of( - 1, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - assertThat(extractor.apply(onlyFiring), containsInAnyOrder(2, 1)); - } - - @Test - public void onlyPaneMultiplePanesFails() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.onlyPane(); - Iterable> multipleFiring = - ImmutableList.of( - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY)), - WindowedValue.of( - 2, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 1, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("trigger that fires at most once"); - extractor.apply(multipleFiring); - } - - @Test - public void onTimePane() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.onTimePane(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 2, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L))); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4)); - } - - @Test - public void onTimePaneOnlyEarlyAndLate() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.onTimePane(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 2, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 1, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY))); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4)); - } - - @Test - public void finalPane() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.finalPane(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, true, Timing.LATE, 2L, 1L)), - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 1, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY))); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(8)); - } - - @Test - public void finalPaneNoExplicitFinalEmpty() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.finalPane(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 1, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY))); - - assertThat(extractor.apply(onlyOnTime), emptyIterable()); - } - - @Test - public void nonLatePanesSingleOnTime() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.nonLatePanes(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), - WindowedValue.of( - 4, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), - WindowedValue.of( - 2, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4, 8)); - } - - @Test - public void nonLatePanesSingleEarly() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.nonLatePanes(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY)), - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY))); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(4, 8)); - } - - @Test - public void allPanesSingleLate() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.nonLatePanes(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.LATE, 0L, 0L))); - - assertThat(extractor.apply(onlyOnTime), emptyIterable()); - } - - @Test - public void nonLatePanesMultiplePanes() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.nonLatePanes(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), - WindowedValue.of(7, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING), - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 1, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY))); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(4, 1, 7)); - } - - @Test - public void allPanesSinglePane() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.allPanes(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), - WindowedValue.of( - 4, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING), - WindowedValue.of( - 2, new Instant(0L), GlobalWindow.INSTANCE, PaneInfo.ON_TIME_AND_ONLY_FIRING)); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(2, 4, 8)); - } - - @Test - public void allPanesMultiplePanes() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.allPanes(); - Iterable> onlyOnTime = - ImmutableList.of( - WindowedValue.of( - 8, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.LATE, 2L, 1L)), - WindowedValue.of( - 4, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(false, false, Timing.ON_TIME, 1L, 0L)), - WindowedValue.of( - 1, - new Instant(0L), - GlobalWindow.INSTANCE, - PaneInfo.createPane(true, false, Timing.EARLY))); - - assertThat(extractor.apply(onlyOnTime), containsInAnyOrder(4, 8, 1)); - } - - @Test - public void allPanesEmpty() { - SerializableFunction>, Iterable> extractor = - PaneExtractors.allPanes(); - Iterable> noPanes = ImmutableList.of(); - - assertThat(extractor.apply(noPanes), emptyIterable()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProvider.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProvider.java deleted file mode 100644 index 34c901b394..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProvider.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import org.joda.time.DateTimeUtils; -import org.joda.time.format.ISODateTimeFormat; -import org.junit.rules.ExternalResource; -import org.junit.rules.TestRule; - -/** - * This {@link TestRule} resets the date time provider in Joda to the system date - * time provider after tests. - */ -public class ResetDateTimeProvider extends ExternalResource { - public void setDateTimeFixed(String iso8601) { - setDateTimeFixed(ISODateTimeFormat.dateTime().parseMillis(iso8601)); - } - - public void setDateTimeFixed(long millis) { - DateTimeUtils.setCurrentMillisFixed(millis); - } - - @Override - protected void after() { - DateTimeUtils.setCurrentMillisSystem(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProviderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProviderTest.java deleted file mode 100644 index 294bb41c67..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/ResetDateTimeProviderTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import org.joda.time.DateTimeUtils; -import org.joda.time.format.ISODateTimeFormat; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link ResetDateTimeProvider}. */ -@RunWith(JUnit4.class) -public class ResetDateTimeProviderTest { - private static final String TEST_TIME = "2014-12-08T19:07:06.698Z"; - private static final long TEST_TIME_MS = - ISODateTimeFormat.dateTime().parseMillis(TEST_TIME); - - @Rule public ResetDateTimeProvider resetDateTimeProviderRule = new ResetDateTimeProvider(); - - /* - * Since these tests can run out of order, both test A and B change the provider - * and verify that the provider was reset. - */ - @Test - public void testResetA() { - assertNotEquals(TEST_TIME_MS, DateTimeUtils.currentTimeMillis()); - resetDateTimeProviderRule.setDateTimeFixed(TEST_TIME); - assertEquals(TEST_TIME_MS, DateTimeUtils.currentTimeMillis()); - } - - @Test - public void testResetB() { - assertNotEquals(TEST_TIME_MS, DateTimeUtils.currentTimeMillis()); - resetDateTimeProviderRule.setDateTimeFixed(TEST_TIME); - assertEquals(TEST_TIME_MS, DateTimeUtils.currentTimeMillis()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java deleted file mode 100644 index a89be3edd7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemProperties.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import org.junit.rules.ExternalResource; -import org.junit.rules.TestRule; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * Saves and restores the current system properties for tests. - */ -public class RestoreSystemProperties extends ExternalResource implements TestRule { - private byte[] originalProperties; - - @Override - protected void before() throws Throwable { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.getProperties().store(baos, ""); - baos.close(); - originalProperties = baos.toByteArray(); - } - - @Override - protected void after() { - try (ByteArrayInputStream bais = new ByteArrayInputStream(originalProperties)) { - System.getProperties().clear(); - System.getProperties().load(bais); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemPropertiesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemPropertiesTest.java deleted file mode 100644 index ab49c75adc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/RestoreSystemPropertiesTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link RestoreSystemProperties}. */ -@RunWith(JUnit4.class) -public class RestoreSystemPropertiesTest { - @Rule public TestRule restoreSystemProperties = new RestoreSystemProperties(); - - /* - * Since these tests can run out of order, both test A and B verify that they - * could insert their property and that the other does not exist. - */ - @Test - public void testThatPropertyIsClearedA() { - System.getProperties().put("TestA", "TestA"); - assertNotNull(System.getProperty("TestA")); - assertNull(System.getProperty("TestB")); - } - - @Test - public void testThatPropertyIsClearedB() { - System.getProperties().put("TestB", "TestB"); - assertNotNull(System.getProperty("TestB")); - assertNull(System.getProperty("TestA")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchersTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchersTest.java deleted file mode 100644 index 1ab94c5379..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SerializableMatchersTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.allOf; -import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.anything; -import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.containsInAnyOrder; -import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.kvWithKey; -import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.not; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; - -/** - * Test case for {@link SerializableMatchers}. - * - *

              Since the only new matchers are those for {@link KV}, only those are tested here, to avoid - * tediously repeating all of hamcrest's tests. - * - *

              A few wrappers of a hamcrest matchers are tested for serializability. Beyond that, - * the boilerplate that is identical to each is considered thoroughly tested. - */ -@RunWith(JUnit4.class) -public class SerializableMatchersTest implements Serializable { - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testAnythingSerializable() throws Exception { - SerializableUtils.ensureSerializable(anything()); - } - - @Test - public void testAllOfSerializable() throws Exception { - SerializableUtils.ensureSerializable(allOf(anything())); - } - - @Test - public void testContainsInAnyOrderSerializable() throws Exception { - assertThat(ImmutableList.of(2, 1, 3), - SerializableUtils.ensureSerializable(containsInAnyOrder(1, 2, 3))); - } - - @Test - public void testContainsInAnyOrderNotSerializable() throws Exception { - assertThat( - ImmutableList.of(new NotSerializableClass()), - SerializableUtils.ensureSerializable(containsInAnyOrder( - new NotSerializableClassCoder(), - new NotSerializableClass()))); - } - - @Test - public void testKvKeyMatcherSerializable() throws Exception { - assertThat( - KV.of("hello", 42L), - SerializableUtils.ensureSerializable(kvWithKey("hello"))); - } - - @Test - public void testKvMatcherBasicSuccess() throws Exception { - assertThat( - KV.of(1, 2), - SerializableMatchers.kv(anything(), anything())); - } - - @Test - public void testKvMatcherKeyFailure() throws Exception { - try { - assertThat( - KV.of(1, 2), - SerializableMatchers.kv(not(anything()), anything())); - } catch (AssertionError exc) { - assertThat(exc.getMessage(), Matchers.containsString("key did not match")); - return; - } - fail("Should have failed"); - } - - @Test - public void testKvMatcherValueFailure() throws Exception { - try { - assertThat( - KV.of(1, 2), - SerializableMatchers.kv(anything(), not(anything()))); - } catch (AssertionError exc) { - assertThat(exc.getMessage(), Matchers.containsString("value did not match")); - return; - } - fail("Should have failed"); - } - - @Test - public void testKvMatcherGBKLikeSuccess() throws Exception { - assertThat( - KV.of("key", ImmutableList.of(1, 2, 3)), - SerializableMatchers.>kv( - anything(), containsInAnyOrder(3, 2, 1))); - } - - @Test - public void testKvMatcherGBKLikeFailure() throws Exception { - try { - assertThat( - KV.of("key", ImmutableList.of(1, 2, 3)), - SerializableMatchers.>kv( - anything(), containsInAnyOrder(1, 2, 3, 4))); - } catch (AssertionError exc) { - assertThat(exc.getMessage(), Matchers.containsString("value did not match")); - return; - } - fail("Should have failed."); - } - - private static class NotSerializableClass { - @Override public boolean equals(Object other) { - return other instanceof NotSerializableClass; - } - - @Override public int hashCode() { - return 0; - } - } - - private static class NotSerializableClassCoder extends AtomicCoder { - @Override - public void encode(NotSerializableClass value, OutputStream outStream, Coder.Context context) { - } - - @Override - public NotSerializableClass decode(InputStream inStream, Coder.Context context) { - return new NotSerializableClass(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java deleted file mode 100644 index d88e8347a9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SourceTestUtilsTest.java +++ /dev/null @@ -1,64 +0,0 @@ - -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.BoundedSource.BoundedReader; -import com.google.cloud.dataflow.sdk.io.CountingSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.common.collect.Sets; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; -import java.util.Set; - -/** - * Tests for {@link SourceTestUtils}. - */ -@RunWith(JUnit4.class) -public class SourceTestUtilsTest { - - @Test - public void testToUnsplittableSource() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - BoundedSource baseSource = CountingSource.upTo(100); - BoundedSource unsplittableSource = SourceTestUtils.toUnsplittableSource(baseSource); - List splits = unsplittableSource.splitIntoBundles(1, options); - assertEquals(splits.size(), 1); - assertEquals(splits.get(0), unsplittableSource); - - BoundedReader unsplittableReader = unsplittableSource.createReader(options); - assertEquals(0, unsplittableReader.getFractionConsumed(), 1e-15); - - Set expected = Sets.newHashSet(SourceTestUtils.readFromSource(baseSource, options)); - Set actual = Sets.newHashSet(); - actual.addAll(SourceTestUtils.readNItemsFromUnstartedReader(unsplittableReader, 40)); - assertNull(unsplittableReader.splitAtFraction(0.5)); - actual.addAll(SourceTestUtils.readRemainingFromReader(unsplittableReader, true /* started */)); - assertEquals(1, unsplittableReader.getFractionConsumed(), 1e-15); - - assertEquals(100, actual.size()); - assertEquals(Sets.newHashSet(expected), Sets.newHashSet(actual)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java deleted file mode 100644 index 9e79f08504..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/StaticWindowsTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link StaticWindows}. - */ -@RunWith(JUnit4.class) -public class StaticWindowsTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private final IntervalWindow first = new IntervalWindow(new Instant(0), new Instant(100_000L)); - private final IntervalWindow second = - new IntervalWindow(new Instant(1_000_000L), GlobalWindow.INSTANCE.maxTimestamp()); - - @Test - public void singleWindowSucceeds() throws Exception { - WindowFn fn = StaticWindows.of(IntervalWindow.getCoder(), first); - assertThat(WindowFnTestUtils.assignedWindows(fn, 100L), - Matchers.contains(first)); - assertThat(WindowFnTestUtils.assignedWindows(fn, -100L), - Matchers.contains(first)); - } - - @Test - public void multipleWindowsSucceeds() throws Exception { - WindowFn fn = - StaticWindows.of(IntervalWindow.getCoder(), ImmutableList.of(first, second)); - assertThat(WindowFnTestUtils.assignedWindows(fn, 100L), - Matchers.containsInAnyOrder(first, second)); - assertThat(WindowFnTestUtils.assignedWindows(fn, 1_000_000_000L), - Matchers.containsInAnyOrder(first, second)); - assertThat(WindowFnTestUtils.assignedWindows(fn, -100L), - Matchers.containsInAnyOrder(first, second)); - } - - @Test - public void getSideInputWindowIdentity() { - WindowFn fn = - StaticWindows.of(IntervalWindow.getCoder(), ImmutableList.of(first, second)); - - assertThat(fn.getSideInputWindow(first), Matchers.equalTo(first)); - assertThat(fn.getSideInputWindow(second), Matchers.equalTo(second)); - } - - @Test - public void getSideInputWindowNotPresent() { - WindowFn fn = - StaticWindows.of(IntervalWindow.getCoder(), ImmutableList.of(second)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("contains"); - fn.getSideInputWindow(first); - } - - @Test - public void emptyIterableThrows() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("may not be empty"); - StaticWindows.of(GlobalWindow.Coder.INSTANCE, ImmutableList.of()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java deleted file mode 100644 index 4a727bc7a7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeper.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import com.google.api.client.util.Sleeper; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.LockSupport; - -/** - * This class provides an expensive sleeper to deal with issues around Java's - * accuracy of {@link System#currentTimeMillis} and methods such as - * {@link Object#wait} and {@link Thread#sleep} which depend on it. This - * article goes into further detail about this issue. - * - *

              This {@link Sleeper} uses {@link System#nanoTime} - * as the timing source and {@link LockSupport#parkNanos} as the wait method. - * Note that usage of this sleeper may impact performance because - * of the relatively more expensive methods being invoked when compared to - * {@link Thread#sleep}. - */ -public class SystemNanoTimeSleeper implements Sleeper { - public static final Sleeper INSTANCE = new SystemNanoTimeSleeper(); - - /** Limit visibility to prevent instantiation. */ - private SystemNanoTimeSleeper() { - } - - @Override - public void sleep(long millis) throws InterruptedException { - long currentTime; - long endTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(millis, TimeUnit.MILLISECONDS); - while ((currentTime = System.nanoTime()) < endTime) { - if (Thread.interrupted()) { - throw new InterruptedException(); - } - LockSupport.parkNanos(endTime - currentTime); - } - if (Thread.interrupted()) { - throw new InterruptedException(); - } - return; - } - - /** - * Causes the currently executing thread to sleep (temporarily cease - * execution) for the specified number of milliseconds. The thread does not - * lose ownership of any monitors. - */ - public static void sleepMillis(long millis) throws InterruptedException { - INSTANCE.sleep(millis); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeperTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeperTest.java deleted file mode 100644 index 33b6b693a2..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/SystemNanoTimeSleeperTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link SystemNanoTimeSleeper}. */ -@RunWith(JUnit4.class) -public class SystemNanoTimeSleeperTest { - @Test - public void testSleep() throws Exception { - long startTime = System.nanoTime(); - sleepMillis(100); - long endTime = System.nanoTime(); - assertTrue(endTime - startTime >= 100); - } - - @Test - public void testNegativeSleep() throws Exception { - sleepMillis(-100); - } - - @Test(expected = InterruptedException.class) - public void testInterruptionInLoop() throws Exception { - Thread.currentThread().interrupt(); - sleepMillis(0); - } - - @Test(expected = InterruptedException.class) - public void testInterruptionOutsideOfLoop() throws Exception { - Thread.currentThread().interrupt(); - sleepMillis(-100); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunnerTest.java deleted file mode 100644 index d39ef2e4ae..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestDataflowPipelineRunnerTest.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doCallRealMethod; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.api.client.http.LowLevelHttpResponse; -import com.google.api.client.json.Json; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.testing.http.MockLowLevelHttpResponse; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.JobMessage; -import com.google.api.services.dataflow.model.JobMetrics; -import com.google.api.services.dataflow.model.MetricStructuredName; -import com.google.api.services.dataflow.model.MetricUpdate; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineJob; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil.JobMessagesHandler; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.TestCredential; -import com.google.cloud.dataflow.sdk.util.TimeUtil; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -/** Tests for {@link TestDataflowPipelineRunner}. */ -@RunWith(JUnit4.class) -public class TestDataflowPipelineRunnerTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Mock private MockHttpTransport transport; - @Mock private MockLowLevelHttpRequest request; - @Mock private GcsUtil mockGcsUtil; - - private TestDataflowPipelineOptions options; - private Dataflow service; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - when(transport.buildRequest(anyString(), anyString())).thenReturn(request); - doCallRealMethod().when(request).getContentAsString(); - service = new Dataflow(transport, Transport.getJsonFactory(), null); - - options = PipelineOptionsFactory.as(TestDataflowPipelineOptions.class); - options.setAppName("TestAppName"); - options.setProject("test-project"); - options.setTempLocation("gs://test/temp/location"); - options.setGcpCredential(new TestCredential()); - options.setDataflowClient(service); - options.setRunner(TestDataflowPipelineRunner.class); - options.setPathValidatorClass(NoopPathValidator.class); - } - - @Test - public void testToString() { - assertEquals("TestDataflowPipelineRunner#TestAppName", - new TestDataflowPipelineRunner(options).toString()); - } - - @Test - public void testRunBatchJobThatSucceeds() throws Exception { - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class); - when(mockJob.getDataflowClient()).thenReturn(service); - when(mockJob.getState()).thenReturn(State.DONE); - when(mockJob.getProjectId()).thenReturn("test-project"); - when(mockJob.getJobId()).thenReturn("test-job"); - - DataflowPipelineRunner mockRunner = Mockito.mock(DataflowPipelineRunner.class); - when(mockRunner.run(any(Pipeline.class))).thenReturn(mockJob); - - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - when(request.execute()).thenReturn( - generateMockMetricResponse(true /* success */, true /* tentative */)); - assertEquals(mockJob, runner.run(p, mockRunner)); - } - - @Test - public void testRunBatchJobThatFails() throws Exception { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The dataflow failed."); - - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class); - when(mockJob.getDataflowClient()).thenReturn(service); - when(mockJob.getState()).thenReturn(State.FAILED); - when(mockJob.getProjectId()).thenReturn("test-project"); - when(mockJob.getJobId()).thenReturn("test-job"); - - DataflowPipelineRunner mockRunner = Mockito.mock(DataflowPipelineRunner.class); - when(mockRunner.run(any(Pipeline.class))).thenReturn(mockJob); - - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - runner.run(p, mockRunner); - } - - @Test - public void testRunStreamingJobThatSucceeds() throws Exception { - options.setStreaming(true); - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class); - when(mockJob.getDataflowClient()).thenReturn(service); - when(mockJob.getState()).thenReturn(State.RUNNING); - when(mockJob.getProjectId()).thenReturn("test-project"); - when(mockJob.getJobId()).thenReturn("test-job"); - - DataflowPipelineRunner mockRunner = Mockito.mock(DataflowPipelineRunner.class); - when(mockRunner.run(any(Pipeline.class))).thenReturn(mockJob); - - when(request.execute()).thenReturn( - generateMockMetricResponse(true /* success */, true /* tentative */)); - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - runner.run(p, mockRunner); - } - - @Test - public void testRunStreamingJobThatFails() throws Exception { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The dataflow failed."); - - options.setStreaming(true); - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class); - when(mockJob.getDataflowClient()).thenReturn(service); - when(mockJob.getState()).thenReturn(State.RUNNING); - when(mockJob.getProjectId()).thenReturn("test-project"); - when(mockJob.getJobId()).thenReturn("test-job"); - - DataflowPipelineRunner mockRunner = Mockito.mock(DataflowPipelineRunner.class); - when(mockRunner.run(any(Pipeline.class))).thenReturn(mockJob); - - when(request.execute()).thenReturn( - generateMockMetricResponse(false /* success */, true /* tentative */)); - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - runner.run(p, mockRunner); - } - - @Test - public void testCheckingForSuccessWhenDataflowAssertSucceeds() throws Exception { - DataflowPipelineJob job = - spy(new DataflowPipelineJob("test-project", "test-job", service, null)); - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - when(request.execute()).thenReturn( - generateMockMetricResponse(true /* success */, true /* tentative */)); - doReturn(State.DONE).when(job).getState(); - assertEquals(Optional.of(true), runner.checkForSuccess(job)); - } - - @Test - public void testCheckingForSuccessWhenDataflowAssertFails() throws Exception { - DataflowPipelineJob job = - spy(new DataflowPipelineJob("test-project", "test-job", service, null)); - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - when(request.execute()).thenReturn( - generateMockMetricResponse(false /* success */, true /* tentative */)); - doReturn(State.DONE).when(job).getState(); - assertEquals(Optional.of(false), runner.checkForSuccess(job)); - } - - @Test - public void testCheckingForSuccessSkipsNonTentativeMetrics() throws Exception { - DataflowPipelineJob job = - spy(new DataflowPipelineJob("test-project", "test-job", service, null)); - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - when(request.execute()).thenReturn( - generateMockMetricResponse(true /* success */, false /* tentative */)); - doReturn(State.RUNNING).when(job).getState(); - assertEquals(Optional.absent(), runner.checkForSuccess(job)); - } - - private LowLevelHttpResponse generateMockMetricResponse(boolean success, boolean tentative) - throws Exception { - MetricStructuredName name = new MetricStructuredName(); - name.setName(success ? "DataflowAssertSuccess" : "DataflowAssertFailure"); - name.setContext( - tentative ? ImmutableMap.of("tentative", "") : ImmutableMap.of()); - - MetricUpdate metric = new MetricUpdate(); - metric.setName(name); - metric.setScalar(BigDecimal.ONE); - - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setContentType(Json.MEDIA_TYPE); - JobMetrics jobMetrics = new JobMetrics(); - jobMetrics.setMetrics(Lists.newArrayList(metric)); - // N.B. Setting the factory is necessary in order to get valid JSON. - jobMetrics.setFactory(Transport.getJsonFactory()); - response.setContent(jobMetrics.toPrettyString()); - return response; - } - - @Test - public void testStreamingPipelineFailsIfServiceFails() throws Exception { - DataflowPipelineJob job = - spy(new DataflowPipelineJob("test-project", "test-job", service, null)); - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - when(request.execute()).thenReturn( - generateMockMetricResponse(true /* success */, false /* tentative */)); - doReturn(State.FAILED).when(job).getState(); - assertEquals(Optional.of(false), runner.checkForSuccess(job)); - } - - @Test - public void testStreamingPipelineFailsIfException() throws Exception { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The dataflow failed."); - - options.setStreaming(true); - Pipeline p = TestPipeline.create(options); - PCollection pc = p.apply(Create.of(1, 2, 3)); - DataflowAssert.that(pc).containsInAnyOrder(1, 2, 3); - - DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class); - when(mockJob.getDataflowClient()).thenReturn(service); - when(mockJob.getState()).thenReturn(State.RUNNING); - when(mockJob.getProjectId()).thenReturn("test-project"); - when(mockJob.getJobId()).thenReturn("test-job"); - when(mockJob.waitToFinish(any(Long.class), any(TimeUnit.class), any(JobMessagesHandler.class))) - .thenAnswer(new Answer() { - @Override - public State answer(InvocationOnMock invocation) { - JobMessage message = new JobMessage(); - message.setMessageText("FooException"); - message.setTime(TimeUtil.toCloudTime(Instant.now())); - message.setMessageImportance("JOB_MESSAGE_ERROR"); - ((MonitoringUtil.JobMessagesHandler) invocation.getArguments()[2]) - .process(Arrays.asList(message)); - return State.CANCELLED; - } - }); - - DataflowPipelineRunner mockRunner = Mockito.mock(DataflowPipelineRunner.class); - when(mockRunner.run(any(Pipeline.class))).thenReturn(mockJob); - - when(request.execute()).thenReturn( - generateMockMetricResponse(false /* success */, true /* tentative */)); - TestDataflowPipelineRunner runner = (TestDataflowPipelineRunner) p.getRunner(); - runner.run(p, mockRunner); - - verify(mockJob).cancel(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java deleted file mode 100644 index 397920a1db..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestPipelineTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.options.ApplicationNameOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link TestPipeline}. */ -@RunWith(JUnit4.class) -public class TestPipelineTest { - @Rule public TestRule restoreSystemProperties = new RestoreSystemProperties(); - - @Test - public void testCreationUsingDefaults() { - assertNotNull(TestPipeline.create()); - } - - @Test - public void testCreationOfPipelineOptions() throws Exception { - ObjectMapper mapper = new ObjectMapper(); - String stringOptions = mapper.writeValueAsString(new String[]{ - "--runner=DataflowPipelineRunner", - "--project=testProject", - "--apiRootUrl=testApiRootUrl", - "--dataflowEndpoint=testDataflowEndpoint", - "--tempLocation=testTempLocation", - "--serviceAccountName=testServiceAccountName", - "--serviceAccountKeyfile=testServiceAccountKeyfile", - "--zone=testZone", - "--numWorkers=1", - "--diskSizeGb=2" - }); - System.getProperties().put("dataflowOptions", stringOptions); - DataflowPipelineOptions options = - TestPipeline.testingPipelineOptions().as(DataflowPipelineOptions.class); - assertEquals(DataflowPipelineRunner.class, options.getRunner()); - assertThat(options.getJobName(), startsWith("testpipelinetest0testcreationofpipelineoptions-")); - assertEquals("testProject", options.as(GcpOptions.class).getProject()); - assertEquals("testApiRootUrl", options.getApiRootUrl()); - assertEquals("testDataflowEndpoint", options.getDataflowEndpoint()); - assertEquals("testTempLocation", options.getTempLocation()); - assertEquals("testServiceAccountName", options.getServiceAccountName()); - assertEquals( - "testServiceAccountKeyfile", options.as(GcpOptions.class).getServiceAccountKeyfile()); - assertEquals("testZone", options.getZone()); - assertEquals(2, options.getDiskSizeGb()); - } - - @Test - public void testCreationOfPipelineOptionsFromReallyVerboselyNamedTestCase() throws Exception { - ObjectMapper mapper = new ObjectMapper(); - String stringOptions = mapper.writeValueAsString(new String[]{}); - System.getProperties().put("dataflowOptions", stringOptions); - PipelineOptions options = TestPipeline.testingPipelineOptions(); - assertThat(options.as(ApplicationNameOptions.class).getAppName(), startsWith( - "TestPipelineTest-testCreationOfPipelineOptionsFromReallyVerboselyNamedTestCase")); - } - - @Test - public void testToString() { - assertEquals("TestPipeline#TestPipelineTest-testToString", TestPipeline.create().toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java deleted file mode 100644 index c894317208..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/TestStreamTest.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; -import com.google.cloud.dataflow.sdk.testing.TestStream.Builder; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.DefaultTrigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Never; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.Serializable; - -/** Tests for {@link TestStream}. */ -@RunWith(JUnit4.class) -public class TestStreamTest implements Serializable { - @Rule public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testLateDataAccumulating() { - Instant instant = new Instant(0); - TestStream source = - TestStream.create(VarIntCoder.of()) - .addElements( - TimestampedValue.of(1, instant), - TimestampedValue.of(2, instant), - TimestampedValue.of(3, instant)) - .advanceWatermarkTo(instant.plus(Duration.standardMinutes(6))) - // These elements are late but within the allowed lateness - .addElements(TimestampedValue.of(4, instant), TimestampedValue.of(5, instant)) - .advanceWatermarkTo(instant.plus(Duration.standardMinutes(20))) - // These elements are droppably late - .addElements( - TimestampedValue.of(-1, instant), - TimestampedValue.of(-2, instant), - TimestampedValue.of(-3, instant)) - .advanceWatermarkToInfinity(); - - Pipeline p = getPipeline(); - PCollection windowed = - p.apply(source) - .apply( - Window.into(FixedWindows.of(Duration.standardMinutes(5))) - .triggering( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(2))) - .withLateFirings(AfterPane.elementCountAtLeast(1))) - .accumulatingFiredPanes() - .withAllowedLateness(Duration.standardMinutes(5), ClosingBehavior.FIRE_ALWAYS)); - PCollection triggered = - windowed - .apply(WithKeys.of(1)) - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(Flatten.iterables()); - PCollection count = windowed.apply(Count.globally().withoutDefaults()); - PCollection sum = windowed.apply(Sum.integersGlobally().withoutDefaults()); - - IntervalWindow window = new IntervalWindow(instant, instant.plus(Duration.standardMinutes(5L))); - DataflowAssert.that(triggered).inFinalPane(window).containsInAnyOrder(1, 2, 3, 4, 5); - DataflowAssert.that(triggered).inOnTimePane(window).containsInAnyOrder(1, 2, 3); - DataflowAssert.that(count) - .inWindow(window) - .satisfies( - new SerializableFunction, Void>() { - @Override - public Void apply(Iterable input) { - for (Long count : input) { - assertThat(count, allOf(greaterThanOrEqualTo(3L), lessThanOrEqualTo(5L))); - } - return null; - } - }); - DataflowAssert.that(sum) - .inWindow(window) - .satisfies( - new SerializableFunction, Void>() { - @Override - public Void apply(Iterable input) { - for (Integer sum : input) { - assertThat(sum, allOf(greaterThanOrEqualTo(6), lessThanOrEqualTo(15))); - } - return null; - } - }); - - p.run(); - } - - @Test - public void testProcessingTimeTrigger() { - TestStream source = - TestStream.create(VarLongCoder.of()) - .addElements( - TimestampedValue.of(1L, new Instant(1000L)), - TimestampedValue.of(2L, new Instant(2000L))) - .advanceProcessingTime(Duration.standardMinutes(12)) - .addElements(TimestampedValue.of(3L, new Instant(3000L))) - .advanceProcessingTime(Duration.standardMinutes(6)) - .advanceWatermarkToInfinity(); - - Pipeline p = getPipeline(); - PCollection sum = - p.apply(source) - .apply( - Window.triggering( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(5)))) - .accumulatingFiredPanes() - .withAllowedLateness(Duration.ZERO)) - .apply(Sum.longsGlobally()); - - DataflowAssert.that(sum).inEarlyGlobalWindowPanes().containsInAnyOrder(3L, 6L); - - p.run(); - } - - /** - * A test that demonstrates that a Trigger in discarding mode fires multiple times, and elements - * that have been produced in a pane are not produced in future panes. - */ - @Test - public void testDiscardingMode() { - TestStream stream = - TestStream.create(StringUtf8Coder.of()) - .advanceWatermarkTo(new Instant(0)) - .addElements( - TimestampedValue.of("firstPane", new Instant(100)), - TimestampedValue.of("alsoFirstPane", new Instant(200))) - .addElements(TimestampedValue.of("onTimePane", new Instant(500))) - .advanceWatermarkTo(new Instant(1001L)) - .addElements( - TimestampedValue.of("finalLatePane", new Instant(750)), - TimestampedValue.of("alsoFinalLatePane", new Instant(250))) - .advanceWatermarkToInfinity(); - - Pipeline p = getPipeline(); - FixedWindows windowFn = FixedWindows.of(Duration.millis(1000L)); - Duration allowedLateness = Duration.millis(5000L); - PCollection values = - p.apply(stream) - .apply( - Window.into(windowFn) - .triggering( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterPane.elementCountAtLeast(2)) - .withLateFirings(Never.ever())) - .discardingFiredPanes() - .withAllowedLateness(allowedLateness)) - .apply(WithKeys.of(1)) - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(Flatten.iterables()); - - IntervalWindow window = windowFn.assignWindow(new Instant(100)); - DataflowAssert.that(values) - .inWindow(window) - .containsInAnyOrder( - "firstPane", "alsoFirstPane", "onTimePane", "finalLatePane", "alsoFinalLatePane"); - DataflowAssert.that(values) - .inCombinedNonLatePanes(window) - .containsInAnyOrder("firstPane", "alsoFirstPane", "onTimePane"); - DataflowAssert.that(values).inOnTimePane(window).containsInAnyOrder("onTimePane"); - DataflowAssert.that(values) - .inFinalPane(window) - .containsInAnyOrder("finalLatePane", "alsoFinalLatePane"); - - p.run(); - } - - @Test - public void testFirstElementLate() { - Instant lateElementTimestamp = new Instant(-1_000_000); - TestStream stream = - TestStream.create(StringUtf8Coder.of()) - .advanceWatermarkTo(new Instant(-1)) - .addElements(TimestampedValue.of("late", lateElementTimestamp)) - .addElements(TimestampedValue.of("onTime", new Instant(100))) - .advanceWatermarkToInfinity(); - - Pipeline p = getPipeline(); - FixedWindows windowFn = FixedWindows.of(Duration.millis(1000L)); - Duration allowedLateness = Duration.millis(5000L); - PCollection values = - p.apply(stream) - .apply( - Window.into(windowFn) - .triggering(DefaultTrigger.of()) - .discardingFiredPanes() - .withAllowedLateness(allowedLateness)) - .apply(WithKeys.of(1)) - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(Flatten.iterables()); - - DataflowAssert.that(values).inWindow(windowFn.assignWindow(lateElementTimestamp)).empty(); - DataflowAssert.that(values) - .inWindow(windowFn.assignWindow(new Instant(100))) - .containsInAnyOrder("onTime"); - - p.run(); - } - - @Test - public void testElementsAtAlmostPositiveInfinity() { - Instant endOfGlobalWindow = GlobalWindow.INSTANCE.maxTimestamp(); - TestStream stream = - TestStream.create(StringUtf8Coder.of()) - .addElements( - TimestampedValue.of("foo", endOfGlobalWindow), - TimestampedValue.of("bar", endOfGlobalWindow)) - .advanceWatermarkToInfinity(); - - Pipeline p = getPipeline(); - FixedWindows windows = FixedWindows.of(Duration.standardHours(6)); - PCollection windowedValues = - p.apply(stream) - .apply(Window.into(windows)) - .apply(WithKeys.of(1)) - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(Flatten.iterables()); - - DataflowAssert.that(windowedValues) - .inWindow(windows.assignWindow(GlobalWindow.INSTANCE.maxTimestamp())) - .containsInAnyOrder("foo", "bar"); - p.run(); - } - - @Test - public void testMultipleStreams() { - Pipeline p = getPipeline(); - - TestStream stream = - TestStream.create(StringUtf8Coder.of()) - .addElements("foo", "bar") - .advanceWatermarkToInfinity(); - - TestStream other = - TestStream.create(VarIntCoder.of()).addElements(1, 2, 3, 4).advanceWatermarkToInfinity(); - - PCollection createStrings = - p.apply("CreateStrings", stream) - .apply( - "WindowStrings", - Window.triggering(AfterPane.elementCountAtLeast(2)) - .withAllowedLateness(Duration.ZERO) - .accumulatingFiredPanes()); - DataflowAssert.that(createStrings).containsInAnyOrder("foo", "bar"); - PCollection createInts = - p.apply("CreateInts", other) - .apply( - "WindowInts", - Window.triggering(AfterPane.elementCountAtLeast(4)) - .withAllowedLateness(Duration.ZERO) - .accumulatingFiredPanes()); - DataflowAssert.that(createInts).containsInAnyOrder(1, 2, 3, 4); - - p.run(); - } - - @Test - public void testElementAtPositiveInfinityThrows() { - Builder stream = - TestStream.create(VarIntCoder.of()) - .addElements(TimestampedValue.of(-1, BoundedWindow.TIMESTAMP_MAX_VALUE.minus(1L))); - thrown.expect(IllegalArgumentException.class); - stream.addElements(TimestampedValue.of(1, BoundedWindow.TIMESTAMP_MAX_VALUE)); - } - - @Test - public void testAdvanceWatermarkNonMonotonicThrows() { - Builder stream = - TestStream.create(VarIntCoder.of()).advanceWatermarkTo(new Instant(-1L)); - thrown.expect(IllegalArgumentException.class); - stream.advanceWatermarkTo(new Instant(-100L)); - } - - @Test - public void testAdvanceWatermarkEqualToPositiveInfinityThrows() { - Builder stream = - TestStream.create(VarIntCoder.of()) - .advanceWatermarkTo(BoundedWindow.TIMESTAMP_MAX_VALUE.minus(1L)); - thrown.expect(IllegalArgumentException.class); - stream.advanceWatermarkTo(BoundedWindow.TIMESTAMP_MAX_VALUE); - } - - private Pipeline getPipeline() { - PipelineOptions options = TestPipeline.testingPipelineOptions(); - options.setRunner(InProcessPipelineRunner.class); - return TestPipeline.fromOptions(options); - } - - @Test - public void testUnsupportedRunnerThrows() { - PipelineOptions opts = PipelineOptionsFactory.create(); - opts.setRunner(DirectPipelineRunner.class); - - Pipeline p = Pipeline.create(opts); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("DirectPipelineRunner"); - thrown.expectMessage("does not support TestStream"); - thrown.expectMessage(TestStream.class.getSimpleName()); - thrown.expectMessage(DirectPipelineRunner.class.getSimpleName()); - p.apply(TestStream.create(VarIntCoder.of()).advanceWatermarkToInfinity()); - } - - @Test - public void testEncodeDecode() throws Exception { - TestStream.Event elems = - TestStream.ElementEvent.add( - TimestampedValue.of(1, new Instant()), - TimestampedValue.of(-10, new Instant()), - TimestampedValue.of(Integer.MAX_VALUE, new Instant())); - TestStream.Event wm = TestStream.WatermarkEvent.advanceTo(new Instant(100)); - TestStream.Event procTime = - TestStream.ProcessingTimeEvent.advanceBy(Duration.millis(90548)); - - TestStream.EventCoder coder = TestStream.EventCoder.of(VarIntCoder.of()); - - CoderProperties.coderSerializable(coder); - CoderProperties.coderDecodeEncodeEqual(coder, elems); - CoderProperties.coderDecodeEncodeEqual(coder, wm); - CoderProperties.coderDecodeEncodeEqual(coder, procTime); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java deleted file mode 100644 index 1ffb2310e1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/testing/WindowSupplierTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.testing; - -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collections; - -/** - * Tests for {@link WindowSupplier}. - */ -@RunWith(JUnit4.class) -public class WindowSupplierTest { - private final IntervalWindow window = new IntervalWindow(new Instant(0L), new Instant(100L)); - private final IntervalWindow otherWindow = - new IntervalWindow(new Instant(-100L), new Instant(100L)); - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void getReturnsProvidedWindows() { - assertThat( - WindowSupplier.of(IntervalWindow.getCoder(), ImmutableList.of(window, otherWindow)).get(), - Matchers.containsInAnyOrder(otherWindow, window)); - } - - @Test - public void getAfterSerialization() { - WindowSupplier supplier = - WindowSupplier.of(IntervalWindow.getCoder(), ImmutableList.of(window, otherWindow)); - assertThat( - SerializableUtils.clone(supplier).get(), - Matchers.containsInAnyOrder(otherWindow, window)); - } - - @Test - public void unencodableWindowFails() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Could not encode"); - WindowSupplier.of( - new FailingCoder(), - Collections.singleton(window)); - } - - private static class FailingCoder extends AtomicCoder { - @Override - public void encode( - BoundedWindow value, OutputStream outStream, Context context) - throws CoderException, IOException { - throw new CoderException("Test Enccode Exception"); - } - - @Override - public BoundedWindow decode( - InputStream inStream, Context context) throws CoderException, IOException { - throw new CoderException("Test Decode Exception"); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java deleted file mode 100644 index 35cb1aa111..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateQuantilesTest.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.runners.DirectPipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.ApproximateQuantiles.ApproximateQuantilesCombineFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.hamcrest.CoreMatchers; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeDiagnosingMatcher; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -/** - * Tests for {@link ApproximateQuantiles}. - */ -@RunWith(JUnit4.class) -public class ApproximateQuantilesTest { - - static final List> TABLE = Arrays.asList( - KV.of("a", 1), - KV.of("a", 2), - KV.of("a", 3), - KV.of("b", 1), - KV.of("b", 10), - KV.of("b", 10), - KV.of("b", 100) - ); - - public PCollection> createInputTable(Pipeline p) { - return p.apply(Create.of(TABLE).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - } - - @Test - public void testQuantilesGlobally() { - DirectPipeline p = DirectPipeline.createForTest(); - - PCollection input = intRangeCollection(p, 101); - PCollection> quantiles = - input.apply(ApproximateQuantiles.globally(5)); - - p.run(); - - DataflowAssert.that(quantiles) - .containsInAnyOrder(Arrays.asList(0, 25, 50, 75, 100)); - } - - @Test - public void testQuantilesGobally_comparable() { - DirectPipeline p = DirectPipeline.createForTest(); - - PCollection input = intRangeCollection(p, 101); - PCollection> quantiles = - input.apply( - ApproximateQuantiles.globally(5, new DescendingIntComparator())); - - p.run(); - - DataflowAssert.that(quantiles) - .containsInAnyOrder(Arrays.asList(100, 75, 50, 25, 0)); - } - - @Test - public void testQuantilesPerKey() { - Pipeline p = TestPipeline.create(); - - PCollection> input = createInputTable(p); - PCollection>> quantiles = input.apply( - ApproximateQuantiles.perKey(2)); - - DataflowAssert.that(quantiles) - .containsInAnyOrder( - KV.of("a", Arrays.asList(1, 3)), - KV.of("b", Arrays.asList(1, 100))); - p.run(); - - } - - @Test - public void testQuantilesPerKey_reversed() { - Pipeline p = TestPipeline.create(); - - PCollection> input = createInputTable(p); - PCollection>> quantiles = input.apply( - ApproximateQuantiles.perKey( - 2, new DescendingIntComparator())); - - DataflowAssert.that(quantiles) - .containsInAnyOrder( - KV.of("a", Arrays.asList(3, 1)), - KV.of("b", Arrays.asList(100, 1))); - p.run(); - } - - @Test - public void testSingleton() { - checkCombineFn( - ApproximateQuantilesCombineFn.create(5), - Arrays.asList(389), - Arrays.asList(389, 389, 389, 389, 389)); - } - - @Test - public void testSimpleQuantiles() { - checkCombineFn( - ApproximateQuantilesCombineFn.create(5), - intRange(101), - Arrays.asList(0, 25, 50, 75, 100)); - } - - @Test - public void testUnevenQuantiles() { - checkCombineFn( - ApproximateQuantilesCombineFn.create(37), - intRange(5000), - quantileMatcher(5000, 37, 20 /* tolerance */)); - } - - @Test - public void testLargerQuantiles() { - checkCombineFn( - ApproximateQuantilesCombineFn.create(50), - intRange(10001), - quantileMatcher(10001, 50, 20 /* tolerance */)); - } - - @Test - public void testTightEpsilon() { - checkCombineFn( - ApproximateQuantilesCombineFn.create(10).withEpsilon(0.01), - intRange(10001), - quantileMatcher(10001, 10, 5 /* tolerance */)); - } - - @Test - public void testDuplicates() { - int size = 101; - List all = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - all.addAll(intRange(size)); - } - checkCombineFn( - ApproximateQuantilesCombineFn.create(5), - all, - Arrays.asList(0, 25, 50, 75, 100)); - } - - @Test - public void testLotsOfDuplicates() { - List all = new ArrayList<>(); - all.add(1); - for (int i = 1; i < 300; i++) { - all.add(2); - } - for (int i = 300; i < 1000; i++) { - all.add(3); - } - checkCombineFn( - ApproximateQuantilesCombineFn.create(5), - all, - Arrays.asList(1, 2, 3, 3, 3)); - } - - @Test - public void testLogDistribution() { - List all = new ArrayList<>(); - for (int i = 1; i < 1000; i++) { - all.add((int) Math.log(i)); - } - checkCombineFn( - ApproximateQuantilesCombineFn.create(5), - all, - Arrays.asList(0, 5, 6, 6, 6)); - } - - @Test - public void testZipfianDistribution() { - List all = new ArrayList<>(); - for (int i = 1; i < 1000; i++) { - all.add(1000 / i); - } - checkCombineFn( - ApproximateQuantilesCombineFn.create(5), - all, - Arrays.asList(1, 1, 2, 4, 1000)); - } - - @Test - public void testAlternateComparator() { - List inputs = Arrays.asList( - "aa", "aaa", "aaaa", "b", "ccccc", "dddd", "zz"); - checkCombineFn( - ApproximateQuantilesCombineFn.create(3), - inputs, - Arrays.asList("aa", "b", "zz")); - checkCombineFn( - ApproximateQuantilesCombineFn.create(3, new OrderByLength()), - inputs, - Arrays.asList("b", "aaa", "ccccc")); - } - - @Test - public void testDisplayData() { - Top.Largest comparer = new Top.Largest(); - PTransform approxQuanitiles = ApproximateQuantiles.globally(20, comparer); - DisplayData displayData = DisplayData.from(approxQuanitiles); - - assertThat(displayData, hasDisplayItem("numQuantiles", 20)); - assertThat(displayData, hasDisplayItem("comparer", comparer.getClass())); - } - - private Matcher> quantileMatcher( - int size, int numQuantiles, int absoluteError) { - List> quantiles = new ArrayList<>(); - quantiles.add(CoreMatchers.is(0)); - for (int k = 1; k < numQuantiles - 1; k++) { - int expected = (int) (((double) (size - 1)) * k / (numQuantiles - 1)); - quantiles.add(new Between<>( - expected - absoluteError, expected + absoluteError)); - } - quantiles.add(CoreMatchers.is(size - 1)); - return contains(quantiles); - } - - private static class Between> - extends TypeSafeDiagnosingMatcher { - private final T min; - private final T max; - private Between(T min, T max) { - this.min = min; - this.max = max; - } - @Override - public void describeTo(Description description) { - description.appendText("is between " + min + " and " + max); - } - - @Override - protected boolean matchesSafely(T item, Description mismatchDescription) { - return min.compareTo(item) <= 0 && item.compareTo(max) <= 0; - } - } - - private static class DescendingIntComparator implements - SerializableComparator { - @Override - public int compare(Integer o1, Integer o2) { - return o2.compareTo(o1); - } - } - - private static class OrderByLength implements Comparator, Serializable { - @Override - public int compare(String a, String b) { - if (a.length() != b.length()) { - return a.length() - b.length(); - } else { - return a.compareTo(b); - } - } - } - - - private PCollection intRangeCollection(Pipeline p, int size) { - return p.apply("CreateIntsUpTo(" + size + ")", Create.of(intRange(size))); - } - - private List intRange(int size) { - List all = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - all.add(i); - } - return all; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java deleted file mode 100644 index 4426db5dcc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ApproximateUniqueTest.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.TestUtils; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests for the ApproximateUnique aggregator transform. - */ -@RunWith(JUnit4.class) -public class ApproximateUniqueTest implements Serializable { - // implements Serializable just to make it easy to use anonymous inner DoFn subclasses - - @Test - public void testEstimationErrorToSampleSize() { - assertEquals(40000, ApproximateUnique.sampleSizeFromEstimationError(0.01)); - assertEquals(10000, ApproximateUnique.sampleSizeFromEstimationError(0.02)); - assertEquals(2500, ApproximateUnique.sampleSizeFromEstimationError(0.04)); - assertEquals(1600, ApproximateUnique.sampleSizeFromEstimationError(0.05)); - assertEquals(400, ApproximateUnique.sampleSizeFromEstimationError(0.1)); - assertEquals(100, ApproximateUnique.sampleSizeFromEstimationError(0.2)); - assertEquals(25, ApproximateUnique.sampleSizeFromEstimationError(0.4)); - assertEquals(16, ApproximateUnique.sampleSizeFromEstimationError(0.5)); - } - - @Test - @Category(RunnableOnService.class) - public void testApproximateUniqueWithSmallInput() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply( - Create.of(Arrays.asList(1, 2, 3, 3))); - - PCollection estimate = input - .apply(ApproximateUnique.globally(1000)); - - DataflowAssert.thatSingleton(estimate).isEqualTo(3L); - - p.run(); - } - - @Test - public void testApproximateUniqueWithDuplicates() { - runApproximateUniqueWithDuplicates(100, 100, 100); - runApproximateUniqueWithDuplicates(1000, 1000, 100); - runApproximateUniqueWithDuplicates(1500, 1000, 100); - runApproximateUniqueWithDuplicates(10000, 1000, 100); - } - - private void runApproximateUniqueWithDuplicates(int elementCount, - int uniqueCount, int sampleSize) { - - assert elementCount >= uniqueCount; - List elements = Lists.newArrayList(); - for (int i = 0; i < elementCount; i++) { - elements.add(1.0 / (i % uniqueCount + 1)); - } - Collections.shuffle(elements); - - Pipeline p = TestPipeline.create(); - PCollection input = p.apply(Create.of(elements)); - PCollection estimate = - input.apply(ApproximateUnique.globally(sampleSize)); - - DataflowAssert.thatSingleton(estimate).satisfies(new VerifyEstimateFn(uniqueCount, sampleSize)); - - p.run(); - } - - @Test - public void testApproximateUniqueWithSkewedDistributions() { - runApproximateUniqueWithSkewedDistributions(100, 100, 100); - runApproximateUniqueWithSkewedDistributions(10000, 10000, 100); - runApproximateUniqueWithSkewedDistributions(10000, 1000, 100); - runApproximateUniqueWithSkewedDistributions(10000, 200, 100); - } - - @Test - public void testApproximateUniqueWithSkewedDistributionsAndLargeSampleSize() { - runApproximateUniqueWithSkewedDistributions(10000, 2000, 1000); - } - - private void runApproximateUniqueWithSkewedDistributions(int elementCount, - final int uniqueCount, final int sampleSize) { - List elements = Lists.newArrayList(); - // Zipf distribution with approximately elementCount items. - double s = 1 - 1.0 * uniqueCount / elementCount; - double maxCount = Math.pow(uniqueCount, s); - for (int k = 0; k < uniqueCount; k++) { - int count = Math.max(1, (int) Math.round(maxCount * Math.pow(k, -s))); - // Element k occurs count times. - for (int c = 0; c < count; c++) { - elements.add(k); - } - } - - Pipeline p = TestPipeline.create(); - PCollection input = p.apply(Create.of(elements)); - PCollection estimate = - input.apply(ApproximateUnique.globally(sampleSize)); - - DataflowAssert.thatSingleton(estimate).satisfies(new VerifyEstimateFn(uniqueCount, sampleSize)); - - p.run(); - } - - @Test - public void testApproximateUniquePerKey() { - List> elements = Lists.newArrayList(); - List keys = ImmutableList.of(20L, 50L, 100L); - int elementCount = 1000; - int sampleSize = 100; - // Use the key as the number of unique values. - for (long uniqueCount : keys) { - for (long value = 0; value < elementCount; value++) { - elements.add(KV.of(uniqueCount, value % uniqueCount)); - } - } - - Pipeline p = TestPipeline.create(); - PCollection> input = p.apply(Create.of(elements)); - PCollection> counts = - input.apply(ApproximateUnique.perKey(sampleSize)); - - DataflowAssert.that(counts).satisfies(new VerifyEstimatePerKeyFn(sampleSize)); - - p.run(); - - } - - /** - * Applies {@link ApproximateUnique} for different sample sizes and verifies - * that the estimation error falls within the maximum allowed error of - * {@code 2 / sqrt(sampleSize)}. - */ - @Test - public void testApproximateUniqueWithDifferentSampleSizes() { - runApproximateUniquePipeline(16); - runApproximateUniquePipeline(64); - runApproximateUniquePipeline(128); - runApproximateUniquePipeline(256); - runApproximateUniquePipeline(512); - runApproximateUniquePipeline(1000); - runApproximateUniquePipeline(1024); - try { - runApproximateUniquePipeline(15); - fail("Accepted sampleSize < 16"); - } catch (IllegalArgumentException e) { - assertTrue("Expected an exception due to sampleSize < 16", e.getMessage() - .startsWith("ApproximateUnique needs a sampleSize >= 16")); - } - } - - @Test - public void testApproximateUniqueGetName() { - assertEquals("ApproximateUnique.PerKey", ApproximateUnique.perKey(16).getName()); - assertEquals("ApproximateUnique.Globally", ApproximateUnique.globally(16).getName()); - } - - /** - * Applies {@code ApproximateUnique(sampleSize)} verifying that the estimation - * error falls within the maximum allowed error of {@code 2/sqrt(sampleSize)}. - */ - private static void runApproximateUniquePipeline(int sampleSize) { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(TEST_LINES)); - PCollection approximate = input.apply(ApproximateUnique.globally(sampleSize)); - final PCollectionView exact = - input - .apply(RemoveDuplicates.create()) - .apply(Count.globally()) - .apply(View.asSingleton()); - - PCollection> approximateAndExact = approximate - .apply(ParDo.of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.sideInput(exact))); - } - }) - .withSideInputs(exact)); - - DataflowAssert.that(approximateAndExact).satisfies(new VerifyEstimatePerKeyFn(sampleSize)); - - p.run(); - } - - private static final int TEST_PAGES = 100; - private static final List TEST_LINES = - new ArrayList<>(TEST_PAGES * TestUtils.LINES.size()); - - static { - for (int i = 0; i < TEST_PAGES; i++) { - TEST_LINES.addAll(TestUtils.LINES); - } - } - - /** - * Checks that the estimation error, i.e., the difference between - * {@code uniqueCount} and {@code estimate} is less than - * {@code 2 / sqrt(sampleSize}). - */ - private static void verifyEstimate(long uniqueCount, int sampleSize, long estimate) { - if (uniqueCount < sampleSize) { - assertEquals("Number of hashes is less than the sample size. " - + "Estimate should be exact", uniqueCount, estimate); - } - - double error = 100.0 * Math.abs(estimate - uniqueCount) / uniqueCount; - double maxError = 100.0 * 2 / Math.sqrt(sampleSize); - - assertTrue("Estimate= " + estimate + " Actual=" + uniqueCount + " Error=" - + error + "%, MaxError=" + maxError + "%.", error < maxError); - - assertTrue("Estimate= " + estimate + " Actual=" + uniqueCount + " Error=" - + error + "%, MaxError=" + maxError + "%.", error < maxError); - } - - private static class VerifyEstimateFn implements SerializableFunction { - private long uniqueCount; - private int sampleSize; - - public VerifyEstimateFn(long uniqueCount, int sampleSize) { - this.uniqueCount = uniqueCount; - this.sampleSize = sampleSize; - } - - @Override - public Void apply(Long estimate) { - verifyEstimate(uniqueCount, sampleSize, estimate); - return null; - } - } - - private static class VerifyEstimatePerKeyFn - implements SerializableFunction>, Void> { - - private int sampleSize; - - public VerifyEstimatePerKeyFn(int sampleSize) { - this.sampleSize = sampleSize; - } - - @Override - public Void apply(Iterable> estimatePerKey) { - for (KV result : estimatePerKey) { - verifyEstimate(result.getKey(), sampleSize, result.getValue()); - } - return null; - } - } - - @Test - public void testDisplayData() { - ApproximateUnique.Globally specifiedSampleSize = ApproximateUnique.globally(1234); - ApproximateUnique.PerKey specifiedMaxError = ApproximateUnique.perKey(0.1234); - - assertThat(DisplayData.from(specifiedSampleSize), hasDisplayItem("sampleSize", 1234)); - - DisplayData maxErrorDisplayData = DisplayData.from(specifiedMaxError); - assertThat(maxErrorDisplayData, hasDisplayItem("maximumEstimationError", 0.1234)); - assertThat("calculated sampleSize should be included", maxErrorDisplayData, - hasDisplayItem("sampleSize")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java deleted file mode 100644 index abffe4055e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineFnsTest.java +++ /dev/null @@ -1,480 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.NullableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Combine.BinaryCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineFns.CoCombineResult; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; -import com.google.cloud.dataflow.sdk.transforms.Min.MinIntegerFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - -/** - * Unit tests for {@link CombineFns}. - */ -@RunWith(JUnit4.class) -public class CombineFnsTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testDuplicatedTags() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("it is already present in the composition"); - - TupleTag tag = new TupleTag(); - CombineFns.compose() - .with(new GetIntegerFunction(), new MaxIntegerFn(), tag) - .with(new GetIntegerFunction(), new MinIntegerFn(), tag); - } - - @Test - public void testDuplicatedTagsKeyed() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("it is already present in the composition"); - - TupleTag tag = new TupleTag(); - CombineFns.composeKeyed() - .with(new GetIntegerFunction(), new MaxIntegerFn(), tag) - .with(new GetIntegerFunction(), new MinIntegerFn(), tag); - } - - @Test - public void testDuplicatedTagsWithContext() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("it is already present in the composition"); - - TupleTag tag = new TupleTag(); - CombineFns.compose() - .with( - new GetUserStringFunction(), - new ConcatStringWithContext(null /* view */).forKey("G", StringUtf8Coder.of()), - tag) - .with( - new GetUserStringFunction(), - new ConcatStringWithContext(null /* view */).forKey("G", StringUtf8Coder.of()), - tag); - } - - @Test - public void testDuplicatedTagsWithContextKeyed() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("it is already present in the composition"); - - TupleTag tag = new TupleTag(); - CombineFns.composeKeyed() - .with( - new GetUserStringFunction(), - new ConcatStringWithContext(null /* view */), - tag) - .with( - new GetUserStringFunction(), - new ConcatStringWithContext(null /* view */), - tag); - } - - @Test - @Category(RunnableOnService.class) - public void testComposedCombine() { - Pipeline p = TestPipeline.create(); - p.getCoderRegistry().registerCoder(UserString.class, UserStringCoder.of()); - - PCollection>> perKeyInput = p.apply( - Create.timestamped( - Arrays.asList( - KV.of("a", KV.of(1, UserString.of("1"))), - KV.of("a", KV.of(1, UserString.of("1"))), - KV.of("a", KV.of(4, UserString.of("4"))), - KV.of("b", KV.of(1, UserString.of("1"))), - KV.of("b", KV.of(13, UserString.of("13")))), - Arrays.asList(0L, 4L, 7L, 10L, 16L)) - .withCoder(KvCoder.of( - StringUtf8Coder.of(), - KvCoder.of(BigEndianIntegerCoder.of(), UserStringCoder.of())))); - - TupleTag maxIntTag = new TupleTag(); - TupleTag concatStringTag = new TupleTag(); - PCollection>> combineGlobally = perKeyInput - .apply(Values.>create()) - .apply(Combine.globally(CombineFns.compose() - .with( - new GetIntegerFunction(), - new MaxIntegerFn(), - maxIntTag) - .with( - new GetUserStringFunction(), - new ConcatString(), - concatStringTag))) - .apply(WithKeys.of("global")) - .apply( - "ExtractGloballyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); - - PCollection>> combinePerKey = perKeyInput - .apply(Combine.perKey(CombineFns.composeKeyed() - .with( - new GetIntegerFunction(), - new MaxIntegerFn().asKeyedFn(), - maxIntTag) - .with( - new GetUserStringFunction(), - new ConcatString().asKeyedFn(), - concatStringTag))) - .apply("ExtractPerKeyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); - DataflowAssert.that(combineGlobally).containsInAnyOrder( - KV.of("global", KV.of(13, "111134"))); - DataflowAssert.that(combinePerKey).containsInAnyOrder( - KV.of("a", KV.of(4, "114")), - KV.of("b", KV.of(13, "113"))); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testComposedCombineWithContext() { - Pipeline p = TestPipeline.create(); - p.getCoderRegistry().registerCoder(UserString.class, UserStringCoder.of()); - - PCollectionView view = p - .apply(Create.of("I")) - .apply(View.asSingleton()); - - PCollection>> perKeyInput = p.apply( - Create.timestamped( - Arrays.asList( - KV.of("a", KV.of(1, UserString.of("1"))), - KV.of("a", KV.of(1, UserString.of("1"))), - KV.of("a", KV.of(4, UserString.of("4"))), - KV.of("b", KV.of(1, UserString.of("1"))), - KV.of("b", KV.of(13, UserString.of("13")))), - Arrays.asList(0L, 4L, 7L, 10L, 16L)) - .withCoder(KvCoder.of( - StringUtf8Coder.of(), - KvCoder.of(BigEndianIntegerCoder.of(), UserStringCoder.of())))); - - TupleTag maxIntTag = new TupleTag(); - TupleTag concatStringTag = new TupleTag(); - PCollection>> combineGlobally = perKeyInput - .apply(Values.>create()) - .apply(Combine.globally(CombineFns.compose() - .with( - new GetIntegerFunction(), - new MaxIntegerFn(), - maxIntTag) - .with( - new GetUserStringFunction(), - new ConcatStringWithContext(view).forKey("G", StringUtf8Coder.of()), - concatStringTag)) - .withoutDefaults() - .withSideInputs(ImmutableList.of(view))) - .apply(WithKeys.of("global")) - .apply( - "ExtractGloballyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); - - PCollection>> combinePerKey = perKeyInput - .apply(Combine.perKey(CombineFns.composeKeyed() - .with( - new GetIntegerFunction(), - new MaxIntegerFn().asKeyedFn(), - maxIntTag) - .with( - new GetUserStringFunction(), - new ConcatStringWithContext(view), - concatStringTag)) - .withSideInputs(ImmutableList.of(view))) - .apply("ExtractPerKeyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); - DataflowAssert.that(combineGlobally).containsInAnyOrder( - KV.of("global", KV.of(13, "111134GI"))); - DataflowAssert.that(combinePerKey).containsInAnyOrder( - KV.of("a", KV.of(4, "114Ia")), - KV.of("b", KV.of(13, "113Ib"))); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testComposedCombineNullValues() { - Pipeline p = TestPipeline.create(); - p.getCoderRegistry().registerCoder(UserString.class, NullableCoder.of(UserStringCoder.of())); - p.getCoderRegistry().registerCoder(String.class, NullableCoder.of(StringUtf8Coder.of())); - - PCollection>> perKeyInput = p.apply( - Create.timestamped( - Arrays.asList( - KV.of("a", KV.of(1, UserString.of("1"))), - KV.of("a", KV.of(1, UserString.of("1"))), - KV.of("a", KV.of(4, UserString.of("4"))), - KV.of("b", KV.of(1, UserString.of("1"))), - KV.of("b", KV.of(13, UserString.of("13")))), - Arrays.asList(0L, 4L, 7L, 10L, 16L)) - .withCoder(KvCoder.of( - StringUtf8Coder.of(), - KvCoder.of( - BigEndianIntegerCoder.of(), NullableCoder.of(UserStringCoder.of()))))); - - TupleTag maxIntTag = new TupleTag(); - TupleTag concatStringTag = new TupleTag(); - - PCollection>> combinePerKey = perKeyInput - .apply(Combine.perKey(CombineFns.composeKeyed() - .with( - new GetIntegerFunction(), - new MaxIntegerFn().asKeyedFn(), - maxIntTag) - .with( - new GetUserStringFunction(), - new OutputNullString().asKeyedFn(), - concatStringTag))) - .apply("ExtractPerKeyResult", ParDo.of(new ExtractResultDoFn(maxIntTag, concatStringTag))); - DataflowAssert.that(combinePerKey).containsInAnyOrder( - KV.of("a", KV.of(4, (String) null)), - KV.of("b", KV.of(13, (String) null))); - p.run(); - } - - @Test - public void testComposedCombineDisplayData() { - SimpleFunction extractFn = new SimpleFunction() { - @Override - public String apply(String input) { - return input; - } - }; - - DisplayDataCombineFn combineFn1 = new DisplayDataCombineFn("value1"); - DisplayDataCombineFn combineFn2 = new DisplayDataCombineFn("value2"); - - CombineFns.ComposedCombineFn composedCombine = CombineFns.compose() - .with(extractFn, combineFn1, new TupleTag()) - .with(extractFn, combineFn2, new TupleTag()); - - DisplayData displayData = DisplayData.from(composedCombine); - assertThat(displayData, hasDisplayItem("combineFn1", combineFn1.getClass())); - assertThat(displayData, hasDisplayItem("combineFn2", combineFn2.getClass())); - - String nsBase = DisplayDataCombineFn.class.getName(); - assertThat(displayData, includesDisplayDataFrom(combineFn1, nsBase + "#1")); - assertThat(displayData, includesDisplayDataFrom(combineFn2, nsBase + "#2")); - } - - private static class DisplayDataCombineFn extends Combine.CombineFn { - private final String value; - private static int i; - private final int id; - - DisplayDataCombineFn(String value) { - id = ++i; - this.value = value; - } - - @Override - public String createAccumulator() { - return null; - } - - @Override - public String addInput(String accumulator, String input) { - return null; - } - - @Override - public String mergeAccumulators(Iterable accumulators) { - return null; - } - - @Override - public String extractOutput(String accumulator) { - return null; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("uniqueKey" + id, value)) - .add(DisplayData.item("sharedKey", value)); - } - } - - private static class UserString implements Serializable { - private String strValue; - - static UserString of(String strValue) { - UserString ret = new UserString(); - ret.strValue = strValue; - return ret; - } - } - - private static class UserStringCoder extends StandardCoder { - public static UserStringCoder of() { - return INSTANCE; - } - - private static final UserStringCoder INSTANCE = new UserStringCoder(); - - @Override - public void encode(UserString value, OutputStream outStream, Context context) - throws CoderException, IOException { - StringUtf8Coder.of().encode(value.strValue, outStream, context); - } - - @Override - public UserString decode(InputStream inStream, Context context) - throws CoderException, IOException { - return UserString.of(StringUtf8Coder.of().decode(inStream, context)); - } - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public void verifyDeterministic() throws NonDeterministicException {} - } - - private static class GetIntegerFunction - extends SimpleFunction, Integer> { - @Override - public Integer apply(KV input) { - return input.getKey(); - } - } - - private static class GetUserStringFunction - extends SimpleFunction, UserString> { - @Override - public UserString apply(KV input) { - return input.getValue(); - } - } - - private static class ConcatString extends BinaryCombineFn { - @Override - public UserString apply(UserString left, UserString right) { - String retStr = left.strValue + right.strValue; - char[] chars = retStr.toCharArray(); - Arrays.sort(chars); - return UserString.of(new String(chars)); - } - } - - private static class OutputNullString extends BinaryCombineFn { - @Override - public UserString apply(UserString left, UserString right) { - return null; - } - } - - private static class ConcatStringWithContext - extends KeyedCombineFnWithContext { - private final PCollectionView view; - - private ConcatStringWithContext(PCollectionView view) { - this.view = view; - } - - @Override - public UserString createAccumulator(String key, CombineWithContext.Context c) { - return UserString.of(key + c.sideInput(view)); - } - - @Override - public UserString addInput( - String key, UserString accumulator, UserString input, CombineWithContext.Context c) { - assertThat(accumulator.strValue, Matchers.startsWith(key + c.sideInput(view))); - accumulator.strValue += input.strValue; - return accumulator; - } - - @Override - public UserString mergeAccumulators( - String key, Iterable accumulators, CombineWithContext.Context c) { - String keyPrefix = key + c.sideInput(view); - String all = keyPrefix; - for (UserString accumulator : accumulators) { - assertThat(accumulator.strValue, Matchers.startsWith(keyPrefix)); - all += accumulator.strValue.substring(keyPrefix.length()); - accumulator.strValue = "cleared in mergeAccumulators"; - } - return UserString.of(all); - } - - @Override - public UserString extractOutput( - String key, UserString accumulator, CombineWithContext.Context c) { - assertThat(accumulator.strValue, Matchers.startsWith(key + c.sideInput(view))); - char[] chars = accumulator.strValue.toCharArray(); - Arrays.sort(chars); - return UserString.of(new String(chars)); - } - } - - private static class ExtractResultDoFn - extends DoFn, KV>>{ - - private final TupleTag maxIntTag; - private final TupleTag concatStringTag; - - ExtractResultDoFn(TupleTag maxIntTag, TupleTag concatStringTag) { - this.maxIntTag = maxIntTag; - this.concatStringTag = concatStringTag; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - UserString userString = c.element().getValue().get(concatStringTag); - KV value = KV.of( - c.element().getValue().get(maxIntTag), - userString == null ? null : userString.strValue); - c.output(KV.of(c.element().getKey(), value)); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java deleted file mode 100644 index bdd8cf2449..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CombineTest.java +++ /dev/null @@ -1,1195 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.CustomCoder; -import com.google.cloud.dataflow.sdk.coders.DoubleCoder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Repeatedly; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.util.PerKeyCombineFnRunners; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Random; -import java.util.Set; - -/** - * Tests for Combine transforms. - */ -@RunWith(JUnit4.class) -public class CombineTest implements Serializable { - // This test is Serializable, just so that it's easy to have - // anonymous inner classes inside the non-static test methods. - - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] TABLE = new KV[] { - KV.of("a", 1), - KV.of("a", 1), - KV.of("a", 4), - KV.of("b", 1), - KV.of("b", 13), - }; - - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] EMPTY_TABLE = new KV[] { - }; - - static final Integer[] NUMBERS = new Integer[] { - 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 - }; - - @Mock private DoFn.ProcessContext processContext; - - PCollection> createInput(Pipeline p, - KV[] table) { - return p.apply(Create.of(Arrays.asList(table)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - } - - private void runTestSimpleCombine(KV[] table, - int globalSum, - KV[] perKeyCombines) { - Pipeline p = TestPipeline.create(); - PCollection> input = createInput(p, table); - - PCollection sum = input - .apply(Values.create()) - .apply(Combine.globally(new SumInts())); - - // Java 8 will infer. - PCollection> sumPerKey = input - .apply(Combine.perKey(new TestKeyedCombineFn())); - - DataflowAssert.that(sum).containsInAnyOrder(globalSum); - DataflowAssert.that(sumPerKey).containsInAnyOrder(perKeyCombines); - - p.run(); - } - - private void runTestSimpleCombineWithContext(KV[] table, - int globalSum, - KV[] perKeyCombines, - String[] globallyCombines) { - Pipeline p = TestPipeline.create(); - PCollection> perKeyInput = createInput(p, table); - PCollection globallyInput = perKeyInput.apply(Values.create()); - - PCollection sum = globallyInput.apply("Sum", Combine.globally(new SumInts())); - - PCollectionView globallySumView = sum.apply(View.asSingleton()); - - // Java 8 will infer. - PCollection> combinePerKey = perKeyInput - .apply(Combine.perKey(new TestKeyedCombineFnWithContext(globallySumView)) - .withSideInputs(Arrays.asList(globallySumView))); - - PCollection combineGlobally = globallyInput - .apply(Combine.globally(new TestKeyedCombineFnWithContext(globallySumView) - .forKey("G", StringUtf8Coder.of())) - .withoutDefaults() - .withSideInputs(Arrays.asList(globallySumView))); - - DataflowAssert.that(sum).containsInAnyOrder(globalSum); - DataflowAssert.that(combinePerKey).containsInAnyOrder(perKeyCombines); - DataflowAssert.that(combineGlobally).containsInAnyOrder(globallyCombines); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings({"rawtypes", "unchecked"}) - public void testSimpleCombine() { - runTestSimpleCombine(TABLE, 20, new KV[] { - KV.of("a", "114a"), KV.of("b", "113b") }); - } - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings({"rawtypes", "unchecked"}) - public void testSimpleCombineWithContext() { - runTestSimpleCombineWithContext(TABLE, 20, - new KV[] {KV.of("a", "01124a"), KV.of("b", "01123b") }, - new String[] {"01111234G"}); - } - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings({"rawtypes", "unchecked"}) - public void testSimpleCombineWithContextEmpty() { - runTestSimpleCombineWithContext(EMPTY_TABLE, 0, new KV[] {}, new String[] {}); - } - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings({"rawtypes", "unchecked"}) - public void testSimpleCombineEmpty() { - runTestSimpleCombine(EMPTY_TABLE, 0, new KV[] { }); - } - - @SuppressWarnings("unchecked") - private void runTestBasicCombine(KV[] table, - Set globalUnique, - KV>[] perKeyUnique) { - Pipeline p = TestPipeline.create(); - p.getCoderRegistry().registerCoder(Set.class, SetCoder.class); - PCollection> input = createInput(p, table); - - PCollection> unique = input - .apply(Values.create()) - .apply(Combine.globally(new UniqueInts())); - - // Java 8 will infer. - PCollection>> uniquePerKey = input - .apply(Combine.>perKey(new UniqueInts())); - - DataflowAssert.that(unique).containsInAnyOrder(globalUnique); - DataflowAssert.that(uniquePerKey).containsInAnyOrder(perKeyUnique); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings({"rawtypes", "unchecked"}) - public void testBasicCombine() { - runTestBasicCombine(TABLE, ImmutableSet.of(1, 13, 4), new KV[] { - KV.of("a", (Set) ImmutableSet.of(1, 4)), - KV.of("b", (Set) ImmutableSet.of(1, 13)) }); - } - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings("rawtypes") - public void testBasicCombineEmpty() { - runTestBasicCombine(EMPTY_TABLE, ImmutableSet.of(), new KV[] { }); - } - - private void runTestAccumulatingCombine(KV[] table, - Double globalMean, - KV[] perKeyMeans) { - Pipeline p = TestPipeline.create(); - PCollection> input = createInput(p, table); - - PCollection mean = input - .apply(Values.create()) - .apply(Combine.globally(new MeanInts())); - - // Java 8 will infer. - PCollection> meanPerKey = input.apply( - Combine.perKey(new MeanInts())); - - DataflowAssert.that(mean).containsInAnyOrder(globalMean); - DataflowAssert.that(meanPerKey).containsInAnyOrder(perKeyMeans); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFixedWindowsCombine() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.timestamped(Arrays.asList(TABLE), - Arrays.asList(0L, 1L, 6L, 7L, 8L)) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into(FixedWindows.of(Duration.millis(2)))); - - PCollection sum = input - .apply(Values.create()) - .apply(Combine.globally(new SumInts()).withoutDefaults()); - - PCollection> sumPerKey = input - .apply(Combine.perKey(new TestKeyedCombineFn())); - - DataflowAssert.that(sum).containsInAnyOrder(2, 5, 13); - DataflowAssert.that(sumPerKey).containsInAnyOrder( - KV.of("a", "11a"), - KV.of("a", "4a"), - KV.of("b", "1b"), - KV.of("b", "13b")); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFixedWindowsCombineWithContext() { - Pipeline p = TestPipeline.create(); - - PCollection> perKeyInput = - p.apply(Create.timestamped(Arrays.asList(TABLE), - Arrays.asList(0L, 1L, 6L, 7L, 8L)) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into(FixedWindows.of(Duration.millis(2)))); - - PCollection globallyInput = perKeyInput.apply(Values.create()); - - PCollection sum = globallyInput - .apply("Sum", Combine.globally(new SumInts()).withoutDefaults()); - - PCollectionView globallySumView = sum.apply(View.asSingleton()); - - PCollection> combinePerKeyWithContext = perKeyInput - .apply(Combine.perKey(new TestKeyedCombineFnWithContext(globallySumView)) - .withSideInputs(Arrays.asList(globallySumView))); - - PCollection combineGloballyWithContext = globallyInput - .apply(Combine.globally(new TestKeyedCombineFnWithContext(globallySumView) - .forKey("G", StringUtf8Coder.of())) - .withoutDefaults() - .withSideInputs(Arrays.asList(globallySumView))); - - DataflowAssert.that(sum).containsInAnyOrder(2, 5, 13); - DataflowAssert.that(combinePerKeyWithContext).containsInAnyOrder( - KV.of("a", "112a"), - KV.of("a", "45a"), - KV.of("b", "15b"), - KV.of("b", "1133b")); - DataflowAssert.that(combineGloballyWithContext).containsInAnyOrder("112G", "145G", "1133G"); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testSlidingWindowsCombineWithContext() { - Pipeline p = TestPipeline.create(); - - PCollection> perKeyInput = - p.apply(Create.timestamped(Arrays.asList(TABLE), - Arrays.asList(2L, 3L, 8L, 9L, 10L)) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into(SlidingWindows.of(Duration.millis(2)))); - - PCollection globallyInput = perKeyInput.apply(Values.create()); - - PCollection sum = globallyInput - .apply("Sum", Combine.globally(new SumInts()).withoutDefaults()); - - PCollectionView globallySumView = sum.apply(View.asSingleton()); - - PCollection> combinePerKeyWithContext = perKeyInput - .apply(Combine.perKey(new TestKeyedCombineFnWithContext(globallySumView)) - .withSideInputs(Arrays.asList(globallySumView))); - - PCollection combineGloballyWithContext = globallyInput - .apply(Combine.globally(new TestKeyedCombineFnWithContext(globallySumView) - .forKey("G", StringUtf8Coder.of())) - .withoutDefaults() - .withSideInputs(Arrays.asList(globallySumView))); - - DataflowAssert.that(sum).containsInAnyOrder(1, 2, 1, 4, 5, 14, 13); - DataflowAssert.that(combinePerKeyWithContext).containsInAnyOrder( - KV.of("a", "11a"), - KV.of("a", "112a"), - KV.of("a", "11a"), - KV.of("a", "44a"), - KV.of("a", "45a"), - KV.of("b", "15b"), - KV.of("b", "11134b"), - KV.of("b", "1133b")); - DataflowAssert.that(combineGloballyWithContext).containsInAnyOrder( - "11G", "112G", "11G", "44G", "145G", "11134G", "1133G"); - p.run(); - } - - private static class FormatPaneInfo extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + ": " + c.pane().isLast()); - } - } - - @Test - @Category(RunnableOnService.class) - public void testGlobalCombineWithDefaultsAndTriggers() { - Pipeline p = TestPipeline.create(); - PCollection input = p.apply(Create.of(1, 1)); - - PCollection output = input - .apply(Window.into(new GlobalWindows()) - .triggering(AfterPane.elementCountAtLeast(1)) - .accumulatingFiredPanes() - .withAllowedLateness(new Duration(0))) - .apply(Sum.integersGlobally()) - .apply(ParDo.of(new FormatPaneInfo())); - - DataflowAssert.that(output).containsInAnyOrder("1: false", "2: true"); - } - - @Test - @Category(RunnableOnService.class) - public void testSessionsCombine() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.timestamped(Arrays.asList(TABLE), - Arrays.asList(0L, 4L, 7L, 10L, 16L)) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into(Sessions.withGapDuration(Duration.millis(5)))); - - PCollection sum = input - .apply(Values.create()) - .apply(Combine.globally(new SumInts()).withoutDefaults()); - - PCollection> sumPerKey = input - .apply(Combine.perKey(new TestKeyedCombineFn())); - - DataflowAssert.that(sum).containsInAnyOrder(7, 13); - DataflowAssert.that(sumPerKey).containsInAnyOrder( - KV.of("a", "114a"), - KV.of("b", "1b"), - KV.of("b", "13b")); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testSessionsCombineWithContext() { - Pipeline p = TestPipeline.create(); - - PCollection> perKeyInput = - p.apply(Create.timestamped(Arrays.asList(TABLE), - Arrays.asList(0L, 4L, 7L, 10L, 16L)) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection globallyInput = perKeyInput.apply(Values.create()); - - PCollection fixedWindowsSum = globallyInput - .apply("FixedWindows", - Window.into(FixedWindows.of(Duration.millis(5)))) - .apply("Sum", Combine.globally(new SumInts()).withoutDefaults()); - - PCollectionView globallyFixedWindowsView = - fixedWindowsSum.apply(View.asSingleton().withDefaultValue(0)); - - PCollection> sessionsCombinePerKey = perKeyInput - .apply("PerKey Input Sessions", - Window.>into(Sessions.withGapDuration(Duration.millis(5)))) - .apply(Combine.perKey(new TestKeyedCombineFnWithContext(globallyFixedWindowsView)) - .withSideInputs(Arrays.asList(globallyFixedWindowsView))); - - PCollection sessionsCombineGlobally = globallyInput - .apply("Globally Input Sessions", - Window.into(Sessions.withGapDuration(Duration.millis(5)))) - .apply(Combine.globally(new TestKeyedCombineFnWithContext(globallyFixedWindowsView) - .forKey("G", StringUtf8Coder.of())) - .withoutDefaults() - .withSideInputs(Arrays.asList(globallyFixedWindowsView))); - - DataflowAssert.that(fixedWindowsSum).containsInAnyOrder(2, 4, 1, 13); - DataflowAssert.that(sessionsCombinePerKey).containsInAnyOrder( - KV.of("a", "1114a"), - KV.of("b", "11b"), - KV.of("b", "013b")); - DataflowAssert.that(sessionsCombineGlobally).containsInAnyOrder("11114G", "013G"); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedCombineEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection mean = p - .apply(Create.of().withCoder(BigEndianIntegerCoder.of())) - .apply(Window.into(FixedWindows.of(Duration.millis(1)))) - .apply(Combine.globally(new MeanInts()).withoutDefaults()); - - DataflowAssert.that(mean).empty(); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testAccumulatingCombine() { - runTestAccumulatingCombine(TABLE, 4.0, new KV[] { - KV.of("a", 2.0), KV.of("b", 7.0) }); - } - - @Test - @Category(RunnableOnService.class) - public void testAccumulatingCombineEmpty() { - runTestAccumulatingCombine(EMPTY_TABLE, 0.0, new KV[] { }); - } - - // Checks that Min, Max, Mean, Sum (operations that pass-through to Combine), - // provide their own top-level name. - @Test - public void testCombinerNames() { - Combine.PerKey min = Min.integersPerKey(); - Combine.PerKey max = Max.integersPerKey(); - Combine.PerKey mean = Mean.perKey(); - Combine.PerKey sum = Sum.integersPerKey(); - - assertThat(min.getName(), Matchers.startsWith("Min")); - assertThat(max.getName(), Matchers.startsWith("Max")); - assertThat(mean.getName(), Matchers.startsWith("Mean")); - assertThat(sum.getName(), Matchers.startsWith("Sum")); - } - - @Test - public void testAddInputsRandomly() { - TestCounter counter = new TestCounter(); - Combine.KeyedCombineFn< - String, Integer, TestCounter.Counter, Iterable> fn = - counter.asKeyedFn(); - - List accums = DirectPipelineRunner.TestCombineDoFn.addInputsRandomly( - PerKeyCombineFnRunners.create(fn), "bob", Arrays.asList(NUMBERS), new Random(42), - processContext); - - assertThat(accums, Matchers.contains( - counter.new Counter(3, 2, 0, 0), - counter.new Counter(131, 5, 0, 0), - counter.new Counter(8, 2, 0, 0), - counter.new Counter(1, 1, 0, 0))); - } - - private static final SerializableFunction hotKeyFanout = - new SerializableFunction() { - @Override - public Integer apply(String input) { - return input.equals("a") ? 3 : 0; - } - }; - - private static final SerializableFunction splitHotKeyFanout = - new SerializableFunction() { - @Override - public Integer apply(String input) { - return Math.random() < 0.5 ? 3 : 0; - } - }; - - @Test - @Category(RunnableOnService.class) - public void testHotKeyCombining() { - Pipeline p = TestPipeline.create(); - PCollection> input = copy(createInput(p, TABLE), 10); - - KeyedCombineFn mean = - new MeanInts().asKeyedFn(); - PCollection> coldMean = input.apply("ColdMean", - Combine.perKey(mean).withHotKeyFanout(0)); - PCollection> warmMean = input.apply("WarmMean", - Combine.perKey(mean).withHotKeyFanout(hotKeyFanout)); - PCollection> hotMean = input.apply("HotMean", - Combine.perKey(mean).withHotKeyFanout(5)); - PCollection> splitMean = input.apply("SplitMean", - Combine.perKey(mean).withHotKeyFanout(splitHotKeyFanout)); - - List> expected = Arrays.asList(KV.of("a", 2.0), KV.of("b", 7.0)); - DataflowAssert.that(coldMean).containsInAnyOrder(expected); - DataflowAssert.that(warmMean).containsInAnyOrder(expected); - DataflowAssert.that(hotMean).containsInAnyOrder(expected); - DataflowAssert.that(splitMean).containsInAnyOrder(expected); - - p.run(); - } - - private static class GetLast extends DoFn { - @Override - public void processElement(ProcessContext c) { - if (c.pane().isLast()) { - c.output(c.element()); - } - } - } - - @Test - @Category(RunnableOnService.class) - public void testHotKeyCombiningWithAccumulationMode() { - Pipeline p = TestPipeline.create(); - PCollection input = p.apply(Create.of(1, 2, 3, 4, 5)); - - PCollection output = input - .apply(Window.into(new GlobalWindows()) - .triggering(Repeatedly.forever(AfterPane.elementCountAtLeast(1))) - .accumulatingFiredPanes() - .withAllowedLateness(new Duration(0), ClosingBehavior.FIRE_ALWAYS)) - .apply(Sum.integersGlobally().withoutDefaults().withFanout(2)) - .apply(ParDo.of(new GetLast())); - - DataflowAssert.that(output).containsInAnyOrder(15); - - p.run(); - } - - @Test - public void testBinaryCombineFn() { - Pipeline p = TestPipeline.create(); - PCollection> input = copy(createInput(p, TABLE), 2); - PCollection> intProduct = input - .apply("IntProduct", Combine.perKey(new TestProdInt())); - PCollection> objProduct = input - .apply("ObjProduct", Combine.perKey(new TestProdObj())); - - List> expected = Arrays.asList(KV.of("a", 16), KV.of("b", 169)); - DataflowAssert.that(intProduct).containsInAnyOrder(expected); - DataflowAssert.that(objProduct).containsInAnyOrder(expected); - - p.run(); - } - - @Test - public void testBinaryCombineFnWithNulls() { - checkCombineFn(new NullCombiner(), Arrays.asList(3, 3, 5), 45); - checkCombineFn(new NullCombiner(), Arrays.asList(null, 3, 5), 30); - checkCombineFn(new NullCombiner(), Arrays.asList(3, 3, null), 18); - checkCombineFn(new NullCombiner(), Arrays.asList(null, 3, null), 12); - checkCombineFn(new NullCombiner(), Arrays.asList(null, null, null), 8); - } - - private static final class TestProdInt extends Combine.BinaryCombineIntegerFn { - @Override - public int apply(int left, int right) { - return left * right; - } - - @Override - public int identity() { - return 1; - } - } - - private static final class TestProdObj extends Combine.BinaryCombineFn { - @Override - public Integer apply(Integer left, Integer right) { - return left * right; - } - } - - /** - * Computes the product, considering null values to be 2. - */ - private static final class NullCombiner extends Combine.BinaryCombineFn { - @Override - public Integer apply(Integer left, Integer right) { - return (left == null ? 2 : left) * (right == null ? 2 : right); - } - } - - @Test - @Category(RunnableOnService.class) - public void testCombineGloballyAsSingletonView() { - Pipeline p = TestPipeline.create(); - final PCollectionView view = p - .apply("CreateEmptySideInput", Create.of().withCoder(BigEndianIntegerCoder.of())) - .apply(Sum.integersGlobally().asSingletonView()); - - PCollection output = p - .apply("CreateVoidMainInput", Create.of((Void) null)) - .apply("OutputSideInput", ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.sideInput(view)); - } - }).withSideInputs(view)); - - DataflowAssert.thatSingleton(output).isEqualTo(0); - p.run(); - } - - @Test - public void testCombineGetName() { - assertEquals("Combine.Globally", Combine.globally(new SumInts()).getName()); - assertEquals( - "MyCombineGlobally", Combine.globally(new SumInts()).named("MyCombineGlobally").getName()); - assertEquals( - "Combine.GloballyAsSingletonView", - Combine.globally(new SumInts()).asSingletonView().getName()); - assertEquals("Combine.PerKey", Combine.perKey(new TestKeyedCombineFn()).getName()); - assertEquals( - "MyCombinePerKey", - Combine.perKey(new TestKeyedCombineFn()).named("MyCombinePerKey").getName()); - assertEquals( - "Combine.PerKeyWithHotKeyFanout", - Combine.perKey(new TestKeyedCombineFn()).withHotKeyFanout(10).getName()); - } - - @Test - public void testDisplayData() { - UniqueInts combineFn = new UniqueInts() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("fnMetadata", "foobar")); - } - }; - Combine.Globally combine = Combine.globally(combineFn) - .withFanout(1234); - DisplayData displayData = DisplayData.from(combine); - - assertThat(displayData, hasDisplayItem("combineFn", combineFn.getClass())); - assertThat(displayData, hasDisplayItem("emitDefaultOnEmptyInput", true)); - assertThat(displayData, hasDisplayItem("fanout", 1234)); - assertThat(displayData, includesDisplayDataFrom(combineFn)); - } - - @Test - public void testDisplayDataForWrappedFn() { - UniqueInts combineFn = new UniqueInts() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - Combine.PerKey combine = Combine.perKey(combineFn); - DisplayData displayData = DisplayData.from(combine); - - assertThat(displayData, hasDisplayItem("combineFn", combineFn.getClass())); - assertThat(displayData, hasDisplayItem(hasNamespace(combineFn.getClass()))); - } - - @Test - public void testCombinePerKeyPrimitiveDisplayData() { - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - - CombineTest.UniqueInts combineFn = new CombineTest.UniqueInts(); - PTransform>, ? extends POutput> combine = - Combine.perKey(combineFn); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(combine, - KvCoder.of(VarIntCoder.of(), VarIntCoder.of())); - - assertThat("Combine.perKey should include the combineFn in its primitive transform", - displayData, hasItem(hasDisplayItem("combineFn", combineFn.getClass()))); - } - - //////////////////////////////////////////////////////////////////////////// - // Test classes, for different kinds of combining fns. - - /** Example SerializableFunction combiner. */ - public static class SumInts - implements SerializableFunction, Integer> { - @Override - public Integer apply(Iterable input) { - int sum = 0; - for (int item : input) { - sum += item; - } - return sum; - } - } - - /** Example CombineFn. */ - public static class UniqueInts extends - Combine.CombineFn, Set> { - - @Override - public Set createAccumulator() { - return new HashSet<>(); - } - - @Override - public Set addInput(Set accumulator, Integer input) { - accumulator.add(input); - return accumulator; - } - - @Override - public Set mergeAccumulators(Iterable> accumulators) { - Set all = new HashSet<>(); - for (Set part : accumulators) { - all.addAll(part); - } - return all; - } - - @Override - public Set extractOutput(Set accumulator) { - return accumulator; - } - } - - // Note: not a deterministic encoding - private static class SetCoder extends StandardCoder> { - - public static SetCoder of(Coder elementCoder) { - return new SetCoder<>(elementCoder); - } - - @JsonCreator - public static SetCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components) { - checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); - return of((Coder) components.get(0)); - } - - @SuppressWarnings("unused") // required for coder instantiation - public static List getInstanceComponents(Set exampleValue) { - return IterableCoder.getInstanceComponents(exampleValue); - } - - private final Coder> iterableCoder; - - private SetCoder(Coder elementCoder) { - iterableCoder = IterableCoder.of(elementCoder); - } - - @Override - public void encode(Set value, OutputStream outStream, Context context) - throws CoderException, IOException { - iterableCoder.encode(value, outStream, context); - } - - @Override - public Set decode(InputStream inStream, Context context) - throws CoderException, IOException { - // TODO: Eliminate extra copy if used in production. - return Sets.newHashSet(iterableCoder.decode(inStream, context)); - } - - @Override - public List> getCoderArguments() { - return iterableCoder.getCoderArguments(); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "CombineTest.SetCoder does not encode in a deterministic order."); - } - - @Override - public boolean isRegisterByteSizeObserverCheap(Set value, Context context) { - return iterableCoder.isRegisterByteSizeObserverCheap(value, context); - } - - @Override - public void registerByteSizeObserver( - Set value, ElementByteSizeObserver observer, Context context) - throws Exception { - iterableCoder.registerByteSizeObserver(value, observer, context); - } - } - - /** Example AccumulatingCombineFn. */ - private static class MeanInts extends - Combine.AccumulatingCombineFn { - private static final Coder LONG_CODER = BigEndianLongCoder.of(); - private static final Coder DOUBLE_CODER = DoubleCoder.of(); - - class CountSum implements - Combine.AccumulatingCombineFn.Accumulator { - long count = 0; - double sum = 0.0; - - CountSum(long count, double sum) { - this.count = count; - this.sum = sum; - } - - @Override - public void addInput(Integer element) { - count++; - sum += element.doubleValue(); - } - - @Override - public void mergeAccumulator(CountSum accumulator) { - count += accumulator.count; - sum += accumulator.sum; - } - - @Override - public Double extractOutput() { - return count == 0 ? 0.0 : sum / count; - } - - @Override - public int hashCode() { - return Objects.hash(count, sum); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof CountSum)) { - return false; - } - CountSum other = (CountSum) obj; - return this.count == other.count - && (Math.abs(this.sum - other.sum) < 0.1); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("count", count) - .add("sum", sum) - .toString(); - } - } - - @Override - public CountSum createAccumulator() { - return new CountSum(0, 0.0); - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder inputCoder) { - return new CountSumCoder(); - } - - /** - * A {@link Coder} for {@link CountSum}. - */ - private class CountSumCoder extends CustomCoder { - @Override - public void encode(CountSum value, OutputStream outStream, - Context context) throws CoderException, IOException { - LONG_CODER.encode(value.count, outStream, context); - DOUBLE_CODER.encode(value.sum, outStream, context); - } - - @Override - public CountSum decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - long count = LONG_CODER.decode(inStream, context); - double sum = DOUBLE_CODER.decode(inStream, context); - return new CountSum(count, sum); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { } - - @Override - public boolean isRegisterByteSizeObserverCheap( - CountSum value, Context context) { - return true; - } - - @Override - public void registerByteSizeObserver( - CountSum value, ElementByteSizeObserver observer, Context context) - throws Exception { - LONG_CODER.registerByteSizeObserver(value.count, observer, context); - DOUBLE_CODER.registerByteSizeObserver(value.sum, observer, context); - } - } - } - - /** - * A KeyedCombineFn that exercises the full generality of [Keyed]CombineFn. - * - *

              The net result of applying this CombineFn is a sorted list of all - * characters occurring in the key and the decimal representations of - * each value. - */ - public static class TestKeyedCombineFn - extends KeyedCombineFn { - - // Not serializable. - static class Accumulator { - String value; - public Accumulator(String value) { - this.value = value; - } - - public static Coder getCoder() { - return new CustomCoder() { - @Override - public void encode(Accumulator accumulator, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - StringUtf8Coder.of().encode(accumulator.value, outStream, context); - } - - @Override - public Accumulator decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - return new Accumulator(StringUtf8Coder.of().decode(inStream, context)); - } - - @Override - public String getEncodingId() { - return "CombineTest.TestKeyedCombineFn.getAccumulatorCoder()"; - } - }; - } - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder keyCoder, Coder inputCoder) { - return Accumulator.getCoder(); - } - - @Override - public Accumulator createAccumulator(String key) { - return new Accumulator(key); - } - - @Override - public Accumulator addInput(String key, Accumulator accumulator, Integer value) { - checkNotNull(key); - try { - assertThat(accumulator.value, Matchers.startsWith(key)); - return new Accumulator(accumulator.value + String.valueOf(value)); - } finally { - accumulator.value = "cleared in addInput"; - } - } - - @Override - public Accumulator mergeAccumulators(String key, Iterable accumulators) { - String all = key; - for (Accumulator accumulator : accumulators) { - assertThat(accumulator.value, Matchers.startsWith(key)); - all += accumulator.value.substring(key.length()); - accumulator.value = "cleared in mergeAccumulators"; - } - return new Accumulator(all); - } - - @Override - public String extractOutput(String key, Accumulator accumulator) { - assertThat(accumulator.value, Matchers.startsWith(key)); - char[] chars = accumulator.value.toCharArray(); - Arrays.sort(chars); - return new String(chars); - } - } - - /** - * A {@link KeyedCombineFnWithContext} that exercises the full generality - * of [Keyed]CombineFnWithContext. - * - *

              The net result of applying this CombineFn is a sorted list of all - * characters occurring in the key and the decimal representations of - * main and side inputs values. - */ - public class TestKeyedCombineFnWithContext - extends KeyedCombineFnWithContext { - private final PCollectionView view; - - public TestKeyedCombineFnWithContext(PCollectionView view) { - this.view = view; - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder keyCoder, Coder inputCoder) { - return TestKeyedCombineFn.Accumulator.getCoder(); - } - - @Override - public TestKeyedCombineFn.Accumulator createAccumulator(String key, Context c) { - return new TestKeyedCombineFn.Accumulator(key + c.sideInput(view).toString()); - } - - @Override - public TestKeyedCombineFn.Accumulator addInput( - String key, TestKeyedCombineFn.Accumulator accumulator, Integer value, Context c) { - try { - assertThat(accumulator.value, Matchers.startsWith(key + c.sideInput(view).toString())); - return new TestKeyedCombineFn.Accumulator(accumulator.value + String.valueOf(value)); - } finally { - accumulator.value = "cleared in addInput"; - } - - } - - @Override - public TestKeyedCombineFn.Accumulator mergeAccumulators( - String key, Iterable accumulators, Context c) { - String keyPrefix = key + c.sideInput(view).toString(); - String all = keyPrefix; - for (TestKeyedCombineFn.Accumulator accumulator : accumulators) { - assertThat(accumulator.value, Matchers.startsWith(keyPrefix)); - all += accumulator.value.substring(keyPrefix.length()); - accumulator.value = "cleared in mergeAccumulators"; - } - return new TestKeyedCombineFn.Accumulator(all); - } - - @Override - public String extractOutput(String key, TestKeyedCombineFn.Accumulator accumulator, Context c) { - assertThat(accumulator.value, Matchers.startsWith(key + c.sideInput(view).toString())); - char[] chars = accumulator.value.toCharArray(); - Arrays.sort(chars); - return new String(chars); - } - } - - /** Another example AccumulatingCombineFn. */ - public static class TestCounter extends - Combine.AccumulatingCombineFn< - Integer, TestCounter.Counter, Iterable> { - - /** An accumulator that observes its merges and outputs. */ - public class Counter implements - Combine.AccumulatingCombineFn.Accumulator>, - Serializable { - - public long sum = 0; - public long inputs = 0; - public long merges = 0; - public long outputs = 0; - - public Counter(long sum, long inputs, long merges, long outputs) { - this.sum = sum; - this.inputs = inputs; - this.merges = merges; - this.outputs = outputs; - } - - @Override - public void addInput(Integer element) { - checkState(merges == 0); - checkState(outputs == 0); - - inputs++; - sum += element; - } - - @Override - public void mergeAccumulator(Counter accumulator) { - checkState(outputs == 0); - checkArgument(accumulator.outputs == 0); - - merges += accumulator.merges + 1; - inputs += accumulator.inputs; - sum += accumulator.sum; - } - - @Override - public Iterable extractOutput() { - checkState(outputs == 0); - - return Arrays.asList(sum, inputs, merges, outputs); - } - - @Override - public int hashCode() { - return (int) (sum * 17 + inputs * 31 + merges * 43 + outputs * 181); - } - - @Override - public boolean equals(Object otherObj) { - if (otherObj instanceof Counter) { - Counter other = (Counter) otherObj; - return (sum == other.sum - && inputs == other.inputs - && merges == other.merges - && outputs == other.outputs); - } - return false; - } - - @Override - public String toString() { - return sum + ":" + inputs + ":" + merges + ":" + outputs; - } - } - - @Override - public Counter createAccumulator() { - return new Counter(0, 0, 0, 0); - } - - @Override - public Coder getAccumulatorCoder( - CoderRegistry registry, Coder inputCoder) { - // This is a *very* inefficient encoding to send over the wire, but suffices - // for tests. - return SerializableCoder.of(Counter.class); - } - } - - private static PCollection copy(PCollection pc, final int n) { - return pc.apply(ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - for (int i = 0; i < n; i++) { - c.output(c.element()); - } - } - })); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CountTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CountTest.java deleted file mode 100644 index 0fe5547872..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CountTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for Count. - */ -@RunWith(JUnit4.class) -public class CountTest { - static final String[] WORDS_ARRAY = new String[] { - "hi", "there", "hi", "hi", "sue", "bob", - "hi", "sue", "", "", "ZOW", "bob", "" }; - - static final List WORDS = Arrays.asList(WORDS_ARRAY); - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings("unchecked") - public void testCountPerElementBasic() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(WORDS)); - - PCollection> output = - input.apply(Count.perElement()); - - DataflowAssert.that(output) - .containsInAnyOrder( - KV.of("hi", 4L), - KV.of("there", 1L), - KV.of("sue", 2L), - KV.of("bob", 2L), - KV.of("", 3L), - KV.of("ZOW", 1L)); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - @SuppressWarnings("unchecked") - public void testCountPerElementEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(NO_LINES).withCoder(StringUtf8Coder.of())); - - PCollection> output = - input.apply(Count.perElement()); - - DataflowAssert.that(output).empty(); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testCountGloballyBasic() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(WORDS)); - - PCollection output = - input.apply(Count.globally()); - - DataflowAssert.that(output) - .containsInAnyOrder(13L); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testCountGloballyEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(NO_LINES).withCoder(StringUtf8Coder.of())); - - PCollection output = - input.apply(Count.globally()); - - DataflowAssert.that(output) - .containsInAnyOrder(0L); - p.run(); - } - - @Test - public void testCountGetName() { - assertEquals("Count.PerElement", Count.perElement().getName()); - assertEquals("Count.Globally", Count.globally().getName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CreateTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CreateTest.java deleted file mode 100644 index 1af072112a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/CreateTest.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.LINES; -import static com.google.cloud.dataflow.sdk.TestUtils.LINES_ARRAY; -import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES; -import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES_ARRAY; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests for Create. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("unchecked") -public class CreateTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - - @Test - @Category(RunnableOnService.class) - public void testCreate() { - Pipeline p = TestPipeline.create(); - - PCollection output = - p.apply(Create.of(LINES)); - - DataflowAssert.that(output) - .containsInAnyOrder(LINES_ARRAY); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testCreateEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection output = - p.apply(Create.of(NO_LINES) - .withCoder(StringUtf8Coder.of())); - - DataflowAssert.that(output) - .containsInAnyOrder(NO_LINES_ARRAY); - p.run(); - } - - @Test - public void testCreateEmptyInfersCoder() { - Pipeline p = TestPipeline.create(); - - PCollection output = - p.apply(Create.of()); - - assertEquals(VoidCoder.of(), output.getCoder()); - } - - static class Record implements Serializable { - } - - static class Record2 extends Record { - } - - @Test - public void testPolymorphicType() throws Exception { - thrown.expect(RuntimeException.class); - thrown.expectMessage( - Matchers.containsString("Unable to infer a coder")); - - Pipeline p = TestPipeline.create(); - - // Create won't infer a default coder in this case. - p.apply(Create.of(new Record(), new Record2())); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testCreateWithNullsAndValues() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection output = - p.apply(Create.of(null, "test1", null, "test2", null) - .withCoder(SerializableCoder.of(String.class))); - DataflowAssert.that(output) - .containsInAnyOrder(null, "test1", null, "test2", null); - p.run(); - } - - @Test - public void testCreateParameterizedType() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection> output = - p.apply(Create.of( - TimestampedValue.of("a", new Instant(0)), - TimestampedValue.of("b", new Instant(0)))); - - DataflowAssert.that(output) - .containsInAnyOrder( - TimestampedValue.of("a", new Instant(0)), - TimestampedValue.of("b", new Instant(0))); - } - private static class PrintTimestamps extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + ":" + c.timestamp().getMillis()); - } - } - - @Test - @Category(RunnableOnService.class) - public void testCreateTimestamped() { - Pipeline p = TestPipeline.create(); - - List> data = Arrays.asList( - TimestampedValue.of("a", new Instant(1L)), - TimestampedValue.of("b", new Instant(2L)), - TimestampedValue.of("c", new Instant(3L))); - - PCollection output = - p.apply(Create.timestamped(data)) - .apply(ParDo.of(new PrintTimestamps())); - - DataflowAssert.that(output) - .containsInAnyOrder("a:1", "b:2", "c:3"); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testCreateTimestampedEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.timestamped(new ArrayList>()) - .withCoder(StringUtf8Coder.of())); - - DataflowAssert.that(output).empty(); - p.run(); - } - - @Test - public void testCreateTimestampedEmptyInfersCoder() { - Pipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.timestamped()); - - assertEquals(VoidCoder.of(), output.getCoder()); - } - - @Test - public void testCreateTimestampedPolymorphicType() throws Exception { - thrown.expect(RuntimeException.class); - thrown.expectMessage( - Matchers.containsString("Unable to infer a coder")); - - Pipeline p = TestPipeline.create(); - - // Create won't infer a default coder in this case. - PCollection c = p.apply(Create.timestamped( - TimestampedValue.of(new Record(), new Instant(0)), - TimestampedValue.of(new Record2(), new Instant(0)))); - - p.run(); - - throw new RuntimeException("Coder: " + c.getCoder()); - } - - @Test - @Category(RunnableOnService.class) - public void testCreateWithVoidType() throws Exception { - Pipeline p = TestPipeline.create(); - PCollection output = p.apply(Create.of((Void) null, (Void) null)); - DataflowAssert.that(output).containsInAnyOrder((Void) null, (Void) null); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testCreateWithKVVoidType() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection> output = p.apply(Create.of( - KV.of((Void) null, (Void) null), - KV.of((Void) null, (Void) null))); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of((Void) null, (Void) null), - KV.of((Void) null, (Void) null)); - - p.run(); - } - - @Test - public void testCreateGetName() { - assertEquals("Create.Values", Create.of(1, 2, 3).getName()); - assertEquals("Create.TimestampedValues", Create.timestamped(Collections.EMPTY_LIST).getName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnContextTest.java deleted file mode 100644 index c4716f9a39..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnContextTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link DoFn.Context}. - */ -@RunWith(JUnit4.class) -public class DoFnContextTest { - - @Mock - private Aggregator agg; - - private DoFn fn; - private DoFn.Context context; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - // Need to be real objects to call the constructor, and to reference the - // outer instance of DoFn - NoOpDoFn noOpFn = new NoOpDoFn<>(); - DoFn.Context noOpContext = noOpFn.context(); - - fn = spy(noOpFn); - context = spy(noOpContext); - } - - @Test - public void testSetupDelegateAggregatorsCreatesAndLinksDelegateAggregators() { - Sum.SumLongFn combiner = new Sum.SumLongFn(); - Aggregator delegateAggregator = - fn.createAggregator("test", combiner); - - when(context.createAggregatorInternal("test", combiner)).thenReturn(agg); - - context.setupDelegateAggregators(); - delegateAggregator.addValue(1L); - - verify(agg).addValue(1L); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnDelegatingAggregatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnDelegatingAggregatorTest.java deleted file mode 100644 index 0b82c51f7c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnDelegatingAggregatorTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.DelegatingAggregator; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Tests for DoFn.DelegatingAggregator. - */ -@RunWith(JUnit4.class) -public class DoFnDelegatingAggregatorTest { - - @Mock - private Aggregator delegate; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testAddValueWithoutDelegateThrowsException() { - DoFn doFn = new NoOpDoFn<>(); - - String name = "agg"; - CombineFn combiner = mockCombineFn(Double.class); - - DelegatingAggregator aggregator = - (DelegatingAggregator) doFn.createAggregator(name, combiner); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("cannot be called"); - thrown.expectMessage("DoFn"); - - aggregator.addValue(21.2); - } - - @Test - public void testSetDelegateThenAddValueCallsDelegate() { - String name = "agg"; - CombineFn combiner = mockCombineFn(Long.class); - - DoFn doFn = new NoOpDoFn<>(); - - DelegatingAggregator aggregator = - (DelegatingAggregator) doFn.createAggregator(name, combiner); - - aggregator.setDelegate(delegate); - - aggregator.addValue(12L); - - verify(delegate).addValue(12L); - } - - @Test - public void testSetDelegateWithExistingDelegateStartsDelegatingToSecond() { - String name = "agg"; - CombineFn combiner = mockCombineFn(Double.class); - - DoFn doFn = new NoOpDoFn<>(); - - DelegatingAggregator aggregator = - (DelegatingAggregator) doFn.createAggregator(name, combiner); - - @SuppressWarnings("unchecked") - Aggregator secondDelegate = - mock(Aggregator.class, "secondDelegate"); - - aggregator.setDelegate(aggregator); - aggregator.setDelegate(secondDelegate); - - aggregator.addValue(2.25); - - verify(secondDelegate).addValue(2.25); - verify(delegate, never()).addValue(anyLong()); - } - - @Test - public void testGetNameReturnsName() { - String name = "agg"; - CombineFn combiner = mockCombineFn(Double.class); - - DoFn doFn = new NoOpDoFn<>(); - - DelegatingAggregator aggregator = - (DelegatingAggregator) doFn.createAggregator(name, combiner); - - assertEquals(name, aggregator.getName()); - } - - @Test - public void testGetCombineFnReturnsCombineFn() { - String name = "agg"; - CombineFn combiner = mockCombineFn(Double.class); - - DoFn doFn = new NoOpDoFn<>(); - - DelegatingAggregator aggregator = - (DelegatingAggregator) doFn.createAggregator(name, combiner); - - assertEquals(combiner, aggregator.getCombineFn()); - } - - @SuppressWarnings("unchecked") - private static CombineFn mockCombineFn( - @SuppressWarnings("unused") Class clazz) { - return mock(CombineFn.class); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflectorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflectorTest.java deleted file mode 100644 index 2a770c25aa..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnReflectorTest.java +++ /dev/null @@ -1,493 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.Context; -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.ExtraContextFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.ProcessContext; -import com.google.cloud.dataflow.sdk.transforms.DoFnWithContext.ProcessElement; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.WindowingInternals; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.lang.reflect.Method; - -/** - * Tests for {@link DoFnReflector}. - */ -@RunWith(JUnit4.class) -public class DoFnReflectorTest { - - private boolean wasProcessElementInvoked = false; - private boolean wasStartBundleInvoked = false; - private boolean wasFinishBundleInvoked = false; - - private DoFnWithContext fn; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Mock - private DoFnWithContext.ProcessContext mockContext; - @Mock - private BoundedWindow mockWindow; - @Mock - private WindowingInternals mockWindowingInternals; - - private ExtraContextFactory extraContextFactory; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.extraContextFactory = new ExtraContextFactory() { - @Override - public BoundedWindow window() { - return mockWindow; - } - - @Override - public WindowingInternals windowingInternals() { - return mockWindowingInternals; - } - }; - } - - private DoFnReflector underTest(DoFnWithContext fn) { - this.fn = fn; - return DoFnReflector.of(fn.getClass()); - } - - private void checkInvokeProcessElementWorks(DoFnReflector r) throws Exception { - assertFalse(wasProcessElementInvoked); - r.invokeProcessElement(fn, mockContext, extraContextFactory); - assertTrue(wasProcessElementInvoked); - } - - private void checkInvokeStartBundleWorks(DoFnReflector r) throws Exception { - assertFalse(wasStartBundleInvoked); - r.invokeStartBundle(fn, mockContext, extraContextFactory); - assertTrue(wasStartBundleInvoked); - } - - private void checkInvokeFinishBundleWorks(DoFnReflector r) throws Exception { - assertFalse(wasFinishBundleInvoked); - r.invokeFinishBundle(fn, mockContext, extraContextFactory); - assertTrue(wasFinishBundleInvoked); - } - - @Test - public void testDoFnWithNoExtraContext() throws Exception { - DoFnReflector reflector = underTest(new DoFnWithContext() { - - @ProcessElement - public void processElement(ProcessContext c) - throws Exception { - wasProcessElementInvoked = true; - assertSame(c, mockContext); - } - }); - - assertFalse(reflector.usesSingleWindow()); - - checkInvokeProcessElementWorks(reflector); - } - - interface InterfaceWithProcessElement { - @ProcessElement - void processElement(DoFnWithContext.ProcessContext c); - } - - interface LayersOfInterfaces extends InterfaceWithProcessElement {} - - private class IdentityUsingInterfaceWithProcessElement - extends DoFnWithContext - implements LayersOfInterfaces { - - @Override - public void processElement(DoFnWithContext.ProcessContext c) { - wasProcessElementInvoked = true; - assertSame(c, mockContext); - } - } - - @Test - public void testDoFnWithProcessElementInterface() throws Exception { - DoFnReflector reflector = underTest(new IdentityUsingInterfaceWithProcessElement()); - assertFalse(reflector.usesSingleWindow()); - checkInvokeProcessElementWorks(reflector); - } - - private class IdentityParent extends DoFnWithContext { - @ProcessElement - public void process(ProcessContext c) { - wasProcessElementInvoked = true; - assertSame(c, mockContext); - } - } - - private class IdentityChild extends IdentityParent {} - - @Test - public void testDoFnWithMethodInSuperclass() throws Exception { - DoFnReflector reflector = underTest(new IdentityChild()); - assertFalse(reflector.usesSingleWindow()); - checkInvokeProcessElementWorks(reflector); - } - - @Test - public void testDoFnWithWindow() throws Exception { - DoFnReflector reflector = underTest(new DoFnWithContext() { - - @ProcessElement - public void processElement(ProcessContext c, BoundedWindow w) - throws Exception { - wasProcessElementInvoked = true; - assertSame(c, mockContext); - assertSame(w, mockWindow); - } - }); - - assertTrue(reflector.usesSingleWindow()); - - checkInvokeProcessElementWorks(reflector); - } - - @Test - public void testDoFnWithWindowingInternals() throws Exception { - DoFnReflector reflector = underTest(new DoFnWithContext() { - - @ProcessElement - public void processElement(ProcessContext c, WindowingInternals w) - throws Exception { - wasProcessElementInvoked = true; - assertSame(c, mockContext); - assertSame(w, mockWindowingInternals); - } - }); - - assertFalse(reflector.usesSingleWindow()); - - checkInvokeProcessElementWorks(reflector); - } - - @Test - public void testDoFnWithStartBundle() throws Exception { - DoFnReflector reflector = underTest(new DoFnWithContext() { - @ProcessElement - public void processElement(@SuppressWarnings("unused") ProcessContext c) {} - - @StartBundle - public void startBundle(Context c) { - wasStartBundleInvoked = true; - assertSame(c, mockContext); - } - - @FinishBundle - public void finishBundle(Context c) { - wasFinishBundleInvoked = true; - assertSame(c, mockContext); - } - }); - - checkInvokeStartBundleWorks(reflector); - checkInvokeFinishBundleWorks(reflector); - } - - @Test - public void testNoProcessElement() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("No method annotated with @ProcessElement found"); - thrown.expectMessage(getClass().getName() + "$"); - underTest(new DoFnWithContext() {}); - } - - @Test - public void testMultipleProcessElement() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Found multiple methods annotated with @ProcessElement"); - thrown.expectMessage("foo()"); - thrown.expectMessage("bar()"); - thrown.expectMessage(getClass().getName() + "$"); - underTest(new DoFnWithContext() { - @ProcessElement - public void foo() {} - - @ProcessElement - public void bar() {} - }); - } - - @Test - public void testMultipleStartBundleElement() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Found multiple methods annotated with @StartBundle"); - thrown.expectMessage("bar()"); - thrown.expectMessage("baz()"); - thrown.expectMessage(getClass().getName() + "$"); - underTest(new DoFnWithContext() { - @ProcessElement - public void foo() {} - - @StartBundle - public void bar() {} - - @StartBundle - public void baz() {} - }); - } - - @Test - public void testMultipleFinishBundleElement() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Found multiple methods annotated with @FinishBundle"); - thrown.expectMessage("bar()"); - thrown.expectMessage("baz()"); - thrown.expectMessage(getClass().getName() + "$"); - underTest(new DoFnWithContext() { - @ProcessElement - public void foo() {} - - @FinishBundle - public void bar() {} - - @FinishBundle - public void baz() {} - }); - } - - @Test - public void testPrivateProcessElement() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("process() must be public"); - thrown.expectMessage(getClass().getName() + "$"); - underTest(new DoFnWithContext() { - @ProcessElement - private void process() {} - }); - } - - @Test - public void testPrivateStartBundle() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("startBundle() must be public"); - thrown.expectMessage(getClass().getName() + "$"); - underTest(new DoFnWithContext() { - @ProcessElement - public void processElement() {} - - @StartBundle - void startBundle() {} - }); - } - - @Test - public void testPrivateFinishBundle() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("finishBundle() must be public"); - thrown.expectMessage(getClass().getName() + "$"); - underTest(new DoFnWithContext() { - @ProcessElement - public void processElement() {} - - @FinishBundle - void finishBundle() {} - }); - } - - @SuppressWarnings({"unused", "rawtypes"}) - private void missingProcessContext() {} - - @Test - public void testMissingProcessContext() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage(getClass().getName() - + "#missingProcessContext() must take a ProcessContext as its first argument"); - - DoFnReflector.verifyProcessMethodArguments( - getClass().getDeclaredMethod("missingProcessContext")); - } - - @SuppressWarnings({"unused", "rawtypes"}) - private void badProcessContext(String s) {} - - @Test - public void testBadProcessContextType() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage(getClass().getName() - + "#badProcessContext(String) must take a ProcessContext as its first argument"); - - DoFnReflector.verifyProcessMethodArguments( - getClass().getDeclaredMethod("badProcessContext", String.class)); - } - - @SuppressWarnings({"unused", "rawtypes"}) - private void badExtraContext(DoFnWithContext.Context c, int n) {} - - @Test - public void testBadExtraContext() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "int is not a valid context parameter for method " - + getClass().getName() + "#badExtraContext(Context, int). Should be one of ["); - - DoFnReflector.verifyBundleMethodArguments( - getClass().getDeclaredMethod("badExtraContext", Context.class, int.class)); - } - - @SuppressWarnings({"unused", "rawtypes"}) - private void badExtraProcessContext( - DoFnWithContext.ProcessContext c, Integer n) {} - - @Test - public void testBadExtraProcessContextType() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Integer is not a valid context parameter for method " - + getClass().getName() + "#badExtraProcessContext(ProcessContext, Integer)" - + ". Should be one of [BoundedWindow, WindowingInternals]"); - - DoFnReflector.verifyProcessMethodArguments( - getClass().getDeclaredMethod("badExtraProcessContext", - ProcessContext.class, Integer.class)); - } - - @SuppressWarnings("unused") - private int badReturnType() { - return 0; - } - - @Test - public void testBadReturnType() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage(getClass().getName() + "#badReturnType() must have a void return type"); - - DoFnReflector.verifyProcessMethodArguments(getClass().getDeclaredMethod("badReturnType")); - } - - @SuppressWarnings("unused") - private void goodGenerics(DoFnWithContext.ProcessContext c, - WindowingInternals i1) {} - - @Test - public void testValidGenerics() throws Exception { - Method method = getClass().getDeclaredMethod("goodGenerics", - DoFnWithContext.ProcessContext.class, WindowingInternals.class); - DoFnReflector.verifyProcessMethodArguments(method); - } - - @SuppressWarnings("unused") - private void goodWildcards(DoFnWithContext.ProcessContext c, - WindowingInternals i1) {} - - @Test - public void testGoodWildcards() throws Exception { - Method method = getClass().getDeclaredMethod("goodWildcards", - DoFnWithContext.ProcessContext.class, WindowingInternals.class); - DoFnReflector.verifyProcessMethodArguments(method); - } - - @SuppressWarnings("unused") - private void goodBoundedWildcards(DoFnWithContext.ProcessContext c, - WindowingInternals i1) {} - - @Test - public void testGoodBoundedWildcards() throws Exception { - Method method = getClass().getDeclaredMethod("goodBoundedWildcards", - DoFnWithContext.ProcessContext.class, WindowingInternals.class); - DoFnReflector.verifyProcessMethodArguments(method); - } - - @SuppressWarnings("unused") - private void goodTypeVariables( - DoFnWithContext.ProcessContext c, - WindowingInternals i1) {} - - @Test - public void testGoodTypeVariables() throws Exception { - Method method = getClass().getDeclaredMethod("goodTypeVariables", - DoFnWithContext.ProcessContext.class, WindowingInternals.class); - DoFnReflector.verifyProcessMethodArguments(method); - } - - @SuppressWarnings("unused") - private void badGenericTwoArgs(DoFnWithContext.ProcessContext c, - WindowingInternals i1) {} - - @Test - public void testBadGenericsTwoArgs() throws Exception { - Method method = getClass().getDeclaredMethod("badGenericTwoArgs", - DoFnWithContext.ProcessContext.class, WindowingInternals.class); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Incompatible generics in context parameter " - + "WindowingInternals " - + "for method " + getClass().getName() - + "#badGenericTwoArgs(ProcessContext, WindowingInternals). Should be " - + "WindowingInternals"); - - DoFnReflector.verifyProcessMethodArguments(method); - } - - @SuppressWarnings("unused") - private void badGenericWildCards(DoFnWithContext.ProcessContext c, - WindowingInternals i1) {} - - @Test - public void testBadGenericWildCards() throws Exception { - Method method = getClass().getDeclaredMethod("badGenericWildCards", - DoFnWithContext.ProcessContext.class, WindowingInternals.class); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Incompatible generics in context parameter " - + "WindowingInternals for method " - + getClass().getName() - + "#badGenericWildCards(ProcessContext, WindowingInternals). Should be " - + "WindowingInternals"); - - DoFnReflector.verifyProcessMethodArguments(method); - } - - @SuppressWarnings("unused") - private void badTypeVariables(DoFnWithContext.ProcessContext c, - WindowingInternals i1) {} - - @Test - public void testBadTypeVariables() throws Exception { - Method method = getClass().getDeclaredMethod("badTypeVariables", - DoFnWithContext.ProcessContext.class, WindowingInternals.class); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Incompatible generics in context parameter " - + "WindowingInternals for method " + getClass().getName() - + "#badTypeVariables(ProcessContext, WindowingInternals). Should be " - + "WindowingInternals"); - - DoFnReflector.verifyProcessMethodArguments(method); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java deleted file mode 100644 index 5bc17f17e4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTest.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.CoreMatchers.isA; -import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Tests for DoFn. - */ -@RunWith(JUnit4.class) -public class DoFnTest implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testCreateAggregatorWithCombinerSucceeds() { - String name = "testAggregator"; - Sum.SumLongFn combiner = new Sum.SumLongFn(); - - DoFn doFn = new NoOpDoFn<>(); - - Aggregator aggregator = doFn.createAggregator(name, combiner); - - assertEquals(name, aggregator.getName()); - assertEquals(combiner, aggregator.getCombineFn()); - } - - @Test - public void testCreateAggregatorWithNullNameThrowsException() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("name cannot be null"); - - DoFn doFn = new NoOpDoFn<>(); - - doFn.createAggregator(null, new Sum.SumLongFn()); - } - - @Test - public void testCreateAggregatorWithNullCombineFnThrowsException() { - CombineFn combiner = null; - - thrown.expect(NullPointerException.class); - thrown.expectMessage("combiner cannot be null"); - - DoFn doFn = new NoOpDoFn<>(); - - doFn.createAggregator("testAggregator", combiner); - } - - @Test - public void testCreateAggregatorWithNullSerializableFnThrowsException() { - SerializableFunction, Object> combiner = null; - - thrown.expect(NullPointerException.class); - thrown.expectMessage("combiner cannot be null"); - - DoFn doFn = new NoOpDoFn<>(); - - doFn.createAggregator("testAggregator", combiner); - } - - @Test - public void testCreateAggregatorWithSameNameThrowsException() { - String name = "testAggregator"; - CombineFn combiner = new Max.MaxDoubleFn(); - - DoFn doFn = new NoOpDoFn<>(); - - doFn.createAggregator(name, combiner); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Cannot create"); - thrown.expectMessage(name); - thrown.expectMessage("already exists"); - - doFn.createAggregator(name, combiner); - } - - @Test - public void testCreateAggregatorsWithDifferentNamesSucceeds() { - String nameOne = "testAggregator"; - String nameTwo = "aggregatorPrime"; - CombineFn combiner = new Max.MaxDoubleFn(); - - DoFn doFn = new NoOpDoFn<>(); - - Aggregator aggregatorOne = - doFn.createAggregator(nameOne, combiner); - Aggregator aggregatorTwo = - doFn.createAggregator(nameTwo, combiner); - - assertNotEquals(aggregatorOne, aggregatorTwo); - } - - @Test - public void testCreateAggregatorInStartBundleThrows() { - TestPipeline p = createTestPipeline(new DoFn() { - @Override - public void startBundle(DoFn.Context c) throws Exception { - createAggregator("anyAggregate", new MaxIntegerFn()); - } - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception {} - }); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalStateException.class)); - - p.run(); - } - - @Test - public void testCreateAggregatorInProcessElementThrows() { - TestPipeline p = createTestPipeline(new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - createAggregator("anyAggregate", new MaxIntegerFn()); - } - }); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalStateException.class)); - - p.run(); - } - - @Test - public void testCreateAggregatorInFinishBundleThrows() { - TestPipeline p = createTestPipeline(new DoFn() { - @Override - public void finishBundle(DoFn.Context c) throws Exception { - createAggregator("anyAggregate", new MaxIntegerFn()); - } - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception {} - }); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalStateException.class)); - - p.run(); - } - - /** - * Initialize a test pipeline with the specified {@link DoFn}. - */ - private TestPipeline createTestPipeline(DoFn fn) { - TestPipeline pipeline = TestPipeline.create(); - pipeline.apply(Create.of((InputT) null)) - .apply(ParDo.of(fn)); - - return pipeline; - } - - @Test - public void testPopulateDisplayDataDefaultBehavior() { - DoFn usesDefault = - new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception {} - }; - - DisplayData data = DisplayData.from(usesDefault); - assertThat(data.items(), empty()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTesterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTesterTest.java deleted file mode 100644 index 8958810491..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTesterTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.DoFnTester.OutputElementWithTimestamp; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** - * Tests for {@link DoFnTester}. - */ -@RunWith(JUnit4.class) -public class DoFnTesterTest { - - @Test - public void processElement() { - CounterDoFn counterDoFn = new CounterDoFn(); - DoFnTester tester = DoFnTester.of(counterDoFn); - - tester.processElement(1L); - - List take = tester.takeOutputElements(); - - assertThat(take, hasItems("1")); - - // Following takeOutputElements(), neither takeOutputElements() - // nor peekOutputElements() return anything. - assertTrue(tester.takeOutputElements().isEmpty()); - assertTrue(tester.peekOutputElements().isEmpty()); - - // processElement() caused startBundle() to be called, but finishBundle() was never called. - CounterDoFn deserializedDoFn = (CounterDoFn) tester.fn; - assertTrue(deserializedDoFn.wasStartBundleCalled()); - assertFalse(deserializedDoFn.wasFinishBundleCalled()); - } - - @Test - public void processElementsWithPeeks() { - CounterDoFn counterDoFn = new CounterDoFn(); - DoFnTester tester = DoFnTester.of(counterDoFn); - - // Explicitly call startBundle(). - tester.startBundle(); - - // verify startBundle() was called but not finishBundle(). - CounterDoFn deserializedDoFn = (CounterDoFn) tester.fn; - assertTrue(deserializedDoFn.wasStartBundleCalled()); - assertFalse(deserializedDoFn.wasFinishBundleCalled()); - - // process a couple of elements. - tester.processElement(1L); - tester.processElement(2L); - - // peek the first 2 outputs. - List peek = tester.peekOutputElements(); - assertThat(peek, hasItems("1", "2")); - - // process a couple more. - tester.processElement(3L); - tester.processElement(4L); - - // peek all the outputs so far. - peek = tester.peekOutputElements(); - assertThat(peek, hasItems("1", "2", "3", "4")); - // take the outputs. - List take = tester.takeOutputElements(); - assertThat(take, hasItems("1", "2", "3", "4")); - - // Following takeOutputElements(), neither takeOutputElements() - // nor peekOutputElements() return anything. - assertTrue(tester.peekOutputElements().isEmpty()); - assertTrue(tester.takeOutputElements().isEmpty()); - - // verify finishBundle() hasn't been called yet. - assertTrue(deserializedDoFn.wasStartBundleCalled()); - assertFalse(deserializedDoFn.wasFinishBundleCalled()); - - // process a couple more. - tester.processElement(5L); - tester.processElement(6L); - - // peek and take now have only the 2 last outputs. - peek = tester.peekOutputElements(); - assertThat(peek, hasItems("5", "6")); - take = tester.takeOutputElements(); - assertThat(take, hasItems("5", "6")); - - tester.finishBundle(); - - // verify finishBundle() was called. - assertTrue(deserializedDoFn.wasStartBundleCalled()); - assertTrue(deserializedDoFn.wasFinishBundleCalled()); - } - - @Test - public void processBatch() { - CounterDoFn counterDoFn = new CounterDoFn(); - DoFnTester tester = DoFnTester.of(counterDoFn); - - // processBatch() returns all the output like takeOutputElements(). - List take = tester.processBatch(1L, 2L, 3L, 4L); - - assertThat(take, hasItems("1", "2", "3", "4")); - - // peek now returns nothing. - assertTrue(tester.peekOutputElements().isEmpty()); - - // verify startBundle() and finishBundle() were both called. - CounterDoFn deserializedDoFn = (CounterDoFn) tester.fn; - assertTrue(deserializedDoFn.wasStartBundleCalled()); - assertTrue(deserializedDoFn.wasFinishBundleCalled()); - } - - @Test - public void processElementWithTimestamp() { - CounterDoFn counterDoFn = new CounterDoFn(); - DoFnTester tester = DoFnTester.of(counterDoFn); - - tester.processElement(1L); - tester.processElement(2L); - - List> peek = tester.peekOutputElementsWithTimestamp(); - OutputElementWithTimestamp one = - new OutputElementWithTimestamp<>("1", new Instant(1000L)); - OutputElementWithTimestamp two = - new OutputElementWithTimestamp<>("2", new Instant(2000L)); - assertThat(peek, hasItems(one, two)); - - tester.processElement(3L); - tester.processElement(4L); - - OutputElementWithTimestamp three = - new OutputElementWithTimestamp<>("3", new Instant(3000L)); - OutputElementWithTimestamp four = - new OutputElementWithTimestamp<>("4", new Instant(4000L)); - peek = tester.peekOutputElementsWithTimestamp(); - assertThat(peek, hasItems(one, two, three, four)); - List> take = tester.takeOutputElementsWithTimestamp(); - assertThat(take, hasItems(one, two, three, four)); - - // Following takeOutputElementsWithTimestamp(), neither takeOutputElementsWithTimestamp() - // nor peekOutputElementsWithTimestamp() return anything. - assertTrue(tester.takeOutputElementsWithTimestamp().isEmpty()); - assertTrue(tester.peekOutputElementsWithTimestamp().isEmpty()); - - // peekOutputElements() and takeOutputElements() also return nothing. - assertTrue(tester.peekOutputElements().isEmpty()); - assertTrue(tester.takeOutputElements().isEmpty()); - } - - @Test - public void getAggregatorValuesShouldGetValueOfCounter() { - CounterDoFn counterDoFn = new CounterDoFn(); - DoFnTester tester = DoFnTester.of(counterDoFn); - tester.processBatch(1L, 2L, 4L, 8L); - - Long aggregatorVal = tester.getAggregatorValue(counterDoFn.agg); - - assertThat(aggregatorVal, equalTo(15L)); - } - - @Test - public void getAggregatorValuesWithEmptyCounterShouldSucceed() { - CounterDoFn counterDoFn = new CounterDoFn(); - DoFnTester tester = DoFnTester.of(counterDoFn); - tester.processBatch(); - Long aggregatorVal = tester.getAggregatorValue(counterDoFn.agg); - // empty bundle - assertThat(aggregatorVal, equalTo(0L)); - } - - @Test - public void getAggregatorValuesInStartFinishBundleShouldGetValues() { - CounterDoFn fn = new CounterDoFn(1L, 2L); - DoFnTester tester = DoFnTester.of(fn); - tester.processBatch(0L, 0L); - - Long aggValue = tester.getAggregatorValue(fn.agg); - assertThat(aggValue, equalTo(1L + 2L)); - } - - /** - * A DoFn that adds values to an aggregator and converts input to String in processElement. - */ - private static class CounterDoFn extends DoFn { - Aggregator agg = createAggregator("ctr", new Sum.SumLongFn()); - private final long startBundleVal; - private final long finishBundleVal; - private boolean startBundleCalled; - private boolean finishBundleCalled; - - public CounterDoFn() { - this(0L, 0L); - } - - public CounterDoFn(long start, long finish) { - this.startBundleVal = start; - this.finishBundleVal = finish; - } - - @Override - public void startBundle(Context c) { - agg.addValue(startBundleVal); - startBundleCalled = true; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - agg.addValue(c.element()); - Instant instant = new Instant(1000L * c.element()); - c.outputWithTimestamp(c.element().toString(), instant); - } - - @Override - public void finishBundle(Context c) { - agg.addValue(finishBundleVal); - finishBundleCalled = true; - } - - boolean wasStartBundleCalled() { - return startBundleCalled; - } - - boolean wasFinishBundleCalled() { - return finishBundleCalled; - } - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java deleted file mode 100644 index f4b38c9d62..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnWithContextTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.CoreMatchers.isA; -import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** Tests for {@link DoFnWithContext}. */ -@RunWith(JUnit4.class) -public class DoFnWithContextTest implements Serializable { - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - private class NoOpDoFnWithContext extends DoFnWithContext { - - /** - * @param c context - */ - @ProcessElement - public void processElement(ProcessContext c) { - } - } - - @Test - public void testCreateAggregatorWithCombinerSucceeds() { - String name = "testAggregator"; - Sum.SumLongFn combiner = new Sum.SumLongFn(); - - DoFnWithContext doFn = new NoOpDoFnWithContext(); - - Aggregator aggregator = doFn.createAggregator(name, combiner); - - assertEquals(name, aggregator.getName()); - assertEquals(combiner, aggregator.getCombineFn()); - } - - @Test - public void testCreateAggregatorWithNullNameThrowsException() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("name cannot be null"); - - DoFnWithContext doFn = new NoOpDoFnWithContext(); - - doFn.createAggregator(null, new Sum.SumLongFn()); - } - - @Test - public void testCreateAggregatorWithNullCombineFnThrowsException() { - CombineFn combiner = null; - - thrown.expect(NullPointerException.class); - thrown.expectMessage("combiner cannot be null"); - - DoFnWithContext doFn = new NoOpDoFnWithContext(); - - doFn.createAggregator("testAggregator", combiner); - } - - @Test - public void testCreateAggregatorWithNullSerializableFnThrowsException() { - SerializableFunction, Object> combiner = null; - - thrown.expect(NullPointerException.class); - thrown.expectMessage("combiner cannot be null"); - - DoFnWithContext doFn = new NoOpDoFnWithContext(); - - doFn.createAggregator("testAggregator", combiner); - } - - @Test - public void testCreateAggregatorWithSameNameThrowsException() { - String name = "testAggregator"; - CombineFn combiner = new Max.MaxDoubleFn(); - - DoFnWithContext doFn = new NoOpDoFnWithContext(); - - doFn.createAggregator(name, combiner); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Cannot create"); - thrown.expectMessage(name); - thrown.expectMessage("already exists"); - - doFn.createAggregator(name, combiner); - } - - @Test - public void testCreateAggregatorsWithDifferentNamesSucceeds() { - String nameOne = "testAggregator"; - String nameTwo = "aggregatorPrime"; - CombineFn combiner = new Max.MaxDoubleFn(); - - DoFnWithContext doFn = new NoOpDoFnWithContext(); - - Aggregator aggregatorOne = - doFn.createAggregator(nameOne, combiner); - Aggregator aggregatorTwo = - doFn.createAggregator(nameTwo, combiner); - - assertNotEquals(aggregatorOne, aggregatorTwo); - } - - @Test - public void testDoFnWithContextUsingAggregators() { - NoOpDoFn noOpFn = new NoOpDoFn<>(); - DoFn.Context context = noOpFn.context(); - - DoFn fn = spy(noOpFn); - context = spy(context); - - @SuppressWarnings("unchecked") - Aggregator agg = mock(Aggregator.class); - - Sum.SumLongFn combiner = new Sum.SumLongFn(); - Aggregator delegateAggregator = - fn.createAggregator("test", combiner); - - when(context.createAggregatorInternal("test", combiner)).thenReturn(agg); - - context.setupDelegateAggregators(); - delegateAggregator.addValue(1L); - - verify(agg).addValue(1L); - } - - @Test - public void testDefaultPopulateDisplayDataImplementation() { - DoFnWithContext fn = new DoFnWithContext() { - }; - DisplayData displayData = DisplayData.from(fn); - assertThat(displayData.items(), empty()); - } - - @Test - public void testCreateAggregatorInStartBundleThrows() { - TestPipeline p = createTestPipeline(new DoFnWithContext() { - @StartBundle - public void startBundle(Context c) { - createAggregator("anyAggregate", new MaxIntegerFn()); - } - - @ProcessElement - public void processElement(ProcessContext c) {} - }); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalStateException.class)); - - p.run(); - } - - @Test - public void testCreateAggregatorInProcessElementThrows() { - TestPipeline p = createTestPipeline(new DoFnWithContext() { - @ProcessElement - public void processElement(ProcessContext c) { - createAggregator("anyAggregate", new MaxIntegerFn()); - } - }); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalStateException.class)); - - p.run(); - } - - @Test - public void testCreateAggregatorInFinishBundleThrows() { - TestPipeline p = createTestPipeline(new DoFnWithContext() { - @FinishBundle - public void finishBundle(Context c) { - createAggregator("anyAggregate", new MaxIntegerFn()); - } - - @ProcessElement - public void processElement(ProcessContext c) {} - }); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalStateException.class)); - - p.run(); - } - - /** - * Initialize a test pipeline with the specified {@link DoFn}. - */ - private TestPipeline createTestPipeline(DoFnWithContext fn) { - TestPipeline pipeline = TestPipeline.create(); - pipeline.apply(Create.of((InputT) null)) - .apply(ParDo.of(fn)); - - return pipeline; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java deleted file mode 100644 index 06f7821de5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FilterTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; - -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Tests for {@link Filter}. - */ -@RunWith(JUnit4.class) -public class FilterTest implements Serializable { - - static class TrivialFn implements SerializableFunction { - private final Boolean returnVal; - - TrivialFn(Boolean returnVal) { - this.returnVal = returnVal; - } - - @Override - public Boolean apply(Integer elem) { - return this.returnVal; - } - } - - static class EvenFn implements SerializableFunction { - @Override - public Boolean apply(Integer elem) { - return elem % 2 == 0; - } - } - - @Deprecated - @Test - @Category(RunnableOnService.class) - public void testIdentityFilterBy() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(591, 11789, 1257, 24578, 24799, 307)) - .apply(Filter.by(new TrivialFn(true))); - - DataflowAssert.that(output).containsInAnyOrder(591, 11789, 1257, 24578, 24799, 307); - p.run(); - } - - @Deprecated - @Test - public void testNoFilter() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(1, 2, 4, 5)) - .apply(Filter.by(new TrivialFn(false))); - - DataflowAssert.that(output).empty(); - p.run(); - } - - @Deprecated - @Test - @Category(RunnableOnService.class) - public void testFilterBy() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(1, 2, 3, 4, 5, 6, 7)) - .apply(Filter.by(new EvenFn())); - - DataflowAssert.that(output).containsInAnyOrder(2, 4, 6); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testIdentityFilterByPredicate() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(591, 11789, 1257, 24578, 24799, 307)) - .apply(Filter.byPredicate(new TrivialFn(true))); - - DataflowAssert.that(output).containsInAnyOrder(591, 11789, 1257, 24578, 24799, 307); - p.run(); - } - - @Test - public void testNoFilterByPredicate() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(1, 2, 4, 5)) - .apply(Filter.byPredicate(new TrivialFn(false))); - - DataflowAssert.that(output).empty(); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFilterByPredicate() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(1, 2, 3, 4, 5, 6, 7)) - .apply(Filter.byPredicate(new EvenFn())); - - DataflowAssert.that(output).containsInAnyOrder(2, 4, 6); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFilterLessThan() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(1, 2, 3, 4, 5, 6, 7)) - .apply(Filter.lessThan(4)); - - DataflowAssert.that(output).containsInAnyOrder(1, 2, 3); - p.run(); - } - - @Test - public void testFilterGreaterThan() { - TestPipeline p = TestPipeline.create(); - - PCollection output = p - .apply(Create.of(1, 2, 3, 4, 5, 6, 7)) - .apply(Filter.greaterThan(4)); - - DataflowAssert.that(output).containsInAnyOrder(5, 6, 7); - p.run(); - } - - @Test - public void testDisplayData() { - ParDo.Bound lessThan = Filter.lessThan(123); - assertThat(DisplayData.from(lessThan), hasDisplayItem("predicate", "x < 123")); - - ParDo.Bound lessThanOrEqual = Filter.lessThanEq(234); - assertThat(DisplayData.from(lessThanOrEqual), hasDisplayItem("predicate", "x ≤ 234")); - - ParDo.Bound greaterThan = Filter.greaterThan(345); - assertThat(DisplayData.from(greaterThan), hasDisplayItem("predicate", "x > 345")); - - ParDo.Bound greaterThanOrEqual = Filter.greaterThanEq(456); - assertThat(DisplayData.from(greaterThanOrEqual), hasDisplayItem("predicate", "x ≥ 456")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java deleted file mode 100644 index 8938b0398f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -/** - * Tests for {@link FlatMapElements}. - */ -@RunWith(JUnit4.class) -public class FlatMapElementsTest implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - /** - * Basic test of {@link FlatMapElements} with a {@link SimpleFunction}. - */ - @Test - public void testFlatMapBasic() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of(1, 2, 3)) - - // Note that FlatMapElements takes a SimpleFunction> - // so the use of List here (as opposed to Iterable) deliberately exercises - // the use of an upper bound. - .apply(FlatMapElements.via(new SimpleFunction>() { - @Override - public List apply(Integer input) { - return ImmutableList.of(-input, input); - } - })); - - DataflowAssert.that(output).containsInAnyOrder(1, -2, -1, -3, 2, 3); - pipeline.run(); - } - - /** - * Tests that when built with a concrete subclass of {@link SimpleFunction}, the type descriptor - * of the output reflects its static type. - */ - @Test - public void testFlatMapFnOutputTypeDescriptor() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of("hello")) - .apply(FlatMapElements.via(new SimpleFunction>() { - @Override - public Set apply(String input) { - return ImmutableSet.copyOf(input.split("")); - } - })); - - assertThat(output.getTypeDescriptor(), - equalTo((TypeDescriptor) new TypeDescriptor() {})); - assertThat(pipeline.getCoderRegistry().getDefaultCoder(output.getTypeDescriptor()), - equalTo(pipeline.getCoderRegistry().getDefaultCoder(new TypeDescriptor() {}))); - - // Make sure the pipeline runs - pipeline.run(); - } - - @Test - public void testVoidValues() throws Exception { - Pipeline pipeline = TestPipeline.create(); - pipeline - .apply(Create.of("hello")) - .apply(WithKeys.of("k")) - .apply(new VoidValues() {}); - // Make sure the pipeline runs - pipeline.run(); - } - - static class VoidValues - extends PTransform>, PCollection>> { - - @Override - public PCollection> apply(PCollection> input) { - return input.apply(FlatMapElements., KV>via( - new SimpleFunction, Iterable>>() { - @Override - public Iterable> apply(KV input) { - return Collections.singletonList(KV.of(input.getKey(), null)); - } - })); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java deleted file mode 100644 index 069ee72fad..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/FlattenTest.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.LINES; -import static com.google.cloud.dataflow.sdk.TestUtils.LINES2; -import static com.google.cloud.dataflow.sdk.TestUtils.LINES_ARRAY; -import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES; -import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES_ARRAY; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CollectionCoder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.SetCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import org.joda.time.Duration; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Set; - -/** - * Tests for Flatten. - */ -@RunWith(JUnit4.class) -public class FlattenTest implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - private static class ClassWithoutCoder { } - - - @Test - @Category(RunnableOnService.class) - public void testFlattenPCollectionList() { - Pipeline p = TestPipeline.create(); - - List> inputs = Arrays.asList( - LINES, NO_LINES, LINES2, NO_LINES, LINES, NO_LINES); - - PCollection output = - makePCollectionListOfStrings(p, inputs) - .apply(Flatten.pCollections()); - - DataflowAssert.that(output).containsInAnyOrder(flattenLists(inputs)); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenPCollectionListThenParDo() { - Pipeline p = TestPipeline.create(); - - List> inputs = Arrays.asList( - LINES, NO_LINES, LINES2, NO_LINES, LINES, NO_LINES); - - PCollection output = - makePCollectionListOfStrings(p, inputs) - .apply(Flatten.pCollections()) - .apply(ParDo.of(new IdentityFn(){})); - - DataflowAssert.that(output).containsInAnyOrder(flattenLists(inputs)); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenPCollectionListEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection output = - PCollectionList.empty(p) - .apply(Flatten.pCollections()).setCoder(StringUtf8Coder.of()); - - DataflowAssert.that(output).empty(); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenInputMultipleCopies() { - Pipeline p = TestPipeline.create(); - - PCollection lines = p.apply("mkLines", Create.of(LINES)); - PCollection lines2 = p.apply("mkOtherLines", Create.of(LINES2)); - - PCollection flattened = PCollectionList.of(lines) - .and(lines2) - .and(lines) - .and(lines) - .apply(Flatten.pCollections()); - - DataflowAssert.that(flattened) - .containsInAnyOrder(Iterables.concat(LINES, LINES, LINES, LINES2)); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testEmptyFlattenAsSideInput() { - Pipeline p = TestPipeline.create(); - - final PCollectionView> view = - PCollectionList.empty(p) - .apply(Flatten.pCollections()).setCoder(StringUtf8Coder.of()) - .apply(View.asIterable()); - - PCollection output = p - .apply(Create.of((Void) null).withCoder(VoidCoder.of())) - .apply(ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - for (String side : c.sideInput(view)) { - c.output(side); - } - } - })); - - DataflowAssert.that(output).empty(); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenPCollectionListEmptyThenParDo() { - - Pipeline p = TestPipeline.create(); - - PCollection output = - PCollectionList.empty(p) - .apply(Flatten.pCollections()).setCoder(StringUtf8Coder.of()) - .apply(ParDo.of(new IdentityFn(){})); - - DataflowAssert.that(output).empty(); - p.run(); - } - - @Test - public void testFlattenNoListsNoCoder() { - // not RunnableOnService because it should fail at pipeline construction time anyhow. - thrown.expect(IllegalStateException.class); - thrown.expectMessage("cannot provide a Coder for empty"); - - Pipeline p = TestPipeline.create(); - - PCollectionList.empty(p) - .apply(Flatten.pCollections()); - - p.run(); - } - - ///////////////////////////////////////////////////////////////////////////// - - @Test - @Category(RunnableOnService.class) - public void testFlattenIterables() { - Pipeline p = TestPipeline.create(); - - PCollection> input = p - .apply(Create.>of(LINES) - .withCoder(IterableCoder.of(StringUtf8Coder.of()))); - - PCollection output = - input.apply(Flatten.iterables()); - - DataflowAssert.that(output) - .containsInAnyOrder(LINES_ARRAY); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenIterablesLists() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.>of(LINES).withCoder(ListCoder.of(StringUtf8Coder.of()))); - - PCollection output = input.apply(Flatten.iterables()); - - DataflowAssert.that(output).containsInAnyOrder(LINES_ARRAY); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenIterablesSets() { - Pipeline p = TestPipeline.create(); - - Set linesSet = ImmutableSet.copyOf(LINES); - - PCollection> input = - p.apply(Create.>of(linesSet).withCoder(SetCoder.of(StringUtf8Coder.of()))); - - PCollection output = input.apply(Flatten.iterables()); - - DataflowAssert.that(output).containsInAnyOrder(LINES_ARRAY); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenIterablesCollections() { - - Pipeline p = TestPipeline.create(); - - Set linesSet = ImmutableSet.copyOf(LINES); - - PCollection> input = - p.apply(Create.>of(linesSet) - .withCoder(CollectionCoder.of(StringUtf8Coder.of()))); - - PCollection output = input.apply(Flatten.iterables()); - - DataflowAssert.that(output).containsInAnyOrder(LINES_ARRAY); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFlattenIterablesEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection> input = p - .apply(Create.>of(NO_LINES) - .withCoder(IterableCoder.of(StringUtf8Coder.of()))); - - PCollection output = - input.apply(Flatten.iterables()); - - DataflowAssert.that(output) - .containsInAnyOrder(NO_LINES_ARRAY); - - p.run(); - } - - ///////////////////////////////////////////////////////////////////////////// - - @Test - public void testEqualWindowFnPropagation() { - Pipeline p = TestPipeline.create(); - - PCollection input1 = - p.apply("CreateInput1", Create.of("Input1")) - .apply("Window1", Window.into(FixedWindows.of(Duration.standardMinutes(1)))); - PCollection input2 = - p.apply("CreateInput2", Create.of("Input2")) - .apply("Window2", Window.into(FixedWindows.of(Duration.standardMinutes(1)))); - - PCollection output = - PCollectionList.of(input1).and(input2) - .apply(Flatten.pCollections()); - - p.run(); - - Assert.assertTrue(output.getWindowingStrategy().getWindowFn().isCompatible( - FixedWindows.of(Duration.standardMinutes(1)))); - } - - @Test - public void testCompatibleWindowFnPropagation() { - Pipeline p = TestPipeline.create(); - - PCollection input1 = - p.apply("CreateInput1", Create.of("Input1")) - .apply("Window1", - Window.into(Sessions.withGapDuration(Duration.standardMinutes(1)))); - PCollection input2 = - p.apply("CreateInput2", Create.of("Input2")) - .apply("Window2", - Window.into(Sessions.withGapDuration(Duration.standardMinutes(2)))); - - PCollection output = - PCollectionList.of(input1).and(input2) - .apply(Flatten.pCollections()); - - p.run(); - - Assert.assertTrue(output.getWindowingStrategy().getWindowFn().isCompatible( - Sessions.withGapDuration(Duration.standardMinutes(2)))); - } - - @Test - public void testIncompatibleWindowFnPropagationFailure() { - Pipeline p = TestPipeline.create(); - - PCollection input1 = - p.apply("CreateInput1", Create.of("Input1")) - .apply("Window1", Window.into(FixedWindows.of(Duration.standardMinutes(1)))); - PCollection input2 = - p.apply("CreateInput2", Create.of("Input2")) - .apply("Window2", Window.into(FixedWindows.of(Duration.standardMinutes(2)))); - - try { - PCollectionList.of(input1).and(input2) - .apply(Flatten.pCollections()); - Assert.fail("Exception should have been thrown"); - } catch (IllegalStateException e) { - Assert.assertTrue(e.getMessage().startsWith( - "Inputs to Flatten had incompatible window windowFns")); - } - } - - @Test - public void testFlattenGetName() { - Assert.assertEquals("Flatten.FlattenIterables", Flatten.iterables().getName()); - Assert.assertEquals("Flatten.FlattenPCollectionList", Flatten.pCollections().getName()); - } - - ///////////////////////////////////////////////////////////////////////////// - - private static class IdentityFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element()); - } - } - - private PCollectionList makePCollectionListOfStrings( - Pipeline p, - List> lists) { - return makePCollectionList(p, StringUtf8Coder.of(), lists); - } - - private PCollectionList makePCollectionList( - Pipeline p, - Coder coder, - List> lists) { - List> pcs = new ArrayList<>(); - int index = 0; - for (List list : lists) { - PCollection pc = p.apply("Create" + (index++), Create.of(list).withCoder(coder)); - pcs.add(pc); - } - return PCollectionList.of(pcs); - } - - private List flattenLists(List> lists) { - List flattened = new ArrayList<>(); - for (List list : lists) { - flattened.addAll(list); - } - return flattened; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java deleted file mode 100644 index 175cc02bb0..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/GroupByKeyTest.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.KvMatcher.isKv; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.InvalidWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Tests for GroupByKey. - */ -@RunWith(JUnit4.class) -@SuppressWarnings({"rawtypes", "unchecked"}) -public class GroupByKeyTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - @Category(RunnableOnService.class) - public void testGroupByKey() { - List> ungroupedPairs = Arrays.asList( - KV.of("k1", 3), - KV.of("k5", Integer.MAX_VALUE), - KV.of("k5", Integer.MIN_VALUE), - KV.of("k2", 66), - KV.of("k1", 4), - KV.of("k2", -33), - KV.of("k3", 0)); - - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(ungroupedPairs) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection>> output = - input.apply(GroupByKey.create()); - - DataflowAssert.that(output) - .satisfies(new AssertThatHasExpectedContentsForTestGroupByKey()); - - p.run(); - } - - static class AssertThatHasExpectedContentsForTestGroupByKey - implements SerializableFunction>>, - Void> { - @Override - public Void apply(Iterable>> actual) { - assertThat(actual, containsInAnyOrder( - isKv(is("k1"), containsInAnyOrder(3, 4)), - isKv(is("k5"), containsInAnyOrder(Integer.MAX_VALUE, - Integer.MIN_VALUE)), - isKv(is("k2"), containsInAnyOrder(66, -33)), - isKv(is("k3"), containsInAnyOrder(0)))); - return null; - } - } - - @Test - @Category(RunnableOnService.class) - public void testGroupByKeyAndWindows() { - List> ungroupedPairs = Arrays.asList( - KV.of("k1", 3), // window [0, 5) - KV.of("k5", Integer.MAX_VALUE), // window [0, 5) - KV.of("k5", Integer.MIN_VALUE), // window [0, 5) - KV.of("k2", 66), // window [0, 5) - KV.of("k1", 4), // window [5, 10) - KV.of("k2", -33), // window [5, 10) - KV.of("k3", 0)); // window [5, 10) - - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.timestamped(ungroupedPairs, Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L)) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - PCollection>> output = - input.apply(Window.>into(FixedWindows.of(new Duration(5)))) - .apply(GroupByKey.create()); - - DataflowAssert.that(output) - .satisfies(new AssertThatHasExpectedContentsForTestGroupByKeyAndWindows()); - - p.run(); - } - - static class AssertThatHasExpectedContentsForTestGroupByKeyAndWindows - implements SerializableFunction>>, - Void> { - @Override - public Void apply(Iterable>> actual) { - assertThat(actual, containsInAnyOrder( - isKv(is("k1"), containsInAnyOrder(3)), - isKv(is("k1"), containsInAnyOrder(4)), - isKv(is("k5"), containsInAnyOrder(Integer.MAX_VALUE, - Integer.MIN_VALUE)), - isKv(is("k2"), containsInAnyOrder(66)), - isKv(is("k2"), containsInAnyOrder(-33)), - isKv(is("k3"), containsInAnyOrder(0)))); - return null; - } - } - - @Test - @Category(RunnableOnService.class) - public void testGroupByKeyEmpty() { - List> ungroupedPairs = Arrays.asList(); - - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(ungroupedPairs) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection>> output = - input.apply(GroupByKey.create()); - - DataflowAssert.that(output).empty(); - - p.run(); - } - - @Test - public void testGroupByKeyNonDeterministic() throws Exception { - - List, Integer>> ungroupedPairs = Arrays.asList(); - - Pipeline p = TestPipeline.create(); - - PCollection, Integer>> input = - p.apply(Create.of(ungroupedPairs) - .withCoder( - KvCoder.of(MapCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()), - BigEndianIntegerCoder.of()))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("must be deterministic"); - input.apply(GroupByKey., Integer>create()); - } - - @Test - public void testIdentityWindowFnPropagation() { - Pipeline p = TestPipeline.create(); - - List> ungroupedPairs = Arrays.asList(); - - PCollection> input = - p.apply(Create.of(ungroupedPairs) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into(FixedWindows.of(Duration.standardMinutes(1)))); - - PCollection>> output = - input.apply(GroupByKey.create()); - - p.run(); - - Assert.assertTrue(output.getWindowingStrategy().getWindowFn().isCompatible( - FixedWindows.of(Duration.standardMinutes(1)))); - } - - @Test - public void testWindowFnInvalidation() { - Pipeline p = TestPipeline.create(); - - List> ungroupedPairs = Arrays.asList(); - - PCollection> input = - p.apply(Create.of(ungroupedPairs) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into( - Sessions.withGapDuration(Duration.standardMinutes(1)))); - - PCollection>> output = - input.apply(GroupByKey.create()); - - p.run(); - - Assert.assertTrue( - output.getWindowingStrategy().getWindowFn().isCompatible( - new InvalidWindows( - "Invalid", - Sessions.withGapDuration( - Duration.standardMinutes(1))))); - } - - /** - * Create a test pipeline that uses the {@link DataflowPipelineRunner} so that {@link GroupByKey} - * is not expanded. This is used for verifying that even without expansion the proper errors show - * up. - */ - private Pipeline createTestServiceRunner() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("someproject"); - options.setStagingLocation("gs://staging"); - options.setPathValidatorClass(NoopPathValidator.class); - options.setDataflowClient(null); - return Pipeline.create(options); - } - - private Pipeline createTestDirectRunner() { - DirectPipelineOptions options = PipelineOptionsFactory.as(DirectPipelineOptions.class); - options.setRunner(DirectPipelineRunner.class); - return Pipeline.create(options); - } - - @Test - public void testInvalidWindowsDirect() { - Pipeline p = createTestDirectRunner(); - - List> ungroupedPairs = Arrays.asList(); - - PCollection> input = - p.apply(Create.of(ungroupedPairs) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into( - Sessions.withGapDuration(Duration.standardMinutes(1)))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("GroupByKey must have a valid Window merge function"); - input - .apply("GroupByKey", GroupByKey.create()) - .apply("GroupByKeyAgain", GroupByKey.>create()); - } - - @Test - public void testInvalidWindowsService() { - Pipeline p = createTestServiceRunner(); - - List> ungroupedPairs = Arrays.asList(); - - PCollection> input = - p.apply(Create.of(ungroupedPairs) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into( - Sessions.withGapDuration(Duration.standardMinutes(1)))); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("GroupByKey must have a valid Window merge function"); - input - .apply("GroupByKey", GroupByKey.create()) - .apply("GroupByKeyAgain", GroupByKey.>create()); - } - - @Test - public void testRemerge() { - Pipeline p = TestPipeline.create(); - - List> ungroupedPairs = Arrays.asList(); - - PCollection> input = - p.apply(Create.of(ungroupedPairs) - .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))) - .apply(Window.>into( - Sessions.withGapDuration(Duration.standardMinutes(1)))); - - PCollection>>> middle = input - .apply("GroupByKey", GroupByKey.create()) - .apply("Remerge", Window.>>remerge()) - .apply("GroupByKeyAgain", GroupByKey.>create()) - .apply("RemergeAgain", Window.>>>remerge()); - - p.run(); - - Assert.assertTrue( - middle.getWindowingStrategy().getWindowFn().isCompatible( - Sessions.withGapDuration(Duration.standardMinutes(1)))); - } - - @Test - public void testGroupByKeyDirectUnbounded() { - Pipeline p = createTestDirectRunner(); - - PCollection> input = - p.apply( - new PTransform>>() { - @Override - public PCollection> apply(PBegin input) { - return PCollection.>createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - PCollection.IsBounded.UNBOUNDED) - .setTypeDescriptorInternal(new TypeDescriptor>() {}); - } - }); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "GroupByKey cannot be applied to non-bounded PCollection in the GlobalWindow without " - + "a trigger. Use a Window.into or Window.triggering transform prior to GroupByKey."); - - input.apply("GroupByKey", GroupByKey.create()); - } - - @Test - public void testGroupByKeyServiceUnbounded() { - Pipeline p = createTestServiceRunner(); - - PCollection> input = - p.apply( - new PTransform>>() { - @Override - public PCollection> apply(PBegin input) { - return PCollection.>createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - PCollection.IsBounded.UNBOUNDED) - .setTypeDescriptorInternal(new TypeDescriptor>() {}); - } - }); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "GroupByKey cannot be applied to non-bounded PCollection in the GlobalWindow without " - + "a trigger. Use a Window.into or Window.triggering transform prior to GroupByKey."); - - input.apply("GroupByKey", GroupByKey.create()); - } - - /** - * Tests that when two elements are combined via a GroupByKey their output timestamp agrees - * with the windowing function customized to actually be the same as the default, the earlier of - * the two values. - */ - @Test - @Category(RunnableOnService.class) - public void testOutputTimeFnEarliest() { - Pipeline pipeline = TestPipeline.create(); - - pipeline.apply( - Create.timestamped( - TimestampedValue.of(KV.of(0, "hello"), new Instant(0)), - TimestampedValue.of(KV.of(0, "goodbye"), new Instant(10)))) - .apply(Window.>into(FixedWindows.of(Duration.standardMinutes(10))) - .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp())) - .apply(GroupByKey.create()) - .apply(ParDo.of(new AssertTimestamp(new Instant(0)))); - - pipeline.run(); - } - - - /** - * Tests that when two elements are combined via a GroupByKey their output timestamp agrees - * with the windowing function customized to use the latest value. - */ - @Test - @Category(RunnableOnService.class) - public void testOutputTimeFnLatest() { - Pipeline pipeline = TestPipeline.create(); - - pipeline.apply( - Create.timestamped( - TimestampedValue.of(KV.of(0, "hello"), new Instant(0)), - TimestampedValue.of(KV.of(0, "goodbye"), new Instant(10)))) - .apply(Window.>into(FixedWindows.of(Duration.standardMinutes(10))) - .withOutputTimeFn(OutputTimeFns.outputAtLatestInputTimestamp())) - .apply(GroupByKey.create()) - .apply(ParDo.of(new AssertTimestamp(new Instant(10)))); - - pipeline.run(); - } - - private static class AssertTimestamp extends DoFn, Void> { - private final Instant timestamp; - - public AssertTimestamp(Instant timestamp) { - this.timestamp = timestamp; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - assertThat(c.timestamp(), equalTo(timestamp)); - } - } - - @Test - public void testGroupByKeyGetName() { - Assert.assertEquals("GroupByKey", GroupByKey.create().getName()); - } - - @Test - public void testDisplayData() { - GroupByKey groupByKey = GroupByKey.create(); - GroupByKey groupByFewKeys = GroupByKey.create(true); - - DisplayData gbkDisplayData = DisplayData.from(groupByKey); - DisplayData fewKeysDisplayData = DisplayData.from(groupByFewKeys); - - assertThat(gbkDisplayData.items(), empty()); - assertThat(fewKeysDisplayData, hasDisplayItem("fewKeys", true)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java deleted file mode 100644 index 012ffe327d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/IntraBundleParallelizationTest.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.testing.SystemNanoTimeSleeper.sleepMillis; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.hamcrest.Matchers.both; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Tests for RateLimiter. - */ -@RunWith(JUnit4.class) -public class IntraBundleParallelizationTest { - private static final int PARALLELISM_FACTOR = 16; - private static final AtomicInteger numSuccesses = new AtomicInteger(); - private static final AtomicInteger numProcessed = new AtomicInteger(); - private static final AtomicInteger numFailures = new AtomicInteger(); - private static int concurrentElements = 0; - private static int maxDownstreamConcurrency = 0; - - private static final AtomicInteger maxFnConcurrency = new AtomicInteger(); - private static final AtomicInteger currentFnConcurrency = new AtomicInteger(); - - @Before - public void setUp() { - numSuccesses.set(0); - numProcessed.set(0); - numFailures.set(0); - concurrentElements = 0; - maxDownstreamConcurrency = 0; - - maxFnConcurrency.set(0); - currentFnConcurrency.set(0); - } - - /** - * Introduces a delay in processing, then passes thru elements. - */ - private static class DelayFn extends DoFn { - public static final long DELAY_MS = 25; - - @Override - public void processElement(ProcessContext c) { - startConcurrentCall(); - try { - sleepMillis(DELAY_MS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - e.printStackTrace(); - throw new RuntimeException("Interrupted"); - } - c.output(c.element()); - finishConcurrentCall(); - } - } - - /** - * Throws an exception after some number of calls. - */ - private static class ExceptionThrowingFn extends DoFn { - private ExceptionThrowingFn(int numSuccesses) { - IntraBundleParallelizationTest.numSuccesses.set(numSuccesses); - } - - @Override - public void processElement(ProcessContext c) { - startConcurrentCall(); - try { - numProcessed.incrementAndGet(); - if (numSuccesses.decrementAndGet() >= 0) { - c.output(c.element()); - return; - } - - numFailures.incrementAndGet(); - throw new RuntimeException("Expected failure"); - } finally { - finishConcurrentCall(); - } - } - } - - /** - * Measures concurrency of the processElement method. - */ - private static class ConcurrencyMeasuringFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - // Synchronize on the class to provide synchronous access irrespective of - // how this DoFn is called. - synchronized (ConcurrencyMeasuringFn.class) { - concurrentElements++; - if (concurrentElements > maxDownstreamConcurrency) { - maxDownstreamConcurrency = concurrentElements; - } - } - - c.output(c.element()); - - synchronized (ConcurrencyMeasuringFn.class) { - concurrentElements--; - } - } - } - - private static void startConcurrentCall() { - int currentlyExecuting = currentFnConcurrency.incrementAndGet(); - int maxConcurrency; - do { - maxConcurrency = maxFnConcurrency.get(); - } while (maxConcurrency < currentlyExecuting - && !maxFnConcurrency.compareAndSet(maxConcurrency, currentlyExecuting)); - } - - private static void finishConcurrentCall() { - currentFnConcurrency.decrementAndGet(); - } - - /** - * Test that the DoFn is parallelized up the the Max Parallelism factor within a bundle, but not - * greater than that amount. - */ - @Test - public void testParallelization() { - int maxConcurrency = Integer.MIN_VALUE; - // Take the minimum from multiple runs. - for (int i = 0; i < 5; ++i) { - maxConcurrency = Math.max(maxConcurrency, - run(2 * PARALLELISM_FACTOR, PARALLELISM_FACTOR, new DelayFn())); - } - - // We should run at least some elements in parallel on some run - assertThat(maxConcurrency, - greaterThanOrEqualTo(2)); - // No run should execute more elements concurrency than the maximum concurrency allowed. - assertThat(maxConcurrency, - lessThanOrEqualTo(PARALLELISM_FACTOR)); - } - - @Test(timeout = 5000L) - public void testExceptionHandling() { - ExceptionThrowingFn fn = new ExceptionThrowingFn<>(10); - try { - run(100, PARALLELISM_FACTOR, fn); - fail("Expected exception to propagate"); - } catch (RuntimeException e) { - assertThat(e.getMessage(), containsString("Expected failure")); - } - - // Should have processed 10 elements, but stopped before processing all - // of them. - assertThat(numProcessed.get(), - is(both(greaterThanOrEqualTo(10)) - .and(lessThan(100)))); - - // The first failure should prevent the scheduling of any more elements. - assertThat(numFailures.get(), - is(both(greaterThanOrEqualTo(1)) - .and(lessThanOrEqualTo(PARALLELISM_FACTOR)))); - } - - @Test(timeout = 5000L) - public void testExceptionHandlingOnLastElement() { - ExceptionThrowingFn fn = new ExceptionThrowingFn<>(9); - try { - run(10, PARALLELISM_FACTOR, fn); - fail("Expected exception to propagate"); - } catch (RuntimeException e) { - assertThat(e.getMessage(), containsString("Expected failure")); - } - - // Should have processed 10 elements, but stopped before processing all - // of them. - assertEquals(10, numProcessed.get()); - assertEquals(1, numFailures.get()); - } - - @Test - public void testIntraBundleParallelizationGetName() { - assertEquals( - "IntraBundleParallelization", - IntraBundleParallelization.of(new DelayFn()).withMaxParallelism(1).getName()); - } - - @Test - public void testDisplayData() { - DoFn fn = new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - PTransform transform = IntraBundleParallelization - .withMaxParallelism(1234) - .of(fn); - - DisplayData displayData = DisplayData.from(transform); - assertThat(displayData, includesDisplayDataFrom(fn)); - assertThat(displayData, hasDisplayItem("fn", fn.getClass())); - assertThat(displayData, hasDisplayItem("maxParallelism", 1234)); - } - - /** - * Runs the provided doFn inside of an {@link IntraBundleParallelization} transform. - * - *

              This method assumes that the DoFn passed to it will call {@link #startConcurrentCall()} - * before processing each elements and {@link #finishConcurrentCall()} after each element. - * - * @param numElements the size of the input - * @param maxParallelism how many threads to execute in parallel - * @param doFn the DoFn to execute - * @return the maximum observed parallelism of the DoFn - */ - private int run(int numElements, int maxParallelism, DoFn doFn) { - Pipeline pipeline = TestPipeline.create(); - - ArrayList data = new ArrayList<>(numElements); - for (int i = 0; i < numElements; ++i) { - data.add(i); - } - - ConcurrencyMeasuringFn downstream = new ConcurrencyMeasuringFn<>(); - pipeline - .apply(Create.of(data)) - .apply(IntraBundleParallelization.of(doFn).withMaxParallelism(maxParallelism)) - .apply(ParDo.of(downstream)); - - pipeline.run(); - - // All elements should have completed. - assertEquals(0, currentFnConcurrency.get()); - // Downstream methods should not see parallel threads. - assertEquals(1, maxDownstreamConcurrency); - - return maxFnConcurrency.get(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KeysTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KeysTest.java deleted file mode 100644 index e9edbb71c8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KeysTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** - * Tests for Keys transform. - */ -@RunWith(JUnit4.class) -public class KeysTest { - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] TABLE = new KV[] { - KV.of("one", 1), - KV.of("two", 2), - KV.of("three", 3), - KV.of("dup", 4), - KV.of("dup", 5) - }; - - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] EMPTY_TABLE = new KV[] { - }; - - @Test - @Category(RunnableOnService.class) - public void testKeys() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(Arrays.asList(TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection output = input.apply(Keys.create()); - DataflowAssert.that(output) - .containsInAnyOrder("one", "two", "three", "dup", "dup"); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testKeysEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(Arrays.asList(EMPTY_TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection output = input.apply(Keys.create()); - DataflowAssert.that(output).empty(); - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KvSwapTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KvSwapTest.java deleted file mode 100644 index 06abbadd1b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/KvSwapTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** - * Tests for KvSwap transform. - */ -@RunWith(JUnit4.class) -@SuppressWarnings({"rawtypes", "unchecked"}) -public class KvSwapTest { - static final KV[] TABLE = new KV[] { - KV.of("one", 1), - KV.of("two", 2), - KV.of("three", 3), - KV.of("four", 4), - KV.of("dup", 4), - KV.of("dup", 5) - }; - - static final KV[] EMPTY_TABLE = new KV[] { - }; - - @Test - @Category(RunnableOnService.class) - public void testKvSwap() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(Arrays.asList(TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection> output = input.apply( - KvSwap.create()); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of(1, "one"), - KV.of(2, "two"), - KV.of(3, "three"), - KV.of(4, "four"), - KV.of(4, "dup"), - KV.of(5, "dup")); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testKvSwapEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(Arrays.asList(EMPTY_TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection> output = input.apply( - KvSwap.create()); - - DataflowAssert.that(output).empty(); - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java deleted file mode 100644 index aba79d9abb..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MapElementsTest.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DataflowDisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataEvaluator; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Set; - -/** - * Tests for {@link MapElements}. - */ -@RunWith(JUnit4.class) -public class MapElementsTest implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - /** - * Basic test of {@link MapElements} with a {@link SimpleFunction}. - */ - @Test - public void testMapBasic() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of(1, 2, 3)) - .apply(MapElements.via(new SimpleFunction() { - @Override - public Integer apply(Integer input) { - return -input; - } - })); - - DataflowAssert.that(output).containsInAnyOrder(-2, -1, -3); - pipeline.run(); - } - - /** - * Basic test of {@link MapElements} with a {@link SerializableFunction}. This style is - * generally discouraged in Java 7, in favor of {@link SimpleFunction}. - */ - @Test - public void testMapBasicSerializableFunction() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of(1, 2, 3)) - .apply(MapElements.via(new SerializableFunction() { - @Override - public Integer apply(Integer input) { - return -input; - } - }).withOutputType(new TypeDescriptor() {})); - - DataflowAssert.that(output).containsInAnyOrder(-2, -1, -3); - pipeline.run(); - } - - /** - * Tests that when built with a concrete subclass of {@link SimpleFunction}, the type descriptor - * of the output reflects its static type. - */ - @Test - public void testSimpleFunctionOutputTypeDescriptor() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of("hello")) - .apply(MapElements.via(new SimpleFunction() { - @Override - public String apply(String input) { - return input; - } - })); - assertThat(output.getTypeDescriptor(), - equalTo((TypeDescriptor) new TypeDescriptor() {})); - assertThat(pipeline.getCoderRegistry().getDefaultCoder(output.getTypeDescriptor()), - equalTo(pipeline.getCoderRegistry().getDefaultCoder(new TypeDescriptor() {}))); - - // Make sure the pipeline runs too - pipeline.run(); - } - - @Test - public void testVoidValues() throws Exception { - Pipeline pipeline = TestPipeline.create(); - pipeline - .apply(Create.of("hello")) - .apply(WithKeys.of("k")) - .apply(new VoidValues() {}); - // Make sure the pipeline runs - pipeline.run(); - } - - @Test - public void testSerializableFunctionDisplayData() { - SerializableFunction serializableFn = - new SerializableFunction() { - @Override - public Integer apply(Integer input) { - return input; - } - }; - - MapElements serializableMap = MapElements.via(serializableFn) - .withOutputType(TypeDescriptor.of(Integer.class)); - assertThat(DisplayData.from(serializableMap), - hasDisplayItem("mapFn", serializableFn.getClass())); - } - - @Test - public void testSimpleFunctionDisplayData() { - SimpleFunction simpleFn = new SimpleFunction() { - @Override - public Integer apply(Integer input) { - return input; - } - }; - - MapElements simpleMap = MapElements.via(simpleFn); - assertThat(DisplayData.from(simpleMap), hasDisplayItem("mapFn", simpleFn.getClass())); - } - - @Test - public void testPrimitiveDisplayData() { - SimpleFunction mapFn = new SimpleFunction() { - @Override - public Integer apply(Integer input) { - return input; - } - }; - - MapElements map = MapElements.via(mapFn); - DisplayDataEvaluator evaluator = DataflowDisplayDataEvaluator.create(); - - Set displayData = evaluator.displayDataForPrimitiveTransforms(map); - assertThat("MapElements should include the mapFn in its primitive display data", - displayData, hasItem(hasDisplayItem("mapFn", mapFn.getClass()))); - } - - static class VoidValues - extends PTransform>, PCollection>> { - - @Override - public PCollection> apply(PCollection> input) { - return input.apply(MapElements.via( - new SimpleFunction, KV>() { - @Override - public KV apply(KV input) { - return KV.of(input.getKey(), null); - } - })); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java deleted file mode 100644 index 0dc95b4cbe..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MaxTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for Max. - */ -@RunWith(JUnit4.class) -public class MaxTest { - @Test - public void testMeanGetNames() { - assertEquals("Max.Globally", Max.integersGlobally().getName()); - assertEquals("Max.Globally", Max.doublesGlobally().getName()); - assertEquals("Max.Globally", Max.longsGlobally().getName()); - assertEquals("Max.PerKey", Max.integersPerKey().getName()); - assertEquals("Max.PerKey", Max.doublesPerKey().getName()); - assertEquals("Max.PerKey", Max.longsPerKey().getName()); - } - - @Test - public void testMaxIntegerFn() { - checkCombineFn( - new Max.MaxIntegerFn(), - Lists.newArrayList(1, 2, 3, 4), - 4); - } - - @Test - public void testMaxLongFn() { - checkCombineFn( - new Max.MaxLongFn(), - Lists.newArrayList(1L, 2L, 3L, 4L), - 4L); - } - - @Test - public void testMaxDoubleFn() { - checkCombineFn( - new Max.MaxDoubleFn(), - Lists.newArrayList(1.0, 2.0, 3.0, 4.0), - 4.0); - } - - @Test - public void testDisplayData() { - Top.Largest comparer = new Top.Largest<>(); - - Combine.Globally max = Max.globally(comparer); - assertThat(DisplayData.from(max), hasDisplayItem("comparer", comparer.getClass())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java deleted file mode 100644 index 64a2f9de94..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MeanTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.transforms.Mean.CountSum; -import com.google.cloud.dataflow.sdk.transforms.Mean.CountSumCoder; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for Mean. - */ -@RunWith(JUnit4.class) -public class MeanTest { - @Test - public void testMeanGetNames() { - assertEquals("Mean.Globally", Mean.globally().getName()); - assertEquals("Mean.PerKey", Mean.perKey().getName()); - } - - private static final Coder> TEST_CODER = new CountSumCoder<>(); - - private static final List> TEST_VALUES = Arrays.asList( - new CountSum<>(1, 5.7), - new CountSum<>(42, 42.0), - new CountSum<>(29, 2.2)); - - @Test - public void testCountSumCoderEncodeDecode() throws Exception { - for (CountSum value : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, value); - } - } - - @Test - public void testCountSumCoderSerializable() throws Exception { - CoderProperties.coderSerializable(TEST_CODER); - } - - @Test - public void testMeanFn() throws Exception { - checkCombineFn( - new Mean.MeanFn(), - Lists.newArrayList(1, 2, 3, 4), - 2.5); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java deleted file mode 100644 index 8ef2a73ab6..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/MinTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - - -import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for Min. - */ -@RunWith(JUnit4.class) -public class MinTest { - @Test - public void testMeanGetNames() { - assertEquals("Min.Globally", Min.integersGlobally().getName()); - assertEquals("Min.Globally", Min.doublesGlobally().getName()); - assertEquals("Min.Globally", Min.longsGlobally().getName()); - assertEquals("Min.PerKey", Min.integersPerKey().getName()); - assertEquals("Min.PerKey", Min.doublesPerKey().getName()); - assertEquals("Min.PerKey", Min.longsPerKey().getName()); - } - - @Test - public void testMinIntegerFn() { - checkCombineFn( - new Min.MinIntegerFn(), - Lists.newArrayList(1, 2, 3, 4), - 1); - } - - @Test - public void testMinLongFn() { - checkCombineFn( - new Min.MinLongFn(), - Lists.newArrayList(1L, 2L, 3L, 4L), - 1L); - } - - @Test - public void testMinDoubleFn() { - checkCombineFn( - new Min.MinDoubleFn(), - Lists.newArrayList(1.0, 2.0, 3.0, 4.0), - 1.0); - } - - @Test - public void testDisplayData() { - Top.Smallest comparer = new Top.Smallest<>(); - - Combine.Globally min = Min.globally(comparer); - assertThat(DisplayData.from(min), hasDisplayItem("comparer", comparer.getClass())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/NoOpDoFn.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/NoOpDoFn.java deleted file mode 100644 index 20646cfb8e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/NoOpDoFn.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.WindowingInternals; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.joda.time.Instant; - -/** - * A {@link DoFn} that does nothing with provided elements. Used for testing - * methods provided by the DoFn abstract class. - * - * @param unused. - * @param unused. - */ -class NoOpDoFn extends DoFn { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - } - - /** - * Returns a new NoOp Context. - */ - public DoFn.Context context() { - return new NoOpDoFnContext(); - } - - /** - * Returns a new NoOp Process Context. - */ - public DoFn.ProcessContext processContext() { - return new NoOpDoFnProcessContext(); - } - - /** - * A {@link DoFn.Context} that does nothing and returns exclusively null. - */ - private class NoOpDoFnContext extends DoFn.Context { - @Override - public PipelineOptions getPipelineOptions() { - return null; - } - @Override - public void output(OutputT output) { - } - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) { - } - @Override - public void sideOutput(TupleTag tag, T output) { - } - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, - Instant timestamp) { - } - @Override - protected Aggregator - createAggregatorInternal(String name, CombineFn combiner) { - return null; - } - } - - /** - * A {@link DoFn.ProcessContext} that does nothing and returns exclusively - * null. - */ - private class NoOpDoFnProcessContext extends DoFn.ProcessContext { - @Override - public InputT element() { - return null; - } - - @Override - public T sideInput(PCollectionView view) { - return null; - } - - @Override - public Instant timestamp() { - return null; - } - - @Override - public BoundedWindow window() { - return null; - } - - @Override - public PaneInfo pane() { - return null; - } - - @Override - public WindowingInternals windowingInternals() { - return null; - } - - @Override - public PipelineOptions getPipelineOptions() { - return null; - } - - @Override - public void output(OutputT output) {} - - @Override - public void outputWithTimestamp(OutputT output, Instant timestamp) {} - - @Override - public void sideOutput(TupleTag tag, T output) {} - - @Override - public void sideOutputWithTimestamp(TupleTag tag, T output, - Instant timestamp) {} - - @Override - protected Aggregator - createAggregatorInternal(String name, CombineFn combiner) { - return null; - } - - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java deleted file mode 100644 index cea1b38df7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PTransformTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link PTransform} base class. - */ -@RunWith(JUnit4.class) -public class PTransformTest { - @Test - public void testPopulateDisplayDataDefaultBehavior() { - PTransform, PCollection> transform = - new PTransform, PCollection>() {}; - DisplayData displayData = DisplayData.from(transform); - assertThat(displayData.items(), empty()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java deleted file mode 100644 index c055db4a9c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ParDoTest.java +++ /dev/null @@ -1,1592 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; -import static com.google.cloud.dataflow.sdk.util.SerializableUtils.serializeToByteArray; -import static com.google.cloud.dataflow.sdk.util.StringUtils.byteArrayToJsonString; -import static com.google.cloud.dataflow.sdk.util.StringUtils.jsonStringToByteArray; -import static com.google.common.base.Preconditions.checkNotNull; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.hamcrest.core.AnyOf.anyOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.ParDo.Bound; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.IllegalMutationException; -import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionTuple; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import com.fasterxml.jackson.annotation.JsonCreator; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests for ParDo. - */ -@RunWith(JUnit4.class) -public class ParDoTest implements Serializable { - // This test is Serializable, just so that it's easy to have - // anonymous inner classes inside the non-static test methods. - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - private static class PrintingDoFn extends DoFn implements RequiresWindowAccess { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + ":" + c.timestamp().getMillis() - + ":" + c.window().maxTimestamp().getMillis()); - } - } - - static class TestDoFn extends DoFn { - enum State { UNSTARTED, STARTED, PROCESSING, FINISHED } - State state = State.UNSTARTED; - - final List> sideInputViews = new ArrayList<>(); - final List> sideOutputTupleTags = new ArrayList<>(); - - public TestDoFn() { - } - - public TestDoFn(List> sideInputViews, - List> sideOutputTupleTags) { - this.sideInputViews.addAll(sideInputViews); - this.sideOutputTupleTags.addAll(sideOutputTupleTags); - } - - @Override - public void startBundle(Context c) { - assertEquals(State.UNSTARTED, state); - state = State.STARTED; - outputToAll(c, "started"); - } - - @Override - public void processElement(ProcessContext c) { - assertThat(state, - anyOf(equalTo(State.STARTED), equalTo(State.PROCESSING))); - state = State.PROCESSING; - outputToAllWithSideInputs(c, "processing: " + c.element()); - } - - @Override - public void finishBundle(Context c) { - assertThat(state, - anyOf(equalTo(State.STARTED), equalTo(State.PROCESSING))); - state = State.FINISHED; - outputToAll(c, "finished"); - } - - private void outputToAll(Context c, String value) { - c.output(value); - for (TupleTag sideOutputTupleTag : sideOutputTupleTags) { - c.sideOutput(sideOutputTupleTag, - sideOutputTupleTag.getId() + ": " + value); - } - } - - private void outputToAllWithSideInputs(ProcessContext c, String value) { - if (!sideInputViews.isEmpty()) { - List sideInputValues = new ArrayList<>(); - for (PCollectionView sideInputView : sideInputViews) { - sideInputValues.add(c.sideInput(sideInputView)); - } - value += ": " + sideInputValues; - } - c.output(value); - for (TupleTag sideOutputTupleTag : sideOutputTupleTags) { - c.sideOutput(sideOutputTupleTag, - sideOutputTupleTag.getId() + ": " + value); - } - } - } - - static class TestNoOutputDoFn extends DoFn { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception {} - } - - static class TestDoFnWithContext extends DoFnWithContext { - enum State { UNSTARTED, STARTED, PROCESSING, FINISHED } - State state = State.UNSTARTED; - - final List> sideInputViews = new ArrayList<>(); - final List> sideOutputTupleTags = new ArrayList<>(); - - public TestDoFnWithContext() { - } - - public TestDoFnWithContext(List> sideInputViews, - List> sideOutputTupleTags) { - this.sideInputViews.addAll(sideInputViews); - this.sideOutputTupleTags.addAll(sideOutputTupleTags); - } - - @StartBundle - public void startBundle(Context c) { - assertEquals(State.UNSTARTED, state); - state = State.STARTED; - outputToAll(c, "started"); - } - - @ProcessElement - public void processElement(ProcessContext c) { - assertThat(state, - anyOf(equalTo(State.STARTED), equalTo(State.PROCESSING))); - state = State.PROCESSING; - outputToAllWithSideInputs(c, "processing: " + c.element()); - } - - @FinishBundle - public void finishBundle(Context c) { - assertThat(state, - anyOf(equalTo(State.STARTED), equalTo(State.PROCESSING))); - state = State.FINISHED; - outputToAll(c, "finished"); - } - - private void outputToAll(Context c, String value) { - c.output(value); - for (TupleTag sideOutputTupleTag : sideOutputTupleTags) { - c.sideOutput(sideOutputTupleTag, - sideOutputTupleTag.getId() + ": " + value); - } - } - - private void outputToAllWithSideInputs(ProcessContext c, String value) { - if (!sideInputViews.isEmpty()) { - List sideInputValues = new ArrayList<>(); - for (PCollectionView sideInputView : sideInputViews) { - sideInputValues.add(c.sideInput(sideInputView)); - } - value += ": " + sideInputValues; - } - c.output(value); - for (TupleTag sideOutputTupleTag : sideOutputTupleTags) { - c.sideOutput(sideOutputTupleTag, - sideOutputTupleTag.getId() + ": " + value); - } - } - } - - static class TestStartBatchErrorDoFn extends DoFn { - @Override - public void startBundle(Context c) { - throw new RuntimeException("test error in initialize"); - } - - @Override - public void processElement(ProcessContext c) { - // This has to be here. - } - } - - static class TestProcessElementErrorDoFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - throw new RuntimeException("test error in process"); - } - } - - static class TestFinishBatchErrorDoFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - // This has to be here. - } - - @Override - public void finishBundle(Context c) { - throw new RuntimeException("test error in finalize"); - } - } - - private static class StrangelyNamedDoer extends DoFn { - @Override - public void processElement(ProcessContext c) { - } - } - - static class TestOutputTimestampDoFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - Integer value = c.element(); - c.outputWithTimestamp(value, new Instant(value.longValue())); - } - } - - static class TestShiftTimestampDoFn extends DoFn { - private Duration allowedTimestampSkew; - private Duration durationToShift; - - public TestShiftTimestampDoFn(Duration allowedTimestampSkew, - Duration durationToShift) { - this.allowedTimestampSkew = allowedTimestampSkew; - this.durationToShift = durationToShift; - } - - @Override - public Duration getAllowedTimestampSkew() { - return allowedTimestampSkew; - } - @Override - public void processElement(ProcessContext c) { - Instant timestamp = c.timestamp(); - checkNotNull(timestamp); - Integer value = c.element(); - c.outputWithTimestamp(value, timestamp.plus(durationToShift)); - } - } - - static class TestFormatTimestampDoFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - checkNotNull(c.timestamp()); - c.output("processing: " + c.element() + ", timestamp: " + c.timestamp().getMillis()); - } - } - - static class MultiFilter - extends PTransform, PCollectionTuple> { - - private static final TupleTag BY2 = new TupleTag("by2"){}; - private static final TupleTag BY3 = new TupleTag("by3"){}; - - @Override - public PCollectionTuple apply(PCollection input) { - PCollection by2 = input.apply("Filter2s", ParDo.of(new FilterFn(2))); - PCollection by3 = input.apply("Filter3s", ParDo.of(new FilterFn(3))); - return PCollectionTuple.of(BY2, by2).and(BY3, by3); - } - - static class FilterFn extends DoFn { - private final int divisor; - - FilterFn(int divisor) { - this.divisor = divisor; - } - - @Override - public void processElement(ProcessContext c) throws Exception { - if (c.element() % divisor == 0) { - c.output(c.element()); - } - } - } - } - - @Test - @Category(RunnableOnService.class) - public void testParDo() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - PCollection output = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.of(new TestDoFn())); - - DataflowAssert.that(output) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDo2() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - PCollection output = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.of(new TestDoFnWithContext())); - - DataflowAssert.that(output) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoEmpty() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(); - - PCollection output = pipeline - .apply(Create.of(inputs).withCoder(VarIntCoder.of())) - .apply("TestDoFn", ParDo.of(new TestDoFn())); - - DataflowAssert.that(output) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoEmptyOutputs() { - - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(); - - PCollection output = pipeline - .apply(Create.of(inputs).withCoder(VarIntCoder.of())) - .apply("TestDoFn", ParDo.of(new TestNoOutputDoFn())); - - DataflowAssert.that(output).empty(); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoWithSideOutputs() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - TupleTag mainOutputTag = new TupleTag("main"){}; - TupleTag sideOutputTag1 = new TupleTag("side1"){}; - TupleTag sideOutputTag2 = new TupleTag("side2"){}; - TupleTag sideOutputTag3 = new TupleTag("side3"){}; - TupleTag sideOutputTagUnwritten = new TupleTag("sideUnwritten"){}; - - PCollectionTuple outputs = pipeline - .apply(Create.of(inputs)) - .apply(ParDo - .of(new TestDoFn( - Arrays.>asList(), - Arrays.asList(sideOutputTag1, sideOutputTag2, sideOutputTag3))) - .withOutputTags( - mainOutputTag, - TupleTagList.of(sideOutputTag3) - .and(sideOutputTag1) - .and(sideOutputTagUnwritten) - .and(sideOutputTag2))); - - DataflowAssert.that(outputs.get(mainOutputTag)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs)); - - DataflowAssert.that(outputs.get(sideOutputTag1)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs) - .fromSideOutput(sideOutputTag1)); - DataflowAssert.that(outputs.get(sideOutputTag2)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs) - .fromSideOutput(sideOutputTag2)); - DataflowAssert.that(outputs.get(sideOutputTag3)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs) - .fromSideOutput(sideOutputTag3)); - DataflowAssert.that(outputs.get(sideOutputTagUnwritten)).empty(); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoEmptyWithSideOutputs() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(); - - TupleTag mainOutputTag = new TupleTag("main"){}; - TupleTag sideOutputTag1 = new TupleTag("side1"){}; - TupleTag sideOutputTag2 = new TupleTag("side2"){}; - TupleTag sideOutputTag3 = new TupleTag("side3"){}; - TupleTag sideOutputTagUnwritten = new TupleTag("sideUnwritten"){}; - - PCollectionTuple outputs = pipeline - .apply(Create.of(inputs)) - .apply(ParDo - .of(new TestDoFn( - Arrays.>asList(), - Arrays.asList(sideOutputTag1, sideOutputTag2, sideOutputTag3))) - .withOutputTags( - mainOutputTag, - TupleTagList.of(sideOutputTag3).and(sideOutputTag1) - .and(sideOutputTagUnwritten).and(sideOutputTag2))); - - DataflowAssert.that(outputs.get(mainOutputTag)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs)); - - DataflowAssert.that(outputs.get(sideOutputTag1)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs) - .fromSideOutput(sideOutputTag1)); - DataflowAssert.that(outputs.get(sideOutputTag2)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs) - .fromSideOutput(sideOutputTag2)); - DataflowAssert.that(outputs.get(sideOutputTag3)) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs) - .fromSideOutput(sideOutputTag3)); - DataflowAssert.that(outputs.get(sideOutputTagUnwritten)).empty(); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoWithEmptySideOutputs() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(); - - TupleTag mainOutputTag = new TupleTag("main"){}; - TupleTag sideOutputTag1 = new TupleTag("side1"){}; - TupleTag sideOutputTag2 = new TupleTag("side2"){}; - - PCollectionTuple outputs = pipeline - .apply(Create.of(inputs)) - .apply(ParDo - .of(new TestNoOutputDoFn()) - .withOutputTags( - mainOutputTag, - TupleTagList.of(sideOutputTag1).and(sideOutputTag2))); - - DataflowAssert.that(outputs.get(mainOutputTag)).empty(); - - DataflowAssert.that(outputs.get(sideOutputTag1)).empty(); - DataflowAssert.that(outputs.get(sideOutputTag2)).empty(); - - pipeline.run(); - } - - - @Test - @Category(RunnableOnService.class) - public void testParDoWithOnlySideOutputs() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - final TupleTag mainOutputTag = new TupleTag("main"){}; - final TupleTag sideOutputTag = new TupleTag("side"){}; - - PCollectionTuple outputs = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag)) - .of(new DoFn(){ - @Override - public void processElement(ProcessContext c) { - c.sideOutput(sideOutputTag, c.element()); - }})); - - DataflowAssert.that(outputs.get(mainOutputTag)).empty(); - DataflowAssert.that(outputs.get(sideOutputTag)).containsInAnyOrder(inputs); - - pipeline.run(); - } - - @Test - public void testParDoWritingToUndeclaredSideOutput() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - TupleTag sideTag = new TupleTag("side"){}; - - PCollection output = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.of(new TestDoFn( - Arrays.>asList(), - Arrays.asList(sideTag)))); - - DataflowAssert.that(output) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs)); - - pipeline.run(); - } - - @Test - public void testParDoUndeclaredSideOutputLimit() { - Pipeline pipeline = TestPipeline.create(); - PCollection input = pipeline.apply(Create.of(Arrays.asList(3))); - - // Success for a total of 1000 outputs. - input - .apply("Success1000", ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - TupleTag specialSideTag = new TupleTag(){}; - c.sideOutput(specialSideTag, "side"); - c.sideOutput(specialSideTag, "side"); - c.sideOutput(specialSideTag, "side"); - - for (int i = 0; i < 998; i++) { - c.sideOutput(new TupleTag(){}, "side"); - } - }})); - pipeline.run(); - - // Failure for a total of 1001 outputs. - input - .apply("Failure1001", ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - for (int i = 0; i < 1000; i++) { - c.sideOutput(new TupleTag(){}, "side"); - } - }})); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("the number of side outputs has exceeded a limit"); - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoWithSideInputs() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - PCollectionView sideInput1 = pipeline - .apply("CreateSideInput1", Create.of(11)) - .apply("ViewSideInput1", View.asSingleton()); - PCollectionView sideInputUnread = pipeline - .apply("CreateSideInputUnread", Create.of(-3333)) - .apply("ViewSideInputUnread", View.asSingleton()); - PCollectionView sideInput2 = pipeline - .apply("CreateSideInput2", Create.of(222)) - .apply("ViewSideInput2", View.asSingleton()); - - PCollection output = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.withSideInputs(sideInput1, sideInputUnread, sideInput2) - .of(new TestDoFn( - Arrays.asList(sideInput1, sideInput2), - Arrays.>asList()))); - - DataflowAssert.that(output) - .satisfies(ParDoTest.HasExpectedOutput - .forInput(inputs) - .andSideInputs(11, 222)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoWithSideInputsIsCumulative() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - PCollectionView sideInput1 = pipeline - .apply("CreateSideInput1", Create.of(11)) - .apply("ViewSideInput1", View.asSingleton()); - PCollectionView sideInputUnread = pipeline - .apply("CreateSideInputUnread", Create.of(-3333)) - .apply("ViewSideInputUnread", View.asSingleton()); - PCollectionView sideInput2 = pipeline - .apply("CreateSideInput2", Create.of(222)) - .apply("ViewSideInput2", View.asSingleton()); - - PCollection output = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.withSideInputs(sideInput1) - .withSideInputs(sideInputUnread) - .withSideInputs(sideInput2) - .of(new TestDoFn( - Arrays.asList(sideInput1, sideInput2), - Arrays.>asList()))); - - DataflowAssert.that(output) - .satisfies(ParDoTest.HasExpectedOutput - .forInput(inputs) - .andSideInputs(11, 222)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMultiOutputParDoWithSideInputs() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - final TupleTag mainOutputTag = new TupleTag("main"){}; - final TupleTag sideOutputTag = new TupleTag("sideOutput"){}; - - PCollectionView sideInput1 = pipeline - .apply("CreateSideInput1", Create.of(11)) - .apply("ViewSideInput1", View.asSingleton()); - PCollectionView sideInputUnread = pipeline - .apply("CreateSideInputUnread", Create.of(-3333)) - .apply("ViewSideInputUnread", View.asSingleton()); - PCollectionView sideInput2 = pipeline - .apply("CreateSideInput2", Create.of(222)) - .apply("ViewSideInput2", View.asSingleton()); - - PCollectionTuple outputs = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.withSideInputs(sideInput1) - .withSideInputs(sideInputUnread) - .withSideInputs(sideInput2) - .withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag)) - .of(new TestDoFn( - Arrays.asList(sideInput1, sideInput2), - Arrays.>asList()))); - - DataflowAssert.that(outputs.get(mainOutputTag)) - .satisfies(ParDoTest.HasExpectedOutput - .forInput(inputs) - .andSideInputs(11, 222)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMultiOutputParDoWithSideInputsIsCumulative() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - final TupleTag mainOutputTag = new TupleTag("main"){}; - final TupleTag sideOutputTag = new TupleTag("sideOutput"){}; - - PCollectionView sideInput1 = pipeline - .apply("CreateSideInput1", Create.of(11)) - .apply("ViewSideInput1", View.asSingleton()); - PCollectionView sideInputUnread = pipeline - .apply("CreateSideInputUnread", Create.of(-3333)) - .apply("ViewSideInputUnread", View.asSingleton()); - PCollectionView sideInput2 = pipeline - .apply("CreateSideInput2", Create.of(222)) - .apply("ViewSideInput2", View.asSingleton()); - - PCollectionTuple outputs = pipeline - .apply(Create.of(inputs)) - .apply(ParDo.withSideInputs(sideInput1) - .withSideInputs(sideInputUnread) - .withSideInputs(sideInput2) - .withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag)) - .of(new TestDoFn( - Arrays.asList(sideInput1, sideInput2), - Arrays.>asList()))); - - DataflowAssert.that(outputs.get(mainOutputTag)) - .satisfies(ParDoTest.HasExpectedOutput - .forInput(inputs) - .andSideInputs(11, 222)); - - pipeline.run(); - } - - @Test - public void testParDoReadingFromUnknownSideInput() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - PCollectionView sideView = pipeline - .apply("Create3", Create.of(3)) - .apply(View.asSingleton()); - - pipeline.apply("CreateMain", Create.of(inputs)) - .apply(ParDo.of(new TestDoFn( - Arrays.>asList(sideView), - Arrays.>asList()))); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("calling sideInput() with unknown view"); - pipeline.run(); - } - - @Test - public void testParDoWithErrorInStartBatch() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - pipeline.apply(Create.of(inputs)) - .apply(ParDo.of(new TestStartBatchErrorDoFn())); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("test error in initialize"); - pipeline.run(); - } - - @Test - public void testParDoWithErrorInProcessElement() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - pipeline.apply(Create.of(inputs)) - .apply(ParDo.of(new TestProcessElementErrorDoFn())); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("test error in process"); - pipeline.run(); - } - - @Test - public void testParDoWithErrorInFinishBatch() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - pipeline.apply(Create.of(inputs)) - .apply(ParDo.of(new TestFinishBatchErrorDoFn())); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("test error in finalize"); - pipeline.run(); - } - - @Test - public void testParDoGetName() { - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(Arrays.asList(3, -42, 666))) - .setName("MyInput"); - - { - PCollection output1 = - input - .apply(ParDo.of(new TestDoFn())); - assertEquals("ParDo(Test).out", output1.getName()); - } - - { - PCollection output2 = - input - .apply(ParDo.named("MyParDo").of(new TestDoFn())); - assertEquals("MyParDo.out", output2.getName()); - } - - { - PCollection output3 = - input - .apply(ParDo.of(new TestDoFn()).named("HerParDo")); - assertEquals("HerParDo.out", output3.getName()); - } - - { - PCollection output4 = - input - .apply(ParDo.of(new TestDoFn()).named("TestDoFn")); - assertEquals("TestDoFn.out", output4.getName()); - } - - { - PCollection output5 = - input - .apply(ParDo.of(new StrangelyNamedDoer())); - assertEquals("ParDo(StrangelyNamedDoer).out", - output5.getName()); - } - - assertEquals("ParDo(Printing)", ParDo.of(new PrintingDoFn()).getName()); - - assertEquals( - "ParMultiDo(SideOutputDummy)", - ParDo.of(new SideOutputDummyFn(null)).withOutputTags(null, null).getName()); - } - - @Test - public void testParDoWithSideOutputsName() { - Pipeline p = TestPipeline.create(); - - TupleTag mainOutputTag = new TupleTag("main"){}; - TupleTag sideOutputTag1 = new TupleTag("side1"){}; - TupleTag sideOutputTag2 = new TupleTag("side2"){}; - TupleTag sideOutputTag3 = new TupleTag("side3"){}; - TupleTag sideOutputTagUnwritten = new TupleTag("sideUnwritten"){}; - - PCollectionTuple outputs = p - .apply(Create.of(Arrays.asList(3, -42, 666))).setName("MyInput") - .apply(ParDo - .named("MyParDo") - .of(new TestDoFn( - Arrays.>asList(), - Arrays.asList(sideOutputTag1, sideOutputTag2, sideOutputTag3))) - .withOutputTags( - mainOutputTag, - TupleTagList.of(sideOutputTag3).and(sideOutputTag1) - .and(sideOutputTagUnwritten).and(sideOutputTag2))); - - assertEquals("MyParDo.main", outputs.get(mainOutputTag).getName()); - assertEquals("MyParDo.side1", outputs.get(sideOutputTag1).getName()); - assertEquals("MyParDo.side2", outputs.get(sideOutputTag2).getName()); - assertEquals("MyParDo.side3", outputs.get(sideOutputTag3).getName()); - assertEquals("MyParDo.sideUnwritten", - outputs.get(sideOutputTagUnwritten).getName()); - } - - @Test - @Category(RunnableOnService.class) - public void testParDoInCustomTransform() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - PCollection output = pipeline - .apply(Create.of(inputs)) - .apply("CustomTransform", new PTransform, PCollection>() { - @Override - public PCollection apply(PCollection input) { - return input.apply(ParDo.of(new TestDoFn())); - } - }); - - // Test that Coder inference of the result works through - // user-defined PTransforms. - DataflowAssert.that(output) - .satisfies(ParDoTest.HasExpectedOutput.forInput(inputs)); - - pipeline.run(); - } - - @Test - public void testMultiOutputChaining() { - Pipeline pipeline = TestPipeline.create(); - - PCollectionTuple filters = pipeline - .apply(Create.of(Arrays.asList(3, 4, 5, 6))) - .apply(new MultiFilter()); - PCollection by2 = filters.get(MultiFilter.BY2); - PCollection by3 = filters.get(MultiFilter.BY3); - - // Apply additional filters to each operation. - PCollection by2then3 = by2 - .apply("Filter3sAgain", ParDo.of(new MultiFilter.FilterFn(3))); - PCollection by3then2 = by3 - .apply("Filter2sAgain", ParDo.of(new MultiFilter.FilterFn(2))); - - DataflowAssert.that(by2then3).containsInAnyOrder(6); - DataflowAssert.that(by3then2).containsInAnyOrder(6); - pipeline.run(); - } - - @Test - public void testJsonEscaping() { - // Declare an arbitrary function and make sure we can serialize it - DoFn doFn = new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + 1); - } - }; - - byte[] serializedBytes = serializeToByteArray(doFn); - String serializedJson = byteArrayToJsonString(serializedBytes); - assertArrayEquals( - serializedBytes, jsonStringToByteArray(serializedJson)); - } - - private static class TestDummy { } - - private static class TestDummyCoder extends AtomicCoder { - private TestDummyCoder() { } - private static final TestDummyCoder INSTANCE = new TestDummyCoder(); - - @JsonCreator - public static TestDummyCoder of() { - return INSTANCE; - } - - @SuppressWarnings("unused") // used to create a CoderFactory - public static List getInstanceComponents(TestDummy exampleValue) { - return Collections.emptyList(); - } - - @Override - public void encode(TestDummy value, OutputStream outStream, Context context) - throws CoderException, IOException { - } - - @Override - public TestDummy decode(InputStream inStream, Context context) - throws CoderException, IOException { - return new TestDummy(); - } - - @Override - public boolean isRegisterByteSizeObserverCheap(TestDummy value, Context context) { - return true; - } - - @Override - public void registerByteSizeObserver( - TestDummy value, ElementByteSizeObserver observer, Context context) - throws Exception { - observer.update(0L); - } - } - - private static class SideOutputDummyFn extends DoFn { - private TupleTag sideTag; - public SideOutputDummyFn(TupleTag sideTag) { - this.sideTag = sideTag; - } - @Override - public void processElement(ProcessContext c) { - c.output(1); - c.sideOutput(sideTag, new TestDummy()); - } - } - - private static class MainOutputDummyFn extends DoFn { - private TupleTag sideTag; - public MainOutputDummyFn(TupleTag sideTag) { - this.sideTag = sideTag; - } - @Override - public void processElement(ProcessContext c) { - c.output(new TestDummy()); - c.sideOutput(sideTag, 1); - } - } - - /** DataflowAssert "matcher" for expected output. */ - static class HasExpectedOutput - implements SerializableFunction, Void>, Serializable { - private final List inputs; - private final List sideInputs; - private final String sideOutput; - private final boolean ordered; - - public static HasExpectedOutput forInput(List inputs) { - return new HasExpectedOutput( - new ArrayList(inputs), - new ArrayList(), - "", - false); - } - - private HasExpectedOutput(List inputs, - List sideInputs, - String sideOutput, - boolean ordered) { - this.inputs = inputs; - this.sideInputs = sideInputs; - this.sideOutput = sideOutput; - this.ordered = ordered; - } - - public HasExpectedOutput andSideInputs(Integer... sideInputValues) { - List sideInputs = new ArrayList<>(); - for (Integer sideInputValue : sideInputValues) { - sideInputs.add(sideInputValue); - } - return new HasExpectedOutput(inputs, sideInputs, sideOutput, ordered); - } - - public HasExpectedOutput fromSideOutput(TupleTag sideOutputTag) { - return fromSideOutput(sideOutputTag.getId()); - } - public HasExpectedOutput fromSideOutput(String sideOutput) { - return new HasExpectedOutput(inputs, sideInputs, sideOutput, ordered); - } - - public HasExpectedOutput inOrder() { - return new HasExpectedOutput(inputs, sideInputs, sideOutput, true); - } - - @Override - public Void apply(Iterable outputs) { - List starteds = new ArrayList<>(); - List processeds = new ArrayList<>(); - List finisheds = new ArrayList<>(); - for (String output : outputs) { - if (output.contains("started")) { - starteds.add(output); - } else if (output.contains("finished")) { - finisheds.add(output); - } else { - processeds.add(output); - } - } - - String sideInputsSuffix; - if (sideInputs.isEmpty()) { - sideInputsSuffix = ""; - } else { - sideInputsSuffix = ": " + sideInputs; - } - - String sideOutputPrefix; - if (sideOutput.isEmpty()) { - sideOutputPrefix = ""; - } else { - sideOutputPrefix = sideOutput + ": "; - } - - List expectedProcesseds = new ArrayList<>(); - for (Integer input : inputs) { - expectedProcesseds.add( - sideOutputPrefix + "processing: " + input + sideInputsSuffix); - } - String[] expectedProcessedsArray = - expectedProcesseds.toArray(new String[expectedProcesseds.size()]); - if (!ordered || expectedProcesseds.isEmpty()) { - assertThat(processeds, containsInAnyOrder(expectedProcessedsArray)); - } else { - assertThat(processeds, contains(expectedProcessedsArray)); - } - - assertEquals(starteds.size(), finisheds.size()); - for (String started : starteds) { - assertEquals(sideOutputPrefix + "started", started); - } - for (String finished : finisheds) { - assertEquals(sideOutputPrefix + "finished", finished); - } - - return null; - } - } - - @Test - public void testSideOutputUnknownCoder() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection input = pipeline - .apply(Create.of(Arrays.asList(1, 2, 3))); - - final TupleTag mainOutputTag = new TupleTag("main"); - final TupleTag sideOutputTag = new TupleTag("unknownSide"); - input.apply(ParDo.of(new SideOutputDummyFn(sideOutputTag)) - .withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag))); - - thrown.expect(PipelineExecutionException.class); - thrown.expectMessage("Unable to return a default Coder"); - pipeline.run(); - } - - @Test - public void testSideOutputUnregisteredExplicitCoder() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection input = pipeline - .apply(Create.of(Arrays.asList(1, 2, 3))); - - final TupleTag mainOutputTag = new TupleTag("main"); - final TupleTag sideOutputTag = new TupleTag("unregisteredSide"); - PCollectionTuple outputTuple = input.apply(ParDo.of(new SideOutputDummyFn(sideOutputTag)) - .withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag))); - - outputTuple.get(sideOutputTag).setCoder(new TestDummyCoder()); - - outputTuple.get(sideOutputTag).apply(View.asSingleton()); - - assertEquals(new TestDummyCoder(), outputTuple.get(sideOutputTag).getCoder()); - outputTuple.get(sideOutputTag).finishSpecifyingOutput(); // Check for crashes - assertEquals(new TestDummyCoder(), - outputTuple.get(sideOutputTag).getCoder()); // Check for corruption - pipeline.run(); - } - - @Test - public void testMainOutputUnregisteredExplicitCoder() { - Pipeline pipeline = TestPipeline.create(); - PCollection input = pipeline - .apply(Create.of(Arrays.asList(1, 2, 3))); - - final TupleTag mainOutputTag = new TupleTag("unregisteredMain"); - final TupleTag sideOutputTag = new TupleTag("side") {}; - PCollectionTuple outputTuple = input.apply(ParDo.of(new MainOutputDummyFn(sideOutputTag)) - .withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag))); - - outputTuple.get(mainOutputTag).setCoder(new TestDummyCoder()); - - pipeline.run(); - } - - @Test - public void testMainOutputApplySideOutputNoCoder() { - // Regression test: applying a transform to the main output - // should not cause a crash based on lack of a coder for the - // side output. - - Pipeline pipeline = TestPipeline.create(); - final TupleTag mainOutputTag = new TupleTag("main"); - final TupleTag sideOutputTag = new TupleTag("side"); - PCollectionTuple tuple = pipeline - .apply(Create.of(new TestDummy()) - .withCoder(TestDummyCoder.of())) - .apply(ParDo - .withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag)) - .of( - new DoFn() { - @Override public void processElement(ProcessContext context) { - TestDummy element = context.element(); - context.output(element); - context.sideOutput(sideOutputTag, element); - } - }) - ); - - // Before fix, tuple.get(mainOutputTag).apply(...) would indirectly trigger - // tuple.get(sideOutputTag).finishSpecifyingOutput(), which would crash - // on a missing coder. - tuple.get(mainOutputTag) - .setCoder(TestDummyCoder.of()) - .apply("Output1", ParDo.of(new DoFn() { - @Override public void processElement(ProcessContext context) { - context.output(1); - } - })); - - tuple.get(sideOutputTag).setCoder(TestDummyCoder.of()); - - pipeline.run(); - } - - @Test - public void testParDoOutputWithTimestamp() { - Pipeline pipeline = TestPipeline.create(); - - PCollection input = - pipeline.apply(Create.of(Arrays.asList(3, 42, 6))); - - PCollection output = - input - .apply(ParDo.of(new TestOutputTimestampDoFn())) - .apply(ParDo.of(new TestShiftTimestampDoFn(Duration.ZERO, Duration.ZERO))) - .apply(ParDo.of(new TestFormatTimestampDoFn())); - - DataflowAssert.that(output).containsInAnyOrder( - "processing: 3, timestamp: 3", - "processing: 42, timestamp: 42", - "processing: 6, timestamp: 6"); - - pipeline.run(); - } - - @Test - public void testParDoSideOutputWithTimestamp() { - Pipeline pipeline = TestPipeline.create(); - - PCollection input = - pipeline.apply(Create.of(Arrays.asList(3, 42, 6))); - - final TupleTag mainOutputTag = new TupleTag("main"){}; - final TupleTag sideOutputTag = new TupleTag("side"){}; - - PCollection output = - input - .apply(ParDo.withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag)).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.sideOutputWithTimestamp( - sideOutputTag, c.element(), new Instant(c.element().longValue())); - } - })).get(sideOutputTag) - .apply(ParDo.of(new TestShiftTimestampDoFn(Duration.ZERO, Duration.ZERO))) - .apply(ParDo.of(new TestFormatTimestampDoFn())); - - DataflowAssert.that(output).containsInAnyOrder( - "processing: 3, timestamp: 3", - "processing: 42, timestamp: 42", - "processing: 6, timestamp: 6"); - - pipeline.run(); - } - - @Test - public void testParDoShiftTimestamp() { - Pipeline pipeline = TestPipeline.create(); - - PCollection input = - pipeline.apply(Create.of(Arrays.asList(3, 42, 6))); - - PCollection output = - input - .apply(ParDo.of(new TestOutputTimestampDoFn())) - .apply(ParDo.of(new TestShiftTimestampDoFn(Duration.millis(1000), - Duration.millis(-1000)))) - .apply(ParDo.of(new TestFormatTimestampDoFn())); - - DataflowAssert.that(output).containsInAnyOrder( - "processing: 3, timestamp: -997", - "processing: 42, timestamp: -958", - "processing: 6, timestamp: -994"); - - pipeline.run(); - } - - @Test - public void testParDoShiftTimestampInvalid() { - Pipeline pipeline = TestPipeline.create(); - - pipeline.apply(Create.of(Arrays.asList(3, 42, 6))) - .apply(ParDo.of(new TestOutputTimestampDoFn())) - .apply(ParDo.of(new TestShiftTimestampDoFn(Duration.millis(1000), // allowed skew = 1 second - Duration.millis(-1001)))) - .apply(ParDo.of(new TestFormatTimestampDoFn())); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("Cannot output with timestamp"); - thrown.expectMessage( - "Output timestamps must be no earlier than the timestamp of the current input"); - thrown.expectMessage("minus the allowed skew (1 second)."); - pipeline.run(); - } - - @Test - public void testParDoShiftTimestampInvalidZeroAllowed() { - Pipeline pipeline = TestPipeline.create(); - - pipeline.apply(Create.of(Arrays.asList(3, 42, 6))) - .apply(ParDo.of(new TestOutputTimestampDoFn())) - .apply(ParDo.of(new TestShiftTimestampDoFn(Duration.ZERO, - Duration.millis(-1001)))) - .apply(ParDo.of(new TestFormatTimestampDoFn())); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("Cannot output with timestamp"); - thrown.expectMessage( - "Output timestamps must be no earlier than the timestamp of the current input"); - thrown.expectMessage("minus the allowed skew (0 milliseconds)."); - pipeline.run(); - } - - private static class Checker implements SerializableFunction, Void> { - @Override - public Void apply(Iterable input) { - boolean foundStart = false; - boolean foundElement = false; - boolean foundFinish = false; - for (String str : input) { - if (str.equals("elem:1:1")) { - if (foundElement) { - throw new AssertionError("Received duplicate element"); - } - foundElement = true; - } else if (str.equals("start:2:2")) { - foundStart = true; - } else if (str.equals("finish:3:3")) { - foundFinish = true; - } else { - throw new AssertionError("Got unexpected value: " + str); - } - } - if (!foundStart) { - throw new AssertionError("Missing \"start:2:2\""); - } - if (!foundElement) { - throw new AssertionError("Missing \"elem:1:1\""); - } - if (!foundFinish) { - throw new AssertionError("Missing \"finish:3:3\""); - } - - return null; - } - } - - @Test - @Category(RunnableOnService.class) - public void testWindowingInStartAndFinishBundle() { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.timestamped(TimestampedValue.of("elem", new Instant(1)))) - .apply(Window.into(FixedWindows.of(Duration.millis(1)))) - .apply(ParDo.of(new DoFn() { - @Override - public void startBundle(Context c) { - c.outputWithTimestamp("start", new Instant(2)); - System.out.println("Start: 2"); - } - - @Override - public void processElement(ProcessContext c) { - c.output(c.element()); - System.out.println("Process: " + c.element() + ":" + c.timestamp().getMillis()); - } - - @Override - public void finishBundle(Context c) { - c.outputWithTimestamp("finish", new Instant(3)); - System.out.println("Finish: 3"); - } - })) - .apply(ParDo.of(new PrintingDoFn())); - - DataflowAssert.that(output).satisfies(new Checker()); - - pipeline.run(); - } - - @Test - public void testWindowingInStartBundleException() { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.timestamped(TimestampedValue.of("elem", new Instant(1)))) - .apply(Window.into(FixedWindows.of(Duration.millis(1)))) - .apply(ParDo.of(new DoFn() { - @Override - public void startBundle(Context c) { - c.output("start"); - } - - @Override - public void processElement(ProcessContext c) { - c.output(c.element()); - } - })); - - thrown.expectMessage("WindowFn attempted to access input timestamp when none was available"); - pipeline.run(); - } - - /** - * Tests that a {@link DoFn} that mutates an output with a good equals() fails in the - * {@link DirectPipelineRunner}. - */ - @Test - public void testMutatingOutputThenOutputDoFnError() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of(42)) - .apply(ParDo.of(new DoFn>() { - @Override public void processElement(ProcessContext c) { - List outputList = Arrays.asList(1, 2, 3, 4); - c.output(outputList); - outputList.set(0, 37); - c.output(outputList); - } - })); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalMutationException.class)); - thrown.expectMessage("output"); - thrown.expectMessage("must not be mutated"); - pipeline.run(); - } - - /** - * Tests that a {@link DoFn} that mutates an output with a good equals() fails in the - * {@link DirectPipelineRunner}. - */ - @Test - public void testMutatingOutputThenTerminateDoFnError() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of(42)) - .apply(ParDo.of(new DoFn>() { - @Override public void processElement(ProcessContext c) { - List outputList = Arrays.asList(1, 2, 3, 4); - c.output(outputList); - outputList.set(0, 37); - } - })); - - thrown.expect(IllegalMutationException.class); - thrown.expectMessage("output"); - thrown.expectMessage("must not be mutated"); - pipeline.run(); - } - - /** - * Tests that a {@link DoFn} that mutates an output with a bad equals() still fails - * in the {@link DirectPipelineRunner}. - */ - @Test - public void testMutatingOutputCoderDoFnError() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of(42)) - .apply(ParDo.of(new DoFn() { - @Override public void processElement(ProcessContext c) { - byte[] outputArray = new byte[]{0x1, 0x2, 0x3}; - c.output(outputArray); - outputArray[0] = 0xa; - c.output(outputArray); - } - })); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalMutationException.class)); - thrown.expectMessage("output"); - thrown.expectMessage("must not be mutated"); - pipeline.run(); - } - - /** - * Tests that a {@link DoFn} that mutates its input with a good equals() fails in the - * {@link DirectPipelineRunner}. - */ - @Test - public void testMutatingInputDoFnError() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6)) - .withCoder(ListCoder.of(VarIntCoder.of()))) - .apply(ParDo.of(new DoFn, Integer>() { - @Override public void processElement(ProcessContext c) { - List inputList = c.element(); - inputList.set(0, 37); - c.output(12); - } - })); - - thrown.expect(IllegalMutationException.class); - thrown.expectMessage("input"); - thrown.expectMessage("must not be mutated"); - pipeline.run(); - } - - /** - * Tests that a {@link DoFn} that mutates an input with a bad equals() still fails - * in the {@link DirectPipelineRunner}. - */ - @Test - public void testMutatingInputCoderDoFnError() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of(new byte[]{0x1, 0x2, 0x3}, new byte[]{0x4, 0x5, 0x6})) - .apply(ParDo.of(new DoFn() { - @Override public void processElement(ProcessContext c) { - byte[] inputArray = c.element(); - inputArray[0] = 0xa; - c.output(13); - } - })); - - thrown.expect(IllegalMutationException.class); - thrown.expectMessage("input"); - thrown.expectMessage("must not be mutated"); - pipeline.run(); - } - - @Test - public void testDoFnDisplayData() { - DoFn fn = new DoFn() { - @Override - public void processElement(ProcessContext c) { - } - - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("doFnMetadata", "bar")); - } - }; - - Bound parDo = ParDo.of(fn); - - DisplayData displayData = DisplayData.from(parDo); - assertThat(displayData, hasDisplayItem(allOf( - hasKey("fn"), - hasType(DisplayData.Type.JAVA_CLASS), - DisplayDataMatchers.hasValue(fn.getClass().getName())))); - - assertThat(displayData, includesDisplayDataFrom(fn)); - } - - @Test - public void testDoFnWithContextDisplayData() { - DoFnWithContext fn = new DoFnWithContext() { - @ProcessElement - public void proccessElement(ProcessContext c) {} - - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("fnMetadata", "foobar")); - } - }; - - Bound parDo = ParDo.of(fn); - - DisplayData displayData = DisplayData.from(parDo); - assertThat(displayData, includesDisplayDataFrom(fn)); - assertThat(displayData, hasDisplayItem("fn", fn.getClass())); - } - - @Test - public void testWithOutputTagsDisplayData() { - DoFnWithContext fn = new DoFnWithContext() { - @ProcessElement - public void proccessElement(ProcessContext c) {} - - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("fnMetadata", "foobar")); - } - }; - - ParDo.BoundMulti parDo = ParDo - .withOutputTags(new TupleTag(), TupleTagList.empty()) - .of(fn); - - DisplayData displayData = DisplayData.from(parDo); - assertThat(displayData, includesDisplayDataFrom(fn)); - assertThat(displayData, hasDisplayItem("fn", fn.getClass())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java deleted file mode 100644 index c24b3690c8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/PartitionTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Partition.PartitionFn; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for {@link Partition}. - */ -@RunWith(JUnit4.class) -public class PartitionTest implements Serializable { - - @Rule public transient ExpectedException thrown = ExpectedException.none(); - - static class ModFn implements PartitionFn { - @Override - public int partitionFor(Integer elem, int numPartitions) { - return elem % numPartitions; - } - } - - static class IdentityFn implements PartitionFn { - @Override - public int partitionFor(Integer elem, int numPartitions) { - return elem; - } - } - - @Test - @Category(RunnableOnService.class) - public void testEvenOddPartition() { - Pipeline pipeline = TestPipeline.create(); - - PCollectionList outputs = pipeline - .apply(Create.of(591, 11789, 1257, 24578, 24799, 307)) - .apply(Partition.of(2, new ModFn())); - assertTrue(outputs.size() == 2); - DataflowAssert.that(outputs.get(0)).containsInAnyOrder(24578); - DataflowAssert.that(outputs.get(1)).containsInAnyOrder(591, 11789, 1257, - 24799, 307); - pipeline.run(); - } - - @Test - public void testModPartition() { - Pipeline pipeline = TestPipeline.create(); - - PCollectionList outputs = pipeline - .apply(Create.of(1, 2, 4, 5)) - .apply(Partition.of(3, new ModFn())); - assertTrue(outputs.size() == 3); - DataflowAssert.that(outputs.get(0)).empty(); - DataflowAssert.that(outputs.get(1)).containsInAnyOrder(1, 4); - DataflowAssert.that(outputs.get(2)).containsInAnyOrder(2, 5); - pipeline.run(); - } - - @Test - public void testOutOfBoundsPartitions() { - Pipeline pipeline = TestPipeline.create(); - - pipeline - .apply(Create.of(-1)) - .apply(Partition.of(5, new IdentityFn())); - - thrown.expect(RuntimeException.class); - thrown.expectMessage( - "Partition function returned out of bounds index: -1 not in [0..5)"); - pipeline.run(); - } - - @Test - public void testZeroNumPartitions() { - Pipeline pipeline = TestPipeline.create(); - - PCollection input = pipeline.apply(Create.of(591)); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("numPartitions must be > 0"); - input.apply(Partition.of(0, new IdentityFn())); - } - - @Test - public void testDroppedPartition() { - Pipeline pipeline = TestPipeline.create(); - - // Compute the set of integers either 1 or 2 mod 3, the hard way. - PCollectionList outputs = pipeline - .apply(Create.of(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) - .apply(Partition.of(3, new ModFn())); - - List> outputsList = new ArrayList<>(outputs.getAll()); - outputsList.remove(0); - outputs = PCollectionList.of(outputsList); - assertTrue(outputs.size() == 2); - - PCollection output = outputs.apply(Flatten.pCollections()); - DataflowAssert.that(output).containsInAnyOrder(2, 4, 5, 7, 8, 10, 11); - pipeline.run(); - } - - @Test - public void testPartitionGetName() { - assertEquals("Partition", Partition.of(3, new ModFn()).getName()); - } - - @Test - public void testDisplayData() { - Partition partition = Partition.of(123, new IdentityFn()); - DisplayData displayData = DisplayData.from(partition); - - assertThat(displayData, hasDisplayItem("numPartitions", 123)); - assertThat(displayData, hasDisplayItem("partitionFn", IdentityFn.class)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesTest.java deleted file mode 100644 index a6fe7e82a1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Tests for RemovedDuplicates. - */ -@RunWith(JUnit4.class) -public class RemoveDuplicatesTest { - @Test - @Category(RunnableOnService.class) - public void testRemoveDuplicates() { - List strings = Arrays.asList( - "k1", - "k5", - "k5", - "k2", - "k1", - "k2", - "k3"); - - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(strings) - .withCoder(StringUtf8Coder.of())); - - PCollection output = - input.apply(RemoveDuplicates.create()); - - DataflowAssert.that(output) - .containsInAnyOrder("k1", "k5", "k2", "k3"); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testRemoveDuplicatesEmpty() { - List strings = Arrays.asList(); - - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(strings) - .withCoder(StringUtf8Coder.of())); - - PCollection output = - input.apply(RemoveDuplicates.create()); - - DataflowAssert.that(output).empty(); - p.run(); - } - - private static class Keys implements SerializableFunction, String> { - @Override - public String apply(KV input) { - return input.getKey(); - } - } - - private static class Checker implements SerializableFunction>, Void> { - @Override - public Void apply(Iterable> input) { - Map values = new HashMap<>(); - for (KV kv : input) { - values.put(kv.getKey(), kv.getValue()); - } - assertEquals(2, values.size()); - assertTrue(values.get("k1").equals("v1") || values.get("k1").equals("v2")); - assertEquals("v1", values.get("k2")); - return null; - } - } - - - @Test - @Category(RunnableOnService.class) - public void testRemoveDuplicatesWithRepresentativeValue() { - List> strings = Arrays.asList( - KV.of("k1", "v1"), - KV.of("k1", "v2"), - KV.of("k2", "v1")); - - Pipeline p = TestPipeline.create(); - - PCollection> input = p.apply(Create.of(strings)); - - PCollection> output = - input.apply(RemoveDuplicates.withRepresentativeValueFn(new Keys())); - - - DataflowAssert.that(output).satisfies(new Checker()); - - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java deleted file mode 100644 index 0b2d15d352..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SampleTest.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.LINES; -import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.common.base.Preconditions.checkArgument; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Joiner; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -/** - * Tests for Sample transform. - */ -@RunWith(JUnit4.class) -public class SampleTest { - static final Integer[] EMPTY = new Integer[] { }; - static final Integer[] DATA = new Integer[] {1, 2, 3, 4, 5}; - static final Integer[] REPEATED_DATA = new Integer[] {1, 1, 2, 2, 3, 3, 4, 4, 5, 5}; - - /** - * Verifies that the result of a Sample operation contains the expected number of elements, - * and that those elements are a subset of the items in expected. - */ - @SuppressWarnings("rawtypes") - public static class VerifyCorrectSample - implements SerializableFunction, Void> { - private T[] expectedValues; - private int expectedSize; - - /** - * expectedSize is the number of elements that the Sample should contain. expected is the set - * of elements that the sample may contain. - */ - @SafeVarargs - VerifyCorrectSample(int expectedSize, T... expected) { - this.expectedValues = expected; - this.expectedSize = expectedSize; - } - - @Override - @SuppressWarnings("unchecked") - public Void apply(Iterable in) { - List actual = new ArrayList<>(); - for (T elem : in) { - actual.add(elem); - } - - assertEquals(expectedSize, actual.size()); - - Collections.sort(actual); // We assume that @expected is already sorted. - int i = 0; // Index into @expected - for (T s : actual) { - boolean matchFound = false; - for (; i < expectedValues.length; i++) { - if (s.equals(expectedValues[i])) { - matchFound = true; - break; - } - } - assertTrue("Invalid sample: " + Joiner.on(',').join(actual), matchFound); - i++; // Don't match the same element again. - } - return null; - } - } - - @Test - @Category(RunnableOnService.class) - public void testSample() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(DATA) - .withCoder(BigEndianIntegerCoder.of())); - PCollection> output = input.apply( - Sample.fixedSizeGlobally(3)); - - DataflowAssert.thatSingletonIterable(output) - .satisfies(new VerifyCorrectSample<>(3, DATA)); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testSampleEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(EMPTY) - .withCoder(BigEndianIntegerCoder.of())); - PCollection> output = input.apply( - Sample.fixedSizeGlobally(3)); - - DataflowAssert.thatSingletonIterable(output) - .satisfies(new VerifyCorrectSample<>(0, EMPTY)); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testSampleZero() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(DATA) - .withCoder(BigEndianIntegerCoder.of())); - PCollection> output = input.apply( - Sample.fixedSizeGlobally(0)); - - DataflowAssert.thatSingletonIterable(output) - .satisfies(new VerifyCorrectSample<>(0, DATA)); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testSampleInsufficientElements() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(DATA) - .withCoder(BigEndianIntegerCoder.of())); - PCollection> output = input.apply( - Sample.fixedSizeGlobally(10)); - - DataflowAssert.thatSingletonIterable(output) - .satisfies(new VerifyCorrectSample<>(5, DATA)); - p.run(); - } - - @Test(expected = IllegalArgumentException.class) - public void testSampleNegative() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(DATA) - .withCoder(BigEndianIntegerCoder.of())); - input.apply(Sample.fixedSizeGlobally(-1)); - } - - @Test - @Category(RunnableOnService.class) - public void testSampleMultiplicity() { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(REPEATED_DATA) - .withCoder(BigEndianIntegerCoder.of())); - // At least one value must be selected with multiplicity. - PCollection> output = input.apply( - Sample.fixedSizeGlobally(6)); - - DataflowAssert.thatSingletonIterable(output) - .satisfies(new VerifyCorrectSample<>(6, REPEATED_DATA)); - p.run(); - } - - private static class VerifyAnySample implements SerializableFunction, Void> { - private final List lines; - private final int limit; - private VerifyAnySample(List lines, int limit) { - this.lines = lines; - this.limit = limit; - } - - @Override - public Void apply(Iterable actualIter) { - final int expectedSize = Math.min(limit, lines.size()); - - // Make sure actual is the right length, and is a - // subset of expected. - List actual = new ArrayList<>(); - for (String s : actualIter) { - actual.add(s); - } - assertEquals(expectedSize, actual.size()); - Set actualAsSet = new TreeSet<>(actual); - Set linesAsSet = new TreeSet<>(lines); - assertEquals(actual.size(), actualAsSet.size()); - assertEquals(lines.size(), linesAsSet.size()); - assertTrue(linesAsSet.containsAll(actualAsSet)); - return null; - } - } - - void runPickAnyTest(final List lines, int limit) { - checkArgument(new HashSet(lines).size() == lines.size(), "Duplicates are unsupported."); - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(lines) - .withCoder(StringUtf8Coder.of())); - - PCollection output = - input.apply(Sample.any(limit)); - - - DataflowAssert.that(output) - .satisfies(new VerifyAnySample(lines, limit)); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testPickAny() { - runPickAnyTest(LINES, 0); - runPickAnyTest(LINES, LINES.size() / 2); - runPickAnyTest(LINES, LINES.size() * 2); - } - - @Test - // Extra tests, not worth the time to run on the real service. - public void testPickAnyMore() { - runPickAnyTest(LINES, LINES.size() - 1); - runPickAnyTest(LINES, LINES.size()); - runPickAnyTest(LINES, LINES.size() + 1); - } - - @Test - @Category(RunnableOnService.class) - public void testPickAnyWhenEmpty() { - runPickAnyTest(NO_LINES, 0); - runPickAnyTest(NO_LINES, 1); - } - - @Test - public void testSampleGetName() { - assertEquals("Sample.SampleAny", Sample.any(1).getName()); - } - - @Test - public void testDisplayData() { - PTransform sampleAny = Sample.any(1234); - DisplayData sampleAnyDisplayData = DisplayData.from(sampleAny); - assertThat(sampleAnyDisplayData, hasDisplayItem("sampleSize", 1234)); - - PTransform samplePerKey = Sample.fixedSizePerKey(2345); - DisplayData perKeyDisplayData = DisplayData.from(samplePerKey); - assertThat(perKeyDisplayData, hasDisplayItem("sampleSize", 2345)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SimpleStatsFnsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SimpleStatsFnsTest.java deleted file mode 100644 index 914f95dc2e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SimpleStatsFnsTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.junit.Assert.assertEquals; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Tests of Min, Max, Mean, and Sum. - */ -@RunWith(JUnit4.class) -public class SimpleStatsFnsTest { - static final double DOUBLE_COMPARISON_ACCURACY = 1e-7; - - private static class TestCase> { - final List data; - final NumT min; - final NumT max; - final NumT sum; - final Double mean; - - @SafeVarargs - @SuppressWarnings("all") - public TestCase(NumT min, NumT max, NumT sum, NumT... values) { - this.data = Arrays.asList(values); - this.min = min; - this.max = max; - this.sum = sum; - this.mean = - values.length == 0 ? Double.NaN : sum.doubleValue() / values.length; - } - } - - static final List> DOUBLE_CASES = Arrays.asList( - new TestCase<>(-312.31, 6312.31, 11629.13, - -312.31, 29.13, 112.158, 6312.31, -312.158, -312.158, 112.158, - -312.31, 6312.31, 0.0), - new TestCase<>(3.14, 3.14, 3.14, 3.14), - new TestCase<>(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.0)); - - static final List> LONG_CASES = Arrays.asList( - new TestCase<>(-50000000000000000L, - 70000000000000000L, - 60000033123213121L, - 0L, 1L, 10000000000000000L, -50000000000000000L, - 70000000000000000L, 0L, 10000000000000000L, -1L, - -50000000000000000L, 70000000000000000L, 33123213121L), - new TestCase<>(3L, 3L, 3L, 3L), - new TestCase<>(Long.MAX_VALUE, Long.MIN_VALUE, 0L)); - - static final List> INTEGER_CASES = Arrays.asList( - new TestCase<>(-3, 6, 22, - 1, -3, 2, 6, 3, 4, -3, 5, 6, 1), - new TestCase<>(3, 3, 3, 3), - new TestCase<>(Integer.MAX_VALUE, Integer.MIN_VALUE, 0)); - - @Test - public void testInstantStats() { - assertEquals(new Instant(1000), Min.MinFn.naturalOrder().apply( - Arrays.asList(new Instant(1000), new Instant(2000)))); - assertEquals(null, Min.MinFn.naturalOrder().apply( - Collections.emptyList())); - assertEquals(new Instant(5000), Min.MinFn.naturalOrder(new Instant(5000)).apply( - Collections.emptyList())); - - assertEquals(new Instant(2000), Max.MaxFn.naturalOrder().apply( - Arrays.asList(new Instant(1000), new Instant(2000)))); - assertEquals(null, Max.MaxFn.naturalOrder().apply( - Collections.emptyList())); - assertEquals(new Instant(5000), Max.MaxFn.naturalOrder(new Instant(5000)).apply( - Collections.emptyList())); - } - - @Test - public void testDoubleStats() { - for (TestCase t : DOUBLE_CASES) { - assertEquals(t.sum, new Sum.SumDoubleFn().apply(t.data), - DOUBLE_COMPARISON_ACCURACY); - assertEquals(t.min, new Min.MinDoubleFn().apply(t.data), - DOUBLE_COMPARISON_ACCURACY); - assertEquals(t.max, new Max.MaxDoubleFn().apply(t.data), - DOUBLE_COMPARISON_ACCURACY); - assertEquals(t.mean, new Mean.MeanFn().apply(t.data), - DOUBLE_COMPARISON_ACCURACY); - } - } - - @Test - public void testIntegerStats() { - for (TestCase t : INTEGER_CASES) { - assertEquals(t.sum, new Sum.SumIntegerFn().apply(t.data)); - assertEquals(t.min, new Min.MinIntegerFn().apply(t.data)); - assertEquals(t.max, new Max.MaxIntegerFn().apply(t.data)); - assertEquals(t.mean, new Mean.MeanFn().apply(t.data)); - } - } - - @Test - public void testLongStats() { - for (TestCase t : LONG_CASES) { - assertEquals(t.sum, new Sum.SumLongFn().apply(t.data)); - assertEquals(t.min, new Min.MinLongFn().apply(t.data)); - assertEquals(t.max, new Max.MaxLongFn().apply(t.data)); - assertEquals(t.mean, new Mean.MeanFn().apply(t.data)); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java deleted file mode 100644 index b5ad51ce13..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/SumTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.TestUtils.checkCombineFn; -import static org.junit.Assert.assertEquals; - -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for Sum. - */ -@RunWith(JUnit4.class) -public class SumTest { - - @Test - public void testSumGetNames() { - assertEquals("Sum.Globally", Sum.integersGlobally().getName()); - assertEquals("Sum.Globally", Sum.doublesGlobally().getName()); - assertEquals("Sum.Globally", Sum.longsGlobally().getName()); - assertEquals("Sum.PerKey", Sum.integersPerKey().getName()); - assertEquals("Sum.PerKey", Sum.doublesPerKey().getName()); - assertEquals("Sum.PerKey", Sum.longsPerKey().getName()); - } - - @Test - public void testSumIntegerFn() { - checkCombineFn( - new Sum.SumIntegerFn(), - Lists.newArrayList(1, 2, 3, 4), - 10); - } - - @Test - public void testSumLongFn() { - checkCombineFn( - new Sum.SumLongFn(), - Lists.newArrayList(1L, 2L, 3L, 4L), - 10L); - } - - @Test - public void testSumDoubleFn() { - checkCombineFn( - new Sum.SumDoubleFn(), - Lists.newArrayList(1.0, 2.0, 3.0, 4.0), - 10.0); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java deleted file mode 100644 index 8a0cfe2f16..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/TopTest.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.Bound; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** Tests for Top. */ -@RunWith(JUnit4.class) -public class TopTest { - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @SuppressWarnings("unchecked") - static final String[] COLLECTION = new String[] { - "a", "bb", "c", "c", "z" - }; - - @SuppressWarnings("unchecked") - static final String[] EMPTY_COLLECTION = new String[] { - }; - - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] TABLE = new KV[] { - KV.of("a", 1), - KV.of("a", 2), - KV.of("a", 3), - KV.of("b", 1), - KV.of("b", 10), - KV.of("b", 10), - KV.of("b", 100), - }; - - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] EMPTY_TABLE = new KV[] { - }; - - public PCollection> createInputTable(Pipeline p) { - return p.apply("CreateInputTable", Create.of(Arrays.asList(TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - } - - public PCollection> createEmptyInputTable(Pipeline p) { - return p.apply("CreateEmptyInputTable", Create.of(Arrays.asList(EMPTY_TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - } - - @Test - @SuppressWarnings("unchecked") - public void testTop() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply(Create.of(Arrays.asList(COLLECTION)) - .withCoder(StringUtf8Coder.of())); - - PCollection> top1 = input.apply(Top.of(1, new OrderByLength())); - PCollection> top2 = input.apply(Top.largest(2)); - PCollection> top3 = input.apply(Top.smallest(3)); - - PCollection> inputTable = createInputTable(p); - PCollection>> largestPerKey = inputTable - .apply(Top.largestPerKey(2)); - PCollection>> smallestPerKey = inputTable - .apply(Top.smallestPerKey(2)); - - DataflowAssert.thatSingletonIterable(top1).containsInAnyOrder(Arrays.asList("bb")); - DataflowAssert.thatSingletonIterable(top2).containsInAnyOrder("z", "c"); - DataflowAssert.thatSingletonIterable(top3).containsInAnyOrder("a", "bb", "c"); - DataflowAssert.that(largestPerKey).containsInAnyOrder( - KV.of("a", Arrays.asList(3, 2)), - KV.of("b", Arrays.asList(100, 10))); - DataflowAssert.that(smallestPerKey).containsInAnyOrder( - KV.of("a", Arrays.asList(1, 2)), - KV.of("b", Arrays.asList(1, 10))); - - p.run(); - } - - @Test - @SuppressWarnings("unchecked") - public void testTopEmpty() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply(Create.of(Arrays.asList(EMPTY_COLLECTION)) - .withCoder(StringUtf8Coder.of())); - - PCollection> top1 = input.apply(Top.of(1, new OrderByLength())); - PCollection> top2 = input.apply(Top.largest(2)); - PCollection> top3 = input.apply(Top.smallest(3)); - - PCollection> inputTable = createEmptyInputTable(p); - PCollection>> largestPerKey = inputTable - .apply(Top.largestPerKey(2)); - PCollection>> smallestPerKey = inputTable - .apply(Top.smallestPerKey(2)); - - DataflowAssert.thatSingletonIterable(top1).empty(); - DataflowAssert.thatSingletonIterable(top2).empty(); - DataflowAssert.thatSingletonIterable(top3).empty(); - DataflowAssert.that(largestPerKey).empty(); - DataflowAssert.that(smallestPerKey).empty(); - - p.run(); - } - - @Test - public void testTopEmptyWithIncompatibleWindows() { - Pipeline p = TestPipeline.create(); - Bound windowingFn = Window.into(FixedWindows.of(Duration.standardDays(10L))); - PCollection input = - p.apply(Create.timestamped(Collections.emptyList(), Collections.emptyList())) - .apply(windowingFn); - - expectedEx.expect(IllegalStateException.class); - expectedEx.expectMessage("Top"); - expectedEx.expectMessage("GlobalWindows"); - expectedEx.expectMessage("withoutDefaults"); - expectedEx.expectMessage("asSingletonView"); - - input.apply(Top.of(1, new OrderByLength())); - } - - @Test - @SuppressWarnings("unchecked") - public void testTopZero() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply(Create.of(Arrays.asList(COLLECTION)) - .withCoder(StringUtf8Coder.of())); - - PCollection> top1 = input.apply(Top.of(0, new OrderByLength())); - PCollection> top2 = input.apply(Top.largest(0)); - PCollection> top3 = input.apply(Top.smallest(0)); - - PCollection> inputTable = createInputTable(p); - PCollection>> largestPerKey = inputTable - .apply(Top.largestPerKey(0)); - - PCollection>> smallestPerKey = inputTable - .apply(Top.smallestPerKey(0)); - - DataflowAssert.thatSingletonIterable(top1).empty(); - DataflowAssert.thatSingletonIterable(top2).empty(); - DataflowAssert.thatSingletonIterable(top3).empty(); - DataflowAssert.that(largestPerKey).containsInAnyOrder( - KV.of("a", Arrays.asList()), - KV.of("b", Arrays.asList())); - DataflowAssert.that(smallestPerKey).containsInAnyOrder( - KV.of("a", Arrays.asList()), - KV.of("b", Arrays.asList())); - - p.run(); - } - - // This is a purely compile-time test. If the code compiles, then it worked. - @Test - public void testPerKeySerializabilityRequirement() { - Pipeline p = TestPipeline.create(); - p.apply("CreateCollection", Create.of(Arrays.asList(COLLECTION)) - .withCoder(StringUtf8Coder.of())); - - PCollection> inputTable = createInputTable(p); - inputTable - .apply(Top.perKey(1, - new IntegerComparator())); - - inputTable - .apply("PerKey2", Top.perKey(1, - new IntegerComparator2())); - } - - @Test - public void testCountConstraint() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply(Create.of(Arrays.asList(COLLECTION)) - .withCoder(StringUtf8Coder.of())); - - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage(Matchers.containsString(">= 0")); - - input.apply(Top.of(-1, new OrderByLength())); - } - - @Test - public void testTopGetNames() { - assertEquals("Top.Globally", Top.of(1, new OrderByLength()).getName()); - assertEquals("Smallest.Globally", Top.smallest(1).getName()); - assertEquals("Largest.Globally", Top.largest(2).getName()); - assertEquals("Top.PerKey", Top.perKey(1, new IntegerComparator()).getName()); - assertEquals("Smallest.PerKey", Top.smallestPerKey(1).getName()); - assertEquals("Largest.PerKey", Top.largestPerKey(2).getName()); - } - - @Test - public void testDisplayData() { - Top.Largest comparer = new Top.Largest(); - Combine.Globally> top = Top.of(1234, comparer); - DisplayData displayData = DisplayData.from(top); - - assertThat(displayData, hasDisplayItem("count", 1234)); - assertThat(displayData, hasDisplayItem("comparer", comparer.getClass())); - } - - private static class OrderByLength implements Comparator, Serializable { - @Override - public int compare(String a, String b) { - if (a.length() != b.length()) { - return a.length() - b.length(); - } else { - return a.compareTo(b); - } - } - } - - private static class IntegerComparator implements Comparator, Serializable { - @Override - public int compare(Integer o1, Integer o2) { - return o1.compareTo(o2); - } - } - - private static class IntegerComparator2 implements Comparator, Serializable { - @Override - public int compare(Integer o1, Integer o2) { - return o1.compareTo(o2); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ValuesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ValuesTest.java deleted file mode 100644 index 9663c453dd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ValuesTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** - * Tests for Values transform. - */ -@RunWith(JUnit4.class) -public class ValuesTest { - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] TABLE = new KV[] { - KV.of("one", 1), - KV.of("two", 2), - KV.of("three", 3), - KV.of("four", 4), - KV.of("dup", 4) - }; - - @SuppressWarnings({"rawtypes", "unchecked"}) - static final KV[] EMPTY_TABLE = new KV[] { - }; - - @Test - @Category(RunnableOnService.class) - public void testValues() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(Arrays.asList(TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection output = input.apply(Values.create()); - - DataflowAssert.that(output) - .containsInAnyOrder(1, 2, 3, 4, 4); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testValuesEmpty() { - Pipeline p = TestPipeline.create(); - - PCollection> input = - p.apply(Create.of(Arrays.asList(EMPTY_TABLE)).withCoder( - KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); - - PCollection output = input.apply(Values.create()); - - DataflowAssert.that(output).empty(); - - p.run(); - } - - @Test - public void testValuesGetName() { - assertEquals("Values", Values.create().getName()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java deleted file mode 100644 index 67bc9c63c9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/ViewTest.java +++ /dev/null @@ -1,1549 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static com.google.common.base.Preconditions.checkArgument; - -import static org.hamcrest.Matchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.CustomCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.NullableCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.DirectPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.InvalidWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.internal.matchers.ThrowableMessageMatcher; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NoSuchElementException; - -/** - * Tests for {@link View}. See also {@link ParDoTest}, which - * provides additional coverage since views can only be - * observed via {@link ParDo}. - */ -@RunWith(JUnit4.class) -public class ViewTest implements Serializable { - // This test is Serializable, just so that it's easy to have - // anonymous inner classes inside the non-static test methods. - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - @Category(RunnableOnService.class) - public void testSingletonSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView view = - pipeline.apply("Create47", Create.of(47)).apply(View.asSingleton()); - - PCollection output = - pipeline.apply("Create123", Create.of(1, 2, 3)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.sideInput(view)); - } - })); - - DataflowAssert.that(output).containsInAnyOrder(47, 47, 47); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedSingletonSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView view = - pipeline.apply("Create47", Create.timestamped( - TimestampedValue.of(47, new Instant(1)), - TimestampedValue.of(48, new Instant(11)))) - .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asSingleton()); - - PCollection output = - pipeline.apply("Create123", Create.timestamped( - TimestampedValue.of(1, new Instant(4)), - TimestampedValue.of(2, new Instant(8)), - TimestampedValue.of(3, new Instant(12)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.sideInput(view)); - } - })); - - DataflowAssert.that(output).containsInAnyOrder(47, 47, 48); - - pipeline.run(); - } - - @Test - public void testEmptySingletonSideInput() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView view = - pipeline.apply("CreateEmptyIntegers", Create.of().withCoder(VarIntCoder.of())) - .apply(View.asSingleton()); - - pipeline.apply("Create123", Create.of(1, 2, 3)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.sideInput(view)); - } - })); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(NoSuchElementException.class)); - thrown.expectMessage("Empty"); - thrown.expectMessage("PCollection"); - thrown.expectMessage("singleton"); - - pipeline.run(); - } - - @Test - public void testNonSingletonSideInput() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollection oneTwoThree = pipeline.apply(Create.of(1, 2, 3)); - final PCollectionView view = oneTwoThree.apply(View.asSingleton()); - - oneTwoThree.apply( - "OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.sideInput(view)); - } - })); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalArgumentException.class)); - thrown.expectMessage("PCollection"); - thrown.expectMessage("more than one"); - thrown.expectMessage("singleton"); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testListSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(11, 13, 17, 23)).apply(View.asList()); - - PCollection output = - pipeline.apply("CreateMainInput", Create.of(29, 31)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - checkArgument(c.sideInput(view).size() == 4); - checkArgument(c.sideInput(view).get(0) == c.sideInput(view).get(0)); - for (Integer i : c.sideInput(view)) { - c.output(i); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 11, 13, 17, 23); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedListSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(11, new Instant(1)), - TimestampedValue.of(13, new Instant(1)), - TimestampedValue.of(17, new Instant(1)), - TimestampedValue.of(23, new Instant(1)), - TimestampedValue.of(31, new Instant(11)), - TimestampedValue.of(33, new Instant(11)), - TimestampedValue.of(37, new Instant(11)), - TimestampedValue.of(43, new Instant(11)))) - .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asList()); - - PCollection output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of(29, new Instant(1)), - TimestampedValue.of(35, new Instant(11)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - checkArgument(c.sideInput(view).size() == 4); - checkArgument(c.sideInput(view).get(0) == c.sideInput(view).get(0)); - for (Integer i : c.sideInput(view)) { - c.output(i); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 31, 33, 37, 43); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testEmptyListSideInput() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateEmptyView", Create.of().withCoder(VarIntCoder.of())) - .apply(View.asList()); - - PCollection results = - pipeline.apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - assertTrue(c.sideInput(view).isEmpty()); - assertFalse(c.sideInput(view).iterator().hasNext()); - c.output(1); - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(results).containsInAnyOrder(1); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testListSideInputIsImmutable() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(11)).apply(View.asList()); - - PCollection output = - pipeline.apply("CreateMainInput", Create.of(29)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - try { - c.sideInput(view).clear(); - fail("Expected UnsupportedOperationException on clear()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).add(4); - fail("Expected UnsupportedOperationException on add()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).addAll(new ArrayList()); - fail("Expected UnsupportedOperationException on addAll()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).remove(0); - fail("Expected UnsupportedOperationException on remove()"); - } catch (UnsupportedOperationException expected) { - } - for (Integer i : c.sideInput(view)) { - c.output(i); - } - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(output).containsInAnyOrder(11); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testIterableSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(11, 13, 17, 23)) - .apply(View.asIterable()); - - PCollection output = - pipeline.apply("CreateMainInput", Create.of(29, 31)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - for (Integer i : c.sideInput(view)) { - c.output(i); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 11, 13, 17, 23); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedIterableSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(11, new Instant(1)), - TimestampedValue.of(13, new Instant(1)), - TimestampedValue.of(17, new Instant(1)), - TimestampedValue.of(23, new Instant(1)), - TimestampedValue.of(31, new Instant(11)), - TimestampedValue.of(33, new Instant(11)), - TimestampedValue.of(37, new Instant(11)), - TimestampedValue.of(43, new Instant(11)))) - .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asIterable()); - - PCollection output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of(29, new Instant(1)), - TimestampedValue.of(35, new Instant(11)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - for (Integer i : c.sideInput(view)) { - c.output(i); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder(11, 13, 17, 23, 31, 33, 37, 43); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testEmptyIterableSideInput() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateEmptyView", Create.of().withCoder(VarIntCoder.of())) - .apply(View.asIterable()); - - PCollection results = - pipeline.apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - assertFalse(c.sideInput(view).iterator().hasNext()); - c.output(1); - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(results).containsInAnyOrder(1); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testIterableSideInputIsImmutable() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(11)).apply(View.asIterable()); - - PCollection output = - pipeline.apply("CreateMainInput", Create.of(29)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - Iterator iterator = c.sideInput(view).iterator(); - while (iterator.hasNext()) { - try { - iterator.remove(); - fail("Expected UnsupportedOperationException on remove()"); - } catch (UnsupportedOperationException expected) { - } - c.output(iterator.next()); - } - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(output).containsInAnyOrder(11); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMultimapSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 2), KV.of("b", 3))) - .apply(View.asMultimap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { - c.output(KV.of(c.element(), v)); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMultimapAsEntrySetSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 2), KV.of("b", 3))) - .apply(View.asMultimap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of(2 /* size */)) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - assertEquals((int) c.element(), c.sideInput(view).size()); - assertEquals((int) c.element(), c.sideInput(view).entrySet().size()); - for (Entry> entry : c.sideInput(view).entrySet()) { - for (Integer value : entry.getValue()) { - c.output(KV.of(entry.getKey(), value)); - } - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("a", 1), KV.of("a", 2), KV.of("b", 3)); - - pipeline.run(); - } - - private static class NonDeterministicStringCoder extends CustomCoder { - @Override - public void encode(String value, OutputStream outStream, Coder.Context context) - throws CoderException, IOException { - StringUtf8Coder.of().encode(value, outStream, context); - } - - @Override - public String decode(InputStream inStream, Coder.Context context) - throws CoderException, IOException { - return StringUtf8Coder.of().decode(inStream, context); - } - - @Override - public void verifyDeterministic() - throws com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException { - throw new NonDeterministicException(this, "Test coder is not deterministic on purpose."); - } - } - - @Test - @Category(RunnableOnService.class) - public void testMultimapSideInputWithNonDeterministicKeyCoder() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateSideInput", - Create.of(KV.of("a", 1), KV.of("a", 2), KV.of("b", 3)) - .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) - .apply(View.asMultimap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { - c.output(KV.of(c.element(), v)); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedMultimapSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(KV.of("a", 1), new Instant(1)), - TimestampedValue.of(KV.of("a", 2), new Instant(7)), - TimestampedValue.of(KV.of("b", 3), new Instant(14)))) - .apply( - "SideWindowInto", - Window.>into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asMultimap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("apple", new Instant(5)), - TimestampedValue.of("banana", new Instant(13)), - TimestampedValue.of("blackberry", new Instant(16)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - for (Integer v : - c.sideInput(view) - .get(c.element().substring(0, 1))) { - c.output(KV.of(c.element(), v)); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedMultimapAsEntrySetSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(KV.of("a", 1), new Instant(1)), - TimestampedValue.of(KV.of("a", 2), new Instant(7)), - TimestampedValue.of(KV.of("b", 3), new Instant(14)))) - .apply( - "SideWindowInto", - Window.>into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asMultimap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of(1 /* size */, new Instant(5)), - TimestampedValue.of(1 /* size */, new Instant(16)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - assertEquals((int) c.element(), - c.sideInput(view).size()); - assertEquals((int) c.element(), - c.sideInput(view).entrySet().size()); - for (Entry> entry - : c.sideInput(view).entrySet()) { - for (Integer value : entry.getValue()) { - c.output(KV.of(entry.getKey(), value)); - } - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("a", 1), KV.of("a", 2), KV.of("b", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedMultimapSideInputWithNonDeterministicKeyCoder() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateSideInput", - Create.timestamped( - TimestampedValue.of(KV.of("a", 1), new Instant(1)), - TimestampedValue.of(KV.of("a", 2), new Instant(7)), - TimestampedValue.of(KV.of("b", 3), new Instant(14))) - .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) - .apply("SideWindowInto", - Window.>into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asMultimap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("apple", new Instant(5)), - TimestampedValue.of("banana", new Instant(13)), - TimestampedValue.of("blackberry", new Instant(16)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - for (Integer v : - c.sideInput(view) - .get(c.element().substring(0, 1))) { - c.output(KV.of(c.element(), v)); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("apple", 2), KV.of("banana", 3), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testEmptyMultimapSideInput() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateEmptyView", Create.>of().withCoder( - KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) - .apply(View.asMultimap()); - - PCollection results = - pipeline.apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - assertTrue(c.sideInput(view).isEmpty()); - assertTrue(c.sideInput(view).entrySet().isEmpty()); - assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); - c.output(c.element()); - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(results).containsInAnyOrder(1); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testEmptyMultimapSideInputWithNonDeterministicKeyCoder() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateEmptyView", - Create.>of().withCoder( - KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) - .apply(View.asMultimap()); - - PCollection results = - pipeline.apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - assertTrue(c.sideInput(view).isEmpty()); - assertTrue(c.sideInput(view).entrySet().isEmpty()); - assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); - c.output(c.element()); - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(results).containsInAnyOrder(1); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMultimapSideInputIsImmutable() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView>> view = - pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1))) - .apply(View.asMultimap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple")) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - try { - c.sideInput(view).clear(); - fail("Expected UnsupportedOperationException on clear()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).put("c", ImmutableList.of(3)); - fail("Expected UnsupportedOperationException on put()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).remove("c"); - fail("Expected UnsupportedOperationException on remove()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).putAll(new HashMap>()); - fail("Expected UnsupportedOperationException on putAll()"); - } catch (UnsupportedOperationException expected) { - } - for (Integer v : c.sideInput(view).get(c.element().substring(0, 1))) { - c.output(KV.of(c.element(), v)); - } - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(output).containsInAnyOrder(KV.of("apple", 1)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMapSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output( - KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("banana", 3), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMapAsEntrySetSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of(2 /* size */)) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - assertEquals((int) c.element(), c.sideInput(view).size()); - assertEquals((int) c.element(), c.sideInput(view).entrySet().size()); - for (Entry entry : c.sideInput(view).entrySet()) { - c.output(KV.of(entry.getKey(), entry.getValue())); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("a", 1), KV.of("b", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMapSideInputWithNonDeterministicKeyCoder() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", - Create.of(KV.of("a", 1), KV.of("b", 3)) - .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output( - KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("banana", 3), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedMapSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(KV.of("a", 1), new Instant(1)), - TimestampedValue.of(KV.of("b", 2), new Instant(4)), - TimestampedValue.of(KV.of("b", 3), new Instant(18)))) - .apply( - "SideWindowInto", - Window.>into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("apple", new Instant(5)), - TimestampedValue.of("banana", new Instant(4)), - TimestampedValue.of("blackberry", new Instant(16)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of( - c.element(), - c.sideInput(view).get( - c.element().substring(0, 1)))); - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("banana", 2), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedMapAsEntrySetSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(KV.of("a", 1), new Instant(1)), - TimestampedValue.of(KV.of("b", 2), new Instant(4)), - TimestampedValue.of(KV.of("b", 3), new Instant(18)))) - .apply( - "SideWindowInto", - Window.>into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of(2 /* size */, new Instant(5)), - TimestampedValue.of(1 /* size */, new Instant(16)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - assertEquals((int) c.element(), - c.sideInput(view).size()); - assertEquals((int) c.element(), - c.sideInput(view).entrySet().size()); - for (Entry entry - : c.sideInput(view).entrySet()) { - c.output(KV.of(entry.getKey(), entry.getValue())); - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("a", 1), KV.of("b", 2), KV.of("b", 3)); - - pipeline.run(); - } - - - @Test - @Category(RunnableOnService.class) - public void testWindowedMapSideInputWithNonDeterministicKeyCoder() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", - Create.timestamped( - TimestampedValue.of(KV.of("a", 1), new Instant(1)), - TimestampedValue.of(KV.of("b", 2), new Instant(4)), - TimestampedValue.of(KV.of("b", 3), new Instant(18))) - .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) - .apply( - "SideWindowInto", - Window.>into(FixedWindows.of(Duration.millis(10)))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("apple", new Instant(5)), - TimestampedValue.of("banana", new Instant(4)), - TimestampedValue.of("blackberry", new Instant(16)))) - .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of( - new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of( - c.element(), - c.sideInput(view).get( - c.element().substring(0, 1)))); - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("banana", 2), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testEmptyMapSideInput() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateEmptyView", Create.>of().withCoder( - KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) - .apply(View.asMap()); - - PCollection results = - pipeline.apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - assertTrue(c.sideInput(view).isEmpty()); - assertTrue(c.sideInput(view).entrySet().isEmpty()); - assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); - c.output(c.element()); - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(results).containsInAnyOrder(1); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testEmptyMapSideInputWithNonDeterministicKeyCoder() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateEmptyView", Create.>of().withCoder( - KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) - .apply(View.asMap()); - - PCollection results = - pipeline.apply("Create1", Create.of(1)) - .apply("OutputSideInputs", ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - assertTrue(c.sideInput(view).isEmpty()); - assertTrue(c.sideInput(view).entrySet().isEmpty()); - assertFalse(c.sideInput(view).entrySet().iterator().hasNext()); - c.output(c.element()); - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(results).containsInAnyOrder(1); - - pipeline.run(); - } - - @Test - public void testMapSideInputWithNullValuesCatchesDuplicates() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline - .apply( - "CreateSideInput", - Create.of(KV.of("a", (Integer) null), KV.of("a", (Integer) null)) - .withCoder( - KvCoder.of(StringUtf8Coder.of(), NullableCoder.of(VarIntCoder.of())))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output( - KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 1), KV.of("banana", 3), KV.of("blackberry", 3)); - - // PipelineExecutionException is thrown with cause having a message stating that a - // duplicate is not allowed. - thrown.expectCause( - ThrowableMessageMatcher.hasMessage(Matchers.containsString("Duplicate values for a"))); - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMapSideInputIsImmutable() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1))) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple")) - .apply( - "OutputSideInputs", - ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - try { - c.sideInput(view).clear(); - fail("Expected UnsupportedOperationException on clear()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).put("c", 3); - fail("Expected UnsupportedOperationException on put()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).remove("c"); - fail("Expected UnsupportedOperationException on remove()"); - } catch (UnsupportedOperationException expected) { - } - try { - c.sideInput(view).putAll(new HashMap()); - fail("Expected UnsupportedOperationException on putAll()"); - } catch (UnsupportedOperationException expected) { - } - c.output( - KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); - } - })); - - // Pass at least one value through to guarantee that DoFn executes. - DataflowAssert.that(output).containsInAnyOrder(KV.of("apple", 1)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testCombinedMapSideInput() { - Pipeline pipeline = TestPipeline.create(); - - final PCollectionView> view = - pipeline.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 20), KV.of("b", 3))) - .apply("SumIntegers", Combine.perKey(new Sum.SumIntegerFn().asKeyedFn())) - .apply(View.asMap()); - - PCollection> output = - pipeline.apply("CreateMainInput", Create.of("apple", "banana", "blackberry")) - .apply("Output", ParDo.withSideInputs(view).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(KV.of(c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("apple", 21), KV.of("banana", 3), KV.of("blackberry", 3)); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedSideInputFixedToFixed() { - Pipeline p = TestPipeline.create(); - - final PCollectionView view = - p.apply( - "CreateSideInput", - Create.timestamped(TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(11)), TimestampedValue.of(3, new Instant(13)))) - .apply("WindowSideInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply(Sum.integersGlobally().withoutDefaults()) - .apply(View.asSingleton()); - - PCollection output = - p.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("A", new Instant(4)), - TimestampedValue.of("B", new Instant(15)), - TimestampedValue.of("C", new Instant(7)))) - .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); - } - })); - - DataflowAssert.that(output).containsInAnyOrder("A1", "B5", "C1"); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedSideInputFixedToGlobal() { - Pipeline p = TestPipeline.create(); - - final PCollectionView view = - p.apply( - "CreateSideInput", - Create.timestamped(TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(11)), TimestampedValue.of(3, new Instant(13)))) - .apply("WindowSideInput", Window.into(new GlobalWindows())) - .apply(Sum.integersGlobally()) - .apply(View.asSingleton()); - - PCollection output = - p.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("A", new Instant(4)), - TimestampedValue.of("B", new Instant(15)), - TimestampedValue.of("C", new Instant(7)))) - .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); - } - })); - - DataflowAssert.that(output).containsInAnyOrder("A6", "B6", "C6"); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowedSideInputFixedToFixedWithDefault() { - Pipeline p = TestPipeline.create(); - - final PCollectionView view = - p.apply("CreateSideInput", Create.timestamped( - TimestampedValue.of(2, new Instant(11)), - TimestampedValue.of(3, new Instant(13)))) - .apply("WindowSideInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply(Sum.integersGlobally().asSingletonView()); - - PCollection output = - p.apply("CreateMainInput", Create.timestamped( - TimestampedValue.of("A", new Instant(4)), - TimestampedValue.of("B", new Instant(15)), - TimestampedValue.of("C", new Instant(7)))) - .apply("WindowMainInput", Window.into(FixedWindows.of(Duration.millis(10)))) - .apply("OutputMainAndSideInputs", ParDo.withSideInputs(view).of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); - } - })); - - DataflowAssert.that(output).containsInAnyOrder("A0", "B5", "C0"); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testSideInputWithNullDefault() { - Pipeline p = TestPipeline.create(); - - final PCollectionView view = - p.apply("CreateSideInput", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply(Combine.globally(new SerializableFunction, Void>() { - @Override - public Void apply(Iterable input) { - return null; - } - }).asSingletonView()); - - PCollection output = - p.apply("CreateMainInput", Create.of("")) - .apply( - "OutputMainAndSideInputs", - ParDo.withSideInputs(view).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element() + c.sideInput(view)); - } - })); - - DataflowAssert.that(output).containsInAnyOrder("null"); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testSideInputWithNestedIterables() { - Pipeline pipeline = TestPipeline.create(); - final PCollectionView> view1 = - pipeline.apply("CreateVoid1", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply("OutputOneInteger", ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.output(17); - } - })) - .apply("View1", View.asIterable()); - - final PCollectionView>> view2 = - pipeline.apply("CreateVoid2", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply( - "OutputSideInput", - ParDo.withSideInputs(view1).of(new DoFn>() { - @Override - public void processElement(ProcessContext c) { - c.output(c.sideInput(view1)); - } - })) - .apply("View2", View.>asIterable()); - - PCollection output = - pipeline.apply("CreateVoid3", Create.of((Void) null).withCoder(VoidCoder.of())) - .apply( - "ReadIterableSideInput", ParDo.withSideInputs(view2).of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - for (Iterable input : c.sideInput(view2)) { - for (Integer i : input) { - c.output(i); - } - } - } - })); - - DataflowAssert.that(output).containsInAnyOrder(17); - - pipeline.run(); - } - - @Test - public void testViewGetName() { - assertEquals("View.AsSingleton", View.asSingleton().getName()); - assertEquals("View.AsIterable", View.asIterable().getName()); - assertEquals("View.AsMap", View.asMap().getName()); - assertEquals("View.AsMultimap", View.asMultimap().getName()); - } - - private Pipeline createTestBatchRunner() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setRunner(DataflowPipelineRunner.class); - options.setProject("someproject"); - options.setStagingLocation("gs://staging"); - options.setPathValidatorClass(NoopPathValidator.class); - options.setDataflowClient(null); - return Pipeline.create(options); - } - - private Pipeline createTestStreamingRunner() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setRunner(DataflowPipelineRunner.class); - options.setStreaming(true); - options.setProject("someproject"); - options.setStagingLocation("gs://staging"); - options.setPathValidatorClass(NoopPathValidator.class); - options.setDataflowClient(null); - return Pipeline.create(options); - } - - private Pipeline createTestDirectRunner() { - DirectPipelineOptions options = PipelineOptionsFactory.as(DirectPipelineOptions.class); - options.setRunner(DirectPipelineRunner.class); - return Pipeline.create(options); - } - - private void testViewUnbounded( - Pipeline pipeline, - PTransform>, ? extends PCollectionView> view) { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Unable to create a side-input view from input"); - thrown.expectCause( - ThrowableMessageMatcher.hasMessage(Matchers.containsString("non-bounded PCollection"))); - pipeline - .apply( - new PTransform>>() { - @Override - public PCollection> apply(PBegin input) { - return PCollection.>createPrimitiveOutputInternal( - input.getPipeline(), - WindowingStrategy.globalDefault(), - PCollection.IsBounded.UNBOUNDED) - .setTypeDescriptorInternal(new TypeDescriptor>() {}); - } - }) - .apply(view); - } - - private void testViewNonmerging( - Pipeline pipeline, - PTransform>, ? extends PCollectionView> view) { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Unable to create a side-input view from input"); - thrown.expectCause( - ThrowableMessageMatcher.hasMessage(Matchers.containsString("Consumed by GroupByKey"))); - pipeline.apply(Create.>of(KV.of("hello", 5))) - .apply(Window.>into(new InvalidWindows<>( - "Consumed by GroupByKey", FixedWindows.of(Duration.standardHours(1))))) - .apply(view); - } - - @Test - public void testViewUnboundedAsSingletonBatch() { - testViewUnbounded(createTestBatchRunner(), View.>asSingleton()); - } - - @Test - public void testViewUnboundedAsSingletonStreaming() { - testViewUnbounded(createTestStreamingRunner(), View.>asSingleton()); - } - - @Test - public void testViewUnboundedAsSingletonDirect() { - testViewUnbounded(createTestDirectRunner(), View.>asSingleton()); - } - - @Test - public void testViewUnboundedAsIterableBatch() { - testViewUnbounded(createTestBatchRunner(), View.>asIterable()); - } - - @Test - public void testViewUnboundedAsIterableStreaming() { - testViewUnbounded(createTestStreamingRunner(), View.>asIterable()); - } - - @Test - public void testViewUnboundedAsIterableDirect() { - testViewUnbounded(createTestDirectRunner(), View.>asIterable()); - } - - @Test - public void testViewUnboundedAsListBatch() { - testViewUnbounded(createTestBatchRunner(), View.>asList()); - } - - @Test - public void testViewUnboundedAsListStreaming() { - testViewUnbounded(createTestStreamingRunner(), View.>asList()); - } - - @Test - public void testViewUnboundedAsListDirect() { - testViewUnbounded(createTestDirectRunner(), View.>asList()); - } - - @Test - public void testViewUnboundedAsMapBatch() { - testViewUnbounded(createTestBatchRunner(), View.asMap()); - } - - @Test - public void testViewUnboundedAsMapStreaming() { - testViewUnbounded(createTestStreamingRunner(), View.asMap()); - } - - @Test - public void testViewUnboundedAsMapDirect() { - testViewUnbounded(createTestDirectRunner(), View.asMap()); - } - - - @Test - public void testViewUnboundedAsMultimapBatch() { - testViewUnbounded(createTestBatchRunner(), View.asMultimap()); - } - - @Test - public void testViewUnboundedAsMultimapStreaming() { - testViewUnbounded(createTestStreamingRunner(), View.asMultimap()); - } - - @Test - public void testViewUnboundedAsMultimapDirect() { - testViewUnbounded(createTestDirectRunner(), View.asMultimap()); - } - - @Test - public void testViewNonmergingAsSingletonBatch() { - testViewNonmerging(createTestBatchRunner(), View.>asSingleton()); - } - - @Test - public void testViewNonmergingAsSingletonStreaming() { - testViewNonmerging(createTestStreamingRunner(), View.>asSingleton()); - } - - @Test - public void testViewNonmergingAsSingletonDirect() { - testViewNonmerging(createTestDirectRunner(), View.>asSingleton()); - } - - @Test - public void testViewNonmergingAsIterableBatch() { - testViewNonmerging(createTestBatchRunner(), View.>asIterable()); - } - - @Test - public void testViewNonmergingAsIterableStreaming() { - testViewNonmerging(createTestStreamingRunner(), View.>asIterable()); - } - - @Test - public void testViewNonmergingAsIterableDirect() { - testViewNonmerging(createTestDirectRunner(), View.>asIterable()); - } - - @Test - public void testViewNonmergingAsListBatch() { - testViewNonmerging(createTestBatchRunner(), View.>asList()); - } - - @Test - public void testViewNonmergingAsListStreaming() { - testViewNonmerging(createTestStreamingRunner(), View.>asList()); - } - - @Test - public void testViewNonmergingAsListDirect() { - testViewNonmerging(createTestDirectRunner(), View.>asList()); - } - - @Test - public void testViewNonmergingAsMapBatch() { - testViewNonmerging(createTestBatchRunner(), View.asMap()); - } - - @Test - public void testViewNonmergingAsMapStreaming() { - testViewNonmerging(createTestStreamingRunner(), View.asMap()); - } - - @Test - public void testViewNonmergingAsMapDirect() { - testViewNonmerging(createTestDirectRunner(), View.asMap()); - } - - - @Test - public void testViewNonmergingAsMultimapBatch() { - testViewNonmerging(createTestBatchRunner(), View.asMultimap()); - } - - @Test - public void testViewNonmergingAsMultimapStreaming() { - testViewNonmerging(createTestStreamingRunner(), View.asMultimap()); - } - - @Test - public void testViewNonmergingAsMultimapDirect() { - testViewNonmerging(createTestDirectRunner(), View.asMultimap()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithKeysTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithKeysTest.java deleted file mode 100644 index 0f9abd487f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithKeysTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for ExtractKeys transform. - */ -@RunWith(JUnit4.class) -public class WithKeysTest { - static final String[] COLLECTION = new String[] { - "a", - "aa", - "b", - "bb", - "bbb" - }; - - static final List> WITH_KEYS = Arrays.asList( - KV.of(1, "a"), - KV.of(2, "aa"), - KV.of(1, "b"), - KV.of(2, "bb"), - KV.of(3, "bbb") - ); - - static final List> WITH_CONST_KEYS = Arrays.asList( - KV.of(100, "a"), - KV.of(100, "aa"), - KV.of(100, "b"), - KV.of(100, "bb"), - KV.of(100, "bbb") - ); - - @Test - public void testExtractKeys() { - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(Arrays.asList(COLLECTION)).withCoder( - StringUtf8Coder.of())); - - PCollection> output = input.apply(WithKeys.of( - new LengthAsKey())); - DataflowAssert.that(output) - .containsInAnyOrder(WITH_KEYS); - - p.run(); - } - - @Test - public void testConstantKeys() { - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(Arrays.asList(COLLECTION)).withCoder( - StringUtf8Coder.of())); - - PCollection> output = - input.apply(WithKeys.of(100)); - DataflowAssert.that(output) - .containsInAnyOrder(WITH_CONST_KEYS); - - p.run(); - } - - @Test - public void testWithKeysGetName() { - assertEquals("WithKeys", WithKeys.of(100).getName()); - } - - @Test - public void testWithKeysWithUnneededWithKeyTypeSucceeds() { - TestPipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(Arrays.asList(COLLECTION)).withCoder( - StringUtf8Coder.of())); - - PCollection> output = - input.apply(WithKeys.of(new LengthAsKey()).withKeyType(TypeDescriptor.of(Integer.class))); - DataflowAssert.that(output).containsInAnyOrder(WITH_KEYS); - - p.run(); - } - - /** - * Key a value by its length. - */ - public static class LengthAsKey - implements SerializableFunction { - @Override - public Integer apply(String value) { - return value.length(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithTimestampsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithTimestampsTest.java deleted file mode 100644 index 09f6931327..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/WithTimestampsTest.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.Matchers.isA; - -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Tests for {@link WithTimestamps}. - */ -@RunWith(JUnit4.class) -public class WithTimestampsTest implements Serializable { - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - @Category(RunnableOnService.class) - public void withTimestampsShouldApplyTimestamps() { - TestPipeline p = TestPipeline.create(); - - SerializableFunction timestampFn = - new SerializableFunction() { - @Override - public Instant apply(String input) { - return new Instant(Long.valueOf(input)); - } - }; - - String yearTwoThousand = "946684800000"; - PCollection timestamped = - p.apply(Create.of("1234", "0", Integer.toString(Integer.MAX_VALUE), yearTwoThousand)) - .apply(WithTimestamps.of(timestampFn)); - - PCollection> timestampedVals = - timestamped.apply(ParDo.of(new DoFn>() { - @Override - public void processElement(DoFn>.ProcessContext c) - throws Exception { - c.output(KV.of(c.element(), c.timestamp())); - } - })); - - DataflowAssert.that(timestamped) - .containsInAnyOrder(yearTwoThousand, "0", "1234", Integer.toString(Integer.MAX_VALUE)); - DataflowAssert.that(timestampedVals) - .containsInAnyOrder( - KV.of("0", new Instant(0)), - KV.of("1234", new Instant(1234L)), - KV.of(Integer.toString(Integer.MAX_VALUE), new Instant(Integer.MAX_VALUE)), - KV.of(yearTwoThousand, new Instant(Long.valueOf(yearTwoThousand)))); - - p.run(); - } - - @Test - public void withTimestampsBackwardsInTimeShouldThrow() { - TestPipeline p = TestPipeline.create(); - - SerializableFunction timestampFn = - new SerializableFunction() { - @Override - public Instant apply(String input) { - return new Instant(Long.valueOf(input)); - } - }; - SerializableFunction backInTimeFn = - new SerializableFunction() { - @Override - public Instant apply(String input) { - return new Instant(Long.valueOf(input)).minus(Duration.millis(1000L)); - } - }; - - - String yearTwoThousand = "946684800000"; - - p.apply(Create.of("1234", "0", Integer.toString(Integer.MAX_VALUE), yearTwoThousand)) - .apply("WithTimestamps", WithTimestamps.of(timestampFn)) - .apply("AddSkew", WithTimestamps.of(backInTimeFn)); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(IllegalArgumentException.class)); - thrown.expectMessage("no earlier than the timestamp of the current input"); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void withTimestampsBackwardsInTimeAndWithAllowedTimestampSkewShouldSucceed() { - TestPipeline p = TestPipeline.create(); - - SerializableFunction timestampFn = - new SerializableFunction() { - @Override - public Instant apply(String input) { - return new Instant(Long.valueOf(input)); - } - }; - - final Duration skew = Duration.millis(1000L); - SerializableFunction backInTimeFn = - new SerializableFunction() { - @Override - public Instant apply(String input) { - return new Instant(Long.valueOf(input)).minus(skew); - } - }; - - String yearTwoThousand = "946684800000"; - PCollection timestampedWithSkew = - p.apply(Create.of("1234", "0", Integer.toString(Integer.MAX_VALUE), yearTwoThousand)) - .apply("FirstTimestamp", WithTimestamps.of(timestampFn)) - .apply( - "WithSkew", - WithTimestamps.of(backInTimeFn).withAllowedTimestampSkew(skew.plus(100L))); - - PCollection> timestampedVals = - timestampedWithSkew.apply(ParDo.of(new DoFn>() { - @Override - public void processElement(DoFn>.ProcessContext c) - throws Exception { - c.output(KV.of(c.element(), c.timestamp())); - } - })); - - DataflowAssert.that(timestampedWithSkew) - .containsInAnyOrder(yearTwoThousand, "0", "1234", Integer.toString(Integer.MAX_VALUE)); - DataflowAssert.that(timestampedVals) - .containsInAnyOrder( - KV.of("0", new Instant(0L).minus(skew)), - KV.of("1234", new Instant(1234L).minus(skew)), - KV.of( - Integer.toString(Integer.MAX_VALUE), - new Instant(Long.valueOf(Integer.MAX_VALUE)).minus(skew)), - KV.of(yearTwoThousand, new Instant(Long.valueOf(yearTwoThousand)).minus(skew))); - - p.run(); - } - - @Test - public void withTimestampsWithNullTimestampShouldThrow() { - SerializableFunction timestampFn = - new SerializableFunction() { - @Override - public Instant apply(String input) { - return null; - } - }; - - TestPipeline p = TestPipeline.create(); - String yearTwoThousand = "946684800000"; - p.apply(Create.of("1234", "0", Integer.toString(Integer.MAX_VALUE), yearTwoThousand)) - .apply(WithTimestamps.of(timestampFn)); - - thrown.expect(PipelineExecutionException.class); - thrown.expectCause(isA(NullPointerException.class)); - thrown.expectMessage("WithTimestamps"); - thrown.expectMessage("cannot be null"); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void withTimestampsWithNullFnShouldThrowOnConstruction() { - TestPipeline p = TestPipeline.create(); - - SerializableFunction timestampFn = null; - - thrown.expect(NullPointerException.class); - thrown.expectMessage("WithTimestamps fn cannot be null"); - - p.apply(Create.of("1234", "0", Integer.toString(Integer.MAX_VALUE))) - .apply(WithTimestamps.of(timestampFn)); - - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DataflowDisplayDataEvaluator.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DataflowDisplayDataEvaluator.java deleted file mode 100644 index 4040634a93..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DataflowDisplayDataEvaluator.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineDebugOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.util.NoopCredentialFactory; -import com.google.cloud.dataflow.sdk.util.NoopPathValidator; -import com.google.common.collect.Lists; - -/** - * Factory methods for creating {@link DisplayDataEvaluator} instances against the - * {@link DataflowPipelineRunner}. - */ -public final class DataflowDisplayDataEvaluator { - /** Do not instantiate. */ - private DataflowDisplayDataEvaluator() {} - - /** - * Retrieve a set of default {@link DataflowPipelineOptions} which can be used to build - * dataflow pipelines for evaluating display data. - */ - public static DataflowPipelineOptions getDefaultOptions() { - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - - options.setRunner(DataflowPipelineRunner.class); - options.setProject("foobar"); - options.setTempLocation("gs://bucket/tmpLocation"); - options.setFilesToStage(Lists.newArrayList()); - - options.as(DataflowPipelineDebugOptions.class).setPathValidatorClass(NoopPathValidator.class); - options.as(GcpOptions.class).setCredentialFactoryClass(NoopCredentialFactory.class); - - return options; - } - - /** - * Create a {@link DisplayDataEvaluator} instance to evaluate pipeline display data against - * the {@link DataflowPipelineRunner}. - */ - public static DisplayDataEvaluator create() { - return create(getDefaultOptions()); - } - - /** - * Create a {@link DisplayDataEvaluator} instance to evaluate pipeline display data against - * the {@link DataflowPipelineRunner} with the specified {@code options}. - */ - public static DisplayDataEvaluator create(DataflowPipelineOptions options) { - return DisplayDataEvaluator.create(options); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java deleted file mode 100644 index 82a06afb87..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluator.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.PipelineRunner; -import com.google.cloud.dataflow.sdk.runners.TransformTreeNode; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.POutput; -import com.google.cloud.dataflow.sdk.values.PValue; -import com.google.common.collect.Sets; - -import java.util.Objects; -import java.util.Set; - -/** - * Test utilities to evaluate the {@link DisplayData} in the context of a {@link PipelineRunner}. - */ -public class DisplayDataEvaluator { - private final PipelineOptions options; - - /** - * Create a new {@link DisplayDataEvaluator} using options returned from - * {@link #getDefaultOptions()}. - */ - public static DisplayDataEvaluator create() { - return create(getDefaultOptions()); - } - - /** - * Create a new {@link DisplayDataEvaluator} using the specified {@link PipelineOptions}. - */ - public static DisplayDataEvaluator create(PipelineOptions pipelineOptions) { - return new DisplayDataEvaluator(pipelineOptions); - } - - /** - * The default {@link PipelineOptions} which will be used by {@link #create()}. - */ - public static PipelineOptions getDefaultOptions() { - return TestPipeline.testingPipelineOptions(); - } - - private DisplayDataEvaluator(PipelineOptions options) { - this.options = options; - } - - /** - * Traverse the specified {@link PTransform}, collecting {@link DisplayData} registered on the - * inner primitive {@link PTransform PTransforms}. - * - * @return the set of {@link DisplayData} for primitive {@link PTransform PTransforms}. - */ - public Set displayDataForPrimitiveTransforms( - final PTransform, ? extends POutput> root) { - return displayDataForPrimitiveTransforms(root, null); - } - - /** - * Traverse the specified {@link PTransform}, collecting {@link DisplayData} registered on the - * inner primitive {@link PTransform PTransforms}. - * - * @param root The root {@link PTransform} to traverse - * @param inputCoder The coder to set for the {@link PTransform} input, or null to infer the - * default coder. - * - * @return the set of {@link DisplayData} for primitive {@link PTransform PTransforms}. - */ - public Set displayDataForPrimitiveTransforms( - final PTransform, ? extends POutput> root, - Coder inputCoder) { - - Create.Values input = Create.of(); - if (inputCoder != null) { - input = input.withCoder(inputCoder); - } - - Pipeline pipeline = Pipeline.create(options); - pipeline - .apply("Input", input) - .apply("Transform", root); - - PrimitiveDisplayDataPTransformVisitor visitor = new PrimitiveDisplayDataPTransformVisitor(root); - pipeline.traverseTopologically(visitor); - return visitor.getPrimitivesDisplayData(); - } - - /** - * Traverse the specified source {@link PTransform}, collecting {@link DisplayData} registered - * on the inner primitive {@link PTransform PTransforms}. - * - * @param root The source root {@link PTransform} to traverse - * @return the set of {@link DisplayData} for primitive source {@link PTransform PTransforms}. - */ - public Set displayDataForPrimitiveSourceTransforms( - final PTransform root) { - Pipeline pipeline = Pipeline.create(options); - pipeline - .apply("SourceTransform", root); - - return displayDataForPipeline(pipeline, root); - } - - private static Set displayDataForPipeline(Pipeline pipeline, PTransform root) { - PrimitiveDisplayDataPTransformVisitor visitor = new PrimitiveDisplayDataPTransformVisitor(root); - pipeline.traverseTopologically(visitor); - return visitor.getPrimitivesDisplayData(); - } - - /** - * Visits {@link PTransform PTransforms} in a pipeline, and collects {@link DisplayData} for - * each primitive transform under a given composite root. - */ - private static class PrimitiveDisplayDataPTransformVisitor implements Pipeline.PipelineVisitor { - private final PTransform root; - private final Set displayData; - private boolean inCompositeRoot = false; - - PrimitiveDisplayDataPTransformVisitor(PTransform root) { - this.root = root; - this.displayData = Sets.newHashSet(); - } - - Set getPrimitivesDisplayData() { - return displayData; - } - - @Override - public void enterCompositeTransform(TransformTreeNode node) { - if (Objects.equals(root, node.getTransform())) { - inCompositeRoot = true; - } - } - - @Override - public void leaveCompositeTransform(TransformTreeNode node) { - if (Objects.equals(root, node.getTransform())) { - inCompositeRoot = false; - } - } - @Override - public void visitTransform(TransformTreeNode node) { - if (inCompositeRoot || Objects.equals(root, node.getTransform())) { - displayData.add(DisplayData.from(node.getTransform())); - } - } - - @Override - public void visitValue(PValue value, TransformTreeNode producer) { - - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java deleted file mode 100644 index 5bbc67d963..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataEvaluatorTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.POutput; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Set; - -/** - * Unit tests for {@link DisplayDataEvaluator}. - */ -@RunWith(JUnit4.class) -public class DisplayDataEvaluatorTest implements Serializable { - - @Test - public void testCompositeTransform() { - PTransform, ? super POutput> myTransform = - new PTransform, POutput> () { - @Override - public PCollection apply(PCollection input) { - return input.apply(ParDo.of(new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element()); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("primitiveKey", "primitiveValue")); - } - })); - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("compositeKey", "compositeValue")); - } - }; - - DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(); - Set displayData = evaluator.displayDataForPrimitiveTransforms(myTransform); - - assertThat(displayData, not(hasItem(hasDisplayItem("compositeKey", "compositeValue")))); - assertThat(displayData, hasItem(hasDisplayItem("primitiveKey", "primitiveValue"))); - } - - @Test - public void testPrimitiveTransform() { - PTransform, ? super PCollection> myTransform = ParDo.of( - new DoFn() { - @Override - public void processElement(ProcessContext c) throws Exception {} - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }); - - DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(); - Set displayData = evaluator.displayDataForPrimitiveTransforms(myTransform); - - assertThat(displayData, hasItem(hasDisplayItem("foo"))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java deleted file mode 100644 index 771b7f3c6f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchers.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import static org.hamcrest.Matchers.allOf; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Item; - -import com.google.common.collect.Sets; -import org.hamcrest.CustomTypeSafeMatcher; -import org.hamcrest.Description; -import org.hamcrest.FeatureMatcher; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeDiagnosingMatcher; -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.Collection; - -/** - * Hamcrest matcher for making assertions on {@link DisplayData} instances. - */ -public class DisplayDataMatchers { - /** - * Do not instantiate. - */ - private DisplayDataMatchers() {} - - /** - * Creates a matcher that matches if the examined {@link DisplayData} contains any items. - */ - public static Matcher hasDisplayItem() { - return new FeatureMatcher>>( - Matchers.not(Matchers.empty()), "DisplayData", "DisplayData") { - @Override - protected Collection> featureValueOf(DisplayData actual) { - return actual.items(); - } - }; - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key. - */ - public static Matcher hasDisplayItem(String key) { - return hasDisplayItem(hasKey(key)); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key and String value. - */ - public static Matcher hasDisplayItem(String key, String value) { - return hasDisplayItem(key, DisplayData.Type.STRING, value); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key and Boolean value. - */ - public static Matcher hasDisplayItem(String key, Boolean value) { - return hasDisplayItem(key, DisplayData.Type.BOOLEAN, value); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key and Duration value. - */ - public static Matcher hasDisplayItem(String key, Duration value) { - return hasDisplayItem(key, DisplayData.Type.DURATION, value); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key and Float value. - */ - public static Matcher hasDisplayItem(String key, double value) { - return hasDisplayItem(key, DisplayData.Type.FLOAT, value); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key and Integer value. - */ - public static Matcher hasDisplayItem(String key, long value) { - return hasDisplayItem(key, DisplayData.Type.INTEGER, value); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key and Class value. - */ - public static Matcher hasDisplayItem(String key, Class value) { - return hasDisplayItem(key, DisplayData.Type.JAVA_CLASS, value); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains an item with the - * specified key and Timestamp value. - */ - public static Matcher hasDisplayItem(String key, Instant value) { - return hasDisplayItem(key, DisplayData.Type.TIMESTAMP, value); - } - - private static Matcher hasDisplayItem( - String key, DisplayData.Type type, Object value) { - DisplayData.FormattedItemValue formattedValue = type.format(value); - return hasDisplayItem(allOf( - hasKey(key), - hasType(type), - hasValue(formattedValue.getLongValue()))); - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData} contains any item - * matching the specified {@code itemMatcher}. - */ - public static Matcher hasDisplayItem(Matcher> itemMatcher) { - return new HasDisplayDataItemMatcher(itemMatcher); - } - - private static class HasDisplayDataItemMatcher extends TypeSafeDiagnosingMatcher { - private final Matcher> itemMatcher; - - private HasDisplayDataItemMatcher(Matcher> itemMatcher) { - this.itemMatcher = itemMatcher; - } - - @Override - public void describeTo(Description description) { - description.appendText("display data with item: "); - itemMatcher.describeTo(description); - } - - @Override - protected boolean matchesSafely(DisplayData data, Description mismatchDescription) { - Collection> items = data.items(); - boolean isMatch = Matchers.hasItem(itemMatcher).matches(items); - if (!isMatch) { - mismatchDescription.appendText("found " + items.size() + " non-matching item(s):\n"); - mismatchDescription.appendValue(data); - } - - return isMatch; - } - } - - /** @see #includesDisplayDataFrom(HasDisplayData, String) */ - public static Matcher includesDisplayDataFrom(HasDisplayData subComponent) { - return includesDisplayDataFrom(subComponent, subComponent.getClass()); - } - - /** @see #includesDisplayDataFrom(HasDisplayData, String) */ - public static Matcher includesDisplayDataFrom( - HasDisplayData subComponent, Class namespace) { - return includesDisplayDataFrom(subComponent, namespace.getName()); - } - - /** - * Create a matcher that matches if the examined {@link DisplayData} contains all display data - * registered from the specified subcomponent and namespace. - */ - public static Matcher includesDisplayDataFrom( - final HasDisplayData subComponent, final String namespace) { - return new CustomTypeSafeMatcher("includes subcomponent") { - @Override - protected boolean matchesSafely(DisplayData displayData) { - DisplayData subComponentData = subComponentData(); - if (subComponentData.items().size() == 0) { - throw new UnsupportedOperationException("subComponent contains no display data; " - + "cannot verify whether it is included"); - } - - DisplayDataComparison comparison = checkSubset(displayData, subComponentData); - return comparison.missingItems.isEmpty(); - } - - @Override - protected void describeMismatchSafely( - DisplayData displayData, Description mismatchDescription) { - DisplayData subComponentDisplayData = subComponentData(); - DisplayDataComparison comparison = checkSubset( - displayData, subComponentDisplayData); - - mismatchDescription - .appendText("did not include:\n") - .appendValue(comparison.missingItems) - .appendText("\nNon-matching items:\n") - .appendValue(comparison.unmatchedItems); - } - - private DisplayData subComponentData() { - return DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.include(subComponent, namespace); - } - }); - } - - private DisplayDataComparison checkSubset( - DisplayData displayData, DisplayData included) { - DisplayDataComparison comparison = new DisplayDataComparison(displayData.items()); - for (Item item : included.items()) { - Item matchedItem = displayData.asMap().get( - DisplayData.Identifier.of(item.getNamespace(), item.getKey())); - - if (matchedItem != null) { - comparison.matched(matchedItem); - } else { - comparison.missing(item); - } - } - - return comparison; - } - - class DisplayDataComparison { - Collection> missingItems; - Collection> unmatchedItems; - - DisplayDataComparison(Collection> superset) { - missingItems = Sets.newHashSet(); - unmatchedItems = Sets.newHashSet(superset); - } - - void matched(Item supersetItem) { - unmatchedItems.remove(supersetItem); - } - - void missing(Item subsetItem) { - missingItems.add(subsetItem); - } - } - }; - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a key - * with the specified value. - */ - public static Matcher> hasKey(String key) { - return hasKey(Matchers.is(key)); - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a key - * matching the specified key matcher. - */ - public static Matcher> hasKey(Matcher keyMatcher) { - return new FeatureMatcher, String>(keyMatcher, "with key", "key") { - @Override - protected String featureValueOf(DisplayData.Item actual) { - return actual.getKey(); - } - }; - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} contains the - * specified namespace. - */ - public static Matcher> hasNamespace(Class namespace) { - return hasNamespace(Matchers.>is(namespace)); - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} contains the - * specified namespace. - */ - public static Matcher> hasNamespace(String namespace) { - return new FeatureMatcher, String>( - Matchers.is(namespace), "display item with namespace", "namespace") { - @Override - protected String featureValueOf(Item actual) { - return actual.getNamespace(); - } - }; - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a namespace - * matching the specified namespace matcher. - */ - public static Matcher> hasNamespace(Matcher> namespaceMatcher) { - return new FeatureMatcher, Class>( - namespaceMatcher, "display item with namespace", "namespace") { - @Override - protected Class featureValueOf(DisplayData.Item actual) { - try { - return Class.forName(actual.getNamespace()); - } catch (ClassNotFoundException e) { - return null; - } - } - }; - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} matches the - * specified type. - */ - public static Matcher> hasType(DisplayData.Type type) { - return hasType(Matchers.is(type)); - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} has a type - * matching the specified type matcher. - */ - public static Matcher> hasType(Matcher typeMatcher) { - return new FeatureMatcher, DisplayData.Type>( - typeMatcher, "with type", "type") { - @Override - protected DisplayData.Type featureValueOf(DisplayData.Item actual) { - return actual.getType(); - } - }; - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} has the specified - * value. - */ - - public static Matcher> hasValue(Object value) { - return hasValue(Matchers.is(value)); - } - - /** - * Creates a matcher that matches if the examined {@link DisplayData.Item} contains a value - * matching the specified value matcher. - */ - public static Matcher> hasValue(Matcher valueMatcher) { - return new FeatureMatcher, T>( - valueMatcher, "with value", "value") { - @Override - protected T featureValueOf(DisplayData.Item actual) { - @SuppressWarnings("unchecked") - T value = (T) actual.getValue(); - return value; - } - }; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java deleted file mode 100644 index d519975898..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataMatchersTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.StringDescription; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Unit tests for {@link DisplayDataMatchers}. - */ -@RunWith(JUnit4.class) -public class DisplayDataMatchersTest { - @Test - public void testHasDisplayItem() { - Matcher matcher = hasDisplayItem(); - - assertFalse(matcher.matches(DisplayData.none())); - assertThat(createDisplayDataWithItem("foo", "bar"), matcher); - } - - @Test - public void testHasDisplayItemDescription() { - Matcher matcher = hasDisplayItem(); - Description desc = new StringDescription(); - Description mismatchDesc = new StringDescription(); - - matcher.describeTo(desc); - matcher.describeMismatch(DisplayData.none(), mismatchDesc); - - assertEquals("DisplayData not an empty collection", desc.toString()); - assertEquals("DisplayData was <[]>", mismatchDesc.toString()); - } - - @Test - public void testHasKey() { - Matcher matcher = hasDisplayItem("foo"); - - assertFalse(matcher.matches(createDisplayDataWithItem("fooz", "bar"))); - - assertThat(createDisplayDataWithItem("foo", "bar"), matcher); - } - - @Test - public void testHasType() { - Matcher matcher = hasDisplayItem(hasType(DisplayData.Type.JAVA_CLASS)); - - DisplayData data = DisplayData.from(new PTransform, PCollection>() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("foo", DisplayDataMatchersTest.class)); - } - }); - - assertFalse(matcher.matches(createDisplayDataWithItem("fooz", "bar"))); - assertThat(data, matcher); - } - - @Test - public void testHasValue() { - Matcher matcher = hasDisplayItem(hasValue("bar")); - - assertFalse(matcher.matches(createDisplayDataWithItem("foo", "baz"))); - assertThat(createDisplayDataWithItem("foo", "bar"), matcher); - } - - @Test - public void testHasNamespace() { - Matcher matcher = hasDisplayItem(hasNamespace(SampleTransform.class)); - - assertFalse(matcher.matches(DisplayData.from( - new PTransform, PCollection>(){}))); - assertThat(createDisplayDataWithItem("foo", "bar"), matcher); - } - - @Test - public void testIncludes() { - final HasDisplayData subComponent = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - HasDisplayData hasSubcomponent = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .include(subComponent) - .add(DisplayData.item("foo2", "bar2")); - } - }; - HasDisplayData sameKeyDifferentNamespace = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - Matcher matcher = includesDisplayDataFrom(subComponent); - - assertFalse(matcher.matches(DisplayData.from(sameKeyDifferentNamespace))); - assertThat(DisplayData.from(hasSubcomponent), matcher); - assertThat(DisplayData.from(subComponent), matcher); - } - - - private DisplayData createDisplayDataWithItem(final String key, final String value) { - return DisplayData.from(new SampleTransform(key, value)); - } - - static class SampleTransform extends PTransform, PCollection> { - private final String key; - private final String value; - - SampleTransform(String key, String value) { - this.key = key; - this.value = value; - } - - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item(key, value)); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java deleted file mode 100644 index d1601996a1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/display/DisplayDataTest.java +++ /dev/null @@ -1,1218 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.display; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasNamespace; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasType; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasValue; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.everyItem; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.isEmptyOrNullString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.options.ValueProvider; -import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Builder; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData.Item; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Multimap; -import com.google.common.testing.EqualsTester; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.hamcrest.CustomTypeSafeMatcher; -import org.hamcrest.FeatureMatcher; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Tests for {@link DisplayData} class. - */ -@RunWith(JUnit4.class) -public class DisplayDataTest implements Serializable { - @Rule public transient ExpectedException thrown = ExpectedException.none(); - - private static final DateTimeFormatter ISO_FORMATTER = ISODateTimeFormat.dateTime(); - private static final ObjectMapper MAPPER = new ObjectMapper(); - - @Test - public void testTypicalUsage() { - final HasDisplayData subComponent1 = - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("ExpectedAnswer", 42)); - } - }; - - final HasDisplayData subComponent2 = - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("Location", "Seattle")) - .add(DisplayData.item("Forecast", "Rain")); - } - }; - - - PTransform transform = - new PTransform, PCollection>() { - final Instant defaultStartTime = new Instant(0); - Instant startTime = defaultStartTime; - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .include(subComponent1) - .include(subComponent2) - .add(DisplayData.item("minSproggles", 200) - .withLabel("Minimum Required Sproggles")) - .add(DisplayData.item("fireLasers", true)) - .addIfNotDefault(DisplayData.item("startTime", startTime), defaultStartTime) - .add(DisplayData.item("timeBomb", Instant.now().plus(Duration.standardDays(1)))) - .add(DisplayData.item("filterLogic", subComponent1.getClass())) - .add(DisplayData.item("serviceUrl", "google.com/fizzbang") - .withLinkUrl("http://www.google.com/fizzbang")); - } - }; - - DisplayData data = DisplayData.from(transform); - - assertThat(data.items(), not(empty())); - assertThat( - data.items(), - everyItem( - allOf( - hasKey(not(isEmptyOrNullString())), - hasNamespace( - Matchers.>isOneOf( - transform.getClass(), subComponent1.getClass(), subComponent2.getClass())), - hasType(notNullValue(DisplayData.Type.class)), - hasValue(not(isEmptyOrNullString()))))); - } - - @Test - public void testDefaultInstance() { - DisplayData none = DisplayData.none(); - assertThat(none.items(), empty()); - } - - @Test - public void testCanBuildDisplayData() { - DisplayData data = - DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }); - - assertThat(data.items(), hasSize(1)); - assertThat(data, hasDisplayItem("foo", "bar")); - } - - @Test - public void testStaticValueProviderDate() { - final Instant value = Instant.now(); - DisplayData data = - DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item( - "foo", StaticValueProvider.of(value))); - } - }); - @SuppressWarnings("unchecked") - DisplayData.Item item = (DisplayData.Item) data.items().toArray()[0]; - - @SuppressWarnings("unchecked") - Matcher> matchesAllOf = Matchers.allOf( - hasKey("foo"), - hasType(DisplayData.Type.TIMESTAMP), - hasValue(ISO_FORMATTER.print(value))); - - assertThat(item, matchesAllOf); - } - - @Test - public void testStaticValueProviderString() { - DisplayData data = - DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item( - "foo", StaticValueProvider.of("bar"))); - } - }); - - assertThat(data.items(), hasSize(1)); - assertThat(data, hasDisplayItem("foo", "bar")); - } - - @Test - public void testStaticValueProviderInt() { - DisplayData data = - DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item( - "foo", StaticValueProvider.of(1))); - } - }); - - assertThat(data.items(), hasSize(1)); - assertThat(data, hasDisplayItem("foo", 1)); - } - - @Test - public void testInaccessibleValueProvider() { - DisplayData data = - DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item( - "foo", new ValueProvider() { - @Override - public boolean isAccessible() { - return false; - } - - @Override - public String get() { - return "bar"; - } - - @Override - public String toString() { - return "toString"; - } - })); - } - }); - - assertThat(data.items(), hasSize(1)); - assertThat(data, hasDisplayItem("foo", "toString")); - } - - @Test - public void testAsMap() { - DisplayData data = - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }); - - Map> map = data.asMap(); - assertEquals(map.size(), 1); - assertThat(data, hasDisplayItem("foo", "bar")); - assertEquals(map.values(), data.items()); - } - - @Test - public void testItemProperties() { - final Instant value = Instant.now(); - DisplayData data = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("now", value) - .withLabel("the current instant") - .withLinkUrl("http://time.gov") - .withNamespace(DisplayDataTest.class)); - } - }); - - @SuppressWarnings("unchecked") - DisplayData.Item item = (DisplayData.Item) data.items().toArray()[0]; - - @SuppressWarnings("unchecked") - Matcher> matchesAllOf = Matchers.allOf( - hasNamespace(DisplayDataTest.class), - hasKey("now"), - hasType(DisplayData.Type.TIMESTAMP), - hasValue(ISO_FORMATTER.print(value)), - hasShortValue(nullValue(String.class)), - hasLabel(is("the current instant")), - hasUrl(is("http://time.gov"))); - - assertThat(item, matchesAllOf); - } - - @Test - public void testUnspecifiedOptionalProperties() { - DisplayData data = - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }); - - assertThat( - data, - hasDisplayItem(allOf(hasLabel(nullValue(String.class)), hasUrl(nullValue(String.class))))); - } - - @Test - public void testAddIfNotDefault() { - DisplayData data = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .addIfNotDefault(DisplayData.item("defaultString", "foo"), "foo") - .addIfNotDefault(DisplayData.item("notDefaultString", "foo"), "notFoo") - .addIfNotDefault(DisplayData.item("defaultInteger", 1), 1) - .addIfNotDefault(DisplayData.item("notDefaultInteger", 1), 2) - .addIfNotDefault(DisplayData.item("defaultDouble", 123.4), 123.4) - .addIfNotDefault(DisplayData.item("notDefaultDouble", 123.4), 234.5) - .addIfNotDefault(DisplayData.item("defaultBoolean", true), true) - .addIfNotDefault(DisplayData.item("notDefaultBoolean", true), false) - .addIfNotDefault(DisplayData.item("defaultInstant", new Instant(0)), new Instant(0)) - .addIfNotDefault(DisplayData.item("notDefaultInstant", new Instant(0)), Instant.now()) - .addIfNotDefault(DisplayData.item("defaultDuration", Duration.ZERO), Duration.ZERO) - .addIfNotDefault( - DisplayData.item("notDefaultDuration", Duration.millis(1234)), - Duration.ZERO) - .addIfNotDefault( - DisplayData.item("defaultClass", DisplayDataTest.class), - DisplayDataTest.class) - .addIfNotDefault( - DisplayData.item("notDefaultClass", DisplayDataTest.class), - null); - } - }); - - assertThat(data.items(), hasSize(7)); - assertThat(data.items(), everyItem(hasKey(startsWith("notDefault")))); - } - - @Test - @SuppressWarnings("UnnecessaryBoxing") - public void testInterpolatedTypeDefaults() { - DisplayData data = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .addIfNotDefault(DisplayData.item("integer", 123), 123) - .addIfNotDefault(DisplayData.item("Integer", - Integer.valueOf(123)), - Integer.valueOf(123)) - .addIfNotDefault(DisplayData.item("long", 123L), 123L) - .addIfNotDefault(DisplayData.item("Long", Long.valueOf(123)), Long.valueOf(123)) - .addIfNotDefault(DisplayData.item("float", 1.23f), 1.23f) - .addIfNotDefault(DisplayData.item("Float", Float.valueOf(1.23f)), Float.valueOf(1.23f)) - .addIfNotDefault(DisplayData.item("double", 1.23), 1.23) - .addIfNotDefault(DisplayData.item("Double", Double.valueOf(1.23)), Double.valueOf(1.23)) - .addIfNotDefault(DisplayData.item("boolean", true), true) - .addIfNotDefault( - DisplayData.item("Boolean", Boolean.valueOf(true)), - Boolean.valueOf(true)); - } - }); - - assertThat(data.items(), empty()); - } - - @Test - public void testAddIfNotNull() { - DisplayData data = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .addIfNotNull(DisplayData.item("nullString", (String) null)) - .addIfNotNull(DisplayData.item("nullVPString", (ValueProvider) null)) - .addIfNotNull(DisplayData.item("nullierVPString", StaticValueProvider.of(null))) - .addIfNotNull(DisplayData.item("notNullString", "foo")) - .addIfNotNull(DisplayData.item("nullLong", (Long) null)) - .addIfNotNull(DisplayData.item("notNullLong", 1234L)) - .addIfNotNull(DisplayData.item("nullDouble", (Double) null)) - .addIfNotNull(DisplayData.item("notNullDouble", 123.4)) - .addIfNotNull(DisplayData.item("nullBoolean", (Boolean) null)) - .addIfNotNull(DisplayData.item("notNullBoolean", true)) - .addIfNotNull(DisplayData.item("nullInstant", (Instant) null)) - .addIfNotNull(DisplayData.item("notNullInstant", Instant.now())) - .addIfNotNull(DisplayData.item("nullDuration", (Duration) null)) - .addIfNotNull(DisplayData.item("notNullDuration", Duration.ZERO)) - .addIfNotNull(DisplayData.item("nullClass", (Class) null)) - .addIfNotNull(DisplayData.item("notNullClass", DisplayDataTest.class)); - } - }); - - assertThat(data.items(), hasSize(7)); - assertThat(data.items(), everyItem(hasKey(startsWith("notNull")))); - } - - @Test - public void testModifyingConditionalItemIsSafe() { - HasDisplayData component = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.addIfNotNull(DisplayData.item("nullItem", (Class) null) - .withLinkUrl("http://abc") - .withNamespace(DisplayDataTest.class) - .withLabel("Null item should be safe")); - } - }; - - DisplayData.from(component); // should not throw - } - - - @Test - public void testIncludes() { - final HasDisplayData subComponent = - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - DisplayData data = - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.include(subComponent); - } - }); - - assertThat(data, includesDisplayDataFrom(subComponent)); - } - - @Test - public void testIncludesNamespaceOverride() { - final HasDisplayData subComponent = new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - final HasDisplayData namespaceOverride = new HasDisplayData(){ - @Override - public void populateDisplayData(Builder builder) { - } - }; - - DisplayData data = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.include(subComponent, namespaceOverride.getClass()); - } - }); - - assertThat(data, includesDisplayDataFrom(subComponent, namespaceOverride.getClass())); - } - - @Test - public void testNamespaceOverrideMultipleLevels() { - final HasDisplayData componentA = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - final HasDisplayData componentB = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .add(DisplayData.item("foo", "bar")) - .include(componentA); - } - }; - - final HasDisplayData componentC = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .add(DisplayData.item("foo", "bar")) - .include(componentB, "overrideB"); - } - }; - - DisplayData data = DisplayData.from(componentC); - assertThat(data, hasDisplayItem(hasNamespace(componentC.getClass()))); - assertThat(data, hasDisplayItem(hasNamespace("overrideB"))); - assertThat(data, hasDisplayItem(hasNamespace(componentA.getClass()))); - } - - @Test - public void testNullNamespaceOverride() { - thrown.expectCause(isA(NullPointerException.class)); - - DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("foo", "bar") - .withNamespace((Class) null)); - } - }); - } - - @Test - public void testIdentifierEquality() { - new EqualsTester() - .addEqualityGroup( - DisplayData.Identifier.of(DisplayDataTest.class, "1"), - DisplayData.Identifier.of(DisplayDataTest.class, "1")) - .addEqualityGroup(DisplayData.Identifier.of(Object.class, "1")) - .addEqualityGroup(DisplayData.Identifier.of(DisplayDataTest.class, "2")) - .testEquals(); - } - - @Test - public void testItemEquality() { - new EqualsTester() - .addEqualityGroup(DisplayData.item("foo", "bar"), DisplayData.item("foo", "bar")) - .addEqualityGroup(DisplayData.item("foo", "barz")) - .testEquals(); - } - - @Test - public void testDisplayDataEquality() { - HasDisplayData component1 = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - HasDisplayData component2 = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - DisplayData component1DisplayData1 = DisplayData.from(component1); - DisplayData component1DisplayData2 = DisplayData.from(component1); - DisplayData component2DisplayData = DisplayData.from(component2); - - new EqualsTester() - .addEqualityGroup(component1DisplayData1, component1DisplayData2) - .addEqualityGroup(component2DisplayData) - .testEquals(); - } - - @Test - public void testAnonymousClassNamespace() { - DisplayData data = - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }); - - DisplayData.Item item = (DisplayData.Item) data.items().toArray()[0]; - final Pattern anonClassRegex = Pattern.compile( - Pattern.quote(DisplayDataTest.class.getName()) + "\\$\\d+$"); - assertThat(item.getNamespace(), new CustomTypeSafeMatcher( - "anonymous class regex: " + anonClassRegex) { - @Override - protected boolean matchesSafely(String item) { - java.util.regex.Matcher m = anonClassRegex.matcher(item); - return m.matches(); - } - }); - } - - @Test - public void testAcceptsKeysWithDifferentNamespaces() { - DisplayData data = - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("foo", "bar")) - .include( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }); - } - }); - - assertThat(data.items(), hasSize(2)); - } - - @Test - public void testDuplicateKeyThrowsException() { - thrown.expectCause(isA(IllegalArgumentException.class)); - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("foo", "bar")) - .add(DisplayData.item("foo", "baz")); - } - }); - } - - @Test - public void testDuplicateKeyWithNamespaceOverrideDoesntThrow() { - DisplayData displayData = DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("foo", "bar")) - .add(DisplayData.item("foo", "baz") - .withNamespace(DisplayDataTest.class)); - } - }); - - assertThat(displayData.items(), hasSize(2)); - } - - @Test - public void testToString() { - HasDisplayData component = new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - DisplayData data = DisplayData.from(component); - assertEquals(String.format("%s:foo=bar", component.getClass().getName()), data.toString()); - } - - @Test - public void testHandlesIncludeCycles() { - - final IncludeSubComponent componentA = - new IncludeSubComponent() { - @Override - String getId() { - return "componentA"; - } - }; - final IncludeSubComponent componentB = - new IncludeSubComponent() { - @Override - String getId() { - return "componentB"; - } - }; - - HasDisplayData component = - new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.include(componentA); - } - }; - - componentA.subComponent = componentB; - componentB.subComponent = componentA; - - DisplayData data = DisplayData.from(component); - assertThat(data.items(), hasSize(2)); - } - - @Test - public void testIncludesSubcomponentsWithObjectEquality() { - DisplayData data = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .include(new EqualsEverything("foo1", "bar1")) - .include(new EqualsEverything("foo2", "bar2")); - } - }); - - assertThat(data.items(), hasSize(2)); - } - - private static class EqualsEverything implements HasDisplayData { - private final String value; - private final String key; - EqualsEverything(String key, String value) { - this.key = key; - this.value = value; - } - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item(key, value)); - } - - @Override - public int hashCode() { - return 1; - } - - @Override - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - public boolean equals(Object obj) { - return true; - } - } - - abstract static class IncludeSubComponent implements HasDisplayData { - HasDisplayData subComponent; - - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("id", getId())) - .include(subComponent); - } - - abstract String getId(); - } - - @Test - public void testTypeMappings() { - DisplayData data = - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("string", "foobar")) - .add(DisplayData.item("integer", 123)) - .add(DisplayData.item("float", 3.14)) - .add(DisplayData.item("boolean", true)) - .add(DisplayData.item("java_class", DisplayDataTest.class)) - .add(DisplayData.item("timestamp", Instant.now())) - .add(DisplayData.item("duration", Duration.standardHours(1))); - } - }); - - Collection> items = data.items(); - assertThat( - items, hasItem(allOf(hasKey("string"), hasType(DisplayData.Type.STRING)))); - assertThat( - items, hasItem(allOf(hasKey("integer"), hasType(DisplayData.Type.INTEGER)))); - assertThat(items, hasItem(allOf(hasKey("float"), hasType(DisplayData.Type.FLOAT)))); - assertThat(items, hasItem(allOf(hasKey("boolean"), hasType(DisplayData.Type.BOOLEAN)))); - assertThat( - items, - hasItem(allOf(hasKey("java_class"), hasType(DisplayData.Type.JAVA_CLASS)))); - assertThat( - items, - hasItem(allOf(hasKey("timestamp"), hasType(DisplayData.Type.TIMESTAMP)))); - assertThat( - items, hasItem(allOf(hasKey("duration"), hasType(DisplayData.Type.DURATION)))); - } - - @Test - public void testExplicitItemType() { - DisplayData data = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .add(DisplayData.item("integer", DisplayData.Type.INTEGER, 1234L)) - .add(DisplayData.item("string", DisplayData.Type.STRING, "foobar")); - } - }); - - assertThat(data, hasDisplayItem("integer", 1234L)); - assertThat(data, hasDisplayItem("string", "foobar")); - } - - @Test - public void testFormatIncompatibleTypes() { - Map invalidPairs = ImmutableMap.builder() - .put(DisplayData.Type.STRING, 1234) - .put(DisplayData.Type.INTEGER, "string value") - .put(DisplayData.Type.FLOAT, "string value") - .put(DisplayData.Type.BOOLEAN, "string value") - .put(DisplayData.Type.TIMESTAMP, "string value") - .put(DisplayData.Type.DURATION, "string value") - .put(DisplayData.Type.JAVA_CLASS, "string value") - .build(); - - for (Map.Entry pair : invalidPairs.entrySet()) { - try { - DisplayData.Type type = pair.getKey(); - Object invalidValue = pair.getValue(); - - type.format(invalidValue); - fail(String.format( - "Expected exception not thrown for invalid %s value: %s", type, invalidValue)); - } catch (ClassCastException e) { - // Expected - } - } - } - - @Test - public void testFormatCompatibleTypes() { - Multimap validPairs = ImmutableMultimap - .builder() - .put(DisplayData.Type.INTEGER, 1234) - .put(DisplayData.Type.INTEGER, 1234L) - .put(DisplayData.Type.FLOAT, 123.4f) - .put(DisplayData.Type.FLOAT, 123.4) - .put(DisplayData.Type.FLOAT, 1234) - .put(DisplayData.Type.FLOAT, 1234L) - .build(); - - for (Map.Entry pair : validPairs.entries()) { - DisplayData.Type type = pair.getKey(); - Object value = pair.getValue(); - - try { - type.format(value); - } catch (ClassCastException e) { - fail(String.format("Failed to format %s for DisplayData.%s", - value.getClass().getSimpleName(), type)); - } - } - } - - @Test - public void testInvalidExplicitItemType() { - HasDisplayData component = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("integer", DisplayData.Type.INTEGER, "foobar")); - } - }; - - thrown.expectCause(isA(ClassCastException.class)); - DisplayData.from(component); - } - - @Test - public void testKnownTypeInference() { - assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234)); - assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234L)); - assertEquals(DisplayData.Type.FLOAT, DisplayData.inferType(12.3)); - assertEquals(DisplayData.Type.FLOAT, DisplayData.inferType(12.3f)); - assertEquals(DisplayData.Type.BOOLEAN, DisplayData.inferType(true)); - assertEquals(DisplayData.Type.TIMESTAMP, DisplayData.inferType(Instant.now())); - assertEquals(DisplayData.Type.DURATION, DisplayData.inferType(Duration.millis(1234))); - assertEquals(DisplayData.Type.JAVA_CLASS, DisplayData.inferType(DisplayDataTest.class)); - assertEquals(DisplayData.Type.STRING, DisplayData.inferType("hello world")); - - assertEquals(null, DisplayData.inferType(null)); - assertEquals(null, DisplayData.inferType(new Object() {})); - } - - @Test - public void testStringFormatting() throws IOException { - final Instant now = Instant.now(); - final Duration oneHour = Duration.standardHours(1); - - HasDisplayData component = new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .add(DisplayData.item("string", "foobar")) - .add(DisplayData.item("integer", 123)) - .add(DisplayData.item("float", 3.14)) - .add(DisplayData.item("boolean", true)) - .add(DisplayData.item("java_class", DisplayDataTest.class)) - .add(DisplayData.item("timestamp", now)) - .add(DisplayData.item("duration", oneHour)); - } - }; - DisplayData data = DisplayData.from(component); - - assertThat(data, hasDisplayItem("string", "foobar")); - assertThat(data, hasDisplayItem("integer", 123)); - assertThat(data, hasDisplayItem("float", 3.14)); - assertThat(data, hasDisplayItem("boolean", true)); - assertThat(data, hasDisplayItem("java_class", DisplayDataTest.class)); - assertThat(data, hasDisplayItem("timestamp", now)); - assertThat(data, hasDisplayItem("duration", oneHour)); - } - - @Test - public void testContextProperlyReset() { - final HasDisplayData subComponent = - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder.add(DisplayData.item("foo", "bar")); - } - }; - - HasDisplayData component = - new HasDisplayData() { - @Override - public void populateDisplayData(DisplayData.Builder builder) { - builder - .include(subComponent) - .add(DisplayData.item("alpha", "bravo")); - } - }; - - DisplayData data = DisplayData.from(component); - assertThat( - data.items(), - hasItem( - allOf( - hasKey("alpha"), - hasNamespace(component.getClass())))); - } - - @Test - public void testFromNull() { - thrown.expect(NullPointerException.class); - DisplayData.from(null); - } - - @Test - public void testIncludeNull() { - thrown.expectCause(isA(NullPointerException.class)); - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.include(null); - } - }); - } - - @Test - public void testIncludeNullNamespace() { - final HasDisplayData subComponent = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - } - }; - - thrown.expectCause(isA(NullPointerException.class)); - DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.include(subComponent, (Class) null); - } - }); - } - - @Test - public void testNullKey() { - thrown.expectCause(isA(NullPointerException.class)); - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item(null, "foo")); - } - }); - } - - @Test - public void testRejectsNullValues() { - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - try { - builder.add(DisplayData.item("key", (String) null)); - throw new RuntimeException("Should throw on null string value"); - } catch (NullPointerException ex) { - // Expected - } - - try { - builder.add(DisplayData.item("key", (Class) null)); - throw new RuntimeException("Should throw on null class value"); - } catch (NullPointerException ex) { - // Expected - } - - try { - builder.add(DisplayData.item("key", (Duration) null)); - throw new RuntimeException("Should throw on null duration value"); - } catch (NullPointerException ex) { - // Expected - } - - try { - builder.add(DisplayData.item("key", (Instant) null)); - throw new RuntimeException("Should throw on null instant value"); - } catch (NullPointerException ex) { - // Expected - } - } - }); - } - - @Test - public void testAcceptsNullOptionalValues() { - DisplayData.from( - new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("key", "value") - .withLabel(null) - .withLinkUrl(null)); - } - }); - - // Should not throw - } - - @Test - public void testJsonSerialization() throws IOException { - final String stringValue = "foobar"; - final int intValue = 1234; - final double floatValue = 123.4; - final boolean boolValue = true; - final int durationMillis = 1234; - - HasDisplayData component = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .add(DisplayData.item("string", stringValue)) - .add(DisplayData.item("long", intValue)) - .add(DisplayData.item("double", floatValue)) - .add(DisplayData.item("boolean", boolValue)) - .add(DisplayData.item("instant", new Instant(0))) - .add(DisplayData.item("duration", Duration.millis(durationMillis))) - .add(DisplayData.item("class", DisplayDataTest.class) - .withLinkUrl("http://abc") - .withLabel("baz")); - } - }; - DisplayData data = DisplayData.from(component); - - JsonNode json = MAPPER.readTree(MAPPER.writeValueAsBytes(data)); - assertThat(json, hasExpectedJson(component, "STRING", "string", quoted(stringValue))); - assertThat(json, hasExpectedJson(component, "INTEGER", "long", intValue)); - assertThat(json, hasExpectedJson(component, "FLOAT", "double", floatValue)); - assertThat(json, hasExpectedJson(component, "BOOLEAN", "boolean", boolValue)); - assertThat(json, hasExpectedJson(component, "DURATION", "duration", durationMillis)); - assertThat(json, hasExpectedJson( - component, "TIMESTAMP", "instant", quoted("1970-01-01T00:00:00.000Z"))); - assertThat(json, hasExpectedJson( - component, "JAVA_CLASS", "class", quoted(DisplayDataTest.class.getName()), - quoted("DisplayDataTest"), "baz", "http://abc")); - } - - /** - * Verify that {@link DisplayData.Builder} can recover from exceptions thrown in user code. - * This is not used within the Beam SDK since we want all code to produce valid DisplayData. - * This test just ensures it is possible to write custom code that does recover. - */ - @Test - public void testCanRecoverFromBuildException() { - final HasDisplayData safeComponent = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.add(DisplayData.item("a", "a")); - } - }; - - final HasDisplayData failingComponent = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - throw new RuntimeException("oh noes!"); - } - }; - - DisplayData displayData = DisplayData.from(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder - .add(DisplayData.item("b", "b")) - .add(DisplayData.item("c", "c")); - - try { - builder.include(failingComponent); - fail("Expected exception not thrown"); - } catch (RuntimeException e) { - // Expected - } - - builder - .include(safeComponent) - .add(DisplayData.item("d", "d")); - } - }); - - assertThat(displayData, hasDisplayItem("a")); - assertThat(displayData, hasDisplayItem("b")); - assertThat(displayData, hasDisplayItem("c")); - assertThat(displayData, hasDisplayItem("d")); - } - - @Test - public void testExceptionMessage() { - final RuntimeException cause = new RuntimeException("oh noes!"); - HasDisplayData component = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - throw cause; - } - }; - - thrown.expectMessage(component.getClass().getName()); - thrown.expectCause(is(cause)); - - DisplayData.from(component); - } - - @Test - public void testExceptionsNotWrappedRecursively() { - final RuntimeException cause = new RuntimeException("oh noes!"); - HasDisplayData component = new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - builder.include(new HasDisplayData() { - @Override - public void populateDisplayData(Builder builder) { - throw cause; - } - }); - } - }; - - thrown.expectCause(is(cause)); - DisplayData.from(component); - } - - private static class IdentityTransform extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection input) { - return input.apply(ParDo.of(new DoFn() { - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - c.output(c.element()); - } - })); - } - } - - private String quoted(Object obj) { - return String.format("\"%s\"", obj); - } - - private Matcher> hasExpectedJson( - HasDisplayData component, String type, String key, Object value) - throws IOException { - return hasExpectedJson(component, type, key, value, null, null, null); - } - - private Matcher> hasExpectedJson( - HasDisplayData component, - String type, - String key, - Object value, - Object shortValue, - String label, - String linkUrl) throws IOException { - Class nsClass = component.getClass(); - - StringBuilder builder = new StringBuilder(); - builder.append("{"); - builder.append(String.format("\"namespace\":\"%s\",", nsClass.getName())); - builder.append(String.format("\"type\":\"%s\",", type)); - builder.append(String.format("\"key\":\"%s\",", key)); - builder.append(String.format("\"value\":%s", value)); - - if (shortValue != null) { - builder.append(String.format(",\"shortValue\":%s", shortValue)); - } - if (label != null) { - builder.append(String.format(",\"label\":\"%s\"", label)); - } - if (linkUrl != null) { - builder.append(String.format(",\"linkUrl\":\"%s\"", linkUrl)); - } - - builder.append("}"); - - JsonNode jsonNode = MAPPER.readTree(builder.toString()); - return hasItem(jsonNode); - } - - private static Matcher> hasLabel(Matcher labelMatcher) { - return new FeatureMatcher, String>( - labelMatcher, "display item with label", "label") { - @Override - protected String featureValueOf(DisplayData.Item actual) { - return actual.getLabel(); - } - }; - } - - private static Matcher> hasUrl(Matcher urlMatcher) { - return new FeatureMatcher, String>( - urlMatcher, "display item with url", "URL") { - @Override - protected String featureValueOf(DisplayData.Item actual) { - return actual.getLinkUrl(); - } - }; - } - - private static Matcher> hasShortValue(Matcher valueStringMatcher) { - return new FeatureMatcher, T>( - valueStringMatcher, "display item with short value", "short value") { - @Override - protected T featureValueOf(DisplayData.Item actual) { - @SuppressWarnings("unchecked") - T shortValue = (T) actual.getShortValue(); - return shortValue; - } - }; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultCoderTest.java deleted file mode 100644 index 7ac278bc8d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultCoderTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import static org.junit.Assert.assertFalse; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.DoubleCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult.CoGbkResultCoder; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; -import com.google.common.collect.ImmutableList; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests the CoGbkResult.CoGbkResultCoder. - */ -@RunWith(JUnit4.class) -public class CoGbkResultCoderTest { - - private static final CoGbkResultSchema TEST_SCHEMA = - new CoGbkResultSchema(TupleTagList.of(new TupleTag()).and( - new TupleTag())); - - private static final UnionCoder TEST_UNION_CODER = - UnionCoder.of(ImmutableList.>of( - StringUtf8Coder.of(), - VarIntCoder.of())); - - private static final UnionCoder COMPATIBLE_UNION_CODER = - UnionCoder.of(ImmutableList.>of( - StringUtf8Coder.of(), - BigEndianIntegerCoder.of())); - - private static final CoGbkResultSchema INCOMPATIBLE_SCHEMA = - new CoGbkResultSchema(TupleTagList.of(new TupleTag()).and( - new TupleTag())); - - private static final UnionCoder INCOMPATIBLE_UNION_CODER = - UnionCoder.of(ImmutableList.>of( - StringUtf8Coder.of(), - DoubleCoder.of())); - - private static final CoGbkResultCoder TEST_CODER = - CoGbkResultCoder.of(TEST_SCHEMA, TEST_UNION_CODER); - - private static final CoGbkResultCoder COMPATIBLE_TEST_CODER = - CoGbkResultCoder.of(TEST_SCHEMA, COMPATIBLE_UNION_CODER); - - private static final CoGbkResultCoder INCOMPATIBLE_TEST_CODER = - CoGbkResultCoder.of(INCOMPATIBLE_SCHEMA, INCOMPATIBLE_UNION_CODER); - - @Test - public void testEquals() { - assertFalse(TEST_CODER.equals(new Object())); - assertFalse(TEST_CODER.equals(COMPATIBLE_TEST_CODER)); - assertFalse(TEST_CODER.equals(INCOMPATIBLE_TEST_CODER)); - } - - @Test - public void testSerializationDeserialization() { - CoderProperties.coderSerializable(TEST_CODER); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultTest.java deleted file mode 100644 index da14d8a412..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResultTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.util.common.Reiterable; -import com.google.cloud.dataflow.sdk.util.common.Reiterator; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.List; - -/** - * Tests the CoGbkResult. - */ -@RunWith(JUnit4.class) -public class CoGbkResultTest { - - @Test - public void testLazyResults() { - runLazyResult(0); - runLazyResult(1); - runLazyResult(3); - runLazyResult(10); - } - - public void runLazyResult(int cacheSize) { - int valueLen = 7; - TestUnionValues values = new TestUnionValues(0, 1, 0, 3, 0, 3, 3); - CoGbkResult result = new CoGbkResult(createSchema(5), values, cacheSize); - assertThat(values.maxPos(), equalTo(Math.min(cacheSize, valueLen))); - assertThat(result.getAll(new TupleTag("tag0")), contains(0, 2, 4)); - assertThat(values.maxPos(), equalTo(valueLen)); - assertThat(result.getAll(new TupleTag("tag3")), contains(3, 5, 6)); - assertThat(result.getAll(new TupleTag("tag2")), emptyIterable()); - assertThat(result.getOnly(new TupleTag("tag1")), equalTo(1)); - assertThat(result.getAll(new TupleTag("tag0")), contains(0, 2, 4)); - } - - private CoGbkResultSchema createSchema(int size) { - List> tags = new ArrayList<>(); - for (int i = 0; i < size; i++) { - tags.add(new TupleTag("tag" + i)); - } - return new CoGbkResultSchema(TupleTagList.of(tags)); - } - - private static class TestUnionValues implements Reiterable { - - final int[] tags; - int maxPos = 0; - - /** - * This will create a list of RawUnionValues whose tags are as given and - * values are increasing starting at 0 (i.e. the index in the constructor). - */ - public TestUnionValues(int... tags) { - this.tags = tags; - } - - /** - * Returns the highest position iterated to so far, useful for ensuring - * laziness. - */ - public int maxPos() { - return maxPos; - } - - @Override - public Reiterator iterator() { - return iterator(0); - } - - public Reiterator iterator(final int start) { - return new Reiterator() { - int pos = start; - - @Override - public boolean hasNext() { - return pos < tags.length; - } - - @Override - public RawUnionValue next() { - maxPos = Math.max(pos + 1, maxPos); - return new RawUnionValue(tags[pos], pos++); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public Reiterator copy() { - return iterator(pos); - } - }; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKeyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKeyTest.java deleted file mode 100644 index 1345289739..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/CoGroupByKeyTest.java +++ /dev/null @@ -1,507 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.Iterables; - -import org.joda.time.Duration; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Tests for CoGroupByKeyTest. Implements Serializable for anonymous DoFns. - */ -@RunWith(JUnit4.class) -public class CoGroupByKeyTest implements Serializable { - - /** - * Converts the given list into a PCollection belonging to the provided - * Pipeline in such a way that coder inference needs to be performed. - */ - private PCollection> createInput(String name, - Pipeline p, List> list) { - return createInput(name, p, list, new ArrayList()); - } - - /** - * Converts the given list with timestamps into a PCollection. - */ - private PCollection> createInput(String name, - Pipeline p, List> list, List timestamps) { - PCollection> input; - if (timestamps.isEmpty()) { - input = p.apply("Create" + name, Create.of(list) - .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of()))); - } else { - input = p.apply("Create" + name, Create.timestamped(list, timestamps) - .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), StringUtf8Coder.of()))); - } - return input - .apply("Identity" + name, ParDo.of(new DoFn, - KV>() { - @Override - public void processElement(ProcessContext c) { - c.output(c.element()); - } - })); - } - - /** - * Returns a {@code PCollection>} containing the result - * of a {@link CoGroupByKey} over 2 {@code PCollection>}, - * where each {@link PCollection} has no duplicate keys and the key sets of - * each {@link PCollection} are intersecting but neither is a subset of the other. - */ - private PCollection> buildGetOnlyGbk( - Pipeline p, - TupleTag tag1, - TupleTag tag2) { - List> list1 = - Arrays.asList( - KV.of(1, "collection1-1"), - KV.of(2, "collection1-2")); - List> list2 = - Arrays.asList( - KV.of(2, "collection2-2"), - KV.of(3, "collection2-3")); - PCollection> collection1 = createInput("CreateList1", p, list1); - PCollection> collection2 = createInput("CreateList2", p, list2); - PCollection> coGbkResults = - KeyedPCollectionTuple.of(tag1, collection1) - .and(tag2, collection2) - .apply(CoGroupByKey.create()); - return coGbkResults; - } - - @Test - public void testCoGroupByKeyGetOnly() { - final TupleTag tag1 = new TupleTag<>(); - final TupleTag tag2 = new TupleTag<>(); - - Pipeline p = TestPipeline.create(); - - PCollection> coGbkResults = - buildGetOnlyGbk(p, tag1, tag2); - - DataflowAssert.thatMap(coGbkResults).satisfies( - new SerializableFunction, Void>() { - @Override - public Void apply(Map results) { - assertEquals("collection1-1", results.get(1).getOnly(tag1)); - assertEquals("collection1-2", results.get(2).getOnly(tag1)); - assertEquals("collection2-2", results.get(2).getOnly(tag2)); - assertEquals("collection2-3", results.get(3).getOnly(tag2)); - return null; - } - }); - - p.run(); - } - - /** - * Returns a {@code PCollection>} containing the - * results of the {@code CoGroupByKey} over three - * {@code PCollection>}, each of which correlates - * a customer id to purchases, addresses, or names, respectively. - */ - private PCollection> buildPurchasesCoGbk( - Pipeline p, - TupleTag purchasesTag, - TupleTag addressesTag, - TupleTag namesTag) { - List> idToPurchases = - Arrays.asList( - KV.of(2, "Boat"), - KV.of(1, "Shoes"), - KV.of(3, "Car"), - KV.of(1, "Book"), - KV.of(10, "Pens"), - KV.of(8, "House"), - KV.of(4, "Suit"), - KV.of(11, "House"), - KV.of(14, "Shoes"), - KV.of(2, "Suit"), - KV.of(8, "Suit Case"), - KV.of(3, "House")); - - List> idToAddress = - Arrays.asList( - KV.of(2, "53 S. 3rd"), - KV.of(10, "383 Jackson Street"), - KV.of(20, "3 W. Arizona"), - KV.of(3, "29 School Rd"), - KV.of(8, "6 Watling Rd")); - - List> idToName = - Arrays.asList( - KV.of(1, "John Smith"), - KV.of(2, "Sally James"), - KV.of(8, "Jeffery Spalding"), - KV.of(20, "Joan Lichtfield")); - - PCollection> purchasesTable = - createInput("CreateIdToPurchases", p, idToPurchases); - - PCollection> addressTable = - createInput("CreateIdToAddress", p, idToAddress); - - PCollection> nameTable = - createInput("CreateIdToName", p, idToName); - - PCollection> coGbkResults = - KeyedPCollectionTuple.of(namesTag, nameTable) - .and(addressesTag, addressTable) - .and(purchasesTag, purchasesTable) - .apply(CoGroupByKey.create()); - return coGbkResults; - } - - /** - * Returns a {@code PCollection>} containing the - * results of the {@code CoGroupByKey} over 2 {@code PCollection>}, - * each of which correlates a customer id to clicks, purchases, respectively. - */ - private PCollection> buildPurchasesCoGbkWithWindowing( - Pipeline p, - TupleTag clicksTag, - TupleTag purchasesTag) { - List> idToClick = - Arrays.asList( - KV.of(1, "Click t0"), - KV.of(2, "Click t2"), - KV.of(1, "Click t4"), - KV.of(1, "Click t6"), - KV.of(2, "Click t8")); - - List> idToPurchases = - Arrays.asList( - KV.of(1, "Boat t1"), - KV.of(1, "Shoesi t2"), - KV.of(1, "Pens t3"), - KV.of(2, "House t4"), - KV.of(2, "Suit t5"), - KV.of(1, "Car t6"), - KV.of(1, "Book t7"), - KV.of(2, "House t8"), - KV.of(2, "Shoes t9"), - KV.of(2, "House t10")); - - PCollection> clicksTable = - createInput("CreateClicks", - p, - idToClick, - Arrays.asList(0L, 2L, 4L, 6L, 8L)) - .apply("WindowClicks", Window.>into( - FixedWindows.of(new Duration(4)))); - - PCollection> purchasesTable = - createInput("CreatePurchases", - p, - idToPurchases, - Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L)) - .apply("WindowPurchases", Window.>into( - FixedWindows.of(new Duration(4)))); - - PCollection> coGbkResults = - KeyedPCollectionTuple.of(clicksTag, clicksTable) - .and(purchasesTag, purchasesTable) - .apply(CoGroupByKey.create()); - return coGbkResults; - } - - @Test - public void testCoGroupByKey() { - final TupleTag namesTag = new TupleTag<>(); - final TupleTag addressesTag = new TupleTag<>(); - final TupleTag purchasesTag = new TupleTag<>(); - - Pipeline p = TestPipeline.create(); - - PCollection> coGbkResults = - buildPurchasesCoGbk(p, purchasesTag, addressesTag, namesTag); - - DataflowAssert.thatMap(coGbkResults).satisfies( - new SerializableFunction, Void>() { - @Override - public Void apply(Map results) { - CoGbkResult result1 = results.get(1); - assertEquals("John Smith", result1.getOnly(namesTag)); - assertThat(result1.getAll(purchasesTag), containsInAnyOrder("Shoes", "Book")); - - CoGbkResult result2 = results.get(2); - assertEquals("Sally James", result2.getOnly(namesTag)); - assertEquals("53 S. 3rd", result2.getOnly(addressesTag)); - assertThat(result2.getAll(purchasesTag), containsInAnyOrder("Suit", "Boat")); - - CoGbkResult result3 = results.get(3); - assertEquals("29 School Rd", result3.getOnly(addressesTag), "29 School Rd"); - assertThat(result3.getAll(purchasesTag), containsInAnyOrder("Car", "House")); - - CoGbkResult result8 = results.get(8); - assertEquals("Jeffery Spalding", result8.getOnly(namesTag)); - assertEquals("6 Watling Rd", result8.getOnly(addressesTag)); - assertThat(result8.getAll(purchasesTag), containsInAnyOrder("House", "Suit Case")); - - CoGbkResult result20 = results.get(20); - assertEquals("Joan Lichtfield", result20.getOnly(namesTag)); - assertEquals("3 W. Arizona", result20.getOnly(addressesTag)); - - assertEquals("383 Jackson Street", results.get(10).getOnly(addressesTag)); - - assertThat(results.get(4).getAll(purchasesTag), containsInAnyOrder("Suit")); - assertThat(results.get(10).getAll(purchasesTag), containsInAnyOrder("Pens")); - assertThat(results.get(11).getAll(purchasesTag), containsInAnyOrder("House")); - assertThat(results.get(14).getAll(purchasesTag), containsInAnyOrder("Shoes")); - - return null; - } - }); - - p.run(); - } - - /** - * A DoFn used in testCoGroupByKeyWithWindowing(), to test processing the - * results of a CoGroupByKey. - */ - private static class ClickOfPurchaseFn extends - DoFn, KV> implements RequiresWindowAccess { - private final TupleTag clicksTag; - - private final TupleTag purchasesTag; - - private ClickOfPurchaseFn( - TupleTag clicksTag, - TupleTag purchasesTag) { - this.clicksTag = clicksTag; - this.purchasesTag = purchasesTag; - } - - @Override - public void processElement(ProcessContext c) { - BoundedWindow w = c.window(); - KV e = c.element(); - CoGbkResult row = e.getValue(); - Iterable clicks = row.getAll(clicksTag); - Iterable purchases = row.getAll(purchasesTag); - for (String click : clicks) { - for (String purchase : purchases) { - c.output(KV.of(click + ":" + purchase, - c.timestamp().getMillis() + ":" + w.maxTimestamp().getMillis())); - } - } - } - } - - - /** - * A DoFn used in testCoGroupByKeyHandleResults(), to test processing the - * results of a CoGroupByKey. - */ - private static class CorrelatePurchaseCountForAddressesWithoutNamesFn extends - DoFn, KV> { - private final TupleTag purchasesTag; - - private final TupleTag addressesTag; - - private final TupleTag namesTag; - - private CorrelatePurchaseCountForAddressesWithoutNamesFn( - TupleTag purchasesTag, - TupleTag addressesTag, - TupleTag namesTag) { - this.purchasesTag = purchasesTag; - this.addressesTag = addressesTag; - this.namesTag = namesTag; - } - - @Override - public void processElement(ProcessContext c) { - KV e = c.element(); - CoGbkResult row = e.getValue(); - // Don't actually care about the id. - Iterable names = row.getAll(namesTag); - if (names.iterator().hasNext()) { - // Nothing to do. There was a name. - return; - } - Iterable addresses = row.getAll(addressesTag); - if (!addresses.iterator().hasNext()) { - // Nothing to do, there was no address. - return; - } - // Buffer the addresses so we can accredit all of them with - // corresponding purchases. All addresses are for the same id, so - // if there are multiple, we apply the same purchase count to all. - ArrayList addressList = new ArrayList(); - for (String address : addresses) { - addressList.add(address); - } - - Iterable purchases = row.getAll(purchasesTag); - - int purchaseCount = Iterables.size(purchases); - - for (String address : addressList) { - c.output(KV.of(address, purchaseCount)); - } - } - } - - /** - * Tests that the consuming DoFn - * (CorrelatePurchaseCountForAddressesWithoutNamesFn) performs as expected. - */ - @SuppressWarnings("unchecked") - @Test - public void testConsumingDoFn() { - TupleTag purchasesTag = new TupleTag<>(); - TupleTag addressesTag = new TupleTag<>(); - TupleTag namesTag = new TupleTag<>(); - - // result1 should get filtered out because it has a name. - CoGbkResult result1 = CoGbkResult - .of(purchasesTag, Arrays.asList("3a", "3b")) - .and(addressesTag, Arrays.asList("2a", "2b")) - .and(namesTag, Arrays.asList("1a")); - // result 2 should be counted because it has an address and purchases. - CoGbkResult result2 = CoGbkResult - .of(purchasesTag, Arrays.asList("5a", "5b")) - .and(addressesTag, Arrays.asList("4a")) - .and(namesTag, new ArrayList()); - // result 3 should not be counted because it has no addresses. - CoGbkResult result3 = CoGbkResult - .of(purchasesTag, Arrays.asList("7a", "7b")) - .and(addressesTag, new ArrayList()) - .and(namesTag, new ArrayList()); - // result 4 should be counted as 0, because it has no purchases. - CoGbkResult result4 = CoGbkResult - .of(purchasesTag, new ArrayList()) - .and(addressesTag, Arrays.asList("8a")) - .and(namesTag, new ArrayList()); - - List> results = - DoFnTester.of( - new CorrelatePurchaseCountForAddressesWithoutNamesFn( - purchasesTag, - addressesTag, - namesTag)) - .processBatch( - KV.of(1, result1), - KV.of(2, result2), - KV.of(3, result3), - KV.of(4, result4)); - - assertThat(results, containsInAnyOrder(KV.of("4a", 2), KV.of("8a", 0))); - } - - /** - * Tests the pipeline end-to-end. Builds the purchases CoGroupByKey, and - * applies CorrelatePurchaseCountForAddressesWithoutNamesFn to the results. - */ - @SuppressWarnings("unchecked") - @Test - @Category(RunnableOnService.class) - public void testCoGroupByKeyHandleResults() { - TupleTag namesTag = new TupleTag<>(); - TupleTag addressesTag = new TupleTag<>(); - TupleTag purchasesTag = new TupleTag<>(); - - Pipeline p = TestPipeline.create(); - - PCollection> coGbkResults = - buildPurchasesCoGbk(p, purchasesTag, addressesTag, namesTag); - - // Do some simple processing on the result of the CoGroupByKey. Count the - // purchases for each address on record that has no associated name. - PCollection> - purchaseCountByKnownAddressesWithoutKnownNames = - coGbkResults.apply(ParDo.of( - new CorrelatePurchaseCountForAddressesWithoutNamesFn( - purchasesTag, addressesTag, namesTag))); - - DataflowAssert.that(purchaseCountByKnownAddressesWithoutKnownNames) - .containsInAnyOrder( - KV.of("29 School Rd", 2), - KV.of("383 Jackson Street", 1)); - p.run(); - } - - /** - * Tests the pipeline end-to-end with FixedWindows. - */ - @SuppressWarnings("unchecked") - @Test - @Category(RunnableOnService.class) - public void testCoGroupByKeyWithWindowing() { - TupleTag clicksTag = new TupleTag<>(); - TupleTag purchasesTag = new TupleTag<>(); - - Pipeline p = TestPipeline.create(); - - PCollection> coGbkResults = - buildPurchasesCoGbkWithWindowing(p, clicksTag, purchasesTag); - - PCollection> - clickOfPurchase = coGbkResults.apply(ParDo.of( - new ClickOfPurchaseFn(clicksTag, purchasesTag))); - DataflowAssert.that(clickOfPurchase) - .containsInAnyOrder( - KV.of("Click t0:Boat t1", "0:3"), - KV.of("Click t0:Shoesi t2", "0:3"), - KV.of("Click t0:Pens t3", "0:3"), - KV.of("Click t4:Car t6", "4:7"), - KV.of("Click t4:Book t7", "4:7"), - KV.of("Click t6:Car t6", "4:7"), - KV.of("Click t6:Book t7", "4:7"), - KV.of("Click t8:House t8", "8:11"), - KV.of("Click t8:Shoes t9", "8:11"), - KV.of("Click t8:House t10", "8:11")); - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoderTest.java deleted file mode 100644 index 8fbe0d4bad..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/join/UnionCoderTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.join; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.DoubleCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.Serializer; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** - * Tests the UnionCoder. - */ -@RunWith(JUnit4.class) -public class UnionCoderTest { - - @Test - public void testSerializationDeserialization() { - UnionCoder newCoder = - UnionCoder.of(Arrays.>asList(StringUtf8Coder.of(), - DoubleCoder.of())); - CloudObject encoding = newCoder.asCloudObject(); - Coder decodedCoder = Serializer.deserialize(encoding, Coder.class); - assertEquals(newCoder, decodedCoder); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java deleted file mode 100644 index 3e8ab333e1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterAllTest.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link AfterAll}. - */ -@RunWith(JUnit4.class) -public class AfterAllTest { - - private SimpleTriggerTester tester; - - @Test - public void testT1FiresFirst() throws Exception { - tester = TriggerTester.forTrigger( - AfterAll.of( - AfterPane.elementCountAtLeast(1), - AfterPane.elementCountAtLeast(2)), - FixedWindows.of(Duration.millis(100))); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - - tester.injectElements(2); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - @Test - public void testT2FiresFirst() throws Exception { - tester = TriggerTester.forTrigger( - AfterAll.of( - AfterPane.elementCountAtLeast(2), - AfterPane.elementCountAtLeast(1)), - FixedWindows.of(Duration.millis(100))); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - - tester.injectElements(2); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - /** - * Tests that the AfterAll properly unsets finished bits when a merge causing it to become - * unfinished. - */ - @Test - public void testOnMergeRewinds() throws Exception { - tester = TriggerTester.forTrigger( - AfterEach.inOrder( - AfterAll.of( - AfterWatermark.pastEndOfWindow(), - AfterPane.elementCountAtLeast(1)), - Repeatedly.forever(AfterPane.elementCountAtLeast(1))), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements(1); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - - tester.injectElements(5); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - - // Finish the AfterAll in the first window - tester.advanceInputWatermark(new Instant(11)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - - // Merge them; the AfterAll should not be finished - tester.mergeWindows(); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - assertFalse(tester.isMarkedFinished(mergedWindow)); - - // Confirm that we are back on the first trigger by probing that it is not ready to fire - // after an element (with merging) - tester.injectElements(3); - tester.mergeWindows(); - assertFalse(tester.shouldFire(mergedWindow)); - - // Fire the AfterAll in the merged window - tester.advanceInputWatermark(new Instant(15)); - assertTrue(tester.shouldFire(mergedWindow)); - tester.fireIfShouldFire(mergedWindow); - - // Confirm that we are on the second trigger by probing - tester.injectElements(2); - tester.mergeWindows(); - assertTrue(tester.shouldFire(mergedWindow)); - tester.fireIfShouldFire(mergedWindow); - tester.injectElements(2); - tester.mergeWindows(); - assertTrue(tester.shouldFire(mergedWindow)); - tester.fireIfShouldFire(mergedWindow); - } - - @Test - public void testFireDeadline() throws Exception { - BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - AfterAll.of(AfterWatermark.pastEndOfWindow(), AfterPane.elementCountAtLeast(1)) - .getWatermarkThatGuaranteesFiring(window)); - } - - @Test - public void testContinuation() throws Exception { - OnceTrigger trigger1 = AfterProcessingTime.pastFirstElementInPane(); - OnceTrigger trigger2 = AfterWatermark.pastEndOfWindow(); - Trigger afterAll = AfterAll.of(trigger1, trigger2); - assertEquals( - AfterAll.of(trigger1.getContinuationTrigger(), trigger2.getContinuationTrigger()), - afterAll.getContinuationTrigger()); - } - - @Test - public void testToString() { - Trigger trigger = AfterAll.of(StubTrigger.named("t1"), StubTrigger.named("t2")); - assertEquals("AfterAll.of(t1, t2)", trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java deleted file mode 100644 index 9c9e79ef55..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterEachTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link AfterEach}. - */ -@RunWith(JUnit4.class) -public class AfterEachTest { - - private SimpleTriggerTester tester; - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - /** - * Tests that the {@link AfterEach} trigger fires and finishes the first trigger then the second. - */ - @Test - public void testAfterEachInSequence() throws Exception { - tester = TriggerTester.forTrigger( - AfterEach.inOrder( - Repeatedly.forever(AfterPane.elementCountAtLeast(2)) - .orFinally(AfterPane.elementCountAtLeast(3)), - Repeatedly.forever(AfterPane.elementCountAtLeast(5)) - .orFinally(AfterWatermark.pastEndOfWindow())), - FixedWindows.of(Duration.millis(10))); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - // AfterCount(2) not ready - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - - // AfterCount(2) ready, not finished - tester.injectElements(2); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - // orFinally(AfterCount(3)) ready and will finish the first - tester.injectElements(1, 2, 3); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - // Now running as the second trigger - assertFalse(tester.shouldFire(window)); - // This quantity of elements would fire and finish if it were erroneously still the first - tester.injectElements(1, 2, 3, 4); - assertFalse(tester.shouldFire(window)); - - // Now fire once - tester.injectElements(5); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - // This time advance the watermark to finish the whole mess. - tester.advanceInputWatermark(new Instant(10)); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - @Test - public void testFireDeadline() throws Exception { - BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - assertEquals(new Instant(9), - AfterEach.inOrder(AfterWatermark.pastEndOfWindow(), - AfterPane.elementCountAtLeast(4)) - .getWatermarkThatGuaranteesFiring(window)); - - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - AfterEach.inOrder(AfterPane.elementCountAtLeast(2), AfterWatermark.pastEndOfWindow()) - .getWatermarkThatGuaranteesFiring(window)); - } - - @Test - public void testContinuation() throws Exception { - OnceTrigger trigger1 = AfterProcessingTime.pastFirstElementInPane(); - OnceTrigger trigger2 = AfterWatermark.pastEndOfWindow(); - Trigger afterEach = AfterEach.inOrder(trigger1, trigger2); - assertEquals( - Repeatedly.forever(AfterFirst.of( - trigger1.getContinuationTrigger(), trigger2.getContinuationTrigger())), - afterEach.getContinuationTrigger()); - } - - @Test - public void testToString() { - Trigger trigger = AfterEach.inOrder( - StubTrigger.named("t1"), - StubTrigger.named("t2"), - StubTrigger.named("t3")); - - assertEquals("AfterEach.inOrder(t1, t2, t3)", trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java deleted file mode 100644 index fc0a5cd5ae..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterFirstTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link AfterFirst}. - */ -@RunWith(JUnit4.class) -public class AfterFirstTest { - - @Mock private OnceTrigger mockTrigger1; - @Mock private OnceTrigger mockTrigger2; - private SimpleTriggerTester tester; - private static Trigger.TriggerContext anyTriggerContext() { - return Mockito..TriggerContext>any(); - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testNeitherShouldFireFixedWindows() throws Exception { - tester = TriggerTester.forTrigger( - AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); - - tester.injectElements(1); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(false); - when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(false); - - assertFalse(tester.shouldFire(window)); // should not fire - assertFalse(tester.isMarkedFinished(window)); // not finished - } - - @Test - public void testOnlyT1ShouldFireFixedWindows() throws Exception { - tester = TriggerTester.forTrigger( - AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); - tester.injectElements(1); - IntervalWindow window = new IntervalWindow(new Instant(1), new Instant(11)); - - when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(true); - when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(false); - - assertTrue(tester.shouldFire(window)); // should fire - - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - @Test - public void testOnlyT2ShouldFireFixedWindows() throws Exception { - tester = TriggerTester.forTrigger( - AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); - tester.injectElements(1); - IntervalWindow window = new IntervalWindow(new Instant(1), new Instant(11)); - - when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(false); - when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(true); - assertTrue(tester.shouldFire(window)); // should fire - - tester.fireIfShouldFire(window); // now finished - assertTrue(tester.isMarkedFinished(window)); - } - - @Test - public void testBothShouldFireFixedWindows() throws Exception { - tester = TriggerTester.forTrigger( - AfterFirst.of(mockTrigger1, mockTrigger2), FixedWindows.of(Duration.millis(10))); - tester.injectElements(1); - IntervalWindow window = new IntervalWindow(new Instant(1), new Instant(11)); - - when(mockTrigger1.shouldFire(anyTriggerContext())).thenReturn(true); - when(mockTrigger2.shouldFire(anyTriggerContext())).thenReturn(true); - assertTrue(tester.shouldFire(window)); // should fire - - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - /** - * Tests that if the first trigger rewinds to be non-finished in the merged window, - * then it becomes the currently active trigger again, with real triggers. - */ - @Test - public void testShouldFireAfterMerge() throws Exception { - tester = TriggerTester.forTrigger( - AfterEach.inOrder( - AfterFirst.of(AfterPane.elementCountAtLeast(5), - AfterWatermark.pastEndOfWindow()), - Repeatedly.forever(AfterPane.elementCountAtLeast(1))), - Sessions.withGapDuration(Duration.millis(10))); - - // Finished the AfterFirst in the first window - tester.injectElements(1); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - assertFalse(tester.shouldFire(firstWindow)); - tester.advanceInputWatermark(new Instant(11)); - assertTrue(tester.shouldFire(firstWindow)); - tester.fireIfShouldFire(firstWindow); - - // Set up second window where it is not done - tester.injectElements(5); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - assertFalse(tester.shouldFire(secondWindow)); - - // Merge them, if the merged window were on the second trigger, it would be ready - tester.mergeWindows(); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - assertFalse(tester.shouldFire(mergedWindow)); - - // Now adding 3 more makes the AfterFirst ready to fire - tester.injectElements(1, 2, 3, 4, 5); - tester.mergeWindows(); - assertTrue(tester.shouldFire(mergedWindow)); - } - - @Test - public void testFireDeadline() throws Exception { - BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - assertEquals(new Instant(9), - AfterFirst.of(AfterWatermark.pastEndOfWindow(), AfterPane.elementCountAtLeast(4)) - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - AfterFirst.of(AfterPane.elementCountAtLeast(2), AfterPane.elementCountAtLeast(1)) - .getWatermarkThatGuaranteesFiring(window)); - } - - @Test - public void testContinuation() throws Exception { - OnceTrigger trigger1 = AfterProcessingTime.pastFirstElementInPane(); - OnceTrigger trigger2 = AfterWatermark.pastEndOfWindow(); - Trigger afterFirst = AfterFirst.of(trigger1, trigger2); - assertEquals( - AfterFirst.of(trigger1.getContinuationTrigger(), trigger2.getContinuationTrigger()), - afterFirst.getContinuationTrigger()); - } - - @Test - public void testToString() { - Trigger trigger = AfterFirst.of(StubTrigger.named("t1"), StubTrigger.named("t2")); - assertEquals("AfterFirst.of(t1, t2)", trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java deleted file mode 100644 index 7274a997d7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterPaneTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link AfterPane}. - */ -@RunWith(JUnit4.class) -public class AfterPaneTest { - - SimpleTriggerTester tester; - /** - * Tests that the trigger does fire when enough elements are in a window, and that it only - * fires that window (no leakage). - */ - @Test - public void testAfterPaneElementCountFixedWindows() throws Exception { - tester = TriggerTester.forTrigger( - AfterPane.elementCountAtLeast(2), - FixedWindows.of(Duration.millis(10))); - - tester.injectElements(1); // [0, 10) - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - assertFalse(tester.shouldFire(window)); - - tester.injectElements(2); // [0, 10) - tester.injectElements(11); // [10, 20) - - assertTrue(tester.shouldFire(window)); // ready to fire - tester.fireIfShouldFire(window); // and finished - assertTrue(tester.isMarkedFinished(window)); - - // But don't finish the other window - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); - } - - @Test - public void testClear() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterPane.elementCountAtLeast(2), - FixedWindows.of(Duration.millis(10))); - - tester.injectElements(1, 2, 3); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - tester.clearState(window); - tester.assertCleared(window); - } - - @Test - public void testAfterPaneElementCountSessions() throws Exception { - tester = TriggerTester.forTrigger( - AfterPane.elementCountAtLeast(2), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements( - 1, // in [1, 11) - 2); // in [2, 12) - - assertFalse(tester.shouldFire(new IntervalWindow(new Instant(1), new Instant(11)))); - assertFalse(tester.shouldFire(new IntervalWindow(new Instant(2), new Instant(12)))); - - tester.mergeWindows(); - - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(12)); - assertTrue(tester.shouldFire(mergedWindow)); - tester.fireIfShouldFire(mergedWindow); - assertTrue(tester.isMarkedFinished(mergedWindow)); - - // Because we closed the previous window, we don't have it around to merge with. So there - // will be a new FIRE_AND_FINISH result. - tester.injectElements( - 7, // in [7, 17) - 9); // in [9, 19) - - tester.mergeWindows(); - - IntervalWindow newMergedWindow = new IntervalWindow(new Instant(7), new Instant(19)); - assertTrue(tester.shouldFire(newMergedWindow)); - tester.fireIfShouldFire(newMergedWindow); - assertTrue(tester.isMarkedFinished(newMergedWindow)); - } - - @Test - public void testFireDeadline() throws Exception { - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - AfterPane.elementCountAtLeast(1).getWatermarkThatGuaranteesFiring( - new IntervalWindow(new Instant(0), new Instant(10)))); - } - - @Test - public void testContinuation() throws Exception { - assertEquals( - AfterPane.elementCountAtLeast(1), - AfterPane.elementCountAtLeast(100).getContinuationTrigger()); - assertEquals( - AfterPane.elementCountAtLeast(1), - AfterPane.elementCountAtLeast(100).getContinuationTrigger().getContinuationTrigger()); - } - - @Test - public void testToString() { - Trigger trigger = AfterPane.elementCountAtLeast(5); - assertEquals("AfterPane.elementCountAtLeast(5)", trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java deleted file mode 100644 index 0a8d534526..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterProcessingTimeTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests the {@link AfterProcessingTime}. - */ -@RunWith(JUnit4.class) -public class AfterProcessingTimeTest { - - /** - * Tests the basic property that the trigger does wait for processing time to be - * far enough advanced. - */ - @Test - public void testAfterProcessingTimeFixedWindows() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterProcessingTime - .pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - FixedWindows.of(windowDuration)); - - tester.advanceProcessingTime(new Instant(10)); - - // Timer at 15 - tester.injectElements(1); - IntervalWindow firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); - tester.advanceProcessingTime(new Instant(12)); - assertFalse(tester.shouldFire(firstWindow)); - - // Load up elements in the next window, timer at 17 for them - tester.injectElements(11, 12, 13); - IntervalWindow secondWindow = new IntervalWindow(new Instant(10), new Instant(20)); - assertFalse(tester.shouldFire(secondWindow)); - - // Not quite time to fire - tester.advanceProcessingTime(new Instant(14)); - assertFalse(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - - // Timer at 19 for these in the first window; it should be ignored since the 15 will fire first - tester.injectElements(2, 3); - - // Advance past the first timer and fire, finishing the first window - tester.advanceProcessingTime(new Instant(16)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - assertTrue(tester.isMarkedFinished(firstWindow)); - - // The next window fires and finishes now - tester.advanceProcessingTime(new Instant(18)); - assertTrue(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(secondWindow); - assertTrue(tester.isMarkedFinished(secondWindow)); - } - - /** - * Tests that when windows merge, if the trigger is waiting for "N millis after the first - * element" that it is relative to the earlier of the two merged windows. - */ - @Test - public void testClear() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterProcessingTime - .pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - FixedWindows.of(Duration.millis(10))); - - tester.injectElements(1, 2, 3); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - tester.clearState(window); - tester.assertCleared(window); - } - - @Test - public void testAfterProcessingTimeWithMergingWindow() throws Exception { - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterProcessingTime - .pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - Sessions.withGapDuration(Duration.millis(10))); - - tester.advanceProcessingTime(new Instant(10)); - tester.injectElements(1); // in [1, 11), timer for 15 - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - assertFalse(tester.shouldFire(firstWindow)); - - tester.advanceProcessingTime(new Instant(12)); - tester.injectElements(3); // in [3, 13), timer for 17 - IntervalWindow secondWindow = new IntervalWindow(new Instant(3), new Instant(13)); - assertFalse(tester.shouldFire(secondWindow)); - - tester.mergeWindows(); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(13)); - - tester.advanceProcessingTime(new Instant(16)); - assertTrue(tester.shouldFire(mergedWindow)); - } - - @Test - public void testFireDeadline() throws Exception { - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - AfterProcessingTime.pastFirstElementInPane().getWatermarkThatGuaranteesFiring( - new IntervalWindow(new Instant(0), new Instant(10)))); - } - - @Test - public void testContinuation() throws Exception { - OnceTrigger firstElementPlus1 = - AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.standardHours(1)); - assertEquals( - new AfterSynchronizedProcessingTime<>(), - firstElementPlus1.getContinuationTrigger()); - } - - /** - * Basic test of compatibility check between identical triggers. - */ - @Test - public void testCompatibilityIdentical() throws Exception { - Trigger t1 = AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(1L)); - Trigger t2 = AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(1L)); - assertTrue(t1.isCompatible(t2)); - } - - @Test - public void testToString() { - Trigger trigger = AfterProcessingTime.pastFirstElementInPane(); - assertEquals("AfterProcessingTime.pastFirstElementInPane()", trigger.toString()); - } - - @Test - public void testWithDelayToString() { - Trigger trigger = AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(5)); - - assertEquals("AfterProcessingTime.pastFirstElementInPane().plusDelayOf(5 minutes)", - trigger.toString()); - } - - @Test - public void testBuiltUpToString() { - Trigger trigger = AfterWatermark.pastEndOfWindow() - .withLateFirings(AfterProcessingTime - .pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(10))) - .buildTrigger(); - - String expected = "AfterWatermark.pastEndOfWindow()" - + ".withLateFirings(AfterProcessingTime" - + ".pastFirstElementInPane()" - + ".plusDelayOf(10 minutes))"; - - assertEquals(expected, trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java deleted file mode 100644 index b37bba42e9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterSynchronizedProcessingTimeTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests the {@link AfterSynchronizedProcessingTime}. - */ -@RunWith(JUnit4.class) -public class AfterSynchronizedProcessingTimeTest { - - private Trigger underTest = - new AfterSynchronizedProcessingTime(); - - @Test - public void testAfterProcessingTimeWithFixedWindows() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterProcessingTime - .pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - FixedWindows.of(windowDuration)); - - tester.advanceProcessingTime(new Instant(10)); - - // Timer at 15 - tester.injectElements(1); - IntervalWindow firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); - tester.advanceProcessingTime(new Instant(12)); - assertFalse(tester.shouldFire(firstWindow)); - - // Load up elements in the next window, timer at 17 for them - tester.injectElements(11, 12, 13); - IntervalWindow secondWindow = new IntervalWindow(new Instant(10), new Instant(20)); - assertFalse(tester.shouldFire(secondWindow)); - - // Not quite time to fire - tester.advanceProcessingTime(new Instant(14)); - assertFalse(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - - // Timer at 19 for these in the first window; it should be ignored since the 15 will fire first - tester.injectElements(2, 3); - - // Advance past the first timer and fire, finishing the first window - tester.advanceProcessingTime(new Instant(16)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - assertTrue(tester.isMarkedFinished(firstWindow)); - - // The next window fires and finishes now - tester.advanceProcessingTime(new Instant(18)); - assertTrue(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(secondWindow); - assertTrue(tester.isMarkedFinished(secondWindow)); - } - - @Test - public void testAfterProcessingTimeWithMergingWindow() throws Exception { - Duration windowDuration = Duration.millis(10); - SimpleTriggerTester tester = TriggerTester.forTrigger( - AfterProcessingTime - .pastFirstElementInPane() - .plusDelayOf(Duration.millis(5)), - Sessions.withGapDuration(windowDuration)); - - tester.advanceProcessingTime(new Instant(10)); - tester.injectElements(1); // in [1, 11), timer for 15 - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - assertFalse(tester.shouldFire(firstWindow)); - - tester.advanceProcessingTime(new Instant(12)); - tester.injectElements(3); // in [3, 13), timer for 17 - IntervalWindow secondWindow = new IntervalWindow(new Instant(3), new Instant(13)); - assertFalse(tester.shouldFire(secondWindow)); - - tester.mergeWindows(); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(13)); - - tester.advanceProcessingTime(new Instant(16)); - assertTrue(tester.shouldFire(mergedWindow)); - } - - @Test - public void testFireDeadline() throws Exception { - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - underTest.getWatermarkThatGuaranteesFiring( - new IntervalWindow(new Instant(0), new Instant(10)))); - } - - @Test - public void testContinuation() throws Exception { - assertEquals(underTest, underTest.getContinuationTrigger()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java deleted file mode 100644 index cca90db4c8..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermarkTest.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -/** - * Tests the {@link AfterWatermark} triggers. - */ -@RunWith(JUnit4.class) -public class AfterWatermarkTest { - - @Mock private OnceTrigger mockEarly; - @Mock private OnceTrigger mockLate; - - private SimpleTriggerTester tester; - private static Trigger.TriggerContext anyTriggerContext() { - return Mockito..TriggerContext>any(); - } - private static Trigger.OnElementContext anyElementContext() { - return Mockito..OnElementContext>any(); - } - - private void injectElements(int... elements) throws Exception { - for (int element : elements) { - doNothing().when(mockEarly).onElement(anyElementContext()); - doNothing().when(mockLate).onElement(anyElementContext()); - tester.injectElements(element); - } - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - public void testRunningAsTrigger(OnceTrigger mockTrigger, IntervalWindow window) - throws Exception { - - // Don't fire due to mock saying no - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - assertFalse(tester.shouldFire(window)); // not ready - - // Fire due to mock trigger; early trigger is required to be a OnceTrigger - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - assertTrue(tester.shouldFire(window)); // ready - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - } - - @Test - public void testEarlyAndAtWatermark() throws Exception { - tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(mockEarly), - FixedWindows.of(Duration.millis(100))); - - injectElements(1); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - - testRunningAsTrigger(mockEarly, window); - - // Fire due to watermark - when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(false); - tester.advanceInputWatermark(new Instant(100)); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - @Test - public void testAtWatermarkAndLate() throws Exception { - tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow() - .withLateFirings(mockLate), - FixedWindows.of(Duration.millis(100))); - - injectElements(1); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - - // No early firing, just double checking - when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(true); - assertFalse(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - // Fire due to watermark - when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(false); - tester.advanceInputWatermark(new Instant(100)); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - testRunningAsTrigger(mockLate, window); - } - - @Test - public void testEarlyAndAtWatermarkAndLate() throws Exception { - tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(mockEarly) - .withLateFirings(mockLate), - FixedWindows.of(Duration.millis(100))); - - injectElements(1); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - - testRunningAsTrigger(mockEarly, window); - - // Fire due to watermark - when(mockEarly.shouldFire(anyTriggerContext())).thenReturn(false); - tester.advanceInputWatermark(new Instant(100)); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - testRunningAsTrigger(mockLate, window); - } - - /** - * Tests that if the EOW is finished in both as well as the merged window, then - * it is finished in the merged result. - * - *

              Because windows are discarded when a trigger finishes, we need to embed this - * in a sequence in order to check that it is re-activated. So this test is potentially - * sensitive to other triggers' correctness. - */ - @Test - public void testOnMergeAlreadyFinished() throws Exception { - tester = TriggerTester.forTrigger( - AfterEach.inOrder( - AfterWatermark.pastEndOfWindow(), - Repeatedly.forever(AfterPane.elementCountAtLeast(1))), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements(1); - tester.injectElements(5); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - - // Finish the AfterWatermark.pastEndOfWindow() trigger in both windows - tester.advanceInputWatermark(new Instant(15)); - assertTrue(tester.shouldFire(firstWindow)); - assertTrue(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - tester.fireIfShouldFire(secondWindow); - - // Confirm that we are on the second trigger by probing - assertFalse(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - tester.injectElements(1); - tester.injectElements(5); - assertTrue(tester.shouldFire(firstWindow)); - assertTrue(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - tester.fireIfShouldFire(secondWindow); - - // Merging should leave it finished - tester.mergeWindows(); - - // Confirm that we are on the second trigger by probing - assertFalse(tester.shouldFire(mergedWindow)); - tester.injectElements(1); - assertTrue(tester.shouldFire(mergedWindow)); - } - - /** - * Tests that the trigger rewinds to be non-finished in the merged window. - * - *

              Because windows are discarded when a trigger finishes, we need to embed this - * in a sequence in order to check that it is re-activated. So this test is potentially - * sensitive to other triggers' correctness. - */ - @Test - public void testOnMergeRewinds() throws Exception { - tester = TriggerTester.forTrigger( - AfterEach.inOrder( - AfterWatermark.pastEndOfWindow(), - Repeatedly.forever(AfterPane.elementCountAtLeast(1))), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements(1); - tester.injectElements(5); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - - // Finish the AfterWatermark.pastEndOfWindow() trigger in only the first window - tester.advanceInputWatermark(new Instant(11)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - - // Confirm that we are on the second trigger by probing - assertFalse(tester.shouldFire(firstWindow)); - tester.injectElements(1); - assertTrue(tester.shouldFire(firstWindow)); - tester.fireIfShouldFire(firstWindow); - - // Merging should re-activate the watermark trigger in the merged window - tester.mergeWindows(); - - // Confirm that we are not on the second trigger by probing - assertFalse(tester.shouldFire(mergedWindow)); - tester.injectElements(1); - assertFalse(tester.shouldFire(mergedWindow)); - - // And confirm that advancing the watermark fires again - tester.advanceInputWatermark(new Instant(15)); - assertTrue(tester.shouldFire(mergedWindow)); - } - - /** - * Tests that if the EOW is finished in both as well as the merged window, then - * it is finished in the merged result. - * - *

              Because windows are discarded when a trigger finishes, we need to embed this - * in a sequence in order to check that it is re-activated. So this test is potentially - * sensitive to other triggers' correctness. - */ - @Test - public void testEarlyAndLateOnMergeAlreadyFinished() throws Exception { - tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterPane.elementCountAtLeast(100)) - .withLateFirings(AfterPane.elementCountAtLeast(1)), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements(1); - tester.injectElements(5); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - - // Finish the AfterWatermark.pastEndOfWindow() bit of the trigger in both windows - tester.advanceInputWatermark(new Instant(15)); - assertTrue(tester.shouldFire(firstWindow)); - assertTrue(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - tester.fireIfShouldFire(secondWindow); - - // Confirm that we are on the late trigger by probing - assertFalse(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - tester.injectElements(1); - tester.injectElements(5); - assertTrue(tester.shouldFire(firstWindow)); - assertTrue(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - tester.fireIfShouldFire(secondWindow); - - // Merging should leave it on the late trigger - tester.mergeWindows(); - - // Confirm that we are on the late trigger by probing - assertFalse(tester.shouldFire(mergedWindow)); - tester.injectElements(1); - assertTrue(tester.shouldFire(mergedWindow)); - } - - /** - * Tests that the trigger rewinds to be non-finished in the merged window. - * - *

              Because windows are discarded when a trigger finishes, we need to embed this - * in a sequence in order to check that it is re-activated. So this test is potentially - * sensitive to other triggers' correctness. - */ - @Test - public void testEarlyAndLateOnMergeRewinds() throws Exception { - tester = TriggerTester.forTrigger( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterPane.elementCountAtLeast(100)) - .withLateFirings(AfterPane.elementCountAtLeast(1)), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements(1); - tester.injectElements(5); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - - // Finish the AfterWatermark.pastEndOfWindow() bit of the trigger in only the first window - tester.advanceInputWatermark(new Instant(11)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - tester.fireIfShouldFire(firstWindow); - - // Confirm that we are on the late trigger by probing - assertFalse(tester.shouldFire(firstWindow)); - tester.injectElements(1); - assertTrue(tester.shouldFire(firstWindow)); - tester.fireIfShouldFire(firstWindow); - - // Merging should re-activate the early trigger in the merged window - tester.mergeWindows(); - - // Confirm that we are not on the second trigger by probing - assertFalse(tester.shouldFire(mergedWindow)); - tester.injectElements(1); - assertFalse(tester.shouldFire(mergedWindow)); - - // And confirm that advancing the watermark fires again - tester.advanceInputWatermark(new Instant(15)); - assertTrue(tester.shouldFire(mergedWindow)); - } - - @Test - public void testFromEndOfWindowToString() { - Trigger trigger = AfterWatermark.pastEndOfWindow(); - assertEquals("AfterWatermark.pastEndOfWindow()", trigger.toString()); - } - - @Test - public void testEarlyFiringsToString() { - Trigger trigger = AfterWatermark.pastEndOfWindow() - .withEarlyFirings(StubTrigger.named("t1")) - .buildTrigger(); - - assertEquals("AfterWatermark.pastEndOfWindow().withEarlyFirings(t1)", trigger.toString()); - } - - @Test - public void testLateFiringsToString() { - Trigger trigger = AfterWatermark.pastEndOfWindow() - .withLateFirings(StubTrigger.named("t1")) - .buildTrigger(); - - assertEquals("AfterWatermark.pastEndOfWindow().withLateFirings(t1)", trigger.toString()); - } - - @Test - public void testEarlyAndLateFiringsToString() { - Trigger trigger = AfterWatermark.pastEndOfWindow() - .withEarlyFirings(StubTrigger.named("t1")) - .withLateFirings(StubTrigger.named("t2")) - .buildTrigger(); - - assertEquals("AfterWatermark.pastEndOfWindow().withEarlyFirings(t1).withLateFirings(t2)", - trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java deleted file mode 100644 index 8b1fbcec85..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/CalendarWindowsTest.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.joda.time.DateTime; -import org.joda.time.DateTimeConstants; -import org.joda.time.DateTimeZone; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Tests for CalendarWindows WindowFn. - */ -@RunWith(JUnit4.class) -public class CalendarWindowsTest { - - private static Instant makeTimestamp(int year, int month, int day, int hours, int minutes) { - return new DateTime(year, month, day, hours, minutes, DateTimeZone.UTC).toInstant(); - } - - @Test - public void testDays() throws Exception { - Map> expected = new HashMap<>(); - - final List timestamps = Arrays.asList( - makeTimestamp(2014, 1, 1, 0, 0).getMillis(), - makeTimestamp(2014, 1, 1, 23, 59).getMillis(), - - makeTimestamp(2014, 1, 2, 0, 0).getMillis(), - makeTimestamp(2014, 1, 2, 5, 5).getMillis(), - - makeTimestamp(2015, 1, 1, 0, 0).getMillis(), - makeTimestamp(2015, 1, 1, 5, 5).getMillis()); - - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 1, 1, 0, 0), - makeTimestamp(2014, 1, 2, 0, 0)), - set(timestamps.get(0), timestamps.get(1))); - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 1, 2, 0, 0), - makeTimestamp(2014, 1, 3, 0, 0)), - set(timestamps.get(2), timestamps.get(3))); - - expected.put( - new IntervalWindow( - makeTimestamp(2015, 1, 1, 0, 0), - makeTimestamp(2015, 1, 2, 0, 0)), - set(timestamps.get(4), timestamps.get(5))); - - assertEquals(expected, runWindowFn(CalendarWindows.days(1), timestamps)); - } - - @Test - public void testWeeks() throws Exception { - Map> expected = new HashMap<>(); - - final List timestamps = Arrays.asList( - makeTimestamp(2014, 1, 1, 0, 0).getMillis(), - makeTimestamp(2014, 1, 5, 5, 5).getMillis(), - - makeTimestamp(2014, 1, 8, 0, 0).getMillis(), - makeTimestamp(2014, 1, 12, 5, 5).getMillis(), - - makeTimestamp(2015, 1, 1, 0, 0).getMillis(), - makeTimestamp(2015, 1, 6, 5, 5).getMillis()); - - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 1, 1, 0, 0), - makeTimestamp(2014, 1, 8, 0, 0)), - set(timestamps.get(0), timestamps.get(1))); - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 1, 8, 0, 0), - makeTimestamp(2014, 1, 15, 0, 0)), - set(timestamps.get(2), timestamps.get(3))); - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 12, 31, 0, 0), - makeTimestamp(2015, 1, 7, 0, 0)), - set(timestamps.get(4), timestamps.get(5))); - - assertEquals(expected, - runWindowFn(CalendarWindows.weeks(1, DateTimeConstants.WEDNESDAY), timestamps)); - } - - @Test - public void testMonths() throws Exception { - Map> expected = new HashMap<>(); - - final List timestamps = Arrays.asList( - makeTimestamp(2014, 1, 1, 0, 0).getMillis(), - makeTimestamp(2014, 1, 31, 5, 5).getMillis(), - - makeTimestamp(2014, 2, 1, 0, 0).getMillis(), - makeTimestamp(2014, 2, 15, 5, 5).getMillis(), - - makeTimestamp(2015, 1, 1, 0, 0).getMillis(), - makeTimestamp(2015, 1, 31, 5, 5).getMillis()); - - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 1, 1, 0, 0), - makeTimestamp(2014, 2, 1, 0, 0)), - set(timestamps.get(0), timestamps.get(1))); - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 2, 1, 0, 0), - makeTimestamp(2014, 3, 1, 0, 0)), - set(timestamps.get(2), timestamps.get(3))); - - expected.put( - new IntervalWindow( - makeTimestamp(2015, 1, 1, 0, 0), - makeTimestamp(2015, 2, 1, 0, 0)), - set(timestamps.get(4), timestamps.get(5))); - - assertEquals(expected, - runWindowFn(CalendarWindows.months(1), timestamps)); - } - - @Test - public void testMultiMonths() throws Exception { - Map> expected = new HashMap<>(); - - final List timestamps = Arrays.asList( - makeTimestamp(2014, 3, 5, 0, 0).getMillis(), - makeTimestamp(2014, 10, 4, 23, 59).getMillis(), - - makeTimestamp(2014, 10, 5, 0, 0).getMillis(), - makeTimestamp(2015, 3, 1, 0, 0).getMillis(), - - makeTimestamp(2016, 1, 5, 0, 0).getMillis(), - makeTimestamp(2016, 1, 31, 5, 5).getMillis()); - - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 3, 5, 0, 0), - makeTimestamp(2014, 10, 5, 0, 0)), - set(timestamps.get(0), timestamps.get(1))); - - expected.put( - new IntervalWindow( - makeTimestamp(2014, 10, 5, 0, 0), - makeTimestamp(2015, 5, 5, 0, 0)), - set(timestamps.get(2), timestamps.get(3))); - - expected.put( - new IntervalWindow( - makeTimestamp(2015, 12, 5, 0, 0), - makeTimestamp(2016, 7, 5, 0, 0)), - set(timestamps.get(4), timestamps.get(5))); - - assertEquals(expected, runWindowFn( - CalendarWindows.months(7).withStartingMonth(2014, 3).beginningOnDay(5), timestamps)); - } - - @Test - public void testYears() throws Exception { - Map> expected = new HashMap<>(); - - final List timestamps = Arrays.asList( - makeTimestamp(2000, 5, 5, 0, 0).getMillis(), - makeTimestamp(2010, 5, 4, 23, 59).getMillis(), - - makeTimestamp(2010, 5, 5, 0, 0).getMillis(), - makeTimestamp(2015, 3, 1, 0, 0).getMillis(), - - makeTimestamp(2052, 1, 5, 0, 0).getMillis(), - makeTimestamp(2060, 5, 4, 5, 5).getMillis()); - - - expected.put( - new IntervalWindow( - makeTimestamp(2000, 5, 5, 0, 0), - makeTimestamp(2010, 5, 5, 0, 0)), - set(timestamps.get(0), timestamps.get(1))); - - expected.put( - new IntervalWindow( - makeTimestamp(2010, 5, 5, 0, 0), - makeTimestamp(2020, 5, 5, 0, 0)), - set(timestamps.get(2), timestamps.get(3))); - - expected.put( - new IntervalWindow( - makeTimestamp(2050, 5, 5, 0, 0), - makeTimestamp(2060, 5, 5, 0, 0)), - set(timestamps.get(4), timestamps.get(5))); - - assertEquals(expected, runWindowFn( - CalendarWindows.years(10).withStartingYear(2000).beginningOnDay(5, 5), timestamps)); - } - - @Test - public void testTimeZone() throws Exception { - Map> expected = new HashMap<>(); - - DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles"); - - final List timestamps = Arrays.asList( - new DateTime(2014, 1, 1, 0, 0, timeZone).getMillis(), - new DateTime(2014, 1, 1, 23, 59, timeZone).getMillis(), - - new DateTime(2014, 1, 2, 8, 0, DateTimeZone.UTC).getMillis(), - new DateTime(2014, 1, 3, 7, 59, DateTimeZone.UTC).getMillis()); - - expected.put( - new IntervalWindow( - new DateTime(2014, 1, 1, 0, 0, timeZone).toInstant(), - new DateTime(2014, 1, 2, 0, 0, timeZone).toInstant()), - set(timestamps.get(0), timestamps.get(1))); - - expected.put( - new IntervalWindow( - new DateTime(2014, 1, 2, 0, 0, timeZone).toInstant(), - new DateTime(2014, 1, 3, 0, 0, timeZone).toInstant()), - set(timestamps.get(2), timestamps.get(3))); - - assertEquals(expected, runWindowFn( - CalendarWindows.days(1).withTimeZone(timeZone), - timestamps)); - } - - @Test - public void testDisplayData() { - DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles"); - Instant jan1 = new DateTime(1990, 1, 1, 0, 0, timeZone).toInstant(); - - CalendarWindows.DaysWindows daysWindow = CalendarWindows.days(5) - .withStartingDay(1990, 1, 1) - .withTimeZone(timeZone); - DisplayData daysDisplayData = DisplayData.from(daysWindow); - assertThat(daysDisplayData, hasDisplayItem("numDays", 5)); - assertThat(daysDisplayData, hasDisplayItem("startDate", jan1)); - - CalendarWindows.MonthsWindows monthsWindow = CalendarWindows.months(2) - .withStartingMonth(1990, 1) - .withTimeZone(timeZone); - DisplayData monthsDisplayData = DisplayData.from(monthsWindow); - assertThat(monthsDisplayData, hasDisplayItem("numMonths", 2)); - assertThat(monthsDisplayData, hasDisplayItem("startDate", jan1)); - - CalendarWindows.YearsWindows yearsWindow = CalendarWindows.years(4) - .withStartingYear(1990) - .withTimeZone(timeZone); - DisplayData yearsDisplayData = DisplayData.from(yearsWindow); - assertThat(yearsDisplayData, hasDisplayItem("numYears", 4)); - assertThat(yearsDisplayData, hasDisplayItem("startDate", jan1)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java deleted file mode 100644 index bdc31e27fd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/DefaultTriggerTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests the {@link DefaultTrigger}, which should be equivalent to - * {@code Repeatedly.forever(AfterWatermark.pastEndOfWindow())}. - */ -@RunWith(JUnit4.class) -public class DefaultTriggerTest { - - SimpleTriggerTester tester; - - @Test - public void testDefaultTriggerFixedWindows() throws Exception { - tester = TriggerTester.forTrigger( - DefaultTrigger.of(), - FixedWindows.of(Duration.millis(100))); - - tester.injectElements( - 1, // [0, 100) - 101); // [100, 200) - - IntervalWindow firstWindow = new IntervalWindow(new Instant(0), new Instant(100)); - IntervalWindow secondWindow = new IntervalWindow(new Instant(100), new Instant(200)); - - // Advance the watermark almost to the end of the first window. - tester.advanceInputWatermark(new Instant(99)); - assertFalse(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - - // Advance watermark past end of the first window, which is then ready - tester.advanceInputWatermark(new Instant(100)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - - // Fire, but the first window is still allowed to fire - tester.fireIfShouldFire(firstWindow); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - - // Advance watermark to 200, then both are ready - tester.advanceInputWatermark(new Instant(200)); - assertTrue(tester.shouldFire(firstWindow)); - assertTrue(tester.shouldFire(secondWindow)); - - assertFalse(tester.isMarkedFinished(firstWindow)); - assertFalse(tester.isMarkedFinished(secondWindow)); - } - - @Test - public void testDefaultTriggerSlidingWindows() throws Exception { - tester = TriggerTester.forTrigger( - DefaultTrigger.of(), - SlidingWindows.of(Duration.millis(100)).every(Duration.millis(50))); - - tester.injectElements( - 1, // [-50, 50), [0, 100) - 50); // [0, 100), [50, 150) - - IntervalWindow firstWindow = new IntervalWindow(new Instant(-50), new Instant(50)); - IntervalWindow secondWindow = new IntervalWindow(new Instant(0), new Instant(100)); - IntervalWindow thirdWindow = new IntervalWindow(new Instant(50), new Instant(150)); - - assertFalse(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - assertFalse(tester.shouldFire(thirdWindow)); - - // At 50, the first becomes ready; it stays ready after firing - tester.advanceInputWatermark(new Instant(50)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - assertFalse(tester.shouldFire(thirdWindow)); - tester.fireIfShouldFire(firstWindow); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - assertFalse(tester.shouldFire(thirdWindow)); - - // At 99, the first is still the only one ready - tester.advanceInputWatermark(new Instant(99)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - assertFalse(tester.shouldFire(thirdWindow)); - - // At 100, the first and second are ready - tester.advanceInputWatermark(new Instant(100)); - assertTrue(tester.shouldFire(firstWindow)); - assertTrue(tester.shouldFire(secondWindow)); - assertFalse(tester.shouldFire(thirdWindow)); - tester.fireIfShouldFire(firstWindow); - - assertFalse(tester.isMarkedFinished(firstWindow)); - assertFalse(tester.isMarkedFinished(secondWindow)); - assertFalse(tester.isMarkedFinished(thirdWindow)); - } - - @Test - public void testDefaultTriggerSessions() throws Exception { - tester = TriggerTester.forTrigger( - DefaultTrigger.of(), - Sessions.withGapDuration(Duration.millis(100))); - - tester.injectElements( - 1, // [1, 101) - 50); // [50, 150) - tester.mergeWindows(); - - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(101)); - IntervalWindow secondWindow = new IntervalWindow(new Instant(50), new Instant(150)); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(150)); - - // Not ready in any window yet - tester.advanceInputWatermark(new Instant(100)); - assertFalse(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - assertFalse(tester.shouldFire(mergedWindow)); - - // The first window is "ready": the caller owns knowledge of which windows are merged away - tester.advanceInputWatermark(new Instant(149)); - assertTrue(tester.shouldFire(firstWindow)); - assertFalse(tester.shouldFire(secondWindow)); - assertFalse(tester.shouldFire(mergedWindow)); - - // Now ready on all windows - tester.advanceInputWatermark(new Instant(150)); - assertTrue(tester.shouldFire(firstWindow)); - assertTrue(tester.shouldFire(secondWindow)); - assertTrue(tester.shouldFire(mergedWindow)); - - // Ensure it repeats - tester.fireIfShouldFire(mergedWindow); - assertTrue(tester.shouldFire(mergedWindow)); - - assertFalse(tester.isMarkedFinished(mergedWindow)); - } - - @Test - public void testFireDeadline() throws Exception { - assertEquals(new Instant(9), DefaultTrigger.of().getWatermarkThatGuaranteesFiring( - new IntervalWindow(new Instant(0), new Instant(10)))); - assertEquals(GlobalWindow.INSTANCE.maxTimestamp(), - DefaultTrigger.of().getWatermarkThatGuaranteesFiring(GlobalWindow.INSTANCE)); - } - - @Test - public void testContinuation() throws Exception { - assertEquals(DefaultTrigger.of(), DefaultTrigger.of().getContinuationTrigger()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java deleted file mode 100644 index e143597c52..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/FixedWindowsTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Tests for FixedWindows WindowFn. - */ -@RunWith(JUnit4.class) -public class FixedWindowsTest { - - @Test - public void testSimpleFixedWindow() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(0), new Instant(10)), set(1, 2, 5, 9)); - expected.put(new IntervalWindow(new Instant(10), new Instant(20)), set(10, 11)); - expected.put(new IntervalWindow(new Instant(100), new Instant(110)), set(100)); - assertEquals( - expected, - runWindowFn( - FixedWindows.of(new Duration(10)), - Arrays.asList(1L, 2L, 5L, 9L, 10L, 11L, 100L))); - } - - @Test - public void testFixedOffsetWindow() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(-5), new Instant(5)), set(1, 2)); - expected.put(new IntervalWindow(new Instant(5), new Instant(15)), set(5, 9, 10, 11)); - expected.put(new IntervalWindow(new Instant(95), new Instant(105)), set(100)); - assertEquals( - expected, - runWindowFn( - FixedWindows.of(new Duration(10)).withOffset(new Duration(5)), - Arrays.asList(1L, 2L, 5L, 9L, 10L, 11L, 100L))); - } - - @Test - public void testTimeUnit() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(-5000), new Instant(5000)), set(1, 2, 1000)); - expected.put(new IntervalWindow(new Instant(5000), new Instant(15000)), set(5000, 5001, 10000)); - assertEquals( - expected, - runWindowFn( - FixedWindows.of(Duration.standardSeconds(10)).withOffset(Duration.standardSeconds(5)), - Arrays.asList(1L, 2L, 1000L, 5000L, 5001L, 10000L))); - } - - void checkConstructionFailure(int size, int offset) { - try { - FixedWindows.of(Duration.standardSeconds(size)).withOffset(Duration.standardSeconds(offset)); - fail("should have failed"); - } catch (IllegalArgumentException e) { - assertThat(e.toString(), - containsString("FixedWindows WindowingStrategies must have 0 <= offset < size")); - } - } - - @Test - public void testInvalidInput() throws Exception { - checkConstructionFailure(-1, 0); - checkConstructionFailure(1, 2); - checkConstructionFailure(1, -1); - } - - @Test - public void testEquality() { - assertTrue(FixedWindows.of(new Duration(10)).isCompatible(FixedWindows.of(new Duration(10)))); - assertTrue( - FixedWindows.of(new Duration(10)).isCompatible( - FixedWindows.of(new Duration(10)))); - assertTrue( - FixedWindows.of(new Duration(10)).isCompatible( - FixedWindows.of(new Duration(10)))); - - assertFalse(FixedWindows.of(new Duration(10)).isCompatible(FixedWindows.of(new Duration(20)))); - assertFalse(FixedWindows.of(new Duration(10)).isCompatible( - FixedWindows.of(new Duration(20)))); - } - - @Test - public void testValidOutputTimes() throws Exception { - for (long timestamp : Arrays.asList(200, 800, 700)) { - WindowFnTestUtils.validateGetOutputTimestamp( - FixedWindows.of(new Duration(500)), timestamp); - } - } - - @Test - public void testDisplayData() { - Duration offset = Duration.standardSeconds(1234); - Duration size = Duration.standardSeconds(2345); - - FixedWindows fixedWindows = FixedWindows.of(size).withOffset(offset); - DisplayData displayData = DisplayData.from(fixedWindows); - - assertThat(displayData, hasDisplayItem("size", size)); - assertThat(displayData, hasDisplayItem("offset", offset)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindowTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindowTest.java deleted file mode 100644 index 968063e45f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/IntervalWindowTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.InstantCoder; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.common.collect.Lists; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** - * Tests for {@link Window}. - */ -@RunWith(JUnit4.class) -public class IntervalWindowTest { - - private static final Coder TEST_CODER = IntervalWindow.getCoder(); - - private static final List TEST_VALUES = Lists.newArrayList( - new IntervalWindow(new Instant(0), new Instant(0)), - new IntervalWindow(new Instant(0), new Instant(1000)), - new IntervalWindow(new Instant(-1000), new Instant(735)), - new IntervalWindow(new Instant(350), new Instant(60 * 60 * 1000)), - new IntervalWindow(new Instant(0), new Instant(24 * 60 * 60 * 1000)), - new IntervalWindow( - Instant.parse("2015-04-01T00:00:00Z"), Instant.parse("2015-04-01T11:45:13Z"))); - - @Test - public void testBasicEncoding() throws Exception { - for (IntervalWindow window : TEST_VALUES) { - CoderProperties.coderDecodeEncodeEqual(TEST_CODER, window); - } - } - - /** - * This is a change detector test for the sizes of encoded windows. Since these are present - * for every element of every windowed PCollection, the size matters. - * - *

              This test documents the expectation that encoding as a (endpoint, duration) pair - * using big endian for the endpoint and variable length long for the duration should be about 25% - * smaller than encoding two big endian Long values. - */ - @Test - public void testLengthsOfEncodingChoices() throws Exception { - Instant start = Instant.parse("2015-04-01T00:00:00Z"); - Instant minuteEnd = Instant.parse("2015-04-01T00:01:00Z"); - Instant hourEnd = Instant.parse("2015-04-01T01:00:00Z"); - Instant dayEnd = Instant.parse("2015-04-02T00:00:00Z"); - - Coder instantCoder = InstantCoder.of(); - byte[] encodedStart = CoderUtils.encodeToByteArray(instantCoder, start); - byte[] encodedMinuteEnd = CoderUtils.encodeToByteArray(instantCoder, minuteEnd); - byte[] encodedHourEnd = CoderUtils.encodeToByteArray(instantCoder, hourEnd); - byte[] encodedDayEnd = CoderUtils.encodeToByteArray(instantCoder, dayEnd); - - byte[] encodedMinuteWindow = CoderUtils.encodeToByteArray( - TEST_CODER, new IntervalWindow(start, minuteEnd)); - byte[] encodedHourWindow = CoderUtils.encodeToByteArray( - TEST_CODER, new IntervalWindow(start, hourEnd)); - byte[] encodedDayWindow = CoderUtils.encodeToByteArray( - TEST_CODER, new IntervalWindow(start, dayEnd)); - - assertThat(encodedMinuteWindow.length, - equalTo(encodedStart.length + encodedMinuteEnd.length - 5)); - assertThat(encodedHourWindow.length, - equalTo(encodedStart.length + encodedHourEnd.length - 4)); - assertThat(encodedDayWindow.length, - equalTo(encodedStart.length + encodedDayEnd.length - 4)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java deleted file mode 100644 index 02bcff9fe0..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/NeverTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link Never}. - */ -@RunWith(JUnit4.class) -public class NeverTest { - private TriggerTester.SimpleTriggerTester triggerTester; - - @Before - public void setup() throws Exception { - triggerTester = - TriggerTester.forTrigger( - Never.ever(), FixedWindows.of(Duration.standardMinutes(5))); - } - - @Test - public void falseAfterEndOfWindow() throws Exception { - triggerTester.injectElements(TimestampedValue.of(1, new Instant(1))); - IntervalWindow window = - new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardMinutes(5))); - assertThat(triggerTester.shouldFire(window), is(false)); - triggerTester.advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE); - assertThat(triggerTester.shouldFire(window), is(false)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java deleted file mode 100644 index 6a734fdb54..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/OrFinallyTriggerTest.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger; -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link OrFinallyTrigger}. - */ -@RunWith(JUnit4.class) -public class OrFinallyTriggerTest { - - private SimpleTriggerTester tester; - - /** - * Tests that for {@code OrFinally(actual, ...)} when {@code actual} - * fires and finishes, the {@code OrFinally} also fires and finishes. - */ - @Test - public void testActualFiresAndFinishes() throws Exception { - tester = TriggerTester.forTrigger( - new OrFinallyTrigger<>( - AfterPane.elementCountAtLeast(2), - AfterPane.elementCountAtLeast(100)), - FixedWindows.of(Duration.millis(100))); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - - // Not yet firing - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - assertFalse(tester.isMarkedFinished(window)); - - // The actual fires and finishes - tester.injectElements(2); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - /** - * Tests that for {@code OrFinally(actual, ...)} when {@code actual} - * fires but does not finish, the {@code OrFinally} also fires and also does not - * finish. - */ - @Test - public void testActualFiresOnly() throws Exception { - tester = TriggerTester.forTrigger( - new OrFinallyTrigger<>( - Repeatedly.forever(AfterPane.elementCountAtLeast(2)), - AfterPane.elementCountAtLeast(100)), - FixedWindows.of(Duration.millis(100))); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100)); - - // Not yet firing - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - assertFalse(tester.isMarkedFinished(window)); - - // The actual fires but does not finish - tester.injectElements(2); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - // And again - tester.injectElements(3, 4); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - } - - /** - * Tests that if the first trigger rewinds to be non-finished in the merged window, - * then it becomes the currently active trigger again, with real triggers. - */ - @Test - public void testShouldFireAfterMerge() throws Exception { - tester = TriggerTester.forTrigger( - AfterEach.inOrder( - AfterPane.elementCountAtLeast(5) - .orFinally(AfterWatermark.pastEndOfWindow()), - Repeatedly.forever(AfterPane.elementCountAtLeast(1))), - Sessions.withGapDuration(Duration.millis(10))); - - // Finished the orFinally in the first window - tester.injectElements(1); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - assertFalse(tester.shouldFire(firstWindow)); - tester.advanceInputWatermark(new Instant(11)); - assertTrue(tester.shouldFire(firstWindow)); - tester.fireIfShouldFire(firstWindow); - - // Set up second window where it is not done - tester.injectElements(5); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - assertFalse(tester.shouldFire(secondWindow)); - - // Merge them, if the merged window were on the second trigger, it would be ready - tester.mergeWindows(); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - assertFalse(tester.shouldFire(mergedWindow)); - - // Now adding 3 more makes the main trigger ready to fire - tester.injectElements(1, 2, 3, 4, 5); - tester.mergeWindows(); - assertTrue(tester.shouldFire(mergedWindow)); - } - - /** - * Tests that for {@code OrFinally(actual, until)} when {@code actual} - * fires but does not finish, then {@code until} fires and finishes, the - * whole thing fires and finished. - */ - @Test - public void testActualFiresButUntilFinishes() throws Exception { - tester = TriggerTester.forTrigger( - new OrFinallyTrigger( - Repeatedly.forever(AfterPane.elementCountAtLeast(2)), - AfterPane.elementCountAtLeast(3)), - FixedWindows.of(Duration.millis(10))); - - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - // Before any firing - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - assertFalse(tester.isMarkedFinished(window)); - - // The actual fires but doesn't finish - tester.injectElements(2); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.isMarkedFinished(window)); - - // The until fires and finishes; the trigger is finished - tester.injectElements(3); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertTrue(tester.isMarkedFinished(window)); - } - - @Test - public void testFireDeadline() throws Exception { - BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - - assertEquals(new Instant(9), - Repeatedly.forever(AfterWatermark.pastEndOfWindow()) - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(new Instant(9), Repeatedly.forever(AfterWatermark.pastEndOfWindow()) - .orFinally(AfterPane.elementCountAtLeast(1)) - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(new Instant(9), Repeatedly.forever(AfterPane.elementCountAtLeast(1)) - .orFinally(AfterWatermark.pastEndOfWindow()) - .getWatermarkThatGuaranteesFiring(window)); - assertEquals(new Instant(9), - AfterPane.elementCountAtLeast(100) - .orFinally(AfterWatermark.pastEndOfWindow()) - .getWatermarkThatGuaranteesFiring(window)); - - assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, - Repeatedly.forever(AfterPane.elementCountAtLeast(1)) - .orFinally(AfterPane.elementCountAtLeast(10)) - .getWatermarkThatGuaranteesFiring(window)); - } - - @Test - public void testContinuation() throws Exception { - OnceTrigger triggerA = AfterProcessingTime.pastFirstElementInPane(); - OnceTrigger triggerB = AfterWatermark.pastEndOfWindow(); - Trigger aOrFinallyB = triggerA.orFinally(triggerB); - Trigger bOrFinallyA = triggerB.orFinally(triggerA); - assertEquals( - Repeatedly.forever( - triggerA.getContinuationTrigger().orFinally(triggerB.getContinuationTrigger())), - aOrFinallyB.getContinuationTrigger()); - assertEquals( - Repeatedly.forever( - triggerB.getContinuationTrigger().orFinally(triggerA.getContinuationTrigger())), - bOrFinallyA.getContinuationTrigger()); - } - - @Test - public void testToString() { - Trigger trigger = StubTrigger.named("t1").orFinally(StubTrigger.named("t2")); - assertEquals("t1.orFinally(t2)", trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfoTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfoTest.java deleted file mode 100644 index 62ac2a1fad..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/PaneInfoTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link PaneInfo}. - */ -@RunWith(JUnit4.class) -public class PaneInfoTest { - - @Test - public void testInterned() throws Exception { - assertSame( - PaneInfo.createPane(true, true, Timing.EARLY), - PaneInfo.createPane(true, true, Timing.EARLY)); - } - - @Test - public void testEncodingRoundTrip() throws Exception { - Coder coder = PaneInfo.PaneInfoCoder.INSTANCE; - for (Timing timing : Timing.values()) { - long onTimeIndex = timing == Timing.EARLY ? -1 : 37; - CoderProperties.coderDecodeEncodeEqual( - coder, PaneInfo.createPane(false, false, timing, 389, onTimeIndex)); - CoderProperties.coderDecodeEncodeEqual( - coder, PaneInfo.createPane(false, true, timing, 5077, onTimeIndex)); - CoderProperties.coderDecodeEncodeEqual( - coder, PaneInfo.createPane(true, false, timing, 0, 0)); - CoderProperties.coderDecodeEncodeEqual( - coder, PaneInfo.createPane(true, true, timing, 0, 0)); - } - } - - @Test - public void testEncodings() { - assertEquals("PaneInfo encoding assumes that there are only 4 Timing values.", - 4, Timing.values().length); - assertEquals("PaneInfo encoding should remain the same.", - 0x0, PaneInfo.createPane(false, false, Timing.EARLY, 1, -1).getEncodedByte()); - assertEquals("PaneInfo encoding should remain the same.", - 0x1, PaneInfo.createPane(true, false, Timing.EARLY).getEncodedByte()); - assertEquals("PaneInfo encoding should remain the same.", - 0x3, PaneInfo.createPane(true, true, Timing.EARLY).getEncodedByte()); - assertEquals("PaneInfo encoding should remain the same.", - 0x7, PaneInfo.createPane(true, true, Timing.ON_TIME).getEncodedByte()); - assertEquals("PaneInfo encoding should remain the same.", - 0xB, PaneInfo.createPane(true, true, Timing.LATE).getEncodedByte()); - assertEquals("PaneInfo encoding should remain the same.", - 0xF, PaneInfo.createPane(true, true, Timing.UNKNOWN).getEncodedByte()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java deleted file mode 100644 index 0a0f99cbf9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.util.TriggerTester; -import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link Repeatedly}. - */ -@RunWith(JUnit4.class) -public class RepeatedlyTest { - - @Mock private Trigger mockTrigger; - private SimpleTriggerTester tester; - private static Trigger.TriggerContext anyTriggerContext() { - return Mockito..TriggerContext>any(); - } - - public void setUp(WindowFn windowFn) throws Exception { - MockitoAnnotations.initMocks(this); - tester = TriggerTester.forTrigger(Repeatedly.forever(mockTrigger), windowFn); - } - - /** - * Tests that onElement correctly passes the data on to the subtrigger. - */ - @Test - public void testOnElement() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - tester.injectElements(37); - verify(mockTrigger).onElement(Mockito..OnElementContext>any()); - } - - /** - * Tests that the repeatedly is ready to fire whenever the subtrigger is ready. - */ - @Test - public void testShouldFire() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - assertTrue(tester.shouldFire(new IntervalWindow(new Instant(0), new Instant(10)))); - - when(mockTrigger.shouldFire(Mockito..TriggerContext>any())) - .thenReturn(false); - assertFalse(tester.shouldFire(new IntervalWindow(new Instant(0), new Instant(10)))); - } - - /** - * Tests that the watermark that guarantees firing is that of the subtrigger. - */ - @Test - public void testFireDeadline() throws Exception { - setUp(FixedWindows.of(Duration.millis(10))); - IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); - Instant arbitraryInstant = new Instant(34957849); - - when(mockTrigger.getWatermarkThatGuaranteesFiring(Mockito.any())) - .thenReturn(arbitraryInstant); - - assertThat( - Repeatedly.forever(mockTrigger).getWatermarkThatGuaranteesFiring(window), - equalTo(arbitraryInstant)); - } - - @Test - public void testContinuation() throws Exception { - Trigger trigger = AfterProcessingTime.pastFirstElementInPane(); - Trigger repeatedly = Repeatedly.forever(trigger); - assertEquals( - Repeatedly.forever(trigger.getContinuationTrigger()), repeatedly.getContinuationTrigger()); - assertEquals( - Repeatedly.forever(trigger.getContinuationTrigger().getContinuationTrigger()), - repeatedly.getContinuationTrigger().getContinuationTrigger()); - } - - @Test - public void testShouldFireAfterMerge() throws Exception { - tester = TriggerTester.forTrigger( - Repeatedly.forever(AfterPane.elementCountAtLeast(2)), - Sessions.withGapDuration(Duration.millis(10))); - - tester.injectElements(1); - IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); - assertFalse(tester.shouldFire(firstWindow)); - - tester.injectElements(5); - IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); - assertFalse(tester.shouldFire(secondWindow)); - - // Merge them, if the merged window were on the second trigger, it would be ready - tester.mergeWindows(); - IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); - assertTrue(tester.shouldFire(mergedWindow)); - } - - @Test - public void testRepeatedlyAfterFirstElementCount() throws Exception { - SimpleTriggerTester tester = - TriggerTester.forTrigger( - Repeatedly.forever( - AfterFirst.of( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(15)), - AfterPane.elementCountAtLeast(5))), - new GlobalWindows()); - - GlobalWindow window = GlobalWindow.INSTANCE; - - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - - tester.injectElements(2, 3, 4, 5); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.shouldFire(window)); - } - - @Test - public void testRepeatedlyAfterFirstProcessingTime() throws Exception { - SimpleTriggerTester tester = - TriggerTester.forTrigger( - Repeatedly.forever( - AfterFirst.of( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(15)), - AfterPane.elementCountAtLeast(5))), - new GlobalWindows()); - - GlobalWindow window = GlobalWindow.INSTANCE; - - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - - tester.advanceProcessingTime(new Instant(0).plus(Duration.standardMinutes(15))); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.shouldFire(window)); - } - - @Test - public void testRepeatedlyElementCount() throws Exception { - SimpleTriggerTester tester = - TriggerTester.forTrigger( - Repeatedly.forever(AfterPane.elementCountAtLeast(5)), - new GlobalWindows()); - - GlobalWindow window = GlobalWindow.INSTANCE; - - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - - tester.injectElements(2, 3, 4, 5); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.shouldFire(window)); - } - - @Test - public void testRepeatedlyProcessingTime() throws Exception { - SimpleTriggerTester tester = - TriggerTester.forTrigger( - Repeatedly.forever( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(Duration.standardMinutes(15))), - new GlobalWindows()); - - GlobalWindow window = GlobalWindow.INSTANCE; - - tester.injectElements(1); - assertFalse(tester.shouldFire(window)); - - tester.advanceProcessingTime(new Instant(0).plus(Duration.standardMinutes(15))); - assertTrue(tester.shouldFire(window)); - tester.fireIfShouldFire(window); - assertFalse(tester.shouldFire(window)); - } - - - @Test - public void testToString() { - Trigger trigger = Repeatedly.forever(new StubTrigger() { - @Override - public String toString() { - return "innerTrigger"; - } - }); - - assertEquals("Repeatedly.forever(innerTrigger)", trigger.toString()); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java deleted file mode 100644 index 4649a6bcc7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SessionsTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Tests for Sessions WindowFn. - */ -@RunWith(JUnit4.class) -public class SessionsTest { - - @Test - public void testSimple() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(0), new Instant(10)), set(0)); - expected.put(new IntervalWindow(new Instant(10), new Instant(20)), set(10)); - expected.put(new IntervalWindow(new Instant(101), new Instant(111)), set(101)); - assertEquals( - expected, - runWindowFn( - Sessions.withGapDuration(new Duration(10)), - Arrays.asList(0L, 10L, 101L))); - } - - @Test - public void testConsecutive() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(1), new Instant(19)), set(1, 2, 5, 9)); - expected.put(new IntervalWindow(new Instant(100), new Instant(111)), set(100, 101)); - assertEquals( - expected, - runWindowFn( - Sessions.withGapDuration(new Duration(10)), - Arrays.asList(1L, 2L, 5L, 9L, 100L, 101L))); - } - - @Test - public void testMerging() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(1), new Instant(40)), set(1, 10, 15, 22, 30)); - expected.put(new IntervalWindow(new Instant(95), new Instant(111)), set(95, 100, 101)); - assertEquals( - expected, - runWindowFn( - Sessions.withGapDuration(new Duration(10)), - Arrays.asList(1L, 15L, 30L, 100L, 101L, 95L, 22L, 10L))); - } - - @Test - public void testTimeUnit() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(1), new Instant(2000)), set(1, 2, 1000)); - expected.put(new IntervalWindow(new Instant(5000), new Instant(6001)), set(5000, 5001)); - expected.put(new IntervalWindow(new Instant(10000), new Instant(11000)), set(10000)); - assertEquals( - expected, - runWindowFn( - Sessions.withGapDuration(Duration.standardSeconds(1)), - Arrays.asList(1L, 2L, 1000L, 5000L, 5001L, 10000L))); - } - - @Test - public void testEquality() { - assertTrue( - Sessions.withGapDuration(new Duration(10)).isCompatible( - Sessions.withGapDuration(new Duration(10)))); - assertTrue( - Sessions.withGapDuration(new Duration(10)).isCompatible( - Sessions.withGapDuration(new Duration(20)))); - } - - /** - * Validates that the output timestamp for aggregate data falls within the acceptable range. - */ - @Test - public void testValidOutputTimes() throws Exception { - for (long timestamp : Arrays.asList(200, 800, 700)) { - WindowFnTestUtils.validateGetOutputTimestamp( - Sessions.withGapDuration(Duration.millis(500)), timestamp); - } - } - - /** - * Test to confirm that {@link Sessions} with the default {@link OutputTimeFn} holds up the - * watermark potentially indefinitely. - */ - @Test - public void testInvalidOutputAtEarliest() throws Exception { - try { - WindowFnTestUtils.validateGetOutputTimestamps( - Sessions.withGapDuration(Duration.millis(10)), - OutputTimeFns.outputAtEarliestInputTimestamp(), - ImmutableList.of( - (List) ImmutableList.of(1L, 3L), - (List) ImmutableList.of(0L, 5L, 10L, 15L, 20L))); - } catch (AssertionError exc) { - assertThat( - exc.getMessage(), - // These are the non-volatile pieces of the error message that a timestamp - // was not greater than what it should be. - allOf(containsString("a value greater than"), containsString("was less than"))); - } - } - - /** - * When a user explicitly requests per-key aggregate values have their derived timestamp to be - * the end of the window (instead of the earliest possible), the session here should not hold - * each other up, even though they overlap. - */ - @Test - public void testValidOutputAtEndTimes() throws Exception { - WindowFnTestUtils.validateGetOutputTimestamps( - Sessions.withGapDuration(Duration.millis(10)), - OutputTimeFns.outputAtEndOfWindow(), - ImmutableList.of( - (List) ImmutableList.of(1L, 3L), - (List) ImmutableList.of(0L, 5L, 10L, 15L, 20L))); - } - - @Test - public void testDisplayData() { - Duration gapDuration = Duration.standardMinutes(234); - Sessions session = Sessions.withGapDuration(gapDuration); - assertThat(DisplayData.from(session), - hasDisplayItem("gapDuration", gapDuration)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java deleted file mode 100644 index 2aae07804c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/SlidingWindowsTest.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.runWindowFn; -import static com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils.set; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.testing.WindowFnTestUtils; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Tests for the SlidingWindows WindowFn. - */ -@RunWith(JUnit4.class) -public class SlidingWindowsTest { - - @Test - public void testSimple() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(-5), new Instant(5)), set(1, 2)); - expected.put(new IntervalWindow(new Instant(0), new Instant(10)), set(1, 2, 5, 9)); - expected.put(new IntervalWindow(new Instant(5), new Instant(15)), set(5, 9, 10, 11)); - expected.put(new IntervalWindow(new Instant(10), new Instant(20)), set(10, 11)); - assertEquals( - expected, - runWindowFn( - SlidingWindows.of(new Duration(10)).every(new Duration(5)), - Arrays.asList(1L, 2L, 5L, 9L, 10L, 11L))); - } - - @Test - public void testSlightlyOverlapping() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(-5), new Instant(2)), set(1)); - expected.put(new IntervalWindow(new Instant(0), new Instant(7)), set(1, 2, 5)); - expected.put(new IntervalWindow(new Instant(5), new Instant(12)), set(5, 9, 10, 11)); - expected.put(new IntervalWindow(new Instant(10), new Instant(17)), set(10, 11)); - assertEquals( - expected, - runWindowFn( - SlidingWindows.of(new Duration(7)).every(new Duration(5)), - Arrays.asList(1L, 2L, 5L, 9L, 10L, 11L))); - } - - @Test - public void testElidings() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(0), new Instant(3)), set(1, 2)); - expected.put(new IntervalWindow(new Instant(10), new Instant(13)), set(10, 11)); - expected.put(new IntervalWindow(new Instant(100), new Instant(103)), set(100)); - assertEquals( - expected, - runWindowFn( - // Only look at the first 3 millisecs of every 10-millisec interval. - SlidingWindows.of(new Duration(3)).every(new Duration(10)), - Arrays.asList(1L, 2L, 3L, 5L, 9L, 10L, 11L, 100L))); - } - - @Test - public void testOffset() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(-8), new Instant(2)), set(1)); - expected.put(new IntervalWindow(new Instant(-3), new Instant(7)), set(1, 2, 5)); - expected.put(new IntervalWindow(new Instant(2), new Instant(12)), set(2, 5, 9, 10, 11)); - expected.put(new IntervalWindow(new Instant(7), new Instant(17)), set(9, 10, 11)); - assertEquals( - expected, - runWindowFn( - SlidingWindows.of(new Duration(10)).every(new Duration(5)).withOffset(new Duration(2)), - Arrays.asList(1L, 2L, 5L, 9L, 10L, 11L))); - } - - @Test - public void testTimeUnit() throws Exception { - Map> expected = new HashMap<>(); - expected.put(new IntervalWindow(new Instant(-5000), new Instant(5000)), set(1, 2, 1000)); - expected.put(new IntervalWindow(new Instant(0), new Instant(10000)), - set(1, 2, 1000, 5000, 5001)); - expected.put(new IntervalWindow(new Instant(5000), new Instant(15000)), set(5000, 5001, 10000)); - expected.put(new IntervalWindow(new Instant(10000), new Instant(20000)), set(10000)); - assertEquals( - expected, - runWindowFn( - SlidingWindows.of(Duration.standardSeconds(10)).every(Duration.standardSeconds(5)), - Arrays.asList(1L, 2L, 1000L, 5000L, 5001L, 10000L))); - } - - @Test - public void testDefaultPeriods() throws Exception { - assertEquals(Duration.standardHours(1), - SlidingWindows.getDefaultPeriod(Duration.standardDays(1))); - assertEquals(Duration.standardHours(1), - SlidingWindows.getDefaultPeriod(Duration.standardHours(2))); - assertEquals(Duration.standardMinutes(1), - SlidingWindows.getDefaultPeriod(Duration.standardHours(1))); - assertEquals(Duration.standardMinutes(1), - SlidingWindows.getDefaultPeriod(Duration.standardMinutes(10))); - assertEquals(Duration.standardSeconds(1), - SlidingWindows.getDefaultPeriod(Duration.standardMinutes(1))); - assertEquals(Duration.standardSeconds(1), - SlidingWindows.getDefaultPeriod(Duration.standardSeconds(10))); - assertEquals(Duration.millis(1), - SlidingWindows.getDefaultPeriod(Duration.standardSeconds(1))); - assertEquals(Duration.millis(1), - SlidingWindows.getDefaultPeriod(Duration.millis(10))); - assertEquals(Duration.millis(1), - SlidingWindows.getDefaultPeriod(Duration.millis(1))); - } - - @Test - public void testEquality() { - assertTrue( - SlidingWindows.of(new Duration(10)).isCompatible( - SlidingWindows.of(new Duration(10)))); - assertTrue( - SlidingWindows.of(new Duration(10)).isCompatible( - SlidingWindows.of(new Duration(10)))); - - assertFalse(SlidingWindows.of(new Duration(10)).isCompatible( - SlidingWindows.of(new Duration(20)))); - assertFalse(SlidingWindows.of(new Duration(10)).isCompatible( - SlidingWindows.of(new Duration(20)))); - } - - @Test - public void testGetSideInputWindow() { - // [40, 1040), [340, 1340), [640, 1640) ... - SlidingWindows slidingWindows = SlidingWindows.of(new Duration(1000)) - .every(new Duration(300)).withOffset(new Duration(40)); - // Prior - assertEquals( - new IntervalWindow(new Instant(340), new Instant(1340)), - slidingWindows.getSideInputWindow( - new IntervalWindow(new Instant(0), new Instant(1041)))); - assertEquals( - new IntervalWindow(new Instant(340), new Instant(1340)), - slidingWindows.getSideInputWindow( - new IntervalWindow(new Instant(0), new Instant(1339)))); - // Align - assertEquals( - new IntervalWindow(new Instant(340), new Instant(1340)), - slidingWindows.getSideInputWindow( - new IntervalWindow(new Instant(0), new Instant(1340)))); - // After - assertEquals( - new IntervalWindow(new Instant(640), new Instant(1640)), - slidingWindows.getSideInputWindow( - new IntervalWindow(new Instant(0), new Instant(1341)))); - } - - @Test - public void testValidOutputTimes() throws Exception { - for (long timestamp : Arrays.asList(200, 800, 499, 500, 501, 700, 1000)) { - WindowFnTestUtils.validateGetOutputTimestamp( - SlidingWindows.of(new Duration(1000)).every(new Duration(500)), timestamp); - } - } - - @Test - public void testOutputTimesNonInterference() throws Exception { - for (long timestamp : Arrays.asList(200, 800, 700)) { - WindowFnTestUtils.validateNonInterferingOutputTimes( - SlidingWindows.of(new Duration(1000)).every(new Duration(500)), timestamp); - } - } - - @Test - public void testDisplayData() { - Duration windowSize = Duration.standardSeconds(1234); - Duration offset = Duration.standardSeconds(2345); - Duration period = Duration.standardSeconds(3456); - - SlidingWindows slidingWindowFn = SlidingWindows - .of(windowSize) - .every(period) - .withOffset(offset); - - DisplayData displayData = DisplayData.from(slidingWindowFn); - assertThat(displayData, hasDisplayItem("size", windowSize)); - assertThat(displayData, hasDisplayItem("period", period)); - assertThat(displayData, hasDisplayItem("offset", offset)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java deleted file mode 100644 index 43fa83cfe1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/StubTrigger.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.common.collect.Lists; - -import org.joda.time.Instant; - -import java.util.List; - -/** - * No-op {@link OnceTrigger} implementation for testing. - */ -abstract class StubTrigger extends Trigger.OnceTrigger { - /** - * Create a stub {@link Trigger} instance which returns the specified name on {@link #toString()}. - */ - static StubTrigger named(final String name) { - return new StubTrigger() { - @Override - public String toString() { - return name; - } - }; - } - - protected StubTrigger() { - super(Lists.>newArrayList()); - } - - @Override - protected void onOnlyFiring(TriggerContext context) throws Exception { - } - - @Override - public void onElement(OnElementContext c) throws Exception { - } - - @Override - public void onMerge(OnMergeContext c) throws Exception { - } - - @Override - public boolean shouldFire(TriggerContext context) throws Exception { - return false; - } - - @Override - protected Trigger getContinuationTrigger(List> continuationTriggers) { - return null; - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(BoundedWindow window) { - return null; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java deleted file mode 100644 index c6ee3517cc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/TriggerTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for {@link Trigger}. - */ -@RunWith(JUnit4.class) -public class TriggerTest { - - @Test - public void testTriggerToString() throws Exception { - assertEquals("AfterWatermark.pastEndOfWindow()", AfterWatermark.pastEndOfWindow().toString()); - assertEquals("Repeatedly.forever(AfterWatermark.pastEndOfWindow())", - Repeatedly.forever(AfterWatermark.pastEndOfWindow()).toString()); - } - - @Test - public void testIsCompatible() throws Exception { - assertTrue(new Trigger1(null).isCompatible(new Trigger1(null))); - assertTrue(new Trigger1(Arrays.>asList(new Trigger2(null))) - .isCompatible(new Trigger1(Arrays.>asList(new Trigger2(null))))); - - assertFalse(new Trigger1(null).isCompatible(new Trigger2(null))); - assertFalse(new Trigger1(Arrays.>asList(new Trigger1(null))) - .isCompatible(new Trigger1(Arrays.>asList(new Trigger2(null))))); - } - - private static class Trigger1 extends Trigger { - - private Trigger1(List> subTriggers) { - super(subTriggers); - } - - @Override - public void onElement(Trigger.OnElementContext c) { } - - @Override - public void onMerge(Trigger.OnMergeContext c) { } - - @Override - protected Trigger getContinuationTrigger( - List> continuationTriggers) { - return null; - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(IntervalWindow window) { - return null; - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return false; - } - - @Override - public void onFire(Trigger.TriggerContext context) throws Exception { } - } - - private static class Trigger2 extends Trigger { - - private Trigger2(List> subTriggers) { - super(subTriggers); - } - - @Override - public void onElement(Trigger.OnElementContext c) { } - - @Override - public void onMerge(Trigger.OnMergeContext c) { } - - @Override - protected Trigger getContinuationTrigger( - List> continuationTriggers) { - return null; - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(IntervalWindow window) { - return null; - } - - @Override - public boolean shouldFire(Trigger.TriggerContext context) throws Exception { - return false; - } - - @Override - public void onFire(Trigger.TriggerContext context) throws Exception { } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java deleted file mode 100644 index 060202a742..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowTest.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.hasKey; -import static com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers.includesDisplayDataFrom; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.isOneOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; - -import org.hamcrest.Matchers; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; - -import java.io.Serializable; - -/** - * Tests for {@link Window}. - */ -@RunWith(JUnit4.class) -public class WindowTest implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testWindowIntoSetWindowfn() { - WindowingStrategy strategy = TestPipeline.create() - .apply(Create.of("hello", "world").withCoder(StringUtf8Coder.of())) - .apply(Window.into(FixedWindows.of(Duration.standardMinutes(10)))) - .getWindowingStrategy(); - assertTrue(strategy.getWindowFn() instanceof FixedWindows); - assertTrue(strategy.getTrigger().getSpec() instanceof DefaultTrigger); - assertEquals(AccumulationMode.DISCARDING_FIRED_PANES, strategy.getMode()); - } - - @Test - public void testWindowIntoTriggersAndAccumulating() { - FixedWindows fixed10 = FixedWindows.of(Duration.standardMinutes(10)); - Repeatedly trigger = Repeatedly.forever(AfterPane.elementCountAtLeast(5)); - WindowingStrategy strategy = TestPipeline.create() - .apply(Create.of("hello", "world").withCoder(StringUtf8Coder.of())) - .apply(Window.into(fixed10) - .triggering(trigger) - .accumulatingFiredPanes() - .withAllowedLateness(Duration.ZERO)) - .getWindowingStrategy(); - - assertEquals(fixed10, strategy.getWindowFn()); - assertEquals(trigger, strategy.getTrigger().getSpec()); - assertEquals(AccumulationMode.ACCUMULATING_FIRED_PANES, strategy.getMode()); - } - - @Test - public void testWindowPropagatesEachPart() { - FixedWindows fixed10 = FixedWindows.of(Duration.standardMinutes(10)); - Repeatedly trigger = Repeatedly.forever(AfterPane.elementCountAtLeast(5)); - WindowingStrategy strategy = TestPipeline.create() - .apply(Create.of("hello", "world").withCoder(StringUtf8Coder.of())) - .apply("Mode", Window.accumulatingFiredPanes()) - .apply("Lateness", Window.withAllowedLateness(Duration.standardDays(1))) - .apply("Trigger", Window.triggering(trigger)) - .apply("Window", Window.into(fixed10)) - .getWindowingStrategy(); - - assertEquals(fixed10, strategy.getWindowFn()); - assertEquals(trigger, strategy.getTrigger().getSpec()); - assertEquals(AccumulationMode.ACCUMULATING_FIRED_PANES, strategy.getMode()); - assertEquals(Duration.standardDays(1), strategy.getAllowedLateness()); - } - - @Test - public void testWindowIntoPropagatesLateness() { - FixedWindows fixed10 = FixedWindows.of(Duration.standardMinutes(10)); - FixedWindows fixed25 = FixedWindows.of(Duration.standardMinutes(25)); - WindowingStrategy strategy = TestPipeline.create() - .apply(Create.of("hello", "world").withCoder(StringUtf8Coder.of())) - .apply(Window.named("WindowInto10").into(fixed10) - .withAllowedLateness(Duration.standardDays(1)) - .triggering(Repeatedly.forever(AfterPane.elementCountAtLeast(5))) - .accumulatingFiredPanes()) - .apply(Window.named("WindowInto25").into(fixed25)) - .getWindowingStrategy(); - - assertEquals(Duration.standardDays(1), strategy.getAllowedLateness()); - assertEquals(fixed25, strategy.getWindowFn()); - } - - @Test - public void testWindowGetName() { - assertEquals("Window.Into()", - Window.into(FixedWindows.of(Duration.standardMinutes(10))).getName()); - } - - @Test - public void testNonDeterministicWindowCoder() throws NonDeterministicException { - FixedWindows mockWindowFn = Mockito.mock(FixedWindows.class); - @SuppressWarnings({"unchecked", "rawtypes"}) - Class> coderClazz = (Class) Coder.class; - Coder mockCoder = Mockito.mock(coderClazz); - when(mockWindowFn.windowCoder()).thenReturn(mockCoder); - NonDeterministicException toBeThrown = - new NonDeterministicException(mockCoder, "Its just not deterministic."); - Mockito.doThrow(toBeThrown).when(mockCoder).verifyDeterministic(); - - thrown.expect(IllegalArgumentException.class); - thrown.expectCause(Matchers.sameInstance(toBeThrown)); - thrown.expectMessage("Window coders must be deterministic"); - Window.into(mockWindowFn); - } - - @Test - public void testMissingMode() { - FixedWindows fixed10 = FixedWindows.of(Duration.standardMinutes(10)); - Repeatedly trigger = Repeatedly.forever(AfterPane.elementCountAtLeast(5)); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("requires that the accumulation mode"); - TestPipeline.create() - .apply(Create.of("hello", "world").withCoder(StringUtf8Coder.of())) - .apply("Window", Window.into(fixed10)) - .apply("Lateness", Window.withAllowedLateness(Duration.standardDays(1))) - .apply("Trigger", Window.triggering(trigger)); - } - - @Test - public void testMissingLateness() { - FixedWindows fixed10 = FixedWindows.of(Duration.standardMinutes(10)); - Repeatedly trigger = Repeatedly.forever(AfterPane.elementCountAtLeast(5)); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("requires that the allowed lateness"); - TestPipeline.create() - .apply(Create.of("hello", "world").withCoder(StringUtf8Coder.of())) - .apply("Mode", Window.accumulatingFiredPanes()) - .apply("Window", Window.into(fixed10)) - .apply("Trigger", Window.triggering(trigger)); - } - - /** - * Tests that when two elements are combined via a GroupByKey their output timestamp agrees - * with the windowing function default, the earlier of the two values. - */ - @Test - @Category(RunnableOnService.class) - public void testOutputTimeFnDefault() { - Pipeline pipeline = TestPipeline.create(); - - pipeline.apply( - Create.timestamped( - TimestampedValue.of(KV.of(0, "hello"), new Instant(0)), - TimestampedValue.of(KV.of(0, "goodbye"), new Instant(10)))) - .apply(Window.>into(FixedWindows.of(Duration.standardMinutes(10)))) - .apply(GroupByKey.create()) - .apply(ParDo.of(new DoFn>, Void>() { - @Override - public void processElement(ProcessContext c) throws Exception { - assertThat(c.timestamp(), equalTo(new Instant(0))); - } - })); - - pipeline.run(); - } - - /** - * Tests that when two elements are combined via a GroupByKey their output timestamp agrees - * with the windowing function customized to use the end of the window. - */ - @Test - @Category(RunnableOnService.class) - public void testOutputTimeFnEndOfWindow() { - Pipeline pipeline = TestPipeline.create(); - - pipeline.apply( - Create.timestamped( - TimestampedValue.of(KV.of(0, "hello"), new Instant(0)), - TimestampedValue.of(KV.of(0, "goodbye"), new Instant(10)))) - .apply(Window.>into(FixedWindows.of(Duration.standardMinutes(10))) - .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow())) - .apply(GroupByKey.create()) - .apply(ParDo.of(new DoFn>, Void>() { - @Override - public void processElement(ProcessContext c) throws Exception { - assertThat(c.timestamp(), equalTo(new Instant(10 * 60 * 1000 - 1))); - } - })); - - pipeline.run(); - } - - @Test - public void testDisplayData() { - FixedWindows windowFn = FixedWindows.of(Duration.standardHours(5)); - AfterWatermark.FromEndOfWindow triggerBuilder = AfterWatermark.pastEndOfWindow(); - Duration allowedLateness = Duration.standardMinutes(10); - Window.ClosingBehavior closingBehavior = Window.ClosingBehavior.FIRE_IF_NON_EMPTY; - OutputTimeFn outputTimeFn = OutputTimeFns.outputAtEndOfWindow(); - - Window.Bound window = Window - .into(windowFn) - .triggering(triggerBuilder) - .accumulatingFiredPanes() - .withAllowedLateness(allowedLateness, closingBehavior) - .withOutputTimeFn(outputTimeFn); - - DisplayData displayData = DisplayData.from(window); - - assertThat(displayData, hasDisplayItem("windowFn", windowFn.getClass())); - assertThat(displayData, includesDisplayDataFrom(windowFn)); - - assertThat(displayData, hasDisplayItem("trigger", triggerBuilder.toString())); - assertThat(displayData, - hasDisplayItem("accumulationMode", AccumulationMode.ACCUMULATING_FIRED_PANES.toString())); - assertThat(displayData, - hasDisplayItem("allowedLateness", allowedLateness)); - assertThat(displayData, hasDisplayItem("closingBehavior", closingBehavior.toString())); - assertThat(displayData, hasDisplayItem("outputTimeFn", outputTimeFn.getClass())); - } - - @Test - public void testDisplayDataExcludesUnspecifiedProperties() { - Window.Bound onlyHasAccumulationMode = Window.named("foobar").discardingFiredPanes(); - assertThat(DisplayData.from(onlyHasAccumulationMode), not(hasDisplayItem(hasKey(isOneOf( - "windowFn", - "trigger", - "outputTimeFn", - "allowedLateness", - "closingBehavior"))))); - - Window.Bound noAccumulationMode = Window.into(new GlobalWindows()); - assertThat(DisplayData.from(noAccumulationMode), - not(hasDisplayItem(hasKey("accumulationMode")))); - } - - @Test - public void testDisplayDataExcludesDefaults() { - Window.Bound window = Window.into(new GlobalWindows()) - .triggering(DefaultTrigger.of()) - .withAllowedLateness(Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis())); - - DisplayData data = DisplayData.from(window); - assertThat(data, not(hasDisplayItem("trigger"))); - assertThat(data, not(hasDisplayItem("allowedLateness"))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java deleted file mode 100644 index 1c1248bd0c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/WindowingTest.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms.windowing; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; -import java.io.Serializable; - -/** Unit tests for bucketing. */ -@RunWith(JUnit4.class) -@SuppressWarnings("unchecked") -public class WindowingTest implements Serializable { - @Rule - public transient TemporaryFolder tmpFolder = new TemporaryFolder(); - - private static class WindowedCount extends PTransform, PCollection> { - - private final class FormatCountsDoFn - extends DoFn, String> implements RequiresWindowAccess { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().getKey() + ":" + c.element().getValue() - + ":" + c.timestamp().getMillis() + ":" + c.window()); - } - } - private WindowFn windowFn; - public WindowedCount(WindowFn windowFn) { - this.windowFn = windowFn; - } - @Override - public PCollection apply(PCollection in) { - return in - .apply(Window.named("Window").into(windowFn)) - .apply(Count.perElement()) - .apply(ParDo - .named("FormatCounts").of(new FormatCountsDoFn())) - .setCoder(StringUtf8Coder.of()); - } - } - - private String output(String value, int count, int timestamp, int windowStart, int windowEnd) { - return value + ":" + count + ":" + timestamp - + ":[" + new Instant(windowStart) + ".." + new Instant(windowEnd) + ")"; - } - - @Test - @Category(RunnableOnService.class) - public void testPartitioningWindowing() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply( - Create.timestamped( - TimestampedValue.of("a", new Instant(1)), - TimestampedValue.of("b", new Instant(2)), - TimestampedValue.of("b", new Instant(3)), - TimestampedValue.of("c", new Instant(11)), - TimestampedValue.of("d", new Instant(11)))); - - PCollection output = - input - .apply(new WindowedCount(FixedWindows.of(new Duration(10)))); - - DataflowAssert.that(output).containsInAnyOrder( - output("a", 1, 1, 0, 10), - output("b", 2, 2, 0, 10), - output("c", 1, 11, 10, 20), - output("d", 1, 11, 10, 20)); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testNonPartitioningWindowing() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply( - Create.timestamped( - TimestampedValue.of("a", new Instant(1)), - TimestampedValue.of("a", new Instant(7)), - TimestampedValue.of("b", new Instant(8)))); - - PCollection output = - input - .apply(new WindowedCount( - SlidingWindows.of(new Duration(10)).every(new Duration(5)))); - - DataflowAssert.that(output).containsInAnyOrder( - output("a", 1, 1, -5, 5), - output("a", 2, 5, 0, 10), - output("a", 1, 10, 5, 15), - output("b", 1, 8, 0, 10), - output("b", 1, 10, 5, 15)); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testMergingWindowing() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply( - Create.timestamped( - TimestampedValue.of("a", new Instant(1)), - TimestampedValue.of("a", new Instant(5)), - TimestampedValue.of("a", new Instant(20)))); - - PCollection output = - input - .apply(new WindowedCount(Sessions.withGapDuration(new Duration(10)))); - - DataflowAssert.that(output).containsInAnyOrder( - output("a", 2, 1, 1, 15), - output("a", 1, 20, 20, 30)); - - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testWindowPreservation() { - Pipeline p = TestPipeline.create(); - PCollection input1 = p.apply("Create12", - Create.timestamped( - TimestampedValue.of("a", new Instant(1)), - TimestampedValue.of("b", new Instant(2)))); - - PCollection input2 = p.apply("Create34", - Create.timestamped( - TimestampedValue.of("a", new Instant(3)), - TimestampedValue.of("b", new Instant(4)))); - - PCollectionList input = PCollectionList.of(input1).and(input2); - - PCollection output = - input - .apply(Flatten.pCollections()) - .apply(new WindowedCount(FixedWindows.of(new Duration(5)))); - - DataflowAssert.that(output).containsInAnyOrder( - output("a", 2, 1, 0, 5), - output("b", 2, 2, 0, 5)); - - p.run(); - } - - @Test - public void testEmptyInput() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply(Create.timestamped() - .withCoder(StringUtf8Coder.of())); - - PCollection output = - input - .apply(new WindowedCount(FixedWindows.of(new Duration(10)))); - - DataflowAssert.that(output).empty(); - - p.run(); - } - - @Test - public void testTextIoInput() throws Exception { - File tmpFile = tmpFolder.newFile("file.txt"); - String filename = tmpFile.getPath(); - - try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) { - writer.println("a 1"); - writer.println("b 2"); - writer.println("b 3"); - writer.println("c 11"); - writer.println("d 11"); - } - - Pipeline p = TestPipeline.create(); - PCollection output = p.begin() - .apply(TextIO.Read.named("ReadLines").from(filename)) - .apply(ParDo.of(new ExtractWordsWithTimestampsFn())) - .apply(new WindowedCount(FixedWindows.of(Duration.millis(10)))); - - DataflowAssert.that(output).containsInAnyOrder( - output("a", 1, 1, 0, 10), - output("b", 2, 2, 0, 10), - output("c", 1, 11, 10, 20), - output("d", 1, 11, 10, 20)); - - p.run(); - } - - /** A DoFn that tokenizes lines of text into individual words. */ - static class ExtractWordsWithTimestampsFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - String[] words = c.element().split("[^a-zA-Z0-9']+"); - if (words.length == 2) { - c.outputWithTimestamp(words[0], new Instant(Long.parseLong(words[1]))); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java deleted file mode 100644 index e63707151f..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ApiSurfaceTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Tests for ApiSurface. These both test the functionality and also that our - * public API is conformant to a hard-coded policy. - */ -@RunWith(JUnit4.class) -public class ApiSurfaceTest { - - @Test - public void testOurApiSurface() throws Exception { - ApiSurface checkedApiSurface = ApiSurface.getSdkApiSurface() - .pruningClassName("com.google.cloud.dataflow.sdk.util.common.ReflectHelpers") - .pruningClassName("com.google.cloud.dataflow.sdk.DataflowMatchers") - .pruningClassName("com.google.cloud.dataflow.sdk.TestUtils") - .pruningClassName("com.google.cloud.dataflow.sdk.WindowMatchers") - .pruningClassName("com.google.cloud.dataflow.sdk.transforms.display.DisplayDataMatchers"); - - checkedApiSurface.getExposedClasses(); - - Map, List>> disallowedClasses = Maps.newHashMap(); - for (Class clazz : checkedApiSurface.getExposedClasses()) { - if (!classIsAllowed(clazz)) { - disallowedClasses.put(clazz, checkedApiSurface.getAnyExposurePath(clazz)); - } - } - - List disallowedMessages = Lists.newArrayList(); - for (Map.Entry, List>> entry : disallowedClasses.entrySet()) { - disallowedMessages.add(entry.getKey() + " exposed via:\n\t\t" - + Joiner.on("\n\t\t").join(entry.getValue())); - } - Collections.sort(disallowedMessages); - - if (!disallowedMessages.isEmpty()) { - fail("The following disallowed classes appear in the public API surface of the SDK:\n\t" - + Joiner.on("\n\t").join(disallowedMessages)); - } - } - - private boolean classIsAllowed(Class clazz) { - return clazz.getName().startsWith("com.google.cloud.dataflow"); - } - - ////////////////////////////////////////////////////////////////////////////////// - - @SuppressWarnings({"rawtypes", "unchecked"}) - private void assertExposed(Class classToExamine, Class... exposedClasses) { - ApiSurface apiSurface = ApiSurface - .ofClass(classToExamine) - .pruningPrefix("java"); - - Set expectedExposed = Sets.newHashSet(classToExamine); - for (Class clazz : exposedClasses) { - expectedExposed.add(clazz); - } - assertThat(apiSurface.getExposedClasses(), containsInAnyOrder(expectedExposed.toArray())); - } - - private interface Exposed { } - - private interface ExposedReturnType { - Exposed zero(); - } - - @Test - public void testExposedReturnType() throws Exception { - assertExposed(ExposedReturnType.class, Exposed.class); - } - - private interface ExposedParameterTypeVarBound { - void getList(T whatever); - } - - @Test - public void testExposedParameterTypeVarBound() throws Exception { - assertExposed(ExposedParameterTypeVarBound.class, Exposed.class); - } - - private interface ExposedWildcardBound { - void acceptList(List arg); - } - - @Test - public void testExposedWildcardBound() throws Exception { - assertExposed(ExposedWildcardBound.class, Exposed.class); - } - - private interface ExposedActualTypeArgument extends List { } - - @Test - public void testExposedActualTypeArgument() throws Exception { - assertExposed(ExposedActualTypeArgument.class, Exposed.class); - } - - @Test - public void testIgnoreAll() throws Exception { - ApiSurface apiSurface = ApiSurface.ofClass(ExposedWildcardBound.class) - .includingClass(Object.class) - .includingClass(ApiSurface.class) - .pruningPattern(".*"); - assertThat(apiSurface.getExposedClasses(), emptyIterable()); - } - - private interface PrunedPattern { } - private interface NotPruned extends PrunedPattern { } - - @Test - public void testprunedPattern() throws Exception { - ApiSurface apiSurface = ApiSurface.ofClass(NotPruned.class) - .pruningClass(PrunedPattern.class); - assertThat(apiSurface.getExposedClasses(), containsInAnyOrder((Class) NotPruned.class)); - } - - private interface ExposedTwice { - Exposed zero(); - Exposed one(); - } - - @Test - public void testExposedTwice() throws Exception { - assertExposed(ExposedTwice.class, Exposed.class); - } - - private interface ExposedCycle { - ExposedCycle zero(Exposed foo); - } - - @Test - public void testExposedCycle() throws Exception { - assertExposed(ExposedCycle.class, Exposed.class); - } - - private interface ExposedGenericCycle { - Exposed zero(List foo); - } - - @Test - public void testExposedGenericCycle() throws Exception { - assertExposed(ExposedGenericCycle.class, Exposed.class); - } - - private interface ExposedArrayCycle { - Exposed zero(ExposedArrayCycle[] foo); - } - - @Test - public void testExposedArrayCycle() throws Exception { - assertExposed(ExposedArrayCycle.class, Exposed.class); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java deleted file mode 100644 index e200ee9a72..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptAndTimeBoundedExponentialBackOffTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.api.client.util.BackOff; -import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link AttemptAndTimeBoundedExponentialBackOff}. */ -@RunWith(JUnit4.class) -@SuppressWarnings("deprecation") // tests a deprecated clas -public class AttemptAndTimeBoundedExponentialBackOffTest { - @Rule public ExpectedException exception = ExpectedException.none(); - @Rule public FastNanoClockAndSleeper fastClock = new FastNanoClockAndSleeper(); - - @Test - public void testUsingInvalidInitialInterval() throws Exception { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Initial interval must be greater than zero."); - new AttemptAndTimeBoundedExponentialBackOff(10, 0L, 1000L); - } - - @Test - public void testUsingInvalidTimeInterval() throws Exception { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Maximum total wait time must be greater than zero."); - new AttemptAndTimeBoundedExponentialBackOff(10, 2L, 0L); - } - - @Test - public void testUsingInvalidMaximumNumberOfRetries() throws Exception { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Maximum number of attempts must be greater than zero."); - new AttemptAndTimeBoundedExponentialBackOff(-1, 10L, 1000L); - } - - @Test - public void testThatFixedNumberOfAttemptsExits() throws Exception { - BackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 3, - 500L, - 1000L, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ALL, - fastClock); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } - - @Test - public void testThatResettingAllowsReuse() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 3, - 500, - 1000L, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ALL, - fastClock); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - - backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 30, - 500, - 1000L, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ALL, - fastClock); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - fastClock.sleep(2000L); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - } - - @Test - public void testThatResettingAttemptsAllowsReuse() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 3, - 500, - 1000, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ATTEMPTS, - fastClock); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } - - @Test - public void testThatResettingAttemptsDoesNotAllowsReuse() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 30, - 500, - 1000L, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ATTEMPTS, - fastClock); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - fastClock.sleep(2000L); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - backOff.reset(); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } - - @Test - public void testThatResettingTimerAllowsReuse() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 30, - 500, - 1000L, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.TIMER, - fastClock); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - fastClock.sleep(2000L); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(561L), lessThan(1688L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(843L), lessThan(2531L))); - } - - @Test - public void testThatResettingTimerDoesNotAllowReuse() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 3, - 500, - 1000L, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.TIMER, - fastClock); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - backOff.reset(); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } - - @Test - public void testTimeBound() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 3, 500L, 5L, AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ALL, fastClock); - assertEquals(backOff.nextBackOffMillis(), 5L); - } - - @Test - public void testAtMaxAttempts() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 3, - 500L, - 1000L, - AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ALL, - fastClock); - assertFalse(backOff.atMaxAttempts()); - backOff.nextBackOffMillis(); - assertFalse(backOff.atMaxAttempts()); - backOff.nextBackOffMillis(); - assertTrue(backOff.atMaxAttempts()); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } - - @Test - public void testAtMaxTime() throws Exception { - AttemptBoundedExponentialBackOff backOff = - new AttemptAndTimeBoundedExponentialBackOff( - 3, 500L, 1L, AttemptAndTimeBoundedExponentialBackOff.ResetPolicy.ALL, fastClock); - fastClock.sleep(2); - assertTrue(backOff.atMaxAttempts()); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java deleted file mode 100644 index b4897dc4df..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AttemptBoundedExponentialBackOffTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - - -import com.google.api.client.util.BackOff; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link AttemptBoundedExponentialBackOff}. */ -@RunWith(JUnit4.class) -@SuppressWarnings("deprecation") // tests a deprecated class -public class AttemptBoundedExponentialBackOffTest { - @Rule public ExpectedException exception = ExpectedException.none(); - - @Test - public void testUsingInvalidInitialInterval() throws Exception { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Initial interval must be greater than zero."); - new AttemptBoundedExponentialBackOff(10, 0L); - } - - @Test - public void testUsingInvalidMaximumNumberOfRetries() throws Exception { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Maximum number of attempts must be greater than zero."); - new AttemptBoundedExponentialBackOff(-1, 10L); - } - - @Test - public void testThatFixedNumberOfAttemptsExits() throws Exception { - BackOff backOff = new AttemptBoundedExponentialBackOff(3, 500); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } - - @Test - public void testThatResettingAllowsReuse() throws Exception { - BackOff backOff = new AttemptBoundedExponentialBackOff(3, 500); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThan(374L), lessThan(1126L))); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } - - @Test - public void testAtMaxAttempts() throws Exception { - AttemptBoundedExponentialBackOff backOff = new AttemptBoundedExponentialBackOff(3, 500); - assertFalse(backOff.atMaxAttempts()); - backOff.nextBackOffMillis(); - assertFalse(backOff.atMaxAttempts()); - backOff.nextBackOffMillis(); - assertTrue(backOff.atMaxAttempts()); - assertEquals(BackOff.STOP, backOff.nextBackOffMillis()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java deleted file mode 100644 index 373b9115ce..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/AvroUtilsTest.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.util.AvroUtils.AvroMetadata; -import com.google.common.collect.Lists; -import com.google.common.io.BaseEncoding; - -import org.apache.avro.Schema; -import org.apache.avro.file.CodecFactory; -import org.apache.avro.file.DataFileConstants; -import org.apache.avro.file.DataFileWriter; -import org.apache.avro.generic.GenericData; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.DatumWriter; -import org.apache.avro.reflect.Nullable; -import org.apache.avro.util.Utf8; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * Tests for AvroUtils. - */ -@RunWith(JUnit4.class) -public class AvroUtilsTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - private static final int DEFAULT_RECORD_COUNT = 10000; - - /** - * Generates an input Avro file containing the given records in the temporary directory and - * returns the full path of the file. - */ - @SuppressWarnings("deprecation") // test of internal functionality - private String generateTestFile(String filename, List elems, AvroCoder coder, - String codec) throws IOException { - File tmpFile = tmpFolder.newFile(filename); - String path = tmpFile.toString(); - - FileOutputStream os = new FileOutputStream(tmpFile); - DatumWriter datumWriter = coder.createDatumWriter(); - try (DataFileWriter writer = new DataFileWriter<>(datumWriter)) { - writer.setCodec(CodecFactory.fromString(codec)); - writer.create(coder.getSchema(), os); - for (T elem : elems) { - writer.append(elem); - } - } - return path; - } - - @Test - public void testReadMetadataWithCodecs() throws Exception { - // Test reading files generated using all codecs. - String codecs[] = {DataFileConstants.NULL_CODEC, DataFileConstants.BZIP2_CODEC, - DataFileConstants.DEFLATE_CODEC, DataFileConstants.SNAPPY_CODEC, - DataFileConstants.XZ_CODEC}; - List expected = createRandomRecords(DEFAULT_RECORD_COUNT); - - for (String codec : codecs) { - String filename = generateTestFile( - codec, expected, AvroCoder.of(Bird.class), codec); - AvroMetadata metadata = AvroUtils.readMetadataFromFile(filename); - assertEquals(codec, metadata.getCodec()); - } - } - - @Test - public void testReadSchemaString() throws Exception { - List expected = createRandomRecords(DEFAULT_RECORD_COUNT); - String codec = DataFileConstants.NULL_CODEC; - String filename = generateTestFile( - codec, expected, AvroCoder.of(Bird.class), codec); - AvroMetadata metadata = AvroUtils.readMetadataFromFile(filename); - // By default, parse validates the schema, which is what we want. - Schema schema = new Schema.Parser().parse(metadata.getSchemaString()); - assertEquals(12, schema.getFields().size()); - } - - @Test - public void testConvertGenericRecordToTableRow() throws Exception { - TableSchema tableSchema = new TableSchema(); - List subFields = Lists.newArrayList( - new TableFieldSchema().setName("species").setType("STRING").setMode("NULLABLE")); - /* - * Note that the quality and quantity fields do not have their mode set, so they should default - * to NULLABLE. This is an important test of BigQuery semantics. - * - * All the other fields we set in this function are required on the Schema response. - * - * See https://cloud.google.com/bigquery/docs/reference/v2/tables#schema - */ - List fields = - Lists.newArrayList( - new TableFieldSchema().setName("number").setType("INTEGER").setMode("REQUIRED"), - new TableFieldSchema().setName("species").setType("STRING").setMode("NULLABLE"), - new TableFieldSchema().setName("quality").setType("FLOAT") /* default to NULLABLE */, - new TableFieldSchema().setName("quantity").setType("INTEGER") /* default to NULLABLE */, - new TableFieldSchema().setName("birthday").setType("TIMESTAMP").setMode("NULLABLE"), - new TableFieldSchema().setName("flighted").setType("BOOLEAN").setMode("NULLABLE"), - new TableFieldSchema().setName("sound").setType("BYTES").setMode("NULLABLE"), - new TableFieldSchema().setName("anniversaryDate").setType("DATE").setMode("NULLABLE"), - new TableFieldSchema().setName("anniversaryDatetime") - .setType("DATETIME").setMode("NULLABLE"), - new TableFieldSchema().setName("anniversaryTime").setType("TIME").setMode("NULLABLE"), - new TableFieldSchema().setName("scion").setType("RECORD").setMode("NULLABLE") - .setFields(subFields), - new TableFieldSchema().setName("associates").setType("RECORD").setMode("REPEATED") - .setFields(subFields)); - tableSchema.setFields(fields); - Schema avroSchema = AvroCoder.of(Bird.class).getSchema(); - - { - // Test nullable fields. - GenericRecord record = new GenericData.Record(avroSchema); - record.put("number", 5L); - TableRow convertedRow = AvroUtils.convertGenericRecordToTableRow(record, tableSchema); - TableRow row = new TableRow() - .set("number", "5") - .set("associates", new ArrayList()); - assertEquals(row, convertedRow); - } - { - // Test type conversion for: - // INTEGER, FLOAT, TIMESTAMP, BOOLEAN, BYTES, DATE, DATETIME, TIME. - GenericRecord record = new GenericData.Record(avroSchema); - byte[] soundBytes = "chirp,chirp".getBytes(); - ByteBuffer soundByteBuffer = ByteBuffer.wrap(soundBytes); - soundByteBuffer.rewind(); - record.put("number", 5L); - record.put("quality", 5.0); - record.put("birthday", 5L); - record.put("flighted", Boolean.TRUE); - record.put("sound", soundByteBuffer); - record.put("anniversaryDate", new Utf8("2000-01-01")); - record.put("anniversaryDatetime", new String("2000-01-01 00:00:00.000005")); - record.put("anniversaryTime", new Utf8("00:00:00.000005")); - TableRow convertedRow = AvroUtils.convertGenericRecordToTableRow(record, tableSchema); - TableRow row = new TableRow() - .set("number", "5") - .set("birthday", "1970-01-01 00:00:00.000005 UTC") - .set("quality", 5.0) - .set("associates", new ArrayList()) - .set("flighted", Boolean.TRUE) - .set("sound", BaseEncoding.base64().encode(soundBytes)) - .set("anniversaryDate", "2000-01-01") - .set("anniversaryDatetime", "2000-01-01 00:00:00.000005") - .set("anniversaryTime", "00:00:00.000005"); - assertEquals(row, convertedRow); - } - { - // Test repeated fields. - Schema subBirdSchema = AvroCoder.of(Bird.SubBird.class).getSchema(); - GenericRecord nestedRecord = new GenericData.Record(subBirdSchema); - nestedRecord.put("species", "other"); - GenericRecord record = new GenericData.Record(avroSchema); - record.put("number", 5L); - record.put("associates", Lists.newArrayList(nestedRecord)); - TableRow convertedRow = AvroUtils.convertGenericRecordToTableRow(record, tableSchema); - TableRow row = new TableRow() - .set("associates", Lists.newArrayList( - new TableRow().set("species", "other"))) - .set("number", "5"); - assertEquals(row, convertedRow); - } - } - - /** - * Pojo class used as the record type in tests. - */ - @DefaultCoder(AvroCoder.class) - static class Bird { - long number; - @Nullable String species; - @Nullable Double quality; - @Nullable Long quantity; - @Nullable Long birthday; // Exercises TIMESTAMP. - @Nullable Boolean flighted; - @Nullable ByteBuffer sound; - @Nullable Utf8 anniversaryDate; - @Nullable String anniversaryDatetime; - @Nullable Utf8 anniversaryTime; - @Nullable SubBird scion; - SubBird[] associates; - - static class SubBird { - @Nullable String species; - - public SubBird() {} - } - - public Bird() { - associates = new SubBird[1]; - associates[0] = new SubBird(); - } - } - - /** - * Create a list of n random records. - */ - private static List createRandomRecords(long n) { - String[] species = {"pigeons", "owls", "gulls", "hawks", "robins", "jays"}; - Random random = new Random(0); - - List records = new ArrayList<>(); - for (long i = 0; i < n; i++) { - Bird bird = new Bird(); - bird.quality = random.nextDouble(); - bird.species = species[random.nextInt(species.length)]; - bird.number = i; - bird.quantity = random.nextLong(); - records.add(bird); - } - return records; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java deleted file mode 100644 index 3228c544bf..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BatchTimerInternalsTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.mockito.Matchers.argThat; - -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaceForTest; - -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.ArgumentMatcher; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Tests for {@link BatchTimerInternals}. - */ -@RunWith(JUnit4.class) -public class BatchTimerInternalsTest { - - private static final StateNamespace NS1 = new StateNamespaceForTest("NS1"); - - @Mock - private ReduceFnRunner mockRunner; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - private static class TimersAre extends ArgumentMatcher> { - final List expectedTimers; - TimersAre(List timers) { - expectedTimers = timers; - } - - @Override - public boolean matches(Object actual) { - if (actual == null || !(actual instanceof Iterable)) { - return false; - } - @SuppressWarnings("unchecked") - Iterable timers = (Iterable) actual; - - List actualTimers = new ArrayList(); - for (TimerData timer : timers) { - actualTimers.add(timer); - } - return expectedTimers.equals(actualTimers); - } - - @Override - public String toString() { - return "ordered timers " + expectedTimers.toString(); - } - } - - private static TimersAre timersAre(TimerData... timers) { - return new TimersAre(Arrays.asList(timers)); - } - - @Test - public void testFiringTimers() throws Exception { - BatchTimerInternals underTest = new BatchTimerInternals(new Instant(0)); - TimerData processingTime1 = TimerData.of(NS1, new Instant(19), TimeDomain.PROCESSING_TIME); - TimerData processingTime2 = TimerData.of(NS1, new Instant(29), TimeDomain.PROCESSING_TIME); - - underTest.setTimer(processingTime1); - underTest.setTimer(processingTime2); - - underTest.advanceProcessingTime(mockRunner, new Instant(20)); - Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime1))); - Mockito.verifyNoMoreInteractions(mockRunner); - - // Advancing just a little shouldn't refire - underTest.advanceProcessingTime(mockRunner, new Instant(21)); - Mockito.verifyNoMoreInteractions(mockRunner); - - // Adding the timer and advancing a little should refire - underTest.setTimer(processingTime1); - underTest.advanceProcessingTime(mockRunner, new Instant(21)); - Mockito.verify(mockRunner, Mockito.times(2)).onTimers(argThat(timersAre(processingTime1))); - Mockito.verifyNoMoreInteractions(mockRunner); - - // And advancing the rest of the way should still have the other timer - underTest.advanceProcessingTime(mockRunner, new Instant(30)); - Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime2))); - Mockito.verifyNoMoreInteractions(mockRunner); - } - - @Test - public void testTimerOrdering() throws Exception { - BatchTimerInternals underTest = new BatchTimerInternals(new Instant(0)); - TimerData watermarkTime1 = TimerData.of(NS1, new Instant(19), TimeDomain.EVENT_TIME); - TimerData processingTime1 = TimerData.of(NS1, new Instant(19), TimeDomain.PROCESSING_TIME); - TimerData watermarkTime2 = TimerData.of(NS1, new Instant(29), TimeDomain.EVENT_TIME); - TimerData processingTime2 = TimerData.of(NS1, new Instant(29), TimeDomain.PROCESSING_TIME); - - underTest.setTimer(processingTime1); - underTest.setTimer(watermarkTime1); - underTest.setTimer(processingTime2); - underTest.setTimer(watermarkTime2); - - underTest.advanceInputWatermark(mockRunner, new Instant(30)); - Mockito.verify(mockRunner).onTimers(argThat(timersAre(watermarkTime1, watermarkTime2))); - Mockito.verifyNoMoreInteractions(mockRunner); - - underTest.advanceProcessingTime(mockRunner, new Instant(30)); - Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime1, processingTime2))); - Mockito.verifyNoMoreInteractions(mockRunner); - } - - @Test - public void testDeduplicate() throws Exception { - BatchTimerInternals underTest = new BatchTimerInternals(new Instant(0)); - TimerData watermarkTime = TimerData.of(NS1, new Instant(19), TimeDomain.EVENT_TIME); - TimerData processingTime = TimerData.of(NS1, new Instant(19), TimeDomain.PROCESSING_TIME); - underTest.setTimer(watermarkTime); - underTest.setTimer(watermarkTime); - underTest.setTimer(processingTime); - underTest.setTimer(processingTime); - underTest.advanceProcessingTime(mockRunner, new Instant(20)); - Mockito.verify(mockRunner).onTimers(argThat(timersAre(processingTime))); - underTest.advanceInputWatermark(mockRunner, new Instant(20)); - Mockito.verify(mockRunner).onTimers(argThat(timersAre(watermarkTime))); - Mockito.verifyNoMoreInteractions(mockRunner); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java deleted file mode 100644 index df6632be76..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImplTest.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; -import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; -import com.google.api.client.http.LowLevelHttpResponse; -import com.google.api.client.json.GenericJson; -import com.google.api.client.json.Json; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.Sleeper; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.ErrorProto; -import com.google.api.services.bigquery.model.Job; -import com.google.api.services.bigquery.model.JobConfigurationLoad; -import com.google.api.services.bigquery.model.JobReference; -import com.google.api.services.bigquery.model.JobStatus; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableReference; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; -import com.google.cloud.dataflow.sdk.util.BigQueryServicesImpl.JobServiceImpl; -import com.google.cloud.hadoop.util.ApiErrorExtractor; -import com.google.common.collect.ImmutableList; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * Tests for {@link BigQueryServicesImpl}. - */ -@RunWith(JUnit4.class) -public class BigQueryServicesImplTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(BigQueryServicesImpl.class); - @Mock private LowLevelHttpResponse response; - private Bigquery bigquery; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - // A mock transport that lets us mock the API responses. - MockHttpTransport transport = - new MockHttpTransport.Builder() - .setLowLevelHttpRequest( - new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - return response; - } - }) - .build(); - - // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer. - bigquery = - new Bigquery.Builder( - transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()) - .build(); - } - - /** - * Tests that {@link BigQueryServicesImpl.JobServiceImpl#startLoadJob} succeeds. - */ - @Test - public void testStartLoadJobSucceeds() throws IOException, InterruptedException { - Job testJob = new Job(); - JobReference jobRef = new JobReference(); - jobRef.setJobId("jobId"); - jobRef.setProjectId("projectId"); - testJob.setJobReference(jobRef); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200); - when(response.getContent()).thenReturn(toStream(testJob)); - - TableReference ref = new TableReference(); - ref.setProjectId("projectId"); - JobConfigurationLoad loadConfig = new JobConfigurationLoad(); - loadConfig.setDestinationTable(ref); - - Sleeper sleeper = new FastNanoClockAndSleeper(); - JobServiceImpl.startJob( - testJob, new ApiErrorExtractor(), bigquery, sleeper, FluentBackoff.DEFAULT.backoff()); - - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - /** - * Tests that {@link BigQueryServicesImpl.JobServiceImpl#startLoadJob} succeeds - * with an already exist job. - */ - @Test - public void testStartLoadJobSucceedsAlreadyExists() throws IOException, InterruptedException { - Job testJob = new Job(); - JobReference jobRef = new JobReference(); - jobRef.setJobId("jobId"); - jobRef.setProjectId("projectId"); - testJob.setJobReference(jobRef); - - when(response.getStatusCode()).thenReturn(409); // 409 means already exists - - TableReference ref = new TableReference(); - ref.setProjectId("projectId"); - JobConfigurationLoad loadConfig = new JobConfigurationLoad(); - loadConfig.setDestinationTable(ref); - - Sleeper sleeper = new FastNanoClockAndSleeper(); - JobServiceImpl.startJob( - testJob, new ApiErrorExtractor(), bigquery, sleeper, FluentBackoff.DEFAULT.backoff()); - - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - /** - * Tests that {@link BigQueryServicesImpl.JobServiceImpl#startLoadJob} succeeds with a retry. - */ - @Test - public void testStartLoadJobRetry() throws IOException, InterruptedException { - Job testJob = new Job(); - JobReference jobRef = new JobReference(); - jobRef.setJobId("jobId"); - jobRef.setProjectId("projectId"); - testJob.setJobReference(jobRef); - - // First response is 403 rate limited, second response has valid payload. - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(403).thenReturn(200); - when(response.getContent()) - .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403))) - .thenReturn(toStream(testJob)); - - TableReference ref = new TableReference(); - ref.setProjectId("projectId"); - JobConfigurationLoad loadConfig = new JobConfigurationLoad(); - loadConfig.setDestinationTable(ref); - - Sleeper sleeper = new FastNanoClockAndSleeper(); - JobServiceImpl.startJob( - testJob, new ApiErrorExtractor(), bigquery, sleeper, FluentBackoff.DEFAULT.backoff()); - - verify(response, times(2)).getStatusCode(); - verify(response, times(2)).getContent(); - verify(response, times(2)).getContentType(); - } - - /** - * Tests that {@link BigQueryServicesImpl.JobServiceImpl#pollJob} succeeds. - */ - @Test - public void testPollJobSucceeds() throws IOException, InterruptedException { - Job testJob = new Job(); - testJob.setStatus(new JobStatus().setState("DONE")); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200); - when(response.getContent()).thenReturn(toStream(testJob)); - - BigQueryServicesImpl.JobServiceImpl jobService = - new BigQueryServicesImpl.JobServiceImpl(bigquery); - JobReference jobRef = new JobReference() - .setProjectId("projectId") - .setJobId("jobId"); - Job job = jobService.pollJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); - - assertEquals(testJob, job); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - /** - * Tests that {@link BigQueryServicesImpl.JobServiceImpl#pollJob} fails. - */ - @Test - public void testPollJobFailed() throws IOException, InterruptedException { - Job testJob = new Job(); - testJob.setStatus(new JobStatus().setState("DONE").setErrorResult(new ErrorProto())); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200); - when(response.getContent()).thenReturn(toStream(testJob)); - - BigQueryServicesImpl.JobServiceImpl jobService = - new BigQueryServicesImpl.JobServiceImpl(bigquery); - JobReference jobRef = new JobReference() - .setProjectId("projectId") - .setJobId("jobId"); - Job job = jobService.pollJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); - - assertEquals(testJob, job); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - /** - * Tests that {@link BigQueryServicesImpl.JobServiceImpl#pollJob} returns UNKNOWN. - */ - @Test - public void testPollJobUnknown() throws IOException, InterruptedException { - Job testJob = new Job(); - testJob.setStatus(new JobStatus()); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200); - when(response.getContent()).thenReturn(toStream(testJob)); - - BigQueryServicesImpl.JobServiceImpl jobService = - new BigQueryServicesImpl.JobServiceImpl(bigquery); - JobReference jobRef = new JobReference() - .setProjectId("projectId") - .setJobId("jobId"); - Job job = jobService.pollJob(jobRef, Sleeper.DEFAULT, BackOff.STOP_BACKOFF); - - assertEquals(null, job); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - @Test - public void testGetJobSucceeds() throws Exception { - Job testJob = new Job(); - testJob.setStatus(new JobStatus()); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200); - when(response.getContent()).thenReturn(toStream(testJob)); - - BigQueryServicesImpl.JobServiceImpl jobService = - new BigQueryServicesImpl.JobServiceImpl(bigquery); - JobReference jobRef = new JobReference() - .setProjectId("projectId") - .setJobId("jobId"); - Job job = jobService.getJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); - - assertEquals(testJob, job); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - @Test - public void testGetJobNotFound() throws Exception { - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(404); - - BigQueryServicesImpl.JobServiceImpl jobService = - new BigQueryServicesImpl.JobServiceImpl(bigquery); - JobReference jobRef = new JobReference() - .setProjectId("projectId") - .setJobId("jobId"); - Job job = jobService.getJob(jobRef, Sleeper.DEFAULT, BackOff.ZERO_BACKOFF); - - assertEquals(null, job); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - @Test - public void testGetJobThrows() throws Exception { - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(401); - - BigQueryServicesImpl.JobServiceImpl jobService = - new BigQueryServicesImpl.JobServiceImpl(bigquery); - JobReference jobRef = new JobReference() - .setProjectId("projectId") - .setJobId("jobId"); - thrown.expect(IOException.class); - thrown.expectMessage(String.format("Unable to find BigQuery job: %s", jobRef)); - - jobService.getJob(jobRef, Sleeper.DEFAULT, BackOff.STOP_BACKOFF); - } - - @Test - public void testExecuteWithRetries() throws IOException, InterruptedException { - Table testTable = new Table(); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200); - when(response.getContent()).thenReturn(toStream(testTable)); - - Table table = BigQueryServicesImpl.executeWithRetries( - bigquery.tables().get("projectId", "datasetId", "tableId"), - "Failed to get table.", - Sleeper.DEFAULT, - BackOff.STOP_BACKOFF); - - assertEquals(testTable, table); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - /** A helper to wrap a {@link GenericJson} object in a content stream. */ - private static InputStream toStream(GenericJson content) throws IOException { - return new ByteArrayInputStream(JacksonFactory.getDefaultInstance().toByteArray(content)); - } - - /** A helper that generates the error JSON payload that Google APIs produce. */ - private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, int status) { - ErrorInfo info = new ErrorInfo(); - info.setReason(reason); - info.setDomain("global"); - // GoogleJsonError contains one or more ErrorInfo objects; our utiities read the first one. - GoogleJsonError error = new GoogleJsonError(); - error.setErrors(ImmutableList.of(info)); - error.setCode(status); - // The actual JSON response is an error container. - GoogleJsonErrorContainer container = new GoogleJsonErrorContainer(); - container.setError(error); - return container; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java deleted file mode 100644 index 102bd17f4b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableInserterTest.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Verify.verifyNotNull; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; -import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.LowLevelHttpResponse; -import com.google.api.client.json.GenericJson; -import com.google.api.client.json.Json; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.testing.util.MockSleeper; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.Sleeper; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableDataInsertAllResponse; -import com.google.api.services.bigquery.model.TableDataInsertAllResponse.InsertErrors; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.hadoop.util.RetryBoundedBackOff; -import com.google.common.collect.ImmutableList; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -/** - * Tests of {@link BigQueryTableInserter}. - */ -@RunWith(JUnit4.class) -public class BigQueryTableInserterTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(BigQueryTableInserter.class); - @Mock private LowLevelHttpResponse response; - private Bigquery bigquery; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - // A mock transport that lets us mock the API responses. - MockHttpTransport transport = - new MockHttpTransport.Builder() - .setLowLevelHttpRequest( - new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - return response; - } - }) - .build(); - - // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer. - bigquery = - new Bigquery.Builder( - transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()) - .build(); - } - - @After - public void tearDown() throws IOException { - // These three interactions happen for every request in the normal response parsing. - verify(response, atLeastOnce()).getContentEncoding(); - verify(response, atLeastOnce()).getHeaderCount(); - verify(response, atLeastOnce()).getReasonPhrase(); - verifyNoMoreInteractions(response); - } - - /** A helper to wrap a {@link GenericJson} object in a content stream. */ - private static InputStream toStream(GenericJson content) throws IOException { - return new ByteArrayInputStream(JacksonFactory.getDefaultInstance().toByteArray(content)); - } - - /** A helper that generates the error JSON payload that Google APIs produce. */ - private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, int status) { - ErrorInfo info = new ErrorInfo(); - info.setReason(reason); - info.setDomain("global"); - // GoogleJsonError contains one or more ErrorInfo objects; our utiities read the first one. - GoogleJsonError error = new GoogleJsonError(); - error.setErrors(ImmutableList.of(info)); - error.setCode(status); - // The actual JSON response is an error container. - GoogleJsonErrorContainer container = new GoogleJsonErrorContainer(); - container.setError(error); - return container; - } - - /** - * Tests that {@link BigQueryTableInserter} succeeds on the first try. - */ - @Test - public void testCreateTableSucceeds() throws IOException { - Table testTable = new Table().setDescription("a table"); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200); - when(response.getContent()).thenReturn(toStream(testTable)); - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - Table ret = - inserter.tryCreateTable( - new Table(), - "project", - "dataset", - new RetryBoundedBackOff(0, BackOff.ZERO_BACKOFF), - Sleeper.DEFAULT); - assertEquals(testTable, ret); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - /** - * Tests that {@link BigQueryTableInserter} succeeds when the table already exists. - */ - @Test - public void testCreateTableSucceedsAlreadyExists() throws IOException { - when(response.getStatusCode()).thenReturn(409); // 409 means already exists - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - Table ret = - inserter.tryCreateTable( - new Table(), - "project", - "dataset", - new RetryBoundedBackOff(0, BackOff.ZERO_BACKOFF), - Sleeper.DEFAULT); - - assertNull(ret); - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - } - - /** - * Tests that {@link BigQueryTableInserter} retries quota rate limited attempts. - */ - @Test - public void testCreateTableRetry() throws IOException { - TableReference ref = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - Table testTable = new Table().setTableReference(ref); - - // First response is 403 rate limited, second response has valid payload. - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(403).thenReturn(200); - when(response.getContent()) - .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403))) - .thenReturn(toStream(testTable)); - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - Table ret = - inserter.tryCreateTable( - testTable, - "project", - "dataset", - new RetryBoundedBackOff(3, BackOff.ZERO_BACKOFF), - Sleeper.DEFAULT); - assertEquals(testTable, ret); - verify(response, times(2)).getStatusCode(); - verify(response, times(2)).getContent(); - verify(response, times(2)).getContentType(); - verifyNotNull(ret.getTableReference()); - expectedLogs.verifyInfo( - "Quota limit reached when creating table project:dataset.table, " - + "retrying up to 5.0 minutes"); - } - - /** - * Tests that {@link BigQueryTableInserter} does not retry non-rate-limited attempts. - */ - @Test - public void testCreateTableDoesNotRetry() throws IOException { - Table testTable = new Table().setDescription("a table"); - - // First response is 403 not-rate-limited, second response has valid payload but should not - // be invoked. - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(403).thenReturn(200); - when(response.getContent()) - .thenReturn(toStream(errorWithReasonAndStatus("actually forbidden", 403))) - .thenReturn(toStream(testTable)); - - thrown.expect(GoogleJsonResponseException.class); - thrown.expectMessage("actually forbidden"); - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - try { - inserter.tryCreateTable( - new Table(), - "project", - "dataset", - new RetryBoundedBackOff(3, BackOff.ZERO_BACKOFF), - Sleeper.DEFAULT); - fail(); - } catch (IOException e) { - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - throw e; - } - } - - /** - * Tests that {@link BigQueryTableInserter#insertAll} retries quota rate limited attempts. - */ - @Test - public void testInsertRetry() throws IOException { - TableReference ref = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - List rows = new ArrayList<>(); - rows.add(new TableRow()); - - // First response is 403 rate limited, second response has valid payload. - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(403).thenReturn(200); - when(response.getContent()) - .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403))) - .thenReturn(toStream(new TableDataInsertAllResponse())); - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - - inserter.insertAll(ref, rows, null, null, TEST_BACKOFF.backoff(), new MockSleeper()); - verify(response, times(2)).getStatusCode(); - verify(response, times(2)).getContent(); - verify(response, times(2)).getContentType(); - expectedLogs.verifyInfo("BigQuery insertAll exceeded rate limit, retrying"); - } - - /** - * Tests that {@link BigQueryTableInserter#insertAll} retries selected rows on failure. - */ - @Test - public void testInsertRetrySelectRows() throws Exception { - TableReference ref = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - List rows = ImmutableList.of( - new TableRow().set("row", "a"), new TableRow().set("row", "b")); - List insertIds = ImmutableList.of("a", "b"); - - final TableDataInsertAllResponse bFailed = new TableDataInsertAllResponse() - .setInsertErrors(ImmutableList.of(new InsertErrors().setIndex(1L))); - - final TableDataInsertAllResponse allRowsSucceeded = new TableDataInsertAllResponse(); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(200).thenReturn(200); - when(response.getContent()) - .thenReturn(toStream(bFailed)).thenReturn(toStream(allRowsSucceeded)); - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - inserter.insertAll(ref, rows, insertIds, null, TEST_BACKOFF.backoff(), new MockSleeper()); - verify(response, times(2)).getStatusCode(); - verify(response, times(2)).getContent(); - verify(response, times(2)).getContentType(); - expectedLogs.verifyInfo("Retrying 1 failed inserts to BigQuery"); - } - - // A BackOff that makes a total of 4 attempts - private static final FluentBackoff TEST_BACKOFF = FluentBackoff.DEFAULT.withMaxRetries(3); - - /** - * Tests that {@link BigQueryTableInserter#insertAll} fails gracefully when persistent issues. - */ - @Test - public void testInsertFailsGracefully() throws Exception { - TableReference ref = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - List rows = ImmutableList.of(new TableRow(), new TableRow()); - - final TableDataInsertAllResponse row1Failed = new TableDataInsertAllResponse() - .setInsertErrors(ImmutableList.of(new InsertErrors().setIndex(1L))); - - final TableDataInsertAllResponse row0Failed = new TableDataInsertAllResponse() - .setInsertErrors(ImmutableList.of(new InsertErrors().setIndex(0L))); - - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - // Always return 200. - when(response.getStatusCode()).thenReturn(200); - // Return row 1 failing, then we retry row 1 as row 0, and row 0 persistently fails. - when(response.getContent()) - .thenReturn(toStream(row1Failed)) - .thenAnswer(new Answer() { - @Override - public InputStream answer(InvocationOnMock invocation) throws Throwable { - return toStream(row0Failed); - } - }); - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - - // Expect it to fail. - try { - inserter.insertAll(ref, rows, null, null, TEST_BACKOFF.backoff(), new MockSleeper()); - fail(); - } catch (IOException e) { - assertThat(e, instanceOf(IOException.class)); - assertThat(e.getMessage(), containsString("Insert failed:")); - assertThat(e.getMessage(), containsString("[{\"index\":0}]")); - } - - // Verify the exact number of retries as well as log messages. - verify(response, times(4)).getStatusCode(); - verify(response, times(4)).getContent(); - verify(response, times(4)).getContentType(); - expectedLogs.verifyInfo("Retrying 1 failed inserts to BigQuery"); - } - - /** - * Tests that {@link BigQueryTableInserter#insertAll} does not retry non-rate-limited attempts. - */ - @Test - public void testInsertDoesNotRetry() throws Throwable { - TableReference ref = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - List rows = new ArrayList<>(); - rows.add(new TableRow()); - - // First response is 403 not-rate-limited, second response has valid payload but should not - // be invoked. - when(response.getContentType()).thenReturn(Json.MEDIA_TYPE); - when(response.getStatusCode()).thenReturn(403).thenReturn(200); - when(response.getContent()) - .thenReturn(toStream(errorWithReasonAndStatus("actually forbidden", 403))) - .thenReturn(toStream(new TableDataInsertAllResponse())); - - thrown.expect(GoogleJsonResponseException.class); - thrown.expectMessage("actually forbidden"); - - BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery); - - try { - inserter.insertAll(ref, rows, null, null, TEST_BACKOFF.backoff(), new MockSleeper()); - fail(); - } catch (RuntimeException e) { - verify(response, times(1)).getStatusCode(); - verify(response, times(1)).getContent(); - verify(response, times(1)).getContentType(); - throw e.getCause(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java deleted file mode 100644 index d6ac5b36ba..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.Job; -import com.google.api.services.bigquery.model.JobConfiguration; -import com.google.api.services.bigquery.model.JobConfigurationQuery; -import com.google.api.services.bigquery.model.JobReference; -import com.google.api.services.bigquery.model.JobStatistics; -import com.google.api.services.bigquery.model.JobStatistics2; -import com.google.api.services.bigquery.model.JobStatus; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableCell; -import com.google.api.services.bigquery.model.TableDataList; -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.common.collect.ImmutableList; -import com.google.common.io.BaseEncoding; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.IOException; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * Tests for {@link BigQueryTableRowIterator}. - */ -@RunWith(JUnit4.class) -public class BigQueryTableRowIteratorTest { - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Mock private Bigquery mockClient; - @Mock private Bigquery.Datasets mockDatasets; - @Mock private Bigquery.Datasets.Delete mockDatasetsDelete; - @Mock private Bigquery.Datasets.Insert mockDatasetsInsert; - @Mock private Bigquery.Jobs mockJobs; - @Mock private Bigquery.Jobs.Get mockJobsGet; - @Mock private Bigquery.Jobs.Insert mockJobsInsert; - @Mock private Bigquery.Tables mockTables; - @Mock private Bigquery.Tables.Get mockTablesGet; - @Mock private Bigquery.Tables.Delete mockTablesDelete; - @Mock private Bigquery.Tabledata mockTabledata; - @Mock private Bigquery.Tabledata.List mockTabledataList; - - @Before - public void setUp() throws IOException { - MockitoAnnotations.initMocks(this); - when(mockClient.tabledata()).thenReturn(mockTabledata); - when(mockTabledata.list(anyString(), anyString(), anyString())).thenReturn(mockTabledataList); - - when(mockClient.tables()).thenReturn(mockTables); - when(mockTables.delete(anyString(), anyString(), anyString())).thenReturn(mockTablesDelete); - when(mockTables.get(anyString(), anyString(), anyString())).thenReturn(mockTablesGet); - - when(mockClient.datasets()).thenReturn(mockDatasets); - when(mockDatasets.delete(anyString(), anyString())).thenReturn(mockDatasetsDelete); - when(mockDatasets.insert(anyString(), any(Dataset.class))).thenReturn(mockDatasetsInsert); - - when(mockClient.jobs()).thenReturn(mockJobs); - when(mockJobs.insert(anyString(), any(Job.class))).thenReturn(mockJobsInsert); - when(mockJobs.get(anyString(), anyString())).thenReturn(mockJobsGet); - } - - @After - public void tearDown() { - verifyNoMoreInteractions(mockClient); - verifyNoMoreInteractions(mockDatasets); - verifyNoMoreInteractions(mockDatasetsDelete); - verifyNoMoreInteractions(mockDatasetsInsert); - verifyNoMoreInteractions(mockJobs); - verifyNoMoreInteractions(mockJobsGet); - verifyNoMoreInteractions(mockJobsInsert); - verifyNoMoreInteractions(mockTables); - verifyNoMoreInteractions(mockTablesDelete); - verifyNoMoreInteractions(mockTablesGet); - verifyNoMoreInteractions(mockTabledata); - verifyNoMoreInteractions(mockTabledataList); - } - - private static Table tableWithBasicSchema() { - return new Table() - .setSchema( - new TableSchema() - .setFields( - Arrays.asList( - new TableFieldSchema().setName("name").setType("STRING"), - new TableFieldSchema().setName("answer").setType("INTEGER"), - new TableFieldSchema().setName("photo").setType("BYTES"), - new TableFieldSchema().setName("anniversary_date").setType("DATE"), - new TableFieldSchema().setName("anniversary_datetime").setType("DATETIME"), - new TableFieldSchema().setName("anniversary_time").setType("TIME")))); - } - - private static Table noTableQuerySchema() { - return new Table() - .setSchema( - new TableSchema() - .setFields( - Arrays.asList( - new TableFieldSchema().setName("name").setType("STRING"), - new TableFieldSchema().setName("count").setType("INTEGER"), - new TableFieldSchema().setName("photo").setType("BYTES")))); - } - - private static Table tableWithLocation() { - return new Table() - .setLocation("EU"); - } - - private TableRow rawRow(Object... args) { - List cells = new LinkedList<>(); - for (Object a : args) { - cells.add(new TableCell().setV(a)); - } - return new TableRow().setF(cells); - } - - private TableDataList rawDataList(TableRow... rows) { - return new TableDataList().setRows(Arrays.asList(rows)); - } - - /** - * Verifies that when the query runs, the correct data is returned and the temporary dataset and - * table are both cleaned up. - */ - @Test - public void testReadFromQuery() throws IOException, InterruptedException { - // Mock job inserting. - Job dryRunJob = new Job().setStatistics( - new JobStatistics().setQuery(new JobStatistics2().setReferencedTables( - ImmutableList.of(new TableReference())))); - Job insertedJob = new Job().setJobReference(new JobReference()); - when(mockJobsInsert.execute()).thenReturn(dryRunJob, insertedJob); - - // Mock job polling. - JobStatus status = new JobStatus().setState("DONE"); - TableReference tableRef = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - JobConfigurationQuery queryConfig = new JobConfigurationQuery().setDestinationTable(tableRef); - Job getJob = - new Job() - .setJobReference(new JobReference()) - .setStatus(status) - .setConfiguration(new JobConfiguration().setQuery(queryConfig)); - when(mockJobsGet.execute()).thenReturn(getJob); - - // Mock table schema fetch. - when(mockTablesGet.execute()).thenReturn(tableWithLocation(), tableWithBasicSchema()); - - byte[] photoBytes = "photograph".getBytes(); - String photoBytesEncoded = BaseEncoding.base64().encode(photoBytes); - // Mock table data fetch. - when(mockTabledataList.execute()).thenReturn( - rawDataList(rawRow("Arthur", 42, photoBytesEncoded, - "2000-01-01", "2000-01-01 00:00:00.000005", "00:00:00.000005"))); - - // Run query and verify - String query = "SELECT name, count, photo, anniversary_date, " - + "anniversary_datetime, anniversary_time from table"; - try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null, null)) { - iterator.open(); - assertTrue(iterator.advance()); - TableRow row = iterator.getCurrent(); - - assertTrue(row.containsKey("name")); - assertTrue(row.containsKey("answer")); - assertTrue(row.containsKey("photo")); - assertTrue(row.containsKey("anniversary_date")); - assertTrue(row.containsKey("anniversary_datetime")); - assertTrue(row.containsKey("anniversary_time")); - assertEquals("Arthur", row.get("name")); - assertEquals(42, row.get("answer")); - assertEquals(photoBytesEncoded, row.get("photo")); - assertEquals("2000-01-01", row.get("anniversary_date")); - assertEquals("2000-01-01 00:00:00.000005", row.get("anniversary_datetime")); - assertEquals("00:00:00.000005", row.get("anniversary_time")); - - assertFalse(iterator.advance()); - } - - // Temp dataset created and later deleted. - verify(mockClient, times(2)).datasets(); - verify(mockDatasets).insert(anyString(), any(Dataset.class)); - verify(mockDatasetsInsert).execute(); - verify(mockDatasets).delete(anyString(), anyString()); - verify(mockDatasetsDelete).execute(); - // Job inserted to run the query, polled once. - verify(mockClient, times(3)).jobs(); - verify(mockJobs, times(2)).insert(anyString(), any(Job.class)); - verify(mockJobsInsert, times(2)).execute(); - verify(mockJobs).get(anyString(), anyString()); - verify(mockJobsGet).execute(); - // Temp table get after query finish, deleted after reading. - verify(mockClient, times(3)).tables(); - verify(mockTables, times(2)).get(anyString(), anyString(), anyString()); - verify(mockTablesGet, times(2)).execute(); - verify(mockTables).delete(anyString(), anyString(), anyString()); - verify(mockTablesDelete).execute(); - // Table data read. - verify(mockClient).tabledata(); - verify(mockTabledata).list("project", "dataset", "table"); - verify(mockTabledataList).execute(); - } - - /** - * Verifies that queries that reference no data can be read. - */ - @Test - public void testReadFromQueryNoTables() throws IOException, InterruptedException { - // Mock job inserting. - Job dryRunJob = new Job().setStatistics( - new JobStatistics().setQuery(new JobStatistics2())); - Job insertedJob = new Job().setJobReference(new JobReference()); - when(mockJobsInsert.execute()).thenReturn(dryRunJob, insertedJob); - - // Mock job polling. - JobStatus status = new JobStatus().setState("DONE"); - TableReference tableRef = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - JobConfigurationQuery queryConfig = new JobConfigurationQuery().setDestinationTable(tableRef); - Job getJob = - new Job() - .setJobReference(new JobReference()) - .setStatus(status) - .setConfiguration(new JobConfiguration().setQuery(queryConfig)); - when(mockJobsGet.execute()).thenReturn(getJob); - - // Mock table schema fetch. - when(mockTablesGet.execute()).thenReturn(noTableQuerySchema()); - - byte[] photoBytes = "photograph".getBytes(); - String photoBytesEncoded = BaseEncoding.base64().encode(photoBytes); - // Mock table data fetch. - when(mockTabledataList.execute()).thenReturn( - rawDataList(rawRow("Arthur", 42, photoBytesEncoded))); - - // Run query and verify - String query = String.format( - "SELECT \"Arthur\" as name, 42 as count, \"%s\" as photo", - photoBytesEncoded); - try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null, null)) { - iterator.open(); - assertTrue(iterator.advance()); - TableRow row = iterator.getCurrent(); - - assertTrue(row.containsKey("name")); - assertTrue(row.containsKey("count")); - assertTrue(row.containsKey("photo")); - assertEquals("Arthur", row.get("name")); - assertEquals(42, row.get("count")); - assertEquals(photoBytesEncoded, row.get("photo")); - - assertFalse(iterator.advance()); - } - - // Temp dataset created and later deleted. - verify(mockClient, times(2)).datasets(); - verify(mockDatasets).insert(anyString(), any(Dataset.class)); - verify(mockDatasetsInsert).execute(); - verify(mockDatasets).delete(anyString(), anyString()); - verify(mockDatasetsDelete).execute(); - // Job inserted to run the query, polled once. - verify(mockClient, times(3)).jobs(); - verify(mockJobs, times(2)).insert(anyString(), any(Job.class)); - verify(mockJobsInsert, times(2)).execute(); - verify(mockJobs).get(anyString(), anyString()); - verify(mockJobsGet).execute(); - // Temp table get after query finish, deleted after reading. - verify(mockClient, times(2)).tables(); - verify(mockTables, times(1)).get(anyString(), anyString(), anyString()); - verify(mockTablesGet, times(1)).execute(); - verify(mockTables).delete(anyString(), anyString(), anyString()); - verify(mockTablesDelete).execute(); - // Table data read. - verify(mockClient).tabledata(); - verify(mockTabledata).list("project", "dataset", "table"); - verify(mockTabledataList).execute(); - } - - /** - * Verifies that when the query fails, the user gets a useful exception and the temporary dataset - * is cleaned up. Also verifies that the temporary table (which is never created) is not - * erroneously attempted to be deleted. - */ - @Test - public void testQueryFailed() throws IOException { - // Job state polled with an error. - String errorReason = "bad query"; - Exception exception = new IOException(errorReason); - when(mockJobsInsert.execute()).thenThrow(exception, exception, exception, exception); - - String query = "NOT A QUERY"; - try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null, null)) { - - try { - iterator.open(); - fail(); - } catch (Exception expected) { - // Verify message explains cause and reports the query. - assertThat(expected.getMessage(), containsString("Error")); - assertThat(expected.getMessage(), containsString(query)); - assertThat(expected.getCause().getMessage(), containsString(errorReason)); - } - } - - // Job inserted to run the query, then polled once. - verify(mockClient, times(1)).jobs(); - verify(mockJobs).insert(anyString(), any(Job.class)); - verify(mockJobsInsert, times(4)).execute(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java deleted file mode 100644 index fab4aecb47..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryUtilTest.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableCell; -import com.google.api.services.bigquery.model.TableDataInsertAllRequest; -import com.google.api.services.bigquery.model.TableDataInsertAllResponse; -import com.google.api.services.bigquery.model.TableDataList; -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * Tests for util classes related to BigQuery. - */ -@RunWith(JUnit4.class) -public class BigQueryUtilTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Mock private Bigquery mockClient; - @Mock private Bigquery.Tables mockTables; - @Mock private Bigquery.Tables.Get mockTablesGet; - @Mock private Bigquery.Tabledata mockTabledata; - @Mock private Bigquery.Tabledata.List mockTabledataList; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() { - verifyNoMoreInteractions(mockClient); - verifyNoMoreInteractions(mockTables); - verifyNoMoreInteractions(mockTablesGet); - verifyNoMoreInteractions(mockTabledata); - verifyNoMoreInteractions(mockTabledataList); - } - - private void onInsertAll(List> errorIndicesSequence) throws Exception { - when(mockClient.tabledata()) - .thenReturn(mockTabledata); - - final List responses = new ArrayList<>(); - for (List errorIndices : errorIndicesSequence) { - List errors = new ArrayList<>(); - for (long i : errorIndices) { - TableDataInsertAllResponse.InsertErrors error = - new TableDataInsertAllResponse.InsertErrors(); - error.setIndex(i); - } - TableDataInsertAllResponse response = new TableDataInsertAllResponse(); - response.setInsertErrors(errors); - responses.add(response); - } - - doAnswer( - new Answer() { - @Override - public Bigquery.Tabledata.InsertAll answer(InvocationOnMock invocation) throws Throwable { - Bigquery.Tabledata.InsertAll mockInsertAll = mock(Bigquery.Tabledata.InsertAll.class); - when(mockInsertAll.execute()) - .thenReturn(responses.get(0), - responses.subList(1, responses.size()).toArray( - new TableDataInsertAllResponse[responses.size() - 1])); - return mockInsertAll; - } - }) - .when(mockTabledata) - .insertAll(anyString(), anyString(), anyString(), any(TableDataInsertAllRequest.class)); - } - - private void verifyInsertAll(int expectedRetries) throws IOException { - verify(mockClient, times(expectedRetries)).tabledata(); - verify(mockTabledata, times(expectedRetries)) - .insertAll(anyString(), anyString(), anyString(), any(TableDataInsertAllRequest.class)); - } - - private void onTableGet(Table table) throws IOException { - when(mockClient.tables()) - .thenReturn(mockTables); - when(mockTables.get(anyString(), anyString(), anyString())) - .thenReturn(mockTablesGet); - when(mockTablesGet.execute()) - .thenReturn(table); - } - - private void verifyTableGet() throws IOException { - verify(mockClient).tables(); - verify(mockTables).get("project", "dataset", "table"); - verify(mockTablesGet, atLeastOnce()).execute(); - } - - private void onTableList(TableDataList result) throws IOException { - when(mockClient.tabledata()) - .thenReturn(mockTabledata); - when(mockTabledata.list(anyString(), anyString(), anyString())) - .thenReturn(mockTabledataList); - when(mockTabledataList.execute()) - .thenReturn(result); - } - - private void verifyTabledataList() throws IOException { - verify(mockClient, atLeastOnce()).tabledata(); - verify(mockTabledata, atLeastOnce()).list("project", "dataset", "table"); - verify(mockTabledataList, atLeastOnce()).execute(); - // Max results may be set when testing for an empty table. - verify(mockTabledataList, atLeast(0)).setMaxResults(anyLong()); - } - - private Table basicTableSchema() { - return new Table() - .setSchema(new TableSchema() - .setFields(Arrays.asList( - new TableFieldSchema() - .setName("name") - .setType("STRING"), - new TableFieldSchema() - .setName("answer") - .setType("INTEGER") - ))); - } - - private Table basicTableSchemaWithTime() { - return new Table() - .setSchema(new TableSchema() - .setFields(Arrays.asList( - new TableFieldSchema() - .setName("time") - .setType("TIMESTAMP") - ))); - } - - @Test - public void testReadWithTime() throws IOException, InterruptedException { - // The BigQuery JSON API returns timestamps in the following format: floating-point seconds - // since epoch (UTC) with microsecond precision. Test that we faithfully preserve a set of - // known values. - TableDataList input = rawDataList( - rawRow("1.430397296789E9"), - rawRow("1.45206228E9"), - rawRow("1.452062291E9"), - rawRow("1.4520622911E9"), - rawRow("1.45206229112E9"), - rawRow("1.452062291123E9"), - rawRow("1.4520622911234E9"), - rawRow("1.45206229112345E9"), - rawRow("1.452062291123456E9")); - onTableGet(basicTableSchemaWithTime()); - onTableList(input); - - // Known results verified from BigQuery's export to JSON on GCS API. - List expected = ImmutableList.of( - "2015-04-30 12:34:56.789 UTC", - "2016-01-06 06:38:00 UTC", - "2016-01-06 06:38:11 UTC", - "2016-01-06 06:38:11.1 UTC", - "2016-01-06 06:38:11.12 UTC", - "2016-01-06 06:38:11.123 UTC", - "2016-01-06 06:38:11.1234 UTC", - "2016-01-06 06:38:11.12345 UTC", - "2016-01-06 06:38:11.123456 UTC"); - - // Download the rows, verify the interactions. - List rows = new ArrayList<>(); - try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromTable( - BigQueryIO.parseTableSpec("project:dataset.table"), mockClient)) { - iterator.open(); - while (iterator.advance()) { - rows.add(iterator.getCurrent()); - } - } - verifyTableGet(); - verifyTabledataList(); - - // Verify the timestamp converted as desired. - assertEquals("Expected input and output rows to have the same size", - expected.size(), rows.size()); - for (int i = 0; i < expected.size(); ++i) { - assertEquals("i=" + i, expected.get(i), rows.get(i).get("time")); - } - - } - - private TableRow rawRow(Object...args) { - List cells = new LinkedList<>(); - for (Object a : args) { - cells.add(new TableCell().setV(a)); - } - return new TableRow().setF(cells); - } - - private TableDataList rawDataList(TableRow...rows) { - return new TableDataList() - .setRows(Arrays.asList(rows)); - } - - @Test - public void testRead() throws IOException, InterruptedException { - onTableGet(basicTableSchema()); - - TableDataList dataList = rawDataList(rawRow("Arthur", 42)); - onTableList(dataList); - - try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromTable( - BigQueryIO.parseTableSpec("project:dataset.table"), - mockClient)) { - iterator.open(); - Assert.assertTrue(iterator.advance()); - TableRow row = iterator.getCurrent(); - - Assert.assertTrue(row.containsKey("name")); - Assert.assertTrue(row.containsKey("answer")); - Assert.assertEquals("Arthur", row.get("name")); - Assert.assertEquals(42, row.get("answer")); - - Assert.assertFalse(iterator.advance()); - - verifyTableGet(); - verifyTabledataList(); - } - } - - @Test - public void testReadEmpty() throws IOException, InterruptedException { - onTableGet(basicTableSchema()); - - // BigQuery may respond with a page token for an empty table, ensure we - // handle it. - TableDataList dataList = new TableDataList() - .setPageToken("FEED==") - .setTotalRows(0L); - onTableList(dataList); - - try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromTable( - BigQueryIO.parseTableSpec("project:dataset.table"), - mockClient)) { - iterator.open(); - - Assert.assertFalse(iterator.advance()); - - verifyTableGet(); - verifyTabledataList(); - } - } - - @Test - public void testReadMultiPage() throws IOException, InterruptedException { - onTableGet(basicTableSchema()); - - TableDataList page1 = rawDataList(rawRow("Row1", 1)) - .setPageToken("page2"); - TableDataList page2 = rawDataList(rawRow("Row2", 2)) - .setTotalRows(2L); - - when(mockClient.tabledata()) - .thenReturn(mockTabledata); - when(mockTabledata.list(anyString(), anyString(), anyString())) - .thenReturn(mockTabledataList); - when(mockTabledataList.execute()) - .thenReturn(page1) - .thenReturn(page2); - - try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromTable( - BigQueryIO.parseTableSpec("project:dataset.table"), - mockClient)) { - iterator.open(); - - List names = new LinkedList<>(); - while (iterator.advance()) { - names.add((String) iterator.getCurrent().get("name")); - } - - Assert.assertThat(names, Matchers.hasItems("Row1", "Row2")); - - verifyTableGet(); - verifyTabledataList(); - // The second call should have used a page token. - verify(mockTabledataList).setPageToken("page2"); - } - } - - @Test - public void testReadOpenFailure() throws IOException, InterruptedException { - thrown.expect(IOException.class); - - when(mockClient.tables()) - .thenReturn(mockTables); - when(mockTables.get(anyString(), anyString(), anyString())) - .thenReturn(mockTablesGet); - when(mockTablesGet.execute()) - .thenThrow(new IOException("No such table")); - - try (BigQueryTableRowIterator iterator = BigQueryTableRowIterator.fromTable( - BigQueryIO.parseTableSpec("project:dataset.table"), - mockClient)) { - try { - iterator.open(); // throws. - } finally { - verifyTableGet(); - } - } - } - - @Test - public void testWriteAppend() throws IOException { - onTableGet(basicTableSchema()); - - TableReference ref = BigQueryIO - .parseTableSpec("project:dataset.table"); - - BigQueryTableInserter inserter = new BigQueryTableInserter(mockClient); - - inserter.getOrCreateTable(ref, BigQueryIO.Write.WriteDisposition.WRITE_APPEND, - BigQueryIO.Write.CreateDisposition.CREATE_NEVER, null); - - verifyTableGet(); - } - - @Test - public void testWriteEmpty() throws IOException { - onTableGet(basicTableSchema()); - - TableDataList dataList = new TableDataList().setTotalRows(0L); - onTableList(dataList); - - TableReference ref = BigQueryIO - .parseTableSpec("project:dataset.table"); - - BigQueryTableInserter inserter = new BigQueryTableInserter(mockClient); - - inserter.getOrCreateTable(ref, BigQueryIO.Write.WriteDisposition.WRITE_EMPTY, - BigQueryIO.Write.CreateDisposition.CREATE_NEVER, null); - - verifyTableGet(); - verifyTabledataList(); - } - - @Test - public void testWriteEmptyFail() throws IOException { - thrown.expect(IOException.class); - - onTableGet(basicTableSchema()); - - TableDataList dataList = rawDataList(rawRow("Arthur", 42)); - onTableList(dataList); - - TableReference ref = BigQueryIO - .parseTableSpec("project:dataset.table"); - - BigQueryTableInserter inserter = new BigQueryTableInserter(mockClient); - - try { - inserter.getOrCreateTable(ref, BigQueryIO.Write.WriteDisposition.WRITE_EMPTY, - BigQueryIO.Write.CreateDisposition.CREATE_NEVER, null); - } finally { - verifyTableGet(); - verifyTabledataList(); - } - } - - @Test - public void testInsertAll() throws Exception, IOException { - // Build up a list of indices to fail on each invocation. This should result in - // 5 calls to insertAll. - List> errorsIndices = new ArrayList<>(); - errorsIndices.add(Arrays.asList(0L, 5L, 10L, 15L, 20L)); - errorsIndices.add(Arrays.asList(0L, 2L, 4L)); - errorsIndices.add(Arrays.asList(0L, 2L)); - errorsIndices.add(new ArrayList()); - onInsertAll(errorsIndices); - - TableReference ref = BigQueryIO - .parseTableSpec("project:dataset.table"); - BigQueryTableInserter inserter = new BigQueryTableInserter(mockClient, 5); - - List rows = new ArrayList<>(); - List ids = new ArrayList<>(); - for (int i = 0; i < 25; ++i) { - rows.add(rawRow("foo", 1234)); - ids.add(new String()); - } - - InMemoryLongSumAggregator byteCountAggregator = new InMemoryLongSumAggregator("ByteCount"); - try { - inserter.insertAll(ref, rows, ids, byteCountAggregator); - } finally { - verifyInsertAll(5); - // Each of the 25 rows is 23 bytes: "{f=[{v=foo}, {v=1234}]}" - assertEquals("Incorrect byte count", 25L * 23L, byteCountAggregator.getSum()); - } - } - - private static class InMemoryLongSumAggregator implements Aggregator { - private final String name; - private long sum = 0; - - public InMemoryLongSumAggregator(String name) { - this.name = name; - } - - @Override - public void addValue(Long value) { - sum += value; - } - - @Override - public String getName() { - return name; - } - - @Override - public CombineFn getCombineFn() { - return new Sum.SumLongFn(); - } - - public long getSum() { - return sum; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java deleted file mode 100644 index 394dcbf349..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BucketingFunctionTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.Combine; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests {@link BucketingFunction}. - */ -@RunWith(JUnit4.class) -public class BucketingFunctionTest { - - private static final long BUCKET_WIDTH = 10; - private static final int SIGNIFICANT_BUCKETS = 2; - private static final int SIGNIFICANT_SAMPLES = 10; - - private static final Combine.BinaryCombineLongFn SUM = - new Combine.BinaryCombineLongFn() { - @Override - public long apply(long left, long right) { - return left + right; - } - - @Override - public long identity() { - return 0; - } - }; - - private BucketingFunction newFunc() { - return new - BucketingFunction(BUCKET_WIDTH, SIGNIFICANT_BUCKETS, - SIGNIFICANT_SAMPLES, SUM); - } - - @Test - public void significantSamples() { - BucketingFunction f = newFunc(); - assertFalse(f.isSignificant()); - for (int i = 0; i < SIGNIFICANT_SAMPLES - 1; i++) { - f.add(0, 0); - assertFalse(f.isSignificant()); - } - f.add(0, 0); - assertTrue(f.isSignificant()); - } - - @Test - public void significantBuckets() { - BucketingFunction f = newFunc(); - assertFalse(f.isSignificant()); - f.add(0, 0); - assertFalse(f.isSignificant()); - f.add(BUCKET_WIDTH, 0); - assertTrue(f.isSignificant()); - } - - @Test - public void sum() { - BucketingFunction f = newFunc(); - for (int i = 0; i < 100; i++) { - f.add(i, i); - assertEquals(((i + 1) * i) / 2, f.get()); - } - } - - @Test - public void movingSum() { - BucketingFunction f = newFunc(); - int lost = 0; - for (int i = 0; i < 200; i++) { - f.add(i, 1); - if (i >= 100) { - f.remove(i - 100); - if (i % BUCKET_WIDTH == BUCKET_WIDTH - 1) { - lost += BUCKET_WIDTH; - } - } - assertEquals(i + 1 - lost, f.get()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStreamTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStreamTest.java deleted file mode 100644 index af2f442550..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BufferedElementCountingOutputStreamTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.collection.IsIterableContainingInOrder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -/** - * Tests for {@link BufferedElementCountingOutputStream}. - */ -@RunWith(JUnit4.class) -public class BufferedElementCountingOutputStreamTest { - @Rule public final ExpectedException expectedException = ExpectedException.none(); - private static final int BUFFER_SIZE = 8; - - @Test - public void testEmptyValues() throws Exception { - testValues(Collections.emptyList()); - } - - @Test - public void testSingleValue() throws Exception { - testValues(toBytes("abc")); - } - - @Test - public void testSingleValueGreaterThanBuffer() throws Exception { - testValues(toBytes("abcdefghijklmnopqrstuvwxyz")); - } - - @Test - public void testMultipleValuesLessThanBuffer() throws Exception { - testValues(toBytes("a", "b", "c")); - } - - @Test - public void testMultipleValuesThatBecomeGreaterThanBuffer() throws Exception { - testValues(toBytes("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", - "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")); - } - - @Test - public void testMultipleRandomSizedValues() throws Exception { - Random r = new Random(234589023580234890L); - byte[] randomData = new byte[r.nextInt(18)]; - for (int i = 0; i < 1000; ++i) { - List bytes = new ArrayList<>(); - for (int j = 0; j < 100; ++j) { - r.nextBytes(randomData); - bytes.add(randomData); - } - testValues(bytes); - } - } - - @Test - public void testFlushInMiddleOfElement() throws Exception { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - BufferedElementCountingOutputStream os = new BufferedElementCountingOutputStream(bos); - os.markElementStart(); - os.write(1); - os.flush(); - os.write(2); - os.close(); - assertArrayEquals(new byte[]{ 1, 1, 2, 0 }, bos.toByteArray()); - } - - @Test - public void testFlushInMiddleOfElementUsingByteArrays() throws Exception { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - BufferedElementCountingOutputStream os = new BufferedElementCountingOutputStream(bos); - os.markElementStart(); - os.write(new byte[]{ 1 }); - os.flush(); - os.write(new byte[]{ 2 }); - os.close(); - assertArrayEquals(new byte[]{ 1, 1, 2, 0 }, bos.toByteArray()); - } - - @Test - public void testFlushingWhenFinishedIsNoOp() throws Exception { - BufferedElementCountingOutputStream os = testValues(toBytes("a")); - os.flush(); - os.flush(); - os.flush(); - } - - @Test - public void testFinishingWhenFinishedIsNoOp() throws Exception { - BufferedElementCountingOutputStream os = testValues(toBytes("a")); - os.finish(); - os.finish(); - os.finish(); - } - - @Test - public void testClosingFinishesTheStream() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - BufferedElementCountingOutputStream os = createAndWriteValues(toBytes("abcdefghij"), baos); - os.close(); - verifyValues(toBytes("abcdefghij"), new ByteArrayInputStream(baos.toByteArray())); - } - - @Test - public void testAddingElementWhenFinishedThrows() throws Exception { - expectedException.expect(IOException.class); - expectedException.expectMessage("Stream has been finished."); - testValues(toBytes("a")).markElementStart(); - } - - @Test - public void testWritingByteWhenFinishedThrows() throws Exception { - expectedException.expect(IOException.class); - expectedException.expectMessage("Stream has been finished."); - testValues(toBytes("a")).write(1); - } - - @Test - public void testWritingBytesWhenFinishedThrows() throws Exception { - expectedException.expect(IOException.class); - expectedException.expectMessage("Stream has been finished."); - testValues(toBytes("a")).write("b".getBytes()); - } - - private List toBytes(String ... values) { - ImmutableList.Builder builder = ImmutableList.builder(); - for (String value : values) { - builder.add(value.getBytes()); - } - return builder.build(); - } - - private BufferedElementCountingOutputStream - testValues(List expectedValues) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - BufferedElementCountingOutputStream os = createAndWriteValues(expectedValues, baos); - os.finish(); - verifyValues(expectedValues, new ByteArrayInputStream(baos.toByteArray())); - return os; - } - - private void verifyValues(List expectedValues, InputStream is) throws Exception { - List values = new ArrayList<>(); - long count; - do { - count = VarInt.decodeLong(is); - for (int i = 0; i < count; ++i) { - values.add(ByteArrayCoder.of().decode(is, Context.NESTED)); - } - } while(count > 0); - - if (expectedValues.isEmpty()) { - assertTrue(values.isEmpty()); - } else { - assertThat(values, IsIterableContainingInOrder.contains(expectedValues.toArray())); - } - } - - private BufferedElementCountingOutputStream - createAndWriteValues(List values, OutputStream output) throws Exception { - BufferedElementCountingOutputStream os = - new BufferedElementCountingOutputStream(output, BUFFER_SIZE); - - for (byte[] value : values) { - os.markElementStart(); - ByteArrayCoder.of().encode(value, os, Context.NESTED); - } - return os; - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CoderUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CoderUtilsTest.java deleted file mode 100644 index e192f456bc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CoderUtilsTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.CoderUtils.makeCloudEncoding; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - -import com.google.cloud.dataflow.sdk.coders.AtomicCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.testing.CoderPropertiesTest.ClosingCoder; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Tests for CoderUtils. - */ -@RunWith(JUnit4.class) -public class CoderUtilsTest { - - @Rule - public transient ExpectedException expectedException = ExpectedException.none(); - - static class TestCoder extends AtomicCoder { - public static TestCoder of() { - return new TestCoder(); - } - - @Override - public void encode(Integer value, OutputStream outStream, Context context) { - throw new RuntimeException("not expecting to be called"); - } - - @Override - public Integer decode(InputStream inStream, Context context) { - throw new RuntimeException("not expecting to be called"); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "TestCoder does not actually encode or decode."); - } - } - - @Test - public void testCoderExceptionPropagation() throws Exception { - @SuppressWarnings("unchecked") - Coder crashingCoder = mock(Coder.class); - doThrow(new CoderException("testing exception")) - .when(crashingCoder) - .encode(anyString(), any(OutputStream.class), any(Coder.Context.class)); - - expectedException.expect(CoderException.class); - expectedException.expectMessage("testing exception"); - - CoderUtils.encodeToByteArray(crashingCoder, "hello"); - } - - @Test - public void testCreateAtomicCoders() throws Exception { - Assert.assertEquals( - BigEndianIntegerCoder.of(), - Serializer.deserialize(makeCloudEncoding("BigEndianIntegerCoder"), Coder.class)); - Assert.assertEquals( - StringUtf8Coder.of(), - Serializer.deserialize( - makeCloudEncoding(StringUtf8Coder.class.getName()), Coder.class)); - Assert.assertEquals( - VoidCoder.of(), - Serializer.deserialize(makeCloudEncoding("VoidCoder"), Coder.class)); - Assert.assertEquals( - TestCoder.of(), - Serializer.deserialize(makeCloudEncoding(TestCoder.class.getName()), Coder.class)); - } - - @Test - public void testCreateCompositeCoders() throws Exception { - Assert.assertEquals( - IterableCoder.of(StringUtf8Coder.of()), - Serializer.deserialize( - makeCloudEncoding("IterableCoder", - makeCloudEncoding("StringUtf8Coder")), Coder.class)); - Assert.assertEquals( - KvCoder.of(BigEndianIntegerCoder.of(), VoidCoder.of()), - Serializer.deserialize( - makeCloudEncoding( - "KvCoder", - makeCloudEncoding(BigEndianIntegerCoder.class.getName()), - makeCloudEncoding("VoidCoder")), Coder.class)); - Assert.assertEquals( - IterableCoder.of( - KvCoder.of(IterableCoder.of(BigEndianIntegerCoder.of()), - KvCoder.of(VoidCoder.of(), - TestCoder.of()))), - Serializer.deserialize( - makeCloudEncoding( - IterableCoder.class.getName(), - makeCloudEncoding( - KvCoder.class.getName(), - makeCloudEncoding( - "IterableCoder", - makeCloudEncoding("BigEndianIntegerCoder")), - makeCloudEncoding( - "KvCoder", - makeCloudEncoding("VoidCoder"), - makeCloudEncoding(TestCoder.class.getName())))), Coder.class)); - } - - @Test - public void testCreateUntypedCoders() throws Exception { - Assert.assertEquals( - IterableCoder.of(StringUtf8Coder.of()), - Serializer.deserialize( - makeCloudEncoding( - "kind:stream", - makeCloudEncoding("StringUtf8Coder")), Coder.class)); - Assert.assertEquals( - KvCoder.of(BigEndianIntegerCoder.of(), VoidCoder.of()), - Serializer.deserialize( - makeCloudEncoding( - "kind:pair", - makeCloudEncoding(BigEndianIntegerCoder.class.getName()), - makeCloudEncoding("VoidCoder")), Coder.class)); - Assert.assertEquals( - IterableCoder.of( - KvCoder.of(IterableCoder.of(BigEndianIntegerCoder.of()), - KvCoder.of(VoidCoder.of(), - TestCoder.of()))), - Serializer.deserialize( - makeCloudEncoding( - "kind:stream", - makeCloudEncoding( - "kind:pair", - makeCloudEncoding( - "kind:stream", - makeCloudEncoding("BigEndianIntegerCoder")), - makeCloudEncoding( - "kind:pair", - makeCloudEncoding("VoidCoder"), - makeCloudEncoding(TestCoder.class.getName())))), Coder.class)); - } - - @Test - public void testCreateUnknownCoder() throws Exception { - try { - Serializer.deserialize(makeCloudEncoding("UnknownCoder"), Coder.class); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - CoreMatchers.containsString( - "Unable to convert coder ID UnknownCoder to class")); - } - } - - @Test - public void testClosingCoderFailsWhenDecodingBase64() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderUtils.decodeFromBase64(new ClosingCoder(), "test-value"); - } - - @Test - public void testClosingCoderFailsWhenDecodingByteArray() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderUtils.decodeFromByteArray(new ClosingCoder(), new byte[0]); - } - - @Test - public void testClosingCoderFailsWhenDecodingByteArrayInContext() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderUtils.decodeFromByteArray(new ClosingCoder(), new byte[0], Context.NESTED); - } - - @Test - public void testClosingCoderFailsWhenEncodingToBase64() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderUtils.encodeToBase64(new ClosingCoder(), "test-value"); - } - - @Test - public void testClosingCoderFailsWhenEncodingToByteArray() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderUtils.encodeToByteArray(new ClosingCoder(), "test-value"); - } - - @Test - public void testClosingCoderFailsWhenEncodingToByteArrayInContext() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - CoderUtils.encodeToByteArray(new ClosingCoder(), "test-value", Context.NESTED); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java deleted file mode 100644 index 978ee50f44..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CombineFnUtilTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.withSettings; - -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.util.state.StateContexts; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; -import java.io.NotSerializableException; -import java.io.ObjectOutputStream; - -/** - * Unit tests for {@link CombineFnUtil}. - */ -@RunWith(JUnit4.class) -public class CombineFnUtilTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - KeyedCombineFnWithContext mockCombineFn; - - @SuppressWarnings("unchecked") - @Before - public void setUp() { - mockCombineFn = mock(KeyedCombineFnWithContext.class, withSettings().serializable()); - } - - @Test - public void testNonSerializable() throws Exception { - expectedException.expect(NotSerializableException.class); - expectedException.expectMessage( - "Cannot serialize the CombineFn resulting from CombineFnUtil.bindContext."); - - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(buffer); - oos.writeObject(CombineFnUtil.bindContext(mockCombineFn, StateContexts.nullContext())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java deleted file mode 100644 index 4cc2f6a30e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/CounterAggregatorTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MIN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.IterableCombineFn; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.util.common.Counter; -import com.google.cloud.dataflow.sdk.util.common.CounterProvider; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator; -import com.google.common.collect.Iterables; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Unit tests for the {@link Aggregator} API. - */ -@RunWith(JUnit4.class) -public class CounterAggregatorTest { - @Rule - public final ExpectedException expectedEx = ExpectedException.none(); - - private static final String AGGREGATOR_NAME = "aggregator_name"; - - @SuppressWarnings("rawtypes") - private void testAggregator(List items, - Combine.CombineFn combiner, - Counter expectedCounter) { - CounterSet counters = new CounterSet(); - Aggregator aggregator = new CounterAggregator<>( - AGGREGATOR_NAME, combiner, counters.getAddCounterMutator()); - for (V item : items) { - aggregator.addValue(item); - } - - assertEquals(Iterables.getOnlyElement(counters), expectedCounter); - } - - @Test - public void testGetName() { - String name = "testAgg"; - CounterAggregator aggregator = new CounterAggregator<>( - name, new Sum.SumLongFn(), - new CounterSet().getAddCounterMutator()); - - assertEquals(name, aggregator.getName()); - } - - @Test - public void testGetCombineFn() { - CombineFn combineFn = new Min.MinLongFn(); - - CounterAggregator aggregator = new CounterAggregator<>("foo", - combineFn, new CounterSet().getAddCounterMutator()); - - assertEquals(combineFn, aggregator.getCombineFn()); - } - - @Test - - public void testSumInteger() throws Exception { - testAggregator(Arrays.asList(2, 4, 1, 3), new Sum.SumIntegerFn(), - Counter.ints(AGGREGATOR_NAME, SUM).resetToValue(10)); - } - - @Test - public void testSumLong() throws Exception { - testAggregator(Arrays.asList(2L, 4L, 1L, 3L), new Sum.SumLongFn(), - Counter.longs(AGGREGATOR_NAME, SUM).resetToValue(10L)); - } - - @Test - public void testSumDouble() throws Exception { - testAggregator(Arrays.asList(2.0, 4.1, 1.0, 3.1), new Sum.SumDoubleFn(), - Counter.doubles(AGGREGATOR_NAME, SUM).resetToValue(10.2)); - } - - @Test - public void testMinInteger() throws Exception { - testAggregator(Arrays.asList(2, 4, 1, 3), new Min.MinIntegerFn(), - Counter.ints(AGGREGATOR_NAME, MIN).resetToValue(1)); - } - - @Test - public void testMinLong() throws Exception { - testAggregator(Arrays.asList(2L, 4L, 1L, 3L), new Min.MinLongFn(), - Counter.longs(AGGREGATOR_NAME, MIN).resetToValue(1L)); - } - - @Test - public void testMinDouble() throws Exception { - testAggregator(Arrays.asList(2.0, 4.1, 1.0, 3.1), new Min.MinDoubleFn(), - Counter.doubles(AGGREGATOR_NAME, MIN).resetToValue(1.0)); - } - - @Test - public void testMaxInteger() throws Exception { - testAggregator(Arrays.asList(2, 4, 1, 3), new Max.MaxIntegerFn(), - Counter.ints(AGGREGATOR_NAME, MAX).resetToValue(4)); - } - - @Test - public void testMaxLong() throws Exception { - testAggregator(Arrays.asList(2L, 4L, 1L, 3L), new Max.MaxLongFn(), - Counter.longs(AGGREGATOR_NAME, MAX).resetToValue(4L)); - } - - @Test - public void testMaxDouble() throws Exception { - testAggregator(Arrays.asList(2.0, 4.1, 1.0, 3.1), new Max.MaxDoubleFn(), - Counter.doubles(AGGREGATOR_NAME, MAX).resetToValue(4.1)); - } - - @Test - public void testCounterProviderCallsProvidedCounterAddValue() { - @SuppressWarnings("unchecked") - CombineFn combiner = mock(CombineFn.class, - withSettings().extraInterfaces(CounterProvider.class)); - @SuppressWarnings("unchecked") - CounterProvider provider = (CounterProvider) combiner; - - @SuppressWarnings("unchecked") - Counter mockCounter = mock(Counter.class); - String name = "foo"; - when(provider.getCounter(name)).thenReturn(mockCounter); - - AddCounterMutator addCounterMutator = mock(AddCounterMutator.class); - when(addCounterMutator.addCounter(mockCounter)).thenReturn(mockCounter); - - Aggregator aggregator = - new CounterAggregator<>(name, combiner, addCounterMutator); - - aggregator.addValue("bar_baz"); - - verify(mockCounter).addValue("bar_baz"); - verify(addCounterMutator).addCounter(mockCounter); - } - - - @Test - public void testCompatibleDuplicateNames() throws Exception { - CounterSet counters = new CounterSet(); - Aggregator aggregator1 = new CounterAggregator<>( - AGGREGATOR_NAME, new Sum.SumIntegerFn(), - counters.getAddCounterMutator()); - - Aggregator aggregator2 = new CounterAggregator<>( - AGGREGATOR_NAME, new Sum.SumIntegerFn(), - counters.getAddCounterMutator()); - - // The duplicate aggregators should update the same counter. - aggregator1.addValue(3); - aggregator2.addValue(4); - Assert.assertEquals( - new CounterSet(Counter.ints(AGGREGATOR_NAME, SUM).resetToValue(7)), - counters); - } - - @Test - public void testIncompatibleDuplicateNames() throws Exception { - CounterSet counters = new CounterSet(); - new CounterAggregator<>( - AGGREGATOR_NAME, new Sum.SumIntegerFn(), - counters.getAddCounterMutator()); - - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage(Matchers.containsString( - "aggregator's name collides with an existing aggregator or " - + "system-provided counter of an incompatible type")); - new CounterAggregator<>( - AGGREGATOR_NAME, new Sum.SumLongFn(), - counters.getAddCounterMutator()); - } - - @Test - public void testUnsupportedCombineFn() throws Exception { - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage(Matchers.containsString("unsupported combiner")); - new CounterAggregator<>( - AGGREGATOR_NAME, - new Combine.CombineFn, Integer>() { - @Override - public List createAccumulator() { - return null; - } - @Override - public List addInput(List accumulator, Integer input) { - return null; - } - @Override - public List mergeAccumulators(Iterable> accumulators) { - return null; - } - @Override - public Integer extractOutput(List accumulator) { - return null; - } - }, (new CounterSet()).getAddCounterMutator()); - } - - @Test - public void testUnsupportedSerializableFunction() throws Exception { - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage(Matchers.containsString("unsupported combiner")); - CombineFn, Integer> combiner = IterableCombineFn - .of(new SerializableFunction, Integer>() { - @Override - public Integer apply(Iterable input) { - return null; - } - }); - new CounterAggregator<>(AGGREGATOR_NAME, combiner, - (new CounterSet()).getAddCounterMutator()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidatorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidatorTest.java deleted file mode 100644 index 19d5adc7cf..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidatorTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** Tests for {@link DataflowPathValidator}. */ -@RunWith(JUnit4.class) -public class DataflowPathValidatorTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Mock private GcsUtil mockGcsUtil; - private DataflowPathValidator validator; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(true); - when(mockGcsUtil.isGcsPatternSupported(anyString())).thenCallRealMethod(); - DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); - options.setGcpCredential(new TestCredential()); - options.setRunner(DataflowPipelineRunner.class); - options.setGcsUtil(mockGcsUtil); - validator = new DataflowPathValidator(options); - } - - @Test - public void testValidFilePattern() { - validator.validateInputFilePatternSupported("gs://bucket/path"); - } - - @Test - public void testInvalidFilePattern() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "DataflowPipelineRunner expected a valid 'gs://' path but was given '/local/path'"); - validator.validateInputFilePatternSupported("/local/path"); - } - - @Test - public void testWhenBucketDoesNotExist() throws Exception { - when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(false); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Could not find file gs://non-existent-bucket/location"); - validator.validateInputFilePatternSupported("gs://non-existent-bucket/location"); - } - - @Test - public void testValidOutputPrefix() { - validator.validateOutputFilePrefixSupported("gs://bucket/path"); - } - - @Test - public void testInvalidOutputPrefix() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "DataflowPipelineRunner expected a valid 'gs://' path but was given '/local/path'"); - validator.validateOutputFilePrefixSupported("/local/path"); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java deleted file mode 100644 index 7b8466a5fa..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExecutableTriggerTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for {@link ExecutableTrigger}. - */ -@RunWith(JUnit4.class) -public class ExecutableTriggerTest { - - @Test - public void testIndexAssignmentLeaf() throws Exception { - StubTrigger t1 = new StubTrigger(); - ExecutableTrigger executable = ExecutableTrigger.create(t1); - assertEquals(0, executable.getTriggerIndex()); - } - - @Test - public void testIndexAssignmentOneLevel() throws Exception { - StubTrigger t1 = new StubTrigger(); - StubTrigger t2 = new StubTrigger(); - StubTrigger t = new StubTrigger(t1, t2); - - ExecutableTrigger executable = ExecutableTrigger.create(t); - - assertEquals(0, executable.getTriggerIndex()); - assertEquals(1, executable.subTriggers().get(0).getTriggerIndex()); - assertSame(t1, executable.subTriggers().get(0).getSpec()); - assertEquals(2, executable.subTriggers().get(1).getTriggerIndex()); - assertSame(t2, executable.subTriggers().get(1).getSpec()); - } - - @Test - public void testIndexAssignmentTwoLevel() throws Exception { - StubTrigger t11 = new StubTrigger(); - StubTrigger t12 = new StubTrigger(); - StubTrigger t13 = new StubTrigger(); - StubTrigger t14 = new StubTrigger(); - StubTrigger t21 = new StubTrigger(); - StubTrigger t22 = new StubTrigger(); - StubTrigger t1 = new StubTrigger(t11, t12, t13, t14); - StubTrigger t2 = new StubTrigger(t21, t22); - StubTrigger t = new StubTrigger(t1, t2); - - ExecutableTrigger executable = ExecutableTrigger.create(t); - - assertEquals(0, executable.getTriggerIndex()); - assertEquals(1, executable.subTriggers().get(0).getTriggerIndex()); - assertEquals(6, executable.subTriggers().get(0).getFirstIndexAfterSubtree()); - assertEquals(6, executable.subTriggers().get(1).getTriggerIndex()); - - assertSame(t1, executable.getSubTriggerContaining(1).getSpec()); - assertSame(t2, executable.getSubTriggerContaining(6).getSpec()); - assertSame(t1, executable.getSubTriggerContaining(2).getSpec()); - assertSame(t1, executable.getSubTriggerContaining(3).getSpec()); - assertSame(t1, executable.getSubTriggerContaining(5).getSpec()); - assertSame(t2, executable.getSubTriggerContaining(7).getSpec()); - } - - private static class StubTrigger extends Trigger { - - @SafeVarargs - protected StubTrigger(Trigger... subTriggers) { - super(Arrays.asList(subTriggers)); - } - - @Override - public void onElement(OnElementContext c) throws Exception { } - - @Override - public void onMerge(OnMergeContext c) throws Exception { } - - @Override - public void clear(TriggerContext c) throws Exception { - } - - @Override - public Instant getWatermarkThatGuaranteesFiring(IntervalWindow window) { - return BoundedWindow.TIMESTAMP_MAX_VALUE; - } - - @Override - public boolean isCompatible(Trigger other) { - return false; - } - - @Override - public Trigger getContinuationTrigger( - List> continuationTriggers) { - return this; - } - - @Override - public boolean shouldFire(TriggerContext c) { - return false; - } - - @Override - public void onFire(TriggerContext c) { } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStreamTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStreamTest.java deleted file mode 100644 index 00830e96cd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayInputStreamTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -/** Unit tests for {@link ExposedByteArrayInputStream}. */ -@RunWith(JUnit4.class) -public class ExposedByteArrayInputStreamTest { - - private static final byte[] TEST_DATA = "Hello World!".getBytes(); - - private ByteArrayInputStream stream = new ByteArrayInputStream(TEST_DATA); - - private ExposedByteArrayInputStream exposedStream = new ExposedByteArrayInputStream(TEST_DATA); - - @Test - public void testConstructWithEmptyArray() throws IOException { - try (ExposedByteArrayInputStream s = new ExposedByteArrayInputStream(new byte[0])) { - assertEquals(0, s.available()); - byte[] data = s.readAll(); - assertEquals(0, data.length); - } - } - - @Test - public void testReadAll() throws IOException { - assertEquals(TEST_DATA.length, exposedStream.available()); - byte[] data = exposedStream.readAll(); - assertArrayEquals(TEST_DATA, data); - assertSame(TEST_DATA, data); - assertEquals(0, exposedStream.available()); - } - - @Test - public void testReadPartial() throws IOException { - assertEquals(TEST_DATA.length, exposedStream.available()); - assertEquals(TEST_DATA.length, stream.available()); - byte[] data1 = new byte[4]; - byte[] data2 = new byte[4]; - int ret1 = exposedStream.read(data1); - int ret2 = stream.read(data2); - assertEquals(ret2, ret1); - assertArrayEquals(data2, data1); - assertEquals(stream.available(), exposedStream.available()); - } - - @Test - public void testReadAllAfterReadPartial() throws IOException { - assertNotEquals(-1, exposedStream.read()); - byte[] ret = exposedStream.readAll(); - assertArrayEquals("ello World!".getBytes(), ret); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStreamTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStreamTest.java deleted file mode 100644 index f40f0508db..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ExposedByteArrayOutputStreamTest.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** Unit tests for {@link ExposedByteArrayOutputStream}. */ -@RunWith(JUnit4.class) -public class ExposedByteArrayOutputStreamTest { - - private static final byte[] TEST_DATA = "Hello World!".getBytes(); - - private ExposedByteArrayOutputStream exposedStream = new ExposedByteArrayOutputStream(); - private ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - @Test - public void testNoWrite() { - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteZeroLengthArray() throws IOException { - writeToBoth(new byte[0]); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteZeroLengthArrayWithOffset(){ - writeToBoth(new byte[0], 0, 0); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteSingleByte() { - writeToBoth(32); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteSingleByteTwice() { - writeToBoth(32); - writeToBoth(32); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteSingleArray() throws IOException { - writeToBoth(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - assertNotSame(TEST_DATA, exposedStream.toByteArray()); - } - - @Test - public void testWriteSingleArrayFast() throws IOException { - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - assertSame(TEST_DATA, exposedStream.toByteArray()); - } - - - @Test - public void testWriteSingleArrayTwice() throws IOException { - writeToBoth(TEST_DATA); - writeToBoth(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteSingleArrayTwiceFast() throws IOException { - writeToBothFast(TEST_DATA); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteSingleArrayTwiceFast1() throws IOException { - writeToBothFast(TEST_DATA); - writeToBoth(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteSingleArrayTwiceFast2() throws IOException { - writeToBoth(TEST_DATA); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteSingleArrayWithLength() { - writeToBoth(TEST_DATA, 0, TEST_DATA.length); - assertStreamContentsEquals(stream, exposedStream); - assertNotSame(TEST_DATA, exposedStream.toByteArray()); - } - - @Test - public void testWritePartial() { - writeToBoth(TEST_DATA, 0, TEST_DATA.length - 1); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWritePartialWithNonZeroBegin() { - writeToBoth(TEST_DATA, 1, TEST_DATA.length - 1); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteByteAfterWriteArrayFast() throws IOException { - writeToBothFast(TEST_DATA); - writeToBoth(32); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteArrayFastAfterByte() throws IOException { - writeToBoth(32); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testResetAfterWriteFast() throws IOException { - writeToBothFast(TEST_DATA); - resetBoth(); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteArrayFastAfterReset() throws IOException { - writeToBothFast(TEST_DATA); - resetBoth(); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - assertSame(TEST_DATA, exposedStream.toByteArray()); - } - - @Test - public void testWriteArrayFastAfterReset1() throws IOException { - writeToBothFast(TEST_DATA); - writeToBothFast(TEST_DATA); - resetBoth(); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - assertSame(TEST_DATA, exposedStream.toByteArray()); - } - - @Test - public void testWriteArrayFastAfterReset2() throws IOException { - resetBoth(); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - assertSame(TEST_DATA, exposedStream.toByteArray()); - } - - @Test - public void testWriteArrayFastTwiceAfterReset() throws IOException { - writeToBothFast(TEST_DATA); - resetBoth(); - writeToBothFast(TEST_DATA); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteArrayFastTwiceAfterReset1() throws IOException { - writeToBothFast(TEST_DATA); - writeToBothFast(TEST_DATA); - resetBoth(); - writeToBothFast(TEST_DATA); - writeToBothFast(TEST_DATA); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteByteAfterReset() { - writeToBoth(32); - resetBoth(); - writeToBoth(32); - assertStreamContentsEquals(stream, exposedStream); - } - - @Test - public void testWriteByteAfterReset1() { - resetBoth(); - writeToBoth(32); - assertStreamContentsEquals(stream, exposedStream); - } - - private void assertStreamContentsEquals( - ByteArrayOutputStream stream1, ByteArrayOutputStream stream2) { - assertArrayEquals(stream1.toByteArray(), stream2.toByteArray()); - assertEquals(stream1.toString(), stream2.toString()); - assertEquals(stream1.size(), stream2.size()); - } - - private void writeToBoth(int b) { - exposedStream.write(b); - stream.write(b); - } - - private void writeToBoth(byte[] b) throws IOException { - exposedStream.write(b); - stream.write(b); - } - - private void writeToBothFast(byte[] b) throws IOException { - exposedStream.writeAndOwn(b); - stream.write(b); - } - - private void writeToBoth(byte[] b, int off, int length) { - exposedStream.write(b, off, length); - stream.write(b, off, length); - } - - private void resetBoth() { - exposedStream.reset(); - stream.reset(); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java deleted file mode 100644 index 80ec3a1308..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FileIOChannelFactoryTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.common.collect.ImmutableList; -import com.google.common.io.Files; -import com.google.common.io.LineReader; - -import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.Reader; -import java.io.Writer; -import java.nio.channels.Channels; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.List; - -/** Tests for {@link FileIOChannelFactory}. */ -@RunWith(JUnit4.class) -public class FileIOChannelFactoryTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private FileIOChannelFactory factory = new FileIOChannelFactory(); - - private void testCreate(Path path) throws Exception { - String expected = "my test string"; - try (Writer writer = Channels.newWriter( - factory.create(path.toString(), MimeTypes.TEXT), StandardCharsets.UTF_8.name())) { - writer.write(expected); - } - assertThat( - Files.readLines(path.toFile(), StandardCharsets.UTF_8), - containsInAnyOrder(expected)); - } - - @Test - public void testCreateWithExistingFile() throws Exception { - File existingFile = temporaryFolder.newFile(); - testCreate(existingFile.toPath()); - } - - @Test - public void testCreateWithinExistingDirectory() throws Exception { - testCreate(temporaryFolder.getRoot().toPath().resolve("file.txt")); - } - - @Test - public void testCreateWithNonExistentSubDirectory() throws Exception { - testCreate(temporaryFolder.getRoot().toPath().resolve("non-existent-dir").resolve("file.txt")); - } - - @Test - public void testReadWithExistingFile() throws Exception { - String expected = "my test string"; - File existingFile = temporaryFolder.newFile(); - Files.write(expected, existingFile, StandardCharsets.UTF_8); - String data; - try (Reader reader = - Channels.newReader(factory.open(existingFile.getPath()), StandardCharsets.UTF_8.name())) { - data = new LineReader(reader).readLine(); - } - assertEquals(expected, data); - } - - @Test - public void testReadNonExistentFile() throws Exception { - thrown.expect(FileNotFoundException.class); - factory - .open( - temporaryFolder - .getRoot() - .toPath() - .resolve("non-existent-file.txt") - .toString()) - .close(); - } - - @Test - public void testIsReadSeekEfficient() throws Exception { - assertTrue(factory.isReadSeekEfficient("somePath")); - } - - @Test - public void testMatchExact() throws Exception { - List expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); - temporaryFolder.newFile("aa"); - temporaryFolder.newFile("ab"); - - assertThat(factory.match(temporaryFolder.getRoot().toPath().resolve("a").toString()), - containsInAnyOrder(expected.toArray(new String[expected.size()]))); - } - - @Test - public void testMatchNone() throws Exception { - List expected = ImmutableList.of(); - temporaryFolder.newFile("a"); - temporaryFolder.newFile("aa"); - temporaryFolder.newFile("ab"); - - // Windows doesn't like resolving paths with * in them, so the * is appended after resolve. - assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "b") + "*"), - containsInAnyOrder(expected.toArray(new String[expected.size()]))); - } - - @Test - public void testMatchUsingExplicitPath() throws Exception { - List expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); - temporaryFolder.newFile("aa"); - - assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a")), - containsInAnyOrder(expected.toArray(new String[expected.size()]))); - } - - @Test - public void testMatchUsingExplicitPathForNonExistentFile() throws Exception { - List expected = ImmutableList.of(); - temporaryFolder.newFile("aa"); - - assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a")), - containsInAnyOrder(expected.toArray(new String[expected.size()]))); - } - - @Test - public void testMatchMultipleWithoutSubdirectoryExpansion() throws Exception { - File unmatchedSubDir = temporaryFolder.newFolder("aaa"); - File unmatchedSubDirFile = File.createTempFile("sub-dir-file", "", unmatchedSubDir); - unmatchedSubDirFile.deleteOnExit(); - List expected = ImmutableList.of(temporaryFolder.newFile("a").toString(), - temporaryFolder.newFile("aa").toString(), temporaryFolder.newFile("ab").toString()); - temporaryFolder.newFile("ba"); - temporaryFolder.newFile("bb"); - - // Windows doesn't like resolving paths with * in them, so the * is appended after resolve. - assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a") + "*"), - containsInAnyOrder(expected.toArray(new String[expected.size()]))); - } - - @Test - public void testMatchMultipleWithSubdirectoryExpansion() throws Exception { - File matchedSubDir = temporaryFolder.newFolder("a"); - File matchedSubDirFile = File.createTempFile("sub-dir-file", "", matchedSubDir); - matchedSubDirFile.deleteOnExit(); - File unmatchedSubDir = temporaryFolder.newFolder("b"); - File unmatchedSubDirFile = File.createTempFile("sub-dir-file", "", unmatchedSubDir); - unmatchedSubDirFile.deleteOnExit(); - - List expected = ImmutableList.of(matchedSubDirFile.toString(), - temporaryFolder.newFile("aa").toString(), temporaryFolder.newFile("ab").toString()); - temporaryFolder.newFile("ba"); - temporaryFolder.newFile("bb"); - - // Windows doesn't like resolving paths with * in them, so the ** is appended after resolve. - assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a") + "**"), - Matchers.hasItems(expected.toArray(new String[expected.size()]))); - } - - @Test - public void testMatchWithDirectoryFiltersOutDirectory() throws Exception { - List expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); - temporaryFolder.newFolder("a_dir_that_should_not_be_matched"); - - // Windows doesn't like resolving paths with * in them, so the * is appended after resolve. - assertThat(factory.match(factory.resolve(temporaryFolder.getRoot().getPath(), "a") + "*"), - containsInAnyOrder(expected.toArray(new String[expected.size()]))); - } - - @Test - public void testResolve() throws Exception { - String expected = temporaryFolder.getRoot().toPath().resolve("aa").toString(); - assertEquals(expected, factory.resolve(temporaryFolder.getRoot().toString(), "aa")); - } - - @Test - public void testResolveOtherIsFullPath() throws Exception { - String expected = temporaryFolder.getRoot().getPath().toString(); - assertEquals(expected, factory.resolve(expected, expected)); - } - - @Test - public void testResolveOtherIsEmptyPath() throws Exception { - String expected = temporaryFolder.getRoot().getPath().toString(); - assertEquals(expected, factory.resolve(expected, "")); - } - - @Test - public void testGetSizeBytes() throws Exception { - String data = "TestData!!!"; - File file = temporaryFolder.newFile(); - Files.write(data, file, StandardCharsets.UTF_8); - assertEquals(data.length(), factory.getSizeBytes(file.getPath())); - } - - @Test - public void testGetSizeBytesForNonExistentFile() throws Exception { - thrown.expect(FileNotFoundException.class); - factory.getSizeBytes( - factory.resolve(temporaryFolder.getRoot().getPath(), "non-existent-file")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java deleted file mode 100644 index 7e66683e26..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersBitSetTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.theInstance; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link FinishedTriggersBitSet}. - */ -@RunWith(JUnit4.class) -public class FinishedTriggersBitSetTest { - /** - * Tests that after a trigger is set to finished, it reads back as finished. - */ - @Test - public void testSetGet() { - FinishedTriggersProperties.verifyGetAfterSet(FinishedTriggersBitSet.emptyWithCapacity(1)); - } - - /** - * Tests that clearing a trigger recursively clears all of that triggers subTriggers, but no - * others. - */ - @Test - public void testClearRecursively() { - FinishedTriggersProperties.verifyClearRecursively(FinishedTriggersBitSet.emptyWithCapacity(1)); - } - - @Test - public void testCopy() throws Exception { - FinishedTriggersBitSet finishedSet = FinishedTriggersBitSet.emptyWithCapacity(10); - assertThat(finishedSet.copy().getBitSet(), not(theInstance(finishedSet.getBitSet()))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java deleted file mode 100644 index 7b3ac689af..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersProperties.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterAll; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterFirst; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; - -/** - * Generalized tests for {@link FinishedTriggers} implementations. - */ -public class FinishedTriggersProperties { - /** - * Tests that for the provided trigger and {@link FinishedTriggers}, when the trigger is set - * finished, it is correctly reported as finished. - */ - public static void verifyGetAfterSet(FinishedTriggers finishedSet, ExecutableTrigger trigger) { - assertFalse(finishedSet.isFinished(trigger)); - finishedSet.setFinished(trigger, true); - assertTrue(finishedSet.isFinished(trigger)); - } - - /** - * For a few arbitrary triggers, tests that when the trigger is set finished it is correctly - * reported as finished. - */ - public static void verifyGetAfterSet(FinishedTriggers finishedSet) { - ExecutableTrigger trigger = ExecutableTrigger.create(AfterAll.of( - AfterFirst.of(AfterPane.elementCountAtLeast(3), AfterWatermark.pastEndOfWindow()), - AfterAll.of( - AfterPane.elementCountAtLeast(10), AfterProcessingTime.pastFirstElementInPane()))); - - verifyGetAfterSet(finishedSet, trigger); - verifyGetAfterSet(finishedSet, trigger.subTriggers().get(0).subTriggers().get(1)); - verifyGetAfterSet(finishedSet, trigger.subTriggers().get(0)); - verifyGetAfterSet(finishedSet, trigger.subTriggers().get(1)); - verifyGetAfterSet(finishedSet, trigger.subTriggers().get(1).subTriggers().get(1)); - verifyGetAfterSet(finishedSet, trigger.subTriggers().get(1).subTriggers().get(0)); - } - - /** - * Tests that clearing a trigger recursively clears all of that triggers subTriggers, but no - * others. - */ - public static void verifyClearRecursively(FinishedTriggers finishedSet) { - ExecutableTrigger trigger = ExecutableTrigger.create(AfterAll.of( - AfterFirst.of(AfterPane.elementCountAtLeast(3), AfterWatermark.pastEndOfWindow()), - AfterAll.of( - AfterPane.elementCountAtLeast(10), AfterProcessingTime.pastFirstElementInPane()))); - - // Set them all finished. This method is not on a trigger as it makes no sense outside tests. - setFinishedRecursively(finishedSet, trigger); - assertTrue(finishedSet.isFinished(trigger)); - assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0))); - assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0).subTriggers().get(0))); - assertTrue(finishedSet.isFinished(trigger.subTriggers().get(0).subTriggers().get(1))); - - // Clear just the second AfterAll - finishedSet.clearRecursively(trigger.subTriggers().get(1)); - - // Check that the first and all that are still finished - assertTrue(finishedSet.isFinished(trigger)); - verifyFinishedRecursively(finishedSet, trigger.subTriggers().get(0)); - verifyUnfinishedRecursively(finishedSet, trigger.subTriggers().get(1)); - } - - private static void setFinishedRecursively( - FinishedTriggers finishedSet, ExecutableTrigger trigger) { - finishedSet.setFinished(trigger, true); - for (ExecutableTrigger subTrigger : trigger.subTriggers()) { - setFinishedRecursively(finishedSet, subTrigger); - } - } - - private static void verifyFinishedRecursively( - FinishedTriggers finishedSet, ExecutableTrigger trigger) { - assertTrue(finishedSet.isFinished(trigger)); - for (ExecutableTrigger subTrigger : trigger.subTriggers()) { - verifyFinishedRecursively(finishedSet, subTrigger); - } - } - - private static void verifyUnfinishedRecursively( - FinishedTriggers finishedSet, ExecutableTrigger trigger) { - assertFalse(finishedSet.isFinished(trigger)); - for (ExecutableTrigger subTrigger : trigger.subTriggers()) { - verifyUnfinishedRecursively(finishedSet, subTrigger); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java deleted file mode 100644 index 60384deebd..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FinishedTriggersSetTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.theInstance; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.HashSet; - -/** - * Tests for {@link FinishedTriggersSet}. - */ -@RunWith(JUnit4.class) -public class FinishedTriggersSetTest { - /** - * Tests that after a trigger is set to finished, it reads back as finished. - */ - @Test - public void testSetGet() { - FinishedTriggersProperties.verifyGetAfterSet( - FinishedTriggersSet.fromSet(new HashSet>())); - } - - /** - * Tests that clearing a trigger recursively clears all of that triggers subTriggers, but no - * others. - */ - @Test - public void testClearRecursively() { - FinishedTriggersProperties.verifyClearRecursively( - FinishedTriggersSet.fromSet(new HashSet>())); - } - - @Test - public void testCopy() throws Exception { - FinishedTriggersSet finishedSet = - FinishedTriggersSet.fromSet(new HashSet>()); - assertThat(finishedSet.copy().getFinishedTriggers(), - not(theInstance(finishedSet.getFinishedTriggers()))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java deleted file mode 100644 index a251387aae..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/FluentBackoffTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.api.client.util.BackOff; - -import org.joda.time.Duration; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; - -/** - * Tests for {@link FluentBackoff}. - */ -@RunWith(JUnit4.class) -public class FluentBackoffTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final FluentBackoff defaultBackoff = FluentBackoff.DEFAULT; - - @Test - public void testInvalidExponent() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("exponent -2.0 must be greater than 0"); - defaultBackoff.withExponent(-2.0); - } - - @Test - public void testInvalidInitialBackoff() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("initialBackoff PT0S must be at least 1 millisecond"); - defaultBackoff.withInitialBackoff(Duration.ZERO); - } - - @Test - public void testInvalidMaxBackoff() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("maxBackoff PT0S must be at least 1 millisecond"); - defaultBackoff.withMaxBackoff(Duration.ZERO); - } - - @Test - public void testInvalidMaxRetries() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("maxRetries -1 cannot be negative"); - defaultBackoff.withMaxRetries(-1); - } - - @Test - public void testInvalidCumulativeBackoff() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("maxCumulativeBackoff PT-0.002S must be at least 1 millisecond"); - defaultBackoff.withMaxCumulativeBackoff(Duration.millis(-2)); - } - - /** - * Tests with bounded interval, custom exponent, and unlimited retries. - */ - @Test - public void testBoundedIntervalWithReset() throws Exception { - BackOff backOff = - FluentBackoff.DEFAULT - .withInitialBackoff(Duration.millis(500)) - .withMaxBackoff(Duration.standardSeconds(1)).backoff(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(374L), lessThan(1126L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - - // Reset, should go back to short times. - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(374L), lessThan(1126L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - - } - - /** - * Tests with bounded interval, custom exponent, limited retries, and a reset. - */ - @Test - public void testMaxRetriesWithReset() throws Exception { - BackOff backOff = - FluentBackoff.DEFAULT - .withInitialBackoff(Duration.millis(500)) - .withMaxRetries(1) - .backoff(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); - assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); - assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); - assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); - - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), equalTo(BackOff.STOP)); - } - - private static long countMaximumBackoff(BackOff backOff) throws IOException { - long cumulativeBackoffMillis = 0; - long currentBackoffMillis = backOff.nextBackOffMillis(); - while (currentBackoffMillis != BackOff.STOP) { - cumulativeBackoffMillis += currentBackoffMillis; - currentBackoffMillis = backOff.nextBackOffMillis(); - } - return cumulativeBackoffMillis; - } - - /** - * Tests with bounded interval, custom exponent, limited cumulative time, and a reset. - */ - @Test - public void testBoundedIntervalAndCumTimeWithReset() throws Exception { - BackOff backOff = - FluentBackoff.DEFAULT - .withInitialBackoff(Duration.millis(500)) - .withMaxBackoff(Duration.standardSeconds(1)) - .withMaxCumulativeBackoff(Duration.standardMinutes(1)).backoff(); - - assertThat(countMaximumBackoff(backOff), equalTo(Duration.standardMinutes(1).getMillis())); - - backOff.reset(); - assertThat(countMaximumBackoff(backOff), equalTo(Duration.standardMinutes(1).getMillis())); - // sanity check: should get 0 if we don't reset - assertThat(countMaximumBackoff(backOff), equalTo(0L)); - - backOff.reset(); - assertThat(countMaximumBackoff(backOff), equalTo(Duration.standardMinutes(1).getMillis())); - } - - /** - * Tests with bounded interval, custom exponent, limited cumulative time and retries. - */ - @Test - public void testBoundedIntervalAndCumTimeAndRetriesWithReset() throws Exception { - BackOff backOff = - FluentBackoff.DEFAULT - .withInitialBackoff(Duration.millis(500)) - .withMaxBackoff(Duration.standardSeconds(1)) - .withMaxCumulativeBackoff(Duration.standardMinutes(1)) - .backoff(); - - long cumulativeBackoffMillis = 0; - long currentBackoffMillis = backOff.nextBackOffMillis(); - while (currentBackoffMillis != BackOff.STOP) { - cumulativeBackoffMillis += currentBackoffMillis; - currentBackoffMillis = backOff.nextBackOffMillis(); - } - assertThat(cumulativeBackoffMillis, equalTo(Duration.standardMinutes(1).getMillis())); - } - - @Test - public void testFluentBackoffToString() throws IOException { - FluentBackoff config = FluentBackoff.DEFAULT - .withExponent(3.4) - .withMaxRetries(4) - .withInitialBackoff(Duration.standardSeconds(3)) - .withMaxBackoff(Duration.standardHours(1)) - .withMaxCumulativeBackoff(Duration.standardDays(1)); - - assertEquals( - "FluentBackoff{exponent=3.4, initialBackoff=PT3S, maxBackoff=PT3600S," - + " maxRetries=4, maxCumulativeBackoff=PT86400S}", - config.toString()); - } - @Test - public void testBackoffImplToString() throws IOException { - FluentBackoff config = FluentBackoff.DEFAULT - .withExponent(3.4) - .withMaxRetries(4) - .withInitialBackoff(Duration.standardSeconds(3)) - .withMaxBackoff(Duration.standardHours(1)) - .withMaxCumulativeBackoff(Duration.standardDays(1)); - BackOff backOff = config.backoff(); - - assertEquals( - "BackoffImpl{backoffConfig=" + config.toString() + "," - + " currentRetry=0, currentCumulativeBackoff=PT0S}", - backOff.toString()); - - // backoff once, ignoring result - backOff.nextBackOffMillis(); - - // currentRetry is exact, we can test it. - assertThat(backOff.toString(), containsString("currentRetry=1")); - // currentCumulativeBackoff is not exact; we cannot even check that it's non-zero (randomness). - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java deleted file mode 100644 index 37bf04d469..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GatherAllPanesTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.io.CountingInput; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.WithTimestamps; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.Iterables; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Tests for {@link GatherAllPanes}. - */ -@RunWith(JUnit4.class) -public class GatherAllPanesTest implements Serializable { - @Test - public void singlePaneSingleReifiedPane() { - TestPipeline p = TestPipeline.create(); - PCollection>>> accumulatedPanes = - p.apply(CountingInput.upTo(20000)) - .apply( - WithTimestamps.of( - new SerializableFunction() { - @Override - public Instant apply(Long input) { - return new Instant(input * 10); - } - })) - .apply( - Window.into(FixedWindows.of(Duration.standardMinutes(1))) - .triggering(AfterWatermark.pastEndOfWindow()) - .withAllowedLateness(Duration.ZERO) - .discardingFiredPanes()) - .apply(WithKeys.of((Void) null).withKeyType(new TypeDescriptor() {})) - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(GatherAllPanes.>globally()); - - DataflowAssert.that(accumulatedPanes) - .satisfies( - new SerializableFunction>>>, Void>() { - @Override - public Void apply(Iterable>>> input) { - for (Iterable>> windowedInput : input) { - if (Iterables.size(windowedInput) > 1) { - fail("Expected all windows to have exactly one pane, got " + windowedInput); - return null; - } - } - return null; - } - }); - } - - @Test - public void multiplePanesMultipleReifiedPane() { - TestPipeline p = TestPipeline.create(); - - PCollection>>> accumulatedPanes = - p.apply(CountingInput.upTo(20000)) - .apply( - WithTimestamps.of( - new SerializableFunction() { - @Override - public Instant apply(Long input) { - return new Instant(input * 10); - } - })) - .apply( - Window.into(FixedWindows.of(Duration.standardMinutes(1))) - .triggering( - AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterPane.elementCountAtLeast(1))) - .withAllowedLateness(Duration.ZERO) - .discardingFiredPanes()) - .apply(WithKeys.of((Void) null).withKeyType(new TypeDescriptor() {})) - .apply(GroupByKey.create()) - .apply(Values.>create()) - .apply(GatherAllPanes.>globally()); - - DataflowAssert.that(accumulatedPanes) - .satisfies( - new SerializableFunction>>>, Void>() { - @Override - public Void apply(Iterable>>> input) { - for (Iterable>> windowedInput : input) { - if (Iterables.size(windowedInput) > 1) { - return null; - } - } - fail("Expected at least one window to have multiple panes"); - return null; - } - }); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactoryTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactoryTest.java deleted file mode 100644 index 6e4605f7de..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsIOChannelFactoryTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link GcsIOChannelFactoryTest}. */ -@RunWith(JUnit4.class) -public class GcsIOChannelFactoryTest { - private GcsIOChannelFactory factory; - - @Before - public void setUp() { - factory = new GcsIOChannelFactory(PipelineOptionsFactory.as(GcsOptions.class)); - } - - @Test - public void testResolve() throws Exception { - assertEquals("gs://bucket/object", factory.resolve("gs://bucket", "object")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java deleted file mode 100644 index e49c52b9a0..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GcsUtilTest.java +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import com.google.api.client.googleapis.batch.BatchRequest; -import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpStatusCodes; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.http.LowLevelHttpRequest; -import com.google.api.client.json.GenericJson; -import com.google.api.client.json.Json; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.client.testing.http.HttpTesting; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.testing.http.MockLowLevelHttpResponse; -import com.google.api.client.util.BackOff; -import com.google.api.services.storage.Storage; -import com.google.api.services.storage.model.Bucket; -import com.google.api.services.storage.model.Objects; -import com.google.api.services.storage.model.StorageObject; -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.hadoop.gcsio.GoogleCloudStorageReadChannel; -import com.google.cloud.hadoop.util.ClientRequestHelper; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.math.BigInteger; -import java.net.SocketTimeoutException; -import java.nio.channels.SeekableByteChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** Test case for {@link GcsUtil}. */ -@RunWith(JUnit4.class) -public class GcsUtilTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testGlobTranslation() { - assertEquals("foo", GcsUtil.globToRegexp("foo")); - assertEquals("fo[^/]*o", GcsUtil.globToRegexp("fo*o")); - assertEquals("f[^/]*o\\.[^/]", GcsUtil.globToRegexp("f*o.?")); - assertEquals("foo-[0-9][^/]*", GcsUtil.globToRegexp("foo-[0-9]*")); - } - - private static GcsOptions gcsOptionsWithTestCredential() { - GcsOptions pipelineOptions = PipelineOptionsFactory.as(GcsOptions.class); - pipelineOptions.setGcpCredential(new TestCredential()); - return pipelineOptions; - } - - @Test - public void testCreationWithDefaultOptions() { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - assertNotNull(pipelineOptions.getGcpCredential()); - } - - @Test - public void testUploadBufferSizeDefault() { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil util = pipelineOptions.getGcsUtil(); - assertNull(util.getUploadBufferSizeBytes()); - } - - @Test - public void testUploadBufferSizeUserSpecified() { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - pipelineOptions.setGcsUploadBufferSizeBytes(12345); - GcsUtil util = pipelineOptions.getGcsUtil(); - assertEquals((Integer) 12345, util.getUploadBufferSizeBytes()); - } - - @Test - public void testCreationWithExecutorServiceProvided() { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - pipelineOptions.setExecutorService(Executors.newCachedThreadPool()); - assertSame(pipelineOptions.getExecutorService(), pipelineOptions.getGcsUtil().executorService); - } - - @Test - public void testCreationWithGcsUtilProvided() { - GcsOptions pipelineOptions = PipelineOptionsFactory.as(GcsOptions.class); - GcsUtil gcsUtil = Mockito.mock(GcsUtil.class); - pipelineOptions.setGcsUtil(gcsUtil); - assertSame(gcsUtil, pipelineOptions.getGcsUtil()); - } - - @Test - public void testMultipleThreadsCanCompleteOutOfOrderWithDefaultThreadPool() throws Exception { - GcsOptions pipelineOptions = PipelineOptionsFactory.as(GcsOptions.class); - ExecutorService executorService = pipelineOptions.getExecutorService(); - - int numThreads = 100; - final CountDownLatch[] countDownLatches = new CountDownLatch[numThreads]; - for (int i = 0; i < numThreads; i++) { - final int currentLatch = i; - countDownLatches[i] = new CountDownLatch(1); - executorService.execute(new Runnable() { - @Override - public void run() { - // Wait for latch N and then release latch N - 1 - try { - countDownLatches[currentLatch].await(); - if (currentLatch > 0) { - countDownLatches[currentLatch - 1].countDown(); - } - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - }); - } - - // Release the last latch starting the chain reaction. - countDownLatches[countDownLatches.length - 1].countDown(); - executorService.shutdown(); - assertTrue("Expected tasks to complete", - executorService.awaitTermination(10, TimeUnit.SECONDS)); - } - - @Test - public void testGlobExpansion() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); - Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); - Storage.Objects.List mockStorageList = Mockito.mock(Storage.Objects.List.class); - - Objects modelObjects = new Objects(); - List items = new ArrayList<>(); - // A directory - items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/")); - - // Files within the directory - items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/file1name")); - items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/file2name")); - items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/file3name")); - items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/otherfile")); - items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/anotherfile")); - - modelObjects.setItems(items); - - when(mockStorage.objects()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get("testbucket", "testdirectory/otherfile")).thenReturn( - mockStorageGet); - when(mockStorageObjects.list("testbucket")).thenReturn(mockStorageList); - when(mockStorageGet.execute()).thenReturn( - new StorageObject().setBucket("testbucket").setName("testdirectory/otherfile")); - when(mockStorageList.execute()).thenReturn(modelObjects); - - // Test a single file. - { - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/otherfile"); - List expectedFiles = - ImmutableList.of(GcsPath.fromUri("gs://testbucket/testdirectory/otherfile")); - - assertThat(expectedFiles, contains(gcsUtil.expand(pattern).toArray())); - } - - // Test patterns. - { - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/file*"); - List expectedFiles = ImmutableList.of( - GcsPath.fromUri("gs://testbucket/testdirectory/file1name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file2name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file3name")); - - assertThat(expectedFiles, contains(gcsUtil.expand(pattern).toArray())); - } - - { - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/file[1-3]*"); - List expectedFiles = ImmutableList.of( - GcsPath.fromUri("gs://testbucket/testdirectory/file1name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file2name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file3name")); - - assertThat(expectedFiles, contains(gcsUtil.expand(pattern).toArray())); - } - - { - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/file?name"); - List expectedFiles = ImmutableList.of( - GcsPath.fromUri("gs://testbucket/testdirectory/file1name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file2name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file3name")); - - assertThat(expectedFiles, contains(gcsUtil.expand(pattern).toArray())); - } - - { - GcsPath pattern = GcsPath.fromUri("gs://testbucket/test*ectory/fi*name"); - List expectedFiles = ImmutableList.of( - GcsPath.fromUri("gs://testbucket/testdirectory/file1name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file2name"), - GcsPath.fromUri("gs://testbucket/testdirectory/file3name")); - - assertThat(expectedFiles, contains(gcsUtil.expand(pattern).toArray())); - } - } - - // Patterns that contain recursive wildcards ('**') are not supported. - @Test - public void testRecursiveGlobExpansionFails() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - GcsPath pattern = GcsPath.fromUri("gs://testbucket/test**"); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unsupported wildcard usage"); - gcsUtil.expand(pattern); - } - - // GCSUtil.expand() should fail when matching a single object when that object does not exist. - // We should return the empty result since GCS get object is strongly consistent. - @Test - public void testNonExistentObjectReturnsEmptyResult() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); - Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); - - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentfile"); - GoogleJsonResponseException expectedException = - googleJsonResponseException(HttpStatusCodes.STATUS_CODE_NOT_FOUND, - "It don't exist", "Nothing here to see"); - - when(mockStorage.objects()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get(pattern.getBucket(), pattern.getObject())).thenReturn( - mockStorageGet); - when(mockStorageGet.execute()).thenThrow(expectedException); - - assertEquals(Collections.EMPTY_LIST, gcsUtil.expand(pattern)); - } - - // GCSUtil.expand() should fail for other errors such as access denied. - @Test - public void testAccessDeniedObjectThrowsIOException() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); - Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); - - GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/accessdeniedfile"); - GoogleJsonResponseException expectedException = - googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, - "Waves hand mysteriously", "These aren't the buckets your looking for"); - - when(mockStorage.objects()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get(pattern.getBucket(), pattern.getObject())).thenReturn( - mockStorageGet); - when(mockStorageGet.execute()).thenThrow(expectedException); - - thrown.expect(IOException.class); - thrown.expectMessage("Unable to match files for pattern"); - gcsUtil.expand(pattern); - } - - @Test - public void testGetSizeBytes() throws Exception { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); - Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); - - when(mockStorage.objects()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get("testbucket", "testobject")).thenReturn(mockStorageGet); - when(mockStorageGet.execute()).thenReturn( - new StorageObject().setSize(BigInteger.valueOf(1000))); - - assertEquals(1000, gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject"))); - } - - @Test - public void testGetSizeBytesWhenFileNotFound() throws Exception { - MockLowLevelHttpResponse notFoundResponse = new MockLowLevelHttpResponse(); - notFoundResponse.setContent(""); - notFoundResponse.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); - - MockHttpTransport mockTransport = - new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build(); - - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null)); - - thrown.expect(FileNotFoundException.class); - gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject")); - } - - @Test - public void testRetryFileSize() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class); - Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class); - - BackOff mockBackOff = FluentBackoff.DEFAULT.withMaxRetries(2).backoff(); - - when(mockStorage.objects()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get("testbucket", "testobject")).thenReturn(mockStorageGet); - when(mockStorageGet.execute()) - .thenThrow(new SocketTimeoutException("SocketException")) - .thenThrow(new SocketTimeoutException("SocketException")) - .thenReturn(new StorageObject().setSize(BigInteger.valueOf(1000))); - - assertEquals(1000, gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject"), - mockBackOff, new FastNanoClockAndSleeper())); - assertEquals(BackOff.STOP, mockBackOff.nextBackOffMillis()); - } - - @Test - public void testBucketExists() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); - Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); - - BackOff mockBackOff = FluentBackoff.DEFAULT.backoff(); - - when(mockStorage.buckets()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet); - when(mockStorageGet.execute()) - .thenThrow(new SocketTimeoutException("SocketException")) - .thenReturn(new Bucket()); - - assertTrue(gcsUtil.bucketExists(GcsPath.fromComponents("testbucket", "testobject"), - mockBackOff, new FastNanoClockAndSleeper())); - } - - @Test - public void testBucketDoesNotExistBecauseOfAccessError() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); - Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); - - BackOff mockBackOff = FluentBackoff.DEFAULT.backoff(); - GoogleJsonResponseException expectedException = - googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, - "Waves hand mysteriously", "These aren't the buckets your looking for"); - - when(mockStorage.buckets()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet); - when(mockStorageGet.execute()) - .thenThrow(expectedException); - - assertFalse(gcsUtil.bucketExists(GcsPath.fromComponents("testbucket", "testobject"), - mockBackOff, new FastNanoClockAndSleeper())); - } - - @Test - public void testBucketDoesNotExist() throws IOException { - GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); - GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); - - Storage mockStorage = Mockito.mock(Storage.class); - gcsUtil.setStorageClient(mockStorage); - - Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); - Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class); - - BackOff mockBackOff = FluentBackoff.DEFAULT.backoff(); - - when(mockStorage.buckets()).thenReturn(mockStorageObjects); - when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet); - when(mockStorageGet.execute()) - .thenThrow(googleJsonResponseException(HttpStatusCodes.STATUS_CODE_NOT_FOUND, - "It don't exist", "Nothing here to see")); - - assertFalse(gcsUtil.bucketExists(GcsPath.fromComponents("testbucket", "testobject"), - mockBackOff, new FastNanoClockAndSleeper())); - } - - @Test - public void testGCSChannelCloseIdempotent() throws IOException { - SeekableByteChannel channel = - new GoogleCloudStorageReadChannel(null, "dummybucket", "dummyobject", null, - new ClientRequestHelper()); - channel.close(); - channel.close(); - } - - /** - * Builds a fake GoogleJsonResponseException for testing API error handling. - */ - private static GoogleJsonResponseException googleJsonResponseException( - final int status, final String reason, final String message) throws IOException { - final JsonFactory jsonFactory = new JacksonFactory(); - HttpTransport transport = new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - ErrorInfo errorInfo = new ErrorInfo(); - errorInfo.setReason(reason); - errorInfo.setMessage(message); - errorInfo.setFactory(jsonFactory); - GenericJson error = new GenericJson(); - error.set("code", status); - error.set("errors", Arrays.asList(errorInfo)); - error.setFactory(jsonFactory); - GenericJson errorResponse = new GenericJson(); - errorResponse.set("error", error); - errorResponse.setFactory(jsonFactory); - return new MockLowLevelHttpRequest().setResponse( - new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString()) - .setContentType(Json.MEDIA_TYPE).setStatusCode(status)); - } - }; - HttpRequest request = - transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); - request.setThrowExceptionOnExecuteError(false); - HttpResponse response = request.execute(); - return GoogleJsonResponseException.from(jsonFactory, response); - } - - private static List makeStrings(String s, int n) { - ImmutableList.Builder ret = ImmutableList.builder(); - for (int i = 0; i < n; ++i) { - ret.add(String.format("gs://bucket/%s%d", s, i)); - } - return ret.build(); - } - - private static int sumBatchSizes(List batches) { - int ret = 0; - for (BatchRequest b : batches) { - ret += b.size(); - assertThat(b.size(), greaterThan(0)); - } - return ret; - } - - @Test - public void testMakeCopyBatches() throws IOException { - GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil(); - - // Small number of files fits in 1 batch - List batches = gcsUtil.makeCopyBatches(makeStrings("s", 3), makeStrings("d", 3)); - assertThat(batches.size(), equalTo(1)); - assertThat(sumBatchSizes(batches), equalTo(3)); - - // 1 batch of files fits in 1 batch - batches = gcsUtil.makeCopyBatches(makeStrings("s", 100), makeStrings("d", 100)); - assertThat(batches.size(), equalTo(1)); - assertThat(sumBatchSizes(batches), equalTo(100)); - - // A little more than 5 batches of files fits in 6 batches - batches = gcsUtil.makeCopyBatches(makeStrings("s", 501), makeStrings("d", 501)); - assertThat(batches.size(), equalTo(6)); - assertThat(sumBatchSizes(batches), equalTo(501)); - } - - @Test - public void testInvalidCopyBatches() throws IOException { - GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil(); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Number of source files 3"); - - gcsUtil.makeCopyBatches(makeStrings("s", 3), makeStrings("d", 1)); - } - - @Test - public void testMakeRemoveBatches() throws IOException { - GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil(); - - // Small number of files fits in 1 batch - List batches = gcsUtil.makeRemoveBatches(makeStrings("s", 3)); - assertThat(batches.size(), equalTo(1)); - assertThat(sumBatchSizes(batches), equalTo(3)); - - // 1 batch of files fits in 1 batch - batches = gcsUtil.makeRemoveBatches(makeStrings("s", 100)); - assertThat(batches.size(), equalTo(1)); - assertThat(sumBatchSizes(batches), equalTo(100)); - - // A little more than 5 batches of files fits in 6 batches - batches = gcsUtil.makeRemoveBatches(makeStrings("s", 501)); - assertThat(batches.size(), equalTo(6)); - assertThat(sumBatchSizes(batches), equalTo(501)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java deleted file mode 100644 index e2ae389b4b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsProperties.java +++ /dev/null @@ -1,691 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.TestUtils.KvMatcher; -import com.google.cloud.dataflow.sdk.WindowMatchers; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.util.common.CounterSet; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** - * Properties of {@link GroupAlsoByWindowsDoFn}. - * - *

              Some properties may not hold of some implementations, due to restrictions on the context - * in which the implementation is applicable. For example, - * {@link GroupAlsoByWindowsViaIteratorsDoFn} does not support merging window functions. - */ -public class GroupAlsoByWindowsProperties { - - /** - * A factory of {@link GroupAlsoByWindowsDoFn} so that the various properties can provide - * the appropriate windowing strategy under test. - */ - public interface GroupAlsoByWindowsDoFnFactory { - GroupAlsoByWindowsDoFn - forStrategy(WindowingStrategy strategy); - } - - /** - * Tests that for empty input and the given {@link WindowingStrategy}, the provided GABW - * implementation produces no output. - * - *

              The input type is deliberately left as a wildcard, since it is not relevant. - */ - public static void emptyInputEmptyOutput( - GroupAlsoByWindowsDoFnFactory gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))); - - List result = runGABW( - gabwFactory, - windowingStrategy, - (K) null, // key should never be used - Collections.>emptyList()); - - assertThat(result.size(), equalTo(0)); - } - - /** - * Tests that for a simple sequence of elements on the same key, the given GABW implementation - * correctly groups them according to fixed windows. - */ - public static void groupsElementsIntoFixedWindows( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "key", - WindowedValue.of( - "v1", - new Instant(1), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(2), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v3", - new Instant(13), - Arrays.asList(window(10, 20)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, containsInAnyOrder( - gabwResult(window(0, 10), new Instant(1), "v1", "v2"), - gabwResult(window(10, 20), new Instant(13), "v3"))); - } - - /** - * Tests that for a simple sequence of elements on the same key, the given GABW implementation - * correctly groups them into sliding windows. - * - *

              In the input here, each element occurs in multiple windows. - */ - public static void groupsElementsIntoSlidingWindows( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = WindowingStrategy.of( - SlidingWindows.of(Duration.millis(20)).every(Duration.millis(10))); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "key", - WindowedValue.of( - "v1", - new Instant(5), - Arrays.asList(window(-10, 10), window(0, 20)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(15), - Arrays.asList(window(0, 20), window(10, 30)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(3)); - assertThat(result, containsInAnyOrder( - gabwResult(window(-10, 10), new Instant(5), "v1"), - gabwResult(window(0, 20), new Instant(10), "v1", "v2"), - gabwResult(window(10, 30), new Instant(20), "v2"))); - } - - /** - * Tests that for a simple sequence of elements on the same key, the given GABW implementation - * correctly groups and combines them according to sliding windows. - * - *

              In the input here, each element occurs in multiple windows. - */ - public static void combinesElementsInSlidingWindows( - GroupAlsoByWindowsDoFnFactory gabwFactory, - CombineFn combineFn) - throws Exception { - - WindowingStrategy windowingStrategy = WindowingStrategy.of( - SlidingWindows.of(Duration.millis(20)).every(Duration.millis(10))); - - List>> result = - runGABW(gabwFactory, windowingStrategy, "k", - WindowedValue.of( - 1L, - new Instant(5), - Arrays.asList(window(-10, 10), window(0, 20)), - PaneInfo.NO_FIRING), - WindowedValue.of( - 2L, - new Instant(15), - Arrays.asList(window(0, 20), window(10, 30)), - PaneInfo.NO_FIRING), - WindowedValue.of( - 4L, - new Instant(18), - Arrays.asList(window(0, 20), window(10, 30)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(3)); - - assertThat(result, contains( - WindowMatchers.isSingleWindowedValue( - KvMatcher.isKv( - equalTo("k"), - equalTo(combineFn.apply(ImmutableList.of(1L)))), - 5, // aggregate timestamp - -10, // window start - 10), // window end - WindowMatchers.isSingleWindowedValue( - KvMatcher.isKv( - equalTo("k"), - equalTo(combineFn.apply(ImmutableList.of(1L, 2L, 4L)))), - 10, // aggregate timestamp - 0, // window start - 20), // window end - WindowMatchers.isSingleWindowedValue( - KvMatcher.isKv( - equalTo("k"), - equalTo(combineFn.apply(ImmutableList.of(2L, 4L)))), - 20, // aggregate timestamp - 10, // window start - 30))); // window end - } - - /** - * Tests that the given GABW implementation correctly groups elements that fall into overlapping - * windows that are not merged. - */ - public static void groupsIntoOverlappingNonmergingWindows( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "key", - WindowedValue.of( - "v1", - new Instant(1), - Arrays.asList(window(0, 5)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(4), - Arrays.asList(window(1, 5)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v3", - new Instant(4), - Arrays.asList(window(0, 5)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, - containsInAnyOrder(gabwResult(window(0, 5), new Instant(1), "v1", "v3"), - gabwResult(window(1, 5), new Instant(4), "v2"))); - } - - /** - * Tests that the given GABW implementation correctly groups elements into merged sessions. - */ - public static void groupsElementsInMergedSessions( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "key", - WindowedValue.of( - "v1", - new Instant(0), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(5), - Arrays.asList(window(5, 15)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v3", - new Instant(15), - Arrays.asList(window(15, 25)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, containsInAnyOrder( - gabwResult(window(0, 15), new Instant(0), "v1", "v2"), - gabwResult(window(15, 25), new Instant(15), "v3"))); - } - - /** - * Tests that the given {@link GroupAlsoByWindowsDoFn} implementation combines elements per - * session window correctly according to the provided {@link CombineFn}. - */ - public static void combinesElementsPerSession( - GroupAlsoByWindowsDoFnFactory gabwFactory, - CombineFn combineFn) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))); - - List>> result = - runGABW(gabwFactory, windowingStrategy, "k", - WindowedValue.of( - 1L, - new Instant(0), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - 2L, - new Instant(5), - Arrays.asList(window(5, 15)), - PaneInfo.NO_FIRING), - WindowedValue.of( - 4L, - new Instant(15), - Arrays.asList(window(15, 25)), - PaneInfo.NO_FIRING)); - - assertThat(result, contains( - WindowMatchers.isSingleWindowedValue( - KvMatcher.isKv( - equalTo("k"), - equalTo(combineFn.apply(ImmutableList.of(1L, 2L)))), - 0, // aggregate timestamp - 0, // window start - 15), // window end - WindowMatchers.isSingleWindowedValue( - KvMatcher.isKv( - equalTo("k"), - equalTo(combineFn.apply(ImmutableList.of(4L)))), - 15, // aggregate timestamp - 15, // window start - 25))); // window end - } - - /** - * Tests that for a simple sequence of elements on the same key, the given GABW implementation - * correctly groups them according to fixed windows and also sets the output timestamp - * according to the policy {@link OutputTimeFns#outputAtEndOfWindow()}. - */ - public static void groupsElementsIntoFixedWindowsWithEndOfWindowTimestamp( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow()); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "key", - WindowedValue.of( - "v1", - new Instant(1), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(2), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v3", - new Instant(13), - Arrays.asList(window(10, 20)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, containsInAnyOrder( - gabwResult(window(0, 10), window(0, 10).maxTimestamp(), "v1", "v2"), - gabwResult(window(10, 20), window(10, 20).maxTimestamp(), "v3"))); - } - - /** - * Tests that for a simple sequence of elements on the same key, the given GABW implementation - * correctly groups them according to fixed windows and also sets the output timestamp - * according to a custom {@link OutputTimeFn}. - */ - public static void groupsElementsIntoFixedWindowsWithCustomTimestamp( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withOutputTimeFn(new OutputTimeFn.Defaults() { - @Override - public Instant assignOutputTime(Instant inputTimestamp, IntervalWindow window) { - return inputTimestamp.isBefore(window.maxTimestamp()) - ? inputTimestamp.plus(1) : window.maxTimestamp(); - } - - @Override - public Instant combine(Instant outputTime, Instant otherOutputTime) { - return outputTime.isBefore(otherOutputTime) ? outputTime : otherOutputTime; - } - - @Override - public boolean dependsOnlyOnEarliestInputTimestamp() { - return true; - } - }); - - List>>> result = runGABW(gabwFactory, - windowingStrategy, "key", - WindowedValue.of("v1", new Instant(1), Arrays.asList(window(0, 10)), PaneInfo.NO_FIRING), - WindowedValue.of("v2", new Instant(2), Arrays.asList(window(0, 10)), PaneInfo.NO_FIRING), - WindowedValue.of("v3", new Instant(13), Arrays.asList(window(10, 20)), PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, containsInAnyOrder( - gabwResult(window(0, 10), new Instant(2), "v1", "v2"), - gabwResult(window(10, 20), new Instant(14), "v3"))); - } - - /** - * Tests that for a simple sequence of elements on the same key, the given GABW implementation - * correctly groups them according to fixed windows and also sets the output timestamp - * according to the policy {@link OutputTimeFns#outputAtLatestInputTimestamp()}. - */ - public static void groupsElementsIntoFixedWindowsWithLatestTimestamp( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withOutputTimeFn(OutputTimeFns.outputAtLatestInputTimestamp()); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "k", - WindowedValue.of( - "v1", - new Instant(1), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(2), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v3", - new Instant(13), - Arrays.asList(window(10, 20)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, containsInAnyOrder( - gabwResult(window(0, 10), new Instant(2), "v1", "v2"), - gabwResult(window(10, 20), new Instant(13), "v3"))); - } - - /** - * Tests that the given GABW implementation correctly groups elements into merged sessions - * with output timestamps at the end of the merged window. - */ - public static void groupsElementsInMergedSessionsWithEndOfWindowTimestamp( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))) - .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow()); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "k", - WindowedValue.of( - "v1", - new Instant(0), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(5), - Arrays.asList(window(5, 15)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v3", - new Instant(15), - Arrays.asList(window(15, 25)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, containsInAnyOrder( - gabwResult(window(0, 15), window(0, 15).maxTimestamp(), "v1", "v2"), - gabwResult(window(15, 25), window(15, 25).maxTimestamp(), "v3"))); - } - - /** - * Tests that the given GABW implementation correctly groups elements into merged sessions - * with output timestamps at the end of the merged window. - */ - public static void groupsElementsInMergedSessionsWithLatestTimestamp( - GroupAlsoByWindowsDoFnFactory> gabwFactory) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))) - .withOutputTimeFn(OutputTimeFns.outputAtLatestInputTimestamp()); - - List>>> result = - runGABW(gabwFactory, windowingStrategy, "k", - WindowedValue.of( - "v1", - new Instant(0), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v2", - new Instant(5), - Arrays.asList(window(5, 15)), - PaneInfo.NO_FIRING), - WindowedValue.of( - "v3", - new Instant(15), - Arrays.asList(window(15, 25)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - assertThat(result, containsInAnyOrder( - gabwResult(window(0, 15), new Instant(5), "v1", "v2"), - gabwResult(window(15, 25), new Instant(15), "v3"))); - } - - /** - * Tests that the given {@link GroupAlsoByWindowsDoFn} implementation combines elements per - * session window correctly according to the provided {@link CombineFn}. - */ - public static void combinesElementsPerSessionWithEndOfWindowTimestamp( - GroupAlsoByWindowsDoFnFactory gabwFactory, - CombineFn combineFn) - throws Exception { - - WindowingStrategy windowingStrategy = - WindowingStrategy.of(Sessions.withGapDuration(Duration.millis(10))) - .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow()); - - - List>> result = - runGABW(gabwFactory, windowingStrategy, "k", - WindowedValue.of( - 1L, - new Instant(0), - Arrays.asList(window(0, 10)), - PaneInfo.NO_FIRING), - WindowedValue.of( - 2L, - new Instant(5), - Arrays.asList(window(5, 15)), - PaneInfo.NO_FIRING), - WindowedValue.of( - 4L, - new Instant(15), - Arrays.asList(window(15, 25)), - PaneInfo.NO_FIRING)); - - assertThat(result.size(), equalTo(2)); - - // TODO: Rewrite to use matchers rather than order-based inspection - WindowedValue> item0; - WindowedValue> item1; - if (result.get(0).getWindows().iterator().next().equals(window(0, 15))) { - item0 = result.get(0); - item1 = result.get(1); - } else { - item0 = result.get(1); - item1 = result.get(0); - } - assertThat(item0.getValue().getValue(), equalTo(combineFn.apply(ImmutableList.of(1L, 2L)))); - assertThat(item0.getWindows(), contains(window(0, 15))); - assertThat(item0.getTimestamp(), - equalTo(Iterables.getOnlyElement(item0.getWindows()).maxTimestamp())); - - assertThat(item1.getValue().getValue(), equalTo(combineFn.apply(ImmutableList.of(4L)))); - assertThat(item1.getWindows(), contains(window(15, 25))); - assertThat(item1.getTimestamp(), - equalTo(Iterables.getOnlyElement(item1.getWindows()).maxTimestamp())); - } - - @SafeVarargs - private static - List>> runGABW( - GroupAlsoByWindowsDoFnFactory gabwFactory, - WindowingStrategy windowingStrategy, - K key, - WindowedValue... values) { - return runGABW(gabwFactory, windowingStrategy, key, Arrays.asList(values)); - } - - private static - List>> runGABW( - GroupAlsoByWindowsDoFnFactory gabwFactory, - WindowingStrategy windowingStrategy, - K key, - Collection> values) { - - TupleTag> outputTag = new TupleTag<>(); - DoFnRunnerBase.ListOutputManager outputManager = new DoFnRunnerBase.ListOutputManager(); - - DoFnRunner>>, KV> runner = - makeRunner( - gabwFactory.forStrategy(windowingStrategy), - windowingStrategy, - outputTag, - outputManager); - - runner.startBundle(); - - if (values.size() > 0) { - runner.processElement(WindowedValue.valueInEmptyWindows( - KV.of(key, (Iterable>) values))); - } - - runner.finishBundle(); - - List>> result = outputManager.getOutput(outputTag); - - // Sanity check for corruption - for (WindowedValue> elem : result) { - assertThat(elem.getValue().getKey(), equalTo(key)); - } - - return result; - } - - private static - DoFnRunner>>, KV> - makeRunner( - GroupAlsoByWindowsDoFn fn, - WindowingStrategy windowingStrategy, - TupleTag> outputTag, - DoFnRunners.OutputManager outputManager) { - - ExecutionContext executionContext = DirectModeExecutionContext.create(); - CounterSet counters = new CounterSet(); - - return DoFnRunners.simpleRunner( - PipelineOptionsFactory.create(), - fn, - NullSideInputReader.empty(), - outputManager, - outputTag, - new ArrayList>(), - executionContext.getOrCreateStepContext("GABWStep", "GABWTransform", null), - counters.getAddCounterMutator(), - windowingStrategy); - } - - private static BoundedWindow window(long start, long end) { - return new IntervalWindow(new Instant(start), new Instant(end)); - } - - private static Matcher>>> gabwResult( - BoundedWindow window, - Instant timestamp, - T... values) { - return new GroupAlsoByWindowResultMatcher<>(values, new BoundedWindow[] {window}, timestamp); - } - - private static class GroupAlsoByWindowResultMatcher - extends BaseMatcher>>> { - - private final T[] values; - private final BoundedWindow[] windows; - private final Instant timestamp; - - private GroupAlsoByWindowResultMatcher(T[] values, BoundedWindow[] windows, Instant timestamp) { - this.values = values; - this.windows = windows; - this.timestamp = timestamp; - } - - @Override - public boolean matches(Object item) { - if (item instanceof WindowedValue && ((WindowedValue) item).getValue() instanceof KV) { - WindowedValue>> that = (WindowedValue>>) item; - return containsInAnyOrder(values).matches(that.getValue().getValue()) - && timestamp.equals(that.getTimestamp()) - && containsInAnyOrder(windows).matches(that.getWindows()); - } - return false; - } - - @Override - public void describeTo(Description description) { - description.appendText("A Windowed Value containing values ") - .appendValueList("[", ", ", "]", values) - .appendText(" in windows ") - .appendValueList("[", ", ", "]", windows) - .appendText(" with timestamp ") - .appendValue(timestamp); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java deleted file mode 100644 index 1e8458de76..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsViaOutputBufferDoFnTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsProperties.GroupAlsoByWindowsDoFnFactory; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Unit tests for {@link GroupAlsoByWindowsViaOutputBufferDoFn}. - */ -@RunWith(JUnit4.class) -public class GroupAlsoByWindowsViaOutputBufferDoFnTest { - - private class BufferingGABWViaOutputBufferDoFnFactory - implements GroupAlsoByWindowsDoFnFactory> { - - private final Coder inputCoder; - - public BufferingGABWViaOutputBufferDoFnFactory(Coder inputCoder) { - this.inputCoder = inputCoder; - } - - @Override - public GroupAlsoByWindowsDoFn, W> - forStrategy(WindowingStrategy windowingStrategy) { - return new GroupAlsoByWindowsViaOutputBufferDoFn, W>( - windowingStrategy, - SystemReduceFn.buffering(inputCoder)); - } - } - - @Test - public void testEmptyInputEmptyOutput() throws Exception { - GroupAlsoByWindowsProperties.emptyInputEmptyOutput( - new BufferingGABWViaOutputBufferDoFnFactory<>(StringUtf8Coder.of())); - } - - @Test - public void testGroupsElementsIntoFixedWindows() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindows( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsElementsIntoSlidingWindows() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoSlidingWindows( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsIntoOverlappingNonmergingWindows() throws Exception { - GroupAlsoByWindowsProperties.groupsIntoOverlappingNonmergingWindows( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsIntoSessions() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsInMergedSessions( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsElementsIntoFixedWindowsWithEndOfWindowTimestamp() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindowsWithEndOfWindowTimestamp( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsElementsIntoFixedWindowsWithLatestTimestamp() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindowsWithLatestTimestamp( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsElementsIntoFixedWindowsWithCustomTimestamp() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsIntoFixedWindowsWithCustomTimestamp( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsElementsIntoSessionsWithEndOfWindowTimestamp() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsInMergedSessionsWithEndOfWindowTimestamp( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } - - @Test - public void testGroupsElementsIntoSessionsWithLatestTimestamp() throws Exception { - GroupAlsoByWindowsProperties.groupsElementsInMergedSessionsWithLatestTimestamp( - new BufferingGABWViaOutputBufferDoFnFactory(StringUtf8Coder.of())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOChannelUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOChannelUtilsTest.java deleted file mode 100644 index cb9e9785e7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IOChannelUtilsTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.common.io.Files; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.nio.charset.StandardCharsets; - -/** - * Tests for IOChannelUtils. - */ -@RunWith(JUnit4.class) -public class IOChannelUtilsTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Test - public void testShardFormatExpansion() { - assertEquals("output-001-of-123.txt", - IOChannelUtils.constructName("output", "-SSS-of-NNN", - ".txt", - 1, 123)); - - assertEquals("out.txt/part-00042", - IOChannelUtils.constructName("out.txt", "/part-SSSSS", "", - 42, 100)); - - assertEquals("out.txt", - IOChannelUtils.constructName("ou", "t.t", "xt", 1, 1)); - - assertEquals("out0102shard.txt", - IOChannelUtils.constructName("out", "SSNNshard", ".txt", 1, 2)); - - assertEquals("out-2/1.part-1-of-2.txt", - IOChannelUtils.constructName("out", "-N/S.part-S-of-N", - ".txt", 1, 2)); - } - - @Test(expected = IllegalArgumentException.class) - public void testShardNameCollision() throws Exception { - File outFolder = tmpFolder.newFolder(); - String filename = outFolder.toPath().resolve("output").toString(); - - IOChannelUtils.create(filename, "", "", 2, "text").close(); - fail("IOChannelUtils.create expected to fail due " - + "to filename collision"); - } - - @Test - public void testLargeShardCount() { - Assert.assertEquals("out-100-of-5000.txt", - IOChannelUtils.constructName("out", "-SS-of-NN", ".txt", - 100, 5000)); - } - - @Test - public void testGetSizeBytes() throws Exception { - String data = "TestData"; - File file = tmpFolder.newFile(); - Files.write(data, file, StandardCharsets.UTF_8); - assertEquals(data.length(), IOChannelUtils.getSizeBytes(file.getPath())); - } - - @Test - public void testResolve() throws Exception { - String expected = tmpFolder.getRoot().toPath().resolve("aa").toString(); - assertEquals(expected, IOChannelUtils.resolve(tmpFolder.getRoot().toString(), "aa")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java deleted file mode 100644 index 0e858127ff..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IdentitySideInputWindowFn.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.NonMergingWindowFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; - -import java.util.Collection; - -/** - * A {@link WindowFn} for use during tests that returns the input window for calls to - * {@link #getSideInputWindow(BoundedWindow)}. - */ -public class IdentitySideInputWindowFn extends NonMergingWindowFn { - @Override - public Collection assignWindows(WindowFn.AssignContext c) - throws Exception { - return (Collection) c.windows(); - } - - @Override - public boolean isCompatible(WindowFn other) { - return true; - } - - @Override - public Coder windowCoder() { - // not used - return (Coder) GlobalWindow.Coder.INSTANCE; - } - - @Override - public BoundedWindow getSideInputWindow(BoundedWindow window) { - return window; - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/InstanceBuilderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/InstanceBuilderTest.java deleted file mode 100644 index 21245ed74b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/InstanceBuilderTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests of InstanceBuilder. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("rawtypes") -public class InstanceBuilderTest { - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @SuppressWarnings("unused") - private static TupleTag createTag(String id) { - return new TupleTag(id); - } - - @Test - public void testFullNameLookup() throws Exception { - TupleTag tag = InstanceBuilder.ofType(TupleTag.class) - .fromClassName(InstanceBuilderTest.class.getName()) - .fromFactoryMethod("createTag") - .withArg(String.class, "hello world!") - .build(); - - Assert.assertEquals("hello world!", tag.getId()); - } - - @Test - public void testConstructor() throws Exception { - TupleTag tag = InstanceBuilder.ofType(TupleTag.class) - .withArg(String.class, "hello world!") - .build(); - - Assert.assertEquals("hello world!", tag.getId()); - } - - @Test - public void testBadMethod() throws Exception { - expectedEx.expect(RuntimeException.class); - expectedEx.expectMessage( - Matchers.containsString("Unable to find factory method")); - - InstanceBuilder.ofType(String.class) - .fromClassName(InstanceBuilderTest.class.getName()) - .fromFactoryMethod("nonexistantFactoryMethod") - .withArg(String.class, "hello") - .withArg(String.class, " world!") - .build(); - } - - @Test - public void testBadArgs() throws Exception { - expectedEx.expect(RuntimeException.class); - expectedEx.expectMessage( - Matchers.containsString("Unable to find factory method")); - - InstanceBuilder.ofType(TupleTag.class) - .fromClassName(InstanceBuilderTest.class.getName()) - .fromFactoryMethod("createTag") - .withArg(String.class, "hello") - .withArg(Integer.class, 42) - .build(); - } - - @Test - public void testBadReturnType() throws Exception { - expectedEx.expect(RuntimeException.class); - expectedEx.expectMessage( - Matchers.containsString("must be assignable to String")); - - InstanceBuilder.ofType(String.class) - .fromClassName(InstanceBuilderTest.class.getName()) - .fromFactoryMethod("createTag") - .withArg(String.class, "hello") - .build(); - } - - @Test - public void testWrongType() throws Exception { - expectedEx.expect(RuntimeException.class); - expectedEx.expectMessage( - Matchers.containsString("must be assignable to TupleTag")); - - InstanceBuilder.ofType(TupleTag.class) - .fromClassName(InstanceBuilderTest.class.getName()) - .build(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java deleted file mode 100644 index 3853705b7c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/IntervalBoundedExponentialBackOffTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link IntervalBoundedExponentialBackOff}. */ -@RunWith(JUnit4.class) -@SuppressWarnings("deprecation") // test of deprecated code. -public class IntervalBoundedExponentialBackOffTest { - @Rule public ExpectedException exception = ExpectedException.none(); - - - @Test - public void testUsingInvalidInitialInterval() throws Exception { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Initial interval must be greater than zero."); - new IntervalBoundedExponentialBackOff(1000, 0L); - } - - @Test - public void testUsingInvalidMaximumInterval() throws Exception { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Maximum interval must be greater than zero."); - new IntervalBoundedExponentialBackOff(-1, 10L); - } - - @Test - public void testThatcertainNumberOfAttemptsReachesMaxInterval() throws Exception { - IntervalBoundedExponentialBackOff backOff = new IntervalBoundedExponentialBackOff(1000, 500); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(374L), lessThan(1126L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - } - - @Test - public void testThatResettingAllowsReuse() throws Exception { - IntervalBoundedExponentialBackOff backOff = new IntervalBoundedExponentialBackOff(1000, 500); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(374L), lessThan(1126L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - backOff.reset(); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(249L), lessThan(751L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(374L), lessThan(1126L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - } - - @Test - public void testAtMaxInterval() throws Exception { - IntervalBoundedExponentialBackOff backOff = new IntervalBoundedExponentialBackOff(1000, 500); - assertFalse(backOff.atMaxInterval()); - backOff.nextBackOffMillis(); - assertFalse(backOff.atMaxInterval()); - backOff.nextBackOffMillis(); - assertTrue(backOff.atMaxInterval()); - assertThat(backOff.nextBackOffMillis(), allOf(greaterThanOrEqualTo(500L), - lessThanOrEqualTo(1500L))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java deleted file mode 100644 index e6cd454fbe..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/KeyedWorkItemCoderTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link KeyedWorkItems}. - */ -@RunWith(JUnit4.class) -public class KeyedWorkItemCoderTest { - @Test - public void testCoderProperties() throws Exception { - CoderProperties.coderSerializable( - KeyedWorkItemCoder.of(StringUtf8Coder.of(), VarIntCoder.of(), GlobalWindow.Coder.INSTANCE)); - } - - @Test - public void testEncodeDecodeEqual() throws Exception { - Iterable timers = - ImmutableList.of( - TimerData.of(StateNamespaces.global(), new Instant(500L), TimeDomain.EVENT_TIME)); - Iterable> elements = - ImmutableList.of( - WindowedValue.valueInGlobalWindow(1), - WindowedValue.valueInGlobalWindow(4), - WindowedValue.valueInGlobalWindow(8)); - - KeyedWorkItemCoder coder = - KeyedWorkItemCoder.of(StringUtf8Coder.of(), VarIntCoder.of(), GlobalWindow.Coder.INSTANCE); - - CoderProperties.coderDecodeEncodeEqual(coder, KeyedWorkItems.workItem("foo", timers, elements)); - CoderProperties.coderDecodeEncodeEqual(coder, KeyedWorkItems.elementsWorkItem("foo", elements)); - CoderProperties.coderDecodeEncodeEqual( - coder, KeyedWorkItems.timersWorkItem("foo", timers)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java deleted file mode 100644 index b654b31b1c..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/LateDataDroppingDoFnRunnerTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.util.LateDataDroppingDoFnRunner.LateDataFilter; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.Arrays; - -/** - * Unit tests for {@link LateDataDroppingDoFnRunner}. - */ -@RunWith(JUnit4.class) -public class LateDataDroppingDoFnRunnerTest { - private static final FixedWindows WINDOW_FN = FixedWindows.of(Duration.millis(10)); - - @Mock private TimerInternals mockTimerInternals; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testLateDataFilter() throws Exception { - when(mockTimerInternals.currentInputWatermarkTime()).thenReturn(new Instant(15L)); - - InMemoryLongSumAggregator droppedDueToLateness = - new InMemoryLongSumAggregator("droppedDueToLateness"); - LateDataFilter lateDataFilter = new LateDataFilter( - WindowingStrategy.of(WINDOW_FN), mockTimerInternals, droppedDueToLateness); - - Iterable> actual = lateDataFilter.filter( - "a", - ImmutableList.of( - createDatum(13, 13L), - createDatum(5, 5L), // late element, earlier than 4L. - createDatum(16, 16L), - createDatum(18, 18L))); - - Iterable> expected = ImmutableList.of( - createDatum(13, 13L), - createDatum(16, 16L), - createDatum(18, 18L)); - assertThat(expected, containsInAnyOrder(Iterables.toArray(actual, WindowedValue.class))); - assertEquals(1, droppedDueToLateness.sum); - // Ensure that reiterating returns the same results and doesn't increment the counter again. - assertThat(expected, containsInAnyOrder(Iterables.toArray(actual, WindowedValue.class))); - assertEquals(1, droppedDueToLateness.sum); - } - - private WindowedValue createDatum(T element, long timestampMillis) { - Instant timestamp = new Instant(timestampMillis); - return WindowedValue.of( - element, - timestamp, - Arrays.asList(WINDOW_FN.assignWindow(timestamp)), - PaneInfo.NO_FIRING); - } - - private static class InMemoryLongSumAggregator implements Aggregator { - private final String name; - private long sum = 0; - - public InMemoryLongSumAggregator(String name) { - this.name = name; - } - - @Override - public void addValue(Long value) { - sum += value; - } - - @Override - public String getName() { - return name; - } - - @Override - public CombineFn getCombineFn() { - return new Sum.SumLongFn(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java deleted file mode 100644 index adebf2967b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MergingActiveWindowSetTest.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Test NonMergingActiveWindowSet. - */ -@RunWith(JUnit4.class) -public class MergingActiveWindowSetTest { - private Sessions windowFn; - private StateInternals state; - private MergingActiveWindowSet set; - private ActiveWindowSet.MergeCallback callback; - - @Before - public void setup() { - windowFn = Sessions.withGapDuration(Duration.millis(10)); - state = InMemoryStateInternals.forKey("dummyKey"); - set = new MergingActiveWindowSet<>(windowFn, state); - @SuppressWarnings("unchecked") - ActiveWindowSet.MergeCallback - callback = mock(ActiveWindowSet.MergeCallback.class); - this.callback = callback; - } - - @After - public void after() { - set = null; - state = null; - windowFn = null; - } - - private void add(long... instants) { - for (final long instant : instants) { - System.out.println("ADD " + instant); - Sessions.AssignContext context = windowFn.new AssignContext() { - @Override - public Object element() { - return (Object) instant; - } - - @Override - public Instant timestamp() { - return new Instant(instant); - } - - @Override - public Collection windows() { - return ImmutableList.of(); - } - }; - - for (IntervalWindow window : windowFn.assignWindows(context)) { - set.ensureWindowExists(window); - } - } - } - - private Map merge( - List toBeMerged, - IntervalWindow mergeResult) throws Exception { - IntervalWindow predictedPostMergeWriteStateAddress = - set.mergedWriteStateAddress(toBeMerged, mergeResult); - - System.out.println("BEFORE MERGE"); - System.out.println(set); - Map map = new HashMap<>(); - for (IntervalWindow window : toBeMerged) { - System.out.println("WILL MERGE " + window + " INTO " + mergeResult); - map.put(window, mergeResult); - } - System.out.println("AFTER MERGE"); - set.merge(callback); - verify(callback).onMerge(toBeMerged, mergeResult); - System.out.println(set); - - assertEquals(predictedPostMergeWriteStateAddress, set.writeStateAddress(mergeResult)); - - return map; - } - - private void activate(Map map, long... instants) { - for (long instant : instants) { - IntervalWindow window = window(instant, 10); - IntervalWindow active = map.get(window); - if (active == null) { - active = window; - } - System.out.println("ACTIVATE " + active); - set.ensureWindowIsActive(active); - } - set.checkInvariants(); - } - - private void cleanup() { - System.out.println("CLEANUP"); - set.cleanupTemporaryWindows(); - set.checkInvariants(); - System.out.println(set); - set.persist(); - MergingActiveWindowSet reloaded = - new MergingActiveWindowSet<>(windowFn, state); - reloaded.checkInvariants(); - assertEquals(set, reloaded); - } - - private IntervalWindow window(long start, long size) { - return new IntervalWindow(new Instant(start), new Duration(size)); - } - - @Test - public void testLifecycle() throws Exception { - // Step 1: New elements show up, introducing NEW windows which are partially merged. - // NEW 1+10 - // NEW 2+10 - // NEW 15+10 - // => - // ACTIVE 1+11 (target 1+11) - // ACTIVE 15+10 (target 15+10) - add(1, 2, 15); - assertEquals(ImmutableSet.of(window(1, 10), window(2, 10), window(15, 10)), - set.getActiveAndNewWindows()); - Map map = - merge(ImmutableList.of(window(1, 10), window(2, 10)), - window(1, 11)); - activate(map, 1, 2, 15); - assertEquals(ImmutableSet.of(window(1, 11), window(15, 10)), set.getActiveAndNewWindows()); - assertEquals( - ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 11))); - assertEquals( - ImmutableSet.of(window(15, 10)), set.readStateAddresses(window(15, 10))); - cleanup(); - - // Step 2: Another element, merged into an existing ACTIVE window. - // NEW 3+10 - // => - // ACTIVE 1+12 (target 1+11) - // ACTIVE 15+10 (target 15+10) - add(3); - assertEquals(ImmutableSet.of(window(3, 10), window(1, 11), window(15, 10)), - set.getActiveAndNewWindows()); - map = merge(ImmutableList.of(window(1, 11), window(3, 10)), - window(1, 12)); - activate(map, 3); - assertEquals(ImmutableSet.of(window(1, 12), window(15, 10)), set.getActiveAndNewWindows()); - assertEquals( - ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 12))); - assertEquals( - ImmutableSet.of(window(15, 10)), set.readStateAddresses(window(15, 10))); - cleanup(); - - // Step 3: Another element, causing two ACTIVE windows to be merged. - // NEW 8+10 - // => - // ACTIVE 1+24 (target 1+11) - add(8); - assertEquals(ImmutableSet.of(window(8, 10), window(1, 12), window(15, 10)), - set.getActiveAndNewWindows()); - map = merge(ImmutableList.of(window(1, 12), window(8, 10), window(15, 10)), - window(1, 24)); - activate(map, 8); - assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveAndNewWindows()); - assertEquals( - ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 24))); - cleanup(); - - // Step 4: Another element, merged into an existing ACTIVE window. - // NEW 9+10 - // => - // ACTIVE 1+24 (target 1+11) - add(9); - assertEquals(ImmutableSet.of(window(9, 10), window(1, 24)), set.getActiveAndNewWindows()); - map = merge(ImmutableList.of(window(1, 24), window(9, 10)), - window(1, 24)); - activate(map, 9); - assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveAndNewWindows()); - assertEquals( - ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 24))); - cleanup(); - - // Step 5: Another element reusing earlier window, merged into an existing ACTIVE window. - // NEW 1+10 - // => - // ACTIVE 1+24 (target 1+11) - add(1); - assertEquals(ImmutableSet.of(window(1, 10), window(1, 24)), set.getActiveAndNewWindows()); - map = merge(ImmutableList.of(window(1, 10), window(1, 24)), - window(1, 24)); - activate(map, 1); - assertEquals(ImmutableSet.of(window(1, 24)), set.getActiveAndNewWindows()); - assertEquals( - ImmutableSet.of(window(1, 11)), set.readStateAddresses(window(1, 24))); - cleanup(); - - // Step 6: Window is closed. - set.remove(window(1, 24)); - cleanup(); - assertTrue(set.getActiveAndNewWindows().isEmpty()); - } - - @Test - public void testLegacyState() { - // Pre 1.4 we merged window state lazily. - // Simulate loading an active window set with multiple state address windows. - set.addActiveForTesting(window(1, 12), - ImmutableList.of(window(1, 10), window(2, 10), window(3, 10))); - - - // Make sure we can detect and repair the state. - assertTrue(set.isActive(window(1, 12))); - assertEquals(ImmutableSet.of(window(1, 10), window(2, 10), window(3, 10)), - set.readStateAddresses(window(1, 12))); - assertEquals(window(1, 10), - set.mergedWriteStateAddress( - ImmutableList.of(window(1, 10), window(2, 10), window(3, 10)), - window(1, 12))); - set.merged(window(1, 12)); - cleanup(); - - // For then on we are back to the eager case. - assertEquals(ImmutableSet.of(window(1, 10)), set.readStateAddresses(window(1, 12))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java deleted file mode 100644 index e1458f76b7..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MonitoringUtilTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.dataflow.model.JobMessage; -import com.google.api.services.dataflow.model.ListJobMessagesResponse; -import com.google.cloud.dataflow.sdk.PipelineResult.State; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; - -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for MonitoringUtil. - */ -@RunWith(JUnit4.class) -public class MonitoringUtilTest { - private static final String PROJECT_ID = "someProject"; - private static final String JOB_ID = "1234"; - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testGetJobMessages() throws IOException { - Dataflow.Projects.Jobs.Messages mockMessages = mock(Dataflow.Projects.Jobs.Messages.class); - - // Two requests are needed to get all the messages. - Dataflow.Projects.Jobs.Messages.List firstRequest = - mock(Dataflow.Projects.Jobs.Messages.List.class); - Dataflow.Projects.Jobs.Messages.List secondRequest = - mock(Dataflow.Projects.Jobs.Messages.List.class); - - when(mockMessages.list(PROJECT_ID, JOB_ID)).thenReturn(firstRequest).thenReturn(secondRequest); - - ListJobMessagesResponse firstResponse = new ListJobMessagesResponse(); - firstResponse.setJobMessages(new ArrayList()); - for (int i = 0; i < 100; ++i) { - JobMessage message = new JobMessage(); - message.setId("message_" + i); - message.setTime(TimeUtil.toCloudTime(new Instant(i))); - firstResponse.getJobMessages().add(message); - } - String pageToken = "page_token"; - firstResponse.setNextPageToken(pageToken); - - ListJobMessagesResponse secondResponse = new ListJobMessagesResponse(); - secondResponse.setJobMessages(new ArrayList()); - for (int i = 100; i < 150; ++i) { - JobMessage message = new JobMessage(); - message.setId("message_" + i); - message.setTime(TimeUtil.toCloudTime(new Instant(i))); - secondResponse.getJobMessages().add(message); - } - - when(firstRequest.execute()).thenReturn(firstResponse); - when(secondRequest.execute()).thenReturn(secondResponse); - - MonitoringUtil util = new MonitoringUtil(PROJECT_ID, mockMessages); - - List messages = util.getJobMessages(JOB_ID, -1); - - verify(secondRequest).setPageToken(pageToken); - - assertEquals(150, messages.size()); - } - - @Test - public void testToStateCreatesState() { - String stateName = "JOB_STATE_DONE"; - - State result = MonitoringUtil.toState(stateName); - - assertEquals(State.DONE, result); - } - - @Test - public void testToStateWithNullReturnsUnknown() { - String stateName = null; - - State result = MonitoringUtil.toState(stateName); - - assertEquals(State.UNKNOWN, result); - } - - @Test - public void testToStateWithOtherValueReturnsUnknown() { - String stateName = "FOO_BAR_BAZ"; - - State result = MonitoringUtil.toState(stateName); - - assertEquals(State.UNKNOWN, result); - } - - @Test - public void testDontOverrideEndpointWithDefaultApi() { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setProject(PROJECT_ID); - options.setGcpCredential(new TestCredential()); - String cancelCommand = MonitoringUtil.getGcloudCancelCommand(options, JOB_ID); - assertEquals("gcloud beta dataflow jobs --project=someProject cancel 1234", cancelCommand); - } - - @Test - public void testOverridesEndpointWithStagedDataflowEndpoint() { - DataflowPipelineOptions options = - PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); - options.setProject(PROJECT_ID); - options.setGcpCredential(new TestCredential()); - String stagingDataflowEndpoint = "v0neverExisted"; - options.setDataflowEndpoint(stagingDataflowEndpoint); - String cancelCommand = MonitoringUtil.getGcloudCancelCommand(options, JOB_ID); - assertEquals( - "CLOUDSDK_API_ENDPOINT_OVERRIDES_DATAFLOW=https://dataflow.googleapis.com/v0neverExisted/ " - + "gcloud beta dataflow jobs --project=someProject cancel 1234", - cancelCommand); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java deleted file mode 100644 index 9303d66d03..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MovingFunctionTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.Combine; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests {@link MovingFunction}. - */ -@RunWith(JUnit4.class) -public class MovingFunctionTest { - - private static final long SAMPLE_PERIOD = 100; - private static final long SAMPLE_UPDATE = 10; - private static final int SIGNIFICANT_BUCKETS = 2; - private static final int SIGNIFICANT_SAMPLES = 10; - - private static final Combine.BinaryCombineLongFn SUM = - new Combine.BinaryCombineLongFn() { - @Override - public long apply(long left, long right) { - return left + right; - } - - @Override - public long identity() { - return 0; - } - }; - - private MovingFunction newFunc() { - return new - MovingFunction(SAMPLE_PERIOD, SAMPLE_UPDATE, SIGNIFICANT_BUCKETS, - SIGNIFICANT_SAMPLES, SUM); - - } - - @Test - public void significantSamples() { - MovingFunction f = newFunc(); - assertFalse(f.isSignificant()); - for (int i = 0; i < SIGNIFICANT_SAMPLES - 1; i++) { - f.add(0, 0); - assertFalse(f.isSignificant()); - } - f.add(0, 0); - assertTrue(f.isSignificant()); - } - - @Test - public void significantBuckets() { - MovingFunction f = newFunc(); - assertFalse(f.isSignificant()); - f.add(0, 0); - assertFalse(f.isSignificant()); - f.add(SAMPLE_UPDATE, 0); - assertTrue(f.isSignificant()); - } - - @Test - public void sum() { - MovingFunction f = newFunc(); - for (int i = 0; i < SAMPLE_PERIOD; i++) { - f.add(i, i); - assertEquals(((i + 1) * i) / 2, f.get(i)); - } - } - - @Test - public void movingSum() { - MovingFunction f = newFunc(); - int lost = 0; - for (int i = 0; i < SAMPLE_PERIOD * 2; i++) { - f.add(i , 1); - if (i >= SAMPLE_PERIOD) { - if (i % SAMPLE_UPDATE == 0) { - lost += SAMPLE_UPDATE; - } - } - assertEquals(i + 1 - lost, f.get(i)); - } - } - - @Test - public void jumpingSum() { - MovingFunction f = newFunc(); - f.add(0, 1); - f.add(SAMPLE_PERIOD - 1, 1); - assertEquals(2, f.get(SAMPLE_PERIOD - 1)); - assertEquals(1, f.get(SAMPLE_PERIOD + 3 * SAMPLE_UPDATE)); - assertEquals(0, f.get(SAMPLE_PERIOD * 2)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MutationDetectorsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MutationDetectorsTest.java deleted file mode 100644 index 0f77679158..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/MutationDetectorsTest.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * Tests for {@link MutationDetectors}. - */ -@RunWith(JUnit4.class) -public class MutationDetectorsTest { - - @Rule public ExpectedException thrown = ExpectedException.none(); - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} detects a mutation to a list. - */ - @Test - public void testMutatingList() throws Exception { - List value = Arrays.asList(1, 2, 3, 4); - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, ListCoder.of(VarIntCoder.of())); - value.set(0, 37); - - thrown.expect(IllegalMutationException.class); - detector.verifyUnmodified(); - } - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} does not false positive on a - * {@link LinkedList} that will clone as an {@code ArrayList}. - */ - @Test - public void testUnmodifiedLinkedList() throws Exception { - List value = Lists.newLinkedList(Arrays.asList(1, 2, 3, 4)); - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, ListCoder.of(VarIntCoder.of())); - detector.verifyUnmodified(); - } - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} does not false positive on a - * {@link LinkedList} coded as an {@link Iterable}. - */ - @Test - public void testImmutableList() throws Exception { - List value = Lists.newLinkedList(Arrays.asList(1, 2, 3, 4)); - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, IterableCoder.of(VarIntCoder.of())); - detector.verifyUnmodified(); - } - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} does not false positive on a - * {@link Set} coded as an {@link Iterable}. - */ - @Test - public void testImmutableSet() throws Exception { - Set value = Sets.newHashSet(Arrays.asList(1, 2, 3, 4)); - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, IterableCoder.of(VarIntCoder.of())); - detector.verifyUnmodified(); - } - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} does not false positive on an - * {@link Iterable} that is not known to be bounded; after coder-based cloning the bound - * will be known and it will be a {@link List} so it will encode more compactly the second - * time around. - */ - @Test - public void testImmutableIterable() throws Exception { - Iterable value = FluentIterable.from(Arrays.asList(1, 2, 3, 4)).cycle().limit(50); - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, IterableCoder.of(VarIntCoder.of())); - detector.verifyUnmodified(); - } - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} detects a mutation to a byte array. - */ - @Test - public void testMutatingArray() throws Exception { - byte[] value = new byte[]{0x1, 0x2, 0x3, 0x4}; - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, ByteArrayCoder.of()); - value[0] = 0xa; - thrown.expect(IllegalMutationException.class); - detector.verifyUnmodified(); - } - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} does not false positive on an - * array, even though it will decode is another array which Java will not say is {@code equals}. - */ - @Test - public void testUnmodifiedArray() throws Exception { - byte[] value = new byte[]{0x1, 0x2, 0x3, 0x4}; - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, ByteArrayCoder.of()); - detector.verifyUnmodified(); - } - - /** - * Tests that {@link MutationDetectors#forValueWithCoder} does not false positive on an - * list of arrays, even when some array is set to a deeply equal array that is not {@code equals}. - */ - @Test - public void testEquivalentListOfArrays() throws Exception { - List value = Arrays.asList(new byte[]{0x1}, new byte[]{0x2, 0x3}, new byte[]{0x4}); - MutationDetector detector = - MutationDetectors.forValueWithCoder(value, ListCoder.of(ByteArrayCoder.of())); - value.set(0, new byte[]{0x1}); - detector.verifyUnmodified(); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PTupleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PTupleTest.java deleted file mode 100644 index 51b9938e1e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PTupleTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link PTuple}. */ -@RunWith(JUnit4.class) -public final class PTupleTest { - @Test - public void accessingNullVoidValuesShouldNotCauseExceptions() { - TupleTag tag = new TupleTag() {}; - PTuple tuple = PTuple.of(tag, null); - assertTrue(tuple.has(tag)); - assertThat(tuple.get(tag), is(nullValue())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PackageUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PackageUtilTest.java deleted file mode 100644 index e051219b78..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PackageUtilTest.java +++ /dev/null @@ -1,482 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpStatusCodes; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.http.LowLevelHttpRequest; -import com.google.api.client.json.GenericJson; -import com.google.api.client.json.Json; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.client.testing.http.HttpTesting; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.testing.http.MockLowLevelHttpResponse; -import com.google.api.services.dataflow.model.DataflowPackage; -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; -import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; -import com.google.cloud.dataflow.sdk.util.PackageUtil.PackageAttributes; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.io.Files; -import com.google.common.io.LineReader; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.channels.Channels; -import java.nio.channels.Pipe; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -/** Tests for PackageUtil. */ -@RunWith(JUnit4.class) -public class PackageUtilTest { - @Rule public ExpectedLogs logged = ExpectedLogs.none(PackageUtil.class); - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Rule - public FastNanoClockAndSleeper fastNanoClockAndSleeper = new FastNanoClockAndSleeper(); - - @Mock - GcsUtil mockGcsUtil; - - // 128 bits, base64 encoded is 171 bits, rounds to 22 bytes - private static final String HASH_PATTERN = "[a-zA-Z0-9+-]{22}"; - - // Hamcrest matcher to assert a string matches a pattern - private static class RegexMatcher extends BaseMatcher { - private final Pattern pattern; - - public RegexMatcher(String regex) { - this.pattern = Pattern.compile(regex); - } - - @Override - public boolean matches(Object o) { - if (!(o instanceof String)) { - return false; - } - return pattern.matcher((String) o).matches(); - } - - @Override - public void describeTo(Description description) { - description.appendText(String.format("matches regular expression %s", pattern)); - } - - public static RegexMatcher matches(String regex) { - return new RegexMatcher(regex); - } - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - GcsOptions pipelineOptions = PipelineOptionsFactory.as(GcsOptions.class); - pipelineOptions.setGcsUtil(mockGcsUtil); - - IOChannelUtils.registerStandardIOFactories(pipelineOptions); - } - - private File makeFileWithContents(String name, String contents) throws Exception { - File tmpFile = tmpFolder.newFile(name); - Files.write(contents, tmpFile, StandardCharsets.UTF_8); - tmpFile.setLastModified(0); // required for determinism with directories - return tmpFile; - } - - static final String STAGING_PATH = GcsPath.fromComponents("somebucket", "base/path").toString(); - private static PackageAttributes makePackageAttributes(File file, String overridePackageName) { - return PackageUtil.createPackageAttributes(file, STAGING_PATH, overridePackageName); - } - - @Test - public void testFileWithExtensionPackageNamingAndSize() throws Exception { - String contents = "This is a test!"; - File tmpFile = makeFileWithContents("file.txt", contents); - PackageAttributes attr = makePackageAttributes(tmpFile, null); - DataflowPackage target = attr.getDataflowPackage(); - - assertThat(target.getName(), RegexMatcher.matches("file-" + HASH_PATTERN + ".txt")); - assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName())); - assertThat(attr.getSize(), equalTo((long) contents.length())); - } - - @Test - public void testPackageNamingWithFileNoExtension() throws Exception { - File tmpFile = makeFileWithContents("file", "This is a test!"); - DataflowPackage target = makePackageAttributes(tmpFile, null).getDataflowPackage(); - - assertThat(target.getName(), RegexMatcher.matches("file-" + HASH_PATTERN)); - assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName())); - } - - @Test - public void testPackageNamingWithDirectory() throws Exception { - File tmpDirectory = tmpFolder.newFolder("folder"); - DataflowPackage target = makePackageAttributes(tmpDirectory, null).getDataflowPackage(); - - assertThat(target.getName(), RegexMatcher.matches("folder-" + HASH_PATTERN + ".jar")); - assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName())); - } - - @Test - public void testPackageNamingWithFilesHavingSameContentsAndSameNames() throws Exception { - File tmpDirectory1 = tmpFolder.newFolder("folder1", "folderA"); - makeFileWithContents("folder1/folderA/sameName", "This is a test!"); - DataflowPackage target1 = makePackageAttributes(tmpDirectory1, null).getDataflowPackage(); - - File tmpDirectory2 = tmpFolder.newFolder("folder2", "folderA"); - makeFileWithContents("folder2/folderA/sameName", "This is a test!"); - DataflowPackage target2 = makePackageAttributes(tmpDirectory2, null).getDataflowPackage(); - - assertEquals(target1.getName(), target2.getName()); - assertEquals(target1.getLocation(), target2.getLocation()); - } - - @Test - public void testPackageNamingWithFilesHavingSameContentsButDifferentNames() throws Exception { - File tmpDirectory1 = tmpFolder.newFolder("folder1", "folderA"); - makeFileWithContents("folder1/folderA/uniqueName1", "This is a test!"); - DataflowPackage target1 = makePackageAttributes(tmpDirectory1, null).getDataflowPackage(); - - File tmpDirectory2 = tmpFolder.newFolder("folder2", "folderA"); - makeFileWithContents("folder2/folderA/uniqueName2", "This is a test!"); - DataflowPackage target2 = makePackageAttributes(tmpDirectory2, null).getDataflowPackage(); - - assertNotEquals(target1.getName(), target2.getName()); - assertNotEquals(target1.getLocation(), target2.getLocation()); - } - - @Test - public void testPackageNamingWithDirectoriesHavingSameContentsButDifferentNames() - throws Exception { - File tmpDirectory1 = tmpFolder.newFolder("folder1", "folderA"); - tmpFolder.newFolder("folder1", "folderA", "uniqueName1"); - DataflowPackage target1 = makePackageAttributes(tmpDirectory1, null).getDataflowPackage(); - - File tmpDirectory2 = tmpFolder.newFolder("folder2", "folderA"); - tmpFolder.newFolder("folder2", "folderA", "uniqueName2"); - DataflowPackage target2 = makePackageAttributes(tmpDirectory2, null).getDataflowPackage(); - - assertNotEquals(target1.getName(), target2.getName()); - assertNotEquals(target1.getLocation(), target2.getLocation()); - } - - @Test - public void testPackageUploadWithLargeClasspathLogsWarning() throws Exception { - File tmpFile = makeFileWithContents("file.txt", "This is a test!"); - // all files will be present and cached so no upload needed. - when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(tmpFile.length()); - - List classpathElements = Lists.newLinkedList(); - for (int i = 0; i < 1005; ++i) { - String eltName = "element" + i; - classpathElements.add(eltName + '=' + tmpFile.getAbsolutePath()); - } - - PackageUtil.stageClasspathElements(classpathElements, STAGING_PATH); - - logged.verifyWarn("Your classpath contains 1005 elements, which Google Cloud Dataflow"); - } - - @Test - public void testPackageUploadWithFileSucceeds() throws Exception { - Pipe pipe = Pipe.open(); - String contents = "This is a test!"; - File tmpFile = makeFileWithContents("file.txt", contents); - when(mockGcsUtil.fileSize(any(GcsPath.class))) - .thenThrow(new FileNotFoundException("some/path")); - when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink()); - - List targets = PackageUtil.stageClasspathElements( - ImmutableList.of(tmpFile.getAbsolutePath()), STAGING_PATH); - DataflowPackage target = Iterables.getOnlyElement(targets); - - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - - assertThat(target.getName(), RegexMatcher.matches("file-" + HASH_PATTERN + ".txt")); - assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName())); - assertThat(new LineReader(Channels.newReader(pipe.source(), "UTF-8")).readLine(), - equalTo(contents)); - } - - @Test - public void testPackageUploadWithDirectorySucceeds() throws Exception { - Pipe pipe = Pipe.open(); - File tmpDirectory = tmpFolder.newFolder("folder"); - tmpFolder.newFolder("folder", "empty_directory"); - tmpFolder.newFolder("folder", "directory"); - makeFileWithContents("folder/file.txt", "This is a test!"); - makeFileWithContents("folder/directory/file.txt", "This is also a test!"); - - when(mockGcsUtil.fileSize(any(GcsPath.class))) - .thenThrow(new FileNotFoundException("some/path")); - when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink()); - - PackageUtil.stageClasspathElements( - ImmutableList.of(tmpDirectory.getAbsolutePath()), STAGING_PATH); - - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - - ZipInputStream inputStream = new ZipInputStream(Channels.newInputStream(pipe.source())); - List zipEntryNames = new ArrayList<>(); - for (ZipEntry entry = inputStream.getNextEntry(); entry != null; - entry = inputStream.getNextEntry()) { - zipEntryNames.add(entry.getName()); - } - - assertThat(zipEntryNames, - containsInAnyOrder("directory/file.txt", "empty_directory/", "file.txt")); - } - - @Test - public void testPackageUploadWithEmptyDirectorySucceeds() throws Exception { - Pipe pipe = Pipe.open(); - File tmpDirectory = tmpFolder.newFolder("folder"); - - when(mockGcsUtil.fileSize(any(GcsPath.class))) - .thenThrow(new FileNotFoundException("some/path")); - when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink()); - - List targets = PackageUtil.stageClasspathElements( - ImmutableList.of(tmpDirectory.getAbsolutePath()), STAGING_PATH); - DataflowPackage target = Iterables.getOnlyElement(targets); - - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - - assertThat(target.getName(), RegexMatcher.matches("folder-" + HASH_PATTERN + ".jar")); - assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName())); - assertNull(new ZipInputStream(Channels.newInputStream(pipe.source())).getNextEntry()); - } - - @Test(expected = RuntimeException.class) - public void testPackageUploadFailsWhenIOExceptionThrown() throws Exception { - File tmpFile = makeFileWithContents("file.txt", "This is a test!"); - when(mockGcsUtil.fileSize(any(GcsPath.class))) - .thenThrow(new FileNotFoundException("some/path")); - when(mockGcsUtil.create(any(GcsPath.class), anyString())) - .thenThrow(new IOException("Fake Exception: Upload error")); - - try { - PackageUtil.stageClasspathElements( - ImmutableList.of(tmpFile.getAbsolutePath()), - STAGING_PATH, fastNanoClockAndSleeper); - } finally { - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil, times(5)).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - } - } - - @Test - public void testPackageUploadFailsWithPermissionsErrorGivesDetailedMessage() throws Exception { - File tmpFile = makeFileWithContents("file.txt", "This is a test!"); - when(mockGcsUtil.fileSize(any(GcsPath.class))) - .thenThrow(new FileNotFoundException("some/path")); - when(mockGcsUtil.create(any(GcsPath.class), anyString())) - .thenThrow(new IOException("Failed to write to GCS path " + STAGING_PATH, - googleJsonResponseException( - HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Permission denied", "Test message"))); - - try { - PackageUtil.stageClasspathElements( - ImmutableList.of(tmpFile.getAbsolutePath()), - STAGING_PATH, fastNanoClockAndSleeper); - fail("Expected RuntimeException"); - } catch (RuntimeException e) { - assertTrue("Expected IOException containing detailed message.", - e.getCause() instanceof IOException); - assertThat(e.getCause().getMessage(), - Matchers.allOf( - Matchers.containsString("Uploaded failed due to permissions error"), - Matchers.containsString( - "Stale credentials can be resolved by executing 'gcloud auth login'"))); - } finally { - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - } - } - - @Test - public void testPackageUploadEventuallySucceeds() throws Exception { - Pipe pipe = Pipe.open(); - File tmpFile = makeFileWithContents("file.txt", "This is a test!"); - when(mockGcsUtil.fileSize(any(GcsPath.class))) - .thenThrow(new FileNotFoundException("some/path")); - when(mockGcsUtil.create(any(GcsPath.class), anyString())) - .thenThrow(new IOException("Fake Exception: 410 Gone")) // First attempt fails - .thenReturn(pipe.sink()); // second attempt succeeds - - try { - PackageUtil.stageClasspathElements( - ImmutableList.of(tmpFile.getAbsolutePath()), - STAGING_PATH, - fastNanoClockAndSleeper); - } finally { - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil, times(2)).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - } - } - - @Test - public void testPackageUploadIsSkippedWhenFileAlreadyExists() throws Exception { - File tmpFile = makeFileWithContents("file.txt", "This is a test!"); - when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(tmpFile.length()); - - PackageUtil.stageClasspathElements( - ImmutableList.of(tmpFile.getAbsolutePath()), STAGING_PATH); - - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verifyNoMoreInteractions(mockGcsUtil); - } - - @Test - public void testPackageUploadIsNotSkippedWhenSizesAreDifferent() throws Exception { - Pipe pipe = Pipe.open(); - File tmpDirectory = tmpFolder.newFolder("folder"); - tmpFolder.newFolder("folder", "empty_directory"); - tmpFolder.newFolder("folder", "directory"); - makeFileWithContents("folder/file.txt", "This is a test!"); - makeFileWithContents("folder/directory/file.txt", "This is also a test!"); - when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(Long.MAX_VALUE); - when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink()); - - PackageUtil.stageClasspathElements( - ImmutableList.of(tmpDirectory.getAbsolutePath()), STAGING_PATH); - - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - } - - @Test - public void testPackageUploadWithExplicitPackageName() throws Exception { - Pipe pipe = Pipe.open(); - File tmpFile = makeFileWithContents("file.txt", "This is a test!"); - final String overriddenName = "alias.txt"; - - when(mockGcsUtil.fileSize(any(GcsPath.class))) - .thenThrow(new FileNotFoundException("some/path")); - when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink()); - - List targets = PackageUtil.stageClasspathElements( - ImmutableList.of(overriddenName + "=" + tmpFile.getAbsolutePath()), STAGING_PATH); - DataflowPackage target = Iterables.getOnlyElement(targets); - - verify(mockGcsUtil).fileSize(any(GcsPath.class)); - verify(mockGcsUtil).create(any(GcsPath.class), anyString()); - verifyNoMoreInteractions(mockGcsUtil); - - assertThat(target.getName(), equalTo(overriddenName)); - assertThat(target.getLocation(), - RegexMatcher.matches(STAGING_PATH + "/file-" + HASH_PATTERN + ".txt")); - } - - @Test - public void testPackageUploadIsSkippedWithNonExistentResource() throws Exception { - String nonExistentFile = - IOChannelUtils.resolve(tmpFolder.getRoot().getPath(), "non-existent-file"); - assertEquals(Collections.EMPTY_LIST, PackageUtil.stageClasspathElements( - ImmutableList.of(nonExistentFile), STAGING_PATH)); - } - - /** - * Builds a fake GoogleJsonResponseException for testing API error handling. - */ - private static GoogleJsonResponseException googleJsonResponseException( - final int status, final String reason, final String message) throws IOException { - final JsonFactory jsonFactory = new JacksonFactory(); - HttpTransport transport = new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - ErrorInfo errorInfo = new ErrorInfo(); - errorInfo.setReason(reason); - errorInfo.setMessage(message); - errorInfo.setFactory(jsonFactory); - GenericJson error = new GenericJson(); - error.set("code", status); - error.set("errors", Arrays.asList(errorInfo)); - error.setFactory(jsonFactory); - GenericJson errorResponse = new GenericJson(); - errorResponse.set("error", error); - errorResponse.setFactory(jsonFactory); - return new MockLowLevelHttpRequest().setResponse( - new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString()) - .setContentType(Json.MEDIA_TYPE).setStatusCode(status)); - } - }; - HttpRequest request = - transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); - request.setThrowExceptionOnExecuteError(false); - HttpResponse response = request.execute(); - return GoogleJsonResponseException.from(jsonFactory, response); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java deleted file mode 100644 index 880dd9fb71..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubClientTest.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; - -import com.google.common.collect.ImmutableMap; - -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Map; - -/** - * Tests for helper classes and methods in PubsubClient. - */ -@RunWith(JUnit4.class) -public class PubsubClientTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - // - // Timestamp handling - // - - private long parse(String timestamp) { - Map map = ImmutableMap.of("myLabel", timestamp); - return PubsubClient.extractTimestamp("myLabel", null, map); - } - - private void roundTripRfc339(String timestamp) { - assertEquals(Instant.parse(timestamp).getMillis(), parse(timestamp)); - } - - private void truncatedRfc339(String timestamp, String truncatedTimestmap) { - assertEquals(Instant.parse(truncatedTimestmap).getMillis(), parse(timestamp)); - } - - @Test - public void noTimestampLabelReturnsPubsubPublish() { - final long time = 987654321L; - long timestamp = PubsubClient.extractTimestamp(null, String.valueOf(time), null); - assertEquals(time, timestamp); - } - - @Test - public void noTimestampLabelAndInvalidPubsubPublishThrowsError() { - thrown.expect(NumberFormatException.class); - PubsubClient.extractTimestamp(null, "not-a-date", null); - } - - @Test - public void timestampLabelWithNullAttributesThrowsError() { - thrown.expect(RuntimeException.class); - thrown.expectMessage("PubSub message is missing a value for timestamp label myLabel"); - PubsubClient.extractTimestamp("myLabel", null, null); - } - - @Test - public void timestampLabelSetWithMissingAttributeThrowsError() { - thrown.expect(RuntimeException.class); - thrown.expectMessage("PubSub message is missing a value for timestamp label myLabel"); - Map map = ImmutableMap.of("otherLabel", "whatever"); - PubsubClient.extractTimestamp("myLabel", null, map); - } - - @Test - public void timestampLabelParsesMillisecondsSinceEpoch() { - long time = 1446162101123L; - Map map = ImmutableMap.of("myLabel", String.valueOf(time)); - long timestamp = PubsubClient.extractTimestamp("myLabel", null, map); - assertEquals(time, timestamp); - } - - @Test - public void timestampLabelParsesRfc3339Seconds() { - roundTripRfc339("2015-10-29T23:41:41Z"); - } - - @Test - public void timestampLabelParsesRfc3339Tenths() { - roundTripRfc339("2015-10-29T23:41:41.1Z"); - } - - @Test - public void timestampLabelParsesRfc3339Hundredths() { - roundTripRfc339("2015-10-29T23:41:41.12Z"); - } - - @Test - public void timestampLabelParsesRfc3339Millis() { - roundTripRfc339("2015-10-29T23:41:41.123Z"); - } - - @Test - public void timestampLabelParsesRfc3339Micros() { - // Note: micros part 456/1000 is dropped. - truncatedRfc339("2015-10-29T23:41:41.123456Z", "2015-10-29T23:41:41.123Z"); - } - - @Test - public void timestampLabelParsesRfc3339MicrosRounding() { - // Note: micros part 999/1000 is dropped, not rounded up. - truncatedRfc339("2015-10-29T23:41:41.123999Z", "2015-10-29T23:41:41.123Z"); - } - - @Test - public void timestampLabelWithInvalidFormatThrowsError() { - thrown.expect(NumberFormatException.class); - parse("not-a-timestamp"); - } - - @Test - public void timestampLabelWithInvalidFormat2ThrowsError() { - thrown.expect(NumberFormatException.class); - parse("null"); - } - - @Test - public void timestampLabelWithInvalidFormat3ThrowsError() { - thrown.expect(NumberFormatException.class); - parse("2015-10"); - } - - @Test - public void timestampLabelParsesRfc3339WithSmallYear() { - // Google and JodaTime agree on dates after 1582-10-15, when the Gregorian Calendar was adopted - // This is therefore a "small year" until this difference is reconciled. - roundTripRfc339("1582-10-15T01:23:45.123Z"); - } - - @Test - public void timestampLabelParsesRfc3339WithLargeYear() { - // Year 9999 in range. - roundTripRfc339("9999-10-29T23:41:41.123999Z"); - } - - @Test - public void timestampLabelRfc3339WithTooLargeYearThrowsError() { - thrown.expect(NumberFormatException.class); - // Year 10000 out of range. - parse("10000-10-29T23:41:41.123999Z"); - } - - // - // Paths - // - - @Test - public void projectPathFromIdWellFormed() { - ProjectPath path = PubsubClient.projectPathFromId("test"); - assertEquals("projects/test", path.getPath()); - } - - @Test - public void subscriptionPathFromNameWellFormed() { - SubscriptionPath path = PubsubClient.subscriptionPathFromName("test", "something"); - assertEquals("projects/test/subscriptions/something", path.getPath()); - assertEquals("/subscriptions/test/something", path.getV1Beta1Path()); - } - - @Test - public void topicPathFromNameWellFormed() { - TopicPath path = PubsubClient.topicPathFromName("test", "something"); - assertEquals("projects/test/topics/something", path.getPath()); - assertEquals("/topics/test/something", path.getV1Beta1Path()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java deleted file mode 100644 index cdb2d91d10..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubGrpcClientTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.auth.oauth2.GoogleCredentials; - -import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.protobuf.ByteString; -import com.google.protobuf.Timestamp; -import com.google.pubsub.v1.PublishRequest; -import com.google.pubsub.v1.PublishResponse; -import com.google.pubsub.v1.PublisherGrpc; -import com.google.pubsub.v1.PubsubMessage; -import com.google.pubsub.v1.PullRequest; -import com.google.pubsub.v1.PullResponse; -import com.google.pubsub.v1.ReceivedMessage; -import com.google.pubsub.v1.SubscriberGrpc; - -import io.grpc.ManagedChannel; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; - -import java.io.IOException; -import java.util.List; - -/** - * Tests for PubsubGrpcClient. - */ -@RunWith(JUnit4.class) -public class PubsubGrpcClientTest { - private ManagedChannel mockChannel; - private GoogleCredentials mockCredentials; - private PublisherGrpc.PublisherBlockingStub mockPublisherStub; - private SubscriberGrpc.SubscriberBlockingStub mockSubscriberStub; - - private PubsubClient client; - - private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); - private static final SubscriptionPath SUBSCRIPTION = - PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); - private static final long REQ_TIME = 1234L; - private static final long PUB_TIME = 3456L; - private static final long MESSAGE_TIME = 6789L; - private static final String TIMESTAMP_LABEL = "timestamp"; - private static final String ID_LABEL = "id"; - private static final String MESSAGE_ID = "testMessageId"; - private static final String DATA = "testData"; - private static final String RECORD_ID = "testRecordId"; - private static final String ACK_ID = "testAckId"; - - @Before - public void setup() throws IOException { - mockChannel = Mockito.mock(ManagedChannel.class); - mockCredentials = Mockito.mock(GoogleCredentials.class); - mockPublisherStub = - Mockito.mock(PublisherGrpc.PublisherBlockingStub.class, Mockito.RETURNS_DEEP_STUBS); - mockSubscriberStub = - Mockito.mock(SubscriberGrpc.SubscriberBlockingStub.class, Mockito.RETURNS_DEEP_STUBS); - client = new PubsubGrpcClient(TIMESTAMP_LABEL, ID_LABEL, 0, mockChannel, - mockCredentials, mockPublisherStub, mockSubscriberStub); - } - - @After - public void teardown() throws IOException { - client.close(); - client = null; - mockChannel = null; - mockCredentials = null; - mockPublisherStub = null; - mockSubscriberStub = null; - } - - @Test - public void pullOneMessage() throws IOException { - String expectedSubscription = SUBSCRIPTION.getPath(); - PullRequest expectedRequest = - PullRequest.newBuilder() - .setSubscription(expectedSubscription) - .setReturnImmediately(true) - .setMaxMessages(10) - .build(); - Timestamp timestamp = Timestamp.newBuilder() - .setSeconds(PUB_TIME / 1000) - .setNanos((int) (PUB_TIME % 1000) * 1000) - .build(); - PubsubMessage expectedPubsubMessage = - PubsubMessage.newBuilder() - .setMessageId(MESSAGE_ID) - .setData( - ByteString.copyFrom(DATA.getBytes())) - .setPublishTime(timestamp) - .putAllAttributes( - ImmutableMap.of(TIMESTAMP_LABEL, - String.valueOf(MESSAGE_TIME), - ID_LABEL, RECORD_ID)) - .build(); - ReceivedMessage expectedReceivedMessage = - ReceivedMessage.newBuilder() - .setMessage(expectedPubsubMessage) - .setAckId(ACK_ID) - .build(); - PullResponse expectedResponse = - PullResponse.newBuilder() - .addAllReceivedMessages(ImmutableList.of(expectedReceivedMessage)) - .build(); - Mockito.when(mockSubscriberStub.pull(expectedRequest)) - .thenReturn(expectedResponse); - List acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true); - assertEquals(1, acutalMessages.size()); - IncomingMessage actualMessage = acutalMessages.get(0); - assertEquals(ACK_ID, actualMessage.ackId); - assertEquals(DATA, new String(actualMessage.elementBytes)); - assertEquals(RECORD_ID, actualMessage.recordId); - assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch); - assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch); - } - - @Test - public void publishOneMessage() throws IOException { - String expectedTopic = TOPIC.getPath(); - PubsubMessage expectedPubsubMessage = - PubsubMessage.newBuilder() - .setData(ByteString.copyFrom(DATA.getBytes())) - .putAllAttributes( - ImmutableMap.of(TIMESTAMP_LABEL, String.valueOf(MESSAGE_TIME), - ID_LABEL, RECORD_ID)) - .build(); - PublishRequest expectedRequest = - PublishRequest.newBuilder() - .setTopic(expectedTopic) - .addAllMessages( - ImmutableList.of(expectedPubsubMessage)) - .build(); - PublishResponse expectedResponse = - PublishResponse.newBuilder() - .addAllMessageIds(ImmutableList.of(MESSAGE_ID)) - .build(); - Mockito.when(mockPublisherStub.publish(expectedRequest)) - .thenReturn(expectedResponse); - OutgoingMessage actualMessage = new OutgoingMessage(DATA.getBytes(), MESSAGE_TIME, RECORD_ID); - int n = client.publish(TOPIC, ImmutableList.of(actualMessage)); - assertEquals(1, n); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClientTest.java deleted file mode 100644 index c3dd452d43..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubJsonClientTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.PublishRequest; -import com.google.api.services.pubsub.model.PublishResponse; -import com.google.api.services.pubsub.model.PubsubMessage; -import com.google.api.services.pubsub.model.PullRequest; -import com.google.api.services.pubsub.model.PullResponse; -import com.google.api.services.pubsub.model.ReceivedMessage; - -import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; - -import java.io.IOException; -import java.util.List; - -/** - * Tests for PubsubJsonClient. - */ -@RunWith(JUnit4.class) -public class PubsubJsonClientTest { - private Pubsub mockPubsub; - private PubsubClient client; - - private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); - private static final SubscriptionPath SUBSCRIPTION = - PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); - private static final long REQ_TIME = 1234L; - private static final long PUB_TIME = 3456L; - private static final long MESSAGE_TIME = 6789L; - private static final String TIMESTAMP_LABEL = "timestamp"; - private static final String ID_LABEL = "id"; - private static final String MESSAGE_ID = "testMessageId"; - private static final String DATA = "testData"; - private static final String RECORD_ID = "testRecordId"; - private static final String ACK_ID = "testAckId"; - - @Before - public void setup() throws IOException { - mockPubsub = Mockito.mock(Pubsub.class, Mockito.RETURNS_DEEP_STUBS); - client = new PubsubJsonClient(TIMESTAMP_LABEL, ID_LABEL, mockPubsub); - } - - @After - public void teardown() throws IOException { - client.close(); - client = null; - mockPubsub = null; - } - - @Test - public void pullOneMessage() throws IOException { - String expectedSubscription = SUBSCRIPTION.getPath(); - PullRequest expectedRequest = - new PullRequest().setReturnImmediately(true).setMaxMessages(10); - PubsubMessage expectedPubsubMessage = new PubsubMessage() - .setMessageId(MESSAGE_ID) - .encodeData(DATA.getBytes()) - .setPublishTime(String.valueOf(PUB_TIME)) - .setAttributes( - ImmutableMap.of(TIMESTAMP_LABEL, String.valueOf(MESSAGE_TIME), - ID_LABEL, RECORD_ID)); - ReceivedMessage expectedReceivedMessage = - new ReceivedMessage().setMessage(expectedPubsubMessage) - .setAckId(ACK_ID); - PullResponse expectedResponse = - new PullResponse().setReceivedMessages(ImmutableList.of(expectedReceivedMessage)); - Mockito.when((Object) mockPubsub.projects() - .subscriptions() - .pull(expectedSubscription, expectedRequest) - .execute()) - .thenReturn(expectedResponse); - List acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true); - assertEquals(1, acutalMessages.size()); - IncomingMessage actualMessage = acutalMessages.get(0); - assertEquals(ACK_ID, actualMessage.ackId); - assertEquals(DATA, new String(actualMessage.elementBytes)); - assertEquals(RECORD_ID, actualMessage.recordId); - assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch); - assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch); - } - - @Test - public void publishOneMessage() throws IOException { - String expectedTopic = TOPIC.getPath(); - PubsubMessage expectedPubsubMessage = new PubsubMessage() - .encodeData(DATA.getBytes()) - .setAttributes( - ImmutableMap.of(TIMESTAMP_LABEL, String.valueOf(MESSAGE_TIME), - ID_LABEL, RECORD_ID)); - PublishRequest expectedRequest = new PublishRequest() - .setMessages(ImmutableList.of(expectedPubsubMessage)); - PublishResponse expectedResponse = new PublishResponse() - .setMessageIds(ImmutableList.of(MESSAGE_ID)); - Mockito.when((Object) mockPubsub.projects() - .topics() - .publish(expectedTopic, expectedRequest) - .execute()) - .thenReturn(expectedResponse); - OutgoingMessage actualMessage = new OutgoingMessage(DATA.getBytes(), MESSAGE_TIME, RECORD_ID); - int n = client.publish(TOPIC, ImmutableList.of(actualMessage)); - assertEquals(1, n); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java deleted file mode 100644 index 1ba1b29cd4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PubsubTestClientTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.api.client.util.Clock; - -import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; -import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; -import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; -import com.google.cloud.dataflow.sdk.util.PubsubTestClient.PubsubTestClientFactory; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Tests for PubsubTestClient. - */ -@RunWith(JUnit4.class) -public class PubsubTestClientTest { - private static final TopicPath TOPIC = PubsubClient.topicPathFromName("testProject", "testTopic"); - private static final SubscriptionPath SUBSCRIPTION = - PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); - private static final long REQ_TIME = 1234L; - private static final long MESSAGE_TIME = 6789L; - private static final String MESSAGE_ID = "testMessageId"; - private static final String DATA = "testData"; - private static final String ACK_ID = "testAckId"; - private static final int ACK_TIMEOUT_S = 60; - - @Test - public void pullOneMessage() throws IOException { - final AtomicLong now = new AtomicLong(); - Clock clock = new Clock() { - @Override - public long currentTimeMillis() { - return now.get(); - } - }; - IncomingMessage expectedIncomingMessage = - new IncomingMessage(DATA.getBytes(), MESSAGE_TIME, REQ_TIME, ACK_ID, MESSAGE_ID); - try (PubsubTestClientFactory factory = - PubsubTestClient.createFactoryForPull(clock, SUBSCRIPTION, ACK_TIMEOUT_S, - Lists.newArrayList(expectedIncomingMessage))) { - try (PubsubTestClient client = (PubsubTestClient) factory.newClient(null, null, null)) { - now.set(REQ_TIME); - client.advance(); - List incomingMessages = client.pull(now.get(), SUBSCRIPTION, 1, true); - assertEquals(1, incomingMessages.size()); - assertEquals(expectedIncomingMessage, incomingMessages.get(0)); - // Timeout on ACK. - now.addAndGet((ACK_TIMEOUT_S + 10) * 1000); - client.advance(); - incomingMessages = client.pull(now.get(), SUBSCRIPTION, 1, true); - assertEquals(1, incomingMessages.size()); - assertEquals(expectedIncomingMessage.withRequestTime(now.get()), incomingMessages.get(0)); - now.addAndGet(10 * 1000); - client.advance(); - // Extend ack - client.modifyAckDeadline(SUBSCRIPTION, ImmutableList.of(ACK_ID), 20); - // Timeout on extended ACK - now.addAndGet(30 * 1000); - client.advance(); - incomingMessages = client.pull(now.get(), SUBSCRIPTION, 1, true); - assertEquals(1, incomingMessages.size()); - assertEquals(expectedIncomingMessage.withRequestTime(now.get()), incomingMessages.get(0)); - // Extend ack - client.modifyAckDeadline(SUBSCRIPTION, ImmutableList.of(ACK_ID), 20); - // Ack - now.addAndGet(15 * 1000); - client.advance(); - client.acknowledge(SUBSCRIPTION, ImmutableList.of(ACK_ID)); - } - } - } - - @Test - public void publishOneMessage() throws IOException { - OutgoingMessage expectedOutgoingMessage = - new OutgoingMessage(DATA.getBytes(), MESSAGE_TIME, MESSAGE_ID); - try (PubsubTestClientFactory factory = - PubsubTestClient.createFactoryForPublish( - TOPIC, - Sets.newHashSet(expectedOutgoingMessage), - ImmutableList.of())) { - try (PubsubTestClient client = (PubsubTestClient) factory.newClient(null, null, null)) { - client.publish(TOPIC, ImmutableList.of(expectedOutgoingMessage)); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunnerTest.java deleted file mode 100644 index d1239ad97d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/PushbackSideInputDoFnRunnerTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for {@link PushbackSideInputDoFnRunner}. - */ -@RunWith(JUnit4.class) -public class PushbackSideInputDoFnRunnerTest { - @Mock private ReadyCheckingSideInputReader reader; - private TestDoFnRunner underlying; - private PCollectionView singletonView; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - TestPipeline p = TestPipeline.create(); - PCollection created = p.apply(Create.of(1, 2, 3)); - singletonView = - created - .apply(Window.into(new IdentitySideInputWindowFn())) - .apply(Sum.integersGlobally().asSingletonView()); - - underlying = new TestDoFnRunner<>(); - } - - private PushbackSideInputDoFnRunner createRunner( - ImmutableList> views) { - PushbackSideInputDoFnRunner runner = - PushbackSideInputDoFnRunner.create(underlying, views, reader); - runner.startBundle(); - return runner; - } - - @Test - public void startFinishBundleDelegates() { - PushbackSideInputDoFnRunner runner = - createRunner(ImmutableList.>of(singletonView)); - - assertThat(underlying.started, is(true)); - assertThat(underlying.finished, is(false)); - runner.finishBundle(); - assertThat(underlying.finished, is(true)); - } - - @Test - public void processElementSideInputNotReady() { - when(reader.isReady(Mockito.eq(singletonView), Mockito.any(BoundedWindow.class))) - .thenReturn(false); - - PushbackSideInputDoFnRunner runner = - createRunner(ImmutableList.>of(singletonView)); - - WindowedValue oneWindow = - WindowedValue.of( - 2, - new Instant(-2), - new IntervalWindow(new Instant(-500L), new Instant(0L)), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - Iterable> oneWindowPushback = - runner.processElementInReadyWindows(oneWindow); - assertThat(oneWindowPushback, containsInAnyOrder(oneWindow)); - assertThat(underlying.inputElems, Matchers.>emptyIterable()); - } - - @Test - public void processElementSideInputNotReadyMultipleWindows() { - when(reader.isReady(Mockito.eq(singletonView), Mockito.any(BoundedWindow.class))) - .thenReturn(false); - - PushbackSideInputDoFnRunner runner = - createRunner(ImmutableList.>of(singletonView)); - - WindowedValue multiWindow = - WindowedValue.of( - 2, - new Instant(-2), - ImmutableList.of( - new IntervalWindow(new Instant(-500L), new Instant(0L)), - new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)), - GlobalWindow.INSTANCE), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - Iterable> multiWindowPushback = - runner.processElementInReadyWindows(multiWindow); - assertThat(multiWindowPushback, equalTo(multiWindow.explodeWindows())); - assertThat(underlying.inputElems, Matchers.>emptyIterable()); - } - - @Test - public void processElementSideInputNotReadySomeWindows() { - when(reader.isReady(Mockito.eq(singletonView), Mockito.eq(GlobalWindow.INSTANCE))) - .thenReturn(false); - when( - reader.isReady( - Mockito.eq(singletonView), - org.mockito.AdditionalMatchers.not(Mockito.eq(GlobalWindow.INSTANCE)))) - .thenReturn(true); - - PushbackSideInputDoFnRunner runner = - createRunner(ImmutableList.>of(singletonView)); - - IntervalWindow littleWindow = new IntervalWindow(new Instant(-500L), new Instant(0L)); - IntervalWindow bigWindow = - new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)); - WindowedValue multiWindow = - WindowedValue.of( - 2, - new Instant(-2), - ImmutableList.of(littleWindow, bigWindow, GlobalWindow.INSTANCE), - PaneInfo.NO_FIRING); - Iterable> multiWindowPushback = - runner.processElementInReadyWindows(multiWindow); - assertThat( - multiWindowPushback, - containsInAnyOrder(WindowedValue.timestampedValueInGlobalWindow(2, new Instant(-2L)))); - assertThat(underlying.inputElems, - containsInAnyOrder(WindowedValue.of(2, new Instant(-2), littleWindow, PaneInfo.NO_FIRING), - WindowedValue.of(2, new Instant(-2), bigWindow, PaneInfo.NO_FIRING))); - } - - @Test - public void processElementSideInputReadyAllWindows() { - when(reader.isReady(Mockito.eq(singletonView), Mockito.any(BoundedWindow.class))) - .thenReturn(true); - - ImmutableList> views = ImmutableList.>of(singletonView); - PushbackSideInputDoFnRunner runner = createRunner(views); - - WindowedValue multiWindow = - WindowedValue.of( - 2, - new Instant(-2), - ImmutableList.of( - new IntervalWindow(new Instant(-500L), new Instant(0L)), - new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)), - GlobalWindow.INSTANCE), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - Iterable> multiWindowPushback = - runner.processElementInReadyWindows(multiWindow); - assertThat(multiWindowPushback, emptyIterable()); - assertThat(underlying.inputElems, - containsInAnyOrder(ImmutableList.copyOf(multiWindow.explodeWindows()).toArray())); - } - - @Test - public void processElementNoSideInputs() { - PushbackSideInputDoFnRunner runner = - createRunner(ImmutableList.>of()); - - WindowedValue multiWindow = - WindowedValue.of( - 2, - new Instant(-2), - ImmutableList.of( - new IntervalWindow(new Instant(-500L), new Instant(0L)), - new IntervalWindow(BoundedWindow.TIMESTAMP_MIN_VALUE, new Instant(250L)), - GlobalWindow.INSTANCE), - PaneInfo.ON_TIME_AND_ONLY_FIRING); - Iterable> multiWindowPushback = - runner.processElementInReadyWindows(multiWindow); - assertThat(multiWindowPushback, emptyIterable()); - assertThat(underlying.inputElems, containsInAnyOrder(multiWindow)); - } - - private static class TestDoFnRunner implements DoFnRunner { - List> inputElems; - private boolean started = false; - private boolean finished = false; - - @Override - public void startBundle() { - started = true; - inputElems = new ArrayList<>(); - } - - @Override - public void processElement(WindowedValue elem) { - inputElems.add(elem); - } - - @Override - public void finishBundle() { - finished = true; - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java deleted file mode 100644 index 6d88305068..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RandomAccessDataTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.coders.Coder.Context; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.util.RandomAccessData.RandomAccessDataCoder; -import com.google.common.primitives.UnsignedBytes; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.Arrays; - -/** - * Tests for {@link RandomAccessData}. - */ -@RunWith(JUnit4.class) -public class RandomAccessDataTest { - private static final byte[] TEST_DATA_A = new byte[]{ 0x01, 0x02, 0x03 }; - private static final byte[] TEST_DATA_B = new byte[]{ 0x06, 0x05, 0x04, 0x03 }; - private static final byte[] TEST_DATA_C = new byte[]{ 0x06, 0x05, 0x03, 0x03 }; - - @Rule public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testCoder() throws Exception { - RandomAccessData streamA = new RandomAccessData(); - streamA.asOutputStream().write(TEST_DATA_A); - RandomAccessData streamB = new RandomAccessData(); - streamB.asOutputStream().write(TEST_DATA_A); - CoderProperties.coderDecodeEncodeEqual(RandomAccessDataCoder.of(), streamA); - CoderProperties.coderDeterministic(RandomAccessDataCoder.of(), streamA, streamB); - CoderProperties.coderConsistentWithEquals(RandomAccessDataCoder.of(), streamA, streamB); - CoderProperties.coderSerializable(RandomAccessDataCoder.of()); - CoderProperties.structuralValueConsistentWithEquals( - RandomAccessDataCoder.of(), streamA, streamB); - assertTrue(RandomAccessDataCoder.of().isRegisterByteSizeObserverCheap(streamA, Context.NESTED)); - assertTrue(RandomAccessDataCoder.of().isRegisterByteSizeObserverCheap(streamA, Context.OUTER)); - assertEquals(4, RandomAccessDataCoder.of().getEncodedElementByteSize(streamA, Context.NESTED)); - assertEquals(3, RandomAccessDataCoder.of().getEncodedElementByteSize(streamA, Context.OUTER)); - } - - @Test - public void testCoderWithPositiveInfinityIsError() throws Exception { - expectedException.expect(CoderException.class); - expectedException.expectMessage("Positive infinity can not be encoded"); - RandomAccessDataCoder.of().encode( - RandomAccessData.POSITIVE_INFINITY, new ByteArrayOutputStream(), Context.OUTER); - } - - @Test - public void testLexicographicalComparator() throws Exception { - RandomAccessData streamA = new RandomAccessData(); - streamA.asOutputStream().write(TEST_DATA_A); - RandomAccessData streamB = new RandomAccessData(); - streamB.asOutputStream().write(TEST_DATA_B); - RandomAccessData streamC = new RandomAccessData(); - streamC.asOutputStream().write(TEST_DATA_C); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - streamA, streamB) < 0); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - streamB, streamA) > 0); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - streamB, streamB) == 0); - // Check common prefix length. - assertEquals(2, RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.commonPrefixLength( - streamB, streamC)); - // Check that we honor the start offset. - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - streamB, streamC, 3) == 0); - // Test positive infinity comparisons. - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - streamA, RandomAccessData.POSITIVE_INFINITY) < 0); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - RandomAccessData.POSITIVE_INFINITY, RandomAccessData.POSITIVE_INFINITY) == 0); - assertTrue(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR.compare( - RandomAccessData.POSITIVE_INFINITY, streamA) > 0); - } - - @Test - public void testEqualsAndHashCode() throws Exception { - // Test that equality by reference works - RandomAccessData streamA = new RandomAccessData(); - streamA.asOutputStream().write(TEST_DATA_A); - assertEquals(streamA, streamA); - assertEquals(streamA.hashCode(), streamA.hashCode()); - - // Test different objects containing the same data are the same - RandomAccessData streamACopy = new RandomAccessData(); - streamACopy.asOutputStream().write(TEST_DATA_A); - assertEquals(streamA, streamACopy); - assertEquals(streamA.hashCode(), streamACopy.hashCode()); - - // Test same length streams with different data differ - RandomAccessData streamB = new RandomAccessData(); - streamB.asOutputStream().write(new byte[]{ 0x01, 0x02, 0x04 }); - assertNotEquals(streamA, streamB); - assertNotEquals(streamA.hashCode(), streamB.hashCode()); - - // Test different length streams differ - streamB.asOutputStream().write(TEST_DATA_B); - assertNotEquals(streamA, streamB); - assertNotEquals(streamA.hashCode(), streamB.hashCode()); - } - - @Test - public void testResetTo() throws Exception { - RandomAccessData stream = new RandomAccessData(); - stream.asOutputStream().write(TEST_DATA_A); - stream.resetTo(1); - assertEquals(1, stream.size()); - stream.asOutputStream().write(TEST_DATA_A); - assertArrayEquals(new byte[]{ 0x01, 0x01, 0x02, 0x03 }, - Arrays.copyOf(stream.array(), stream.size())); - } - - @Test - public void testAsInputStream() throws Exception { - RandomAccessData stream = new RandomAccessData(); - stream.asOutputStream().write(TEST_DATA_A); - InputStream in = stream.asInputStream(1, 1); - assertEquals(0x02, in.read()); - assertEquals(-1, in.read()); - in.close(); - } - - @Test - public void testReadFrom() throws Exception { - ByteArrayInputStream bais = new ByteArrayInputStream(TEST_DATA_A); - RandomAccessData stream = new RandomAccessData(); - stream.readFrom(bais, 3, 2); - assertArrayEquals(new byte[]{ 0x00, 0x00, 0x00, 0x01, 0x02 }, - Arrays.copyOf(stream.array(), stream.size())); - bais.close(); - } - - @Test - public void testWriteTo() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - RandomAccessData stream = new RandomAccessData(); - stream.asOutputStream().write(TEST_DATA_B); - stream.writeTo(baos, 1, 2); - assertArrayEquals(new byte[]{ 0x05, 0x04 }, baos.toByteArray()); - baos.close(); - } - - @Test - public void testThatRandomAccessDataGrowsWhenResettingToPositionBeyondEnd() throws Exception { - RandomAccessData stream = new RandomAccessData(0); - assertArrayEquals(new byte[0], stream.array()); - stream.resetTo(3); // force resize - assertArrayEquals(new byte[]{ 0x00, 0x00, 0x00 }, stream.array()); - } - - @Test - public void testThatRandomAccessDataGrowsWhenReading() throws Exception { - RandomAccessData stream = new RandomAccessData(0); - assertArrayEquals(new byte[0], stream.array()); - stream.readFrom(new ByteArrayInputStream(TEST_DATA_A), 0, TEST_DATA_A.length); - assertArrayEquals(TEST_DATA_A, - Arrays.copyOf(stream.array(), TEST_DATA_A.length)); - } - - @Test - public void testIncrement() throws Exception { - assertEquals(new RandomAccessData(new byte[]{ 0x00, 0x01 }), - new RandomAccessData(new byte[]{ 0x00, 0x00 }).increment()); - assertEquals(new RandomAccessData(new byte[]{ 0x01, UnsignedBytes.MAX_VALUE }), - new RandomAccessData(new byte[]{ 0x00, UnsignedBytes.MAX_VALUE }).increment()); - - // Test for positive infinity - assertSame(RandomAccessData.POSITIVE_INFINITY, new RandomAccessData(new byte[0]).increment()); - assertSame(RandomAccessData.POSITIVE_INFINITY, - new RandomAccessData(new byte[]{ UnsignedBytes.MAX_VALUE }).increment()); - assertSame(RandomAccessData.POSITIVE_INFINITY, RandomAccessData.POSITIVE_INFINITY.increment()); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java deleted file mode 100644 index 1af82a358d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnRunnerTest.java +++ /dev/null @@ -1,1450 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.WindowMatchers.isSingleWindowedValue; -import static com.google.cloud.dataflow.sdk.WindowMatchers.isWindowedValue; -import static com.google.common.base.Preconditions.checkArgument; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; - -import com.google.cloud.dataflow.sdk.WindowMatchers; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.CombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.Context; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterEach; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterFirst; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterPane; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Never; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.cloud.dataflow.sdk.transforms.windowing.Repeatedly; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.collect.Iterables; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -/** - * Tests for {@link ReduceFnRunner}. These tests instantiate a full "stack" of - * {@link ReduceFnRunner} with enclosed {@link ReduceFn}, down to the installed {@link Trigger} - * (sometimes mocked). They proceed by injecting elements and advancing watermark and - * processing time, then verifying produced panes and counters. - */ -@RunWith(JUnit4.class) -public class ReduceFnRunnerTest { - @Mock private SideInputReader mockSideInputReader; - private Trigger mockTrigger; - private PCollectionView mockView; - - private IntervalWindow firstWindow; - - private static Trigger.TriggerContext anyTriggerContext() { - return Mockito..TriggerContext>any(); - } - private static Trigger.OnElementContext anyElementContext() { - return Mockito..OnElementContext>any(); - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - @SuppressWarnings("unchecked") - Trigger mockTriggerUnchecked = - mock(Trigger.class, withSettings().serializable()); - mockTrigger = mockTriggerUnchecked; - when(mockTrigger.buildTrigger()).thenReturn(mockTrigger); - - @SuppressWarnings("unchecked") - PCollectionView mockViewUnchecked = - mock(PCollectionView.class, withSettings().serializable()); - mockView = mockViewUnchecked; - firstWindow = new IntervalWindow(new Instant(0), new Instant(10)); - } - - private void injectElement(ReduceFnTester tester, int element) - throws Exception { - doNothing().when(mockTrigger).onElement(anyElementContext()); - tester.injectElements(TimestampedValue.of(element, new Instant(element))); - } - - private void triggerShouldFinish(Trigger mockTrigger) throws Exception { - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Exception { - @SuppressWarnings("unchecked") - Trigger.TriggerContext context = - (Trigger.TriggerContext) invocation.getArguments()[0]; - context.trigger().setFinished(true); - return null; - } - }) - .when(mockTrigger).onFire(anyTriggerContext()); - } - - @Test - public void testOnElementBufferingDiscarding() throws Exception { - // Test basic execution of a trigger using a non-combining window set and discarding mode. - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // Pane of {1, 2} - injectElement(tester, 1); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 2); - assertThat(tester.extractOutput(), - contains(isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10))); - - // Pane of just 3, and finish - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 3); - assertThat(tester.extractOutput(), - contains(isSingleWindowedValue(containsInAnyOrder(3), 3, 0, 10))); - assertTrue(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); - - // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 4); - - assertEquals(1, tester.getElementsDroppedDueToClosedWindow()); - } - - @Test - public void testOnElementBufferingAccumulating() throws Exception { - // Test basic execution of a trigger using a non-combining window set and accumulating mode. - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - injectElement(tester, 1); - - // Fires {1, 2} - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 2); - - // Fires {1, 2, 3} because we are in accumulating mode - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 3); - - // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 4); - - assertThat( - tester.extractOutput(), - contains( - isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10), - isSingleWindowedValue(containsInAnyOrder(1, 2, 3), 3, 0, 10))); - assertTrue(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); - } - - @Test - public void testOnElementCombiningDiscarding() throws Exception { - // Test basic execution of a trigger using a non-combining window set and discarding mode. - ReduceFnTester tester = ReduceFnTester.combining( - FixedWindows.of(Duration.millis(10)), mockTrigger, AccumulationMode.DISCARDING_FIRED_PANES, - new Sum.SumIntegerFn().asKeyedFn(), VarIntCoder.of(), Duration.millis(100)); - - injectElement(tester, 2); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 3); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 4); - - // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 6); - - assertThat( - tester.extractOutput(), - contains( - isSingleWindowedValue(equalTo(5), 2, 0, 10), - isSingleWindowedValue(equalTo(4), 4, 0, 10))); - assertTrue(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); - } - - /** - * Tests that the garbage collection time for a fixed window does not overflow the end of time. - */ - @Test - public void testFixedWindowEndOfTimeGarbageCollection() throws Exception { - - Duration allowedLateness = Duration.standardDays(365); - Duration windowSize = Duration.millis(10); - WindowFn windowFn = FixedWindows.of(windowSize); - - // This timestamp falls into a window where the end of the window is before the end of the - // global window - the "end of time" - yet its expiration time is after. - final Instant elementTimestamp = - GlobalWindow.INSTANCE.maxTimestamp().minus(allowedLateness).plus(1); - - IntervalWindow window = Iterables.getOnlyElement( - windowFn.assignWindows( - windowFn.new AssignContext() { - @Override - public Object element() { - throw new UnsupportedOperationException(); - } - @Override - public Instant timestamp() { - return elementTimestamp; - } - - @Override - public Collection windows() { - throw new UnsupportedOperationException(); - } - })); - - assertTrue( - window.maxTimestamp().isBefore(GlobalWindow.INSTANCE.maxTimestamp())); - assertTrue( - window.maxTimestamp().plus(allowedLateness).isAfter(GlobalWindow.INSTANCE.maxTimestamp())); - - // Test basic execution of a trigger using a non-combining window set and accumulating mode. - ReduceFnTester tester = - ReduceFnTester.combining( - windowFn, - AfterWatermark.pastEndOfWindow() - .withLateFirings(Never.ever()).buildTrigger(), - AccumulationMode.DISCARDING_FIRED_PANES, - new Sum.SumIntegerFn().asKeyedFn(), - VarIntCoder.of(), - allowedLateness); - - tester.injectElements(TimestampedValue.of(13, elementTimestamp)); - - // Should fire ON_TIME pane and there will be a checkState that the cleanup time - // is prior to timestamp max value - tester.advanceInputWatermark(window.maxTimestamp()); - - // Nothing in the ON_TIME pane (not governed by triggers, but by ReduceFnRunner) - assertThat(tester.extractOutput(), emptyIterable()); - - tester.injectElements(TimestampedValue.of(42, elementTimestamp)); - - // Now the final pane should fire, demonstrating that the GC time was truncated - tester.advanceInputWatermark(GlobalWindow.INSTANCE.maxTimestamp()); - assertThat(tester.extractOutput(), contains(isWindowedValue(equalTo(55)))); - } - - @Test - public void testOnElementCombiningAccumulating() throws Exception { - // Test basic execution of a trigger using a non-combining window set and accumulating mode. - ReduceFnTester tester = - ReduceFnTester.combining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, new Sum.SumIntegerFn().asKeyedFn(), - VarIntCoder.of(), Duration.millis(100)); - - injectElement(tester, 1); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 2); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 3); - - // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 4); - - assertThat( - tester.extractOutput(), - contains( - isSingleWindowedValue(equalTo(3), 1, 0, 10), - isSingleWindowedValue(equalTo(6), 3, 0, 10))); - assertTrue(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); - } - - @Test - public void testOnElementCombiningWithContext() throws Exception { - Integer expectedValue = 5; - WindowingStrategy windowingStrategy = WindowingStrategy - .of(FixedWindows.of(Duration.millis(10))) - .withTrigger(mockTrigger) - .withMode(AccumulationMode.DISCARDING_FIRED_PANES) - .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) - .withAllowedLateness(Duration.millis(100)); - - TestOptions options = PipelineOptionsFactory.as(TestOptions.class); - options.setValue(5); - - when(mockSideInputReader.contains(Matchers.>any())).thenReturn(true); - when(mockSideInputReader.get( - Matchers.>any(), any(BoundedWindow.class))).thenReturn(5); - - @SuppressWarnings({"rawtypes", "unchecked", "unused"}) - Object suppressWarningsVar = when(mockView.getWindowingStrategyInternal()) - .thenReturn((WindowingStrategy) windowingStrategy); - - SumAndVerifyContextFn combineFn = new SumAndVerifyContextFn(mockView, expectedValue); - // Test basic execution of a trigger using a non-combining window set and discarding mode. - ReduceFnTester tester = ReduceFnTester.combining( - windowingStrategy, combineFn.asKeyedFn(), - VarIntCoder.of(), options, mockSideInputReader); - - injectElement(tester, 2); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 3); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 4); - - // This element shouldn't be seen, because the trigger has finished - injectElement(tester, 6); - - assertThat( - tester.extractOutput(), - contains( - isSingleWindowedValue(equalTo(5), 2, 0, 10), - isSingleWindowedValue(equalTo(4), 4, 0, 10))); - assertTrue(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); - } - - @Test - public void testWatermarkHoldAndLateData() throws Exception { - // Test handling of late data. Specifically, ensure the watermark hold is correct. - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(10), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // Input watermark -> null - assertEquals(null, tester.getWatermarkHold()); - assertEquals(null, tester.getOutputWatermark()); - - // All on time data, verify watermark hold. - injectElement(tester, 1); - injectElement(tester, 3); - assertEquals(new Instant(1), tester.getWatermarkHold()); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 2); - List>> output = tester.extractOutput(); - assertThat(output, contains( - isSingleWindowedValue(containsInAnyOrder(1, 2, 3), - 1, // timestamp - 0, // window start - 10))); // window end - assertThat(output.get(0).getPane(), - equalTo(PaneInfo.createPane(true, false, Timing.EARLY, 0, -1))); - - // Holding for the end-of-window transition. - assertEquals(new Instant(9), tester.getWatermarkHold()); - // Nothing dropped. - assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - - // Input watermark -> 4, output watermark should advance that far as well - tester.advanceInputWatermark(new Instant(4)); - assertEquals(new Instant(4), tester.getOutputWatermark()); - - // Some late, some on time. Verify that we only hold to the minimum of on-time. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - tester.advanceInputWatermark(new Instant(4)); - injectElement(tester, 2); - injectElement(tester, 3); - assertEquals(new Instant(9), tester.getWatermarkHold()); - injectElement(tester, 5); - assertEquals(new Instant(5), tester.getWatermarkHold()); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 4); - output = tester.extractOutput(); - assertThat(output, - contains( - isSingleWindowedValue(containsInAnyOrder( - 1, 2, 3, // earlier firing - 2, 3, 4, 5), // new elements - 4, // timestamp - 0, // window start - 10))); // window end - assertThat(output.get(0).getPane(), - equalTo(PaneInfo.createPane(false, false, Timing.EARLY, 1, -1))); - - // All late -- output at end of window timestamp. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - tester.advanceInputWatermark(new Instant(8)); - injectElement(tester, 6); - injectElement(tester, 5); - assertEquals(new Instant(9), tester.getWatermarkHold()); - injectElement(tester, 4); - - // Fire the ON_TIME pane - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - tester.advanceInputWatermark(new Instant(10)); - - // Output time is end of the window, because all the new data was late, but the pane - // is the ON_TIME pane. - output = tester.extractOutput(); - assertThat(output, - contains(isSingleWindowedValue( - containsInAnyOrder(1, 2, 3, // earlier firing - 2, 3, 4, 5, // earlier firing - 4, 5, 6), // new elements - 9, // timestamp - 0, // window start - 10))); // window end - assertThat(output.get(0).getPane(), - equalTo(PaneInfo.createPane(false, false, Timing.ON_TIME, 2, 0))); - - // This is "pending" at the time the watermark makes it way-late. - // Because we're about to expire the window, we output it. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - injectElement(tester, 8); - assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - - // Exceed the GC limit, triggering the last pane to be fired - tester.advanceInputWatermark(new Instant(50)); - output = tester.extractOutput(); - // Output time is still end of the window, because the new data (8) was behind - // the output watermark. - assertThat(output, - contains(isSingleWindowedValue( - containsInAnyOrder(1, 2, 3, // earlier firing - 2, 3, 4, 5, // earlier firing - 4, 5, 6, // earlier firing - 8), // new element prior to window becoming expired - 9, // timestamp - 0, // window start - 10))); // window end - assertThat( - output.get(0).getPane(), - equalTo(PaneInfo.createPane(false, true, Timing.LATE, 3, 1))); - assertEquals(new Instant(50), tester.getOutputWatermark()); - assertEquals(null, tester.getWatermarkHold()); - - // Late timers are ignored - tester.fireTimer(new IntervalWindow(new Instant(0), new Instant(10)), new Instant(12), - TimeDomain.EVENT_TIME); - - // And because we're past the end of window + allowed lateness, everything should be cleaned up. - assertFalse(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(); - } - - @Test - public void dontSetHoldIfTooLateForEndOfWindowTimer() throws Exception { - // Make sure holds are only set if they are accompanied by an end-of-window timer. - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(10), - ClosingBehavior.FIRE_ALWAYS); - tester.setAutoAdvanceOutputWatermark(false); - - // Case: Unobservably late - tester.advanceInputWatermark(new Instant(15)); - tester.advanceOutputWatermark(new Instant(11)); - injectElement(tester, 14); - // Hold was applied, waiting for end-of-window timer. - assertEquals(new Instant(14), tester.getWatermarkHold()); - assertEquals(new Instant(19), tester.getNextTimer(TimeDomain.EVENT_TIME)); - - // Trigger the end-of-window timer. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - tester.advanceInputWatermark(new Instant(20)); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - // Hold has been replaced with garbage collection hold. Waiting for garbage collection. - assertEquals(new Instant(29), tester.getWatermarkHold()); - assertEquals(new Instant(29), tester.getNextTimer(TimeDomain.EVENT_TIME)); - - // Case: Maybe late 1 - injectElement(tester, 13); - // No change to hold or timers. - assertEquals(new Instant(29), tester.getWatermarkHold()); - assertEquals(new Instant(29), tester.getNextTimer(TimeDomain.EVENT_TIME)); - - // Trigger the garbage collection timer. - tester.advanceInputWatermark(new Instant(30)); - - // Everything should be cleaned up. - assertFalse(tester.isMarkedFinished(new IntervalWindow(new Instant(10), new Instant(20)))); - tester.assertHasOnlyGlobalAndFinishedSetsFor(); - } - - @Test - public void testPaneInfoAllStates() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - tester.advanceInputWatermark(new Instant(0)); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 1); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, false, Timing.EARLY)))); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 2); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.EARLY, 1, -1)))); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - tester.advanceInputWatermark(new Instant(15)); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 3); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, false, Timing.ON_TIME, 2, 0)))); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - injectElement(tester, 4); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, false, Timing.LATE, 3, 1)))); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 5); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 4, 2)))); - } - - @Test - public void testPaneInfoAllStatesAfterWatermark() throws Exception { - ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withTrigger(Repeatedly.forever(AfterFirst.of( - AfterPane.elementCountAtLeast(2), - AfterWatermark.pastEndOfWindow()))) - .withMode(AccumulationMode.DISCARDING_FIRED_PANES) - .withAllowedLateness(Duration.millis(100)) - .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) - .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); - - tester.advanceInputWatermark(new Instant(0)); - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), TimestampedValue.of(2, new Instant(2))); - - List>> output = tester.extractOutput(); - assertThat( - output, - contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(true, false, Timing.EARLY, 0, -1)))); - assertThat( - output, - contains( - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10))); - - tester.advanceInputWatermark(new Instant(50)); - - // We should get the ON_TIME pane even though it is empty, - // because we have an AfterWatermark.pastEndOfWindow() trigger. - output = tester.extractOutput(); - assertThat( - output, - contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, false, Timing.ON_TIME, 1, 0)))); - assertThat( - output, - contains( - WindowMatchers.isSingleWindowedValue(emptyIterable(), 9, 0, 10))); - - // We should get the final pane even though it is empty. - tester.advanceInputWatermark(new Instant(150)); - output = tester.extractOutput(); - assertThat( - output, - contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 2, 1)))); - assertThat( - output, - contains( - WindowMatchers.isSingleWindowedValue(emptyIterable(), 9, 0, 10))); - } - - @Test - public void noEmptyPanesFinalIfNonEmpty() throws Exception { - ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withTrigger(Repeatedly.forever(AfterFirst.of( - AfterPane.elementCountAtLeast(2), - AfterWatermark.pastEndOfWindow()))) - .withMode(AccumulationMode.ACCUMULATING_FIRED_PANES) - .withAllowedLateness(Duration.millis(100)) - .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) - .withClosingBehavior(ClosingBehavior.FIRE_IF_NON_EMPTY)); - - tester.advanceInputWatermark(new Instant(0)); - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(2))); - tester.advanceInputWatermark(new Instant(20)); - tester.advanceInputWatermark(new Instant(250)); - - List>> output = tester.extractOutput(); - assertThat(output, contains( - // Trigger with 2 elements - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10), - // Trigger for the empty on time pane - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); - } - - @Test - public void noEmptyPanesFinalAlways() throws Exception { - ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withTrigger(Repeatedly.forever(AfterFirst.of( - AfterPane.elementCountAtLeast(2), - AfterWatermark.pastEndOfWindow()))) - .withMode(AccumulationMode.ACCUMULATING_FIRED_PANES) - .withAllowedLateness(Duration.millis(100)) - .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) - .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); - - tester.advanceInputWatermark(new Instant(0)); - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(2))); - tester.advanceInputWatermark(new Instant(20)); - tester.advanceInputWatermark(new Instant(250)); - - List>> output = tester.extractOutput(); - assertThat(output, contains( - // Trigger with 2 elements - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10), - // Trigger for the empty on time pane - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10), - // Trigger for the final pane - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); - } - - @Test - public void testPaneInfoAllStatesAfterWatermarkAccumulating() throws Exception { - ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withTrigger(Repeatedly.forever(AfterFirst.of( - AfterPane.elementCountAtLeast(2), - AfterWatermark.pastEndOfWindow()))) - .withMode(AccumulationMode.ACCUMULATING_FIRED_PANES) - .withAllowedLateness(Duration.millis(100)) - .withOutputTimeFn(OutputTimeFns.outputAtEarliestInputTimestamp()) - .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); - - tester.advanceInputWatermark(new Instant(0)); - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), TimestampedValue.of(2, new Instant(2))); - - List>> output = tester.extractOutput(); - assertThat( - output, - contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(true, false, Timing.EARLY, 0, -1)))); - assertThat( - output, - contains( - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10))); - - tester.advanceInputWatermark(new Instant(50)); - - // We should get the ON_TIME pane even though it is empty, - // because we have an AfterWatermark.pastEndOfWindow() trigger. - output = tester.extractOutput(); - assertThat( - output, - contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(false, false, Timing.ON_TIME, 1, 0)))); - assertThat( - output, - contains( - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); - - // We should get the final pane even though it is empty. - tester.advanceInputWatermark(new Instant(150)); - output = tester.extractOutput(); - assertThat( - output, - contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 2, 1)))); - assertThat( - output, - contains( - WindowMatchers.isSingleWindowedValue(containsInAnyOrder(1, 2), 9, 0, 10))); - } - - @Test - public void testPaneInfoFinalAndOnTime() throws Exception { - ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( - WindowingStrategy.of(FixedWindows.of(Duration.millis(10))) - .withTrigger( - Repeatedly.forever(AfterPane.elementCountAtLeast(2)) - .orFinally(AfterWatermark.pastEndOfWindow())) - .withMode(AccumulationMode.DISCARDING_FIRED_PANES) - .withAllowedLateness(Duration.millis(100)) - .withClosingBehavior(ClosingBehavior.FIRE_ALWAYS)); - - tester.advanceInputWatermark(new Instant(0)); - - // Should trigger due to element count - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), TimestampedValue.of(2, new Instant(2))); - - assertThat( - tester.extractOutput(), - contains(WindowMatchers.valueWithPaneInfo( - PaneInfo.createPane(true, false, Timing.EARLY, 0, -1)))); - - tester.advanceInputWatermark(new Instant(150)); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.ON_TIME, 1, 0)))); - } - - @Test - public void testPaneInfoSkipToFinish() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - tester.advanceInputWatermark(new Instant(0)); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 1); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, true, Timing.EARLY)))); - } - - @Test - public void testPaneInfoSkipToNonSpeculativeAndFinish() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - tester.advanceInputWatermark(new Instant(15)); - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 1); - assertThat(tester.extractOutput(), contains( - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, true, Timing.LATE)))); - } - - @Test - public void testMergeBeforeFinalizing() throws Exception { - // Verify that we merge windows before producing output so users don't see undesired - // unmerged windows. - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(0), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // All on time data, verify watermark hold. - // These two windows should pre-merge immediately to [1, 20) - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), // in [1, 11) - TimestampedValue.of(10, new Instant(10))); // in [10, 20) - - // And this should fire the end-of-window timer - tester.advanceInputWatermark(new Instant(100)); - - List>> output = tester.extractOutput(); - assertThat(output.size(), equalTo(1)); - assertThat(output.get(0), - isSingleWindowedValue(containsInAnyOrder(1, 10), - 1, // timestamp - 1, // window start - 20)); // window end - assertThat( - output.get(0).getPane(), - equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); - } - - /** - * It is possible for a session window's trigger to be closed at the point at which - * the (merged) session window is garbage collected. Make sure we don't accidentally - * assume the window is still active. - */ - @Test - public void testMergingWithCloseBeforeGC() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // Two elements in two overlapping session windows. - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), // in [1, 11) - TimestampedValue.of(10, new Instant(10))); // in [10, 20) - - // Close the trigger, but the gargbage collection timer is still pending. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - tester.advanceInputWatermark(new Instant(30)); - - // Now the garbage collection timer will fire, finding the trigger already closed. - tester.advanceInputWatermark(new Instant(100)); - - List>> output = tester.extractOutput(); - assertThat(output.size(), equalTo(1)); - assertThat(output.get(0), - isSingleWindowedValue(containsInAnyOrder(1, 10), - 1, // timestamp - 1, // window start - 20)); // window end - assertThat( - output.get(0).getPane(), - equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); - } - - /** - * Ensure a closed trigger has its state recorded in the merge result window. - */ - @Test - public void testMergingWithCloseTrigger() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // Create a new merged session window. - tester.injectElements(TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(2))); - - // Force the trigger to be closed for the merged window. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - tester.advanceInputWatermark(new Instant(13)); - - // Trigger is now closed. - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - - // Revisit the same session window. - tester.injectElements(TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(2))); - - // Trigger is still closed. - assertTrue(tester.isMarkedFinished(new IntervalWindow(new Instant(1), new Instant(12)))); - } - - /** - * If a later event tries to reuse an earlier session window which has been closed, we - * should reject that element and not fail due to the window no longer being active. - */ - @Test - public void testMergingWithReusedWindow() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // One elements in one session window. - tester.injectElements(TimestampedValue.of(1, new Instant(1))); // in [1, 11), gc at 21. - - // Close the trigger, but the gargbage collection timer is still pending. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - tester.advanceInputWatermark(new Instant(15)); - - // Another element in the same session window. - // Should be discarded with 'window closed'. - tester.injectElements(TimestampedValue.of(1, new Instant(1))); // in [1, 11), gc at 21. - - // And nothing should be left in the active window state. - assertTrue(tester.hasNoActiveWindows()); - - // Now the garbage collection timer will fire, finding the trigger already closed. - tester.advanceInputWatermark(new Instant(100)); - - List>> output = tester.extractOutput(); - assertThat(output.size(), equalTo(1)); - assertThat(output.get(0), - isSingleWindowedValue(containsInAnyOrder(1), - 1, // timestamp - 1, // window start - 11)); // window end - assertThat( - output.get(0).getPane(), - equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); - } - - /** - * When a merged window's trigger is closed we record that state using the merged window rather - * than the original windows. - */ - @Test - public void testMergingWithClosedRepresentative() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // 2 elements into merged session window. - // Close the trigger, but the garbage collection timer is still pending. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - tester.injectElements(TimestampedValue.of(1, new Instant(1)), // in [1, 11), gc at 21. - TimestampedValue.of(8, new Instant(8))); // in [8, 18), gc at 28. - - // More elements into the same merged session window. - // It has not yet been gced. - // Should be discarded with 'window closed'. - tester.injectElements(TimestampedValue.of(1, new Instant(1)), // in [1, 11), gc at 21. - TimestampedValue.of(2, new Instant(2)), // in [2, 12), gc at 22. - TimestampedValue.of(8, new Instant(8))); // in [8, 18), gc at 28. - - // Now the garbage collection timer will fire, finding the trigger already closed. - tester.advanceInputWatermark(new Instant(100)); - - List>> output = tester.extractOutput(); - - assertThat(output.size(), equalTo(1)); - assertThat(output.get(0), - isSingleWindowedValue(containsInAnyOrder(1, 8), - 1, // timestamp - 1, // window start - 18)); // window end - assertThat( - output.get(0).getPane(), - equalTo(PaneInfo.createPane(true, true, Timing.EARLY, 0, 0))); - } - - /** - * If an element for a closed session window ends up being merged into other still-open - * session windows, the resulting session window is not 'poisoned'. - */ - @Test - public void testMergingWithClosedDoesNotPoison() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(Sessions.withGapDuration(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(50), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // 1 element, force its trigger to close. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - tester.injectElements(TimestampedValue.of(2, new Instant(2))); - - // 3 elements, one already closed. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(false); - tester.injectElements(TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(2, new Instant(2)), - TimestampedValue.of(3, new Instant(3))); - - tester.advanceInputWatermark(new Instant(100)); - - List>> output = tester.extractOutput(); - assertThat(output.size(), equalTo(2)); - assertThat(output.get(0), - isSingleWindowedValue(containsInAnyOrder(2), - 2, // timestamp - 2, // window start - 12)); // window end - assertThat( - output.get(0).getPane(), - equalTo(PaneInfo.createPane(true, true, Timing.EARLY, 0, 0))); - assertThat(output.get(1), - isSingleWindowedValue(containsInAnyOrder(1, 2, 3), - 1, // timestamp - 1, // window start - 13)); // window end - assertThat( - output.get(1).getPane(), - equalTo(PaneInfo.createPane(true, true, Timing.ON_TIME, 0, 0))); - } - - /** - * Tests that when data is assigned to multiple windows but some of those windows have - * had their triggers finish, then the data is dropped and counted accurately. - */ - @Test - public void testDropDataMultipleWindowsFinishedTrigger() throws Exception { - ReduceFnTester tester = ReduceFnTester.combining( - WindowingStrategy.of( - SlidingWindows.of(Duration.millis(100)).every(Duration.millis(30))) - .withTrigger(AfterWatermark.pastEndOfWindow()) - .withAllowedLateness(Duration.millis(1000)), - new Sum.SumIntegerFn().asKeyedFn(), VarIntCoder.of()); - - tester.injectElements( - // assigned to [-60, 40), [-30, 70), [0, 100) - TimestampedValue.of(10, new Instant(23)), - // assigned to [-30, 70), [0, 100), [30, 130) - TimestampedValue.of(12, new Instant(40))); - - assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - - tester.advanceInputWatermark(new Instant(70)); - tester.injectElements( - // assigned to [-30, 70), [0, 100), [30, 130) - // but [-30, 70) is closed by the trigger - TimestampedValue.of(14, new Instant(60))); - - assertEquals(1, tester.getElementsDroppedDueToClosedWindow()); - - tester.advanceInputWatermark(new Instant(130)); - // assigned to [-30, 70), [0, 100), [30, 130) - // but they are all closed - tester.injectElements(TimestampedValue.of(16, new Instant(40))); - - assertEquals(4, tester.getElementsDroppedDueToClosedWindow()); - } - - @Test - public void testIdempotentEmptyPanesDiscarding() throws Exception { - // Test uninteresting (empty) panes don't increment the index or otherwise - // modify PaneInfo. - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.DISCARDING_FIRED_PANES, Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // Inject a couple of on-time elements and fire at the window end. - injectElement(tester, 1); - injectElement(tester, 2); - tester.advanceInputWatermark(new Instant(12)); - - // Fire the on-time pane - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); - - // Fire another timer (with no data, so it's an uninteresting pane that should not be output). - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); - - // Finish it off with another datum. - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 3); - - // The intermediate trigger firing shouldn't result in any output. - List>> output = tester.extractOutput(); - assertThat(output.size(), equalTo(2)); - - // The on-time pane is as expected. - assertThat(output.get(0), isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10)); - - // The late pane has the correct indices. - assertThat(output.get(1).getValue(), contains(3)); - assertThat( - output.get(1).getPane(), equalTo(PaneInfo.createPane(false, true, Timing.LATE, 1, 1))); - - assertTrue(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); - - assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - } - - @Test - public void testIdempotentEmptyPanesAccumulating() throws Exception { - // Test uninteresting (empty) panes don't increment the index or otherwise - // modify PaneInfo. - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining(FixedWindows.of(Duration.millis(10)), mockTrigger, - AccumulationMode.ACCUMULATING_FIRED_PANES, Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - // Inject a couple of on-time elements and fire at the window end. - injectElement(tester, 1); - injectElement(tester, 2); - tester.advanceInputWatermark(new Instant(12)); - - // Trigger the on-time pane - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); - List>> output = tester.extractOutput(); - assertThat(output.size(), equalTo(1)); - assertThat(output.get(0), isSingleWindowedValue(containsInAnyOrder(1, 2), 1, 0, 10)); - assertThat(output.get(0).getPane(), - equalTo(PaneInfo.createPane(true, false, Timing.ON_TIME, 0, 0))); - - // Fire another timer with no data; the empty pane should not be output even though the - // trigger is ready to fire - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - tester.fireTimer(firstWindow, new Instant(9), TimeDomain.EVENT_TIME); - assertThat(tester.extractOutput().size(), equalTo(0)); - - // Finish it off with another datum, which is late - when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); - triggerShouldFinish(mockTrigger); - injectElement(tester, 3); - output = tester.extractOutput(); - assertThat(output.size(), equalTo(1)); - - // The late pane has the correct indices. - assertThat(output.get(0).getValue(), containsInAnyOrder(1, 2, 3)); - assertThat(output.get(0).getPane(), - equalTo(PaneInfo.createPane(false, true, Timing.LATE, 1, 1))); - - assertTrue(tester.isMarkedFinished(firstWindow)); - tester.assertHasOnlyGlobalAndFinishedSetsFor(firstWindow); - - assertEquals(0, tester.getElementsDroppedDueToClosedWindow()); - } - - /** - * Test that we receive an empty on-time pane when an or-finally waiting for the watermark fires. - * Specifically, verify the proper triggerings and pane-info of a typical speculative/on-time/late - * when the on-time pane is empty. - */ - @Test - public void testEmptyOnTimeFromOrFinally() throws Exception { - ReduceFnTester tester = - ReduceFnTester.combining(FixedWindows.of(Duration.millis(10)), - AfterEach.inOrder( - Repeatedly - .forever( - AfterProcessingTime.pastFirstElementInPane().plusDelayOf( - new Duration(5))) - .orFinally(AfterWatermark.pastEndOfWindow()), - Repeatedly.forever( - AfterProcessingTime.pastFirstElementInPane().plusDelayOf( - new Duration(25)))), - AccumulationMode.ACCUMULATING_FIRED_PANES, new Sum.SumIntegerFn().asKeyedFn(), - VarIntCoder.of(), Duration.millis(100)); - - tester.advanceInputWatermark(new Instant(0)); - tester.advanceProcessingTime(new Instant(0)); - - // Processing time timer for 5 - tester.injectElements( - TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(1, new Instant(3)), - TimestampedValue.of(1, new Instant(7)), - TimestampedValue.of(1, new Instant(5))); - - // Should fire early pane - tester.advanceProcessingTime(new Instant(6)); - - // Should fire empty on time pane - tester.advanceInputWatermark(new Instant(11)); - List> output = tester.extractOutput(); - assertEquals(2, output.size()); - - assertThat(output.get(0), WindowMatchers.isSingleWindowedValue(4, 1, 0, 10)); - assertThat(output.get(1), WindowMatchers.isSingleWindowedValue(4, 9, 0, 10)); - - assertThat( - output.get(0), - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, false, Timing.EARLY, 0, -1))); - assertThat( - output.get(1), - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.ON_TIME, 1, 0))); - } - - /** - * Tests for processing time firings after the watermark passes the end of the window. - * Specifically, verify the proper triggerings and pane-info of a typical speculative/on-time/late - * when the on-time pane is non-empty. - */ - @Test - public void testProcessingTime() throws Exception { - ReduceFnTester tester = - ReduceFnTester.combining(FixedWindows.of(Duration.millis(10)), - AfterEach.inOrder( - Repeatedly - .forever( - AfterProcessingTime.pastFirstElementInPane().plusDelayOf( - new Duration(5))) - .orFinally(AfterWatermark.pastEndOfWindow()), - Repeatedly.forever( - AfterProcessingTime.pastFirstElementInPane().plusDelayOf( - new Duration(25)))), - AccumulationMode.ACCUMULATING_FIRED_PANES, new Sum.SumIntegerFn().asKeyedFn(), - VarIntCoder.of(), Duration.millis(100)); - - tester.advanceInputWatermark(new Instant(0)); - tester.advanceProcessingTime(new Instant(0)); - - tester.injectElements(TimestampedValue.of(1, new Instant(1)), - TimestampedValue.of(1, new Instant(3)), TimestampedValue.of(1, new Instant(7)), - TimestampedValue.of(1, new Instant(5))); - // 4 elements all at processing time 0 - - tester.advanceProcessingTime(new Instant(6)); // fire [1,3,7,5] since 6 > 0 + 5 - tester.injectElements( - TimestampedValue.of(1, new Instant(8)), - TimestampedValue.of(1, new Instant(4))); - // 6 elements - - tester.advanceInputWatermark(new Instant(11)); // fire [1,3,7,5,8,4] since 11 > 9 - tester.injectElements( - TimestampedValue.of(1, new Instant(8)), - TimestampedValue.of(1, new Instant(4)), - TimestampedValue.of(1, new Instant(5))); - // 9 elements - - tester.advanceInputWatermark(new Instant(12)); - tester.injectElements( - TimestampedValue.of(1, new Instant(3))); - // 10 elements - - tester.advanceProcessingTime(new Instant(15)); - tester.injectElements( - TimestampedValue.of(1, new Instant(5))); - // 11 elements - tester.advanceProcessingTime(new Instant(32)); // fire since 32 > 6 + 25 - - tester.injectElements( - TimestampedValue.of(1, new Instant(3))); - // 12 elements - // fire [1,3,7,5,8,4,8,4,5,3,5,3] since 125 > 6 + 25 - tester.advanceInputWatermark(new Instant(125)); - - List> output = tester.extractOutput(); - assertEquals(4, output.size()); - - assertThat(output.get(0), WindowMatchers.isSingleWindowedValue(4, 1, 0, 10)); - assertThat(output.get(1), WindowMatchers.isSingleWindowedValue(6, 4, 0, 10)); - assertThat(output.get(2), WindowMatchers.isSingleWindowedValue(11, 9, 0, 10)); - assertThat(output.get(3), WindowMatchers.isSingleWindowedValue(12, 9, 0, 10)); - - assertThat( - output.get(0), - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(true, false, Timing.EARLY, 0, -1))); - assertThat( - output.get(1), - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.ON_TIME, 1, 0))); - assertThat( - output.get(2), - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, false, Timing.LATE, 2, 1))); - assertThat( - output.get(3), - WindowMatchers.valueWithPaneInfo(PaneInfo.createPane(false, true, Timing.LATE, 3, 2))); - } - - /** - * We should fire a non-empty ON_TIME pane in the GlobalWindow when the watermark moves to - * end-of-time. - */ - @Test - public void fireNonEmptyOnDrainInGlobalWindow() throws Exception { - ReduceFnTester, GlobalWindow> tester = - ReduceFnTester.nonCombining( - WindowingStrategy.of(new GlobalWindows()) - .withTrigger(Repeatedly.forever( - AfterPane.elementCountAtLeast(3))) - .withMode(AccumulationMode.DISCARDING_FIRED_PANES)); - - tester.advanceInputWatermark(new Instant(0)); - - final int n = 20; - for (int i = 0; i < n; i++) { - tester.injectElements(TimestampedValue.of(i, new Instant(i))); - } - - List>> output = tester.extractOutput(); - assertEquals(n / 3, output.size()); - for (int i = 0; i < output.size(); i++) { - assertEquals(Timing.EARLY, output.get(i).getPane().getTiming()); - assertEquals(i, output.get(i).getPane().getIndex()); - assertEquals(3, Iterables.size(output.get(i).getValue())); - } - - tester.advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE); - - output = tester.extractOutput(); - assertEquals(1, output.size()); - assertEquals(Timing.ON_TIME, output.get(0).getPane().getTiming()); - assertEquals(n / 3, output.get(0).getPane().getIndex()); - assertEquals(n - ((n / 3) * 3), Iterables.size(output.get(0).getValue())); - } - - /** - * We should fire an empty ON_TIME pane in the GlobalWindow when the watermark moves to - * end-of-time. - */ - @Test - public void fireEmptyOnDrainInGlobalWindowIfRequested() throws Exception { - ReduceFnTester, GlobalWindow> tester = - ReduceFnTester.nonCombining( - WindowingStrategy.of(new GlobalWindows()) - .withTrigger(Repeatedly.forever( - AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(new Duration(3)))) - .withMode(AccumulationMode.DISCARDING_FIRED_PANES)); - - final int n = 20; - for (int i = 0; i < n; i++) { - tester.advanceProcessingTime(new Instant(i)); - tester.injectElements(TimestampedValue.of(i, new Instant(i))); - } - tester.advanceProcessingTime(new Instant(n + 4)); - List>> output = tester.extractOutput(); - assertEquals((n + 3) / 4, output.size()); - for (int i = 0; i < output.size(); i++) { - assertEquals(Timing.EARLY, output.get(i).getPane().getTiming()); - assertEquals(i, output.get(i).getPane().getIndex()); - assertEquals(4, Iterables.size(output.get(i).getValue())); - } - - tester.advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE); - - output = tester.extractOutput(); - assertEquals(1, output.size()); - assertEquals(Timing.ON_TIME, output.get(0).getPane().getTiming()); - assertEquals((n + 3) / 4, output.get(0).getPane().getIndex()); - assertEquals(0, Iterables.size(output.get(0).getValue())); - } - - /** - * Late elements should still have a garbage collection hold set so that they - * can make a late pane rather than be dropped due to lateness. - */ - @Test - public void setGarbageCollectionHoldOnLateElements() throws Exception { - ReduceFnTester, IntervalWindow> tester = - ReduceFnTester.nonCombining( - FixedWindows.of(Duration.millis(10)), - AfterWatermark.pastEndOfWindow() - .withLateFirings(AfterPane.elementCountAtLeast(2)), - AccumulationMode.DISCARDING_FIRED_PANES, - Duration.millis(100), - ClosingBehavior.FIRE_IF_NON_EMPTY); - - tester.advanceInputWatermark(new Instant(0)); - tester.advanceOutputWatermark(new Instant(0)); - tester.injectElements(TimestampedValue.of(1, new Instant(1))); - - // Fire ON_TIME pane @ 9 with 1 - - tester.advanceInputWatermark(new Instant(109)); - tester.advanceOutputWatermark(new Instant(109)); - tester.injectElements(TimestampedValue.of(2, new Instant(2))); - // We should have set a garbage collection hold for the final pane. - Instant hold = tester.getWatermarkHold(); - assertEquals(new Instant(109), hold); - - tester.advanceInputWatermark(new Instant(110)); - tester.advanceOutputWatermark(new Instant(110)); - - // Fire final LATE pane @ 9 with 2 - - List>> output = tester.extractOutput(); - assertEquals(2, output.size()); - } - - private static class SumAndVerifyContextFn extends CombineFnWithContext { - - private final PCollectionView view; - private final int expectedValue; - - private SumAndVerifyContextFn(PCollectionView view, int expectedValue) { - this.view = view; - this.expectedValue = expectedValue; - } - @Override - public int[] createAccumulator(Context c) { - checkArgument(c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); - checkArgument(c.sideInput(view) == expectedValue); - return wrap(0); - } - - @Override - public int[] addInput(int[] accumulator, Integer input, Context c) { - checkArgument( - c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); - checkArgument(c.sideInput(view) == expectedValue); - accumulator[0] += input.intValue(); - return accumulator; - } - - @Override - public int[] mergeAccumulators(Iterable accumulators, Context c) { - checkArgument( - c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); - checkArgument(c.sideInput(view) == expectedValue); - Iterator iter = accumulators.iterator(); - if (!iter.hasNext()) { - return createAccumulator(c); - } else { - int[] running = iter.next(); - while (iter.hasNext()) { - running[0] += iter.next()[0]; - } - return running; - } - } - - @Override - public Integer extractOutput(int[] accumulator, Context c) { - checkArgument( - c.getPipelineOptions().as(TestOptions.class).getValue() == expectedValue); - checkArgument(c.sideInput(view) == expectedValue); - return accumulator[0]; - } - - private int[] wrap(int value) { - return new int[] { value }; - } - } - - /** - * A {@link PipelineOptions} to test combining with context. - */ - public interface TestOptions extends PipelineOptions { - Integer getValue(); - void setValue(Integer value); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java deleted file mode 100644 index f206a4cfb9..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReduceFnTester.java +++ /dev/null @@ -1,781 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.CombineWithContext.KeyedCombineFnWithContext; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.TriggerBuilder; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window.ClosingBehavior; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.PriorityQueue; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * Test utility that runs a {@link ReduceFn}, {@link WindowFn}, {@link Trigger} using in-memory stub - * implementations to provide the {@link TimerInternals} and {@link WindowingInternals} needed to - * run {@code Trigger}s and {@code ReduceFn}s. - * - * @param The element types. - * @param The final type for elements in the window (for instance, - * {@code Iterable}) - * @param The type of windows being used. - */ -public class ReduceFnTester { - private static final String KEY = "TEST_KEY"; - - private final TestInMemoryStateInternals stateInternals = - new TestInMemoryStateInternals<>(KEY); - private final TestTimerInternals timerInternals = new TestTimerInternals(); - - private final WindowFn windowFn; - private final TestWindowingInternals windowingInternals; - private final Coder outputCoder; - private final WindowingStrategy objectStrategy; - private final ReduceFn reduceFn; - private final PipelineOptions options; - - /** - * If true, the output watermark is automatically advanced to the latest possible - * point when the input watermark is advanced. This is the default for most tests. - * If false, the output watermark must be explicitly advanced by the test, which can - * be used to exercise some of the more subtle behavior of WatermarkHold. - */ - private boolean autoAdvanceOutputWatermark; - - private ExecutableTrigger executableTrigger; - - private final InMemoryLongSumAggregator droppedDueToClosedWindow = - new InMemoryLongSumAggregator(GroupAlsoByWindowsDoFn.DROPPED_DUE_TO_CLOSED_WINDOW_COUNTER); - - public static ReduceFnTester, W> - nonCombining(WindowingStrategy windowingStrategy) throws Exception { - return new ReduceFnTester, W>( - windowingStrategy, - SystemReduceFn.buffering(VarIntCoder.of()), - IterableCoder.of(VarIntCoder.of()), - PipelineOptionsFactory.create(), - NullSideInputReader.empty()); - } - - public static ReduceFnTester, W> - nonCombining(WindowFn windowFn, TriggerBuilder trigger, AccumulationMode mode, - Duration allowedDataLateness, ClosingBehavior closingBehavior) throws Exception { - WindowingStrategy strategy = - WindowingStrategy.of(windowFn) - .withTrigger(trigger.buildTrigger()) - .withMode(mode) - .withAllowedLateness(allowedDataLateness) - .withClosingBehavior(closingBehavior); - return nonCombining(strategy); - } - - public static ReduceFnTester - combining(WindowingStrategy strategy, - KeyedCombineFn combineFn, - Coder outputCoder) throws Exception { - - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - AppliedCombineFn fn = - AppliedCombineFn.withInputCoder( - combineFn, registry, KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())); - - return new ReduceFnTester( - strategy, - SystemReduceFn.combining(StringUtf8Coder.of(), fn), - outputCoder, - PipelineOptionsFactory.create(), - NullSideInputReader.empty()); - } - - public static ReduceFnTester - combining(WindowingStrategy strategy, - KeyedCombineFnWithContext combineFn, - Coder outputCoder, - PipelineOptions options, - SideInputReader sideInputReader) throws Exception { - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - AppliedCombineFn fn = - AppliedCombineFn.withInputCoder( - combineFn, registry, KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())); - - return new ReduceFnTester( - strategy, - SystemReduceFn.combining(StringUtf8Coder.of(), fn), - outputCoder, - options, - sideInputReader); - } - public static ReduceFnTester - combining(WindowFn windowFn, Trigger trigger, AccumulationMode mode, - KeyedCombineFn combineFn, Coder outputCoder, - Duration allowedDataLateness) throws Exception { - - WindowingStrategy strategy = - WindowingStrategy.of(windowFn).withTrigger(trigger).withMode(mode).withAllowedLateness( - allowedDataLateness); - - return combining(strategy, combineFn, outputCoder); - } - - private ReduceFnTester(WindowingStrategy wildcardStrategy, - ReduceFn reduceFn, Coder outputCoder, - PipelineOptions options, SideInputReader sideInputReader) throws Exception { - @SuppressWarnings("unchecked") - WindowingStrategy objectStrategy = (WindowingStrategy) wildcardStrategy; - - this.objectStrategy = objectStrategy; - this.reduceFn = reduceFn; - this.windowFn = objectStrategy.getWindowFn(); - this.windowingInternals = new TestWindowingInternals(sideInputReader); - this.outputCoder = outputCoder; - this.autoAdvanceOutputWatermark = true; - this.executableTrigger = wildcardStrategy.getTrigger(); - this.options = options; - } - - public void setAutoAdvanceOutputWatermark(boolean autoAdvanceOutputWatermark) { - this.autoAdvanceOutputWatermark = autoAdvanceOutputWatermark; - } - - @Nullable - public Instant getNextTimer(TimeDomain domain) { - return timerInternals.getNextTimer(domain); - } - - ReduceFnRunner createRunner() { - return new ReduceFnRunner<>( - KEY, - objectStrategy, - stateInternals, - timerInternals, - windowingInternals, - droppedDueToClosedWindow, - reduceFn, - options); - } - - public ExecutableTrigger getTrigger() { - return executableTrigger; - } - - public boolean isMarkedFinished(W window) { - return createRunner().isFinished(window); - } - - public boolean hasNoActiveWindows() { - return createRunner().hasNoActiveWindows(); - } - - @SafeVarargs - public final void assertHasOnlyGlobalAndFinishedSetsFor(W... expectedWindows) { - assertHasOnlyGlobalAndAllowedTags( - ImmutableSet.copyOf(expectedWindows), - ImmutableSet.>of(TriggerRunner.FINISHED_BITS_TAG)); - } - - @SafeVarargs - public final void assertHasOnlyGlobalAndFinishedSetsAndPaneInfoFor(W... expectedWindows) { - assertHasOnlyGlobalAndAllowedTags( - ImmutableSet.copyOf(expectedWindows), - ImmutableSet.>of( - TriggerRunner.FINISHED_BITS_TAG, PaneInfoTracker.PANE_INFO_TAG, - WatermarkHold.watermarkHoldTagForOutputTimeFn(objectStrategy.getOutputTimeFn()), - WatermarkHold.EXTRA_HOLD_TAG)); - } - - public final void assertHasOnlyGlobalState() { - assertHasOnlyGlobalAndAllowedTags( - Collections.emptySet(), Collections.>emptySet()); - } - - @SafeVarargs - public final void assertHasOnlyGlobalAndPaneInfoFor(W... expectedWindows) { - assertHasOnlyGlobalAndAllowedTags( - ImmutableSet.copyOf(expectedWindows), - ImmutableSet.>of( - PaneInfoTracker.PANE_INFO_TAG, - WatermarkHold.watermarkHoldTagForOutputTimeFn(objectStrategy.getOutputTimeFn()), - WatermarkHold.EXTRA_HOLD_TAG)); - } - - /** - * Verifies that the the set of windows that have any state stored is exactly - * {@code expectedWindows} and that each of these windows has only tags from {@code allowedTags}. - */ - private void assertHasOnlyGlobalAndAllowedTags( - Set expectedWindows, Set> allowedTags) { - Set expectedWindowsSet = new HashSet<>(); - for (W expectedWindow : expectedWindows) { - expectedWindowsSet.add(windowNamespace(expectedWindow)); - } - Map>> actualWindows = new HashMap<>(); - - for (StateNamespace namespace : stateInternals.getNamespacesInUse()) { - if (namespace instanceof StateNamespaces.GlobalNamespace) { - continue; - } else if (namespace instanceof StateNamespaces.WindowNamespace) { - Set> tagsInUse = stateInternals.getTagsInUse(namespace); - if (tagsInUse.isEmpty()) { - continue; - } - actualWindows.put(namespace, tagsInUse); - Set> unexpected = Sets.difference(tagsInUse, allowedTags); - if (unexpected.isEmpty()) { - continue; - } else { - fail(namespace + " has unexpected states: " + tagsInUse); - } - } else if (namespace instanceof StateNamespaces.WindowAndTriggerNamespace) { - Set> tagsInUse = stateInternals.getTagsInUse(namespace); - assertTrue(namespace + " contains " + tagsInUse, tagsInUse.isEmpty()); - } else { - fail("Unrecognized namespace " + namespace); - } - } - - assertEquals("Still in use: " + actualWindows.toString(), expectedWindowsSet, - actualWindows.keySet()); - } - - private StateNamespace windowNamespace(W window) { - return StateNamespaces.window(windowFn.windowCoder(), window); - } - - public Instant getWatermarkHold() { - return stateInternals.earliestWatermarkHold(); - } - - public Instant getOutputWatermark() { - return timerInternals.currentOutputWatermarkTime(); - } - - public long getElementsDroppedDueToClosedWindow() { - return droppedDueToClosedWindow.getSum(); - } - - /** - * How many panes do we have in the output? - */ - public int getOutputSize() { - return windowingInternals.outputs.size(); - } - - /** - * Retrieve the values that have been output to this time, and clear out the output accumulator. - */ - public List> extractOutput() { - ImmutableList> result = - FluentIterable.from(windowingInternals.outputs) - .transform(new Function>, WindowedValue>() { - @Override - public WindowedValue apply(WindowedValue> input) { - return input.withValue(input.getValue().getValue()); - } - }) - .toList(); - windowingInternals.outputs.clear(); - return result; - } - - /** - * Advance the input watermark to the specified time, firing any timers that should - * fire. Then advance the output watermark as far as possible. - */ - public void advanceInputWatermark(Instant newInputWatermark) throws Exception { - ReduceFnRunner runner = createRunner(); - timerInternals.advanceInputWatermark(runner, newInputWatermark); - runner.persist(); - } - - /** - * If {@link #autoAdvanceOutputWatermark} is {@literal false}, advance the output watermark - * to the given value. Otherwise throw. - */ - public void advanceOutputWatermark(Instant newOutputWatermark) throws Exception { - timerInternals.advanceOutputWatermark(newOutputWatermark); - } - - /** Advance the processing time to the specified time, firing any timers that should fire. */ - public void advanceProcessingTime(Instant newProcessingTime) throws Exception { - ReduceFnRunner runner = createRunner(); - timerInternals.advanceProcessingTime(runner, newProcessingTime); - runner.persist(); - } - - /** - * Advance the synchronized processing time to the specified time, - * firing any timers that should fire. - */ - public void advanceSynchronizedProcessingTime(Instant newProcessingTime) throws Exception { - ReduceFnRunner runner = createRunner(); - timerInternals.advanceSynchronizedProcessingTime(runner, newProcessingTime); - runner.persist(); - } - - /** - * Inject all the timestamped values (after passing through the window function) as if they - * arrived in a single chunk of a bundle (or work-unit). - */ - @SafeVarargs - public final void injectElements(TimestampedValue... values) throws Exception { - for (TimestampedValue value : values) { - WindowTracing.trace("TriggerTester.injectElements: {}", value); - } - ReduceFnRunner runner = createRunner(); - runner.processElements(Iterables.transform( - Arrays.asList(values), new Function, WindowedValue>() { - @Override - public WindowedValue apply(TimestampedValue input) { - try { - InputT value = input.getValue(); - Instant timestamp = input.getTimestamp(); - Collection windows = windowFn.assignWindows(new TestAssignContext( - windowFn, value, timestamp, Arrays.asList(GlobalWindow.INSTANCE))); - return WindowedValue.of(value, timestamp, windows, PaneInfo.NO_FIRING); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - })); - - // Persist after each bundle. - runner.persist(); - } - - public void fireTimer(W window, Instant timestamp, TimeDomain domain) throws Exception { - ReduceFnRunner runner = createRunner(); - ArrayList timers = new ArrayList(1); - timers.add( - TimerData.of(StateNamespaces.window(windowFn.windowCoder(), window), timestamp, domain)); - runner.onTimers(timers); - runner.persist(); - } - - /** - * Simulate state. - */ - private static class TestInMemoryStateInternals extends InMemoryStateInternals { - - public TestInMemoryStateInternals(K key) { - super(key); - } - - public Set> getTagsInUse(StateNamespace namespace) { - Set> inUse = new HashSet<>(); - for (Entry, State> entry : - inMemoryState.getTagsInUse(namespace).entrySet()) { - if (!isEmptyForTesting(entry.getValue())) { - inUse.add(entry.getKey()); - } - } - return inUse; - } - - public Set getNamespacesInUse() { - return inMemoryState.getNamespacesInUse(); - } - - /** Return the earliest output watermark hold in state, or null if none. */ - public Instant earliestWatermarkHold() { - Instant minimum = null; - for (State storage : inMemoryState.values()) { - if (storage instanceof WatermarkHoldState) { - Instant hold = ((WatermarkHoldState) storage).read(); - if (minimum == null || (hold != null && hold.isBefore(minimum))) { - minimum = hold; - } - } - } - return minimum; - } - } - - /** - * Convey the simulated state and implement {@link #outputWindowedValue} to capture all output - * elements. - */ - private class TestWindowingInternals implements WindowingInternals> { - private List>> outputs = new ArrayList<>(); - private SideInputReader sideInputReader; - - private TestWindowingInternals(SideInputReader sideInputReader) { - this.sideInputReader = sideInputReader; - } - - @Override - public void outputWindowedValue(KV output, Instant timestamp, - Collection windows, PaneInfo pane) { - // Copy the output value (using coders) before capturing it. - KV copy = SerializableUtils.>ensureSerializableByCoder( - KvCoder.of(StringUtf8Coder.of(), outputCoder), output, "outputForWindow"); - WindowedValue> value = WindowedValue.of(copy, timestamp, windows, pane); - outputs.add(value); - } - - @Override - public TimerInternals timerInternals() { - throw new UnsupportedOperationException( - "Testing triggers should not use timers from WindowingInternals."); - } - - @Override - public Collection windows() { - throw new UnsupportedOperationException( - "Testing triggers should not use windows from WindowingInternals."); - } - - @Override - public PaneInfo pane() { - throw new UnsupportedOperationException( - "Testing triggers should not use pane from WindowingInternals."); - } - - @Override - public void writePCollectionViewData( - TupleTag tag, Iterable> data, Coder elemCoder) throws IOException { - throw new UnsupportedOperationException( - "Testing triggers should not use writePCollectionViewData from WindowingInternals."); - } - - @Override - public StateInternals stateInternals() { - // Safe for testing only - @SuppressWarnings({"unchecked", "rawtypes"}) - TestInMemoryStateInternals untypedStateInternals = - (TestInMemoryStateInternals) stateInternals; - return untypedStateInternals; - } - - @Override - public T sideInput(PCollectionView view, BoundedWindow mainInputWindow) { - if (!sideInputReader.contains(view)) { - throw new IllegalArgumentException("calling sideInput() with unknown view"); - } - BoundedWindow sideInputWindow = - view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(mainInputWindow); - return sideInputReader.get(view, sideInputWindow); - } - } - - private static class TestAssignContext - extends WindowFn.AssignContext { - private Object element; - private Instant timestamp; - private Collection windows; - - public TestAssignContext(WindowFn windowFn, Object element, Instant timestamp, - Collection windows) { - windowFn.super(); - this.element = element; - this.timestamp = timestamp; - this.windows = windows; - } - - @Override - public Object element() { - return element; - } - - @Override - public Instant timestamp() { - return timestamp; - } - - @Override - public Collection windows() { - return windows; - } - } - - private static class InMemoryLongSumAggregator implements Aggregator { - private final String name; - private long sum = 0; - - public InMemoryLongSumAggregator(String name) { - this.name = name; - } - - @Override - public void addValue(Long value) { - sum += value; - } - - @Override - public String getName() { - return name; - } - - @Override - public CombineFn getCombineFn() { - return new Sum.SumLongFn(); - } - - public long getSum() { - return sum; - } - } - - /** - * Simulate the firing of timers and progression of input and output watermarks for a - * single computation and key in a Windmill-like streaming environment. Similar to - * {@link BatchTimerInternals}, but also tracks the output watermark. - */ - private class TestTimerInternals implements TimerInternals { - /** At most one timer per timestamp is kept. */ - private Set existingTimers = new HashSet<>(); - - /** Pending input watermark timers, in timestamp order. */ - private PriorityQueue watermarkTimers = new PriorityQueue<>(11); - - /** Pending processing time timers, in timestamp order. */ - private PriorityQueue processingTimers = new PriorityQueue<>(11); - - /** Current input watermark. */ - @Nullable - private Instant inputWatermarkTime = BoundedWindow.TIMESTAMP_MIN_VALUE; - - /** Current output watermark. */ - @Nullable - private Instant outputWatermarkTime = null; - - /** Current processing time. */ - private Instant processingTime = BoundedWindow.TIMESTAMP_MIN_VALUE; - - /** Current synchronized processing time. */ - @Nullable - private Instant synchronizedProcessingTime = null; - - @Nullable - public Instant getNextTimer(TimeDomain domain) { - TimerData data = null; - switch (domain) { - case EVENT_TIME: - data = watermarkTimers.peek(); - break; - case PROCESSING_TIME: - case SYNCHRONIZED_PROCESSING_TIME: - data = processingTimers.peek(); - break; - } - checkNotNull(data); // cases exhaustive - return data == null ? null : data.getTimestamp(); - } - - private PriorityQueue queue(TimeDomain domain) { - switch (domain) { - case EVENT_TIME: - return watermarkTimers; - case PROCESSING_TIME: - case SYNCHRONIZED_PROCESSING_TIME: - return processingTimers; - } - throw new RuntimeException(); // cases exhaustive - } - - @Override - public void setTimer(TimerData timer) { - WindowTracing.trace("TestTimerInternals.setTimer: {}", timer); - if (existingTimers.add(timer)) { - queue(timer.getDomain()).add(timer); - } - } - - @Override - public void deleteTimer(TimerData timer) { - WindowTracing.trace("TestTimerInternals.deleteTimer: {}", timer); - existingTimers.remove(timer); - queue(timer.getDomain()).remove(timer); - } - - @Override - public Instant currentProcessingTime() { - return processingTime; - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return synchronizedProcessingTime; - } - - @Override - public Instant currentInputWatermarkTime() { - return checkNotNull(inputWatermarkTime); - } - - @Override - @Nullable - public Instant currentOutputWatermarkTime() { - return outputWatermarkTime; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("watermarkTimers", watermarkTimers) - .add("processingTimers", processingTimers) - .add("inputWatermarkTime", inputWatermarkTime) - .add("outputWatermarkTime", outputWatermarkTime) - .add("processingTime", processingTime) - .toString(); - } - - public void advanceInputWatermark( - ReduceFnRunner runner, Instant newInputWatermark) throws Exception { - checkNotNull(newInputWatermark); - checkState( - !newInputWatermark.isBefore(inputWatermarkTime), - "Cannot move input watermark time backwards from %s to %s", inputWatermarkTime, - newInputWatermark); - WindowTracing.trace("TestTimerInternals.advanceInputWatermark: from {} to {}", - inputWatermarkTime, newInputWatermark); - inputWatermarkTime = newInputWatermark; - advanceAndFire(runner, newInputWatermark, TimeDomain.EVENT_TIME); - - Instant hold = stateInternals.earliestWatermarkHold(); - if (hold == null) { - WindowTracing.trace("TestTimerInternals.advanceInputWatermark: no holds, " - + "so output watermark = input watermark"); - hold = inputWatermarkTime; - } - if (autoAdvanceOutputWatermark) { - advanceOutputWatermark(hold); - } - } - - public void advanceOutputWatermark(Instant newOutputWatermark) { - checkNotNull(newOutputWatermark); - if (newOutputWatermark.isAfter(inputWatermarkTime)) { - WindowTracing.trace( - "TestTimerInternals.advanceOutputWatermark: clipping output watermark from {} to {}", - newOutputWatermark, inputWatermarkTime); - newOutputWatermark = inputWatermarkTime; - } - checkState( - outputWatermarkTime == null || !newOutputWatermark.isBefore(outputWatermarkTime), - "Cannot move output watermark time backwards from %s to %s", outputWatermarkTime, - newOutputWatermark); - WindowTracing.trace("TestTimerInternals.advanceOutputWatermark: from {} to {}", - outputWatermarkTime, newOutputWatermark); - outputWatermarkTime = newOutputWatermark; - } - - public void advanceProcessingTime( - ReduceFnRunner runner, Instant newProcessingTime) throws Exception { - checkState(!newProcessingTime.isBefore(processingTime), - "Cannot move processing time backwards from %s to %s", processingTime, newProcessingTime); - WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", processingTime, - newProcessingTime); - processingTime = newProcessingTime; - advanceAndFire(runner, newProcessingTime, TimeDomain.PROCESSING_TIME); - } - - public void advanceSynchronizedProcessingTime( - ReduceFnRunner runner, Instant newSynchronizedProcessingTime) throws Exception { - checkState(!newSynchronizedProcessingTime.isBefore(synchronizedProcessingTime), - "Cannot move processing time backwards from %s to %s", processingTime, - newSynchronizedProcessingTime); - WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", - synchronizedProcessingTime, newSynchronizedProcessingTime); - synchronizedProcessingTime = newSynchronizedProcessingTime; - advanceAndFire( - runner, newSynchronizedProcessingTime, TimeDomain.SYNCHRONIZED_PROCESSING_TIME); - } - - private void advanceAndFire( - ReduceFnRunner runner, Instant currentTime, TimeDomain domain) - throws Exception { - PriorityQueue queue = queue(domain); - boolean shouldFire = false; - - while (true) { - ArrayList firedTimers = new ArrayList(); - while (!queue.isEmpty() && currentTime.isAfter(queue.peek().getTimestamp())) { - // Remove before firing, so that if the callback adds another identical - // timer we don't remove it. - TimerData timer = queue.remove(); - existingTimers.remove(timer); - firedTimers.add(timer); - } - if (firedTimers.isEmpty()) { - break; - } - runner.onTimers(firedTimers); - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTest.java deleted file mode 100644 index c2a4fc40fc..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTest.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.collect.ImmutableList; - -import org.joda.time.Duration; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** - * Tests for {@link Reshuffle}. - */ -@RunWith(JUnit4.class) -public class ReshuffleTest { - - private static final List> ARBITRARY_KVS = ImmutableList.of( - KV.of("k1", 3), - KV.of("k5", Integer.MAX_VALUE), - KV.of("k5", Integer.MIN_VALUE), - KV.of("k2", 66), - KV.of("k1", 4), - KV.of("k2", -33), - KV.of("k3", 0)); - - // TODO: test with more than one value per key - private static final List> GBK_TESTABLE_KVS = ImmutableList.of( - KV.of("k1", 3), - KV.of("k2", 4)); - - private static final List>> GROUPED_TESTABLE_KVS = ImmutableList.of( - KV.of("k1", (Iterable) ImmutableList.of(3)), - KV.of("k2", (Iterable) ImmutableList.of(4))); - - @Test - @Category(RunnableOnService.class) - public void testJustReshuffle() { - Pipeline pipeline = TestPipeline.create(); - - PCollection> input = pipeline - .apply(Create.of(ARBITRARY_KVS) - .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))); - - PCollection> output = input - .apply(Reshuffle.of()); - - DataflowAssert.that(output).containsInAnyOrder(ARBITRARY_KVS); - - assertEquals( - input.getWindowingStrategy(), - output.getWindowingStrategy()); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testReshuffleAfterSessionsAndGroupByKey() { - Pipeline pipeline = TestPipeline.create(); - - PCollection>> input = pipeline - .apply(Create.of(GBK_TESTABLE_KVS) - .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) - .apply(Window.>into( - Sessions.withGapDuration(Duration.standardMinutes(10)))) - .apply(GroupByKey.create()); - - PCollection>> output = input - .apply(Reshuffle.>of()); - - DataflowAssert.that(output).containsInAnyOrder(GROUPED_TESTABLE_KVS); - - assertEquals( - input.getWindowingStrategy(), - output.getWindowingStrategy()); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testReshuffleAfterFixedWindowsAndGroupByKey() { - Pipeline pipeline = TestPipeline.create(); - - PCollection>> input = pipeline - .apply(Create.of(GBK_TESTABLE_KVS) - .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) - .apply(Window.>into( - FixedWindows.of(Duration.standardMinutes(10L)))) - .apply(GroupByKey.create()); - - PCollection>> output = input - .apply(Reshuffle.>of()); - - DataflowAssert.that(output).containsInAnyOrder(GROUPED_TESTABLE_KVS); - - assertEquals( - input.getWindowingStrategy(), - output.getWindowingStrategy()); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testReshuffleAfterSlidingWindowsAndGroupByKey() { - Pipeline pipeline = TestPipeline.create(); - - PCollection>> input = pipeline - .apply(Create.of(GBK_TESTABLE_KVS) - .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) - .apply(Window.>into( - FixedWindows.of(Duration.standardMinutes(10L)))) - .apply(GroupByKey.create()); - - PCollection>> output = input - .apply(Reshuffle.>of()); - - DataflowAssert.that(output).containsInAnyOrder(GROUPED_TESTABLE_KVS); - - assertEquals( - input.getWindowingStrategy(), - output.getWindowingStrategy()); - - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testReshuffleAfterFixedWindows() { - Pipeline pipeline = TestPipeline.create(); - - PCollection> input = pipeline - .apply(Create.of(ARBITRARY_KVS) - .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) - .apply(Window.>into( - FixedWindows.of(Duration.standardMinutes(10L)))); - - PCollection> output = input - .apply(Reshuffle.of()); - - DataflowAssert.that(output).containsInAnyOrder(ARBITRARY_KVS); - - assertEquals( - input.getWindowingStrategy(), - output.getWindowingStrategy()); - - pipeline.run(); - } - - - @Test - @Category(RunnableOnService.class) - public void testReshuffleAfterSlidingWindows() { - Pipeline pipeline = TestPipeline.create(); - - PCollection> input = pipeline - .apply(Create.of(ARBITRARY_KVS) - .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) - .apply(Window.>into( - FixedWindows.of(Duration.standardMinutes(10L)))); - - PCollection> output = input - .apply(Reshuffle.of()); - - DataflowAssert.that(output).containsInAnyOrder(ARBITRARY_KVS); - - assertEquals( - input.getWindowingStrategy(), - output.getWindowingStrategy()); - - pipeline.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java deleted file mode 100644 index eb3262bcac..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ReshuffleTriggerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link ReshuffleTrigger}. - */ -@RunWith(JUnit4.class) -public class ReshuffleTriggerTest { - - /** Public so that other tests can instantiate {@link ReshuffleTrigger}. */ - public static ReshuffleTrigger forTest() { - return new ReshuffleTrigger<>(); - } - - @Test - public void testShouldFire() throws Exception { - TriggerTester tester = TriggerTester.forTrigger( - new ReshuffleTrigger(), FixedWindows.of(Duration.millis(100))); - IntervalWindow arbitraryWindow = new IntervalWindow(new Instant(300), new Instant(400)); - assertTrue(tester.shouldFire(arbitraryWindow)); - } - - @Test - public void testOnTimer() throws Exception { - TriggerTester tester = TriggerTester.forTrigger( - new ReshuffleTrigger(), FixedWindows.of(Duration.millis(100))); - IntervalWindow arbitraryWindow = new IntervalWindow(new Instant(100), new Instant(200)); - tester.fireIfShouldFire(arbitraryWindow); - assertFalse(tester.isMarkedFinished(arbitraryWindow)); - } - - @Test - public void testToString() { - Trigger trigger = new ReshuffleTrigger<>(); - assertEquals("ReshuffleTrigger()", trigger.toString()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializerTest.java deleted file mode 100644 index 7097190802..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/RetryHttpRequestInitializerTest.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpResponseException; -import com.google.api.client.http.HttpResponseInterceptor; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.http.LowLevelHttpRequest; -import com.google.api.client.http.LowLevelHttpResponse; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpRequest; -import com.google.api.client.util.NanoClock; -import com.google.api.client.util.Sleeper; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.storage.Storage; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.security.PrivateKey; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Tests for RetryHttpRequestInitializer. - */ -@RunWith(JUnit4.class) -public class RetryHttpRequestInitializerTest { - - @Mock private Credential mockCredential; - @Mock private PrivateKey mockPrivateKey; - @Mock private LowLevelHttpRequest mockLowLevelRequest; - @Mock private LowLevelHttpResponse mockLowLevelResponse; - @Mock private HttpResponseInterceptor mockHttpResponseInterceptor; - - private final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); - private Storage storage; - - // Used to test retrying a request more than the default 10 times. - static class MockNanoClock implements NanoClock { - private int timesMs[] = {500, 750, 1125, 1688, 2531, 3797, 5695, 8543, - 12814, 19222, 28833, 43249, 64873, 97310, 145965, 218945, 328420}; - private int i = 0; - - @Override - public long nanoTime() { - return timesMs[i++ / 2] * 1000000; - } - } - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - HttpTransport lowLevelTransport = new HttpTransport() { - @Override - protected LowLevelHttpRequest buildRequest(String method, String url) - throws IOException { - return mockLowLevelRequest; - } - }; - - // Retry initializer will pass through to credential, since we can have - // only a single HttpRequestInitializer, and we use multiple Credential - // types in the SDK, not all of which allow for retry configuration. - RetryHttpRequestInitializer initializer = new RetryHttpRequestInitializer( - mockCredential, new MockNanoClock(), new Sleeper() { - @Override - public void sleep(long millis) throws InterruptedException {} - }, Arrays.asList(418 /* I'm a teapot */), mockHttpResponseInterceptor); - storage = new Storage.Builder(lowLevelTransport, jsonFactory, initializer) - .setApplicationName("test").build(); - } - - @After - public void tearDown() { - verifyNoMoreInteractions(mockPrivateKey); - verifyNoMoreInteractions(mockLowLevelRequest); - verifyNoMoreInteractions(mockCredential); - verifyNoMoreInteractions(mockHttpResponseInterceptor); - } - - @Test - public void testBasicOperation() throws IOException { - when(mockLowLevelRequest.execute()) - .thenReturn(mockLowLevelResponse); - when(mockLowLevelResponse.getStatusCode()) - .thenReturn(200); - - Storage.Buckets.Get result = storage.buckets().get("test"); - HttpResponse response = result.executeUnparsed(); - assertNotNull(response); - - verify(mockCredential).initialize(any(HttpRequest.class)); - verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class)); - verify(mockLowLevelRequest, atLeastOnce()) - .addHeader(anyString(), anyString()); - verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt()); - verify(mockLowLevelRequest).execute(); - verify(mockLowLevelResponse).getStatusCode(); - } - - /** - * Tests that a non-retriable error is not retried. - */ - @Test - public void testErrorCodeForbidden() throws IOException { - when(mockLowLevelRequest.execute()) - .thenReturn(mockLowLevelResponse); - when(mockLowLevelResponse.getStatusCode()) - .thenReturn(403) // Non-retryable error. - .thenReturn(200); // Shouldn't happen. - - try { - Storage.Buckets.Get result = storage.buckets().get("test"); - HttpResponse response = result.executeUnparsed(); - assertNotNull(response); - } catch (HttpResponseException e) { - Assert.assertThat(e.getMessage(), Matchers.containsString("403")); - } - - verify(mockCredential).initialize(any(HttpRequest.class)); - verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class)); - verify(mockLowLevelRequest, atLeastOnce()) - .addHeader(anyString(), anyString()); - verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt()); - verify(mockLowLevelRequest).execute(); - verify(mockLowLevelResponse).getStatusCode(); - } - - /** - * Tests that a retriable error is retried. - */ - @Test - public void testRetryableError() throws IOException { - when(mockLowLevelRequest.execute()) - .thenReturn(mockLowLevelResponse) - .thenReturn(mockLowLevelResponse) - .thenReturn(mockLowLevelResponse); - when(mockLowLevelResponse.getStatusCode()) - .thenReturn(503) // Retryable - .thenReturn(429) // We also retry on 429 Too Many Requests. - .thenReturn(200); - - Storage.Buckets.Get result = storage.buckets().get("test"); - HttpResponse response = result.executeUnparsed(); - assertNotNull(response); - - verify(mockCredential).initialize(any(HttpRequest.class)); - verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class)); - verify(mockLowLevelRequest, atLeastOnce()) - .addHeader(anyString(), anyString()); - verify(mockLowLevelRequest, times(3)).setTimeout(anyInt(), anyInt()); - verify(mockLowLevelRequest, times(3)).execute(); - verify(mockLowLevelResponse, times(3)).getStatusCode(); - } - - /** - * Tests that an IOException is retried. - */ - @Test - public void testThrowIOException() throws IOException { - when(mockLowLevelRequest.execute()) - .thenThrow(new IOException("Fake Error")) - .thenReturn(mockLowLevelResponse); - when(mockLowLevelResponse.getStatusCode()) - .thenReturn(200); - - Storage.Buckets.Get result = storage.buckets().get("test"); - HttpResponse response = result.executeUnparsed(); - assertNotNull(response); - - verify(mockCredential).initialize(any(HttpRequest.class)); - verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class)); - verify(mockLowLevelRequest, atLeastOnce()) - .addHeader(anyString(), anyString()); - verify(mockLowLevelRequest, times(2)).setTimeout(anyInt(), anyInt()); - verify(mockLowLevelRequest, times(2)).execute(); - verify(mockLowLevelResponse).getStatusCode(); - } - - /** - * Tests that a retryable error is retried enough times. - */ - @Test - public void testRetryableErrorRetryEnoughTimes() throws IOException { - when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse); - final int retries = 10; - when(mockLowLevelResponse.getStatusCode()).thenAnswer(new Answer(){ - int n = 0; - @Override - public Integer answer(InvocationOnMock invocation) { - return (n++ < retries - 1) ? 503 : 200; - }}); - - Storage.Buckets.Get result = storage.buckets().get("test"); - HttpResponse response = result.executeUnparsed(); - assertNotNull(response); - - verify(mockCredential).initialize(any(HttpRequest.class)); - verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class)); - verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), - anyString()); - verify(mockLowLevelRequest, times(retries)).setTimeout(anyInt(), anyInt()); - verify(mockLowLevelRequest, times(retries)).execute(); - verify(mockLowLevelResponse, times(retries)).getStatusCode(); - } - - /** - * Tests that when RPCs fail with {@link SocketTimeoutException}, the IO exception handler - * is invoked. - */ - @Test - public void testIOExceptionHandlerIsInvokedOnTimeout() throws Exception { - // Counts the number of calls to execute the HTTP request. - final AtomicLong executeCount = new AtomicLong(); - - // 10 is a private internal constant in the Google API Client library. See - // com.google.api.client.http.HttpRequest#setNumberOfRetries - // TODO: update this test once the private internal constant is public. - final int defaultNumberOfRetries = 10; - - // A mock HTTP request that always throws SocketTimeoutException. - MockHttpTransport transport = - new MockHttpTransport.Builder().setLowLevelHttpRequest(new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - executeCount.incrementAndGet(); - throw new SocketTimeoutException("Fake forced timeout exception"); - } - }).build(); - - // A sample HTTP request to BigQuery that uses both default Transport and default - // RetryHttpInitializer. - Bigquery b = new Bigquery.Builder( - transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()).build(); - BigQueryTableInserter inserter = new BigQueryTableInserter(b); - TableReference t = new TableReference() - .setProjectId("project").setDatasetId("dataset").setTableId("table"); - - try { - inserter.insertAll(t, ImmutableList.of(new TableRow())); - fail(); - } catch (Throwable e) { - assertThat(e, Matchers.instanceOf(RuntimeException.class)); - assertThat(e.getCause(), Matchers.instanceOf(SocketTimeoutException.class)); - assertEquals(1 + defaultNumberOfRetries, executeCount.get()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializableUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializableUtilsTest.java deleted file mode 100644 index 5d52c31134..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializableUtilsTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.DeterministicStandardCoder; -import com.google.common.collect.ImmutableList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.List; - -/** Tests for {@link SerializableUtils}. */ -@RunWith(JUnit4.class) -public class SerializableUtilsTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - - /** A class that is serializable by Java. */ - private static class SerializableByJava implements Serializable { - final String stringValue; - final int intValue; - - public SerializableByJava(String stringValue, int intValue) { - this.stringValue = stringValue; - this.intValue = intValue; - } - } - - @Test - public void testTranscode() { - String stringValue = "hi bob"; - int intValue = 42; - - SerializableByJava testObject = new SerializableByJava(stringValue, intValue); - SerializableByJava testCopy = SerializableUtils.ensureSerializable(testObject); - - assertEquals(stringValue, testCopy.stringValue); - assertEquals(intValue, testCopy.intValue); - } - - @Test - public void testDeserializationError() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("unable to deserialize a bogus string"); - SerializableUtils.deserializeFromByteArray( - "this isn't legal".getBytes(), - "a bogus string"); - } - - /** A class that is not serializable by Java. */ - private static class UnserializableByJava implements Serializable { - @SuppressWarnings("unused") - private Object unserializableField = new Object(); - } - - @Test - public void testSerializationError() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("unable to serialize"); - SerializableUtils.serializeToByteArray(new UnserializableByJava()); - } - - /** A {@link Coder} that is not serializable by Java. */ - private static class UnserializableCoderByJava extends DeterministicStandardCoder { - private final Object unserializableField = new Object(); - - @Override - public void encode(Object value, OutputStream outStream, Context context) - throws CoderException, IOException { - } - - @Override - public Object decode(InputStream inStream, Context context) - throws CoderException, IOException { - return unserializableField; - } - - @Override - public List> getCoderArguments() { - return ImmutableList.of(); - } - } - - @Test - public void testEnsureSerializableWithUnserializableCoderByJava() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("unable to serialize"); - SerializableUtils.ensureSerializable(new UnserializableCoderByJava()); - } - - /** A {@link Coder} that is not serializable by Jackson. */ - private static class UnserializableCoderByJackson extends DeterministicStandardCoder { - private final SerializableByJava unserializableField; - - public UnserializableCoderByJackson(SerializableByJava unserializableField) { - this.unserializableField = unserializableField; - } - - @JsonCreator - public static UnserializableCoderByJackson of( - @JsonProperty("unserializableField") SerializableByJava unserializableField) { - return new UnserializableCoderByJackson(unserializableField); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - result.put("unserializableField", unserializableField); - return result; - } - - @Override - public void encode(Object value, OutputStream outStream, Context context) - throws CoderException, IOException { - } - - @Override - public Object decode(InputStream inStream, Context context) - throws CoderException, IOException { - return unserializableField; - } - - @Override - public List> getCoderArguments() { - return ImmutableList.of(); - } - } - - @Test - public void testEnsureSerializableWithUnserializableCoderByJackson() throws Exception { - expectedException.expect(RuntimeException.class); - expectedException.expectMessage("Unable to deserialize Coder:"); - SerializableUtils.ensureSerializable( - new UnserializableCoderByJackson(new SerializableByJava("TestData", 5))); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializerTest.java deleted file mode 100644 index 80c797a231..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SerializerTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addDouble; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests Serializer implementation. - */ -@RunWith(JUnit4.class) -public class SerializerTest { - /** - * A POJO to use for testing serialization. - */ - @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, - property = PropertyNames.OBJECT_TYPE_NAME) - public static class TestRecord { - // TODO: When we apply property name typing to all non-final classes, the - // annotation on this class should be removed. - public String name; - public boolean ok; - public int value; - public double dValue; - } - - @Test - public void testStatefulDeserialization() { - CloudObject object = CloudObject.forClass(TestRecord.class); - - addString(object, "name", "foobar"); - addBoolean(object, "ok", true); - addLong(object, "value", 42L); - addDouble(object, "dValue", .25); - - TestRecord record = Serializer.deserialize(object, TestRecord.class); - Assert.assertEquals("foobar", record.name); - Assert.assertEquals(true, record.ok); - Assert.assertEquals(42L, record.value); - Assert.assertEquals(0.25, record.dValue, 0.0001); - } - - private static class InjectedTestRecord { - private final String n; - private final int v; - - @SuppressWarnings("unused") // used for JSON serialization - public InjectedTestRecord( - @JsonProperty("name") String name, - @JsonProperty("value") int value) { - this.n = name; - this.v = value; - } - - public String getName() { - return n; - } - public int getValue() { - return v; - } - } - - @Test - public void testDeserializationInjection() { - CloudObject object = CloudObject.forClass(InjectedTestRecord.class); - addString(object, "name", "foobar"); - addLong(object, "value", 42L); - - InjectedTestRecord record = - Serializer.deserialize(object, InjectedTestRecord.class); - - Assert.assertEquals("foobar", record.getName()); - Assert.assertEquals(42L, record.getValue()); - } - - private static class FactoryInjectedTestRecord { - @JsonCreator - public static FactoryInjectedTestRecord of( - @JsonProperty("name") String name, - @JsonProperty("value") int value) { - return new FactoryInjectedTestRecord(name, value); - } - - private final String n; - private final int v; - - private FactoryInjectedTestRecord(String name, int value) { - this.n = name; - this.v = value; - } - - public String getName() { - return n; - } - public int getValue() { - return v; - } - } - - @Test - public void testDeserializationFactoryInjection() { - CloudObject object = CloudObject.forClass(FactoryInjectedTestRecord.class); - addString(object, "name", "foobar"); - addLong(object, "value", 42L); - - FactoryInjectedTestRecord record = - Serializer.deserialize(object, FactoryInjectedTestRecord.class); - Assert.assertEquals("foobar", record.getName()); - Assert.assertEquals(42L, record.getValue()); - } - - private static class DerivedTestRecord extends TestRecord { - public String derived; - } - - @Test - public void testSubclassDeserialization() { - CloudObject object = CloudObject.forClass(DerivedTestRecord.class); - - addString(object, "name", "foobar"); - addBoolean(object, "ok", true); - addLong(object, "value", 42L); - addDouble(object, "dValue", .25); - addString(object, "derived", "baz"); - - TestRecord result = Serializer.deserialize(object, TestRecord.class); - Assert.assertThat(result, Matchers.instanceOf(DerivedTestRecord.class)); - - DerivedTestRecord record = (DerivedTestRecord) result; - Assert.assertEquals("foobar", record.name); - Assert.assertEquals(true, record.ok); - Assert.assertEquals(42L, record.value); - Assert.assertEquals(0.25, record.dValue, 0.0001); - Assert.assertEquals("baz", record.derived); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java deleted file mode 100644 index e75a3e8cb4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/SimpleDoFnRunnerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.mock; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.util.BaseExecutionContext.StepContext; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests for base {@link DoFnRunnerBase} functionality. - */ -@RunWith(JUnit4.class) -public class SimpleDoFnRunnerTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testExceptionsWrappedAsUserCodeException() { - ThrowingDoFn fn = new ThrowingDoFn(); - DoFnRunner runner = createRunner(fn); - - thrown.expect(UserCodeException.class); - thrown.expectCause(is(fn.exceptionToThrow)); - - runner.processElement(WindowedValue.valueInGlobalWindow("anyValue")); - } - - @Test - public void testSystemDoFnInternalExceptionsNotWrapped() { - ThrowingSystemDoFn fn = new ThrowingSystemDoFn(); - DoFnRunner runner = createRunner(fn); - - thrown.expect(is(fn.exceptionToThrow)); - - runner.processElement(WindowedValue.valueInGlobalWindow("anyValue")); - } - - private DoFnRunner createRunner(DoFn fn) { - // Pass in only necessary parameters for the test - List> sideOutputTags = Arrays.asList(); - StepContext context = mock(StepContext.class); - return DoFnRunners.simpleRunner( - null, fn, null, null, null, sideOutputTags, context, null, null); - } - - static class ThrowingDoFn extends DoFn { - final Exception exceptionToThrow = - new UnsupportedOperationException("Expected exception"); - - @Override - public void processElement(ProcessContext c) throws Exception { - throw exceptionToThrow; - } - } - - @SystemDoFnInternal - static class ThrowingSystemDoFn extends ThrowingDoFn { - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StreamUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StreamUtilsTest.java deleted file mode 100644 index 595dbdc155..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StreamUtilsTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; - -/** Unit tests for {@link ExposedByteArrayInputStream}. */ -@RunWith(JUnit4.class) -public class StreamUtilsTest { - - private byte[] testData = null; - - @Before - public void setUp() { - testData = new byte[60 * 1024]; - Arrays.fill(testData, (byte) 32); - } - - @Test - public void testGetBytesFromExposedByteArrayInputStream() throws IOException { - InputStream stream = new ExposedByteArrayInputStream(testData); - byte[] bytes = StreamUtils.getBytes(stream); - assertArrayEquals(testData, bytes); - assertSame(testData, bytes); - assertEquals(0, stream.available()); - } - - @Test - public void testGetBytesFromByteArrayInputStream() throws IOException { - InputStream stream = new ByteArrayInputStream(testData); - byte[] bytes = StreamUtils.getBytes(stream); - assertArrayEquals(testData, bytes); - assertEquals(0, stream.available()); - } - - @Test - public void testGetBytesFromInputStream() throws IOException { - // Any stream which is not a ByteArrayInputStream. - InputStream stream = - new BufferedInputStream(new ByteArrayInputStream(testData)); - byte[] bytes = StreamUtils.getBytes(stream); - assertArrayEquals(testData, bytes); - assertEquals(0, stream.available()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StringUtilsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StringUtilsTest.java deleted file mode 100644 index 49d8688ace..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StringUtilsTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PDone; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for StringUtils. - */ -@RunWith(JUnit4.class) -public class StringUtilsTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testTranscodeEmptyByteArray() { - byte[] bytes = { }; - String string = ""; - assertEquals(string, StringUtils.byteArrayToJsonString(bytes)); - assertArrayEquals(bytes, StringUtils.jsonStringToByteArray(string)); - } - - @Test - public void testTranscodeMixedByteArray() { - byte[] bytes = { - 0, 5, 12, 16, 31, 32, 65, 66, 126, 127, (byte) 128, (byte) 255, 67, 0 }; - String string = "%00%05%0c%10%1f AB~%7f%80%ffC%00"; - assertEquals(string, StringUtils.byteArrayToJsonString(bytes)); - assertArrayEquals(bytes, StringUtils.jsonStringToByteArray(string)); - } - - /** - * Inner class for simple name test. - */ - private class EmbeddedDoFn { - - private class DeeperEmbeddedDoFn extends EmbeddedDoFn {} - - private EmbeddedDoFn getEmbedded() { - return new DeeperEmbeddedDoFn(); - } - } - - private class EmbeddedPTransform extends PTransform { - private class Bound extends PTransform {} - - private Bound getBound() { - return new Bound(); - } - } - - private interface AnonymousClass { - Object getInnerClassInstance(); - } - - @Test - public void testSimpleName() { - assertEquals("Embedded", - StringUtils.approximateSimpleName(EmbeddedDoFn.class)); - } - - @Test - public void testAnonSimpleName() throws Exception { - thrown.expect(IllegalArgumentException.class); - - EmbeddedDoFn anon = new EmbeddedDoFn(){}; - - StringUtils.approximateSimpleName(anon.getClass()); - } - - @Test - public void testNestedSimpleName() { - EmbeddedDoFn fn = new EmbeddedDoFn(); - EmbeddedDoFn inner = fn.getEmbedded(); - - assertEquals("DeeperEmbedded", StringUtils.approximateSimpleName(inner.getClass())); - } - - @Test - public void testPTransformName() { - EmbeddedPTransform transform = new EmbeddedPTransform(); - assertEquals( - "StringUtilsTest.EmbeddedPTransform", - StringUtils.approximatePTransformName(transform.getClass())); - assertEquals( - "StringUtilsTest.EmbeddedPTransform", - StringUtils.approximatePTransformName(transform.getBound().getClass())); - assertEquals("TextIO.Write", StringUtils.approximatePTransformName(TextIO.Write.Bound.class)); - } - - @Test - public void testPTransformNameWithAnonOuterClass() throws Exception { - AnonymousClass anonymousClassObj = new AnonymousClass() { - class NamedInnerClass extends PTransform {} - - @Override - public Object getInnerClassInstance() { - return new NamedInnerClass(); - } - }; - - assertEquals("NamedInnerClass", - StringUtils.approximateSimpleName(anonymousClassObj.getInnerClassInstance().getClass())); - assertEquals("StringUtilsTest.NamedInnerClass", - StringUtils.approximatePTransformName( - anonymousClassObj.getInnerClassInstance().getClass())); - } - - @Test - public void testLevenshteinDistance() { - assertEquals(0, StringUtils.getLevenshteinDistance("", "")); // equal - assertEquals(3, StringUtils.getLevenshteinDistance("", "abc")); // first empty - assertEquals(3, StringUtils.getLevenshteinDistance("abc", "")); // second empty - assertEquals(5, StringUtils.getLevenshteinDistance("abc", "12345")); // completely different - assertEquals(1, StringUtils.getLevenshteinDistance("abc", "ac")); // deletion - assertEquals(1, StringUtils.getLevenshteinDistance("abc", "ab1c")); // insertion - assertEquals(1, StringUtils.getLevenshteinDistance("abc", "a1c")); // modification - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java deleted file mode 100644 index bc0bdd82ec..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/StructsTest.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.addDouble; -import static com.google.cloud.dataflow.sdk.util.Structs.addList; -import static com.google.cloud.dataflow.sdk.util.Structs.addLong; -import static com.google.cloud.dataflow.sdk.util.Structs.addLongs; -import static com.google.cloud.dataflow.sdk.util.Structs.addNull; -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import static com.google.cloud.dataflow.sdk.util.Structs.addStringList; -import static com.google.cloud.dataflow.sdk.util.Structs.getBoolean; -import static com.google.cloud.dataflow.sdk.util.Structs.getDictionary; -import static com.google.cloud.dataflow.sdk.util.Structs.getInt; -import static com.google.cloud.dataflow.sdk.util.Structs.getListOfMaps; -import static com.google.cloud.dataflow.sdk.util.Structs.getLong; -import static com.google.cloud.dataflow.sdk.util.Structs.getObject; -import static com.google.cloud.dataflow.sdk.util.Structs.getString; -import static com.google.cloud.dataflow.sdk.util.Structs.getStrings; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Tests for Structs. - */ -@RunWith(JUnit4.class) -public class StructsTest { - private List> makeCloudObjects() { - List> objects = new ArrayList<>(); - { - CloudObject o = CloudObject.forClassName("string"); - addString(o, "singletonStringKey", "stringValue"); - objects.add(o); - } - { - CloudObject o = CloudObject.forClassName("long"); - addLong(o, "singletonLongKey", 42L); - objects.add(o); - } - return objects; - } - - private Map makeCloudDictionary() { - Map o = new HashMap<>(); - addList(o, "emptyKey", Collections.>emptyList()); - addNull(o, "noStringsKey"); - addString(o, "singletonStringKey", "stringValue"); - addStringList(o, "multipleStringsKey", Arrays.asList("hi", "there", "bob")); - addLongs(o, "multipleLongsKey", 47L, 1L << 42, -5L); - addLong(o, "singletonLongKey", 42L); - addDouble(o, "singletonDoubleKey", 3.14); - addBoolean(o, "singletonBooleanKey", true); - addNull(o, "noObjectsKey"); - addList(o, "multipleObjectsKey", makeCloudObjects()); - return o; - } - - @Test - public void testGetStringParameter() throws Exception { - Map o = makeCloudDictionary(); - - Assert.assertEquals( - "stringValue", - getString(o, "singletonStringKey")); - Assert.assertEquals( - "stringValue", - getString(o, "singletonStringKey", "defaultValue")); - Assert.assertEquals( - "defaultValue", - getString(o, "missingKey", "defaultValue")); - - try { - getString(o, "missingKey"); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString( - "didn't find required parameter missingKey")); - } - - try { - getString(o, "noStringsKey"); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString("not a string")); - } - - Assert.assertThat(getStrings(o, "noStringsKey", null), Matchers.emptyIterable()); - Assert.assertThat(getObject(o, "noStringsKey").keySet(), Matchers.emptyIterable()); - Assert.assertThat(getDictionary(o, "noStringsKey").keySet(), Matchers.emptyIterable()); - Assert.assertThat(getDictionary(o, "noStringsKey", null).keySet(), - Matchers.emptyIterable()); - - try { - getString(o, "multipleStringsKey"); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString("not a string")); - } - - try { - getString(o, "emptyKey"); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString("not a string")); - } - } - - @Test - public void testGetBooleanParameter() throws Exception { - Map o = makeCloudDictionary(); - - Assert.assertEquals( - true, - getBoolean(o, "singletonBooleanKey", false)); - Assert.assertEquals( - false, - getBoolean(o, "missingKey", false)); - - try { - getBoolean(o, "emptyKey", false); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString("not a boolean")); - } - } - - @Test - public void testGetLongParameter() throws Exception { - Map o = makeCloudDictionary(); - - Assert.assertEquals( - (Long) 42L, - getLong(o, "singletonLongKey", 666L)); - Assert.assertEquals( - (Integer) 42, - getInt(o, "singletonLongKey", 666)); - Assert.assertEquals( - (Long) 666L, - getLong(o, "missingKey", 666L)); - - try { - getLong(o, "emptyKey", 666L); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString("not a long")); - } - try { - getInt(o, "emptyKey", 666); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString("not an int")); - } - } - - @Test - public void testGetListOfMaps() throws Exception { - Map o = makeCloudDictionary(); - - Assert.assertEquals( - makeCloudObjects(), - getListOfMaps(o, "multipleObjectsKey", null)); - - try { - getListOfMaps(o, "singletonLongKey", null); - Assert.fail("should have thrown an exception"); - } catch (Exception exn) { - Assert.assertThat(exn.toString(), - Matchers.containsString("not a list")); - } - } - - // TODO: Test builder operations. -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimeUtilTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimeUtilTest.java deleted file mode 100644 index d7c3384be1..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimeUtilTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudDuration; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudTime; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudDuration; -import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudTime; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Unit tests for {@link TimeUtil}. */ -@RunWith(JUnit4.class) -public final class TimeUtilTest { - @Test - public void toCloudTimeShouldPrintTimeStrings() { - assertEquals("1970-01-01T00:00:00Z", toCloudTime(new Instant(0))); - assertEquals("1970-01-01T00:00:00.001Z", toCloudTime(new Instant(1))); - } - - @Test - public void fromCloudTimeShouldParseTimeStrings() { - assertEquals(new Instant(0), fromCloudTime("1970-01-01T00:00:00Z")); - assertEquals(new Instant(1), fromCloudTime("1970-01-01T00:00:00.001Z")); - assertEquals(new Instant(1), fromCloudTime("1970-01-01T00:00:00.001000Z")); - assertEquals(new Instant(1), fromCloudTime("1970-01-01T00:00:00.001001Z")); - assertEquals(new Instant(1), fromCloudTime("1970-01-01T00:00:00.001000000Z")); - assertEquals(new Instant(1), fromCloudTime("1970-01-01T00:00:00.001000001Z")); - assertNull(fromCloudTime("")); - assertNull(fromCloudTime("1970-01-01T00:00:00")); - } - - @Test - public void toCloudDurationShouldPrintDurationStrings() { - assertEquals("0s", toCloudDuration(Duration.ZERO)); - assertEquals("4s", toCloudDuration(Duration.millis(4000))); - assertEquals("4.001s", toCloudDuration(Duration.millis(4001))); - } - - @Test - public void fromCloudDurationShouldParseDurationStrings() { - assertEquals(Duration.millis(4000), fromCloudDuration("4s")); - assertEquals(Duration.millis(4001), fromCloudDuration("4.001s")); - assertEquals(Duration.millis(4001), fromCloudDuration("4.001000s")); - assertEquals(Duration.millis(4001), fromCloudDuration("4.001001s")); - assertEquals(Duration.millis(4001), fromCloudDuration("4.001000000s")); - assertEquals(Duration.millis(4001), fromCloudDuration("4.001000001s")); - assertNull(fromCloudDuration("")); - assertNull(fromCloudDuration("4")); - assertNull(fromCloudDuration("4.1")); - assertNull(fromCloudDuration("4.1s")); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java deleted file mode 100644 index 797237f763..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TimerInternalsTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.comparesEqualTo; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.testing.CoderProperties; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerDataCoder; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Unit tests for {@link TimerInternals}. - */ -@RunWith(JUnit4.class) -public class TimerInternalsTest { - - @Test - public void testTimerDataCoder() throws Exception { - CoderProperties.coderDecodeEncodeEqual( - TimerDataCoder.of(GlobalWindow.Coder.INSTANCE), - TimerData.of(StateNamespaces.global(), new Instant(0), TimeDomain.EVENT_TIME)); - - Coder windowCoder = IntervalWindow.getCoder(); - CoderProperties.coderDecodeEncodeEqual( - TimerDataCoder.of(windowCoder), - TimerData.of( - StateNamespaces.window( - windowCoder, new IntervalWindow(new Instant(0), new Instant(100))), - new Instant(99), TimeDomain.PROCESSING_TIME)); - } - - @Test - public void testCompareTo() { - Instant firstTimestamp = new Instant(100); - Instant secondTimestamp = new Instant(200); - IntervalWindow firstWindow = new IntervalWindow(new Instant(0), firstTimestamp); - IntervalWindow secondWindow = new IntervalWindow(firstTimestamp, secondTimestamp); - Coder windowCoder = IntervalWindow.getCoder(); - - StateNamespace firstWindowNs = StateNamespaces.window(windowCoder, firstWindow); - StateNamespace secondWindowNs = StateNamespaces.window(windowCoder, secondWindow); - - TimerData firstEventTime = TimerData.of(firstWindowNs, firstTimestamp, TimeDomain.EVENT_TIME); - TimerData secondEventTime = TimerData.of(firstWindowNs, secondTimestamp, TimeDomain.EVENT_TIME); - TimerData thirdEventTime = TimerData.of(secondWindowNs, secondTimestamp, TimeDomain.EVENT_TIME); - - TimerData firstProcTime = - TimerData.of(firstWindowNs, firstTimestamp, TimeDomain.PROCESSING_TIME); - TimerData secondProcTime = - TimerData.of(firstWindowNs, secondTimestamp, TimeDomain.PROCESSING_TIME); - TimerData thirdProcTime = - TimerData.of(secondWindowNs, secondTimestamp, TimeDomain.PROCESSING_TIME); - - assertThat(firstEventTime, - comparesEqualTo(TimerData.of(firstWindowNs, firstTimestamp, TimeDomain.EVENT_TIME))); - assertThat(firstEventTime, lessThan(secondEventTime)); - assertThat(secondEventTime, lessThan(thirdEventTime)); - assertThat(firstEventTime, lessThan(thirdEventTime)); - - assertThat(secondProcTime, - comparesEqualTo(TimerData.of(firstWindowNs, secondTimestamp, TimeDomain.PROCESSING_TIME))); - assertThat(firstProcTime, lessThan(secondProcTime)); - assertThat(secondProcTime, lessThan(thirdProcTime)); - assertThat(firstProcTime, lessThan(thirdProcTime)); - - assertThat(firstEventTime, not(comparesEqualTo(firstProcTime))); - assertThat(firstProcTime, - not(comparesEqualTo(TimerData.of(firstWindowNs, - firstTimestamp, - TimeDomain.SYNCHRONIZED_PROCESSING_TIME)))); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java deleted file mode 100644 index 7b9e088c3d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/TriggerTester.java +++ /dev/null @@ -1,596 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger; -import com.google.cloud.dataflow.sdk.transforms.windowing.TriggerBuilder; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.util.ActiveWindowSet.MergeCallback; -import com.google.cloud.dataflow.sdk.util.TimerInternals.TimerData; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode; -import com.google.cloud.dataflow.sdk.util.state.InMemoryStateInternals; -import com.google.cloud.dataflow.sdk.util.state.State; -import com.google.cloud.dataflow.sdk.util.state.StateInternals; -import com.google.cloud.dataflow.sdk.util.state.StateNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowAndTriggerNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateNamespaces.WindowNamespace; -import com.google.cloud.dataflow.sdk.util.state.StateTag; -import com.google.cloud.dataflow.sdk.util.state.WatermarkHoldState; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.base.MoreObjects; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * Test utility that runs a {@link Trigger}, using in-memory stub implementation to provide - * the {@link StateInternals}. - * - * @param The type of windows being used. - */ -public class TriggerTester { - - /** - * A {@link TriggerTester} specialized to {@link Integer} values, so elements and timestamps - * can be conflated. Today, triggers should not observed the element type, so this is the - * only trigger tester that needs to be used. - */ - public static class SimpleTriggerTester - extends TriggerTester { - - private SimpleTriggerTester(WindowingStrategy windowingStrategy) throws Exception { - super(windowingStrategy); - } - - public void injectElements(int... values) throws Exception { - List> timestampedValues = - Lists.newArrayListWithCapacity(values.length); - for (int value : values) { - timestampedValues.add(TimestampedValue.of(value, new Instant(value))); - } - injectElements(timestampedValues); - } - - public SimpleTriggerTester withAllowedLateness(Duration allowedLateness) throws Exception { - return new SimpleTriggerTester<>( - windowingStrategy.withAllowedLateness(allowedLateness)); - } - } - - protected final WindowingStrategy windowingStrategy; - - private final TestInMemoryStateInternals stateInternals = - new TestInMemoryStateInternals(); - private final TestTimerInternals timerInternals = new TestTimerInternals(); - private final TriggerContextFactory contextFactory; - private final WindowFn windowFn; - private final ActiveWindowSet activeWindows; - private final Map windowToMergeResult; - - /** - * An {@link ExecutableTrigger} built from the {@link Trigger} or {@link TriggerBuilder} - * under test. - */ - private final ExecutableTrigger executableTrigger; - - /** - * A map from a window and trigger to whether that trigger is finished for the window. - */ - private final Map finishedSets; - - public static SimpleTriggerTester forTrigger( - TriggerBuilder trigger, WindowFn windowFn) - throws Exception { - WindowingStrategy windowingStrategy = - WindowingStrategy.of(windowFn).withTrigger(trigger.buildTrigger()) - // Merging requires accumulation mode or early firings can break up a session. - // Not currently an issue with the tester (because we never GC) but we don't want - // mystery failures due to violating this need. - .withMode(windowFn.isNonMerging() - ? AccumulationMode.DISCARDING_FIRED_PANES - : AccumulationMode.ACCUMULATING_FIRED_PANES); - - return new SimpleTriggerTester<>(windowingStrategy); - } - - public static TriggerTester forAdvancedTrigger( - TriggerBuilder trigger, WindowFn windowFn) throws Exception { - WindowingStrategy strategy = - WindowingStrategy.of(windowFn).withTrigger(trigger.buildTrigger()) - // Merging requires accumulation mode or early firings can break up a session. - // Not currently an issue with the tester (because we never GC) but we don't want - // mystery failures due to violating this need. - .withMode(windowFn.isNonMerging() - ? AccumulationMode.DISCARDING_FIRED_PANES - : AccumulationMode.ACCUMULATING_FIRED_PANES); - - return new TriggerTester<>(strategy); - } - - protected TriggerTester(WindowingStrategy windowingStrategy) throws Exception { - this.windowingStrategy = windowingStrategy; - this.windowFn = windowingStrategy.getWindowFn(); - this.executableTrigger = windowingStrategy.getTrigger(); - this.finishedSets = new HashMap<>(); - - this.activeWindows = - windowFn.isNonMerging() - ? new NonMergingActiveWindowSet() - : new MergingActiveWindowSet(windowFn, stateInternals); - this.windowToMergeResult = new HashMap<>(); - - this.contextFactory = - new TriggerContextFactory<>(windowingStrategy, stateInternals, activeWindows); - } - - /** - * Instructs the trigger to clear its state for the given window. - */ - public void clearState(W window) throws Exception { - executableTrigger.invokeClear(contextFactory.base(window, - new TestTimers(windowNamespace(window)), executableTrigger, getFinishedSet(window))); - } - - /** - * Asserts that the trigger has actually cleared all of its state for the given window. Since - * the trigger under test is the root, this makes the assert for all triggers regardless - * of their position in the trigger tree. - */ - public void assertCleared(W window) { - for (StateNamespace untypedNamespace : stateInternals.getNamespacesInUse()) { - if (untypedNamespace instanceof WindowAndTriggerNamespace) { - @SuppressWarnings("unchecked") - WindowAndTriggerNamespace namespace = (WindowAndTriggerNamespace) untypedNamespace; - if (namespace.getWindow().equals(window)) { - Set tagsInUse = stateInternals.getTagsInUse(namespace); - assertTrue("Trigger has not cleared tags: " + tagsInUse, tagsInUse.isEmpty()); - } - } - } - } - - /** - * Returns {@code true} if the {@link Trigger} under test is finished for the given window. - */ - public boolean isMarkedFinished(W window) { - FinishedTriggers finishedSet = finishedSets.get(window); - if (finishedSet == null) { - return false; - } - - return finishedSet.isFinished(executableTrigger); - } - - private StateNamespace windowNamespace(W window) { - return StateNamespaces.window(windowFn.windowCoder(), checkNotNull(window)); - } - - /** - * Advance the input watermark to the specified time, firing any timers that should - * fire. Then advance the output watermark as far as possible. - */ - public void advanceInputWatermark(Instant newInputWatermark) throws Exception { - timerInternals.advanceInputWatermark(newInputWatermark); - } - - /** Advance the processing time to the specified time, firing any timers that should fire. */ - public void advanceProcessingTime(Instant newProcessingTime) throws Exception { - timerInternals.advanceProcessingTime(newProcessingTime); - } - - /** Advance the processing time to the specified time, firing any timers that should fire. */ - public void advanceSynchronizedProcessingTime(Instant newSynchronizedProcessingTime) - throws Exception { - timerInternals.advanceSynchronizedProcessingTime(newSynchronizedProcessingTime); - } - - /** - * Inject all the timestamped values (after passing through the window function) as if they - * arrived in a single chunk of a bundle (or work-unit). - */ - @SafeVarargs - public final void injectElements(TimestampedValue... values) throws Exception { - injectElements(Arrays.asList(values)); - } - - public final void injectElements(Collection> values) throws Exception { - for (TimestampedValue value : values) { - WindowTracing.trace("TriggerTester.injectElements: {}", value); - } - - List> windowedValues = Lists.newArrayListWithCapacity(values.size()); - - for (TimestampedValue input : values) { - try { - InputT value = input.getValue(); - Instant timestamp = input.getTimestamp(); - Collection assignedWindows = windowFn.assignWindows(new TestAssignContext( - windowFn, value, timestamp, Arrays.asList(GlobalWindow.INSTANCE))); - - for (W window : assignedWindows) { - activeWindows.addActiveForTesting(window); - - // Today, triggers assume onTimer firing at the watermark time, whether or not they - // explicitly set the timer themselves. So this tester must set it. - timerInternals.setTimer( - TimerData.of(windowNamespace(window), window.maxTimestamp(), TimeDomain.EVENT_TIME)); - } - - windowedValues.add(WindowedValue.of(value, timestamp, assignedWindows, PaneInfo.NO_FIRING)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - for (WindowedValue windowedValue : windowedValues) { - for (BoundedWindow untypedWindow : windowedValue.getWindows()) { - // SDK is responsible for type safety - @SuppressWarnings("unchecked") - W window = mergeResult((W) untypedWindow); - - Trigger.OnElementContext context = contextFactory.createOnElementContext(window, - new TestTimers(windowNamespace(window)), windowedValue.getTimestamp(), - executableTrigger, getFinishedSet(window)); - - if (!context.trigger().isFinished()) { - executableTrigger.invokeOnElement(context); - } - } - } - } - - public boolean shouldFire(W window) throws Exception { - Trigger.TriggerContext context = contextFactory.base( - window, - new TestTimers(windowNamespace(window)), - executableTrigger, getFinishedSet(window)); - executableTrigger.getSpec().prefetchShouldFire(context.state()); - return executableTrigger.invokeShouldFire(context); - } - - public void fireIfShouldFire(W window) throws Exception { - Trigger.TriggerContext context = contextFactory.base( - window, - new TestTimers(windowNamespace(window)), - executableTrigger, getFinishedSet(window)); - - executableTrigger.getSpec().prefetchShouldFire(context.state()); - if (executableTrigger.invokeShouldFire(context)) { - executableTrigger.getSpec().prefetchOnFire(context.state()); - executableTrigger.invokeOnFire(context); - if (context.trigger().isFinished()) { - activeWindows.remove(context.window()); - executableTrigger.invokeClear(context); - } - } - } - - public void setSubTriggerFinishedForWindow(int subTriggerIndex, W window, boolean value) { - getFinishedSet(window).setFinished(executableTrigger.subTriggers().get(subTriggerIndex), value); - } - - /** - * Invokes merge from the {@link WindowFn} a single time and passes the resulting merge - * events on to the trigger under test. Does not persist the fact that merging happened, - * since it is just to test the trigger's {@code OnMerge} method. - */ - public final void mergeWindows() throws Exception { - windowToMergeResult.clear(); - activeWindows.merge(new MergeCallback() { - @Override - public void prefetchOnMerge(Collection toBeMerged, W mergeResult) throws Exception {} - - @Override - public void onMerge(Collection toBeMerged, W mergeResult) throws Exception { - List activeToBeMerged = new ArrayList(); - for (W window : toBeMerged) { - windowToMergeResult.put(window, mergeResult); - if (activeWindows.isActive(window)) { - activeToBeMerged.add(window); - } - } - Map mergingFinishedSets = - Maps.newHashMapWithExpectedSize(activeToBeMerged.size()); - for (W oldWindow : activeToBeMerged) { - mergingFinishedSets.put(oldWindow, getFinishedSet(oldWindow)); - } - executableTrigger.invokeOnMerge(contextFactory.createOnMergeContext(mergeResult, - new TestTimers(windowNamespace(mergeResult)), executableTrigger, - getFinishedSet(mergeResult), mergingFinishedSets)); - timerInternals.setTimer(TimerData.of( - windowNamespace(mergeResult), mergeResult.maxTimestamp(), TimeDomain.EVENT_TIME)); - } - }); - } - - public W mergeResult(W window) { - W result = windowToMergeResult.get(window); - return result == null ? window : result; - } - - private FinishedTriggers getFinishedSet(W window) { - FinishedTriggers finishedSet = finishedSets.get(window); - if (finishedSet == null) { - finishedSet = FinishedTriggersSet.fromSet(new HashSet>()); - finishedSets.put(window, finishedSet); - } - return finishedSet; - } - - /** - * Simulate state. - */ - private static class TestInMemoryStateInternals extends InMemoryStateInternals { - - public TestInMemoryStateInternals() { - super(null); - } - - public Set> getTagsInUse(StateNamespace namespace) { - Set> inUse = new HashSet<>(); - for (Map.Entry, State> entry : - inMemoryState.getTagsInUse(namespace).entrySet()) { - if (!isEmptyForTesting(entry.getValue())) { - inUse.add(entry.getKey()); - } - } - return inUse; - } - - public Set getNamespacesInUse() { - return inMemoryState.getNamespacesInUse(); - } - - /** Return the earliest output watermark hold in state, or null if none. */ - public Instant earliestWatermarkHold() { - Instant minimum = null; - for (State storage : inMemoryState.values()) { - if (storage instanceof WatermarkHoldState) { - @SuppressWarnings("unchecked") - Instant hold = ((WatermarkHoldState) storage).read(); - if (minimum == null || (hold != null && hold.isBefore(minimum))) { - minimum = hold; - } - } - } - return minimum; - } - } - - private static class TestAssignContext - extends WindowFn.AssignContext { - private Object element; - private Instant timestamp; - private Collection windows; - - public TestAssignContext(WindowFn windowFn, Object element, Instant timestamp, - Collection windows) { - windowFn.super(); - this.element = element; - this.timestamp = timestamp; - this.windows = windows; - } - - @Override - public Object element() { - return element; - } - - @Override - public Instant timestamp() { - return timestamp; - } - - @Override - public Collection windows() { - return windows; - } - } - - /** - * Simulate the firing of timers and progression of input and output watermarks for a - * single computation and key in a Windmill-like streaming environment. Similar to - * {@link BatchTimerInternals}, but also tracks the output watermark. - */ - private class TestTimerInternals implements TimerInternals { - /** At most one timer per timestamp is kept. */ - private Set existingTimers = new HashSet<>(); - - /** Pending input watermark timers, in timestamp order. */ - private PriorityQueue watermarkTimers = new PriorityQueue<>(11); - - /** Pending processing time timers, in timestamp order. */ - private PriorityQueue processingTimers = new PriorityQueue<>(11); - - /** Current input watermark. */ - @Nullable - private Instant inputWatermarkTime = BoundedWindow.TIMESTAMP_MIN_VALUE; - - /** Current output watermark. */ - @Nullable - private Instant outputWatermarkTime = null; - - /** Current processing time. */ - private Instant processingTime = BoundedWindow.TIMESTAMP_MIN_VALUE; - - /** Current processing time. */ - private Instant synchronizedProcessingTime = null; - - private PriorityQueue queue(TimeDomain domain) { - return TimeDomain.EVENT_TIME.equals(domain) ? watermarkTimers : processingTimers; - } - - @Override - public void setTimer(TimerData timer) { - WindowTracing.trace("TestTimerInternals.setTimer: {}", timer); - if (existingTimers.add(timer)) { - queue(timer.getDomain()).add(timer); - } - } - - @Override - public void deleteTimer(TimerData timer) { - WindowTracing.trace("TestTimerInternals.deleteTimer: {}", timer); - existingTimers.remove(timer); - queue(timer.getDomain()).remove(timer); - } - - @Override - public Instant currentProcessingTime() { - return processingTime; - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return synchronizedProcessingTime; - } - - @Override - public Instant currentInputWatermarkTime() { - return checkNotNull(inputWatermarkTime); - } - - @Override - @Nullable - public Instant currentOutputWatermarkTime() { - return outputWatermarkTime; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("watermarkTimers", watermarkTimers) - .add("processingTimers", processingTime) - .add("inputWatermarkTime", inputWatermarkTime) - .add("outputWatermarkTime", outputWatermarkTime) - .add("processingTime", processingTime) - .toString(); - } - - public void advanceInputWatermark(Instant newInputWatermark) throws Exception { - checkNotNull(newInputWatermark); - checkState(!newInputWatermark.isBefore(inputWatermarkTime), - "Cannot move input watermark time backwards from %s to %s", inputWatermarkTime, - newInputWatermark); - WindowTracing.trace("TestTimerInternals.advanceInputWatermark: from {} to {}", - inputWatermarkTime, newInputWatermark); - inputWatermarkTime = newInputWatermark; - - Instant hold = stateInternals.earliestWatermarkHold(); - if (hold == null) { - WindowTracing.trace("TestTimerInternals.advanceInputWatermark: no holds, " - + "so output watermark = input watermark"); - hold = inputWatermarkTime; - } - advanceOutputWatermark(hold); - } - - private void advanceOutputWatermark(Instant newOutputWatermark) throws Exception { - checkNotNull(newOutputWatermark); - if (newOutputWatermark.isAfter(inputWatermarkTime)) { - WindowTracing.trace( - "TestTimerInternals.advanceOutputWatermark: clipping output watermark from {} to {}", - newOutputWatermark, inputWatermarkTime); - newOutputWatermark = inputWatermarkTime; - } - checkState(outputWatermarkTime == null || !newOutputWatermark.isBefore(outputWatermarkTime), - "Cannot move output watermark time backwards from %s to %s", outputWatermarkTime, - newOutputWatermark); - WindowTracing.trace("TestTimerInternals.advanceOutputWatermark: from {} to {}", - outputWatermarkTime, newOutputWatermark); - outputWatermarkTime = newOutputWatermark; - } - - public void advanceProcessingTime(Instant newProcessingTime) throws Exception { - checkState(!newProcessingTime.isBefore(processingTime), - "Cannot move processing time backwards from %s to %s", processingTime, newProcessingTime); - WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", processingTime, - newProcessingTime); - processingTime = newProcessingTime; - } - - public void advanceSynchronizedProcessingTime(Instant newSynchronizedProcessingTime) - throws Exception { - checkState(!newSynchronizedProcessingTime.isBefore(synchronizedProcessingTime), - "Cannot move processing time backwards from %s to %s", synchronizedProcessingTime, - newSynchronizedProcessingTime); - WindowTracing.trace("TestTimerInternals.advanceProcessingTime: from {} to {}", - synchronizedProcessingTime, newSynchronizedProcessingTime); - synchronizedProcessingTime = newSynchronizedProcessingTime; - } - } - - private class TestTimers implements Timers { - private final StateNamespace namespace; - - public TestTimers(StateNamespace namespace) { - checkArgument(namespace instanceof WindowNamespace); - this.namespace = namespace; - } - - @Override - public void setTimer(Instant timestamp, TimeDomain timeDomain) { - timerInternals.setTimer(TimerData.of(namespace, timestamp, timeDomain)); - } - - @Override - public void deleteTimer(Instant timestamp, TimeDomain timeDomain) { - timerInternals.deleteTimer(TimerData.of(namespace, timestamp, timeDomain)); - } - - @Override - public Instant currentProcessingTime() { - return timerInternals.currentProcessingTime(); - } - - @Override - @Nullable - public Instant currentSynchronizedProcessingTime() { - return timerInternals.currentSynchronizedProcessingTime(); - } - - @Override - public Instant currentEventTime() { - return timerInternals.currentInputWatermarkTime(); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedInputStreamTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedInputStreamTest.java deleted file mode 100644 index 30da6ae723..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedInputStreamTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; - -/** Unit tests for {@link UnownedInputStream}. */ -@RunWith(JUnit4.class) -public class UnownedInputStreamTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - private ByteArrayInputStream bais; - private UnownedInputStream os; - - @Before - public void setup() { - bais = new ByteArrayInputStream(new byte[]{ 1, 2, 3 }); - os = new UnownedInputStream(bais); - } - - @Test - public void testHashCodeEqualsAndToString() throws Exception { - assertEquals(bais.hashCode(), os.hashCode()); - assertEquals("UnownedInputStream{in=" + bais + "}", os.toString()); - assertEquals(new UnownedInputStream(bais), os); - } - - @Test - public void testClosingThrows() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - expectedException.expectMessage("close()"); - os.close(); - } - - @Test - public void testMarkThrows() throws Exception { - assertFalse(os.markSupported()); - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - expectedException.expectMessage("mark()"); - os.mark(1); - } - - @Test - public void testResetThrows() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - expectedException.expectMessage("reset()"); - os.reset(); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStreamTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStreamTest.java deleted file mode 100644 index eea70fe6cb..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UnownedOutputStreamTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayOutputStream; - -/** Unit tests for {@link UnownedOutputStream}. */ -@RunWith(JUnit4.class) -public class UnownedOutputStreamTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - private ByteArrayOutputStream baos; - private UnownedOutputStream os; - - @Before - public void setup() { - baos = new ByteArrayOutputStream(); - os = new UnownedOutputStream(baos); - } - - @Test - public void testHashCodeEqualsAndToString() throws Exception { - assertEquals(baos.hashCode(), os.hashCode()); - assertEquals("UnownedOutputStream{out=" + baos + "}", os.toString()); - assertEquals(new UnownedOutputStream(baos), os); - } - - @Test - public void testClosingThrows() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Caller does not own the underlying"); - os.close(); - } -} - diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptorTest.java deleted file mode 100644 index 698d0cb5a5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UploadIdResponseInterceptorTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import com.google.api.client.http.GenericUrl; -import com.google.api.client.http.HttpResponse; - -import com.google.api.client.testing.http.HttpTesting; -import com.google.api.client.testing.http.MockHttpTransport; -import com.google.api.client.testing.http.MockLowLevelHttpResponse; -import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; - -/** - * A test for {@link UploadIdResponseInterceptor}. - */ - -@RunWith(JUnit4.class) -public class UploadIdResponseInterceptorTest { - - @Rule public ExpectedException expectedException = ExpectedException.none(); - // Note that expected logs also turns on debug logging. - @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(UploadIdResponseInterceptor.class); - - /** - * Builds a HttpResponse with the given string response. - * - * @param header header value to provide or null if none. - * @param uploadId upload id to provide in the url upload id param or null if none. - * @param uploadType upload type to provide in url upload type param or null if none. - * @return HttpResponse with the given parameters - * @throws IOException - */ - private HttpResponse buildHttpResponse(String header, String uploadId, String uploadType) - throws IOException { - MockHttpTransport.Builder builder = new MockHttpTransport.Builder(); - MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse(); - builder.setLowLevelHttpResponse(resp); - resp.setStatusCode(200); - GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL); - if (header != null) { - resp.addHeader("X-GUploader-UploadID", header); - } - if (uploadId != null) { - url.put("upload_id", uploadId); - } - if (uploadType != null) { - url.put("uploadType", uploadType); - } - return builder.build().createRequestFactory().buildGetRequest(url).execute(); - } - - /** - * Tests the responses that should not log. - */ - @Test - public void testResponseNoLogging() throws IOException { - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse(null, null, null)); - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse("hh", "a", null)); - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse(null, "h", null)); - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse("hh", null, null)); - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse(null, null, "type")); - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse("hh", "a", "type")); - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse(null, "h", "type")); - expectedLogs.verifyNotLogged(""); - } - - /** - * Check that a response logs with the correct log. - */ - @Test - public void testResponseLogs() throws IOException { - new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse("abc", null, "type")); - GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL); - url.put("uploadType", "type"); - String worker = System.getProperty("worker_id"); - expectedLogs.verifyDebug("Upload ID for url " + url + " on worker " + worker + " is abc"); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java deleted file mode 100644 index 8bb3ee7ae4..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/UserCodeExceptionTest.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import org.hamcrest.Description; -import org.hamcrest.FeatureMatcher; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; - -/** - * Tests for {@link UserCodeException} functionality. - */ -@RunWith(JUnit4.class) -public class UserCodeExceptionTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void existingUserCodeExceptionsNotWrapped() { - UserCodeException existing = UserCodeException.wrap(new IOException()); - UserCodeException wrapped = UserCodeException.wrap(existing); - - assertEquals(existing, wrapped); - } - - @Test - public void testCauseIsSet() { - thrown.expectCause(isA(IOException.class)); - throwUserCodeException(); - } - - @Test - public void testStackTraceIsTruncatedToUserCode() { - thrown.expectCause(hasBottomStackFrame(method("userCode"))); - throwUserCodeException(); - } - - @Test - public void testStackTraceIsTruncatedProperlyFromHelperMethod() { - thrown.expectCause(hasBottomStackFrame(method("userCode"))); - throwUserCodeExceptionFromHelper(); - } - - @Test - public void testWrapIfOnlyWrapsWhenTrue() { - IOException cause = new IOException(); - RuntimeException wrapped = UserCodeException.wrapIf(true, cause); - - assertThat(wrapped, is(instanceOf(UserCodeException.class))); - } - - @Test - public void testWrapIfReturnsRuntimeExceptionWhenFalse() { - IOException cause = new IOException(); - RuntimeException wrapped = UserCodeException.wrapIf(false, cause); - - assertThat(wrapped, is(not(instanceOf(UserCodeException.class)))); - assertEquals(cause, wrapped.getCause()); - } - - @Test - public void testWrapIfReturnsSourceRuntimeExceptionWhenFalse() { - RuntimeException runtimeException = new RuntimeException("oh noes!"); - RuntimeException wrapped = UserCodeException.wrapIf(false, runtimeException); - - assertEquals(runtimeException, wrapped); - } - - @Test - public void robustAgainstEmptyStackTrace() { - RuntimeException runtimeException = new RuntimeException("empty stack"); - runtimeException.setStackTrace(new StackTraceElement[0]); - RuntimeException wrapped = UserCodeException.wrap(runtimeException); - assertEquals(runtimeException, wrapped.getCause()); - } - - private void throwUserCodeException() { - try { - userCode(); - } catch (Exception ex) { - throw UserCodeException.wrap(ex); - } - } - - private void throwUserCodeExceptionFromHelper() { - try { - userCode(); - } catch (Exception ex) { - throw wrap(ex); - } - } - - private UserCodeException wrap(Throwable t) { - throw UserCodeException.wrap(t); - } - - private void userCode() throws IOException { - userCode2(); - } - - private void userCode2() throws IOException { - userCode3(); - } - - private void userCode3() throws IOException { - IOException ex = new IOException("User processing error!"); - throw ex; - } - - private static ThrowableBottomStackFrameMethodMatcher hasBottomStackFrame( - Matcher frameMatcher) { - return new ThrowableBottomStackFrameMethodMatcher(frameMatcher); - } - - private static StackFrameMethodMatcher method(String methodName) { - return new StackFrameMethodMatcher(is(methodName)); - } - - static class ThrowableBottomStackFrameMethodMatcher - extends FeatureMatcher { - - public ThrowableBottomStackFrameMethodMatcher(Matcher subMatcher) { - super(subMatcher, "Throwable with bottom stack frame:", "stack frame"); - } - - @Override - protected StackTraceElement featureValueOf(Throwable actual) { - StackTraceElement[] stackTrace = actual.getStackTrace(); - return stackTrace[stackTrace.length - 1]; - } - } - - static class StackFrameMethodMatcher extends TypeSafeMatcher { - - private Matcher methodNameMatcher; - - public StackFrameMethodMatcher(Matcher methodNameMatcher) { - this.methodNameMatcher = methodNameMatcher; - } - - @Override - public void describeTo(Description description) { - description.appendText("stack frame where method name "); - methodNameMatcher.describeTo(description); - } - - @Override - protected boolean matchesSafely(StackTraceElement item) { - return methodNameMatcher.matches(item.getMethodName()); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/VarIntTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/VarIntTest.java deleted file mode 100644 index ca233ed124..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/VarIntTest.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.IOException; - -/** Unit tests for {@link VarInt}. */ -@RunWith(JUnit4.class) -public class VarIntTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - - // Long values to check for boundary cases. - private static final long[] LONG_VALUES = { - 0, - 1, - 127, - 128, - 16383, - 16384, - 2097151, - 2097152, - 268435455, - 268435456, - 34359738367L, - 34359738368L, - 9223372036854775807L, - -9223372036854775808L, - -1, - }; - - // VarInt encoding of the above VALUES. - private static final byte[][] LONG_ENCODED = { - // 0 - { 0x00 }, - // 1 - { 0x01 }, - // 127 - { 0x7f }, - // 128 - { (byte) 0x80, 0x01 }, - // 16383 - { (byte) 0xff, 0x7f }, - // 16834 - { (byte) 0x80, (byte) 0x80, 0x01 }, - // 2097151 - { (byte) 0xff, (byte) 0xff, 0x7f }, - // 2097152 - { (byte) 0x80, (byte) 0x80, (byte) 0x80, 0x01 }, - // 268435455 - { (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x7f }, - // 268435456 - { (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, 0x01 }, - // 34359738367 - { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x7f }, - // 34359738368 - { (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, - 0x01 }, - // 9223372036854775807 - { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x7f }, - // -9223372036854775808L - { (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, - (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, 0x01 }, - // -1 - { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x01 } - }; - - // Integer values to check for boundary cases. - private static final int[] INT_VALUES = { - 0, - 1, - 127, - 128, - 16383, - 16384, - 2097151, - 2097152, - 268435455, - 268435456, - 2147483647, - -2147483648, - -1, - }; - - // VarInt encoding of the above VALUES. - private static final byte[][] INT_ENCODED = { - // 0 - { (byte) 0x00 }, - // 1 - { (byte) 0x01 }, - // 127 - { (byte) 0x7f }, - // 128 - { (byte) 0x80, (byte) 0x01 }, - // 16383 - { (byte) 0xff, (byte) 0x7f }, - // 16834 - { (byte) 0x80, (byte) 0x80, (byte) 0x01 }, - // 2097151 - { (byte) 0xff, (byte) 0xff, (byte) 0x7f }, - // 2097152 - { (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x01 }, - // 268435455 - { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x7f }, - // 268435456 - { (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x01 }, - // 2147483647 - { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x07 }, - // -2147483648 - { (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x08 }, - // -1 - { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x0f } - }; - - private static byte[] encodeInt(int v) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - VarInt.encode(v, stream); - return stream.toByteArray(); - } - - private static byte[] encodeLong(long v) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - VarInt.encode(v, stream); - return stream.toByteArray(); - } - - private static int decodeInt(byte[] encoded) throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream(encoded); - return VarInt.decodeInt(stream); - } - - private static long decodeLong(byte[] encoded) throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream(encoded); - return VarInt.decodeLong(stream); - } - - @Test - public void decodeValues() throws IOException { - assertEquals(LONG_VALUES.length, LONG_ENCODED.length); - for (int i = 0; i < LONG_ENCODED.length; ++i) { - ByteArrayInputStream stream = new ByteArrayInputStream(LONG_ENCODED[i]); - long parsed = VarInt.decodeLong(stream); - assertEquals(LONG_VALUES[i], parsed); - assertEquals(-1, stream.read()); - } - - assertEquals(INT_VALUES.length, INT_ENCODED.length); - for (int i = 0; i < INT_ENCODED.length; ++i) { - ByteArrayInputStream stream = new ByteArrayInputStream(INT_ENCODED[i]); - int parsed = VarInt.decodeInt(stream); - assertEquals(INT_VALUES[i], parsed); - assertEquals(-1, stream.read()); - } - } - - @Test - public void encodeValuesAndGetLength() throws IOException { - assertEquals(LONG_VALUES.length, LONG_ENCODED.length); - for (int i = 0; i < LONG_VALUES.length; ++i) { - byte[] encoded = encodeLong(LONG_VALUES[i]); - assertThat(encoded, equalTo(LONG_ENCODED[i])); - assertEquals(LONG_ENCODED[i].length, VarInt.getLength(LONG_VALUES[i])); - } - - assertEquals(INT_VALUES.length, INT_ENCODED.length); - for (int i = 0; i < INT_VALUES.length; ++i) { - byte[] encoded = encodeInt(INT_VALUES[i]); - assertThat(encoded, equalTo(INT_ENCODED[i])); - assertEquals(INT_ENCODED[i].length, VarInt.getLength(INT_VALUES[i])); - } - } - - @Test - public void decodeThrowsExceptionForOverflow() throws IOException { - final byte[] tooLargeNumber = - { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x02 }; - - thrown.expect(IOException.class); - decodeLong(tooLargeNumber); - } - - @Test - public void decodeThrowsExceptionForIntOverflow() throws IOException { - byte[] encoded = encodeLong(1L << 32); - - thrown.expect(IOException.class); - decodeInt(encoded); - } - - @Test - public void decodeThrowsExceptionForIntUnderflow() throws IOException { - byte[] encoded = encodeLong(-1); - - thrown.expect(IOException.class); - decodeInt(encoded); - } - - @Test - public void decodeThrowsExceptionForNonterminated() throws IOException { - final byte[] nonTerminatedNumber = - { (byte) 0xff, (byte) 0xff }; - - thrown.expect(IOException.class); - decodeLong(nonTerminatedNumber); - } - - @Test - public void decodeParsesEncodedValues() throws IOException { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - for (int i = 10; i < Integer.MAX_VALUE; i = (int) (i * 1.1)) { - VarInt.encode(i, outStream); - VarInt.encode(-i, outStream); - } - for (long i = 10; i < Long.MAX_VALUE; i = (long) (i * 1.1)) { - VarInt.encode(i, outStream); - VarInt.encode(-i, outStream); - } - - ByteArrayInputStream inStream = - new ByteArrayInputStream(outStream.toByteArray()); - for (int i = 10; i < Integer.MAX_VALUE; i = (int) (i * 1.1)) { - assertEquals(i, VarInt.decodeInt(inStream)); - assertEquals(-i, VarInt.decodeInt(inStream)); - } - for (long i = 10; i < Long.MAX_VALUE; i = (long) (i * 1.1)) { - assertEquals(i, VarInt.decodeLong(inStream)); - assertEquals(-i, VarInt.decodeLong(inStream)); - } - } - - @Test - public void endOfFileThrowsException() throws Exception { - ByteArrayInputStream inStream = - new ByteArrayInputStream(new byte[0]); - thrown.expect(EOFException.class); - VarInt.decodeInt(inStream); - } - - @Test - public void unterminatedThrowsException() throws Exception { - byte[] e = encodeLong(Long.MAX_VALUE); - byte[] s = new byte[1]; - s[0] = e[0]; - ByteArrayInputStream inStream = new ByteArrayInputStream(s); - thrown.expect(IOException.class); - VarInt.decodeInt(inStream); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java deleted file mode 100644 index b1f89907d5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/WindowedValueTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo; -import com.google.cloud.dataflow.sdk.transforms.windowing.PaneInfo.Timing; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** Test case for {@link WindowedValue}. */ -@RunWith(JUnit4.class) -public class WindowedValueTest { - @Test - public void testWindowedValueCoder() throws CoderException { - Instant timestamp = new Instant(1234); - WindowedValue value = WindowedValue.of( - "abc", - new Instant(1234), - Arrays.asList(new IntervalWindow(timestamp, timestamp.plus(1000)), - new IntervalWindow(timestamp.plus(1000), timestamp.plus(2000))), - PaneInfo.NO_FIRING); - - Coder> windowedValueCoder = - WindowedValue.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); - - byte[] encodedValue = CoderUtils.encodeToByteArray(windowedValueCoder, value); - WindowedValue decodedValue = - CoderUtils.decodeFromByteArray(windowedValueCoder, encodedValue); - - Assert.assertEquals(value.getValue(), decodedValue.getValue()); - Assert.assertEquals(value.getTimestamp(), decodedValue.getTimestamp()); - Assert.assertArrayEquals(value.getWindows().toArray(), decodedValue.getWindows().toArray()); - } - - @Test - public void testExplodeWindowsInNoWindowsEmptyIterable() { - WindowedValue value = - WindowedValue.of( - "foo", Instant.now(), ImmutableList.of(), PaneInfo.NO_FIRING); - - assertThat(value.explodeWindows(), emptyIterable()); - } - - @Test - public void testExplodeWindowsInOneWindowEquals() { - Instant now = Instant.now(); - BoundedWindow window = new IntervalWindow(now.minus(1000L), now.plus(1000L)); - WindowedValue value = - WindowedValue.of("foo", now, window, PaneInfo.ON_TIME_AND_ONLY_FIRING); - - assertThat(Iterables.getOnlyElement(value.explodeWindows()), equalTo(value)); - } - - @Test - public void testExplodeWindowsManyWindowsMultipleWindowedValues() { - Instant now = Instant.now(); - BoundedWindow centerWindow = new IntervalWindow(now.minus(1000L), now.plus(1000L)); - BoundedWindow pastWindow = new IntervalWindow(now.minus(1500L), now.plus(500L)); - BoundedWindow futureWindow = new IntervalWindow(now.minus(500L), now.plus(1500L)); - BoundedWindow futureFutureWindow = new IntervalWindow(now, now.plus(2000L)); - PaneInfo pane = PaneInfo.createPane(false, false, Timing.ON_TIME, 3L, 0L); - WindowedValue value = - WindowedValue.of( - "foo", - now, - ImmutableList.of(pastWindow, centerWindow, futureWindow, futureFutureWindow), - pane); - - assertThat( - value.explodeWindows(), - containsInAnyOrder( - WindowedValue.of("foo", now, futureFutureWindow, pane), - WindowedValue.of("foo", now, futureWindow, pane), - WindowedValue.of("foo", now, centerWindow, pane), - WindowedValue.of("foo", now, pastWindow, pane))); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java deleted file mode 100644 index 8c079a6bd5..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util; - -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.common.io.ByteSource; -import com.google.common.io.CharSource; -import com.google.common.io.Files; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -/** - * Tests for the {@link ZipFiles} class. These tests make sure that the handling - * of zip-files works fine. - */ -@RunWith(JUnit4.class) -public class ZipFilesTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - private File tmpDir; - - @Rule - public TemporaryFolder tmpOutputFolder = new TemporaryFolder(); - private File zipFile; - - @Before - public void setUp() throws Exception { - tmpDir = tmpFolder.getRoot(); - zipFile = createZipFileHandle(); // the file is not actually created - } - - /** - * Verify that zipping and unzipping works fine. We zip a directory having - * some subdirectories, unzip it again and verify the structure to be in - * place. - */ - @Test - public void testZipWithSubdirectories() throws Exception { - File zipDir = new File(tmpDir, "zip"); - File subDir1 = new File(zipDir, "subDir1"); - File subDir2 = new File(subDir1, "subdir2"); - assertTrue(subDir2.mkdirs()); - createFileWithContents(subDir2, "myTextFile.txt", "Simple Text"); - - assertZipAndUnzipOfDirectoryMatchesOriginal(tmpDir); - } - - /** - * An empty subdirectory must have its own zip-entry. - */ - @Test - public void testEmptySubdirectoryHasZipEntry() throws Exception { - File zipDir = new File(tmpDir, "zip"); - File subDirEmpty = new File(zipDir, "subDirEmpty"); - assertTrue(subDirEmpty.mkdirs()); - - ZipFiles.zipDirectory(tmpDir, zipFile); - assertZipOnlyContains("zip/subDirEmpty/"); - } - - /** - * A directory with contents should not have a zip entry. - */ - @Test - public void testSubdirectoryWithContentsHasNoZipEntry() throws Exception { - File zipDir = new File(tmpDir, "zip"); - File subDirContent = new File(zipDir, "subdirContent"); - assertTrue(subDirContent.mkdirs()); - createFileWithContents(subDirContent, "myTextFile.txt", "Simple Text"); - - ZipFiles.zipDirectory(tmpDir, zipFile); - assertZipOnlyContains("zip/subdirContent/myTextFile.txt"); - } - - @Test - public void testZipDirectoryToOutputStream() throws Exception { - createFileWithContents(tmpDir, "myTextFile.txt", "Simple Text"); - File[] sourceFiles = tmpDir.listFiles(); - Arrays.sort(sourceFiles); - assertThat(sourceFiles, not(arrayWithSize(0))); - - try (FileOutputStream outputStream = new FileOutputStream(zipFile)) { - ZipFiles.zipDirectory(tmpDir, outputStream); - } - File outputDir = Files.createTempDir(); - ZipFiles.unzipFile(zipFile, outputDir); - File[] outputFiles = outputDir.listFiles(); - Arrays.sort(outputFiles); - - assertThat(outputFiles, arrayWithSize(sourceFiles.length)); - for (int i = 0; i < sourceFiles.length; i++) { - compareFileContents(sourceFiles[i], outputFiles[i]); - } - - removeRecursive(outputDir.toPath()); - assertTrue(zipFile.delete()); - } - - @Test - public void testEntries() throws Exception { - File zipDir = new File(tmpDir, "zip"); - File subDir1 = new File(zipDir, "subDir1"); - File subDir2 = new File(subDir1, "subdir2"); - assertTrue(subDir2.mkdirs()); - createFileWithContents(subDir2, "myTextFile.txt", "Simple Text"); - - ZipFiles.zipDirectory(tmpDir, zipFile); - - ZipFile zip = new ZipFile(zipFile); - try { - Enumeration entries = zip.entries(); - for (ZipEntry entry : ZipFiles.entries(zip)) { - assertTrue(entries.hasMoreElements()); - // ZipEntry doesn't override equals - assertEquals(entry.getName(), entries.nextElement().getName()); - } - assertFalse(entries.hasMoreElements()); - } finally { - zip.close(); - } - } - - @Test - public void testAsByteSource() throws Exception { - File zipDir = new File(tmpDir, "zip"); - assertTrue(zipDir.mkdirs()); - createFileWithContents(zipDir, "myTextFile.txt", "Simple Text"); - - ZipFiles.zipDirectory(tmpDir, zipFile); - - try (ZipFile zip = new ZipFile(zipFile)) { - ZipEntry entry = zip.getEntry("zip/myTextFile.txt"); - ByteSource byteSource = ZipFiles.asByteSource(zip, entry); - if (entry.getSize() != -1) { - assertEquals(entry.getSize(), byteSource.size()); - } - assertArrayEquals("Simple Text".getBytes(StandardCharsets.UTF_8), byteSource.read()); - } - } - - @Test - public void testAsCharSource() throws Exception { - File zipDir = new File(tmpDir, "zip"); - assertTrue(zipDir.mkdirs()); - createFileWithContents(zipDir, "myTextFile.txt", "Simple Text"); - - ZipFiles.zipDirectory(tmpDir, zipFile); - - try (ZipFile zip = new ZipFile(zipFile)) { - ZipEntry entry = zip.getEntry("zip/myTextFile.txt"); - CharSource charSource = ZipFiles.asCharSource(zip, entry, StandardCharsets.UTF_8); - assertEquals("Simple Text", charSource.read()); - } - } - - private void assertZipOnlyContains(String zipFileEntry) throws IOException { - try (ZipFile zippedFile = new ZipFile(zipFile)) { - assertEquals(1, zippedFile.size()); - ZipEntry entry = zippedFile.entries().nextElement(); - assertEquals(zipFileEntry, entry.getName()); - } - } - - /** - * try to unzip to a non-existent directory and make sure that it fails. - */ - @Test - public void testInvalidTargetDirectory() throws IOException { - File zipDir = new File(tmpDir, "zipdir"); - assertTrue(zipDir.mkdir()); - ZipFiles.zipDirectory(tmpDir, zipFile); - File invalidDirectory = new File("/foo/bar"); - assertTrue(!invalidDirectory.exists()); - try { - ZipFiles.unzipFile(zipFile, invalidDirectory); - fail("We expect the IllegalArgumentException, but it never occured"); - } catch (IllegalArgumentException e) { - // This is the expected exception - we passed the test. - } - } - - /** - * Try to unzip to an existing directory, but failing to create directories. - */ - @Test - public void testDirectoryCreateFailed() throws IOException { - File zipDir = new File(tmpDir, "zipdir"); - assertTrue(zipDir.mkdir()); - ZipFiles.zipDirectory(tmpDir, zipFile); - File targetDirectory = Files.createTempDir(); - // Touch a file where the directory should be. - Files.touch(new File(targetDirectory, "zipdir")); - try { - ZipFiles.unzipFile(zipFile, targetDirectory); - fail("We expect the IOException, but it never occured"); - } catch (IOException e) { - // This is the expected exception - we passed the test. - } - } - - /** - * zip and unzip a certain directory, and verify the content afterward to be - * identical. - * @param sourceDir the directory to zip - */ - private void assertZipAndUnzipOfDirectoryMatchesOriginal(File sourceDir) throws IOException { - File[] sourceFiles = sourceDir.listFiles(); - Arrays.sort(sourceFiles); - - File zipFile = createZipFileHandle(); - ZipFiles.zipDirectory(sourceDir, zipFile); - File outputDir = Files.createTempDir(); - ZipFiles.unzipFile(zipFile, outputDir); - File[] outputFiles = outputDir.listFiles(); - Arrays.sort(outputFiles); - - assertThat(outputFiles, arrayWithSize(sourceFiles.length)); - for (int i = 0; i < sourceFiles.length; i++) { - compareFileContents(sourceFiles[i], outputFiles[i]); - } - - removeRecursive(outputDir.toPath()); - assertTrue(zipFile.delete()); - } - - /** - * Compare the content of two files or directories recursively. - * @param expected the expected directory or file content - * @param actual the actual directory or file content - */ - private void compareFileContents(File expected, File actual) throws IOException { - assertEquals(expected.isDirectory(), actual.isDirectory()); - assertEquals(expected.getName(), actual.getName()); - if (expected.isDirectory()) { - // Go through the children step by step. - File[] expectedChildren = expected.listFiles(); - Arrays.sort(expectedChildren); - File[] actualChildren = actual.listFiles(); - Arrays.sort(actualChildren); - assertThat(actualChildren, arrayWithSize(expectedChildren.length)); - for (int i = 0; i < expectedChildren.length; i++) { - compareFileContents(expectedChildren[i], actualChildren[i]); - } - } else { - // Compare the file content itself. - assertTrue(Files.equal(expected, actual)); - } - } - - /** - * Create a File object to which we can safely zip a file. - */ - private File createZipFileHandle() throws IOException { - File zipFile = File.createTempFile("test", "zip", tmpOutputFolder.getRoot()); - assertTrue(zipFile.delete()); - return zipFile; - } - - // This is not generally safe as it does not handle symlinks, etc. However it is safe - // enough for these tests. - private static void removeRecursive(Path path) throws IOException { - Iterable files = Files.fileTreeTraverser().postOrderTraversal(path.toFile()); - for (File f : files) { - java.nio.file.Files.delete(f.toPath()); - } - } - - /** Create file dir/fileName with contents fileContents. */ - private void createFileWithContents(File dir, String fileName, String fileContents) - throws IOException { - File txtFile = new File(dir, fileName); - Files.asCharSink(txtFile, StandardCharsets.UTF_8).write(fileContents); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java deleted file mode 100644 index 397743637e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterSetTest.java +++ /dev/null @@ -1,345 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Unit tests for {@link CounterSet}. - */ -@RunWith(JUnit4.class) -public class CounterSetTest { - private CounterSet set; - - private static final String counterName = "counter-name"; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setup() { - set = new CounterSet(); - } - - @Test - public void testAddWithDifferentNamesAddsAll() { - Counter c1 = Counter.longs("c1", SUM); - Counter c2 = Counter.ints("c2", MAX); - - boolean c1Add = set.add(c1); - boolean c2Add = set.add(c2); - - assertTrue(c1Add); - assertTrue(c2Add); - assertThat(set, containsInAnyOrder(c1, c2)); - } - - @Test - public void testAddWithAlreadyPresentNameReturnsFalse() { - Counter c1 = Counter.longs("c1", SUM); - Counter c1Dup = Counter.longs("c1", SUM); - - boolean c1Add = set.add(c1); - boolean c1DupAdd = set.add(c1Dup); - - assertTrue(c1Add); - assertFalse(c1DupAdd); - assertThat(set, containsInAnyOrder((Counter) c1)); - } - - @Test - public void testAddOrReuseWithAlreadyPresentReturnsPresent() { - Counter c1 = Counter.longs("c1", SUM); - Counter c1Dup = Counter.longs("c1", SUM); - - Counter c1AddResult = set.addOrReuseCounter(c1); - Counter c1DupAddResult = set.addOrReuseCounter(c1Dup); - - assertSame(c1, c1AddResult); - assertSame(c1AddResult, c1DupAddResult); - assertThat(set, containsInAnyOrder((Counter) c1)); - } - - @Test - public void testAddOrReuseWithNoCounterReturnsProvided() { - Counter c1 = Counter.longs("c1", SUM); - - Counter c1AddResult = set.addOrReuseCounter(c1); - - assertSame(c1, c1AddResult); - assertThat(set, containsInAnyOrder((Counter) c1)); - } - - @Test - public void testAddOrReuseWithIncompatibleTypesThrowsException() { - Counter c1 = Counter.longs("c1", SUM); - Counter c1Incompatible = Counter.ints("c1", MAX); - - set.addOrReuseCounter(c1); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Counter " + c1Incompatible - + " duplicates incompatible counter " + c1 + " in " + set); - - set.addOrReuseCounter(c1Incompatible); - } - - @Test - public void testMergeWithDifferentNamesAddsAll() { - Counter c1 = Counter.longs("c1", SUM); - Counter c2 = Counter.ints("c2", MAX); - - set.add(c1); - set.add(c2); - - CounterSet newSet = new CounterSet(); - newSet.merge(set); - - assertThat(newSet, containsInAnyOrder(c1, c2)); - } - - @SuppressWarnings("unchecked") - @Test - public void testMergeWithSameNamesMerges() { - Counter c1 = Counter.longs("c1", SUM); - Counter c2 = Counter.ints("c2", MAX); - - set.add(c1); - set.add(c2); - - c1.addValue(3L); - c2.addValue(22); - - CounterSet newSet = new CounterSet(); - Counter c1Prime = Counter.longs("c1", SUM); - Counter c2Prime = Counter.ints("c2", MAX); - - c1Prime.addValue(7L); - c2Prime.addValue(14); - - newSet.add(c1Prime); - newSet.add(c2Prime); - - newSet.merge(set); - - assertThat((Counter) newSet.getExistingCounter("c1"), equalTo(c1Prime)); - assertThat((Long) newSet.getExistingCounter("c1").getAggregate(), equalTo(10L)); - - assertThat((Counter) newSet.getExistingCounter("c2"), equalTo(c2Prime)); - assertThat((Integer) newSet.getExistingCounter("c2").getAggregate(), equalTo(22)); - } - - @SuppressWarnings("unchecked") - @Test - public void testMergeWithIncompatibleTypesThrowsException() { - Counter c1 = Counter.longs("c1", SUM); - - set.add(c1); - - CounterSet newSet = new CounterSet(); - Counter c1Prime = Counter.longs("c1", MAX); - - newSet.add(c1Prime); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("c1"); - thrown.expectMessage("incompatible counters with the same name"); - - newSet.merge(set); - } - - @Test - public void testAddCounterMutatorAddCounterAddsCounter() { - Counter c1 = Counter.longs("c1", SUM); - - Counter addC1Result = set.getAddCounterMutator().addCounter(c1); - - assertSame(c1, addC1Result); - assertThat(set, containsInAnyOrder((Counter) c1)); - } - - @Test - public void testAddCounterMutatorAddEqualCounterReusesCounter() { - Counter c1 = Counter.longs("c1", SUM); - Counter c1dup = Counter.longs("c1", SUM); - - Counter addC1Result = set.getAddCounterMutator().addCounter(c1); - Counter addC1DupResult = set.getAddCounterMutator().addCounter(c1dup); - - assertThat(set, containsInAnyOrder((Counter) c1)); - assertSame(c1, addC1Result); - assertSame(c1, addC1DupResult); - } - - @Test - public void testAddCounterMutatorIncompatibleTypesThrowsException() { - Counter c1 = Counter.longs("c1", SUM); - Counter c1Incompatible = Counter.longs("c1", MAX); - - set.getAddCounterMutator().addCounter(c1); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Counter " + c1Incompatible - + " duplicates incompatible counter " + c1 + " in " + set); - - set.getAddCounterMutator().addCounter(c1Incompatible); - } - - @Test - public void testAddCounterMutatorAddMultipleCounters() { - Counter c1 = Counter.longs("c1", SUM); - Counter c2 = Counter.longs("c2", MAX); - - set.getAddCounterMutator().addCounter(c1); - set.getAddCounterMutator().addCounter(c2); - - assertThat(set, containsInAnyOrder(c1, c2)); - } - - @Test - public void testNullCounterBeforeAdd() { - // getting a nonexistent counter returns null, then after add a value is - // returned - assertThat(set.getExistingCounter(counterName), is(nullValue())); - Counter counterAddCheck = Counter.ints(counterName, SUM); - set.addNewCounter(counterAddCheck); - assertThat(set.getExistingCounter(counterName), is(notNullValue())); - } - - @Test - public void testAddDuplicate() { - // adding an already existing counter using addNewCounter throws an exception - Counter counterAddCheck = Counter.ints(counterName, SUM); - set.addNewCounter(counterAddCheck); - thrown.expect(IllegalArgumentException.class); - set.addNewCounter(counterAddCheck); - assertThat(set.getExistingCounter(counterName), is(notNullValue())); - } - - /** - * CounterSet mutators with different contexts should not conflict with one another. - * The below tests creates a few counter mutators, some with and without an associated - * NameContext, and verify the counters added through the mutators are as - * expected. - */ - @Test - public void testMutatorsDoNotConflict() { - NameContext context = NameContext.create("original_name", "optimized_name"); - Counter.Name structuredName = - Counter.Name.withOriginalName(counterName, context); - - // Create an unstructured counter with a value - Counter counterUnstructured = Counter.ints(counterName, SUM); - set.addNewCounter(counterUnstructured); - counterUnstructured.addValue(10); - - // create a counter with the same name, but a different context and value - CounterSet.AddCounterMutator adder = set.getAddCounterMutator(context); - @SuppressWarnings("unchecked") - Counter counterStructured = Counter.ints(structuredName, SUM); - adder.addCounter(counterStructured); - counterStructured.addValue(-10); - - // now read back both counters and check values - @SuppressWarnings("unchecked") - Counter counterUnstructuredToo = - (Counter) set.getExistingCounter(counterName); - - @SuppressWarnings("unchecked") - Counter counterStructuredToo = - (Counter) set.getExistingCounter(structuredName); - assertThat(counterUnstructuredToo.getAggregate(), is(10)); - assertThat(counterStructuredToo.getAggregate(), is(-10)); - - // grab a regular mutator, first check that adding an existing counter simply reuses - adder = set.getAddCounterMutator(); - int size = set.size(); - counterUnstructuredToo = adder.addCounter(counterUnstructuredToo); - assertThat(set.size(), is(size)); - assertThat(counterUnstructuredToo.getAggregate(), is(10)); - - // This counter should still be unstructured, ie the two mutators should not interfere with one - // another - Counter.Name unstructured = counterUnstructuredToo.getUniqueName(); - assertThat(unstructured.counterName(), is(notNullValue())); - assertThat(unstructured.contextSystemName(), is(nullValue())); - assertThat(unstructured.contextOriginalName(), is(nullValue())); - } - - /** - * Adding counters to a CounterSet via mutator should be equivalent to - * directly adding counters to a CounterSet. - */ - @Test - public void testMutatorsAndConstructorAreEquivalent() { - // First a regular counterset created with an array of counters - CounterSet cs1 = - new CounterSet( - Counter.longs("counter-1", SUM).resetToValue(0L), - Counter.longs("counter-2", SUM).resetToValue(0L)); - - // Now add via counter mutator - CounterSet cs2 = new CounterSet(); - CounterSet.AddCounterMutator adder = cs2.getAddCounterMutator(); - adder.addCounter(Counter.longs("counter-1", SUM).resetToValue(0L)); - adder.addCounter(Counter.longs("counter-2", SUM).resetToValue(0L)); - assertEquals(cs1, cs2); - - // Now add unstructured counters with a counter mutator - CounterSet cs3 = new CounterSet(); - NameContext context = NameContext.create("original_name", "optimized_name"); - adder = cs3.getAddCounterMutator(context); - Counter c1 = Counter.longs("counter-1", SUM).resetToValue(0L); - Counter c2 = Counter.longs("counter-2", SUM).resetToValue(0L); - adder.addCounter(c1); - adder.addCounter(c2); - assertEquals(cs3, cs2); - - // now try two cases with structured names - c1 = Counter.longs( - Counter.Name.withOriginalName( - "counter-1", context), SUM).resetToValue(0L); - c2 = Counter.longs( - Counter.Name.withOriginalName( - "counter-2", context), SUM).resetToValue(0L); - cs1 = new CounterSet(c1, c2); - - cs2 = new CounterSet(); - adder = cs2.getAddCounterMutator(context); - adder.addCounter(c1); - adder.addCounter(c2); - assertEquals(cs1, cs2); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java deleted file mode 100644 index e913f1a969..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTest.java +++ /dev/null @@ -1,747 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.cloud.dataflow.sdk.util.Values.asDouble; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.AND; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MAX; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MIN; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.OR; -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.SUM; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.util.common.Counter.CommitState; -import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Unit tests for the {@link Counter} API. - */ -@RunWith(JUnit4.class) -public class CounterTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static void flush(Counter c) { - switch (c.getKind()) { - case SUM: - case MAX: - case MIN: - case AND: - case OR: - c.getAndResetDelta(); - break; - case MEAN: - c.getAndResetMeanDelta(); - break; - default: - throw new IllegalArgumentException("Unknown counter kind " + c.getKind()); - } - } - - private static final double EPSILON = 0.00000000001; - - @Test - public void testCompatibility() { - // Equal counters are compatible, of all kinds. - assertTrue( - Counter.longs("c", SUM).isCompatibleWith(Counter.longs("c", SUM))); - assertTrue( - Counter.ints("c", SUM).isCompatibleWith(Counter.ints("c", SUM))); - assertTrue( - Counter.doubles("c", SUM).isCompatibleWith(Counter.doubles("c", SUM))); - assertTrue( - Counter.booleans("c", OR).isCompatibleWith( - Counter.booleans("c", OR))); - - // The name, kind, and type of the counter must match. - assertFalse( - Counter.longs("c", SUM).isCompatibleWith(Counter.longs("c2", SUM))); - assertFalse( - Counter.longs("c", SUM).isCompatibleWith(Counter.longs("c", MAX))); - assertFalse( - Counter.longs("c", SUM).isCompatibleWith(Counter.ints("c", SUM))); - - // The value of the counters are ignored. - assertTrue( - Counter.longs("c", SUM).resetToValue(666L).isCompatibleWith( - Counter.longs("c", SUM).resetToValue(42L))); - - // now a structured counter should not be compatible - final String counterName = "counter-name"; - Counter counter1 = Counter.ints(counterName, SUM); - NameContext context = NameContext.create("original_name", "optimized_name"); - - Counter counterStructured = Counter.ints( - Counter.Name.withOriginalName(counterName, context), SUM); - assertThat(counter1.isCompatibleWith(counterStructured), is(false)); - assertThat(counterStructured.isCompatibleWith(counter1), is(false)); - } - - private void assertOK(long total, long delta, Counter c) { - assertEquals(total, c.getAggregate().longValue()); - assertEquals(delta, c.getAndResetDelta().longValue()); - } - - private void assertOK(double total, double delta, Counter c) { - assertEquals(total, asDouble(c.getAggregate()), EPSILON); - assertEquals(delta, asDouble(c.getAndResetDelta()), EPSILON); - } - - - // Tests for SUM. - - @Test - public void testSumLong() { - Counter c = Counter.longs("sum-long", SUM); - long expectedTotal = 0; - long expectedDelta = 0; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(13L).addValue(42L).addValue(0L); - expectedTotal += 55; - expectedDelta += 55; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(120L).addValue(17L).addValue(37L); - expectedTotal = expectedDelta = 174; - assertOK(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = 0; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(15L).addValue(42L); - expectedTotal += 57; - expectedDelta += 57; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(100L).addValue(17L).addValue(49L); - expectedTotal = expectedDelta = 166; - assertOK(expectedTotal, expectedDelta, c); - - Counter other = Counter.longs("sum-long", SUM); - other.addValue(12L); - expectedDelta = 12L; - expectedTotal += 12L; - c.merge(other); - assertOK(expectedTotal, expectedDelta, c); - } - - @Test - public void testSumDouble() { - Counter c = Counter.doubles("sum-double", SUM); - double expectedTotal = 0.0; - double expectedDelta = 0.0; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(Math.E).addValue(Math.PI).addValue(0.0); - expectedTotal += Math.E + Math.PI; - expectedDelta += Math.E + Math.PI; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(Math.sqrt(2)).addValue(2 * Math.PI).addValue(3 * Math.E); - expectedTotal = expectedDelta = Math.sqrt(2) + 2 * Math.PI + 3 * Math.E; - assertOK(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = 0.0; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(7 * Math.PI).addValue(5 * Math.E); - expectedTotal += 7 * Math.PI + 5 * Math.E; - expectedDelta += 7 * Math.PI + 5 * Math.E; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(Math.sqrt(17)).addValue(17.0).addValue(49.0); - expectedTotal = expectedDelta = Math.sqrt(17.0) + 17.0 + 49.0; - assertOK(expectedTotal, expectedDelta, c); - - Counter other = Counter.doubles("sum-double", SUM); - other.addValue(12 * Math.PI); - expectedDelta = 12 * Math.PI; - expectedTotal += 12 * Math.PI; - c.merge(other); - assertOK(expectedTotal, expectedDelta, c); - } - - - // Tests for MAX. - - @Test - public void testMaxLong() { - Counter c = Counter.longs("max-long", MAX); - long expectedTotal = Long.MIN_VALUE; - long expectedDelta = Long.MIN_VALUE; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(13L).addValue(42L).addValue(Long.MIN_VALUE); - expectedTotal = expectedDelta = 42; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(120L).addValue(17L).addValue(37L); - expectedTotal = expectedDelta = 120; - assertOK(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = Long.MIN_VALUE; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(42L).addValue(15L); - expectedDelta = 42; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(100L).addValue(171L).addValue(49L); - expectedTotal = expectedDelta = 171; - assertOK(expectedTotal, expectedDelta, c); - - Counter other = Counter.longs("max-long", MAX); - other.addValue(12L); - expectedDelta = 12L; - c.merge(other); - assertOK(expectedTotal, expectedDelta, c); - } - - @Test - public void testMaxDouble() { - Counter c = Counter.doubles("max-double", MAX); - double expectedTotal = Double.NEGATIVE_INFINITY; - double expectedDelta = Double.NEGATIVE_INFINITY; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(Math.E).addValue(Math.PI).addValue(Double.NEGATIVE_INFINITY); - expectedTotal = expectedDelta = Math.PI; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(Math.sqrt(12345)).addValue(2 * Math.PI).addValue(3 * Math.E); - expectedTotal = expectedDelta = Math.sqrt(12345); - assertOK(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = Double.NEGATIVE_INFINITY; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(7 * Math.PI).addValue(5 * Math.E); - expectedDelta = 7 * Math.PI; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(Math.sqrt(17)).addValue(171.0).addValue(49.0); - expectedTotal = expectedDelta = 171.0; - assertOK(expectedTotal, expectedDelta, c); - - Counter other = Counter.doubles("max-double", MAX); - other.addValue(12 * Math.PI); - expectedDelta = 12 * Math.PI; - c.merge(other); - assertOK(expectedTotal, expectedDelta, c); - } - - - // Tests for MIN. - - @Test - public void testMinLong() { - Counter c = Counter.longs("min-long", MIN); - long expectedTotal = Long.MAX_VALUE; - long expectedDelta = Long.MAX_VALUE; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(13L).addValue(42L).addValue(Long.MAX_VALUE); - expectedTotal = expectedDelta = 13; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(120L).addValue(17L).addValue(37L); - expectedTotal = expectedDelta = 17; - assertOK(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = Long.MAX_VALUE; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(42L).addValue(18L); - expectedDelta = 18; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(100L).addValue(171L).addValue(49L); - expectedTotal = expectedDelta = 49; - assertOK(expectedTotal, expectedDelta, c); - - Counter other = Counter.longs("min-long", MIN); - other.addValue(42L); - expectedTotal = expectedDelta = 42L; - c.merge(other); - assertOK(expectedTotal, expectedDelta, c); - } - - @Test - public void testMinDouble() { - Counter c = Counter.doubles("min-double", MIN); - double expectedTotal = Double.POSITIVE_INFINITY; - double expectedDelta = Double.POSITIVE_INFINITY; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(Math.E).addValue(Math.PI).addValue(Double.POSITIVE_INFINITY); - expectedTotal = expectedDelta = Math.E; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(Math.sqrt(12345)).addValue(2 * Math.PI).addValue(3 * Math.E); - expectedTotal = expectedDelta = 2 * Math.PI; - assertOK(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = Double.POSITIVE_INFINITY; - assertOK(expectedTotal, expectedDelta, c); - - c.addValue(7 * Math.PI).addValue(5 * Math.E); - expectedDelta = 5 * Math.E; - assertOK(expectedTotal, expectedDelta, c); - - c.resetToValue(Math.sqrt(17)).addValue(171.0).addValue(0.0); - expectedTotal = expectedDelta = 0.0; - assertOK(expectedTotal, expectedDelta, c); - - Counter other = Counter.doubles("min-double", MIN); - other.addValue(42 * Math.E); - expectedDelta = 42 * Math.E; - c.merge(other); - assertOK(expectedTotal, expectedDelta, c); - } - - - // Tests for MEAN. - - private void assertMean(long s, long sd, long c, long cd, Counter cn) { - CounterMean mean = cn.getMean(); - CounterMean deltaMean = cn.getAndResetMeanDelta(); - assertEquals(s, mean.getAggregate().longValue()); - assertEquals(sd, deltaMean.getAggregate().longValue()); - assertEquals(c, mean.getCount()); - assertEquals(cd, deltaMean.getCount()); - } - - private void assertMean(double s, double sd, long c, long cd, - Counter cn) { - CounterMean mean = cn.getMean(); - CounterMean deltaMean = cn.getAndResetMeanDelta(); - assertEquals(s, mean.getAggregate().doubleValue(), EPSILON); - assertEquals(sd, deltaMean.getAggregate().doubleValue(), EPSILON); - assertEquals(c, mean.getCount()); - assertEquals(cd, deltaMean.getCount()); - } - - @Test - public void testMeanLong() { - Counter c = Counter.longs("mean-long", MEAN); - long expTotal = 0; - long expDelta = 0; - long expCountTotal = 0; - long expCountDelta = 0; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.addValue(13L).addValue(42L).addValue(0L); - expTotal += 55; - expDelta += 55; - expCountTotal += 3; - expCountDelta += 3; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.resetMeanToValue(1L, 120L).addValue(17L).addValue(37L); - expTotal = expDelta = 174; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - flush(c); - expDelta = 0; - expCountDelta = 0; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.addValue(15L).addValue(42L); - expTotal += 57; - expDelta += 57; - expCountTotal += 2; - expCountDelta += 2; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.resetMeanToValue(3L, 100L).addValue(17L).addValue(49L); - expTotal = expDelta = 166; - expCountTotal = expCountDelta = 5; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - Counter other = Counter.longs("mean-long", MEAN); - other.addValue(12L).addValue(44L).addValue(-5L); - expTotal += 12L + 44L - 5L; - expDelta += 12L + 44L - 5L; - expCountTotal += 3; - expCountDelta += 3; - c.merge(other); - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - } - - @Test - public void testMeanDouble() { - Counter c = Counter.doubles("mean-double", MEAN); - double expTotal = 0.0; - double expDelta = 0.0; - long expCountTotal = 0; - long expCountDelta = 0; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.addValue(Math.E).addValue(Math.PI).addValue(0.0); - expTotal += Math.E + Math.PI; - expDelta += Math.E + Math.PI; - expCountTotal += 3; - expCountDelta += 3; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.resetMeanToValue(1L, Math.sqrt(2)).addValue(2 * Math.PI) - .addValue(3 * Math.E); - expTotal = expDelta = Math.sqrt(2) + 2 * Math.PI + 3 * Math.E; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - flush(c); - expDelta = 0.0; - expCountDelta = 0; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.addValue(7 * Math.PI).addValue(5 * Math.E); - expTotal += 7 * Math.PI + 5 * Math.E; - expDelta += 7 * Math.PI + 5 * Math.E; - expCountTotal += 2; - expCountDelta += 2; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - c.resetMeanToValue(3L, Math.sqrt(17)).addValue(17.0).addValue(49.0); - expTotal = expDelta = Math.sqrt(17.0) + 17.0 + 49.0; - expCountTotal = expCountDelta = 5; - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - - Counter other = Counter.doubles("mean-double", MEAN); - other.addValue(3 * Math.PI).addValue(12 * Math.E); - expTotal += 3 * Math.PI + 12 * Math.E; - expDelta += 3 * Math.PI + 12 * Math.E; - expCountTotal += 2; - expCountDelta += 2; - c.merge(other); - assertMean(expTotal, expDelta, expCountTotal, expCountDelta, c); - } - - - // Test for AND and OR. - private void assertBool(boolean total, boolean delta, Counter c) { - assertEquals(total, c.getAggregate().booleanValue()); - assertEquals(delta, c.getAndResetDelta().booleanValue()); - } - - @Test - public void testBoolAnd() { - Counter c = Counter.booleans("bool-and", AND); - boolean expectedTotal = true; - boolean expectedDelta = true; - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(true); - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(false); - expectedTotal = expectedDelta = false; - assertBool(expectedTotal, expectedDelta, c); - - c.resetToValue(true).addValue(true); - expectedTotal = expectedDelta = true; - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(false); - expectedTotal = expectedDelta = false; - assertBool(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = true; - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(false); - expectedDelta = false; - assertBool(expectedTotal, expectedDelta, c); - } - - @Test - public void testBoolOr() { - Counter c = Counter.booleans("bool-or", OR); - boolean expectedTotal = false; - boolean expectedDelta = false; - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(false); - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(true); - expectedTotal = expectedDelta = true; - assertBool(expectedTotal, expectedDelta, c); - - c.resetToValue(false).addValue(false); - expectedTotal = expectedDelta = false; - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(true); - expectedTotal = expectedDelta = true; - assertBool(expectedTotal, expectedDelta, c); - - flush(c); - expectedDelta = false; - assertBool(expectedTotal, expectedDelta, c); - - c.addValue(true); - expectedDelta = true; - assertBool(expectedTotal, expectedDelta, c); - } - - // Incompatibility tests. - - @Test(expected = IllegalArgumentException.class) - public void testSumBool() { - Counter.booleans("counter", SUM); - } - - @Test(expected = IllegalArgumentException.class) - public void testMinBool() { - Counter.booleans("counter", MIN); - } - - @Test(expected = IllegalArgumentException.class) - public void testMaxBool() { - Counter.booleans("counter", MAX); - } - - @Test(expected = IllegalArgumentException.class) - public void testMeanBool() { - Counter.booleans("counter", MEAN); - } - - @Test(expected = IllegalArgumentException.class) - public void testAndLong() { - Counter.longs("counter", AND); - } - - @Test(expected = IllegalArgumentException.class) - public void testAndDouble() { - Counter.doubles("counter", AND); - } - - @Test(expected = IllegalArgumentException.class) - public void testOrLong() { - Counter.longs("counter", OR); - } - - @Test(expected = IllegalArgumentException.class) - public void testOrDouble() { - Counter.doubles("counter", OR); - } - - @Test - public void testMergeIncompatibleCounters() { - Counter longSums = Counter.longs("longsums", SUM); - Counter longMean = Counter.longs("longmean", MEAN); - Counter longMin = Counter.longs("longmin", MIN); - - Counter otherLongSums = Counter.longs("othersums", SUM); - Counter otherLongMean = Counter.longs("otherlongmean", MEAN); - - Counter doubleSums = Counter.doubles("doublesums", SUM); - Counter doubleMean = Counter.doubles("doublemean", MEAN); - - Counter boolAnd = Counter.booleans("and", AND); - Counter boolOr = Counter.booleans("or", OR); - - List> longCounters = - Arrays.asList(longSums, longMean, longMin, otherLongSums, otherLongMean); - for (Counter left : longCounters) { - for (Counter right : longCounters) { - if (left != right) { - assertIncompatibleMerge(left, right); - } - } - } - - assertIncompatibleMerge(doubleSums, doubleMean); - assertIncompatibleMerge(boolAnd, boolOr); - } - - private void assertIncompatibleMerge(Counter left, Counter right) { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Counters"); - thrown.expectMessage("are incompatible"); - left.merge(right); - } - - @Test - public void testDirtyBit() { - Counter longSum = Counter.longs("long-sum", SUM); - Counter longMean = Counter.longs("long-mean", MEAN); - Counter doubleSum = Counter.doubles("double-sum", SUM); - Counter doubleMean = Counter.doubles("double-sum", MEAN); - Counter intSum = Counter.ints("int-sum", SUM); - Counter intMean = Counter.ints("int-sum", MEAN); - Counter boolAnd = Counter.booleans("and", AND); - - // Test counters are not dirty and are COMMITTED initially. - assertFalse(longSum.isDirty()); - assertFalse(longMean.isDirty()); - assertFalse(doubleSum.isDirty()); - assertFalse(doubleMean.isDirty()); - assertFalse(intSum.isDirty()); - assertFalse(intMean.isDirty()); - assertFalse(boolAnd.isDirty()); - - assertEquals(CommitState.COMMITTED, longSum.commitState.get()); - assertEquals(CommitState.COMMITTED, longMean.commitState.get()); - assertEquals(CommitState.COMMITTED, doubleSum.commitState.get()); - assertEquals(CommitState.COMMITTED, doubleMean.commitState.get()); - assertEquals(CommitState.COMMITTED, intSum.commitState.get()); - assertEquals(CommitState.COMMITTED, intMean.commitState.get()); - assertEquals(CommitState.COMMITTED, boolAnd.commitState.get()); - - // Test counters are dirty after mutating. - longSum.addValue(1L); - longMean.resetMeanToValue(1L, 1L); - doubleSum.addValue(1.0); - doubleMean.resetMeanToValue(1L, 1.0); - intSum.addValue(1); - intMean.resetMeanToValue(1, 1); - boolAnd.addValue(true); - - assertTrue(longSum.isDirty()); - assertTrue(longMean.isDirty()); - assertTrue(doubleSum.isDirty()); - assertTrue(doubleMean.isDirty()); - assertTrue(intSum.isDirty()); - assertTrue(intMean.isDirty()); - assertTrue(boolAnd.isDirty()); - - assertEquals(CommitState.DIRTY, longSum.commitState.get()); - assertEquals(CommitState.DIRTY, longMean.commitState.get()); - assertEquals(CommitState.DIRTY, doubleSum.commitState.get()); - assertEquals(CommitState.DIRTY, doubleMean.commitState.get()); - assertEquals(CommitState.DIRTY, intSum.commitState.get()); - assertEquals(CommitState.DIRTY, intMean.commitState.get()); - assertEquals(CommitState.DIRTY, boolAnd.commitState.get()); - - // Test counters are dirty and are COMMITTING. - assertTrue(longSum.committing()); - assertTrue(longMean.committing()); - assertTrue(doubleSum.committing()); - assertTrue(doubleMean.committing()); - assertTrue(intSum.committing()); - assertTrue(intMean.committing()); - assertTrue(boolAnd.committing()); - - assertTrue(longSum.isDirty()); - assertTrue(longMean.isDirty()); - assertTrue(doubleSum.isDirty()); - assertTrue(doubleMean.isDirty()); - assertTrue(intSum.isDirty()); - assertTrue(intMean.isDirty()); - assertTrue(boolAnd.isDirty()); - - assertEquals(CommitState.COMMITTING, longSum.commitState.get()); - assertEquals(CommitState.COMMITTING, longMean.commitState.get()); - assertEquals(CommitState.COMMITTING, doubleSum.commitState.get()); - assertEquals(CommitState.COMMITTING, doubleMean.commitState.get()); - assertEquals(CommitState.COMMITTING, intSum.commitState.get()); - assertEquals(CommitState.COMMITTING, intMean.commitState.get()); - assertEquals(CommitState.COMMITTING, boolAnd.commitState.get()); - - // Test counters are dirty again after mutating. - longSum.addValue(1L); - longMean.resetMeanToValue(1L, 1L); - doubleSum.addValue(1.0); - doubleMean.resetMeanToValue(1L, 1.0); - intSum.addValue(1); - intMean.resetMeanToValue(1, 1); - boolAnd.addValue(true); - - assertFalse(longSum.committed()); - assertFalse(longMean.committed()); - assertFalse(doubleSum.committed()); - assertFalse(doubleMean.committed()); - assertFalse(intSum.committed()); - assertFalse(intMean.committed()); - assertFalse(boolAnd.committed()); - - assertTrue(longSum.isDirty()); - assertTrue(longMean.isDirty()); - assertTrue(doubleSum.isDirty()); - assertTrue(doubleMean.isDirty()); - assertTrue(intSum.isDirty()); - assertTrue(intMean.isDirty()); - assertTrue(boolAnd.isDirty()); - - assertEquals(CommitState.DIRTY, longSum.commitState.get()); - assertEquals(CommitState.DIRTY, longMean.commitState.get()); - assertEquals(CommitState.DIRTY, doubleSum.commitState.get()); - assertEquals(CommitState.DIRTY, doubleMean.commitState.get()); - assertEquals(CommitState.DIRTY, intSum.commitState.get()); - assertEquals(CommitState.DIRTY, intMean.commitState.get()); - assertEquals(CommitState.DIRTY, boolAnd.commitState.get()); - - // Test counters are not dirty and are COMMITTED. - assertTrue(longSum.committing()); - assertTrue(longMean.committing()); - assertTrue(doubleSum.committing()); - assertTrue(doubleMean.committing()); - assertTrue(intSum.committing()); - assertTrue(intMean.committing()); - assertTrue(boolAnd.committing()); - - assertTrue(longSum.committed()); - assertTrue(longMean.committed()); - assertTrue(doubleSum.committed()); - assertTrue(doubleMean.committed()); - assertTrue(intSum.committed()); - assertTrue(intMean.committed()); - assertTrue(boolAnd.committed()); - - assertFalse(longSum.isDirty()); - assertFalse(longMean.isDirty()); - assertFalse(doubleSum.isDirty()); - assertFalse(doubleMean.isDirty()); - assertFalse(intSum.isDirty()); - assertFalse(intMean.isDirty()); - assertFalse(boolAnd.isDirty()); - - assertEquals(CommitState.COMMITTED, longSum.commitState.get()); - assertEquals(CommitState.COMMITTED, longMean.commitState.get()); - assertEquals(CommitState.COMMITTED, doubleSum.commitState.get()); - assertEquals(CommitState.COMMITTED, doubleMean.commitState.get()); - assertEquals(CommitState.COMMITTED, intSum.commitState.get()); - assertEquals(CommitState.COMMITTED, intMean.commitState.get()); - assertEquals(CommitState.COMMITTED, boolAnd.commitState.get()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java deleted file mode 100644 index faaa34110d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/CounterTestUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static com.google.cloud.dataflow.sdk.util.common.Counter.AggregationKind.MEAN; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.util.common.Counter.CounterMean; - -import org.junit.Assert; - -import java.io.ByteArrayOutputStream; - -/** - * Utilities for testing {@link Counter}s. - */ -public class CounterTestUtils { - /** - * A utility method that passes the given (unencoded) elements through - * coder's registerByteSizeObserver() and encode() methods, and confirms - * they are mutually consistent. This is useful for testing coder - * implementations. - */ - public static void testByteCount(Coder coder, Coder.Context context, T[] elements) - throws Exception { - Counter meanByteCount = Counter.longs("meanByteCount", MEAN); - ElementByteSizeObserver observer = new ElementByteSizeObserver(meanByteCount); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - for (T elem : elements) { - coder.registerByteSizeObserver(elem, observer, context); - coder.encode(elem, os, context); - observer.advance(); - } - long expectedLength = os.toByteArray().length; - - CounterMean mean = meanByteCount.getMean(); - - Assert.assertEquals(expectedLength, mean.getAggregate().longValue()); - Assert.assertEquals(elements.length, mean.getCount()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpersTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpersTest.java deleted file mode 100644 index f7d678ba8e..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/common/ReflectHelpersTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.common; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; -import java.util.Map; - -/** - * Tests for {@link ReflectHelpers}. - */ -@RunWith(JUnit4.class) -public class ReflectHelpersTest { - - @Test - public void testClassName() { - assertEquals(getClass().getName(), ReflectHelpers.CLASS_NAME.apply(getClass())); - } - - @Test - public void testClassSimpleName() { - assertEquals(getClass().getSimpleName(), - ReflectHelpers.CLASS_SIMPLE_NAME.apply(getClass())); - } - - @Test - public void testMethodFormatter() throws Exception { - assertEquals("testMethodFormatter()", - ReflectHelpers.METHOD_FORMATTER.apply(getClass().getMethod("testMethodFormatter"))); - - assertEquals("oneArg(int)", - ReflectHelpers.METHOD_FORMATTER.apply(getClass().getDeclaredMethod("oneArg", int.class))); - assertEquals("twoArg(String, List)", - ReflectHelpers.METHOD_FORMATTER.apply( - getClass().getDeclaredMethod("twoArg", String.class, List.class))); - } - - @Test - public void testClassMethodFormatter() throws Exception { - assertEquals( - getClass().getName() + "#testMethodFormatter()", - ReflectHelpers.CLASS_AND_METHOD_FORMATTER - .apply(getClass().getMethod("testMethodFormatter"))); - - assertEquals( - getClass().getName() + "#oneArg(int)", - ReflectHelpers.CLASS_AND_METHOD_FORMATTER - .apply(getClass().getDeclaredMethod("oneArg", int.class))); - assertEquals( - getClass().getName() + "#twoArg(String, List)", - ReflectHelpers.CLASS_AND_METHOD_FORMATTER.apply( - getClass().getDeclaredMethod("twoArg", String.class, List.class))); - } - - @SuppressWarnings("unused") - void oneArg(int n) {} - @SuppressWarnings("unused") - void twoArg(String foo, List bar) {} - - @Test - public void testTypeFormatterOnClasses() throws Exception { - assertEquals("Integer", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(Integer.class)); - assertEquals("int", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(int.class)); - assertEquals("Map", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(Map.class)); - assertEquals(getClass().getSimpleName(), - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(getClass())); - } - - @Test - public void testTypeFormatterOnArrays() throws Exception { - assertEquals("Integer[]", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(Integer[].class)); - assertEquals("int[]", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(int[].class)); - } - - @Test - public void testTypeFormatterWithGenerics() throws Exception { - assertEquals("Map", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply( - new TypeDescriptor>() {}.getType())); - assertEquals("Map", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply( - new TypeDescriptor>() {}.getType())); - assertEquals("Map", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply( - new TypeDescriptor>() {}.getType())); - } - - @Test - public void testTypeFormatterWithWildcards() throws Exception { - assertEquals("Map", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply( - new TypeDescriptor>() {}.getType())); - } - - @Test - public void testTypeFormatterWithMultipleWildcards() throws Exception { - assertEquals("Map", - ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply( - new TypeDescriptor>() {}.getType())); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPathTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPathTest.java deleted file mode 100644 index 3aefa6d0f0..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/gcsfs/GcsPathTest.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.gcsfs; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.net.URI; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -/** - * Tests of GcsPath. - */ -@RunWith(JUnit4.class) -public class GcsPathTest { - - /** - * Test case, which tests parsing and building of GcsPaths. - */ - static final class TestCase { - - final String uri; - final String expectedBucket; - final String expectedObject; - final String[] namedComponents; - - TestCase(String uri, String... namedComponents) { - this.uri = uri; - this.expectedBucket = namedComponents[0]; - this.namedComponents = namedComponents; - this.expectedObject = uri.substring(expectedBucket.length() + 6); - } - } - - // Each test case is an expected URL, then the components used to build it. - // Empty components result in a double slash. - static final List PATH_TEST_CASES = Arrays.asList( - new TestCase("gs://bucket/then/object", "bucket", "then", "object"), - new TestCase("gs://bucket//then/object", "bucket", "", "then", "object"), - new TestCase("gs://bucket/then//object", "bucket", "then", "", "object"), - new TestCase("gs://bucket/then///object", "bucket", "then", "", "", "object"), - new TestCase("gs://bucket/then/object/", "bucket", "then", "object/"), - new TestCase("gs://bucket/then/object/", "bucket", "then/", "object/"), - new TestCase("gs://bucket/then/object//", "bucket", "then", "object", ""), - new TestCase("gs://bucket/then/object//", "bucket", "then", "object/", ""), - new TestCase("gs://bucket/", "bucket") - ); - - @Test - public void testGcsPathParsing() throws Exception { - for (TestCase testCase : PATH_TEST_CASES) { - String uriString = testCase.uri; - - GcsPath path = GcsPath.fromUri(URI.create(uriString)); - // Deconstruction - check bucket, object, and components. - assertEquals(testCase.expectedBucket, path.getBucket()); - assertEquals(testCase.expectedObject, path.getObject()); - assertEquals(testCase.uri, - testCase.namedComponents.length, path.getNameCount()); - - // Construction - check that the path can be built from components. - GcsPath built = GcsPath.fromComponents(null, null); - for (String component : testCase.namedComponents) { - built = built.resolve(component); - } - assertEquals(testCase.uri, built.toString()); - } - } - - @Test - public void testParentRelationship() throws Exception { - GcsPath path = GcsPath.fromComponents("bucket", "then/object"); - assertEquals("bucket", path.getBucket()); - assertEquals("then/object", path.getObject()); - assertEquals(3, path.getNameCount()); - assertTrue(path.endsWith("object")); - assertTrue(path.startsWith("bucket/then")); - - GcsPath parent = path.getParent(); // gs://bucket/then/ - assertEquals("bucket", parent.getBucket()); - assertEquals("then/", parent.getObject()); - assertEquals(2, parent.getNameCount()); - assertThat(path, Matchers.not(Matchers.equalTo(parent))); - assertTrue(path.startsWith(parent)); - assertFalse(parent.startsWith(path)); - assertTrue(parent.endsWith("then/")); - assertTrue(parent.startsWith("bucket/then")); - assertTrue(parent.isAbsolute()); - - GcsPath root = path.getRoot(); - assertEquals(0, root.getNameCount()); - assertEquals("gs://", root.toString()); - assertEquals("", root.getBucket()); - assertEquals("", root.getObject()); - assertTrue(root.isAbsolute()); - assertThat(root, Matchers.equalTo(parent.getRoot())); - - GcsPath grandParent = parent.getParent(); // gs://bucket/ - assertEquals(1, grandParent.getNameCount()); - assertEquals("gs://bucket/", grandParent.toString()); - assertTrue(grandParent.isAbsolute()); - assertThat(root, Matchers.equalTo(grandParent.getParent())); - assertThat(root.getParent(), Matchers.nullValue()); - - assertTrue(path.startsWith(path.getRoot())); - assertTrue(parent.startsWith(path.getRoot())); - } - - @Test - public void testRelativeParent() throws Exception { - GcsPath path = GcsPath.fromComponents(null, "a/b"); - GcsPath parent = path.getParent(); - assertEquals("a/", parent.toString()); - - GcsPath grandParent = parent.getParent(); - assertNull(grandParent); - } - - @Test - public void testUriSupport() throws Exception { - URI uri = URI.create("gs://bucket/some/path"); - - GcsPath path = GcsPath.fromUri(uri); - assertEquals("bucket", path.getBucket()); - assertEquals("some/path", path.getObject()); - - URI reconstructed = path.toUri(); - assertEquals(uri, reconstructed); - - path = GcsPath.fromUri("gs://bucket"); - assertEquals("gs://bucket/", path.toString()); - } - - @Test - public void testBucketParsing() throws Exception { - GcsPath path = GcsPath.fromUri("gs://bucket"); - GcsPath path2 = GcsPath.fromUri("gs://bucket/"); - - assertEquals(path, path2); - assertEquals(path.toString(), path2.toString()); - assertEquals(path.toUri(), path2.toUri()); - } - - @Test - public void testGcsPathToString() throws Exception { - String filename = "gs://some_bucket/some/file.txt"; - GcsPath path = GcsPath.fromUri(filename); - assertEquals(filename, path.toString()); - } - - @Test - public void testEquals() { - GcsPath a = GcsPath.fromComponents(null, "a/b/c"); - GcsPath a2 = GcsPath.fromComponents(null, "a/b/c"); - assertFalse(a.isAbsolute()); - assertFalse(a2.isAbsolute()); - - GcsPath b = GcsPath.fromComponents("bucket", "a/b/c"); - GcsPath b2 = GcsPath.fromComponents("bucket", "a/b/c"); - assertTrue(b.isAbsolute()); - assertTrue(b2.isAbsolute()); - - assertEquals(a, a); - assertThat(a, Matchers.not(Matchers.equalTo(b))); - assertThat(b, Matchers.not(Matchers.equalTo(a))); - - assertEquals(a, a2); - assertEquals(a2, a); - assertEquals(b, b2); - assertEquals(b2, b); - - assertThat(a, Matchers.not(Matchers.equalTo(Paths.get("/tmp/foo")))); - assertTrue(a != null); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidGcsPath() { - @SuppressWarnings("unused") - GcsPath filename = - GcsPath.fromUri("file://invalid/gcs/path"); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidBucket() { - GcsPath.fromComponents("invalid/", ""); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidObject_newline() { - GcsPath.fromComponents(null, "a\nb"); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidObject_cr() { - GcsPath.fromComponents(null, "a\rb"); - } - - @Test - public void testResolveUri() { - GcsPath path = GcsPath.fromComponents("bucket", "a/b/c"); - GcsPath d = path.resolve("gs://bucket2/d"); - assertEquals("gs://bucket2/d", d.toString()); - } - - @Test - public void testResolveOther() { - GcsPath a = GcsPath.fromComponents("bucket", "a"); - GcsPath b = a.resolve(Paths.get("b")); - assertEquals("a/b", b.getObject()); - } - - @Test - public void testCompareTo() { - GcsPath a = GcsPath.fromComponents("bucket", "a"); - GcsPath b = GcsPath.fromComponents("bucket", "b"); - GcsPath b2 = GcsPath.fromComponents("bucket2", "b"); - GcsPath brel = GcsPath.fromComponents(null, "b"); - GcsPath a2 = GcsPath.fromComponents("bucket", "a"); - GcsPath arel = GcsPath.fromComponents(null, "a"); - - assertThat(a.compareTo(b), Matchers.lessThan(0)); - assertThat(b.compareTo(a), Matchers.greaterThan(0)); - assertThat(a.compareTo(a2), Matchers.equalTo(0)); - - assertThat(a.hashCode(), Matchers.equalTo(a2.hashCode())); - assertThat(a.hashCode(), Matchers.not(Matchers.equalTo(b.hashCode()))); - assertThat(b.hashCode(), Matchers.not(Matchers.equalTo(brel.hashCode()))); - - assertThat(brel.compareTo(b), Matchers.lessThan(0)); - assertThat(b.compareTo(brel), Matchers.greaterThan(0)); - assertThat(arel.compareTo(brel), Matchers.lessThan(0)); - assertThat(brel.compareTo(arel), Matchers.greaterThan(0)); - - assertThat(b.compareTo(b2), Matchers.lessThan(0)); - assertThat(b2.compareTo(b), Matchers.greaterThan(0)); - } - - @Test - public void testCompareTo_ordering() { - GcsPath ab = GcsPath.fromComponents("bucket", "a/b"); - GcsPath abc = GcsPath.fromComponents("bucket", "a/b/c"); - GcsPath a1b = GcsPath.fromComponents("bucket", "a-1/b"); - - assertThat(ab.compareTo(a1b), Matchers.lessThan(0)); - assertThat(a1b.compareTo(ab), Matchers.greaterThan(0)); - - assertThat(ab.compareTo(abc), Matchers.lessThan(0)); - assertThat(abc.compareTo(ab), Matchers.greaterThan(0)); - } - - @Test - public void testCompareTo_buckets() { - GcsPath a = GcsPath.fromComponents(null, "a/b/c"); - GcsPath b = GcsPath.fromComponents("bucket", "a/b/c"); - - assertThat(a.compareTo(b), Matchers.lessThan(0)); - assertThat(b.compareTo(a), Matchers.greaterThan(0)); - } - - @Test - public void testIterator() { - GcsPath a = GcsPath.fromComponents("bucket", "a/b/c"); - Iterator it = a.iterator(); - - assertTrue(it.hasNext()); - assertEquals("gs://bucket/", it.next().toString()); - assertTrue(it.hasNext()); - assertEquals("a", it.next().toString()); - assertTrue(it.hasNext()); - assertEquals("b", it.next().toString()); - assertTrue(it.hasNext()); - assertEquals("c", it.next().toString()); - assertFalse(it.hasNext()); - } - - @Test - public void testSubpath() { - GcsPath a = GcsPath.fromComponents("bucket", "a/b/c/d"); - assertThat(a.subpath(0, 1).toString(), Matchers.equalTo("gs://bucket/")); - assertThat(a.subpath(0, 2).toString(), Matchers.equalTo("gs://bucket/a")); - assertThat(a.subpath(0, 3).toString(), Matchers.equalTo("gs://bucket/a/b")); - assertThat(a.subpath(0, 4).toString(), Matchers.equalTo("gs://bucket/a/b/c")); - assertThat(a.subpath(1, 2).toString(), Matchers.equalTo("a")); - assertThat(a.subpath(2, 3).toString(), Matchers.equalTo("b")); - assertThat(a.subpath(2, 4).toString(), Matchers.equalTo("b/c")); - assertThat(a.subpath(2, 5).toString(), Matchers.equalTo("b/c/d")); - } - - @Test - public void testGetName() { - GcsPath a = GcsPath.fromComponents("bucket", "a/b/c/d"); - assertEquals(5, a.getNameCount()); - assertThat(a.getName(0).toString(), Matchers.equalTo("gs://bucket/")); - assertThat(a.getName(1).toString(), Matchers.equalTo("a")); - assertThat(a.getName(2).toString(), Matchers.equalTo("b")); - assertThat(a.getName(3).toString(), Matchers.equalTo("c")); - assertThat(a.getName(4).toString(), Matchers.equalTo("d")); - } - - @Test(expected = IllegalArgumentException.class) - public void testSubPathError() { - GcsPath a = GcsPath.fromComponents("bucket", "a/b/c/d"); - a.subpath(1, 1); // throws IllegalArgumentException - Assert.fail(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java deleted file mode 100644 index 5bb0f59772..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/CopyOnAccessInMemoryStateInternalsTest.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.theInstance; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; -import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; - -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link CopyOnAccessInMemoryStateInternals}. - */ -@RunWith(JUnit4.class) -public class CopyOnAccessInMemoryStateInternalsTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - private String key = "foo"; - @Test - public void testGetWithEmpty() { - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - assertThat(stringBag.read(), containsInAnyOrder("baz", "bar")); - - BagState reReadStringBag = internals.state(namespace, bagTag); - assertThat(reReadStringBag.read(), containsInAnyOrder("baz", "bar")); - } - - @Test - public void testGetWithAbsentInUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - assertThat(stringBag.read(), containsInAnyOrder("baz", "bar")); - - BagState reReadVoidBag = internals.state(namespace, bagTag); - assertThat(reReadVoidBag.read(), containsInAnyOrder("baz", "bar")); - - BagState underlyingState = underlying.state(namespace, bagTag); - assertThat(underlyingState.read(), emptyIterable()); - } - - /** - * Tests that retrieving state with an underlying StateInternals with an existing value returns - * a value that initially has equal value to the provided state but can be modified without - * modifying the existing state. - */ - @Test - public void testGetWithPresentInUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> valueTag = StateTags.value("foo", StringUtf8Coder.of()); - ValueState underlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.read(), nullValue(String.class)); - - underlyingValue.write("bar"); - assertThat(underlyingValue.read(), equalTo("bar")); - - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - ValueState copyOnAccessState = internals.state(namespace, valueTag); - assertThat(copyOnAccessState.read(), equalTo("bar")); - - copyOnAccessState.write("baz"); - assertThat(copyOnAccessState.read(), equalTo("baz")); - assertThat(underlyingValue.read(), equalTo("bar")); - - ValueState reReadUnderlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); - } - - @Test - public void testBagStateWithUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> valueTag = StateTags.bag("foo", VarIntCoder.of()); - BagState underlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.read(), emptyIterable()); - - underlyingValue.add(1); - assertThat(underlyingValue.read(), containsInAnyOrder(1)); - - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - BagState copyOnAccessState = internals.state(namespace, valueTag); - assertThat(copyOnAccessState.read(), containsInAnyOrder(1)); - - copyOnAccessState.add(4); - assertThat(copyOnAccessState.read(), containsInAnyOrder(4, 1)); - assertThat(underlyingValue.read(), containsInAnyOrder(1)); - - BagState reReadUnderlyingValue = underlying.state(namespace, valueTag); - assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); - } - - @Test - public void testAccumulatorCombiningStateWithUnderlying() throws CannotProvideCoderException { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - CombineFn sumLongFn = new Sum.SumLongFn(); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - CoderRegistry reg = TestPipeline.create().getCoderRegistry(); - StateTag> stateTag = - StateTags.combiningValue("summer", - sumLongFn.getAccumulatorCoder(reg, reg.getDefaultCoder(Long.class)), sumLongFn); - CombiningState underlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.read(), equalTo(0L)); - - underlyingValue.add(1L); - assertThat(underlyingValue.read(), equalTo(1L)); - - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - CombiningState copyOnAccessState = internals.state(namespace, stateTag); - assertThat(copyOnAccessState.read(), equalTo(1L)); - - copyOnAccessState.add(4L); - assertThat(copyOnAccessState.read(), equalTo(5L)); - assertThat(underlyingValue.read(), equalTo(1L)); - - CombiningState reReadUnderlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); - } - - @Test - public void testKeyedAccumulatorCombiningStateWithUnderlying() throws Exception { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - KeyedCombineFn sumLongFn = new Sum.SumLongFn().asKeyedFn(); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - CoderRegistry reg = TestPipeline.create().getCoderRegistry(); - StateTag> stateTag = - StateTags.keyedCombiningValue( - "summer", - sumLongFn.getAccumulatorCoder( - reg, StringUtf8Coder.of(), reg.getDefaultCoder(Long.class)), - sumLongFn); - CombiningState underlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.read(), equalTo(0L)); - - underlyingValue.add(1L); - assertThat(underlyingValue.read(), equalTo(1L)); - - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - CombiningState copyOnAccessState = internals.state(namespace, stateTag); - assertThat(copyOnAccessState.read(), equalTo(1L)); - - copyOnAccessState.add(4L); - assertThat(copyOnAccessState.read(), equalTo(5L)); - assertThat(underlyingValue.read(), equalTo(1L)); - - CombiningState reReadUnderlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); - } - - @Test - public void testWatermarkHoldStateWithUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - - @SuppressWarnings("unchecked") - OutputTimeFn outputTimeFn = (OutputTimeFn) - TestPipeline.create().apply(Create.of("foo")).getWindowingStrategy().getOutputTimeFn(); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> stateTag = - StateTags.watermarkStateInternal("wmstate", outputTimeFn); - WatermarkHoldState underlyingValue = underlying.state(namespace, stateTag); - assertThat(underlyingValue.read(), nullValue()); - - underlyingValue.add(new Instant(250L)); - assertThat(underlyingValue.read(), equalTo(new Instant(250L))); - - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - WatermarkHoldState copyOnAccessState = internals.state(namespace, stateTag); - assertThat(copyOnAccessState.read(), equalTo(new Instant(250L))); - - copyOnAccessState.add(new Instant(100L)); - assertThat(copyOnAccessState.read(), equalTo(new Instant(100L))); - assertThat(underlyingValue.read(), equalTo(new Instant(250L))); - - copyOnAccessState.add(new Instant(500L)); - assertThat(copyOnAccessState.read(), equalTo(new Instant(100L))); - - WatermarkHoldState reReadUnderlyingValue = - underlying.state(namespace, stateTag); - assertThat(underlyingValue.read(), equalTo(reReadUnderlyingValue.read())); - } - - @Test - public void testCommitWithoutUnderlying() { - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - assertThat(stringBag.read(), containsInAnyOrder("baz", "bar")); - - internals.commit(); - - BagState reReadStringBag = internals.state(namespace, bagTag); - assertThat(reReadStringBag.read(), containsInAnyOrder("baz", "bar")); - assertThat(internals.isEmpty(), is(false)); - } - - @Test - public void testCommitWithUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - - internals.commit(); - BagState reReadStringBag = internals.state(namespace, bagTag); - assertThat(reReadStringBag.read(), containsInAnyOrder("baz", "bar")); - - reReadStringBag.add("spam"); - - BagState underlyingState = underlying.state(namespace, bagTag); - assertThat(underlyingState.read(), containsInAnyOrder("spam", "bar", "baz")); - assertThat(underlyingState, is(theInstance(stringBag))); - assertThat(internals.isEmpty(), is(false)); - } - - @Test - public void testCommitWithClearedInUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - CopyOnAccessInMemoryStateInternals secondUnderlying = - spy(CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying)); - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, secondUnderlying); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - stringBag.clear(); - // We should not read through the cleared bag - secondUnderlying.commit(); - - // Should not be visible - stringBag.add("foo"); - - internals.commit(); - BagState internalsStringBag = internals.state(namespace, bagTag); - assertThat(internalsStringBag.read(), emptyIterable()); - verify(secondUnderlying, never()).state(namespace, bagTag); - assertThat(internals.isEmpty(), is(false)); - } - - @Test - public void testCommitWithOverwrittenUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - - BagState internalsState = internals.state(namespace, bagTag); - internalsState.add("eggs"); - internalsState.add("ham"); - internalsState.add("0x00ff00"); - internalsState.add("&"); - - internals.commit(); - - BagState reReadInternalState = internals.state(namespace, bagTag); - assertThat( - reReadInternalState.read(), - containsInAnyOrder("bar", "baz", "0x00ff00", "eggs", "&", "ham")); - BagState reReadUnderlyingState = underlying.state(namespace, bagTag); - assertThat(reReadUnderlyingState.read(), containsInAnyOrder("bar", "baz")); - } - - @Test - public void testCommitWithAddedUnderlying() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - - internals.commit(); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - - BagState internalState = internals.state(namespace, bagTag); - assertThat(internalState.read(), emptyIterable()); - - BagState reReadUnderlyingState = underlying.state(namespace, bagTag); - assertThat(reReadUnderlyingState.read(), containsInAnyOrder("bar", "baz")); - } - - @Test - public void testCommitWithEmptyTableIsEmpty() { - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - - internals.commit(); - - assertThat(internals.isEmpty(), is(true)); - } - - @Test - public void testCommitWithOnlyClearedValuesIsEmpty() { - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = internals.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("foo"); - stringBag.clear(); - - internals.commit(); - - assertThat(internals.isEmpty(), is(true)); - } - - @Test - public void testCommitWithEmptyNewAndFullUnderlyingIsNotEmpty() { - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, underlying); - - StateNamespace namespace = new StateNamespaceForTest("foo"); - StateTag> bagTag = StateTags.bag("foo", StringUtf8Coder.of()); - BagState stringBag = underlying.state(namespace, bagTag); - assertThat(stringBag.read(), emptyIterable()); - - stringBag.add("bar"); - stringBag.add("baz"); - - internals.commit(); - assertThat(internals.isEmpty(), is(false)); - } - - @Test - public void testGetEarliestWatermarkHoldAfterCommit() { - BoundedWindow first = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(2048L); - } - }; - BoundedWindow second = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(689743L); - } - }; - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); - - StateTag> firstHoldAddress = - StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkHoldState firstHold = - internals.state(StateNamespaces.window(null, first), firstHoldAddress); - firstHold.add(new Instant(22L)); - - StateTag> secondHoldAddress = - StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkHoldState secondHold = - internals.state(StateNamespaces.window(null, second), secondHoldAddress); - secondHold.add(new Instant(2L)); - - internals.commit(); - assertThat(internals.getEarliestWatermarkHold(), equalTo(new Instant(2L))); - } - - @Test - public void testGetEarliestWatermarkHoldWithEarliestInUnderlyingTable() { - BoundedWindow first = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(2048L); - } - }; - BoundedWindow second = new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(689743L); - } - }; - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); - StateTag> firstHoldAddress = - StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkHoldState firstHold = - underlying.state(StateNamespaces.window(null, first), firstHoldAddress); - firstHold.add(new Instant(22L)); - - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying("foo", underlying.commit()); - - StateTag> secondHoldAddress = - StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkHoldState secondHold = - internals.state(StateNamespaces.window(null, second), secondHoldAddress); - secondHold.add(new Instant(244L)); - - internals.commit(); - assertThat(internals.getEarliestWatermarkHold(), equalTo(new Instant(22L))); - } - - @Test - public void testGetEarliestWatermarkHoldWithEarliestInNewTable() { - BoundedWindow first = - new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(2048L); - } - }; - BoundedWindow second = - new BoundedWindow() { - @Override - public Instant maxTimestamp() { - return new Instant(689743L); - } - }; - CopyOnAccessInMemoryStateInternals underlying = - CopyOnAccessInMemoryStateInternals.withUnderlying("foo", null); - StateTag> firstHoldAddress = - StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkHoldState firstHold = - underlying.state(StateNamespaces.window(null, first), firstHoldAddress); - firstHold.add(new Instant(224L)); - - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying("foo", underlying.commit()); - - StateTag> secondHoldAddress = - StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - WatermarkHoldState secondHold = - internals.state(StateNamespaces.window(null, second), secondHoldAddress); - secondHold.add(new Instant(24L)); - - internals.commit(); - assertThat(internals.getEarliestWatermarkHold(), equalTo(new Instant(24L))); - } - - @Test - public void testGetEarliestHoldBeforeCommit() { - CopyOnAccessInMemoryStateInternals internals = - CopyOnAccessInMemoryStateInternals.withUnderlying(key, null); - - internals - .state( - StateNamespaces.global(), - StateTags.watermarkStateInternal("foo", OutputTimeFns.outputAtEarliestInputTimestamp())) - .add(new Instant(1234L)); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage(CopyOnAccessInMemoryStateInternals.class.getSimpleName()); - thrown.expectMessage("Can't get the earliest watermark hold"); - thrown.expectMessage("before it is committed"); - - internals.getEarliestWatermarkHold(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java deleted file mode 100644 index 0c10560e4a..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/InMemoryStateInternalsTest.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** - * Tests for {@link InMemoryStateInternals}. - */ -@RunWith(JUnit4.class) -public class InMemoryStateInternalsTest { - private static final BoundedWindow WINDOW_1 = new IntervalWindow(new Instant(0), new Instant(10)); - private static final StateNamespace NAMESPACE_1 = new StateNamespaceForTest("ns1"); - private static final StateNamespace NAMESPACE_2 = new StateNamespaceForTest("ns2"); - private static final StateNamespace NAMESPACE_3 = new StateNamespaceForTest("ns3"); - - private static final StateTag> STRING_VALUE_ADDR = - StateTags.value("stringValue", StringUtf8Coder.of()); - private static final StateTag> - SUM_INTEGER_ADDR = StateTags.combiningValueFromInputInternal( - "sumInteger", VarIntCoder.of(), new Sum.SumIntegerFn()); - private static final StateTag> STRING_BAG_ADDR = - StateTags.bag("stringBag", StringUtf8Coder.of()); - private static final StateTag> - WATERMARK_EARLIEST_ADDR = - StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEarliestInputTimestamp()); - private static final StateTag> - WATERMARK_LATEST_ADDR = - StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtLatestInputTimestamp()); - private static final StateTag> WATERMARK_EOW_ADDR = - StateTags.watermarkStateInternal("watermark", OutputTimeFns.outputAtEndOfWindow()); - - InMemoryStateInternals underTest = InMemoryStateInternals.forKey("dummyKey"); - - @Test - public void testValue() throws Exception { - ValueState value = underTest.state(NAMESPACE_1, STRING_VALUE_ADDR); - - // State instances are cached, but depend on the namespace. - assertThat(underTest.state(NAMESPACE_1, STRING_VALUE_ADDR), Matchers.sameInstance(value)); - assertThat( - underTest.state(NAMESPACE_2, STRING_VALUE_ADDR), - Matchers.not(Matchers.sameInstance(value))); - - assertThat(value.read(), Matchers.nullValue()); - value.write("hello"); - assertThat(value.read(), Matchers.equalTo("hello")); - value.write("world"); - assertThat(value.read(), Matchers.equalTo("world")); - - value.clear(); - assertThat(value.read(), Matchers.nullValue()); - assertThat(underTest.state(NAMESPACE_1, STRING_VALUE_ADDR), Matchers.sameInstance(value)); - } - - @Test - public void testBag() throws Exception { - BagState value = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); - - // State instances are cached, but depend on the namespace. - assertEquals(value, underTest.state(NAMESPACE_1, STRING_BAG_ADDR)); - assertFalse(value.equals(underTest.state(NAMESPACE_2, STRING_BAG_ADDR))); - - assertThat(value.read(), Matchers.emptyIterable()); - value.add("hello"); - assertThat(value.read(), Matchers.containsInAnyOrder("hello")); - - value.add("world"); - assertThat(value.read(), Matchers.containsInAnyOrder("hello", "world")); - - value.clear(); - assertThat(value.read(), Matchers.emptyIterable()); - assertThat(underTest.state(NAMESPACE_1, STRING_BAG_ADDR), Matchers.sameInstance(value)); - } - - @Test - public void testBagIsEmpty() throws Exception { - BagState value = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); - - assertThat(value.isEmpty().read(), Matchers.is(true)); - ReadableState readFuture = value.isEmpty(); - value.add("hello"); - assertThat(readFuture.read(), Matchers.is(false)); - - value.clear(); - assertThat(readFuture.read(), Matchers.is(true)); - } - - @Test - public void testMergeBagIntoSource() throws Exception { - BagState bag1 = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); - BagState bag2 = underTest.state(NAMESPACE_2, STRING_BAG_ADDR); - - bag1.add("Hello"); - bag2.add("World"); - bag1.add("!"); - - StateMerging.mergeBags(Arrays.asList(bag1, bag2), bag1); - - // Reading the merged bag gets both the contents - assertThat(bag1.read(), Matchers.containsInAnyOrder("Hello", "World", "!")); - assertThat(bag2.read(), Matchers.emptyIterable()); - } - - @Test - public void testMergeBagIntoNewNamespace() throws Exception { - BagState bag1 = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); - BagState bag2 = underTest.state(NAMESPACE_2, STRING_BAG_ADDR); - BagState bag3 = underTest.state(NAMESPACE_3, STRING_BAG_ADDR); - - bag1.add("Hello"); - bag2.add("World"); - bag1.add("!"); - - StateMerging.mergeBags(Arrays.asList(bag1, bag2, bag3), bag3); - - // Reading the merged bag gets both the contents - assertThat(bag3.read(), Matchers.containsInAnyOrder("Hello", "World", "!")); - assertThat(bag1.read(), Matchers.emptyIterable()); - assertThat(bag2.read(), Matchers.emptyIterable()); - } - - @Test - public void testCombiningValue() throws Exception { - CombiningState value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - - // State instances are cached, but depend on the namespace. - assertEquals(value, underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR)); - assertFalse(value.equals(underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR))); - - assertThat(value.read(), Matchers.equalTo(0)); - value.add(2); - assertThat(value.read(), Matchers.equalTo(2)); - - value.add(3); - assertThat(value.read(), Matchers.equalTo(5)); - - value.clear(); - assertThat(value.read(), Matchers.equalTo(0)); - assertThat(underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR), Matchers.sameInstance(value)); - } - - @Test - public void testCombiningIsEmpty() throws Exception { - CombiningState value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - - assertThat(value.isEmpty().read(), Matchers.is(true)); - ReadableState readFuture = value.isEmpty(); - value.add(5); - assertThat(readFuture.read(), Matchers.is(false)); - - value.clear(); - assertThat(readFuture.read(), Matchers.is(true)); - } - - @Test - public void testMergeCombiningValueIntoSource() throws Exception { - AccumulatorCombiningState value1 = - underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - AccumulatorCombiningState value2 = - underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); - - value1.add(5); - value2.add(10); - value1.add(6); - - assertThat(value1.read(), Matchers.equalTo(11)); - assertThat(value2.read(), Matchers.equalTo(10)); - - // Merging clears the old values and updates the result value. - StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value1); - - assertThat(value1.read(), Matchers.equalTo(21)); - assertThat(value2.read(), Matchers.equalTo(0)); - } - - @Test - public void testMergeCombiningValueIntoNewNamespace() throws Exception { - AccumulatorCombiningState value1 = - underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); - AccumulatorCombiningState value2 = - underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); - AccumulatorCombiningState value3 = - underTest.state(NAMESPACE_3, SUM_INTEGER_ADDR); - - value1.add(5); - value2.add(10); - value1.add(6); - - StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value3); - - // Merging clears the old values and updates the result value. - assertThat(value1.read(), Matchers.equalTo(0)); - assertThat(value2.read(), Matchers.equalTo(0)); - assertThat(value3.read(), Matchers.equalTo(21)); - } - - @Test - public void testWatermarkEarliestState() throws Exception { - WatermarkHoldState value = - underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); - - // State instances are cached, but depend on the namespace. - assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR)); - assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR))); - - assertThat(value.read(), Matchers.nullValue()); - value.add(new Instant(2000)); - assertThat(value.read(), Matchers.equalTo(new Instant(2000))); - - value.add(new Instant(3000)); - assertThat(value.read(), Matchers.equalTo(new Instant(2000))); - - value.add(new Instant(1000)); - assertThat(value.read(), Matchers.equalTo(new Instant(1000))); - - value.clear(); - assertThat(value.read(), Matchers.equalTo(null)); - assertThat(underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR), Matchers.sameInstance(value)); - } - - @Test - public void testWatermarkLatestState() throws Exception { - WatermarkHoldState value = - underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); - - // State instances are cached, but depend on the namespace. - assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR)); - assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR))); - - assertThat(value.read(), Matchers.nullValue()); - value.add(new Instant(2000)); - assertThat(value.read(), Matchers.equalTo(new Instant(2000))); - - value.add(new Instant(3000)); - assertThat(value.read(), Matchers.equalTo(new Instant(3000))); - - value.add(new Instant(1000)); - assertThat(value.read(), Matchers.equalTo(new Instant(3000))); - - value.clear(); - assertThat(value.read(), Matchers.equalTo(null)); - assertThat(underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR), Matchers.sameInstance(value)); - } - - @Test - public void testWatermarkEndOfWindowState() throws Exception { - WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR); - - // State instances are cached, but depend on the namespace. - assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR)); - assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_EOW_ADDR))); - - assertThat(value.read(), Matchers.nullValue()); - value.add(new Instant(2000)); - assertThat(value.read(), Matchers.equalTo(new Instant(2000))); - - value.clear(); - assertThat(value.read(), Matchers.equalTo(null)); - assertThat(underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR), Matchers.sameInstance(value)); - } - - @Test - public void testWatermarkStateIsEmpty() throws Exception { - WatermarkHoldState value = - underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); - - assertThat(value.isEmpty().read(), Matchers.is(true)); - ReadableState readFuture = value.isEmpty(); - value.add(new Instant(1000)); - assertThat(readFuture.read(), Matchers.is(false)); - - value.clear(); - assertThat(readFuture.read(), Matchers.is(true)); - } - - @Test - public void testMergeEarliestWatermarkIntoSource() throws Exception { - WatermarkHoldState value1 = - underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); - WatermarkHoldState value2 = - underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR); - - value1.add(new Instant(3000)); - value2.add(new Instant(5000)); - value1.add(new Instant(4000)); - value2.add(new Instant(2000)); - - // Merging clears the old values and updates the merged value. - StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value1, WINDOW_1); - - assertThat(value1.read(), Matchers.equalTo(new Instant(2000))); - assertThat(value2.read(), Matchers.equalTo(null)); - } - - @Test - public void testMergeLatestWatermarkIntoSource() throws Exception { - WatermarkHoldState value1 = - underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); - WatermarkHoldState value2 = - underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR); - WatermarkHoldState value3 = - underTest.state(NAMESPACE_3, WATERMARK_LATEST_ADDR); - - value1.add(new Instant(3000)); - value2.add(new Instant(5000)); - value1.add(new Instant(4000)); - value2.add(new Instant(2000)); - - // Merging clears the old values and updates the result value. - StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value3, WINDOW_1); - - // Merging clears the old values and updates the result value. - assertThat(value3.read(), Matchers.equalTo(new Instant(5000))); - assertThat(value1.read(), Matchers.equalTo(null)); - assertThat(value2.read(), Matchers.equalTo(null)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateNamespacesTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateNamespacesTest.java deleted file mode 100644 index 933383db40..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateNamespacesTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; - -import org.hamcrest.Matchers; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link StateNamespaces}. - */ -@RunWith(JUnit4.class) -public class StateNamespacesTest { - - private final Coder intervalCoder = IntervalWindow.getCoder(); - - private IntervalWindow intervalWindow(long start, long end) { - return new IntervalWindow(new Instant(start), new Instant(end)); - } - - /** - * This test should not be changed. It verifies that the stringKey matches certain expectations. - * If this changes, the ability to reload any pipeline that has persisted these namespaces will - * be impacted. - */ - @Test - public void testStability() { - StateNamespace global = StateNamespaces.global(); - StateNamespace intervalWindow = - StateNamespaces.window(intervalCoder, intervalWindow(1000, 87392)); - StateNamespace intervalWindowAndTrigger = - StateNamespaces.windowAndTrigger(intervalCoder, intervalWindow(1000, 87392), 57); - StateNamespace globalWindow = StateNamespaces.window( - GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE); - StateNamespace globalWindowAndTrigger = StateNamespaces.windowAndTrigger( - GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE, 12); - - assertEquals("/", global.stringKey()); - assertEquals("/gAAAAAABVWD4ogU/", intervalWindow.stringKey()); - assertEquals("/gAAAAAABVWD4ogU/1L/", intervalWindowAndTrigger.stringKey()); - assertEquals("//", globalWindow.stringKey()); - assertEquals("//C/", globalWindowAndTrigger.stringKey()); - } - - /** - * Test that WindowAndTrigger namespaces are prefixed by the related Window namespace. - */ - @Test - public void testIntervalWindowPrefixing() { - StateNamespace window = - StateNamespaces.window(intervalCoder, intervalWindow(1000, 87392)); - StateNamespace windowAndTrigger = StateNamespaces.windowAndTrigger( - intervalCoder, intervalWindow(1000, 87392), 57); - assertThat(windowAndTrigger.stringKey(), Matchers.startsWith(window.stringKey())); - assertThat(StateNamespaces.global().stringKey(), - Matchers.not(Matchers.startsWith(window.stringKey()))); - } - - /** - * Test that WindowAndTrigger namespaces are prefixed by the related Window namespace. - */ - @Test - public void testGlobalWindowPrefixing() { - StateNamespace window = - StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE); - StateNamespace windowAndTrigger = StateNamespaces.windowAndTrigger( - GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE, 57); - assertThat(windowAndTrigger.stringKey(), Matchers.startsWith(window.stringKey())); - assertThat(StateNamespaces.global().stringKey(), - Matchers.not(Matchers.startsWith(window.stringKey()))); - } - - @Test - public void testFromStringGlobal() { - assertStringKeyRoundTrips(intervalCoder, StateNamespaces.global()); - } - - @Test - public void testFromStringIntervalWindow() { - assertStringKeyRoundTrips( - intervalCoder, StateNamespaces.window(intervalCoder, intervalWindow(1000, 8000))); - assertStringKeyRoundTrips( - intervalCoder, StateNamespaces.window(intervalCoder, intervalWindow(1000, 8000))); - - assertStringKeyRoundTrips(intervalCoder, - StateNamespaces.windowAndTrigger(intervalCoder, intervalWindow(1000, 8000), 18)); - assertStringKeyRoundTrips(intervalCoder, - StateNamespaces.windowAndTrigger(intervalCoder, intervalWindow(1000, 8000), 19)); - assertStringKeyRoundTrips(intervalCoder, - StateNamespaces.windowAndTrigger(intervalCoder, intervalWindow(2000, 8000), 19)); - } - - @Test - public void testFromStringGlobalWindow() { - assertStringKeyRoundTrips(GlobalWindow.Coder.INSTANCE, StateNamespaces.global()); - assertStringKeyRoundTrips(GlobalWindow.Coder.INSTANCE, - StateNamespaces.window(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE)); - assertStringKeyRoundTrips(GlobalWindow.Coder.INSTANCE, - StateNamespaces.windowAndTrigger(GlobalWindow.Coder.INSTANCE, GlobalWindow.INSTANCE, 18)); - } - - private void assertStringKeyRoundTrips( - Coder coder, StateNamespace namespace) { - assertEquals(namespace, StateNamespaces.fromString(namespace.stringKey(), coder)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java deleted file mode 100644 index b4ff36fae3..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/state/StateTagTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.util.state; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderRegistry; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.transforms.Combine.Holder; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Max.MaxIntegerFn; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.Min.MinIntegerFn; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.util.CombineFnUtil; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link StateTag}. - */ -@RunWith(JUnit4.class) -public class StateTagTest { - @Test - public void testValueEquality() { - StateTag fooVarInt1 = StateTags.value("foo", VarIntCoder.of()); - StateTag fooVarInt2 = StateTags.value("foo", VarIntCoder.of()); - StateTag fooBigEndian = StateTags.value("foo", BigEndianIntegerCoder.of()); - StateTag barVarInt = StateTags.value("bar", VarIntCoder.of()); - - assertEquals(fooVarInt1, fooVarInt2); - assertNotEquals(fooVarInt1, fooBigEndian); - assertNotEquals(fooVarInt1, barVarInt); - } - - @Test - public void testBagEquality() { - StateTag fooVarInt1 = StateTags.bag("foo", VarIntCoder.of()); - StateTag fooVarInt2 = StateTags.bag("foo", VarIntCoder.of()); - StateTag fooBigEndian = StateTags.bag("foo", BigEndianIntegerCoder.of()); - StateTag barVarInt = StateTags.bag("bar", VarIntCoder.of()); - - assertEquals(fooVarInt1, fooVarInt2); - assertNotEquals(fooVarInt1, fooBigEndian); - assertNotEquals(fooVarInt1, barVarInt); - } - - @Test - public void testWatermarkBagEquality() { - StateTag foo1 = StateTags.watermarkStateInternal( - "foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - StateTag foo2 = StateTags.watermarkStateInternal( - "foo", OutputTimeFns.outputAtEarliestInputTimestamp()); - StateTag bar = StateTags.watermarkStateInternal( - "bar", OutputTimeFns.outputAtEarliestInputTimestamp()); - - StateTag bar2 = StateTags.watermarkStateInternal( - "bar", OutputTimeFns.outputAtLatestInputTimestamp()); - - // Same id, same fn. - assertEquals(foo1, foo2); - // Different id, same fn. - assertNotEquals(foo1, bar); - // Same id, different fn. - assertEquals(bar, bar2); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Test - public void testCombiningValueEquality() { - MaxIntegerFn maxFn = new Max.MaxIntegerFn(); - Coder input1 = VarIntCoder.of(); - Coder input2 = BigEndianIntegerCoder.of(); - MinIntegerFn minFn = new Min.MinIntegerFn(); - - StateTag fooCoder1Max1 = StateTags.combiningValueFromInputInternal("foo", input1, maxFn); - StateTag fooCoder1Max2 = StateTags.combiningValueFromInputInternal("foo", input1, maxFn); - StateTag fooCoder1Min = StateTags.combiningValueFromInputInternal("foo", input1, minFn); - - StateTag fooCoder2Max = StateTags.combiningValueFromInputInternal("foo", input2, maxFn); - StateTag barCoder1Max = StateTags.combiningValueFromInputInternal("bar", input1, maxFn); - - // Same name, coder and combineFn - assertEquals(fooCoder1Max1, fooCoder1Max2); - assertEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max2)); - - // Different combineFn, but we treat them as equal since we only serialize the bits. - assertEquals(fooCoder1Max1, fooCoder1Min); - assertEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) fooCoder1Min)); - - // Different input coder coder. - assertNotEquals(fooCoder1Max1, fooCoder2Max); - assertNotEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) fooCoder2Max)); - - // These StateTags have different IDs. - assertNotEquals(fooCoder1Max1, barCoder1Max); - assertNotEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) barCoder1Max)); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Test - public void testCombiningValueWithContextEquality() { - CoderRegistry registry = new CoderRegistry(); - registry.registerStandardCoders(); - - MaxIntegerFn maxFn = new Max.MaxIntegerFn(); - MinIntegerFn minFn = new Min.MinIntegerFn(); - - Coder> accum1 = maxFn.getAccumulatorCoder(registry, VarIntCoder.of()); - Coder> accum2 = minFn.getAccumulatorCoder(registry, BigEndianIntegerCoder.of()); - - StateTag fooCoder1Max1 = StateTags.keyedCombiningValueWithContext( - "foo", accum1, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); - StateTag fooCoder1Max2 = StateTags.keyedCombiningValueWithContext( - "foo", accum1, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); - StateTag fooCoder1Min = StateTags.keyedCombiningValueWithContext( - "foo", accum1, CombineFnUtil.toFnWithContext(minFn).asKeyedFn()); - - StateTag fooCoder2Max = StateTags.keyedCombiningValueWithContext( - "foo", accum2, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); - StateTag barCoder1Max = StateTags.keyedCombiningValueWithContext( - "bar", accum1, CombineFnUtil.toFnWithContext(maxFn).asKeyedFn()); - - // Same name, coder and combineFn - assertEquals(fooCoder1Max1, fooCoder1Max2); - assertEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max2)); - // Different combineFn, but we treat them as equal since we only serialize the bits. - assertEquals(fooCoder1Max1, fooCoder1Min); - assertEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) fooCoder1Min)); - - // Different input coder coder. - assertNotEquals(fooCoder1Max1, fooCoder2Max); - assertNotEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) fooCoder2Max)); - - // These StateTags have different IDs. - assertNotEquals(fooCoder1Max1, barCoder1Max); - assertNotEquals( - StateTags.convertToBagTagInternal((StateTag) fooCoder1Max1), - StateTags.convertToBagTagInternal((StateTag) barCoder1Max)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/KVTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/KVTest.java deleted file mode 100644 index 75d4fc5a6b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/KVTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import com.google.common.collect.ImmutableList; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Comparator; - -/** - * Tests for KV. - */ -@RunWith(JUnit4.class) -public class KVTest { - private static final Integer TEST_VALUES[] = - {null, Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; - - // Wrapper around Integer.compareTo() to support null values. - private int compareInt(Integer a, Integer b) { - if (a == null) { - return b == null ? 0 : -1; - } else { - return b == null ? 1 : a.compareTo(b); - } - } - - @Test - public void testEquals() { - // Neither position are arrays - assertThat(KV.of(1, 2), equalTo(KV.of(1, 2))); - - // Key is array - assertThat(KV.of(new int[]{1, 2}, 3), equalTo(KV.of(new int[]{1, 2}, 3))); - - // Value is array - assertThat(KV.of(1, new int[]{2, 3}), equalTo(KV.of(1, new int[]{2, 3}))); - - // Both are arrays - assertThat(KV.of(new int[]{1, 2}, new int[]{3, 4}), - equalTo(KV.of(new int[]{1, 2}, new int[]{3, 4}))); - - // Unfortunately, deep equals only goes so far - assertThat(KV.of(ImmutableList.of(new int[]{1, 2}), 3), - not(equalTo(KV.of(ImmutableList.of(new int[]{1, 2}), 3)))); - assertThat(KV.of(1, ImmutableList.of(new int[]{2, 3})), - not(equalTo(KV.of(1, ImmutableList.of(new int[]{2, 3}))))); - - // Key is array and differs - assertThat(KV.of(new int[]{1, 2}, 3), not(equalTo(KV.of(new int[]{1, 37}, 3)))); - - // Key is non-array and differs - assertThat(KV.of(1, new int[]{2, 3}), not(equalTo(KV.of(37, new int[]{1, 2})))); - - // Value is array and differs - assertThat(KV.of(1, new int[]{2, 3}), not(equalTo(KV.of(1, new int[]{37, 3})))); - - // Value is non-array and differs - assertThat(KV.of(new byte[]{1, 2}, 3), not(equalTo(KV.of(new byte[]{1, 2}, 37)))); - } - - @Test - public void testOrderByKey() { - Comparator> orderByKey = new KV.OrderByKey<>(); - for (Integer key1 : TEST_VALUES) { - for (Integer val1 : TEST_VALUES) { - for (Integer key2 : TEST_VALUES) { - for (Integer val2 : TEST_VALUES) { - assertEquals(compareInt(key1, key2), - orderByKey.compare(KV.of(key1, val1), KV.of(key2, val2))); - } - } - } - } - } - - @Test - public void testOrderByValue() { - Comparator> orderByValue = new KV.OrderByValue<>(); - for (Integer key1 : TEST_VALUES) { - for (Integer val1 : TEST_VALUES) { - for (Integer key2 : TEST_VALUES) { - for (Integer val2 : TEST_VALUES) { - assertEquals(compareInt(val1, val2), - orderByValue.compare(KV.of(key1, val1), KV.of(key2, val2))); - } - } - } - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionListTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionListTest.java deleted file mode 100644 index 3df088fd8b..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionListTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collections; - -/** - * Tests for PCollectionLists. - */ -@RunWith(JUnit4.class) -public class PCollectionListTest { - @Test - public void testEmptyListFailure() { - try { - PCollectionList.of(Collections.>emptyList()); - fail("should have failed"); - } catch (IllegalArgumentException exn) { - assertThat( - exn.toString(), - containsString( - "must either have a non-empty list of PCollections, " - + "or must first call empty(Pipeline)")); - } - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionTupleTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionTupleTest.java deleted file mode 100644 index 1017556e77..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PCollectionTupleTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.WindowingStrategy; -import com.google.cloud.dataflow.sdk.values.PCollection.IsBounded; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - -/** Unit tests for {@link PCollectionTuple}. */ -@RunWith(JUnit4.class) -public final class PCollectionTupleTest implements Serializable { - @Test - public void testOfThenHas() { - Pipeline pipeline = TestPipeline.create(); - PCollection pCollection = PCollection.createPrimitiveOutputInternal( - pipeline, WindowingStrategy.globalDefault(), IsBounded.BOUNDED); - TupleTag tag = new TupleTag<>(); - - assertTrue(PCollectionTuple.of(tag, pCollection).has(tag)); - } - - @Test - public void testEmpty() { - Pipeline pipeline = TestPipeline.create(); - TupleTag tag = new TupleTag<>(); - assertFalse(PCollectionTuple.empty(pipeline).has(tag)); - } - - @Test - @Category(RunnableOnService.class) - public void testComposePCollectionTuple() { - Pipeline pipeline = TestPipeline.create(); - - List inputs = Arrays.asList(3, -42, 666); - - TupleTag mainOutputTag = new TupleTag("main") {}; - TupleTag emptyOutputTag = new TupleTag("empty") {}; - final TupleTag sideOutputTag = new TupleTag("side") {}; - - PCollection mainInput = pipeline - .apply(Create.of(inputs)); - - PCollectionTuple outputs = mainInput.apply(ParDo - .of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - c.sideOutput(sideOutputTag, c.element()); - }}) - .withOutputTags(emptyOutputTag, TupleTagList.of(sideOutputTag))); - assertNotNull("outputs.getPipeline()", outputs.getPipeline()); - outputs = outputs.and(mainOutputTag, mainInput); - - DataflowAssert.that(outputs.get(mainOutputTag)).containsInAnyOrder(inputs); - DataflowAssert.that(outputs.get(sideOutputTag)).containsInAnyOrder(inputs); - DataflowAssert.that(outputs.get(emptyOutputTag)).empty(); - - pipeline.run(); - } - -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PDoneTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PDoneTest.java deleted file mode 100644 index 4c273672cb..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/PDoneTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static com.google.cloud.dataflow.sdk.TestUtils.LINES; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.PTransform; - -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; - -/** - * Tests for PDone. - */ -@RunWith(JUnit4.class) -public class PDoneTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - /** - * A PTransform that just returns a fresh PDone. - */ - static class EmptyTransform extends PTransform { - @Override - public PDone apply(PBegin begin) { - return PDone.in(begin.getPipeline()); - } - } - - /** - * A PTransform that's composed of something that returns a PDone. - */ - static class SimpleTransform extends PTransform { - private final String filename; - - public SimpleTransform(String filename) { - this.filename = filename; - } - - @Override - public PDone apply(PBegin begin) { - return - begin - .apply(Create.of(LINES)) - .apply(TextIO.Write.to(filename)); - } - } - - // TODO: This test doesn't work, because we can't handle composite - // transforms that contain no nested transforms. - @Ignore - @Test - @Category(RunnableOnService.class) - public void testEmptyTransform() { - Pipeline p = TestPipeline.create(); - - p.begin().apply(new EmptyTransform()); - - p.run(); - } - - // Cannot run on the service, unless we allocate a GCS temp file - // instead of a local temp file. Or switch to applying a different - // transform that returns PDone. - @Test - public void testSimpleTransform() throws Exception { - File tmpFile = tmpFolder.newFile("file.txt"); - String filename = tmpFile.getPath(); - - Pipeline p = TestPipeline.create(); - - p.begin().apply(new SimpleTransform(filename)); - - p.run(); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TupleTagTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TupleTagTest.java deleted file mode 100644 index af67434194..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TupleTagTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link TupleTag}. - */ -@RunWith(JUnit4.class) -public class TupleTagTest { - - private static TupleTag staticTag = new TupleTag<>(); - private static TupleTag staticBlockTag; - private static TupleTag staticMethodTag = createTag(); - private static TupleTag instanceMethodTag = new AnotherClass().createAnotherTag(); - - static { - staticBlockTag = new TupleTag<>(); - } - - private static TupleTag createTag() { - return new TupleTag<>(); - } - - private static class AnotherClass { - private static TupleTag anotherTag = new TupleTag<>(); - private TupleTag createAnotherTag() { - return new TupleTag<>(); - } - } - - @Test - public void testStaticTupleTag() { - assertEquals("com.google.cloud.dataflow.sdk.values.TupleTagTest#0", staticTag.getId()); - assertEquals("com.google.cloud.dataflow.sdk.values.TupleTagTest#3", staticBlockTag.getId()); - assertEquals("com.google.cloud.dataflow.sdk.values.TupleTagTest#1", staticMethodTag.getId()); - assertEquals("com.google.cloud.dataflow.sdk.values.TupleTagTest#2", instanceMethodTag.getId()); - assertEquals( - "com.google.cloud.dataflow.sdk.values.TupleTagTest$AnotherClass#0", - AnotherClass.anotherTag.getId()); - } - - private TupleTag createNonstaticTupleTag() { - return new TupleTag(); - } - - @Test - public void testNonstaticTupleTag() { - assertNotEquals(new TupleTag().getId(), new TupleTag().getId()); - assertNotEquals(createNonstaticTupleTag(), createNonstaticTupleTag()); - - TupleTag tag = createNonstaticTupleTag(); - - // Check that the name is derived from the method it is created in. - assertThat(tag.getId().split("#")[0], - startsWith("com.google.cloud.dataflow.sdk.values.TupleTagTest.createNonstaticTupleTag")); - - // Check that after the name there is a ':' followed by a line number, and just make - // sure the line number is big enough to be reasonable, so superficial changes don't break - // the test. - assertThat(Integer.parseInt(tag.getId().split("#")[0].split(":")[1]), - greaterThan(15)); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java deleted file mode 100644 index a811a7cf65..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypeDescriptorTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static org.junit.Assert.assertEquals; - -import com.google.common.reflect.TypeToken; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.lang.reflect.Method; -import java.lang.reflect.TypeVariable; -import java.util.List; -import java.util.Set; - -/** - * Tests for TypeDescriptor. - */ -@RunWith(JUnit4.class) -public class TypeDescriptorTest { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testTypeDescriptorOfRawType() throws Exception { - assertEquals( - TypeToken.of(String.class).getRawType(), - TypeDescriptor.of(String.class).getRawType()); - } - - @Test - public void testTypeDescriptorImmediate() throws Exception { - TypeDescriptor descriptor = new TypeDescriptor(){}; - assertEquals(String.class, descriptor.getRawType()); - } - - @Test - public void testTypeDescriptorGeneric() throws Exception { - TypeDescriptor> descriptor = new TypeDescriptor>(){}; - TypeToken> token = new TypeToken>(){}; - assertEquals(token.getType(), descriptor.getType()); - } - - private static class TypeRememberer { - public final TypeDescriptor descriptorByClass; - public final TypeDescriptor descriptorByInstance; - - public TypeRememberer() { - descriptorByClass = new TypeDescriptor(getClass()){}; - descriptorByInstance = new TypeDescriptor(this) {}; - } - } - - @Test - public void testTypeDescriptorNested() throws Exception { - TypeRememberer rememberer = new TypeRememberer(){}; - assertEquals(new TypeToken() {}.getType(), rememberer.descriptorByClass.getType()); - assertEquals(new TypeToken() {}.getType(), rememberer.descriptorByInstance.getType()); - - TypeRememberer> genericRememberer = new TypeRememberer>(){}; - assertEquals(new TypeToken>() {}.getType(), - genericRememberer.descriptorByClass.getType()); - assertEquals(new TypeToken>() {}.getType(), - genericRememberer.descriptorByInstance.getType()); - } - - private static class Id { - @SuppressWarnings("unused") // used via reflection - public T identity(T thingie) { - return thingie; - } - } - - @Test - public void testGetArgumentTypes() throws Exception { - Method identity = Id.class.getDeclaredMethod("identity", Object.class); - - TypeToken> token = new TypeToken >(){}; - TypeDescriptor> descriptor = new TypeDescriptor >(){}; - assertEquals( - token.method(identity).getParameters().get(0).getType().getType(), - descriptor.getArgumentTypes(identity).get(0).getType()); - - TypeToken>> genericToken = new TypeToken >>(){}; - TypeDescriptor>> genericDescriptor = new TypeDescriptor >>(){}; - assertEquals( - genericToken.method(identity).getParameters().get(0).getType().getType(), - genericDescriptor.getArgumentTypes(identity).get(0).getType()); - } - - private static class TypeRemembererer { - public TypeDescriptor descriptor1; - public TypeDescriptor descriptor2; - - public TypeRemembererer() { - descriptor1 = new TypeDescriptor(getClass()){}; - descriptor2 = new TypeDescriptor(getClass()){}; - } - } - - @Test - public void testTypeDescriptorNested2() throws Exception { - TypeRemembererer remembererer = new TypeRemembererer(){}; - assertEquals(new TypeToken() {}.getType(), remembererer.descriptor1.getType()); - assertEquals(new TypeToken() {}.getType(), remembererer.descriptor2.getType()); - - TypeRemembererer, Set> genericRemembererer = - new TypeRemembererer, Set>(){}; - assertEquals(new TypeToken>() {}.getType(), - genericRemembererer.descriptor1.getType()); - assertEquals(new TypeToken>() {}.getType(), - genericRemembererer.descriptor2.getType()); - } - - private static class GenericClass { } - - @Test - public void testGetTypeParameterGood() throws Exception { - @SuppressWarnings("rawtypes") - TypeVariable> bizzleT = - TypeDescriptor.of(GenericClass.class).getTypeParameter("BizzleT"); - assertEquals(GenericClass.class.getTypeParameters()[0], bizzleT); - } - - @Test - public void testGetTypeParameterBad() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("MerpleT"); // just check that the message gives actionable details - TypeDescriptor.of(GenericClass.class).getTypeParameter("MerpleT"); - } - - private static class GenericMaker { - public TypeRememberer> getRememberer() { - return new TypeRememberer>() {}; - } - } - - private static class GenericMaker2 { - public GenericMaker> getGenericMaker() { - return new GenericMaker>() {}; - } - } - - @Test - public void testEnclosing() throws Exception { - TypeRememberer> rememberer = new GenericMaker(){}.getRememberer(); - assertEquals( - new TypeToken>() {}.getType(), rememberer.descriptorByInstance.getType()); - - // descriptorByClass *is not* able to find the type of T because it comes from the enclosing - // instance of GenericMaker. - // assertEquals(new TypeToken>() {}.getType(), rememberer.descriptorByClass.getType()); - } - - @Test - public void testEnclosing2() throws Exception { - // If we don't override, the best we can get is List> - // TypeRememberer>> rememberer = - // new GenericMaker2(){}.getGenericMaker().getRememberer(); - // assertNotEquals( - // new TypeToken>>() {}.getType(), - // rememberer.descriptorByInstance.getType()); - - // If we've overridden the getGenericMaker we can determine the types. - TypeRememberer>> rememberer = new GenericMaker2() { - @Override public GenericMaker> getGenericMaker() { - return new GenericMaker>() {}; - } - }.getGenericMaker().getRememberer(); - assertEquals( - new TypeToken>>() {}.getType(), - rememberer.descriptorByInstance.getType()); - } -} diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypedPValueTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypedPValueTest.java deleted file mode 100644 index b0a13ec37d..0000000000 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/values/TypedPValueTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.values; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - - -/** - * Tests for {@link TypedPValue}, primarily focusing on Coder inference. - */ -@RunWith(JUnit4.class) -public class TypedPValueTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static class IdentityDoFn extends DoFn { - private static final long serialVersionUID = 0; - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element()); - } - } - - private static PCollectionTuple buildPCollectionTupleWithTags( - TupleTag mainOutputTag, TupleTag sideOutputTag) { - Pipeline p = TestPipeline.create(); - PCollection input = p.apply(Create.of(1, 2, 3)); - PCollectionTuple tuple = input.apply( - ParDo - .withOutputTags(mainOutputTag, TupleTagList.of(sideOutputTag)) - .of(new IdentityDoFn())); - return tuple; - } - - private static TupleTag makeTagStatically() { - return new TupleTag() {}; - } - - @Test - public void testUntypedSideOutputTupleTagGivesActionableMessage() { - TupleTag mainOutputTag = new TupleTag() {}; - // untypedSideOutputTag did not use anonymous subclass. - TupleTag untypedSideOutputTag = new TupleTag(); - PCollectionTuple tuple = buildPCollectionTupleWithTags(mainOutputTag, untypedSideOutputTag); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("No Coder has been manually specified"); - thrown.expectMessage("erasure"); - thrown.expectMessage("see TupleTag Javadoc"); - - tuple.get(untypedSideOutputTag).getCoder(); - } - - @Test - public void testStaticFactorySideOutputTupleTagGivesActionableMessage() { - TupleTag mainOutputTag = new TupleTag() {}; - // untypedSideOutputTag constructed from a static factory method. - TupleTag untypedSideOutputTag = makeTagStatically(); - PCollectionTuple tuple = buildPCollectionTupleWithTags(mainOutputTag, untypedSideOutputTag); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("No Coder has been manually specified"); - thrown.expectMessage("erasure"); - thrown.expectMessage("see TupleTag Javadoc"); - - tuple.get(untypedSideOutputTag).getCoder(); - } - - @Test - public void testTypedSideOutputTupleTag() { - TupleTag mainOutputTag = new TupleTag() {}; - // typedSideOutputTag was constructed with compile-time type information. - TupleTag typedSideOutputTag = new TupleTag() {}; - PCollectionTuple tuple = buildPCollectionTupleWithTags(mainOutputTag, typedSideOutputTag); - - assertThat(tuple.get(typedSideOutputTag).getCoder(), instanceOf(VarIntCoder.class)); - } - - @Test - public void testUntypedMainOutputTagTypedSideOutputTupleTag() { - // mainOutputTag is allowed to be untyped because Coder can be inferred other ways. - TupleTag mainOutputTag = new TupleTag<>(); - TupleTag typedSideOutputTag = new TupleTag() {}; - PCollectionTuple tuple = buildPCollectionTupleWithTags(mainOutputTag, typedSideOutputTag); - - assertThat(tuple.get(typedSideOutputTag).getCoder(), instanceOf(VarIntCoder.class)); - } - - // A simple class for which there should be no obvious Coder. - static class EmptyClass { - } - - private static class EmptyClassDoFn extends DoFn { - private static final long serialVersionUID = 0; - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(new EmptyClass()); - } - } - - @Test - public void testParDoWithNoSideOutputsErrorDoesNotMentionTupleTag() { - Pipeline p = TestPipeline.create(); - PCollection input = - p.apply(Create.of(1, 2, 3)).apply(ParDo.of(new EmptyClassDoFn())); - - thrown.expect(IllegalStateException.class); - - // Output specific to ParDo TupleTag side outputs should not be present. - thrown.expectMessage(not(containsString("erasure"))); - thrown.expectMessage(not(containsString("see TupleTag Javadoc"))); - // Instead, expect output suggesting other possible fixes. - thrown.expectMessage(containsString("Building a Coder using a registered CoderFactory failed")); - thrown.expectMessage( - containsString("Building a Coder from the @DefaultCoder annotation failed")); - thrown.expectMessage(containsString("Building a Coder from the fallback CoderProvider failed")); - - input.getCoder(); - } - - @Test - public void testFinishSpecifyingShouldFailIfNoCoderInferrable() { - Pipeline p = TestPipeline.create(); - PCollection unencodable = - p.apply(Create.of(1, 2, 3)).apply(ParDo.of(new EmptyClassDoFn())); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Unable to return a default Coder"); - thrown.expectMessage("Inferring a Coder from the CoderRegistry failed"); - - unencodable.finishSpecifying(); - } -} - diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java deleted file mode 100644 index d363bd473d..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/options/PipelineOptionsFactoryJava8Test.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.options; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Java 8 tests for {@link PipelineOptionsFactory}. - */ -@RunWith(JUnit4.class) -public class PipelineOptionsFactoryJava8Test { - @Rule public ExpectedException thrown = ExpectedException.none(); - - private interface OptionsWithDefaultMethod extends PipelineOptions { - default Number getValue() { - return 1024; - } - - void setValue(Number value); - } - - @Test - public void testDefaultMethodIgnoresDefaultImplementation() { - OptionsWithDefaultMethod optsWithDefault = - PipelineOptionsFactory.as(OptionsWithDefaultMethod.class); - assertThat(optsWithDefault.getValue(), nullValue()); - - optsWithDefault.setValue(12.25); - assertThat(optsWithDefault.getValue(), equalTo(Double.valueOf(12.25))); - } - - private interface ExtendedOptionsWithDefault extends OptionsWithDefaultMethod {} - - @Test - public void testDefaultMethodInExtendedClassIgnoresDefaultImplementation() { - OptionsWithDefaultMethod extendedOptsWithDefault = - PipelineOptionsFactory.as(ExtendedOptionsWithDefault.class); - assertThat(extendedOptsWithDefault.getValue(), nullValue()); - - extendedOptsWithDefault.setValue(Double.NEGATIVE_INFINITY); - assertThat(extendedOptsWithDefault.getValue(), equalTo(Double.NEGATIVE_INFINITY)); - } - - private interface Options extends PipelineOptions { - Number getValue(); - - void setValue(Number value); - } - - private interface SubtypeReturingOptions extends Options { - @Override - Integer getValue(); - void setValue(Integer value); - } - - @Test - public void testReturnTypeConflictThrows() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Method [getValue] has multiple definitions [public abstract java.lang.Integer " - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryJava8Test$" - + "SubtypeReturingOptions.getValue(), public abstract java.lang.Number " - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryJava8Test$Options" - + ".getValue()] with different return types for [" - + "com.google.cloud.dataflow.sdk.options.PipelineOptionsFactoryJava8Test$" - + "SubtypeReturingOptions]."); - PipelineOptionsFactory.as(SubtypeReturingOptions.class); - } -} diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java deleted file mode 100644 index 49476172e8..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/CombineJava8Test.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.not; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.display.DisplayData; -import com.google.cloud.dataflow.sdk.util.SerializableUtils; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import com.google.common.collect.Iterables; - -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Java 8 Tests for {@link Combine}. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("serial") -public class CombineJava8Test implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - /** - * Class for use in testing use of Java 8 method references. - */ - private static class Summer implements Serializable { - public int sum(Iterable integers) { - int sum = 0; - for (int i : integers) { - sum += i; - } - return sum; - } - } - - /** - * Tests creation of a global {@link Combine} via Java 8 lambda. - */ - @Test - public void testCombineGloballyLambda() { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.of(1, 2, 3, 4)) - .apply(Combine.globally(integers -> { - int sum = 0; - for (int i : integers) { - sum += i; - } - return sum; - })); - - DataflowAssert.that(output).containsInAnyOrder(10); - pipeline.run(); - } - - /** - * Tests creation of a global {@link Combine} via a Java 8 method reference. - */ - @Test - public void testCombineGloballyInstanceMethodReference() { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.of(1, 2, 3, 4)) - .apply(Combine.globally(new Summer()::sum)); - - DataflowAssert.that(output).containsInAnyOrder(10); - pipeline.run(); - } - - /** - * Tests creation of a per-key {@link Combine} via a Java 8 lambda. - */ - @Test - public void testCombinePerKeyLambda() { - Pipeline pipeline = TestPipeline.create(); - - PCollection> output = pipeline - .apply(Create.of(KV.of("a", 1), KV.of("b", 2), KV.of("a", 3), KV.of("c", 4))) - .apply(Combine.perKey(integers -> { - int sum = 0; - for (int i : integers) { - sum += i; - } - return sum; - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("a", 4), - KV.of("b", 2), - KV.of("c", 4)); - pipeline.run(); - } - - /** - * Tests creation of a per-key {@link Combine} via a Java 8 method reference. - */ - @Test - public void testCombinePerKeyInstanceMethodReference() { - Pipeline pipeline = TestPipeline.create(); - - PCollection> output = pipeline - .apply(Create.of(KV.of("a", 1), KV.of("b", 2), KV.of("a", 3), KV.of("c", 4))) - .apply(Combine.perKey(new Summer()::sum)); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("a", 4), - KV.of("b", 2), - KV.of("c", 4)); - pipeline.run(); - } - - /** - * Tests that we can serialize {@link Combine.CombineFn CombineFns} constructed from a lambda. - * Lambdas can be problematic because the {@link Class} object is synthetic and cannot be - * deserialized. - */ - @Test - public void testLambdaSerialization() { - SerializableFunction, Object> combiner = xs -> Iterables.getFirst(xs, 0); - - boolean lambdaClassSerializationThrows; - try { - SerializableUtils.clone(combiner.getClass()); - lambdaClassSerializationThrows = false; - } catch (IllegalArgumentException e) { - // Expected - lambdaClassSerializationThrows = true; - } - Assume.assumeTrue("Expected lambda class serialization to fail. " - + "If it's fixed, we can remove special behavior in Combine.", - lambdaClassSerializationThrows); - - - Combine.Globally combine = Combine.globally(combiner); - SerializableUtils.clone(combine); // should not throw. - } - - @Test - public void testLambdaDisplayData() { - Combine.Globally combine = Combine.globally(xs -> Iterables.getFirst(xs, 0)); - DisplayData displayData = DisplayData.from(combine); - assertThat(displayData.items(), not(empty())); - } -} diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FilterJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FilterJava8Test.java deleted file mode 100644 index db65932ccb..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FilterJava8Test.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Java 8 Tests for {@link Filter}. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("serial") -public class FilterJava8Test implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - @Category(RunnableOnService.class) - public void testIdentityFilterByPredicate() { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.of(591, 11789, 1257, 24578, 24799, 307)) - .apply(Filter.byPredicate(i -> true)); - - DataflowAssert.that(output).containsInAnyOrder(591, 11789, 1257, 24578, 24799, 307); - pipeline.run(); - } - - @Test - public void testNoFilterByPredicate() { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.of(1, 2, 4, 5)) - .apply(Filter.byPredicate(i -> false)); - - DataflowAssert.that(output).empty(); - pipeline.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testFilterByPredicate() { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.of(1, 2, 3, 4, 5, 6, 7)) - .apply(Filter.byPredicate(i -> i % 2 == 0)); - - DataflowAssert.that(output).containsInAnyOrder(2, 4, 6); - pipeline.run(); - } - - /** - * Confirms that in Java 8 style, where a lambda results in a rawtype, the output type token is - * not useful. If this test ever fails there may be simplifications available to us. - */ - @Test - public void testFilterParDoOutputTypeDescriptorRaw() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - PCollection output = pipeline - .apply(Create.of("hello")) - .apply(Filter.by(s -> true)); - - thrown.expect(CannotProvideCoderException.class); - pipeline.getCoderRegistry().getDefaultCoder(output.getTypeDescriptor()); - } - - @Test - @Category(RunnableOnService.class) - public void testFilterByMethodReference() { - Pipeline pipeline = TestPipeline.create(); - - PCollection output = pipeline - .apply(Create.of(1, 2, 3, 4, 5, 6, 7)) - .apply(Filter.byPredicate(new EvenFilter()::isEven)); - - DataflowAssert.that(output).containsInAnyOrder(2, 4, 6); - pipeline.run(); - } - - private static class EvenFilter implements Serializable { - public boolean isEven(int i) { - return i % 2 == 0; - } - } -} diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsJava8Test.java deleted file mode 100644 index e0b946b77f..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/FlatMapElementsJava8Test.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.List; - -/** - * Java 8 Tests for {@link FlatMapElements}. - */ -@RunWith(JUnit4.class) -public class FlatMapElementsJava8Test implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - /** - * Basic test of {@link FlatMapElements} with a lambda (which is instantiated as a - * {@link SerializableFunction}). - */ - @Test - public void testFlatMapBasic() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of(1, 2, 3)) - .apply(FlatMapElements - // Note that the input type annotation is required. - .via((Integer i) -> ImmutableList.of(i, -i)) - .withOutputType(new TypeDescriptor() {})); - - DataflowAssert.that(output).containsInAnyOrder(1, 3, -1, -3, 2, -2); - pipeline.run(); - } - - /** - * Basic test of {@link FlatMapElements} with a method reference. - */ - @Test - public void testFlatMapMethodReference() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of(1, 2, 3)) - .apply(FlatMapElements - // Note that the input type annotation is required. - .via(new Negater()::numAndNegation) - .withOutputType(new TypeDescriptor() {})); - - DataflowAssert.that(output).containsInAnyOrder(1, 3, -1, -3, 2, -2); - pipeline.run(); - } - - private static class Negater implements Serializable { - public List numAndNegation(int input) { - return ImmutableList.of(input, -input); - } - } -} diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/MapElementsJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/MapElementsJava8Test.java deleted file mode 100644 index 123e680387..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/MapElementsJava8Test.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Java 8 tests for {@link MapElements}. - */ -@RunWith(JUnit4.class) -public class MapElementsJava8Test implements Serializable { - - /** - * Basic test of {@link MapElements} with a lambda (which is instantiated as a - * {@link SerializableFunction}). - */ - @Test - public void testMapBasic() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of(1, 2, 3)) - .apply(MapElements - // Note that the type annotation is required (for Java, not for Dataflow) - .via((Integer i) -> i * 2) - .withOutputType(new TypeDescriptor() {})); - - DataflowAssert.that(output).containsInAnyOrder(6, 2, 4); - pipeline.run(); - } - - /** - * Basic test of {@link MapElements} with a method reference. - */ - @Test - public void testMapMethodReference() throws Exception { - Pipeline pipeline = TestPipeline.create(); - PCollection output = pipeline - .apply(Create.of(1, 2, 3)) - .apply(MapElements - // Note that the type annotation is required (for Java, not for Dataflow) - .via(new Doubler()::doubleIt) - .withOutputType(new TypeDescriptor() {})); - - DataflowAssert.that(output).containsInAnyOrder(6, 2, 4); - pipeline.run(); - } - - private static class Doubler implements Serializable { - public int doubleIt(int val) { - return val * 2; - } - } -} diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/PartitionJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/PartitionJava8Test.java deleted file mode 100644 index c459ada0ce..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/PartitionJava8Test.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Java 8 Tests for {@link Filter}. - */ -@RunWith(JUnit4.class) -@SuppressWarnings("serial") -public class PartitionJava8Test implements Serializable { - - @Rule - public transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testModPartition() { - Pipeline pipeline = TestPipeline.create(); - - PCollectionList outputs = pipeline - .apply(Create.of(1, 2, 4, 5)) - .apply(Partition.of(3, (element, numPartitions) -> element % numPartitions)); - assertEquals(3, outputs.size()); - DataflowAssert.that(outputs.get(0)).empty(); - DataflowAssert.that(outputs.get(1)).containsInAnyOrder(1, 4); - DataflowAssert.that(outputs.get(2)).containsInAnyOrder(2, 5); - pipeline.run(); - } - - /** - * Confirms that in Java 8 style, where a lambda results in a rawtype, the output type token is - * not useful. If this test ever fails there may be simplifications available to us. - */ - @Test - public void testPartitionFnOutputTypeDescriptorRaw() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - PCollectionList output = pipeline - .apply(Create.of("hello")) - .apply(Partition.of(1, (element, numPartitions) -> 0)); - - thrown.expect(CannotProvideCoderException.class); - pipeline.getCoderRegistry().getDefaultCoder(output.get(0).getTypeDescriptor()); - } -} diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesJava8Test.java deleted file mode 100644 index d9e2180b7d..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/RemoveDuplicatesJava8Test.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.HashSet; -import java.util.Set; - -/** - * Java 8 tests for {@link RemoveDuplicates}. - */ -@RunWith(JUnit4.class) -public class RemoveDuplicatesJava8Test { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void withLambdaRepresentativeValuesFnAndTypeDescriptorShouldApplyFn() { - TestPipeline p = TestPipeline.create(); - - Multimap predupedContents = HashMultimap.create(); - predupedContents.put(3, "foo"); - predupedContents.put(4, "foos"); - predupedContents.put(6, "barbaz"); - predupedContents.put(6, "bazbar"); - PCollection dupes = - p.apply(Create.of("foo", "foos", "barbaz", "barbaz", "bazbar", "foo")); - PCollection deduped = - dupes.apply(RemoveDuplicates.withRepresentativeValueFn((String s) -> s.length()) - .withRepresentativeType(TypeDescriptor.of(Integer.class))); - - DataflowAssert.that(deduped).satisfies((Iterable strs) -> { - Set seenLengths = new HashSet<>(); - for (String s : strs) { - assertThat(predupedContents.values(), hasItem(s)); - assertThat(seenLengths, not(contains(s.length()))); - seenLengths.add(s.length()); - } - return null; - }); - - p.run(); - } - - @Test - public void withLambdaRepresentativeValuesFnNoTypeDescriptorShouldThrow() { - TestPipeline p = TestPipeline.create(); - - Multimap predupedContents = HashMultimap.create(); - predupedContents.put(3, "foo"); - predupedContents.put(4, "foos"); - predupedContents.put(6, "barbaz"); - predupedContents.put(6, "bazbar"); - PCollection dupes = - p.apply(Create.of("foo", "foos", "barbaz", "barbaz", "bazbar", "foo")); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Unable to return a default Coder for RemoveRepresentativeDupes"); - thrown.expectMessage("Cannot provide a coder for type variable K"); - thrown.expectMessage("the actual type is unknown due to erasure."); - - // Thrown when applying a transform to the internal WithKeys that withRepresentativeValueFn is - // implemented with - dupes.apply("RemoveRepresentativeDupes", - RemoveDuplicates.withRepresentativeValueFn((String s) -> s.length())); - } -} - diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithKeysJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithKeysJava8Test.java deleted file mode 100644 index c10af29030..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithKeysJava8Test.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Java 8 Tests for {@link WithKeys}. - */ -@RunWith(JUnit4.class) -public class WithKeysJava8Test { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - @Category(RunnableOnService.class) - public void withLambdaAndTypeDescriptorShouldSucceed() { - TestPipeline p = TestPipeline.create(); - - PCollection values = p.apply(Create.of("1234", "3210", "0", "-12")); - PCollection> kvs = values.apply( - WithKeys.of((String s) -> Integer.valueOf(s)) - .withKeyType(TypeDescriptor.of(Integer.class))); - - DataflowAssert.that(kvs).containsInAnyOrder( - KV.of(1234, "1234"), KV.of(0, "0"), KV.of(-12, "-12"), KV.of(3210, "3210")); - - p.run(); - } - - @Test - public void withLambdaAndNoTypeDescriptorShouldThrow() { - TestPipeline p = TestPipeline.create(); - - PCollection values = p.apply(Create.of("1234", "3210", "0", "-12")); - - values.apply("ApplyKeysWithWithKeys", WithKeys.of((String s) -> Integer.valueOf(s))); - - thrown.expect(PipelineExecutionException.class); - thrown.expectMessage("Unable to return a default Coder for ApplyKeysWithWithKeys"); - thrown.expectMessage("Cannot provide a coder for type variable K"); - thrown.expectMessage("the actual type is unknown due to erasure."); - - p.run(); - } -} - diff --git a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithTimestampsJava8Test.java b/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithTimestampsJava8Test.java deleted file mode 100644 index 50b5ff737f..0000000000 --- a/sdk/src/test/java8/com/google/cloud/dataflow/sdk/transforms/WithTimestampsJava8Test.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk.transforms; - -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; - -/** - * Java 8 tests for {@link WithTimestamps}. - */ -@RunWith(JUnit4.class) -public class WithTimestampsJava8Test implements Serializable { - @Test - @Category(RunnableOnService.class) - public void withTimestampsLambdaShouldApplyTimestamps() { - TestPipeline p = TestPipeline.create(); - - String yearTwoThousand = "946684800000"; - PCollection timestamped = - p.apply(Create.of("1234", "0", Integer.toString(Integer.MAX_VALUE), yearTwoThousand)) - .apply(WithTimestamps.of((String input) -> new Instant(Long.valueOf(yearTwoThousand)))); - - PCollection> timestampedVals = - timestamped.apply(ParDo.of(new DoFn>() { - @Override - public void processElement(DoFn>.ProcessContext c) - throws Exception { - c.output(KV.of(c.element(), c.timestamp())); - } - })); - - DataflowAssert.that(timestamped) - .containsInAnyOrder(yearTwoThousand, "0", "1234", Integer.toString(Integer.MAX_VALUE)); - DataflowAssert.that(timestampedVals) - .containsInAnyOrder( - KV.of("0", new Instant(0)), - KV.of("1234", new Instant("1234")), - KV.of(Integer.toString(Integer.MAX_VALUE), new Instant(Integer.MAX_VALUE)), - KV.of(yearTwoThousand, new Instant(Long.valueOf(yearTwoThousand)))); - } -} - From dacd837c812cfbaff2b03de64d1eba79f0d5d6de Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 14:59:45 -0800 Subject: [PATCH 659/751] Remove all example source files. They are now brought by the dependency on Apache Beam. --- examples/README.md | 95 --- .../dataflow/examples/DebuggingWordCount.java | 198 ------ .../dataflow/examples/MinimalWordCount.java | 117 ---- .../dataflow/examples/WindowedWordCount.java | 274 --------- .../cloud/dataflow/examples/WordCount.java | 206 ------- .../common/DataflowExampleOptions.java | 34 -- .../examples/common/DataflowExampleUtils.java | 489 --------------- .../common/ExampleBigQueryTableOptions.java | 53 -- ...mplePubsubTopicAndSubscriptionOptions.java | 44 -- .../common/ExamplePubsubTopicOptions.java | 44 -- .../examples/common/PubsubFileInjector.java | 153 ----- .../examples/complete/AutoComplete.java | 535 ----------------- .../dataflow/examples/complete/README.md | 44 -- .../complete/StreamingWordExtract.java | 163 ----- .../dataflow/examples/complete/TfIdf.java | 431 ------------- .../complete/TopWikipediaSessions.java | 214 ------- .../examples/complete/TrafficMaxLaneFlow.java | 425 ------------- .../examples/complete/TrafficRoutes.java | 459 -------------- .../examples/cookbook/BigQueryTornadoes.java | 179 ------ .../cookbook/CombinePerKeyExamples.java | 223 ------- .../examples/cookbook/DatastoreWordCount.java | 267 --------- .../examples/cookbook/DeDupExample.java | 100 ---- .../examples/cookbook/FilterExamples.java | 266 --------- .../examples/cookbook/JoinExamples.java | 185 ------ .../examples/cookbook/MaxPerKeyExamples.java | 173 ------ .../dataflow/examples/cookbook/README.md | 55 -- .../examples/cookbook/TriggerExample.java | 564 ------------------ .../examples/MinimalWordCountJava8.java | 68 --- .../examples/complete/game/GameStats.java | 352 ----------- .../complete/game/HourlyTeamScore.java | 195 ------ .../examples/complete/game/LeaderBoard.java | 279 --------- .../dataflow/examples/complete/game/README.md | 119 ---- .../examples/complete/game/UserScore.java | 239 -------- .../complete/game/injector/Injector.java | 417 ------------- .../complete/game/injector/InjectorUtils.java | 101 ---- .../injector/RetryHttpInitializerWrapper.java | 128 ---- .../complete/game/utils/WriteToBigQuery.java | 134 ----- .../game/utils/WriteWindowedToBigQuery.java | 76 --- .../examples/DebuggingWordCountTest.java | 45 -- .../dataflow/examples/WordCountTest.java | 85 --- .../examples/complete/AutoCompleteTest.java | 181 ------ .../dataflow/examples/complete/TfIdfTest.java | 67 --- .../complete/TopWikipediaSessionsTest.java | 62 -- .../cookbook/BigQueryTornadoesTest.java | 80 --- .../cookbook/CombinePerKeyExamplesTest.java | 90 --- .../examples/cookbook/DeDupExampleTest.java | 83 --- .../examples/cookbook/FilterExamplesTest.java | 85 --- .../examples/cookbook/JoinExamplesTest.java | 114 ---- .../cookbook/MaxPerKeyExamplesTest.java | 85 --- .../examples/cookbook/TriggerExampleTest.java | 160 ----- .../examples/MinimalWordCountJava8Test.java | 103 ---- .../examples/complete/game/GameStatsTest.java | 81 --- .../complete/game/HourlyTeamScoreTest.java | 111 ---- .../complete/game/LeaderBoardTest.java | 367 ------------ .../examples/complete/game/UserScoreTest.java | 154 ----- 55 files changed, 10051 deletions(-) delete mode 100644 examples/README.md delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/MinimalWordCount.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleOptions.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/common/ExampleBigQueryTableOptions.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicAndSubscriptionOptions.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicOptions.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/common/PubsubFileInjector.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/complete/README.md delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/complete/StreamingWordExtract.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/complete/TfIdf.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficMaxLaneFlow.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficRoutes.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoes.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamples.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DeDupExample.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/FilterExamples.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/JoinExamples.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamples.java delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/README.md delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/README.md delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/InjectorUtils.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/RetryHttpInitializerWrapper.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java delete mode 100644 examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/DebuggingWordCountTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/WordCountTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/complete/AutoCompleteTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/complete/TfIdfTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessionsTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoesTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamplesTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/DeDupExampleTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/FilterExamplesTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/JoinExamplesTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamplesTest.java delete mode 100644 examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java delete mode 100644 examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java delete mode 100644 examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/GameStatsTest.java delete mode 100644 examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScoreTest.java delete mode 100644 examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java delete mode 100644 examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/UserScoreTest.java diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index cbcd01fc0f..0000000000 --- a/examples/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# Example Pipelines - -The examples included in this module serve to demonstrate the basic -functionality of Google Cloud Dataflow, and act as starting points for -the development of more complex pipelines. - -## Word Count - -A good starting point for new users is our set of -[word count](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/src/main/java/com/google/cloud/dataflow/examples) examples, which computes word frequencies. This series of four successively more detailed pipelines is described in detail in the accompanying [walkthrough](https://cloud.google.com/dataflow/examples/wordcount-example). - -1. [`MinimalWordCount`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/src/main/java/com/google/cloud/dataflow/examples/MinimalWordCount.java) is the simplest word count pipeline and introduces basic concepts like [Pipelines](https://cloud.google.com/dataflow/model/pipelines), -[PCollections](https://cloud.google.com/dataflow/model/pcollection), -[ParDo](https://cloud.google.com/dataflow/model/par-do), -and [reading and writing data](https://cloud.google.com/dataflow/model/reading-and-writing-data) from external storage. - -1. [`WordCount`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java) introduces Dataflow best practices like [PipelineOptions](https://cloud.google.com/dataflow/pipelines/constructing-your-pipeline#Creating) and custom [PTransforms](https://cloud.google.com/dataflow/model/composite-transforms). - -1. [`DebuggingWordCount`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java) -shows how to view live aggregators in the [Dataflow Monitoring Interface](https://cloud.google.com/dataflow/pipelines/dataflow-monitoring-intf), get the most out of -[Cloud Logging](https://cloud.google.com/dataflow/pipelines/logging) integration, and start writing -[good tests](https://cloud.google.com/dataflow/pipelines/testing-your-pipeline). - -1. [`WindowedWordCount`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java) shows how to run the same pipeline over either unbounded PCollections in streaming mode or bounded PCollections in batch mode. - -## Building and Running - -The examples in this repository can be built and executed from the root directory by running: - - mvn compile exec:java -pl examples \ - -Dexec.mainClass=
              \ - -Dexec.args="" - -For example, you can execute the `WordCount` pipeline on your local machine as follows: - - mvn compile exec:java -pl examples \ - -Dexec.mainClass=com.google.cloud.dataflow.examples.WordCount \ - -Dexec.args="--inputFile= --output=" - -Once you have followed the general Cloud Dataflow -[Getting Started](https://cloud.google.com/dataflow/getting-started) instructions, you can execute -the same pipeline on fully managed resources in Google Cloud Platform: - - mvn compile exec:java -pl examples \ - -Dexec.mainClass=com.google.cloud.dataflow.examples.WordCount \ - -Dexec.args="--project= \ - --stagingLocation= \ - --runner=BlockingDataflowPipelineRunner" - -Make sure to use your project id, not the project number or the descriptive name. -The Cloud Storage location should be entered in the form of -`gs://bucket/path/to/staging/directory`. - -Alternatively, you may choose to bundle all dependencies into a single JAR and -execute it outside of the Maven environment. For example, you can execute the -following commands to create the -bundled JAR of the examples and execute it both locally and in Cloud -Platform: - - mvn package - - java -cp examples/target/google-cloud-dataflow-java-examples-all-bundled-.jar \ - com.google.cloud.dataflow.examples.WordCount \ - --inputFile= --output= - - java -cp examples/target/google-cloud-dataflow-java-examples-all-bundled-.jar \ - com.google.cloud.dataflow.examples.WordCount \ - --project= \ - --stagingLocation= \ - --runner=BlockingDataflowPipelineRunner - -Other examples can be run similarly by replacing the `WordCount` class path with the example classpath, e.g. -`com.google.cloud.dataflow.examples.cookbook.BigQueryTornadoes`, -and adjusting runtime options under the `Dexec.args` parameter, as specified in -the example itself. - -Note that when running Maven on Microsoft Windows platform, backslashes (`\`) -under the `Dexec.args` parameter should be escaped with another backslash. For -example, input file pattern of `c:\*.txt` should be entered as `c:\\*.txt`. - -## Beyond Word Count - -After you've finished running your first few word count pipelines, take a look at the [`cookbook`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook) -directory for some common and useful patterns like joining, filtering, and combining. - -The [`complete`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/src/main/java/com/google/cloud/dataflow/examples/complete) -directory contains a few realistic end-to-end pipelines. - -See the -[Java 8](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/examples/src/main/java8/com/google/cloud/dataflow/examples) -examples as well. This directory includes a Java 8 version of the -MinimalWordCount example, as well as series of examples in a simple 'mobile -gaming' domain. This series introduces some advanced concepts and provides -additional examples of using Java 8 syntax. Other than usage of Java 8 lambda -expressions, the concepts that are used apply equally well in Java 7. diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java deleted file mode 100644 index bd1748b69f..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/DebuggingWordCount.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - - -/** - * An example that verifies word counts in Shakespeare and includes Dataflow best practices. - * - *

              This class, {@link DebuggingWordCount}, is the third in a series of four successively more - * detailed 'word count' examples. You may first want to take a look at {@link MinimalWordCount} - * and {@link WordCount}. After you've looked at this example, then see the - * {@link WindowedWordCount} pipeline, for introduction of additional concepts. - * - *

              Basic concepts, also in the MinimalWordCount and WordCount examples: - * Reading text files; counting a PCollection; executing a Pipeline both locally - * and using the Dataflow service; defining DoFns. - * - *

              New Concepts: - *

              - *   1. Logging to Cloud Logging
              - *   2. Controlling Dataflow worker log levels
              - *   3. Creating a custom aggregator
              - *   4. Testing your Pipeline via DataflowAssert
              - * 
              - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * - *

              To execute this pipeline using the Dataflow service and the additional logging discussed - * below, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - *   --workerLogLevelOverrides={"com.google.cloud.dataflow.examples":"DEBUG"}
              - * }
              - * 
              - * - *

              Note that when you run via mvn exec, you may need to escape - * the quotations as appropriate for your shell. For example, in bash: - *

              - * mvn compile exec:java ... \
              - *   -Dexec.args="... \
              - *     --workerLogLevelOverrides={\\\"com.google.cloud.dataflow.examples\\\":\\\"DEBUG\\\"}"
              - * 
              - * - *

              Concept #2: Dataflow workers which execute user code are configured to log to Cloud - * Logging by default at "INFO" log level and higher. One may override log levels for specific - * logging namespaces by specifying: - *

              
              - *   --workerLogLevelOverrides={"Name1":"Level1","Name2":"Level2",...}
              - * 
              - * For example, by specifying: - *
              
              - *   --workerLogLevelOverrides={"com.google.cloud.dataflow.examples":"DEBUG"}
              - * 
              - * when executing this pipeline using the Dataflow service, Cloud Logging would contain only - * "DEBUG" or higher level logs for the {@code com.google.cloud.dataflow.examples} package in - * addition to the default "INFO" or higher level logs. In addition, the default Dataflow worker - * logging configuration can be overridden by specifying - * {@code --defaultWorkerLogLevel=}. For example, - * by specifying {@code --defaultWorkerLogLevel=DEBUG} when executing this pipeline with - * the Dataflow service, Cloud Logging would contain all "DEBUG" or higher level logs. Note - * that changing the default worker log level to TRACE or DEBUG will significantly increase - * the amount of logs output. - * - *

              The input file defaults to {@code gs://dataflow-samples/shakespeare/kinglear.txt} and can be - * overridden with {@code --inputFile}. - */ -public class DebuggingWordCount { - /** A DoFn that filters for a specific key based upon a regular expression. */ - public static class FilterTextFn extends DoFn, KV> { - /** - * Concept #1: The logger below uses the fully qualified class name of FilterTextFn - * as the logger. All log statements emitted by this logger will be referenced by this name - * and will be visible in the Cloud Logging UI. Learn more at https://cloud.google.com/logging - * about the Cloud Logging UI. - */ - private static final Logger LOG = LoggerFactory.getLogger(FilterTextFn.class); - - private final Pattern filter; - public FilterTextFn(String pattern) { - filter = Pattern.compile(pattern); - } - - /** - * Concept #3: A custom aggregator can track values in your pipeline as it runs. Those - * values will be displayed in the Dataflow Monitoring UI when this pipeline is run using the - * Dataflow service. These aggregators below track the number of matched and unmatched words. - * Learn more at https://cloud.google.com/dataflow/pipelines/dataflow-monitoring-intf about - * the Dataflow Monitoring UI. - */ - private final Aggregator matchedWords = - createAggregator("matchedWords", new Sum.SumLongFn()); - private final Aggregator unmatchedWords = - createAggregator("umatchedWords", new Sum.SumLongFn()); - - @Override - public void processElement(ProcessContext c) { - if (filter.matcher(c.element().getKey()).matches()) { - // Log at the "DEBUG" level each element that we match. When executing this pipeline - // using the Dataflow service, these log lines will appear in the Cloud Logging UI - // only if the log level is set to "DEBUG" or lower. - LOG.debug("Matched: " + c.element().getKey()); - matchedWords.addValue(1L); - c.output(c.element()); - } else { - // Log at the "TRACE" level each element that is not matched. Different log levels - // can be used to control the verbosity of logging providing an effective mechanism - // to filter less important information. - LOG.trace("Did not match: " + c.element().getKey()); - unmatchedWords.addValue(1L); - } - } - } - - /** - * Options supported by {@link DebuggingWordCount}. - * - *

              Inherits standard configuration options and all options defined in - * {@link WordCount.WordCountOptions}. - */ - public interface WordCountOptions extends WordCount.WordCountOptions { - - @Description("Regex filter pattern to use in DebuggingWordCount. " - + "Only words matching this pattern will be counted.") - @Default.String("Flourish|stomach") - String getFilterPattern(); - void setFilterPattern(String value); - } - - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); - Pipeline p = Pipeline.create(options); - - PCollection> filteredWords = - p.apply(TextIO.Read.named("ReadLines").from(options.getInputFile())) - .apply(new WordCount.CountWords()) - .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); - - /** - * Concept #4: DataflowAssert is a set of convenient PTransforms in the style of - * Hamcrest's collection matchers that can be used when writing Pipeline level tests - * to validate the contents of PCollections. DataflowAssert is best used in unit tests - * with small data sets but is demonstrated here as a teaching tool. - * - *

              Below we verify that the set of filtered words matches our expected counts. Note - * that DataflowAssert does not provide any output and that successful completion of the - * Pipeline implies that the expectations were met. Learn more at - * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline on how to test - * your Pipeline and see {@link DebuggingWordCountTest} for an example unit test. - */ - List> expectedResults = Arrays.asList( - KV.of("Flourish", 3L), - KV.of("stomach", 1L)); - DataflowAssert.that(filteredWords).containsInAnyOrder(expectedResults); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/MinimalWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/MinimalWordCount.java deleted file mode 100644 index 4ed05207c4..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/MinimalWordCount.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; -import com.google.cloud.dataflow.sdk.values.KV; - - -/** - * An example that counts words in Shakespeare. - * - *

              This class, {@link MinimalWordCount}, is the first in a series of four successively more - * detailed 'word count' examples. Here, for simplicity, we don't show any error-checking or - * argument processing, and focus on construction of the pipeline, which chains together the - * application of core transforms. - * - *

              Next, see the {@link WordCount} pipeline, then the {@link DebuggingWordCount}, and finally - * the {@link WindowedWordCount} pipeline, for more detailed examples that introduce additional - * concepts. - * - *

              Concepts: - *

              - *   1. Reading data from text files
              - *   2. Specifying 'inline' transforms
              - *   3. Counting a PCollection
              - *   4. Writing data to Cloud Storage as text files
              - * 
              - * - *

              To execute this pipeline, first edit the code to set your project ID, the staging - * location, and the output location. The specified GCS bucket(s) must already exist. - * - *

              Then, run the pipeline as described in the README. It will be deployed and run using the - * Dataflow service. No args are required to run the pipeline. You can see the results in your - * output bucket in the GCS browser. - */ -public class MinimalWordCount { - - public static void main(String[] args) { - // Create a DataflowPipelineOptions object. This object lets us set various execution - // options for our pipeline, such as the associated Cloud Platform project and the location - // in Google Cloud Storage to stage files. - DataflowPipelineOptions options = PipelineOptionsFactory.create() - .as(DataflowPipelineOptions.class); - options.setRunner(BlockingDataflowPipelineRunner.class); - // CHANGE 1/3: Your project ID is required in order to run your pipeline on the Google Cloud. - options.setProject("SET_YOUR_PROJECT_ID_HERE"); - // CHANGE 2/3: Your Google Cloud Storage path is required for staging local files. - options.setStagingLocation("gs://SET_YOUR_BUCKET_NAME_HERE/AND_STAGING_DIRECTORY"); - - // Create the Pipeline object with the options we defined above. - Pipeline p = Pipeline.create(options); - - // Apply the pipeline's transforms. - - // Concept #1: Apply a root transform to the pipeline; in this case, TextIO.Read to read a set - // of input text files. TextIO.Read returns a PCollection where each element is one line from - // the input text (a set of Shakespeare's texts). - p.apply(TextIO.Read.from("gs://dataflow-samples/shakespeare/*")) - // Concept #2: Apply a ParDo transform to our PCollection of text lines. This ParDo invokes a - // DoFn (defined in-line) on each element that tokenizes the text line into individual words. - // The ParDo returns a PCollection, where each element is an individual word in - // Shakespeare's collected texts. - .apply(ParDo.named("ExtractWords").of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - for (String word : c.element().split("[^a-zA-Z']+")) { - if (!word.isEmpty()) { - c.output(word); - } - } - } - })) - // Concept #3: Apply the Count transform to our PCollection of individual words. The Count - // transform returns a new PCollection of key/value pairs, where each key represents a unique - // word in the text. The associated value is the occurrence count for that word. - .apply(Count.perElement()) - // Apply a MapElements transform that formats our PCollection of word counts into a printable - // string, suitable for writing to an output file. - .apply("FormatResults", MapElements.via(new SimpleFunction, String>() { - @Override - public String apply(KV input) { - return input.getKey() + ": " + input.getValue(); - } - })) - // Concept #4: Apply a write transform, TextIO.Write, at the end of the pipeline. - // TextIO.Write writes the contents of a PCollection (in this case, our PCollection of - // formatted strings) to a series of text files in Google Cloud Storage. - // CHANGE 3/3: The Google Cloud Storage path is required for outputting the results to. - .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); - - // Run the pipeline. - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java deleted file mode 100644 index d523159156..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/WindowedWordCount.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.examples.common.DataflowExampleOptions; -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions; -import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicOptions; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - - -/** - * An example that counts words in text, and can run over either unbounded or bounded input - * collections. - * - *

              This class, {@link WindowedWordCount}, is the last in a series of four successively more - * detailed 'word count' examples. First take a look at {@link MinimalWordCount}, - * {@link WordCount}, and {@link DebuggingWordCount}. - * - *

              Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples: - * Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally - * and using the Dataflow service; defining DoFns; creating a custom aggregator; - * user-defined PTransforms; defining PipelineOptions. - * - *

              New Concepts: - *

              - *   1. Unbounded and bounded pipeline input modes
              - *   2. Adding timestamps to data
              - *   3. PubSub topics as sources
              - *   4. Windowing
              - *   5. Re-using PTransforms over windowed PCollections
              - *   6. Writing to BigQuery
              - * 
              - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * - *

              Optionally specify the input file path via: - * {@code --inputFile=gs://INPUT_PATH}, - * which defaults to {@code gs://dataflow-samples/shakespeare/kinglear.txt}. - * - *

              Specify an output BigQuery dataset and optionally, a table for the output. If you don't - * specify the table, one will be created for you using the job name. If you don't specify the - * dataset, a dataset called {@code dataflow-examples} must already exist in your project. - * {@code --bigQueryDataset=YOUR-DATASET --bigQueryTable=YOUR-NEW-TABLE-NAME}. - * - *

              Decide whether you want your pipeline to run with 'bounded' (such as files in GCS) or - * 'unbounded' input (such as a PubSub topic). To run with unbounded input, set - * {@code --unbounded=true}. Then, optionally specify the Google Cloud PubSub topic to read from - * via {@code --pubsubTopic=projects/PROJECT_ID/topics/YOUR_TOPIC_NAME}. If the topic does not - * exist, the pipeline will create one for you. It will delete this topic when it terminates. - * The pipeline will automatically launch an auxiliary batch pipeline to populate the given PubSub - * topic with the contents of the {@code --inputFile}, in order to make the example easy to run. - * If you want to use an independently-populated PubSub topic, indicate this by setting - * {@code --inputFile=""}. In that case, the auxiliary pipeline will not be started. - * - *

              By default, the pipeline will do fixed windowing, on 1-minute windows. You can - * change this interval by setting the {@code --windowSize} parameter, e.g. {@code --windowSize=10} - * for 10-minute windows. - */ -public class WindowedWordCount { - private static final Logger LOG = LoggerFactory.getLogger(WindowedWordCount.class); - static final int WINDOW_SIZE = 1; // Default window duration in minutes - - /** - * Concept #2: A DoFn that sets the data element timestamp. This is a silly method, just for - * this example, for the bounded data case. - * - *

              Imagine that many ghosts of Shakespeare are all typing madly at the same time to recreate - * his masterworks. Each line of the corpus will get a random associated timestamp somewhere in a - * 2-hour period. - */ - static class AddTimestampFn extends DoFn { - private static final Duration RAND_RANGE = Duration.standardHours(2); - private final Instant minTimestamp; - - AddTimestampFn() { - this.minTimestamp = new Instant(System.currentTimeMillis()); - } - - @Override - public void processElement(ProcessContext c) { - // Generate a timestamp that falls somewhere in the past two hours. - long randMillis = (long) (Math.random() * RAND_RANGE.getMillis()); - Instant randomTimestamp = minTimestamp.plus(randMillis); - /** - * Concept #2: Set the data element with that timestamp. - */ - c.outputWithTimestamp(c.element(), new Instant(randomTimestamp)); - } - } - - /** A DoFn that converts a Word and Count into a BigQuery table row. */ - static class FormatAsTableRowFn extends DoFn, TableRow> { - @Override - public void processElement(ProcessContext c) { - TableRow row = new TableRow() - .set("word", c.element().getKey()) - .set("count", c.element().getValue()) - // include a field for the window timestamp - .set("window_timestamp", c.timestamp().toString()); - c.output(row); - } - } - - /** - * Helper method that defines the BigQuery schema used for the output. - */ - private static TableSchema getSchema() { - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("word").setType("STRING")); - fields.add(new TableFieldSchema().setName("count").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("window_timestamp").setType("TIMESTAMP")); - TableSchema schema = new TableSchema().setFields(fields); - return schema; - } - - /** - * Concept #6: We'll stream the results to a BigQuery table. The BigQuery output source is one - * that supports both bounded and unbounded data. This is a helper method that creates a - * TableReference from input options, to tell the pipeline where to write its BigQuery results. - */ - private static TableReference getTableReference(Options options) { - TableReference tableRef = new TableReference(); - tableRef.setProjectId(options.getProject()); - tableRef.setDatasetId(options.getBigQueryDataset()); - tableRef.setTableId(options.getBigQueryTable()); - return tableRef; - } - - /** - * Options supported by {@link WindowedWordCount}. - * - *

              Inherits standard example configuration options, which allow specification of the BigQuery - * table and the PubSub topic, as well as the {@link WordCount.WordCountOptions} support for - * specification of the input file. - */ - public interface Options extends WordCount.WordCountOptions, - DataflowExampleOptions, ExamplePubsubTopicOptions, ExampleBigQueryTableOptions { - @Description("Fixed window duration, in minutes") - @Default.Integer(WINDOW_SIZE) - Integer getWindowSize(); - void setWindowSize(Integer value); - - @Description("Whether to run the pipeline with unbounded input") - boolean isUnbounded(); - void setUnbounded(boolean value); - } - - public static void main(String[] args) throws IOException { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - options.setBigQuerySchema(getSchema()); - // DataflowExampleUtils creates the necessary input sources to simplify execution of this - // Pipeline. - DataflowExampleUtils exampleDataflowUtils = new DataflowExampleUtils(options, - options.isUnbounded()); - - Pipeline pipeline = Pipeline.create(options); - - /** - * Concept #1: the Dataflow SDK lets us run the same pipeline with either a bounded or - * unbounded input source. - */ - PCollection input; - if (options.isUnbounded()) { - LOG.info("Reading from PubSub."); - /** - * Concept #3: Read from the PubSub topic. A topic will be created if it wasn't - * specified as an argument. The data elements' timestamps will come from the pubsub - * injection. - */ - input = pipeline - .apply(PubsubIO.Read.topic(options.getPubsubTopic())); - } else { - /** Else, this is a bounded pipeline. Read from the GCS file. */ - input = pipeline - .apply(TextIO.Read.from(options.getInputFile())) - // Concept #2: Add an element timestamp, using an artificial time just to show windowing. - // See AddTimestampFn for more detail on this. - .apply(ParDo.of(new AddTimestampFn())); - } - - /** - * Concept #4: Window into fixed windows. The fixed window size for this example defaults to 1 - * minute (you can change this with a command-line option). See the documentation for more - * information on how fixed windows work, and for information on the other types of windowing - * available (e.g., sliding windows). - */ - PCollection windowedWords = input - .apply(Window.into( - FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); - - /** - * Concept #5: Re-use our existing CountWords transform that does not have knowledge of - * windows over a PCollection containing windowed values. - */ - PCollection> wordCounts = windowedWords.apply(new WordCount.CountWords()); - - /** - * Concept #6: Format the results for a BigQuery table, then write to BigQuery. - * The BigQuery output source supports both bounded and unbounded data. - */ - wordCounts.apply(ParDo.of(new FormatAsTableRowFn())) - .apply(BigQueryIO.Write - .to(getTableReference(options)) - .withSchema(getSchema()) - .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)); - - PipelineResult result = pipeline.run(); - - /** - * To mock unbounded input from PubSub, we'll now start an auxiliary 'injector' pipeline that - * runs for a limited time, and publishes to the input PubSub topic. - * - * With an unbounded input source, you will need to explicitly shut down this pipeline when you - * are done with it, so that you do not continue to be charged for the instances. You can do - * this via a ctrl-C from the command line, or from the developer's console UI for Dataflow - * pipelines. The PubSub topic will also be deleted at this time. - */ - exampleDataflowUtils.mockUnboundedSource(options.getInputFile(), result); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java deleted file mode 100644 index c7697b8df6..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SimpleFunction; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - - -/** - * An example that counts words in Shakespeare and includes Dataflow best practices. - * - *

              This class, {@link WordCount}, is the second in a series of four successively more detailed - * 'word count' examples. You may first want to take a look at {@link MinimalWordCount}. - * After you've looked at this example, then see the {@link DebuggingWordCount} - * pipeline, for introduction of additional concepts. - * - *

              For a detailed walkthrough of this example, see - * - * https://cloud.google.com/dataflow/java-sdk/wordcount-example - * - * - *

              Basic concepts, also in the MinimalWordCount example: - * Reading text files; counting a PCollection; writing to GCS. - * - *

              New Concepts: - *

              - *   1. Executing a Pipeline both locally and using the Dataflow service
              - *   2. Using ParDo with static DoFns defined out-of-line
              - *   3. Building a composite transform
              - *   4. Defining your own pipeline options
              - * 
              - * - *

              Concept #1: you can execute this pipeline either locally or using the Dataflow service. - * These are now command-line options and not hard-coded as they were in the MinimalWordCount - * example. - * To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * and a local output file or output prefix on GCS: - *
              {@code
              - *   --output=[YOUR_LOCAL_FILE | gs://YOUR_OUTPUT_PREFIX]
              - * }
              - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * and an output prefix on GCS: - *
              {@code
              - *   --output=gs://YOUR_OUTPUT_PREFIX
              - * }
              - * - *

              The input file defaults to {@code gs://dataflow-samples/shakespeare/kinglear.txt} and can be - * overridden with {@code --inputFile}. - */ -public class WordCount { - - /** - * Concept #2: You can make your pipeline code less verbose by defining your DoFns statically out- - * of-line. This DoFn tokenizes lines of text into individual words; we pass it to a ParDo in the - * pipeline. - */ - static class ExtractWordsFn extends DoFn { - private final Aggregator emptyLines = - createAggregator("emptyLines", new Sum.SumLongFn()); - - @Override - public void processElement(ProcessContext c) { - if (c.element().trim().isEmpty()) { - emptyLines.addValue(1L); - } - - // Split the line into words. - String[] words = c.element().split("[^a-zA-Z']+"); - - // Output each word encountered into the output PCollection. - for (String word : words) { - if (!word.isEmpty()) { - c.output(word); - } - } - } - } - - /** A SimpleFunction that converts a Word and Count into a printable string. */ - public static class FormatAsTextFn extends SimpleFunction, String> { - @Override - public String apply(KV input) { - return input.getKey() + ": " + input.getValue(); - } - } - - /** - * A PTransform that converts a PCollection containing lines of text into a PCollection of - * formatted word counts. - * - *

              Concept #3: This is a custom composite transform that bundles two transforms (ParDo and - * Count) as a reusable PTransform subclass. Using composite transforms allows for easy reuse, - * modular testing, and an improved monitoring experience. - */ - public static class CountWords extends PTransform, - PCollection>> { - @Override - public PCollection> apply(PCollection lines) { - - // Convert lines of text into individual words. - PCollection words = lines.apply( - ParDo.of(new ExtractWordsFn())); - - // Count the number of times each word occurs. - PCollection> wordCounts = - words.apply(Count.perElement()); - - return wordCounts; - } - } - - /** - * Options supported by {@link WordCount}. - * - *

              Concept #4: Defining your own configuration options. Here, you can add your own arguments - * to be processed by the command-line parser, and specify default values for them. You can then - * access the options values in your pipeline code. - * - *

              Inherits standard configuration options. - */ - public interface WordCountOptions extends PipelineOptions { - @Description("Path of the file to read from") - @Default.String("gs://dataflow-samples/shakespeare/kinglear.txt") - String getInputFile(); - void setInputFile(String value); - - @Description("Path of the file to write to") - @Default.InstanceFactory(OutputFactory.class) - String getOutput(); - void setOutput(String value); - - /** - * Returns "gs://${YOUR_STAGING_DIRECTORY}/counts.txt" as the default destination. - */ - class OutputFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - if (dataflowOptions.getStagingLocation() != null) { - return GcsPath.fromUri(dataflowOptions.getStagingLocation()) - .resolve("counts.txt").toString(); - } else { - throw new IllegalArgumentException("Must specify --output or --stagingLocation"); - } - } - } - - } - - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); - Pipeline p = Pipeline.create(options); - - // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the - // static FormatAsTextFn() to the ParDo transform. - p.apply(TextIO.Read.named("ReadLines").from(options.getInputFile())) - .apply(new CountWords()) - .apply(MapElements.via(new FormatAsTextFn())) - .apply(TextIO.Write.named("WriteCounts").to(options.getOutput())); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleOptions.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleOptions.java deleted file mode 100644 index 606bfb4c03..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleOptions.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.common; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; - -/** - * Options that can be used to configure the Dataflow examples. - */ -public interface DataflowExampleOptions extends DataflowPipelineOptions { - @Description("Whether to keep jobs running on the Dataflow service after local process exit") - @Default.Boolean(false) - boolean getKeepJobsRunning(); - void setKeepJobsRunning(boolean keepJobsRunning); - - @Description("Number of workers to use when executing the injector pipeline") - @Default.Integer(1) - int getInjectorNumWorkers(); - void setInjectorNumWorkers(int numWorkers); -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java deleted file mode 100644 index 523044138f..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/DataflowExampleUtils.java +++ /dev/null @@ -1,489 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.common; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.Sleeper; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.Bigquery.Datasets; -import com.google.api.services.bigquery.Bigquery.Tables; -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.DatasetReference; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.Subscription; -import com.google.api.services.pubsub.model.Topic; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineJob; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.IntraBundleParallelization; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.util.FluentBackoff; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.common.util.concurrent.Uninterruptibles; - -import org.joda.time.Duration; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import javax.servlet.http.HttpServletResponse; - - -/** - * The utility class that sets up and tears down external resources, starts the Google Cloud Pub/Sub - * injector, and cancels the streaming and the injector pipelines once the program terminates. - * - *

              It is used to run Dataflow examples, such as TrafficMaxLaneFlow and TrafficRoutes. - */ -public class DataflowExampleUtils { - - private final DataflowPipelineOptions options; - private Bigquery bigQueryClient = null; - private Pubsub pubsubClient = null; - private Dataflow dataflowClient = null; - private Set jobsToCancel = Sets.newHashSet(); - private List pendingMessages = Lists.newArrayList(); - - public DataflowExampleUtils(DataflowPipelineOptions options) { - this.options = options; - } - - /** - * Do resources and runner options setup. - */ - public DataflowExampleUtils(DataflowPipelineOptions options, boolean isUnbounded) - throws IOException { - this.options = options; - setupResourcesAndRunner(isUnbounded); - } - - /** - * Sets up external resources that are required by the example, - * such as Pub/Sub topics and BigQuery tables. - * - * @throws IOException if there is a problem setting up the resources - */ - public void setup() throws IOException { - Sleeper sleeper = Sleeper.DEFAULT; - BackOff backOff = - FluentBackoff.DEFAULT - .withMaxRetries(3).withInitialBackoff(Duration.millis(200)).backoff(); - Throwable lastException = null; - try { - do { - try { - setupPubsub(); - setupBigQueryTable(); - return; - } catch (GoogleJsonResponseException e) { - lastException = e; - } - } while (BackOffUtils.next(sleeper, backOff)); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - // Ignore InterruptedException - } - throw new RuntimeException(lastException); - } - - /** - * Set up external resources, and configure the runner appropriately. - */ - public void setupResourcesAndRunner(boolean isUnbounded) throws IOException { - if (isUnbounded) { - options.setStreaming(true); - } - setup(); - setupRunner(); - } - - /** - * Sets up the Google Cloud Pub/Sub topic. - * - *

              If the topic doesn't exist, a new topic with the given name will be created. - * - * @throws IOException if there is a problem setting up the Pub/Sub topic - */ - public void setupPubsub() throws IOException { - ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = - options.as(ExamplePubsubTopicAndSubscriptionOptions.class); - if (!pubsubOptions.getPubsubTopic().isEmpty()) { - pendingMessages.add("**********************Set Up Pubsub************************"); - setupPubsubTopic(pubsubOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been set up for this example: " - + pubsubOptions.getPubsubTopic()); - - if (!pubsubOptions.getPubsubSubscription().isEmpty()) { - setupPubsubSubscription( - pubsubOptions.getPubsubTopic(), pubsubOptions.getPubsubSubscription()); - pendingMessages.add("The Pub/Sub subscription has been set up for this example: " - + pubsubOptions.getPubsubSubscription()); - } - } - } - - /** - * Sets up the BigQuery table with the given schema. - * - *

              If the table already exists, the schema has to match the given one. Otherwise, the example - * will throw a RuntimeException. If the table doesn't exist, a new table with the given schema - * will be created. - * - * @throws IOException if there is a problem setting up the BigQuery table - */ - public void setupBigQueryTable() throws IOException { - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("******************Set Up Big Query Table*******************"); - setupBigQueryTable(bigQueryTableOptions.getProject(), - bigQueryTableOptions.getBigQueryDataset(), - bigQueryTableOptions.getBigQueryTable(), - bigQueryTableOptions.getBigQuerySchema()); - pendingMessages.add("The BigQuery table has been set up for this example: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - } - } - - /** - * Tears down external resources that can be deleted upon the example's completion. - */ - private void tearDown() { - pendingMessages.add("*************************Tear Down*************************"); - ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = - options.as(ExamplePubsubTopicAndSubscriptionOptions.class); - if (!pubsubOptions.getPubsubTopic().isEmpty()) { - try { - deletePubsubTopic(pubsubOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been deleted: " - + pubsubOptions.getPubsubTopic()); - } catch (IOException e) { - pendingMessages.add("Failed to delete the Pub/Sub topic : " - + pubsubOptions.getPubsubTopic()); - } - if (!pubsubOptions.getPubsubSubscription().isEmpty()) { - try { - deletePubsubSubscription(pubsubOptions.getPubsubSubscription()); - pendingMessages.add("The Pub/Sub subscription has been deleted: " - + pubsubOptions.getPubsubSubscription()); - } catch (IOException e) { - pendingMessages.add("Failed to delete the Pub/Sub subscription : " - + pubsubOptions.getPubsubSubscription()); - } - } - } - - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("The BigQuery table might contain the example's output, " - + "and it is not deleted automatically: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - pendingMessages.add("Please go to the Developers Console to delete it manually." - + " Otherwise, you may be charged for its usage."); - } - } - - private void setupBigQueryTable(String projectId, String datasetId, String tableId, - TableSchema schema) throws IOException { - if (bigQueryClient == null) { - bigQueryClient = Transport.newBigQueryClient(options.as(BigQueryOptions.class)).build(); - } - - Datasets datasetService = bigQueryClient.datasets(); - if (executeNullIfNotFound(datasetService.get(projectId, datasetId)) == null) { - Dataset newDataset = new Dataset().setDatasetReference( - new DatasetReference().setProjectId(projectId).setDatasetId(datasetId)); - datasetService.insert(projectId, newDataset).execute(); - } - - Tables tableService = bigQueryClient.tables(); - Table table = executeNullIfNotFound(tableService.get(projectId, datasetId, tableId)); - if (table == null) { - Table newTable = new Table().setSchema(schema).setTableReference( - new TableReference().setProjectId(projectId).setDatasetId(datasetId).setTableId(tableId)); - tableService.insert(projectId, datasetId, newTable).execute(); - } else if (!table.getSchema().equals(schema)) { - throw new RuntimeException( - "Table exists and schemas do not match, expecting: " + schema.toPrettyString() - + ", actual: " + table.getSchema().toPrettyString()); - } - } - - private void setupPubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) == null) { - pubsubClient.projects().topics().create(topic, new Topic().setName(topic)).execute(); - } - } - - private void setupPubsubSubscription(String topic, String subscription) throws IOException { - if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) == null) { - Subscription subInfo = new Subscription() - .setAckDeadlineSeconds(60) - .setTopic(topic); - pubsubClient.projects().subscriptions().create(subscription, subInfo).execute(); - } - } - - /** - * Deletes the Google Cloud Pub/Sub topic. - * - * @throws IOException if there is a problem deleting the Pub/Sub topic - */ - private void deletePubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) != null) { - pubsubClient.projects().topics().delete(topic).execute(); - } - } - - /** - * Deletes the Google Cloud Pub/Sub subscription. - * - * @throws IOException if there is a problem deleting the Pub/Sub subscription - */ - private void deletePubsubSubscription(String subscription) throws IOException { - if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) != null) { - pubsubClient.projects().subscriptions().delete(subscription).execute(); - } - } - - /** - * If this is an unbounded (streaming) pipeline, and both inputFile and pubsub topic are defined, - * start an 'injector' pipeline that publishes the contents of the file to the given topic, first - * creating the topic if necessary. - */ - public void startInjectorIfNeeded(String inputFile) { - ExamplePubsubTopicOptions pubsubTopicOptions = options.as(ExamplePubsubTopicOptions.class); - if (pubsubTopicOptions.isStreaming() - && !Strings.isNullOrEmpty(inputFile) - && !Strings.isNullOrEmpty(pubsubTopicOptions.getPubsubTopic())) { - runInjectorPipeline(inputFile, pubsubTopicOptions.getPubsubTopic()); - } - } - - /** - * Do some runner setup: check that the DirectPipelineRunner is not used in conjunction with - * streaming, and if streaming is specified, use the DataflowPipelineRunner. Return the streaming - * flag value. - */ - public void setupRunner() { - if (options.isStreaming() && options.getRunner() != DirectPipelineRunner.class) { - // In order to cancel the pipelines automatically, - // {@literal DataflowPipelineRunner} is forced to be used. - options.setRunner(DataflowPipelineRunner.class); - } - } - - /** - * Runs a batch pipeline to inject data into the PubSubIO input topic. - * - *

              The injector pipeline will read from the given text file, and inject data - * into the Google Cloud Pub/Sub topic. - */ - public void runInjectorPipeline(String inputFile, String topic) { - runInjectorPipeline(TextIO.Read.from(inputFile), topic, null); - } - - /** - * Runs a batch pipeline to inject data into the PubSubIO input topic. - * - *

              The injector pipeline will read from the given source, and inject data - * into the Google Cloud Pub/Sub topic. - */ - public void runInjectorPipeline(PTransform> readSource, - String topic, - String pubsubTimestampTabelKey) { - PubsubFileInjector.Bound injector; - if (Strings.isNullOrEmpty(pubsubTimestampTabelKey)) { - injector = PubsubFileInjector.publish(topic); - } else { - injector = PubsubFileInjector.withTimestampLabelKey(pubsubTimestampTabelKey).publish(topic); - } - DataflowPipelineOptions copiedOptions = options.cloneAs(DataflowPipelineOptions.class); - if (options.getServiceAccountName() != null) { - copiedOptions.setServiceAccountName(options.getServiceAccountName()); - } - if (options.getServiceAccountKeyfile() != null) { - copiedOptions.setServiceAccountKeyfile(options.getServiceAccountKeyfile()); - } - copiedOptions.setStreaming(false); - copiedOptions.setWorkerHarnessContainerImage( - DataflowPipelineRunner.BATCH_WORKER_HARNESS_CONTAINER_IMAGE); - copiedOptions.setNumWorkers(options.as(DataflowExampleOptions.class).getInjectorNumWorkers()); - copiedOptions.setJobName(options.getJobName() + "-injector"); - Pipeline injectorPipeline = Pipeline.create(copiedOptions); - injectorPipeline.apply(readSource) - .apply(IntraBundleParallelization - .of(injector) - .withMaxParallelism(20)); - PipelineResult result = injectorPipeline.run(); - if (result instanceof DataflowPipelineJob) { - jobsToCancel.add(((DataflowPipelineJob) result)); - } - } - - /** - * Runs the provided pipeline to inject data into the PubSubIO input topic. - */ - public void runInjectorPipeline(Pipeline injectorPipeline) { - PipelineResult result = injectorPipeline.run(); - if (result instanceof DataflowPipelineJob) { - jobsToCancel.add(((DataflowPipelineJob) result)); - } - } - - /** - * Start the auxiliary injector pipeline, then wait for this pipeline to finish. - */ - public void mockUnboundedSource(String inputFile, PipelineResult result) { - startInjectorIfNeeded(inputFile); - waitToFinish(result); - } - - /** - * If {@literal DataflowPipelineRunner} or {@literal BlockingDataflowPipelineRunner} is used, - * waits for the pipeline to finish and cancels it (and the injector) before the program exists. - */ - public void waitToFinish(PipelineResult result) { - if (result instanceof DataflowPipelineJob) { - final DataflowPipelineJob job = (DataflowPipelineJob) result; - jobsToCancel.add(job); - if (!options.as(DataflowExampleOptions.class).getKeepJobsRunning()) { - addShutdownHook(jobsToCancel); - } - try { - job.waitToFinish(-1, TimeUnit.SECONDS, new MonitoringUtil.PrintHandler(System.out)); - } catch (Exception e) { - throw new RuntimeException("Failed to wait for job to finish: " + job.getJobId()); - } - } else { - // Do nothing if the given PipelineResult doesn't support waitToFinish(), - // such as EvaluationResults returned by DirectPipelineRunner. - tearDown(); - printPendingMessages(); - } - } - - private void addShutdownHook(final Collection jobs) { - if (dataflowClient == null) { - dataflowClient = options.getDataflowClient(); - } - - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - tearDown(); - printPendingMessages(); - for (DataflowPipelineJob job : jobs) { - System.out.println("Canceling example pipeline: " + job.getJobId()); - try { - job.cancel(); - } catch (IOException e) { - System.out.println("Failed to cancel the job," - + " please go to the Developers Console to cancel it manually"); - System.out.println( - MonitoringUtil.getJobMonitoringPageURL(job.getProjectId(), job.getJobId())); - } - } - - for (DataflowPipelineJob job : jobs) { - boolean cancellationVerified = false; - for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { - if (job.getState().isTerminal()) { - cancellationVerified = true; - System.out.println("Canceled example pipeline: " + job.getJobId()); - break; - } else { - System.out.println( - "The example pipeline is still running. Verifying the cancellation."); - } - Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); - } - if (!cancellationVerified) { - System.out.println("Failed to verify the cancellation for job: " + job.getJobId()); - System.out.println("Please go to the Developers Console to verify manually:"); - System.out.println( - MonitoringUtil.getJobMonitoringPageURL(job.getProjectId(), job.getJobId())); - } - } - } - }); - } - - private void printPendingMessages() { - System.out.println(); - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - for (String message : pendingMessages) { - System.out.println(message); - } - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - } - - private static T executeNullIfNotFound( - AbstractGoogleClientRequest request) throws IOException { - try { - return request.execute(); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { - return null; - } else { - throw e; - } - } - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExampleBigQueryTableOptions.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExampleBigQueryTableOptions.java deleted file mode 100644 index 07f180ecee..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExampleBigQueryTableOptions.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.common; - -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure BigQuery tables in Dataflow examples. - * The project defaults to the project being used to run the example. - */ -public interface ExampleBigQueryTableOptions extends DataflowPipelineOptions { - @Description("BigQuery dataset name") - @Default.String("dataflow_examples") - String getBigQueryDataset(); - void setBigQueryDataset(String dataset); - - @Description("BigQuery table name") - @Default.InstanceFactory(BigQueryTableFactory.class) - String getBigQueryTable(); - void setBigQueryTable(String table); - - @Description("BigQuery table schema") - TableSchema getBigQuerySchema(); - void setBigQuerySchema(TableSchema schema); - - /** - * Returns the job name as the default BigQuery table name. - */ - class BigQueryTableFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return options.as(DataflowPipelineOptions.class).getJobName() - .replace('-', '_'); - } - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicAndSubscriptionOptions.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicAndSubscriptionOptions.java deleted file mode 100644 index 2993cdf092..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicAndSubscriptionOptions.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.common; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure Pub/Sub topic/subscription in Dataflow examples. - */ -public interface ExamplePubsubTopicAndSubscriptionOptions extends ExamplePubsubTopicOptions { - @Description("Pub/Sub subscription") - @Default.InstanceFactory(PubsubSubscriptionFactory.class) - String getPubsubSubscription(); - void setPubsubSubscription(String subscription); - - /** - * Returns a default Pub/Sub subscription based on the project and the job names. - */ - class PubsubSubscriptionFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - DataflowPipelineOptions dataflowPipelineOptions = - options.as(DataflowPipelineOptions.class); - return "projects/" + dataflowPipelineOptions.getProject() - + "/subscriptions/" + dataflowPipelineOptions.getJobName(); - } - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicOptions.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicOptions.java deleted file mode 100644 index 56e4264d36..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/ExamplePubsubTopicOptions.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.common; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure Pub/Sub topic in Dataflow examples. - */ -public interface ExamplePubsubTopicOptions extends DataflowPipelineOptions { - @Description("Pub/Sub topic") - @Default.InstanceFactory(PubsubTopicFactory.class) - String getPubsubTopic(); - void setPubsubTopic(String topic); - - /** - * Returns a default Pub/Sub topic based on the project and the job names. - */ - class PubsubTopicFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - DataflowPipelineOptions dataflowPipelineOptions = - options.as(DataflowPipelineOptions.class); - return "projects/" + dataflowPipelineOptions.getProject() - + "/topics/" + dataflowPipelineOptions.getJobName(); - } - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/common/PubsubFileInjector.java b/examples/src/main/java/com/google/cloud/dataflow/examples/common/PubsubFileInjector.java deleted file mode 100644 index 4a82ae612a..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/common/PubsubFileInjector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.common; - -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.PublishRequest; -import com.google.api.services.pubsub.model.PubsubMessage; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.IntraBundleParallelization; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.common.collect.ImmutableMap; - -import java.io.IOException; -import java.util.Arrays; - -/** - * A batch Dataflow pipeline for injecting a set of GCS files into - * a PubSub topic line by line. Empty lines are skipped. - * - *

              This is useful for testing streaming - * pipelines. Note that since batch pipelines might retry chunks, this - * does _not_ guarantee exactly-once injection of file data. Some lines may - * be published multiple times. - *

              - */ -public class PubsubFileInjector { - - /** - * An incomplete {@code PubsubFileInjector} transform with unbound output topic. - */ - public static class Unbound { - private final String timestampLabelKey; - - Unbound() { - this.timestampLabelKey = null; - } - - Unbound(String timestampLabelKey) { - this.timestampLabelKey = timestampLabelKey; - } - - Unbound withTimestampLabelKey(String timestampLabelKey) { - return new Unbound(timestampLabelKey); - } - - public Bound publish(String outputTopic) { - return new Bound(outputTopic, timestampLabelKey); - } - } - - /** A DoFn that publishes non-empty lines to Google Cloud PubSub. */ - public static class Bound extends DoFn { - private final String outputTopic; - private final String timestampLabelKey; - public transient Pubsub pubsub; - - public Bound(String outputTopic, String timestampLabelKey) { - this.outputTopic = outputTopic; - this.timestampLabelKey = timestampLabelKey; - } - - @Override - public void startBundle(Context context) { - this.pubsub = - Transport.newPubsubClient(context.getPipelineOptions().as(DataflowPipelineOptions.class)) - .build(); - } - - @Override - public void processElement(ProcessContext c) throws IOException { - if (c.element().isEmpty()) { - return; - } - PubsubMessage pubsubMessage = new PubsubMessage(); - pubsubMessage.encodeData(c.element().getBytes()); - if (timestampLabelKey != null) { - pubsubMessage.setAttributes( - ImmutableMap.of(timestampLabelKey, Long.toString(c.timestamp().getMillis()))); - } - PublishRequest publishRequest = new PublishRequest(); - publishRequest.setMessages(Arrays.asList(pubsubMessage)); - this.pubsub.projects().topics().publish(outputTopic, publishRequest).execute(); - } - } - - /** - * Creates a {@code PubsubFileInjector} transform with the given timestamp label key. - */ - public static Unbound withTimestampLabelKey(String timestampLabelKey) { - return new Unbound(timestampLabelKey); - } - - /** - * Creates a {@code PubsubFileInjector} transform that publishes to the given output topic. - */ - public static Bound publish(String outputTopic) { - return new Unbound().publish(outputTopic); - } - - /** - * Command line parameter options. - */ - private interface PubsubFileInjectorOptions extends PipelineOptions { - @Description("GCS location of files.") - @Validation.Required - String getInput(); - void setInput(String value); - - @Description("Topic to publish on.") - @Validation.Required - String getOutputTopic(); - void setOutputTopic(String value); - } - - /** - * Sets up and starts streaming pipeline. - */ - public static void main(String[] args) { - PubsubFileInjectorOptions options = PipelineOptionsFactory.fromArgs(args) - .withValidation() - .as(PubsubFileInjectorOptions.class); - - Pipeline pipeline = Pipeline.create(options); - - pipeline - .apply(TextIO.Read.from(options.getInput())) - .apply(IntraBundleParallelization.of(PubsubFileInjector.publish(options.getOutputTopic())) - .withMaxParallelism(20)); - - pipeline.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java deleted file mode 100644 index 30528b0424..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/AutoComplete.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.datastore.v1.client.DatastoreHelper.makeKey; -import static com.google.datastore.v1.client.DatastoreHelper.makeValue; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions; -import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicOptions; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Filter; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Partition; -import com.google.cloud.dataflow.sdk.transforms.Partition.PartitionFn; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.Top; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.common.base.MoreObjects; -import com.google.datastore.v1.Entity; -import com.google.datastore.v1.Key; -import com.google.datastore.v1.Value; - -import org.joda.time.Duration; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * An example that computes the most popular hash tags - * for every prefix, which can be used for auto-completion. - * - *

              Concepts: Using the same pipeline in both streaming and batch, combiners, - * composite transforms. - * - *

              To execute this pipeline using the Dataflow service in batch mode, - * specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=DataflowPipelineRunner
              - *   --inputFile=gs://path/to/input*.txt
              - * }
              - * - *

              To execute this pipeline using the Dataflow service in streaming mode, - * specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=DataflowPipelineRunner
              - *   --inputFile=gs://YOUR_INPUT_DIRECTORY/*.txt
              - *   --streaming
              - * }
              - * - *

              This will update the Cloud Datastore every 10 seconds based on the last - * 30 minutes of data received. - */ -public class AutoComplete { - - /** - * A PTransform that takes as input a list of tokens and returns - * the most common tokens per prefix. - */ - public static class ComputeTopCompletions - extends PTransform, PCollection>>> { - private final int candidatesPerPrefix; - private final boolean recursive; - - protected ComputeTopCompletions(int candidatesPerPrefix, boolean recursive) { - this.candidatesPerPrefix = candidatesPerPrefix; - this.recursive = recursive; - } - - public static ComputeTopCompletions top(int candidatesPerPrefix, boolean recursive) { - return new ComputeTopCompletions(candidatesPerPrefix, recursive); - } - - @Override - public PCollection>> apply(PCollection input) { - PCollection candidates = input - // First count how often each token appears. - .apply(new Count.PerElement()) - - // Map the KV outputs of Count into our own CompletionCandiate class. - .apply(ParDo.named("CreateCompletionCandidates").of( - new DoFn, CompletionCandidate>() { - @Override - public void processElement(ProcessContext c) { - c.output(new CompletionCandidate(c.element().getKey(), c.element().getValue())); - } - })); - - // Compute the top via either a flat or recursive algorithm. - if (recursive) { - return candidates - .apply(new ComputeTopRecursive(candidatesPerPrefix, 1)) - .apply(Flatten.>>pCollections()); - } else { - return candidates - .apply(new ComputeTopFlat(candidatesPerPrefix, 1)); - } - } - } - - /** - * Lower latency, but more expensive. - */ - private static class ComputeTopFlat - extends PTransform, - PCollection>>> { - private final int candidatesPerPrefix; - private final int minPrefix; - - public ComputeTopFlat(int candidatesPerPrefix, int minPrefix) { - this.candidatesPerPrefix = candidatesPerPrefix; - this.minPrefix = minPrefix; - } - - @Override - public PCollection>> apply( - PCollection input) { - return input - // For each completion candidate, map it to all prefixes. - .apply(ParDo.of(new AllPrefixes(minPrefix))) - - // Find and return the top candiates for each prefix. - .apply(Top.largestPerKey(candidatesPerPrefix) - .withHotKeyFanout(new HotKeyFanout())); - } - - private static class HotKeyFanout implements SerializableFunction { - @Override - public Integer apply(String input) { - return (int) Math.pow(4, 5 - input.length()); - } - } - } - - /** - * Cheaper but higher latency. - * - *

              Returns two PCollections, the first is top prefixes of size greater - * than minPrefix, and the second is top prefixes of size exactly - * minPrefix. - */ - private static class ComputeTopRecursive - extends PTransform, - PCollectionList>>> { - private final int candidatesPerPrefix; - private final int minPrefix; - - public ComputeTopRecursive(int candidatesPerPrefix, int minPrefix) { - this.candidatesPerPrefix = candidatesPerPrefix; - this.minPrefix = minPrefix; - } - - private class KeySizePartitionFn implements PartitionFn>> { - @Override - public int partitionFor(KV> elem, int numPartitions) { - return elem.getKey().length() > minPrefix ? 0 : 1; - } - } - - private static class FlattenTops - extends DoFn>, CompletionCandidate> { - @Override - public void processElement(ProcessContext c) { - for (CompletionCandidate cc : c.element().getValue()) { - c.output(cc); - } - } - } - - @Override - public PCollectionList>> apply( - PCollection input) { - if (minPrefix > 10) { - // Base case, partitioning to return the output in the expected format. - return input - .apply(new ComputeTopFlat(candidatesPerPrefix, minPrefix)) - .apply(Partition.of(2, new KeySizePartitionFn())); - } else { - // If a candidate is in the top N for prefix a...b, it must also be in the top - // N for a...bX for every X, which is typlically a much smaller set to consider. - // First, compute the top candidate for prefixes of size at least minPrefix + 1. - PCollectionList>> larger = input - .apply(new ComputeTopRecursive(candidatesPerPrefix, minPrefix + 1)); - // Consider the top candidates for each prefix of length minPrefix + 1... - PCollection>> small = - PCollectionList - .of(larger.get(1).apply(ParDo.of(new FlattenTops()))) - // ...together with those (previously excluded) candidates of length - // exactly minPrefix... - .and(input.apply(Filter.byPredicate( - new SerializableFunction() { - @Override - public Boolean apply(CompletionCandidate c) { - return c.getValue().length() == minPrefix; - } - }))) - .apply("FlattenSmall", Flatten.pCollections()) - // ...set the key to be the minPrefix-length prefix... - .apply(ParDo.of(new AllPrefixes(minPrefix, minPrefix))) - // ...and (re)apply the Top operator to all of them together. - .apply(Top.largestPerKey(candidatesPerPrefix)); - - PCollection>> flattenLarger = larger - .apply("FlattenLarge", Flatten.>>pCollections()); - - return PCollectionList.of(flattenLarger).and(small); - } - } - } - - /** - * A DoFn that keys each candidate by all its prefixes. - */ - private static class AllPrefixes - extends DoFn> { - private final int minPrefix; - private final int maxPrefix; - public AllPrefixes(int minPrefix) { - this(minPrefix, Integer.MAX_VALUE); - } - public AllPrefixes(int minPrefix, int maxPrefix) { - this.minPrefix = minPrefix; - this.maxPrefix = maxPrefix; - } - @Override - public void processElement(ProcessContext c) { - String word = c.element().value; - for (int i = minPrefix; i <= Math.min(word.length(), maxPrefix); i++) { - c.output(KV.of(word.substring(0, i), c.element())); - } - } - } - - /** - * Class used to store tag-count pairs. - */ - @DefaultCoder(AvroCoder.class) - static class CompletionCandidate implements Comparable { - private long count; - private String value; - - public CompletionCandidate(String value, long count) { - this.value = value; - this.count = count; - } - - public long getCount() { - return count; - } - - public String getValue() { - return value; - } - - // Empty constructor required for Avro decoding. - public CompletionCandidate() {} - - @Override - public int compareTo(CompletionCandidate o) { - if (this.count < o.count) { - return -1; - } else if (this.count == o.count) { - return this.value.compareTo(o.value); - } else { - return 1; - } - } - - @Override - public boolean equals(Object other) { - if (other instanceof CompletionCandidate) { - CompletionCandidate that = (CompletionCandidate) other; - return this.count == that.count && this.value.equals(that.value); - } else { - return false; - } - } - - @Override - public int hashCode() { - return Long.valueOf(count).hashCode() ^ value.hashCode(); - } - - @Override - public String toString() { - return "CompletionCandidate[" + value + ", " + count + "]"; - } - } - - /** - * Takes as input a set of strings, and emits each #hashtag found therein. - */ - static class ExtractHashtags extends DoFn { - @Override - public void processElement(ProcessContext c) { - Matcher m = Pattern.compile("#\\S+").matcher(c.element()); - while (m.find()) { - c.output(m.group().substring(1)); - } - } - } - - static class FormatForBigquery extends DoFn>, TableRow> { - @Override - public void processElement(ProcessContext c) { - List completions = new ArrayList<>(); - for (CompletionCandidate cc : c.element().getValue()) { - completions.add(new TableRow() - .set("count", cc.getCount()) - .set("tag", cc.getValue())); - } - TableRow row = new TableRow() - .set("prefix", c.element().getKey()) - .set("tags", completions); - c.output(row); - } - - /** - * Defines the BigQuery schema used for the output. - */ - static TableSchema getSchema() { - List tagFields = new ArrayList<>(); - tagFields.add(new TableFieldSchema().setName("count").setType("INTEGER")); - tagFields.add(new TableFieldSchema().setName("tag").setType("STRING")); - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("prefix").setType("STRING")); - fields.add(new TableFieldSchema() - .setName("tags").setType("RECORD").setMode("REPEATED").setFields(tagFields)); - return new TableSchema().setFields(fields); - } - } - - /** - * Takes as input a the top candidates per prefix, and emits an entity - * suitable for writing to Cloud Datastore. - * - *

              Note: We use ancestor keys for strong consistency. See the Cloud Datastore documentation on - * - * Structuring Data for Strong Consistency - */ - static class FormatForDatastore extends DoFn>, Entity> { - private String kind; - private String ancestorKey; - - public FormatForDatastore(String kind, String ancestorKey) { - this.kind = kind; - this.ancestorKey = ancestorKey; - } - - @Override - public void processElement(ProcessContext c) { - Entity.Builder entityBuilder = Entity.newBuilder(); - Key key = makeKey(makeKey(kind, ancestorKey).build(), kind, c.element().getKey()).build(); - - entityBuilder.setKey(key); - List candidates = new ArrayList<>(); - Map properties = new HashMap<>(); - for (CompletionCandidate tag : c.element().getValue()) { - Entity.Builder tagEntity = Entity.newBuilder(); - properties.put("tag", makeValue(tag.value).build()); - properties.put("count", makeValue(tag.count).build()); - candidates.add(makeValue(tagEntity).build()); - } - properties.put("candidates", makeValue(candidates).build()); - entityBuilder.putAllProperties(properties); - c.output(entityBuilder.build()); - } - } - - /** - * Options supported by this class. - * - *

              Inherits standard Dataflow configuration options. - */ - private interface Options extends ExamplePubsubTopicOptions, ExampleBigQueryTableOptions { - @Description("Input text file") - @Validation.Required - String getInputFile(); - void setInputFile(String value); - - @Description("Whether to use the recursive algorithm") - @Default.Boolean(true) - Boolean getRecursive(); - void setRecursive(Boolean value); - - @Description("Cloud Datastore entity kind") - @Default.String("autocomplete-demo") - String getKind(); - void setKind(String value); - - @Description("Whether output to BigQuery") - @Default.Boolean(true) - Boolean getOutputToBigQuery(); - void setOutputToBigQuery(Boolean value); - - @Description("Whether output to Cloud Datastore") - @Default.Boolean(false) - Boolean getOutputToDatastore(); - void setOutputToDatastore(Boolean value); - - @Description("Cloud Datastore output dataset ID, defaults to project ID") - String getOutputDataset(); - void setOutputDataset(String value); - - @Description("Cloud Datastore ancestor key") - @Default.String("root") - String getDatastoreAncestorKey(); - void setDatastoreAncestorKey(String value); - } - - public static void main(String[] args) throws IOException { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - - if (options.isStreaming()) { - // In order to cancel the pipelines automatically, - // {@literal DataflowPipelineRunner} is forced to be used. - options.setRunner(DataflowPipelineRunner.class); - } - - options.setBigQuerySchema(FormatForBigquery.getSchema()); - DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options); - - // We support running the same pipeline in either - // batch or windowed streaming mode. - PTransform> readSource; - WindowFn windowFn; - if (options.isStreaming()) { - checkArgument( - !options.getOutputToDatastore(), "DatastoreIO is not supported in streaming."); - dataflowUtils.setupPubsub(); - - readSource = PubsubIO.Read.topic(options.getPubsubTopic()); - windowFn = SlidingWindows.of(Duration.standardMinutes(30)).every(Duration.standardSeconds(5)); - } else { - readSource = TextIO.Read.from(options.getInputFile()); - windowFn = new GlobalWindows(); - } - - // Create the pipeline. - Pipeline p = Pipeline.create(options); - PCollection>> toWrite = p - .apply(readSource) - .apply(ParDo.of(new ExtractHashtags())) - .apply(Window.into(windowFn)) - .apply(ComputeTopCompletions.top(10, options.getRecursive())); - - if (options.getOutputToDatastore()) { - toWrite - .apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind(), - options.getDatastoreAncestorKey()))) - .apply(DatastoreIO.v1().write().withProjectId(MoreObjects.firstNonNull( - options.getOutputDataset(), options.getProject()))); - } - if (options.getOutputToBigQuery()) { - dataflowUtils.setupBigQueryTable(); - - TableReference tableRef = new TableReference(); - tableRef.setProjectId(options.getProject()); - tableRef.setDatasetId(options.getBigQueryDataset()); - tableRef.setTableId(options.getBigQueryTable()); - - toWrite - .apply(ParDo.of(new FormatForBigquery())) - .apply(BigQueryIO.Write - .to(tableRef) - .withSchema(FormatForBigquery.getSchema()) - .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(options.isStreaming() - ? BigQueryIO.Write.WriteDisposition.WRITE_APPEND - : BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); - } - - // Run the pipeline. - PipelineResult result = p.run(); - - if (options.isStreaming() && !options.getInputFile().isEmpty()) { - // Inject the data into the Pub/Sub topic with a Dataflow batch pipeline. - dataflowUtils.runInjectorPipeline(options.getInputFile(), options.getPubsubTopic()); - } - - // dataflowUtils will try to cancel the pipeline and the injector before the program exists. - dataflowUtils.waitToFinish(result); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/README.md b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/README.md deleted file mode 100644 index 5fba15494e..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/README.md +++ /dev/null @@ -1,44 +0,0 @@ - -# "Complete" Examples - -This directory contains end-to-end example pipelines that perform complex data processing tasks. They include: - -

                -
              • AutoComplete - — An example that computes the most popular hash tags for every - prefix, which can be used for auto-completion. Demonstrates how to use the - same pipeline in both streaming and batch, combiners, and composite - transforms.
              • -
              • StreamingWordExtract - — A streaming pipeline example that inputs lines of text from a Cloud - Pub/Sub topic, splits each line into individual words, capitalizes those - words, and writes the output to a BigQuery table. -
              • -
              • TfIdf - — An example that computes a basic TF-IDF search table for a directory or - Cloud Storage prefix. Demonstrates joining data, side inputs, and logging. -
              • -
              • TopWikipediaSessions - — An example that reads Wikipedia edit data from Cloud Storage and - computes the user with the longest string of edits separated by no more than - an hour within each month. Demonstrates using Cloud Dataflow - Windowing to perform time-based aggregations of data. -
              • -
              • TrafficMaxLaneFlow - — A streaming Cloud Dataflow example using BigQuery output in the - traffic sensor domain. Demonstrates the Cloud Dataflow streaming - runner, sliding windows, Cloud Pub/Sub topic ingestion, the use of the - AvroCoder to encode a custom class, and custom - Combine transforms. -
              • -
              • TrafficRoutes - — A streaming Cloud Dataflow example using BigQuery output in the - traffic sensor domain. Demonstrates the Cloud Dataflow streaming - runner, GroupByKey, keyed state, sliding windows, and Cloud - Pub/Sub topic ingestion. -
              • -
              - -See the [documentation](https://cloud.google.com/dataflow/getting-started) and the [Examples -README](../../../../../../../../../README.md) for -information about how to run these examples. diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/StreamingWordExtract.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/StreamingWordExtract.java deleted file mode 100644 index 99c5249362..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/StreamingWordExtract.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions; -import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicOptions; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; - -import java.io.IOException; -import java.util.ArrayList; - -/** - * A streaming Dataflow Example using BigQuery output. - * - *

              This pipeline example reads lines of text from a PubSub topic, splits each line - * into individual words, capitalizes those words, and writes the output to - * a BigQuery table. - * - *

              By default, the example will run a separate pipeline to inject the data from the default - * {@literal --inputFile} to the Pub/Sub {@literal --pubsubTopic}. It will make it available for - * the streaming pipeline to process. You may override the default {@literal --inputFile} with the - * file of your choosing. You may also set {@literal --inputFile} to an empty string, which will - * disable the automatic Pub/Sub injection, and allow you to use separate tool to control the input - * to this example. - * - *

              The example is configured to use the default Pub/Sub topic and the default BigQuery table - * from the example common package (there are no defaults for a general Dataflow pipeline). - * You can override them by using the {@literal --pubsubTopic}, {@literal --bigQueryDataset}, and - * {@literal --bigQueryTable} options. If the Pub/Sub topic or the BigQuery table do not exist, - * the example will try to create them. - * - *

              The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C) - * and then exits. - */ -public class StreamingWordExtract { - - /** A DoFn that tokenizes lines of text into individual words. */ - static class ExtractWords extends DoFn { - @Override - public void processElement(ProcessContext c) { - String[] words = c.element().split("[^a-zA-Z']+"); - for (String word : words) { - if (!word.isEmpty()) { - c.output(word); - } - } - } - } - - /** A DoFn that uppercases a word. */ - static class Uppercase extends DoFn { - @Override - public void processElement(ProcessContext c) { - c.output(c.element().toUpperCase()); - } - } - - /** - * Converts strings into BigQuery rows. - */ - static class StringToRowConverter extends DoFn { - /** - * In this example, put the whole string into single BigQuery field. - */ - @Override - public void processElement(ProcessContext c) { - c.output(new TableRow().set("string_field", c.element())); - } - - static TableSchema getSchema() { - return new TableSchema().setFields(new ArrayList() { - // Compose the list of TableFieldSchema from tableSchema. - { - add(new TableFieldSchema().setName("string_field").setType("STRING")); - } - }); - } - } - - /** - * Options supported by {@link StreamingWordExtract}. - * - *

              Inherits standard configuration options. - */ - private interface StreamingWordExtractOptions - extends ExamplePubsubTopicOptions, ExampleBigQueryTableOptions { - @Description("Input file to inject to Pub/Sub topic") - @Default.String("gs://dataflow-samples/shakespeare/kinglear.txt") - String getInputFile(); - void setInputFile(String value); - } - - /** - * Sets up and starts streaming pipeline. - * - * @throws IOException if there is a problem setting up resources - */ - public static void main(String[] args) throws IOException { - StreamingWordExtractOptions options = PipelineOptionsFactory.fromArgs(args) - .withValidation() - .as(StreamingWordExtractOptions.class); - options.setStreaming(true); - // In order to cancel the pipelines automatically, - // {@literal DataflowPipelineRunner} is forced to be used. - options.setRunner(DataflowPipelineRunner.class); - - options.setBigQuerySchema(StringToRowConverter.getSchema()); - DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options); - dataflowUtils.setup(); - - Pipeline pipeline = Pipeline.create(options); - - String tableSpec = new StringBuilder() - .append(options.getProject()).append(":") - .append(options.getBigQueryDataset()).append(".") - .append(options.getBigQueryTable()) - .toString(); - pipeline - .apply(PubsubIO.Read.topic(options.getPubsubTopic())) - .apply(ParDo.of(new ExtractWords())) - .apply(ParDo.of(new Uppercase())) - .apply(ParDo.of(new StringToRowConverter())) - .apply(BigQueryIO.Write.to(tableSpec) - .withSchema(StringToRowConverter.getSchema())); - - PipelineResult result = pipeline.run(); - - if (!options.getInputFile().isEmpty()) { - // Inject the data into the Pub/Sub topic with a Dataflow batch pipeline. - dataflowUtils.runInjectorPipeline(options.getInputFile(), options.getPubsubTopic()); - } - - // dataflowUtils will try to cancel the pipeline and the injector before the program exists. - dataflowUtils.waitToFinish(result); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TfIdf.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TfIdf.java deleted file mode 100644 index a02b52554e..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TfIdf.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StringDelegateCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.Keys; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.WithKeys; -import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult; -import com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey; -import com.google.cloud.dataflow.sdk.transforms.join.KeyedPCollectionTuple; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashSet; -import java.util.Set; - -/** - * An example that computes a basic TF-IDF search table for a directory or GCS prefix. - * - *

              Concepts: joining data; side inputs; logging - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * and a local output file or output prefix on GCS: - *
              {@code
              - *   --output=[YOUR_LOCAL_FILE | gs://YOUR_OUTPUT_PREFIX]
              - * }
              - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * and an output prefix on GCS:
              - *   --output=gs://YOUR_OUTPUT_PREFIX
              - * }
              - * - *

              The default input is {@code gs://dataflow-samples/shakespeare/} and can be overridden with - * {@code --input}. - */ -public class TfIdf { - /** - * Options supported by {@link TfIdf}. - * - *

              Inherits standard configuration options. - */ - private interface Options extends PipelineOptions { - @Description("Path to the directory or GCS prefix containing files to read from") - @Default.String("gs://dataflow-samples/shakespeare/") - String getInput(); - void setInput(String value); - - @Description("Prefix of output URI to write to") - @Validation.Required - String getOutput(); - void setOutput(String value); - } - - /** - * Lists documents contained beneath the {@code options.input} prefix/directory. - */ - public static Set listInputDocuments(Options options) - throws URISyntaxException, IOException { - URI baseUri = new URI(options.getInput()); - - // List all documents in the directory or GCS prefix. - URI absoluteUri; - if (baseUri.getScheme() != null) { - absoluteUri = baseUri; - } else { - absoluteUri = new URI( - "file", - baseUri.getAuthority(), - baseUri.getPath(), - baseUri.getQuery(), - baseUri.getFragment()); - } - - Set uris = new HashSet<>(); - if (absoluteUri.getScheme().equals("file")) { - File directory = new File(absoluteUri); - for (String entry : directory.list()) { - File path = new File(directory, entry); - uris.add(path.toURI()); - } - } else if (absoluteUri.getScheme().equals("gs")) { - GcsUtil gcsUtil = options.as(GcsOptions.class).getGcsUtil(); - URI gcsUriGlob = new URI( - absoluteUri.getScheme(), - absoluteUri.getAuthority(), - absoluteUri.getPath() + "*", - absoluteUri.getQuery(), - absoluteUri.getFragment()); - for (GcsPath entry : gcsUtil.expand(GcsPath.fromUri(gcsUriGlob))) { - uris.add(entry.toUri()); - } - } - - return uris; - } - - /** - * Reads the documents at the provided uris and returns all lines - * from the documents tagged with which document they are from. - */ - public static class ReadDocuments - extends PTransform>> { - private Iterable uris; - - public ReadDocuments(Iterable uris) { - this.uris = uris; - } - - @Override - public Coder getDefaultOutputCoder() { - return KvCoder.of(StringDelegateCoder.of(URI.class), StringUtf8Coder.of()); - } - - @Override - public PCollection> apply(PInput input) { - Pipeline pipeline = input.getPipeline(); - - // Create one TextIO.Read transform for each document - // and add its output to a PCollectionList - PCollectionList> urisToLines = - PCollectionList.empty(pipeline); - - // TextIO.Read supports: - // - file: URIs and paths locally - // - gs: URIs on the service - for (final URI uri : uris) { - String uriString; - if (uri.getScheme().equals("file")) { - uriString = new File(uri).getPath(); - } else { - uriString = uri.toString(); - } - - PCollection> oneUriToLines = pipeline - .apply(TextIO.Read.from(uriString) - .named("TextIO.Read(" + uriString + ")")) - .apply("WithKeys(" + uriString + ")", WithKeys.of(uri)); - - urisToLines = urisToLines.and(oneUriToLines); - } - - return urisToLines.apply(Flatten.>pCollections()); - } - } - - /** - * A transform containing a basic TF-IDF pipeline. The input consists of KV objects - * where the key is the document's URI and the value is a piece - * of the document's content. The output is mapping from terms to - * scores for each document URI. - */ - public static class ComputeTfIdf - extends PTransform>, PCollection>>> { - public ComputeTfIdf() { } - - @Override - public PCollection>> apply( - PCollection> uriToContent) { - - // Compute the total number of documents, and - // prepare this singleton PCollectionView for - // use as a side input. - final PCollectionView totalDocuments = - uriToContent - .apply("GetURIs", Keys.create()) - .apply("RemoveDuplicateDocs", RemoveDuplicates.create()) - .apply(Count.globally()) - .apply(View.asSingleton()); - - // Create a collection of pairs mapping a URI to each - // of the words in the document associated with that that URI. - PCollection> uriToWords = uriToContent - .apply(ParDo.named("SplitWords").of( - new DoFn, KV>() { - @Override - public void processElement(ProcessContext c) { - URI uri = c.element().getKey(); - String line = c.element().getValue(); - for (String word : line.split("\\W+")) { - // Log INFO messages when the word “love” is found. - if (word.toLowerCase().equals("love")) { - LOG.info("Found {}", word.toLowerCase()); - } - - if (!word.isEmpty()) { - c.output(KV.of(uri, word.toLowerCase())); - } - } - } - })); - - // Compute a mapping from each word to the total - // number of documents in which it appears. - PCollection> wordToDocCount = uriToWords - .apply("RemoveDuplicateWords", RemoveDuplicates.>create()) - .apply(Values.create()) - .apply("CountDocs", Count.perElement()); - - // Compute a mapping from each URI to the total - // number of words in the document associated with that URI. - PCollection> uriToWordTotal = uriToWords - .apply("GetURIs2", Keys.create()) - .apply("CountWords", Count.perElement()); - - // Count, for each (URI, word) pair, the number of - // occurrences of that word in the document associated - // with the URI. - PCollection, Long>> uriAndWordToCount = uriToWords - .apply("CountWordDocPairs", Count.>perElement()); - - // Adjust the above collection to a mapping from - // (URI, word) pairs to counts into an isomorphic mapping - // from URI to (word, count) pairs, to prepare for a join - // by the URI key. - PCollection>> uriToWordAndCount = uriAndWordToCount - .apply(ParDo.named("ShiftKeys").of( - new DoFn, Long>, KV>>() { - @Override - public void processElement(ProcessContext c) { - URI uri = c.element().getKey().getKey(); - String word = c.element().getKey().getValue(); - Long occurrences = c.element().getValue(); - c.output(KV.of(uri, KV.of(word, occurrences))); - } - })); - - // Prepare to join the mapping of URI to (word, count) pairs with - // the mapping of URI to total word counts, by associating - // each of the input PCollection> with - // a tuple tag. Each input must have the same key type, URI - // in this case. The type parameter of the tuple tag matches - // the types of the values for each collection. - final TupleTag wordTotalsTag = new TupleTag(); - final TupleTag> wordCountsTag = new TupleTag>(); - KeyedPCollectionTuple coGbkInput = KeyedPCollectionTuple - .of(wordTotalsTag, uriToWordTotal) - .and(wordCountsTag, uriToWordAndCount); - - // Perform a CoGroupByKey (a sort of pre-join) on the prepared - // inputs. This yields a mapping from URI to a CoGbkResult - // (CoGroupByKey Result). The CoGbkResult is a mapping - // from the above tuple tags to the values in each input - // associated with a particular URI. In this case, each - // KV group a URI with the total number of - // words in that document as well as all the (word, count) - // pairs for particular words. - PCollection> uriToWordAndCountAndTotal = coGbkInput - .apply("CoGroupByUri", CoGroupByKey.create()); - - // Compute a mapping from each word to a (URI, term frequency) - // pair for each URI. A word's term frequency for a document - // is simply the number of times that word occurs in the document - // divided by the total number of words in the document. - PCollection>> wordToUriAndTf = uriToWordAndCountAndTotal - .apply(ParDo.named("ComputeTermFrequencies").of( - new DoFn, KV>>() { - @Override - public void processElement(ProcessContext c) { - URI uri = c.element().getKey(); - Long wordTotal = c.element().getValue().getOnly(wordTotalsTag); - - for (KV wordAndCount - : c.element().getValue().getAll(wordCountsTag)) { - String word = wordAndCount.getKey(); - Long wordCount = wordAndCount.getValue(); - Double termFrequency = wordCount.doubleValue() / wordTotal.doubleValue(); - c.output(KV.of(word, KV.of(uri, termFrequency))); - } - } - })); - - // Compute a mapping from each word to its document frequency. - // A word's document frequency in a corpus is the number of - // documents in which the word appears divided by the total - // number of documents in the corpus. Note how the total number of - // documents is passed as a side input; the same value is - // presented to each invocation of the DoFn. - PCollection> wordToDf = wordToDocCount - .apply(ParDo - .named("ComputeDocFrequencies") - .withSideInputs(totalDocuments) - .of(new DoFn, KV>() { - @Override - public void processElement(ProcessContext c) { - String word = c.element().getKey(); - Long documentCount = c.element().getValue(); - Long documentTotal = c.sideInput(totalDocuments); - Double documentFrequency = documentCount.doubleValue() - / documentTotal.doubleValue(); - - c.output(KV.of(word, documentFrequency)); - } - })); - - // Join the term frequency and document frequency - // collections, each keyed on the word. - final TupleTag> tfTag = new TupleTag>(); - final TupleTag dfTag = new TupleTag(); - PCollection> wordToUriAndTfAndDf = KeyedPCollectionTuple - .of(tfTag, wordToUriAndTf) - .and(dfTag, wordToDf) - .apply(CoGroupByKey.create()); - - // Compute a mapping from each word to a (URI, TF-IDF) score - // for each URI. There are a variety of definitions of TF-IDF - // ("term frequency - inverse document frequency") score; - // here we use a basic version that is the term frequency - // divided by the log of the document frequency. - PCollection>> wordToUriAndTfIdf = wordToUriAndTfAndDf - .apply(ParDo.named("ComputeTfIdf").of( - new DoFn, KV>>() { - @Override - public void processElement(ProcessContext c) { - String word = c.element().getKey(); - Double df = c.element().getValue().getOnly(dfTag); - - for (KV uriAndTf : c.element().getValue().getAll(tfTag)) { - URI uri = uriAndTf.getKey(); - Double tf = uriAndTf.getValue(); - Double tfIdf = tf * Math.log(1 / df); - c.output(KV.of(word, KV.of(uri, tfIdf))); - } - } - })); - - return wordToUriAndTfIdf; - } - - // Instantiate Logger. - // It is suggested that the user specify the class name of the containing class - // (in this case ComputeTfIdf). - private static final Logger LOG = LoggerFactory.getLogger(ComputeTfIdf.class); - } - - /** - * A {@link PTransform} to write, in CSV format, a mapping from term and URI - * to score. - */ - public static class WriteTfIdf - extends PTransform>>, PDone> { - private String output; - - public WriteTfIdf(String output) { - this.output = output; - } - - @Override - public PDone apply(PCollection>> wordToUriAndTfIdf) { - return wordToUriAndTfIdf - .apply(ParDo.named("Format").of(new DoFn>, String>() { - @Override - public void processElement(ProcessContext c) { - c.output(String.format("%s,\t%s,\t%f", - c.element().getKey(), - c.element().getValue().getKey(), - c.element().getValue().getValue())); - } - })) - .apply(TextIO.Write - .to(output) - .withSuffix(".csv")); - } - } - - public static void main(String[] args) throws Exception { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline pipeline = Pipeline.create(options); - pipeline.getCoderRegistry().registerCoder(URI.class, StringDelegateCoder.of(URI.class)); - - pipeline - .apply(new ReadDocuments(listInputDocuments(options))) - .apply(new ComputeTfIdf()) - .apply(new WriteTfIdf(options.getOutput())); - - pipeline.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java deleted file mode 100644 index 1f2be1f0b1..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessions.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableComparator; -import com.google.cloud.dataflow.sdk.transforms.Top; -import com.google.cloud.dataflow.sdk.transforms.windowing.CalendarWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.List; - -/** - * An example that reads Wikipedia edit data from Cloud Storage and computes the user with - * the longest string of edits separated by no more than an hour within each month. - * - *

              Concepts: Using Windowing to perform time-based aggregations of data. - * - *

              It is not recommended to execute this pipeline locally, given the size of the default input - * data. - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * and an output prefix on GCS: - *
              {@code
              - *   --output=gs://YOUR_OUTPUT_PREFIX
              - * }
              - * - *

              The default input is {@code gs://dataflow-samples/wikipedia_edits/*.json} and can be - * overridden with {@code --input}. - */ -public class TopWikipediaSessions { - private static final String EXPORTED_WIKI_TABLE = "gs://dataflow-samples/wikipedia_edits/*.json"; - - /** - * Extracts user and timestamp from a TableRow representing a Wikipedia edit. - */ - static class ExtractUserAndTimestamp extends DoFn { - @Override - public void processElement(ProcessContext c) { - TableRow row = c.element(); - int timestamp = (Integer) row.get("timestamp"); - String userName = (String) row.get("contributor_username"); - if (userName != null) { - // Sets the implicit timestamp field to be used in windowing. - c.outputWithTimestamp(userName, new Instant(timestamp * 1000L)); - } - } - } - - /** - * Computes the number of edits in each user session. A session is defined as - * a string of edits where each is separated from the next by less than an hour. - */ - static class ComputeSessions - extends PTransform, PCollection>> { - @Override - public PCollection> apply(PCollection actions) { - return actions - .apply(Window.into(Sessions.withGapDuration(Duration.standardHours(1)))) - - .apply(Count.perElement()); - } - } - - /** - * Computes the longest session ending in each month. - */ - private static class TopPerMonth - extends PTransform>, PCollection>>> { - @Override - public PCollection>> apply(PCollection> sessions) { - return sessions - .apply(Window.>into(CalendarWindows.months(1))) - - .apply(Top.of(1, new SerializableComparator>() { - @Override - public int compare(KV o1, KV o2) { - return Long.compare(o1.getValue(), o2.getValue()); - } - }).withoutDefaults()); - } - } - - static class SessionsToStringsDoFn extends DoFn, KV> - implements RequiresWindowAccess { - - @Override - public void processElement(ProcessContext c) { - c.output(KV.of( - c.element().getKey() + " : " + c.window(), c.element().getValue())); - } - } - - static class FormatOutputDoFn extends DoFn>, String> - implements RequiresWindowAccess { - @Override - public void processElement(ProcessContext c) { - for (KV item : c.element()) { - String session = item.getKey(); - long count = item.getValue(); - c.output(session + " : " + count + " : " + ((IntervalWindow) c.window()).start()); - } - } - } - - static class ComputeTopSessions extends PTransform, PCollection> { - - private final double samplingThreshold; - - public ComputeTopSessions(double samplingThreshold) { - this.samplingThreshold = samplingThreshold; - } - - @Override - public PCollection apply(PCollection input) { - return input - .apply(ParDo.of(new ExtractUserAndTimestamp())) - - .apply(ParDo.named("SampleUsers").of( - new DoFn() { - @Override - public void processElement(ProcessContext c) { - if (Math.abs(c.element().hashCode()) <= Integer.MAX_VALUE * samplingThreshold) { - c.output(c.element()); - } - } - })) - - .apply(new ComputeSessions()) - - .apply(ParDo.named("SessionsToStrings").of(new SessionsToStringsDoFn())) - .apply(new TopPerMonth()) - .apply(ParDo.named("FormatOutput").of(new FormatOutputDoFn())); - } - } - - /** - * Options supported by this class. - * - *

              Inherits standard Dataflow configuration options. - */ - private interface Options extends PipelineOptions { - @Description( - "Input specified as a GCS path containing a BigQuery table exported as json") - @Default.String(EXPORTED_WIKI_TABLE) - String getInput(); - void setInput(String value); - - @Description("File to output results to") - @Validation.Required - String getOutput(); - void setOutput(String value); - } - - public static void main(String[] args) { - Options options = PipelineOptionsFactory.fromArgs(args) - .withValidation() - .as(Options.class); - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - - Pipeline p = Pipeline.create(dataflowOptions); - - double samplingThreshold = 0.1; - - p.apply(TextIO.Read - .from(options.getInput()) - .withCoder(TableRowJsonCoder.of())) - .apply(new ComputeTopSessions(samplingThreshold)) - .apply(TextIO.Write.named("Write").withoutSharding().to(options.getOutput())); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficMaxLaneFlow.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficMaxLaneFlow.java deleted file mode 100644 index 2d5425208b..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficMaxLaneFlow.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.examples.common.DataflowExampleOptions; -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions; -import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicAndSubscriptionOptions; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Strings; - -import org.apache.avro.reflect.Nullable; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * A Dataflow Example that runs in both batch and streaming modes with traffic sensor data. - * You can configure the running mode by setting {@literal --streaming} to true or false. - * - *

              Concepts: The batch and streaming runners, sliding windows, Google Cloud Pub/Sub - * topic injection, use of the AvroCoder to encode a custom class, and custom Combine transforms. - * - *

              This example analyzes traffic sensor data using SlidingWindows. For each window, - * it finds the lane that had the highest flow recorded, for each sensor station. It writes - * those max values along with auxiliary info to a BigQuery table. - * - *

              In batch mode, the pipeline reads traffic sensor data from {@literal --inputFile}. - * - *

              In streaming mode, the pipeline reads the data from a Pub/Sub topic. - * By default, the example will run a separate pipeline to inject the data from the default - * {@literal --inputFile} to the Pub/Sub {@literal --pubsubTopic}. It will make it available for - * the streaming pipeline to process. You may override the default {@literal --inputFile} with the - * file of your choosing. You may also set {@literal --inputFile} to an empty string, which will - * disable the automatic Pub/Sub injection, and allow you to use separate tool to control the input - * to this example. An example code, which publishes traffic sensor data to a Pub/Sub topic, - * is provided in - * . - * - *

              The example is configured to use the default Pub/Sub topic and the default BigQuery table - * from the example common package (there are no defaults for a general Dataflow pipeline). - * You can override them by using the {@literal --pubsubTopic}, {@literal --bigQueryDataset}, and - * {@literal --bigQueryTable} options. If the Pub/Sub topic or the BigQuery table do not exist, - * the example will try to create them. - * - *

              The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C) - * and then exits. - */ -public class TrafficMaxLaneFlow { - - private static final String PUBSUB_TIMESTAMP_LABEL_KEY = "timestamp_ms"; - private static final Integer VALID_INPUTS = 4999; - - static final int WINDOW_DURATION = 60; // Default sliding window duration in minutes - static final int WINDOW_SLIDE_EVERY = 5; // Default window 'slide every' setting in minutes - - /** - * This class holds information about each lane in a station reading, along with some general - * information from the reading. - */ - @DefaultCoder(AvroCoder.class) - static class LaneInfo { - @Nullable String stationId; - @Nullable String lane; - @Nullable String direction; - @Nullable String freeway; - @Nullable String recordedTimestamp; - @Nullable Integer laneFlow; - @Nullable Integer totalFlow; - @Nullable Double laneAO; - @Nullable Double laneAS; - - public LaneInfo() {} - - public LaneInfo(String stationId, String lane, String direction, String freeway, - String timestamp, Integer laneFlow, Double laneAO, - Double laneAS, Integer totalFlow) { - this.stationId = stationId; - this.lane = lane; - this.direction = direction; - this.freeway = freeway; - this.recordedTimestamp = timestamp; - this.laneFlow = laneFlow; - this.laneAO = laneAO; - this.laneAS = laneAS; - this.totalFlow = totalFlow; - } - - public String getStationId() { - return this.stationId; - } - public String getLane() { - return this.lane; - } - public String getDirection() { - return this.direction; - } - public String getFreeway() { - return this.freeway; - } - public String getRecordedTimestamp() { - return this.recordedTimestamp; - } - public Integer getLaneFlow() { - return this.laneFlow; - } - public Double getLaneAO() { - return this.laneAO; - } - public Double getLaneAS() { - return this.laneAS; - } - public Integer getTotalFlow() { - return this.totalFlow; - } - } - - /** - * Extract the timestamp field from the input string, and use it as the element timestamp. - */ - static class ExtractTimestamps extends DoFn { - private static final DateTimeFormatter dateTimeFormat = - DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss"); - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - String[] items = c.element().split(","); - if (items.length > 0) { - try { - String timestamp = items[0]; - c.outputWithTimestamp(c.element(), new Instant(dateTimeFormat.parseMillis(timestamp))); - } catch (IllegalArgumentException e) { - // Skip the invalid input. - } - } - } - } - - /** - * Extract flow information for each of the 8 lanes in a reading, and output as separate tuples. - * This will let us determine which lane has the max flow for that station over the span of the - * window, and output not only the max flow from that calculation, but other associated - * information. The number of lanes for which data is present depends upon which freeway the data - * point comes from. - */ - static class ExtractFlowInfoFn extends DoFn> { - - @Override - public void processElement(ProcessContext c) { - String[] items = c.element().split(","); - if (items.length < 48) { - // Skip the invalid input. - return; - } - // extract the sensor information for the lanes from the input string fields. - String timestamp = items[0]; - String stationId = items[1]; - String freeway = items[2]; - String direction = items[3]; - Integer totalFlow = tryIntParse(items[7]); - for (int i = 1; i <= 8; ++i) { - Integer laneFlow = tryIntParse(items[6 + 5 * i]); - Double laneAvgOccupancy = tryDoubleParse(items[7 + 5 * i]); - Double laneAvgSpeed = tryDoubleParse(items[8 + 5 * i]); - if (laneFlow == null || laneAvgOccupancy == null || laneAvgSpeed == null) { - return; - } - LaneInfo laneInfo = new LaneInfo(stationId, "lane" + i, direction, freeway, timestamp, - laneFlow, laneAvgOccupancy, laneAvgSpeed, totalFlow); - c.output(KV.of(stationId, laneInfo)); - } - } - } - - /** - * A custom 'combine function' used with the Combine.perKey transform. Used to find the max lane - * flow over all the data points in the Window. Extracts the lane flow from the input string and - * determines whether it's the max seen so far. We're using a custom combiner instead of the Max - * transform because we want to retain the additional information we've associated with the flow - * value. - */ - public static class MaxFlow implements SerializableFunction, LaneInfo> { - @Override - public LaneInfo apply(Iterable input) { - Integer max = 0; - LaneInfo maxInfo = new LaneInfo(); - for (LaneInfo item : input) { - Integer flow = item.getLaneFlow(); - if (flow != null && (flow >= max)) { - max = flow; - maxInfo = item; - } - } - return maxInfo; - } - } - - /** - * Format the results of the Max Lane flow calculation to a TableRow, to save to BigQuery. - * Add the timestamp from the window context. - */ - static class FormatMaxesFn extends DoFn, TableRow> { - @Override - public void processElement(ProcessContext c) { - - LaneInfo laneInfo = c.element().getValue(); - TableRow row = new TableRow() - .set("station_id", c.element().getKey()) - .set("direction", laneInfo.getDirection()) - .set("freeway", laneInfo.getFreeway()) - .set("lane_max_flow", laneInfo.getLaneFlow()) - .set("lane", laneInfo.getLane()) - .set("avg_occ", laneInfo.getLaneAO()) - .set("avg_speed", laneInfo.getLaneAS()) - .set("total_flow", laneInfo.getTotalFlow()) - .set("recorded_timestamp", laneInfo.getRecordedTimestamp()) - .set("window_timestamp", c.timestamp().toString()); - c.output(row); - } - - /** Defines the BigQuery schema used for the output. */ - static TableSchema getSchema() { - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("station_id").setType("STRING")); - fields.add(new TableFieldSchema().setName("direction").setType("STRING")); - fields.add(new TableFieldSchema().setName("freeway").setType("STRING")); - fields.add(new TableFieldSchema().setName("lane_max_flow").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("lane").setType("STRING")); - fields.add(new TableFieldSchema().setName("avg_occ").setType("FLOAT")); - fields.add(new TableFieldSchema().setName("avg_speed").setType("FLOAT")); - fields.add(new TableFieldSchema().setName("total_flow").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("window_timestamp").setType("TIMESTAMP")); - fields.add(new TableFieldSchema().setName("recorded_timestamp").setType("STRING")); - TableSchema schema = new TableSchema().setFields(fields); - return schema; - } - } - - /** - * This PTransform extracts lane info, calculates the max lane flow found for a given station (for - * the current Window) using a custom 'combiner', and formats the results for BigQuery. - */ - static class MaxLaneFlow - extends PTransform>, PCollection> { - @Override - public PCollection apply(PCollection> flowInfo) { - // stationId, LaneInfo => stationId + max lane flow info - PCollection> flowMaxes = - flowInfo.apply(Combine.perKey( - new MaxFlow())); - - // ... => row... - PCollection results = flowMaxes.apply( - ParDo.of(new FormatMaxesFn())); - - return results; - } - } - - static class ReadFileAndExtractTimestamps extends PTransform> { - private final String inputFile; - - public ReadFileAndExtractTimestamps(String inputFile) { - this.inputFile = inputFile; - } - - @Override - public PCollection apply(PBegin begin) { - return begin - .apply(TextIO.Read.from(inputFile)) - .apply(ParDo.of(new ExtractTimestamps())); - } - } - - /** - * Options supported by {@link TrafficMaxLaneFlow}. - * - *

              Inherits standard configuration options. - */ - private interface TrafficMaxLaneFlowOptions extends DataflowExampleOptions, - ExamplePubsubTopicAndSubscriptionOptions, ExampleBigQueryTableOptions { - @Description("Input file to inject to Pub/Sub topic") - @Default.String("gs://dataflow-samples/traffic_sensor/" - + "Freeways-5Minaa2010-01-01_to_2010-02-15_test2.csv") - String getInputFile(); - void setInputFile(String value); - - @Description("Numeric value of sliding window duration, in minutes") - @Default.Integer(WINDOW_DURATION) - Integer getWindowDuration(); - void setWindowDuration(Integer value); - - @Description("Numeric value of window 'slide every' setting, in minutes") - @Default.Integer(WINDOW_SLIDE_EVERY) - Integer getWindowSlideEvery(); - void setWindowSlideEvery(Integer value); - - @Description("Whether to run the pipeline with unbounded input") - @Default.Boolean(false) - boolean isUnbounded(); - void setUnbounded(boolean value); - } - - /** - * Sets up and starts streaming pipeline. - * - * @throws IOException if there is a problem setting up resources - */ - public static void main(String[] args) throws IOException { - TrafficMaxLaneFlowOptions options = PipelineOptionsFactory.fromArgs(args) - .withValidation() - .as(TrafficMaxLaneFlowOptions.class); - options.setBigQuerySchema(FormatMaxesFn.getSchema()); - // Using DataflowExampleUtils to set up required resources. - DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options, options.isUnbounded()); - - Pipeline pipeline = Pipeline.create(options); - TableReference tableRef = new TableReference(); - tableRef.setProjectId(options.getProject()); - tableRef.setDatasetId(options.getBigQueryDataset()); - tableRef.setTableId(options.getBigQueryTable()); - - PCollection input; - if (options.isUnbounded()) { - // Read unbounded PubSubIO. - input = pipeline.apply(PubsubIO.Read - .timestampLabel(PUBSUB_TIMESTAMP_LABEL_KEY) - .subscription(options.getPubsubSubscription())); - } else { - // Read bounded PubSubIO. - input = pipeline.apply(PubsubIO.Read - .timestampLabel(PUBSUB_TIMESTAMP_LABEL_KEY) - .subscription(options.getPubsubSubscription()).maxNumRecords(VALID_INPUTS)); - - // To read bounded TextIO files, use: - // input = pipeline.apply(new ReadFileAndExtractTimestamps(options.getInputFile())); - } - input - // row... => ... - .apply(ParDo.of(new ExtractFlowInfoFn())) - // map the incoming data stream into sliding windows. The default window duration values - // work well if you're running the accompanying Pub/Sub generator script with the - // --replay flag, which simulates pauses in the sensor data publication. You may want to - // adjust them otherwise. - .apply(Window.>into(SlidingWindows.of( - Duration.standardMinutes(options.getWindowDuration())). - every(Duration.standardMinutes(options.getWindowSlideEvery())))) - .apply(new MaxLaneFlow()) - .apply(BigQueryIO.Write.to(tableRef) - .withSchema(FormatMaxesFn.getSchema())); - - // Inject the data into the Pub/Sub topic with a Dataflow batch pipeline. - if (!Strings.isNullOrEmpty(options.getInputFile()) - && !Strings.isNullOrEmpty(options.getPubsubTopic())) { - dataflowUtils.runInjectorPipeline( - new ReadFileAndExtractTimestamps(options.getInputFile()), - options.getPubsubTopic(), - PUBSUB_TIMESTAMP_LABEL_KEY); - } - - // Run the pipeline. - PipelineResult result = pipeline.run(); - - // dataflowUtils will try to cancel the pipeline and the injector before the program exists. - dataflowUtils.waitToFinish(result); - } - - private static Integer tryIntParse(String number) { - try { - return Integer.parseInt(number); - } catch (NumberFormatException e) { - return null; - } - } - - private static Double tryDoubleParse(String number) { - try { - return Double.parseDouble(number); - } catch (NumberFormatException e) { - return null; - } - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficRoutes.java b/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficRoutes.java deleted file mode 100644 index e3e88c22da..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/complete/TrafficRoutes.java +++ /dev/null @@ -1,459 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.examples.common.DataflowExampleOptions; -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions; -import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicAndSubscriptionOptions; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; - -import org.apache.avro.reflect.Nullable; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; - -/** - * A Dataflow Example that runs in both batch and streaming modes with traffic sensor data. - * You can configure the running mode by setting {@literal --streaming} to true or false. - * - *

              Concepts: The batch and streaming runners, GroupByKey, sliding windows, and - * Google Cloud Pub/Sub topic injection. - * - *

              This example analyzes traffic sensor data using SlidingWindows. For each window, - * it calculates the average speed over the window for some small set of predefined 'routes', - * and looks for 'slowdowns' in those routes. It writes its results to a BigQuery table. - * - *

              In batch mode, the pipeline reads traffic sensor data from {@literal --inputFile}. - * - *

              In streaming mode, the pipeline reads the data from a Pub/Sub topic. - * By default, the example will run a separate pipeline to inject the data from the default - * {@literal --inputFile} to the Pub/Sub {@literal --pubsubTopic}. It will make it available for - * the streaming pipeline to process. You may override the default {@literal --inputFile} with the - * file of your choosing. You may also set {@literal --inputFile} to an empty string, which will - * disable the automatic Pub/Sub injection, and allow you to use separate tool to control the input - * to this example. An example code, which publishes traffic sensor data to a Pub/Sub topic, - * is provided in - * . - * - *

              The example is configured to use the default Pub/Sub topic and the default BigQuery table - * from the example common package (there are no defaults for a general Dataflow pipeline). - * You can override them by using the {@literal --pubsubTopic}, {@literal --bigQueryDataset}, and - * {@literal --bigQueryTable} options. If the Pub/Sub topic or the BigQuery table do not exist, - * the example will try to create them. - * - *

              The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C) - * and then exits. - */ - -public class TrafficRoutes { - - private static final String PUBSUB_TIMESTAMP_LABEL_KEY = "timestamp_ms"; - private static final Integer VALID_INPUTS = 4999; - - // Instantiate some small predefined San Diego routes to analyze - static Map sdStations = buildStationInfo(); - static final int WINDOW_DURATION = 3; // Default sliding window duration in minutes - static final int WINDOW_SLIDE_EVERY = 1; // Default window 'slide every' setting in minutes - - /** - * This class holds information about a station reading's average speed. - */ - @DefaultCoder(AvroCoder.class) - static class StationSpeed implements Comparable { - @Nullable String stationId; - @Nullable Double avgSpeed; - @Nullable Long timestamp; - - public StationSpeed() {} - - public StationSpeed(String stationId, Double avgSpeed, Long timestamp) { - this.stationId = stationId; - this.avgSpeed = avgSpeed; - this.timestamp = timestamp; - } - - public String getStationId() { - return this.stationId; - } - public Double getAvgSpeed() { - return this.avgSpeed; - } - - @Override - public int compareTo(StationSpeed other) { - return Long.compare(this.timestamp, other.timestamp); - } - } - - /** - * This class holds information about a route's speed/slowdown. - */ - @DefaultCoder(AvroCoder.class) - static class RouteInfo { - @Nullable String route; - @Nullable Double avgSpeed; - @Nullable Boolean slowdownEvent; - - - public RouteInfo() {} - - public RouteInfo(String route, Double avgSpeed, Boolean slowdownEvent) { - this.route = route; - this.avgSpeed = avgSpeed; - this.slowdownEvent = slowdownEvent; - } - - public String getRoute() { - return this.route; - } - public Double getAvgSpeed() { - return this.avgSpeed; - } - public Boolean getSlowdownEvent() { - return this.slowdownEvent; - } - } - - /** - * Extract the timestamp field from the input string, and use it as the element timestamp. - */ - static class ExtractTimestamps extends DoFn { - private static final DateTimeFormatter dateTimeFormat = - DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss"); - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - String[] items = c.element().split(","); - String timestamp = tryParseTimestamp(items); - if (timestamp != null) { - try { - c.outputWithTimestamp(c.element(), new Instant(dateTimeFormat.parseMillis(timestamp))); - } catch (IllegalArgumentException e) { - // Skip the invalid input. - } - } - } - } - - /** - * Filter out readings for the stations along predefined 'routes', and output - * (station, speed info) keyed on route. - */ - static class ExtractStationSpeedFn extends DoFn> { - - @Override - public void processElement(ProcessContext c) { - String[] items = c.element().split(","); - String stationType = tryParseStationType(items); - // For this analysis, use only 'main line' station types - if (stationType != null && stationType.equals("ML")) { - Double avgSpeed = tryParseAvgSpeed(items); - String stationId = tryParseStationId(items); - // For this simple example, filter out everything but some hardwired routes. - if (avgSpeed != null && stationId != null && sdStations.containsKey(stationId)) { - StationSpeed stationSpeed = - new StationSpeed(stationId, avgSpeed, c.timestamp().getMillis()); - // The tuple key is the 'route' name stored in the 'sdStations' hash. - KV outputValue = KV.of(sdStations.get(stationId), stationSpeed); - c.output(outputValue); - } - } - } - } - - /** - * For a given route, track average speed for the window. Calculate whether - * traffic is currently slowing down, via a predefined threshold. If a supermajority of - * speeds in this sliding window are less than the previous reading we call this a 'slowdown'. - * Note: these calculations are for example purposes only, and are unrealistic and oversimplified. - */ - static class GatherStats - extends DoFn>, KV> { - @Override - public void processElement(ProcessContext c) throws IOException { - String route = c.element().getKey(); - double speedSum = 0.0; - int speedCount = 0; - int speedups = 0; - int slowdowns = 0; - List infoList = Lists.newArrayList(c.element().getValue()); - // StationSpeeds sort by embedded timestamp. - Collections.sort(infoList); - Map prevSpeeds = new HashMap<>(); - // For all stations in the route, sum (non-null) speeds. Keep a count of the non-null speeds. - for (StationSpeed item : infoList) { - Double speed = item.getAvgSpeed(); - if (speed != null) { - speedSum += speed; - speedCount++; - Double lastSpeed = prevSpeeds.get(item.getStationId()); - if (lastSpeed != null) { - if (lastSpeed < speed) { - speedups += 1; - } else { - slowdowns += 1; - } - } - prevSpeeds.put(item.getStationId(), speed); - } - } - if (speedCount == 0) { - // No average to compute. - return; - } - double speedAvg = speedSum / speedCount; - boolean slowdownEvent = slowdowns >= 2 * speedups; - RouteInfo routeInfo = new RouteInfo(route, speedAvg, slowdownEvent); - c.output(KV.of(route, routeInfo)); - } - } - - /** - * Format the results of the slowdown calculations to a TableRow, to save to BigQuery. - */ - static class FormatStatsFn extends DoFn, TableRow> { - @Override - public void processElement(ProcessContext c) { - RouteInfo routeInfo = c.element().getValue(); - TableRow row = new TableRow() - .set("avg_speed", routeInfo.getAvgSpeed()) - .set("slowdown_event", routeInfo.getSlowdownEvent()) - .set("route", c.element().getKey()) - .set("window_timestamp", c.timestamp().toString()); - c.output(row); - } - - /** - * Defines the BigQuery schema used for the output. - */ - static TableSchema getSchema() { - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("route").setType("STRING")); - fields.add(new TableFieldSchema().setName("avg_speed").setType("FLOAT")); - fields.add(new TableFieldSchema().setName("slowdown_event").setType("BOOLEAN")); - fields.add(new TableFieldSchema().setName("window_timestamp").setType("TIMESTAMP")); - TableSchema schema = new TableSchema().setFields(fields); - return schema; - } - } - - /** - * This PTransform extracts speed info from traffic station readings. - * It groups the readings by 'route' and analyzes traffic slowdown for that route. - * Lastly, it formats the results for BigQuery. - */ - static class TrackSpeed extends - PTransform>, PCollection> { - @Override - public PCollection apply(PCollection> stationSpeed) { - // Apply a GroupByKey transform to collect a list of all station - // readings for a given route. - PCollection>> timeGroup = stationSpeed.apply( - GroupByKey.create()); - - // Analyze 'slowdown' over the route readings. - PCollection> stats = timeGroup.apply(ParDo.of(new GatherStats())); - - // Format the results for writing to BigQuery - PCollection results = stats.apply( - ParDo.of(new FormatStatsFn())); - - return results; - } - } - - static class ReadFileAndExtractTimestamps extends PTransform> { - private final String inputFile; - - public ReadFileAndExtractTimestamps(String inputFile) { - this.inputFile = inputFile; - } - - @Override - public PCollection apply(PBegin begin) { - return begin - .apply(TextIO.Read.from(inputFile)) - .apply(ParDo.of(new ExtractTimestamps())); - } - } - - /** - * Options supported by {@link TrafficRoutes}. - * - *

              Inherits standard configuration options. - */ - private interface TrafficRoutesOptions extends DataflowExampleOptions, - ExamplePubsubTopicAndSubscriptionOptions, ExampleBigQueryTableOptions { - @Description("Input file to inject to Pub/Sub topic") - @Default.String("gs://dataflow-samples/traffic_sensor/" - + "Freeways-5Minaa2010-01-01_to_2010-02-15_test2.csv") - String getInputFile(); - void setInputFile(String value); - - @Description("Numeric value of sliding window duration, in minutes") - @Default.Integer(WINDOW_DURATION) - Integer getWindowDuration(); - void setWindowDuration(Integer value); - - @Description("Numeric value of window 'slide every' setting, in minutes") - @Default.Integer(WINDOW_SLIDE_EVERY) - Integer getWindowSlideEvery(); - void setWindowSlideEvery(Integer value); - - @Description("Whether to run the pipeline with unbounded input") - @Default.Boolean(false) - boolean isUnbounded(); - void setUnbounded(boolean value); - } - - /** - * Sets up and starts streaming pipeline. - * - * @throws IOException if there is a problem setting up resources - */ - public static void main(String[] args) throws IOException { - TrafficRoutesOptions options = PipelineOptionsFactory.fromArgs(args) - .withValidation() - .as(TrafficRoutesOptions.class); - - options.setBigQuerySchema(FormatStatsFn.getSchema()); - // Using DataflowExampleUtils to set up required resources. - DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options, options.isUnbounded()); - - Pipeline pipeline = Pipeline.create(options); - TableReference tableRef = new TableReference(); - tableRef.setProjectId(options.getProject()); - tableRef.setDatasetId(options.getBigQueryDataset()); - tableRef.setTableId(options.getBigQueryTable()); - - PCollection input; - if (options.isUnbounded()) { - // Read unbounded PubSubIO. - input = pipeline.apply(PubsubIO.Read - .timestampLabel(PUBSUB_TIMESTAMP_LABEL_KEY) - .subscription(options.getPubsubSubscription())); - } else { - // Read bounded PubSubIO. - input = pipeline.apply(PubsubIO.Read - .timestampLabel(PUBSUB_TIMESTAMP_LABEL_KEY) - .subscription(options.getPubsubSubscription()).maxNumRecords(VALID_INPUTS)); - - // To read bounded TextIO files, use: - // input = pipeline.apply(TextIO.Read.from(options.getInputFile())) - // .apply(ParDo.of(new ExtractTimestamps())); - } - input - // row... => ... - .apply(ParDo.of(new ExtractStationSpeedFn())) - // map the incoming data stream into sliding windows. - // The default window duration values work well if you're running the accompanying Pub/Sub - // generator script without the --replay flag, so that there are no simulated pauses in - // the sensor data publication. You may want to adjust the values otherwise. - .apply(Window.>into(SlidingWindows.of( - Duration.standardMinutes(options.getWindowDuration())). - every(Duration.standardMinutes(options.getWindowSlideEvery())))) - .apply(new TrackSpeed()) - .apply(BigQueryIO.Write.to(tableRef) - .withSchema(FormatStatsFn.getSchema())); - - // Inject the data into the Pub/Sub topic with a Dataflow batch pipeline. - if (!Strings.isNullOrEmpty(options.getInputFile()) - && !Strings.isNullOrEmpty(options.getPubsubTopic())) { - dataflowUtils.runInjectorPipeline( - new ReadFileAndExtractTimestamps(options.getInputFile()), - options.getPubsubTopic(), - PUBSUB_TIMESTAMP_LABEL_KEY); - } - - // Run the pipeline. - PipelineResult result = pipeline.run(); - - // dataflowUtils will try to cancel the pipeline and the injector before the program exists. - dataflowUtils.waitToFinish(result); - } - - private static Double tryParseAvgSpeed(String[] inputItems) { - try { - return Double.parseDouble(tryParseString(inputItems, 9)); - } catch (NumberFormatException e) { - return null; - } catch (NullPointerException e) { - return null; - } - } - - private static String tryParseStationType(String[] inputItems) { - return tryParseString(inputItems, 4); - } - - private static String tryParseStationId(String[] inputItems) { - return tryParseString(inputItems, 1); - } - - private static String tryParseTimestamp(String[] inputItems) { - return tryParseString(inputItems, 0); - } - - private static String tryParseString(String[] inputItems, int index) { - return inputItems.length >= index ? inputItems[index] : null; - } - - /** - * Define some small hard-wired San Diego 'routes' to track based on sensor station ID. - */ - private static Map buildStationInfo() { - Map stations = new Hashtable(); - stations.put("1108413", "SDRoute1"); // from freeway 805 S - stations.put("1108699", "SDRoute2"); // from freeway 78 E - stations.put("1108702", "SDRoute2"); - return stations; - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoes.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoes.java deleted file mode 100644 index 3d86170894..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoes.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import java.util.ArrayList; -import java.util.List; - -/** - * An example that reads the public samples of weather data from BigQuery, counts the number of - * tornadoes that occur in each month, and writes the results to BigQuery. - * - *

              Concepts: Reading/writing BigQuery; counting a PCollection; user-defined PTransforms - * - *

              Note: Before running this example, you must create a BigQuery dataset to contain your output - * table. - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * and the BigQuery table for the output, with the form - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - * }
              - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * and the BigQuery table for the output: - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - * }
              - * - *

              The BigQuery input table defaults to {@code clouddataflow-readonly:samples.weather_stations} - * and can be overridden with {@code --input}. - */ -public class BigQueryTornadoes { - // Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod. - private static final String WEATHER_SAMPLES_TABLE = - "clouddataflow-readonly:samples.weather_stations"; - - /** - * Examines each row in the input table. If a tornado was recorded - * in that sample, the month in which it occurred is output. - */ - static class ExtractTornadoesFn extends DoFn { - @Override - public void processElement(ProcessContext c){ - TableRow row = c.element(); - if ((Boolean) row.get("tornado")) { - c.output(Integer.parseInt((String) row.get("month"))); - } - } - } - - /** - * Prepares the data for writing to BigQuery by building a TableRow object containing an - * integer representation of month and the number of tornadoes that occurred in each month. - */ - static class FormatCountsFn extends DoFn, TableRow> { - @Override - public void processElement(ProcessContext c) { - TableRow row = new TableRow() - .set("month", c.element().getKey()) - .set("tornado_count", c.element().getValue()); - c.output(row); - } - } - - /** - * Takes rows from a table and generates a table of counts. - * - *

              The input schema is described by - * https://developers.google.com/bigquery/docs/dataset-gsod . - * The output contains the total number of tornadoes found in each month in - * the following schema: - *

                - *
              • month: integer
              • - *
              • tornado_count: integer
              • - *
              - */ - static class CountTornadoes - extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection rows) { - - // row... => month... - PCollection tornadoes = rows.apply( - ParDo.of(new ExtractTornadoesFn())); - - // month... => ... - PCollection> tornadoCounts = - tornadoes.apply(Count.perElement()); - - // ... => row... - PCollection results = tornadoCounts.apply( - ParDo.of(new FormatCountsFn())); - - return results; - } - } - - /** - * Options supported by {@link BigQueryTornadoes}. - * - *

              Inherits standard configuration options. - */ - private interface Options extends PipelineOptions { - @Description("Table to read from, specified as " - + ":.") - @Default.String(WEATHER_SAMPLES_TABLE) - String getInput(); - void setInput(String value); - - @Description("BigQuery table to write to, specified as " - + ":.. The dataset must already exist.") - @Validation.Required - String getOutput(); - void setOutput(String value); - } - - public static void main(String[] args) { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - - Pipeline p = Pipeline.create(options); - - // Build the table schema for the output table. - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("month").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("tornado_count").setType("INTEGER")); - TableSchema schema = new TableSchema().setFields(fields); - - p.apply(BigQueryIO.Read.from(options.getInput())) - .apply(new CountTornadoes()) - .apply(BigQueryIO.Write - .to(options.getOutput()) - .withSchema(schema) - .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamples.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamples.java deleted file mode 100644 index b06e573301..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamples.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import java.util.ArrayList; -import java.util.List; - -/** - * An example that reads the public 'Shakespeare' data, and for each word in - * the dataset that is over a given length, generates a string containing the - * list of play names in which that word appears, and saves this information - * to a bigquery table. - * - *

              Concepts: the Combine.perKey transform, which lets you combine the values in a - * key-grouped Collection, and how to use an Aggregator to track information in the - * Monitoring UI. - * - *

              Note: Before running this example, you must create a BigQuery dataset to contain your output - * table. - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * and the BigQuery table for the output: - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - * }
              - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * and the BigQuery table for the output: - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - * }
              - * - *

              The BigQuery input table defaults to {@code publicdata:samples.shakespeare} and can - * be overridden with {@code --input}. - */ -public class CombinePerKeyExamples { - // Use the shakespeare public BigQuery sample - private static final String SHAKESPEARE_TABLE = - "publicdata:samples.shakespeare"; - // We'll track words >= this word length across all plays in the table. - private static final int MIN_WORD_LENGTH = 9; - - /** - * Examines each row in the input table. If the word is greater than or equal to MIN_WORD_LENGTH, - * outputs word, play_name. - */ - static class ExtractLargeWordsFn extends DoFn> { - private final Aggregator smallerWords = - createAggregator("smallerWords", new Sum.SumLongFn()); - - @Override - public void processElement(ProcessContext c){ - TableRow row = c.element(); - String playName = (String) row.get("corpus"); - String word = (String) row.get("word"); - if (word.length() >= MIN_WORD_LENGTH) { - c.output(KV.of(word, playName)); - } else { - // Track how many smaller words we're not including. This information will be - // visible in the Monitoring UI. - smallerWords.addValue(1L); - } - } - } - - - /** - * Prepares the data for writing to BigQuery by building a TableRow object - * containing a word with a string listing the plays in which it appeared. - */ - static class FormatShakespeareOutputFn extends DoFn, TableRow> { - @Override - public void processElement(ProcessContext c) { - TableRow row = new TableRow() - .set("word", c.element().getKey()) - .set("all_plays", c.element().getValue()); - c.output(row); - } - } - - /** - * Reads the public 'Shakespeare' data, and for each word in the dataset - * over a given length, generates a string containing the list of play names - * in which that word appears. It does this via the Combine.perKey - * transform, with the ConcatWords combine function. - * - *

              Combine.perKey is similar to a GroupByKey followed by a ParDo, but - * has more restricted semantics that allow it to be executed more - * efficiently. These records are then formatted as BQ table rows. - */ - static class PlaysForWord - extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection rows) { - - // row... => ... - PCollection> words = rows.apply( - ParDo.of(new ExtractLargeWordsFn())); - - // word, play_name => word, all_plays ... - PCollection> wordAllPlays = - words.apply(Combine.perKey( - new ConcatWords())); - - // ... => row... - PCollection results = wordAllPlays.apply( - ParDo.of(new FormatShakespeareOutputFn())); - - return results; - } - } - - /** - * A 'combine function' used with the Combine.perKey transform. Builds a - * comma-separated string of all input items. So, it will build a string - * containing all the different Shakespeare plays in which the given input - * word has appeared. - */ - public static class ConcatWords implements SerializableFunction, String> { - @Override - public String apply(Iterable input) { - StringBuilder all = new StringBuilder(); - for (String item : input) { - if (!item.isEmpty()) { - if (all.length() == 0) { - all.append(item); - } else { - all.append(","); - all.append(item); - } - } - } - return all.toString(); - } - } - - /** - * Options supported by {@link CombinePerKeyExamples}. - * - *

              Inherits standard configuration options. - */ - private interface Options extends PipelineOptions { - @Description("Table to read from, specified as " - + ":.") - @Default.String(SHAKESPEARE_TABLE) - String getInput(); - void setInput(String value); - - @Description("Table to write to, specified as " - + ":.. " - + "The dataset_id must already exist") - @Validation.Required - String getOutput(); - void setOutput(String value); - } - - public static void main(String[] args) - throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline p = Pipeline.create(options); - - // Build the table schema for the output table. - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("word").setType("STRING")); - fields.add(new TableFieldSchema().setName("all_plays").setType("STRING")); - TableSchema schema = new TableSchema().setFields(fields); - - p.apply(BigQueryIO.Read.from(options.getInput())) - .apply(new PlaysForWord()) - .apply(BigQueryIO.Write - .to(options.getOutput()) - .withSchema(schema) - .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java deleted file mode 100644 index 0e5723dcb1..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DatastoreWordCount.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import static com.google.datastore.v1.client.DatastoreHelper.getString; -import static com.google.datastore.v1.client.DatastoreHelper.makeFilter; -import static com.google.datastore.v1.client.DatastoreHelper.makeKey; -import static com.google.datastore.v1.client.DatastoreHelper.makeValue; - -import com.google.cloud.dataflow.examples.WordCount; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreIO; -import com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.datastore.v1.Entity; -import com.google.datastore.v1.Key; -import com.google.datastore.v1.PropertyFilter; -import com.google.datastore.v1.Query; -import com.google.datastore.v1.Value; - -import java.util.Map; -import java.util.UUID; - -import javax.annotation.Nullable; - -/** - * A WordCount example using DatastoreIO. - * - *

              This example shows how to use DatastoreIO to read from Cloud Datastore and - * write the results to Cloud Storage. Note that this example will write - * data to Cloud Datastore, which may incur charge for Cloud Datastore operations. - * - *

              To run this example, users need to use gcloud to get credential for Cloud Datastore: - *

              {@code
              - * $ gcloud auth login
              - * }
              - * - *

              To run this pipeline locally, the following options must be provided: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --dataset=YOUR_DATASET_ID
              - *   --output=[YOUR_LOCAL_FILE | gs://YOUR_OUTPUT_PATH]
              - * }
              - * - *

              To run this example using Dataflow service, you must additionally - * provide either {@literal --stagingLocation} or {@literal --tempLocation}, and - * select one of the Dataflow pipeline runners, eg - * {@literal --runner=BlockingDataflowPipelineRunner}. - * - *

              Note: this example creates entities with Ancestor keys to ensure that all - * entities created are in the same entity group. Similarly, the query used to read from the Cloud - * Datastore uses an Ancestor filter. Ancestors are used to ensure strongly consistent - * results in Cloud Datastore. For more information, see the Cloud Datastore documentation on - * - * Structing Data for Strong Consistency. - */ -public class DatastoreWordCount { - - /** - * A DoFn that gets the content of an entity (one line in a - * Shakespeare play) and converts it to a string. - */ - static class GetContentFn extends DoFn { - @Override - public void processElement(ProcessContext c) { - Map props = c.element().getProperties(); - Value value = props.get("content"); - if (value != null) { - c.output(getString(value)); - } - } - } - - /** - * A helper function to create the ancestor key for all created and queried entities. - * - *

              We use ancestor keys and ancestor queries for strong consistency. See - * {@link DatastoreWordCount} javadoc for more information. - */ - static Key makeAncestorKey(@Nullable String namespace, String kind) { - Key.Builder keyBuilder = makeKey(kind, "root"); - if (namespace != null) { - keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace); - } - return keyBuilder.build(); - } - - /** - * A DoFn that creates entity for every line in Shakespeare. - */ - static class CreateEntityFn extends DoFn { - private final String namespace; - private final String kind; - private final Key ancestorKey; - - CreateEntityFn(String namespace, String kind) { - this.namespace = namespace; - this.kind = kind; - - // Build the ancestor key for all created entities once, including the namespace. - ancestorKey = makeAncestorKey(namespace, kind); - } - - public Entity makeEntity(String content) { - Entity.Builder entityBuilder = Entity.newBuilder(); - - // All created entities have the same ancestor Key. - Key.Builder keyBuilder = makeKey(ancestorKey, kind, UUID.randomUUID().toString()); - // NOTE: Namespace is not inherited between keys created with DatastoreHelper.makeKey, so - // we must set the namespace on keyBuilder. TODO: Once partitionId inheritance is added, - // we can simplify this code. - if (namespace != null) { - keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace); - } - - entityBuilder.setKey(keyBuilder.build()); - entityBuilder.getMutableProperties().put("content", makeValue(content).build()); - return entityBuilder.build(); - } - - @Override - public void processElement(ProcessContext c) { - c.output(makeEntity(c.element())); - } - } - - /** - * Options supported by {@link DatastoreWordCount}. - * - *

              Inherits standard configuration options. - */ - public interface Options extends PipelineOptions { - @Description("Path of the file to read from and store to Cloud Datastore") - @Default.String("gs://dataflow-samples/shakespeare/kinglear.txt") - String getInput(); - void setInput(String value); - - @Description("Path of the file to write to") - @Validation.Required - String getOutput(); - void setOutput(String value); - - // Note: This maps to Project ID for v1 version of datastore - @Description("Dataset ID to read from Cloud Datastore") - @Validation.Required - String getDataset(); - void setDataset(String value); - - @Description("Cloud Datastore Entity Kind") - @Default.String("shakespeare-demo") - String getKind(); - void setKind(String value); - - @Description("Dataset namespace") - String getNamespace(); - void setNamespace(@Nullable String value); - - @Description("Read an existing dataset, do not write first") - boolean isReadOnly(); - void setReadOnly(boolean value); - - @Description("Number of output shards") - @Default.Integer(0) // If the system should choose automatically. - int getNumShards(); - void setNumShards(int value); - } - - /** - * An example that creates a pipeline to populate DatastoreIO from a - * text input. Forces use of DirectPipelineRunner for local execution mode. - */ - public static void writeDataToDatastore(Options options) { - Pipeline p = Pipeline.create(options); - p.apply(TextIO.Read.named("ReadLines").from(options.getInput())) - .apply(ParDo.of(new CreateEntityFn(options.getNamespace(), options.getKind()))) - .apply(DatastoreIO.v1().write().withProjectId(options.getDataset())); - - p.run(); - } - - /** - * Build a Cloud Datastore ancestor query for the specified {@link Options#getNamespace} and - * {@link Options#getKind}. - * - *

              We use ancestor keys and ancestor queries for strong consistency. See - * {@link DatastoreWordCount} javadoc for more information. - * - * @see Ancestor filters - */ - static Query makeAncestorKindQuery(Options options) { - Query.Builder q = Query.newBuilder(); - q.addKindBuilder().setName(options.getKind()); - q.setFilter(makeFilter( - "__key__", - PropertyFilter.Operator.HAS_ANCESTOR, - makeValue(makeAncestorKey(options.getNamespace(), options.getKind())))); - return q.build(); - } - - /** - * An example that creates a pipeline to do DatastoreIO.Read from Cloud Datastore. - */ - public static void readDataFromDatastore(Options options) { - Query query = makeAncestorKindQuery(options); - - // For Datastore sources, the read namespace can be set on the entire query. - DatastoreV1.Read read = DatastoreIO.v1().read() - .withProjectId(options.getDataset()) - .withQuery(query) - .withNamespace(options.getNamespace()); - - Pipeline p = Pipeline.create(options); - p.apply("ReadShakespeareFromDatastore", read) - .apply("StringifyEntity", ParDo.of(new GetContentFn())) - .apply("CountWords", new WordCount.CountWords()) - .apply("PrintWordCount", MapElements.via(new WordCount.FormatAsTextFn())) - .apply("WriteLines", TextIO.Write.to(options.getOutput()) - .withNumShards(options.getNumShards())); - p.run(); - } - - /** - * An example to demo how to use {@link DatastoreIO}. The runner here is - * customizable, which means users could pass either {@code DirectPipelineRunner} - * or {@code DataflowPipelineRunner} in the pipeline options. - */ - public static void main(String args[]) { - // The options are used in two places, for Dataflow service, and - // building DatastoreIO.Read object - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - - if (!options.isReadOnly()) { - // First example: write data to Datastore for reading later. - // - // NOTE: this write does not delete any existing Entities in the Datastore, so if run - // multiple times with the same output dataset, there may be duplicate entries. The - // Datastore Query tool in the Google Developers Console can be used to inspect or erase all - // entries with a particular namespace and/or kind. - DatastoreWordCount.writeDataToDatastore(options); - } - - // Second example: do parallel read from Datastore. - DatastoreWordCount.readDataFromDatastore(options); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DeDupExample.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DeDupExample.java deleted file mode 100644 index 4cb94a6726..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/DeDupExample.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; - -/** - * This example uses as input Shakespeare's plays as plaintext files, and will remove any - * duplicate lines across all the files. (The output does not preserve any input order). - * - *

              Concepts: the RemoveDuplicates transform, and how to wire transforms together. - * Demonstrates {@link com.google.cloud.dataflow.sdk.io.TextIO.Read}/ - * {@link RemoveDuplicates}/{@link com.google.cloud.dataflow.sdk.io.TextIO.Write}. - * - *

              To execute this pipeline locally, specify general pipeline configuration: - * --project=YOUR_PROJECT_ID - * and a local output file or output prefix on GCS: - * --output=[YOUR_LOCAL_FILE | gs://YOUR_OUTPUT_PREFIX] - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - * --project=YOUR_PROJECT_ID - * --stagingLocation=gs://YOUR_STAGING_DIRECTORY - * --runner=BlockingDataflowPipelineRunner - * and an output prefix on GCS: - * --output=gs://YOUR_OUTPUT_PREFIX - * - *

              The input defaults to {@code gs://dataflow-samples/shakespeare/*} and can be - * overridden with {@code --input}. - */ -public class DeDupExample { - - /** - * Options supported by {@link DeDupExample}. - * - *

              Inherits standard configuration options. - */ - private interface Options extends PipelineOptions { - @Description("Path to the directory or GCS prefix containing files to read from") - @Default.String("gs://dataflow-samples/shakespeare/*") - String getInput(); - void setInput(String value); - - @Description("Path of the file to write to") - @Default.InstanceFactory(OutputFactory.class) - String getOutput(); - void setOutput(String value); - - /** Returns gs://${STAGING_LOCATION}/"deduped.txt". */ - class OutputFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - if (dataflowOptions.getStagingLocation() != null) { - return GcsPath.fromUri(dataflowOptions.getStagingLocation()) - .resolve("deduped.txt").toString(); - } else { - throw new IllegalArgumentException("Must specify --output or --stagingLocation"); - } - } - } - } - - - public static void main(String[] args) - throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline p = Pipeline.create(options); - - p.apply(TextIO.Read.named("ReadLines").from(options.getInput())) - .apply(RemoveDuplicates.create()) - .apply(TextIO.Write.named("DedupedShakespeare") - .to(options.getOutput())); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/FilterExamples.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/FilterExamples.java deleted file mode 100644 index 4538531463..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/FilterExamples.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Mean; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; - -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Logger; - -/** - * This is an example that demonstrates several approaches to filtering, and use of the Mean - * transform. It shows how to dynamically set parameters by defining and using new pipeline options, - * and how to use a value derived by the pipeline. - * - *

              Concepts: The Mean transform; Options configuration; using pipeline-derived data as a side - * input; approaches to filtering, selection, and projection. - * - *

              The example reads public samples of weather data from BigQuery. It performs a - * projection on the data, finds the global mean of the temperature readings, filters on readings - * for a single given month, and then outputs only data (for that month) that has a mean temp - * smaller than the derived global mean. -* - *

              Note: Before running this example, you must create a BigQuery dataset to contain your output - * table. - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * and the BigQuery table for the output: - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - *   [--monthFilter=]
              - * }
              - * 
              - * where optional parameter {@code --monthFilter} is set to a number 1-12. - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * and the BigQuery table for the output: - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - *   [--monthFilter=]
              - * }
              - * 
              - * where optional parameter {@code --monthFilter} is set to a number 1-12. - * - *

              The BigQuery input table defaults to {@code clouddataflow-readonly:samples.weather_stations} - * and can be overridden with {@code --input}. - */ -public class FilterExamples { - // Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod. - private static final String WEATHER_SAMPLES_TABLE = - "clouddataflow-readonly:samples.weather_stations"; - static final Logger LOG = Logger.getLogger(FilterExamples.class.getName()); - static final int MONTH_TO_FILTER = 7; - - /** - * Examines each row in the input table. Outputs only the subset of the cells this example - * is interested in-- the mean_temp and year, month, and day-- as a bigquery table row. - */ - static class ProjectionFn extends DoFn { - @Override - public void processElement(ProcessContext c){ - TableRow row = c.element(); - // Grab year, month, day, mean_temp from the row - Integer year = Integer.parseInt((String) row.get("year")); - Integer month = Integer.parseInt((String) row.get("month")); - Integer day = Integer.parseInt((String) row.get("day")); - Double meanTemp = Double.parseDouble(row.get("mean_temp").toString()); - // Prepares the data for writing to BigQuery by building a TableRow object - TableRow outRow = new TableRow() - .set("year", year).set("month", month) - .set("day", day).set("mean_temp", meanTemp); - c.output(outRow); - } - } - - /** - * Implements 'filter' functionality. - * - *

              Examines each row in the input table. Outputs only rows from the month - * monthFilter, which is passed in as a parameter during construction of this DoFn. - */ - static class FilterSingleMonthDataFn extends DoFn { - Integer monthFilter; - - public FilterSingleMonthDataFn(Integer monthFilter) { - this.monthFilter = monthFilter; - } - - @Override - public void processElement(ProcessContext c){ - TableRow row = c.element(); - Integer month; - month = (Integer) row.get("month"); - if (month.equals(this.monthFilter)) { - c.output(row); - } - } - } - - /** - * Examines each row (weather reading) in the input table. Output the temperature - * reading for that row ('mean_temp'). - */ - static class ExtractTempFn extends DoFn { - @Override - public void processElement(ProcessContext c){ - TableRow row = c.element(); - Double meanTemp = Double.parseDouble(row.get("mean_temp").toString()); - c.output(meanTemp); - } - } - - - - /* - * Finds the global mean of the mean_temp for each day/record, and outputs - * only data that has a mean temp larger than this global mean. - **/ - static class BelowGlobalMean - extends PTransform, PCollection> { - Integer monthFilter; - - public BelowGlobalMean(Integer monthFilter) { - this.monthFilter = monthFilter; - } - - - @Override - public PCollection apply(PCollection rows) { - - // Extract the mean_temp from each row. - PCollection meanTemps = rows.apply( - ParDo.of(new ExtractTempFn())); - - // Find the global mean, of all the mean_temp readings in the weather data, - // and prepare this singleton PCollectionView for use as a side input. - final PCollectionView globalMeanTemp = - meanTemps.apply(Mean.globally()) - .apply(View.asSingleton()); - - // Rows filtered to remove all but a single month - PCollection monthFilteredRows = rows - .apply(ParDo.of(new FilterSingleMonthDataFn(monthFilter))); - - // Then, use the global mean as a side input, to further filter the weather data. - // By using a side input to pass in the filtering criteria, we can use a value - // that is computed earlier in pipeline execution. - // We'll only output readings with temperatures below this mean. - PCollection filteredRows = monthFilteredRows - .apply(ParDo - .named("ParseAndFilter") - .withSideInputs(globalMeanTemp) - .of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - Double meanTemp = Double.parseDouble(c.element().get("mean_temp").toString()); - Double gTemp = c.sideInput(globalMeanTemp); - if (meanTemp < gTemp) { - c.output(c.element()); - } - } - })); - - return filteredRows; - } - } - - - /** - * Options supported by {@link FilterExamples}. - * - *

              Inherits standard configuration options. - */ - private interface Options extends PipelineOptions { - @Description("Table to read from, specified as " - + ":.") - @Default.String(WEATHER_SAMPLES_TABLE) - String getInput(); - void setInput(String value); - - @Description("Table to write to, specified as " - + ":.. " - + "The dataset_id must already exist") - @Validation.Required - String getOutput(); - void setOutput(String value); - - @Description("Numeric value of month to filter on") - @Default.Integer(MONTH_TO_FILTER) - Integer getMonthFilter(); - void setMonthFilter(Integer value); - } - - /** - * Helper method to build the table schema for the output table. - */ - private static TableSchema buildWeatherSchemaProjection() { - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("year").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("month").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("day").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("mean_temp").setType("FLOAT")); - TableSchema schema = new TableSchema().setFields(fields); - return schema; - } - - public static void main(String[] args) - throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline p = Pipeline.create(options); - - TableSchema schema = buildWeatherSchemaProjection(); - - p.apply(BigQueryIO.Read.from(options.getInput())) - .apply(ParDo.of(new ProjectionFn())) - .apply(new BelowGlobalMean(options.getMonthFilter())) - .apply(BigQueryIO.Write - .to(options.getOutput()) - .withSchema(schema) - .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/JoinExamples.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/JoinExamples.java deleted file mode 100644 index c8354c2126..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/JoinExamples.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult; -import com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey; -import com.google.cloud.dataflow.sdk.transforms.join.KeyedPCollectionTuple; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -/** - * This example shows how to do a join on two collections. - * It uses a sample of the GDELT 'world event' data (http://goo.gl/OB6oin), joining the event - * 'action' country code against a table that maps country codes to country names. - * - *

              Concepts: Join operation; multiple input sources. - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * and a local output file or output prefix on GCS: - *
              {@code
              - *   --output=[YOUR_LOCAL_FILE | gs://YOUR_OUTPUT_PREFIX]
              - * }
              - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * and an output prefix on GCS: - *
              {@code
              - *   --output=gs://YOUR_OUTPUT_PREFIX
              - * }
              - */ -public class JoinExamples { - - // A 1000-row sample of the GDELT data here: gdelt-bq:full.events. - private static final String GDELT_EVENTS_TABLE = - "clouddataflow-readonly:samples.gdelt_sample"; - // A table that maps country codes to country names. - private static final String COUNTRY_CODES = - "gdelt-bq:full.crosswalk_geocountrycodetohuman"; - - /** - * Join two collections, using country code as the key. - */ - static PCollection joinEvents(PCollection eventsTable, - PCollection countryCodes) throws Exception { - - final TupleTag eventInfoTag = new TupleTag(); - final TupleTag countryInfoTag = new TupleTag(); - - // transform both input collections to tuple collections, where the keys are country - // codes in both cases. - PCollection> eventInfo = eventsTable.apply( - ParDo.of(new ExtractEventDataFn())); - PCollection> countryInfo = countryCodes.apply( - ParDo.of(new ExtractCountryInfoFn())); - - // country code 'key' -> CGBKR (, ) - PCollection> kvpCollection = KeyedPCollectionTuple - .of(eventInfoTag, eventInfo) - .and(countryInfoTag, countryInfo) - .apply(CoGroupByKey.create()); - - // Process the CoGbkResult elements generated by the CoGroupByKey transform. - // country code 'key' -> string of , - PCollection> finalResultCollection = - kvpCollection.apply(ParDo.named("Process").of( - new DoFn, KV>() { - @Override - public void processElement(ProcessContext c) { - KV e = c.element(); - String countryCode = e.getKey(); - String countryName = "none"; - countryName = e.getValue().getOnly(countryInfoTag); - for (String eventInfo : c.element().getValue().getAll(eventInfoTag)) { - // Generate a string that combines information from both collection values - c.output(KV.of(countryCode, "Country name: " + countryName - + ", Event info: " + eventInfo)); - } - } - })); - - // write to GCS - PCollection formattedResults = finalResultCollection - .apply(ParDo.named("Format").of(new DoFn, String>() { - @Override - public void processElement(ProcessContext c) { - String outputstring = "Country code: " + c.element().getKey() - + ", " + c.element().getValue(); - c.output(outputstring); - } - })); - return formattedResults; - } - - /** - * Examines each row (event) in the input table. Output a KV with the key the country - * code of the event, and the value a string encoding event information. - */ - static class ExtractEventDataFn extends DoFn> { - @Override - public void processElement(ProcessContext c) { - TableRow row = c.element(); - String countryCode = (String) row.get("ActionGeo_CountryCode"); - String sqlDate = (String) row.get("SQLDATE"); - String actor1Name = (String) row.get("Actor1Name"); - String sourceUrl = (String) row.get("SOURCEURL"); - String eventInfo = "Date: " + sqlDate + ", Actor1: " + actor1Name + ", url: " + sourceUrl; - c.output(KV.of(countryCode, eventInfo)); - } - } - - - /** - * Examines each row (country info) in the input table. Output a KV with the key the country - * code, and the value the country name. - */ - static class ExtractCountryInfoFn extends DoFn> { - @Override - public void processElement(ProcessContext c) { - TableRow row = c.element(); - String countryCode = (String) row.get("FIPSCC"); - String countryName = (String) row.get("HumanName"); - c.output(KV.of(countryCode, countryName)); - } - } - - - /** - * Options supported by {@link JoinExamples}. - * - *

              Inherits standard configuration options. - */ - private interface Options extends PipelineOptions { - @Description("Path of the file to write to") - @Validation.Required - String getOutput(); - void setOutput(String value); - } - - public static void main(String[] args) throws Exception { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline p = Pipeline.create(options); - // the following two 'applys' create multiple inputs to our pipeline, one for each - // of our two input sources. - PCollection eventsTable = p.apply(BigQueryIO.Read.from(GDELT_EVENTS_TABLE)); - PCollection countryCodes = p.apply(BigQueryIO.Read.from(COUNTRY_CODES)); - PCollection formattedResults = joinEvents(eventsTable, countryCodes); - formattedResults.apply(TextIO.Write.to(options.getOutput())); - p.run(); - } - -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamples.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamples.java deleted file mode 100644 index e7ec7eac31..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamples.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import java.util.ArrayList; -import java.util.List; - -/** - * An example that reads the public samples of weather data from BigQuery, and finds - * the maximum temperature ('mean_temp') for each month. - * - *

              Concepts: The 'Max' statistical combination function, and how to find the max per - * key group. - * - *

              Note: Before running this example, you must create a BigQuery dataset to contain your output - * table. - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * and the BigQuery table for the output, with the form - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - * }
              - * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * and the BigQuery table for the output: - *
              {@code
              - *   --output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
              - * }
              - * - *

              The BigQuery input table defaults to {@code clouddataflow-readonly:samples.weather_stations } - * and can be overridden with {@code --input}. - */ -public class MaxPerKeyExamples { - // Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod. - private static final String WEATHER_SAMPLES_TABLE = - "clouddataflow-readonly:samples.weather_stations"; - - /** - * Examines each row (weather reading) in the input table. Output the month of the reading, - * and the mean_temp. - */ - static class ExtractTempFn extends DoFn> { - @Override - public void processElement(ProcessContext c) { - TableRow row = c.element(); - Integer month = Integer.parseInt((String) row.get("month")); - Double meanTemp = Double.parseDouble(row.get("mean_temp").toString()); - c.output(KV.of(month, meanTemp)); - } - } - - /** - * Format the results to a TableRow, to save to BigQuery. - * - */ - static class FormatMaxesFn extends DoFn, TableRow> { - @Override - public void processElement(ProcessContext c) { - TableRow row = new TableRow() - .set("month", c.element().getKey()) - .set("max_mean_temp", c.element().getValue()); - c.output(row); - } - } - - /** - * Reads rows from a weather data table, and finds the max mean_temp for each - * month via the 'Max' statistical combination function. - */ - static class MaxMeanTemp - extends PTransform, PCollection> { - @Override - public PCollection apply(PCollection rows) { - - // row... => ... - PCollection> temps = rows.apply( - ParDo.of(new ExtractTempFn())); - - // month, mean_temp... => ... - PCollection> tempMaxes = - temps.apply(Max.doublesPerKey()); - - // ... => row... - PCollection results = tempMaxes.apply( - ParDo.of(new FormatMaxesFn())); - - return results; - } - } - - /** - * Options supported by {@link MaxPerKeyExamples}. - * - *

              Inherits standard configuration options. - */ - private interface Options extends PipelineOptions { - @Description("Table to read from, specified as " - + ":.") - @Default.String(WEATHER_SAMPLES_TABLE) - String getInput(); - void setInput(String value); - - @Description("Table to write to, specified as " - + ":.") - @Validation.Required - String getOutput(); - void setOutput(String value); - } - - public static void main(String[] args) - throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline p = Pipeline.create(options); - - // Build the table schema for the output table. - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("month").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("max_mean_temp").setType("FLOAT")); - TableSchema schema = new TableSchema().setFields(fields); - - p.apply(BigQueryIO.Read.from(options.getInput())) - .apply(new MaxMeanTemp()) - .apply(BigQueryIO.Write - .to(options.getOutput()) - .withSchema(schema) - .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)); - - p.run(); - } -} diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/README.md b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/README.md deleted file mode 100644 index 99f3080a06..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/README.md +++ /dev/null @@ -1,55 +0,0 @@ - -# "Cookbook" Examples - -This directory holds simple "cookbook" examples, which show how to define -commonly-used data analysis patterns that you would likely incorporate into a -larger Dataflow pipeline. They include: - -

                -
              • BigQueryTornadoes - — An example that reads the public samples of weather data from Google - BigQuery, counts the number of tornadoes that occur in each month, and - writes the results to BigQuery. Demonstrates reading/writing BigQuery, - counting a PCollection, and user-defined PTransforms.
              • -
              • CombinePerKeyExamples - — An example that reads the public "Shakespeare" data, and for - each word in the dataset that exceeds a given length, generates a string - containing the list of play names in which that word appears. - Demonstrates the Combine.perKey - transform, which lets you combine the values in a key-grouped - PCollection. -
              • -
              • DatastoreWordCount - — An example that shows you how to read from Google Cloud Datastore.
              • -
              • DeDupExample - — An example that uses Shakespeare's plays as plain text files, and - removes duplicate lines across all the files. Demonstrates the - RemoveDuplicates, TextIO.Read, - and TextIO.Write transforms, and how to wire transforms together. -
              • -
              • FilterExamples - — An example that shows different approaches to filtering, including - selection and projection. It also shows how to dynamically set parameters - by defining and using new pipeline options, and use how to use a value derived - by a pipeline. Demonstrates the Mean transform, - Options configuration, and using pipeline-derived data as a side - input. -
              • -
              • JoinExamples - — An example that shows how to join two collections. It uses a - sample of the GDELT "world event" - data, joining the event action country code against a table - that maps country codes to country names. Demonstrates the Join - operation, and using multiple input sources. -
              • -
              • MaxPerKeyExamples - — An example that reads the public samples of weather data from BigQuery, - and finds the maximum temperature (mean_temp) for each month. - Demonstrates the Max statistical combination transform, and how to - find the max-per-key group. -
              • -
              - -See the [documentation](https://cloud.google.com/dataflow/getting-started) and the [Examples -README](../../../../../../../../../README.md) for -information about how to run these examples. diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java b/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java deleted file mode 100644 index b40d2b6f6e..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/examples/cookbook/TriggerExample.java +++ /dev/null @@ -1,564 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.examples.common.DataflowExampleOptions; -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions; -import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicOptions; -import com.google.cloud.dataflow.examples.common.PubsubFileInjector; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.IntraBundleParallelization; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterEach; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Repeatedly; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; - -import org.joda.time.Duration; -import org.joda.time.Instant; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** - * This example illustrates the basic concepts behind triggering. It shows how to use different - * trigger definitions to produce partial (speculative) results before all the data is processed and - * to control when updated results are produced for late data. The example performs a streaming - * analysis of the data coming in from PubSub and writes the results to BigQuery. It divides the - * data into {@link Window windows} to be processed, and demonstrates using various kinds of {@link - * Trigger triggers} to control when the results for each window are emitted. - * - *

              This example uses a portion of real traffic data from San Diego freeways. It contains - * readings from sensor stations set up along each freeway. Each sensor reading includes a - * calculation of the 'total flow' across all lanes in that freeway direction. - * - *

              Concepts: - *

              - *   1. The default triggering behavior
              - *   2. Late data with the default trigger
              - *   3. How to get speculative estimates
              - *   4. Combining late data and speculative estimates
              - * 
              - * - *

              Before running this example, it will be useful to familiarize yourself with Dataflow triggers - * and understand the concept of 'late data', - * See: - * https://cloud.google.com/dataflow/model/triggers and - * - * https://cloud.google.com/dataflow/model/windowing#Advanced - * - *

              The example pipeline reads data from a Pub/Sub topic. By default, running the example will - * also run an auxiliary pipeline to inject data from the default {@code --input} file to the - * {@code --pubsubTopic}. The auxiliary pipeline puts a timestamp on the injected data so that the - * example pipeline can operate on event time (rather than arrival time). The auxiliary - * pipeline also randomly simulates late data, by setting the timestamps of some of the data - * elements to be in the past. You may override the default {@code --input} with the file of your - * choosing or set {@code --input=""} which will disable the automatic Pub/Sub injection, and allow - * you to use a separate tool to publish to the given topic. - * - *

              The example is configured to use the default Pub/Sub topic and the default BigQuery table - * from the example common package (there are no defaults for a general Dataflow pipeline). - * You can override them by using the {@code --pubsubTopic}, {@code --bigQueryDataset}, and - * {@code --bigQueryTable} options. If the Pub/Sub topic or the BigQuery table do not exist, - * the example will try to create them. - * - *

              The pipeline outputs its results to a BigQuery table. - * Here are some queries you can use to see interesting results: - * Replace {@code } in the query below with the name of the BigQuery table. - * Replace {@code } in the query below with the window interval. - * - *

              To see the results of the default trigger, - * Note: When you start up your pipeline, you'll initially see results from 'late' data. Wait after - * the window duration, until the first pane of non-late data has been emitted, to see more - * interesting results. - * {@code SELECT * FROM enter_table_name WHERE trigger_type = "default" ORDER BY window DESC} - * - *

              To see the late data i.e. dropped by the default trigger, - * {@code SELECT * FROM WHERE trigger_type = "withAllowedLateness" and - * (timing = "LATE" or timing = "ON_TIME") and freeway = "5" ORDER BY window DESC, processing_time} - * - *

              To see the the difference between accumulation mode and discarding mode, - * {@code SELECT * FROM WHERE (timing = "LATE" or timing = "ON_TIME") AND - * (trigger_type = "withAllowedLateness" or trigger_type = "sequential") and freeway = "5" ORDER BY - * window DESC, processing_time} - * - *

              To see speculative results every minute, - * {@code SELECT * FROM WHERE trigger_type = "speculative" and freeway = "5" - * ORDER BY window DESC, processing_time} - * - *

              To see speculative results every five minutes after the end of the window - * {@code SELECT * FROM WHERE trigger_type = "sequential" and timing != "EARLY" - * and freeway = "5" ORDER BY window DESC, processing_time} - * - *

              To see the first and the last pane for a freeway in a window for all the trigger types, - * {@code SELECT * FROM WHERE (isFirst = true or isLast = true) ORDER BY window} - * - *

              To reduce the number of results for each query we can add additional where clauses. - * For examples, To see the results of the default trigger, - * {@code SELECT * FROM WHERE trigger_type = "default" AND freeway = "5" AND - * window = ""} - * - *

              The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C) - * and then exits. - */ - -public class TriggerExample { - //Numeric value of fixed window duration, in minutes - public static final int WINDOW_DURATION = 30; - // Constants used in triggers. - // Speeding up ONE_MINUTE or FIVE_MINUTES helps you get an early approximation of results. - // ONE_MINUTE is used only with processing time before the end of the window - public static final Duration ONE_MINUTE = Duration.standardMinutes(1); - // FIVE_MINUTES is used only with processing time after the end of the window - public static final Duration FIVE_MINUTES = Duration.standardMinutes(5); - // ONE_DAY is used to specify the amount of lateness allowed for the data elements. - public static final Duration ONE_DAY = Duration.standardDays(1); - - /** - * This transform demonstrates using triggers to control when data is produced for each window - * Consider an example to understand the results generated by each type of trigger. - * The example uses "freeway" as the key. Event time is the timestamp associated with the data - * element and processing time is the time when the data element gets processed in the pipeline. - * For freeway 5, suppose there are 10 elements in the [10:00:00, 10:30:00) window. - * Key (freeway) | Value (total_flow) | event time | processing time - * 5 | 50 | 10:00:03 | 10:00:47 - * 5 | 30 | 10:01:00 | 10:01:03 - * 5 | 30 | 10:02:00 | 11:07:00 - * 5 | 20 | 10:04:10 | 10:05:15 - * 5 | 60 | 10:05:00 | 11:03:00 - * 5 | 20 | 10:05:01 | 11.07:30 - * 5 | 60 | 10:15:00 | 10:27:15 - * 5 | 40 | 10:26:40 | 10:26:43 - * 5 | 60 | 10:27:20 | 10:27:25 - * 5 | 60 | 10:29:00 | 11:11:00 - * - *

              Dataflow tracks a watermark which records up to what point in event time the data is - * complete. For the purposes of the example, we'll assume the watermark is approximately 15m - * behind the current processing time. In practice, the actual value would vary over time based - * on the systems knowledge of the current PubSub delay and contents of the backlog (data - * that has not yet been processed). - * - *

              If the watermark is 15m behind, then the window [10:00:00, 10:30:00) (in event time) would - * close at 10:44:59, when the watermark passes 10:30:00. - */ - static class CalculateTotalFlow - extends PTransform >, PCollectionList> { - private int windowDuration; - - CalculateTotalFlow(int windowDuration) { - this.windowDuration = windowDuration; - } - - @Override - public PCollectionList apply(PCollection> flowInfo) { - - // Concept #1: The default triggering behavior - // By default Dataflow uses a trigger which fires when the watermark has passed the end of the - // window. This would be written {@code Repeatedly.forever(AfterWatermark.pastEndOfWindow())}. - - // The system also defaults to dropping late data -- data which arrives after the watermark - // has passed the event timestamp of the arriving element. This means that the default trigger - // will only fire once. - - // Each pane produced by the default trigger with no allowed lateness will be the first and - // last pane in the window, and will be ON_TIME. - - // The results for the example above with the default trigger and zero allowed lateness - // would be: - // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing - // 5 | 260 | 6 | true | true | ON_TIME - - // At 11:03:00 (processing time) the system watermark may have advanced to 10:54:00. As a - // result, when the data record with event time 10:05:00 arrives at 11:03:00, it is considered - // late, and dropped. - - PCollection defaultTriggerResults = flowInfo - .apply("Default", Window - // The default window duration values work well if you're running the default input - // file. You may want to adjust the window duration otherwise. - .>into(FixedWindows.of(Duration.standardMinutes(windowDuration))) - // The default trigger first emits output when the system's watermark passes the end - // of the window. - .triggering(Repeatedly.forever(AfterWatermark.pastEndOfWindow())) - // Late data is dropped - .withAllowedLateness(Duration.ZERO) - // Discard elements after emitting each pane. - // With no allowed lateness and the specified trigger there will only be a single - // pane, so this doesn't have a noticeable effect. See concept 2 for more details. - .discardingFiredPanes()) - .apply(new TotalFlow("default")); - - // Concept #2: Late data with the default trigger - // This uses the same trigger as concept #1, but allows data that is up to ONE_DAY late. This - // leads to each window staying open for ONE_DAY after the watermark has passed the end of the - // window. Any late data will result in an additional pane being fired for that same window. - - // The first pane produced will be ON_TIME and the remaining panes will be LATE. - // To definitely get the last pane when the window closes, use - // .withAllowedLateness(ONE_DAY, ClosingBehavior.FIRE_ALWAYS). - - // The results for the example above with the default trigger and ONE_DAY allowed lateness - // would be: - // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing - // 5 | 260 | 6 | true | false | ON_TIME - // 5 | 60 | 1 | false | false | LATE - // 5 | 30 | 1 | false | false | LATE - // 5 | 20 | 1 | false | false | LATE - // 5 | 60 | 1 | false | false | LATE - PCollection withAllowedLatenessResults = flowInfo - .apply("WithLateData", Window - .>into(FixedWindows.of(Duration.standardMinutes(windowDuration))) - // Late data is emitted as it arrives - .triggering(Repeatedly.forever(AfterWatermark.pastEndOfWindow())) - // Once the output is produced, the pane is dropped and we start preparing the next - // pane for the window - .discardingFiredPanes() - // Late data is handled up to one day - .withAllowedLateness(ONE_DAY)) - .apply(new TotalFlow("withAllowedLateness")); - - // Concept #3: How to get speculative estimates - // We can specify a trigger that fires independent of the watermark, for instance after - // ONE_MINUTE of processing time. This allows us to produce speculative estimates before - // all the data is available. Since we don't have any triggers that depend on the watermark - // we don't get an ON_TIME firing. Instead, all panes are either EARLY or LATE. - - // We also use accumulatingFiredPanes to build up the results across each pane firing. - - // The results for the example above for this trigger would be: - // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing - // 5 | 80 | 2 | true | false | EARLY - // 5 | 100 | 3 | false | false | EARLY - // 5 | 260 | 6 | false | false | EARLY - // 5 | 320 | 7 | false | false | LATE - // 5 | 370 | 9 | false | false | LATE - // 5 | 430 | 10 | false | false | LATE - PCollection speculativeResults = flowInfo - .apply("Speculative" , Window - .>into(FixedWindows.of(Duration.standardMinutes(windowDuration))) - // Trigger fires every minute. - .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() - // Speculative every ONE_MINUTE - .plusDelayOf(ONE_MINUTE))) - // After emitting each pane, it will continue accumulating the elements so that each - // approximation includes all of the previous data in addition to the newly arrived - // data. - .accumulatingFiredPanes() - .withAllowedLateness(ONE_DAY)) - .apply(new TotalFlow("speculative")); - - // Concept #4: Combining late data and speculative estimates - // We can put the previous concepts together to get EARLY estimates, an ON_TIME result, - // and LATE updates based on late data. - - // Each time a triggering condition is satisfied it advances to the next trigger. - // If there are new elements this trigger emits a window under following condition: - // > Early approximations every minute till the end of the window. - // > An on-time firing when the watermark has passed the end of the window - // > Every five minutes of late data. - - // Every pane produced will either be EARLY, ON_TIME or LATE. - - // The results for the example above for this trigger would be: - // Key (freeway) | Value (total_flow) | number_of_records | isFirst | isLast | timing - // 5 | 80 | 2 | true | false | EARLY - // 5 | 100 | 3 | false | false | EARLY - // 5 | 260 | 6 | false | false | EARLY - // [First pane fired after the end of the window] - // 5 | 320 | 7 | false | false | ON_TIME - // 5 | 430 | 10 | false | false | LATE - - // For more possibilities of how to build advanced triggers, see {@link Trigger}. - PCollection sequentialResults = flowInfo - .apply("Sequential", Window - .>into(FixedWindows.of(Duration.standardMinutes(windowDuration))) - .triggering(AfterEach.inOrder( - Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() - // Speculative every ONE_MINUTE - .plusDelayOf(ONE_MINUTE)).orFinally(AfterWatermark.pastEndOfWindow()), - Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() - // Late data every FIVE_MINUTES - .plusDelayOf(FIVE_MINUTES)))) - .accumulatingFiredPanes() - // For up to ONE_DAY - .withAllowedLateness(ONE_DAY)) - .apply(new TotalFlow("sequential")); - - // Adds the results generated by each trigger type to a PCollectionList. - PCollectionList resultsList = PCollectionList.of(defaultTriggerResults) - .and(withAllowedLatenessResults) - .and(speculativeResults) - .and(sequentialResults); - - return resultsList; - } - } - - ////////////////////////////////////////////////////////////////////////////////////////////////// - // The remaining parts of the pipeline are needed to produce the output for each - // concept above. Not directly relevant to understanding the trigger examples. - - /** - * Calculate total flow and number of records for each freeway and format the results to TableRow - * objects, to save to BigQuery. - */ - static class TotalFlow extends - PTransform >, PCollection> { - private String triggerType; - - public TotalFlow(String triggerType) { - this.triggerType = triggerType; - } - - @Override - public PCollection apply(PCollection> flowInfo) { - PCollection>> flowPerFreeway = flowInfo - .apply(GroupByKey.create()); - - PCollection> results = flowPerFreeway.apply(ParDo.of( - new DoFn >, KV>() { - - @Override - public void processElement(ProcessContext c) throws Exception { - Iterable flows = c.element().getValue(); - Integer sum = 0; - Long numberOfRecords = 0L; - for (Integer value : flows) { - sum += value; - numberOfRecords++; - } - c.output(KV.of(c.element().getKey(), sum + "," + numberOfRecords)); - } - })); - PCollection output = results.apply(ParDo.of(new FormatTotalFlow(triggerType))); - return output; - } - } - - /** - * Format the results of the Total flow calculation to a TableRow, to save to BigQuery. - * Adds the triggerType, pane information, processing time and the window timestamp. - * */ - static class FormatTotalFlow extends DoFn, TableRow> - implements RequiresWindowAccess { - private String triggerType; - - public FormatTotalFlow(String triggerType) { - this.triggerType = triggerType; - } - @Override - public void processElement(ProcessContext c) throws Exception { - String[] values = c.element().getValue().split(","); - TableRow row = new TableRow() - .set("trigger_type", triggerType) - .set("freeway", c.element().getKey()) - .set("total_flow", Integer.parseInt(values[0])) - .set("number_of_records", Long.parseLong(values[1])) - .set("window", c.window().toString()) - .set("isFirst", c.pane().isFirst()) - .set("isLast", c.pane().isLast()) - .set("timing", c.pane().getTiming().toString()) - .set("event_time", c.timestamp().toString()) - .set("processing_time", Instant.now().toString()); - c.output(row); - } - } - - /** - * Extract the freeway and total flow in a reading. - * Freeway is used as key since we are calculating the total flow for each freeway. - */ - static class ExtractFlowInfo extends DoFn> { - @Override - public void processElement(ProcessContext c) throws Exception { - String[] laneInfo = c.element().split(","); - if (laneInfo[0].equals("timestamp")) { - // Header row - return; - } - if (laneInfo.length < 48) { - //Skip the invalid input. - return; - } - String freeway = laneInfo[2]; - Integer totalFlow = tryIntegerParse(laneInfo[7]); - // Ignore the records with total flow 0 to easily understand the working of triggers. - // Skip the records with total flow -1 since they are invalid input. - if (totalFlow == null || totalFlow <= 0) { - return; - } - c.output(KV.of(freeway, totalFlow)); - } - } - - /** - * Inherits standard configuration options. - */ - public interface TrafficFlowOptions - extends ExamplePubsubTopicOptions, ExampleBigQueryTableOptions, DataflowExampleOptions { - - @Description("Input file to inject to Pub/Sub topic") - @Default.String("gs://dataflow-samples/traffic_sensor/" - + "Freeways-5Minaa2010-01-01_to_2010-02-15.csv") - String getInput(); - void setInput(String value); - - @Description("Numeric value of window duration for fixed windows, in minutes") - @Default.Integer(WINDOW_DURATION) - Integer getWindowDuration(); - void setWindowDuration(Integer value); - } - - private static final String PUBSUB_TIMESTAMP_LABEL_KEY = "timestamp_ms"; - - public static void main(String[] args) throws Exception { - TrafficFlowOptions options = PipelineOptionsFactory.fromArgs(args) - .withValidation() - .as(TrafficFlowOptions.class); - options.setStreaming(true); - - // In order to cancel the pipelines automatically, - // {@code DataflowPipelineRunner} is forced to be used. - options.setRunner(DataflowPipelineRunner.class); - options.setBigQuerySchema(getSchema()); - - DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options); - dataflowUtils.setup(); - - Pipeline pipeline = Pipeline.create(options); - - TableReference tableRef = getTableReference(options.getProject(), - options.getBigQueryDataset(), options.getBigQueryTable()); - - PCollectionList resultList = pipeline.apply(PubsubIO.Read.named("ReadPubsubInput") - .timestampLabel(PUBSUB_TIMESTAMP_LABEL_KEY) - .topic(options.getPubsubTopic())) - .apply(ParDo.of(new ExtractFlowInfo())) - .apply(new CalculateTotalFlow(options.getWindowDuration())); - - for (int i = 0; i < resultList.size(); i++){ - resultList.get(i).apply(BigQueryIO.Write.to(tableRef).withSchema(getSchema())); - } - - PipelineResult result = pipeline.run(); - if (!options.getInput().isEmpty()){ - //Inject the data into the pubsub topic - dataflowUtils.runInjectorPipeline(runInjector(options)); - } - // dataflowUtils will try to cancel the pipeline and the injector before the program exits. - dataflowUtils.waitToFinish(result); - } - - private static Pipeline runInjector(TrafficFlowOptions options){ - DataflowPipelineOptions copiedOptions = options.cloneAs(DataflowPipelineOptions.class); - copiedOptions.setStreaming(false); - copiedOptions.setNumWorkers(options.as(DataflowExampleOptions.class).getInjectorNumWorkers()); - copiedOptions.setJobName(options.getJobName() + "-injector"); - Pipeline injectorPipeline = Pipeline.create(copiedOptions); - injectorPipeline - .apply(TextIO.Read.named("ReadMyFile").from(options.getInput())) - .apply(ParDo.named("InsertRandomDelays").of(new InsertDelays())) - .apply(IntraBundleParallelization.of(PubsubFileInjector - .withTimestampLabelKey(PUBSUB_TIMESTAMP_LABEL_KEY) - .publish(options.getPubsubTopic())) - .withMaxParallelism(20)); - - return injectorPipeline; - } - - /** - * Add current time to each record. - * Also insert a delay at random to demo the triggers. - */ - public static class InsertDelays extends DoFn { - private static final double THRESHOLD = 0.001; - // MIN_DELAY and MAX_DELAY in minutes. - private static final int MIN_DELAY = 1; - private static final int MAX_DELAY = 100; - - @Override - public void processElement(ProcessContext c) throws Exception { - Instant timestamp = Instant.now(); - if (Math.random() < THRESHOLD){ - int range = MAX_DELAY - MIN_DELAY; - int delayInMinutes = (int) (Math.random() * range) + MIN_DELAY; - long delayInMillis = TimeUnit.MINUTES.toMillis(delayInMinutes); - timestamp = new Instant(timestamp.getMillis() - delayInMillis); - } - c.outputWithTimestamp(c.element(), timestamp); - } - } - - - /**Sets the table reference. **/ - private static TableReference getTableReference(String project, String dataset, String table){ - TableReference tableRef = new TableReference(); - tableRef.setProjectId(project); - tableRef.setDatasetId(dataset); - tableRef.setTableId(table); - return tableRef; - } - - /** Defines the BigQuery schema used for the output. */ - private static TableSchema getSchema() { - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("trigger_type").setType("STRING")); - fields.add(new TableFieldSchema().setName("freeway").setType("STRING")); - fields.add(new TableFieldSchema().setName("total_flow").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("number_of_records").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("window").setType("STRING")); - fields.add(new TableFieldSchema().setName("isFirst").setType("BOOLEAN")); - fields.add(new TableFieldSchema().setName("isLast").setType("BOOLEAN")); - fields.add(new TableFieldSchema().setName("timing").setType("STRING")); - fields.add(new TableFieldSchema().setName("event_time").setType("TIMESTAMP")); - fields.add(new TableFieldSchema().setName("processing_time").setType("TIMESTAMP")); - TableSchema schema = new TableSchema().setFields(fields); - return schema; - } - - private static Integer tryIntegerParse(String number) { - try { - return Integer.parseInt(number); - } catch (NumberFormatException e) { - return null; - } - } -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8.java deleted file mode 100644 index c115ea0a33..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Filter; -import com.google.cloud.dataflow.sdk.transforms.FlatMapElements; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import java.util.Arrays; - -/** - * An example that counts words in Shakespeare, using Java 8 language features. - * - *

              See {@link MinimalWordCount} for a comprehensive explanation. - */ -public class MinimalWordCountJava8 { - - public static void main(String[] args) { - DataflowPipelineOptions options = PipelineOptionsFactory.create() - .as(DataflowPipelineOptions.class); - - options.setRunner(BlockingDataflowPipelineRunner.class); - - // CHANGE 1 of 3: Your project ID is required in order to run your pipeline on the Google Cloud. - options.setProject("SET_YOUR_PROJECT_ID_HERE"); - - // CHANGE 2 of 3: Your Google Cloud Storage path is required for staging local files. - options.setStagingLocation("gs://SET_YOUR_BUCKET_NAME_HERE/AND_STAGING_DIRECTORY"); - - Pipeline p = Pipeline.create(options); - - p.apply(TextIO.Read.from("gs://dataflow-samples/shakespeare/*")) - .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) - .withOutputType(new TypeDescriptor() {})) - .apply(Filter.byPredicate((String word) -> !word.isEmpty())) - .apply(Count.perElement()) - .apply(MapElements - .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue()) - .withOutputType(new TypeDescriptor() {})) - - // CHANGE 3 of 3: The Google Cloud Storage path is required for outputting the results to. - .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); - - p.run(); - } -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java deleted file mode 100644 index 63b875af02..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/GameStats.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.complete.game.utils.WriteWindowedToBigQuery; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Combine; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.Mean; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.transforms.View; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.OutputTimeFns; -import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionView; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.joda.time.DateTimeZone; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - -/** - * This class is the fourth in a series of four pipelines that tell a story in a 'gaming' - * domain, following {@link UserScore}, {@link HourlyTeamScore}, and {@link LeaderBoard}. - * New concepts: session windows and finding session duration; use of both - * singleton and non-singleton side inputs. - * - *

              This pipeline builds on the {@link LeaderBoard} functionality, and adds some "business - * intelligence" analysis: abuse detection and usage patterns. The pipeline derives the Mean user - * score sum for a window, and uses that information to identify likely spammers/robots. (The robots - * have a higher click rate than the human users). The 'robot' users are then filtered out when - * calculating the team scores. - * - *

              Additionally, user sessions are tracked: that is, we find bursts of user activity using - * session windows. Then, the mean session duration information is recorded in the context of - * subsequent fixed windowing. (This could be used to tell us what games are giving us greater - * user retention). - * - *

              Run {@link injector.Injector} to generate pubsub data for this pipeline. The Injector - * documentation provides more detail. - * - *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration - * like this: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - *   --dataset=YOUR-DATASET
              - *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              - * }
              - * 
              - * where the BigQuery dataset you specify must already exist. The PubSub topic you specify should - * be the same topic to which the Injector is publishing. - */ -public class GameStats extends LeaderBoard { - - private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; - private static final Logger LOG = LoggerFactory.getLogger(GameStats.class); - - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); - static final Duration FIVE_MINUTES = Duration.standardMinutes(5); - static final Duration TEN_MINUTES = Duration.standardMinutes(10); - - - /** - * Filter out all but those users with a high clickrate, which we will consider as 'spammy' uesrs. - * We do this by finding the mean total score per user, then using that information as a side - * input to filter out all but those user scores that are > (mean * SCORE_WEIGHT) - */ - // [START DocInclude_AbuseDetect] - public static class CalculateSpammyUsers - extends PTransform>, PCollection>> { - private static final Logger LOG = LoggerFactory.getLogger(CalculateSpammyUsers.class); - private static final double SCORE_WEIGHT = 2.5; - - @Override - public PCollection> apply(PCollection> userScores) { - - // Get the sum of scores for each user. - PCollection> sumScores = userScores - .apply("UserSum", Sum.integersPerKey()); - - // Extract the score from each element, and use it to find the global mean. - final PCollectionView globalMeanScore = sumScores.apply(Values.create()) - .apply(Mean.globally().asSingletonView()); - - // Filter the user sums using the global mean. - PCollection> filtered = sumScores - .apply(ParDo - .named("ProcessAndFilter") - // use the derived mean total score as a side input - .withSideInputs(globalMeanScore) - .of(new DoFn, KV>() { - private final Aggregator numSpammerUsers = - createAggregator("SpammerUsers", new Sum.SumLongFn()); - @Override - public void processElement(ProcessContext c) { - Integer score = c.element().getValue(); - Double gmc = c.sideInput(globalMeanScore); - if (score > (gmc * SCORE_WEIGHT)) { - LOG.info("user " + c.element().getKey() + " spammer score " + score - + " with mean " + gmc); - numSpammerUsers.addValue(1L); - c.output(c.element()); - } - } - })); - return filtered; - } - } - // [END DocInclude_AbuseDetect] - - /** - * Calculate and output an element's session duration. - */ - private static class UserSessionInfoFn extends DoFn, Integer> - implements RequiresWindowAccess { - - @Override - public void processElement(ProcessContext c) { - IntervalWindow w = (IntervalWindow) c.window(); - int duration = new Duration( - w.start(), w.end()).toPeriod().toStandardMinutes().getMinutes(); - c.output(duration); - } - } - - - /** - * Options supported by {@link GameStats}. - */ - interface Options extends LeaderBoard.Options { - @Description("Pub/Sub topic to read from") - @Validation.Required - String getTopic(); - void setTopic(String value); - - @Description("Numeric value of fixed window duration for user analysis, in minutes") - @Default.Integer(60) - Integer getFixedWindowDuration(); - void setFixedWindowDuration(Integer value); - - @Description("Numeric value of gap between user sessions, in minutes") - @Default.Integer(5) - Integer getSessionGap(); - void setSessionGap(Integer value); - - @Description("Numeric value of fixed window for finding mean of user session duration, " - + "in minutes") - @Default.Integer(30) - Integer getUserActivityWindowDuration(); - void setUserActivityWindowDuration(Integer value); - - @Description("Prefix used for the BigQuery table names") - @Default.String("game_stats") - String getTablePrefix(); - void setTablePrefix(String value); - } - - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write information about team score sums. - */ - protected static Map>> - configureWindowedWrite() { - Map>> tableConfigure = - new HashMap>>(); - tableConfigure.put("team", - new WriteWindowedToBigQuery.FieldInfo>("STRING", - c -> c.element().getKey())); - tableConfigure.put("total_score", - new WriteWindowedToBigQuery.FieldInfo>("INTEGER", - c -> c.element().getValue())); - tableConfigure.put("window_start", - new WriteWindowedToBigQuery.FieldInfo>("STRING", - c -> { - IntervalWindow w = (IntervalWindow) c.window(); - return fmt.print(w.start()); - })); - tableConfigure.put("processing_time", - new WriteWindowedToBigQuery.FieldInfo>( - "STRING", c -> fmt.print(Instant.now()))); - return tableConfigure; - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write information about mean user session time. - */ - protected static Map> - configureSessionWindowWrite() { - - Map> tableConfigure = - new HashMap>(); - tableConfigure.put("window_start", - new WriteWindowedToBigQuery.FieldInfo("STRING", - c -> { - IntervalWindow w = (IntervalWindow) c.window(); - return fmt.print(w.start()); - })); - tableConfigure.put("mean_duration", - new WriteWindowedToBigQuery.FieldInfo("FLOAT", c -> c.element())); - return tableConfigure; - } - - - - public static void main(String[] args) throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - // Enforce that this pipeline is always run in streaming mode. - options.setStreaming(true); - // Allow the pipeline to be cancelled automatically. - options.setRunner(DataflowPipelineRunner.class); - DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options); - Pipeline pipeline = Pipeline.create(options); - - // Read Events from Pub/Sub using custom timestamps - PCollection rawEvents = pipeline - .apply(PubsubIO.Read.timestampLabel(TIMESTAMP_ATTRIBUTE).topic(options.getTopic())) - .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())); - - // Extract username/score pairs from the event stream - PCollection> userEvents = - rawEvents.apply("ExtractUserScore", - MapElements.via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) - .withOutputType(new TypeDescriptor>() {})); - - // Calculate the total score per user over fixed windows, and - // cumulative updates for late data. - final PCollectionView> spammersView = userEvents - .apply(Window.named("FixedWindowsUser") - .>into(FixedWindows.of( - Duration.standardMinutes(options.getFixedWindowDuration()))) - ) - - // Filter out everyone but those with (SCORE_WEIGHT * avg) clickrate. - // These might be robots/spammers. - .apply("CalculateSpammyUsers", new CalculateSpammyUsers()) - // Derive a view from the collection of spammer users. It will be used as a side input - // in calculating the team score sums, below. - .apply("CreateSpammersView", View.asMap()); - - // [START DocInclude_FilterAndCalc] - // Calculate the total score per team over fixed windows, - // and emit cumulative updates for late data. Uses the side input derived above-- the set of - // suspected robots-- to filter out scores from those users from the sum. - // Write the results to BigQuery. - rawEvents - .apply(Window.named("WindowIntoFixedWindows") - .into(FixedWindows.of( - Duration.standardMinutes(options.getFixedWindowDuration()))) - ) - // Filter out the detected spammer users, using the side input derived above. - .apply(ParDo.named("FilterOutSpammers") - .withSideInputs(spammersView) - .of(new DoFn() { - @Override - public void processElement(ProcessContext c) { - // If the user is not in the spammers Map, output the data element. - if (c.sideInput(spammersView).get(c.element().getUser().trim()) == null) { - c.output(c.element()); - } - }})) - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")) - // [END DocInclude_FilterAndCalc] - // Write the result to BigQuery - .apply("WriteTeamSums", - new WriteWindowedToBigQuery>( - options.getTablePrefix() + "_team", configureWindowedWrite())); - - - // [START DocInclude_SessionCalc] - // Detect user sessions-- that is, a burst of activity separated by a gap from further - // activity. Find and record the mean session lengths. - // This information could help the game designers track the changing user engagement - // as their set of games changes. - userEvents - .apply(Window.named("WindowIntoSessions") - .>into( - Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap()))) - .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow())) - // For this use, we care only about the existence of the session, not any particular - // information aggregated over it, so the following is an efficient way to do that. - .apply(Combine.perKey(x -> 0)) - // Get the duration per session. - .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn())) - // [END DocInclude_SessionCalc] - // [START DocInclude_Rewindow] - // Re-window to process groups of session sums according to when the sessions complete. - .apply(Window.named("WindowToExtractSessionMean") - .into( - FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration())))) - // Find the mean session duration in each window. - .apply(Mean.globally().withoutDefaults()) - // Write this info to a BigQuery table. - .apply("WriteAvgSessionLength", - new WriteWindowedToBigQuery( - options.getTablePrefix() + "_sessions", configureSessionWindowWrite())); - // [END DocInclude_Rewindow] - - - // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the - // command line. - PipelineResult result = pipeline.run(); - dataflowUtils.waitToFinish(result); - } -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java deleted file mode 100644 index 82904c2f18..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScore.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import com.google.cloud.dataflow.examples.complete.game.utils.WriteWindowedToBigQuery; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Filter; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.WithTimestamps; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.joda.time.DateTimeZone; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - -/** - * This class is the second in a series of four pipelines that tell a story in a 'gaming' - * domain, following {@link UserScore}. In addition to the concepts introduced in {@link UserScore}, - * new concepts include: windowing and element timestamps; use of {@code Filter.byPredicate()}. - * - *

              This pipeline processes data collected from gaming events in batch, building on {@link - * UserScore} but using fixed windows. It calculates the sum of scores per team, for each window, - * optionally allowing specification of two timestamps before and after which data is filtered out. - * This allows a model where late data collected after the intended analysis window can be included, - * and any late-arriving data prior to the beginning of the analysis window can be removed as well. - * By using windowing and adding element timestamps, we can do finer-grained analysis than with the - * {@link UserScore} pipeline. However, our batch processing is high-latency, in that we don't get - * results from plays at the beginning of the batch's time period until the batch is processed. - * - *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration - * like this: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - *   --dataset=YOUR-DATASET
              - * }
              - * 
              - * where the BigQuery dataset you specify must already exist. - * - *

              Optionally include {@code --input} to specify the batch input file path. - * To indicate a time after which the data should be filtered out, include the - * {@code --stopMin} arg. E.g., {@code --stopMin=2015-10-18-23-59} indicates that any data - * timestamped after 23:59 PST on 2015-10-18 should not be included in the analysis. - * To indicate a time before which data should be filtered out, include the {@code --startMin} arg. - * If you're using the default input specified in {@link UserScore}, - * "gs://dataflow-samples/game/gaming_data*.csv", then - * {@code --startMin=2015-11-16-16-10 --stopMin=2015-11-17-16-10} are good values. - */ -public class HourlyTeamScore extends UserScore { - - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); - private static DateTimeFormatter minFmt = - DateTimeFormat.forPattern("yyyy-MM-dd-HH-mm") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); - - - /** - * Options supported by {@link HourlyTeamScore}. - */ - interface Options extends UserScore.Options { - - @Description("Numeric value of fixed window duration, in minutes") - @Default.Integer(60) - Integer getWindowDuration(); - void setWindowDuration(Integer value); - - @Description("String representation of the first minute after which to generate results," - + "in the format: yyyy-MM-dd-HH-mm . This time should be in PST." - + "Any input data timestamped prior to that minute won't be included in the sums.") - @Default.String("1970-01-01-00-00") - String getStartMin(); - void setStartMin(String value); - - @Description("String representation of the first minute for which to not generate results," - + "in the format: yyyy-MM-dd-HH-mm . This time should be in PST." - + "Any input data timestamped after that minute won't be included in the sums.") - @Default.String("2100-01-01-00-00") - String getStopMin(); - void setStopMin(String value); - - @Description("The BigQuery table name. Should not already exist.") - @Default.String("hourly_team_score") - String getTableName(); - void setTableName(String value); - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is passed to the {@link WriteWindowedToBigQuery} constructor to write team score sums and - * includes information about window start time. - */ - protected static Map>> - configureWindowedTableWrite() { - Map>> tableConfig = - new HashMap>>(); - tableConfig.put("team", - new WriteWindowedToBigQuery.FieldInfo>("STRING", - c -> c.element().getKey())); - tableConfig.put("total_score", - new WriteWindowedToBigQuery.FieldInfo>("INTEGER", - c -> c.element().getValue())); - tableConfig.put("window_start", - new WriteWindowedToBigQuery.FieldInfo>("STRING", - c -> { - IntervalWindow w = (IntervalWindow) c.window(); - return fmt.print(w.start()); - })); - return tableConfig; - } - - - /** - * Run a batch pipeline to do windowed analysis of the data. - */ - // [START DocInclude_HTSMain] - public static void main(String[] args) throws Exception { - // Begin constructing a pipeline configured by commandline flags. - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline pipeline = Pipeline.create(options); - - final Instant stopMinTimestamp = new Instant(minFmt.parseMillis(options.getStopMin())); - final Instant startMinTimestamp = new Instant(minFmt.parseMillis(options.getStartMin())); - - // Read 'gaming' events from a text file. - pipeline.apply(TextIO.Read.from(options.getInput())) - // Parse the incoming data. - .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())) - - // Filter out data before and after the given times so that it is not included - // in the calculations. As we collect data in batches (say, by day), the batch for the day - // that we want to analyze could potentially include some late-arriving data from the previous - // day. If so, we want to weed it out. Similarly, if we include data from the following day - // (to scoop up late-arriving events from the day we're analyzing), we need to weed out events - // that fall after the time period we want to analyze. - // [START DocInclude_HTSFilters] - .apply("FilterStartTime", Filter.byPredicate( - (GameActionInfo gInfo) - -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) - .apply("FilterEndTime", Filter.byPredicate( - (GameActionInfo gInfo) - -> gInfo.getTimestamp() < stopMinTimestamp.getMillis())) - // [END DocInclude_HTSFilters] - - // [START DocInclude_HTSAddTsAndWindow] - // Add an element timestamp based on the event log, and apply fixed windowing. - .apply("AddEventTimestamps", - WithTimestamps.of((GameActionInfo i) -> new Instant(i.getTimestamp()))) - .apply(Window.named("FixedWindowsTeam") - .into(FixedWindows.of( - Duration.standardMinutes(options.getWindowDuration())))) - // [END DocInclude_HTSAddTsAndWindow] - - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")) - .apply("WriteTeamScoreSums", - new WriteWindowedToBigQuery>(options.getTableName(), - configureWindowedTableWrite())); - - - pipeline.run(); - } - // [END DocInclude_HTSMain] - -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java deleted file mode 100644 index ae1491d136..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoard.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import com.google.cloud.dataflow.examples.common.DataflowExampleOptions; -import com.google.cloud.dataflow.examples.common.DataflowExampleUtils; -import com.google.cloud.dataflow.examples.complete.game.utils.WriteToBigQuery; -import com.google.cloud.dataflow.examples.complete.game.utils.WriteWindowedToBigQuery; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterProcessingTime; -import com.google.cloud.dataflow.sdk.transforms.windowing.AfterWatermark; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.Repeatedly; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.common.annotations.VisibleForTesting; -import org.joda.time.DateTimeZone; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - - -/** - * This class is the third in a series of four pipelines that tell a story in a 'gaming' domain, - * following {@link UserScore} and {@link HourlyTeamScore}. Concepts include: processing unbounded - * data using fixed windows; use of custom timestamps and event-time processing; generation of - * early/speculative results; using .accumulatingFiredPanes() to do cumulative processing of late- - * arriving data. - * - *

              This pipeline processes an unbounded stream of 'game events'. The calculation of the team - * scores uses fixed windowing based on event time (the time of the game play event), not - * processing time (the time that an event is processed by the pipeline). The pipeline calculates - * the sum of scores per team, for each window. By default, the team scores are calculated using - * one-hour windows. - * - *

              In contrast-- to demo another windowing option-- the user scores are calculated using a - * global window, which periodically (every ten minutes) emits cumulative user score sums. - * - *

              In contrast to the previous pipelines in the series, which used static, finite input data, - * here we're using an unbounded data source, which lets us provide speculative results, and allows - * handling of late data, at much lower latency. We can use the early/speculative results to keep a - * 'leaderboard' updated in near-realtime. Our handling of late data lets us generate correct - * results, e.g. for 'team prizes'. We're now outputting window results as they're - * calculated, giving us much lower latency than with the previous batch examples. - * - *

              Run {@link injector.Injector} to generate pubsub data for this pipeline. The Injector - * documentation provides more detail on how to do this. - * - *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration - * like this: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - *   --dataset=YOUR-DATASET
              - *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              - * }
              - * 
              - * where the BigQuery dataset you specify must already exist. - * The PubSub topic you specify should be the same topic to which the Injector is publishing. - */ -public class LeaderBoard extends HourlyTeamScore { - - private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; - - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); - static final Duration FIVE_MINUTES = Duration.standardMinutes(5); - static final Duration TEN_MINUTES = Duration.standardMinutes(10); - - - /** - * Options supported by {@link LeaderBoard}. - */ - interface Options extends HourlyTeamScore.Options, DataflowExampleOptions { - - @Description("Pub/Sub topic to read from") - @Validation.Required - String getTopic(); - void setTopic(String value); - - @Description("Numeric value of fixed window duration for team analysis, in minutes") - @Default.Integer(60) - Integer getTeamWindowDuration(); - void setTeamWindowDuration(Integer value); - - @Description("Numeric value of allowed data lateness, in minutes") - @Default.Integer(120) - Integer getAllowedLateness(); - void setAllowedLateness(Integer value); - - @Description("Prefix used for the BigQuery table names") - @Default.String("leaderboard") - String getTableName(); - void setTableName(String value); - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write team score sums and includes event timing information. - */ - protected static Map>> - configureWindowedTableWrite() { - - Map>> tableConfigure = - new HashMap>>(); - tableConfigure.put("team", - new WriteWindowedToBigQuery.FieldInfo>("STRING", - c -> c.element().getKey())); - tableConfigure.put("total_score", - new WriteWindowedToBigQuery.FieldInfo>("INTEGER", - c -> c.element().getValue())); - tableConfigure.put("window_start", - new WriteWindowedToBigQuery.FieldInfo>("STRING", - c -> { - IntervalWindow w = (IntervalWindow) c.window(); - return fmt.print(w.start()); - })); - tableConfigure.put("processing_time", - new WriteWindowedToBigQuery.FieldInfo>( - "STRING", c -> fmt.print(Instant.now()))); - tableConfigure.put("timing", - new WriteWindowedToBigQuery.FieldInfo>( - "STRING", c -> c.pane().getTiming().toString())); - return tableConfigure; - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write user score sums. - */ - protected static Map>> - configureGlobalWindowBigQueryWrite() { - - Map>> tableConfigure = - configureBigQueryWrite(); - tableConfigure.put("processing_time", - new WriteToBigQuery.FieldInfo>( - "STRING", c -> fmt.print(Instant.now()))); - return tableConfigure; - } - - - public static void main(String[] args) throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - // Enforce that this pipeline is always run in streaming mode. - options.setStreaming(true); - // For example purposes, allow the pipeline to be easily cancelled instead of running - // continuously. - options.setRunner(DataflowPipelineRunner.class); - DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options); - Pipeline pipeline = Pipeline.create(options); - - // Read game events from Pub/Sub using custom timestamps, which are extracted from the pubsub - // data elements, and parse the data. - PCollection gameEvents = pipeline - .apply(PubsubIO.Read.timestampLabel(TIMESTAMP_ATTRIBUTE).topic(options.getTopic())) - .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())); - - gameEvents.apply("CalculateTeamScores", - new CalculateTeamScores( - Duration.standardMinutes(options.getTeamWindowDuration()), - Duration.standardMinutes(options.getAllowedLateness()))) - // Write the results to BigQuery. - .apply("WriteTeamScoreSums", - new WriteWindowedToBigQuery>( - options.getTableName() + "_team", configureWindowedTableWrite())); - gameEvents - .apply( - "CalculateUserScores", - new CalculateUserScores(Duration.standardMinutes(options.getAllowedLateness()))) - // Write the results to BigQuery. - .apply( - "WriteUserScoreSums", - new WriteToBigQuery>( - options.getTableName() + "_user", configureGlobalWindowBigQueryWrite())); - - // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the - // command line. - PipelineResult result = pipeline.run(); - dataflowUtils.waitToFinish(result); - } - - /** - * Calculates scores for each team within the configured window duration. - */ - // [START DocInclude_WindowAndTrigger] - // Extract team/score pairs from the event stream, using hour-long windows by default. - @VisibleForTesting - static class CalculateTeamScores - extends PTransform, PCollection>> { - private final Duration teamWindowDuration; - private final Duration allowedLateness; - - CalculateTeamScores(Duration teamWindowDuration, Duration allowedLateness) { - this.teamWindowDuration = teamWindowDuration; - this.allowedLateness = allowedLateness; - } - - @Override - public PCollection> apply(PCollection infos) { - return infos.apply("LeaderboardTeamFixedWindows", - Window.into(FixedWindows.of(teamWindowDuration)) - // We will get early (speculative) results as well as cumulative - // processing of late data. - .triggering(AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(FIVE_MINUTES)) - .withLateFirings(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(TEN_MINUTES))) - .withAllowedLateness(allowedLateness) - .accumulatingFiredPanes()) - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")); - } - } - // [END DocInclude_WindowAndTrigger] - - // [START DocInclude_ProcTimeTrigger] - /** - * Extract user/score pairs from the event stream using processing time, via global windowing. - * Get periodic updates on all users' running scores. - */ - @VisibleForTesting - static class CalculateUserScores - extends PTransform, PCollection>> { - private final Duration allowedLateness; - - CalculateUserScores(Duration allowedLateness) { - this.allowedLateness = allowedLateness; - } - - @Override - public PCollection> apply(PCollection input) { - return input.apply("LeaderboardUserGlobalWindow", - Window.into(new GlobalWindows()) - // Get periodic results every ten minutes. - .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(TEN_MINUTES))) - .accumulatingFiredPanes() - .withAllowedLateness(allowedLateness)) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")); - } - } - // [END DocInclude_ProcTimeTrigger] -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/README.md b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/README.md deleted file mode 100644 index 4cad16d5f5..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/README.md +++ /dev/null @@ -1,119 +0,0 @@ - -# 'Gaming' examples - - -This directory holds a series of example Dataflow pipelines in a simple 'mobile -gaming' domain. They all require Java 8. Each pipeline successively introduces -new concepts, and gives some examples of using Java 8 syntax in constructing -Dataflow pipelines. Other than usage of Java 8 lambda expressions, the concepts -that are used apply equally well in Java 7. - -In the gaming scenario, many users play, as members of different teams, over -the course of a day, and their actions are logged for processing. Some of the -logged game events may be late-arriving, if users play on mobile devices and go -transiently offline for a period. - -The scenario includes not only "regular" users, but "robot users", which have a -higher click rate than the regular users, and may move from team to team. - -The first two pipelines in the series use pre-generated batch data samples. The -second two pipelines read from a [PubSub](https://cloud.google.com/pubsub/) -topic input. For these examples, you will also need to run the -`injector.Injector` program, which generates and publishes the gaming data to -PubSub. The javadocs for each pipeline have more detailed information on how to -run that pipeline. - -All of these pipelines write their results to BigQuery table(s). - - -## The pipelines in the 'gaming' series - -### UserScore - -The first pipeline in the series is `UserScore`. This pipeline does batch -processing of data collected from gaming events. It calculates the sum of -scores per user, over an entire batch of gaming data (collected, say, for each -day). The batch processing will not include any late data that arrives after -the day's cutoff point. - -### HourlyTeamScore - -The next pipeline in the series is `HourlyTeamScore`. This pipeline also -processes data collected from gaming events in batch. It builds on `UserScore`, -but uses [fixed windows](https://cloud.google.com/dataflow/model/windowing), by -default an hour in duration. It calculates the sum of scores per team, for each -window, optionally allowing specification of two timestamps before and after -which data is filtered out. This allows a model where late data collected after -the intended analysis window can be included in the analysis, and any late- -arriving data prior to the beginning of the analysis window can be removed as -well. - -By using windowing and adding element timestamps, we can do finer-grained -analysis than with the `UserScore` pipeline — we're now tracking scores for -each hour rather than over the course of a whole day. However, our batch -processing is high-latency, in that we don't get results from plays at the -beginning of the batch's time period until the complete batch is processed. - -### LeaderBoard - -The third pipeline in the series is `LeaderBoard`. This pipeline processes an -unbounded stream of 'game events' from a PubSub topic. The calculation of the -team scores uses fixed windowing based on event time (the time of the game play -event), not processing time (the time that an event is processed by the -pipeline). The pipeline calculates the sum of scores per team, for each window. -By default, the team scores are calculated using one-hour windows. - -In contrast — to demo another windowing option — the user scores are calculated -using a global window, which periodically (every ten minutes) emits cumulative -user score sums. - -In contrast to the previous pipelines in the series, which used static, finite -input data, here we're using an unbounded data source, which lets us provide -_speculative_ results, and allows handling of late data, at much lower latency. -E.g., we could use the early/speculative results to keep a 'leaderboard' -updated in near-realtime. Our handling of late data lets us generate correct -results, e.g. for 'team prizes'. We're now outputing window results as they're -calculated, giving us much lower latency than with the previous batch examples. - -### GameStats - -The fourth pipeline in the series is `GameStats`. This pipeline builds -on the `LeaderBoard` functionality — supporting output of speculative and late -data — and adds some "business intelligence" analysis: identifying abuse -detection. The pipeline derives the Mean user score sum for a window, and uses -that information to identify likely spammers/robots. (The injector is designed -so that the "robots" have a higher click rate than the "real" users). The robot -users are then filtered out when calculating the team scores. - -Additionally, user sessions are tracked: that is, we find bursts of user -activity using session windows. Then, the mean session duration information is -recorded in the context of subsequent fixed windowing. (This could be used to -tell us what games are giving us greater user retention). - -### Running the PubSub Injector - -The `LeaderBoard` and `GameStats` example pipelines read unbounded data -from a PubSub topic. - -Use the `injector.Injector` program to generate this data and publish to a -PubSub topic. See the `Injector`javadocs for more information on how to run the -injector. Set up the injector before you start one of these pipelines. Then, -when you start the pipeline, pass as an argument the name of that PubSub topic. -See the pipeline javadocs for the details. - -## Viewing the results in BigQuery - -All of the pipelines write their results to BigQuery. `UserScore` and -`HourlyTeamScore` each write one table, and `LeaderBoard` and -`GameStats` each write two. The pipelines have default table names that -you can override when you start up the pipeline if those tables already exist. - -Depending on the windowing intervals defined in a given pipeline, you may have -to wait for a while (more than an hour) before you start to see results written -to the BigQuery tables. - - - - - - diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java deleted file mode 100644 index f0215cf8aa..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/UserScore.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import com.google.cloud.dataflow.examples.complete.game.utils.WriteToBigQuery; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.apache.avro.reflect.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; - -/** - * This class is the first in a series of four pipelines that tell a story in a 'gaming' domain. - * Concepts: batch processing; reading input from Google Cloud Storage and writing output to - * BigQuery; using standalone DoFns; use of the sum by key transform; examples of - * Java 8 lambda syntax. - * - *

              In this gaming scenario, many users play, as members of different teams, over the course of a - * day, and their actions are logged for processing. Some of the logged game events may be late- - * arriving, if users play on mobile devices and go transiently offline for a period. - * - *

              This pipeline does batch processing of data collected from gaming events. It calculates the - * sum of scores per user, over an entire batch of gaming data (collected, say, for each day). The - * batch processing will not include any late data that arrives after the day's cutoff point. - * - *

              To execute this pipeline using the Dataflow service and static example input data, specify - * the pipeline configuration like this: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - *   --dataset=YOUR-DATASET
              - * }
              - * 
              - * where the BigQuery dataset you specify must already exist. - * - *

              Optionally include the --input argument to specify a batch input file. - * See the --input default value for example batch data file, or use {@link injector.Injector} to - * generate your own batch data. - */ -public class UserScore { - - /** - * Class to hold info about a game event. - */ - @DefaultCoder(AvroCoder.class) - static class GameActionInfo { - @Nullable String user; - @Nullable String team; - @Nullable Integer score; - @Nullable Long timestamp; - - public GameActionInfo() {} - - public GameActionInfo(String user, String team, Integer score, Long timestamp) { - this.user = user; - this.team = team; - this.score = score; - this.timestamp = timestamp; - } - - public String getUser() { - return this.user; - } - public String getTeam() { - return this.team; - } - public Integer getScore() { - return this.score; - } - public String getKey(String keyname) { - if (keyname.equals("team")) { - return this.team; - } else { // return username as default - return this.user; - } - } - public Long getTimestamp() { - return this.timestamp; - } - } - - - /** - * Parses the raw game event info into GameActionInfo objects. Each event line has the following - * format: username,teamname,score,timestamp_in_ms,readable_time - * e.g.: - * user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 - * The human-readable time string is not used here. - */ - static class ParseEventFn extends DoFn { - - // Log and count parse errors. - private static final Logger LOG = LoggerFactory.getLogger(ParseEventFn.class); - private final Aggregator numParseErrors = - createAggregator("ParseErrors", new Sum.SumLongFn()); - - @Override - public void processElement(ProcessContext c) { - String[] components = c.element().split(","); - try { - String user = components[0].trim(); - String team = components[1].trim(); - Integer score = Integer.parseInt(components[2].trim()); - Long timestamp = Long.parseLong(components[3].trim()); - GameActionInfo gInfo = new GameActionInfo(user, team, score, timestamp); - c.output(gInfo); - } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) { - numParseErrors.addValue(1L); - LOG.info("Parse error on " + c.element() + ", " + e.getMessage()); - } - } - } - - /** - * A transform to extract key/score information from GameActionInfo, and sum the scores. The - * constructor arg determines whether 'team' or 'user' info is extracted. - */ - // [START DocInclude_USExtractXform] - public static class ExtractAndSumScore - extends PTransform, PCollection>> { - - private final String field; - - ExtractAndSumScore(String field) { - this.field = field; - } - - @Override - public PCollection> apply( - PCollection gameInfo) { - - return gameInfo - .apply(MapElements - .via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore())) - .withOutputType(new TypeDescriptor>() {})) - .apply(Sum.integersPerKey()); - } - } - // [END DocInclude_USExtractXform] - - - /** - * Options supported by {@link UserScore}. - */ - public interface Options extends PipelineOptions { - - @Description("Path to the data file(s) containing game data.") - // The default maps to two large Google Cloud Storage files (each ~12GB) holding two subsequent - // day's worth (roughly) of data. - @Default.String("gs://dataflow-samples/game/gaming_data*.csv") - String getInput(); - void setInput(String value); - - @Description("BigQuery Dataset to write tables to. Must already exist.") - @Validation.Required - String getDataset(); - void setDataset(String value); - - @Description("The BigQuery table name. Should not already exist.") - @Default.String("user_score") - String getTableName(); - void setTableName(String value); - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is passed to the {@link WriteToBigQuery} constructor to write user score sums. - */ - protected static Map>> - configureBigQueryWrite() { - Map>> tableConfigure = - new HashMap>>(); - tableConfigure.put("user", - new WriteToBigQuery.FieldInfo>("STRING", c -> c.element().getKey())); - tableConfigure.put("total_score", - new WriteToBigQuery.FieldInfo>("INTEGER", c -> c.element().getValue())); - return tableConfigure; - } - - - /** - * Run a batch pipeline. - */ - // [START DocInclude_USMain] - public static void main(String[] args) throws Exception { - // Begin constructing a pipeline configured by commandline flags. - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline pipeline = Pipeline.create(options); - - // Read events from a text file and parse them. - pipeline.apply(TextIO.Read.from(options.getInput())) - .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")) - .apply("WriteUserScoreSums", - new WriteToBigQuery>(options.getTableName(), - configureBigQueryWrite())); - - // Run the batch pipeline. - pipeline.run(); - } - // [END DocInclude_USMain] - -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java deleted file mode 100644 index 39584f403a..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/Injector.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game.injector; - -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.PublishRequest; -import com.google.api.services.pubsub.model.PubsubMessage; - -import com.google.common.collect.ImmutableMap; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import java.io.BufferedOutputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.TimeZone; - - -/** - * This is a generator that simulates usage data from a mobile game, and either publishes the data - * to a pubsub topic or writes it to a file. - * - *

              The general model used by the generator is the following. There is a set of teams with team - * members. Each member is scoring points for their team. After some period, a team will dissolve - * and a new one will be created in its place. There is also a set of 'Robots', or spammer users. - * They hop from team to team. The robots are set to have a higher 'click rate' (generate more - * events) than the regular team members. - * - *

              Each generated line of data has the following form: - * username,teamname,score,timestamp_in_ms,readable_time - * e.g.: - * user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 - * - *

              The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if - * specified. It takes the following arguments: - * {@code Injector project-name (topic-name|none) (filename|none)}. - * - *

              To run the Injector in the mode where it publishes to PubSub, you will need to authenticate - * locally using project-based service account credentials to avoid running over PubSub - * quota. - * See https://developers.google.com/identity/protocols/application-default-credentials - * for more information on using service account credentials. Set the GOOGLE_APPLICATION_CREDENTIALS - * environment variable to point to your downloaded service account credentials before starting the - * program, e.g.: - * {@code export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials-key.json}. - * If you do not do this, then your injector will only run for a few minutes on your - * 'user account' credentials before you will start to see quota error messages like: - * "Request throttled due to user QPS limit being reached", and see this exception: - * ".com.google.api.client.googleapis.json.GoogleJsonResponseException: 429 Too Many Requests". - * Once you've set up your credentials, run the Injector like this": - *

              {@code
              - * Injector   none
              - * }
              - * 
              - * The pubsub topic will be created if it does not exist. - * - *

              To run the injector in write-to-file-mode, set the topic name to "none" and specify the - * filename: - *

              {@code
              - * Injector  none 
              - * }
              - * 
              - */ -class Injector { - private static Pubsub pubsub; - private static Random random = new Random(); - private static String topic; - private static String project; - private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; - - // QPS ranges from 800 to 1000. - private static final int MIN_QPS = 800; - private static final int QPS_RANGE = 200; - // How long to sleep, in ms, between creation of the threads that make API requests to PubSub. - private static final int THREAD_SLEEP_MS = 500; - - // Lists used to generate random team names. - private static final ArrayList COLORS = - new ArrayList(Arrays.asList( - "Magenta", "AliceBlue", "Almond", "Amaranth", "Amber", - "Amethyst", "AndroidGreen", "AntiqueBrass", "Fuchsia", "Ruby", "AppleGreen", - "Apricot", "Aqua", "ArmyGreen", "Asparagus", "Auburn", "Azure", "Banana", - "Beige", "Bisque", "BarnRed", "BattleshipGrey")); - - private static final ArrayList ANIMALS = - new ArrayList(Arrays.asList( - "Echidna", "Koala", "Wombat", "Marmot", "Quokka", "Kangaroo", "Dingo", "Numbat", "Emu", - "Wallaby", "CaneToad", "Bilby", "Possum", "Cassowary", "Kookaburra", "Platypus", - "Bandicoot", "Cockatoo", "Antechinus")); - - // The list of live teams. - private static ArrayList liveTeams = new ArrayList(); - - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); - - - // The total number of robots in the system. - private static final int NUM_ROBOTS = 20; - // Determines the chance that a team will have a robot team member. - private static final int ROBOT_PROBABILITY = 3; - private static final int NUM_LIVE_TEAMS = 15; - private static final int BASE_MEMBERS_PER_TEAM = 5; - private static final int MEMBERS_PER_TEAM = 15; - private static final int MAX_SCORE = 20; - private static final int LATE_DATA_RATE = 5 * 60 * 2; // Every 10 minutes - private static final int BASE_DELAY_IN_MILLIS = 5 * 60 * 1000; // 5-10 minute delay - private static final int FUZZY_DELAY_IN_MILLIS = 5 * 60 * 1000; - - // The minimum time a 'team' can live. - private static final int BASE_TEAM_EXPIRATION_TIME_IN_MINS = 20; - private static final int TEAM_EXPIRATION_TIME_IN_MINS = 20; - - - /** - * A class for holding team info: the name of the team, when it started, - * and the current team members. Teams may but need not include one robot team member. - */ - private static class TeamInfo { - String teamName; - long startTimeInMillis; - int expirationPeriod; - // The team might but need not include 1 robot. Will be non-null if so. - String robot; - int numMembers; - - private TeamInfo(String teamName, long startTimeInMillis, String robot) { - this.teamName = teamName; - this.startTimeInMillis = startTimeInMillis; - // How long until this team is dissolved. - this.expirationPeriod = random.nextInt(TEAM_EXPIRATION_TIME_IN_MINS) - + BASE_TEAM_EXPIRATION_TIME_IN_MINS; - this.robot = robot; - // Determine the number of team members. - numMembers = random.nextInt(MEMBERS_PER_TEAM) + BASE_MEMBERS_PER_TEAM; - } - - String getTeamName() { - return teamName; - } - String getRobot() { - return robot; - } - - long getStartTimeInMillis() { - return startTimeInMillis; - } - long getEndTimeInMillis() { - return startTimeInMillis + (expirationPeriod * 60 * 1000); - } - String getRandomUser() { - int userNum = random.nextInt(numMembers); - return "user" + userNum + "_" + teamName; - } - - int numMembers() { - return numMembers; - } - - @Override - public String toString() { - return "(" + teamName + ", num members: " + numMembers() + ", starting at: " - + startTimeInMillis + ", expires in: " + expirationPeriod + ", robot: " + robot + ")"; - } - } - - /** Utility to grab a random element from an array of Strings. */ - private static String randomElement(ArrayList list) { - int index = random.nextInt(list.size()); - return list.get(index); - } - - /** - * Get and return a random team. If the selected team is too old w.r.t its expiration, remove - * it, replacing it with a new team. - */ - private static TeamInfo randomTeam(ArrayList list) { - int index = random.nextInt(list.size()); - TeamInfo team = list.get(index); - // If the selected team is expired, remove it and return a new team. - long currTime = System.currentTimeMillis(); - if ((team.getEndTimeInMillis() < currTime) || team.numMembers() == 0) { - System.out.println("\nteam " + team + " is too old; replacing."); - System.out.println("start time: " + team.getStartTimeInMillis() - + ", end time: " + team.getEndTimeInMillis() - + ", current time:" + currTime); - removeTeam(index); - // Add a new team in its stead. - return (addLiveTeam()); - } else { - return team; - } - } - - /** - * Create and add a team. Possibly add a robot to the team. - */ - private static synchronized TeamInfo addLiveTeam() { - String teamName = randomElement(COLORS) + randomElement(ANIMALS); - String robot = null; - // Decide if we want to add a robot to the team. - if (random.nextInt(ROBOT_PROBABILITY) == 0) { - robot = "Robot-" + random.nextInt(NUM_ROBOTS); - } - long currTime = System.currentTimeMillis(); - // Create the new team. - TeamInfo newTeam = new TeamInfo(teamName, System.currentTimeMillis(), robot); - liveTeams.add(newTeam); - System.out.println("[+" + newTeam + "]"); - return newTeam; - } - - /** - * Remove a specific team. - */ - private static synchronized void removeTeam(int teamIndex) { - TeamInfo removedTeam = liveTeams.remove(teamIndex); - System.out.println("[-" + removedTeam + "]"); - } - - /** Generate a user gaming event. */ - private static String generateEvent(Long currTime, int delayInMillis) { - TeamInfo team = randomTeam(liveTeams); - String teamName = team.getTeamName(); - String user; - final int parseErrorRate = 900000; - - String robot = team.getRobot(); - // If the team has an associated robot team member... - if (robot != null) { - // Then use that robot for the message with some probability. - // Set this probability to higher than that used to select any of the 'regular' team - // members, so that if there is a robot on the team, it has a higher click rate. - if (random.nextInt(team.numMembers() / 2) == 0) { - user = robot; - } else { - user = team.getRandomUser(); - } - } else { // No robot. - user = team.getRandomUser(); - } - String event = user + "," + teamName + "," + random.nextInt(MAX_SCORE); - // Randomly introduce occasional parse errors. You can see a custom counter tracking the number - // of such errors in the Dataflow Monitoring UI, as the example pipeline runs. - if (random.nextInt(parseErrorRate) == 0) { - System.out.println("Introducing a parse error."); - event = "THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR"; - } - return addTimeInfoToEvent(event, currTime, delayInMillis); - } - - /** - * Add time info to a generated gaming event. - */ - private static String addTimeInfoToEvent(String message, Long currTime, int delayInMillis) { - String eventTimeString = - Long.toString((currTime - delayInMillis) / 1000 * 1000); - // Add a (redundant) 'human-readable' date string to make the data semantics more clear. - String dateString = fmt.print(currTime); - message = message + "," + eventTimeString + "," + dateString; - return message; - } - - /** - * Publish 'numMessages' arbitrary events from live users with the provided delay, to a - * PubSub topic. - */ - public static void publishData(int numMessages, int delayInMillis) - throws IOException { - List pubsubMessages = new ArrayList<>(); - - for (int i = 0; i < Math.max(1, numMessages); i++) { - Long currTime = System.currentTimeMillis(); - String message = generateEvent(currTime, delayInMillis); - PubsubMessage pubsubMessage = new PubsubMessage() - .encodeData(message.getBytes("UTF-8")); - pubsubMessage.setAttributes( - ImmutableMap.of(TIMESTAMP_ATTRIBUTE, - Long.toString((currTime - delayInMillis) / 1000 * 1000))); - if (delayInMillis != 0) { - System.out.println(pubsubMessage.getAttributes()); - System.out.println("late data for: " + message); - } - pubsubMessages.add(pubsubMessage); - } - - PublishRequest publishRequest = new PublishRequest(); - publishRequest.setMessages(pubsubMessages); - pubsub.projects().topics().publish(topic, publishRequest).execute(); - } - - /** - * Publish generated events to a file. - */ - public static void publishDataToFile(String fileName, int numMessages, int delayInMillis) - throws IOException { - List pubsubMessages = new ArrayList<>(); - PrintWriter out = new PrintWriter(new OutputStreamWriter( - new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8")); - - try { - for (int i = 0; i < Math.max(1, numMessages); i++) { - Long currTime = System.currentTimeMillis(); - String message = generateEvent(currTime, delayInMillis); - out.println(message); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (out != null) { - out.flush(); - out.close(); - } - } - } - - - public static void main(String[] args) - throws GeneralSecurityException, IOException, InterruptedException { - if (args.length < 3) { - System.out.println("Usage: Injector project-name (topic-name|none) (filename|none)"); - System.exit(1); - } - boolean writeToFile = false; - boolean writeToPubsub = true; - project = args[0]; - String topicName = args[1]; - String fileName = args[2]; - // The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if - // specified; otherwise, it will try to write to a file. - if (topicName.equalsIgnoreCase("none")) { - writeToFile = true; - writeToPubsub = false; - } - if (writeToPubsub) { - // Create the PubSub client. - pubsub = InjectorUtils.getClient(); - // Create the PubSub topic as necessary. - topic = InjectorUtils.getFullyQualifiedTopicName(project, topicName); - InjectorUtils.createTopic(pubsub, topic); - System.out.println("Injecting to topic: " + topic); - } else { - if (fileName.equalsIgnoreCase("none")) { - System.out.println("Filename not specified."); - System.exit(1); - } - System.out.println("Writing to file: " + fileName); - } - System.out.println("Starting Injector"); - - // Start off with some random live teams. - while (liveTeams.size() < NUM_LIVE_TEAMS) { - addLiveTeam(); - } - - // Publish messages at a rate determined by the QPS and Thread sleep settings. - for (int i = 0; true; i++) { - if (Thread.activeCount() > 10) { - System.err.println("I'm falling behind!"); - } - - // Decide if this should be a batch of late data. - final int numMessages; - final int delayInMillis; - if (i % LATE_DATA_RATE == 0) { - // Insert delayed data for one user (one message only) - delayInMillis = BASE_DELAY_IN_MILLIS + random.nextInt(FUZZY_DELAY_IN_MILLIS); - numMessages = 1; - System.out.println("DELAY(" + delayInMillis + ", " + numMessages + ")"); - } else { - System.out.print("."); - delayInMillis = 0; - numMessages = MIN_QPS + random.nextInt(QPS_RANGE); - } - - if (writeToFile) { // Won't use threading for the file write. - publishDataToFile(fileName, numMessages, delayInMillis); - } else { // Write to PubSub. - // Start a thread to inject some data. - new Thread(){ - public void run() { - try { - publishData(numMessages, delayInMillis); - } catch (IOException e) { - System.err.println(e); - } - } - }.start(); - } - - // Wait before creating another injector thread. - Thread.sleep(THREAD_SLEEP_MS); - } - } -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/InjectorUtils.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/InjectorUtils.java deleted file mode 100644 index 41cfaefd89..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/InjectorUtils.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game.injector; - - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpStatusCodes; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.PubsubScopes; -import com.google.api.services.pubsub.model.Topic; - -import java.io.IOException; - -class InjectorUtils { - - private static final String APP_NAME = "injector"; - - /** - * Builds a new Pubsub client and returns it. - */ - public static Pubsub getClient(final HttpTransport httpTransport, - final JsonFactory jsonFactory) - throws IOException { - checkNotNull(httpTransport); - checkNotNull(jsonFactory); - GoogleCredential credential = - GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); - if (credential.createScopedRequired()) { - credential = credential.createScoped(PubsubScopes.all()); - } - if (credential.getClientAuthentication() != null) { - System.out.println("\n***Warning! You are not using service account credentials to " - + "authenticate.\nYou need to use service account credentials for this example," - + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " - + "out of PubSub quota very quickly.\nSee " - + "https://developers.google.com/identity/protocols/application-default-credentials."); - System.exit(1); - } - HttpRequestInitializer initializer = - new RetryHttpInitializerWrapper(credential); - return new Pubsub.Builder(httpTransport, jsonFactory, initializer) - .setApplicationName(APP_NAME) - .build(); - } - - /** - * Builds a new Pubsub client with default HttpTransport and - * JsonFactory and returns it. - */ - public static Pubsub getClient() throws IOException { - return getClient(Utils.getDefaultTransport(), - Utils.getDefaultJsonFactory()); - } - - - /** - * Returns the fully qualified topic name for Pub/Sub. - */ - public static String getFullyQualifiedTopicName( - final String project, final String topic) { - return String.format("projects/%s/topics/%s", project, topic); - } - - /** - * Create a topic if it doesn't exist. - */ - public static void createTopic(Pubsub client, String fullTopicName) - throws IOException { - try { - client.projects().topics().get(fullTopicName).execute(); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { - Topic topic = client.projects().topics() - .create(fullTopicName, new Topic()) - .execute(); - System.out.printf("Topic %s was created.\n", topic.getName()); - } - } - } -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/RetryHttpInitializerWrapper.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/RetryHttpInitializerWrapper.java deleted file mode 100644 index 7a0f9c872b..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/injector/RetryHttpInitializerWrapper.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game.injector; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.http.HttpBackOffIOExceptionHandler; -import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpUnsuccessfulResponseHandler; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.client.util.Sleeper; - -import java.io.IOException; -import java.util.logging.Logger; - -/** - * RetryHttpInitializerWrapper will automatically retry upon RPC - * failures, preserving the auto-refresh behavior of the Google - * Credentials. - */ -public class RetryHttpInitializerWrapper implements HttpRequestInitializer { - - /** - * A private logger. - */ - private static final Logger LOG = - Logger.getLogger(RetryHttpInitializerWrapper.class.getName()); - - /** - * One minutes in miliseconds. - */ - private static final int ONEMINITUES = 60000; - - /** - * Intercepts the request for filling in the "Authorization" - * header field, as well as recovering from certain unsuccessful - * error codes wherein the Credential must refresh its token for a - * retry. - */ - private final Credential wrappedCredential; - - /** - * A sleeper; you can replace it with a mock in your test. - */ - private final Sleeper sleeper; - - /** - * A constructor. - * - * @param wrappedCredential Credential which will be wrapped and - * used for providing auth header. - */ - public RetryHttpInitializerWrapper(final Credential wrappedCredential) { - this(wrappedCredential, Sleeper.DEFAULT); - } - - /** - * A protected constructor only for testing. - * - * @param wrappedCredential Credential which will be wrapped and - * used for providing auth header. - * @param sleeper Sleeper for easy testing. - */ - RetryHttpInitializerWrapper( - final Credential wrappedCredential, final Sleeper sleeper) { - this.wrappedCredential = checkNotNull(wrappedCredential); - this.sleeper = sleeper; - } - - /** - * Initializes the given request. - */ - @Override - public final void initialize(final HttpRequest request) { - request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout - final HttpUnsuccessfulResponseHandler backoffHandler = - new HttpBackOffUnsuccessfulResponseHandler( - new ExponentialBackOff()) - .setSleeper(sleeper); - request.setInterceptor(wrappedCredential); - request.setUnsuccessfulResponseHandler( - new HttpUnsuccessfulResponseHandler() { - @Override - public boolean handleResponse( - final HttpRequest request, - final HttpResponse response, - final boolean supportsRetry) throws IOException { - if (wrappedCredential.handleResponse( - request, response, supportsRetry)) { - // If credential decides it can handle it, - // the return code or message indicated - // something specific to authentication, - // and no backoff is desired. - return true; - } else if (backoffHandler.handleResponse( - request, response, supportsRetry)) { - // Otherwise, we defer to the judgement of - // our internal backoff handler. - LOG.info("Retrying " - + request.getUrl().toString()); - return true; - } else { - return false; - } - } - }); - request.setIOExceptionHandler( - new HttpBackOffIOExceptionHandler(new ExponentialBackOff()) - .setSleeper(sleeper)); - } -} - diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java deleted file mode 100644 index 2cf719a7ef..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteToBigQuery.java +++ /dev/null @@ -1,134 +0,0 @@ - /* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game.utils; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.examples.complete.game.UserScore; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; -import com.google.cloud.dataflow.sdk.options.GcpOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Generate, format, and write BigQuery table row information. Use provided information about - * the field names and types, as well as lambda functions that describe how to generate their - * values. - */ -public class WriteToBigQuery - extends PTransform, PDone> { - - protected String tableName; - protected Map> fieldInfo; - - public WriteToBigQuery() { - } - - public WriteToBigQuery(String tableName, - Map> fieldInfo) { - this.tableName = tableName; - this.fieldInfo = fieldInfo; - } - - /** Define a class to hold information about output table field definitions. */ - public static class FieldInfo implements Serializable { - // The BigQuery 'type' of the field - private String fieldType; - // A lambda function to generate the field value - private SerializableFunction.ProcessContext, Object> fieldFn; - - public FieldInfo(String fieldType, - SerializableFunction.ProcessContext, Object> fieldFn) { - this.fieldType = fieldType; - this.fieldFn = fieldFn; - } - - String getFieldType() { - return this.fieldType; - } - - SerializableFunction.ProcessContext, Object> getFieldFn() { - return this.fieldFn; - } - } - /** Convert each key/score pair into a BigQuery TableRow as specified by fieldFn. */ - protected class BuildRowFn extends DoFn { - - @Override - public void processElement(ProcessContext c) { - - TableRow row = new TableRow(); - for (Map.Entry> entry : fieldInfo.entrySet()) { - String key = entry.getKey(); - FieldInfo fcnInfo = entry.getValue(); - SerializableFunction.ProcessContext, Object> fcn = - fcnInfo.getFieldFn(); - row.set(key, fcn.apply(c)); - } - c.output(row); - } - } - - /** Build the output table schema. */ - protected TableSchema getSchema() { - List fields = new ArrayList<>(); - for (Map.Entry> entry : fieldInfo.entrySet()) { - String key = entry.getKey(); - FieldInfo fcnInfo = entry.getValue(); - String bqType = fcnInfo.getFieldType(); - fields.add(new TableFieldSchema().setName(key).setType(bqType)); - } - return new TableSchema().setFields(fields); - } - - @Override - public PDone apply(PCollection teamAndScore) { - return teamAndScore - .apply(ParDo.named("ConvertToRow").of(new BuildRowFn())) - .apply(BigQueryIO.Write - .to(getTable(teamAndScore.getPipeline(), - tableName)) - .withSchema(getSchema()) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(WriteDisposition.WRITE_APPEND)); - } - - /** Utility to construct an output table reference. */ - static TableReference getTable(Pipeline pipeline, String tableName) { - PipelineOptions options = pipeline.getOptions(); - TableReference table = new TableReference(); - table.setDatasetId(options.as(UserScore.Options.class).getDataset()); - table.setProjectId(options.as(GcpOptions.class).getProject()); - table.setTableId(tableName); - return table; - } -} diff --git a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java b/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java deleted file mode 100644 index 8433021f2e..0000000000 --- a/examples/src/main/java8/com/google/cloud/dataflow/examples/complete/game/utils/WriteWindowedToBigQuery.java +++ /dev/null @@ -1,76 +0,0 @@ - /* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game.utils; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.CreateDisposition; -import com.google.cloud.dataflow.sdk.io.BigQueryIO.Write.WriteDisposition; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFn.RequiresWindowAccess; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; - -import java.util.Map; - -/** - * Generate, format, and write BigQuery table row information. Subclasses {@link WriteToBigQuery} - * to require windowing; so this subclass may be used for writes that require access to the - * context's window information. - */ -public class WriteWindowedToBigQuery - extends WriteToBigQuery { - - public WriteWindowedToBigQuery(String tableName, - Map> fieldInfo) { - super(tableName, fieldInfo); - } - - /** Convert each key/score pair into a BigQuery TableRow. */ - protected class BuildRowFn extends DoFn - implements RequiresWindowAccess { - - @Override - public void processElement(ProcessContext c) { - - TableRow row = new TableRow(); - for (Map.Entry> entry : fieldInfo.entrySet()) { - String key = entry.getKey(); - FieldInfo fcnInfo = entry.getValue(); - SerializableFunction.ProcessContext, Object> fcn = - fcnInfo.getFieldFn(); - row.set(key, fcn.apply(c)); - } - c.output(row); - } - } - - @Override - public PDone apply(PCollection teamAndScore) { - return teamAndScore - .apply(ParDo.named("ConvertToRow").of(new BuildRowFn())) - .apply(BigQueryIO.Write - .to(getTable(teamAndScore.getPipeline(), - tableName)) - .withSchema(getSchema()) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(WriteDisposition.WRITE_APPEND)); - } - -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/DebuggingWordCountTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/DebuggingWordCountTest.java deleted file mode 100644 index 77d7bc878a..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/DebuggingWordCountTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.common.io.Files; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.File; -import java.nio.charset.StandardCharsets; - -/** - * Tests for {@link DebuggingWordCount}. - */ -@RunWith(JUnit4.class) -public class DebuggingWordCountTest { - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Test - public void testDebuggingWordCount() throws Exception { - File file = tmpFolder.newFile(); - Files.write("stomach secret Flourish message Flourish here Flourish", file, - StandardCharsets.UTF_8); - DebuggingWordCount.main(new String[]{"--inputFile=" + file.getAbsolutePath()}); - } -} - diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/WordCountTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/WordCountTest.java deleted file mode 100644 index 4542c48540..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/WordCountTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.cloud.dataflow.examples.WordCount.CountWords; -import com.google.cloud.dataflow.examples.WordCount.ExtractWordsFn; -import com.google.cloud.dataflow.examples.WordCount.FormatAsTextFn; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** - * Tests of WordCount. - */ -@RunWith(JUnit4.class) -public class WordCountTest { - - /** Example test that tests a specific DoFn. */ - @Test - public void testExtractWordsFn() { - DoFnTester extractWordsFn = - DoFnTester.of(new ExtractWordsFn()); - - Assert.assertThat(extractWordsFn.processBatch(" some input words "), - CoreMatchers.hasItems("some", "input", "words")); - Assert.assertThat(extractWordsFn.processBatch(" "), - CoreMatchers.hasItems()); - Assert.assertThat(extractWordsFn.processBatch(" some ", " input", " words"), - CoreMatchers.hasItems("some", "input", "words")); - } - - static final String[] WORDS_ARRAY = new String[] { - "hi there", "hi", "hi sue bob", - "hi sue", "", "bob hi"}; - - static final List WORDS = Arrays.asList(WORDS_ARRAY); - - static final String[] COUNTS_ARRAY = new String[] { - "hi: 5", "there: 1", "sue: 2", "bob: 2"}; - - /** Example test that tests a PTransform by using an in-memory input and inspecting the output. */ - @Test - @Category(RunnableOnService.class) - public void testCountWords() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); - - PCollection output = input.apply(new CountWords()) - .apply(MapElements.via(new FormatAsTextFn())); - - DataflowAssert.that(output).containsInAnyOrder(COUNTS_ARRAY); - p.run(); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/complete/AutoCompleteTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/complete/AutoCompleteTest.java deleted file mode 100644 index aec1557c28..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/complete/AutoCompleteTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.cloud.dataflow.examples.complete.AutoComplete.CompletionCandidate; -import com.google.cloud.dataflow.examples.complete.AutoComplete.ComputeTopCompletions; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Filter; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** - * Tests of AutoComplete. - */ -@RunWith(Parameterized.class) -public class AutoCompleteTest implements Serializable { - private boolean recursive; - - public AutoCompleteTest(Boolean recursive) { - this.recursive = recursive; - } - - @Parameterized.Parameters - public static Collection testRecursive() { - return Arrays.asList(new Object[][] { - { true }, - { false } - }); - } - - @Test - public void testAutoComplete() { - List words = Arrays.asList( - "apple", - "apple", - "apricot", - "banana", - "blackberry", - "blackberry", - "blackberry", - "blueberry", - "blueberry", - "cherry"); - - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(words)); - - PCollection>> output = - input.apply(new ComputeTopCompletions(2, recursive)) - .apply(Filter.byPredicate( - new SerializableFunction>, Boolean>() { - @Override - public Boolean apply(KV> element) { - return element.getKey().length() <= 2; - } - })); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("a", parseList("apple:2", "apricot:1")), - KV.of("ap", parseList("apple:2", "apricot:1")), - KV.of("b", parseList("blackberry:3", "blueberry:2")), - KV.of("ba", parseList("banana:1")), - KV.of("bl", parseList("blackberry:3", "blueberry:2")), - KV.of("c", parseList("cherry:1")), - KV.of("ch", parseList("cherry:1"))); - p.run(); - } - - @Test - public void testTinyAutoComplete() { - List words = Arrays.asList("x", "x", "x", "xy", "xy", "xyz"); - - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(words)); - - PCollection>> output = - input.apply(new ComputeTopCompletions(2, recursive)); - - DataflowAssert.that(output).containsInAnyOrder( - KV.of("x", parseList("x:3", "xy:2")), - KV.of("xy", parseList("xy:2", "xyz:1")), - KV.of("xyz", parseList("xyz:1"))); - p.run(); - } - - @Test - public void testWindowedAutoComplete() { - List> words = Arrays.asList( - TimestampedValue.of("xA", new Instant(1)), - TimestampedValue.of("xA", new Instant(1)), - TimestampedValue.of("xB", new Instant(1)), - TimestampedValue.of("xB", new Instant(2)), - TimestampedValue.of("xB", new Instant(2))); - - Pipeline p = TestPipeline.create(); - - PCollection input = p - .apply(Create.of(words)) - .apply(new ReifyTimestamps()); - - PCollection>> output = - input.apply(Window.into(SlidingWindows.of(new Duration(2)))) - .apply(new ComputeTopCompletions(2, recursive)); - - DataflowAssert.that(output).containsInAnyOrder( - // Window [0, 2) - KV.of("x", parseList("xA:2", "xB:1")), - KV.of("xA", parseList("xA:2")), - KV.of("xB", parseList("xB:1")), - - // Window [1, 3) - KV.of("x", parseList("xB:3", "xA:2")), - KV.of("xA", parseList("xA:2")), - KV.of("xB", parseList("xB:3")), - - // Window [2, 3) - KV.of("x", parseList("xB:2")), - KV.of("xB", parseList("xB:2"))); - p.run(); - } - - private static List parseList(String... entries) { - List all = new ArrayList<>(); - for (String s : entries) { - String[] countValue = s.split(":"); - all.add(new CompletionCandidate(countValue[0], Integer.valueOf(countValue[1]))); - } - return all; - } - - private static class ReifyTimestamps - extends PTransform>, PCollection> { - @Override - public PCollection apply(PCollection> input) { - return input.apply(ParDo.of(new DoFn, T>() { - @Override - public void processElement(ProcessContext c) { - c.outputWithTimestamp(c.element().getValue(), c.element().getTimestamp()); - } - })); - } - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/complete/TfIdfTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/complete/TfIdfTest.java deleted file mode 100644 index 5ee136cee2..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/complete/TfIdfTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringDelegateCoder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Keys; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.net.URI; -import java.util.Arrays; - -/** - * Tests of {@link TfIdf}. - */ -@RunWith(JUnit4.class) -public class TfIdfTest { - - /** Test that the example runs. */ - @Test - @Category(RunnableOnService.class) - public void testTfIdf() throws Exception { - Pipeline pipeline = TestPipeline.create(); - - pipeline.getCoderRegistry().registerCoder(URI.class, StringDelegateCoder.of(URI.class)); - - PCollection>> wordToUriAndTfIdf = pipeline - .apply(Create.of( - KV.of(new URI("x"), "a b c d"), - KV.of(new URI("y"), "a b c"), - KV.of(new URI("z"), "a m n"))) - .apply(new TfIdf.ComputeTfIdf()); - - PCollection words = wordToUriAndTfIdf - .apply(Keys.create()) - .apply(RemoveDuplicates.create()); - - DataflowAssert.that(words).containsInAnyOrder(Arrays.asList("a", "m", "n", "b", "c", "d")); - - pipeline.run(); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessionsTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessionsTest.java deleted file mode 100644 index ce9de51409..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/complete/TopWikipediaSessionsTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** Unit tests for {@link TopWikipediaSessions}. */ -@RunWith(JUnit4.class) -public class TopWikipediaSessionsTest { - @Test - @Category(RunnableOnService.class) - public void testComputeTopUsers() { - Pipeline p = TestPipeline.create(); - - PCollection output = - p.apply(Create.of(Arrays.asList( - new TableRow().set("timestamp", 0).set("contributor_username", "user1"), - new TableRow().set("timestamp", 1).set("contributor_username", "user1"), - new TableRow().set("timestamp", 2).set("contributor_username", "user1"), - new TableRow().set("timestamp", 0).set("contributor_username", "user2"), - new TableRow().set("timestamp", 1).set("contributor_username", "user2"), - new TableRow().set("timestamp", 3601).set("contributor_username", "user2"), - new TableRow().set("timestamp", 3602).set("contributor_username", "user2"), - new TableRow().set("timestamp", 35 * 24 * 3600).set("contributor_username", "user3")))) - .apply(new TopWikipediaSessions.ComputeTopSessions(1.0)); - - DataflowAssert.that(output).containsInAnyOrder(Arrays.asList( - "user1 : [1970-01-01T00:00:00.000Z..1970-01-01T01:00:02.000Z)" - + " : 3 : 1970-01-01T00:00:00.000Z", - "user3 : [1970-02-05T00:00:00.000Z..1970-02-05T01:00:00.000Z)" - + " : 1 : 1970-02-01T00:00:00.000Z")); - - p.run(); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoesTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoesTest.java deleted file mode 100644 index 6dce4eddfa..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/BigQueryTornadoesTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.examples.cookbook.BigQueryTornadoes.ExtractTornadoesFn; -import com.google.cloud.dataflow.examples.cookbook.BigQueryTornadoes.FormatCountsFn; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** - * Test case for {@link BigQueryTornadoes}. - */ -@RunWith(JUnit4.class) -public class BigQueryTornadoesTest { - - @Test - public void testExtractTornadoes() throws Exception { - TableRow row = new TableRow() - .set("month", "6") - .set("tornado", true); - DoFnTester extractWordsFn = - DoFnTester.of(new ExtractTornadoesFn()); - Assert.assertThat(extractWordsFn.processBatch(row), - CoreMatchers.hasItems(6)); - } - - @Test - public void testNoTornadoes() throws Exception { - TableRow row = new TableRow() - .set("month", 6) - .set("tornado", false); - DoFnTester extractWordsFn = - DoFnTester.of(new ExtractTornadoesFn()); - Assert.assertTrue(extractWordsFn.processBatch(row).isEmpty()); - } - - @Test - @SuppressWarnings({"rawtypes", "unchecked"}) - public void testFormatCounts() throws Exception { - DoFnTester, TableRow> formatCountsFn = - DoFnTester.of(new FormatCountsFn()); - KV empty[] = {}; - List results = formatCountsFn.processBatch(empty); - Assert.assertTrue(results.size() == 0); - KV input[] = { KV.of(3, 0L), - KV.of(4, Long.MAX_VALUE), - KV.of(5, Long.MIN_VALUE) }; - results = formatCountsFn.processBatch(input); - Assert.assertEquals(results.size(), 3); - Assert.assertEquals(results.get(0).get("month"), 3); - Assert.assertEquals(results.get(0).get("tornado_count"), 0L); - Assert.assertEquals(results.get(1).get("month"), 4); - Assert.assertEquals(results.get(1).get("tornado_count"), Long.MAX_VALUE); - Assert.assertEquals(results.get(2).get("month"), 5); - Assert.assertEquals(results.get(2).get("tornado_count"), Long.MIN_VALUE); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamplesTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamplesTest.java deleted file mode 100644 index fe4823d099..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/CombinePerKeyExamplesTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.examples.cookbook.CombinePerKeyExamples.ExtractLargeWordsFn; -import com.google.cloud.dataflow.examples.cookbook.CombinePerKeyExamples.FormatShakespeareOutputFn; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** Unit tests for {@link CombinePerKeyExamples}. */ -@RunWith(JUnit4.class) -public class CombinePerKeyExamplesTest { - - private static final TableRow row1 = new TableRow() - .set("corpus", "king_lear").set("word", "snuffleupaguses"); - private static final TableRow row2 = new TableRow() - .set("corpus", "macbeth").set("word", "antidisestablishmentarianism"); - private static final TableRow row3 = new TableRow() - .set("corpus", "king_lear").set("word", "antidisestablishmentarianism"); - private static final TableRow row4 = new TableRow() - .set("corpus", "macbeth").set("word", "bob"); - private static final TableRow row5 = new TableRow() - .set("corpus", "king_lear").set("word", "hi"); - - static final TableRow[] ROWS_ARRAY = new TableRow[] { - row1, row2, row3, row4, row5 - }; - - private static final KV tuple1 = KV.of("snuffleupaguses", "king_lear"); - private static final KV tuple2 = KV.of("antidisestablishmentarianism", "macbeth"); - private static final KV tuple3 = KV.of("antidisestablishmentarianism", - "king_lear"); - - private static final KV combinedTuple1 = KV.of("antidisestablishmentarianism", - "king_lear,macbeth"); - private static final KV combinedTuple2 = KV.of("snuffleupaguses", "king_lear"); - - @SuppressWarnings({"unchecked", "rawtypes"}) - static final KV[] COMBINED_TUPLES_ARRAY = new KV[] { - combinedTuple1, combinedTuple2 - }; - - private static final TableRow resultRow1 = new TableRow() - .set("word", "snuffleupaguses").set("all_plays", "king_lear"); - private static final TableRow resultRow2 = new TableRow() - .set("word", "antidisestablishmentarianism") - .set("all_plays", "king_lear,macbeth"); - - @Test - public void testExtractLargeWordsFn() { - DoFnTester> extractLargeWordsFn = - DoFnTester.of(new ExtractLargeWordsFn()); - List> results = extractLargeWordsFn.processBatch(ROWS_ARRAY); - Assert.assertThat(results, CoreMatchers.hasItem(tuple1)); - Assert.assertThat(results, CoreMatchers.hasItem(tuple2)); - Assert.assertThat(results, CoreMatchers.hasItem(tuple3)); - } - - @Test - public void testFormatShakespeareOutputFn() { - DoFnTester, TableRow> formatShakespeareOutputFn = - DoFnTester.of(new FormatShakespeareOutputFn()); - List results = formatShakespeareOutputFn.processBatch(COMBINED_TUPLES_ARRAY); - Assert.assertThat(results, CoreMatchers.hasItem(resultRow1)); - Assert.assertThat(results, CoreMatchers.hasItem(resultRow2)); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/DeDupExampleTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/DeDupExampleTest.java deleted file mode 100644 index bce6b11831..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/DeDupExampleTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** Unit tests for {@link DeDupExample}. */ -@RunWith(JUnit4.class) -public class DeDupExampleTest { - - @Test - @Category(RunnableOnService.class) - public void testRemoveDuplicates() { - List strings = Arrays.asList( - "k1", - "k5", - "k5", - "k2", - "k1", - "k2", - "k3"); - - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(strings) - .withCoder(StringUtf8Coder.of())); - - PCollection output = - input.apply(RemoveDuplicates.create()); - - DataflowAssert.that(output) - .containsInAnyOrder("k1", "k5", "k2", "k3"); - p.run(); - } - - @Test - @Category(RunnableOnService.class) - public void testRemoveDuplicatesEmpty() { - List strings = Arrays.asList(); - - Pipeline p = TestPipeline.create(); - - PCollection input = - p.apply(Create.of(strings) - .withCoder(StringUtf8Coder.of())); - - PCollection output = - input.apply(RemoveDuplicates.create()); - - DataflowAssert.that(output).empty(); - p.run(); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/FilterExamplesTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/FilterExamplesTest.java deleted file mode 100644 index 6d822f9805..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/FilterExamplesTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.examples.cookbook.FilterExamples.FilterSingleMonthDataFn; -import com.google.cloud.dataflow.examples.cookbook.FilterExamples.ProjectionFn; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** Unit tests for {@link FilterExamples}. */ -@RunWith(JUnit4.class) -public class FilterExamplesTest { - - private static final TableRow row1 = new TableRow() - .set("month", "6").set("day", "21") - .set("year", "2014").set("mean_temp", "85.3") - .set("tornado", true); - private static final TableRow row2 = new TableRow() - .set("month", "7").set("day", "20") - .set("year", "2014").set("mean_temp", "75.4") - .set("tornado", false); - private static final TableRow row3 = new TableRow() - .set("month", "6").set("day", "18") - .set("year", "2014").set("mean_temp", "45.3") - .set("tornado", true); - static final TableRow[] ROWS_ARRAY = new TableRow[] { - row1, row2, row3 - }; - static final List ROWS = Arrays.asList(ROWS_ARRAY); - - private static final TableRow outRow1 = new TableRow() - .set("year", 2014).set("month", 6) - .set("day", 21).set("mean_temp", 85.3); - private static final TableRow outRow2 = new TableRow() - .set("year", 2014).set("month", 7) - .set("day", 20).set("mean_temp", 75.4); - private static final TableRow outRow3 = new TableRow() - .set("year", 2014).set("month", 6) - .set("day", 18).set("mean_temp", 45.3); - private static final TableRow[] PROJROWS_ARRAY = new TableRow[] { - outRow1, outRow2, outRow3 - }; - - - @Test - public void testProjectionFn() { - DoFnTester projectionFn = - DoFnTester.of(new ProjectionFn()); - List results = projectionFn.processBatch(ROWS_ARRAY); - Assert.assertThat(results, CoreMatchers.hasItem(outRow1)); - Assert.assertThat(results, CoreMatchers.hasItem(outRow2)); - Assert.assertThat(results, CoreMatchers.hasItem(outRow3)); - } - - @Test - public void testFilterSingleMonthDataFn() { - DoFnTester filterSingleMonthDataFn = - DoFnTester.of(new FilterSingleMonthDataFn(7)); - List results = filterSingleMonthDataFn.processBatch(PROJROWS_ARRAY); - Assert.assertThat(results, CoreMatchers.hasItem(outRow2)); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/JoinExamplesTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/JoinExamplesTest.java deleted file mode 100644 index db3ae34e7d..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/JoinExamplesTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.examples.cookbook.JoinExamples.ExtractCountryInfoFn; -import com.google.cloud.dataflow.examples.cookbook.JoinExamples.ExtractEventDataFn; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.List; - -/** Unit tests for {@link JoinExamples}. */ -@RunWith(JUnit4.class) -public class JoinExamplesTest { - - private static final TableRow row1 = new TableRow() - .set("ActionGeo_CountryCode", "VM").set("SQLDATE", "20141212") - .set("Actor1Name", "BANGKOK").set("SOURCEURL", "http://cnn.com"); - private static final TableRow row2 = new TableRow() - .set("ActionGeo_CountryCode", "VM").set("SQLDATE", "20141212") - .set("Actor1Name", "LAOS").set("SOURCEURL", "http://www.chicagotribune.com"); - private static final TableRow row3 = new TableRow() - .set("ActionGeo_CountryCode", "BE").set("SQLDATE", "20141213") - .set("Actor1Name", "AFGHANISTAN").set("SOURCEURL", "http://cnn.com"); - static final TableRow[] EVENTS = new TableRow[] { - row1, row2, row3 - }; - static final List EVENT_ARRAY = Arrays.asList(EVENTS); - - private static final KV kv1 = KV.of("VM", - "Date: 20141212, Actor1: LAOS, url: http://www.chicagotribune.com"); - private static final KV kv2 = KV.of("BE", - "Date: 20141213, Actor1: AFGHANISTAN, url: http://cnn.com"); - private static final KV kv3 = KV.of("BE", "Belgium"); - private static final KV kv4 = KV.of("VM", "Vietnam"); - - private static final TableRow cc1 = new TableRow() - .set("FIPSCC", "VM").set("HumanName", "Vietnam"); - private static final TableRow cc2 = new TableRow() - .set("FIPSCC", "BE").set("HumanName", "Belgium"); - static final TableRow[] CCS = new TableRow[] { - cc1, cc2 - }; - static final List CC_ARRAY = Arrays.asList(CCS); - - static final String[] JOINED_EVENTS = new String[] { - "Country code: VM, Country name: Vietnam, Event info: Date: 20141212, Actor1: LAOS, " - + "url: http://www.chicagotribune.com", - "Country code: VM, Country name: Vietnam, Event info: Date: 20141212, Actor1: BANGKOK, " - + "url: http://cnn.com", - "Country code: BE, Country name: Belgium, Event info: Date: 20141213, Actor1: AFGHANISTAN, " - + "url: http://cnn.com" - }; - - @Test - public void testExtractEventDataFn() { - DoFnTester> extractEventDataFn = - DoFnTester.of(new ExtractEventDataFn()); - List> results = extractEventDataFn.processBatch(EVENTS); - Assert.assertThat(results, CoreMatchers.hasItem(kv1)); - Assert.assertThat(results, CoreMatchers.hasItem(kv2)); - } - - @Test - public void testExtractCountryInfoFn() { - DoFnTester> extractCountryInfoFn = - DoFnTester.of(new ExtractCountryInfoFn()); - List> results = extractCountryInfoFn.processBatch(CCS); - Assert.assertThat(results, CoreMatchers.hasItem(kv3)); - Assert.assertThat(results, CoreMatchers.hasItem(kv4)); - } - - - @Test - @Category(RunnableOnService.class) - public void testJoin() throws java.lang.Exception { - Pipeline p = TestPipeline.create(); - PCollection input1 = p.apply("CreateEvent", Create.of(EVENT_ARRAY)); - PCollection input2 = p.apply("CreateCC", Create.of(CC_ARRAY)); - - PCollection output = JoinExamples.joinEvents(input1, input2); - DataflowAssert.that(output).containsInAnyOrder(JOINED_EVENTS); - p.run(); - } -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamplesTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamplesTest.java deleted file mode 100644 index 3deff2a2e3..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/MaxPerKeyExamplesTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.examples.cookbook.MaxPerKeyExamples.ExtractTempFn; -import com.google.cloud.dataflow.examples.cookbook.MaxPerKeyExamples.FormatMaxesFn; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.collect.ImmutableList; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** Unit tests for {@link MaxPerKeyExamples}. */ -@RunWith(JUnit4.class) -public class MaxPerKeyExamplesTest { - - private static final TableRow row1 = new TableRow() - .set("month", "6").set("day", "21") - .set("year", "2014").set("mean_temp", "85.3") - .set("tornado", true); - private static final TableRow row2 = new TableRow() - .set("month", "7").set("day", "20") - .set("year", "2014").set("mean_temp", "75.4") - .set("tornado", false); - private static final TableRow row3 = new TableRow() - .set("month", "6").set("day", "18") - .set("year", "2014").set("mean_temp", "45.3") - .set("tornado", true); - private static final List TEST_ROWS = ImmutableList.of(row1, row2, row3); - - private static final KV kv1 = KV.of(6, 85.3); - private static final KV kv2 = KV.of(6, 45.3); - private static final KV kv3 = KV.of(7, 75.4); - - private static final List> TEST_KVS = ImmutableList.of(kv1, kv2, kv3); - - private static final TableRow resultRow1 = new TableRow() - .set("month", 6) - .set("max_mean_temp", 85.3); - private static final TableRow resultRow2 = new TableRow() - .set("month", 7) - .set("max_mean_temp", 75.4); - - - @Test - public void testExtractTempFn() { - DoFnTester> extractTempFn = - DoFnTester.of(new ExtractTempFn()); - List> results = extractTempFn.processBatch(TEST_ROWS); - Assert.assertThat(results, CoreMatchers.hasItem(kv1)); - Assert.assertThat(results, CoreMatchers.hasItem(kv2)); - Assert.assertThat(results, CoreMatchers.hasItem(kv3)); - } - - @Test - public void testFormatMaxesFn() { - DoFnTester, TableRow> formatMaxesFnFn = - DoFnTester.of(new FormatMaxesFn()); - List results = formatMaxesFnFn.processBatch(TEST_KVS); - Assert.assertThat(results, CoreMatchers.hasItem(resultRow1)); - Assert.assertThat(results, CoreMatchers.hasItem(resultRow2)); - } - -} diff --git a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java b/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java deleted file mode 100644 index 75cd0cf03a..0000000000 --- a/examples/src/test/java/com/google/cloud/dataflow/examples/cookbook/TriggerExampleTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.cookbook; - -import com.google.api.services.bigquery.model.TableRow; -import com.google.cloud.dataflow.examples.cookbook.TriggerExample.ExtractFlowInfo; -import com.google.cloud.dataflow.examples.cookbook.TriggerExample.TotalFlow; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; - -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** - * Unit Tests for {@link TriggerExample}. - * The results generated by triggers are by definition non-deterministic and hence hard to test. - * The unit test does not test all aspects of the example. - */ -@RunWith(JUnit4.class) -public class TriggerExampleTest { - - private static final String[] INPUT = - {"01/01/2010 00:00:00,1108302,94,E,ML,36,100,29,0.0065,66,9,1,0.001,74.8,1,9,3,0.0028,71,1,9," - + "12,0.0099,67.4,1,9,13,0.0121,99.0,1,,,,,0,,,,,0,,,,,0,,,,,0", "01/01/2010 00:00:00," - + "1100333,5,N,FR,9,0,39,,,9,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,,0,,,,"}; - - private static final List> TIME_STAMPED_INPUT = Arrays.asList( - TimestampedValue.of("01/01/2010 00:00:00,1108302,5,W,ML,36,100,30,0.0065,66,9,1,0.001," - + "74.8,1,9,3,0.0028,71,1,9,12,0.0099,87.4,1,9,13,0.0121,99.0,1,,,,,0,,,,,0,,,,,0,,," - + ",,0", new Instant(60000)), - TimestampedValue.of("01/01/2010 00:00:00,1108302,110,E,ML,36,100,40,0.0065,66,9,1,0.001," - + "74.8,1,9,3,0.0028,71,1,9,12,0.0099,67.4,1,9,13,0.0121,99.0,1,,,,,0,,,,,0,,,,,0,,," - + ",,0", new Instant(1)), - TimestampedValue.of("01/01/2010 00:00:00,1108302,110,E,ML,36,100,50,0.0065,66,9,1," - + "0.001,74.8,1,9,3,0.0028,71,1,9,12,0.0099,97.4,1,9,13,0.0121,50.0,1,,,,,0,,,,,0" - + ",,,,,0,,,,,0", new Instant(1))); - - private static final TableRow OUT_ROW_1 = - new TableRow() - .set("trigger_type", "default") - .set("freeway", "5") - .set("total_flow", 30) - .set("number_of_records", 1) - .set("isFirst", true) - .set("isLast", true) - .set("timing", "ON_TIME") - .set("window", "[1970-01-01T00:01:00.000Z..1970-01-01T00:02:00.000Z)"); - - private static final TableRow OUT_ROW_2 = - new TableRow() - .set("trigger_type", "default") - .set("freeway", "110") - .set("total_flow", 90) - .set("number_of_records", 2) - .set("isFirst", true) - .set("isLast", true) - .set("timing", "ON_TIME") - .set("window", "[1970-01-01T00:00:00.000Z..1970-01-01T00:01:00.000Z)"); - - @Test - public void testExtractTotalFlow() throws Exception { - DoFnTester> extractFlowInfow = DoFnTester - .of(new ExtractFlowInfo()); - - List> results = extractFlowInfow.processBatch(INPUT); - Assert.assertEquals(results.size(), 1); - Assert.assertEquals(results.get(0).getKey(), "94"); - Assert.assertEquals(results.get(0).getValue(), new Integer(29)); - - List> output = extractFlowInfow.processBatch(""); - Assert.assertEquals(output.size(), 0); - } - - @Test - @Category(RunnableOnService.class) - public void testTotalFlow () { - Pipeline pipeline = TestPipeline.create(); - PCollection> flow = pipeline - .apply(Create.timestamped(TIME_STAMPED_INPUT)) - .apply(ParDo.of(new ExtractFlowInfo())); - - PCollection totalFlow = flow - .apply(Window.>into(FixedWindows.of(Duration.standardMinutes(1)))) - .apply(new TotalFlow("default")); - - PCollection results = totalFlow.apply(ParDo.of(new FormatResults())); - - DataflowAssert.that(results) - .containsInAnyOrder(canonicalFormat(OUT_ROW_1), canonicalFormat(OUT_ROW_2)); - pipeline.run(); - - } - - // Sort the fields and toString() the values, since TableRow has a bit of a dynamically - // typed API and equals()/hashCode() are not appropriate for matching in tests - static String canonicalFormat(TableRow row) { - List entries = Lists.newArrayListWithCapacity(row.size()); - for (Map.Entry entry : row.entrySet()) { - entries.add(entry.getKey() + ":" + entry.getValue()); - } - Collections.sort(entries); - return Joiner.on(",").join(entries); - } - - static class FormatResults extends DoFn { - @Override - public void processElement(ProcessContext c) throws Exception { - TableRow element = c.element(); - TableRow row = new TableRow() - .set("trigger_type", element.get("trigger_type")) - .set("freeway", element.get("freeway")) - .set("total_flow", element.get("total_flow")) - .set("number_of_records", element.get("number_of_records")) - .set("isFirst", element.get("isFirst")) - .set("isLast", element.get("isLast")) - .set("timing", element.get("timing")) - .set("window", element.get("window")); - c.output(canonicalFormat(row)); - } - } -} - - diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java deleted file mode 100644 index fcae41c6bb..0000000000 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/MinimalWordCountJava8Test.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.GcsOptions; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.Filter; -import com.google.cloud.dataflow.sdk.transforms.FlatMapElements; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.util.GcsUtil; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; -import com.google.common.collect.ImmutableList; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.io.IOException; -import java.io.Serializable; -import java.nio.channels.FileChannel; -import java.nio.channels.SeekableByteChannel; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; -import java.util.Arrays; -import java.util.List; - -/** - * To keep {@link MinimalWordCountJava8} simple, it is not factored or testable. This test - * file should be maintained with a copy of its code for a basic smoke test. - */ -@RunWith(JUnit4.class) -public class MinimalWordCountJava8Test implements Serializable { - - /** - * A basic smoke test that ensures there is no crash at pipeline construction time. - */ - @Test - public void testMinimalWordCountJava8() throws Exception { - Pipeline p = TestPipeline.create(); - p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); - - p.apply(TextIO.Read.from("gs://dataflow-samples/shakespeare/*")) - .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) - .withOutputType(new TypeDescriptor() {})) - .apply(Filter.byPredicate((String word) -> !word.isEmpty())) - .apply(Count.perElement()) - .apply(MapElements - .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue()) - .withOutputType(new TypeDescriptor() {})) - .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); - } - - private GcsUtil buildMockGcsUtil() throws IOException { - GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); - - // Any request to open gets a new bogus channel - Mockito - .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); - - // Any request for expansion returns a list containing the original GcsPath - // This is required to pass validation that occurs in TextIO during apply() - Mockito - .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); - - return mockGcsUtil; - } -} diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/GameStatsTest.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/GameStatsTest.java deleted file mode 100644 index e12c440413..0000000000 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/GameStatsTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import com.google.cloud.dataflow.examples.complete.game.GameStats.CalculateSpammyUsers; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - -/** - * Tests of GameStats. - * Because the pipeline was designed for easy readability and explanations, it lacks good - * modularity for testing. See our testing documentation for better ideas: - * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. - */ -@RunWith(JUnit4.class) -public class GameStatsTest implements Serializable { - - // User scores - static final KV[] USER_SCORES_ARRAY = new KV[] { - KV.of("Robot-2", 66), KV.of("Robot-1", 116), KV.of("user7_AndroidGreenKookaburra", 23), - KV.of("user7_AndroidGreenKookaburra", 1), - KV.of("user19_BisqueBilby", 14), KV.of("user13_ApricotQuokka", 15), - KV.of("user18_BananaEmu", 25), KV.of("user6_AmberEchidna", 8), - KV.of("user2_AmberQuokka", 6), KV.of("user0_MagentaKangaroo", 4), - KV.of("user0_MagentaKangaroo", 3), KV.of("user2_AmberCockatoo", 13), - KV.of("user7_AlmondWallaby", 15), KV.of("user6_AmberNumbat", 11), - KV.of("user6_AmberQuokka", 4) - }; - - static final List> USER_SCORES = Arrays.asList(USER_SCORES_ARRAY); - - // The expected list of 'spammers'. - static final KV[] SPAMMERS = new KV[] { - KV.of("Robot-2", 66), KV.of("Robot-1", 116) - }; - - - /** Test the calculation of 'spammy users'. */ - @Test - @Category(RunnableOnService.class) - public void testCalculateSpammyUsers() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection> input = p.apply(Create.of(USER_SCORES)); - PCollection> output = input.apply(new CalculateSpammyUsers()); - - // Check the set of spammers. - DataflowAssert.that(output).containsInAnyOrder(SPAMMERS); - - p.run(); - } - -} diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScoreTest.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScoreTest.java deleted file mode 100644 index f77a5d4488..0000000000 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScoreTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import com.google.cloud.dataflow.examples.complete.game.UserScore.GameActionInfo; -import com.google.cloud.dataflow.examples.complete.game.UserScore.ParseEventFn; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.Filter; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - -/** - * Tests of HourlyTeamScore. - * Because the pipeline was designed for easy readability and explanations, it lacks good - * modularity for testing. See our testing documentation for better ideas: - * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. - */ -@RunWith(JUnit4.class) -public class HourlyTeamScoreTest implements Serializable { - - static final String[] GAME_EVENTS_ARRAY = new String[] { - "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", - "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", - "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", - "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444", - // time gap... - "user0_AndroidGreenEchidna,AndroidGreenEchidna,0,1447965690000,2015-11-19 12:41:31.053", - "user0_MagentaKangaroo,MagentaKangaroo,4,1447965690000,2015-11-19 12:41:31.053", - "user2_AmberCockatoo,AmberCockatoo,13,1447965690000,2015-11-19 12:41:31.053", - "user18_BananaEmu,BananaEmu,7,1447965690000,2015-11-19 12:41:31.053", - "user3_BananaEmu,BananaEmu,17,1447965690000,2015-11-19 12:41:31.053", - "user18_BananaEmu,BananaEmu,1,1447965690000,2015-11-19 12:41:31.053", - "user18_ApricotCaneToad,ApricotCaneToad,14,1447965690000,2015-11-19 12:41:31.053" - }; - - - static final List GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); - - - // Used to check the filtering. - static final KV[] FILTERED_EVENTS = new KV[] { - KV.of("user0_AndroidGreenEchidna", 0), KV.of("user0_MagentaKangaroo", 4), - KV.of("user2_AmberCockatoo", 13), - KV.of("user18_BananaEmu", 7), KV.of("user3_BananaEmu", 17), - KV.of("user18_BananaEmu", 1), KV.of("user18_ApricotCaneToad", 14) - }; - - - /** Test the filtering. */ - @Test - @Category(RunnableOnService.class) - public void testUserScoresFilter() throws Exception { - Pipeline p = TestPipeline.create(); - - final Instant startMinTimestamp = new Instant(1447965680000L); - - PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); - - PCollection> output = input - .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())) - - .apply("FilterStartTime", Filter.byPredicate( - (GameActionInfo gInfo) - -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) - // run a map to access the fields in the result. - .apply(MapElements - .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) - .withOutputType(new TypeDescriptor>() {})); - - DataflowAssert.that(output).containsInAnyOrder(FILTERED_EVENTS); - - p.run(); - } - -} diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java deleted file mode 100644 index 295d85ee6b..0000000000 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/LeaderBoardTest.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.examples.complete.game.LeaderBoard.CalculateTeamScores; -import com.google.cloud.dataflow.examples.complete.game.LeaderBoard.CalculateUserScores; -import com.google.cloud.dataflow.examples.complete.game.UserScore.GameActionInfo; -import com.google.cloud.dataflow.sdk.coders.AvroCoder; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.testing.TestStream; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindow; -import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TimestampedValue; -import com.google.common.collect.ImmutableMap; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import java.io.Serializable; - -/** - * Tests for {@link LeaderBoard}. - */ -@RunWith(JUnit4.class) -public class LeaderBoardTest implements Serializable { - private static final Duration ALLOWED_LATENESS = Duration.standardHours(1); - private static final Duration TEAM_WINDOW_DURATION = Duration.standardMinutes(20); - private Instant baseTime = new Instant(0); - - /** - * Some example users, on two separate teams. - */ - private enum TestUser { - RED_ONE("scarlet", "red"), RED_TWO("burgundy", "red"), - BLUE_ONE("navy", "blue"), BLUE_TWO("sky", "blue"); - - private final String userName; - private final String teamName; - - TestUser(String userName, String teamName) { - this.userName = userName; - this.teamName = teamName; - } - - public String getUser() { - return userName; - } - - public String getTeam() { - return teamName; - } - } - - /** - * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive - * on time (ahead of the watermark). - */ - @Test - public void testTeamScoresOnTime() { - TestPipeline p = getPipeline(); - - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - // Start at the epoch - .advanceWatermarkTo(baseTime) - // add some elements ahead of the watermark - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1)), - event(TestUser.RED_TWO, 3, Duration.standardSeconds(22)), - event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(3))) - // The watermark advances slightly, but not past the end of the window - .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) - // Add some more on time elements - .addElements(event(TestUser.RED_ONE, 1, Duration.standardMinutes(4)), - event(TestUser.BLUE_ONE, 2, Duration.standardSeconds(270))) - // The window should close and emit an ON_TIME pane - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - DataflowAssert.that(teamScores) - .inOnTimePane(new IntervalWindow(baseTime, TEAM_WINDOW_DURATION)) - .containsInAnyOrder(KV.of(blueTeam, 12), KV.of(redTeam, 4)); - - p.run(); - } - - /** - * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive - * on time, and the processing time advances far enough for speculative panes. - */ - @Test - public void testTeamScoresSpeculative() { - TestPipeline p = getPipeline(); - - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - // Start at the epoch - .advanceWatermarkTo(baseTime) - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1))) - // Some time passes within the runner, which causes a speculative pane containing the blue - // team's score to be emitted - .advanceProcessingTime(Duration.standardMinutes(10)) - .addElements(event(TestUser.RED_TWO, 5, Duration.standardMinutes(3))) - // Some additional time passes and we get a speculative pane for the red team - .advanceProcessingTime(Duration.standardMinutes(12)) - .addElements(event(TestUser.BLUE_TWO, 3, Duration.standardSeconds(22))) - // More time passes and a speculative pane containing a refined value for the blue pane is - // emitted - .advanceProcessingTime(Duration.standardMinutes(10)) - // Some more events occur - .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(4)), - event(TestUser.BLUE_TWO, 2, Duration.standardMinutes(2))) - // The window closes and we get an ON_TIME pane that contains all of the updates - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - IntervalWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - // The window contains speculative panes alongside the on-time pane - DataflowAssert.that(teamScores) - .inWindow(window) - .containsInAnyOrder(KV.of(blueTeam, 10) /* The on-time blue pane */, - KV.of(redTeam, 9) /* The on-time red pane */, - KV.of(blueTeam, 5) /* The first blue speculative pane */, - KV.of(blueTeam, 8) /* The second blue speculative pane */, - KV.of(redTeam, 5) /* The red speculative pane */); - DataflowAssert.that(teamScores) - .inOnTimePane(window) - .containsInAnyOrder(KV.of(blueTeam, 10), KV.of(redTeam, 9)); - - p.run(); - } - - /** - * A test where elements arrive behind the watermark (late data), but before the end of the - * window. These elements are emitted on time. - */ - @Test - public void testTeamScoresUnobservablyLate() { - TestPipeline p = getPipeline(); - - BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - .advanceWatermarkTo(baseTime) - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8)), - event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) - .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).minus(Duration.standardMinutes(1))) - // These events are late, but the window hasn't closed yet, so the elements are in the - // on-time pane - .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), - event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), - event(TestUser.BLUE_TWO, 2, Duration.standardSeconds(90)), - event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) - .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) - .advanceWatermarkToInfinity(); - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - // The On Time pane contains the late elements that arrived before the end of the window - DataflowAssert.that(teamScores) - .inOnTimePane(window) - .containsInAnyOrder(KV.of(redTeam, 14), KV.of(blueTeam, 13)); - - p.run(); - } - - /** - * A test where elements arrive behind the watermark (late data) after the watermark passes the - * end of the window, but before the maximum allowed lateness. These elements are emitted in a - * late pane. - */ - @Test - public void testTeamScoresObservablyLate() { - TestPipeline p = getPipeline(); - - Instant firstWindowCloses = baseTime.plus(ALLOWED_LATENESS).plus(TEAM_WINDOW_DURATION); - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - .advanceWatermarkTo(baseTime) - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8))) - .advanceProcessingTime(Duration.standardMinutes(10)) - .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) - .addElements(event(TestUser.RED_ONE, 3, Duration.standardMinutes(1)), - event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) - .advanceWatermarkTo(firstWindowCloses.minus(Duration.standardMinutes(1))) - // These events are late but should still appear in a late pane - .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), - event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), - event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) - // A late refinement is emitted due to the advance in processing time, but the window has - // not yet closed because the watermark has not advanced - .advanceProcessingTime(Duration.standardMinutes(12)) - // These elements should appear in the final pane - .addElements(event(TestUser.RED_TWO, 9, Duration.standardMinutes(1)), - event(TestUser.RED_TWO, 1, Duration.standardMinutes(3))) - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - DataflowAssert.that(teamScores) - .inWindow(window) - .satisfies((SerializableFunction>, Void>) input -> { - // The final sums need not exist in the same pane, but must appear in the output - // PCollection - assertThat(input, hasItem(KV.of(blueTeam, 11))); - assertThat(input, hasItem(KV.of(redTeam, 27))); - return null; - }); - DataflowAssert.thatMap(teamScores) - // The closing behavior of CalculateTeamScores precludes an inFinalPane matcher - .inOnTimePane(window) - .isEqualTo(ImmutableMap.builder().put(redTeam, 7) - .put(blueTeam, 11) - .build()); - - // No final pane is emitted for the blue team, as all of their updates have been taken into - // account in earlier panes - DataflowAssert.that(teamScores).inFinalPane(window).containsInAnyOrder(KV.of(redTeam, 27)); - - p.run(); - } - - /** - * A test where elements arrive beyond the maximum allowed lateness. These elements are dropped - * within {@link CalculateTeamScores} and do not impact the final result. - */ - @Test - public void testTeamScoresDroppablyLate() { - TestPipeline p = getPipeline(); - - BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - TestStream infos = TestStream.create(AvroCoder.of(GameActionInfo.class)) - .addElements(event(TestUser.BLUE_ONE, 12, Duration.ZERO), - event(TestUser.RED_ONE, 3, Duration.ZERO)) - .advanceWatermarkTo(window.maxTimestamp()) - .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_TWO, 3, Duration.ZERO), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) - // Move the watermark past the end of the allowed lateness plus the end of the window - .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS) - .plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) - // These elements within the expired window are droppably late, and will not appear in the - // output - .addElements( - event(TestUser.BLUE_TWO, 3, TEAM_WINDOW_DURATION.minus(Duration.standardSeconds(5))), - event(TestUser.RED_ONE, 7, Duration.standardMinutes(4))) - .advanceWatermarkToInfinity(); - PCollection> teamScores = p.apply(infos) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - // Only one on-time pane and no late panes should be emitted - DataflowAssert.that(teamScores) - .inWindow(window) - .containsInAnyOrder(KV.of(redTeam, 7), KV.of(blueTeam, 18)); - // No elements are added before the watermark passes the end of the window plus the allowed - // lateness, so no refinement should be emitted - DataflowAssert.that(teamScores).inFinalPane(window).empty(); - } - - /** - * A test where elements arrive both on-time and late in {@link CalculateUserScores}, which emits - * output into the {@link GlobalWindow}. All elements that arrive should be taken into account, - * even if they arrive later than the maximum allowed lateness. - */ - @Test - public void testUserScore() { - TestPipeline p = getPipeline(); - - TestStream infos = - TestStream.create(AvroCoder.of(GameActionInfo.class)) - .addElements( - event(TestUser.BLUE_ONE, 12, Duration.ZERO), - event(TestUser.RED_ONE, 3, Duration.ZERO)) - .advanceProcessingTime(Duration.standardMinutes(7)) - .addElements( - event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_TWO, 3, Duration.ZERO), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) - .advanceProcessingTime(Duration.standardMinutes(5)) - .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS).plus(Duration.standardHours(12))) - // Late elements are always observable within the global window - they arrive before - // the window closes, so they will appear in a pane, even if they arrive after the - // allowed lateness, and are taken into account alongside on-time elements - .addElements( - event(TestUser.RED_ONE, 3, Duration.standardMinutes(7)), - event(TestUser.RED_ONE, 2, (ALLOWED_LATENESS).plus(Duration.standardHours(13)))) - .advanceProcessingTime(Duration.standardMinutes(6)) - .addElements(event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(12))) - .advanceProcessingTime(Duration.standardMinutes(20)) - .advanceWatermarkToInfinity(); - - PCollection> userScores = - p.apply(infos).apply(new CalculateUserScores(ALLOWED_LATENESS)); - - // User scores are emitted in speculative panes in the Global Window - this matcher choice - // ensures that panes emitted by the watermark advancing to positive infinity are not included, - // as that will not occur outside of tests - DataflowAssert.that(userScores) - .inEarlyGlobalWindowPanes() - .containsInAnyOrder(KV.of(TestUser.BLUE_ONE.getUser(), 15), - KV.of(TestUser.RED_ONE.getUser(), 7), - KV.of(TestUser.RED_ONE.getUser(), 12), - KV.of(TestUser.BLUE_TWO.getUser(), 3), - KV.of(TestUser.BLUE_TWO.getUser(), 8)); - - p.run(); - } - - private TestPipeline getPipeline() { - PipelineOptions options = TestPipeline.testingPipelineOptions(); - options.setRunner(InProcessPipelineRunner.class); - return TestPipeline.fromOptions(options); - } - - private TimestampedValue event( - TestUser user, - int score, - Duration baseTimeOffset) { - return TimestampedValue.of(new GameActionInfo(user.getUser(), - user.getTeam(), - score, - baseTime.plus(baseTimeOffset).getMillis()), baseTime.plus(baseTimeOffset)); - } -} diff --git a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/UserScoreTest.java b/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/UserScoreTest.java deleted file mode 100644 index f24d99fca1..0000000000 --- a/examples/src/test/java8/com/google/cloud/dataflow/examples/complete/game/UserScoreTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.examples.complete.game; - -import com.google.cloud.dataflow.examples.complete.game.UserScore.ExtractAndSumScore; -import com.google.cloud.dataflow.examples.complete.game.UserScore.GameActionInfo; -import com.google.cloud.dataflow.examples.complete.game.UserScore.ParseEventFn; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.MapElements; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - -/** - * Tests of UserScore. - */ -@RunWith(JUnit4.class) -public class UserScoreTest implements Serializable { - - static final String[] GAME_EVENTS_ARRAY = new String[] { - "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", - "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", - "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", - "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", - "user6_AliceBlueDingo,AliceBlueDingo,4,xxxxxxx,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", - "THIS IS A PARSE ERROR,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444" - }; - - static final String[] GAME_EVENTS_ARRAY2 = new String[] { - "user6_AliceBlueDingo,AliceBlueDingo,4,xxxxxxx,2015-11-19 09:53:53.444", - "THIS IS A PARSE ERROR,2015-11-19 09:53:53.444", - "user13_BisqueBilby,BisqueBilby,xxx,1447955630000,2015-11-19 09:53:53.444" - }; - - static final List GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); - static final List GAME_EVENTS2 = Arrays.asList(GAME_EVENTS_ARRAY2); - - static final KV[] USER_SUMS = new KV[] { - KV.of("user0_MagentaKangaroo", 3), KV.of("user13_ApricotQuokka", 15), - KV.of("user6_AmberNumbat", 11), KV.of("user7_AlmondWallaby", 15), - KV.of("user7_AndroidGreenKookaburra", 23), - KV.of("user19_BisqueBilby", 14) }; - - static final KV[] TEAM_SUMS = new KV[] { - KV.of("MagentaKangaroo", 3), KV.of("ApricotQuokka", 15), - KV.of("AmberNumbat", 11), KV.of("AlmondWallaby", 15), - KV.of("AndroidGreenKookaburra", 23), - KV.of("BisqueBilby", 14) }; - - /** Test the ParseEventFn DoFn. */ - @Test - public void testParseEventFn() { - DoFnTester parseEventFn = - DoFnTester.of(new ParseEventFn()); - - List results = parseEventFn.processBatch(GAME_EVENTS_ARRAY); - Assert.assertEquals(results.size(), 8); - Assert.assertEquals(results.get(0).getUser(), "user0_MagentaKangaroo"); - Assert.assertEquals(results.get(0).getTeam(), "MagentaKangaroo"); - Assert.assertEquals(results.get(0).getScore(), new Integer(3)); - } - - /** Tests ExtractAndSumScore("user"). */ - @Test - @Category(RunnableOnService.class) - public void testUserScoreSums() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); - - PCollection> output = input - .apply(ParDo.of(new ParseEventFn())) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")); - - // Check the user score sums. - DataflowAssert.that(output).containsInAnyOrder(USER_SUMS); - - p.run(); - } - - /** Tests ExtractAndSumScore("team"). */ - @Test - @Category(RunnableOnService.class) - public void testTeamScoreSums() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); - - PCollection> output = input - .apply(ParDo.of(new ParseEventFn())) - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")); - - // Check the team score sums. - DataflowAssert.that(output).containsInAnyOrder(TEAM_SUMS); - - p.run(); - } - - /** Test that bad input data is dropped appropriately. */ - @Test - @Category(RunnableOnService.class) - public void testUserScoresBadInput() throws Exception { - Pipeline p = TestPipeline.create(); - - PCollection input = p.apply(Create.of(GAME_EVENTS2).withCoder(StringUtf8Coder.of())); - - PCollection> extract = input - .apply(ParDo.of(new ParseEventFn())) - .apply( - MapElements.via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) - .withOutputType(new TypeDescriptor>() {})); - - DataflowAssert.that(extract).empty(); - - p.run(); - } -} From 49246298e8906c88a1df1a9ab1f5d8f13eb4a430 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 15:29:01 -0800 Subject: [PATCH 660/751] Upgrade "starter" archetype to Dataflow 2.0.0 --- checkstyle.xml | 2 +- maven-archetypes/starter/pom.xml | 23 +++------ .../resources/archetype-resources/pom.xml | 22 +++++++- .../src/main/java/StarterPipeline.java | 50 ++++++++++--------- .../projects/basic/archetype.properties | 14 ++++++ .../projects/basic/reference/pom.xml | 22 +++++++- .../src/main/java/it/pkg/StarterPipeline.java | 50 ++++++++++--------- 7 files changed, 116 insertions(+), 67 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 66d1379c4e..1bb56748da 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -36,7 +36,7 @@ page at http://checkstyle.sourceforge.net/config.html --> --> + value="^(//| \*|#) Copyright (\([cC]\) )?[\d]{4}(\-[\d]{4})? (Google Inc\.|The Google Cloud Dataflow.*Authors).*$" /> diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index e40c1955d9..efc5023c46 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -1,6 +1,6 @@ diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java b/maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java index ffabbc01cf..d6afdecf11 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java @@ -1,37 +1,39 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 ${package}; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; - +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SimpleFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A starter example for writing Google Cloud Dataflow programs. + * A starter example for writing Beam programs. * *

              The example takes two strings, converts them to their upper-case * representation and logs them. * - *

              To run this starter example locally using DirectPipelineRunner, just + *

              To run this starter example locally using DirectRunner, just * execute it without any additional parameters from your favorite development * environment. * @@ -39,7 +41,7 @@ * Platform, you should specify the following command-line options: * --project= * --stagingLocation= - * --runner=BlockingDataflowPipelineRunner + * --runner=DataflowRunner */ public class StarterPipeline { private static final Logger LOG = LoggerFactory.getLogger(StarterPipeline.class); @@ -49,14 +51,14 @@ public static void main(String[] args) { PipelineOptionsFactory.fromArgs(args).withValidation().create()); p.apply(Create.of("Hello", "World")) - .apply(ParDo.of(new DoFn() { + .apply(MapElements.via(new SimpleFunction() { @Override - public void processElement(ProcessContext c) { - c.output(c.element().toUpperCase()); + public String apply(String input) { + return input.toUpperCase(); } })) .apply(ParDo.of(new DoFn() { - @Override + @ProcessElement public void processElement(ProcessContext c) { LOG.info(c.element()); } diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties index c59e77a9d5..1f3c9c5178 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties +++ b/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties @@ -1,3 +1,17 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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=it.pkg version=0.1-SNAPSHOT groupId=archetype.it diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index b94fb39e12..336de14adf 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -7,6 +7,26 @@ basic 0.1-SNAPSHOT + + UTF-8 + + + + + ossrh.snapshots + Sonatype OSS Repository Hosting + https://oss.sonatype.org/content/repositories/snapshots/ + + false + + + true + + + + + jar + @@ -38,7 +58,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - [1.0.0, 2.0.0) + 2.0.0-beta1-SNAPSHOT diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java b/maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java index 2e7c4e1fc9..4ae92e8ce6 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java @@ -1,37 +1,39 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 it.pkg; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; - +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SimpleFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A starter example for writing Google Cloud Dataflow programs. + * A starter example for writing Beam programs. * *

              The example takes two strings, converts them to their upper-case * representation and logs them. * - *

              To run this starter example locally using DirectPipelineRunner, just + *

              To run this starter example locally using DirectRunner, just * execute it without any additional parameters from your favorite development * environment. * @@ -39,7 +41,7 @@ * Platform, you should specify the following command-line options: * --project= * --stagingLocation= - * --runner=BlockingDataflowPipelineRunner + * --runner=DataflowRunner */ public class StarterPipeline { private static final Logger LOG = LoggerFactory.getLogger(StarterPipeline.class); @@ -49,14 +51,14 @@ public static void main(String[] args) { PipelineOptionsFactory.fromArgs(args).withValidation().create()); p.apply(Create.of("Hello", "World")) - .apply(ParDo.of(new DoFn() { + .apply(MapElements.via(new SimpleFunction() { @Override - public void processElement(ProcessContext c) { - c.output(c.element().toUpperCase()); + public String apply(String input) { + return input.toUpperCase(); } })) .apply(ParDo.of(new DoFn() { - @Override + @ProcessElement public void processElement(ProcessContext c) { LOG.info(c.element()); } From 90d03eb2ef410dd077f5a128ebf173c4d91ed213 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 15:29:26 -0800 Subject: [PATCH 661/751] Add SdkDependencies.java and ExamplesDependencies.java to mark dependencies as used. --- .../dataflow/sdk/ExamplesDependencies.java | 29 +++++++++++++++++ .../cloud/dataflow/sdk/SdkDependencies.java | 31 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java create mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java diff --git a/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java b/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java new file mode 100644 index 0000000000..827aff8395 --- /dev/null +++ b/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2017 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk; + +import org.apache.beam.examples.MinimalWordCountJava8; +import org.apache.beam.examples.WordCount; + +/** + * Mark the examples dependencies as used at compile time. This is also needed + * to produce some content in the final JAR file. + */ +class ExamplesDependencies { + SdkDependencies sdkDependencies; + WordCount wordCount; + MinimalWordCountJava8 minimalWordCount; +} diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java new file mode 100644 index 0000000000..7bbfbe3729 --- /dev/null +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2017 Google Inc. + * + * Licensed 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 com.google.cloud.dataflow.sdk; + +import org.apache.beam.runners.dataflow.DataflowRunner; +import org.apache.beam.runners.direct.DirectRunner; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; + +/** + * Mark the dependencies as used at compile time. + */ +class SdkDependencies { + private Pipeline p; + private BigQueryIO bigQueryIO; + private DirectRunner directRunner; + private DataflowRunner dataflowRunner; +} From 87a474ed477965d5c7895ac0281475521d7bb970 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 15:33:11 -0800 Subject: [PATCH 662/751] Remove contrib modules from this repository These modules are part of Apache Beam, but not Dataflow any more. --- .travis.yml | 2 - contrib/README.md | 53 - contrib/firebaseio/AUTHORS.md | 1 - contrib/firebaseio/README.md | 15 - contrib/firebaseio/pom.xml | 116 -- .../firebase/contrib/JacksonCoder.java | 152 -- .../contrib/firebase/contrib/LogElements.java | 76 - .../contrib/firebase/events/ChildAdded.java | 45 - .../contrib/firebase/events/ChildChanged.java | 43 - .../contrib/firebase/events/ChildMoved.java | 40 - .../contrib/firebase/events/ChildRemoved.java | 41 - .../firebase/events/FirebaseChildEvent.java | 53 - .../firebase/events/FirebaseEvent.java | 75 - .../contrib/firebase/events/ValueChanged.java | 44 - .../contrib/firebase/io/DoFirebasePush.java | 52 - .../contrib/firebase/io/DoFirebaseSet.java | 43 - .../contrib/firebase/io/DoFirebaseUpdate.java | 45 - .../contrib/firebase/io/FirebaseDoFn.java | 96 - .../contrib/firebase/io/FirebaseSource.java | 406 ----- .../firebase/utils/FirebaseAuthenticator.java | 34 - .../firebase/utils/FirebaseCheckpoint.java | 125 -- .../utils/FirebaseCheckpointCoder.java | 104 -- .../utils/FirebaseEmptyAuthenticator.java | 33 - .../firebase/utils/FirebaseEventCoder.java | 105 -- .../utils/FirebasePasswordAuthenticator.java | 59 - .../contrib/firebase/utils/Record.java | 48 - .../firebase/io/BaseFirebaseSourceTest.java | 181 -- .../contrib/firebase/io/ChildAddedTest.java | 58 - .../contrib/firebase/io/ChildChangedTest.java | 43 - .../contrib/firebase/io/ChildMovedTest.java | 70 - .../contrib/firebase/io/ChildRemovedTest.java | 60 - .../io/DoFirebaseSetWithPriority.java | 51 - .../firebase/io/FirebaseChildTest.java | 86 - .../firebase/io/FirebaseValueTest.java | 103 -- .../src/test/resources/testdata.json | 302 --- contrib/hadoop/AUTHORS.md | 7 - contrib/hadoop/README.md | 24 - contrib/hadoop/pom.xml | 170 -- .../contrib/hadoop/HadoopFileSource.java | 494 ----- .../contrib/hadoop/WritableCoder.java | 110 -- .../contrib/hadoop/HadoopFileSourceTest.java | 189 -- .../contrib/hadoop/WritableCoderTest.java | 36 - contrib/join-library/AUTHORS.md | 6 - contrib/join-library/README.md | 33 - contrib/join-library/pom.xml | 186 -- .../dataflow/contrib/joinlibrary/Join.java | 186 -- .../contrib/joinlibrary/InnerJoinTest.java | 142 -- .../joinlibrary/OuterLeftJoinTest.java | 152 -- .../joinlibrary/OuterRightJoinTest.java | 152 -- contrib/kafka/pom.xml | 174 -- .../contrib/kafka/KafkaCheckpointMark.java | 74 - .../cloud/dataflow/contrib/kafka/KafkaIO.java | 1611 ----------------- .../dataflow/contrib/kafka/KafkaRecord.java | 80 - .../contrib/kafka/KafkaRecordCoder.java | 122 -- .../dataflow/contrib/kafka/package-info.java | 20 - .../dataflow/contrib/kafka/KafkaIOTest.java | 668 ------- contrib/sorter/README.md | 23 - contrib/sorter/pom.xml | 233 --- .../sorter/BufferedExternalSorter.java | 127 -- .../contrib/sorter/ExternalSorter.java | 237 --- .../contrib/sorter/InMemorySorter.java | 164 -- .../dataflow/contrib/sorter/SortValues.java | 211 --- .../cloud/dataflow/contrib/sorter/Sorter.java | 45 - .../dataflow/contrib/sorter/package-info.java | 21 - .../sorter/BufferedExternalSorterTest.java | 192 -- .../contrib/sorter/ExternalSorterTest.java | 101 -- .../contrib/sorter/InMemorySorterTest.java | 150 -- .../contrib/sorter/SortValuesTest.java | 127 -- .../contrib/sorter/SorterTestUtils.java | 128 -- 69 files changed, 9255 deletions(-) delete mode 100644 contrib/README.md delete mode 100644 contrib/firebaseio/AUTHORS.md delete mode 100644 contrib/firebaseio/README.md delete mode 100644 contrib/firebaseio/pom.xml delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java delete mode 100644 contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java delete mode 100644 contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java delete mode 100644 contrib/firebaseio/src/test/resources/testdata.json delete mode 100644 contrib/hadoop/AUTHORS.md delete mode 100644 contrib/hadoop/README.md delete mode 100644 contrib/hadoop/pom.xml delete mode 100644 contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java delete mode 100644 contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoder.java delete mode 100644 contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java delete mode 100644 contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoderTest.java delete mode 100644 contrib/join-library/AUTHORS.md delete mode 100644 contrib/join-library/README.md delete mode 100644 contrib/join-library/pom.xml delete mode 100644 contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java delete mode 100644 contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java delete mode 100644 contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterLeftJoinTest.java delete mode 100644 contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterRightJoinTest.java delete mode 100644 contrib/kafka/pom.xml delete mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java delete mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java delete mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java delete mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java delete mode 100644 contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java delete mode 100644 contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java delete mode 100644 contrib/sorter/README.md delete mode 100644 contrib/sorter/pom.xml delete mode 100644 contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java delete mode 100644 contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java delete mode 100644 contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java delete mode 100644 contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/SortValues.java delete mode 100644 contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/Sorter.java delete mode 100644 contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/package-info.java delete mode 100644 contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java delete mode 100644 contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java delete mode 100644 contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java delete mode 100644 contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java delete mode 100644 contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SorterTestUtils.java diff --git a/.travis.yml b/.travis.yml index 51926a3d8c..2f5ed182c5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,9 +30,7 @@ before_install: install: - travis_retry mvn install clean -U -DskipTests=true - - travis_retry mvn -f contrib/kafka/pom.xml install clean -U -DskipTests=true script: - travis_retry mvn $MAVEN_OVERRIDE install -U - - travis_retry mvn -f contrib/kafka/pom.xml $MAVEN_OVERRIDE install -U - travis_retry travis/test_wordcount.sh diff --git a/contrib/README.md b/contrib/README.md deleted file mode 100644 index b99cf46f58..0000000000 --- a/contrib/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Community contributions - -This directory hosts a wide variety of community contributions that may be -useful to other users of -[Google Cloud Dataflow](https://cloud.google.com/dataflow/), -but may not be appropriate or ready yet for inclusion into the -[mainline SDK](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/) or a -separate Google-maintained artifact. - -## Organization - -Each subdirectory represents a logically separate and independent module. -Preferably, the code is hosted directly in this repository. When appropriate, we -are also open to linking external repositories via -[`submodule`](http://git-scm.com/docs/git-submodule/) functionality within Git. - -While we are happy to host individual modules to provide additional value to all -Cloud Dataflow users, the modules are _maintained solely by their respective -authors_. We will make sure that modules are related to Cloud Dataflow, that -they are distributed under the same license as the mainline SDK, and provide -some guidance to the authors to make the quality as high as possible. - -We __cannot__, however, provide _any_ guarantees about correctness, -compatibility, performance, support, test coverage, maintenance or future -availability of individual modules hosted here. - -## Process - -In general, we recommend to get in touch with us through the issue tracker -first. That way we can help out and possibly guide you. Coordinating up front -makes it much easier to avoid frustration later on. - -We welcome pull requests with a new module from everyone. Every module must be -related to Cloud Dataflow and must have an informative README.md file. We will -provide general guidance, but usually won't be reviewing the module in detail. -We reserve the right to refuse acceptance to any module, or remove it at any -time in the future. - -We also welcome improvements to an existing module from everyone. We'll often -wait for comments from the primary author of the module before merging a pull -request from a non-primary author. - -As the module matures, we may choose to pull it directly into the mainline SDK -or promote it to a Google-managed artifact. - -## Licensing - -We require all contributors to sign the Contributor License Agreement, exactly -as we require for any contributions to the mainline SDK. More information is -available in our [CONTRIBUTING.md](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/CONTRIBUTING.md) -file. - -_Thank you for your contribution to the Cloud Dataflow community!_ diff --git a/contrib/firebaseio/AUTHORS.md b/contrib/firebaseio/AUTHORS.md deleted file mode 100644 index ac5722ea5b..0000000000 --- a/contrib/firebaseio/AUTHORS.md +++ /dev/null @@ -1 +0,0 @@ -elibixby [@ github, google, gmail ] diff --git a/contrib/firebaseio/README.md b/contrib/firebaseio/README.md deleted file mode 100644 index 776b3d54fc..0000000000 --- a/contrib/firebaseio/README.md +++ /dev/null @@ -1,15 +0,0 @@ -## FirebaseIO for Dataflow - -This library includes two components for communicating with [Firebase](https://www.firebase.com/) from Dataflow: - -* `FirebaseSource` an `UnboundedSource` which can watch a Firebase ref for events and attempts (but does not guarantee) to deliver those events in order to the Dataflow pipeline. The source will unmarshal `DataSnapshot`s generated by these events into the paramaterized type specified by your `FirebaseSource`, which can be any object serializable by Jackson. - -* Various `FirebaseDoFn` which can be used to write data to a firebase: - * `DoFirebasePush` will attach unique and time-ordered strings as keys to objects recieved from the pipeline. - * `DoFirebaseSet` will overriding data at the key's location with the specified `Object` - * `DoFirebaseUpdate` will update the tree at the ref with the given `Map` - - -These utilities also use various `FirebaseEvents` to wrap your unmarshalled data in a Jackson Serializable POJO, which retains event type information. So for example you could filter a pipeline on `ChildAdded` events, where your original `DataSnapshot` was unmarshalled into a Jackson Serializable POJO of type `T`. - -The library uses the firebase JVM client library and as such takes advantage of Web sockets for data transfer. However this means that writing to Firebase will use one websocket per shard, so if you plan to fan out your writes, make sure to limit the parallelism with `PTransform#withMaxParallelism` to avoid capping out your available connections. diff --git a/contrib/firebaseio/pom.xml b/contrib/firebaseio/pom.xml deleted file mode 100644 index b50ef89167..0000000000 --- a/contrib/firebaseio/pom.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - 4.0.0 - - com.google.cloud.dataflow - google-cloud-dataflow-java-contrib-firebaseio - FirebaseIO - Unbounded Source, and DoFns to read and write to Firebase from Dataflow - 0.0.2-SNAPSHOT - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - [1.2.0, 2.0.0) - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.7 - 1.7 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.puppycrawl.tools - checkstyle - 6.19 - - - - ../../checkstyle.xml - ../../suppressions.xml - true - true - true - - - - validate - - check - - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${google-cloud-dataflow-version} - - - - com.google.guava - guava - 18.0 - - - - com.firebase - firebase-client-jvm - 2.4.0 - - - - org.slf4j - slf4j-api - 1.7.15 - - - - org.slf4j - slf4j-simple - 1.7.15 - - - - - org.hamcrest - hamcrest-all - 1.3 - test - - - - junit - junit - 4.12 - test - - - - diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java deleted file mode 100644 index 61a862922d..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/JacksonCoder.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.contrib; - -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.SerializationFeature; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.Collections; -import java.util.List; - -/** - * Encodes objects using {@link ObjectReader} and {@link ObjectWriter}. - */ -public class JacksonCoder extends StandardCoder { - - private static final long serialVersionUID = -754345287170755870L; - - private static final ObjectMapper MAPPER = new ObjectMapper() - .enableDefaultTyping(DefaultTyping.NON_FINAL) - .enable(DeserializationFeature.WRAP_EXCEPTIONS) - .enable(SerializationFeature.WRAP_EXCEPTIONS) - .disable(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS) - .enable(SerializationFeature.WRITE_NULL_MAP_VALUES) - .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false) - .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); - - // Threadsafe as per http://wiki.fasterxml.com/JacksonBestPracticesPerformance - private final ObjectWriter writer; - private final ObjectReader reader; - - protected final Class type; - - public static JacksonCoder of(TypeDescriptor type) { - @SuppressWarnings("unchecked") - Class clazz = (Class) type.getRawType(); - return of(clazz); - } - - /** - * JacksonCoder will encode any type that can be serialized/deserialized by Jackson. - * This can be achieved by using either Jackson annotations (as seen in this library), or - * implementing @see - * custom serializers. - * @param clazz Type to encode - * @return A JacksonCoder parameterized with type {@code clazz} - */ - public static JacksonCoder of(Class clazz){ - return new JacksonCoder<>(clazz); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @JsonCreator - public static JacksonCoder of( - @JsonProperty("type") String classType) throws ClassNotFoundException { - return new JacksonCoder(Class.forName(classType)); - } - - protected JacksonCoder(Class clazz){ - this.type = clazz; - writer = MAPPER.writer(); - reader = MAPPER.readerFor(type); - } - - @Override - public void encode(T value, OutputStream outStream, Context context) - throws IOException { - writer.writeValue(outStream, value); - } - - @Override - public T decode(InputStream inStream, com.google.cloud.dataflow.sdk.coders.Coder.Context context) - throws IOException { - return reader.readValue(inStream); - } - - @Override - public List> getCoderArguments() { - return Collections.emptyList(); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException{ - throw new Coder.NonDeterministicException(this, "JSON is not a deterministic encoding"); - } - - public Class getType(){ - return this.type; - } - - protected Object writeReplace() { - // When serialized by Java, instances of AvroCoder should be replaced by - // a SerializedJacksonCoderProxy. - return new SerializedJacksonCoderProxy<>(type); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addString(result, "type", type.getName()); - return result; - } - - /** - * Proxy to use in place of serializing the JacksonCoder. This allows the fields - * to remain final. - */ - protected static class SerializedJacksonCoderProxy implements Serializable { - protected final Class type; - - public SerializedJacksonCoderProxy(Class type) { - this.type = type; - } - - private Object readResolve() { - // When deserialized, instances of this object should be replaced by - // constructing an JacksonCoder. - return new JacksonCoder<>(type); - } - } -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java deleted file mode 100644 index 4afe30afbc..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/contrib/LogElements.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.contrib; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; - -import org.slf4j.event.Level; -import org.slf4j.event.LoggingEvent; -import org.slf4j.event.SubstituteLoggingEvent; -import org.slf4j.impl.SimpleLogger; -import org.slf4j.impl.SimpleLoggerFactory; - -/** - * Logs a {@link PCollection} to a logger for the specified {@link Class}. - */ -public class LogElements extends PTransform, PDone> { - - private final Level level; - private final String className; - - public LogElements(Class clazz, Level level){ - this.className = clazz.getName(); - this.level = level; - } - - @Override - public PDone apply(PCollection input){ - input.apply(ParDo.of(new LoggingDoFn(this.className, this.level))); - return PDone.in(input.getPipeline()); - } - - /** - * Given a PCollection of {@link LoggingEvent}s, log them to a simple logger (uses System.err). - */ - public static class LoggingDoFn extends DoFn{ - - private final String className; - private final Level level; - private transient SimpleLogger logger; - - public LoggingDoFn(String className, Level level){ - this.className = className; - this.level = level; - } - - @Override - public void startBundle(Context c) throws Exception { - logger = (SimpleLogger) new SimpleLoggerFactory().getLogger(this.className); - } - - @Override - public void processElement(DoFn.ProcessContext c) throws Exception { - SubstituteLoggingEvent event = new SubstituteLoggingEvent(); - event.setMessage(c.element().toString()); - event.setLevel(this.level); - logger.log(event); - } - } -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java deleted file mode 100644 index a880126108..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; - -import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.firebase.client.ChildEventListener; -import com.firebase.client.DataSnapshot; - - -/** - * Created by {@link ChildEventListener#onChildRemoved } triggered in {@link FirebaseSource}. - * @param type that {@link DataSnapshot} is parsed as. - */ -public class ChildAdded extends FirebaseChildEvent { - - @JsonCreator - public ChildAdded( - @JsonProperty("key") String key, - @JsonProperty("data") T data, - @JsonProperty("previousChildName") String previousChildName) { - super(key, data, previousChildName); - } - - public ChildAdded(DataSnapshot snapshot, String previousChildName){ - super(snapshot, previousChildName); - } - - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java deleted file mode 100644 index c152639bd0..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildChanged.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; - -import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.firebase.client.ChildEventListener; -import com.firebase.client.DataSnapshot; - -/** - * Created by {@link ChildEventListener#onChildRemoved } triggered in {@link FirebaseSource}. - * @param - */ -public class ChildChanged extends FirebaseChildEvent { - - @JsonCreator - public ChildChanged( - @JsonProperty("key") String key, - @JsonProperty("data") T data, - @JsonProperty("previousChildName") String previousChildName) { - super(key, data, previousChildName); - } - - public ChildChanged(DataSnapshot snapshot, String previousChildName){ - super(snapshot, previousChildName); - } - - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java deleted file mode 100644 index c0193f76fa..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildMoved.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.firebase.client.DataSnapshot; - -/** - * TODO: Insert description here. (generated by elibixby) - * @param type that {@link DataSnapshot} is parsed as. - */ -public class ChildMoved extends FirebaseChildEvent { - - @JsonCreator - public ChildMoved( - @JsonProperty("key") String key, - @JsonProperty("data") T data, - @JsonProperty("previousChildName") String previousChildName) { - super(key, data, previousChildName); - } - - public ChildMoved(DataSnapshot snapshot, String previousChildName){ - super(snapshot, previousChildName); - } - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java deleted file mode 100644 index 97e1e38204..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildRemoved.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; - -import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.firebase.client.ChildEventListener; -import com.firebase.client.DataSnapshot; - -/** - * Created by {@link ChildEventListener#onChildRemoved } triggered in {@link FirebaseSource}. - * @param type that {@link DataSnapshot} is parsed as. - */ -public class ChildRemoved extends FirebaseEvent { - - @JsonCreator - public ChildRemoved( - @JsonProperty("key") String key, - @JsonProperty("data") T data) { - super(key, data); - } - - public ChildRemoved(DataSnapshot snapshot){ - super(snapshot); - } - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java deleted file mode 100644 index e985478553..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseChildEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; - -import com.firebase.client.DataSnapshot; - -import java.util.Objects; - -/** - * TODO: Super class for events which come with a {@code previousChildName}. - * @param type that {@link DataSnapshot} is parsed as. - */ -public class FirebaseChildEvent extends FirebaseEvent { - - public final String previousChildName; - - protected FirebaseChildEvent(String key, T data, String previousChildName) { - super(key, data); - this.previousChildName = previousChildName; - } - - protected FirebaseChildEvent(DataSnapshot snapshot, String previousChildName) { - super(snapshot); - this.previousChildName = previousChildName; - } - - @Override - public int hashCode(){ - return Objects.hash(previousChildName, super.hashCode()); - } - - @Override - public boolean equals(Object e){ - if (this.getClass().isInstance(e)){ - FirebaseChildEvent other = (FirebaseChildEvent) e; - return Objects.equals(this.previousChildName, other.previousChildName) && super.equals(e); - } - return false; - } -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java deleted file mode 100644 index 276252cd2d..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/FirebaseEvent.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; -import com.fasterxml.jackson.databind.SerializationFeature; - -import com.firebase.client.DataSnapshot; -import com.firebase.client.GenericTypeIndicator; - -import java.util.Objects; - -/** - * Supertype for all {@link FirebaseEvent}s. - * @param type that {@link DataSnapshot} is parsed as. -**/ -public class FirebaseEvent{ - - private static ObjectMapper mapper = new ObjectMapper() - .enableDefaultTyping(DefaultTyping.NON_FINAL) - .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); - - public final String key; - public final T data; - - protected FirebaseEvent(String key, T data){ - this.key = key; - this.data = data; - } - - protected FirebaseEvent(DataSnapshot snapshot){ - this(snapshot.getKey(), snapshot.getValue(new GenericTypeIndicator(){})); - } - - @Override - public int hashCode(){ - return Objects.hash(key, data); - } - - /** - * Does a deep equality check by delegating to {@code T.equals()}. - */ - @Override - public boolean equals(Object e){ - if (this.getClass().isInstance(e)){ - FirebaseEvent other = (FirebaseEvent) e; - return Objects.equals(this.key, other.key) && Objects.equals(this.data, other.data); - } - return false; - } - - @Override - public String toString(){ - try { - return mapper.writeValueAsString(this); - } catch (JsonProcessingException e) { - return e.toString(); - } - } -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java deleted file mode 100644 index 3c29a96c7e..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ValueChanged.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.events; - -import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.firebase.client.DataSnapshot; -import com.firebase.client.ValueEventListener; - - - -/** - * Created by {@link ValueEventListener#onDataChange } triggered in {@link FirebaseSource}. - * @param type that {@link DataSnapshot} is parsed as. - */ -public class ValueChanged extends FirebaseEvent { - - @JsonCreator - public ValueChanged( - @JsonProperty("key") String key, - @JsonProperty("data") T data) { - super(key, data); - } - - public ValueChanged(DataSnapshot snapshot){ - super(snapshot); - } - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java deleted file mode 100644 index 52e0bf5b63..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebasePush.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.values.KV; - -import com.firebase.client.Firebase; - - - -/** - * Creates a unique String ID using {@link Firebase#push()} and outputs an - * {@link com.google.cloud.dataflow.sdk.values.KV} with the String as a key. - */ -public class DoFirebasePush extends FirebaseDoFn> { - - private static final long serialVersionUID = -2377431649046447957L; - - public DoFirebasePush(String url, FirebaseAuthenticator auther) { - super(url, auther); - } - - @Override - public void processElement(DoFn>.ProcessContext context) { - context.output(KV.of(root.push().getKey(), context.element())); - } - - - @Override - public void asyncProcessElement(DoFn>.ProcessContext context, - FirebaseDoFn>.FirebaseListener listener) { - //Call is synchronous, this will not be called - } - -} - - diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java deleted file mode 100644 index 55d0fe2302..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSet.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.values.KV; -import com.firebase.client.Firebase; - -/** - * Sets a value using {@link Firebase#setValue(Object)} where the {@code String} key is the - * path to the child to set the value on. Set a path as {@code null} to remove a value. - */ -public class DoFirebaseSet extends FirebaseDoFn, Void> { - - private static final long serialVersionUID = -4587959210797506754L; - - public DoFirebaseSet(String url, FirebaseAuthenticator auther) { - super(url, auther); - } - - @Override - public void asyncProcessElement(DoFn, Void>.ProcessContext context, - FirebaseDoFn, Void>.FirebaseListener listener) { - root.child(context.element().getKey()) - .setValue(context.element().getValue(), listener); - } -} - - diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java deleted file mode 100644 index 973aabca70..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseUpdate.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; - -import com.firebase.client.Firebase; - -import java.util.Map; - -/** - * Updates the element at the specified url, using {@link Firebase#updateChildren(Map)}. - */ -public class DoFirebaseUpdate extends FirebaseDoFn, Void> { - - private static final long serialVersionUID = 937268867072092459L; - - - public DoFirebaseUpdate(String url, FirebaseAuthenticator auther) { - super(url, auther); - } - - @Override - public void asyncProcessElement(DoFn, Void>.ProcessContext context, - FirebaseDoFn, Void>.FirebaseListener listener) { - root.updateChildren(context.element(), listener); - } - -} - - diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java deleted file mode 100644 index 20eeef3c42..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseDoFn.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; - -import com.google.cloud.dataflow.sdk.transforms.DoFn; - -import com.firebase.client.Firebase; -import com.firebase.client.Firebase.CompletionListener; -import com.firebase.client.FirebaseError; - -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -/** - * Abstract superclass for DoFns that need a {@link Firebase} ref. - * This class allows concurrent writes to a Firebase within a bundle and blocks once all writes in - * the bundle are complete, by sharing a single lock across the bundle - * (via the {@code FirebaseListener} class) - */ -public abstract class FirebaseDoFn extends DoFn { - - private static final long serialVersionUID = 2668706582381990870L; - - final String url; - final FirebaseAuthenticator auther; - - transient Firebase root; - private transient Semaphore lock; - - /** - * Releases a permit on the {@link Semaphore} when - * {@link CompletionListener#onComplete(FirebaseError, Firebase)} is called. - */ - protected class FirebaseListener implements CompletionListener{ - @Override - public void onComplete(FirebaseError err, Firebase arg1) { - lock.release(); - if (err != null){ - throw err.toException(); - } - } - } - - /** - * @param url Fully qualified address to the Firebase ref which this DoFn uses. - * @param auther Used to authenticate to Firebase - */ - public FirebaseDoFn(String url, FirebaseAuthenticator auther){ - this.url = url; - this.auther = auther; - } - - @Override - public void startBundle(Context c) throws Exception { - root = new Firebase(this.url); - auther.authenticate(root); - //No need to throttle, that will be taken care of by bundle size - lock = new Semaphore(Integer.MAX_VALUE); - } - - /** - * @param context ProcessContext from the Pipeline - * @param listener Used to indicate when the asynchronous operation is complete - */ - public abstract void asyncProcessElement( - DoFn.ProcessContext context, - FirebaseListener listener); - - @Override - public void processElement(DoFn.ProcessContext context) - throws InterruptedException{ - lock.acquire(); - this.asyncProcessElement(context, new FirebaseListener()); - } - - @Override - public void finishBundle(Context c) throws InterruptedException{ - //Wait "forever" - lock.tryAcquire(Integer.MAX_VALUE, Long.MAX_VALUE, TimeUnit.DAYS); - } -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java deleted file mode 100644 index 2ffff2bdf7..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseSource.java +++ /dev/null @@ -1,406 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.contrib.firebase.events.ChildAdded; -import com.google.cloud.dataflow.contrib.firebase.events.ChildChanged; -import com.google.cloud.dataflow.contrib.firebase.events.ChildMoved; -import com.google.cloud.dataflow.contrib.firebase.events.ChildRemoved; -import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; -import com.google.cloud.dataflow.contrib.firebase.events.ValueChanged; - -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseCheckpoint; -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseCheckpointCoder; -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseEventCoder; -import com.google.cloud.dataflow.contrib.firebase.utils.Record; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import com.fasterxml.jackson.databind.ObjectWriter; -import com.firebase.client.AuthData; -import com.firebase.client.ChildEventListener; -import com.firebase.client.DataSnapshot; -import com.firebase.client.Firebase; -import com.firebase.client.Firebase.CompletionListener; -import com.firebase.client.FirebaseError; -import com.firebase.client.FirebaseException; -import com.firebase.client.Query; -import com.firebase.client.ServerValue; -import com.firebase.client.ValueEventListener; - -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.CountDownLatch; - - - -import javax.annotation.Nullable; - - - - -/** - * Reads events from a {@code Query} and outputs them as {@link FirebaseEvent}s. - * @param Type of object to deserialize {@link DataSnapshot}s into. E.g. {@link java.util.Map} - */ -public class FirebaseSource - extends UnboundedSource, FirebaseCheckpoint> { - - private static final long serialVersionUID = 5926529400127617094L; - - /** - * Uses {@link FirebaseCheckpoint} to build a priority queue based on event time, - * for events triggered by listeners specified in {@link FirebaseSource} construction. - **/ - public class FirebaseReader extends UnboundedReader>{ - - private final FirebaseSource source; - private final MessageDigest digest; - private final Firebase timestampRef; - private final FirebaseCheckpoint checkpoint; - private final Firebase ref; - private ValueEventListener valueListener; - private ChildEventListener childListener; - private FirebaseError error = null; - - FirebaseReader( - FirebaseSource source, - FirebaseCheckpoint checkpoint) { - this.source = source; - try { - this.digest = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - if (checkpoint == null){ - this.checkpoint = new FirebaseCheckpoint<>(); - } else { - this.checkpoint = checkpoint.reset(); - } - this.ref = this.source.getRef(); - this.valueListener = makeValueListener(); - this.childListener = makeChildListener(); - this.timestampRef = this.ref.getRoot().child( - Integer.toHexString(this.hashCode()) + Long.toHexString(System.currentTimeMillis())); - } - - private ValueEventListener makeValueListener() { - return new ValueEventListener(){ - - @Override - public void onCancelled(FirebaseError err) { - error = err; - } - - @Override - public void onDataChange(DataSnapshot snapshot) { - wrapEventWithInstant(new ValueChanged( - snapshot)); - } - }; - } - - private ChildEventListener makeChildListener() { - return new ChildEventListener(){ - @Override - public void onCancelled(FirebaseError err) { - error = err; - } - - @Override - public void onChildAdded(DataSnapshot snapshot, String previousChildName) { - wrapEventWithInstant(new ChildAdded( - snapshot, - previousChildName)); - } - - @Override - public void onChildChanged(DataSnapshot snapshot, String previousChildName) { - wrapEventWithInstant(new ChildChanged( - snapshot, - previousChildName)); - } - - @Override - public void onChildMoved(DataSnapshot snapshot, String previousChildName) { - wrapEventWithInstant(new ChildMoved( - snapshot, - previousChildName)); - } - - @Override - public void onChildRemoved(DataSnapshot snapshot) { - wrapEventWithInstant(new ChildRemoved( - snapshot)); - } - }; - } - - /** - * On receiving an event, {@link FirebaseReader} sets the {@link ServerValue#TIMESTAMP} - * in the Firebase which will be populated with the current server time. This will trigger - * a value change event, which can be used to retrieve a timestamp. Effectively this method - * delegates dealing with clock drift between shards to the Firebase servers. Since events are - * always processed in order by a single client, timestamps will be in the order events were - * recieved. - * @param event {@link FirebaseEvent} to wrap - */ - private void wrapEventWithInstant(final FirebaseEvent event){ - timestampRef.setValue(ServerValue.TIMESTAMP, new CompletionListener(){ - @Override - public void onComplete(FirebaseError err, Firebase ref) { - if (err != null){ - error = err; - } - ref.addListenerForSingleValueEvent(new ValueEventListener(){ - @Override - public void onCancelled(FirebaseError err) { - error = err; - } - @Override - public void onDataChange(DataSnapshot timestamp) { - checkpoint.put(new Record<>( - new Instant(timestamp.getValue(Long.class)), - event)); - } - }); - } - }); - } - - @Override - public boolean advance() throws IOException { - if (error == null){ - return this.checkpoint.advance(); - } - throw error.toException(); - } - - @Override - public CheckpointMark getCheckpointMark() { - return checkpoint; - } - - @Override - public byte[] getCurrentRecordId() throws NoSuchElementException { - return digest.digest( - ByteBuffer.allocate(12).putInt( - this.checkpoint.read().data.hashCode()).putLong( - this.checkpoint.read().timestamp.getMillis()).array()); - } - - @Override - public UnboundedSource, ?> getCurrentSource() { - return this.source; - } - - @Override - public Instant getWatermark() { - return this.checkpoint.minTimestamp(); - } - - @Override - public boolean start() throws IOException { - try { - this.source.auther.authenticate(this.ref); - } catch (Exception e) { - throw new IOException(e); - } - if (this.source.listenForChildEvents){ - this.childListener = this.ref.addChildEventListener(this.childListener); - } - if (this.source.listenForValueEvents){ - this.valueListener = this.ref.addValueEventListener(this.valueListener); - } - return this.advance(); - } - - @Override - public void close() throws IOException { - if (this.source.listenForChildEvents) { - this.ref.removeEventListener(this.childListener); - } - if (this.source.listenForValueEvents){ - this.ref.removeEventListener(this.valueListener); - } - final CountDownLatch lock = new CountDownLatch(1); - timestampRef.removeValue(new CompletionListener(){ - - @Override - public void onComplete(FirebaseError err, Firebase arg1) { - lock.countDown(); - if (err != null){ - throw err.toException(); - } - } - }); - try { - lock.await(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException(); - } - } - - /** - * @see com.google.cloud.dataflow.sdk.io.Source.Reader#getCurrent() - **/ - @Override - public FirebaseEvent getCurrent() throws NoSuchElementException { - if (this.checkpoint.read() == null){ - throw new NoSuchElementException(); - } - return this.checkpoint.read().data; - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - if (this.checkpoint.read() == null){ - throw new NoSuchElementException(); - } - return this.checkpoint.read().timestamp; - } - } - - private final String queryString; - private final FirebaseAuthenticator auther; - private final boolean listenForChildEvents; - private final boolean listenForValueEvents; - private final Class clazz; - private final Logger logger = LoggerFactory.getLogger(FirebaseSource.class); - - /** - * @see FirebaseSource#of(Class, FirebaseAuthenticator, Query) - * @return A FirebaseSource that uses only a {@link ChildEventListener} - */ - public static FirebaseSource childListenerOf( - Class clazz, - FirebaseAuthenticator auther, - Query query){ - return new FirebaseSource<>(clazz, auther, query, true, false); - } - - /** - * @see FirebaseSource#of(Class, FirebaseAuthenticator, Query) - * @return A FirebaseSource that uses only a {@link ValueEventListener} - */ - public static FirebaseSource valueListenerOf( - Class clazz, - FirebaseAuthenticator auther, - Query query){ - return new FirebaseSource<>(clazz, auther, query, false, true); - } - - /** - * @param clazz determines the type of data the {@link DataSnapshot}s received from Firebase - * servers will be unmarshalled into, and serialized and deserialized. Any POJO which is - * serializable as a JSON Object by an {@link ObjectWriter} will work. - * @param auther Used to authenticate to Firebase - * @param query The {@link Query} which will create events passed on to the pipeline. - * @return A FirebaseSource that uses both a {@link ChildEventListener} and a - * {@link ValueEventListener} - */ - public static FirebaseSource of( - Class clazz, - FirebaseAuthenticator auther, - Query query){ - return new FirebaseSource<>(clazz, auther, query, true, true); - } - - /** - * @param clazz Class Reference for the type to deserialize {@link DataSnapshot}s into. - * @param auther Authenticator - * @param query Any {@link Query} reference. - * @param listenForChildEvents Adds a {@link ChildEventListener} during runtime - * @param listenForValueEvents Adds a {@link ValueEventListener} during runtime - */ - protected FirebaseSource( - Class clazz, - FirebaseAuthenticator auther, - Query query, - boolean listenForChildEvents, - boolean listenForValueEvents){ - if (query.toString().equals(query.getRef().getRoot().toString())){ - throw new IllegalArgumentException("Cannot use a reference to the root of a Firebase " - + "repository. Since FirebaseSource uses a ref at the root of the repository to store" - + "timestamps, this will result in an endless event loop, which will livelock your" - + "pipeline."); - } - this.clazz = clazz; - this.auther = auther; - this.queryString = query.getRef().toString(); - this.listenForChildEvents = listenForChildEvents; - this.listenForValueEvents = listenForValueEvents; - } - - protected Firebase getRef(){ - return new Firebase(this.queryString); - } - - @SuppressWarnings("unchecked") - @Override - public List, FirebaseCheckpoint>> - generateInitialSplits( - int numSplits, PipelineOptions arg1) throws Exception { - return Collections.singletonList(this); - } - - @Override - public Coder> getDefaultOutputCoder() { - return FirebaseEventCoder.of(new TypeDescriptor>(){}, this.clazz); - } - - @Override - public void validate() { - AuthData result; - try { - result = auther.authenticate(this.getRef()); - } catch (FirebaseException e) { - throw new RuntimeException("Authenticator failed to authenticate", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException("Thread interrupted while waiting for authentication to complete", e); - } - checkNotNull(result, "If result is null, authenticators is "); - } - - @Override - public UnboundedReader> createReader( - PipelineOptions arg0, @Nullable FirebaseCheckpoint arg1) { - return new FirebaseReader(this, arg1); - } - - @Override - public Coder> getCheckpointMarkCoder() { - return FirebaseCheckpointCoder.of(new TypeDescriptor>(){}, this.clazz); - } - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java deleted file mode 100644 index c7e49f02cf..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseAuthenticator.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; -import com.firebase.client.AuthData; -import com.firebase.client.Firebase; -import com.firebase.client.FirebaseException; - -import java.io.Serializable; - -/** - * Wrapper for the many {@link Firebase} auth methods. - */ -public abstract class FirebaseAuthenticator implements Serializable { - - private static final long serialVersionUID = 2795829710483502835L; - - public abstract AuthData authenticate(Firebase firebase) - throws FirebaseException, InterruptedException; - - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java deleted file mode 100644 index 8259a1f1fc..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpoint.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; - -import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource.FirebaseReader; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; - -import java.io.IOException; -import java.util.Arrays; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.PriorityBlockingQueue; - -import javax.annotation.Nullable; - -/** - * Maintains a {@link PriorityBlockingQueue} to store the {@link Record}s created by - * {@link FirebaseReader}, on error these records are replayed on the new Reader to prevent - * dataloss. - * @param - */ -public class FirebaseCheckpoint implements CheckpointMark { - - //Oldest on top - private PriorityBlockingQueue> unread; - private LinkedBlockingQueue> read; - - private Record cur; - - @JsonCreator - public FirebaseCheckpoint( - @JsonProperty("read") Record[] read, - @JsonProperty("unread") Record[] unread, - @JsonProperty("cur") Record cur){ - this.read = new LinkedBlockingQueue<>(read.length); - this.read.addAll(Arrays.asList(read)); - this.unread = new PriorityBlockingQueue<>(unread.length); - this.unread.addAll(Arrays.asList(unread)); - this.cur = cur; - } - - public FirebaseCheckpoint(){ - this.unread = new PriorityBlockingQueue<>(); - this.read = new LinkedBlockingQueue<>(); - } - - @Override - public void finalizeCheckpoint() throws IOException { - this.read = new LinkedBlockingQueue<>(); - } - - public Instant minTimestamp(){ - @Nullable Record next = unread.peek(); - // NOTE: records compare using their timestamps - if (next == null || cur.compareTo(next) < 0) { - return cur.timestamp; - } else { - return next.timestamp; - } - } - - public FirebaseCheckpoint reset(){ - unread.addAll(read); - try { - this.finalizeCheckpoint(); - } catch (IOException e) { - e.printStackTrace(); - } - return this; - } - - public void put(Record e){ - unread.put(e); - } - - public Record read(){ - return this.cur; - } - - public boolean advance(){ - if (cur != null){ - read.add(cur); - } - cur = unread.poll(); - return cur != null; - } - - /** - * For {@link FirebaseCheckpointCoder}. - */ - @SuppressWarnings("unchecked") - public Record[] getRead(){ - return this.read.toArray(new Record[read.size()]); - } - - /** - * For {@link FirebaseCheckpointCoder}. - */ - @SuppressWarnings("unchecked") - public Record[] getUnread(){ - return this.unread.toArray(new Record[unread.size()]); - } - - public Record getCur(){ - return this.cur; - } - - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java deleted file mode 100644 index fda469c96c..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseCheckpointCoder.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; - -import static com.google.cloud.dataflow.sdk.util.Structs.addString; -import com.google.cloud.dataflow.contrib.firebase.contrib.JacksonCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - - - -/** - * @see JacksonCoder - * Subclassed to allow parameterized type to behave property - * @param Type of {@link Record} encoded by {@link FirebaseCheckpoint} - */ -public class FirebaseCheckpointCoder extends JacksonCoder> { - private final Class subType; - - @SuppressWarnings("unchecked") - public FirebaseCheckpointCoder(TypeDescriptor> type, Class subType) { - this((Class>) type.getRawType(), subType); - } - - public FirebaseCheckpointCoder(Class> type, Class subType) { - super(type); - this.subType = subType; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @JsonCreator - public static FirebaseCheckpointCoder of( - @JsonProperty("type") String classType, - @JsonProperty("subType") String subClassType) throws ClassNotFoundException { - return new FirebaseCheckpointCoder(Class.forName(classType), Class.forName(subClassType)); - } - - public static FirebaseCheckpointCoder of( - TypeDescriptor> type, - Class subType) { - return new FirebaseCheckpointCoder(type, subType); - } - - @Override - protected Object writeReplace() { - // When serialized by Java, instances of FirebaseCheckpointCoder should be replaced by - // a SerializedAvroCoderProxy. - return new FirebaseJacksonCoderProxy<>(type, subType); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addString(result, "subType", subType.getName()); - return result; - } - - public Class getSubType(){ - return this.subType; - } - - - /** - * Serialization proxy to allow fields to be final. - * @param Type of {@link Record} encoded by {@link FirebaseCheckpoint} - */ - protected static class FirebaseJacksonCoderProxy - extends SerializedJacksonCoderProxy>{ - - private final Class subType; - - /** - * @param type - */ - public FirebaseJacksonCoderProxy(Class> type, Class subType) { - super(type); - this.subType = subType; - } - - private Object readResolve() { - // When deserialized, instances of this object should be replaced by - // constructing a FirebaseJacksonCoder. - return new FirebaseCheckpointCoder(this.type, this.subType); - } - - } - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java deleted file mode 100644 index f078fe55e5..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEmptyAuthenticator.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; - -import com.firebase.client.AuthData; -import com.firebase.client.Firebase; -import com.firebase.client.FirebaseException; - -/** - * Dummy authenticator for test instances of {@link Firebase}. - */ -public class FirebaseEmptyAuthenticator extends FirebaseAuthenticator { - - private static final long serialVersionUID = 7664558699766082532L; - - @Override - public AuthData authenticate(Firebase firebase) throws FirebaseException { - return new AuthData(null, 0, null, null, null, null); - } -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java deleted file mode 100644 index aad2cd7396..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebaseEventCoder.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; - -import static com.google.cloud.dataflow.sdk.util.Structs.addString; - -import com.google.cloud.dataflow.contrib.firebase.contrib.JacksonCoder; -import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.values.TypeDescriptor; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - - -/** - * Coder for {@link FirebaseEvent}. Subclasses {@link JacksonCoder} so that parameterized types - * behave properly. - */ -public class FirebaseEventCoder extends JacksonCoder> { - - private final Class subType; - - @SuppressWarnings("unchecked") - public FirebaseEventCoder(TypeDescriptor> type, Class subType) { - this((Class>) type.getRawType(), subType); - } - - public FirebaseEventCoder(Class> type, Class subType) { - super(type); - this.subType = subType; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @JsonCreator - public static FirebaseEventCoder of( - @JsonProperty("type") String classType, - @JsonProperty("subType") String subClassType) throws ClassNotFoundException { - return new FirebaseEventCoder(Class.forName(classType), Class.forName(subClassType)); - } - - public static FirebaseEventCoder of( - TypeDescriptor> type, - Class subType) { - return new FirebaseEventCoder(type, subType); - } - - @Override - protected Object writeReplace() { - // When serialized by Java, instances of FirebaseEventCoder should be replaced by - // a SerializedAvroCoderProxy. - return new FirebaseJacksonCoderProxy<>(type, subType); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addString(result, "subType", subType.getName()); - return result; - } - - public Class getSubType(){ - return this.subType; - } - - /** - * Proxy to allow internal fields to be final. - * @param @see FirebaseEvent - */ - protected static class FirebaseJacksonCoderProxy - extends SerializedJacksonCoderProxy>{ - - private final Class subType; - - /** - * @param type - */ - public FirebaseJacksonCoderProxy(Class> type, Class subType) { - super(type); - this.subType = subType; - } - - private Object readResolve() { - // When deserialized, instances of this object should be replaced by - // constructing an AvroCoder. - return new FirebaseEventCoder(this.type, this.subType); - } - - } - - -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java deleted file mode 100644 index f5850331e1..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/FirebasePasswordAuthenticator.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; - -import com.firebase.client.AuthData; -import com.firebase.client.Firebase; -import com.firebase.client.Firebase.AuthResultHandler; -import com.firebase.client.FirebaseError; -import com.firebase.client.FirebaseException; - -import java.util.concurrent.CountDownLatch; - -/** - * Wrapper for {@link Firebase#authWithPassword(String, String, AuthResultHandler)}. - */ -public class FirebasePasswordAuthenticator extends FirebaseAuthenticator { - - private static final long serialVersionUID = -3274906800271012577L; - private final String email; - private final String password; - private transient AuthData result; - - public FirebasePasswordAuthenticator(String email, String password){ - this.email = email; - this.password = password; - } - - @Override - public AuthData authenticate(Firebase firebase) throws FirebaseException, InterruptedException { - final CountDownLatch done = new CountDownLatch(1); - firebase.authWithPassword(this.email, this.password, new AuthResultHandler() { - @Override - public void onAuthenticationError(FirebaseError err) { - done.countDown(); - throw err.toException(); - } - @Override - public void onAuthenticated(AuthData arg0) { - result = arg0; - done.countDown(); - } - }); - done.await(); - return result; - } -} diff --git a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java b/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java deleted file mode 100644 index b8e57b2327..0000000000 --- a/contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/utils/Record.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.utils; - -import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.joda.time.Instant; - - - -/** - * Wrapper for a {@link FirebaseEvent} and a {@link Instant}. - * @param @see FirebaseDataEvent - */ -public class Record implements Comparable>{ - - public final Instant timestamp; - public final FirebaseEvent data; - - @JsonCreator - public Record( - @JsonProperty("timestamp") Instant timestamp, - @JsonProperty("event") FirebaseEvent event){ - this.timestamp = timestamp; - this.data = event; - } - - @Override - public int compareTo(Record o) { - return this.timestamp.compareTo(o.timestamp); - } -} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java deleted file mode 100644 index 0c96e657a0..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/BaseFirebaseSourceTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.contrib.LogElements; -import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseEmptyAuthenticator; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.firebase.client.ChildEventListener; -import com.firebase.client.Firebase; -import com.firebase.client.Firebase.CompletionListener; -import com.firebase.client.FirebaseError; -import com.firebase.client.ValueEventListener; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.event.Level; - -import java.io.IOException; -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - - - -/** - * Archetype for comparing events produced by through {@link FirebaseSource} with events surfaced - * by the unmodified {@link ChildEventListener} and {@link ValueEventListener}. - **/ -@RunWith(JUnit4.class) -public abstract class BaseFirebaseSourceTest { - - /** - * Logs all the added entries! - **/ - private class LoggingArrayList extends ArrayList { - private Logger logger; - - LoggingArrayList(Logger logger){ - this.logger = logger; - } - - @Override - public boolean add(T e){ - logger.info(e.toString()); - return super.add(e); - } - - } - - FirebaseAuthenticator auther = new FirebaseEmptyAuthenticator(); - private Throwable err; - Firebase testRef; - - static final Logger LOGGER = LoggerFactory.getLogger(BaseFirebaseSourceTest.class); - - private final LoggingArrayList> expected = - new LoggingArrayList<>(LOGGER); - - @Before - public void setUp() throws IOException, InterruptedException { - - testRef = new Firebase("https://dataflowio.firebaseio-demo.com") - .child(Integer.toHexString(this.hashCode()) - + Long.toHexString(System.currentTimeMillis())); - - cleanFirebase(testRef); - - prepareData(new ObjectMapper().>>readValue( - ClassLoader.getSystemResourceAsStream("testdata.json"), - new TypeReference>() {})); - - } - - @After - public void teardown() throws InterruptedException{ - cleanFirebase(testRef); - } - - private Thread getPipelineThread(final Pipeline p){ - Thread t = new Thread(new Runnable(){ - @Override - public void run() { - LOGGER.info(p.run().getState().toString()); - } - }); - t.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){ - @Override - public void uncaughtException(Thread t, Throwable e) { - err = e; - } - }); - return t; - } - - private void cleanFirebase(Firebase f) throws InterruptedException{ - final CountDownLatch lock = new CountDownLatch(1); - f.removeValue(new CompletionListener(){ - @Override - public void onComplete(FirebaseError arg0, Firebase arg1) { - lock.countDown(); - } - }); - lock.await(); - } - - public abstract void prepareData(List> testData); - - public abstract void triggerEvents(Firebase f); - - public abstract void addListener(Firebase f, final Collection> events); - - public abstract void removeListener(Firebase f); - - public abstract FirebaseSource makeSource(FirebaseAuthenticator auther, - Firebase f); - - @Test - public void matchEvents() throws Throwable{ - - //Generate expected events - addListener(testRef, expected); - triggerEvents(testRef); - cleanFirebase(testRef); - removeListener(testRef); - LOGGER.info("At most " + expected.size() + " elements to look for in pipeline"); - - - FirebaseSource source = makeSource(auther, testRef); - - TestPipeline p = TestPipeline.create(); - - PCollection> events = p - .apply(Read.from(source).withMaxNumRecords(expected.size())); - - events.apply(new LogElements>(FirebaseChildTest.class, Level.INFO)); - - DataflowAssert.that(events).containsInAnyOrder(expected); - - //Test pipeline against expected events; - Thread t = getPipelineThread(p); - t.start(); - Thread.sleep(1500); - triggerEvents(testRef); - cleanFirebase(testRef); - t.join(); - if (err != null){ - throw err; - } - } - -} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java deleted file mode 100644 index 4fd74079d7..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildAddedTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.events.ChildAdded; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.values.KV; - -import com.firebase.client.Firebase; - -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; -import java.util.Map; - - - - -/** - * Triggers {@link ChildAdded} events. - */ -@RunWith(JUnit4.class) -public class ChildAddedTest extends FirebaseChildTest { - - private KV[] usableData; - - @Override - public void triggerEvents(Firebase f) { - DoFnTester.of(new DoFirebaseSet(f.toString(), auther)).processBatch(usableData); - } - - @SuppressWarnings("unchecked") - @Override - public void prepareData(List> testData) { - Object[] entries = testData.toArray(); - - List> withKeys = DoFnTester.of( - new DoFirebasePush(testRef.toString(), - auther)) - .processBatch(entries); - - usableData = withKeys.toArray(new KV[withKeys.size()]); - } -} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java deleted file mode 100644 index ce6d5dacae..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildChangedTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; - -import com.firebase.client.Firebase; - -import java.util.List; -import java.util.Map; - -/** - * TODO: Insert description here. (generated by elibixby) - */ -public class ChildChangedTest extends FirebaseChildTest { - - Map[] usableData; - - @SuppressWarnings("unchecked") - @Override - public void prepareData(List> testData) { - usableData = testData.toArray(new Map[testData.size()]); - } - - @Override - public void triggerEvents(Firebase f) { - DoFnTester.of(new DoFirebaseUpdate(f.toString(), auther)).processBatch(usableData); - } - -} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java deleted file mode 100644 index ce0d799af7..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildMovedTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.values.KV; - -import com.firebase.client.Firebase; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * TODO: Insert description here. (generated by elibixby) - */ -public class ChildMovedTest extends FirebaseChildTest { - - private KV>[] withPriority; - private KV>[] shuffle; - - @Override - public void triggerEvents(Firebase f) { - @SuppressWarnings("deprecation") - DoFnTester>, Void> setWithPriority = - DoFnTester.of(new DoFirebaseSetWithPriority(f.toString(), auther)); - - setWithPriority.processBatch(withPriority); - setWithPriority.processBatch(shuffle); - - } - - @SuppressWarnings("unchecked") - @Override - public void prepareData(List> testData) { - Set> entrySet = testData.get(0).entrySet(); - - withPriority = new KV[entrySet.size()]; - shuffle = new KV[entrySet.size()]; - - int i = 0; - for (Entry entry : entrySet){ - withPriority[i] = KV.of( - entry.getKey(), - KV.of( - entry.getValue(), - String.valueOf(i))); - shuffle[i] = KV.of( - entry.getKey(), - KV.of( - entry.getValue(), - String.valueOf((i + 1) % entrySet.size()))); - i++; - } - } -} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java deleted file mode 100644 index 04f61f2a91..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/ChildRemovedTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.events.ChildRemoved; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.values.KV; - -import com.firebase.client.Firebase; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * Triggers {@link ChildRemoved} events by adding a large number of data and removing it. - */ -public class ChildRemovedTest extends FirebaseChildTest { - - private KV[] someData; - private KV[] nulls; - - @SuppressWarnings("unchecked") - @Override - public void prepareData(List> testData) { - Set> entrySet = testData.get(0).entrySet(); - - nulls = new KV[entrySet.size()]; - someData = new KV[entrySet.size()]; - int i = 0; - for (Entry entry : entrySet){ - LOGGER.info(entry.getKey()); - nulls[i] = KV.of(entry.getKey(), null); - someData[i] = KV.of(entry.getKey(), entry.getValue()); - i++; - } - } - - @Override - public void triggerEvents(Firebase f) { - DoFnTester, Void> setter = DoFnTester.of( - new DoFirebaseSet(f.toString(), auther)); - setter.processBatch(someData); - setter.processBatch(nulls); - } -} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java deleted file mode 100644 index d3996910b4..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/DoFirebaseSetWithPriority.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.values.KV; - -import com.firebase.client.Firebase; - -/** - * Uses {@link Firebase#setValue(Object, Object)} to set an object with a priority. - * This is a bad pattern, and only used to trigger ChildMovedTest. Users should prefer - * {@link Firebase#orderByKey()} to {@link Firebase#orderByPriority()} and as such have no need - * to set priority. - */ -@Deprecated -class DoFirebaseSetWithPriority extends - FirebaseDoFn>, Void> { - - private static final long serialVersionUID = 1321447767620652932L; - - DoFirebaseSetWithPriority(String url, FirebaseAuthenticator auther) { - super(url, auther); - } - - @Override - public void asyncProcessElement( - DoFn>, Void>.ProcessContext context, - FirebaseDoFn>, Void>.FirebaseListener listener) { - root.child(context.element().getKey()) - .setValue( - context.element().getValue().getKey(), - context.element().getValue().getValue(), - listener); - } -} - diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java deleted file mode 100644 index e8a5409a48..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseChildTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.events.ChildAdded; -import com.google.cloud.dataflow.contrib.firebase.events.ChildChanged; -import com.google.cloud.dataflow.contrib.firebase.events.ChildMoved; -import com.google.cloud.dataflow.contrib.firebase.events.ChildRemoved; -import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; - -import com.fasterxml.jackson.databind.JsonNode; -import com.firebase.client.ChildEventListener; -import com.firebase.client.DataSnapshot; -import com.firebase.client.Firebase; -import com.firebase.client.FirebaseError; - -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collection; - -/** - * Parent test for all tests which trigger events in a {@link ChildEventListener}. - **/ -@RunWith(JUnit4.class) -public abstract class FirebaseChildTest extends BaseFirebaseSourceTest { - - ChildEventListener listener; - - @Override - public void addListener(Firebase f, final Collection> events) { - listener = f.addChildEventListener(new ChildEventListener(){ - - @Override - public void onCancelled(FirebaseError err) { } - - @Override - public void onChildAdded(DataSnapshot data, String previousChildName) { - events.add(new ChildAdded(data, previousChildName)); - } - - @Override - public void onChildChanged(DataSnapshot data, String previousChildName) { - events.add(new ChildChanged(data, previousChildName)); - } - - @Override - public void onChildMoved(DataSnapshot data, String previousChildName) { - events.add(new ChildMoved(data, previousChildName)); - } - - @Override - public void onChildRemoved(DataSnapshot data) { - events.add(new ChildRemoved(data)); - } - }); - } - - @Override - public void removeListener(Firebase f) { - f.removeEventListener(listener); - } - - @Override - public FirebaseSource makeSource( - FirebaseAuthenticator auther, - Firebase f) { - return FirebaseSource.childListenerOf(JsonNode.class, auther, f); - - } - -} diff --git a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java b/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java deleted file mode 100644 index 757df2bfbc..0000000000 --- a/contrib/firebaseio/src/test/java/com/google/cloud/dataflow/contrib/firebase/io/FirebaseValueTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2015 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.firebase.io; - -import com.google.cloud.dataflow.contrib.firebase.events.FirebaseEvent; -import com.google.cloud.dataflow.contrib.firebase.events.ValueChanged; -import com.google.cloud.dataflow.contrib.firebase.utils.FirebaseAuthenticator; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.firebase.client.DataSnapshot; -import com.firebase.client.Firebase; -import com.firebase.client.FirebaseError; -import com.firebase.client.ValueEventListener; - -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - - - -/** - * Triggers value changes. - * Potentially flakey since it relies on spacing out value changes to avoid events being - * globbed by Firebase Client Library - */ -@RunWith(JUnit4.class) -public class FirebaseValueTest extends BaseFirebaseSourceTest { - - ValueEventListener listener; - List> someData; - - @SuppressWarnings("unchecked") - @Override - public void prepareData(List> testData) { - someData = testData; - try { - LOGGER.info(new ObjectMapper().writeValueAsString(someData)); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - } - - @SuppressWarnings("unchecked") - @Override - public void triggerEvents(Firebase f) { - DoFnTester, Void> updater = DoFnTester.of( - new DoFirebaseUpdate(f.toString(), auther)); - for (Map data : someData){ - updater.processBatch(data); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - @Override - public void addListener(Firebase f, final Collection> events) { - listener = f.addValueEventListener(new ValueEventListener(){ - - @Override - public void onCancelled(FirebaseError err) { } - - @Override - public void onDataChange(DataSnapshot data) { - events.add(new ValueChanged(data)); - } - }); - } - - @Override - public void removeListener(Firebase f) { - f.removeEventListener(listener); - } - - @Override - public FirebaseSource makeSource( - FirebaseAuthenticator auther, - Firebase f) { - return FirebaseSource.valueListenerOf(JsonNode.class, auther, f); - } - -} diff --git a/contrib/firebaseio/src/test/resources/testdata.json b/contrib/firebaseio/src/test/resources/testdata.json deleted file mode 100644 index 34b5153fab..0000000000 --- a/contrib/firebaseio/src/test/resources/testdata.json +++ /dev/null @@ -1,302 +0,0 @@ -[ - { - "_id": "55e61a3012dc397360c371f2", - "index": 0, - "guid": "012118a4-5f74-460d-83f9-acfa91fb1bc3", - "isActive": false, - "balance": "$2,685.88", - "picture": "http://placehold.it/32x32", - "age": 28, - "eyeColor": "blue", - "name": { - "first": "Carrillo", - "last": "Cantrell" - }, - "company": "ENVIRE", - "email": "carrillo.cantrell@envire.me", - "phone": "+1 (923) 418-3207", - "address": "153 Nassau Street, Choctaw, Tennessee, 3970", - "about": "Ullamco labore eiusmod fugiat non culpa reprehenderit qui incididunt deserunt nisi minim sit voluptate excepteur. Esse sunt sunt cillum voluptate ea. Incididunt non anim aliquip qui Lorem aute veniam ad cupidatat.", - "registered": "Tuesday, March 17, 2015 10:20 AM", - "latitude": "-36.557494", - "longitude": "164.76669", - "tags": [ - "mollit", - "occaecat", - "et", - "non", - "est", - "deserunt", - "esse", - "custom_tag" - ], - "range": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9 - ], - "friends": [ - { - "id": 0, - "name": "Virginia Watkins" - }, - { - "id": 1, - "name": "Duffy Hancock" - }, - { - "id": 2, - "name": "Kelsey Hill" - } - ], - "greeting": "Hello, Carrillo! You have 9 unread messages.", - "favoriteFruit": "apple" - }, - { - "_id": "55e61a30a83a40606944bf81", - "index": 1, - "guid": "989508d7-8545-481f-b13d-d14e92e718cd", - "isActive": false, - "balance": "$3,122.94", - "picture": "http://placehold.it/32x32", - "age": 25, - "eyeColor": "blue", - "name": { - "first": "Priscilla", - "last": "Adkins" - }, - "company": "ZILLACON", - "email": "priscilla.adkins@zillacon.org", - "phone": "+1 (818) 547-3211", - "address": "137 Grant Avenue, Riverton, Rhode Island, 2077", - "about": "Irure sit ad occaecat et minim eu. Deserunt deserunt et enim fugiat. Ex commodo aliquip ad ipsum do aliquip sunt consectetur culpa dolore commodo. Reprehenderit aute amet aliquip enim esse magna do. Est nostrud amet voluptate magna est elit qui occaecat ea qui eu est sint. Aute exercitation sunt nostrud tempor cupidatat mollit culpa nulla labore.", - "registered": "Sunday, May 17, 2015 4:29 AM", - "latitude": "27.772689", - "longitude": "-46.103999", - "tags": [ - "mollit", - "occaecat", - "et", - "non", - "est", - "deserunt", - "esse", - "custom_tag" - ], - "range": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9 - ], - "friends": [ - { - "id": 0, - "name": "Virginia Watkins" - }, - { - "id": 1, - "name": "Duffy Hancock" - }, - { - "id": 2, - "name": "Kelsey Hill" - } - ], - "greeting": "Hello, Priscilla! You have 5 unread messages.", - "favoriteFruit": "apple" - }, - { - "_id": "55e61a3099c1283f4d6dd2ba", - "index": 2, - "guid": "4afb20cd-a10f-4aff-9433-6f91c70ad371", - "isActive": true, - "balance": "$1,120.38", - "picture": "http://placehold.it/32x32", - "age": 27, - "eyeColor": "blue", - "name": { - "first": "Kirk", - "last": "Clarke" - }, - "company": "ENERFORCE", - "email": "kirk.clarke@enerforce.us", - "phone": "+1 (862) 592-3458", - "address": "242 Euclid Avenue, Ronco, North Dakota, 4513", - "about": "Dolor elit ad excepteur labore do sint nisi voluptate Lorem et qui pariatur veniam sit. Amet in in eiusmod exercitation culpa quis enim fugiat sit. Duis magna ex laborum irure. Cillum culpa est mollit id enim do deserunt in officia. Elit mollit elit sit enim elit non.", - "registered": "Thursday, July 30, 2015 2:27 PM", - "latitude": "52.963677", - "longitude": "-48.650757", - "tags": [ - "mollit", - "occaecat", - "et", - "non", - "est", - "deserunt", - "esse", - "custom_tag" - ], - "range": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9 - ], - "friends": [ - { - "id": 0, - "name": "Virginia Watkins" - }, - { - "id": 1, - "name": "Duffy Hancock" - }, - { - "id": 2, - "name": "Kelsey Hill" - } - ], - "greeting": "Hello, Kirk! You have 9 unread messages.", - "favoriteFruit": "banana" - }, - { - "_id": "55e61a30c7cc81267cba07b1", - "index": 3, - "guid": "287199ca-5e64-4a25-b900-f23fee037d49", - "isActive": true, - "balance": "$3,579.20", - "picture": "http://placehold.it/32x32", - "age": 20, - "eyeColor": "green", - "name": { - "first": "Lillie", - "last": "Glenn" - }, - "company": "VISUALIX", - "email": "lillie.glenn@visualix.info", - "phone": "+1 (844) 476-3891", - "address": "127 Kingston Avenue, Roderfield, Arizona, 5033", - "about": "Officia tempor eu in voluptate. Ipsum nisi ut irure aliqua laborum excepteur cillum. Cillum ea eiusmod duis tempor quis ut. Est aute ipsum mollit consectetur exercitation fugiat pariatur minim.", - "registered": "Monday, June 23, 2014 7:10 AM", - "latitude": "39.351941", - "longitude": "-147.015315", - "tags": [ - "mollit", - "occaecat", - "et", - "non", - "est", - "deserunt", - "esse", - "custom_tag" - ], - "range": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9 - ], - "friends": [ - { - "id": 0, - "name": "Virginia Watkins" - }, - { - "id": 1, - "name": "Duffy Hancock" - }, - { - "id": 2, - "name": "Kelsey Hill" - } - ], - "greeting": "Hello, Lillie! You have 6 unread messages.", - "favoriteFruit": "strawberry" - }, - { - "_id": "55e61a30fc1bed5d41139b57", - "index": 4, - "guid": "4ae2f0d8-4648-4f9c-a0ae-8866c2ff07cb", - "isActive": true, - "balance": "$1,868.85", - "picture": "http://placehold.it/32x32", - "age": 30, - "eyeColor": "green", - "name": { - "first": "Hudson", - "last": "Blevins" - }, - "company": "DOGNOSIS", - "email": "hudson.blevins@dognosis.net", - "phone": "+1 (808) 407-3340", - "address": "554 Portland Avenue, Abrams, Illinois, 6182", - "about": "Pariatur elit tempor ut officia minim aliquip anim sint mollit. Nostrud fugiat exercitation irure veniam reprehenderit ad in consequat quis ea nisi. Eiusmod nisi nostrud consectetur nulla eiusmod ipsum excepteur do irure consectetur culpa velit fugiat. Nostrud sit ullamco nostrud eu exercitation labore. Quis magna laboris et consequat. Sit fugiat nisi amet sint culpa ullamco.", - "registered": "Friday, December 5, 2014 5:28 AM", - "latitude": "0.694342", - "longitude": "104.825617", - "tags": [ - "mollit", - "occaecat", - "et", - "non", - "est", - "deserunt", - "esse", - "custom_tag" - ], - "range": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9 - ], - "friends": [ - { - "id": 0, - "name": "Virginia Watkins" - }, - { - "id": 1, - "name": "Duffy Hancock" - }, - { - "id": 2, - "name": "Kelsey Hill" - } - ], - "greeting": "Hello, Hudson! You have 8 unread messages.", - "favoriteFruit": "strawberry" - } -] \ No newline at end of file diff --git a/contrib/hadoop/AUTHORS.md b/contrib/hadoop/AUTHORS.md deleted file mode 100644 index 6effdb917d..0000000000 --- a/contrib/hadoop/AUTHORS.md +++ /dev/null @@ -1,7 +0,0 @@ -# Authors of 'hadoop' module - -The following is the official list of authors for copyright purposes of this community-contributed module. - - Cloudera - Tom White, tom [at] cloudera [dot] com - Google Inc. \ No newline at end of file diff --git a/contrib/hadoop/README.md b/contrib/hadoop/README.md deleted file mode 100644 index 49bbf980e8..0000000000 --- a/contrib/hadoop/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Hadoop module - -This library provides Dataflow sources and sinks to make it possible to read and -write Apache Hadoop file formats from Dataflow pipelines. - -Currently, only the read path is implemented. A `HadoopFileSource` allows any -Hadoop `FileInputFormat` to be read as a `PCollection`. - -A `HadoopFileSource` can be read from using the -`com.google.cloud.dataflow.sdk.io.Read` transform. For example: - -```java -HadoopFileSource source = HadoopFileSource.from(path, MyInputFormat.class, - MyKey.class, MyValue.class); -PCollection> records = Read.from(mySource); -``` - -Alternatively, the `readFrom` method is a convenience method that returns a read -transform. For example: - -```java -PCollection> records = HadoopFileSource.readFrom(path, - MyInputFormat.class, MyKey.class, MyValue.class); -``` diff --git a/contrib/hadoop/pom.xml b/contrib/hadoop/pom.xml deleted file mode 100644 index 0659e3ebaa..0000000000 --- a/contrib/hadoop/pom.xml +++ /dev/null @@ -1,170 +0,0 @@ - - - - 4.0.0 - - com.google.cloud.dataflow - google-cloud-dataflow-java-contrib-hadoop - Google Cloud Dataflow Hadoop Library - Library to read and write Hadoop file formats from Dataflow. - 0.0.1-SNAPSHOT - jar - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - [1.2.0,2.0.0) - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.7 - 1.7 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.puppycrawl.tools - checkstyle - 6.19 - - - - ../../checkstyle.xml - ../../suppressions.xml - true - true - true - - - - - check - - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - compile - - jar - - - - attach-test-sources - test-compile - - test-jar - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - Google Cloud Dataflow Hadoop Contrib - Google Cloud Dataflow Hadoop Contrib - - com.google.cloud.dataflow.contrib.hadoop - false - ]]> - - - - https://cloud.google.com/dataflow/java-sdk/JavaDoc/ - ${basedir}/../../javadoc/dataflow-sdk-docs - - - http://docs.guava-libraries.googlecode.com/git-history/release18/javadoc/ - ${basedir}/../../javadoc/guava-docs - - - - - - - jar - - package - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${google-cloud-dataflow-version} - - - - - org.apache.hadoop - hadoop-client - 2.7.0 - provided - - - - - org.hamcrest - hamcrest-all - 1.3 - test - - - - junit - junit - 4.11 - test - - - diff --git a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java deleted file mode 100644 index e8981d2d6a..0000000000 --- a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow Hadoop Library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.hadoop; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.FileStatus; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.Writable; -import org.apache.hadoop.io.WritableUtils; -import org.apache.hadoop.mapreduce.InputSplit; -import org.apache.hadoop.mapreduce.Job; -import org.apache.hadoop.mapreduce.JobContext; -import org.apache.hadoop.mapreduce.RecordReader; -import org.apache.hadoop.mapreduce.TaskAttemptContext; -import org.apache.hadoop.mapreduce.TaskAttemptID; -import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; -import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; -import java.io.Externalizable; -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import javax.annotation.Nullable; - -/** - * A {@code BoundedSource} for reading files resident in a Hadoop filesystem using a - * Hadoop file-based input format. - * - *

              To read a {@link com.google.cloud.dataflow.sdk.values.PCollection} of - * {@link com.google.cloud.dataflow.sdk.values.KV} key-value pairs from one or more - * Hadoop files, use {@link HadoopFileSource#from} to specify the path(s) of the files to - * read, the Hadoop {@link org.apache.hadoop.mapreduce.lib.input.FileInputFormat}, the - * key class and the value class. - * - *

              A {@code HadoopFileSource} can be read from using the - * {@link com.google.cloud.dataflow.sdk.io.Read} transform. For example: - * - *

              - * {@code
              - * HadoopFileSource source = HadoopFileSource.from(path, MyInputFormat.class,
              - *   MyKey.class, MyValue.class);
              - * PCollection> records = Read.from(mySource);
              - * }
              - * 
              - * - *

              The {@link HadoopFileSource#readFrom} method is a convenience method - * that returns a read transform. For example: - * - *

              - * {@code
              - * PCollection> records = HadoopFileSource.readFrom(path,
              - *   MyInputFormat.class, MyKey.class, MyValue.class);
              - * }
              - * 
              - * - * Implementation note: Since Hadoop's {@link org.apache.hadoop.mapreduce.lib.input.FileInputFormat} - * determines the input splits, this class extends {@link BoundedSource} rather than - * {@link com.google.cloud.dataflow.sdk.io.OffsetBasedSource}, since the latter - * dictates input splits. - - * @param The type of keys to be read from the source. - * @param The type of values to be read from the source. - */ -public class HadoopFileSource extends BoundedSource> { - private static final long serialVersionUID = 0L; - - private final String filepattern; - private final Class> formatClass; - private final Class keyClass; - private final Class valueClass; - private final SerializableSplit serializableSplit; - - /** - * Creates a {@code Read} transform that will read from an {@code HadoopFileSource} - * with the given file name or pattern ("glob") using the given Hadoop - * {@link org.apache.hadoop.mapreduce.lib.input.FileInputFormat}, - * with key-value types specified by the given key class and value class. - */ - public static > Read.Bounded> readFrom( - String filepattern, Class formatClass, Class keyClass, Class valueClass) { - return Read.from(from(filepattern, formatClass, keyClass, valueClass)); - } - - /** - * Creates a {@code HadoopFileSource} that reads from the given file name or pattern ("glob") - * using the given Hadoop {@link org.apache.hadoop.mapreduce.lib.input.FileInputFormat}, - * with key-value types specified by the given key class and value class. - */ - public static > HadoopFileSource from( - String filepattern, Class formatClass, Class keyClass, Class valueClass) { - @SuppressWarnings("unchecked") - HadoopFileSource source = (HadoopFileSource) - new HadoopFileSource(filepattern, formatClass, keyClass, valueClass); - return source; - } - - /** - * Create a {@code HadoopFileSource} based on a file or a file pattern specification. - */ - private HadoopFileSource(String filepattern, - Class> formatClass, Class keyClass, - Class valueClass) { - this(filepattern, formatClass, keyClass, valueClass, null); - } - - /** - * Create a {@code HadoopFileSource} based on a single Hadoop input split, which won't be - * split up further. - */ - private HadoopFileSource(String filepattern, - Class> formatClass, Class keyClass, - Class valueClass, SerializableSplit serializableSplit) { - this.filepattern = filepattern; - this.formatClass = formatClass; - this.keyClass = keyClass; - this.valueClass = valueClass; - this.serializableSplit = serializableSplit; - } - - public String getFilepattern() { - return filepattern; - } - - public Class> getFormatClass() { - return formatClass; - } - - public Class getKeyClass() { - return keyClass; - } - - public Class getValueClass() { - return valueClass; - } - - @Override - public void validate() { - checkNotNull(filepattern, "need to set the filepattern of a HadoopFileSource"); - checkNotNull(formatClass, "need to set the format class of a HadoopFileSource"); - checkNotNull(keyClass, "need to set the key class of a HadoopFileSource"); - checkNotNull(valueClass, "need to set the value class of a HadoopFileSource"); - } - - @Override - public List>> splitIntoBundles(long desiredBundleSizeBytes, - PipelineOptions options) throws Exception { - if (serializableSplit == null) { - return Lists.transform(computeSplits(desiredBundleSizeBytes), - new Function>>() { - @Nullable @Override - public BoundedSource> apply(@Nullable InputSplit inputSplit) { - return new HadoopFileSource(filepattern, formatClass, keyClass, - valueClass, new SerializableSplit(inputSplit)); - } - }); - } else { - return ImmutableList.of(this); - } - } - - private FileInputFormat createFormat(Job job) throws IOException, IllegalAccessException, - InstantiationException { - Path path = new Path(filepattern); - FileInputFormat.addInputPath(job, path); - return formatClass.newInstance(); - } - - private List computeSplits(long desiredBundleSizeBytes) throws IOException, - IllegalAccessException, InstantiationException { - Job job = Job.getInstance(); - FileInputFormat.setMinInputSplitSize(job, desiredBundleSizeBytes); - FileInputFormat.setMaxInputSplitSize(job, desiredBundleSizeBytes); - return createFormat(job).getSplits(job); - } - - @Override - public BoundedReader> createReader(PipelineOptions options) throws IOException { - this.validate(); - - if (serializableSplit == null) { - return new HadoopFileReader<>(this, filepattern, formatClass); - } else { - return new HadoopFileReader<>(this, filepattern, formatClass, - serializableSplit.getSplit()); - } - } - - @Override - public Coder> getDefaultOutputCoder() { - return KvCoder.of(getDefaultCoder(keyClass), getDefaultCoder(valueClass)); - } - - @SuppressWarnings("unchecked") - private Coder getDefaultCoder(Class c) { - if (Writable.class.isAssignableFrom(c)) { - Class writableClass = (Class) c; - return (Coder) WritableCoder.of(writableClass); - } else if (Void.class.equals(c)) { - return (Coder) VoidCoder.of(); - } - // TODO: how to use registered coders here? - throw new IllegalStateException("Cannot find coder for " + c); - } - - // BoundedSource - - @Override - public long getEstimatedSizeBytes(PipelineOptions options) { - long size = 0; - try { - Job job = Job.getInstance(); // new instance - for (FileStatus st : listStatus(createFormat(job), job)) { - size += st.getLen(); - } - } catch (IOException | NoSuchMethodException | InvocationTargetException - | IllegalAccessException | InstantiationException e) { - // ignore, and return 0 - } - return size; - } - - private List listStatus(FileInputFormat format, - JobContext jobContext) throws NoSuchMethodException, InvocationTargetException, - IllegalAccessException { - // FileInputFormat#listStatus is protected, so call using reflection - Method listStatus = FileInputFormat.class.getDeclaredMethod("listStatus", JobContext.class); - listStatus.setAccessible(true); - @SuppressWarnings("unchecked") - List stat = (List) listStatus.invoke(format, jobContext); - return stat; - } - - @Override - public boolean producesSortedKeys(PipelineOptions options) throws Exception { - return false; - } - - static class HadoopFileReader extends BoundedSource.BoundedReader> { - - private final BoundedSource> source; - private final String filepattern; - private final Class formatClass; - - private FileInputFormat format; - private TaskAttemptContext attemptContext; - private List splits; - private ListIterator splitsIterator; - private Configuration conf; - private RecordReader currentReader; - private KV currentPair; - private volatile boolean done = false; - - /** - * Create a {@code HadoopFileReader} based on a file or a file pattern specification. - */ - public HadoopFileReader(BoundedSource> source, String filepattern, - Class> formatClass) { - this(source, filepattern, formatClass, null); - } - - /** - * Create a {@code HadoopFileReader} based on a single Hadoop input split. - */ - public HadoopFileReader(BoundedSource> source, String filepattern, - Class> formatClass, InputSplit split) { - this.source = source; - this.filepattern = filepattern; - this.formatClass = formatClass; - if (split != null) { - this.splits = ImmutableList.of(split); - this.splitsIterator = splits.listIterator(); - } - } - - @Override - public boolean start() throws IOException { - Job job = Job.getInstance(); // new instance - Path path = new Path(filepattern); - FileInputFormat.addInputPath(job, path); - - try { - @SuppressWarnings("unchecked") - FileInputFormat f = (FileInputFormat) formatClass.newInstance(); - this.format = f; - } catch (InstantiationException | IllegalAccessException e) { - throw new IOException("Cannot instantiate file input format " + formatClass, e); - } - this.attemptContext = new TaskAttemptContextImpl(job.getConfiguration(), - new TaskAttemptID()); - - if (splitsIterator == null) { - this.splits = format.getSplits(job); - this.splitsIterator = splits.listIterator(); - } - this.conf = job.getConfiguration(); - return advance(); - } - - @Override - public boolean advance() throws IOException { - try { - if (currentReader != null && currentReader.nextKeyValue()) { - currentPair = nextPair(); - return true; - } else { - while (splitsIterator.hasNext()) { - // advance the reader and see if it has records - InputSplit nextSplit = splitsIterator.next(); - @SuppressWarnings("unchecked") - RecordReader reader = - (RecordReader) format.createRecordReader(nextSplit, attemptContext); - if (currentReader != null) { - currentReader.close(); - } - currentReader = reader; - currentReader.initialize(nextSplit, attemptContext); - if (currentReader.nextKeyValue()) { - currentPair = nextPair(); - return true; - } - currentReader.close(); - currentReader = null; - } - // either no next split or all readers were empty - currentPair = null; - done = true; - return false; - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException(e); - } - } - - @SuppressWarnings("unchecked") - private KV nextPair() throws IOException, InterruptedException { - K key = currentReader.getCurrentKey(); - V value = currentReader.getCurrentValue(); - // clone Writable objects since they are reused between calls to RecordReader#nextKeyValue - if (key instanceof Writable) { - key = (K) WritableUtils.clone((Writable) key, conf); - } - if (value instanceof Writable) { - value = (V) WritableUtils.clone((Writable) value, conf); - } - return KV.of(key, value); - } - - @Override - public KV getCurrent() throws NoSuchElementException { - if (currentPair == null) { - throw new NoSuchElementException(); - } - return currentPair; - } - - @Override - public void close() throws IOException { - if (currentReader != null) { - currentReader.close(); - currentReader = null; - } - currentPair = null; - } - - @Override - public BoundedSource> getCurrentSource() { - return source; - } - - // BoundedReader - - @Override - public Double getFractionConsumed() { - if (currentReader == null) { - return 0.0; - } - if (splits.isEmpty()) { - return 1.0; - } - int index = splitsIterator.previousIndex(); - int numReaders = splits.size(); - if (index == numReaders) { - return 1.0; - } - double before = 1.0 * index / numReaders; - double after = 1.0 * (index + 1) / numReaders; - Double fractionOfCurrentReader = getProgress(); - if (fractionOfCurrentReader == null) { - return before; - } - return before + fractionOfCurrentReader * (after - before); - } - - private Double getProgress() { - try { - return (double) currentReader.getProgress(); - } catch (IOException | InterruptedException e) { - return null; - } - } - - @Override - public final long getSplitPointsRemaining() { - if (done) { - return 0; - } - // This source does not currently support dynamic work rebalancing, so remaining - // parallelism is always 1. - return 1; - } - - @Override - public BoundedSource> splitAtFraction(double fraction) { - // Not yet supported. To implement this, the sizes of the splits should be used to - // calculate the remaining splits that constitute the given fraction, then a - // new source backed by those splits should be returned. - return null; - } - } - - /** - * A wrapper to allow Hadoop {@link org.apache.hadoop.mapreduce.InputSplit}s to be - * serialized using Java's standard serialization mechanisms. Note that the InputSplit - * has to be Writable (which most are). - */ - public static class SerializableSplit implements Externalizable { - private static final long serialVersionUID = 0L; - - private InputSplit split; - - public SerializableSplit() { - } - - public SerializableSplit(InputSplit split) { - checkArgument(split instanceof Writable, "Split is not writable: %s", split); - this.split = split; - } - - public InputSplit getSplit() { - return split; - } - - @Override - public void writeExternal(ObjectOutput out) throws IOException { - out.writeUTF(split.getClass().getCanonicalName()); - ((Writable) split).write(out); - } - - @Override - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - String className = in.readUTF(); - try { - split = (InputSplit) Class.forName(className).newInstance(); - ((Writable) split).readFields(in); - } catch (InstantiationException | IllegalAccessException e) { - throw new IOException(e); - } - } - } - - -} diff --git a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoder.java b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoder.java deleted file mode 100644 index 5dba58d39c..0000000000 --- a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoder.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow Hadoop Library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.hadoop; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.hadoop.io.Writable; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -/** - * A {@code WritableCoder} is a {@link com.google.cloud.dataflow.sdk.coders.Coder} for a - * Java class that implements {@link org.apache.hadoop.io.Writable}. - * - *

              To use, specify the coder type on a PCollection: - *

              - * {@code
              - *   PCollection records =
              - *       foo.apply(...).setCoder(WritableCoder.of(MyRecord.class));
              - * }
              - * 
              - * - * @param the type of elements handled by this coder - */ -public class WritableCoder extends StandardCoder { - private static final long serialVersionUID = 0L; - - /** - * Returns a {@code WritableCoder} instance for the provided element class. - * @param the element type - */ - public static WritableCoder of(Class clazz) { - return new WritableCoder<>(clazz); - } - - @JsonCreator - @SuppressWarnings("unchecked") - public static WritableCoder of(@JsonProperty("type") String classType) - throws ClassNotFoundException { - Class clazz = Class.forName(classType); - if (!Writable.class.isAssignableFrom(clazz)) { - throw new ClassNotFoundException( - "Class " + classType + " does not implement Writable"); - } - return of((Class) clazz); - } - - private final Class type; - - public WritableCoder(Class type) { - this.type = type; - } - - @Override - public void encode(T value, OutputStream outStream, Context context) throws IOException { - value.write(new DataOutputStream(outStream)); - } - - @Override - public T decode(InputStream inStream, Context context) throws IOException { - try { - T t = type.newInstance(); - t.readFields(new DataInputStream(inStream)); - return t; - } catch (InstantiationException | IllegalAccessException e) { - throw new CoderException("unable to deserialize record", e); - } - } - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - result.put("type", type.getName()); - return result; - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - throw new NonDeterministicException(this, - "Hadoop Writable may be non-deterministic."); - } - -} diff --git a/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java b/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java deleted file mode 100644 index cef3c08348..0000000000 --- a/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow Hadoop Library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.hadoop; - -import static com.google.cloud.dataflow.sdk.testing.SourceTestUtils.readFromSource; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.sdk.io.BoundedSource; -import com.google.cloud.dataflow.sdk.io.Source; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.SourceTestUtils; -import com.google.cloud.dataflow.sdk.values.KV; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.IntWritable; -import org.apache.hadoop.io.SequenceFile; -import org.apache.hadoop.io.SequenceFile.Writer; -import org.apache.hadoop.io.Text; -import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * Tests for HadoopFileSource. - */ -public class HadoopFileSourceTest { - - Random random = new Random(0L); - - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); - - @Test - public void testFullyReadSingleFile() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - List> expectedResults = createRandomRecords(3, 10, 0); - File file = createFileWithData("tmp.seq", expectedResults); - - HadoopFileSource source = - HadoopFileSource.from(file.toString(), SequenceFileInputFormat.class, - IntWritable.class, Text.class); - - assertEquals(file.length(), source.getEstimatedSizeBytes(null)); - - assertThat(expectedResults, containsInAnyOrder(readFromSource(source, options).toArray())); - } - - @Test - public void testFullyReadFilePattern() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List> data1 = createRandomRecords(3, 10, 0); - File file1 = createFileWithData("file1", data1); - - List> data2 = createRandomRecords(3, 10, 10); - createFileWithData("file2", data2); - - List> data3 = createRandomRecords(3, 10, 20); - createFileWithData("file3", data3); - - List> data4 = createRandomRecords(3, 10, 30); - createFileWithData("otherfile", data4); - - HadoopFileSource source = - HadoopFileSource.from(new File(file1.getParent(), "file*").toString(), - SequenceFileInputFormat.class, IntWritable.class, Text.class); - List> expectedResults = new ArrayList<>(); - expectedResults.addAll(data1); - expectedResults.addAll(data2); - expectedResults.addAll(data3); - assertThat(expectedResults, containsInAnyOrder(readFromSource(source, options).toArray())); - } - - @Test - public void testCloseUnstartedFilePatternReader() throws IOException { - PipelineOptions options = PipelineOptionsFactory.create(); - List> data1 = createRandomRecords(3, 10, 0); - File file1 = createFileWithData("file1", data1); - - List> data2 = createRandomRecords(3, 10, 10); - createFileWithData("file2", data2); - - List> data3 = createRandomRecords(3, 10, 20); - createFileWithData("file3", data3); - - List> data4 = createRandomRecords(3, 10, 30); - createFileWithData("otherfile", data4); - - HadoopFileSource source = - HadoopFileSource.from(new File(file1.getParent(), "file*").toString(), - SequenceFileInputFormat.class, IntWritable.class, Text.class); - Source.Reader> reader = source.createReader(options); - // Closing an unstarted FilePatternReader should not throw an exception. - try { - reader.close(); - } catch (Exception e) { - fail("Closing an unstarted FilePatternReader should not throw an exception"); - } - } - - @Test - public void testSplits() throws Exception { - PipelineOptions options = PipelineOptionsFactory.create(); - - List> expectedResults = createRandomRecords(3, 10000, 0); - File file = createFileWithData("tmp.avro", expectedResults); - - HadoopFileSource source = - HadoopFileSource.from(file.toString(), SequenceFileInputFormat.class, - IntWritable.class, Text.class); - - // Assert that the source produces the expected records - assertEquals(expectedResults, readFromSource(source, options)); - - // Split with a small bundle size (has to be at least size of sync interval) - List>> splits = source - .splitIntoBundles(SequenceFile.SYNC_INTERVAL, options); - assertTrue(splits.size() > 2); - SourceTestUtils.assertSourcesEqualReferenceSource(source, splits, options); - int nonEmptySplits = 0; - for (BoundedSource> subSource : splits) { - if (readFromSource(subSource, options).size() > 0) { - nonEmptySplits += 1; - } - } - assertTrue(nonEmptySplits > 2); - } - - private File createFileWithData(String filename, List> records) - throws IOException { - File tmpFile = tmpFolder.newFile(filename); - try (Writer writer = SequenceFile.createWriter(new Configuration(), - Writer.keyClass(IntWritable.class), Writer.valueClass(Text.class), - Writer.file(new Path(tmpFile.toURI())))) { - - for (KV record : records) { - writer.append(record.getKey(), record.getValue()); - } - } - return tmpFile; - } - - private List> createRandomRecords(int dataItemLength, - int numItems, int offset) { - List> records = new ArrayList<>(); - for (int i = 0; i < numItems; i++) { - IntWritable key = new IntWritable(i + offset); - Text value = new Text(createRandomString(dataItemLength)); - records.add(KV.of(key, value)); - } - return records; - } - - private String createRandomString(int length) { - char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < length; i++) { - builder.append(chars[random.nextInt(chars.length)]); - } - return builder.toString(); - } - -} diff --git a/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoderTest.java b/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoderTest.java deleted file mode 100644 index 8eeb5e5167..0000000000 --- a/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/WritableCoderTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow Hadoop Library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.hadoop; - -import com.google.cloud.dataflow.sdk.testing.CoderProperties; - -import org.apache.hadoop.io.IntWritable; -import org.junit.Test; - -/** - * Tests for WritableCoder. - */ -public class WritableCoderTest { - - @Test - public void testIntWritableEncoding() throws Exception { - IntWritable value = new IntWritable(42); - WritableCoder coder = WritableCoder.of(IntWritable.class); - - CoderProperties.coderDecodeEncodeEqual(coder, value); - } -} diff --git a/contrib/join-library/AUTHORS.md b/contrib/join-library/AUTHORS.md deleted file mode 100644 index d32b6a7eba..0000000000 --- a/contrib/join-library/AUTHORS.md +++ /dev/null @@ -1,6 +0,0 @@ -# Authors of join-library - -The following is the official list of authors for copyright purposes of this community-contributed module. - - Google Inc. - Magnus Runesson, M.Runesson [at] gmail [dot] com diff --git a/contrib/join-library/README.md b/contrib/join-library/README.md deleted file mode 100644 index 8e2a011c34..0000000000 --- a/contrib/join-library/README.md +++ /dev/null @@ -1,33 +0,0 @@ -Join-library -============ - -Join-library provides inner join, outer left and right join functions to -Google Cloud Dataflow. The aim is to simplify the most common cases of join to a -simple function call. - -The functions are generic so it supports join of any types supported by -Dataflow. Input to the join functions are PCollections of Key/Values. Both the -left and right PCollections need the same type for the key. All the join -functions return a Key/Value where Key is the join key and value is -a Key/Value where the key is the left value and right is the value. - -In the cases of outer join, since null cannot be serialized the user have -to provide a value that represent null for that particular use case. - -Example how to use join-library: - - PCollection> leftPcollection = ... - PCollection> rightPcollection = ... - - PCollection>> joinedPcollection = - Join.innerJoin(leftPcollection, rightPcollection); - -Join-library can be found on maven-central: - - - org.linuxalert.dataflow - google-cloud-dataflow-java-contrib-joinlibrary - 0.0.3 - - -Questions or comments: `M.Runesson [at] gmail [dot] com` diff --git a/contrib/join-library/pom.xml b/contrib/join-library/pom.xml deleted file mode 100644 index f15ef9794c..0000000000 --- a/contrib/join-library/pom.xml +++ /dev/null @@ -1,186 +0,0 @@ - - - - 4.0.0 - - org.linuxalert.dataflow - google-cloud-dataflow-java-contrib-joinlibrary - Google Cloud Dataflow Join Library - Library with generic join functions for Dataflow. - https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/contrib/join-library - - - Google Inc. - http://www.google.com - - - Magnus Runesson - M (dot) Runesson (at) gmail (dot) com - - Developer - - +1 - - - - - Magnus Runesson - M (dot) Runesson (at) gmail (dot) com - https://github.com/mrunesson - - - 0.0.4 - jar - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/contrib/join-library - - - - UTF-8 - [1.0.0, 2.0.0) - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.7 - 1.7 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - ../../checkstyle.xml - ../../suppressions.xml - true - true - true - - - - validate - - check - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - - jar - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - - attach-javadocs - - jar - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.3 - true - - ossrh - https://oss.sonatype.org/ - true - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${google-cloud-dataflow-version} - - - - com.google.guava - guava - 19.0 - - - - - org.hamcrest - hamcrest-all - 1.3 - test - - - - junit - junit - 4.12 - test - - - - diff --git a/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java b/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java deleted file mode 100644 index 465a1ebc6a..0000000000 --- a/contrib/join-library/src/main/java/com/google/cloud/dataflow/contrib/joinlibrary/Join.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow join-library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.joinlibrary; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult; -import com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey; -import com.google.cloud.dataflow.sdk.transforms.join.KeyedPCollectionTuple; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.TupleTag; - -/** - * Utility class with different versions of joins. All methods join two collections of - * key/value pairs (KV). - */ -public class Join { - - /** - * Inner join of two collections of KV elements. - * @param leftCollection Left side collection to join. - * @param rightCollection Right side collection to join. - * @param Type of the key for both collections - * @param Type of the values for the left collection. - * @param Type of the values for the right collection. - * @return A joined collection of KV where Key is the key and value is a - * KV where Key is of type V1 and Value is type V2. - */ - public static PCollection>> innerJoin( - final PCollection> leftCollection, final PCollection> rightCollection) { - checkNotNull(leftCollection); - checkNotNull(rightCollection); - - final TupleTag v1Tuple = new TupleTag<>(); - final TupleTag v2Tuple = new TupleTag<>(); - - PCollection> coGbkResultCollection = - KeyedPCollectionTuple.of(v1Tuple, leftCollection) - .and(v2Tuple, rightCollection) - .apply(CoGroupByKey.create()); - - return coGbkResultCollection.apply(ParDo.of( - new DoFn, KV>>() { - @Override - public void processElement(ProcessContext c) { - KV e = c.element(); - - Iterable leftValuesIterable = e.getValue().getAll(v1Tuple); - Iterable rightValuesIterable = e.getValue().getAll(v2Tuple); - - for (V1 leftValue : leftValuesIterable) { - for (V2 rightValue : rightValuesIterable) { - c.output(KV.of(e.getKey(), KV.of(leftValue, rightValue))); - } - } - } - })) - .setCoder(KvCoder.of(((KvCoder) leftCollection.getCoder()).getKeyCoder(), - KvCoder.of(((KvCoder) leftCollection.getCoder()).getValueCoder(), - ((KvCoder) rightCollection.getCoder()).getValueCoder()))); - } - - /** - * Left Outer Join of two collections of KV elements. - * @param leftCollection Left side collection to join. - * @param rightCollection Right side collection to join. - * @param nullValue Value to use as null value when right side do not match left side. - * @param Type of the key for both collections - * @param Type of the values for the left collection. - * @param Type of the values for the right collection. - * @return A joined collection of KV where Key is the key and value is a - * KV where Key is of type V1 and Value is type V2. Values that - * should be null or empty is replaced with nullValue. - */ - public static PCollection>> leftOuterJoin( - final PCollection> leftCollection, - final PCollection> rightCollection, - final V2 nullValue) { - checkNotNull(leftCollection); - checkNotNull(rightCollection); - checkNotNull(nullValue); - - final TupleTag v1Tuple = new TupleTag<>(); - final TupleTag v2Tuple = new TupleTag<>(); - - PCollection> coGbkResultCollection = - KeyedPCollectionTuple.of(v1Tuple, leftCollection) - .and(v2Tuple, rightCollection) - .apply(CoGroupByKey.create()); - - return coGbkResultCollection.apply(ParDo.of( - new DoFn, KV>>() { - @Override - public void processElement(ProcessContext c) { - KV e = c.element(); - - Iterable leftValuesIterable = e.getValue().getAll(v1Tuple); - Iterable rightValuesIterable = e.getValue().getAll(v2Tuple); - - for (V1 leftValue : leftValuesIterable) { - if (rightValuesIterable.iterator().hasNext()) { - for (V2 rightValue : rightValuesIterable) { - c.output(KV.of(e.getKey(), KV.of(leftValue, rightValue))); - } - } else { - c.output(KV.of(e.getKey(), KV.of(leftValue, nullValue))); - } - } - } - })) - .setCoder(KvCoder.of(((KvCoder) leftCollection.getCoder()).getKeyCoder(), - KvCoder.of(((KvCoder) leftCollection.getCoder()).getValueCoder(), - ((KvCoder) rightCollection.getCoder()).getValueCoder()))); - } - - /** - * Right Outer Join of two collections of KV elements. - * @param leftCollection Left side collection to join. - * @param rightCollection Right side collection to join. - * @param nullValue Value to use as null value when left side do not match right side. - * @param Type of the key for both collections - * @param Type of the values for the left collection. - * @param Type of the values for the right collection. - * @return A joined collection of KV where Key is the key and value is a - * KV where Key is of type V1 and Value is type V2. Keys that - * should be null or empty is replaced with nullValue. - */ - public static PCollection>> rightOuterJoin( - final PCollection> leftCollection, - final PCollection> rightCollection, - final V1 nullValue) { - checkNotNull(leftCollection); - checkNotNull(rightCollection); - checkNotNull(nullValue); - - final TupleTag v1Tuple = new TupleTag<>(); - final TupleTag v2Tuple = new TupleTag<>(); - - PCollection> coGbkResultCollection = - KeyedPCollectionTuple.of(v1Tuple, leftCollection) - .and(v2Tuple, rightCollection) - .apply(CoGroupByKey.create()); - - return coGbkResultCollection.apply(ParDo.of( - new DoFn, KV>>() { - @Override - public void processElement(ProcessContext c) { - KV e = c.element(); - - Iterable leftValuesIterable = e.getValue().getAll(v1Tuple); - Iterable rightValuesIterable = e.getValue().getAll(v2Tuple); - - for (V2 rightValue : rightValuesIterable) { - if (leftValuesIterable.iterator().hasNext()) { - for (V1 leftValue : leftValuesIterable) { - c.output(KV.of(e.getKey(), KV.of(leftValue, rightValue))); - } - } else { - c.output(KV.of(e.getKey(), KV.of(nullValue, rightValue))); - } - } - } - })) - .setCoder(KvCoder.of(((KvCoder) leftCollection.getCoder()).getKeyCoder(), - KvCoder.of(((KvCoder) leftCollection.getCoder()).getValueCoder(), - ((KvCoder) rightCollection.getCoder()).getValueCoder()))); - } -} diff --git a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java b/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java deleted file mode 100644 index 839c451950..0000000000 --- a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/InnerJoinTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow join-library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.joinlibrary; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** - * This test Inner Join functionality. - */ -public class InnerJoinTest { - - Pipeline p; - List> leftListOfKv; - List> listRightOfKv; - List>> expectedResult; - - @Before - public void setup() { - - p = TestPipeline.create(); - leftListOfKv = new ArrayList<>(); - listRightOfKv = new ArrayList<>(); - - expectedResult = new ArrayList<>(); - } - - @Test - public void testJoinOneToOneMapping() { - leftListOfKv.add(KV.of("Key1", 5L)); - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = - p.apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key1", "foo")); - listRightOfKv.add(KV.of("Key2", "bar")); - PCollection> rightCollection = - p.apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.innerJoin( - leftCollection, rightCollection); - - expectedResult.add(KV.of("Key1", KV.of(5L, "foo"))); - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinOneToManyMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key2", "bar")); - listRightOfKv.add(KV.of("Key2", "gazonk")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.innerJoin( - leftCollection, rightCollection); - - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - expectedResult.add(KV.of("Key2", KV.of(4L, "gazonk"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinManyToOneMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - leftListOfKv.add(KV.of("Key2", 6L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key2", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.innerJoin( - leftCollection, rightCollection); - - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - expectedResult.add(KV.of("Key2", KV.of(6L, "bar"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinNoneToNoneMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key3", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.innerJoin( - leftCollection, rightCollection); - - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - p.run(); - } - - @Test(expected = NullPointerException.class) - public void testJoinLeftCollectionNull() { - Join.innerJoin(null, p.apply(Create.of(listRightOfKv))); - } - - @Test(expected = NullPointerException.class) - public void testJoinRightCollectionNull() { - Join.innerJoin(p.apply(Create.of(leftListOfKv)), null); - } -} diff --git a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterLeftJoinTest.java b/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterLeftJoinTest.java deleted file mode 100644 index 3dd67422d7..0000000000 --- a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterLeftJoinTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow join-library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.joinlibrary; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - - -/** - * This test Outer Left Join functionality. - */ -public class OuterLeftJoinTest { - - Pipeline p; - List> leftListOfKv; - List> listRightOfKv; - List>> expectedResult; - - @Before - public void setup() { - - p = TestPipeline.create(); - leftListOfKv = new ArrayList<>(); - listRightOfKv = new ArrayList<>(); - - expectedResult = new ArrayList<>(); - } - - @Test - public void testJoinOneToOneMapping() { - leftListOfKv.add(KV.of("Key1", 5L)); - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key1", "foo")); - listRightOfKv.add(KV.of("Key2", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.leftOuterJoin( - leftCollection, rightCollection, ""); - - expectedResult.add(KV.of("Key1", KV.of(5L, "foo"))); - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinOneToManyMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key2", "bar")); - listRightOfKv.add(KV.of("Key2", "gazonk")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.leftOuterJoin( - leftCollection, rightCollection, ""); - - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - expectedResult.add(KV.of("Key2", KV.of(4L, "gazonk"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinManyToOneMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - leftListOfKv.add(KV.of("Key2", 6L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key2", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.leftOuterJoin( - leftCollection, rightCollection, ""); - - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - expectedResult.add(KV.of("Key2", KV.of(6L, "bar"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinOneToNoneMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key3", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.leftOuterJoin( - leftCollection, rightCollection, ""); - - expectedResult.add(KV.of("Key2", KV.of(4L, ""))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - p.run(); - } - - @Test(expected = NullPointerException.class) - public void testJoinLeftCollectionNull() { - Join.leftOuterJoin(null, p.apply(Create.of(listRightOfKv)), ""); - } - - @Test(expected = NullPointerException.class) - public void testJoinRightCollectionNull() { - Join.leftOuterJoin(p.apply(Create.of(leftListOfKv)), null, ""); - } - - @Test(expected = NullPointerException.class) - public void testJoinNullValueIsNull() { - Join.leftOuterJoin( - p.apply("CreateLeft", Create.of(leftListOfKv)), - p.apply("CreateRight", Create.of(listRightOfKv)), - null); - } -} diff --git a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterRightJoinTest.java b/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterRightJoinTest.java deleted file mode 100644 index 9f3b80b8c9..0000000000 --- a/contrib/join-library/src/test/java/com/google/cloud/dataflow/contrib/joinlibrary/OuterRightJoinTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2015 The Google Cloud Dataflow join-library Authors - * - * Licensed 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 com.google.cloud.dataflow.contrib.joinlibrary; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - - -/** - * This test Outer Right Join functionality. - */ -public class OuterRightJoinTest { - - Pipeline p; - List> leftListOfKv; - List> listRightOfKv; - List>> expectedResult; - - @Before - public void setup() { - - p = TestPipeline.create(); - leftListOfKv = new ArrayList<>(); - listRightOfKv = new ArrayList<>(); - - expectedResult = new ArrayList<>(); - } - - @Test - public void testJoinOneToOneMapping() { - leftListOfKv.add(KV.of("Key1", 5L)); - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key1", "foo")); - listRightOfKv.add(KV.of("Key2", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.rightOuterJoin( - leftCollection, rightCollection, -1L); - - expectedResult.add(KV.of("Key1", KV.of(5L, "foo"))); - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinOneToManyMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key2", "bar")); - listRightOfKv.add(KV.of("Key2", "gazonk")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.rightOuterJoin( - leftCollection, rightCollection, -1L); - - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - expectedResult.add(KV.of("Key2", KV.of(4L, "gazonk"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinManyToOneMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - leftListOfKv.add(KV.of("Key2", 6L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key2", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.rightOuterJoin( - leftCollection, rightCollection, -1L); - - expectedResult.add(KV.of("Key2", KV.of(4L, "bar"))); - expectedResult.add(KV.of("Key2", KV.of(6L, "bar"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - - p.run(); - } - - @Test - public void testJoinNoneToOneMapping() { - leftListOfKv.add(KV.of("Key2", 4L)); - PCollection> leftCollection = p - .apply("CreateLeft", Create.of(leftListOfKv)); - - listRightOfKv.add(KV.of("Key3", "bar")); - PCollection> rightCollection = p - .apply("CreateRight", Create.of(listRightOfKv)); - - PCollection>> output = Join.rightOuterJoin( - leftCollection, rightCollection, -1L); - - expectedResult.add(KV.of("Key3", KV.of(-1L, "bar"))); - DataflowAssert.that(output).containsInAnyOrder(expectedResult); - p.run(); - } - - @Test(expected = NullPointerException.class) - public void testJoinLeftCollectionNull() { - Join.rightOuterJoin(null, p.apply(Create.of(listRightOfKv)), ""); - } - - @Test(expected = NullPointerException.class) - public void testJoinRightCollectionNull() { - Join.rightOuterJoin(p.apply(Create.of(leftListOfKv)), null, -1L); - } - - @Test(expected = NullPointerException.class) - public void testJoinNullValueIsNull() { - Join.rightOuterJoin( - p.apply("CreateLeft", Create.of(leftListOfKv)), - p.apply("CreateRight", Create.of(listRightOfKv)), - null); - } -} diff --git a/contrib/kafka/pom.xml b/contrib/kafka/pom.xml deleted file mode 100644 index 4beecd7ba5..0000000000 --- a/contrib/kafka/pom.xml +++ /dev/null @@ -1,174 +0,0 @@ - - - - 4.0.0 - - jar - - com.google.cloud.dataflow - google-cloud-dataflow-java-contrib-kafka - Google Cloud Dataflow Kafka IO Library - Library to read Kafka topics. - 0.1.0-SNAPSHOT - - - [1.6.0, 2.0.0) - 0.9.0.1 - - 19.0 - 1.3 - 2.7.0 - 2.4 - 4.11 - 1.7.14 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.puppycrawl.tools - checkstyle - 6.19 - - - - ../../checkstyle.xml - ../../suppressions.xml - true - true - true - - - - - check - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - true - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - compile - - jar - - - - attach-test-sources - test-compile - - test-jar - - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${dataflow.version} - - - - org.apache.kafka - kafka-clients - ${kafka.version} - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - joda-time - joda-time - ${joda.version} - - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - - com.google.guava - guava - ${guava.version} - - - - - org.hamcrest - hamcrest-all - test - ${hamcrest.version} - - - - junit - junit - test - ${junit.version} - - - - org.slf4j - slf4j-jdk14 - test - ${slf4j.version} - - - diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java deleted file mode 100644 index a9231de6e0..0000000000 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaCheckpointMark.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.kafka; - -import com.google.cloud.dataflow.sdk.coders.DefaultCoder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; - -import org.apache.kafka.common.TopicPartition; - -import java.io.IOException; -import java.io.Serializable; -import java.util.List; - -/** - * Checkpoint for an unbounded KafkaIO.Read. Consists of Kafka topic name, partition id, and the - * latest offset consumed so far. - */ -@DefaultCoder(SerializableCoder.class) -public class KafkaCheckpointMark implements UnboundedSource.CheckpointMark, Serializable { - - private final List partitions; - - public KafkaCheckpointMark(List partitions) { - this.partitions = partitions; - } - - public List getPartitions() { - return partitions; - } - - @Override - public void finalizeCheckpoint() throws IOException { - /* nothing to do */ - - // We might want to support committing offset in Kafka for better resume point when the job - // is restarted (checkpoint is not available for job restarts). - } - - /** - * A tuple to hold topic, partition, and offset that comprise the checkpoint for a single - * partition. - */ - public static class PartitionMark implements Serializable { - private final TopicPartition topicPartition; - private final long offset; - - public PartitionMark(TopicPartition topicPartition, long offset) { - this.topicPartition = topicPartition; - this.offset = offset; - } - - public TopicPartition getTopicPartition() { - return topicPartition; - } - - public long getOffset() { - return offset; - } - } -} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java deleted file mode 100644 index 67d523a1ac..0000000000 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java +++ /dev/null @@ -1,1611 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.kafka; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark.PartitionMark; -import com.google.cloud.dataflow.sdk.coders.ByteArrayCoder; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.SerializableCoder; -import com.google.cloud.dataflow.sdk.coders.VoidCoder; -import com.google.cloud.dataflow.sdk.io.Read.Unbounded; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.CheckpointMark; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.util.ExposedByteArrayInputStream; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PBegin; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PDone; -import com.google.cloud.dataflow.sdk.values.PInput; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.collect.ComparisonChain; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import com.google.common.io.Closeables; - -import org.apache.kafka.clients.consumer.Consumer; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.clients.producer.Callback; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.PartitionInfo; -import org.apache.kafka.common.TopicPartition; -import org.apache.kafka.common.errors.WakeupException; -import org.apache.kafka.common.serialization.ByteArrayDeserializer; -import org.apache.kafka.common.serialization.Serializer; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.annotation.Nullable; - -/** - * An unbounded source and a sink for Kafka topics. Kafka - * version 0.9 and above are supported. - * - *

              Reading from Kafka topics

              - * - *

              KafkaIO source returns unbounded collection of Kafka records as {@code - * PCollection>}. A {@link KafkaRecord} includes basic metadata like - * topic-partition and offset, along with key and value associated with a Kafka record. - * - *

              Although most applications consumer single topic, the source can be configured to consume - * multiple topics or even a specific set of {@link TopicPartition}s. - * - *

              To configure a Kafka source, you must specify at the minimum Kafka bootstrapServers - * and one or more topics to consume. The following example illustrates various options for - * configuring the source : - * - *

              {@code
              - *
              - *  pipeline
              - *    .apply(KafkaIO.read()
              - *       .withBootstrapServers("broker_1:9092,broker_2:9092")
              - *       .withTopics(ImmutableList.of("topic_a", "topic_b"))
              - *       // above two are required configuration. returns PCollection
              - *
              - *       // rest of the settings are optional :
              - *
              - *       // set a Coder for Key and Value (note the change to return type)
              - *       .withKeyCoder(BigEndianLongCoder.of()) // PCollection
              - *       .withValueCoder(StringUtf8Coder.of())  // PCollection
              - *
              - *       // you can further customize KafkaConsumer used to read the records by adding more
              - *       // settings for ConsumerConfig. e.g :
              - *       .updateConsumerProperties(ImmutableMap.of("receive.buffer.bytes", 1024 * 1024))
              - *
              - *       // custom function for calculating record timestamp (default is processing time)
              - *       .withTimestampFn(new MyTypestampFunction())
              - *
              - *       // custom function for watermark (default is record timestamp)
              - *       .withWatermarkFn(new MyWatermarkFunction())
              - *
              - *       // finally, if you don't need Kafka metadata, you can drop it
              - *       .withoutMetadata() // PCollection>
              - *    )
              - *    .apply(Values.create()) // PCollection
              - *     ...
              - * }
              - * - *

              Partition Assignment and Checkpointing

              The Kafka partitions are evenly distributed among - * splits (workers). Dataflow checkpointing is fully supported and each split can resume from - * previous checkpoint. See {@link UnboundedKafkaSource#generateInitialSplits(int, PipelineOptions)} - * for more details on splits and checkpoint support. - * - *

              When the pipeline starts for the first time without any checkpoint, the source starts - * consuming from the latest offsets. You can override this behavior to consume from the - * beginning by setting appropriate appropriate properties in {@link ConsumerConfig}, through {@link - * Read#updateConsumerProperties(Map)}. - * - *

              Writing to Kafka

              - * - *

              KafkaIO sink supports writing key-value pairs to a Kafka topic. Users can also write just the - * values. To configure a Kafka sink, you must specify at the minimum Kafka - * bootstrapServers and the topic to write to. The following example illustrates various - * options for configuring the sink: - * - *

              {@code
              - *
              - *  PCollection> kvColl = ...;
              - *  kvColl.apply(KafkaIO.write()
              - *       .withBootstrapServers("broker_1:9092,broker_2:9092")
              - *       .withTopic("results")
              - *
              - *       // set Coder for Key and Value
              - *       .withKeyCoder(BigEndianLongCoder.of())
              - *       .withValueCoder(StringUtf8Coder.of())
              - *
              - *       // you can further customize KafkaProducer used to write the records by adding more
              - *       // settings for ProducerConfig. e.g, to enable compression :
              - *       .updateProducerProperties(ImmutableMap.of("compression.type", "gzip"))
              - *    );
              - * }
              - * - *

              Often you might want to write just values without any keys to Kafka. Use {@code values()} to - * write records with default empty(null) key: - * - *

              {@code
              - *  PCollection strings = ...;
              - *  strings.apply(KafkaIO.write()
              - *      .withBootstrapServers("broker_1:9092,broker_2:9092")
              - *      .withTopic("results")
              - *      .withValueCoder(StringUtf8Coder.of()) // just need coder for value
              - *      .values() // writes values to Kafka with default key
              - *    );
              - * }
              - * - *

              Advanced Kafka Configuration

              KafakIO allows setting most of the properties in {@link - * ConsumerConfig} for source or in {@link ProducerConfig} for sink. E.g. if you would like to - * enable offset auto commit (for external monitoring or other purposes), you can set - * "group.id", "enable.auto.commit", etc. - */ -public class KafkaIO { - - /** - * Creates an uninitialized {@link Read} {@link PTransform}. Before use, basic Kafka configuration - * should set with {@link Read#withBootstrapServers(String)} and {@link Read#withTopics(List)}. - * Other optional settings include key and value coders, custom timestamp and watermark - * functions. - */ - public static Read read() { - return new Read( - new ArrayList(), - new ArrayList(), - ByteArrayCoder.of(), - ByteArrayCoder.of(), - Read.KAFKA_9_CONSUMER_FACTORY_FN, - Read.DEFAULT_CONSUMER_PROPERTIES, - Long.MAX_VALUE, - null); - } - - /** - * Creates an uninitialized {@link Write} {@link PTransform}. Before use, Kafka configuration - * should be set with {@link Write#withBootstrapServers(String)} and {@link Write#withTopic} along - * with {@link Coder}s for (optional) key and values. - */ - public static Write write() { - return new Write( - null, ByteArrayCoder.of(), ByteArrayCoder.of(), TypedWrite.DEFAULT_PRODUCER_PROPERTIES); - } - - ///////////////////////// Read Support \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ - - /** - * A {@link PTransform} to read from Kafka topics. See {@link KafkaIO} for more information on - * usage and configuration. - */ - public static class Read extends TypedRead { - - /** - * Returns a new {@link Read} with Kafka consumer pointing to {@code bootstrapServers}. - */ - public Read withBootstrapServers(String bootstrapServers) { - return updateConsumerProperties( - ImmutableMap.of( - ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers)); - } - - /** - * Returns a new {@link Read} that reads from the topics. All the partitions are from each of - * the topics is read. See {@link UnboundedKafkaSource#generateInitialSplits(int, - * PipelineOptions)} for description of how the partitions are distributed among the splits. - */ - public Read withTopics(List topics) { - checkState(topicPartitions.isEmpty(), "Only topics or topicPartitions can be set, not both"); - - return new Read( - ImmutableList.copyOf(topics), - topicPartitions, - keyCoder, - valueCoder, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * Returns a new {@link Read} that reads from the partitions. This allows reading only a subset - * of partitions for one or more topics when (if ever) needed. See {@link - * UnboundedKafkaSource#generateInitialSplits(int, PipelineOptions)} for description of how the - * partitions are distributed among the splits. - */ - public Read withTopicPartitions(List topicPartitions) { - checkState(topics.isEmpty(), "Only topics or topicPartitions can be set, not both"); - - return new Read( - topics, - ImmutableList.copyOf(topicPartitions), - keyCoder, - valueCoder, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * Returns a new {@link Read} with {@link Coder} for key bytes. - */ - public Read withKeyCoder(Coder keyCoder) { - return new Read( - topics, - topicPartitions, - keyCoder, - valueCoder, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * Returns a new {@link Read} with {@link Coder} for value bytes. - */ - public Read withValueCoder(Coder valueCoder) { - return new Read( - topics, - topicPartitions, - keyCoder, - valueCoder, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * A factory to create Kafka {@link Consumer} from consumer configuration. This is useful for - * supporting another version of Kafka consumer. Default is {@link KafkaConsumer}. - */ - public Read withConsumerFactoryFn( - SerializableFunction, Consumer> consumerFactoryFn) { - return new Read( - topics, - topicPartitions, - keyCoder, - valueCoder, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * Update consumer configuration with new properties. - */ - public Read updateConsumerProperties(Map configUpdates) { - - Map config = - updateKafkaProperties(consumerConfig, IGNORED_CONSUMER_PROPERTIES, configUpdates); - - return new Read( - topics, - topicPartitions, - keyCoder, - valueCoder, - consumerFactoryFn, - config, - maxNumRecords, - maxReadTime); - } - - /** - * Similar to {@link com.google.cloud.dataflow.sdk.io.Read.Unbounded#withMaxNumRecords(long)}. - * Mainly used for tests and demo applications. - */ - public Read withMaxNumRecords(long maxNumRecords) { - return new Read( - topics, - topicPartitions, - keyCoder, - valueCoder, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - null); - } - - /** - * Similar to {@link com.google.cloud.dataflow.sdk.io.Read.Unbounded#withMaxReadTime(Duration)}. - * Mainly used for tests and demo applications. - */ - public Read withMaxReadTime(Duration maxReadTime) { - return new Read( - topics, - topicPartitions, - keyCoder, - valueCoder, - consumerFactoryFn, - consumerConfig, - Long.MAX_VALUE, - maxReadTime); - } - - /////////////////////////////////////////////////////////////////////////////////////// - - private Read( - List topics, - List topicPartitions, - Coder keyCoder, - Coder valueCoder, - SerializableFunction, Consumer> consumerFactoryFn, - Map consumerConfig, - long maxNumRecords, - @Nullable Duration maxReadTime) { - - super( - topics, - topicPartitions, - keyCoder, - valueCoder, - null, - null, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * A set of properties that are not required or don't make sense for our consumer. - */ - private static final Map IGNORED_CONSUMER_PROPERTIES = - ImmutableMap.of( - ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, - "Set keyCoder instead", - ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, - "Set valueCoder instead" - // "group.id", "enable.auto.commit", "auto.commit.interval.ms" : - // lets allow these, applications can have better resume point for restarts. - ); - - // set config defaults - private static final Map DEFAULT_CONSUMER_PROPERTIES = - ImmutableMap.of( - ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, - ByteArrayDeserializer.class.getName(), - ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, - ByteArrayDeserializer.class.getName(), - - // Use large receive buffer. Once KAFKA-3135 is fixed, this _may_ not be required. - // with default value of of 32K, It takes multiple seconds between successful polls. - // All the consumer work is done inside poll(), with smaller send buffer size, it - // takes many polls before a 1MB chunk from the server is fully read. In my testing - // about half of the time select() inside kafka consumer waited for 20-30ms, though - // the server had lots of data in tcp send buffers on its side. Compared to default, - // this setting increased throughput increased by many fold (3-4x). - ConsumerConfig.RECEIVE_BUFFER_CONFIG, - 512 * 1024, - - // default to latest offset when we are not resuming. - ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, - "latest", - // disable auto commit of offsets. we don't require group_id. could be enabled by user. - ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, - false); - - // default Kafka 0.9 Consumer supplier. - private static final SerializableFunction, Consumer> - KAFKA_9_CONSUMER_FACTORY_FN = - new SerializableFunction, Consumer>() { - public Consumer apply(Map config) { - return new KafkaConsumer<>(config); - } - }; - } - - /** - * A {@link PTransform} to read from Kafka topics. See {@link KafkaIO} for more information on - * usage and configuration. - */ - public static class TypedRead extends PTransform>> { - - /** - * A function to assign a timestamp to a record. Default is processing timestamp. - */ - public TypedRead withTimestampFn2( - SerializableFunction, Instant> timestampFn) { - checkNotNull(timestampFn); - return new TypedRead( - topics, - topicPartitions, - keyCoder, - valueCoder, - timestampFn, - watermarkFn, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * A function to calculate watermark after a record. Default is last record timestamp - * - * @see #withTimestampFn(SerializableFunction) - */ - public TypedRead withWatermarkFn2( - SerializableFunction, Instant> watermarkFn) { - checkNotNull(watermarkFn); - return new TypedRead( - topics, - topicPartitions, - keyCoder, - valueCoder, - timestampFn, - watermarkFn, - consumerFactoryFn, - consumerConfig, - maxNumRecords, - maxReadTime); - } - - /** - * A function to assign a timestamp to a record. Default is processing timestamp. - */ - public TypedRead withTimestampFn(SerializableFunction, Instant> timestampFn) { - checkNotNull(timestampFn); - return withTimestampFn2(unwrapKafkaAndThen(timestampFn)); - } - - /** - * A function to calculate watermark after a record. Default is last record timestamp - * - * @see #withTimestampFn(SerializableFunction) - */ - public TypedRead withWatermarkFn(SerializableFunction, Instant> watermarkFn) { - checkNotNull(watermarkFn); - return withWatermarkFn2(unwrapKafkaAndThen(watermarkFn)); - } - - /** - * Returns a {@link PTransform} for PCollection of {@link KV}, dropping Kafka metatdata. - */ - public PTransform>> withoutMetadata() { - return new TypedWithoutMetadata(this); - } - - @Override - public PCollection> apply(PBegin input) { - // Handles unbounded source to bounded conversion if maxNumRecords or maxReadTime is set. - Unbounded> unbounded = - com.google.cloud.dataflow.sdk.io.Read.from(makeSource()); - - PTransform>> transform = unbounded; - - if (maxNumRecords < Long.MAX_VALUE) { - transform = unbounded.withMaxNumRecords(maxNumRecords); - } else if (maxReadTime != null) { - transform = unbounded.withMaxReadTime(maxReadTime); - } - - return input.getPipeline().apply(transform); - } - - //////////////////////////////////////////////////////////////////////////////////////// - - protected final List topics; - protected final List topicPartitions; // mutually exclusive with topics - protected final Coder keyCoder; - protected final Coder valueCoder; - @Nullable protected final SerializableFunction, Instant> timestampFn; - @Nullable protected final SerializableFunction, Instant> watermarkFn; - protected final SerializableFunction, Consumer> - consumerFactoryFn; - protected final Map consumerConfig; - protected final long maxNumRecords; // bounded read, mainly for testing - protected final Duration maxReadTime; // bounded read, mainly for testing - - private TypedRead( - List topics, - List topicPartitions, - Coder keyCoder, - Coder valueCoder, - @Nullable SerializableFunction, Instant> timestampFn, - @Nullable SerializableFunction, Instant> watermarkFn, - SerializableFunction, Consumer> consumerFactoryFn, - Map consumerConfig, - long maxNumRecords, - @Nullable Duration maxReadTime) { - super("KafkaIO.Read"); - - this.topics = topics; - this.topicPartitions = topicPartitions; - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; - this.timestampFn = timestampFn; - this.watermarkFn = watermarkFn; - this.consumerFactoryFn = consumerFactoryFn; - this.consumerConfig = consumerConfig; - this.maxNumRecords = maxNumRecords; - this.maxReadTime = maxReadTime; - } - - /** - * Creates an {@link UnboundedSource} with the configuration in {@link - * TypedRead}. Primary use case is unit tests, should not be used in an application. - */ - @VisibleForTesting - UnboundedSource, com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> - makeSource() { - return new UnboundedKafkaSource( - -1, - topics, - topicPartitions, - keyCoder, - valueCoder, - timestampFn, - Optional.fromNullable(watermarkFn), - consumerFactoryFn, - consumerConfig); - } - - // utility method to convert KafkRecord to user KV before applying user functions - private static - SerializableFunction, OutT> unwrapKafkaAndThen( - final SerializableFunction, OutT> fn) { - return new SerializableFunction, OutT>() { - public OutT apply(KafkaRecord record) { - return fn.apply(record.getKV()); - } - }; - } - } - - /** - * A {@link PTransform} to read from Kafka topics. Similar to {@link KafkaIO.TypedRead}, but - * removes Kafka metatdata and returns a {@link PCollection} of {@link KV}. See {@link KafkaIO} - * for more information on usage and configuration of reader. - */ - public static class TypedWithoutMetadata extends PTransform>> { - - private final TypedRead typedRead; - - TypedWithoutMetadata(TypedRead read) { - super("KafkaIO.Read"); - this.typedRead = read; - } - - @Override - public PCollection> apply(PBegin begin) { - return typedRead - .apply(begin) - .apply( - "Remove Kafka Metadata", - ParDo.of( - new DoFn, KV>() { - @Override - public void processElement(ProcessContext ctx) { - ctx.output(ctx.element().getKV()); - } - })); - } - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - - private static final Logger LOG = LoggerFactory.getLogger(KafkaIO.class); - - /** - * Returns a new config map which is merge of current config and updates. Verifies the updates do - * not includes ignored properties. - */ - private static Map updateKafkaProperties( - Map currentConfig, - Map ignoredProperties, - Map updates) { - - for (String key : updates.keySet()) { - checkArgument( - !ignoredProperties.containsKey(key), - "No need to configure '%s'. %s", - key, - ignoredProperties.get(key)); - } - - Map config = new HashMap<>(currentConfig); - config.putAll(updates); - - return config; - } - - private static class NowTimestampFn implements SerializableFunction { - @Override - public Instant apply(T input) { - return Instant.now(); - } - } - - /** Static class, prevent instantiation. */ - private KafkaIO() {} - - private static class UnboundedKafkaSource - extends UnboundedSource< - KafkaRecord, com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> { - - private final int id; // split id, mainly for debugging - private final List topics; - private final List assignedPartitions; - private final Coder keyCoder; - private final Coder valueCoder; - private final SerializableFunction, Instant> timestampFn; - // would it be a good idea to pass currentTimestamp to watermarkFn? - private final Optional, Instant>> watermarkFn; - private SerializableFunction, Consumer> consumerFactoryFn; - private final Map consumerConfig; - - public UnboundedKafkaSource( - int id, - List topics, - List assignedPartitions, - Coder keyCoder, - Coder valueCoder, - @Nullable SerializableFunction, Instant> timestampFn, - Optional, Instant>> watermarkFn, - SerializableFunction, Consumer> consumerFactoryFn, - Map consumerConfig) { - - this.id = id; - this.assignedPartitions = assignedPartitions; - this.topics = topics; - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; - this.timestampFn = - (timestampFn == null ? new NowTimestampFn>() : timestampFn); - this.watermarkFn = watermarkFn; - this.consumerFactoryFn = consumerFactoryFn; - this.consumerConfig = consumerConfig; - } - - private List fetchKafkaPartitions() { - - List partitions = new ArrayList<>(assignedPartitions); - - // (a) fetch partitions for each topic - // (b) sort by - - if (partitions.isEmpty()) { - try (Consumer consumer = consumerFactoryFn.apply(consumerConfig)) { - for (String topic : topics) { - for (PartitionInfo p : consumer.partitionsFor(topic)) { - partitions.add(new TopicPartition(p.topic(), p.partition())); - } - } - } - } - - Collections.sort( - partitions, - new Comparator() { - public int compare(TopicPartition tp1, TopicPartition tp2) { - return ComparisonChain.start() - .compare(tp1.topic(), tp2.topic()) - .compare(tp1.partition(), tp2.partition()) - .result(); - } - }); - - checkState( - partitions.size() > 0, - "Could not find any partitions. Please check Kafka configuration and topic names"); - - return partitions; - } - - /** - * Returns one split for each of the Kafka partitions. - * - *

              It is important to sort the partitions deterministically so that we can support - * resuming a split from last checkpoint. The Kafka partitions are sorted by {@code }. - */ - @Override - public List> generateInitialSplits( - int desiredNumSplits, PipelineOptions options) throws Exception { - - List partitions = fetchKafkaPartitions(); - - List> result = new ArrayList<>(partitions.size()); - - // one split for each partition. - for (int i = 0; i < partitions.size(); i++) { - TopicPartition partition = partitions.get(i); - - LOG.info("Partition assigned to split {} : {}", i, partition); - - result.add( - new UnboundedKafkaSource<>( - i, - this.topics, - ImmutableList.of(partition), - this.keyCoder, - this.valueCoder, - this.timestampFn, - this.watermarkFn, - this.consumerFactoryFn, - this.consumerConfig)); - } - - return result; - } - - @Override - public UnboundedKafkaReader createReader( - PipelineOptions options, - com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark checkpointMark) { - if (assignedPartitions.isEmpty()) { - LOG.warn("Looks like generateSplits() is not called. Generate single split."); - try { - return new UnboundedKafkaReader( - new UnboundedKafkaSource<>( - 0, - this.topics, - fetchKafkaPartitions(), - this.keyCoder, - this.valueCoder, - this.timestampFn, - this.watermarkFn, - this.consumerFactoryFn, - this.consumerConfig), - checkpointMark); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - return new UnboundedKafkaReader(this, checkpointMark); - } - - @Override - public Coder - getCheckpointMarkCoder() { - return SerializableCoder.of( - com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark.class); - } - - @Override - public boolean requiresDeduping() { - // Kafka records are ordered with in partitions. In addition checkpoint guarantees - // records are not consumed twice. - return false; - } - - @Override - public void validate() { - checkNotNull( - consumerConfig.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG), - "Kafka bootstrap servers should be set"); - checkArgument( - topics.size() > 0 || assignedPartitions.size() > 0, - "Kafka topics or topic_partitions are required"); - } - - @Override - public Coder> getDefaultOutputCoder() { - return KafkaRecordCoder.of(keyCoder, valueCoder); - } - } - - private static class UnboundedKafkaReader extends UnboundedReader> { - - private final UnboundedKafkaSource source; - private final String name; - private Consumer consumer; - private final List partitionStates; - private KafkaRecord curRecord; - private Instant curTimestamp; - private Iterator curBatch = Collections.emptyIterator(); - - private static final Duration KAFKA_POLL_TIMEOUT = Duration.millis(1000); - // how long to wait for new records from kafka consumer inside start() - private static final Duration START_NEW_RECORDS_POLL_TIMEOUT = Duration.standardSeconds(5); - // how long to wait for new records from kafka consumer inside advance() - private static final Duration NEW_RECORDS_POLL_TIMEOUT = Duration.millis(10); - - // Use a separate thread to read Kafka messages. Kafka Consumer does all its work including - // network I/O inside poll(). Polling only inside #advance(), especially with a small timeout - // like 100 milliseconds does not work well. This along with large receive buffer for - // consumer achieved best throughput in tests (see `defaultConsumerProperties`). - private final ExecutorService consumerPollThread = Executors.newSingleThreadExecutor(); - private final SynchronousQueue> availableRecordsQueue = - new SynchronousQueue<>(); - private AtomicBoolean closed = new AtomicBoolean(false); - - // Backlog support : - // Kafka consumer does not have an API to fetch latest offset for topic. We need to seekToEnd() - // then look at position(). Use another consumer to do this so that the primary consumer does - // not need to be interrupted. The latest offsets are fetched periodically on another thread. - // This is still a hack. There could be unintended side effects, e.g. if user enabled offset - // auto commit in consumer config, this could interfere with the primary consumer (we will - // handle this particular problem). We might have to make this optional. - private Consumer offsetConsumer; - private final ScheduledExecutorService offsetFetcherThread = - Executors.newSingleThreadScheduledExecutor(); - private static final int OFFSET_UPDATE_INTERVAL_SECONDS = 5; - - /** watermark before any records have been read. */ - private static Instant initialWatermark = new Instant(Long.MIN_VALUE); - - public String toString() { - return name; - } - - // maintains state of each assigned partition (buffered records, consumed offset, etc) - private static class PartitionState { - private final TopicPartition topicPartition; - private long consumedOffset; - private long latestOffset; - private Iterator> recordIter = Collections.emptyIterator(); - - // simple moving average for size of each record in bytes - private double avgRecordSize = 0; - private static final int movingAvgWindow = 1000; // very roughly avg of last 1000 elements - - PartitionState(TopicPartition partition, long offset) { - this.topicPartition = partition; - this.consumedOffset = offset; - this.latestOffset = -1; - } - - // update consumedOffset and avgRecordSize - void recordConsumed(long offset, int size) { - consumedOffset = offset; - - // this is always updated from single thread. probably not worth making it an AtomicDouble - if (avgRecordSize <= 0) { - avgRecordSize = size; - } else { - // initially, first record heavily contributes to average. - avgRecordSize += ((size - avgRecordSize) / movingAvgWindow); - } - } - - synchronized void setLatestOffset(long latestOffset) { - this.latestOffset = latestOffset; - } - - synchronized long approxBacklogInBytes() { - // Note that is an an estimate of uncompressed backlog. - // Messages on Kafka might be comressed. - if (latestOffset < 0 || consumedOffset < 0) { - return UnboundedReader.BACKLOG_UNKNOWN; - } - if (latestOffset <= consumedOffset || consumedOffset < 0) { - return 0; - } - return (long) ((latestOffset - consumedOffset - 1) * avgRecordSize); - } - } - - public UnboundedKafkaReader( - UnboundedKafkaSource source, - @Nullable com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark checkpointMark) { - - this.source = source; - this.name = "Reader-" + source.id; - - partitionStates = - ImmutableList.copyOf( - Lists.transform( - source.assignedPartitions, - new Function() { - public PartitionState apply(TopicPartition tp) { - return new PartitionState(tp, -1L); - } - })); - - if (checkpointMark != null) { - // a) verify that assigned and check-pointed partitions match exactly - // b) set consumed offsets - - checkState( - checkpointMark.getPartitions().size() == source.assignedPartitions.size(), - "checkPointMark and assignedPartitions should match"); - // we could consider allowing a mismatch, though it is not expected in current Dataflow - - for (int i = 0; i < source.assignedPartitions.size(); i++) { - PartitionMark ckptMark = checkpointMark.getPartitions().get(i); - TopicPartition assigned = source.assignedPartitions.get(i); - - checkState( - ckptMark.getTopicPartition().equals(assigned), - "checkpointed partition %s and assigned partition %s don't match", - ckptMark.getTopicPartition(), - assigned); - - partitionStates.get(i).consumedOffset = ckptMark.getOffset(); - } - } - } - - private void consumerPollLoop() { - // Read in a loop and enqueue the batch of records, if any, to availableRecordsQueue - while (!closed.get()) { - try { - ConsumerRecords records = consumer.poll(KAFKA_POLL_TIMEOUT.getMillis()); - if (!records.isEmpty() && !closed.get()) { - availableRecordsQueue.put(records); // blocks until dequeued. - } - } catch (InterruptedException e) { - LOG.warn("{}: consumer thread is interrupted", this, e); // not expected - break; - } catch (WakeupException e) { - break; - } - } - - LOG.info("{}: Returning from consumer pool loop", this); - } - - private void nextBatch(Duration timeout) { - curBatch = Collections.emptyIterator(); - - ConsumerRecords records; - try { - records = availableRecordsQueue.poll(timeout.getMillis(), TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOG.warn("{}: Unexpected", this, e); - return; - } - - if (records == null) { - return; - } - - List nonEmpty = new LinkedList<>(); - - for (PartitionState p : partitionStates) { - p.recordIter = records.records(p.topicPartition).iterator(); - if (p.recordIter.hasNext()) { - nonEmpty.add(p); - } - } - - // cycle through the partitions in order to interleave records from each. - curBatch = Iterators.cycle(nonEmpty); - } - - @Override - public boolean start() throws IOException { - consumer = source.consumerFactoryFn.apply(source.consumerConfig); - consumer.assign(source.assignedPartitions); - - // seek to consumedOffset + 1 if it is set - for (PartitionState p : partitionStates) { - if (p.consumedOffset >= 0) { - LOG.info("{}: resuming {} at {}", name, p.topicPartition, p.consumedOffset + 1); - consumer.seek(p.topicPartition, p.consumedOffset + 1); - } else { - LOG.info("{}: resuming {} at default offset", name, p.topicPartition); - } - } - - // start consumer read loop. - // Note that consumer is not thread safe, should not accessed out side consumerPollLoop() - consumerPollThread.submit( - new Runnable() { - public void run() { - consumerPollLoop(); - } - }); - - // offsetConsumer setup : - - Object groupId = source.consumerConfig.get(ConsumerConfig.GROUP_ID_CONFIG); - // override group_id and disable auto_commit so that it does not interfere with main consumer - String offsetGroupId = - String.format( - "%s_offset_consumer_%d_%s", - name, - (new Random()).nextInt(Integer.MAX_VALUE), - (groupId == null ? "none" : groupId)); - Map offsetConsumerConfig = new HashMap<>(source.consumerConfig); - offsetConsumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, offsetGroupId); - offsetConsumerConfig.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); - - offsetConsumer = source.consumerFactoryFn.apply(offsetConsumerConfig); - offsetConsumer.assign(source.assignedPartitions); - - offsetFetcherThread.scheduleAtFixedRate( - new Runnable() { - public void run() { - updateLatestOffsets(); - } - }, - 0, - OFFSET_UPDATE_INTERVAL_SECONDS, - TimeUnit.SECONDS); - - // Wait for longer than normal when fetching a batch to improve chances a record is available - // when start() returns. - nextBatch(START_NEW_RECORDS_POLL_TIMEOUT); - return advance(); - } - - @Override - public boolean advance() throws IOException { - /* Read first record (if any). we need to loop here because : - * - (a) some records initially need to be skipped if they are before consumedOffset - * - (b) if curBatch is empty, we want to fetch next batch and then advance. - * - (c) curBatch is an iterator of iterators. we interleave the records from each. - * curBatch.next() might return an empty iterator. - */ - while (true) { - if (curBatch.hasNext()) { - PartitionState pState = curBatch.next(); - - if (!pState.recordIter.hasNext()) { // -- (c) - pState.recordIter = Collections.emptyIterator(); // drop ref - curBatch.remove(); - continue; - } - - ConsumerRecord rawRecord = pState.recordIter.next(); - long consumed = pState.consumedOffset; - long offset = rawRecord.offset(); - - if (consumed >= 0 && offset <= consumed) { // -- (a) - // this can happen when compression is enabled in Kafka (seems to be fixed in 0.10) - // should we check if the offset is way off from consumedOffset (say > 1M)? - LOG.warn( - "{}: ignoring already consumed offset {} for {}", - this, - offset, - pState.topicPartition); - continue; - } - - // sanity check - if (consumed >= 0 && (offset - consumed) != 1) { - LOG.warn( - "{}: gap in offsets for {} after {}. {} records missing.", - this, - pState.topicPartition, - consumed, - offset - consumed - 1); - } - - if (curRecord == null) { - LOG.info("{}: first record offset {}", name, offset); - } - - curRecord = null; // user coders below might throw. - - // apply user coders. might want to allow skipping records that fail to decode. - // TODO: wrap exceptions from coders to make explicit to users - KafkaRecord record = - new KafkaRecord( - rawRecord.topic(), - rawRecord.partition(), - rawRecord.offset(), - decode(rawRecord.key(), source.keyCoder), - decode(rawRecord.value(), source.valueCoder)); - - curTimestamp = source.timestampFn.apply(record); - curRecord = record; - - int recordSize = - (rawRecord.key() == null ? 0 : rawRecord.key().length) - + (rawRecord.value() == null ? 0 : rawRecord.value().length); - pState.recordConsumed(offset, recordSize); - return true; - - } else { // -- (b) - nextBatch(NEW_RECORDS_POLL_TIMEOUT); - - if (!curBatch.hasNext()) { - return false; - } - } - } - } - - private static byte[] nullBytes = new byte[0]; - - private static T decode(byte[] bytes, Coder coder) throws IOException { - // If 'bytes' is null, use byte[0]. It is common for key in Kakfa record to be null. - // This makes it impossible for user to distinguish between zero length byte and null. - // Alternately, we could have a ByteArrayCoder that handles nulls, and use that for default - // coder. - byte[] toDecode = bytes == null ? nullBytes : bytes; - return coder.decode(new ExposedByteArrayInputStream(toDecode), Coder.Context.OUTER); - } - - // update latest offset for each partition. - // called from offsetFetcher thread - private void updateLatestOffsets() { - for (PartitionState p : partitionStates) { - try { - offsetConsumer.seekToEnd(p.topicPartition); - long offset = offsetConsumer.position(p.topicPartition); - p.setLatestOffset(offset); - } catch (Exception e) { - LOG.warn("{}: exception while fetching latest offsets. ignored.", this, e); - p.setLatestOffset(-1L); // reset - } - - LOG.debug( - "{}: latest offset update for {} : {} (consumed offset {}, avg record size {})", - this, - p.topicPartition, - p.latestOffset, - p.consumedOffset, - p.avgRecordSize); - } - - LOG.debug("{}: backlog {}", this, getSplitBacklogBytes()); - } - - @Override - public Instant getWatermark() { - if (curRecord == null) { - LOG.warn("{}: getWatermark() : no records have been read yet.", name); - return initialWatermark; - } - - return source.watermarkFn.isPresent() - ? source.watermarkFn.get().apply(curRecord) - : curTimestamp; - } - - @Override - public CheckpointMark getCheckpointMark() { - return new KafkaCheckpointMark( - ImmutableList.copyOf( - // avoid lazy (consumedOffset can change) - Lists.transform( - partitionStates, - new Function() { - public PartitionMark apply(PartitionState p) { - return new PartitionMark(p.topicPartition, p.consumedOffset); - } - }))); - } - - @Override - public UnboundedSource, ?> getCurrentSource() { - return source; - } - - @Override - public KafkaRecord getCurrent() throws NoSuchElementException { - // should we delay updating consumed offset till this point? Mostly not required. - return curRecord; - } - - @Override - public Instant getCurrentTimestamp() throws NoSuchElementException { - return curTimestamp; - } - - @Override - public long getSplitBacklogBytes() { - long backlogBytes = 0; - - for (PartitionState p : partitionStates) { - long pBacklog = p.approxBacklogInBytes(); - if (pBacklog == UnboundedReader.BACKLOG_UNKNOWN) { - return UnboundedReader.BACKLOG_UNKNOWN; - } - backlogBytes += pBacklog; - } - - return backlogBytes; - } - - @Override - public void close() throws IOException { - closed.set(true); - consumerPollThread.shutdown(); - offsetFetcherThread.shutdown(); - - boolean isShutdown = false; - - // Wait for threads to shutdown. Trying this a loop to handle a tiny race where poll thread - // might block to enqueue right after availableRecordsQueue.poll() below. - while (!isShutdown) { - - consumer.wakeup(); - offsetConsumer.wakeup(); - availableRecordsQueue.poll(); // drain unread batch, this unblocks consumer thread. - try { - isShutdown = - consumerPollThread.awaitTermination(10, TimeUnit.SECONDS) - && offsetFetcherThread.awaitTermination(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); // not expected - } - - if (!isShutdown) { - LOG.warn("An internal thread is taking a long time to shutdown. will retry."); - } - } - - Closeables.close(offsetConsumer, true); - Closeables.close(consumer, true); - } - } - - //////////////////////// Sink Support \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ - - /** - * A {@link PTransform} to write to a Kafka topic. See {@link KafkaIO} for more information on - * usage and configuration. - */ - public static class Write extends TypedWrite { - - /** - * Returns a new {@link Write} transform with Kafka producer pointing to {@code - * bootstrapServers}. - */ - public Write withBootstrapServers(String bootstrapServers) { - return updateProducerProperties( - ImmutableMap.of( - ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers)); - } - - /** - * Returns a new {@link Write} transform that write to given topic. - */ - public Write withTopic(String topic) { - return new Write(topic, keyCoder, valueCoder, producerConfig); - } - - /** - * Returns a new {@link Write} with {@link Coder} for serializing key (if any) to bytes. A key - * is optional while writing to Kafka. Note when a key is set, its hash is used to determine - * partition in Kafka (see {@link ProducerRecord} for more details). - */ - public Write withKeyCoder(Coder keyCoder) { - return new Write(topic, keyCoder, valueCoder, producerConfig); - } - - /** - * Returns a new {@link Write} with {@link Coder} for serializing value to bytes. - */ - public Write withValueCoder(Coder valueCoder) { - return new Write(topic, keyCoder, valueCoder, producerConfig); - } - - public Write updateProducerProperties(Map configUpdates) { - Map config = - updateKafkaProperties( - producerConfig, TypedWrite.IGNORED_PRODUCER_PROPERTIES, configUpdates); - return new Write(topic, keyCoder, valueCoder, config); - } - - private Write( - String topic, Coder keyCoder, Coder valueCoder, Map producerConfig) { - super( - topic, - keyCoder, - valueCoder, - producerConfig, - Optional., Producer>>absent()); - } - } - - /** - * A {@link PTransform} to write to a Kafka topic. See {@link KafkaIO} for more information on - * usage and configuration. - */ - public static class TypedWrite extends PTransform>, PDone> { - - /** - * Returns a new {@link Write} with a custom function to create Kafka producer. Primarily used - * for tests. Default is {@link KafkaProducer} - */ - public TypedWrite withProducerFactoryFn( - SerializableFunction, Producer> producerFactoryFn) { - return new TypedWrite( - topic, keyCoder, valueCoder, producerConfig, Optional.of(producerFactoryFn)); - } - - /** - * Returns a new transform that writes just the values to Kafka. This is useful for writing - * collections of values rather thank {@link KV}s. - */ - @SuppressWarnings("unchecked") - public PTransform, PDone> values() { - return new KafkaValueWrite((TypedWrite) this); - // Any way to avoid casting here to TypedWrite? We can't create - // new TypedWrite without casting producerFactoryFn. - } - - @Override - public PDone apply(PCollection> input) { - input.apply( - ParDo.of( - new KafkaWriter( - topic, keyCoder, valueCoder, producerConfig, producerFactoryFnOpt))); - return PDone.in(input.getPipeline()); - } - - @Override - public void validate(PCollection> input) { - checkNotNull( - producerConfig.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG), - "Kafka bootstrap servers should be set"); - checkNotNull(topic, "Kafka topic should be set"); - } - - ////////////////////////////////////////////////////////////////////////////////////////// - - protected final String topic; - protected final Coder keyCoder; - protected final Coder valueCoder; - protected final Optional, Producer>> - producerFactoryFnOpt; - protected final Map producerConfig; - - protected TypedWrite( - String topic, - Coder keyCoder, - Coder valueCoder, - Map producerConfig, - Optional, Producer>> producerFactoryFnOpt) { - - this.topic = topic; - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; - this.producerConfig = producerConfig; - this.producerFactoryFnOpt = producerFactoryFnOpt; - } - - // set config defaults - private static final Map DEFAULT_PRODUCER_PROPERTIES = - ImmutableMap.of( - ProducerConfig.RETRIES_CONFIG, - 3, - ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, - CoderBasedKafkaSerializer.class, - ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, - CoderBasedKafkaSerializer.class); - - /** - * A set of properties that are not required or don't make sense for our consumer. - */ - private static final Map IGNORED_PRODUCER_PROPERTIES = - ImmutableMap.of( - ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, - "Set keyCoder instead", - ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, - "Set valueCoder instead", - configForKeySerializer(), - "Reserved for internal serializer", - configForValueSerializer(), - "Reserved for internal serializer"); - } - - /** - * Same as {@link Write Write<K, V>} without a Key. Null is used for key as it is the - * convention is Kafka when there is no key specified. Majority of Kafka writers don't specify a - * key. - */ - private static class KafkaValueWrite extends PTransform, PDone> { - - private final TypedWrite kvWriteTransform; - - private KafkaValueWrite(TypedWrite kvWriteTransform) { - this.kvWriteTransform = kvWriteTransform; - } - - @Override - public PDone apply(PCollection input) { - return input - .apply( - "Kafka values with default key", - ParDo.of( - new DoFn>() { - @Override - public void processElement(ProcessContext ctx) throws Exception { - ctx.output(KV.of(null, ctx.element())); - } - })) - .setCoder(KvCoder.of(VoidCoder.of(), kvWriteTransform.valueCoder)) - .apply(kvWriteTransform); - } - } - - private static class KafkaWriter extends DoFn, Void> { - - @Override - public void startBundle(Context c) throws Exception { - // Producer initialization is fairly costly. Move this to future initialization api to avoid - // creating a producer for each bundle. - if (producer == null) { - if (producerFactoryFnOpt.isPresent()) { - producer = producerFactoryFnOpt.get().apply(producerConfig); - } else { - producer = new KafkaProducer(producerConfig); - } - } - } - - @Override - public void processElement(ProcessContext ctx) throws Exception { - checkForFailures(); - - KV kv = ctx.element(); - producer.send( - new ProducerRecord(topic, kv.getKey(), kv.getValue()), new SendCallback()); - } - - @Override - public void finishBundle(Context c) throws Exception { - producer.flush(); - producer.close(); - producer = null; - checkForFailures(); - } - - /////////////////////////////////////////////////////////////////////////////////// - - private final String topic; - private final Map producerConfig; - private final Optional, Producer>> - producerFactoryFnOpt; - - private transient Producer producer = null; - //private transient Callback sendCallback = new SendCallback(); - // first exception and number of failures since last invocation of checkForFailures(): - private transient Exception sendException = null; - private transient long numSendFailures = 0; - - KafkaWriter( - String topic, - Coder keyCoder, - Coder valueCoder, - Map producerConfig, - Optional, Producer>> producerFactoryFnOpt) { - - this.topic = topic; - this.producerFactoryFnOpt = producerFactoryFnOpt; - - // Set custom kafka serializers. We can not serialize user objects then pass the bytes to - // producer. The key and value objects are used in kafka Partitioner interface. - // This does not matter for default partitioner in Kafka as it uses just the serialized - // key bytes to pick a partition. But are making sure user's custom partitioner would work - // as expected. - - this.producerConfig = new HashMap<>(producerConfig); - this.producerConfig.put(configForKeySerializer(), keyCoder); - this.producerConfig.put(configForValueSerializer(), valueCoder); - } - - private synchronized void checkForFailures() throws IOException { - if (numSendFailures == 0) { - return; - } - - String msg = - String.format( - "KafkaWriter : failed to send %d records (since last report)", numSendFailures); - - Exception e = sendException; - sendException = null; - numSendFailures = 0; - - LOG.warn(msg); - throw new IOException(msg, e); - } - - private class SendCallback implements Callback { - @Override - public void onCompletion(RecordMetadata metadata, Exception exception) { - if (exception == null) { - return; - } - - synchronized (KafkaWriter.this) { - if (sendException == null) { - sendException = exception; - } - numSendFailures++; - } - // don't log exception stacktrace here, exception will be propagated up. - LOG.warn("KafkaWriter send failed : '{}'", exception.getMessage()); - } - } - } - - /** - * Implements Kafka's {@link Serializer} with a {@link Coder}. The coder is stored as serialized - * value in producer configuration map. - */ - public static class CoderBasedKafkaSerializer implements Serializer { - - @SuppressWarnings("unchecked") - @Override - public void configure(Map configs, boolean isKey) { - String configKey = isKey ? configForKeySerializer() : configForValueSerializer(); - coder = (Coder) configs.get(configKey); - checkNotNull(coder, "could not instantiate coder for Kafka serialization"); - } - - @Override - public byte[] serialize(String topic, @Nullable T data) { - if (data == null) { - return null; // common for keys to be null - } - - try { - return CoderUtils.encodeToByteArray(coder, data); - } catch (CoderException e) { - throw new RuntimeException(e); - } - } - - @Override - public void close() {} - - private Coder coder = null; - private static final String CONFIG_FORMAT = - "com.google.cloud.dataflow.coder.based.kafka.%s.serializer"; - } - - private static String configForKeySerializer() { - return String.format(CoderBasedKafkaSerializer.CONFIG_FORMAT, "key"); - } - - private static String configForValueSerializer() { - return String.format(CoderBasedKafkaSerializer.CONFIG_FORMAT, "value"); - } -} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java deleted file mode 100644 index 7373c2d6e5..0000000000 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecord.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.kafka; - -import com.google.cloud.dataflow.sdk.values.KV; - -import java.io.Serializable; -import java.util.Arrays; - -/** - * KafkaRecord contains key and value of the record as well as metadata for the record (topic name, - * partition id, and offset). - */ -public class KafkaRecord implements Serializable { - - private final String topic; - private final int partition; - private final long offset; - private final KV kv; - - public KafkaRecord(String topic, int partition, long offset, K key, V value) { - this(topic, partition, offset, KV.of(key, value)); - } - - public KafkaRecord(String topic, int partition, long offset, KV kv) { - - this.topic = topic; - this.partition = partition; - this.offset = offset; - this.kv = kv; - } - - public String getTopic() { - return topic; - } - - public int getPartition() { - return partition; - } - - public long getOffset() { - return offset; - } - - public KV getKV() { - return kv; - } - - @Override - public int hashCode() { - return Arrays.deepHashCode(new Object[] {topic, partition, offset, kv}); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof KafkaRecord) { - @SuppressWarnings("unchecked") - KafkaRecord other = (KafkaRecord) obj; - return topic.equals(other.topic) - && partition == other.partition - && offset == other.offset - && kv.equals(other.kv); - } else { - return false; - } - } -} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java deleted file mode 100644 index ed29c13342..0000000000 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaRecordCoder.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.kafka; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.coders.VarLongCoder; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.values.KV; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -/** - * {@link Coder} for {@link KafkaRecord}. - */ -public class KafkaRecordCoder extends StandardCoder> { - - private static final StringUtf8Coder stringCoder = StringUtf8Coder.of(); - private static final VarLongCoder longCoder = VarLongCoder.of(); - private static final VarIntCoder intCoder = VarIntCoder.of(); - - private final KvCoder kvCoder; - - @JsonCreator - public static KafkaRecordCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List> components) { - KvCoder kvCoder = KvCoder.of(components); - return of(kvCoder.getKeyCoder(), kvCoder.getValueCoder()); - } - - public static KafkaRecordCoder of(Coder keyCoder, Coder valueCoder) { - return new KafkaRecordCoder(keyCoder, valueCoder); - } - - public KafkaRecordCoder(Coder keyCoder, Coder valueCoder) { - this.kvCoder = KvCoder.of(keyCoder, valueCoder); - } - - @Override - public void encode( - com.google.cloud.dataflow.contrib.kafka.KafkaRecord value, - OutputStream outStream, - Context context) - throws CoderException, IOException { - Context nested = context.nested(); - stringCoder.encode(value.getTopic(), outStream, nested); - intCoder.encode(value.getPartition(), outStream, nested); - longCoder.encode(value.getOffset(), outStream, nested); - kvCoder.encode(value.getKV(), outStream, nested); - } - - @Override - public com.google.cloud.dataflow.contrib.kafka.KafkaRecord decode( - InputStream inStream, Context context) throws CoderException, IOException { - Context nested = context.nested(); - return new com.google.cloud.dataflow.contrib.kafka.KafkaRecord( - stringCoder.decode(inStream, nested), - intCoder.decode(inStream, nested), - longCoder.decode(inStream, nested), - kvCoder.decode(inStream, nested)); - } - - @Override - public List> getCoderArguments() { - return kvCoder.getCoderArguments(); - } - - @Override - public void verifyDeterministic() throws NonDeterministicException { - kvCoder.verifyDeterministic(); - } - - @Override - public boolean isRegisterByteSizeObserverCheap( - com.google.cloud.dataflow.contrib.kafka.KafkaRecord value, Context context) { - return kvCoder.isRegisterByteSizeObserverCheap(value.getKV(), context); - //TODO : do we have to implement getEncodedSize()? - } - - @SuppressWarnings("unchecked") - @Override - public Object structuralValue(com.google.cloud.dataflow.contrib.kafka.KafkaRecord value) - throws Exception { - if (consistentWithEquals()) { - return value; - } else { - return new com.google.cloud.dataflow.contrib.kafka.KafkaRecord( - value.getTopic(), - value.getPartition(), - value.getOffset(), - (KV) kvCoder.structuralValue(value.getKV())); - } - } - - @Override - public boolean consistentWithEquals() { - return kvCoder.consistentWithEquals(); - } -} diff --git a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java b/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java deleted file mode 100644 index 48746c1908..0000000000 --- a/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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. - */ - -/** - * Transforms for reading and writing from Apache Kafka. - */ -package com.google.cloud.dataflow.contrib.kafka; diff --git a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java b/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java deleted file mode 100644 index 19d4336a5b..0000000000 --- a/contrib/kafka/src/test/java/com/google/cloud/dataflow/contrib/kafka/KafkaIOTest.java +++ /dev/null @@ -1,668 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.kafka; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.Pipeline.PipelineExecutionException; -import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; -import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; -import com.google.cloud.dataflow.sdk.io.Read; -import com.google.cloud.dataflow.sdk.io.UnboundedSource; -import com.google.cloud.dataflow.sdk.io.UnboundedSource.UnboundedReader; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.Flatten; -import com.google.cloud.dataflow.sdk.transforms.Max; -import com.google.cloud.dataflow.sdk.transforms.Min; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.transforms.Values; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import com.google.cloud.dataflow.sdk.values.PCollectionList; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -import org.apache.kafka.clients.consumer.Consumer; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.MockConsumer; -import org.apache.kafka.clients.consumer.OffsetResetStrategy; -import org.apache.kafka.clients.producer.MockProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.PartitionInfo; -import org.apache.kafka.common.TopicPartition; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.annotation.Nullable; - -/** - * Tests of {@link KafkaIO}. - */ -@RunWith(JUnit4.class) -public class KafkaIOTest { - /* - * The tests below borrow code and structure from CountingSourceTest. In addition verifies - * the reader interleaves the records from multiple partitions. - * - * Other tests to consider : - * - test KafkaRecordCoder - */ - - @Rule public ExpectedException thrown = ExpectedException.none(); - - // Update mock consumer with records distributed among the given topics, each with given number - // of partitions. Records are assigned in round-robin order among the partitions. - private static MockConsumer mkMockConsumer( - List topics, int partitionsPerTopic, int numElements) { - - final List partitions = new ArrayList<>(); - final Map>> records = new HashMap<>(); - Map> partitionMap = new HashMap<>(); - - for (String topic : topics) { - List partIds = new ArrayList<>(partitionsPerTopic); - for (int i = 0; i < partitionsPerTopic; i++) { - partitions.add(new TopicPartition(topic, i)); - partIds.add(new PartitionInfo(topic, i, null, null, null)); - } - partitionMap.put(topic, partIds); - } - - int numPartitions = partitions.size(); - long[] offsets = new long[numPartitions]; - - for (int i = 0; i < numElements; i++) { - int pIdx = i % numPartitions; - TopicPartition tp = partitions.get(pIdx); - - if (!records.containsKey(tp)) { - records.put(tp, new ArrayList>()); - } - records - .get(tp) - .add( - new ConsumerRecord( - tp.topic(), - tp.partition(), - offsets[pIdx]++, - ByteBuffer.wrap(new byte[8]).putInt(i).array(), - // key is 4 byte record id - ByteBuffer.wrap(new byte[8]).putLong(i).array())); // value is 8 byte record id - } - - MockConsumer consumer = - new MockConsumer(OffsetResetStrategy.EARLIEST) { - // override assign() to add records that belong to the assigned partitions. - public void assign(List assigned) { - super.assign(assigned); - for (TopicPartition tp : assigned) { - for (ConsumerRecord r : records.get(tp)) { - addRecord(r); - } - updateBeginningOffsets(ImmutableMap.of(tp, 0L)); - updateEndOffsets(ImmutableMap.of(tp, (long) records.get(tp).size())); - seek(tp, 0); - } - } - }; - - for (String topic : topics) { - consumer.updatePartitions(topic, partitionMap.get(topic)); - } - - return consumer; - } - - private static class ConsumerFactoryFn - implements SerializableFunction, Consumer> { - private final List topics; - private final int partitionsPerTopic; - private final int numElements; - - public ConsumerFactoryFn(List topics, int partitionsPerTopic, int numElements) { - this.topics = topics; - this.partitionsPerTopic = partitionsPerTopic; - this.numElements = numElements; - } - - public Consumer apply(Map config) { - return mkMockConsumer(topics, partitionsPerTopic, numElements); - } - } - - /** - * Creates a consumer with two topics, with 10 partitions each. numElements are (round-robin) - * assigned all the 20 partitions. - */ - private static KafkaIO.TypedRead mkKafkaReadTransform( - int numElements, @Nullable SerializableFunction, Instant> timestampFn) { - - List topics = ImmutableList.of("topic_a", "topic_b"); - - com.google.cloud.dataflow.contrib.kafka.KafkaIO.Read reader = - com.google.cloud.dataflow.contrib.kafka.KafkaIO.read() - .withBootstrapServers("none") - .withTopics(topics) - .withConsumerFactoryFn(new ConsumerFactoryFn(topics, 10, numElements)) // 20 partitions - .withKeyCoder(BigEndianIntegerCoder.of()) - .withValueCoder(BigEndianLongCoder.of()) - .withMaxNumRecords(numElements); - - if (timestampFn != null) { - return reader.withTimestampFn(timestampFn); - } else { - return reader; - } - } - - private static class AssertMultipleOf implements SerializableFunction, Void> { - private final int num; - - public AssertMultipleOf(int num) { - this.num = num; - } - - @Override - public Void apply(Iterable values) { - for (Long v : values) { - assertEquals(0, v % num); - } - return null; - } - } - - public static void addCountingAsserts(PCollection input, long numElements) { - // Count == numElements - DataflowAssert.thatSingleton(input.apply("Count", Count.globally())) - .isEqualTo(numElements); - // Unique count == numElements - DataflowAssert.thatSingleton( - input - .apply(RemoveDuplicates.create()) - .apply("UniqueCount", Count.globally())) - .isEqualTo(numElements); - // Min == 0 - DataflowAssert.thatSingleton(input.apply("Min", Min.globally())).isEqualTo(0L); - // Max == numElements-1 - DataflowAssert.thatSingleton(input.apply("Max", Max.globally())) - .isEqualTo(numElements - 1); - } - - @Test - public void testUnboundedSource() { - Pipeline p = TestPipeline.create(); - int numElements = 1000; - - PCollection input = - p - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) - .apply(Values.create()); - - addCountingAsserts(input, numElements); - p.run(); - } - - @Test - public void testUnboundedSourceWithExplicitPartitions() { - Pipeline p = TestPipeline.create(); - int numElements = 1000; - - List topics = ImmutableList.of("test"); - - com.google.cloud.dataflow.contrib.kafka.KafkaIO.TypedRead reader = - com.google.cloud.dataflow.contrib.kafka.KafkaIO.read() - .withBootstrapServers("none") - .withTopicPartitions(ImmutableList.of(new TopicPartition("test", 5))) - .withConsumerFactoryFn(new ConsumerFactoryFn(topics, 10, numElements)) // 10 partitions - .withValueCoder(BigEndianLongCoder.of()) - .withMaxNumRecords(numElements / 10); - - PCollection input = p.apply(reader.withoutMetadata()).apply(Values.create()); - - // assert that every element is a multiple of 5. - DataflowAssert.that(input).satisfies(new AssertMultipleOf(5)); - - DataflowAssert.thatSingleton(input.apply(Count.globally())).isEqualTo(numElements / 10L); - - p.run(); - } - - private static class ElementValueDiff extends DoFn { - @Override - public void processElement(ProcessContext c) throws Exception { - c.output(c.element() - c.timestamp().getMillis()); - } - } - - @Test - public void testUnboundedSourceTimestamps() { - Pipeline p = TestPipeline.create(); - int numElements = 1000; - - PCollection input = - p - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) - .apply(Values.create()); - - addCountingAsserts(input, numElements); - - PCollection diffs = - input - .apply("TimestampDiff", ParDo.of(new ElementValueDiff())) - .apply("RemoveDuplicateTimestamps", RemoveDuplicates.create()); - // This assert also confirms that diffs only has one unique value. - DataflowAssert.thatSingleton(diffs).isEqualTo(0L); - - p.run(); - } - - private static class RemoveKafkaMetadata - extends DoFn, KV> { - @Override - public void processElement(ProcessContext ctx) throws Exception { - ctx.output(ctx.element().getKV()); - } - } - - @Test - public void testUnboundedSourceSplits() throws Exception { - Pipeline p = TestPipeline.create(); - int numElements = 1000; - int numSplits = 20; - - UnboundedSource, ?> initial = - mkKafkaReadTransform(numElements, null).makeSource(); - List, ?>> splits = - initial.generateInitialSplits(1, p.getOptions()); - assertEquals("KafkaIO should ignore desiredNumSplits", numSplits, splits.size()); - - long elementsPerSplit = numElements / numSplits; - assertEquals("Expected even splits", numElements, elementsPerSplit * numSplits); - PCollectionList pcollections = PCollectionList.empty(p); - for (int i = 0; i < splits.size(); ++i) { - pcollections = - pcollections.and( - p - .apply("split" + i, Read.from(splits.get(i)).withMaxNumRecords(elementsPerSplit)) - .apply("Remove Metadata " + i, ParDo.of(new RemoveKafkaMetadata())) - .apply("collection " + i, Values.create())); - } - PCollection input = pcollections.apply(Flatten.pCollections()); - - addCountingAsserts(input, numElements); - p.run(); - } - - /** - * A timestamp function that uses the given value as the timestamp. - */ - private static class ValueAsTimestampFn - implements SerializableFunction, Instant> { - @Override - public Instant apply(KV input) { - return new Instant(input.getValue()); - } - } - - // Kafka records are read in a separate thread inside the reader. As a result advance() might not - // read any records even from the mock consumer, especially for the first record. - // This is a helper method to loop until we read a record. - private static void advanceOnce(UnboundedReader reader) throws IOException { - while (!reader.advance()) { - // very rarely will there be more than one attempts. - // in case of a bug we might end up looping forever, and test will fail with a timeout. - } - } - - @Test - public void testUnboundedSourceCheckpointMark() throws Exception { - int numElements = 85; // 85 to make sure some partitions have more records than other. - - // create a single split: - UnboundedSource< - com.google.cloud.dataflow.contrib.kafka.KafkaRecord, - com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark> - source = - mkKafkaReadTransform(numElements, new ValueAsTimestampFn()) - .makeSource(); - - UnboundedReader> reader = - source.createReader(null, null); - final int numToSkip = 3; - - // advance numToSkip elements - if (!reader.start()) { - advanceOnce(reader); - } - - for (long l = 0; l < numToSkip - 1; ++l) { - advanceOnce(reader); - } - - // Confirm that we get the expected element in sequence before checkpointing. - assertEquals(numToSkip - 1, (long) reader.getCurrent().getKV().getValue()); - assertEquals(numToSkip - 1, reader.getCurrentTimestamp().getMillis()); - - // Checkpoint and restart, and confirm that the source continues correctly. - com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark mark = - CoderUtils.clone( - source.getCheckpointMarkCoder(), - (com.google.cloud.dataflow.contrib.kafka.KafkaCheckpointMark) - reader.getCheckpointMark()); - reader = source.createReader(null, mark); - - // Confirm that we get the next elements in sequence. - // This also confirms that Reader interleaves records from each partitions by the reader. - - if (!reader.start()) { - advanceOnce(reader); - } - - for (int i = numToSkip; i < numElements; i++) { - assertEquals(i, (long) reader.getCurrent().getKV().getValue()); - assertEquals(i, reader.getCurrentTimestamp().getMillis()); - if ((i + 1) < numElements) { - advanceOnce(reader); - } - } - } - - @Test - public void testSink() throws Exception { - // Simply read from kafka source and write to kafka sink. Then verify the records - // are correctly published to mock kafka producer. - - int numElements = 1000; - - synchronized (MOCK_PRODUCER_LOCK) { - MOCK_PRODUCER.clear(); - - ProducerSendCompletionThread completionThread = new ProducerSendCompletionThread().start(); - - Pipeline pipeline = TestPipeline.create(); - String topic = "test"; - - pipeline - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) - .apply( - com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() - .withBootstrapServers("none") - .withTopic(topic) - .withKeyCoder(BigEndianIntegerCoder.of()) - .withValueCoder(BigEndianLongCoder.of()) - .withProducerFactoryFn(new ProducerFactoryFn())); - - pipeline.run(); - - completionThread.shutdown(); - - verifyProducerRecords(topic, numElements, false); - } - } - - @Test - public void testValuesSink() throws Exception { - // similar to testSink(), but use values()' interface. - - int numElements = 1000; - - synchronized (MOCK_PRODUCER_LOCK) { - MOCK_PRODUCER.clear(); - - ProducerSendCompletionThread completionThread = new ProducerSendCompletionThread().start(); - - Pipeline pipeline = TestPipeline.create(); - String topic = "test"; - - pipeline - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) - .apply(Values.create()) // there are no keys - .apply( - com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() - .withBootstrapServers("none") - .withTopic(topic) - .withKeyCoder(BigEndianIntegerCoder.of()) - .withValueCoder(BigEndianLongCoder.of()) - .withProducerFactoryFn(new ProducerFactoryFn()) - .values()); - - pipeline.run(); - - completionThread.shutdown(); - - verifyProducerRecords(topic, numElements, true); - } - } - - @Test - public void testSinkWithSendErrors() throws Throwable { - // similar to testSink(), except that up to 10 of the send calls to producer will fail - // asynchronously. - - // TODO: Ideally we want the pipeline to run to completion by retrying bundles that fail. - // We limit the number of errors injected to 10 below. This would reflect a real streaming - // pipeline. But I am sure how to achieve that. For now expect an exception: - - thrown.expect(InjectedErrorException.class); - thrown.expectMessage("Injected Error #1"); - - int numElements = 1000; - - synchronized (MOCK_PRODUCER_LOCK) { - MOCK_PRODUCER.clear(); - - Pipeline pipeline = TestPipeline.create(); - String topic = "test"; - - ProducerSendCompletionThread completionThreadWithErrors = - new ProducerSendCompletionThread(10, 100).start(); - - pipeline - .apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata()) - .apply( - com.google.cloud.dataflow.contrib.kafka.KafkaIO.write() - .withBootstrapServers("none") - .withTopic(topic) - .withKeyCoder(BigEndianIntegerCoder.of()) - .withValueCoder(BigEndianLongCoder.of()) - .withProducerFactoryFn(new ProducerFactoryFn())); - - try { - pipeline.run(); - } catch (PipelineExecutionException e) { - // throwing inner exception helps assert that first exception is thrown from the Sink - throw e.getCause().getCause(); - } finally { - completionThreadWithErrors.shutdown(); - } - } - } - - private static void verifyProducerRecords(String topic, int numElements, boolean keyIsAbsent) { - - // verify that appropriate messages are written to kafka - List> sent = MOCK_PRODUCER.history(); - - // sort by values - Collections.sort( - sent, - new Comparator>() { - @Override - public int compare(ProducerRecord o1, ProducerRecord o2) { - return Long.compare(o1.value(), o2.value()); - } - }); - - for (int i = 0; i < numElements; i++) { - ProducerRecord record = sent.get(i); - assertEquals(topic, record.topic()); - if (keyIsAbsent) { - assertNull(record.key()); - } else { - assertEquals(i, record.key().intValue()); - } - assertEquals(i, record.value().longValue()); - } - } - - /** - * Singleton MockProudcer. Using a singleton here since we need access to the object to fetch the - * actual records published to the producer. This prohibits running the tests using the producer - * in parallel, but there are only one or two tests. - */ - private static final MockProducer MOCK_PRODUCER = - new MockProducer( - false, - // disable synchronous completion of send. see ProducerSendCompletionThread below. - new com.google.cloud.dataflow.contrib.kafka.KafkaIO.CoderBasedKafkaSerializer(), - new com.google.cloud.dataflow.contrib.kafka.KafkaIO.CoderBasedKafkaSerializer()) { - - // override flush() so that it does not complete all the waiting sends, giving a chance to - // ProducerCompletionThread to inject errors. - - @Override - public void flush() { - while (completeNext()) { - // there are some uncompleted records. let the completion thread handle them. - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - } - }; - - // use a separate object serialize tests using MOCK_PRODUCER so that we don't interfere - // with Kafka MockProducer locking itself. - private static final Object MOCK_PRODUCER_LOCK = new Object(); - - private static class ProducerFactoryFn - implements SerializableFunction, Producer> { - - @Override - public Producer apply(Map config) { - return MOCK_PRODUCER; - } - } - - private static class InjectedErrorException extends RuntimeException { - public InjectedErrorException(String message) { - super(message); - } - } - - /** - * We start MockProducer with auto-completion disabled. That implies a record is not marked sent - * until #completeNext() is called on it. This class starts a thread to asynchronously 'complete' - * the the sends. During completion, we can also make those requests fail. This error injection is - * used in one of the tests. - */ - private static class ProducerSendCompletionThread { - - private final int maxErrors; - private final int errorFrequency; - private final AtomicBoolean done = new AtomicBoolean(false); - private final ExecutorService injectorThread; - private int numCompletions = 0; - - ProducerSendCompletionThread() { - // complete everything successfully - this(0, 0); - } - - ProducerSendCompletionThread(final int maxErrors, final int errorFrequency) { - this.maxErrors = maxErrors; - this.errorFrequency = errorFrequency; - injectorThread = Executors.newSingleThreadExecutor(); - } - - ProducerSendCompletionThread start() { - injectorThread.submit( - new Runnable() { - @Override - public void run() { - int errorsInjected = 0; - - while (!done.get()) { - boolean successful; - - if (errorsInjected < maxErrors && ((numCompletions + 1) % errorFrequency) == 0) { - successful = - MOCK_PRODUCER.errorNext( - new InjectedErrorException("Injected Error #" + (errorsInjected + 1))); - - if (successful) { - errorsInjected++; - } - } else { - successful = MOCK_PRODUCER.completeNext(); - } - - if (successful) { - numCompletions++; - } else { - // wait a bit since there are no unsent records - try { - Thread.sleep(1); - } catch (InterruptedException e) { - } - } - } - } - }); - - return this; - } - - void shutdown() { - done.set(true); - injectorThread.shutdown(); - try { - assertTrue(injectorThread.awaitTermination(10, TimeUnit.SECONDS)); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - } - } - } -} diff --git a/contrib/sorter/README.md b/contrib/sorter/README.md deleted file mode 100644 index 1f6c3a5d93..0000000000 --- a/contrib/sorter/README.md +++ /dev/null @@ -1,23 +0,0 @@ -#Sorter -This module provides the SortValues transform, which takes a `PCollection>>>` and produces a `PCollection>>>` where, for each primary key `K` the paired `Iterable>` has been sorted by the byte encoding of secondary key (`K2`). It will efficiently and scalably sort the iterables, even if they are large (do not fit in memory). - -##Caveats -* This transform performs value-only sorting; the iterable accompanying each key is sorted, but *there is no relationship between different keys*, as Dataflow does not support any defined relationship between different elements in a PCollection. -* Each `Iterable>` is sorted on a single worker using local memory and disk. This means that `SortValues` may be a performance and/or scalability bottleneck when used in different pipelines. For example, users are discouraged from using `SortValues` on a `PCollection` of a single element to globally sort a large `PCollection`. A (rough) estimate of the number of bytes of disk space utilized if sorting spills to disk is `numRecords * (numSecondaryKeyBytesPerRecord + numValueBytesPerRecord + 16) * 3`. - -##Options -* The user can customize the temporary location used if sorting requires spilling to disk and the maximum amount of memory to use by creating a custom instance of `BufferedExternalSorter.Options` to pass into `SortValues.create`. - -##Using `SortValues` -~~~~ -PCollection>> input = ... - -// Group by primary key, bringing pairs for the same key together. -PCollection>>> grouped = - input.apply(GroupByKey.>create()); - -// For every primary key, sort the iterable of pairs by secondary key. -PCollection>>> groupedAndSorted = - grouped.apply( - SortValues.create(new BufferedExternalSorter.Options())); -~~~~ diff --git a/contrib/sorter/pom.xml b/contrib/sorter/pom.xml deleted file mode 100644 index d9ffb65bd9..0000000000 --- a/contrib/sorter/pom.xml +++ /dev/null @@ -1,233 +0,0 @@ - - - - 4.0.0 - - com.google.cloud.dataflow - google-cloud-dataflow-java-contrib-sorter - Google Cloud Dataflow Sorter Library - Library to sort data from within Dataflow pipelines. - 0.0.1-SNAPSHOT - jar - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - [1.2.0,2.0.0) - 2.7.1 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.7 - 1.7 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - com.puppycrawl.tools - checkstyle - 6.19 - - - - ../../checkstyle.xml - true - true - true - - - - - check - - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - compile - - jar - - - - attach-test-sources - test-compile - - test-jar - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - Google Cloud Dataflow Sorter Contrib - Google Cloud Dataflow Sorter Contrib - - com.google.cloud.dataflow.contrib.sorter - false - ]]> - - - - https://cloud.google.com/dataflow/java-sdk/JavaDoc/ - ${basedir}/../../javadoc/dataflow-sdk-docs - - - http://docs.guava-libraries.googlecode.com/git-history/release18/javadoc/ - ${basedir}/../../javadoc/guava-docs - - - - - - - jar - - package - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - bundle-and-repackage - package - - shade - - - true - - - com.google.guava:guava - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - com.google.common - com.google.cloud.dataflow.repackaged.com.google.common - - - com.google.thirdparty - com.google.cloud.dataflow.repackaged.com.google.thirdparty - - - - - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${google-cloud-dataflow-version} - - - - org.apache.hadoop - hadoop-mapreduce-client-core - ${hadoop.version} - provided - - - - org.apache.hadoop - hadoop-common - ${hadoop.version} - provided - - - - com.google.guava - guava - 19.0 - - - - - org.hamcrest - hamcrest-all - 1.3 - test - - - - org.mockito - mockito-all - 1.10.19 - test - - - - junit - junit - 4.11 - test - - - diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java deleted file mode 100644 index d717f79ed7..0000000000 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorter.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.cloud.dataflow.sdk.values.KV; -import java.io.IOException; -import java.io.Serializable; - -/** - * {@link Sorter} that will use in memory sorting until the values can't fit into memory and will - * then fall back to external sorting. - */ -public class BufferedExternalSorter implements Sorter { - /** Contains configuration for the sorter. */ - public static class Options implements Serializable { - private String tempLocation = "/tmp"; - private int memoryMB = 100; - - /** Sets the path to a temporary location where the sorter writes intermediate files. */ - public void setTempLocation(String tempLocation) { - checkArgument( - !tempLocation.startsWith("gs://"), - "BufferedExternalSorter does not support GCS temporary location"); - - this.tempLocation = tempLocation; - } - - /** Returns the configured temporary location. */ - public String getTempLocation() { - return tempLocation; - } - - /** - * Sets the size of the memory buffer in megabytes. This controls both the buffer for initial in - * memory sorting and the buffer used when external sorting. Must be greater than zero and less - * than 2048. - */ - public void setMemoryMB(int memoryMB) { - checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); - // Hadoop's external sort stores the number of available memory bytes in an int, this prevents - // overflow - checkArgument(memoryMB < 2048, "memoryMB must be less than 2048"); - this.memoryMB = memoryMB; - } - - /** Returns the configured size of the memory buffer. */ - public int getMemoryMB() { - return memoryMB; - } - } - - private ExternalSorter externalSorter; - private InMemorySorter inMemorySorter; - - boolean inMemorySorterFull; - - BufferedExternalSorter(ExternalSorter externalSorter, InMemorySorter inMemorySorter) { - this.externalSorter = externalSorter; - this.inMemorySorter = inMemorySorter; - } - - public static BufferedExternalSorter create(Options options) { - ExternalSorter.Options externalSorterOptions = new ExternalSorter.Options(); - externalSorterOptions.setMemoryMB(options.getMemoryMB()); - externalSorterOptions.setTempLocation(options.getTempLocation()); - - InMemorySorter.Options inMemorySorterOptions = new InMemorySorter.Options(); - inMemorySorterOptions.setMemoryMB(options.getMemoryMB()); - - return new BufferedExternalSorter( - ExternalSorter.create(externalSorterOptions), InMemorySorter.create(inMemorySorterOptions)); - } - - @Override - public void add(KV record) throws IOException { - if (!inMemorySorterFull) { - if (inMemorySorter.addIfRoom(record)) { - return; - } else { - // Flushing contents of in memory sorter to external sorter so we can rely on external - // from here on out - inMemorySorterFull = true; - transferToExternalSorter(); - } - } - - // In memory sorter is full, so put in external sorter instead - externalSorter.add(record); - } - - /** - * Transfers all of the records loaded so far into the in memory sorter over to the external - * sorter. - */ - private void transferToExternalSorter() throws IOException { - for (KV record : inMemorySorter.sort()) { - externalSorter.add(record); - } - // Allow in memory sorter and its contents to be garbage collected - inMemorySorter = null; - } - - @Override - public Iterable> sort() throws IOException { - if (!inMemorySorterFull) { - return inMemorySorter.sort(); - } else { - return externalSorter.sort(); - } - } -} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java deleted file mode 100644 index 80937ec9e3..0000000000 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorter.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.values.KV; -import org.apache.hadoop.fs.FileSystem; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.BytesWritable; -import org.apache.hadoop.io.SequenceFile; -import org.apache.hadoop.io.SequenceFile.CompressionType; -import org.apache.hadoop.io.SequenceFile.Sorter.RawKeyValueIterator; -import org.apache.hadoop.io.SequenceFile.Writer; -import org.apache.hadoop.mapred.JobConf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.Serializable; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.UUID; - -/** Does an external sort of the provided values using Hadoop's {@link SequenceFile}. */ -class ExternalSorter implements Sorter { - private Options options; - - /** Whether {@link #sort()} was already called. */ - private boolean sortCalled = false; - - /** SequenceFile Writer for writing all input data to a file. */ - private Writer writer; - - /** Sorter used to sort the input file. */ - private SequenceFile.Sorter sorter; - - /** Temporary directory for input and intermediate files. */ - private Path tempDir; - - /** The list of input files to be sorted. */ - private Path[] paths; - - private boolean initialized = false; - - /** {@link Options} contains configuration of the sorter. */ - public static class Options implements Serializable { - private String tempLocation = "/tmp"; - private int memoryMB = 100; - - /** Sets the path to a temporary location where the sorter writes intermediate files. */ - public void setTempLocation(String tempLocation) { - if (tempLocation.startsWith("gs://")) { - throw new IllegalArgumentException("Sorter doesn't support GCS temporary location."); - } - - this.tempLocation = tempLocation; - } - - /** Returns the configured temporary location. */ - public String getTempLocation() { - return tempLocation; - } - - /** - * Sets the size of the memory buffer in megabytes. Must be greater than zero and less than - * 2048. - */ - public void setMemoryMB(int memoryMB) { - checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); - // Hadoop's external sort stores the number of available memory bytes in an int, this prevents - // integer overflow - checkArgument(memoryMB < 2048, "memoryMB must be less than 2048"); - this.memoryMB = memoryMB; - } - - /** Returns the configured size of the memory buffer. */ - public int getMemoryMB() { - return memoryMB; - } - } - - /** Returns a {@link Sorter} configured with the given {@link Options}. */ - public static ExternalSorter create(Options options) { - return new ExternalSorter(options); - } - - @Override - public void add(KV record) throws IOException { - checkState(!sortCalled, "Records can only be added before sort()"); - - initHadoopSorter(); - - BytesWritable key = new BytesWritable(record.getKey()); - BytesWritable value = new BytesWritable(record.getValue()); - - writer.append(key, value); - } - - @Override - public Iterable> sort() throws IOException { - checkState(!sortCalled, "sort() can only be called once."); - sortCalled = true; - - initHadoopSorter(); - - writer.close(); - - return new SortedRecordsIterable(); - } - - private ExternalSorter(Options options) { - this.options = options; - } - - /** - * Initializes the hadoop sorter. Does some local file system setup, and is somewhat expensive - * (~20 ms on local machine). Only executed when necessary. - */ - private void initHadoopSorter() throws IOException { - if (!initialized) { - tempDir = new Path(options.getTempLocation(), "tmp" + UUID.randomUUID().toString()); - paths = new Path[] {new Path(tempDir, "test.seq")}; - - JobConf conf = new JobConf(); - // Sets directory for intermediate files created during merge of merge sort - conf.set("io.seqfile.local.dir", tempDir.toUri().getPath()); - - writer = - SequenceFile.createWriter( - conf, - Writer.valueClass(BytesWritable.class), - Writer.keyClass(BytesWritable.class), - Writer.file(paths[0]), - Writer.compression(CompressionType.NONE)); - - FileSystem fs = FileSystem.getLocal(conf); - // Directory has to exist for Hadoop to recognize it as deletable on exit - fs.mkdirs(tempDir); - fs.deleteOnExit(tempDir); - - sorter = - new SequenceFile.Sorter( - fs, new BytesWritable.Comparator(), BytesWritable.class, BytesWritable.class, conf); - sorter.setMemory(options.getMemoryMB() * 1024 * 1024); - - initialized = true; - } - } - - /** An {@link Iterable} producing the iterators over sorted data. */ - private class SortedRecordsIterable implements Iterable> { - @Override - public Iterator> iterator() { - return new SortedRecordsIterator(); - } - } - - /** An {@link Iterator} producing the sorted data. */ - private class SortedRecordsIterator implements Iterator> { - private RawKeyValueIterator iterator; - - /** Next {@link KV} to return from {@link #next()}. */ - private KV nextKV = null; - - SortedRecordsIterator() { - try { - this.iterator = sorter.sortAndIterate(paths, tempDir, false); - } catch (IOException e) { - throw new RuntimeException(e); - } - - nextKV = KV.of(null, null); // A dummy value that will be overwritten by next(). - next(); - } - - @Override - public boolean hasNext() { - return nextKV != null; - } - - @Override - public KV next() { - if (nextKV == null) { - throw new NoSuchElementException(); - } - - KV current = nextKV; - - try { - if (iterator.next()) { - // Parse key from DataOutputBuffer. - ByteArrayInputStream keyStream = new ByteArrayInputStream(iterator.getKey().getData()); - BytesWritable key = new BytesWritable(); - key.readFields(new DataInputStream(keyStream)); - - // Parse value from ValueBytes. - ByteArrayOutputStream valOutStream = new ByteArrayOutputStream(); - iterator.getValue().writeUncompressedBytes(new DataOutputStream(valOutStream)); - ByteArrayInputStream valInStream = new ByteArrayInputStream(valOutStream.toByteArray()); - BytesWritable value = new BytesWritable(); - value.readFields(new DataInputStream(valInStream)); - - nextKV = KV.of(key.copyBytes(), value.copyBytes()); - } else { - nextKV = null; - } - } catch (IOException e) { - throw new RuntimeException(e); - } - - return current; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Iterator does not support remove"); - } - } -} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java deleted file mode 100644 index ac1b520f4e..0000000000 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorter.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.primitives.UnsignedBytes; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; - -/** - * Sorts {@code } pairs in memory. Based on the configured size of the memory buffer, - * will reject additional pairs. - */ -class InMemorySorter implements Sorter { - /** {@code Options} contains configuration of the sorter. */ - public static class Options implements Serializable { - private long memoryMB = 100; - - /** Sets the size of the memory buffer in megabytes. */ - public void setMemoryMB(long memoryMB) { - checkArgument(memoryMB > 0, "memoryMB must be greater than zero"); - this.memoryMB = memoryMB; - } - - /** Returns the configured size of the memory buffer. */ - public long getMemoryMB() { - return memoryMB; - } - } - - /** The comparator to use to sort the records by key. */ - private static final Comparator COMPARATOR = UnsignedBytes.lexicographicalComparator(); - - /** How many bytes per word in the running JVM. Assumes 64 bit/8 bytes if unknown. */ - private static final long NUM_BYTES_PER_WORD = getNumBytesPerWord(); - - /** - * Estimate of memory overhead per KV record in bytes not including memory associated with keys - * and values. - * - *

                - *
              • Object reference within {@link ArrayList} (1 word), - *
              • A {@link KV} (2 words), - *
              • Two byte arrays (2 words for array lengths), - *
              • Per-object overhead (JVM-specific, guessing 2 words * 3 objects) - *
              - */ - private static final long RECORD_MEMORY_OVERHEAD_ESTIMATE = 11 * NUM_BYTES_PER_WORD; - - /** Maximum size of the buffer in bytes. */ - private long maxBufferSize; - - /** Current number of stored bytes. Including estimated overhead bytes. */ - private long numBytes; - - /** Whether sort has been called. */ - private boolean sortCalled; - - /** The stored records to be sorted. */ - private ArrayList> records = new ArrayList>(); - - /** Private constructor. */ - private InMemorySorter(Options options) { - maxBufferSize = options.getMemoryMB() * 1024L * 1024L; - } - - /** Create a new sorter from provided options. */ - public static InMemorySorter create(Options options) { - return new InMemorySorter(options); - } - - @Override - public void add(KV record) { - checkState(addIfRoom(record), "No space remaining for in memory sorting"); - } - - /** Adds the record is there is room and returns true. Otherwise returns false. */ - public boolean addIfRoom(KV record) { - checkState(!sortCalled, "Records can only be added before sort()"); - - long recordBytes = estimateRecordBytes(record); - if (roomInBuffer(numBytes + recordBytes, records.size() + 1)) { - records.add(record); - numBytes += recordBytes; - return true; - } else { - return false; - } - } - - @Override - public Iterable> sort() { - checkState(!sortCalled, "sort() can only be called once."); - - sortCalled = true; - - Comparator> kvComparator = - new Comparator>() { - - @Override - public int compare(KV o1, KV o2) { - return COMPARATOR.compare(o1.getKey(), o2.getKey()); - } - }; - Collections.sort(records, kvComparator); - return Collections.unmodifiableList(records); - } - - /** - * Estimate the number of additional bytes required to store this record. Including the key, the - * value and any overhead for objects and references. - */ - private long estimateRecordBytes(KV record) { - return RECORD_MEMORY_OVERHEAD_ESTIMATE + record.getKey().length + record.getValue().length; - } - - /** - * Check whether we have room to store the provided total number of bytes and total number of - * records. - */ - private boolean roomInBuffer(long numBytes, long numRecords) { - // Collections.sort may allocate up to n/2 extra object references. - // Also, ArrayList grows by a factor of 1.5x, so there might be up to n/2 null object - // references in the backing array. - // And finally, in Java 7, Collections.sort performs a defensive copy to an array in case the - // input list is a LinkedList. - // So assume we need an additional overhead of two words per record in the worst case - return (numBytes + (numRecords * NUM_BYTES_PER_WORD * 2)) < maxBufferSize; - } - - /** - * Returns the number of bytes in a word according to the JVM. Defaults to 8 for 64 bit if answer - * unknown. - */ - private static long getNumBytesPerWord() { - String bitsPerWord = System.getProperty("sun.arch.data.model"); - - try { - return Long.parseLong(bitsPerWord) / 8; - } catch (Exception e) { - // Can't determine whether 32 or 64 bit, so assume 64 - return 8; - } - } -} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/SortValues.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/SortValues.java deleted file mode 100644 index 32c393277c..0000000000 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/SortValues.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.IterableCoder; -import com.google.cloud.dataflow.sdk.coders.KvCoder; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.util.CoderUtils; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import java.io.IOException; -import java.util.Iterator; - -/** - * {@code SortValues} takes a {@code PCollection>>>} with elements consisting of a primary key and iterables - * over {@code } pairs, and returns a {@code PCollection>>} of the same elements but with values sorted by a secondary - * key. - * - *

              This transform ignores the primary key, there is no guarantee of any relationship between - * elements with different primary keys. The primary key is explicit here only because this - * transform is typically used on a result of a {@link GroupByKey} transform. - * - *

              This transform sorts by lexicographic comparison of the byte representations of the secondary - * keys and may write secondary key-value pairs to disk. In order to retrieve the byte - * representations it requires the input PCollection to use a {@link KvCoder} for its input, an - * {@link IterableCoder} for its input values and a {@link KvCoder} for its secondary key-value - * pairs. - */ -public class SortValues - extends PTransform< - PCollection>>>, - PCollection>>>> { - - private BufferedExternalSorter.Options sorterOptions; - - private SortValues(BufferedExternalSorter.Options sorterOptions) { - this.sorterOptions = sorterOptions; - } - - /** - * Returns a {@code SortValues} {@link PTransform}. - * - * @param the type of the primary keys of the input and output {@code PCollection}s - * @param the type of the secondary (sort) keys of the input and output {@code - * PCollection}s - * @param the type of the values of the input and output {@code PCollection}s - */ - public static - SortValues create( - BufferedExternalSorter.Options sorterOptions) { - return new SortValues<>(sorterOptions); - } - - @Override - public PCollection>>> apply( - PCollection>>> input) { - return input.apply( - ParDo.of( - new SortValuesDoFn( - sorterOptions, - getSecondaryKeyCoder(input.getCoder()), - getValueCoder(input.getCoder())))); - } - - @Override - protected Coder>>> getDefaultOutputCoder( - PCollection>>> input) { - return input.getCoder(); - } - - /** Retrieves the {@link Coder} for the secondary key-value pairs. */ - @SuppressWarnings("unchecked") - private static - KvCoder getSecondaryKeyValueCoder( - Coder>>> inputCoder) { - if (!(inputCoder instanceof KvCoder)) { - throw new IllegalStateException("SortValues requires its input to use KvCoder"); - } - @SuppressWarnings("unchecked") - KvCoder>> kvCoder = - (KvCoder>>) (inputCoder); - - if (!(kvCoder.getValueCoder() instanceof IterableCoder)) { - throw new IllegalStateException( - "SortValues requires the values be encoded with IterableCoder"); - } - IterableCoder> iterableCoder = - (IterableCoder>) (kvCoder.getValueCoder()); - - if (!(iterableCoder.getElemCoder() instanceof KvCoder)) { - throw new IllegalStateException( - "SortValues requires the secondary key-value pairs to use KvCoder"); - } - return (KvCoder) (iterableCoder.getElemCoder()); - } - - /** Retrieves the {@link Coder} for the secondary keys. */ - private static Coder getSecondaryKeyCoder( - Coder>>> inputCoder) { - return getSecondaryKeyValueCoder(inputCoder).getKeyCoder(); - } - - /** Returns the {@code Coder} of the values associated with the secondary keys. */ - private static Coder getValueCoder( - Coder>>> inputCoder) { - return getSecondaryKeyValueCoder(inputCoder).getValueCoder(); - } - - private static class SortValuesDoFn - extends DoFn< - KV>>, - KV>>> { - private final BufferedExternalSorter.Options sorterOptions; - private final Coder keyCoder; - private final Coder valueCoder; - - SortValuesDoFn( - BufferedExternalSorter.Options sorterOptions, - Coder keyCoder, - Coder valueCoder) { - this.sorterOptions = sorterOptions; - this.keyCoder = keyCoder; - this.valueCoder = valueCoder; - } - - @Override - public void processElement(ProcessContext c) { - Iterable> records = c.element().getValue(); - - try { - Sorter sorter = BufferedExternalSorter.create(sorterOptions); - for (KV record : records) { - sorter.add( - KV.of( - CoderUtils.encodeToByteArray(keyCoder, record.getKey()), - CoderUtils.encodeToByteArray(valueCoder, record.getValue()))); - } - - c.output( - KV.of( - c.element().getKey(), - (Iterable>) (new DecodingIterable(sorter.sort())))); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private class DecodingIterable implements Iterable> { - Iterable> iterable; - - DecodingIterable(Iterable> iterable) { - this.iterable = iterable; - } - - @Override - public Iterator> iterator() { - return new DecodingIterator(iterable.iterator()); - } - } - - private class DecodingIterator implements Iterator> { - Iterator> iterator; - - DecodingIterator(Iterator> iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public KV next() { - KV next = iterator.next(); - try { - return KV.of( - CoderUtils.decodeFromByteArray(keyCoder, next.getKey()), - CoderUtils.decodeFromByteArray(valueCoder, next.getValue())); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Iterator does not support remove"); - } - } - } -} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/Sorter.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/Sorter.java deleted file mode 100644 index b28b28314c..0000000000 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/Sorter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import com.google.cloud.dataflow.sdk.values.KV; -import java.io.IOException; - -/** - * Interface for classes which can sort {@code } pairs by the key. - * - *

              Records must first be added by calling {@link #add(KV)}. Then {@link #sort()} can be called at - * most once. - * - *

              TODO: Support custom comparison functions. - */ -interface Sorter { - - /** - * Adds a given record to the sorter. - * - *

              Records can only be added before calling {@link #sort()}. - */ - void add(KV record) throws IOException; - - /** - * Sorts the added elements and returns an {@link Iterable} over the sorted elements. - * - *

              Can be called at most once. - */ - Iterable> sort() throws IOException; -} diff --git a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/package-info.java b/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/package-info.java deleted file mode 100644 index 9a06e84b5b..0000000000 --- a/contrib/sorter/src/main/java/com/google/cloud/dataflow/contrib/sorter/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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. - */ - -/** - * Utility for performing local sort of potentially large sets of values. Will sort in memory and - * spill to disk for external sorting if necessary. - */ -package com.google.cloud.dataflow.contrib.sorter; diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java deleted file mode 100644 index f43663c60b..0000000000 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/BufferedExternalSorterTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.cloud.dataflow.contrib.sorter.SorterTestUtils.SorterGenerator; -import com.google.cloud.dataflow.sdk.values.KV; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** Tests for {@link BufferedExternalSorter}. */ -@RunWith(JUnit4.class) -public class BufferedExternalSorterTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - @SuppressWarnings("unchecked") - @Test - public void testNoFallback() throws Exception { - ExternalSorter mockExternalSorter = mock(ExternalSorter.class); - InMemorySorter mockInMemorySorter = mock(InMemorySorter.class); - BufferedExternalSorter testSorter = - new BufferedExternalSorter(mockExternalSorter, mockInMemorySorter); - - KV[] kvs = - new KV[] { - KV.of(new byte[] {0}, new byte[] {}), - KV.of(new byte[] {0, 1}, new byte[] {}), - KV.of(new byte[] {1}, new byte[] {}) - }; - - when(mockInMemorySorter.addIfRoom(kvs[0])).thenReturn(true); - when(mockInMemorySorter.addIfRoom(kvs[1])).thenReturn(true); - when(mockInMemorySorter.addIfRoom(kvs[2])).thenReturn(true); - when(mockInMemorySorter.sort()).thenReturn(Arrays.asList(kvs[0], kvs[1], kvs[2])); - - testSorter.add(kvs[0]); - testSorter.add(kvs[1]); - testSorter.add(kvs[2]); - - assertEquals(Arrays.asList(kvs[0], kvs[1], kvs[2]), testSorter.sort()); - - // Verify external sorter was never called - verify(mockExternalSorter, never()).add(any(KV.class)); - verify(mockExternalSorter, never()).sort(); - } - - @Test - public void testFallback() throws Exception { - ExternalSorter mockExternalSorter = mock(ExternalSorter.class); - InMemorySorter mockInMemorySorter = mock(InMemorySorter.class); - BufferedExternalSorter testSorter = - new BufferedExternalSorter(mockExternalSorter, mockInMemorySorter); - - @SuppressWarnings("unchecked") - KV[] kvs = - new KV[] { - KV.of(new byte[] {0}, new byte[] {}), - KV.of(new byte[] {0, 1}, new byte[] {}), - KV.of(new byte[] {1}, new byte[] {}) - }; - - when(mockInMemorySorter.addIfRoom(kvs[0])).thenReturn(true); - when(mockInMemorySorter.addIfRoom(kvs[1])).thenReturn(true); - when(mockInMemorySorter.addIfRoom(kvs[2])).thenReturn(false); - when(mockInMemorySorter.sort()).thenReturn(Arrays.asList(kvs[0], kvs[1])); - when(mockExternalSorter.sort()).thenReturn(Arrays.asList(kvs[0], kvs[1], kvs[2])); - - testSorter.add(kvs[0]); - testSorter.add(kvs[1]); - testSorter.add(kvs[2]); - - assertEquals(Arrays.asList(kvs[0], kvs[1], kvs[2]), testSorter.sort()); - - verify(mockExternalSorter, times(1)).add(kvs[0]); - verify(mockExternalSorter, times(1)).add(kvs[1]); - verify(mockExternalSorter, times(1)).add(kvs[2]); - } - - @Test - public void testEmpty() throws Exception { - SorterTestUtils.testEmpty(BufferedExternalSorter.create(new BufferedExternalSorter.Options())); - } - - @Test - public void testSingleElement() throws Exception { - SorterTestUtils.testSingleElement( - BufferedExternalSorter.create(new BufferedExternalSorter.Options())); - } - - @Test - public void testEmptyKeyValueElement() throws Exception { - SorterTestUtils.testEmptyKeyValueElement( - BufferedExternalSorter.create(new BufferedExternalSorter.Options())); - } - - @Test - public void testMultipleIterations() throws Exception { - SorterTestUtils.testMultipleIterations( - BufferedExternalSorter.create(new BufferedExternalSorter.Options())); - } - - @Test - public void testManySortersFewRecords() throws Exception { - SorterTestUtils.testRandom( - new SorterGenerator() { - @Override - public Sorter generateSorter() throws Exception { - return BufferedExternalSorter.create(new BufferedExternalSorter.Options()); - } - }, - 1000000, - 10); - } - - @Test - public void testOneSorterManyRecords() throws Exception { - SorterTestUtils.testRandom( - new SorterGenerator() { - @Override - public Sorter generateSorter() throws Exception { - return BufferedExternalSorter.create(new BufferedExternalSorter.Options()); - } - }, - 1, - 1000000); - } - - @Test - public void testAddAfterSort() throws Exception { - SorterTestUtils.testAddAfterSort( - BufferedExternalSorter.create(new BufferedExternalSorter.Options()), thrown); - fail(); - } - - @Test - public void testSortTwice() throws Exception { - SorterTestUtils.testSortTwice( - BufferedExternalSorter.create(new BufferedExternalSorter.Options()), thrown); - fail(); - } - - @Test - public void testNegativeMemory() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be greater than zero"); - BufferedExternalSorter.Options options = new BufferedExternalSorter.Options(); - options.setMemoryMB(-1); - } - - @Test - public void testZeroMemory() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be greater than zero"); - BufferedExternalSorter.Options options = new BufferedExternalSorter.Options(); - options.setMemoryMB(0); - } - - @Test - public void testMemoryTooLarge() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be less than 2048"); - BufferedExternalSorter.Options options = new BufferedExternalSorter.Options(); - options.setMemoryMB(2048); - } -} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java deleted file mode 100644 index 6db3437379..0000000000 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/ExternalSorterTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.contrib.sorter.SorterTestUtils.SorterGenerator; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for Sorter. */ -@RunWith(JUnit4.class) -public class ExternalSorterTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testEmpty() throws Exception { - SorterTestUtils.testEmpty(ExternalSorter.create(new ExternalSorter.Options())); - } - - @Test - public void testSingleElement() throws Exception { - SorterTestUtils.testSingleElement(ExternalSorter.create(new ExternalSorter.Options())); - } - - @Test - public void testEmptyKeyValueElement() throws Exception { - SorterTestUtils.testEmptyKeyValueElement(ExternalSorter.create(new ExternalSorter.Options())); - } - - @Test - public void testMultipleIterations() throws Exception { - SorterTestUtils.testMultipleIterations(ExternalSorter.create(new ExternalSorter.Options())); - } - - @Test - public void testRandom() throws Exception { - SorterTestUtils.testRandom( - new SorterGenerator() { - @Override - public Sorter generateSorter() throws Exception { - return ExternalSorter.create(new ExternalSorter.Options()); - } - }, - 1, - 1000000); - } - - @Test - public void testAddAfterSort() throws Exception { - SorterTestUtils.testAddAfterSort(ExternalSorter.create(new ExternalSorter.Options()), thrown); - fail(); - } - - @Test - public void testSortTwice() throws Exception { - SorterTestUtils.testSortTwice(ExternalSorter.create(new ExternalSorter.Options()), thrown); - fail(); - } - - @Test - public void testNegativeMemory() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be greater than zero"); - ExternalSorter.Options options = new ExternalSorter.Options(); - options.setMemoryMB(-1); - } - - @Test - public void testZeroMemory() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be greater than zero"); - ExternalSorter.Options options = new ExternalSorter.Options(); - options.setMemoryMB(0); - } - - @Test - public void testMemoryTooLarge() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be less than 2048"); - ExternalSorter.Options options = new ExternalSorter.Options(); - options.setMemoryMB(2048); - } -} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java deleted file mode 100644 index 2865dfe203..0000000000 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/InMemorySorterTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.fail; - -import com.google.cloud.dataflow.contrib.sorter.SorterTestUtils.SorterGenerator; -import com.google.cloud.dataflow.sdk.values.KV; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link InMemorySorter}. */ -@RunWith(JUnit4.class) -public class InMemorySorterTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testEmpty() throws Exception { - SorterTestUtils.testEmpty(InMemorySorter.create(new InMemorySorter.Options())); - } - - @Test - public void testSingleElement() throws Exception { - SorterTestUtils.testSingleElement(InMemorySorter.create(new InMemorySorter.Options())); - } - - @Test - public void testEmptyKeyValueElement() throws Exception { - SorterTestUtils.testEmptyKeyValueElement(InMemorySorter.create(new InMemorySorter.Options())); - } - - @Test - public void testMultipleIterations() throws Exception { - SorterTestUtils.testMultipleIterations(InMemorySorter.create(new InMemorySorter.Options())); - } - - @Test - public void testManySorters() throws Exception { - SorterTestUtils.testRandom( - new SorterGenerator() { - @Override - public Sorter generateSorter() throws Exception { - return InMemorySorter.create(new InMemorySorter.Options()); - } - }, - 1000000, - 10); - } - - @Test - public void testAddAfterSort() throws Exception { - SorterTestUtils.testAddAfterSort(InMemorySorter.create(new InMemorySorter.Options()), thrown); - fail(); - } - - @Test - public void testSortTwice() throws Exception { - SorterTestUtils.testSortTwice(InMemorySorter.create(new InMemorySorter.Options()), thrown); - fail(); - } - - /** - * Verify an exception is thrown when the in memory sorter runs out of space. - * - * @throws Exception - */ - @Test - public void testOutOfSpace() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage(is("No space remaining for in memory sorting")); - SorterTestUtils.testRandom( - new SorterGenerator() { - @Override - public Sorter generateSorter() throws Exception { - InMemorySorter.Options options = new InMemorySorter.Options(); - options.setMemoryMB(1); - return InMemorySorter.create(options); - } - }, - 1, - 10000000); - } - - @Test - public void testAddIfRoom() throws Exception { - InMemorySorter.Options options = new InMemorySorter.Options(); - options.setMemoryMB(1); - InMemorySorter sorter = InMemorySorter.create(options); - - // Should be a few kb less than what the total buffer supports - KV bigRecord = KV.of(new byte[1024 * 500], new byte[1024 * 500]); - - // First add should succeed, second add should fail due to insufficient room - Assert.assertTrue(sorter.addIfRoom(bigRecord)); - Assert.assertFalse(sorter.addIfRoom(bigRecord)); - } - - @Test - public void testAddIfRoomOverhead() throws Exception { - InMemorySorter.Options options = new InMemorySorter.Options(); - options.setMemoryMB(1); - InMemorySorter sorter = InMemorySorter.create(options); - - // No bytes within record, should still run out of room due to memory overhead of record - KV tinyRecord = KV.of(new byte[0], new byte[0]); - - // Verify we can't insert one million records into this one megabyte buffer - boolean stillRoom = true; - for (int i = 0; (i < 1000000) && stillRoom; i++) { - stillRoom = sorter.addIfRoom(tinyRecord); - } - - Assert.assertFalse(stillRoom); - } - - @Test - public void testNegativeMemory() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be greater than zero"); - InMemorySorter.Options options = new InMemorySorter.Options(); - options.setMemoryMB(-1); - } - - @Test - public void testZeroMemory() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("memoryMB must be greater than zero"); - InMemorySorter.Options options = new InMemorySorter.Options(); - options.setMemoryMB(0); - } -} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java deleted file mode 100644 index bb7273bad6..0000000000 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SortValuesTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.GroupByKey; -import com.google.cloud.dataflow.sdk.transforms.SerializableFunction; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Arrays; - -/** Tests for {@link SortValues} transform. */ -@RunWith(JUnit4.class) -public class SortValuesTest { - - @Test - public void testSecondaryKeySorting() throws Exception { - Pipeline p = TestPipeline.create(); - - // Create a PCollection of > pairs. - PCollection>> input = - p.apply( - Create.of( - Arrays.asList( - KV.of("key1", KV.of("secondaryKey2", 20)), - KV.of("key2", KV.of("secondaryKey2", 200)), - KV.of("key1", KV.of("secondaryKey3", 30)), - KV.of("key1", KV.of("secondaryKey1", 10)), - KV.of("key2", KV.of("secondaryKey1", 100))))); - - // Group by Key, bringing pairs for the same Key together. - PCollection>>> grouped = - input.apply(GroupByKey.>create()); - - // For every Key, sort the iterable of pairs by SecondaryKey. - PCollection>>> groupedAndSorted = - grouped.apply( - SortValues.create(new BufferedExternalSorter.Options())); - - DataflowAssert.that(groupedAndSorted) - .satisfies(new AssertThatHasExpectedContentsForTestSecondaryKeySorting()); - - p.run(); - } - - static class AssertThatHasExpectedContentsForTestSecondaryKeySorting - implements SerializableFunction>>>, Void> { - @SuppressWarnings("unchecked") - @Override - public Void apply(Iterable>>> actual) { - assertThat( - actual, - containsInAnyOrder( - KvMatcher.isKv( - is("key1"), - contains( - KvMatcher.isKv(is("secondaryKey1"), is(10)), - KvMatcher.isKv(is("secondaryKey2"), is(20)), - KvMatcher.isKv(is("secondaryKey3"), is(30)))), - KvMatcher.isKv( - is("key2"), - contains( - KvMatcher.isKv(is("secondaryKey1"), is(100)), - KvMatcher.isKv(is("secondaryKey2"), is(200)))))); - return null; - } - } - - /** Matcher for KVs. Forked from com.google.cloud.dataflow/sdk/TestUtils.java */ - public static class KvMatcher extends TypeSafeMatcher> { - final Matcher keyMatcher; - final Matcher valueMatcher; - - public static KvMatcher isKv(Matcher keyMatcher, Matcher valueMatcher) { - return new KvMatcher<>(keyMatcher, valueMatcher); - } - - public KvMatcher(Matcher keyMatcher, Matcher valueMatcher) { - this.keyMatcher = keyMatcher; - this.valueMatcher = valueMatcher; - } - - @Override - public boolean matchesSafely(KV kv) { - return keyMatcher.matches(kv.getKey()) && valueMatcher.matches(kv.getValue()); - } - - @Override - public void describeTo(Description description) { - description - .appendText("a KV(") - .appendValue(keyMatcher) - .appendText(", ") - .appendValue(valueMatcher) - .appendText(")"); - } - } -} diff --git a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SorterTestUtils.java b/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SorterTestUtils.java deleted file mode 100644 index 9aff1f0c11..0000000000 --- a/contrib/sorter/src/test/java/com/google/cloud/dataflow/contrib/sorter/SorterTestUtils.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2016 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.contrib.sorter; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.common.primitives.UnsignedBytes; -import org.junit.rules.ExpectedException; - -import java.util.Random; - -/** A set of basic tests for {@link Sorter}s. */ -public class SorterTestUtils { - - public static void testEmpty(Sorter sorter) throws Exception { - assertThat(sorter.sort(), is(emptyIterable())); - } - - @SuppressWarnings("unchecked") - public static void testSingleElement(Sorter sorter) throws Exception { - KV kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2}); - sorter.add(kv); - assertThat(sorter.sort(), contains(kv)); - } - - @SuppressWarnings("unchecked") - public static void testEmptyKeyValueElement(Sorter sorter) throws Exception { - KV kv = KV.of(new byte[] {}, new byte[] {}); - sorter.add(kv); - assertThat(sorter.sort(), contains(kv)); - } - - @SuppressWarnings("unchecked") - public static void testMultipleIterations(Sorter sorter) throws Exception { - KV[] kvs = - new KV[] { - KV.of(new byte[] {0}, new byte[] {}), - KV.of(new byte[] {0, 1}, new byte[] {}), - KV.of(new byte[] {1}, new byte[] {}) - }; - sorter.add(kvs[1]); - sorter.add(kvs[2]); - sorter.add(kvs[0]); - Iterable> sorted = sorter.sort(); - assertThat(sorted, contains(kvs[0], kvs[1], kvs[2])); - // Iterate second time. - assertThat(sorted, contains(kvs[0], kvs[1], kvs[2])); - } - - /** Class that generates a new sorter. Used when performance testing multiple sorter creation. */ - interface SorterGenerator { - Sorter generateSorter() throws Exception; - } - - /** - * Generates random records and executes a test with the provided number of sorters and number of - * records per sorter. - */ - public static void testRandom( - SorterGenerator sorterGenerator, int numSorters, int numRecordsPerSorter) throws Exception { - long start = System.currentTimeMillis(); - for (int i = 0; i < numSorters; ++i) { - Sorter sorter = sorterGenerator.generateSorter(); - Random rnd = new Random(0L); - for (int j = 0; j < numRecordsPerSorter; ++j) { - byte[] key = new byte[8]; - byte[] value = new byte[8]; - rnd.nextBytes(key); - rnd.nextBytes(value); - sorter.add(KV.of(key, value)); - } - - byte[] prevKey = null; - for (KV record : sorter.sort()) { - assertTrue( - prevKey == null - || UnsignedBytes.lexicographicalComparator().compare(prevKey, record.getKey()) < 0); - prevKey = record.getKey(); - } - } - long end = System.currentTimeMillis(); - System.out.println( - "Took " - + (end - start) - + "ms for " - + numRecordsPerSorter * numSorters * 1000.0 / (end - start) - + " records/s"); - } - - /** Tests trying to call add after calling sort. Should throw an exception. */ - public static void testAddAfterSort(Sorter sorter, ExpectedException thrown) throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage(is("Records can only be added before sort()")); - KV kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2}); - sorter.add(kv); - sorter.sort(); - sorter.add(kv); - } - - /** Tests trying to calling sort twice. Should throw an exception. */ - public static void testSortTwice(Sorter sorter, ExpectedException thrown) throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage(is("sort() can only be called once.")); - KV kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2}); - sorter.add(kv); - sorter.sort(); - sorter.sort(); - } -} From 1cd42304e57a70bb82a1a7009a5746a4f5564ee2 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 15:34:15 -0800 Subject: [PATCH 663/751] Remove infrastructure for building Javadoc Dataflow distribution of Beam is not expected to have its own Javadoc build. --- javadoc/README.md | 4 --- javadoc/apiclient-docs/package-list | 34 ------------------- javadoc/avro-docs/package-list | 30 ---------------- javadoc/bq-docs/package-list | 2 -- javadoc/dataflow-sdk-docs/package-list | 11 ------ javadoc/datastore-docs/package-list | 2 -- javadoc/guava-docs/package-list | 15 -------- javadoc/hamcrest-docs/package-list | 10 ------ javadoc/jackson-annotations-docs/package-list | 1 - javadoc/jackson-databind-docs/package-list | 20 ----------- javadoc/joda-docs/package-list | 7 ---- javadoc/junit-docs/package-list | 7 ---- javadoc/oauth-docs/package-list | 11 ------ javadoc/overview.html | 31 ----------------- 14 files changed, 185 deletions(-) delete mode 100644 javadoc/README.md delete mode 100644 javadoc/apiclient-docs/package-list delete mode 100644 javadoc/avro-docs/package-list delete mode 100644 javadoc/bq-docs/package-list delete mode 100644 javadoc/dataflow-sdk-docs/package-list delete mode 100644 javadoc/datastore-docs/package-list delete mode 100644 javadoc/guava-docs/package-list delete mode 100644 javadoc/hamcrest-docs/package-list delete mode 100644 javadoc/jackson-annotations-docs/package-list delete mode 100644 javadoc/jackson-databind-docs/package-list delete mode 100644 javadoc/joda-docs/package-list delete mode 100644 javadoc/junit-docs/package-list delete mode 100644 javadoc/oauth-docs/package-list delete mode 100644 javadoc/overview.html diff --git a/javadoc/README.md b/javadoc/README.md deleted file mode 100644 index 8240d3ce00..0000000000 --- a/javadoc/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# SDK Javadoc - -This directory contains package-info files for external javadoc we would like -our javadoc to link to using `-linkoffline`. diff --git a/javadoc/apiclient-docs/package-list b/javadoc/apiclient-docs/package-list deleted file mode 100644 index 3ec1471f30..0000000000 --- a/javadoc/apiclient-docs/package-list +++ /dev/null @@ -1,34 +0,0 @@ -com.google.api.client.googleapis -com.google.api.client.googleapis.apache -com.google.api.client.googleapis.auth.clientlogin -com.google.api.client.googleapis.auth.oauth2 -com.google.api.client.googleapis.batch -com.google.api.client.googleapis.batch.json -com.google.api.client.googleapis.compute -com.google.api.client.googleapis.extensions.android.accounts -com.google.api.client.googleapis.extensions.android.gms.auth -com.google.api.client.googleapis.extensions.appengine.auth.oauth2 -com.google.api.client.googleapis.extensions.appengine.notifications -com.google.api.client.googleapis.extensions.appengine.testing.auth.oauth2 -com.google.api.client.googleapis.extensions.java6.auth.oauth2 -com.google.api.client.googleapis.extensions.servlet.notifications -com.google.api.client.googleapis.javanet -com.google.api.client.googleapis.json -com.google.api.client.googleapis.media -com.google.api.client.googleapis.notifications -com.google.api.client.googleapis.notifications.json -com.google.api.client.googleapis.notifications.json.gson -com.google.api.client.googleapis.notifications.json.jackson2 -com.google.api.client.googleapis.services -com.google.api.client.googleapis.services.json -com.google.api.client.googleapis.services.protobuf -com.google.api.client.googleapis.testing -com.google.api.client.googleapis.testing.auth.oauth2 -com.google.api.client.googleapis.testing.compute -com.google.api.client.googleapis.testing.json -com.google.api.client.googleapis.testing.notifications -com.google.api.client.googleapis.testing.services -com.google.api.client.googleapis.testing.services.json -com.google.api.client.googleapis.testing.services.protobuf -com.google.api.client.googleapis.util -com.google.api.client.googleapis.xml.atom diff --git a/javadoc/avro-docs/package-list b/javadoc/avro-docs/package-list deleted file mode 100644 index 319ff01fde..0000000000 --- a/javadoc/avro-docs/package-list +++ /dev/null @@ -1,30 +0,0 @@ -org.apache.avro -org.apache.avro.compiler.idl -org.apache.avro.compiler.specific -org.apache.avro.data -org.apache.avro.file -org.apache.avro.generic -org.apache.avro.hadoop.file -org.apache.avro.hadoop.io -org.apache.avro.hadoop.util -org.apache.avro.io -org.apache.avro.io.parsing -org.apache.avro.ipc -org.apache.avro.ipc.generic -org.apache.avro.ipc.reflect -org.apache.avro.ipc.specific -org.apache.avro.ipc.stats -org.apache.avro.ipc.trace -org.apache.avro.mapred -org.apache.avro.mapred.tether -org.apache.avro.mapreduce -org.apache.avro.mojo -org.apache.avro.protobuf -org.apache.avro.reflect -org.apache.avro.specific -org.apache.avro.thrift -org.apache.avro.tool -org.apache.avro.util -org.apache.trevni -org.apache.trevni.avro -org.apache.trevni.avro.mapreduce diff --git a/javadoc/bq-docs/package-list b/javadoc/bq-docs/package-list deleted file mode 100644 index 384b3fc2d8..0000000000 --- a/javadoc/bq-docs/package-list +++ /dev/null @@ -1,2 +0,0 @@ -com.google.api.services.bigquery -com.google.api.services.bigquery.model diff --git a/javadoc/dataflow-sdk-docs/package-list b/javadoc/dataflow-sdk-docs/package-list deleted file mode 100644 index a26f5a35cb..0000000000 --- a/javadoc/dataflow-sdk-docs/package-list +++ /dev/null @@ -1,11 +0,0 @@ -com.google.cloud.dataflow.sdk -com.google.cloud.dataflow.sdk.annotations -com.google.cloud.dataflow.sdk.coders -com.google.cloud.dataflow.sdk.io -com.google.cloud.dataflow.sdk.options -com.google.cloud.dataflow.sdk.runners -com.google.cloud.dataflow.sdk.testing -com.google.cloud.dataflow.sdk.transforms -com.google.cloud.dataflow.sdk.transforms.join -com.google.cloud.dataflow.sdk.transforms.windowing -com.google.cloud.dataflow.sdk.values diff --git a/javadoc/datastore-docs/package-list b/javadoc/datastore-docs/package-list deleted file mode 100644 index ebbafd860d..0000000000 --- a/javadoc/datastore-docs/package-list +++ /dev/null @@ -1,2 +0,0 @@ -com.google.api.services.datastore -com.google.api.services.datastore.client diff --git a/javadoc/guava-docs/package-list b/javadoc/guava-docs/package-list deleted file mode 100644 index f8551784fd..0000000000 --- a/javadoc/guava-docs/package-list +++ /dev/null @@ -1,15 +0,0 @@ -com.google.common.annotations -com.google.common.base -com.google.common.cache -com.google.common.collect -com.google.common.escape -com.google.common.eventbus -com.google.common.hash -com.google.common.html -com.google.common.io -com.google.common.math -com.google.common.net -com.google.common.primitives -com.google.common.reflect -com.google.common.util.concurrent -com.google.common.xml diff --git a/javadoc/hamcrest-docs/package-list b/javadoc/hamcrest-docs/package-list deleted file mode 100644 index 3f5e945f7a..0000000000 --- a/javadoc/hamcrest-docs/package-list +++ /dev/null @@ -1,10 +0,0 @@ -org.hamcrest -org.hamcrest.beans -org.hamcrest.collection -org.hamcrest.core -org.hamcrest.integration -org.hamcrest.internal -org.hamcrest.number -org.hamcrest.object -org.hamcrest.text -org.hamcrest.xml diff --git a/javadoc/jackson-annotations-docs/package-list b/javadoc/jackson-annotations-docs/package-list deleted file mode 100644 index 768b3bab1c..0000000000 --- a/javadoc/jackson-annotations-docs/package-list +++ /dev/null @@ -1 +0,0 @@ -com.fasterxml.jackson.annotation diff --git a/javadoc/jackson-databind-docs/package-list b/javadoc/jackson-databind-docs/package-list deleted file mode 100644 index 8a2cd8be56..0000000000 --- a/javadoc/jackson-databind-docs/package-list +++ /dev/null @@ -1,20 +0,0 @@ -com.fasterxml.jackson.databind -com.fasterxml.jackson.databind.annotation -com.fasterxml.jackson.databind.cfg -com.fasterxml.jackson.databind.deser -com.fasterxml.jackson.databind.deser.impl -com.fasterxml.jackson.databind.deser.std -com.fasterxml.jackson.databind.exc -com.fasterxml.jackson.databind.ext -com.fasterxml.jackson.databind.introspect -com.fasterxml.jackson.databind.jsonFormatVisitors -com.fasterxml.jackson.databind.jsonschema -com.fasterxml.jackson.databind.jsontype -com.fasterxml.jackson.databind.jsontype.impl -com.fasterxml.jackson.databind.module -com.fasterxml.jackson.databind.node -com.fasterxml.jackson.databind.ser -com.fasterxml.jackson.databind.ser.impl -com.fasterxml.jackson.databind.ser.std -com.fasterxml.jackson.databind.type -com.fasterxml.jackson.databind.util diff --git a/javadoc/joda-docs/package-list b/javadoc/joda-docs/package-list deleted file mode 100644 index 2ab05aa0cf..0000000000 --- a/javadoc/joda-docs/package-list +++ /dev/null @@ -1,7 +0,0 @@ -org.joda.time -org.joda.time.base -org.joda.time.chrono -org.joda.time.convert -org.joda.time.field -org.joda.time.format -org.joda.time.tz diff --git a/javadoc/junit-docs/package-list b/javadoc/junit-docs/package-list deleted file mode 100644 index 0735177ae6..0000000000 --- a/javadoc/junit-docs/package-list +++ /dev/null @@ -1,7 +0,0 @@ -org.hamcrest.core -org.junit -org.junit.matchers -org.junit.runner -org.junit.runner.manipulation -org.junit.runner.notification -org.junit.runners diff --git a/javadoc/oauth-docs/package-list b/javadoc/oauth-docs/package-list deleted file mode 100644 index 38fc0461af..0000000000 --- a/javadoc/oauth-docs/package-list +++ /dev/null @@ -1,11 +0,0 @@ -com.google.api.client.auth.oauth -com.google.api.client.auth.oauth2 -com.google.api.client.auth.openidconnect -com.google.api.client.extensions.appengine.auth -com.google.api.client.extensions.appengine.auth.oauth2 -com.google.api.client.extensions.auth.helpers -com.google.api.client.extensions.auth.helpers.oauth -com.google.api.client.extensions.java6.auth.oauth2 -com.google.api.client.extensions.jetty.auth.oauth2 -com.google.api.client.extensions.servlet.auth -com.google.api.client.extensions.servlet.auth.oauth2 diff --git a/javadoc/overview.html b/javadoc/overview.html deleted file mode 100644 index 4ffd33f22f..0000000000 --- a/javadoc/overview.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - Google Cloud Dataflow Java SDK - - -

              The Google Cloud Dataflow SDK for Java provides a simple and elegant - programming model to express your data processing pipelines; - see our product page - for more information and getting started instructions.

              - -

              The easiest way to use the Google Cloud Dataflow SDK for Java is via - one of the released artifacts from the - - Maven Central Repository. - See our - release notes for more information about each released version.

              - -

              Version numbers use the form major.minor.incremental - and are incremented as follows:

              -

                -
              • major version for incompatible API changes
              • -
              • minor version for new functionality added in a backward-compatible manner
              • -
              • incremental version for forward-compatible bug fixes
              • -
              - -

              Please note that APIs marked - {@link com.google.cloud.dataflow.sdk.annotations.Experimental @Experimental} - may change at any point and are not guaranteed to remain compatible across versions.

              - - From a36ca52b50d5e29797e5ddaa726679ce5e3c0f1b Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 15:36:07 -0800 Subject: [PATCH 664/751] Remove unnecessary test_wordcount.sh test This test lives in Beam, and doesn't need to be duplicated in the Dataflow distribution. --- .travis.yml | 1 - travis/README.md | 4 -- travis/test_wordcount.sh | 109 --------------------------------------- 3 files changed, 114 deletions(-) delete mode 100644 travis/README.md delete mode 100755 travis/test_wordcount.sh diff --git a/.travis.yml b/.travis.yml index 2f5ed182c5..2c560857a0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,4 +33,3 @@ install: script: - travis_retry mvn $MAVEN_OVERRIDE install -U - - travis_retry travis/test_wordcount.sh diff --git a/travis/README.md b/travis/README.md deleted file mode 100644 index f7d89999b3..0000000000 --- a/travis/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Travis Scripts - -This directory contains scripts used for [Travis CI](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK) -testing. diff --git a/travis/test_wordcount.sh b/travis/test_wordcount.sh deleted file mode 100755 index fdb9d10a85..0000000000 --- a/travis/test_wordcount.sh +++ /dev/null @@ -1,109 +0,0 @@ -#!/bin/bash - -# This script runs WordCount example locally in a few different ways. -# Specifically, all combinations of: -# a) using mvn exec, or java -cp with a bundled jar file; -# b) input filename with no directory component, with a relative directory, or -# with an absolute directory; AND -# c) input filename containing wildcards or not. -# -# The one optional parameter is a path from the directory containing the script -# to the directory containing the top-level (parent) pom.xml. If no parameter -# is provided, the script assumes that directory is equal to the directory -# containing the script itself. -# -# The exit-code of the script indicates success or a failure. - -set -e -set -o pipefail - -PASS=1 -VERSION=$(mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep -v '\[') -JAR_FILE=examples/target/google-cloud-dataflow-java-examples-all-bundled-${VERSION}.jar - -function check_result_hash { - local name=$1 - local outfile_prefix=$2 - local expected=$3 - - local actual=$(LC_ALL=C sort $outfile_prefix-* | md5sum | awk '{print $1}' \ - || LC_ALL=C sort $outfile_prefix-* | md5 -q) || exit 2 # OSX - if [[ "$actual" != "$expected" ]] - then - echo "FAIL $name: Output hash mismatch. Got $actual, expected $expected." - PASS="" - echo "head hexdump of actual:" - head $outfile_prefix-* | hexdump -c - else - echo "pass $name" - # Output files are left behind in /tmp - fi -} - -function get_outfile_prefix { - local name=$1 - # NOTE: mktemp on OSX doesn't support --tmpdir - mktemp -u "/tmp/$name.out.XXXXXXXXXX" -} - -function run_via_mvn { - local name=$1 - local input=$2 - local expected_hash=$3 - - local outfile_prefix="$(get_outfile_prefix "$name")" || exit 2 - local cmd='mvn exec:java -f pom.xml -pl examples \ - -Dexec.mainClass=com.google.cloud.dataflow.examples.WordCount \ - -Dexec.args="--runner=DirectPipelineRunner --inputFile='"$input"' --output='"$outfile_prefix"'"' - echo "$name: Running $cmd" >&2 - sh -c "$cmd" - check_result_hash "$name" "$outfile_prefix" "$expected_hash" -} - -function run_bundled { - local name=$1 - local input=$2 - local expected_hash=$3 - - local outfile_prefix="$(get_outfile_prefix "$name")" || exit 2 - local cmd='java -cp '"$JAR_FILE"' \ - com.google.cloud.dataflow.examples.WordCount \ - --runner=DirectPipelineRunner \ - --inputFile='"'$input'"' \ - --output='"$outfile_prefix" - echo "$name: Running $cmd" >&2 - sh -c "$cmd" - check_result_hash "$name" "$outfile_prefix" "$expected_hash" -} - -function run_all_ways { - local name=$1 - local input=$2 - local expected_hash=$3 - - run_via_mvn ${name}a "$input" $expected_hash - check_for_jar_file - run_bundled ${name}b "$input" $expected_hash -} - -function check_for_jar_file { - if [[ ! -f $JAR_FILE ]] - then - echo "Jar file $JAR_FILE not created" >&2 - exit 2 - fi -} - -run_all_ways wordcount1 "LICENSE" c5350a5ad4bb51e3e018612b4b044097 -run_all_ways wordcount2 "./LICENSE" c5350a5ad4bb51e3e018612b4b044097 -run_all_ways wordcount3 "$PWD/LICENSE" c5350a5ad4bb51e3e018612b4b044097 -run_all_ways wordcount4 "L*N?E*" c5350a5ad4bb51e3e018612b4b044097 -run_all_ways wordcount5 "./LICE*N?E" c5350a5ad4bb51e3e018612b4b044097 -run_all_ways wordcount6 "$PWD/*LIC?NSE" c5350a5ad4bb51e3e018612b4b044097 - -if [[ ! "$PASS" ]] -then - echo "One or more tests FAILED." - exit 1 -fi -echo "All tests PASS" From d71ba431c1a7cd840c1b2cd9f7878964a235ccf2 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 16:17:12 -0800 Subject: [PATCH 665/751] Add Dataflow distribution properties to identify this distribution --- .../google/cloud/dataflow/sdk/sdk.properties | 5 ----- .../beam/runners/dataflow/dataflow.properties | 18 ++++++++++++++++++ .../org/apache/beam/sdk/sdk.properties | 17 +++++++++++++++++ 3 files changed, 35 insertions(+), 5 deletions(-) delete mode 100644 sdk/src/main/resources/com/google/cloud/dataflow/sdk/sdk.properties create mode 100644 sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties create mode 100644 sdk/src/main/resources/org/apache/beam/sdk/sdk.properties diff --git a/sdk/src/main/resources/com/google/cloud/dataflow/sdk/sdk.properties b/sdk/src/main/resources/com/google/cloud/dataflow/sdk/sdk.properties deleted file mode 100644 index 5b0a720b21..0000000000 --- a/sdk/src/main/resources/com/google/cloud/dataflow/sdk/sdk.properties +++ /dev/null @@ -1,5 +0,0 @@ -# SDK source version. -version=${pom.version} - -build.date=${timestamp} - diff --git a/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties b/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties new file mode 100644 index 0000000000..1af27fdd48 --- /dev/null +++ b/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties @@ -0,0 +1,18 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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. + +environment.major.version=6 + +worker.image.batch=dataflow.gcr.io/v1beta3/beam-java-batch:${project.version}-20170103 +worker.image.streaming=dataflow.gcr.io/v1beta3/beam-java-streaming:${project.version}-20170103 diff --git a/sdk/src/main/resources/org/apache/beam/sdk/sdk.properties b/sdk/src/main/resources/org/apache/beam/sdk/sdk.properties new file mode 100644 index 0000000000..a9df3b5b5c --- /dev/null +++ b/sdk/src/main/resources/org/apache/beam/sdk/sdk.properties @@ -0,0 +1,17 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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. + +name=Google Cloud Dataflow SDK for Java +version=${pom.version} +build.date=${timestamp} From 2393729cc0747f750c2d54d2c75b5fa79de7984e Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 16:45:19 -0800 Subject: [PATCH 666/751] Update top-level README.md and CONTRIBUTING.md to reflect what this branch contains --- CONTRIBUTING.md | 14 ++++++---- README.md | 68 +++++++++++++++++-------------------------------- 2 files changed, 33 insertions(+), 49 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8b0fcba196..606049f5a2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,15 @@ Want to contribute? Great! First, read this page (including the small print at the end). +Google Cloud Dataflow SDK is a distribution of Apache Beam. If you'd like to +change anything under the `org.apache.beam.*` namespace, please submit that +change directly to the [Apache Beam](https://github.com/apache/beam) project. + +This repository contains code to build the Dataflow distribution of Beam, and +some Dataflow-specific code. Only changes to how the distribution is built, or +the Dataflow-specific code under the `com.google.cloud.dataflow.*` namespace, +can be merged here. + ### Before you contribute Before we can use your code, you must sign the [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) @@ -21,11 +30,6 @@ frustration later on. All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. -### Organization -During our review and triage of incoming pull requests, we'll advise whether to -include your contribution into the mainline SDK, or to maintain it within the -separate group of [community-contributed modules](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master/contrib). - ### The small print Contributions made by corporations are covered by a different agreement than the one above, the Software Grant and Corporate Contributor License Agreement. diff --git a/README.md b/README.md index d5345a38c1..b3f85b2451 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,13 @@ [Google Cloud Dataflow](https://cloud.google.com/dataflow/) provides a simple, powerful programming model for building both batch and streaming parallel data -processing pipelines. This repository hosts the open-sourced Cloud Dataflow SDK -for Java, which can be used to run pipelines against the Google Cloud Dataflow -Service. +processing pipelines. + +Dataflow SDK for Java is a distribution of a portion of the +[Apache Beam](https://beam.apache.org) project. This repository hosts the +code to build this distribution and any Dataflow-specific code/modules. The +underlying source code is hosted in the +[Apache Beam repository](https://github.com/apache/beam). [General usage](https://cloud.google.com/dataflow/getting-started) of Google Cloud Dataflow does **not** require use of this repository. Instead: @@ -25,13 +29,19 @@ environments like Eclipse or Apache Maven: [DataflowJavaSDK-examples](https://github.com/GoogleCloudPlatform/DataflowJavaSDK-examples) repository. -However, if you'd like to contribute to the SDK, write your own PipelineRunner, -or just dig in for the fun of it, please stay with us here! + + +## Status [![Build Status](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK.svg?branch=v2)](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK) -## Status [![Build Status](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK) +This branch is a work-in-progress for the Dataflow SDK for Java, version 2.0.0. +It is currently supported on the Cloud Dataflow service in Beta. -Both the SDK and the Dataflow Service are generally available, open to all -developers, and considered stable and fully qualified for production use. + ## Overview @@ -48,25 +58,17 @@ for execution. * [`PipelineRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunner.java): specifies where and how the pipeline should execute. -We provide three PipelineRunners: +We provide two runners: - 1. The [`DirectPipelineRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java) + 1. The [`DirectRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java) runs the pipeline on your local machine. - 2. The [`DataflowPipelineRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java) + 1. The [`DataflowRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java) submits the pipeline to the Dataflow Service, where it runs using managed resources in the [Google Cloud Platform](https://cloud.google.com) (GCP). - 3. The [`BlockingDataflowPipelineRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/BlockingDataflowPipelineRunner.java) -submits the pipeline to the Dataflow Service via the `DataflowPipelineRunner` -and then prints messages about the job status until the execution is complete. The SDK is built to be extensible and support additional execution environments -beyond local execution and the Google Cloud Dataflow Service. In partnership -with [Cloudera](https://www.cloudera.com/), you can run Dataflow pipelines on -an [Apache Spark](https://spark.apache.org/) backend using the -[`SparkPipelineRunner`](https://github.com/cloudera/spark-dataflow). -Additionally, you can run Dataflow pipelines on an -[Apache Flink](https://flink.apache.org/) backend using the -[`FlinkPipelineRunner`](https://github.com/dataArtisans/flink-dataflow). +beyond local execution and the Google Cloud Dataflow Service. Apache Beam +contains additional SDKs, runners, IO connectors, etc. ## Getting Started @@ -77,35 +79,12 @@ module provides a set of basic Java APIs to program against. * The [`examples`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples) module provides a few samples to get started. We recommend starting with the `WordCount` example. -* The [`contrib`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/contrib) -directory hosts community-contributed Dataflow modules. The following command will build both the `sdk` and `example` modules and install them in your local Maven repository: mvn clean install -You can speed up the build and install process by using the following options: - - 1. To skip execution of the unit tests, run: - - mvn install -DskipTests - - 2. While iterating on a specific module, use the following command to compile - and reinstall it. For example, to reinstall the `examples` module, run: - - mvn install -pl examples - - Be careful, however, as this command will use the most recently installed SDK - from the local repository (or Maven Central) even if you have changed it - locally. - -If you are using [Eclipse](https://eclipse.org/) integrated development -environment (IDE), the -[Cloud Dataflow Plugin for Eclipse](https://cloud.google.com/dataflow/getting-started-eclipse) -provides tools to create and execute Dataflow pipelines locally and on the -Dataflow Service. - After building and installing, you can execute the `WordCount` and other example pipelines by following the instructions in this [README](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/README.md). @@ -121,5 +100,6 @@ on GitHub to report any bugs, comments or questions regarding SDK development. ## More Information * [Google Cloud Dataflow](https://cloud.google.com/dataflow/) +* [Apache Beam](https://beam.apache.org/) * [Dataflow Concepts and Programming Model](https://cloud.google.com/dataflow/model/programming-model) * [Java API Reference](https://cloud.google.com/dataflow/java-sdk/JavaDoc/index) From 4929d838b99e6484784e7a9fea4a1bc50083ecdc Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 16:46:04 -0800 Subject: [PATCH 667/751] Update .travis.yml to simplify testing --- .travis.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2c560857a0..d3c5cf99e4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,14 +15,15 @@ matrix: include: # On OSX, run with default JDK only. - os: osx - env: MAVEN_OVERRIDE="" # On Linux, run with specific JDKs only. - os: linux - env: CUSTOM_JDK="oraclejdk8" MAVEN_OVERRIDE="-Ddataflow.surefire_argline='-Xmx512m'" - - os: linux - env: CUSTOM_JDK="oraclejdk7" MAVEN_OVERRIDE="-Ddataflow.surefire_argline='-Xmx512m'" - - os: linux - env: CUSTOM_JDK="openjdk7" MAVEN_OVERRIDE="-Ddataflow.surefire_argline='-Xmx512m'" + env: CUSTOM_JDK="oraclejdk8" + # The distribution does not build with Java 7 by design. We need to rewrite these tests + # to, for example, build and install with Java 8 and then test examples with Java 7. + # - os: linux + # env: CUSTOM_JDK="oraclejdk7" + # - os: linux + # env: CUSTOM_JDK="openjdk7" before_install: - if [ "$TRAVIS_OS_NAME" == "osx" ]; then export JAVA_HOME=$(/usr/libexec/java_home); fi @@ -32,4 +33,4 @@ install: - travis_retry mvn install clean -U -DskipTests=true script: - - travis_retry mvn $MAVEN_OVERRIDE install -U + - travis_retry mvn install -U From ee1e9c91f5e3bc353583dc78f78aa3ce9bffeaa0 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 3 Jan 2017 18:13:00 -0800 Subject: [PATCH 668/751] Move checkstyle configuration into sdk/ directory --- pom.xml | 4 ++-- checkstyle.xml => sdk/checkstyle.xml | 4 ++-- suppressions.xml => sdk/suppressions.xml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) rename checkstyle.xml => sdk/checkstyle.xml (99%) rename suppressions.xml => sdk/suppressions.xml (97%) diff --git a/pom.xml b/pom.xml index c6225324ee..a94365235e 100644 --- a/pom.xml +++ b/pom.xml @@ -126,8 +126,8 @@ - checkstyle.xml - suppressions.xml + sdk/checkstyle.xml + sdk/suppressions.xml true true true diff --git a/checkstyle.xml b/sdk/checkstyle.xml similarity index 99% rename from checkstyle.xml rename to sdk/checkstyle.xml index 1bb56748da..1769c8bed9 100644 --- a/checkstyle.xml +++ b/sdk/checkstyle.xml @@ -1,6 +1,6 @@ notice, so that this required text appears on the second line:
                       /*
              -         * Copyright 2015 Google Inc.
              +         * Copyright 2017 Google Inc.
                        *
                        * (details of open-source license...)
                     
              diff --git a/suppressions.xml b/sdk/suppressions.xml similarity index 97% rename from suppressions.xml rename to sdk/suppressions.xml index 4c9649a62a..c3635c9bb8 100644 --- a/suppressions.xml +++ b/sdk/suppressions.xml @@ -1,6 +1,6 @@ @@ -195,7 +207,7 @@ org.slf4j slf4j-jdk14 - 1.7.7 + 1.7.14 runtime diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java index 0d5afdef12..99ae79687c 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java @@ -1,45 +1,43 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 ${package}; -import ${package}.WordCount; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.transforms.Aggregator; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * An example that verifies word counts in Shakespeare and includes Dataflow best practices. + * An example that verifies word counts in Shakespeare and includes Beam best practices. * *

              This class, {@link DebuggingWordCount}, is the third in a series of four successively more * detailed 'word count' examples. You may first want to take a look at {@link MinimalWordCount} @@ -48,14 +46,13 @@ * *

              Basic concepts, also in the MinimalWordCount and WordCount examples: * Reading text files; counting a PCollection; executing a Pipeline both locally - * and using the Dataflow service; defining DoFns. + * and using a selected runner; defining DoFns. * *

              New Concepts: *

              - *   1. Logging to Cloud Logging
              - *   2. Controlling Dataflow worker log levels
              - *   3. Creating a custom aggregator
              - *   4. Testing your Pipeline via DataflowAssert
              + *   1. Logging using SLF4J, even in a distributed environment
              + *   2. Creating a custom aggregator (runners have varying levels of support)
              + *   3. Testing your Pipeline via PAssert
                * 
              * *

              To execute this pipeline locally, specify general pipeline configuration: @@ -64,55 +61,26 @@ * } * * - *

              To execute this pipeline using the Dataflow service and the additional logging discussed - * below, specify pipeline configuration: + *

              To change the runner, specify: *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - *   --workerLogLevelOverrides={"com.google.cloud.dataflow.examples":"DEBUG"}
              + *   --runner=YOUR_SELECTED_RUNNER
                * }
                * 
              * - *

              Note that when you run via mvn exec, you may need to escape - * the quotations as appropriate for your shell. For example, in bash: - *

              - * mvn compile exec:java ... \
              - *   -Dexec.args="... \
              - *     --workerLogLevelOverrides={\\\"com.google.cloud.dataflow.examples\\\":\\\"DEBUG\\\"}"
              - * 
              - * - *

              Concept #2: Dataflow workers which execute user code are configured to log to Cloud - * Logging by default at "INFO" log level and higher. One may override log levels for specific - * logging namespaces by specifying: - *

              
              - *   --workerLogLevelOverrides={"Name1":"Level1","Name2":"Level2",...}
              - * 
              - * For example, by specifying: - *
              
              - *   --workerLogLevelOverrides={"com.google.cloud.dataflow.examples":"DEBUG"}
              - * 
              - * when executing this pipeline using the Dataflow service, Cloud Logging would contain only - * "DEBUG" or higher level logs for the {@code com.google.cloud.dataflow.examples} package in - * addition to the default "INFO" or higher level logs. In addition, the default Dataflow worker - * logging configuration can be overridden by specifying - * {@code --defaultWorkerLogLevel=}. For example, - * by specifying {@code --defaultWorkerLogLevel=DEBUG} when executing this pipeline with - * the Dataflow service, Cloud Logging would contain all "DEBUG" or higher level logs. Note - * that changing the default worker log level to TRACE or DEBUG will significantly increase - * the amount of logs output. + *

              The input file defaults to a public data set containing the text of of King Lear, + * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. * - *

              The input file defaults to {@code gs://dataflow-samples/shakespeare/kinglear.txt} and can be - * overridden with {@code --inputFile}. */ public class DebuggingWordCount { /** A DoFn that filters for a specific key based upon a regular expression. */ public static class FilterTextFn extends DoFn, KV> { /** - * Concept #1: The logger below uses the fully qualified class name of FilterTextFn - * as the logger. All log statements emitted by this logger will be referenced by this name - * and will be visible in the Cloud Logging UI. Learn more at https://cloud.google.com/logging - * about the Cloud Logging UI. + * Concept #1: The logger below uses the fully qualified class name of FilterTextFn as the + * logger. Depending on your SLF4J configuration, log statements will likely be qualified by + * this name. + * + *

              Note that this is entirely standard SLF4J usage. Some runners may provide a default SLF4J + * configuration that is most appropriate for their logging integration. */ private static final Logger LOG = LoggerFactory.getLogger(FilterTextFn.class); @@ -122,23 +90,20 @@ public FilterTextFn(String pattern) { } /** - * Concept #3: A custom aggregator can track values in your pipeline as it runs. Those - * values will be displayed in the Dataflow Monitoring UI when this pipeline is run using the - * Dataflow service. These aggregators below track the number of matched and unmatched words. - * Learn more at https://cloud.google.com/dataflow/pipelines/dataflow-monitoring-intf about - * the Dataflow Monitoring UI. + * Concept #2: A custom aggregator can track values in your pipeline as it runs. Each + * runner provides varying levels of support for aggregators, and may expose them + * in a dashboard, etc. */ private final Aggregator matchedWords = createAggregator("matchedWords", new Sum.SumLongFn()); private final Aggregator unmatchedWords = createAggregator("umatchedWords", new Sum.SumLongFn()); - @Override + @ProcessElement public void processElement(ProcessContext c) { if (filter.matcher(c.element().getKey()).matches()) { // Log at the "DEBUG" level each element that we match. When executing this pipeline - // using the Dataflow service, these log lines will appear in the Cloud Logging UI - // only if the log level is set to "DEBUG" or lower. + // these log lines will appear only if the log level is set to "DEBUG" or lower. LOG.debug("Matched: " + c.element().getKey()); matchedWords.addValue(1L); c.output(c.element()); @@ -173,18 +138,18 @@ public static void main(String[] args) { Pipeline p = Pipeline.create(options); PCollection> filteredWords = - p.apply(TextIO.Read.named("ReadLines").from(options.getInputFile())) + p.apply("ReadLines", TextIO.Read.from(options.getInputFile())) .apply(new WordCount.CountWords()) .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); /** - * Concept #4: DataflowAssert is a set of convenient PTransforms in the style of + * Concept #3: PAssert is a set of convenient PTransforms in the style of * Hamcrest's collection matchers that can be used when writing Pipeline level tests - * to validate the contents of PCollections. DataflowAssert is best used in unit tests + * to validate the contents of PCollections. PAssert is best used in unit tests * with small data sets but is demonstrated here as a teaching tool. * *

              Below we verify that the set of filtered words matches our expected counts. Note - * that DataflowAssert does not provide any output and that successful completion of the + * that PAssert does not provide any output and that successful completion of the * Pipeline implies that the expectations were met. Learn more at * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline on how to test * your Pipeline and see {@link DebuggingWordCountTest} for an example unit test. @@ -192,8 +157,8 @@ public static void main(String[] args) { List> expectedResults = Arrays.asList( KV.of("Flourish", 3L), KV.of("stomach", 1L)); - DataflowAssert.that(filteredWords).containsInAnyOrder(expectedResults); + PAssert.that(filteredWords).containsInAnyOrder(expectedResults); - p.run(); + p.run().waitUntilFinish(); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java index 035db01e4a..97bd8243b8 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java @@ -1,30 +1,32 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 ${package}; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.KV; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SimpleFunction; +import org.apache.beam.sdk.values.KV; /** @@ -35,38 +37,32 @@ * argument processing, and focus on construction of the pipeline, which chains together the * application of core transforms. * - *

              Next, see the {@link WordCount} pipeline, then the {@link DebuggingWordCount}, and finally - * the {@link WindowedWordCount} pipeline, for more detailed examples that introduce additional + *

              Next, see the {@link WordCount} pipeline, then the {@link DebuggingWordCount}, and finally the + * {@link WindowedWordCount} pipeline, for more detailed examples that introduce additional * concepts. * *

              Concepts: + * *

                *   1. Reading data from text files
                *   2. Specifying 'inline' transforms
              - *   3. Counting a PCollection
              - *   4. Writing data to Cloud Storage as text files
              + *   3. Counting items in a PCollection
              + *   4. Writing data to text files
                * 
              * - *

              To execute this pipeline, first edit the code to set your project ID, the staging - * location, and the output location. The specified GCS bucket(s) must already exist. - * - *

              Then, run the pipeline as described in the README. It will be deployed and run using the - * Dataflow service. No args are required to run the pipeline. You can see the results in your - * output bucket in the GCS browser. + *

              No arguments are required to run this pipeline. It will be executed with the DirectRunner. You + * can see the results in the output files in your current working directory, with names like + * "wordcounts-00001-of-00005. When running on a distributed service, you would use an appropriate + * file service. */ public class MinimalWordCount { public static void main(String[] args) { - // Create a DataflowPipelineOptions object. This object lets us set various execution - // options for our pipeline, such as the associated Cloud Platform project and the location - // in Google Cloud Storage to stage files. - DataflowPipelineOptions options = PipelineOptionsFactory.create() - .as(DataflowPipelineOptions.class); - options.setRunner(BlockingDataflowPipelineRunner.class); - // CHANGE 1/3: Your project ID is required in order to run your pipeline on the Google Cloud. - options.setProject("SET_YOUR_PROJECT_ID_HERE"); - // CHANGE 2/3: Your Google Cloud Storage path is required for staging local files. - options.setStagingLocation("gs://SET_YOUR_BUCKET_NAME_HERE/AND_STAGING_DIRECTORY"); + // Create a PipelineOptions object. This object lets us set various execution + // options for our pipeline, such as the runner you wish to use. This example + // will run with the DirectRunner by default, based on the class path configured + // in its dependencies. + PipelineOptions options = PipelineOptionsFactory.create(); // Create the Pipeline object with the options we defined above. Pipeline p = Pipeline.create(options); @@ -76,13 +72,16 @@ public static void main(String[] args) { // Concept #1: Apply a root transform to the pipeline; in this case, TextIO.Read to read a set // of input text files. TextIO.Read returns a PCollection where each element is one line from // the input text (a set of Shakespeare's texts). - p.apply(TextIO.Read.from("gs://dataflow-samples/shakespeare/*")) + + // This example reads a public data set consisting of the complete works of Shakespeare. + p.apply(TextIO.Read.from("gs://apache-beam-samples/shakespeare/*")) + // Concept #2: Apply a ParDo transform to our PCollection of text lines. This ParDo invokes a // DoFn (defined in-line) on each element that tokenizes the text line into individual words. // The ParDo returns a PCollection, where each element is an individual word in // Shakespeare's collected texts. - .apply(ParDo.named("ExtractWords").of(new DoFn() { - @Override + .apply("ExtractWords", ParDo.of(new DoFn() { + @ProcessElement public void processElement(ProcessContext c) { for (String word : c.element().split("[^a-zA-Z']+")) { if (!word.isEmpty()) { @@ -91,25 +90,29 @@ public void processElement(ProcessContext c) { } } })) + // Concept #3: Apply the Count transform to our PCollection of individual words. The Count // transform returns a new PCollection of key/value pairs, where each key represents a unique // word in the text. The associated value is the occurrence count for that word. .apply(Count.perElement()) - // Apply another ParDo transform that formats our PCollection of word counts into a printable + + // Apply a MapElements transform that formats our PCollection of word counts into a printable // string, suitable for writing to an output file. - .apply(ParDo.named("FormatResults").of(new DoFn, String>() { + .apply("FormatResults", MapElements.via(new SimpleFunction, String>() { @Override - public void processElement(ProcessContext c) { - c.output(c.element().getKey() + ": " + c.element().getValue()); + public String apply(KV input) { + return input.getKey() + ": " + input.getValue(); } })) + // Concept #4: Apply a write transform, TextIO.Write, at the end of the pipeline. // TextIO.Write writes the contents of a PCollection (in this case, our PCollection of - // formatted strings) to a series of text files in Google Cloud Storage. - // CHANGE 3/3: The Google Cloud Storage path is required for outputting the results to. - .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); + // formatted strings) to a series of text files. + // + // By default, it will write to a set of files with names like wordcount-00001-of-00005 + .apply(TextIO.Write.to("wordcounts")); // Run the pipeline. - p.run(); + p.run().waitUntilFinish(); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java index 48b54069c4..052d7b6a0e 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java @@ -1,49 +1,46 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 ${package}; -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import ${package}.common.DataflowExampleUtils; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.BigQueryIO; -import com.google.cloud.dataflow.sdk.io.PubsubIO; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; -import com.google.cloud.dataflow.sdk.transforms.windowing.Window; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - +import java.io.IOException; +import java.util.concurrent.ThreadLocalRandom; +import ${package}.common.ExampleBigQueryTableOptions; +import ${package}.common.ExampleOptions; +import ${package}.common.WriteWindowedFilesDoFn; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.GroupByKey; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.FixedWindows; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; import org.joda.time.Duration; import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** @@ -56,60 +53,44 @@ * *

              Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples: * Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally - * and using the Dataflow service; defining DoFns; creating a custom aggregator; + * and using a selected runner; defining DoFns; creating a custom aggregator; * user-defined PTransforms; defining PipelineOptions. * *

              New Concepts: *

                *   1. Unbounded and bounded pipeline input modes
                *   2. Adding timestamps to data
              - *   3. PubSub topics as sources
              - *   4. Windowing
              - *   5. Re-using PTransforms over windowed PCollections
              - *   6. Writing to BigQuery
              + *   3. Windowing
              + *   4. Re-using PTransforms over windowed PCollections
              + *   5. Accessing the window of an element
              + *   6. Writing data to per-window text files
                * 
              * - *

              To execute this pipeline locally, specify general pipeline configuration: + *

              By default, the examples will run with the {@code DirectRunner}. + * To change the runner, specify: *

              {@code
              - *   --project=YOUR_PROJECT_ID
              + *   --runner=YOUR_SELECTED_RUNNER
                * }
                * 
              + * See examples/java/README.md for instructions about how to configure different runners. * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: + *

              To execute this pipeline locally, specify a local output file (if using the + * {@code DirectRunner}) or output prefix on a supported distributed file system. *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              - * }
              - * 
              - * - *

              Optionally specify the input file path via: - * {@code --inputFile=gs://INPUT_PATH}, - * which defaults to {@code gs://dataflow-samples/shakespeare/kinglear.txt}. - * - *

              Specify an output BigQuery dataset and optionally, a table for the output. If you don't - * specify the table, one will be created for you using the job name. If you don't specify the - * dataset, a dataset called {@code dataflow-examples} must already exist in your project. - * {@code --bigQueryDataset=YOUR-DATASET --bigQueryTable=YOUR-NEW-TABLE-NAME}. + * --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX] + * } * - *

              Decide whether you want your pipeline to run with 'bounded' (such as files in GCS) or - * 'unbounded' input (such as a PubSub topic). To run with unbounded input, set - * {@code --unbounded=true}. Then, optionally specify the Google Cloud PubSub topic to read from - * via {@code --pubsubTopic=projects/PROJECT_ID/topics/YOUR_TOPIC_NAME}. If the topic does not - * exist, the pipeline will create one for you. It will delete this topic when it terminates. - * The pipeline will automatically launch an auxiliary batch pipeline to populate the given PubSub - * topic with the contents of the {@code --inputFile}, in order to make the example easy to run. - * If you want to use an independently-populated PubSub topic, indicate this by setting - * {@code --inputFile=""}. In that case, the auxiliary pipeline will not be started. + *

              The input file defaults to a public data set containing the text of of King Lear, + * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. * *

              By default, the pipeline will do fixed windowing, on 1-minute windows. You can * change this interval by setting the {@code --windowSize} parameter, e.g. {@code --windowSize=10} * for 10-minute windows. + * + *

              The example will try to cancel the pipeline on the signal to terminate the process (CTRL-C). */ public class WindowedWordCount { - private static final Logger LOG = LoggerFactory.getLogger(WindowedWordCount.class); - static final int WINDOW_SIZE = 1; // Default window duration in minutes - + static final int WINDOW_SIZE = 10; // Default window duration in minutes /** * Concept #2: A DoFn that sets the data element timestamp. This is a silly method, just for * this example, for the bounded data case. @@ -119,13 +100,22 @@ public class WindowedWordCount { * 2-hour period. */ static class AddTimestampFn extends DoFn { - private static final long RAND_RANGE = 7200000; // 2 hours in ms + private static final Duration RAND_RANGE = Duration.standardHours(1); + private final Instant minTimestamp; + private final Instant maxTimestamp; - @Override + AddTimestampFn(Instant minTimestamp, Instant maxTimestamp) { + this.minTimestamp = minTimestamp; + this.maxTimestamp = maxTimestamp; + } + + @ProcessElement public void processElement(ProcessContext c) { - // Generate a timestamp that falls somewhere in the past two hours. - long randomTimestamp = System.currentTimeMillis() - - (int) (Math.random() * RAND_RANGE); + Instant randomTimestamp = + new Instant( + ThreadLocalRandom.current() + .nextLong(minTimestamp.getMillis(), maxTimestamp.getMillis())); + /** * Concept #2: Set the data element with that timestamp. */ @@ -133,130 +123,120 @@ public void processElement(ProcessContext c) { } } - /** A DoFn that converts a Word and Count into a BigQuery table row. */ - static class FormatAsTableRowFn extends DoFn, TableRow> { + /** A {@link DefaultValueFactory} that returns the current system time. */ + public static class DefaultToCurrentSystemTime implements DefaultValueFactory { @Override - public void processElement(ProcessContext c) { - TableRow row = new TableRow() - .set("word", c.element().getKey()) - .set("count", c.element().getValue()) - // include a field for the window timestamp - .set("window_timestamp", c.timestamp().toString()); - c.output(row); + public Long create(PipelineOptions options) { + return System.currentTimeMillis(); } } - /** - * Helper method that defines the BigQuery schema used for the output. - */ - private static TableSchema getSchema() { - List fields = new ArrayList<>(); - fields.add(new TableFieldSchema().setName("word").setType("STRING")); - fields.add(new TableFieldSchema().setName("count").setType("INTEGER")); - fields.add(new TableFieldSchema().setName("window_timestamp").setType("TIMESTAMP")); - TableSchema schema = new TableSchema().setFields(fields); - return schema; - } - - /** - * Concept #6: We'll stream the results to a BigQuery table. The BigQuery output source is one - * that supports both bounded and unbounded data. This is a helper method that creates a - * TableReference from input options, to tell the pipeline where to write its BigQuery results. - */ - private static TableReference getTableReference(Options options) { - TableReference tableRef = new TableReference(); - tableRef.setProjectId(options.getProject()); - tableRef.setDatasetId(options.getBigQueryDataset()); - tableRef.setTableId(options.getBigQueryTable()); - return tableRef; + /** A {@link DefaultValueFactory} that returns the minimum timestamp plus one hour. */ + public static class DefaultToMinTimestampPlusOneHour implements DefaultValueFactory { + @Override + public Long create(PipelineOptions options) { + return options.as(Options.class).getMinTimestampMillis() + + Duration.standardHours(1).getMillis(); + } } /** - * Options supported by {@link WindowedWordCount}. + * Options for {@link WindowedWordCount}. * - *

              Inherits standard example configuration options, which allow specification of the BigQuery - * table and the PubSub topic, as well as the {@link WordCount.WordCountOptions} support for - * specification of the input file. + *

              Inherits standard example configuration options, which allow specification of the + * runner, as well as the {@link WordCount.WordCountOptions} support for + * specification of the input and output files. */ - public interface Options - extends WordCount.WordCountOptions, DataflowExampleUtils.DataflowExampleUtilsOptions { + public interface Options extends WordCount.WordCountOptions, + ExampleOptions, ExampleBigQueryTableOptions { @Description("Fixed window duration, in minutes") @Default.Integer(WINDOW_SIZE) Integer getWindowSize(); void setWindowSize(Integer value); - @Description("Whether to run the pipeline with unbounded input") - boolean isUnbounded(); - void setUnbounded(boolean value); + @Description("Minimum randomly assigned timestamp, in milliseconds-since-epoch") + @Default.InstanceFactory(DefaultToCurrentSystemTime.class) + Long getMinTimestampMillis(); + void setMinTimestampMillis(Long value); + + @Description("Maximum randomly assigned timestamp, in milliseconds-since-epoch") + @Default.InstanceFactory(DefaultToMinTimestampPlusOneHour.class) + Long getMaxTimestampMillis(); + void setMaxTimestampMillis(Long value); } public static void main(String[] args) throws IOException { Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - options.setBigQuerySchema(getSchema()); - // DataflowExampleUtils creates the necessary input sources to simplify execution of this - // Pipeline. - DataflowExampleUtils exampleDataflowUtils = new DataflowExampleUtils(options, - options.isUnbounded()); + final String output = options.getOutput(); + final Duration windowSize = Duration.standardMinutes(options.getWindowSize()); + final Instant minTimestamp = new Instant(options.getMinTimestampMillis()); + final Instant maxTimestamp = new Instant(options.getMaxTimestampMillis()); Pipeline pipeline = Pipeline.create(options); /** - * Concept #1: the Dataflow SDK lets us run the same pipeline with either a bounded or + * Concept #1: the Beam SDK lets us run the same pipeline with either a bounded or * unbounded input source. */ - PCollection input; - if (options.isUnbounded()) { - LOG.info("Reading from PubSub."); - /** - * Concept #3: Read from the PubSub topic. A topic will be created if it wasn't - * specified as an argument. The data elements' timestamps will come from the pubsub - * injection. - */ - input = pipeline - .apply(PubsubIO.Read.topic(options.getPubsubTopic())); - } else { - /** Else, this is a bounded pipeline. Read from the GCS file. */ - input = pipeline - .apply(TextIO.Read.from(options.getInputFile())) - // Concept #2: Add an element timestamp, using an artificial time just to show windowing. - // See AddTimestampFn for more detail on this. - .apply(ParDo.of(new AddTimestampFn())); - } + PCollection input = pipeline + /** Read from the GCS file. */ + .apply(TextIO.Read.from(options.getInputFile())) + // Concept #2: Add an element timestamp, using an artificial time just to show windowing. + // See AddTimestampFn for more detail on this. + .apply(ParDo.of(new AddTimestampFn(minTimestamp, maxTimestamp))); /** - * Concept #4: Window into fixed windows. The fixed window size for this example defaults to 1 + * Concept #3: Window into fixed windows. The fixed window size for this example defaults to 1 * minute (you can change this with a command-line option). See the documentation for more * information on how fixed windows work, and for information on the other types of windowing * available (e.g., sliding windows). */ - PCollection windowedWords = input - .apply(Window.into( - FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); + PCollection windowedWords = + input.apply( + Window.into( + FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); /** - * Concept #5: Re-use our existing CountWords transform that does not have knowledge of + * Concept #4: Re-use our existing CountWords transform that does not have knowledge of * windows over a PCollection containing windowed values. */ PCollection> wordCounts = windowedWords.apply(new WordCount.CountWords()); /** - * Concept #6: Format the results for a BigQuery table, then write to BigQuery. - * The BigQuery output source supports both bounded and unbounded data. + * Concept #5: Customize the output format using windowing information + * + *

              At this point, the data is organized by window. We're writing text files and and have no + * late data, so for simplicity we can use the window as the key and {@link GroupByKey} to get + * one output file per window. (if we had late data this key would not be unique) + * + *

              To access the window in a {@link DoFn}, add a {@link BoundedWindow} parameter. This will + * be automatically detected and populated with the window for the current element. */ - wordCounts.apply(ParDo.of(new FormatAsTableRowFn())) - .apply(BigQueryIO.Write.to(getTableReference(options)).withSchema(getSchema())); - - PipelineResult result = pipeline.run(); + PCollection>> keyedByWindow = + wordCounts.apply( + ParDo.of( + new DoFn, KV>>() { + @ProcessElement + public void processElement(ProcessContext context, IntervalWindow window) { + context.output(KV.of(window, context.element())); + } + })); /** - * To mock unbounded input from PubSub, we'll now start an auxiliary 'injector' pipeline that - * runs for a limited time, and publishes to the input PubSub topic. - * - * With an unbounded input source, you will need to explicitly shut down this pipeline when you - * are done with it, so that you do not continue to be charged for the instances. You can do - * this via a ctrl-C from the command line, or from the developer's console UI for Dataflow - * pipelines. The PubSub topic will also be deleted at this time. + * Concept #6: Format the results and write to a sharded file partitioned by window, using a + * simple ParDo operation. Because there may be failures followed by retries, the + * writes must be idempotent, but the details of writing to files is elided here. */ - exampleDataflowUtils.mockUnboundedSource(options.getInputFile(), result); + keyedByWindow + .apply(GroupByKey.>create()) + .apply(ParDo.of(new WriteWindowedFilesDoFn(output))); + + PipelineResult result = pipeline.run(); + try { + result.waitUntilFinish(); + } catch (Exception exc) { + result.cancel(); + } } + } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java index c787585e25..634dea1a0a 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -1,42 +1,42 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 ${package}; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.transforms.Aggregator; -import com.google.cloud.dataflow.sdk.transforms.Count; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.PTransform; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.transforms.Sum; -import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; -import com.google.cloud.dataflow.sdk.values.KV; -import com.google.cloud.dataflow.sdk.values.PCollection; - +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.options.Validation.Required; +import org.apache.beam.sdk.transforms.Aggregator; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SimpleFunction; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; /** - * An example that counts words in Shakespeare and includes Dataflow best practices. + * An example that counts words in Shakespeare and includes Beam best practices. * *

              This class, {@link WordCount}, is the second in a series of four successively more detailed * 'word count' examples. You may first want to take a look at {@link MinimalWordCount}. @@ -44,61 +44,52 @@ * pipeline, for introduction of additional concepts. * *

              For a detailed walkthrough of this example, see - * - * https://cloud.google.com/dataflow/java-sdk/wordcount-example + * + * http://beam.apache.org/use/walkthroughs/ * * *

              Basic concepts, also in the MinimalWordCount example: - * Reading text files; counting a PCollection; writing to GCS. + * Reading text files; counting a PCollection; writing to text files * *

              New Concepts: *

              - *   1. Executing a Pipeline both locally and using the Dataflow service
              + *   1. Executing a Pipeline both locally and using the selected runner
                *   2. Using ParDo with static DoFns defined out-of-line
                *   3. Building a composite transform
                *   4. Defining your own pipeline options
                * 
              * - *

              Concept #1: you can execute this pipeline either locally or using the Dataflow service. + *

              Concept #1: you can execute this pipeline either locally or using by selecting another runner. * These are now command-line options and not hard-coded as they were in the MinimalWordCount * example. - * To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * and a local output file or output prefix on GCS: - *
              {@code
              - *   --output=[YOUR_LOCAL_FILE | gs://YOUR_OUTPUT_PREFIX]
              - * }
              * - *

              To execute this pipeline using the Dataflow service, specify pipeline configuration: + *

              To change the runner, specify: *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --stagingLocation=gs://YOUR_STAGING_DIRECTORY
              - *   --runner=BlockingDataflowPipelineRunner
              + *   --runner=YOUR_SELECTED_RUNNER
                * }
                * 
              - * and an output prefix on GCS: + * + *

              To execute this pipeline, specify a local output file (if using the + * {@code DirectRunner}) or output prefix on a supported distributed file system. *

              {@code
              - *   --output=gs://YOUR_OUTPUT_PREFIX
              + *   --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
                * }
              * - *

              The input file defaults to {@code gs://dataflow-samples/shakespeare/kinglear.txt} and can be - * overridden with {@code --inputFile}. + *

              The input file defaults to a public data set containing the text of of King Lear, + * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. */ public class WordCount { /** - * Concept #2: You can make your pipeline code less verbose by defining your DoFns statically out- - * of-line. This DoFn tokenizes lines of text into individual words; we pass it to a ParDo in the - * pipeline. + * Concept #2: You can make your pipeline assembly code less verbose by defining your DoFns + * statically out-of-line. This DoFn tokenizes lines of text into individual words; we pass it + * to a ParDo in the pipeline. */ static class ExtractWordsFn extends DoFn { private final Aggregator emptyLines = createAggregator("emptyLines", new Sum.SumLongFn()); - @Override + @ProcessElement public void processElement(ProcessContext c) { if (c.element().trim().isEmpty()) { emptyLines.addValue(1L); @@ -116,11 +107,11 @@ public void processElement(ProcessContext c) { } } - /** A DoFn that converts a Word and Count into a printable string. */ - public static class FormatAsTextFn extends DoFn, String> { + /** A SimpleFunction that converts a Word and Count into a printable string. */ + public static class FormatAsTextFn extends SimpleFunction, String> { @Override - public void processElement(ProcessContext c) { - c.output(c.element().getKey() + ": " + c.element().getValue()); + public String apply(KV input) { + return input.getKey() + ": " + input.getValue(); } } @@ -135,7 +126,7 @@ public void processElement(ProcessContext c) { public static class CountWords extends PTransform, PCollection>> { @Override - public PCollection> apply(PCollection lines) { + public PCollection> expand(PCollection lines) { // Convert lines of text into individual words. PCollection words = lines.apply( @@ -159,32 +150,23 @@ public PCollection> apply(PCollection lines) { *

              Inherits standard configuration options. */ public interface WordCountOptions extends PipelineOptions { + + /** + * By default, this example reads from a public dataset containing the text of + * King Lear. Set this option to choose a different input file or glob. + */ @Description("Path of the file to read from") - @Default.String("gs://dataflow-samples/shakespeare/kinglear.txt") + @Default.String("gs://apache-beam-samples/shakespeare/kinglear.txt") String getInputFile(); void setInputFile(String value); + /** + * Set this required option to specify where to write the output. + */ @Description("Path of the file to write to") - @Default.InstanceFactory(OutputFactory.class) + @Required String getOutput(); void setOutput(String value); - - /** - * Returns "gs://${YOUR_STAGING_DIRECTORY}/counts.txt" as the default destination. - */ - class OutputFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - if (dataflowOptions.getStagingLocation() != null) { - return GcsPath.fromUri(dataflowOptions.getStagingLocation()) - .resolve("counts.txt").toString(); - } else { - throw new IllegalArgumentException("Must specify --output or --stagingLocation"); - } - } - } - } public static void main(String[] args) { @@ -194,11 +176,11 @@ public static void main(String[] args) { // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the // static FormatAsTextFn() to the ParDo transform. - p.apply(TextIO.Read.named("ReadLines").from(options.getInputFile())) + p.apply("ReadLines", TextIO.Read.from(options.getInputFile())) .apply(new CountWords()) - .apply(ParDo.of(new FormatAsTextFn())) - .apply(TextIO.Write.named("WriteCounts").to(options.getOutput())); + .apply(MapElements.via(new FormatAsTextFn())) + .apply("WriteCounts", TextIO.Write.to(options.getOutput())); - p.run(); + p.run().waitUntilFinish(); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleOptions.java deleted file mode 100644 index e182f4cd2b..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleOptions.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 ${package}.common; - -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.Description; - -/** - * Options that can be used to configure the Dataflow examples. - */ -public interface DataflowExampleOptions extends DataflowPipelineOptions { - @Description("Whether to keep jobs running on the Dataflow service after local process exit") - @Default.Boolean(false) - boolean getKeepJobsRunning(); - void setKeepJobsRunning(boolean keepJobsRunning); -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java deleted file mode 100644 index e663224db9..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/DataflowExampleUtils.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 ${package}.common; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.Bigquery.Datasets; -import com.google.api.services.bigquery.Bigquery.Tables; -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.DatasetReference; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.api.services.dataflow.Dataflow; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.Topic; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.PipelineResult; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.BigQueryOptions; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineJob; -import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner; -import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner; -import com.google.cloud.dataflow.sdk.transforms.IntraBundleParallelization; -import com.google.cloud.dataflow.sdk.util.MonitoringUtil; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import javax.servlet.http.HttpServletResponse; - -/** - * The utility class that sets up and tears down external resources, starts the Google Cloud Pub/Sub - * injector, and cancels the streaming and the injector pipelines once the program terminates. - * - *

              It is used to run Dataflow examples, such as TrafficMaxLaneFlow and TrafficRoutes. - */ -public class DataflowExampleUtils { - - private final DataflowPipelineOptions options; - private Bigquery bigQueryClient = null; - private Pubsub pubsubClient = null; - private Dataflow dataflowClient = null; - private Set jobsToCancel = Sets.newHashSet(); - private List pendingMessages = Lists.newArrayList(); - - /** - * Define an interface that supports the PubSub and BigQuery example options. - */ - public interface DataflowExampleUtilsOptions - extends DataflowExampleOptions, ExamplePubsubTopicOptions, ExampleBigQueryTableOptions { - } - - public DataflowExampleUtils(DataflowPipelineOptions options) { - this.options = options; - } - - /** - * Do resources and runner options setup. - */ - public DataflowExampleUtils(DataflowPipelineOptions options, boolean isUnbounded) - throws IOException { - this.options = options; - setupResourcesAndRunner(isUnbounded); - } - - /** - * Sets up external resources that are required by the example, - * such as Pub/Sub topics and BigQuery tables. - * - * @throws IOException if there is a problem setting up the resources - */ - public void setup() throws IOException { - setupPubsubTopic(); - setupBigQueryTable(); - } - - /** - * Set up external resources, and configure the runner appropriately. - */ - public void setupResourcesAndRunner(boolean isUnbounded) throws IOException { - if (isUnbounded) { - options.setStreaming(true); - } - setup(); - setupRunner(); - } - - /** - * Sets up the Google Cloud Pub/Sub topic. - * - *

              If the topic doesn't exist, a new topic with the given name will be created. - * - * @throws IOException if there is a problem setting up the Pub/Sub topic - */ - public void setupPubsubTopic() throws IOException { - ExamplePubsubTopicOptions pubsubTopicOptions = options.as(ExamplePubsubTopicOptions.class); - if (!pubsubTopicOptions.getPubsubTopic().isEmpty()) { - pendingMessages.add("*******************Set Up Pubsub Topic*********************"); - setupPubsubTopic(pubsubTopicOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been set up for this example: " - + pubsubTopicOptions.getPubsubTopic()); - } - } - - /** - * Sets up the BigQuery table with the given schema. - * - *

              If the table already exists, the schema has to match the given one. Otherwise, the example - * will throw a RuntimeException. If the table doesn't exist, a new table with the given schema - * will be created. - * - * @throws IOException if there is a problem setting up the BigQuery table - */ - public void setupBigQueryTable() throws IOException { - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("******************Set Up Big Query Table*******************"); - setupBigQueryTable(bigQueryTableOptions.getProject(), - bigQueryTableOptions.getBigQueryDataset(), - bigQueryTableOptions.getBigQueryTable(), - bigQueryTableOptions.getBigQuerySchema()); - pendingMessages.add("The BigQuery table has been set up for this example: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - } - } - - /** - * Tears down external resources that can be deleted upon the example's completion. - */ - private void tearDown() { - pendingMessages.add("*************************Tear Down*************************"); - ExamplePubsubTopicOptions pubsubTopicOptions = options.as(ExamplePubsubTopicOptions.class); - if (!pubsubTopicOptions.getPubsubTopic().isEmpty()) { - try { - deletePubsubTopic(pubsubTopicOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been deleted: " - + pubsubTopicOptions.getPubsubTopic()); - } catch (IOException e) { - pendingMessages.add("Failed to delete the Pub/Sub topic : " - + pubsubTopicOptions.getPubsubTopic()); - } - } - - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("The BigQuery table might contain the example's output, " - + "and it is not deleted automatically: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - pendingMessages.add("Please go to the Developers Console to delete it manually." - + " Otherwise, you may be charged for its usage."); - } - } - - private void setupBigQueryTable(String projectId, String datasetId, String tableId, - TableSchema schema) throws IOException { - if (bigQueryClient == null) { - bigQueryClient = Transport.newBigQueryClient(options.as(BigQueryOptions.class)).build(); - } - - Datasets datasetService = bigQueryClient.datasets(); - if (executeNullIfNotFound(datasetService.get(projectId, datasetId)) == null) { - Dataset newDataset = new Dataset().setDatasetReference( - new DatasetReference().setProjectId(projectId).setDatasetId(datasetId)); - datasetService.insert(projectId, newDataset).execute(); - } - - Tables tableService = bigQueryClient.tables(); - Table table = executeNullIfNotFound(tableService.get(projectId, datasetId, tableId)); - if (table == null) { - Table newTable = new Table().setSchema(schema).setTableReference( - new TableReference().setProjectId(projectId).setDatasetId(datasetId).setTableId(tableId)); - tableService.insert(projectId, datasetId, newTable).execute(); - } else if (!table.getSchema().equals(schema)) { - throw new RuntimeException( - "Table exists and schemas do not match, expecting: " + schema.toPrettyString() - + ", actual: " + table.getSchema().toPrettyString()); - } - } - - private void setupPubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) == null) { - pubsubClient.projects().topics().create(topic, new Topic().setName(topic)).execute(); - } - } - - /** - * Deletes the Google Cloud Pub/Sub topic. - * - * @throws IOException if there is a problem deleting the Pub/Sub topic - */ - private void deletePubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) != null) { - pubsubClient.projects().topics().delete(topic).execute(); - } - } - - /** - * If this is an unbounded (streaming) pipeline, and both inputFile and pubsub topic are defined, - * start an 'injector' pipeline that publishes the contents of the file to the given topic, first - * creating the topic if necessary. - */ - public void startInjectorIfNeeded(String inputFile) { - ExamplePubsubTopicOptions pubsubTopicOptions = options.as(ExamplePubsubTopicOptions.class); - if (pubsubTopicOptions.isStreaming() - && inputFile != null && !inputFile.isEmpty() - && pubsubTopicOptions.getPubsubTopic() != null - && !pubsubTopicOptions.getPubsubTopic().isEmpty()) { - runInjectorPipeline(inputFile, pubsubTopicOptions.getPubsubTopic()); - } - } - - /** - * Do some runner setup: check that the DirectPipelineRunner is not used in conjunction with - * streaming, and if streaming is specified, use the DataflowPipelineRunner. Return the streaming - * flag value. - */ - public void setupRunner() { - if (options.isStreaming()) { - if (options.getRunner() == DirectPipelineRunner.class) { - throw new IllegalArgumentException( - "Processing of unbounded input sources is not supported with the DirectPipelineRunner."); - } - // In order to cancel the pipelines automatically, - // {@literal DataflowPipelineRunner} is forced to be used. - options.setRunner(DataflowPipelineRunner.class); - } - } - - /** - * Runs the batch injector for the streaming pipeline. - * - *

              The injector pipeline will read from the given text file, and inject data - * into the Google Cloud Pub/Sub topic. - */ - public void runInjectorPipeline(String inputFile, String topic) { - DataflowPipelineOptions copiedOptions = options.cloneAs(DataflowPipelineOptions.class); - copiedOptions.setStreaming(false); - copiedOptions.setWorkerHarnessContainerImage( - DataflowPipelineRunner.BATCH_WORKER_HARNESS_CONTAINER_IMAGE); - copiedOptions.setNumWorkers( - options.as(ExamplePubsubTopicOptions.class).getInjectorNumWorkers()); - copiedOptions.setJobName(options.getJobName() + "-injector"); - Pipeline injectorPipeline = Pipeline.create(copiedOptions); - injectorPipeline.apply(TextIO.Read.from(inputFile)) - .apply(IntraBundleParallelization - .of(PubsubFileInjector.publish(topic)) - .withMaxParallelism(20)); - DataflowPipelineJob injectorJob = (DataflowPipelineJob) injectorPipeline.run(); - jobsToCancel.add(injectorJob); - } - - /** - * Runs the provided injector pipeline for the streaming pipeline. - */ - public void runInjectorPipeline(Pipeline injectorPipeline) { - DataflowPipelineJob injectorJob = (DataflowPipelineJob) injectorPipeline.run(); - jobsToCancel.add(injectorJob); - } - - /** - * Start the auxiliary injector pipeline, then wait for this pipeline to finish. - */ - public void mockUnboundedSource(String inputFile, PipelineResult result) { - startInjectorIfNeeded(inputFile); - waitToFinish(result); - } - - /** - * If {@literal DataflowPipelineRunner} or {@literal BlockingDataflowPipelineRunner} is used, - * waits for the pipeline to finish and cancels it (and the injector) before the program exists. - */ - public void waitToFinish(PipelineResult result) { - if (result instanceof DataflowPipelineJob) { - final DataflowPipelineJob job = (DataflowPipelineJob) result; - jobsToCancel.add(job); - if (!options.as(DataflowExampleOptions.class).getKeepJobsRunning()) { - addShutdownHook(jobsToCancel); - } - try { - job.waitToFinish(-1, TimeUnit.SECONDS, new MonitoringUtil.PrintHandler(System.out)); - } catch (Exception e) { - throw new RuntimeException("Failed to wait for job to finish: " + job.getJobId()); - } - } else { - // Do nothing if the given PipelineResult doesn't support waitToFinish(), - // such as EvaluationResults returned by DirectPipelineRunner. - } - } - - private void addShutdownHook(final Collection jobs) { - if (dataflowClient == null) { - dataflowClient = options.getDataflowClient(); - } - - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - tearDown(); - printPendingMessages(); - for (DataflowPipelineJob job : jobs) { - System.out.println("Canceling example pipeline: " + job.getJobId()); - try { - job.cancel(); - } catch (IOException e) { - System.out.println("Failed to cancel the job," - + " please go to the Developers Console to cancel it manually"); - System.out.println( - MonitoringUtil.getJobMonitoringPageURL(job.getProjectId(), job.getJobId())); - } - } - - for (DataflowPipelineJob job : jobs) { - boolean cancellationVerified = false; - for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { - if (job.getState().isTerminal()) { - cancellationVerified = true; - System.out.println("Canceled example pipeline: " + job.getJobId()); - break; - } else { - System.out.println( - "The example pipeline is still running. Verifying the cancellation."); - } - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - // Ignore - } - } - if (!cancellationVerified) { - System.out.println("Failed to verify the cancellation for job: " + job.getJobId()); - System.out.println("Please go to the Developers Console to verify manually:"); - System.out.println( - MonitoringUtil.getJobMonitoringPageURL(job.getProjectId(), job.getJobId())); - } - } - } - }); - } - - private void printPendingMessages() { - System.out.println(); - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - for (String message : pendingMessages) { - System.out.println(message); - } - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - } - - private static T executeNullIfNotFound( - AbstractGoogleClientRequest request) throws IOException { - try { - return request.execute(); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { - return null; - } else { - throw e; - } - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java index 45546b1717..6b51074f44 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java @@ -1,33 +1,36 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 * - * 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. + * 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 ${package}.common; import com.google.api.services.bigquery.model.TableSchema; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.GcpOptions; +import org.apache.beam.sdk.options.PipelineOptions; /** - * Options that can be used to configure BigQuery tables in Dataflow examples. + * Options that can be used to configure BigQuery tables in Beam examples. * The project defaults to the project being used to run the example. */ -public interface ExampleBigQueryTableOptions extends DataflowPipelineOptions { +public interface ExampleBigQueryTableOptions extends GcpOptions { @Description("BigQuery dataset name") - @Default.String("dataflow_examples") + @Default.String("beam_examples") String getBigQueryDataset(); void setBigQueryDataset(String dataset); @@ -46,8 +49,7 @@ public interface ExampleBigQueryTableOptions extends DataflowPipelineOptions { class BigQueryTableFactory implements DefaultValueFactory { @Override public String create(PipelineOptions options) { - return options.as(DataflowPipelineOptions.class).getJobName() - .replace('-', '_'); + return options.getJobName().replace('-', '_'); } } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java new file mode 100644 index 0000000000..90f935c3ce --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java @@ -0,0 +1,37 @@ +/* + * 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 ${package}.common; + +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptions; + +/** + * Options that can be used to configure the Beam examples. + */ +public interface ExampleOptions extends PipelineOptions { + @Description("Whether to keep jobs running after local process exit") + @Default.Boolean(false) + boolean getKeepJobsRunning(); + void setKeepJobsRunning(boolean keepJobsRunning); + + @Description("Number of workers to use when executing the injector pipeline") + @Default.Integer(1) + int getInjectorNumWorkers(); + void setInjectorNumWorkers(int numWorkers); +} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java new file mode 100644 index 0000000000..daeb398f7f --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java @@ -0,0 +1,45 @@ +/* + * 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 ${package}.common; + +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.GcpOptions; +import org.apache.beam.sdk.options.PipelineOptions; + +/** + * Options that can be used to configure Pub/Sub topic/subscription in Beam examples. + */ +public interface ExamplePubsubTopicAndSubscriptionOptions extends ExamplePubsubTopicOptions { + @Description("Pub/Sub subscription") + @Default.InstanceFactory(PubsubSubscriptionFactory.class) + String getPubsubSubscription(); + void setPubsubSubscription(String subscription); + + /** + * Returns a default Pub/Sub subscription based on the project and the job names. + */ + class PubsubSubscriptionFactory implements DefaultValueFactory { + @Override + public String create(PipelineOptions options) { + return "projects/" + options.as(GcpOptions.class).getProject() + + "/subscriptions/" + options.getJobName(); + } + } +} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java index f217821f1c..936bff5675 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java @@ -1,49 +1,45 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 * - * 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. + * 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 ${package}.common; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Default; -import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.GcpOptions; +import org.apache.beam.sdk.options.PipelineOptions; /** - * Options that can be used to configure Pub/Sub topic in Dataflow examples. + * Options that can be used to configure Pub/Sub topic in Beam examples. */ -public interface ExamplePubsubTopicOptions extends DataflowPipelineOptions { +public interface ExamplePubsubTopicOptions extends GcpOptions { @Description("Pub/Sub topic") @Default.InstanceFactory(PubsubTopicFactory.class) String getPubsubTopic(); void setPubsubTopic(String topic); - @Description("Number of workers to use when executing the injector pipeline") - @Default.Integer(1) - int getInjectorNumWorkers(); - void setInjectorNumWorkers(int numWorkers); - /** * Returns a default Pub/Sub topic based on the project and the job names. */ class PubsubTopicFactory implements DefaultValueFactory { @Override public String create(PipelineOptions options) { - DataflowPipelineOptions dataflowPipelineOptions = - options.as(DataflowPipelineOptions.class); - return "projects/" + dataflowPipelineOptions.getProject() - + "/topics/" + dataflowPipelineOptions.getJobName(); + return "projects/" + options.as(GcpOptions.class).getProject() + + "/topics/" + options.getJobName(); } } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java new file mode 100644 index 0000000000..570b3827b7 --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java @@ -0,0 +1,352 @@ +/* + * 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 ${package}.common; + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.BackOffUtils; +import com.google.api.client.util.Sleeper; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.Bigquery.Datasets; +import com.google.api.services.bigquery.Bigquery.Tables; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.api.services.pubsub.Pubsub; +import com.google.api.services.pubsub.model.Subscription; +import com.google.api.services.pubsub.model.Topic; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.common.util.concurrent.Uninterruptibles; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.options.BigQueryOptions; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PubsubOptions; +import org.apache.beam.sdk.util.FluentBackoff; +import org.apache.beam.sdk.util.Transport; +import org.joda.time.Duration; + +/** + * The utility class that sets up and tears down external resources, + * and cancels the streaming pipelines once the program terminates. + * + *

              It is used to run Beam examples. + */ +public class ExampleUtils { + + private static final int SC_NOT_FOUND = 404; + + private final PipelineOptions options; + private Bigquery bigQueryClient = null; + private Pubsub pubsubClient = null; + private Set pipelinesToCancel = Sets.newHashSet(); + private List pendingMessages = Lists.newArrayList(); + + /** + * Do resources and runner options setup. + */ + public ExampleUtils(PipelineOptions options) { + this.options = options; + } + + /** + * Sets up external resources that are required by the example, + * such as Pub/Sub topics and BigQuery tables. + * + * @throws IOException if there is a problem setting up the resources + */ + public void setup() throws IOException { + Sleeper sleeper = Sleeper.DEFAULT; + BackOff backOff = + FluentBackoff.DEFAULT + .withMaxRetries(3).withInitialBackoff(Duration.millis(200)).backoff(); + Throwable lastException = null; + try { + do { + try { + setupPubsub(); + setupBigQueryTable(); + return; + } catch (GoogleJsonResponseException e) { + lastException = e; + } + } while (BackOffUtils.next(sleeper, backOff)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + // Ignore InterruptedException + } + throw new RuntimeException(lastException); + } + + /** + * Sets up the Google Cloud Pub/Sub topic. + * + *

              If the topic doesn't exist, a new topic with the given name will be created. + * + * @throws IOException if there is a problem setting up the Pub/Sub topic + */ + public void setupPubsub() throws IOException { + ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = + options.as(ExamplePubsubTopicAndSubscriptionOptions.class); + if (!pubsubOptions.getPubsubTopic().isEmpty()) { + pendingMessages.add("**********************Set Up Pubsub************************"); + setupPubsubTopic(pubsubOptions.getPubsubTopic()); + pendingMessages.add("The Pub/Sub topic has been set up for this example: " + + pubsubOptions.getPubsubTopic()); + + if (!pubsubOptions.getPubsubSubscription().isEmpty()) { + setupPubsubSubscription( + pubsubOptions.getPubsubTopic(), pubsubOptions.getPubsubSubscription()); + pendingMessages.add("The Pub/Sub subscription has been set up for this example: " + + pubsubOptions.getPubsubSubscription()); + } + } + } + + /** + * Sets up the BigQuery table with the given schema. + * + *

              If the table already exists, the schema has to match the given one. Otherwise, the example + * will throw a RuntimeException. If the table doesn't exist, a new table with the given schema + * will be created. + * + * @throws IOException if there is a problem setting up the BigQuery table + */ + public void setupBigQueryTable() throws IOException { + ExampleBigQueryTableOptions bigQueryTableOptions = + options.as(ExampleBigQueryTableOptions.class); + if (bigQueryTableOptions.getBigQueryDataset() != null + && bigQueryTableOptions.getBigQueryTable() != null + && bigQueryTableOptions.getBigQuerySchema() != null) { + pendingMessages.add("******************Set Up Big Query Table*******************"); + setupBigQueryTable(bigQueryTableOptions.getProject(), + bigQueryTableOptions.getBigQueryDataset(), + bigQueryTableOptions.getBigQueryTable(), + bigQueryTableOptions.getBigQuerySchema()); + pendingMessages.add("The BigQuery table has been set up for this example: " + + bigQueryTableOptions.getProject() + + ":" + bigQueryTableOptions.getBigQueryDataset() + + "." + bigQueryTableOptions.getBigQueryTable()); + } + } + + /** + * Tears down external resources that can be deleted upon the example's completion. + */ + private void tearDown() { + pendingMessages.add("*************************Tear Down*************************"); + ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = + options.as(ExamplePubsubTopicAndSubscriptionOptions.class); + if (!pubsubOptions.getPubsubTopic().isEmpty()) { + try { + deletePubsubTopic(pubsubOptions.getPubsubTopic()); + pendingMessages.add("The Pub/Sub topic has been deleted: " + + pubsubOptions.getPubsubTopic()); + } catch (IOException e) { + pendingMessages.add("Failed to delete the Pub/Sub topic : " + + pubsubOptions.getPubsubTopic()); + } + if (!pubsubOptions.getPubsubSubscription().isEmpty()) { + try { + deletePubsubSubscription(pubsubOptions.getPubsubSubscription()); + pendingMessages.add("The Pub/Sub subscription has been deleted: " + + pubsubOptions.getPubsubSubscription()); + } catch (IOException e) { + pendingMessages.add("Failed to delete the Pub/Sub subscription : " + + pubsubOptions.getPubsubSubscription()); + } + } + } + + ExampleBigQueryTableOptions bigQueryTableOptions = + options.as(ExampleBigQueryTableOptions.class); + if (bigQueryTableOptions.getBigQueryDataset() != null + && bigQueryTableOptions.getBigQueryTable() != null + && bigQueryTableOptions.getBigQuerySchema() != null) { + pendingMessages.add("The BigQuery table might contain the example's output, " + + "and it is not deleted automatically: " + + bigQueryTableOptions.getProject() + + ":" + bigQueryTableOptions.getBigQueryDataset() + + "." + bigQueryTableOptions.getBigQueryTable()); + pendingMessages.add("Please go to the Developers Console to delete it manually." + + " Otherwise, you may be charged for its usage."); + } + } + + private void setupBigQueryTable(String projectId, String datasetId, String tableId, + TableSchema schema) throws IOException { + if (bigQueryClient == null) { + bigQueryClient = Transport.newBigQueryClient(options.as(BigQueryOptions.class)).build(); + } + + Datasets datasetService = bigQueryClient.datasets(); + if (executeNullIfNotFound(datasetService.get(projectId, datasetId)) == null) { + Dataset newDataset = new Dataset().setDatasetReference( + new DatasetReference().setProjectId(projectId).setDatasetId(datasetId)); + datasetService.insert(projectId, newDataset).execute(); + } + + Tables tableService = bigQueryClient.tables(); + Table table = executeNullIfNotFound(tableService.get(projectId, datasetId, tableId)); + if (table == null) { + Table newTable = new Table().setSchema(schema).setTableReference( + new TableReference().setProjectId(projectId).setDatasetId(datasetId).setTableId(tableId)); + tableService.insert(projectId, datasetId, newTable).execute(); + } else if (!table.getSchema().equals(schema)) { + throw new RuntimeException( + "Table exists and schemas do not match, expecting: " + schema.toPrettyString() + + ", actual: " + table.getSchema().toPrettyString()); + } + } + + private void setupPubsubTopic(String topic) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) == null) { + pubsubClient.projects().topics().create(topic, new Topic().setName(topic)).execute(); + } + } + + private void setupPubsubSubscription(String topic, String subscription) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) == null) { + Subscription subInfo = new Subscription() + .setAckDeadlineSeconds(60) + .setTopic(topic); + pubsubClient.projects().subscriptions().create(subscription, subInfo).execute(); + } + } + + /** + * Deletes the Google Cloud Pub/Sub topic. + * + * @throws IOException if there is a problem deleting the Pub/Sub topic + */ + private void deletePubsubTopic(String topic) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) != null) { + pubsubClient.projects().topics().delete(topic).execute(); + } + } + + /** + * Deletes the Google Cloud Pub/Sub subscription. + * + * @throws IOException if there is a problem deleting the Pub/Sub subscription + */ + private void deletePubsubSubscription(String subscription) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) != null) { + pubsubClient.projects().subscriptions().delete(subscription).execute(); + } + } + + /** + * Waits for the pipeline to finish and cancels it before the program exists. + */ + public void waitToFinish(PipelineResult result) { + pipelinesToCancel.add(result); + if (!options.as(ExampleOptions.class).getKeepJobsRunning()) { + addShutdownHook(pipelinesToCancel); + } + try { + result.waitUntilFinish(); + } catch (UnsupportedOperationException e) { + // Do nothing if the given PipelineResult doesn't support waitUntilFinish(), + // such as EvaluationResults returned by DirectRunner. + tearDown(); + printPendingMessages(); + } catch (Exception e) { + throw new RuntimeException("Failed to wait the pipeline until finish: " + result); + } + } + + private void addShutdownHook(final Collection pipelineResults) { + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + tearDown(); + printPendingMessages(); + for (PipelineResult pipelineResult : pipelineResults) { + try { + pipelineResult.cancel(); + } catch (IOException e) { + System.out.println("Failed to cancel the job."); + System.out.println(e.getMessage()); + } + } + + for (PipelineResult pipelineResult : pipelineResults) { + boolean cancellationVerified = false; + for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { + if (pipelineResult.getState().isTerminal()) { + cancellationVerified = true; + break; + } else { + System.out.println( + "The example pipeline is still running. Verifying the cancellation."); + } + Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); + } + if (!cancellationVerified) { + System.out.println("Failed to verify the cancellation for job: " + pipelineResult); + } + } + } + }); + } + + private void printPendingMessages() { + System.out.println(); + System.out.println("***********************************************************"); + System.out.println("***********************************************************"); + for (String message : pendingMessages) { + System.out.println(message); + } + System.out.println("***********************************************************"); + System.out.println("***********************************************************"); + } + + private static T executeNullIfNotFound( + AbstractGoogleClientRequest request) throws IOException { + try { + return request.execute(); + } catch (GoogleJsonResponseException e) { + if (e.getStatusCode() == SC_NOT_FOUND) { + return null; + } else { + throw e; + } + } + } +} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/PubsubFileInjector.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/PubsubFileInjector.java deleted file mode 100644 index f6f80aec7d..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/PubsubFileInjector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2015 Google Inc. - * - * Licensed 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 ${package}.common; - -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.PublishRequest; -import com.google.api.services.pubsub.model.PubsubMessage; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.io.TextIO; -import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; -import com.google.cloud.dataflow.sdk.options.Description; -import com.google.cloud.dataflow.sdk.options.PipelineOptions; -import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; -import com.google.cloud.dataflow.sdk.options.Validation; -import com.google.cloud.dataflow.sdk.transforms.DoFn; -import com.google.cloud.dataflow.sdk.transforms.IntraBundleParallelization; -import com.google.cloud.dataflow.sdk.util.Transport; -import com.google.common.collect.ImmutableMap; - -import java.io.IOException; -import java.util.Arrays; - -/** - * A batch Dataflow pipeline for injecting a set of GCS files into - * a PubSub topic line by line. Empty lines are skipped. - * - *

              This is useful for testing streaming - * pipelines. Note that since batch pipelines might retry chunks, this - * does _not_ guarantee exactly-once injection of file data. Some lines may - * be published multiple times. - *

              - */ -public class PubsubFileInjector { - - /** - * An incomplete {@code PubsubFileInjector} transform with unbound output topic. - */ - public static class Unbound { - private final String timestampLabelKey; - - Unbound() { - this.timestampLabelKey = null; - } - - Unbound(String timestampLabelKey) { - this.timestampLabelKey = timestampLabelKey; - } - - Unbound withTimestampLabelKey(String timestampLabelKey) { - return new Unbound(timestampLabelKey); - } - - public Bound publish(String outputTopic) { - return new Bound(outputTopic, timestampLabelKey); - } - } - - /** A DoFn that publishes non-empty lines to Google Cloud PubSub. */ - public static class Bound extends DoFn { - private final String outputTopic; - private final String timestampLabelKey; - public transient Pubsub pubsub; - - public Bound(String outputTopic, String timestampLabelKey) { - this.outputTopic = outputTopic; - this.timestampLabelKey = timestampLabelKey; - } - - @Override - public void startBundle(Context context) { - this.pubsub = - Transport.newPubsubClient(context.getPipelineOptions().as(DataflowPipelineOptions.class)) - .build(); - } - - @Override - public void processElement(ProcessContext c) throws IOException { - if (c.element().isEmpty()) { - return; - } - PubsubMessage pubsubMessage = new PubsubMessage(); - pubsubMessage.encodeData(c.element().getBytes()); - if (timestampLabelKey != null) { - pubsubMessage.setAttributes( - ImmutableMap.of(timestampLabelKey, Long.toString(c.timestamp().getMillis()))); - } - PublishRequest publishRequest = new PublishRequest(); - publishRequest.setMessages(Arrays.asList(pubsubMessage)); - this.pubsub.projects().topics().publish(outputTopic, publishRequest).execute(); - } - } - - /** - * Creates a {@code PubsubFileInjector} transform with the given timestamp label key. - */ - public static Unbound withTimestampLabelKey(String timestampLabelKey) { - return new Unbound(timestampLabelKey); - } - - /** - * Creates a {@code PubsubFileInjector} transform that publishes to the given output topic. - */ - public static Bound publish(String outputTopic) { - return new Unbound().publish(outputTopic); - } - - /** - * Command line parameter options. - */ - private interface PubsubFileInjectorOptions extends PipelineOptions { - @Description("GCS location of files.") - @Validation.Required - String getInput(); - void setInput(String value); - - @Description("Topic to publish on.") - @Validation.Required - String getOutputTopic(); - void setOutputTopic(String value); - } - - /** - * Sets up and starts streaming pipeline. - */ - public static void main(String[] args) { - PubsubFileInjectorOptions options = PipelineOptionsFactory.fromArgs(args) - .withValidation() - .as(PubsubFileInjectorOptions.class); - - Pipeline pipeline = Pipeline.create(options); - - pipeline - .apply(TextIO.Read.from(options.getInput())) - .apply(IntraBundleParallelization.of(PubsubFileInjector.publish(options.getOutputTopic())) - .withMaxParallelism(20)); - - pipeline.run(); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java new file mode 100644 index 0000000000..a08e6a9b0f --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java @@ -0,0 +1,77 @@ +/* + * 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 ${package}.common; + +import com.google.common.annotations.VisibleForTesting; +import java.io.OutputStream; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.util.IOChannelFactory; +import org.apache.beam.sdk.util.IOChannelUtils; +import org.apache.beam.sdk.values.KV; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +/** + * A {@link DoFn} that writes elements to files with names deterministically derived from the lower + * and upper bounds of their key (an {@link IntervalWindow}). + * + *

              This is test utility code, not for end-users, so examples can be focused + * on their primary lessons. + */ +public class WriteWindowedFilesDoFn + extends DoFn>>, Void> { + + static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); + static final Coder STRING_CODER = StringUtf8Coder.of(); + + private static DateTimeFormatter formatter = ISODateTimeFormat.hourMinute(); + + private final String output; + + public WriteWindowedFilesDoFn(String output) { + this.output = output; + } + + @VisibleForTesting + public static String fileForWindow(String output, IntervalWindow window) { + return String.format( + "%s-%s-%s", output, formatter.print(window.start()), formatter.print(window.end())); + } + + @ProcessElement + public void processElement(ProcessContext context) throws Exception { + // Build a file name from the window + IntervalWindow window = context.element().getKey(); + String outputShard = fileForWindow(output, window); + + // Open the file and write all the values + IOChannelFactory factory = IOChannelUtils.getFactory(outputShard); + OutputStream out = Channels.newOutputStream(factory.create(outputShard, "text/plain")); + for (KV wordCount : context.element().getValue()) { + STRING_CODER.encode( + wordCount.getKey() + ": " + wordCount.getValue(), out, Coder.Context.OUTER); + out.write(NEWLINE); + } + out.close(); + } +} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java index 7a9aa4c5c6..155242d996 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java @@ -1,32 +1,33 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 ${package}; import com.google.common.io.Files; - +import java.io.File; +import java.nio.charset.StandardCharsets; +import ${package}.DebuggingWordCount.WordCountOptions; +import org.apache.beam.sdk.testing.TestPipeline; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.File; -import java.nio.charset.StandardCharsets; - /** * Tests for {@link DebuggingWordCount}. */ @@ -36,9 +37,16 @@ public class DebuggingWordCountTest { @Test public void testDebuggingWordCount() throws Exception { - File file = tmpFolder.newFile(); - Files.write("stomach secret Flourish message Flourish here Flourish", file, + File inputFile = tmpFolder.newFile(); + File outputFile = tmpFolder.newFile(); + Files.write( + "stomach secret Flourish message Flourish here Flourish", + inputFile, StandardCharsets.UTF_8); - DebuggingWordCount.main(new String[]{"--inputFile=" + file.getAbsolutePath()}); + WordCountOptions options = + TestPipeline.testingPipelineOptions().as(WordCountOptions.class); + options.setInputFile(inputFile.getAbsolutePath()); + options.setOutput(outputFile.getAbsolutePath()); + DebuggingWordCount.main(TestPipeline.convertToArgs(options)); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java index 45555ce3ce..e86c2aac96 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java @@ -1,34 +1,37 @@ /* - * Copyright (C) 2015 Google Inc. + * 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 * - * Licensed 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 + * 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. + * 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 ${package}; +import java.util.Arrays; +import java.util.List; import ${package}.WordCount.CountWords; import ${package}.WordCount.ExtractWordsFn; import ${package}.WordCount.FormatAsTextFn; -import com.google.cloud.dataflow.sdk.Pipeline; -import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; -import com.google.cloud.dataflow.sdk.testing.DataflowAssert; -import com.google.cloud.dataflow.sdk.testing.RunnableOnService; -import com.google.cloud.dataflow.sdk.testing.TestPipeline; -import com.google.cloud.dataflow.sdk.transforms.Create; -import com.google.cloud.dataflow.sdk.transforms.DoFnTester; -import com.google.cloud.dataflow.sdk.transforms.ParDo; -import com.google.cloud.dataflow.sdk.values.PCollection; - +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.RunnableOnService; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.DoFnTester; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.values.PCollection; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; @@ -36,26 +39,23 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.Arrays; -import java.util.List; - /** * Tests of WordCount. */ @RunWith(JUnit4.class) public class WordCountTest { - /** Example test that tests a specific DoFn. */ + /** Example test that tests a specific {@link DoFn}. */ @Test - public void testExtractWordsFn() { + public void testExtractWordsFn() throws Exception { DoFnTester extractWordsFn = DoFnTester.of(new ExtractWordsFn()); - Assert.assertThat(extractWordsFn.processBatch(" some input words "), + Assert.assertThat(extractWordsFn.processBundle(" some input words "), CoreMatchers.hasItems("some", "input", "words")); - Assert.assertThat(extractWordsFn.processBatch(" "), + Assert.assertThat(extractWordsFn.processBundle(" "), CoreMatchers.hasItems()); - Assert.assertThat(extractWordsFn.processBatch(" some ", " input", " words"), + Assert.assertThat(extractWordsFn.processBundle(" some ", " input", " words"), CoreMatchers.hasItems("some", "input", "words")); } @@ -77,9 +77,9 @@ public void testCountWords() throws Exception { PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); PCollection output = input.apply(new CountWords()) - .apply(ParDo.of(new FormatAsTextFn())); + .apply(MapElements.via(new FormatAsTextFn())); - DataflowAssert.that(output).containsInAnyOrder(COUNTS_ARRAY); - p.run(); + PAssert.that(output).containsInAnyOrder(COUNTS_ARRAY); + p.run().waitUntilFinish(); } } diff --git a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties index c59e77a9d5..1f3c9c5178 100644 --- a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties +++ b/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties @@ -1,3 +1,17 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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=it.pkg version=0.1-SNAPSHOT groupId=archetype.it From 2f2cc875d2776768c8b43c91200a7e8722218e1a Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 5 Jan 2017 11:33:44 -0800 Subject: [PATCH 670/751] Add copyright and license throughout --- .gitattributes | 14 ++++++++++++++ .gitignore | 14 ++++++++++++++ .travis.yml | 14 ++++++++++++++ CONTRIBUTING.md | 16 ++++++++++++++++ README.md | 16 ++++++++++++++++ .../META-INF/maven/archetype-metadata.xml | 15 +++++++++++++++ .../META-INF/maven/archetype-metadata.xml | 15 +++++++++++++++ .../main/resources/archetype-resources/pom.xml | 16 ++++++++++++++++ .../resources/projects/basic/reference/pom.xml | 16 ++++++++++++++++ 9 files changed, 136 insertions(+) diff --git a/.gitattributes b/.gitattributes index cce74a2d90..c39158cf00 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,17 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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. + # The default behavior, which overrides 'core.autocrlf', is to use Git's # built-in heuristics to determine whether a particular file is text or binary. # Text files are automatically normalized to the user's platforms. diff --git a/.gitignore b/.gitignore index 0ba351f6d6..2a27023c28 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,17 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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. + target/ # Ignore IntelliJ files. diff --git a/.travis.yml b/.travis.yml index d3c5cf99e4..1d59774ff6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,17 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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. + language: java sudo: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 606049f5a2..9b616e5fe3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,19 @@ + + Want to contribute? Great! First, read this page (including the small print at the end). diff --git a/README.md b/README.md index b3f85b2451..a644049218 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,19 @@ + + # Google Cloud Dataflow SDK for Java [Google Cloud Dataflow](https://cloud.google.com/dataflow/) provides a simple, diff --git a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml index 7742af4e72..2b9eb52d80 100644 --- a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml +++ b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -1,4 +1,19 @@ + + + diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index 336de14adf..db4b1c9784 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -1,3 +1,19 @@ + + From 44d1a179ee6c8061a0b6b0c8f83ac0d61f00f33d Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 5 Jan 2017 11:45:44 -0800 Subject: [PATCH 671/751] Add NOTICE file --- NOTICE | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 NOTICE diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000000..981fde5a9e --- /dev/null +++ b/NOTICE @@ -0,0 +1,5 @@ +Google Cloud Dataflow SDK for Java +Copyright 2017, Google Inc. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). From 2cc474ee3b37503185a56cd0a306e2a5da6d4f20 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 5 Jan 2017 20:20:05 -0800 Subject: [PATCH 672/751] Add NOTICE to archetypes and enforce they match the root NOTICE --- .travis.yml | 6 +++++- .../main/resources/META-INF/maven/archetype-metadata.xml | 7 +++++++ .../examples/src/main/resources/archetype-resources/NOTICE | 5 +++++ .../main/resources/META-INF/maven/archetype-metadata.xml | 7 +++++++ .../starter/src/main/resources/archetype-resources/NOTICE | 5 +++++ .../src/test/resources/projects/basic/reference/NOTICE | 5 +++++ 6 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE create mode 100644 maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE create mode 100644 maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE diff --git a/.travis.yml b/.travis.yml index 1d59774ff6..d72ff70f8e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -47,4 +47,8 @@ install: - travis_retry mvn install clean -U -DskipTests=true script: - - travis_retry mvn install -U + # Verify that the project can be built and installed. + - mvn install + # Verify that starter and examples archetypes have the correct version of the NOTICE file. + - diff -q NOTICE maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE + - diff -q NOTICE maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE diff --git a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml index 2b9eb52d80..1d26f20888 100644 --- a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml +++ b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -40,5 +40,12 @@ **/*.java + + + + + NOTICE + + diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE b/maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE new file mode 100644 index 0000000000..981fde5a9e --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE @@ -0,0 +1,5 @@ +Google Cloud Dataflow SDK for Java +Copyright 2017, Google Inc. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml index 4c22d5d68b..d8ded73555 100644 --- a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml +++ b/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -32,5 +32,12 @@ **/*.java + + + + + NOTICE + + diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE b/maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE new file mode 100644 index 0000000000..981fde5a9e --- /dev/null +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE @@ -0,0 +1,5 @@ +Google Cloud Dataflow SDK for Java +Copyright 2017, Google Inc. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE b/maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE new file mode 100644 index 0000000000..981fde5a9e --- /dev/null +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE @@ -0,0 +1,5 @@ +Google Cloud Dataflow SDK for Java +Copyright 2017, Google Inc. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). From 82175f5b17af24adfa6c9806ac2d664ad742b5aa Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Thu, 5 Jan 2017 21:32:47 -0800 Subject: [PATCH 673/751] maven-enforcer: require Java 1.8.0 and above --- pom.xml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/pom.xml b/pom.xml index a94365235e..7c6f4b738c 100644 --- a/pom.xml +++ b/pom.xml @@ -92,6 +92,34 @@ + + org.apache.maven.plugins + maven-enforcer-plugin + 1.4.1 + + + enforce-java + + enforce + + + + + + [1.8.0,) + + + + + + + org.apache.maven.plugins maven-clean-plugin @@ -264,6 +292,11 @@ + + org.apache.maven.plugins + maven-enforcer-plugin + + org.apache.maven.plugins maven-compiler-plugin From 518f462206c7d7cd0cae86089948e84af6b078b1 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 6 Jan 2017 09:59:25 -0800 Subject: [PATCH 674/751] Move NOTICE to the right location Root of the jars we ship Not in the generated projects --- .travis.yml | 4 ++-- .../main/resources/META-INF/maven/archetype-metadata.xml | 7 ------- .../src/main/resources/{archetype-resources => }/NOTICE | 0 .../main/resources/META-INF/maven/archetype-metadata.xml | 7 ------- .../src/main/resources/{archetype-resources => }/NOTICE | 0 .../src/test/resources/projects/basic/reference/NOTICE | 5 ----- 6 files changed, 2 insertions(+), 21 deletions(-) rename maven-archetypes/examples/src/main/resources/{archetype-resources => }/NOTICE (100%) rename maven-archetypes/starter/src/main/resources/{archetype-resources => }/NOTICE (100%) delete mode 100644 maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE diff --git a/.travis.yml b/.travis.yml index d72ff70f8e..8fa5d9a932 100644 --- a/.travis.yml +++ b/.travis.yml @@ -50,5 +50,5 @@ script: # Verify that the project can be built and installed. - mvn install # Verify that starter and examples archetypes have the correct version of the NOTICE file. - - diff -q NOTICE maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE - - diff -q NOTICE maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE + - diff -q NOTICE maven-archetypes/starter/src/main/resources/NOTICE + - diff -q NOTICE maven-archetypes/examples/src/main/resources/NOTICE diff --git a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml index 1d26f20888..2b9eb52d80 100644 --- a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml +++ b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -40,12 +40,5 @@ **/*.java - - - - - NOTICE - - diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE b/maven-archetypes/examples/src/main/resources/NOTICE similarity index 100% rename from maven-archetypes/examples/src/main/resources/archetype-resources/NOTICE rename to maven-archetypes/examples/src/main/resources/NOTICE diff --git a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml index d8ded73555..4c22d5d68b 100644 --- a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml +++ b/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -32,12 +32,5 @@ **/*.java - - - - - NOTICE - - diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE b/maven-archetypes/starter/src/main/resources/NOTICE similarity index 100% rename from maven-archetypes/starter/src/main/resources/archetype-resources/NOTICE rename to maven-archetypes/starter/src/main/resources/NOTICE diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE b/maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE deleted file mode 100644 index 981fde5a9e..0000000000 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Google Cloud Dataflow SDK for Java -Copyright 2017, Google Inc. - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). From b25cac0703b55fd62c3ecc752d3cb30a320de53b Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 6 Jan 2017 18:07:41 -0800 Subject: [PATCH 675/751] [maven-release-plugin] prepare branch release-2.0.0-beta1 --- examples/pom.xml | 4 +--- maven-archetypes/examples/pom.xml | 4 +--- maven-archetypes/starter/pom.xml | 4 +--- pom.xml | 5 ++--- sdk/pom.xml | 4 +--- 5 files changed, 6 insertions(+), 15 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index ec5277c800..4c8584a91c 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -14,9 +14,7 @@ ~ License for the specific language governing permissions and limitations under ~ the License. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> - + 4.0.0 diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 922acd49d1..fa781ac432 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -14,9 +14,7 @@ ~ License for the specific language governing permissions and limitations under ~ the License. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> - + 4.0.0 diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index efc5023c46..c600393712 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -14,9 +14,7 @@ ~ License for the specific language governing permissions and limitations under ~ the License. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> - + 4.0.0 diff --git a/pom.xml b/pom.xml index 7c6f4b738c..c3c64811f4 100644 --- a/pom.xml +++ b/pom.xml @@ -14,9 +14,7 @@ ~ License for the specific language governing permissions and limitations under ~ the License. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> - + 4.0.0 @@ -56,6 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git + release-2.0.0-beta1 diff --git a/sdk/pom.xml b/sdk/pom.xml index b6f5ecc572..8dd014f9f7 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -14,9 +14,7 @@ ~ License for the specific language governing permissions and limitations under ~ the License. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> - + 4.0.0 From 90fcfc07be037b96e1b98ef785569324984433c9 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 6 Jan 2017 18:07:50 -0800 Subject: [PATCH 676/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 4c8584a91c..c987e94893 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index fa781ac432..a640cd4e5e 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index c600393712..ec3bec3948 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index c3c64811f4..60d054b063 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.0.0-beta1 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index 8dd014f9f7..511e4e0a73 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT google-cloud-dataflow-java-sdk-all From d8b880def712cc990be0f0e1eb440d6a114e6d1c Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 6 Jan 2017 18:11:05 -0800 Subject: [PATCH 677/751] Manual fixes to archetypes to pin next development version --- .../examples/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/test/resources/projects/basic/reference/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 163212d61a..20e89f3064 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -125,7 +125,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index 183b29062c..01e9aa951b 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -74,7 +74,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index db4b1c9784..5530617bfe 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -74,7 +74,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta1-SNAPSHOT + 2.0.0-beta2-SNAPSHOT From 4a55dda33be95db80d9d20c2ab95b307ef1f0cfd Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 6 Jan 2017 18:34:40 -0800 Subject: [PATCH 678/751] Generate empty Javadoc --- pom.xml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/pom.xml b/pom.xml index 60d054b063..d7d7e4dab7 100644 --- a/pom.xml +++ b/pom.xml @@ -215,6 +215,24 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + false + + + + javadoc + package + + jar + + + + + org.apache.maven.plugins maven-dependency-plugin @@ -306,6 +324,11 @@ maven-source-plugin + + org.apache.maven.plugins + maven-javadoc-plugin + + org.apache.maven.plugins maven-dependency-plugin From aad7cafb876c03a50e16bd753a55e2450f461d50 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 6 Jan 2017 19:16:02 -0800 Subject: [PATCH 679/751] Move properties to root pom.xml --- pom.xml | 4 ++++ .../org/apache/beam/runners/dataflow/dataflow.properties | 6 +++--- sdk/src/main/resources/org/apache/beam/sdk/sdk.properties | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index d7d7e4dab7..ef65d33de6 100644 --- a/pom.xml +++ b/pom.xml @@ -78,6 +78,10 @@ yyyy-MM-dd HH:mm 0.4.0 + + Google Cloud Dataflow SDK for Java + ${project.version}-20170103 + 6 pom diff --git a/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties b/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties index 1af27fdd48..d499ad6699 100644 --- a/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties +++ b/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties @@ -12,7 +12,7 @@ # License for the specific language governing permissions and limitations under # the License. -environment.major.version=6 +environment.major.version=${dataflow.environment_major_version} -worker.image.batch=dataflow.gcr.io/v1beta3/beam-java-batch:${project.version}-20170103 -worker.image.streaming=dataflow.gcr.io/v1beta3/beam-java-streaming:${project.version}-20170103 +worker.image.batch=dataflow.gcr.io/v1beta3/beam-java-batch:${dataflow.container_version} +worker.image.streaming=dataflow.gcr.io/v1beta3/beam-java-streaming:${dataflow.container_version} diff --git a/sdk/src/main/resources/org/apache/beam/sdk/sdk.properties b/sdk/src/main/resources/org/apache/beam/sdk/sdk.properties index a9df3b5b5c..5b7997a43a 100644 --- a/sdk/src/main/resources/org/apache/beam/sdk/sdk.properties +++ b/sdk/src/main/resources/org/apache/beam/sdk/sdk.properties @@ -12,6 +12,6 @@ # License for the specific language governing permissions and limitations under # the License. -name=Google Cloud Dataflow SDK for Java +name=${dataflow.release_name} version=${pom.version} build.date=${timestamp} From 8fd6661267d254b2089f35649f9f1102eeecda57 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Mon, 9 Jan 2017 10:30:55 -0800 Subject: [PATCH 680/751] Update version range dependency to exclude 2.0.0-betaX versions (#528) * Update version range dependency to exclude 2.0.0-betaX versions * fixup --- contrib/firebaseio/pom.xml | 2 +- contrib/hadoop/pom.xml | 2 +- contrib/join-library/pom.xml | 2 +- contrib/kafka/pom.xml | 2 +- contrib/sorter/pom.xml | 2 +- .../examples/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/test/resources/projects/basic/reference/pom.xml | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/contrib/firebaseio/pom.xml b/contrib/firebaseio/pom.xml index b50ef89167..bf5414e24f 100644 --- a/contrib/firebaseio/pom.xml +++ b/contrib/firebaseio/pom.xml @@ -21,7 +21,7 @@ UTF-8 - [1.2.0, 2.0.0) + [1.2.0, 1.99) diff --git a/contrib/hadoop/pom.xml b/contrib/hadoop/pom.xml index 0659e3ebaa..60327b7fda 100644 --- a/contrib/hadoop/pom.xml +++ b/contrib/hadoop/pom.xml @@ -36,7 +36,7 @@ UTF-8 - [1.2.0,2.0.0) + [1.2.0, 1.99) diff --git a/contrib/join-library/pom.xml b/contrib/join-library/pom.xml index f15ef9794c..3f5675de4d 100644 --- a/contrib/join-library/pom.xml +++ b/contrib/join-library/pom.xml @@ -50,7 +50,7 @@ UTF-8 - [1.0.0, 2.0.0) + [1.0.0, 1.99) diff --git a/contrib/kafka/pom.xml b/contrib/kafka/pom.xml index 4beecd7ba5..c13946cc64 100644 --- a/contrib/kafka/pom.xml +++ b/contrib/kafka/pom.xml @@ -28,7 +28,7 @@ 0.1.0-SNAPSHOT - [1.6.0, 2.0.0) + [1.6.0, 1.99) 0.9.0.1 19.0 diff --git a/contrib/sorter/pom.xml b/contrib/sorter/pom.xml index d9ffb65bd9..4580ea5bab 100644 --- a/contrib/sorter/pom.xml +++ b/contrib/sorter/pom.xml @@ -36,7 +36,7 @@ UTF-8 - [1.2.0,2.0.0) + [1.2.0, 1.99) 2.7.1 diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 486a82b602..f58aafce9c 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -107,7 +107,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - [1.0.0, 2.0.0) + [1.0.0, 1.99) diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index ab2bcf9a70..70bf1e53d3 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -38,7 +38,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - [1.0.0, 2.0.0) + [1.0.0, 1.99) diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index b94fb39e12..db136756b3 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -38,7 +38,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - [1.0.0, 2.0.0) + [1.0.0, 1.99) From faa4c2e9af1c3c28a6ba78ebeabeced4866f82fc Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Mon, 9 Jan 2017 11:13:31 -0800 Subject: [PATCH 681/751] README.md for contrib/kafka --- contrib/kafka/README.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 contrib/kafka/README.md diff --git a/contrib/kafka/README.md b/contrib/kafka/README.md new file mode 100644 index 0000000000..e69de29bb2 From 2829f00fa224e56d832d8a2e7174b5d5d05da223 Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Mon, 9 Jan 2017 11:16:13 -0800 Subject: [PATCH 682/751] README.md for contrib/kafka --- contrib/kafka/README.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/contrib/kafka/README.md b/contrib/kafka/README.md index e69de29bb2..386072317f 100644 --- a/contrib/kafka/README.md +++ b/contrib/kafka/README.md @@ -0,0 +1,36 @@ +# KafkaIO : Dataflow Unbounded Source and Sink for Kafka Topics + +KafkaIO provides unbounded sources and sinks for [Kafka](https://www.firebase.com/) +topics. Kafka version 0.9 and above are supported. + +## Basic Usage + * Read from a topic with 8 byte long keys and string values: + ```java + PCollection> kafkaRecords = + pipeline + .applY(KafkaIO.read() + .withBootstrapServers("broker_1:9092,broker_2:9092") + .withTopics(ImmutableList.of("topic_a")) + .withKeyCoder(BigEndianLongCoder.of()) + .withValueCoder(StringUtf8Coder.of()) + .withoutMetadata() + ); + ``` + * Write the same PCollection to a Kafka topic: + ```java + kafkaRecords.apply(KafkaIO.write() + .withBootstrapServers("broker_1:9092,broker_2:9092") + .withTopic("results") + .withKeyCoder(BigEndianLongCoder.of()) + .withValueCoder(StringUtf8Coder.of()) + ``` + +Please see JavaDoc for KafkaIO in +[KafkaIO.java](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java#L100) +for complete documentation and a more descriptive usage example. + +## Release Notes + * **0.2.0** : Assign one split for each of the Kafka topic partitions. This makes Dataflow + [Update](https://cloud.google.com/dataflow/pipelines/updating-a-pipeline) + from previous version incompatible. + * **0.1.0** : KafkaIO with support for Unbounded Source and Sink. From 3e6116294f53085dab04dba9094b5a462f00104e Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Mon, 9 Jan 2017 13:55:49 -0800 Subject: [PATCH 683/751] Fix formatting --- contrib/kafka/README.md | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/contrib/kafka/README.md b/contrib/kafka/README.md index 386072317f..40b6c00ddf 100644 --- a/contrib/kafka/README.md +++ b/contrib/kafka/README.md @@ -4,26 +4,28 @@ KafkaIO provides unbounded sources and sinks for [Kafka](https://www.firebase.co topics. Kafka version 0.9 and above are supported. ## Basic Usage - * Read from a topic with 8 byte long keys and string values: - ```java - PCollection> kafkaRecords = - pipeline - .applY(KafkaIO.read() - .withBootstrapServers("broker_1:9092,broker_2:9092") - .withTopics(ImmutableList.of("topic_a")) - .withKeyCoder(BigEndianLongCoder.of()) - .withValueCoder(StringUtf8Coder.of()) - .withoutMetadata() - ); - ``` - * Write the same PCollection to a Kafka topic: - ```java - kafkaRecords.apply(KafkaIO.write() + +* Read from a topic with 8 byte long keys and string values: +```java + PCollection> kafkaRecords = + pipeline + .applY(KafkaIO.read() .withBootstrapServers("broker_1:9092,broker_2:9092") - .withTopic("results") + .withTopics(ImmutableList.of("topic_a")) .withKeyCoder(BigEndianLongCoder.of()) .withValueCoder(StringUtf8Coder.of()) - ``` + .withoutMetadata() + ); +``` + +* Write the same PCollection to a Kafka topic: +```java + kafkaRecords.apply(KafkaIO.write() + .withBootstrapServers("broker_1:9092,broker_2:9092") + .withTopic("results") + .withKeyCoder(BigEndianLongCoder.of()) + .withValueCoder(StringUtf8Coder.of()) +``` Please see JavaDoc for KafkaIO in [KafkaIO.java](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/contrib/kafka/src/main/java/com/google/cloud/dataflow/contrib/kafka/KafkaIO.java#L100) From 40d174f955e3f999b35388deea47fcd6c250c273 Mon Sep 17 00:00:00 2001 From: Raghu Angadi Date: Mon, 9 Jan 2017 15:04:07 -0800 Subject: [PATCH 684/751] review comments --- contrib/kafka/README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/contrib/kafka/README.md b/contrib/kafka/README.md index 40b6c00ddf..a84a493a03 100644 --- a/contrib/kafka/README.md +++ b/contrib/kafka/README.md @@ -1,7 +1,7 @@ # KafkaIO : Dataflow Unbounded Source and Sink for Kafka Topics -KafkaIO provides unbounded sources and sinks for [Kafka](https://www.firebase.com/) -topics. Kafka version 0.9 and above are supported. +KafkaIO provides unbounded source and sink for [Kafka](http://kafka.apache.org/) +topics. Kafka versions 0.9 and above are supported. ## Basic Usage @@ -9,7 +9,7 @@ topics. Kafka version 0.9 and above are supported. ```java PCollection> kafkaRecords = pipeline - .applY(KafkaIO.read() + .apply(KafkaIO.read() .withBootstrapServers("broker_1:9092,broker_2:9092") .withTopics(ImmutableList.of("topic_a")) .withKeyCoder(BigEndianLongCoder.of()) @@ -25,6 +25,7 @@ topics. Kafka version 0.9 and above are supported. .withTopic("results") .withKeyCoder(BigEndianLongCoder.of()) .withValueCoder(StringUtf8Coder.of()) + ); ``` Please see JavaDoc for KafkaIO in From efd33cc43061e54d8fe1e16415157de21b904d90 Mon Sep 17 00:00:00 2001 From: igorbernstein2 Date: Thu, 26 Jan 2017 14:57:48 -0500 Subject: [PATCH 685/751] =?UTF-8?q?Fix=20HadoopFileSource=E2=80=99s=20spli?= =?UTF-8?q?t=20size=20estimate=20(#534)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix HadoopFileSource’s split size estimate * Properly set interrupted state --- .../contrib/hadoop/HadoopFileSource.java | 11 ++++++++- .../contrib/hadoop/HadoopFileSourceTest.java | 23 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java index e8981d2d6a..cffc475d71 100644 --- a/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java +++ b/contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java @@ -239,12 +239,21 @@ private Coder getDefaultCoder(Class c) { public long getEstimatedSizeBytes(PipelineOptions options) { long size = 0; try { + // If this source represents a split from splitIntoBundles, then return the size of the split, + // rather then the entire input + if (serializableSplit != null) { + return serializableSplit.getSplit().getLength(); + } + Job job = Job.getInstance(); // new instance for (FileStatus st : listStatus(createFormat(job), job)) { size += st.getLen(); } } catch (IOException | NoSuchMethodException | InvocationTargetException - | IllegalAccessException | InstantiationException e) { + | IllegalAccessException | InstantiationException) { + // ignore, and return 0 + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // ignore, and return 0 } return size; diff --git a/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java b/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java index cef3c08348..eac54a1e31 100644 --- a/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java +++ b/contrib/hadoop/src/test/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSourceTest.java @@ -152,6 +152,29 @@ public void testSplits() throws Exception { assertTrue(nonEmptySplits > 2); } + @Test + public void testSplitEstimatedSize() throws Exception { + PipelineOptions options = PipelineOptionsFactory.create(); + + List> expectedResults = createRandomRecords(3, 10000, 0); + File file = createFileWithData("tmp.avro", expectedResults); + + HadoopFileSource source = HadoopFileSource.from( + file.toString(), SequenceFileInputFormat.class, IntWritable.class, Text.class + ); + + long originalSize = source.getEstimatedSizeBytes(options); + long splitTotalSize = 0; + List>> splits = source.splitIntoBundles( + SequenceFile.SYNC_INTERVAL, options + ); + for (BoundedSource> splitSource : splits) { + splitTotalSize += splitSource.getEstimatedSizeBytes(options); + } + // Assert that the estimated size of the whole is the sum of its parts + assertEquals(originalSize, splitTotalSize); + } + private File createFileWithData(String filename, List> records) throws IOException { File tmpFile = tmpFolder.newFile(filename); From dbe464440011decfc6d1a11ff6af9cc7b5ee3b68 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 30 Jan 2017 12:25:27 -0800 Subject: [PATCH 686/751] BigQuery: fix an issue with option propagation and refactor to future-proof * We created a helper in BigQueryIO to create a JobConfigurationQuery capturing all options, but we had not yet propagated this cleanup into the Services abstraction or helper classes. Refactor BigQueryServices and BigQueryTableRowIterator to propagate the same configuration. Adds a new deprecated constructor to BigQueryTableRowIterator for backwards-compatibility. This fixes GoogleCloudPlatform/DataflowJavaSDK#539. --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 10 ++- .../dataflow/sdk/util/BigQueryServices.java | 3 +- .../sdk/util/BigQueryServicesImpl.java | 17 ++--- .../sdk/util/BigQueryTableRowIterator.java | 67 ++++++++++--------- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 8 +-- 5 files changed, 52 insertions(+), 53 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index ace18eff5e..3472a8afed 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1075,7 +1075,7 @@ public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { public BoundedReader createReader(PipelineOptions options) throws IOException { BigQueryOptions bqOptions = options.as(BigQueryOptions.class); return new BigQueryReader(this, bqServices.getReaderFromQuery( - bqOptions, query.get(), executingProject.get(), flattenResults, useLegacySql)); + bqOptions, createBasicQueryConfig(), executingProject.get())); } @Override @@ -1152,11 +1152,12 @@ private void executeQuery( .setProjectId(executingProject) .setJobId(jobId); + // When changing options here, consider whether to change the defaults from + // #createBasicQueryConfig instead. JobConfigurationQuery queryConfig = createBasicQueryConfig() .setAllowLargeResults(true) .setCreateDisposition("CREATE_IF_NEEDED") .setDestinationTable(destinationTable) - .setPriority("BATCH") .setWriteDisposition("WRITE_EMPTY"); jobService.startQueryJob(jobRef, queryConfig); @@ -1167,9 +1168,12 @@ private void executeQuery( } private JobConfigurationQuery createBasicQueryConfig() { + // Due to deprecated functionality, if this function is updated + // then the similar code in BigQueryTableRowIterator#fromQuery should be updated. return new JobConfigurationQuery() - .setQuery(query.get()) .setFlattenResults(flattenResults) + .setPriority("BATCH") + .setQuery(query.get()) .setUseLegacySql(useLegacySql); } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java index ec96009494..df247629f5 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -58,8 +58,7 @@ public interface BigQueryServices extends Serializable { * Returns a real, mock, or fake {@link BigQueryJsonReader} to query tables. */ BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten, - @Nullable Boolean useLegacySql); + BigQueryOptions bqOptions, JobConfigurationQuery queryConfig, String projectId); /** * An interface for the Cloud BigQuery load service. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index 1a37e01375..af2ed9e73b 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -39,14 +39,11 @@ import com.google.cloud.dataflow.sdk.options.BigQueryOptions; import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; - import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.NoSuchElementException; - import javax.annotation.Nullable; /** @@ -83,9 +80,8 @@ public BigQueryJsonReader getReaderFromTable(BigQueryOptions bqOptions, TableRef @Override public BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten, - @Nullable Boolean useLegacySql) { - return BigQueryJsonReaderImpl.fromQuery(bqOptions, query, projectId, flatten, useLegacySql); + BigQueryOptions bqOptions, JobConfigurationQuery queryConfig, String projectId) { + return BigQueryJsonReaderImpl.fromQuery(bqOptions, queryConfig, projectId); } @VisibleForTesting @@ -521,14 +517,11 @@ private BigQueryJsonReaderImpl(BigQueryTableRowIterator iterator) { private static BigQueryJsonReader fromQuery( BigQueryOptions bqOptions, - String query, - String projectId, - @Nullable Boolean flattenResults, - @Nullable Boolean useLegacySql) { + JobConfigurationQuery queryConfig, + String projectId) { return new BigQueryJsonReaderImpl( BigQueryTableRowIterator.fromQuery( - query, projectId, Transport.newBigQueryClient(bqOptions).build(), flattenResults, - useLegacySql)); + queryConfig, projectId, Transport.newBigQueryClient(bqOptions).build())); } private static BigQueryJsonReader fromTable( diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 8f4ff793dc..63bd025099 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -46,11 +46,9 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.Uninterruptibles; - import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.Collection; import java.util.Collections; @@ -61,7 +59,6 @@ import java.util.Objects; import java.util.Random; import java.util.concurrent.TimeUnit; - import javax.annotation.Nullable; /** @@ -73,6 +70,7 @@ public class BigQueryTableRowIterator implements AutoCloseable { @Nullable private TableReference ref; @Nullable private final String projectId; @Nullable private TableSchema schema; + @Nullable private final JobConfigurationQuery queryConfig; private final Bigquery client; private String pageToken; private Iterator iteratorOverCurrentBatch; @@ -89,25 +87,18 @@ public class BigQueryTableRowIterator implements AutoCloseable { // following interval to check the status of query execution job private static final Duration QUERY_COMPLETION_POLL_TIME = Duration.standardSeconds(1); - private final String query; - // Whether to flatten query results. - private final boolean flattenResults; - // Whether to use the BigQuery legacy SQL dialect.. - private final boolean useLegacySql; // Temporary dataset used to store query results. private String temporaryDatasetId = null; // Temporary table used to store query results. private String temporaryTableId = null; private BigQueryTableRowIterator( - @Nullable TableReference ref, @Nullable String query, @Nullable String projectId, - Bigquery client, boolean flattenResults, boolean useLegacySql) { + @Nullable TableReference ref, @Nullable JobConfigurationQuery queryConfig, + @Nullable String projectId, Bigquery client) { this.ref = ref; - this.query = query; + this.queryConfig = queryConfig; this.projectId = projectId; this.client = checkNotNull(client, "client"); - this.flattenResults = flattenResults; - this.useLegacySql = useLegacySql; } /** @@ -116,7 +107,7 @@ private BigQueryTableRowIterator( public static BigQueryTableRowIterator fromTable(TableReference ref, Bigquery client) { checkNotNull(ref, "ref"); checkNotNull(client, "client"); - return new BigQueryTableRowIterator(ref, null, ref.getProjectId(), client, true, true); + return new BigQueryTableRowIterator(ref, null, ref.getProjectId(), client); } /** @@ -135,15 +126,31 @@ public static BigQueryTableRowIterator fromQuery( * Constructs a {@code BigQueryTableRowIterator} that reads from the results of executing the * specified query in the specified project. */ + @Deprecated public static BigQueryTableRowIterator fromQuery( String query, String projectId, Bigquery client, @Nullable Boolean flattenResults, @Nullable Boolean useLegacySql) { checkNotNull(query, "query"); checkNotNull(projectId, "projectId"); checkNotNull(client, "client"); - return new BigQueryTableRowIterator(null, query, projectId, client, - MoreObjects.firstNonNull(flattenResults, Boolean.TRUE), - MoreObjects.firstNonNull(useLegacySql, Boolean.TRUE)); + JobConfigurationQuery queryConfig = new JobConfigurationQuery() + .setFlattenResults(MoreObjects.firstNonNull(flattenResults, Boolean.TRUE)) + .setPriority("BATCH") + .setQuery(query) + .setUseLegacySql(MoreObjects.firstNonNull(useLegacySql, Boolean.TRUE)); + return new BigQueryTableRowIterator(null, queryConfig, projectId, client); + } + + /** + * Constructs a {@code BigQueryTableRowIterator} that reads from the results of executing the + * specified query in the specified project. + */ + public static BigQueryTableRowIterator fromQuery( + JobConfigurationQuery queryConfig, String projectId, Bigquery client) { + checkNotNull(queryConfig, "queryConfig"); + checkNotNull(projectId, "projectId"); + checkNotNull(client, "client"); + return new BigQueryTableRowIterator(null, queryConfig, projectId, client); } /** @@ -151,7 +158,7 @@ public static BigQueryTableRowIterator fromQuery( * @throws IOException on failure */ public void open() throws IOException, InterruptedException { - if (query != null) { + if (queryConfig != null) { ref = executeQueryAndWaitForCompletion(); } // Get table schema. @@ -401,15 +408,17 @@ private void deleteDataset(String datasetId) throws IOException, InterruptedExce */ private TableReference executeQueryAndWaitForCompletion() throws IOException, InterruptedException { + checkState(projectId != null, "Cannot dryRun a query in unknown (null) project"); + checkState(queryConfig != null, "Cannot dryRun a null query"); // Dry run query to get source table location Job dryRunJob = new Job() .setConfiguration(new JobConfiguration() - .setQuery(new JobConfigurationQuery() - .setQuery(query)) + .setQuery(queryConfig) .setDryRun(true)); JobStatistics jobStats = executeWithBackOff( client.jobs().insert(projectId, dryRunJob), - String.format("Error when trying to dry run query %s.", query)).getStatistics(); + String.format("Error when trying to dry run query %s.", + queryConfig.toPrettyString())).getStatistics(); // Let BigQuery to pick default location if the query does not read any tables. String location = null; @@ -428,14 +437,8 @@ private TableReference executeQueryAndWaitForCompletion() createDataset(temporaryDatasetId, location); Job job = new Job(); JobConfiguration config = new JobConfiguration(); - JobConfigurationQuery queryConfig = new JobConfigurationQuery(); config.setQuery(queryConfig); job.setConfiguration(config); - queryConfig.setQuery(query); - queryConfig.setAllowLargeResults(true); - queryConfig.setFlattenResults(flattenResults); - queryConfig.setUseLegacySql(useLegacySql); - TableReference destinationTable = new TableReference(); destinationTable.setProjectId(projectId); @@ -445,13 +448,15 @@ private TableReference executeQueryAndWaitForCompletion() Job queryJob = executeWithBackOff( client.jobs().insert(projectId, job), - String.format("Error when trying to execute the job for query %s.", query)); + String.format("Error when trying to execute the job for query %s.", + queryConfig.toPrettyString())); JobReference jobId = queryJob.getJobReference(); while (true) { Job pollJob = executeWithBackOff( client.jobs().get(projectId, jobId.getJobId()), - String.format("Error when trying to get status of the job for query %s.", query)); + String.format("Error when trying to get status of the job for query %s.", + queryConfig.toPrettyString())); JobStatus status = pollJob.getStatus(); if (status.getState().equals("DONE")) { // Job is DONE, but did not necessarily succeed. @@ -461,7 +466,9 @@ private TableReference executeQueryAndWaitForCompletion() } else { // There will be no temporary table to delete, so null out the reference. temporaryTableId = null; - throw new IOException("Executing query " + query + " failed: " + error.getMessage()); + throw new IOException( + String.format("Executing query %s failed: %s", + queryConfig.toPrettyString(), error.getMessage())); } } Uninterruptibles.sleepUninterruptibly( diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index a5bddec315..61356e18d0 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -106,7 +106,6 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; - import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Assert; @@ -122,7 +121,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; - import java.io.File; import java.io.FileFilter; import java.io.IOException; @@ -135,8 +133,6 @@ import java.util.NoSuchElementException; import java.util.Set; -import javax.annotation.Nullable; - /** * Tests for BigQueryIO. */ @@ -187,8 +183,7 @@ public BigQueryJsonReader getReaderFromTable( @Override public BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten, - @Nullable Boolean useLegacySql) { + BigQueryOptions bqOptions, JobConfigurationQuery queryConfig, String projectId) { return new FakeBigQueryReader(jsonTableRowReturns); } @@ -1749,3 +1744,4 @@ public boolean accept(File pathname) { }}).length); } } + From b4e391ee3fd3fd7cbd4b7e499601ae201f6dcf6d Mon Sep 17 00:00:00 2001 From: Eugene Hlyzov Date: Mon, 30 Jan 2017 23:45:34 +0300 Subject: [PATCH 687/751] [BEAM-359] Treat erased type variables as non-deterministic in AvroCoder (#531) --- .../cloud/dataflow/sdk/coders/AvroCoder.java | 9 +++++-- .../dataflow/sdk/coders/AvroCoderTest.java | 26 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java index c5aa029531..d85eb9b937 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/AvroCoder.java @@ -474,6 +474,10 @@ private void doCheck(String context, TypeDescriptor type, Schema schema) { checkMap(context, type, schema); break; case RECORD: + if (!(type.getType() instanceof Class)) { + reportError(context, "Cannot determine type from generic %s due to erasure", type); + return; + } checkRecord(type, schema); break; case UNION: @@ -694,7 +698,8 @@ private void checkArray(String context, TypeDescriptor type, Schema schema) { * Extract a field from a class. We need to look at the declared fields so that we can * see private fields. We may need to walk up to the parent to get classes from the parent. */ - private static Field getField(Class clazz, String name) { + private static Field getField(Class originalClazz, String name) { + Class clazz = originalClazz; while (clazz != null) { for (Field field : clazz.getDeclaredFields()) { AvroName avroName = field.getAnnotation(AvroName.class); @@ -708,7 +713,7 @@ private static Field getField(Class clazz, String name) { } throw new IllegalArgumentException( - "Unable to get field " + name + " from class " + clazz); + "Unable to get field " + name + " from class " + originalClazz); } } } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java index 3ed055bc4a..d6a2a172c9 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/coders/AvroCoderTest.java @@ -751,4 +751,30 @@ public int hashCode() { return Objects.hash(getClass(), onlySomeTypesAllowed); } } + + @Test + public void testAvroCoderForGenerics() throws Exception { + Schema fooSchema = AvroCoder.of(Foo.class).getSchema(); + Schema schema = new Schema.Parser().parse("{" + + "\"type\":\"record\"," + + "\"name\":\"SomeGeneric\"," + + "\"namespace\":\"ns\"," + + "\"fields\":[" + + " {\"name\":\"foo\", \"type\":" + fooSchema.toString() + "}" + + "]}"); + @SuppressWarnings("rawtypes") + AvroCoder coder = AvroCoder.of(SomeGeneric.class, schema); + + assertNonDeterministic(coder, + reasonField(SomeGeneric.class, "foo", "erasure")); + } + + private static class SomeGeneric { + @SuppressWarnings("unused") + private T foo; + } + private static class Foo { + @SuppressWarnings("unused") + String id; + } } From 502f99f6dfb233b2681ea6be55b8f63d900c4e67 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 30 Jan 2017 14:20:15 -0800 Subject: [PATCH 688/751] fixups --- .../sdk/util/BigQueryTableRowIterator.java | 1 + .../util/BigQueryTableRowIteratorTest.java | 37 ++++++++++--------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index 63bd025099..a518032228 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -445,6 +445,7 @@ private TableReference executeQueryAndWaitForCompletion() destinationTable.setDatasetId(temporaryDatasetId); destinationTable.setTableId(temporaryTableId); queryConfig.setDestinationTable(destinationTable); + queryConfig.setAllowLargeResults(Boolean.TRUE); Job queryJob = executeWithBackOff( client.jobs().insert(projectId, job), diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java index d6ac5b36ba..94d858aebb 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIteratorTest.java @@ -258,14 +258,18 @@ public void testReadFromQueryNoTables() throws IOException, InterruptedException // Mock job polling. JobStatus status = new JobStatus().setState("DONE"); - TableReference tableRef = - new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); - JobConfigurationQuery queryConfig = new JobConfigurationQuery().setDestinationTable(tableRef); + JobConfigurationQuery resultQueryConfig = + new JobConfigurationQuery().setDestinationTable( + new TableReference() + .setProjectId("project") + .setDatasetId("tempdataset") + .setTableId("temptable") + ); Job getJob = new Job() .setJobReference(new JobReference()) .setStatus(status) - .setConfiguration(new JobConfiguration().setQuery(queryConfig)); + .setConfiguration(new JobConfiguration().setQuery(resultQueryConfig)); when(mockJobsGet.execute()).thenReturn(getJob); // Mock table schema fetch. @@ -281,8 +285,9 @@ public void testReadFromQueryNoTables() throws IOException, InterruptedException String query = String.format( "SELECT \"Arthur\" as name, 42 as count, \"%s\" as photo", photoBytesEncoded); + JobConfigurationQuery queryConfig = new JobConfigurationQuery().setQuery(query); try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null, null)) { + BigQueryTableRowIterator.fromQuery(queryConfig, "project", mockClient)) { iterator.open(); assertTrue(iterator.advance()); TableRow row = iterator.getCurrent(); @@ -317,7 +322,7 @@ public void testReadFromQueryNoTables() throws IOException, InterruptedException verify(mockTablesDelete).execute(); // Table data read. verify(mockClient).tabledata(); - verify(mockTabledata).list("project", "dataset", "table"); + verify(mockTabledata).list("project", "tempdataset", "temptable"); verify(mockTabledataList).execute(); } @@ -334,18 +339,16 @@ public void testQueryFailed() throws IOException { when(mockJobsInsert.execute()).thenThrow(exception, exception, exception, exception); String query = "NOT A QUERY"; + JobConfigurationQuery queryConfig = new JobConfigurationQuery().setQuery(query); try (BigQueryTableRowIterator iterator = - BigQueryTableRowIterator.fromQuery(query, "project", mockClient, null, null)) { - - try { - iterator.open(); - fail(); - } catch (Exception expected) { - // Verify message explains cause and reports the query. - assertThat(expected.getMessage(), containsString("Error")); - assertThat(expected.getMessage(), containsString(query)); - assertThat(expected.getCause().getMessage(), containsString(errorReason)); - } + BigQueryTableRowIterator.fromQuery(queryConfig, "project", mockClient)) { + iterator.open(); + fail(); + } catch (Exception expected) { + // Verify message explains cause and reports the query. + assertThat(expected.getMessage(), containsString("Error")); + assertThat(expected.getMessage(), containsString(query)); + assertThat(expected.getCause().getMessage(), containsString(errorReason)); } // Job inserted to run the query, then polled once. From 254180dc87b182b63c6cbfaf8036bf26744686fd Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Thu, 2 Feb 2017 13:13:08 -0800 Subject: [PATCH 689/751] Upgrade to Apache Beam, version 0.5.0 This is based on the release candidate #2, currenly being considered as the release. --- .../resources/archetype-resources/pom.xml | 10 +++---- .../src/main/java/DebuggingWordCount.java | 4 +-- .../src/main/java/WordCount.java | 2 +- .../src/test/java/WordCountTest.java | 7 +++-- .../resources/archetype-resources/pom.xml | 6 ++-- .../projects/basic/reference/pom.xml | 6 ++-- pom.xml | 28 ++++++++++++++++++- 7 files changed, 45 insertions(+), 18 deletions(-) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 20e89f3064..c5e16cd789 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -48,7 +48,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.3 + 3.5.1 ${targetPlatform} ${targetPlatform} @@ -90,7 +90,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18.1 + 2.19.1 all 4 @@ -100,7 +100,7 @@ org.apache.maven.surefire surefire-junit47 - 2.18.1 + 2.19.1 @@ -201,7 +201,7 @@ org.slf4j slf4j-api - 1.7.7 + 1.7.14 @@ -223,7 +223,7 @@ junit junit - 4.11 + 4.12 diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java index 99ae79687c..dd9b91decc 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java @@ -95,9 +95,9 @@ public FilterTextFn(String pattern) { * in a dashboard, etc. */ private final Aggregator matchedWords = - createAggregator("matchedWords", new Sum.SumLongFn()); + createAggregator("matchedWords", Sum.ofLongs()); private final Aggregator unmatchedWords = - createAggregator("umatchedWords", new Sum.SumLongFn()); + createAggregator("unmatchedWords", Sum.ofLongs()); @ProcessElement public void processElement(ProcessContext c) { diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java index 634dea1a0a..b3ef26c493 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -87,7 +87,7 @@ public class WordCount { */ static class ExtractWordsFn extends DoFn { private final Aggregator emptyLines = - createAggregator("emptyLines", new Sum.SumLongFn()); + createAggregator("emptyLines", Sum.ofLongs()); @ProcessElement public void processElement(ProcessContext c) { diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java index e86c2aac96..e9621032e5 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java @@ -22,7 +22,6 @@ import ${package}.WordCount.CountWords; import ${package}.WordCount.ExtractWordsFn; import ${package}.WordCount.FormatAsTextFn; -import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.RunnableOnService; @@ -34,6 +33,7 @@ import org.apache.beam.sdk.values.PCollection; import org.hamcrest.CoreMatchers; import org.junit.Assert; +import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; @@ -68,12 +68,13 @@ public void testExtractWordsFn() throws Exception { static final String[] COUNTS_ARRAY = new String[] { "hi: 5", "there: 1", "sue: 2", "bob: 2"}; + @Rule + public TestPipeline p = TestPipeline.create(); + /** Example test that tests a PTransform by using an in-memory input and inspecting the output. */ @Test @Category(RunnableOnService.class) public void testCountWords() throws Exception { - Pipeline p = TestPipeline.create(); - PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); PCollection output = input.apply(new CountWords()) diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index 01e9aa951b..a73e9db9ed 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -48,7 +48,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.3 + 3.5.1 ${targetPlatform} ${targetPlatform} @@ -81,12 +81,12 @@ org.slf4j slf4j-api - 1.7.7 + 1.7.14 org.slf4j slf4j-jdk14 - 1.7.7 + 1.7.14 diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index 5530617bfe..ea55b72c91 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -48,7 +48,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.3 + 3.5.1 1.7 1.7 @@ -81,12 +81,12 @@ org.slf4j slf4j-api - 1.7.7 + 1.7.14 org.slf4j slf4j-jdk14 - 1.7.7 + 1.7.14 diff --git a/pom.xml b/pom.xml index ef65d33de6..0ee36a4c19 100644 --- a/pom.xml +++ b/pom.xml @@ -68,6 +68,32 @@ + + + apache.staging + Apache Software Foundation Staging Repository + https://repository.apache.org/content/repositories/staging/ + + true + + + false + + + + + apache.snapshots + Apache Software Foundation Snapshot Repository + https://repository.apache.org/content/repositories/snapshots/ + + false + + + true + + + + 3.0.3 @@ -77,7 +103,7 @@ ${maven.build.timestamp} yyyy-MM-dd HH:mm - 0.4.0 + 0.5.0 Google Cloud Dataflow SDK for Java ${project.version}-20170103 From 2ea5a233e1e895cf4f8babf9924d2b88cffbc5e9 Mon Sep 17 00:00:00 2001 From: Sam McVeety Date: Thu, 2 Feb 2017 13:24:23 -0800 Subject: [PATCH 690/751] Fix InProcessPipelineRunner to handle a null subscription --- .../dataflow/sdk/io/PubsubUnboundedSource.java | 11 ++++++----- .../dataflow/sdk/util/PubsubTestClient.java | 2 +- .../sdk/io/PubsubUnboundedSourceTest.java | 17 +++++++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java index 575fe39771..4da8ad1bad 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSource.java @@ -30,6 +30,7 @@ import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptions; import com.google.cloud.dataflow.sdk.options.ValueProvider; +import com.google.cloud.dataflow.sdk.options.ValueProvider.StaticValueProvider; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.Combine; import com.google.cloud.dataflow.sdk.transforms.DoFn; @@ -1290,6 +1291,7 @@ public String getIdLabel() { @Override public PCollection apply(PBegin input) { + ValueProvider subscriptionPath = subscription; if (subscription == null) { try { try (PubsubClient pubsubClient = @@ -1299,9 +1301,8 @@ public PCollection apply(PBegin input) { .as(DataflowPipelineOptions.class))) { checkState(project.isAccessible(), "createRandomSubscription must be called at runtime."); checkState(topic.isAccessible(), "createRandomSubscription must be called at runtime."); - SubscriptionPath subscriptionPath = - pubsubClient.createRandomSubscription( - project.get(), topic.get(), DEAULT_ACK_TIMEOUT_SEC); + subscriptionPath = StaticValueProvider.of(pubsubClient.createRandomSubscription( + project.get(), topic.get(), DEAULT_ACK_TIMEOUT_SEC)); LOG.warn("Created subscription {} to topic {}." + " Note this subscription WILL NOT be deleted when the pipeline terminates", subscription, topic); @@ -1314,7 +1315,7 @@ public PCollection apply(PBegin input) { return input.getPipeline().begin() .apply(Read.from(new PubsubSource(this))) .apply(ParDo.named("PubsubUnboundedSource.Stats") - .of(new StatsFn(pubsubFactory, subscription, - timestampLabel, idLabel))); + .of(new StatsFn(pubsubFactory, checkNotNull(subscriptionPath), + timestampLabel, idLabel))); } } diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java index c3a5a4e959..2f8a1db18c 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java @@ -372,7 +372,7 @@ public List listTopics(ProjectPath project) throws IOException { @Override public void createSubscription( TopicPath topic, SubscriptionPath subscription, int ackDeadlineSeconds) throws IOException { - throw new UnsupportedOperationException(); + return; } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java index f7e4f863de..dc48bab878 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java @@ -36,7 +36,10 @@ import com.google.cloud.dataflow.sdk.util.CoderUtils; import com.google.cloud.dataflow.sdk.util.PubsubClient; import com.google.cloud.dataflow.sdk.util.PubsubClient.IncomingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.OutgoingMessage; +import com.google.cloud.dataflow.sdk.util.PubsubClient.ProjectPath; import com.google.cloud.dataflow.sdk.util.PubsubClient.SubscriptionPath; +import com.google.cloud.dataflow.sdk.util.PubsubClient.TopicPath; import com.google.cloud.dataflow.sdk.util.PubsubTestClient; import com.google.cloud.dataflow.sdk.util.PubsubTestClient.PubsubTestClientFactory; @@ -60,8 +63,12 @@ */ @RunWith(JUnit4.class) public class PubsubUnboundedSourceTest { + private static final ProjectPath PROJECT = + PubsubClient.projectPathFromId("testProject"); private static final SubscriptionPath SUBSCRIPTION = PubsubClient.subscriptionPathFromName("testProject", "testSubscription"); + private static final TopicPath TOPIC = + PubsubClient.topicPathFromName("testProject", "testTopic"); private static final String DATA = "testData"; private static final long TIMESTAMP = 1234L; private static final long REQ_TIME = 6373L; @@ -320,4 +327,14 @@ public void readManyMessages() throws IOException { assertTrue(dataToMessageNum.isEmpty()); reader.close(); } + + @Test + public void testNullTopic() throws Exception { + factory = PubsubTestClient.createFactoryForPublish( + TOPIC, ImmutableList.of(), ImmutableList.of()); + TestPipeline p = TestPipeline.create(); + p.apply(new PubsubUnboundedSource<>( + clock, factory, StaticValueProvider.of(PROJECT), StaticValueProvider.of(TOPIC), + null, StringUtf8Coder.of(), TIMESTAMP_LABEL, ID_LABEL)); + } } From 669fa4308b7b61f0ef5fdde90c24e8e03bd31ed6 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Thu, 2 Feb 2017 13:38:43 -0800 Subject: [PATCH 691/751] [maven-release-plugin] prepare branch release-2.0.0-beta2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0ee36a4c19..004a9d1269 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.0.0-beta2 From a5d6a666b5432f309250b722e2c92c2c5531d3fc Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Thu, 2 Feb 2017 13:38:52 -0800 Subject: [PATCH 692/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index c987e94893..5bddc98bf4 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index a640cd4e5e..80d03bde09 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT ../../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index ec3bec3948..eee032d419 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index 004a9d1269..f24f902820 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.0.0-beta2 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index 511e4e0a73..b43e014a63 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT google-cloud-dataflow-java-sdk-all From 211b76d257a1481ae17cac89b9362d049c53e288 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Thu, 2 Feb 2017 13:41:58 -0800 Subject: [PATCH 693/751] Update archetype versioning after cutting 2.0.0-beta2 release branch --- .../examples/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/test/resources/projects/basic/reference/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index c5e16cd789..e1ce538e52 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -125,7 +125,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index a73e9db9ed..2ba93d7291 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -74,7 +74,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index ea55b72c91..1f06820c65 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -74,7 +74,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta2-SNAPSHOT + 2.0.0-beta3-SNAPSHOT From c827108b61a8b2145b325ec4636e64922e2695c7 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Thu, 2 Feb 2017 13:57:29 -0800 Subject: [PATCH 694/751] Update worker container image for 2.0.0-beta3-SNAPSHOT --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f24f902820..8af9511fc5 100644 --- a/pom.xml +++ b/pom.xml @@ -106,7 +106,7 @@ 0.5.0 Google Cloud Dataflow SDK for Java - ${project.version}-20170103 + ${project.version}-20170202 6 From 5625ffbf5ab9cfee4debbc38afc6a1fe5c69c892 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 6 Feb 2017 14:48:43 -0800 Subject: [PATCH 695/751] fixups --- .../main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index 3472a8afed..a6d9871287 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1158,6 +1158,7 @@ private void executeQuery( .setAllowLargeResults(true) .setCreateDisposition("CREATE_IF_NEEDED") .setDestinationTable(destinationTable) + .setPriority("BATCH") .setWriteDisposition("WRITE_EMPTY"); jobService.startQueryJob(jobRef, queryConfig); @@ -1172,7 +1173,6 @@ private JobConfigurationQuery createBasicQueryConfig() { // then the similar code in BigQueryTableRowIterator#fromQuery should be updated. return new JobConfigurationQuery() .setFlattenResults(flattenResults) - .setPriority("BATCH") .setQuery(query.get()) .setUseLegacySql(useLegacySql); } From 9c59d78112a51451eb9e6ae64a966b0ee2677fb8 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Mon, 6 Feb 2017 14:56:50 -0800 Subject: [PATCH 696/751] fixups --- .../java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 2 +- .../google/cloud/dataflow/sdk/util/BigQueryServices.java | 2 +- .../cloud/dataflow/sdk/util/BigQueryServicesImpl.java | 8 +++----- .../cloud/dataflow/sdk/util/BigQueryTableRowIterator.java | 4 ++-- .../com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java | 2 +- 5 files changed, 8 insertions(+), 10 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index a6d9871287..f844f49aed 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1075,7 +1075,7 @@ public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { public BoundedReader createReader(PipelineOptions options) throws IOException { BigQueryOptions bqOptions = options.as(BigQueryOptions.class); return new BigQueryReader(this, bqServices.getReaderFromQuery( - bqOptions, createBasicQueryConfig(), executingProject.get())); + bqOptions, executingProject.get(), createBasicQueryConfig())); } @Override diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java index df247629f5..43232f699a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServices.java @@ -58,7 +58,7 @@ public interface BigQueryServices extends Serializable { * Returns a real, mock, or fake {@link BigQueryJsonReader} to query tables. */ BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, JobConfigurationQuery queryConfig, String projectId); + BigQueryOptions bqOptions, String projectId, JobConfigurationQuery queryConfig); /** * An interface for the Cloud BigQuery load service. diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java index af2ed9e73b..84e718addd 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryServicesImpl.java @@ -80,8 +80,8 @@ public BigQueryJsonReader getReaderFromTable(BigQueryOptions bqOptions, TableRef @Override public BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, JobConfigurationQuery queryConfig, String projectId) { - return BigQueryJsonReaderImpl.fromQuery(bqOptions, queryConfig, projectId); + BigQueryOptions bqOptions, String projectId, JobConfigurationQuery queryConfig) { + return BigQueryJsonReaderImpl.fromQuery(bqOptions, projectId, queryConfig); } @VisibleForTesting @@ -516,9 +516,7 @@ private BigQueryJsonReaderImpl(BigQueryTableRowIterator iterator) { } private static BigQueryJsonReader fromQuery( - BigQueryOptions bqOptions, - JobConfigurationQuery queryConfig, - String projectId) { + BigQueryOptions bqOptions, String projectId, JobConfigurationQuery queryConfig) { return new BigQueryJsonReaderImpl( BigQueryTableRowIterator.fromQuery( queryConfig, projectId, Transport.newBigQueryClient(bqOptions).build())); diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java index a518032228..5ab5c897ed 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java @@ -408,8 +408,8 @@ private void deleteDataset(String datasetId) throws IOException, InterruptedExce */ private TableReference executeQueryAndWaitForCompletion() throws IOException, InterruptedException { - checkState(projectId != null, "Cannot dryRun a query in unknown (null) project"); - checkState(queryConfig != null, "Cannot dryRun a null query"); + checkState(projectId != null, "Unable to execute a query without a configured project id"); + checkState(queryConfig != null, "Unable to execute a query without a configured query"); // Dry run query to get source table location Job dryRunJob = new Job() .setConfiguration(new JobConfiguration() diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 61356e18d0..7f9d2e95ce 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -183,7 +183,7 @@ public BigQueryJsonReader getReaderFromTable( @Override public BigQueryJsonReader getReaderFromQuery( - BigQueryOptions bqOptions, JobConfigurationQuery queryConfig, String projectId) { + BigQueryOptions bqOptions, String projectId, JobConfigurationQuery queryConfig) { return new FakeBigQueryReader(jsonTableRowReturns); } From 20862aa7b9a690e8025ac5c1a6756eaffb05794c Mon Sep 17 00:00:00 2001 From: Sam McVeety Date: Fri, 10 Feb 2017 17:09:34 -0800 Subject: [PATCH 697/751] Fixups --- .../google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java index dc48bab878..06979315d8 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java @@ -329,7 +329,7 @@ public void readManyMessages() throws IOException { } @Test - public void testNullTopic() throws Exception { + public void testNullSubscription() throws Exception { factory = PubsubTestClient.createFactoryForPublish( TOPIC, ImmutableList.of(), ImmutableList.of()); TestPipeline p = TestPipeline.create(); From d7a70fef5f68074fd175dabce9870d55369a6dc0 Mon Sep 17 00:00:00 2001 From: Sam McVeety Date: Tue, 14 Feb 2017 16:57:33 -0800 Subject: [PATCH 698/751] Fixups --- .../dataflow/sdk/util/PubsubTestClient.java | 39 +++++++++++++++++++ .../sdk/io/PubsubUnboundedSourceTest.java | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java index 2f8a1db18c..01831218d4 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/util/PubsubTestClient.java @@ -107,6 +107,11 @@ private static class State { */ @Nullable Map ackDeadline; + + /** + * Whether a subscription has been created. + */ + boolean createdSubscription; } private static final State STATE = new State(); @@ -124,12 +129,40 @@ public static PubsubTestClientFactory createFactoryForPublish( final TopicPath expectedTopic, final Iterable expectedOutgoingMessages, final Iterable failingOutgoingMessages) { + return createFactoryForPublishInternal( + expectedTopic, expectedOutgoingMessages, failingOutgoingMessages, false); + } + + /** + * Return a factory for testing publishers. Only one factory may be in-flight at a time. + * The factory must be closed when the test is complete, at which point final validation will + * occur. Additionally, verify that createSubscription was called. + */ + public static PubsubTestClientFactory createFactoryForPublishVerifySubscription( + final TopicPath expectedTopic, + final Iterable expectedOutgoingMessages, + final Iterable failingOutgoingMessages) { + return createFactoryForPublishInternal( + expectedTopic, expectedOutgoingMessages, failingOutgoingMessages, true); + } + + /** + * Return a factory for testing publishers. Only one factory may be in-flight at a time. + * The factory must be closed when the test is complete, at which point final validation will + * occur. + */ + public static PubsubTestClientFactory createFactoryForPublishInternal( + final TopicPath expectedTopic, + final Iterable expectedOutgoingMessages, + final Iterable failingOutgoingMessages, + final boolean verifySubscriptionCreated) { synchronized (STATE) { checkState(!STATE.isActive, "Test still in flight"); STATE.expectedTopic = expectedTopic; STATE.remainingExpectedOutgoingMessages = Sets.newHashSet(expectedOutgoingMessages); STATE.remainingFailingOutgoingMessages = Sets.newHashSet(failingOutgoingMessages); STATE.isActive = true; + STATE.createdSubscription = false; } return new PubsubTestClientFactory() { @Override @@ -148,6 +181,9 @@ public String getKind() { @Override public void close() { synchronized (STATE) { + if (verifySubscriptionCreated) { + checkState(STATE.createdSubscription, "Did not call create subscription"); + } checkState(STATE.isActive, "No test still in flight"); checkState(STATE.remainingExpectedOutgoingMessages.isEmpty(), "Still waiting for %s messages to be published", @@ -372,6 +408,9 @@ public List listTopics(ProjectPath project) throws IOException { @Override public void createSubscription( TopicPath topic, SubscriptionPath subscription, int ackDeadlineSeconds) throws IOException { + synchronized (STATE) { + STATE.createdSubscription = true; + } return; } diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java index 06979315d8..65fdf737af 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/PubsubUnboundedSourceTest.java @@ -330,7 +330,7 @@ public void readManyMessages() throws IOException { @Test public void testNullSubscription() throws Exception { - factory = PubsubTestClient.createFactoryForPublish( + factory = PubsubTestClient.createFactoryForPublishVerifySubscription( TOPIC, ImmutableList.of(), ImmutableList.of()); TestPipeline p = TestPipeline.create(); p.apply(new PubsubUnboundedSource<>( From 4a9f16469fec467cf54efaa98a658413da231a00 Mon Sep 17 00:00:00 2001 From: gsgalloway Date: Wed, 1 Mar 2017 15:22:22 -0800 Subject: [PATCH 699/751] Small fix for BigtableIO.WriteOperation.finalize --- .../com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java index 3751d160f5..62f3b25d57 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/bigtable/BigtableIO.java @@ -976,9 +976,9 @@ public void initialize(PipelineOptions options) {} public void finalize(Iterable writerResults, PipelineOptions options) { long count = 0; for (Long value : writerResults) { - value += count; + count += value; } - logger.debug("Wrote {} elements to BigtableIO.Sink {}", sink); + logger.debug("Wrote {} elements to BigtableIO.Sink {}", count, sink); } @Override From e70747838e0af9c6d7ff0c6cb64177ba6d7ad2ea Mon Sep 17 00:00:00 2001 From: Jason Kuster Date: Fri, 17 Mar 2017 15:09:15 -0700 Subject: [PATCH 700/751] Upgrade to Apache Beam, version 0.6.0 Signed-off-by: Jason Kuster --- maven-archetypes/examples-java8/pom.xml | 79 ++++ .../META-INF/maven/archetype-metadata.xml | 38 ++ .../examples-java8/src/main/resources/NOTICE | 5 + .../resources/archetype-resources/pom.xml | 239 ++++++++++ .../src/main/java/DebuggingWordCount.java | 164 +++++++ .../src/main/java/MinimalWordCount.java | 118 +++++ .../src/main/java/MinimalWordCountJava8.java | 72 +++ .../src/main/java/WindowedWordCount.java | 242 ++++++++++ .../src/main/java/WordCount.java | 186 ++++++++ .../common/ExampleBigQueryTableOptions.java | 55 +++ .../src/main/java/common/ExampleOptions.java | 37 ++ ...mplePubsubTopicAndSubscriptionOptions.java | 45 ++ .../common/ExamplePubsubTopicOptions.java | 45 ++ .../src/main/java/common/ExampleUtils.java | 352 +++++++++++++++ .../java/common/WriteWindowedFilesDoFn.java | 77 ++++ .../main/java/complete/game/GameStats.java | 343 +++++++++++++++ .../java/complete/game/HourlyTeamScore.java | 196 +++++++++ .../main/java/complete/game/LeaderBoard.java | 286 ++++++++++++ .../src/main/java/complete/game/README.md | 131 ++++++ .../main/java/complete/game/UserScore.java | 243 ++++++++++ .../java/complete/game/injector/Injector.java | 414 ++++++++++++++++++ .../complete/game/injector/InjectorUtils.java | 100 +++++ .../injector/RetryHttpInitializerWrapper.java | 129 ++++++ .../complete/game/utils/WriteToBigQuery.java | 141 ++++++ .../game/utils/WriteWindowedToBigQuery.java | 71 +++ .../src/test/java/DebuggingWordCountTest.java | 52 +++ .../test/java/MinimalWordCountJava8Test.java | 104 +++++ .../src/test/java/WordCountTest.java | 86 ++++ .../java/complete/game/GameStatsTest.java | 81 ++++ .../complete/game/HourlyTeamScoreTest.java | 117 +++++ .../java/complete/game/LeaderBoardTest.java | 366 ++++++++++++++++ .../java/complete/game/UserScoreTest.java | 154 +++++++ .../projects/basic/archetype.properties | 19 + .../test/resources/projects/basic/goal.txt | 1 + maven-archetypes/examples/pom.xml | 38 +- .../resources/archetype-resources/pom.xml | 59 +-- .../projects/basic/archetype.properties | 2 +- maven-archetypes/pom.xml | 38 ++ maven-archetypes/starter/pom.xml | 44 +- .../resources/archetype-resources/pom.xml | 2 - .../projects/basic/archetype.properties | 2 +- .../projects/basic/reference/pom.xml | 4 +- pom.xml | 5 +- 43 files changed, 4940 insertions(+), 42 deletions(-) create mode 100644 maven-archetypes/examples-java8/pom.xml create mode 100644 maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml create mode 100644 maven-archetypes/examples-java8/src/main/resources/NOTICE create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/README.md create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java create mode 100644 maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties create mode 100644 maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt create mode 100644 maven-archetypes/pom.xml diff --git a/maven-archetypes/examples-java8/pom.xml b/maven-archetypes/examples-java8/pom.xml new file mode 100644 index 0000000000..3c19164933 --- /dev/null +++ b/maven-archetypes/examples-java8/pom.xml @@ -0,0 +1,79 @@ + + + + + 4.0.0 + + + com.google.cloud.dataflow + google-cloud-dataflow-java-archetypes-parent + 2.0.0-beta3-SNAPSHOT + ../pom.xml + + + google-cloud-dataflow-java-archetypes-examples-java8 + Google Cloud Dataflow SDK for Java - Java 8 Examples Archetype + Google Cloud Dataflow SDK for Java is a distribution of Apache + Beam designed to simplify usage of Apache Beam on Google Cloud Dataflow + service. This archetype creates a project containing all the example + pipelines targeting Java 8. + + maven-archetype + + + + + org.apache.maven.archetype + archetype-packaging + 2.4 + + + + + + + maven-archetype-plugin + 2.4 + + + org.apache.maven.shared + maven-invoker + 2.2 + + + + + + default-integration-test + install + + integration-test + + + + + + + + + diff --git a/maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100644 index 0000000000..326fdaa528 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,38 @@ + + + + + + + src/main/java + + **/*.java + + + + + src/test/java + + **/*.java + + + + diff --git a/maven-archetypes/examples-java8/src/main/resources/NOTICE b/maven-archetypes/examples-java8/src/main/resources/NOTICE new file mode 100644 index 0000000000..981fde5a9e --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/NOTICE @@ -0,0 +1,5 @@ +Google Cloud Dataflow SDK for Java +Copyright 2017, Google Inc. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml new file mode 100644 index 0000000000..0f5c2d13aa --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,239 @@ + + + + 4.0.0 + + ${groupId} + ${artifactId} + ${version} + + jar + + + UTF-8 + + + + + ossrh.snapshots + Sonatype OSS Repository Hosting + https://oss.sonatype.org/content/repositories/snapshots/ + + false + + + true + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + all + 4 + true + + + + org.apache.maven.surefire + surefire-junit47 + 2.19.1 + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.1 + + + package + + shade + + + ${project.artifactId}-bundled-${project.version} + + + *:* + + META-INF/LICENSE + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + false + + + + + + + + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-all + 2.0.0-beta3-SNAPSHOT + + + + + com.google.api-client + google-api-client + 1.22.0 + + + + com.google.guava + guava-jdk5 + + + + + + com.google.apis + google-api-services-bigquery + v2-rev295-1.22.0 + + + + com.google.guava + guava-jdk5 + + + + + + com.google.http-client + google-http-client + 1.22.0 + + + + com.google.guava + guava-jdk5 + + + + + + com.google.apis + google-api-services-pubsub + v1-rev10-1.22.0 + + + + com.google.guava + guava-jdk5 + + + + + + joda-time + joda-time + 2.4 + + + + com.google.guava + guava + 20.0 + + + + + org.slf4j + slf4j-api + 1.7.14 + + + + org.slf4j + slf4j-jdk14 + 1.7.14 + + runtime + + + + + org.hamcrest + hamcrest-all + 1.3 + + + + junit + junit + 4.12 + + + + org.mockito + mockito-all + 1.9.5 + test + + + diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java new file mode 100644 index 0000000000..dd9b91decc --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java @@ -0,0 +1,164 @@ +/* + * 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 ${package}; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.transforms.Aggregator; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * An example that verifies word counts in Shakespeare and includes Beam best practices. + * + *

              This class, {@link DebuggingWordCount}, is the third in a series of four successively more + * detailed 'word count' examples. You may first want to take a look at {@link MinimalWordCount} + * and {@link WordCount}. After you've looked at this example, then see the + * {@link WindowedWordCount} pipeline, for introduction of additional concepts. + * + *

              Basic concepts, also in the MinimalWordCount and WordCount examples: + * Reading text files; counting a PCollection; executing a Pipeline both locally + * and using a selected runner; defining DoFns. + * + *

              New Concepts: + *

              + *   1. Logging using SLF4J, even in a distributed environment
              + *   2. Creating a custom aggregator (runners have varying levels of support)
              + *   3. Testing your Pipeline via PAssert
              + * 
              + * + *

              To execute this pipeline locally, specify general pipeline configuration: + *

              {@code
              + *   --project=YOUR_PROJECT_ID
              + * }
              + * 
              + * + *

              To change the runner, specify: + *

              {@code
              + *   --runner=YOUR_SELECTED_RUNNER
              + * }
              + * 
              + * + *

              The input file defaults to a public data set containing the text of of King Lear, + * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. + * + */ +public class DebuggingWordCount { + /** A DoFn that filters for a specific key based upon a regular expression. */ + public static class FilterTextFn extends DoFn, KV> { + /** + * Concept #1: The logger below uses the fully qualified class name of FilterTextFn as the + * logger. Depending on your SLF4J configuration, log statements will likely be qualified by + * this name. + * + *

              Note that this is entirely standard SLF4J usage. Some runners may provide a default SLF4J + * configuration that is most appropriate for their logging integration. + */ + private static final Logger LOG = LoggerFactory.getLogger(FilterTextFn.class); + + private final Pattern filter; + public FilterTextFn(String pattern) { + filter = Pattern.compile(pattern); + } + + /** + * Concept #2: A custom aggregator can track values in your pipeline as it runs. Each + * runner provides varying levels of support for aggregators, and may expose them + * in a dashboard, etc. + */ + private final Aggregator matchedWords = + createAggregator("matchedWords", Sum.ofLongs()); + private final Aggregator unmatchedWords = + createAggregator("unmatchedWords", Sum.ofLongs()); + + @ProcessElement + public void processElement(ProcessContext c) { + if (filter.matcher(c.element().getKey()).matches()) { + // Log at the "DEBUG" level each element that we match. When executing this pipeline + // these log lines will appear only if the log level is set to "DEBUG" or lower. + LOG.debug("Matched: " + c.element().getKey()); + matchedWords.addValue(1L); + c.output(c.element()); + } else { + // Log at the "TRACE" level each element that is not matched. Different log levels + // can be used to control the verbosity of logging providing an effective mechanism + // to filter less important information. + LOG.trace("Did not match: " + c.element().getKey()); + unmatchedWords.addValue(1L); + } + } + } + + /** + * Options supported by {@link DebuggingWordCount}. + * + *

              Inherits standard configuration options and all options defined in + * {@link WordCount.WordCountOptions}. + */ + public interface WordCountOptions extends WordCount.WordCountOptions { + + @Description("Regex filter pattern to use in DebuggingWordCount. " + + "Only words matching this pattern will be counted.") + @Default.String("Flourish|stomach") + String getFilterPattern(); + void setFilterPattern(String value); + } + + public static void main(String[] args) { + WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() + .as(WordCountOptions.class); + Pipeline p = Pipeline.create(options); + + PCollection> filteredWords = + p.apply("ReadLines", TextIO.Read.from(options.getInputFile())) + .apply(new WordCount.CountWords()) + .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); + + /** + * Concept #3: PAssert is a set of convenient PTransforms in the style of + * Hamcrest's collection matchers that can be used when writing Pipeline level tests + * to validate the contents of PCollections. PAssert is best used in unit tests + * with small data sets but is demonstrated here as a teaching tool. + * + *

              Below we verify that the set of filtered words matches our expected counts. Note + * that PAssert does not provide any output and that successful completion of the + * Pipeline implies that the expectations were met. Learn more at + * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline on how to test + * your Pipeline and see {@link DebuggingWordCountTest} for an example unit test. + */ + List> expectedResults = Arrays.asList( + KV.of("Flourish", 3L), + KV.of("stomach", 1L)); + PAssert.that(filteredWords).containsInAnyOrder(expectedResults); + + p.run().waitUntilFinish(); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java new file mode 100644 index 0000000000..97bd8243b8 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java @@ -0,0 +1,118 @@ +/* + * 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 ${package}; + +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SimpleFunction; +import org.apache.beam.sdk.values.KV; + + +/** + * An example that counts words in Shakespeare. + * + *

              This class, {@link MinimalWordCount}, is the first in a series of four successively more + * detailed 'word count' examples. Here, for simplicity, we don't show any error-checking or + * argument processing, and focus on construction of the pipeline, which chains together the + * application of core transforms. + * + *

              Next, see the {@link WordCount} pipeline, then the {@link DebuggingWordCount}, and finally the + * {@link WindowedWordCount} pipeline, for more detailed examples that introduce additional + * concepts. + * + *

              Concepts: + * + *

              + *   1. Reading data from text files
              + *   2. Specifying 'inline' transforms
              + *   3. Counting items in a PCollection
              + *   4. Writing data to text files
              + * 
              + * + *

              No arguments are required to run this pipeline. It will be executed with the DirectRunner. You + * can see the results in the output files in your current working directory, with names like + * "wordcounts-00001-of-00005. When running on a distributed service, you would use an appropriate + * file service. + */ +public class MinimalWordCount { + + public static void main(String[] args) { + // Create a PipelineOptions object. This object lets us set various execution + // options for our pipeline, such as the runner you wish to use. This example + // will run with the DirectRunner by default, based on the class path configured + // in its dependencies. + PipelineOptions options = PipelineOptionsFactory.create(); + + // Create the Pipeline object with the options we defined above. + Pipeline p = Pipeline.create(options); + + // Apply the pipeline's transforms. + + // Concept #1: Apply a root transform to the pipeline; in this case, TextIO.Read to read a set + // of input text files. TextIO.Read returns a PCollection where each element is one line from + // the input text (a set of Shakespeare's texts). + + // This example reads a public data set consisting of the complete works of Shakespeare. + p.apply(TextIO.Read.from("gs://apache-beam-samples/shakespeare/*")) + + // Concept #2: Apply a ParDo transform to our PCollection of text lines. This ParDo invokes a + // DoFn (defined in-line) on each element that tokenizes the text line into individual words. + // The ParDo returns a PCollection, where each element is an individual word in + // Shakespeare's collected texts. + .apply("ExtractWords", ParDo.of(new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + for (String word : c.element().split("[^a-zA-Z']+")) { + if (!word.isEmpty()) { + c.output(word); + } + } + } + })) + + // Concept #3: Apply the Count transform to our PCollection of individual words. The Count + // transform returns a new PCollection of key/value pairs, where each key represents a unique + // word in the text. The associated value is the occurrence count for that word. + .apply(Count.perElement()) + + // Apply a MapElements transform that formats our PCollection of word counts into a printable + // string, suitable for writing to an output file. + .apply("FormatResults", MapElements.via(new SimpleFunction, String>() { + @Override + public String apply(KV input) { + return input.getKey() + ": " + input.getValue(); + } + })) + + // Concept #4: Apply a write transform, TextIO.Write, at the end of the pipeline. + // TextIO.Write writes the contents of a PCollection (in this case, our PCollection of + // formatted strings) to a series of text files. + // + // By default, it will write to a set of files with names like wordcount-00001-of-00005 + .apply(TextIO.Write.to("wordcounts")); + + // Run the pipeline. + p.run().waitUntilFinish(); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java new file mode 100644 index 0000000000..532ca352ff --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java @@ -0,0 +1,72 @@ +/* + * 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 ${package}; + +import java.util.Arrays; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.Filter; +import org.apache.beam.sdk.transforms.FlatMapElements; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.TypeDescriptors; + +/** + * An example that counts words in Shakespeare, using Java 8 language features. + * + *

              See {@link MinimalWordCount} for a comprehensive explanation. + */ +public class MinimalWordCountJava8 { + + public static void main(String[] args) { + PipelineOptions options = PipelineOptionsFactory.create(); + // In order to run your pipeline, you need to make following runner specific changes: + // + // CHANGE 1/3: Select a Beam runner, such as BlockingDataflowRunner + // or FlinkRunner. + // CHANGE 2/3: Specify runner-required options. + // For BlockingDataflowRunner, set project and temp location as follows: + // DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); + // dataflowOptions.setRunner(BlockingDataflowRunner.class); + // dataflowOptions.setProject("SET_YOUR_PROJECT_ID_HERE"); + // dataflowOptions.setTempLocation("gs://SET_YOUR_BUCKET_NAME_HERE/AND_TEMP_DIRECTORY"); + // For FlinkRunner, set the runner as follows. See {@code FlinkPipelineOptions} + // for more details. + // options.as(FlinkPipelineOptions.class) + // .setRunner(FlinkRunner.class); + + Pipeline p = Pipeline.create(options); + + p.apply(TextIO.Read.from("gs://apache-beam-samples/shakespeare/*")) + .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) + .withOutputType(TypeDescriptors.strings())) + .apply(Filter.by((String word) -> !word.isEmpty())) + .apply(Count.perElement()) + .apply(MapElements + .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue()) + .withOutputType(TypeDescriptors.strings())) + + // CHANGE 3/3: The Google Cloud Storage path is required for outputting the results to. + .apply(TextIO.Write.to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); + + p.run().waitUntilFinish(); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java new file mode 100644 index 0000000000..052d7b6a0e --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java @@ -0,0 +1,242 @@ +/* + * 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 ${package}; + +import java.io.IOException; +import java.util.concurrent.ThreadLocalRandom; +import ${package}.common.ExampleBigQueryTableOptions; +import ${package}.common.ExampleOptions; +import ${package}.common.WriteWindowedFilesDoFn; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.GroupByKey; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.FixedWindows; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.joda.time.Duration; +import org.joda.time.Instant; + + +/** + * An example that counts words in text, and can run over either unbounded or bounded input + * collections. + * + *

              This class, {@link WindowedWordCount}, is the last in a series of four successively more + * detailed 'word count' examples. First take a look at {@link MinimalWordCount}, + * {@link WordCount}, and {@link DebuggingWordCount}. + * + *

              Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples: + * Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally + * and using a selected runner; defining DoFns; creating a custom aggregator; + * user-defined PTransforms; defining PipelineOptions. + * + *

              New Concepts: + *

              + *   1. Unbounded and bounded pipeline input modes
              + *   2. Adding timestamps to data
              + *   3. Windowing
              + *   4. Re-using PTransforms over windowed PCollections
              + *   5. Accessing the window of an element
              + *   6. Writing data to per-window text files
              + * 
              + * + *

              By default, the examples will run with the {@code DirectRunner}. + * To change the runner, specify: + *

              {@code
              + *   --runner=YOUR_SELECTED_RUNNER
              + * }
              + * 
              + * See examples/java/README.md for instructions about how to configure different runners. + * + *

              To execute this pipeline locally, specify a local output file (if using the + * {@code DirectRunner}) or output prefix on a supported distributed file system. + *

              {@code
              + *   --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
              + * }
              + * + *

              The input file defaults to a public data set containing the text of of King Lear, + * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. + * + *

              By default, the pipeline will do fixed windowing, on 1-minute windows. You can + * change this interval by setting the {@code --windowSize} parameter, e.g. {@code --windowSize=10} + * for 10-minute windows. + * + *

              The example will try to cancel the pipeline on the signal to terminate the process (CTRL-C). + */ +public class WindowedWordCount { + static final int WINDOW_SIZE = 10; // Default window duration in minutes + /** + * Concept #2: A DoFn that sets the data element timestamp. This is a silly method, just for + * this example, for the bounded data case. + * + *

              Imagine that many ghosts of Shakespeare are all typing madly at the same time to recreate + * his masterworks. Each line of the corpus will get a random associated timestamp somewhere in a + * 2-hour period. + */ + static class AddTimestampFn extends DoFn { + private static final Duration RAND_RANGE = Duration.standardHours(1); + private final Instant minTimestamp; + private final Instant maxTimestamp; + + AddTimestampFn(Instant minTimestamp, Instant maxTimestamp) { + this.minTimestamp = minTimestamp; + this.maxTimestamp = maxTimestamp; + } + + @ProcessElement + public void processElement(ProcessContext c) { + Instant randomTimestamp = + new Instant( + ThreadLocalRandom.current() + .nextLong(minTimestamp.getMillis(), maxTimestamp.getMillis())); + + /** + * Concept #2: Set the data element with that timestamp. + */ + c.outputWithTimestamp(c.element(), new Instant(randomTimestamp)); + } + } + + /** A {@link DefaultValueFactory} that returns the current system time. */ + public static class DefaultToCurrentSystemTime implements DefaultValueFactory { + @Override + public Long create(PipelineOptions options) { + return System.currentTimeMillis(); + } + } + + /** A {@link DefaultValueFactory} that returns the minimum timestamp plus one hour. */ + public static class DefaultToMinTimestampPlusOneHour implements DefaultValueFactory { + @Override + public Long create(PipelineOptions options) { + return options.as(Options.class).getMinTimestampMillis() + + Duration.standardHours(1).getMillis(); + } + } + + /** + * Options for {@link WindowedWordCount}. + * + *

              Inherits standard example configuration options, which allow specification of the + * runner, as well as the {@link WordCount.WordCountOptions} support for + * specification of the input and output files. + */ + public interface Options extends WordCount.WordCountOptions, + ExampleOptions, ExampleBigQueryTableOptions { + @Description("Fixed window duration, in minutes") + @Default.Integer(WINDOW_SIZE) + Integer getWindowSize(); + void setWindowSize(Integer value); + + @Description("Minimum randomly assigned timestamp, in milliseconds-since-epoch") + @Default.InstanceFactory(DefaultToCurrentSystemTime.class) + Long getMinTimestampMillis(); + void setMinTimestampMillis(Long value); + + @Description("Maximum randomly assigned timestamp, in milliseconds-since-epoch") + @Default.InstanceFactory(DefaultToMinTimestampPlusOneHour.class) + Long getMaxTimestampMillis(); + void setMaxTimestampMillis(Long value); + } + + public static void main(String[] args) throws IOException { + Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + final String output = options.getOutput(); + final Duration windowSize = Duration.standardMinutes(options.getWindowSize()); + final Instant minTimestamp = new Instant(options.getMinTimestampMillis()); + final Instant maxTimestamp = new Instant(options.getMaxTimestampMillis()); + + Pipeline pipeline = Pipeline.create(options); + + /** + * Concept #1: the Beam SDK lets us run the same pipeline with either a bounded or + * unbounded input source. + */ + PCollection input = pipeline + /** Read from the GCS file. */ + .apply(TextIO.Read.from(options.getInputFile())) + // Concept #2: Add an element timestamp, using an artificial time just to show windowing. + // See AddTimestampFn for more detail on this. + .apply(ParDo.of(new AddTimestampFn(minTimestamp, maxTimestamp))); + + /** + * Concept #3: Window into fixed windows. The fixed window size for this example defaults to 1 + * minute (you can change this with a command-line option). See the documentation for more + * information on how fixed windows work, and for information on the other types of windowing + * available (e.g., sliding windows). + */ + PCollection windowedWords = + input.apply( + Window.into( + FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); + + /** + * Concept #4: Re-use our existing CountWords transform that does not have knowledge of + * windows over a PCollection containing windowed values. + */ + PCollection> wordCounts = windowedWords.apply(new WordCount.CountWords()); + + /** + * Concept #5: Customize the output format using windowing information + * + *

              At this point, the data is organized by window. We're writing text files and and have no + * late data, so for simplicity we can use the window as the key and {@link GroupByKey} to get + * one output file per window. (if we had late data this key would not be unique) + * + *

              To access the window in a {@link DoFn}, add a {@link BoundedWindow} parameter. This will + * be automatically detected and populated with the window for the current element. + */ + PCollection>> keyedByWindow = + wordCounts.apply( + ParDo.of( + new DoFn, KV>>() { + @ProcessElement + public void processElement(ProcessContext context, IntervalWindow window) { + context.output(KV.of(window, context.element())); + } + })); + + /** + * Concept #6: Format the results and write to a sharded file partitioned by window, using a + * simple ParDo operation. Because there may be failures followed by retries, the + * writes must be idempotent, but the details of writing to files is elided here. + */ + keyedByWindow + .apply(GroupByKey.>create()) + .apply(ParDo.of(new WriteWindowedFilesDoFn(output))); + + PipelineResult result = pipeline.run(); + try { + result.waitUntilFinish(); + } catch (Exception exc) { + result.cancel(); + } + } + +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java new file mode 100644 index 0000000000..b3ef26c493 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -0,0 +1,186 @@ +/* + * 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 ${package}; + +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.options.Validation.Required; +import org.apache.beam.sdk.transforms.Aggregator; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SimpleFunction; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; + +/** + * An example that counts words in Shakespeare and includes Beam best practices. + * + *

              This class, {@link WordCount}, is the second in a series of four successively more detailed + * 'word count' examples. You may first want to take a look at {@link MinimalWordCount}. + * After you've looked at this example, then see the {@link DebuggingWordCount} + * pipeline, for introduction of additional concepts. + * + *

              For a detailed walkthrough of this example, see + * + * http://beam.apache.org/use/walkthroughs/ + * + * + *

              Basic concepts, also in the MinimalWordCount example: + * Reading text files; counting a PCollection; writing to text files + * + *

              New Concepts: + *

              + *   1. Executing a Pipeline both locally and using the selected runner
              + *   2. Using ParDo with static DoFns defined out-of-line
              + *   3. Building a composite transform
              + *   4. Defining your own pipeline options
              + * 
              + * + *

              Concept #1: you can execute this pipeline either locally or using by selecting another runner. + * These are now command-line options and not hard-coded as they were in the MinimalWordCount + * example. + * + *

              To change the runner, specify: + *

              {@code
              + *   --runner=YOUR_SELECTED_RUNNER
              + * }
              + * 
              + * + *

              To execute this pipeline, specify a local output file (if using the + * {@code DirectRunner}) or output prefix on a supported distributed file system. + *

              {@code
              + *   --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
              + * }
              + * + *

              The input file defaults to a public data set containing the text of of King Lear, + * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. + */ +public class WordCount { + + /** + * Concept #2: You can make your pipeline assembly code less verbose by defining your DoFns + * statically out-of-line. This DoFn tokenizes lines of text into individual words; we pass it + * to a ParDo in the pipeline. + */ + static class ExtractWordsFn extends DoFn { + private final Aggregator emptyLines = + createAggregator("emptyLines", Sum.ofLongs()); + + @ProcessElement + public void processElement(ProcessContext c) { + if (c.element().trim().isEmpty()) { + emptyLines.addValue(1L); + } + + // Split the line into words. + String[] words = c.element().split("[^a-zA-Z']+"); + + // Output each word encountered into the output PCollection. + for (String word : words) { + if (!word.isEmpty()) { + c.output(word); + } + } + } + } + + /** A SimpleFunction that converts a Word and Count into a printable string. */ + public static class FormatAsTextFn extends SimpleFunction, String> { + @Override + public String apply(KV input) { + return input.getKey() + ": " + input.getValue(); + } + } + + /** + * A PTransform that converts a PCollection containing lines of text into a PCollection of + * formatted word counts. + * + *

              Concept #3: This is a custom composite transform that bundles two transforms (ParDo and + * Count) as a reusable PTransform subclass. Using composite transforms allows for easy reuse, + * modular testing, and an improved monitoring experience. + */ + public static class CountWords extends PTransform, + PCollection>> { + @Override + public PCollection> expand(PCollection lines) { + + // Convert lines of text into individual words. + PCollection words = lines.apply( + ParDo.of(new ExtractWordsFn())); + + // Count the number of times each word occurs. + PCollection> wordCounts = + words.apply(Count.perElement()); + + return wordCounts; + } + } + + /** + * Options supported by {@link WordCount}. + * + *

              Concept #4: Defining your own configuration options. Here, you can add your own arguments + * to be processed by the command-line parser, and specify default values for them. You can then + * access the options values in your pipeline code. + * + *

              Inherits standard configuration options. + */ + public interface WordCountOptions extends PipelineOptions { + + /** + * By default, this example reads from a public dataset containing the text of + * King Lear. Set this option to choose a different input file or glob. + */ + @Description("Path of the file to read from") + @Default.String("gs://apache-beam-samples/shakespeare/kinglear.txt") + String getInputFile(); + void setInputFile(String value); + + /** + * Set this required option to specify where to write the output. + */ + @Description("Path of the file to write to") + @Required + String getOutput(); + void setOutput(String value); + } + + public static void main(String[] args) { + WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() + .as(WordCountOptions.class); + Pipeline p = Pipeline.create(options); + + // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the + // static FormatAsTextFn() to the ParDo transform. + p.apply("ReadLines", TextIO.Read.from(options.getInputFile())) + .apply(new CountWords()) + .apply(MapElements.via(new FormatAsTextFn())) + .apply("WriteCounts", TextIO.Write.to(options.getOutput())); + + p.run().waitUntilFinish(); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java new file mode 100644 index 0000000000..6b51074f44 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java @@ -0,0 +1,55 @@ +/* + * 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 ${package}.common; + +import com.google.api.services.bigquery.model.TableSchema; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.GcpOptions; +import org.apache.beam.sdk.options.PipelineOptions; + +/** + * Options that can be used to configure BigQuery tables in Beam examples. + * The project defaults to the project being used to run the example. + */ +public interface ExampleBigQueryTableOptions extends GcpOptions { + @Description("BigQuery dataset name") + @Default.String("beam_examples") + String getBigQueryDataset(); + void setBigQueryDataset(String dataset); + + @Description("BigQuery table name") + @Default.InstanceFactory(BigQueryTableFactory.class) + String getBigQueryTable(); + void setBigQueryTable(String table); + + @Description("BigQuery table schema") + TableSchema getBigQuerySchema(); + void setBigQuerySchema(TableSchema schema); + + /** + * Returns the job name as the default BigQuery table name. + */ + class BigQueryTableFactory implements DefaultValueFactory { + @Override + public String create(PipelineOptions options) { + return options.getJobName().replace('-', '_'); + } + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java new file mode 100644 index 0000000000..90f935c3ce --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java @@ -0,0 +1,37 @@ +/* + * 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 ${package}.common; + +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptions; + +/** + * Options that can be used to configure the Beam examples. + */ +public interface ExampleOptions extends PipelineOptions { + @Description("Whether to keep jobs running after local process exit") + @Default.Boolean(false) + boolean getKeepJobsRunning(); + void setKeepJobsRunning(boolean keepJobsRunning); + + @Description("Number of workers to use when executing the injector pipeline") + @Default.Integer(1) + int getInjectorNumWorkers(); + void setInjectorNumWorkers(int numWorkers); +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java new file mode 100644 index 0000000000..daeb398f7f --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java @@ -0,0 +1,45 @@ +/* + * 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 ${package}.common; + +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.GcpOptions; +import org.apache.beam.sdk.options.PipelineOptions; + +/** + * Options that can be used to configure Pub/Sub topic/subscription in Beam examples. + */ +public interface ExamplePubsubTopicAndSubscriptionOptions extends ExamplePubsubTopicOptions { + @Description("Pub/Sub subscription") + @Default.InstanceFactory(PubsubSubscriptionFactory.class) + String getPubsubSubscription(); + void setPubsubSubscription(String subscription); + + /** + * Returns a default Pub/Sub subscription based on the project and the job names. + */ + class PubsubSubscriptionFactory implements DefaultValueFactory { + @Override + public String create(PipelineOptions options) { + return "projects/" + options.as(GcpOptions.class).getProject() + + "/subscriptions/" + options.getJobName(); + } + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java new file mode 100644 index 0000000000..936bff5675 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java @@ -0,0 +1,45 @@ +/* + * 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 ${package}.common; + +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.DefaultValueFactory; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.GcpOptions; +import org.apache.beam.sdk.options.PipelineOptions; + +/** + * Options that can be used to configure Pub/Sub topic in Beam examples. + */ +public interface ExamplePubsubTopicOptions extends GcpOptions { + @Description("Pub/Sub topic") + @Default.InstanceFactory(PubsubTopicFactory.class) + String getPubsubTopic(); + void setPubsubTopic(String topic); + + /** + * Returns a default Pub/Sub topic based on the project and the job names. + */ + class PubsubTopicFactory implements DefaultValueFactory { + @Override + public String create(PipelineOptions options) { + return "projects/" + options.as(GcpOptions.class).getProject() + + "/topics/" + options.getJobName(); + } + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java new file mode 100644 index 0000000000..570b3827b7 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java @@ -0,0 +1,352 @@ +/* + * 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 ${package}.common; + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; +import com.google.api.client.util.BackOff; +import com.google.api.client.util.BackOffUtils; +import com.google.api.client.util.Sleeper; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.Bigquery.Datasets; +import com.google.api.services.bigquery.Bigquery.Tables; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.api.services.pubsub.Pubsub; +import com.google.api.services.pubsub.model.Subscription; +import com.google.api.services.pubsub.model.Topic; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.common.util.concurrent.Uninterruptibles; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.options.BigQueryOptions; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PubsubOptions; +import org.apache.beam.sdk.util.FluentBackoff; +import org.apache.beam.sdk.util.Transport; +import org.joda.time.Duration; + +/** + * The utility class that sets up and tears down external resources, + * and cancels the streaming pipelines once the program terminates. + * + *

              It is used to run Beam examples. + */ +public class ExampleUtils { + + private static final int SC_NOT_FOUND = 404; + + private final PipelineOptions options; + private Bigquery bigQueryClient = null; + private Pubsub pubsubClient = null; + private Set pipelinesToCancel = Sets.newHashSet(); + private List pendingMessages = Lists.newArrayList(); + + /** + * Do resources and runner options setup. + */ + public ExampleUtils(PipelineOptions options) { + this.options = options; + } + + /** + * Sets up external resources that are required by the example, + * such as Pub/Sub topics and BigQuery tables. + * + * @throws IOException if there is a problem setting up the resources + */ + public void setup() throws IOException { + Sleeper sleeper = Sleeper.DEFAULT; + BackOff backOff = + FluentBackoff.DEFAULT + .withMaxRetries(3).withInitialBackoff(Duration.millis(200)).backoff(); + Throwable lastException = null; + try { + do { + try { + setupPubsub(); + setupBigQueryTable(); + return; + } catch (GoogleJsonResponseException e) { + lastException = e; + } + } while (BackOffUtils.next(sleeper, backOff)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + // Ignore InterruptedException + } + throw new RuntimeException(lastException); + } + + /** + * Sets up the Google Cloud Pub/Sub topic. + * + *

              If the topic doesn't exist, a new topic with the given name will be created. + * + * @throws IOException if there is a problem setting up the Pub/Sub topic + */ + public void setupPubsub() throws IOException { + ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = + options.as(ExamplePubsubTopicAndSubscriptionOptions.class); + if (!pubsubOptions.getPubsubTopic().isEmpty()) { + pendingMessages.add("**********************Set Up Pubsub************************"); + setupPubsubTopic(pubsubOptions.getPubsubTopic()); + pendingMessages.add("The Pub/Sub topic has been set up for this example: " + + pubsubOptions.getPubsubTopic()); + + if (!pubsubOptions.getPubsubSubscription().isEmpty()) { + setupPubsubSubscription( + pubsubOptions.getPubsubTopic(), pubsubOptions.getPubsubSubscription()); + pendingMessages.add("The Pub/Sub subscription has been set up for this example: " + + pubsubOptions.getPubsubSubscription()); + } + } + } + + /** + * Sets up the BigQuery table with the given schema. + * + *

              If the table already exists, the schema has to match the given one. Otherwise, the example + * will throw a RuntimeException. If the table doesn't exist, a new table with the given schema + * will be created. + * + * @throws IOException if there is a problem setting up the BigQuery table + */ + public void setupBigQueryTable() throws IOException { + ExampleBigQueryTableOptions bigQueryTableOptions = + options.as(ExampleBigQueryTableOptions.class); + if (bigQueryTableOptions.getBigQueryDataset() != null + && bigQueryTableOptions.getBigQueryTable() != null + && bigQueryTableOptions.getBigQuerySchema() != null) { + pendingMessages.add("******************Set Up Big Query Table*******************"); + setupBigQueryTable(bigQueryTableOptions.getProject(), + bigQueryTableOptions.getBigQueryDataset(), + bigQueryTableOptions.getBigQueryTable(), + bigQueryTableOptions.getBigQuerySchema()); + pendingMessages.add("The BigQuery table has been set up for this example: " + + bigQueryTableOptions.getProject() + + ":" + bigQueryTableOptions.getBigQueryDataset() + + "." + bigQueryTableOptions.getBigQueryTable()); + } + } + + /** + * Tears down external resources that can be deleted upon the example's completion. + */ + private void tearDown() { + pendingMessages.add("*************************Tear Down*************************"); + ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = + options.as(ExamplePubsubTopicAndSubscriptionOptions.class); + if (!pubsubOptions.getPubsubTopic().isEmpty()) { + try { + deletePubsubTopic(pubsubOptions.getPubsubTopic()); + pendingMessages.add("The Pub/Sub topic has been deleted: " + + pubsubOptions.getPubsubTopic()); + } catch (IOException e) { + pendingMessages.add("Failed to delete the Pub/Sub topic : " + + pubsubOptions.getPubsubTopic()); + } + if (!pubsubOptions.getPubsubSubscription().isEmpty()) { + try { + deletePubsubSubscription(pubsubOptions.getPubsubSubscription()); + pendingMessages.add("The Pub/Sub subscription has been deleted: " + + pubsubOptions.getPubsubSubscription()); + } catch (IOException e) { + pendingMessages.add("Failed to delete the Pub/Sub subscription : " + + pubsubOptions.getPubsubSubscription()); + } + } + } + + ExampleBigQueryTableOptions bigQueryTableOptions = + options.as(ExampleBigQueryTableOptions.class); + if (bigQueryTableOptions.getBigQueryDataset() != null + && bigQueryTableOptions.getBigQueryTable() != null + && bigQueryTableOptions.getBigQuerySchema() != null) { + pendingMessages.add("The BigQuery table might contain the example's output, " + + "and it is not deleted automatically: " + + bigQueryTableOptions.getProject() + + ":" + bigQueryTableOptions.getBigQueryDataset() + + "." + bigQueryTableOptions.getBigQueryTable()); + pendingMessages.add("Please go to the Developers Console to delete it manually." + + " Otherwise, you may be charged for its usage."); + } + } + + private void setupBigQueryTable(String projectId, String datasetId, String tableId, + TableSchema schema) throws IOException { + if (bigQueryClient == null) { + bigQueryClient = Transport.newBigQueryClient(options.as(BigQueryOptions.class)).build(); + } + + Datasets datasetService = bigQueryClient.datasets(); + if (executeNullIfNotFound(datasetService.get(projectId, datasetId)) == null) { + Dataset newDataset = new Dataset().setDatasetReference( + new DatasetReference().setProjectId(projectId).setDatasetId(datasetId)); + datasetService.insert(projectId, newDataset).execute(); + } + + Tables tableService = bigQueryClient.tables(); + Table table = executeNullIfNotFound(tableService.get(projectId, datasetId, tableId)); + if (table == null) { + Table newTable = new Table().setSchema(schema).setTableReference( + new TableReference().setProjectId(projectId).setDatasetId(datasetId).setTableId(tableId)); + tableService.insert(projectId, datasetId, newTable).execute(); + } else if (!table.getSchema().equals(schema)) { + throw new RuntimeException( + "Table exists and schemas do not match, expecting: " + schema.toPrettyString() + + ", actual: " + table.getSchema().toPrettyString()); + } + } + + private void setupPubsubTopic(String topic) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) == null) { + pubsubClient.projects().topics().create(topic, new Topic().setName(topic)).execute(); + } + } + + private void setupPubsubSubscription(String topic, String subscription) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) == null) { + Subscription subInfo = new Subscription() + .setAckDeadlineSeconds(60) + .setTopic(topic); + pubsubClient.projects().subscriptions().create(subscription, subInfo).execute(); + } + } + + /** + * Deletes the Google Cloud Pub/Sub topic. + * + * @throws IOException if there is a problem deleting the Pub/Sub topic + */ + private void deletePubsubTopic(String topic) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) != null) { + pubsubClient.projects().topics().delete(topic).execute(); + } + } + + /** + * Deletes the Google Cloud Pub/Sub subscription. + * + * @throws IOException if there is a problem deleting the Pub/Sub subscription + */ + private void deletePubsubSubscription(String subscription) throws IOException { + if (pubsubClient == null) { + pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + } + if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) != null) { + pubsubClient.projects().subscriptions().delete(subscription).execute(); + } + } + + /** + * Waits for the pipeline to finish and cancels it before the program exists. + */ + public void waitToFinish(PipelineResult result) { + pipelinesToCancel.add(result); + if (!options.as(ExampleOptions.class).getKeepJobsRunning()) { + addShutdownHook(pipelinesToCancel); + } + try { + result.waitUntilFinish(); + } catch (UnsupportedOperationException e) { + // Do nothing if the given PipelineResult doesn't support waitUntilFinish(), + // such as EvaluationResults returned by DirectRunner. + tearDown(); + printPendingMessages(); + } catch (Exception e) { + throw new RuntimeException("Failed to wait the pipeline until finish: " + result); + } + } + + private void addShutdownHook(final Collection pipelineResults) { + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + tearDown(); + printPendingMessages(); + for (PipelineResult pipelineResult : pipelineResults) { + try { + pipelineResult.cancel(); + } catch (IOException e) { + System.out.println("Failed to cancel the job."); + System.out.println(e.getMessage()); + } + } + + for (PipelineResult pipelineResult : pipelineResults) { + boolean cancellationVerified = false; + for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { + if (pipelineResult.getState().isTerminal()) { + cancellationVerified = true; + break; + } else { + System.out.println( + "The example pipeline is still running. Verifying the cancellation."); + } + Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); + } + if (!cancellationVerified) { + System.out.println("Failed to verify the cancellation for job: " + pipelineResult); + } + } + } + }); + } + + private void printPendingMessages() { + System.out.println(); + System.out.println("***********************************************************"); + System.out.println("***********************************************************"); + for (String message : pendingMessages) { + System.out.println(message); + } + System.out.println("***********************************************************"); + System.out.println("***********************************************************"); + } + + private static T executeNullIfNotFound( + AbstractGoogleClientRequest request) throws IOException { + try { + return request.execute(); + } catch (GoogleJsonResponseException e) { + if (e.getStatusCode() == SC_NOT_FOUND) { + return null; + } else { + throw e; + } + } + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java new file mode 100644 index 0000000000..a08e6a9b0f --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java @@ -0,0 +1,77 @@ +/* + * 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 ${package}.common; + +import com.google.common.annotations.VisibleForTesting; +import java.io.OutputStream; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.util.IOChannelFactory; +import org.apache.beam.sdk.util.IOChannelUtils; +import org.apache.beam.sdk.values.KV; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +/** + * A {@link DoFn} that writes elements to files with names deterministically derived from the lower + * and upper bounds of their key (an {@link IntervalWindow}). + * + *

              This is test utility code, not for end-users, so examples can be focused + * on their primary lessons. + */ +public class WriteWindowedFilesDoFn + extends DoFn>>, Void> { + + static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); + static final Coder STRING_CODER = StringUtf8Coder.of(); + + private static DateTimeFormatter formatter = ISODateTimeFormat.hourMinute(); + + private final String output; + + public WriteWindowedFilesDoFn(String output) { + this.output = output; + } + + @VisibleForTesting + public static String fileForWindow(String output, IntervalWindow window) { + return String.format( + "%s-%s-%s", output, formatter.print(window.start()), formatter.print(window.end())); + } + + @ProcessElement + public void processElement(ProcessContext context) throws Exception { + // Build a file name from the window + IntervalWindow window = context.element().getKey(); + String outputShard = fileForWindow(output, window); + + // Open the file and write all the values + IOChannelFactory factory = IOChannelUtils.getFactory(outputShard); + OutputStream out = Channels.newOutputStream(factory.create(outputShard, "text/plain")); + for (KV wordCount : context.element().getValue()) { + STRING_CODER.encode( + wordCount.getKey() + ": " + wordCount.getValue(), out, Coder.Context.OUTER); + out.write(NEWLINE); + } + out.close(); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java new file mode 100644 index 0000000000..9877844058 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java @@ -0,0 +1,343 @@ +/* + * 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 ${package}.complete.game; + +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import ${package}.common.ExampleUtils; +import ${package}.complete.game.utils.WriteWindowedToBigQuery; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.io.PubsubIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Aggregator; +import org.apache.beam.sdk.transforms.Combine; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.Mean; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.transforms.Values; +import org.apache.beam.sdk.transforms.View; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.FixedWindows; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.OutputTimeFns; +import org.apache.beam.sdk.transforms.windowing.Sessions; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PCollectionView; +import org.apache.beam.sdk.values.TypeDescriptors; +import org.joda.time.DateTimeZone; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is the fourth in a series of four pipelines that tell a story in a 'gaming' + * domain, following {@link UserScore}, {@link HourlyTeamScore}, and {@link LeaderBoard}. + * New concepts: session windows and finding session duration; use of both + * singleton and non-singleton side inputs. + * + *

              This pipeline builds on the {@link LeaderBoard} functionality, and adds some "business + * intelligence" analysis: abuse detection and usage patterns. The pipeline derives the Mean user + * score sum for a window, and uses that information to identify likely spammers/robots. (The robots + * have a higher click rate than the human users). The 'robot' users are then filtered out when + * calculating the team scores. + * + *

              Additionally, user sessions are tracked: that is, we find bursts of user activity using + * session windows. Then, the mean session duration information is recorded in the context of + * subsequent fixed windowing. (This could be used to tell us what games are giving us greater + * user retention). + * + *

              Run {@code org.apache.beam.examples.complete.game.injector.Injector} to generate + * pubsub data for this pipeline. The {@code Injector} documentation provides more detail. + * + *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration + * like this: + *

              {@code
              + *   --project=YOUR_PROJECT_ID
              + *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              + *   --runner=BlockingDataflowRunner
              + *   --dataset=YOUR-DATASET
              + *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              + * }
              + * 
              + * where the BigQuery dataset you specify must already exist. The PubSub topic you specify should + * be the same topic to which the Injector is publishing. + */ +public class GameStats extends LeaderBoard { + + private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; + + private static DateTimeFormatter fmt = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + + /** + * Filter out all but those users with a high clickrate, which we will consider as 'spammy' uesrs. + * We do this by finding the mean total score per user, then using that information as a side + * input to filter out all but those user scores that are larger than + * {@code (mean * SCORE_WEIGHT)}. + */ + // [START DocInclude_AbuseDetect] + public static class CalculateSpammyUsers + extends PTransform>, PCollection>> { + private static final Logger LOG = LoggerFactory.getLogger(CalculateSpammyUsers.class); + private static final double SCORE_WEIGHT = 2.5; + + @Override + public PCollection> expand(PCollection> userScores) { + + // Get the sum of scores for each user. + PCollection> sumScores = userScores + .apply("UserSum", Sum.integersPerKey()); + + // Extract the score from each element, and use it to find the global mean. + final PCollectionView globalMeanScore = sumScores.apply(Values.create()) + .apply(Mean.globally().asSingletonView()); + + // Filter the user sums using the global mean. + PCollection> filtered = sumScores + .apply("ProcessAndFilter", ParDo + // use the derived mean total score as a side input + .withSideInputs(globalMeanScore) + .of(new DoFn, KV>() { + private final Aggregator numSpammerUsers = + createAggregator("SpammerUsers", Sum.ofLongs()); + @ProcessElement + public void processElement(ProcessContext c) { + Integer score = c.element().getValue(); + Double gmc = c.sideInput(globalMeanScore); + if (score > (gmc * SCORE_WEIGHT)) { + LOG.info("user " + c.element().getKey() + " spammer score " + score + + " with mean " + gmc); + numSpammerUsers.addValue(1L); + c.output(c.element()); + } + } + })); + return filtered; + } + } + // [END DocInclude_AbuseDetect] + + /** + * Calculate and output an element's session duration. + */ + private static class UserSessionInfoFn extends DoFn, Integer> { + @ProcessElement + public void processElement(ProcessContext c, BoundedWindow window) { + IntervalWindow w = (IntervalWindow) window; + int duration = new Duration( + w.start(), w.end()).toPeriod().toStandardMinutes().getMinutes(); + c.output(duration); + } + } + + + /** + * Options supported by {@link GameStats}. + */ + interface Options extends LeaderBoard.Options { + @Description("Numeric value of fixed window duration for user analysis, in minutes") + @Default.Integer(60) + Integer getFixedWindowDuration(); + void setFixedWindowDuration(Integer value); + + @Description("Numeric value of gap between user sessions, in minutes") + @Default.Integer(5) + Integer getSessionGap(); + void setSessionGap(Integer value); + + @Description("Numeric value of fixed window for finding mean of user session duration, " + + "in minutes") + @Default.Integer(30) + Integer getUserActivityWindowDuration(); + void setUserActivityWindowDuration(Integer value); + + @Description("Prefix used for the BigQuery table names") + @Default.String("game_stats") + String getGameStatsTablePrefix(); + void setGameStatsTablePrefix(String value); + } + + + /** + * Create a map of information that describes how to write pipeline output to BigQuery. This map + * is used to write information about team score sums. + */ + protected static Map>> + configureWindowedWrite() { + Map>> tableConfigure = + new HashMap>>(); + tableConfigure.put( + "team", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", (c, w) -> c.element().getKey())); + tableConfigure.put( + "total_score", + new WriteWindowedToBigQuery.FieldInfo>( + "INTEGER", (c, w) -> c.element().getValue())); + tableConfigure.put( + "window_start", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", + (c, w) -> { + IntervalWindow window = (IntervalWindow) w; + return fmt.print(window.start()); + })); + tableConfigure.put( + "processing_time", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", (c, w) -> fmt.print(Instant.now()))); + return tableConfigure; + } + + /** + * Create a map of information that describes how to write pipeline output to BigQuery. This map + * is used to write information about mean user session time. + */ + protected static Map> + configureSessionWindowWrite() { + + Map> tableConfigure = + new HashMap>(); + tableConfigure.put( + "window_start", + new WriteWindowedToBigQuery.FieldInfo( + "STRING", + (c, w) -> { + IntervalWindow window = (IntervalWindow) w; + return fmt.print(window.start()); + })); + tableConfigure.put( + "mean_duration", + new WriteWindowedToBigQuery.FieldInfo("FLOAT", (c, w) -> c.element())); + return tableConfigure; + } + + + + public static void main(String[] args) throws Exception { + + Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + // Enforce that this pipeline is always run in streaming mode. + options.setStreaming(true); + ExampleUtils exampleUtils = new ExampleUtils(options); + Pipeline pipeline = Pipeline.create(options); + + // Read Events from Pub/Sub using custom timestamps + PCollection rawEvents = pipeline + .apply(PubsubIO.read() + .timestampLabel(TIMESTAMP_ATTRIBUTE).topic(options.getTopic()) + .withCoder(StringUtf8Coder.of())) + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())); + + // Extract username/score pairs from the event stream + PCollection> userEvents = + rawEvents.apply("ExtractUserScore", + MapElements.via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) + .withOutputType( + TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))); + + // Calculate the total score per user over fixed windows, and + // cumulative updates for late data. + final PCollectionView> spammersView = userEvents + .apply("FixedWindowsUser", Window.>into( + FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) + + // Filter out everyone but those with (SCORE_WEIGHT * avg) clickrate. + // These might be robots/spammers. + .apply("CalculateSpammyUsers", new CalculateSpammyUsers()) + // Derive a view from the collection of spammer users. It will be used as a side input + // in calculating the team score sums, below. + .apply("CreateSpammersView", View.asMap()); + + // [START DocInclude_FilterAndCalc] + // Calculate the total score per team over fixed windows, + // and emit cumulative updates for late data. Uses the side input derived above-- the set of + // suspected robots-- to filter out scores from those users from the sum. + // Write the results to BigQuery. + rawEvents + .apply("WindowIntoFixedWindows", Window.into( + FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) + // Filter out the detected spammer users, using the side input derived above. + .apply("FilterOutSpammers", ParDo + .withSideInputs(spammersView) + .of(new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + // If the user is not in the spammers Map, output the data element. + if (c.sideInput(spammersView).get(c.element().getUser().trim()) == null) { + c.output(c.element()); + } + } + })) + // Extract and sum teamname/score pairs from the event data. + .apply("ExtractTeamScore", new ExtractAndSumScore("team")) + // [END DocInclude_FilterAndCalc] + // Write the result to BigQuery + .apply("WriteTeamSums", + new WriteWindowedToBigQuery>( + options.getGameStatsTablePrefix() + "_team", configureWindowedWrite())); + + + // [START DocInclude_SessionCalc] + // Detect user sessions-- that is, a burst of activity separated by a gap from further + // activity. Find and record the mean session lengths. + // This information could help the game designers track the changing user engagement + // as their set of games changes. + userEvents + .apply("WindowIntoSessions", Window.>into( + Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap()))) + .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow())) + // For this use, we care only about the existence of the session, not any particular + // information aggregated over it, so the following is an efficient way to do that. + .apply(Combine.perKey(x -> 0)) + // Get the duration per session. + .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn())) + // [END DocInclude_SessionCalc] + // [START DocInclude_Rewindow] + // Re-window to process groups of session sums according to when the sessions complete. + .apply("WindowToExtractSessionMean", Window.into( + FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration())))) + // Find the mean session duration in each window. + .apply(Mean.globally().withoutDefaults()) + // Write this info to a BigQuery table. + .apply("WriteAvgSessionLength", + new WriteWindowedToBigQuery( + options.getGameStatsTablePrefix() + "_sessions", configureSessionWindowWrite())); + // [END DocInclude_Rewindow] + + + // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the + // command line. + PipelineResult result = pipeline.run(); + exampleUtils.waitToFinish(result); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java new file mode 100644 index 0000000000..3a0745c735 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java @@ -0,0 +1,196 @@ +/* + * 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 ${package}.complete.game; + +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import ${package}.complete.game.utils.WriteWindowedToBigQuery; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.Filter; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.WithTimestamps; +import org.apache.beam.sdk.transforms.windowing.FixedWindows; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.KV; +import org.joda.time.DateTimeZone; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + +/** + * This class is the second in a series of four pipelines that tell a story in a 'gaming' + * domain, following {@link UserScore}. In addition to the concepts introduced in {@link UserScore}, + * new concepts include: windowing and element timestamps; use of {@code Filter.by()}. + * + *

              This pipeline processes data collected from gaming events in batch, building on {@link + * UserScore} but using fixed windows. It calculates the sum of scores per team, for each window, + * optionally allowing specification of two timestamps before and after which data is filtered out. + * This allows a model where late data collected after the intended analysis window can be included, + * and any late-arriving data prior to the beginning of the analysis window can be removed as well. + * By using windowing and adding element timestamps, we can do finer-grained analysis than with the + * {@link UserScore} pipeline. However, our batch processing is high-latency, in that we don't get + * results from plays at the beginning of the batch's time period until the batch is processed. + * + *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration + * like this: + *

              {@code
              + *   --project=YOUR_PROJECT_ID
              + *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              + *   --runner=BlockingDataflowRunner
              + *   --dataset=YOUR-DATASET
              + * }
              + * 
              + * where the BigQuery dataset you specify must already exist. + * + *

              Optionally include {@code --input} to specify the batch input file path. + * To indicate a time after which the data should be filtered out, include the + * {@code --stopMin} arg. E.g., {@code --stopMin=2015-10-18-23-59} indicates that any data + * timestamped after 23:59 PST on 2015-10-18 should not be included in the analysis. + * To indicate a time before which data should be filtered out, include the {@code --startMin} arg. + * If you're using the default input specified in {@link UserScore}, + * "gs://apache-beam-samples/game/gaming_data*.csv", then + * {@code --startMin=2015-11-16-16-10 --stopMin=2015-11-17-16-10} are good values. + */ +public class HourlyTeamScore extends UserScore { + + private static DateTimeFormatter fmt = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + private static DateTimeFormatter minFmt = + DateTimeFormat.forPattern("yyyy-MM-dd-HH-mm") + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + + + /** + * Options supported by {@link HourlyTeamScore}. + */ + interface Options extends UserScore.Options { + + @Description("Numeric value of fixed window duration, in minutes") + @Default.Integer(60) + Integer getWindowDuration(); + void setWindowDuration(Integer value); + + @Description("String representation of the first minute after which to generate results," + + "in the format: yyyy-MM-dd-HH-mm . This time should be in PST." + + "Any input data timestamped prior to that minute won't be included in the sums.") + @Default.String("1970-01-01-00-00") + String getStartMin(); + void setStartMin(String value); + + @Description("String representation of the first minute for which to not generate results," + + "in the format: yyyy-MM-dd-HH-mm . This time should be in PST." + + "Any input data timestamped after that minute won't be included in the sums.") + @Default.String("2100-01-01-00-00") + String getStopMin(); + void setStopMin(String value); + + @Description("The BigQuery table name. Should not already exist.") + @Default.String("hourly_team_score") + String getHourlyTeamScoreTableName(); + void setHourlyTeamScoreTableName(String value); + } + + /** + * Create a map of information that describes how to write pipeline output to BigQuery. This map + * is passed to the {@link WriteWindowedToBigQuery} constructor to write team score sums and + * includes information about window start time. + */ + protected static Map>> + configureWindowedTableWrite() { + Map>> tableConfig = + new HashMap>>(); + tableConfig.put( + "team", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", (c, w) -> c.element().getKey())); + tableConfig.put( + "total_score", + new WriteWindowedToBigQuery.FieldInfo>( + "INTEGER", (c, w) -> c.element().getValue())); + tableConfig.put( + "window_start", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", + (c, w) -> { + IntervalWindow window = (IntervalWindow) w; + return fmt.print(window.start()); + })); + return tableConfig; + } + + + /** + * Run a batch pipeline to do windowed analysis of the data. + */ + // [START DocInclude_HTSMain] + public static void main(String[] args) throws Exception { + // Begin constructing a pipeline configured by commandline flags. + Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + Pipeline pipeline = Pipeline.create(options); + + final Instant stopMinTimestamp = new Instant(minFmt.parseMillis(options.getStopMin())); + final Instant startMinTimestamp = new Instant(minFmt.parseMillis(options.getStartMin())); + + // Read 'gaming' events from a text file. + pipeline.apply(TextIO.Read.from(options.getInput())) + // Parse the incoming data. + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) + + // Filter out data before and after the given times so that it is not included + // in the calculations. As we collect data in batches (say, by day), the batch for the day + // that we want to analyze could potentially include some late-arriving data from the previous + // day. If so, we want to weed it out. Similarly, if we include data from the following day + // (to scoop up late-arriving events from the day we're analyzing), we need to weed out events + // that fall after the time period we want to analyze. + // [START DocInclude_HTSFilters] + .apply("FilterStartTime", Filter.by( + (GameActionInfo gInfo) + -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) + .apply("FilterEndTime", Filter.by( + (GameActionInfo gInfo) + -> gInfo.getTimestamp() < stopMinTimestamp.getMillis())) + // [END DocInclude_HTSFilters] + + // [START DocInclude_HTSAddTsAndWindow] + // Add an element timestamp based on the event log, and apply fixed windowing. + .apply("AddEventTimestamps", + WithTimestamps.of((GameActionInfo i) -> new Instant(i.getTimestamp()))) + .apply("FixedWindowsTeam", Window.into( + FixedWindows.of(Duration.standardMinutes(options.getWindowDuration())))) + // [END DocInclude_HTSAddTsAndWindow] + + // Extract and sum teamname/score pairs from the event data. + .apply("ExtractTeamScore", new ExtractAndSumScore("team")) + .apply("WriteTeamScoreSums", + new WriteWindowedToBigQuery>(options.getHourlyTeamScoreTableName(), + configureWindowedTableWrite())); + + + pipeline.run().waitUntilFinish(); + } + // [END DocInclude_HTSMain] + +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java new file mode 100644 index 0000000000..e339ec3212 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java @@ -0,0 +1,286 @@ +/* + * 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 ${package}.complete.game; + +import com.google.common.annotations.VisibleForTesting; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import ${package}.common.ExampleOptions; +import ${package}.common.ExampleUtils; +import ${package}.complete.game.utils.WriteToBigQuery; +import ${package}.complete.game.utils.WriteWindowedToBigQuery; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.io.PubsubIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.options.StreamingOptions; +import org.apache.beam.sdk.options.Validation; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.AfterProcessingTime; +import org.apache.beam.sdk.transforms.windowing.AfterWatermark; +import org.apache.beam.sdk.transforms.windowing.FixedWindows; +import org.apache.beam.sdk.transforms.windowing.GlobalWindows; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.Repeatedly; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.joda.time.DateTimeZone; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + +/** + * This class is the third in a series of four pipelines that tell a story in a 'gaming' domain, + * following {@link UserScore} and {@link HourlyTeamScore}. Concepts include: processing unbounded + * data using fixed windows; use of custom timestamps and event-time processing; generation of + * early/speculative results; using .accumulatingFiredPanes() to do cumulative processing of late- + * arriving data. + * + *

              This pipeline processes an unbounded stream of 'game events'. The calculation of the team + * scores uses fixed windowing based on event time (the time of the game play event), not + * processing time (the time that an event is processed by the pipeline). The pipeline calculates + * the sum of scores per team, for each window. By default, the team scores are calculated using + * one-hour windows. + * + *

              In contrast-- to demo another windowing option-- the user scores are calculated using a + * global window, which periodically (every ten minutes) emits cumulative user score sums. + * + *

              In contrast to the previous pipelines in the series, which used static, finite input data, + * here we're using an unbounded data source, which lets us provide speculative results, and allows + * handling of late data, at much lower latency. We can use the early/speculative results to keep a + * 'leaderboard' updated in near-realtime. Our handling of late data lets us generate correct + * results, e.g. for 'team prizes'. We're now outputting window results as they're + * calculated, giving us much lower latency than with the previous batch examples. + * + *

              Run {@code injector.Injector} to generate pubsub data for this pipeline. The Injector + * documentation provides more detail on how to do this. + * + *

              To execute this pipeline using the Dataflow service, specify the pipeline configuration + * like this: + *

              {@code
              + *   --project=YOUR_PROJECT_ID
              + *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              + *   --runner=BlockingDataflowRunner
              + *   --dataset=YOUR-DATASET
              + *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              + * }
              + * 
              + * where the BigQuery dataset you specify must already exist. + * The PubSub topic you specify should be the same topic to which the Injector is publishing. + */ +public class LeaderBoard extends HourlyTeamScore { + + private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; + + private static DateTimeFormatter fmt = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + static final Duration FIVE_MINUTES = Duration.standardMinutes(5); + static final Duration TEN_MINUTES = Duration.standardMinutes(10); + + + /** + * Options supported by {@link LeaderBoard}. + */ + interface Options extends HourlyTeamScore.Options, ExampleOptions, StreamingOptions { + + @Description("Pub/Sub topic to read from") + @Validation.Required + String getTopic(); + void setTopic(String value); + + @Description("Numeric value of fixed window duration for team analysis, in minutes") + @Default.Integer(60) + Integer getTeamWindowDuration(); + void setTeamWindowDuration(Integer value); + + @Description("Numeric value of allowed data lateness, in minutes") + @Default.Integer(120) + Integer getAllowedLateness(); + void setAllowedLateness(Integer value); + + @Description("Prefix used for the BigQuery table names") + @Default.String("leaderboard") + String getLeaderBoardTableName(); + void setLeaderBoardTableName(String value); + } + + /** + * Create a map of information that describes how to write pipeline output to BigQuery. This map + * is used to write team score sums and includes event timing information. + */ + protected static Map>> + configureWindowedTableWrite() { + + Map>> tableConfigure = + new HashMap>>(); + tableConfigure.put( + "team", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", (c, w) -> c.element().getKey())); + tableConfigure.put( + "total_score", + new WriteWindowedToBigQuery.FieldInfo>( + "INTEGER", (c, w) -> c.element().getValue())); + tableConfigure.put( + "window_start", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", + (c, w) -> { + IntervalWindow window = (IntervalWindow) w; + return fmt.print(window.start()); + })); + tableConfigure.put( + "processing_time", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", (c, w) -> fmt.print(Instant.now()))); + tableConfigure.put( + "timing", + new WriteWindowedToBigQuery.FieldInfo>( + "STRING", (c, w) -> c.pane().getTiming().toString())); + return tableConfigure; + } + + /** + * Create a map of information that describes how to write pipeline output to BigQuery. This map + * is used to write user score sums. + */ + protected static Map>> + configureGlobalWindowBigQueryWrite() { + + Map>> tableConfigure = + configureBigQueryWrite(); + tableConfigure.put( + "processing_time", + new WriteToBigQuery.FieldInfo>( + "STRING", (c, w) -> fmt.print(Instant.now()))); + return tableConfigure; + } + + + public static void main(String[] args) throws Exception { + + Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + // Enforce that this pipeline is always run in streaming mode. + options.setStreaming(true); + ExampleUtils exampleUtils = new ExampleUtils(options); + Pipeline pipeline = Pipeline.create(options); + + // Read game events from Pub/Sub using custom timestamps, which are extracted from the pubsub + // data elements, and parse the data. + PCollection gameEvents = pipeline + .apply(PubsubIO.read() + .timestampLabel(TIMESTAMP_ATTRIBUTE).topic(options.getTopic()) + .withCoder(StringUtf8Coder.of())) + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())); + + gameEvents.apply("CalculateTeamScores", + new CalculateTeamScores( + Duration.standardMinutes(options.getTeamWindowDuration()), + Duration.standardMinutes(options.getAllowedLateness()))) + // Write the results to BigQuery. + .apply("WriteTeamScoreSums", + new WriteWindowedToBigQuery>( + options.getLeaderBoardTableName() + "_team", configureWindowedTableWrite())); + gameEvents + .apply( + "CalculateUserScores", + new CalculateUserScores(Duration.standardMinutes(options.getAllowedLateness()))) + // Write the results to BigQuery. + .apply( + "WriteUserScoreSums", + new WriteToBigQuery>( + options.getLeaderBoardTableName() + "_user", configureGlobalWindowBigQueryWrite())); + + // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the + // command line. + PipelineResult result = pipeline.run(); + exampleUtils.waitToFinish(result); + } + + /** + * Calculates scores for each team within the configured window duration. + */ + // [START DocInclude_WindowAndTrigger] + // Extract team/score pairs from the event stream, using hour-long windows by default. + @VisibleForTesting + static class CalculateTeamScores + extends PTransform, PCollection>> { + private final Duration teamWindowDuration; + private final Duration allowedLateness; + + CalculateTeamScores(Duration teamWindowDuration, Duration allowedLateness) { + this.teamWindowDuration = teamWindowDuration; + this.allowedLateness = allowedLateness; + } + + @Override + public PCollection> expand(PCollection infos) { + return infos.apply("LeaderboardTeamFixedWindows", + Window.into(FixedWindows.of(teamWindowDuration)) + // We will get early (speculative) results as well as cumulative + // processing of late data. + .triggering(AfterWatermark.pastEndOfWindow() + .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(FIVE_MINUTES)) + .withLateFirings(AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(TEN_MINUTES))) + .withAllowedLateness(allowedLateness) + .accumulatingFiredPanes()) + // Extract and sum teamname/score pairs from the event data. + .apply("ExtractTeamScore", new ExtractAndSumScore("team")); + } + } + // [END DocInclude_WindowAndTrigger] + + // [START DocInclude_ProcTimeTrigger] + /** + * Extract user/score pairs from the event stream using processing time, via global windowing. + * Get periodic updates on all users' running scores. + */ + @VisibleForTesting + static class CalculateUserScores + extends PTransform, PCollection>> { + private final Duration allowedLateness; + + CalculateUserScores(Duration allowedLateness) { + this.allowedLateness = allowedLateness; + } + + @Override + public PCollection> expand(PCollection input) { + return input.apply("LeaderboardUserGlobalWindow", + Window.into(new GlobalWindows()) + // Get periodic results every ten minutes. + .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() + .plusDelayOf(TEN_MINUTES))) + .accumulatingFiredPanes() + .withAllowedLateness(allowedLateness)) + // Extract and sum username/score pairs from the event data. + .apply("ExtractUserScore", new ExtractAndSumScore("user")); + } + } + // [END DocInclude_ProcTimeTrigger] +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/README.md b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/README.md new file mode 100644 index 0000000000..25e31f55c9 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/README.md @@ -0,0 +1,131 @@ + + +# 'Gaming' examples + + +This directory holds a series of example Dataflow pipelines in a simple 'mobile +gaming' domain. They all require Java 8. Each pipeline successively introduces +new concepts, and gives some examples of using Java 8 syntax in constructing +Dataflow pipelines. Other than usage of Java 8 lambda expressions, the concepts +that are used apply equally well in Java 7. + +In the gaming scenario, many users play, as members of different teams, over +the course of a day, and their actions are logged for processing. Some of the +logged game events may be late-arriving, if users play on mobile devices and go +transiently offline for a period. + +The scenario includes not only "regular" users, but "robot users", which have a +higher click rate than the regular users, and may move from team to team. + +The first two pipelines in the series use pre-generated batch data samples. The +second two pipelines read from a [PubSub](https://cloud.google.com/pubsub/) +topic input. For these examples, you will also need to run the +`injector.Injector` program, which generates and publishes the gaming data to +PubSub. The javadocs for each pipeline have more detailed information on how to +run that pipeline. + +All of these pipelines write their results to BigQuery table(s). + + +## The pipelines in the 'gaming' series + +### UserScore + +The first pipeline in the series is `UserScore`. This pipeline does batch +processing of data collected from gaming events. It calculates the sum of +scores per user, over an entire batch of gaming data (collected, say, for each +day). The batch processing will not include any late data that arrives after +the day's cutoff point. + +### HourlyTeamScore + +The next pipeline in the series is `HourlyTeamScore`. This pipeline also +processes data collected from gaming events in batch. It builds on `UserScore`, +but uses [fixed windows](https://cloud.google.com/dataflow/model/windowing), by +default an hour in duration. It calculates the sum of scores per team, for each +window, optionally allowing specification of two timestamps before and after +which data is filtered out. This allows a model where late data collected after +the intended analysis window can be included in the analysis, and any late- +arriving data prior to the beginning of the analysis window can be removed as +well. + +By using windowing and adding element timestamps, we can do finer-grained +analysis than with the `UserScore` pipeline — we're now tracking scores for +each hour rather than over the course of a whole day. However, our batch +processing is high-latency, in that we don't get results from plays at the +beginning of the batch's time period until the complete batch is processed. + +### LeaderBoard + +The third pipeline in the series is `LeaderBoard`. This pipeline processes an +unbounded stream of 'game events' from a PubSub topic. The calculation of the +team scores uses fixed windowing based on event time (the time of the game play +event), not processing time (the time that an event is processed by the +pipeline). The pipeline calculates the sum of scores per team, for each window. +By default, the team scores are calculated using one-hour windows. + +In contrast — to demo another windowing option — the user scores are calculated +using a global window, which periodically (every ten minutes) emits cumulative +user score sums. + +In contrast to the previous pipelines in the series, which used static, finite +input data, here we're using an unbounded data source, which lets us provide +_speculative_ results, and allows handling of late data, at much lower latency. +E.g., we could use the early/speculative results to keep a 'leaderboard' +updated in near-realtime. Our handling of late data lets us generate correct +results, e.g. for 'team prizes'. We're now outputing window results as they're +calculated, giving us much lower latency than with the previous batch examples. + +### GameStats + +The fourth pipeline in the series is `GameStats`. This pipeline builds +on the `LeaderBoard` functionality — supporting output of speculative and late +data — and adds some "business intelligence" analysis: identifying abuse +detection. The pipeline derives the Mean user score sum for a window, and uses +that information to identify likely spammers/robots. (The injector is designed +so that the "robots" have a higher click rate than the "real" users). The robot +users are then filtered out when calculating the team scores. + +Additionally, user sessions are tracked: that is, we find bursts of user +activity using session windows. Then, the mean session duration information is +recorded in the context of subsequent fixed windowing. (This could be used to +tell us what games are giving us greater user retention). + +### Running the PubSub Injector + +The `LeaderBoard` and `GameStats` example pipelines read unbounded data +from a PubSub topic. + +Use the `injector.Injector` program to generate this data and publish to a +PubSub topic. See the `Injector`javadocs for more information on how to run the +injector. Set up the injector before you start one of these pipelines. Then, +when you start the pipeline, pass as an argument the name of that PubSub topic. +See the pipeline javadocs for the details. + +## Viewing the results in BigQuery + +All of the pipelines write their results to BigQuery. `UserScore` and +`HourlyTeamScore` each write one table, and `LeaderBoard` and +`GameStats` each write two. The pipelines have default table names that +you can override when you start up the pipeline if those tables already exist. + +Depending on the windowing intervals defined in a given pipeline, you may have +to wait for a while (more than an hour) before you start to see results written +to the BigQuery tables. diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java new file mode 100644 index 0000000000..d500658694 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java @@ -0,0 +1,243 @@ +/* + * 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 ${package}.complete.game; + +import java.util.HashMap; +import java.util.Map; +import org.apache.avro.reflect.Nullable; +import ${package}.complete.game.utils.WriteToBigQuery; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.coders.AvroCoder; +import org.apache.beam.sdk.coders.DefaultCoder; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.options.Validation; +import org.apache.beam.sdk.transforms.Aggregator; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.TypeDescriptors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is the first in a series of four pipelines that tell a story in a 'gaming' domain. + * Concepts: batch processing; reading input from Google Cloud Storage and writing output to + * BigQuery; using standalone DoFns; use of the sum by key transform; examples of + * Java 8 lambda syntax. + * + *

              In this gaming scenario, many users play, as members of different teams, over the course of a + * day, and their actions are logged for processing. Some of the logged game events may be late- + * arriving, if users play on mobile devices and go transiently offline for a period. + * + *

              This pipeline does batch processing of data collected from gaming events. It calculates the + * sum of scores per user, over an entire batch of gaming data (collected, say, for each day). The + * batch processing will not include any late data that arrives after the day's cutoff point. + * + *

              To execute this pipeline using the Dataflow service and static example input data, specify + * the pipeline configuration like this: + *

              {@code
              + *   --project=YOUR_PROJECT_ID
              + *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              + *   --runner=BlockingDataflowRunner
              + *   --dataset=YOUR-DATASET
              + * }
              + * 
              + * where the BigQuery dataset you specify must already exist. + * + *

              Optionally include the --input argument to specify a batch input file. + * See the --input default value for example batch data file, or use {@code injector.Injector} to + * generate your own batch data. + */ +public class UserScore { + + /** + * Class to hold info about a game event. + */ + @DefaultCoder(AvroCoder.class) + static class GameActionInfo { + @Nullable String user; + @Nullable String team; + @Nullable Integer score; + @Nullable Long timestamp; + + public GameActionInfo() {} + + public GameActionInfo(String user, String team, Integer score, Long timestamp) { + this.user = user; + this.team = team; + this.score = score; + this.timestamp = timestamp; + } + + public String getUser() { + return this.user; + } + public String getTeam() { + return this.team; + } + public Integer getScore() { + return this.score; + } + public String getKey(String keyname) { + if (keyname.equals("team")) { + return this.team; + } else { // return username as default + return this.user; + } + } + public Long getTimestamp() { + return this.timestamp; + } + } + + + /** + * Parses the raw game event info into GameActionInfo objects. Each event line has the following + * format: username,teamname,score,timestamp_in_ms,readable_time + * e.g.: + * user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 + * The human-readable time string is not used here. + */ + static class ParseEventFn extends DoFn { + + // Log and count parse errors. + private static final Logger LOG = LoggerFactory.getLogger(ParseEventFn.class); + private final Aggregator numParseErrors = + createAggregator("ParseErrors", Sum.ofLongs()); + + @ProcessElement + public void processElement(ProcessContext c) { + String[] components = c.element().split(","); + try { + String user = components[0].trim(); + String team = components[1].trim(); + Integer score = Integer.parseInt(components[2].trim()); + Long timestamp = Long.parseLong(components[3].trim()); + GameActionInfo gInfo = new GameActionInfo(user, team, score, timestamp); + c.output(gInfo); + } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) { + numParseErrors.addValue(1L); + LOG.info("Parse error on " + c.element() + ", " + e.getMessage()); + } + } + } + + /** + * A transform to extract key/score information from GameActionInfo, and sum the scores. The + * constructor arg determines whether 'team' or 'user' info is extracted. + */ + // [START DocInclude_USExtractXform] + public static class ExtractAndSumScore + extends PTransform, PCollection>> { + + private final String field; + + ExtractAndSumScore(String field) { + this.field = field; + } + + @Override + public PCollection> expand( + PCollection gameInfo) { + + return gameInfo + .apply(MapElements + .via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore())) + .withOutputType( + TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))) + .apply(Sum.integersPerKey()); + } + } + // [END DocInclude_USExtractXform] + + + /** + * Options supported by {@link UserScore}. + */ + public interface Options extends PipelineOptions { + + @Description("Path to the data file(s) containing game data.") + // The default maps to two large Google Cloud Storage files (each ~12GB) holding two subsequent + // day's worth (roughly) of data. + @Default.String("gs://apache-beam-samples/game/gaming_data*.csv") + String getInput(); + void setInput(String value); + + @Description("BigQuery Dataset to write tables to. Must already exist.") + @Validation.Required + String getDataset(); + void setDataset(String value); + + @Description("The BigQuery table name. Should not already exist.") + @Default.String("user_score") + String getUserScoreTableName(); + void setUserScoreTableName(String value); + } + + /** + * Create a map of information that describes how to write pipeline output to BigQuery. This map + * is passed to the {@link WriteToBigQuery} constructor to write user score sums. + */ + protected static Map>> + configureBigQueryWrite() { + Map>> tableConfigure = + new HashMap>>(); + tableConfigure.put( + "user", + new WriteToBigQuery.FieldInfo>( + "STRING", (c, w) -> c.element().getKey())); + tableConfigure.put( + "total_score", + new WriteToBigQuery.FieldInfo>( + "INTEGER", (c, w) -> c.element().getValue())); + return tableConfigure; + } + + + /** + * Run a batch pipeline. + */ + // [START DocInclude_USMain] + public static void main(String[] args) throws Exception { + // Begin constructing a pipeline configured by commandline flags. + Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + Pipeline pipeline = Pipeline.create(options); + + // Read events from a text file and parse them. + pipeline.apply(TextIO.Read.from(options.getInput())) + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) + // Extract and sum username/score pairs from the event data. + .apply("ExtractUserScore", new ExtractAndSumScore("user")) + .apply("WriteUserScoreSums", + new WriteToBigQuery>(options.getUserScoreTableName(), + configureBigQueryWrite())); + + // Run the batch pipeline. + pipeline.run().waitUntilFinish(); + } + // [END DocInclude_USMain] + +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java new file mode 100644 index 0000000000..c8531c15d1 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java @@ -0,0 +1,414 @@ +/* + * 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 ${package}.complete.game.injector; + +import com.google.api.services.pubsub.Pubsub; +import com.google.api.services.pubsub.model.PublishRequest; +import com.google.api.services.pubsub.model.PubsubMessage; +import com.google.common.collect.ImmutableMap; +import java.io.BufferedOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.TimeZone; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + + +/** + * This is a generator that simulates usage data from a mobile game, and either publishes the data + * to a pubsub topic or writes it to a file. + * + *

              The general model used by the generator is the following. There is a set of teams with team + * members. Each member is scoring points for their team. After some period, a team will dissolve + * and a new one will be created in its place. There is also a set of 'Robots', or spammer users. + * They hop from team to team. The robots are set to have a higher 'click rate' (generate more + * events) than the regular team members. + * + *

              Each generated line of data has the following form: + * username,teamname,score,timestamp_in_ms,readable_time + * e.g.: + * user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 + * + *

              The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if + * specified. It takes the following arguments: + * {@code Injector project-name (topic-name|none) (filename|none)}. + * + *

              To run the Injector in the mode where it publishes to PubSub, you will need to authenticate + * locally using project-based service account credentials to avoid running over PubSub + * quota. + * See https://developers.google.com/identity/protocols/application-default-credentials + * for more information on using service account credentials. Set the GOOGLE_APPLICATION_CREDENTIALS + * environment variable to point to your downloaded service account credentials before starting the + * program, e.g.: + * {@code export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials-key.json}. + * If you do not do this, then your injector will only run for a few minutes on your + * 'user account' credentials before you will start to see quota error messages like: + * "Request throttled due to user QPS limit being reached", and see this exception: + * ".com.google.api.client.googleapis.json.GoogleJsonResponseException: 429 Too Many Requests". + * Once you've set up your credentials, run the Injector like this": + *

              {@code
              + * Injector   none
              + * }
              + * 
              + * The pubsub topic will be created if it does not exist. + * + *

              To run the injector in write-to-file-mode, set the topic name to "none" and specify the + * filename: + *

              {@code
              + * Injector  none 
              + * }
              + * 
              + */ +class Injector { + private static Pubsub pubsub; + private static Random random = new Random(); + private static String topic; + private static String project; + private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; + + // QPS ranges from 800 to 1000. + private static final int MIN_QPS = 800; + private static final int QPS_RANGE = 200; + // How long to sleep, in ms, between creation of the threads that make API requests to PubSub. + private static final int THREAD_SLEEP_MS = 500; + + // Lists used to generate random team names. + private static final ArrayList COLORS = + new ArrayList(Arrays.asList( + "Magenta", "AliceBlue", "Almond", "Amaranth", "Amber", + "Amethyst", "AndroidGreen", "AntiqueBrass", "Fuchsia", "Ruby", "AppleGreen", + "Apricot", "Aqua", "ArmyGreen", "Asparagus", "Auburn", "Azure", "Banana", + "Beige", "Bisque", "BarnRed", "BattleshipGrey")); + + private static final ArrayList ANIMALS = + new ArrayList(Arrays.asList( + "Echidna", "Koala", "Wombat", "Marmot", "Quokka", "Kangaroo", "Dingo", "Numbat", "Emu", + "Wallaby", "CaneToad", "Bilby", "Possum", "Cassowary", "Kookaburra", "Platypus", + "Bandicoot", "Cockatoo", "Antechinus")); + + // The list of live teams. + private static ArrayList liveTeams = new ArrayList(); + + private static DateTimeFormatter fmt = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + + + // The total number of robots in the system. + private static final int NUM_ROBOTS = 20; + // Determines the chance that a team will have a robot team member. + private static final int ROBOT_PROBABILITY = 3; + private static final int NUM_LIVE_TEAMS = 15; + private static final int BASE_MEMBERS_PER_TEAM = 5; + private static final int MEMBERS_PER_TEAM = 15; + private static final int MAX_SCORE = 20; + private static final int LATE_DATA_RATE = 5 * 60 * 2; // Every 10 minutes + private static final int BASE_DELAY_IN_MILLIS = 5 * 60 * 1000; // 5-10 minute delay + private static final int FUZZY_DELAY_IN_MILLIS = 5 * 60 * 1000; + + // The minimum time a 'team' can live. + private static final int BASE_TEAM_EXPIRATION_TIME_IN_MINS = 20; + private static final int TEAM_EXPIRATION_TIME_IN_MINS = 20; + + + /** + * A class for holding team info: the name of the team, when it started, + * and the current team members. Teams may but need not include one robot team member. + */ + private static class TeamInfo { + String teamName; + long startTimeInMillis; + int expirationPeriod; + // The team might but need not include 1 robot. Will be non-null if so. + String robot; + int numMembers; + + private TeamInfo(String teamName, long startTimeInMillis, String robot) { + this.teamName = teamName; + this.startTimeInMillis = startTimeInMillis; + // How long until this team is dissolved. + this.expirationPeriod = random.nextInt(TEAM_EXPIRATION_TIME_IN_MINS) + + BASE_TEAM_EXPIRATION_TIME_IN_MINS; + this.robot = robot; + // Determine the number of team members. + numMembers = random.nextInt(MEMBERS_PER_TEAM) + BASE_MEMBERS_PER_TEAM; + } + + String getTeamName() { + return teamName; + } + String getRobot() { + return robot; + } + + long getStartTimeInMillis() { + return startTimeInMillis; + } + long getEndTimeInMillis() { + return startTimeInMillis + (expirationPeriod * 60 * 1000); + } + String getRandomUser() { + int userNum = random.nextInt(numMembers); + return "user" + userNum + "_" + teamName; + } + + int numMembers() { + return numMembers; + } + + @Override + public String toString() { + return "(" + teamName + ", num members: " + numMembers() + ", starting at: " + + startTimeInMillis + ", expires in: " + expirationPeriod + ", robot: " + robot + ")"; + } + } + + /** Utility to grab a random element from an array of Strings. */ + private static String randomElement(ArrayList list) { + int index = random.nextInt(list.size()); + return list.get(index); + } + + /** + * Get and return a random team. If the selected team is too old w.r.t its expiration, remove + * it, replacing it with a new team. + */ + private static TeamInfo randomTeam(ArrayList list) { + int index = random.nextInt(list.size()); + TeamInfo team = list.get(index); + // If the selected team is expired, remove it and return a new team. + long currTime = System.currentTimeMillis(); + if ((team.getEndTimeInMillis() < currTime) || team.numMembers() == 0) { + System.out.println("\nteam " + team + " is too old; replacing."); + System.out.println("start time: " + team.getStartTimeInMillis() + + ", end time: " + team.getEndTimeInMillis() + + ", current time:" + currTime); + removeTeam(index); + // Add a new team in its stead. + return (addLiveTeam()); + } else { + return team; + } + } + + /** + * Create and add a team. Possibly add a robot to the team. + */ + private static synchronized TeamInfo addLiveTeam() { + String teamName = randomElement(COLORS) + randomElement(ANIMALS); + String robot = null; + // Decide if we want to add a robot to the team. + if (random.nextInt(ROBOT_PROBABILITY) == 0) { + robot = "Robot-" + random.nextInt(NUM_ROBOTS); + } + // Create the new team. + TeamInfo newTeam = new TeamInfo(teamName, System.currentTimeMillis(), robot); + liveTeams.add(newTeam); + System.out.println("[+" + newTeam + "]"); + return newTeam; + } + + /** + * Remove a specific team. + */ + private static synchronized void removeTeam(int teamIndex) { + TeamInfo removedTeam = liveTeams.remove(teamIndex); + System.out.println("[-" + removedTeam + "]"); + } + + /** Generate a user gaming event. */ + private static String generateEvent(Long currTime, int delayInMillis) { + TeamInfo team = randomTeam(liveTeams); + String teamName = team.getTeamName(); + String user; + final int parseErrorRate = 900000; + + String robot = team.getRobot(); + // If the team has an associated robot team member... + if (robot != null) { + // Then use that robot for the message with some probability. + // Set this probability to higher than that used to select any of the 'regular' team + // members, so that if there is a robot on the team, it has a higher click rate. + if (random.nextInt(team.numMembers() / 2) == 0) { + user = robot; + } else { + user = team.getRandomUser(); + } + } else { // No robot. + user = team.getRandomUser(); + } + String event = user + "," + teamName + "," + random.nextInt(MAX_SCORE); + // Randomly introduce occasional parse errors. You can see a custom counter tracking the number + // of such errors in the Dataflow Monitoring UI, as the example pipeline runs. + if (random.nextInt(parseErrorRate) == 0) { + System.out.println("Introducing a parse error."); + event = "THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR"; + } + return addTimeInfoToEvent(event, currTime, delayInMillis); + } + + /** + * Add time info to a generated gaming event. + */ + private static String addTimeInfoToEvent(String message, Long currTime, int delayInMillis) { + String eventTimeString = + Long.toString((currTime - delayInMillis) / 1000 * 1000); + // Add a (redundant) 'human-readable' date string to make the data semantics more clear. + String dateString = fmt.print(currTime); + message = message + "," + eventTimeString + "," + dateString; + return message; + } + + /** + * Publish 'numMessages' arbitrary events from live users with the provided delay, to a + * PubSub topic. + */ + public static void publishData(int numMessages, int delayInMillis) + throws IOException { + List pubsubMessages = new ArrayList<>(); + + for (int i = 0; i < Math.max(1, numMessages); i++) { + Long currTime = System.currentTimeMillis(); + String message = generateEvent(currTime, delayInMillis); + PubsubMessage pubsubMessage = new PubsubMessage() + .encodeData(message.getBytes("UTF-8")); + pubsubMessage.setAttributes( + ImmutableMap.of(TIMESTAMP_ATTRIBUTE, + Long.toString((currTime - delayInMillis) / 1000 * 1000))); + if (delayInMillis != 0) { + System.out.println(pubsubMessage.getAttributes()); + System.out.println("late data for: " + message); + } + pubsubMessages.add(pubsubMessage); + } + + PublishRequest publishRequest = new PublishRequest(); + publishRequest.setMessages(pubsubMessages); + pubsub.projects().topics().publish(topic, publishRequest).execute(); + } + + /** + * Publish generated events to a file. + */ + public static void publishDataToFile(String fileName, int numMessages, int delayInMillis) + throws IOException { + PrintWriter out = new PrintWriter(new OutputStreamWriter( + new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8")); + + try { + for (int i = 0; i < Math.max(1, numMessages); i++) { + Long currTime = System.currentTimeMillis(); + String message = generateEvent(currTime, delayInMillis); + out.println(message); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (out != null) { + out.flush(); + out.close(); + } + } + } + + + public static void main(String[] args) throws IOException, InterruptedException { + if (args.length < 3) { + System.out.println("Usage: Injector project-name (topic-name|none) (filename|none)"); + System.exit(1); + } + boolean writeToFile = false; + boolean writeToPubsub = true; + project = args[0]; + String topicName = args[1]; + String fileName = args[2]; + // The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if + // specified; otherwise, it will try to write to a file. + if (topicName.equalsIgnoreCase("none")) { + writeToFile = true; + writeToPubsub = false; + } + if (writeToPubsub) { + // Create the PubSub client. + pubsub = InjectorUtils.getClient(); + // Create the PubSub topic as necessary. + topic = InjectorUtils.getFullyQualifiedTopicName(project, topicName); + InjectorUtils.createTopic(pubsub, topic); + System.out.println("Injecting to topic: " + topic); + } else { + if (fileName.equalsIgnoreCase("none")) { + System.out.println("Filename not specified."); + System.exit(1); + } + System.out.println("Writing to file: " + fileName); + } + System.out.println("Starting Injector"); + + // Start off with some random live teams. + while (liveTeams.size() < NUM_LIVE_TEAMS) { + addLiveTeam(); + } + + // Publish messages at a rate determined by the QPS and Thread sleep settings. + for (int i = 0; true; i++) { + if (Thread.activeCount() > 10) { + System.err.println("I'm falling behind!"); + } + + // Decide if this should be a batch of late data. + final int numMessages; + final int delayInMillis; + if (i % LATE_DATA_RATE == 0) { + // Insert delayed data for one user (one message only) + delayInMillis = BASE_DELAY_IN_MILLIS + random.nextInt(FUZZY_DELAY_IN_MILLIS); + numMessages = 1; + System.out.println("DELAY(" + delayInMillis + ", " + numMessages + ")"); + } else { + System.out.print("."); + delayInMillis = 0; + numMessages = MIN_QPS + random.nextInt(QPS_RANGE); + } + + if (writeToFile) { // Won't use threading for the file write. + publishDataToFile(fileName, numMessages, delayInMillis); + } else { // Write to PubSub. + // Start a thread to inject some data. + new Thread(){ + @Override + public void run() { + try { + publishData(numMessages, delayInMillis); + } catch (IOException e) { + System.err.println(e); + } + } + }.start(); + } + + // Wait before creating another injector thread. + Thread.sleep(THREAD_SLEEP_MS); + } + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java new file mode 100644 index 0000000000..55e8c7a8c3 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java @@ -0,0 +1,100 @@ +/* + * 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 ${package}.complete.game.injector; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.googleapis.util.Utils; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.services.pubsub.Pubsub; +import com.google.api.services.pubsub.PubsubScopes; +import com.google.api.services.pubsub.model.Topic; +import java.io.IOException; + +class InjectorUtils { + + private static final String APP_NAME = "injector"; + + /** + * Builds a new Pubsub client and returns it. + */ + public static Pubsub getClient(final HttpTransport httpTransport, + final JsonFactory jsonFactory) + throws IOException { + checkNotNull(httpTransport); + checkNotNull(jsonFactory); + GoogleCredential credential = + GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); + if (credential.createScopedRequired()) { + credential = credential.createScoped(PubsubScopes.all()); + } + if (credential.getClientAuthentication() != null) { + System.out.println("\n***Warning! You are not using service account credentials to " + + "authenticate.\nYou need to use service account credentials for this example," + + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " + + "out of PubSub quota very quickly.\nSee " + + "https://developers.google.com/identity/protocols/application-default-credentials."); + System.exit(1); + } + HttpRequestInitializer initializer = + new RetryHttpInitializerWrapper(credential); + return new Pubsub.Builder(httpTransport, jsonFactory, initializer) + .setApplicationName(APP_NAME) + .build(); + } + + /** + * Builds a new Pubsub client with default HttpTransport and + * JsonFactory and returns it. + */ + public static Pubsub getClient() throws IOException { + return getClient(Utils.getDefaultTransport(), + Utils.getDefaultJsonFactory()); + } + + + /** + * Returns the fully qualified topic name for Pub/Sub. + */ + public static String getFullyQualifiedTopicName( + final String project, final String topic) { + return String.format("projects/%s/topics/%s", project, topic); + } + + /** + * Create a topic if it doesn't exist. + */ + public static void createTopic(Pubsub client, String fullTopicName) + throws IOException { + try { + client.projects().topics().get(fullTopicName).execute(); + } catch (GoogleJsonResponseException e) { + if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + Topic topic = client.projects().topics() + .create(fullTopicName, new Topic()) + .execute(); + System.out.printf("Topic %s was created.\n", topic.getName()); + } + } + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java new file mode 100644 index 0000000000..5d0cc68763 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java @@ -0,0 +1,129 @@ +/* + * 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 ${package}.complete.game.injector; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.client.auth.oauth2.Credential; +import com.google.api.client.http.HttpBackOffIOExceptionHandler; +import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; +import com.google.api.client.http.HttpRequest; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpUnsuccessfulResponseHandler; +import com.google.api.client.util.ExponentialBackOff; +import com.google.api.client.util.Sleeper; +import java.io.IOException; +import java.util.logging.Logger; + +/** + * RetryHttpInitializerWrapper will automatically retry upon RPC + * failures, preserving the auto-refresh behavior of the Google + * Credentials. + */ +public class RetryHttpInitializerWrapper implements HttpRequestInitializer { + + /** + * A private logger. + */ + private static final Logger LOG = + Logger.getLogger(RetryHttpInitializerWrapper.class.getName()); + + /** + * One minutes in miliseconds. + */ + private static final int ONEMINITUES = 60000; + + /** + * Intercepts the request for filling in the "Authorization" + * header field, as well as recovering from certain unsuccessful + * error codes wherein the Credential must refresh its token for a + * retry. + */ + private final Credential wrappedCredential; + + /** + * A sleeper; you can replace it with a mock in your test. + */ + private final Sleeper sleeper; + + /** + * A constructor. + * + * @param wrappedCredential Credential which will be wrapped and + * used for providing auth header. + */ + public RetryHttpInitializerWrapper(final Credential wrappedCredential) { + this(wrappedCredential, Sleeper.DEFAULT); + } + + /** + * A protected constructor only for testing. + * + * @param wrappedCredential Credential which will be wrapped and + * used for providing auth header. + * @param sleeper Sleeper for easy testing. + */ + RetryHttpInitializerWrapper( + final Credential wrappedCredential, final Sleeper sleeper) { + this.wrappedCredential = checkNotNull(wrappedCredential); + this.sleeper = sleeper; + } + + /** + * Initializes the given request. + */ + @Override + public final void initialize(final HttpRequest request) { + request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout + final HttpUnsuccessfulResponseHandler backoffHandler = + new HttpBackOffUnsuccessfulResponseHandler( + new ExponentialBackOff()) + .setSleeper(sleeper); + request.setInterceptor(wrappedCredential); + request.setUnsuccessfulResponseHandler( + new HttpUnsuccessfulResponseHandler() { + @Override + public boolean handleResponse( + final HttpRequest request, + final HttpResponse response, + final boolean supportsRetry) throws IOException { + if (wrappedCredential.handleResponse( + request, response, supportsRetry)) { + // If credential decides it can handle it, + // the return code or message indicated + // something specific to authentication, + // and no backoff is desired. + return true; + } else if (backoffHandler.handleResponse( + request, response, supportsRetry)) { + // Otherwise, we defer to the judgement of + // our internal backoff handler. + LOG.info("Retrying " + + request.getUrl().toString()); + return true; + } else { + return false; + } + } + }); + request.setIOExceptionHandler( + new HttpBackOffIOExceptionHandler(new ExponentialBackOff()) + .setSleeper(sleeper)); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java new file mode 100644 index 0000000000..0e800623ab --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java @@ -0,0 +1,141 @@ +/* + * 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 ${package}.complete.game.utils; + +import com.google.api.services.bigquery.model.TableFieldSchema; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableRow; +import com.google.api.services.bigquery.model.TableSchema; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import ${package}.complete.game.UserScore; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition; +import org.apache.beam.sdk.options.GcpOptions; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PDone; + +/** + * Generate, format, and write BigQuery table row information. Use provided information about + * the field names and types, as well as lambda functions that describe how to generate their + * values. + */ +public class WriteToBigQuery + extends PTransform, PDone> { + + protected String tableName; + protected Map> fieldInfo; + + public WriteToBigQuery() { + } + + public WriteToBigQuery(String tableName, + Map> fieldInfo) { + this.tableName = tableName; + this.fieldInfo = fieldInfo; + } + + /** + * A {@link Serializable} function from a {@link DoFn.ProcessContext} + * and {@link BoundedWindow} to the value for that field. + */ + public interface FieldFn extends Serializable { + Object apply(DoFn.ProcessContext context, BoundedWindow window); + } + + /** Define a class to hold information about output table field definitions. */ + public static class FieldInfo implements Serializable { + // The BigQuery 'type' of the field + private String fieldType; + // A lambda function to generate the field value + private FieldFn fieldFn; + + public FieldInfo(String fieldType, + FieldFn fieldFn) { + this.fieldType = fieldType; + this.fieldFn = fieldFn; + } + + String getFieldType() { + return this.fieldType; + } + + FieldFn getFieldFn() { + return this.fieldFn; + } + } + /** Convert each key/score pair into a BigQuery TableRow as specified by fieldFn. */ + protected class BuildRowFn extends DoFn { + + @ProcessElement + public void processElement(ProcessContext c, BoundedWindow window) { + + TableRow row = new TableRow(); + for (Map.Entry> entry : fieldInfo.entrySet()) { + String key = entry.getKey(); + FieldInfo fcnInfo = entry.getValue(); + FieldFn fcn = fcnInfo.getFieldFn(); + row.set(key, fcn.apply(c, window)); + } + c.output(row); + } + } + + /** Build the output table schema. */ + protected TableSchema getSchema() { + List fields = new ArrayList<>(); + for (Map.Entry> entry : fieldInfo.entrySet()) { + String key = entry.getKey(); + FieldInfo fcnInfo = entry.getValue(); + String bqType = fcnInfo.getFieldType(); + fields.add(new TableFieldSchema().setName(key).setType(bqType)); + } + return new TableSchema().setFields(fields); + } + + @Override + public PDone expand(PCollection teamAndScore) { + return teamAndScore + .apply("ConvertToRow", ParDo.of(new BuildRowFn())) + .apply(BigQueryIO.Write + .to(getTable(teamAndScore.getPipeline(), + tableName)) + .withSchema(getSchema()) + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) + .withWriteDisposition(WriteDisposition.WRITE_APPEND)); + } + + /** Utility to construct an output table reference. */ + static TableReference getTable(Pipeline pipeline, String tableName) { + PipelineOptions options = pipeline.getOptions(); + TableReference table = new TableReference(); + table.setDatasetId(options.as(UserScore.Options.class).getDataset()); + table.setProjectId(options.as(GcpOptions.class).getProject()); + table.setTableId(tableName); + return table; + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java new file mode 100644 index 0000000000..839650f02d --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java @@ -0,0 +1,71 @@ +/* + * 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 ${package}.complete.game.utils; + +import com.google.api.services.bigquery.model.TableRow; +import java.util.Map; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PDone; + +/** + * Generate, format, and write BigQuery table row information. Subclasses {@link WriteToBigQuery} + * to require windowing; so this subclass may be used for writes that require access to the + * context's window information. + */ +public class WriteWindowedToBigQuery + extends WriteToBigQuery { + + public WriteWindowedToBigQuery(String tableName, + Map> fieldInfo) { + super(tableName, fieldInfo); + } + + /** Convert each key/score pair into a BigQuery TableRow. */ + protected class BuildRowFn extends DoFn { + @ProcessElement + public void processElement(ProcessContext c, BoundedWindow window) { + + TableRow row = new TableRow(); + for (Map.Entry> entry : fieldInfo.entrySet()) { + String key = entry.getKey(); + FieldInfo fcnInfo = entry.getValue(); + row.set(key, fcnInfo.getFieldFn().apply(c, window)); + } + c.output(row); + } + } + + @Override + public PDone expand(PCollection teamAndScore) { + return teamAndScore + .apply("ConvertToRow", ParDo.of(new BuildRowFn())) + .apply(BigQueryIO.Write + .to(getTable(teamAndScore.getPipeline(), + tableName)) + .withSchema(getSchema()) + .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) + .withWriteDisposition(WriteDisposition.WRITE_APPEND)); + } + +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java new file mode 100644 index 0000000000..155242d996 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java @@ -0,0 +1,52 @@ +/* + * 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 ${package}; + +import com.google.common.io.Files; +import java.io.File; +import java.nio.charset.StandardCharsets; +import ${package}.DebuggingWordCount.WordCountOptions; +import org.apache.beam.sdk.testing.TestPipeline; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link DebuggingWordCount}. + */ +@RunWith(JUnit4.class) +public class DebuggingWordCountTest { + @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); + + @Test + public void testDebuggingWordCount() throws Exception { + File inputFile = tmpFolder.newFile(); + File outputFile = tmpFolder.newFile(); + Files.write( + "stomach secret Flourish message Flourish here Flourish", + inputFile, + StandardCharsets.UTF_8); + WordCountOptions options = + TestPipeline.testingPipelineOptions().as(WordCountOptions.class); + options.setInputFile(inputFile.getAbsolutePath()); + options.setOutput(outputFile.getAbsolutePath()); + DebuggingWordCount.main(TestPipeline.convertToArgs(options)); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java new file mode 100644 index 0000000000..bfca71bcf9 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java @@ -0,0 +1,104 @@ +/* + * 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 ${package}; + +import com.google.common.collect.ImmutableList; +import java.io.IOException; +import java.io.Serializable; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.util.Arrays; +import java.util.List; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.options.GcsOptions; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.Filter; +import org.apache.beam.sdk.transforms.FlatMapElements; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.util.GcsUtil; +import org.apache.beam.sdk.util.gcsfs.GcsPath; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.TypeDescriptors; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +/** + * To keep {@link MinimalWordCountJava8} simple, it is not factored or testable. This test + * file should be maintained with a copy of its code for a basic smoke test. + */ +@RunWith(JUnit4.class) +public class MinimalWordCountJava8Test implements Serializable { + + @Rule + public TestPipeline p = TestPipeline.create().enableAbandonedNodeEnforcement(false); + + /** + * A basic smoke test that ensures there is no crash at pipeline construction time. + */ + @Test + public void testMinimalWordCountJava8() throws Exception { + p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); + + p.apply(TextIO.Read.from("gs://apache-beam-samples/shakespeare/*")) + .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) + .withOutputType(TypeDescriptors.strings())) + .apply(Filter.by((String word) -> !word.isEmpty())) + .apply(Count.perElement()) + .apply(MapElements + .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue()) + .withOutputType(TypeDescriptors.strings())) + .apply(TextIO.Write.to("gs://your-output-bucket/and-output-prefix")); + } + + private GcsUtil buildMockGcsUtil() throws IOException { + GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); + + // Any request to open gets a new bogus channel + Mockito + .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) + .then(new Answer() { + @Override + public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { + return FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + } + }); + + // Any request for expansion returns a list containing the original GcsPath + // This is required to pass validation that occurs in TextIO during apply() + Mockito + .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) + .then(new Answer>() { + @Override + public List answer(InvocationOnMock invocation) throws Throwable { + return ImmutableList.of((GcsPath) invocation.getArguments()[0]); + } + }); + + return mockGcsUtil; + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java new file mode 100644 index 0000000000..e9621032e5 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java @@ -0,0 +1,86 @@ +/* + * 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 ${package}; + +import java.util.Arrays; +import java.util.List; +import ${package}.WordCount.CountWords; +import ${package}.WordCount.ExtractWordsFn; +import ${package}.WordCount.FormatAsTextFn; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.RunnableOnService; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.DoFnTester; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.values.PCollection; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests of WordCount. + */ +@RunWith(JUnit4.class) +public class WordCountTest { + + /** Example test that tests a specific {@link DoFn}. */ + @Test + public void testExtractWordsFn() throws Exception { + DoFnTester extractWordsFn = + DoFnTester.of(new ExtractWordsFn()); + + Assert.assertThat(extractWordsFn.processBundle(" some input words "), + CoreMatchers.hasItems("some", "input", "words")); + Assert.assertThat(extractWordsFn.processBundle(" "), + CoreMatchers.hasItems()); + Assert.assertThat(extractWordsFn.processBundle(" some ", " input", " words"), + CoreMatchers.hasItems("some", "input", "words")); + } + + static final String[] WORDS_ARRAY = new String[] { + "hi there", "hi", "hi sue bob", + "hi sue", "", "bob hi"}; + + static final List WORDS = Arrays.asList(WORDS_ARRAY); + + static final String[] COUNTS_ARRAY = new String[] { + "hi: 5", "there: 1", "sue: 2", "bob: 2"}; + + @Rule + public TestPipeline p = TestPipeline.create(); + + /** Example test that tests a PTransform by using an in-memory input and inspecting the output. */ + @Test + @Category(RunnableOnService.class) + public void testCountWords() throws Exception { + PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); + + PCollection output = input.apply(new CountWords()) + .apply(MapElements.via(new FormatAsTextFn())); + + PAssert.that(output).containsInAnyOrder(COUNTS_ARRAY); + p.run().waitUntilFinish(); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java new file mode 100644 index 0000000000..3823bea673 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java @@ -0,0 +1,81 @@ +/* + * 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 ${package}.complete.game; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; +import ${package}.complete.game.GameStats.CalculateSpammyUsers; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.RunnableOnService; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests of GameStats. + * Because the pipeline was designed for easy readability and explanations, it lacks good + * modularity for testing. See our testing documentation for better ideas: + * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. + */ +@RunWith(JUnit4.class) +public class GameStatsTest implements Serializable { + + // User scores + static final List> USER_SCORES = Arrays.asList( + KV.of("Robot-2", 66), KV.of("Robot-1", 116), KV.of("user7_AndroidGreenKookaburra", 23), + KV.of("user7_AndroidGreenKookaburra", 1), + KV.of("user19_BisqueBilby", 14), KV.of("user13_ApricotQuokka", 15), + KV.of("user18_BananaEmu", 25), KV.of("user6_AmberEchidna", 8), + KV.of("user2_AmberQuokka", 6), KV.of("user0_MagentaKangaroo", 4), + KV.of("user0_MagentaKangaroo", 3), KV.of("user2_AmberCockatoo", 13), + KV.of("user7_AlmondWallaby", 15), KV.of("user6_AmberNumbat", 11), + KV.of("user6_AmberQuokka", 4)); + + // The expected list of 'spammers'. + static final List> SPAMMERS = Arrays.asList( + KV.of("Robot-2", 66), KV.of("Robot-1", 116)); + + @Rule + public TestPipeline p = TestPipeline.create(); + + /** Test the calculation of 'spammy users'. */ + @Test + @Category(RunnableOnService.class) + public void testCalculateSpammyUsers() throws Exception { + PCollection> input = p.apply(Create.of(USER_SCORES)); + PCollection> output = input.apply(new CalculateSpammyUsers()); + + // Check the set of spammers. + PAssert.that(output).containsInAnyOrder(SPAMMERS); + + p.run().waitUntilFinish(); + } + + @Test + public void testGameStatsOptions() { + PipelineOptionsFactory.as(GameStats.Options.class); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java new file mode 100644 index 0000000000..c777ffb2fb --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java @@ -0,0 +1,117 @@ +/* + * 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 ${package}.complete.game; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; +import ${package}.complete.game.UserScore.GameActionInfo; +import ${package}.complete.game.UserScore.ParseEventFn; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.RunnableOnService; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.Filter; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.TypeDescriptors; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests of HourlyTeamScore. + * Because the pipeline was designed for easy readability and explanations, it lacks good + * modularity for testing. See our testing documentation for better ideas: + * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. + */ +@RunWith(JUnit4.class) +public class HourlyTeamScoreTest implements Serializable { + + static final String[] GAME_EVENTS_ARRAY = new String[] { + "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", + "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", + "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", + "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", + "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", + "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", + "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", + "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444", + // time gap... + "user0_AndroidGreenEchidna,AndroidGreenEchidna,0,1447965690000,2015-11-19 12:41:31.053", + "user0_MagentaKangaroo,MagentaKangaroo,4,1447965690000,2015-11-19 12:41:31.053", + "user2_AmberCockatoo,AmberCockatoo,13,1447965690000,2015-11-19 12:41:31.053", + "user18_BananaEmu,BananaEmu,7,1447965690000,2015-11-19 12:41:31.053", + "user3_BananaEmu,BananaEmu,17,1447965690000,2015-11-19 12:41:31.053", + "user18_BananaEmu,BananaEmu,1,1447965690000,2015-11-19 12:41:31.053", + "user18_ApricotCaneToad,ApricotCaneToad,14,1447965690000,2015-11-19 12:41:31.053" + }; + + + static final List GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); + + + // Used to check the filtering. + static final KV[] FILTERED_EVENTS = new KV[] { + KV.of("user0_AndroidGreenEchidna", 0), KV.of("user0_MagentaKangaroo", 4), + KV.of("user2_AmberCockatoo", 13), + KV.of("user18_BananaEmu", 7), KV.of("user3_BananaEmu", 17), + KV.of("user18_BananaEmu", 1), KV.of("user18_ApricotCaneToad", 14) + }; + + @Rule + public TestPipeline p = TestPipeline.create(); + + /** Test the filtering. */ + @Test + @Category(RunnableOnService.class) + public void testUserScoresFilter() throws Exception { + + final Instant startMinTimestamp = new Instant(1447965680000L); + + PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); + + PCollection> output = input + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) + + .apply("FilterStartTime", Filter.by( + (GameActionInfo gInfo) + -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) + // run a map to access the fields in the result. + .apply(MapElements + .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) + .withOutputType( + TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))); + + PAssert.that(output).containsInAnyOrder(FILTERED_EVENTS); + + p.run().waitUntilFinish(); + } + + @Test + public void testUserScoreOptions() { + PipelineOptionsFactory.as(HourlyTeamScore.Options.class); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java new file mode 100644 index 0000000000..b6d673a9db --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java @@ -0,0 +1,366 @@ +/* + * 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 ${package}.complete.game; + +import static org.hamcrest.Matchers.hasItem; +import static org.junit.Assert.assertThat; + +import com.google.common.collect.ImmutableMap; +import java.io.Serializable; +import ${package}.complete.game.LeaderBoard.CalculateTeamScores; +import ${package}.complete.game.LeaderBoard.CalculateUserScores; +import ${package}.complete.game.UserScore.GameActionInfo; +import org.apache.beam.sdk.coders.AvroCoder; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.testing.TestStream; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.SerializableFunction; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.TimestampedValue; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link LeaderBoard}. + */ +@RunWith(JUnit4.class) +public class LeaderBoardTest implements Serializable { + private static final Duration ALLOWED_LATENESS = Duration.standardHours(1); + private static final Duration TEAM_WINDOW_DURATION = Duration.standardMinutes(20); + private Instant baseTime = new Instant(0); + + @Rule + public TestPipeline p = TestPipeline.create(); + /** + * Some example users, on two separate teams. + */ + private enum TestUser { + RED_ONE("scarlet", "red"), RED_TWO("burgundy", "red"), + BLUE_ONE("navy", "blue"), BLUE_TWO("sky", "blue"); + + private final String userName; + private final String teamName; + + TestUser(String userName, String teamName) { + this.userName = userName; + this.teamName = teamName; + } + + public String getUser() { + return userName; + } + + public String getTeam() { + return teamName; + } + } + + /** + * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive + * on time (ahead of the watermark). + */ + @Test + public void testTeamScoresOnTime() { + + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + // Start at the epoch + .advanceWatermarkTo(baseTime) + // add some elements ahead of the watermark + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1)), + event(TestUser.RED_TWO, 3, Duration.standardSeconds(22)), + event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(3))) + // The watermark advances slightly, but not past the end of the window + .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) + // Add some more on time elements + .addElements(event(TestUser.RED_ONE, 1, Duration.standardMinutes(4)), + event(TestUser.BLUE_ONE, 2, Duration.standardSeconds(270))) + // The window should close and emit an ON_TIME pane + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + PAssert.that(teamScores) + .inOnTimePane(new IntervalWindow(baseTime, TEAM_WINDOW_DURATION)) + .containsInAnyOrder(KV.of(blueTeam, 12), KV.of(redTeam, 4)); + + p.run().waitUntilFinish(); + } + + /** + * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive + * on time, and the processing time advances far enough for speculative panes. + */ + @Test + public void testTeamScoresSpeculative() { + + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + // Start at the epoch + .advanceWatermarkTo(baseTime) + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1))) + // Some time passes within the runner, which causes a speculative pane containing the blue + // team's score to be emitted + .advanceProcessingTime(Duration.standardMinutes(10)) + .addElements(event(TestUser.RED_TWO, 5, Duration.standardMinutes(3))) + // Some additional time passes and we get a speculative pane for the red team + .advanceProcessingTime(Duration.standardMinutes(12)) + .addElements(event(TestUser.BLUE_TWO, 3, Duration.standardSeconds(22))) + // More time passes and a speculative pane containing a refined value for the blue pane is + // emitted + .advanceProcessingTime(Duration.standardMinutes(10)) + // Some more events occur + .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(4)), + event(TestUser.BLUE_TWO, 2, Duration.standardMinutes(2))) + // The window closes and we get an ON_TIME pane that contains all of the updates + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + IntervalWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + // The window contains speculative panes alongside the on-time pane + PAssert.that(teamScores) + .inWindow(window) + .containsInAnyOrder(KV.of(blueTeam, 10) /* The on-time blue pane */, + KV.of(redTeam, 9) /* The on-time red pane */, + KV.of(blueTeam, 5) /* The first blue speculative pane */, + KV.of(blueTeam, 8) /* The second blue speculative pane */, + KV.of(redTeam, 5) /* The red speculative pane */); + PAssert.that(teamScores) + .inOnTimePane(window) + .containsInAnyOrder(KV.of(blueTeam, 10), KV.of(redTeam, 9)); + + p.run().waitUntilFinish(); + } + + /** + * A test where elements arrive behind the watermark (late data), but before the end of the + * window. These elements are emitted on time. + */ + @Test + public void testTeamScoresUnobservablyLate() { + + BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + .advanceWatermarkTo(baseTime) + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8)), + event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) + .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).minus(Duration.standardMinutes(1))) + // These events are late, but the window hasn't closed yet, so the elements are in the + // on-time pane + .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), + event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), + event(TestUser.BLUE_TWO, 2, Duration.standardSeconds(90)), + event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) + .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) + .advanceWatermarkToInfinity(); + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + // The On Time pane contains the late elements that arrived before the end of the window + PAssert.that(teamScores) + .inOnTimePane(window) + .containsInAnyOrder(KV.of(redTeam, 14), KV.of(blueTeam, 13)); + + p.run().waitUntilFinish(); + } + + /** + * A test where elements arrive behind the watermark (late data) after the watermark passes the + * end of the window, but before the maximum allowed lateness. These elements are emitted in a + * late pane. + */ + @Test + public void testTeamScoresObservablyLate() { + + Instant firstWindowCloses = baseTime.plus(ALLOWED_LATENESS).plus(TEAM_WINDOW_DURATION); + TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) + .advanceWatermarkTo(baseTime) + .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), + event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8))) + .advanceProcessingTime(Duration.standardMinutes(10)) + .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) + .addElements(event(TestUser.RED_ONE, 3, Duration.standardMinutes(1)), + event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) + .advanceWatermarkTo(firstWindowCloses.minus(Duration.standardMinutes(1))) + // These events are late but should still appear in a late pane + .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), + event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), + event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) + // A late refinement is emitted due to the advance in processing time, but the window has + // not yet closed because the watermark has not advanced + .advanceProcessingTime(Duration.standardMinutes(12)) + // These elements should appear in the final pane + .addElements(event(TestUser.RED_TWO, 9, Duration.standardMinutes(1)), + event(TestUser.RED_TWO, 1, Duration.standardMinutes(3))) + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + PAssert.that(teamScores) + .inWindow(window) + .satisfies((SerializableFunction>, Void>) input -> { + // The final sums need not exist in the same pane, but must appear in the output + // PCollection + assertThat(input, hasItem(KV.of(blueTeam, 11))); + assertThat(input, hasItem(KV.of(redTeam, 27))); + return null; + }); + PAssert.thatMap(teamScores) + // The closing behavior of CalculateTeamScores precludes an inFinalPane matcher + .inOnTimePane(window) + .isEqualTo(ImmutableMap.builder().put(redTeam, 7) + .put(blueTeam, 11) + .build()); + + // No final pane is emitted for the blue team, as all of their updates have been taken into + // account in earlier panes + PAssert.that(teamScores).inFinalPane(window).containsInAnyOrder(KV.of(redTeam, 27)); + + p.run().waitUntilFinish(); + } + + /** + * A test where elements arrive beyond the maximum allowed lateness. These elements are dropped + * within {@link CalculateTeamScores} and do not impact the final result. + */ + @Test + public void testTeamScoresDroppablyLate() { + + BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); + TestStream infos = TestStream.create(AvroCoder.of(GameActionInfo.class)) + .addElements(event(TestUser.BLUE_ONE, 12, Duration.ZERO), + event(TestUser.RED_ONE, 3, Duration.ZERO)) + .advanceWatermarkTo(window.maxTimestamp()) + .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_TWO, 3, Duration.ZERO), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) + // Move the watermark past the end of the allowed lateness plus the end of the window + .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS) + .plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) + // These elements within the expired window are droppably late, and will not appear in the + // output + .addElements( + event(TestUser.BLUE_TWO, 3, TEAM_WINDOW_DURATION.minus(Duration.standardSeconds(5))), + event(TestUser.RED_ONE, 7, Duration.standardMinutes(4))) + .advanceWatermarkToInfinity(); + PCollection> teamScores = p.apply(infos) + .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); + + String blueTeam = TestUser.BLUE_ONE.getTeam(); + String redTeam = TestUser.RED_ONE.getTeam(); + // Only one on-time pane and no late panes should be emitted + PAssert.that(teamScores) + .inWindow(window) + .containsInAnyOrder(KV.of(redTeam, 7), KV.of(blueTeam, 18)); + // No elements are added before the watermark passes the end of the window plus the allowed + // lateness, so no refinement should be emitted + PAssert.that(teamScores).inFinalPane(window).empty(); + + p.run().waitUntilFinish(); + } + + /** + * A test where elements arrive both on-time and late in {@link CalculateUserScores}, which emits + * output into the {@link GlobalWindow}. All elements that arrive should be taken into account, + * even if they arrive later than the maximum allowed lateness. + */ + @Test + public void testUserScore() { + + TestStream infos = + TestStream.create(AvroCoder.of(GameActionInfo.class)) + .addElements( + event(TestUser.BLUE_ONE, 12, Duration.ZERO), + event(TestUser.RED_ONE, 3, Duration.ZERO)) + .advanceProcessingTime(Duration.standardMinutes(7)) + .addElements( + event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), + event(TestUser.BLUE_TWO, 3, Duration.ZERO), + event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) + .advanceProcessingTime(Duration.standardMinutes(5)) + .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS).plus(Duration.standardHours(12))) + // Late elements are always observable within the global window - they arrive before + // the window closes, so they will appear in a pane, even if they arrive after the + // allowed lateness, and are taken into account alongside on-time elements + .addElements( + event(TestUser.RED_ONE, 3, Duration.standardMinutes(7)), + event(TestUser.RED_ONE, 2, (ALLOWED_LATENESS).plus(Duration.standardHours(13)))) + .advanceProcessingTime(Duration.standardMinutes(6)) + .addElements(event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(12))) + .advanceProcessingTime(Duration.standardMinutes(20)) + .advanceWatermarkToInfinity(); + + PCollection> userScores = + p.apply(infos).apply(new CalculateUserScores(ALLOWED_LATENESS)); + + // User scores are emitted in speculative panes in the Global Window - this matcher choice + // ensures that panes emitted by the watermark advancing to positive infinity are not included, + // as that will not occur outside of tests + PAssert.that(userScores) + .inEarlyGlobalWindowPanes() + .containsInAnyOrder(KV.of(TestUser.BLUE_ONE.getUser(), 15), + KV.of(TestUser.RED_ONE.getUser(), 7), + KV.of(TestUser.RED_ONE.getUser(), 12), + KV.of(TestUser.BLUE_TWO.getUser(), 3), + KV.of(TestUser.BLUE_TWO.getUser(), 8)); + + p.run().waitUntilFinish(); + } + + @Test + public void testLeaderBoardOptions() { + PipelineOptionsFactory.as(LeaderBoard.Options.class); + } + + private TimestampedValue event( + TestUser user, + int score, + Duration baseTimeOffset) { + return TimestampedValue.of(new GameActionInfo(user.getUser(), + user.getTeam(), + score, + baseTime.plus(baseTimeOffset).getMillis()), baseTime.plus(baseTimeOffset)); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java new file mode 100644 index 0000000000..25987ee2cc --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java @@ -0,0 +1,154 @@ +/* + * 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 ${package}.complete.game; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; +import ${package}.complete.game.UserScore.ExtractAndSumScore; +import ${package}.complete.game.UserScore.GameActionInfo; +import ${package}.complete.game.UserScore.ParseEventFn; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.RunnableOnService; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.DoFnTester; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.TypeDescriptors; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests of UserScore. + */ +@RunWith(JUnit4.class) +public class UserScoreTest implements Serializable { + + static final String[] GAME_EVENTS_ARRAY = new String[] { + "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", + "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", + "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", + "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", + "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", + "user6_AliceBlueDingo,AliceBlueDingo,4,xxxxxxx,2015-11-19 09:53:53.444", + "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", + "THIS IS A PARSE ERROR,2015-11-19 09:53:53.444", + "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", + "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444" + }; + + static final String[] GAME_EVENTS_ARRAY2 = new String[] { + "user6_AliceBlueDingo,AliceBlueDingo,4,xxxxxxx,2015-11-19 09:53:53.444", + "THIS IS A PARSE ERROR,2015-11-19 09:53:53.444", + "user13_BisqueBilby,BisqueBilby,xxx,1447955630000,2015-11-19 09:53:53.444" + }; + + static final List GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); + static final List GAME_EVENTS2 = Arrays.asList(GAME_EVENTS_ARRAY2); + + static final List> USER_SUMS = Arrays.asList( + KV.of("user0_MagentaKangaroo", 3), KV.of("user13_ApricotQuokka", 15), + KV.of("user6_AmberNumbat", 11), KV.of("user7_AlmondWallaby", 15), + KV.of("user7_AndroidGreenKookaburra", 23), + KV.of("user19_BisqueBilby", 14)); + + static final List> TEAM_SUMS = Arrays.asList( + KV.of("MagentaKangaroo", 3), KV.of("ApricotQuokka", 15), + KV.of("AmberNumbat", 11), KV.of("AlmondWallaby", 15), + KV.of("AndroidGreenKookaburra", 23), + KV.of("BisqueBilby", 14)); + + @Rule + public TestPipeline p = TestPipeline.create(); + + /** Test the {@link ParseEventFn} {@link org.apache.beam.sdk.transforms.DoFn}. */ + @Test + public void testParseEventFn() throws Exception { + DoFnTester parseEventFn = + DoFnTester.of(new ParseEventFn()); + + List results = parseEventFn.processBundle(GAME_EVENTS_ARRAY); + Assert.assertEquals(results.size(), 8); + Assert.assertEquals(results.get(0).getUser(), "user0_MagentaKangaroo"); + Assert.assertEquals(results.get(0).getTeam(), "MagentaKangaroo"); + Assert.assertEquals(results.get(0).getScore(), new Integer(3)); + } + + /** Tests ExtractAndSumScore("user"). */ + @Test + @Category(RunnableOnService.class) + public void testUserScoreSums() throws Exception { + + PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); + + PCollection> output = input + .apply(ParDo.of(new ParseEventFn())) + // Extract and sum username/score pairs from the event data. + .apply("ExtractUserScore", new ExtractAndSumScore("user")); + + // Check the user score sums. + PAssert.that(output).containsInAnyOrder(USER_SUMS); + + p.run().waitUntilFinish(); + } + + /** Tests ExtractAndSumScore("team"). */ + @Test + @Category(RunnableOnService.class) + public void testTeamScoreSums() throws Exception { + + PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); + + PCollection> output = input + .apply(ParDo.of(new ParseEventFn())) + // Extract and sum teamname/score pairs from the event data. + .apply("ExtractTeamScore", new ExtractAndSumScore("team")); + + // Check the team score sums. + PAssert.that(output).containsInAnyOrder(TEAM_SUMS); + + p.run().waitUntilFinish(); + } + + /** Test that bad input data is dropped appropriately. */ + @Test + @Category(RunnableOnService.class) + public void testUserScoresBadInput() throws Exception { + + PCollection input = p.apply(Create.of(GAME_EVENTS2).withCoder(StringUtf8Coder.of())); + + PCollection> extract = input + .apply(ParDo.of(new ParseEventFn())) + .apply( + MapElements.via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) + .withOutputType( + TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))); + + PAssert.that(extract).empty(); + + p.run().waitUntilFinish(); + } +} diff --git a/maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties new file mode 100644 index 0000000000..b0195b3f16 --- /dev/null +++ b/maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties @@ -0,0 +1,19 @@ +# Copyright (C) 2017 Google Inc. +# +# Licensed 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=it.pkg +version=0.1 +groupId=archetype.it +artifactId=basic +targetPlatform=1.8 diff --git a/maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt b/maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt new file mode 100644 index 0000000000..0b5987362f --- /dev/null +++ b/maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt @@ -0,0 +1 @@ +verify diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 80d03bde09..a534e91393 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -15,13 +15,14 @@ ~ the License. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> + 4.0.0 com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-parent + google-cloud-dataflow-java-archetypes-parent 2.0.0-beta3-SNAPSHOT - ../../pom.xml + ../pom.xml google-cloud-dataflow-java-archetypes-examples @@ -41,5 +42,38 @@ 2.4 + + + + + maven-archetype-plugin + 2.4 + + + org.apache.maven.shared + maven-invoker + 2.2 + + + + + + default-integration-test + install + + integration-test + + + + + + + diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index e1ce538e52..389064a05f 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -23,6 +23,8 @@ ${artifactId} ${version} + jar + UTF-8 @@ -41,8 +43,6 @@ - jar - @@ -55,10 +55,32 @@
              + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + all + 4 + true + + + + org.apache.maven.surefire + surefire-junit47 + 2.19.1 + + + + + org.apache.maven.plugins maven-shade-plugin - 2.3 + 2.4.1 package @@ -67,43 +89,24 @@ ${project.artifactId}-bundled-${project.version} - - - *:* - - *:* + META-INF/LICENSE META-INF/*.SF META-INF/*.DSA META-INF/*.RSA + + + - - - org.apache.maven.plugins - maven-surefire-plugin - 2.19.1 - - all - 4 - true - - - - org.apache.maven.surefire - surefire-junit47 - 2.19.1 - - - @@ -128,6 +131,7 @@ 2.0.0-beta3-SNAPSHOT + com.google.api-client google-api-client @@ -142,7 +146,6 @@ - com.google.apis google-api-services-bigquery @@ -194,7 +197,7 @@ com.google.guava guava - 19.0 + 20.0 diff --git a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties index 1f3c9c5178..8a76657024 100644 --- a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties +++ b/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties @@ -13,7 +13,7 @@ # the License. package=it.pkg -version=0.1-SNAPSHOT +version=0.1 groupId=archetype.it artifactId=basic targetPlatform=1.7 diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml new file mode 100644 index 0000000000..5e323f6506 --- /dev/null +++ b/maven-archetypes/pom.xml @@ -0,0 +1,38 @@ + + + + + 4.0.0 + + + com.google.cloud.dataflow + google-cloud-dataflow-java-sdk-parent + 2.0.0-beta3-SNAPSHOT + ../pom.xml + + + google-cloud-dataflow-java-archetypes-parent + pom + + Google Cloud Dataflow SDK for Java - Maven Archetypes + + + starter + examples + examples-java8 + + diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index eee032d419..70c82c4e98 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -15,13 +15,14 @@ ~ the License. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> + 4.0.0 com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-parent + google-cloud-dataflow-java-archetypes-parent 2.0.0-beta3-SNAPSHOT - ../../pom.xml + ../pom.xml google-cloud-dataflow-java-archetypes-starter @@ -41,5 +42,44 @@ 2.4 + + + + + maven-archetype-plugin + 2.4 + + + org.apache.maven.shared + maven-invoker + 2.2 + + + + + + default-integration-test + install + + integration-test + + + + true + + + + + + + diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index 2ba93d7291..19e0e7acfe 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -41,8 +41,6 @@ - jar - diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties index 1f3c9c5178..8a76657024 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties +++ b/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties @@ -13,7 +13,7 @@ # the License. package=it.pkg -version=0.1-SNAPSHOT +version=0.1 groupId=archetype.it artifactId=basic targetPlatform=1.7 diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index 1f06820c65..a363653e24 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -21,7 +21,7 @@ archetype.it basic - 0.1-SNAPSHOT + 0.1 UTF-8 @@ -41,8 +41,6 @@ - jar - diff --git a/pom.xml b/pom.xml index 8af9511fc5..2e954c12f7 100644 --- a/pom.xml +++ b/pom.xml @@ -103,7 +103,7 @@ ${maven.build.timestamp} yyyy-MM-dd HH:mm - 0.5.0 + 0.6.0 Google Cloud Dataflow SDK for Java ${project.version}-20170202 @@ -114,8 +114,7 @@ sdk examples - maven-archetypes/starter - maven-archetypes/examples + maven-archetypes From 39e87383964d93d99ab5b720568f7fba40eaca14 Mon Sep 17 00:00:00 2001 From: Jason Kuster Date: Fri, 17 Mar 2017 16:02:03 -0700 Subject: [PATCH 701/751] [maven-release-plugin] prepare branch release-2.0.0-beta3 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2e954c12f7..f1d44cbc7c 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.0.0-beta3 From 317aebad878f9045218cfe77357259bf3546eb58 Mon Sep 17 00:00:00 2001 From: Jason Kuster Date: Fri, 17 Mar 2017 16:02:07 -0700 Subject: [PATCH 702/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples-java8/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 5bddc98bf4..f5ae58ad8a 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples-java8/pom.xml b/maven-archetypes/examples-java8/pom.xml index 3c19164933..4056cf6f8f 100644 --- a/maven-archetypes/examples-java8/pom.xml +++ b/maven-archetypes/examples-java8/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index a534e91393..8cf6cd34ca 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 5e323f6506..b698ec84b8 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 70c82c4e98..2e61c542c1 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index f1d44cbc7c..a7e091a86e 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.0.0-beta3 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index b43e014a63..14b8061c1b 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT google-cloud-dataflow-java-sdk-all From f0ccc77f8f255e0b3cc5b2d570ce43e347d7dabe Mon Sep 17 00:00:00 2001 From: Jason Kuster Date: Fri, 17 Mar 2017 16:17:04 -0700 Subject: [PATCH 703/751] Update archetype versioning after cutting 2.0.0-beta3 release branch Signed-off-by: Jason Kuster --- .../src/main/resources/archetype-resources/pom.xml | 2 +- .../examples/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/main/resources/archetype-resources/pom.xml | 2 +- .../starter/src/test/resources/projects/basic/reference/pom.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml index 0f5c2d13aa..e7c1647069 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml @@ -128,7 +128,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 389064a05f..0ee80d0539 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -128,7 +128,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index 19e0e7acfe..b392af2991 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -72,7 +72,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index a363653e24..6aff824959 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -72,7 +72,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta3-SNAPSHOT + 2.0.0-beta4-SNAPSHOT From 328a0d44588bfda2d78e46960ddbb61ebb2ec65e Mon Sep 17 00:00:00 2001 From: Jason Kuster Date: Fri, 17 Mar 2017 16:20:32 -0700 Subject: [PATCH 704/751] Update worker container image for 2.0.0-beta4-SNAPSHOT Signed-off-by: Jason Kuster --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a7e091a86e..7908489603 100644 --- a/pom.xml +++ b/pom.xml @@ -106,7 +106,7 @@ 0.6.0 Google Cloud Dataflow SDK for Java - ${project.version}-20170202 + ${project.version}-20170317 6 From 4ede2806b898157e381995242384e3c515e8795f Mon Sep 17 00:00:00 2001 From: Anil Muppalla Date: Mon, 3 Apr 2017 22:05:16 -0400 Subject: [PATCH 705/751] edited doc --- .../cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java index 5fd8554c90..4b4184063d 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/windowing/AfterWatermark.java @@ -58,7 +58,7 @@ * *

              Additionaly firings before or after the watermark can be requested by calling * {@code AfterWatermark.pastEndOfWindow.withEarlyFirings(OnceTrigger)} or - * {@code AfterWatermark.pastEndOfWindow.withEarlyFirings(OnceTrigger)}. + * {@code AfterWatermark.pastEndOfWindow.withLateFirings(OnceTrigger)}. * * @param {@link BoundedWindow} subclass used to represent the windows used. */ From 1cb04a638781943af15975590c4cabb6995fafd7 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Fri, 7 Apr 2017 15:35:25 -0700 Subject: [PATCH 706/751] DataflowPipelineJob: gracefully handle cancellatoin concurrent with termination This is a backport of BEAM-1880 https://github.com/apache/beam/pull/2428 --- .../sdk/runners/DataflowPipelineJob.java | 32 ++++++++++++++++-- .../sdk/runners/DataflowPipelineJobTest.java | 33 +++++++++++++++++++ 2 files changed, 62 insertions(+), 3 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java index 4a68755565..ced2759561 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJob.java @@ -292,9 +292,35 @@ public void cancel() throws IOException { content.setProjectId(projectId); content.setId(jobId); content.setRequestedState("JOB_STATE_CANCELLED"); - dataflowClient.projects().jobs() - .update(projectId, jobId, content) - .execute(); + try { + dataflowClient.projects().jobs() + .update(projectId, jobId, content) + .execute(); + } catch (IOException e) { + State state = getState(); + if (state.isTerminal()) { + LOG.warn("Cancel failed because job {} is already terminated in state {}.", jobId, state); + } else if (e.getMessage().contains("has terminated")) { + // This handles the case where the getState() call above returns RUNNING but the cancel + // was rejected because the job is in fact done. Hopefully, someday we can delete this + // code if there is better consistency between the State and whether Cancel succeeds. + // + // Example message: + // Workflow modification failed. Causes: (7603adc9e9bff51e): Cannot perform + // operation 'cancel' on Job: 2017-04-01_22_50_59-9269855660514862348. Job has + // terminated in state SUCCESS: Workflow job: 2017-04-01_22_50_59-9269855660514862348 + // succeeded. + LOG.warn("Cancel failed because job {} is already terminated.", jobId, e); + } else { + String errorMsg = String.format( + "Failed to cancel job in state %s, " + + "please go to the Developers Console to cancel it manually: %s", + state, + MonitoringUtil.getJobMonitoringPageURL(getProjectId(), getJobId())); + LOG.warn(errorMsg); + throw new IOException(errorMsg, e); + } + } } @Override diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java index 1d6ccc66ab..9d1172bb7b 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineJobTest.java @@ -26,6 +26,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -42,6 +43,7 @@ import com.google.api.services.dataflow.model.MetricUpdate; import com.google.cloud.dataflow.sdk.PipelineResult.State; import com.google.cloud.dataflow.sdk.runners.dataflow.DataflowAggregatorTransforms; +import com.google.cloud.dataflow.sdk.testing.ExpectedLogs; import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper; import com.google.cloud.dataflow.sdk.transforms.Aggregator; import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform; @@ -91,6 +93,9 @@ public class DataflowPipelineJobTest { @Rule public ExpectedException thrown = ExpectedException.none(); + @Rule + public ExpectedLogs expectedLogs = ExpectedLogs.none(DataflowPipelineJob.class); + @Before public void setup() { MockitoAnnotations.initMocks(this); @@ -193,6 +198,34 @@ public void testWaitToFinishCancelled() throws Exception { assertEquals(State.CANCELLED, mockWaitToFinishInState(State.CANCELLED)); } + /** + * Test that {@link DataflowPipelineJob#cancel} doesn't throw if the Dataflow service returns + * non-terminal state even though the cancel API call failed, which can happen in practice. + * + *

              TODO: delete this code if the API calls become consistent. + */ + @Test + public void testCancelTerminatedJobWithStaleState() throws IOException { + Dataflow.Projects.Jobs.Get statusRequest = + mock(Dataflow.Projects.Jobs.Get.class); + + Job statusResponse = new Job(); + statusResponse.setCurrentState("JOB_STATE_RUNNING"); + when(mockJobs.get(PROJECT_ID, JOB_ID)).thenReturn(statusRequest); + when(statusRequest.execute()).thenReturn(statusResponse); + + Dataflow.Projects.Jobs.Update update = mock( + Dataflow.Projects.Jobs.Update.class); + when(mockJobs.update(eq(PROJECT_ID), eq(JOB_ID), any(Job.class))) + .thenReturn(update); + when(update.execute()).thenThrow(new IOException("Job has terminated in state SUCCESS")); + + DataflowPipelineJob job = new DataflowPipelineJob( + PROJECT_ID, JOB_ID, mockWorkflowClient, null); + job.cancel(); + expectedLogs.verifyWarn("Cancel failed because job " + JOB_ID + " is already terminated."); + } + /** * Tests that the {@link DataflowPipelineJob} understands that the {@link State#FAILED FAILED} * state is terminal. From 7cecf6e249015dac02a1a0e66b9225b03077611e Mon Sep 17 00:00:00 2001 From: Eugene Kirpichov Date: Wed, 19 Apr 2017 10:27:12 -0700 Subject: [PATCH 707/751] Cache result of BigQuerySourceBase.split --- .../cloud/dataflow/sdk/io/BigQueryIO.java | 39 ++++++++++++------- .../cloud/dataflow/sdk/io/BigQueryIOTest.java | 7 +++- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index f844f49aed..ba5fc3bb4a 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1211,6 +1211,8 @@ private abstract static class BigQuerySourceBase extends BoundedSource protected final BigQueryServices bqServices; protected final ValueProvider executingProject; + private List> cachedSplitResult; + private BigQuerySourceBase( String jobIdToken, String extractDestinationDir, @@ -1225,19 +1227,30 @@ private BigQuerySourceBase( @Override public List> splitIntoBundles( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { - BigQueryOptions bqOptions = options.as(BigQueryOptions.class); - TableReference tableToExtract = getTableToExtract(bqOptions); - JobService jobService = bqServices.getJobService(bqOptions); - String extractJobId = getExtractJobId(jobIdToken); - List tempFiles = executeExtract(extractJobId, tableToExtract, jobService); - - TableSchema tableSchema = bqServices.getDatasetService(bqOptions).getTable( - tableToExtract.getProjectId(), - tableToExtract.getDatasetId(), - tableToExtract.getTableId()).getSchema(); - - cleanupTempResource(bqOptions); - return createSources(tempFiles, tableSchema); + // splitIntoBundles() can be called multiple times, e.g. Dataflow runner may call it multiple + // times with different desiredBundleSizeBytes in case the splitIntoBundles() call produces + // too many sources. We ignore desiredBundleSizeBytes anyway, however in any case, we should + // not initiate another BigQuery extract job for the repeated splitIntoBundles() calls. + if (cachedSplitResult == null) { + BigQueryOptions bqOptions = options.as(BigQueryOptions.class); + TableReference tableToExtract = getTableToExtract(bqOptions); + JobService jobService = bqServices.getJobService(bqOptions); + String extractJobId = getExtractJobId(jobIdToken); + List tempFiles = executeExtract(extractJobId, tableToExtract, jobService); + + TableSchema tableSchema = + bqServices + .getDatasetService(bqOptions) + .getTable( + tableToExtract.getProjectId(), + tableToExtract.getDatasetId(), + tableToExtract.getTableId()) + .getSchema(); + + cleanupTempResource(bqOptions); + cachedSplitResult = createSources(tempFiles, tableSchema); + } + return cachedSplitResult; } protected abstract TableReference getTableToExtract(BigQueryOptions bqOptions) throws Exception; diff --git a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java index 7f9d2e95ce..1e4f733096 100644 --- a/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java +++ b/sdk/src/test/java/com/google/cloud/dataflow/sdk/io/BigQueryIOTest.java @@ -30,6 +30,7 @@ import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import com.google.api.client.util.Data; @@ -1130,10 +1131,14 @@ public void testBigQueryTableSourceInitSplit() throws Exception { List> sources = bqSource.splitIntoBundles(100, options); assertEquals(1, sources.size()); + // Simulate a repeated call to splitIntoBundles(), like a Dataflow worker will sometimes do. + sources = bqSource.splitIntoBundles(200, options); + assertEquals(1, sources.size()); BoundedSource actual = sources.get(0); assertThat(actual, CoreMatchers.instanceOf(TransformingSource.class)); - Mockito.verify(mockJobService) + // A repeated call to splitIntoBundles() should not have caused a duplicate extract job. + Mockito.verify(mockJobService, times(1)) .startExtractJob(Mockito.any(), Mockito.any()); } From 52e593a18b92ead25341244922b5334307daa70f Mon Sep 17 00:00:00 2001 From: Eugene Kirpichov Date: Fri, 21 Apr 2017 13:25:58 -0700 Subject: [PATCH 708/751] Makes cachedSplitResult transient in BigQuerySourceBase --- .../main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java index ba5fc3bb4a..d55dfd5910 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BigQueryIO.java @@ -1211,7 +1211,7 @@ private abstract static class BigQuerySourceBase extends BoundedSource protected final BigQueryServices bqServices; protected final ValueProvider executingProject; - private List> cachedSplitResult; + private transient List> cachedSplitResult; private BigQuerySourceBase( String jobIdToken, From 0b189833709c3bb35327e31e29f0dc87152c1c46 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Fri, 28 Apr 2017 10:32:20 -0700 Subject: [PATCH 709/751] Archetypes: version management at the top-level outside archetype source code --- .../resources/archetype-resources/pom.xml | 2 +- .../resources/archetype-resources/pom.xml | 2 +- maven-archetypes/pom.xml | 34 +++++++++++++++++++ .../resources/archetype-resources/pom.xml | 2 +- pom.xml | 8 +++++ 5 files changed, 45 insertions(+), 3 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml index e7c1647069..a8677aeb3e 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml @@ -128,7 +128,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta4-SNAPSHOT + @archetype.sdk_version_dependency@ diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 0ee80d0539..55eac300f1 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -128,7 +128,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta4-SNAPSHOT + @archetype.sdk_version_dependency@ diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index b698ec84b8..837c2afad2 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -35,4 +35,38 @@ examples examples-java8 + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + @ + + false + + + + + + + + src/main/resources + true + + archetype-resources/pom.xml + + + + src/main/resources + false + + archetype-resources/pom.xml + + + + diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index b392af2991..e7f2e59c1f 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -72,7 +72,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta4-SNAPSHOT + @archetype.sdk_version_dependency@ diff --git a/pom.xml b/pom.xml index 7908489603..5c5e993397 100644 --- a/pom.xml +++ b/pom.xml @@ -108,6 +108,8 @@ Google Cloud Dataflow SDK for Java ${project.version}-20170317 6 + + 2.0.0-beta4-SNAPSHOT pom @@ -262,6 +264,12 @@ + + org.apache.maven.plugins + maven-resources-plugin + 3.0.2 + + org.apache.maven.plugins maven-dependency-plugin From f89d619f68c94ac54971265b7ecf0b7778f072fe Mon Sep 17 00:00:00 2001 From: Daniel Halperin Date: Fri, 28 Apr 2017 16:10:25 -0700 Subject: [PATCH 710/751] Fix a typo in Count.java --- .../java/com/google/cloud/dataflow/sdk/transforms/Count.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java index ffa11d13a3..99d5fb8c86 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/Count.java @@ -21,7 +21,7 @@ import com.google.cloud.dataflow.sdk.values.PCollection; /** - * {@code PTransorm}s to count the elements in a {@link PCollection}. + * {@code PTransform}s to count the elements in a {@link PCollection}. * *

              {@link Count#perElement()} can be used to count the number of occurrences of each * distinct element in the PCollection, {@link Count#perKey()} can be used to count the From 3bedec34db0c965d199c2139eeeb9aa8fb4ec936 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Wed, 3 May 2017 23:56:59 -0700 Subject: [PATCH 711/751] Add comment to pom.xml explaining archetype.sdk_version_dependency --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index 5c5e993397..e6efd5c2d7 100644 --- a/pom.xml +++ b/pom.xml @@ -109,6 +109,11 @@ ${project.version}-20170317 6 + 2.0.0-beta4-SNAPSHOT From 0e93387d9e9f6d29fe75f53a98d39163ac56d29b Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Wed, 3 May 2017 23:57:14 -0700 Subject: [PATCH 712/751] Add comment to pom.xml explaining "archetype.sdk_version_dependency" From 8c35b75454ffb714e9663b5c0d4b9b65dcf047bf Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Fri, 5 May 2017 16:36:44 -0700 Subject: [PATCH 713/751] Starter archetype: automate version management in the reference code --- maven-archetypes/starter/pom.xml | 8 ++++++++ .../src/test/resources/projects/basic/reference/pom.xml | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 2e61c542c1..5832a55772 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -43,6 +43,14 @@ + + + + src/test/resources + true + + + diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index 6aff824959..19732871d0 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -72,7 +72,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - 2.0.0-beta4-SNAPSHOT + @project.version@ From 5c096caa20b6d1800a318eeeafe68056346214b1 Mon Sep 17 00:00:00 2001 From: jasonkuster Date: Mon, 22 May 2017 19:24:04 -0700 Subject: [PATCH 714/751] Upgrade to Apache Beam, version 2.0.0 (#571) * Upgrade to Apache Beam, version 2.0.0 Signed-off-by: Jason Kuster * Revert enforcer plugin changes since they seem to be beam-only. Signed-off-by: Jason Kuster * Pull request comments. Signed-off-by: Jason Kuster --- maven-archetypes/examples-java8/pom.xml | 1 + .../resources/archetype-resources/pom.xml | 14 +- .../src/main/java/DebuggingWordCount.java | 24 ++- .../src/main/java/MinimalWordCount.java | 7 +- .../src/main/java/MinimalWordCountJava8.java | 14 +- .../src/main/java/WindowedWordCount.java | 43 ++-- .../src/main/java/WordCount.java | 20 +- .../common/ExampleBigQueryTableOptions.java | 2 +- ...mplePubsubTopicAndSubscriptionOptions.java | 2 +- .../common/ExamplePubsubTopicOptions.java | 2 +- .../src/main/java/common/ExampleUtils.java | 74 ++++++- .../java/common/WriteOneFilePerWindow.java | 114 +++++++++++ .../java/common/WriteWindowedFilesDoFn.java | 77 -------- .../main/java/complete/game/GameStats.java | 49 ++--- .../java/complete/game/HourlyTeamScore.java | 60 +++--- .../main/java/complete/game/LeaderBoard.java | 70 +++++-- .../src/main/java/complete/game/README.md | 131 ------------- .../main/java/complete/game/UserScore.java | 87 ++++----- .../java/complete/game/injector/Injector.java | 3 +- .../complete/game/utils/WriteToBigQuery.java | 31 +-- .../java/complete/game/utils/WriteToText.java | 184 ++++++++++++++++++ .../game/utils/WriteWindowedToBigQuery.java | 14 +- .../test/java/MinimalWordCountJava8Test.java | 15 +- .../src/test/java/WordCountTest.java | 4 +- .../java/complete/game/GameStatsTest.java | 6 +- .../complete/game/HourlyTeamScoreTest.java | 11 +- .../java/complete/game/UserScoreTest.java | 14 +- maven-archetypes/examples/pom.xml | 1 + .../resources/archetype-resources/pom.xml | 16 +- .../src/main/java/DebuggingWordCount.java | 24 ++- .../src/main/java/MinimalWordCount.java | 7 +- .../src/main/java/WindowedWordCount.java | 43 ++-- .../src/main/java/WordCount.java | 20 +- .../common/ExampleBigQueryTableOptions.java | 2 +- ...mplePubsubTopicAndSubscriptionOptions.java | 2 +- .../common/ExamplePubsubTopicOptions.java | 2 +- .../src/main/java/common/ExampleUtils.java | 74 ++++++- .../java/common/WriteOneFilePerWindow.java | 114 +++++++++++ .../java/common/WriteWindowedFilesDoFn.java | 77 -------- .../src/test/java/WordCountTest.java | 4 +- maven-archetypes/pom.xml | 51 +++-- pom.xml | 10 +- 42 files changed, 883 insertions(+), 637 deletions(-) create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/README.md create mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java create mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java diff --git a/maven-archetypes/examples-java8/pom.xml b/maven-archetypes/examples-java8/pom.xml index 4056cf6f8f..b9ae4738d9 100644 --- a/maven-archetypes/examples-java8/pom.xml +++ b/maven-archetypes/examples-java8/pom.xml @@ -74,6 +74,7 @@ + diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml index a8677aeb3e..275e2581a2 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml @@ -27,6 +27,7 @@ UTF-8 + 2.20 @@ -58,7 +59,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + ${surefire-plugin.version} all 4 @@ -68,11 +69,18 @@ org.apache.maven.surefire surefire-junit47 - 2.19.1 + ${surefire-plugin.version} + + + org.apache.maven.plugins + maven-jar-plugin + + - -# 'Gaming' examples - - -This directory holds a series of example Dataflow pipelines in a simple 'mobile -gaming' domain. They all require Java 8. Each pipeline successively introduces -new concepts, and gives some examples of using Java 8 syntax in constructing -Dataflow pipelines. Other than usage of Java 8 lambda expressions, the concepts -that are used apply equally well in Java 7. - -In the gaming scenario, many users play, as members of different teams, over -the course of a day, and their actions are logged for processing. Some of the -logged game events may be late-arriving, if users play on mobile devices and go -transiently offline for a period. - -The scenario includes not only "regular" users, but "robot users", which have a -higher click rate than the regular users, and may move from team to team. - -The first two pipelines in the series use pre-generated batch data samples. The -second two pipelines read from a [PubSub](https://cloud.google.com/pubsub/) -topic input. For these examples, you will also need to run the -`injector.Injector` program, which generates and publishes the gaming data to -PubSub. The javadocs for each pipeline have more detailed information on how to -run that pipeline. - -All of these pipelines write their results to BigQuery table(s). - - -## The pipelines in the 'gaming' series - -### UserScore - -The first pipeline in the series is `UserScore`. This pipeline does batch -processing of data collected from gaming events. It calculates the sum of -scores per user, over an entire batch of gaming data (collected, say, for each -day). The batch processing will not include any late data that arrives after -the day's cutoff point. - -### HourlyTeamScore - -The next pipeline in the series is `HourlyTeamScore`. This pipeline also -processes data collected from gaming events in batch. It builds on `UserScore`, -but uses [fixed windows](https://cloud.google.com/dataflow/model/windowing), by -default an hour in duration. It calculates the sum of scores per team, for each -window, optionally allowing specification of two timestamps before and after -which data is filtered out. This allows a model where late data collected after -the intended analysis window can be included in the analysis, and any late- -arriving data prior to the beginning of the analysis window can be removed as -well. - -By using windowing and adding element timestamps, we can do finer-grained -analysis than with the `UserScore` pipeline — we're now tracking scores for -each hour rather than over the course of a whole day. However, our batch -processing is high-latency, in that we don't get results from plays at the -beginning of the batch's time period until the complete batch is processed. - -### LeaderBoard - -The third pipeline in the series is `LeaderBoard`. This pipeline processes an -unbounded stream of 'game events' from a PubSub topic. The calculation of the -team scores uses fixed windowing based on event time (the time of the game play -event), not processing time (the time that an event is processed by the -pipeline). The pipeline calculates the sum of scores per team, for each window. -By default, the team scores are calculated using one-hour windows. - -In contrast — to demo another windowing option — the user scores are calculated -using a global window, which periodically (every ten minutes) emits cumulative -user score sums. - -In contrast to the previous pipelines in the series, which used static, finite -input data, here we're using an unbounded data source, which lets us provide -_speculative_ results, and allows handling of late data, at much lower latency. -E.g., we could use the early/speculative results to keep a 'leaderboard' -updated in near-realtime. Our handling of late data lets us generate correct -results, e.g. for 'team prizes'. We're now outputing window results as they're -calculated, giving us much lower latency than with the previous batch examples. - -### GameStats - -The fourth pipeline in the series is `GameStats`. This pipeline builds -on the `LeaderBoard` functionality — supporting output of speculative and late -data — and adds some "business intelligence" analysis: identifying abuse -detection. The pipeline derives the Mean user score sum for a window, and uses -that information to identify likely spammers/robots. (The injector is designed -so that the "robots" have a higher click rate than the "real" users). The robot -users are then filtered out when calculating the team scores. - -Additionally, user sessions are tracked: that is, we find bursts of user -activity using session windows. Then, the mean session duration information is -recorded in the context of subsequent fixed windowing. (This could be used to -tell us what games are giving us greater user retention). - -### Running the PubSub Injector - -The `LeaderBoard` and `GameStats` example pipelines read unbounded data -from a PubSub topic. - -Use the `injector.Injector` program to generate this data and publish to a -PubSub topic. See the `Injector`javadocs for more information on how to run the -injector. Set up the injector before you start one of these pipelines. Then, -when you start the pipeline, pass as an argument the name of that PubSub topic. -See the pipeline javadocs for the details. - -## Viewing the results in BigQuery - -All of the pipelines write their results to BigQuery. `UserScore` and -`HourlyTeamScore` each write one table, and `LeaderBoard` and -`GameStats` each write two. The pipelines have default table names that -you can override when you start up the pipeline if those tables already exist. - -Depending on the windowing intervals defined in a given pipeline, you may have -to wait for a while (more than an hour) before you start to see results written -to the BigQuery tables. diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java index d500658694..c693614c57 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java @@ -20,17 +20,18 @@ import java.util.HashMap; import java.util.Map; import org.apache.avro.reflect.Nullable; -import ${package}.complete.game.utils.WriteToBigQuery; +import ${package}.complete.game.utils.WriteToText; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.DefaultCoder; import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.Validation; -import org.apache.beam.sdk.transforms.Aggregator; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.PTransform; @@ -44,8 +45,8 @@ /** * This class is the first in a series of four pipelines that tell a story in a 'gaming' domain. - * Concepts: batch processing; reading input from Google Cloud Storage and writing output to - * BigQuery; using standalone DoFns; use of the sum by key transform; examples of + * Concepts: batch processing, reading input from text files, writing output to + * text files, using standalone DoFns, use of the sum per key transform, and use of * Java 8 lambda syntax. * *

              In this gaming scenario, many users play, as members of different teams, over the course of a @@ -56,16 +57,14 @@ * sum of scores per user, over an entire batch of gaming data (collected, say, for each day). The * batch processing will not include any late data that arrives after the day's cutoff point. * - *

              To execute this pipeline using the Dataflow service and static example input data, specify - * the pipeline configuration like this: + *

              To execute this pipeline, specify the pipeline configuration like this: *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              - *   --runner=BlockingDataflowRunner
              - *   --dataset=YOUR-DATASET
              + *   --tempLocation=YOUR_TEMP_DIRECTORY
              + *   --runner=YOUR_RUNNER
              + *   --output=YOUR_OUTPUT_DIRECTORY
              + *   (possibly options specific to your runner or permissions for your temp/output locations)
                * }
                * 
              - * where the BigQuery dataset you specify must already exist. * *

              Optionally include the --input argument to specify a batch input file. * See the --input default value for example batch data file, or use {@code injector.Injector} to @@ -125,8 +124,7 @@ static class ParseEventFn extends DoFn { // Log and count parse errors. private static final Logger LOG = LoggerFactory.getLogger(ParseEventFn.class); - private final Aggregator numParseErrors = - createAggregator("ParseErrors", Sum.ofLongs()); + private final Counter numParseErrors = Metrics.counter("main", "ParseErrors"); @ProcessElement public void processElement(ProcessContext c) { @@ -139,7 +137,7 @@ public void processElement(ProcessContext c) { GameActionInfo gInfo = new GameActionInfo(user, team, score, timestamp); c.output(gInfo); } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) { - numParseErrors.addValue(1L); + numParseErrors.inc(); LOG.info("Parse error on " + c.element() + ", " + e.getMessage()); } } @@ -165,9 +163,8 @@ public PCollection> expand( return gameInfo .apply(MapElements - .via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore())) - .withOutputType( - TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))) + .into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) + .via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore()))) .apply(Sum.integersPerKey()); } } @@ -186,37 +183,26 @@ public interface Options extends PipelineOptions { String getInput(); void setInput(String value); - @Description("BigQuery Dataset to write tables to. Must already exist.") + // Set this required option to specify where to write the output. + @Description("Path of the file to write to.") @Validation.Required - String getDataset(); - void setDataset(String value); - - @Description("The BigQuery table name. Should not already exist.") - @Default.String("user_score") - String getUserScoreTableName(); - void setUserScoreTableName(String value); + String getOutput(); + void setOutput(String value); } /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is passed to the {@link WriteToBigQuery} constructor to write user score sums. + * Create a map of information that describes how to write pipeline output to text. This map + * is passed to the {@link WriteToText} constructor to write user score sums. */ - protected static Map>> - configureBigQueryWrite() { - Map>> tableConfigure = - new HashMap>>(); - tableConfigure.put( - "user", - new WriteToBigQuery.FieldInfo>( - "STRING", (c, w) -> c.element().getKey())); - tableConfigure.put( - "total_score", - new WriteToBigQuery.FieldInfo>( - "INTEGER", (c, w) -> c.element().getValue())); - return tableConfigure; + protected static Map>> + configureOutput() { + Map>> config = + new HashMap>>(); + config.put("user", (c, w) -> c.element().getKey()); + config.put("total_score", (c, w) -> c.element().getValue()); + return config; } - /** * Run a batch pipeline. */ @@ -227,17 +213,20 @@ public static void main(String[] args) throws Exception { Pipeline pipeline = Pipeline.create(options); // Read events from a text file and parse them. - pipeline.apply(TextIO.Read.from(options.getInput())) - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")) - .apply("WriteUserScoreSums", - new WriteToBigQuery>(options.getUserScoreTableName(), - configureBigQueryWrite())); + pipeline + .apply(TextIO.read().from(options.getInput())) + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) + // Extract and sum username/score pairs from the event data. + .apply("ExtractUserScore", new ExtractAndSumScore("user")) + .apply( + "WriteUserScoreSums", + new WriteToText>( + options.getOutput(), + configureOutput(), + false)); // Run the batch pipeline. pipeline.run().waitUntilFinish(); } // [END DocInclude_USMain] - } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java index c8531c15d1..4814ffb66f 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java @@ -260,8 +260,7 @@ private static String generateEvent(Long currTime, int delayInMillis) { user = team.getRandomUser(); } String event = user + "," + teamName + "," + random.nextInt(MAX_SCORE); - // Randomly introduce occasional parse errors. You can see a custom counter tracking the number - // of such errors in the Dataflow Monitoring UI, as the example pipeline runs. + // Randomly introduce occasional parse errors. if (random.nextInt(parseErrorRate) == 0) { System.out.println("Introducing a parse error."); event = "THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR"; diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java index 0e800623ab..984e958c50 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java @@ -25,13 +25,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import ${package}.complete.game.UserScore; -import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition; -import org.apache.beam.sdk.options.GcpOptions; -import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; @@ -47,14 +43,21 @@ public class WriteToBigQuery extends PTransform, PDone> { + protected String projectId; + protected String datasetId; protected String tableName; protected Map> fieldInfo; public WriteToBigQuery() { } - public WriteToBigQuery(String tableName, + public WriteToBigQuery( + String projectId, + String datasetId, + String tableName, Map> fieldInfo) { + this.projectId = projectId; + this.datasetId = datasetId; this.tableName = tableName; this.fieldInfo = fieldInfo; } @@ -119,22 +122,22 @@ protected TableSchema getSchema() { @Override public PDone expand(PCollection teamAndScore) { - return teamAndScore - .apply("ConvertToRow", ParDo.of(new BuildRowFn())) - .apply(BigQueryIO.Write - .to(getTable(teamAndScore.getPipeline(), - tableName)) + teamAndScore + .apply("ConvertToRow", ParDo.of(new BuildRowFn())) + .apply( + BigQueryIO.writeTableRows() + .to(getTable(projectId, datasetId, tableName)) .withSchema(getSchema()) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND)); + return PDone.in(teamAndScore.getPipeline()); } /** Utility to construct an output table reference. */ - static TableReference getTable(Pipeline pipeline, String tableName) { - PipelineOptions options = pipeline.getOptions(); + static TableReference getTable(String projectId, String datasetId, String tableName) { TableReference table = new TableReference(); - table.setDatasetId(options.as(UserScore.Options.class).getDataset()); - table.setProjectId(options.as(GcpOptions.class).getProject()); + table.setDatasetId(datasetId); + table.setProjectId(projectId); table.setTableId(tableName); return table; } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java new file mode 100644 index 0000000000..6d4e1399b3 --- /dev/null +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java @@ -0,0 +1,184 @@ +/* + * 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 ${package}.complete.game.utils; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Verify.verifyNotNull; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.stream.Collectors; +import org.apache.beam.sdk.io.FileBasedSink; +import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; +import org.apache.beam.sdk.io.fs.ResourceId; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PDone; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + +/** + * Generate, format, and write rows. Use provided information about the field names and types, as + * well as lambda functions that describe how to generate their values. + */ +public class WriteToText + extends PTransform, PDone> { + + private static final DateTimeFormatter formatter = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + + protected String filenamePrefix; + protected Map> fieldFn; + protected boolean windowed; + + public WriteToText() { + } + + public WriteToText( + String filenamePrefix, + Map> fieldFn, + boolean windowed) { + this.filenamePrefix = filenamePrefix; + this.fieldFn = fieldFn; + this.windowed = windowed; + } + + /** + * A {@link Serializable} function from a {@link DoFn.ProcessContext} + * and {@link BoundedWindow} to the value for that field. + */ + public interface FieldFn extends Serializable { + Object apply(DoFn.ProcessContext context, BoundedWindow window); + } + + /** Convert each key/score pair into a row as specified by fieldFn. */ + protected class BuildRowFn extends DoFn { + + @ProcessElement + public void processElement(ProcessContext c, BoundedWindow window) { + List fields = new ArrayList(); + for (Map.Entry> entry : fieldFn.entrySet()) { + String key = entry.getKey(); + FieldFn fcn = entry.getValue(); + fields.add(key + ": " + fcn.apply(c, window)); + } + String result = fields.stream().collect(Collectors.joining(", ")); + c.output(result); + } + } + + /** + * A {@link DoFn} that writes elements to files with names deterministically derived from the + * lower and upper bounds of their key (an {@link IntervalWindow}). + */ + protected class WriteOneFilePerWindow extends PTransform, PDone> { + + private final String filenamePrefix; + + public WriteOneFilePerWindow(String filenamePrefix) { + this.filenamePrefix = filenamePrefix; + } + + @Override + public PDone expand(PCollection input) { + // Verify that the input has a compatible window type. + checkArgument( + input.getWindowingStrategy().getWindowFn().windowCoder() == IntervalWindow.getCoder()); + + // filenamePrefix may contain a directory and a filename component. Pull out only the filename + // component from that path for the PerWindowFiles. + String prefix = ""; + ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); + if (!resource.isDirectory()) { + prefix = verifyNotNull( + resource.getFilename(), + "A non-directory resource should have a non-null filename: %s", + resource); + } + + return input.apply( + TextIO.write() + .to(resource.getCurrentDirectory()) + .withFilenamePolicy(new PerWindowFiles(prefix)) + .withWindowedWrites() + .withNumShards(3)); + } + } + + /** + * A {@link FilenamePolicy} produces a base file name for a write based on metadata about the data + * being written. This always includes the shard number and the total number of shards. For + * windowed writes, it also includes the window and pane index (a sequence number assigned to each + * trigger firing). + */ + protected static class PerWindowFiles extends FilenamePolicy { + + private final String prefix; + + public PerWindowFiles(String prefix) { + this.prefix = prefix; + } + + public String filenamePrefixForWindow(IntervalWindow window) { + return String.format("%s-%s-%s", + prefix, formatter.print(window.start()), formatter.print(window.end())); + } + + @Override + public ResourceId windowedFilename( + ResourceId outputDirectory, WindowedContext context, String extension) { + IntervalWindow window = (IntervalWindow) context.getWindow(); + String filename = String.format( + "%s-%s-of-%s%s", + filenamePrefixForWindow(window), context.getShardNumber(), context.getNumShards(), + extension); + return outputDirectory.resolve(filename, StandardResolveOptions.RESOLVE_FILE); + } + + @Override + public ResourceId unwindowedFilename( + ResourceId outputDirectory, Context context, String extension) { + throw new UnsupportedOperationException("Unsupported."); + } + } + + @Override + public PDone expand(PCollection teamAndScore) { + if (windowed) { + teamAndScore + .apply("ConvertToRow", ParDo.of(new BuildRowFn())) + .apply(new WriteToText.WriteOneFilePerWindow(filenamePrefix)); + } else { + teamAndScore + .apply("ConvertToRow", ParDo.of(new BuildRowFn())) + .apply(TextIO.write().to(filenamePrefix)); + } + return PDone.in(teamAndScore.getPipeline()); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java index 839650f02d..6aef88706d 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java @@ -36,9 +36,9 @@ public class WriteWindowedToBigQuery extends WriteToBigQuery { - public WriteWindowedToBigQuery(String tableName, - Map> fieldInfo) { - super(tableName, fieldInfo); + public WriteWindowedToBigQuery( + String projectId, String datasetId, String tableName, Map> fieldInfo) { + super(projectId, datasetId, tableName, fieldInfo); } /** Convert each key/score pair into a BigQuery TableRow. */ @@ -58,14 +58,14 @@ public void processElement(ProcessContext c, BoundedWindow window) { @Override public PDone expand(PCollection teamAndScore) { - return teamAndScore + teamAndScore .apply("ConvertToRow", ParDo.of(new BuildRowFn())) - .apply(BigQueryIO.Write - .to(getTable(teamAndScore.getPipeline(), - tableName)) + .apply(BigQueryIO.writeTableRows() + .to(getTable(projectId, datasetId, tableName)) .withSchema(getSchema()) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND)); + return PDone.in(teamAndScore.getPipeline()); } } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java index bfca71bcf9..af347c1c0a 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java @@ -26,8 +26,8 @@ import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; +import org.apache.beam.sdk.extensions.gcp.options.GcsOptions; import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.options.GcsOptions; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Count; import org.apache.beam.sdk.transforms.Filter; @@ -62,15 +62,16 @@ public class MinimalWordCountJava8Test implements Serializable { public void testMinimalWordCountJava8() throws Exception { p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); - p.apply(TextIO.Read.from("gs://apache-beam-samples/shakespeare/*")) - .apply(FlatMapElements.via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+"))) - .withOutputType(TypeDescriptors.strings())) + p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) + .apply(FlatMapElements + .into(TypeDescriptors.strings()) + .via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+")))) .apply(Filter.by((String word) -> !word.isEmpty())) .apply(Count.perElement()) .apply(MapElements - .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue()) - .withOutputType(TypeDescriptors.strings())) - .apply(TextIO.Write.to("gs://your-output-bucket/and-output-prefix")); + .into(TypeDescriptors.strings()) + .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue())) + .apply(TextIO.write().to("gs://your-output-bucket/and-output-prefix")); } private GcsUtil buildMockGcsUtil() throws IOException { diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java index e9621032e5..b4e4124e26 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java @@ -24,8 +24,8 @@ import ${package}.WordCount.FormatAsTextFn; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.RunnableOnService; import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.testing.ValidatesRunner; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.DoFnTester; @@ -73,7 +73,7 @@ public void testExtractWordsFn() throws Exception { /** Example test that tests a PTransform by using an in-memory input and inspecting the output. */ @Test - @Category(RunnableOnService.class) + @Category(ValidatesRunner.class) public void testCountWords() throws Exception { PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java index 3823bea673..5cbdc6244f 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java @@ -23,8 +23,8 @@ import ${package}.complete.game.GameStats.CalculateSpammyUsers; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.RunnableOnService; import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.testing.ValidatesRunner; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; @@ -38,7 +38,7 @@ * Tests of GameStats. * Because the pipeline was designed for easy readability and explanations, it lacks good * modularity for testing. See our testing documentation for better ideas: - * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. + * https://beam.apache.org/documentation/pipelines/test-your-pipeline/ */ @RunWith(JUnit4.class) public class GameStatsTest implements Serializable { @@ -63,7 +63,7 @@ public class GameStatsTest implements Serializable { /** Test the calculation of 'spammy users'. */ @Test - @Category(RunnableOnService.class) + @Category(ValidatesRunner.class) public void testCalculateSpammyUsers() throws Exception { PCollection> input = p.apply(Create.of(USER_SCORES)); PCollection> output = input.apply(new CalculateSpammyUsers()); diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java index c777ffb2fb..17d459df93 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java @@ -25,8 +25,8 @@ import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.RunnableOnService; import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.testing.ValidatesRunner; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.Filter; import org.apache.beam.sdk.transforms.MapElements; @@ -45,7 +45,7 @@ * Tests of HourlyTeamScore. * Because the pipeline was designed for easy readability and explanations, it lacks good * modularity for testing. See our testing documentation for better ideas: - * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. + * https://beam.apache.org/documentation/pipelines/test-your-pipeline/ */ @RunWith(JUnit4.class) public class HourlyTeamScoreTest implements Serializable { @@ -86,7 +86,7 @@ public class HourlyTeamScoreTest implements Serializable { /** Test the filtering. */ @Test - @Category(RunnableOnService.class) + @Category(ValidatesRunner.class) public void testUserScoresFilter() throws Exception { final Instant startMinTimestamp = new Instant(1447965680000L); @@ -101,9 +101,8 @@ public void testUserScoresFilter() throws Exception { -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) // run a map to access the fields in the result. .apply(MapElements - .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) - .withOutputType( - TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))); + .into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) + .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore()))); PAssert.that(output).containsInAnyOrder(FILTERED_EVENTS); diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java index 25987ee2cc..83b8821480 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java @@ -25,8 +25,8 @@ import ${package}.complete.game.UserScore.ParseEventFn; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.RunnableOnService; import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.testing.ValidatesRunner; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFnTester; import org.apache.beam.sdk.transforms.MapElements; @@ -99,7 +99,7 @@ public void testParseEventFn() throws Exception { /** Tests ExtractAndSumScore("user"). */ @Test - @Category(RunnableOnService.class) + @Category(ValidatesRunner.class) public void testUserScoreSums() throws Exception { PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); @@ -117,7 +117,7 @@ public void testUserScoreSums() throws Exception { /** Tests ExtractAndSumScore("team"). */ @Test - @Category(RunnableOnService.class) + @Category(ValidatesRunner.class) public void testTeamScoreSums() throws Exception { PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); @@ -135,7 +135,7 @@ public void testTeamScoreSums() throws Exception { /** Test that bad input data is dropped appropriately. */ @Test - @Category(RunnableOnService.class) + @Category(ValidatesRunner.class) public void testUserScoresBadInput() throws Exception { PCollection input = p.apply(Create.of(GAME_EVENTS2).withCoder(StringUtf8Coder.of())); @@ -143,9 +143,9 @@ public void testUserScoresBadInput() throws Exception { PCollection> extract = input .apply(ParDo.of(new ParseEventFn())) .apply( - MapElements.via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) - .withOutputType( - TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))); + MapElements + .into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) + .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore()))); PAssert.that(extract).empty(); diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 8cf6cd34ca..8c16f5e547 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -74,6 +74,7 @@ + diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 55eac300f1..83165d572c 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -27,6 +27,7 @@ UTF-8 + 2.20 @@ -58,7 +59,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + ${surefire-plugin.version} all 4 @@ -68,11 +69,18 @@ org.apache.maven.surefire surefire-junit47 - 2.19.1 + ${surefire-plugin.version} + + + org.apache.maven.plugins + maven-jar-plugin + + org.hamcrest diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java index dd9b91decc..07870f2ed0 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java @@ -22,14 +22,14 @@ import java.util.regex.Pattern; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.transforms.Aggregator; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.Sum; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.slf4j.Logger; @@ -51,7 +51,7 @@ *

              New Concepts: *

                *   1. Logging using SLF4J, even in a distributed environment
              - *   2. Creating a custom aggregator (runners have varying levels of support)
              + *   2. Creating a custom metric (runners have varying levels of support)
                *   3. Testing your Pipeline via PAssert
                * 
              * @@ -90,14 +90,12 @@ public FilterTextFn(String pattern) { } /** - * Concept #2: A custom aggregator can track values in your pipeline as it runs. Each - * runner provides varying levels of support for aggregators, and may expose them + * Concept #2: A custom metric can track values in your pipeline as it runs. Each + * runner provides varying levels of support for metrics, and may expose them * in a dashboard, etc. */ - private final Aggregator matchedWords = - createAggregator("matchedWords", Sum.ofLongs()); - private final Aggregator unmatchedWords = - createAggregator("unmatchedWords", Sum.ofLongs()); + private final Counter matchedWords = Metrics.counter(FilterTextFn.class, "matchedWords"); + private final Counter unmatchedWords = Metrics.counter(FilterTextFn.class, "unmatchedWords"); @ProcessElement public void processElement(ProcessContext c) { @@ -105,14 +103,14 @@ public void processElement(ProcessContext c) { // Log at the "DEBUG" level each element that we match. When executing this pipeline // these log lines will appear only if the log level is set to "DEBUG" or lower. LOG.debug("Matched: " + c.element().getKey()); - matchedWords.addValue(1L); + matchedWords.inc(); c.output(c.element()); } else { // Log at the "TRACE" level each element that is not matched. Different log levels // can be used to control the verbosity of logging providing an effective mechanism // to filter less important information. LOG.trace("Did not match: " + c.element().getKey()); - unmatchedWords.addValue(1L); + unmatchedWords.inc(); } } } @@ -138,7 +136,7 @@ public static void main(String[] args) { Pipeline p = Pipeline.create(options); PCollection> filteredWords = - p.apply("ReadLines", TextIO.Read.from(options.getInputFile())) + p.apply("ReadLines", TextIO.read().from(options.getInputFile())) .apply(new WordCount.CountWords()) .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); @@ -151,7 +149,7 @@ public static void main(String[] args) { *

              Below we verify that the set of filtered words matches our expected counts. Note * that PAssert does not provide any output and that successful completion of the * Pipeline implies that the expectations were met. Learn more at - * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline on how to test + * https://beam.apache.org/documentation/pipelines/test-your-pipeline/ on how to test * your Pipeline and see {@link DebuggingWordCountTest} for an example unit test. */ List> expectedResults = Arrays.asList( diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java index 97bd8243b8..d6b08066db 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java @@ -17,6 +17,7 @@ */ package ${package}; +import ${package}.common.ExampleUtils; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.options.PipelineOptions; @@ -74,7 +75,7 @@ public static void main(String[] args) { // the input text (a set of Shakespeare's texts). // This example reads a public data set consisting of the complete works of Shakespeare. - p.apply(TextIO.Read.from("gs://apache-beam-samples/shakespeare/*")) + p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) // Concept #2: Apply a ParDo transform to our PCollection of text lines. This ParDo invokes a // DoFn (defined in-line) on each element that tokenizes the text line into individual words. @@ -83,7 +84,7 @@ public static void main(String[] args) { .apply("ExtractWords", ParDo.of(new DoFn() { @ProcessElement public void processElement(ProcessContext c) { - for (String word : c.element().split("[^a-zA-Z']+")) { + for (String word : c.element().split(ExampleUtils.TOKENIZER_PATTERN)) { if (!word.isEmpty()) { c.output(word); } @@ -110,7 +111,7 @@ public String apply(KV input) { // formatted strings) to a series of text files. // // By default, it will write to a set of files with names like wordcount-00001-of-00005 - .apply(TextIO.Write.to("wordcounts")); + .apply(TextIO.write().to("wordcounts")); // Run the pipeline. p.run().waitUntilFinish(); diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java index 052d7b6a0e..6a1d07c485 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java @@ -21,7 +21,7 @@ import java.util.concurrent.ThreadLocalRandom; import ${package}.common.ExampleBigQueryTableOptions; import ${package}.common.ExampleOptions; -import ${package}.common.WriteWindowedFilesDoFn; +import ${package}.common.WriteOneFilePerWindow; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.io.TextIO; @@ -31,11 +31,9 @@ import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.GroupByKey; +import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.FixedWindows; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; import org.apache.beam.sdk.transforms.windowing.Window; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; @@ -53,7 +51,7 @@ * *

              Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples: * Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally - * and using a selected runner; defining DoFns; creating a custom aggregator; + * and using a selected runner; defining DoFns; * user-defined PTransforms; defining PipelineOptions. * *

              New Concepts: @@ -163,12 +161,15 @@ public interface Options extends WordCount.WordCountOptions, @Default.InstanceFactory(DefaultToMinTimestampPlusOneHour.class) Long getMaxTimestampMillis(); void setMaxTimestampMillis(Long value); + + @Description("Fixed number of shards to produce per window, or null for runner-chosen sharding") + Integer getNumShards(); + void setNumShards(Integer numShards); } public static void main(String[] args) throws IOException { Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); final String output = options.getOutput(); - final Duration windowSize = Duration.standardMinutes(options.getWindowSize()); final Instant minTimestamp = new Instant(options.getMinTimestampMillis()); final Instant maxTimestamp = new Instant(options.getMaxTimestampMillis()); @@ -180,7 +181,7 @@ public static void main(String[] args) throws IOException { */ PCollection input = pipeline /** Read from the GCS file. */ - .apply(TextIO.Read.from(options.getInputFile())) + .apply(TextIO.read().from(options.getInputFile())) // Concept #2: Add an element timestamp, using an artificial time just to show windowing. // See AddTimestampFn for more detail on this. .apply(ParDo.of(new AddTimestampFn(minTimestamp, maxTimestamp))); @@ -203,33 +204,13 @@ public static void main(String[] args) throws IOException { PCollection> wordCounts = windowedWords.apply(new WordCount.CountWords()); /** - * Concept #5: Customize the output format using windowing information - * - *

              At this point, the data is organized by window. We're writing text files and and have no - * late data, so for simplicity we can use the window as the key and {@link GroupByKey} to get - * one output file per window. (if we had late data this key would not be unique) - * - *

              To access the window in a {@link DoFn}, add a {@link BoundedWindow} parameter. This will - * be automatically detected and populated with the window for the current element. - */ - PCollection>> keyedByWindow = - wordCounts.apply( - ParDo.of( - new DoFn, KV>>() { - @ProcessElement - public void processElement(ProcessContext context, IntervalWindow window) { - context.output(KV.of(window, context.element())); - } - })); - - /** - * Concept #6: Format the results and write to a sharded file partitioned by window, using a + * Concept #5: Format the results and write to a sharded file partitioned by window, using a * simple ParDo operation. Because there may be failures followed by retries, the * writes must be idempotent, but the details of writing to files is elided here. */ - keyedByWindow - .apply(GroupByKey.>create()) - .apply(ParDo.of(new WriteWindowedFilesDoFn(output))); + wordCounts + .apply(MapElements.via(new WordCount.FormatAsTextFn())) + .apply(new WriteOneFilePerWindow(output, options.getNumShards())); PipelineResult result = pipeline.run(); try { diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java index b3ef26c493..79b71403b9 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -17,21 +17,22 @@ */ package ${package}; +import ${package}.common.ExampleUtils; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.Validation.Required; -import org.apache.beam.sdk.transforms.Aggregator; import org.apache.beam.sdk.transforms.Count; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.SimpleFunction; -import org.apache.beam.sdk.transforms.Sum; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; @@ -44,8 +45,8 @@ * pipeline, for introduction of additional concepts. * *

              For a detailed walkthrough of this example, see - * - * http://beam.apache.org/use/walkthroughs/ + * + * https://beam.apache.org/get-started/wordcount-example/ * * *

              Basic concepts, also in the MinimalWordCount example: @@ -86,17 +87,16 @@ public class WordCount { * to a ParDo in the pipeline. */ static class ExtractWordsFn extends DoFn { - private final Aggregator emptyLines = - createAggregator("emptyLines", Sum.ofLongs()); + private final Counter emptyLines = Metrics.counter(ExtractWordsFn.class, "emptyLines"); @ProcessElement public void processElement(ProcessContext c) { if (c.element().trim().isEmpty()) { - emptyLines.addValue(1L); + emptyLines.inc(); } // Split the line into words. - String[] words = c.element().split("[^a-zA-Z']+"); + String[] words = c.element().split(ExampleUtils.TOKENIZER_PATTERN); // Output each word encountered into the output PCollection. for (String word : words) { @@ -176,10 +176,10 @@ public static void main(String[] args) { // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the // static FormatAsTextFn() to the ParDo transform. - p.apply("ReadLines", TextIO.Read.from(options.getInputFile())) + p.apply("ReadLines", TextIO.read().from(options.getInputFile())) .apply(new CountWords()) .apply(MapElements.via(new FormatAsTextFn())) - .apply("WriteCounts", TextIO.Write.to(options.getOutput())); + .apply("WriteCounts", TextIO.write().to(options.getOutput())); p.run().waitUntilFinish(); } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java index 6b51074f44..57f1546e27 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java @@ -18,10 +18,10 @@ package ${package}.common; import com.google.api.services.bigquery.model.TableSchema; +import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.DefaultValueFactory; import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.GcpOptions; import org.apache.beam.sdk.options.PipelineOptions; /** diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java index daeb398f7f..cf142a10fd 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java @@ -17,10 +17,10 @@ */ package ${package}.common; +import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.DefaultValueFactory; import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.GcpOptions; import org.apache.beam.sdk.options.PipelineOptions; /** diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java index 936bff5675..86784b06da 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java @@ -17,10 +17,10 @@ */ package ${package}.common; +import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.DefaultValueFactory; import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.GcpOptions; import org.apache.beam.sdk.options.PipelineOptions; /** diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java index 570b3827b7..78f3849b40 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java @@ -19,9 +19,7 @@ import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.BackOffUtils; -import com.google.api.client.util.Sleeper; +import com.google.api.client.http.HttpRequestInitializer; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.Bigquery.Datasets; import com.google.api.services.bigquery.Bigquery.Tables; @@ -33,6 +31,10 @@ import com.google.api.services.pubsub.Pubsub; import com.google.api.services.pubsub.model.Subscription; import com.google.api.services.pubsub.model.Topic; +import com.google.auth.Credentials; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Uninterruptibles; @@ -42,10 +44,15 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.options.BigQueryOptions; +import org.apache.beam.sdk.extensions.gcp.auth.NullCredentialInitializer; +import org.apache.beam.sdk.io.gcp.bigquery.BigQueryOptions; +import org.apache.beam.sdk.io.gcp.pubsub.PubsubOptions; import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PubsubOptions; +import org.apache.beam.sdk.util.BackOff; +import org.apache.beam.sdk.util.BackOffUtils; import org.apache.beam.sdk.util.FluentBackoff; +import org.apache.beam.sdk.util.RetryHttpRequestInitializer; +import org.apache.beam.sdk.util.Sleeper; import org.apache.beam.sdk.util.Transport; import org.joda.time.Duration; @@ -59,6 +66,14 @@ public class ExampleUtils { private static final int SC_NOT_FOUND = 404; + /** + * \p{L} denotes the category of Unicode letters, + * so this pattern will match on everything that is not a letter. + * + *

              It is used for tokenizing strings in the wordcount examples. + */ + public static final String TOKENIZER_PATTERN = "[^\\p{L}]+"; + private final PipelineOptions options; private Bigquery bigQueryClient = null; private Pubsub pubsubClient = null; @@ -196,10 +211,49 @@ private void tearDown() { } } + /** + * Returns a BigQuery client builder using the specified {@link BigQueryOptions}. + */ + private static Bigquery.Builder newBigQueryClient(BigQueryOptions options) { + return new Bigquery.Builder(Transport.getTransport(), Transport.getJsonFactory(), + chainHttpRequestInitializer( + options.getGcpCredential(), + // Do not log 404. It clutters the output and is possibly even required by the caller. + new RetryHttpRequestInitializer(ImmutableList.of(404)))) + .setApplicationName(options.getAppName()) + .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); + } + + /** + * Returns a Pubsub client builder using the specified {@link PubsubOptions}. + */ + private static Pubsub.Builder newPubsubClient(PubsubOptions options) { + return new Pubsub.Builder(Transport.getTransport(), Transport.getJsonFactory(), + chainHttpRequestInitializer( + options.getGcpCredential(), + // Do not log 404. It clutters the output and is possibly even required by the caller. + new RetryHttpRequestInitializer(ImmutableList.of(404)))) + .setRootUrl(options.getPubsubRootUrl()) + .setApplicationName(options.getAppName()) + .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); + } + + private static HttpRequestInitializer chainHttpRequestInitializer( + Credentials credential, HttpRequestInitializer httpRequestInitializer) { + if (credential == null) { + return new ChainingHttpRequestInitializer( + new NullCredentialInitializer(), httpRequestInitializer); + } else { + return new ChainingHttpRequestInitializer( + new HttpCredentialsAdapter(credential), + httpRequestInitializer); + } + } + private void setupBigQueryTable(String projectId, String datasetId, String tableId, TableSchema schema) throws IOException { if (bigQueryClient == null) { - bigQueryClient = Transport.newBigQueryClient(options.as(BigQueryOptions.class)).build(); + bigQueryClient = newBigQueryClient(options.as(BigQueryOptions.class)).build(); } Datasets datasetService = bigQueryClient.datasets(); @@ -224,7 +278,7 @@ private void setupBigQueryTable(String projectId, String datasetId, String table private void setupPubsubTopic(String topic) throws IOException { if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); } if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) == null) { pubsubClient.projects().topics().create(topic, new Topic().setName(topic)).execute(); @@ -233,7 +287,7 @@ private void setupPubsubTopic(String topic) throws IOException { private void setupPubsubSubscription(String topic, String subscription) throws IOException { if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); } if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) == null) { Subscription subInfo = new Subscription() @@ -250,7 +304,7 @@ private void setupPubsubSubscription(String topic, String subscription) throws I */ private void deletePubsubTopic(String topic) throws IOException { if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); } if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) != null) { pubsubClient.projects().topics().delete(topic).execute(); @@ -264,7 +318,7 @@ private void deletePubsubTopic(String topic) throws IOException { */ private void deletePubsubSubscription(String subscription) throws IOException { if (pubsubClient == null) { - pubsubClient = Transport.newPubsubClient(options.as(PubsubOptions.class)).build(); + pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); } if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) != null) { pubsubClient.projects().subscriptions().delete(subscription).execute(); diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java new file mode 100644 index 0000000000..fc314b9d7b --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java @@ -0,0 +1,114 @@ +/* + * 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 ${package}.common; + +import static com.google.common.base.Verify.verifyNotNull; + +import javax.annotation.Nullable; +import org.apache.beam.sdk.io.FileBasedSink; +import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; +import org.apache.beam.sdk.io.fs.ResourceId; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PDone; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +/** + * A {@link DoFn} that writes elements to files with names deterministically derived from the lower + * and upper bounds of their key (an {@link IntervalWindow}). + * + *

              This is test utility code, not for end-users, so examples can be focused on their primary + * lessons. + */ +public class WriteOneFilePerWindow extends PTransform, PDone> { + private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.hourMinute(); + private String filenamePrefix; + @Nullable + private Integer numShards; + + public WriteOneFilePerWindow(String filenamePrefix, Integer numShards) { + this.filenamePrefix = filenamePrefix; + this.numShards = numShards; + } + + @Override + public PDone expand(PCollection input) { + // filenamePrefix may contain a directory and a filename component. Pull out only the filename + // component from that path for the PerWindowFiles. + String prefix = ""; + ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); + if (!resource.isDirectory()) { + prefix = verifyNotNull( + resource.getFilename(), + "A non-directory resource should have a non-null filename: %s", + resource); + } + + + TextIO.Write write = TextIO.write() + .to(resource.getCurrentDirectory()) + .withFilenamePolicy(new PerWindowFiles(prefix)) + .withWindowedWrites(); + if (numShards != null) { + write = write.withNumShards(numShards); + } + return input.apply(write); + } + + /** + * A {@link FilenamePolicy} produces a base file name for a write based on metadata about the data + * being written. This always includes the shard number and the total number of shards. For + * windowed writes, it also includes the window and pane index (a sequence number assigned to each + * trigger firing). + */ + public static class PerWindowFiles extends FilenamePolicy { + + private final String prefix; + + public PerWindowFiles(String prefix) { + this.prefix = prefix; + } + + public String filenamePrefixForWindow(IntervalWindow window) { + return String.format("%s-%s-%s", + prefix, FORMATTER.print(window.start()), FORMATTER.print(window.end())); + } + + @Override + public ResourceId windowedFilename( + ResourceId outputDirectory, WindowedContext context, String extension) { + IntervalWindow window = (IntervalWindow) context.getWindow(); + String filename = String.format( + "%s-%s-of-%s%s", + filenamePrefixForWindow(window), context.getShardNumber(), context.getNumShards(), + extension); + return outputDirectory.resolve(filename, StandardResolveOptions.RESOLVE_FILE); + } + + @Override + public ResourceId unwindowedFilename( + ResourceId outputDirectory, Context context, String extension) { + throw new UnsupportedOperationException("Unsupported."); + } + } +} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java deleted file mode 100644 index a08e6a9b0f..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteWindowedFilesDoFn.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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 ${package}.common; - -import com.google.common.annotations.VisibleForTesting; -import java.io.OutputStream; -import java.nio.channels.Channels; -import java.nio.charset.StandardCharsets; -import org.apache.beam.sdk.coders.Coder; -import org.apache.beam.sdk.coders.StringUtf8Coder; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.util.IOChannelFactory; -import org.apache.beam.sdk.util.IOChannelUtils; -import org.apache.beam.sdk.values.KV; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -/** - * A {@link DoFn} that writes elements to files with names deterministically derived from the lower - * and upper bounds of their key (an {@link IntervalWindow}). - * - *

              This is test utility code, not for end-users, so examples can be focused - * on their primary lessons. - */ -public class WriteWindowedFilesDoFn - extends DoFn>>, Void> { - - static final byte[] NEWLINE = "\n".getBytes(StandardCharsets.UTF_8); - static final Coder STRING_CODER = StringUtf8Coder.of(); - - private static DateTimeFormatter formatter = ISODateTimeFormat.hourMinute(); - - private final String output; - - public WriteWindowedFilesDoFn(String output) { - this.output = output; - } - - @VisibleForTesting - public static String fileForWindow(String output, IntervalWindow window) { - return String.format( - "%s-%s-%s", output, formatter.print(window.start()), formatter.print(window.end())); - } - - @ProcessElement - public void processElement(ProcessContext context) throws Exception { - // Build a file name from the window - IntervalWindow window = context.element().getKey(); - String outputShard = fileForWindow(output, window); - - // Open the file and write all the values - IOChannelFactory factory = IOChannelUtils.getFactory(outputShard); - OutputStream out = Channels.newOutputStream(factory.create(outputShard, "text/plain")); - for (KV wordCount : context.element().getValue()) { - STRING_CODER.encode( - wordCount.getKey() + ": " + wordCount.getValue(), out, Coder.Context.OUTER); - out.write(NEWLINE); - } - out.close(); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java index e9621032e5..b4e4124e26 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java @@ -24,8 +24,8 @@ import ${package}.WordCount.FormatAsTextFn; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.RunnableOnService; import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.testing.ValidatesRunner; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.DoFnTester; @@ -73,7 +73,7 @@ public void testExtractWordsFn() throws Exception { /** Example test that tests a PTransform by using an in-memory input and inspecting the output. */ @Test - @Category(RunnableOnService.class) + @Category(ValidatesRunner.class) public void testCountWords() throws Exception { PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 837c2afad2..98c39c2f53 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -37,22 +37,8 @@ - - - - org.apache.maven.plugins - maven-resources-plugin - - - @ - - false - - - - - + src/main/resources true @@ -60,6 +46,7 @@ archetype-resources/pom.xml + src/main/resources false @@ -68,5 +55,39 @@ + + + + + org.apache.maven.plugins + maven-resources-plugin + + + @ + + false + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + default-jar + none + + + default-test-jar + none + + + + diff --git a/pom.xml b/pom.xml index e6efd5c2d7..3db8b7cff0 100644 --- a/pom.xml +++ b/pom.xml @@ -95,7 +95,7 @@ - 3.0.3 + 3.2 @@ -103,7 +103,7 @@ ${maven.build.timestamp} yyyy-MM-dd HH:mm - 0.6.0 + 2.0.0 Google Cloud Dataflow SDK for Java ${project.version}-20170317 @@ -164,7 +164,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.0 + 3.6.1 1.7 1.7 @@ -254,7 +254,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.3 + 2.10.4 false @@ -294,7 +294,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + 2.20 From dfe74966052f98bafc7425e65b8e4aa4f10b6de2 Mon Sep 17 00:00:00 2001 From: Jason Kuster Date: Mon, 22 May 2017 22:31:52 -0700 Subject: [PATCH 715/751] [maven-release-plugin] prepare branch release-2.0.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3db8b7cff0..5957289ac4 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.0.0 From d40555732e08c272b30103b603d9518bd85eb69f Mon Sep 17 00:00:00 2001 From: Jason Kuster Date: Mon, 22 May 2017 22:32:01 -0700 Subject: [PATCH 716/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples-java8/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index f5ae58ad8a..aa7e2c7fe2 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta4-SNAPSHOT + 2.1.0-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples-java8/pom.xml b/maven-archetypes/examples-java8/pom.xml index b9ae4738d9..c88a2c90b2 100644 --- a/maven-archetypes/examples-java8/pom.xml +++ b/maven-archetypes/examples-java8/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.0.0-beta4-SNAPSHOT + 2.1.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 8c16f5e547..5a389df83b 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.0.0-beta4-SNAPSHOT + 2.1.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 98c39c2f53..083654bf2e 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta4-SNAPSHOT + 2.1.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 5832a55772..e8cc2e3bac 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.0.0-beta4-SNAPSHOT + 2.1.0-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index 5957289ac4..db89ee4386 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.0.0-beta4-SNAPSHOT + 2.1.0-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.0.0 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index 14b8061c1b..8513702e47 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.0.0-beta4-SNAPSHOT + 2.1.0-SNAPSHOT google-cloud-dataflow-java-sdk-all From f671e6aaa372fa724bd326156677a7a85af62187 Mon Sep 17 00:00:00 2001 From: jasonkuster Date: Tue, 23 May 2017 10:31:16 -0700 Subject: [PATCH 717/751] Update versioning after cutting 2.0.0 release branch. (#574) * Update archetype versioning after cutting 2.0.0 release branch. Signed-off-by: Jason Kuster * Update worker container image for 2.1.0-SNAPSHOT. Signed-off-by: Jason Kuster * Pin all versions to project version. Signed-off-by: Jason Kuster --- .../src/main/resources/archetype-resources/pom.xml | 2 +- .../src/main/resources/archetype-resources/pom.xml | 2 +- .../src/main/resources/archetype-resources/pom.xml | 2 +- pom.xml | 9 +-------- 4 files changed, 4 insertions(+), 11 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml index 275e2581a2..baa1508b2b 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml @@ -136,7 +136,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - @archetype.sdk_version_dependency@ + @project.version@ diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 83165d572c..fbf5994c53 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -136,7 +136,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - @archetype.sdk_version_dependency@ + @project.version@ diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index e7f2e59c1f..a92f922f24 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -72,7 +72,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-all - @archetype.sdk_version_dependency@ + @project.version@ diff --git a/pom.xml b/pom.xml index db89ee4386..db4451e1e6 100644 --- a/pom.xml +++ b/pom.xml @@ -106,15 +106,8 @@ 2.0.0 Google Cloud Dataflow SDK for Java - ${project.version}-20170317 + ${project.version}-20170517 6 - - - 2.0.0-beta4-SNAPSHOT pom From e08f5c0a18422afba35ba34ec7d27f0a49ea0313 Mon Sep 17 00:00:00 2001 From: Dan Halperin Date: Tue, 23 May 2017 11:46:07 -0700 Subject: [PATCH 718/751] dataflow.properties: update for new configuration in Apache Beam 2.0.0 See https://github.com/apache/beam/commit/b6508977e56e18903f2224e3a2a4ad9816ea1c89\#diff-2dcc904003e8cbcbf02e330b8be4c7db --- pom.xml | 3 ++- .../org/apache/beam/runners/dataflow/dataflow.properties | 7 +++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index db4451e1e6..de3af83152 100644 --- a/pom.xml +++ b/pom.xml @@ -107,7 +107,8 @@ Google Cloud Dataflow SDK for Java ${project.version}-20170517 - 6 + 6 + 1 pom diff --git a/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties b/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties index d499ad6699..699990047c 100644 --- a/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties +++ b/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow.properties @@ -12,7 +12,6 @@ # License for the specific language governing permissions and limitations under # the License. -environment.major.version=${dataflow.environment_major_version} - -worker.image.batch=dataflow.gcr.io/v1beta3/beam-java-batch:${dataflow.container_version} -worker.image.streaming=dataflow.gcr.io/v1beta3/beam-java-streaming:${dataflow.container_version} +legacy.environment.major.version=${dataflow.legacy_environment_major_version} +fnapi.environment.major.version=${dataflow.fnapi_environment_major_version} +container.version=${dataflow.container_version} From 7cdb503880682c2c4765d58f2ce791ad5134d306 Mon Sep 17 00:00:00 2001 From: Davor Bonaci Date: Tue, 30 May 2017 16:12:15 -0700 Subject: [PATCH 719/751] Update README.md for Dataflow SDK 2.0.0 release (#578) Update README.md for Dataflow SDK 2.0.0 release --- README.md | 80 +++++++++++++++++++++++-------------------------------- 1 file changed, 33 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index a644049218..112df59d01 100644 --- a/README.md +++ b/README.md @@ -27,10 +27,11 @@ underlying source code is hosted in the [Apache Beam repository](https://github.com/apache/beam). [General usage](https://cloud.google.com/dataflow/getting-started) of Google -Cloud Dataflow does **not** require use of this repository. Instead: +Cloud Dataflow does **not** require use of this repository. Instead, you can do +any one of the following: -1. depend directly on a specific -[version](https://cloud.google.com/dataflow/release-notes/java) of the SDK in +1. Depend directly on a specific +[version](https://cloud.google.com/dataflow/downloads) of the SDK in the [Maven Central Repository](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.google.cloud.dataflow%22) by adding the following dependency to development environments like Eclipse or Apache Maven: @@ -41,69 +42,52 @@ environments like Eclipse or Apache Maven: version_number -1. download the example pipelines from the separate +1. Download the example pipelines from the separate [DataflowJavaSDK-examples](https://github.com/GoogleCloudPlatform/DataflowJavaSDK-examples) repository. - +[Cloud Dataflow Plugin for Eclipse](https://cloud.google.com/dataflow/docs/quickstarts/quickstart-java-eclipse) +provides tools to create and execute Dataflow pipelines inside Eclipse. -## Status [![Build Status](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK.svg?branch=v2)](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK) +## Status [![Build Status](https://api.travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK) -This branch is a work-in-progress for the Dataflow SDK for Java, version 2.0.0. -It is currently supported on the Cloud Dataflow service in Beta. +Both the SDK and the Dataflow Service are generally available and considered +stable and fully qualified for production use. - +This [`master`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/) branch +contains code to build Dataflow SDK 2.0.0 and newer, as a distribution of Apache +Beam. Pre-Beam SDKs, versions 1.x, are maintained in the +[`master-1.x`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master-1.x) +branch. ## Overview The key concepts in this programming model are: -* [`PCollection`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/values/PCollection.java): -represents a collection of data, which could be bounded or unbounded in size. -* [`PTransform`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/PTransform.java): -represents a computation that transforms input PCollections into output -PCollections. -* [`Pipeline`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/Pipeline.java): -manages a directed acyclic graph of PTransforms and PCollections that is ready -for execution. -* [`PipelineRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/PipelineRunner.java): -specifies where and how the pipeline should execute. +* `PCollection`: represents a collection of data, which could be bounded or +unbounded in size. +* `PTransform`: represents a computation that transforms input PCollections +into output PCollections. +* `Pipeline`: manages a directed acyclic graph of PTransforms and PCollections +that is ready for execution. +* `PipelineRunner`: specifies where and how the pipeline should execute. We provide two runners: - 1. The [`DirectRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DirectPipelineRunner.java) -runs the pipeline on your local machine. - 1. The [`DataflowRunner`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/DataflowPipelineRunner.java) -submits the pipeline to the Dataflow Service, where it runs using managed -resources in the [Google Cloud Platform](https://cloud.google.com) (GCP). + 1. The `DirectRunner` runs the pipeline on your local machine. + 1. The `DataflowRunner` submits the pipeline to the Cloud Dataflow Service, +where it runs using managed resources in the +[Google Cloud Platform](https://cloud.google.com). The SDK is built to be extensible and support additional execution environments beyond local execution and the Google Cloud Dataflow Service. Apache Beam -contains additional SDKs, runners, IO connectors, etc. +contains additional SDKs, runners, and IO connectors. ## Getting Started -This repository consists of the following parts: - -* The [`sdk`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/sdk) -module provides a set of basic Java APIs to program against. -* The [`examples`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples) -module provides a few samples to get started. We recommend starting with the -`WordCount` example. - -The following command will build both the `sdk` and `example` modules and -install them in your local Maven repository: - - mvn clean install - -After building and installing, you can execute the `WordCount` and other -example pipelines by following the instructions in this -[README](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/blob/master/examples/README.md). +Please try our [Quickstarts](https://cloud.google.com/dataflow/docs/quickstarts). ## Contact Us @@ -117,5 +101,7 @@ on GitHub to report any bugs, comments or questions regarding SDK development. * [Google Cloud Dataflow](https://cloud.google.com/dataflow/) * [Apache Beam](https://beam.apache.org/) -* [Dataflow Concepts and Programming Model](https://cloud.google.com/dataflow/model/programming-model) -* [Java API Reference](https://cloud.google.com/dataflow/java-sdk/JavaDoc/index) +* [Dataflow Concepts and Programming Model](https://beam.apache.org/documentation/programming-guide/) +* [Java API Reference](https://beam.apache.org/documentation/sdks/javadoc/) + +_Apache, Apache Beam and the orange letter B logo are either registered trademarks or trademarks of the Apache Software Foundation in the United States and/or other countries._ From 3b9f029d3ad209fd8b29ce1c3786e214b232d590 Mon Sep 17 00:00:00 2001 From: Bill Neubauer Date: Wed, 23 Aug 2017 12:48:27 -0700 Subject: [PATCH 720/751] Update to Apache Beam, v2.1.0. --- .../src/main/resources/archetype-resources/pom.xml | 5 +++-- .../src/test/java/complete/game/LeaderBoardTest.java | 2 ++ .../examples/src/main/resources/archetype-resources/pom.xml | 5 +++-- .../starter/src/main/resources/archetype-resources/pom.xml | 4 ++-- .../src/test/resources/projects/basic/reference/pom.xml | 4 ++-- pom.xml | 2 +- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml index baa1508b2b..f33914d476 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml @@ -49,7 +49,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.5.1 + 3.6.1 1.8 1.8 @@ -79,6 +79,7 @@ org.apache.maven.plugins maven-jar-plugin + 3.0.2 + -Xlint:-processing true @@ -181,18 +185,29 @@ checkstyle 6.19 + + org.apache.beam + beam-sdks-java-build-tools + ${beam.version} + - sdk/checkstyle.xml + beam/checkstyle.xml sdk/suppressions.xml true true - true + false true + - verify + test-compile check @@ -425,6 +440,13 @@ beam-examples-java8 ${beam.version} + + + junit + junit + ${junit.version} + test + diff --git a/sdk/checkstyle.xml b/sdk/checkstyle.xml deleted file mode 100644 index 1769c8bed9..0000000000 --- a/sdk/checkstyle.xml +++ /dev/null @@ -1,458 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sdk/pom.xml b/sdk/pom.xml index 1e86beaf72..33f2255f82 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -60,5 +60,11 @@ org.apache.beam beam-runners-google-cloud-dataflow-java + + + junit + junit + test + diff --git a/sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java b/sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java index 44aa72285a..5088a00cfc 100644 --- a/sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java +++ b/sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2017 Google Inc. + * + * Licensed 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.beam.runners.dataflow; import static org.junit.Assert.assertEquals; @@ -26,8 +41,8 @@ public class DataflowRunnerInfoOverrideTest { @Test public void testDataflowDistributionOverride() throws Exception { - try (InputStream in - = DataflowRunnerInfo.class.getResourceAsStream(DATAFLOW_DISTRIBUTION_PROPERTIES_PATH)) { + try (InputStream in = + DataflowRunnerInfo.class.getResourceAsStream(DATAFLOW_DISTRIBUTION_PROPERTIES_PATH)) { Properties properties = new Properties(); properties.load(in); diff --git a/sdk/suppressions.xml b/sdk/suppressions.xml index c3635c9bb8..4d707ab291 100644 --- a/sdk/suppressions.xml +++ b/sdk/suppressions.xml @@ -19,9 +19,8 @@ "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> - - - + + From 053003a277d34b5afce70f281e8673c8dd2fdd1f Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Tue, 26 Sep 2017 17:31:48 -0700 Subject: [PATCH 725/751] Update Dataflow archetypes to be compatible with Apache Beam 2.2.0 changes. --- .../java/common/WriteOneFilePerWindow.java | 85 +++++++++-------- .../java/complete/game/utils/WriteToText.java | 95 +++++++++---------- .../java/common/WriteOneFilePerWindow.java | 59 ++++++------ 3 files changed, 122 insertions(+), 117 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java index fc314b9d7b..59b6ce3015 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java @@ -17,21 +17,24 @@ */ package ${package}.common; -import static com.google.common.base.Verify.verifyNotNull; + import static com.google.common.base.MoreObjects.firstNonNull; -import javax.annotation.Nullable; -import org.apache.beam.sdk.io.FileBasedSink; -import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; -import org.apache.beam.sdk.io.fs.ResourceId; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PDone; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; + import javax.annotation.Nullable; + import org.apache.beam.sdk.io.FileBasedSink; + import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; + import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; + import org.apache.beam.sdk.io.TextIO; + import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; + import org.apache.beam.sdk.io.fs.ResourceId; + import org.apache.beam.sdk.transforms.DoFn; + import org.apache.beam.sdk.transforms.PTransform; + import org.apache.beam.sdk.transforms.windowing.BoundedWindow; + import org.apache.beam.sdk.transforms.windowing.IntervalWindow; + import org.apache.beam.sdk.transforms.windowing.PaneInfo; + import org.apache.beam.sdk.values.PCollection; + import org.apache.beam.sdk.values.PDone; + import org.joda.time.format.DateTimeFormatter; + import org.joda.time.format.ISODateTimeFormat; /** * A {@link DoFn} that writes elements to files with names deterministically derived from the lower @@ -53,22 +56,12 @@ public WriteOneFilePerWindow(String filenamePrefix, Integer numShards) { @Override public PDone expand(PCollection input) { - // filenamePrefix may contain a directory and a filename component. Pull out only the filename - // component from that path for the PerWindowFiles. - String prefix = ""; ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); - if (!resource.isDirectory()) { - prefix = verifyNotNull( - resource.getFilename(), - "A non-directory resource should have a non-null filename: %s", - resource); - } - - - TextIO.Write write = TextIO.write() - .to(resource.getCurrentDirectory()) - .withFilenamePolicy(new PerWindowFiles(prefix)) - .withWindowedWrites(); + TextIO.Write write = + TextIO.write() + .to(new PerWindowFiles(resource)) + .withTempDirectory(resource.getCurrentDirectory()) + .withWindowedWrites(); if (numShards != null) { write = write.withNumShards(numShards); } @@ -83,31 +76,41 @@ public PDone expand(PCollection input) { */ public static class PerWindowFiles extends FilenamePolicy { - private final String prefix; + private final ResourceId baseFilename; - public PerWindowFiles(String prefix) { - this.prefix = prefix; + public PerWindowFiles(ResourceId baseFilename) { + this.baseFilename = baseFilename; } public String filenamePrefixForWindow(IntervalWindow window) { + String prefix = + baseFilename.isDirectory() ? "" : firstNonNull(baseFilename.getFilename(), ""); return String.format("%s-%s-%s", prefix, FORMATTER.print(window.start()), FORMATTER.print(window.end())); } @Override - public ResourceId windowedFilename( - ResourceId outputDirectory, WindowedContext context, String extension) { - IntervalWindow window = (IntervalWindow) context.getWindow(); - String filename = String.format( - "%s-%s-of-%s%s", - filenamePrefixForWindow(window), context.getShardNumber(), context.getNumShards(), - extension); - return outputDirectory.resolve(filename, StandardResolveOptions.RESOLVE_FILE); + public ResourceId windowedFilename(int shardNumber, + int numShards, + BoundedWindow window, + PaneInfo paneInfo, + OutputFileHints outputFileHints) { + IntervalWindow intervalWindow = (IntervalWindow) window; + String filename = + String.format( + "%s-%s-of-%s%s", + filenamePrefixForWindow(intervalWindow), + shardNumber, + numShards, + outputFileHints.getSuggestedFilenameSuffix()); + return baseFilename + .getCurrentDirectory() + .resolve(filename, StandardResolveOptions.RESOLVE_FILE); } @Override public ResourceId unwindowedFilename( - ResourceId outputDirectory, Context context, String extension) { + int shardNumber, int numShards, OutputFileHints outputFileHints) { throw new UnsupportedOperationException("Unsupported."); } } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java index 6d4e1399b3..c5828996ad 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java @@ -17,30 +17,31 @@ */ package ${package}.complete.game.utils; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Verify.verifyNotNull; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; -import java.util.stream.Collectors; -import org.apache.beam.sdk.io.FileBasedSink; -import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; -import org.apache.beam.sdk.io.fs.ResourceId; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PDone; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; + import static com.google.common.base.Preconditions.checkArgument; + + import java.io.Serializable; + import java.util.ArrayList; + import java.util.List; + import java.util.Map; + import java.util.TimeZone; + import java.util.stream.Collectors; + import org.apache.beam.sdk.io.FileBasedSink; + import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; + import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; + import org.apache.beam.sdk.io.TextIO; + import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; + import org.apache.beam.sdk.io.fs.ResourceId; + import org.apache.beam.sdk.transforms.DoFn; + import org.apache.beam.sdk.transforms.PTransform; + import org.apache.beam.sdk.transforms.ParDo; + import org.apache.beam.sdk.transforms.windowing.BoundedWindow; + import org.apache.beam.sdk.transforms.windowing.IntervalWindow; + import org.apache.beam.sdk.transforms.windowing.PaneInfo; + import org.apache.beam.sdk.values.PCollection; + import org.apache.beam.sdk.values.PDone; + import org.joda.time.DateTimeZone; + import org.joda.time.format.DateTimeFormat; + import org.joda.time.format.DateTimeFormatter; /** * Generate, format, and write rows. Use provided information about the field names and types, as @@ -111,21 +112,12 @@ public PDone expand(PCollection input) { checkArgument( input.getWindowingStrategy().getWindowFn().windowCoder() == IntervalWindow.getCoder()); - // filenamePrefix may contain a directory and a filename component. Pull out only the filename - // component from that path for the PerWindowFiles. - String prefix = ""; ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); - if (!resource.isDirectory()) { - prefix = verifyNotNull( - resource.getFilename(), - "A non-directory resource should have a non-null filename: %s", - resource); - } return input.apply( TextIO.write() - .to(resource.getCurrentDirectory()) - .withFilenamePolicy(new PerWindowFiles(prefix)) + .to(new PerWindowFiles(resource)) + .withTempDirectory(resource.getCurrentDirectory()) .withWindowedWrites() .withNumShards(3)); } @@ -139,31 +131,38 @@ public PDone expand(PCollection input) { */ protected static class PerWindowFiles extends FilenamePolicy { - private final String prefix; + private final ResourceId prefix; - public PerWindowFiles(String prefix) { + public PerWindowFiles(ResourceId prefix) { this.prefix = prefix; } public String filenamePrefixForWindow(IntervalWindow window) { - return String.format("%s-%s-%s", - prefix, formatter.print(window.start()), formatter.print(window.end())); + String filePrefix = prefix.isDirectory() ? "" : prefix.getFilename(); + return String.format( + "%s-%s-%s", filePrefix, formatter.print(window.start()), formatter.print(window.end())); } @Override - public ResourceId windowedFilename( - ResourceId outputDirectory, WindowedContext context, String extension) { - IntervalWindow window = (IntervalWindow) context.getWindow(); - String filename = String.format( - "%s-%s-of-%s%s", - filenamePrefixForWindow(window), context.getShardNumber(), context.getNumShards(), - extension); - return outputDirectory.resolve(filename, StandardResolveOptions.RESOLVE_FILE); + public ResourceId windowedFilename(int shardNumber, + int numShards, + BoundedWindow window, + PaneInfo paneInfo, + OutputFileHints outputFileHints) { + IntervalWindow intervalWindow = (IntervalWindow) window; + String filename = + String.format( + "%s-%s-of-%s%s", + filenamePrefixForWindow(intervalWindow), + shardNumber, + numShards, + outputFileHints.getSuggestedFilenameSuffix()); + return prefix.getCurrentDirectory().resolve(filename, StandardResolveOptions.RESOLVE_FILE); } @Override public ResourceId unwindowedFilename( - ResourceId outputDirectory, Context context, String extension) { + int shardNumber, int numShards, OutputFileHints outputFileHints) { throw new UnsupportedOperationException("Unsupported."); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java index fc314b9d7b..9796d647b5 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java @@ -17,17 +17,20 @@ */ package ${package}.common; -import static com.google.common.base.Verify.verifyNotNull; +import static com.google.common.base.MoreObjects.firstNonNull; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileBasedSink; import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; +import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; import org.apache.beam.sdk.io.fs.ResourceId; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PDone; import org.joda.time.format.DateTimeFormatter; @@ -53,22 +56,12 @@ public WriteOneFilePerWindow(String filenamePrefix, Integer numShards) { @Override public PDone expand(PCollection input) { - // filenamePrefix may contain a directory and a filename component. Pull out only the filename - // component from that path for the PerWindowFiles. - String prefix = ""; ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); - if (!resource.isDirectory()) { - prefix = verifyNotNull( - resource.getFilename(), - "A non-directory resource should have a non-null filename: %s", - resource); - } - - - TextIO.Write write = TextIO.write() - .to(resource.getCurrentDirectory()) - .withFilenamePolicy(new PerWindowFiles(prefix)) - .withWindowedWrites(); + TextIO.Write write = + TextIO.write() + .to(new PerWindowFiles(resource)) + .withTempDirectory(resource.getCurrentDirectory()) + .withWindowedWrites(); if (numShards != null) { write = write.withNumShards(numShards); } @@ -83,31 +76,41 @@ public PDone expand(PCollection input) { */ public static class PerWindowFiles extends FilenamePolicy { - private final String prefix; + private final ResourceId baseFilename; - public PerWindowFiles(String prefix) { - this.prefix = prefix; + public PerWindowFiles(ResourceId baseFilename) { + this.baseFilename = baseFilename; } public String filenamePrefixForWindow(IntervalWindow window) { + String prefix = + baseFilename.isDirectory() ? "" : firstNonNull(baseFilename.getFilename(), ""); return String.format("%s-%s-%s", prefix, FORMATTER.print(window.start()), FORMATTER.print(window.end())); } @Override - public ResourceId windowedFilename( - ResourceId outputDirectory, WindowedContext context, String extension) { - IntervalWindow window = (IntervalWindow) context.getWindow(); - String filename = String.format( - "%s-%s-of-%s%s", - filenamePrefixForWindow(window), context.getShardNumber(), context.getNumShards(), - extension); - return outputDirectory.resolve(filename, StandardResolveOptions.RESOLVE_FILE); + public ResourceId windowedFilename(int shardNumber, + int numShards, + BoundedWindow window, + PaneInfo paneInfo, + OutputFileHints outputFileHints) { + IntervalWindow intervalWindow = (IntervalWindow) window; + String filename = + String.format( + "%s-%s-of-%s%s", + filenamePrefixForWindow(intervalWindow), + shardNumber, + numShards, + outputFileHints.getSuggestedFilenameSuffix()); + return baseFilename + .getCurrentDirectory() + .resolve(filename, StandardResolveOptions.RESOLVE_FILE); } @Override public ResourceId unwindowedFilename( - ResourceId outputDirectory, Context context, String extension) { + int shardNumber, int numShards, OutputFileHints outputFileHints) { throw new UnsupportedOperationException("Unsupported."); } } From 9f5fef097989c64372af4a22dda76c54fc0a2506 Mon Sep 17 00:00:00 2001 From: Luke Cwik Date: Thu, 28 Sep 2017 09:08:20 -0700 Subject: [PATCH 726/751] fixup! Address PR comments. --- .../java/common/WriteOneFilePerWindow.java | 34 ++++++------- .../java/complete/game/utils/WriteToText.java | 50 +++++++++---------- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java index 59b6ce3015..c7296162b6 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java @@ -17,24 +17,24 @@ */ package ${package}.common; - import static com.google.common.base.MoreObjects.firstNonNull; +import static com.google.common.base.MoreObjects.firstNonNull; - import javax.annotation.Nullable; - import org.apache.beam.sdk.io.FileBasedSink; - import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; - import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; - import org.apache.beam.sdk.io.TextIO; - import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; - import org.apache.beam.sdk.io.fs.ResourceId; - import org.apache.beam.sdk.transforms.DoFn; - import org.apache.beam.sdk.transforms.PTransform; - import org.apache.beam.sdk.transforms.windowing.BoundedWindow; - import org.apache.beam.sdk.transforms.windowing.IntervalWindow; - import org.apache.beam.sdk.transforms.windowing.PaneInfo; - import org.apache.beam.sdk.values.PCollection; - import org.apache.beam.sdk.values.PDone; - import org.joda.time.format.DateTimeFormatter; - import org.joda.time.format.ISODateTimeFormat; +import javax.annotation.Nullable; +import org.apache.beam.sdk.io.FileBasedSink; +import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; +import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; +import org.apache.beam.sdk.io.fs.ResourceId; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PDone; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; /** * A {@link DoFn} that writes elements to files with names deterministically derived from the lower diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java index c5828996ad..7d8d19f70d 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java @@ -17,31 +17,31 @@ */ package ${package}.complete.game.utils; - import static com.google.common.base.Preconditions.checkArgument; - - import java.io.Serializable; - import java.util.ArrayList; - import java.util.List; - import java.util.Map; - import java.util.TimeZone; - import java.util.stream.Collectors; - import org.apache.beam.sdk.io.FileBasedSink; - import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; - import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; - import org.apache.beam.sdk.io.TextIO; - import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; - import org.apache.beam.sdk.io.fs.ResourceId; - import org.apache.beam.sdk.transforms.DoFn; - import org.apache.beam.sdk.transforms.PTransform; - import org.apache.beam.sdk.transforms.ParDo; - import org.apache.beam.sdk.transforms.windowing.BoundedWindow; - import org.apache.beam.sdk.transforms.windowing.IntervalWindow; - import org.apache.beam.sdk.transforms.windowing.PaneInfo; - import org.apache.beam.sdk.values.PCollection; - import org.apache.beam.sdk.values.PDone; - import org.joda.time.DateTimeZone; - import org.joda.time.format.DateTimeFormat; - import org.joda.time.format.DateTimeFormatter; +import static com.google.common.base.Preconditions.checkArgument; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.stream.Collectors; +import org.apache.beam.sdk.io.FileBasedSink; +import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; +import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; +import org.apache.beam.sdk.io.TextIO; +import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; +import org.apache.beam.sdk.io.fs.ResourceId; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PDone; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; /** * Generate, format, and write rows. Use provided information about the field names and types, as From c45ff300ad12b8a625ed81fd5a42a0549456fd4a Mon Sep 17 00:00:00 2001 From: Bill Neubauer Date: Thu, 5 Oct 2017 15:08:59 -0700 Subject: [PATCH 727/751] Refactor versioning information for archetypes. This makes versioning consistent with the Beam POMs. The top-level POM contains the version numbers, and versions are plumbed into the archetypes via properties. --- .../resources/archetype-resources/pom.xml | 47 ++++++++++++------- .../resources/archetype-resources/pom.xml | 44 +++++++++++------ .../resources/archetype-resources/pom.xml | 11 +++-- .../projects/basic/reference/pom.xml | 11 +++-- pom.xml | 13 +++++ 5 files changed, 87 insertions(+), 39 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml index f33914d476..12d2783a0f 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml @@ -27,7 +27,22 @@ UTF-8 - 2.20 + + @bigquery.version@ + @google-clients.version@ + @guava.version@ + @hamcrest.version@ + @jackson.version@ + @joda.version@ + @junit.version@ + @maven-compiler-plugin.version@ + @maven-exec-plugin.version@ + @maven-jar-plugin.version@ + @maven-shade-plugin.version@ + @mockito.version@ + @pubsub.version@ + @slf4j.version@ + @surefire-plugin.version@ @@ -49,7 +64,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + ${maven-compiler-plugin.version} 1.8 1.8 @@ -79,7 +94,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.0.2 + ${maven-jar-plugin.version} @@ -158,7 +173,7 @@ com.google.apis google-api-services-bigquery - v2-rev295-1.22.0 + ${bigquery.version} @@ -172,7 +187,7 @@ com.google.http-client google-http-client - 1.22.0 + ${google-clients.version} @@ -186,7 +201,7 @@ com.google.apis google-api-services-pubsub - v1-rev10-1.22.0 + ${pubsub.version} @@ -200,26 +215,26 @@ joda-time joda-time - 2.4 + ${joda.version} com.google.guava guava - 20.0 + ${guava.version} org.slf4j slf4j-api - 1.7.14 + ${slf4j.version} org.slf4j slf4j-jdk14 - 1.7.14 + ${slf4j.version} runtime @@ -229,19 +244,19 @@ org.hamcrest hamcrest-all - 1.3 + ${hamcrest.version} junit junit - 4.12 + ${junit.version} org.mockito mockito-all - 1.9.5 + ${mockito.version} test diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 28ae0db9fe..2c2b8d3fc6 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -27,7 +27,21 @@ UTF-8 - 2.20 + + @bigquery.version@ + @google-clients.version@ + @guava.version@ + @hamcrest.version@ + @jackson.version@ + @joda.version@ + @junit.version@ + @maven-compiler-plugin.version@ + @maven-exec-plugin.version@ + @maven-jar-plugin.version@ + @maven-shade-plugin.version@ + @pubsub.version@ + @slf4j.version@ + @surefire-plugin.version@ @@ -49,7 +63,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + ${maven-compiler-plugin.version} ${targetPlatform} ${targetPlatform} @@ -79,7 +93,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.0.2 + ${maven-jar-plugin.version} @@ -158,7 +172,7 @@ com.google.apis google-api-services-bigquery - v2-rev295-1.22.0 + ${bigquery.version} @@ -172,7 +186,7 @@ com.google.http-client google-http-client - 1.22.0 + ${google-clients.version} @@ -186,7 +200,7 @@ com.google.apis google-api-services-pubsub - v1-rev10-1.22.0 + ${pubsub.version} @@ -200,26 +214,26 @@ joda-time joda-time - 2.4 + ${joda.version} com.google.guava guava - 20.0 + ${guava.version} org.slf4j slf4j-api - 1.7.14 + ${slf4j.version} org.slf4j slf4j-jdk14 - 1.7.14 + ${slf4j.version} runtime @@ -229,13 +243,13 @@ org.hamcrest hamcrest-all - 1.3 + ${hamcrest.version} junit junit - 4.12 + ${junit.version} diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index 75eaaade81..22f717f97a 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -25,6 +25,9 @@ UTF-8 + @maven-compiler-plugin.version@ + @maven-exec-plugin.version@ + @slf4j.version@ @@ -46,7 +49,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + ${maven-compiler-plugin.version} ${targetPlatform} ${targetPlatform} @@ -59,7 +62,7 @@ org.codehaus.mojo exec-maven-plugin - 1.5.0 + ${maven-exec-plugin.version} false @@ -79,12 +82,12 @@ org.slf4j slf4j-api - 1.7.14 + ${slf4j.version} org.slf4j slf4j-jdk14 - 1.7.14 + ${slf4j.version} diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index fc0940bf2d..8e4edbd29e 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -25,6 +25,9 @@ UTF-8 + @maven-compiler-plugin.version@ + @maven-exec-plugin.version@ + @slf4j.version@ @@ -46,7 +49,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + ${maven-compiler-plugin.version} 1.7 1.7 @@ -59,7 +62,7 @@ org.codehaus.mojo exec-maven-plugin - 1.5.0 + ${maven-exec-plugin.version} false @@ -79,12 +82,12 @@ org.slf4j slf4j-api - 1.7.14 + ${slf4j.version} org.slf4j slf4j-jdk14 - 1.7.14 + ${slf4j.version} diff --git a/pom.xml b/pom.xml index f9a662c658..a54ec1c5e9 100644 --- a/pom.xml +++ b/pom.xml @@ -110,7 +110,20 @@ 6 1 + v2-rev295-1.22.0 + 1.22.0 + 20.0 + 1.3 + 2.4 4.12 + 3.6.1 + 1.4.0 + 3.0.2 + 3.0.0 + 1.9.5 + v1-rev10-1.22.0 + 1.7.14 + 2.20 pom From 63cd3ae0c0ed1c6f4b820759d5666be27f241c29 Mon Sep 17 00:00:00 2001 From: Bill Neubauer Date: Wed, 11 Oct 2017 11:56:07 -0700 Subject: [PATCH 728/751] Set executor version to 1.5.0 Leaving the executor version where it was, rather than changing it to match Beam. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a54ec1c5e9..e4b917f0cf 100644 --- a/pom.xml +++ b/pom.xml @@ -117,7 +117,7 @@ 2.4 4.12 3.6.1 - 1.4.0 + 1.5.0 3.0.2 3.0.0 1.9.5 From 8a1b42be31802e40571566dc285bf1b37f6555bd Mon Sep 17 00:00:00 2001 From: Kenneth Knowles Date: Wed, 6 Dec 2017 15:13:20 -0800 Subject: [PATCH 729/751] Upgrade Beam to version 2.2.0 --- .../src/main/java/WordCount.java | 4 ++++ .../main/java/common/WriteOneFilePerWindow.java | 8 ++++---- .../java/complete/game/injector/Injector.java | 2 +- .../complete/game/injector/InjectorUtils.java | 2 +- .../java/complete/game/utils/WriteToText.java | 8 ++++---- .../src/test/java/DebuggingWordCountTest.java | 11 +++++++++-- .../src/main/java/WordCount.java | 4 ++++ .../src/test/java/DebuggingWordCountTest.java | 11 +++++++++-- pom.xml | 15 ++++++++------- 9 files changed, 44 insertions(+), 21 deletions(-) diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java index 79b71403b9..9947a26eda 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -21,6 +21,7 @@ import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.Distribution; import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; @@ -88,9 +89,12 @@ public class WordCount { */ static class ExtractWordsFn extends DoFn { private final Counter emptyLines = Metrics.counter(ExtractWordsFn.class, "emptyLines"); + private final Distribution lineLenDist = Metrics.distribution( + ExtractWordsFn.class, "lineLenDistro"); @ProcessElement public void processElement(ProcessContext c) { + lineLenDist.update(c.element().length()); if (c.element().trim().isEmpty()) { emptyLines.inc(); } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java index c7296162b6..9796d647b5 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java @@ -91,10 +91,10 @@ public String filenamePrefixForWindow(IntervalWindow window) { @Override public ResourceId windowedFilename(int shardNumber, - int numShards, - BoundedWindow window, - PaneInfo paneInfo, - OutputFileHints outputFileHints) { + int numShards, + BoundedWindow window, + PaneInfo paneInfo, + OutputFileHints outputFileHints) { IntervalWindow intervalWindow = (IntervalWindow) window; String filename = String.format( diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java index 4814ffb66f..980966e0ce 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java @@ -167,7 +167,7 @@ long getStartTimeInMillis() { return startTimeInMillis; } long getEndTimeInMillis() { - return startTimeInMillis + (expirationPeriod * 60 * 1000); + return startTimeInMillis + (expirationPeriod * 60L * 1000L); } String getRandomUser() { int userNum = random.nextInt(numMembers); diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java index 55e8c7a8c3..ddcbff4f41 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java @@ -93,7 +93,7 @@ public static void createTopic(Pubsub client, String fullTopicName) Topic topic = client.projects().topics() .create(fullTopicName, new Topic()) .execute(); - System.out.printf("Topic %s was created.\n", topic.getName()); + System.out.printf("Topic %s was created.%n", topic.getName()); } } } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java index 7d8d19f70d..dbd5e39977 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java @@ -145,10 +145,10 @@ public String filenamePrefixForWindow(IntervalWindow window) { @Override public ResourceId windowedFilename(int shardNumber, - int numShards, - BoundedWindow window, - PaneInfo paneInfo, - OutputFileHints outputFileHints) { + int numShards, + BoundedWindow window, + PaneInfo paneInfo, + OutputFileHints outputFileHints) { IntervalWindow intervalWindow = (IntervalWindow) window; String filename = String.format( diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java index 155242d996..26e1498d71 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java +++ b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java @@ -35,6 +35,13 @@ public class DebuggingWordCountTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); + private String getFilePath(String filePath) { + if (filePath.contains(":")) { + return filePath.replace("\\", "/").split(":")[1]; + } + return filePath; + } + @Test public void testDebuggingWordCount() throws Exception { File inputFile = tmpFolder.newFile(); @@ -45,8 +52,8 @@ public void testDebuggingWordCount() throws Exception { StandardCharsets.UTF_8); WordCountOptions options = TestPipeline.testingPipelineOptions().as(WordCountOptions.class); - options.setInputFile(inputFile.getAbsolutePath()); - options.setOutput(outputFile.getAbsolutePath()); + options.setInputFile(getFilePath(inputFile.getAbsolutePath())); + options.setOutput(getFilePath(outputFile.getAbsolutePath())); DebuggingWordCount.main(TestPipeline.convertToArgs(options)); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java index 79b71403b9..9947a26eda 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -21,6 +21,7 @@ import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.Distribution; import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; @@ -88,9 +89,12 @@ public class WordCount { */ static class ExtractWordsFn extends DoFn { private final Counter emptyLines = Metrics.counter(ExtractWordsFn.class, "emptyLines"); + private final Distribution lineLenDist = Metrics.distribution( + ExtractWordsFn.class, "lineLenDistro"); @ProcessElement public void processElement(ProcessContext c) { + lineLenDist.update(c.element().length()); if (c.element().trim().isEmpty()) { emptyLines.inc(); } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java index 155242d996..26e1498d71 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java @@ -35,6 +35,13 @@ public class DebuggingWordCountTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); + private String getFilePath(String filePath) { + if (filePath.contains(":")) { + return filePath.replace("\\", "/").split(":")[1]; + } + return filePath; + } + @Test public void testDebuggingWordCount() throws Exception { File inputFile = tmpFolder.newFile(); @@ -45,8 +52,8 @@ public void testDebuggingWordCount() throws Exception { StandardCharsets.UTF_8); WordCountOptions options = TestPipeline.testingPipelineOptions().as(WordCountOptions.class); - options.setInputFile(inputFile.getAbsolutePath()); - options.setOutput(outputFile.getAbsolutePath()); + options.setInputFile(getFilePath(inputFile.getAbsolutePath())); + options.setOutput(getFilePath(outputFile.getAbsolutePath())); DebuggingWordCount.main(TestPipeline.convertToArgs(options)); } } diff --git a/pom.xml b/pom.xml index e4b917f0cf..a3ce24f916 100644 --- a/pom.xml +++ b/pom.xml @@ -103,27 +103,28 @@ ${maven.build.timestamp} yyyy-MM-dd HH:mm - 2.2.0-SNAPSHOT + 2.2.0 Google Cloud Dataflow SDK for Java ${project.version}-20170517 6 1 - v2-rev295-1.22.0 + v2-rev355-1.22.0 1.22.0 20.0 1.3 2.4 4.12 - 3.6.1 - 1.5.0 - 3.0.2 - 3.0.0 1.9.5 v1-rev10-1.22.0 - 1.7.14 + 1.7.25 + 2.20 + 3.6.2 + 1.6.0 + 3.0.2 + 3.0.0 pom From a363bb33af4a8de572de15c1344fbc3e4133220a Mon Sep 17 00:00:00 2001 From: Batkhuyag Batsaikhan Date: Mon, 26 Feb 2018 17:51:59 -0800 Subject: [PATCH 730/751] Upgrade to Apache Beam, version 2.3.0 --- examples/pom.xml | 5 - .../dataflow/sdk/ExamplesDependencies.java | 4 +- maven-archetypes/examples-java8/pom.xml | 80 ---- .../META-INF/maven/archetype-metadata.xml | 38 -- .../examples-java8/src/main/resources/NOTICE | 5 - .../resources/archetype-resources/pom.xml | 263 ------------ .../src/main/java/DebuggingWordCount.java | 162 ------- .../src/main/java/MinimalWordCount.java | 119 ----- .../src/main/java/MinimalWordCountJava8.java | 72 ---- .../src/main/java/WindowedWordCount.java | 223 ---------- .../src/main/java/WordCount.java | 190 -------- .../common/ExampleBigQueryTableOptions.java | 55 --- ...mplePubsubTopicAndSubscriptionOptions.java | 45 -- .../common/ExamplePubsubTopicOptions.java | 45 -- .../src/main/java/common/ExampleUtils.java | 406 ------------------ .../java/common/WriteOneFilePerWindow.java | 117 ----- .../src/test/java/DebuggingWordCountTest.java | 59 --- .../src/test/java/WordCountTest.java | 86 ---- .../projects/basic/archetype.properties | 19 - .../test/resources/projects/basic/goal.txt | 1 - maven-archetypes/examples/pom.xml | 6 +- .../META-INF/maven/archetype-metadata.xml | 2 +- .../resources/archetype-resources/pom.xml | 13 +- .../src/main/java/MinimalWordCount.java | 88 ++-- .../src/main/java/WindowedWordCount.java | 7 +- .../src/main/java/WordCount.java | 3 +- .../src/main/java/common/ExampleUtils.java | 63 +-- .../main/java/complete/game/GameStats.java | 172 ++++---- .../java/complete/game/HourlyTeamScore.java | 80 ++-- .../main/java/complete/game/LeaderBoard.java | 50 +-- .../java/complete/game/StatefulTeamScore.java | 227 ++++++++++ .../main/java/complete/game/UserScore.java | 18 +- .../java/complete/game/injector/Injector.java | 91 ++-- .../complete/game/injector/InjectorUtils.java | 0 .../injector/RetryHttpInitializerWrapper.java | 42 +- .../complete/game/utils/GameConstants.java} | 26 +- .../complete/game/utils/WriteToBigQuery.java | 0 .../java/complete/game/utils/WriteToText.java | 2 +- .../game/utils/WriteWindowedToBigQuery.java | 0 .../src/test/java/MinimalWordCountTest.java} | 57 +-- .../src/test/java/WordCountTest.java | 3 +- .../java/complete/game/GameStatsTest.java | 0 .../complete/game/HourlyTeamScoreTest.java | 0 .../java/complete/game/LeaderBoardTest.java | 16 +- .../complete/game/StatefulTeamScoreTest.java | 208 +++++++++ .../java/complete/game/UserScoreTest.java | 0 .../projects/basic/archetype.properties | 2 +- maven-archetypes/pom.xml | 1 - maven-archetypes/starter/pom.xml | 6 +- .../META-INF/maven/archetype-metadata.xml | 2 +- .../projects/basic/archetype.properties | 2 +- .../projects/basic/reference/pom.xml | 4 +- pom.xml | 85 ++-- 53 files changed, 840 insertions(+), 2430 deletions(-) delete mode 100644 maven-archetypes/examples-java8/pom.xml delete mode 100644 maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml delete mode 100644 maven-archetypes/examples-java8/src/main/resources/NOTICE delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java delete mode 100644 maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java delete mode 100644 maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties delete mode 100644 maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java (68%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java (75%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java (87%) create mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java (94%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java (89%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java (100%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java (71%) rename maven-archetypes/{examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java => examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java} (55%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java (100%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java (99%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java (100%) rename maven-archetypes/{examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java => examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java} (61%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java (100%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java (100%) rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java (97%) create mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java rename maven-archetypes/{examples-java8 => examples}/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java (100%) diff --git a/examples/pom.xml b/examples/pom.xml index f87ae36b1d..75a1d92174 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -42,10 +42,5 @@ org.apache.beam beam-examples-java - - - org.apache.beam - beam-examples-java8 - diff --git a/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java b/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java index 827aff8395..c51e527edb 100644 --- a/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java +++ b/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java @@ -15,7 +15,7 @@ */ package com.google.cloud.dataflow.sdk; -import org.apache.beam.examples.MinimalWordCountJava8; +import org.apache.beam.examples.MinimalWordCount; import org.apache.beam.examples.WordCount; /** @@ -25,5 +25,5 @@ class ExamplesDependencies { SdkDependencies sdkDependencies; WordCount wordCount; - MinimalWordCountJava8 minimalWordCount; + MinimalWordCount minimalWordCount; } diff --git a/maven-archetypes/examples-java8/pom.xml b/maven-archetypes/examples-java8/pom.xml deleted file mode 100644 index 463c66f1d1..0000000000 --- a/maven-archetypes/examples-java8/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - 4.0.0 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-archetypes-parent - 2.2.0-SNAPSHOT - ../pom.xml - - - google-cloud-dataflow-java-archetypes-examples-java8 - Google Cloud Dataflow SDK for Java - Java 8 Examples Archetype - Google Cloud Dataflow SDK for Java is a distribution of Apache - Beam designed to simplify usage of Apache Beam on Google Cloud Dataflow - service. This archetype creates a project containing all the example - pipelines targeting Java 8. - - maven-archetype - - - - - org.apache.maven.archetype - archetype-packaging - 2.4 - - - - - - - maven-archetype-plugin - 2.4 - - - org.apache.maven.shared - maven-invoker - 2.2 - - - - - - default-integration-test - install - - integration-test - - - - - - - - - - diff --git a/maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml deleted file mode 100644 index 326fdaa528..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/META-INF/maven/archetype-metadata.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - src/main/java - - **/*.java - - - - - src/test/java - - **/*.java - - - - diff --git a/maven-archetypes/examples-java8/src/main/resources/NOTICE b/maven-archetypes/examples-java8/src/main/resources/NOTICE deleted file mode 100644 index 981fde5a9e..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Google Cloud Dataflow SDK for Java -Copyright 2017, Google Inc. - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml deleted file mode 100644 index 12d2783a0f..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml +++ /dev/null @@ -1,263 +0,0 @@ - - - - 4.0.0 - - ${groupId} - ${artifactId} - ${version} - - jar - - - UTF-8 - - @bigquery.version@ - @google-clients.version@ - @guava.version@ - @hamcrest.version@ - @jackson.version@ - @joda.version@ - @junit.version@ - @maven-compiler-plugin.version@ - @maven-exec-plugin.version@ - @maven-jar-plugin.version@ - @maven-shade-plugin.version@ - @mockito.version@ - @pubsub.version@ - @slf4j.version@ - @surefire-plugin.version@ - - - - - ossrh.snapshots - Sonatype OSS Repository Hosting - https://oss.sonatype.org/content/repositories/snapshots/ - - false - - - true - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire-plugin.version} - - all - 4 - true - - - - org.apache.maven.surefire - surefire-junit47 - ${surefire-plugin.version} - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - - package - - shade - - - ${project.artifactId}-bundled-${project.version} - - - *:* - - META-INF/LICENSE - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${maven-exec-plugin.version} - - false - - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - @project.version@ - - - - - com.google.api-client - google-api-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-bigquery - ${bigquery.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.http-client - google-http-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-pubsub - ${pubsub.version} - - - - com.google.guava - guava-jdk5 - - - - - - joda-time - joda-time - ${joda.version} - - - - com.google.guava - guava - ${guava.version} - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - - runtime - - - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - - - - junit - junit - ${junit.version} - - - - org.mockito - mockito-all - ${mockito.version} - test - - - diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java deleted file mode 100644 index 07870f2ed0..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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 ${package}; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.metrics.Counter; -import org.apache.beam.sdk.metrics.Metrics; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * An example that verifies word counts in Shakespeare and includes Beam best practices. - * - *

              This class, {@link DebuggingWordCount}, is the third in a series of four successively more - * detailed 'word count' examples. You may first want to take a look at {@link MinimalWordCount} - * and {@link WordCount}. After you've looked at this example, then see the - * {@link WindowedWordCount} pipeline, for introduction of additional concepts. - * - *

              Basic concepts, also in the MinimalWordCount and WordCount examples: - * Reading text files; counting a PCollection; executing a Pipeline both locally - * and using a selected runner; defining DoFns. - * - *

              New Concepts: - *

              - *   1. Logging using SLF4J, even in a distributed environment
              - *   2. Creating a custom metric (runners have varying levels of support)
              - *   3. Testing your Pipeline via PAssert
              - * 
              - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * - *

              To change the runner, specify: - *

              {@code
              - *   --runner=YOUR_SELECTED_RUNNER
              - * }
              - * 
              - * - *

              The input file defaults to a public data set containing the text of of King Lear, - * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. - * - */ -public class DebuggingWordCount { - /** A DoFn that filters for a specific key based upon a regular expression. */ - public static class FilterTextFn extends DoFn, KV> { - /** - * Concept #1: The logger below uses the fully qualified class name of FilterTextFn as the - * logger. Depending on your SLF4J configuration, log statements will likely be qualified by - * this name. - * - *

              Note that this is entirely standard SLF4J usage. Some runners may provide a default SLF4J - * configuration that is most appropriate for their logging integration. - */ - private static final Logger LOG = LoggerFactory.getLogger(FilterTextFn.class); - - private final Pattern filter; - public FilterTextFn(String pattern) { - filter = Pattern.compile(pattern); - } - - /** - * Concept #2: A custom metric can track values in your pipeline as it runs. Each - * runner provides varying levels of support for metrics, and may expose them - * in a dashboard, etc. - */ - private final Counter matchedWords = Metrics.counter(FilterTextFn.class, "matchedWords"); - private final Counter unmatchedWords = Metrics.counter(FilterTextFn.class, "unmatchedWords"); - - @ProcessElement - public void processElement(ProcessContext c) { - if (filter.matcher(c.element().getKey()).matches()) { - // Log at the "DEBUG" level each element that we match. When executing this pipeline - // these log lines will appear only if the log level is set to "DEBUG" or lower. - LOG.debug("Matched: " + c.element().getKey()); - matchedWords.inc(); - c.output(c.element()); - } else { - // Log at the "TRACE" level each element that is not matched. Different log levels - // can be used to control the verbosity of logging providing an effective mechanism - // to filter less important information. - LOG.trace("Did not match: " + c.element().getKey()); - unmatchedWords.inc(); - } - } - } - - /** - * Options supported by {@link DebuggingWordCount}. - * - *

              Inherits standard configuration options and all options defined in - * {@link WordCount.WordCountOptions}. - */ - public interface WordCountOptions extends WordCount.WordCountOptions { - - @Description("Regex filter pattern to use in DebuggingWordCount. " - + "Only words matching this pattern will be counted.") - @Default.String("Flourish|stomach") - String getFilterPattern(); - void setFilterPattern(String value); - } - - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); - Pipeline p = Pipeline.create(options); - - PCollection> filteredWords = - p.apply("ReadLines", TextIO.read().from(options.getInputFile())) - .apply(new WordCount.CountWords()) - .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); - - /** - * Concept #3: PAssert is a set of convenient PTransforms in the style of - * Hamcrest's collection matchers that can be used when writing Pipeline level tests - * to validate the contents of PCollections. PAssert is best used in unit tests - * with small data sets but is demonstrated here as a teaching tool. - * - *

              Below we verify that the set of filtered words matches our expected counts. Note - * that PAssert does not provide any output and that successful completion of the - * Pipeline implies that the expectations were met. Learn more at - * https://beam.apache.org/documentation/pipelines/test-your-pipeline/ on how to test - * your Pipeline and see {@link DebuggingWordCountTest} for an example unit test. - */ - List> expectedResults = Arrays.asList( - KV.of("Flourish", 3L), - KV.of("stomach", 1L)); - PAssert.that(filteredWords).containsInAnyOrder(expectedResults); - - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java deleted file mode 100644 index d6b08066db..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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 ${package}; - -import ${package}.common.ExampleUtils; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.Count; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.SimpleFunction; -import org.apache.beam.sdk.values.KV; - - -/** - * An example that counts words in Shakespeare. - * - *

              This class, {@link MinimalWordCount}, is the first in a series of four successively more - * detailed 'word count' examples. Here, for simplicity, we don't show any error-checking or - * argument processing, and focus on construction of the pipeline, which chains together the - * application of core transforms. - * - *

              Next, see the {@link WordCount} pipeline, then the {@link DebuggingWordCount}, and finally the - * {@link WindowedWordCount} pipeline, for more detailed examples that introduce additional - * concepts. - * - *

              Concepts: - * - *

              - *   1. Reading data from text files
              - *   2. Specifying 'inline' transforms
              - *   3. Counting items in a PCollection
              - *   4. Writing data to text files
              - * 
              - * - *

              No arguments are required to run this pipeline. It will be executed with the DirectRunner. You - * can see the results in the output files in your current working directory, with names like - * "wordcounts-00001-of-00005. When running on a distributed service, you would use an appropriate - * file service. - */ -public class MinimalWordCount { - - public static void main(String[] args) { - // Create a PipelineOptions object. This object lets us set various execution - // options for our pipeline, such as the runner you wish to use. This example - // will run with the DirectRunner by default, based on the class path configured - // in its dependencies. - PipelineOptions options = PipelineOptionsFactory.create(); - - // Create the Pipeline object with the options we defined above. - Pipeline p = Pipeline.create(options); - - // Apply the pipeline's transforms. - - // Concept #1: Apply a root transform to the pipeline; in this case, TextIO.Read to read a set - // of input text files. TextIO.Read returns a PCollection where each element is one line from - // the input text (a set of Shakespeare's texts). - - // This example reads a public data set consisting of the complete works of Shakespeare. - p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) - - // Concept #2: Apply a ParDo transform to our PCollection of text lines. This ParDo invokes a - // DoFn (defined in-line) on each element that tokenizes the text line into individual words. - // The ParDo returns a PCollection, where each element is an individual word in - // Shakespeare's collected texts. - .apply("ExtractWords", ParDo.of(new DoFn() { - @ProcessElement - public void processElement(ProcessContext c) { - for (String word : c.element().split(ExampleUtils.TOKENIZER_PATTERN)) { - if (!word.isEmpty()) { - c.output(word); - } - } - } - })) - - // Concept #3: Apply the Count transform to our PCollection of individual words. The Count - // transform returns a new PCollection of key/value pairs, where each key represents a unique - // word in the text. The associated value is the occurrence count for that word. - .apply(Count.perElement()) - - // Apply a MapElements transform that formats our PCollection of word counts into a printable - // string, suitable for writing to an output file. - .apply("FormatResults", MapElements.via(new SimpleFunction, String>() { - @Override - public String apply(KV input) { - return input.getKey() + ": " + input.getValue(); - } - })) - - // Concept #4: Apply a write transform, TextIO.Write, at the end of the pipeline. - // TextIO.Write writes the contents of a PCollection (in this case, our PCollection of - // formatted strings) to a series of text files. - // - // By default, it will write to a set of files with names like wordcount-00001-of-00005 - .apply(TextIO.write().to("wordcounts")); - - // Run the pipeline. - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java deleted file mode 100644 index e635a885b7..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/MinimalWordCountJava8.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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 ${package}; - -import java.util.Arrays; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.Count; -import org.apache.beam.sdk.transforms.Filter; -import org.apache.beam.sdk.transforms.FlatMapElements; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.TypeDescriptors; - -/** - * An example that counts words in Shakespeare, using Java 8 language features. - * - *

              See {@link MinimalWordCount} for a comprehensive explanation. - */ -public class MinimalWordCountJava8 { - - public static void main(String[] args) { - PipelineOptions options = PipelineOptionsFactory.create(); - // In order to run your pipeline, you need to make following runner specific changes: - // - // CHANGE 1/3: Select a Beam runner, such as BlockingDataflowRunner - // or FlinkRunner. - // CHANGE 2/3: Specify runner-required options. - // For BlockingDataflowRunner, set project and temp location as follows: - // DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - // dataflowOptions.setRunner(BlockingDataflowRunner.class); - // dataflowOptions.setProject("SET_YOUR_PROJECT_ID_HERE"); - // dataflowOptions.setTempLocation("gs://SET_YOUR_BUCKET_NAME_HERE/AND_TEMP_DIRECTORY"); - // For FlinkRunner, set the runner as follows. See {@code FlinkPipelineOptions} - // for more details. - // options.as(FlinkPipelineOptions.class) - // .setRunner(FlinkRunner.class); - - Pipeline p = Pipeline.create(options); - - p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) - .apply(FlatMapElements - .into(TypeDescriptors.strings()) - .via((String word) -> Arrays.asList(word.split("[^\\p{L}]+")))) - .apply(Filter.by((String word) -> !word.isEmpty())) - .apply(Count.perElement()) - .apply(MapElements - .into(TypeDescriptors.strings()) - .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue())) - // CHANGE 3/3: The Google Cloud Storage path is required for outputting the results to. - .apply(TextIO.write().to("gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX")); - - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java deleted file mode 100644 index 6a1d07c485..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * 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 ${package}; - -import java.io.IOException; -import java.util.concurrent.ThreadLocalRandom; -import ${package}.common.ExampleBigQueryTableOptions; -import ${package}.common.ExampleOptions; -import ${package}.common.WriteOneFilePerWindow; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.FixedWindows; -import org.apache.beam.sdk.transforms.windowing.Window; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.joda.time.Duration; -import org.joda.time.Instant; - - -/** - * An example that counts words in text, and can run over either unbounded or bounded input - * collections. - * - *

              This class, {@link WindowedWordCount}, is the last in a series of four successively more - * detailed 'word count' examples. First take a look at {@link MinimalWordCount}, - * {@link WordCount}, and {@link DebuggingWordCount}. - * - *

              Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples: - * Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally - * and using a selected runner; defining DoFns; - * user-defined PTransforms; defining PipelineOptions. - * - *

              New Concepts: - *

              - *   1. Unbounded and bounded pipeline input modes
              - *   2. Adding timestamps to data
              - *   3. Windowing
              - *   4. Re-using PTransforms over windowed PCollections
              - *   5. Accessing the window of an element
              - *   6. Writing data to per-window text files
              - * 
              - * - *

              By default, the examples will run with the {@code DirectRunner}. - * To change the runner, specify: - *

              {@code
              - *   --runner=YOUR_SELECTED_RUNNER
              - * }
              - * 
              - * See examples/java/README.md for instructions about how to configure different runners. - * - *

              To execute this pipeline locally, specify a local output file (if using the - * {@code DirectRunner}) or output prefix on a supported distributed file system. - *

              {@code
              - *   --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
              - * }
              - * - *

              The input file defaults to a public data set containing the text of of King Lear, - * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. - * - *

              By default, the pipeline will do fixed windowing, on 1-minute windows. You can - * change this interval by setting the {@code --windowSize} parameter, e.g. {@code --windowSize=10} - * for 10-minute windows. - * - *

              The example will try to cancel the pipeline on the signal to terminate the process (CTRL-C). - */ -public class WindowedWordCount { - static final int WINDOW_SIZE = 10; // Default window duration in minutes - /** - * Concept #2: A DoFn that sets the data element timestamp. This is a silly method, just for - * this example, for the bounded data case. - * - *

              Imagine that many ghosts of Shakespeare are all typing madly at the same time to recreate - * his masterworks. Each line of the corpus will get a random associated timestamp somewhere in a - * 2-hour period. - */ - static class AddTimestampFn extends DoFn { - private static final Duration RAND_RANGE = Duration.standardHours(1); - private final Instant minTimestamp; - private final Instant maxTimestamp; - - AddTimestampFn(Instant minTimestamp, Instant maxTimestamp) { - this.minTimestamp = minTimestamp; - this.maxTimestamp = maxTimestamp; - } - - @ProcessElement - public void processElement(ProcessContext c) { - Instant randomTimestamp = - new Instant( - ThreadLocalRandom.current() - .nextLong(minTimestamp.getMillis(), maxTimestamp.getMillis())); - - /** - * Concept #2: Set the data element with that timestamp. - */ - c.outputWithTimestamp(c.element(), new Instant(randomTimestamp)); - } - } - - /** A {@link DefaultValueFactory} that returns the current system time. */ - public static class DefaultToCurrentSystemTime implements DefaultValueFactory { - @Override - public Long create(PipelineOptions options) { - return System.currentTimeMillis(); - } - } - - /** A {@link DefaultValueFactory} that returns the minimum timestamp plus one hour. */ - public static class DefaultToMinTimestampPlusOneHour implements DefaultValueFactory { - @Override - public Long create(PipelineOptions options) { - return options.as(Options.class).getMinTimestampMillis() - + Duration.standardHours(1).getMillis(); - } - } - - /** - * Options for {@link WindowedWordCount}. - * - *

              Inherits standard example configuration options, which allow specification of the - * runner, as well as the {@link WordCount.WordCountOptions} support for - * specification of the input and output files. - */ - public interface Options extends WordCount.WordCountOptions, - ExampleOptions, ExampleBigQueryTableOptions { - @Description("Fixed window duration, in minutes") - @Default.Integer(WINDOW_SIZE) - Integer getWindowSize(); - void setWindowSize(Integer value); - - @Description("Minimum randomly assigned timestamp, in milliseconds-since-epoch") - @Default.InstanceFactory(DefaultToCurrentSystemTime.class) - Long getMinTimestampMillis(); - void setMinTimestampMillis(Long value); - - @Description("Maximum randomly assigned timestamp, in milliseconds-since-epoch") - @Default.InstanceFactory(DefaultToMinTimestampPlusOneHour.class) - Long getMaxTimestampMillis(); - void setMaxTimestampMillis(Long value); - - @Description("Fixed number of shards to produce per window, or null for runner-chosen sharding") - Integer getNumShards(); - void setNumShards(Integer numShards); - } - - public static void main(String[] args) throws IOException { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - final String output = options.getOutput(); - final Instant minTimestamp = new Instant(options.getMinTimestampMillis()); - final Instant maxTimestamp = new Instant(options.getMaxTimestampMillis()); - - Pipeline pipeline = Pipeline.create(options); - - /** - * Concept #1: the Beam SDK lets us run the same pipeline with either a bounded or - * unbounded input source. - */ - PCollection input = pipeline - /** Read from the GCS file. */ - .apply(TextIO.read().from(options.getInputFile())) - // Concept #2: Add an element timestamp, using an artificial time just to show windowing. - // See AddTimestampFn for more detail on this. - .apply(ParDo.of(new AddTimestampFn(minTimestamp, maxTimestamp))); - - /** - * Concept #3: Window into fixed windows. The fixed window size for this example defaults to 1 - * minute (you can change this with a command-line option). See the documentation for more - * information on how fixed windows work, and for information on the other types of windowing - * available (e.g., sliding windows). - */ - PCollection windowedWords = - input.apply( - Window.into( - FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); - - /** - * Concept #4: Re-use our existing CountWords transform that does not have knowledge of - * windows over a PCollection containing windowed values. - */ - PCollection> wordCounts = windowedWords.apply(new WordCount.CountWords()); - - /** - * Concept #5: Format the results and write to a sharded file partitioned by window, using a - * simple ParDo operation. Because there may be failures followed by retries, the - * writes must be idempotent, but the details of writing to files is elided here. - */ - wordCounts - .apply(MapElements.via(new WordCount.FormatAsTextFn())) - .apply(new WriteOneFilePerWindow(output, options.getNumShards())); - - PipelineResult result = pipeline.run(); - try { - result.waitUntilFinish(); - } catch (Exception exc) { - result.cancel(); - } - } - -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java deleted file mode 100644 index 9947a26eda..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * 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 ${package}; - -import ${package}.common.ExampleUtils; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.metrics.Counter; -import org.apache.beam.sdk.metrics.Distribution; -import org.apache.beam.sdk.metrics.Metrics; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.options.Validation.Required; -import org.apache.beam.sdk.transforms.Count; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.SimpleFunction; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; - -/** - * An example that counts words in Shakespeare and includes Beam best practices. - * - *

              This class, {@link WordCount}, is the second in a series of four successively more detailed - * 'word count' examples. You may first want to take a look at {@link MinimalWordCount}. - * After you've looked at this example, then see the {@link DebuggingWordCount} - * pipeline, for introduction of additional concepts. - * - *

              For a detailed walkthrough of this example, see - * - * https://beam.apache.org/get-started/wordcount-example/ - * - * - *

              Basic concepts, also in the MinimalWordCount example: - * Reading text files; counting a PCollection; writing to text files - * - *

              New Concepts: - *

              - *   1. Executing a Pipeline both locally and using the selected runner
              - *   2. Using ParDo with static DoFns defined out-of-line
              - *   3. Building a composite transform
              - *   4. Defining your own pipeline options
              - * 
              - * - *

              Concept #1: you can execute this pipeline either locally or using by selecting another runner. - * These are now command-line options and not hard-coded as they were in the MinimalWordCount - * example. - * - *

              To change the runner, specify: - *

              {@code
              - *   --runner=YOUR_SELECTED_RUNNER
              - * }
              - * 
              - * - *

              To execute this pipeline, specify a local output file (if using the - * {@code DirectRunner}) or output prefix on a supported distributed file system. - *

              {@code
              - *   --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
              - * }
              - * - *

              The input file defaults to a public data set containing the text of of King Lear, - * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. - */ -public class WordCount { - - /** - * Concept #2: You can make your pipeline assembly code less verbose by defining your DoFns - * statically out-of-line. This DoFn tokenizes lines of text into individual words; we pass it - * to a ParDo in the pipeline. - */ - static class ExtractWordsFn extends DoFn { - private final Counter emptyLines = Metrics.counter(ExtractWordsFn.class, "emptyLines"); - private final Distribution lineLenDist = Metrics.distribution( - ExtractWordsFn.class, "lineLenDistro"); - - @ProcessElement - public void processElement(ProcessContext c) { - lineLenDist.update(c.element().length()); - if (c.element().trim().isEmpty()) { - emptyLines.inc(); - } - - // Split the line into words. - String[] words = c.element().split(ExampleUtils.TOKENIZER_PATTERN); - - // Output each word encountered into the output PCollection. - for (String word : words) { - if (!word.isEmpty()) { - c.output(word); - } - } - } - } - - /** A SimpleFunction that converts a Word and Count into a printable string. */ - public static class FormatAsTextFn extends SimpleFunction, String> { - @Override - public String apply(KV input) { - return input.getKey() + ": " + input.getValue(); - } - } - - /** - * A PTransform that converts a PCollection containing lines of text into a PCollection of - * formatted word counts. - * - *

              Concept #3: This is a custom composite transform that bundles two transforms (ParDo and - * Count) as a reusable PTransform subclass. Using composite transforms allows for easy reuse, - * modular testing, and an improved monitoring experience. - */ - public static class CountWords extends PTransform, - PCollection>> { - @Override - public PCollection> expand(PCollection lines) { - - // Convert lines of text into individual words. - PCollection words = lines.apply( - ParDo.of(new ExtractWordsFn())); - - // Count the number of times each word occurs. - PCollection> wordCounts = - words.apply(Count.perElement()); - - return wordCounts; - } - } - - /** - * Options supported by {@link WordCount}. - * - *

              Concept #4: Defining your own configuration options. Here, you can add your own arguments - * to be processed by the command-line parser, and specify default values for them. You can then - * access the options values in your pipeline code. - * - *

              Inherits standard configuration options. - */ - public interface WordCountOptions extends PipelineOptions { - - /** - * By default, this example reads from a public dataset containing the text of - * King Lear. Set this option to choose a different input file or glob. - */ - @Description("Path of the file to read from") - @Default.String("gs://apache-beam-samples/shakespeare/kinglear.txt") - String getInputFile(); - void setInputFile(String value); - - /** - * Set this required option to specify where to write the output. - */ - @Description("Path of the file to write to") - @Required - String getOutput(); - void setOutput(String value); - } - - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); - Pipeline p = Pipeline.create(options); - - // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the - // static FormatAsTextFn() to the ParDo transform. - p.apply("ReadLines", TextIO.read().from(options.getInputFile())) - .apply(new CountWords()) - .apply(MapElements.via(new FormatAsTextFn())) - .apply("WriteCounts", TextIO.write().to(options.getOutput())); - - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java deleted file mode 100644 index 57f1546e27..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 ${package}.common; - -import com.google.api.services.bigquery.model.TableSchema; -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure BigQuery tables in Beam examples. - * The project defaults to the project being used to run the example. - */ -public interface ExampleBigQueryTableOptions extends GcpOptions { - @Description("BigQuery dataset name") - @Default.String("beam_examples") - String getBigQueryDataset(); - void setBigQueryDataset(String dataset); - - @Description("BigQuery table name") - @Default.InstanceFactory(BigQueryTableFactory.class) - String getBigQueryTable(); - void setBigQueryTable(String table); - - @Description("BigQuery table schema") - TableSchema getBigQuerySchema(); - void setBigQuerySchema(TableSchema schema); - - /** - * Returns the job name as the default BigQuery table name. - */ - class BigQueryTableFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return options.getJobName().replace('-', '_'); - } - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java deleted file mode 100644 index cf142a10fd..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 ${package}.common; - -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure Pub/Sub topic/subscription in Beam examples. - */ -public interface ExamplePubsubTopicAndSubscriptionOptions extends ExamplePubsubTopicOptions { - @Description("Pub/Sub subscription") - @Default.InstanceFactory(PubsubSubscriptionFactory.class) - String getPubsubSubscription(); - void setPubsubSubscription(String subscription); - - /** - * Returns a default Pub/Sub subscription based on the project and the job names. - */ - class PubsubSubscriptionFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return "projects/" + options.as(GcpOptions.class).getProject() - + "/subscriptions/" + options.getJobName(); - } - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java deleted file mode 100644 index 86784b06da..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 ${package}.common; - -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure Pub/Sub topic in Beam examples. - */ -public interface ExamplePubsubTopicOptions extends GcpOptions { - @Description("Pub/Sub topic") - @Default.InstanceFactory(PubsubTopicFactory.class) - String getPubsubTopic(); - void setPubsubTopic(String topic); - - /** - * Returns a default Pub/Sub topic based on the project and the job names. - */ - class PubsubTopicFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return "projects/" + options.as(GcpOptions.class).getProject() - + "/topics/" + options.getJobName(); - } - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java deleted file mode 100644 index 78f3849b40..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * 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 ${package}.common; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.Bigquery.Datasets; -import com.google.api.services.bigquery.Bigquery.Tables; -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.DatasetReference; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.Subscription; -import com.google.api.services.pubsub.model.Topic; -import com.google.auth.Credentials; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.common.util.concurrent.Uninterruptibles; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.extensions.gcp.auth.NullCredentialInitializer; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryOptions; -import org.apache.beam.sdk.io.gcp.pubsub.PubsubOptions; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.util.BackOff; -import org.apache.beam.sdk.util.BackOffUtils; -import org.apache.beam.sdk.util.FluentBackoff; -import org.apache.beam.sdk.util.RetryHttpRequestInitializer; -import org.apache.beam.sdk.util.Sleeper; -import org.apache.beam.sdk.util.Transport; -import org.joda.time.Duration; - -/** - * The utility class that sets up and tears down external resources, - * and cancels the streaming pipelines once the program terminates. - * - *

              It is used to run Beam examples. - */ -public class ExampleUtils { - - private static final int SC_NOT_FOUND = 404; - - /** - * \p{L} denotes the category of Unicode letters, - * so this pattern will match on everything that is not a letter. - * - *

              It is used for tokenizing strings in the wordcount examples. - */ - public static final String TOKENIZER_PATTERN = "[^\\p{L}]+"; - - private final PipelineOptions options; - private Bigquery bigQueryClient = null; - private Pubsub pubsubClient = null; - private Set pipelinesToCancel = Sets.newHashSet(); - private List pendingMessages = Lists.newArrayList(); - - /** - * Do resources and runner options setup. - */ - public ExampleUtils(PipelineOptions options) { - this.options = options; - } - - /** - * Sets up external resources that are required by the example, - * such as Pub/Sub topics and BigQuery tables. - * - * @throws IOException if there is a problem setting up the resources - */ - public void setup() throws IOException { - Sleeper sleeper = Sleeper.DEFAULT; - BackOff backOff = - FluentBackoff.DEFAULT - .withMaxRetries(3).withInitialBackoff(Duration.millis(200)).backoff(); - Throwable lastException = null; - try { - do { - try { - setupPubsub(); - setupBigQueryTable(); - return; - } catch (GoogleJsonResponseException e) { - lastException = e; - } - } while (BackOffUtils.next(sleeper, backOff)); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - // Ignore InterruptedException - } - throw new RuntimeException(lastException); - } - - /** - * Sets up the Google Cloud Pub/Sub topic. - * - *

              If the topic doesn't exist, a new topic with the given name will be created. - * - * @throws IOException if there is a problem setting up the Pub/Sub topic - */ - public void setupPubsub() throws IOException { - ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = - options.as(ExamplePubsubTopicAndSubscriptionOptions.class); - if (!pubsubOptions.getPubsubTopic().isEmpty()) { - pendingMessages.add("**********************Set Up Pubsub************************"); - setupPubsubTopic(pubsubOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been set up for this example: " - + pubsubOptions.getPubsubTopic()); - - if (!pubsubOptions.getPubsubSubscription().isEmpty()) { - setupPubsubSubscription( - pubsubOptions.getPubsubTopic(), pubsubOptions.getPubsubSubscription()); - pendingMessages.add("The Pub/Sub subscription has been set up for this example: " - + pubsubOptions.getPubsubSubscription()); - } - } - } - - /** - * Sets up the BigQuery table with the given schema. - * - *

              If the table already exists, the schema has to match the given one. Otherwise, the example - * will throw a RuntimeException. If the table doesn't exist, a new table with the given schema - * will be created. - * - * @throws IOException if there is a problem setting up the BigQuery table - */ - public void setupBigQueryTable() throws IOException { - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("******************Set Up Big Query Table*******************"); - setupBigQueryTable(bigQueryTableOptions.getProject(), - bigQueryTableOptions.getBigQueryDataset(), - bigQueryTableOptions.getBigQueryTable(), - bigQueryTableOptions.getBigQuerySchema()); - pendingMessages.add("The BigQuery table has been set up for this example: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - } - } - - /** - * Tears down external resources that can be deleted upon the example's completion. - */ - private void tearDown() { - pendingMessages.add("*************************Tear Down*************************"); - ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = - options.as(ExamplePubsubTopicAndSubscriptionOptions.class); - if (!pubsubOptions.getPubsubTopic().isEmpty()) { - try { - deletePubsubTopic(pubsubOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been deleted: " - + pubsubOptions.getPubsubTopic()); - } catch (IOException e) { - pendingMessages.add("Failed to delete the Pub/Sub topic : " - + pubsubOptions.getPubsubTopic()); - } - if (!pubsubOptions.getPubsubSubscription().isEmpty()) { - try { - deletePubsubSubscription(pubsubOptions.getPubsubSubscription()); - pendingMessages.add("The Pub/Sub subscription has been deleted: " - + pubsubOptions.getPubsubSubscription()); - } catch (IOException e) { - pendingMessages.add("Failed to delete the Pub/Sub subscription : " - + pubsubOptions.getPubsubSubscription()); - } - } - } - - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("The BigQuery table might contain the example's output, " - + "and it is not deleted automatically: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - pendingMessages.add("Please go to the Developers Console to delete it manually." - + " Otherwise, you may be charged for its usage."); - } - } - - /** - * Returns a BigQuery client builder using the specified {@link BigQueryOptions}. - */ - private static Bigquery.Builder newBigQueryClient(BigQueryOptions options) { - return new Bigquery.Builder(Transport.getTransport(), Transport.getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - /** - * Returns a Pubsub client builder using the specified {@link PubsubOptions}. - */ - private static Pubsub.Builder newPubsubClient(PubsubOptions options) { - return new Pubsub.Builder(Transport.getTransport(), Transport.getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setRootUrl(options.getPubsubRootUrl()) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - private static HttpRequestInitializer chainHttpRequestInitializer( - Credentials credential, HttpRequestInitializer httpRequestInitializer) { - if (credential == null) { - return new ChainingHttpRequestInitializer( - new NullCredentialInitializer(), httpRequestInitializer); - } else { - return new ChainingHttpRequestInitializer( - new HttpCredentialsAdapter(credential), - httpRequestInitializer); - } - } - - private void setupBigQueryTable(String projectId, String datasetId, String tableId, - TableSchema schema) throws IOException { - if (bigQueryClient == null) { - bigQueryClient = newBigQueryClient(options.as(BigQueryOptions.class)).build(); - } - - Datasets datasetService = bigQueryClient.datasets(); - if (executeNullIfNotFound(datasetService.get(projectId, datasetId)) == null) { - Dataset newDataset = new Dataset().setDatasetReference( - new DatasetReference().setProjectId(projectId).setDatasetId(datasetId)); - datasetService.insert(projectId, newDataset).execute(); - } - - Tables tableService = bigQueryClient.tables(); - Table table = executeNullIfNotFound(tableService.get(projectId, datasetId, tableId)); - if (table == null) { - Table newTable = new Table().setSchema(schema).setTableReference( - new TableReference().setProjectId(projectId).setDatasetId(datasetId).setTableId(tableId)); - tableService.insert(projectId, datasetId, newTable).execute(); - } else if (!table.getSchema().equals(schema)) { - throw new RuntimeException( - "Table exists and schemas do not match, expecting: " + schema.toPrettyString() - + ", actual: " + table.getSchema().toPrettyString()); - } - } - - private void setupPubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) == null) { - pubsubClient.projects().topics().create(topic, new Topic().setName(topic)).execute(); - } - } - - private void setupPubsubSubscription(String topic, String subscription) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) == null) { - Subscription subInfo = new Subscription() - .setAckDeadlineSeconds(60) - .setTopic(topic); - pubsubClient.projects().subscriptions().create(subscription, subInfo).execute(); - } - } - - /** - * Deletes the Google Cloud Pub/Sub topic. - * - * @throws IOException if there is a problem deleting the Pub/Sub topic - */ - private void deletePubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) != null) { - pubsubClient.projects().topics().delete(topic).execute(); - } - } - - /** - * Deletes the Google Cloud Pub/Sub subscription. - * - * @throws IOException if there is a problem deleting the Pub/Sub subscription - */ - private void deletePubsubSubscription(String subscription) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) != null) { - pubsubClient.projects().subscriptions().delete(subscription).execute(); - } - } - - /** - * Waits for the pipeline to finish and cancels it before the program exists. - */ - public void waitToFinish(PipelineResult result) { - pipelinesToCancel.add(result); - if (!options.as(ExampleOptions.class).getKeepJobsRunning()) { - addShutdownHook(pipelinesToCancel); - } - try { - result.waitUntilFinish(); - } catch (UnsupportedOperationException e) { - // Do nothing if the given PipelineResult doesn't support waitUntilFinish(), - // such as EvaluationResults returned by DirectRunner. - tearDown(); - printPendingMessages(); - } catch (Exception e) { - throw new RuntimeException("Failed to wait the pipeline until finish: " + result); - } - } - - private void addShutdownHook(final Collection pipelineResults) { - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - tearDown(); - printPendingMessages(); - for (PipelineResult pipelineResult : pipelineResults) { - try { - pipelineResult.cancel(); - } catch (IOException e) { - System.out.println("Failed to cancel the job."); - System.out.println(e.getMessage()); - } - } - - for (PipelineResult pipelineResult : pipelineResults) { - boolean cancellationVerified = false; - for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { - if (pipelineResult.getState().isTerminal()) { - cancellationVerified = true; - break; - } else { - System.out.println( - "The example pipeline is still running. Verifying the cancellation."); - } - Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); - } - if (!cancellationVerified) { - System.out.println("Failed to verify the cancellation for job: " + pipelineResult); - } - } - } - }); - } - - private void printPendingMessages() { - System.out.println(); - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - for (String message : pendingMessages) { - System.out.println(message); - } - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - } - - private static T executeNullIfNotFound( - AbstractGoogleClientRequest request) throws IOException { - try { - return request.execute(); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == SC_NOT_FOUND) { - return null; - } else { - throw e; - } - } - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java deleted file mode 100644 index 9796d647b5..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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 ${package}.common; - -import static com.google.common.base.MoreObjects.firstNonNull; - -import javax.annotation.Nullable; -import org.apache.beam.sdk.io.FileBasedSink; -import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; -import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; -import org.apache.beam.sdk.io.fs.ResourceId; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.PaneInfo; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PDone; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -/** - * A {@link DoFn} that writes elements to files with names deterministically derived from the lower - * and upper bounds of their key (an {@link IntervalWindow}). - * - *

              This is test utility code, not for end-users, so examples can be focused on their primary - * lessons. - */ -public class WriteOneFilePerWindow extends PTransform, PDone> { - private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.hourMinute(); - private String filenamePrefix; - @Nullable - private Integer numShards; - - public WriteOneFilePerWindow(String filenamePrefix, Integer numShards) { - this.filenamePrefix = filenamePrefix; - this.numShards = numShards; - } - - @Override - public PDone expand(PCollection input) { - ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); - TextIO.Write write = - TextIO.write() - .to(new PerWindowFiles(resource)) - .withTempDirectory(resource.getCurrentDirectory()) - .withWindowedWrites(); - if (numShards != null) { - write = write.withNumShards(numShards); - } - return input.apply(write); - } - - /** - * A {@link FilenamePolicy} produces a base file name for a write based on metadata about the data - * being written. This always includes the shard number and the total number of shards. For - * windowed writes, it also includes the window and pane index (a sequence number assigned to each - * trigger firing). - */ - public static class PerWindowFiles extends FilenamePolicy { - - private final ResourceId baseFilename; - - public PerWindowFiles(ResourceId baseFilename) { - this.baseFilename = baseFilename; - } - - public String filenamePrefixForWindow(IntervalWindow window) { - String prefix = - baseFilename.isDirectory() ? "" : firstNonNull(baseFilename.getFilename(), ""); - return String.format("%s-%s-%s", - prefix, FORMATTER.print(window.start()), FORMATTER.print(window.end())); - } - - @Override - public ResourceId windowedFilename(int shardNumber, - int numShards, - BoundedWindow window, - PaneInfo paneInfo, - OutputFileHints outputFileHints) { - IntervalWindow intervalWindow = (IntervalWindow) window; - String filename = - String.format( - "%s-%s-of-%s%s", - filenamePrefixForWindow(intervalWindow), - shardNumber, - numShards, - outputFileHints.getSuggestedFilenameSuffix()); - return baseFilename - .getCurrentDirectory() - .resolve(filename, StandardResolveOptions.RESOLVE_FILE); - } - - @Override - public ResourceId unwindowedFilename( - int shardNumber, int numShards, OutputFileHints outputFileHints) { - throw new UnsupportedOperationException("Unsupported."); - } - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java deleted file mode 100644 index 26e1498d71..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 ${package}; - -import com.google.common.io.Files; -import java.io.File; -import java.nio.charset.StandardCharsets; -import ${package}.DebuggingWordCount.WordCountOptions; -import org.apache.beam.sdk.testing.TestPipeline; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link DebuggingWordCount}. - */ -@RunWith(JUnit4.class) -public class DebuggingWordCountTest { - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - - private String getFilePath(String filePath) { - if (filePath.contains(":")) { - return filePath.replace("\\", "/").split(":")[1]; - } - return filePath; - } - - @Test - public void testDebuggingWordCount() throws Exception { - File inputFile = tmpFolder.newFile(); - File outputFile = tmpFolder.newFile(); - Files.write( - "stomach secret Flourish message Flourish here Flourish", - inputFile, - StandardCharsets.UTF_8); - WordCountOptions options = - TestPipeline.testingPipelineOptions().as(WordCountOptions.class); - options.setInputFile(getFilePath(inputFile.getAbsolutePath())); - options.setOutput(getFilePath(outputFile.getAbsolutePath())); - DebuggingWordCount.main(TestPipeline.convertToArgs(options)); - } -} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java deleted file mode 100644 index b4e4124e26..0000000000 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/WordCountTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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 ${package}; - -import java.util.Arrays; -import java.util.List; -import ${package}.WordCount.CountWords; -import ${package}.WordCount.ExtractWordsFn; -import ${package}.WordCount.FormatAsTextFn; -import org.apache.beam.sdk.coders.StringUtf8Coder; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.testing.ValidatesRunner; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.DoFnTester; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.values.PCollection; -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests of WordCount. - */ -@RunWith(JUnit4.class) -public class WordCountTest { - - /** Example test that tests a specific {@link DoFn}. */ - @Test - public void testExtractWordsFn() throws Exception { - DoFnTester extractWordsFn = - DoFnTester.of(new ExtractWordsFn()); - - Assert.assertThat(extractWordsFn.processBundle(" some input words "), - CoreMatchers.hasItems("some", "input", "words")); - Assert.assertThat(extractWordsFn.processBundle(" "), - CoreMatchers.hasItems()); - Assert.assertThat(extractWordsFn.processBundle(" some ", " input", " words"), - CoreMatchers.hasItems("some", "input", "words")); - } - - static final String[] WORDS_ARRAY = new String[] { - "hi there", "hi", "hi sue bob", - "hi sue", "", "bob hi"}; - - static final List WORDS = Arrays.asList(WORDS_ARRAY); - - static final String[] COUNTS_ARRAY = new String[] { - "hi: 5", "there: 1", "sue: 2", "bob: 2"}; - - @Rule - public TestPipeline p = TestPipeline.create(); - - /** Example test that tests a PTransform by using an in-memory input and inspecting the output. */ - @Test - @Category(ValidatesRunner.class) - public void testCountWords() throws Exception { - PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); - - PCollection output = input.apply(new CountWords()) - .apply(MapElements.via(new FormatAsTextFn())); - - PAssert.that(output).containsInAnyOrder(COUNTS_ARRAY); - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties deleted file mode 100644 index b0195b3f16..0000000000 --- a/maven-archetypes/examples-java8/src/test/resources/projects/basic/archetype.properties +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed 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=it.pkg -version=0.1 -groupId=archetype.it -artifactId=basic -targetPlatform=1.8 diff --git a/maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt b/maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt deleted file mode 100644 index 0b5987362f..0000000000 --- a/maven-archetypes/examples-java8/src/test/resources/projects/basic/goal.txt +++ /dev/null @@ -1 +0,0 @@ -verify diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index cfe47d4d8a..5ff4872335 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -39,7 +39,7 @@ org.apache.maven.archetype archetype-packaging - 2.4 + ${archetype-packaging.version} @@ -47,12 +47,12 @@ maven-archetype-plugin - 2.4 + ${maven-archetype-plugin.version} org.apache.maven.shared maven-invoker - 2.2 + ${maven-invoker.version} diff --git a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml index 2b9eb52d80..29f8605cce 100644 --- a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml +++ b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -22,7 +22,7 @@ - 1.7 + 1.8 diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index 2c2b8d3fc6..dcbedafd76 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -32,13 +32,13 @@ @google-clients.version@ @guava.version@ @hamcrest.version@ - @jackson.version@ @joda.version@ @junit.version@ @maven-compiler-plugin.version@ - @maven-exec-plugin.version@ + @exec-maven-plugin.version@ @maven-jar-plugin.version@ @maven-shade-plugin.version@ + @mockito.version@ @pubsub.version@ @slf4j.version@ @surefire-plugin.version@ @@ -137,7 +137,7 @@ org.codehaus.mojo exec-maven-plugin - ${maven-exec-plugin.version} + ${exec-maven-plugin.version} false @@ -251,5 +251,12 @@ junit ${junit.version} + + + org.mockito + mockito-all + ${mockito.version} + test + diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java index d6b08066db..f1bd8bfaa8 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java @@ -17,18 +17,17 @@ */ package ${package}; -import ${package}.common.ExampleUtils; +import java.util.Arrays; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.transforms.Count; -import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.Filter; +import org.apache.beam.sdk.transforms.FlatMapElements; import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.SimpleFunction; import org.apache.beam.sdk.values.KV; - +import org.apache.beam.sdk.values.TypeDescriptors; /** * An example that counts words in Shakespeare. @@ -59,16 +58,30 @@ public class MinimalWordCount { public static void main(String[] args) { + // Create a PipelineOptions object. This object lets us set various execution // options for our pipeline, such as the runner you wish to use. This example // will run with the DirectRunner by default, based on the class path configured // in its dependencies. PipelineOptions options = PipelineOptionsFactory.create(); - // Create the Pipeline object with the options we defined above. - Pipeline p = Pipeline.create(options); + // In order to run your pipeline, you need to make following runner specific changes: + // + // CHANGE 1/3: Select a Beam runner, such as BlockingDataflowRunner + // or FlinkRunner. + // CHANGE 2/3: Specify runner-required options. + // For BlockingDataflowRunner, set project and temp location as follows: + // DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); + // dataflowOptions.setRunner(BlockingDataflowRunner.class); + // dataflowOptions.setProject("SET_YOUR_PROJECT_ID_HERE"); + // dataflowOptions.setTempLocation("gs://SET_YOUR_BUCKET_NAME_HERE/AND_TEMP_DIRECTORY"); + // For FlinkRunner, set the runner as follows. See {@code FlinkPipelineOptions} + // for more details. + // options.as(FlinkPipelineOptions.class) + // .setRunner(FlinkRunner.class); - // Apply the pipeline's transforms. + // Create the Pipeline object with the options we defined above + Pipeline p = Pipeline.create(options); // Concept #1: Apply a root transform to the pipeline; in this case, TextIO.Read to read a set // of input text files. TextIO.Read returns a PCollection where each element is one line from @@ -77,43 +90,30 @@ public static void main(String[] args) { // This example reads a public data set consisting of the complete works of Shakespeare. p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) - // Concept #2: Apply a ParDo transform to our PCollection of text lines. This ParDo invokes a - // DoFn (defined in-line) on each element that tokenizes the text line into individual words. - // The ParDo returns a PCollection, where each element is an individual word in - // Shakespeare's collected texts. - .apply("ExtractWords", ParDo.of(new DoFn() { - @ProcessElement - public void processElement(ProcessContext c) { - for (String word : c.element().split(ExampleUtils.TOKENIZER_PATTERN)) { - if (!word.isEmpty()) { - c.output(word); - } - } - } - })) - - // Concept #3: Apply the Count transform to our PCollection of individual words. The Count - // transform returns a new PCollection of key/value pairs, where each key represents a unique - // word in the text. The associated value is the occurrence count for that word. - .apply(Count.perElement()) - - // Apply a MapElements transform that formats our PCollection of word counts into a printable - // string, suitable for writing to an output file. - .apply("FormatResults", MapElements.via(new SimpleFunction, String>() { - @Override - public String apply(KV input) { - return input.getKey() + ": " + input.getValue(); - } - })) - - // Concept #4: Apply a write transform, TextIO.Write, at the end of the pipeline. - // TextIO.Write writes the contents of a PCollection (in this case, our PCollection of - // formatted strings) to a series of text files. - // - // By default, it will write to a set of files with names like wordcount-00001-of-00005 - .apply(TextIO.write().to("wordcounts")); + // Concept #2: Apply a FlatMapElements transform the PCollection of text lines. + // This transform splits the lines in PCollection, where each element is an + // individual word in Shakespeare's collected texts. + .apply(FlatMapElements + .into(TypeDescriptors.strings()) + .via((String word) -> Arrays.asList(word.split("[^\\p{L}]+")))) + // We use a Filter transform to avoid empty word + .apply(Filter.by((String word) -> !word.isEmpty())) + // Concept #3: Apply the Count transform to our PCollection of individual words. The Count + // transform returns a new PCollection of key/value pairs, where each key represents a + // unique word in the text. The associated value is the occurrence count for that word. + .apply(Count.perElement()) + // Apply a MapElements transform that formats our PCollection of word counts into a + // printable string, suitable for writing to an output file. + .apply(MapElements + .into(TypeDescriptors.strings()) + .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue())) + // Concept #4: Apply a write transform, TextIO.Write, at the end of the pipeline. + // TextIO.Write writes the contents of a PCollection (in this case, our PCollection of + // formatted strings) to a series of text files. + // + // By default, it will write to a set of files with names like wordcounts-00001-of-00005 + .apply(TextIO.write().to("wordcounts")); - // Run the pipeline. p.run().waitUntilFinish(); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java index 6a1d07c485..501ac27881 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java @@ -40,7 +40,6 @@ import org.joda.time.Duration; import org.joda.time.Instant; - /** * An example that counts words in text, and can run over either unbounded or bounded input * collections. @@ -98,7 +97,6 @@ public class WindowedWordCount { * 2-hour period. */ static class AddTimestampFn extends DoFn { - private static final Duration RAND_RANGE = Duration.standardHours(1); private final Instant minTimestamp; private final Instant maxTimestamp; @@ -162,7 +160,7 @@ public interface Options extends WordCount.WordCountOptions, Long getMaxTimestampMillis(); void setMaxTimestampMillis(Long value); - @Description("Fixed number of shards to produce per window, or null for runner-chosen sharding") + @Description("Fixed number of shards to produce per window") Integer getNumShards(); void setNumShards(Integer numShards); } @@ -194,8 +192,7 @@ public static void main(String[] args) throws IOException { */ PCollection windowedWords = input.apply( - Window.into( - FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); + Window.into(FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); /** * Concept #4: Re-use our existing CountWords transform that does not have knowledge of diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java index 9947a26eda..33f7b39f19 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -137,8 +137,7 @@ public PCollection> expand(PCollection lines) { ParDo.of(new ExtractWordsFn())); // Count the number of times each word occurs. - PCollection> wordCounts = - words.apply(Count.perElement()); + PCollection> wordCounts = words.apply(Count.perElement()); return wordCounts; } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java index 78f3849b40..e1159b9018 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java @@ -346,38 +346,39 @@ public void waitToFinish(PipelineResult result) { } private void addShutdownHook(final Collection pipelineResults) { - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - tearDown(); - printPendingMessages(); - for (PipelineResult pipelineResult : pipelineResults) { - try { - pipelineResult.cancel(); - } catch (IOException e) { - System.out.println("Failed to cancel the job."); - System.out.println(e.getMessage()); - } - } + Runtime.getRuntime() + .addShutdownHook( + new Thread( + () -> { + tearDown(); + printPendingMessages(); + for (PipelineResult pipelineResult : pipelineResults) { + try { + pipelineResult.cancel(); + } catch (IOException e) { + System.out.println("Failed to cancel the job."); + System.out.println(e.getMessage()); + } + } - for (PipelineResult pipelineResult : pipelineResults) { - boolean cancellationVerified = false; - for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { - if (pipelineResult.getState().isTerminal()) { - cancellationVerified = true; - break; - } else { - System.out.println( - "The example pipeline is still running. Verifying the cancellation."); - } - Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); - } - if (!cancellationVerified) { - System.out.println("Failed to verify the cancellation for job: " + pipelineResult); - } - } - } - }); + for (PipelineResult pipelineResult : pipelineResults) { + boolean cancellationVerified = false; + for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { + if (pipelineResult.getState().isTerminal()) { + cancellationVerified = true; + break; + } else { + System.out.println( + "The example pipeline is still running. Verifying the cancellation."); + } + Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); + } + if (!cancellationVerified) { + System.out.println( + "Failed to verify the cancellation for job: " + pipelineResult); + } + } + })); } private void printPendingMessages() { diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java similarity index 68% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java index a286811293..3cb04bd2e4 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java @@ -19,8 +19,8 @@ import java.util.HashMap; import java.util.Map; -import java.util.TimeZone; import ${package}.common.ExampleUtils; +import ${package}.complete.game.utils.GameConstants; import ${package}.complete.game.utils.WriteWindowedToBigQuery; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.PipelineResult; @@ -50,11 +50,8 @@ import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; import org.apache.beam.sdk.values.TypeDescriptors; -import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -93,14 +90,8 @@ */ public class GameStats extends LeaderBoard { - private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; - - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); - /** - * Filter out all but those users with a high clickrate, which we will consider as 'spammy' uesrs. + * Filter out all users but those with a high clickrate, which we will consider as 'spammy' users. * We do this by finding the mean total score per user, then using that information as a side * input to filter out all but those user scores that are larger than * {@code (mean * SCORE_WEIGHT)}. @@ -115,12 +106,12 @@ public static class CalculateSpammyUsers public PCollection> expand(PCollection> userScores) { // Get the sum of scores for each user. - PCollection> sumScores = userScores - .apply("UserSum", Sum.integersPerKey()); + PCollection> sumScores = + userScores.apply("UserSum", Sum.integersPerKey()); // Extract the score from each element, and use it to find the global mean. - final PCollectionView globalMeanScore = sumScores.apply(Values.create()) - .apply(Mean.globally().asSingletonView()); + final PCollectionView globalMeanScore = + sumScores.apply(Values.create()).apply(Mean.globally().asSingletonView()); // Filter the user sums using the global mean. PCollection> filtered = sumScores @@ -193,27 +184,24 @@ interface Options extends LeaderBoard.Options { protected static Map>> configureWindowedWrite() { Map>> tableConfigure = - new HashMap>>(); + new HashMap<>(); tableConfigure.put( - "team", - new WriteWindowedToBigQuery.FieldInfo>( - "STRING", (c, w) -> c.element().getKey())); + "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); tableConfigure.put( "total_score", - new WriteWindowedToBigQuery.FieldInfo>( - "INTEGER", (c, w) -> c.element().getValue())); + new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); tableConfigure.put( "window_start", - new WriteWindowedToBigQuery.FieldInfo>( + new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> { IntervalWindow window = (IntervalWindow) w; - return fmt.print(window.start()); + return GameConstants.DATE_TIME_FORMATTER.print(window.start()); })); tableConfigure.put( "processing_time", - new WriteWindowedToBigQuery.FieldInfo>( - "STRING", (c, w) -> fmt.print(Instant.now()))); + new WriteWindowedToBigQuery.FieldInfo<>( + "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); return tableConfigure; } @@ -224,19 +212,17 @@ interface Options extends LeaderBoard.Options { protected static Map> configureSessionWindowWrite() { - Map> tableConfigure = - new HashMap>(); + Map> tableConfigure = new HashMap<>(); tableConfigure.put( "window_start", - new WriteWindowedToBigQuery.FieldInfo( + new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> { IntervalWindow window = (IntervalWindow) w; - return fmt.print(window.start()); + return GameConstants.DATE_TIME_FORMATTER.print(window.start()); })); tableConfigure.put( - "mean_duration", - new WriteWindowedToBigQuery.FieldInfo("FLOAT", (c, w) -> c.element())); + "mean_duration", new WriteWindowedToBigQuery.FieldInfo<>("FLOAT", (c, w) -> c.element())); return tableConfigure; } @@ -253,7 +239,8 @@ public static void main(String[] args) throws Exception { // Read Events from Pub/Sub using custom timestamps PCollection rawEvents = pipeline .apply(PubsubIO.readStrings() - .withTimestampAttribute(TIMESTAMP_ATTRIBUTE).fromTopic(options.getTopic())) + .withTimestampAttribute(GameConstants.TIMESTAMP_ATTRIBUTE) + .fromTopic(options.getTopic())) .apply("ParseGameEvent", ParDo.of(new ParseEventFn())); // Extract username/score pairs from the event stream @@ -265,16 +252,19 @@ public static void main(String[] args) throws Exception { // Calculate the total score per user over fixed windows, and // cumulative updates for late data. - final PCollectionView> spammersView = userEvents - .apply("FixedWindowsUser", Window.>into( - FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) - - // Filter out everyone but those with (SCORE_WEIGHT * avg) clickrate. - // These might be robots/spammers. - .apply("CalculateSpammyUsers", new CalculateSpammyUsers()) - // Derive a view from the collection of spammer users. It will be used as a side input - // in calculating the team score sums, below. - .apply("CreateSpammersView", View.asMap()); + final PCollectionView> spammersView = + userEvents + .apply( + "FixedWindowsUser", + Window.into( + FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) + + // Filter out everyone but those with (SCORE_WEIGHT * avg) clickrate. + // These might be robots/spammers. + .apply("CalculateSpammyUsers", new CalculateSpammyUsers()) + // Derive a view from the collection of spammer users. It will be used as a side input + // in calculating the team score sums, below. + .apply("CreateSpammersView", View.asMap()); // [START DocInclude_FilterAndCalc] // Calculate the total score per team over fixed windows, @@ -282,29 +272,35 @@ public static void main(String[] args) throws Exception { // suspected robots-- to filter out scores from those users from the sum. // Write the results to BigQuery. rawEvents - .apply("WindowIntoFixedWindows", Window.into( - FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) - // Filter out the detected spammer users, using the side input derived above. - .apply("FilterOutSpammers", ParDo - .of(new DoFn() { - @ProcessElement - public void processElement(ProcessContext c) { - // If the user is not in the spammers Map, output the data element. - if (c.sideInput(spammersView).get(c.element().getUser().trim()) == null) { - c.output(c.element()); - } - } - }).withSideInputs(spammersView)) + .apply( + "WindowIntoFixedWindows", + Window.into( + FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) + // Filter out the detected spammer users, using the side input derived above. + .apply( + "FilterOutSpammers", + ParDo.of( + new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + // If the user is not in the spammers Map, output the data element. + if (c.sideInput(spammersView).get(c.element().getUser().trim()) == null) { + c.output(c.element()); + } + } + }) + .withSideInputs(spammersView)) // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")) - // [END DocInclude_FilterAndCalc] - // Write the result to BigQuery - .apply("WriteTeamSums", - new WriteWindowedToBigQuery>( - options.as(GcpOptions.class).getProject(), - options.getDataset(), - options.getGameStatsTablePrefix() + "_team", configureWindowedWrite())); - + .apply("ExtractTeamScore", new ExtractAndSumScore("team")) + // [END DocInclude_FilterAndCalc] + // Write the result to BigQuery + .apply( + "WriteTeamSums", + new WriteWindowedToBigQuery<>( + options.as(GcpOptions.class).getProject(), + options.getDataset(), + options.getGameStatsTablePrefix() + "_team", + configureWindowedWrite())); // [START DocInclude_SessionCalc] // Detect user sessions-- that is, a burst of activity separated by a gap from further @@ -312,27 +308,33 @@ public void processElement(ProcessContext c) { // This information could help the game designers track the changing user engagement // as their set of games changes. userEvents - .apply("WindowIntoSessions", Window.>into( - Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap()))) - .withTimestampCombiner(TimestampCombiner.END_OF_WINDOW)) - // For this use, we care only about the existence of the session, not any particular - // information aggregated over it, so the following is an efficient way to do that. - .apply(Combine.perKey(x -> 0)) - // Get the duration per session. - .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn())) - // [END DocInclude_SessionCalc] - // [START DocInclude_Rewindow] - // Re-window to process groups of session sums according to when the sessions complete. - .apply("WindowToExtractSessionMean", Window.into( - FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration())))) - // Find the mean session duration in each window. - .apply(Mean.globally().withoutDefaults()) - // Write this info to a BigQuery table. - .apply("WriteAvgSessionLength", - new WriteWindowedToBigQuery( - options.as(GcpOptions.class).getProject(), - options.getDataset(), - options.getGameStatsTablePrefix() + "_sessions", configureSessionWindowWrite())); + .apply( + "WindowIntoSessions", + Window.>into( + Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap()))) + .withTimestampCombiner(TimestampCombiner.END_OF_WINDOW)) + // For this use, we care only about the existence of the session, not any particular + // information aggregated over it, so the following is an efficient way to do that. + .apply(Combine.perKey(x -> 0)) + // Get the duration per session. + .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn())) + // [END DocInclude_SessionCalc] + // [START DocInclude_Rewindow] + // Re-window to process groups of session sums according to when the sessions complete. + .apply( + "WindowToExtractSessionMean", + Window.into( + FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration())))) + // Find the mean session duration in each window. + .apply(Mean.globally().withoutDefaults()) + // Write this info to a BigQuery table. + .apply( + "WriteAvgSessionLength", + new WriteWindowedToBigQuery<>( + options.as(GcpOptions.class).getProject(), + options.getDataset(), + options.getGameStatsTablePrefix() + "_sessions", + configureSessionWindowWrite())); // [END DocInclude_Rewindow] diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java similarity index 75% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java index e60af492e4..fe1fe99da7 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.Map; import java.util.TimeZone; +import ${package}.complete.game.utils.GameConstants; import ${package}.complete.game.utils.WriteToText; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; @@ -73,9 +74,6 @@ */ public class HourlyTeamScore extends UserScore { - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); private static DateTimeFormatter minFmt = DateTimeFormat.forPattern("yyyy-MM-dd-HH-mm") .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); @@ -113,15 +111,14 @@ interface Options extends UserScore.Options { */ protected static Map>> configureOutput() { - Map>> config = - new HashMap>>(); + Map>> config = new HashMap<>(); config.put("team", (c, w) -> c.element().getKey()); config.put("total_score", (c, w) -> c.element().getValue()); config.put( "window_start", (c, w) -> { IntervalWindow window = (IntervalWindow) w; - return fmt.print(window.start()); + return GameConstants.DATE_TIME_FORMATTER.print(window.start()); }); return config; } @@ -140,40 +137,43 @@ public static void main(String[] args) throws Exception { final Instant startMinTimestamp = new Instant(minFmt.parseMillis(options.getStartMin())); // Read 'gaming' events from a text file. - pipeline.apply(TextIO.read().from(options.getInput())) - // Parse the incoming data. - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) - - // Filter out data before and after the given times so that it is not included - // in the calculations. As we collect data in batches (say, by day), the batch for the day - // that we want to analyze could potentially include some late-arriving data from the previous - // day. If so, we want to weed it out. Similarly, if we include data from the following day - // (to scoop up late-arriving events from the day we're analyzing), we need to weed out events - // that fall after the time period we want to analyze. - // [START DocInclude_HTSFilters] - .apply("FilterStartTime", Filter.by( - (GameActionInfo gInfo) - -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) - .apply("FilterEndTime", Filter.by( - (GameActionInfo gInfo) - -> gInfo.getTimestamp() < stopMinTimestamp.getMillis())) - // [END DocInclude_HTSFilters] - - // [START DocInclude_HTSAddTsAndWindow] - // Add an element timestamp based on the event log, and apply fixed windowing. - .apply("AddEventTimestamps", - WithTimestamps.of((GameActionInfo i) -> new Instant(i.getTimestamp()))) - .apply("FixedWindowsTeam", Window.into( - FixedWindows.of(Duration.standardMinutes(options.getWindowDuration())))) - // [END DocInclude_HTSAddTsAndWindow] - - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")) - .apply("WriteTeamScoreSums", - new WriteToText>( - options.getOutput(), - configureOutput(), - true)); + pipeline + .apply(TextIO.read().from(options.getInput())) + // Parse the incoming data. + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) + + // Filter out data before and after the given times so that it is not included + // in the calculations. As we collect data in batches (say, by day), the batch for the day + // that we want to analyze could potentially include some late-arriving data from the + // previous day. + // If so, we want to weed it out. Similarly, if we include data from the following day + // (to scoop up late-arriving events from the day we're analyzing), we need to weed out + // events that fall after the time period we want to analyze. + // [START DocInclude_HTSFilters] + .apply( + "FilterStartTime", + Filter.by( + (GameActionInfo gInfo) -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) + .apply( + "FilterEndTime", + Filter.by( + (GameActionInfo gInfo) -> gInfo.getTimestamp() < stopMinTimestamp.getMillis())) + // [END DocInclude_HTSFilters] + + // [START DocInclude_HTSAddTsAndWindow] + // Add an element timestamp based on the event log, and apply fixed windowing. + .apply( + "AddEventTimestamps", + WithTimestamps.of((GameActionInfo i) -> new Instant(i.getTimestamp()))) + .apply( + "FixedWindowsTeam", + Window.into(FixedWindows.of(Duration.standardMinutes(options.getWindowDuration())))) + // [END DocInclude_HTSAddTsAndWindow] + + // Extract and sum teamname/score pairs from the event data. + .apply("ExtractTeamScore", new ExtractAndSumScore("team")) + .apply( + "WriteTeamScoreSums", new WriteToText<>(options.getOutput(), configureOutput(), true)); pipeline.run().waitUntilFinish(); } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java similarity index 87% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java index 4f0ee28128..ae32637e15 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java @@ -20,9 +20,9 @@ import com.google.common.annotations.VisibleForTesting; import java.util.HashMap; import java.util.Map; -import java.util.TimeZone; import ${package}.common.ExampleOptions; import ${package}.common.ExampleUtils; +import ${package}.complete.game.utils.GameConstants; import ${package}.complete.game.utils.WriteToBigQuery; import ${package}.complete.game.utils.WriteWindowedToBigQuery; import org.apache.beam.sdk.Pipeline; @@ -45,11 +45,8 @@ import org.apache.beam.sdk.transforms.windowing.Window; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; -import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; /** * This class is the third in a series of four pipelines that tell a story in a 'gaming' domain, @@ -92,11 +89,6 @@ */ public class LeaderBoard extends HourlyTeamScore { - private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; - - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); static final Duration FIVE_MINUTES = Duration.standardMinutes(5); static final Duration TEN_MINUTES = Duration.standardMinutes(10); @@ -140,30 +132,27 @@ interface Options extends HourlyTeamScore.Options, ExampleOptions, StreamingOpti configureWindowedTableWrite() { Map>> tableConfigure = - new HashMap>>(); + new HashMap<>(); tableConfigure.put( - "team", - new WriteWindowedToBigQuery.FieldInfo>( - "STRING", (c, w) -> c.element().getKey())); + "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); tableConfigure.put( "total_score", - new WriteWindowedToBigQuery.FieldInfo>( - "INTEGER", (c, w) -> c.element().getValue())); + new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); tableConfigure.put( "window_start", - new WriteWindowedToBigQuery.FieldInfo>( + new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> { IntervalWindow window = (IntervalWindow) w; - return fmt.print(window.start()); + return GameConstants.DATE_TIME_FORMATTER.print(window.start()); })); tableConfigure.put( "processing_time", - new WriteWindowedToBigQuery.FieldInfo>( - "STRING", (c, w) -> fmt.print(Instant.now()))); + new WriteWindowedToBigQuery.FieldInfo<>( + "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); tableConfigure.put( "timing", - new WriteWindowedToBigQuery.FieldInfo>( + new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> c.pane().getTiming().toString())); return tableConfigure; } @@ -175,16 +164,12 @@ interface Options extends HourlyTeamScore.Options, ExampleOptions, StreamingOpti */ protected static Map>> configureBigQueryWrite() { - Map>> tableConfigure = - new HashMap>>(); + Map>> tableConfigure = new HashMap<>(); tableConfigure.put( - "user", - new WriteToBigQuery.FieldInfo>( - "STRING", (c, w) -> c.element().getKey())); + "user", new WriteToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); tableConfigure.put( "total_score", - new WriteToBigQuery.FieldInfo>( - "INTEGER", (c, w) -> c.element().getValue())); + new WriteToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); return tableConfigure; } @@ -200,8 +185,8 @@ interface Options extends HourlyTeamScore.Options, ExampleOptions, StreamingOpti configureBigQueryWrite(); tableConfigure.put( "processing_time", - new WriteToBigQuery.FieldInfo>( - "STRING", (c, w) -> fmt.print(Instant.now()))); + new WriteToBigQuery.FieldInfo<>( + "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); return tableConfigure; } @@ -218,7 +203,8 @@ public static void main(String[] args) throws Exception { // data elements, and parse the data. PCollection gameEvents = pipeline .apply(PubsubIO.readStrings() - .withTimestampAttribute(TIMESTAMP_ATTRIBUTE).fromTopic(options.getTopic())) + .withTimestampAttribute(GameConstants.TIMESTAMP_ATTRIBUTE) + .fromTopic(options.getTopic())) .apply("ParseGameEvent", ParDo.of(new ParseEventFn())); gameEvents @@ -230,7 +216,7 @@ public static void main(String[] args) throws Exception { // Write the results to BigQuery. .apply( "WriteTeamScoreSums", - new WriteWindowedToBigQuery>( + new WriteWindowedToBigQuery<>( options.as(GcpOptions.class).getProject(), options.getDataset(), options.getLeaderBoardTableName() + "_team", @@ -242,7 +228,7 @@ public static void main(String[] args) throws Exception { // Write the results to BigQuery. .apply( "WriteUserScoreSums", - new WriteToBigQuery>( + new WriteToBigQuery<>( options.as(GcpOptions.class).getProject(), options.getDataset(), options.getLeaderBoardTableName() + "_user", diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java new file mode 100644 index 0000000000..c0a7bc8e17 --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java @@ -0,0 +1,227 @@ +/* + * 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 ${package}.complete.game; + +import static com.google.common.base.MoreObjects.firstNonNull; + +import com.google.common.annotations.VisibleForTesting; +import java.util.HashMap; +import java.util.Map; +import ${package}.common.ExampleUtils; +import ${package}.complete.game.utils.GameConstants; +import ${package}.complete.game.utils.WriteToBigQuery.FieldInfo; +import ${package}.complete.game.utils.WriteWindowedToBigQuery; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; +import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO; +import org.apache.beam.sdk.options.Default; +import org.apache.beam.sdk.options.Description; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.state.StateSpec; +import org.apache.beam.sdk.state.StateSpecs; +import org.apache.beam.sdk.state.ValueState; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.MapElements; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.TypeDescriptor; +import org.apache.beam.sdk.values.TypeDescriptors; +import org.joda.time.Instant; + +/** + * This class is part of a series of pipelines that tell a story in a gaming domain. Concepts + * include: stateful processing. + * + *

              This pipeline processes an unbounded stream of 'game events'. It uses stateful processing to + * aggregate team scores per team and outputs team name and it's total score every time the team + * passes a new multiple of a threshold score. For example, multiples of the threshold could be the + * corresponding scores required to pass each level of the game. By default, this threshold is set + * to 5000. + * + *

              Stateful processing allows us to write pipelines that output based on a runtime state (when + * a team reaches a certain score, in every 100 game events etc) without time triggers. See + * https://beam.apache.org/blog/2017/02/13/stateful-processing.html for more information on using + * stateful processing. + * + *

              Run {@code injector.Injector} to generate pubsub data for this pipeline. The Injector + * documentation provides more detail on how to do this. + * + *

              To execute this pipeline, specify the pipeline configuration like this: + *

              {@code
              + *   --project=YOUR_PROJECT_ID
              + *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              + *   --runner=YOUR_RUNNER
              + *   --dataset=YOUR-DATASET
              + *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              + * }
              + * 
              + * + *

              The BigQuery dataset you specify must already exist. The PubSub topic you specify should be + * the same topic to which the Injector is publishing. + */ +public class StatefulTeamScore extends LeaderBoard { + + /** + * Options supported by {@link StatefulTeamScore}. + */ + interface Options extends LeaderBoard.Options { + + @Description("Numeric value, multiple of which is used as threshold for outputting team score.") + @Default.Integer(5000) + Integer getThresholdScore(); + + void setThresholdScore(Integer value); + } + + /** + * Create a map of information that describes how to write pipeline output to BigQuery. This map + * is used to write team score sums. + */ + private static Map>> configureCompleteWindowedTableWrite() { + + Map>> tableConfigure = + new HashMap<>(); + tableConfigure.put( + "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); + tableConfigure.put( + "total_score", + new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); + tableConfigure.put( + "processing_time", + new WriteWindowedToBigQuery.FieldInfo<>( + "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); + return tableConfigure; + } + + + public static void main(String[] args) throws Exception { + + Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + // Enforce that this pipeline is always run in streaming mode. + options.setStreaming(true); + ExampleUtils exampleUtils = new ExampleUtils(options); + Pipeline pipeline = Pipeline.create(options); + + pipeline + // Read game events from Pub/Sub using custom timestamps, which are extracted from the + // pubsub data elements, and parse the data. + .apply( + PubsubIO.readStrings() + .withTimestampAttribute(GameConstants.TIMESTAMP_ATTRIBUTE) + .fromTopic(options.getTopic())) + .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) + // Create mapping. UpdateTeamScore uses team name as key. + .apply( + "MapTeamAsKey", + MapElements.into( + TypeDescriptors.kvs( + TypeDescriptors.strings(), TypeDescriptor.of(GameActionInfo.class))) + .via((GameActionInfo gInfo) -> KV.of(gInfo.team, gInfo))) + // Outputs a team's score every time it passes a new multiple of the threshold. + .apply("UpdateTeamScore", ParDo.of(new UpdateTeamScoreFn(options.getThresholdScore()))) + // Write the results to BigQuery. + .apply( + "WriteTeamLeaders", + new WriteWindowedToBigQuery<>( + options.as(GcpOptions.class).getProject(), + options.getDataset(), + options.getLeaderBoardTableName() + "_team_leader", + configureCompleteWindowedTableWrite())); + + // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the + // command line. + PipelineResult result = pipeline.run(); + exampleUtils.waitToFinish(result); + } + + /** + * Tracks each team's score separately in a single state cell and outputs the score every time it + * passes a new multiple of a threshold. + * + *

              We use stateful {@link DoFn} because: + *

                + *
              • State is key-partitioned. Therefore, the score is calculated per team.
              • + *
              • Stateful {@link DoFn} can determine when to output based on the state. This only allows + * outputting when a team's score passes a given threshold.
              • + *
              + */ + @VisibleForTesting + public static class UpdateTeamScoreFn + extends DoFn, KV> { + + private static final String TOTAL_SCORE = "totalScore"; + private final int thresholdScore; + + public UpdateTeamScoreFn(int thresholdScore) { + this.thresholdScore = thresholdScore; + } + + /** + * Describes the state for storing team score. Let's break down this statement. + * + * {@link StateSpec} configures the state cell, which is provided by a runner during pipeline + * execution. + * + * {@link org.apache.beam.sdk.transforms.DoFn.StateId} annotation assigns an identifier to the + * state, which is used to refer the state in + * {@link org.apache.beam.sdk.transforms.DoFn.ProcessElement}. + * + *

              A {@link ValueState} stores single value per key and per window. Because our pipeline is + * globally windowed in this example, this {@link ValueState} is just key partitioned, with one + * score per team. Any other class that extends {@link org.apache.beam.sdk.state.State} can be + * used.

              + * + *

              In order to store the value, the state must be encoded. Therefore, we provide a coder, in + * this case the {@link VarIntCoder}. If the coder is not provided as in + * {@code StateSpecs.value()}, Beam's coder inference will try to provide a coder automatically. + *

              + */ + @StateId(TOTAL_SCORE) + private final StateSpec> totalScoreSpec = + StateSpecs.value(VarIntCoder.of()); + + /** + * To use a state cell, annotate a parameter with + * {@link org.apache.beam.sdk.transforms.DoFn.StateId} that matches the state declaration. The + * type of the parameter should match the {@link StateSpec} type. + */ + @ProcessElement + public void processElement( + ProcessContext c, + @StateId(TOTAL_SCORE) ValueState totalScore) { + String teamName = c.element().getKey(); + GameActionInfo gInfo = c.element().getValue(); + + // ValueState cells do not contain a default value. If the state is possibly not written, make + // sure to check for null on read. + int oldTotalScore = firstNonNull(totalScore.read(), 0); + totalScore.write(oldTotalScore + gInfo.score); + + // Since there are no negative scores, the easiest way to check whether a team just passed a + // new multiple of the threshold score is to compare the quotients of dividing total scores by + // threshold before and after this aggregation. For example, if the total score was 1999, + // the new total is 2002, and the threshold is 1000, 1999 / 1000 = 1, 2002 / 1000 = 2. + // Therefore, this team passed the threshold. + if (oldTotalScore / this.thresholdScore < totalScore.read() / this.thresholdScore) { + c.output(KV.of(teamName, totalScore.read())); + } + } + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java similarity index 94% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java index c693614c57..f7aa8ff8c0 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java @@ -162,10 +162,11 @@ public PCollection> expand( PCollection gameInfo) { return gameInfo - .apply(MapElements - .into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) - .via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore()))) - .apply(Sum.integersPerKey()); + .apply( + MapElements.into( + TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) + .via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore()))) + .apply(Sum.integersPerKey()); } } // [END DocInclude_USExtractXform] @@ -196,8 +197,7 @@ public interface Options extends PipelineOptions { */ protected static Map>> configureOutput() { - Map>> config = - new HashMap>>(); + Map>> config = new HashMap<>(); config.put("user", (c, w) -> c.element().getKey()); config.put("total_score", (c, w) -> c.element().getValue()); return config; @@ -219,11 +219,7 @@ public static void main(String[] args) throws Exception { // Extract and sum username/score pairs from the event data. .apply("ExtractUserScore", new ExtractAndSumScore("user")) .apply( - "WriteUserScoreSums", - new WriteToText>( - options.getOutput(), - configureOutput(), - false)); + "WriteUserScoreSums", new WriteToText<>(options.getOutput(), configureOutput(), false)); // Run the batch pipeline. pipeline.run().waitUntilFinish(); diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java similarity index 89% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java index 980966e0ce..952cb6fc34 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java @@ -30,11 +30,7 @@ import java.util.Arrays; import java.util.List; import java.util.Random; -import java.util.TimeZone; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - +import ${package}.complete.game.utils.GameConstants; /** * This is a generator that simulates usage data from a mobile game, and either publishes the data @@ -86,7 +82,6 @@ class Injector { private static Random random = new Random(); private static String topic; private static String project; - private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; // QPS ranges from 800 to 1000. private static final int MIN_QPS = 800; @@ -96,25 +91,56 @@ class Injector { // Lists used to generate random team names. private static final ArrayList COLORS = - new ArrayList(Arrays.asList( - "Magenta", "AliceBlue", "Almond", "Amaranth", "Amber", - "Amethyst", "AndroidGreen", "AntiqueBrass", "Fuchsia", "Ruby", "AppleGreen", - "Apricot", "Aqua", "ArmyGreen", "Asparagus", "Auburn", "Azure", "Banana", - "Beige", "Bisque", "BarnRed", "BattleshipGrey")); + new ArrayList<>( + Arrays.asList( + "Magenta", + "AliceBlue", + "Almond", + "Amaranth", + "Amber", + "Amethyst", + "AndroidGreen", + "AntiqueBrass", + "Fuchsia", + "Ruby", + "AppleGreen", + "Apricot", + "Aqua", + "ArmyGreen", + "Asparagus", + "Auburn", + "Azure", + "Banana", + "Beige", + "Bisque", + "BarnRed", + "BattleshipGrey")); private static final ArrayList ANIMALS = - new ArrayList(Arrays.asList( - "Echidna", "Koala", "Wombat", "Marmot", "Quokka", "Kangaroo", "Dingo", "Numbat", "Emu", - "Wallaby", "CaneToad", "Bilby", "Possum", "Cassowary", "Kookaburra", "Platypus", - "Bandicoot", "Cockatoo", "Antechinus")); + new ArrayList<>( + Arrays.asList( + "Echidna", + "Koala", + "Wombat", + "Marmot", + "Quokka", + "Kangaroo", + "Dingo", + "Numbat", + "Emu", + "Wallaby", + "CaneToad", + "Bilby", + "Possum", + "Cassowary", + "Kookaburra", + "Platypus", + "Bandicoot", + "Cockatoo", + "Antechinus")); // The list of live teams. - private static ArrayList liveTeams = new ArrayList(); - - private static DateTimeFormatter fmt = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); - + private static ArrayList liveTeams = new ArrayList<>(); // The total number of robots in the system. private static final int NUM_ROBOTS = 20; @@ -275,7 +301,7 @@ private static String addTimeInfoToEvent(String message, Long currTime, int dela String eventTimeString = Long.toString((currTime - delayInMillis) / 1000 * 1000); // Add a (redundant) 'human-readable' date string to make the data semantics more clear. - String dateString = fmt.print(currTime); + String dateString = GameConstants.DATE_TIME_FORMATTER.print(currTime); message = message + "," + eventTimeString + "," + dateString; return message; } @@ -294,7 +320,7 @@ public static void publishData(int numMessages, int delayInMillis) PubsubMessage pubsubMessage = new PubsubMessage() .encodeData(message.getBytes("UTF-8")); pubsubMessage.setAttributes( - ImmutableMap.of(TIMESTAMP_ATTRIBUTE, + ImmutableMap.of(GameConstants.TIMESTAMP_ATTRIBUTE, Long.toString((currTime - delayInMillis) / 1000 * 1000))); if (delayInMillis != 0) { System.out.println(pubsubMessage.getAttributes()); @@ -394,16 +420,15 @@ public static void main(String[] args) throws IOException, InterruptedException publishDataToFile(fileName, numMessages, delayInMillis); } else { // Write to PubSub. // Start a thread to inject some data. - new Thread(){ - @Override - public void run() { - try { - publishData(numMessages, delayInMillis); - } catch (IOException e) { - System.err.println(e); - } - } - }.start(); + new Thread( + () -> { + try { + publishData(numMessages, delayInMillis); + } catch (IOException e) { + System.err.println(e); + } + }) + .start(); } // Wait before creating another injector thread. diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java similarity index 100% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java similarity index 71% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java index 5d0cc68763..e90fbcc18e 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java @@ -24,11 +24,9 @@ import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.util.ExponentialBackOff; import com.google.api.client.util.Sleeper; -import java.io.IOException; import java.util.logging.Logger; /** @@ -96,32 +94,20 @@ public final void initialize(final HttpRequest request) { new ExponentialBackOff()) .setSleeper(sleeper); request.setInterceptor(wrappedCredential); - request.setUnsuccessfulResponseHandler( - new HttpUnsuccessfulResponseHandler() { - @Override - public boolean handleResponse( - final HttpRequest request, - final HttpResponse response, - final boolean supportsRetry) throws IOException { - if (wrappedCredential.handleResponse( - request, response, supportsRetry)) { - // If credential decides it can handle it, - // the return code or message indicated - // something specific to authentication, - // and no backoff is desired. - return true; - } else if (backoffHandler.handleResponse( - request, response, supportsRetry)) { - // Otherwise, we defer to the judgement of - // our internal backoff handler. - LOG.info("Retrying " - + request.getUrl().toString()); - return true; - } else { - return false; - } - } - }); + request.setUnsuccessfulResponseHandler( + (request1, response, supportsRetry) -> { + if (wrappedCredential.handleResponse(request1, response, supportsRetry)) { + // If credential decides it can handle it, the return code or message indicated + // something specific to authentication, and no backoff is desired. + return true; + } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) { + // Otherwise, we defer to the judgement of our internal backoff handler. + LOG.info("Retrying " + request1.getUrl().toString()); + return true; + } else { + return false; + } + }); request.setIOExceptionHandler( new HttpBackOffIOExceptionHandler(new ExponentialBackOff()) .setSleeper(sleeper)); diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java similarity index 55% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java index 90f935c3ce..93da132690 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java @@ -15,23 +15,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package ${package}.common; +package ${package}.complete.game.utils; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; +import java.util.TimeZone; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; /** - * Options that can be used to configure the Beam examples. + * Shared constants between game series classes. */ -public interface ExampleOptions extends PipelineOptions { - @Description("Whether to keep jobs running after local process exit") - @Default.Boolean(false) - boolean getKeepJobsRunning(); - void setKeepJobsRunning(boolean keepJobsRunning); +public class GameConstants { - @Description("Number of workers to use when executing the injector pipeline") - @Default.Integer(1) - int getInjectorNumWorkers(); - void setInjectorNumWorkers(int numWorkers); + public static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; + + public static final DateTimeFormatter DATE_TIME_FORMATTER = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java similarity index 100% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java similarity index 99% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java index dbd5e39977..45135fb059 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java @@ -83,7 +83,7 @@ protected class BuildRowFn extends DoFn { @ProcessElement public void processElement(ProcessContext c, BoundedWindow window) { - List fields = new ArrayList(); + List fields = new ArrayList<>(); for (Map.Entry> entry : fieldFn.entrySet()) { String key = entry.getKey(); FieldFn fcn = entry.getValue(); diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java similarity index 100% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java similarity index 61% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java index af347c1c0a..f4c8b160d7 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/MinimalWordCountJava8Test.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java @@ -21,11 +21,9 @@ import java.io.IOException; import java.io.Serializable; import java.nio.channels.FileChannel; -import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.Arrays; -import java.util.List; import org.apache.beam.sdk.extensions.gcp.options.GcsOptions; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.testing.TestPipeline; @@ -42,15 +40,13 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; /** - * To keep {@link MinimalWordCountJava8} simple, it is not factored or testable. This test + * To keep {@link MinimalWordCount} simple, it is not factored or testable. This test * file should be maintained with a copy of its code for a basic smoke test. */ @RunWith(JUnit4.class) -public class MinimalWordCountJava8Test implements Serializable { +public class MinimalWordCountTest implements Serializable { @Rule public TestPipeline p = TestPipeline.create().enableAbandonedNodeEnforcement(false); @@ -59,46 +55,39 @@ public class MinimalWordCountJava8Test implements Serializable { * A basic smoke test that ensures there is no crash at pipeline construction time. */ @Test - public void testMinimalWordCountJava8() throws Exception { + public void testMinimalWordCount() throws Exception { p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) - .apply(FlatMapElements - .into(TypeDescriptors.strings()) - .via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+")))) - .apply(Filter.by((String word) -> !word.isEmpty())) - .apply(Count.perElement()) - .apply(MapElements - .into(TypeDescriptors.strings()) - .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue())) - .apply(TextIO.write().to("gs://your-output-bucket/and-output-prefix")); + .apply( + FlatMapElements.into(TypeDescriptors.strings()) + .via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+")))) + .apply(Filter.by((String word) -> !word.isEmpty())) + .apply(Count.perElement()) + .apply( + MapElements.into(TypeDescriptors.strings()) + .via( + (KV wordCount) -> + wordCount.getKey() + ": " + wordCount.getValue())) + .apply(TextIO.write().to("gs://your-output-bucket/and-output-prefix")); } private GcsUtil buildMockGcsUtil() throws IOException { GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); // Any request to open gets a new bogus channel - Mockito - .when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .then(new Answer() { - @Override - public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable { - return FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - } - }); + Mockito.when(mockGcsUtil.open(Mockito.any(GcsPath.class))) + .then( + invocation -> + FileChannel.open( + Files.createTempFile("channel-", ".tmp"), + StandardOpenOption.CREATE, + StandardOpenOption.DELETE_ON_CLOSE)); // Any request for expansion returns a list containing the original GcsPath // This is required to pass validation that occurs in TextIO during apply() - Mockito - .when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .then(new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - return ImmutableList.of((GcsPath) invocation.getArguments()[0]); - } - }); + Mockito.when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) + .then(invocation -> ImmutableList.of((GcsPath) invocation.getArguments()[0])); return mockGcsUtil; } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java index b4e4124e26..91a1bf8edc 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java @@ -53,8 +53,7 @@ public void testExtractWordsFn() throws Exception { Assert.assertThat(extractWordsFn.processBundle(" some input words "), CoreMatchers.hasItems("some", "input", "words")); - Assert.assertThat(extractWordsFn.processBundle(" "), - CoreMatchers.hasItems()); + Assert.assertThat(extractWordsFn.processBundle(" "), CoreMatchers.hasItems()); Assert.assertThat(extractWordsFn.processBundle(" some ", " input", " words"), CoreMatchers.hasItems("some", "input", "words")); } diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java similarity index 100% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java similarity index 100% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java similarity index 97% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java index 6075c564b7..2478c07fa8 100644 --- a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java @@ -32,7 +32,6 @@ import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.testing.TestStream; import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow; @@ -240,13 +239,14 @@ public void testTeamScoresObservablyLate() { String redTeam = TestUser.RED_ONE.getTeam(); PAssert.that(teamScores) .inWindow(window) - .satisfies((SerializableFunction>, Void>) input -> { - // The final sums need not exist in the same pane, but must appear in the output - // PCollection - assertThat(input, hasItem(KV.of(blueTeam, 11))); - assertThat(input, hasItem(KV.of(redTeam, 27))); - return null; - }); + .satisfies( + input -> { + // The final sums need not exist in the same pane, but must appear in the output + // PCollection + assertThat(input, hasItem(KV.of(blueTeam, 11))); + assertThat(input, hasItem(KV.of(redTeam, 27))); + return null; + }); PAssert.thatMap(teamScores) // The closing behavior of CalculateTeamScores precludes an inFinalPane matcher .inOnTimePane(window) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java new file mode 100644 index 0000000000..d48b450547 --- /dev/null +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java @@ -0,0 +1,208 @@ +/* + * 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 ${package}.complete.game; + +import ${package}.complete.game.StatefulTeamScore.UpdateTeamScoreFn; +import ${package}.complete.game.UserScore.GameActionInfo; +import org.apache.beam.sdk.coders.AvroCoder; +import org.apache.beam.sdk.coders.KvCoder; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.testing.TestStream; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.windowing.FixedWindows; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.TimestampedValue; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link StatefulTeamScore}. + */ +@RunWith(JUnit4.class) +public class StatefulTeamScoreTest { + + private static final Duration ALLOWED_LATENESS = Duration.standardHours(1); + private static final Duration TEAM_WINDOW_DURATION = Duration.standardMinutes(20); + private Instant baseTime = new Instant(0); + + @Rule + public TestPipeline p = TestPipeline.create(); + + /** + * Some example users, on two separate teams. + */ + private enum TestUser { + RED_ONE("scarlet", "red"), RED_TWO("burgundy", "red"), + BLUE_ONE("navy", "blue"), BLUE_TWO("sky", "blue"); + + private final String userName; + private final String teamName; + + TestUser(String userName, String teamName) { + this.userName = userName; + this.teamName = teamName; + } + + public String getUser() { + return userName; + } + + public String getTeam() { + return teamName; + } + } + + /** + * Tests that {@link UpdateTeamScoreFn} {@link org.apache.beam.sdk.transforms.DoFn} outputs + * correctly for one team. + */ + @Test + public void testScoreUpdatesOneTeam() { + + TestStream> createEvents = TestStream.create(KvCoder.of( + StringUtf8Coder.of(), AvroCoder.of(GameActionInfo.class))) + .advanceWatermarkTo(baseTime) + .addElements( + event(TestUser.RED_TWO, 99, Duration.standardSeconds(10)), + event(TestUser.RED_ONE, 1, Duration.standardSeconds(20)), + event(TestUser.RED_ONE, 0, Duration.standardSeconds(30)), + event(TestUser.RED_TWO, 100, Duration.standardSeconds(40)), + event(TestUser.RED_TWO, 201, Duration.standardSeconds(50)) + ) + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(ParDo.of(new UpdateTeamScoreFn(100))); + + String redTeam = TestUser.RED_ONE.getTeam(); + + PAssert.that(teamScores) + .inWindow(GlobalWindow.INSTANCE) + .containsInAnyOrder( + KV.of(redTeam, 100), + KV.of(redTeam, 200), + KV.of(redTeam, 401) + ); + + p.run().waitUntilFinish(); + } + + /** + * Tests that {@link UpdateTeamScoreFn} {@link org.apache.beam.sdk.transforms.DoFn} outputs + * correctly for multiple teams. + */ + @Test + public void testScoreUpdatesPerTeam() { + + TestStream> createEvents = TestStream.create(KvCoder.of( + StringUtf8Coder.of(), AvroCoder.of(GameActionInfo.class))) + .advanceWatermarkTo(baseTime) + .addElements( + event(TestUser.RED_ONE, 50, Duration.standardSeconds(10)), + event(TestUser.RED_TWO, 50, Duration.standardSeconds(20)), + event(TestUser.BLUE_ONE, 70, Duration.standardSeconds(30)), + event(TestUser.BLUE_TWO, 80, Duration.standardSeconds(40)), + event(TestUser.BLUE_TWO, 50, Duration.standardSeconds(50)) + ) + .advanceWatermarkToInfinity(); + + PCollection> teamScores = p.apply(createEvents) + .apply(ParDo.of(new UpdateTeamScoreFn(100))); + + String redTeam = TestUser.RED_ONE.getTeam(); + String blueTeam = TestUser.BLUE_ONE.getTeam(); + + PAssert.that(teamScores) + .inWindow(GlobalWindow.INSTANCE) + .containsInAnyOrder( + KV.of(redTeam, 100), + KV.of(blueTeam, 150), + KV.of(blueTeam, 200) + ); + + p.run().waitUntilFinish(); + } + + /** + * Tests that {@link UpdateTeamScoreFn} {@link org.apache.beam.sdk.transforms.DoFn} outputs + * correctly per window and per key. + */ + @Test + public void testScoreUpdatesPerWindow() { + + TestStream> createEvents = TestStream.create(KvCoder.of( + StringUtf8Coder.of(), AvroCoder.of(GameActionInfo.class))) + .advanceWatermarkTo(baseTime) + .addElements( + event(TestUser.RED_ONE, 50, Duration.standardMinutes(1)), + event(TestUser.RED_TWO, 50, Duration.standardMinutes(2)), + event(TestUser.RED_ONE, 50, Duration.standardMinutes(3)), + event(TestUser.RED_ONE, 60, Duration.standardMinutes(6)), + event(TestUser.RED_TWO, 60, Duration.standardMinutes(7)) + ) + .advanceWatermarkToInfinity(); + + Duration teamWindowDuration = Duration.standardMinutes(5); + + PCollection> teamScores = p + .apply(createEvents) + .apply(Window.>into(FixedWindows.of(teamWindowDuration))) + .apply(ParDo.of(new UpdateTeamScoreFn(100))); + + String redTeam = TestUser.RED_ONE.getTeam(); + String blueTeam = TestUser.BLUE_ONE.getTeam(); + + IntervalWindow window1 = new IntervalWindow(baseTime, teamWindowDuration); + IntervalWindow window2 = new IntervalWindow(window1.end(), teamWindowDuration); + + PAssert.that(teamScores) + .inWindow(window1) + .containsInAnyOrder( + KV.of(redTeam, 100) + ); + + PAssert.that(teamScores) + .inWindow(window2) + .containsInAnyOrder( + KV.of(redTeam, 120) + ); + + p.run().waitUntilFinish(); + } + + private TimestampedValue> event( + TestUser user, + int score, + Duration baseTimeOffset) { + return TimestampedValue.of(KV.of(user.getTeam(), new GameActionInfo(user.getUser(), + user.getTeam(), + score, + baseTime.plus(baseTimeOffset).getMillis())), baseTime.plus(baseTimeOffset)); + } +} diff --git a/maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java similarity index 100% rename from maven-archetypes/examples-java8/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java rename to maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java diff --git a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties index 8a76657024..b0195b3f16 100644 --- a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties +++ b/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties @@ -16,4 +16,4 @@ package=it.pkg version=0.1 groupId=archetype.it artifactId=basic -targetPlatform=1.7 +targetPlatform=1.8 diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 7e5eb44cc9..53eeaf01b8 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -33,7 +33,6 @@ starter examples - examples-java8 diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 34bfd076bb..000e743cd2 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -39,7 +39,7 @@ org.apache.maven.archetype archetype-packaging - 2.4 + ${archetype-packaging.version} @@ -55,12 +55,12 @@ maven-archetype-plugin - 2.4 + ${maven-archetype-plugin.version} org.apache.maven.shared maven-invoker - 2.2 + ${maven-invoker.version} diff --git a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml index 4c22d5d68b..428c74aa4a 100644 --- a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml +++ b/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -21,7 +21,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - 1.7 + 1.8 diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties index 8a76657024..b0195b3f16 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties +++ b/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties @@ -16,4 +16,4 @@ package=it.pkg version=0.1 groupId=archetype.it artifactId=basic -targetPlatform=1.7 +targetPlatform=1.8 diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index 8e4edbd29e..506665830a 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -51,8 +51,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - 1.7 - 1.7 + 1.8 + 1.8 diff --git a/pom.xml b/pom.xml index a3ce24f916..320ac544c3 100644 --- a/pom.xml +++ b/pom.xml @@ -99,18 +99,21 @@ + 1.8 + UTF-8 ${maven.build.timestamp} yyyy-MM-dd HH:mm - 2.2.0 + 2.3.0 Google Cloud Dataflow SDK for Java - ${project.version}-20170517 + ${beam.version} 6 1 v2-rev355-1.22.0 + 6.19 1.22.0 20.0 1.3 @@ -120,11 +123,22 @@ v1-rev10-1.22.0 1.7.25 + 2.4 + 1.6.0 2.20 + 2.4 + 2.17 + 3.0.0 3.6.2 - 1.6.0 + 3.0.1 + 2.2 3.0.2 + 3.0.0-M1 + 2.5.3 + 3.0.2 3.0.0 + 2.20 + 3.0.1 pom @@ -137,47 +151,19 @@ - - org.apache.maven.plugins - maven-enforcer-plugin - 1.4.1 - - - enforce-java - - enforce - - - - - - [1.8.0,) - - - - - - - org.apache.maven.plugins maven-clean-plugin - 3.0.0 + ${maven-clean-plugin.version} org.apache.maven.plugins maven-compiler-plugin - 3.6.2 + ${maven-compiler-plugin.version} - 1.7 - 1.7 + ${java.version} + ${java.version} -Xlint:all -Werror @@ -192,12 +178,12 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.17 + ${maven-checkstyle-plugin.version} com.puppycrawl.tools checkstyle - 6.19 + ${checkstyle.version} org.apache.beam @@ -232,7 +218,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.0.2 + ${maven-jar-plugin.version} true @@ -255,7 +241,7 @@ org.apache.maven.plugins maven-source-plugin - 3.0.1 + ${maven-source-plugin.version} attach-sources @@ -277,7 +263,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.4 + ${maven-javadoc-plugin.version} false @@ -295,13 +281,13 @@ org.apache.maven.plugins maven-resources-plugin - 3.0.2 + ${maven-resources-plugin.version} org.apache.maven.plugins maven-dependency-plugin - 3.0.0 + ${maven-dependency-plugin.version} @@ -317,18 +303,18 @@ org.apache.maven.plugins maven-surefire-plugin - 2.20 + ${maven-surefire-plugin.version} org.apache.maven.plugins maven-archetype-plugin - 2.4 + ${maven-archetype-plugin.version} org.apache.maven.shared maven-invoker - 2.2 + ${maven-invoker.version} @@ -354,7 +340,7 @@ org.apache.maven.plugins maven-release-plugin - 2.5.3 + ${maven-release-plugin} true true @@ -365,7 +351,7 @@ org.codehaus.mojo exec-maven-plugin - 1.5.0 + ${exec-maven-plugin.version} false @@ -374,11 +360,6 @@ - - org.apache.maven.plugins - maven-enforcer-plugin - - org.apache.maven.plugins maven-compiler-plugin From 8090e858362899a7a6682b2f46dea882820626b3 Mon Sep 17 00:00:00 2001 From: Batkhuyag Batsaikhan Date: Tue, 27 Feb 2018 18:45:50 -0800 Subject: [PATCH 731/751] removed java8 example --- pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/pom.xml b/pom.xml index 320ac544c3..e24580f9e9 100644 --- a/pom.xml +++ b/pom.xml @@ -430,12 +430,6 @@ ${beam.version}
              - - org.apache.beam - beam-examples-java8 - ${beam.version} - - junit junit From 5b20661f8ae21f390aa764daf9a3b14da060bce0 Mon Sep 17 00:00:00 2001 From: Batkhuyag Batsaikhan Date: Tue, 27 Feb 2018 19:41:41 -0800 Subject: [PATCH 732/751] [maven-release-plugin] prepare for the current development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 2 +- sdk/pom.xml | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 75a1d92174..ef6d842c47 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 5ff4872335..477a670dcb 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 53eeaf01b8..9774b06575 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 000e743cd2..3d51805b04 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index e24580f9e9..937f0aa2ff 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT diff --git a/sdk/pom.xml b/sdk/pom.xml index 33f2255f82..d6ede19a5d 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.2.0-SNAPSHOT + 2.3.0-SNAPSHOT google-cloud-dataflow-java-sdk-all From 0e8ae93463edfc32019a01369e440edec922e91a Mon Sep 17 00:00:00 2001 From: Batkhuyag Batsaikhan Date: Tue, 27 Feb 2018 19:43:58 -0800 Subject: [PATCH 733/751] [maven-release-plugin] prepare branch release-2.3.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 937f0aa2ff..11621568fc 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.3.0 From 3f896cb574abf90f1fcad7c46dce0488c8e69cb2 Mon Sep 17 00:00:00 2001 From: Batkhuyag Batsaikhan Date: Tue, 27 Feb 2018 19:43:58 -0800 Subject: [PATCH 734/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index ef6d842c47..14d46dc1ef 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.3.0-SNAPSHOT + 2.4.0-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 477a670dcb..13b0d6114d 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.3.0-SNAPSHOT + 2.4.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 9774b06575..70bd4462cd 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.3.0-SNAPSHOT + 2.4.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 3d51805b04..cb80d97dc8 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.3.0-SNAPSHOT + 2.4.0-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index 11621568fc..8fa0890f60 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.3.0-SNAPSHOT + 2.4.0-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.3.0 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index d6ede19a5d..c17eacadca 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.3.0-SNAPSHOT + 2.4.0-SNAPSHOT google-cloud-dataflow-java-sdk-all From 16729af118a52b0fb2a64b85e3962e7689a18518 Mon Sep 17 00:00:00 2001 From: tvalentyn Date: Thu, 22 Mar 2018 16:17:33 -0700 Subject: [PATCH 735/751] Use beam-x.y.z containers for DF SDK releases moving forward. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8fa0890f60..f22890e0b9 100644 --- a/pom.xml +++ b/pom.xml @@ -108,7 +108,7 @@ 2.3.0 Google Cloud Dataflow SDK for Java - ${beam.version} + beam-${beam.version} 6 1 From 3e015a8884604b5e22ccbf2e1fb576a934917720 Mon Sep 17 00:00:00 2001 From: tvalentyn Date: Thu, 22 Mar 2018 16:17:33 -0700 Subject: [PATCH 736/751] Use beam-x.y.z containers for DF SDK releases moving forward. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8fa0890f60..f22890e0b9 100644 --- a/pom.xml +++ b/pom.xml @@ -108,7 +108,7 @@ 2.3.0 Google Cloud Dataflow SDK for Java - ${beam.version} + beam-${beam.version} 6 1 From b391210d013538d55c5ea85f3b78d640ab031d9e Mon Sep 17 00:00:00 2001 From: akedin Date: Tue, 27 Mar 2018 15:49:43 -0700 Subject: [PATCH 737/751] Upgrade to Apache Beam version 2.4.0 --- maven-archetypes/examples/pom.xml | 28 +++++++++++++++++++ .../resources/archetype-resources/pom.xml | 2 +- .../complete/game/utils/WriteToBigQuery.java | 1 + .../complete/game/StatefulTeamScoreTest.java | 2 -- maven-archetypes/pom.xml | 2 +- pom.xml | 19 +++++++------ 6 files changed, 41 insertions(+), 13 deletions(-) diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 13b0d6114d..cc50502e5e 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -71,6 +71,34 @@ + + + + org.eclipse.m2e + lifecycle-mapping + ${eclipse-m2e.version} + + + + + + org.codehaus.mojo + exec-maven-plugin + [1.5.0,) + + exec + + + + + false + + + + + + +
              diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml index dcbedafd76..04d70618d9 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml @@ -254,7 +254,7 @@ org.mockito - mockito-all + mockito-core ${mockito.version} test diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java index 984e958c50..d35a4ffcfc 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java @@ -91,6 +91,7 @@ FieldFn getFieldFn() { return this.fieldFn; } } + /** Convert each key/score pair into a BigQuery TableRow as specified by fieldFn. */ protected class BuildRowFn extends DoFn { diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java index d48b450547..c80c57f4fc 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java @@ -47,8 +47,6 @@ @RunWith(JUnit4.class) public class StatefulTeamScoreTest { - private static final Duration ALLOWED_LATENESS = Duration.standardHours(1); - private static final Duration TEAM_WINDOW_DURATION = Duration.standardMinutes(20); private Instant baseTime = new Instant(0); @Rule diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 70bd4462cd..1d0500729c 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -69,7 +69,7 @@ - + diff --git a/pom.xml b/pom.xml index f22890e0b9..be1fba9dd6 100644 --- a/pom.xml +++ b/pom.xml @@ -105,15 +105,16 @@ ${maven.build.timestamp} yyyy-MM-dd HH:mm - 2.3.0 + 2.4.0 Google Cloud Dataflow SDK for Java beam-${beam.version} 6 1 - v2-rev355-1.22.0 - 6.19 + v2-rev374-1.22.0 + 8.7 + 1.0.0 1.22.0 20.0 1.3 @@ -125,19 +126,19 @@ 2.4 1.6.0 - 2.20 + 2.20.1 2.4 - 2.17 + 3.0.0 3.0.0 - 3.6.2 - 3.0.1 + 3.7.0 + 3.0.2 2.2 3.0.2 3.0.0-M1 2.5.3 3.0.2 - 3.0.0 - 2.20 + 3.1.0 + 2.20.1 3.0.1 From f75991996c8cb39473519a7138c814e2b62b7919 Mon Sep 17 00:00:00 2001 From: Anton Kedin Date: Wed, 28 Mar 2018 10:13:58 -0700 Subject: [PATCH 738/751] [maven-release-plugin] prepare branch release-2.4.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index be1fba9dd6..621f2bc192 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.4.0 From 46b74c852ad97fbfedfc2b3e4d7d46143546d662 Mon Sep 17 00:00:00 2001 From: Anton Kedin Date: Wed, 28 Mar 2018 10:13:58 -0700 Subject: [PATCH 739/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 14d46dc1ef..54b3613909 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.4.0-SNAPSHOT + 2.5.0-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index cc50502e5e..2c4a6eb9fe 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.4.0-SNAPSHOT + 2.5.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 1d0500729c..95f647d608 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.4.0-SNAPSHOT + 2.5.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index cb80d97dc8..4e91b8de88 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.4.0-SNAPSHOT + 2.5.0-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index 621f2bc192..4b3108219d 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.4.0-SNAPSHOT + 2.5.0-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.4.0 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index c17eacadca..475af49854 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.4.0-SNAPSHOT + 2.5.0-SNAPSHOT google-cloud-dataflow-java-sdk-all From fb0d662af48359d2d123a4a7ec4b63ce92ede1dd Mon Sep 17 00:00:00 2001 From: Chanseok Oh Date: Wed, 2 May 2018 14:00:07 -0400 Subject: [PATCH 740/751] Fix undefined property bug --- .../starter/src/main/resources/archetype-resources/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml index 22f717f97a..da443b16fa 100644 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml @@ -26,7 +26,7 @@ UTF-8 @maven-compiler-plugin.version@ - @maven-exec-plugin.version@ + @exec-maven-plugin.version@ @slf4j.version@ @@ -62,7 +62,7 @@ org.codehaus.mojo exec-maven-plugin - ${maven-exec-plugin.version} + ${exec-maven-plugin.version} false From bf7770d222ac2a9b89633e8287e26e7c84196d17 Mon Sep 17 00:00:00 2001 From: Chanseok Oh Date: Wed, 2 May 2018 14:08:17 -0400 Subject: [PATCH 741/751] Fix test --- .../src/test/resources/projects/basic/reference/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml index 506665830a..daf87595b7 100644 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml @@ -26,7 +26,7 @@ UTF-8 @maven-compiler-plugin.version@ - @maven-exec-plugin.version@ + @exec-maven-plugin.version@ @slf4j.version@ @@ -62,7 +62,7 @@ org.codehaus.mojo exec-maven-plugin - ${maven-exec-plugin.version} + ${exec-maven-plugin.version} false From 568a4ed5eb3c6908a5f882281da98572826d9512 Mon Sep 17 00:00:00 2001 From: Pablo Date: Mon, 25 Jun 2018 13:34:41 -0700 Subject: [PATCH 742/751] Dataflow SDK Release 2.5.0 --- .../src/main/java/DebuggingWordCount.java | 11 ++++++--- .../src/main/java/WindowedWordCount.java | 13 +++++++---- .../src/main/java/WordCount.java | 21 ++++++++++------- .../main/java/complete/game/GameStats.java | 2 +- .../java/complete/game/HourlyTeamScore.java | 4 ++-- .../main/java/complete/game/LeaderBoard.java | 2 +- .../main/java/complete/game/UserScore.java | 5 ++-- .../java/complete/game/injector/Injector.java | 13 ++++++----- .../complete/game/injector/InjectorUtils.java | 1 + .../complete/game/utils/GameConstants.java | 2 +- .../java/complete/game/utils/WriteToText.java | 4 ++-- .../src/test/java/DebuggingWordCountTest.java | 4 ++-- .../java/complete/game/UserScoreTest.java | 8 +++---- pom.xml | 23 ++++++++++++------- 14 files changed, 69 insertions(+), 44 deletions(-) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java index 07870f2ed0..0ae31d575d 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java @@ -130,9 +130,7 @@ public interface WordCountOptions extends WordCount.WordCountOptions { void setFilterPattern(String value); } - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); + static void runDebuggingWordCount(WordCountOptions options) { Pipeline p = Pipeline.create(options); PCollection> filteredWords = @@ -159,4 +157,11 @@ public static void main(String[] args) { p.run().waitUntilFinish(); } + + public static void main(String[] args) { + WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() + .as(WordCountOptions.class); + + runDebuggingWordCount(options); + } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java index 501ac27881..5798f290eb 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java @@ -106,7 +106,7 @@ static class AddTimestampFn extends DoFn { } @ProcessElement - public void processElement(ProcessContext c) { + public void processElement(@Element String element, OutputReceiver receiver) { Instant randomTimestamp = new Instant( ThreadLocalRandom.current() @@ -115,7 +115,7 @@ public void processElement(ProcessContext c) { /** * Concept #2: Set the data element with that timestamp. */ - c.outputWithTimestamp(c.element(), new Instant(randomTimestamp)); + receiver.outputWithTimestamp(element, new Instant(randomTimestamp)); } } @@ -165,8 +165,7 @@ public interface Options extends WordCount.WordCountOptions, void setNumShards(Integer numShards); } - public static void main(String[] args) throws IOException { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + static void runWindowedWordCount(Options options) throws IOException { final String output = options.getOutput(); final Instant minTimestamp = new Instant(options.getMinTimestampMillis()); final Instant maxTimestamp = new Instant(options.getMaxTimestampMillis()); @@ -217,4 +216,10 @@ public static void main(String[] args) throws IOException { } } + public static void main(String[] args) throws IOException { + Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); + + runWindowedWordCount(options); + } + } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java index 33f7b39f19..d4302ed67a 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java @@ -93,19 +93,19 @@ static class ExtractWordsFn extends DoFn { ExtractWordsFn.class, "lineLenDistro"); @ProcessElement - public void processElement(ProcessContext c) { - lineLenDist.update(c.element().length()); - if (c.element().trim().isEmpty()) { + public void processElement(@Element String element, OutputReceiver receiver) { + lineLenDist.update(element.length()); + if (element.trim().isEmpty()) { emptyLines.inc(); } // Split the line into words. - String[] words = c.element().split(ExampleUtils.TOKENIZER_PATTERN); + String[] words = element.split(ExampleUtils.TOKENIZER_PATTERN, -1); // Output each word encountered into the output PCollection. for (String word : words) { if (!word.isEmpty()) { - c.output(word); + receiver.output(word); } } } @@ -172,9 +172,7 @@ public interface WordCountOptions extends PipelineOptions { void setOutput(String value); } - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); + static void runWordCount(WordCountOptions options) { Pipeline p = Pipeline.create(options); // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the @@ -186,4 +184,11 @@ public static void main(String[] args) { p.run().waitUntilFinish(); } + + public static void main(String[] args) { + WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() + .as(WordCountOptions.class); + + runWordCount(options); + } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java index 3cb04bd2e4..2660cdac2b 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java @@ -153,7 +153,7 @@ public void processElement(ProcessContext c, BoundedWindow window) { /** * Options supported by {@link GameStats}. */ - interface Options extends LeaderBoard.Options { + public interface Options extends LeaderBoard.Options { @Description("Numeric value of fixed window duration for user analysis, in minutes") @Default.Integer(60) Integer getFixedWindowDuration(); diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java index fe1fe99da7..05455219fc 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java @@ -76,13 +76,13 @@ public class HourlyTeamScore extends UserScore { private static DateTimeFormatter minFmt = DateTimeFormat.forPattern("yyyy-MM-dd-HH-mm") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))); /** * Options supported by {@link HourlyTeamScore}. */ - interface Options extends UserScore.Options { + public interface Options extends UserScore.Options { @Description("Numeric value of fixed window duration, in minutes") @Default.Integer(60) diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java index ae32637e15..b5983fa789 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java @@ -96,7 +96,7 @@ public class LeaderBoard extends HourlyTeamScore { /** * Options supported by {@link LeaderBoard}. */ - interface Options extends HourlyTeamScore.Options, ExampleOptions, StreamingOptions { + public interface Options extends HourlyTeamScore.Options, ExampleOptions, StreamingOptions { @Description("BigQuery Dataset to write tables to. Must already exist.") @Validation.Required diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java index f7aa8ff8c0..3459d043f5 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java @@ -101,7 +101,7 @@ public Integer getScore() { return this.score; } public String getKey(String keyname) { - if (keyname.equals("team")) { + if ("team".equals(keyname)) { return this.team; } else { // return username as default return this.user; @@ -128,7 +128,8 @@ static class ParseEventFn extends DoFn { @ProcessElement public void processElement(ProcessContext c) { - String[] components = c.element().split(","); + System.out.println("GOT " + c.element()); + String[] components = c.element().split(",", -1); try { String user = components[0].trim(); String team = components[1].trim(); diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java index 952cb6fc34..c21ec2e319 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java @@ -90,6 +90,8 @@ class Injector { private static final int THREAD_SLEEP_MS = 500; // Lists used to generate random team names. + // If COLORS is changed, please also make changes in + // release/src/main/groovy/MobileGamingCommands.COLORS private static final ArrayList COLORS = new ArrayList<>( Arrays.asList( @@ -349,12 +351,11 @@ public static void publishDataToFile(String fileName, int numMessages, int delay out.println(message); } } catch (Exception e) { + System.err.print("Error in writing generated events to file"); e.printStackTrace(); } finally { - if (out != null) { - out.flush(); - out.close(); - } + out.flush(); + out.close(); } } @@ -371,7 +372,7 @@ public static void main(String[] args) throws IOException, InterruptedException String fileName = args[2]; // The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if // specified; otherwise, it will try to write to a file. - if (topicName.equalsIgnoreCase("none")) { + if ("none".equalsIgnoreCase(topicName)) { writeToFile = true; writeToPubsub = false; } @@ -383,7 +384,7 @@ public static void main(String[] args) throws IOException, InterruptedException InjectorUtils.createTopic(pubsub, topic); System.out.println("Injecting to topic: " + topic); } else { - if (fileName.equalsIgnoreCase("none")) { + if ("none".equalsIgnoreCase(fileName)) { System.out.println("Filename not specified."); System.exit(1); } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java index ddcbff4f41..5a0cf0166e 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java @@ -86,6 +86,7 @@ public static String getFullyQualifiedTopicName( */ public static void createTopic(Pubsub client, String fullTopicName) throws IOException { + System.out.println("fullTopicName " + fullTopicName); try { client.projects().topics().get(fullTopicName).execute(); } catch (GoogleJsonResponseException e) { diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java index 93da132690..dc28ad72ea 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java @@ -31,5 +31,5 @@ public class GameConstants { public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))); } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java index 45135fb059..76fa3ff075 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java @@ -52,7 +52,7 @@ public class WriteToText private static final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST"))); + .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))); protected String filenamePrefix; protected Map> fieldFn; @@ -98,7 +98,7 @@ public void processElement(ProcessContext c, BoundedWindow window) { * A {@link DoFn} that writes elements to files with names deterministically derived from the * lower and upper bounds of their key (an {@link IntervalWindow}). */ - protected class WriteOneFilePerWindow extends PTransform, PDone> { + protected static class WriteOneFilePerWindow extends PTransform, PDone> { private final String filenamePrefix; diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java index 26e1498d71..0fbee20cb5 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java @@ -37,7 +37,7 @@ public class DebuggingWordCountTest { private String getFilePath(String filePath) { if (filePath.contains(":")) { - return filePath.replace("\\", "/").split(":")[1]; + return filePath.replace("\\", "/").split(":", -1)[1]; } return filePath; } @@ -54,6 +54,6 @@ public void testDebuggingWordCount() throws Exception { TestPipeline.testingPipelineOptions().as(WordCountOptions.class); options.setInputFile(getFilePath(inputFile.getAbsolutePath())); options.setOutput(getFilePath(outputFile.getAbsolutePath())); - DebuggingWordCount.main(TestPipeline.convertToArgs(options)); + DebuggingWordCount.runDebuggingWordCount(options); } } diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java index 83b8821480..b691a0cbd5 100644 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java +++ b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java @@ -91,10 +91,10 @@ public void testParseEventFn() throws Exception { DoFnTester.of(new ParseEventFn()); List results = parseEventFn.processBundle(GAME_EVENTS_ARRAY); - Assert.assertEquals(results.size(), 8); - Assert.assertEquals(results.get(0).getUser(), "user0_MagentaKangaroo"); - Assert.assertEquals(results.get(0).getTeam(), "MagentaKangaroo"); - Assert.assertEquals(results.get(0).getScore(), new Integer(3)); + Assert.assertEquals(8, results.size()); + Assert.assertEquals("user0_MagentaKangaroo", results.get(0).getUser()); + Assert.assertEquals("MagentaKangaroo", results.get(0).getTeam()); + Assert.assertEquals(Integer.valueOf(3), results.get(0).getScore()); } /** Tests ExtractAndSumScore("user"). */ diff --git a/pom.xml b/pom.xml index 4b3108219d..6cf1ef6b6c 100644 --- a/pom.xml +++ b/pom.xml @@ -105,23 +105,24 @@ ${maven.build.timestamp} yyyy-MM-dd HH:mm - 2.4.0 + 2.5.0 Google Cloud Dataflow SDK for Java beam-${beam.version} 6 1 - v2-rev374-1.22.0 + v2-rev374-1.23.0 8.7 1.0.0 - 1.22.0 + 1.23.0 20.0 1.3 2.4 4.12 + 1.0.0 1.9.5 - v1-rev10-1.22.0 + v1-rev382-1.23.0 1.7.25 2.4 @@ -129,16 +130,16 @@ 2.20.1 2.4 3.0.0 - 3.0.0 + 3.1.0 3.7.0 - 3.0.2 + 3.1.1 2.2 3.0.2 3.0.0-M1 2.5.3 - 3.0.2 + 3.1.0 3.1.0 - 2.20.1 + 2.21.0 3.0.1 @@ -431,6 +432,12 @@ ${beam.version} + + org.apache.beam + beam-sdks-java-io-kafka + ${beam.version} + + junit junit From 0e6e1039a276ed183320e51228944daa5542b697 Mon Sep 17 00:00:00 2001 From: Pablo Date: Mon, 25 Jun 2018 14:25:39 -0700 Subject: [PATCH 743/751] [maven-release-plugin] prepare branch release-2.5.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6cf1ef6b6c..43b148a3fe 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.5.0 From eef52e96134085ecbf618b247308b9be0b567789 Mon Sep 17 00:00:00 2001 From: Pablo Date: Mon, 25 Jun 2018 14:25:39 -0700 Subject: [PATCH 744/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 54b3613909..468d87505e 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 2c4a6eb9fe..792eb40c92 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 95f647d608..f995770ea6 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 4e91b8de88..643cfa4096 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index 43b148a3fe..2924ff9fa2 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.5.0 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index 475af49854..21e2a2df0f 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT google-cloud-dataflow-java-sdk-all From 422c8eb2b6e0959627af33375ddcdfe8c98cab8c Mon Sep 17 00:00:00 2001 From: Pablo Date: Tue, 26 Jun 2018 10:13:30 -0700 Subject: [PATCH 745/751] Adding Kafka IO to Dataflow SDK dependencies --- sdk/pom.xml | 5 +++++ .../java/com/google/cloud/dataflow/sdk/SdkDependencies.java | 2 ++ 2 files changed, 7 insertions(+) diff --git a/sdk/pom.xml b/sdk/pom.xml index 21e2a2df0f..0bd69dc58c 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -61,6 +61,11 @@ beam-runners-google-cloud-dataflow-java + + org.apache.beam + beam-sdks-java-io-kafka + + junit junit diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java index 7bbfbe3729..df3fd76ae6 100644 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java +++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java @@ -19,6 +19,7 @@ import org.apache.beam.runners.direct.DirectRunner; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; +import org.apache.beam.sdk.io.kafka.KafkaIO; /** * Mark the dependencies as used at compile time. @@ -26,6 +27,7 @@ class SdkDependencies { private Pipeline p; private BigQueryIO bigQueryIO; + private KafkaIO kafkaIO; private DirectRunner directRunner; private DataflowRunner dataflowRunner; } From 0968379b3d63e3a3e181d7229cba2e8a2b6c3290 Mon Sep 17 00:00:00 2001 From: Pablo Date: Tue, 26 Jun 2018 11:15:47 -0700 Subject: [PATCH 746/751] Revert "[maven-release-plugin] prepare for next development iteration" This reverts commit eef52e96134085ecbf618b247308b9be0b567789. --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 468d87505e..54b3613909 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.6.0-SNAPSHOT + 2.5.0-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 792eb40c92..2c4a6eb9fe 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.6.0-SNAPSHOT + 2.5.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index f995770ea6..95f647d608 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.6.0-SNAPSHOT + 2.5.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 643cfa4096..4e91b8de88 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.6.0-SNAPSHOT + 2.5.0-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index 2924ff9fa2..43b148a3fe 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.6.0-SNAPSHOT + 2.5.0-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.5.0 diff --git a/sdk/pom.xml b/sdk/pom.xml index 0bd69dc58c..d54342364c 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.6.0-SNAPSHOT + 2.5.0-SNAPSHOT google-cloud-dataflow-java-sdk-all From 279fda33114999da2d9158a51a79acdc36a4108c Mon Sep 17 00:00:00 2001 From: Pablo Date: Tue, 26 Jun 2018 11:17:54 -0700 Subject: [PATCH 747/751] Revert "[maven-release-plugin] prepare branch release-2.5.0" This reverts commit 0e6e1039a276ed183320e51228944daa5542b697. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 43b148a3fe..6cf1ef6b6c 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.5.0 + HEAD From e598e911b554e0150853aefff06a510fdbc1fe69 Mon Sep 17 00:00:00 2001 From: Pablo Date: Tue, 26 Jun 2018 13:04:23 -0700 Subject: [PATCH 748/751] [maven-release-plugin] prepare branch release-2.5.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6cf1ef6b6c..43b148a3fe 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD + release-2.5.0 From 0668997c78639ee05d41a2c1ba79899ebba37649 Mon Sep 17 00:00:00 2001 From: Pablo Date: Tue, 26 Jun 2018 13:04:23 -0700 Subject: [PATCH 749/751] [maven-release-plugin] prepare for next development iteration --- examples/pom.xml | 2 +- maven-archetypes/examples/pom.xml | 2 +- maven-archetypes/pom.xml | 2 +- maven-archetypes/starter/pom.xml | 2 +- pom.xml | 4 ++-- sdk/pom.xml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index 54b3613909..468d87505e 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT google-cloud-dataflow-java-examples-all diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml index 2c4a6eb9fe..792eb40c92 100644 --- a/maven-archetypes/examples/pom.xml +++ b/maven-archetypes/examples/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml index 95f647d608..f995770ea6 100644 --- a/maven-archetypes/pom.xml +++ b/maven-archetypes/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT ../pom.xml diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml index 4e91b8de88..643cfa4096 100644 --- a/maven-archetypes/starter/pom.xml +++ b/maven-archetypes/starter/pom.xml @@ -21,7 +21,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-archetypes-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index 43b148a3fe..2924ff9fa2 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ http://cloud.google.com/dataflow 2013 - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT @@ -54,7 +54,7 @@ scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - release-2.5.0 + HEAD diff --git a/sdk/pom.xml b/sdk/pom.xml index d54342364c..0bd69dc58c 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -20,7 +20,7 @@ com.google.cloud.dataflow google-cloud-dataflow-java-sdk-parent - 2.5.0-SNAPSHOT + 2.6.0-SNAPSHOT google-cloud-dataflow-java-sdk-all From 913d720638a37f5ea150cde5734c731192e5ab16 Mon Sep 17 00:00:00 2001 From: Ahmet Altay Date: Wed, 25 Jul 2018 10:40:55 -0700 Subject: [PATCH 750/751] Clean up, and point to Beam locations. --- .gitattributes | 40 -- .gitignore | 30 -- .travis.yml | 54 --- CONTRIBUTING.md | 51 -- LICENSE | 202 -------- NOTICE | 5 - examples/pom.xml | 46 -- .../dataflow/sdk/ExamplesDependencies.java | 29 -- maven-archetypes/examples/pom.xml | 108 ----- .../META-INF/maven/archetype-metadata.xml | 44 -- .../examples/src/main/resources/NOTICE | 5 - .../resources/archetype-resources/pom.xml | 262 ---------- .../src/main/java/DebuggingWordCount.java | 167 ------- .../src/main/java/MinimalWordCount.java | 119 ----- .../src/main/java/WindowedWordCount.java | 225 --------- .../src/main/java/WordCount.java | 194 -------- .../common/ExampleBigQueryTableOptions.java | 55 --- .../src/main/java/common/ExampleOptions.java | 37 -- ...mplePubsubTopicAndSubscriptionOptions.java | 45 -- .../common/ExamplePubsubTopicOptions.java | 45 -- .../src/main/java/common/ExampleUtils.java | 407 ---------------- .../java/common/WriteOneFilePerWindow.java | 117 ----- .../main/java/complete/game/GameStats.java | 346 -------------- .../java/complete/game/HourlyTeamScore.java | 182 ------- .../main/java/complete/game/LeaderBoard.java | 306 ------------ .../java/complete/game/StatefulTeamScore.java | 227 --------- .../main/java/complete/game/UserScore.java | 229 --------- .../java/complete/game/injector/Injector.java | 439 ----------------- .../complete/game/injector/InjectorUtils.java | 101 ---- .../injector/RetryHttpInitializerWrapper.java | 115 ----- .../complete/game/utils/GameConstants.java | 35 -- .../complete/game/utils/WriteToBigQuery.java | 145 ------ .../java/complete/game/utils/WriteToText.java | 183 ------- .../game/utils/WriteWindowedToBigQuery.java | 71 --- .../src/test/java/DebuggingWordCountTest.java | 59 --- .../src/test/java/MinimalWordCountTest.java | 94 ---- .../src/test/java/WordCountTest.java | 85 ---- .../java/complete/game/GameStatsTest.java | 81 ---- .../complete/game/HourlyTeamScoreTest.java | 116 ----- .../java/complete/game/LeaderBoardTest.java | 368 -------------- .../complete/game/StatefulTeamScoreTest.java | 206 -------- .../java/complete/game/UserScoreTest.java | 154 ------ .../projects/basic/archetype.properties | 19 - .../test/resources/projects/basic/goal.txt | 1 - maven-archetypes/pom.xml | 92 ---- maven-archetypes/starter/pom.xml | 93 ---- .../META-INF/maven/archetype-metadata.xml | 36 -- .../starter/src/main/resources/NOTICE | 5 - .../resources/archetype-resources/pom.xml | 93 ---- .../src/main/java/StarterPipeline.java | 69 --- .../projects/basic/archetype.properties | 19 - .../test/resources/projects/basic/goal.txt | 1 - .../projects/basic/reference/pom.xml | 93 ---- .../src/main/java/it/pkg/StarterPipeline.java | 69 --- pom.xml | 449 ------------------ sdk/pom.xml | 75 --- .../cloud/dataflow/sdk/SdkDependencies.java | 33 -- .../dataflow/dataflow-distribution.properties | 20 - .../DataflowRunnerInfoOverrideTest.java | 57 --- sdk/suppressions.xml | 30 -- 60 files changed, 7083 deletions(-) delete mode 100644 .gitattributes delete mode 100644 .gitignore delete mode 100644 .travis.yml delete mode 100644 CONTRIBUTING.md delete mode 100644 LICENSE delete mode 100644 NOTICE delete mode 100644 examples/pom.xml delete mode 100644 examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java delete mode 100644 maven-archetypes/examples/pom.xml delete mode 100644 maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml delete mode 100644 maven-archetypes/examples/src/main/resources/NOTICE delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java delete mode 100644 maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java delete mode 100644 maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties delete mode 100644 maven-archetypes/examples/src/test/resources/projects/basic/goal.txt delete mode 100644 maven-archetypes/pom.xml delete mode 100644 maven-archetypes/starter/pom.xml delete mode 100644 maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml delete mode 100644 maven-archetypes/starter/src/main/resources/NOTICE delete mode 100644 maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml delete mode 100644 maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java delete mode 100644 maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties delete mode 100644 maven-archetypes/starter/src/test/resources/projects/basic/goal.txt delete mode 100644 maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml delete mode 100644 maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java delete mode 100644 pom.xml delete mode 100644 sdk/pom.xml delete mode 100644 sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java delete mode 100644 sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow-distribution.properties delete mode 100644 sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java delete mode 100644 sdk/suppressions.xml diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index c39158cf00..0000000000 --- a/.gitattributes +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed 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. - -# The default behavior, which overrides 'core.autocrlf', is to use Git's -# built-in heuristics to determine whether a particular file is text or binary. -# Text files are automatically normalized to the user's platforms. -* text=auto - -# Explicitly declare text files that should always be normalized and converted -# to native line endings. -.gitattributes text -.gitignore text -LICENSE text -*.avsc text -*.html text -*.java text -*.md text -*.properties text -*.proto text -*.py text -*.sh text -*.xml text -*.yml text - -# Declare files that will always have CRLF line endings on checkout. -# *.sln text eol=crlf - -# Explicitly denote all files that are truly binary and should not be modified. -# *.jpg binary diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 2a27023c28..0000000000 --- a/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed 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. - -target/ - -# Ignore IntelliJ files. -.idea/ -*.iml -*.ipr -*.iws - -# Ignore Eclipse files. -.classpath -.project -.settings/ - -# The build process generates the dependency-reduced POM, but it shouldn't be -# committed. -dependency-reduced-pom.xml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 8fa5d9a932..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed 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. - -language: java - -sudo: false - -notifications: - email: - # Group email notifications are disabled for now, since we cannot do it on a per-branch basis. - # Right now, it would trigger a notification for each fork, which generates a lot of spam. - # recipients: - # - dataflow-sdk-build-notifications+travis@google.com - on_success: change - on_failure: always - -matrix: - include: - # On OSX, run with default JDK only. - - os: osx - # On Linux, run with specific JDKs only. - - os: linux - env: CUSTOM_JDK="oraclejdk8" - # The distribution does not build with Java 7 by design. We need to rewrite these tests - # to, for example, build and install with Java 8 and then test examples with Java 7. - # - os: linux - # env: CUSTOM_JDK="oraclejdk7" - # - os: linux - # env: CUSTOM_JDK="openjdk7" - -before_install: - - if [ "$TRAVIS_OS_NAME" == "osx" ]; then export JAVA_HOME=$(/usr/libexec/java_home); fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then jdk_switcher use "$CUSTOM_JDK"; fi - -install: - - travis_retry mvn install clean -U -DskipTests=true - -script: - # Verify that the project can be built and installed. - - mvn install - # Verify that starter and examples archetypes have the correct version of the NOTICE file. - - diff -q NOTICE maven-archetypes/starter/src/main/resources/NOTICE - - diff -q NOTICE maven-archetypes/examples/src/main/resources/NOTICE diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 9b616e5fe3..0000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,51 +0,0 @@ - - -Want to contribute? Great! First, read this page (including the small print at -the end). - -Google Cloud Dataflow SDK is a distribution of Apache Beam. If you'd like to -change anything under the `org.apache.beam.*` namespace, please submit that -change directly to the [Apache Beam](https://github.com/apache/beam) project. - -This repository contains code to build the Dataflow distribution of Beam, and -some Dataflow-specific code. Only changes to how the distribution is built, or -the Dataflow-specific code under the `com.google.cloud.dataflow.*` namespace, -can be merged here. - -### Before you contribute -Before we can use your code, you must sign the -[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) -(CLA), which you can do online. The CLA is necessary mainly because you own the -copyright to your changes, even after your contribution becomes part of our -codebase, so we need your permission to use and distribute your code. We also -need to be sure of various other things. For instance that you'll tell us if you -know that your code infringes on other people's patents. You don't have to sign -the CLA until after you've submitted your code for review and a member has -approved it, but you must do it before we can put your code into our codebase. - -Before you start working on a larger contribution, we recommend to get in touch -with us first through the issue tracker with your idea so that we can help out -and possibly guide you. Coordinating up front makes it much easier to avoid -frustration later on. - -### Code reviews -All submissions, including submissions by project members, require review. We -use GitHub pull requests for this purpose. - -### The small print -Contributions made by corporations are covered by a different agreement than -the one above, the Software Grant and Corporate Contributor License Agreement. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed 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. diff --git a/NOTICE b/NOTICE deleted file mode 100644 index 981fde5a9e..0000000000 --- a/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Google Cloud Dataflow SDK for Java -Copyright 2017, Google Inc. - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). diff --git a/examples/pom.xml b/examples/pom.xml deleted file mode 100644 index 468d87505e..0000000000 --- a/examples/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - 4.0.0 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-parent - 2.6.0-SNAPSHOT - - - google-cloud-dataflow-java-examples-all - Google Cloud Dataflow Java Examples - All - Google Cloud Dataflow SDK for Java is a distribution of Apache - Beam designed to simplify usage of Apache Beam on Google Cloud Dataflow - service. This artifact includes all Dataflow Java SDK - examples. - - jar - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - - - - org.apache.beam - beam-examples-java - - - diff --git a/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java b/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java deleted file mode 100644 index c51e527edb..0000000000 --- a/examples/src/main/java/com/google/cloud/dataflow/sdk/ExamplesDependencies.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2017 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import org.apache.beam.examples.MinimalWordCount; -import org.apache.beam.examples.WordCount; - -/** - * Mark the examples dependencies as used at compile time. This is also needed - * to produce some content in the final JAR file. - */ -class ExamplesDependencies { - SdkDependencies sdkDependencies; - WordCount wordCount; - MinimalWordCount minimalWordCount; -} diff --git a/maven-archetypes/examples/pom.xml b/maven-archetypes/examples/pom.xml deleted file mode 100644 index 792eb40c92..0000000000 --- a/maven-archetypes/examples/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - 4.0.0 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-archetypes-parent - 2.6.0-SNAPSHOT - ../pom.xml - - - google-cloud-dataflow-java-archetypes-examples - Google Cloud Dataflow SDK for Java - Examples Archetype - Google Cloud Dataflow SDK for Java is a distribution of Apache - Beam designed to simplify usage of Apache Beam on Google Cloud Dataflow - service. This archetype creates a project containing all the example - pipelines. - - maven-archetype - - - - - org.apache.maven.archetype - archetype-packaging - ${archetype-packaging.version} - - - - - - - maven-archetype-plugin - ${maven-archetype-plugin.version} - - - org.apache.maven.shared - maven-invoker - ${maven-invoker.version} - - - - - - default-integration-test - install - - integration-test - - - - - - - - org.eclipse.m2e - lifecycle-mapping - ${eclipse-m2e.version} - - - - - - org.codehaus.mojo - exec-maven-plugin - [1.5.0,) - - exec - - - - - false - - - - - - - - - - - - - diff --git a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml deleted file mode 100644 index 29f8605cce..0000000000 --- a/maven-archetypes/examples/src/main/resources/META-INF/maven/archetype-metadata.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - 1.8 - - - - - - src/main/java - - **/*.java - - - - - src/test/java - - **/*.java - - - - diff --git a/maven-archetypes/examples/src/main/resources/NOTICE b/maven-archetypes/examples/src/main/resources/NOTICE deleted file mode 100644 index 981fde5a9e..0000000000 --- a/maven-archetypes/examples/src/main/resources/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Google Cloud Dataflow SDK for Java -Copyright 2017, Google Inc. - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml deleted file mode 100644 index 04d70618d9..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/pom.xml +++ /dev/null @@ -1,262 +0,0 @@ - - - - 4.0.0 - - ${groupId} - ${artifactId} - ${version} - - jar - - - UTF-8 - - @bigquery.version@ - @google-clients.version@ - @guava.version@ - @hamcrest.version@ - @joda.version@ - @junit.version@ - @maven-compiler-plugin.version@ - @exec-maven-plugin.version@ - @maven-jar-plugin.version@ - @maven-shade-plugin.version@ - @mockito.version@ - @pubsub.version@ - @slf4j.version@ - @surefire-plugin.version@ - - - - - ossrh.snapshots - Sonatype OSS Repository Hosting - https://oss.sonatype.org/content/repositories/snapshots/ - - false - - - true - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${targetPlatform} - ${targetPlatform} - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire-plugin.version} - - all - 4 - true - - - - org.apache.maven.surefire - surefire-junit47 - ${surefire-plugin.version} - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - - package - - shade - - - ${project.artifactId}-bundled-${project.version} - - - *:* - - META-INF/LICENSE - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - false - - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - @project.version@ - - - - - com.google.api-client - google-api-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-bigquery - ${bigquery.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.http-client - google-http-client - ${google-clients.version} - - - - com.google.guava - guava-jdk5 - - - - - - com.google.apis - google-api-services-pubsub - ${pubsub.version} - - - - com.google.guava - guava-jdk5 - - - - - - joda-time - joda-time - ${joda.version} - - - - com.google.guava - guava - ${guava.version} - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - - runtime - - - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - - - - junit - junit - ${junit.version} - - - - org.mockito - mockito-core - ${mockito.version} - test - - - diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java deleted file mode 100644 index 0ae31d575d..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/DebuggingWordCount.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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 ${package}; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.metrics.Counter; -import org.apache.beam.sdk.metrics.Metrics; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * An example that verifies word counts in Shakespeare and includes Beam best practices. - * - *

              This class, {@link DebuggingWordCount}, is the third in a series of four successively more - * detailed 'word count' examples. You may first want to take a look at {@link MinimalWordCount} - * and {@link WordCount}. After you've looked at this example, then see the - * {@link WindowedWordCount} pipeline, for introduction of additional concepts. - * - *

              Basic concepts, also in the MinimalWordCount and WordCount examples: - * Reading text files; counting a PCollection; executing a Pipeline both locally - * and using a selected runner; defining DoFns. - * - *

              New Concepts: - *

              - *   1. Logging using SLF4J, even in a distributed environment
              - *   2. Creating a custom metric (runners have varying levels of support)
              - *   3. Testing your Pipeline via PAssert
              - * 
              - * - *

              To execute this pipeline locally, specify general pipeline configuration: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - * }
              - * 
              - * - *

              To change the runner, specify: - *

              {@code
              - *   --runner=YOUR_SELECTED_RUNNER
              - * }
              - * 
              - * - *

              The input file defaults to a public data set containing the text of of King Lear, - * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. - * - */ -public class DebuggingWordCount { - /** A DoFn that filters for a specific key based upon a regular expression. */ - public static class FilterTextFn extends DoFn, KV> { - /** - * Concept #1: The logger below uses the fully qualified class name of FilterTextFn as the - * logger. Depending on your SLF4J configuration, log statements will likely be qualified by - * this name. - * - *

              Note that this is entirely standard SLF4J usage. Some runners may provide a default SLF4J - * configuration that is most appropriate for their logging integration. - */ - private static final Logger LOG = LoggerFactory.getLogger(FilterTextFn.class); - - private final Pattern filter; - public FilterTextFn(String pattern) { - filter = Pattern.compile(pattern); - } - - /** - * Concept #2: A custom metric can track values in your pipeline as it runs. Each - * runner provides varying levels of support for metrics, and may expose them - * in a dashboard, etc. - */ - private final Counter matchedWords = Metrics.counter(FilterTextFn.class, "matchedWords"); - private final Counter unmatchedWords = Metrics.counter(FilterTextFn.class, "unmatchedWords"); - - @ProcessElement - public void processElement(ProcessContext c) { - if (filter.matcher(c.element().getKey()).matches()) { - // Log at the "DEBUG" level each element that we match. When executing this pipeline - // these log lines will appear only if the log level is set to "DEBUG" or lower. - LOG.debug("Matched: " + c.element().getKey()); - matchedWords.inc(); - c.output(c.element()); - } else { - // Log at the "TRACE" level each element that is not matched. Different log levels - // can be used to control the verbosity of logging providing an effective mechanism - // to filter less important information. - LOG.trace("Did not match: " + c.element().getKey()); - unmatchedWords.inc(); - } - } - } - - /** - * Options supported by {@link DebuggingWordCount}. - * - *

              Inherits standard configuration options and all options defined in - * {@link WordCount.WordCountOptions}. - */ - public interface WordCountOptions extends WordCount.WordCountOptions { - - @Description("Regex filter pattern to use in DebuggingWordCount. " - + "Only words matching this pattern will be counted.") - @Default.String("Flourish|stomach") - String getFilterPattern(); - void setFilterPattern(String value); - } - - static void runDebuggingWordCount(WordCountOptions options) { - Pipeline p = Pipeline.create(options); - - PCollection> filteredWords = - p.apply("ReadLines", TextIO.read().from(options.getInputFile())) - .apply(new WordCount.CountWords()) - .apply(ParDo.of(new FilterTextFn(options.getFilterPattern()))); - - /** - * Concept #3: PAssert is a set of convenient PTransforms in the style of - * Hamcrest's collection matchers that can be used when writing Pipeline level tests - * to validate the contents of PCollections. PAssert is best used in unit tests - * with small data sets but is demonstrated here as a teaching tool. - * - *

              Below we verify that the set of filtered words matches our expected counts. Note - * that PAssert does not provide any output and that successful completion of the - * Pipeline implies that the expectations were met. Learn more at - * https://beam.apache.org/documentation/pipelines/test-your-pipeline/ on how to test - * your Pipeline and see {@link DebuggingWordCountTest} for an example unit test. - */ - List> expectedResults = Arrays.asList( - KV.of("Flourish", 3L), - KV.of("stomach", 1L)); - PAssert.that(filteredWords).containsInAnyOrder(expectedResults); - - p.run().waitUntilFinish(); - } - - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); - - runDebuggingWordCount(options); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java deleted file mode 100644 index f1bd8bfaa8..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/MinimalWordCount.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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 ${package}; - -import java.util.Arrays; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.Count; -import org.apache.beam.sdk.transforms.Filter; -import org.apache.beam.sdk.transforms.FlatMapElements; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.TypeDescriptors; - -/** - * An example that counts words in Shakespeare. - * - *

              This class, {@link MinimalWordCount}, is the first in a series of four successively more - * detailed 'word count' examples. Here, for simplicity, we don't show any error-checking or - * argument processing, and focus on construction of the pipeline, which chains together the - * application of core transforms. - * - *

              Next, see the {@link WordCount} pipeline, then the {@link DebuggingWordCount}, and finally the - * {@link WindowedWordCount} pipeline, for more detailed examples that introduce additional - * concepts. - * - *

              Concepts: - * - *

              - *   1. Reading data from text files
              - *   2. Specifying 'inline' transforms
              - *   3. Counting items in a PCollection
              - *   4. Writing data to text files
              - * 
              - * - *

              No arguments are required to run this pipeline. It will be executed with the DirectRunner. You - * can see the results in the output files in your current working directory, with names like - * "wordcounts-00001-of-00005. When running on a distributed service, you would use an appropriate - * file service. - */ -public class MinimalWordCount { - - public static void main(String[] args) { - - // Create a PipelineOptions object. This object lets us set various execution - // options for our pipeline, such as the runner you wish to use. This example - // will run with the DirectRunner by default, based on the class path configured - // in its dependencies. - PipelineOptions options = PipelineOptionsFactory.create(); - - // In order to run your pipeline, you need to make following runner specific changes: - // - // CHANGE 1/3: Select a Beam runner, such as BlockingDataflowRunner - // or FlinkRunner. - // CHANGE 2/3: Specify runner-required options. - // For BlockingDataflowRunner, set project and temp location as follows: - // DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class); - // dataflowOptions.setRunner(BlockingDataflowRunner.class); - // dataflowOptions.setProject("SET_YOUR_PROJECT_ID_HERE"); - // dataflowOptions.setTempLocation("gs://SET_YOUR_BUCKET_NAME_HERE/AND_TEMP_DIRECTORY"); - // For FlinkRunner, set the runner as follows. See {@code FlinkPipelineOptions} - // for more details. - // options.as(FlinkPipelineOptions.class) - // .setRunner(FlinkRunner.class); - - // Create the Pipeline object with the options we defined above - Pipeline p = Pipeline.create(options); - - // Concept #1: Apply a root transform to the pipeline; in this case, TextIO.Read to read a set - // of input text files. TextIO.Read returns a PCollection where each element is one line from - // the input text (a set of Shakespeare's texts). - - // This example reads a public data set consisting of the complete works of Shakespeare. - p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) - - // Concept #2: Apply a FlatMapElements transform the PCollection of text lines. - // This transform splits the lines in PCollection, where each element is an - // individual word in Shakespeare's collected texts. - .apply(FlatMapElements - .into(TypeDescriptors.strings()) - .via((String word) -> Arrays.asList(word.split("[^\\p{L}]+")))) - // We use a Filter transform to avoid empty word - .apply(Filter.by((String word) -> !word.isEmpty())) - // Concept #3: Apply the Count transform to our PCollection of individual words. The Count - // transform returns a new PCollection of key/value pairs, where each key represents a - // unique word in the text. The associated value is the occurrence count for that word. - .apply(Count.perElement()) - // Apply a MapElements transform that formats our PCollection of word counts into a - // printable string, suitable for writing to an output file. - .apply(MapElements - .into(TypeDescriptors.strings()) - .via((KV wordCount) -> wordCount.getKey() + ": " + wordCount.getValue())) - // Concept #4: Apply a write transform, TextIO.Write, at the end of the pipeline. - // TextIO.Write writes the contents of a PCollection (in this case, our PCollection of - // formatted strings) to a series of text files. - // - // By default, it will write to a set of files with names like wordcounts-00001-of-00005 - .apply(TextIO.write().to("wordcounts")); - - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java deleted file mode 100644 index 5798f290eb..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WindowedWordCount.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * 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 ${package}; - -import java.io.IOException; -import java.util.concurrent.ThreadLocalRandom; -import ${package}.common.ExampleBigQueryTableOptions; -import ${package}.common.ExampleOptions; -import ${package}.common.WriteOneFilePerWindow; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.FixedWindows; -import org.apache.beam.sdk.transforms.windowing.Window; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.joda.time.Duration; -import org.joda.time.Instant; - -/** - * An example that counts words in text, and can run over either unbounded or bounded input - * collections. - * - *

              This class, {@link WindowedWordCount}, is the last in a series of four successively more - * detailed 'word count' examples. First take a look at {@link MinimalWordCount}, - * {@link WordCount}, and {@link DebuggingWordCount}. - * - *

              Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples: - * Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally - * and using a selected runner; defining DoFns; - * user-defined PTransforms; defining PipelineOptions. - * - *

              New Concepts: - *

              - *   1. Unbounded and bounded pipeline input modes
              - *   2. Adding timestamps to data
              - *   3. Windowing
              - *   4. Re-using PTransforms over windowed PCollections
              - *   5. Accessing the window of an element
              - *   6. Writing data to per-window text files
              - * 
              - * - *

              By default, the examples will run with the {@code DirectRunner}. - * To change the runner, specify: - *

              {@code
              - *   --runner=YOUR_SELECTED_RUNNER
              - * }
              - * 
              - * See examples/java/README.md for instructions about how to configure different runners. - * - *

              To execute this pipeline locally, specify a local output file (if using the - * {@code DirectRunner}) or output prefix on a supported distributed file system. - *

              {@code
              - *   --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
              - * }
              - * - *

              The input file defaults to a public data set containing the text of of King Lear, - * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. - * - *

              By default, the pipeline will do fixed windowing, on 1-minute windows. You can - * change this interval by setting the {@code --windowSize} parameter, e.g. {@code --windowSize=10} - * for 10-minute windows. - * - *

              The example will try to cancel the pipeline on the signal to terminate the process (CTRL-C). - */ -public class WindowedWordCount { - static final int WINDOW_SIZE = 10; // Default window duration in minutes - /** - * Concept #2: A DoFn that sets the data element timestamp. This is a silly method, just for - * this example, for the bounded data case. - * - *

              Imagine that many ghosts of Shakespeare are all typing madly at the same time to recreate - * his masterworks. Each line of the corpus will get a random associated timestamp somewhere in a - * 2-hour period. - */ - static class AddTimestampFn extends DoFn { - private final Instant minTimestamp; - private final Instant maxTimestamp; - - AddTimestampFn(Instant minTimestamp, Instant maxTimestamp) { - this.minTimestamp = minTimestamp; - this.maxTimestamp = maxTimestamp; - } - - @ProcessElement - public void processElement(@Element String element, OutputReceiver receiver) { - Instant randomTimestamp = - new Instant( - ThreadLocalRandom.current() - .nextLong(minTimestamp.getMillis(), maxTimestamp.getMillis())); - - /** - * Concept #2: Set the data element with that timestamp. - */ - receiver.outputWithTimestamp(element, new Instant(randomTimestamp)); - } - } - - /** A {@link DefaultValueFactory} that returns the current system time. */ - public static class DefaultToCurrentSystemTime implements DefaultValueFactory { - @Override - public Long create(PipelineOptions options) { - return System.currentTimeMillis(); - } - } - - /** A {@link DefaultValueFactory} that returns the minimum timestamp plus one hour. */ - public static class DefaultToMinTimestampPlusOneHour implements DefaultValueFactory { - @Override - public Long create(PipelineOptions options) { - return options.as(Options.class).getMinTimestampMillis() - + Duration.standardHours(1).getMillis(); - } - } - - /** - * Options for {@link WindowedWordCount}. - * - *

              Inherits standard example configuration options, which allow specification of the - * runner, as well as the {@link WordCount.WordCountOptions} support for - * specification of the input and output files. - */ - public interface Options extends WordCount.WordCountOptions, - ExampleOptions, ExampleBigQueryTableOptions { - @Description("Fixed window duration, in minutes") - @Default.Integer(WINDOW_SIZE) - Integer getWindowSize(); - void setWindowSize(Integer value); - - @Description("Minimum randomly assigned timestamp, in milliseconds-since-epoch") - @Default.InstanceFactory(DefaultToCurrentSystemTime.class) - Long getMinTimestampMillis(); - void setMinTimestampMillis(Long value); - - @Description("Maximum randomly assigned timestamp, in milliseconds-since-epoch") - @Default.InstanceFactory(DefaultToMinTimestampPlusOneHour.class) - Long getMaxTimestampMillis(); - void setMaxTimestampMillis(Long value); - - @Description("Fixed number of shards to produce per window") - Integer getNumShards(); - void setNumShards(Integer numShards); - } - - static void runWindowedWordCount(Options options) throws IOException { - final String output = options.getOutput(); - final Instant minTimestamp = new Instant(options.getMinTimestampMillis()); - final Instant maxTimestamp = new Instant(options.getMaxTimestampMillis()); - - Pipeline pipeline = Pipeline.create(options); - - /** - * Concept #1: the Beam SDK lets us run the same pipeline with either a bounded or - * unbounded input source. - */ - PCollection input = pipeline - /** Read from the GCS file. */ - .apply(TextIO.read().from(options.getInputFile())) - // Concept #2: Add an element timestamp, using an artificial time just to show windowing. - // See AddTimestampFn for more detail on this. - .apply(ParDo.of(new AddTimestampFn(minTimestamp, maxTimestamp))); - - /** - * Concept #3: Window into fixed windows. The fixed window size for this example defaults to 1 - * minute (you can change this with a command-line option). See the documentation for more - * information on how fixed windows work, and for information on the other types of windowing - * available (e.g., sliding windows). - */ - PCollection windowedWords = - input.apply( - Window.into(FixedWindows.of(Duration.standardMinutes(options.getWindowSize())))); - - /** - * Concept #4: Re-use our existing CountWords transform that does not have knowledge of - * windows over a PCollection containing windowed values. - */ - PCollection> wordCounts = windowedWords.apply(new WordCount.CountWords()); - - /** - * Concept #5: Format the results and write to a sharded file partitioned by window, using a - * simple ParDo operation. Because there may be failures followed by retries, the - * writes must be idempotent, but the details of writing to files is elided here. - */ - wordCounts - .apply(MapElements.via(new WordCount.FormatAsTextFn())) - .apply(new WriteOneFilePerWindow(output, options.getNumShards())); - - PipelineResult result = pipeline.run(); - try { - result.waitUntilFinish(); - } catch (Exception exc) { - result.cancel(); - } - } - - public static void main(String[] args) throws IOException { - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - - runWindowedWordCount(options); - } - -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java deleted file mode 100644 index d4302ed67a..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * 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 ${package}; - -import ${package}.common.ExampleUtils; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.metrics.Counter; -import org.apache.beam.sdk.metrics.Distribution; -import org.apache.beam.sdk.metrics.Metrics; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.options.Validation.Required; -import org.apache.beam.sdk.transforms.Count; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.SimpleFunction; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; - -/** - * An example that counts words in Shakespeare and includes Beam best practices. - * - *

              This class, {@link WordCount}, is the second in a series of four successively more detailed - * 'word count' examples. You may first want to take a look at {@link MinimalWordCount}. - * After you've looked at this example, then see the {@link DebuggingWordCount} - * pipeline, for introduction of additional concepts. - * - *

              For a detailed walkthrough of this example, see - * - * https://beam.apache.org/get-started/wordcount-example/ - * - * - *

              Basic concepts, also in the MinimalWordCount example: - * Reading text files; counting a PCollection; writing to text files - * - *

              New Concepts: - *

              - *   1. Executing a Pipeline both locally and using the selected runner
              - *   2. Using ParDo with static DoFns defined out-of-line
              - *   3. Building a composite transform
              - *   4. Defining your own pipeline options
              - * 
              - * - *

              Concept #1: you can execute this pipeline either locally or using by selecting another runner. - * These are now command-line options and not hard-coded as they were in the MinimalWordCount - * example. - * - *

              To change the runner, specify: - *

              {@code
              - *   --runner=YOUR_SELECTED_RUNNER
              - * }
              - * 
              - * - *

              To execute this pipeline, specify a local output file (if using the - * {@code DirectRunner}) or output prefix on a supported distributed file system. - *

              {@code
              - *   --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
              - * }
              - * - *

              The input file defaults to a public data set containing the text of of King Lear, - * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. - */ -public class WordCount { - - /** - * Concept #2: You can make your pipeline assembly code less verbose by defining your DoFns - * statically out-of-line. This DoFn tokenizes lines of text into individual words; we pass it - * to a ParDo in the pipeline. - */ - static class ExtractWordsFn extends DoFn { - private final Counter emptyLines = Metrics.counter(ExtractWordsFn.class, "emptyLines"); - private final Distribution lineLenDist = Metrics.distribution( - ExtractWordsFn.class, "lineLenDistro"); - - @ProcessElement - public void processElement(@Element String element, OutputReceiver receiver) { - lineLenDist.update(element.length()); - if (element.trim().isEmpty()) { - emptyLines.inc(); - } - - // Split the line into words. - String[] words = element.split(ExampleUtils.TOKENIZER_PATTERN, -1); - - // Output each word encountered into the output PCollection. - for (String word : words) { - if (!word.isEmpty()) { - receiver.output(word); - } - } - } - } - - /** A SimpleFunction that converts a Word and Count into a printable string. */ - public static class FormatAsTextFn extends SimpleFunction, String> { - @Override - public String apply(KV input) { - return input.getKey() + ": " + input.getValue(); - } - } - - /** - * A PTransform that converts a PCollection containing lines of text into a PCollection of - * formatted word counts. - * - *

              Concept #3: This is a custom composite transform that bundles two transforms (ParDo and - * Count) as a reusable PTransform subclass. Using composite transforms allows for easy reuse, - * modular testing, and an improved monitoring experience. - */ - public static class CountWords extends PTransform, - PCollection>> { - @Override - public PCollection> expand(PCollection lines) { - - // Convert lines of text into individual words. - PCollection words = lines.apply( - ParDo.of(new ExtractWordsFn())); - - // Count the number of times each word occurs. - PCollection> wordCounts = words.apply(Count.perElement()); - - return wordCounts; - } - } - - /** - * Options supported by {@link WordCount}. - * - *

              Concept #4: Defining your own configuration options. Here, you can add your own arguments - * to be processed by the command-line parser, and specify default values for them. You can then - * access the options values in your pipeline code. - * - *

              Inherits standard configuration options. - */ - public interface WordCountOptions extends PipelineOptions { - - /** - * By default, this example reads from a public dataset containing the text of - * King Lear. Set this option to choose a different input file or glob. - */ - @Description("Path of the file to read from") - @Default.String("gs://apache-beam-samples/shakespeare/kinglear.txt") - String getInputFile(); - void setInputFile(String value); - - /** - * Set this required option to specify where to write the output. - */ - @Description("Path of the file to write to") - @Required - String getOutput(); - void setOutput(String value); - } - - static void runWordCount(WordCountOptions options) { - Pipeline p = Pipeline.create(options); - - // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the - // static FormatAsTextFn() to the ParDo transform. - p.apply("ReadLines", TextIO.read().from(options.getInputFile())) - .apply(new CountWords()) - .apply(MapElements.via(new FormatAsTextFn())) - .apply("WriteCounts", TextIO.write().to(options.getOutput())); - - p.run().waitUntilFinish(); - } - - public static void main(String[] args) { - WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() - .as(WordCountOptions.class); - - runWordCount(options); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java deleted file mode 100644 index 57f1546e27..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleBigQueryTableOptions.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 ${package}.common; - -import com.google.api.services.bigquery.model.TableSchema; -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure BigQuery tables in Beam examples. - * The project defaults to the project being used to run the example. - */ -public interface ExampleBigQueryTableOptions extends GcpOptions { - @Description("BigQuery dataset name") - @Default.String("beam_examples") - String getBigQueryDataset(); - void setBigQueryDataset(String dataset); - - @Description("BigQuery table name") - @Default.InstanceFactory(BigQueryTableFactory.class) - String getBigQueryTable(); - void setBigQueryTable(String table); - - @Description("BigQuery table schema") - TableSchema getBigQuerySchema(); - void setBigQuerySchema(TableSchema schema); - - /** - * Returns the job name as the default BigQuery table name. - */ - class BigQueryTableFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return options.getJobName().replace('-', '_'); - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java deleted file mode 100644 index 90f935c3ce..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleOptions.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 ${package}.common; - -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure the Beam examples. - */ -public interface ExampleOptions extends PipelineOptions { - @Description("Whether to keep jobs running after local process exit") - @Default.Boolean(false) - boolean getKeepJobsRunning(); - void setKeepJobsRunning(boolean keepJobsRunning); - - @Description("Number of workers to use when executing the injector pipeline") - @Default.Integer(1) - int getInjectorNumWorkers(); - void setInjectorNumWorkers(int numWorkers); -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java deleted file mode 100644 index cf142a10fd..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicAndSubscriptionOptions.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 ${package}.common; - -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure Pub/Sub topic/subscription in Beam examples. - */ -public interface ExamplePubsubTopicAndSubscriptionOptions extends ExamplePubsubTopicOptions { - @Description("Pub/Sub subscription") - @Default.InstanceFactory(PubsubSubscriptionFactory.class) - String getPubsubSubscription(); - void setPubsubSubscription(String subscription); - - /** - * Returns a default Pub/Sub subscription based on the project and the job names. - */ - class PubsubSubscriptionFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return "projects/" + options.as(GcpOptions.class).getProject() - + "/subscriptions/" + options.getJobName(); - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java deleted file mode 100644 index 86784b06da..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExamplePubsubTopicOptions.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 ${package}.common; - -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.DefaultValueFactory; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; - -/** - * Options that can be used to configure Pub/Sub topic in Beam examples. - */ -public interface ExamplePubsubTopicOptions extends GcpOptions { - @Description("Pub/Sub topic") - @Default.InstanceFactory(PubsubTopicFactory.class) - String getPubsubTopic(); - void setPubsubTopic(String topic); - - /** - * Returns a default Pub/Sub topic based on the project and the job names. - */ - class PubsubTopicFactory implements DefaultValueFactory { - @Override - public String create(PipelineOptions options) { - return "projects/" + options.as(GcpOptions.class).getProject() - + "/topics/" + options.getJobName(); - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java deleted file mode 100644 index e1159b9018..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/ExampleUtils.java +++ /dev/null @@ -1,407 +0,0 @@ -/* - * 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 ${package}.common; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.services.bigquery.Bigquery; -import com.google.api.services.bigquery.Bigquery.Datasets; -import com.google.api.services.bigquery.Bigquery.Tables; -import com.google.api.services.bigquery.model.Dataset; -import com.google.api.services.bigquery.model.DatasetReference; -import com.google.api.services.bigquery.model.Table; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableSchema; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.Subscription; -import com.google.api.services.pubsub.model.Topic; -import com.google.auth.Credentials; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.common.util.concurrent.Uninterruptibles; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.extensions.gcp.auth.NullCredentialInitializer; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryOptions; -import org.apache.beam.sdk.io.gcp.pubsub.PubsubOptions; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.util.BackOff; -import org.apache.beam.sdk.util.BackOffUtils; -import org.apache.beam.sdk.util.FluentBackoff; -import org.apache.beam.sdk.util.RetryHttpRequestInitializer; -import org.apache.beam.sdk.util.Sleeper; -import org.apache.beam.sdk.util.Transport; -import org.joda.time.Duration; - -/** - * The utility class that sets up and tears down external resources, - * and cancels the streaming pipelines once the program terminates. - * - *

              It is used to run Beam examples. - */ -public class ExampleUtils { - - private static final int SC_NOT_FOUND = 404; - - /** - * \p{L} denotes the category of Unicode letters, - * so this pattern will match on everything that is not a letter. - * - *

              It is used for tokenizing strings in the wordcount examples. - */ - public static final String TOKENIZER_PATTERN = "[^\\p{L}]+"; - - private final PipelineOptions options; - private Bigquery bigQueryClient = null; - private Pubsub pubsubClient = null; - private Set pipelinesToCancel = Sets.newHashSet(); - private List pendingMessages = Lists.newArrayList(); - - /** - * Do resources and runner options setup. - */ - public ExampleUtils(PipelineOptions options) { - this.options = options; - } - - /** - * Sets up external resources that are required by the example, - * such as Pub/Sub topics and BigQuery tables. - * - * @throws IOException if there is a problem setting up the resources - */ - public void setup() throws IOException { - Sleeper sleeper = Sleeper.DEFAULT; - BackOff backOff = - FluentBackoff.DEFAULT - .withMaxRetries(3).withInitialBackoff(Duration.millis(200)).backoff(); - Throwable lastException = null; - try { - do { - try { - setupPubsub(); - setupBigQueryTable(); - return; - } catch (GoogleJsonResponseException e) { - lastException = e; - } - } while (BackOffUtils.next(sleeper, backOff)); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - // Ignore InterruptedException - } - throw new RuntimeException(lastException); - } - - /** - * Sets up the Google Cloud Pub/Sub topic. - * - *

              If the topic doesn't exist, a new topic with the given name will be created. - * - * @throws IOException if there is a problem setting up the Pub/Sub topic - */ - public void setupPubsub() throws IOException { - ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = - options.as(ExamplePubsubTopicAndSubscriptionOptions.class); - if (!pubsubOptions.getPubsubTopic().isEmpty()) { - pendingMessages.add("**********************Set Up Pubsub************************"); - setupPubsubTopic(pubsubOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been set up for this example: " - + pubsubOptions.getPubsubTopic()); - - if (!pubsubOptions.getPubsubSubscription().isEmpty()) { - setupPubsubSubscription( - pubsubOptions.getPubsubTopic(), pubsubOptions.getPubsubSubscription()); - pendingMessages.add("The Pub/Sub subscription has been set up for this example: " - + pubsubOptions.getPubsubSubscription()); - } - } - } - - /** - * Sets up the BigQuery table with the given schema. - * - *

              If the table already exists, the schema has to match the given one. Otherwise, the example - * will throw a RuntimeException. If the table doesn't exist, a new table with the given schema - * will be created. - * - * @throws IOException if there is a problem setting up the BigQuery table - */ - public void setupBigQueryTable() throws IOException { - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("******************Set Up Big Query Table*******************"); - setupBigQueryTable(bigQueryTableOptions.getProject(), - bigQueryTableOptions.getBigQueryDataset(), - bigQueryTableOptions.getBigQueryTable(), - bigQueryTableOptions.getBigQuerySchema()); - pendingMessages.add("The BigQuery table has been set up for this example: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - } - } - - /** - * Tears down external resources that can be deleted upon the example's completion. - */ - private void tearDown() { - pendingMessages.add("*************************Tear Down*************************"); - ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = - options.as(ExamplePubsubTopicAndSubscriptionOptions.class); - if (!pubsubOptions.getPubsubTopic().isEmpty()) { - try { - deletePubsubTopic(pubsubOptions.getPubsubTopic()); - pendingMessages.add("The Pub/Sub topic has been deleted: " - + pubsubOptions.getPubsubTopic()); - } catch (IOException e) { - pendingMessages.add("Failed to delete the Pub/Sub topic : " - + pubsubOptions.getPubsubTopic()); - } - if (!pubsubOptions.getPubsubSubscription().isEmpty()) { - try { - deletePubsubSubscription(pubsubOptions.getPubsubSubscription()); - pendingMessages.add("The Pub/Sub subscription has been deleted: " - + pubsubOptions.getPubsubSubscription()); - } catch (IOException e) { - pendingMessages.add("Failed to delete the Pub/Sub subscription : " - + pubsubOptions.getPubsubSubscription()); - } - } - } - - ExampleBigQueryTableOptions bigQueryTableOptions = - options.as(ExampleBigQueryTableOptions.class); - if (bigQueryTableOptions.getBigQueryDataset() != null - && bigQueryTableOptions.getBigQueryTable() != null - && bigQueryTableOptions.getBigQuerySchema() != null) { - pendingMessages.add("The BigQuery table might contain the example's output, " - + "and it is not deleted automatically: " - + bigQueryTableOptions.getProject() - + ":" + bigQueryTableOptions.getBigQueryDataset() - + "." + bigQueryTableOptions.getBigQueryTable()); - pendingMessages.add("Please go to the Developers Console to delete it manually." - + " Otherwise, you may be charged for its usage."); - } - } - - /** - * Returns a BigQuery client builder using the specified {@link BigQueryOptions}. - */ - private static Bigquery.Builder newBigQueryClient(BigQueryOptions options) { - return new Bigquery.Builder(Transport.getTransport(), Transport.getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - /** - * Returns a Pubsub client builder using the specified {@link PubsubOptions}. - */ - private static Pubsub.Builder newPubsubClient(PubsubOptions options) { - return new Pubsub.Builder(Transport.getTransport(), Transport.getJsonFactory(), - chainHttpRequestInitializer( - options.getGcpCredential(), - // Do not log 404. It clutters the output and is possibly even required by the caller. - new RetryHttpRequestInitializer(ImmutableList.of(404)))) - .setRootUrl(options.getPubsubRootUrl()) - .setApplicationName(options.getAppName()) - .setGoogleClientRequestInitializer(options.getGoogleApiTrace()); - } - - private static HttpRequestInitializer chainHttpRequestInitializer( - Credentials credential, HttpRequestInitializer httpRequestInitializer) { - if (credential == null) { - return new ChainingHttpRequestInitializer( - new NullCredentialInitializer(), httpRequestInitializer); - } else { - return new ChainingHttpRequestInitializer( - new HttpCredentialsAdapter(credential), - httpRequestInitializer); - } - } - - private void setupBigQueryTable(String projectId, String datasetId, String tableId, - TableSchema schema) throws IOException { - if (bigQueryClient == null) { - bigQueryClient = newBigQueryClient(options.as(BigQueryOptions.class)).build(); - } - - Datasets datasetService = bigQueryClient.datasets(); - if (executeNullIfNotFound(datasetService.get(projectId, datasetId)) == null) { - Dataset newDataset = new Dataset().setDatasetReference( - new DatasetReference().setProjectId(projectId).setDatasetId(datasetId)); - datasetService.insert(projectId, newDataset).execute(); - } - - Tables tableService = bigQueryClient.tables(); - Table table = executeNullIfNotFound(tableService.get(projectId, datasetId, tableId)); - if (table == null) { - Table newTable = new Table().setSchema(schema).setTableReference( - new TableReference().setProjectId(projectId).setDatasetId(datasetId).setTableId(tableId)); - tableService.insert(projectId, datasetId, newTable).execute(); - } else if (!table.getSchema().equals(schema)) { - throw new RuntimeException( - "Table exists and schemas do not match, expecting: " + schema.toPrettyString() - + ", actual: " + table.getSchema().toPrettyString()); - } - } - - private void setupPubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) == null) { - pubsubClient.projects().topics().create(topic, new Topic().setName(topic)).execute(); - } - } - - private void setupPubsubSubscription(String topic, String subscription) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) == null) { - Subscription subInfo = new Subscription() - .setAckDeadlineSeconds(60) - .setTopic(topic); - pubsubClient.projects().subscriptions().create(subscription, subInfo).execute(); - } - } - - /** - * Deletes the Google Cloud Pub/Sub topic. - * - * @throws IOException if there is a problem deleting the Pub/Sub topic - */ - private void deletePubsubTopic(String topic) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().topics().get(topic)) != null) { - pubsubClient.projects().topics().delete(topic).execute(); - } - } - - /** - * Deletes the Google Cloud Pub/Sub subscription. - * - * @throws IOException if there is a problem deleting the Pub/Sub subscription - */ - private void deletePubsubSubscription(String subscription) throws IOException { - if (pubsubClient == null) { - pubsubClient = newPubsubClient(options.as(PubsubOptions.class)).build(); - } - if (executeNullIfNotFound(pubsubClient.projects().subscriptions().get(subscription)) != null) { - pubsubClient.projects().subscriptions().delete(subscription).execute(); - } - } - - /** - * Waits for the pipeline to finish and cancels it before the program exists. - */ - public void waitToFinish(PipelineResult result) { - pipelinesToCancel.add(result); - if (!options.as(ExampleOptions.class).getKeepJobsRunning()) { - addShutdownHook(pipelinesToCancel); - } - try { - result.waitUntilFinish(); - } catch (UnsupportedOperationException e) { - // Do nothing if the given PipelineResult doesn't support waitUntilFinish(), - // such as EvaluationResults returned by DirectRunner. - tearDown(); - printPendingMessages(); - } catch (Exception e) { - throw new RuntimeException("Failed to wait the pipeline until finish: " + result); - } - } - - private void addShutdownHook(final Collection pipelineResults) { - Runtime.getRuntime() - .addShutdownHook( - new Thread( - () -> { - tearDown(); - printPendingMessages(); - for (PipelineResult pipelineResult : pipelineResults) { - try { - pipelineResult.cancel(); - } catch (IOException e) { - System.out.println("Failed to cancel the job."); - System.out.println(e.getMessage()); - } - } - - for (PipelineResult pipelineResult : pipelineResults) { - boolean cancellationVerified = false; - for (int retryAttempts = 6; retryAttempts > 0; retryAttempts--) { - if (pipelineResult.getState().isTerminal()) { - cancellationVerified = true; - break; - } else { - System.out.println( - "The example pipeline is still running. Verifying the cancellation."); - } - Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); - } - if (!cancellationVerified) { - System.out.println( - "Failed to verify the cancellation for job: " + pipelineResult); - } - } - })); - } - - private void printPendingMessages() { - System.out.println(); - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - for (String message : pendingMessages) { - System.out.println(message); - } - System.out.println("***********************************************************"); - System.out.println("***********************************************************"); - } - - private static T executeNullIfNotFound( - AbstractGoogleClientRequest request) throws IOException { - try { - return request.execute(); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == SC_NOT_FOUND) { - return null; - } else { - throw e; - } - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java deleted file mode 100644 index 9796d647b5..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/common/WriteOneFilePerWindow.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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 ${package}.common; - -import static com.google.common.base.MoreObjects.firstNonNull; - -import javax.annotation.Nullable; -import org.apache.beam.sdk.io.FileBasedSink; -import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; -import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; -import org.apache.beam.sdk.io.fs.ResourceId; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.PaneInfo; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PDone; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -/** - * A {@link DoFn} that writes elements to files with names deterministically derived from the lower - * and upper bounds of their key (an {@link IntervalWindow}). - * - *

              This is test utility code, not for end-users, so examples can be focused on their primary - * lessons. - */ -public class WriteOneFilePerWindow extends PTransform, PDone> { - private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.hourMinute(); - private String filenamePrefix; - @Nullable - private Integer numShards; - - public WriteOneFilePerWindow(String filenamePrefix, Integer numShards) { - this.filenamePrefix = filenamePrefix; - this.numShards = numShards; - } - - @Override - public PDone expand(PCollection input) { - ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); - TextIO.Write write = - TextIO.write() - .to(new PerWindowFiles(resource)) - .withTempDirectory(resource.getCurrentDirectory()) - .withWindowedWrites(); - if (numShards != null) { - write = write.withNumShards(numShards); - } - return input.apply(write); - } - - /** - * A {@link FilenamePolicy} produces a base file name for a write based on metadata about the data - * being written. This always includes the shard number and the total number of shards. For - * windowed writes, it also includes the window and pane index (a sequence number assigned to each - * trigger firing). - */ - public static class PerWindowFiles extends FilenamePolicy { - - private final ResourceId baseFilename; - - public PerWindowFiles(ResourceId baseFilename) { - this.baseFilename = baseFilename; - } - - public String filenamePrefixForWindow(IntervalWindow window) { - String prefix = - baseFilename.isDirectory() ? "" : firstNonNull(baseFilename.getFilename(), ""); - return String.format("%s-%s-%s", - prefix, FORMATTER.print(window.start()), FORMATTER.print(window.end())); - } - - @Override - public ResourceId windowedFilename(int shardNumber, - int numShards, - BoundedWindow window, - PaneInfo paneInfo, - OutputFileHints outputFileHints) { - IntervalWindow intervalWindow = (IntervalWindow) window; - String filename = - String.format( - "%s-%s-of-%s%s", - filenamePrefixForWindow(intervalWindow), - shardNumber, - numShards, - outputFileHints.getSuggestedFilenameSuffix()); - return baseFilename - .getCurrentDirectory() - .resolve(filename, StandardResolveOptions.RESOLVE_FILE); - } - - @Override - public ResourceId unwindowedFilename( - int shardNumber, int numShards, OutputFileHints outputFileHints) { - throw new UnsupportedOperationException("Unsupported."); - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java deleted file mode 100644 index 2660cdac2b..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/GameStats.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import java.util.HashMap; -import java.util.Map; -import ${package}.common.ExampleUtils; -import ${package}.complete.game.utils.GameConstants; -import ${package}.complete.game.utils.WriteWindowedToBigQuery; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO; -import org.apache.beam.sdk.metrics.Counter; -import org.apache.beam.sdk.metrics.Metrics; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.Combine; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.Mean; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.Sum; -import org.apache.beam.sdk.transforms.Values; -import org.apache.beam.sdk.transforms.View; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.FixedWindows; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.Sessions; -import org.apache.beam.sdk.transforms.windowing.TimestampCombiner; -import org.apache.beam.sdk.transforms.windowing.Window; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PCollectionView; -import org.apache.beam.sdk.values.TypeDescriptors; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is the fourth in a series of four pipelines that tell a story in a 'gaming' - * domain, following {@link UserScore}, {@link HourlyTeamScore}, and {@link LeaderBoard}. - * New concepts: session windows and finding session duration; use of both - * singleton and non-singleton side inputs. - * - *

              This pipeline builds on the {@link LeaderBoard} functionality, and adds some "business - * intelligence" analysis: abuse detection and usage patterns. The pipeline derives the Mean user - * score sum for a window, and uses that information to identify likely spammers/robots. (The robots - * have a higher click rate than the human users). The 'robot' users are then filtered out when - * calculating the team scores. - * - *

              Additionally, user sessions are tracked: that is, we find bursts of user activity using - * session windows. Then, the mean session duration information is recorded in the context of - * subsequent fixed windowing. (This could be used to tell us what games are giving us greater - * user retention). - * - *

              Run {@code org.apache.beam.examples.complete.game.injector.Injector} to generate - * pubsub data for this pipeline. The {@code Injector} documentation provides more detail. - * - *

              To execute this pipeline, specify the pipeline configuration like this: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              - *   --runner=YOUR_RUNNER
              - *   --dataset=YOUR-DATASET
              - *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              - * }
              - * 
              - * - *

              The BigQuery dataset you specify must already exist. The PubSub topic you specify should - * be the same topic to which the Injector is publishing. - */ -public class GameStats extends LeaderBoard { - - /** - * Filter out all users but those with a high clickrate, which we will consider as 'spammy' users. - * We do this by finding the mean total score per user, then using that information as a side - * input to filter out all but those user scores that are larger than - * {@code (mean * SCORE_WEIGHT)}. - */ - // [START DocInclude_AbuseDetect] - public static class CalculateSpammyUsers - extends PTransform>, PCollection>> { - private static final Logger LOG = LoggerFactory.getLogger(CalculateSpammyUsers.class); - private static final double SCORE_WEIGHT = 2.5; - - @Override - public PCollection> expand(PCollection> userScores) { - - // Get the sum of scores for each user. - PCollection> sumScores = - userScores.apply("UserSum", Sum.integersPerKey()); - - // Extract the score from each element, and use it to find the global mean. - final PCollectionView globalMeanScore = - sumScores.apply(Values.create()).apply(Mean.globally().asSingletonView()); - - // Filter the user sums using the global mean. - PCollection> filtered = sumScores - .apply("ProcessAndFilter", ParDo - // use the derived mean total score as a side input - .of(new DoFn, KV>() { - private final Counter numSpammerUsers = Metrics.counter("main", "SpammerUsers"); - @ProcessElement - public void processElement(ProcessContext c) { - Integer score = c.element().getValue(); - Double gmc = c.sideInput(globalMeanScore); - if (score > (gmc * SCORE_WEIGHT)) { - LOG.info("user " + c.element().getKey() + " spammer score " + score - + " with mean " + gmc); - numSpammerUsers.inc(); - c.output(c.element()); - } - } - }).withSideInputs(globalMeanScore)); - return filtered; - } - } - // [END DocInclude_AbuseDetect] - - /** - * Calculate and output an element's session duration. - */ - private static class UserSessionInfoFn extends DoFn, Integer> { - @ProcessElement - public void processElement(ProcessContext c, BoundedWindow window) { - IntervalWindow w = (IntervalWindow) window; - int duration = new Duration( - w.start(), w.end()).toPeriod().toStandardMinutes().getMinutes(); - c.output(duration); - } - } - - - /** - * Options supported by {@link GameStats}. - */ - public interface Options extends LeaderBoard.Options { - @Description("Numeric value of fixed window duration for user analysis, in minutes") - @Default.Integer(60) - Integer getFixedWindowDuration(); - void setFixedWindowDuration(Integer value); - - @Description("Numeric value of gap between user sessions, in minutes") - @Default.Integer(5) - Integer getSessionGap(); - void setSessionGap(Integer value); - - @Description("Numeric value of fixed window for finding mean of user session duration, " - + "in minutes") - @Default.Integer(30) - Integer getUserActivityWindowDuration(); - void setUserActivityWindowDuration(Integer value); - - @Description("Prefix used for the BigQuery table names") - @Default.String("game_stats") - String getGameStatsTablePrefix(); - void setGameStatsTablePrefix(String value); - } - - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write information about team score sums. - */ - protected static Map>> - configureWindowedWrite() { - Map>> tableConfigure = - new HashMap<>(); - tableConfigure.put( - "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); - tableConfigure.put( - "total_score", - new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); - tableConfigure.put( - "window_start", - new WriteWindowedToBigQuery.FieldInfo<>( - "STRING", - (c, w) -> { - IntervalWindow window = (IntervalWindow) w; - return GameConstants.DATE_TIME_FORMATTER.print(window.start()); - })); - tableConfigure.put( - "processing_time", - new WriteWindowedToBigQuery.FieldInfo<>( - "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); - return tableConfigure; - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write information about mean user session time. - */ - protected static Map> - configureSessionWindowWrite() { - - Map> tableConfigure = new HashMap<>(); - tableConfigure.put( - "window_start", - new WriteWindowedToBigQuery.FieldInfo<>( - "STRING", - (c, w) -> { - IntervalWindow window = (IntervalWindow) w; - return GameConstants.DATE_TIME_FORMATTER.print(window.start()); - })); - tableConfigure.put( - "mean_duration", new WriteWindowedToBigQuery.FieldInfo<>("FLOAT", (c, w) -> c.element())); - return tableConfigure; - } - - - - public static void main(String[] args) throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - // Enforce that this pipeline is always run in streaming mode. - options.setStreaming(true); - ExampleUtils exampleUtils = new ExampleUtils(options); - Pipeline pipeline = Pipeline.create(options); - - // Read Events from Pub/Sub using custom timestamps - PCollection rawEvents = pipeline - .apply(PubsubIO.readStrings() - .withTimestampAttribute(GameConstants.TIMESTAMP_ATTRIBUTE) - .fromTopic(options.getTopic())) - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())); - - // Extract username/score pairs from the event stream - PCollection> userEvents = - rawEvents.apply("ExtractUserScore", - MapElements - .into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) - .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore()))); - - // Calculate the total score per user over fixed windows, and - // cumulative updates for late data. - final PCollectionView> spammersView = - userEvents - .apply( - "FixedWindowsUser", - Window.into( - FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) - - // Filter out everyone but those with (SCORE_WEIGHT * avg) clickrate. - // These might be robots/spammers. - .apply("CalculateSpammyUsers", new CalculateSpammyUsers()) - // Derive a view from the collection of spammer users. It will be used as a side input - // in calculating the team score sums, below. - .apply("CreateSpammersView", View.asMap()); - - // [START DocInclude_FilterAndCalc] - // Calculate the total score per team over fixed windows, - // and emit cumulative updates for late data. Uses the side input derived above-- the set of - // suspected robots-- to filter out scores from those users from the sum. - // Write the results to BigQuery. - rawEvents - .apply( - "WindowIntoFixedWindows", - Window.into( - FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration())))) - // Filter out the detected spammer users, using the side input derived above. - .apply( - "FilterOutSpammers", - ParDo.of( - new DoFn() { - @ProcessElement - public void processElement(ProcessContext c) { - // If the user is not in the spammers Map, output the data element. - if (c.sideInput(spammersView).get(c.element().getUser().trim()) == null) { - c.output(c.element()); - } - } - }) - .withSideInputs(spammersView)) - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")) - // [END DocInclude_FilterAndCalc] - // Write the result to BigQuery - .apply( - "WriteTeamSums", - new WriteWindowedToBigQuery<>( - options.as(GcpOptions.class).getProject(), - options.getDataset(), - options.getGameStatsTablePrefix() + "_team", - configureWindowedWrite())); - - // [START DocInclude_SessionCalc] - // Detect user sessions-- that is, a burst of activity separated by a gap from further - // activity. Find and record the mean session lengths. - // This information could help the game designers track the changing user engagement - // as their set of games changes. - userEvents - .apply( - "WindowIntoSessions", - Window.>into( - Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap()))) - .withTimestampCombiner(TimestampCombiner.END_OF_WINDOW)) - // For this use, we care only about the existence of the session, not any particular - // information aggregated over it, so the following is an efficient way to do that. - .apply(Combine.perKey(x -> 0)) - // Get the duration per session. - .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn())) - // [END DocInclude_SessionCalc] - // [START DocInclude_Rewindow] - // Re-window to process groups of session sums according to when the sessions complete. - .apply( - "WindowToExtractSessionMean", - Window.into( - FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration())))) - // Find the mean session duration in each window. - .apply(Mean.globally().withoutDefaults()) - // Write this info to a BigQuery table. - .apply( - "WriteAvgSessionLength", - new WriteWindowedToBigQuery<>( - options.as(GcpOptions.class).getProject(), - options.getDataset(), - options.getGameStatsTablePrefix() + "_sessions", - configureSessionWindowWrite())); - // [END DocInclude_Rewindow] - - - // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the - // command line. - PipelineResult result = pipeline.run(); - exampleUtils.waitToFinish(result); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java deleted file mode 100644 index 05455219fc..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/HourlyTeamScore.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; -import ${package}.complete.game.utils.GameConstants; -import ${package}.complete.game.utils.WriteToText; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.Filter; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.WithTimestamps; -import org.apache.beam.sdk.transforms.windowing.FixedWindows; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.Window; -import org.apache.beam.sdk.values.KV; -import org.joda.time.DateTimeZone; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -/** - * This class is the second in a series of four pipelines that tell a story in a 'gaming' - * domain, following {@link UserScore}. In addition to the concepts introduced in {@link UserScore}, - * new concepts include: windowing and element timestamps; use of {@code Filter.by()}. - * - *

              This pipeline processes data collected from gaming events in batch, building on {@link - * UserScore} but using fixed windows. It calculates the sum of scores per team, for each window, - * optionally allowing specification of two timestamps before and after which data is filtered out. - * This allows a model where late data collected after the intended analysis window can be included, - * and any late-arriving data prior to the beginning of the analysis window can be removed as well. - * By using windowing and adding element timestamps, we can do finer-grained analysis than with the - * {@link UserScore} pipeline. However, our batch processing is high-latency, in that we don't get - * results from plays at the beginning of the batch's time period until the batch is processed. - * - *

              To execute this pipeline, specify the pipeline configuration like this: - *

              {@code
              - *   --tempLocation=YOUR_TEMP_DIRECTORY
              - *   --runner=YOUR_RUNNER
              - *   --output=YOUR_OUTPUT_DIRECTORY
              - *   (possibly options specific to your runner or permissions for your temp/output locations)
              - * }
              - * 
              - * - *

              Optionally include {@code --input} to specify the batch input file path. - * To indicate a time after which the data should be filtered out, include the - * {@code --stopMin} arg. E.g., {@code --stopMin=2015-10-18-23-59} indicates that any data - * timestamped after 23:59 PST on 2015-10-18 should not be included in the analysis. - * To indicate a time before which data should be filtered out, include the {@code --startMin} arg. - * If you're using the default input specified in {@link UserScore}, - * "gs://apache-beam-samples/game/gaming_data*.csv", then - * {@code --startMin=2015-11-16-16-10 --stopMin=2015-11-17-16-10} are good values. - */ -public class HourlyTeamScore extends UserScore { - - private static DateTimeFormatter minFmt = - DateTimeFormat.forPattern("yyyy-MM-dd-HH-mm") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))); - - - /** - * Options supported by {@link HourlyTeamScore}. - */ - public interface Options extends UserScore.Options { - - @Description("Numeric value of fixed window duration, in minutes") - @Default.Integer(60) - Integer getWindowDuration(); - void setWindowDuration(Integer value); - - @Description("String representation of the first minute after which to generate results," - + "in the format: yyyy-MM-dd-HH-mm . This time should be in PST." - + "Any input data timestamped prior to that minute won't be included in the sums.") - @Default.String("1970-01-01-00-00") - String getStartMin(); - void setStartMin(String value); - - @Description("String representation of the first minute for which to not generate results," - + "in the format: yyyy-MM-dd-HH-mm . This time should be in PST." - + "Any input data timestamped after that minute won't be included in the sums.") - @Default.String("2100-01-01-00-00") - String getStopMin(); - void setStopMin(String value); - } - - /** - * Create a map of information that describes how to write pipeline output to text. This map - * is passed to the {@link WriteToText} constructor to write team score sums and - * includes information about window start time. - */ - protected static Map>> - configureOutput() { - Map>> config = new HashMap<>(); - config.put("team", (c, w) -> c.element().getKey()); - config.put("total_score", (c, w) -> c.element().getValue()); - config.put( - "window_start", - (c, w) -> { - IntervalWindow window = (IntervalWindow) w; - return GameConstants.DATE_TIME_FORMATTER.print(window.start()); - }); - return config; - } - - - /** - * Run a batch pipeline to do windowed analysis of the data. - */ - // [START DocInclude_HTSMain] - public static void main(String[] args) throws Exception { - // Begin constructing a pipeline configured by commandline flags. - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline pipeline = Pipeline.create(options); - - final Instant stopMinTimestamp = new Instant(minFmt.parseMillis(options.getStopMin())); - final Instant startMinTimestamp = new Instant(minFmt.parseMillis(options.getStartMin())); - - // Read 'gaming' events from a text file. - pipeline - .apply(TextIO.read().from(options.getInput())) - // Parse the incoming data. - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) - - // Filter out data before and after the given times so that it is not included - // in the calculations. As we collect data in batches (say, by day), the batch for the day - // that we want to analyze could potentially include some late-arriving data from the - // previous day. - // If so, we want to weed it out. Similarly, if we include data from the following day - // (to scoop up late-arriving events from the day we're analyzing), we need to weed out - // events that fall after the time period we want to analyze. - // [START DocInclude_HTSFilters] - .apply( - "FilterStartTime", - Filter.by( - (GameActionInfo gInfo) -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) - .apply( - "FilterEndTime", - Filter.by( - (GameActionInfo gInfo) -> gInfo.getTimestamp() < stopMinTimestamp.getMillis())) - // [END DocInclude_HTSFilters] - - // [START DocInclude_HTSAddTsAndWindow] - // Add an element timestamp based on the event log, and apply fixed windowing. - .apply( - "AddEventTimestamps", - WithTimestamps.of((GameActionInfo i) -> new Instant(i.getTimestamp()))) - .apply( - "FixedWindowsTeam", - Window.into(FixedWindows.of(Duration.standardMinutes(options.getWindowDuration())))) - // [END DocInclude_HTSAddTsAndWindow] - - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")) - .apply( - "WriteTeamScoreSums", new WriteToText<>(options.getOutput(), configureOutput(), true)); - - pipeline.run().waitUntilFinish(); - } - // [END DocInclude_HTSMain] - -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java deleted file mode 100644 index b5983fa789..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/LeaderBoard.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import com.google.common.annotations.VisibleForTesting; -import java.util.HashMap; -import java.util.Map; -import ${package}.common.ExampleOptions; -import ${package}.common.ExampleUtils; -import ${package}.complete.game.utils.GameConstants; -import ${package}.complete.game.utils.WriteToBigQuery; -import ${package}.complete.game.utils.WriteWindowedToBigQuery; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.options.StreamingOptions; -import org.apache.beam.sdk.options.Validation; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.AfterProcessingTime; -import org.apache.beam.sdk.transforms.windowing.AfterWatermark; -import org.apache.beam.sdk.transforms.windowing.FixedWindows; -import org.apache.beam.sdk.transforms.windowing.GlobalWindows; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.Repeatedly; -import org.apache.beam.sdk.transforms.windowing.Window; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.joda.time.Duration; -import org.joda.time.Instant; - -/** - * This class is the third in a series of four pipelines that tell a story in a 'gaming' domain, - * following {@link UserScore} and {@link HourlyTeamScore}. Concepts include: processing unbounded - * data using fixed windows; use of custom timestamps and event-time processing; generation of - * early/speculative results; using .accumulatingFiredPanes() to do cumulative processing of late- - * arriving data. - * - *

              This pipeline processes an unbounded stream of 'game events'. The calculation of the team - * scores uses fixed windowing based on event time (the time of the game play event), not - * processing time (the time that an event is processed by the pipeline). The pipeline calculates - * the sum of scores per team, for each window. By default, the team scores are calculated using - * one-hour windows. - * - *

              In contrast-- to demo another windowing option-- the user scores are calculated using a - * global window, which periodically (every ten minutes) emits cumulative user score sums. - * - *

              In contrast to the previous pipelines in the series, which used static, finite input data, - * here we're using an unbounded data source, which lets us provide speculative results, and allows - * handling of late data, at much lower latency. We can use the early/speculative results to keep a - * 'leaderboard' updated in near-realtime. Our handling of late data lets us generate correct - * results, e.g. for 'team prizes'. We're now outputting window results as they're - * calculated, giving us much lower latency than with the previous batch examples. - * - *

              Run {@code injector.Injector} to generate pubsub data for this pipeline. The Injector - * documentation provides more detail on how to do this. - * - *

              To execute this pipeline, specify the pipeline configuration like this: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              - *   --runner=YOUR_RUNNER
              - *   --dataset=YOUR-DATASET
              - *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              - * }
              - * 
              - * - *

              The BigQuery dataset you specify must already exist. The PubSub topic you specify should be - * the same topic to which the Injector is publishing. - */ -public class LeaderBoard extends HourlyTeamScore { - - static final Duration FIVE_MINUTES = Duration.standardMinutes(5); - static final Duration TEN_MINUTES = Duration.standardMinutes(10); - - - /** - * Options supported by {@link LeaderBoard}. - */ - public interface Options extends HourlyTeamScore.Options, ExampleOptions, StreamingOptions { - - @Description("BigQuery Dataset to write tables to. Must already exist.") - @Validation.Required - String getDataset(); - void setDataset(String value); - - @Description("Pub/Sub topic to read from") - @Validation.Required - String getTopic(); - void setTopic(String value); - - @Description("Numeric value of fixed window duration for team analysis, in minutes") - @Default.Integer(60) - Integer getTeamWindowDuration(); - void setTeamWindowDuration(Integer value); - - @Description("Numeric value of allowed data lateness, in minutes") - @Default.Integer(120) - Integer getAllowedLateness(); - void setAllowedLateness(Integer value); - - @Description("Prefix used for the BigQuery table names") - @Default.String("leaderboard") - String getLeaderBoardTableName(); - void setLeaderBoardTableName(String value); - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write team score sums and includes event timing information. - */ - protected static Map>> - configureWindowedTableWrite() { - - Map>> tableConfigure = - new HashMap<>(); - tableConfigure.put( - "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); - tableConfigure.put( - "total_score", - new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); - tableConfigure.put( - "window_start", - new WriteWindowedToBigQuery.FieldInfo<>( - "STRING", - (c, w) -> { - IntervalWindow window = (IntervalWindow) w; - return GameConstants.DATE_TIME_FORMATTER.print(window.start()); - })); - tableConfigure.put( - "processing_time", - new WriteWindowedToBigQuery.FieldInfo<>( - "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); - tableConfigure.put( - "timing", - new WriteWindowedToBigQuery.FieldInfo<>( - "STRING", (c, w) -> c.pane().getTiming().toString())); - return tableConfigure; - } - - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is passed to the {@link WriteToBigQuery} constructor to write user score sums. - */ - protected static Map>> - configureBigQueryWrite() { - Map>> tableConfigure = new HashMap<>(); - tableConfigure.put( - "user", new WriteToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); - tableConfigure.put( - "total_score", - new WriteToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); - return tableConfigure; - } - - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write user score sums. - */ - protected static Map>> - configureGlobalWindowBigQueryWrite() { - - Map>> tableConfigure = - configureBigQueryWrite(); - tableConfigure.put( - "processing_time", - new WriteToBigQuery.FieldInfo<>( - "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); - return tableConfigure; - } - - - public static void main(String[] args) throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - // Enforce that this pipeline is always run in streaming mode. - options.setStreaming(true); - ExampleUtils exampleUtils = new ExampleUtils(options); - Pipeline pipeline = Pipeline.create(options); - - // Read game events from Pub/Sub using custom timestamps, which are extracted from the pubsub - // data elements, and parse the data. - PCollection gameEvents = pipeline - .apply(PubsubIO.readStrings() - .withTimestampAttribute(GameConstants.TIMESTAMP_ATTRIBUTE) - .fromTopic(options.getTopic())) - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())); - - gameEvents - .apply( - "CalculateTeamScores", - new CalculateTeamScores( - Duration.standardMinutes(options.getTeamWindowDuration()), - Duration.standardMinutes(options.getAllowedLateness()))) - // Write the results to BigQuery. - .apply( - "WriteTeamScoreSums", - new WriteWindowedToBigQuery<>( - options.as(GcpOptions.class).getProject(), - options.getDataset(), - options.getLeaderBoardTableName() + "_team", - configureWindowedTableWrite())); - gameEvents - .apply( - "CalculateUserScores", - new CalculateUserScores(Duration.standardMinutes(options.getAllowedLateness()))) - // Write the results to BigQuery. - .apply( - "WriteUserScoreSums", - new WriteToBigQuery<>( - options.as(GcpOptions.class).getProject(), - options.getDataset(), - options.getLeaderBoardTableName() + "_user", - configureGlobalWindowBigQueryWrite())); - - // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the - // command line. - PipelineResult result = pipeline.run(); - exampleUtils.waitToFinish(result); - } - - /** - * Calculates scores for each team within the configured window duration. - */ - // [START DocInclude_WindowAndTrigger] - // Extract team/score pairs from the event stream, using hour-long windows by default. - @VisibleForTesting - static class CalculateTeamScores - extends PTransform, PCollection>> { - private final Duration teamWindowDuration; - private final Duration allowedLateness; - - CalculateTeamScores(Duration teamWindowDuration, Duration allowedLateness) { - this.teamWindowDuration = teamWindowDuration; - this.allowedLateness = allowedLateness; - } - - @Override - public PCollection> expand(PCollection infos) { - return infos.apply("LeaderboardTeamFixedWindows", - Window.into(FixedWindows.of(teamWindowDuration)) - // We will get early (speculative) results as well as cumulative - // processing of late data. - .triggering(AfterWatermark.pastEndOfWindow() - .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(FIVE_MINUTES)) - .withLateFirings(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(TEN_MINUTES))) - .withAllowedLateness(allowedLateness) - .accumulatingFiredPanes()) - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")); - } - } - // [END DocInclude_WindowAndTrigger] - - // [START DocInclude_ProcTimeTrigger] - /** - * Extract user/score pairs from the event stream using processing time, via global windowing. - * Get periodic updates on all users' running scores. - */ - @VisibleForTesting - static class CalculateUserScores - extends PTransform, PCollection>> { - private final Duration allowedLateness; - - CalculateUserScores(Duration allowedLateness) { - this.allowedLateness = allowedLateness; - } - - @Override - public PCollection> expand(PCollection input) { - return input.apply("LeaderboardUserGlobalWindow", - Window.into(new GlobalWindows()) - // Get periodic results every ten minutes. - .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane() - .plusDelayOf(TEN_MINUTES))) - .accumulatingFiredPanes() - .withAllowedLateness(allowedLateness)) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")); - } - } - // [END DocInclude_ProcTimeTrigger] -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java deleted file mode 100644 index c0a7bc8e17..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/StatefulTeamScore.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import static com.google.common.base.MoreObjects.firstNonNull; - -import com.google.common.annotations.VisibleForTesting; -import java.util.HashMap; -import java.util.Map; -import ${package}.common.ExampleUtils; -import ${package}.complete.game.utils.GameConstants; -import ${package}.complete.game.utils.WriteToBigQuery.FieldInfo; -import ${package}.complete.game.utils.WriteWindowedToBigQuery; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.PipelineResult; -import org.apache.beam.sdk.coders.VarIntCoder; -import org.apache.beam.sdk.extensions.gcp.options.GcpOptions; -import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.state.StateSpec; -import org.apache.beam.sdk.state.StateSpecs; -import org.apache.beam.sdk.state.ValueState; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.TypeDescriptor; -import org.apache.beam.sdk.values.TypeDescriptors; -import org.joda.time.Instant; - -/** - * This class is part of a series of pipelines that tell a story in a gaming domain. Concepts - * include: stateful processing. - * - *

              This pipeline processes an unbounded stream of 'game events'. It uses stateful processing to - * aggregate team scores per team and outputs team name and it's total score every time the team - * passes a new multiple of a threshold score. For example, multiples of the threshold could be the - * corresponding scores required to pass each level of the game. By default, this threshold is set - * to 5000. - * - *

              Stateful processing allows us to write pipelines that output based on a runtime state (when - * a team reaches a certain score, in every 100 game events etc) without time triggers. See - * https://beam.apache.org/blog/2017/02/13/stateful-processing.html for more information on using - * stateful processing. - * - *

              Run {@code injector.Injector} to generate pubsub data for this pipeline. The Injector - * documentation provides more detail on how to do this. - * - *

              To execute this pipeline, specify the pipeline configuration like this: - *

              {@code
              - *   --project=YOUR_PROJECT_ID
              - *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
              - *   --runner=YOUR_RUNNER
              - *   --dataset=YOUR-DATASET
              - *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
              - * }
              - * 
              - * - *

              The BigQuery dataset you specify must already exist. The PubSub topic you specify should be - * the same topic to which the Injector is publishing. - */ -public class StatefulTeamScore extends LeaderBoard { - - /** - * Options supported by {@link StatefulTeamScore}. - */ - interface Options extends LeaderBoard.Options { - - @Description("Numeric value, multiple of which is used as threshold for outputting team score.") - @Default.Integer(5000) - Integer getThresholdScore(); - - void setThresholdScore(Integer value); - } - - /** - * Create a map of information that describes how to write pipeline output to BigQuery. This map - * is used to write team score sums. - */ - private static Map>> configureCompleteWindowedTableWrite() { - - Map>> tableConfigure = - new HashMap<>(); - tableConfigure.put( - "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); - tableConfigure.put( - "total_score", - new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); - tableConfigure.put( - "processing_time", - new WriteWindowedToBigQuery.FieldInfo<>( - "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); - return tableConfigure; - } - - - public static void main(String[] args) throws Exception { - - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - // Enforce that this pipeline is always run in streaming mode. - options.setStreaming(true); - ExampleUtils exampleUtils = new ExampleUtils(options); - Pipeline pipeline = Pipeline.create(options); - - pipeline - // Read game events from Pub/Sub using custom timestamps, which are extracted from the - // pubsub data elements, and parse the data. - .apply( - PubsubIO.readStrings() - .withTimestampAttribute(GameConstants.TIMESTAMP_ATTRIBUTE) - .fromTopic(options.getTopic())) - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) - // Create mapping. UpdateTeamScore uses team name as key. - .apply( - "MapTeamAsKey", - MapElements.into( - TypeDescriptors.kvs( - TypeDescriptors.strings(), TypeDescriptor.of(GameActionInfo.class))) - .via((GameActionInfo gInfo) -> KV.of(gInfo.team, gInfo))) - // Outputs a team's score every time it passes a new multiple of the threshold. - .apply("UpdateTeamScore", ParDo.of(new UpdateTeamScoreFn(options.getThresholdScore()))) - // Write the results to BigQuery. - .apply( - "WriteTeamLeaders", - new WriteWindowedToBigQuery<>( - options.as(GcpOptions.class).getProject(), - options.getDataset(), - options.getLeaderBoardTableName() + "_team_leader", - configureCompleteWindowedTableWrite())); - - // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the - // command line. - PipelineResult result = pipeline.run(); - exampleUtils.waitToFinish(result); - } - - /** - * Tracks each team's score separately in a single state cell and outputs the score every time it - * passes a new multiple of a threshold. - * - *

              We use stateful {@link DoFn} because: - *

                - *
              • State is key-partitioned. Therefore, the score is calculated per team.
              • - *
              • Stateful {@link DoFn} can determine when to output based on the state. This only allows - * outputting when a team's score passes a given threshold.
              • - *
              - */ - @VisibleForTesting - public static class UpdateTeamScoreFn - extends DoFn, KV> { - - private static final String TOTAL_SCORE = "totalScore"; - private final int thresholdScore; - - public UpdateTeamScoreFn(int thresholdScore) { - this.thresholdScore = thresholdScore; - } - - /** - * Describes the state for storing team score. Let's break down this statement. - * - * {@link StateSpec} configures the state cell, which is provided by a runner during pipeline - * execution. - * - * {@link org.apache.beam.sdk.transforms.DoFn.StateId} annotation assigns an identifier to the - * state, which is used to refer the state in - * {@link org.apache.beam.sdk.transforms.DoFn.ProcessElement}. - * - *

              A {@link ValueState} stores single value per key and per window. Because our pipeline is - * globally windowed in this example, this {@link ValueState} is just key partitioned, with one - * score per team. Any other class that extends {@link org.apache.beam.sdk.state.State} can be - * used.

              - * - *

              In order to store the value, the state must be encoded. Therefore, we provide a coder, in - * this case the {@link VarIntCoder}. If the coder is not provided as in - * {@code StateSpecs.value()}, Beam's coder inference will try to provide a coder automatically. - *

              - */ - @StateId(TOTAL_SCORE) - private final StateSpec> totalScoreSpec = - StateSpecs.value(VarIntCoder.of()); - - /** - * To use a state cell, annotate a parameter with - * {@link org.apache.beam.sdk.transforms.DoFn.StateId} that matches the state declaration. The - * type of the parameter should match the {@link StateSpec} type. - */ - @ProcessElement - public void processElement( - ProcessContext c, - @StateId(TOTAL_SCORE) ValueState totalScore) { - String teamName = c.element().getKey(); - GameActionInfo gInfo = c.element().getValue(); - - // ValueState cells do not contain a default value. If the state is possibly not written, make - // sure to check for null on read. - int oldTotalScore = firstNonNull(totalScore.read(), 0); - totalScore.write(oldTotalScore + gInfo.score); - - // Since there are no negative scores, the easiest way to check whether a team just passed a - // new multiple of the threshold score is to compare the quotients of dividing total scores by - // threshold before and after this aggregation. For example, if the total score was 1999, - // the new total is 2002, and the threshold is 1000, 1999 / 1000 = 1, 2002 / 1000 = 2. - // Therefore, this team passed the threshold. - if (oldTotalScore / this.thresholdScore < totalScore.read() / this.thresholdScore) { - c.output(KV.of(teamName, totalScore.read())); - } - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java deleted file mode 100644 index 3459d043f5..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/UserScore.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import java.util.HashMap; -import java.util.Map; -import org.apache.avro.reflect.Nullable; -import ${package}.complete.game.utils.WriteToText; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.coders.AvroCoder; -import org.apache.beam.sdk.coders.DefaultCoder; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.metrics.Counter; -import org.apache.beam.sdk.metrics.Metrics; -import org.apache.beam.sdk.options.Default; -import org.apache.beam.sdk.options.Description; -import org.apache.beam.sdk.options.PipelineOptions; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.options.Validation; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.Sum; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.TypeDescriptors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is the first in a series of four pipelines that tell a story in a 'gaming' domain. - * Concepts: batch processing, reading input from text files, writing output to - * text files, using standalone DoFns, use of the sum per key transform, and use of - * Java 8 lambda syntax. - * - *

              In this gaming scenario, many users play, as members of different teams, over the course of a - * day, and their actions are logged for processing. Some of the logged game events may be late- - * arriving, if users play on mobile devices and go transiently offline for a period. - * - *

              This pipeline does batch processing of data collected from gaming events. It calculates the - * sum of scores per user, over an entire batch of gaming data (collected, say, for each day). The - * batch processing will not include any late data that arrives after the day's cutoff point. - * - *

              To execute this pipeline, specify the pipeline configuration like this: - *

              {@code
              - *   --tempLocation=YOUR_TEMP_DIRECTORY
              - *   --runner=YOUR_RUNNER
              - *   --output=YOUR_OUTPUT_DIRECTORY
              - *   (possibly options specific to your runner or permissions for your temp/output locations)
              - * }
              - * 
              - * - *

              Optionally include the --input argument to specify a batch input file. - * See the --input default value for example batch data file, or use {@code injector.Injector} to - * generate your own batch data. - */ -public class UserScore { - - /** - * Class to hold info about a game event. - */ - @DefaultCoder(AvroCoder.class) - static class GameActionInfo { - @Nullable String user; - @Nullable String team; - @Nullable Integer score; - @Nullable Long timestamp; - - public GameActionInfo() {} - - public GameActionInfo(String user, String team, Integer score, Long timestamp) { - this.user = user; - this.team = team; - this.score = score; - this.timestamp = timestamp; - } - - public String getUser() { - return this.user; - } - public String getTeam() { - return this.team; - } - public Integer getScore() { - return this.score; - } - public String getKey(String keyname) { - if ("team".equals(keyname)) { - return this.team; - } else { // return username as default - return this.user; - } - } - public Long getTimestamp() { - return this.timestamp; - } - } - - - /** - * Parses the raw game event info into GameActionInfo objects. Each event line has the following - * format: username,teamname,score,timestamp_in_ms,readable_time - * e.g.: - * user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 - * The human-readable time string is not used here. - */ - static class ParseEventFn extends DoFn { - - // Log and count parse errors. - private static final Logger LOG = LoggerFactory.getLogger(ParseEventFn.class); - private final Counter numParseErrors = Metrics.counter("main", "ParseErrors"); - - @ProcessElement - public void processElement(ProcessContext c) { - System.out.println("GOT " + c.element()); - String[] components = c.element().split(",", -1); - try { - String user = components[0].trim(); - String team = components[1].trim(); - Integer score = Integer.parseInt(components[2].trim()); - Long timestamp = Long.parseLong(components[3].trim()); - GameActionInfo gInfo = new GameActionInfo(user, team, score, timestamp); - c.output(gInfo); - } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) { - numParseErrors.inc(); - LOG.info("Parse error on " + c.element() + ", " + e.getMessage()); - } - } - } - - /** - * A transform to extract key/score information from GameActionInfo, and sum the scores. The - * constructor arg determines whether 'team' or 'user' info is extracted. - */ - // [START DocInclude_USExtractXform] - public static class ExtractAndSumScore - extends PTransform, PCollection>> { - - private final String field; - - ExtractAndSumScore(String field) { - this.field = field; - } - - @Override - public PCollection> expand( - PCollection gameInfo) { - - return gameInfo - .apply( - MapElements.into( - TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) - .via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore()))) - .apply(Sum.integersPerKey()); - } - } - // [END DocInclude_USExtractXform] - - - /** - * Options supported by {@link UserScore}. - */ - public interface Options extends PipelineOptions { - - @Description("Path to the data file(s) containing game data.") - // The default maps to two large Google Cloud Storage files (each ~12GB) holding two subsequent - // day's worth (roughly) of data. - @Default.String("gs://apache-beam-samples/game/gaming_data*.csv") - String getInput(); - void setInput(String value); - - // Set this required option to specify where to write the output. - @Description("Path of the file to write to.") - @Validation.Required - String getOutput(); - void setOutput(String value); - } - - /** - * Create a map of information that describes how to write pipeline output to text. This map - * is passed to the {@link WriteToText} constructor to write user score sums. - */ - protected static Map>> - configureOutput() { - Map>> config = new HashMap<>(); - config.put("user", (c, w) -> c.element().getKey()); - config.put("total_score", (c, w) -> c.element().getValue()); - return config; - } - - /** - * Run a batch pipeline. - */ - // [START DocInclude_USMain] - public static void main(String[] args) throws Exception { - // Begin constructing a pipeline configured by commandline flags. - Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); - Pipeline pipeline = Pipeline.create(options); - - // Read events from a text file and parse them. - pipeline - .apply(TextIO.read().from(options.getInput())) - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")) - .apply( - "WriteUserScoreSums", new WriteToText<>(options.getOutput(), configureOutput(), false)); - - // Run the batch pipeline. - pipeline.run().waitUntilFinish(); - } - // [END DocInclude_USMain] -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java deleted file mode 100644 index c21ec2e319..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/Injector.java +++ /dev/null @@ -1,439 +0,0 @@ -/* - * 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 ${package}.complete.game.injector; - -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.model.PublishRequest; -import com.google.api.services.pubsub.model.PubsubMessage; -import com.google.common.collect.ImmutableMap; -import java.io.BufferedOutputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import ${package}.complete.game.utils.GameConstants; - -/** - * This is a generator that simulates usage data from a mobile game, and either publishes the data - * to a pubsub topic or writes it to a file. - * - *

              The general model used by the generator is the following. There is a set of teams with team - * members. Each member is scoring points for their team. After some period, a team will dissolve - * and a new one will be created in its place. There is also a set of 'Robots', or spammer users. - * They hop from team to team. The robots are set to have a higher 'click rate' (generate more - * events) than the regular team members. - * - *

              Each generated line of data has the following form: - * username,teamname,score,timestamp_in_ms,readable_time - * e.g.: - * user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 - * - *

              The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if - * specified. It takes the following arguments: - * {@code Injector project-name (topic-name|none) (filename|none)}. - * - *

              To run the Injector in the mode where it publishes to PubSub, you will need to authenticate - * locally using project-based service account credentials to avoid running over PubSub - * quota. - * See https://developers.google.com/identity/protocols/application-default-credentials - * for more information on using service account credentials. Set the GOOGLE_APPLICATION_CREDENTIALS - * environment variable to point to your downloaded service account credentials before starting the - * program, e.g.: - * {@code export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials-key.json}. - * If you do not do this, then your injector will only run for a few minutes on your - * 'user account' credentials before you will start to see quota error messages like: - * "Request throttled due to user QPS limit being reached", and see this exception: - * ".com.google.api.client.googleapis.json.GoogleJsonResponseException: 429 Too Many Requests". - * Once you've set up your credentials, run the Injector like this": - *

              {@code
              - * Injector   none
              - * }
              - * 
              - * The pubsub topic will be created if it does not exist. - * - *

              To run the injector in write-to-file-mode, set the topic name to "none" and specify the - * filename: - *

              {@code
              - * Injector  none 
              - * }
              - * 
              - */ -class Injector { - private static Pubsub pubsub; - private static Random random = new Random(); - private static String topic; - private static String project; - - // QPS ranges from 800 to 1000. - private static final int MIN_QPS = 800; - private static final int QPS_RANGE = 200; - // How long to sleep, in ms, between creation of the threads that make API requests to PubSub. - private static final int THREAD_SLEEP_MS = 500; - - // Lists used to generate random team names. - // If COLORS is changed, please also make changes in - // release/src/main/groovy/MobileGamingCommands.COLORS - private static final ArrayList COLORS = - new ArrayList<>( - Arrays.asList( - "Magenta", - "AliceBlue", - "Almond", - "Amaranth", - "Amber", - "Amethyst", - "AndroidGreen", - "AntiqueBrass", - "Fuchsia", - "Ruby", - "AppleGreen", - "Apricot", - "Aqua", - "ArmyGreen", - "Asparagus", - "Auburn", - "Azure", - "Banana", - "Beige", - "Bisque", - "BarnRed", - "BattleshipGrey")); - - private static final ArrayList ANIMALS = - new ArrayList<>( - Arrays.asList( - "Echidna", - "Koala", - "Wombat", - "Marmot", - "Quokka", - "Kangaroo", - "Dingo", - "Numbat", - "Emu", - "Wallaby", - "CaneToad", - "Bilby", - "Possum", - "Cassowary", - "Kookaburra", - "Platypus", - "Bandicoot", - "Cockatoo", - "Antechinus")); - - // The list of live teams. - private static ArrayList liveTeams = new ArrayList<>(); - - // The total number of robots in the system. - private static final int NUM_ROBOTS = 20; - // Determines the chance that a team will have a robot team member. - private static final int ROBOT_PROBABILITY = 3; - private static final int NUM_LIVE_TEAMS = 15; - private static final int BASE_MEMBERS_PER_TEAM = 5; - private static final int MEMBERS_PER_TEAM = 15; - private static final int MAX_SCORE = 20; - private static final int LATE_DATA_RATE = 5 * 60 * 2; // Every 10 minutes - private static final int BASE_DELAY_IN_MILLIS = 5 * 60 * 1000; // 5-10 minute delay - private static final int FUZZY_DELAY_IN_MILLIS = 5 * 60 * 1000; - - // The minimum time a 'team' can live. - private static final int BASE_TEAM_EXPIRATION_TIME_IN_MINS = 20; - private static final int TEAM_EXPIRATION_TIME_IN_MINS = 20; - - - /** - * A class for holding team info: the name of the team, when it started, - * and the current team members. Teams may but need not include one robot team member. - */ - private static class TeamInfo { - String teamName; - long startTimeInMillis; - int expirationPeriod; - // The team might but need not include 1 robot. Will be non-null if so. - String robot; - int numMembers; - - private TeamInfo(String teamName, long startTimeInMillis, String robot) { - this.teamName = teamName; - this.startTimeInMillis = startTimeInMillis; - // How long until this team is dissolved. - this.expirationPeriod = random.nextInt(TEAM_EXPIRATION_TIME_IN_MINS) - + BASE_TEAM_EXPIRATION_TIME_IN_MINS; - this.robot = robot; - // Determine the number of team members. - numMembers = random.nextInt(MEMBERS_PER_TEAM) + BASE_MEMBERS_PER_TEAM; - } - - String getTeamName() { - return teamName; - } - String getRobot() { - return robot; - } - - long getStartTimeInMillis() { - return startTimeInMillis; - } - long getEndTimeInMillis() { - return startTimeInMillis + (expirationPeriod * 60L * 1000L); - } - String getRandomUser() { - int userNum = random.nextInt(numMembers); - return "user" + userNum + "_" + teamName; - } - - int numMembers() { - return numMembers; - } - - @Override - public String toString() { - return "(" + teamName + ", num members: " + numMembers() + ", starting at: " - + startTimeInMillis + ", expires in: " + expirationPeriod + ", robot: " + robot + ")"; - } - } - - /** Utility to grab a random element from an array of Strings. */ - private static String randomElement(ArrayList list) { - int index = random.nextInt(list.size()); - return list.get(index); - } - - /** - * Get and return a random team. If the selected team is too old w.r.t its expiration, remove - * it, replacing it with a new team. - */ - private static TeamInfo randomTeam(ArrayList list) { - int index = random.nextInt(list.size()); - TeamInfo team = list.get(index); - // If the selected team is expired, remove it and return a new team. - long currTime = System.currentTimeMillis(); - if ((team.getEndTimeInMillis() < currTime) || team.numMembers() == 0) { - System.out.println("\nteam " + team + " is too old; replacing."); - System.out.println("start time: " + team.getStartTimeInMillis() - + ", end time: " + team.getEndTimeInMillis() - + ", current time:" + currTime); - removeTeam(index); - // Add a new team in its stead. - return (addLiveTeam()); - } else { - return team; - } - } - - /** - * Create and add a team. Possibly add a robot to the team. - */ - private static synchronized TeamInfo addLiveTeam() { - String teamName = randomElement(COLORS) + randomElement(ANIMALS); - String robot = null; - // Decide if we want to add a robot to the team. - if (random.nextInt(ROBOT_PROBABILITY) == 0) { - robot = "Robot-" + random.nextInt(NUM_ROBOTS); - } - // Create the new team. - TeamInfo newTeam = new TeamInfo(teamName, System.currentTimeMillis(), robot); - liveTeams.add(newTeam); - System.out.println("[+" + newTeam + "]"); - return newTeam; - } - - /** - * Remove a specific team. - */ - private static synchronized void removeTeam(int teamIndex) { - TeamInfo removedTeam = liveTeams.remove(teamIndex); - System.out.println("[-" + removedTeam + "]"); - } - - /** Generate a user gaming event. */ - private static String generateEvent(Long currTime, int delayInMillis) { - TeamInfo team = randomTeam(liveTeams); - String teamName = team.getTeamName(); - String user; - final int parseErrorRate = 900000; - - String robot = team.getRobot(); - // If the team has an associated robot team member... - if (robot != null) { - // Then use that robot for the message with some probability. - // Set this probability to higher than that used to select any of the 'regular' team - // members, so that if there is a robot on the team, it has a higher click rate. - if (random.nextInt(team.numMembers() / 2) == 0) { - user = robot; - } else { - user = team.getRandomUser(); - } - } else { // No robot. - user = team.getRandomUser(); - } - String event = user + "," + teamName + "," + random.nextInt(MAX_SCORE); - // Randomly introduce occasional parse errors. - if (random.nextInt(parseErrorRate) == 0) { - System.out.println("Introducing a parse error."); - event = "THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR"; - } - return addTimeInfoToEvent(event, currTime, delayInMillis); - } - - /** - * Add time info to a generated gaming event. - */ - private static String addTimeInfoToEvent(String message, Long currTime, int delayInMillis) { - String eventTimeString = - Long.toString((currTime - delayInMillis) / 1000 * 1000); - // Add a (redundant) 'human-readable' date string to make the data semantics more clear. - String dateString = GameConstants.DATE_TIME_FORMATTER.print(currTime); - message = message + "," + eventTimeString + "," + dateString; - return message; - } - - /** - * Publish 'numMessages' arbitrary events from live users with the provided delay, to a - * PubSub topic. - */ - public static void publishData(int numMessages, int delayInMillis) - throws IOException { - List pubsubMessages = new ArrayList<>(); - - for (int i = 0; i < Math.max(1, numMessages); i++) { - Long currTime = System.currentTimeMillis(); - String message = generateEvent(currTime, delayInMillis); - PubsubMessage pubsubMessage = new PubsubMessage() - .encodeData(message.getBytes("UTF-8")); - pubsubMessage.setAttributes( - ImmutableMap.of(GameConstants.TIMESTAMP_ATTRIBUTE, - Long.toString((currTime - delayInMillis) / 1000 * 1000))); - if (delayInMillis != 0) { - System.out.println(pubsubMessage.getAttributes()); - System.out.println("late data for: " + message); - } - pubsubMessages.add(pubsubMessage); - } - - PublishRequest publishRequest = new PublishRequest(); - publishRequest.setMessages(pubsubMessages); - pubsub.projects().topics().publish(topic, publishRequest).execute(); - } - - /** - * Publish generated events to a file. - */ - public static void publishDataToFile(String fileName, int numMessages, int delayInMillis) - throws IOException { - PrintWriter out = new PrintWriter(new OutputStreamWriter( - new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8")); - - try { - for (int i = 0; i < Math.max(1, numMessages); i++) { - Long currTime = System.currentTimeMillis(); - String message = generateEvent(currTime, delayInMillis); - out.println(message); - } - } catch (Exception e) { - System.err.print("Error in writing generated events to file"); - e.printStackTrace(); - } finally { - out.flush(); - out.close(); - } - } - - - public static void main(String[] args) throws IOException, InterruptedException { - if (args.length < 3) { - System.out.println("Usage: Injector project-name (topic-name|none) (filename|none)"); - System.exit(1); - } - boolean writeToFile = false; - boolean writeToPubsub = true; - project = args[0]; - String topicName = args[1]; - String fileName = args[2]; - // The Injector writes either to a PubSub topic, or a file. It will use the PubSub topic if - // specified; otherwise, it will try to write to a file. - if ("none".equalsIgnoreCase(topicName)) { - writeToFile = true; - writeToPubsub = false; - } - if (writeToPubsub) { - // Create the PubSub client. - pubsub = InjectorUtils.getClient(); - // Create the PubSub topic as necessary. - topic = InjectorUtils.getFullyQualifiedTopicName(project, topicName); - InjectorUtils.createTopic(pubsub, topic); - System.out.println("Injecting to topic: " + topic); - } else { - if ("none".equalsIgnoreCase(fileName)) { - System.out.println("Filename not specified."); - System.exit(1); - } - System.out.println("Writing to file: " + fileName); - } - System.out.println("Starting Injector"); - - // Start off with some random live teams. - while (liveTeams.size() < NUM_LIVE_TEAMS) { - addLiveTeam(); - } - - // Publish messages at a rate determined by the QPS and Thread sleep settings. - for (int i = 0; true; i++) { - if (Thread.activeCount() > 10) { - System.err.println("I'm falling behind!"); - } - - // Decide if this should be a batch of late data. - final int numMessages; - final int delayInMillis; - if (i % LATE_DATA_RATE == 0) { - // Insert delayed data for one user (one message only) - delayInMillis = BASE_DELAY_IN_MILLIS + random.nextInt(FUZZY_DELAY_IN_MILLIS); - numMessages = 1; - System.out.println("DELAY(" + delayInMillis + ", " + numMessages + ")"); - } else { - System.out.print("."); - delayInMillis = 0; - numMessages = MIN_QPS + random.nextInt(QPS_RANGE); - } - - if (writeToFile) { // Won't use threading for the file write. - publishDataToFile(fileName, numMessages, delayInMillis); - } else { // Write to PubSub. - // Start a thread to inject some data. - new Thread( - () -> { - try { - publishData(numMessages, delayInMillis); - } catch (IOException e) { - System.err.println(e); - } - }) - .start(); - } - - // Wait before creating another injector thread. - Thread.sleep(THREAD_SLEEP_MS); - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java deleted file mode 100644 index 5a0cf0166e..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/InjectorUtils.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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 ${package}.complete.game.injector; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpStatusCodes; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.services.pubsub.Pubsub; -import com.google.api.services.pubsub.PubsubScopes; -import com.google.api.services.pubsub.model.Topic; -import java.io.IOException; - -class InjectorUtils { - - private static final String APP_NAME = "injector"; - - /** - * Builds a new Pubsub client and returns it. - */ - public static Pubsub getClient(final HttpTransport httpTransport, - final JsonFactory jsonFactory) - throws IOException { - checkNotNull(httpTransport); - checkNotNull(jsonFactory); - GoogleCredential credential = - GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); - if (credential.createScopedRequired()) { - credential = credential.createScoped(PubsubScopes.all()); - } - if (credential.getClientAuthentication() != null) { - System.out.println("\n***Warning! You are not using service account credentials to " - + "authenticate.\nYou need to use service account credentials for this example," - + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " - + "out of PubSub quota very quickly.\nSee " - + "https://developers.google.com/identity/protocols/application-default-credentials."); - System.exit(1); - } - HttpRequestInitializer initializer = - new RetryHttpInitializerWrapper(credential); - return new Pubsub.Builder(httpTransport, jsonFactory, initializer) - .setApplicationName(APP_NAME) - .build(); - } - - /** - * Builds a new Pubsub client with default HttpTransport and - * JsonFactory and returns it. - */ - public static Pubsub getClient() throws IOException { - return getClient(Utils.getDefaultTransport(), - Utils.getDefaultJsonFactory()); - } - - - /** - * Returns the fully qualified topic name for Pub/Sub. - */ - public static String getFullyQualifiedTopicName( - final String project, final String topic) { - return String.format("projects/%s/topics/%s", project, topic); - } - - /** - * Create a topic if it doesn't exist. - */ - public static void createTopic(Pubsub client, String fullTopicName) - throws IOException { - System.out.println("fullTopicName " + fullTopicName); - try { - client.projects().topics().get(fullTopicName).execute(); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { - Topic topic = client.projects().topics() - .create(fullTopicName, new Topic()) - .execute(); - System.out.printf("Topic %s was created.%n", topic.getName()); - } - } - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java deleted file mode 100644 index e90fbcc18e..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/injector/RetryHttpInitializerWrapper.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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 ${package}.complete.game.injector; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.http.HttpBackOffIOExceptionHandler; -import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpUnsuccessfulResponseHandler; -import com.google.api.client.util.ExponentialBackOff; -import com.google.api.client.util.Sleeper; -import java.util.logging.Logger; - -/** - * RetryHttpInitializerWrapper will automatically retry upon RPC - * failures, preserving the auto-refresh behavior of the Google - * Credentials. - */ -public class RetryHttpInitializerWrapper implements HttpRequestInitializer { - - /** - * A private logger. - */ - private static final Logger LOG = - Logger.getLogger(RetryHttpInitializerWrapper.class.getName()); - - /** - * One minutes in miliseconds. - */ - private static final int ONEMINITUES = 60000; - - /** - * Intercepts the request for filling in the "Authorization" - * header field, as well as recovering from certain unsuccessful - * error codes wherein the Credential must refresh its token for a - * retry. - */ - private final Credential wrappedCredential; - - /** - * A sleeper; you can replace it with a mock in your test. - */ - private final Sleeper sleeper; - - /** - * A constructor. - * - * @param wrappedCredential Credential which will be wrapped and - * used for providing auth header. - */ - public RetryHttpInitializerWrapper(final Credential wrappedCredential) { - this(wrappedCredential, Sleeper.DEFAULT); - } - - /** - * A protected constructor only for testing. - * - * @param wrappedCredential Credential which will be wrapped and - * used for providing auth header. - * @param sleeper Sleeper for easy testing. - */ - RetryHttpInitializerWrapper( - final Credential wrappedCredential, final Sleeper sleeper) { - this.wrappedCredential = checkNotNull(wrappedCredential); - this.sleeper = sleeper; - } - - /** - * Initializes the given request. - */ - @Override - public final void initialize(final HttpRequest request) { - request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout - final HttpUnsuccessfulResponseHandler backoffHandler = - new HttpBackOffUnsuccessfulResponseHandler( - new ExponentialBackOff()) - .setSleeper(sleeper); - request.setInterceptor(wrappedCredential); - request.setUnsuccessfulResponseHandler( - (request1, response, supportsRetry) -> { - if (wrappedCredential.handleResponse(request1, response, supportsRetry)) { - // If credential decides it can handle it, the return code or message indicated - // something specific to authentication, and no backoff is desired. - return true; - } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) { - // Otherwise, we defer to the judgement of our internal backoff handler. - LOG.info("Retrying " + request1.getUrl().toString()); - return true; - } else { - return false; - } - }); - request.setIOExceptionHandler( - new HttpBackOffIOExceptionHandler(new ExponentialBackOff()) - .setSleeper(sleeper)); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java deleted file mode 100644 index dc28ad72ea..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/GameConstants.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 ${package}.complete.game.utils; - -import java.util.TimeZone; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -/** - * Shared constants between game series classes. - */ -public class GameConstants { - - public static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms"; - - public static final DateTimeFormatter DATE_TIME_FORMATTER = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))); -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java deleted file mode 100644 index d35a4ffcfc..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToBigQuery.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * 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 ${package}.complete.game.utils; - -import com.google.api.services.bigquery.model.TableFieldSchema; -import com.google.api.services.bigquery.model.TableReference; -import com.google.api.services.bigquery.model.TableRow; -import com.google.api.services.bigquery.model.TableSchema; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PDone; - -/** - * Generate, format, and write BigQuery table row information. Use provided information about - * the field names and types, as well as lambda functions that describe how to generate their - * values. - */ -public class WriteToBigQuery - extends PTransform, PDone> { - - protected String projectId; - protected String datasetId; - protected String tableName; - protected Map> fieldInfo; - - public WriteToBigQuery() { - } - - public WriteToBigQuery( - String projectId, - String datasetId, - String tableName, - Map> fieldInfo) { - this.projectId = projectId; - this.datasetId = datasetId; - this.tableName = tableName; - this.fieldInfo = fieldInfo; - } - - /** - * A {@link Serializable} function from a {@link DoFn.ProcessContext} - * and {@link BoundedWindow} to the value for that field. - */ - public interface FieldFn extends Serializable { - Object apply(DoFn.ProcessContext context, BoundedWindow window); - } - - /** Define a class to hold information about output table field definitions. */ - public static class FieldInfo implements Serializable { - // The BigQuery 'type' of the field - private String fieldType; - // A lambda function to generate the field value - private FieldFn fieldFn; - - public FieldInfo(String fieldType, - FieldFn fieldFn) { - this.fieldType = fieldType; - this.fieldFn = fieldFn; - } - - String getFieldType() { - return this.fieldType; - } - - FieldFn getFieldFn() { - return this.fieldFn; - } - } - - /** Convert each key/score pair into a BigQuery TableRow as specified by fieldFn. */ - protected class BuildRowFn extends DoFn { - - @ProcessElement - public void processElement(ProcessContext c, BoundedWindow window) { - - TableRow row = new TableRow(); - for (Map.Entry> entry : fieldInfo.entrySet()) { - String key = entry.getKey(); - FieldInfo fcnInfo = entry.getValue(); - FieldFn fcn = fcnInfo.getFieldFn(); - row.set(key, fcn.apply(c, window)); - } - c.output(row); - } - } - - /** Build the output table schema. */ - protected TableSchema getSchema() { - List fields = new ArrayList<>(); - for (Map.Entry> entry : fieldInfo.entrySet()) { - String key = entry.getKey(); - FieldInfo fcnInfo = entry.getValue(); - String bqType = fcnInfo.getFieldType(); - fields.add(new TableFieldSchema().setName(key).setType(bqType)); - } - return new TableSchema().setFields(fields); - } - - @Override - public PDone expand(PCollection teamAndScore) { - teamAndScore - .apply("ConvertToRow", ParDo.of(new BuildRowFn())) - .apply( - BigQueryIO.writeTableRows() - .to(getTable(projectId, datasetId, tableName)) - .withSchema(getSchema()) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(WriteDisposition.WRITE_APPEND)); - return PDone.in(teamAndScore.getPipeline()); - } - - /** Utility to construct an output table reference. */ - static TableReference getTable(String projectId, String datasetId, String tableName) { - TableReference table = new TableReference(); - table.setDatasetId(datasetId); - table.setProjectId(projectId); - table.setTableId(tableName); - return table; - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java deleted file mode 100644 index 76fa3ff075..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteToText.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * 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 ${package}.complete.game.utils; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; -import java.util.stream.Collectors; -import org.apache.beam.sdk.io.FileBasedSink; -import org.apache.beam.sdk.io.FileBasedSink.FilenamePolicy; -import org.apache.beam.sdk.io.FileBasedSink.OutputFileHints; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions; -import org.apache.beam.sdk.io.fs.ResourceId; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.PaneInfo; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PDone; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -/** - * Generate, format, and write rows. Use provided information about the field names and types, as - * well as lambda functions that describe how to generate their values. - */ -public class WriteToText - extends PTransform, PDone> { - - private static final DateTimeFormatter formatter = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") - .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))); - - protected String filenamePrefix; - protected Map> fieldFn; - protected boolean windowed; - - public WriteToText() { - } - - public WriteToText( - String filenamePrefix, - Map> fieldFn, - boolean windowed) { - this.filenamePrefix = filenamePrefix; - this.fieldFn = fieldFn; - this.windowed = windowed; - } - - /** - * A {@link Serializable} function from a {@link DoFn.ProcessContext} - * and {@link BoundedWindow} to the value for that field. - */ - public interface FieldFn extends Serializable { - Object apply(DoFn.ProcessContext context, BoundedWindow window); - } - - /** Convert each key/score pair into a row as specified by fieldFn. */ - protected class BuildRowFn extends DoFn { - - @ProcessElement - public void processElement(ProcessContext c, BoundedWindow window) { - List fields = new ArrayList<>(); - for (Map.Entry> entry : fieldFn.entrySet()) { - String key = entry.getKey(); - FieldFn fcn = entry.getValue(); - fields.add(key + ": " + fcn.apply(c, window)); - } - String result = fields.stream().collect(Collectors.joining(", ")); - c.output(result); - } - } - - /** - * A {@link DoFn} that writes elements to files with names deterministically derived from the - * lower and upper bounds of their key (an {@link IntervalWindow}). - */ - protected static class WriteOneFilePerWindow extends PTransform, PDone> { - - private final String filenamePrefix; - - public WriteOneFilePerWindow(String filenamePrefix) { - this.filenamePrefix = filenamePrefix; - } - - @Override - public PDone expand(PCollection input) { - // Verify that the input has a compatible window type. - checkArgument( - input.getWindowingStrategy().getWindowFn().windowCoder() == IntervalWindow.getCoder()); - - ResourceId resource = FileBasedSink.convertToFileResourceIfPossible(filenamePrefix); - - return input.apply( - TextIO.write() - .to(new PerWindowFiles(resource)) - .withTempDirectory(resource.getCurrentDirectory()) - .withWindowedWrites() - .withNumShards(3)); - } - } - - /** - * A {@link FilenamePolicy} produces a base file name for a write based on metadata about the data - * being written. This always includes the shard number and the total number of shards. For - * windowed writes, it also includes the window and pane index (a sequence number assigned to each - * trigger firing). - */ - protected static class PerWindowFiles extends FilenamePolicy { - - private final ResourceId prefix; - - public PerWindowFiles(ResourceId prefix) { - this.prefix = prefix; - } - - public String filenamePrefixForWindow(IntervalWindow window) { - String filePrefix = prefix.isDirectory() ? "" : prefix.getFilename(); - return String.format( - "%s-%s-%s", filePrefix, formatter.print(window.start()), formatter.print(window.end())); - } - - @Override - public ResourceId windowedFilename(int shardNumber, - int numShards, - BoundedWindow window, - PaneInfo paneInfo, - OutputFileHints outputFileHints) { - IntervalWindow intervalWindow = (IntervalWindow) window; - String filename = - String.format( - "%s-%s-of-%s%s", - filenamePrefixForWindow(intervalWindow), - shardNumber, - numShards, - outputFileHints.getSuggestedFilenameSuffix()); - return prefix.getCurrentDirectory().resolve(filename, StandardResolveOptions.RESOLVE_FILE); - } - - @Override - public ResourceId unwindowedFilename( - int shardNumber, int numShards, OutputFileHints outputFileHints) { - throw new UnsupportedOperationException("Unsupported."); - } - } - - @Override - public PDone expand(PCollection teamAndScore) { - if (windowed) { - teamAndScore - .apply("ConvertToRow", ParDo.of(new BuildRowFn())) - .apply(new WriteToText.WriteOneFilePerWindow(filenamePrefix)); - } else { - teamAndScore - .apply("ConvertToRow", ParDo.of(new BuildRowFn())) - .apply(TextIO.write().to(filenamePrefix)); - } - return PDone.in(teamAndScore.getPipeline()); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java deleted file mode 100644 index 6aef88706d..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/complete/game/utils/WriteWindowedToBigQuery.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 ${package}.complete.game.utils; - -import com.google.api.services.bigquery.model.TableRow; -import java.util.Map; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.PDone; - -/** - * Generate, format, and write BigQuery table row information. Subclasses {@link WriteToBigQuery} - * to require windowing; so this subclass may be used for writes that require access to the - * context's window information. - */ -public class WriteWindowedToBigQuery - extends WriteToBigQuery { - - public WriteWindowedToBigQuery( - String projectId, String datasetId, String tableName, Map> fieldInfo) { - super(projectId, datasetId, tableName, fieldInfo); - } - - /** Convert each key/score pair into a BigQuery TableRow. */ - protected class BuildRowFn extends DoFn { - @ProcessElement - public void processElement(ProcessContext c, BoundedWindow window) { - - TableRow row = new TableRow(); - for (Map.Entry> entry : fieldInfo.entrySet()) { - String key = entry.getKey(); - FieldInfo fcnInfo = entry.getValue(); - row.set(key, fcnInfo.getFieldFn().apply(c, window)); - } - c.output(row); - } - } - - @Override - public PDone expand(PCollection teamAndScore) { - teamAndScore - .apply("ConvertToRow", ParDo.of(new BuildRowFn())) - .apply(BigQueryIO.writeTableRows() - .to(getTable(projectId, datasetId, tableName)) - .withSchema(getSchema()) - .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) - .withWriteDisposition(WriteDisposition.WRITE_APPEND)); - return PDone.in(teamAndScore.getPipeline()); - } - -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java deleted file mode 100644 index 0fbee20cb5..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/DebuggingWordCountTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 ${package}; - -import com.google.common.io.Files; -import java.io.File; -import java.nio.charset.StandardCharsets; -import ${package}.DebuggingWordCount.WordCountOptions; -import org.apache.beam.sdk.testing.TestPipeline; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link DebuggingWordCount}. - */ -@RunWith(JUnit4.class) -public class DebuggingWordCountTest { - @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - - private String getFilePath(String filePath) { - if (filePath.contains(":")) { - return filePath.replace("\\", "/").split(":", -1)[1]; - } - return filePath; - } - - @Test - public void testDebuggingWordCount() throws Exception { - File inputFile = tmpFolder.newFile(); - File outputFile = tmpFolder.newFile(); - Files.write( - "stomach secret Flourish message Flourish here Flourish", - inputFile, - StandardCharsets.UTF_8); - WordCountOptions options = - TestPipeline.testingPipelineOptions().as(WordCountOptions.class); - options.setInputFile(getFilePath(inputFile.getAbsolutePath())); - options.setOutput(getFilePath(outputFile.getAbsolutePath())); - DebuggingWordCount.runDebuggingWordCount(options); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java deleted file mode 100644 index f4c8b160d7..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/MinimalWordCountTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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 ${package}; - -import com.google.common.collect.ImmutableList; -import java.io.IOException; -import java.io.Serializable; -import java.nio.channels.FileChannel; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; -import java.util.Arrays; -import org.apache.beam.sdk.extensions.gcp.options.GcsOptions; -import org.apache.beam.sdk.io.TextIO; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.transforms.Count; -import org.apache.beam.sdk.transforms.Filter; -import org.apache.beam.sdk.transforms.FlatMapElements; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.util.GcsUtil; -import org.apache.beam.sdk.util.gcsfs.GcsPath; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.TypeDescriptors; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; - -/** - * To keep {@link MinimalWordCount} simple, it is not factored or testable. This test - * file should be maintained with a copy of its code for a basic smoke test. - */ -@RunWith(JUnit4.class) -public class MinimalWordCountTest implements Serializable { - - @Rule - public TestPipeline p = TestPipeline.create().enableAbandonedNodeEnforcement(false); - - /** - * A basic smoke test that ensures there is no crash at pipeline construction time. - */ - @Test - public void testMinimalWordCount() throws Exception { - p.getOptions().as(GcsOptions.class).setGcsUtil(buildMockGcsUtil()); - - p.apply(TextIO.read().from("gs://apache-beam-samples/shakespeare/*")) - .apply( - FlatMapElements.into(TypeDescriptors.strings()) - .via((String word) -> Arrays.asList(word.split("[^a-zA-Z']+")))) - .apply(Filter.by((String word) -> !word.isEmpty())) - .apply(Count.perElement()) - .apply( - MapElements.into(TypeDescriptors.strings()) - .via( - (KV wordCount) -> - wordCount.getKey() + ": " + wordCount.getValue())) - .apply(TextIO.write().to("gs://your-output-bucket/and-output-prefix")); - } - - private GcsUtil buildMockGcsUtil() throws IOException { - GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class); - - // Any request to open gets a new bogus channel - Mockito.when(mockGcsUtil.open(Mockito.any(GcsPath.class))) - .then( - invocation -> - FileChannel.open( - Files.createTempFile("channel-", ".tmp"), - StandardOpenOption.CREATE, - StandardOpenOption.DELETE_ON_CLOSE)); - - // Any request for expansion returns a list containing the original GcsPath - // This is required to pass validation that occurs in TextIO during apply() - Mockito.when(mockGcsUtil.expand(Mockito.any(GcsPath.class))) - .then(invocation -> ImmutableList.of((GcsPath) invocation.getArguments()[0])); - - return mockGcsUtil; - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java deleted file mode 100644 index 91a1bf8edc..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/WordCountTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 ${package}; - -import java.util.Arrays; -import java.util.List; -import ${package}.WordCount.CountWords; -import ${package}.WordCount.ExtractWordsFn; -import ${package}.WordCount.FormatAsTextFn; -import org.apache.beam.sdk.coders.StringUtf8Coder; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.testing.ValidatesRunner; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.DoFnTester; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.values.PCollection; -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests of WordCount. - */ -@RunWith(JUnit4.class) -public class WordCountTest { - - /** Example test that tests a specific {@link DoFn}. */ - @Test - public void testExtractWordsFn() throws Exception { - DoFnTester extractWordsFn = - DoFnTester.of(new ExtractWordsFn()); - - Assert.assertThat(extractWordsFn.processBundle(" some input words "), - CoreMatchers.hasItems("some", "input", "words")); - Assert.assertThat(extractWordsFn.processBundle(" "), CoreMatchers.hasItems()); - Assert.assertThat(extractWordsFn.processBundle(" some ", " input", " words"), - CoreMatchers.hasItems("some", "input", "words")); - } - - static final String[] WORDS_ARRAY = new String[] { - "hi there", "hi", "hi sue bob", - "hi sue", "", "bob hi"}; - - static final List WORDS = Arrays.asList(WORDS_ARRAY); - - static final String[] COUNTS_ARRAY = new String[] { - "hi: 5", "there: 1", "sue: 2", "bob: 2"}; - - @Rule - public TestPipeline p = TestPipeline.create(); - - /** Example test that tests a PTransform by using an in-memory input and inspecting the output. */ - @Test - @Category(ValidatesRunner.class) - public void testCountWords() throws Exception { - PCollection input = p.apply(Create.of(WORDS).withCoder(StringUtf8Coder.of())); - - PCollection output = input.apply(new CountWords()) - .apply(MapElements.via(new FormatAsTextFn())); - - PAssert.that(output).containsInAnyOrder(COUNTS_ARRAY); - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java deleted file mode 100644 index 5cbdc6244f..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/GameStatsTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; -import ${package}.complete.game.GameStats.CalculateSpammyUsers; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.testing.ValidatesRunner; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests of GameStats. - * Because the pipeline was designed for easy readability and explanations, it lacks good - * modularity for testing. See our testing documentation for better ideas: - * https://beam.apache.org/documentation/pipelines/test-your-pipeline/ - */ -@RunWith(JUnit4.class) -public class GameStatsTest implements Serializable { - - // User scores - static final List> USER_SCORES = Arrays.asList( - KV.of("Robot-2", 66), KV.of("Robot-1", 116), KV.of("user7_AndroidGreenKookaburra", 23), - KV.of("user7_AndroidGreenKookaburra", 1), - KV.of("user19_BisqueBilby", 14), KV.of("user13_ApricotQuokka", 15), - KV.of("user18_BananaEmu", 25), KV.of("user6_AmberEchidna", 8), - KV.of("user2_AmberQuokka", 6), KV.of("user0_MagentaKangaroo", 4), - KV.of("user0_MagentaKangaroo", 3), KV.of("user2_AmberCockatoo", 13), - KV.of("user7_AlmondWallaby", 15), KV.of("user6_AmberNumbat", 11), - KV.of("user6_AmberQuokka", 4)); - - // The expected list of 'spammers'. - static final List> SPAMMERS = Arrays.asList( - KV.of("Robot-2", 66), KV.of("Robot-1", 116)); - - @Rule - public TestPipeline p = TestPipeline.create(); - - /** Test the calculation of 'spammy users'. */ - @Test - @Category(ValidatesRunner.class) - public void testCalculateSpammyUsers() throws Exception { - PCollection> input = p.apply(Create.of(USER_SCORES)); - PCollection> output = input.apply(new CalculateSpammyUsers()); - - // Check the set of spammers. - PAssert.that(output).containsInAnyOrder(SPAMMERS); - - p.run().waitUntilFinish(); - } - - @Test - public void testGameStatsOptions() { - PipelineOptionsFactory.as(GameStats.Options.class); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java deleted file mode 100644 index 17d459df93..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/HourlyTeamScoreTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; -import ${package}.complete.game.UserScore.GameActionInfo; -import ${package}.complete.game.UserScore.ParseEventFn; -import org.apache.beam.sdk.coders.StringUtf8Coder; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.testing.ValidatesRunner; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.transforms.Filter; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.TypeDescriptors; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests of HourlyTeamScore. - * Because the pipeline was designed for easy readability and explanations, it lacks good - * modularity for testing. See our testing documentation for better ideas: - * https://beam.apache.org/documentation/pipelines/test-your-pipeline/ - */ -@RunWith(JUnit4.class) -public class HourlyTeamScoreTest implements Serializable { - - static final String[] GAME_EVENTS_ARRAY = new String[] { - "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", - "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", - "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", - "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444", - // time gap... - "user0_AndroidGreenEchidna,AndroidGreenEchidna,0,1447965690000,2015-11-19 12:41:31.053", - "user0_MagentaKangaroo,MagentaKangaroo,4,1447965690000,2015-11-19 12:41:31.053", - "user2_AmberCockatoo,AmberCockatoo,13,1447965690000,2015-11-19 12:41:31.053", - "user18_BananaEmu,BananaEmu,7,1447965690000,2015-11-19 12:41:31.053", - "user3_BananaEmu,BananaEmu,17,1447965690000,2015-11-19 12:41:31.053", - "user18_BananaEmu,BananaEmu,1,1447965690000,2015-11-19 12:41:31.053", - "user18_ApricotCaneToad,ApricotCaneToad,14,1447965690000,2015-11-19 12:41:31.053" - }; - - - static final List GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); - - - // Used to check the filtering. - static final KV[] FILTERED_EVENTS = new KV[] { - KV.of("user0_AndroidGreenEchidna", 0), KV.of("user0_MagentaKangaroo", 4), - KV.of("user2_AmberCockatoo", 13), - KV.of("user18_BananaEmu", 7), KV.of("user3_BananaEmu", 17), - KV.of("user18_BananaEmu", 1), KV.of("user18_ApricotCaneToad", 14) - }; - - @Rule - public TestPipeline p = TestPipeline.create(); - - /** Test the filtering. */ - @Test - @Category(ValidatesRunner.class) - public void testUserScoresFilter() throws Exception { - - final Instant startMinTimestamp = new Instant(1447965680000L); - - PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); - - PCollection> output = input - .apply("ParseGameEvent", ParDo.of(new ParseEventFn())) - - .apply("FilterStartTime", Filter.by( - (GameActionInfo gInfo) - -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) - // run a map to access the fields in the result. - .apply(MapElements - .into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) - .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore()))); - - PAssert.that(output).containsInAnyOrder(FILTERED_EVENTS); - - p.run().waitUntilFinish(); - } - - @Test - public void testUserScoreOptions() { - PipelineOptionsFactory.as(HourlyTeamScore.Options.class); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java deleted file mode 100644 index 2478c07fa8..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/LeaderBoardTest.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertThat; - -import com.google.common.collect.ImmutableMap; -import java.io.Serializable; -import ${package}.complete.game.LeaderBoard.CalculateTeamScores; -import ${package}.complete.game.LeaderBoard.CalculateUserScores; -import ${package}.complete.game.UserScore.GameActionInfo; -import org.apache.beam.sdk.coders.AvroCoder; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.testing.TestStream; -import org.apache.beam.sdk.transforms.PTransform; -import org.apache.beam.sdk.transforms.windowing.BoundedWindow; -import org.apache.beam.sdk.transforms.windowing.GlobalWindow; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.TimestampedValue; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link LeaderBoard}. - */ -@RunWith(JUnit4.class) -public class LeaderBoardTest implements Serializable { - private static final Duration ALLOWED_LATENESS = Duration.standardHours(1); - private static final Duration TEAM_WINDOW_DURATION = Duration.standardMinutes(20); - private Instant baseTime = new Instant(0); - - @Rule - public TestPipeline p = TestPipeline.create(); - /** - * Some example users, on two separate teams. - */ - private enum TestUser { - RED_ONE("scarlet", "red"), RED_TWO("burgundy", "red"), - BLUE_ONE("navy", "blue"), BLUE_TWO("sky", "blue"); - - private final String userName; - private final String teamName; - - TestUser(String userName, String teamName) { - this.userName = userName; - this.teamName = teamName; - } - - public String getUser() { - return userName; - } - - public String getTeam() { - return teamName; - } - } - - /** - * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive - * on time (ahead of the watermark). - */ - @Test - public void testTeamScoresOnTime() { - - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - // Start at the epoch - .advanceWatermarkTo(baseTime) - // add some elements ahead of the watermark - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1)), - event(TestUser.RED_TWO, 3, Duration.standardSeconds(22)), - event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(3))) - // The watermark advances slightly, but not past the end of the window - .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) - // Add some more on time elements - .addElements(event(TestUser.RED_ONE, 1, Duration.standardMinutes(4)), - event(TestUser.BLUE_ONE, 2, Duration.standardSeconds(270))) - // The window should close and emit an ON_TIME pane - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - PAssert.that(teamScores) - .inOnTimePane(new IntervalWindow(baseTime, TEAM_WINDOW_DURATION)) - .containsInAnyOrder(KV.of(blueTeam, 12), KV.of(redTeam, 4)); - - p.run().waitUntilFinish(); - } - - /** - * A test of the {@link CalculateTeamScores} {@link PTransform} when all of the elements arrive - * on time, and the processing time advances far enough for speculative panes. - */ - @Test - public void testTeamScoresSpeculative() { - - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - // Start at the epoch - .advanceWatermarkTo(baseTime) - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_ONE, 2, Duration.standardMinutes(1))) - // Some time passes within the runner, which causes a speculative pane containing the blue - // team's score to be emitted - .advanceProcessingTime(Duration.standardMinutes(10)) - .addElements(event(TestUser.RED_TWO, 5, Duration.standardMinutes(3))) - // Some additional time passes and we get a speculative pane for the red team - .advanceProcessingTime(Duration.standardMinutes(12)) - .addElements(event(TestUser.BLUE_TWO, 3, Duration.standardSeconds(22))) - // More time passes and a speculative pane containing a refined value for the blue pane is - // emitted - .advanceProcessingTime(Duration.standardMinutes(10)) - // Some more events occur - .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(4)), - event(TestUser.BLUE_TWO, 2, Duration.standardMinutes(2))) - // The window closes and we get an ON_TIME pane that contains all of the updates - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - IntervalWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - // The window contains speculative panes alongside the on-time pane - PAssert.that(teamScores) - .inWindow(window) - .containsInAnyOrder(KV.of(blueTeam, 10) /* The on-time blue pane */, - KV.of(redTeam, 9) /* The on-time red pane */, - KV.of(blueTeam, 5) /* The first blue speculative pane */, - KV.of(blueTeam, 8) /* The second blue speculative pane */, - KV.of(redTeam, 5) /* The red speculative pane */); - PAssert.that(teamScores) - .inOnTimePane(window) - .containsInAnyOrder(KV.of(blueTeam, 10), KV.of(redTeam, 9)); - - p.run().waitUntilFinish(); - } - - /** - * A test where elements arrive behind the watermark (late data), but before the end of the - * window. These elements are emitted on time. - */ - @Test - public void testTeamScoresUnobservablyLate() { - - BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - .advanceWatermarkTo(baseTime) - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8)), - event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) - .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).minus(Duration.standardMinutes(1))) - // These events are late, but the window hasn't closed yet, so the elements are in the - // on-time pane - .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), - event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), - event(TestUser.BLUE_TWO, 2, Duration.standardSeconds(90)), - event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) - .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) - .advanceWatermarkToInfinity(); - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - // The On Time pane contains the late elements that arrived before the end of the window - PAssert.that(teamScores) - .inOnTimePane(window) - .containsInAnyOrder(KV.of(redTeam, 14), KV.of(blueTeam, 13)); - - p.run().waitUntilFinish(); - } - - /** - * A test where elements arrive behind the watermark (late data) after the watermark passes the - * end of the window, but before the maximum allowed lateness. These elements are emitted in a - * late pane. - */ - @Test - public void testTeamScoresObservablyLate() { - - Instant firstWindowCloses = baseTime.plus(ALLOWED_LATENESS).plus(TEAM_WINDOW_DURATION); - TestStream createEvents = TestStream.create(AvroCoder.of(GameActionInfo.class)) - .advanceWatermarkTo(baseTime) - .addElements(event(TestUser.BLUE_ONE, 3, Duration.standardSeconds(3)), - event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(8))) - .advanceProcessingTime(Duration.standardMinutes(10)) - .advanceWatermarkTo(baseTime.plus(Duration.standardMinutes(3))) - .addElements(event(TestUser.RED_ONE, 3, Duration.standardMinutes(1)), - event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(5))) - .advanceWatermarkTo(firstWindowCloses.minus(Duration.standardMinutes(1))) - // These events are late but should still appear in a late pane - .addElements(event(TestUser.RED_TWO, 2, Duration.ZERO), - event(TestUser.RED_TWO, 5, Duration.standardMinutes(1)), - event(TestUser.RED_TWO, 3, Duration.standardMinutes(3))) - // A late refinement is emitted due to the advance in processing time, but the window has - // not yet closed because the watermark has not advanced - .advanceProcessingTime(Duration.standardMinutes(12)) - // These elements should appear in the final pane - .addElements(event(TestUser.RED_TWO, 9, Duration.standardMinutes(1)), - event(TestUser.RED_TWO, 1, Duration.standardMinutes(3))) - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - PAssert.that(teamScores) - .inWindow(window) - .satisfies( - input -> { - // The final sums need not exist in the same pane, but must appear in the output - // PCollection - assertThat(input, hasItem(KV.of(blueTeam, 11))); - assertThat(input, hasItem(KV.of(redTeam, 27))); - return null; - }); - PAssert.thatMap(teamScores) - // The closing behavior of CalculateTeamScores precludes an inFinalPane matcher - .inOnTimePane(window) - .isEqualTo(ImmutableMap.builder().put(redTeam, 7) - .put(blueTeam, 11) - .build()); - - // No final pane is emitted for the blue team, as all of their updates have been taken into - // account in earlier panes - PAssert.that(teamScores).inFinalPane(window).containsInAnyOrder(KV.of(redTeam, 27)); - - p.run().waitUntilFinish(); - } - - /** - * A test where elements arrive beyond the maximum allowed lateness. These elements are dropped - * within {@link CalculateTeamScores} and do not impact the final result. - */ - @Test - public void testTeamScoresDroppablyLate() { - - BoundedWindow window = new IntervalWindow(baseTime, TEAM_WINDOW_DURATION); - TestStream infos = TestStream.create(AvroCoder.of(GameActionInfo.class)) - .addElements(event(TestUser.BLUE_ONE, 12, Duration.ZERO), - event(TestUser.RED_ONE, 3, Duration.ZERO)) - .advanceWatermarkTo(window.maxTimestamp()) - .addElements(event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_TWO, 3, Duration.ZERO), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) - // Move the watermark to the end of the window to output on time - .advanceWatermarkTo(baseTime.plus(TEAM_WINDOW_DURATION)) - // Move the watermark past the end of the allowed lateness plus the end of the window - .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS) - .plus(TEAM_WINDOW_DURATION).plus(Duration.standardMinutes(1))) - // These elements within the expired window are droppably late, and will not appear in the - // output - .addElements( - event(TestUser.BLUE_TWO, 3, TEAM_WINDOW_DURATION.minus(Duration.standardSeconds(5))), - event(TestUser.RED_ONE, 7, Duration.standardMinutes(4))) - .advanceWatermarkToInfinity(); - PCollection> teamScores = p.apply(infos) - .apply(new CalculateTeamScores(TEAM_WINDOW_DURATION, ALLOWED_LATENESS)); - - String blueTeam = TestUser.BLUE_ONE.getTeam(); - String redTeam = TestUser.RED_ONE.getTeam(); - // Only one on-time pane and no late panes should be emitted - PAssert.that(teamScores) - .inWindow(window) - .containsInAnyOrder(KV.of(redTeam, 7), KV.of(blueTeam, 18)); - // No elements are added before the watermark passes the end of the window plus the allowed - // lateness, so no refinement should be emitted - PAssert.that(teamScores).inFinalPane(window).empty(); - - p.run().waitUntilFinish(); - } - - /** - * A test where elements arrive both on-time and late in {@link CalculateUserScores}, which emits - * output into the {@link GlobalWindow}. All elements that arrive should be taken into account, - * even if they arrive later than the maximum allowed lateness. - */ - @Test - public void testUserScore() { - - TestStream infos = - TestStream.create(AvroCoder.of(GameActionInfo.class)) - .addElements( - event(TestUser.BLUE_ONE, 12, Duration.ZERO), - event(TestUser.RED_ONE, 3, Duration.ZERO)) - .advanceProcessingTime(Duration.standardMinutes(7)) - .addElements( - event(TestUser.RED_ONE, 4, Duration.standardMinutes(2)), - event(TestUser.BLUE_TWO, 3, Duration.ZERO), - event(TestUser.BLUE_ONE, 3, Duration.standardMinutes(3))) - .advanceProcessingTime(Duration.standardMinutes(5)) - .advanceWatermarkTo(baseTime.plus(ALLOWED_LATENESS).plus(Duration.standardHours(12))) - // Late elements are always observable within the global window - they arrive before - // the window closes, so they will appear in a pane, even if they arrive after the - // allowed lateness, and are taken into account alongside on-time elements - .addElements( - event(TestUser.RED_ONE, 3, Duration.standardMinutes(7)), - event(TestUser.RED_ONE, 2, (ALLOWED_LATENESS).plus(Duration.standardHours(13)))) - .advanceProcessingTime(Duration.standardMinutes(6)) - .addElements(event(TestUser.BLUE_TWO, 5, Duration.standardMinutes(12))) - .advanceProcessingTime(Duration.standardMinutes(20)) - .advanceWatermarkToInfinity(); - - PCollection> userScores = - p.apply(infos).apply(new CalculateUserScores(ALLOWED_LATENESS)); - - // User scores are emitted in speculative panes in the Global Window - this matcher choice - // ensures that panes emitted by the watermark advancing to positive infinity are not included, - // as that will not occur outside of tests - PAssert.that(userScores) - .inEarlyGlobalWindowPanes() - .containsInAnyOrder(KV.of(TestUser.BLUE_ONE.getUser(), 15), - KV.of(TestUser.RED_ONE.getUser(), 7), - KV.of(TestUser.RED_ONE.getUser(), 12), - KV.of(TestUser.BLUE_TWO.getUser(), 3), - KV.of(TestUser.BLUE_TWO.getUser(), 8)); - - p.run().waitUntilFinish(); - } - - @Test - public void testLeaderBoardOptions() { - PipelineOptionsFactory.as(LeaderBoard.Options.class); - } - - private TimestampedValue event( - TestUser user, - int score, - Duration baseTimeOffset) { - return TimestampedValue.of(new GameActionInfo(user.getUser(), - user.getTeam(), - score, - baseTime.plus(baseTimeOffset).getMillis()), baseTime.plus(baseTimeOffset)); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java deleted file mode 100644 index c80c57f4fc..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/StatefulTeamScoreTest.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import ${package}.complete.game.StatefulTeamScore.UpdateTeamScoreFn; -import ${package}.complete.game.UserScore.GameActionInfo; -import org.apache.beam.sdk.coders.AvroCoder; -import org.apache.beam.sdk.coders.KvCoder; -import org.apache.beam.sdk.coders.StringUtf8Coder; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.testing.TestStream; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.windowing.FixedWindows; -import org.apache.beam.sdk.transforms.windowing.GlobalWindow; -import org.apache.beam.sdk.transforms.windowing.IntervalWindow; -import org.apache.beam.sdk.transforms.windowing.Window; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.TimestampedValue; -import org.joda.time.Duration; -import org.joda.time.Instant; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link StatefulTeamScore}. - */ -@RunWith(JUnit4.class) -public class StatefulTeamScoreTest { - - private Instant baseTime = new Instant(0); - - @Rule - public TestPipeline p = TestPipeline.create(); - - /** - * Some example users, on two separate teams. - */ - private enum TestUser { - RED_ONE("scarlet", "red"), RED_TWO("burgundy", "red"), - BLUE_ONE("navy", "blue"), BLUE_TWO("sky", "blue"); - - private final String userName; - private final String teamName; - - TestUser(String userName, String teamName) { - this.userName = userName; - this.teamName = teamName; - } - - public String getUser() { - return userName; - } - - public String getTeam() { - return teamName; - } - } - - /** - * Tests that {@link UpdateTeamScoreFn} {@link org.apache.beam.sdk.transforms.DoFn} outputs - * correctly for one team. - */ - @Test - public void testScoreUpdatesOneTeam() { - - TestStream> createEvents = TestStream.create(KvCoder.of( - StringUtf8Coder.of(), AvroCoder.of(GameActionInfo.class))) - .advanceWatermarkTo(baseTime) - .addElements( - event(TestUser.RED_TWO, 99, Duration.standardSeconds(10)), - event(TestUser.RED_ONE, 1, Duration.standardSeconds(20)), - event(TestUser.RED_ONE, 0, Duration.standardSeconds(30)), - event(TestUser.RED_TWO, 100, Duration.standardSeconds(40)), - event(TestUser.RED_TWO, 201, Duration.standardSeconds(50)) - ) - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(ParDo.of(new UpdateTeamScoreFn(100))); - - String redTeam = TestUser.RED_ONE.getTeam(); - - PAssert.that(teamScores) - .inWindow(GlobalWindow.INSTANCE) - .containsInAnyOrder( - KV.of(redTeam, 100), - KV.of(redTeam, 200), - KV.of(redTeam, 401) - ); - - p.run().waitUntilFinish(); - } - - /** - * Tests that {@link UpdateTeamScoreFn} {@link org.apache.beam.sdk.transforms.DoFn} outputs - * correctly for multiple teams. - */ - @Test - public void testScoreUpdatesPerTeam() { - - TestStream> createEvents = TestStream.create(KvCoder.of( - StringUtf8Coder.of(), AvroCoder.of(GameActionInfo.class))) - .advanceWatermarkTo(baseTime) - .addElements( - event(TestUser.RED_ONE, 50, Duration.standardSeconds(10)), - event(TestUser.RED_TWO, 50, Duration.standardSeconds(20)), - event(TestUser.BLUE_ONE, 70, Duration.standardSeconds(30)), - event(TestUser.BLUE_TWO, 80, Duration.standardSeconds(40)), - event(TestUser.BLUE_TWO, 50, Duration.standardSeconds(50)) - ) - .advanceWatermarkToInfinity(); - - PCollection> teamScores = p.apply(createEvents) - .apply(ParDo.of(new UpdateTeamScoreFn(100))); - - String redTeam = TestUser.RED_ONE.getTeam(); - String blueTeam = TestUser.BLUE_ONE.getTeam(); - - PAssert.that(teamScores) - .inWindow(GlobalWindow.INSTANCE) - .containsInAnyOrder( - KV.of(redTeam, 100), - KV.of(blueTeam, 150), - KV.of(blueTeam, 200) - ); - - p.run().waitUntilFinish(); - } - - /** - * Tests that {@link UpdateTeamScoreFn} {@link org.apache.beam.sdk.transforms.DoFn} outputs - * correctly per window and per key. - */ - @Test - public void testScoreUpdatesPerWindow() { - - TestStream> createEvents = TestStream.create(KvCoder.of( - StringUtf8Coder.of(), AvroCoder.of(GameActionInfo.class))) - .advanceWatermarkTo(baseTime) - .addElements( - event(TestUser.RED_ONE, 50, Duration.standardMinutes(1)), - event(TestUser.RED_TWO, 50, Duration.standardMinutes(2)), - event(TestUser.RED_ONE, 50, Duration.standardMinutes(3)), - event(TestUser.RED_ONE, 60, Duration.standardMinutes(6)), - event(TestUser.RED_TWO, 60, Duration.standardMinutes(7)) - ) - .advanceWatermarkToInfinity(); - - Duration teamWindowDuration = Duration.standardMinutes(5); - - PCollection> teamScores = p - .apply(createEvents) - .apply(Window.>into(FixedWindows.of(teamWindowDuration))) - .apply(ParDo.of(new UpdateTeamScoreFn(100))); - - String redTeam = TestUser.RED_ONE.getTeam(); - String blueTeam = TestUser.BLUE_ONE.getTeam(); - - IntervalWindow window1 = new IntervalWindow(baseTime, teamWindowDuration); - IntervalWindow window2 = new IntervalWindow(window1.end(), teamWindowDuration); - - PAssert.that(teamScores) - .inWindow(window1) - .containsInAnyOrder( - KV.of(redTeam, 100) - ); - - PAssert.that(teamScores) - .inWindow(window2) - .containsInAnyOrder( - KV.of(redTeam, 120) - ); - - p.run().waitUntilFinish(); - } - - private TimestampedValue> event( - TestUser user, - int score, - Duration baseTimeOffset) { - return TimestampedValue.of(KV.of(user.getTeam(), new GameActionInfo(user.getUser(), - user.getTeam(), - score, - baseTime.plus(baseTimeOffset).getMillis())), baseTime.plus(baseTimeOffset)); - } -} diff --git a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java b/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java deleted file mode 100644 index b691a0cbd5..0000000000 --- a/maven-archetypes/examples/src/main/resources/archetype-resources/src/test/java/complete/game/UserScoreTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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 ${package}.complete.game; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; -import ${package}.complete.game.UserScore.ExtractAndSumScore; -import ${package}.complete.game.UserScore.GameActionInfo; -import ${package}.complete.game.UserScore.ParseEventFn; -import org.apache.beam.sdk.coders.StringUtf8Coder; -import org.apache.beam.sdk.testing.PAssert; -import org.apache.beam.sdk.testing.TestPipeline; -import org.apache.beam.sdk.testing.ValidatesRunner; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.transforms.DoFnTester; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.values.KV; -import org.apache.beam.sdk.values.PCollection; -import org.apache.beam.sdk.values.TypeDescriptors; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests of UserScore. - */ -@RunWith(JUnit4.class) -public class UserScoreTest implements Serializable { - - static final String[] GAME_EVENTS_ARRAY = new String[] { - "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", - "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", - "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", - "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", - "user6_AliceBlueDingo,AliceBlueDingo,4,xxxxxxx,2015-11-19 09:53:53.444", - "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", - "THIS IS A PARSE ERROR,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", - "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444" - }; - - static final String[] GAME_EVENTS_ARRAY2 = new String[] { - "user6_AliceBlueDingo,AliceBlueDingo,4,xxxxxxx,2015-11-19 09:53:53.444", - "THIS IS A PARSE ERROR,2015-11-19 09:53:53.444", - "user13_BisqueBilby,BisqueBilby,xxx,1447955630000,2015-11-19 09:53:53.444" - }; - - static final List GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); - static final List GAME_EVENTS2 = Arrays.asList(GAME_EVENTS_ARRAY2); - - static final List> USER_SUMS = Arrays.asList( - KV.of("user0_MagentaKangaroo", 3), KV.of("user13_ApricotQuokka", 15), - KV.of("user6_AmberNumbat", 11), KV.of("user7_AlmondWallaby", 15), - KV.of("user7_AndroidGreenKookaburra", 23), - KV.of("user19_BisqueBilby", 14)); - - static final List> TEAM_SUMS = Arrays.asList( - KV.of("MagentaKangaroo", 3), KV.of("ApricotQuokka", 15), - KV.of("AmberNumbat", 11), KV.of("AlmondWallaby", 15), - KV.of("AndroidGreenKookaburra", 23), - KV.of("BisqueBilby", 14)); - - @Rule - public TestPipeline p = TestPipeline.create(); - - /** Test the {@link ParseEventFn} {@link org.apache.beam.sdk.transforms.DoFn}. */ - @Test - public void testParseEventFn() throws Exception { - DoFnTester parseEventFn = - DoFnTester.of(new ParseEventFn()); - - List results = parseEventFn.processBundle(GAME_EVENTS_ARRAY); - Assert.assertEquals(8, results.size()); - Assert.assertEquals("user0_MagentaKangaroo", results.get(0).getUser()); - Assert.assertEquals("MagentaKangaroo", results.get(0).getTeam()); - Assert.assertEquals(Integer.valueOf(3), results.get(0).getScore()); - } - - /** Tests ExtractAndSumScore("user"). */ - @Test - @Category(ValidatesRunner.class) - public void testUserScoreSums() throws Exception { - - PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); - - PCollection> output = input - .apply(ParDo.of(new ParseEventFn())) - // Extract and sum username/score pairs from the event data. - .apply("ExtractUserScore", new ExtractAndSumScore("user")); - - // Check the user score sums. - PAssert.that(output).containsInAnyOrder(USER_SUMS); - - p.run().waitUntilFinish(); - } - - /** Tests ExtractAndSumScore("team"). */ - @Test - @Category(ValidatesRunner.class) - public void testTeamScoreSums() throws Exception { - - PCollection input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); - - PCollection> output = input - .apply(ParDo.of(new ParseEventFn())) - // Extract and sum teamname/score pairs from the event data. - .apply("ExtractTeamScore", new ExtractAndSumScore("team")); - - // Check the team score sums. - PAssert.that(output).containsInAnyOrder(TEAM_SUMS); - - p.run().waitUntilFinish(); - } - - /** Test that bad input data is dropped appropriately. */ - @Test - @Category(ValidatesRunner.class) - public void testUserScoresBadInput() throws Exception { - - PCollection input = p.apply(Create.of(GAME_EVENTS2).withCoder(StringUtf8Coder.of())); - - PCollection> extract = input - .apply(ParDo.of(new ParseEventFn())) - .apply( - MapElements - .into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())) - .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore()))); - - PAssert.that(extract).empty(); - - p.run().waitUntilFinish(); - } -} diff --git a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties deleted file mode 100644 index b0195b3f16..0000000000 --- a/maven-archetypes/examples/src/test/resources/projects/basic/archetype.properties +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed 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=it.pkg -version=0.1 -groupId=archetype.it -artifactId=basic -targetPlatform=1.8 diff --git a/maven-archetypes/examples/src/test/resources/projects/basic/goal.txt b/maven-archetypes/examples/src/test/resources/projects/basic/goal.txt deleted file mode 100644 index 0b5987362f..0000000000 --- a/maven-archetypes/examples/src/test/resources/projects/basic/goal.txt +++ /dev/null @@ -1 +0,0 @@ -verify diff --git a/maven-archetypes/pom.xml b/maven-archetypes/pom.xml deleted file mode 100644 index f995770ea6..0000000000 --- a/maven-archetypes/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - 4.0.0 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-parent - 2.6.0-SNAPSHOT - ../pom.xml - - - google-cloud-dataflow-java-archetypes-parent - pom - - Google Cloud Dataflow SDK for Java - Maven Archetypes - - - starter - examples - - - - - - - src/main/resources - true - - archetype-resources/pom.xml - - - - - src/main/resources - false - - archetype-resources/pom.xml - - - - - - - - org.apache.maven.plugins - maven-resources-plugin - - - @ - - false - - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - default-jar - none - - - default-test-jar - none - - - - - - diff --git a/maven-archetypes/starter/pom.xml b/maven-archetypes/starter/pom.xml deleted file mode 100644 index 643cfa4096..0000000000 --- a/maven-archetypes/starter/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - 4.0.0 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-archetypes-parent - 2.6.0-SNAPSHOT - ../pom.xml - - - google-cloud-dataflow-java-archetypes-starter - Google Cloud Dataflow SDK for Java - Starter Archetype - Google Cloud Dataflow SDK for Java is a distribution of Apache - Beam designed to simplify usage of Apache Beam on Google Cloud Dataflow - service. This archetype creates a simple starter pipeline to get started - using the Google Cloud Dataflow SDK for Java. - - maven-archetype - - - - - org.apache.maven.archetype - archetype-packaging - ${archetype-packaging.version} - - - - - - - src/test/resources - true - - - - - - - maven-archetype-plugin - ${maven-archetype-plugin.version} - - - org.apache.maven.shared - maven-invoker - ${maven-invoker.version} - - - - - - default-integration-test - install - - integration-test - - - - true - - - - - - - - - diff --git a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml deleted file mode 100644 index 428c74aa4a..0000000000 --- a/maven-archetypes/starter/src/main/resources/META-INF/maven/archetype-metadata.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - 1.8 - - - - - - src/main/java - - **/*.java - - - - diff --git a/maven-archetypes/starter/src/main/resources/NOTICE b/maven-archetypes/starter/src/main/resources/NOTICE deleted file mode 100644 index 981fde5a9e..0000000000 --- a/maven-archetypes/starter/src/main/resources/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Google Cloud Dataflow SDK for Java -Copyright 2017, Google Inc. - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml b/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml deleted file mode 100644 index da443b16fa..0000000000 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - 4.0.0 - - ${groupId} - ${artifactId} - ${version} - - - UTF-8 - @maven-compiler-plugin.version@ - @exec-maven-plugin.version@ - @slf4j.version@ - - - - - ossrh.snapshots - Sonatype OSS Repository Hosting - https://oss.sonatype.org/content/repositories/snapshots/ - - false - - - true - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${targetPlatform} - ${targetPlatform} - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - false - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - @project.version@ - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - - - diff --git a/maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java b/maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java deleted file mode 100644 index d6afdecf11..0000000000 --- a/maven-archetypes/starter/src/main/resources/archetype-resources/src/main/java/StarterPipeline.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 ${package}; - -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.SimpleFunction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A starter example for writing Beam programs. - * - *

              The example takes two strings, converts them to their upper-case - * representation and logs them. - * - *

              To run this starter example locally using DirectRunner, just - * execute it without any additional parameters from your favorite development - * environment. - * - *

              To run this starter example using managed resource in Google Cloud - * Platform, you should specify the following command-line options: - * --project= - * --stagingLocation= - * --runner=DataflowRunner - */ -public class StarterPipeline { - private static final Logger LOG = LoggerFactory.getLogger(StarterPipeline.class); - - public static void main(String[] args) { - Pipeline p = Pipeline.create( - PipelineOptionsFactory.fromArgs(args).withValidation().create()); - - p.apply(Create.of("Hello", "World")) - .apply(MapElements.via(new SimpleFunction() { - @Override - public String apply(String input) { - return input.toUpperCase(); - } - })) - .apply(ParDo.of(new DoFn() { - @ProcessElement - public void processElement(ProcessContext c) { - LOG.info(c.element()); - } - })); - - p.run(); - } -} diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties b/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties deleted file mode 100644 index b0195b3f16..0000000000 --- a/maven-archetypes/starter/src/test/resources/projects/basic/archetype.properties +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed 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=it.pkg -version=0.1 -groupId=archetype.it -artifactId=basic -targetPlatform=1.8 diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/goal.txt b/maven-archetypes/starter/src/test/resources/projects/basic/goal.txt deleted file mode 100644 index 0b5987362f..0000000000 --- a/maven-archetypes/starter/src/test/resources/projects/basic/goal.txt +++ /dev/null @@ -1 +0,0 @@ -verify diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml b/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml deleted file mode 100644 index daf87595b7..0000000000 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - 4.0.0 - - archetype.it - basic - 0.1 - - - UTF-8 - @maven-compiler-plugin.version@ - @exec-maven-plugin.version@ - @slf4j.version@ - - - - - ossrh.snapshots - Sonatype OSS Repository Hosting - https://oss.sonatype.org/content/repositories/snapshots/ - - false - - - true - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - false - - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - @project.version@ - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - - - diff --git a/maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java b/maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java deleted file mode 100644 index 4ae92e8ce6..0000000000 --- a/maven-archetypes/starter/src/test/resources/projects/basic/reference/src/main/java/it/pkg/StarterPipeline.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 it.pkg; - -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.options.PipelineOptionsFactory; -import org.apache.beam.sdk.transforms.Create; -import org.apache.beam.sdk.transforms.DoFn; -import org.apache.beam.sdk.transforms.MapElements; -import org.apache.beam.sdk.transforms.ParDo; -import org.apache.beam.sdk.transforms.SimpleFunction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A starter example for writing Beam programs. - * - *

              The example takes two strings, converts them to their upper-case - * representation and logs them. - * - *

              To run this starter example locally using DirectRunner, just - * execute it without any additional parameters from your favorite development - * environment. - * - *

              To run this starter example using managed resource in Google Cloud - * Platform, you should specify the following command-line options: - * --project= - * --stagingLocation= - * --runner=DataflowRunner - */ -public class StarterPipeline { - private static final Logger LOG = LoggerFactory.getLogger(StarterPipeline.class); - - public static void main(String[] args) { - Pipeline p = Pipeline.create( - PipelineOptionsFactory.fromArgs(args).withValidation().create()); - - p.apply(Create.of("Hello", "World")) - .apply(MapElements.via(new SimpleFunction() { - @Override - public String apply(String input) { - return input.toUpperCase(); - } - })) - .apply(ParDo.of(new DoFn() { - @ProcessElement - public void processElement(ProcessContext c) { - LOG.info(c.element()); - } - })); - - p.run(); - } -} diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 2924ff9fa2..0000000000 --- a/pom.xml +++ /dev/null @@ -1,449 +0,0 @@ - - - - 4.0.0 - - - com.google - google - 5 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-parent - Google Cloud Dataflow SDK for Java - Parent - Google Cloud Dataflow SDK for Java is a distribution of Apache - Beam designed to simplify usage of Apache Beam on Google Cloud Dataflow - service. This artifact includes the parent POM for other Dataflow SDK - artifacts. - http://cloud.google.com/dataflow - 2013 - - 2.6.0-SNAPSHOT - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - - Google Inc. - http://www.google.com - - - - - scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - scm:git:git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - git@github.com:GoogleCloudPlatform/DataflowJavaSDK.git - HEAD - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - apache.staging - Apache Software Foundation Staging Repository - https://repository.apache.org/content/repositories/staging/ - - true - - - false - - - - - apache.snapshots - Apache Software Foundation Snapshot Repository - https://repository.apache.org/content/repositories/snapshots/ - - false - - - true - - - - - - 3.2 - - - - 1.8 - - UTF-8 - ${maven.build.timestamp} - yyyy-MM-dd HH:mm - - 2.5.0 - - Google Cloud Dataflow SDK for Java - beam-${beam.version} - 6 - 1 - - v2-rev374-1.23.0 - 8.7 - 1.0.0 - 1.23.0 - 20.0 - 1.3 - 2.4 - 4.12 - 1.0.0 - 1.9.5 - v1-rev382-1.23.0 - 1.7.25 - - 2.4 - 1.6.0 - 2.20.1 - 2.4 - 3.0.0 - 3.1.0 - 3.7.0 - 3.1.1 - 2.2 - 3.0.2 - 3.0.0-M1 - 2.5.3 - 3.1.0 - 3.1.0 - 2.21.0 - 3.0.1 - - - pom - - sdk - examples - maven-archetypes - - - - - - - org.apache.maven.plugins - maven-clean-plugin - ${maven-clean-plugin.version} - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - -Xlint:all - -Werror - -Xlint:-options - - -Xlint:-processing - - true - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${maven-checkstyle-plugin.version} - - - com.puppycrawl.tools - checkstyle - ${checkstyle.version} - - - org.apache.beam - beam-sdks-java-build-tools - ${beam.version} - - - - beam/checkstyle.xml - sdk/suppressions.xml - true - true - false - true - - - - - test-compile - - check - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - true - - - - default-jar - - jar - - - - default-test-jar - - test-jar - - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - attach-sources - compile - - jar - - - - attach-test-sources - test-compile - - test-jar - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - false - - - - javadoc - package - - jar - - - - - - - org.apache.maven.plugins - maven-resources-plugin - ${maven-resources-plugin.version} - - - - org.apache.maven.plugins - maven-dependency-plugin - ${maven-dependency-plugin.version} - - - - analyze-only - - - true - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - org.apache.maven.plugins - maven-archetype-plugin - ${maven-archetype-plugin.version} - - - org.apache.maven.shared - maven-invoker - ${maven-invoker.version} - - - - - - default-integration-test - install - - integration-test - - - true - - - - - - - org.apache.maven.plugins - maven-release-plugin - ${maven-release-plugin} - - true - true - deploy - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - false - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-source-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - org.apache.maven.plugins - maven-dependency-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - - - - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - ${project.version} - - - - org.apache.beam - beam-sdks-java-core - ${beam.version} - - - - org.apache.beam - beam-sdks-java-io-google-cloud-platform - ${beam.version} - - - - org.apache.beam - beam-runners-direct-java - ${beam.version} - - - - org.apache.beam - beam-runners-google-cloud-dataflow-java - ${beam.version} - - - - org.apache.beam - beam-examples-java - ${beam.version} - - - - org.apache.beam - beam-sdks-java-io-kafka - ${beam.version} - - - - junit - junit - ${junit.version} - test - - - - diff --git a/sdk/pom.xml b/sdk/pom.xml deleted file mode 100644 index 0bd69dc58c..0000000000 --- a/sdk/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - 4.0.0 - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-parent - 2.6.0-SNAPSHOT - - - google-cloud-dataflow-java-sdk-all - Google Cloud Dataflow SDK for Java - All - Google Cloud Dataflow SDK for Java is a distribution of Apache - Beam designed to simplify usage of Apache Beam on Google Cloud Dataflow - service. This artifact includes entire Dataflow Java SDK. - - jar - - - - - src/main/resources - true - - - - - - - org.apache.beam - beam-sdks-java-core - - - - org.apache.beam - beam-sdks-java-io-google-cloud-platform - - - - org.apache.beam - beam-runners-direct-java - - - - org.apache.beam - beam-runners-google-cloud-dataflow-java - - - - org.apache.beam - beam-sdks-java-io-kafka - - - - junit - junit - test - - - diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java deleted file mode 100644 index df3fd76ae6..0000000000 --- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/SdkDependencies.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2017 Google Inc. - * - * Licensed 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 com.google.cloud.dataflow.sdk; - -import org.apache.beam.runners.dataflow.DataflowRunner; -import org.apache.beam.runners.direct.DirectRunner; -import org.apache.beam.sdk.Pipeline; -import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; -import org.apache.beam.sdk.io.kafka.KafkaIO; - -/** - * Mark the dependencies as used at compile time. - */ -class SdkDependencies { - private Pipeline p; - private BigQueryIO bigQueryIO; - private KafkaIO kafkaIO; - private DirectRunner directRunner; - private DataflowRunner dataflowRunner; -} diff --git a/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow-distribution.properties b/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow-distribution.properties deleted file mode 100644 index 33ee76287a..0000000000 --- a/sdk/src/main/resources/org/apache/beam/runners/dataflow/dataflow-distribution.properties +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed 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. - -name=${dataflow.release_name} -version=${pom.version} -build.date=${timestamp} -legacy.environment.major.version=${dataflow.legacy_environment_major_version} -fnapi.environment.major.version=${dataflow.fnapi_environment_major_version} -container.version=${dataflow.container_version} diff --git a/sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java b/sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java deleted file mode 100644 index 5088a00cfc..0000000000 --- a/sdk/src/test/java/org/apache/beam/runners/dataflow/DataflowRunnerInfoOverrideTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2017 Google Inc. - * - * Licensed 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.beam.runners.dataflow; - -import static org.junit.Assert.assertEquals; - -import java.io.InputStream; -import java.util.Properties; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * Tests for {@link DataflowRunnerInfo} specifically validating that properties in - * this distrbution are correctly read. - */ -@RunWith(JUnit4.class) -public class DataflowRunnerInfoOverrideTest { - private static final String DATAFLOW_DISTRIBUTION_PROPERTIES_PATH = - "/org/apache/beam/runners/dataflow/dataflow-distribution.properties"; - - private static final String FNAPI_ENVIRONMENT_MAJOR_VERSION_KEY = - "fnapi.environment.major.version"; - private static final String LEGACY_ENVIRONMENT_MAJOR_VERSION_KEY = - "legacy.environment.major.version"; - private static final String CONTAINER_VERSION_KEY = "container.version"; - - - @Test - public void testDataflowDistributionOverride() throws Exception { - try (InputStream in = - DataflowRunnerInfo.class.getResourceAsStream(DATAFLOW_DISTRIBUTION_PROPERTIES_PATH)) { - Properties properties = new Properties(); - properties.load(in); - - assertEquals(properties.getProperty(FNAPI_ENVIRONMENT_MAJOR_VERSION_KEY), - DataflowRunnerInfo.getDataflowRunnerInfo().getFnApiEnvironmentMajorVersion()); - assertEquals(properties.getProperty(LEGACY_ENVIRONMENT_MAJOR_VERSION_KEY), - DataflowRunnerInfo.getDataflowRunnerInfo().getLegacyEnvironmentMajorVersion()); - assertEquals(properties.getProperty(CONTAINER_VERSION_KEY), - DataflowRunnerInfo.getDataflowRunnerInfo().getContainerVersion()); - } - } -} diff --git a/sdk/suppressions.xml b/sdk/suppressions.xml deleted file mode 100644 index 4d707ab291..0000000000 --- a/sdk/suppressions.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - From 9f055d9b6e15f512491e6e8310abb31d73fc4cb0 Mon Sep 17 00:00:00 2001 From: Ahmet Altay Date: Wed, 25 Jul 2018 10:42:36 -0700 Subject: [PATCH 751/751] Clean up README --- README.md | 84 +++++++++---------------------------------------------- 1 file changed, 13 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 112df59d01..dfb630ad79 100644 --- a/README.md +++ b/README.md @@ -16,86 +16,28 @@ # Google Cloud Dataflow SDK for Java -[Google Cloud Dataflow](https://cloud.google.com/dataflow/) provides a simple, -powerful programming model for building both batch and streaming parallel data -processing pipelines. +[Google Cloud Dataflow](https://cloud.google.com/dataflow/) is a service for executing [Apache Beam](https://beam.apache.org) pipelines on Google Cloud Platform. -Dataflow SDK for Java is a distribution of a portion of the -[Apache Beam](https://beam.apache.org) project. This repository hosts the -code to build this distribution and any Dataflow-specific code/modules. The -underlying source code is hosted in the -[Apache Beam repository](https://github.com/apache/beam). - -[General usage](https://cloud.google.com/dataflow/getting-started) of Google -Cloud Dataflow does **not** require use of this repository. Instead, you can do -any one of the following: - -1. Depend directly on a specific -[version](https://cloud.google.com/dataflow/downloads) of the SDK in -the [Maven Central Repository](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.google.cloud.dataflow%22) -by adding the following dependency to development -environments like Eclipse or Apache Maven: - - - com.google.cloud.dataflow - google-cloud-dataflow-java-sdk-all - version_number - - -1. Download the example pipelines from the separate -[DataflowJavaSDK-examples](https://github.com/GoogleCloudPlatform/DataflowJavaSDK-examples) -repository. - -1. If you are using [Eclipse](https://eclipse.org/) integrated development -environment (IDE), the -[Cloud Dataflow Plugin for Eclipse](https://cloud.google.com/dataflow/docs/quickstarts/quickstart-java-eclipse) -provides tools to create and execute Dataflow pipelines inside Eclipse. - -## Status [![Build Status](https://api.travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/DataflowJavaSDK) - -Both the SDK and the Dataflow Service are generally available and considered -stable and fully qualified for production use. - -This [`master`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/) branch -contains code to build Dataflow SDK 2.0.0 and newer, as a distribution of Apache -Beam. Pre-Beam SDKs, versions 1.x, are maintained in the -[`master-1.x`](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/tree/master-1.x) -branch. - -## Overview - -The key concepts in this programming model are: - -* `PCollection`: represents a collection of data, which could be bounded or -unbounded in size. -* `PTransform`: represents a computation that transforms input PCollections -into output PCollections. -* `Pipeline`: manages a directed acyclic graph of PTransforms and PCollections -that is ready for execution. -* `PipelineRunner`: specifies where and how the pipeline should execute. - -We provide two runners: - - 1. The `DirectRunner` runs the pipeline on your local machine. - 1. The `DataflowRunner` submits the pipeline to the Cloud Dataflow Service, -where it runs using managed resources in the -[Google Cloud Platform](https://cloud.google.com). +## Getting Started -The SDK is built to be extensible and support additional execution environments -beyond local execution and the Google Cloud Dataflow Service. Apache Beam -contains additional SDKs, runners, and IO connectors. +* [Quickstart Using Java](https://cloud.google.com/dataflow/docs/quickstarts/quickstart-java-maven) on Google Cloud Dataflow +* [Java API Reference](https://beam.apache.org/documentation/sdks/javadoc/) +* [Java Examples](https://github.com/apache/beam/tree/master/examples/java) -## Getting Started +## We moved to Apache Beam! +Apache Beam Java SDK and the code development moved to the [Apache Beam repo](https://github.com/apache/beam/tree/master/sdks/java). -Please try our [Quickstarts](https://cloud.google.com/dataflow/docs/quickstarts). +If you want to contribute to the project (please do!) use this [Apache Beam contributor's guide](http://beam.apache.org/contribution-guide/) ## Contact Us -We welcome all usage-related questions on [Stack Overflow](http://stackoverflow.com/questions/tagged/google-cloud-dataflow) +We welcome all usage-related questions on +[Stack Overflow](https://stackoverflow.com/questions/tagged/google-cloud-dataflow) tagged with `google-cloud-dataflow`. -Please use [issue tracker](https://github.com/GoogleCloudPlatform/DataflowJavaSDK/issues) -on GitHub to report any bugs, comments or questions regarding SDK development. +Please use the +[issue tracker](https://issues.apache.org/jira/browse/BEAM) +on Apache JIRA to report any bugs, comments or questions regarding SDK development. ## More Information